@frontmcp/sdk 1.11.0-rc.1 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.mjs CHANGED
@@ -182,7 +182,7 @@ For other providers (Google, Mistral, Groq, etc.), use one of:
182
182
  - Custom AgentLlmAdapter implementation
183
183
  `,"config","unknown_provider")}}var DeferredProviderAdapter;var init_providers=__esm({"libs/sdk/src/agent/adapters/providers/index.ts"(){"use strict";init_anthropic_adapter();init_base_adapter();init_openai_adapter();init_types2();DeferredProviderAdapter=class{constructor(options){this.options=options}options;adapter=null;getAdapter(){if(this.adapter){return this.adapter}this.adapter=createAdapterForProvider(this.options);return this.adapter}async completion(prompt,tools,options){return this.getAdapter().completion(prompt,tools,options)}async*streamCompletion(prompt,tools,options){const adapter=this.getAdapter();if(adapter.streamCompletion){yield*adapter.streamCompletion(prompt,tools,options)}else{const result=await adapter.completion(prompt,tools,options);if(result.toolCalls){for(const toolCall of result.toolCalls){yield{type:"tool_call",toolCall:{id:toolCall.id,name:toolCall.name,arguments:toolCall.arguments}}}}if(result.content){yield{type:"content",content:result.content}}yield{type:"done",completion:result}}}}}});import{getEnv as getEnv7}from"@frontmcp/utils";function resolveWithConfigValue(withConfig2,configResolver,entityContext){let paths;if(withConfig2.fallbacks===false){paths=[withConfig2.configPath]}else if(Array.isArray(withConfig2.fallbacks)){paths=withConfig2.fallbacks}else if(entityContext){paths=generateFallbacks(withConfig2.configPath,entityContext)}else{paths=[withConfig2.configPath]}for(const path4 of paths){const value=configResolver.tryGet(path4);if(value!==void 0){return withConfig2.transform?withConfig2.transform(value):value}}return void 0}function resolveApiKey(config,configResolver,entityContext){if(typeof config==="string"){return config}if("env"in config){const value=getEnv7(config.env);if(!value){throw new LlmAdapterError(`Environment variable ${config.env} is not set`,"config","missing_env_var")}return value}if("configPath"in config){if(!configResolver){throw new LlmAdapterError(`ConfigResolver required to resolve configPath: ${config.configPath}`,"config","no_resolver")}const value=resolveWithConfigValue(config,configResolver,entityContext);if(value===void 0){let triedPaths;if(config.fallbacks===false){triedPaths=[config.configPath]}else if(Array.isArray(config.fallbacks)){triedPaths=config.fallbacks}else if(entityContext){triedPaths=generateFallbacks(config.configPath,entityContext)}else{triedPaths=[config.configPath]}throw new LlmAdapterError(`Config key "${config.configPath}" not found. Tried: ${triedPaths.join(", ")}`,"config","key_not_found")}return value}throw new LlmAdapterError("Invalid API key configuration","config","invalid_config")}function resolveStringValue(value,configResolver,entityContext){if(typeof value==="string"){return value}if(!configResolver){throw new LlmAdapterError(`ConfigResolver required to resolve configPath: ${value.configPath}`,"config","no_resolver")}const resolved=resolveWithConfigValue(value,configResolver,entityContext);if(resolved===void 0){let triedPaths;if(value.fallbacks===false){triedPaths=[value.configPath]}else if(Array.isArray(value.fallbacks)){triedPaths=value.fallbacks}else if(entityContext){triedPaths=generateFallbacks(value.configPath,entityContext)}else{triedPaths=[value.configPath]}throw new LlmAdapterError(`Config key "${value.configPath}" not found. Tried: ${triedPaths.join(", ")}`,"config","key_not_found")}return resolved}function isBuiltinConfig(config){if(typeof config!=="object"||config===null)return false;const obj=config;return"provider"in obj&&typeof obj["provider"]==="string"&&["openai","anthropic"].includes(obj["provider"])}function isAdapterConfig(config){return typeof config==="object"&&config!==null&&"adapter"in config&&(typeof config.adapter==="object"||typeof config.adapter==="function")}function isTokenConfig(config){return typeof config==="symbol"}function isAdapterInstance2(value){return typeof value==="object"&&value!==null&&"completion"in value&&typeof value["completion"]==="function"}function createAdapter(config,options={}){const{configResolver,providerResolver,entityContext}=options;if(isTokenConfig(config)){if(!providerResolver){throw new LlmAdapterError("ProviderResolver required to resolve LLM adapter token","config","no_resolver")}const adapter=providerResolver.get(config);if(!adapter){throw new LlmAdapterError("LLM adapter token not found in providers","config","token_not_found")}return adapter}if(isAdapterConfig(config)){if(typeof config.adapter==="function"){const result=config.adapter(providerResolver);return result}return config.adapter}if(isBuiltinConfig(config)){return createBuiltinAdapter(config,configResolver,entityContext)}if(isAdapterInstance2(config)){return config}throw new LlmAdapterError("Invalid LLM configuration. Expected built-in config, adapter instance, factory, or DI token.","config","invalid_config")}function createBuiltinAdapter(config,configResolver,entityContext){const obj=config;const provider=obj["provider"];const model=resolveStringValue(config.model,configResolver,entityContext);const apiKey=resolveApiKey(config.apiKey,configResolver,entityContext);const baseUrl=config.baseUrl?resolveStringValue(config.baseUrl,configResolver,entityContext):void 0;const{temperature,maxTokens}=config;return createProviderAdapterSync({provider,model,apiKey,baseUrl,temperature,maxTokens})}var init_adapter_factory=__esm({"libs/sdk/src/agent/adapters/adapter.factory.ts"(){"use strict";init_config_resolver();init_base_adapter();init_providers()}});function supportsStreaming(adapter){return typeof adapter.streamCompletion==="function"}var LLM_ADAPTER;var init_llm_adapter_interface=__esm({"libs/sdk/src/common/interfaces/llm-adapter.interface.ts"(){"use strict";LLM_ADAPTER=Symbol.for("frontmcp:LLM_ADAPTER")}});var init_adapters=__esm({"libs/sdk/src/agent/adapters/index.ts"(){"use strict";init_openai_adapter();init_anthropic_adapter();init_adapter_factory()}});import{internalZ as z71}from"@frontmcp/lazy-zod";function offeredAgentBuiltinTools(scope){const offered=entry=>isOfferedOnSurface(entry.metadata.availableWhen,AGENT_SURFACE);const hasResources=scope.resources.getResources(true).some(offered)||scope.resources.getResourceTemplates().some(offered);const hasPrompts=scope.prompts.getPrompts(true).some(offered);return[...hasResources?[AGENT_BUILTIN_TOOL_NAMES.listResources,AGENT_BUILTIN_TOOL_NAMES.readResource]:[],...hasPrompts?[AGENT_BUILTIN_TOOL_NAMES.listPrompts,AGENT_BUILTIN_TOOL_NAMES.getPrompt]:[]]}async function runAgentBuiltinTool(scope,name51,args,context){const ctx={authInfo:context.authInfo,surface:AGENT_SURFACE,agentPrivateCall:true};const run=(flow,input)=>scope.runFlowForOutput(flow,input).catch(error=>{throw errorBehindFlowControl(error)});switch(name51){case"list_resources":{const[listed,templates]=await Promise.all([run("resources:list-resources",{request:{method:"resources/list",params:{}},ctx}),run("resources:list-resource-templates",{request:{method:"resources/templates/list",params:{}},ctx})]);return describeResourceListing(listed,templates)}case"read_resource":{const{uri}=parseArgs(name51,readResourceArgsSchema,args);const result=await run("resources:read-resource",{request:{method:"resources/read",params:{uri}},ctx});return resourceContentsToText(result)}case"list_prompts":{const listed=await run("prompts:list-prompts",{request:{method:"prompts/list",params:{}},ctx});return describePromptListing(listed)}case"get_prompt":{const parsed=parseArgs(name51,getPromptArgsSchema,args);const promptArgs=parsed.arguments?Object.fromEntries(Object.entries(parsed.arguments).map(([key,value])=>[key,String(value)])):void 0;const result=await run("prompts:get-prompt",{request:{method:"prompts/get",params:{name:parsed.name,...promptArgs&&{arguments:promptArgs}}},ctx});return promptResultToText(result)}}}function parseArgs(tool,schema,args){const parsed=schema.safeParse(args);if(parsed.success)return parsed.data;const issues=parsed.error.issues.map(issue=>`${issue.path.join(".")||"arguments"}: ${issue.message}`);throw new InvalidInputError(`Invalid arguments for ${tool}: ${issues.join("; ")}`,parsed.error.issues)}function describeResourceListing(listed,templates){return{resources:listed.resources.map(resource=>({uri:resource.uri,name:resource.name,...resource.title!==void 0&&{title:resource.title},...resource.description!==void 0&&{description:resource.description},...resource.mimeType!==void 0&&{mimeType:resource.mimeType}})),resourceTemplates:templates.resourceTemplates.map(template=>({uriTemplate:template.uriTemplate,name:template.name,...template.title!==void 0&&{title:template.title},...template.description!==void 0&&{description:template.description},...template.mimeType!==void 0&&{mimeType:template.mimeType}}))}}function describePromptListing(listed){return{prompts:listed.prompts.map(prompt=>({name:prompt.name,...prompt.title!==void 0&&{title:prompt.title},...prompt.description!==void 0&&{description:prompt.description},...prompt.arguments!==void 0&&{arguments:prompt.arguments.map(argument=>({name:argument.name,...argument.description!==void 0&&{description:argument.description},...argument.required!==void 0&&{required:argument.required}}))}}))}}function resourceContentsToText(result){const{contents}=result;if(contents.length===0)return"(the resource has no content)";const[only]=contents;if(contents.length===1&&"text"in only)return only.text;return contents.map(content=>{if(!("text"in content))return describeBinary(content.uri,content.mimeType,content.blob);return`[${content.uri}]${content.mimeType?` (${content.mimeType})`:""}
184
184
  ${content.text}`}).join("\n\n")}function promptResultToText(result){const parts=result.messages.map(message=>`[${message.role}]
185
- ${promptContentToText(message.content)}`);return[...result.description?[result.description]:[],...parts].join("\n\n")}function promptContentToText(content){switch(content.type){case"text":return content.text;case"image":return`[image omitted (${content.mimeType})]`;case"audio":return`[audio omitted (${content.mimeType})]`;case"resource_link":return`[resource link: ${content.uri}${content.name?` (${content.name})`:""}]`;case"resource":{const resource=content.resource;if("text"in resource)return resource.text;return describeBinary(resource.uri,resource.mimeType,resource.blob)}default:return`[${content.type} content omitted]`}}function describeBinary(uri,mimeType,base64){const padding=base64.endsWith("==")?2:base64.endsWith("=")?1:0;const bytes=Math.max(0,Math.floor(base64.length*3/4)-padding);return`[binary content omitted: ${uri} (${mimeType??"application/octet-stream"}, ${bytes} bytes)]`}var AGENT_SURFACE,AGENT_BUILTIN_TOOL_NAMES,EMPTY_PARAMETERS,AGENT_BUILTIN_TOOL_DEFINITIONS,readResourceArgsSchema,getPromptArgsSchema;var init_agent_builtin_tools=__esm({"libs/sdk/src/agent/agent-builtin-tools.ts"(){"use strict";init_availability();init_errors();init_mcp_error_utils();AGENT_SURFACE="agent";AGENT_BUILTIN_TOOL_NAMES={listResources:"list_resources",readResource:"read_resource",listPrompts:"list_prompts",getPrompt:"get_prompt"};EMPTY_PARAMETERS={type:"object",properties:{},additionalProperties:false};AGENT_BUILTIN_TOOL_DEFINITIONS={list_resources:{name:AGENT_BUILTIN_TOOL_NAMES.listResources,description:"List the resources you can read with read_resource: each resource with its URI, and each resource template with the URI template whose placeholders you fill in.",parameters:EMPTY_PARAMETERS},read_resource:{name:AGENT_BUILTIN_TOOL_NAMES.readResource,description:"Read a resource by its URI: one list_resources lists, or a resource template URI with its placeholders filled in. Returns the text of the resource; binary content is described, not included.",parameters:{type:"object",properties:{uri:{type:"string",description:"The URI of the resource to read"}},required:["uri"],additionalProperties:false}},list_prompts:{name:AGENT_BUILTIN_TOOL_NAMES.listPrompts,description:"List the prompts you can get with get_prompt, with the arguments each one takes.",parameters:EMPTY_PARAMETERS},get_prompt:{name:AGENT_BUILTIN_TOOL_NAMES.getPrompt,description:"Get a prompt by its name, with its arguments filled in. Returns its messages as text.",parameters:{type:"object",properties:{name:{type:"string",description:"The name of the prompt, as list_prompts lists it"},arguments:{type:"object",description:"The prompt's arguments, by name",additionalProperties:{type:"string"}}},required:["name"],additionalProperties:false}}};readResourceArgsSchema=z71.object({uri:z71.string().min(1)});getPromptArgsSchema=z71.object({name:z71.string().min(1),arguments:z71.record(z71.string(),z71.union([z71.string(),z71.number(),z71.boolean()])).optional()})}});function isObserverChain(value){return Array.isArray(value)&&value.every(observer=>typeof observer==="function")}function observersOf(context){const installed=context.get(HOOK_OBSERVER_KEY);if(typeof installed==="function")return[installed];return isObserverChain(installed)?installed:NO_OBSERVERS}function addHookObserver(context,observer){const observers=observersOf(context);if(!observers.includes(observer))context.set(HOOK_OBSERVER_KEY,[...observers,observer])}function runObservedHook(observers,hook,run,onObserverError=()=>void 0){const runFrom=async index=>{const observer=observers[index];if(!observer)return run();let inner;const runInner=()=>{if(!inner){inner=runFrom(index+1);inner.catch(()=>void 0)}return inner};try{await observer(hook,runInner)}catch(error){const innerError=inner&&await inner.then(()=>void 0,failure=>({failure}));if(!innerError||innerError.failure!==error)onObserverError(error,observer)}return runInner()};return runFrom(0)}function planStageOf(hook){if(hook.type==="stage")return hook.stage;const stage=hook.stage.slice(hook.type.length);return stage?stage[0].toLowerCase()+stage.slice(1):hook.stage}function outcomeOf(thrown){return thrown instanceof FlowControl?thrown.type:"error"}function recordHookTrace(trace){return async(hook,run)=>{const entry={owner:hook.owner,method:hook.method,stage:planStageOf(hook),type:hook.type,ms:0,outcome:"ok"};trace.push(entry);const started=performance.now();try{await run()}catch(thrown){entry.outcome=outcomeOf(thrown);throw thrown}finally{entry.ms=Math.round((performance.now()-started)*1e3)/1e3}}}function withHookTrace(answer,trace){if(typeof answer!=="object"||answer===null||Array.isArray(answer))return answer;const meta=answer._meta;return{...answer,_meta:{...meta,[HOOK_TRACE_META_KEY]:trace}}}var HOOK_OBSERVER_KEY,HOOK_TRACE_META_KEY,NO_OBSERVERS;var init_hook_observers=__esm({"libs/sdk/src/hooks/hook-observers.ts"(){"use strict";init_common();HOOK_OBSERVER_KEY=Symbol.for("frontmcp:hook-observer");HOOK_TRACE_META_KEY="frontmcp/trace";NO_OBSERVERS=[]}});function declaringClassOf(hook){const target=hook.target;if(typeof target==="function")return target;return target&&typeof target==="object"?target.constructor:void 0}function classNameOf(hook){const cls=declaringClassOf(hook);return typeof cls==="function"?cls.name:""}function hookOwnerName(hook){return hook.pluginName||classNameOf(hook)}function hookIdOf(hook){return`${hookOwnerName(hook)}.${hook.method}`}function namesHook(target,hook){return[hook.pluginName,classNameOf(hook)].some(name51=>!!name51&&(target===name51||target===`${name51}.${hook.method}`))}function isSameHook(a,b){const cls=declaringClassOf(a);return a===b||cls!==void 0&&cls===declaringClassOf(b)&&a.method===b.method}function hasConstraints(hook){return(hook.before?.length??0)>0||(hook.after?.length??0)>0}function cycleError(hooks,waitsFor,placed){const path4=[];let current=hooks.findIndex((_hook,index)=>!placed.has(index));while(!path4.includes(current)){path4.push(current);current=[...waitsFor[current]].find(first3=>!placed.has(first3))??current}const cycle=path4.slice(path4.indexOf(current)).reverse();const start=cycle.indexOf(Math.min(...cycle));const inRunOrder=[...cycle.slice(start),...cycle.slice(0,start)];const{flow,type,stage}=hooks[inRunOrder[0]];return new HookOrderCycleError(flow,type,String(stage),inRunOrder.map(index=>hookIdOf(hooks[index])))}function placesOf(runsBefore){const places=runsBefore.map((_targets,index)=>index);let moved=true;while(moved){moved=false;runsBefore.forEach((targets,index)=>{for(const target of targets){if(places[target]<places[index]){places[index]=places[target];moved=true}}})}return places}function orderByConstraints(items,hookOf,canBeNamed=()=>true){const hooks=items.map(hookOf);if(!hooks.some(hasConstraints))return items;const waitsFor=hooks.map(()=>new Set);const runsBefore=hooks.map(()=>new Set);hooks.forEach((hook,index)=>{hooks.forEach((other,otherIndex)=>{if(isSameHook(hook,other)||!canBeNamed(items[otherIndex]))return;if(hook.before?.some(target=>namesHook(target,other))){waitsFor[otherIndex].add(index);runsBefore[index].add(otherIndex)}if(hook.after?.some(target=>namesHook(target,other)))waitsFor[index].add(otherIndex)})});const places=placesOf(runsBefore);const placed=new Set;const ordered=[];while(ordered.length<items.length){let next=-1;hooks.forEach((_hook,index)=>{if(placed.has(index)||![...waitsFor[index]].every(first3=>placed.has(first3)))return;if(next===-1||places[index]<places[next])next=index});if(next===-1)throw cycleError(hooks,waitsFor,placed);placed.add(next);ordered.push(items[next])}return ordered}function joinWithAnd(parts){return parts.length>1?`${parts.slice(0,-1).join(", ")} and ${parts[parts.length-1]}`:parts.join("")}function unmatchedTargetsWarning(hook,stageHooks){const unmatched=direction=>(hook[direction]??[]).filter(target=>!stageHooks.some(other=>!isSameHook(hook,other)&&namesHook(target,other))).map(target=>`'${target}' in ${direction}`);const listed=[...unmatched("before"),...unmatched("after")];if(listed.length===0)return void 0;const effect=listed.length===1?"it, so it changes":"them, so they change";return`Hook ${hookIdOf(hook)} (${hook.type} '${String(hook.stage)}' of '${hook.flow}') names ${joinWithAnd(listed)}, but no hook on that stage matches ${effect} nothing. A target is a plugin name or the class that declares the hook, optionally followed by .method.`}function byStage(hooks){const groups=new Map;for(const hook of hooks){const key=`${hook.flow} ${hook.type} ${String(hook.stage)}`;const stageHooks=groups.get(key)??[];stageHooks.push(hook);groups.set(key,stageHooks)}return[...groups.values()]}function hookRunsOf(registry){const hooks=registry.getHooks();const runs=[];for(const flow of new Set(hooks.map(hook=>hook.metadata.flow))){const flowHooks=registry.getFlowHooksForOwner(flow);const servedByFlow=new Set(flowHooks);const entryHooks=new Map;for(const hook of hooks){if(hook.metadata.flow!==flow||servedByFlow.has(hook))continue;const cls=declaringClassOf(hook.metadata);entryHooks.set(cls,[...entryHooks.get(cls)??[],hook.metadata])}const shared=flowHooks.map(hook=>hook.metadata);runs.push(shared,...[...entryHooks.values()].map(own=>[...shared,...own]))}return runs}function checkHookOrder(runs,warn){for(const run of runs){for(const stageHooks of byStage(run)){if(!stageHooks.some(hasConstraints))continue;const byPriority=[...stageHooks].sort((a,b)=>(a.priority??0)-(b.priority??0));orderByConstraints(byPriority,hook=>hook)}}const warned2=new Set;for(const stageHooks of byStage(new Set(runs.flat()))){for(const hook of stageHooks){const warning=hasConstraints(hook)?unmatchedTargetsWarning(hook,stageHooks):void 0;if(warning&&!warned2.has(warning)){warned2.add(warning);warn(warning)}}}}var init_hook_order=__esm({"libs/sdk/src/hooks/hook-order.ts"(){"use strict";init_errors()}});import{base64Decode as base64Decode3}from"@frontmcp/utils";function applyHeaders(res,headers){if(!headers)return;for(const[k,v]of Object.entries(headers)){res.setHeader(k,v)}}function applyCookies(res,cookies){if(!cookies||cookies.length===0)return;const existing=typeof res.getHeader==="function"?res.getHeader("Set-Cookie"):void 0;const existingArr=Array.isArray(existing)?existing:existing?[String(existing)]:[];const cookieStrings=cookies.map(serializeHttpCookie);res.setHeader("Set-Cookie",[...existingArr,...cookieStrings])}function contentDisposition(disposition,filename){return`${disposition}${filename?`; filename="${filename}"`:""}`}function utf8ByteLength(s){const enc=new TextEncoder;return enc.encode(s).byteLength}function stringToBytes(str,encoding){if(encoding==="utf8"){return new TextEncoder().encode(str)}try{return base64Decode3(str)}catch(err){throw new Error(`Invalid base64 body: ${err instanceof Error?err.message:String(err)}`,{cause:err})}}async function writeSseChunks(res,iterator){let clientLeft=false;let resume;const stop=()=>{if(clientLeft)return;clientLeft=true;resume?.();void iterator.return?.()};const drained=()=>resume?.();res.on?.("close",stop);res.on?.("drain",drained);if(res.destroyed)stop();try{for(let step=await iterator.next();!step.done&&!clientLeft;step=await iterator.next()){if(res.write(step.value)===false&&!clientLeft)await new Promise(resolve4=>resume=resolve4);resume=void 0}}finally{res.off?.("close",stop);res.off?.("drain",drained)}}async function writeHttpResponse(res,value){const parsed=httpOutputSchema.safeParse(value);if(!parsed.success){res.setHeader("Content-Type","text/plain; charset=utf-8");res.status(500).end("Internal Server Error");return}const out=parsed.data;if(out.kind==="next"||out.kind==="consumed"){return}const{headers,cookies}=out;if(headers){applyHeaders(res,headers)}if(cookies){applyCookies(res,cookies)}switch(out.kind){case"redirect":{res.setHeader("Location",out.location);if("redirect"in res&&typeof res.redirect==="function"){res.redirect(out.location)}else{res.status(out.status).end()}return}case"json":{res.setHeader("Content-Type",out.contentType);res.status(out.status??200);if(typeof res.json!=="function"){res.end(JSON.stringify(out.body))}else{res.json(out.body)}return}case"text":case"html":{res.setHeader("Content-Type",out.contentType);res.setHeader("Content-Length",utf8ByteLength(out.body));res.status(out.status).end(out.body);return}case"binary":case"image":{res.setHeader("Content-Type",out.contentType);res.setHeader("Content-Disposition",contentDisposition(out.disposition,out.filename));const bytes=typeof out.body==="string"?stringToBytes(out.body,out.encoding):out.body;res.setHeader("Content-Length",bytes.byteLength);res.status(out.status).end(bytes);return}case"stream":{res.setHeader("Content-Type",out.contentType);res.setHeader("Content-Disposition",contentDisposition(out.disposition,out.filename));res.status(out.status);if("flushHeaders"in res&&typeof res.flushHeaders==="function")res.flushHeaders();const maybeIter=out.stream[Symbol.asyncIterator];if(typeof maybeIter==="function"&&"write"in res&&typeof res.write==="function"){for await(const chunk of out.stream){res.write(chunk)}res.end();return}if("pipe"in out.stream&&typeof out.stream.pipe==="function"){out.stream.pipe(res);return}res.status(500).end("Streaming not supported by response object");return}case"sse":{res.setHeader("Content-Type",out.contentType);if(!out.headers||!("Cache-Control"in out.headers))res.setHeader("Cache-Control","no-cache");if(!out.headers||!("Connection"in out.headers))res.setHeader("Connection","keep-alive");res.status(out.status);if("flushHeaders"in res&&typeof res.flushHeaders==="function")res.flushHeaders();const maybeIter=out.stream[Symbol.asyncIterator];if(typeof maybeIter==="function"&&"write"in res&&typeof res.write==="function"){await writeSseChunks(res,maybeIter.call(out.stream));res.end();return}if("pipe"in out.stream&&typeof out.stream.pipe==="function"){out.stream.pipe(res);return}res.status(500).end("Streaming not supported by response object");return}case"jsonrpc":{res.setHeader("Content-Type",out.contentType);res.status(out.status);if(typeof res.json==="function"){res.json(out.body)}else{res.end(JSON.stringify(out.body))}return}case"problem":{res.setHeader("Content-Type",out.contentType);res.status(out.status);if(typeof res.json==="function"){res.json(out.body)}else{res.end(JSON.stringify(out.body))}return}case"empty":{res.status(out.status).end();return}case"web-response":{const r=out.response;r.headers.forEach((v,k)=>res.setHeader(k,v));res.status(r.status);if(r.body){for await(const chunk of r.body){res.write(chunk)}}res.end();return}}}var init_server_validation=__esm({"libs/sdk/src/server/server.validation.ts"(){"use strict";init_common()}});function flowErrorToHttpOutput(error){const misconfiguration=findMisconfiguration(error);if(misconfiguration){return{kind:"json",status:500,contentType:"application/json; charset=utf-8",body:misconfigurationBody(misconfiguration)}}if(error instanceof FlowControl){switch(error.type){case"respond":return error.output;case"next":case"handled":return void 0;default:return{kind:"text",status:500,body:"Internal Server Error",contentType:"text/plain; charset=utf-8"}}}if(error instanceof PublicMcpError){const challenge=error.wwwAuthenticate;return{kind:"json",status:error.statusCode,contentType:"application/json; charset=utf-8",body:{error:error.getPublicMessage()},...typeof challenge==="string"&&challenge.length>0?{headers:{"WWW-Authenticate":challenge}}:{}}}return{kind:"text",status:500,body:"Internal Server Error",contentType:"text/plain; charset=utf-8"}}var init_flow_error_output=__esm({"libs/sdk/src/transport/flow-error-output.ts"(){"use strict";init_common();init_errors();init_misconfiguration()}});import"reflect-metadata";function deferredFlow(declaration,load2){class DeferredFlow extends FlowBase{}Reflect.defineMetadata(FrontMcpFlowTokens.type,true,DeferredFlow);Reflect.defineMetadata(FrontMcpFlowTokens.name,declaration.name,DeferredFlow);Reflect.defineMetadata(FrontMcpFlowTokens.middleware,declaration.middleware,DeferredFlow);flowClassLoaders.set(DeferredFlow,load2);return DeferredFlow}function deferredFlowLoader(flowClass){return flowClassLoaders.get(flowClass)}var flowClassLoaders;var init_deferred_flow=__esm({"libs/sdk/src/flows/deferred-flow.ts"(){"use strict";init_common();flowClassLoaders=new WeakMap}});function matchMountedPath(pattern,path4){if(!pattern.includes("/:")){const prefix=pattern.endsWith("/")?pattern:`${pattern}/`;return path4===pattern||path4.startsWith(prefix)?{}:void 0}const mount=pattern.endsWith("/")?pattern.slice(0,-1):pattern;const expected=mount.split("/");const actual=path4.split("/");if(actual.length<expected.length)return void 0;return captureSegments(expected,actual)}function matchRoutePath(pattern,path4){const expected=withoutTrailingSlash(pattern).split("/");const actual=withoutTrailingSlash(path4).split("/");if(actual.length!==expected.length)return void 0;return captureSegments(expected,actual)}function withoutTrailingSlash(path4){return path4.length>1&&path4.endsWith("/")?path4.slice(0,-1):path4}function captureSegments(expected,actual){const params={};for(let i=0;i<expected.length;i++){const segment=expected[i];const value=actual[i];if(segment.length>1&&segment.startsWith(":")){if(value.length===0)return void 0;try{params[segment.slice(1)]=decodeURIComponent(value)}catch{return void 0}}else if(segment!==value){return void 0}}return params}var init_flow_http_path=__esm({"libs/sdk/src/flows/flow.http-path.ts"(){"use strict"}});function sortStageMap(table){for(const key of Object.keys(table)){const list=table[key];list.sort((a,b)=>a._priority-b._priority||a._order-b._order);const ordered=orderByConstraints(list,entry=>entry.hook,entry=>!entry.flowStep);if(ordered!==list)list.splice(0,list.length,...ordered)}}function cloneStageMap(table){const out={};for(const[k,v]of Object.entries(table))out[k]=v.slice();return out}function resolveStageKey(type,stage){return type==="stage"?stage:`${type}${cap(stage)}`}function collectFlowHookMap(FlowClass){const cached=CACHE.get(FlowClass);if(cached){return cached}const existingMetas=Reflect.getMetadata(FrontMcpFlowHookTokens.hooks,FlowClass)??[];const tc39Metas=resolvePendingTC39HooksForClass(FlowClass);const metas=[...existingMetas,...tc39Metas];const sorted=metas.map((m,i)=>({m,i})).sort((a,b)=>(a.m.priority??0)-(b.m.priority??0)||a.i-b.i).map(x=>x.m);const table={};let order=0;for(const m of sorted){const resolved=resolveStageKey(m.type,m.stage);const entry={hook:m,flowStep:true,_priority:m.priority??0,_order:order++,method:async(ctx,next=NO_NEXT)=>{const skipHook=()=>m.type==="around"?next():void 0;const target=m.static?FlowClass:ctx;const impl=typeof m.method==="function"?m.method:target?.[m.method];if(typeof impl!=="function")return skipHook();if(m.filter&&!await m.filter(ctx))return skipHook();if(m.type==="around"){return m.static?impl.call(FlowClass,ctx,next):impl.call(ctx,ctx,next)}else{return m.static?impl.call(FlowClass,ctx):impl.call(ctx,ctx)}}};(table[resolved]??=[]).push(entry)}sortStageMap(table);CACHE.set(FlowClass,table);return table}function mergeHookMetasIntoStageMap(FlowClass,table,metas,orderStart=1e5,runHook=(_hook,run)=>run()){let order=orderStart;const sorted=metas.map((m,i)=>({m,i})).sort((a,b)=>(a.m.priority??0)-(b.m.priority??0)||a.i-b.i).map(x=>x.m);for(const m of sorted){const resolved=resolveStageKey(m.type,m.stage);const entry={hook:m,_priority:m.priority??0,_order:order++,method:async(ctx,next=NO_NEXT)=>{const skipHook=()=>m.type==="around"?next():void 0;const target=m.target;if(!target){console.warn(`[flow] Hook target is missing for method ${m.method}`);return skipHook()}const impl=typeof m.method==="function"?m.method:target?.[m.method].bind(target);if(typeof impl!=="function")return skipHook();if(m.filter&&!await m.filter(ctx))return skipHook();return runHook({stage:resolved,target,metadata:m},async()=>m.type==="around"?impl.call(target,ctx,next):impl.call(target,ctx))}};(table[resolved]??=[]).push(entry)}sortStageMap(table)}function describeStep(hook,flowClassName){const target=hook.target;const owner=typeof target==="function"?target.name:target&&typeof target==="object"?target.constructor.name:"";const placement=[hook.priority??0,...(hook.before??[]).map(name51=>`before ${name51}`),...(hook.after??[]).map(name51=>`after ${name51}`)];return`${hook.type} ${owner||flowClassName}.${hook.method} (${placement.join(", ")})`}function describeHookOrder(stages,base,resolved,flowClassName){const lines=[];for(const stage of stages){const keys=HOOK_TYPES_IN_RUN_ORDER.map(type=>resolveStageKey(type,stage));if(!keys.some(key=>(resolved[key]?.length??0)>(base[key]?.length??0)))continue;const[will,around,body,did,after]=keys.map(key=>(resolved[key]??[]).map(entry=>describeStep(entry.hook,flowClassName)));const wrapped=around.reduceRight((inner,outer)=>`${outer} [ ${inner} ]`,body.join(" \u2192 "));lines.push(` ${stage}: ${[...will,wrapped,...did,...after].filter(Boolean).join(" \u2192 ")}`)}return lines}var cap,CACHE,NO_NEXT,HOOK_TYPES_IN_RUN_ORDER;var init_flow_stages=__esm({"libs/sdk/src/flows/flow.stages.ts"(){"use strict";init_common();init_hook_decorator();init_hook_order();cap=s=>s?s[0].toUpperCase()+s.slice(1):s;CACHE=new WeakMap;NO_NEXT=async()=>void 0;HOOK_TYPES_IN_RUN_ORDER=["will","around","stage","did","finally"]}});import{depsOfClass as depsOfClass6,getMetadata as getMetadata13,isClass as isClass10}from"@frontmcp/di";function collectFlowMetadata(cls){return Object.entries(FrontMcpFlowTokens).reduce((metadata,[key,token])=>{return Object.assign(metadata,{[key]:getMetadata13(token,cls)})},{})}function normalizeFlow(item){if(isClass10(item)){const metadata=collectFlowMetadata(item);return{kind:"CLASS_TOKEN",provide:item,metadata}}const name51=item?.name??String(item);throw new InvalidEntityError("flow",name51,"a class or a flow object")}var init_flow_utils2=__esm({"libs/sdk/src/flows/flow.utils.ts"(){"use strict";init_common();init_errors()}});import"reflect-metadata";import{tokenName as tokenName10}from"@frontmcp/di";import{isDebug as isDebug2,isDevelopment as isDevelopment4}from"@frontmcp/utils";function stageKeysOf(stage){let keys=stageKeysByName.get(stage);if(!keys){keys={will:`will${CAP(stage)}`,did:`did${CAP(stage)}`,around:`around${CAP(stage)}`,finally:`finally${CAP(stage)}`};stageKeysByName.set(stage,keys)}return keys}function parseTypedKey(k){const lc=k.toLowerCase();if(lc.startsWith("will")&&k.length>4)return{base:k.slice(4,5).toLowerCase()+k.slice(5),type:"will"};if(lc.startsWith("did")&&k.length>3)return{base:k.slice(3,4).toLowerCase()+k.slice(4),type:"did"};if(lc.startsWith("around")&&k.length>6)return{base:k.slice(6,7).toLowerCase()+k.slice(7),type:"around"};if(lc.startsWith("finally")&&k.length>7)return{base:k.slice(7,8).toLowerCase()+k.slice(8),type:"finally"};return{base:k}}function describeValue2(value){try{return String(value)}catch{return Object.prototype.toString.call(value)}}function failureOf(control){const originalError=control.originalError;if(originalError!==void 0)return originalError;return control.type==="abort"?new InternalMcpError(`Flow aborted: ${String(control.output)}`):control}function stageBasesOf(group){let bases=stageBasesByGroup.get(group);if(!bases){const seen=new Set;bases=[];for(const rawKey of group){const{base,type}=parseTypedKey(rawKey);const stage=type==="finally"&&!group.includes(base)?rawKey:base;if(type&&stage===base||seen.has(stage))continue;seen.add(stage);bases.push(stage)}stageBasesByGroup.set(group,bases)}return bases}function listJoinedAfterStep(list,present,step){const stepIndex=list.indexOf(step);if(stepIndex===-1)return list;const joinedBefore=list.slice(0,stepIndex).filter(entry=>!present.includes(entry));const rest=list.filter(entry=>!joinedBefore.includes(entry));rest.splice(rest.indexOf(step)+1,0,...joinedBefore);return rest}function nextStageOrder(stages){return Math.max(0,...Object.values(stages).flatMap(list=>list.map(e=>e._order??0)))+1}var FAILED_OUTCOMES,CAP,stageKeysByName,stageBasesByGroup,FLOW_PHASES,FlowInstance;var init_flow_instance=__esm({"libs/sdk/src/flows/flow.instance.ts"(){"use strict";init_common();init_context();init_running_flow();init_errors();init_misconfiguration();init_entry_class_hooks();init_hook_observers();init_hook_order();init_hooks_utils();init_server_validation();init_flow_error_output();init_deferred_flow();init_flow_http_path();init_flow_stages();init_flow_utils2();FAILED_OUTCOMES=new Set(["fail","abort","unknown_error"]);CAP=s=>s?s[0].toUpperCase()+s.slice(1):s;stageKeysByName=new Map;stageBasesByGroup=new WeakMap;FLOW_PHASES=["pre","execute","post","error","finalize"];FlowInstance=class extends FlowEntry{deps;globalProviders;plan;FlowClass;flowClassLoad;stages;hooks;logger;baseStageOrderEnd;loggedHookOrders=isDevelopment4()||isDebug2()?new Map:void 0;tracesHooks;failedObservers=new WeakSet;constructor(scope,record,deps,globalProviders){super(scope,record);this.deps=[...deps];this.globalProviders=globalProviders;this.FlowClass=this.record.provide;this.ready=this.initialize();this.plan=this.record.metadata.plan;this.hooks=scope.hooks;this.logger=scope.logger.child("FlowInstance");this.tracesHooks=this.FlowClass.tracesHooksInAnswer===true&&(scope.metadata.devtools?.hookTrace??isDevelopment4())}async initialize(){const server=this.globalProviders.getActiveServer();this.stages=collectFlowHookMap(this.FlowClass);const{middleware}=this.metadata;if(middleware){const path4=typeof middleware.path==="string"?middleware.path:"";server.registerMiddleware(path4,async(request2,response,next)=>{const canActivate=await this.canActivate(request2);if(!canActivate)return next();const contextStorage=this.getContextStorage();try{const result=await this.runWithContext(contextStorage,request2,{request:request2,response,next},new Map);if(result)return writeHttpResponse(response,result)}catch(e){if(e instanceof FlowControl){switch(e.type){case"abort":return writeHttpResponse(response,{kind:"text",status:500,body:"Aborted"});case"fail":return writeHttpResponse(response,{kind:"text",status:500,body:"Internal Server Error"});case"handled":return;case"next":return next();case"respond":return writeHttpResponse(response,e.output)}}const misconfiguration=findMisconfiguration(e);if(misconfiguration){this.logger.error("Server misconfigured",{flow:this.name,code:misconfiguration.code});return writeHttpResponse(response,{kind:"json",status:500,body:misconfigurationBody(misconfiguration)})}if(e instanceof PublicMcpError){const challenge=e.wwwAuthenticate;this.logger.warn("Public error in flow",{flow:this.name,name:e.name,status:e.statusCode,code:e.code});return writeHttpResponse(response,{kind:"json",status:e.statusCode,body:{error:e.getPublicMessage()},...typeof challenge==="string"&&challenge.length>0?{headers:{"WWW-Authenticate":challenge}}:{}})}this.logger.error("Unhandled error in flow",{flow:this.name,name:e instanceof Error?e.name:"UnknownError",message:e instanceof Error?e.message:String(e)});return writeHttpResponse(response,{kind:"text",status:500,body:"Internal Server Error"})}return next()})}return Promise.resolve()}loadFlowClass(){const load2=deferredFlowLoader(this.FlowClass);if(!load2)return Promise.resolve();this.flowClassLoad??=load2().then(flowClass=>{Object.assign(this.metadata,collectFlowMetadata(flowClass));this.plan=this.metadata.plan;this.stages=collectFlowHookMap(flowClass);this.FlowClass=flowClass});return this.flowClassLoad}async canActivate(request2){if(this.method&&request2.method!==this.method)return false;try{await this.loadFlowClass()}catch{return true}const canActivate=[...this.metadata.middleware?.canActivate??[]];if(this.FlowClass["canActivate"]){canActivate.push(this.FlowClass["canActivate"])}if(canActivate.length===0)return true;const results=await Promise.all(canActivate.map(m=>m(request2,this.scope)));return results.every(r=>r)}async matchHttp(request2){const mw=this.metadata.middleware;if(!mw)return false;const path4=typeof mw.path==="string"?mw.path:"";const hasStaticCanActivate=typeof this.FlowClass.canActivate==="function";const hasMwCanActivate=(mw.canActivate?.length??0)>0;if(!path4&&!hasStaticCanActivate&&!hasMwCanActivate)return false;if(this.method&&request2.method!==this.method)return false;const captured=path4?matchMountedPath(path4,request2.path):{};if(!captured)return false;const previous=request2.params;if(Object.keys(captured).length>0)request2.params={...captured,...previous};const activated=await this.canActivate(request2);if(!activated){if(previous===void 0)delete request2.params;else request2.params=previous}return activated}getContextStorage(){try{return this.globalProviders.get(FrontMcpContextStorage)}catch{this.logger.verbose("getContextStorage: FrontMcpContextStorage not available");return void 0}}async runWithContext(storage,request2,input,deps){if(!storage){return this.run(input,deps)}const scope=this.globalProviders.getActiveScope();return storage.runForHttpRequest(request2,scope.id,async()=>{return this.run(input,deps)})}async run(input,deps){this.logger.verbose(`run: starting flow '${this.name}'`);await this.loadFlowClass();const scope=this.globalProviders.getActiveScope();const contextStorage=this.getContextStorage();const currentContext=contextStorage?.getStore();const sessionKey=currentContext?.sessionId;if(!currentContext||!sessionKey){throw new RequestContextNotAvailableError("FrontMcpContext unavailable - session ID required for provider resolution. Ensure flow is wrapped with runWithContext.")}const runStages=()=>runAsFlow({context:currentContext,flow:this,scope},()=>this.runStages(input,deps,scope,currentContext,sessionKey));const responseHeaders=this.metadata.middleware?.responseHeaders;return responseHeaders?this.respondWithHeaders(runStages,responseHeaders):runStages()}async respondWithHeaders(runStages,headers){let output;try{output=await runStages()}catch(error){output=flowErrorToHttpOutput(error);if(!output)throw error;this.logger.error("Flow failed",{flow:this.name,name:error instanceof Error?error.name:"UnknownError",message:error instanceof Error?error.message:String(error)})}return output&&withHttpHeaders(output,headers)}async runStages(input,deps,scope,currentContext,sessionKey){const{FlowClass,plan:plan50,name:name51}=this;const contextProviders=new Map([[FRONTMCP_CONTEXT,currentContext]]);for(const[token,value]of currentContext.getContextTokens()){contextProviders.set(token,value)}const views=await this.globalProviders.buildViews(sessionKey,contextProviders);const mergedDeps=new Map(deps);for(const[token,instance]of views.context){mergedDeps.set(token,instance)}const baseStages=this.stages;let stages=baseStages;let ownsStages=false;let orderBase=this.baseStageOrderEnd??=nextStageOrder(baseStages);const hookOwnerId=await FlowClass.resolveHookOwnerId?.(input,scope);const entryClass=await FlowClass.resolveHookEntryClass?.(input,scope);const entryStaticHooks=entryClass?staticHooksFor(this.hooks.getClsHooks(entryClass),name51):[];const initialInjectedHooks=await bindContextHookTargets(this.hooks.getFlowHooksForOwner(name51,hookOwnerId)??[],{sessionKey,contextProviders:mergedDeps,contextSource:this.globalProviders});let contextReady=false;const trace=this.tracesHooks?[]:void 0;const traceObserver=trace&&recordHookTrace(trace);const runHook=({stage,target,metadata},run)=>{const installed=observersOf(currentContext);const observers=traceObserver?[...installed,traceObserver]:installed;if(observers.length===0)return run();const hook={flowName:name51,stage,type:metadata.type,owner:hookOwnerName(metadata),method:metadata.method,target,flowContext:context};return runObservedHook(observers,hook,run,(error,observer)=>this.logObserverFailure(observer,error))};const answer=output=>trace?withHookTrace(output,trace):output;const materializeAndMerge=async(newHooks,opts)=>{if(!newHooks?.length||!contextReady)return;const metas=[];for(const h2 of newHooks){try{metas.push(h2.metadata)}catch(e){this.logger.warn("Ignoring injected hook that failed to materialize",{flow:this.name,error:e instanceof Error?e.message:"Unknown error"})}}if(metas.length){const start=opts?.orderStart??orderBase;if(!ownsStages){stages=cloneStageMap(baseStages);ownsStages=true}mergeHookMetasIntoStageMap(FlowClass,stages,metas,start,runHook);if(opts?.orderStart===void 0)orderBase+=metas.length}};const appendContextHooks=async hooks=>{await materializeAndMerge(hooks)};const context=new FlowClass(this.metadata,input,scope,appendContextHooks,mergedDeps);contextReady=true;await materializeAndMerge(initialInjectedHooks,{orderStart:-1e6});if(ownsStages)orderBase=nextStageOrder(stages);await materializeAndMerge(entryStaticHooks);if(this.loggedHookOrders)this.logHookOrderOnce(this.loggedHookOrders,stages,hookOwnerId,entryClass);let responded;const toStageResult=e=>{if(e instanceof FlowControl){if(e.type==="respond"){responded=e.output;const status=e.output?.status;context.state.set("statusCode",typeof status==="number"?status:void 0)}return{outcome:e.type,control:e}}return{outcome:"unknown_error",control:e}};const hasEntries=key=>(stages[key]?.length??0)>0;const ignoreFinallyThrow=(key,thrown)=>{const description=thrown instanceof FlowControl?`FlowControl '${thrown.type}'`:describeValue2(thrown);this.logger.warn(`Ignored a throw from a Finally hook of '${key}': it cannot change the stage's outcome`,{flow:name51,thrown:description})};const restoreState=before=>{const state=context.state;for(const key of Object.keys(context.state.snapshot())){if(!(key in before))delete state[key]}context.state.set(before)};const runList=async(key,opts)=>{const seen=new Set;while(true){const list=stages[key]??[];let item;for(const entry of list){if(!seen.has(entry)){item=entry;break}}if(!item)break;seen.add(item);const stateBefore=opts?.ignoreThrows?context.state.snapshot():void 0;try{await item.method(context)}catch(e){if(opts?.ignoreThrows){if(stateBefore)restoreState(stateBefore);ignoreFinallyThrow(key,e);continue}if(e instanceof FlowControl&&e.type==="respond"&&opts?.ignoreRespond)continue;return toStageResult(e)}}return{outcome:"ok"}};const runAroundChain=async(stageName,index=0)=>{const around=(stages[stageKeysOf(stageName).around]??[])[index];if(!around)return runList(stageName,{ignoreRespond:false});let innerResult={outcome:"ok"};const next=async()=>{innerResult=await runAroundChain(stageName,index+1);if(innerResult.outcome!=="ok"&&innerResult.outcome!=="respond")throw innerResult.control};try{await around.method(context,next)}catch(e){return toStageResult(e)}return FAILED_OUTCOMES.has(innerResult.outcome)?{outcome:"ok"}:innerResult};const recordFailure=control=>{if(context.state.get("flowError"))return;const failure=control instanceof FlowControl?failureOf(control):control;const flowError=failure instanceof Error?failure:new InternalMcpError(`Flow failed with a non-Error value: ${describeValue2(failure)}`);context.state.set("flowError",flowError)};const runStageSteps=async(stageName,stopOnRespond)=>{const keys=stageKeysOf(stageName);if(hasEntries(keys.will)){const res=await runList(keys.will);if(res.outcome==="respond"&&stopOnRespond)return res;if(res.outcome!=="ok"&&res.outcome!=="respond")return res}const bodyOutcome=hasEntries(keys.around)?await runAroundChain(stageName):await runList(stageName,{ignoreRespond:false});if(bodyOutcome.outcome!=="ok"&&bodyOutcome.outcome!=="respond"){return bodyOutcome}if(hasEntries(keys.did)){const res=await runList(keys.did,{ignoreRespond:true});if(res.outcome!=="ok"&&res.outcome!=="respond")return res}if(bodyOutcome.outcome==="respond")return bodyOutcome;return{outcome:"ok"}};const runOneStage=async(stageName,stopOnRespond)=>{const result=await runStageSteps(stageName,stopOnRespond);if(FAILED_OUTCOMES.has(result.outcome))recordFailure(result.control);const finallyKey=stageKeysOf(stageName).finally;if(hasEntries(finallyKey))await runList(finallyKey,{ignoreThrows:true});return result};const runStageGroup=async(group,stopOnRespond,opts)=>{if(!group||group.length===0)return{outcome:"ok"};for(const base of stageBasesOf(group)){const res=await runOneStage(base,stopOnRespond);if(res.outcome==="respond"){if(stopOnRespond)return res}else if(res.outcome!=="ok"){return res}}return{outcome:"ok"}};const runErrorStage=async()=>{await runStageGroup(plan50.error,false,{ignoreRespond:true})};const runFinalizeStage=async options=>{const res=await runStageGroup(plan50.finalize,false);if(res.outcome==="unknown_error"||res.outcome==="fail"){const finalizeError=res.control??new InternalMcpError("Finalize stage failed");if(options?.suppressErrors){this.scope.logger.error("[FrontMCP] Finalize stage error (suppressed to preserve original error):",finalizeError);return res}throw finalizeError}return res};{const pre=await runStageGroup(plan50.pre,true);this.logger.verbose(`run: PRE completed, outcome=${pre.outcome}`);if(pre.outcome==="respond"){const post=await runStageGroup(plan50.post,false);if(post.outcome==="unknown_error"||post.outcome==="fail"){try{await runErrorStage()}finally{await runFinalizeStage({suppressErrors:true})}throw post.control??new InternalMcpError("Missing control for fail/error outcome")}if(post.outcome==="abort"||post.outcome==="next"||post.outcome==="handled"){await runFinalizeStage({suppressErrors:true});if(!(post.control instanceof FlowControl)){throw new InternalMcpError("Expected FlowControl but received different error type")}throw post.control}await runFinalizeStage();return answer(responded)}if(pre.outcome==="unknown_error"||pre.outcome==="fail"){try{await runErrorStage()}finally{await runFinalizeStage({suppressErrors:true})}throw pre.control??new InternalMcpError("Missing control for fail/error outcome")}if(pre.outcome==="abort"||pre.outcome==="next"||pre.outcome==="handled"){await runFinalizeStage({suppressErrors:true});if(!(pre.control instanceof FlowControl)){throw new InternalMcpError("Expected FlowControl but received different error type")}throw pre.control}}if(!responded){const exec=await runStageGroup(plan50.execute,true);this.logger.verbose(`run: EXECUTE completed, outcome=${exec.outcome}`);if(exec.outcome==="respond"){}else if(exec.outcome==="unknown_error"||exec.outcome==="fail"){try{await runErrorStage()}finally{await runFinalizeStage({suppressErrors:true})}throw exec.control??new InternalMcpError("Missing control for fail/error outcome")}else if(exec.outcome==="abort"||exec.outcome==="next"||exec.outcome==="handled"){await runFinalizeStage({suppressErrors:true});if(!(exec.control instanceof FlowControl)){throw new InternalMcpError("Expected FlowControl but received different error type")}throw exec.control}}{const post=await runStageGroup(plan50.post,false);this.logger.verbose(`run: POST completed, outcome=${post.outcome}`);if(post.outcome==="unknown_error"||post.outcome==="fail"){try{await runErrorStage()}finally{await runFinalizeStage({suppressErrors:true})}throw post.control??new InternalMcpError("Missing control for fail/error outcome")}if(post.outcome==="abort"||post.outcome==="next"||post.outcome==="handled"){await runFinalizeStage({suppressErrors:true});if(!(post.control instanceof FlowControl)){throw new InternalMcpError("Expected FlowControl but received different error type")}throw post.control}}await runFinalizeStage();return answer(responded)}logObserverFailure(observer,error){if(this.failedObservers.has(observer))return;this.failedObservers.add(observer);this.logger.warn("Ignored a throw from a hook observer: the hook ran as it would with no observer",{flow:this.name,error:error instanceof Error?error.message:describeValue2(error)})}logHookOrderOnce(logged,stages,ownerId,entryClass){const entryHooks=entryClass?this.hooks.getClsHooks(entryClass).filter(hook=>hook.metadata.flow===this.name):[];const entryKey=entryHooks.length>0?entryClass:void 0;const loggedEntries=logged.get(ownerId)??new Set;if(loggedEntries.has(entryKey))return;logged.set(ownerId,loggedEntries.add(entryKey));const resolved=cloneStageMap(stages);const instanceHooks=entryHooks.filter(hook=>!hook.metadata.static).map(hook=>hook.metadata);mergeHookMetasIntoStageMap(this.FlowClass,resolved,instanceHooks,nextStageOrder(stages));const contextStage=entryContextStageOf(this.name);const contextStep=contextStage?this.stages[contextStage]?.[0]:void 0;if(contextStage&&contextStep&&resolved[contextStage]){resolved[contextStage]=listJoinedAfterStep(resolved[contextStage],stages[contextStage]??[],contextStep)}const stageNames=FLOW_PHASES.flatMap(phase=>{const group=this.plan[phase];return group?stageBasesOf(group):[]});const lines=describeHookOrder(stageNames,this.stages,resolved,this.FlowClass.name);if(lines.length===0)return;const owner=ownerId===void 0?"":` for '${ownerId}'`;const entry=entryKey===void 0?"":` and ${tokenName10(entryKey)}`;const header2=`Hook order of '${this.name}'${owner}${entry}, lowest priority first (an around hook wraps what its brackets hold):`;this.logger.info([header2,...lines].join("\n"))}}}});import{tokenName as tokenName11}from"@frontmcp/di";import{randomUUID as randomUUID15}from"@frontmcp/utils";var FlowRegistry;var init_flow_registry=__esm({"libs/sdk/src/flows/flow.registry.ts"(){"use strict";init_common();init_context();init_metadata_utils();init_errors();init_regsitry();init_flow_instance();init_flow_utils2();FlowRegistry=class extends RegistryAbstract{constructor(providers,list){super("FlowRegistry",providers,list)}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;for(const raw of list){const rec=normalizeFlow(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);const deps=rec.metadata.dependsOn??[];for(const d of deps){if(d==ScopeEntry){this.graph.get(token).add(ScopeEntry)}else{if(!this.providers.get(d)){throw new RegistryDependencyNotRegisteredError("Flow",tokenName11(token),tokenName11(d))}this.graph.get(token).add(d)}}}}async initialize(){const readyArr=[];for(const token of this.tokens){const instance=this.initializeOne(token);readyArr.push(instance.ready)}await Promise.all(readyArr)}initializeOne(token){const rec=this.defs.get(token);const deps=this.graph.get(token);const instance=new FlowInstance(this.providers.getActiveScope(),rec,deps,this.providers);this.instances.set(rec.metadata.name,instance);return instance}async registryFlows(rawFlows){const readyArr=[];for(const raw of rawFlows){const rec=normalizeFlow(raw);const provide=rec.provide;this.tokens.add(provide);this.defs.set(provide,rec);this.graph.set(provide,new Set);readyArr.push(this.initializeOne(provide).ready)}await Promise.all(readyArr)}runFlow(name51,input,deps){const flow=this.instances.get(name51);if(!flow){throw new FlowNotRegisteredError(name51)}const contextStorage=this.getContextStorage();if(!contextStorage){return flow.run(input,deps??new Map)}const mcpCtx=input?.ctx;const inProcessMetadata=mcpCtx?.metadata;const inProcessPlatformEnv=mcpCtx?.platformEnv;const existingContext=contextStorage.getStore();if(existingContext&&!inProcessMetadata&&inProcessPlatformEnv===void 0){return flow.run(input,deps??new Map)}const scope=this.providers.getActiveScope();const httpRequest=input?.request;if(httpRequest?.headers&&!input.ctx){return Promise.resolve(contextStorage.runForHttpRequest(httpRequest,scope.id,async()=>{return flow.run(input,deps??new Map)}))}const authInfo=mcpCtx?.authInfo;const rawSessionId=authInfo?.sessionId;const sessionId=typeof rawSessionId==="string"&&rawSessionId.trim().length>0?rawSessionId.trim():`anon:${randomUUID15()}`;return Promise.resolve(contextStorage.run({sessionId,scopeId:scope.id,authInfo,...inProcessMetadata?inProcessRequestContext(inProcessMetadata,{forwardsHeader:contextStorage.forwardsHeader}):{},...inProcessPlatformEnv!==void 0?{platformEnv:inProcessPlatformEnv}:{}},async()=>{return flow.run(input,deps??new Map)}))}async findHttpFlowName(request2,exclude=new Set){for(const instance of this.instances.values()){const name51=instance.name;if(exclude.has(name51))continue;if(await instance.matchHttp(request2))return name51}return void 0}getContextStorage(){try{return this.providers.get(FrontMcpContextStorage)}catch{return void 0}}}}});var HookInstance;var init_hook_instance=__esm({"libs/sdk/src/hooks/hook.instance.ts"(){"use strict";init_common();init_errors();HookInstance=class extends HookEntry{logger;constructor(scope,providers,record,token){super(scope,providers,record,token,record.metadata);const{flow,method,stage}=this.metadata;this.logger=scope.logger.child(`${flow}:hook:${stage}(${method})`)}initialize(){return Promise.resolve(void 0)}async run(input,ctx){const{target,method}=this.metadata;if(!target){throw new HookTargetNotDefinedError(method)}this.logger.verbose("start");await target[method](input,ctx);this.logger.verbose("done")}}}});function appliesToOwner(hook,ownerId){const hookOwner=hook.metadata.owner;if(!hookOwner)return true;switch(hookOwner.kind){case"scope":case"plugin":return true;case"app":case"agent":return hookOwner.id===ownerId||hook.metadata.appliesTo==="all-apps";default:throw new UnsupportedHookOwnerKindError(hookOwner.kind)}}function hookClassOf(hook){const{target}=hook.metadata;if(target===null||target===void 0)return void 0;if(hook.metadata.static||typeof target!=="object")return target;return target.constructor}function isSameHook2(a,b){const cls=hookClassOf(a);return cls!==void 0&&cls===hookClassOf(b)&&a.metadata.flow===b.metadata.flow&&a.metadata.method===b.metadata.method}var HookRegistry;var init_hook_registry=__esm({"libs/sdk/src/hooks/hook.registry.ts"(){"use strict";init_errors();init_regsitry();init_hook_instance();HookRegistry=class extends RegistryAbstract{scope;recordsByCls=new Map;entriesByCls=new Map;hooksByFlow=new Map;hooksByFlowStage=new Map;inherited;constructor(providers,list){super("HookRegistry",providers,list);this.scope=this.providers.getActiveScope()}buildMap(){const tokens=new Set;const defs=new Map;const graph=new Map;return{tokens,defs,graph}}buildGraph(){}async initialize(){}getPriority(entry){return entry.metadata?.priority??0}insertSorted(arr,item){const p=this.getPriority(item);let lo=0;let hi=arr.length;while(lo<hi){const mid=lo+hi>>>1;const mp=this.getPriority(arr[mid]);if(mp>p){hi=mid}else{lo=mid+1}}arr.splice(lo,0,item)}upsert(map,key,init){let v=map.get(key);if(!v){v=init();map.set(key,v)}return v}indexByClass(cls,entry){const list=this.upsert(this.entriesByCls,cls,()=>[]);this.insertSorted(list,entry)}indexByFlow(flow,entry){const list=this.upsert(this.hooksByFlow,flow,()=>[]);this.insertSorted(list,entry)}indexByFlowStage(flow,stage,entry){const stages=this.upsert(this.hooksByFlowStage,flow,()=>new Map);const list=this.upsert(stages,String(stage),()=>[]);this.insertSorted(list,entry)}initializeOne(embedded,token){const rec=this.defs.get(token);const providers=this.providers;const instance=new HookInstance(this.scope,providers,rec,token);this.instances.set(token,instance);const cls=rec.metadata.target;if(cls){const recs=this.recordsByCls.get(cls)??[];recs.push(rec);this.recordsByCls.set(cls,recs)}const entry=this.instances.get(token);const{flow,stage,target}=rec.metadata;if(embedded&&target){this.indexByClass(rec.metadata.static?target:target.constructor,entry)}else if(!embedded){this.indexByFlowStage(flow,String(stage),entry);this.indexByFlow(flow,entry)}return instance.ready}registerHooks(embedded,...records){const readyArr=[];for(const record of records){this.defs.set(record.provide,record);this.tokens.add(record.provide);this.graph.set(record.provide,new Set);readyArr.push(this.initializeOne(embedded,record.provide))}return Promise.all(readyArr)}removeHooks(hooks){const removed=new Set(hooks);if(removed.size===0)return;const removedTokens=new Set;for(const[token,entry]of this.instances){if(!removed.has(entry))continue;removedTokens.add(token);this.instances.delete(token);this.defs.delete(token);this.tokens.delete(token);this.graph.delete(token)}const prune=index=>{for(const[key,entries]of index){index.set(key,entries.filter(entry=>!removed.has(entry)))}};prune(this.entriesByCls);prune(this.hooksByFlow);for(const stages of this.hooksByFlowStage.values())prune(stages);for(const[cls,records]of this.recordsByCls){this.recordsByCls.set(cls,records.filter(record=>!removedTokens.has(record.provide)))}}inheritFrom(parent,ownerId){this.inherited={registry:parent,ownerId}}getFlowHooksForOwner(flow,ownerId){const own=this.getOwnFlowHooksForOwner(flow,ownerId);if(!this.inherited)return own;const inherited=this.inherited.registry.getFlowHooksForOwner(flow,this.inherited.ownerId).filter(hook=>!own.some(ownHook=>isSameHook2(ownHook,hook)));if(inherited.length===0)return own;const merged=[...own];for(const hook of inherited)this.insertSorted(merged,hook);return merged}getOwnFlowHooksForOwner(flow,ownerId){const allHooks=this.getFlowHooks(flow);if(!ownerId){return allHooks}const ownHooks=allHooks.filter(hook=>appliesToOwner(hook,ownerId));if(!allHooks.some(hook=>hook.metadata.appliesTo==="uncovered-apps"))return ownHooks;const own=new Set(ownHooks);return allHooks.filter(hook=>own.has(hook)||hook.metadata.appliesTo==="uncovered-apps"&&!ownHooks.some(ownHook=>isSameHook2(ownHook,hook)))}getClsHooks(token){return this.entriesByCls.get(token)??[]}getHooks(){return[...this.instances.values()]}getFlowHooks(flow){return this.hooksByFlow.get(flow)??[]}getFlowStageHooks(flow,stage){const byStage2=this.hooksByFlowStage.get(flow);return byStage2?.get(String(stage))??[]}}}});import{brandClass as brandClass3,isBrandedInstance as isBrandedInstance3}from"@frontmcp/utils";function isDynamicPluginClass(value){return typeof value==="function"&&value.prototype instanceof DynamicPlugin}function initOptionsOf(instance){return initOptionsByInstance.has(instance)?{options:initOptionsByInstance.get(instance)}:void 0}var initOptionsByInstance,DynamicPlugin;var init_dynamic_plugin=__esm({"libs/sdk/src/common/dynamic/dynamic.plugin.ts"(){"use strict";init_transport_errors();init_dynamic_utils();initOptionsByInstance=new WeakMap;DynamicPlugin=class{static[Symbol.hasInstance](value){return isBrandedInstance3(this,value)}get(token){throw new MethodNotImplementedError("DynamicPlugin","get")}static init(options={}){const providersOption=options.providers;const extraProviders=Array.isArray(providersOption)?providersOption:[];const typedOptions=options;if("useFactory"in options){return{...pluginMetadataFromOptions(typedOptions,[]),provide:this,inject:options.inject,useFactory:options.useFactory,providers:dedupePluginProviders(extraProviders)}}const dyn=collectDynamicProviders(this,typedOptions);const mergedProviders=dedupePluginProviders([...dyn??[],...extraProviders]);const dynamicTools=collectDynamicTools(this,typedOptions);const instance=new this(options);initOptionsByInstance.set(instance,options);return{...pluginMetadataFromOptions(typedOptions,dynamicTools),provide:this,useValue:instance,providers:mergedProviders}}};brandClass3(DynamicPlugin,"@frontmcp/sdk:DynamicPlugin")}});function installContextExtensions(pluginName,extensions){for(const ext of extensions){const{property,token,errorMessage:errorMessage2}=ext;if(installedExtensions.has(property)){continue}if(Object.prototype.hasOwnProperty.call(ExecutionContextBase.prototype,property)){console.warn(`[${pluginName}] Context property '${property}' already exists on ExecutionContextBase. Skipping.`);continue}const defaultErrorMessage=errorMessage2??`${pluginName} is not installed or '${property}' is not configured.`;Object.defineProperty(ExecutionContextBase.prototype,property,{get:function(){try{return this.get(token)}catch(err){throw new ContextExtensionNotAvailableError(defaultErrorMessage,err instanceof Error?err:void 0)}},configurable:true,enumerable:false});installedExtensions.add(property)}}var installedExtensions;var init_context_extension=__esm({"libs/sdk/src/context/context-extension.ts"(){"use strict";init_execution_context_interface();init_errors();installedExtensions=new Set}});import{dirname as dirname4,stat}from"@frontmcp/utils";async function findReplaceableDirectory(start){for(let directory=start;;directory=dirname4(directory)){const{mode,uid}=await stat(directory);if(uid!==ROOT_UID&&uid!==process.getuid?.())return{directory,mode,ownerUid:uid};if(mode&GROUP_OR_OTHER_WRITE&&!(mode&STICKY_BIT))return{directory,mode};if(dirname4(directory)===directory)return void 0}}var GROUP_OR_OTHER_WRITE,STICKY_BIT,ROOT_UID;var init_replaceable_directory=__esm({"libs/sdk/src/server/security/replaceable-directory.ts"(){"use strict";GROUP_OR_OTHER_WRITE=18;STICKY_BIT=512;ROOT_UID=0}});import{createChangeFeed,createStorage,getEnv as getEnv8,getRuntimeContext as getRuntimeContext12,lstat,mkdir,realpath,writeFile}from"@frontmcp/utils";async function createQuestionStore(options){const{storage:config,keyPrefix="mcp:questions:",encryption,pollIntervalMs,coalesceMs,logger}=options;const enabled=encryption?.enabled??"auto";const secret=enabled===false?void 0:encryption?.secret??getElicitationSecret()??void 0;if(enabled===true&&!secret){throw new InvalidQuestionStoreError("encryption is on but no secret is set: set MCP_ELICITATION_SECRET (or MCP_SESSION_SECRET / MCP_SERVER_SECRET)")}let storage;try{storage=await createStorage({...config,prefix:keyPrefix,fallback:"error"})}catch(error){throw new InvalidQuestionStoreError(`the ${config.type} store cannot be opened: ${error instanceof Error?error.message:String(error)}`)}const feed=createChangeFeed(storage,{pollIntervalMs,coalesceMs,onError:error=>logger?.warn("Persistent questions: a change notification failed",error)});return{store:new QuestionStore({storage,feed,secret}),type:config.type,encrypted:!!secret,storage}}async function resolveQuestionStorage(sources3){if(sources3.storage)return sources3.storage;const redis=sources3.redis===void 0?void 0:redisOptionsSchema.safeParse(sources3.redis);if(redis?.success&&isRedisProvider(redis.data)){const{host,port,password,db,tls}=redis.data;return{type:"redis",redis:{config:{host,port,password,db,tls}}}}if(sources3.sqlite)return{type:"sqlite",sqlite:sources3.sqlite};const{runtime,deployment}=getRuntimeContext12();if(runtime!=="node"||deployment==="serverless"){throw new InvalidQuestionStoreError("this runtime has no default store for questions: set elicitation.persistent.storage, or the server redis")}const path4=nodePath2();const home=getEnv8("FRONTMCP_HOME")||path4.join(nodeOs2().homedir(),".frontmcp");const file=path4.join(home,"questions.sqlite");await mkdir(home,{recursive:true,mode:OWNER_ONLY_DIRECTORY});if(process.platform!=="win32")await assertNoOtherUserCanReplace(home);await writeFile(file,"",{mode:OWNER_ONLY_FILE,flag:"a"});if(process.platform!=="win32")await assertOwnerOnlyFile(file);return{type:"sqlite",sqlite:{path:file}}}async function assertNoOtherUserCanReplace(home){for(const directory of new Set([home,await realpath(home)])){const replaceable=await findReplaceableDirectory(directory);if(!replaceable)continue;const{ownerUid}=replaceable;const reason=ownerUid===void 0?"the group or others can write to it":`it belongs to another user (uid ${ownerUid})`;throw new InvalidQuestionStoreError(`refusing the default store under ${replaceable.directory}: ${reason}. Set FRONTMCP_HOME to a folder only you can write to, or elicitation.persistent.storage`)}}async function assertOwnerOnlyFile(file){const stats=await lstat(file);const reason=!stats.isFile()?"it is not a regular file":stats.uid!==process.getuid?.()?`it belongs to another user (uid ${stats.uid})`:stats.mode&GROUP_OR_OTHER_ACCESS?"the group or others can read it":void 0;if(reason){throw new InvalidQuestionStoreError(`refusing the default store ${file}: ${reason}; make it owner-only (0600)`)}}function nodeOs2(){return __require("os")}function nodePath2(){return __require("path")}var OWNER_ONLY_DIRECTORY,OWNER_ONLY_FILE,GROUP_OR_OTHER_ACCESS;var init_question_store_factory=__esm({"libs/sdk/src/elicitation/questions/question-store.factory.ts"(){"use strict";init_common();init_replaceable_directory();init_elicitation_encryption();init_question_errors();init_question_store();OWNER_ONLY_DIRECTORY=448;OWNER_ONLY_FILE=384;GROUP_OR_OTHER_ACCESS=63}});var question_scope_helper_exports={};__export(question_scope_helper_exports,{DEFAULT_QUESTION_TTL_MS:()=>DEFAULT_QUESTION_TTL_MS,openPersistentQuestions:()=>openPersistentQuestions,parsePersistentQuestionsOptions:()=>parsePersistentQuestionsOptions,persistentQuestionsSettings:()=>persistentQuestionsSettings,questionsServerStore:()=>questionsServerStore});import{internalZ as z72}from"@frontmcp/lazy-zod";import{sha256Hex as sha256Hex11}from"@frontmcp/utils";function parsePersistentQuestionsOptions(persistent){const parsed=persistentQuestionsOptionsSchema.safeParse(persistent===true?{}:persistent);if(!parsed.success){throw new InvalidQuestionStoreError(parsed.error.issues.map(issue=>issue.message).join("; "))}return{...parsed.data,storage:parsed.data.storage}}function persistentQuestionsSettings(persistent,onEdgeRuntime){const settings=parsePersistentQuestionsOptions(persistent);if(onEdgeRuntime)throw new InvalidQuestionStoreError(NOT_ON_EDGE_RUNTIME);return settings}function questionsServerStore(storage,server){if(storage)return storage.type==="memory"?void 0:"elicitation.persistent.storage";const elicitationRedis=server.elicitation?.redis;const[option,redis]=elicitationRedis?["elicitation.redis",elicitationRedis]:["redis",server.redis];if(redis&&redis.provider!=="vercel-kv")return option;return server.sqlite?"sqlite":"the default questions.sqlite file"}async function openPersistentQuestions(options){const{persistent,serverName="",logger}=options;if(!persistent)return void 0;const settings=persistentQuestionsSettings(persistent,options.onEdgeRuntime??false);const storage=await resolveQuestionStorage({storage:settings.storage,redis:options.redis,sqlite:options.sqlite});const keyPrefix=`mcp:questions:${sha256Hex11(`server:${serverName}`).slice(0,16)}:`;const{store,type,encrypted}=await createQuestionStore({storage,keyPrefix,logger});logger.info("Persistent questions are on",{type,encrypted});return{store,type,ttlMs:settings.ttlMs??DEFAULT_QUESTION_TTL_MS,inboxLinks:settings.inboxLinks??"terminal"}}var DEFAULT_QUESTION_TTL_MS,persistentQuestionsOptionsSchema,NOT_ON_EDGE_RUNTIME;var init_question_scope_helper=__esm({"libs/sdk/src/elicitation/questions/question-scope.helper.ts"(){"use strict";init_question_store_factory();init_question_errors();DEFAULT_QUESTION_TTL_MS=864e5;persistentQuestionsOptionsSchema=z72.object({ttlMs:z72.number({message:"ttlMs must be a number of milliseconds"}).int("ttlMs must be a whole number of milliseconds").positive("ttlMs must be greater than 0").optional(),storage:z72.object({type:z72.enum(["memory","redis","sqlite"],{message:"storage.type must be 'memory', 'redis' or 'sqlite'"})}).passthrough().optional(),inboxLinks:z72.enum(["terminal","stderr","off"],{message:"inboxLinks must be 'terminal', 'stderr' or 'off'"}).optional()},{error:issue=>issue.code==="invalid_type"?"it must be true, false or an object of settings":void 0}).strict();NOT_ON_EDGE_RUNTIME="it is not available on an edge runtime: a question must outlive the isolate that asked it, and none of its stores runs there ('redis' needs a TCP connection, 'sqlite' a local file, and 'memory' ends with the isolate). Run the server on Node.js to keep questions, or turn elicitation.persistent off"}});function completionEventsOf(scope){let events=byScope.get(scope);if(!events){events=new ScopeCompletionEvents;byScope.set(scope,events)}return events}function completionOutputText(value){if(value===void 0)return void 0;if(typeof value==="string")return value;try{return JSON.stringify(value)}catch{return String(value)}}var CompletionStream,ScopeCompletionEvents,byScope;var init_completion_events=__esm({"libs/sdk/src/channel/sources/completion-events.ts"(){"use strict";CompletionStream=class{listeners=new Set;subscribe(listener){this.listeners.add(listener);return()=>{this.listeners.delete(listener)}}emit(event){for(const listener of[...this.listeners]){try{listener(event)}catch{}}}};ScopeCompletionEvents=class{agents=new CompletionStream;jobs=new CompletionStream};byScope=new WeakMap}});import{internalZ as z73}from"@frontmcp/lazy-zod";var ExecuteWorkflowTool;var init_execute_workflow_tool=__esm({"libs/sdk/src/workflow/tools/execute-workflow.tool.ts"(){"use strict";init_common();init_errors();ExecuteWorkflowTool=class extends ToolContext{async execute(input){const scope=this.scope;const executionManager=scope._jobExecutionManager;const workflowRegistry=this.scope.workflows;const jobRegistry=this.scope.jobs;if(!executionManager||!workflowRegistry||!jobRegistry){return this.fail(new Error("Jobs/workflows system is not enabled"))}const workflow=workflowRegistry.findByName(input.name);if(!workflow){return this.fail(new JobNotAuthorizedError(input.name))}const result=await executionManager.executeWorkflow(workflow,jobRegistry,{background:input.background,sessionId:this.authInfo.sessionId,authInfo:this.authInfo,context:this.context,authoritiesContextBuilder:this.scope.authoritiesContextBuilder,workflowInput:input.input});return result}};ExecuteWorkflowTool=__decorateClass([Tool({name:"execute_workflow",description:"Execute a registered workflow by name. Supports inline and background execution.",inputSchema:{name:z73.string().describe("Workflow name to execute"),input:z73.record(z73.string(),z73.unknown()).optional().describe("Workflow input data"),background:z73.boolean().optional().default(false).describe("Run in background (returns runId)")},outputSchema:{runId:z73.string(),state:z73.string(),result:z73.unknown().optional()}})],ExecuteWorkflowTool)}});var JobPermissionGuard;var init_job_permission_guard=__esm({"libs/sdk/src/job/job-permission.guard.ts"(){"use strict";init_principal_utils();JobPermissionGuard=class _JobPermissionGuard{static async check(permissions,action,authInfo,contextBuilder){if(!permissions||permissions.length===0){return true}const relevant=permissions.filter(p=>p.action===action);if(relevant.length===0){return true}const principal=resolvePrincipal(authInfo,contextBuilder);for(const perm of relevant){const passed=await _JobPermissionGuard.checkSingle(perm,principal,authInfo);if(!passed)return false}return true}static async checkSingle(perm,principal,authInfo){if(perm.roles&&perm.roles.length>0){if(!perm.roles.some(role=>principal.roles.includes(role)))return false}if(perm.scopes&&perm.scopes.length>0){if(!perm.scopes.some(scope=>principal.scopes.includes(scope)))return false}if(perm.custom){const result=await perm.custom(authInfo??{});if(!result)return false}return true}}}});function jobRunUri(runId){return`job://runs/${runId}`}function jobExecutionManagerOf(scope){return scope._jobExecutionManager}async function mayAccessRun(scope,record,action,authInfo){const builder=scope.authoritiesContextBuilder;if(record.ownerSub){if(record.ownerSub===resolvePrincipal(authInfo,builder).sub)return true}else if(record.sessionId&&record.sessionId===authInfo["sessionId"]){return true}const permissions=permissionsOfRun(scope,record);if(!permissions?.some(rule=>rule.action===action))return false;return JobPermissionGuard.check(permissions,action,authInfo,builder)}function permissionsOfRun(scope,record){if("workflowName"in record)return scope.workflows?.findByName(record.workflowName)?.metadata.permissions;return scope.jobs?.findByName(record.jobName)?.metadata.permissions}var init_job_run_access=__esm({"libs/sdk/src/job/job-run-access.ts"(){"use strict";init_principal_utils();init_job_permission_guard()}});import{internalZ as z74}from"@frontmcp/lazy-zod";var GetWorkflowStatusTool;var init_get_workflow_status_tool=__esm({"libs/sdk/src/workflow/tools/get-workflow-status.tool.ts"(){"use strict";init_common();init_job_run_access();GetWorkflowStatusTool=class extends ToolContext{async execute(input){const scope=this.scope;const executionManager=scope._jobExecutionManager;if(!executionManager){return this.fail(new Error("Jobs system is not enabled"))}const record=await executionManager.getStatus(input.runId);if(!record||!await mayAccessRun(this.scope,record,"read",this.authInfo)){return this.fail(new Error(`Run "${input.runId}" not found`))}const workflowRecord=record;return{runId:record.runId,workflowName:workflowRecord.workflowName,state:record.state,stepResults:workflowRecord.stepResults,startedAt:record.startedAt,completedAt:record.completedAt}}};GetWorkflowStatusTool=__decorateClass([Tool({name:"get_workflow_status",description:"Get the execution status of a workflow run with per-step results.",inputSchema:{runId:z74.string().describe("Run ID returned from execute_workflow")},outputSchema:{runId:z74.string(),workflowName:z74.string().optional(),state:z74.string(),stepResults:z74.record(z74.string(),z74.object({state:z74.string(),outputs:z74.record(z74.string(),z74.unknown()).optional()})).optional(),startedAt:z74.number(),completedAt:z74.number().optional()}})],GetWorkflowStatusTool)}});import{internalZ as z75}from"@frontmcp/lazy-zod";var ListWorkflowsTool;var init_list_workflows_tool=__esm({"libs/sdk/src/workflow/tools/list-workflows.tool.ts"(){"use strict";init_common();init_job_permission_guard();ListWorkflowsTool=class extends ToolContext{async execute(input){const workflowRegistry=this.scope.workflows;if(!workflowRegistry){return{workflows:[],count:0}}const workflows=workflowRegistry.search(input.query,{tags:input.tags,labels:input.labels});const visible=[];for(const workflow of workflows){if(await this.maySee(workflow))visible.push(workflow)}const mapped=visible.map(w=>({name:w.name,description:w.metadata.description,trigger:w.getTrigger(),stepCount:w.getSteps().length,tags:w.getTags()}));return{workflows:mapped,count:mapped.length}}async maySee(workflow){const permissions=workflow.metadata.permissions;const builder=this.scope.authoritiesContextBuilder;if(!await JobPermissionGuard.check(permissions,"list",this.authInfo,builder))return false;return JobPermissionGuard.check(permissions,"execute",this.authInfo,builder)}};ListWorkflowsTool=__decorateClass([Tool({name:"list_workflows",description:"List registered workflows with optional filtering by tags or labels.",inputSchema:{tags:z75.array(z75.string()).optional().describe("Filter by tags"),labels:z75.record(z75.string(),z75.string()).optional().describe("Filter by labels"),query:z75.string().optional().describe("Search query for name/description")},outputSchema:{workflows:z75.array(z75.object({name:z75.string(),description:z75.string().optional(),trigger:z75.string(),stepCount:z75.number(),tags:z75.array(z75.string()).optional()})),count:z75.number()},hideFromDiscovery:true})],ListWorkflowsTool)}});var WorkflowKind;var init_workflow_record=__esm({"libs/sdk/src/common/records/workflow.record.ts"(){"use strict";WorkflowKind=(WorkflowKind2=>{WorkflowKind2["CLASS_TOKEN"]="CLASS_TOKEN";WorkflowKind2["VALUE"]="VALUE";WorkflowKind2["DYNAMIC"]="DYNAMIC";WorkflowKind2["ESM"]="ESM";WorkflowKind2["REMOTE"]="REMOTE";return WorkflowKind2})(WorkflowKind||{})}});import{internalZ as z76}from"@frontmcp/lazy-zod";var RegisterWorkflowTool;var init_register_workflow_tool=__esm({"libs/sdk/src/workflow/tools/register-workflow.tool.ts"(){"use strict";init_common();init_errors();RegisterWorkflowTool=class extends ToolContext{async execute(input){const workflowRegistry=this.scope.workflows;if(!workflowRegistry){return this.fail(new Error("Workflows system is not enabled"))}if(!this.dynamicRegistrationEnabled()){return this.fail(new DynamicJobRegistrationDisabledError("workflow"))}const existing=workflowRegistry.findByName(input.name);if(existing){return this.fail(new Error(`Workflow "${input.name}" already exists`))}const workflowId=input.name;workflowRegistry.registerDynamic({kind:"DYNAMIC",provide:workflowId,metadata:{id:workflowId,name:input.name,description:input.description,steps:input.steps,trigger:input.trigger??"manual",tags:input.tags},registeredBy:this.authInfo?.["sub"]??"anonymous",registeredAt:Date.now()});return{success:true,workflowId}}dynamicRegistrationEnabled(){const jobs=this.scope.metadata?.jobs;return jobs?.allowDynamicRegistration===true}};RegisterWorkflowTool=__decorateClass([Tool({name:"register_workflow",description:"Register a dynamic workflow with step definitions.",inputSchema:{name:z76.string().describe("Workflow name"),description:z76.string().optional().describe("Workflow description"),steps:z76.array(z76.object({id:z76.string().describe("Step identifier"),jobName:z76.string().describe("Job name to execute"),input:z76.record(z76.string(),z76.unknown()).optional().describe("Static input for the step"),dependsOn:z76.array(z76.string()).optional().describe("Step IDs that must complete first"),continueOnError:z76.boolean().optional().describe("Continue on failure"),timeout:z76.number().optional().describe("Step timeout in ms")})).describe("Workflow step definitions"),trigger:z76.enum(["manual","webhook","event"]).optional().describe("Trigger type"),tags:z76.array(z76.string()).optional().describe("Tags for categorization")},outputSchema:{success:z76.boolean(),workflowId:z76.string()},hideFromDiscovery:true})],RegisterWorkflowTool)}});import{internalZ as z77}from"@frontmcp/lazy-zod";var RemoveWorkflowTool;var init_remove_workflow_tool=__esm({"libs/sdk/src/workflow/tools/remove-workflow.tool.ts"(){"use strict";init_common();init_errors();init_job_permission_guard();RemoveWorkflowTool=class extends ToolContext{async execute(input){const workflowRegistry=this.scope.workflows;if(!workflowRegistry){return this.fail(new Error("Workflows system is not enabled"))}const workflow=workflowRegistry.findByName(input.name);if(!workflow){return this.fail(new JobNotAuthorizedError(input.name))}const allowed=await JobPermissionGuard.check(workflow.metadata.permissions,"delete",this.authInfo,this.scope.authoritiesContextBuilder);if(!allowed){return this.fail(new JobNotAuthorizedError(input.name))}if(!workflow.isDynamic()){return this.fail(new Error(`Workflow "${input.name}" is not dynamic and cannot be removed`))}const removed=workflowRegistry.removeDynamic(input.name);return{success:removed,message:removed?`Workflow "${input.name}" removed`:`Failed to remove workflow "${input.name}"`}}};RemoveWorkflowTool=__decorateClass([Tool({name:"remove_workflow",description:"Remove a dynamic workflow by name.",inputSchema:{name:z77.string().describe("Workflow name to remove")},outputSchema:{success:z77.boolean(),message:z77.string()},hideFromDiscovery:true})],RemoveWorkflowTool)}});var LogTransportInterface,FrontMcpLogger,FRONTMCP_LOGGER;var init_logger_interface=__esm({"libs/sdk/src/common/interfaces/logger.interface.ts"(){"use strict";LogTransportInterface=class{};FrontMcpLogger=class{};FRONTMCP_LOGGER=Symbol.for("frontmcp:LOGGER")}});var WorkflowEmitter;var init_workflow_events=__esm({"libs/sdk/src/workflow/workflow.events.ts"(){"use strict";WorkflowEmitter=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)}}}});var ScopeKind;var init_scope_record=__esm({"libs/sdk/src/common/records/scope.record.ts"(){"use strict";ScopeKind=(ScopeKind2=>{ScopeKind2["SPLIT_BY_APP"]="SPLIT_BY_APP";ScopeKind2["MULTI_APP"]="MULTI_APP";return ScopeKind2})(ScopeKind||{})}});var FlowKind;var init_flow_record=__esm({"libs/sdk/src/common/records/flow.record.ts"(){"use strict";FlowKind=(FlowKind2=>{FlowKind2["CLASS_TOKEN"]="CLASS_TOKEN";return FlowKind2})(FlowKind||{})}});var HookKind;var init_hook_record=__esm({"libs/sdk/src/common/records/hook.record.ts"(){"use strict";HookKind=(HookKind2=>{HookKind2["METHOD_TOKEN"]="METHOD_TOKEN";return HookKind2})(HookKind||{})}});var AppKind;var init_app_record=__esm({"libs/sdk/src/common/records/app.record.ts"(){"use strict";AppKind=(AppKind2=>{AppKind2["LOCAL_CLASS"]="LOCAL_CLASS";AppKind2["REMOTE_VALUE"]="REMOTE_VALUE";AppKind2["LAZY_IMPORT"]="LAZY_IMPORT";return AppKind2})(AppKind||{})}});import{ProviderKind as ProviderKind2}from"@frontmcp/di";var init_provider_record=__esm({"libs/sdk/src/common/records/provider.record.ts"(){"use strict"}});var AuthProviderKind;var init_auth_provider_record=__esm({"libs/sdk/src/common/records/auth-provider.record.ts"(){"use strict";AuthProviderKind=(AuthProviderKind2=>{AuthProviderKind2["CLASS_TOKEN"]="CLASS_TOKEN";AuthProviderKind2["CLASS"]="CLASS";AuthProviderKind2["VALUE"]="VALUE";AuthProviderKind2["FACTORY"]="FACTORY";AuthProviderKind2["PRIMARY"]="PRIMARY";return AuthProviderKind2})(AuthProviderKind||{})}});var PluginKind;var init_plugin_record=__esm({"libs/sdk/src/common/records/plugin.record.ts"(){"use strict";PluginKind=(PluginKind2=>{PluginKind2["CLASS_TOKEN"]="CLASS_TOKEN";PluginKind2["CLASS"]="CLASS";PluginKind2["FACTORY"]="FACTORY";PluginKind2["VALUE"]="VALUE";return PluginKind2})(PluginKind||{})}});var AdapterKind;var init_adapter_record=__esm({"libs/sdk/src/common/records/adapter.record.ts"(){"use strict";AdapterKind=(AdapterKind2=>{AdapterKind2["CLASS_TOKEN"]="CLASS_TOKEN";AdapterKind2["CLASS"]="CLASS";AdapterKind2["VALUE"]="VALUE";AdapterKind2["FACTORY"]="FACTORY";return AdapterKind2})(AdapterKind||{})}});var PromptKind;var init_prompt_record=__esm({"libs/sdk/src/common/records/prompt.record.ts"(){"use strict";PromptKind=(PromptKind2=>{PromptKind2["CLASS_TOKEN"]="CLASS_TOKEN";PromptKind2["FUNCTION"]="FUNCTION";PromptKind2["ESM"]="ESM";PromptKind2["REMOTE"]="REMOTE";return PromptKind2})(PromptKind||{})}});var LoggerKind;var init_logger_record=__esm({"libs/sdk/src/common/records/logger.record.ts"(){"use strict";LoggerKind=(LoggerKind2=>{LoggerKind2["CLASS_TOKEN"]="CLASS_TOKEN";return LoggerKind2})(LoggerKind||{})}});var AgentKind;var init_agent_record=__esm({"libs/sdk/src/common/records/agent.record.ts"(){"use strict";AgentKind=(AgentKind2=>{AgentKind2["CLASS_TOKEN"]="CLASS_TOKEN";AgentKind2["FUNCTION"]="FUNCTION";AgentKind2["VALUE"]="VALUE";AgentKind2["FACTORY"]="FACTORY";AgentKind2["ESM"]="ESM";AgentKind2["REMOTE"]="REMOTE";return AgentKind2})(AgentKind||{})}});var SkillKind;var init_skill_record=__esm({"libs/sdk/src/common/records/skill.record.ts"(){"use strict";SkillKind=(SkillKind2=>{SkillKind2["CLASS_TOKEN"]="CLASS_TOKEN";SkillKind2["VALUE"]="VALUE";SkillKind2["FILE"]="FILE";SkillKind2["ESM"]="ESM";SkillKind2["REMOTE"]="REMOTE";return SkillKind2})(SkillKind||{})}});var JobKind;var init_job_record=__esm({"libs/sdk/src/common/records/job.record.ts"(){"use strict";JobKind=(JobKind2=>{JobKind2["CLASS_TOKEN"]="CLASS_TOKEN";JobKind2["FUNCTION"]="FUNCTION";JobKind2["DYNAMIC"]="DYNAMIC";JobKind2["ESM"]="ESM";JobKind2["REMOTE"]="REMOTE";return JobKind2})(JobKind||{})}});import{ProviderKind as ProviderKind3}from"@frontmcp/di";var init_records=__esm({"libs/sdk/src/common/records/index.ts"(){"use strict";init_scope_record();init_flow_record();init_hook_record();init_app_record();init_provider_record();init_auth_provider_record();init_plugin_record();init_adapter_record();init_tool_record();init_resource_record();init_prompt_record();init_logger_record();init_agent_record();init_skill_record();init_job_record();init_workflow_record();init_channel_record()}});import"reflect-metadata";var BaseEntry;var init_base_entry=__esm({"libs/sdk/src/common/entries/base.entry.ts"(){"use strict";BaseEntry=class{ready;record;token;metadata;constructor(record,token,metadata){this.record=record;this.token=token??record.provide;this.metadata=metadata??record.metadata}}}});var WorkflowEntry;var init_workflow_entry=__esm({"libs/sdk/src/common/entries/workflow.entry.ts"(){"use strict";init_base_entry();WorkflowEntry=class extends BaseEntry{owner;name;fullName;isDynamic(){return this.record.kind==="DYNAMIC"}isHidden(){return this.metadata.hideFromDiscovery===true}getTags(){return this.metadata.tags??[]}getLabels(){return this.metadata.labels??{}}getSteps(){return this.metadata.steps}getTrigger(){return this.metadata.trigger??"manual"}}}});var WorkflowInstance;var init_workflow_instance=__esm({"libs/sdk/src/workflow/workflow.instance.ts"(){"use strict";init_workflow_entry();WorkflowInstance=class extends WorkflowEntry{_providers;scope;hooks;constructor(record,providers,owner){super(record);this.owner=owner;this._providers=providers;this.name=record.metadata.id||record.metadata.name;this.fullName=this.owner.id+":"+this.name;this.scope=this._providers.getActiveScope();this.hooks=this.scope.hooks;this.ready=this.initialize()}async initialize(){return Promise.resolve()}getMetadata(){return this.record.metadata}get providers(){return this._providers}}}});import{getMetadata as getMetadata14,isClass as isClass11}from"@frontmcp/di";function collectWorkflowMetadata(cls){const extended=getMetadata14(extendedWorkflowMetadata,cls);const seed=extended?{...extended}:{};return Object.entries(FrontMcpWorkflowTokens).reduce((metadata,[key,token])=>{const value=getMetadata14(token,cls);if(value!==void 0){return Object.assign(metadata,{[key]:value})}else{return metadata}},seed)}function normalizeWorkflow(item){if(item&&typeof item==="function"&&item[FrontMcpWorkflowTokens.type]==="value-workflow"&&item[FrontMcpWorkflowTokens.metadata]){const metadata=item[FrontMcpWorkflowTokens.metadata];return{kind:"VALUE",provide:Symbol.for(`workflow:${metadata.name}`),metadata}}if(isClass11(item)){const metadata=collectWorkflowMetadata(item);return{kind:"CLASS_TOKEN",provide:item,metadata}}const name51=(item!=null&&typeof item==="object"&&"name"in item?item.name:void 0)??String(item);throw new InvalidEntityError("workflow",name51,"a class or a workflow object")}var init_workflow_utils=__esm({"libs/sdk/src/workflow/workflow.utils.ts"(){"use strict";init_workflow_tokens();init_errors()}});import{tokenName as tokenName12}from"@frontmcp/di";var WorkflowRegistry;var init_workflow_registry=__esm({"libs/sdk/src/workflow/workflow.registry.ts"(){"use strict";init_logger_interface();init_regsitry();init_lineage_utils();init_workflow_events();init_workflow_instance();init_workflow_utils();WorkflowRegistry=class extends RegistryAbstract{owner;localRows=[];dynamicRows=[];byName=new Map;byId=new Map;version=0;emitter=new WorkflowEmitter;logger;constructor(providers,list,owner){super("WorkflowRegistry",providers,list,false);this.owner=owner;try{this.logger=providers.get(FrontMcpLogger)}catch{}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=normalizeWorkflow(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){}async initialize(){for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)continue;const wi=new WorkflowInstance(rec,this.providers,this.owner);this.instances.set(token,wi);const lineage=this.owner?[this.owner]:[];const row=this.makeRow(token,wi,lineage);this.localRows.push(row)}this.reindex();this.bump("reset")}getWorkflows(includeHidden=false){const all=[...this.localRows,...this.dynamicRows].map(r=>r.instance);return all.filter(w=>w.metadata.hideFromDiscovery!==true||includeHidden)}findByName(name51){return this.byName.get(name51)?.instance}findById(id){return this.byId.get(id)?.instance}search(query,opts){let workflows=this.getWorkflows(false);if(query){const q=query.toLowerCase();workflows=workflows.filter(w=>w.name.toLowerCase().includes(q)||(w.metadata.description??"").toLowerCase().includes(q))}if(opts?.tags&&opts.tags.length>0){const filterTags=opts.tags;workflows=workflows.filter(w=>{const tags=w.getTags();return filterTags.some(t=>tags.includes(t))})}if(opts?.labels){const labelEntries=Object.entries(opts.labels);workflows=workflows.filter(w=>{const labels=w.getLabels();return labelEntries.every(([k,v])=>labels[k]===v)})}return workflows}registerDynamic(record){const token=Symbol.for(`workflow:dynamic:${record.provide}`);const existing=this.dynamicRows.findIndex(r=>r.token===token);if(existing!==-1){this.dynamicRows.splice(existing,1)}const wi=new WorkflowInstance(record,this.providers,this.owner);this.instances.set(token,wi);const lineage=this.owner?[this.owner]:[];const row=this.makeRow(token,wi,lineage);this.dynamicRows.push(row);this.reindex();this.bump("added")}removeDynamic(workflowId){const idx=this.dynamicRows.findIndex(r=>r.instance.metadata.id===workflowId||r.instance.name===workflowId);if(idx===-1)return false;const row=this.dynamicRows[idx];this.dynamicRows.splice(idx,1);this.instances.delete(row.token);this.reindex();this.bump("removed");return true}subscribe(opts,cb){if(opts.immediate){cb({kind:"reset",changeScope:"global",version:this.version,snapshot:this.getWorkflows()})}return this.emitter.on(cb)}hasAny(){return this.localRows.length>0||this.dynamicRows.length>0}reindex(){this.byName.clear();this.byId.clear();const effective=[...this.localRows,...this.dynamicRows];for(const r of effective){if(this.byName.has(r.baseName)){this.logger?.warn(`WorkflowRegistry: duplicate workflow name "${r.baseName}" detected during reindex; later entry wins`)}this.byName.set(r.baseName,r);const idKey=r.instance.metadata.id??r.baseName;if(this.byId.has(idKey)){this.logger?.warn(`WorkflowRegistry: duplicate workflow id "${idKey}" detected during reindex; later entry wins`)}this.byId.set(idKey,r)}}bump(kind){const version=++this.version;this.emitter.emit({kind,changeScope:"global",version,snapshot:this.getWorkflows()})}makeRow(token,instance,lineage){const ownerKey=ownerKeyOf(lineage);const baseName=instance.name;const qualifiedName=qualifiedNameOf(lineage,baseName);const qualifiedId=`${ownerKey}:${tokenName12(token)}`;return{token,instance,baseName,lineage,ownerKey,qualifiedName,qualifiedId,source:this}}}}});import{tokenName as tokenName13}from"@frontmcp/di";function lifecycleHooksOf(value){if(typeof value!=="object"||value===null)return void 0;const candidate=value;return HOOK_NAMES.some(name51=>typeof candidate[name51]==="function")?value:void 0}async function bootstrapProvider({token,instance}){try{await instance.onBootstrap?.()}catch(error){throw new ProviderBootstrapError(tokenName13(token),error)}}async function readyProviders(entries,logger){for(const{token,instance}of entries){try{await instance.onReady?.()}catch(error){logger.error(`Provider "${tokenName13(token)}" failed in onReady(): ${messageOf3(error)}`)}}}async function shutdownProviders(entries,timeoutMs,logger){for(const{token,instance}of[...entries].reverse()){const onShutdown=instance.onShutdown;if(typeof onShutdown!=="function")continue;try{if(await outlasts(()=>onShutdown.call(instance),timeoutMs)){logger.warn(`Provider "${tokenName13(token)}" onShutdown() did not finish within ${timeoutMs} ms`)}}catch(error){logger.warn(`Provider "${tokenName13(token)}" failed in onShutdown(): ${messageOf3(error)}`)}}}async function outlasts(run,timeoutMs){let timer;const deadline=new Promise(resolve4=>{timer=setTimeout(()=>resolve4(true),timeoutMs)});try{const finished=Promise.resolve().then(run).then(()=>false);return await Promise.race([finished,deadline])}finally{clearTimeout(timer)}}function messageOf3(error){return error instanceof Error?error.message:String(error)}var DEFAULT_SHUTDOWN_HOOK_TIMEOUT_MS,HOOK_NAMES;var init_provider_lifecycle=__esm({"libs/sdk/src/provider/provider.lifecycle.ts"(){"use strict";init_errors();DEFAULT_SHUTDOWN_HOOK_TIMEOUT_MS=3e3;HOOK_NAMES=["onBootstrap","onReady","onShutdown"]}});import{getHostname}from"@frontmcp/utils";function isLocalWorker(executor){return executor.hostname===void 0||executor.hostname===getHostname()}function isAlive(pid){if(!Number.isFinite(pid)||pid<=0)return false;try{process.kill(pid,0);return true}catch(err){const code=err?.code;if(code==="EPERM")return true;return false}}var init_process_liveness=__esm({"libs/sdk/src/task/helpers/process-liveness.ts"(){"use strict"}});async function runJobAttemptFlow(request2){const{job,context}=request2;const scope=job.providers.getActiveScope();const admission=request2.admission?.slot();const run=()=>scope.runFlowForOutput(EXECUTE_JOB_FLOW,{job,input:request2.input,attempt:request2.attempt,ctx:{authInfo:request2.authInfo,contextProviders:context?void 0:request2.contextProviders,authoritiesContextBuilder:request2.authoritiesContextBuilder,run:request2.run,workflow:request2.workflow,signal:request2.signal,timeoutMs:request2.timeoutMs,admission}});try{const storage=contextStorageOf(scope);if(!context||!storage||storage.getStore()===context)return await run();return await storage.runWithContext(context,run)}finally{admission?.release()}}function willRetryJobAttempt(error,attempt,maxAttempts){if(attempt>=maxAttempts)return false;const cause=error instanceof FlowControl?error.originalError??error:error;return!FINAL_FAILURES.some(failure=>cause instanceof failure)}async function runJobCleanup(job,jobContext,reason,logger){const cleanup=job.metadata.cleanup;if(!cleanup)return;const{run,timeoutMs=DEFAULT_CLEANUP_TIMEOUT_MS}=typeof cleanup==="function"?{run:cleanup}:cleanup;try{if(await outlasts(()=>run(jobContext,reason),timeoutMs)){logger.warn(`cleanup: the ${reason} cleanup did not finish within ${timeoutMs} ms`)}}catch(error){logger.warn(`cleanup: the ${reason} cleanup failed: ${toJobError(error).message}`)}}function interruptReasonOf(reason){if(reason instanceof JobCancelledError)return"cancel";if(reason instanceof JobInterruptedError)return"interrupt";return"timeout"}function untilAborted(work,signal){return new Promise((resolve4,reject)=>{const aborted=()=>reject(signal.reason);if(signal.aborted)aborted();else signal.addEventListener("abort",aborted,{once:true});work.then(resolve4,reject).finally(()=>signal.removeEventListener("abort",aborted))})}function abortableDelay(ms,signal){return new Promise((resolve4,reject)=>{if(signal?.aborted)return reject(signal.reason);const aborted=()=>{clearTimeout(timer);reject(signal?.reason)};const timer=setTimeout(()=>{signal?.removeEventListener("abort",aborted);resolve4()},ms);signal?.addEventListener("abort",aborted,{once:true})})}function retryDelayMs(retry,attempt){const backoffMs=retry.backoffMs??1e3;const backoffMultiplier=retry.backoffMultiplier??2;const maxBackoffMs=retry.maxBackoffMs??6e4;return Math.min(backoffMs*Math.pow(backoffMultiplier,attempt-1),maxBackoffMs)}function toJobError(error){return error instanceof Error?error:new Error(String(error))}function contextStorageOf(scope){try{return scope.providers.get(FrontMcpContextStorage)}catch{return void 0}}var EXECUTE_JOB_FLOW,FINAL_FAILURES,DEFAULT_CLEANUP_TIMEOUT_MS;var init_job_attempt=__esm({"libs/sdk/src/job/job-attempt.ts"(){"use strict";init_common();init_context();init_errors();init_provider_lifecycle();EXECUTE_JOB_FLOW="jobs:execute-job";FINAL_FAILURES=[InvalidOutputError,JobNotAuthorizedError,JobCancelledError,JobInterruptedError,JobAdmissionTimeoutError];DEFAULT_CLEANUP_TIMEOUT_MS=3e3}});var WorkflowStepExecutor;var init_workflow_step_executor=__esm({"libs/sdk/src/workflow/engine/workflow-step.executor.ts"(){"use strict";init_errors();init_workflow_errors();init_job_attempt();WorkflowStepExecutor=class{jobRegistry;logger;extra;constructor(jobRegistry,logger,extra){this.jobRegistry=jobRegistry;this.logger=logger;this.extra=extra}async executeStep(step,input){const job=this.jobRegistry.findByName(step.jobName);if(!job){throw new InvalidEntityError("job",step.jobName,`a registered job (referenced by step "${step.id}")`)}const retryConfig=step.retry??job.metadata.retry??{};const maxAttempts=retryConfig.maxAttempts??3;const timeout=step.timeout??job.metadata.timeout??this.extra.defaultTimeoutMs??3e5;let lastError;for(let attempt=1;attempt<=maxAttempts;attempt++){try{const result=await this.executeWithTimeout(job,step,input,timeout,attempt);return{outputs:result??{},state:"completed"}}catch(err){lastError=toJobError(err);this.logger.warn(`Step "${step.id}" attempt ${attempt}/${maxAttempts} failed: ${lastError.message}`);if(!willRetryJobAttempt(lastError,attempt,maxAttempts))break;await new Promise(resolve4=>setTimeout(resolve4,retryDelayMs(retryConfig,attempt)))}}throw lastError??new Error(`Step "${step.id}" failed after ${maxAttempts} attempts`)}executeWithTimeout(job,step,input,timeout,attempt){const{context,contextProviders,authInfo,authoritiesContextBuilder,workflowName,workflowRunId,admission}=this.extra;const abandon=new AbortController;return new Promise((resolve4,reject)=>{const timer=timeout>0?setTimeout(()=>{const timedOut=new WorkflowJobTimeoutError(job.name,timeout);abandon.abort(timedOut);reject(timedOut)},timeout):void 0;runJobAttemptFlow({job,input,attempt,authInfo,context,contextProviders,authoritiesContextBuilder,workflow:{name:workflowName,stepId:step.id,runId:workflowRunId},signal:abandon.signal,admission}).then(({result})=>{clearTimeout(timer);resolve4(result)}).catch(err=>{clearTimeout(timer);reject(err)})})}}}});import{getAsyncContextMode}from"@frontmcp/utils";var WorkflowEngine;var init_workflow_engine=__esm({"libs/sdk/src/workflow/engine/workflow.engine.ts"(){"use strict";init_workflow_errors();init_workflow_step_executor();WorkflowEngine=class{metadata;stepExecutor;logger;maxConcurrency;constructor(metadata,jobRegistry,logger,extra){this.metadata=metadata;this.logger=logger;this.maxConcurrency=metadata.maxConcurrency??5;this.stepExecutor=new WorkflowStepExecutor(jobRegistry,logger,{...extra,workflowName:extra.workflowName??metadata.name})}async execute(workflowInput){const startedAt=Date.now();const steps=this.metadata.steps;this.validateDag(steps);const stepResults=new Map;const stepsContext={get(alias){const result=stepResults.get(alias);if(!result){throw new WorkflowStepNotFoundError(alias)}return result}};const completed=new Set;const failed=new Set;const skipped=new Set;const allStepIds=new Set(steps.map(s=>s.id));const timeoutMs=this.metadata.timeout??6e5;const deadline=startedAt+timeoutMs;while(completed.size+failed.size+skipped.size<allStepIds.size){if(Date.now()>deadline){throw new WorkflowTimeoutError(this.metadata.name,timeoutMs)}const ready=steps.filter(step=>{if(completed.has(step.id)||failed.has(step.id)||skipped.has(step.id))return false;const deps=step.dependsOn??[];return deps.every(d=>completed.has(d)||skipped.has(d))});if(ready.length===0){const sizeBefore=completed.size+failed.size+skipped.size;const remaining=steps.filter(s=>!completed.has(s.id)&&!failed.has(s.id)&&!skipped.has(s.id));for(const step of remaining){const deps=step.dependsOn??[];const hasFailedDep=deps.some(d=>failed.has(d));if(hasFailedDep){skipped.add(step.id);stepResults.set(step.id,{outputs:{},state:"skipped"});this.logger.info(`Skipping step "${step.id}" due to failed dependency`)}}const sizeAfter=completed.size+failed.size+skipped.size;if(sizeAfter===sizeBefore){for(const step of remaining){skipped.add(step.id);stepResults.set(step.id,{outputs:{},state:"skipped"});this.logger.info(`Skipping step "${step.id}" \u2014 unreachable due to deadlock`)}break}continue}const batch=ready.slice(0,getAsyncContextMode()==="serialized"?1:this.maxConcurrency);await Promise.allSettled(batch.map(async step=>{if(step.condition){try{const shouldRun=step.condition(stepsContext);if(!shouldRun){skipped.add(step.id);stepResults.set(step.id,{outputs:{},state:"skipped"});this.logger.info(`Skipping step "${step.id}" (condition returned false)`);return}}catch(err){this.logger.warn(`Step "${step.id}" condition evaluation failed: ${err}`);skipped.add(step.id);stepResults.set(step.id,{outputs:{},state:"skipped"});return}}try{let input;if(typeof step.input==="function"){input=step.input(stepsContext)}else{input=step.input??workflowInput??{}}const result=await this.stepExecutor.executeStep(step,input);completed.add(step.id);stepResults.set(step.id,result);this.logger.info(`Step "${step.id}" completed successfully`)}catch(err){if(step.continueOnError){completed.add(step.id);stepResults.set(step.id,{outputs:{},state:"failed"});this.logger.warn(`Step "${step.id}" failed but continueOnError=true: ${err}`)}else{failed.add(step.id);stepResults.set(step.id,{outputs:{},state:"failed"});this.logger.error(`Step "${step.id}" failed: ${err}`)}}}))}const completedAt=Date.now();const hasFailed=failed.size>0;const resultRecord={};for(const[k,v]of stepResults){resultRecord[k]=v}return{workflowName:this.metadata.name,state:hasFailed?"failed":"completed",stepResults:resultRecord,startedAt,completedAt}}validateDag(steps){const ids=new Set(steps.map(s=>s.id));if(ids.size!==steps.length){throw new WorkflowDagValidationError("Workflow has duplicate step IDs")}for(const step of steps){for(const dep of step.dependsOn??[]){if(!ids.has(dep)){throw new WorkflowDagValidationError(`Step "${step.id}" depends on unknown step "${dep}"`)}}}const stepMap=new Map(steps.map(s=>[s.id,s]));const visiting=new Set;const visited=new Set;const dfs=id=>{if(visited.has(id))return;if(visiting.has(id)){throw new WorkflowDagValidationError(`Workflow has a cycle involving step "${id}"`)}visiting.add(id);const step=stepMap.get(id);if(!step){throw new WorkflowDagValidationError(`Step "${id}" not found during cycle detection`)}for(const dep of step.dependsOn??[]){dfs(dep)}visiting.delete(id);visited.add(id)};for(const step of steps){dfs(step.id)}}}}});async function jobContextProviders(job,context){const contextDeps=new Map([[FRONTMCP_CONTEXT,context]]);for(const[token,instance]of context.getContextTokens())contextDeps.set(token,instance);const views=await job.providers.buildViews(context.sessionId,contextDeps);return new FlowContextProviders(job.providers,views.context)}function detachedRunContext(context){const runContext=new FrontMcpContext({sessionId:context.sessionId,authInfo:context.authInfo,scopeId:context.scopeId,traceContext:context.traceContext,metadata:context.metadata,config:context.config,platformEnv:context.platformEnv});for(const[token,instance]of context.getContextTokens())runContext.setContextToken(token,instance);return runContext}var init_job_context_providers=__esm({"libs/sdk/src/job/job-context-providers.ts"(){"use strict";init_context();init_flow_context_providers()}});function detachedJobRunId(){return typeof process==="undefined"?void 0:process.env?.[RUN_JOB_ENV_VAR]}function isJobWorker(metadata){return metadata[JOB_WORKER_FLAG]===true}function markEntryServer(config){config[ENTRY_SERVER_FLAG]=true}function isEntryServer(metadata){return metadata[ENTRY_SERVER_FLAG]===true}var JOB_WORKER_MARKER,RUN_JOB_ENV_VAR,JOB_WORKER_FLAG,ENTRY_SERVER_FLAG;var init_detached_job_flag=__esm({"libs/sdk/src/front-mcp/detached-job.flag.ts"(){"use strict";JOB_WORKER_MARKER="frontmcp-job";RUN_JOB_ENV_VAR="FRONTMCP_RUN_JOB_ID";JOB_WORKER_FLAG="__jobWorker";ENTRY_SERVER_FLAG="__entryServer"}});var cli_task_runner_exports={};__export(cli_task_runner_exports,{CliTaskRunner:()=>CliTaskRunner,RUN_TASK_ENV_VAR:()=>RUN_TASK_ENV_VAR,RUN_TASK_SUBCOMMAND:()=>RUN_TASK_SUBCOMMAND,TASK_WORKER_MARKER:()=>TASK_WORKER_MARKER});import{getHostname as getHostname2,spawnOwned}from"@frontmcp/utils";var RUN_TASK_SUBCOMMAND,RUN_TASK_ENV_VAR,TASK_WORKER_MARKER,CliTaskRunner;var init_cli_task_runner=__esm({"libs/sdk/src/task/helpers/cli-task-runner.ts"(){"use strict";init_process_liveness();RUN_TASK_SUBCOMMAND="__run-task";RUN_TASK_ENV_VAR="FRONTMCP_RUN_TASK_ID";TASK_WORKER_MARKER="frontmcp-task";CliTaskRunner=class{constructor(deps){this.deps=deps}deps;kind="cli";async run(record,_context){const{exe,args}=this.resolveCommand();const fullArgs=[...args,RUN_TASK_SUBCOMMAND,record.taskId];this.deps.logger?.info("[CliTaskRunner] spawning detached worker",{taskId:record.taskId,exe,args:fullArgs});const{child}=spawnOwned(exe,fullArgs,{marker:TASK_WORKER_MARKER,detached:true,stdio:"ignore",env:{...process.env,[RUN_TASK_ENV_VAR]:record.taskId}});child.on("error",err=>{this.deps.logger?.error("[CliTaskRunner] worker spawn failed",{taskId:record.taskId,exe,error:err instanceof Error?err.message:String(err)});void this.markBootstrapFailure(record,err instanceof Error?err.message:String(err))});child.unref();if(typeof child.pid!=="number"){const reason="spawn produced no PID";this.deps.logger?.error("[CliTaskRunner] worker spawn failed",{taskId:record.taskId,reason});await this.markBootstrapFailure(record,reason);return}await this.deps.store.update(record.taskId,record.sessionId,{executor:{host:"cli",pid:child.pid,spawnedAt:new Date().toISOString(),hostname:getHostname2()}})}async markBootstrapFailure(record,reason){try{const failed=await this.deps.store.update(record.taskId,record.sessionId,{status:"failed",statusMessage:`Task runner failed to start worker: ${reason}`,outcome:{kind:"error",error:{code:-32603,message:reason}}});if(failed){try{await this.deps.store.publishTerminal(failed)}catch{}}}catch(err){this.deps.logger?.warn?.("[CliTaskRunner] bootstrap-failure bookkeeping write failed",{taskId:record.taskId,error:err instanceof Error?err.message:String(err)})}}async cancel(record){const executor=record.executor;const pid=executor?.pid;if(executor&&!isLocalWorker(executor)){this.deps.logger?.debug?.("[CliTaskRunner] cancel: the worker runs on another host; not signalling it",{taskId:record.taskId,pid,hostname:executor.hostname});return}if(!pid||!isAlive(pid)){this.deps.logger?.debug?.("[CliTaskRunner] cancel: worker already dead",{taskId:record.taskId,pid});return}try{process.kill(pid,"SIGTERM");this.deps.logger?.info("[CliTaskRunner] sent SIGTERM to worker",{taskId:record.taskId,pid})}catch(err){const code=err?.code;if(code!=="ESRCH"){this.deps.logger?.warn("[CliTaskRunner] failed to SIGTERM worker",{taskId:record.taskId,pid,error:err instanceof Error?err.message:String(err)})}}}resolveCommand(){const explicit=this.deps.command;if(explicit)return{exe:explicit.exe,args:[...explicit.args??[]]};const exe=process.argv[0]??"node";const entry=process.argv[1];if(!entry){throw new Error("[CliTaskRunner] cannot resolve worker command: process.argv[1] is empty and no `tasks.cliRunnerCommand` override was set")}if(/\.(ts|tsx|mts|cts)$/i.test(entry)){return{exe:"npx",args:["tsx",entry]}}return{exe,args:[entry]}}}}});import{getRuntimeContext as getRuntimeContext13,spawnOwned as spawnOwned2}from"@frontmcp/utils";function runnerOf(job,serverRunner){return job.metadata.runner??serverRunner??"inline"}function assertRunnersAvailable(jobs,serverRunner,runtime=getRuntimeContext13()){for(const job of jobs){if(runnerOf(job,serverRunner)!=="detached")continue;if(runtime.runtime!=="node"){throw new JobRunnerUnavailableError(job.name,`a detached run needs a process of its own, which the ${runtime.runtime} runtime cannot start`,INLINE_REMEDY)}if(runtime.deployment==="serverless"){throw new JobRunnerUnavailableError(job.name,"a detached run must outlive the server, which a serverless deployment stops or replaces after each request",INLINE_REMEDY)}if(job.metadata.permissions?.some(rule=>rule.action==="execute")){throw new JobRunnerUnavailableError(job.name,"its execute permissions are checked on every attempt, and a detached process never receives the caller credentials","Set runner: 'inline' or 'worker' on the job, or drop its execute permissions")}}}function detachedRunnerCommand(){const[,entry,...args]=process.argv;if(!entry){throw new JobRunnerUnavailableError("detached","the server process has no entry a detached runner can run again","Start the server from its entry (node dist/main.js, frontmcp dev) to run jobs detached")}const ownArgs=args.filter(arg=>!arg.startsWith(OWNER_ARG_PREFIX));const flags=process.execArgv.filter(flag=>!INSPECTOR_FLAG.test(flag));return{command:process.execPath,args:[...flags,entry,...ownArgs]}}function spawnDetachedRunner(runId){const{command,args}=detachedRunnerCommand();const env={...process.env,[RUN_JOB_ENV_VAR]:runId};delete env[RUN_TASK_ENV_VAR];const{child}=spawnOwned2(command,args,{marker:JOB_WORKER_MARKER,detached:true,stdio:"ignore",windowsHide:true,env});child.unref();return child}var OWNER_ARG_PREFIX,INSPECTOR_FLAG,INLINE_REMEDY;var init_job_runner=__esm({"libs/sdk/src/job/runner/job-runner.ts"(){"use strict";init_errors();init_detached_job_flag();init_cli_task_runner();OWNER_ARG_PREFIX="--frontmcp-owner=";INSPECTOR_FLAG=/^--inspect(-brk|-wait)?(=|$)/;INLINE_REMEDY="Set runner: 'inline' (or 'worker') on the job, or run the server where it can start processes"}});var RUNNER_HEARTBEAT_MS,RUNNER_HEARTBEAT_TTL_SECONDS,LatestValueFlusher,RunnerHeartbeat;var init_run_flusher=__esm({"libs/sdk/src/job/runner/run-flusher.ts"(){"use strict";RUNNER_HEARTBEAT_MS=1e3;RUNNER_HEARTBEAT_TTL_SECONDS=30;LatestValueFlusher=class{constructor(write,everyMs,onError=()=>void 0){this.write=write;this.onError=onError;this.timer=setInterval(()=>void this.tick(),everyMs);this.timer.unref?.()}write;onError;pending;inFlight;timer;stopped=false;push(value){if(!this.stopped)this.pending={value}}async flush(){await this.inFlight;await this.tick()}stop(){this.stopped=true;this.pending=void 0;clearInterval(this.timer)}async tick(){if(this.inFlight||!this.pending)return;const{value}=this.pending;this.pending=void 0;this.inFlight=this.write(value).catch(error=>{this.pending??={value};this.onError(error)});try{await this.inFlight}finally{this.inFlight=void 0}}};RunnerHeartbeat=class{constructor(store,runnerId,onError=()=>void 0){this.store=store;this.runnerId=runnerId;this.onError=onError}store;runnerId;onError;holders=0;timer;async hold(){this.holders++;if(this.holders===1&&this.store.touchRunner){this.timer=setInterval(()=>void this.beat(),RUNNER_HEARTBEAT_MS);this.timer.unref?.();await this.beat()}let released=false;return()=>{if(released)return;released=true;this.holders--;if(this.holders===0)clearInterval(this.timer)}}async beat(){try{await this.store.touchRunner?.(this.runnerId,RUNNER_HEARTBEAT_TTL_SECONDS)}catch(error){this.onError(error)}}}}});var FINISHED_JOB_STATES;var init_job_state_interface=__esm({"libs/sdk/src/job/store/job-state.interface.ts"(){"use strict";FINISHED_JOB_STATES=new Set(["completed","failed","cancelled","timed_out","interrupted"])}});import{getHostname as getHostname3,randomUUID as randomUUID16,runRequestExclusive as runRequestExclusive3}from"@frontmcp/utils";function withBackgroundContext(opts,scopeId){if(opts.context)return{...opts,context:detachedRunContext(opts.context)};const sessionFromAuth=opts.authInfo?.["sessionId"];const sessionId=opts.sessionId??(typeof sessionFromAuth==="string"&&sessionFromAuth?sessionFromAuth:void 0);const context=new FrontMcpContext({sessionId:sessionId??`anon:${randomUUID16()}`,scopeId,authInfo:opts.authInfo});return{...opts,context}}function currentPid(){return typeof process==="undefined"?0:process.pid}function cancelledUpdate(reason){return{state:"cancelled",error:{message:reason.message,name:reason.name},completedAt:Date.now()}}function finishedStateOf(error){if(error instanceof JobCancelledError)return"cancelled";if(error instanceof JobInterruptedError)return"interrupted";if(error instanceof JobTimeoutError)return"timed_out";return"failed"}var DEFAULT_JOB_TIMEOUT_MS,DETACHED_FLUSH_MS,DETACHED_BOOT_TTL_SECONDS,DETACHED_WATCH_MS,JobExecutionManager,RunRecorder;var init_job_execution_manager=__esm({"libs/sdk/src/job/execution/job-execution.manager.ts"(){"use strict";init_principal_utils();init_context();init_errors();init_provider_lifecycle();init_process_liveness();init_workflow_engine();init_job_attempt();init_job_context_providers();init_job_permission_guard();init_job_run_access();init_job_runner();init_run_flusher();init_job_state_interface();DEFAULT_JOB_TIMEOUT_MS=3e5;DETACHED_FLUSH_MS=500;DETACHED_BOOT_TTL_SECONDS=60;DETACHED_WATCH_MS=1e3;JobExecutionManager=class{stateStore;logger;notifyFn;scope;options;activeRuns=new Map;runWrites=new Map;heartbeat;watchers=new Map;progressFlushers=new Map;constructor(stateStore,logger,notifyFn,scope,options={}){this.stateStore=stateStore;this.logger=logger;this.notifyFn=notifyFn;this.scope=scope;this.options=options;this.heartbeat=new RunnerHeartbeat(stateStore,randomUUID16(),error=>this.logger.warn(`Could not renew this server's job heartbeat: ${toJobError(error).message}`))}async executeJob(job,input,opts={}){await this.assertMayExecute(job.metadata.permissions,job.name,opts);const runId=randomUUID16();const retryConfig=job.metadata.retry??{};const maxAttempts=retryConfig.maxAttempts??1;const runner=runnerOf(job,this.options.runner);const runRecord={runId,jobId:job.metadata.id??job.name,jobName:job.name,sessionId:opts.sessionId,ownerSub:resolvePrincipal(opts.authInfo,opts.authoritiesContextBuilder).sub||void 0,state:"pending",input,startedAt:Date.now(),attempt:1,maxAttempts,logs:[],background:runner==="detached"||(opts.background??false),scopeId:this.scope?.id};if(runner==="detached")return this.startDetached(job,runRecord);const release=await this.heartbeat.hold();try{await this.stateStore.createRun({...runRecord,runner:this.ownRunner(runner)})}catch(error){release();throw error}if(opts.background){const runOpts=withBackgroundContext(opts,(this.scope??job.providers.getActiveScope()).id);void runRequestExclusive3(()=>this.executeJobBackground(job,input,runId,runOpts)).catch(async err=>{this.logger.error(`Background job execution failed: ${err}`);try{await this.updateState(runId,{state:"failed",error:{message:err?.message??String(err),name:err?.name??"Error"},completedAt:Date.now()})}catch(updateErr){this.logger.error(`Failed to update run state after error: ${updateErr}`)}}).finally(release);return{runId,state:"pending"}}try{return await this.executeJobInline(job,input,runId,opts)}finally{release()}}async executeWorkflow(workflow,jobRegistry,opts={}){await this.assertMayExecute(workflow.metadata.permissions,workflow.name,opts);const runId=randomUUID16();const runRecord={runId,jobId:workflow.metadata.id??workflow.name,jobName:workflow.name,workflowName:workflow.name,sessionId:opts.sessionId,ownerSub:resolvePrincipal(opts.authInfo,opts.authoritiesContextBuilder).sub||void 0,state:"pending",input:opts.workflowInput,startedAt:Date.now(),attempt:1,maxAttempts:1,logs:[],background:opts.background??false,stepResults:{}};await this.stateStore.createRun(runRecord);if(opts.background){const runOpts=withBackgroundContext(opts,(this.scope??workflow.providers.getActiveScope()).id);runRequestExclusive3(()=>this.executeWorkflowBackground(workflow,jobRegistry,runId,runOpts)).catch(async err=>{this.logger.error(`Background workflow execution failed: ${err}`);try{await this.updateState(runId,{state:"failed",error:{message:err?.message??String(err),name:err?.name??"Error"},completedAt:Date.now()})}catch(updateErr){this.logger.error(`Failed to update run state after error: ${updateErr}`)}});return{runId,state:"pending"}}return this.executeWorkflowInline(workflow,jobRegistry,runId,opts)}async assertMayExecute(permissions,name51,opts){const allowed=await JobPermissionGuard.check(permissions,"execute",opts.authInfo,opts.authoritiesContextBuilder);if(!allowed){this.logger.warn(`Execution of "${name51}" denied: caller does not satisfy its execute permissions`);throw new JobNotAuthorizedError(name51)}}async getStatus(runId){return this.stateStore.getRun(runId)}async cancel(runId){const reason=new JobCancelledError(runId);await this.withRunLock(runId,async()=>{const record=await this.stateStore.getRun(runId);if(!record)throw new JobRunNotFoundError(runId);if("workflowName"in record)throw new JobRunNotCancellableError(runId);if(FINISHED_JOB_STATES.has(record.state))throw new JobRunFinishedError(runId,record.state);await this.stateStore.requestCancel?.(runId);await this.write(runId,cancelledUpdate(reason))});this.activeRuns.get(runId)?.controller.abort(reason)}async dispose(timeoutMs){for(const watch of this.watchers.values())clearInterval(watch);this.watchers.clear();const runs=[...this.activeRuns.entries()];for(const[runId,run]of runs)run.controller.abort(new JobInterruptedError(runId));const ended=()=>Promise.all(runs.map(([,run])=>run.settled));if(timeoutMs===void 0){await ended()}else if(await outlasts(ended,timeoutMs)){this.logger.warn(`The interrupted job runs did not end within ${timeoutMs} ms`)}}async reconcile(){for(const record of await this.stateStore.listRuns()){if(FINISHED_JOB_STATES.has(record.state)||!record.runner)continue;if(this.scope&&record.scopeId!==void 0&&record.scopeId!==this.scope.id)continue;if(await this.runnerGone(record.runner,record.startedAt))await this.endOrphan(record);else if(record.runner.kind==="detached")this.watch(record.runId)}}async runDetached(runId){const record=await this.stateStore.getRun(runId);if(!record?.runner||FINISHED_JOB_STATES.has(record.state))return;const job=this.options.findJob?.(record.jobName);if(!job){await this.failToBoot(record,`the server has no job named "${record.jobName}"`);return}const warn=error=>this.logger.warn(`Detached run ${runId}: ${toJobError(error).message}`);const release=await new RunnerHeartbeat(this.stateStore,record.runner.id,warn).hold();const flusher=new LatestValueFlusher(progress=>this.updateState(runId,{progress}),DETACHED_FLUSH_MS,warn);this.progressFlushers.set(runId,flusher);try{await this.updateState(runId,{runner:{...record.runner,pid:currentPid(),hostname:getHostname3()}});const scopeId=this.scope?.id??job.providers.getActiveScope().id;const opts=withBackgroundContext({sessionId:record.sessionId,authInfo:{}},scopeId);await this.executeJobInline(job,record.input,runId,opts).catch(()=>void 0)}finally{flusher.stop();this.progressFlushers.delete(runId);release()}}async listRuns(opts){return this.stateStore.listRuns(opts)}async startDetached(job,record){const unavailable=this.options.detachedUnavailable;if(unavailable)throw new JobRunnerUnavailableError(job.name,unavailable.why,unavailable.remedy);const runner={kind:"detached",id:randomUUID16(),pid:0,hostname:getHostname3()};await this.stateStore.touchRunner?.(runner.id,DETACHED_BOOT_TTL_SECONDS);const child=(this.options.spawnDetached??spawnDetachedRunner)(record.runId);const created=this.stateStore.createRun({...record,runner:{...runner,pid:child.pid??0}});child.once("error",error=>{void created.then(()=>this.failToBoot(record,error.message),()=>void 0)});await created;this.watch(record.runId);return{runId:record.runId,state:"pending"}}watch(runId){if(this.watchers.has(runId))return;let revision;let reading=false;const timer=setInterval(async()=>{if(reading)return;reading=true;try{const record=await this.stateStore.getRun(runId);if(record&&record.revision!==revision){revision=record.revision;this.scope?.resources.notifyContentChanged(jobRunUri(runId))}if(!record||FINISHED_JOB_STATES.has(record.state)){this.unwatch(runId);if(record)await this.notify({type:"job:status",runId,state:record.state,jobName:record.jobName})}else if(record.runner&&await this.runnerGone(record.runner,record.startedAt)){this.unwatch(runId);await this.endOrphan(record)}}catch(error){this.logger.warn(`Could not read detached run ${runId}: ${toJobError(error).message}`)}finally{reading=false}},DETACHED_WATCH_MS);timer.unref?.();this.watchers.set(runId,timer)}unwatch(runId){clearInterval(this.watchers.get(runId));this.watchers.delete(runId)}async runnerGone(runner,startedAt){if(runner.hostname!==void 0&&runner.hostname===getHostname3()){return runner.pid===currentPid()?startedAt<performance.timeOrigin:!isAlive(runner.pid)}if(!this.stateStore.isRunnerAlive)return false;return!await this.stateStore.isRunnerAlive(runner.id)}async endOrphan(listed){const{runId}=listed;if(this.stateStore.claimRun&&!await this.stateStore.claimRun(runId))return;const record=await this.stateStore.getRun(runId)??listed;const neverStarted=record.state==="pending"&&record.runner?.kind==="detached";const error=neverStarted?new JobRunnerBootError(runId,"its process exited before it took the run over"):new JobInterruptedError(runId,"its runner is gone");const state=await this.endRun(record,error);if(state&&record.state==="running"){await this.cleanupOrphan(record,state==="cancelled"?"cancel":"interrupt")}}async endRun(record,error){const{runId}=record;const state=await this.withRunLock(runId,async()=>{const current=await this.stateStore.getRun(runId);if(!current||FINISHED_JOB_STATES.has(current.state))return void 0;return this.writeOutcome(runId,{state:"failed",attempt:current.attempt,error})});if(!state)return void 0;this.unwatch(runId);await this.notify({type:"job:status",runId,state,jobName:record.jobName});return state}async cleanupOrphan(record,reason){const job=this.options.findJob?.(record.jobName);if(!job?.metadata.cleanup)return;try{const scopeId=this.scope?.id??job.providers.getActiveScope().id;const{context}=withBackgroundContext({sessionId:record.sessionId,authInfo:{}},scopeId);const contextProviders=context?await jobContextProviders(job,context):void 0;const instance=job.create(job.parseInput(record.input),{authInfo:{},contextProviders,attempt:record.attempt});await runJobCleanup(job,instance,reason,this.logger)}catch(error){this.logger.warn(`The ${reason} cleanup of run ${record.runId} could not run: ${toJobError(error).message}`)}}async failToBoot(record,cause){try{await this.endRun(record,new JobRunnerBootError(record.runId,cause))}catch(error){this.logger.error(`Could not record that run ${record.runId} did not start: ${toJobError(error).message}`)}}ownRunner(kind){return{kind,id:this.heartbeat.runnerId,pid:currentPid(),hostname:getHostname3()}}async executeJobInline(job,input,runId,opts){const{signal,end}=this.startRun(runId);try{return await this.runJobAttempts(job,input,runId,opts,signal)}finally{end()}}startRun(runId){const controller=new AbortController;let settle=()=>void 0;const settled=new Promise(resolve4=>settle=resolve4);const{cancelPollMs}=this.options;const watch=cancelPollMs?setInterval(()=>void this.abortIfEnded(runId,controller),cancelPollMs):void 0;watch?.unref?.();this.activeRuns.set(runId,{controller,settled});const end=()=>{clearInterval(watch);this.activeRuns.delete(runId);settle()};return{signal:controller.signal,end}}async abortIfEnded(runId,controller){try{if(await this.cancelRequested(runId)){controller.abort(new JobCancelledError(runId))}else if(FINISHED_JOB_STATES.has((await this.stateStore.getRun(runId))?.state??"pending")){controller.abort(new JobInterruptedError(runId,"another process ended it"))}}catch(error){this.logger.warn(`Could not read whether run ${runId} was cancelled or ended: ${toJobError(error).message}`)}}async runJobAttempts(job,input,runId,opts,signal){const started=await this.withRunLock(runId,async()=>{if(await this.cancelRequested(runId))return false;await this.write(runId,{state:"running"});return true});if(!started){await this.notify({type:"job:status",runId,state:"cancelled",jobName:job.name});throw new JobCancelledError(runId)}await this.notify({type:"job:status",runId,state:"running",jobName:job.name});const retryConfig=job.metadata.retry??{};const maxAttempts=retryConfig.maxAttempts??1;const timeoutMs=job.metadata.timeout??this.options.defaultTimeoutMs??DEFAULT_JOB_TIMEOUT_MS;const run=new RunRecorder(runId,maxAttempts,outcome=>this.recordAttempt(job,runId,outcome),progress=>this.recordProgress(runId,progress));for(let attempt=1;;attempt++){let answer;try{answer=await runJobAttemptFlow({job,input,attempt,authInfo:opts.authInfo??{},context:opts.context,contextProviders:opts.contextProviders,authoritiesContextBuilder:opts.authoritiesContextBuilder,run,signal,timeoutMs,admission:this.options.admission})}catch(err){const error=toJobError(err);const retry=willRetryJobAttempt(error,attempt,maxAttempts);await run.ensureRecorded({state:retry?"retrying":"failed",attempt,error});if(!retry)throw error;try{await abortableDelay(retryDelayMs(retryConfig,attempt),signal)}catch(stopped){const stoppedError=toJobError(stopped);await run.recordAttempt({state:"failed",attempt,error:stoppedError});throw stoppedError}continue}const{result,logs}=answer;await run.ensureRecorded({state:"completed",attempt,result,logs});return{runId,result,state:"completed",logs:[...logs]}}}async recordProgress(runId,progress){const flusher=this.progressFlushers.get(runId);if(flusher)flusher.push(progress);else await this.updateState(runId,{progress})}async recordAttempt(job,runId,outcome){await this.progressFlushers.get(runId)?.flush();const state=await this.withRunLock(runId,()=>this.writeOutcome(runId,outcome));if(!state)return;const attempt=state==="retrying"?{attempt:outcome.attempt}:{};await this.notify({type:"job:status",runId,state,jobName:job.name,...attempt})}async writeOutcome(runId,outcome){if(await this.cancelRequested(runId)){if(outcome.state==="retrying")return void 0;await this.write(runId,{...cancelledUpdate(new JobCancelledError(runId)),attempt:outcome.attempt});return"cancelled"}const current=await this.stateStore.getRun(runId);if(current&&FINISHED_JOB_STATES.has(current.state))return void 0;switch(outcome.state){case"completed":await this.write(runId,{state:"completed",result:outcome.result,completedAt:Date.now(),attempt:outcome.attempt,logs:[...outcome.logs]});return"completed";case"retrying":await this.write(runId,{state:"retrying",attempt:outcome.attempt});return"retrying";case"failed":{const{error}=outcome;const state=finishedStateOf(error);await this.write(runId,{state,error:{message:error.message,name:error.name,stack:error.stack},completedAt:Date.now(),attempt:outcome.attempt});return state}}}async executeJobBackground(job,input,runId,opts){try{await this.executeJobInline(job,input,runId,opts)}catch{}}async executeWorkflowInline(workflow,jobRegistry,runId,opts){await this.updateState(runId,{state:"running"});await this.notify({type:"workflow:status",runId,state:"running",workflowName:workflow.name});try{const engine=new WorkflowEngine(workflow.metadata,jobRegistry,this.logger,{authInfo:opts.authInfo??{},contextProviders:opts.contextProviders,context:opts.context,authoritiesContextBuilder:opts.authoritiesContextBuilder,workflowRunId:runId,admission:this.options.admission,defaultTimeoutMs:this.options.defaultTimeoutMs});const result=await engine.execute(opts.workflowInput);await this.updateState(runId,{state:result.state==="completed"?"completed":"failed",result,completedAt:Date.now()});await this.notify({type:"workflow:status",runId,state:result.state==="completed"?"completed":"failed",workflowName:workflow.name});return{runId,result,state:result.state==="completed"?"completed":"failed",logs:[]}}catch(err){const error=err instanceof Error?err:new Error(String(err));await this.updateState(runId,{state:"failed",error:{message:error.message,name:error.name,stack:error.stack},completedAt:Date.now()});await this.notify({type:"workflow:status",runId,state:"failed",workflowName:workflow.name});throw error}}async executeWorkflowBackground(workflow,jobRegistry,runId,opts){try{await this.executeWorkflowInline(workflow,jobRegistry,runId,opts)}catch{}}updateState(runId,updates){return this.withRunLock(runId,()=>this.write(runId,updates))}async write(runId,updates){await this.stateStore.updateRun(runId,updates);this.scope?.resources.notifyContentChanged(jobRunUri(runId))}withRunLock(runId,task){const queued=(this.runWrites.get(runId)??Promise.resolve()).then(task);const done=queued.catch(()=>void 0);this.runWrites.set(runId,done);void done.then(()=>{if(this.runWrites.get(runId)===done)this.runWrites.delete(runId)});return queued}async cancelRequested(runId){if(this.stateStore.isCancelRequested)return this.stateStore.isCancelRequested(runId);return(await this.stateStore.getRun(runId))?.state==="cancelled"}async notify(data){if(this.notifyFn){try{await this.notifyFn(data)}catch(err){this.logger.warn(`Failed to send notification: ${err}`)}}}};RunRecorder=class{constructor(runId,maxAttempts,write,writeProgress){this.runId=runId;this.maxAttempts=maxAttempts;this.write=write;this.writeProgress=writeProgress}runId;maxAttempts;write;writeProgress;recorded=new Set;finished=false;async recordProgress(progress){if(!this.finished)await this.writeProgress(progress)}async recordAttempt(outcome){if(outcome.state!=="retrying")this.finished=true;await this.write(outcome);this.recorded.add(outcome.attempt)}async ensureRecorded(outcome){if(!this.recorded.has(outcome.attempt))await this.recordAttempt(outcome)}}}});import{toJSONSchema as toJSONSchema4,internalZ as z78}from"@frontmcp/lazy-zod";var JobEntry;var init_job_entry=__esm({"libs/sdk/src/common/entries/job.entry.ts"(){"use strict";init_base_entry();JobEntry=class extends BaseEntry{owner;name;fullName;inputSchema;outputSchema;isDynamic(){return this.record.kind==="DYNAMIC"}isHidden(){return this.metadata.hideFromDiscovery===true}getTags(){return this.metadata.tags??[]}getLabels(){return this.metadata.labels??{}}getInputJsonSchema(){if(this.inputSchema&&Object.keys(this.inputSchema).length>0){try{return toJSONSchema4(z78.object(this.inputSchema))}catch{return{type:"object",properties:{}}}}return null}getOutputJsonSchema(){const outSchema=this.outputSchema;if(!outSchema)return null;try{if(outSchema instanceof z78.ZodType){return toJSONSchema4(outSchema)}if(outSchema&&typeof outSchema==="object"){if(Object.keys(outSchema).length===0)return null;return toJSONSchema4(z78.object(outSchema))}}catch{return{type:"object",properties:{}}}return null}}}});var JobContext;var init_job_interface=__esm({"libs/sdk/src/common/interfaces/job.interface.ts"(){"use strict";init_execution_context_interface();init_flow_interface();JobContext=class extends ExecutionContextBase{jobId;jobName;metadata;_input;_output;_attempt;_logs=[];onProgress;constructor(args){const{metadata,input,providers,logger,attempt,signal,onProgress}=args;super({providers,logger:logger.child(`job:${metadata.id??metadata.name}`),authInfo:args.authInfo,signal});this.jobName=metadata.name;this.jobId=metadata.id??metadata.name;this.metadata=metadata;this._input=input;this._attempt=attempt;this.onProgress=onProgress}fetch(input,init){const context=this.fetchContext(init);if(context&&this.signal)return context.fetch(input,init,this.signal);return super.fetch(input,init)}get input(){return this._input}get output(){return this._output}set output(v){this._output=v}get attempt(){return this._attempt}log(message){this._logs.push(`[${new Date().toISOString()}] ${message}`);this.logger.info(message)}async progress(pct,total,msg){const recorded=this.onProgress?await this.recordProgress({progress:pct,total,message:msg}):false;const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.debug("Cannot send progress: no session ID");return recorded}const sent=await this.scope.notifications.sendProgressNotification(sessionId,this.jobId,pct,total,msg);return sent||recorded}async recordProgress(progress){try{await this.onProgress?.(progress);return true}catch(error){this.logger.warn(`Could not record progress on the run: ${error instanceof Error?error.message:String(error)}`);return false}}respond(value){this._output=value;FlowControl.respond(value)}getLogs(){return this._logs}keepLogs(lines){this._logs.push(...lines)}callToolSurface(){return"job"}}}});var worker_job_runner_exports={};__export(worker_job_runner_exports,{runWorkerJob:()=>runWorkerJob});import{isClass as isClass12}from"@frontmcp/di";async function runWorkerJob(target,metadata,input,attempt,log,progress){const args={metadata,input,attempt,providers:new WorkerProviders(`job "${metadata.name}" runs in a worker thread (runner: 'worker')`),logger:workerLogger(log),authInfo:{},onProgress:async reported=>progress(reported)};const context=isClass12(target)?new target(args):new WorkerFunctionJobContext(target,args);try{return{output:await context.execute(input),logs:[...context.getLogs()]}}catch(error){if(!(error instanceof FlowControl))throw error;if(error.type==="respond")return{output:error.output,logs:[...context.getLogs()]};const original=Reflect.get(error,"originalError");throw original??new Error(`The job ended with ${error.type}`)}}var WorkerFunctionJobContext;var init_worker_job_runner=__esm({"libs/sdk/src/offload/worker-job.runner.ts"(){"use strict";init_flow_interface();init_job_interface();init_worker_resource_reader();WorkerFunctionJobContext=class extends JobContext{constructor(handler,args){super(args);this.handler=handler}handler;async execute(input){return this.handler(input,this)}}}});function registerWorkerJob(target,metadata,file){const key=workerJobKey(file??"",metadata.name);sources2.set(target,{file,name:metadata.name,key});if(!file)return;workerJobRunners().set(key,{run:async(input,attempt,log,progress)=>{const{runWorkerJob:runWorkerJob2}=await Promise.resolve().then(()=>(init_worker_job_runner(),worker_job_runner_exports));return runWorkerJob2(target,metadata,input,attempt,log,progress)}})}function workerJobSourceOf(target){return typeof target==="function"?sources2.get(target):void 0}var sources2;var init_worker_jobs=__esm({"libs/sdk/src/offload/worker-jobs.ts"(){"use strict";init_offload_worker_globals();sources2=new WeakMap}});var run_job_in_worker_exports={};__export(run_job_in_worker_exports,{runJobInWorker:()=>runJobInWorker});async function runJobInWorker(jobContext,job,input,signal){const name51=job.metadata.name;const source=workerJobSourceOf(job.record.provide);if(!source?.file){throw new InvalidOffloadCallError(`job "${name51}" runs on the worker runner, but the module that declares it was not found on the call stack, so no worker can import it (a bundle that inlines @frontmcp/sdk has no separate module to import)`)}const progress=new LatestValueFlusher(async reported=>{await jobContext.progress(reported.progress,reported.total,reported.message)},PROGRESS_FLUSH_MS);try{const answer=await jobContext.get(OffloadService).run({kind:"job",file:source.file,key:source.key,name:source.name,input,attempt:jobContext.attempt},{label:name51,budgetMs:MAX_TIMER_MS2,signal,logger:jobContext.scope.logger.child(`job:${name51}`),onProgress:reported=>progress.push(reported)});await progress.flush();jobContext.keepLogs(answer.logs);return answer.output}finally{progress.stop()}}var MAX_TIMER_MS2,PROGRESS_FLUSH_MS;var init_run_job_in_worker=__esm({"libs/sdk/src/offload/run-job-in-worker.ts"(){"use strict";init_offload_errors();init_run_flusher();init_offload_service();init_worker_jobs();MAX_TIMER_MS2=2147483647;PROGRESS_FLUSH_MS=500}});import{internalZ as z79}from"@frontmcp/lazy-zod";function jobOf(rawInput){const job=rawInput?.job;return job instanceof JobEntry?job:void 0}function abortControllerFollowing(signal){const controller=new AbortController;if(signal?.aborted)controller.abort(signal.reason);signal?.addEventListener("abort",()=>controller.abort(signal.reason),{once:true});return controller}function progressUntilAborted(run,signal){const record=run?.recordProgress?.bind(run);if(!record)return void 0;return async progress=>{if(!signal.aborted)await record(progress)}}var jobEntrySchema,workflowStepSchema2,inputSchema10,outputSchema10,stateSchema10,plan10,name10,jobClassHooksJoin,Stage10,ExecuteJobFlow;var init_execute_job_flow=__esm({"libs/sdk/src/job/flows/execute-job.flow.ts"(){"use strict";init_common();init_job_entry();init_job_interface();init_call_surface();init_errors();init_entry_class_hooks();init_hooks_utils();init_job_attempt();init_job_context_providers();init_job_permission_guard();init_job_runner();jobEntrySchema=z79.custom(value=>value instanceof JobEntry,{message:"Expected a job entry"});workflowStepSchema2=z79.object({name:z79.string().optional(),stepId:z79.string(),runId:z79.string().optional()});inputSchema10=z79.object({job:jobEntrySchema,input:z79.unknown(),attempt:z79.number().int().min(1),ctx:z79.object({authInfo:z79.record(z79.string(),z79.unknown()),contextProviders:z79.unknown().optional(),authoritiesContextBuilder:z79.custom().optional(),run:z79.custom().optional(),workflow:workflowStepSchema2.optional(),signal:z79.instanceof(AbortSignal).optional(),timeoutMs:z79.number().int().nonnegative().optional(),admission:z79.custom().optional()})});outputSchema10=z79.object({result:z79.unknown(),logs:z79.array(z79.string())});stateSchema10=z79.object({job:jobEntrySchema,attempt:z79.number(),runId:z79.string().optional(),workflow:workflowStepSchema2.optional(),authInfo:z79.record(z79.string(),z79.unknown()),input:z79.unknown(),parsedInput:z79.custom(),jobContext:z79.instanceof(JobContext),attemptAbort:z79.instanceof(AbortController),output:z79.custom(),answer:outputSchema10,flowError:z79.instanceof(Error)});plan10={pre:["parseInput","checkJobAuthorization","validateInput","admit","createJobContext"],execute:["execute","validateOutput"],error:["cleanup"],finalize:["updateRunState","finalize"]};name10=EXECUTE_JOB_FLOW;jobClassHooksJoin=entryClassHooksJoin({flow:name10,plan:plan10,contextStage:"createJobContext"});({Stage:Stage10}=FlowHooksOf(name10));ExecuteJobFlow=class extends FlowBase{static resolveHookOwnerId(rawInput,scope){const job=jobOf(rawInput);if(!job)return void 0;return scope.apps.getApps().find(app=>app.providers===job.providers)?.id}static resolveHookEntryClass(rawInput){return jobOf(rawInput)?.record.provide}logger=this.scopeLogger.child("ExecuteJobFlow");async parseInput(){const{job,input,attempt,ctx}=this.input;this.state.set({job,input,attempt,runId:ctx.run?.runId,workflow:ctx.workflow,authInfo:ctx.authInfo});this.logger=this.logger.child(`ExecuteJobFlow(${job.name})`);this.logger.verbose(`parseInput: attempt ${attempt}`)}async checkJobAuthorization(){const{job}=this.state.required;const allowed=await JobPermissionGuard.check(job.metadata.permissions,"execute",this.state.authInfo,this.input.ctx.authoritiesContextBuilder);if(!allowed){this.logger.warn(`checkJobAuthorization: caller does not satisfy the execute permissions of "${job.name}"`);throw new JobNotAuthorizedError(job.name)}}async validateInput(){const{job}=this.state.required;this.state.set("parsedInput",job.parseInput(this.state.input))}async admit(){const{job}=this.state.required;await this.input.ctx.admission?.acquire(job.name,this.input.ctx.signal)}async createJobContext(){const{job,parsedInput}=this.state.required;const{ctx,attempt}=this.input;const contextProviders=ctx.contextProviders??await jobContextProviders(job,this.context);this.throwIfAborted();const attemptAbort=abortControllerFollowing(ctx.signal);this.state.set("attemptAbort",attemptAbort);const jobContext=job.create(parsedInput,{authInfo:this.state.authInfo??{},contextProviders,attempt,signal:attemptAbort.signal,onProgress:progressUntilAborted(ctx.run,attemptAbort.signal)});await jobContext.loadAuthContext();this.throwIfAborted();this.appendContextHooks(hooksBoundTo(this.scope.hooks.getClsHooks(job.record.provide),jobContext));this.state.set("jobContext",jobContext)}async execute(){const{job,jobContext,parsedInput,attemptAbort}=this.state.required;this.throwIfAborted();const timeoutMs=this.input.ctx.timeoutMs;const timer=timeoutMs?setTimeout(()=>attemptAbort.abort(new JobTimeoutError(job.name,timeoutMs)),timeoutMs):void 0;const onWorker=runnerOf(job,this.scope.metadata.jobs?.runner)==="worker";let output;try{output=await untilAborted(runOnSurface("job",async()=>onWorker?(await Promise.resolve().then(()=>(init_run_job_in_worker(),run_job_in_worker_exports))).runJobInWorker(jobContext,job,parsedInput,attemptAbort.signal):jobContext.execute(parsedInput)),attemptAbort.signal)}catch(error){this.throwIfAborted();if(!(error instanceof FlowControl&&error.type==="respond"))throw toJobError(error);output=error.output}finally{clearTimeout(timer)}this.throwIfAborted();this.state.set("output",output)}async validateOutput(){this.throwIfAborted();const{job,jobContext}=this.state.required;const result=job.parseOutput(this.state.output);this.state.set("answer",{result,logs:[...jobContext.getLogs()]})}async cleanup(){const{job,jobContext,attemptAbort}=this.state;if(!job||!jobContext||!attemptAbort?.signal.aborted)return;await runJobCleanup(job,jobContext,interruptReasonOf(attemptAbort.signal.reason),this.logger)}async updateRunState(){const run=this.input.ctx.run;if(!run)return;const{attempt}=this.input;const{flowError,answer}=this.state;let outcome;if(!flowError&&answer){outcome={state:"completed",attempt,result:answer.result,logs:answer.logs}}else{const error=flowError??new InternalMcpError("The job attempt ended before it produced a result");outcome={state:willRetryJobAttempt(error,attempt,run.maxAttempts)?"retrying":"failed",attempt,error}}try{await run.recordAttempt(outcome)}catch(error){this.logger.warn(`updateRunState: could not record attempt ${attempt} as ${outcome.state}: ${toJobError(error).message}`)}}async finalize(){const{flowError,answer}=this.state;if(flowError||!answer)return;this.respond(answer)}respond(output){const answer=output===this.state.answer?output:this.checkedAnswer(output);this.state.set("answer",answer);throw FlowControl.respond(answer)}checkedAnswer(output){const{result,logs}=outputSchema10.parse(output);return{result:this.input.job.parseOutput(result),logs}}throwIfAborted(){const signal=this.state.attemptAbort?.signal??this.input.ctx.signal;if(!signal?.aborted)return;throw signal.reason instanceof Error?signal.reason:new InternalMcpError("The job attempt was abandoned")}};__decorateClass([Stage10("parseInput")],ExecuteJobFlow.prototype,"parseInput",1);__decorateClass([Stage10("checkJobAuthorization")],ExecuteJobFlow.prototype,"checkJobAuthorization",1);__decorateClass([Stage10("validateInput")],ExecuteJobFlow.prototype,"validateInput",1);__decorateClass([Stage10("admit")],ExecuteJobFlow.prototype,"admit",1);__decorateClass([Stage10("createJobContext")],ExecuteJobFlow.prototype,"createJobContext",1);__decorateClass([Stage10("execute")],ExecuteJobFlow.prototype,"execute",1);__decorateClass([Stage10("validateOutput")],ExecuteJobFlow.prototype,"validateOutput",1);__decorateClass([Stage10("cleanup")],ExecuteJobFlow.prototype,"cleanup",1);__decorateClass([Stage10("updateRunState")],ExecuteJobFlow.prototype,"updateRunState",1);__decorateClass([Stage10("finalize")],ExecuteJobFlow.prototype,"finalize",1);ExecuteJobFlow=__decorateClass([FrontMcpFlow({name:name10,plan:plan10,inputSchema:inputSchema10,outputSchema:outputSchema10,access:"authorized"})],ExecuteJobFlow)}});function systemFreeMemoryMb(){if(typeof process!=="undefined"&&typeof process.availableMemory==="function"){return process.availableMemory()/BYTES_PER_MB}const{freemem}=__require("node:os");return freemem()/BYTES_PER_MB}var RECHECK_MS2,BYTES_PER_MB,JobAdmission;var init_job_admission=__esm({"libs/sdk/src/job/job-admission.ts"(){"use strict";init_errors();RECHECK_MS2=250;BYTES_PER_MB=1024*1024;JobAdmission=class{constructor(options,probes={}){this.options=options;this.maxWaitMs=options.maxWaitMs??6e5;this.freeMemoryMb=probes.freeMemoryMb??systemFreeMemoryMb}options;running=0;claimedMb=0;queue=[];listeners=new Set;maxWaitMs;freeMemoryMb;slot(){let release;return{acquire:async(jobName,signal)=>{release=await this.admit(jobName,signal)},release:()=>{release?.();release=void 0}}}async admit(jobName,signal){signal?.throwIfAborted();const deadline=Date.now()+this.maxWaitMs;const ticket={};this.queue.push(ticket);try{while(this.queue[0]!==ticket||!this.fits()){const left=deadline-Date.now();if(left<=0)throw new JobAdmissionTimeoutError(jobName,this.maxWaitMs,this.describeWait());await this.nextChange(Math.min(left,RECHECK_MS2),signal)}return this.claim()}finally{this.queue.splice(this.queue.indexOf(ticket),1);this.wake()}}fits(){const{concurrency,memoryMb}=this.options;if(concurrency!==void 0&&this.running>=concurrency)return false;return memoryMb===void 0||this.freeMemoryMb()-this.claimedMb>=memoryMb}claim(){const claimedMb=this.options.memoryMb??0;this.running++;this.claimedMb+=claimedMb;let held=true;return()=>{if(!held)return;held=false;this.running--;this.claimedMb-=claimedMb;this.wake()}}describeWait(){const{concurrency,memoryMb}=this.options;if(concurrency!==void 0&&this.running>=concurrency){return`${this.running} of ${concurrency} job runs are busy`}const availableMb=Math.max(0,Math.floor(this.freeMemoryMb()-this.claimedMb));return`it needs ${memoryMb} MB free, and ${availableMb} MB is`}nextChange(ms,signal){return new Promise((resolve4,reject)=>{const stopListening=()=>{clearTimeout(timer);this.listeners.delete(changed);signal?.removeEventListener("abort",aborted)};const changed=()=>{stopListening();resolve4()};const aborted=()=>{stopListening();reject(signal?.reason)};const timer=setTimeout(changed,ms);this.listeners.add(changed);signal?.addEventListener("abort",aborted,{once:true})})}wake(){for(const listener of[...this.listeners])listener()}}}});var JobEmitter;var init_job_events=__esm({"libs/sdk/src/job/job.events.ts"(){"use strict";JobEmitter=class{listeners=new Set;on(l){this.listeners.add(l);return()=>this.listeners.delete(l)}emit(e){for(const l of[...this.listeners])l(e)}}}});import{internalZ as z80}from"@frontmcp/lazy-zod";var JobInstance,RequestOverAppProviders,FunctionJobContext;var init_job_instance=__esm({"libs/sdk/src/job/job.instance.ts"(){"use strict";init_job_entry();init_job_interface();init_errors();init_mcp_error();init_entry_class_hooks();init_hooks_utils();init_execute_job_flow();JobInstance=class extends JobEntry{_providers;scope;hooks;constructor(record,providers,owner){super(record);this.owner=owner;this._providers=providers;this.name=record.metadata.id||record.metadata.name;this.fullName=this.owner.id+":"+this.name;this.scope=this._providers.getActiveScope();this.hooks=this.scope.hooks;this.inputSchema=record.metadata.inputSchema??{};this.outputSchema=record.metadata.outputSchema??{};this.ready=this.initialize()}async initialize(){if(this.record.kind==="DYNAMIC"){return}const allHooks=normalizeHooksFromCls(this.record.provide);if(allHooks.length===0)return;const className=this.record.provide?.name??this.name;const invalidHooks=allHooks.filter(hook=>hook.metadata.flow!==jobClassHooksJoin.flow);if(invalidHooks.length>0){const declared=invalidHooks.map(h2=>`${h2.metadata.method}() on ${h2.metadata.flow}`).join(", ");throw new InvalidHookFlowError(`Job "${className}" has hooks for unsupported flows: ${declared}. Only the job flow (${jobClassHooksJoin.flow}) is supported on job classes; hook other flows from a provider or a plugin.`)}const unreachable=describeUnreachableEntryClassHooks(allHooks,jobClassHooksJoin,[]);if(unreachable.length>0){throw new InvalidHookFlowError(unreachableHooksMessage("Job",className,unreachable))}await this.hooks.registerHooks(true,...allHooks)}getMetadata(){return this.record.metadata}get providers(){return this._providers}create(input,extra){const metadata=this.metadata;const providers=extra.contextProviders?new RequestOverAppProviders(extra.contextProviders,this._providers):this._providers;const scope=this._providers.getActiveScope();const logger=scope.logger;const authInfo=extra.authInfo;const jobCtorArgs={metadata,input,providers,logger,authInfo,attempt:extra.attempt??1,signal:extra.signal,onProgress:extra.onProgress};switch(this.record.kind){case"CLASS_TOKEN":return new this.record.provide(jobCtorArgs);case"FUNCTION":return new FunctionJobContext(this.record,jobCtorArgs);case"DYNAMIC":throw new DynamicJobDirectExecutionError(this.name);default:throw new InvalidRegistryKindError("job",this.record.kind)}}parseInput(input){const inputSchema45=z80.object(this.inputSchema);return inputSchema45.parse(input)}parseOutput(raw){const outSchema=this.outputSchema;let schema;if(outSchema instanceof z80.ZodType){schema=outSchema}else if(outSchema&&typeof outSchema==="object"&&Object.keys(outSchema).length>0){schema=z80.object(outSchema)}if(!schema)return raw;const parsed=schema.safeParse(raw);if(parsed.success)return parsed.data;const firstIssue=parsed.error.issues[0];throw new InvalidOutputError({reason:"output does not match outputSchema",path:firstIssue?.path.length?firstIssue.path.join("."):void 0})}safeParseOutput(raw){try{return{success:true,data:this.parseOutput(raw)}}catch(error){return{success:false,error}}}};RequestOverAppProviders=class{constructor(requestProviders,appProviders){this.requestProviders=requestProviders;this.appProviders=appProviders}requestProviders;appProviders;get(token){try{return this.requestProviders.get(token)}catch(error){if(error instanceof ProviderNotAvailableError)return this.appProviders.get(token);throw error}}getScope(){return this.requestProviders.getScope()}getProviders(){return this.requestProviders.getProviders()}getRegistries(type){return this.requestProviders.getRegistries(type)}buildViews(sessionKey,contextProviders,contextSource){return this.requestProviders.buildViews(sessionKey,contextProviders,contextSource)}};FunctionJobContext=class extends JobContext{constructor(record,args){super(args);this.record=record}record;execute(input){return this.record.provide(input,this)}}}});import{depsOfClass as depsOfClass7,depsOfFunc as depsOfFunc4,getMetadata as getMetadata15,isClass as isClass13}from"@frontmcp/di";function collectJobMetadata(cls){const extended=getMetadata15(extendedJobMetadata,cls);const seed=extended?{...extended}:{};return Object.entries(FrontMcpJobTokens).reduce((metadata,[key,token])=>{const value=getMetadata15(token,cls);if(value!==void 0){return Object.assign(metadata,{[key]:value})}else{return metadata}},seed)}function normalizeJob(item){if(isExternalEntryRecord(item)){throw unsupportedExternalEntry("job",item)}const fn=item;if(item&&typeof item==="function"&&fn[FrontMcpJobTokens.type]==="function-job"&&fn[FrontMcpJobTokens.metadata]){return{kind:"FUNCTION",provide:item(),metadata:fn[FrontMcpJobTokens.metadata]}}if(isClass13(item)){const metadata=collectJobMetadata(item);return{kind:"CLASS_TOKEN",provide:item,metadata}}const name51=(item!=null&&typeof item==="object"&&"name"in item?item.name:void 0)??String(item);throw new InvalidEntityError("job",name51,"a class or a job object")}function jobDiscoveryDeps(rec){switch(rec.kind){case"FUNCTION":return depsOfFunc4(rec.provide,"discovery");case"CLASS_TOKEN":return depsOfClass7(rec.provide,"discovery");case"DYNAMIC":case"ESM":case"REMOTE":return[]}}var init_job_utils=__esm({"libs/sdk/src/job/job.utils.ts"(){"use strict";init_job_tokens();init_external_entry_utils();init_errors()}});import{tokenName as tokenName14}from"@frontmcp/di";var JobRegistry;var init_job_registry=__esm({"libs/sdk/src/job/job.registry.ts"(){"use strict";init_logger_interface();init_errors();init_regsitry();init_lineage_utils();init_job_events();init_job_instance();init_job_utils();JobRegistry=class extends RegistryAbstract{owner;localRows=[];dynamicRows=[];byName=new Map;byId=new Map;version=0;emitter=new JobEmitter;logger;entryProviders;constructor(providers,list,owner,entryProviders=new Map){super("JobRegistry",providers,list,false);this.owner=owner;this.entryProviders=entryProviders;try{this.logger=providers.get(FrontMcpLogger)}catch{}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=normalizeJob(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);if(!rec){throw new RegistryDefinitionNotFoundError("JobRegistry",tokenName14(token))}const deps=jobDiscoveryDeps(rec);for(const d of deps){this.providersOf(token).get(d);const edges=this.graph.get(token);if(!edges){throw new RegistryGraphEntryNotFoundError("JobRegistry",tokenName14(token))}edges.add(d)}}}async initialize(){for(const token of this.tokens){const rec=this.defs.get(token);if(!rec){throw new RegistryDefinitionNotFoundError("JobRegistry",tokenName14(token))}const ji=new JobInstance(rec,this.providersOf(token),this.owner);this.instances.set(token,ji);const lineage=this.owner?[this.owner]:[];const row=this.makeRow(token,ji,lineage);this.localRows.push(row)}await Promise.all([...this.instances.values()].map(ji=>ji.ready));this.reindex();this.bump("reset")}providersOf(token){return this.entryProviders.get(token)??this.providers}getJobs(includeHidden=false){const all=[...this.localRows,...this.dynamicRows].map(r=>r.instance);return all.filter(j=>j.metadata.hideFromDiscovery!==true||includeHidden)}findByName(name51){return this.byName.get(name51)?.instance}findById(id){return this.byId.get(id)?.instance}search(query,opts){let jobs=this.getJobs(false);if(query){const q=query.toLowerCase();jobs=jobs.filter(j=>j.name.toLowerCase().includes(q)||(j.metadata.description??"").toLowerCase().includes(q))}if(opts?.tags&&opts.tags.length>0){const filterTags=opts.tags;jobs=jobs.filter(j=>{const tags=j.getTags();return filterTags.some(t=>tags.includes(t))})}if(opts?.labels){const labelEntries=Object.entries(opts.labels);jobs=jobs.filter(j=>{const labels=j.getLabels();return labelEntries.every(([k,v])=>labels[k]===v)})}return jobs}registerDynamic(record){const token=Symbol.for(`job:dynamic:${record.provide}`);const existing=this.dynamicRows.findIndex(r=>r.token===token);if(existing!==-1){this.dynamicRows.splice(existing,1)}const ji=new JobInstance(record,this.providers,this.owner);this.instances.set(token,ji);const lineage=this.owner?[this.owner]:[];const row=this.makeRow(token,ji,lineage);this.dynamicRows.push(row);this.reindex();this.bump("added")}removeDynamic(jobId){const idx=this.dynamicRows.findIndex(r=>r.instance.metadata.id===jobId||r.instance.name===jobId);if(idx===-1)return false;const row=this.dynamicRows[idx];this.dynamicRows.splice(idx,1);this.instances.delete(row.token);this.reindex();this.bump("removed");return true}subscribe(opts,cb){if(opts.immediate){cb({kind:"reset",changeScope:"global",version:this.version,snapshot:this.getJobs()})}return this.emitter.on(cb)}hasAny(){return this.localRows.length>0||this.dynamicRows.length>0}reindex(){this.byName.clear();this.byId.clear();const effective=[...this.localRows,...this.dynamicRows];for(const r of effective){if(this.byName.has(r.baseName)){this.logger?.warn(`JobRegistry: duplicate job name "${r.baseName}" detected during reindex; later entry wins`)}this.byName.set(r.baseName,r);const idKey=r.instance.metadata.id??r.baseName;if(this.byId.has(idKey)){this.logger?.warn(`JobRegistry: duplicate job id "${idKey}" detected during reindex; later entry wins`)}this.byId.set(idKey,r)}}bump(kind){const version=++this.version;this.emitter.emit({kind,changeScope:"global",version,snapshot:this.getJobs()})}makeRow(token,instance,lineage){const ownerKey=ownerKeyOf(lineage);const baseName=instance.name;const qualifiedName=qualifiedNameOf(lineage,baseName);const qualifiedId=`${ownerKey}:${tokenName14(token)}`;return{token,instance,baseName,lineage,ownerKey,qualifiedName,qualifiedId,source:this}}}}});var init_base_interface=__esm({"libs/sdk/src/common/interfaces/base.interface.ts"(){"use strict"}});var init_front_mcp_interface=__esm({"libs/sdk/src/common/interfaces/front-mcp.interface.ts"(){"use strict"}});import{HttpServerResponse,IncomingMessage}from"@frontmcp/protocol";var ServerRequest,ServerResponse,FrontMcpServer;var init_server_interface=__esm({"libs/sdk/src/common/interfaces/server.interface.ts"(){"use strict";ServerRequest=class extends IncomingMessage{path;query;params;body;authSession};ServerResponse=class extends HttpServerResponse{};FrontMcpServer=class{async stop(){return}}}});var init_scope_interface=__esm({"libs/sdk/src/common/interfaces/scope.interface.ts"(){"use strict"}});var init_hook_interface=__esm({"libs/sdk/src/common/interfaces/hook.interface.ts"(){"use strict"}});var init_app_interface=__esm({"libs/sdk/src/common/interfaces/app.interface.ts"(){"use strict"}});function AsyncAuthProvider(cfg){return cfg}var init_auth_provider_interface=__esm({"libs/sdk/src/common/interfaces/auth-provider.interface.ts"(){"use strict"}});var init_adapter_interface=__esm({"libs/sdk/src/common/interfaces/adapter.interface.ts"(){"use strict"}});var init_plugin_interface=__esm({"libs/sdk/src/common/interfaces/plugin.interface.ts"(){"use strict"}});var ToolContext;var init_tool_interface=__esm({"libs/sdk/src/common/interfaces/tool.interface.ts"(){"use strict";init_helpers();init_execution_context_interface();init_flow_interface();ToolContext=class extends ExecutionContextBase{toolId;toolName;metadata;_toolNameInternal;_toolInputInternal;_jsonRpcRequestIdInternal;_rawInput;_input;_outputDraft;_output;_inputHistory=[];_outputHistory=[];_progressToken;constructor(args){const{metadata,input,providers,logger,progressToken,signal}=args;super({providers,logger:logger.child(`tool:${metadata.id??metadata.name}`),authInfo:args.authInfo,signal});this.toolName=metadata.name;this.toolId=metadata.id??metadata.name;this.metadata=metadata;this._input=input;this._progressToken=progressToken}get _progressTokenInternal(){return this._progressToken}fetch(input,init){const context=this.fetchContext(init);if(context&&this.signal)return context.fetch(input,init,this.signal);return super.fetch(input,init)}get input(){return this._input}set input(v){this._input=v;this._inputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get inputHistory(){return this._inputHistory}get output(){return this._output}set output(v){this._output=v;this._outputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get outputHistory(){return this._outputHistory}respond(value){this.output=value;FlowControl.respond(value)}async notify(message,level="info"){const data=typeof message==="string"?{message}:message;const sink=this.tryGetContext()?.getRequestNotificationSink?.();if(sink)return sink.log(level,this.toolName,data);const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.warn("Cannot send notification: no session ID");return false}return this.scope.notifications.sendLogMessageToSession(sessionId,level,this.toolName,data)}async progress(progress,total,message){const sink=this.tryGetContext()?.getRequestNotificationSink?.();if(sink)return sink.progress(progress,total,message);if(!this._progressToken){this.logger.debug("Cannot send progress: no progressToken in request");return false}const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.warn("Cannot send progress: no session ID");return false}return this.scope.notifications.sendProgressNotification(sessionId,this._progressToken,progress,total,message)}notifyResourceUpdated(uri){this.scope.resources.notifyContentChanged(uri)}notifyResourceListChanged(){this.scope.notifications.broadcastNotification("notifications/resources/list_changed")}async elicit(message,requestedSchema,options){return performElicit({sessionId:this.context.sessionId,getClientCapabilities:sid=>this.scope.notifications.getClientCapabilities(sid),tryGetContext:()=>this.tryGetContext(),entryName:this._toolNameInternal??this.toolName,entryInput:this._toolInputInternal??this.input,elicitationEnabled:this.scope.metadata.elicitation?.enabled===true,questions:this.scope.persistentQuestions,signal:this.signal},message,requestedSchema,options)}async sample(options){return performSample(this.tryGetContext(),options)}async listRoots(){return performListRoots(this.tryGetContext())}get platform(){const payloadPlatform=this.authInfo.sessionIdPayload?.platformType;if(payloadPlatform&&payloadPlatform!=="unknown"){return payloadPlatform}const requestPlatform=this.tryGetContext()?.platformType;if(requestPlatform&&requestPlatform!=="unknown"){return requestPlatform}const sessionId=this.authInfo.sessionId;if(!sessionId){return"unknown"}return this.scope.notifications.getPlatformType(sessionId)}get clientInfo(){const requestClientInfo=this.tryGetContext()?.clientInfo;if(requestClientInfo){return requestClientInfo}const sessionId=this.authInfo.sessionId;if(!sessionId){return void 0}return this.scope.notifications.getClientInfo(sessionId)}}}});var PromptContext;var init_prompt_interface=__esm({"libs/sdk/src/common/interfaces/prompt.interface.ts"(){"use strict";init_execution_context_interface();init_flow_interface();PromptContext=class extends ExecutionContextBase{promptId;promptName;metadata;args;_output;_outputHistory=[];constructor(ctorArgs){const{metadata,args,providers,logger,authInfo}=ctorArgs;super({providers,logger:logger.child(`prompt:${metadata.name}`),authInfo});this.promptName=metadata.name;this.promptId=metadata.name;this.metadata=metadata;this.args=args}get authInfo(){return super.authInfo}get output(){return this._output}set output(v){this._output=v;this._outputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get outputHistory(){return this._outputHistory}respond(value){this.output=value;FlowControl.respond(value)}get error(){return super.error}}}});function definedFields(toolCall){return Object.fromEntries(Object.entries(toolCall).filter(([,value])=>value!==void 0))}var AgentExecutionLoop,AgentMaxIterationsError;var init_agent_execution_loop=__esm({"libs/sdk/src/agent/agent-execution-loop.ts"(){"use strict";init_common();AgentExecutionLoop=class{config;constructor(config){this.config={maxIterations:10,timeout:12e4,...config}}async run(userMessage,toolExecutor,existingMessages=[]){const startTime=Date.now();const messages=[...existingMessages,{role:"user",content:userMessage}];let iterations=0;let totalPromptTokens=0;let totalCompletionTokens=0;let timeout;try{const timeoutPromise=new Promise((_,reject)=>{timeout=setTimeout(()=>reject(new Error(`Agent execution timed out after ${this.config.timeout}ms`)),this.config.timeout)});const result=await Promise.race([this.executeLoop(messages,toolExecutor,{onIteration:(iter,msg)=>{iterations=iter;this.config.onIteration?.(iter,msg)},onUsage:(prompt,completion)=>{totalPromptTokens+=prompt;totalCompletionTokens+=completion}}),timeoutPromise]);return{content:result.content,messages,iterations,usage:{promptTokens:totalPromptTokens,completionTokens:totalCompletionTokens,totalTokens:totalPromptTokens+totalCompletionTokens},success:true,durationMs:Date.now()-startTime}}catch(error){return{content:null,messages,iterations,usage:{promptTokens:totalPromptTokens,completionTokens:totalCompletionTokens,totalTokens:totalPromptTokens+totalCompletionTokens},success:false,error,durationMs:Date.now()-startTime}}finally{clearTimeout(timeout)}}async*runStreaming(userMessage,toolExecutor,existingMessages=[]){const startTime=Date.now();const deadline=startTime+this.config.timeout;const messages=[...existingMessages,{role:"user",content:userMessage}];let iterations=0;let totalPromptTokens=0;let totalCompletionTokens=0;const result=(content,error)=>({content,messages,iterations,usage:{promptTokens:totalPromptTokens,completionTokens:totalCompletionTokens,totalTokens:totalPromptTokens+totalCompletionTokens},success:error===void 0,...error&&{error},durationMs:Date.now()-startTime});const events=this.executeLoopStreaming(messages,toolExecutor);try{for(;;){const step=await this.beforeDeadline(events.next(),deadline);if(step.done){const done=result(step.value.content);yield{type:"done",result:done};return done}const event=step.value;if(event.type==="iteration")iterations=event.iteration;if(event.type==="usage"){totalPromptTokens+=event.promptTokens;totalCompletionTokens+=event.completionTokens}yield event}}catch(caught){void events.return({content:null}).catch(()=>void 0);const error=caught;const failed=result(null,error);yield{type:"error",error};yield{type:"done",result:failed};return failed}}async beforeDeadline(step,deadline){let timer;const timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(`Agent execution timed out after ${this.config.timeout}ms`)),Math.max(0,deadline-Date.now()))});try{return await Promise.race([step,timeout])}finally{clearTimeout(timer)}}async executeLoop(messages,toolExecutor,callbacks){for(let iteration=1;iteration<=this.config.maxIterations;iteration++){this.config.logger?.debug(`Agent loop iteration ${iteration}/${this.config.maxIterations}`);this.config.onLlmStart?.(iteration,this.config.maxIterations);const prompt={system:this.config.systemInstructions,messages};const completion=await this.config.adapter.completion(prompt,this.config.tools.length>0?this.config.tools:void 0,this.config.completionOptions);this.config.onLlmComplete?.(iteration,completion.usage);if(completion.usage){callbacks.onUsage(completion.usage.promptTokens,completion.usage.completionTokens)}if(completion.finishReason==="tool_calls"&&completion.toolCalls?.length){this.config.onToolsIdentified?.(completion.toolCalls.length,completion.toolCalls.map(tc=>tc.name));const assistantMessage={role:"assistant",content:completion.content,toolCalls:completion.toolCalls};messages.push(assistantMessage);callbacks.onIteration(iteration,assistantMessage);const totalTools=completion.toolCalls.length;for(let toolIndex=0;toolIndex<totalTools;toolIndex++){const toolCall=completion.toolCalls[toolIndex];this.config.onToolStart?.(toolCall,toolIndex,totalTools);this.config.onToolCall?.(toolCall);let result;let error2;try{result=await toolExecutor(toolCall.name,toolCall.arguments)}catch(e){error2=e;result={error:error2.message}}this.config.onToolResult?.(toolCall,result,error2);const toolMessage={role:"tool",content:typeof result==="string"?result:JSON.stringify(result),toolCallId:toolCall.id,name:toolCall.name};messages.push(toolMessage)}}else{const assistantMessage={role:"assistant",content:completion.content};messages.push(assistantMessage);callbacks.onIteration(iteration,assistantMessage);this.config.onContent?.(completion.content??"");this.config.onComplete?.(completion.content,void 0);return{content:completion.content}}}const error=new AgentMaxIterationsError(`Agent reached maximum iterations (${this.config.maxIterations}) without completing`,this.config.maxIterations);this.config.onComplete?.(null,error);throw error}async*executeLoopStreaming(messages,toolExecutor){for(let iteration=1;iteration<=this.config.maxIterations;iteration++){this.config.logger?.debug(`Agent loop iteration ${iteration}/${this.config.maxIterations}`);this.config.onLlmStart?.(iteration,this.config.maxIterations);yield{type:"iteration",iteration};const prompt={system:this.config.systemInstructions,messages};const completion=yield*this.streamCompletion(prompt);this.config.onLlmComplete?.(iteration,completion.usage);if(completion.finishReason==="tool_calls"&&completion.toolCalls?.length){const toolCalls=completion.toolCalls;this.config.onToolsIdentified?.(toolCalls.length,toolCalls.map(tc=>tc.name));const assistantMessage={role:"assistant",content:completion.content,toolCalls};messages.push(assistantMessage);this.config.onIteration?.(iteration,assistantMessage);const totalTools=toolCalls.length;for(let toolIndex=0;toolIndex<totalTools;toolIndex++){const toolCall=toolCalls[toolIndex];this.config.onToolStart?.(toolCall,toolIndex,totalTools);this.config.onToolCall?.(toolCall);yield{type:"tool_start",toolCall};let result;let error2;try{result=await toolExecutor(toolCall.name,toolCall.arguments)}catch(e){error2=e;result={error:error2.message}}this.config.onToolResult?.(toolCall,result,error2);yield{type:"tool_end",toolCall,result,error:error2};const toolMessage={role:"tool",content:typeof result==="string"?result:JSON.stringify(result),toolCallId:toolCall.id,name:toolCall.name};messages.push(toolMessage)}}else{const assistantMessage={role:"assistant",content:completion.content};messages.push(assistantMessage);this.config.onIteration?.(iteration,assistantMessage);this.config.onComplete?.(completion.content,void 0);return{content:completion.content}}}const error=new AgentMaxIterationsError(`Agent reached maximum iterations (${this.config.maxIterations}) without completing`,this.config.maxIterations);this.config.onComplete?.(null,error);throw error}async*streamCompletion(prompt){const adapter=this.config.adapter;const tools=this.config.tools.length>0?this.config.tools:void 0;let streamedText="";let completion;if(supportsStreaming(adapter)){const announced=new Map;let done;for await(const chunk of adapter.streamCompletion(prompt,tools,this.config.completionOptions)){if(chunk.type==="content"&&chunk.content){streamedText+=chunk.content;yield{type:"content",content:chunk.content};this.config.onContent?.(chunk.content)}else if(chunk.type==="tool_call"&&chunk.toolCall){announced.set(chunk.toolCall.id,{...announced.get(chunk.toolCall.id),...definedFields(chunk.toolCall)});yield{type:"tool_call",toolCall:chunk.toolCall}}else if(chunk.type==="done"&&chunk.completion){done=chunk.completion}}const toolCalls=done?.toolCalls??[...announced.values()].map(call=>({id:call.id,name:call.name??"",arguments:call.arguments??{}}));completion={content:streamedText||(done?.content??null),finishReason:done?.finishReason??(toolCalls.length>0?"tool_calls":"stop"),...toolCalls.length>0&&{toolCalls},...done?.usage&&{usage:done.usage}}}else{completion=await adapter.completion(prompt,tools,this.config.completionOptions)}if(!streamedText&&completion.content){yield{type:"content",content:completion.content};this.config.onContent?.(completion.content)}if(completion.usage){yield{type:"usage",promptTokens:completion.usage.promptTokens,completionTokens:completion.usage.completionTokens}}return completion}};AgentMaxIterationsError=class extends Error{constructor(message,maxIterations){super(message);this.maxIterations=maxIterations;this.name="AgentMaxIterationsError"}maxIterations}}});var AgentContext;var init_agent_interface=__esm({"libs/sdk/src/common/interfaces/agent.interface.ts"(){"use strict";init_agent_execution_loop();init_frontmcp_context_storage();init_helpers();init_errors();init_tool_lookup_utils();init_execution_context_interface();init_flow_interface();AgentContext=class _AgentContext extends ExecutionContextBase{agentId;agentName;metadata;llmAdapter;agentScope;systemInstructions;toolDefinitions;toolExecutor;agentInvoker;privateScope;_agentNameInternal;_agentInputInternal;_rawInput;_input;_outputDraft;_output;_inputHistory=[];_outputHistory=[];_progressToken;constructor(args){const{metadata,input,providers,logger,llmAdapter,agentScope,toolDefinitions,toolExecutor,agentInvoker,privateScope,progressToken}=args;super({providers,logger:logger.child(`agent:${metadata.id??metadata.name}`),authInfo:args.authInfo,signal:args.signal});this.agentName=metadata.name;this.agentId=metadata.id??metadata.name;this.metadata=metadata;this._input=input;this.llmAdapter=llmAdapter;this.agentScope=agentScope;this.systemInstructions=metadata.systemInstructions??"";this.toolDefinitions=toolDefinitions??[];this.toolExecutor=toolExecutor;this.agentInvoker=agentInvoker;this.privateScope=privateScope;this._progressToken=progressToken}async execute(input){return this.runAgentLoop(input)}async runAgentLoop(input){const userMessage=this.buildUserMessage(input);const streaming=this.streamsReplies();const enableAutoProgress=this.metadata.execution?.enableAutoProgress===true&&this.metadata.execution?.enableNotifications!==false;const maxIterations=this.metadata.execution?.maxIterations??10;const notificationInterval=this.metadata.execution?.notificationInterval??1e3;const iterationShare=80/maxIterations;let iterationStart=0;let lastSentProgress=-1;let lastAutoProgressAt;const autoProgress=(progress,message,isFinal=false)=>{if(streaming)return;const now=Date.now();if(progress<=lastSentProgress)return;if(!isFinal&&lastAutoProgressAt!==void 0&&now-lastAutoProgressAt<notificationInterval)return;lastAutoProgressAt=now;lastSentProgress=progress;void this.progress(progress,100,message)};const loop=new AgentExecutionLoop({adapter:{completion:(prompt,tools,options)=>this.completion(prompt,tools,options),...streaming&&{streamCompletion:(prompt,tools,options)=>this.streamCompletion(prompt,tools,options)}},systemInstructions:this.systemInstructions,tools:this.toolDefinitions,maxIterations,timeout:this.metadata.execution?.timeout??12e4,logger:this.logger,completionOptions:this.completionOptions(),onLlmStart:enableAutoProgress?(iteration,maxIter)=>{iterationStart=(iteration-1)*iterationShare;autoProgress(Math.round(iterationStart),`Starting LLM call (iteration ${iteration}/${maxIter})`)}:void 0,onLlmComplete:enableAutoProgress?(iteration,usage)=>{const usageStr=usage?` (${usage.promptTokens??0}P + ${usage.completionTokens??0}C tokens)`:"";autoProgress(Math.round(iterationStart+iterationShare/2),`LLM response received${usageStr}`)}:void 0,onToolsIdentified:enableAutoProgress?(count,names)=>{this.notify(`Identified ${count} tool call(s): ${names.join(", ")}`,"info")}:void 0,onToolStart:enableAutoProgress?(toolCall,index,total)=>{const toolsDone=(index+1)/(total+1);const toolProgress=iterationStart+iterationShare/2*(1+toolsDone);autoProgress(Math.round(toolProgress),`Executing tool ${index+1}/${total}: ${toolCall.name}`)}:void 0,onComplete:enableAutoProgress?(content,error)=>{autoProgress(100,error?`Agent failed: ${toMcpError(error).getPublicMessage()}`:"Agent completed",true)}:void 0,onToolCall:toolCall=>{if(this.metadata.execution?.enableNotifications!==false){this.notify(`Calling tool: ${toolCall.name}`,"info")}this.logger.debug(`Tool call: ${toolCall.name}`,{args:toolCall.arguments})},onToolResult:(toolCall,result2,error)=>{if(error){const reported=toMcpError(error);if(this.metadata.execution?.enableNotifications!==false){this.notify(`Tool ${toolCall.name} failed: ${reported.getPublicMessage()}`,"error")}this.logger.error(`Tool ${toolCall.name} failed (${reported.errorId})`,error)}else{this.logger.debug(`Tool ${toolCall.name} completed`,{result:result2})}},onContent:content=>{if(this.metadata.execution?.enableNotifications!==false){this.logger.debug(`Content received: ${content.slice(0,100)}...`)}}});const executor=async(name51,args)=>this.executeTool(name51,args);const result=streaming?await this.streamAgentLoop(loop.runStreaming(userMessage,executor)):await loop.run(userMessage,executor);if(!result.success&&result.error){throw result.error}return this.parseAgentResponse(result.content)}streamsReplies(){if(this.metadata.execution?.enableStreaming!==true||this._progressToken===void 0)return false;const overridesCompletion=this.completion!==_AgentContext.prototype.completion;const overridesStreamCompletion=this.streamCompletion!==_AgentContext.prototype.streamCompletion;return overridesStreamCompletion||!overridesCompletion&&typeof this.llmAdapter.streamCompletion==="function"}async streamAgentLoop(events){let chunks=0;for(let step=await events.next();;step=await events.next()){if(step.done)return step.value;const event=step.value;if(event.type==="content"&&event.content){chunks+=1;await this.progress(chunks,void 0,event.content)}}}completionOptions(){const llm=this.metadata.llm;return{...llm?.temperature!==void 0&&{temperature:llm.temperature},...llm?.maxTokens!==void 0&&{maxTokens:llm.maxTokens}}}buildUserMessage(input){if(typeof input==="string"){return input}const inputObj=input;if(inputObj["query"])return String(inputObj["query"]);if(inputObj["message"])return String(inputObj["message"]);if(inputObj["prompt"])return String(inputObj["prompt"]);if(inputObj["input"])return String(inputObj["input"]);return JSON.stringify(input)}parseAgentResponse(content){if(content===null){return{response:""}}if(content.trim().startsWith("{")||content.trim().startsWith("[")){try{return JSON.parse(content)}catch{}}return{response:content}}get input(){return this._input}set input(v){this._input=v;this._inputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get inputHistory(){return this._inputHistory}get output(){return this._output}set output(v){this._output=v;this._outputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get outputHistory(){return this._outputHistory}async completion(prompt,tools,options){return this.llmAdapter.completion(prompt,tools,options)}async*streamCompletion(prompt,tools,options){if(!this.llmAdapter.streamCompletion){const result=await this.completion(prompt,tools,options);yield{type:"done",completion:result};return}yield*this.llmAdapter.streamCompletion(prompt,tools,options)}async executeTool(name51,args){if(!this.toolExecutor){throw new AgentMethodNotAvailableError("executeTool",this.agentName)}return this.toolExecutor(name51,args)}async invokeAgent(agentId,input){if(!this.agentInvoker){throw new AgentMethodNotAvailableError("invokeAgent",this.agentName)}return this.agentInvoker(agentId,input)}callToolSurface(){return"agent"}callToolScope(name51){const privateScope=this.privateScope;const isPrivateTool=privateScope&&lookupTool(privateScope,name51);return isPrivateTool?privateScope:super.callToolScope(name51)}async notify(message,level="info"){const logMessage=typeof message==="string"?message:JSON.stringify(message);if(level==="error"){this.logger.error(logMessage)}else if(level==="warning"){this.logger.warn(logMessage)}else{this.logger.info(logMessage)}const data=typeof message==="string"?{message}:message;const sink=this.requestNotificationSink();if(sink)return sink.log(level,this.agentName,data);const sessionId=this.authInfo.sessionId;if(!sessionId){return false}return this.scope.notifications.sendLogMessageToSession(sessionId,level,this.agentName,data)}async progress(progress,total,message){const sink=this.requestNotificationSink();if(sink)return sink.progress(progress,total,message);if(this._progressToken===void 0){this.logger.debug("Cannot send progress: no progressToken in request");return false}const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.warn("Cannot send progress: no session ID");return false}return this.scope.notifications.sendProgressNotification(sessionId,this._progressToken,progress,total,message)}async elicit(message,requestedSchema,options){return performElicit({sessionId:this.authInfo.sessionId,getClientCapabilities:sid=>this.scope.notifications.getClientCapabilities(sid),tryGetContext:()=>this.tryGetContext()??this.runningRequestContext(),entryName:this._agentNameInternal??this.agentName,entryInput:this._agentInputInternal??this.input,elicitationEnabled:this.scope.metadata.elicitation?.enabled===true,questions:this.scope.persistentQuestions,signal:this.signal},message,requestedSchema,options)}requestNotificationSink(){return(this.tryGetContext()??this.runningRequestContext())?.getRequestNotificationSink?.()}runningRequestContext(){try{return this.scope.providers.get(FrontMcpContextStorage).getStore()}catch{return void 0}}respond(value){this.output=value;FlowControl.respond(value)}get platform(){const payloadPlatform=this.authInfo.sessionIdPayload?.platformType;if(payloadPlatform&&payloadPlatform!=="unknown"){return payloadPlatform}const requestPlatform=this.tryGetContext()?.platformType;if(requestPlatform&&requestPlatform!=="unknown"){return requestPlatform}const sessionId=this.authInfo.sessionId;if(!sessionId){return"unknown"}return this.scope.notifications.getPlatformType(sessionId)}get clientInfo(){const requestClientInfo=this.tryGetContext()?.clientInfo;if(requestClientInfo){return requestClientInfo}const sessionId=this.authInfo.sessionId;if(!sessionId){return void 0}return this.scope.notifications.getClientInfo(sessionId)}}}});var SkillContext;var init_skill_interface=__esm({"libs/sdk/src/common/interfaces/skill.interface.ts"(){"use strict";init_sdk_errors();init_metadata();init_execution_context_interface();SkillContext=class extends ExecutionContextBase{skillId;skillName;metadata;defaults;constructor(args){const{metadata,providers,logger,defaults}=args;super({providers,logger:logger.child(`skill:${metadata.id??metadata.name}`),authInfo:args.authInfo});this.skillName=metadata.name;this.skillId=metadata.id??metadata.name;this.metadata=metadata;this.defaults=defaults}async loadInstructions(){if(!this.defaults)throw new SkillContextNotImplementedError(this.skillName,"loadInstructions");return this.defaults.loadInstructions()}async build(){if(!this.defaults)throw new SkillContextNotImplementedError(this.skillName,"build");return this.defaults.build()}getToolRefs(){if(!this.metadata.tools)return[];return this.metadata.tools.map(t=>normalizeToolRef(t))}getToolNames(){return this.getToolRefs().map(t=>t.name)}}}});var WorkflowContext;var init_workflow_interface=__esm({"libs/sdk/src/common/interfaces/workflow.interface.ts"(){"use strict";init_execution_context_interface();WorkflowContext=class extends ExecutionContextBase{metadata;_stepResults=new Map;constructor(args){const{metadata,providers,logger}=args;super({providers,logger:logger.child(`workflow:${metadata.id??metadata.name}`),authInfo:args.authInfo});this.metadata=metadata}get workflowName(){return this.metadata.name}get workflowId(){return this.metadata.id??this.metadata.name}get stepResults(){return this._stepResults}_setStepResult(stepId,result){this._stepResults.set(stepId,result)}}}});var ChannelContext;var init_channel_interface=__esm({"libs/sdk/src/common/interfaces/channel.interface.ts"(){"use strict";init_call_surface();init_mcp_error();init_execution_context_interface();ChannelContext=class extends ExecutionContextBase{channelName;metadata;_pushIncoming;constructor(args){const{metadata,providers,logger}=args;super({providers,logger:logger.child(`channel:${metadata.name}`),authInfo:args.authInfo});this.channelName=metadata.name;this.metadata=metadata}async onReply(reply,meta){throw new PublicMcpError(`Channel "${this.channelName}" has twoWay: true but onReply() is not implemented. Override onReply() to forward replies to the external system.`,"CHANNEL_REPLY_NOT_IMPLEMENTED",501)}async onConnect(){}async onDisconnect(){}pushIncoming(payload){if(this._pushIncoming){this._pushIncoming(payload)}else{this.logger.warn(`Channel "${this.channelName}": pushIncoming called but no handler is wired`)}}callToolSurface(){return getCallSurface()==="http-trigger"?"http-trigger":void 0}}}});var init_duty_interface=__esm({"libs/sdk/src/common/interfaces/duty.interface.ts"(){"use strict"}});var HttpRouteContext;var init_http_route_interface=__esm({"libs/sdk/src/common/interfaces/http-route.interface.ts"(){"use strict";init_execution_context_interface();HttpRouteContext=class extends ExecutionContextBase{request;person;constructor(args){super(args);this.request=args.request;this.person=args.person}get params(){return this.request.params??{}}}}});import{scopesFromClaims}from"@frontmcp/auth";function sessionIdPresentedBy(request2){const header2=request2.headers?.["mcp-session-id"];if(typeof header2==="string"&&header2.length>0)return header2;const query=request2.query?.["sessionId"];return typeof query==="string"&&query.length>0?query:void 0}function authInfoFromAuthorization(authorization,presentedSessionId){const{token,user,session}=authorization;const verifiedSession=session!==void 0&&presentedSessionId!==void 0&&session.id===presentedSessionId?session:void 0;return{token,clientId:user?.sub,scopes:scopesFromClaims(user),expiresAt:user?.exp?user.exp*1e3:void 0,user,extra:{user,sessionId:verifiedSession?.id,sessionPayload:verifiedSession?.payload}}}var init_auth_info_utils=__esm({"libs/sdk/src/common/utils/auth-info.utils.ts"(){"use strict"}});import{internalZ as z81}from"@frontmcp/lazy-zod";function pathOf(req){const anyReq=req;const raw=anyReq.path??anyReq.pathname??anyReq.url??"/";try{const u=new URL(String(raw),"http://local");return u.pathname||"/"}catch{return String(raw).split("?")[0]||"/"}}function isLegacySsePath(path4){return path4==="/sse"||path4.endsWith("/sse")}function tryDecodeTransportType(sessionId){if(!sessionId)return;try{const b64=sessionId.replace(/-/g,"+").replace(/_/g,"/");const json=Buffer.from(b64,"base64").toString("utf8");if(json.trimStart()[0]!=="{")return;const obj=JSON.parse(json);return obj?.transportType}catch{return}}function getQuerySessionId(req){const anyReq=req;const raw=anyReq.url??anyReq.path??"/";try{const u=new URL(String(raw),"http://local");return u.searchParams.get("sessionId")??void 0}catch{return void 0}}function computeBitmap(req,cfg){const method=req.method.toUpperCase();const accept=h(req,"accept");const path4=pathOf(req);const postToMessage=method==="POST"&&(path4==="/message"||path4.endsWith("/message"));const headerSessionId=h(req,"mcp-session-id");const querySessionId=postToMessage?getQuerySessionId(req):void 0;const sessionId=headerSessionId??querySessionId;const legacyHeader=h(req,"x-legacy-sse")==="true";const transportType=tryDecodeTransportType(sessionId);const acceptSSE=wantsSSE(accept);const acceptJSON=wantsJSON(accept)||!accept&&cfg.tolerateMissingAccept;const init=method==="POST"&&isInitialize(req.body);const getToSsePath=method==="GET"&&isLegacySsePath(path4);const channel2=method==="POST"&&postToMessage?CH_POST_MESSAGE:getToSsePath&&acceptSSE?CH_GET_SSE_PATH:method==="GET"&&acceptSSE?CH_GET_SSE:method==="POST"&&init&&acceptSSE?CH_POST_INIT_SSE:method==="POST"&&init&&acceptJSON?CH_POST_INIT_JSON:method==="POST"&&!init&&acceptSSE?CH_POST_SSE:method==="POST"&&!init&&acceptJSON?CH_POST_JSON:CH_OTHER;let flags=0;if(sessionId)flags|=B_HAS_SESSION;if(cfg.enableStatelessHttp)flags|=B_STATELESS_EN;if(cfg.requireSessionForStreamable)flags|=B_REQ_SESSION;if(legacyHeader||transportType==="legacy-sse")flags|=B_LEGACY_HINT;if(cfg.enableSseListener)flags|=B_SSE_LISTENER_EN;if(cfg.enableStreamableHttp)flags|=B_STREAMABLE_EN;if(cfg.enableStatefulHttp)flags|=B_STATEFUL_EN;if(cfg.enableLegacySSE)flags|=B_LEGACY_EN;return{key:channel2&CH_MASK|flags,channel:channel2,flags,init}}function decideIntent(req,cfg){const reasons=[];const method=req.method.toUpperCase();if(method==="DELETE"){const sessionId=h(req,"mcp-session-id");if(!sessionId){return{intent:"unknown",reasons:["DELETE requires Mcp-Session-Id header."],recommendation:{httpStatus:400,message:"Session ID required for DELETE"},debug:{key:0,channel:0,flags:0}}}return{intent:"delete-session",reasons:["DELETE with Mcp-Session-Id \u2192 session termination."],debug:{key:0,channel:0,flags:sessionId?B_HAS_SESSION:0}}}const{key,channel:channel2,flags,init}=computeBitmap(req,cfg);if(method==="POST"&&channel2!==CH_POST_MESSAGE){const accept=h(req,"accept");const acceptsSSE=wantsSSE(accept);const acceptsJSON=wantsJSON(accept)||!accept&&cfg.tolerateMissingAccept;if(!acceptsSSE&&!acceptsJSON){return{intent:"unknown",reasons:["Client must accept application/json or text/event-stream."],recommendation:{httpStatus:406,message:"Not acceptable"},debug:{key,channel:channel2,flags}}}}for(const rule of RULES){if((key&rule.care)===rule.match){const{reason,...rest}=rule.outcome;reasons.push(reason);if(init)reasons.push("Initialize body detected.");return{...rest,reasons,debug:{key,channel:channel2,flags}}}}return{intent:"unknown",reasons:["No matching rule."],recommendation:{httpStatus:500,message:"Unroutable request"},debug:{key,channel:channel2,flags}}}function authorizeSessionTermination(verifyResult,requestedSessionId){if(!verifyResult||verifyResult.kind!=="authorized"||!verifyResult.authorization){return{kind:"unauthorized"}}const ownedSessionId=verifyResult.authorization.session?.id;if(!ownedSessionId||!requestedSessionId||requestedSessionId!==ownedSessionId){return{kind:"forbidden"}}return{kind:"ok",sessionId:ownedSessionId}}var intentSchema,decisionSchema,CH_OTHER,CH_GET_SSE,CH_POST_INIT_JSON,CH_POST_INIT_SSE,CH_POST_JSON,CH_POST_SSE,CH_POST_MESSAGE,CH_GET_SSE_PATH,CH_MASK,B_HAS_SESSION,B_STATELESS_EN,B_REQ_SESSION,B_LEGACY_HINT,B_SSE_LISTENER_EN,B_STREAMABLE_EN,B_STATEFUL_EN,B_LEGACY_EN,h,wantsSSE,wantsJSON,isInitialize,RULES;var init_decide_request_intent_utils=__esm({"libs/sdk/src/common/utils/decide-request-intent.utils.ts"(){"use strict";intentSchema=z81.union([z81.literal("legacy-sse"),z81.literal("sse"),z81.literal("streamable-http"),z81.literal("stateful-http"),z81.literal("stateless-http"),z81.literal("delete-session"),z81.literal("mcp-20260728"),z81.literal("unknown")]);decisionSchema=z81.object({intent:intentSchema,reasons:z81.array(z81.string()),recommendation:z81.object({httpStatus:z81.number(),message:z81.string()}).optional(),debug:z81.object({key:z81.number(),channel:z81.number(),flags:z81.number()}).optional()});CH_OTHER=0;CH_GET_SSE=1;CH_POST_INIT_JSON=2;CH_POST_INIT_SSE=3;CH_POST_JSON=4;CH_POST_SSE=5;CH_POST_MESSAGE=6;CH_GET_SSE_PATH=7;CH_MASK=7;B_HAS_SESSION=1<<3;B_STATELESS_EN=1<<4;B_REQ_SESSION=1<<5;B_LEGACY_HINT=1<<6;B_SSE_LISTENER_EN=1<<7;B_STREAMABLE_EN=1<<8;B_STATEFUL_EN=1<<9;B_LEGACY_EN=1<<10;h=(req,name51)=>Object.entries(req.headers).find(([k])=>k.toLowerCase()===name51.toLowerCase())?.[1];wantsSSE=accept=>(accept??"").toLowerCase().includes("text/event-stream");wantsJSON=accept=>(accept??"").toLowerCase().includes("application/json");isInitialize=body=>!!body&&typeof body==="object"&&body.method==="initialize";RULES=[{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_GET_SSE_PATH|B_LEGACY_EN,outcome:{intent:"legacy-sse",reason:"GET /sse without Mcp-Session-Id \u2192 legacy SSE."}},{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_GET_SSE_PATH,outcome:{intent:"unknown",reason:"Legacy SSE disabled.",recommendation:{httpStatus:405,message:"Legacy SSE disabled"}}},{care:CH_MASK|B_HAS_SESSION|B_SSE_LISTENER_EN|B_STREAMABLE_EN,match:CH_GET_SSE|B_HAS_SESSION|B_SSE_LISTENER_EN|B_STREAMABLE_EN,outcome:{intent:"streamable-http",reason:"GET / with session ID \u2192 SSE listener for streamable-http."}},{care:CH_MASK|B_HAS_SESSION|B_SSE_LISTENER_EN,match:CH_GET_SSE|B_HAS_SESSION,outcome:{intent:"unknown",reason:"SSE listener disabled for GET / requests.",recommendation:{httpStatus:405,message:"SSE listener disabled"}}},{care:CH_MASK|B_HAS_SESSION,match:CH_GET_SSE,outcome:{intent:"unknown",reason:"GET / with SSE requires session for MCP transport."}},{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_POST_MESSAGE|B_HAS_SESSION|B_LEGACY_EN,outcome:{intent:"legacy-sse",reason:"POST /message with Mcp-Session-Id \u2192 legacy SSE bridge."}},{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_POST_MESSAGE|B_HAS_SESSION,outcome:{intent:"unknown",reason:"Legacy /message endpoint disabled.",recommendation:{httpStatus:405,message:"Legacy SSE disabled"}}},{care:CH_MASK|B_SSE_LISTENER_EN|B_HAS_SESSION,match:CH_GET_SSE_PATH|B_HAS_SESSION,outcome:{intent:"unknown",reason:"SSE listener disabled.",recommendation:{httpStatus:405,message:"SSE listener disabled"}}},{care:CH_MASK|B_SSE_LISTENER_EN|B_HAS_SESSION,match:CH_GET_SSE_PATH|B_SSE_LISTENER_EN|B_HAS_SESSION,outcome:{intent:"sse",reason:"GET /sse with Mcp-Session-Id."}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_INIT_SSE|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless initialize (no session)."}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_SSE,outcome:{intent:"unknown",reason:"Streamable HTTP disabled.",recommendation:{httpStatus:405,message:"Streamable HTTP disabled"}}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_SSE|B_STREAMABLE_EN,outcome:{intent:"streamable-http",reason:"Initialize with SSE."}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_INIT_JSON|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless initialize JSON (no session)."}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_JSON,outcome:{intent:"unknown",reason:"JSON mode disabled.",recommendation:{httpStatus:405,message:"JSON mode disabled"}}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_JSON|B_STREAMABLE_EN,outcome:{intent:"stateful-http",reason:"Initialize with JSON."}},{care:CH_MASK|B_REQ_SESSION|B_HAS_SESSION|B_STATELESS_EN,match:CH_POST_SSE|B_REQ_SESSION,outcome:{intent:"unknown",reason:"POST SSE requires session.",recommendation:{httpStatus:400,message:"Initialize required (no Mcp-Session-Id)"}}},{care:CH_MASK|B_STREAMABLE_EN|B_STATELESS_EN,match:CH_POST_SSE,outcome:{intent:"unknown",reason:"Streamable HTTP disabled.",recommendation:{httpStatus:405,message:"Streamable HTTP disabled"}}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_SSE|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless short-lived SSE."}},{care:CH_MASK,match:CH_POST_SSE,outcome:{intent:"streamable-http",reason:"Short-lived SSE for this request."}},{care:CH_MASK|B_REQ_SESSION|B_HAS_SESSION|B_STATELESS_EN,match:CH_POST_JSON|B_REQ_SESSION,outcome:{intent:"unknown",reason:"POST JSON requires session.",recommendation:{httpStatus:400,message:"Initialize required (no Mcp-Session-Id)"}}},{care:CH_MASK|B_STATEFUL_EN|B_STREAMABLE_EN|B_STATELESS_EN,match:CH_POST_JSON,outcome:{intent:"unknown",reason:"JSON mode disabled.",recommendation:{httpStatus:405,message:"JSON mode disabled"}}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_JSON|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless JSON request."}},{care:CH_MASK,match:CH_POST_JSON,outcome:{intent:"stateful-http",reason:"Aggregated JSON response."}},{care:CH_MASK,match:CH_OTHER,outcome:{intent:"unknown",reason:"Method/Accept not allowed.",recommendation:{httpStatus:405,message:"Method/Accept not allowed"}}}]}});import{isAnonymousSubject as isAnonymousSubject5}from"@frontmcp/auth";import{ConcurrencyLimitError,GuardStorageUnavailableError as GuardStorageUnavailableError2}from"@frontmcp/guard";function enforceIpFilter(scope,clientIp,buildRejection=()=>httpRespond.forbidden({body:{...IP_FILTER_REJECTION_BODY}})){const result=scope.rateLimitManager?.checkIpFilter(clientIp);if(!result||result.allowed)return;scope.logger.warn("request rejected by ipFilter",{reason:result.reason,hasClientIp:clientIp!==void 0});FlowControl.respond(buildRejection())}function buildPartitionContext(source){if(!source)return void 0;const clientId=source.authInfo?.clientId;const userId=isAnonymousSubject5(clientId)?void 0:String(clientId);const callerKey=userId?`user:${userId}`:"anonymous";return{sessionId:verifiedSessionOf(source)??callerKey,clientIp:source.metadata?.clientIp,userId}}function verifiedSessionOf(source){if("verifiedSessionId"in source)return source.verifiedSessionId;const confirmed=source.authInfo?.sessionId??source.authInfo?.extra?.sessionId;return confirmed===source.sessionId?source.sessionId:void 0}function partitionsByIdentity(partitionBy){return partitionBy==="session"||partitionBy==="userId"||typeof partitionBy==="function"}async function enforceGlobalRateLimit(scope,context){const manager=scope.rateLimitManager;const globalConfig=manager?.config?.global;const partitionBy=globalConfig?.partitionBy;if(!manager||!globalConfig||partitionBy==="session"||partitionBy==="userId")return;let result;try{result=await manager.checkGlobalRateLimit(buildPartitionContext(context))}catch(error){if(!(error instanceof GuardStorageUnavailableError2))throw error;FlowControl.respond(httpRespond.json({error:"service_unavailable",message:"Service temporarily unavailable: the rate-limit store cannot be reached",code:error.code},{status:error.statusCode,headers:{"Retry-After":"1"}}))}context?.set(GLOBAL_RATE_LIMIT_CHECKED,true);if(result.allowed)return;const retryAfter=Math.ceil((result.retryAfterMs??6e4)/1e3);FlowControl.respond(httpRespond.json({error:"rate_limited",message:`Rate limit exceeded. Retry after ${retryAfter} seconds`},{status:429,headers:{"Retry-After":String(retryAfter)}}))}async function acquireConcurrencySlots(manager,entityName,entityConfig,partitionContext,options={}){const globalConfig=options.skipGlobal?void 0:manager.config.globalConcurrency;const globalTicket=globalConfig?await manager.acquireGlobalSemaphore(partitionContext):null;if(globalConfig&&!globalTicket){throw new ConcurrencyLimitError("global",globalConfig.maxConcurrent)}const config=entityConfig??manager.config.defaultConcurrency;if(!config)return globalTicket??void 0;let entityTicket;try{entityTicket=await manager.acquireSemaphore(entityName,config,partitionContext)}catch(error){await globalTicket?.release();throw error}if(!entityTicket){await globalTicket?.release();throw new ConcurrencyLimitError(entityName,config.maxConcurrent)}if(!globalTicket)return entityTicket;const heldEntityTicket=entityTicket;return{ticket:heldEntityTicket.ticket,release:async()=>{try{await heldEntityTicket.release()}finally{await globalTicket.release()}}}}var IP_FILTER_REJECTION_BODY,GLOBAL_RATE_LIMIT_CHECKED;var init_guard_utils=__esm({"libs/sdk/src/common/utils/guard.utils.ts"(){"use strict";init_flow_interface();init_http_output_schema();IP_FILTER_REJECTION_BODY={error:"forbidden",message:"Client IP rejected by ipFilter"};GLOBAL_RATE_LIMIT_CHECKED=Symbol.for("frontmcp:guard:global-rate-limit-checked")}});function getGlobalStoreConfig(pluginName,config){if(!config.redis){throw new GlobalConfigNotFoundError(pluginName,"redis")}return config.redis}var init_global_config_utils=__esm({"libs/sdk/src/common/utils/global-config.utils.ts"(){"use strict";init_errors()}});function matchPattern(name51,pattern){if(pattern==="*")return true;if(!pattern.includes("*"))return name51===pattern;const segments=pattern.split("*");let pos=0;for(let i=0;i<segments.length;i++){const seg=segments[i];if(i===0){if(!name51.startsWith(seg))return false;pos=seg.length}else if(i===segments.length-1){if(!name51.endsWith(seg))return false;if(name51.length-seg.length<pos)return false}else{const idx=name51.indexOf(seg,pos);if(idx===-1)return false;pos=idx+seg.length}}return true}function matchesAny(name51,patterns){return patterns.some(p=>matchPattern(name51,p))}function isPrimitiveIncluded(name51,primitiveType,config){if(!config)return true;if((config.default??"include")==="include"){return!matchesAny(name51,config.exclude?.[primitiveType]??[])}return matchesAny(name51,config.include?.[primitiveType]??[])}function applyPrimitiveFilter(items,primitiveType,config){return items.filter(item=>isPrimitiveIncluded(item.name,primitiveType,config))}var init_primitive_filter=__esm({"libs/sdk/src/common/utils/primitive-filter.ts"(){"use strict"}});var init_utils3=__esm({"libs/sdk/src/common/utils/index.ts"(){"use strict";init_auth_info_utils();init_caller_dir_utils();init_decide_request_intent_utils();init_guard_utils();init_path_utils();init_principal_utils();init_global_config_utils();init_primitive_filter();init_validate_remote_url()}});var FrontMcpAuth;var init_primary_auth_provider_interface=__esm({"libs/sdk/src/common/interfaces/internal/primary-auth-provider.interface.ts"(){"use strict";init_types();init_utils3();FrontMcpAuth=class{ready;options;id;constructor(options){this.options=options;this.id=this.deriveId(options)}deriveId(options){if(isPublicMode(options)){return options.issuer??"public"}if(isTransparentMode(options)){return options.providerConfig?.id??urlToSafeId(options.provider)}if(isOrchestratedMode(options)){if(isOrchestratedRemote(options)){return options.providerConfig?.id??urlToSafeId(options.provider)}return options.local?.issuer??"local"}return"unknown"}verifyGatewayToken(_token,_requestBaseUrl,_expectedAudience,_expectedIssuer){return Promise.resolve({ok:false,error:"gateway token verification is not supported by this auth mode"})}}}});var init_registry_interface=__esm({"libs/sdk/src/common/interfaces/internal/registry.interface.ts"(){"use strict"}});var init_internal=__esm({"libs/sdk/src/common/interfaces/internal/index.ts"(){"use strict";init_primary_auth_provider_interface();init_registry_interface()}});var init_interfaces2=__esm({"libs/sdk/src/common/interfaces/index.ts"(){"use strict";init_base_interface();init_execution_context_interface();init_front_mcp_interface();init_server_interface();init_scope_interface();init_flow_interface();init_hook_interface();init_app_interface();init_provider_interface();init_auth_provider_interface();init_adapter_interface();init_plugin_interface();init_tool_interface();init_resource_interface();init_prompt_interface();init_logger_interface();init_llm_adapter_interface();init_agent_interface();init_skill_interface();init_job_interface();init_workflow_interface();init_channel_interface();init_duty_interface();init_http_route_interface();init_internal()}});var JobRunResource;var init_job_run_resource=__esm({"libs/sdk/src/job/resources/job-run.resource.ts"(){"use strict";init_common();init_interfaces2();init_errors();init_job_run_access();JobRunResource=class extends ResourceContext{async execute(uri,{runId}){const record=await jobExecutionManagerOf(this.scope)?.getStatus(runId);if(!record||!await mayAccessRun(this.scope,record,"read",this.getAuthInfo())){throw new ResourceNotFoundError(uri)}const run={runId:record.runId,jobName:record.jobName,state:record.state,attempt:record.attempt,maxAttempts:record.maxAttempts,startedAt:record.startedAt,completedAt:record.completedAt,updatedAt:record.updatedAt,revision:record.revision,progress:record.progress,result:record.result,error:record.error&&{name:record.error.name,message:record.error.message},logs:record.logs};return{contents:[{uri,mimeType:"application/json",text:JSON.stringify(run)}]}}};JobRunResource=__decorateClass([_ResourceTemplate({name:"job-run",uriTemplate:"job://runs/{runId}",description:"A job or workflow run: its state, progress, result or error, revision and last update",mimeType:"application/json"})],JobRunResource)}});var MemoryJobStateStore;var init_memory_job_state_store=__esm({"libs/sdk/src/job/store/memory-job-state.store.ts"(){"use strict";MemoryJobStateStore=class{runs=new Map;cancelRequests=new Set;runnerExpiries=new Map;claims=new Set;async createRun(record){this.runs.set(record.runId,{...record,revision:1,updatedAt:Date.now()})}async updateRun(runId,updates){const existing=this.runs.get(runId);if(!existing)return;const{runId:_ignoreRunId,...safeUpdates}=updates;const revision=(existing.revision??0)+1;this.runs.set(runId,{...existing,...safeUpdates,revision,updatedAt:Date.now()})}async getRun(runId){const record=this.runs.get(runId);return record?{...record}:null}async listRuns(opts){let results=[...this.runs.values()];if(opts?.jobId){results=results.filter(r=>r.jobId===opts.jobId)}if(opts?.sessionId){results=results.filter(r=>r.sessionId===opts.sessionId)}if(opts?.state){results=results.filter(r=>r.state===opts.state)}results.sort((a,b)=>b.startedAt-a.startedAt);if(opts?.limit!==void 0&&opts.limit>0){results=results.slice(0,opts.limit)}return results.map(r=>({...r}))}async cleanup(olderThanMs){const cutoff=Date.now()-olderThanMs;let removed=0;for(const[runId,record]of this.runs){if(record.startedAt<cutoff){this.runs.delete(runId);removed++}}return removed}async requestCancel(runId){this.cancelRequests.add(runId)}async isCancelRequested(runId){return this.cancelRequests.has(runId)}async touchRunner(runnerId,ttlSeconds){this.runnerExpiries.set(runnerId,Date.now()+ttlSeconds*1e3)}async isRunnerAlive(runnerId){return(this.runnerExpiries.get(runnerId)??0)>Date.now()}async claimRun(runId){if(this.claims.has(runId))return false;this.claims.add(runId);return true}async dispose(){this.runs.clear();this.cancelRequests.clear();this.runnerExpiries.clear();this.claims.clear()}}}});var RedisJobStateStore;var init_redis_job_state_store=__esm({"libs/sdk/src/job/store/redis-job-state.store.ts"(){"use strict";RedisJobStateStore=class{client;keyPrefix;logger;ttlSeconds;ownsClient;constructor(client,logger,keyPrefix="mcp:jobs:",ttlSeconds=86400,options={}){this.client=client;this.logger=logger;this.keyPrefix=keyPrefix;this.ttlSeconds=ttlSeconds;this.ownsClient=options.ownsClient??false}key(runId){return`${this.keyPrefix}run:${runId}`}indexKey(field,value){return`${this.keyPrefix}idx:${field}:${value}`}cancelKey(runId){return`${this.keyPrefix}cancel:${runId}`}async createRun(record){const key=this.key(record.runId);const data=JSON.stringify({...record,revision:1,updatedAt:Date.now()});await this.client.set(key,data,"EX",this.ttlSeconds);if(record.jobId)await this.index(this.indexKey("jobId",record.jobId),record.runId);if(record.sessionId)await this.index(this.indexKey("sessionId",record.sessionId),record.runId)}async index(key,runId){await this.client.sadd(key,runId);await this.client.expire?.(key,this.ttlSeconds)}async updateRun(runId,updates){const key=this.key(runId);const raw=await this.client.get(key);if(!raw)return;const existing=JSON.parse(raw);const{runId:_ignoreRunId,...safeUpdates}=updates;const updated={...existing,...safeUpdates,revision:(existing.revision??0)+1,updatedAt:Date.now()};await this.client.set(key,JSON.stringify(updated),"EX",this.ttlSeconds)}async getRun(runId){const raw=await this.client.get(this.key(runId));if(!raw)return null;return JSON.parse(raw)}async listRuns(opts){let runIds;if(opts?.jobId){runIds=await this.client.smembers(this.indexKey("jobId",opts.jobId))}else if(opts?.sessionId){runIds=await this.client.smembers(this.indexKey("sessionId",opts.sessionId))}else{const keys=await this.client.keys(`${this.keyPrefix}run:*`);runIds=keys.map(k=>k.replace(`${this.keyPrefix}run:`,""))}const results=[];for(const runId of runIds){const record=await this.getRun(runId);if(!record)continue;if(opts?.state&&record.state!==opts.state)continue;results.push(record)}results.sort((a,b)=>b.startedAt-a.startedAt);if(opts?.limit){return results.slice(0,opts.limit)}return results}async cleanup(olderThanMs){const cutoff=Date.now()-olderThanMs;const keys=await this.client.keys(`${this.keyPrefix}run:*`);let removed=0;for(const key of keys){const raw=await this.client.get(key);if(!raw)continue;const record=JSON.parse(raw);if(record.startedAt<cutoff){await this.client.del(key);const runId=key.replace(`${this.keyPrefix}run:`,"");if(record.jobId){await this.client.srem(this.indexKey("jobId",record.jobId),runId)}if(record.sessionId){await this.client.srem(this.indexKey("sessionId",record.sessionId),runId)}removed++}}return removed}async requestCancel(runId){await this.client.set(this.cancelKey(runId),"1","EX",this.ttlSeconds)}async isCancelRequested(runId){return await this.client.get(this.cancelKey(runId))!==null}async touchRunner(runnerId,ttlSeconds){await this.client.set(`${this.keyPrefix}runner:${runnerId}`,"1","EX",ttlSeconds)}async isRunnerAlive(runnerId){return await this.client.get(`${this.keyPrefix}runner:${runnerId}`)!==null}async claimRun(runId){return await this.client.set(`${this.keyPrefix}claim:${runId}`,"1","NX","EX",this.ttlSeconds)==="OK"}async dispose(){if(!this.ownsClient)return;this.ownsClient=false;try{await this.client.quit?.()}catch(error){const message=error instanceof Error?error.message:String(error);this.logger?.warn(`Could not close the job state store's redis client: ${message}`)}}}}});function runKey(runId){return`run:${runId}`}function cancelKey(runId){return`cancel:${runId}`}function runnerKey(runnerId){return`runner:${runnerId}`}function claimKey(runId){return`claim:${runId}`}var StorageJobStateStore;var init_storage_job_state_store=__esm({"libs/sdk/src/job/store/storage-job-state.store.ts"(){"use strict";StorageJobStateStore=class{constructor(storage,ttlSeconds=86400){this.storage=storage;this.ttlSeconds=ttlSeconds}storage;ttlSeconds;async createRun(record){await this.write({...record,revision:1,updatedAt:Date.now()})}async updateRun(runId,updates){const existing=await this.getRun(runId);if(!existing)return;const{runId:_ignoreRunId,...safeUpdates}=updates;await this.write({...existing,...safeUpdates,revision:(existing.revision??0)+1,updatedAt:Date.now()})}async getRun(runId){const raw=await this.storage.get(runKey(runId));return raw?JSON.parse(raw):null}async listRuns(opts){const runs=(await this.allRuns()).filter(run=>(!opts?.jobId||run.jobId===opts.jobId)&&(!opts?.sessionId||run.sessionId===opts.sessionId)&&(!opts?.state||run.state===opts.state));runs.sort((a,b)=>b.startedAt-a.startedAt);return opts?.limit!==void 0&&opts.limit>0?runs.slice(0,opts.limit):runs}async cleanup(olderThanMs){const cutoff=Date.now()-olderThanMs;const stale=(await this.allRuns()).filter(run=>run.startedAt<cutoff);if(stale.length>0){await this.storage.mdelete(stale.flatMap(run=>[runKey(run.runId),cancelKey(run.runId),claimKey(run.runId)]))}return stale.length}async requestCancel(runId){await this.storage.set(cancelKey(runId),"1",{ttlSeconds:this.ttlSeconds})}async isCancelRequested(runId){return this.storage.exists(cancelKey(runId))}async touchRunner(runnerId,ttlSeconds){await this.storage.set(runnerKey(runnerId),"1",{ttlSeconds})}async isRunnerAlive(runnerId){return this.storage.exists(runnerKey(runnerId))}async claimRun(runId){const claimed=await this.storage.incr(claimKey(runId))===1;if(claimed)await this.storage.expire(claimKey(runId),this.ttlSeconds);return claimed}async dispose(){await this.storage.disconnect()}async write(record){await this.storage.set(runKey(record.runId),JSON.stringify(record),{ttlSeconds:this.ttlSeconds})}async allRuns(){const keys=await this.storage.keys("run:*");if(keys.length===0)return[];const values=await this.storage.mget(keys);return values.filter(raw=>raw!==null).map(raw=>JSON.parse(raw))}}}});import{createRedisClient,createStorage as createStorage2,StorageConfigError}from"@frontmcp/utils";function refuseVercelKvJobStore(redis){if(redis?.provider!=="vercel-kv")return;throw new JobStoreNotSupportedError("Vercel KV is not supported for job stores: jobs.store.redis is opened over the Redis protocol, which Vercel KV does not serve. Use a Redis server, jobs.store.sqlite, or jobs.store: false.")}async function createJobStateStore(options,logger){const keyPrefix=options?.keyPrefix??"mcp:jobs:";const ttlSeconds=options?.ttlSeconds??86400;if(options?.sqlite){const storage=await createStorage2({type:"sqlite",sqlite:options.sqlite,prefix:keyPrefix,fallback:"error"});return{store:new StorageJobStateStore(storage,ttlSeconds),type:"sqlite"}}if(options?.redis){refuseVercelKvJobStore(options.redis);try{const{url,host,port,password,db,tls}=options.redis;const client=createRedisClient({url,host,port,password,db,tls,label:"JobStateStore",logger});return{store:new RedisJobStateStore(client,logger,keyPrefix,ttlSeconds,{ownsClient:true}),type:"redis"}}catch(err){if(err instanceof StorageConfigError)throw err;logger?.warn?.(`Failed to create Redis job state store, falling back to memory: ${err}`)}}return{store:new MemoryJobStateStore,type:"memory"}}var init_job_state_store_factory=__esm({"libs/sdk/src/job/store/job-state-store.factory.ts"(){"use strict";init_job_errors();init_memory_job_state_store();init_redis_job_state_store();init_storage_job_state_store()}});var MemoryJobDefinitionStore;var init_memory_job_definition_store=__esm({"libs/sdk/src/job/store/memory-job-definition.store.ts"(){"use strict";MemoryJobDefinitionStore=class{jobs=new Map;workflows=new Map;async saveDefinition(record){this.jobs.set(record.provide,{...record})}async getDefinition(jobId){return this.jobs.get(jobId)??null}async listDefinitions(){return[...this.jobs.values()]}async removeDefinition(jobId){return this.jobs.delete(jobId)}async saveWorkflowDefinition(record){this.workflows.set(record.provide,{...record})}async getWorkflowDefinition(wfId){return this.workflows.get(wfId)??null}async listWorkflowDefinitions(){return[...this.workflows.values()]}async removeWorkflowDefinition(wfId){return this.workflows.delete(wfId)}async dispose(){this.jobs.clear();this.workflows.clear()}}}});var RedisJobDefinitionStore;var init_redis_job_definition_store=__esm({"libs/sdk/src/job/store/redis-job-definition.store.ts"(){"use strict";RedisJobDefinitionStore=class{client;keyPrefix;logger;ownsClient;disposed=false;constructor(client,logger,keyPrefix="mcp:jobs:def:",options={}){this.client=client;this.logger=logger;this.keyPrefix=keyPrefix;this.ownsClient=options.ownsClient??false}safeParse(raw,jobId,kind){try{return JSON.parse(raw)}catch(e){const message=e instanceof Error?e.message:String(e);this.logger.error(`[RedisJobDefinitionStore] Failed to parse ${kind} definition for "${jobId}": ${message}; payloadLength=${raw.length}`);return null}}jobKey(jobId){return`${this.keyPrefix}job:${jobId}`}workflowKey(wfId){return`${this.keyPrefix}wf:${wfId}`}async saveDefinition(record){await this.client.set(this.jobKey(record.provide),JSON.stringify(record));await this.client.sadd(`${this.keyPrefix}jobs`,record.provide)}async getDefinition(jobId){const raw=await this.client.get(this.jobKey(jobId));if(!raw)return null;return this.safeParse(raw,jobId,"job")}async listDefinitions(){const ids=await this.client.smembers(`${this.keyPrefix}jobs`);const records=await Promise.all(ids.map(id=>this.getDefinition(id)));return records.filter(r=>r!==null)}async removeDefinition(jobId){const existed=await this.client.del(this.jobKey(jobId));await this.client.srem(`${this.keyPrefix}jobs`,jobId);return existed>0}async saveWorkflowDefinition(record){await this.client.set(this.workflowKey(record.provide),JSON.stringify(record));await this.client.sadd(`${this.keyPrefix}workflows`,record.provide)}async getWorkflowDefinition(wfId){const raw=await this.client.get(this.workflowKey(wfId));if(!raw)return null;return this.safeParse(raw,wfId,"workflow")}async listWorkflowDefinitions(){const ids=await this.client.smembers(`${this.keyPrefix}workflows`);const records=await Promise.all(ids.map(id=>this.getWorkflowDefinition(id)));return records.filter(r=>r!==null)}async removeWorkflowDefinition(wfId){const existed=await this.client.del(this.workflowKey(wfId));await this.client.srem(`${this.keyPrefix}workflows`,wfId);return existed>0}async dispose(){if(this.disposed)return;this.disposed=true;if(!this.ownsClient)return;try{if(typeof this.client.quit==="function"){await this.client.quit()}else if(typeof this.client.disconnect==="function"){this.client.disconnect()}}catch(e){this.logger.warn(`[RedisJobDefinitionStore] dispose: failed to close redis client: ${e.message}`)}}}}});var StorageJobDefinitionStore;var init_storage_job_definition_store=__esm({"libs/sdk/src/job/store/storage-job-definition.store.ts"(){"use strict";StorageJobDefinitionStore=class{constructor(storage){this.storage=storage}storage;async saveDefinition(record){await this.storage.set(`job:${record.provide}`,JSON.stringify(record))}async getDefinition(jobId){return this.read(`job:${jobId}`)}async listDefinitions(){return this.list("job:*")}async removeDefinition(jobId){return this.storage.delete(`job:${jobId}`)}async saveWorkflowDefinition(record){await this.storage.set(`wf:${record.provide}`,JSON.stringify(record))}async getWorkflowDefinition(wfId){return this.read(`wf:${wfId}`)}async listWorkflowDefinitions(){return this.list("wf:*")}async removeWorkflowDefinition(wfId){return this.storage.delete(`wf:${wfId}`)}async dispose(){await this.storage.disconnect()}async read(key){const raw=await this.storage.get(key);return raw?JSON.parse(raw):null}async list(pattern){const keys=await this.storage.keys(pattern);if(keys.length===0)return[];const values=await this.storage.mget(keys);return values.filter(raw=>raw!==null).map(raw=>JSON.parse(raw))}}}});import{createRedisClient as createRedisClient2,createStorage as createStorage3,StorageConfigError as StorageConfigError2}from"@frontmcp/utils";async function createJobDefinitionStore(options,logger){const keyPrefix=options?.keyPrefix??"mcp:jobs:def:";const effectiveLogger=logger??noopLogger;if(options?.sqlite){const storage=await createStorage3({type:"sqlite",sqlite:options.sqlite,prefix:keyPrefix,fallback:"error"});return{store:new StorageJobDefinitionStore(storage),type:"sqlite"}}if(options?.redis){refuseVercelKvJobStore(options.redis);try{const{url,host,port,password,db,tls}=options.redis;const client=createRedisClient2({url,host,port,password,db,tls,label:"JobDefinitionStore",logger:effectiveLogger});return{store:new RedisJobDefinitionStore(client,effectiveLogger,keyPrefix,{ownsClient:true}),type:"redis"}}catch(err){if(err instanceof StorageConfigError2)throw err;effectiveLogger.warn(`Failed to create Redis job definition store, falling back to memory: ${err}`)}}return{store:new MemoryJobDefinitionStore,type:"memory"}}var noopFn,noopLogger;var init_job_definition_store_factory=__esm({"libs/sdk/src/job/store/job-definition-store.factory.ts"(){"use strict";init_job_state_store_factory();init_memory_job_definition_store();init_redis_job_definition_store();init_storage_job_definition_store();noopFn=()=>{};noopLogger={child:()=>noopLogger,get verbose(){return noopFn},get debug(){return noopFn},get info(){return noopFn},get warn(){return noopFn},get error(){return noopFn}}}});import{z as z82}from"@frontmcp/lazy-zod";var CancelJobTool;var init_cancel_job_tool=__esm({"libs/sdk/src/job/tools/cancel-job.tool.ts"(){"use strict";init_common();init_errors();init_job_run_access();CancelJobTool=class extends ToolContext{async execute(input){const executionManager=jobExecutionManagerOf(this.scope);if(!executionManager){return this.fail(new GenericServerError("Jobs system is not enabled"))}const record=await executionManager.getStatus(input.runId);if(!record||!await mayAccessRun(this.scope,record,"delete",this.authInfo)){return this.fail(new JobRunNotFoundError(input.runId))}await executionManager.cancel(input.runId);return{runId:input.runId,state:"cancelled"}}};CancelJobTool=__decorateClass([Tool({name:"cancel_job",description:"Cancel a job run by runId. The cancel is kept in the job store, so the process running it stops it, and its cleanup runs.",inputSchema:{runId:z82.string().describe("Run ID returned from execute_job")},outputSchema:{runId:z82.string(),state:z82.literal("cancelled")}})],CancelJobTool)}});import{internalZ as z83}from"@frontmcp/lazy-zod";var ExecuteJobTool;var init_execute_job_tool=__esm({"libs/sdk/src/job/tools/execute-job.tool.ts"(){"use strict";init_common();init_errors();init_job_run_access();ExecuteJobTool=class extends ToolContext{async execute(input){const scope=this.scope;const executionManager=scope._jobExecutionManager;const jobRegistry=this.scope.jobs;if(!executionManager||!jobRegistry){return this.fail(new Error("Jobs system is not enabled"))}const job=jobRegistry.findByName(input.name);if(!job){return this.fail(new JobNotAuthorizedError(input.name))}const result=await executionManager.executeJob(job,input.input??{},{background:input.background,sessionId:this.authInfo.sessionId,authInfo:this.authInfo,context:this.context,authoritiesContextBuilder:this.scope.authoritiesContextBuilder});return{...result,uri:jobRunUri(result.runId)}}};ExecuteJobTool=__decorateClass([Tool({name:"execute_job",description:"Execute a registered job by name. Supports inline (synchronous) and background execution; a background run answers at once with its runId and the job://runs/{runId} resource to read or subscribe to.",inputSchema:{name:z83.string().describe("Job name to execute"),input:z83.record(z83.string(),z83.unknown()).optional().describe("Job input data"),background:z83.boolean().optional().default(false).describe("Run in background (returns runId for status polling)")},outputSchema:{runId:z83.string(),state:z83.string(),uri:z83.string().describe("The job://runs/{runId} resource of the run"),result:z83.unknown().optional(),logs:z83.array(z83.string()).optional()}})],ExecuteJobTool)}});import{internalZ as z84}from"@frontmcp/lazy-zod";var GetJobStatusTool;var init_get_job_status_tool=__esm({"libs/sdk/src/job/tools/get-job-status.tool.ts"(){"use strict";init_common();init_errors();init_job_run_access();GetJobStatusTool=class extends ToolContext{async execute(input){const scope=this.scope;const executionManager=scope._jobExecutionManager;if(!executionManager){return this.fail(new GenericServerError("Jobs system is not enabled"))}const record=await executionManager.getStatus(input.runId);if(!record||!await mayAccessRun(this.scope,record,"read",this.authInfo)){return this.fail(new InvalidInputError(`Run "${input.runId}" not found`))}return{runId:record.runId,jobName:record.jobName,state:record.state,result:record.result,error:record.error,startedAt:record.startedAt,completedAt:record.completedAt,attempt:record.attempt,logs:record.logs}}};GetJobStatusTool=__decorateClass([Tool({name:"get_job_status",description:"Get the execution status of a job run by runId.",inputSchema:{runId:z84.string().describe("Run ID returned from execute_job or execute_workflow")},outputSchema:{runId:z84.string(),jobName:z84.string(),state:z84.string(),result:z84.unknown().optional(),error:z84.object({message:z84.string(),name:z84.string()}).optional(),startedAt:z84.number(),completedAt:z84.number().optional(),attempt:z84.number(),logs:z84.array(z84.string())}})],GetJobStatusTool)}});import{internalZ as z85}from"@frontmcp/lazy-zod";var ListJobsTool;var init_list_jobs_tool=__esm({"libs/sdk/src/job/tools/list-jobs.tool.ts"(){"use strict";init_common();init_job_permission_guard();ListJobsTool=class extends ToolContext{async execute(input){const jobRegistry=this.scope.jobs;if(!jobRegistry){return{jobs:[],count:0}}const jobs=jobRegistry.search(input.query,{tags:input.tags,labels:input.labels});const visible=[];for(const job of jobs){if(await this.maySee(job))visible.push(job)}const mapped=visible.map(j=>({name:j.name,description:j.metadata.description,tags:j.getTags(),labels:j.getLabels(),inputSchema:j.getInputJsonSchema()??void 0}));return{jobs:mapped,count:mapped.length}}async maySee(job){const permissions=job.metadata.permissions;const builder=this.scope.authoritiesContextBuilder;if(!await JobPermissionGuard.check(permissions,"list",this.authInfo,builder))return false;return JobPermissionGuard.check(permissions,"execute",this.authInfo,builder)}};ListJobsTool=__decorateClass([Tool({name:"list_jobs",description:"List registered jobs with optional filtering by tags or labels.",inputSchema:{tags:z85.array(z85.string()).optional().describe("Filter by tags"),labels:z85.record(z85.string(),z85.string()).optional().describe("Filter by labels"),query:z85.string().optional().describe("Search query for name/description")},outputSchema:{jobs:z85.array(z85.object({name:z85.string(),description:z85.string().optional(),tags:z85.array(z85.string()).optional(),labels:z85.record(z85.string(),z85.string()).optional(),inputSchema:z85.record(z85.string(),z85.unknown()).optional()})),count:z85.number()},hideFromDiscovery:true})],ListJobsTool)}});import{internalZ as z86}from"@frontmcp/lazy-zod";var RegisterJobTool;var init_register_job_tool=__esm({"libs/sdk/src/job/tools/register-job.tool.ts"(){"use strict";init_common();init_errors();RegisterJobTool=class extends ToolContext{async execute(input){const jobRegistry=this.scope.jobs;if(!jobRegistry){return this.fail(new Error("Jobs system is not enabled"))}if(!this.dynamicRegistrationEnabled()){return this.fail(new DynamicJobRegistrationDisabledError("job"))}const existing=jobRegistry.findByName(input.name);if(existing){return this.fail(new Error(`Job "${input.name}" already exists`))}const jobId=input.name;jobRegistry.registerDynamic({kind:"DYNAMIC",provide:jobId,metadata:{id:jobId,name:input.name,description:input.description,inputSchema:input.inputSchema??{},outputSchema:input.outputSchema??{},tags:input.tags},script:input.script,registeredBy:this.authInfo?.["sub"]??"anonymous",registeredAt:Date.now()});return{success:true,jobId}}dynamicRegistrationEnabled(){const jobs=this.scope.metadata?.jobs;return jobs?.allowDynamicRegistration===true}};RegisterJobTool=__decorateClass([Tool({name:"register_job",description:"Register a dynamic job that runs in a sandboxed environment.",inputSchema:{name:z86.string().describe("Job name"),description:z86.string().optional().describe("Job description"),script:z86.string().describe("JavaScript source code for the job"),inputSchema:z86.record(z86.string(),z86.unknown()).optional().describe("JSON Schema for input"),outputSchema:z86.record(z86.string(),z86.unknown()).optional().describe("JSON Schema for output"),tags:z86.array(z86.string()).optional().describe("Tags for categorization")},outputSchema:{success:z86.boolean(),jobId:z86.string()},hideFromDiscovery:true})],RegisterJobTool)}});import{internalZ as z87}from"@frontmcp/lazy-zod";var RemoveJobTool;var init_remove_job_tool=__esm({"libs/sdk/src/job/tools/remove-job.tool.ts"(){"use strict";init_common();init_errors();init_job_permission_guard();RemoveJobTool=class extends ToolContext{async execute(input){const jobRegistry=this.scope.jobs;if(!jobRegistry){return this.fail(new Error("Jobs system is not enabled"))}const job=jobRegistry.findByName(input.name);if(!job){return this.fail(new JobNotAuthorizedError(input.name))}const allowed=await JobPermissionGuard.check(job.metadata.permissions,"delete",this.authInfo,this.scope.authoritiesContextBuilder);if(!allowed){return this.fail(new JobNotAuthorizedError(input.name))}if(!job.isDynamic()){return this.fail(new Error(`Job "${input.name}" is not a dynamic job and cannot be removed`))}const removed=jobRegistry.removeDynamic(input.name);return{success:removed,message:removed?`Job "${input.name}" removed`:`Failed to remove job "${input.name}"`}}};RemoveJobTool=__decorateClass([Tool({name:"remove_job",description:"Remove a dynamic job by name.",inputSchema:{name:z87.string().describe("Job name to remove")},outputSchema:{success:z87.boolean(),message:z87.string()},hideFromDiscovery:true})],RemoveJobTool)}});var job_scope_helper_exports={};__export(job_scope_helper_exports,{jobsServerStore:()=>jobsServerStore,registerJobCapabilities:()=>registerJobCapabilities,resolveJobsStore:()=>resolveJobsStore});function resolveJobsStore(store,topLevel){if(store===false)return void 0;if(store?.redis||store?.sqlite)return store;const redis=topLevel.redis;if(redis&&!isVercelKv(redis)){const keyPrefix=store?.keyPrefix??(redis.keyPrefix===void 0?void 0:`${redis.keyPrefix}jobs:`);return{...store,redis,...keyPrefix===void 0?{}:{keyPrefix}}}if(topLevel.sqlite)return{...store,sqlite:topLevel.sqlite};return store}function jobsServerStore(store,topLevel){if(store===false)return void 0;if(store?.sqlite)return"jobs.store.sqlite";if(store?.redis)return"jobs.store.redis";if(topLevel.redis&&!isVercelKv(topLevel.redis))return"redis";return topLevel.sqlite?"sqlite":void 0}function isVercelKv(redis){return"provider"in redis&&redis.provider==="vercel-kv"}async function registerJobCapabilities(args){const{providers,flowRegistry,owner,jobsList,jobProviders,workflowsList,jobsConfig,logger,notifyFn}=args;const{entryServer=false,jobWorker=false}=args;await flowRegistry.registryFlows([ExecuteJobFlow]);const{redis,sqlite,keyPrefix="mcp:jobs:"}=jobsConfig.store||{};const{store:stateStore,type:stateStoreType}=await createJobStateStore({redis,sqlite,keyPrefix},logger);logger.info(`Job state store: ${stateStoreType}`);const{store:definitionStore,type:defStoreType}=await createJobDefinitionStore({redis,sqlite,keyPrefix:keyPrefix+"def:"},logger);logger.info(`Job definition store: ${defStoreType}`);const dynamicJobs=await definitionStore.listDefinitions();const dynamicWorkflows=await definitionStore.listWorkflowDefinitions();const jobRegistry=new JobRegistry(providers,jobsList,owner,jobProviders);await jobRegistry.ready;for(const dynJob of dynamicJobs){jobRegistry.registerDynamic(dynJob)}const workflowRegistry=new WorkflowRegistry(providers,workflowsList,owner);await workflowRegistry.ready;for(const dynWf of dynamicWorkflows){workflowRegistry.registerDynamic(dynWf)}try{assertRunnersAvailable(jobRegistry.getJobs(),jobsConfig.runner)}catch(error){await stateStore.dispose();await definitionStore.dispose();throw error}const scope=providers.getActiveScope();const completions=completionEventsOf(scope);const executionManager=new JobExecutionManager(stateStore,logger,async data=>{await notifyFn?.(data);await publishJobCompletion(data,stateStore,completions)},scope,{defaultTimeoutMs:jobsConfig.defaultTimeoutMs,admission:jobsConfig.admission?new JobAdmission(jobsConfig.admission):void 0,cancelPollMs:stateStoreType==="memory"?void 0:jobWorker?DETACHED_FLUSH_MS:CANCEL_POLL_MS,runner:jobsConfig.runner,findJob:name51=>jobRegistry.findByName(name51),detachedUnavailable:detachedUnavailable(stateStoreType,!entryServer&&!jobWorker)});scope.onDispose(async()=>{await executionManager.dispose(providers.shutdownHookTimeoutMs);await stateStore.dispose();await definitionStore.dispose()});scope.resources.registerDynamicResource(JobRunResource);if(stateStoreType!=="memory"&&!jobWorker){void executionManager.reconcile().catch(error=>logger.warn(`Could not reconcile the job runs in the store: ${String(error)}`))}const managementTools=[ListJobsTool,ExecuteJobTool,GetJobStatusTool,CancelJobTool,RemoveJobTool,ListWorkflowsTool,ExecuteWorkflowTool,GetWorkflowStatusTool,RemoveWorkflowTool];if(jobsConfig.allowDynamicRegistration===true){managementTools.push(RegisterJobTool,RegisterWorkflowTool);logger.warn("Dynamic job registration is ENABLED: register_job/register_workflow accept a raw script and register it as an executable job.")}logger.info(`Jobs initialized: ${jobRegistry.getJobs().length} jobs, ${workflowRegistry.getWorkflows().length} workflows`);return{jobRegistry,workflowRegistry,executionManager,stateStore,definitionStore,managementTools}}function detachedUnavailable(storeType,inProcess){if(inProcess){return{why:"this server was not started by an entry a detached process can run again (bootstrap(), runStdio(), runUnixSocket() or @FrontMcp), as an in-process server (create(), createDirect(), connect(), the generated CLI) is not",remedy:"Start the server from its entry (node dist/main.js, frontmcp dev), or set runner: 'inline' on the job"}}if(storeType==="memory"){return{why:"job runs are kept in this process memory, which a detached process cannot read",remedy:"Give jobs a store other processes share: jobs.store.sqlite, or a top-level sqlite or redis without jobs.store: false"}}return void 0}async function publishJobCompletion(data,stateStore,completions){const{type,state,runId}=data;if(type!=="job:status"&&type!=="workflow:status")return;const status=completionStatusOf(state);if(!status||typeof runId!=="string")return;const run=await stateStore.getRun(runId);if(!run)return;const workflowName=type==="workflow:status"?run.workflowName:void 0;completions.jobs.emit({jobName:workflowName??run.jobName,jobId:run.jobId,status,...run.completedAt!==void 0?{durationMs:run.completedAt-run.startedAt}:{},...status==="success"?{output:completionOutputText(run.result)}:{error:run.error?.message},attempt:run.attempt,...run.sessionId?{sessionId:run.sessionId}:{}})}function completionStatusOf(state){switch(state){case"completed":return"success";case"failed":case"interrupted":return"error";case"timed_out":return"timeout";case"cancelled":return"cancelled";default:return void 0}}var CANCEL_POLL_MS;var init_job_scope_helper=__esm({"libs/sdk/src/job/job-scope.helper.ts"(){"use strict";init_completion_events();init_execute_workflow_tool();init_get_workflow_status_tool();init_list_workflows_tool();init_register_workflow_tool();init_remove_workflow_tool();init_workflow_registry();init_job_execution_manager();init_execute_job_flow();init_job_admission();init_job_registry();init_job_run_resource();init_job_runner();init_job_definition_store_factory();init_job_state_store_factory();init_cancel_job_tool();init_execute_job_tool();init_get_job_status_tool();init_list_jobs_tool();init_register_job_tool();init_remove_job_tool();CANCEL_POLL_MS=1e3}});import{getMetadata as getMetadata16,isClass as isClass14}from"@frontmcp/di";import{getRuntimeContext as getRuntimeContext14}from"@frontmcp/utils";function isVercelKv2(redis){return redis?.provider==="vercel-kv"}function redisOf(ownRedis,ownRedisOption,server){return ownRedis?[ownRedisOption,ownRedis]:["redis",server.redis]}function redisElseSqlite([option,redis],server){if(redis)return isVercelKv2(redis)?void 0:option;return server.sqlite?"sqlite":void 0}function tasksServerStore(options){const{tasks}=options;if(tasks?.enabled===false||tasks?.store===false)return void 0;if(tasks?.sqlite)return"tasks.sqlite";return redisElseSqlite(redisOf(tasks?.redis,"tasks.redis",options),options)}function elicitationServerStore(options){const{elicitation}=options;if(!elicitation?.enabled||elicitation.store===false)return void 0;return redisElseSqlite(redisOf(elicitation.redis,"elicitation.redis",options),options)}async function questionsStore(options){const{elicitation}=options;if(!elicitation?.enabled||!elicitation.persistent)return void 0;const questions=await Promise.resolve().then(()=>(init_question_scope_helper(),question_scope_helper_exports));const{storage}=questions.persistentQuestionsSettings(elicitation.persistent,false);return questions.questionsServerStore(storage,options)}function declaredOnApps(options,token){return(options.apps??[]).flatMap(app=>isClass14(app)?getMetadata16(token,app)??[]:[])}async function jobsStore(options){const{jobs}=options;const declared=[...options.jobTypes??[],...options.workflowTypes??[],...declaredOnApps(options,FrontMcpLocalAppTokens.jobs),...declaredOnApps(options,FrontMcpLocalAppTokens.workflows)];if(jobs?.enabled===false||jobs?.enabled!==true&&declared.length===0)return void 0;const{jobsServerStore:jobsServerStore2}=await Promise.resolve().then(()=>(init_job_scope_helper(),job_scope_helper_exports));return jobsServerStore2(jobs?.store,options)}function rateLimitsStore({throttle,auth}){const publicAccess=auth?.publicAccess;const publicRateLimited=publicAccess!==void 0&&publicAccess.rateLimit!==0;const type=throttle?.enabled||publicRateLimited?throttle?.storage?.type:void 0;return type==="redis"||type==="sqlite"?`throttle.storage: { type: '${type}' }`:void 0}function authStore({auth},setting){const value=auth&&setting in auth?auth[setting]:void 0;if(typeof value!=="object"||value===null)return void 0;const{redis,sqlite}=value;if(redis!==void 0)return`auth.${setting}.redis`;return sqlite!==void 0?`auth.${setting}.sqlite`:void 0}function skillsCacheStore({skillsConfig}){const cache2=skillsConfig?.cache;return cache2?.enabled&&cache2.redis?.provider==="redis"?"skillsConfig.cache.redis":void 0}function declaredPluginStores(plugin,options,server){const declare=plugin?.browserStores;return typeof declare==="function"?declare.call(plugin,options,server):[]}function listedPluginStores(item,server){if(isClass14(item))return declaredPluginStores(item,{},server);const{provide,useClass,useValue}=item;if(useClass)return declaredPluginStores(useClass,{},server);const init=typeof useValue==="object"&&useValue!==null?initOptionsOf(useValue):void 0;return init?declaredPluginStores(provide,init.options,server):[]}function refusal2(stores,plugins){const refused2=[...stores,...plugins.map(({plugin,option})=>[plugin,option])].filter(entry=>entry[1]!==void 0);if(refused2.length===0)return void 0;return new BrowserStoreUnavailableError(refused2,Object.fromEntries(plugins.map(({plugin,memory})=>[plugin,memory])))}async function refuseStoresInBrowser(options,runtime=getRuntimeContext14().runtime){if(runtime!=="browser")return;const listed=[...options.plugins??[],...declaredOnApps(options,FrontMcpLocalAppTokens.plugins)];const plugins=listed.flatMap(item=>listedPluginStores(item,options));const error=refusal2([["tasks",tasksServerStore(options)],["elicitation",elicitationServerStore(options)],["questions",await questionsStore(options)],["jobs",await jobsStore(options)],["rateLimits",rateLimitsStore(options)],["authTokens",authStore(options,"tokenStorage")],["secureStore",authStore(options,"secureStore")],["skillsCache",skillsCacheStore(options)]],plugins);if(error)throw error}function refuseServerStoresInBrowser(stores,runtime=getRuntimeContext14().runtime){if(runtime!=="browser")return;const error=refusal2(Object.entries(stores),[]);if(error)throw error}function refusePluginStoreInBrowser(store,runtime=getRuntimeContext14().runtime){refusePluginStoresInBrowser([store],runtime)}function refusePluginStoresInBrowser(stores,runtime=getRuntimeContext14().runtime){if(runtime!=="browser")return;const error=refusal2([],stores);if(error)throw error}var init_browser_stores=__esm({"libs/sdk/src/scope/browser-stores.ts"(){"use strict";init_dynamic_plugin();init_tokens();init_errors()}});var SkillValidationError;var init_skill_validation_error=__esm({"libs/sdk/src/skill/errors/skill-validation.error.ts"(){"use strict";init_errors();SkillValidationError=class _SkillValidationError extends PublicMcpError{mcpErrorCode=MCP_ERROR_CODES.INVALID_PARAMS;failedSkills;report;constructor(message,report){super(message);this.name="SkillValidationError";this.failedSkills=report.results.filter(r=>r.status==="failed");this.report=report}static fromReport(report){const failedSkills=report.results.filter(r=>r.status==="failed");const message=failedSkills.length===1?`Skill '${failedSkills[0].skillName}' failed tool validation: missing tools [${failedSkills[0].missingTools.join(", ")}]`:`${failedSkills.length} skill(s) failed tool validation: ${failedSkills.map(s=>`'${s.skillName}' (missing tools [${s.missingTools.join(", ")}])`).join(", ")}`;return new _SkillValidationError(message,report)}getPublicMessage(){return this.message}toJsonRpcError(){return{code:this.mcpErrorCode,message:this.getPublicMessage(),data:{failedSkills:this.failedSkills.map(s=>({skillId:s.skillId,skillName:s.skillName,missingTools:s.missingTools,hiddenTools:s.hiddenTools})),totalSkills:this.report.totalSkills,failedCount:this.report.failedCount,warningCount:this.report.warningCount}}}}}});var SkillToolValidator;var init_skill_validator=__esm({"libs/sdk/src/skill/skill-validator.ts"(){"use strict";SkillToolValidator=class{toolRegistry;constructor(toolRegistry){this.toolRegistry=toolRegistry}validate(toolNames,requiredTools){if(toolNames.length===0){return{available:[],missing:[],hidden:[],complete:true}}const allTools=this.toolRegistry.getTools(true);const allToolNames=new Set(allTools.map(t=>t.name));const visibleTools=this.toolRegistry.getTools(false);const visibleToolNames=new Set(visibleTools.map(t=>t.name));const available=[];const missing=[];const hidden=[];for(const toolName of toolNames){if(visibleToolNames.has(toolName)){available.push(toolName)}else if(allToolNames.has(toolName)){hidden.push(toolName)}else{missing.push(toolName)}}let complete=true;if(requiredTools&&requiredTools.size>0){for(const reqTool of requiredTools){if(!visibleToolNames.has(reqTool)){complete=false;break}}}else{complete=missing.length===0}return{available,missing,hidden,complete}}formatWarning(result,skillName){const issues=[];if(result.missing.length>0){issues.push(`missing tools: ${result.missing.join(", ")}`)}if(result.hidden.length>0){issues.push(`hidden tools: ${result.hidden.join(", ")}`)}if(issues.length===0){return void 0}return`Skill "${skillName}" references ${issues.join("; ")}. Some functionality may be limited.`}isToolAvailable(toolName){const visibleTools=this.toolRegistry.getTools(false);return visibleTools.some(t=>t.name===toolName)}toolExists(toolName){const allTools=this.toolRegistry.getTools(true);return allTools.some(t=>t.name===toolName)}}}});var SkillEmitter;var init_skill_events=__esm({"libs/sdk/src/skill/skill.events.ts"(){"use strict";SkillEmitter=class{listeners=new Set;on(listener){this.listeners.add(listener);return()=>this.listeners.delete(listener)}emit(event){for(const listener of[...this.listeners]){try{listener(event)}catch(err){console.error("SkillEmitter listener error:",err instanceof Error?err.message:"Unknown error")}}}get listenerCount(){return this.listeners.size}clear(){this.listeners.clear()}}}});var skill_md_parser_exports={};__export(skill_md_parser_exports,{loadSkillMdFile:()=>loadSkillMdFile,parseSkillMdFrontmatter:()=>parseSkillMdFrontmatter,skillMdFrontmatterToMetadata:()=>skillMdFrontmatterToMetadata,stripFrontmatter:()=>stripFrontmatter});import{readFile as readFile4}from"@frontmcp/utils";function parseSkillMdFrontmatter(content){const trimmed=content.trimStart();if(!trimmed.startsWith("---")){return{frontmatter:{},body:content}}const closingIndex=trimmed.indexOf("\n---",3);if(closingIndex===-1){return{frontmatter:{},body:content}}const yamlBlock=trimmed.substring(3,closingIndex).trim();const afterClose=closingIndex+4;const bodyStart=trimmed[afterClose]==="\n"?afterClose+1:afterClose;const body=trimmed.substring(bodyStart);let frontmatter={};try{const parsed=load(yamlBlock);if(typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed)){frontmatter=parsed}}catch{return{frontmatter:{},body:content}}return{frontmatter,body}}function skillMdFrontmatterToMetadata(frontmatter,body){const result={};if(typeof frontmatter["id"]==="string")result.id=frontmatter["id"];if(typeof frontmatter["name"]==="string")result.name=frontmatter["name"];if(typeof frontmatter["description"]==="string")result.description=frontmatter["description"];if(typeof frontmatter["license"]==="string")result.license=frontmatter["license"];if(typeof frontmatter["compatibility"]==="string")result.compatibility=frontmatter["compatibility"];if(typeof frontmatter["category"]==="string")result.category=frontmatter["category"];const rating=frontmatter["rating"];if(typeof rating==="number"&&Number.isFinite(rating)&&rating>=0&&rating<=5){result.rating=rating}if(Array.isArray(frontmatter["skillPath"])){const segments=frontmatter["skillPath"].filter(s=>typeof s==="string").map(s=>s.trim()).filter(s=>s.length>0);if(segments.length>0)result.skillPath=segments}if(typeof frontmatter["resources"]==="object"&&frontmatter["resources"]!==null){const r=frontmatter["resources"];const resources={};if(typeof r["scripts"]==="string")resources.scripts=r["scripts"];if(typeof r["references"]==="string")resources.references=r["references"];if(typeof r["assets"]==="string")resources.assets=r["assets"];if(typeof r["examples"]==="string")resources.examples=r["examples"];if(Object.keys(resources).length>0)result.resources=resources}const availableWhen=frontmatter["availableWhen"]??frontmatter["available-when"];if(typeof availableWhen==="object"&&availableWhen!==null&&!Array.isArray(availableWhen)){result.availableWhen=availableWhen}if(typeof frontmatter["metadata"]==="object"&&frontmatter["metadata"]!==null){const meta=frontmatter["metadata"];const specMeta={};for(const[key,val]of Object.entries(meta)){if(typeof val==="string")specMeta[key]=val;else specMeta[key]=JSON.stringify(val)}result.specMetadata=specMeta}if(typeof frontmatter["allowed-tools"]==="string"){result.allowedTools=frontmatter["allowed-tools"]}if(Array.isArray(frontmatter["tags"])){result.tags=frontmatter["tags"].filter(t=>typeof t==="string")}if(Array.isArray(frontmatter["tools"])){result.tools=frontmatter["tools"].map(t=>{if(typeof t==="string")return t;if(typeof t==="object"&&t!==null&&"name"in t&&typeof t["name"]==="string"){const ref={name:t["name"]};if(typeof t["purpose"]==="string")ref.purpose=t["purpose"];if(typeof t["required"]==="boolean")ref.required=t["required"];return ref}return void 0}).filter(t=>t!==void 0)}if(Array.isArray(frontmatter["parameters"])){result.parameters=frontmatter["parameters"].filter(p=>typeof p==="object"&&p!==null&&"name"in p).map(p=>{const param={name:String(p["name"])};if(typeof p["description"]==="string")param.description=p["description"];if(typeof p["required"]==="boolean")param.required=p["required"];if(typeof p["type"]==="string")param.type=p["type"];if(p["default"]!==void 0)param.default=p["default"];return param})}if(Array.isArray(frontmatter["examples"])){result.examples=frontmatter["examples"].filter(e=>typeof e==="object"&&e!==null&&"scenario"in e).map(e=>{const example={scenario:String(e["scenario"])};if(typeof e["parameters"]==="object"&&e["parameters"]!==null){example.parameters=e["parameters"]}if(typeof e["expectedOutcome"]==="string")example.expectedOutcome=e["expectedOutcome"];if(typeof e["expected-outcome"]==="string")example.expectedOutcome=e["expected-outcome"];return example})}if(typeof frontmatter["priority"]==="number"){result.priority=frontmatter["priority"]}const vis=frontmatter["visibility"];if(vis==="mcp"||vis==="http"||vis==="both"){result.visibility=vis}const hide=frontmatter["hideFromDiscovery"]??frontmatter["hide-from-discovery"];if(typeof hide==="boolean"){result.hideFromDiscovery=hide}const tv=frontmatter["toolValidation"]??frontmatter["tool-validation"];if(tv==="strict"||tv==="warn"||tv==="ignore"){result.toolValidation=tv}const knownKeys=new Set(["id","name","description","license","compatibility","category","rating","skillPath","resources","availableWhen","available-when","metadata","allowed-tools","tags","tools","parameters","examples","priority","visibility","hideFromDiscovery","hide-from-discovery","toolValidation","tool-validation"]);for(const[key,val]of Object.entries(frontmatter)){if(!knownKeys.has(key)&&val!==void 0){if(!result.specMetadata)result.specMetadata={};result.specMetadata[key]=typeof val==="string"?val:JSON.stringify(val)}}if(body.length>0){result.instructions=body}return result}async function loadSkillMdFile(filePath,resources){const content=await readFile4(filePath,"utf-8");const{frontmatter,body}=parseSkillMdFrontmatter(content);const metadata=skillMdFrontmatterToMetadata(frontmatter,body);if(resources){metadata.resources=resources}return metadata}function stripFrontmatter(content){const{body}=parseSkillMdFrontmatter(content);return body}var init_skill_md_parser=__esm({"libs/sdk/src/skill/skill-md-parser.ts"(){"use strict";init_js_yaml()}});import{depsOfClass as depsOfClass8,getMetadata as getMetadata17,isClass as isClass15}from"@frontmcp/di";import{fileExists as fileExists4,isAbsolute as isAbsolute2,pathJoin as pathJoin2,readdir,readFile as readFile5,stat as stat2}from"@frontmcp/utils";function collectSkillMetadata(cls){const extended=getMetadata17(extendedSkillMetadata,cls);const seed=extended?{...extended}:{};return Object.entries(FrontMcpSkillTokens).reduce((metadata,[key,token])=>{const value=getMetadata17(token,cls);if(value!==void 0){return Object.assign(metadata,{[key]:value})}return metadata},seed)}function normalizeSkill(item){if(isExternalEntryRecord(item)){throw unsupportedExternalEntry("skill",item)}if(isSkillRecord(item)){return item}if(isClass15(item)){const metadata=collectSkillMetadata(item);if(!metadata.name){const className=item.constructor?.name??String(item);throw new InvalidSkillError(className,"Class must be decorated with @Skill decorator and have a name property.")}const callerDir=getMetadata17(skillCallerDir,item);return{kind:"CLASS_TOKEN",provide:item,metadata,...callerDir?{callerDir}:{}}}const name51=typeof item==="object"&&item!==null?item["name"]:String(item);throw new InvalidSkillError(String(name51??"unknown"),"Expected a class decorated with @Skill or a skill() helper result.")}function isSkillRecord(item){if(typeof item!=="object"||item===null){return false}const record=item;if(!record["kind"]||typeof record["kind"]!=="string"){return false}const validKinds=["CLASS_TOKEN","VALUE","FILE","ESM","REMOTE"];if(!validKinds.includes(record["kind"])){return false}if(!record["provide"]||!record["metadata"]){return false}return true}function skillDiscoveryDeps(rec){switch(rec.kind){case"CLASS_TOKEN":return depsOfClass8(rec.provide,"discovery");case"VALUE":case"FILE":case"ESM":case"REMOTE":return[]}}async function loadInstructions(source,basePath){if(isInlineInstructions(source)){return source}if(isFileInstructions(source)){const filePath=isAbsolute2(source.file)?source.file:basePath?pathJoin2(basePath,source.file):source.file;const content=await readFile5(filePath,"utf-8");const{stripFrontmatter:stripFrontmatter2}=await Promise.resolve().then(()=>(init_skill_md_parser(),skill_md_parser_exports));return stripFrontmatter2(content)}if(isUrlInstructions(source)){const response=await fetch(source.url);if(!response.ok){throw new SkillInstructionFetchError(source.url,response.status,response.statusText)}return response.text()}throw new InvalidInstructionSourceError}function buildSkillContent(metadata,instructions,resolvedReferences2,resolvedExamples){let finalInstructions=instructions;if(resolvedReferences2&&resolvedReferences2.length>0){finalInstructions+=buildReferencesTable(resolvedReferences2)}if(resolvedExamples&&resolvedExamples.length>0){finalInstructions+=buildExamplesTable(resolvedExamples)}return{id:metadata.id??metadata.name,name:metadata.name,description:metadata.description,instructions:finalInstructions,tools:normalizeToolRefs(metadata.tools),parameters:metadata.parameters,examples:metadata.examples,license:metadata.license,compatibility:metadata.compatibility,specMetadata:metadata.specMetadata,allowedTools:metadata.allowedTools,resources:metadata.resources,resolvedReferences:resolvedReferences2,resolvedExamples}}function buildReferencesTable(refs){const lines=["","","## References","","| Reference | Description |","| --------- | ----------- |"];for(const ref of refs){lines.push(`| \`${ref.name}\` | ${ref.description} |`)}return lines.join("\n")}function buildExamplesTable(examples){const lines=["","","## Examples","","| Example | Reference | Level | Description |","| ------- | --------- | ----- | ----------- |"];for(const ex of examples){lines.push(`| \`${ex.name}\` | \`${ex.reference}\` | ${ex.level} | ${ex.description} |`)}return lines.join("\n")}async function resolveExamples(examplesDir){if(!await fileExists4(examplesDir))return void 0;let refDirs;try{refDirs=(await readdir(examplesDir)).sort()}catch{return void 0}const examples=[];for(const refDir of refDirs){const refPath=`${examplesDir}/${refDir}`;try{const s=await stat2(refPath);if(!s.isDirectory())continue}catch{continue}let files;try{files=(await readdir(refPath)).filter(f=>f.endsWith(".md")).sort()}catch{continue}for(const file of files){const content=await readFile5(`${refPath}/${file}`,"utf-8");const filenameWithoutExt=file.replace(/\.md$/,"");let name51=filenameWithoutExt;let description="";let reference=refDir;let level="basic";const fmMatch=content.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(fmMatch){const fmLines=fmMatch[1].split(/\r?\n/);for(const line of fmLines){const colonIdx=line.indexOf(":");if(colonIdx===-1)continue;const key=line.slice(0,colonIdx).trim();const val=line.slice(colonIdx+1).trim().replace(/^["']|["']$/g,"");if(key==="name"&&val)name51=val;if(key==="description"&&val)description=val;if(key==="reference"&&val)reference=val;if(key==="level"&&val)level=val}}if(!description){const body=fmMatch?content.substring(content.indexOf("---",3)+3).trim():content.trim();description=extractFirstParagraph(body)}examples.push({name:name51,description,reference,level,filename:`${refDir}/${file}`})}}return examples.length>0?examples:void 0}async function resolveReferences(refsDir){if(!await fileExists4(refsDir))return void 0;let files;try{files=(await readdir(refsDir)).filter(f=>f.endsWith(".md")).sort()}catch{return void 0}if(files.length===0)return void 0;const refs=[];for(const file of files){const content=await readFile5(`${refsDir}/${file}`,"utf-8");const filenameWithoutExt=file.replace(/\.md$/,"");let name51=filenameWithoutExt;let description="";const fmMatch=content.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(fmMatch){const fmLines=fmMatch[1].split(/\r?\n/);for(const line of fmLines){const colonIdx=line.indexOf(":");if(colonIdx===-1)continue;const key=line.slice(0,colonIdx).trim();const val=line.slice(colonIdx+1).trim().replace(/^["']|["']$/g,"");if(key==="name"&&val)name51=val;if(key==="description"&&val)description=val}}if(!description){const body=fmMatch?content.substring(content.indexOf("---",3)+3).trim():content.trim();description=extractFirstParagraph(body)}refs.push({name:name51,description,filename:file})}return refs}function extractFirstParagraph(body){const lines=body.split(/\r?\n/);let foundHeading=false;const paragraphLines=[];for(const line of lines){const trimmed=line.trim();if(!foundHeading&&trimmed.startsWith("#")){foundHeading=true;continue}if(foundHeading){if(trimmed===""){if(paragraphLines.length>0)break;continue}if(trimmed.startsWith("#")||trimmed.startsWith("|")||trimmed.startsWith("-"))break;paragraphLines.push(trimmed)}}return paragraphLines.join(" ").slice(0,200)||""}function normalizeToolRefs(tools){if(!tools)return[];return tools.map(tool=>{try{const normalized2=normalizeToolRef(tool);return{name:normalized2.name,purpose:normalized2.purpose,required:normalized2.required}}catch{if(typeof tool==="string")return{name:tool};if(typeof tool==="function")return{name:tool.name??"unknown"};if("name"in tool){const obj=tool;return{name:obj.name,purpose:obj.purpose,required:obj.required}}if("tool"in tool){const obj=tool;return{name:obj.tool.name??"unknown",purpose:obj.purpose,required:obj.required}}return{name:"unknown"}}})}function formatSkillForLLM(skill,availableTools,missingTools){const parts=[];parts.push(`# Skill: ${skill.name}`);parts.push("");parts.push(skill.description);parts.push("");if(skill.license){parts.push(`**License:** ${skill.license}`);parts.push("")}if(skill.compatibility){parts.push(`**Compatibility:** ${skill.compatibility}`);parts.push("")}if(missingTools.length>0){parts.push("> **Warning:** Some tools referenced by this skill are not available:");parts.push(`> Missing: ${missingTools.join(", ")}`);parts.push("> You may need to adapt the workflow or skip steps that require these tools.");parts.push("")}if(skill.tools.length>0){parts.push("## Tools");parts.push("");for(const tool of skill.tools){const status=availableTools.includes(tool.name)?"\u2713":"\u2717";const purpose=tool.purpose?` - ${tool.purpose}`:"";parts.push(`- [${status}] \`${tool.name}\`${purpose}`)}parts.push("")}if(skill.parameters&&skill.parameters.length>0){parts.push("## Parameters");parts.push("");for(const param of skill.parameters){const required=param.required?" (required)":"";const desc=param.description?`: ${param.description}`:"";parts.push(`- **${param.name}**${required}${desc}`)}parts.push("")}parts.push("## Instructions");parts.push("");parts.push(skill.instructions);if(skill.examples&&skill.examples.length>0){parts.push("");parts.push("## Examples");parts.push("");for(const example of skill.examples){parts.push(`### ${example.scenario}`);if(example.expectedOutcome){parts.push(`Expected outcome: ${example.expectedOutcome}`)}parts.push("")}}return parts.join("\n")}var init_skill_utils=__esm({"libs/sdk/src/skill/skill.utils.ts"(){"use strict";init_common();init_external_entry_utils();init_errors()}});import{dirname as dirname5,fileExists as fileExists5,getCwd as getCwd4,pathJoin as pathJoin3,pathResolve as pathResolve4,readJSON}from"@frontmcp/utils";function createSkillInstance(record,providers,owner){return new SkillInstance(record,providers,owner)}function getSkillManifestMainDir(){try{const cwd=getCwd4();return cwd&&cwd.length>0?cwd:void 0}catch{return void 0}}async function loadResourceWithManifestFallback(resourcePath,baseDir,skillName,resourceType,loader){if(!resourcePath)return void 0;let dir=resourcePath.startsWith("/")?resourcePath:baseDir?pathResolve4(baseDir,resourcePath):void 0;if(dir){try{return await loader(dir)}catch(err){if(err.code!=="ENOENT")throw err;dir=await resolveResourceFromManifest(skillName,resourceType);if(dir)return await loader(dir)}}else{dir=await resolveResourceFromManifest(skillName,resourceType);if(dir)return await loader(dir)}return void 0}async function resolveFromSkillManifest(skillName){if(skillManifestCache===null)return void 0;if(skillManifestCache===void 0){const mainDir2=getSkillManifestMainDir();if(!mainDir2){skillManifestCache=null;return void 0}try{const manifestPath=pathJoin3(mainDir2,"_skills","manifest.json");if(await fileExists5(manifestPath)){skillManifestCache=await readJSON(manifestPath)}else{skillManifestCache=null;return void 0}}catch(err){if(err.code==="ENOENT"){skillManifestCache=null;return void 0}throw err}}if(!skillManifestCache)return void 0;const entry=skillManifestCache[skillName];if(!entry?.instructions)return void 0;const mainDir=getSkillManifestMainDir();if(!mainDir)return void 0;return pathResolve4(mainDir,entry.instructions)}async function resolveResourceFromManifest(skillName,resourceType){await resolveFromSkillManifest(skillName);if(!skillManifestCache)return void 0;const entry=skillManifestCache[skillName];const relPath=entry?.[resourceType];if(!relPath)return void 0;const mainDir=getSkillManifestMainDir();if(!mainDir)return void 0;return pathResolve4(mainDir,relPath)}var SkillInstance,skillManifestCache;var init_skill_instance=__esm({"libs/sdk/src/skill/skill.instance.ts"(){"use strict";init_common();init_skill_utils();SkillInstance=class extends SkillEntry{providersRef;scope;cachedInstructions;cachedContent;instructionsLoading;contentLoading;tags;priority;hidden;skillVisibility;skillContext;constructor(record,providers,owner){super(record);this.owner=owner;this.providersRef=providers;this.name=record.metadata.id??record.metadata.name;this.fullName=`${this.owner.id}:${this.name}`;this.tags=record.metadata.tags??[];this.priority=record.metadata.priority??0;this.hidden=record.metadata.hideFromDiscovery??false;this.skillVisibility=record.metadata.visibility??"both";this.scope=this.providersRef.getActiveScope();this.ready=this.initialize()}async initialize(){return Promise.resolve()}getDescription(){return this.cachedContent?.description??this.metadata.description}async loadInstructions(){if(this.cachedInstructions!==void 0){return this.cachedInstructions}this.instructionsLoading??=this.resolveInstructions().finally(()=>{this.instructionsLoading=void 0});return this.instructionsLoading}async resolveInstructions(){const context=this.overridingContext("loadInstructions");this.cachedInstructions=context?await context.loadInstructions():await this.readInstructions();return this.cachedInstructions}async readInstructions(){let basePath;if(this.record.kind==="FILE"){const filePath=this.record.filePath;const lastSlash=filePath.lastIndexOf("/");basePath=lastSlash>0?filePath.substring(0,lastSlash):void 0}else if((this.record.kind==="VALUE"||this.record.kind==="CLASS_TOKEN")&&this.record.callerDir){basePath=this.record.callerDir}try{return await loadInstructions(this.metadata.instructions,basePath)}catch(err){if(err.code==="ENOENT"){const resolved=await resolveFromSkillManifest(this.metadata.name);if(resolved){return loadInstructions({file:resolved},void 0)}}throw err}}overridingContext(method){if(this.record.kind!=="CLASS_TOKEN")return void 0;const prototype=this.record.provide.prototype;if(typeof prototype[method]!=="function"||prototype[method]===SkillContext.prototype[method]){return void 0}this.skillContext??=new this.record.provide({metadata:this.metadata,providers:this.providersRef,logger:this.scope.logger,authInfo:{},defaults:{loadInstructions:()=>this.readInstructions(),build:()=>this.buildContent()}});return this.skillContext}getBaseDir(){if(this.record.kind==="FILE"){return dirname5(this.record.filePath)||void 0}if((this.record.kind==="VALUE"||this.record.kind==="CLASS_TOKEN")&&this.record.callerDir){return this.record.callerDir}return void 0}async load(){if(this.cachedContent!==void 0){return this.cachedContent}this.contentLoading??=this.resolveContent().finally(()=>{this.contentLoading=void 0});return this.contentLoading}async resolveContent(){const context=this.overridingContext("build");const baseContent=context?await context.build():await this.buildContent();this.cachedContent={...baseContent,tags:this.tags,priority:this.priority,hideFromDiscovery:this.hidden,visibility:this.skillVisibility};return this.cachedContent}async buildContent(){const instructions=await this.loadInstructions();const baseDir=this.getBaseDir();const resolvedRefs=await loadResourceWithManifestFallback(this.metadata.resources?.references,baseDir,this.metadata.name,"references",resolveReferences);const resolvedExs=await loadResourceWithManifestFallback(this.metadata.resources?.examples,baseDir,this.metadata.name,"examples",resolveExamples);return buildSkillContent(this.metadata,instructions,resolvedRefs,resolvedExs)}getToolRefs(){const tools=this.metadata.tools;if(!tools)return[];return tools.map(t=>normalizeToolRef(t))}getToolNames(){return this.getToolRefs().map(t=>t.name)}getTags(){return this.tags}isHidden(){return this.hidden}getPriority(){return this.priority}get providers(){return this.providersRef}clearCache(){this.cachedInstructions=void 0;this.cachedContent=void 0}getContentSync(){if(this.cachedContent){return this.cachedContent}if(typeof this.metadata.instructions==="string"&&!this.overridingContext("loadInstructions")&&!this.overridingContext("build")){return buildSkillContent(this.metadata,this.metadata.instructions)}return void 0}}}});async function importWithRequireFallback(dynamicImport,requireFallback){try{return await dynamicImport()}catch(importError){try{return requireFallback()}catch{throw importError}}}var init_dynamic_import_utils=__esm({"libs/sdk/src/utils/dynamic-import.utils.ts"(){"use strict"}});var memory_skill_provider_exports={};__export(memory_skill_provider_exports,{MemorySkillProvider:()=>MemorySkillProvider});import{sha256Hex as sha256Hex12}from"@frontmcp/utils";function isSnapshotCapable(db){const d=db;return typeof d.toSnapshot==="function"&&typeof d.loadSnapshot==="function"}var STOP_WORDS,MemorySkillProvider;var init_memory_skill_provider=__esm({"libs/sdk/src/skill/providers/memory-skill.provider.ts"(){"use strict";init_dynamic_import_utils();STOP_WORDS=new Set(["the","a","an","this","that","these","those","in","on","at","to","for","of","with","by","from","into","and","or","but","so","as","if","when","where","i","me","my","you","your","it","its","we","our","they","their","is","was","are","were","be","been","being","have","has","had","do","does","did","will","would","can","could","should","may","might","please","help","want","need","like","just","how","what"]);MemorySkillProvider=class{type="memory";vectorDB;vectorDBLoading;skills=new Map;defaultTopK;defaultMinScore;toolValidator;initialized=false;scoring;indexCache;skillsVersion=0;indexedVersion=-1;constructor(options={}){this.defaultTopK=options.defaultTopK??10;this.defaultMinScore=options.defaultMinScore??.1;this.toolValidator=options.toolValidator;this.scoring=options.scoring??"cosine";this.indexCache=options.indexCache}async createVectorDB(){const{TFIDFVectoria}=await importWithRequireFallback(()=>import("vectoriadb"),()=>__require("vectoriadb"));const dbConfig={defaultTopK:this.defaultTopK,defaultSimilarityThreshold:this.defaultMinScore};if(this.scoring!=="cosine")dbConfig.scoring=this.scoring;return new TFIDFVectoria(dbConfig)}setIndexCache(cache2){this.indexCache=cache2;this.markStale()}get indexReady(){return this.indexedVersion===this.skillsVersion}markStale(){this.skillsVersion++}async ensureIndexed(){if(this.indexReady)return;const version=this.skillsVersion;const db=await this.db();if(this.indexCache&&isSnapshotCapable(db)){const key=await this.computeIndexKey();try{const snapshot=await this.indexCache.get(key);if(snapshot!==void 0&&snapshot!==null){db.loadSnapshot(snapshot);this.indexedVersion=version;return}}catch{}this.rebuildIndex(db);this.indexedVersion=version;try{await this.indexCache.set(key,db.toSnapshot())}catch{}return}this.rebuildIndex(db);this.indexedVersion=version}async warm(){await this.ensureIndexed()}rebuildIndex(db){db.clear();db.addDocuments(Array.from(this.skills.values(),skill=>this.toDocument(skill)));db.reindex()}toDocument(skill){return{id:skill.id,text:this.buildSearchableText(skill),metadata:{id:skill.id,skillId:skill.id,skill}}}async computeIndexKey(){const parts=Array.from(this.skills.values()).map(s=>`${s.id}\0${this.buildSearchableText(s)}`).sort();const canonical=`frontmcp-skill-index:v1|${this.scoring}|${this.skills.size}|${parts.join("")}`;return sha256Hex12(canonical)}async db(){if(this.vectorDB)return this.vectorDB;this.vectorDBLoading??=this.createVectorDB().then(db=>this.vectorDB??=db,error=>{this.vectorDBLoading=void 0;throw error});return this.vectorDBLoading}setToolValidator(validator){this.toolValidator=validator}async initialize(){this.initialized=true}async search(query,options={}){if(query.trim().length===0){return[]}const{topK=this.defaultTopK,tags,minScore=this.defaultMinScore,requireAllTools=false,excludeIds=[],tools}=options;const filter=metadata=>{const skill=metadata.skill;if(this.isHidden(skill)){return false}if(excludeIds.includes(skill.id)){return false}if(tags&&tags.length>0){const skillTags=this.getSkillTags(skill);if(!tags.some(t=>skillTags.includes(t))){return false}}if(tools&&tools.length>0){const skillTools=skill.tools.map(t=>t.name);if(!tools.some(t=>skillTools.includes(t))){return false}}return true};const db=await this.db();await this.ensureIndexed();let results=await db.search(query,{topK,threshold:minScore,filter,...options.negativeQuery!==void 0?{negativeQuery:options.negativeQuery}:{},...options.negativeWeight!==void 0?{negativeWeight:options.negativeWeight}:{}});if(results.length===0&&query.trim().length>0&&this.skills.size>0){results=this.fallbackTextSearch(query,topK,filter)}const searchResults=[];for(const result of results){const skill=result.metadata.skill;const toolNames=skill.tools.map(t=>t.name);let validation;if(this.toolValidator){validation=this.toolValidator.validate(toolNames);if(requireAllTools&&!validation.complete){continue}}searchResults.push({metadata:this.skillToMetadata(skill),score:result.score,availableTools:validation?.available??toolNames,missingTools:validation?.missing??[],source:"local"})}return searchResults}async load(skillId){const skill=this.skills.get(skillId);if(!skill){return null}const toolNames=skill.tools.map(t=>t.name);let availableTools=toolNames;let missingTools=[];let isComplete=true;let warning;if(this.toolValidator){const validation=this.toolValidator.validate(toolNames);availableTools=validation.available;missingTools=validation.missing;isComplete=validation.complete;warning=this.toolValidator.formatWarning(validation,skill.name)}return{skill,availableTools,missingTools,isComplete,warning}}async list(options={}){const{offset=0,limit=50,tags,sortBy="name",sortOrder="asc",includeHidden=false}=options;let skills=Array.from(this.skills.values());if(!includeHidden){skills=skills.filter(s=>!this.isHidden(s))}if(tags&&tags.length>0){skills=skills.filter(s=>{const skillTags=this.getSkillTags(s);return tags.some(t=>skillTags.includes(t))})}skills.sort((a,b)=>{let comparison;switch(sortBy){case"name":comparison=a.name.localeCompare(b.name);break;case"priority":comparison=(this.getPriority(a)??0)-(this.getPriority(b)??0);break;default:comparison=a.name.localeCompare(b.name)}return sortOrder==="desc"?-comparison:comparison});const total=skills.length;const hasMore=offset+limit<total;skills=skills.slice(offset,offset+limit);return{skills:skills.map(s=>this.skillToMetadata(s)),total,hasMore}}async exists(skillId){return this.skills.has(skillId)}async count(options={}){const{tags,includeHidden=false}=options;let count=0;for(const skill of this.skills.values()){if(!includeHidden&&this.isHidden(skill)){continue}if(tags&&tags.length>0){const skillTags=this.getSkillTags(skill);if(!tags.some(t=>skillTags.includes(t))){continue}}count++}return count}async add(skill){this.skills.set(skill.id,skill);this.markStale()}async update(skillId,skill){const normalizedSkill=skill.id!==skillId?{...skill,id:skillId}:skill;this.skills.set(skillId,normalizedSkill);this.markStale()}async remove(skillId){this.skills.delete(skillId);this.markStale()}async clear(){this.skills.clear();this.vectorDB?.clear();this.markStale()}async dispose(){this.skills.clear();this.vectorDB?.clear();this.markStale();this.initialized=false}async addMany(skills){for(const skill of skills)this.skills.set(skill.id,skill);this.markStale()}buildSearchableText(skill){const parts=[];if(skill.name){const nameParts=skill.name.split(/[:\-_.\s]/).filter(Boolean);parts.push(...nameParts)}if(skill.description){parts.push(skill.description,skill.description,skill.description);const keyTerms=skill.description.toLowerCase().split(/\s+/).filter(word=>word.length>=4&&!STOP_WORDS.has(word));parts.push(...keyTerms)}const tags=this.getSkillTags(skill);for(const tag of tags){parts.push(tag,tag)}for(const tool of skill.tools){parts.push(tool.name);if(tool.purpose){parts.push(tool.purpose)}}if(skill.parameters){for(const param of skill.parameters){parts.push(param.name);if(param.description){parts.push(param.description)}}}if(skill.examples){for(const example of skill.examples){parts.push(example.scenario);if(example.expectedOutcome){parts.push(example.expectedOutcome)}}}return parts.join(" ")}fallbackTextSearch(query,topK,filter){const queryTerms=query.toLowerCase().split(/\s+/).filter(t=>t.length>0&&!STOP_WORDS.has(t));if(queryTerms.length===0){return[]}const matches=[];this.skills.forEach(skill=>{const metadata={id:skill.id,skillId:skill.id,skill};if(!filter(metadata)){return}const searchableText=this.buildSearchableText(skill);const matchCount=queryTerms.filter(term=>searchableText.toLowerCase().includes(term)).length;if(matchCount>0){matches.push({id:skill.id,text:searchableText,score:matchCount/queryTerms.length,metadata})}});matches.sort((a,b)=>b.score-a.score);return matches.slice(0,topK)}skillToMetadata(skill){const tags=this.getSkillTags(skill);const priority=this.getPriority(skill);const hideFromDiscovery=this.isHidden(skill);const visibility=this.getVisibility(skill);return{id:skill.id,name:skill.name,description:skill.description,instructions:skill.instructions,tools:skill.tools.map(t=>{if(t.purpose||t.required){return{name:t.name,...t.purpose&&{purpose:t.purpose},...t.required&&{required:t.required}}}return t.name}),parameters:skill.parameters,examples:skill.examples,...tags.length>0&&{tags},...priority!==void 0&&{priority},...hideFromDiscovery&&{hideFromDiscovery},visibility:visibility??"both"}}getSkillTags(skill){return skill.tags??[]}isHidden(skill){return skill.hideFromDiscovery===true}getPriority(skill){return skill.priority}getVisibility(skill){return skill.visibility}}}});import{tokenName as tokenName15}from"@frontmcp/di";import{getRuntimeContext as getRuntimeContext15,isEntryAvailable as isEntryAvailable5}from"@frontmcp/utils";function findIdPathCollision(skills){const byPath=new Map;for(const skill of skills){const path4=skill.getSkillPath();if(!byPath.has(path4))byPath.set(path4,skill)}for(const idOwner of skills){const id=idOwner.metadata.id;if(!id||id===idOwner.getSkillPath())continue;const pathOwner=byPath.get(id);if(pathOwner)return{idOwner,pathOwner}}return void 0}function describeIdPathCollision({idOwner,pathOwner}){const id=idOwner.metadata.id;return`id "${id}" of skill "${idOwner.metadata.name}" is the skill:// path of skill "${pathOwner.metadata.name}", so skill://${id}/SKILL.md would serve one for the other. Give one of them another id or name.`}var DEFAULT_LIST_LIMIT,SkillRegistry;var init_skill_registry=__esm({"libs/sdk/src/skill/skill.registry.ts"(){"use strict";init_availability();init_errors();init_regsitry();init_lineage_utils();init_skill_validation_error();init_sep_2640_constants();init_skill_validator();init_skill_events();init_skill_instance();init_skill_utils();DEFAULT_LIST_LIMIT=50;SkillRegistry=class _SkillRegistry extends RegistryAbstract{owner;localRows=[];dynamicRows=[];dynamicContents=new Map;dynamicGenerations=new Map;withdrawn=new Map;withdrawals=0;providerWrites=new Map;dynamicSkillsExpected=false;adopted=new Map;children=new Set;adopters=new Set;byQualifiedId=new Map;lineages=new EntryLineageIndex;byName=new Map;byOwnerAndName=new Map;version=0;emitter=new SkillEmitter;storageProvider;storageProviderLoad;indexCache;externalProvider;toolValidator;scope;options;sep2640IndexTemplates=[];sep2640IndexArchives=[];sep2640InstructionUris=[];constructor(providers,list,owner,options){super("SkillRegistry",providers,list,false);this.owner=owner;this.scope=providers.getActiveScope();this.options=options??{};this.indexCache=this.options.indexCache;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=normalizeSkill(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)continue;const deps=skillDiscoveryDeps(rec);for(const d of deps){this.providers.get(d);this.graph.get(token)?.add(d)}}}async initialize(){try{const toolRegistry=this.scope.tools;if(toolRegistry){this.toolValidator=new SkillToolValidator(toolRegistry)}}catch{}for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)continue;const instance=createSkillInstance(rec,this.providers,this.owner);this.instances.set(token,instance);const lineage=this.owner?[this.owner]:[];const row=this.makeRow(token,instance,lineage,this);this.localRows.push(row);try{await this.syncProvider(instance.metadata.id??instance.metadata.name,async()=>{const content=await instance.load();await(await this.storage()).add(content)})}catch(error){this.scope.logger.warn(`Failed to load skill ${instance.name}: ${error.message}`)}}const childAppRegistries=this.providers.getRegistries("AppRegistry");for(const appRegistry of childAppRegistries){const apps=appRegistry.getApps();for(const app of apps){const appSkillsRegistry=app.skills;if(appSkillsRegistry&&"adoptFromChild"in this&&appSkillsRegistry!==this){if(!app.isRemote&&appSkillsRegistry instanceof _SkillRegistry){await this.adoptFromChild(appSkillsRegistry,appSkillsRegistry.owner)}}}}const childRegistries=this.providers.getRegistries("SkillRegistry");for(const child of childRegistries){if(child!==this){await this.adoptFromChild(child,child.owner)}}const collision=findIdPathCollision(this.listAllInstances());if(collision){throw new InvalidSkillError(collision.idOwner.metadata.name,describeIdPathCollision(collision))}this.reindex();logAvailabilityFiltering("SkillRegistry",this.listAllIndexed().map(r=>r.instance),this.scope.logger);this.bump("reset")}async adoptFromChild(child,_childOwner){if(this.children.has(child))return;const childRows=child.listAllIndexed();const prepend=this.owner?[this.owner]:[];const adoptedRows=childRows.map(r=>this.relineage(r,prepend));this.adopted.set(child,adoptedRows);this.children.add(child);child.adopters.add(this);child.subscribe({immediate:false},()=>{const previous=this.adopted.get(child)??[];const latest=child.listAllIndexed().map(r=>this.relineage(r,prepend));this.adopted.set(child,latest);this.reindex();this.withdrawGoneAdoptedSkills(previous);for(const row of latest){const skillId=row.instance.metadata.id??row.instance.metadata.name;this.syncProvider(skillId,async()=>{const content=await row.instance.load();await(await this.storage()).add(content)}).catch(error=>{this.scope.logger.warn(`Failed to reload adopted skill ${row.baseName}: ${error.message}`)})}this.bump("reset")});await Promise.all(adoptedRows.map(async row=>{try{await this.syncProvider(row.instance.metadata.id??row.instance.metadata.name,async()=>{const content=await row.instance.load();await(await this.storage()).add(content)})}catch(error){this.scope.logger.warn(`Failed to load adopted skill ${row.baseName}: ${error.message}`)}}));this.reindex();this.bump("reset")}namespacesServingThis(){const registries=new Set;const climb=registry=>{if(registries.has(registry))return;registries.add(registry);for(const adopter of registry.adopters)climb(adopter)};climb(this);return[...registries].map(registry=>registry.liveSkills())}liveSkills(){const registries=new Set;const skills=new Set;const descend=registry=>{if(registries.has(registry))return;registries.add(registry);for(const row of[...registry.localRows,...registry.dynamicRows])skills.add(row.instance);for(const child of registry.children)descend(child)};descend(this);return[...skills]}getSkills(options){const opts=typeof options==="boolean"?{includeHidden:options}:options??{};const{includeHidden=false,visibility="all"}=opts;let skills=this.listAllIndexed().map(r=>r.instance);if(!includeHidden){skills=skills.filter(s=>!s.isHidden())}if(visibility!=="all"){skills=skills.filter(s=>{const skillVis=s.metadata.visibility??"both";if(skillVis==="both")return true;return skillVis===visibility})}const ctx=getRuntimeContext15();skills=skills.filter(s=>isEntryAvailable5(s.metadata.availableWhen,ctx));return skills}getInlineSkills(){return[...this.instances.values()]}getAlwaysLoadedSkills(){let skills=this.listAllIndexed().map(r=>r.instance);skills=skills.filter(s=>s.isAlwaysLoaded());const ctx=getRuntimeContext15();skills=skills.filter(s=>isEntryAvailable5(s.metadata.availableWhen,ctx));return skills}getExecutableSkills(opts){return this.getSkills(opts).filter(s=>s.isExecutable())}getKnowledgeOnlySkills(opts){return this.getSkills(opts).filter(s=>s.isKnowledgeOnly())}findByName(name51){const rows=this.byName.get(name51);return rows?.[0]?.instance}findByQualifiedName(qualifiedName){for(const row of this.listAllIndexed()){if(row.qualifiedName===qualifiedName){return row.instance}}return void 0}setIndexCache(cache2){this.indexCache=cache2;const provider=this.storageProvider;if(typeof provider?.setIndexCache==="function"){provider.setIndexCache(cache2)}}async warmIndex(){await this.ready;const provider=await this.storage();if(typeof provider.warm==="function"){await provider.warm()}}async search(query,options){const topK=options?.topK;const hidden=this.hiddenFromProviderRead();const providerOptions=hidden.size>0&&typeof topK==="number"&&topK>=0?{...options,topK:topK+hidden.size}:options;let baseResults=await(await this.storage()).search(query,providerOptions);if(hidden.size>0||this.withdrawn.size>0){baseResults=baseResults.filter(r=>!hidden.has(r.metadata));if(typeof topK==="number"&&topK>=0)baseResults=baseResults.slice(0,topK)}if(this.dynamicContents.size===0)return baseResults;const baseSeen=new Set;let rewrites=0;const rewrittenBase=baseResults.map(r=>{const id=r.metadata.id??r.metadata.name;baseSeen.add(id);const dyn=this.dynamicContents.get(id);if(!dyn)return r;rewrites++;const meta=this.dynamicSkillMetadata(dyn);const toolNames=dyn.tools.map(t=>t.name);let availableTools=toolNames;let missingTools=[];if(this.toolValidator){const v=this.toolValidator.validate(toolNames);availableTools=v.available;missingTools=v.missing}return{...r,metadata:meta,availableTools,missingTools}});const overlayOnly=this.searchDynamicOverlay(query,options,baseSeen);if(overlayOnly.length===0&&rewrites===0)return baseResults;const merged=[...rewrittenBase,...overlayOnly].sort((a,b)=>b.score-a.score);return typeof topK==="number"&&topK>=0?merged.slice(0,topK):merged}async loadSkill(skillId){const dynamic=this.dynamicContents.get(skillId);if(dynamic){return this.buildDynamicLoadResult(dynamic)}let localSkill=this.findByName(skillId)??this.findByQualifiedName(skillId);if(!localSkill){for(const row of this.listAllIndexed()){if(row.instance.metadata.name===skillId){localSkill=row.instance;break}}}if(localSkill){const ctx=getRuntimeContext15();if(!isEntryAvailable5(localSkill.metadata.availableWhen,ctx)){return void 0}const dynamicResolved=this.dynamicContents.get(localSkill.metadata.id??localSkill.metadata.name);if(dynamicResolved){return this.buildDynamicLoadResult(dynamicResolved)}const instance=localSkill;const content=await instance.load();const toolNames=instance.getToolNames();let availableTools=toolNames;let missingTools=[];let isComplete=true;let warning;if(this.toolValidator){const validation=this.toolValidator.validate(toolNames);availableTools=validation.available;missingTools=validation.missing;isComplete=validation.complete;warning=this.toolValidator.formatWarning(validation,instance.name)}return{skill:content,availableTools,missingTools,isComplete,warning}}const hidden=this.hiddenFromProviderRead();if(hidden.has({name:skillId}))return void 0;const result=await(await this.storage()).load(skillId);if(result&&hidden.has(result.skill))return void 0;return result??void 0}buildDynamicLoadResult(content){const toolNames=content.tools.map(t=>t.name);let availableTools=toolNames;let missingTools=[];let isComplete=true;let warning;if(this.toolValidator){const validation=this.toolValidator.validate(toolNames);availableTools=validation.available;missingTools=validation.missing;isComplete=validation.complete;warning=this.toolValidator.formatWarning(validation,content.name)}return{skill:structuredClone(content),availableTools,missingTools,isComplete,warning}}async listSkills(options){const hidden=this.hiddenFromProviderRead();if(this.dynamicContents.size===0&&hidden.size===0){const page2=await(await this.storage()).list(options);if(this.withdrawn.size===0)return page2}const base=(await this.listAllFromProvider(options)).filter(meta=>!hidden.has(meta));const baseIds=new Set;const merged=base.map(meta=>{const id=meta.id??meta.name;baseIds.add(id);const dyn=this.dynamicContents.get(id);return dyn?this.dynamicSkillMetadata(dyn):meta});for(const meta of this.collectDynamicMetadata(options)){const id=meta.id??meta.name;if(!baseIds.has(id)){baseIds.add(id);merged.push(meta)}}const offset=options?.offset??0;const limit=options?.limit??DEFAULT_LIST_LIMIT;const skills=merged.slice(offset,offset+limit);return{skills,total:merged.length,hasMore:offset+skills.length<merged.length}}async listAllFromProvider(options){const all=[];const storage=await this.storage();for(;;){const page2=await storage.list({...options,offset:all.length,limit:Number.MAX_SAFE_INTEGER});all.push(...page2.skills);if(!page2.hasMore||page2.skills.length===0)return all}}lineageOf(entry){return this.lineages.lineageOf(entry)}hasAny(){return this.listAllIndexed().length>0}expectDynamicSkills(){this.dynamicSkillsExpected=true}servesSkills(){return this.dynamicSkillsExpected||this.hasAny()||this.externalProvider?.isReadOnly()===true}async count(options){const hidden=this.hiddenFromProviderRead();if(this.dynamicContents.size===0&&hidden.size===0){const counted=await(await this.storage()).count(options);if(this.withdrawn.size===0)return counted}const baseList=(await this.listAllFromProvider({tags:options?.tags,includeHidden:options?.includeHidden})).filter(m=>!hidden.has(m));const baseIds=new Set;for(const m of baseList)baseIds.add(m.id??m.name);const overlay=this.collectDynamicMetadata(options).filter(m=>!baseIds.has(m.id??m.name));return baseList.length+overlay.length}dynamicSkillMetadata(content){return{id:content.id,name:content.name,description:content.description,instructions:content.instructions,tools:content.tools.map(t=>({name:t.name,...t.purpose!==void 0&&{purpose:t.purpose},...t.required!==void 0&&{required:t.required}})),...content.parameters!==void 0&&{parameters:content.parameters},...content.examples!==void 0&&{examples:content.examples},...content.license!==void 0&&{license:content.license},...content.compatibility!==void 0&&{compatibility:content.compatibility},...content.specMetadata!==void 0&&{specMetadata:content.specMetadata},...content.allowedTools!==void 0&&{allowedTools:content.allowedTools},...content.resources!==void 0&&{resources:content.resources},...content.rating!==void 0&&{rating:content.rating},...content.category!==void 0&&{category:content.category}}}collectDynamicMetadata(options){const out=[];for(const content of this.dynamicContents.values()){const meta=this.dynamicSkillMetadata(content);if(options?.tags?.length){const tags=meta.tags??[];if(!options.tags.some(t=>tags.includes(t)))continue}if(!options?.includeHidden&&meta.hideFromDiscovery===true)continue;out.push(meta)}return out}searchDynamicOverlay(query,options,excludeIds){const q=query.trim().toLowerCase();const minScore=options?.minScore??.1;const out=[];for(const content of this.dynamicContents.values()){const id=content.id;if(excludeIds.has(id))continue;if(options?.excludeIds?.includes(id))continue;const meta=this.dynamicSkillMetadata(content);if(options?.tags?.length){const tags=meta.tags??[];if(!options.tags.some(t=>tags.includes(t)))continue}const toolNames=content.tools.map(t=>t.name);let availableTools=toolNames;let missingTools=[];if(this.toolValidator){const v=this.toolValidator.validate(toolNames);availableTools=v.available;missingTools=v.missing}if(options?.requireAllTools&&missingTools.length>0)continue;if(options?.tools?.length){const refSet=new Set(toolNames);if(!options.tools.some(t=>refSet.has(t)))continue}const name51=(meta.name??"").toLowerCase();const desc=(meta.description??"").toLowerCase();let score;if(q.length===0){score=.5}else if(name51.includes(q)){score=1}else if(desc.includes(q)){score=.5}else{continue}if(score<minScore)continue;out.push({metadata:meta,score,availableTools,missingTools,source:"local"})}return out}subscribe(opts,cb){const filter=opts.filter??(()=>true);if(opts.immediate){cb({kind:"reset",changeScope:"global",version:this.version,snapshot:this.listAllInstances().filter(filter)})}return this.emitter.on(e=>cb({...e,snapshot:this.listAllInstances().filter(filter)}))}getCapabilities(){if(!this.servesSkills())return{};return{experimental:{[SEP_2640_EXTENSION_ID]:{}},extensions:{[SEP_2640_EXTENSION_ID]:{}}}}getSep2640IndexTemplates(){return[...this.sep2640IndexTemplates]}addSep2640IndexTemplate(entry){if(entry.type!=="mcp-resource-template"){throw new Error(`addSep2640IndexTemplate: entry.type must be "mcp-resource-template", got "${entry.type}"`)}this.sep2640IndexTemplates.push(entry);this.bump("reset")}getSep2640IndexArchives(){return[...this.sep2640IndexArchives]}addSep2640IndexArchive(entry){if(entry.type!=="archive"){throw new Error(`addSep2640IndexArchive: entry.type must be "archive", got "${entry.type}"`)}this.sep2640IndexArchives.push(entry);this.bump("reset")}getSep2640InstructionUris(){return[...this.sep2640InstructionUris]}addSep2640InstructionUri(uri){if(!this.sep2640InstructionUris.includes(uri)){this.sep2640InstructionUris.push(uri);this.bump("reset")}}async validateAllTools(){const results=[];const allInstances=this.listAllInstances();for(const entry of allInstances){const instance=entry;const toolNames=instance.getToolNames();const skillValidation=instance.metadata.toolValidation??this.options.defaultToolValidation??"warn";if(skillValidation==="ignore"){results.push({skillId:instance.name,skillName:instance.name,status:"valid",missingTools:[],hiddenTools:[],validationMode:skillValidation});continue}if(this.toolValidator&&toolNames.length>0){const validation=this.toolValidator.validate(toolNames);if(!validation.complete){const status=skillValidation==="strict"?"failed":"warning";if(skillValidation==="warn"){const warning=this.toolValidator.formatWarning(validation,instance.name);if(warning){this.scope.logger.warn(warning)}}else if(this.options.failOnInvalidSkills===false){this.scope.logger.error(`Skill "${instance.name}" (toolValidation: 'strict') references missing tools: ${validation.missing.join(", ")}`)}results.push({skillId:instance.name,skillName:instance.name,status,missingTools:validation.missing,hiddenTools:validation.hidden,validationMode:skillValidation})}else{results.push({skillId:instance.name,skillName:instance.name,status:"valid",missingTools:[],hiddenTools:[],validationMode:skillValidation})}}else{results.push({skillId:instance.name,skillName:instance.name,status:"valid",missingTools:[],hiddenTools:[],validationMode:skillValidation})}}const failedCount=results.filter(r=>r.status==="failed").length;const warningCount=results.filter(r=>r.status==="warning").length;const report={results,isValid:failedCount===0,totalSkills:results.length,failedCount,warningCount};this.emitter.emit({kind:"validated",changeScope:"global",version:this.version,snapshot:allInstances,validationReport:report});if(this.options.failOnInvalidSkills!==false&&failedCount>0){throw SkillValidationError.fromReport(report)}return report}async registerSkillContent(content,opts){if(!content||typeof content.id!=="string"||content.id.length===0){throw new PublicMcpError("registerSkillContent: SkillContent.id is required","INVALID_PARAMS")}if(typeof content.name!=="string"||content.name.length===0){throw new PublicMcpError("registerSkillContent: SkillContent.name is required","INVALID_PARAMS")}const id=content.id;const metadata={id,name:content.name,description:content.description,instructions:content.instructions,tools:content.tools.map(t=>({name:t.name,...t.purpose!==void 0&&{purpose:t.purpose},...t.required!==void 0&&{required:t.required}})),...content.parameters&&{parameters:content.parameters},...content.examples&&{examples:content.examples},...content.license&&{license:content.license},...content.compatibility&&{compatibility:content.compatibility},...content.specMetadata&&{specMetadata:content.specMetadata},...content.allowedTools&&{allowedTools:content.allowedTools},...content.resources&&{resources:content.resources},...content.rating!==void 0&&{rating:content.rating},...content.category&&{category:content.category}};const provideToken=Symbol(`dynamic-skill:${id}`);const record={kind:"VALUE",provide:provideToken,metadata};const instance=createSkillInstance(record,this.providers,this.owner);try{await instance.load()}catch(error){this.scope.logger.warn(`[SkillRegistry] Failed to pre-load dynamic skill ${id} from source ${opts?.source??"unknown"}: ${error.message}`)}const storage=await this.storage();const existingIdx=this.dynamicRows.findIndex(r=>r.instance.name===id);const superseded=new Set(opts?.supersedes);const leaving=new Set(this.dynamicRows.filter(r=>r.instance.name===id||superseded.has(r.instance.name)).map(r=>r.instance));for(const skills of this.namespacesServingThis()){const collision=findIdPathCollision([...skills.filter(other=>!leaving.has(other)),instance]);if(collision){throw new PublicMcpError(`registerSkillContent: ${describeIdPathCollision(collision)}`,"INVALID_PARAMS")}}if(existingIdx!==-1){this.dynamicRows.splice(existingIdx,1)}const mutable=this.asMutableProvider(storage);const removed=this.dynamicRows.filter(r=>superseded.has(r.instance.name)&&findIdPathCollision([r.instance,instance])).map(r=>r.instance.name);for(const removedId of removed){this.withdrawDynamicSkill(removedId,mutable)}const lineage=this.owner?[this.owner]:[];const row=this.makeRow(provideToken,instance,lineage,this);this.dynamicRows.push(row);this.dynamicContents.set(id,structuredClone(content));this.withdrawn.delete(id);const generation=(this.dynamicGenerations.get(id)??0)+1;this.dynamicGenerations.set(id,generation);this.reindex();const providerWrites=mutable?[...removed.map(removedId=>this.removeFromProvider(removedId)),this.syncProvider(id,async()=>{if(await mutable.exists(id)){await mutable.update(id,content)}else{await mutable.add(content)}}).catch(error=>{this.scope.logger.warn(`[SkillRegistry] Failed to index dynamic skill ${id} in storage provider: ${error.message}`)})]:[];this.bump("reset");await Promise.all(providerWrites);let unregistered=false;const unregister=async()=>{if(unregistered)return;unregistered=true;if(this.dynamicGenerations.get(id)!==generation){return}await this.unregisterSkill(id)};this.scope.logger.debug(`[SkillRegistry] Registered dynamic skill ${id}${opts?.source?` (source: ${opts.source})`:""}`);return{id,unregister,removed}}async unregisterSkill(id){if(!this.dynamicRows.some(r=>r.instance.name===id))return false;const mutable=this.asMutableProvider(this.storageProvider);this.withdrawDynamicSkill(id,mutable);this.reindex();const removal=mutable?this.removeFromProvider(id):void 0;this.bump("reset");await removal;this.scope.logger.debug(`[SkillRegistry] Unregistered dynamic skill ${id}`);return true}withdrawDynamicSkill(id,mutable){this.dynamicRows.splice(this.dynamicRows.findIndex(r=>r.instance.name===id),1);this.dynamicContents.delete(id);this.dynamicGenerations.set(id,(this.dynamicGenerations.get(id)??0)+1);if(mutable)this.withdrawn.set(id,++this.withdrawals)}async removeFromProvider(id){const withdrawal=this.withdrawn.get(id);try{await this.syncProvider(id,async()=>{await this.asMutableProvider(await this.storage())?.remove(id)});if(this.withdrawn.get(id)===withdrawal)this.withdrawn.delete(id)}catch(error){this.scope.logger.warn(`[SkillRegistry] Failed to remove skill ${id} from storage provider; it stays hidden from provider-backed reads: ${error.message}`)}}syncProvider(id,write){const run=(this.providerWrites.get(id)??Promise.resolve()).then(write);const settled=run.then(()=>void 0,()=>void 0);this.providerWrites.set(id,settled);void settled.then(()=>{if(this.providerWrites.get(id)===settled)this.providerWrites.delete(id)});return run}withdrawGoneAdoptedSkills(previous){if(this.storageProvider&&!this.asMutableProvider(this.storageProvider))return;const skillIdOf=entry=>entry.metadata.id??entry.metadata.name;const live=new Set(this.listAllIndexed().map(r=>skillIdOf(r.instance)));for(const id of live)this.withdrawn.delete(id);for(const row of previous){const id=skillIdOf(row.instance);if(live.has(id)||this.withdrawn.has(id))continue;this.withdrawn.set(id,++this.withdrawals);void this.removeFromProvider(id)}}hiddenFromProviderRead(){const atStart=new Set(this.withdrawn.keys());return{size:atStart.size,has:meta=>{const id=meta.id??meta.name;return atStart.has(id)||this.withdrawn.has(id)}}}asMutableProvider(provider){const candidate=provider;if(candidate&&typeof candidate.add==="function"&&typeof candidate.update==="function"&&typeof candidate.remove==="function"&&typeof candidate.exists==="function"){return provider}return void 0}storage(){if(!this.storageProviderLoad){const load2=this.createMemoryProvider().catch(error=>{if(this.storageProviderLoad===load2)this.storageProviderLoad=void 0;throw error});this.storageProviderLoad=load2}return this.storageProviderLoad}async createMemoryProvider(){const{MemorySkillProvider:Provider}=await Promise.resolve().then(()=>(init_memory_skill_provider(),memory_skill_provider_exports));const provider=new Provider({defaultTopK:10,defaultMinScore:.1,...this.options.scoring?{scoring:this.options.scoring}:{},...this.indexCache?{indexCache:this.indexCache}:{}});if(this.toolValidator)provider.setToolValidator(this.toolValidator);await provider.initialize();this.storageProvider??=provider;return this.storageProvider}listAllIndexed(){return[...this.localRows,...this.dynamicRows,...[...this.adopted.values()].flat()]}listAllInstances(){return this.listAllIndexed().map(r=>r.instance)}reindex(){const effective=this.listAllIndexed();this.lineages.rebuild(effective);this.byQualifiedId.clear();this.byName.clear();this.byOwnerAndName.clear();for(const r of effective){this.byQualifiedId.set(r.qualifiedId,r);const listByName=this.byName.get(r.baseName)??[];listByName.push(r);this.byName.set(r.baseName,listByName);const key=`${r.ownerKey}:${r.baseName}`;if(!this.byOwnerAndName.has(key)){this.byOwnerAndName.set(key,r)}}}makeRow(token,instance,lineage,source){const ownerKey=ownerKeyOf(lineage);const baseName=instance.name;const qualifiedName=qualifiedNameOf(lineage,baseName);const qualifiedId=`${ownerKey}:${tokenName15(token)}`;return{token,instance,baseName,lineage,ownerKey,qualifiedName,qualifiedId,source}}relineage(row,prepend){const lineage=[...prepend,...row.lineage];const ownerKey=ownerKeyOf(lineage);const qualifiedName=qualifiedNameOf(lineage,row.baseName);const qualifiedId=`${ownerKey}:${tokenName15(row.token)}`;return{token:row.token,instance:row.instance,baseName:row.baseName,lineage,ownerKey,qualifiedName,qualifiedId,source:row.source}}bump(kind){const version=++this.version;this.emitter.emit({kind,changeScope:"global",version,snapshot:this.listAllInstances()})}setExternalProvider(provider){this.externalProvider=provider;if(provider.isReadOnly()){this.storageProvider=provider;this.storageProviderLoad=Promise.resolve(provider);this.scope.logger.info("[SkillRegistry] Using external provider in read-only mode")}else{this.scope.logger.info("[SkillRegistry] External provider configured for persistent sync")}}getExternalProvider(){return this.externalProvider}hasExternalProvider(){return this.externalProvider!==void 0}async syncToExternal(){if(!this.externalProvider){this.scope.logger.debug("[SkillRegistry] No external provider configured, skipping sync");return null}if(this.externalProvider.isReadOnly()){this.scope.logger.debug("[SkillRegistry] External provider is read-only, skipping sync");return null}const localSkills=[];const allIndexed=this.listAllIndexed();for(const row of allIndexed){try{const content=await row.instance.load();localSkills.push(content)}catch(error){this.scope.logger.warn(`[SkillRegistry] Failed to load skill for sync: ${row.baseName}`,{error:error instanceof Error?error.message:String(error)})}}this.scope.logger.info("[SkillRegistry] Starting external sync",{skillCount:localSkills.length});const result=await this.externalProvider.syncSkills(localSkills);this.scope.logger.info("[SkillRegistry] External sync complete",{added:result.added.length,updated:result.updated.length,unchanged:result.unchanged.length,removed:result.removed.length,failed:result.failed.length,durationMs:result.durationMs});this.emitter.emit({kind:"synced",changeScope:"global",version:this.version,snapshot:this.listAllInstances(),syncResult:result});return result}}}});import{depsOfClass as depsOfClass9,getMetadata as getMetadata18,isClass as isClass16,tokenName as tokenName16}from"@frontmcp/di";function collectPluginMetadata(cls){return Object.entries(FrontMcpPluginTokens).reduce((metadata,[key,token])=>{return Object.assign(metadata,{[key]:getMetadata18(token,cls)})},{})}function normalizePlugin(item){if(isClass16(item)){const metadata=collectPluginMetadata(item);return{kind:"CLASS_TOKEN",provide:item,metadata}}if(item&&typeof item==="object"){const{provide,useClass,useFactory,useValue,inject,...metadata}=item;if(!provide){const name52=item?.name??"[object]";throw new MissingProvideError("plugin",name52)}if(useClass){if(!isClass16(useClass)){throw new InvalidUseClassError("plugin",tokenName16(provide))}const decoratorMetadata=collectPluginMetadata(useClass);const{providers:_dynamicProviders,...inlineMetadata}=metadata;const mergedMetadata={...decoratorMetadata,...inlineMetadata};return{kind:"CLASS",provide,useClass,metadata:mergedMetadata}}if(useFactory){if(typeof useFactory!=="function"){throw new InvalidUseFactoryError("plugin",tokenName16(provide))}const inj=typeof inject==="function"?inject:()=>[];if(!isClass16(provide)){return{kind:"FACTORY",provide,inject:inj,useFactory,metadata}}const decoratorMetadata=collectPluginMetadata(provide);const{providers:dynamicProviders,...inlineMetadata}=metadata;return{kind:"FACTORY",provide,inject:inj,useFactory,metadata:{...decoratorMetadata,...inlineMetadata},providers:dynamicProviders??[]}}if("useValue"in item){if(useValue===void 0||useValue===null){throw new InvalidUseValueError("plugin",tokenName16(provide))}const decoratorMetadata=collectPluginMetadata(useValue.constructor);const{providers:_dynamicProviders,...inlineMetadata}=metadata;const mergedMetadata={...decoratorMetadata,...inlineMetadata};return{kind:"VALUE",provide,useValue,metadata:mergedMetadata,providers:item.providers??[]}}}const name51=item?.name??String(item);throw new InvalidEntityError("plugin",name51,"a class or a plugin object")}function pluginDiscoveryDeps(rec){switch(rec.kind){case"VALUE":return[];case"FACTORY":{return[...rec.inject()]}case"CLASS":return depsOfClass9(rec.useClass,"discovery").filter(v=>v!==null&&typeof v==="object");case"CLASS_TOKEN":return depsOfClass9(rec.provide,"discovery").filter(v=>v!==null&&typeof v==="object")}}var init_plugin_utils=__esm({"libs/sdk/src/plugin/plugin.utils.ts"(){"use strict";init_common();init_errors()}});import"reflect-metadata";import{tokenName as tokenName17}from"@frontmcp/di";import{getRuntimeContext as getRuntimeContext16}from"@frontmcp/utils";function instantiateClassPlugin(klass,depsInstances,recordProviders){if(!isConfiguredByOptions(klass)){return{pluginInstance:new klass(...depsInstances),dynamicProviders:recordProviders,dynamicTools:[]}}const options={};const optionDerived=collectDynamicProviders(klass,options);const dynamicTools=collectDynamicTools(klass,options);return{pluginInstance:new klass(options),dynamicProviders:optionDerived.length>0?dedupePluginProviders([...optionDerived,...recordProviders??[]]):recordProviders,dynamicTools}}function isConfiguredByOptions(klass){if(isDynamicPluginClass(klass))return true;const hooks=klass;return typeof hooks.dynamicProviders==="function"||typeof hooks.dynamicTools==="function"}var installedPluginValues,PluginRegistry;var init_plugin_registry=__esm({"libs/sdk/src/plugin/plugin.registry.ts"(){"use strict";init_adapter_registry();init_common();init_dynamic_plugin();init_dynamic_utils();init_context_extension();init_errors();init_hooks_utils();init_prompt_registry();init_provider_registry();init_provider_utils();init_regsitry();init_resource_registry();init_browser_stores();init_skill_registry();init_tool_registry();init_plugin_utils();installedPluginValues=new WeakSet;PluginRegistry=class _PluginRegistry extends RegistryAbstract{pProviders=new Map;pPlugins=new Map;pAdapters=new Map;pTools=new Map;pResources=new Map;pPrompts=new Map;pSkills=new Map;scope;scopeInfo;owner;logger;constructor(providers,list,owner,scopeInfo){super("PluginRegistry",providers,list);this.scope=providers.getActiveScope();this.scopeInfo=scopeInfo;this.owner=owner;try{this.logger=providers.get(FrontMcpLogger)?.child("PluginRegistry")}catch{}}getPlugins(){return[...this.instances.values()]}getPluginNames(){return[...this.defs.values()].map(rec=>rec.metadata.name)}getToolRegistries(){return[...this.pTools.values()]}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;for(const raw of list){const rec=normalizePlugin(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)throw new RegistryDependencyNotRegisteredError("Plugin",tokenName17(token),"self");const deps=pluginDiscoveryDeps(rec);for(const d of deps){if(!this.providers.get(d)){throw new RegistryDependencyNotRegisteredError("Plugin",tokenName17(token),tokenName17(d))}const edges=this.graph.get(token);if(edges)edges.add(d)}}}async initialize(){this.logger?.verbose(`PluginRegistry: initializing ${this.tokens.size} plugin(s)`);for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)continue;const deps=this.graph.get(token)??new Set;const providers=new ProviderRegistry(rec.metadata.providers??[],this.providers);await providers.ready;const{pluginInstance,dynamicProviders,dynamicTools}=await this.instantiatePlugin(rec,deps);if(dynamicProviders){await providers.addDynamicProviders(dynamicProviders)}const providerHooks=normalizeHooksFromProviders(providers);const pluginOwner={kind:"plugin",id:rec.metadata.name,ref:token};const nestedHookOwner=this.owner?.kind==="app"||this.owner?.kind==="agent"||this.owner?.kind==="scope"?this.owner:pluginOwner;const plugins=new _PluginRegistry(providers,rec.metadata.plugins??[],nestedHookOwner,this.scopeInfo);await plugins.ready;const adapters=new AdapterRegistry(providers,rec.metadata.adapters??[]);await adapters.ready;if(adapters.getAdapters().length>0)this.scope.onDispose(()=>adapters.dispose());const tools=new ToolRegistry(providers,[...rec.metadata.tools??[],...dynamicTools],pluginOwner);const resources=new ResourceRegistry(providers,rec.metadata.resources??[],pluginOwner);const prompts=new PromptRegistry(providers,rec.metadata.prompts??[],pluginOwner);const skills=new SkillRegistry(providers,rec.metadata.skills??[],pluginOwner);await Promise.all([tools.ready,resources.ready,prompts.ready,skills.ready]);this.providers.addRegistry("ToolRegistry",tools);this.providers.addRegistry("ResourceRegistry",resources);this.providers.addRegistry("PromptRegistry",prompts);this.providers.addRegistry("SkillRegistry",skills);this.pProviders.set(token,providers);this.pPlugins.set(token,plugins);this.pAdapters.set(token,adapters);this.pTools.set(token,tools);this.pResources.set(token,resources);this.pPrompts.set(token,prompts);this.pSkills.set(token,skills);const exported=(rec.metadata.exports??[]).map(rawToken=>{const token2=normalizeProvider(rawToken);return providers.getProviderInfo(token2.provide)});this.providers.mergeFromRegistry(providers,exported);const pluginScope=rec.metadata.scope??"app";if(this.scopeInfo?.isStandaloneApp&&pluginScope==="server"){throw new InvalidPluginScopeError(`Plugin "${rec.metadata.name}" has scope='server' but is used in a standalone app. Server-scoped plugins can only be used in non-standalone apps.`)}const hooks=[...normalizeHooksFromCls(pluginInstance),...providerHooks];if(hooks.length>0){let targetHookScope;let hookOwner=this.owner;if(pluginScope==="server"&&this.scopeInfo?.parentScope){targetHookScope=this.scopeInfo.parentScope;hookOwner=pluginOwner}else{targetHookScope=this.scope;if(pluginScope==="server"&&!this.scopeInfo?.parentScope){this.scope.logger.warn(`Plugin "${rec.metadata.name}" has scope='server' but no parent scope is available. Hooks will be registered to the current scope instead. This may happen for server-level plugins or standalone apps.`)}}const hooksWithOwner=hooks.map(hook=>({...hook,metadata:{...hook.metadata,owner:hookOwner,pluginName:rec.metadata.name}}));await targetHookScope.hooks.registerHooks(false,...hooksWithOwner)}const getFromPluginProviders=providers.get.bind(providers);pluginInstance.get=getFromPluginProviders;this.scope.onDispose(()=>{if(pluginInstance.get===getFromPluginProviders)Reflect.deleteProperty(pluginInstance,"get")});const contextExtensions=rec.metadata.contextExtensions;if(contextExtensions&&contextExtensions.length>0){installContextExtensions(rec.metadata.name,contextExtensions)}if(dynamicProviders){const normalized2=dynamicProviders.map(p=>normalizeProvider(p));const singletons=providers.getAllSingletons();const exported2=normalized2.map(def=>({token:def.provide,def,instance:singletons.get(def.provide)}));this.providers.mergeFromRegistry(providers,exported2);const scopeProviders=this.scope.providers;if(scopeProviders!==this.providers&&scopeProviders instanceof ProviderRegistry){const installedOnScope=!this.owner||this.owner.kind==="scope";const visibleBelow=installedOnScope?void 0:this.providers.subtreeBelow(scopeProviders)??this.providers;scopeProviders.mergeFromRegistry(providers,exported2,visibleBelow)}}this.instances.set(token,pluginInstance);this.logger?.verbose(`PluginRegistry: registered plugin '${rec.metadata.name}' (${hooks.length} hook(s), ${contextExtensions?.length??0} context extension(s))`)}}refuseStoresInBrowser(plugin,options){if(getRuntimeContext16().runtime!=="browser")return;refusePluginStoresInBrowser(declaredPluginStores(plugin,options,this.scope.metadata))}async instantiatePlugin(rec,deps){const depsInstances=await Promise.all([...deps].map(t=>this.providers.resolveBootstrapDep(t)));switch(rec.kind){case"CLASS":this.refuseStoresInBrowser(rec.useClass,{});return instantiateClassPlugin(rec.useClass,depsInstances,rec.providers);case"CLASS_TOKEN":this.refuseStoresInBrowser(rec.provide,{});return instantiateClassPlugin(rec.provide,depsInstances,rec.providers);case"VALUE":{const value=rec.useValue;const recorded=initOptionsOf(value);if(recorded)this.refuseStoresInBrowser(rec.provide,recorded.options);const init=installedPluginValues.has(value)?recorded:void 0;installedPluginValues.add(value);if(init&&isDynamicPluginClass(rec.provide)){return{pluginInstance:new rec.provide(init.options),dynamicProviders:rec.providers,dynamicTools:[]}}return{pluginInstance:value,dynamicProviders:rec.providers,dynamicTools:[]}}case"FACTORY":{const args=[];for(const d of rec.inject())args.push(await this.providers.resolveBootstrapDep(d));const produced=await rec.useFactory(...args);if(isDynamicPluginClass(rec.provide)&&!(produced instanceof rec.provide)){this.refuseStoresInBrowser(rec.provide,produced);const optionDerived=collectDynamicProviders(rec.provide,produced);return{pluginInstance:new rec.provide(produced),dynamicProviders:optionDerived.length>0?dedupePluginProviders([...optionDerived,...rec.providers??[]]):rec.providers,dynamicTools:collectDynamicTools(rec.provide,produced)}}return{pluginInstance:produced,dynamicProviders:rec.providers,dynamicTools:[]}}default:throw new InvalidRegistryKindError("plugin",rec.kind)}}}}});import{AsyncLocalStorage as AsyncLocalStorage6}from"@frontmcp/utils";function runAsAgent(agent,fn){return chains.run([...getAgentCallChain(),agent],fn)}function getAgentCallChain(){return chains.getStore()??[]}function nextAgentCallDepth(){const chain=getAgentCallChain();if(chain.length===0)return void 0;const limit=Math.min(...chain.map(agent=>agent.maxCallDepth));return{depth:chain.length,limit,chain}}var DEFAULT_MAX_AGENT_CALL_DEPTH,chains;var init_agent_call_chain=__esm({"libs/sdk/src/agent/agent-call-chain.ts"(){"use strict";DEFAULT_MAX_AGENT_CALL_DEPTH=3;chains=new AsyncLocalStorage6}});import{AuthorityDeniedError as AuthorityDeniedError7,resolveRequiredScopes as resolveRequiredScopes6}from"@frontmcp/auth";import{ExecutionTimeoutError as ExecutionTimeoutError2,withTimeout as withTimeout2}from"@frontmcp/guard";import{internalZ as z88}from"@frontmcp/lazy-zod";import{CallToolRequestSchema as CallToolRequestSchema3,CallToolResultSchema as CallToolResultSchema3}from"@frontmcp/protocol";function invalidOutputFrom(outputError){return outputError instanceof InvalidOutputError?outputError:new InvalidOutputError}function findAgentForCall(agents,toolName){return agents.findById(toolName)??agents.findByName(toolName)??agents.getAgents(true).find(entry=>entry.fullName===toolName||entry.name===toolName)}var inputSchema11,outputSchema11,stateSchema11,plan11,name11,agentClassHooksJoin,Stage11,CallAgentFlow;var init_call_agent_flow=__esm({"libs/sdk/src/agent/flows/call-agent.flow.ts"(){"use strict";init_completion_events();init_common();init_errors();init_entry_class_hooks();init_hooks_utils();init_flow_context_providers();init_abort_utils();init_agent_call_chain();inputSchema11=z88.object({request:CallToolRequestSchema3,ctx:z88.any(),gatedBy:z88.literal("tools:call-tool").optional()});outputSchema11=CallToolResultSchema3;stateSchema11=z88.object({input:z88.looseObject({name:z88.string().min(1).max(128),arguments:z88.looseObject({}).optional()}),authInfo:z88.any().optional(),agent:z88.instanceof(AgentEntry),agentContext:z88.instanceof(AgentContext),rawOutput:z88.any().optional(),output:outputSchema11,_agentOwnerId:z88.string().optional(),progressToken:z88.union([z88.string(),z88.number()]).optional(),jsonRpcRequestId:z88.union([z88.string(),z88.number()]).optional(),executionMeta:z88.object({iterations:z88.number().optional(),durationMs:z88.number().optional(),usage:z88.object({promptTokens:z88.number().optional(),completionTokens:z88.number().optional(),totalTokens:z88.number().optional()}).optional()}).optional(),semaphoreTicket:z88.any().optional(),abandonedExecution:z88.instanceof(Promise).optional(),executionAbort:z88.instanceof(AbortController).optional(),executionStartedAt:z88.number().optional(),executionError:z88.any().optional(),parsedOutput:z88.any().optional(),outputError:z88.any().optional()});plan11={pre:["parseInput","findAgent","checkCallDepth","checkEntryAuthorities","checkAgentAuthorization","createAgentContext","acquireQuota","acquireSemaphore"],execute:["validateInput","execute","validateOutput"],finalize:["releaseSemaphore","releaseQuota","parseOutput","emitCompletion","finalize"]};name11="agents:call-agent";agentClassHooksJoin=entryClassHooksJoin({flow:name11,plan:plan11,contextStage:"createAgentContext"});({Stage:Stage11}=FlowHooksOf(name11));CallAgentFlow=class extends FlowBase{static resolveHookEntryClass(rawInput,scope){const toolName=rawInput?.request?.params?.name;if(typeof toolName!=="string"||!scope.agents)return void 0;return findAgentForCall(scope.agents,toolName)?.record.provide}logger=this.scopeLogger.child("CallAgentFlow");get gatedByToolFlow(){return this.input.gatedBy==="tools:call-tool"}async parseInput(){this.logger.verbose("parseInput:start");let method;let params;let ctx;try{const inputData=inputSchema11.parse(this.rawInput);method=inputData.request.method;params=inputData.request.params;ctx=inputData.ctx}catch(e){throw new InvalidInputError("Invalid Input",e instanceof z88.ZodError?e.issues:void 0)}if(method!=="tools/call"){this.logger.warn(`parseInput: invalid method "${method}"`);throw new InvalidMethodError(method,"tools/call")}const{name:toolName}=params;const agentId=toolName;let agent;if(this.scope.agents){agent=this.scope.agents.findById(agentId)??this.scope.agents.findByName(agentId)}const agentOwnerId=agent?.owner?.id;const progressToken=params._meta?.progressToken;const jsonRpcRequestId=ctx.requestId;this.state.set({input:params,authInfo:ctx.authInfo,_agentOwnerId:agentOwnerId,progressToken,jsonRpcRequestId});this.logger.verbose("parseInput:done")}async findAgent(){this.logger.verbose("findAgent:start");const agents=this.scope.agents;if(!agents){this.logger.warn("findAgent: no agent registry available");throw new AgentNotFoundError(this.state.required.input.name)}const activeAgents=agents.getAgents(true);this.logger.verbose(`findAgent: discovered ${activeAgents.length} active agent(s) (including hidden)`);const{name:toolName}=this.state.required.input;const agentId=toolName;const agent=findAgentForCall(agents,toolName);if(!agent){this.logger.warn(`findAgent: agent "${agentId}" not found`);throw new AgentNotFoundError(agentId)}this.logger=this.logger.child(`CallAgentFlow(${agent.name})`);this.state.set("agent",agent);this.logger.verbose(`findAgent: agent "${agent.name}" found`);this.logger.verbose("findAgent:done")}async checkCallDepth(){const next=nextAgentCallDepth();if(!next||next.depth<=next.limit)return;const agent=this.state.required.agent;this.logger.warn(`checkCallDepth: agent call ${next.depth} exceeds maxCallDepth ${next.limit}`);throw new AgentCallDepthExceededError(agent.id,next.chain.map(running=>running.id),next.limit)}async checkEntryAuthorities(){this.logger.verbose("checkEntryAuthorities:start");if(this.gatedByToolFlow){this.logger.verbose("checkEntryAuthorities:skip (checked by the invoke tool flow)");return}const engine=this.scope.authoritiesEngine;const ctxBuilder=this.scope.authoritiesContextBuilder;if(!engine||!ctxBuilder){this.logger.verbose("checkEntryAuthorities:skip (no engine configured)");return}const agent=this.state.agent;if(!agent)return;const metadata=agent.metadata;const authorities=metadata["authorities"];if(!authorities){this.logger.verbose("checkEntryAuthorities:skip (no authorities on agent)");return}const authInfo=this.state.authInfo??{};const stateInput=this.state.input;const input=stateInput?.["arguments"]??stateInput??{};const evalCtx=ctxBuilder.build(authInfo,input);const result=await engine.evaluate(authorities,evalCtx);if(!result.granted){let requiredScopes;const scopeMapping=this.scope.authoritiesScopeMapping;if(scopeMapping&&result.denial){requiredScopes=resolveRequiredScopes6(result.denial,scopeMapping,authorities)}throw new AuthorityDeniedError7({entryType:"Agent",entryName:agent.fullName||agent.name,deniedBy:result.deniedBy??"policy denied",denial:result.denial,requiredScopes})}this.logger.verbose("checkEntryAuthorities:done")}async checkAgentAuthorization(){this.logger.verbose("checkAgentAuthorization:start");const{agent,authInfo}=this.state;const authorization=authInfo?.extra?.["authorization"];if(!authorization){this.logger.verbose("checkAgentAuthorization:skip (no auth context)");return}const appId=agent?.owner?.id;if(!appId){this.logger.verbose("checkAgentAuthorization:skip (no owner)");return}const isAppAuthorized=authorization.authorizedAppIds?.includes(appId)||appId in(authorization.authorizedApps||{});if(!isAppAuthorized){this.logger.verbose(`checkAgentAuthorization: app "${appId}" not authorized, but proceeding`)}this.logger.verbose("checkAgentAuthorization:done")}async createAgentContext(){this.logger.verbose("createAgentContext:start");const{ctx}=this.input;const{agent,input}=this.state.required;const progressToken=this.state.progressToken;const authInfo=this.state.authInfo;try{const sessionKey=authInfo?.sessionId??"anonymous";const agentViews=await agent.providers.buildViews(sessionKey,new Map(this.deps),this.scope.providers);const contextProviders=new FlowContextProviders(agent.providers,agentViews.context);const executionAbort=linkedAbortController(ctx.signal);this.state.set("executionAbort",executionAbort);const context=agent.create(input.arguments,{...ctx,progressToken,contextProviders,signal:executionAbort.signal});await context.loadAuthContext();this.appendContextHooks(hooksBoundTo(this.scope.hooks.getClsHooks(agent.record.provide),context));context.mark("createAgentContext");const frontmcpContext=context.tryGetContext();const sdkAuthInfo=authInfo;const jsonRpcRequestId=this.state.jsonRpcRequestId;if(frontmcpContext&&sdkAuthInfo?.transport?.sendElicitRequest&&jsonRpcRequestId!==void 0){const transport=sdkAuthInfo.transport;frontmcpContext.setTransport({sendElicitRequest:transport.sendElicitRequest.bind(transport),type:transport.type??"unknown",jsonRpcRequestId})}this.state.set("agentContext",context);this.logger.verbose("createAgentContext:done")}catch(error){this.logger.error("createAgentContext: failed to create context",error);throw new AgentExecutionError(agent.metadata.name,error instanceof Error?error:void 0)}}async acquireQuota(){this.logger.verbose("acquireQuota:start");const manager=this.scope.rateLimitManager;if(!manager||this.gatedByToolFlow){this.state.agentContext?.mark("acquireQuota");this.logger.verbose("acquireQuota:done (no rate limit manager)");return}const{agent}=this.state.required;const context=this.tryGetContext();const partitionCtx=buildPartitionContext(context);if(!context?.has(GLOBAL_RATE_LIMIT_CHECKED)){const globalResult=await manager.checkGlobalRateLimit(partitionCtx);if(!globalResult.allowed){throw new RateLimitError(Math.ceil((globalResult.retryAfterMs??6e4)/1e3))}}const result=await manager.checkRateLimit(agent.metadata.name,agent.metadata.rateLimit,partitionCtx);if(!result.allowed){throw new RateLimitError(Math.ceil((result.retryAfterMs??6e4)/1e3))}this.state.agentContext?.mark("acquireQuota");this.logger.verbose("acquireQuota:done")}async acquireSemaphore(){this.logger.verbose("acquireSemaphore:start");const manager=this.scope.rateLimitManager;if(!manager||this.gatedByToolFlow){this.state.agentContext?.mark("acquireSemaphore");this.logger.verbose("acquireSemaphore:done (no rate limit manager)");return}const{agent}=this.state.required;const partitionCtx=buildPartitionContext(this.tryGetContext());const ticket=await acquireConcurrencySlots(manager,agent.metadata.name,agent.metadata.concurrency,partitionCtx);this.state.set("semaphoreTicket",ticket);this.state.agentContext?.mark("acquireSemaphore");this.logger.verbose("acquireSemaphore:done")}async validateInput(){this.logger.verbose("validateInput:start");const{agent,input}=this.state.required;const{agentContext}=this.state;if(!agentContext){return}agentContext.mark("validateInput");try{agentContext.input=agent.parseInput(input);this.logger.verbose("validateInput:done")}catch(err){if(err instanceof z88.ZodError){throw new InvalidInputError("Invalid agent input",err.issues)}this.logger.error("validateInput: failed to parse input",err);throw new InvalidInputError("Unknown error occurred when trying to parse agent input")}}async execute(){this.logger.verbose("execute:start");const agentContext=this.state.agentContext;const agent=this.state.agent;if(!agentContext||!agent){return}agentContext.mark("execute");const startTime=Date.now();this.state.set("executionStartedAt",startTime);const timeoutMs=this.gatedByToolFlow?agent.metadata.timeout?.executeMs===void 0?agent.metadata.execution?.timeout:void 0:agent.metadata.timeout?.executeMs??agent.metadata.execution?.timeout??this.scope.rateLimitManager?.config?.defaultTimeout?.executeMs;const runningAgent={id:agent.id,maxCallDepth:agent.metadata.swarm?.maxCallDepth??DEFAULT_MAX_AGENT_CALL_DEPTH};const running=runAsAgent(runningAgent,async()=>{agentContext.output=await agentContext.execute(agentContext.input)});try{await(timeoutMs?withTimeout2(()=>running,timeoutMs,agent.metadata.name):running);this.state.set("executionMeta",{durationMs:Date.now()-startTime});this.logger.verbose("execute:done")}catch(error){this.state.executionAbort?.abort(error);this.state.set("executionError",error);if(error instanceof ExecutionTimeoutError2){this.logger.warn("execute: agent execution timed out",{agent:agent.metadata.name,timeoutMs});this.state.set("abandonedExecution",running);throw error}if(this.gatedByToolFlow)throw error;throw new AgentExecutionError(agent.metadata.name,error instanceof Error?error:void 0)}}async validateOutput(){this.logger.verbose("validateOutput:start");const{agentContext}=this.state;if(!agentContext){return}agentContext.mark("validateOutput");this.state.set("rawOutput",agentContext.output);this.logger.verbose("validateOutput:done")}async releaseSemaphore(){this.logger.verbose("releaseSemaphore:start");const ticket=this.state.semaphoreTicket;if(ticket){const release=async()=>{try{await ticket.release();this.logger.verbose("releaseSemaphore: slot released")}catch(error){this.logger.warn("releaseSemaphore: failed to release slot",error)}};const abandonedExecution=this.state.abandonedExecution;if(abandonedExecution)void abandonedExecution.then(release,release);else await release()}this.state.agentContext?.mark("releaseSemaphore");this.logger.verbose("releaseSemaphore:done")}async releaseQuota(){this.logger.verbose("releaseQuota:start");this.state.agentContext?.mark("releaseQuota");this.logger.verbose("releaseQuota:done")}async parseOutput(){const{agent,rawOutput}=this.state;if(!agent||rawOutput===void 0)return;const parseResult=agent.safeParseOutput(rawOutput);if(parseResult.success)this.state.set("parsedOutput",parseResult.data);else this.state.set("outputError",parseResult.error)}async emitCompletion(){const{agent,agentContext,executionStartedAt,executionError,outputError,authInfo}=this.state;if(!agent||executionStartedAt===void 0)return;if(executionError instanceof ElicitationFallbackRequired||executionError instanceof FlowControl)return;const failure=executionError??(outputError!==void 0?invalidOutputFrom(outputError):void 0);const failed=failure!==void 0;const requestId=this.tryGetContext()?.requestId;const sessionId=typeof authInfo?.sessionId==="string"&&authInfo.sessionId?authInfo.sessionId:void 0;completionEventsOf(this.scope).agents.emit({agentId:agent.id,agentName:agent.name,status:failed?"error":"success",durationMs:Date.now()-executionStartedAt,...failed?{error:failure instanceof Error?failure.message:String(failure)}:{output:completionOutputText(agentContext?.output)},...requestId?{runId:requestId}:{},...sessionId?{sessionId}:{}})}async finalize(){this.logger.verbose("finalize:start");const{agent,rawOutput,parsedOutput,outputError,executionMeta}=this.state;if(!agent){this.logger.verbose("finalize: skipping (no agent in state)");return}if(rawOutput===void 0){this.logger.verbose("finalize: skipping (no output - execute stage likely failed)");return}if(outputError!==void 0||parsedOutput===void 0){this.logger.error("finalize: output validation failed",{agent:agent.metadata.name,errors:outputError});throw invalidOutputFrom(outputError)}const result=parsedOutput;if(executionMeta){result._meta={...result._meta,"agent/execution":{agentId:agent.id,agentName:agent.name,durationMs:executionMeta.durationMs,iterations:executionMeta.iterations,usage:executionMeta.usage}}}this.logger.verbose("finalize: sending response",{agent:agent.metadata.name,hasContent:Array.isArray(result.content)&&result.content.length>0,contentParts:Array.isArray(result.content)?result.content.length:0,contentBytes:Array.isArray(result.content)?result.content.reduce((sum,part)=>{const str=JSON.stringify(part);return sum+(typeof Buffer!=="undefined"?Buffer.byteLength(str,"utf8"):new TextEncoder().encode(str).byteLength)},0):0,hasStructuredContent:result.structuredContent!==void 0,hasMeta:result._meta!==void 0,metaKeys:result._meta?Object.keys(result._meta):[],isError:result.isError});this.respond(result);this.logger.verbose("finalize:done")}};__decorateClass([Stage11("parseInput")],CallAgentFlow.prototype,"parseInput",1);__decorateClass([Stage11("findAgent")],CallAgentFlow.prototype,"findAgent",1);__decorateClass([Stage11("checkCallDepth")],CallAgentFlow.prototype,"checkCallDepth",1);__decorateClass([Stage11("checkEntryAuthorities")],CallAgentFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage11("checkAgentAuthorization")],CallAgentFlow.prototype,"checkAgentAuthorization",1);__decorateClass([Stage11("createAgentContext")],CallAgentFlow.prototype,"createAgentContext",1);__decorateClass([Stage11("acquireQuota")],CallAgentFlow.prototype,"acquireQuota",1);__decorateClass([Stage11("acquireSemaphore")],CallAgentFlow.prototype,"acquireSemaphore",1);__decorateClass([Stage11("validateInput")],CallAgentFlow.prototype,"validateInput",1);__decorateClass([Stage11("execute")],CallAgentFlow.prototype,"execute",1);__decorateClass([Stage11("validateOutput")],CallAgentFlow.prototype,"validateOutput",1);__decorateClass([Stage11("releaseSemaphore")],CallAgentFlow.prototype,"releaseSemaphore",1);__decorateClass([Stage11("releaseQuota")],CallAgentFlow.prototype,"releaseQuota",1);__decorateClass([Stage11("parseOutput")],CallAgentFlow.prototype,"parseOutput",1);__decorateClass([Stage11("emitCompletion")],CallAgentFlow.prototype,"emitCompletion",1);__decorateClass([Stage11("finalize")],CallAgentFlow.prototype,"finalize",1);CallAgentFlow=__decorateClass([FrontMcpFlow({name:name11,plan:plan11,inputSchema:inputSchema11,outputSchema:outputSchema11,access:"authorized"})],CallAgentFlow)}});import"reflect-metadata";import{ProviderScope as ProviderScope5}from"@frontmcp/di";var AgentScope,AgentScopeEntry;var init_agent_scope=__esm({"libs/sdk/src/agent/agent.scope.ts"(){"use strict";init_adapter_registry();init_common();init_errors();init_flow_registry();init_hook_order();init_hook_registry();init_plugin_registry();init_get_prompt_flow();init_prompts_list_flow();init_prompt_registry();init_provider_registry();init_read_resource_flow();init_resource_templates_list_flow();init_resources_list_flow();init_resource_registry();init_scope();init_call_tool_flow();init_tool_instance();init_tool_registry();init_tool_utils();init_agent_registry();init_call_agent_flow();AgentScope=class _AgentScope{constructor(parentScope,agentId,metadata,agentToken,options){this.metadata=metadata;this.options=options;this.parentScope=parentScope;this.id=`agent:${agentId}`;this.entryPath=parentScope.entryPath;this.routeBase=parentScope.routeBase;this.fullPath=parentScope.fullPath;this.logger=parentScope.logger.child(`AgentScope(${agentId})`);this.agentOwner={kind:"agent",id:this.id,ref:agentToken};this.ready=this.initialize()}metadata;options;id;entryPath;routeBase;fullPath;logger;ready;parentScope;agentOwner;agentProviders;agentPlugins;agentAdapters;agentTools;agentResources;agentPrompts;agentAgents;agentHooks;agentFlows;async initialize(){const agentScopeEntry=new AgentScopeEntry(this);this.agentProviders=new ProviderRegistry([{scope:ProviderScope5.GLOBAL,name:"ScopeEntry",provide:ScopeEntry,useValue:agentScopeEntry},{scope:ProviderScope5.GLOBAL,name:"Scope",provide:Scope,useValue:agentScopeEntry},{scope:ProviderScope5.GLOBAL,name:"AgentScope",provide:_AgentScope,useValue:this},{scope:ProviderScope5.GLOBAL,name:"FrontMcpLogger",provide:FrontMcpLogger,useValue:this.logger},...this.metadata.providers??[]],this.options?.providers??this.parentScope.providers);await this.agentProviders.ready;this.agentHooks=new HookRegistry(this.agentProviders,[]);await this.agentHooks.ready;if(this.metadata.execution?.inheritPlugins===true&&this.options){this.agentHooks.inheritFrom(this.parentScope.hooks,this.options.ownerId)}this.agentFlows=new FlowRegistry(this.agentProviders,[CallToolFlow,CallAgentFlow,ReadResourceFlow,ResourcesListFlow,ResourceTemplatesListFlow,GetPromptFlow,PromptsListFlow]);await this.agentFlows.ready;const pluginOwner={kind:"agent",id:this.id,ref:this.agentOwner.ref};this.agentPlugins=new PluginRegistry(this.agentProviders,this.metadata.plugins??[],pluginOwner);await this.agentPlugins.ready;this.agentAdapters=new AdapterRegistry(this.agentProviders,this.metadata.adapters??[]);await this.agentAdapters.ready;this.agentTools=new ToolRegistry(this.agentProviders,[],this.agentOwner);await this.agentTools.ready;const toolTypes=this.metadata.tools??[];for(const toolType of toolTypes){try{const record=normalizeTool(toolType);if(isExternalToolRecord(record)){await this.agentTools.registerExternalTools([record]);continue}const toolInstance=new ToolInstance(record,this.agentProviders,this.agentOwner);await toolInstance.ready;this.agentTools.registerToolInstance(toolInstance)}catch(error){this.logger.error(`Failed to initialize tool in agent scope ${this.id}`,error);throw error}}this.agentResources=new ResourceRegistry(this.agentProviders,this.metadata.resources??[],this.agentOwner);await this.agentResources.ready;this.agentPrompts=new PromptRegistry(this.agentProviders,this.metadata.prompts??[],this.agentOwner);await this.agentPrompts.ready;this.agentAgents=new AgentRegistry(this.agentProviders,this.metadata.agents??[],this.agentOwner);await this.agentAgents.ready;checkHookOrder(hookRunsOf(this.agentHooks),message=>this.logger.warn(message));this.logger.info(`AgentScope initialized with ${toolTypes.length} tool(s), ${this.metadata.plugins?.length??0} plugin(s)`)}get tools(){return this.agentTools}get hooks(){return this.agentHooks}get providers(){return this.agentProviders}get plugins(){return this.agentPlugins}get adapters(){return this.agentAdapters}get resources(){return this.agentResources}get prompts(){return this.agentPrompts}get agents(){return this.agentAgents}get auth(){return this.parentScope.auth}get authProviders(){return this.parentScope.authProviders}get apps(){return this.parentScope.apps}get notifications(){return this.parentScope.notifications}onDispose(callback){return this.parentScope.onDispose(callback)}get toolUI(){return this.parentScope.toolUI}get skills(){return this.parentScope.skills}get scopeMetadata(){return this.parentScope.metadata}get authoritiesEngine(){return this.parentScope.authoritiesEngine}get authoritiesContextBuilder(){return this.parentScope.authoritiesContextBuilder}get authoritiesScopeMapping(){return this.parentScope.authoritiesScopeMapping}get rateLimitManager(){return this.parentScope.rateLimitManager}get persistentQuestions(){return this.parentScope.persistentQuestions}get publicAccessGuard(){return this.parentScope.publicAccessGuard}async registryFlows(...flows){await this.agentFlows.registryFlows(flows)}runFlow(name51,input,deps){return this.agentFlows.runFlow(name51,input,deps)}async runFlowForOutput(name51,input,deps){const result=await this.agentFlows.runFlow(name51,input,deps);if(result!==void 0){return result}throw new FlowExitedWithoutOutputError}};AgentScopeEntry=class{constructor(agentScope){this.agentScope=agentScope;this.id=agentScope.id;this.entryPath=agentScope.entryPath;this.routeBase=agentScope.routeBase;this.fullPath=agentScope.fullPath;this.logger=agentScope.logger}agentScope;id;entryPath;routeBase;fullPath;logger;get auth(){return this.agentScope.auth}get hooks(){return this.agentScope.hooks}get authProviders(){return this.agentScope.authProviders}get providers(){return this.agentScope.providers}get apps(){return this.agentScope.apps}get tools(){return this.agentScope.tools}get resources(){return this.agentScope.resources}get prompts(){return this.agentScope.prompts}get agents(){return this.agentScope.agents}get skills(){return this.agentScope.skills}get notifications(){return this.agentScope.notifications}get toolUI(){return this.agentScope.toolUI}get transportService(){return void 0}get rateLimitManager(){return this.agentScope.rateLimitManager}get publicAccessGuard(){return this.agentScope.publicAccessGuard}get elicitationStore(){return void 0}get persistentQuestions(){return this.agentScope.persistentQuestions}get metadata(){return this.agentScope.scopeMetadata}get authoritiesEngine(){return this.agentScope.authoritiesEngine}get authoritiesContextBuilder(){return this.agentScope.authoritiesContextBuilder}get authoritiesScopeMapping(){return this.agentScope.authoritiesScopeMapping}get record(){return void 0}get ready(){return this.agentScope.ready}onDispose(callback){return this.agentScope.onDispose(callback)}registryFlows(...flows){return this.agentScope.registryFlows(...flows)}runFlow(name51,input,deps){return this.agentScope.runFlow(name51,input,deps)}runFlowForOutput(name51,input,deps){return this.agentScope.runFlowForOutput(name51,input,deps)}}}});var agent_instance_exports={};__export(agent_instance_exports,{AGENT_ONLY_METADATA_KEYS:()=>AGENT_ONLY_METADATA_KEYS,AgentInstance:()=>AgentInstance});import{AuthorityDeniedError as AuthorityDeniedError8}from"@frontmcp/auth";import{toJSONSchema as toJSONSchema5,internalZ as z89}from"@frontmcp/lazy-zod";var VALID_AGENT_HOOK_FLOWS,AGENT_SURFACE2,AGENT_ONLY_METADATA_KEYS,AgentInstance,FunctionAgentContext;var init_agent_instance=__esm({"libs/sdk/src/agent/agent.instance.ts"(){"use strict";init_config();init_common();init_availability();init_tool_decorator();init_call_surface();init_running_tool();init_errors();init_entry_class_hooks();init_hooks_utils();init_prompt_utils();init_provider_utils();init_resource_utils();init_tool_instance();init_tool_utils();init_mcp_error_utils();init_adapters();init_agent_builtin_tools();init_agent_scope();init_agent_utils();init_call_agent_flow();VALID_AGENT_HOOK_FLOWS=["agents:call-agent","agents:list-agents"];AGENT_SURFACE2="agent";AGENT_ONLY_METADATA_KEYS=new Set(["id","name","description","systemInstructions","inputSchema","outputSchema","llm","providers","plugins","adapters","agents","tools","resources","prompts","exports","swarm","execution","tags","hideFromDiscovery"]);AgentInstance=class extends AgentEntry{providerRegistry;scope;hooks;llmAdapter=null;agentTools=[];agentScope=null;agentToolInstance=null;exportedResources=[];exportedPrompts=[];constructor(record,providers,owner){super(record);this.owner=owner;this.providerRegistry=providers;this.name=record.metadata.id??record.metadata.name;this.id=record.metadata.id??record.metadata.name;this.fullName=this.owner.id+":"+this.name;this.scope=this.providerRegistry.getActiveScope();this.hooks=this.scope.hooks;this.inputSchema=record.metadata.inputSchema??{};this.outputSchema=record.metadata.outputSchema;this.systemInstructions=record.metadata.systemInstructions;this.ready=this.initialize()}async initialize(){await this.initializeAgentTools();this.assertNoBuiltinToolClash();await this.initializeLlmAdapter();await this.registerHooks();await this.createAgentAsTool()}assertNoBuiltinToolClash(){if(!this.agentScope)return;const builtins=new Set(offeredAgentBuiltinTools(this.agentScope));const clash=this.agentTools.find(tool=>builtins.has(tool.metadata.id??tool.metadata.name));if(!clash)return;throw new AgentConfigurationError(`Agent "${this.name}" has a tool named "${clash.metadata.id??clash.metadata.name}", the name of a built-in tool its model reads the agent's resources and prompts with. Rename the tool.`,{agentId:this.id})}async initializeAgentTools(){const metadata=this.record.metadata;const hasTools=(metadata.tools?.length??0)>0;const hasPlugins=(metadata.plugins?.length??0)>0;const hasAdapters=(metadata.adapters?.length??0)>0;const hasProviders=(metadata.providers?.length??0)>0;const hasResources=(metadata.resources?.length??0)>0;const hasPrompts=(metadata.prompts?.length??0)>0;const hasAgents=(metadata.agents?.length??0)>0;if(!hasTools&&!hasPlugins&&!hasAdapters&&!hasProviders&&!hasResources&&!hasPrompts&&!hasAgents){this.resolveExports(void 0);return}this.agentScope=new AgentScope(this.scope,this.id,metadata,this.record.provide,{ownerId:this.owner.id,providers:this.providerRegistry});await this.agentScope.ready;this.agentTools=this.agentScope.tools.getTools(true);this.resolveExports(this.agentScope);this.scope.logger.info(`Agent ${this.name} initialized with AgentScope: ${this.agentTools.length} tool(s), ${metadata.plugins?.length??0} plugin(s)`)}resolveExports(agentScope){const exportsConfig=this.record.metadata.exports;if(!exportsConfig)return;const resources=agentScope?.resources.getInlineResources()??[];if(exportsConfig.resources==="*"){this.exportedResources=resources}else if(exportsConfig.resources){this.exportedResources=exportsConfig.resources.map(item=>{const token=(isResourceTemplate(item)?normalizeResourceTemplate(item):normalizeResource(item)).provide;const entry=resources.find(resource=>resource.record.provide===token);if(!entry)throw this.undeclaredExportError("resources",token);return entry})}const prompts=agentScope?.prompts.getInlinePrompts()??[];if(exportsConfig.prompts==="*"){this.exportedPrompts=prompts}else if(exportsConfig.prompts){this.exportedPrompts=exportsConfig.prompts.map(item=>{const token=normalizePrompt(item).provide;const entry=prompts.find(prompt=>prompt.record.provide===token);if(!entry)throw this.undeclaredExportError("prompts",token);return entry})}if(exportsConfig.providers&&exportsConfig.providers.length>0){const declared=new Set((this.record.metadata.providers??[]).map(item=>normalizeProvider(item).provide));const tokens=exportsConfig.providers.map(item=>{const token=normalizeProvider(item).provide;if(!declared.has(token)||!agentScope)throw this.undeclaredExportError("providers",token);return token});if(agentScope){const exported=tokens.map(token=>agentScope.providers.getProviderInfo(token));this.providerRegistry.mergeFromRegistry(agentScope.providers,exported)}}}undeclaredExportError(kind,token){const label=typeof token==="function"?token.name||"(anonymous)":typeof token==="symbol"?token.description??token.toString():String(token);return new AgentConfigurationError(`Agent "${this.name}" exports ${kind} "${label}", which is not one of its own ${kind} (\`${kind}: [...]\`)`,{agentId:this.id})}getExportedResources(){return this.exportedResources}getExportedPrompts(){return this.exportedPrompts}async initializeLlmAdapter(){const llmConfig=this.record.metadata.llm;if(!llmConfig){return}const adapterOptions={providerResolver:{get:token=>{return this.providerRegistry.get(token)},tryGet:token=>{try{return this.providerRegistry.get(token)}catch{return void 0}}},entityContext:{entityType:"agents",entityName:this.name}};try{const configService=this.providerRegistry.get(ConfigService);if(configService){adapterOptions.configResolver=this.createConfigResolver(configService)}}catch{this.scope.logger.debug(`ConfigService not available for agent ${this.name} - withConfig resolution disabled`)}try{this.llmAdapter=createAdapter(llmConfig,adapterOptions)}catch(error){this.scope.logger.error(`Failed to create LLM adapter for agent ${this.name}`,error);throw error}}createConfigResolver(configService){const config=configService.getAll();const getNestedValue2=path4=>{const keys=path4.split(".");let current=config;for(const key of keys){if(current&&typeof current==="object"&&key in current){current=current[key]}else{return void 0}}return current};return{get(path4){const value=getNestedValue2(path4);if(value===void 0){throw new AgentConfigKeyNotFoundError(path4)}return value},tryGet(path4){return getNestedValue2(path4)}}}async registerHooks(){const allHooks=normalizeHooksFromCls(this.record.provide);const validHooks=allHooks.filter(hook=>VALID_AGENT_HOOK_FLOWS.includes(hook.metadata.flow));const invalidHooks=allHooks.filter(hook=>!VALID_AGENT_HOOK_FLOWS.includes(hook.metadata.flow));if(invalidHooks.length>0){const className=this.getClassName();const invalidFlowNames=invalidHooks.map(h2=>h2.metadata.flow).join(", ");throw new InvalidHookFlowError(`Agent "${className}" has hooks for unsupported flows: ${invalidFlowNames}. Only agent flows (${VALID_AGENT_HOOK_FLOWS.join(", ")}) are supported on agent classes.`)}const unreachable=describeUnreachableEntryClassHooks(validHooks,agentClassHooksJoin,["agents:list-agents"]);if(unreachable.length>0){throw new InvalidHookFlowError(unreachableHooksMessage("Agent",this.getClassName(),unreachable))}if(validHooks.length>0){await this.hooks.registerHooks(true,...validHooks)}}getClassName(){const provide=this.record.provide;if(typeof provide==="function"&&"name"in provide){return provide.name}return"Unknown"}async createAgentAsTool(){if(!this.llmAdapter){this.scope.logger.debug(`Agent ${this.name} has no LLM adapter configured - skipping tool registration. Agent will not be callable as a tool via invoke_${this.id}.`);return}try{const toolMetadata=this.buildAgentToolMetadata();const agentToolFunction=frontMcpTool(toolMetadata)(this.createAgentToolExecuteHandler());const toolRecord=normalizeTool(agentToolFunction);this.agentToolInstance=new ToolInstance(toolRecord,this.providerRegistry,this.owner);await this.agentToolInstance.ready;this.scope.logger.debug(`Created agent tool instance: ${this.agentToolInstance.name} for agent ${this.name}`)}catch(error){this.scope.logger.error(`Failed to create agent tool instance for ${this.name}`,error);throw error}}buildAgentToolMetadata(){const agentMeta=this.record.metadata;const toolMeta={id:agentToolName(this.id),name:agentToolName(this.id),description:this.buildToolDescription(agentMeta),inputSchema:this.inputSchema??{},outputSchema:agentMeta.outputSchema,tags:[...agentMeta.tags??[],"agent"],annotations:{title:agentMeta.name,readOnlyHint:false,openWorldHint:true},hideFromDiscovery:agentMeta.hideFromDiscovery};const extendedMeta=agentMeta;const mutableToolMeta=toolMeta;for(const[key,value]of Object.entries(extendedMeta)){if(value===void 0||AGENT_ONLY_METADATA_KEYS.has(key)||key in mutableToolMeta)continue;mutableToolMeta[key]=value}return toolMeta}createAgentToolExecuteHandler(){return async(input,toolCtx)=>{const authInfo=toolCtx.authInfo;const progressToken=toolCtx._progressTokenInternal;const requestId=toolCtx._jsonRpcRequestIdInternal;return this.scope.runFlowForOutput("agents:call-agent",{request:{method:"tools/call",params:{name:this.id,arguments:input,...progressToken!==void 0?{_meta:{progressToken}}:{}}},ctx:{authInfo,...requestId!==void 0?{requestId}:{},...toolCtx.signal?{signal:toolCtx.signal}:{}},gatedBy:"tools:call-tool"})}}getToolInstance(){return this.agentToolInstance}get providers(){return this.providerRegistry}getAgentTools(){return this.agentTools}declaresScopedLimits(){if(!this.agentScope)return false;const declaresLimit=tool=>Boolean(tool.metadata.rateLimit||tool.metadata.concurrency);return this.agentScope.tools.getTools(true).some(declaresLimit)||this.agentScope.agents.listAllInstances().some(agent=>agent.declaresScopedLimits())}getMetadata(){return this.record.metadata}getOutputSchema(){return this.outputSchema}getLlmAdapter(){return this.llmAdapter}create(input,ctx){if(!this.llmAdapter){throw new AgentNotConfiguredError(this.name)}const agentCtorArgs=this.buildAgentCtorArgs(input,ctx,this.llmAdapter);switch(this.record.kind){case"CLASS_TOKEN":return new this.record.provide(agentCtorArgs);case"FUNCTION":return new FunctionAgentContext(this.record,agentCtorArgs);case"VALUE":return this.record.useValue;case"FACTORY":return this.record.useFactory(this.providerRegistry);case"ESM":throw new AgentNotConfiguredError(`ESM agent "${this.name}" cannot be created via AgentInstance.create()`);case"REMOTE":throw new AgentNotConfiguredError(`Remote agent "${this.name}" cannot be created via AgentInstance.create()`);default:{const _exhaustive=this.record;throw new Error(`Unknown agent kind: ${_exhaustive.kind}`)}}}buildAgentCtorArgs(input,ctx,llmAdapter){const scope=this.providerRegistry.getActiveScope();const modelTools=this.getModelTools();return{metadata:this.metadata,input,providers:ctx.contextProviders??this.providerRegistry,logger:scope.logger,authInfo:ctx.authInfo,llmAdapter,toolDefinitions:modelTools.map(tool=>tool.kind==="builtin"?AGENT_BUILTIN_TOOL_DEFINITIONS[tool.name]:buildAgentToolDefinition(tool.entry)),toolExecutor:this.createToolExecutor(ctx,modelTools),agentInvoker:this.createAgentInvoker(ctx),...this.agentScope&&{privateScope:this.agentScope},progressToken:ctx.progressToken,signal:ctx.signal}}getModelTools(){const tools=[];const names=new Set;if(this.agentScope){for(const name51 of offeredAgentBuiltinTools(this.agentScope)){names.add(name51);tools.push({kind:"builtin",name:name51,scope:this.agentScope})}}const add=(entry,via)=>{const name51=entry.metadata.id??entry.metadata.name;if(names.has(name51)||!isOfferedOnSurface(entry.metadata.availableWhen,AGENT_SURFACE2))return;names.add(name51);tools.push({kind:"tool",name:name51,entry,via})};const nestedAgentTools=this.getNestedAgentTools();for(const tool of this.agentTools)add(tool,nestedAgentTools.has(tool)?"nested-agent":"agent-scope");for(const agent of this.getSwarmAgents()){const tool=agent.getToolInstance();if(tool)add(tool,"parent-scope")}for(const tool of this.getInheritedTools())add(tool,"parent-scope");return tools}getNestedAgentTools(){const tools=new Set;for(const agent of this.agentScope?.agents.listAllInstances()??[]){const tool=agent.getToolInstance();if(tool)tools.add(tool)}return tools}getSwarmAgents(){if(!this.canSeeSwarm())return[];return this.scope.agents?.getVisibleAgentsFor(this.id)??[]}getInheritedTools(){if(this.record.metadata.execution?.inheritParentTools!==true)return[];const agentTools=new Set;for(const agent of this.scope.agents?.listAllInstances()??[]){const tool=agent.getToolInstance();if(tool)agentTools.add(tool)}return(this.scope.tools?.getTools()??[]).filter(tool=>!agentTools.has(tool))}createToolExecutor(ctx,modelTools){const useToolFlow=this.record.metadata.execution?.useToolFlow!==false;return async(toolName,args)=>{const offered=modelTools.find(t=>t.name===toolName||t.kind==="tool"&&(t.entry.name===toolName||t.entry.fullName===toolName));if(!offered){throw new AgentToolNotFoundError(this.name,toolName,modelTools.map(t=>t.name))}if(offered.kind==="builtin"){return runAgentBuiltinTool(offered.scope,offered.name,args,{authInfo:ctx.authInfo})}const tool=offered.entry;if(offered.via==="parent-scope"){return this.callToolThrough(this.scope,tool,args,ctx)}if(this.agentScope&&(useToolFlow||offered.via==="nested-agent")){return this.callToolThrough(this.agentScope,tool,args,ctx)}await this.assertToolAuthorized(tool,ctx.authInfo,args);const runningTool={name:tool.name,fullName:tool.fullName};return runOnSurface(AGENT_SURFACE2,async()=>{const{contextProviders:_agentProviders,...toolCtx}=ctx;const toolContext=runAsTool(runningTool,()=>tool.create(args,toolCtx));try{return await runAsTool(runningTool,()=>Promise.resolve(toolContext.execute(args)))}catch(error){throw errorBehindFlowControl(error)}})}}async callToolThrough(scope,tool,args,ctx){const result=await scope.runFlowForOutput("tools:call-tool",{request:{method:"tools/call",params:{name:tool.fullName,arguments:args}},ctx:{authInfo:ctx.authInfo,signal:ctx.signal,_skipUI:true,surface:AGENT_SURFACE2,...this.isAgentPrivateScope(scope)&&{agentPrivateCall:true}}}).catch(error=>{throw errorBehindFlowControl(error)});return this.extractToolResult(result)}isAgentPrivateScope(scope){return scope===this.agentScope||scope===this.scope&&this.owner.kind==="agent"}createAgentInvoker(ctx){return async(agentId,input)=>{if(input!==void 0&&(typeof input!=="object"||input===null||Array.isArray(input))){throw new InvalidInputError(`invokeAgent("${agentId}"): the input must be an object of the agent's arguments`)}const args=input??{};const matches=agent=>agent.id===agentId||agent.name===agentId;const nested=this.agentScope?.agents.listAllInstances().find(matches);const nestedTool=nested?.getToolInstance();if(this.agentScope&&nestedTool){return this.callToolThrough(this.agentScope,nestedTool,args,ctx)}const visibleTool=this.getSwarmAgents().find(matches)?.getToolInstance();if(visibleTool){return this.callToolThrough(this.scope,visibleTool,args,ctx)}if(this.scope.agents?.listAllInstances().some(matches)){throw new AgentVisibilityError(this.id,agentId)}throw new AgentNotFoundError(agentId)}}async assertToolAuthorized(tool,authInfo,args){const authorities=tool.metadata["authorities"];if(!authorities)return;const entryName=tool.fullName||tool.name;const engine=this.scope.authoritiesEngine;const ctxBuilder=this.scope.authoritiesContextBuilder;if(!engine||!ctxBuilder){throw new AuthorityDeniedError8({entryType:"Tool",entryName,deniedBy:"authorities are not configured"})}const result=await engine.evaluate(authorities,ctxBuilder.build(authInfo??{},args));if(!result.granted){throw new AuthorityDeniedError8({entryType:"Tool",entryName,deniedBy:result.deniedBy??"policy denied",denial:result.denial})}}extractToolResult(mcpResult){if(!mcpResult)return void 0;if(mcpResult.isError){const errorContent=mcpResult.content?.[0];if(errorContent?.type==="text"){throw new AgentToolExecutionError(errorContent.text)}throw new AgentToolExecutionError("Tool execution failed")}if(mcpResult.structuredContent!==void 0){return mcpResult.structuredContent}const content=mcpResult.content;if(!content||content.length===0)return void 0;if(content.length===1&&content[0].type==="text"){const text=content[0].text;try{return JSON.parse(text)}catch{return text}}return content}parseInput(input){const inputSchema45=z89.object(this.inputSchema??{});return inputSchema45.parse(input.arguments)}parseOutput(raw){const descriptor=this.outputSchema;return buildParsedToolResult(descriptor,raw)}safeParseOutput(raw){try{return{success:true,data:this.parseOutput(raw)}}catch(error){return{success:false,error}}}getToolDefinition(){const metadata=this.record.metadata;let inputSchema45={type:"object",properties:{}};const toolInputSchema=this.agentToolInstance?.getInputJsonSchema();if(toolInputSchema){inputSchema45=toolInputSchema}else if(this.inputSchema&&Object.keys(this.inputSchema).length>0){try{inputSchema45=toJSONSchema5(z89.object(this.inputSchema),{io:"input",unrepresentable:"any"})}catch{this.scope.logger.warn(`Failed to convert input schema for agent ${this.name}`)}}return{name:agentToolName(this.id),description:this.buildToolDescription(metadata),inputSchema:inputSchema45}}buildToolDescription(metadata){if(metadata.description){return metadata.description}const baseDescription=`Invoke the ${metadata.name} agent.`;if(metadata.systemInstructions){return`${baseDescription} ${metadata.systemInstructions.slice(0,100)}...`}return baseDescription}isVisibleToSwarm(){return isAgentVisibleToSwarm(this.record.metadata)}canSeeSwarm(){return canAgentSeeSwarm(this.record.metadata)}getVisibleAgentIds(){return getVisibleAgentIds(this.record.metadata)??[]}};FunctionAgentContext=class extends AgentContext{constructor(record,args){super(args);this.record=record}record;async execute(input){const handler=this.record.provide();return await handler(input,this)}}}});import{tokenName as tokenName18}from"@frontmcp/di";import{getRuntimeContext as getRuntimeContext17,isEntryAvailable as isEntryAvailable6}from"@frontmcp/utils";function ownerKeyOf2(lineage){return lineage.map(o=>`${o.kind}:${o.id}`).join("/")}function qualifiedNameOf2(lineage,baseName){const prefix=lineage.map(o=>o.id).join(".");return prefix?`${prefix}.${baseName}`:baseName}function dedupLineage4(l){const out=[];for(const o of l){const last=out[out.length-1];if(!last||last.kind!==o.kind||last.id!==o.id)out.push(o)}return out}var AgentRegistry;var init_agent_registry=__esm({"libs/sdk/src/agent/agent.registry.ts"(){"use strict";init_availability();init_mcp_error();init_regsitry();init_agent_events();init_agent_utils();AgentRegistry=class extends RegistryAbstract{owner;localRows=[];adopted=new Map;children=new Set;childSubscriptions=new Map;byQualifiedId=new Map;byName=new Map;byOwnerAndName=new Map;byOwner=new Map;byId=new Map;version=0;emitter=new AgentEmitter;constructor(providers,list,owner){super("AgentRegistry",providers,list,false);this.owner=owner;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=normalizeAgent(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);if(!rec){throw new DependencyNotFoundError("AgentRegistry",tokenName18(token))}const deps=agentDiscoveryDeps(rec);for(const d of deps){this.providers.get(d);const graphEntry=this.graph.get(token);if(!graphEntry){throw new DependencyNotFoundError("AgentRegistry.graph",tokenName18(token))}graphEntry.add(d)}}}async initialize(){if(this.tokens.size>0)await this.instantiateLocalAgents();const childAppRegistries=this.providers.getRegistries("AppRegistry");childAppRegistries.forEach(appRegistry=>{const apps=appRegistry.getApps();for(const app of apps){const appAgentRegistries=app.providers.getRegistries("AgentRegistry");appAgentRegistries.filter(r=>r.owner.kind==="app").forEach(appAgentRegistry=>{this.adoptFromChild(appAgentRegistry,appAgentRegistry.owner)})}});const childAgentRegistries=this.providers.getRegistries("AgentRegistry");childAgentRegistries.filter(r=>r!==this).forEach(agentRegistry=>{this.adoptFromChild(agentRegistry,agentRegistry.owner)});this.reindex();const scope=this.providers.getActiveScope();logAvailabilityFiltering("AgentRegistry",this.listAllInstances(),scope.logger);this.bump("reset");await Promise.all([...this.instances.values()].map(ai=>ai.ready));if(this.owner.kind==="scope"||this.owner.kind==="agent"){await this.registerAgentToolsInParentScope()}}async instantiateLocalAgents(){const agentModule=await Promise.resolve().then(()=>(init_agent_instance(),agent_instance_exports));for(const token of this.tokens){const rec=this.defs.get(token);if(!rec){throw new DependencyNotFoundError("AgentRegistry",tokenName18(token))}const ai=new agentModule.AgentInstance(rec,this.providers,this.owner);this.instances.set(token,ai);const lineage=this.owner?[this.owner]:[];const row=this.makeRow(token,ai,lineage,this);this.localRows.push(row)}}async registerAgentToolsInParentScope(){const scope=this.providers.getActiveScope();const toolRegistry=scope.tools;if(!toolRegistry){return}for(const agentInstance of this.listAllInstances()){const toolInstance=agentInstance.getToolInstance();if(toolInstance){try{toolRegistry.registerToolInstance(toolInstance);scope.logger.debug(`Registered agent tool ${toolInstance.name} in parent ToolRegistry`)}catch(error){scope.logger.warn(`Failed to register agent tool for ${agentInstance.name}: ${error instanceof Error?error.message:"Unknown error"}`)}}for(const resource of agentInstance.getExportedResources()){scope.resources?.registerResourceInstance(resource)}for(const prompt of agentInstance.getExportedPrompts()){scope.prompts?.registerPromptInstance(prompt)}}}adoptFromChild(child,_childOwner){if(this.children.has(child))return;const childRows=child.listAllIndexed();const prepend=this.owner?[this.owner]:[];const adoptedRows=childRows.map(r=>this.relineage(r,prepend));this.adopted.set(child,adoptedRows);this.children.add(child);const unsubscribe=child.subscribe({immediate:false},()=>{const latest=child.listAllIndexed().map(r=>this.relineage(r,prepend));this.adopted.set(child,latest);this.reindex();this.bump("reset")});this.childSubscriptions.set(child,unsubscribe);this.reindex();this.bump("reset")}removeChild(child){if(!this.children.has(child))return;const unsubscribe=this.childSubscriptions.get(child);if(unsubscribe){unsubscribe();this.childSubscriptions.delete(child)}this.adopted.delete(child);this.children.delete(child);this.reindex();this.bump("reset")}dispose(){for(const[child,unsubscribe]of this.childSubscriptions){unsubscribe();this.children.delete(child);this.adopted.delete(child)}this.childSubscriptions.clear();this.reindex()}getAgents(includeHidden=false){const ctx=getRuntimeContext17();const local=[...this.localRows].map(a=>a.instance);const adopted=[...this.adopted.values()].flat().map(a=>a.instance);return[...local,...adopted].filter(a=>{if(!isEntryAvailable6(a.metadata.availableWhen,ctx))return false;if(!includeHidden&&a.metadata.hideFromDiscovery===true)return false;return true})}getInlineAgents(){return[...this.instances.values()]}listAllIndexed(){return[...this.localRows,...[...this.adopted.values()].flat()]}listAllInstances(){return this.listAllIndexed().map(r=>r.instance)}getAvailableInstances(){const ctx=getRuntimeContext17();return[...this.listAllInstances()].filter(a=>isEntryAvailable6(a.metadata.availableWhen,ctx))}findById(id){return this.byId.get(id)?.instance}findByName(name51){const rows=this.byName.get(name51);return rows?.[0]?.instance}getVisibleAgentsFor(agentId){const agent=this.findById(agentId);if(!agent)return[];const canSeeSwarm=agent.canSeeSwarm();if(!canSeeSwarm)return[];const visibleIds=agent.getVisibleAgentIds();const allAgents=this.getAvailableInstances();return allAgents.filter(a=>{if(a.id===agentId)return false;if(!a.isVisibleToSwarm())return false;if(visibleIds&&visibleIds.length>0){return visibleIds.includes(a.id)}return true})}getAgentsAsTools(){return this.getAvailableInstances().filter(a=>a.isVisibleToSwarm()).map(a=>a.getToolDefinition())}getAgentToolsFor(agentId){return this.getVisibleAgentsFor(agentId).map(a=>a.getToolDefinition())}reindex(){const effective=this.listAllIndexed();this.byQualifiedId.clear();this.byName.clear();this.byOwnerAndName.clear();this.byOwner.clear();this.byId.clear();for(const r of effective){this.byQualifiedId.set(r.qualifiedId,r);this.byId.set(r.instance.id,r);const listByName=this.byName.get(r.baseName)??[];listByName.push(r);this.byName.set(r.baseName,listByName);const byOwnerKey=this.byOwner.get(r.ownerKey)??[];byOwnerKey.push(r);this.byOwner.set(r.ownerKey,byOwnerKey);const on=`${r.ownerKey}:${r.baseName}`;if(!this.byOwnerAndName.has(on))this.byOwnerAndName.set(on,r)}}subscribe(opts,cb){const filter=opts.filter??(()=>true);if(opts.immediate){cb({kind:"reset",changeScope:"global",version:this.version,snapshot:this.listAllInstances().filter(filter)})}return this.emitter.on(e=>cb({...e,snapshot:this.listAllInstances().filter(filter)}))}bump(kind){const version=++this.version;this.emitter.emit({kind,changeScope:"global",version,snapshot:this.listAllInstances()})}makeRow(token,instance,lineage,source){const ownerKey=ownerKeyOf2(lineage);const baseName=instance.name;const qualifiedName=qualifiedNameOf2(lineage,baseName);const qualifiedId=`${ownerKey}:${tokenName18(token)}`;return{token,instance,baseName,lineage,ownerKey,qualifiedName,qualifiedId,source}}relineage(row,prepend){const merged=[...prepend,...row.lineage];const lineage=dedupLineage4(merged);const ownerKey=ownerKeyOf2(lineage);const qualifiedName=qualifiedNameOf2(lineage,row.baseName);const qualifiedId=`${ownerKey}:${tokenName18(row.token)}`;return{token:row.token,instance:row.instance,baseName:row.baseName,lineage,ownerKey,qualifiedName,qualifiedId,source:row.source}}hasAny(){return this.listAllIndexed().length>0||this.tokens.size>0}getCapabilities(){return this.hasAny()?{tools:{listChanged:true}}:{}}}}});import{depsOfClass as depsOfClass10,getMetadata as getMetadata19,isClass as isClass17}from"@frontmcp/di";import{idFromString,isValidMcpUri as isValidMcpUri7}from"@frontmcp/utils";function collectAppMetadata(cls){return Object.entries(FrontMcpLocalAppTokens).reduce((metadata,[key,token])=>{return Object.assign(metadata,{[key]:getMetadata19(token,cls)})},{})}function appIdOf(metadata){return metadata.id??idFromString(metadata.name)}function isRemoteAppConfig(item){if(!item||typeof item!=="object"){return false}const obj=item;if(typeof obj["urlType"]!=="string"||typeof obj["url"]!=="string"||typeof obj["name"]!=="string"){return false}if(obj["urlType"]==="npm"||obj["urlType"]==="esm"){return true}if(obj["urlType"]==="url"||obj["urlType"]==="worker"){return isValidMcpUri7(obj["url"])}return false}function normalizeApp(item){if(isClass17(item)){const metadata=collectAppMetadata(item);return{kind:"LOCAL_CLASS",provide:item,metadata}}if(item&&typeof item==="object"&&"lazy"in item){return normalizeLazyApp(item)}if(isRemoteAppConfig(item)){const metadata=item;const appId=metadata.id??metadata.name;const provide=Symbol(`remote:${appId}`);return{kind:"REMOTE_VALUE",provide,useValue:null,metadata}}if(item&&typeof item==="object"){const{provide,useValue,...metadata}=item;if(!provide){const name52=item?.name??JSON.stringify(item)??"[object]";throw new MissingProvideError("App",name52)}if(useValue){return{kind:"REMOTE_VALUE",provide,useValue,metadata}}}const name51=item?.name??String(item);throw new InvalidEntityError("app",name51,"a class or remote app config object")}function normalizeLazyApp(item){const parsed=lazyAppMetadataSchema.safeParse(item);if(!parsed.success){const name51=item.name;const label=typeof name51==="string"?`Lazy app "${name51}"`:"A lazy app";const issues=parsed.error.issues.map(issue=>{const field=issue.path.join(".")||(issue.code==="unrecognized_keys"?issue.keys.join(", "):"");return field?`${field}: ${issue.message}`:issue.message});throw new LazyAppConfigurationError(`${label} is invalid (${issues.join("; ")}). A lazy app takes id, name, description, enabled and lazy; declare everything else on the @App class it imports.`)}const metadata={...parsed.data,standalone:false};return{kind:"LAZY_IMPORT",provide:Symbol(`lazy:${appIdOf(metadata)}`),metadata}}function appDiscoveryDeps(rec){switch(rec.kind){case"REMOTE_VALUE":case"LAZY_IMPORT":return[];case"LOCAL_CLASS":return depsOfClass10(rec.provide,"discovery")}}var init_app_utils=__esm({"libs/sdk/src/app/app.utils.ts"(){"use strict";init_common();init_errors()}});import{idFromString as idFromString2}from"@frontmcp/utils";var AppLocalInstance;var init_app_local_instance=__esm({"libs/sdk/src/app/instances/app.local.instance.ts"(){"use strict";init_adapter_registry();init_agent_registry();init_common();init_hooks_utils();init_plugin_registry();init_prompt_registry();init_provider_registry();init_resource_registry();init_skill_registry();init_tool_registry();AppLocalInstance=class extends AppEntry{id;scopeProviders;appProviders;appPlugins;appAdapters;appTools;appResources;appPrompts;appAgents;appSkills;logger;constructor(record,scopeProviders){super(record);this.scopeProviders=scopeProviders;this.id=this.metadata.id??idFromString2(this.metadata.name);try{this.logger=scopeProviders.get(FrontMcpLogger)?.child("AppLocalInstance")}catch{}this.ready=this.initialize()}async initialize(){this.logger?.verbose(`Initializing app: ${this.metadata.name} (id: ${this.id})`);this.appProviders=new ProviderRegistry(this.metadata.providers??[],this.scopeProviders);await this.appProviders.ready;const appOwner={kind:"app",id:this.id,ref:this.token};const isStandalone=this.metadata.standalone!==false;const scopeInfo={ownScope:this.appProviders.getActiveScope(),parentScope:!isStandalone?this.scopeProviders.getActiveScope():void 0,isStandaloneApp:isStandalone};const providerHooks=normalizeHooksFromProviders(this.appProviders).map(hook=>({...hook,metadata:{...hook.metadata,owner:appOwner}}));if(providerHooks.length>0){await scopeInfo.ownScope.hooks.registerHooks(false,...providerHooks)}this.appPlugins=new PluginRegistry(this.appProviders,this.metadata.plugins??[],appOwner,scopeInfo);await this.appPlugins.ready;this.logger?.verbose(`App ${this.metadata.name}: ${this.appPlugins.getPlugins().length} plugin(s) registered`);const appAdapters=new AdapterRegistry(this.appProviders,this.metadata.adapters??[]);this.appAdapters=appAdapters;await appAdapters.ready;if(appAdapters.getAdapters().length>0)scopeInfo.ownScope.onDispose(()=>appAdapters.dispose());this.logger?.verbose(`App ${this.metadata.name}: ${this.appAdapters.getAdapters().length} adapter(s) found`);this.appTools=new ToolRegistry(this.appProviders,this.metadata.tools??[],appOwner);await this.appTools.ready;const toolNames=this.appTools.getTools(true).map(t=>t.metadata.name);this.logger?.verbose(`App ${this.metadata.name}: ${toolNames.length} tool(s) registered: [${toolNames.join(", ")}]`);this.appResources=new ResourceRegistry(this.appProviders,this.metadata.resources??[],appOwner);this.appPrompts=new PromptRegistry(this.appProviders,this.metadata.prompts??[],appOwner);this.appAgents=new AgentRegistry(this.appProviders,this.metadata.agents??[],appOwner);this.appSkills=new SkillRegistry(this.appProviders,this.metadata.skills??[],appOwner);await Promise.all([this.appResources.ready,this.appPrompts.ready,this.appAgents.ready,this.appSkills.ready]);this.logger?.verbose(`App ${this.metadata.name}: ${this.appResources.getResources().length} resource(s) registered`);this.logger?.verbose(`App ${this.metadata.name}: ${this.appPrompts.getPrompts().length} prompt(s) registered`);const parts=[];const toolCount=this.appTools.getTools(true).length;const resourceCount=this.appResources.getResources().length;const promptCount=this.appPrompts.getPrompts().length;const adapterCount=this.appAdapters.getAdapters().length;const pluginCount=this.appPlugins.getPlugins().length;if(toolCount>0)parts.push(`${toolCount} tool${toolCount!==1?"s":""}`);if(resourceCount>0)parts.push(`${resourceCount} resource${resourceCount!==1?"s":""}`);if(promptCount>0)parts.push(`${promptCount} prompt${promptCount!==1?"s":""}`);if(adapterCount>0)parts.push(`${adapterCount} adapter${adapterCount!==1?"s":""}`);if(pluginCount>0)parts.push(`${pluginCount} plugin${pluginCount!==1?"s":""}`);this.logger?.info(`${this.metadata.name}: ${parts.length>0?parts.join(", "):"no entries"}`)}get providers(){return this.appProviders}get adapters(){return this.appAdapters}get plugins(){return this.appPlugins}get tools(){return this.appTools}get resources(){return this.appResources}get prompts(){return this.appPrompts}get agents(){return this.appAgents}get skills(){return this.appSkills}}}});var DEFAULT_INTERVAL_MS,VersionPoller;var init_version_poller=__esm({"libs/sdk/src/esm-loader/version-poller.ts"(){"use strict";init_version_resolver();init_semver_utils();DEFAULT_INTERVAL_MS=5*60*1e3;VersionPoller=class{intervalMs;logger;onNewVersion;versionResolver;packages=new Map;intervalId;running=false;polling=false;constructor(options){this.intervalMs=options.intervalMs??DEFAULT_INTERVAL_MS;this.logger=options.logger;this.onNewVersion=options.onNewVersion;this.versionResolver=new VersionResolver({registryAuth:options.registryAuth})}addPackage(specifier,currentVersion){this.packages.set(specifier.fullName,{specifier,currentVersion});this.logger?.debug(`Version poller: tracking ${specifier.fullName}@${specifier.range} (current: ${currentVersion})`)}removePackage(packageName){this.packages.delete(packageName);this.logger?.debug(`Version poller: stopped tracking ${packageName}`)}updateCurrentVersion(packageName,newVersion){const entry=this.packages.get(packageName);if(entry){entry.currentVersion=newVersion;return true}return false}start(){if(this.running)return;if(this.packages.size===0)return;this.running=true;this.intervalId=setInterval(()=>{void this.poll()},this.intervalMs);this.logger?.info(`Version poller started (interval: ${this.intervalMs}ms, packages: ${this.packages.size})`)}stop(){if(!this.running)return;this.running=false;if(this.intervalId){clearInterval(this.intervalId);this.intervalId=void 0}this.logger?.info("Version poller stopped")}async checkNow(){const results=[];for(const[,entry]of this.packages){try{const result=await this.checkPackage(entry);results.push(result)}catch(error){this.logger?.warn(`Version check failed for ${entry.specifier.fullName}: ${error.message}`)}}return results}isRunning(){return this.running}get trackedCount(){return this.packages.size}async poll(){if(this.polling)return;this.polling=true;try{for(const[,entry]of this.packages){try{const result=await this.checkPackage(entry);if(result.hasUpdate){this.logger?.info(`New version available for ${entry.specifier.fullName}: ${entry.currentVersion} \u2192 ${result.latestVersion}`);await this.onNewVersion(entry.specifier.fullName,entry.currentVersion,result.latestVersion);entry.currentVersion=result.latestVersion}}catch(error){this.logger?.warn(`Version poll failed for ${entry.specifier.fullName}: ${error.message}`)}}}finally{this.polling=false}}async checkPackage(entry){const resolution=await this.versionResolver.resolve(entry.specifier);const hasUpdate=resolution.resolvedVersion!==entry.currentVersion&&isNewerVersion(resolution.resolvedVersion,entry.currentVersion);const rangeMatch=satisfiesRange(resolution.resolvedVersion,entry.specifier.range);return{packageName:entry.specifier.fullName,currentVersion:entry.currentVersion,latestVersion:resolution.resolvedVersion,hasUpdate:hasUpdate&&rangeMatch,satisfiesRange:rangeMatch}}}}});var app_esm_instance_exports={};__export(app_esm_instance_exports,{AppEsmInstance:()=>AppEsmInstance});var UNLOADED_MANIFEST_KINDS,EmptyPluginRegistry,EmptyAdapterRegistry,EmptySkillRegistry,AppEsmInstance;var init_app_esm_instance=__esm({"libs/sdk/src/app/instances/app.esm.instance.ts"(){"use strict";init_common();init_primitive_filter();init_errors();init_esm_entries();init_package_specifier();init_version_poller();init_prompt_instance();init_prompt_registry();init_resource_instance();init_resource_registry();init_tool_instance();init_tool_registry();init_app_utils();UNLOADED_MANIFEST_KINDS=["skills","agents","jobs","workflows","providers"];EmptyPluginRegistry=class{getPlugins(){return[]}getPluginNames(){return[]}};EmptyAdapterRegistry=class{getAdapters(){return[]}};EmptySkillRegistry=class _EmptySkillRegistry{owner={kind:"app",id:"_esm",ref:_EmptySkillRegistry};getSkills(){return[]}getExecutableSkills(){return[]}getKnowledgeOnlySkills(){return[]}findByName(){return void 0}findByQualifiedName(){return void 0}async search(){return[]}async loadSkill(){return void 0}async listSkills(){return{skills:[],total:0,hasMore:false}}hasAny(){return false}async count(){return 0}subscribe(){return()=>{}}getCapabilities(){return{}}async validateAllTools(){return{results:[],isValid:true,totalSkills:0,failedCount:0,warningCount:0}}async syncToExternal(){return null}setExternalProvider(){return void 0}getExternalProvider(){return void 0}hasExternalProvider(){return false}async registerSkillContent(){throw new InternalMcpError("registerSkillContent is not supported on ESM apps","UNSUPPORTED_OPERATION")}async unregisterSkill(){return false}};AppEsmInstance=class extends AppEntry{id;get isRemote(){return true}scopeProviders;appOwner;loader;specifier;poller;loadResult;updateInProgress=false;_tools;_resources;_prompts;_plugins;_adapters;_skills;constructor(record,scopeProviders){super(record);this.id=appIdOf(this.metadata);this.scopeProviders=scopeProviders;this.appOwner={kind:"app",id:this.id,ref:this.token};this.specifier=parsePackageSpecifier(this.metadata.url);const scope=scopeProviders.getActiveScope();const appConfig=this.metadata.packageConfig;this.loader=createPackageModuleLoader({loader:appConfig?.loader??scope.metadata.loader,cacheTTL:appConfig?.cacheTTL,importMap:appConfig?.importMap,logger:scope.logger});this._tools=new ToolRegistry(this.scopeProviders,[],this.appOwner);this._resources=new ResourceRegistry(this.scopeProviders,[],this.appOwner);this._prompts=new PromptRegistry(this.scopeProviders,[],this.appOwner);this._plugins=new EmptyPluginRegistry;this._adapters=new EmptyAdapterRegistry;this._skills=new EmptySkillRegistry;this.ready=this.initialize()}async initialize(){const logger=this.scopeProviders.getActiveScope().logger;logger.info(`Initializing ESM app: ${this.id} (${this.specifier.fullName}@${this.specifier.range})`);try{await Promise.all([this._tools.ready,this._resources.ready,this._prompts.ready]);this.loadResult=await this.loader.load(this.specifier);logger.info(`Loaded ESM package ${this.specifier.fullName}@${this.loadResult.resolvedVersion} (source: ${this.loadResult.source})`);await this.registerFromManifest(this.loadResult.manifest);const autoUpdate=this.metadata.packageConfig?.autoUpdate;if(autoUpdate?.enabled){const scopeMeta=this.scopeProviders.getActiveScope().metadata;const pollerLoader=this.metadata.packageConfig?.loader??scopeMeta.loader;this.poller=new VersionPoller({intervalMs:autoUpdate.intervalMs,registryAuth:registryAuthOf(pollerLoader),logger,onNewVersion:(pkg,oldVer,newVer)=>this.handleVersionUpdate(pkg,oldVer,newVer)});this.poller.addPackage(this.specifier,this.loadResult.resolvedVersion);this.poller.start()}}catch(error){logger.error(`Failed to initialize ESM app ${this.id}: ${error.message}`);throw error}}get providers(){return this.scopeProviders}get adapters(){return this._adapters}get plugins(){return this._plugins}get tools(){return this._tools}get resources(){return this._resources}get prompts(){return this._prompts}get skills(){return this._skills}getLoadedVersion(){return this.loadResult?.resolvedVersion}getSpecifier(){return this.specifier}async reload(){const logger=this.scopeProviders.getActiveScope().logger;logger.info(`Reloading ESM app ${this.id}`);this.loadResult=await this.loader.load(this.specifier);await this.registerFromManifest(this.loadResult.manifest);if(this.poller){this.poller.updateCurrentVersion(this.specifier.fullName,this.loadResult.resolvedVersion)}}async dispose(){this.poller?.stop()}async registerFromManifest(manifest){const logger=this.scopeProviders.getActiveScope().logger;const namespace=this.metadata.namespace??this.metadata.name;const notLoaded=UNLOADED_MANIFEST_KINDS.filter(kind=>(manifest[kind]?.length??0)>0);if(notLoaded.length>0){logger.warn(`ESM app ${this.id}: App.esm() loads only tools, resources and prompts; the package's ${notLoaded.join(", ")} are not loaded`)}const filter=this.metadata.filter;const prefixLength=namespace?namespace.length+1:0;const included=kind=>record=>isPrimitiveIncluded(record.metadata.name.slice(prefixLength),kind,filter);const tools=esmManifestRecords(manifest.tools,raw=>esmToolRecord(raw,namespace)).filter(included("tools"));const resources=esmManifestRecords(manifest.resources,raw=>esmResourceRecord(raw,namespace)).filter(included("resources"));const prompts=esmManifestRecords(manifest.prompts,raw=>esmPromptRecord(raw,namespace)).filter(included("prompts"));for(const record of tools){const instance=new ToolInstance(record,this.scopeProviders,this.appOwner);await instance.ready;this._tools.registerToolInstance(instance)}for(const record of resources){const instance=new ResourceInstance(record,this.scopeProviders,this.appOwner);await instance.ready;this._resources.registerResourceInstance(instance)}for(const record of prompts){const instance=new PromptInstance(record,this.scopeProviders,this.appOwner);await instance.ready;this._prompts.registerPromptInstance(instance)}logger.info(`ESM app ${this.id} registered: ${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts`)}async handleVersionUpdate(_packageName,oldVersion,newVersion){const logger=this.scopeProviders.getActiveScope().logger;if(this.updateInProgress){logger.warn(`Update already in progress for ${this.id}, skipping ${newVersion}`);return}this.updateInProgress=true;logger.info(`Updating ESM app ${this.id}: ${oldVersion} \u2192 ${newVersion}`);try{this.loadResult=await this.loader.load(this.specifier);this._tools.replaceAll([],this.appOwner);this._resources.replaceAll([],this.appOwner);this._prompts.replaceAll([],this.appOwner);await this.registerFromManifest(this.loadResult.manifest);logger.info(`ESM app ${this.id} updated to ${newVersion}`)}catch(error){logger.error(`Failed to update ESM app ${this.id} to ${newVersion}: ${error.message}`)}finally{this.updateInProgress=false}}}}});var CapabilityCache;var init_capability_cache=__esm({"libs/sdk/src/remote-mcp/cache/capability-cache.ts"(){"use strict";CapabilityCache=class{cache=new Map;defaultTTL;constructor(config={}){this.defaultTTL=config.defaultTTL??6e4}get(appId){const cached=this.cache.get(appId);if(!cached){return null}if(Date.now()>cached.expiresAt){this.cache.delete(appId);return null}return cached.capabilities}set(appId,capabilities,ttl){const effectiveTTL=ttl??this.defaultTTL;this.cache.set(appId,{capabilities,expiresAt:Date.now()+effectiveTTL,fetchedAt:capabilities.fetchedAt})}invalidate(appId){this.cache.delete(appId)}clear(){this.cache.clear()}isExpired(appId){const cached=this.cache.get(appId);if(!cached){return true}return Date.now()>cached.expiresAt}getTimeToExpiry(appId){const cached=this.cache.get(appId);if(!cached){return 0}const remaining=cached.expiresAt-Date.now();return Math.max(0,remaining)}getFetchedAt(appId){const cached=this.cache.get(appId);return cached?.fetchedAt??null}getCachedAppIds(){const now=Date.now();const activeIds=[];for(const[appId,cached]of this.cache.entries()){if(cached.expiresAt>now){activeIds.push(appId)}}return activeIds}getStats(){const now=Date.now();let activeEntries=0;let expiredEntries=0;for(const cached of this.cache.values()){if(cached.expiresAt>now){activeEntries++}else{expiredEntries++}}return{totalEntries:this.cache.size,activeEntries,expiredEntries}}}}});var init_cache=__esm({"libs/sdk/src/remote-mcp/cache/index.ts"(){"use strict";init_capability_cache()}});function createRemoteToolInstance(remoteTool,mcpClient,remoteAppId,providers,owner,namespace){const record=buildRemoteToolRecord(remoteTool,mcpClient,remoteAppId,namespace);return new ToolInstance(record,providers,owner)}function createRemoteResourceInstance(remoteResource,mcpClient,remoteAppId,providers,owner,namespace){const record=buildRemoteResourceRecord(remoteResource,mcpClient,remoteAppId,namespace);return new ResourceInstance(record,providers,owner)}function createRemoteResourceTemplateInstance(remoteTemplate,mcpClient,remoteAppId,providers,owner,namespace){const record=buildRemoteResourceTemplateRecord(remoteTemplate,mcpClient,remoteAppId,namespace);return new ResourceInstance(record,providers,owner)}function createRemotePromptInstance(remotePrompt,mcpClient,remoteAppId,providers,owner,namespace){const record=buildRemotePromptRecord(remotePrompt,mcpClient,remoteAppId,namespace);return new PromptInstance(record,providers,owner)}var init_instance_factories=__esm({"libs/sdk/src/remote-mcp/factories/instance-factories.ts"(){"use strict";init_tool_instance();init_resource_instance();init_prompt_instance();init_record_builders()}});var init_factories=__esm({"libs/sdk/src/remote-mcp/factories/index.ts"(){"use strict";init_context_factories();init_record_builders();init_instance_factories()}});var EmptyPluginRegistry2,EmptyAdapterRegistry2,EmptySkillRegistry2;var init_empty_app_registries=__esm({"libs/sdk/src/app/instances/empty-app-registries.ts"(){"use strict";init_errors();EmptyPluginRegistry2=class{getPlugins(){return[]}getPluginNames(){return[]}};EmptyAdapterRegistry2=class{getAdapters(){return[]}};EmptySkillRegistry2=class _EmptySkillRegistry{owner={kind:"app",id:"_remote",ref:_EmptySkillRegistry};getSkills(){return[]}getExecutableSkills(){return[]}getKnowledgeOnlySkills(){return[]}findByName(){return void 0}findByQualifiedName(){return void 0}async search(){return[]}async loadSkill(){return void 0}async listSkills(){return{skills:[],total:0,hasMore:false}}hasAny(){return false}async count(){return 0}subscribe(){return()=>{}}getCapabilities(){return{}}async validateAllTools(){return{results:[],isValid:true,totalSkills:0,failedCount:0,warningCount:0}}async syncToExternal(){return null}setExternalProvider(){return void 0}getExternalProvider(){return void 0}hasExternalProvider(){return false}async registerSkillContent(){throw new InternalMcpError("registerSkillContent is not supported on remote apps","UNSUPPORTED_OPERATION")}async unregisterSkill(){return false}}}});var app_remote_instance_exports={};__export(app_remote_instance_exports,{AppRemoteInstance:()=>AppRemoteInstance});var AppRemoteInstance;var init_app_remote_instance=__esm({"libs/sdk/src/app/instances/app.remote.instance.ts"(){"use strict";init_common();init_primitive_filter();init_errors();init_prompt_registry();init_cache();init_factories();init_remote_entries();init_resource_registry();init_tool_registry();init_app_utils();init_empty_app_registries();AppRemoteInstance=class extends AppEntry{id;get isRemote(){return true}scopeProviders;mcpClient;appOwner;capabilityCache;_tools;_resources;_prompts;_plugins;_adapters;_skills;isConnected=false;capabilitiesLoaded=false;loadingPromise=null;_unsubscribeCapability;registeredProxies={tools:[],resources:[],prompts:[]};constructor(record,scopeProviders){super(record);this.id=appIdOf(this.metadata);this.scopeProviders=scopeProviders;this.appOwner={kind:"app",id:this.id,ref:this.token};const cacheTTL=this.metadata.cacheTTL??6e4;this.capabilityCache=new CapabilityCache({defaultTTL:cacheTTL});this._tools=new ToolRegistry(this.scopeProviders,[],this.appOwner,{adopt:false});this._resources=new ResourceRegistry(this.scopeProviders,[],this.appOwner,{adopt:false});this._prompts=new PromptRegistry(this.scopeProviders,[],this.appOwner,{adopt:false});this._plugins=new EmptyPluginRegistry2;this._adapters=new EmptyAdapterRegistry2;this._skills=new EmptySkillRegistry2;this.mcpClient=mcpClientServiceOf(this.scopeProviders.getActiveScope(),{capabilityRefreshInterval:this.metadata.refreshInterval??0});this.ready=this.initialize()}async initialize(){const logger=this.scopeProviders.getActiveScope().logger;logger.info(`Initializing remote app: ${this.id} (${this.metadata.url})`);try{await Promise.all([this._tools.ready,this._resources.ready,this._prompts.ready]);await this.mcpClient.connect(buildRemoteConnectRequest({appId:this.id,name:this.metadata.name,url:this.metadata.url,transportType:this.mapUrlTypeToTransportType(this.metadata.urlType),transportOptions:this.metadata.transportOptions,remoteAuth:this.metadata.remoteAuth,namespace:this.metadata.namespace}));this.isConnected=true;this._unsubscribeCapability=this.mcpClient.onCapabilityChange(event=>{if(event.appId===this.id){logger.info(`Remote capabilities changed for ${this.id}: ${event.kind}`);this.capabilityCache.invalidate(this.id);this.capabilitiesLoaded=false}});logger.info(`Remote app ${this.id} connected. Capabilities will be loaded lazily.`)}catch(error){logger.error(`Failed to initialize remote app ${this.id}: ${error.message}`);throw error}}async ensureCapabilitiesLoaded(){if(this.capabilitiesLoaded&&!this.capabilityCache.isExpired(this.id)){return}if(this.loadingPromise){return this.loadingPromise}this.loadingPromise=this.discoverAndRegisterCapabilities();try{await this.loadingPromise;this.capabilitiesLoaded=true}finally{this.loadingPromise=null}}async refreshCapabilities(){this.capabilityCache.invalidate(this.id);this.capabilitiesLoaded=false;await this.ensureCapabilitiesLoaded()}get providers(){return this.scopeProviders}get adapters(){return this._adapters}get plugins(){return this._plugins}get tools(){return this._tools}get resources(){return this._resources}get prompts(){return this._prompts}get skills(){return this._skills}getMcpClient(){return this.mcpClient}getIsConnected(){return this.isConnected}getCapabilitiesLoaded(){return this.capabilitiesLoaded}getCacheStats(){return this.capabilityCache.getStats()}async disconnect(){if(this._unsubscribeCapability){this._unsubscribeCapability();this._unsubscribeCapability=void 0}if(this.isConnected){await this.mcpClient.disconnect(this.id);this.isConnected=false;this.capabilitiesLoaded=false;this.capabilityCache.invalidate(this.id)}}async reconnect(){await this.mcpClient.reconnect(this.id);this.isConnected=true;this.capabilitiesLoaded=false;this.capabilityCache.invalidate(this.id)}mapUrlTypeToTransportType(urlType){switch(urlType){case"url":return"http";case"worker":return"worker";case"npm":return"npm";case"esm":return"esm";default:return"http"}}registerRemoteTool(instance,logger){try{this._tools.registerToolInstance(instance)}catch(error){if(!(error instanceof ToolAliasConflictError))throw error;logger.warn(`Remote app ${this.id}: tool "${instance.name}" is not loaded. ${error.message}`)}}async discoverAndRegisterCapabilities(){const logger=this.scopeProviders.getActiveScope().logger;const namespace=this.metadata.namespace||this.metadata.name;let capabilities=this.capabilityCache.get(this.id);if(!capabilities){logger.debug(`Fetching capabilities for remote app ${this.id}`);capabilities=await this.mcpClient.discoverCapabilities(this.id);const cacheTTL=this.metadata.cacheTTL??6e4;this.capabilityCache.set(this.id,capabilities,cacheTTL)}else{logger.debug(`Using cached capabilities for remote app ${this.id}`)}const filter=this.metadata.filter;const included=kind=>entry=>isPrimitiveIncluded(entry.name,kind,filter);const tools=await Promise.all(capabilities.tools.filter(included("tools")).map(async remoteTool=>{const instance=createRemoteToolInstance(remoteTool,this.mcpClient,this.id,this.scopeProviders,this.appOwner,namespace);await instance.ready;return instance}));const resources=await Promise.all([...capabilities.resources.filter(included("resources")).map(remoteResource=>createRemoteResourceInstance(remoteResource,this.mcpClient,this.id,this.scopeProviders,this.appOwner,namespace)),...capabilities.resourceTemplates.filter(included("resources")).map(remoteTemplate=>createRemoteResourceTemplateInstance(remoteTemplate,this.mcpClient,this.id,this.scopeProviders,this.appOwner,namespace))].map(async instance=>{await instance.ready;return instance}));const prompts=await Promise.all(capabilities.prompts.filter(included("prompts")).map(async remotePrompt=>{const instance=createRemotePromptInstance(remotePrompt,this.mcpClient,this.id,this.scopeProviders,this.appOwner,namespace);await instance.ready;return instance}));const previous=this.registeredProxies;for(const token of previous.tools)this._tools.unregisterToolInstance(token);for(const token of previous.resources)this._resources.unregisterResourceInstance(token);for(const token of previous.prompts)this._prompts.unregisterPromptInstance(token);for(const instance of tools)this.registerRemoteTool(instance,logger);for(const instance of resources)this._resources.registerResourceInstance(instance);for(const instance of prompts)this._prompts.registerPromptInstance(instance);this.registeredProxies={tools:tools.map(instance=>instance.record.provide),resources:resources.map(instance=>instance.record.provide),prompts:prompts.map(instance=>instance.record.provide)};logger.info(`Remote app ${this.id} capabilities loaded: ${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts`)}}}});import{sha256Hex as sha256Hex13}from"@frontmcp/utils";function serializeForHash(skill){const sortedTools=[...skill.tools].sort((a,b)=>byText(a.name,b.name));const sortedParameters=skill.parameters?[...skill.parameters].sort((a,b)=>byText(a.name,b.name)):void 0;const sortedExamples=skill.examples?[...skill.examples].sort((a,b)=>byText(a.scenario,b.scenario)):void 0;const content={id:skill.id,name:skill.name,description:skill.description,instructions:skill.instructions,tools:sortedTools,parameters:sortedParameters,examples:sortedExamples};return JSON.stringify(content)}function computeSkillHash(skill){const serialized=serializeForHash(skill);return sha256Hex13(serialized)}var byText;var init_skill_hash=__esm({"libs/sdk/src/skill/sync/skill-hash.ts"(){"use strict";byText=(a,b)=>a.localeCompare(b,"en")}});import{z as z90}from"@frontmcp/lazy-zod";var SERVER_MANIFEST_VERSION,SERVER_MANIFEST_FILE,jsonObjectSchema,ownedEntryShape,manifestToolSchema,resourceShape,manifestResourceSchema,manifestResourceTemplateSchema,manifestPromptSchema,manifestSkillSchema,manifestAppSchema,serverManifestSchema;var init_server_manifest_schema=__esm({"libs/sdk/src/manifest/server-manifest.schema.ts"(){"use strict";SERVER_MANIFEST_VERSION=1;SERVER_MANIFEST_FILE="frontmcp.manifest.json";jsonObjectSchema=z90.record(z90.string(),z90.unknown());ownedEntryShape={app:z90.string().optional(),owner:z90.string(),enabled:z90.union([z90.literal(false),z90.literal("source")]).optional(),availableWhen:jsonObjectSchema.optional(),authorities:z90.literal(true).optional()};manifestToolSchema=z90.object({name:z90.string(),...ownedEntryShape,title:z90.string().optional(),description:z90.string().optional(),inputSchema:jsonObjectSchema,outputSchema:jsonObjectSchema.optional(),annotations:jsonObjectSchema.optional(),icons:z90.array(jsonObjectSchema).optional(),_meta:jsonObjectSchema.optional(),tags:z90.array(z90.string()).optional(),aliases:z90.array(z90.string()).optional(),visibility:z90.enum(["public","hidden","internal"]),execution:jsonObjectSchema.optional(),output:jsonObjectSchema.optional(),examples:z90.array(jsonObjectSchema).optional(),ui:z90.literal(true).optional()});resourceShape={name:z90.string(),...ownedEntryShape,title:z90.string().optional(),description:z90.string().optional(),mimeType:z90.string().optional(),icons:z90.array(jsonObjectSchema).optional(),annotations:jsonObjectSchema.optional(),_meta:jsonObjectSchema.optional()};manifestResourceSchema=z90.object({uri:z90.string(),...resourceShape});manifestResourceTemplateSchema=z90.object({uriTemplate:z90.string(),...resourceShape});manifestPromptSchema=z90.object({name:z90.string(),...ownedEntryShape,title:z90.string().optional(),description:z90.string().optional(),arguments:z90.array(z90.object({name:z90.string(),description:z90.string().optional(),required:z90.boolean().optional()})).optional(),icons:z90.array(jsonObjectSchema).optional()});manifestSkillSchema=z90.object({name:z90.string(),...ownedEntryShape,path:z90.string(),description:z90.string(),tags:z90.array(z90.string()).optional(),visibility:z90.enum(["mcp","http","both"]),hidden:z90.literal(true).optional(),tools:z90.array(z90.object({name:z90.string(),purpose:z90.string().optional(),required:z90.boolean().optional()})),license:z90.string().optional(),hash:z90.string().optional()});manifestAppSchema=z90.object({id:z90.string(),name:z90.string(),description:z90.string().optional(),remote:z90.literal(true).optional(),standalone:z90.union([z90.boolean(),z90.literal("includeInParent")]).optional(),output:jsonObjectSchema.optional()});serverManifestSchema=z90.object({manifestVersion:z90.literal(SERVER_MANIFEST_VERSION),server:z90.object({name:z90.string(),version:z90.string(),title:z90.string().optional(),instructions:z90.string().optional()}),budget:z90.object({instructions:z90.number(),toolDescription:z90.number()}).optional(),apps:z90.array(manifestAppSchema),tools:z90.array(manifestToolSchema),resources:z90.array(manifestResourceSchema),resourceTemplates:z90.array(manifestResourceTemplateSchema),prompts:z90.array(manifestPromptSchema),skills:z90.array(manifestSkillSchema)})}});function ownersOf(lineage,owner){const owners2=(lineage??[]).filter(candidate=>candidate.kind!=="scope");if(owners2.length>0)return owners2;return lineage&&lineage.length>0?[lineage[lineage.length-1]]:[owner]}function entriesOf(scopes,registryOf){const seen=new Set;const found=[];for(const scope of scopes){const registry=registryOf(scope);for(const entry of registry.listAllInstances()){if(seen.has(entry))continue;seen.add(entry);found.push({entry,lineage:ownersOf(registry.lineageOf(entry),entry.owner)})}}return found}function enabledState(enabled){if(enabled===false)return false;return isEnabledSource(enabled)?"source":void 0}function ownedFields(lineage,metadata){const fields=metadata;return{app:lineage.find(owner=>owner.kind==="app")?.id,owner:ownerKeyOf(lineage),enabled:enabledState(fields.enabled),availableWhen:jsonObject(fields.availableWhen),authorities:fields.authorities===void 0?void 0:true}}function jsonObject(value){return value}function jsonObjects(values){return values?.map(value=>value)}function sortedBy(items,key){return items.sort((left,right)=>{const a=key(left);const b=key(right);if(a===b)return 0;return a<b?-1:1})}async function skillHash(skill){try{const content=await skill.load();return computeSkillHash({...content,instructions:content.instructions.replace(/\r\n/g,"\n")})}catch{return void 0}}function manifestToolOf(tool,lineage){return{name:tool.metadata.id??tool.metadata.name,title:tool.metadata.title,description:tool.metadata.description,...ownedFields(lineage,tool.metadata),inputSchema:tool.getInputJsonSchema()??{type:"object",properties:{}},outputSchema:tool.getOutputJsonSchema()??void 0,annotations:jsonObject(tool.metadata.annotations),icons:jsonObjects(tool.metadata.icons),_meta:tool.metadata._meta,tags:tool.metadata.tags,aliases:tool.metadata.aliases,visibility:resolveToolVisibility(tool.metadata),execution:jsonObject(tool.metadata.execution),output:jsonObject(tool.metadata.output),examples:jsonObjects(tool.metadata.examples),ui:hasUIConfig(tool.metadata)?true:void 0}}function manifestResourceOf(resource,lineage){const metadata=resource.metadata;const fields={name:metadata.name,title:metadata.title,description:metadata.description,mimeType:metadata.mimeType,icons:jsonObjects(metadata.icons),annotations:jsonObject(metadata.annotations),_meta:metadata._meta,...ownedFields(lineage,metadata)};if(resource.isTemplate&&resource.uriTemplate)return{template:{uriTemplate:resource.uriTemplate,...fields}};return resource.uri?{resource:{uri:resource.uri,...fields}}:void 0}function manifestPromptOf(prompt,lineage){return{name:prompt.metadata.name,title:prompt.metadata.title,description:prompt.metadata.description,...ownedFields(lineage,prompt.metadata),arguments:prompt.metadata.arguments,icons:jsonObjects(prompt.metadata.icons)}}function manifestAppOf(app){const metadata=app.metadata;return{id:app.id,name:metadata.name,description:metadata.description,remote:app.isRemote?true:void 0,standalone:metadata.standalone||void 0,output:jsonObject(app.metadata.output)}}async function buildServerManifest(scopes,primary){const tools=entriesOf(scopes,scope=>scope.tools).map(({entry,lineage})=>manifestToolOf(entry,lineage));const resources=[];const resourceTemplates=[];for(const{entry,lineage}of entriesOf(scopes,scope=>scope.resources)){const recorded=manifestResourceOf(entry,lineage);if(recorded&&"template"in recorded)resourceTemplates.push(recorded.template);else if(recorded)resources.push(recorded.resource)}const prompts=entriesOf(scopes,scope=>scope.prompts).map(({entry,lineage})=>manifestPromptOf(entry,lineage));const skills=await Promise.all(entriesOf(scopes,scope=>scope.skills).map(async({entry:skill,lineage})=>({name:skill.metadata.name,path:skill.getSkillPath(),description:skill.getDescription(),...ownedFields(lineage,skill.metadata),tags:skill.metadata.tags,visibility:skill.metadata.visibility??"both",hidden:skill.isHidden()?true:void 0,tools:skill.getToolRefs().map(({name:name51,purpose,required})=>({name:name51,purpose,required})),license:skill.getLicense(),hash:await skillHash(skill)})));const apps=new Map;for(const scope of scopes){for(const app of scope.apps.getApps()){if(!apps.has(app.id))apps.set(app.id,manifestAppOf(app))}}const instructions=await composeCallerInstructions(primary,{skillUriHints:true});const manifest={manifestVersion:SERVER_MANIFEST_VERSION,server:{name:primary.metadata.info.name,version:primary.metadata.info.version,title:primary.metadata.info.title,instructions:instructions.length>0?instructions:void 0},budget:resolveInstructionsBudget(primary.metadata.instructionsBudget),apps:sortedBy([...apps.values()],app=>app.id),tools:sortedBy(tools,tool=>`${tool.name}\0${tool.owner}`),resources:sortedBy(resources,resource=>`${resource.uri}\0${resource.owner}`),resourceTemplates:sortedBy(resourceTemplates,template=>`${template.uriTemplate}\0${template.owner}`),prompts:sortedBy(prompts,prompt=>`${prompt.name}\0${prompt.owner}`),skills:sortedBy(skills,skill=>`${skill.path}\0${skill.owner}`)};return JSON.parse(JSON.stringify(manifest))}var init_build_server_manifest=__esm({"libs/sdk/src/manifest/build-server-manifest.ts"(){"use strict";init_enabled_metadata();init_tool_metadata();init_instructions_budget();init_skill_instructions_helper();init_skill_hash();init_ui_shared();init_lineage_utils();init_server_manifest_schema()}});function registerEnforcedMetadataKeys(keys,enforcedBy){for(const key of keys){if(!enforcedMetadataKeys.has(key))enforcedMetadataKeys.set(key,enforcedBy)}}function getEnforcedMetadataKeys(){return[...enforcedMetadataKeys.keys()]}function describeMetadataEnforcer(key){return enforcedMetadataKeys.get(key)}function isEnforcementRequested(value){return value!==void 0&&value!==null&&value!==false}var enforcedMetadataKeys;var init_enforced_metadata_utils=__esm({"libs/sdk/src/common/utils/enforced-metadata.utils.ts"(){"use strict";enforcedMetadataKeys=new Map([["approval","ApprovalPlugin from @frontmcp/plugin-approval"],["featureFlag","FeatureFlagPlugin from @frontmcp/plugin-feature-flags"]])}});function reasonsOf(entries){return entries.flatMap(({label,authorities,ownEnabledSource,widget,readBeforeTheCall=[]})=>[...authorities?[`${label} declares authorities`]:[],...ownEnabledSource?[`${label} has an enabled source of its own (give the lazy app the switch instead)`]:[],...widget?[`${label} has a widget (ui)`]:[],...readBeforeTheCall.map(key=>`${label} declares '${key}', which a plugin reads from its placeholder`)])}function whyListedAppCannotBeLazy(listed){const facts=(label,entry)=>({label,authorities:entry.authorities===true,ownEnabledSource:entry.enabled==="source",widget:entry.ui===true});return[...listed.skills.map(skill=>`the manifest lists skill "${skill.name}" for it`),...reasonsOf([...listed.tools.map(tool=>facts(`tool "${tool.name}"`,tool)),...listed.resources.map(resource=>facts(`resource "${resource.uri}"`,resource)),...listed.resourceTemplates.map(template=>facts(`resource template "${template.uriTemplate}"`,template)),...listed.prompts.map(prompt=>facts(`prompt "${prompt.name}"`,prompt))])]}function whyAppCannotBeLazy(metadata){const reasons=[];for(const key of["jobs","workflows","channels"]){if(metadata[key]?.length)reasons.push(`it declares ${key}`)}if(metadata.auth)reasons.push("it declares its own auth");if(metadata.standalone)reasons.push("it is standalone (a lazy app joins the server's scope)");if(metadata.ui)reasons.push("it declares ui defaults");for(const name51 of serverScopedPluginsOf(metadata.plugins??[])){reasons.push(`plugin "${name51}" has scope 'server' (its hooks would guard no other app until this one is imported)`)}return reasons}function serverScopedPluginsOf(plugins){return plugins.flatMap(plugin=>{const{metadata}=normalizePlugin(plugin);const nested=serverScopedPluginsOf(metadata.plugins??[]);return metadata.scope==="server"?[metadata.name,...nested]:nested})}function whyLoadedAppCannotBeLazy(entries){const names=list=>list.map(({name:name51})=>`"${name51}"`).join(", ");const reasons=[];if(entries.skills.length>0)reasons.push(`it has skills (${names(entries.skills)})`);if(entries.agents.length>0)reasons.push(`it has agents (${names(entries.agents)})`);if(entries.duties.length>0)reasons.push(`it has duties (${names(entries.duties)}), which start with the server`);for(const hook of entries.hooks){const label=`${hook.metadata.pluginName??classNameOf2(hook)}.${hook.metadata.method}`;if(!ENTRY_CALL_FLOWS.has(hook.metadata.flow)){reasons.push(`the hook ${label} is on ${hook.metadata.flow}, which runs it for every app`)}else if(hook.metadata.appliesTo==="all-apps"){reasons.push(`the hook ${label} applies to all apps`)}}const facts=(label,entry,widget=false)=>({label,authorities:entry.authorities!==void 0,ownEnabledSource:isEnabledSource(entry.enabled),widget,readBeforeTheCall:READ_BEFORE_THE_CALL.filter(key=>isEnforcementRequested(entry[key]))});return[...reasons,...reasonsOf([...entries.tools.map(tool=>facts(`tool "${tool.name}"`,tool.metadata,hasUIConfig(tool.metadata))),...entries.resources.map(resource=>facts(resource.isTemplate?`resource template "${resource.uriTemplate}"`:`resource "${resource.uri}"`,resource.metadata)),...entries.prompts.map(prompt=>facts(`prompt "${prompt.name}"`,prompt.metadata))])]}function classNameOf2(hook){const cls=hookClassOf(hook);return typeof cls==="function"&&cls.name?cls.name:"an anonymous class"}var ENTRY_CALL_FLOWS,READ_BEFORE_THE_CALL;var init_lazy_app_rules=__esm({"libs/sdk/src/app/lazy/lazy-app.rules.ts"(){"use strict";init_enabled_metadata();init_enforced_metadata_utils();init_hook_registry();init_plugin_utils();init_ui_shared();ENTRY_CALL_FLOWS=new Set(["tools:call-tool","resources:read-resource","prompts:get-prompt","completion:complete"]);READ_BEFORE_THE_CALL=["featureFlag","codecall"]}});import{dirname as dirname6,fileExists as fileExists6,pathResolve as pathResolve5,readFile as readFile6}from"@frontmcp/utils";function serverManifestOf(scope){let lookup=lookups.get(scope);if(!lookup){const{manifest,__sourceDir}=scope.metadata;lookup=readServerManifest(manifest,__sourceDir);lookups.set(scope,lookup)}return lookup}async function readServerManifest(option,sourceDir){if(typeof option==="object")return{manifest:parsedManifest(option,"@FrontMcp({ manifest })"),where:"@FrontMcp({ manifest })"};const path4=option===void 0?manifestNextToEntry():pathResolve5(sourceDir??process.cwd(),option);if(!path4)return{where:`${SERVER_MANIFEST_FILE} next to the entry script, which this runtime does not name`};if(!await fileExists6(path4))return{where:path4};let content;try{content=JSON.parse(await readFile6(path4))}catch(error){throw unreadableManifest(path4,error instanceof Error?error.message:String(error))}return{manifest:parsedManifest(content,path4),where:path4}}function manifestNextToEntry(){const entry=typeof process==="undefined"?void 0:process.argv?.[1];return entry?pathResolve5(dirname6(pathResolve5(entry)),SERVER_MANIFEST_FILE):void 0}function parsedManifest(value,where){const parsed=serverManifestSchema.safeParse(value);if(parsed.success)return parsed.data;const issues=parsed.error.issues.slice(0,3).map(issue=>`${issue.path.join(".")||"manifest"}: ${issue.message}`);throw unreadableManifest(where,issues.join("; "))}function unreadableManifest(where,reason){return new LazyAppConfigurationError(`${where} is not a ${SERVER_MANIFEST_FILE} this server can read (${reason}). Run \`frontmcp build\` to write it again.`)}function noteEagerLoading(scope,where){if(notedEagerLoading.has(scope))return;notedEagerLoading.add(scope);scope.logger.info(`No ${SERVER_MANIFEST_FILE} (looked for ${where}): lazy apps are loaded at startup. Run \`frontmcp build\` to write one; with it, each lazy app is imported on its first call.`)}function listedAppOf(manifest,appId){const app=manifest.apps.find(candidate=>candidate.id===appId);if(!app)return void 0;const own=entries=>entries.filter(entry=>entry.app===appId);return{app,tools:own(manifest.tools),resources:own(manifest.resources),resourceTemplates:own(manifest.resourceTemplates),prompts:own(manifest.prompts),skills:own(manifest.skills)}}function recordedListsOf(listed){return{tools:listed.tools,resources:[...listed.resources,...listed.resourceTemplates],prompts:listed.prompts}}function canonicalJson(value){const sorted=node=>{if(Array.isArray(node))return node.map(sorted);if(node===null||typeof node!=="object")return node;const record=node;return Object.fromEntries(Object.keys(record).sort().map(key=>[key,sorted(record[key])]))};return JSON.stringify(sorted(JSON.parse(JSON.stringify(value))))}function sameEntries(left,right){const fingerprint=entries=>entries.map(canonicalJson).sort().join("\n");return fingerprint(left)===fingerprint(right)}function changedLists(listed,loaded,outputs){const kinds=["tools","resources","prompts"];return kinds.filter(kind=>!sameEntries(listed[kind],loaded[kind])||kind==="tools"&&canonicalJson(outputs.listed??{})!==canonicalJson(outputs.loaded??{}))}var lookups,notedEagerLoading;var init_lazy_manifest=__esm({"libs/sdk/src/app/lazy/lazy-manifest.ts"(){"use strict";init_lazy_app_errors();init_server_manifest_schema();lookups=new WeakMap;notedEagerLoading=new WeakSet}});var app_lazy_instance_exports={};__export(app_lazy_instance_exports,{AppLazyInstance:()=>AppLazyInstance});import{getMetadata as getMetadata20,isClass as isClass18}from"@frontmcp/di";import{isProduction as isProduction5}from"@frontmcp/utils";function appClassOf(imported,appId){const isApp=value=>isClass18(value)&&getMetadata20(FrontMcpLocalAppTokens.type,value)!==void 0;if(isApp(imported))return imported;const exports=typeof imported==="object"&&imported!==null?imported:{};if(isApp(exports["default"]))return exports["default"];const apps=Object.values(exports).filter(isApp);if(apps.length===1)return apps[0];throw new LazyAppConfigurationError(`App "${appId}": the lazy import resolved to no @App class (${apps.length>1?`${apps.length} @App exports and no default export`:"no @App export"}). Resolve it to the app's class, such as () => import('./billing.app').then((m) => m.BillingApp).`)}function placeholderToolClass(app){return class LazyToolPlaceholder extends ToolContext{async execute(){throw new LazyAppLoadError(app.metadata.name,app.retryable)}}}function placeholderResourceClass(app){return class LazyResourcePlaceholder extends ResourceContext{async execute(){throw new LazyAppLoadError(app.metadata.name,app.retryable)}}}function placeholderPromptClass(app){return class LazyPromptPlaceholder extends PromptContext{async execute(){throw new LazyAppLoadError(app.metadata.name,app.retryable)}}}function recordedListsOfApp(app){const lineageOf=(registry,entry)=>ownersOf(registry.lineageOf(entry),entry.owner);const resources=app.resources.listAllInstances().flatMap(resource=>{const recorded=manifestResourceOf(resource,lineageOf(app.resources,resource));if(!recorded)return[];return["template"in recorded?recorded.template:recorded.resource]});return{tools:app.tools.listAllInstances().map(tool=>manifestToolOf(tool,lineageOf(app.tools,tool))),resources,prompts:app.prompts.listAllInstances().map(prompt=>manifestPromptOf(prompt,lineageOf(app.prompts,prompt)))}}function cannotBeLazy(appId,reasons){return new LazyAppConfigurationError(`App "${appId}" cannot be lazy: ${reasons.join("; ")}. A lazy app's tools, resources and prompts are listed from ${SERVER_MANIFEST_FILE} before its code is imported, so nothing in them may need that code to be listed, its hooks may run only for its own calls, and nothing only startup sets up. Remove \`lazy\` to import the app at startup, or move these to an app that is not lazy.`)}function messageOf4(error){return error instanceof Error?error.message:String(error)}var AppLazyInstance;var init_app_lazy_instance=__esm({"libs/sdk/src/app/instances/app.lazy.instance.ts"(){"use strict";init_common();init_duty_metadata();init_lazy_app_errors();init_plugin_errors();init_manifest_mode_flag();init_hook_registry();init_build_server_manifest();init_server_manifest_schema();init_prompt_instance();init_prompt_registry();init_provider_registry();init_resource_instance();init_resource_registry();init_unchanged_lists();init_tool_instance();init_tool_registry();init_app_utils();init_lazy_app_rules();init_lazy_manifest();init_lazy_placeholders();init_app_local_instance();init_empty_app_registries();AppLazyInstance=class extends AppEntry{id;retryable=true;scopeProviders;ownProviders;appOwner;appTools;appResources;appPrompts;noPlugins=new EmptyPluginRegistry2;noAdapters=new EmptyAdapterRegistry2;noSkills=new EmptySkillRegistry2;listed;loaded;loading;failure;constructor(record,scopeProviders){super(record);this.id=appIdOf(this.metadata);this.scopeProviders=scopeProviders;this.appOwner={kind:"app",id:this.id,ref:this.token};this.ownProviders=new ProviderRegistry([],scopeProviders);this.appTools=new ToolRegistry(this.ownProviders,[],this.appOwner,{adopt:false});this.appResources=new ResourceRegistry(this.ownProviders,[],this.appOwner,{adopt:false});this.appPrompts=new PromptRegistry(this.ownProviders,[],this.appOwner,{adopt:false});this.ready=this.initialize()}async initialize(){await Promise.all([this.ownProviders.ready,this.appTools.ready,this.appResources.ready,this.appPrompts.ready]);const scope=this.scope;if(isManifestMode(scope.metadata))return this.load();const{manifest,where}=await serverManifestOf(scope);const listed=manifest&&listedAppOf(manifest,this.id);if(listed)return this.listFrom(listed);if(isProduction5()){const missing=manifest?`${where} does not list it`:`no ${SERVER_MANIFEST_FILE} was found (looked for ${where})`;throw new LazyAppConfigurationError(`App "${this.id}" is lazy, and ${missing}. In production a lazy app is listed from the manifest until its first call: Run \`frontmcp build\` and ship ${SERVER_MANIFEST_FILE} next to the server's entry, or pass @FrontMcp({ manifest }).`)}if(this.metadata.enabled===false)return;if(manifest){scope.logger.info(`App "${this.id}" is loaded at startup: ${where} does not list it. Run \`frontmcp build\` to write it again.`)}else{noteEagerLoading(scope,where)}await this.load()}get scope(){return this.scopeProviders.getActiveScope()}load(){if(this.loaded)return Promise.resolve();if(this.failure)return Promise.reject(this.failure);this.loading??=this.importApp().finally(()=>{this.loading=void 0});return this.loading}async importApp(){const scope=this.scope;const hooksBefore=new Set(scope.hooks.getHooks());let app;try{const record=normalizeApp(appClassOf(await this.metadata.lazy(),this.id));const imported=record.metadata;if(appIdOf(imported)!==this.id){throw new LazyAppConfigurationError(`App "${this.id}": the lazy import resolved to the imported app "${appIdOf(imported)}". Give the lazy app the @App's id, or import the app it names.`)}const reasons=whyAppCannotBeLazy(imported);if(reasons.length>0)throw cannotBeLazy(this.id,reasons);this.assertServing();app=new AppLocalInstance(record,this.scopeProviders);await app.ready;this.assertCanBeLazy(app,hooksBefore);const recorded=recordedListsOfApp(app);if(!isManifestMode(scope.metadata))this.applySwitch(app);if(this.listed){await scope.checkLateApp(app);await app.providers.runReadyHooks(scope.logger)}this.assertServing();this.useLoaded(app,imported,recorded)}catch(error){if(app)await this.discard(app,hooksBefore);this.retryable=!(error instanceof LazyAppConfigurationError||error instanceof UnenforcedMetadataError);if(!this.retryable)this.failure=error;if(this.listed&&!scope.isDisposed){const next=this.retryable?"the next call imports it again":"restart the server once it is fixed";scope.logger.error(`App "${this.id}" could not be loaded (${next}): ${messageOf4(error)}`)}throw error}}assertServing(){if(this.scope.isDisposed)throw new LazyAppLoadError(this.metadata.name,false)}assertCanBeLazy(app,hooksBefore){const duties=[...app.providers.getAllSingletons().values()].flatMap(value=>dutyMetadataOf(value)??[]);const reasons=whyLoadedAppCannotBeLazy({tools:app.tools.listAllInstances(),resources:app.resources.listAllInstances(),prompts:app.prompts.listAllInstances(),skills:app.skills.getSkills(true),agents:app.agents.listAllInstances(),hooks:this.hooksRegisteredBy(app,hooksBefore).filter(hook=>hook.metadata.owner),duties});if(reasons.length>0)throw cannotBeLazy(this.id,reasons)}hooksRegisteredBy(app,hooksBefore){const registries=[app.tools,app.resources,app.prompts];const entryClasses=new Set(registries.flatMap(registry=>registry?.listAllInstances().map(entry=>entry.record.provide)??[]));return this.scope.hooks.getHooks().filter(hook=>{if(hooksBefore.has(hook))return false;const owner=hook.metadata.owner;return owner?owner.kind==="app"&&owner.id===this.id:entryClasses.has(hookClassOf(hook))})}async discard(app,hooksBefore){const scope=this.scope;scope.hooks.removeHooks(this.hooksRegisteredBy(app,hooksBefore));const providers=app.providers;await providers?.runShutdownHooks(scope.logger);providers?.dispose();app.adapters?.dispose()}applySwitch(app){const enabled=this.metadata.enabled;if(enabled===void 0)return;const entries=[...app.tools.listAllInstances(),...app.resources.listAllInstances(),...app.prompts.listAllInstances()];for(const entry of entries){if(entry.metadata.enabled!==false)entry.metadata.enabled=enabled}}useLoaded(app,imported,recorded){const listedOutput=this.metadata.output;this.metadata.description??=imported.description;this.metadata.output=imported.output;const changed=this.listed?changedLists(recordedListsOf(this.listed),recorded,{listed:listedOutput,loaded:imported.output}):[];keepingListsUnchanged(()=>{this.appTools.replaceAll([],this.appOwner);this.appResources.replaceAll([],this.appOwner);this.appPrompts.replaceAll([],this.appOwner);this.appTools.adoptFromChild(app.tools,app.tools.owner);this.appResources.adoptFromChild(app.resources,app.resources.owner);this.appPrompts.adoptFromChild(app.prompts,app.prompts.owner)});this.loaded=app;this.listed=void 0;if(changed.length===0)return;this.scope.logger.warn(`App "${this.id}" does not match ${SERVER_MANIFEST_FILE} (${changed.join(", ")}): its entries are listed from its code from now on. Run \`frontmcp build\` to write the manifest again.`);for(const kind of changed)this.registryOf(kind).notifyListChanged()}registryOf(kind){const scope=this.scope;return kind==="tools"?scope.tools:kind==="resources"?scope.resources:scope.prompts}async listFrom(listed){const reasons=whyListedAppCannotBeLazy(listed);if(reasons.length>0)throw cannotBeLazy(this.id,reasons);this.listed=listed;this.metadata.description??=listed.app.description;this.metadata.output=listed.app.output;const enabledOf=entry=>entry.enabled===false?false:this.metadata.enabled;const placeholders=[...listed.tools.map(tool=>this.toolPlaceholder(tool,enabledOf(tool))),...listed.resources.map(resource=>this.resourcePlaceholder(resource,enabledOf(resource))),...listed.resourceTemplates.map(template=>this.resourcePlaceholder(template,enabledOf(template))),...listed.prompts.map(prompt=>this.promptPlaceholder(prompt,enabledOf(prompt)))];await Promise.all(placeholders.map(placeholder=>placeholder.ready));for(const placeholder of placeholders)markPlaceholder(placeholder,this)}toolPlaceholder(tool,enabled){const metadata={name:tool.name,title:tool.title,description:tool.description,inputSchema:{},rawInputSchema:tool.inputSchema,rawOutputSchema:tool.outputSchema,annotations:tool.annotations,icons:tool.icons,_meta:tool._meta,tags:tool.tags,aliases:tool.aliases,visibility:tool.visibility,execution:tool.execution,output:tool.output,examples:tool.examples,availableWhen:tool.availableWhen,enabled};const placeholder=new ToolInstance({kind:"CLASS_TOKEN",provide:placeholderToolClass(this),metadata},this.ownProviders,this.appOwner);this.appTools.registerToolInstance(placeholder);return placeholder}resourcePlaceholder(resource,enabled){const{app:_app,owner:_owner,authorities:_authorities,enabled:_enabled,...listedFields}=resource;const metadata={...listedFields,enabled};const provide=placeholderResourceClass(this);const record="uriTemplate"in resource?{kind:"CLASS_TOKEN",provide,metadata}:{kind:"CLASS_TOKEN",provide,metadata};const placeholder=new ResourceInstance(record,this.ownProviders,this.appOwner);this.appResources.registerResourceInstance(placeholder);return placeholder}promptPlaceholder(prompt,enabled){const{app:_app,owner:_owner,authorities:_authorities,enabled:_enabled,...listedFields}=prompt;const metadata={...listedFields,arguments:listedFields.arguments??[],enabled};const provide=placeholderPromptClass(this);const placeholder=new PromptInstance({kind:"CLASS_TOKEN",provide,metadata},this.ownProviders,this.appOwner);this.appPrompts.registerPromptInstance(placeholder);return placeholder}get providers(){return this.ownProviders}get adapters(){return this.loaded?.adapters??this.noAdapters}get plugins(){return this.loaded?.plugins??this.noPlugins}get tools(){return this.appTools}get resources(){return this.appResources}get prompts(){return this.appPrompts}get skills(){return this.noSkills}}}});import"reflect-metadata";import{tokenName as tokenName19}from"@frontmcp/di";var AppRegistry;var init_app_registry=__esm({"libs/sdk/src/app/app.registry.ts"(){"use strict";init_common();init_errors();init_regsitry();init_app_utils();init_app_local_instance();AppRegistry=class extends RegistryAbstract{owner;logger;constructor(globalProviders,list,owner){super("AppRegistry",globalProviders,list);this.owner=owner;try{this.logger=globalProviders.get(FrontMcpLogger)?.child("AppRegistry")}catch{}}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;const configuredAppIds=new Set;const records=list.map(raw=>normalizeApp(raw));for(const rec of records){if(rec.kind==="REMOTE_VALUE"&&!rec.useValue||rec.kind==="LAZY_IMPORT"){const appId=appIdOf(rec.metadata);if(configuredAppIds.has(appId))throw new DuplicateAppIdError(appId);configuredAppIds.add(appId)}const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}for(const rec of records){if(rec.kind!=="LAZY_IMPORT")continue;const appId=appIdOf(rec.metadata);if(records.some(other=>other!==rec&&appIdOf(other.metadata)===appId)){throw new DuplicateAppIdError(appId)}}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);const deps=appDiscoveryDeps(rec);for(const d of deps){if(!this.providers.get(d)){throw new RegistryDependencyNotRegisteredError("App",tokenName19(token),tokenName19(d))}this.graph.get(token).add(d)}}}async initialize(){this.logger?.verbose(`AppRegistry: initializing ${this.tokens.size} app(s)`);const readyArr=[];for(const token of this.tokens){const rec=this.defs.get(token);let app;if(rec.kind==="LOCAL_CLASS"){app=new AppLocalInstance(rec,this.providers)}else if(rec.kind==="REMOTE_VALUE"){const remoteMeta=rec.metadata;if(remoteMeta.urlType==="npm"||remoteMeta.urlType==="esm"){const{AppEsmInstance:AppEsmInstance2}=await Promise.resolve().then(()=>(init_app_esm_instance(),app_esm_instance_exports));app=new AppEsmInstance2(rec,this.providers)}else{const{AppRemoteInstance:AppRemoteInstance2}=await Promise.resolve().then(()=>(init_app_remote_instance(),app_remote_instance_exports));app=new AppRemoteInstance2(rec,this.providers)}}else if(rec.kind==="LAZY_IMPORT"){const{AppLazyInstance:AppLazyInstance2}=await Promise.resolve().then(()=>(init_app_lazy_instance(),app_lazy_instance_exports));app=new AppLazyInstance2(rec,this.providers)}else{throw new InvalidRegistryKindError("app",rec.kind)}this.instances.set(token,app);readyArr.push(app.ready);this.logger?.verbose(`AppRegistry: registered ${rec.kind} app '${rec.metadata.name}'`)}const settled=await Promise.allSettled(readyArr);const failure=settled.find(result=>result.status==="rejected");if(failure)throw failure.reason;this.logger?.debug(`AppRegistry: initialization complete (${this.instances.size} app(s))`)}getApps(){return[...this.instances.values()]}}}});import{depsOfClass as depsOfClass11,getMetadata as getMetadata21,isClass as isClass19,tokenName as tokenName20}from"@frontmcp/di";function collectAuthMetadata(cls){return Object.entries(FrontMcpAuthProviderTokens).reduce((metadata,[key,token])=>{return Object.assign(metadata,{[key]:getMetadata21(token,cls)})},{})}function normalizeAuth(item){if(isClass19(item)){const metadata=collectAuthMetadata(item);return{kind:"CLASS_TOKEN",provide:item,metadata}}if(item&&typeof item==="object"){const{provide,useClass,useValue,useFactory,inject,...metadata}=item;if(!provide){const name52=item?.name??"[object]";throw new MissingProvideError("Auth",name52)}if(useClass){if(!isClass19(useClass)){throw new InvalidUseClassError("auth",tokenName20(provide))}return{kind:"CLASS",provide,useClass,metadata}}if(useFactory){if(typeof useFactory!=="function"){throw new InvalidUseFactoryError("auth",tokenName20(provide))}const inj=typeof inject==="function"?inject:()=>[];return{kind:"FACTORY",provide,inject:inj,useFactory,metadata}}if("useValue"in item){return{kind:"VALUE",provide,useValue,metadata}}}const name51=item?.name??String(item);throw new InvalidEntityError("auth",name51,"a class or an auth object")}function authDiscoveryDeps(rec){switch(rec.kind){case"VALUE":case"PRIMARY":return[];case"FACTORY":{return[...rec.inject()]}case"CLASS":return depsOfClass11(rec.useClass,"discovery");case"CLASS_TOKEN":return depsOfClass11(rec.provide,"discovery")}}var init_auth_utils=__esm({"libs/sdk/src/auth/auth.utils.ts"(){"use strict";init_common();init_errors()}});import{ORCHESTRATED_AUTH_ACCESSOR,NullOrchestratedAuthAccessor}from"@frontmcp/auth";var orchestratedAuthContextExtension;var init_orchestrated_context_extension=__esm({"libs/sdk/src/auth/authorization/orchestrated.context-extension.ts"(){"use strict";orchestratedAuthContextExtension={property:"orchestration",token:ORCHESTRATED_AUTH_ACCESSOR,errorMessage:"Orchestrated authorization not available. Ensure your server is configured with orchestrated mode and the user has completed authentication."}}});import"reflect-metadata";import{detectAuthProviders}from"@frontmcp/auth";import{tokenName as tokenName21}from"@frontmcp/di";var DEFAULT_AUTH_OPTIONS,AuthRegistry;var init_auth_registry=__esm({"libs/sdk/src/auth/auth.registry.ts"(){"use strict";init_app_utils();init_common();init_context_extension();init_errors();init_regsitry();init_auth_utils();init_orchestrated_context_extension();DEFAULT_AUTH_OPTIONS={mode:"public"};AuthRegistry=class extends RegistryAbstract{primary;parsedOptions;logger;owner;detection;requiresOrchestration;constructor(scope,providers,metadata,owner,primaryInput,createPrimaryAuth2){super("AuthRegistry",providers,metadata,false);this.owner=owner;this.logger=providers.get(FrontMcpLogger).child("AuthRegistry");this.parsedOptions=parseAuthOptions(primaryInput??DEFAULT_AUTH_OPTIONS);const appAuthInfos=this.extractAppAuthInfo(scope);this.detection=detectAuthProviders(this.parsedOptions,appAuthInfos);this.requiresOrchestration=this.detection.requiresOrchestration;this.logDetectionResults();this.validateConfiguration();this.primary=createPrimaryAuth2(scope,providers,this.parsedOptions);if(isOrchestratedMode(this.parsedOptions)){installContextExtensions("orchestrated-auth",[orchestratedAuthContextExtension])}const primaryRecord={kind:"PRIMARY",provide:FrontMcpAuth,useValue:this.primary,metadata:this.parsedOptions};this.tokens.add(FrontMcpAuth);this.defs.set(FrontMcpAuth,primaryRecord);this.graph.set(FrontMcpAuth,new Set);this.buildGraph();this.ready=this.initialize()}extractAppAuthInfo(scope){const apps=scope.metadata.apps||[];const result=[];for(const app of apps){const appMeta=this.getAppMetadata(app);if(appMeta){result.push({id:appMeta.id||appMeta.name,name:appMeta.name,auth:appMeta.auth,remoteAuthMode:appMeta.remoteAuthMode})}}return result}getAppMetadata(app){if(typeof app==="object"&&"name"in app){const appValue=app;return{id:appValue.id,name:appValue.name,auth:appValue.auth,remoteAuthMode:appValue.remoteAuth?.mode}}if(typeof app==="function"){const metadata=collectAppMetadata(app);if(metadata.name){return{id:metadata.id,name:metadata.name,auth:metadata.auth}}}return void 0}logDetectionResults(){const{providers,uniqueProviderCount,requiresOrchestration,warnings}=this.detection;if(uniqueProviderCount>1){this.logger.info(`Detected ${uniqueProviderCount} unique auth providers: ${[...providers.keys()].join(", ")}`)}if(requiresOrchestration){this.logger.info(`Orchestration required: Multiple auth providers detected across apps`)}for(const warning of warnings){this.logger.warn(warning)}}validateConfiguration(){const{validationErrors}=this.detection;if(validationErrors.length>0){for(const error of validationErrors){this.logger.error(`[AuthRegistry] ${error}`)}throw new AuthConfigurationError(`Invalid auth configuration: ${validationErrors[0]}`,{errors:validationErrors,suggestion:this.suggestionFor(validationErrors[0])})}}suggestionFor(error){if(error.includes("remoteAuth: { mode: 'forward' }")){return`Give the remote its own credentials, or run the server in transparent mode:
185
+ ${promptContentToText(message.content)}`);return[...result.description?[result.description]:[],...parts].join("\n\n")}function promptContentToText(content){switch(content.type){case"text":return content.text;case"image":return`[image omitted (${content.mimeType})]`;case"audio":return`[audio omitted (${content.mimeType})]`;case"resource_link":return`[resource link: ${content.uri}${content.name?` (${content.name})`:""}]`;case"resource":{const resource=content.resource;if("text"in resource)return resource.text;return describeBinary(resource.uri,resource.mimeType,resource.blob)}default:return`[${content.type} content omitted]`}}function describeBinary(uri,mimeType,base64){const padding=base64.endsWith("==")?2:base64.endsWith("=")?1:0;const bytes=Math.max(0,Math.floor(base64.length*3/4)-padding);return`[binary content omitted: ${uri} (${mimeType??"application/octet-stream"}, ${bytes} bytes)]`}var AGENT_SURFACE,AGENT_BUILTIN_TOOL_NAMES,EMPTY_PARAMETERS,AGENT_BUILTIN_TOOL_DEFINITIONS,readResourceArgsSchema,getPromptArgsSchema;var init_agent_builtin_tools=__esm({"libs/sdk/src/agent/agent-builtin-tools.ts"(){"use strict";init_availability();init_errors();init_mcp_error_utils();AGENT_SURFACE="agent";AGENT_BUILTIN_TOOL_NAMES={listResources:"list_resources",readResource:"read_resource",listPrompts:"list_prompts",getPrompt:"get_prompt"};EMPTY_PARAMETERS={type:"object",properties:{},additionalProperties:false};AGENT_BUILTIN_TOOL_DEFINITIONS={list_resources:{name:AGENT_BUILTIN_TOOL_NAMES.listResources,description:"List the resources you can read with read_resource: each resource with its URI, and each resource template with the URI template whose placeholders you fill in.",parameters:EMPTY_PARAMETERS},read_resource:{name:AGENT_BUILTIN_TOOL_NAMES.readResource,description:"Read a resource by its URI: one list_resources lists, or a resource template URI with its placeholders filled in. Returns the text of the resource; binary content is described, not included.",parameters:{type:"object",properties:{uri:{type:"string",description:"The URI of the resource to read"}},required:["uri"],additionalProperties:false}},list_prompts:{name:AGENT_BUILTIN_TOOL_NAMES.listPrompts,description:"List the prompts you can get with get_prompt, with the arguments each one takes.",parameters:EMPTY_PARAMETERS},get_prompt:{name:AGENT_BUILTIN_TOOL_NAMES.getPrompt,description:"Get a prompt by its name, with its arguments filled in. Returns its messages as text.",parameters:{type:"object",properties:{name:{type:"string",description:"The name of the prompt, as list_prompts lists it"},arguments:{type:"object",description:"The prompt's arguments, by name",additionalProperties:{type:"string"}}},required:["name"],additionalProperties:false}}};readResourceArgsSchema=z71.object({uri:z71.string().min(1)});getPromptArgsSchema=z71.object({name:z71.string().min(1),arguments:z71.record(z71.string(),z71.union([z71.string(),z71.number(),z71.boolean()])).optional()})}});function isObserverChain(value){return Array.isArray(value)&&value.every(observer=>typeof observer==="function")}function observersOf(context){const installed=context.get(HOOK_OBSERVER_KEY);if(typeof installed==="function")return[installed];return isObserverChain(installed)?installed:NO_OBSERVERS}function addHookObserver(context,observer){const observers=observersOf(context);if(!observers.includes(observer))context.set(HOOK_OBSERVER_KEY,[...observers,observer])}function runObservedHook(observers,hook,run,onObserverError=()=>void 0){const runFrom=async index=>{const observer=observers[index];if(!observer)return run();let inner;const runInner=()=>{if(!inner){inner=runFrom(index+1);inner.catch(()=>void 0)}return inner};try{await observer(hook,runInner)}catch(error){const innerError=inner&&await inner.then(()=>void 0,failure=>({failure}));if(!innerError||innerError.failure!==error)onObserverError(error,observer)}return runInner()};return runFrom(0)}function planStageOf(hook){if(hook.type==="stage")return hook.stage;const stage=hook.stage.slice(hook.type.length);return stage?stage[0].toLowerCase()+stage.slice(1):hook.stage}function outcomeOf(thrown){return thrown instanceof FlowControl?thrown.type:"error"}function recordHookTrace(trace){return async(hook,run)=>{const entry={owner:hook.owner,method:hook.method,stage:planStageOf(hook),type:hook.type,ms:0,outcome:"ok"};trace.push(entry);const started=performance.now();try{await run()}catch(thrown){entry.outcome=outcomeOf(thrown);throw thrown}finally{entry.ms=Math.round((performance.now()-started)*1e3)/1e3}}}function withHookTrace(answer,trace){if(trace.length===0)return answer;if(typeof answer!=="object"||answer===null||Array.isArray(answer))return answer;const meta=answer._meta;return{...answer,_meta:{...meta,[HOOK_TRACE_META_KEY]:trace}}}var HOOK_OBSERVER_KEY,HOOK_TRACE_META_KEY,NO_OBSERVERS;var init_hook_observers=__esm({"libs/sdk/src/hooks/hook-observers.ts"(){"use strict";init_common();HOOK_OBSERVER_KEY=Symbol.for("frontmcp:hook-observer");HOOK_TRACE_META_KEY="frontmcp/trace";NO_OBSERVERS=[]}});function declaringClassOf(hook){const target=hook.target;if(typeof target==="function")return target;return target&&typeof target==="object"?target.constructor:void 0}function classNameOf(hook){const cls=declaringClassOf(hook);return typeof cls==="function"?cls.name:""}function hookOwnerName(hook){return hook.pluginName||classNameOf(hook)}function hookIdOf(hook){return`${hookOwnerName(hook)}.${hook.method}`}function namesHook(target,hook){return[hook.pluginName,classNameOf(hook)].some(name51=>!!name51&&(target===name51||target===`${name51}.${hook.method}`))}function isSameHook(a,b){const cls=declaringClassOf(a);return a===b||cls!==void 0&&cls===declaringClassOf(b)&&a.method===b.method}function hasConstraints(hook){return(hook.before?.length??0)>0||(hook.after?.length??0)>0}function cycleError(hooks,waitsFor,placed){const path4=[];let current=hooks.findIndex((_hook,index)=>!placed.has(index));while(!path4.includes(current)){path4.push(current);current=[...waitsFor[current]].find(first3=>!placed.has(first3))??current}const cycle=path4.slice(path4.indexOf(current)).reverse();const start=cycle.indexOf(Math.min(...cycle));const inRunOrder=[...cycle.slice(start),...cycle.slice(0,start)];const{flow,type,stage}=hooks[inRunOrder[0]];return new HookOrderCycleError(flow,type,String(stage),inRunOrder.map(index=>hookIdOf(hooks[index])))}function placesOf(runsBefore){const places=runsBefore.map((_targets,index)=>index);let moved=true;while(moved){moved=false;runsBefore.forEach((targets,index)=>{for(const target of targets){if(places[target]<places[index]){places[index]=places[target];moved=true}}})}return places}function orderByConstraints(items,hookOf,canBeNamed=()=>true){const hooks=items.map(hookOf);if(!hooks.some(hasConstraints))return items;const waitsFor=hooks.map(()=>new Set);const runsBefore=hooks.map(()=>new Set);hooks.forEach((hook,index)=>{hooks.forEach((other,otherIndex)=>{if(isSameHook(hook,other)||!canBeNamed(items[otherIndex]))return;if(hook.before?.some(target=>namesHook(target,other))){waitsFor[otherIndex].add(index);runsBefore[index].add(otherIndex)}if(hook.after?.some(target=>namesHook(target,other)))waitsFor[index].add(otherIndex)})});const places=placesOf(runsBefore);const placed=new Set;const ordered=[];while(ordered.length<items.length){let next=-1;hooks.forEach((_hook,index)=>{if(placed.has(index)||![...waitsFor[index]].every(first3=>placed.has(first3)))return;if(next===-1||places[index]<places[next])next=index});if(next===-1)throw cycleError(hooks,waitsFor,placed);placed.add(next);ordered.push(items[next])}return ordered}function joinWithAnd(parts){return parts.length>1?`${parts.slice(0,-1).join(", ")} and ${parts[parts.length-1]}`:parts.join("")}function unmatchedTargetsWarning(hook,stageHooks){const unmatched=direction=>(hook[direction]??[]).filter(target=>!stageHooks.some(other=>!isSameHook(hook,other)&&namesHook(target,other))).map(target=>`'${target}' in ${direction}`);const listed=[...unmatched("before"),...unmatched("after")];if(listed.length===0)return void 0;const effect=listed.length===1?"it, so it changes":"them, so they change";return`Hook ${hookIdOf(hook)} (${hook.type} '${String(hook.stage)}' of '${hook.flow}') names ${joinWithAnd(listed)}, but no hook on that stage matches ${effect} nothing. A target is a plugin name or the class that declares the hook, optionally followed by .method.`}function byStage(hooks){const groups=new Map;for(const hook of hooks){const key=`${hook.flow} ${hook.type} ${String(hook.stage)}`;const stageHooks=groups.get(key)??[];stageHooks.push(hook);groups.set(key,stageHooks)}return[...groups.values()]}function hookRunsOf(registry){const hooks=registry.getHooks();const runs=[];for(const flow of new Set(hooks.map(hook=>hook.metadata.flow))){const flowHooks=registry.getFlowHooksForOwner(flow);const servedByFlow=new Set(flowHooks);const entryHooks=new Map;for(const hook of hooks){if(hook.metadata.flow!==flow||servedByFlow.has(hook))continue;const cls=declaringClassOf(hook.metadata);entryHooks.set(cls,[...entryHooks.get(cls)??[],hook.metadata])}const shared=flowHooks.map(hook=>hook.metadata);runs.push(shared,...[...entryHooks.values()].map(own=>[...shared,...own]))}return runs}function checkHookOrder(runs,warn){for(const run of runs){for(const stageHooks of byStage(run)){if(!stageHooks.some(hasConstraints))continue;const byPriority=[...stageHooks].sort((a,b)=>(a.priority??0)-(b.priority??0));orderByConstraints(byPriority,hook=>hook)}}const warned2=new Set;for(const stageHooks of byStage(new Set(runs.flat()))){for(const hook of stageHooks){const warning=hasConstraints(hook)?unmatchedTargetsWarning(hook,stageHooks):void 0;if(warning&&!warned2.has(warning)){warned2.add(warning);warn(warning)}}}}var init_hook_order=__esm({"libs/sdk/src/hooks/hook-order.ts"(){"use strict";init_errors()}});import{base64Decode as base64Decode3}from"@frontmcp/utils";function applyHeaders(res,headers){if(!headers)return;for(const[k,v]of Object.entries(headers)){res.setHeader(k,v)}}function applyCookies(res,cookies){if(!cookies||cookies.length===0)return;const existing=typeof res.getHeader==="function"?res.getHeader("Set-Cookie"):void 0;const existingArr=Array.isArray(existing)?existing:existing?[String(existing)]:[];const cookieStrings=cookies.map(serializeHttpCookie);res.setHeader("Set-Cookie",[...existingArr,...cookieStrings])}function contentDisposition(disposition,filename){return`${disposition}${filename?`; filename="${filename}"`:""}`}function utf8ByteLength(s){const enc=new TextEncoder;return enc.encode(s).byteLength}function stringToBytes(str,encoding){if(encoding==="utf8"){return new TextEncoder().encode(str)}try{return base64Decode3(str)}catch(err){throw new Error(`Invalid base64 body: ${err instanceof Error?err.message:String(err)}`,{cause:err})}}async function writeSseChunks(res,iterator){let clientLeft=false;let resume;const stop=()=>{if(clientLeft)return;clientLeft=true;resume?.();void iterator.return?.()};const drained=()=>resume?.();res.on?.("close",stop);res.on?.("drain",drained);if(res.destroyed)stop();try{for(let step=await iterator.next();!step.done&&!clientLeft;step=await iterator.next()){if(res.write(step.value)===false&&!clientLeft)await new Promise(resolve4=>resume=resolve4);resume=void 0}}finally{res.off?.("close",stop);res.off?.("drain",drained)}}async function writeHttpResponse(res,value){const parsed=httpOutputSchema.safeParse(value);if(!parsed.success){res.setHeader("Content-Type","text/plain; charset=utf-8");res.status(500).end("Internal Server Error");return}const out=parsed.data;if(out.kind==="next"||out.kind==="consumed"){return}const{headers,cookies}=out;if(headers){applyHeaders(res,headers)}if(cookies){applyCookies(res,cookies)}switch(out.kind){case"redirect":{res.setHeader("Location",out.location);if("redirect"in res&&typeof res.redirect==="function"){res.redirect(out.location)}else{res.status(out.status).end()}return}case"json":{res.setHeader("Content-Type",out.contentType);res.status(out.status??200);if(typeof res.json!=="function"){res.end(JSON.stringify(out.body))}else{res.json(out.body)}return}case"text":case"html":{res.setHeader("Content-Type",out.contentType);res.setHeader("Content-Length",utf8ByteLength(out.body));res.status(out.status).end(out.body);return}case"binary":case"image":{res.setHeader("Content-Type",out.contentType);res.setHeader("Content-Disposition",contentDisposition(out.disposition,out.filename));const bytes=typeof out.body==="string"?stringToBytes(out.body,out.encoding):out.body;res.setHeader("Content-Length",bytes.byteLength);res.status(out.status).end(bytes);return}case"stream":{res.setHeader("Content-Type",out.contentType);res.setHeader("Content-Disposition",contentDisposition(out.disposition,out.filename));res.status(out.status);if("flushHeaders"in res&&typeof res.flushHeaders==="function")res.flushHeaders();const maybeIter=out.stream[Symbol.asyncIterator];if(typeof maybeIter==="function"&&"write"in res&&typeof res.write==="function"){for await(const chunk of out.stream){res.write(chunk)}res.end();return}if("pipe"in out.stream&&typeof out.stream.pipe==="function"){out.stream.pipe(res);return}res.status(500).end("Streaming not supported by response object");return}case"sse":{res.setHeader("Content-Type",out.contentType);if(!out.headers||!("Cache-Control"in out.headers))res.setHeader("Cache-Control","no-cache");if(!out.headers||!("Connection"in out.headers))res.setHeader("Connection","keep-alive");res.status(out.status);if("flushHeaders"in res&&typeof res.flushHeaders==="function")res.flushHeaders();const maybeIter=out.stream[Symbol.asyncIterator];if(typeof maybeIter==="function"&&"write"in res&&typeof res.write==="function"){await writeSseChunks(res,maybeIter.call(out.stream));res.end();return}if("pipe"in out.stream&&typeof out.stream.pipe==="function"){out.stream.pipe(res);return}res.status(500).end("Streaming not supported by response object");return}case"jsonrpc":{res.setHeader("Content-Type",out.contentType);res.status(out.status);if(typeof res.json==="function"){res.json(out.body)}else{res.end(JSON.stringify(out.body))}return}case"problem":{res.setHeader("Content-Type",out.contentType);res.status(out.status);if(typeof res.json==="function"){res.json(out.body)}else{res.end(JSON.stringify(out.body))}return}case"empty":{res.status(out.status).end();return}case"web-response":{const r=out.response;r.headers.forEach((v,k)=>res.setHeader(k,v));res.status(r.status);if(r.body){for await(const chunk of r.body){res.write(chunk)}}res.end();return}}}var init_server_validation=__esm({"libs/sdk/src/server/server.validation.ts"(){"use strict";init_common()}});function flowErrorToHttpOutput(error){const misconfiguration=findMisconfiguration(error);if(misconfiguration){return{kind:"json",status:500,contentType:"application/json; charset=utf-8",body:misconfigurationBody(misconfiguration)}}if(error instanceof FlowControl){switch(error.type){case"respond":return error.output;case"next":case"handled":return void 0;default:return{kind:"text",status:500,body:"Internal Server Error",contentType:"text/plain; charset=utf-8"}}}if(error instanceof PublicMcpError){const challenge=error.wwwAuthenticate;return{kind:"json",status:error.statusCode,contentType:"application/json; charset=utf-8",body:{error:error.getPublicMessage()},...typeof challenge==="string"&&challenge.length>0?{headers:{"WWW-Authenticate":challenge}}:{}}}return{kind:"text",status:500,body:"Internal Server Error",contentType:"text/plain; charset=utf-8"}}var init_flow_error_output=__esm({"libs/sdk/src/transport/flow-error-output.ts"(){"use strict";init_common();init_errors();init_misconfiguration()}});import"reflect-metadata";function deferredFlow(declaration,load2){class DeferredFlow extends FlowBase{}Reflect.defineMetadata(FrontMcpFlowTokens.type,true,DeferredFlow);Reflect.defineMetadata(FrontMcpFlowTokens.name,declaration.name,DeferredFlow);Reflect.defineMetadata(FrontMcpFlowTokens.middleware,declaration.middleware,DeferredFlow);flowClassLoaders.set(DeferredFlow,load2);return DeferredFlow}function deferredFlowLoader(flowClass){return flowClassLoaders.get(flowClass)}var flowClassLoaders;var init_deferred_flow=__esm({"libs/sdk/src/flows/deferred-flow.ts"(){"use strict";init_common();flowClassLoaders=new WeakMap}});function matchMountedPath(pattern,path4){if(!pattern.includes("/:")){const prefix=pattern.endsWith("/")?pattern:`${pattern}/`;return path4===pattern||path4.startsWith(prefix)?{}:void 0}const mount=pattern.endsWith("/")?pattern.slice(0,-1):pattern;const expected=mount.split("/");const actual=path4.split("/");if(actual.length<expected.length)return void 0;return captureSegments(expected,actual)}function matchRoutePath(pattern,path4){const expected=withoutTrailingSlash(pattern).split("/");const actual=withoutTrailingSlash(path4).split("/");if(actual.length!==expected.length)return void 0;return captureSegments(expected,actual)}function withoutTrailingSlash(path4){return path4.length>1&&path4.endsWith("/")?path4.slice(0,-1):path4}function captureSegments(expected,actual){const params={};for(let i=0;i<expected.length;i++){const segment=expected[i];const value=actual[i];if(segment.length>1&&segment.startsWith(":")){if(value.length===0)return void 0;try{params[segment.slice(1)]=decodeURIComponent(value)}catch{return void 0}}else if(segment!==value){return void 0}}return params}var init_flow_http_path=__esm({"libs/sdk/src/flows/flow.http-path.ts"(){"use strict"}});function sortStageMap(table){for(const key of Object.keys(table)){const list=table[key];list.sort((a,b)=>a._priority-b._priority||a._order-b._order);const ordered=orderByConstraints(list,entry=>entry.hook,entry=>!entry.flowStep);if(ordered!==list)list.splice(0,list.length,...ordered)}}function cloneStageMap(table){const out={};for(const[k,v]of Object.entries(table))out[k]=v.slice();return out}function resolveStageKey(type,stage){return type==="stage"?stage:`${type}${cap(stage)}`}function collectFlowHookMap(FlowClass){const cached=CACHE.get(FlowClass);if(cached){return cached}const existingMetas=Reflect.getMetadata(FrontMcpFlowHookTokens.hooks,FlowClass)??[];const tc39Metas=resolvePendingTC39HooksForClass(FlowClass);const metas=[...existingMetas,...tc39Metas];const sorted=metas.map((m,i)=>({m,i})).sort((a,b)=>(a.m.priority??0)-(b.m.priority??0)||a.i-b.i).map(x=>x.m);const table={};let order=0;for(const m of sorted){const resolved=resolveStageKey(m.type,m.stage);const entry={hook:m,flowStep:true,_priority:m.priority??0,_order:order++,method:async(ctx,next=NO_NEXT)=>{const skipHook=()=>m.type==="around"?next():void 0;const target=m.static?FlowClass:ctx;const impl=typeof m.method==="function"?m.method:target?.[m.method];if(typeof impl!=="function")return skipHook();if(m.filter&&!await m.filter(ctx))return skipHook();if(m.type==="around"){return m.static?impl.call(FlowClass,ctx,next):impl.call(ctx,ctx,next)}else{return m.static?impl.call(FlowClass,ctx):impl.call(ctx,ctx)}}};(table[resolved]??=[]).push(entry)}sortStageMap(table);CACHE.set(FlowClass,table);return table}function mergeHookMetasIntoStageMap(FlowClass,table,metas,orderStart=1e5,runHook=(_hook,run)=>run()){let order=orderStart;const sorted=metas.map((m,i)=>({m,i})).sort((a,b)=>(a.m.priority??0)-(b.m.priority??0)||a.i-b.i).map(x=>x.m);for(const m of sorted){const resolved=resolveStageKey(m.type,m.stage);const entry={hook:m,_priority:m.priority??0,_order:order++,method:async(ctx,next=NO_NEXT)=>{const skipHook=()=>m.type==="around"?next():void 0;const target=m.target;if(!target){console.warn(`[flow] Hook target is missing for method ${m.method}`);return skipHook()}const impl=typeof m.method==="function"?m.method:target?.[m.method].bind(target);if(typeof impl!=="function")return skipHook();if(m.filter&&!await m.filter(ctx))return skipHook();return runHook({stage:resolved,target,metadata:m},async()=>m.type==="around"?impl.call(target,ctx,next):impl.call(target,ctx))}};(table[resolved]??=[]).push(entry)}sortStageMap(table)}function describeStep(hook,flowClassName){const target=hook.target;const owner=typeof target==="function"?target.name:target&&typeof target==="object"?target.constructor.name:"";const placement=[hook.priority??0,...(hook.before??[]).map(name51=>`before ${name51}`),...(hook.after??[]).map(name51=>`after ${name51}`)];return`${hook.type} ${owner||flowClassName}.${hook.method} (${placement.join(", ")})`}function describeHookOrder(stages,base,resolved,flowClassName){const lines=[];for(const stage of stages){const keys=HOOK_TYPES_IN_RUN_ORDER.map(type=>resolveStageKey(type,stage));if(!keys.some(key=>(resolved[key]?.length??0)>(base[key]?.length??0)))continue;const[will,around,body,did,after]=keys.map(key=>(resolved[key]??[]).map(entry=>describeStep(entry.hook,flowClassName)));const wrapped=around.reduceRight((inner,outer)=>`${outer} [ ${inner} ]`,body.join(" \u2192 "));lines.push(` ${stage}: ${[...will,wrapped,...did,...after].filter(Boolean).join(" \u2192 ")}`)}return lines}var cap,CACHE,NO_NEXT,HOOK_TYPES_IN_RUN_ORDER;var init_flow_stages=__esm({"libs/sdk/src/flows/flow.stages.ts"(){"use strict";init_common();init_hook_decorator();init_hook_order();cap=s=>s?s[0].toUpperCase()+s.slice(1):s;CACHE=new WeakMap;NO_NEXT=async()=>void 0;HOOK_TYPES_IN_RUN_ORDER=["will","around","stage","did","finally"]}});import{depsOfClass as depsOfClass6,getMetadata as getMetadata13,isClass as isClass10}from"@frontmcp/di";function collectFlowMetadata(cls){return Object.entries(FrontMcpFlowTokens).reduce((metadata,[key,token])=>{return Object.assign(metadata,{[key]:getMetadata13(token,cls)})},{})}function normalizeFlow(item){if(isClass10(item)){const metadata=collectFlowMetadata(item);return{kind:"CLASS_TOKEN",provide:item,metadata}}const name51=item?.name??String(item);throw new InvalidEntityError("flow",name51,"a class or a flow object")}var init_flow_utils2=__esm({"libs/sdk/src/flows/flow.utils.ts"(){"use strict";init_common();init_errors()}});import"reflect-metadata";import{tokenName as tokenName10}from"@frontmcp/di";import{isDebug as isDebug2,isDevelopment as isDevelopment4}from"@frontmcp/utils";function stageKeysOf(stage){let keys=stageKeysByName.get(stage);if(!keys){keys={will:`will${CAP(stage)}`,did:`did${CAP(stage)}`,around:`around${CAP(stage)}`,finally:`finally${CAP(stage)}`};stageKeysByName.set(stage,keys)}return keys}function parseTypedKey(k){const lc=k.toLowerCase();if(lc.startsWith("will")&&k.length>4)return{base:k.slice(4,5).toLowerCase()+k.slice(5),type:"will"};if(lc.startsWith("did")&&k.length>3)return{base:k.slice(3,4).toLowerCase()+k.slice(4),type:"did"};if(lc.startsWith("around")&&k.length>6)return{base:k.slice(6,7).toLowerCase()+k.slice(7),type:"around"};if(lc.startsWith("finally")&&k.length>7)return{base:k.slice(7,8).toLowerCase()+k.slice(8),type:"finally"};return{base:k}}function describeValue2(value){try{return String(value)}catch{return Object.prototype.toString.call(value)}}function failureOf(control){const originalError=control.originalError;if(originalError!==void 0)return originalError;return control.type==="abort"?new InternalMcpError(`Flow aborted: ${String(control.output)}`):control}function stageBasesOf(group){let bases=stageBasesByGroup.get(group);if(!bases){const seen=new Set;bases=[];for(const rawKey of group){const{base,type}=parseTypedKey(rawKey);const stage=type==="finally"&&!group.includes(base)?rawKey:base;if(type&&stage===base||seen.has(stage))continue;seen.add(stage);bases.push(stage)}stageBasesByGroup.set(group,bases)}return bases}function listJoinedAfterStep(list,present,step){const stepIndex=list.indexOf(step);if(stepIndex===-1)return list;const joinedBefore=list.slice(0,stepIndex).filter(entry=>!present.includes(entry));const rest=list.filter(entry=>!joinedBefore.includes(entry));rest.splice(rest.indexOf(step)+1,0,...joinedBefore);return rest}function nextStageOrder(stages){return Math.max(0,...Object.values(stages).flatMap(list=>list.map(e=>e._order??0)))+1}var FAILED_OUTCOMES,CAP,stageKeysByName,stageBasesByGroup,FLOW_PHASES,FlowInstance;var init_flow_instance=__esm({"libs/sdk/src/flows/flow.instance.ts"(){"use strict";init_common();init_context();init_running_flow();init_errors();init_misconfiguration();init_entry_class_hooks();init_hook_observers();init_hook_order();init_hooks_utils();init_server_validation();init_flow_error_output();init_deferred_flow();init_flow_http_path();init_flow_stages();init_flow_utils2();FAILED_OUTCOMES=new Set(["fail","abort","unknown_error"]);CAP=s=>s?s[0].toUpperCase()+s.slice(1):s;stageKeysByName=new Map;stageBasesByGroup=new WeakMap;FLOW_PHASES=["pre","execute","post","error","finalize"];FlowInstance=class extends FlowEntry{deps;globalProviders;plan;FlowClass;flowClassLoad;stages;hooks;logger;baseStageOrderEnd;loggedHookOrders=isDevelopment4()||isDebug2()?new Map:void 0;tracesHooks;failedObservers=new WeakSet;constructor(scope,record,deps,globalProviders){super(scope,record);this.deps=[...deps];this.globalProviders=globalProviders;this.FlowClass=this.record.provide;this.ready=this.initialize();this.plan=this.record.metadata.plan;this.hooks=scope.hooks;this.logger=scope.logger.child("FlowInstance");this.tracesHooks=this.FlowClass.tracesHooksInAnswer===true&&(scope.metadata.devtools?.hookTrace??isDevelopment4())}async initialize(){const server=this.globalProviders.getActiveServer();this.stages=collectFlowHookMap(this.FlowClass);const{middleware}=this.metadata;if(middleware){const path4=typeof middleware.path==="string"?middleware.path:"";server.registerMiddleware(path4,async(request2,response,next)=>{const canActivate=await this.canActivate(request2);if(!canActivate)return next();const contextStorage=this.getContextStorage();try{const result=await this.runWithContext(contextStorage,request2,{request:request2,response,next},new Map);if(result)return writeHttpResponse(response,result)}catch(e){if(e instanceof FlowControl){switch(e.type){case"abort":return writeHttpResponse(response,{kind:"text",status:500,body:"Aborted"});case"fail":return writeHttpResponse(response,{kind:"text",status:500,body:"Internal Server Error"});case"handled":return;case"next":return next();case"respond":return writeHttpResponse(response,e.output)}}const misconfiguration=findMisconfiguration(e);if(misconfiguration){this.logger.error("Server misconfigured",{flow:this.name,code:misconfiguration.code});return writeHttpResponse(response,{kind:"json",status:500,body:misconfigurationBody(misconfiguration)})}if(e instanceof PublicMcpError){const challenge=e.wwwAuthenticate;this.logger.warn("Public error in flow",{flow:this.name,name:e.name,status:e.statusCode,code:e.code});return writeHttpResponse(response,{kind:"json",status:e.statusCode,body:{error:e.getPublicMessage()},...typeof challenge==="string"&&challenge.length>0?{headers:{"WWW-Authenticate":challenge}}:{}})}this.logger.error("Unhandled error in flow",{flow:this.name,name:e instanceof Error?e.name:"UnknownError",message:e instanceof Error?e.message:String(e)});return writeHttpResponse(response,{kind:"text",status:500,body:"Internal Server Error"})}return next()})}return Promise.resolve()}loadFlowClass(){const load2=deferredFlowLoader(this.FlowClass);if(!load2)return Promise.resolve();this.flowClassLoad??=load2().then(flowClass=>{Object.assign(this.metadata,collectFlowMetadata(flowClass));this.plan=this.metadata.plan;this.stages=collectFlowHookMap(flowClass);this.FlowClass=flowClass});return this.flowClassLoad}async canActivate(request2){if(this.method&&request2.method!==this.method)return false;try{await this.loadFlowClass()}catch{return true}const canActivate=[...this.metadata.middleware?.canActivate??[]];if(this.FlowClass["canActivate"]){canActivate.push(this.FlowClass["canActivate"])}if(canActivate.length===0)return true;const results=await Promise.all(canActivate.map(m=>m(request2,this.scope)));return results.every(r=>r)}async matchHttp(request2){const mw=this.metadata.middleware;if(!mw)return false;const path4=typeof mw.path==="string"?mw.path:"";const hasStaticCanActivate=typeof this.FlowClass.canActivate==="function";const hasMwCanActivate=(mw.canActivate?.length??0)>0;if(!path4&&!hasStaticCanActivate&&!hasMwCanActivate)return false;if(this.method&&request2.method!==this.method)return false;const captured=path4?matchMountedPath(path4,request2.path):{};if(!captured)return false;const previous=request2.params;if(Object.keys(captured).length>0)request2.params={...captured,...previous};const activated=await this.canActivate(request2);if(!activated){if(previous===void 0)delete request2.params;else request2.params=previous}return activated}getContextStorage(){try{return this.globalProviders.get(FrontMcpContextStorage)}catch{this.logger.verbose("getContextStorage: FrontMcpContextStorage not available");return void 0}}async runWithContext(storage,request2,input,deps){if(!storage){return this.run(input,deps)}const scope=this.globalProviders.getActiveScope();return storage.runForHttpRequest(request2,scope.id,async()=>{return this.run(input,deps)})}async run(input,deps){this.logger.verbose(`run: starting flow '${this.name}'`);await this.loadFlowClass();const scope=this.globalProviders.getActiveScope();const contextStorage=this.getContextStorage();const currentContext=contextStorage?.getStore();const sessionKey=currentContext?.sessionId;if(!currentContext||!sessionKey){throw new RequestContextNotAvailableError("FrontMcpContext unavailable - session ID required for provider resolution. Ensure flow is wrapped with runWithContext.")}const runStages=()=>runAsFlow({context:currentContext,flow:this,scope},()=>this.runStages(input,deps,scope,currentContext,sessionKey));const responseHeaders=this.metadata.middleware?.responseHeaders;return responseHeaders?this.respondWithHeaders(runStages,responseHeaders):runStages()}async respondWithHeaders(runStages,headers){let output;try{output=await runStages()}catch(error){output=flowErrorToHttpOutput(error);if(!output)throw error;this.logger.error("Flow failed",{flow:this.name,name:error instanceof Error?error.name:"UnknownError",message:error instanceof Error?error.message:String(error)})}return output&&withHttpHeaders(output,headers)}async runStages(input,deps,scope,currentContext,sessionKey){const{FlowClass,plan:plan50,name:name51}=this;const contextProviders=new Map([[FRONTMCP_CONTEXT,currentContext]]);for(const[token,value]of currentContext.getContextTokens()){contextProviders.set(token,value)}const views=await this.globalProviders.buildViews(sessionKey,contextProviders);const mergedDeps=new Map(deps);for(const[token,instance]of views.context){mergedDeps.set(token,instance)}const baseStages=this.stages;let stages=baseStages;let ownsStages=false;let orderBase=this.baseStageOrderEnd??=nextStageOrder(baseStages);const hookOwnerId=await FlowClass.resolveHookOwnerId?.(input,scope);const entryClass=await FlowClass.resolveHookEntryClass?.(input,scope);const entryStaticHooks=entryClass?staticHooksFor(this.hooks.getClsHooks(entryClass),name51):[];const initialInjectedHooks=await bindContextHookTargets(this.hooks.getFlowHooksForOwner(name51,hookOwnerId)??[],{sessionKey,contextProviders:mergedDeps,contextSource:this.globalProviders});let contextReady=false;const trace=this.tracesHooks?[]:void 0;const traceObserver=trace&&recordHookTrace(trace);const runHook=({stage,target,metadata},run)=>{const installed=observersOf(currentContext);const observers=traceObserver?[...installed,traceObserver]:installed;if(observers.length===0)return run();const hook={flowName:name51,stage,type:metadata.type,owner:hookOwnerName(metadata),method:metadata.method,target,flowContext:context};return runObservedHook(observers,hook,run,(error,observer)=>this.logObserverFailure(observer,error))};const answer=output=>trace?withHookTrace(output,trace):output;const materializeAndMerge=async(newHooks,opts)=>{if(!newHooks?.length||!contextReady)return;const metas=[];for(const h2 of newHooks){try{metas.push(h2.metadata)}catch(e){this.logger.warn("Ignoring injected hook that failed to materialize",{flow:this.name,error:e instanceof Error?e.message:"Unknown error"})}}if(metas.length){const start=opts?.orderStart??orderBase;if(!ownsStages){stages=cloneStageMap(baseStages);ownsStages=true}mergeHookMetasIntoStageMap(FlowClass,stages,metas,start,runHook);if(opts?.orderStart===void 0)orderBase+=metas.length}};const appendContextHooks=async hooks=>{await materializeAndMerge(hooks)};const context=new FlowClass(this.metadata,input,scope,appendContextHooks,mergedDeps);contextReady=true;await materializeAndMerge(initialInjectedHooks,{orderStart:-1e6});if(ownsStages)orderBase=nextStageOrder(stages);await materializeAndMerge(entryStaticHooks);if(this.loggedHookOrders)this.logHookOrderOnce(this.loggedHookOrders,stages,hookOwnerId,entryClass);let responded;const toStageResult=e=>{if(e instanceof FlowControl){if(e.type==="respond"){responded=e.output;const status=e.output?.status;context.state.set("statusCode",typeof status==="number"?status:void 0)}return{outcome:e.type,control:e}}return{outcome:"unknown_error",control:e}};const hasEntries=key=>(stages[key]?.length??0)>0;const ignoreFinallyThrow=(key,thrown)=>{const description=thrown instanceof FlowControl?`FlowControl '${thrown.type}'`:describeValue2(thrown);this.logger.warn(`Ignored a throw from a Finally hook of '${key}': it cannot change the stage's outcome`,{flow:name51,thrown:description})};const restoreState=before=>{const state=context.state;for(const key of Object.keys(context.state.snapshot())){if(!(key in before))delete state[key]}context.state.set(before)};const runList=async(key,opts)=>{const seen=new Set;while(true){const list=stages[key]??[];let item;for(const entry of list){if(!seen.has(entry)){item=entry;break}}if(!item)break;seen.add(item);const stateBefore=opts?.ignoreThrows?context.state.snapshot():void 0;try{await item.method(context)}catch(e){if(opts?.ignoreThrows){if(stateBefore)restoreState(stateBefore);ignoreFinallyThrow(key,e);continue}if(e instanceof FlowControl&&e.type==="respond"&&opts?.ignoreRespond)continue;return toStageResult(e)}}return{outcome:"ok"}};const runAroundChain=async(stageName,index=0)=>{const around=(stages[stageKeysOf(stageName).around]??[])[index];if(!around)return runList(stageName,{ignoreRespond:false});let innerResult={outcome:"ok"};const next=async()=>{innerResult=await runAroundChain(stageName,index+1);if(innerResult.outcome!=="ok"&&innerResult.outcome!=="respond")throw innerResult.control};try{await around.method(context,next)}catch(e){return toStageResult(e)}return FAILED_OUTCOMES.has(innerResult.outcome)?{outcome:"ok"}:innerResult};const recordFailure=control=>{if(context.state.get("flowError"))return;const failure=control instanceof FlowControl?failureOf(control):control;const flowError=failure instanceof Error?failure:new InternalMcpError(`Flow failed with a non-Error value: ${describeValue2(failure)}`);context.state.set("flowError",flowError)};const runStageSteps=async(stageName,stopOnRespond)=>{const keys=stageKeysOf(stageName);if(hasEntries(keys.will)){const res=await runList(keys.will);if(res.outcome==="respond"&&stopOnRespond)return res;if(res.outcome!=="ok"&&res.outcome!=="respond")return res}const bodyOutcome=hasEntries(keys.around)?await runAroundChain(stageName):await runList(stageName,{ignoreRespond:false});if(bodyOutcome.outcome!=="ok"&&bodyOutcome.outcome!=="respond"){return bodyOutcome}if(hasEntries(keys.did)){const res=await runList(keys.did,{ignoreRespond:true});if(res.outcome!=="ok"&&res.outcome!=="respond")return res}if(bodyOutcome.outcome==="respond")return bodyOutcome;return{outcome:"ok"}};const runOneStage=async(stageName,stopOnRespond)=>{const result=await runStageSteps(stageName,stopOnRespond);if(FAILED_OUTCOMES.has(result.outcome))recordFailure(result.control);const finallyKey=stageKeysOf(stageName).finally;if(hasEntries(finallyKey))await runList(finallyKey,{ignoreThrows:true});return result};const runStageGroup=async(group,stopOnRespond,opts)=>{if(!group||group.length===0)return{outcome:"ok"};for(const base of stageBasesOf(group)){const res=await runOneStage(base,stopOnRespond);if(res.outcome==="respond"){if(stopOnRespond)return res}else if(res.outcome!=="ok"){return res}}return{outcome:"ok"}};const runErrorStage=async()=>{await runStageGroup(plan50.error,false,{ignoreRespond:true})};const runFinalizeStage=async options=>{const res=await runStageGroup(plan50.finalize,false);if(res.outcome==="unknown_error"||res.outcome==="fail"){const finalizeError=res.control??new InternalMcpError("Finalize stage failed");if(options?.suppressErrors){this.scope.logger.error("[FrontMCP] Finalize stage error (suppressed to preserve original error):",finalizeError);return res}throw finalizeError}return res};{const pre=await runStageGroup(plan50.pre,true);this.logger.verbose(`run: PRE completed, outcome=${pre.outcome}`);if(pre.outcome==="respond"){const post=await runStageGroup(plan50.post,false);if(post.outcome==="unknown_error"||post.outcome==="fail"){try{await runErrorStage()}finally{await runFinalizeStage({suppressErrors:true})}throw post.control??new InternalMcpError("Missing control for fail/error outcome")}if(post.outcome==="abort"||post.outcome==="next"||post.outcome==="handled"){await runFinalizeStage({suppressErrors:true});if(!(post.control instanceof FlowControl)){throw new InternalMcpError("Expected FlowControl but received different error type")}throw post.control}await runFinalizeStage();return answer(responded)}if(pre.outcome==="unknown_error"||pre.outcome==="fail"){try{await runErrorStage()}finally{await runFinalizeStage({suppressErrors:true})}throw pre.control??new InternalMcpError("Missing control for fail/error outcome")}if(pre.outcome==="abort"||pre.outcome==="next"||pre.outcome==="handled"){await runFinalizeStage({suppressErrors:true});if(!(pre.control instanceof FlowControl)){throw new InternalMcpError("Expected FlowControl but received different error type")}throw pre.control}}if(!responded){const exec=await runStageGroup(plan50.execute,true);this.logger.verbose(`run: EXECUTE completed, outcome=${exec.outcome}`);if(exec.outcome==="respond"){}else if(exec.outcome==="unknown_error"||exec.outcome==="fail"){try{await runErrorStage()}finally{await runFinalizeStage({suppressErrors:true})}throw exec.control??new InternalMcpError("Missing control for fail/error outcome")}else if(exec.outcome==="abort"||exec.outcome==="next"||exec.outcome==="handled"){await runFinalizeStage({suppressErrors:true});if(!(exec.control instanceof FlowControl)){throw new InternalMcpError("Expected FlowControl but received different error type")}throw exec.control}}{const post=await runStageGroup(plan50.post,false);this.logger.verbose(`run: POST completed, outcome=${post.outcome}`);if(post.outcome==="unknown_error"||post.outcome==="fail"){try{await runErrorStage()}finally{await runFinalizeStage({suppressErrors:true})}throw post.control??new InternalMcpError("Missing control for fail/error outcome")}if(post.outcome==="abort"||post.outcome==="next"||post.outcome==="handled"){await runFinalizeStage({suppressErrors:true});if(!(post.control instanceof FlowControl)){throw new InternalMcpError("Expected FlowControl but received different error type")}throw post.control}}await runFinalizeStage();return answer(responded)}logObserverFailure(observer,error){if(this.failedObservers.has(observer))return;this.failedObservers.add(observer);this.logger.warn("Ignored a throw from a hook observer: the hook ran as it would with no observer",{flow:this.name,error:error instanceof Error?error.message:describeValue2(error)})}logHookOrderOnce(logged,stages,ownerId,entryClass){const entryHooks=entryClass?this.hooks.getClsHooks(entryClass).filter(hook=>hook.metadata.flow===this.name):[];const entryKey=entryHooks.length>0?entryClass:void 0;const loggedEntries=logged.get(ownerId)??new Set;if(loggedEntries.has(entryKey))return;logged.set(ownerId,loggedEntries.add(entryKey));const resolved=cloneStageMap(stages);const instanceHooks=entryHooks.filter(hook=>!hook.metadata.static).map(hook=>hook.metadata);mergeHookMetasIntoStageMap(this.FlowClass,resolved,instanceHooks,nextStageOrder(stages));const contextStage=entryContextStageOf(this.name);const contextStep=contextStage?this.stages[contextStage]?.[0]:void 0;if(contextStage&&contextStep&&resolved[contextStage]){resolved[contextStage]=listJoinedAfterStep(resolved[contextStage],stages[contextStage]??[],contextStep)}const stageNames=FLOW_PHASES.flatMap(phase=>{const group=this.plan[phase];return group?stageBasesOf(group):[]});const lines=describeHookOrder(stageNames,this.stages,resolved,this.FlowClass.name);if(lines.length===0)return;const owner=ownerId===void 0?"":` for '${ownerId}'`;const entry=entryKey===void 0?"":` and ${tokenName10(entryKey)}`;const header2=`Hook order of '${this.name}'${owner}${entry}, lowest priority first (an around hook wraps what its brackets hold):`;this.logger.info([header2,...lines].join("\n"))}}}});import{tokenName as tokenName11}from"@frontmcp/di";import{randomUUID as randomUUID15}from"@frontmcp/utils";var FlowRegistry;var init_flow_registry=__esm({"libs/sdk/src/flows/flow.registry.ts"(){"use strict";init_common();init_context();init_metadata_utils();init_errors();init_regsitry();init_flow_instance();init_flow_utils2();FlowRegistry=class extends RegistryAbstract{constructor(providers,list){super("FlowRegistry",providers,list)}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;for(const raw of list){const rec=normalizeFlow(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);const deps=rec.metadata.dependsOn??[];for(const d of deps){if(d==ScopeEntry){this.graph.get(token).add(ScopeEntry)}else{if(!this.providers.get(d)){throw new RegistryDependencyNotRegisteredError("Flow",tokenName11(token),tokenName11(d))}this.graph.get(token).add(d)}}}}async initialize(){const readyArr=[];for(const token of this.tokens){const instance=this.initializeOne(token);readyArr.push(instance.ready)}await Promise.all(readyArr)}initializeOne(token){const rec=this.defs.get(token);const deps=this.graph.get(token);const instance=new FlowInstance(this.providers.getActiveScope(),rec,deps,this.providers);this.instances.set(rec.metadata.name,instance);return instance}async registryFlows(rawFlows){const readyArr=[];for(const raw of rawFlows){const rec=normalizeFlow(raw);const provide=rec.provide;this.tokens.add(provide);this.defs.set(provide,rec);this.graph.set(provide,new Set);readyArr.push(this.initializeOne(provide).ready)}await Promise.all(readyArr)}runFlow(name51,input,deps){const flow=this.instances.get(name51);if(!flow){throw new FlowNotRegisteredError(name51)}const contextStorage=this.getContextStorage();if(!contextStorage){return flow.run(input,deps??new Map)}const mcpCtx=input?.ctx;const inProcessMetadata=mcpCtx?.metadata;const inProcessPlatformEnv=mcpCtx?.platformEnv;const existingContext=contextStorage.getStore();if(existingContext&&!inProcessMetadata&&inProcessPlatformEnv===void 0){return flow.run(input,deps??new Map)}const scope=this.providers.getActiveScope();const httpRequest=input?.request;if(httpRequest?.headers&&!input.ctx){return Promise.resolve(contextStorage.runForHttpRequest(httpRequest,scope.id,async()=>{return flow.run(input,deps??new Map)}))}const authInfo=mcpCtx?.authInfo;const rawSessionId=authInfo?.sessionId;const sessionId=typeof rawSessionId==="string"&&rawSessionId.trim().length>0?rawSessionId.trim():`anon:${randomUUID15()}`;return Promise.resolve(contextStorage.run({sessionId,scopeId:scope.id,authInfo,...inProcessMetadata?inProcessRequestContext(inProcessMetadata,{forwardsHeader:contextStorage.forwardsHeader}):{},...inProcessPlatformEnv!==void 0?{platformEnv:inProcessPlatformEnv}:{}},async()=>{return flow.run(input,deps??new Map)}))}async findHttpFlowName(request2,exclude=new Set){for(const instance of this.instances.values()){const name51=instance.name;if(exclude.has(name51))continue;if(await instance.matchHttp(request2))return name51}return void 0}getContextStorage(){try{return this.providers.get(FrontMcpContextStorage)}catch{return void 0}}}}});var HookInstance;var init_hook_instance=__esm({"libs/sdk/src/hooks/hook.instance.ts"(){"use strict";init_common();init_errors();HookInstance=class extends HookEntry{logger;constructor(scope,providers,record,token){super(scope,providers,record,token,record.metadata);const{flow,method,stage}=this.metadata;this.logger=scope.logger.child(`${flow}:hook:${stage}(${method})`)}initialize(){return Promise.resolve(void 0)}async run(input,ctx){const{target,method}=this.metadata;if(!target){throw new HookTargetNotDefinedError(method)}this.logger.verbose("start");await target[method](input,ctx);this.logger.verbose("done")}}}});function appliesToOwner(hook,ownerId){const hookOwner=hook.metadata.owner;if(!hookOwner)return true;switch(hookOwner.kind){case"scope":case"plugin":return true;case"app":case"agent":return hookOwner.id===ownerId||hook.metadata.appliesTo==="all-apps";default:throw new UnsupportedHookOwnerKindError(hookOwner.kind)}}function hookClassOf(hook){const{target}=hook.metadata;if(target===null||target===void 0)return void 0;if(hook.metadata.static||typeof target!=="object")return target;return target.constructor}function isSameHook2(a,b){const cls=hookClassOf(a);return cls!==void 0&&cls===hookClassOf(b)&&a.metadata.flow===b.metadata.flow&&a.metadata.method===b.metadata.method}var HookRegistry;var init_hook_registry=__esm({"libs/sdk/src/hooks/hook.registry.ts"(){"use strict";init_errors();init_regsitry();init_hook_instance();HookRegistry=class extends RegistryAbstract{scope;recordsByCls=new Map;entriesByCls=new Map;hooksByFlow=new Map;hooksByFlowStage=new Map;inherited;constructor(providers,list){super("HookRegistry",providers,list);this.scope=this.providers.getActiveScope()}buildMap(){const tokens=new Set;const defs=new Map;const graph=new Map;return{tokens,defs,graph}}buildGraph(){}async initialize(){}getPriority(entry){return entry.metadata?.priority??0}insertSorted(arr,item){const p=this.getPriority(item);let lo=0;let hi=arr.length;while(lo<hi){const mid=lo+hi>>>1;const mp=this.getPriority(arr[mid]);if(mp>p){hi=mid}else{lo=mid+1}}arr.splice(lo,0,item)}upsert(map,key,init){let v=map.get(key);if(!v){v=init();map.set(key,v)}return v}indexByClass(cls,entry){const list=this.upsert(this.entriesByCls,cls,()=>[]);this.insertSorted(list,entry)}indexByFlow(flow,entry){const list=this.upsert(this.hooksByFlow,flow,()=>[]);this.insertSorted(list,entry)}indexByFlowStage(flow,stage,entry){const stages=this.upsert(this.hooksByFlowStage,flow,()=>new Map);const list=this.upsert(stages,String(stage),()=>[]);this.insertSorted(list,entry)}initializeOne(embedded,token){const rec=this.defs.get(token);const providers=this.providers;const instance=new HookInstance(this.scope,providers,rec,token);this.instances.set(token,instance);const cls=rec.metadata.target;if(cls){const recs=this.recordsByCls.get(cls)??[];recs.push(rec);this.recordsByCls.set(cls,recs)}const entry=this.instances.get(token);const{flow,stage,target}=rec.metadata;if(embedded&&target){this.indexByClass(rec.metadata.static?target:target.constructor,entry)}else if(!embedded){this.indexByFlowStage(flow,String(stage),entry);this.indexByFlow(flow,entry)}return instance.ready}registerHooks(embedded,...records){const readyArr=[];for(const record of records){this.defs.set(record.provide,record);this.tokens.add(record.provide);this.graph.set(record.provide,new Set);readyArr.push(this.initializeOne(embedded,record.provide))}return Promise.all(readyArr)}removeHooks(hooks){const removed=new Set(hooks);if(removed.size===0)return;const removedTokens=new Set;for(const[token,entry]of this.instances){if(!removed.has(entry))continue;removedTokens.add(token);this.instances.delete(token);this.defs.delete(token);this.tokens.delete(token);this.graph.delete(token)}const prune=index=>{for(const[key,entries]of index){index.set(key,entries.filter(entry=>!removed.has(entry)))}};prune(this.entriesByCls);prune(this.hooksByFlow);for(const stages of this.hooksByFlowStage.values())prune(stages);for(const[cls,records]of this.recordsByCls){this.recordsByCls.set(cls,records.filter(record=>!removedTokens.has(record.provide)))}}inheritFrom(parent,ownerId){this.inherited={registry:parent,ownerId}}getFlowHooksForOwner(flow,ownerId){const own=this.getOwnFlowHooksForOwner(flow,ownerId);if(!this.inherited)return own;const inherited=this.inherited.registry.getFlowHooksForOwner(flow,this.inherited.ownerId).filter(hook=>!own.some(ownHook=>isSameHook2(ownHook,hook)));if(inherited.length===0)return own;const merged=[...own];for(const hook of inherited)this.insertSorted(merged,hook);return merged}getOwnFlowHooksForOwner(flow,ownerId){const allHooks=this.getFlowHooks(flow);if(!ownerId){return allHooks}const ownHooks=allHooks.filter(hook=>appliesToOwner(hook,ownerId));if(!allHooks.some(hook=>hook.metadata.appliesTo==="uncovered-apps"))return ownHooks;const own=new Set(ownHooks);return allHooks.filter(hook=>own.has(hook)||hook.metadata.appliesTo==="uncovered-apps"&&!ownHooks.some(ownHook=>isSameHook2(ownHook,hook)))}getClsHooks(token){return this.entriesByCls.get(token)??[]}getHooks(){return[...this.instances.values()]}getFlowHooks(flow){return this.hooksByFlow.get(flow)??[]}getFlowStageHooks(flow,stage){const byStage2=this.hooksByFlowStage.get(flow);return byStage2?.get(String(stage))??[]}}}});import{brandClass as brandClass3,isBrandedInstance as isBrandedInstance3}from"@frontmcp/utils";function isDynamicPluginClass(value){return typeof value==="function"&&value.prototype instanceof DynamicPlugin}function initOptionsOf(instance){return initOptionsByInstance.has(instance)?{options:initOptionsByInstance.get(instance)}:void 0}var initOptionsByInstance,DynamicPlugin;var init_dynamic_plugin=__esm({"libs/sdk/src/common/dynamic/dynamic.plugin.ts"(){"use strict";init_transport_errors();init_dynamic_utils();initOptionsByInstance=new WeakMap;DynamicPlugin=class{static[Symbol.hasInstance](value){return isBrandedInstance3(this,value)}get(token){throw new MethodNotImplementedError("DynamicPlugin","get")}static init(options={}){const providersOption=options.providers;const extraProviders=Array.isArray(providersOption)?providersOption:[];const typedOptions=options;if("useFactory"in options){return{...pluginMetadataFromOptions(typedOptions,[]),provide:this,inject:options.inject,useFactory:options.useFactory,providers:dedupePluginProviders(extraProviders)}}const dyn=collectDynamicProviders(this,typedOptions);const mergedProviders=dedupePluginProviders([...dyn??[],...extraProviders]);const dynamicTools=collectDynamicTools(this,typedOptions);const instance=new this(options);initOptionsByInstance.set(instance,options);return{...pluginMetadataFromOptions(typedOptions,dynamicTools),provide:this,useValue:instance,providers:mergedProviders}}};brandClass3(DynamicPlugin,"@frontmcp/sdk:DynamicPlugin")}});function installContextExtensions(pluginName,extensions){for(const ext of extensions){const{property,token,errorMessage:errorMessage2}=ext;if(installedExtensions.has(property)){continue}if(Object.prototype.hasOwnProperty.call(ExecutionContextBase.prototype,property)){console.warn(`[${pluginName}] Context property '${property}' already exists on ExecutionContextBase. Skipping.`);continue}const defaultErrorMessage=errorMessage2??`${pluginName} is not installed or '${property}' is not configured.`;Object.defineProperty(ExecutionContextBase.prototype,property,{get:function(){try{return this.get(token)}catch(err){throw new ContextExtensionNotAvailableError(defaultErrorMessage,err instanceof Error?err:void 0)}},configurable:true,enumerable:false});installedExtensions.add(property)}}var installedExtensions;var init_context_extension=__esm({"libs/sdk/src/context/context-extension.ts"(){"use strict";init_execution_context_interface();init_errors();installedExtensions=new Set}});import{dirname as dirname4,stat}from"@frontmcp/utils";async function findReplaceableDirectory(start){for(let directory=start;;directory=dirname4(directory)){const{mode,uid}=await stat(directory);if(uid!==ROOT_UID&&uid!==process.getuid?.())return{directory,mode,ownerUid:uid};if(mode&GROUP_OR_OTHER_WRITE&&!(mode&STICKY_BIT))return{directory,mode};if(dirname4(directory)===directory)return void 0}}var GROUP_OR_OTHER_WRITE,STICKY_BIT,ROOT_UID;var init_replaceable_directory=__esm({"libs/sdk/src/server/security/replaceable-directory.ts"(){"use strict";GROUP_OR_OTHER_WRITE=18;STICKY_BIT=512;ROOT_UID=0}});import{createChangeFeed,createStorage,getEnv as getEnv8,getRuntimeContext as getRuntimeContext12,lstat,mkdir,realpath,writeFile}from"@frontmcp/utils";async function createQuestionStore(options){const{storage:config,keyPrefix="mcp:questions:",encryption,pollIntervalMs,coalesceMs,logger}=options;const enabled=encryption?.enabled??"auto";const secret=enabled===false?void 0:encryption?.secret??getElicitationSecret()??void 0;if(enabled===true&&!secret){throw new InvalidQuestionStoreError("encryption is on but no secret is set: set MCP_ELICITATION_SECRET (or MCP_SESSION_SECRET / MCP_SERVER_SECRET)")}let storage;try{storage=await createStorage({...config,prefix:keyPrefix,fallback:"error"})}catch(error){throw new InvalidQuestionStoreError(`the ${config.type} store cannot be opened: ${error instanceof Error?error.message:String(error)}`)}const feed=createChangeFeed(storage,{pollIntervalMs,coalesceMs,onError:error=>logger?.warn("Persistent questions: a change notification failed",error)});return{store:new QuestionStore({storage,feed,secret}),type:config.type,encrypted:!!secret,storage}}async function resolveQuestionStorage(sources3){if(sources3.storage)return sources3.storage;const redis=sources3.redis===void 0?void 0:redisOptionsSchema.safeParse(sources3.redis);if(redis?.success&&isRedisProvider(redis.data)){const{host,port,password,db,tls}=redis.data;return{type:"redis",redis:{config:{host,port,password,db,tls}}}}if(sources3.sqlite)return{type:"sqlite",sqlite:sources3.sqlite};const{runtime,deployment}=getRuntimeContext12();if(runtime!=="node"||deployment==="serverless"){throw new InvalidQuestionStoreError("this runtime has no default store for questions: set elicitation.persistent.storage, or the server redis")}const path4=nodePath2();const home=getEnv8("FRONTMCP_HOME")||path4.join(nodeOs2().homedir(),".frontmcp");const file=path4.join(home,"questions.sqlite");await mkdir(home,{recursive:true,mode:OWNER_ONLY_DIRECTORY});if(process.platform!=="win32")await assertNoOtherUserCanReplace(home);await writeFile(file,"",{mode:OWNER_ONLY_FILE,flag:"a"});if(process.platform!=="win32")await assertOwnerOnlyFile(file);return{type:"sqlite",sqlite:{path:file}}}async function assertNoOtherUserCanReplace(home){for(const directory of new Set([home,await realpath(home)])){const replaceable=await findReplaceableDirectory(directory);if(!replaceable)continue;const{ownerUid}=replaceable;const reason=ownerUid===void 0?"the group or others can write to it":`it belongs to another user (uid ${ownerUid})`;throw new InvalidQuestionStoreError(`refusing the default store under ${replaceable.directory}: ${reason}. Set FRONTMCP_HOME to a folder only you can write to, or elicitation.persistent.storage`)}}async function assertOwnerOnlyFile(file){const stats=await lstat(file);const reason=!stats.isFile()?"it is not a regular file":stats.uid!==process.getuid?.()?`it belongs to another user (uid ${stats.uid})`:stats.mode&GROUP_OR_OTHER_ACCESS?"the group or others can read it":void 0;if(reason){throw new InvalidQuestionStoreError(`refusing the default store ${file}: ${reason}; make it owner-only (0600)`)}}function nodeOs2(){return __require("os")}function nodePath2(){return __require("path")}var OWNER_ONLY_DIRECTORY,OWNER_ONLY_FILE,GROUP_OR_OTHER_ACCESS;var init_question_store_factory=__esm({"libs/sdk/src/elicitation/questions/question-store.factory.ts"(){"use strict";init_common();init_replaceable_directory();init_elicitation_encryption();init_question_errors();init_question_store();OWNER_ONLY_DIRECTORY=448;OWNER_ONLY_FILE=384;GROUP_OR_OTHER_ACCESS=63}});var question_scope_helper_exports={};__export(question_scope_helper_exports,{DEFAULT_QUESTION_TTL_MS:()=>DEFAULT_QUESTION_TTL_MS,openPersistentQuestions:()=>openPersistentQuestions,parsePersistentQuestionsOptions:()=>parsePersistentQuestionsOptions,persistentQuestionsSettings:()=>persistentQuestionsSettings,questionsServerStore:()=>questionsServerStore});import{internalZ as z72}from"@frontmcp/lazy-zod";import{sha256Hex as sha256Hex11}from"@frontmcp/utils";function parsePersistentQuestionsOptions(persistent){const parsed=persistentQuestionsOptionsSchema.safeParse(persistent===true?{}:persistent);if(!parsed.success){throw new InvalidQuestionStoreError(parsed.error.issues.map(issue=>issue.message).join("; "))}return{...parsed.data,storage:parsed.data.storage}}function persistentQuestionsSettings(persistent,onEdgeRuntime){const settings=parsePersistentQuestionsOptions(persistent);if(onEdgeRuntime)throw new InvalidQuestionStoreError(NOT_ON_EDGE_RUNTIME);return settings}function questionsServerStore(storage,server){if(storage)return storage.type==="memory"?void 0:"elicitation.persistent.storage";const elicitationRedis=server.elicitation?.redis;const[option,redis]=elicitationRedis?["elicitation.redis",elicitationRedis]:["redis",server.redis];if(redis&&redis.provider!=="vercel-kv")return option;return server.sqlite?"sqlite":"the default questions.sqlite file"}async function openPersistentQuestions(options){const{persistent,serverName="",logger}=options;if(!persistent)return void 0;const settings=persistentQuestionsSettings(persistent,options.onEdgeRuntime??false);const storage=await resolveQuestionStorage({storage:settings.storage,redis:options.redis,sqlite:options.sqlite});const keyPrefix=`mcp:questions:${sha256Hex11(`server:${serverName}`).slice(0,16)}:`;const{store,type,encrypted}=await createQuestionStore({storage,keyPrefix,logger});logger.info("Persistent questions are on",{type,encrypted});return{store,type,ttlMs:settings.ttlMs??DEFAULT_QUESTION_TTL_MS,inboxLinks:settings.inboxLinks??"terminal"}}var DEFAULT_QUESTION_TTL_MS,persistentQuestionsOptionsSchema,NOT_ON_EDGE_RUNTIME;var init_question_scope_helper=__esm({"libs/sdk/src/elicitation/questions/question-scope.helper.ts"(){"use strict";init_question_store_factory();init_question_errors();DEFAULT_QUESTION_TTL_MS=864e5;persistentQuestionsOptionsSchema=z72.object({ttlMs:z72.number({message:"ttlMs must be a number of milliseconds"}).int("ttlMs must be a whole number of milliseconds").positive("ttlMs must be greater than 0").optional(),storage:z72.object({type:z72.enum(["memory","redis","sqlite"],{message:"storage.type must be 'memory', 'redis' or 'sqlite'"})}).passthrough().optional(),inboxLinks:z72.enum(["terminal","stderr","off"],{message:"inboxLinks must be 'terminal', 'stderr' or 'off'"}).optional()},{error:issue=>issue.code==="invalid_type"?"it must be true, false or an object of settings":void 0}).strict();NOT_ON_EDGE_RUNTIME="it is not available on an edge runtime: a question must outlive the isolate that asked it, and none of its stores runs there ('redis' needs a TCP connection, 'sqlite' a local file, and 'memory' ends with the isolate). Run the server on Node.js to keep questions, or turn elicitation.persistent off"}});function completionEventsOf(scope){let events=byScope.get(scope);if(!events){events=new ScopeCompletionEvents;byScope.set(scope,events)}return events}function completionOutputText(value){if(value===void 0)return void 0;if(typeof value==="string")return value;try{return JSON.stringify(value)}catch{return String(value)}}var CompletionStream,ScopeCompletionEvents,byScope;var init_completion_events=__esm({"libs/sdk/src/channel/sources/completion-events.ts"(){"use strict";CompletionStream=class{listeners=new Set;subscribe(listener){this.listeners.add(listener);return()=>{this.listeners.delete(listener)}}emit(event){for(const listener of[...this.listeners]){try{listener(event)}catch{}}}};ScopeCompletionEvents=class{agents=new CompletionStream;jobs=new CompletionStream};byScope=new WeakMap}});import{internalZ as z73}from"@frontmcp/lazy-zod";var ExecuteWorkflowTool;var init_execute_workflow_tool=__esm({"libs/sdk/src/workflow/tools/execute-workflow.tool.ts"(){"use strict";init_common();init_errors();ExecuteWorkflowTool=class extends ToolContext{async execute(input){const scope=this.scope;const executionManager=scope._jobExecutionManager;const workflowRegistry=this.scope.workflows;const jobRegistry=this.scope.jobs;if(!executionManager||!workflowRegistry||!jobRegistry){return this.fail(new Error("Jobs/workflows system is not enabled"))}const workflow=workflowRegistry.findByName(input.name);if(!workflow){return this.fail(new JobNotAuthorizedError(input.name))}const result=await executionManager.executeWorkflow(workflow,jobRegistry,{background:input.background,sessionId:this.authInfo.sessionId,authInfo:this.authInfo,context:this.context,authoritiesContextBuilder:this.scope.authoritiesContextBuilder,workflowInput:input.input});return result}};ExecuteWorkflowTool=__decorateClass([Tool({name:"execute_workflow",description:"Execute a registered workflow by name. Supports inline and background execution.",inputSchema:{name:z73.string().describe("Workflow name to execute"),input:z73.record(z73.string(),z73.unknown()).optional().describe("Workflow input data"),background:z73.boolean().optional().default(false).describe("Run in background (returns runId)")},outputSchema:{runId:z73.string(),state:z73.string(),result:z73.unknown().optional()}})],ExecuteWorkflowTool)}});var JobPermissionGuard;var init_job_permission_guard=__esm({"libs/sdk/src/job/job-permission.guard.ts"(){"use strict";init_principal_utils();JobPermissionGuard=class _JobPermissionGuard{static async check(permissions,action,authInfo,contextBuilder){if(!permissions||permissions.length===0){return true}const relevant=permissions.filter(p=>p.action===action);if(relevant.length===0){return true}const principal=resolvePrincipal(authInfo,contextBuilder);for(const perm of relevant){const passed=await _JobPermissionGuard.checkSingle(perm,principal,authInfo);if(!passed)return false}return true}static async checkSingle(perm,principal,authInfo){if(perm.roles&&perm.roles.length>0){if(!perm.roles.some(role=>principal.roles.includes(role)))return false}if(perm.scopes&&perm.scopes.length>0){if(!perm.scopes.some(scope=>principal.scopes.includes(scope)))return false}if(perm.custom){const result=await perm.custom(authInfo??{});if(!result)return false}return true}}}});function jobRunUri(runId){return`job://runs/${runId}`}function jobExecutionManagerOf(scope){return scope._jobExecutionManager}async function mayAccessRun(scope,record,action,authInfo){const builder=scope.authoritiesContextBuilder;if(record.ownerSub){if(record.ownerSub===resolvePrincipal(authInfo,builder).sub)return true}else if(record.sessionId&&record.sessionId===authInfo["sessionId"]){return true}const permissions=permissionsOfRun(scope,record);if(!permissions?.some(rule=>rule.action===action))return false;return JobPermissionGuard.check(permissions,action,authInfo,builder)}function permissionsOfRun(scope,record){if("workflowName"in record)return scope.workflows?.findByName(record.workflowName)?.metadata.permissions;return scope.jobs?.findByName(record.jobName)?.metadata.permissions}var init_job_run_access=__esm({"libs/sdk/src/job/job-run-access.ts"(){"use strict";init_principal_utils();init_job_permission_guard()}});import{internalZ as z74}from"@frontmcp/lazy-zod";var GetWorkflowStatusTool;var init_get_workflow_status_tool=__esm({"libs/sdk/src/workflow/tools/get-workflow-status.tool.ts"(){"use strict";init_common();init_job_run_access();GetWorkflowStatusTool=class extends ToolContext{async execute(input){const scope=this.scope;const executionManager=scope._jobExecutionManager;if(!executionManager){return this.fail(new Error("Jobs system is not enabled"))}const record=await executionManager.getStatus(input.runId);if(!record||!await mayAccessRun(this.scope,record,"read",this.authInfo)){return this.fail(new Error(`Run "${input.runId}" not found`))}const workflowRecord=record;return{runId:record.runId,workflowName:workflowRecord.workflowName,state:record.state,stepResults:workflowRecord.stepResults,startedAt:record.startedAt,completedAt:record.completedAt}}};GetWorkflowStatusTool=__decorateClass([Tool({name:"get_workflow_status",description:"Get the execution status of a workflow run with per-step results.",inputSchema:{runId:z74.string().describe("Run ID returned from execute_workflow")},outputSchema:{runId:z74.string(),workflowName:z74.string().optional(),state:z74.string(),stepResults:z74.record(z74.string(),z74.object({state:z74.string(),outputs:z74.record(z74.string(),z74.unknown()).optional()})).optional(),startedAt:z74.number(),completedAt:z74.number().optional()}})],GetWorkflowStatusTool)}});import{internalZ as z75}from"@frontmcp/lazy-zod";var ListWorkflowsTool;var init_list_workflows_tool=__esm({"libs/sdk/src/workflow/tools/list-workflows.tool.ts"(){"use strict";init_common();init_job_permission_guard();ListWorkflowsTool=class extends ToolContext{async execute(input){const workflowRegistry=this.scope.workflows;if(!workflowRegistry){return{workflows:[],count:0}}const workflows=workflowRegistry.search(input.query,{tags:input.tags,labels:input.labels});const visible=[];for(const workflow of workflows){if(await this.maySee(workflow))visible.push(workflow)}const mapped=visible.map(w=>({name:w.name,description:w.metadata.description,trigger:w.getTrigger(),stepCount:w.getSteps().length,tags:w.getTags()}));return{workflows:mapped,count:mapped.length}}async maySee(workflow){const permissions=workflow.metadata.permissions;const builder=this.scope.authoritiesContextBuilder;if(!await JobPermissionGuard.check(permissions,"list",this.authInfo,builder))return false;return JobPermissionGuard.check(permissions,"execute",this.authInfo,builder)}};ListWorkflowsTool=__decorateClass([Tool({name:"list_workflows",description:"List registered workflows with optional filtering by tags or labels.",inputSchema:{tags:z75.array(z75.string()).optional().describe("Filter by tags"),labels:z75.record(z75.string(),z75.string()).optional().describe("Filter by labels"),query:z75.string().optional().describe("Search query for name/description")},outputSchema:{workflows:z75.array(z75.object({name:z75.string(),description:z75.string().optional(),trigger:z75.string(),stepCount:z75.number(),tags:z75.array(z75.string()).optional()})),count:z75.number()},hideFromDiscovery:true})],ListWorkflowsTool)}});var WorkflowKind;var init_workflow_record=__esm({"libs/sdk/src/common/records/workflow.record.ts"(){"use strict";WorkflowKind=(WorkflowKind2=>{WorkflowKind2["CLASS_TOKEN"]="CLASS_TOKEN";WorkflowKind2["VALUE"]="VALUE";WorkflowKind2["DYNAMIC"]="DYNAMIC";WorkflowKind2["ESM"]="ESM";WorkflowKind2["REMOTE"]="REMOTE";return WorkflowKind2})(WorkflowKind||{})}});import{internalZ as z76}from"@frontmcp/lazy-zod";var RegisterWorkflowTool;var init_register_workflow_tool=__esm({"libs/sdk/src/workflow/tools/register-workflow.tool.ts"(){"use strict";init_common();init_errors();RegisterWorkflowTool=class extends ToolContext{async execute(input){const workflowRegistry=this.scope.workflows;if(!workflowRegistry){return this.fail(new Error("Workflows system is not enabled"))}if(!this.dynamicRegistrationEnabled()){return this.fail(new DynamicJobRegistrationDisabledError("workflow"))}const existing=workflowRegistry.findByName(input.name);if(existing){return this.fail(new Error(`Workflow "${input.name}" already exists`))}const workflowId=input.name;workflowRegistry.registerDynamic({kind:"DYNAMIC",provide:workflowId,metadata:{id:workflowId,name:input.name,description:input.description,steps:input.steps,trigger:input.trigger??"manual",tags:input.tags},registeredBy:this.authInfo?.["sub"]??"anonymous",registeredAt:Date.now()});return{success:true,workflowId}}dynamicRegistrationEnabled(){const jobs=this.scope.metadata?.jobs;return jobs?.allowDynamicRegistration===true}};RegisterWorkflowTool=__decorateClass([Tool({name:"register_workflow",description:"Register a dynamic workflow with step definitions.",inputSchema:{name:z76.string().describe("Workflow name"),description:z76.string().optional().describe("Workflow description"),steps:z76.array(z76.object({id:z76.string().describe("Step identifier"),jobName:z76.string().describe("Job name to execute"),input:z76.record(z76.string(),z76.unknown()).optional().describe("Static input for the step"),dependsOn:z76.array(z76.string()).optional().describe("Step IDs that must complete first"),continueOnError:z76.boolean().optional().describe("Continue on failure"),timeout:z76.number().optional().describe("Step timeout in ms")})).describe("Workflow step definitions"),trigger:z76.enum(["manual","webhook","event"]).optional().describe("Trigger type"),tags:z76.array(z76.string()).optional().describe("Tags for categorization")},outputSchema:{success:z76.boolean(),workflowId:z76.string()},hideFromDiscovery:true})],RegisterWorkflowTool)}});import{internalZ as z77}from"@frontmcp/lazy-zod";var RemoveWorkflowTool;var init_remove_workflow_tool=__esm({"libs/sdk/src/workflow/tools/remove-workflow.tool.ts"(){"use strict";init_common();init_errors();init_job_permission_guard();RemoveWorkflowTool=class extends ToolContext{async execute(input){const workflowRegistry=this.scope.workflows;if(!workflowRegistry){return this.fail(new Error("Workflows system is not enabled"))}const workflow=workflowRegistry.findByName(input.name);if(!workflow){return this.fail(new JobNotAuthorizedError(input.name))}const allowed=await JobPermissionGuard.check(workflow.metadata.permissions,"delete",this.authInfo,this.scope.authoritiesContextBuilder);if(!allowed){return this.fail(new JobNotAuthorizedError(input.name))}if(!workflow.isDynamic()){return this.fail(new Error(`Workflow "${input.name}" is not dynamic and cannot be removed`))}const removed=workflowRegistry.removeDynamic(input.name);return{success:removed,message:removed?`Workflow "${input.name}" removed`:`Failed to remove workflow "${input.name}"`}}};RemoveWorkflowTool=__decorateClass([Tool({name:"remove_workflow",description:"Remove a dynamic workflow by name.",inputSchema:{name:z77.string().describe("Workflow name to remove")},outputSchema:{success:z77.boolean(),message:z77.string()},hideFromDiscovery:true})],RemoveWorkflowTool)}});var LogTransportInterface,FrontMcpLogger,FRONTMCP_LOGGER;var init_logger_interface=__esm({"libs/sdk/src/common/interfaces/logger.interface.ts"(){"use strict";LogTransportInterface=class{};FrontMcpLogger=class{};FRONTMCP_LOGGER=Symbol.for("frontmcp:LOGGER")}});var WorkflowEmitter;var init_workflow_events=__esm({"libs/sdk/src/workflow/workflow.events.ts"(){"use strict";WorkflowEmitter=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)}}}});var ScopeKind;var init_scope_record=__esm({"libs/sdk/src/common/records/scope.record.ts"(){"use strict";ScopeKind=(ScopeKind2=>{ScopeKind2["SPLIT_BY_APP"]="SPLIT_BY_APP";ScopeKind2["MULTI_APP"]="MULTI_APP";return ScopeKind2})(ScopeKind||{})}});var FlowKind;var init_flow_record=__esm({"libs/sdk/src/common/records/flow.record.ts"(){"use strict";FlowKind=(FlowKind2=>{FlowKind2["CLASS_TOKEN"]="CLASS_TOKEN";return FlowKind2})(FlowKind||{})}});var HookKind;var init_hook_record=__esm({"libs/sdk/src/common/records/hook.record.ts"(){"use strict";HookKind=(HookKind2=>{HookKind2["METHOD_TOKEN"]="METHOD_TOKEN";return HookKind2})(HookKind||{})}});var AppKind;var init_app_record=__esm({"libs/sdk/src/common/records/app.record.ts"(){"use strict";AppKind=(AppKind2=>{AppKind2["LOCAL_CLASS"]="LOCAL_CLASS";AppKind2["REMOTE_VALUE"]="REMOTE_VALUE";AppKind2["LAZY_IMPORT"]="LAZY_IMPORT";return AppKind2})(AppKind||{})}});import{ProviderKind as ProviderKind2}from"@frontmcp/di";var init_provider_record=__esm({"libs/sdk/src/common/records/provider.record.ts"(){"use strict"}});var AuthProviderKind;var init_auth_provider_record=__esm({"libs/sdk/src/common/records/auth-provider.record.ts"(){"use strict";AuthProviderKind=(AuthProviderKind2=>{AuthProviderKind2["CLASS_TOKEN"]="CLASS_TOKEN";AuthProviderKind2["CLASS"]="CLASS";AuthProviderKind2["VALUE"]="VALUE";AuthProviderKind2["FACTORY"]="FACTORY";AuthProviderKind2["PRIMARY"]="PRIMARY";return AuthProviderKind2})(AuthProviderKind||{})}});var PluginKind;var init_plugin_record=__esm({"libs/sdk/src/common/records/plugin.record.ts"(){"use strict";PluginKind=(PluginKind2=>{PluginKind2["CLASS_TOKEN"]="CLASS_TOKEN";PluginKind2["CLASS"]="CLASS";PluginKind2["FACTORY"]="FACTORY";PluginKind2["VALUE"]="VALUE";return PluginKind2})(PluginKind||{})}});var AdapterKind;var init_adapter_record=__esm({"libs/sdk/src/common/records/adapter.record.ts"(){"use strict";AdapterKind=(AdapterKind2=>{AdapterKind2["CLASS_TOKEN"]="CLASS_TOKEN";AdapterKind2["CLASS"]="CLASS";AdapterKind2["VALUE"]="VALUE";AdapterKind2["FACTORY"]="FACTORY";return AdapterKind2})(AdapterKind||{})}});var PromptKind;var init_prompt_record=__esm({"libs/sdk/src/common/records/prompt.record.ts"(){"use strict";PromptKind=(PromptKind2=>{PromptKind2["CLASS_TOKEN"]="CLASS_TOKEN";PromptKind2["FUNCTION"]="FUNCTION";PromptKind2["ESM"]="ESM";PromptKind2["REMOTE"]="REMOTE";return PromptKind2})(PromptKind||{})}});var LoggerKind;var init_logger_record=__esm({"libs/sdk/src/common/records/logger.record.ts"(){"use strict";LoggerKind=(LoggerKind2=>{LoggerKind2["CLASS_TOKEN"]="CLASS_TOKEN";return LoggerKind2})(LoggerKind||{})}});var AgentKind;var init_agent_record=__esm({"libs/sdk/src/common/records/agent.record.ts"(){"use strict";AgentKind=(AgentKind2=>{AgentKind2["CLASS_TOKEN"]="CLASS_TOKEN";AgentKind2["FUNCTION"]="FUNCTION";AgentKind2["VALUE"]="VALUE";AgentKind2["FACTORY"]="FACTORY";AgentKind2["ESM"]="ESM";AgentKind2["REMOTE"]="REMOTE";return AgentKind2})(AgentKind||{})}});var SkillKind;var init_skill_record=__esm({"libs/sdk/src/common/records/skill.record.ts"(){"use strict";SkillKind=(SkillKind2=>{SkillKind2["CLASS_TOKEN"]="CLASS_TOKEN";SkillKind2["VALUE"]="VALUE";SkillKind2["FILE"]="FILE";SkillKind2["ESM"]="ESM";SkillKind2["REMOTE"]="REMOTE";return SkillKind2})(SkillKind||{})}});var JobKind;var init_job_record=__esm({"libs/sdk/src/common/records/job.record.ts"(){"use strict";JobKind=(JobKind2=>{JobKind2["CLASS_TOKEN"]="CLASS_TOKEN";JobKind2["FUNCTION"]="FUNCTION";JobKind2["DYNAMIC"]="DYNAMIC";JobKind2["ESM"]="ESM";JobKind2["REMOTE"]="REMOTE";return JobKind2})(JobKind||{})}});import{ProviderKind as ProviderKind3}from"@frontmcp/di";var init_records=__esm({"libs/sdk/src/common/records/index.ts"(){"use strict";init_scope_record();init_flow_record();init_hook_record();init_app_record();init_provider_record();init_auth_provider_record();init_plugin_record();init_adapter_record();init_tool_record();init_resource_record();init_prompt_record();init_logger_record();init_agent_record();init_skill_record();init_job_record();init_workflow_record();init_channel_record()}});import"reflect-metadata";var BaseEntry;var init_base_entry=__esm({"libs/sdk/src/common/entries/base.entry.ts"(){"use strict";BaseEntry=class{ready;record;token;metadata;constructor(record,token,metadata){this.record=record;this.token=token??record.provide;this.metadata=metadata??record.metadata}}}});var WorkflowEntry;var init_workflow_entry=__esm({"libs/sdk/src/common/entries/workflow.entry.ts"(){"use strict";init_base_entry();WorkflowEntry=class extends BaseEntry{owner;name;fullName;isDynamic(){return this.record.kind==="DYNAMIC"}isHidden(){return this.metadata.hideFromDiscovery===true}getTags(){return this.metadata.tags??[]}getLabels(){return this.metadata.labels??{}}getSteps(){return this.metadata.steps}getTrigger(){return this.metadata.trigger??"manual"}}}});var WorkflowInstance;var init_workflow_instance=__esm({"libs/sdk/src/workflow/workflow.instance.ts"(){"use strict";init_workflow_entry();WorkflowInstance=class extends WorkflowEntry{_providers;scope;hooks;constructor(record,providers,owner){super(record);this.owner=owner;this._providers=providers;this.name=record.metadata.id||record.metadata.name;this.fullName=this.owner.id+":"+this.name;this.scope=this._providers.getActiveScope();this.hooks=this.scope.hooks;this.ready=this.initialize()}async initialize(){return Promise.resolve()}getMetadata(){return this.record.metadata}get providers(){return this._providers}}}});import{getMetadata as getMetadata14,isClass as isClass11}from"@frontmcp/di";function collectWorkflowMetadata(cls){const extended=getMetadata14(extendedWorkflowMetadata,cls);const seed=extended?{...extended}:{};return Object.entries(FrontMcpWorkflowTokens).reduce((metadata,[key,token])=>{const value=getMetadata14(token,cls);if(value!==void 0){return Object.assign(metadata,{[key]:value})}else{return metadata}},seed)}function normalizeWorkflow(item){if(item&&typeof item==="function"&&item[FrontMcpWorkflowTokens.type]==="value-workflow"&&item[FrontMcpWorkflowTokens.metadata]){const metadata=item[FrontMcpWorkflowTokens.metadata];return{kind:"VALUE",provide:Symbol.for(`workflow:${metadata.name}`),metadata}}if(isClass11(item)){const metadata=collectWorkflowMetadata(item);return{kind:"CLASS_TOKEN",provide:item,metadata}}const name51=(item!=null&&typeof item==="object"&&"name"in item?item.name:void 0)??String(item);throw new InvalidEntityError("workflow",name51,"a class or a workflow object")}var init_workflow_utils=__esm({"libs/sdk/src/workflow/workflow.utils.ts"(){"use strict";init_workflow_tokens();init_errors()}});import{tokenName as tokenName12}from"@frontmcp/di";var WorkflowRegistry;var init_workflow_registry=__esm({"libs/sdk/src/workflow/workflow.registry.ts"(){"use strict";init_logger_interface();init_regsitry();init_lineage_utils();init_workflow_events();init_workflow_instance();init_workflow_utils();WorkflowRegistry=class extends RegistryAbstract{owner;localRows=[];dynamicRows=[];byName=new Map;byId=new Map;version=0;emitter=new WorkflowEmitter;logger;constructor(providers,list,owner){super("WorkflowRegistry",providers,list,false);this.owner=owner;try{this.logger=providers.get(FrontMcpLogger)}catch{}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=normalizeWorkflow(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){}async initialize(){for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)continue;const wi=new WorkflowInstance(rec,this.providers,this.owner);this.instances.set(token,wi);const lineage=this.owner?[this.owner]:[];const row=this.makeRow(token,wi,lineage);this.localRows.push(row)}this.reindex();this.bump("reset")}getWorkflows(includeHidden=false){const all=[...this.localRows,...this.dynamicRows].map(r=>r.instance);return all.filter(w=>w.metadata.hideFromDiscovery!==true||includeHidden)}findByName(name51){return this.byName.get(name51)?.instance}findById(id){return this.byId.get(id)?.instance}search(query,opts){let workflows=this.getWorkflows(false);if(query){const q=query.toLowerCase();workflows=workflows.filter(w=>w.name.toLowerCase().includes(q)||(w.metadata.description??"").toLowerCase().includes(q))}if(opts?.tags&&opts.tags.length>0){const filterTags=opts.tags;workflows=workflows.filter(w=>{const tags=w.getTags();return filterTags.some(t=>tags.includes(t))})}if(opts?.labels){const labelEntries=Object.entries(opts.labels);workflows=workflows.filter(w=>{const labels=w.getLabels();return labelEntries.every(([k,v])=>labels[k]===v)})}return workflows}registerDynamic(record){const token=Symbol.for(`workflow:dynamic:${record.provide}`);const existing=this.dynamicRows.findIndex(r=>r.token===token);if(existing!==-1){this.dynamicRows.splice(existing,1)}const wi=new WorkflowInstance(record,this.providers,this.owner);this.instances.set(token,wi);const lineage=this.owner?[this.owner]:[];const row=this.makeRow(token,wi,lineage);this.dynamicRows.push(row);this.reindex();this.bump("added")}removeDynamic(workflowId){const idx=this.dynamicRows.findIndex(r=>r.instance.metadata.id===workflowId||r.instance.name===workflowId);if(idx===-1)return false;const row=this.dynamicRows[idx];this.dynamicRows.splice(idx,1);this.instances.delete(row.token);this.reindex();this.bump("removed");return true}subscribe(opts,cb){if(opts.immediate){cb({kind:"reset",changeScope:"global",version:this.version,snapshot:this.getWorkflows()})}return this.emitter.on(cb)}hasAny(){return this.localRows.length>0||this.dynamicRows.length>0}reindex(){this.byName.clear();this.byId.clear();const effective=[...this.localRows,...this.dynamicRows];for(const r of effective){if(this.byName.has(r.baseName)){this.logger?.warn(`WorkflowRegistry: duplicate workflow name "${r.baseName}" detected during reindex; later entry wins`)}this.byName.set(r.baseName,r);const idKey=r.instance.metadata.id??r.baseName;if(this.byId.has(idKey)){this.logger?.warn(`WorkflowRegistry: duplicate workflow id "${idKey}" detected during reindex; later entry wins`)}this.byId.set(idKey,r)}}bump(kind){const version=++this.version;this.emitter.emit({kind,changeScope:"global",version,snapshot:this.getWorkflows()})}makeRow(token,instance,lineage){const ownerKey=ownerKeyOf(lineage);const baseName=instance.name;const qualifiedName=qualifiedNameOf(lineage,baseName);const qualifiedId=`${ownerKey}:${tokenName12(token)}`;return{token,instance,baseName,lineage,ownerKey,qualifiedName,qualifiedId,source:this}}}}});import{tokenName as tokenName13}from"@frontmcp/di";function lifecycleHooksOf(value){if(typeof value!=="object"||value===null)return void 0;const candidate=value;return HOOK_NAMES.some(name51=>typeof candidate[name51]==="function")?value:void 0}async function bootstrapProvider({token,instance}){try{await instance.onBootstrap?.()}catch(error){throw new ProviderBootstrapError(tokenName13(token),error)}}async function readyProviders(entries,logger){for(const{token,instance}of entries){try{await instance.onReady?.()}catch(error){logger.error(`Provider "${tokenName13(token)}" failed in onReady(): ${messageOf3(error)}`)}}}async function shutdownProviders(entries,timeoutMs,logger){for(const{token,instance}of[...entries].reverse()){const onShutdown=instance.onShutdown;if(typeof onShutdown!=="function")continue;try{if(await outlasts(()=>onShutdown.call(instance),timeoutMs)){logger.warn(`Provider "${tokenName13(token)}" onShutdown() did not finish within ${timeoutMs} ms`)}}catch(error){logger.warn(`Provider "${tokenName13(token)}" failed in onShutdown(): ${messageOf3(error)}`)}}}async function outlasts(run,timeoutMs){let timer;const deadline=new Promise(resolve4=>{timer=setTimeout(()=>resolve4(true),timeoutMs)});try{const finished=Promise.resolve().then(run).then(()=>false);return await Promise.race([finished,deadline])}finally{clearTimeout(timer)}}function messageOf3(error){return error instanceof Error?error.message:String(error)}var DEFAULT_SHUTDOWN_HOOK_TIMEOUT_MS,HOOK_NAMES;var init_provider_lifecycle=__esm({"libs/sdk/src/provider/provider.lifecycle.ts"(){"use strict";init_errors();DEFAULT_SHUTDOWN_HOOK_TIMEOUT_MS=3e3;HOOK_NAMES=["onBootstrap","onReady","onShutdown"]}});import{getHostname}from"@frontmcp/utils";function isLocalWorker(executor){return executor.hostname===void 0||executor.hostname===getHostname()}function isAlive(pid){if(!Number.isFinite(pid)||pid<=0)return false;try{process.kill(pid,0);return true}catch(err){const code=err?.code;if(code==="EPERM")return true;return false}}var init_process_liveness=__esm({"libs/sdk/src/task/helpers/process-liveness.ts"(){"use strict"}});async function runJobAttemptFlow(request2){const{job,context}=request2;const scope=job.providers.getActiveScope();const admission=request2.admission?.slot();const run=()=>scope.runFlowForOutput(EXECUTE_JOB_FLOW,{job,input:request2.input,attempt:request2.attempt,ctx:{authInfo:request2.authInfo,contextProviders:context?void 0:request2.contextProviders,authoritiesContextBuilder:request2.authoritiesContextBuilder,run:request2.run,workflow:request2.workflow,signal:request2.signal,timeoutMs:request2.timeoutMs,admission}});try{const storage=contextStorageOf(scope);if(!context||!storage||storage.getStore()===context)return await run();return await storage.runWithContext(context,run)}finally{admission?.release()}}function willRetryJobAttempt(error,attempt,maxAttempts){if(attempt>=maxAttempts)return false;const cause=error instanceof FlowControl?error.originalError??error:error;return!FINAL_FAILURES.some(failure=>cause instanceof failure)}async function runJobCleanup(job,jobContext,reason,logger){const cleanup=job.metadata.cleanup;if(!cleanup)return;const{run,timeoutMs=DEFAULT_CLEANUP_TIMEOUT_MS}=typeof cleanup==="function"?{run:cleanup}:cleanup;try{if(await outlasts(()=>run(jobContext,reason),timeoutMs)){logger.warn(`cleanup: the ${reason} cleanup did not finish within ${timeoutMs} ms`)}}catch(error){logger.warn(`cleanup: the ${reason} cleanup failed: ${toJobError(error).message}`)}}function interruptReasonOf(reason){if(reason instanceof JobCancelledError)return"cancel";if(reason instanceof JobInterruptedError)return"interrupt";return"timeout"}function untilAborted(work,signal){return new Promise((resolve4,reject)=>{const aborted=()=>reject(signal.reason);if(signal.aborted)aborted();else signal.addEventListener("abort",aborted,{once:true});work.then(resolve4,reject).finally(()=>signal.removeEventListener("abort",aborted))})}function abortableDelay(ms,signal){return new Promise((resolve4,reject)=>{if(signal?.aborted)return reject(signal.reason);const aborted=()=>{clearTimeout(timer);reject(signal?.reason)};const timer=setTimeout(()=>{signal?.removeEventListener("abort",aborted);resolve4()},ms);signal?.addEventListener("abort",aborted,{once:true})})}function retryDelayMs(retry,attempt){const backoffMs=retry.backoffMs??1e3;const backoffMultiplier=retry.backoffMultiplier??2;const maxBackoffMs=retry.maxBackoffMs??6e4;return Math.min(backoffMs*Math.pow(backoffMultiplier,attempt-1),maxBackoffMs)}function toJobError(error){return error instanceof Error?error:new Error(String(error))}function contextStorageOf(scope){try{return scope.providers.get(FrontMcpContextStorage)}catch{return void 0}}var EXECUTE_JOB_FLOW,FINAL_FAILURES,DEFAULT_CLEANUP_TIMEOUT_MS;var init_job_attempt=__esm({"libs/sdk/src/job/job-attempt.ts"(){"use strict";init_common();init_context();init_errors();init_provider_lifecycle();EXECUTE_JOB_FLOW="jobs:execute-job";FINAL_FAILURES=[InvalidOutputError,JobNotAuthorizedError,JobCancelledError,JobInterruptedError,JobAdmissionTimeoutError];DEFAULT_CLEANUP_TIMEOUT_MS=3e3}});var WorkflowStepExecutor;var init_workflow_step_executor=__esm({"libs/sdk/src/workflow/engine/workflow-step.executor.ts"(){"use strict";init_errors();init_workflow_errors();init_job_attempt();WorkflowStepExecutor=class{jobRegistry;logger;extra;constructor(jobRegistry,logger,extra){this.jobRegistry=jobRegistry;this.logger=logger;this.extra=extra}async executeStep(step,input){const job=this.jobRegistry.findByName(step.jobName);if(!job){throw new InvalidEntityError("job",step.jobName,`a registered job (referenced by step "${step.id}")`)}const retryConfig=step.retry??job.metadata.retry??{};const maxAttempts=retryConfig.maxAttempts??3;const timeout=step.timeout??job.metadata.timeout??this.extra.defaultTimeoutMs??3e5;let lastError;for(let attempt=1;attempt<=maxAttempts;attempt++){try{const result=await this.executeWithTimeout(job,step,input,timeout,attempt);return{outputs:result??{},state:"completed"}}catch(err){lastError=toJobError(err);this.logger.warn(`Step "${step.id}" attempt ${attempt}/${maxAttempts} failed: ${lastError.message}`);if(!willRetryJobAttempt(lastError,attempt,maxAttempts))break;await new Promise(resolve4=>setTimeout(resolve4,retryDelayMs(retryConfig,attempt)))}}throw lastError??new Error(`Step "${step.id}" failed after ${maxAttempts} attempts`)}executeWithTimeout(job,step,input,timeout,attempt){const{context,contextProviders,authInfo,authoritiesContextBuilder,workflowName,workflowRunId,admission}=this.extra;const abandon=new AbortController;return new Promise((resolve4,reject)=>{const timer=timeout>0?setTimeout(()=>{const timedOut=new WorkflowJobTimeoutError(job.name,timeout);abandon.abort(timedOut);reject(timedOut)},timeout):void 0;runJobAttemptFlow({job,input,attempt,authInfo,context,contextProviders,authoritiesContextBuilder,workflow:{name:workflowName,stepId:step.id,runId:workflowRunId},signal:abandon.signal,admission}).then(({result})=>{clearTimeout(timer);resolve4(result)}).catch(err=>{clearTimeout(timer);reject(err)})})}}}});import{getAsyncContextMode}from"@frontmcp/utils";var WorkflowEngine;var init_workflow_engine=__esm({"libs/sdk/src/workflow/engine/workflow.engine.ts"(){"use strict";init_workflow_errors();init_workflow_step_executor();WorkflowEngine=class{metadata;stepExecutor;logger;maxConcurrency;constructor(metadata,jobRegistry,logger,extra){this.metadata=metadata;this.logger=logger;this.maxConcurrency=metadata.maxConcurrency??5;this.stepExecutor=new WorkflowStepExecutor(jobRegistry,logger,{...extra,workflowName:extra.workflowName??metadata.name})}async execute(workflowInput){const startedAt=Date.now();const steps=this.metadata.steps;this.validateDag(steps);const stepResults=new Map;const stepsContext={get(alias){const result=stepResults.get(alias);if(!result){throw new WorkflowStepNotFoundError(alias)}return result}};const completed=new Set;const failed=new Set;const skipped=new Set;const allStepIds=new Set(steps.map(s=>s.id));const timeoutMs=this.metadata.timeout??6e5;const deadline=startedAt+timeoutMs;while(completed.size+failed.size+skipped.size<allStepIds.size){if(Date.now()>deadline){throw new WorkflowTimeoutError(this.metadata.name,timeoutMs)}const ready=steps.filter(step=>{if(completed.has(step.id)||failed.has(step.id)||skipped.has(step.id))return false;const deps=step.dependsOn??[];return deps.every(d=>completed.has(d)||skipped.has(d))});if(ready.length===0){const sizeBefore=completed.size+failed.size+skipped.size;const remaining=steps.filter(s=>!completed.has(s.id)&&!failed.has(s.id)&&!skipped.has(s.id));for(const step of remaining){const deps=step.dependsOn??[];const hasFailedDep=deps.some(d=>failed.has(d));if(hasFailedDep){skipped.add(step.id);stepResults.set(step.id,{outputs:{},state:"skipped"});this.logger.info(`Skipping step "${step.id}" due to failed dependency`)}}const sizeAfter=completed.size+failed.size+skipped.size;if(sizeAfter===sizeBefore){for(const step of remaining){skipped.add(step.id);stepResults.set(step.id,{outputs:{},state:"skipped"});this.logger.info(`Skipping step "${step.id}" \u2014 unreachable due to deadlock`)}break}continue}const batch=ready.slice(0,getAsyncContextMode()==="serialized"?1:this.maxConcurrency);await Promise.allSettled(batch.map(async step=>{if(step.condition){try{const shouldRun=step.condition(stepsContext);if(!shouldRun){skipped.add(step.id);stepResults.set(step.id,{outputs:{},state:"skipped"});this.logger.info(`Skipping step "${step.id}" (condition returned false)`);return}}catch(err){this.logger.warn(`Step "${step.id}" condition evaluation failed: ${err}`);skipped.add(step.id);stepResults.set(step.id,{outputs:{},state:"skipped"});return}}try{let input;if(typeof step.input==="function"){input=step.input(stepsContext)}else{input=step.input??workflowInput??{}}const result=await this.stepExecutor.executeStep(step,input);completed.add(step.id);stepResults.set(step.id,result);this.logger.info(`Step "${step.id}" completed successfully`)}catch(err){if(step.continueOnError){completed.add(step.id);stepResults.set(step.id,{outputs:{},state:"failed"});this.logger.warn(`Step "${step.id}" failed but continueOnError=true: ${err}`)}else{failed.add(step.id);stepResults.set(step.id,{outputs:{},state:"failed"});this.logger.error(`Step "${step.id}" failed: ${err}`)}}}))}const completedAt=Date.now();const hasFailed=failed.size>0;const resultRecord={};for(const[k,v]of stepResults){resultRecord[k]=v}return{workflowName:this.metadata.name,state:hasFailed?"failed":"completed",stepResults:resultRecord,startedAt,completedAt}}validateDag(steps){const ids=new Set(steps.map(s=>s.id));if(ids.size!==steps.length){throw new WorkflowDagValidationError("Workflow has duplicate step IDs")}for(const step of steps){for(const dep of step.dependsOn??[]){if(!ids.has(dep)){throw new WorkflowDagValidationError(`Step "${step.id}" depends on unknown step "${dep}"`)}}}const stepMap=new Map(steps.map(s=>[s.id,s]));const visiting=new Set;const visited=new Set;const dfs=id=>{if(visited.has(id))return;if(visiting.has(id)){throw new WorkflowDagValidationError(`Workflow has a cycle involving step "${id}"`)}visiting.add(id);const step=stepMap.get(id);if(!step){throw new WorkflowDagValidationError(`Step "${id}" not found during cycle detection`)}for(const dep of step.dependsOn??[]){dfs(dep)}visiting.delete(id);visited.add(id)};for(const step of steps){dfs(step.id)}}}}});async function jobContextProviders(job,context){const contextDeps=new Map([[FRONTMCP_CONTEXT,context]]);for(const[token,instance]of context.getContextTokens())contextDeps.set(token,instance);const views=await job.providers.buildViews(context.sessionId,contextDeps);return new FlowContextProviders(job.providers,views.context)}function detachedRunContext(context){const runContext=new FrontMcpContext({sessionId:context.sessionId,authInfo:context.authInfo,scopeId:context.scopeId,traceContext:context.traceContext,metadata:context.metadata,config:context.config,platformEnv:context.platformEnv});for(const[token,instance]of context.getContextTokens())runContext.setContextToken(token,instance);return runContext}var init_job_context_providers=__esm({"libs/sdk/src/job/job-context-providers.ts"(){"use strict";init_context();init_flow_context_providers()}});function detachedJobRunId(){return typeof process==="undefined"?void 0:process.env?.[RUN_JOB_ENV_VAR]}function isJobWorker(metadata){return metadata[JOB_WORKER_FLAG]===true}function markEntryServer(config){config[ENTRY_SERVER_FLAG]=true}function isEntryServer(metadata){return metadata[ENTRY_SERVER_FLAG]===true}var JOB_WORKER_MARKER,RUN_JOB_ENV_VAR,JOB_WORKER_FLAG,ENTRY_SERVER_FLAG;var init_detached_job_flag=__esm({"libs/sdk/src/front-mcp/detached-job.flag.ts"(){"use strict";JOB_WORKER_MARKER="frontmcp-job";RUN_JOB_ENV_VAR="FRONTMCP_RUN_JOB_ID";JOB_WORKER_FLAG="__jobWorker";ENTRY_SERVER_FLAG="__entryServer"}});var cli_task_runner_exports={};__export(cli_task_runner_exports,{CliTaskRunner:()=>CliTaskRunner,RUN_TASK_ENV_VAR:()=>RUN_TASK_ENV_VAR,RUN_TASK_SUBCOMMAND:()=>RUN_TASK_SUBCOMMAND,TASK_WORKER_MARKER:()=>TASK_WORKER_MARKER});import{getHostname as getHostname2,spawnOwned}from"@frontmcp/utils";var RUN_TASK_SUBCOMMAND,RUN_TASK_ENV_VAR,TASK_WORKER_MARKER,CliTaskRunner;var init_cli_task_runner=__esm({"libs/sdk/src/task/helpers/cli-task-runner.ts"(){"use strict";init_process_liveness();RUN_TASK_SUBCOMMAND="__run-task";RUN_TASK_ENV_VAR="FRONTMCP_RUN_TASK_ID";TASK_WORKER_MARKER="frontmcp-task";CliTaskRunner=class{constructor(deps){this.deps=deps}deps;kind="cli";async run(record,_context){const{exe,args}=this.resolveCommand();const fullArgs=[...args,RUN_TASK_SUBCOMMAND,record.taskId];this.deps.logger?.info("[CliTaskRunner] spawning detached worker",{taskId:record.taskId,exe,args:fullArgs});const{child}=spawnOwned(exe,fullArgs,{marker:TASK_WORKER_MARKER,detached:true,stdio:"ignore",env:{...process.env,[RUN_TASK_ENV_VAR]:record.taskId}});child.on("error",err=>{this.deps.logger?.error("[CliTaskRunner] worker spawn failed",{taskId:record.taskId,exe,error:err instanceof Error?err.message:String(err)});void this.markBootstrapFailure(record,err instanceof Error?err.message:String(err))});child.unref();if(typeof child.pid!=="number"){const reason="spawn produced no PID";this.deps.logger?.error("[CliTaskRunner] worker spawn failed",{taskId:record.taskId,reason});await this.markBootstrapFailure(record,reason);return}await this.deps.store.update(record.taskId,record.sessionId,{executor:{host:"cli",pid:child.pid,spawnedAt:new Date().toISOString(),hostname:getHostname2()}})}async markBootstrapFailure(record,reason){try{const failed=await this.deps.store.update(record.taskId,record.sessionId,{status:"failed",statusMessage:`Task runner failed to start worker: ${reason}`,outcome:{kind:"error",error:{code:-32603,message:reason}}});if(failed){try{await this.deps.store.publishTerminal(failed)}catch{}}}catch(err){this.deps.logger?.warn?.("[CliTaskRunner] bootstrap-failure bookkeeping write failed",{taskId:record.taskId,error:err instanceof Error?err.message:String(err)})}}async cancel(record){const executor=record.executor;const pid=executor?.pid;if(executor&&!isLocalWorker(executor)){this.deps.logger?.debug?.("[CliTaskRunner] cancel: the worker runs on another host; not signalling it",{taskId:record.taskId,pid,hostname:executor.hostname});return}if(!pid||!isAlive(pid)){this.deps.logger?.debug?.("[CliTaskRunner] cancel: worker already dead",{taskId:record.taskId,pid});return}try{process.kill(pid,"SIGTERM");this.deps.logger?.info("[CliTaskRunner] sent SIGTERM to worker",{taskId:record.taskId,pid})}catch(err){const code=err?.code;if(code!=="ESRCH"){this.deps.logger?.warn("[CliTaskRunner] failed to SIGTERM worker",{taskId:record.taskId,pid,error:err instanceof Error?err.message:String(err)})}}}resolveCommand(){const explicit=this.deps.command;if(explicit)return{exe:explicit.exe,args:[...explicit.args??[]]};const exe=process.argv[0]??"node";const entry=process.argv[1];if(!entry){throw new Error("[CliTaskRunner] cannot resolve worker command: process.argv[1] is empty and no `tasks.cliRunnerCommand` override was set")}if(/\.(ts|tsx|mts|cts)$/i.test(entry)){return{exe:"npx",args:["tsx",entry]}}return{exe,args:[entry]}}}}});import{getRuntimeContext as getRuntimeContext13,spawnOwned as spawnOwned2}from"@frontmcp/utils";function runnerOf(job,serverRunner){return job.metadata.runner??serverRunner??"inline"}function assertRunnersAvailable(jobs,serverRunner,runtime=getRuntimeContext13()){for(const job of jobs){if(runnerOf(job,serverRunner)!=="detached")continue;if(runtime.runtime!=="node"){throw new JobRunnerUnavailableError(job.name,`a detached run needs a process of its own, which the ${runtime.runtime} runtime cannot start`,INLINE_REMEDY)}if(runtime.deployment==="serverless"){throw new JobRunnerUnavailableError(job.name,"a detached run must outlive the server, which a serverless deployment stops or replaces after each request",INLINE_REMEDY)}if(job.metadata.permissions?.some(rule=>rule.action==="execute")){throw new JobRunnerUnavailableError(job.name,"its execute permissions are checked on every attempt, and a detached process never receives the caller credentials","Set runner: 'inline' or 'worker' on the job, or drop its execute permissions")}}}function detachedRunnerCommand(){const[,entry,...args]=process.argv;if(!entry){throw new JobRunnerUnavailableError("detached","the server process has no entry a detached runner can run again","Start the server from its entry (node dist/main.js, frontmcp dev) to run jobs detached")}const ownArgs=args.filter(arg=>!arg.startsWith(OWNER_ARG_PREFIX));const flags=process.execArgv.filter(flag=>!INSPECTOR_FLAG.test(flag));return{command:process.execPath,args:[...flags,entry,...ownArgs]}}function spawnDetachedRunner(runId){const{command,args}=detachedRunnerCommand();const env={...process.env,[RUN_JOB_ENV_VAR]:runId};delete env[RUN_TASK_ENV_VAR];const{child}=spawnOwned2(command,args,{marker:JOB_WORKER_MARKER,detached:true,stdio:"ignore",windowsHide:true,env});child.unref();return child}var OWNER_ARG_PREFIX,INSPECTOR_FLAG,INLINE_REMEDY;var init_job_runner=__esm({"libs/sdk/src/job/runner/job-runner.ts"(){"use strict";init_errors();init_detached_job_flag();init_cli_task_runner();OWNER_ARG_PREFIX="--frontmcp-owner=";INSPECTOR_FLAG=/^--inspect(-brk|-wait)?(=|$)/;INLINE_REMEDY="Set runner: 'inline' (or 'worker') on the job, or run the server where it can start processes"}});var RUNNER_HEARTBEAT_MS,RUNNER_HEARTBEAT_TTL_SECONDS,LatestValueFlusher,RunnerHeartbeat;var init_run_flusher=__esm({"libs/sdk/src/job/runner/run-flusher.ts"(){"use strict";RUNNER_HEARTBEAT_MS=1e3;RUNNER_HEARTBEAT_TTL_SECONDS=30;LatestValueFlusher=class{constructor(write,everyMs,onError=()=>void 0){this.write=write;this.onError=onError;this.timer=setInterval(()=>void this.tick(),everyMs);this.timer.unref?.()}write;onError;pending;inFlight;timer;stopped=false;push(value){if(!this.stopped)this.pending={value}}async flush(){await this.inFlight;await this.tick()}stop(){this.stopped=true;this.pending=void 0;clearInterval(this.timer)}async tick(){if(this.inFlight||!this.pending)return;const{value}=this.pending;this.pending=void 0;this.inFlight=this.write(value).catch(error=>{this.pending??={value};this.onError(error)});try{await this.inFlight}finally{this.inFlight=void 0}}};RunnerHeartbeat=class{constructor(store,runnerId,onError=()=>void 0){this.store=store;this.runnerId=runnerId;this.onError=onError}store;runnerId;onError;holders=0;timer;async hold(){this.holders++;if(this.holders===1&&this.store.touchRunner){this.timer=setInterval(()=>void this.beat(),RUNNER_HEARTBEAT_MS);this.timer.unref?.();await this.beat()}let released=false;return()=>{if(released)return;released=true;this.holders--;if(this.holders===0)clearInterval(this.timer)}}async beat(){try{await this.store.touchRunner?.(this.runnerId,RUNNER_HEARTBEAT_TTL_SECONDS)}catch(error){this.onError(error)}}}}});var FINISHED_JOB_STATES;var init_job_state_interface=__esm({"libs/sdk/src/job/store/job-state.interface.ts"(){"use strict";FINISHED_JOB_STATES=new Set(["completed","failed","cancelled","timed_out","interrupted"])}});import{getHostname as getHostname3,randomUUID as randomUUID16,runRequestExclusive as runRequestExclusive3}from"@frontmcp/utils";function withBackgroundContext(opts,scopeId){if(opts.context)return{...opts,context:detachedRunContext(opts.context)};const sessionFromAuth=opts.authInfo?.["sessionId"];const sessionId=opts.sessionId??(typeof sessionFromAuth==="string"&&sessionFromAuth?sessionFromAuth:void 0);const context=new FrontMcpContext({sessionId:sessionId??`anon:${randomUUID16()}`,scopeId,authInfo:opts.authInfo});return{...opts,context}}function currentPid(){return typeof process==="undefined"?0:process.pid}function cancelledUpdate(reason){return{state:"cancelled",error:{message:reason.message,name:reason.name},completedAt:Date.now()}}function finishedStateOf(error){if(error instanceof JobCancelledError)return"cancelled";if(error instanceof JobInterruptedError)return"interrupted";if(error instanceof JobTimeoutError)return"timed_out";return"failed"}var DEFAULT_JOB_TIMEOUT_MS,DETACHED_FLUSH_MS,DETACHED_BOOT_TTL_SECONDS,DETACHED_WATCH_MS,JobExecutionManager,RunRecorder;var init_job_execution_manager=__esm({"libs/sdk/src/job/execution/job-execution.manager.ts"(){"use strict";init_principal_utils();init_context();init_errors();init_provider_lifecycle();init_process_liveness();init_workflow_engine();init_job_attempt();init_job_context_providers();init_job_permission_guard();init_job_run_access();init_job_runner();init_run_flusher();init_job_state_interface();DEFAULT_JOB_TIMEOUT_MS=3e5;DETACHED_FLUSH_MS=500;DETACHED_BOOT_TTL_SECONDS=60;DETACHED_WATCH_MS=1e3;JobExecutionManager=class{stateStore;logger;notifyFn;scope;options;activeRuns=new Map;runWrites=new Map;heartbeat;watchers=new Map;progressFlushers=new Map;constructor(stateStore,logger,notifyFn,scope,options={}){this.stateStore=stateStore;this.logger=logger;this.notifyFn=notifyFn;this.scope=scope;this.options=options;this.heartbeat=new RunnerHeartbeat(stateStore,randomUUID16(),error=>this.logger.warn(`Could not renew this server's job heartbeat: ${toJobError(error).message}`))}async executeJob(job,input,opts={}){await this.assertMayExecute(job.metadata.permissions,job.name,opts);const runId=randomUUID16();const retryConfig=job.metadata.retry??{};const maxAttempts=retryConfig.maxAttempts??1;const runner=runnerOf(job,this.options.runner);const runRecord={runId,jobId:job.metadata.id??job.name,jobName:job.name,sessionId:opts.sessionId,ownerSub:resolvePrincipal(opts.authInfo,opts.authoritiesContextBuilder).sub||void 0,state:"pending",input,startedAt:Date.now(),attempt:1,maxAttempts,logs:[],background:runner==="detached"||(opts.background??false),scopeId:this.scope?.id};if(runner==="detached")return this.startDetached(job,runRecord);const release=await this.heartbeat.hold();try{await this.stateStore.createRun({...runRecord,runner:this.ownRunner(runner)})}catch(error){release();throw error}if(opts.background){const runOpts=withBackgroundContext(opts,(this.scope??job.providers.getActiveScope()).id);void runRequestExclusive3(()=>this.executeJobBackground(job,input,runId,runOpts)).catch(async err=>{this.logger.error(`Background job execution failed: ${err}`);try{await this.updateState(runId,{state:"failed",error:{message:err?.message??String(err),name:err?.name??"Error"},completedAt:Date.now()})}catch(updateErr){this.logger.error(`Failed to update run state after error: ${updateErr}`)}}).finally(release);return{runId,state:"pending"}}try{return await this.executeJobInline(job,input,runId,opts)}finally{release()}}async executeWorkflow(workflow,jobRegistry,opts={}){await this.assertMayExecute(workflow.metadata.permissions,workflow.name,opts);const runId=randomUUID16();const runRecord={runId,jobId:workflow.metadata.id??workflow.name,jobName:workflow.name,workflowName:workflow.name,sessionId:opts.sessionId,ownerSub:resolvePrincipal(opts.authInfo,opts.authoritiesContextBuilder).sub||void 0,state:"pending",input:opts.workflowInput,startedAt:Date.now(),attempt:1,maxAttempts:1,logs:[],background:opts.background??false,stepResults:{}};await this.stateStore.createRun(runRecord);if(opts.background){const runOpts=withBackgroundContext(opts,(this.scope??workflow.providers.getActiveScope()).id);runRequestExclusive3(()=>this.executeWorkflowBackground(workflow,jobRegistry,runId,runOpts)).catch(async err=>{this.logger.error(`Background workflow execution failed: ${err}`);try{await this.updateState(runId,{state:"failed",error:{message:err?.message??String(err),name:err?.name??"Error"},completedAt:Date.now()})}catch(updateErr){this.logger.error(`Failed to update run state after error: ${updateErr}`)}});return{runId,state:"pending"}}return this.executeWorkflowInline(workflow,jobRegistry,runId,opts)}async assertMayExecute(permissions,name51,opts){const allowed=await JobPermissionGuard.check(permissions,"execute",opts.authInfo,opts.authoritiesContextBuilder);if(!allowed){this.logger.warn(`Execution of "${name51}" denied: caller does not satisfy its execute permissions`);throw new JobNotAuthorizedError(name51)}}async getStatus(runId){return this.stateStore.getRun(runId)}async cancel(runId){const reason=new JobCancelledError(runId);await this.withRunLock(runId,async()=>{const record=await this.stateStore.getRun(runId);if(!record)throw new JobRunNotFoundError(runId);if("workflowName"in record)throw new JobRunNotCancellableError(runId);if(FINISHED_JOB_STATES.has(record.state))throw new JobRunFinishedError(runId,record.state);await this.stateStore.requestCancel?.(runId);await this.write(runId,cancelledUpdate(reason))});this.activeRuns.get(runId)?.controller.abort(reason)}async dispose(timeoutMs){for(const watch of this.watchers.values())clearInterval(watch);this.watchers.clear();const runs=[...this.activeRuns.entries()];for(const[runId,run]of runs)run.controller.abort(new JobInterruptedError(runId));const ended=()=>Promise.all(runs.map(([,run])=>run.settled));if(timeoutMs===void 0){await ended()}else if(await outlasts(ended,timeoutMs)){this.logger.warn(`The interrupted job runs did not end within ${timeoutMs} ms`)}}async reconcile(){for(const record of await this.stateStore.listRuns()){if(FINISHED_JOB_STATES.has(record.state)||!record.runner)continue;if(this.scope&&record.scopeId!==void 0&&record.scopeId!==this.scope.id)continue;if(await this.runnerGone(record.runner,record.startedAt))await this.endOrphan(record);else if(record.runner.kind==="detached")this.watch(record.runId)}}async runDetached(runId){const record=await this.stateStore.getRun(runId);if(!record?.runner||FINISHED_JOB_STATES.has(record.state))return;const job=this.options.findJob?.(record.jobName);if(!job){await this.failToBoot(record,`the server has no job named "${record.jobName}"`);return}const warn=error=>this.logger.warn(`Detached run ${runId}: ${toJobError(error).message}`);const release=await new RunnerHeartbeat(this.stateStore,record.runner.id,warn).hold();const flusher=new LatestValueFlusher(progress=>this.updateState(runId,{progress}),DETACHED_FLUSH_MS,warn);this.progressFlushers.set(runId,flusher);try{await this.updateState(runId,{runner:{...record.runner,pid:currentPid(),hostname:getHostname3()}});const scopeId=this.scope?.id??job.providers.getActiveScope().id;const opts=withBackgroundContext({sessionId:record.sessionId,authInfo:{}},scopeId);await this.executeJobInline(job,record.input,runId,opts).catch(()=>void 0)}finally{flusher.stop();this.progressFlushers.delete(runId);release()}}async listRuns(opts){return this.stateStore.listRuns(opts)}async startDetached(job,record){const unavailable=this.options.detachedUnavailable;if(unavailable)throw new JobRunnerUnavailableError(job.name,unavailable.why,unavailable.remedy);const runner={kind:"detached",id:randomUUID16(),pid:0,hostname:getHostname3()};await this.stateStore.touchRunner?.(runner.id,DETACHED_BOOT_TTL_SECONDS);const child=(this.options.spawnDetached??spawnDetachedRunner)(record.runId);const created=this.stateStore.createRun({...record,runner:{...runner,pid:child.pid??0}});child.once("error",error=>{void created.then(()=>this.failToBoot(record,error.message),()=>void 0)});await created;this.watch(record.runId);return{runId:record.runId,state:"pending"}}watch(runId){if(this.watchers.has(runId))return;let revision;let reading=false;const timer=setInterval(async()=>{if(reading)return;reading=true;try{const record=await this.stateStore.getRun(runId);if(record&&record.revision!==revision){revision=record.revision;this.scope?.resources.notifyContentChanged(jobRunUri(runId))}if(!record||FINISHED_JOB_STATES.has(record.state)){this.unwatch(runId);if(record)await this.notify({type:"job:status",runId,state:record.state,jobName:record.jobName})}else if(record.runner&&await this.runnerGone(record.runner,record.startedAt)){this.unwatch(runId);await this.endOrphan(record)}}catch(error){this.logger.warn(`Could not read detached run ${runId}: ${toJobError(error).message}`)}finally{reading=false}},DETACHED_WATCH_MS);timer.unref?.();this.watchers.set(runId,timer)}unwatch(runId){clearInterval(this.watchers.get(runId));this.watchers.delete(runId)}async runnerGone(runner,startedAt){if(runner.hostname!==void 0&&runner.hostname===getHostname3()){return runner.pid===currentPid()?startedAt<performance.timeOrigin:!isAlive(runner.pid)}if(!this.stateStore.isRunnerAlive)return false;return!await this.stateStore.isRunnerAlive(runner.id)}async endOrphan(listed){const{runId}=listed;if(this.stateStore.claimRun&&!await this.stateStore.claimRun(runId))return;const record=await this.stateStore.getRun(runId)??listed;const neverStarted=record.state==="pending"&&record.runner?.kind==="detached";const error=neverStarted?new JobRunnerBootError(runId,"its process exited before it took the run over"):new JobInterruptedError(runId,"its runner is gone");const state=await this.endRun(record,error);if(state&&record.state==="running"){await this.cleanupOrphan(record,state==="cancelled"?"cancel":"interrupt")}}async endRun(record,error){const{runId}=record;const state=await this.withRunLock(runId,async()=>{const current=await this.stateStore.getRun(runId);if(!current||FINISHED_JOB_STATES.has(current.state))return void 0;return this.writeOutcome(runId,{state:"failed",attempt:current.attempt,error})});if(!state)return void 0;this.unwatch(runId);await this.notify({type:"job:status",runId,state,jobName:record.jobName});return state}async cleanupOrphan(record,reason){const job=this.options.findJob?.(record.jobName);if(!job?.metadata.cleanup)return;try{const scopeId=this.scope?.id??job.providers.getActiveScope().id;const{context}=withBackgroundContext({sessionId:record.sessionId,authInfo:{}},scopeId);const contextProviders=context?await jobContextProviders(job,context):void 0;const instance=job.create(job.parseInput(record.input),{authInfo:{},contextProviders,attempt:record.attempt});await runJobCleanup(job,instance,reason,this.logger)}catch(error){this.logger.warn(`The ${reason} cleanup of run ${record.runId} could not run: ${toJobError(error).message}`)}}async failToBoot(record,cause){try{await this.endRun(record,new JobRunnerBootError(record.runId,cause))}catch(error){this.logger.error(`Could not record that run ${record.runId} did not start: ${toJobError(error).message}`)}}ownRunner(kind){return{kind,id:this.heartbeat.runnerId,pid:currentPid(),hostname:getHostname3()}}async executeJobInline(job,input,runId,opts){const{signal,end}=this.startRun(runId);try{return await this.runJobAttempts(job,input,runId,opts,signal)}finally{end()}}startRun(runId){const controller=new AbortController;let settle=()=>void 0;const settled=new Promise(resolve4=>settle=resolve4);const{cancelPollMs}=this.options;const watch=cancelPollMs?setInterval(()=>void this.abortIfEnded(runId,controller),cancelPollMs):void 0;watch?.unref?.();this.activeRuns.set(runId,{controller,settled});const end=()=>{clearInterval(watch);this.activeRuns.delete(runId);settle()};return{signal:controller.signal,end}}async abortIfEnded(runId,controller){try{if(await this.cancelRequested(runId)){controller.abort(new JobCancelledError(runId))}else if(FINISHED_JOB_STATES.has((await this.stateStore.getRun(runId))?.state??"pending")){controller.abort(new JobInterruptedError(runId,"another process ended it"))}}catch(error){this.logger.warn(`Could not read whether run ${runId} was cancelled or ended: ${toJobError(error).message}`)}}async runJobAttempts(job,input,runId,opts,signal){const started=await this.withRunLock(runId,async()=>{if(await this.cancelRequested(runId))return false;await this.write(runId,{state:"running"});return true});if(!started){await this.notify({type:"job:status",runId,state:"cancelled",jobName:job.name});throw new JobCancelledError(runId)}await this.notify({type:"job:status",runId,state:"running",jobName:job.name});const retryConfig=job.metadata.retry??{};const maxAttempts=retryConfig.maxAttempts??1;const timeoutMs=job.metadata.timeout??this.options.defaultTimeoutMs??DEFAULT_JOB_TIMEOUT_MS;const run=new RunRecorder(runId,maxAttempts,outcome=>this.recordAttempt(job,runId,outcome),progress=>this.recordProgress(runId,progress));for(let attempt=1;;attempt++){let answer;try{answer=await runJobAttemptFlow({job,input,attempt,authInfo:opts.authInfo??{},context:opts.context,contextProviders:opts.contextProviders,authoritiesContextBuilder:opts.authoritiesContextBuilder,run,signal,timeoutMs,admission:this.options.admission})}catch(err){const error=toJobError(err);const retry=willRetryJobAttempt(error,attempt,maxAttempts);await run.ensureRecorded({state:retry?"retrying":"failed",attempt,error});if(!retry)throw error;try{await abortableDelay(retryDelayMs(retryConfig,attempt),signal)}catch(stopped){const stoppedError=toJobError(stopped);await run.recordAttempt({state:"failed",attempt,error:stoppedError});throw stoppedError}continue}const{result,logs}=answer;await run.ensureRecorded({state:"completed",attempt,result,logs});return{runId,result,state:"completed",logs:[...logs]}}}async recordProgress(runId,progress){const flusher=this.progressFlushers.get(runId);if(flusher)flusher.push(progress);else await this.updateState(runId,{progress})}async recordAttempt(job,runId,outcome){await this.progressFlushers.get(runId)?.flush();const state=await this.withRunLock(runId,()=>this.writeOutcome(runId,outcome));if(!state)return;const attempt=state==="retrying"?{attempt:outcome.attempt}:{};await this.notify({type:"job:status",runId,state,jobName:job.name,...attempt})}async writeOutcome(runId,outcome){if(await this.cancelRequested(runId)){if(outcome.state==="retrying")return void 0;await this.write(runId,{...cancelledUpdate(new JobCancelledError(runId)),attempt:outcome.attempt});return"cancelled"}const current=await this.stateStore.getRun(runId);if(current&&FINISHED_JOB_STATES.has(current.state))return void 0;switch(outcome.state){case"completed":await this.write(runId,{state:"completed",result:outcome.result,completedAt:Date.now(),attempt:outcome.attempt,logs:[...outcome.logs]});return"completed";case"retrying":await this.write(runId,{state:"retrying",attempt:outcome.attempt});return"retrying";case"failed":{const{error}=outcome;const state=finishedStateOf(error);await this.write(runId,{state,error:{message:error.message,name:error.name,stack:error.stack},completedAt:Date.now(),attempt:outcome.attempt});return state}}}async executeJobBackground(job,input,runId,opts){try{await this.executeJobInline(job,input,runId,opts)}catch{}}async executeWorkflowInline(workflow,jobRegistry,runId,opts){await this.updateState(runId,{state:"running"});await this.notify({type:"workflow:status",runId,state:"running",workflowName:workflow.name});try{const engine=new WorkflowEngine(workflow.metadata,jobRegistry,this.logger,{authInfo:opts.authInfo??{},contextProviders:opts.contextProviders,context:opts.context,authoritiesContextBuilder:opts.authoritiesContextBuilder,workflowRunId:runId,admission:this.options.admission,defaultTimeoutMs:this.options.defaultTimeoutMs});const result=await engine.execute(opts.workflowInput);await this.updateState(runId,{state:result.state==="completed"?"completed":"failed",result,completedAt:Date.now()});await this.notify({type:"workflow:status",runId,state:result.state==="completed"?"completed":"failed",workflowName:workflow.name});return{runId,result,state:result.state==="completed"?"completed":"failed",logs:[]}}catch(err){const error=err instanceof Error?err:new Error(String(err));await this.updateState(runId,{state:"failed",error:{message:error.message,name:error.name,stack:error.stack},completedAt:Date.now()});await this.notify({type:"workflow:status",runId,state:"failed",workflowName:workflow.name});throw error}}async executeWorkflowBackground(workflow,jobRegistry,runId,opts){try{await this.executeWorkflowInline(workflow,jobRegistry,runId,opts)}catch{}}updateState(runId,updates){return this.withRunLock(runId,()=>this.write(runId,updates))}async write(runId,updates){await this.stateStore.updateRun(runId,updates);this.scope?.resources.notifyContentChanged(jobRunUri(runId))}withRunLock(runId,task){const queued=(this.runWrites.get(runId)??Promise.resolve()).then(task);const done=queued.catch(()=>void 0);this.runWrites.set(runId,done);void done.then(()=>{if(this.runWrites.get(runId)===done)this.runWrites.delete(runId)});return queued}async cancelRequested(runId){if(this.stateStore.isCancelRequested)return this.stateStore.isCancelRequested(runId);return(await this.stateStore.getRun(runId))?.state==="cancelled"}async notify(data){if(this.notifyFn){try{await this.notifyFn(data)}catch(err){this.logger.warn(`Failed to send notification: ${err}`)}}}};RunRecorder=class{constructor(runId,maxAttempts,write,writeProgress){this.runId=runId;this.maxAttempts=maxAttempts;this.write=write;this.writeProgress=writeProgress}runId;maxAttempts;write;writeProgress;recorded=new Set;finished=false;async recordProgress(progress){if(!this.finished)await this.writeProgress(progress)}async recordAttempt(outcome){if(outcome.state!=="retrying")this.finished=true;await this.write(outcome);this.recorded.add(outcome.attempt)}async ensureRecorded(outcome){if(!this.recorded.has(outcome.attempt))await this.recordAttempt(outcome)}}}});import{toJSONSchema as toJSONSchema4,internalZ as z78}from"@frontmcp/lazy-zod";var JobEntry;var init_job_entry=__esm({"libs/sdk/src/common/entries/job.entry.ts"(){"use strict";init_base_entry();JobEntry=class extends BaseEntry{owner;name;fullName;inputSchema;outputSchema;isDynamic(){return this.record.kind==="DYNAMIC"}isHidden(){return this.metadata.hideFromDiscovery===true}getTags(){return this.metadata.tags??[]}getLabels(){return this.metadata.labels??{}}getInputJsonSchema(){if(this.inputSchema&&Object.keys(this.inputSchema).length>0){try{return toJSONSchema4(z78.object(this.inputSchema))}catch{return{type:"object",properties:{}}}}return null}getOutputJsonSchema(){const outSchema=this.outputSchema;if(!outSchema)return null;try{if(outSchema instanceof z78.ZodType){return toJSONSchema4(outSchema)}if(outSchema&&typeof outSchema==="object"){if(Object.keys(outSchema).length===0)return null;return toJSONSchema4(z78.object(outSchema))}}catch{return{type:"object",properties:{}}}return null}}}});var JobContext;var init_job_interface=__esm({"libs/sdk/src/common/interfaces/job.interface.ts"(){"use strict";init_execution_context_interface();init_flow_interface();JobContext=class extends ExecutionContextBase{jobId;jobName;metadata;_input;_output;_attempt;_logs=[];onProgress;constructor(args){const{metadata,input,providers,logger,attempt,signal,onProgress}=args;super({providers,logger:logger.child(`job:${metadata.id??metadata.name}`),authInfo:args.authInfo,signal});this.jobName=metadata.name;this.jobId=metadata.id??metadata.name;this.metadata=metadata;this._input=input;this._attempt=attempt;this.onProgress=onProgress}fetch(input,init){const context=this.fetchContext(init);if(context&&this.signal)return context.fetch(input,init,this.signal);return super.fetch(input,init)}get input(){return this._input}get output(){return this._output}set output(v){this._output=v}get attempt(){return this._attempt}log(message){this._logs.push(`[${new Date().toISOString()}] ${message}`);this.logger.info(message)}async progress(pct,total,msg){const recorded=this.onProgress?await this.recordProgress({progress:pct,total,message:msg}):false;const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.debug("Cannot send progress: no session ID");return recorded}const sent=await this.scope.notifications.sendProgressNotification(sessionId,this.jobId,pct,total,msg);return sent||recorded}async recordProgress(progress){try{await this.onProgress?.(progress);return true}catch(error){this.logger.warn(`Could not record progress on the run: ${error instanceof Error?error.message:String(error)}`);return false}}respond(value){this._output=value;FlowControl.respond(value)}getLogs(){return this._logs}keepLogs(lines){this._logs.push(...lines)}callToolSurface(){return"job"}}}});var worker_job_runner_exports={};__export(worker_job_runner_exports,{runWorkerJob:()=>runWorkerJob});import{isClass as isClass12}from"@frontmcp/di";async function runWorkerJob(target,metadata,input,attempt,log,progress){const args={metadata,input,attempt,providers:new WorkerProviders(`job "${metadata.name}" runs in a worker thread (runner: 'worker')`),logger:workerLogger(log),authInfo:{},onProgress:async reported=>progress(reported)};const context=isClass12(target)?new target(args):new WorkerFunctionJobContext(target,args);try{return{output:await context.execute(input),logs:[...context.getLogs()]}}catch(error){if(!(error instanceof FlowControl))throw error;if(error.type==="respond")return{output:error.output,logs:[...context.getLogs()]};const original=Reflect.get(error,"originalError");throw original??new Error(`The job ended with ${error.type}`)}}var WorkerFunctionJobContext;var init_worker_job_runner=__esm({"libs/sdk/src/offload/worker-job.runner.ts"(){"use strict";init_flow_interface();init_job_interface();init_worker_resource_reader();WorkerFunctionJobContext=class extends JobContext{constructor(handler,args){super(args);this.handler=handler}handler;async execute(input){return this.handler(input,this)}}}});function registerWorkerJob(target,metadata,file){const key=workerJobKey(file??"",metadata.name);sources2.set(target,{file,name:metadata.name,key});if(!file)return;workerJobRunners().set(key,{run:async(input,attempt,log,progress)=>{const{runWorkerJob:runWorkerJob2}=await Promise.resolve().then(()=>(init_worker_job_runner(),worker_job_runner_exports));return runWorkerJob2(target,metadata,input,attempt,log,progress)}})}function workerJobSourceOf(target){return typeof target==="function"?sources2.get(target):void 0}var sources2;var init_worker_jobs=__esm({"libs/sdk/src/offload/worker-jobs.ts"(){"use strict";init_offload_worker_globals();sources2=new WeakMap}});var run_job_in_worker_exports={};__export(run_job_in_worker_exports,{runJobInWorker:()=>runJobInWorker});async function runJobInWorker(jobContext,job,input,signal){const name51=job.metadata.name;const source=workerJobSourceOf(job.record.provide);if(!source?.file){throw new InvalidOffloadCallError(`job "${name51}" runs on the worker runner, but the module that declares it was not found on the call stack, so no worker can import it (a bundle that inlines @frontmcp/sdk has no separate module to import)`)}const progress=new LatestValueFlusher(async reported=>{await jobContext.progress(reported.progress,reported.total,reported.message)},PROGRESS_FLUSH_MS);try{const answer=await jobContext.get(OffloadService).run({kind:"job",file:source.file,key:source.key,name:source.name,input,attempt:jobContext.attempt},{label:name51,budgetMs:MAX_TIMER_MS2,signal,logger:jobContext.scope.logger.child(`job:${name51}`),onProgress:reported=>progress.push(reported)});await progress.flush();jobContext.keepLogs(answer.logs);return answer.output}finally{progress.stop()}}var MAX_TIMER_MS2,PROGRESS_FLUSH_MS;var init_run_job_in_worker=__esm({"libs/sdk/src/offload/run-job-in-worker.ts"(){"use strict";init_offload_errors();init_run_flusher();init_offload_service();init_worker_jobs();MAX_TIMER_MS2=2147483647;PROGRESS_FLUSH_MS=500}});import{internalZ as z79}from"@frontmcp/lazy-zod";function jobOf(rawInput){const job=rawInput?.job;return job instanceof JobEntry?job:void 0}function abortControllerFollowing(signal){const controller=new AbortController;if(signal?.aborted)controller.abort(signal.reason);signal?.addEventListener("abort",()=>controller.abort(signal.reason),{once:true});return controller}function progressUntilAborted(run,signal){const record=run?.recordProgress?.bind(run);if(!record)return void 0;return async progress=>{if(!signal.aborted)await record(progress)}}var jobEntrySchema,workflowStepSchema2,inputSchema10,outputSchema10,stateSchema10,plan10,name10,jobClassHooksJoin,Stage10,ExecuteJobFlow;var init_execute_job_flow=__esm({"libs/sdk/src/job/flows/execute-job.flow.ts"(){"use strict";init_common();init_job_entry();init_job_interface();init_call_surface();init_errors();init_entry_class_hooks();init_hooks_utils();init_job_attempt();init_job_context_providers();init_job_permission_guard();init_job_runner();jobEntrySchema=z79.custom(value=>value instanceof JobEntry,{message:"Expected a job entry"});workflowStepSchema2=z79.object({name:z79.string().optional(),stepId:z79.string(),runId:z79.string().optional()});inputSchema10=z79.object({job:jobEntrySchema,input:z79.unknown(),attempt:z79.number().int().min(1),ctx:z79.object({authInfo:z79.record(z79.string(),z79.unknown()),contextProviders:z79.unknown().optional(),authoritiesContextBuilder:z79.custom().optional(),run:z79.custom().optional(),workflow:workflowStepSchema2.optional(),signal:z79.instanceof(AbortSignal).optional(),timeoutMs:z79.number().int().nonnegative().optional(),admission:z79.custom().optional()})});outputSchema10=z79.object({result:z79.unknown(),logs:z79.array(z79.string())});stateSchema10=z79.object({job:jobEntrySchema,attempt:z79.number(),runId:z79.string().optional(),workflow:workflowStepSchema2.optional(),authInfo:z79.record(z79.string(),z79.unknown()),input:z79.unknown(),parsedInput:z79.custom(),jobContext:z79.instanceof(JobContext),attemptAbort:z79.instanceof(AbortController),output:z79.custom(),answer:outputSchema10,flowError:z79.instanceof(Error)});plan10={pre:["parseInput","checkJobAuthorization","validateInput","admit","createJobContext"],execute:["execute","validateOutput"],error:["cleanup"],finalize:["updateRunState","finalize"]};name10=EXECUTE_JOB_FLOW;jobClassHooksJoin=entryClassHooksJoin({flow:name10,plan:plan10,contextStage:"createJobContext"});({Stage:Stage10}=FlowHooksOf(name10));ExecuteJobFlow=class extends FlowBase{static resolveHookOwnerId(rawInput,scope){const job=jobOf(rawInput);if(!job)return void 0;return scope.apps.getApps().find(app=>app.providers===job.providers)?.id}static resolveHookEntryClass(rawInput){return jobOf(rawInput)?.record.provide}logger=this.scopeLogger.child("ExecuteJobFlow");async parseInput(){const{job,input,attempt,ctx}=this.input;this.state.set({job,input,attempt,runId:ctx.run?.runId,workflow:ctx.workflow,authInfo:ctx.authInfo});this.logger=this.logger.child(`ExecuteJobFlow(${job.name})`);this.logger.verbose(`parseInput: attempt ${attempt}`)}async checkJobAuthorization(){const{job}=this.state.required;const allowed=await JobPermissionGuard.check(job.metadata.permissions,"execute",this.state.authInfo,this.input.ctx.authoritiesContextBuilder);if(!allowed){this.logger.warn(`checkJobAuthorization: caller does not satisfy the execute permissions of "${job.name}"`);throw new JobNotAuthorizedError(job.name)}}async validateInput(){const{job}=this.state.required;this.state.set("parsedInput",job.parseInput(this.state.input))}async admit(){const{job}=this.state.required;await this.input.ctx.admission?.acquire(job.name,this.input.ctx.signal)}async createJobContext(){const{job,parsedInput}=this.state.required;const{ctx,attempt}=this.input;const contextProviders=ctx.contextProviders??await jobContextProviders(job,this.context);this.throwIfAborted();const attemptAbort=abortControllerFollowing(ctx.signal);this.state.set("attemptAbort",attemptAbort);const jobContext=job.create(parsedInput,{authInfo:this.state.authInfo??{},contextProviders,attempt,signal:attemptAbort.signal,onProgress:progressUntilAborted(ctx.run,attemptAbort.signal)});await jobContext.loadAuthContext();this.throwIfAborted();this.appendContextHooks(hooksBoundTo(this.scope.hooks.getClsHooks(job.record.provide),jobContext));this.state.set("jobContext",jobContext)}async execute(){const{job,jobContext,parsedInput,attemptAbort}=this.state.required;this.throwIfAborted();const timeoutMs=this.input.ctx.timeoutMs;const timer=timeoutMs?setTimeout(()=>attemptAbort.abort(new JobTimeoutError(job.name,timeoutMs)),timeoutMs):void 0;const onWorker=runnerOf(job,this.scope.metadata.jobs?.runner)==="worker";let output;try{output=await untilAborted(runOnSurface("job",async()=>onWorker?(await Promise.resolve().then(()=>(init_run_job_in_worker(),run_job_in_worker_exports))).runJobInWorker(jobContext,job,parsedInput,attemptAbort.signal):jobContext.execute(parsedInput)),attemptAbort.signal)}catch(error){this.throwIfAborted();if(!(error instanceof FlowControl&&error.type==="respond"))throw toJobError(error);output=error.output}finally{clearTimeout(timer)}this.throwIfAborted();this.state.set("output",output)}async validateOutput(){this.throwIfAborted();const{job,jobContext}=this.state.required;const result=job.parseOutput(this.state.output);this.state.set("answer",{result,logs:[...jobContext.getLogs()]})}async cleanup(){const{job,jobContext,attemptAbort}=this.state;if(!job||!jobContext||!attemptAbort?.signal.aborted)return;await runJobCleanup(job,jobContext,interruptReasonOf(attemptAbort.signal.reason),this.logger)}async updateRunState(){const run=this.input.ctx.run;if(!run)return;const{attempt}=this.input;const{flowError,answer}=this.state;let outcome;if(!flowError&&answer){outcome={state:"completed",attempt,result:answer.result,logs:answer.logs}}else{const error=flowError??new InternalMcpError("The job attempt ended before it produced a result");outcome={state:willRetryJobAttempt(error,attempt,run.maxAttempts)?"retrying":"failed",attempt,error}}try{await run.recordAttempt(outcome)}catch(error){this.logger.warn(`updateRunState: could not record attempt ${attempt} as ${outcome.state}: ${toJobError(error).message}`)}}async finalize(){const{flowError,answer}=this.state;if(flowError||!answer)return;this.respond(answer)}respond(output){const answer=output===this.state.answer?output:this.checkedAnswer(output);this.state.set("answer",answer);throw FlowControl.respond(answer)}checkedAnswer(output){const{result,logs}=outputSchema10.parse(output);return{result:this.input.job.parseOutput(result),logs}}throwIfAborted(){const signal=this.state.attemptAbort?.signal??this.input.ctx.signal;if(!signal?.aborted)return;throw signal.reason instanceof Error?signal.reason:new InternalMcpError("The job attempt was abandoned")}};__decorateClass([Stage10("parseInput")],ExecuteJobFlow.prototype,"parseInput",1);__decorateClass([Stage10("checkJobAuthorization")],ExecuteJobFlow.prototype,"checkJobAuthorization",1);__decorateClass([Stage10("validateInput")],ExecuteJobFlow.prototype,"validateInput",1);__decorateClass([Stage10("admit")],ExecuteJobFlow.prototype,"admit",1);__decorateClass([Stage10("createJobContext")],ExecuteJobFlow.prototype,"createJobContext",1);__decorateClass([Stage10("execute")],ExecuteJobFlow.prototype,"execute",1);__decorateClass([Stage10("validateOutput")],ExecuteJobFlow.prototype,"validateOutput",1);__decorateClass([Stage10("cleanup")],ExecuteJobFlow.prototype,"cleanup",1);__decorateClass([Stage10("updateRunState")],ExecuteJobFlow.prototype,"updateRunState",1);__decorateClass([Stage10("finalize")],ExecuteJobFlow.prototype,"finalize",1);ExecuteJobFlow=__decorateClass([FrontMcpFlow({name:name10,plan:plan10,inputSchema:inputSchema10,outputSchema:outputSchema10,access:"authorized"})],ExecuteJobFlow)}});function systemFreeMemoryMb(){if(typeof process!=="undefined"&&typeof process.availableMemory==="function"){return process.availableMemory()/BYTES_PER_MB}const{freemem}=__require("node:os");return freemem()/BYTES_PER_MB}var RECHECK_MS2,BYTES_PER_MB,JobAdmission;var init_job_admission=__esm({"libs/sdk/src/job/job-admission.ts"(){"use strict";init_errors();RECHECK_MS2=250;BYTES_PER_MB=1024*1024;JobAdmission=class{constructor(options,probes={}){this.options=options;this.maxWaitMs=options.maxWaitMs??6e5;this.freeMemoryMb=probes.freeMemoryMb??systemFreeMemoryMb}options;running=0;claimedMb=0;queue=[];listeners=new Set;maxWaitMs;freeMemoryMb;slot(){let release;return{acquire:async(jobName,signal)=>{release=await this.admit(jobName,signal)},release:()=>{release?.();release=void 0}}}async admit(jobName,signal){signal?.throwIfAborted();const deadline=Date.now()+this.maxWaitMs;const ticket={};this.queue.push(ticket);try{while(this.queue[0]!==ticket||!this.fits()){const left=deadline-Date.now();if(left<=0)throw new JobAdmissionTimeoutError(jobName,this.maxWaitMs,this.describeWait());await this.nextChange(Math.min(left,RECHECK_MS2),signal)}return this.claim()}finally{this.queue.splice(this.queue.indexOf(ticket),1);this.wake()}}fits(){const{concurrency,memoryMb}=this.options;if(concurrency!==void 0&&this.running>=concurrency)return false;return memoryMb===void 0||this.freeMemoryMb()-this.claimedMb>=memoryMb}claim(){const claimedMb=this.options.memoryMb??0;this.running++;this.claimedMb+=claimedMb;let held=true;return()=>{if(!held)return;held=false;this.running--;this.claimedMb-=claimedMb;this.wake()}}describeWait(){const{concurrency,memoryMb}=this.options;if(concurrency!==void 0&&this.running>=concurrency){return`${this.running} of ${concurrency} job runs are busy`}const availableMb=Math.max(0,Math.floor(this.freeMemoryMb()-this.claimedMb));return`it needs ${memoryMb} MB free, and ${availableMb} MB is`}nextChange(ms,signal){return new Promise((resolve4,reject)=>{const stopListening=()=>{clearTimeout(timer);this.listeners.delete(changed);signal?.removeEventListener("abort",aborted)};const changed=()=>{stopListening();resolve4()};const aborted=()=>{stopListening();reject(signal?.reason)};const timer=setTimeout(changed,ms);this.listeners.add(changed);signal?.addEventListener("abort",aborted,{once:true})})}wake(){for(const listener of[...this.listeners])listener()}}}});var JobEmitter;var init_job_events=__esm({"libs/sdk/src/job/job.events.ts"(){"use strict";JobEmitter=class{listeners=new Set;on(l){this.listeners.add(l);return()=>this.listeners.delete(l)}emit(e){for(const l of[...this.listeners])l(e)}}}});import{internalZ as z80}from"@frontmcp/lazy-zod";var JobInstance,RequestOverAppProviders,FunctionJobContext;var init_job_instance=__esm({"libs/sdk/src/job/job.instance.ts"(){"use strict";init_job_entry();init_job_interface();init_errors();init_mcp_error();init_entry_class_hooks();init_hooks_utils();init_execute_job_flow();JobInstance=class extends JobEntry{_providers;scope;hooks;constructor(record,providers,owner){super(record);this.owner=owner;this._providers=providers;this.name=record.metadata.id||record.metadata.name;this.fullName=this.owner.id+":"+this.name;this.scope=this._providers.getActiveScope();this.hooks=this.scope.hooks;this.inputSchema=record.metadata.inputSchema??{};this.outputSchema=record.metadata.outputSchema??{};this.ready=this.initialize()}async initialize(){if(this.record.kind==="DYNAMIC"){return}const allHooks=normalizeHooksFromCls(this.record.provide);if(allHooks.length===0)return;const className=this.record.provide?.name??this.name;const invalidHooks=allHooks.filter(hook=>hook.metadata.flow!==jobClassHooksJoin.flow);if(invalidHooks.length>0){const declared=invalidHooks.map(h2=>`${h2.metadata.method}() on ${h2.metadata.flow}`).join(", ");throw new InvalidHookFlowError(`Job "${className}" has hooks for unsupported flows: ${declared}. Only the job flow (${jobClassHooksJoin.flow}) is supported on job classes; hook other flows from a provider or a plugin.`)}const unreachable=describeUnreachableEntryClassHooks(allHooks,jobClassHooksJoin,[]);if(unreachable.length>0){throw new InvalidHookFlowError(unreachableHooksMessage("Job",className,unreachable))}await this.hooks.registerHooks(true,...allHooks)}getMetadata(){return this.record.metadata}get providers(){return this._providers}create(input,extra){const metadata=this.metadata;const providers=extra.contextProviders?new RequestOverAppProviders(extra.contextProviders,this._providers):this._providers;const scope=this._providers.getActiveScope();const logger=scope.logger;const authInfo=extra.authInfo;const jobCtorArgs={metadata,input,providers,logger,authInfo,attempt:extra.attempt??1,signal:extra.signal,onProgress:extra.onProgress};switch(this.record.kind){case"CLASS_TOKEN":return new this.record.provide(jobCtorArgs);case"FUNCTION":return new FunctionJobContext(this.record,jobCtorArgs);case"DYNAMIC":throw new DynamicJobDirectExecutionError(this.name);default:throw new InvalidRegistryKindError("job",this.record.kind)}}parseInput(input){const inputSchema45=z80.object(this.inputSchema);return inputSchema45.parse(input)}parseOutput(raw){const outSchema=this.outputSchema;let schema;if(outSchema instanceof z80.ZodType){schema=outSchema}else if(outSchema&&typeof outSchema==="object"&&Object.keys(outSchema).length>0){schema=z80.object(outSchema)}if(!schema)return raw;const parsed=schema.safeParse(raw);if(parsed.success)return parsed.data;const firstIssue=parsed.error.issues[0];throw new InvalidOutputError({reason:"output does not match outputSchema",path:firstIssue?.path.length?firstIssue.path.join("."):void 0})}safeParseOutput(raw){try{return{success:true,data:this.parseOutput(raw)}}catch(error){return{success:false,error}}}};RequestOverAppProviders=class{constructor(requestProviders,appProviders){this.requestProviders=requestProviders;this.appProviders=appProviders}requestProviders;appProviders;get(token){try{return this.requestProviders.get(token)}catch(error){if(error instanceof ProviderNotAvailableError)return this.appProviders.get(token);throw error}}getScope(){return this.requestProviders.getScope()}getProviders(){return this.requestProviders.getProviders()}getRegistries(type){return this.requestProviders.getRegistries(type)}buildViews(sessionKey,contextProviders,contextSource){return this.requestProviders.buildViews(sessionKey,contextProviders,contextSource)}};FunctionJobContext=class extends JobContext{constructor(record,args){super(args);this.record=record}record;execute(input){return this.record.provide(input,this)}}}});import{depsOfClass as depsOfClass7,depsOfFunc as depsOfFunc4,getMetadata as getMetadata15,isClass as isClass13}from"@frontmcp/di";function collectJobMetadata(cls){const extended=getMetadata15(extendedJobMetadata,cls);const seed=extended?{...extended}:{};return Object.entries(FrontMcpJobTokens).reduce((metadata,[key,token])=>{const value=getMetadata15(token,cls);if(value!==void 0){return Object.assign(metadata,{[key]:value})}else{return metadata}},seed)}function normalizeJob(item){if(isExternalEntryRecord(item)){throw unsupportedExternalEntry("job",item)}const fn=item;if(item&&typeof item==="function"&&fn[FrontMcpJobTokens.type]==="function-job"&&fn[FrontMcpJobTokens.metadata]){return{kind:"FUNCTION",provide:item(),metadata:fn[FrontMcpJobTokens.metadata]}}if(isClass13(item)){const metadata=collectJobMetadata(item);return{kind:"CLASS_TOKEN",provide:item,metadata}}const name51=(item!=null&&typeof item==="object"&&"name"in item?item.name:void 0)??String(item);throw new InvalidEntityError("job",name51,"a class or a job object")}function jobDiscoveryDeps(rec){switch(rec.kind){case"FUNCTION":return depsOfFunc4(rec.provide,"discovery");case"CLASS_TOKEN":return depsOfClass7(rec.provide,"discovery");case"DYNAMIC":case"ESM":case"REMOTE":return[]}}var init_job_utils=__esm({"libs/sdk/src/job/job.utils.ts"(){"use strict";init_job_tokens();init_external_entry_utils();init_errors()}});import{tokenName as tokenName14}from"@frontmcp/di";var JobRegistry;var init_job_registry=__esm({"libs/sdk/src/job/job.registry.ts"(){"use strict";init_logger_interface();init_errors();init_regsitry();init_lineage_utils();init_job_events();init_job_instance();init_job_utils();JobRegistry=class extends RegistryAbstract{owner;localRows=[];dynamicRows=[];byName=new Map;byId=new Map;version=0;emitter=new JobEmitter;logger;entryProviders;constructor(providers,list,owner,entryProviders=new Map){super("JobRegistry",providers,list,false);this.owner=owner;this.entryProviders=entryProviders;try{this.logger=providers.get(FrontMcpLogger)}catch{}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=normalizeJob(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);if(!rec){throw new RegistryDefinitionNotFoundError("JobRegistry",tokenName14(token))}const deps=jobDiscoveryDeps(rec);for(const d of deps){this.providersOf(token).get(d);const edges=this.graph.get(token);if(!edges){throw new RegistryGraphEntryNotFoundError("JobRegistry",tokenName14(token))}edges.add(d)}}}async initialize(){for(const token of this.tokens){const rec=this.defs.get(token);if(!rec){throw new RegistryDefinitionNotFoundError("JobRegistry",tokenName14(token))}const ji=new JobInstance(rec,this.providersOf(token),this.owner);this.instances.set(token,ji);const lineage=this.owner?[this.owner]:[];const row=this.makeRow(token,ji,lineage);this.localRows.push(row)}await Promise.all([...this.instances.values()].map(ji=>ji.ready));this.reindex();this.bump("reset")}providersOf(token){return this.entryProviders.get(token)??this.providers}getJobs(includeHidden=false){const all=[...this.localRows,...this.dynamicRows].map(r=>r.instance);return all.filter(j=>j.metadata.hideFromDiscovery!==true||includeHidden)}findByName(name51){return this.byName.get(name51)?.instance}findById(id){return this.byId.get(id)?.instance}search(query,opts){let jobs=this.getJobs(false);if(query){const q=query.toLowerCase();jobs=jobs.filter(j=>j.name.toLowerCase().includes(q)||(j.metadata.description??"").toLowerCase().includes(q))}if(opts?.tags&&opts.tags.length>0){const filterTags=opts.tags;jobs=jobs.filter(j=>{const tags=j.getTags();return filterTags.some(t=>tags.includes(t))})}if(opts?.labels){const labelEntries=Object.entries(opts.labels);jobs=jobs.filter(j=>{const labels=j.getLabels();return labelEntries.every(([k,v])=>labels[k]===v)})}return jobs}registerDynamic(record){const token=Symbol.for(`job:dynamic:${record.provide}`);const existing=this.dynamicRows.findIndex(r=>r.token===token);if(existing!==-1){this.dynamicRows.splice(existing,1)}const ji=new JobInstance(record,this.providers,this.owner);this.instances.set(token,ji);const lineage=this.owner?[this.owner]:[];const row=this.makeRow(token,ji,lineage);this.dynamicRows.push(row);this.reindex();this.bump("added")}removeDynamic(jobId){const idx=this.dynamicRows.findIndex(r=>r.instance.metadata.id===jobId||r.instance.name===jobId);if(idx===-1)return false;const row=this.dynamicRows[idx];this.dynamicRows.splice(idx,1);this.instances.delete(row.token);this.reindex();this.bump("removed");return true}subscribe(opts,cb){if(opts.immediate){cb({kind:"reset",changeScope:"global",version:this.version,snapshot:this.getJobs()})}return this.emitter.on(cb)}hasAny(){return this.localRows.length>0||this.dynamicRows.length>0}reindex(){this.byName.clear();this.byId.clear();const effective=[...this.localRows,...this.dynamicRows];for(const r of effective){if(this.byName.has(r.baseName)){this.logger?.warn(`JobRegistry: duplicate job name "${r.baseName}" detected during reindex; later entry wins`)}this.byName.set(r.baseName,r);const idKey=r.instance.metadata.id??r.baseName;if(this.byId.has(idKey)){this.logger?.warn(`JobRegistry: duplicate job id "${idKey}" detected during reindex; later entry wins`)}this.byId.set(idKey,r)}}bump(kind){const version=++this.version;this.emitter.emit({kind,changeScope:"global",version,snapshot:this.getJobs()})}makeRow(token,instance,lineage){const ownerKey=ownerKeyOf(lineage);const baseName=instance.name;const qualifiedName=qualifiedNameOf(lineage,baseName);const qualifiedId=`${ownerKey}:${tokenName14(token)}`;return{token,instance,baseName,lineage,ownerKey,qualifiedName,qualifiedId,source:this}}}}});var init_base_interface=__esm({"libs/sdk/src/common/interfaces/base.interface.ts"(){"use strict"}});var init_front_mcp_interface=__esm({"libs/sdk/src/common/interfaces/front-mcp.interface.ts"(){"use strict"}});import{HttpServerResponse,IncomingMessage}from"@frontmcp/protocol";var ServerRequest,ServerResponse,FrontMcpServer;var init_server_interface=__esm({"libs/sdk/src/common/interfaces/server.interface.ts"(){"use strict";ServerRequest=class extends IncomingMessage{path;query;params;body;authSession};ServerResponse=class extends HttpServerResponse{};FrontMcpServer=class{async stop(){return}}}});var init_scope_interface=__esm({"libs/sdk/src/common/interfaces/scope.interface.ts"(){"use strict"}});var init_hook_interface=__esm({"libs/sdk/src/common/interfaces/hook.interface.ts"(){"use strict"}});var init_app_interface=__esm({"libs/sdk/src/common/interfaces/app.interface.ts"(){"use strict"}});function AsyncAuthProvider(cfg){return cfg}var init_auth_provider_interface=__esm({"libs/sdk/src/common/interfaces/auth-provider.interface.ts"(){"use strict"}});var init_adapter_interface=__esm({"libs/sdk/src/common/interfaces/adapter.interface.ts"(){"use strict"}});var init_plugin_interface=__esm({"libs/sdk/src/common/interfaces/plugin.interface.ts"(){"use strict"}});var ToolContext;var init_tool_interface=__esm({"libs/sdk/src/common/interfaces/tool.interface.ts"(){"use strict";init_helpers();init_execution_context_interface();init_flow_interface();ToolContext=class extends ExecutionContextBase{toolId;toolName;metadata;_toolNameInternal;_toolInputInternal;_jsonRpcRequestIdInternal;_rawInput;_input;_outputDraft;_output;_inputHistory=[];_outputHistory=[];_progressToken;constructor(args){const{metadata,input,providers,logger,progressToken,signal}=args;super({providers,logger:logger.child(`tool:${metadata.id??metadata.name}`),authInfo:args.authInfo,signal});this.toolName=metadata.name;this.toolId=metadata.id??metadata.name;this.metadata=metadata;this._input=input;this._progressToken=progressToken}get _progressTokenInternal(){return this._progressToken}fetch(input,init){const context=this.fetchContext(init);if(context&&this.signal)return context.fetch(input,init,this.signal);return super.fetch(input,init)}get input(){return this._input}set input(v){this._input=v;this._inputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get inputHistory(){return this._inputHistory}get output(){return this._output}set output(v){this._output=v;this._outputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get outputHistory(){return this._outputHistory}respond(value){this.output=value;FlowControl.respond(value)}async notify(message,level="info"){const data=typeof message==="string"?{message}:message;const sink=this.tryGetContext()?.getRequestNotificationSink?.();if(sink)return sink.log(level,this.toolName,data);const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.warn("Cannot send notification: no session ID");return false}return this.scope.notifications.sendLogMessageToSession(sessionId,level,this.toolName,data)}async progress(progress,total,message){const sink=this.tryGetContext()?.getRequestNotificationSink?.();if(sink)return sink.progress(progress,total,message);if(!this._progressToken){this.logger.debug("Cannot send progress: no progressToken in request");return false}const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.warn("Cannot send progress: no session ID");return false}return this.scope.notifications.sendProgressNotification(sessionId,this._progressToken,progress,total,message)}notifyResourceUpdated(uri){this.scope.resources.notifyContentChanged(uri)}notifyResourceListChanged(){this.scope.notifications.broadcastNotification("notifications/resources/list_changed")}async elicit(message,requestedSchema,options){return performElicit({sessionId:this.context.sessionId,getClientCapabilities:sid=>this.scope.notifications.getClientCapabilities(sid),tryGetContext:()=>this.tryGetContext(),entryName:this._toolNameInternal??this.toolName,entryInput:this._toolInputInternal??this.input,elicitationEnabled:this.scope.metadata.elicitation?.enabled===true,questions:this.scope.persistentQuestions,signal:this.signal},message,requestedSchema,options)}async sample(options){return performSample(this.tryGetContext(),options)}async listRoots(){return performListRoots(this.tryGetContext())}get platform(){const payloadPlatform=this.authInfo.sessionIdPayload?.platformType;if(payloadPlatform&&payloadPlatform!=="unknown"){return payloadPlatform}const requestPlatform=this.tryGetContext()?.platformType;if(requestPlatform&&requestPlatform!=="unknown"){return requestPlatform}const sessionId=this.authInfo.sessionId;if(!sessionId){return"unknown"}return this.scope.notifications.getPlatformType(sessionId)}get clientInfo(){const requestClientInfo=this.tryGetContext()?.clientInfo;if(requestClientInfo){return requestClientInfo}const sessionId=this.authInfo.sessionId;if(!sessionId){return void 0}return this.scope.notifications.getClientInfo(sessionId)}}}});var PromptContext;var init_prompt_interface=__esm({"libs/sdk/src/common/interfaces/prompt.interface.ts"(){"use strict";init_execution_context_interface();init_flow_interface();PromptContext=class extends ExecutionContextBase{promptId;promptName;metadata;args;_output;_outputHistory=[];constructor(ctorArgs){const{metadata,args,providers,logger,authInfo}=ctorArgs;super({providers,logger:logger.child(`prompt:${metadata.name}`),authInfo});this.promptName=metadata.name;this.promptId=metadata.name;this.metadata=metadata;this.args=args}get authInfo(){return super.authInfo}get output(){return this._output}set output(v){this._output=v;this._outputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get outputHistory(){return this._outputHistory}respond(value){this.output=value;FlowControl.respond(value)}get error(){return super.error}}}});function definedFields(toolCall){return Object.fromEntries(Object.entries(toolCall).filter(([,value])=>value!==void 0))}var AgentExecutionLoop,AgentMaxIterationsError;var init_agent_execution_loop=__esm({"libs/sdk/src/agent/agent-execution-loop.ts"(){"use strict";init_common();AgentExecutionLoop=class{config;constructor(config){this.config={maxIterations:10,timeout:12e4,...config}}async run(userMessage,toolExecutor,existingMessages=[]){const startTime=Date.now();const messages=[...existingMessages,{role:"user",content:userMessage}];let iterations=0;let totalPromptTokens=0;let totalCompletionTokens=0;let timeout;try{const timeoutPromise=new Promise((_,reject)=>{timeout=setTimeout(()=>reject(new Error(`Agent execution timed out after ${this.config.timeout}ms`)),this.config.timeout)});const result=await Promise.race([this.executeLoop(messages,toolExecutor,{onIteration:(iter,msg)=>{iterations=iter;this.config.onIteration?.(iter,msg)},onUsage:(prompt,completion)=>{totalPromptTokens+=prompt;totalCompletionTokens+=completion}}),timeoutPromise]);return{content:result.content,messages,iterations,usage:{promptTokens:totalPromptTokens,completionTokens:totalCompletionTokens,totalTokens:totalPromptTokens+totalCompletionTokens},success:true,durationMs:Date.now()-startTime}}catch(error){return{content:null,messages,iterations,usage:{promptTokens:totalPromptTokens,completionTokens:totalCompletionTokens,totalTokens:totalPromptTokens+totalCompletionTokens},success:false,error,durationMs:Date.now()-startTime}}finally{clearTimeout(timeout)}}async*runStreaming(userMessage,toolExecutor,existingMessages=[]){const startTime=Date.now();const deadline=startTime+this.config.timeout;const messages=[...existingMessages,{role:"user",content:userMessage}];let iterations=0;let totalPromptTokens=0;let totalCompletionTokens=0;const result=(content,error)=>({content,messages,iterations,usage:{promptTokens:totalPromptTokens,completionTokens:totalCompletionTokens,totalTokens:totalPromptTokens+totalCompletionTokens},success:error===void 0,...error&&{error},durationMs:Date.now()-startTime});const events=this.executeLoopStreaming(messages,toolExecutor);try{for(;;){const step=await this.beforeDeadline(events.next(),deadline);if(step.done){const done=result(step.value.content);yield{type:"done",result:done};return done}const event=step.value;if(event.type==="iteration")iterations=event.iteration;if(event.type==="usage"){totalPromptTokens+=event.promptTokens;totalCompletionTokens+=event.completionTokens}yield event}}catch(caught){void events.return({content:null}).catch(()=>void 0);const error=caught;const failed=result(null,error);yield{type:"error",error};yield{type:"done",result:failed};return failed}}async beforeDeadline(step,deadline){let timer;const timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(`Agent execution timed out after ${this.config.timeout}ms`)),Math.max(0,deadline-Date.now()))});try{return await Promise.race([step,timeout])}finally{clearTimeout(timer)}}async executeLoop(messages,toolExecutor,callbacks){for(let iteration=1;iteration<=this.config.maxIterations;iteration++){this.config.logger?.debug(`Agent loop iteration ${iteration}/${this.config.maxIterations}`);this.config.onLlmStart?.(iteration,this.config.maxIterations);const prompt={system:this.config.systemInstructions,messages};const completion=await this.config.adapter.completion(prompt,this.config.tools.length>0?this.config.tools:void 0,this.config.completionOptions);this.config.onLlmComplete?.(iteration,completion.usage);if(completion.usage){callbacks.onUsage(completion.usage.promptTokens,completion.usage.completionTokens)}if(completion.finishReason==="tool_calls"&&completion.toolCalls?.length){this.config.onToolsIdentified?.(completion.toolCalls.length,completion.toolCalls.map(tc=>tc.name));const assistantMessage={role:"assistant",content:completion.content,toolCalls:completion.toolCalls};messages.push(assistantMessage);callbacks.onIteration(iteration,assistantMessage);const totalTools=completion.toolCalls.length;for(let toolIndex=0;toolIndex<totalTools;toolIndex++){const toolCall=completion.toolCalls[toolIndex];this.config.onToolStart?.(toolCall,toolIndex,totalTools);this.config.onToolCall?.(toolCall);let result;let error2;try{result=await toolExecutor(toolCall.name,toolCall.arguments)}catch(e){error2=e;result={error:error2.message}}this.config.onToolResult?.(toolCall,result,error2);const toolMessage={role:"tool",content:typeof result==="string"?result:JSON.stringify(result),toolCallId:toolCall.id,name:toolCall.name};messages.push(toolMessage)}}else{const assistantMessage={role:"assistant",content:completion.content};messages.push(assistantMessage);callbacks.onIteration(iteration,assistantMessage);this.config.onContent?.(completion.content??"");this.config.onComplete?.(completion.content,void 0);return{content:completion.content}}}const error=new AgentMaxIterationsError(`Agent reached maximum iterations (${this.config.maxIterations}) without completing`,this.config.maxIterations);this.config.onComplete?.(null,error);throw error}async*executeLoopStreaming(messages,toolExecutor){for(let iteration=1;iteration<=this.config.maxIterations;iteration++){this.config.logger?.debug(`Agent loop iteration ${iteration}/${this.config.maxIterations}`);this.config.onLlmStart?.(iteration,this.config.maxIterations);yield{type:"iteration",iteration};const prompt={system:this.config.systemInstructions,messages};const completion=yield*this.streamCompletion(prompt);this.config.onLlmComplete?.(iteration,completion.usage);if(completion.finishReason==="tool_calls"&&completion.toolCalls?.length){const toolCalls=completion.toolCalls;this.config.onToolsIdentified?.(toolCalls.length,toolCalls.map(tc=>tc.name));const assistantMessage={role:"assistant",content:completion.content,toolCalls};messages.push(assistantMessage);this.config.onIteration?.(iteration,assistantMessage);const totalTools=toolCalls.length;for(let toolIndex=0;toolIndex<totalTools;toolIndex++){const toolCall=toolCalls[toolIndex];this.config.onToolStart?.(toolCall,toolIndex,totalTools);this.config.onToolCall?.(toolCall);yield{type:"tool_start",toolCall};let result;let error2;try{result=await toolExecutor(toolCall.name,toolCall.arguments)}catch(e){error2=e;result={error:error2.message}}this.config.onToolResult?.(toolCall,result,error2);yield{type:"tool_end",toolCall,result,error:error2};const toolMessage={role:"tool",content:typeof result==="string"?result:JSON.stringify(result),toolCallId:toolCall.id,name:toolCall.name};messages.push(toolMessage)}}else{const assistantMessage={role:"assistant",content:completion.content};messages.push(assistantMessage);this.config.onIteration?.(iteration,assistantMessage);this.config.onComplete?.(completion.content,void 0);return{content:completion.content}}}const error=new AgentMaxIterationsError(`Agent reached maximum iterations (${this.config.maxIterations}) without completing`,this.config.maxIterations);this.config.onComplete?.(null,error);throw error}async*streamCompletion(prompt){const adapter=this.config.adapter;const tools=this.config.tools.length>0?this.config.tools:void 0;let streamedText="";let completion;if(supportsStreaming(adapter)){const announced=new Map;let done;for await(const chunk of adapter.streamCompletion(prompt,tools,this.config.completionOptions)){if(chunk.type==="content"&&chunk.content){streamedText+=chunk.content;yield{type:"content",content:chunk.content};this.config.onContent?.(chunk.content)}else if(chunk.type==="tool_call"&&chunk.toolCall){announced.set(chunk.toolCall.id,{...announced.get(chunk.toolCall.id),...definedFields(chunk.toolCall)});yield{type:"tool_call",toolCall:chunk.toolCall}}else if(chunk.type==="done"&&chunk.completion){done=chunk.completion}}const toolCalls=done?.toolCalls??[...announced.values()].map(call=>({id:call.id,name:call.name??"",arguments:call.arguments??{}}));completion={content:streamedText||(done?.content??null),finishReason:done?.finishReason??(toolCalls.length>0?"tool_calls":"stop"),...toolCalls.length>0&&{toolCalls},...done?.usage&&{usage:done.usage}}}else{completion=await adapter.completion(prompt,tools,this.config.completionOptions)}if(!streamedText&&completion.content){yield{type:"content",content:completion.content};this.config.onContent?.(completion.content)}if(completion.usage){yield{type:"usage",promptTokens:completion.usage.promptTokens,completionTokens:completion.usage.completionTokens}}return completion}};AgentMaxIterationsError=class extends Error{constructor(message,maxIterations){super(message);this.maxIterations=maxIterations;this.name="AgentMaxIterationsError"}maxIterations}}});var AgentContext;var init_agent_interface=__esm({"libs/sdk/src/common/interfaces/agent.interface.ts"(){"use strict";init_agent_execution_loop();init_frontmcp_context_storage();init_helpers();init_errors();init_tool_lookup_utils();init_execution_context_interface();init_flow_interface();AgentContext=class _AgentContext extends ExecutionContextBase{agentId;agentName;metadata;llmAdapter;agentScope;systemInstructions;toolDefinitions;toolExecutor;agentInvoker;privateScope;_agentNameInternal;_agentInputInternal;_rawInput;_input;_outputDraft;_output;_inputHistory=[];_outputHistory=[];_progressToken;constructor(args){const{metadata,input,providers,logger,llmAdapter,agentScope,toolDefinitions,toolExecutor,agentInvoker,privateScope,progressToken}=args;super({providers,logger:logger.child(`agent:${metadata.id??metadata.name}`),authInfo:args.authInfo,signal:args.signal});this.agentName=metadata.name;this.agentId=metadata.id??metadata.name;this.metadata=metadata;this._input=input;this.llmAdapter=llmAdapter;this.agentScope=agentScope;this.systemInstructions=metadata.systemInstructions??"";this.toolDefinitions=toolDefinitions??[];this.toolExecutor=toolExecutor;this.agentInvoker=agentInvoker;this.privateScope=privateScope;this._progressToken=progressToken}async execute(input){return this.runAgentLoop(input)}async runAgentLoop(input){const userMessage=this.buildUserMessage(input);const streaming=this.streamsReplies();const enableAutoProgress=this.metadata.execution?.enableAutoProgress===true&&this.metadata.execution?.enableNotifications!==false;const maxIterations=this.metadata.execution?.maxIterations??10;const notificationInterval=this.metadata.execution?.notificationInterval??1e3;const iterationShare=80/maxIterations;let iterationStart=0;let lastSentProgress=-1;let lastAutoProgressAt;const autoProgress=(progress,message,isFinal=false)=>{if(streaming)return;const now=Date.now();if(progress<=lastSentProgress)return;if(!isFinal&&lastAutoProgressAt!==void 0&&now-lastAutoProgressAt<notificationInterval)return;lastAutoProgressAt=now;lastSentProgress=progress;void this.progress(progress,100,message)};const loop=new AgentExecutionLoop({adapter:{completion:(prompt,tools,options)=>this.completion(prompt,tools,options),...streaming&&{streamCompletion:(prompt,tools,options)=>this.streamCompletion(prompt,tools,options)}},systemInstructions:this.systemInstructions,tools:this.toolDefinitions,maxIterations,timeout:this.metadata.execution?.timeout??12e4,logger:this.logger,completionOptions:this.completionOptions(),onLlmStart:enableAutoProgress?(iteration,maxIter)=>{iterationStart=(iteration-1)*iterationShare;autoProgress(Math.round(iterationStart),`Starting LLM call (iteration ${iteration}/${maxIter})`)}:void 0,onLlmComplete:enableAutoProgress?(iteration,usage)=>{const usageStr=usage?` (${usage.promptTokens??0}P + ${usage.completionTokens??0}C tokens)`:"";autoProgress(Math.round(iterationStart+iterationShare/2),`LLM response received${usageStr}`)}:void 0,onToolsIdentified:enableAutoProgress?(count,names)=>{this.notify(`Identified ${count} tool call(s): ${names.join(", ")}`,"info")}:void 0,onToolStart:enableAutoProgress?(toolCall,index,total)=>{const toolsDone=(index+1)/(total+1);const toolProgress=iterationStart+iterationShare/2*(1+toolsDone);autoProgress(Math.round(toolProgress),`Executing tool ${index+1}/${total}: ${toolCall.name}`)}:void 0,onComplete:enableAutoProgress?(content,error)=>{autoProgress(100,error?`Agent failed: ${toMcpError(error).getPublicMessage()}`:"Agent completed",true)}:void 0,onToolCall:toolCall=>{if(this.metadata.execution?.enableNotifications!==false){this.notify(`Calling tool: ${toolCall.name}`,"info")}this.logger.debug(`Tool call: ${toolCall.name}`,{args:toolCall.arguments})},onToolResult:(toolCall,result2,error)=>{if(error){const reported=toMcpError(error);if(this.metadata.execution?.enableNotifications!==false){this.notify(`Tool ${toolCall.name} failed: ${reported.getPublicMessage()}`,"error")}this.logger.error(`Tool ${toolCall.name} failed (${reported.errorId})`,error)}else{this.logger.debug(`Tool ${toolCall.name} completed`,{result:result2})}},onContent:content=>{if(this.metadata.execution?.enableNotifications!==false){this.logger.debug(`Content received: ${content.slice(0,100)}...`)}}});const executor=async(name51,args)=>this.executeTool(name51,args);const result=streaming?await this.streamAgentLoop(loop.runStreaming(userMessage,executor)):await loop.run(userMessage,executor);if(!result.success&&result.error){throw result.error}return this.parseAgentResponse(result.content)}streamsReplies(){if(this.metadata.execution?.enableStreaming!==true||this._progressToken===void 0)return false;const overridesCompletion=this.completion!==_AgentContext.prototype.completion;const overridesStreamCompletion=this.streamCompletion!==_AgentContext.prototype.streamCompletion;return overridesStreamCompletion||!overridesCompletion&&typeof this.llmAdapter.streamCompletion==="function"}async streamAgentLoop(events){let chunks=0;for(let step=await events.next();;step=await events.next()){if(step.done)return step.value;const event=step.value;if(event.type==="content"&&event.content){chunks+=1;await this.progress(chunks,void 0,event.content)}}}completionOptions(){const llm=this.metadata.llm;return{...llm?.temperature!==void 0&&{temperature:llm.temperature},...llm?.maxTokens!==void 0&&{maxTokens:llm.maxTokens}}}buildUserMessage(input){if(typeof input==="string"){return input}const inputObj=input;if(inputObj["query"])return String(inputObj["query"]);if(inputObj["message"])return String(inputObj["message"]);if(inputObj["prompt"])return String(inputObj["prompt"]);if(inputObj["input"])return String(inputObj["input"]);return JSON.stringify(input)}parseAgentResponse(content){if(content===null){return{response:""}}if(content.trim().startsWith("{")||content.trim().startsWith("[")){try{return JSON.parse(content)}catch{}}return{response:content}}get input(){return this._input}set input(v){this._input=v;this._inputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get inputHistory(){return this._inputHistory}get output(){return this._output}set output(v){this._output=v;this._outputHistory.push({at:Date.now(),stage:this.activeStage,value:v})}get outputHistory(){return this._outputHistory}async completion(prompt,tools,options){return this.llmAdapter.completion(prompt,tools,options)}async*streamCompletion(prompt,tools,options){if(!this.llmAdapter.streamCompletion){const result=await this.completion(prompt,tools,options);yield{type:"done",completion:result};return}yield*this.llmAdapter.streamCompletion(prompt,tools,options)}async executeTool(name51,args){if(!this.toolExecutor){throw new AgentMethodNotAvailableError("executeTool",this.agentName)}return this.toolExecutor(name51,args)}async invokeAgent(agentId,input){if(!this.agentInvoker){throw new AgentMethodNotAvailableError("invokeAgent",this.agentName)}return this.agentInvoker(agentId,input)}callToolSurface(){return"agent"}callToolScope(name51){const privateScope=this.privateScope;const isPrivateTool=privateScope&&lookupTool(privateScope,name51);return isPrivateTool?privateScope:super.callToolScope(name51)}async notify(message,level="info"){const logMessage=typeof message==="string"?message:JSON.stringify(message);if(level==="error"){this.logger.error(logMessage)}else if(level==="warning"){this.logger.warn(logMessage)}else{this.logger.info(logMessage)}const data=typeof message==="string"?{message}:message;const sink=this.requestNotificationSink();if(sink)return sink.log(level,this.agentName,data);const sessionId=this.authInfo.sessionId;if(!sessionId){return false}return this.scope.notifications.sendLogMessageToSession(sessionId,level,this.agentName,data)}async progress(progress,total,message){const sink=this.requestNotificationSink();if(sink)return sink.progress(progress,total,message);if(this._progressToken===void 0){this.logger.debug("Cannot send progress: no progressToken in request");return false}const sessionId=this.authInfo.sessionId;if(!sessionId){this.logger.warn("Cannot send progress: no session ID");return false}return this.scope.notifications.sendProgressNotification(sessionId,this._progressToken,progress,total,message)}async elicit(message,requestedSchema,options){return performElicit({sessionId:this.authInfo.sessionId,getClientCapabilities:sid=>this.scope.notifications.getClientCapabilities(sid),tryGetContext:()=>this.tryGetContext()??this.runningRequestContext(),entryName:this._agentNameInternal??this.agentName,entryInput:this._agentInputInternal??this.input,elicitationEnabled:this.scope.metadata.elicitation?.enabled===true,questions:this.scope.persistentQuestions,signal:this.signal},message,requestedSchema,options)}requestNotificationSink(){return(this.tryGetContext()??this.runningRequestContext())?.getRequestNotificationSink?.()}runningRequestContext(){try{return this.scope.providers.get(FrontMcpContextStorage).getStore()}catch{return void 0}}respond(value){this.output=value;FlowControl.respond(value)}get platform(){const payloadPlatform=this.authInfo.sessionIdPayload?.platformType;if(payloadPlatform&&payloadPlatform!=="unknown"){return payloadPlatform}const requestPlatform=this.tryGetContext()?.platformType;if(requestPlatform&&requestPlatform!=="unknown"){return requestPlatform}const sessionId=this.authInfo.sessionId;if(!sessionId){return"unknown"}return this.scope.notifications.getPlatformType(sessionId)}get clientInfo(){const requestClientInfo=this.tryGetContext()?.clientInfo;if(requestClientInfo){return requestClientInfo}const sessionId=this.authInfo.sessionId;if(!sessionId){return void 0}return this.scope.notifications.getClientInfo(sessionId)}}}});var SkillContext;var init_skill_interface=__esm({"libs/sdk/src/common/interfaces/skill.interface.ts"(){"use strict";init_sdk_errors();init_metadata();init_execution_context_interface();SkillContext=class extends ExecutionContextBase{skillId;skillName;metadata;defaults;constructor(args){const{metadata,providers,logger,defaults}=args;super({providers,logger:logger.child(`skill:${metadata.id??metadata.name}`),authInfo:args.authInfo});this.skillName=metadata.name;this.skillId=metadata.id??metadata.name;this.metadata=metadata;this.defaults=defaults}async loadInstructions(){if(!this.defaults)throw new SkillContextNotImplementedError(this.skillName,"loadInstructions");return this.defaults.loadInstructions()}async build(){if(!this.defaults)throw new SkillContextNotImplementedError(this.skillName,"build");return this.defaults.build()}getToolRefs(){if(!this.metadata.tools)return[];return this.metadata.tools.map(t=>normalizeToolRef(t))}getToolNames(){return this.getToolRefs().map(t=>t.name)}}}});var WorkflowContext;var init_workflow_interface=__esm({"libs/sdk/src/common/interfaces/workflow.interface.ts"(){"use strict";init_execution_context_interface();WorkflowContext=class extends ExecutionContextBase{metadata;_stepResults=new Map;constructor(args){const{metadata,providers,logger}=args;super({providers,logger:logger.child(`workflow:${metadata.id??metadata.name}`),authInfo:args.authInfo});this.metadata=metadata}get workflowName(){return this.metadata.name}get workflowId(){return this.metadata.id??this.metadata.name}get stepResults(){return this._stepResults}_setStepResult(stepId,result){this._stepResults.set(stepId,result)}}}});var ChannelContext;var init_channel_interface=__esm({"libs/sdk/src/common/interfaces/channel.interface.ts"(){"use strict";init_call_surface();init_mcp_error();init_execution_context_interface();ChannelContext=class extends ExecutionContextBase{channelName;metadata;_pushIncoming;constructor(args){const{metadata,providers,logger}=args;super({providers,logger:logger.child(`channel:${metadata.name}`),authInfo:args.authInfo});this.channelName=metadata.name;this.metadata=metadata}async onReply(reply,meta){throw new PublicMcpError(`Channel "${this.channelName}" has twoWay: true but onReply() is not implemented. Override onReply() to forward replies to the external system.`,"CHANNEL_REPLY_NOT_IMPLEMENTED",501)}async onConnect(){}async onDisconnect(){}pushIncoming(payload){if(this._pushIncoming){this._pushIncoming(payload)}else{this.logger.warn(`Channel "${this.channelName}": pushIncoming called but no handler is wired`)}}callToolSurface(){return getCallSurface()==="http-trigger"?"http-trigger":void 0}}}});var init_duty_interface=__esm({"libs/sdk/src/common/interfaces/duty.interface.ts"(){"use strict"}});var HttpRouteContext;var init_http_route_interface=__esm({"libs/sdk/src/common/interfaces/http-route.interface.ts"(){"use strict";init_execution_context_interface();HttpRouteContext=class extends ExecutionContextBase{request;person;constructor(args){super(args);this.request=args.request;this.person=args.person}get params(){return this.request.params??{}}}}});import{scopesFromClaims}from"@frontmcp/auth";function sessionIdPresentedBy(request2){const header2=request2.headers?.["mcp-session-id"];if(typeof header2==="string"&&header2.length>0)return header2;const query=request2.query?.["sessionId"];return typeof query==="string"&&query.length>0?query:void 0}function authInfoFromAuthorization(authorization,presentedSessionId){const{token,user,session}=authorization;const verifiedSession=session!==void 0&&presentedSessionId!==void 0&&session.id===presentedSessionId?session:void 0;return{token,clientId:user?.sub,scopes:scopesFromClaims(user),expiresAt:user?.exp?user.exp*1e3:void 0,user,extra:{user,sessionId:verifiedSession?.id,sessionPayload:verifiedSession?.payload}}}var init_auth_info_utils=__esm({"libs/sdk/src/common/utils/auth-info.utils.ts"(){"use strict"}});import{internalZ as z81}from"@frontmcp/lazy-zod";function pathOf(req){const anyReq=req;const raw=anyReq.path??anyReq.pathname??anyReq.url??"/";try{const u=new URL(String(raw),"http://local");return u.pathname||"/"}catch{return String(raw).split("?")[0]||"/"}}function isLegacySsePath(path4){return path4==="/sse"||path4.endsWith("/sse")}function tryDecodeTransportType(sessionId){if(!sessionId)return;try{const b64=sessionId.replace(/-/g,"+").replace(/_/g,"/");const json=Buffer.from(b64,"base64").toString("utf8");if(json.trimStart()[0]!=="{")return;const obj=JSON.parse(json);return obj?.transportType}catch{return}}function getQuerySessionId(req){const anyReq=req;const raw=anyReq.url??anyReq.path??"/";try{const u=new URL(String(raw),"http://local");return u.searchParams.get("sessionId")??void 0}catch{return void 0}}function computeBitmap(req,cfg){const method=req.method.toUpperCase();const accept=h(req,"accept");const path4=pathOf(req);const postToMessage=method==="POST"&&(path4==="/message"||path4.endsWith("/message"));const headerSessionId=h(req,"mcp-session-id");const querySessionId=postToMessage?getQuerySessionId(req):void 0;const sessionId=headerSessionId??querySessionId;const legacyHeader=h(req,"x-legacy-sse")==="true";const transportType=tryDecodeTransportType(sessionId);const acceptSSE=wantsSSE(accept);const acceptJSON=wantsJSON(accept)||!accept&&cfg.tolerateMissingAccept;const init=method==="POST"&&isInitialize(req.body);const getToSsePath=method==="GET"&&isLegacySsePath(path4);const channel2=method==="POST"&&postToMessage?CH_POST_MESSAGE:getToSsePath&&acceptSSE?CH_GET_SSE_PATH:method==="GET"&&acceptSSE?CH_GET_SSE:method==="POST"&&init&&acceptSSE?CH_POST_INIT_SSE:method==="POST"&&init&&acceptJSON?CH_POST_INIT_JSON:method==="POST"&&!init&&acceptSSE?CH_POST_SSE:method==="POST"&&!init&&acceptJSON?CH_POST_JSON:CH_OTHER;let flags=0;if(sessionId)flags|=B_HAS_SESSION;if(cfg.enableStatelessHttp)flags|=B_STATELESS_EN;if(cfg.requireSessionForStreamable)flags|=B_REQ_SESSION;if(legacyHeader||transportType==="legacy-sse")flags|=B_LEGACY_HINT;if(cfg.enableSseListener)flags|=B_SSE_LISTENER_EN;if(cfg.enableStreamableHttp)flags|=B_STREAMABLE_EN;if(cfg.enableStatefulHttp)flags|=B_STATEFUL_EN;if(cfg.enableLegacySSE)flags|=B_LEGACY_EN;return{key:channel2&CH_MASK|flags,channel:channel2,flags,init}}function decideIntent(req,cfg){const reasons=[];const method=req.method.toUpperCase();if(method==="DELETE"){const sessionId=h(req,"mcp-session-id");if(!sessionId){return{intent:"unknown",reasons:["DELETE requires Mcp-Session-Id header."],recommendation:{httpStatus:400,message:"Session ID required for DELETE"},debug:{key:0,channel:0,flags:0}}}return{intent:"delete-session",reasons:["DELETE with Mcp-Session-Id \u2192 session termination."],debug:{key:0,channel:0,flags:sessionId?B_HAS_SESSION:0}}}const{key,channel:channel2,flags,init}=computeBitmap(req,cfg);if(method==="POST"&&channel2!==CH_POST_MESSAGE){const accept=h(req,"accept");const acceptsSSE=wantsSSE(accept);const acceptsJSON=wantsJSON(accept)||!accept&&cfg.tolerateMissingAccept;if(!acceptsSSE&&!acceptsJSON){return{intent:"unknown",reasons:["Client must accept application/json or text/event-stream."],recommendation:{httpStatus:406,message:"Not acceptable"},debug:{key,channel:channel2,flags}}}}for(const rule of RULES){if((key&rule.care)===rule.match){const{reason,...rest}=rule.outcome;reasons.push(reason);if(init)reasons.push("Initialize body detected.");return{...rest,reasons,debug:{key,channel:channel2,flags}}}}return{intent:"unknown",reasons:["No matching rule."],recommendation:{httpStatus:500,message:"Unroutable request"},debug:{key,channel:channel2,flags}}}function authorizeSessionTermination(verifyResult,requestedSessionId){if(!verifyResult||verifyResult.kind!=="authorized"||!verifyResult.authorization){return{kind:"unauthorized"}}const ownedSessionId=verifyResult.authorization.session?.id;if(!ownedSessionId||!requestedSessionId||requestedSessionId!==ownedSessionId){return{kind:"forbidden"}}return{kind:"ok",sessionId:ownedSessionId}}var intentSchema,decisionSchema,CH_OTHER,CH_GET_SSE,CH_POST_INIT_JSON,CH_POST_INIT_SSE,CH_POST_JSON,CH_POST_SSE,CH_POST_MESSAGE,CH_GET_SSE_PATH,CH_MASK,B_HAS_SESSION,B_STATELESS_EN,B_REQ_SESSION,B_LEGACY_HINT,B_SSE_LISTENER_EN,B_STREAMABLE_EN,B_STATEFUL_EN,B_LEGACY_EN,h,wantsSSE,wantsJSON,isInitialize,RULES;var init_decide_request_intent_utils=__esm({"libs/sdk/src/common/utils/decide-request-intent.utils.ts"(){"use strict";intentSchema=z81.union([z81.literal("legacy-sse"),z81.literal("sse"),z81.literal("streamable-http"),z81.literal("stateful-http"),z81.literal("stateless-http"),z81.literal("delete-session"),z81.literal("mcp-20260728"),z81.literal("unknown")]);decisionSchema=z81.object({intent:intentSchema,reasons:z81.array(z81.string()),recommendation:z81.object({httpStatus:z81.number(),message:z81.string()}).optional(),debug:z81.object({key:z81.number(),channel:z81.number(),flags:z81.number()}).optional()});CH_OTHER=0;CH_GET_SSE=1;CH_POST_INIT_JSON=2;CH_POST_INIT_SSE=3;CH_POST_JSON=4;CH_POST_SSE=5;CH_POST_MESSAGE=6;CH_GET_SSE_PATH=7;CH_MASK=7;B_HAS_SESSION=1<<3;B_STATELESS_EN=1<<4;B_REQ_SESSION=1<<5;B_LEGACY_HINT=1<<6;B_SSE_LISTENER_EN=1<<7;B_STREAMABLE_EN=1<<8;B_STATEFUL_EN=1<<9;B_LEGACY_EN=1<<10;h=(req,name51)=>Object.entries(req.headers).find(([k])=>k.toLowerCase()===name51.toLowerCase())?.[1];wantsSSE=accept=>(accept??"").toLowerCase().includes("text/event-stream");wantsJSON=accept=>(accept??"").toLowerCase().includes("application/json");isInitialize=body=>!!body&&typeof body==="object"&&body.method==="initialize";RULES=[{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_GET_SSE_PATH|B_LEGACY_EN,outcome:{intent:"legacy-sse",reason:"GET /sse without Mcp-Session-Id \u2192 legacy SSE."}},{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_GET_SSE_PATH,outcome:{intent:"unknown",reason:"Legacy SSE disabled.",recommendation:{httpStatus:405,message:"Legacy SSE disabled"}}},{care:CH_MASK|B_HAS_SESSION|B_SSE_LISTENER_EN|B_STREAMABLE_EN,match:CH_GET_SSE|B_HAS_SESSION|B_SSE_LISTENER_EN|B_STREAMABLE_EN,outcome:{intent:"streamable-http",reason:"GET / with session ID \u2192 SSE listener for streamable-http."}},{care:CH_MASK|B_HAS_SESSION|B_SSE_LISTENER_EN,match:CH_GET_SSE|B_HAS_SESSION,outcome:{intent:"unknown",reason:"SSE listener disabled for GET / requests.",recommendation:{httpStatus:405,message:"SSE listener disabled"}}},{care:CH_MASK|B_HAS_SESSION,match:CH_GET_SSE,outcome:{intent:"unknown",reason:"GET / with SSE requires session for MCP transport."}},{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_POST_MESSAGE|B_HAS_SESSION|B_LEGACY_EN,outcome:{intent:"legacy-sse",reason:"POST /message with Mcp-Session-Id \u2192 legacy SSE bridge."}},{care:CH_MASK|B_HAS_SESSION|B_LEGACY_EN,match:CH_POST_MESSAGE|B_HAS_SESSION,outcome:{intent:"unknown",reason:"Legacy /message endpoint disabled.",recommendation:{httpStatus:405,message:"Legacy SSE disabled"}}},{care:CH_MASK|B_SSE_LISTENER_EN|B_HAS_SESSION,match:CH_GET_SSE_PATH|B_HAS_SESSION,outcome:{intent:"unknown",reason:"SSE listener disabled.",recommendation:{httpStatus:405,message:"SSE listener disabled"}}},{care:CH_MASK|B_SSE_LISTENER_EN|B_HAS_SESSION,match:CH_GET_SSE_PATH|B_SSE_LISTENER_EN|B_HAS_SESSION,outcome:{intent:"sse",reason:"GET /sse with Mcp-Session-Id."}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_INIT_SSE|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless initialize (no session)."}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_SSE,outcome:{intent:"unknown",reason:"Streamable HTTP disabled.",recommendation:{httpStatus:405,message:"Streamable HTTP disabled"}}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_SSE|B_STREAMABLE_EN,outcome:{intent:"streamable-http",reason:"Initialize with SSE."}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_INIT_JSON|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless initialize JSON (no session)."}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_JSON,outcome:{intent:"unknown",reason:"JSON mode disabled.",recommendation:{httpStatus:405,message:"JSON mode disabled"}}},{care:CH_MASK|B_STREAMABLE_EN,match:CH_POST_INIT_JSON|B_STREAMABLE_EN,outcome:{intent:"stateful-http",reason:"Initialize with JSON."}},{care:CH_MASK|B_REQ_SESSION|B_HAS_SESSION|B_STATELESS_EN,match:CH_POST_SSE|B_REQ_SESSION,outcome:{intent:"unknown",reason:"POST SSE requires session.",recommendation:{httpStatus:400,message:"Initialize required (no Mcp-Session-Id)"}}},{care:CH_MASK|B_STREAMABLE_EN|B_STATELESS_EN,match:CH_POST_SSE,outcome:{intent:"unknown",reason:"Streamable HTTP disabled.",recommendation:{httpStatus:405,message:"Streamable HTTP disabled"}}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_SSE|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless short-lived SSE."}},{care:CH_MASK,match:CH_POST_SSE,outcome:{intent:"streamable-http",reason:"Short-lived SSE for this request."}},{care:CH_MASK|B_REQ_SESSION|B_HAS_SESSION|B_STATELESS_EN,match:CH_POST_JSON|B_REQ_SESSION,outcome:{intent:"unknown",reason:"POST JSON requires session.",recommendation:{httpStatus:400,message:"Initialize required (no Mcp-Session-Id)"}}},{care:CH_MASK|B_STATEFUL_EN|B_STREAMABLE_EN|B_STATELESS_EN,match:CH_POST_JSON,outcome:{intent:"unknown",reason:"JSON mode disabled.",recommendation:{httpStatus:405,message:"JSON mode disabled"}}},{care:CH_MASK|B_HAS_SESSION|B_STATELESS_EN|B_STREAMABLE_EN,match:CH_POST_JSON|B_STATELESS_EN,outcome:{intent:"stateless-http",reason:"Stateless JSON request."}},{care:CH_MASK,match:CH_POST_JSON,outcome:{intent:"stateful-http",reason:"Aggregated JSON response."}},{care:CH_MASK,match:CH_OTHER,outcome:{intent:"unknown",reason:"Method/Accept not allowed.",recommendation:{httpStatus:405,message:"Method/Accept not allowed"}}}]}});import{isAnonymousSubject as isAnonymousSubject5}from"@frontmcp/auth";import{ConcurrencyLimitError,GuardStorageUnavailableError as GuardStorageUnavailableError2}from"@frontmcp/guard";function enforceIpFilter(scope,clientIp,buildRejection=()=>httpRespond.forbidden({body:{...IP_FILTER_REJECTION_BODY}})){const result=scope.rateLimitManager?.checkIpFilter(clientIp);if(!result||result.allowed)return;scope.logger.warn("request rejected by ipFilter",{reason:result.reason,hasClientIp:clientIp!==void 0});FlowControl.respond(buildRejection())}function buildPartitionContext(source){if(!source)return void 0;const clientId=source.authInfo?.clientId;const userId=isAnonymousSubject5(clientId)?void 0:String(clientId);const callerKey=userId?`user:${userId}`:"anonymous";return{sessionId:verifiedSessionOf(source)??callerKey,clientIp:source.metadata?.clientIp,userId}}function verifiedSessionOf(source){if("verifiedSessionId"in source)return source.verifiedSessionId;const confirmed=source.authInfo?.sessionId??source.authInfo?.extra?.sessionId;return confirmed===source.sessionId?source.sessionId:void 0}function partitionsByIdentity(partitionBy){return partitionBy==="session"||partitionBy==="userId"||typeof partitionBy==="function"}async function enforceGlobalRateLimit(scope,context){const manager=scope.rateLimitManager;const globalConfig=manager?.config?.global;const partitionBy=globalConfig?.partitionBy;if(!manager||!globalConfig||partitionBy==="session"||partitionBy==="userId")return;let result;try{result=await manager.checkGlobalRateLimit(buildPartitionContext(context))}catch(error){if(!(error instanceof GuardStorageUnavailableError2))throw error;FlowControl.respond(httpRespond.json({error:"service_unavailable",message:"Service temporarily unavailable: the rate-limit store cannot be reached",code:error.code},{status:error.statusCode,headers:{"Retry-After":"1"}}))}context?.set(GLOBAL_RATE_LIMIT_CHECKED,true);if(result.allowed)return;const retryAfter=Math.ceil((result.retryAfterMs??6e4)/1e3);FlowControl.respond(httpRespond.json({error:"rate_limited",message:`Rate limit exceeded. Retry after ${retryAfter} seconds`},{status:429,headers:{"Retry-After":String(retryAfter)}}))}async function acquireConcurrencySlots(manager,entityName,entityConfig,partitionContext,options={}){const globalConfig=options.skipGlobal?void 0:manager.config.globalConcurrency;const globalTicket=globalConfig?await manager.acquireGlobalSemaphore(partitionContext):null;if(globalConfig&&!globalTicket){throw new ConcurrencyLimitError("global",globalConfig.maxConcurrent)}const config=entityConfig??manager.config.defaultConcurrency;if(!config)return globalTicket??void 0;let entityTicket;try{entityTicket=await manager.acquireSemaphore(entityName,config,partitionContext)}catch(error){await globalTicket?.release();throw error}if(!entityTicket){await globalTicket?.release();throw new ConcurrencyLimitError(entityName,config.maxConcurrent)}if(!globalTicket)return entityTicket;const heldEntityTicket=entityTicket;return{ticket:heldEntityTicket.ticket,release:async()=>{try{await heldEntityTicket.release()}finally{await globalTicket.release()}}}}var IP_FILTER_REJECTION_BODY,GLOBAL_RATE_LIMIT_CHECKED;var init_guard_utils=__esm({"libs/sdk/src/common/utils/guard.utils.ts"(){"use strict";init_flow_interface();init_http_output_schema();IP_FILTER_REJECTION_BODY={error:"forbidden",message:"Client IP rejected by ipFilter"};GLOBAL_RATE_LIMIT_CHECKED=Symbol.for("frontmcp:guard:global-rate-limit-checked")}});function getGlobalStoreConfig(pluginName,config){if(!config.redis){throw new GlobalConfigNotFoundError(pluginName,"redis")}return config.redis}var init_global_config_utils=__esm({"libs/sdk/src/common/utils/global-config.utils.ts"(){"use strict";init_errors()}});function matchPattern(name51,pattern){if(pattern==="*")return true;if(!pattern.includes("*"))return name51===pattern;const segments=pattern.split("*");let pos=0;for(let i=0;i<segments.length;i++){const seg=segments[i];if(i===0){if(!name51.startsWith(seg))return false;pos=seg.length}else if(i===segments.length-1){if(!name51.endsWith(seg))return false;if(name51.length-seg.length<pos)return false}else{const idx=name51.indexOf(seg,pos);if(idx===-1)return false;pos=idx+seg.length}}return true}function matchesAny(name51,patterns){return patterns.some(p=>matchPattern(name51,p))}function isPrimitiveIncluded(name51,primitiveType,config){if(!config)return true;if((config.default??"include")==="include"){return!matchesAny(name51,config.exclude?.[primitiveType]??[])}return matchesAny(name51,config.include?.[primitiveType]??[])}function applyPrimitiveFilter(items,primitiveType,config){return items.filter(item=>isPrimitiveIncluded(item.name,primitiveType,config))}var init_primitive_filter=__esm({"libs/sdk/src/common/utils/primitive-filter.ts"(){"use strict"}});var init_utils3=__esm({"libs/sdk/src/common/utils/index.ts"(){"use strict";init_auth_info_utils();init_caller_dir_utils();init_decide_request_intent_utils();init_guard_utils();init_path_utils();init_principal_utils();init_global_config_utils();init_primitive_filter();init_validate_remote_url()}});var FrontMcpAuth;var init_primary_auth_provider_interface=__esm({"libs/sdk/src/common/interfaces/internal/primary-auth-provider.interface.ts"(){"use strict";init_types();init_utils3();FrontMcpAuth=class{ready;options;id;constructor(options){this.options=options;this.id=this.deriveId(options)}deriveId(options){if(isPublicMode(options)){return options.issuer??"public"}if(isTransparentMode(options)){return options.providerConfig?.id??urlToSafeId(options.provider)}if(isOrchestratedMode(options)){if(isOrchestratedRemote(options)){return options.providerConfig?.id??urlToSafeId(options.provider)}return options.local?.issuer??"local"}return"unknown"}verifyGatewayToken(_token,_requestBaseUrl,_expectedAudience,_expectedIssuer){return Promise.resolve({ok:false,error:"gateway token verification is not supported by this auth mode"})}}}});var init_registry_interface=__esm({"libs/sdk/src/common/interfaces/internal/registry.interface.ts"(){"use strict"}});var init_internal=__esm({"libs/sdk/src/common/interfaces/internal/index.ts"(){"use strict";init_primary_auth_provider_interface();init_registry_interface()}});var init_interfaces2=__esm({"libs/sdk/src/common/interfaces/index.ts"(){"use strict";init_base_interface();init_execution_context_interface();init_front_mcp_interface();init_server_interface();init_scope_interface();init_flow_interface();init_hook_interface();init_app_interface();init_provider_interface();init_auth_provider_interface();init_adapter_interface();init_plugin_interface();init_tool_interface();init_resource_interface();init_prompt_interface();init_logger_interface();init_llm_adapter_interface();init_agent_interface();init_skill_interface();init_job_interface();init_workflow_interface();init_channel_interface();init_duty_interface();init_http_route_interface();init_internal()}});var JobRunResource;var init_job_run_resource=__esm({"libs/sdk/src/job/resources/job-run.resource.ts"(){"use strict";init_common();init_interfaces2();init_errors();init_job_run_access();JobRunResource=class extends ResourceContext{async execute(uri,{runId}){const record=await jobExecutionManagerOf(this.scope)?.getStatus(runId);if(!record||!await mayAccessRun(this.scope,record,"read",this.getAuthInfo())){throw new ResourceNotFoundError(uri)}const run={runId:record.runId,jobName:record.jobName,state:record.state,attempt:record.attempt,maxAttempts:record.maxAttempts,startedAt:record.startedAt,completedAt:record.completedAt,updatedAt:record.updatedAt,revision:record.revision,progress:record.progress,result:record.result,error:record.error&&{name:record.error.name,message:record.error.message},logs:record.logs};return{contents:[{uri,mimeType:"application/json",text:JSON.stringify(run)}]}}};JobRunResource=__decorateClass([_ResourceTemplate({name:"job-run",uriTemplate:"job://runs/{runId}",description:"A job or workflow run: its state, progress, result or error, revision and last update",mimeType:"application/json"})],JobRunResource)}});var MemoryJobStateStore;var init_memory_job_state_store=__esm({"libs/sdk/src/job/store/memory-job-state.store.ts"(){"use strict";MemoryJobStateStore=class{runs=new Map;cancelRequests=new Set;runnerExpiries=new Map;claims=new Set;async createRun(record){this.runs.set(record.runId,{...record,revision:1,updatedAt:Date.now()})}async updateRun(runId,updates){const existing=this.runs.get(runId);if(!existing)return;const{runId:_ignoreRunId,...safeUpdates}=updates;const revision=(existing.revision??0)+1;this.runs.set(runId,{...existing,...safeUpdates,revision,updatedAt:Date.now()})}async getRun(runId){const record=this.runs.get(runId);return record?{...record}:null}async listRuns(opts){let results=[...this.runs.values()];if(opts?.jobId){results=results.filter(r=>r.jobId===opts.jobId)}if(opts?.sessionId){results=results.filter(r=>r.sessionId===opts.sessionId)}if(opts?.state){results=results.filter(r=>r.state===opts.state)}results.sort((a,b)=>b.startedAt-a.startedAt);if(opts?.limit!==void 0&&opts.limit>0){results=results.slice(0,opts.limit)}return results.map(r=>({...r}))}async cleanup(olderThanMs){const cutoff=Date.now()-olderThanMs;let removed=0;for(const[runId,record]of this.runs){if(record.startedAt<cutoff){this.runs.delete(runId);removed++}}return removed}async requestCancel(runId){this.cancelRequests.add(runId)}async isCancelRequested(runId){return this.cancelRequests.has(runId)}async touchRunner(runnerId,ttlSeconds){this.runnerExpiries.set(runnerId,Date.now()+ttlSeconds*1e3)}async isRunnerAlive(runnerId){return(this.runnerExpiries.get(runnerId)??0)>Date.now()}async claimRun(runId){if(this.claims.has(runId))return false;this.claims.add(runId);return true}async dispose(){this.runs.clear();this.cancelRequests.clear();this.runnerExpiries.clear();this.claims.clear()}}}});var RedisJobStateStore;var init_redis_job_state_store=__esm({"libs/sdk/src/job/store/redis-job-state.store.ts"(){"use strict";RedisJobStateStore=class{client;keyPrefix;logger;ttlSeconds;ownsClient;constructor(client,logger,keyPrefix="mcp:jobs:",ttlSeconds=86400,options={}){this.client=client;this.logger=logger;this.keyPrefix=keyPrefix;this.ttlSeconds=ttlSeconds;this.ownsClient=options.ownsClient??false}key(runId){return`${this.keyPrefix}run:${runId}`}indexKey(field,value){return`${this.keyPrefix}idx:${field}:${value}`}cancelKey(runId){return`${this.keyPrefix}cancel:${runId}`}async createRun(record){const key=this.key(record.runId);const data=JSON.stringify({...record,revision:1,updatedAt:Date.now()});await this.client.set(key,data,"EX",this.ttlSeconds);if(record.jobId)await this.index(this.indexKey("jobId",record.jobId),record.runId);if(record.sessionId)await this.index(this.indexKey("sessionId",record.sessionId),record.runId)}async index(key,runId){await this.client.sadd(key,runId);await this.client.expire?.(key,this.ttlSeconds)}async updateRun(runId,updates){const key=this.key(runId);const raw=await this.client.get(key);if(!raw)return;const existing=JSON.parse(raw);const{runId:_ignoreRunId,...safeUpdates}=updates;const updated={...existing,...safeUpdates,revision:(existing.revision??0)+1,updatedAt:Date.now()};await this.client.set(key,JSON.stringify(updated),"EX",this.ttlSeconds)}async getRun(runId){const raw=await this.client.get(this.key(runId));if(!raw)return null;return JSON.parse(raw)}async listRuns(opts){let runIds;if(opts?.jobId){runIds=await this.client.smembers(this.indexKey("jobId",opts.jobId))}else if(opts?.sessionId){runIds=await this.client.smembers(this.indexKey("sessionId",opts.sessionId))}else{const keys=await this.client.keys(`${this.keyPrefix}run:*`);runIds=keys.map(k=>k.replace(`${this.keyPrefix}run:`,""))}const results=[];for(const runId of runIds){const record=await this.getRun(runId);if(!record)continue;if(opts?.state&&record.state!==opts.state)continue;results.push(record)}results.sort((a,b)=>b.startedAt-a.startedAt);if(opts?.limit){return results.slice(0,opts.limit)}return results}async cleanup(olderThanMs){const cutoff=Date.now()-olderThanMs;const keys=await this.client.keys(`${this.keyPrefix}run:*`);let removed=0;for(const key of keys){const raw=await this.client.get(key);if(!raw)continue;const record=JSON.parse(raw);if(record.startedAt<cutoff){await this.client.del(key);const runId=key.replace(`${this.keyPrefix}run:`,"");if(record.jobId){await this.client.srem(this.indexKey("jobId",record.jobId),runId)}if(record.sessionId){await this.client.srem(this.indexKey("sessionId",record.sessionId),runId)}removed++}}return removed}async requestCancel(runId){await this.client.set(this.cancelKey(runId),"1","EX",this.ttlSeconds)}async isCancelRequested(runId){return await this.client.get(this.cancelKey(runId))!==null}async touchRunner(runnerId,ttlSeconds){await this.client.set(`${this.keyPrefix}runner:${runnerId}`,"1","EX",ttlSeconds)}async isRunnerAlive(runnerId){return await this.client.get(`${this.keyPrefix}runner:${runnerId}`)!==null}async claimRun(runId){return await this.client.set(`${this.keyPrefix}claim:${runId}`,"1","NX","EX",this.ttlSeconds)==="OK"}async dispose(){if(!this.ownsClient)return;this.ownsClient=false;try{await this.client.quit?.()}catch(error){const message=error instanceof Error?error.message:String(error);this.logger?.warn(`Could not close the job state store's redis client: ${message}`)}}}}});function runKey(runId){return`run:${runId}`}function cancelKey(runId){return`cancel:${runId}`}function runnerKey(runnerId){return`runner:${runnerId}`}function claimKey(runId){return`claim:${runId}`}var StorageJobStateStore;var init_storage_job_state_store=__esm({"libs/sdk/src/job/store/storage-job-state.store.ts"(){"use strict";StorageJobStateStore=class{constructor(storage,ttlSeconds=86400){this.storage=storage;this.ttlSeconds=ttlSeconds}storage;ttlSeconds;async createRun(record){await this.write({...record,revision:1,updatedAt:Date.now()})}async updateRun(runId,updates){const existing=await this.getRun(runId);if(!existing)return;const{runId:_ignoreRunId,...safeUpdates}=updates;await this.write({...existing,...safeUpdates,revision:(existing.revision??0)+1,updatedAt:Date.now()})}async getRun(runId){const raw=await this.storage.get(runKey(runId));return raw?JSON.parse(raw):null}async listRuns(opts){const runs=(await this.allRuns()).filter(run=>(!opts?.jobId||run.jobId===opts.jobId)&&(!opts?.sessionId||run.sessionId===opts.sessionId)&&(!opts?.state||run.state===opts.state));runs.sort((a,b)=>b.startedAt-a.startedAt);return opts?.limit!==void 0&&opts.limit>0?runs.slice(0,opts.limit):runs}async cleanup(olderThanMs){const cutoff=Date.now()-olderThanMs;const stale=(await this.allRuns()).filter(run=>run.startedAt<cutoff);if(stale.length>0){await this.storage.mdelete(stale.flatMap(run=>[runKey(run.runId),cancelKey(run.runId),claimKey(run.runId)]))}return stale.length}async requestCancel(runId){await this.storage.set(cancelKey(runId),"1",{ttlSeconds:this.ttlSeconds})}async isCancelRequested(runId){return this.storage.exists(cancelKey(runId))}async touchRunner(runnerId,ttlSeconds){await this.storage.set(runnerKey(runnerId),"1",{ttlSeconds})}async isRunnerAlive(runnerId){return this.storage.exists(runnerKey(runnerId))}async claimRun(runId){const claimed=await this.storage.incr(claimKey(runId))===1;if(claimed)await this.storage.expire(claimKey(runId),this.ttlSeconds);return claimed}async dispose(){await this.storage.disconnect()}async write(record){await this.storage.set(runKey(record.runId),JSON.stringify(record),{ttlSeconds:this.ttlSeconds})}async allRuns(){const keys=await this.storage.keys("run:*");if(keys.length===0)return[];const values=await this.storage.mget(keys);return values.filter(raw=>raw!==null).map(raw=>JSON.parse(raw))}}}});import{createRedisClient,createStorage as createStorage2,StorageConfigError}from"@frontmcp/utils";function refuseVercelKvJobStore(redis){if(redis?.provider!=="vercel-kv")return;throw new JobStoreNotSupportedError("Vercel KV is not supported for job stores: jobs.store.redis is opened over the Redis protocol, which Vercel KV does not serve. Use a Redis server, jobs.store.sqlite, or jobs.store: false.")}async function createJobStateStore(options,logger){const keyPrefix=options?.keyPrefix??"mcp:jobs:";const ttlSeconds=options?.ttlSeconds??86400;if(options?.sqlite){const storage=await createStorage2({type:"sqlite",sqlite:options.sqlite,prefix:keyPrefix,fallback:"error"});return{store:new StorageJobStateStore(storage,ttlSeconds),type:"sqlite"}}if(options?.redis){refuseVercelKvJobStore(options.redis);try{const{url,host,port,password,db,tls}=options.redis;const client=createRedisClient({url,host,port,password,db,tls,label:"JobStateStore",logger});return{store:new RedisJobStateStore(client,logger,keyPrefix,ttlSeconds,{ownsClient:true}),type:"redis"}}catch(err){if(err instanceof StorageConfigError)throw err;logger?.warn?.(`Failed to create Redis job state store, falling back to memory: ${err}`)}}return{store:new MemoryJobStateStore,type:"memory"}}var init_job_state_store_factory=__esm({"libs/sdk/src/job/store/job-state-store.factory.ts"(){"use strict";init_job_errors();init_memory_job_state_store();init_redis_job_state_store();init_storage_job_state_store()}});var MemoryJobDefinitionStore;var init_memory_job_definition_store=__esm({"libs/sdk/src/job/store/memory-job-definition.store.ts"(){"use strict";MemoryJobDefinitionStore=class{jobs=new Map;workflows=new Map;async saveDefinition(record){this.jobs.set(record.provide,{...record})}async getDefinition(jobId){return this.jobs.get(jobId)??null}async listDefinitions(){return[...this.jobs.values()]}async removeDefinition(jobId){return this.jobs.delete(jobId)}async saveWorkflowDefinition(record){this.workflows.set(record.provide,{...record})}async getWorkflowDefinition(wfId){return this.workflows.get(wfId)??null}async listWorkflowDefinitions(){return[...this.workflows.values()]}async removeWorkflowDefinition(wfId){return this.workflows.delete(wfId)}async dispose(){this.jobs.clear();this.workflows.clear()}}}});var RedisJobDefinitionStore;var init_redis_job_definition_store=__esm({"libs/sdk/src/job/store/redis-job-definition.store.ts"(){"use strict";RedisJobDefinitionStore=class{client;keyPrefix;logger;ownsClient;disposed=false;constructor(client,logger,keyPrefix="mcp:jobs:def:",options={}){this.client=client;this.logger=logger;this.keyPrefix=keyPrefix;this.ownsClient=options.ownsClient??false}safeParse(raw,jobId,kind){try{return JSON.parse(raw)}catch(e){const message=e instanceof Error?e.message:String(e);this.logger.error(`[RedisJobDefinitionStore] Failed to parse ${kind} definition for "${jobId}": ${message}; payloadLength=${raw.length}`);return null}}jobKey(jobId){return`${this.keyPrefix}job:${jobId}`}workflowKey(wfId){return`${this.keyPrefix}wf:${wfId}`}async saveDefinition(record){await this.client.set(this.jobKey(record.provide),JSON.stringify(record));await this.client.sadd(`${this.keyPrefix}jobs`,record.provide)}async getDefinition(jobId){const raw=await this.client.get(this.jobKey(jobId));if(!raw)return null;return this.safeParse(raw,jobId,"job")}async listDefinitions(){const ids=await this.client.smembers(`${this.keyPrefix}jobs`);const records=await Promise.all(ids.map(id=>this.getDefinition(id)));return records.filter(r=>r!==null)}async removeDefinition(jobId){const existed=await this.client.del(this.jobKey(jobId));await this.client.srem(`${this.keyPrefix}jobs`,jobId);return existed>0}async saveWorkflowDefinition(record){await this.client.set(this.workflowKey(record.provide),JSON.stringify(record));await this.client.sadd(`${this.keyPrefix}workflows`,record.provide)}async getWorkflowDefinition(wfId){const raw=await this.client.get(this.workflowKey(wfId));if(!raw)return null;return this.safeParse(raw,wfId,"workflow")}async listWorkflowDefinitions(){const ids=await this.client.smembers(`${this.keyPrefix}workflows`);const records=await Promise.all(ids.map(id=>this.getWorkflowDefinition(id)));return records.filter(r=>r!==null)}async removeWorkflowDefinition(wfId){const existed=await this.client.del(this.workflowKey(wfId));await this.client.srem(`${this.keyPrefix}workflows`,wfId);return existed>0}async dispose(){if(this.disposed)return;this.disposed=true;if(!this.ownsClient)return;try{if(typeof this.client.quit==="function"){await this.client.quit()}else if(typeof this.client.disconnect==="function"){this.client.disconnect()}}catch(e){this.logger.warn(`[RedisJobDefinitionStore] dispose: failed to close redis client: ${e.message}`)}}}}});var StorageJobDefinitionStore;var init_storage_job_definition_store=__esm({"libs/sdk/src/job/store/storage-job-definition.store.ts"(){"use strict";StorageJobDefinitionStore=class{constructor(storage){this.storage=storage}storage;async saveDefinition(record){await this.storage.set(`job:${record.provide}`,JSON.stringify(record))}async getDefinition(jobId){return this.read(`job:${jobId}`)}async listDefinitions(){return this.list("job:*")}async removeDefinition(jobId){return this.storage.delete(`job:${jobId}`)}async saveWorkflowDefinition(record){await this.storage.set(`wf:${record.provide}`,JSON.stringify(record))}async getWorkflowDefinition(wfId){return this.read(`wf:${wfId}`)}async listWorkflowDefinitions(){return this.list("wf:*")}async removeWorkflowDefinition(wfId){return this.storage.delete(`wf:${wfId}`)}async dispose(){await this.storage.disconnect()}async read(key){const raw=await this.storage.get(key);return raw?JSON.parse(raw):null}async list(pattern){const keys=await this.storage.keys(pattern);if(keys.length===0)return[];const values=await this.storage.mget(keys);return values.filter(raw=>raw!==null).map(raw=>JSON.parse(raw))}}}});import{createRedisClient as createRedisClient2,createStorage as createStorage3,StorageConfigError as StorageConfigError2}from"@frontmcp/utils";async function createJobDefinitionStore(options,logger){const keyPrefix=options?.keyPrefix??"mcp:jobs:def:";const effectiveLogger=logger??noopLogger;if(options?.sqlite){const storage=await createStorage3({type:"sqlite",sqlite:options.sqlite,prefix:keyPrefix,fallback:"error"});return{store:new StorageJobDefinitionStore(storage),type:"sqlite"}}if(options?.redis){refuseVercelKvJobStore(options.redis);try{const{url,host,port,password,db,tls}=options.redis;const client=createRedisClient2({url,host,port,password,db,tls,label:"JobDefinitionStore",logger:effectiveLogger});return{store:new RedisJobDefinitionStore(client,effectiveLogger,keyPrefix,{ownsClient:true}),type:"redis"}}catch(err){if(err instanceof StorageConfigError2)throw err;effectiveLogger.warn(`Failed to create Redis job definition store, falling back to memory: ${err}`)}}return{store:new MemoryJobDefinitionStore,type:"memory"}}var noopFn,noopLogger;var init_job_definition_store_factory=__esm({"libs/sdk/src/job/store/job-definition-store.factory.ts"(){"use strict";init_job_state_store_factory();init_memory_job_definition_store();init_redis_job_definition_store();init_storage_job_definition_store();noopFn=()=>{};noopLogger={child:()=>noopLogger,get verbose(){return noopFn},get debug(){return noopFn},get info(){return noopFn},get warn(){return noopFn},get error(){return noopFn}}}});import{z as z82}from"@frontmcp/lazy-zod";var CancelJobTool;var init_cancel_job_tool=__esm({"libs/sdk/src/job/tools/cancel-job.tool.ts"(){"use strict";init_common();init_errors();init_job_run_access();CancelJobTool=class extends ToolContext{async execute(input){const executionManager=jobExecutionManagerOf(this.scope);if(!executionManager){return this.fail(new GenericServerError("Jobs system is not enabled"))}const record=await executionManager.getStatus(input.runId);if(!record||!await mayAccessRun(this.scope,record,"delete",this.authInfo)){return this.fail(new JobRunNotFoundError(input.runId))}await executionManager.cancel(input.runId);return{runId:input.runId,state:"cancelled"}}};CancelJobTool=__decorateClass([Tool({name:"cancel_job",description:"Cancel a job run by runId. The cancel is kept in the job store, so the process running it stops it, and its cleanup runs.",inputSchema:{runId:z82.string().describe("Run ID returned from execute_job")},outputSchema:{runId:z82.string(),state:z82.literal("cancelled")}})],CancelJobTool)}});import{internalZ as z83}from"@frontmcp/lazy-zod";var ExecuteJobTool;var init_execute_job_tool=__esm({"libs/sdk/src/job/tools/execute-job.tool.ts"(){"use strict";init_common();init_errors();init_job_run_access();ExecuteJobTool=class extends ToolContext{async execute(input){const scope=this.scope;const executionManager=scope._jobExecutionManager;const jobRegistry=this.scope.jobs;if(!executionManager||!jobRegistry){return this.fail(new Error("Jobs system is not enabled"))}const job=jobRegistry.findByName(input.name);if(!job){return this.fail(new JobNotAuthorizedError(input.name))}const result=await executionManager.executeJob(job,input.input??{},{background:input.background,sessionId:this.authInfo.sessionId,authInfo:this.authInfo,context:this.context,authoritiesContextBuilder:this.scope.authoritiesContextBuilder});return{...result,uri:jobRunUri(result.runId)}}};ExecuteJobTool=__decorateClass([Tool({name:"execute_job",description:"Execute a registered job by name. Supports inline (synchronous) and background execution; a background run answers at once with its runId and the job://runs/{runId} resource to read or subscribe to.",inputSchema:{name:z83.string().describe("Job name to execute"),input:z83.record(z83.string(),z83.unknown()).optional().describe("Job input data"),background:z83.boolean().optional().default(false).describe("Run in background (returns runId for status polling)")},outputSchema:{runId:z83.string(),state:z83.string(),uri:z83.string().describe("The job://runs/{runId} resource of the run"),result:z83.unknown().optional(),logs:z83.array(z83.string()).optional()}})],ExecuteJobTool)}});import{internalZ as z84}from"@frontmcp/lazy-zod";var GetJobStatusTool;var init_get_job_status_tool=__esm({"libs/sdk/src/job/tools/get-job-status.tool.ts"(){"use strict";init_common();init_errors();init_job_run_access();GetJobStatusTool=class extends ToolContext{async execute(input){const scope=this.scope;const executionManager=scope._jobExecutionManager;if(!executionManager){return this.fail(new GenericServerError("Jobs system is not enabled"))}const record=await executionManager.getStatus(input.runId);if(!record||!await mayAccessRun(this.scope,record,"read",this.authInfo)){return this.fail(new InvalidInputError(`Run "${input.runId}" not found`))}return{runId:record.runId,jobName:record.jobName,state:record.state,result:record.result,error:record.error,startedAt:record.startedAt,completedAt:record.completedAt,attempt:record.attempt,logs:record.logs}}};GetJobStatusTool=__decorateClass([Tool({name:"get_job_status",description:"Get the execution status of a job run by runId.",inputSchema:{runId:z84.string().describe("Run ID returned from execute_job or execute_workflow")},outputSchema:{runId:z84.string(),jobName:z84.string(),state:z84.string(),result:z84.unknown().optional(),error:z84.object({message:z84.string(),name:z84.string()}).optional(),startedAt:z84.number(),completedAt:z84.number().optional(),attempt:z84.number(),logs:z84.array(z84.string())}})],GetJobStatusTool)}});import{internalZ as z85}from"@frontmcp/lazy-zod";var ListJobsTool;var init_list_jobs_tool=__esm({"libs/sdk/src/job/tools/list-jobs.tool.ts"(){"use strict";init_common();init_job_permission_guard();ListJobsTool=class extends ToolContext{async execute(input){const jobRegistry=this.scope.jobs;if(!jobRegistry){return{jobs:[],count:0}}const jobs=jobRegistry.search(input.query,{tags:input.tags,labels:input.labels});const visible=[];for(const job of jobs){if(await this.maySee(job))visible.push(job)}const mapped=visible.map(j=>({name:j.name,description:j.metadata.description,tags:j.getTags(),labels:j.getLabels(),inputSchema:j.getInputJsonSchema()??void 0}));return{jobs:mapped,count:mapped.length}}async maySee(job){const permissions=job.metadata.permissions;const builder=this.scope.authoritiesContextBuilder;if(!await JobPermissionGuard.check(permissions,"list",this.authInfo,builder))return false;return JobPermissionGuard.check(permissions,"execute",this.authInfo,builder)}};ListJobsTool=__decorateClass([Tool({name:"list_jobs",description:"List registered jobs with optional filtering by tags or labels.",inputSchema:{tags:z85.array(z85.string()).optional().describe("Filter by tags"),labels:z85.record(z85.string(),z85.string()).optional().describe("Filter by labels"),query:z85.string().optional().describe("Search query for name/description")},outputSchema:{jobs:z85.array(z85.object({name:z85.string(),description:z85.string().optional(),tags:z85.array(z85.string()).optional(),labels:z85.record(z85.string(),z85.string()).optional(),inputSchema:z85.record(z85.string(),z85.unknown()).optional()})),count:z85.number()},hideFromDiscovery:true})],ListJobsTool)}});import{internalZ as z86}from"@frontmcp/lazy-zod";var RegisterJobTool;var init_register_job_tool=__esm({"libs/sdk/src/job/tools/register-job.tool.ts"(){"use strict";init_common();init_errors();RegisterJobTool=class extends ToolContext{async execute(input){const jobRegistry=this.scope.jobs;if(!jobRegistry){return this.fail(new Error("Jobs system is not enabled"))}if(!this.dynamicRegistrationEnabled()){return this.fail(new DynamicJobRegistrationDisabledError("job"))}const existing=jobRegistry.findByName(input.name);if(existing){return this.fail(new Error(`Job "${input.name}" already exists`))}const jobId=input.name;jobRegistry.registerDynamic({kind:"DYNAMIC",provide:jobId,metadata:{id:jobId,name:input.name,description:input.description,inputSchema:input.inputSchema??{},outputSchema:input.outputSchema??{},tags:input.tags},script:input.script,registeredBy:this.authInfo?.["sub"]??"anonymous",registeredAt:Date.now()});return{success:true,jobId}}dynamicRegistrationEnabled(){const jobs=this.scope.metadata?.jobs;return jobs?.allowDynamicRegistration===true}};RegisterJobTool=__decorateClass([Tool({name:"register_job",description:"Register a dynamic job that runs in a sandboxed environment.",inputSchema:{name:z86.string().describe("Job name"),description:z86.string().optional().describe("Job description"),script:z86.string().describe("JavaScript source code for the job"),inputSchema:z86.record(z86.string(),z86.unknown()).optional().describe("JSON Schema for input"),outputSchema:z86.record(z86.string(),z86.unknown()).optional().describe("JSON Schema for output"),tags:z86.array(z86.string()).optional().describe("Tags for categorization")},outputSchema:{success:z86.boolean(),jobId:z86.string()},hideFromDiscovery:true})],RegisterJobTool)}});import{internalZ as z87}from"@frontmcp/lazy-zod";var RemoveJobTool;var init_remove_job_tool=__esm({"libs/sdk/src/job/tools/remove-job.tool.ts"(){"use strict";init_common();init_errors();init_job_permission_guard();RemoveJobTool=class extends ToolContext{async execute(input){const jobRegistry=this.scope.jobs;if(!jobRegistry){return this.fail(new Error("Jobs system is not enabled"))}const job=jobRegistry.findByName(input.name);if(!job){return this.fail(new JobNotAuthorizedError(input.name))}const allowed=await JobPermissionGuard.check(job.metadata.permissions,"delete",this.authInfo,this.scope.authoritiesContextBuilder);if(!allowed){return this.fail(new JobNotAuthorizedError(input.name))}if(!job.isDynamic()){return this.fail(new Error(`Job "${input.name}" is not a dynamic job and cannot be removed`))}const removed=jobRegistry.removeDynamic(input.name);return{success:removed,message:removed?`Job "${input.name}" removed`:`Failed to remove job "${input.name}"`}}};RemoveJobTool=__decorateClass([Tool({name:"remove_job",description:"Remove a dynamic job by name.",inputSchema:{name:z87.string().describe("Job name to remove")},outputSchema:{success:z87.boolean(),message:z87.string()},hideFromDiscovery:true})],RemoveJobTool)}});var job_scope_helper_exports={};__export(job_scope_helper_exports,{jobsServerStore:()=>jobsServerStore,registerJobCapabilities:()=>registerJobCapabilities,resolveJobsStore:()=>resolveJobsStore});function resolveJobsStore(store,topLevel){if(store===false)return void 0;if(store?.redis||store?.sqlite)return store;const redis=topLevel.redis;if(redis&&!isVercelKv(redis)){const keyPrefix=store?.keyPrefix??(redis.keyPrefix===void 0?void 0:`${redis.keyPrefix}jobs:`);return{...store,redis,...keyPrefix===void 0?{}:{keyPrefix}}}if(topLevel.sqlite)return{...store,sqlite:topLevel.sqlite};return store}function jobsServerStore(store,topLevel){if(store===false)return void 0;if(store?.sqlite)return"jobs.store.sqlite";if(store?.redis)return"jobs.store.redis";if(topLevel.redis&&!isVercelKv(topLevel.redis))return"redis";return topLevel.sqlite?"sqlite":void 0}function isVercelKv(redis){return"provider"in redis&&redis.provider==="vercel-kv"}async function registerJobCapabilities(args){const{providers,flowRegistry,owner,jobsList,jobProviders,workflowsList,jobsConfig,logger,notifyFn}=args;const{entryServer=false,jobWorker=false}=args;await flowRegistry.registryFlows([ExecuteJobFlow]);const{redis,sqlite,keyPrefix="mcp:jobs:"}=jobsConfig.store||{};const{store:stateStore,type:stateStoreType}=await createJobStateStore({redis,sqlite,keyPrefix},logger);logger.info(`Job state store: ${stateStoreType}`);const{store:definitionStore,type:defStoreType}=await createJobDefinitionStore({redis,sqlite,keyPrefix:keyPrefix+"def:"},logger);logger.info(`Job definition store: ${defStoreType}`);const dynamicJobs=await definitionStore.listDefinitions();const dynamicWorkflows=await definitionStore.listWorkflowDefinitions();const jobRegistry=new JobRegistry(providers,jobsList,owner,jobProviders);await jobRegistry.ready;for(const dynJob of dynamicJobs){jobRegistry.registerDynamic(dynJob)}const workflowRegistry=new WorkflowRegistry(providers,workflowsList,owner);await workflowRegistry.ready;for(const dynWf of dynamicWorkflows){workflowRegistry.registerDynamic(dynWf)}try{assertRunnersAvailable(jobRegistry.getJobs(),jobsConfig.runner)}catch(error){await stateStore.dispose();await definitionStore.dispose();throw error}const scope=providers.getActiveScope();const completions=completionEventsOf(scope);const executionManager=new JobExecutionManager(stateStore,logger,async data=>{await notifyFn?.(data);await publishJobCompletion(data,stateStore,completions)},scope,{defaultTimeoutMs:jobsConfig.defaultTimeoutMs,admission:jobsConfig.admission?new JobAdmission(jobsConfig.admission):void 0,cancelPollMs:stateStoreType==="memory"?void 0:jobWorker?DETACHED_FLUSH_MS:CANCEL_POLL_MS,runner:jobsConfig.runner,findJob:name51=>jobRegistry.findByName(name51),detachedUnavailable:detachedUnavailable(stateStoreType,!entryServer&&!jobWorker)});scope.onDispose(async()=>{await executionManager.dispose(providers.shutdownHookTimeoutMs);await stateStore.dispose();await definitionStore.dispose()});scope.resources.registerDynamicResource(JobRunResource);if(stateStoreType!=="memory"&&!jobWorker){void executionManager.reconcile().catch(error=>logger.warn(`Could not reconcile the job runs in the store: ${String(error)}`))}const managementTools=[ListJobsTool,ExecuteJobTool,GetJobStatusTool,CancelJobTool,RemoveJobTool,ListWorkflowsTool,ExecuteWorkflowTool,GetWorkflowStatusTool,RemoveWorkflowTool];if(jobsConfig.allowDynamicRegistration===true){managementTools.push(RegisterJobTool,RegisterWorkflowTool);logger.warn("Dynamic job registration is ENABLED: register_job/register_workflow accept a raw script and register it as an executable job.")}logger.info(`Jobs initialized: ${jobRegistry.getJobs().length} jobs, ${workflowRegistry.getWorkflows().length} workflows`);return{jobRegistry,workflowRegistry,executionManager,stateStore,definitionStore,managementTools}}function detachedUnavailable(storeType,inProcess){if(inProcess){return{why:"this server was not started by an entry a detached process can run again (bootstrap(), runStdio(), runUnixSocket() or @FrontMcp), as an in-process server (create(), createDirect(), connect(), the generated CLI) is not",remedy:"Start the server from its entry (node dist/main.js, frontmcp dev), or set runner: 'inline' on the job"}}if(storeType==="memory"){return{why:"job runs are kept in this process memory, which a detached process cannot read",remedy:"Give jobs a store other processes share: jobs.store.sqlite, or a top-level sqlite or redis without jobs.store: false"}}return void 0}async function publishJobCompletion(data,stateStore,completions){const{type,state,runId}=data;if(type!=="job:status"&&type!=="workflow:status")return;const status=completionStatusOf(state);if(!status||typeof runId!=="string")return;const run=await stateStore.getRun(runId);if(!run)return;const workflowName=type==="workflow:status"?run.workflowName:void 0;completions.jobs.emit({jobName:workflowName??run.jobName,jobId:run.jobId,status,...run.completedAt!==void 0?{durationMs:run.completedAt-run.startedAt}:{},...status==="success"?{output:completionOutputText(run.result)}:{error:run.error?.message},attempt:run.attempt,...run.sessionId?{sessionId:run.sessionId}:{}})}function completionStatusOf(state){switch(state){case"completed":return"success";case"failed":case"interrupted":return"error";case"timed_out":return"timeout";case"cancelled":return"cancelled";default:return void 0}}var CANCEL_POLL_MS;var init_job_scope_helper=__esm({"libs/sdk/src/job/job-scope.helper.ts"(){"use strict";init_completion_events();init_execute_workflow_tool();init_get_workflow_status_tool();init_list_workflows_tool();init_register_workflow_tool();init_remove_workflow_tool();init_workflow_registry();init_job_execution_manager();init_execute_job_flow();init_job_admission();init_job_registry();init_job_run_resource();init_job_runner();init_job_definition_store_factory();init_job_state_store_factory();init_cancel_job_tool();init_execute_job_tool();init_get_job_status_tool();init_list_jobs_tool();init_register_job_tool();init_remove_job_tool();CANCEL_POLL_MS=1e3}});import{getMetadata as getMetadata16,isClass as isClass14}from"@frontmcp/di";import{getRuntimeContext as getRuntimeContext14,isProduction as isProduction5}from"@frontmcp/utils";function isVercelKv2(redis){return redis?.provider==="vercel-kv"}function redisOf(ownRedis,ownRedisOption,server){return ownRedis?[ownRedisOption,ownRedis]:["redis",server.redis]}function redisElseSqlite([option,redis],server){if(redis)return isVercelKv2(redis)?void 0:option;return server.sqlite?"sqlite":void 0}function tasksServerStore(options){const{tasks}=options;if(tasks?.enabled===false||tasks?.store===false)return void 0;if(tasks?.sqlite)return"tasks.sqlite";return redisElseSqlite(redisOf(tasks?.redis,"tasks.redis",options),options)}function elicitationServerStore(options){const{elicitation}=options;if(!elicitation?.enabled||elicitation.store===false)return void 0;return redisElseSqlite(redisOf(elicitation.redis,"elicitation.redis",options),options)}async function questionsStore(options){const{elicitation}=options;if(!elicitation?.enabled||!elicitation.persistent)return void 0;const questions=await Promise.resolve().then(()=>(init_question_scope_helper(),question_scope_helper_exports));const{storage}=questions.persistentQuestionsSettings(elicitation.persistent,false);return questions.questionsServerStore(storage,options)}function declaredOnApps(options,token){return(options.apps??[]).flatMap(app=>isClass14(app)?getMetadata16(token,app)??[]:[])}async function jobsStore(options){const{jobs}=options;const declared=[...options.jobTypes??[],...options.workflowTypes??[],...declaredOnApps(options,FrontMcpLocalAppTokens.jobs),...declaredOnApps(options,FrontMcpLocalAppTokens.workflows)];if(jobs?.enabled===false||jobs?.enabled!==true&&declared.length===0)return void 0;const{jobsServerStore:jobsServerStore2}=await Promise.resolve().then(()=>(init_job_scope_helper(),job_scope_helper_exports));return jobsServerStore2(jobs?.store,options)}function guardServerStore(storage){const type=storage?.type;const callerClient=storage?.redis?.client;if(type==="sqlite"||type==="redis"&&callerClient===void 0){return`throttle.storage: { type: '${type}' }`}return void 0}function guardFallsBackToMemory(storage){return(storage.fallback??(isProduction5()?"error":"memory"))==="memory"}function rateLimitsStore({throttle,auth}){const publicAccess=auth?.publicAccess;const publicRateLimited=publicAccess!==void 0&&publicAccess.rateLimit!==0;const storage=throttle?.enabled||publicRateLimited?throttle?.storage:void 0;const store=guardServerStore(storage);return store&&storage&&!guardFallsBackToMemory(storage)?store:void 0}function guardStorageInBrowser(storage,logger,runtime=getRuntimeContext14().runtime){if(runtime!=="browser"||!storage)return storage;const store=guardServerStore(storage);if(!store||!guardFallsBackToMemory(storage))return storage;logger.warn(`A browser cannot open Redis or SQLite: rate limits use per-instance counters in place of ${store} (throttle.storage.fallback: 'memory')`);return{...storage,type:"memory"}}function authStore({auth},setting){const value=auth&&setting in auth?auth[setting]:void 0;if(typeof value!=="object"||value===null)return void 0;const{redis,sqlite}=value;if(redis!==void 0)return`auth.${setting}.redis`;return sqlite!==void 0?`auth.${setting}.sqlite`:void 0}function skillsCacheStore({skillsConfig}){const cache2=skillsConfig?.cache;return cache2?.enabled&&cache2.redis?.provider==="redis"?"skillsConfig.cache.redis":void 0}function declaredPluginStores(plugin,options,server){const declare=plugin?.browserStores;return typeof declare==="function"?declare.call(plugin,options,server):[]}function listedPluginStores(item,server){if(isClass14(item))return declaredPluginStores(item,{},server);const{provide,useClass,useValue}=item;if(useClass)return declaredPluginStores(useClass,{},server);const init=typeof useValue==="object"&&useValue!==null?initOptionsOf(useValue):void 0;return init?declaredPluginStores(provide,init.options,server):[]}function refusal2(stores,plugins){const refused2=[...stores,...plugins.map(({plugin,option})=>[plugin,option])].filter(entry=>entry[1]!==void 0);if(refused2.length===0)return void 0;return new BrowserStoreUnavailableError(refused2,Object.fromEntries(plugins.map(({plugin,memory})=>[plugin,memory])))}async function refuseStoresInBrowser(options,runtime=getRuntimeContext14().runtime){if(runtime!=="browser")return;const listed=[...options.plugins??[],...declaredOnApps(options,FrontMcpLocalAppTokens.plugins)];const plugins=listed.flatMap(item=>listedPluginStores(item,options));const error=refusal2([["tasks",tasksServerStore(options)],["elicitation",elicitationServerStore(options)],["questions",await questionsStore(options)],["jobs",await jobsStore(options)],["rateLimits",rateLimitsStore(options)],["authTokens",authStore(options,"tokenStorage")],["secureStore",authStore(options,"secureStore")],["skillsCache",skillsCacheStore(options)]],plugins);if(error)throw error}function refuseServerStoresInBrowser(stores,runtime=getRuntimeContext14().runtime){if(runtime!=="browser")return;const error=refusal2(Object.entries(stores),[]);if(error)throw error}function refusePluginStoreInBrowser(store,runtime=getRuntimeContext14().runtime){refusePluginStoresInBrowser([store],runtime)}function refusePluginStoresInBrowser(stores,runtime=getRuntimeContext14().runtime){if(runtime!=="browser")return;const error=refusal2([],stores);if(error)throw error}var init_browser_stores=__esm({"libs/sdk/src/scope/browser-stores.ts"(){"use strict";init_dynamic_plugin();init_tokens();init_errors()}});var SkillValidationError;var init_skill_validation_error=__esm({"libs/sdk/src/skill/errors/skill-validation.error.ts"(){"use strict";init_errors();SkillValidationError=class _SkillValidationError extends PublicMcpError{mcpErrorCode=MCP_ERROR_CODES.INVALID_PARAMS;failedSkills;report;constructor(message,report){super(message);this.name="SkillValidationError";this.failedSkills=report.results.filter(r=>r.status==="failed");this.report=report}static fromReport(report){const failedSkills=report.results.filter(r=>r.status==="failed");const message=failedSkills.length===1?`Skill '${failedSkills[0].skillName}' failed tool validation: missing tools [${failedSkills[0].missingTools.join(", ")}]`:`${failedSkills.length} skill(s) failed tool validation: ${failedSkills.map(s=>`'${s.skillName}' (missing tools [${s.missingTools.join(", ")}])`).join(", ")}`;return new _SkillValidationError(message,report)}getPublicMessage(){return this.message}toJsonRpcError(){return{code:this.mcpErrorCode,message:this.getPublicMessage(),data:{failedSkills:this.failedSkills.map(s=>({skillId:s.skillId,skillName:s.skillName,missingTools:s.missingTools,hiddenTools:s.hiddenTools})),totalSkills:this.report.totalSkills,failedCount:this.report.failedCount,warningCount:this.report.warningCount}}}}}});var SkillToolValidator;var init_skill_validator=__esm({"libs/sdk/src/skill/skill-validator.ts"(){"use strict";SkillToolValidator=class{toolRegistry;constructor(toolRegistry){this.toolRegistry=toolRegistry}validate(toolNames,requiredTools){if(toolNames.length===0){return{available:[],missing:[],hidden:[],complete:true}}const allTools=this.toolRegistry.getTools(true);const allToolNames=new Set(allTools.map(t=>t.name));const visibleTools=this.toolRegistry.getTools(false);const visibleToolNames=new Set(visibleTools.map(t=>t.name));const available=[];const missing=[];const hidden=[];for(const toolName of toolNames){if(visibleToolNames.has(toolName)){available.push(toolName)}else if(allToolNames.has(toolName)){hidden.push(toolName)}else{missing.push(toolName)}}let complete=true;if(requiredTools&&requiredTools.size>0){for(const reqTool of requiredTools){if(!visibleToolNames.has(reqTool)){complete=false;break}}}else{complete=missing.length===0}return{available,missing,hidden,complete}}formatWarning(result,skillName){const issues=[];if(result.missing.length>0){issues.push(`missing tools: ${result.missing.join(", ")}`)}if(result.hidden.length>0){issues.push(`hidden tools: ${result.hidden.join(", ")}`)}if(issues.length===0){return void 0}return`Skill "${skillName}" references ${issues.join("; ")}. Some functionality may be limited.`}isToolAvailable(toolName){const visibleTools=this.toolRegistry.getTools(false);return visibleTools.some(t=>t.name===toolName)}toolExists(toolName){const allTools=this.toolRegistry.getTools(true);return allTools.some(t=>t.name===toolName)}}}});var SkillEmitter;var init_skill_events=__esm({"libs/sdk/src/skill/skill.events.ts"(){"use strict";SkillEmitter=class{listeners=new Set;on(listener){this.listeners.add(listener);return()=>this.listeners.delete(listener)}emit(event){for(const listener of[...this.listeners]){try{listener(event)}catch(err){console.error("SkillEmitter listener error:",err instanceof Error?err.message:"Unknown error")}}}get listenerCount(){return this.listeners.size}clear(){this.listeners.clear()}}}});var skill_md_parser_exports={};__export(skill_md_parser_exports,{loadSkillMdFile:()=>loadSkillMdFile,parseSkillMdFrontmatter:()=>parseSkillMdFrontmatter,skillMdFrontmatterToMetadata:()=>skillMdFrontmatterToMetadata,stripFrontmatter:()=>stripFrontmatter});import{readFile as readFile4}from"@frontmcp/utils";function parseSkillMdFrontmatter(content){const trimmed=content.trimStart();if(!trimmed.startsWith("---")){return{frontmatter:{},body:content}}const closingIndex=trimmed.indexOf("\n---",3);if(closingIndex===-1){return{frontmatter:{},body:content}}const yamlBlock=trimmed.substring(3,closingIndex).trim();const afterClose=closingIndex+4;const bodyStart=trimmed[afterClose]==="\n"?afterClose+1:afterClose;const body=trimmed.substring(bodyStart);let frontmatter={};try{const parsed=load(yamlBlock);if(typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed)){frontmatter=parsed}}catch{return{frontmatter:{},body:content}}return{frontmatter,body}}function skillMdFrontmatterToMetadata(frontmatter,body){const result={};if(typeof frontmatter["id"]==="string")result.id=frontmatter["id"];if(typeof frontmatter["name"]==="string")result.name=frontmatter["name"];if(typeof frontmatter["description"]==="string")result.description=frontmatter["description"];if(typeof frontmatter["license"]==="string")result.license=frontmatter["license"];if(typeof frontmatter["compatibility"]==="string")result.compatibility=frontmatter["compatibility"];if(typeof frontmatter["category"]==="string")result.category=frontmatter["category"];const rating=frontmatter["rating"];if(typeof rating==="number"&&Number.isFinite(rating)&&rating>=0&&rating<=5){result.rating=rating}if(Array.isArray(frontmatter["skillPath"])){const segments=frontmatter["skillPath"].filter(s=>typeof s==="string").map(s=>s.trim()).filter(s=>s.length>0);if(segments.length>0)result.skillPath=segments}if(typeof frontmatter["resources"]==="object"&&frontmatter["resources"]!==null){const r=frontmatter["resources"];const resources={};if(typeof r["scripts"]==="string")resources.scripts=r["scripts"];if(typeof r["references"]==="string")resources.references=r["references"];if(typeof r["assets"]==="string")resources.assets=r["assets"];if(typeof r["examples"]==="string")resources.examples=r["examples"];if(Object.keys(resources).length>0)result.resources=resources}const availableWhen=frontmatter["availableWhen"]??frontmatter["available-when"];if(typeof availableWhen==="object"&&availableWhen!==null&&!Array.isArray(availableWhen)){result.availableWhen=availableWhen}if(typeof frontmatter["metadata"]==="object"&&frontmatter["metadata"]!==null){const meta=frontmatter["metadata"];const specMeta={};for(const[key,val]of Object.entries(meta)){if(typeof val==="string")specMeta[key]=val;else specMeta[key]=JSON.stringify(val)}result.specMetadata=specMeta}if(typeof frontmatter["allowed-tools"]==="string"){result.allowedTools=frontmatter["allowed-tools"]}if(Array.isArray(frontmatter["tags"])){result.tags=frontmatter["tags"].filter(t=>typeof t==="string")}if(Array.isArray(frontmatter["tools"])){result.tools=frontmatter["tools"].map(t=>{if(typeof t==="string")return t;if(typeof t==="object"&&t!==null&&"name"in t&&typeof t["name"]==="string"){const ref={name:t["name"]};if(typeof t["purpose"]==="string")ref.purpose=t["purpose"];if(typeof t["required"]==="boolean")ref.required=t["required"];return ref}return void 0}).filter(t=>t!==void 0)}if(Array.isArray(frontmatter["parameters"])){result.parameters=frontmatter["parameters"].filter(p=>typeof p==="object"&&p!==null&&"name"in p).map(p=>{const param={name:String(p["name"])};if(typeof p["description"]==="string")param.description=p["description"];if(typeof p["required"]==="boolean")param.required=p["required"];if(typeof p["type"]==="string")param.type=p["type"];if(p["default"]!==void 0)param.default=p["default"];return param})}if(Array.isArray(frontmatter["examples"])){result.examples=frontmatter["examples"].filter(e=>typeof e==="object"&&e!==null&&"scenario"in e).map(e=>{const example={scenario:String(e["scenario"])};if(typeof e["parameters"]==="object"&&e["parameters"]!==null){example.parameters=e["parameters"]}if(typeof e["expectedOutcome"]==="string")example.expectedOutcome=e["expectedOutcome"];if(typeof e["expected-outcome"]==="string")example.expectedOutcome=e["expected-outcome"];return example})}if(typeof frontmatter["priority"]==="number"){result.priority=frontmatter["priority"]}const vis=frontmatter["visibility"];if(vis==="mcp"||vis==="http"||vis==="both"){result.visibility=vis}const hide=frontmatter["hideFromDiscovery"]??frontmatter["hide-from-discovery"];if(typeof hide==="boolean"){result.hideFromDiscovery=hide}const tv=frontmatter["toolValidation"]??frontmatter["tool-validation"];if(tv==="strict"||tv==="warn"||tv==="ignore"){result.toolValidation=tv}const knownKeys=new Set(["id","name","description","license","compatibility","category","rating","skillPath","resources","availableWhen","available-when","metadata","allowed-tools","tags","tools","parameters","examples","priority","visibility","hideFromDiscovery","hide-from-discovery","toolValidation","tool-validation"]);for(const[key,val]of Object.entries(frontmatter)){if(!knownKeys.has(key)&&val!==void 0){if(!result.specMetadata)result.specMetadata={};result.specMetadata[key]=typeof val==="string"?val:JSON.stringify(val)}}if(body.length>0){result.instructions=body}return result}async function loadSkillMdFile(filePath,resources){const content=await readFile4(filePath,"utf-8");const{frontmatter,body}=parseSkillMdFrontmatter(content);const metadata=skillMdFrontmatterToMetadata(frontmatter,body);if(resources){metadata.resources=resources}return metadata}function stripFrontmatter(content){const{body}=parseSkillMdFrontmatter(content);return body}var init_skill_md_parser=__esm({"libs/sdk/src/skill/skill-md-parser.ts"(){"use strict";init_js_yaml()}});import{depsOfClass as depsOfClass8,getMetadata as getMetadata17,isClass as isClass15}from"@frontmcp/di";import{fileExists as fileExists4,isAbsolute as isAbsolute2,pathJoin as pathJoin2,readdir,readFile as readFile5,stat as stat2}from"@frontmcp/utils";function collectSkillMetadata(cls){const extended=getMetadata17(extendedSkillMetadata,cls);const seed=extended?{...extended}:{};return Object.entries(FrontMcpSkillTokens).reduce((metadata,[key,token])=>{const value=getMetadata17(token,cls);if(value!==void 0){return Object.assign(metadata,{[key]:value})}return metadata},seed)}function normalizeSkill(item){if(isExternalEntryRecord(item)){throw unsupportedExternalEntry("skill",item)}if(isSkillRecord(item)){return item}if(isClass15(item)){const metadata=collectSkillMetadata(item);if(!metadata.name){const className=item.constructor?.name??String(item);throw new InvalidSkillError(className,"Class must be decorated with @Skill decorator and have a name property.")}const callerDir=getMetadata17(skillCallerDir,item);return{kind:"CLASS_TOKEN",provide:item,metadata,...callerDir?{callerDir}:{}}}const name51=typeof item==="object"&&item!==null?item["name"]:String(item);throw new InvalidSkillError(String(name51??"unknown"),"Expected a class decorated with @Skill or a skill() helper result.")}function isSkillRecord(item){if(typeof item!=="object"||item===null){return false}const record=item;if(!record["kind"]||typeof record["kind"]!=="string"){return false}const validKinds=["CLASS_TOKEN","VALUE","FILE","ESM","REMOTE"];if(!validKinds.includes(record["kind"])){return false}if(!record["provide"]||!record["metadata"]){return false}return true}function skillDiscoveryDeps(rec){switch(rec.kind){case"CLASS_TOKEN":return depsOfClass8(rec.provide,"discovery");case"VALUE":case"FILE":case"ESM":case"REMOTE":return[]}}async function loadInstructions(source,basePath){if(isInlineInstructions(source)){return source}if(isFileInstructions(source)){const filePath=isAbsolute2(source.file)?source.file:basePath?pathJoin2(basePath,source.file):source.file;const content=await readFile5(filePath,"utf-8");const{stripFrontmatter:stripFrontmatter2}=await Promise.resolve().then(()=>(init_skill_md_parser(),skill_md_parser_exports));return stripFrontmatter2(content)}if(isUrlInstructions(source)){const response=await fetch(source.url);if(!response.ok){throw new SkillInstructionFetchError(source.url,response.status,response.statusText)}return response.text()}throw new InvalidInstructionSourceError}function buildSkillContent(metadata,instructions,resolvedReferences2,resolvedExamples){let finalInstructions=instructions;if(resolvedReferences2&&resolvedReferences2.length>0){finalInstructions+=buildReferencesTable(resolvedReferences2)}if(resolvedExamples&&resolvedExamples.length>0){finalInstructions+=buildExamplesTable(resolvedExamples)}return{id:metadata.id??metadata.name,name:metadata.name,description:metadata.description,instructions:finalInstructions,tools:normalizeToolRefs(metadata.tools),parameters:metadata.parameters,examples:metadata.examples,license:metadata.license,compatibility:metadata.compatibility,specMetadata:metadata.specMetadata,allowedTools:metadata.allowedTools,resources:metadata.resources,resolvedReferences:resolvedReferences2,resolvedExamples}}function buildReferencesTable(refs){const lines=["","","## References","","| Reference | Description |","| --------- | ----------- |"];for(const ref of refs){lines.push(`| \`${ref.name}\` | ${ref.description} |`)}return lines.join("\n")}function buildExamplesTable(examples){const lines=["","","## Examples","","| Example | Reference | Level | Description |","| ------- | --------- | ----- | ----------- |"];for(const ex of examples){lines.push(`| \`${ex.name}\` | \`${ex.reference}\` | ${ex.level} | ${ex.description} |`)}return lines.join("\n")}async function resolveExamples(examplesDir){if(!await fileExists4(examplesDir))return void 0;let refDirs;try{refDirs=(await readdir(examplesDir)).sort()}catch{return void 0}const examples=[];for(const refDir of refDirs){const refPath=`${examplesDir}/${refDir}`;try{const s=await stat2(refPath);if(!s.isDirectory())continue}catch{continue}let files;try{files=(await readdir(refPath)).filter(f=>f.endsWith(".md")).sort()}catch{continue}for(const file of files){const content=await readFile5(`${refPath}/${file}`,"utf-8");const filenameWithoutExt=file.replace(/\.md$/,"");let name51=filenameWithoutExt;let description="";let reference=refDir;let level="basic";const fmMatch=content.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(fmMatch){const fmLines=fmMatch[1].split(/\r?\n/);for(const line of fmLines){const colonIdx=line.indexOf(":");if(colonIdx===-1)continue;const key=line.slice(0,colonIdx).trim();const val=line.slice(colonIdx+1).trim().replace(/^["']|["']$/g,"");if(key==="name"&&val)name51=val;if(key==="description"&&val)description=val;if(key==="reference"&&val)reference=val;if(key==="level"&&val)level=val}}if(!description){const body=fmMatch?content.substring(content.indexOf("---",3)+3).trim():content.trim();description=extractFirstParagraph(body)}examples.push({name:name51,description,reference,level,filename:`${refDir}/${file}`})}}return examples.length>0?examples:void 0}async function resolveReferences(refsDir){if(!await fileExists4(refsDir))return void 0;let files;try{files=(await readdir(refsDir)).filter(f=>f.endsWith(".md")).sort()}catch{return void 0}if(files.length===0)return void 0;const refs=[];for(const file of files){const content=await readFile5(`${refsDir}/${file}`,"utf-8");const filenameWithoutExt=file.replace(/\.md$/,"");let name51=filenameWithoutExt;let description="";const fmMatch=content.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(fmMatch){const fmLines=fmMatch[1].split(/\r?\n/);for(const line of fmLines){const colonIdx=line.indexOf(":");if(colonIdx===-1)continue;const key=line.slice(0,colonIdx).trim();const val=line.slice(colonIdx+1).trim().replace(/^["']|["']$/g,"");if(key==="name"&&val)name51=val;if(key==="description"&&val)description=val}}if(!description){const body=fmMatch?content.substring(content.indexOf("---",3)+3).trim():content.trim();description=extractFirstParagraph(body)}refs.push({name:name51,description,filename:file})}return refs}function extractFirstParagraph(body){const lines=body.split(/\r?\n/);let foundHeading=false;const paragraphLines=[];for(const line of lines){const trimmed=line.trim();if(!foundHeading&&trimmed.startsWith("#")){foundHeading=true;continue}if(foundHeading){if(trimmed===""){if(paragraphLines.length>0)break;continue}if(trimmed.startsWith("#")||trimmed.startsWith("|")||trimmed.startsWith("-"))break;paragraphLines.push(trimmed)}}return paragraphLines.join(" ").slice(0,200)||""}function normalizeToolRefs(tools){if(!tools)return[];return tools.map(tool=>{try{const normalized2=normalizeToolRef(tool);return{name:normalized2.name,purpose:normalized2.purpose,required:normalized2.required}}catch{if(typeof tool==="string")return{name:tool};if(typeof tool==="function")return{name:tool.name??"unknown"};if("name"in tool){const obj=tool;return{name:obj.name,purpose:obj.purpose,required:obj.required}}if("tool"in tool){const obj=tool;return{name:obj.tool.name??"unknown",purpose:obj.purpose,required:obj.required}}return{name:"unknown"}}})}function formatSkillForLLM(skill,availableTools,missingTools){const parts=[];parts.push(`# Skill: ${skill.name}`);parts.push("");parts.push(skill.description);parts.push("");if(skill.license){parts.push(`**License:** ${skill.license}`);parts.push("")}if(skill.compatibility){parts.push(`**Compatibility:** ${skill.compatibility}`);parts.push("")}if(missingTools.length>0){parts.push("> **Warning:** Some tools referenced by this skill are not available:");parts.push(`> Missing: ${missingTools.join(", ")}`);parts.push("> You may need to adapt the workflow or skip steps that require these tools.");parts.push("")}if(skill.tools.length>0){parts.push("## Tools");parts.push("");for(const tool of skill.tools){const status=availableTools.includes(tool.name)?"\u2713":"\u2717";const purpose=tool.purpose?` - ${tool.purpose}`:"";parts.push(`- [${status}] \`${tool.name}\`${purpose}`)}parts.push("")}if(skill.parameters&&skill.parameters.length>0){parts.push("## Parameters");parts.push("");for(const param of skill.parameters){const required=param.required?" (required)":"";const desc=param.description?`: ${param.description}`:"";parts.push(`- **${param.name}**${required}${desc}`)}parts.push("")}parts.push("## Instructions");parts.push("");parts.push(skill.instructions);if(skill.examples&&skill.examples.length>0){parts.push("");parts.push("## Examples");parts.push("");for(const example of skill.examples){parts.push(`### ${example.scenario}`);if(example.expectedOutcome){parts.push(`Expected outcome: ${example.expectedOutcome}`)}parts.push("")}}return parts.join("\n")}var init_skill_utils=__esm({"libs/sdk/src/skill/skill.utils.ts"(){"use strict";init_common();init_external_entry_utils();init_errors()}});import{dirname as dirname5,fileExists as fileExists5,getCwd as getCwd4,pathJoin as pathJoin3,pathResolve as pathResolve4,readJSON}from"@frontmcp/utils";function createSkillInstance(record,providers,owner){return new SkillInstance(record,providers,owner)}function getSkillManifestMainDir(){try{const cwd=getCwd4();return cwd&&cwd.length>0?cwd:void 0}catch{return void 0}}async function loadResourceWithManifestFallback(resourcePath,baseDir,skillName,resourceType,loader){if(!resourcePath)return void 0;let dir=resourcePath.startsWith("/")?resourcePath:baseDir?pathResolve4(baseDir,resourcePath):void 0;if(dir){try{return await loader(dir)}catch(err){if(err.code!=="ENOENT")throw err;dir=await resolveResourceFromManifest(skillName,resourceType);if(dir)return await loader(dir)}}else{dir=await resolveResourceFromManifest(skillName,resourceType);if(dir)return await loader(dir)}return void 0}async function resolveFromSkillManifest(skillName){if(skillManifestCache===null)return void 0;if(skillManifestCache===void 0){const mainDir2=getSkillManifestMainDir();if(!mainDir2){skillManifestCache=null;return void 0}try{const manifestPath=pathJoin3(mainDir2,"_skills","manifest.json");if(await fileExists5(manifestPath)){skillManifestCache=await readJSON(manifestPath)}else{skillManifestCache=null;return void 0}}catch(err){if(err.code==="ENOENT"){skillManifestCache=null;return void 0}throw err}}if(!skillManifestCache)return void 0;const entry=skillManifestCache[skillName];if(!entry?.instructions)return void 0;const mainDir=getSkillManifestMainDir();if(!mainDir)return void 0;return pathResolve4(mainDir,entry.instructions)}async function resolveResourceFromManifest(skillName,resourceType){await resolveFromSkillManifest(skillName);if(!skillManifestCache)return void 0;const entry=skillManifestCache[skillName];const relPath=entry?.[resourceType];if(!relPath)return void 0;const mainDir=getSkillManifestMainDir();if(!mainDir)return void 0;return pathResolve4(mainDir,relPath)}var SkillInstance,skillManifestCache;var init_skill_instance=__esm({"libs/sdk/src/skill/skill.instance.ts"(){"use strict";init_common();init_skill_utils();SkillInstance=class extends SkillEntry{providersRef;scope;cachedInstructions;cachedContent;instructionsLoading;contentLoading;tags;priority;hidden;skillVisibility;skillContext;constructor(record,providers,owner){super(record);this.owner=owner;this.providersRef=providers;this.name=record.metadata.id??record.metadata.name;this.fullName=`${this.owner.id}:${this.name}`;this.tags=record.metadata.tags??[];this.priority=record.metadata.priority??0;this.hidden=record.metadata.hideFromDiscovery??false;this.skillVisibility=record.metadata.visibility??"both";this.scope=this.providersRef.getActiveScope();this.ready=this.initialize()}async initialize(){return Promise.resolve()}getDescription(){return this.cachedContent?.description??this.metadata.description}async loadInstructions(){if(this.cachedInstructions!==void 0){return this.cachedInstructions}this.instructionsLoading??=this.resolveInstructions().finally(()=>{this.instructionsLoading=void 0});return this.instructionsLoading}async resolveInstructions(){const context=this.overridingContext("loadInstructions");this.cachedInstructions=context?await context.loadInstructions():await this.readInstructions();return this.cachedInstructions}async readInstructions(){let basePath;if(this.record.kind==="FILE"){const filePath=this.record.filePath;const lastSlash=filePath.lastIndexOf("/");basePath=lastSlash>0?filePath.substring(0,lastSlash):void 0}else if((this.record.kind==="VALUE"||this.record.kind==="CLASS_TOKEN")&&this.record.callerDir){basePath=this.record.callerDir}try{return await loadInstructions(this.metadata.instructions,basePath)}catch(err){if(err.code==="ENOENT"){const resolved=await resolveFromSkillManifest(this.metadata.name);if(resolved){return loadInstructions({file:resolved},void 0)}}throw err}}overridingContext(method){if(this.record.kind!=="CLASS_TOKEN")return void 0;const prototype=this.record.provide.prototype;if(typeof prototype[method]!=="function"||prototype[method]===SkillContext.prototype[method]){return void 0}this.skillContext??=new this.record.provide({metadata:this.metadata,providers:this.providersRef,logger:this.scope.logger,authInfo:{},defaults:{loadInstructions:()=>this.readInstructions(),build:()=>this.buildContent()}});return this.skillContext}getBaseDir(){if(this.record.kind==="FILE"){return dirname5(this.record.filePath)||void 0}if((this.record.kind==="VALUE"||this.record.kind==="CLASS_TOKEN")&&this.record.callerDir){return this.record.callerDir}return void 0}async load(){if(this.cachedContent!==void 0){return this.cachedContent}this.contentLoading??=this.resolveContent().finally(()=>{this.contentLoading=void 0});return this.contentLoading}async resolveContent(){const context=this.overridingContext("build");const baseContent=context?await context.build():await this.buildContent();this.cachedContent={...baseContent,tags:this.tags,priority:this.priority,hideFromDiscovery:this.hidden,visibility:this.skillVisibility};return this.cachedContent}async buildContent(){const instructions=await this.loadInstructions();const baseDir=this.getBaseDir();const resolvedRefs=await loadResourceWithManifestFallback(this.metadata.resources?.references,baseDir,this.metadata.name,"references",resolveReferences);const resolvedExs=await loadResourceWithManifestFallback(this.metadata.resources?.examples,baseDir,this.metadata.name,"examples",resolveExamples);return buildSkillContent(this.metadata,instructions,resolvedRefs,resolvedExs)}getToolRefs(){const tools=this.metadata.tools;if(!tools)return[];return tools.map(t=>normalizeToolRef(t))}getToolNames(){return this.getToolRefs().map(t=>t.name)}getTags(){return this.tags}isHidden(){return this.hidden}getPriority(){return this.priority}get providers(){return this.providersRef}clearCache(){this.cachedInstructions=void 0;this.cachedContent=void 0}getContentSync(){if(this.cachedContent){return this.cachedContent}if(typeof this.metadata.instructions==="string"&&!this.overridingContext("loadInstructions")&&!this.overridingContext("build")){return buildSkillContent(this.metadata,this.metadata.instructions)}return void 0}}}});async function importWithRequireFallback(dynamicImport,requireFallback){try{return await dynamicImport()}catch(importError){try{return requireFallback()}catch{throw importError}}}var init_dynamic_import_utils=__esm({"libs/sdk/src/utils/dynamic-import.utils.ts"(){"use strict"}});var memory_skill_provider_exports={};__export(memory_skill_provider_exports,{MemorySkillProvider:()=>MemorySkillProvider});import{sha256Hex as sha256Hex12}from"@frontmcp/utils";function isSnapshotCapable(db){const d=db;return typeof d.toSnapshot==="function"&&typeof d.loadSnapshot==="function"}var STOP_WORDS,MemorySkillProvider;var init_memory_skill_provider=__esm({"libs/sdk/src/skill/providers/memory-skill.provider.ts"(){"use strict";init_dynamic_import_utils();STOP_WORDS=new Set(["the","a","an","this","that","these","those","in","on","at","to","for","of","with","by","from","into","and","or","but","so","as","if","when","where","i","me","my","you","your","it","its","we","our","they","their","is","was","are","were","be","been","being","have","has","had","do","does","did","will","would","can","could","should","may","might","please","help","want","need","like","just","how","what"]);MemorySkillProvider=class{type="memory";vectorDB;vectorDBLoading;skills=new Map;defaultTopK;defaultMinScore;toolValidator;initialized=false;scoring;indexCache;skillsVersion=0;indexedVersion=-1;constructor(options={}){this.defaultTopK=options.defaultTopK??10;this.defaultMinScore=options.defaultMinScore??.1;this.toolValidator=options.toolValidator;this.scoring=options.scoring??"cosine";this.indexCache=options.indexCache}async createVectorDB(){const{TFIDFVectoria}=await importWithRequireFallback(()=>import("vectoriadb"),()=>__require("vectoriadb"));const dbConfig={defaultTopK:this.defaultTopK,defaultSimilarityThreshold:this.defaultMinScore};if(this.scoring!=="cosine")dbConfig.scoring=this.scoring;return new TFIDFVectoria(dbConfig)}setIndexCache(cache2){this.indexCache=cache2;this.markStale()}get indexReady(){return this.indexedVersion===this.skillsVersion}markStale(){this.skillsVersion++}async ensureIndexed(){if(this.indexReady)return;const version=this.skillsVersion;const db=await this.db();if(this.indexCache&&isSnapshotCapable(db)){const key=await this.computeIndexKey();try{const snapshot=await this.indexCache.get(key);if(snapshot!==void 0&&snapshot!==null){db.loadSnapshot(snapshot);this.indexedVersion=version;return}}catch{}this.rebuildIndex(db);this.indexedVersion=version;try{await this.indexCache.set(key,db.toSnapshot())}catch{}return}this.rebuildIndex(db);this.indexedVersion=version}async warm(){await this.ensureIndexed()}rebuildIndex(db){db.clear();db.addDocuments(Array.from(this.skills.values(),skill=>this.toDocument(skill)));db.reindex()}toDocument(skill){return{id:skill.id,text:this.buildSearchableText(skill),metadata:{id:skill.id,skillId:skill.id,skill}}}async computeIndexKey(){const parts=Array.from(this.skills.values()).map(s=>`${s.id}\0${this.buildSearchableText(s)}`).sort();const canonical=`frontmcp-skill-index:v1|${this.scoring}|${this.skills.size}|${parts.join("")}`;return sha256Hex12(canonical)}async db(){if(this.vectorDB)return this.vectorDB;this.vectorDBLoading??=this.createVectorDB().then(db=>this.vectorDB??=db,error=>{this.vectorDBLoading=void 0;throw error});return this.vectorDBLoading}setToolValidator(validator){this.toolValidator=validator}async initialize(){this.initialized=true}async search(query,options={}){if(query.trim().length===0){return[]}const{topK=this.defaultTopK,tags,minScore=this.defaultMinScore,requireAllTools=false,excludeIds=[],tools}=options;const filter=metadata=>{const skill=metadata.skill;if(this.isHidden(skill)){return false}if(excludeIds.includes(skill.id)){return false}if(tags&&tags.length>0){const skillTags=this.getSkillTags(skill);if(!tags.some(t=>skillTags.includes(t))){return false}}if(tools&&tools.length>0){const skillTools=skill.tools.map(t=>t.name);if(!tools.some(t=>skillTools.includes(t))){return false}}return true};const db=await this.db();await this.ensureIndexed();let results=await db.search(query,{topK,threshold:minScore,filter,...options.negativeQuery!==void 0?{negativeQuery:options.negativeQuery}:{},...options.negativeWeight!==void 0?{negativeWeight:options.negativeWeight}:{}});if(results.length===0&&query.trim().length>0&&this.skills.size>0){results=this.fallbackTextSearch(query,topK,filter)}const searchResults=[];for(const result of results){const skill=result.metadata.skill;const toolNames=skill.tools.map(t=>t.name);let validation;if(this.toolValidator){validation=this.toolValidator.validate(toolNames);if(requireAllTools&&!validation.complete){continue}}searchResults.push({metadata:this.skillToMetadata(skill),score:result.score,availableTools:validation?.available??toolNames,missingTools:validation?.missing??[],source:"local"})}return searchResults}async load(skillId){const skill=this.skills.get(skillId);if(!skill){return null}const toolNames=skill.tools.map(t=>t.name);let availableTools=toolNames;let missingTools=[];let isComplete=true;let warning;if(this.toolValidator){const validation=this.toolValidator.validate(toolNames);availableTools=validation.available;missingTools=validation.missing;isComplete=validation.complete;warning=this.toolValidator.formatWarning(validation,skill.name)}return{skill,availableTools,missingTools,isComplete,warning}}async list(options={}){const{offset=0,limit=50,tags,sortBy="name",sortOrder="asc",includeHidden=false}=options;let skills=Array.from(this.skills.values());if(!includeHidden){skills=skills.filter(s=>!this.isHidden(s))}if(tags&&tags.length>0){skills=skills.filter(s=>{const skillTags=this.getSkillTags(s);return tags.some(t=>skillTags.includes(t))})}skills.sort((a,b)=>{let comparison;switch(sortBy){case"name":comparison=a.name.localeCompare(b.name);break;case"priority":comparison=(this.getPriority(a)??0)-(this.getPriority(b)??0);break;default:comparison=a.name.localeCompare(b.name)}return sortOrder==="desc"?-comparison:comparison});const total=skills.length;const hasMore=offset+limit<total;skills=skills.slice(offset,offset+limit);return{skills:skills.map(s=>this.skillToMetadata(s)),total,hasMore}}async exists(skillId){return this.skills.has(skillId)}async count(options={}){const{tags,includeHidden=false}=options;let count=0;for(const skill of this.skills.values()){if(!includeHidden&&this.isHidden(skill)){continue}if(tags&&tags.length>0){const skillTags=this.getSkillTags(skill);if(!tags.some(t=>skillTags.includes(t))){continue}}count++}return count}async add(skill){this.skills.set(skill.id,skill);this.markStale()}async update(skillId,skill){const normalizedSkill=skill.id!==skillId?{...skill,id:skillId}:skill;this.skills.set(skillId,normalizedSkill);this.markStale()}async remove(skillId){this.skills.delete(skillId);this.markStale()}async clear(){this.skills.clear();this.vectorDB?.clear();this.markStale()}async dispose(){this.skills.clear();this.vectorDB?.clear();this.markStale();this.initialized=false}async addMany(skills){for(const skill of skills)this.skills.set(skill.id,skill);this.markStale()}buildSearchableText(skill){const parts=[];if(skill.name){const nameParts=skill.name.split(/[:\-_.\s]/).filter(Boolean);parts.push(...nameParts)}if(skill.description){parts.push(skill.description,skill.description,skill.description);const keyTerms=skill.description.toLowerCase().split(/\s+/).filter(word=>word.length>=4&&!STOP_WORDS.has(word));parts.push(...keyTerms)}const tags=this.getSkillTags(skill);for(const tag of tags){parts.push(tag,tag)}for(const tool of skill.tools){parts.push(tool.name);if(tool.purpose){parts.push(tool.purpose)}}if(skill.parameters){for(const param of skill.parameters){parts.push(param.name);if(param.description){parts.push(param.description)}}}if(skill.examples){for(const example of skill.examples){parts.push(example.scenario);if(example.expectedOutcome){parts.push(example.expectedOutcome)}}}return parts.join(" ")}fallbackTextSearch(query,topK,filter){const queryTerms=query.toLowerCase().split(/\s+/).filter(t=>t.length>0&&!STOP_WORDS.has(t));if(queryTerms.length===0){return[]}const matches=[];this.skills.forEach(skill=>{const metadata={id:skill.id,skillId:skill.id,skill};if(!filter(metadata)){return}const searchableText=this.buildSearchableText(skill);const matchCount=queryTerms.filter(term=>searchableText.toLowerCase().includes(term)).length;if(matchCount>0){matches.push({id:skill.id,text:searchableText,score:matchCount/queryTerms.length,metadata})}});matches.sort((a,b)=>b.score-a.score);return matches.slice(0,topK)}skillToMetadata(skill){const tags=this.getSkillTags(skill);const priority=this.getPriority(skill);const hideFromDiscovery=this.isHidden(skill);const visibility=this.getVisibility(skill);return{id:skill.id,name:skill.name,description:skill.description,instructions:skill.instructions,tools:skill.tools.map(t=>{if(t.purpose||t.required){return{name:t.name,...t.purpose&&{purpose:t.purpose},...t.required&&{required:t.required}}}return t.name}),parameters:skill.parameters,examples:skill.examples,...tags.length>0&&{tags},...priority!==void 0&&{priority},...hideFromDiscovery&&{hideFromDiscovery},visibility:visibility??"both"}}getSkillTags(skill){return skill.tags??[]}isHidden(skill){return skill.hideFromDiscovery===true}getPriority(skill){return skill.priority}getVisibility(skill){return skill.visibility}}}});import{tokenName as tokenName15}from"@frontmcp/di";import{getRuntimeContext as getRuntimeContext15,isEntryAvailable as isEntryAvailable5}from"@frontmcp/utils";function findIdPathCollision(skills){const byPath=new Map;for(const skill of skills){const path4=skill.getSkillPath();if(!byPath.has(path4))byPath.set(path4,skill)}for(const idOwner of skills){const id=idOwner.metadata.id;if(!id||id===idOwner.getSkillPath())continue;const pathOwner=byPath.get(id);if(pathOwner)return{idOwner,pathOwner}}return void 0}function describeIdPathCollision({idOwner,pathOwner}){const id=idOwner.metadata.id;return`id "${id}" of skill "${idOwner.metadata.name}" is the skill:// path of skill "${pathOwner.metadata.name}", so skill://${id}/SKILL.md would serve one for the other. Give one of them another id or name.`}var DEFAULT_LIST_LIMIT,SkillRegistry;var init_skill_registry=__esm({"libs/sdk/src/skill/skill.registry.ts"(){"use strict";init_availability();init_errors();init_regsitry();init_lineage_utils();init_skill_validation_error();init_sep_2640_constants();init_skill_validator();init_skill_events();init_skill_instance();init_skill_utils();DEFAULT_LIST_LIMIT=50;SkillRegistry=class _SkillRegistry extends RegistryAbstract{owner;localRows=[];dynamicRows=[];dynamicContents=new Map;dynamicGenerations=new Map;withdrawn=new Map;withdrawals=0;providerWrites=new Map;dynamicSkillsExpected=false;adopted=new Map;children=new Set;adopters=new Set;byQualifiedId=new Map;lineages=new EntryLineageIndex;byName=new Map;byOwnerAndName=new Map;version=0;emitter=new SkillEmitter;storageProvider;storageProviderLoad;indexCache;externalProvider;toolValidator;scope;options;sep2640IndexTemplates=[];sep2640IndexArchives=[];sep2640InstructionUris=[];constructor(providers,list,owner,options){super("SkillRegistry",providers,list,false);this.owner=owner;this.scope=providers.getActiveScope();this.options=options??{};this.indexCache=this.options.indexCache;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=normalizeSkill(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)continue;const deps=skillDiscoveryDeps(rec);for(const d of deps){this.providers.get(d);this.graph.get(token)?.add(d)}}}async initialize(){try{const toolRegistry=this.scope.tools;if(toolRegistry){this.toolValidator=new SkillToolValidator(toolRegistry)}}catch{}for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)continue;const instance=createSkillInstance(rec,this.providers,this.owner);this.instances.set(token,instance);const lineage=this.owner?[this.owner]:[];const row=this.makeRow(token,instance,lineage,this);this.localRows.push(row);try{await this.syncProvider(instance.metadata.id??instance.metadata.name,async()=>{const content=await instance.load();await(await this.storage()).add(content)})}catch(error){this.scope.logger.warn(`Failed to load skill ${instance.name}: ${error.message}`)}}const childAppRegistries=this.providers.getRegistries("AppRegistry");for(const appRegistry of childAppRegistries){const apps=appRegistry.getApps();for(const app of apps){const appSkillsRegistry=app.skills;if(appSkillsRegistry&&"adoptFromChild"in this&&appSkillsRegistry!==this){if(!app.isRemote&&appSkillsRegistry instanceof _SkillRegistry){await this.adoptFromChild(appSkillsRegistry,appSkillsRegistry.owner)}}}}const childRegistries=this.providers.getRegistries("SkillRegistry");for(const child of childRegistries){if(child!==this){await this.adoptFromChild(child,child.owner)}}const collision=findIdPathCollision(this.listAllInstances());if(collision){throw new InvalidSkillError(collision.idOwner.metadata.name,describeIdPathCollision(collision))}this.reindex();logAvailabilityFiltering("SkillRegistry",this.listAllIndexed().map(r=>r.instance),this.scope.logger);this.bump("reset")}async adoptFromChild(child,_childOwner){if(this.children.has(child))return;const childRows=child.listAllIndexed();const prepend=this.owner?[this.owner]:[];const adoptedRows=childRows.map(r=>this.relineage(r,prepend));this.adopted.set(child,adoptedRows);this.children.add(child);child.adopters.add(this);child.subscribe({immediate:false},()=>{const previous=this.adopted.get(child)??[];const latest=child.listAllIndexed().map(r=>this.relineage(r,prepend));this.adopted.set(child,latest);this.reindex();this.withdrawGoneAdoptedSkills(previous);for(const row of latest){const skillId=row.instance.metadata.id??row.instance.metadata.name;this.syncProvider(skillId,async()=>{const content=await row.instance.load();await(await this.storage()).add(content)}).catch(error=>{this.scope.logger.warn(`Failed to reload adopted skill ${row.baseName}: ${error.message}`)})}this.bump("reset")});await Promise.all(adoptedRows.map(async row=>{try{await this.syncProvider(row.instance.metadata.id??row.instance.metadata.name,async()=>{const content=await row.instance.load();await(await this.storage()).add(content)})}catch(error){this.scope.logger.warn(`Failed to load adopted skill ${row.baseName}: ${error.message}`)}}));this.reindex();this.bump("reset")}namespacesServingThis(){const registries=new Set;const climb=registry=>{if(registries.has(registry))return;registries.add(registry);for(const adopter of registry.adopters)climb(adopter)};climb(this);return[...registries].map(registry=>registry.liveSkills())}liveSkills(){const registries=new Set;const skills=new Set;const descend=registry=>{if(registries.has(registry))return;registries.add(registry);for(const row of[...registry.localRows,...registry.dynamicRows])skills.add(row.instance);for(const child of registry.children)descend(child)};descend(this);return[...skills]}getSkills(options){const opts=typeof options==="boolean"?{includeHidden:options}:options??{};const{includeHidden=false,visibility="all"}=opts;let skills=this.listAllIndexed().map(r=>r.instance);if(!includeHidden){skills=skills.filter(s=>!s.isHidden())}if(visibility!=="all"){skills=skills.filter(s=>{const skillVis=s.metadata.visibility??"both";if(skillVis==="both")return true;return skillVis===visibility})}const ctx=getRuntimeContext15();skills=skills.filter(s=>isEntryAvailable5(s.metadata.availableWhen,ctx));return skills}getInlineSkills(){return[...this.instances.values()]}getAlwaysLoadedSkills(){let skills=this.listAllIndexed().map(r=>r.instance);skills=skills.filter(s=>s.isAlwaysLoaded());const ctx=getRuntimeContext15();skills=skills.filter(s=>isEntryAvailable5(s.metadata.availableWhen,ctx));return skills}getExecutableSkills(opts){return this.getSkills(opts).filter(s=>s.isExecutable())}getKnowledgeOnlySkills(opts){return this.getSkills(opts).filter(s=>s.isKnowledgeOnly())}findByName(name51){const rows=this.byName.get(name51);return rows?.[0]?.instance}findByQualifiedName(qualifiedName){for(const row of this.listAllIndexed()){if(row.qualifiedName===qualifiedName){return row.instance}}return void 0}setIndexCache(cache2){this.indexCache=cache2;const provider=this.storageProvider;if(typeof provider?.setIndexCache==="function"){provider.setIndexCache(cache2)}}async warmIndex(){await this.ready;const provider=await this.storage();if(typeof provider.warm==="function"){await provider.warm()}}async search(query,options){const topK=options?.topK;const hidden=this.hiddenFromProviderRead();const providerOptions=hidden.size>0&&typeof topK==="number"&&topK>=0?{...options,topK:topK+hidden.size}:options;let baseResults=await(await this.storage()).search(query,providerOptions);if(hidden.size>0||this.withdrawn.size>0){baseResults=baseResults.filter(r=>!hidden.has(r.metadata));if(typeof topK==="number"&&topK>=0)baseResults=baseResults.slice(0,topK)}if(this.dynamicContents.size===0)return baseResults;const baseSeen=new Set;let rewrites=0;const rewrittenBase=baseResults.map(r=>{const id=r.metadata.id??r.metadata.name;baseSeen.add(id);const dyn=this.dynamicContents.get(id);if(!dyn)return r;rewrites++;const meta=this.dynamicSkillMetadata(dyn);const toolNames=dyn.tools.map(t=>t.name);let availableTools=toolNames;let missingTools=[];if(this.toolValidator){const v=this.toolValidator.validate(toolNames);availableTools=v.available;missingTools=v.missing}return{...r,metadata:meta,availableTools,missingTools}});const overlayOnly=this.searchDynamicOverlay(query,options,baseSeen);if(overlayOnly.length===0&&rewrites===0)return baseResults;const merged=[...rewrittenBase,...overlayOnly].sort((a,b)=>b.score-a.score);return typeof topK==="number"&&topK>=0?merged.slice(0,topK):merged}async loadSkill(skillId){const dynamic=this.dynamicContents.get(skillId);if(dynamic){return this.buildDynamicLoadResult(dynamic)}let localSkill=this.findByName(skillId)??this.findByQualifiedName(skillId);if(!localSkill){for(const row of this.listAllIndexed()){if(row.instance.metadata.name===skillId){localSkill=row.instance;break}}}if(localSkill){const ctx=getRuntimeContext15();if(!isEntryAvailable5(localSkill.metadata.availableWhen,ctx)){return void 0}const dynamicResolved=this.dynamicContents.get(localSkill.metadata.id??localSkill.metadata.name);if(dynamicResolved){return this.buildDynamicLoadResult(dynamicResolved)}const instance=localSkill;const content=await instance.load();const toolNames=instance.getToolNames();let availableTools=toolNames;let missingTools=[];let isComplete=true;let warning;if(this.toolValidator){const validation=this.toolValidator.validate(toolNames);availableTools=validation.available;missingTools=validation.missing;isComplete=validation.complete;warning=this.toolValidator.formatWarning(validation,instance.name)}return{skill:content,availableTools,missingTools,isComplete,warning}}const hidden=this.hiddenFromProviderRead();if(hidden.has({name:skillId}))return void 0;const result=await(await this.storage()).load(skillId);if(result&&hidden.has(result.skill))return void 0;return result??void 0}buildDynamicLoadResult(content){const toolNames=content.tools.map(t=>t.name);let availableTools=toolNames;let missingTools=[];let isComplete=true;let warning;if(this.toolValidator){const validation=this.toolValidator.validate(toolNames);availableTools=validation.available;missingTools=validation.missing;isComplete=validation.complete;warning=this.toolValidator.formatWarning(validation,content.name)}return{skill:structuredClone(content),availableTools,missingTools,isComplete,warning}}async listSkills(options){const hidden=this.hiddenFromProviderRead();if(this.dynamicContents.size===0&&hidden.size===0){const page2=await(await this.storage()).list(options);if(this.withdrawn.size===0)return page2}const base=(await this.listAllFromProvider(options)).filter(meta=>!hidden.has(meta));const baseIds=new Set;const merged=base.map(meta=>{const id=meta.id??meta.name;baseIds.add(id);const dyn=this.dynamicContents.get(id);return dyn?this.dynamicSkillMetadata(dyn):meta});for(const meta of this.collectDynamicMetadata(options)){const id=meta.id??meta.name;if(!baseIds.has(id)){baseIds.add(id);merged.push(meta)}}const offset=options?.offset??0;const limit=options?.limit??DEFAULT_LIST_LIMIT;const skills=merged.slice(offset,offset+limit);return{skills,total:merged.length,hasMore:offset+skills.length<merged.length}}async listAllFromProvider(options){const all=[];const storage=await this.storage();for(;;){const page2=await storage.list({...options,offset:all.length,limit:Number.MAX_SAFE_INTEGER});all.push(...page2.skills);if(!page2.hasMore||page2.skills.length===0)return all}}lineageOf(entry){return this.lineages.lineageOf(entry)}hasAny(){return this.listAllIndexed().length>0}expectDynamicSkills(){this.dynamicSkillsExpected=true}servesSkills(){return this.dynamicSkillsExpected||this.hasAny()||this.externalProvider?.isReadOnly()===true}async count(options){const hidden=this.hiddenFromProviderRead();if(this.dynamicContents.size===0&&hidden.size===0){const counted=await(await this.storage()).count(options);if(this.withdrawn.size===0)return counted}const baseList=(await this.listAllFromProvider({tags:options?.tags,includeHidden:options?.includeHidden})).filter(m=>!hidden.has(m));const baseIds=new Set;for(const m of baseList)baseIds.add(m.id??m.name);const overlay=this.collectDynamicMetadata(options).filter(m=>!baseIds.has(m.id??m.name));return baseList.length+overlay.length}dynamicSkillMetadata(content){return{id:content.id,name:content.name,description:content.description,instructions:content.instructions,tools:content.tools.map(t=>({name:t.name,...t.purpose!==void 0&&{purpose:t.purpose},...t.required!==void 0&&{required:t.required}})),...content.parameters!==void 0&&{parameters:content.parameters},...content.examples!==void 0&&{examples:content.examples},...content.license!==void 0&&{license:content.license},...content.compatibility!==void 0&&{compatibility:content.compatibility},...content.specMetadata!==void 0&&{specMetadata:content.specMetadata},...content.allowedTools!==void 0&&{allowedTools:content.allowedTools},...content.resources!==void 0&&{resources:content.resources},...content.rating!==void 0&&{rating:content.rating},...content.category!==void 0&&{category:content.category}}}collectDynamicMetadata(options){const out=[];for(const content of this.dynamicContents.values()){const meta=this.dynamicSkillMetadata(content);if(options?.tags?.length){const tags=meta.tags??[];if(!options.tags.some(t=>tags.includes(t)))continue}if(!options?.includeHidden&&meta.hideFromDiscovery===true)continue;out.push(meta)}return out}searchDynamicOverlay(query,options,excludeIds){const q=query.trim().toLowerCase();const minScore=options?.minScore??.1;const out=[];for(const content of this.dynamicContents.values()){const id=content.id;if(excludeIds.has(id))continue;if(options?.excludeIds?.includes(id))continue;const meta=this.dynamicSkillMetadata(content);if(options?.tags?.length){const tags=meta.tags??[];if(!options.tags.some(t=>tags.includes(t)))continue}const toolNames=content.tools.map(t=>t.name);let availableTools=toolNames;let missingTools=[];if(this.toolValidator){const v=this.toolValidator.validate(toolNames);availableTools=v.available;missingTools=v.missing}if(options?.requireAllTools&&missingTools.length>0)continue;if(options?.tools?.length){const refSet=new Set(toolNames);if(!options.tools.some(t=>refSet.has(t)))continue}const name51=(meta.name??"").toLowerCase();const desc=(meta.description??"").toLowerCase();let score;if(q.length===0){score=.5}else if(name51.includes(q)){score=1}else if(desc.includes(q)){score=.5}else{continue}if(score<minScore)continue;out.push({metadata:meta,score,availableTools,missingTools,source:"local"})}return out}subscribe(opts,cb){const filter=opts.filter??(()=>true);if(opts.immediate){cb({kind:"reset",changeScope:"global",version:this.version,snapshot:this.listAllInstances().filter(filter)})}return this.emitter.on(e=>cb({...e,snapshot:this.listAllInstances().filter(filter)}))}getCapabilities(){if(!this.servesSkills())return{};return{experimental:{[SEP_2640_EXTENSION_ID]:{}},extensions:{[SEP_2640_EXTENSION_ID]:{}}}}getSep2640IndexTemplates(){return[...this.sep2640IndexTemplates]}addSep2640IndexTemplate(entry){if(entry.type!=="mcp-resource-template"){throw new Error(`addSep2640IndexTemplate: entry.type must be "mcp-resource-template", got "${entry.type}"`)}this.sep2640IndexTemplates.push(entry);this.bump("reset")}getSep2640IndexArchives(){return[...this.sep2640IndexArchives]}addSep2640IndexArchive(entry){if(entry.type!=="archive"){throw new Error(`addSep2640IndexArchive: entry.type must be "archive", got "${entry.type}"`)}this.sep2640IndexArchives.push(entry);this.bump("reset")}getSep2640InstructionUris(){return[...this.sep2640InstructionUris]}addSep2640InstructionUri(uri){if(!this.sep2640InstructionUris.includes(uri)){this.sep2640InstructionUris.push(uri);this.bump("reset")}}async validateAllTools(){const results=[];const allInstances=this.listAllInstances();for(const entry of allInstances){const instance=entry;const toolNames=instance.getToolNames();const skillValidation=instance.metadata.toolValidation??this.options.defaultToolValidation??"warn";if(skillValidation==="ignore"){results.push({skillId:instance.name,skillName:instance.name,status:"valid",missingTools:[],hiddenTools:[],validationMode:skillValidation});continue}if(this.toolValidator&&toolNames.length>0){const validation=this.toolValidator.validate(toolNames);if(!validation.complete){const status=skillValidation==="strict"?"failed":"warning";if(skillValidation==="warn"){const warning=this.toolValidator.formatWarning(validation,instance.name);if(warning){this.scope.logger.warn(warning)}}else if(this.options.failOnInvalidSkills===false){this.scope.logger.error(`Skill "${instance.name}" (toolValidation: 'strict') references missing tools: ${validation.missing.join(", ")}`)}results.push({skillId:instance.name,skillName:instance.name,status,missingTools:validation.missing,hiddenTools:validation.hidden,validationMode:skillValidation})}else{results.push({skillId:instance.name,skillName:instance.name,status:"valid",missingTools:[],hiddenTools:[],validationMode:skillValidation})}}else{results.push({skillId:instance.name,skillName:instance.name,status:"valid",missingTools:[],hiddenTools:[],validationMode:skillValidation})}}const failedCount=results.filter(r=>r.status==="failed").length;const warningCount=results.filter(r=>r.status==="warning").length;const report={results,isValid:failedCount===0,totalSkills:results.length,failedCount,warningCount};this.emitter.emit({kind:"validated",changeScope:"global",version:this.version,snapshot:allInstances,validationReport:report});if(this.options.failOnInvalidSkills!==false&&failedCount>0){throw SkillValidationError.fromReport(report)}return report}async registerSkillContent(content,opts){if(!content||typeof content.id!=="string"||content.id.length===0){throw new PublicMcpError("registerSkillContent: SkillContent.id is required","INVALID_PARAMS")}if(typeof content.name!=="string"||content.name.length===0){throw new PublicMcpError("registerSkillContent: SkillContent.name is required","INVALID_PARAMS")}const id=content.id;const metadata={id,name:content.name,description:content.description,instructions:content.instructions,tools:content.tools.map(t=>({name:t.name,...t.purpose!==void 0&&{purpose:t.purpose},...t.required!==void 0&&{required:t.required}})),...content.parameters&&{parameters:content.parameters},...content.examples&&{examples:content.examples},...content.license&&{license:content.license},...content.compatibility&&{compatibility:content.compatibility},...content.specMetadata&&{specMetadata:content.specMetadata},...content.allowedTools&&{allowedTools:content.allowedTools},...content.resources&&{resources:content.resources},...content.rating!==void 0&&{rating:content.rating},...content.category&&{category:content.category}};const provideToken=Symbol(`dynamic-skill:${id}`);const record={kind:"VALUE",provide:provideToken,metadata};const instance=createSkillInstance(record,this.providers,this.owner);try{await instance.load()}catch(error){this.scope.logger.warn(`[SkillRegistry] Failed to pre-load dynamic skill ${id} from source ${opts?.source??"unknown"}: ${error.message}`)}const storage=await this.storage();const existingIdx=this.dynamicRows.findIndex(r=>r.instance.name===id);const superseded=new Set(opts?.supersedes);const leaving=new Set(this.dynamicRows.filter(r=>r.instance.name===id||superseded.has(r.instance.name)).map(r=>r.instance));for(const skills of this.namespacesServingThis()){const collision=findIdPathCollision([...skills.filter(other=>!leaving.has(other)),instance]);if(collision){throw new PublicMcpError(`registerSkillContent: ${describeIdPathCollision(collision)}`,"INVALID_PARAMS")}}if(existingIdx!==-1){this.dynamicRows.splice(existingIdx,1)}const mutable=this.asMutableProvider(storage);const removed=this.dynamicRows.filter(r=>superseded.has(r.instance.name)&&findIdPathCollision([r.instance,instance])).map(r=>r.instance.name);for(const removedId of removed){this.withdrawDynamicSkill(removedId,mutable)}const lineage=this.owner?[this.owner]:[];const row=this.makeRow(provideToken,instance,lineage,this);this.dynamicRows.push(row);this.dynamicContents.set(id,structuredClone(content));this.withdrawn.delete(id);const generation=(this.dynamicGenerations.get(id)??0)+1;this.dynamicGenerations.set(id,generation);this.reindex();const providerWrites=mutable?[...removed.map(removedId=>this.removeFromProvider(removedId)),this.syncProvider(id,async()=>{if(await mutable.exists(id)){await mutable.update(id,content)}else{await mutable.add(content)}}).catch(error=>{this.scope.logger.warn(`[SkillRegistry] Failed to index dynamic skill ${id} in storage provider: ${error.message}`)})]:[];this.bump("reset");await Promise.all(providerWrites);let unregistered=false;const unregister=async()=>{if(unregistered)return;unregistered=true;if(this.dynamicGenerations.get(id)!==generation){return}await this.unregisterSkill(id)};this.scope.logger.debug(`[SkillRegistry] Registered dynamic skill ${id}${opts?.source?` (source: ${opts.source})`:""}`);return{id,unregister,removed}}async unregisterSkill(id){if(!this.dynamicRows.some(r=>r.instance.name===id))return false;const mutable=this.asMutableProvider(this.storageProvider);this.withdrawDynamicSkill(id,mutable);this.reindex();const removal=mutable?this.removeFromProvider(id):void 0;this.bump("reset");await removal;this.scope.logger.debug(`[SkillRegistry] Unregistered dynamic skill ${id}`);return true}withdrawDynamicSkill(id,mutable){this.dynamicRows.splice(this.dynamicRows.findIndex(r=>r.instance.name===id),1);this.dynamicContents.delete(id);this.dynamicGenerations.set(id,(this.dynamicGenerations.get(id)??0)+1);if(mutable)this.withdrawn.set(id,++this.withdrawals)}async removeFromProvider(id){const withdrawal=this.withdrawn.get(id);try{await this.syncProvider(id,async()=>{await this.asMutableProvider(await this.storage())?.remove(id)});if(this.withdrawn.get(id)===withdrawal)this.withdrawn.delete(id)}catch(error){this.scope.logger.warn(`[SkillRegistry] Failed to remove skill ${id} from storage provider; it stays hidden from provider-backed reads: ${error.message}`)}}syncProvider(id,write){const run=(this.providerWrites.get(id)??Promise.resolve()).then(write);const settled=run.then(()=>void 0,()=>void 0);this.providerWrites.set(id,settled);void settled.then(()=>{if(this.providerWrites.get(id)===settled)this.providerWrites.delete(id)});return run}withdrawGoneAdoptedSkills(previous){if(this.storageProvider&&!this.asMutableProvider(this.storageProvider))return;const skillIdOf=entry=>entry.metadata.id??entry.metadata.name;const live=new Set(this.listAllIndexed().map(r=>skillIdOf(r.instance)));for(const id of live)this.withdrawn.delete(id);for(const row of previous){const id=skillIdOf(row.instance);if(live.has(id)||this.withdrawn.has(id))continue;this.withdrawn.set(id,++this.withdrawals);void this.removeFromProvider(id)}}hiddenFromProviderRead(){const atStart=new Set(this.withdrawn.keys());return{size:atStart.size,has:meta=>{const id=meta.id??meta.name;return atStart.has(id)||this.withdrawn.has(id)}}}asMutableProvider(provider){const candidate=provider;if(candidate&&typeof candidate.add==="function"&&typeof candidate.update==="function"&&typeof candidate.remove==="function"&&typeof candidate.exists==="function"){return provider}return void 0}storage(){if(!this.storageProviderLoad){const load2=this.createMemoryProvider().catch(error=>{if(this.storageProviderLoad===load2)this.storageProviderLoad=void 0;throw error});this.storageProviderLoad=load2}return this.storageProviderLoad}async createMemoryProvider(){const{MemorySkillProvider:Provider}=await Promise.resolve().then(()=>(init_memory_skill_provider(),memory_skill_provider_exports));const provider=new Provider({defaultTopK:10,defaultMinScore:.1,...this.options.scoring?{scoring:this.options.scoring}:{},...this.indexCache?{indexCache:this.indexCache}:{}});if(this.toolValidator)provider.setToolValidator(this.toolValidator);await provider.initialize();this.storageProvider??=provider;return this.storageProvider}listAllIndexed(){return[...this.localRows,...this.dynamicRows,...[...this.adopted.values()].flat()]}listAllInstances(){return this.listAllIndexed().map(r=>r.instance)}reindex(){const effective=this.listAllIndexed();this.lineages.rebuild(effective);this.byQualifiedId.clear();this.byName.clear();this.byOwnerAndName.clear();for(const r of effective){this.byQualifiedId.set(r.qualifiedId,r);const listByName=this.byName.get(r.baseName)??[];listByName.push(r);this.byName.set(r.baseName,listByName);const key=`${r.ownerKey}:${r.baseName}`;if(!this.byOwnerAndName.has(key)){this.byOwnerAndName.set(key,r)}}}makeRow(token,instance,lineage,source){const ownerKey=ownerKeyOf(lineage);const baseName=instance.name;const qualifiedName=qualifiedNameOf(lineage,baseName);const qualifiedId=`${ownerKey}:${tokenName15(token)}`;return{token,instance,baseName,lineage,ownerKey,qualifiedName,qualifiedId,source}}relineage(row,prepend){const lineage=[...prepend,...row.lineage];const ownerKey=ownerKeyOf(lineage);const qualifiedName=qualifiedNameOf(lineage,row.baseName);const qualifiedId=`${ownerKey}:${tokenName15(row.token)}`;return{token:row.token,instance:row.instance,baseName:row.baseName,lineage,ownerKey,qualifiedName,qualifiedId,source:row.source}}bump(kind){const version=++this.version;this.emitter.emit({kind,changeScope:"global",version,snapshot:this.listAllInstances()})}setExternalProvider(provider){this.externalProvider=provider;if(provider.isReadOnly()){this.storageProvider=provider;this.storageProviderLoad=Promise.resolve(provider);this.scope.logger.info("[SkillRegistry] Using external provider in read-only mode")}else{this.scope.logger.info("[SkillRegistry] External provider configured for persistent sync")}}getExternalProvider(){return this.externalProvider}hasExternalProvider(){return this.externalProvider!==void 0}async syncToExternal(){if(!this.externalProvider){this.scope.logger.debug("[SkillRegistry] No external provider configured, skipping sync");return null}if(this.externalProvider.isReadOnly()){this.scope.logger.debug("[SkillRegistry] External provider is read-only, skipping sync");return null}const localSkills=[];const allIndexed=this.listAllIndexed();for(const row of allIndexed){try{const content=await row.instance.load();localSkills.push(content)}catch(error){this.scope.logger.warn(`[SkillRegistry] Failed to load skill for sync: ${row.baseName}`,{error:error instanceof Error?error.message:String(error)})}}this.scope.logger.info("[SkillRegistry] Starting external sync",{skillCount:localSkills.length});const result=await this.externalProvider.syncSkills(localSkills);this.scope.logger.info("[SkillRegistry] External sync complete",{added:result.added.length,updated:result.updated.length,unchanged:result.unchanged.length,removed:result.removed.length,failed:result.failed.length,durationMs:result.durationMs});this.emitter.emit({kind:"synced",changeScope:"global",version:this.version,snapshot:this.listAllInstances(),syncResult:result});return result}}}});import{depsOfClass as depsOfClass9,getMetadata as getMetadata18,isClass as isClass16,tokenName as tokenName16}from"@frontmcp/di";function collectPluginMetadata(cls){return Object.entries(FrontMcpPluginTokens).reduce((metadata,[key,token])=>{return Object.assign(metadata,{[key]:getMetadata18(token,cls)})},{})}function normalizePlugin(item){if(isClass16(item)){const metadata=collectPluginMetadata(item);return{kind:"CLASS_TOKEN",provide:item,metadata}}if(item&&typeof item==="object"){const{provide,useClass,useFactory,useValue,inject,...metadata}=item;if(!provide){const name52=item?.name??"[object]";throw new MissingProvideError("plugin",name52)}if(useClass){if(!isClass16(useClass)){throw new InvalidUseClassError("plugin",tokenName16(provide))}const decoratorMetadata=collectPluginMetadata(useClass);const{providers:_dynamicProviders,...inlineMetadata}=metadata;const mergedMetadata={...decoratorMetadata,...inlineMetadata};return{kind:"CLASS",provide,useClass,metadata:mergedMetadata}}if(useFactory){if(typeof useFactory!=="function"){throw new InvalidUseFactoryError("plugin",tokenName16(provide))}const inj=typeof inject==="function"?inject:()=>[];if(!isClass16(provide)){return{kind:"FACTORY",provide,inject:inj,useFactory,metadata}}const decoratorMetadata=collectPluginMetadata(provide);const{providers:dynamicProviders,...inlineMetadata}=metadata;return{kind:"FACTORY",provide,inject:inj,useFactory,metadata:{...decoratorMetadata,...inlineMetadata},providers:dynamicProviders??[]}}if("useValue"in item){if(useValue===void 0||useValue===null){throw new InvalidUseValueError("plugin",tokenName16(provide))}const decoratorMetadata=collectPluginMetadata(useValue.constructor);const{providers:_dynamicProviders,...inlineMetadata}=metadata;const mergedMetadata={...decoratorMetadata,...inlineMetadata};return{kind:"VALUE",provide,useValue,metadata:mergedMetadata,providers:item.providers??[]}}}const name51=item?.name??String(item);throw new InvalidEntityError("plugin",name51,"a class or a plugin object")}function pluginDiscoveryDeps(rec){switch(rec.kind){case"VALUE":return[];case"FACTORY":{return[...rec.inject()]}case"CLASS":return depsOfClass9(rec.useClass,"discovery").filter(v=>v!==null&&typeof v==="object");case"CLASS_TOKEN":return depsOfClass9(rec.provide,"discovery").filter(v=>v!==null&&typeof v==="object")}}var init_plugin_utils=__esm({"libs/sdk/src/plugin/plugin.utils.ts"(){"use strict";init_common();init_errors()}});import"reflect-metadata";import{tokenName as tokenName17}from"@frontmcp/di";import{getRuntimeContext as getRuntimeContext16}from"@frontmcp/utils";function instantiateClassPlugin(klass,depsInstances,recordProviders){if(!isConfiguredByOptions(klass)){return{pluginInstance:new klass(...depsInstances),dynamicProviders:recordProviders,dynamicTools:[]}}const options={};const optionDerived=collectDynamicProviders(klass,options);const dynamicTools=collectDynamicTools(klass,options);return{pluginInstance:new klass(options),dynamicProviders:optionDerived.length>0?dedupePluginProviders([...optionDerived,...recordProviders??[]]):recordProviders,dynamicTools}}function isConfiguredByOptions(klass){if(isDynamicPluginClass(klass))return true;const hooks=klass;return typeof hooks.dynamicProviders==="function"||typeof hooks.dynamicTools==="function"}var installedPluginValues,PluginRegistry;var init_plugin_registry=__esm({"libs/sdk/src/plugin/plugin.registry.ts"(){"use strict";init_adapter_registry();init_common();init_dynamic_plugin();init_dynamic_utils();init_context_extension();init_errors();init_hooks_utils();init_prompt_registry();init_provider_registry();init_provider_utils();init_regsitry();init_resource_registry();init_browser_stores();init_skill_registry();init_tool_registry();init_plugin_utils();installedPluginValues=new WeakSet;PluginRegistry=class _PluginRegistry extends RegistryAbstract{pProviders=new Map;pPlugins=new Map;pAdapters=new Map;pTools=new Map;pResources=new Map;pPrompts=new Map;pSkills=new Map;scope;scopeInfo;owner;logger;constructor(providers,list,owner,scopeInfo){super("PluginRegistry",providers,list);this.scope=providers.getActiveScope();this.scopeInfo=scopeInfo;this.owner=owner;try{this.logger=providers.get(FrontMcpLogger)?.child("PluginRegistry")}catch{}}getPlugins(){return[...this.instances.values()]}getPluginNames(){return[...this.defs.values()].map(rec=>rec.metadata.name)}getToolRegistries(){return[...this.pTools.values()]}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;for(const raw of list){const rec=normalizePlugin(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)throw new RegistryDependencyNotRegisteredError("Plugin",tokenName17(token),"self");const deps=pluginDiscoveryDeps(rec);for(const d of deps){if(!this.providers.get(d)){throw new RegistryDependencyNotRegisteredError("Plugin",tokenName17(token),tokenName17(d))}const edges=this.graph.get(token);if(edges)edges.add(d)}}}async initialize(){this.logger?.verbose(`PluginRegistry: initializing ${this.tokens.size} plugin(s)`);for(const token of this.tokens){const rec=this.defs.get(token);if(!rec)continue;const deps=this.graph.get(token)??new Set;const providers=new ProviderRegistry(rec.metadata.providers??[],this.providers);await providers.ready;const{pluginInstance,dynamicProviders,dynamicTools}=await this.instantiatePlugin(rec,deps);if(dynamicProviders){await providers.addDynamicProviders(dynamicProviders)}const providerHooks=normalizeHooksFromProviders(providers);const pluginOwner={kind:"plugin",id:rec.metadata.name,ref:token};const nestedHookOwner=this.owner?.kind==="app"||this.owner?.kind==="agent"||this.owner?.kind==="scope"?this.owner:pluginOwner;const plugins=new _PluginRegistry(providers,rec.metadata.plugins??[],nestedHookOwner,this.scopeInfo);await plugins.ready;const adapters=new AdapterRegistry(providers,rec.metadata.adapters??[]);await adapters.ready;if(adapters.getAdapters().length>0)this.scope.onDispose(()=>adapters.dispose());const tools=new ToolRegistry(providers,[...rec.metadata.tools??[],...dynamicTools],pluginOwner);const resources=new ResourceRegistry(providers,rec.metadata.resources??[],pluginOwner);const prompts=new PromptRegistry(providers,rec.metadata.prompts??[],pluginOwner);const skills=new SkillRegistry(providers,rec.metadata.skills??[],pluginOwner);await Promise.all([tools.ready,resources.ready,prompts.ready,skills.ready]);this.providers.addRegistry("ToolRegistry",tools);this.providers.addRegistry("ResourceRegistry",resources);this.providers.addRegistry("PromptRegistry",prompts);this.providers.addRegistry("SkillRegistry",skills);this.pProviders.set(token,providers);this.pPlugins.set(token,plugins);this.pAdapters.set(token,adapters);this.pTools.set(token,tools);this.pResources.set(token,resources);this.pPrompts.set(token,prompts);this.pSkills.set(token,skills);const exported=(rec.metadata.exports??[]).map(rawToken=>{const token2=normalizeProvider(rawToken);return providers.getProviderInfo(token2.provide)});this.providers.mergeFromRegistry(providers,exported);const pluginScope=rec.metadata.scope??"app";if(this.scopeInfo?.isStandaloneApp&&pluginScope==="server"){throw new InvalidPluginScopeError(`Plugin "${rec.metadata.name}" has scope='server' but is used in a standalone app. Server-scoped plugins can only be used in non-standalone apps.`)}const hooks=[...normalizeHooksFromCls(pluginInstance),...providerHooks];if(hooks.length>0){let targetHookScope;let hookOwner=this.owner;if(pluginScope==="server"&&this.scopeInfo?.parentScope){targetHookScope=this.scopeInfo.parentScope;hookOwner=pluginOwner}else{targetHookScope=this.scope;if(pluginScope==="server"&&!this.scopeInfo?.parentScope){this.scope.logger.warn(`Plugin "${rec.metadata.name}" has scope='server' but no parent scope is available. Hooks will be registered to the current scope instead. This may happen for server-level plugins or standalone apps.`)}}const hooksWithOwner=hooks.map(hook=>({...hook,metadata:{...hook.metadata,owner:hookOwner,pluginName:rec.metadata.name}}));await targetHookScope.hooks.registerHooks(false,...hooksWithOwner)}const getFromPluginProviders=providers.get.bind(providers);pluginInstance.get=getFromPluginProviders;this.scope.onDispose(()=>{if(pluginInstance.get===getFromPluginProviders)Reflect.deleteProperty(pluginInstance,"get")});const contextExtensions=rec.metadata.contextExtensions;if(contextExtensions&&contextExtensions.length>0){installContextExtensions(rec.metadata.name,contextExtensions)}if(dynamicProviders){const normalized2=dynamicProviders.map(p=>normalizeProvider(p));const singletons=providers.getAllSingletons();const exported2=normalized2.map(def=>({token:def.provide,def,instance:singletons.get(def.provide)}));this.providers.mergeFromRegistry(providers,exported2);const scopeProviders=this.scope.providers;if(scopeProviders!==this.providers&&scopeProviders instanceof ProviderRegistry){const installedOnScope=!this.owner||this.owner.kind==="scope";const visibleBelow=installedOnScope?void 0:this.providers.subtreeBelow(scopeProviders)??this.providers;scopeProviders.mergeFromRegistry(providers,exported2,visibleBelow)}}this.instances.set(token,pluginInstance);this.logger?.verbose(`PluginRegistry: registered plugin '${rec.metadata.name}' (${hooks.length} hook(s), ${contextExtensions?.length??0} context extension(s))`)}}refuseStoresInBrowser(plugin,options){if(getRuntimeContext16().runtime!=="browser")return;refusePluginStoresInBrowser(declaredPluginStores(plugin,options,this.scope.metadata))}async instantiatePlugin(rec,deps){const depsInstances=await Promise.all([...deps].map(t=>this.providers.resolveBootstrapDep(t)));switch(rec.kind){case"CLASS":this.refuseStoresInBrowser(rec.useClass,{});return instantiateClassPlugin(rec.useClass,depsInstances,rec.providers);case"CLASS_TOKEN":this.refuseStoresInBrowser(rec.provide,{});return instantiateClassPlugin(rec.provide,depsInstances,rec.providers);case"VALUE":{const value=rec.useValue;const recorded=initOptionsOf(value);if(recorded)this.refuseStoresInBrowser(rec.provide,recorded.options);const init=installedPluginValues.has(value)?recorded:void 0;installedPluginValues.add(value);if(init&&isDynamicPluginClass(rec.provide)){return{pluginInstance:new rec.provide(init.options),dynamicProviders:rec.providers,dynamicTools:[]}}return{pluginInstance:value,dynamicProviders:rec.providers,dynamicTools:[]}}case"FACTORY":{const args=[];for(const d of rec.inject())args.push(await this.providers.resolveBootstrapDep(d));const produced=await rec.useFactory(...args);if(isDynamicPluginClass(rec.provide)&&!(produced instanceof rec.provide)){this.refuseStoresInBrowser(rec.provide,produced);const optionDerived=collectDynamicProviders(rec.provide,produced);return{pluginInstance:new rec.provide(produced),dynamicProviders:optionDerived.length>0?dedupePluginProviders([...optionDerived,...rec.providers??[]]):rec.providers,dynamicTools:collectDynamicTools(rec.provide,produced)}}return{pluginInstance:produced,dynamicProviders:rec.providers,dynamicTools:[]}}default:throw new InvalidRegistryKindError("plugin",rec.kind)}}}}});import{AsyncLocalStorage as AsyncLocalStorage6}from"@frontmcp/utils";function runAsAgent(agent,fn){return chains.run([...getAgentCallChain(),agent],fn)}function getAgentCallChain(){return chains.getStore()??[]}function nextAgentCallDepth(){const chain=getAgentCallChain();if(chain.length===0)return void 0;const limit=Math.min(...chain.map(agent=>agent.maxCallDepth));return{depth:chain.length,limit,chain}}var DEFAULT_MAX_AGENT_CALL_DEPTH,chains;var init_agent_call_chain=__esm({"libs/sdk/src/agent/agent-call-chain.ts"(){"use strict";DEFAULT_MAX_AGENT_CALL_DEPTH=3;chains=new AsyncLocalStorage6}});import{AuthorityDeniedError as AuthorityDeniedError7,resolveRequiredScopes as resolveRequiredScopes6}from"@frontmcp/auth";import{ExecutionTimeoutError as ExecutionTimeoutError2,withTimeout as withTimeout2}from"@frontmcp/guard";import{internalZ as z88}from"@frontmcp/lazy-zod";import{CallToolRequestSchema as CallToolRequestSchema3,CallToolResultSchema as CallToolResultSchema3}from"@frontmcp/protocol";function invalidOutputFrom(outputError){return outputError instanceof InvalidOutputError?outputError:new InvalidOutputError}function findAgentForCall(agents,toolName){return agents.findById(toolName)??agents.findByName(toolName)??agents.getAgents(true).find(entry=>entry.fullName===toolName||entry.name===toolName)}var inputSchema11,outputSchema11,stateSchema11,plan11,name11,agentClassHooksJoin,Stage11,CallAgentFlow;var init_call_agent_flow=__esm({"libs/sdk/src/agent/flows/call-agent.flow.ts"(){"use strict";init_completion_events();init_common();init_errors();init_entry_class_hooks();init_hooks_utils();init_flow_context_providers();init_abort_utils();init_agent_call_chain();inputSchema11=z88.object({request:CallToolRequestSchema3,ctx:z88.any(),gatedBy:z88.literal("tools:call-tool").optional()});outputSchema11=CallToolResultSchema3;stateSchema11=z88.object({input:z88.looseObject({name:z88.string().min(1).max(128),arguments:z88.looseObject({}).optional()}),authInfo:z88.any().optional(),agent:z88.instanceof(AgentEntry),agentContext:z88.instanceof(AgentContext),rawOutput:z88.any().optional(),output:outputSchema11,_agentOwnerId:z88.string().optional(),progressToken:z88.union([z88.string(),z88.number()]).optional(),jsonRpcRequestId:z88.union([z88.string(),z88.number()]).optional(),executionMeta:z88.object({iterations:z88.number().optional(),durationMs:z88.number().optional(),usage:z88.object({promptTokens:z88.number().optional(),completionTokens:z88.number().optional(),totalTokens:z88.number().optional()}).optional()}).optional(),semaphoreTicket:z88.any().optional(),abandonedExecution:z88.instanceof(Promise).optional(),executionAbort:z88.instanceof(AbortController).optional(),executionStartedAt:z88.number().optional(),executionError:z88.any().optional(),parsedOutput:z88.any().optional(),outputError:z88.any().optional()});plan11={pre:["parseInput","findAgent","checkCallDepth","checkEntryAuthorities","checkAgentAuthorization","createAgentContext","acquireQuota","acquireSemaphore"],execute:["validateInput","execute","validateOutput"],finalize:["releaseSemaphore","releaseQuota","parseOutput","emitCompletion","finalize"]};name11="agents:call-agent";agentClassHooksJoin=entryClassHooksJoin({flow:name11,plan:plan11,contextStage:"createAgentContext"});({Stage:Stage11}=FlowHooksOf(name11));CallAgentFlow=class extends FlowBase{static resolveHookEntryClass(rawInput,scope){const toolName=rawInput?.request?.params?.name;if(typeof toolName!=="string"||!scope.agents)return void 0;return findAgentForCall(scope.agents,toolName)?.record.provide}logger=this.scopeLogger.child("CallAgentFlow");get gatedByToolFlow(){return this.input.gatedBy==="tools:call-tool"}async parseInput(){this.logger.verbose("parseInput:start");let method;let params;let ctx;try{const inputData=inputSchema11.parse(this.rawInput);method=inputData.request.method;params=inputData.request.params;ctx=inputData.ctx}catch(e){throw new InvalidInputError("Invalid Input",e instanceof z88.ZodError?e.issues:void 0)}if(method!=="tools/call"){this.logger.warn(`parseInput: invalid method "${method}"`);throw new InvalidMethodError(method,"tools/call")}const{name:toolName}=params;const agentId=toolName;let agent;if(this.scope.agents){agent=this.scope.agents.findById(agentId)??this.scope.agents.findByName(agentId)}const agentOwnerId=agent?.owner?.id;const progressToken=params._meta?.progressToken;const jsonRpcRequestId=ctx.requestId;this.state.set({input:params,authInfo:ctx.authInfo,_agentOwnerId:agentOwnerId,progressToken,jsonRpcRequestId});this.logger.verbose("parseInput:done")}async findAgent(){this.logger.verbose("findAgent:start");const agents=this.scope.agents;if(!agents){this.logger.warn("findAgent: no agent registry available");throw new AgentNotFoundError(this.state.required.input.name)}const activeAgents=agents.getAgents(true);this.logger.verbose(`findAgent: discovered ${activeAgents.length} active agent(s) (including hidden)`);const{name:toolName}=this.state.required.input;const agentId=toolName;const agent=findAgentForCall(agents,toolName);if(!agent){this.logger.warn(`findAgent: agent "${agentId}" not found`);throw new AgentNotFoundError(agentId)}this.logger=this.logger.child(`CallAgentFlow(${agent.name})`);this.state.set("agent",agent);this.logger.verbose(`findAgent: agent "${agent.name}" found`);this.logger.verbose("findAgent:done")}async checkCallDepth(){const next=nextAgentCallDepth();if(!next||next.depth<=next.limit)return;const agent=this.state.required.agent;this.logger.warn(`checkCallDepth: agent call ${next.depth} exceeds maxCallDepth ${next.limit}`);throw new AgentCallDepthExceededError(agent.id,next.chain.map(running=>running.id),next.limit)}async checkEntryAuthorities(){this.logger.verbose("checkEntryAuthorities:start");if(this.gatedByToolFlow){this.logger.verbose("checkEntryAuthorities:skip (checked by the invoke tool flow)");return}const engine=this.scope.authoritiesEngine;const ctxBuilder=this.scope.authoritiesContextBuilder;if(!engine||!ctxBuilder){this.logger.verbose("checkEntryAuthorities:skip (no engine configured)");return}const agent=this.state.agent;if(!agent)return;const metadata=agent.metadata;const authorities=metadata["authorities"];if(!authorities){this.logger.verbose("checkEntryAuthorities:skip (no authorities on agent)");return}const authInfo=this.state.authInfo??{};const stateInput=this.state.input;const input=stateInput?.["arguments"]??stateInput??{};const evalCtx=ctxBuilder.build(authInfo,input);const result=await engine.evaluate(authorities,evalCtx);if(!result.granted){let requiredScopes;const scopeMapping=this.scope.authoritiesScopeMapping;if(scopeMapping&&result.denial){requiredScopes=resolveRequiredScopes6(result.denial,scopeMapping,authorities)}throw new AuthorityDeniedError7({entryType:"Agent",entryName:agent.fullName||agent.name,deniedBy:result.deniedBy??"policy denied",denial:result.denial,requiredScopes})}this.logger.verbose("checkEntryAuthorities:done")}async checkAgentAuthorization(){this.logger.verbose("checkAgentAuthorization:start");const{agent,authInfo}=this.state;const authorization=authInfo?.extra?.["authorization"];if(!authorization){this.logger.verbose("checkAgentAuthorization:skip (no auth context)");return}const appId=agent?.owner?.id;if(!appId){this.logger.verbose("checkAgentAuthorization:skip (no owner)");return}const isAppAuthorized=authorization.authorizedAppIds?.includes(appId)||appId in(authorization.authorizedApps||{});if(!isAppAuthorized){this.logger.verbose(`checkAgentAuthorization: app "${appId}" not authorized, but proceeding`)}this.logger.verbose("checkAgentAuthorization:done")}async createAgentContext(){this.logger.verbose("createAgentContext:start");const{ctx}=this.input;const{agent,input}=this.state.required;const progressToken=this.state.progressToken;const authInfo=this.state.authInfo;try{const sessionKey=authInfo?.sessionId??"anonymous";const agentViews=await agent.providers.buildViews(sessionKey,new Map(this.deps),this.scope.providers);const contextProviders=new FlowContextProviders(agent.providers,agentViews.context);const executionAbort=linkedAbortController(ctx.signal);this.state.set("executionAbort",executionAbort);const context=agent.create(input.arguments,{...ctx,progressToken,contextProviders,signal:executionAbort.signal});await context.loadAuthContext();this.appendContextHooks(hooksBoundTo(this.scope.hooks.getClsHooks(agent.record.provide),context));context.mark("createAgentContext");const frontmcpContext=context.tryGetContext();const sdkAuthInfo=authInfo;const jsonRpcRequestId=this.state.jsonRpcRequestId;if(frontmcpContext&&sdkAuthInfo?.transport?.sendElicitRequest&&jsonRpcRequestId!==void 0){const transport=sdkAuthInfo.transport;frontmcpContext.setTransport({sendElicitRequest:transport.sendElicitRequest.bind(transport),type:transport.type??"unknown",jsonRpcRequestId})}this.state.set("agentContext",context);this.logger.verbose("createAgentContext:done")}catch(error){this.logger.error("createAgentContext: failed to create context",error);throw new AgentExecutionError(agent.metadata.name,error instanceof Error?error:void 0)}}async acquireQuota(){this.logger.verbose("acquireQuota:start");const manager=this.scope.rateLimitManager;if(!manager||this.gatedByToolFlow){this.state.agentContext?.mark("acquireQuota");this.logger.verbose("acquireQuota:done (no rate limit manager)");return}const{agent}=this.state.required;const context=this.tryGetContext();const partitionCtx=buildPartitionContext(context);if(!context?.has(GLOBAL_RATE_LIMIT_CHECKED)){const globalResult=await manager.checkGlobalRateLimit(partitionCtx);if(!globalResult.allowed){throw new RateLimitError(Math.ceil((globalResult.retryAfterMs??6e4)/1e3))}}const result=await manager.checkRateLimit(agent.metadata.name,agent.metadata.rateLimit,partitionCtx);if(!result.allowed){throw new RateLimitError(Math.ceil((result.retryAfterMs??6e4)/1e3))}this.state.agentContext?.mark("acquireQuota");this.logger.verbose("acquireQuota:done")}async acquireSemaphore(){this.logger.verbose("acquireSemaphore:start");const manager=this.scope.rateLimitManager;if(!manager||this.gatedByToolFlow){this.state.agentContext?.mark("acquireSemaphore");this.logger.verbose("acquireSemaphore:done (no rate limit manager)");return}const{agent}=this.state.required;const partitionCtx=buildPartitionContext(this.tryGetContext());const ticket=await acquireConcurrencySlots(manager,agent.metadata.name,agent.metadata.concurrency,partitionCtx);this.state.set("semaphoreTicket",ticket);this.state.agentContext?.mark("acquireSemaphore");this.logger.verbose("acquireSemaphore:done")}async validateInput(){this.logger.verbose("validateInput:start");const{agent,input}=this.state.required;const{agentContext}=this.state;if(!agentContext){return}agentContext.mark("validateInput");try{agentContext.input=agent.parseInput(input);this.logger.verbose("validateInput:done")}catch(err){if(err instanceof z88.ZodError){throw new InvalidInputError("Invalid agent input",err.issues)}this.logger.error("validateInput: failed to parse input",err);throw new InvalidInputError("Unknown error occurred when trying to parse agent input")}}async execute(){this.logger.verbose("execute:start");const agentContext=this.state.agentContext;const agent=this.state.agent;if(!agentContext||!agent){return}agentContext.mark("execute");const startTime=Date.now();this.state.set("executionStartedAt",startTime);const timeoutMs=this.gatedByToolFlow?agent.metadata.timeout?.executeMs===void 0?agent.metadata.execution?.timeout:void 0:agent.metadata.timeout?.executeMs??agent.metadata.execution?.timeout??this.scope.rateLimitManager?.config?.defaultTimeout?.executeMs;const runningAgent={id:agent.id,maxCallDepth:agent.metadata.swarm?.maxCallDepth??DEFAULT_MAX_AGENT_CALL_DEPTH};const running=runAsAgent(runningAgent,async()=>{agentContext.output=await agentContext.execute(agentContext.input)});try{await(timeoutMs?withTimeout2(()=>running,timeoutMs,agent.metadata.name):running);this.state.set("executionMeta",{durationMs:Date.now()-startTime});this.logger.verbose("execute:done")}catch(error){this.state.executionAbort?.abort(error);this.state.set("executionError",error);if(error instanceof ExecutionTimeoutError2){this.logger.warn("execute: agent execution timed out",{agent:agent.metadata.name,timeoutMs});this.state.set("abandonedExecution",running);throw error}if(this.gatedByToolFlow)throw error;throw new AgentExecutionError(agent.metadata.name,error instanceof Error?error:void 0)}}async validateOutput(){this.logger.verbose("validateOutput:start");const{agentContext}=this.state;if(!agentContext){return}agentContext.mark("validateOutput");this.state.set("rawOutput",agentContext.output);this.logger.verbose("validateOutput:done")}async releaseSemaphore(){this.logger.verbose("releaseSemaphore:start");const ticket=this.state.semaphoreTicket;if(ticket){const release=async()=>{try{await ticket.release();this.logger.verbose("releaseSemaphore: slot released")}catch(error){this.logger.warn("releaseSemaphore: failed to release slot",error)}};const abandonedExecution=this.state.abandonedExecution;if(abandonedExecution)void abandonedExecution.then(release,release);else await release()}this.state.agentContext?.mark("releaseSemaphore");this.logger.verbose("releaseSemaphore:done")}async releaseQuota(){this.logger.verbose("releaseQuota:start");this.state.agentContext?.mark("releaseQuota");this.logger.verbose("releaseQuota:done")}async parseOutput(){const{agent,rawOutput}=this.state;if(!agent||rawOutput===void 0)return;const parseResult=agent.safeParseOutput(rawOutput);if(parseResult.success)this.state.set("parsedOutput",parseResult.data);else this.state.set("outputError",parseResult.error)}async emitCompletion(){const{agent,agentContext,executionStartedAt,executionError,outputError,authInfo}=this.state;if(!agent||executionStartedAt===void 0)return;if(executionError instanceof ElicitationFallbackRequired||executionError instanceof FlowControl)return;const failure=executionError??(outputError!==void 0?invalidOutputFrom(outputError):void 0);const failed=failure!==void 0;const requestId=this.tryGetContext()?.requestId;const sessionId=typeof authInfo?.sessionId==="string"&&authInfo.sessionId?authInfo.sessionId:void 0;completionEventsOf(this.scope).agents.emit({agentId:agent.id,agentName:agent.name,status:failed?"error":"success",durationMs:Date.now()-executionStartedAt,...failed?{error:failure instanceof Error?failure.message:String(failure)}:{output:completionOutputText(agentContext?.output)},...requestId?{runId:requestId}:{},...sessionId?{sessionId}:{}})}async finalize(){this.logger.verbose("finalize:start");const{agent,rawOutput,parsedOutput,outputError,executionMeta}=this.state;if(!agent){this.logger.verbose("finalize: skipping (no agent in state)");return}if(rawOutput===void 0){this.logger.verbose("finalize: skipping (no output - execute stage likely failed)");return}if(outputError!==void 0||parsedOutput===void 0){this.logger.error("finalize: output validation failed",{agent:agent.metadata.name,errors:outputError});throw invalidOutputFrom(outputError)}const result=parsedOutput;if(executionMeta){result._meta={...result._meta,"agent/execution":{agentId:agent.id,agentName:agent.name,durationMs:executionMeta.durationMs,iterations:executionMeta.iterations,usage:executionMeta.usage}}}this.logger.verbose("finalize: sending response",{agent:agent.metadata.name,hasContent:Array.isArray(result.content)&&result.content.length>0,contentParts:Array.isArray(result.content)?result.content.length:0,contentBytes:Array.isArray(result.content)?result.content.reduce((sum,part)=>{const str=JSON.stringify(part);return sum+(typeof Buffer!=="undefined"?Buffer.byteLength(str,"utf8"):new TextEncoder().encode(str).byteLength)},0):0,hasStructuredContent:result.structuredContent!==void 0,hasMeta:result._meta!==void 0,metaKeys:result._meta?Object.keys(result._meta):[],isError:result.isError});this.respond(result);this.logger.verbose("finalize:done")}};__decorateClass([Stage11("parseInput")],CallAgentFlow.prototype,"parseInput",1);__decorateClass([Stage11("findAgent")],CallAgentFlow.prototype,"findAgent",1);__decorateClass([Stage11("checkCallDepth")],CallAgentFlow.prototype,"checkCallDepth",1);__decorateClass([Stage11("checkEntryAuthorities")],CallAgentFlow.prototype,"checkEntryAuthorities",1);__decorateClass([Stage11("checkAgentAuthorization")],CallAgentFlow.prototype,"checkAgentAuthorization",1);__decorateClass([Stage11("createAgentContext")],CallAgentFlow.prototype,"createAgentContext",1);__decorateClass([Stage11("acquireQuota")],CallAgentFlow.prototype,"acquireQuota",1);__decorateClass([Stage11("acquireSemaphore")],CallAgentFlow.prototype,"acquireSemaphore",1);__decorateClass([Stage11("validateInput")],CallAgentFlow.prototype,"validateInput",1);__decorateClass([Stage11("execute")],CallAgentFlow.prototype,"execute",1);__decorateClass([Stage11("validateOutput")],CallAgentFlow.prototype,"validateOutput",1);__decorateClass([Stage11("releaseSemaphore")],CallAgentFlow.prototype,"releaseSemaphore",1);__decorateClass([Stage11("releaseQuota")],CallAgentFlow.prototype,"releaseQuota",1);__decorateClass([Stage11("parseOutput")],CallAgentFlow.prototype,"parseOutput",1);__decorateClass([Stage11("emitCompletion")],CallAgentFlow.prototype,"emitCompletion",1);__decorateClass([Stage11("finalize")],CallAgentFlow.prototype,"finalize",1);CallAgentFlow=__decorateClass([FrontMcpFlow({name:name11,plan:plan11,inputSchema:inputSchema11,outputSchema:outputSchema11,access:"authorized"})],CallAgentFlow)}});import"reflect-metadata";import{ProviderScope as ProviderScope5}from"@frontmcp/di";var AgentScope,AgentScopeEntry;var init_agent_scope=__esm({"libs/sdk/src/agent/agent.scope.ts"(){"use strict";init_adapter_registry();init_common();init_errors();init_flow_registry();init_hook_order();init_hook_registry();init_plugin_registry();init_get_prompt_flow();init_prompts_list_flow();init_prompt_registry();init_provider_registry();init_read_resource_flow();init_resource_templates_list_flow();init_resources_list_flow();init_resource_registry();init_scope();init_call_tool_flow();init_tool_instance();init_tool_registry();init_tool_utils();init_agent_registry();init_call_agent_flow();AgentScope=class _AgentScope{constructor(parentScope,agentId,metadata,agentToken,options){this.metadata=metadata;this.options=options;this.parentScope=parentScope;this.id=`agent:${agentId}`;this.entryPath=parentScope.entryPath;this.routeBase=parentScope.routeBase;this.fullPath=parentScope.fullPath;this.logger=parentScope.logger.child(`AgentScope(${agentId})`);this.agentOwner={kind:"agent",id:this.id,ref:agentToken};this.ready=this.initialize()}metadata;options;id;entryPath;routeBase;fullPath;logger;ready;parentScope;agentOwner;agentProviders;agentPlugins;agentAdapters;agentTools;agentResources;agentPrompts;agentAgents;agentHooks;agentFlows;async initialize(){const agentScopeEntry=new AgentScopeEntry(this);this.agentProviders=new ProviderRegistry([{scope:ProviderScope5.GLOBAL,name:"ScopeEntry",provide:ScopeEntry,useValue:agentScopeEntry},{scope:ProviderScope5.GLOBAL,name:"Scope",provide:Scope,useValue:agentScopeEntry},{scope:ProviderScope5.GLOBAL,name:"AgentScope",provide:_AgentScope,useValue:this},{scope:ProviderScope5.GLOBAL,name:"FrontMcpLogger",provide:FrontMcpLogger,useValue:this.logger},...this.metadata.providers??[]],this.options?.providers??this.parentScope.providers);await this.agentProviders.ready;this.agentHooks=new HookRegistry(this.agentProviders,[]);await this.agentHooks.ready;if(this.metadata.execution?.inheritPlugins===true&&this.options){this.agentHooks.inheritFrom(this.parentScope.hooks,this.options.ownerId)}this.agentFlows=new FlowRegistry(this.agentProviders,[CallToolFlow,CallAgentFlow,ReadResourceFlow,ResourcesListFlow,ResourceTemplatesListFlow,GetPromptFlow,PromptsListFlow]);await this.agentFlows.ready;const pluginOwner={kind:"agent",id:this.id,ref:this.agentOwner.ref};this.agentPlugins=new PluginRegistry(this.agentProviders,this.metadata.plugins??[],pluginOwner);await this.agentPlugins.ready;this.agentAdapters=new AdapterRegistry(this.agentProviders,this.metadata.adapters??[]);await this.agentAdapters.ready;this.agentTools=new ToolRegistry(this.agentProviders,[],this.agentOwner);await this.agentTools.ready;const toolTypes=this.metadata.tools??[];for(const toolType of toolTypes){try{const record=normalizeTool(toolType);if(isExternalToolRecord(record)){await this.agentTools.registerExternalTools([record]);continue}const toolInstance=new ToolInstance(record,this.agentProviders,this.agentOwner);await toolInstance.ready;this.agentTools.registerToolInstance(toolInstance)}catch(error){this.logger.error(`Failed to initialize tool in agent scope ${this.id}`,error);throw error}}this.agentResources=new ResourceRegistry(this.agentProviders,this.metadata.resources??[],this.agentOwner);await this.agentResources.ready;this.agentPrompts=new PromptRegistry(this.agentProviders,this.metadata.prompts??[],this.agentOwner);await this.agentPrompts.ready;this.agentAgents=new AgentRegistry(this.agentProviders,this.metadata.agents??[],this.agentOwner);await this.agentAgents.ready;checkHookOrder(hookRunsOf(this.agentHooks),message=>this.logger.warn(message));this.logger.info(`AgentScope initialized with ${toolTypes.length} tool(s), ${this.metadata.plugins?.length??0} plugin(s)`)}get tools(){return this.agentTools}get hooks(){return this.agentHooks}get providers(){return this.agentProviders}get plugins(){return this.agentPlugins}get adapters(){return this.agentAdapters}get resources(){return this.agentResources}get prompts(){return this.agentPrompts}get agents(){return this.agentAgents}get auth(){return this.parentScope.auth}get authProviders(){return this.parentScope.authProviders}get apps(){return this.parentScope.apps}get notifications(){return this.parentScope.notifications}onDispose(callback){return this.parentScope.onDispose(callback)}get toolUI(){return this.parentScope.toolUI}get skills(){return this.parentScope.skills}get scopeMetadata(){return this.parentScope.metadata}get authoritiesEngine(){return this.parentScope.authoritiesEngine}get authoritiesContextBuilder(){return this.parentScope.authoritiesContextBuilder}get authoritiesScopeMapping(){return this.parentScope.authoritiesScopeMapping}get rateLimitManager(){return this.parentScope.rateLimitManager}get persistentQuestions(){return this.parentScope.persistentQuestions}get publicAccessGuard(){return this.parentScope.publicAccessGuard}async registryFlows(...flows){await this.agentFlows.registryFlows(flows)}runFlow(name51,input,deps){return this.agentFlows.runFlow(name51,input,deps)}async runFlowForOutput(name51,input,deps){const result=await this.agentFlows.runFlow(name51,input,deps);if(result!==void 0){return result}throw new FlowExitedWithoutOutputError}};AgentScopeEntry=class{constructor(agentScope){this.agentScope=agentScope;this.id=agentScope.id;this.entryPath=agentScope.entryPath;this.routeBase=agentScope.routeBase;this.fullPath=agentScope.fullPath;this.logger=agentScope.logger}agentScope;id;entryPath;routeBase;fullPath;logger;get auth(){return this.agentScope.auth}get hooks(){return this.agentScope.hooks}get authProviders(){return this.agentScope.authProviders}get providers(){return this.agentScope.providers}get apps(){return this.agentScope.apps}get tools(){return this.agentScope.tools}get resources(){return this.agentScope.resources}get prompts(){return this.agentScope.prompts}get agents(){return this.agentScope.agents}get skills(){return this.agentScope.skills}get notifications(){return this.agentScope.notifications}get toolUI(){return this.agentScope.toolUI}get transportService(){return void 0}get rateLimitManager(){return this.agentScope.rateLimitManager}get publicAccessGuard(){return this.agentScope.publicAccessGuard}get elicitationStore(){return void 0}get persistentQuestions(){return this.agentScope.persistentQuestions}get metadata(){return this.agentScope.scopeMetadata}get authoritiesEngine(){return this.agentScope.authoritiesEngine}get authoritiesContextBuilder(){return this.agentScope.authoritiesContextBuilder}get authoritiesScopeMapping(){return this.agentScope.authoritiesScopeMapping}get record(){return void 0}get ready(){return this.agentScope.ready}onDispose(callback){return this.agentScope.onDispose(callback)}registryFlows(...flows){return this.agentScope.registryFlows(...flows)}runFlow(name51,input,deps){return this.agentScope.runFlow(name51,input,deps)}runFlowForOutput(name51,input,deps){return this.agentScope.runFlowForOutput(name51,input,deps)}}}});var agent_instance_exports={};__export(agent_instance_exports,{AGENT_ONLY_METADATA_KEYS:()=>AGENT_ONLY_METADATA_KEYS,AgentInstance:()=>AgentInstance});import{AuthorityDeniedError as AuthorityDeniedError8}from"@frontmcp/auth";import{toJSONSchema as toJSONSchema5,internalZ as z89}from"@frontmcp/lazy-zod";var VALID_AGENT_HOOK_FLOWS,AGENT_SURFACE2,AGENT_ONLY_METADATA_KEYS,AgentInstance,FunctionAgentContext;var init_agent_instance=__esm({"libs/sdk/src/agent/agent.instance.ts"(){"use strict";init_config();init_common();init_availability();init_tool_decorator();init_call_surface();init_running_tool();init_errors();init_entry_class_hooks();init_hooks_utils();init_prompt_utils();init_provider_utils();init_resource_utils();init_tool_instance();init_tool_utils();init_mcp_error_utils();init_adapters();init_agent_builtin_tools();init_agent_scope();init_agent_utils();init_call_agent_flow();VALID_AGENT_HOOK_FLOWS=["agents:call-agent","agents:list-agents"];AGENT_SURFACE2="agent";AGENT_ONLY_METADATA_KEYS=new Set(["id","name","description","systemInstructions","inputSchema","outputSchema","llm","providers","plugins","adapters","agents","tools","resources","prompts","exports","swarm","execution","tags","hideFromDiscovery"]);AgentInstance=class extends AgentEntry{providerRegistry;scope;hooks;llmAdapter=null;agentTools=[];agentScope=null;agentToolInstance=null;exportedResources=[];exportedPrompts=[];constructor(record,providers,owner){super(record);this.owner=owner;this.providerRegistry=providers;this.name=record.metadata.id??record.metadata.name;this.id=record.metadata.id??record.metadata.name;this.fullName=this.owner.id+":"+this.name;this.scope=this.providerRegistry.getActiveScope();this.hooks=this.scope.hooks;this.inputSchema=record.metadata.inputSchema??{};this.outputSchema=record.metadata.outputSchema;this.systemInstructions=record.metadata.systemInstructions;this.ready=this.initialize()}async initialize(){await this.initializeAgentTools();this.assertNoBuiltinToolClash();await this.initializeLlmAdapter();await this.registerHooks();await this.createAgentAsTool()}assertNoBuiltinToolClash(){if(!this.agentScope)return;const builtins=new Set(offeredAgentBuiltinTools(this.agentScope));const clash=this.agentTools.find(tool=>builtins.has(tool.metadata.id??tool.metadata.name));if(!clash)return;throw new AgentConfigurationError(`Agent "${this.name}" has a tool named "${clash.metadata.id??clash.metadata.name}", the name of a built-in tool its model reads the agent's resources and prompts with. Rename the tool.`,{agentId:this.id})}async initializeAgentTools(){const metadata=this.record.metadata;const hasTools=(metadata.tools?.length??0)>0;const hasPlugins=(metadata.plugins?.length??0)>0;const hasAdapters=(metadata.adapters?.length??0)>0;const hasProviders=(metadata.providers?.length??0)>0;const hasResources=(metadata.resources?.length??0)>0;const hasPrompts=(metadata.prompts?.length??0)>0;const hasAgents=(metadata.agents?.length??0)>0;if(!hasTools&&!hasPlugins&&!hasAdapters&&!hasProviders&&!hasResources&&!hasPrompts&&!hasAgents){this.resolveExports(void 0);return}this.agentScope=new AgentScope(this.scope,this.id,metadata,this.record.provide,{ownerId:this.owner.id,providers:this.providerRegistry});await this.agentScope.ready;this.agentTools=this.agentScope.tools.getTools(true);this.resolveExports(this.agentScope);this.scope.logger.info(`Agent ${this.name} initialized with AgentScope: ${this.agentTools.length} tool(s), ${metadata.plugins?.length??0} plugin(s)`)}resolveExports(agentScope){const exportsConfig=this.record.metadata.exports;if(!exportsConfig)return;const resources=agentScope?.resources.getInlineResources()??[];if(exportsConfig.resources==="*"){this.exportedResources=resources}else if(exportsConfig.resources){this.exportedResources=exportsConfig.resources.map(item=>{const token=(isResourceTemplate(item)?normalizeResourceTemplate(item):normalizeResource(item)).provide;const entry=resources.find(resource=>resource.record.provide===token);if(!entry)throw this.undeclaredExportError("resources",token);return entry})}const prompts=agentScope?.prompts.getInlinePrompts()??[];if(exportsConfig.prompts==="*"){this.exportedPrompts=prompts}else if(exportsConfig.prompts){this.exportedPrompts=exportsConfig.prompts.map(item=>{const token=normalizePrompt(item).provide;const entry=prompts.find(prompt=>prompt.record.provide===token);if(!entry)throw this.undeclaredExportError("prompts",token);return entry})}if(exportsConfig.providers&&exportsConfig.providers.length>0){const declared=new Set((this.record.metadata.providers??[]).map(item=>normalizeProvider(item).provide));const tokens=exportsConfig.providers.map(item=>{const token=normalizeProvider(item).provide;if(!declared.has(token)||!agentScope)throw this.undeclaredExportError("providers",token);return token});if(agentScope){const exported=tokens.map(token=>agentScope.providers.getProviderInfo(token));this.providerRegistry.mergeFromRegistry(agentScope.providers,exported)}}}undeclaredExportError(kind,token){const label=typeof token==="function"?token.name||"(anonymous)":typeof token==="symbol"?token.description??token.toString():String(token);return new AgentConfigurationError(`Agent "${this.name}" exports ${kind} "${label}", which is not one of its own ${kind} (\`${kind}: [...]\`)`,{agentId:this.id})}getExportedResources(){return this.exportedResources}getExportedPrompts(){return this.exportedPrompts}async initializeLlmAdapter(){const llmConfig=this.record.metadata.llm;if(!llmConfig){return}const adapterOptions={providerResolver:{get:token=>{return this.providerRegistry.get(token)},tryGet:token=>{try{return this.providerRegistry.get(token)}catch{return void 0}}},entityContext:{entityType:"agents",entityName:this.name}};try{const configService=this.providerRegistry.get(ConfigService);if(configService){adapterOptions.configResolver=this.createConfigResolver(configService)}}catch{this.scope.logger.debug(`ConfigService not available for agent ${this.name} - withConfig resolution disabled`)}try{this.llmAdapter=createAdapter(llmConfig,adapterOptions)}catch(error){this.scope.logger.error(`Failed to create LLM adapter for agent ${this.name}`,error);throw error}}createConfigResolver(configService){const config=configService.getAll();const getNestedValue2=path4=>{const keys=path4.split(".");let current=config;for(const key of keys){if(current&&typeof current==="object"&&key in current){current=current[key]}else{return void 0}}return current};return{get(path4){const value=getNestedValue2(path4);if(value===void 0){throw new AgentConfigKeyNotFoundError(path4)}return value},tryGet(path4){return getNestedValue2(path4)}}}async registerHooks(){const allHooks=normalizeHooksFromCls(this.record.provide);const validHooks=allHooks.filter(hook=>VALID_AGENT_HOOK_FLOWS.includes(hook.metadata.flow));const invalidHooks=allHooks.filter(hook=>!VALID_AGENT_HOOK_FLOWS.includes(hook.metadata.flow));if(invalidHooks.length>0){const className=this.getClassName();const invalidFlowNames=invalidHooks.map(h2=>h2.metadata.flow).join(", ");throw new InvalidHookFlowError(`Agent "${className}" has hooks for unsupported flows: ${invalidFlowNames}. Only agent flows (${VALID_AGENT_HOOK_FLOWS.join(", ")}) are supported on agent classes.`)}const unreachable=describeUnreachableEntryClassHooks(validHooks,agentClassHooksJoin,["agents:list-agents"]);if(unreachable.length>0){throw new InvalidHookFlowError(unreachableHooksMessage("Agent",this.getClassName(),unreachable))}if(validHooks.length>0){await this.hooks.registerHooks(true,...validHooks)}}getClassName(){const provide=this.record.provide;if(typeof provide==="function"&&"name"in provide){return provide.name}return"Unknown"}async createAgentAsTool(){if(!this.llmAdapter){this.scope.logger.debug(`Agent ${this.name} has no LLM adapter configured - skipping tool registration. Agent will not be callable as a tool via invoke_${this.id}.`);return}try{const toolMetadata=this.buildAgentToolMetadata();const agentToolFunction=frontMcpTool(toolMetadata)(this.createAgentToolExecuteHandler());const toolRecord=normalizeTool(agentToolFunction);this.agentToolInstance=new ToolInstance(toolRecord,this.providerRegistry,this.owner);await this.agentToolInstance.ready;this.scope.logger.debug(`Created agent tool instance: ${this.agentToolInstance.name} for agent ${this.name}`)}catch(error){this.scope.logger.error(`Failed to create agent tool instance for ${this.name}`,error);throw error}}buildAgentToolMetadata(){const agentMeta=this.record.metadata;const toolMeta={id:agentToolName(this.id),name:agentToolName(this.id),description:this.buildToolDescription(agentMeta),inputSchema:this.inputSchema??{},outputSchema:agentMeta.outputSchema,tags:[...agentMeta.tags??[],"agent"],annotations:{title:agentMeta.name,readOnlyHint:false,openWorldHint:true},hideFromDiscovery:agentMeta.hideFromDiscovery};const extendedMeta=agentMeta;const mutableToolMeta=toolMeta;for(const[key,value]of Object.entries(extendedMeta)){if(value===void 0||AGENT_ONLY_METADATA_KEYS.has(key)||key in mutableToolMeta)continue;mutableToolMeta[key]=value}return toolMeta}createAgentToolExecuteHandler(){return async(input,toolCtx)=>{const authInfo=toolCtx.authInfo;const progressToken=toolCtx._progressTokenInternal;const requestId=toolCtx._jsonRpcRequestIdInternal;return this.scope.runFlowForOutput("agents:call-agent",{request:{method:"tools/call",params:{name:this.id,arguments:input,...progressToken!==void 0?{_meta:{progressToken}}:{}}},ctx:{authInfo,...requestId!==void 0?{requestId}:{},...toolCtx.signal?{signal:toolCtx.signal}:{}},gatedBy:"tools:call-tool"})}}getToolInstance(){return this.agentToolInstance}get providers(){return this.providerRegistry}getAgentTools(){return this.agentTools}declaresScopedLimits(){if(!this.agentScope)return false;const declaresLimit=tool=>Boolean(tool.metadata.rateLimit||tool.metadata.concurrency);return this.agentScope.tools.getTools(true).some(declaresLimit)||this.agentScope.agents.listAllInstances().some(agent=>agent.declaresScopedLimits())}getMetadata(){return this.record.metadata}getOutputSchema(){return this.outputSchema}getLlmAdapter(){return this.llmAdapter}create(input,ctx){if(!this.llmAdapter){throw new AgentNotConfiguredError(this.name)}const agentCtorArgs=this.buildAgentCtorArgs(input,ctx,this.llmAdapter);switch(this.record.kind){case"CLASS_TOKEN":return new this.record.provide(agentCtorArgs);case"FUNCTION":return new FunctionAgentContext(this.record,agentCtorArgs);case"VALUE":return this.record.useValue;case"FACTORY":return this.record.useFactory(this.providerRegistry);case"ESM":throw new AgentNotConfiguredError(`ESM agent "${this.name}" cannot be created via AgentInstance.create()`);case"REMOTE":throw new AgentNotConfiguredError(`Remote agent "${this.name}" cannot be created via AgentInstance.create()`);default:{const _exhaustive=this.record;throw new Error(`Unknown agent kind: ${_exhaustive.kind}`)}}}buildAgentCtorArgs(input,ctx,llmAdapter){const scope=this.providerRegistry.getActiveScope();const modelTools=this.getModelTools();return{metadata:this.metadata,input,providers:ctx.contextProviders??this.providerRegistry,logger:scope.logger,authInfo:ctx.authInfo,llmAdapter,toolDefinitions:modelTools.map(tool=>tool.kind==="builtin"?AGENT_BUILTIN_TOOL_DEFINITIONS[tool.name]:buildAgentToolDefinition(tool.entry)),toolExecutor:this.createToolExecutor(ctx,modelTools),agentInvoker:this.createAgentInvoker(ctx),...this.agentScope&&{privateScope:this.agentScope},progressToken:ctx.progressToken,signal:ctx.signal}}getModelTools(){const tools=[];const names=new Set;if(this.agentScope){for(const name51 of offeredAgentBuiltinTools(this.agentScope)){names.add(name51);tools.push({kind:"builtin",name:name51,scope:this.agentScope})}}const add=(entry,via)=>{const name51=entry.metadata.id??entry.metadata.name;if(names.has(name51)||!isOfferedOnSurface(entry.metadata.availableWhen,AGENT_SURFACE2))return;names.add(name51);tools.push({kind:"tool",name:name51,entry,via})};const nestedAgentTools=this.getNestedAgentTools();for(const tool of this.agentTools)add(tool,nestedAgentTools.has(tool)?"nested-agent":"agent-scope");for(const agent of this.getSwarmAgents()){const tool=agent.getToolInstance();if(tool)add(tool,"parent-scope")}for(const tool of this.getInheritedTools())add(tool,"parent-scope");return tools}getNestedAgentTools(){const tools=new Set;for(const agent of this.agentScope?.agents.listAllInstances()??[]){const tool=agent.getToolInstance();if(tool)tools.add(tool)}return tools}getSwarmAgents(){if(!this.canSeeSwarm())return[];return this.scope.agents?.getVisibleAgentsFor(this.id)??[]}getInheritedTools(){if(this.record.metadata.execution?.inheritParentTools!==true)return[];const agentTools=new Set;for(const agent of this.scope.agents?.listAllInstances()??[]){const tool=agent.getToolInstance();if(tool)agentTools.add(tool)}return(this.scope.tools?.getTools()??[]).filter(tool=>!agentTools.has(tool))}createToolExecutor(ctx,modelTools){const useToolFlow=this.record.metadata.execution?.useToolFlow!==false;return async(toolName,args)=>{const offered=modelTools.find(t=>t.name===toolName||t.kind==="tool"&&(t.entry.name===toolName||t.entry.fullName===toolName));if(!offered){throw new AgentToolNotFoundError(this.name,toolName,modelTools.map(t=>t.name))}if(offered.kind==="builtin"){return runAgentBuiltinTool(offered.scope,offered.name,args,{authInfo:ctx.authInfo})}const tool=offered.entry;if(offered.via==="parent-scope"){return this.callToolThrough(this.scope,tool,args,ctx)}if(this.agentScope&&(useToolFlow||offered.via==="nested-agent")){return this.callToolThrough(this.agentScope,tool,args,ctx)}await this.assertToolAuthorized(tool,ctx.authInfo,args);const runningTool={name:tool.name,fullName:tool.fullName};return runOnSurface(AGENT_SURFACE2,async()=>{const{contextProviders:_agentProviders,...toolCtx}=ctx;const toolContext=runAsTool(runningTool,()=>tool.create(args,toolCtx));try{return await runAsTool(runningTool,()=>Promise.resolve(toolContext.execute(args)))}catch(error){throw errorBehindFlowControl(error)}})}}async callToolThrough(scope,tool,args,ctx){const result=await scope.runFlowForOutput("tools:call-tool",{request:{method:"tools/call",params:{name:tool.fullName,arguments:args}},ctx:{authInfo:ctx.authInfo,signal:ctx.signal,_skipUI:true,surface:AGENT_SURFACE2,...this.isAgentPrivateScope(scope)&&{agentPrivateCall:true}}}).catch(error=>{throw errorBehindFlowControl(error)});return this.extractToolResult(result)}isAgentPrivateScope(scope){return scope===this.agentScope||scope===this.scope&&this.owner.kind==="agent"}createAgentInvoker(ctx){return async(agentId,input)=>{if(input!==void 0&&(typeof input!=="object"||input===null||Array.isArray(input))){throw new InvalidInputError(`invokeAgent("${agentId}"): the input must be an object of the agent's arguments`)}const args=input??{};const matches=agent=>agent.id===agentId||agent.name===agentId;const nested=this.agentScope?.agents.listAllInstances().find(matches);const nestedTool=nested?.getToolInstance();if(this.agentScope&&nestedTool){return this.callToolThrough(this.agentScope,nestedTool,args,ctx)}const visibleTool=this.getSwarmAgents().find(matches)?.getToolInstance();if(visibleTool){return this.callToolThrough(this.scope,visibleTool,args,ctx)}if(this.scope.agents?.listAllInstances().some(matches)){throw new AgentVisibilityError(this.id,agentId)}throw new AgentNotFoundError(agentId)}}async assertToolAuthorized(tool,authInfo,args){const authorities=tool.metadata["authorities"];if(!authorities)return;const entryName=tool.fullName||tool.name;const engine=this.scope.authoritiesEngine;const ctxBuilder=this.scope.authoritiesContextBuilder;if(!engine||!ctxBuilder){throw new AuthorityDeniedError8({entryType:"Tool",entryName,deniedBy:"authorities are not configured"})}const result=await engine.evaluate(authorities,ctxBuilder.build(authInfo??{},args));if(!result.granted){throw new AuthorityDeniedError8({entryType:"Tool",entryName,deniedBy:result.deniedBy??"policy denied",denial:result.denial})}}extractToolResult(mcpResult){if(!mcpResult)return void 0;if(mcpResult.isError){const errorContent=mcpResult.content?.[0];if(errorContent?.type==="text"){throw new AgentToolExecutionError(errorContent.text)}throw new AgentToolExecutionError("Tool execution failed")}if(mcpResult.structuredContent!==void 0){return mcpResult.structuredContent}const content=mcpResult.content;if(!content||content.length===0)return void 0;if(content.length===1&&content[0].type==="text"){const text=content[0].text;try{return JSON.parse(text)}catch{return text}}return content}parseInput(input){const inputSchema45=z89.object(this.inputSchema??{});return inputSchema45.parse(input.arguments)}parseOutput(raw){const descriptor=this.outputSchema;return buildParsedToolResult(descriptor,raw)}safeParseOutput(raw){try{return{success:true,data:this.parseOutput(raw)}}catch(error){return{success:false,error}}}getToolDefinition(){const metadata=this.record.metadata;let inputSchema45={type:"object",properties:{}};const toolInputSchema=this.agentToolInstance?.getInputJsonSchema();if(toolInputSchema){inputSchema45=toolInputSchema}else if(this.inputSchema&&Object.keys(this.inputSchema).length>0){try{inputSchema45=toJSONSchema5(z89.object(this.inputSchema),{io:"input",unrepresentable:"any"})}catch{this.scope.logger.warn(`Failed to convert input schema for agent ${this.name}`)}}return{name:agentToolName(this.id),description:this.buildToolDescription(metadata),inputSchema:inputSchema45}}buildToolDescription(metadata){if(metadata.description){return metadata.description}const baseDescription=`Invoke the ${metadata.name} agent.`;if(metadata.systemInstructions){return`${baseDescription} ${metadata.systemInstructions.slice(0,100)}...`}return baseDescription}isVisibleToSwarm(){return isAgentVisibleToSwarm(this.record.metadata)}canSeeSwarm(){return canAgentSeeSwarm(this.record.metadata)}getVisibleAgentIds(){return getVisibleAgentIds(this.record.metadata)??[]}};FunctionAgentContext=class extends AgentContext{constructor(record,args){super(args);this.record=record}record;async execute(input){const handler=this.record.provide();return await handler(input,this)}}}});import{tokenName as tokenName18}from"@frontmcp/di";import{getRuntimeContext as getRuntimeContext17,isEntryAvailable as isEntryAvailable6}from"@frontmcp/utils";function ownerKeyOf2(lineage){return lineage.map(o=>`${o.kind}:${o.id}`).join("/")}function qualifiedNameOf2(lineage,baseName){const prefix=lineage.map(o=>o.id).join(".");return prefix?`${prefix}.${baseName}`:baseName}function dedupLineage4(l){const out=[];for(const o of l){const last=out[out.length-1];if(!last||last.kind!==o.kind||last.id!==o.id)out.push(o)}return out}var AgentRegistry;var init_agent_registry=__esm({"libs/sdk/src/agent/agent.registry.ts"(){"use strict";init_availability();init_mcp_error();init_regsitry();init_agent_events();init_agent_utils();AgentRegistry=class extends RegistryAbstract{owner;localRows=[];adopted=new Map;children=new Set;childSubscriptions=new Map;byQualifiedId=new Map;byName=new Map;byOwnerAndName=new Map;byOwner=new Map;byId=new Map;version=0;emitter=new AgentEmitter;constructor(providers,list,owner){super("AgentRegistry",providers,list,false);this.owner=owner;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=normalizeAgent(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);if(!rec){throw new DependencyNotFoundError("AgentRegistry",tokenName18(token))}const deps=agentDiscoveryDeps(rec);for(const d of deps){this.providers.get(d);const graphEntry=this.graph.get(token);if(!graphEntry){throw new DependencyNotFoundError("AgentRegistry.graph",tokenName18(token))}graphEntry.add(d)}}}async initialize(){if(this.tokens.size>0)await this.instantiateLocalAgents();const childAppRegistries=this.providers.getRegistries("AppRegistry");childAppRegistries.forEach(appRegistry=>{const apps=appRegistry.getApps();for(const app of apps){const appAgentRegistries=app.providers.getRegistries("AgentRegistry");appAgentRegistries.filter(r=>r.owner.kind==="app").forEach(appAgentRegistry=>{this.adoptFromChild(appAgentRegistry,appAgentRegistry.owner)})}});const childAgentRegistries=this.providers.getRegistries("AgentRegistry");childAgentRegistries.filter(r=>r!==this).forEach(agentRegistry=>{this.adoptFromChild(agentRegistry,agentRegistry.owner)});this.reindex();const scope=this.providers.getActiveScope();logAvailabilityFiltering("AgentRegistry",this.listAllInstances(),scope.logger);this.bump("reset");await Promise.all([...this.instances.values()].map(ai=>ai.ready));if(this.owner.kind==="scope"||this.owner.kind==="agent"){await this.registerAgentToolsInParentScope()}}async instantiateLocalAgents(){const agentModule=await Promise.resolve().then(()=>(init_agent_instance(),agent_instance_exports));for(const token of this.tokens){const rec=this.defs.get(token);if(!rec){throw new DependencyNotFoundError("AgentRegistry",tokenName18(token))}const ai=new agentModule.AgentInstance(rec,this.providers,this.owner);this.instances.set(token,ai);const lineage=this.owner?[this.owner]:[];const row=this.makeRow(token,ai,lineage,this);this.localRows.push(row)}}async registerAgentToolsInParentScope(){const scope=this.providers.getActiveScope();const toolRegistry=scope.tools;if(!toolRegistry){return}for(const agentInstance of this.listAllInstances()){const toolInstance=agentInstance.getToolInstance();if(toolInstance){try{toolRegistry.registerToolInstance(toolInstance);scope.logger.debug(`Registered agent tool ${toolInstance.name} in parent ToolRegistry`)}catch(error){scope.logger.warn(`Failed to register agent tool for ${agentInstance.name}: ${error instanceof Error?error.message:"Unknown error"}`)}}for(const resource of agentInstance.getExportedResources()){scope.resources?.registerResourceInstance(resource)}for(const prompt of agentInstance.getExportedPrompts()){scope.prompts?.registerPromptInstance(prompt)}}}adoptFromChild(child,_childOwner){if(this.children.has(child))return;const childRows=child.listAllIndexed();const prepend=this.owner?[this.owner]:[];const adoptedRows=childRows.map(r=>this.relineage(r,prepend));this.adopted.set(child,adoptedRows);this.children.add(child);const unsubscribe=child.subscribe({immediate:false},()=>{const latest=child.listAllIndexed().map(r=>this.relineage(r,prepend));this.adopted.set(child,latest);this.reindex();this.bump("reset")});this.childSubscriptions.set(child,unsubscribe);this.reindex();this.bump("reset")}removeChild(child){if(!this.children.has(child))return;const unsubscribe=this.childSubscriptions.get(child);if(unsubscribe){unsubscribe();this.childSubscriptions.delete(child)}this.adopted.delete(child);this.children.delete(child);this.reindex();this.bump("reset")}dispose(){for(const[child,unsubscribe]of this.childSubscriptions){unsubscribe();this.children.delete(child);this.adopted.delete(child)}this.childSubscriptions.clear();this.reindex()}getAgents(includeHidden=false){const ctx=getRuntimeContext17();const local=[...this.localRows].map(a=>a.instance);const adopted=[...this.adopted.values()].flat().map(a=>a.instance);return[...local,...adopted].filter(a=>{if(!isEntryAvailable6(a.metadata.availableWhen,ctx))return false;if(!includeHidden&&a.metadata.hideFromDiscovery===true)return false;return true})}getInlineAgents(){return[...this.instances.values()]}listAllIndexed(){return[...this.localRows,...[...this.adopted.values()].flat()]}listAllInstances(){return this.listAllIndexed().map(r=>r.instance)}getAvailableInstances(){const ctx=getRuntimeContext17();return[...this.listAllInstances()].filter(a=>isEntryAvailable6(a.metadata.availableWhen,ctx))}findById(id){return this.byId.get(id)?.instance}findByName(name51){const rows=this.byName.get(name51);return rows?.[0]?.instance}getVisibleAgentsFor(agentId){const agent=this.findById(agentId);if(!agent)return[];const canSeeSwarm=agent.canSeeSwarm();if(!canSeeSwarm)return[];const visibleIds=agent.getVisibleAgentIds();const allAgents=this.getAvailableInstances();return allAgents.filter(a=>{if(a.id===agentId)return false;if(!a.isVisibleToSwarm())return false;if(visibleIds&&visibleIds.length>0){return visibleIds.includes(a.id)}return true})}getAgentsAsTools(){return this.getAvailableInstances().filter(a=>a.isVisibleToSwarm()).map(a=>a.getToolDefinition())}getAgentToolsFor(agentId){return this.getVisibleAgentsFor(agentId).map(a=>a.getToolDefinition())}reindex(){const effective=this.listAllIndexed();this.byQualifiedId.clear();this.byName.clear();this.byOwnerAndName.clear();this.byOwner.clear();this.byId.clear();for(const r of effective){this.byQualifiedId.set(r.qualifiedId,r);this.byId.set(r.instance.id,r);const listByName=this.byName.get(r.baseName)??[];listByName.push(r);this.byName.set(r.baseName,listByName);const byOwnerKey=this.byOwner.get(r.ownerKey)??[];byOwnerKey.push(r);this.byOwner.set(r.ownerKey,byOwnerKey);const on=`${r.ownerKey}:${r.baseName}`;if(!this.byOwnerAndName.has(on))this.byOwnerAndName.set(on,r)}}subscribe(opts,cb){const filter=opts.filter??(()=>true);if(opts.immediate){cb({kind:"reset",changeScope:"global",version:this.version,snapshot:this.listAllInstances().filter(filter)})}return this.emitter.on(e=>cb({...e,snapshot:this.listAllInstances().filter(filter)}))}bump(kind){const version=++this.version;this.emitter.emit({kind,changeScope:"global",version,snapshot:this.listAllInstances()})}makeRow(token,instance,lineage,source){const ownerKey=ownerKeyOf2(lineage);const baseName=instance.name;const qualifiedName=qualifiedNameOf2(lineage,baseName);const qualifiedId=`${ownerKey}:${tokenName18(token)}`;return{token,instance,baseName,lineage,ownerKey,qualifiedName,qualifiedId,source}}relineage(row,prepend){const merged=[...prepend,...row.lineage];const lineage=dedupLineage4(merged);const ownerKey=ownerKeyOf2(lineage);const qualifiedName=qualifiedNameOf2(lineage,row.baseName);const qualifiedId=`${ownerKey}:${tokenName18(row.token)}`;return{token:row.token,instance:row.instance,baseName:row.baseName,lineage,ownerKey,qualifiedName,qualifiedId,source:row.source}}hasAny(){return this.listAllIndexed().length>0||this.tokens.size>0}getCapabilities(){return this.hasAny()?{tools:{listChanged:true}}:{}}}}});import{depsOfClass as depsOfClass10,getMetadata as getMetadata19,isClass as isClass17}from"@frontmcp/di";import{idFromString,isValidMcpUri as isValidMcpUri7}from"@frontmcp/utils";function collectAppMetadata(cls){return Object.entries(FrontMcpLocalAppTokens).reduce((metadata,[key,token])=>{return Object.assign(metadata,{[key]:getMetadata19(token,cls)})},{})}function appIdOf(metadata){return metadata.id??idFromString(metadata.name)}function isRemoteAppConfig(item){if(!item||typeof item!=="object"){return false}const obj=item;if(typeof obj["urlType"]!=="string"||typeof obj["url"]!=="string"||typeof obj["name"]!=="string"){return false}if(obj["urlType"]==="npm"||obj["urlType"]==="esm"){return true}if(obj["urlType"]==="url"||obj["urlType"]==="worker"){return isValidMcpUri7(obj["url"])}return false}function normalizeApp(item){if(isClass17(item)){const metadata=collectAppMetadata(item);return{kind:"LOCAL_CLASS",provide:item,metadata}}if(item&&typeof item==="object"&&"lazy"in item){return normalizeLazyApp(item)}if(isRemoteAppConfig(item)){const metadata=item;const appId=metadata.id??metadata.name;const provide=Symbol(`remote:${appId}`);return{kind:"REMOTE_VALUE",provide,useValue:null,metadata}}if(item&&typeof item==="object"){const{provide,useValue,...metadata}=item;if(!provide){const name52=item?.name??JSON.stringify(item)??"[object]";throw new MissingProvideError("App",name52)}if(useValue){return{kind:"REMOTE_VALUE",provide,useValue,metadata}}}const name51=item?.name??String(item);throw new InvalidEntityError("app",name51,"a class or remote app config object")}function normalizeLazyApp(item){const parsed=lazyAppMetadataSchema.safeParse(item);if(!parsed.success){const name51=item.name;const label=typeof name51==="string"?`Lazy app "${name51}"`:"A lazy app";const issues=parsed.error.issues.map(issue=>{const field=issue.path.join(".")||(issue.code==="unrecognized_keys"?issue.keys.join(", "):"");return field?`${field}: ${issue.message}`:issue.message});throw new LazyAppConfigurationError(`${label} is invalid (${issues.join("; ")}). A lazy app takes id, name, description, enabled and lazy; declare everything else on the @App class it imports.`)}const metadata={...parsed.data,standalone:false};return{kind:"LAZY_IMPORT",provide:Symbol(`lazy:${appIdOf(metadata)}`),metadata}}function appDiscoveryDeps(rec){switch(rec.kind){case"REMOTE_VALUE":case"LAZY_IMPORT":return[];case"LOCAL_CLASS":return depsOfClass10(rec.provide,"discovery")}}var init_app_utils=__esm({"libs/sdk/src/app/app.utils.ts"(){"use strict";init_common();init_errors()}});import{idFromString as idFromString2}from"@frontmcp/utils";var AppLocalInstance;var init_app_local_instance=__esm({"libs/sdk/src/app/instances/app.local.instance.ts"(){"use strict";init_adapter_registry();init_agent_registry();init_common();init_hooks_utils();init_plugin_registry();init_prompt_registry();init_provider_registry();init_resource_registry();init_skill_registry();init_tool_registry();AppLocalInstance=class extends AppEntry{id;scopeProviders;appProviders;appPlugins;appAdapters;appTools;appResources;appPrompts;appAgents;appSkills;logger;constructor(record,scopeProviders){super(record);this.scopeProviders=scopeProviders;this.id=this.metadata.id??idFromString2(this.metadata.name);try{this.logger=scopeProviders.get(FrontMcpLogger)?.child("AppLocalInstance")}catch{}this.ready=this.initialize()}async initialize(){this.logger?.verbose(`Initializing app: ${this.metadata.name} (id: ${this.id})`);this.appProviders=new ProviderRegistry(this.metadata.providers??[],this.scopeProviders);await this.appProviders.ready;const appOwner={kind:"app",id:this.id,ref:this.token};const isStandalone=this.metadata.standalone!==false;const scopeInfo={ownScope:this.appProviders.getActiveScope(),parentScope:!isStandalone?this.scopeProviders.getActiveScope():void 0,isStandaloneApp:isStandalone};const providerHooks=normalizeHooksFromProviders(this.appProviders).map(hook=>({...hook,metadata:{...hook.metadata,owner:appOwner}}));if(providerHooks.length>0){await scopeInfo.ownScope.hooks.registerHooks(false,...providerHooks)}this.appPlugins=new PluginRegistry(this.appProviders,this.metadata.plugins??[],appOwner,scopeInfo);await this.appPlugins.ready;this.logger?.verbose(`App ${this.metadata.name}: ${this.appPlugins.getPlugins().length} plugin(s) registered`);const appAdapters=new AdapterRegistry(this.appProviders,this.metadata.adapters??[]);this.appAdapters=appAdapters;await appAdapters.ready;if(appAdapters.getAdapters().length>0)scopeInfo.ownScope.onDispose(()=>appAdapters.dispose());this.logger?.verbose(`App ${this.metadata.name}: ${this.appAdapters.getAdapters().length} adapter(s) found`);this.appTools=new ToolRegistry(this.appProviders,this.metadata.tools??[],appOwner);await this.appTools.ready;const toolNames=this.appTools.getTools(true).map(t=>t.metadata.name);this.logger?.verbose(`App ${this.metadata.name}: ${toolNames.length} tool(s) registered: [${toolNames.join(", ")}]`);this.appResources=new ResourceRegistry(this.appProviders,this.metadata.resources??[],appOwner);this.appPrompts=new PromptRegistry(this.appProviders,this.metadata.prompts??[],appOwner);this.appAgents=new AgentRegistry(this.appProviders,this.metadata.agents??[],appOwner);this.appSkills=new SkillRegistry(this.appProviders,this.metadata.skills??[],appOwner);await Promise.all([this.appResources.ready,this.appPrompts.ready,this.appAgents.ready,this.appSkills.ready]);this.logger?.verbose(`App ${this.metadata.name}: ${this.appResources.getResources().length} resource(s) registered`);this.logger?.verbose(`App ${this.metadata.name}: ${this.appPrompts.getPrompts().length} prompt(s) registered`);const parts=[];const toolCount=this.appTools.getTools(true).length;const resourceCount=this.appResources.getResources().length;const promptCount=this.appPrompts.getPrompts().length;const adapterCount=this.appAdapters.getAdapters().length;const pluginCount=this.appPlugins.getPlugins().length;if(toolCount>0)parts.push(`${toolCount} tool${toolCount!==1?"s":""}`);if(resourceCount>0)parts.push(`${resourceCount} resource${resourceCount!==1?"s":""}`);if(promptCount>0)parts.push(`${promptCount} prompt${promptCount!==1?"s":""}`);if(adapterCount>0)parts.push(`${adapterCount} adapter${adapterCount!==1?"s":""}`);if(pluginCount>0)parts.push(`${pluginCount} plugin${pluginCount!==1?"s":""}`);this.logger?.info(`${this.metadata.name}: ${parts.length>0?parts.join(", "):"no entries"}`)}get providers(){return this.appProviders}get adapters(){return this.appAdapters}get plugins(){return this.appPlugins}get tools(){return this.appTools}get resources(){return this.appResources}get prompts(){return this.appPrompts}get agents(){return this.appAgents}get skills(){return this.appSkills}}}});var DEFAULT_INTERVAL_MS,VersionPoller;var init_version_poller=__esm({"libs/sdk/src/esm-loader/version-poller.ts"(){"use strict";init_version_resolver();init_semver_utils();DEFAULT_INTERVAL_MS=5*60*1e3;VersionPoller=class{intervalMs;logger;onNewVersion;versionResolver;packages=new Map;intervalId;running=false;polling=false;constructor(options){this.intervalMs=options.intervalMs??DEFAULT_INTERVAL_MS;this.logger=options.logger;this.onNewVersion=options.onNewVersion;this.versionResolver=new VersionResolver({registryAuth:options.registryAuth})}addPackage(specifier,currentVersion){this.packages.set(specifier.fullName,{specifier,currentVersion});this.logger?.debug(`Version poller: tracking ${specifier.fullName}@${specifier.range} (current: ${currentVersion})`)}removePackage(packageName){this.packages.delete(packageName);this.logger?.debug(`Version poller: stopped tracking ${packageName}`)}updateCurrentVersion(packageName,newVersion){const entry=this.packages.get(packageName);if(entry){entry.currentVersion=newVersion;return true}return false}start(){if(this.running)return;if(this.packages.size===0)return;this.running=true;this.intervalId=setInterval(()=>{void this.poll()},this.intervalMs);this.logger?.info(`Version poller started (interval: ${this.intervalMs}ms, packages: ${this.packages.size})`)}stop(){if(!this.running)return;this.running=false;if(this.intervalId){clearInterval(this.intervalId);this.intervalId=void 0}this.logger?.info("Version poller stopped")}async checkNow(){const results=[];for(const[,entry]of this.packages){try{const result=await this.checkPackage(entry);results.push(result)}catch(error){this.logger?.warn(`Version check failed for ${entry.specifier.fullName}: ${error.message}`)}}return results}isRunning(){return this.running}get trackedCount(){return this.packages.size}async poll(){if(this.polling)return;this.polling=true;try{for(const[,entry]of this.packages){try{const result=await this.checkPackage(entry);if(result.hasUpdate){this.logger?.info(`New version available for ${entry.specifier.fullName}: ${entry.currentVersion} \u2192 ${result.latestVersion}`);await this.onNewVersion(entry.specifier.fullName,entry.currentVersion,result.latestVersion);entry.currentVersion=result.latestVersion}}catch(error){this.logger?.warn(`Version poll failed for ${entry.specifier.fullName}: ${error.message}`)}}}finally{this.polling=false}}async checkPackage(entry){const resolution=await this.versionResolver.resolve(entry.specifier);const hasUpdate=resolution.resolvedVersion!==entry.currentVersion&&isNewerVersion(resolution.resolvedVersion,entry.currentVersion);const rangeMatch=satisfiesRange(resolution.resolvedVersion,entry.specifier.range);return{packageName:entry.specifier.fullName,currentVersion:entry.currentVersion,latestVersion:resolution.resolvedVersion,hasUpdate:hasUpdate&&rangeMatch,satisfiesRange:rangeMatch}}}}});var app_esm_instance_exports={};__export(app_esm_instance_exports,{AppEsmInstance:()=>AppEsmInstance});var UNLOADED_MANIFEST_KINDS,EmptyPluginRegistry,EmptyAdapterRegistry,EmptySkillRegistry,AppEsmInstance;var init_app_esm_instance=__esm({"libs/sdk/src/app/instances/app.esm.instance.ts"(){"use strict";init_common();init_primitive_filter();init_errors();init_esm_entries();init_package_specifier();init_version_poller();init_prompt_instance();init_prompt_registry();init_resource_instance();init_resource_registry();init_tool_instance();init_tool_registry();init_app_utils();UNLOADED_MANIFEST_KINDS=["skills","agents","jobs","workflows","providers"];EmptyPluginRegistry=class{getPlugins(){return[]}getPluginNames(){return[]}};EmptyAdapterRegistry=class{getAdapters(){return[]}};EmptySkillRegistry=class _EmptySkillRegistry{owner={kind:"app",id:"_esm",ref:_EmptySkillRegistry};getSkills(){return[]}getExecutableSkills(){return[]}getKnowledgeOnlySkills(){return[]}findByName(){return void 0}findByQualifiedName(){return void 0}async search(){return[]}async loadSkill(){return void 0}async listSkills(){return{skills:[],total:0,hasMore:false}}hasAny(){return false}async count(){return 0}subscribe(){return()=>{}}getCapabilities(){return{}}async validateAllTools(){return{results:[],isValid:true,totalSkills:0,failedCount:0,warningCount:0}}async syncToExternal(){return null}setExternalProvider(){return void 0}getExternalProvider(){return void 0}hasExternalProvider(){return false}async registerSkillContent(){throw new InternalMcpError("registerSkillContent is not supported on ESM apps","UNSUPPORTED_OPERATION")}async unregisterSkill(){return false}};AppEsmInstance=class extends AppEntry{id;get isRemote(){return true}scopeProviders;appOwner;loader;specifier;poller;loadResult;updateInProgress=false;_tools;_resources;_prompts;_plugins;_adapters;_skills;constructor(record,scopeProviders){super(record);this.id=appIdOf(this.metadata);this.scopeProviders=scopeProviders;this.appOwner={kind:"app",id:this.id,ref:this.token};this.specifier=parsePackageSpecifier(this.metadata.url);const scope=scopeProviders.getActiveScope();const appConfig=this.metadata.packageConfig;this.loader=createPackageModuleLoader({loader:appConfig?.loader??scope.metadata.loader,cacheTTL:appConfig?.cacheTTL,importMap:appConfig?.importMap,logger:scope.logger});this._tools=new ToolRegistry(this.scopeProviders,[],this.appOwner);this._resources=new ResourceRegistry(this.scopeProviders,[],this.appOwner);this._prompts=new PromptRegistry(this.scopeProviders,[],this.appOwner);this._plugins=new EmptyPluginRegistry;this._adapters=new EmptyAdapterRegistry;this._skills=new EmptySkillRegistry;this.ready=this.initialize()}async initialize(){const logger=this.scopeProviders.getActiveScope().logger;logger.info(`Initializing ESM app: ${this.id} (${this.specifier.fullName}@${this.specifier.range})`);try{await Promise.all([this._tools.ready,this._resources.ready,this._prompts.ready]);this.loadResult=await this.loader.load(this.specifier);logger.info(`Loaded ESM package ${this.specifier.fullName}@${this.loadResult.resolvedVersion} (source: ${this.loadResult.source})`);await this.registerFromManifest(this.loadResult.manifest);const autoUpdate=this.metadata.packageConfig?.autoUpdate;if(autoUpdate?.enabled){const scopeMeta=this.scopeProviders.getActiveScope().metadata;const pollerLoader=this.metadata.packageConfig?.loader??scopeMeta.loader;this.poller=new VersionPoller({intervalMs:autoUpdate.intervalMs,registryAuth:registryAuthOf(pollerLoader),logger,onNewVersion:(pkg,oldVer,newVer)=>this.handleVersionUpdate(pkg,oldVer,newVer)});this.poller.addPackage(this.specifier,this.loadResult.resolvedVersion);this.poller.start()}}catch(error){logger.error(`Failed to initialize ESM app ${this.id}: ${error.message}`);throw error}}get providers(){return this.scopeProviders}get adapters(){return this._adapters}get plugins(){return this._plugins}get tools(){return this._tools}get resources(){return this._resources}get prompts(){return this._prompts}get skills(){return this._skills}getLoadedVersion(){return this.loadResult?.resolvedVersion}getSpecifier(){return this.specifier}async reload(){const logger=this.scopeProviders.getActiveScope().logger;logger.info(`Reloading ESM app ${this.id}`);this.loadResult=await this.loader.load(this.specifier);await this.registerFromManifest(this.loadResult.manifest);if(this.poller){this.poller.updateCurrentVersion(this.specifier.fullName,this.loadResult.resolvedVersion)}}async dispose(){this.poller?.stop()}async registerFromManifest(manifest){const logger=this.scopeProviders.getActiveScope().logger;const namespace=this.metadata.namespace??this.metadata.name;const notLoaded=UNLOADED_MANIFEST_KINDS.filter(kind=>(manifest[kind]?.length??0)>0);if(notLoaded.length>0){logger.warn(`ESM app ${this.id}: App.esm() loads only tools, resources and prompts; the package's ${notLoaded.join(", ")} are not loaded`)}const filter=this.metadata.filter;const prefixLength=namespace?namespace.length+1:0;const included=kind=>record=>isPrimitiveIncluded(record.metadata.name.slice(prefixLength),kind,filter);const tools=esmManifestRecords(manifest.tools,raw=>esmToolRecord(raw,namespace)).filter(included("tools"));const resources=esmManifestRecords(manifest.resources,raw=>esmResourceRecord(raw,namespace)).filter(included("resources"));const prompts=esmManifestRecords(manifest.prompts,raw=>esmPromptRecord(raw,namespace)).filter(included("prompts"));for(const record of tools){const instance=new ToolInstance(record,this.scopeProviders,this.appOwner);await instance.ready;this._tools.registerToolInstance(instance)}for(const record of resources){const instance=new ResourceInstance(record,this.scopeProviders,this.appOwner);await instance.ready;this._resources.registerResourceInstance(instance)}for(const record of prompts){const instance=new PromptInstance(record,this.scopeProviders,this.appOwner);await instance.ready;this._prompts.registerPromptInstance(instance)}logger.info(`ESM app ${this.id} registered: ${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts`)}async handleVersionUpdate(_packageName,oldVersion,newVersion){const logger=this.scopeProviders.getActiveScope().logger;if(this.updateInProgress){logger.warn(`Update already in progress for ${this.id}, skipping ${newVersion}`);return}this.updateInProgress=true;logger.info(`Updating ESM app ${this.id}: ${oldVersion} \u2192 ${newVersion}`);try{this.loadResult=await this.loader.load(this.specifier);this._tools.replaceAll([],this.appOwner);this._resources.replaceAll([],this.appOwner);this._prompts.replaceAll([],this.appOwner);await this.registerFromManifest(this.loadResult.manifest);logger.info(`ESM app ${this.id} updated to ${newVersion}`)}catch(error){logger.error(`Failed to update ESM app ${this.id} to ${newVersion}: ${error.message}`)}finally{this.updateInProgress=false}}}}});var CapabilityCache;var init_capability_cache=__esm({"libs/sdk/src/remote-mcp/cache/capability-cache.ts"(){"use strict";CapabilityCache=class{cache=new Map;defaultTTL;constructor(config={}){this.defaultTTL=config.defaultTTL??6e4}get(appId){const cached=this.cache.get(appId);if(!cached){return null}if(Date.now()>cached.expiresAt){this.cache.delete(appId);return null}return cached.capabilities}set(appId,capabilities,ttl){const effectiveTTL=ttl??this.defaultTTL;this.cache.set(appId,{capabilities,expiresAt:Date.now()+effectiveTTL,fetchedAt:capabilities.fetchedAt})}invalidate(appId){this.cache.delete(appId)}clear(){this.cache.clear()}isExpired(appId){const cached=this.cache.get(appId);if(!cached){return true}return Date.now()>cached.expiresAt}getTimeToExpiry(appId){const cached=this.cache.get(appId);if(!cached){return 0}const remaining=cached.expiresAt-Date.now();return Math.max(0,remaining)}getFetchedAt(appId){const cached=this.cache.get(appId);return cached?.fetchedAt??null}getCachedAppIds(){const now=Date.now();const activeIds=[];for(const[appId,cached]of this.cache.entries()){if(cached.expiresAt>now){activeIds.push(appId)}}return activeIds}getStats(){const now=Date.now();let activeEntries=0;let expiredEntries=0;for(const cached of this.cache.values()){if(cached.expiresAt>now){activeEntries++}else{expiredEntries++}}return{totalEntries:this.cache.size,activeEntries,expiredEntries}}}}});var init_cache=__esm({"libs/sdk/src/remote-mcp/cache/index.ts"(){"use strict";init_capability_cache()}});function createRemoteToolInstance(remoteTool,mcpClient,remoteAppId,providers,owner,namespace){const record=buildRemoteToolRecord(remoteTool,mcpClient,remoteAppId,namespace);return new ToolInstance(record,providers,owner)}function createRemoteResourceInstance(remoteResource,mcpClient,remoteAppId,providers,owner,namespace){const record=buildRemoteResourceRecord(remoteResource,mcpClient,remoteAppId,namespace);return new ResourceInstance(record,providers,owner)}function createRemoteResourceTemplateInstance(remoteTemplate,mcpClient,remoteAppId,providers,owner,namespace){const record=buildRemoteResourceTemplateRecord(remoteTemplate,mcpClient,remoteAppId,namespace);return new ResourceInstance(record,providers,owner)}function createRemotePromptInstance(remotePrompt,mcpClient,remoteAppId,providers,owner,namespace){const record=buildRemotePromptRecord(remotePrompt,mcpClient,remoteAppId,namespace);return new PromptInstance(record,providers,owner)}var init_instance_factories=__esm({"libs/sdk/src/remote-mcp/factories/instance-factories.ts"(){"use strict";init_tool_instance();init_resource_instance();init_prompt_instance();init_record_builders()}});var init_factories=__esm({"libs/sdk/src/remote-mcp/factories/index.ts"(){"use strict";init_context_factories();init_record_builders();init_instance_factories()}});var EmptyPluginRegistry2,EmptyAdapterRegistry2,EmptySkillRegistry2;var init_empty_app_registries=__esm({"libs/sdk/src/app/instances/empty-app-registries.ts"(){"use strict";init_errors();EmptyPluginRegistry2=class{getPlugins(){return[]}getPluginNames(){return[]}};EmptyAdapterRegistry2=class{getAdapters(){return[]}};EmptySkillRegistry2=class _EmptySkillRegistry{owner={kind:"app",id:"_remote",ref:_EmptySkillRegistry};getSkills(){return[]}getExecutableSkills(){return[]}getKnowledgeOnlySkills(){return[]}findByName(){return void 0}findByQualifiedName(){return void 0}async search(){return[]}async loadSkill(){return void 0}async listSkills(){return{skills:[],total:0,hasMore:false}}hasAny(){return false}async count(){return 0}subscribe(){return()=>{}}getCapabilities(){return{}}async validateAllTools(){return{results:[],isValid:true,totalSkills:0,failedCount:0,warningCount:0}}async syncToExternal(){return null}setExternalProvider(){return void 0}getExternalProvider(){return void 0}hasExternalProvider(){return false}async registerSkillContent(){throw new InternalMcpError("registerSkillContent is not supported on remote apps","UNSUPPORTED_OPERATION")}async unregisterSkill(){return false}}}});var app_remote_instance_exports={};__export(app_remote_instance_exports,{AppRemoteInstance:()=>AppRemoteInstance});var AppRemoteInstance;var init_app_remote_instance=__esm({"libs/sdk/src/app/instances/app.remote.instance.ts"(){"use strict";init_common();init_primitive_filter();init_errors();init_prompt_registry();init_cache();init_factories();init_remote_entries();init_resource_registry();init_tool_registry();init_app_utils();init_empty_app_registries();AppRemoteInstance=class extends AppEntry{id;get isRemote(){return true}scopeProviders;mcpClient;appOwner;capabilityCache;_tools;_resources;_prompts;_plugins;_adapters;_skills;isConnected=false;capabilitiesLoaded=false;loadingPromise=null;_unsubscribeCapability;registeredProxies={tools:[],resources:[],prompts:[]};constructor(record,scopeProviders){super(record);this.id=appIdOf(this.metadata);this.scopeProviders=scopeProviders;this.appOwner={kind:"app",id:this.id,ref:this.token};const cacheTTL=this.metadata.cacheTTL??6e4;this.capabilityCache=new CapabilityCache({defaultTTL:cacheTTL});this._tools=new ToolRegistry(this.scopeProviders,[],this.appOwner,{adopt:false});this._resources=new ResourceRegistry(this.scopeProviders,[],this.appOwner,{adopt:false});this._prompts=new PromptRegistry(this.scopeProviders,[],this.appOwner,{adopt:false});this._plugins=new EmptyPluginRegistry2;this._adapters=new EmptyAdapterRegistry2;this._skills=new EmptySkillRegistry2;this.mcpClient=mcpClientServiceOf(this.scopeProviders.getActiveScope(),{capabilityRefreshInterval:this.metadata.refreshInterval??0});this.ready=this.initialize()}async initialize(){const logger=this.scopeProviders.getActiveScope().logger;logger.info(`Initializing remote app: ${this.id} (${this.metadata.url})`);try{await Promise.all([this._tools.ready,this._resources.ready,this._prompts.ready]);await this.mcpClient.connect(buildRemoteConnectRequest({appId:this.id,name:this.metadata.name,url:this.metadata.url,transportType:this.mapUrlTypeToTransportType(this.metadata.urlType),transportOptions:this.metadata.transportOptions,remoteAuth:this.metadata.remoteAuth,namespace:this.metadata.namespace}));this.isConnected=true;this._unsubscribeCapability=this.mcpClient.onCapabilityChange(event=>{if(event.appId===this.id){logger.info(`Remote capabilities changed for ${this.id}: ${event.kind}`);this.capabilityCache.invalidate(this.id);this.capabilitiesLoaded=false}});logger.info(`Remote app ${this.id} connected. Capabilities will be loaded lazily.`)}catch(error){logger.error(`Failed to initialize remote app ${this.id}: ${error.message}`);throw error}}async ensureCapabilitiesLoaded(){if(this.capabilitiesLoaded&&!this.capabilityCache.isExpired(this.id)){return}if(this.loadingPromise){return this.loadingPromise}this.loadingPromise=this.discoverAndRegisterCapabilities();try{await this.loadingPromise;this.capabilitiesLoaded=true}finally{this.loadingPromise=null}}async refreshCapabilities(){this.capabilityCache.invalidate(this.id);this.capabilitiesLoaded=false;await this.ensureCapabilitiesLoaded()}get providers(){return this.scopeProviders}get adapters(){return this._adapters}get plugins(){return this._plugins}get tools(){return this._tools}get resources(){return this._resources}get prompts(){return this._prompts}get skills(){return this._skills}getMcpClient(){return this.mcpClient}getIsConnected(){return this.isConnected}getCapabilitiesLoaded(){return this.capabilitiesLoaded}getCacheStats(){return this.capabilityCache.getStats()}async disconnect(){if(this._unsubscribeCapability){this._unsubscribeCapability();this._unsubscribeCapability=void 0}if(this.isConnected){await this.mcpClient.disconnect(this.id);this.isConnected=false;this.capabilitiesLoaded=false;this.capabilityCache.invalidate(this.id)}}async reconnect(){await this.mcpClient.reconnect(this.id);this.isConnected=true;this.capabilitiesLoaded=false;this.capabilityCache.invalidate(this.id)}mapUrlTypeToTransportType(urlType){switch(urlType){case"url":return"http";case"worker":return"worker";case"npm":return"npm";case"esm":return"esm";default:return"http"}}registerRemoteTool(instance,logger){try{this._tools.registerToolInstance(instance)}catch(error){if(!(error instanceof ToolAliasConflictError))throw error;logger.warn(`Remote app ${this.id}: tool "${instance.name}" is not loaded. ${error.message}`)}}async discoverAndRegisterCapabilities(){const logger=this.scopeProviders.getActiveScope().logger;const namespace=this.metadata.namespace||this.metadata.name;let capabilities=this.capabilityCache.get(this.id);if(!capabilities){logger.debug(`Fetching capabilities for remote app ${this.id}`);capabilities=await this.mcpClient.discoverCapabilities(this.id);const cacheTTL=this.metadata.cacheTTL??6e4;this.capabilityCache.set(this.id,capabilities,cacheTTL)}else{logger.debug(`Using cached capabilities for remote app ${this.id}`)}const filter=this.metadata.filter;const included=kind=>entry=>isPrimitiveIncluded(entry.name,kind,filter);const tools=await Promise.all(capabilities.tools.filter(included("tools")).map(async remoteTool=>{const instance=createRemoteToolInstance(remoteTool,this.mcpClient,this.id,this.scopeProviders,this.appOwner,namespace);await instance.ready;return instance}));const resources=await Promise.all([...capabilities.resources.filter(included("resources")).map(remoteResource=>createRemoteResourceInstance(remoteResource,this.mcpClient,this.id,this.scopeProviders,this.appOwner,namespace)),...capabilities.resourceTemplates.filter(included("resources")).map(remoteTemplate=>createRemoteResourceTemplateInstance(remoteTemplate,this.mcpClient,this.id,this.scopeProviders,this.appOwner,namespace))].map(async instance=>{await instance.ready;return instance}));const prompts=await Promise.all(capabilities.prompts.filter(included("prompts")).map(async remotePrompt=>{const instance=createRemotePromptInstance(remotePrompt,this.mcpClient,this.id,this.scopeProviders,this.appOwner,namespace);await instance.ready;return instance}));const previous=this.registeredProxies;for(const token of previous.tools)this._tools.unregisterToolInstance(token);for(const token of previous.resources)this._resources.unregisterResourceInstance(token);for(const token of previous.prompts)this._prompts.unregisterPromptInstance(token);for(const instance of tools)this.registerRemoteTool(instance,logger);for(const instance of resources)this._resources.registerResourceInstance(instance);for(const instance of prompts)this._prompts.registerPromptInstance(instance);this.registeredProxies={tools:tools.map(instance=>instance.record.provide),resources:resources.map(instance=>instance.record.provide),prompts:prompts.map(instance=>instance.record.provide)};logger.info(`Remote app ${this.id} capabilities loaded: ${tools.length} tools, ${resources.length} resources, ${prompts.length} prompts`)}}}});import{sha256Hex as sha256Hex13}from"@frontmcp/utils";function serializeForHash(skill){const sortedTools=[...skill.tools].sort((a,b)=>byText(a.name,b.name));const sortedParameters=skill.parameters?[...skill.parameters].sort((a,b)=>byText(a.name,b.name)):void 0;const sortedExamples=skill.examples?[...skill.examples].sort((a,b)=>byText(a.scenario,b.scenario)):void 0;const content={id:skill.id,name:skill.name,description:skill.description,instructions:skill.instructions,tools:sortedTools,parameters:sortedParameters,examples:sortedExamples};return JSON.stringify(content)}function computeSkillHash(skill){const serialized=serializeForHash(skill);return sha256Hex13(serialized)}var byText;var init_skill_hash=__esm({"libs/sdk/src/skill/sync/skill-hash.ts"(){"use strict";byText=(a,b)=>a.localeCompare(b,"en")}});import{z as z90}from"@frontmcp/lazy-zod";var SERVER_MANIFEST_VERSION,SERVER_MANIFEST_FILE,jsonObjectSchema,ownedEntryShape,manifestToolSchema,resourceShape,manifestResourceSchema,manifestResourceTemplateSchema,manifestPromptSchema,manifestSkillSchema,manifestAppSchema,serverManifestSchema;var init_server_manifest_schema=__esm({"libs/sdk/src/manifest/server-manifest.schema.ts"(){"use strict";SERVER_MANIFEST_VERSION=1;SERVER_MANIFEST_FILE="frontmcp.manifest.json";jsonObjectSchema=z90.record(z90.string(),z90.unknown());ownedEntryShape={app:z90.string().optional(),owner:z90.string(),enabled:z90.union([z90.literal(false),z90.literal("source")]).optional(),availableWhen:jsonObjectSchema.optional(),authorities:z90.literal(true).optional()};manifestToolSchema=z90.object({name:z90.string(),...ownedEntryShape,title:z90.string().optional(),description:z90.string().optional(),inputSchema:jsonObjectSchema,outputSchema:jsonObjectSchema.optional(),annotations:jsonObjectSchema.optional(),icons:z90.array(jsonObjectSchema).optional(),_meta:jsonObjectSchema.optional(),tags:z90.array(z90.string()).optional(),aliases:z90.array(z90.string()).optional(),visibility:z90.enum(["public","hidden","internal"]),execution:jsonObjectSchema.optional(),output:jsonObjectSchema.optional(),examples:z90.array(jsonObjectSchema).optional(),ui:z90.literal(true).optional()});resourceShape={name:z90.string(),...ownedEntryShape,title:z90.string().optional(),description:z90.string().optional(),mimeType:z90.string().optional(),icons:z90.array(jsonObjectSchema).optional(),annotations:jsonObjectSchema.optional(),_meta:jsonObjectSchema.optional()};manifestResourceSchema=z90.object({uri:z90.string(),...resourceShape});manifestResourceTemplateSchema=z90.object({uriTemplate:z90.string(),...resourceShape});manifestPromptSchema=z90.object({name:z90.string(),...ownedEntryShape,title:z90.string().optional(),description:z90.string().optional(),arguments:z90.array(z90.object({name:z90.string(),description:z90.string().optional(),required:z90.boolean().optional()})).optional(),icons:z90.array(jsonObjectSchema).optional()});manifestSkillSchema=z90.object({name:z90.string(),...ownedEntryShape,path:z90.string(),description:z90.string(),tags:z90.array(z90.string()).optional(),visibility:z90.enum(["mcp","http","both"]),hidden:z90.literal(true).optional(),tools:z90.array(z90.object({name:z90.string(),purpose:z90.string().optional(),required:z90.boolean().optional()})),license:z90.string().optional(),hash:z90.string().optional()});manifestAppSchema=z90.object({id:z90.string(),name:z90.string(),description:z90.string().optional(),remote:z90.literal(true).optional(),standalone:z90.union([z90.boolean(),z90.literal("includeInParent")]).optional(),output:jsonObjectSchema.optional()});serverManifestSchema=z90.object({manifestVersion:z90.literal(SERVER_MANIFEST_VERSION),server:z90.object({name:z90.string(),version:z90.string(),title:z90.string().optional(),instructions:z90.string().optional()}),budget:z90.object({instructions:z90.number(),toolDescription:z90.number()}).optional(),apps:z90.array(manifestAppSchema),tools:z90.array(manifestToolSchema),resources:z90.array(manifestResourceSchema),resourceTemplates:z90.array(manifestResourceTemplateSchema),prompts:z90.array(manifestPromptSchema),skills:z90.array(manifestSkillSchema)})}});function ownersOf(lineage,owner){const owners2=(lineage??[]).filter(candidate=>candidate.kind!=="scope");if(owners2.length>0)return owners2;return lineage&&lineage.length>0?[lineage[lineage.length-1]]:[owner]}function entriesOf(scopes,registryOf){const seen=new Set;const found=[];for(const scope of scopes){const registry=registryOf(scope);for(const entry of registry.listAllInstances()){if(seen.has(entry))continue;seen.add(entry);found.push({entry,lineage:ownersOf(registry.lineageOf(entry),entry.owner)})}}return found}function enabledState(enabled){if(enabled===false)return false;return isEnabledSource(enabled)?"source":void 0}function ownedFields(lineage,metadata){const fields=metadata;return{app:lineage.find(owner=>owner.kind==="app")?.id,owner:ownerKeyOf(lineage),enabled:enabledState(fields.enabled),availableWhen:jsonObject(fields.availableWhen),authorities:fields.authorities===void 0?void 0:true}}function jsonObject(value){return value}function jsonObjects(values){return values?.map(value=>value)}function sortedBy(items,key){return items.sort((left,right)=>{const a=key(left);const b=key(right);if(a===b)return 0;return a<b?-1:1})}async function skillHash(skill){try{const content=await skill.load();return computeSkillHash({...content,instructions:content.instructions.replace(/\r\n/g,"\n")})}catch{return void 0}}function manifestToolOf(tool,lineage){return{name:tool.metadata.id??tool.metadata.name,title:tool.metadata.title,description:tool.metadata.description,...ownedFields(lineage,tool.metadata),inputSchema:tool.getInputJsonSchema()??{type:"object",properties:{}},outputSchema:tool.getOutputJsonSchema()??void 0,annotations:jsonObject(tool.metadata.annotations),icons:jsonObjects(tool.metadata.icons),_meta:tool.metadata._meta,tags:tool.metadata.tags,aliases:tool.metadata.aliases,visibility:resolveToolVisibility(tool.metadata),execution:jsonObject(tool.metadata.execution),output:jsonObject(tool.metadata.output),examples:jsonObjects(tool.metadata.examples),ui:hasUIConfig(tool.metadata)?true:void 0}}function manifestResourceOf(resource,lineage){const metadata=resource.metadata;const fields={name:metadata.name,title:metadata.title,description:metadata.description,mimeType:metadata.mimeType,icons:jsonObjects(metadata.icons),annotations:jsonObject(metadata.annotations),_meta:metadata._meta,...ownedFields(lineage,metadata)};if(resource.isTemplate&&resource.uriTemplate)return{template:{uriTemplate:resource.uriTemplate,...fields}};return resource.uri?{resource:{uri:resource.uri,...fields}}:void 0}function manifestPromptOf(prompt,lineage){return{name:prompt.metadata.name,title:prompt.metadata.title,description:prompt.metadata.description,...ownedFields(lineage,prompt.metadata),arguments:prompt.metadata.arguments,icons:jsonObjects(prompt.metadata.icons)}}function manifestAppOf(app){const metadata=app.metadata;return{id:app.id,name:metadata.name,description:metadata.description,remote:app.isRemote?true:void 0,standalone:metadata.standalone||void 0,output:jsonObject(app.metadata.output)}}async function buildServerManifest(scopes,primary){const tools=entriesOf(scopes,scope=>scope.tools).map(({entry,lineage})=>manifestToolOf(entry,lineage));const resources=[];const resourceTemplates=[];for(const{entry,lineage}of entriesOf(scopes,scope=>scope.resources)){const recorded=manifestResourceOf(entry,lineage);if(recorded&&"template"in recorded)resourceTemplates.push(recorded.template);else if(recorded)resources.push(recorded.resource)}const prompts=entriesOf(scopes,scope=>scope.prompts).map(({entry,lineage})=>manifestPromptOf(entry,lineage));const skills=await Promise.all(entriesOf(scopes,scope=>scope.skills).map(async({entry:skill,lineage})=>({name:skill.metadata.name,path:skill.getSkillPath(),description:skill.getDescription(),...ownedFields(lineage,skill.metadata),tags:skill.metadata.tags,visibility:skill.metadata.visibility??"both",hidden:skill.isHidden()?true:void 0,tools:skill.getToolRefs().map(({name:name51,purpose,required})=>({name:name51,purpose,required})),license:skill.getLicense(),hash:await skillHash(skill)})));const apps=new Map;for(const scope of scopes){for(const app of scope.apps.getApps()){if(!apps.has(app.id))apps.set(app.id,manifestAppOf(app))}}const instructions=await composeCallerInstructions(primary,{skillUriHints:true});const manifest={manifestVersion:SERVER_MANIFEST_VERSION,server:{name:primary.metadata.info.name,version:primary.metadata.info.version,title:primary.metadata.info.title,instructions:instructions.length>0?instructions:void 0},budget:resolveInstructionsBudget(primary.metadata.instructionsBudget),apps:sortedBy([...apps.values()],app=>app.id),tools:sortedBy(tools,tool=>`${tool.name}\0${tool.owner}`),resources:sortedBy(resources,resource=>`${resource.uri}\0${resource.owner}`),resourceTemplates:sortedBy(resourceTemplates,template=>`${template.uriTemplate}\0${template.owner}`),prompts:sortedBy(prompts,prompt=>`${prompt.name}\0${prompt.owner}`),skills:sortedBy(skills,skill=>`${skill.path}\0${skill.owner}`)};return JSON.parse(JSON.stringify(manifest))}var init_build_server_manifest=__esm({"libs/sdk/src/manifest/build-server-manifest.ts"(){"use strict";init_enabled_metadata();init_tool_metadata();init_instructions_budget();init_skill_instructions_helper();init_skill_hash();init_ui_shared();init_lineage_utils();init_server_manifest_schema()}});function registerEnforcedMetadataKeys(keys,enforcedBy){for(const key of keys){if(!enforcedMetadataKeys.has(key))enforcedMetadataKeys.set(key,enforcedBy)}}function getEnforcedMetadataKeys(){return[...enforcedMetadataKeys.keys()]}function describeMetadataEnforcer(key){return enforcedMetadataKeys.get(key)}function isEnforcementRequested(value){return value!==void 0&&value!==null&&value!==false}var enforcedMetadataKeys;var init_enforced_metadata_utils=__esm({"libs/sdk/src/common/utils/enforced-metadata.utils.ts"(){"use strict";enforcedMetadataKeys=new Map([["approval","ApprovalPlugin from @frontmcp/plugin-approval"],["featureFlag","FeatureFlagPlugin from @frontmcp/plugin-feature-flags"]])}});function reasonsOf(entries){return entries.flatMap(({label,authorities,ownEnabledSource,widget,readBeforeTheCall=[]})=>[...authorities?[`${label} declares authorities`]:[],...ownEnabledSource?[`${label} has an enabled source of its own (give the lazy app the switch instead)`]:[],...widget?[`${label} has a widget (ui)`]:[],...readBeforeTheCall.map(key=>`${label} declares '${key}', which a plugin reads from its placeholder`)])}function whyListedAppCannotBeLazy(listed){const facts=(label,entry)=>({label,authorities:entry.authorities===true,ownEnabledSource:entry.enabled==="source",widget:entry.ui===true});return[...listed.skills.map(skill=>`the manifest lists skill "${skill.name}" for it`),...reasonsOf([...listed.tools.map(tool=>facts(`tool "${tool.name}"`,tool)),...listed.resources.map(resource=>facts(`resource "${resource.uri}"`,resource)),...listed.resourceTemplates.map(template=>facts(`resource template "${template.uriTemplate}"`,template)),...listed.prompts.map(prompt=>facts(`prompt "${prompt.name}"`,prompt))])]}function whyAppCannotBeLazy(metadata){const reasons=[];for(const key of["jobs","workflows","channels"]){if(metadata[key]?.length)reasons.push(`it declares ${key}`)}if(metadata.auth)reasons.push("it declares its own auth");if(metadata.standalone)reasons.push("it is standalone (a lazy app joins the server's scope)");if(metadata.ui)reasons.push("it declares ui defaults");for(const name51 of serverScopedPluginsOf(metadata.plugins??[])){reasons.push(`plugin "${name51}" has scope 'server' (its hooks would guard no other app until this one is imported)`)}return reasons}function serverScopedPluginsOf(plugins){return plugins.flatMap(plugin=>{const{metadata}=normalizePlugin(plugin);const nested=serverScopedPluginsOf(metadata.plugins??[]);return metadata.scope==="server"?[metadata.name,...nested]:nested})}function whyLoadedAppCannotBeLazy(entries){const names=list=>list.map(({name:name51})=>`"${name51}"`).join(", ");const reasons=[];if(entries.skills.length>0)reasons.push(`it has skills (${names(entries.skills)})`);if(entries.agents.length>0)reasons.push(`it has agents (${names(entries.agents)})`);if(entries.duties.length>0)reasons.push(`it has duties (${names(entries.duties)}), which start with the server`);for(const hook of entries.hooks){const label=`${hook.metadata.pluginName??classNameOf2(hook)}.${hook.metadata.method}`;if(!ENTRY_CALL_FLOWS.has(hook.metadata.flow)){reasons.push(`the hook ${label} is on ${hook.metadata.flow}, which runs it for every app`)}else if(hook.metadata.appliesTo==="all-apps"){reasons.push(`the hook ${label} applies to all apps`)}}const facts=(label,entry,widget=false)=>({label,authorities:entry.authorities!==void 0,ownEnabledSource:isEnabledSource(entry.enabled),widget,readBeforeTheCall:READ_BEFORE_THE_CALL.filter(key=>isEnforcementRequested(entry[key]))});return[...reasons,...reasonsOf([...entries.tools.map(tool=>facts(`tool "${tool.name}"`,tool.metadata,hasUIConfig(tool.metadata))),...entries.resources.map(resource=>facts(resource.isTemplate?`resource template "${resource.uriTemplate}"`:`resource "${resource.uri}"`,resource.metadata)),...entries.prompts.map(prompt=>facts(`prompt "${prompt.name}"`,prompt.metadata))])]}function classNameOf2(hook){const cls=hookClassOf(hook);return typeof cls==="function"&&cls.name?cls.name:"an anonymous class"}var ENTRY_CALL_FLOWS,READ_BEFORE_THE_CALL;var init_lazy_app_rules=__esm({"libs/sdk/src/app/lazy/lazy-app.rules.ts"(){"use strict";init_enabled_metadata();init_enforced_metadata_utils();init_hook_registry();init_plugin_utils();init_ui_shared();ENTRY_CALL_FLOWS=new Set(["tools:call-tool","resources:read-resource","prompts:get-prompt","completion:complete"]);READ_BEFORE_THE_CALL=["featureFlag","codecall"]}});import{dirname as dirname6,fileExists as fileExists6,pathResolve as pathResolve5,readFile as readFile6}from"@frontmcp/utils";function serverManifestOf(scope){let lookup=lookups.get(scope);if(!lookup){const{manifest,__sourceDir}=scope.metadata;lookup=readServerManifest(manifest,__sourceDir);lookups.set(scope,lookup)}return lookup}async function readServerManifest(option,sourceDir){if(typeof option==="object")return{manifest:parsedManifest(option,"@FrontMcp({ manifest })"),where:"@FrontMcp({ manifest })"};const path4=option===void 0?manifestNextToEntry():pathResolve5(sourceDir??process.cwd(),option);if(!path4)return{where:`${SERVER_MANIFEST_FILE} next to the entry script, which this runtime does not name`};if(!await fileExists6(path4))return{where:path4};let content;try{content=JSON.parse(await readFile6(path4))}catch(error){throw unreadableManifest(path4,error instanceof Error?error.message:String(error))}return{manifest:parsedManifest(content,path4),where:path4}}function manifestNextToEntry(){const entry=typeof process==="undefined"?void 0:process.argv?.[1];return entry?pathResolve5(dirname6(pathResolve5(entry)),SERVER_MANIFEST_FILE):void 0}function parsedManifest(value,where){const parsed=serverManifestSchema.safeParse(value);if(parsed.success)return parsed.data;const issues=parsed.error.issues.slice(0,3).map(issue=>`${issue.path.join(".")||"manifest"}: ${issue.message}`);throw unreadableManifest(where,issues.join("; "))}function unreadableManifest(where,reason){return new LazyAppConfigurationError(`${where} is not a ${SERVER_MANIFEST_FILE} this server can read (${reason}). Run \`frontmcp build\` to write it again.`)}function noteEagerLoading(scope,where){if(notedEagerLoading.has(scope))return;notedEagerLoading.add(scope);scope.logger.info(`No ${SERVER_MANIFEST_FILE} (looked for ${where}): lazy apps are loaded at startup. Run \`frontmcp build\` to write one; with it, each lazy app is imported on its first call.`)}function listedAppOf(manifest,appId){const app=manifest.apps.find(candidate=>candidate.id===appId);if(!app)return void 0;const own=entries=>entries.filter(entry=>entry.app===appId);return{app,tools:own(manifest.tools),resources:own(manifest.resources),resourceTemplates:own(manifest.resourceTemplates),prompts:own(manifest.prompts),skills:own(manifest.skills)}}function recordedListsOf(listed){return{tools:listed.tools,resources:[...listed.resources,...listed.resourceTemplates],prompts:listed.prompts}}function canonicalJson(value){const sorted=node=>{if(Array.isArray(node))return node.map(sorted);if(node===null||typeof node!=="object")return node;const record=node;return Object.fromEntries(Object.keys(record).sort().map(key=>[key,sorted(record[key])]))};return JSON.stringify(sorted(JSON.parse(JSON.stringify(value))))}function sameEntries(left,right){const fingerprint=entries=>entries.map(canonicalJson).sort().join("\n");return fingerprint(left)===fingerprint(right)}function changedLists(listed,loaded,outputs){const kinds=["tools","resources","prompts"];return kinds.filter(kind=>!sameEntries(listed[kind],loaded[kind])||kind==="tools"&&canonicalJson(outputs.listed??{})!==canonicalJson(outputs.loaded??{}))}var lookups,notedEagerLoading;var init_lazy_manifest=__esm({"libs/sdk/src/app/lazy/lazy-manifest.ts"(){"use strict";init_lazy_app_errors();init_server_manifest_schema();lookups=new WeakMap;notedEagerLoading=new WeakSet}});var app_lazy_instance_exports={};__export(app_lazy_instance_exports,{AppLazyInstance:()=>AppLazyInstance});import{getMetadata as getMetadata20,isClass as isClass18}from"@frontmcp/di";import{isProduction as isProduction6}from"@frontmcp/utils";function appClassOf(imported,appId){const isApp=value=>isClass18(value)&&getMetadata20(FrontMcpLocalAppTokens.type,value)!==void 0;if(isApp(imported))return imported;const exports=typeof imported==="object"&&imported!==null?imported:{};if(isApp(exports["default"]))return exports["default"];const apps=Object.values(exports).filter(isApp);if(apps.length===1)return apps[0];throw new LazyAppConfigurationError(`App "${appId}": the lazy import resolved to no @App class (${apps.length>1?`${apps.length} @App exports and no default export`:"no @App export"}). Resolve it to the app's class, such as () => import('./billing.app').then((m) => m.BillingApp).`)}function placeholderToolClass(app){return class LazyToolPlaceholder extends ToolContext{async execute(){throw new LazyAppLoadError(app.metadata.name,app.retryable)}}}function placeholderResourceClass(app){return class LazyResourcePlaceholder extends ResourceContext{async execute(){throw new LazyAppLoadError(app.metadata.name,app.retryable)}}}function placeholderPromptClass(app){return class LazyPromptPlaceholder extends PromptContext{async execute(){throw new LazyAppLoadError(app.metadata.name,app.retryable)}}}function recordedListsOfApp(app){const lineageOf=(registry,entry)=>ownersOf(registry.lineageOf(entry),entry.owner);const resources=app.resources.listAllInstances().flatMap(resource=>{const recorded=manifestResourceOf(resource,lineageOf(app.resources,resource));if(!recorded)return[];return["template"in recorded?recorded.template:recorded.resource]});return{tools:app.tools.listAllInstances().map(tool=>manifestToolOf(tool,lineageOf(app.tools,tool))),resources,prompts:app.prompts.listAllInstances().map(prompt=>manifestPromptOf(prompt,lineageOf(app.prompts,prompt)))}}function cannotBeLazy(appId,reasons){return new LazyAppConfigurationError(`App "${appId}" cannot be lazy: ${reasons.join("; ")}. A lazy app's tools, resources and prompts are listed from ${SERVER_MANIFEST_FILE} before its code is imported, so nothing in them may need that code to be listed, its hooks may run only for its own calls, and nothing only startup sets up. Remove \`lazy\` to import the app at startup, or move these to an app that is not lazy.`)}function messageOf4(error){return error instanceof Error?error.message:String(error)}var AppLazyInstance;var init_app_lazy_instance=__esm({"libs/sdk/src/app/instances/app.lazy.instance.ts"(){"use strict";init_common();init_duty_metadata();init_lazy_app_errors();init_plugin_errors();init_manifest_mode_flag();init_hook_registry();init_build_server_manifest();init_server_manifest_schema();init_prompt_instance();init_prompt_registry();init_provider_registry();init_resource_instance();init_resource_registry();init_unchanged_lists();init_tool_instance();init_tool_registry();init_app_utils();init_lazy_app_rules();init_lazy_manifest();init_lazy_placeholders();init_app_local_instance();init_empty_app_registries();AppLazyInstance=class extends AppEntry{id;retryable=true;scopeProviders;ownProviders;appOwner;appTools;appResources;appPrompts;noPlugins=new EmptyPluginRegistry2;noAdapters=new EmptyAdapterRegistry2;noSkills=new EmptySkillRegistry2;listed;loaded;loading;failure;constructor(record,scopeProviders){super(record);this.id=appIdOf(this.metadata);this.scopeProviders=scopeProviders;this.appOwner={kind:"app",id:this.id,ref:this.token};this.ownProviders=new ProviderRegistry([],scopeProviders);this.appTools=new ToolRegistry(this.ownProviders,[],this.appOwner,{adopt:false});this.appResources=new ResourceRegistry(this.ownProviders,[],this.appOwner,{adopt:false});this.appPrompts=new PromptRegistry(this.ownProviders,[],this.appOwner,{adopt:false});this.ready=this.initialize()}async initialize(){await Promise.all([this.ownProviders.ready,this.appTools.ready,this.appResources.ready,this.appPrompts.ready]);const scope=this.scope;if(isManifestMode(scope.metadata))return this.load();const{manifest,where}=await serverManifestOf(scope);const listed=manifest&&listedAppOf(manifest,this.id);if(listed)return this.listFrom(listed);if(isProduction6()){const missing=manifest?`${where} does not list it`:`no ${SERVER_MANIFEST_FILE} was found (looked for ${where})`;throw new LazyAppConfigurationError(`App "${this.id}" is lazy, and ${missing}. In production a lazy app is listed from the manifest until its first call: Run \`frontmcp build\` and ship ${SERVER_MANIFEST_FILE} next to the server's entry, or pass @FrontMcp({ manifest }).`)}if(this.metadata.enabled===false)return;if(manifest){scope.logger.info(`App "${this.id}" is loaded at startup: ${where} does not list it. Run \`frontmcp build\` to write it again.`)}else{noteEagerLoading(scope,where)}await this.load()}get scope(){return this.scopeProviders.getActiveScope()}load(){if(this.loaded)return Promise.resolve();if(this.failure)return Promise.reject(this.failure);this.loading??=this.importApp().finally(()=>{this.loading=void 0});return this.loading}async importApp(){const scope=this.scope;const hooksBefore=new Set(scope.hooks.getHooks());let app;try{const record=normalizeApp(appClassOf(await this.metadata.lazy(),this.id));const imported=record.metadata;if(appIdOf(imported)!==this.id){throw new LazyAppConfigurationError(`App "${this.id}": the lazy import resolved to the imported app "${appIdOf(imported)}". Give the lazy app the @App's id, or import the app it names.`)}const reasons=whyAppCannotBeLazy(imported);if(reasons.length>0)throw cannotBeLazy(this.id,reasons);this.assertServing();app=new AppLocalInstance(record,this.scopeProviders);await app.ready;this.assertCanBeLazy(app,hooksBefore);const recorded=recordedListsOfApp(app);if(!isManifestMode(scope.metadata))this.applySwitch(app);if(this.listed){await scope.checkLateApp(app);await app.providers.runReadyHooks(scope.logger)}this.assertServing();this.useLoaded(app,imported,recorded)}catch(error){if(app)await this.discard(app,hooksBefore);this.retryable=!(error instanceof LazyAppConfigurationError||error instanceof UnenforcedMetadataError);if(!this.retryable)this.failure=error;if(this.listed&&!scope.isDisposed){const next=this.retryable?"the next call imports it again":"restart the server once it is fixed";scope.logger.error(`App "${this.id}" could not be loaded (${next}): ${messageOf4(error)}`)}throw error}}assertServing(){if(this.scope.isDisposed)throw new LazyAppLoadError(this.metadata.name,false)}assertCanBeLazy(app,hooksBefore){const duties=[...app.providers.getAllSingletons().values()].flatMap(value=>dutyMetadataOf(value)??[]);const reasons=whyLoadedAppCannotBeLazy({tools:app.tools.listAllInstances(),resources:app.resources.listAllInstances(),prompts:app.prompts.listAllInstances(),skills:app.skills.getSkills(true),agents:app.agents.listAllInstances(),hooks:this.hooksRegisteredBy(app,hooksBefore).filter(hook=>hook.metadata.owner),duties});if(reasons.length>0)throw cannotBeLazy(this.id,reasons)}hooksRegisteredBy(app,hooksBefore){const registries=[app.tools,app.resources,app.prompts];const entryClasses=new Set(registries.flatMap(registry=>registry?.listAllInstances().map(entry=>entry.record.provide)??[]));return this.scope.hooks.getHooks().filter(hook=>{if(hooksBefore.has(hook))return false;const owner=hook.metadata.owner;return owner?owner.kind==="app"&&owner.id===this.id:entryClasses.has(hookClassOf(hook))})}async discard(app,hooksBefore){const scope=this.scope;scope.hooks.removeHooks(this.hooksRegisteredBy(app,hooksBefore));const providers=app.providers;await providers?.runShutdownHooks(scope.logger);providers?.dispose();app.adapters?.dispose()}applySwitch(app){const enabled=this.metadata.enabled;if(enabled===void 0)return;const entries=[...app.tools.listAllInstances(),...app.resources.listAllInstances(),...app.prompts.listAllInstances()];for(const entry of entries){if(entry.metadata.enabled!==false)entry.metadata.enabled=enabled}}useLoaded(app,imported,recorded){const listedOutput=this.metadata.output;this.metadata.description??=imported.description;this.metadata.output=imported.output;const changed=this.listed?changedLists(recordedListsOf(this.listed),recorded,{listed:listedOutput,loaded:imported.output}):[];keepingListsUnchanged(()=>{this.appTools.replaceAll([],this.appOwner);this.appResources.replaceAll([],this.appOwner);this.appPrompts.replaceAll([],this.appOwner);this.appTools.adoptFromChild(app.tools,app.tools.owner);this.appResources.adoptFromChild(app.resources,app.resources.owner);this.appPrompts.adoptFromChild(app.prompts,app.prompts.owner)});this.loaded=app;this.listed=void 0;if(changed.length===0)return;this.scope.logger.warn(`App "${this.id}" does not match ${SERVER_MANIFEST_FILE} (${changed.join(", ")}): its entries are listed from its code from now on. Run \`frontmcp build\` to write the manifest again.`);for(const kind of changed)this.registryOf(kind).notifyListChanged()}registryOf(kind){const scope=this.scope;return kind==="tools"?scope.tools:kind==="resources"?scope.resources:scope.prompts}async listFrom(listed){const reasons=whyListedAppCannotBeLazy(listed);if(reasons.length>0)throw cannotBeLazy(this.id,reasons);this.listed=listed;this.metadata.description??=listed.app.description;this.metadata.output=listed.app.output;const enabledOf=entry=>entry.enabled===false?false:this.metadata.enabled;const placeholders=[...listed.tools.map(tool=>this.toolPlaceholder(tool,enabledOf(tool))),...listed.resources.map(resource=>this.resourcePlaceholder(resource,enabledOf(resource))),...listed.resourceTemplates.map(template=>this.resourcePlaceholder(template,enabledOf(template))),...listed.prompts.map(prompt=>this.promptPlaceholder(prompt,enabledOf(prompt)))];await Promise.all(placeholders.map(placeholder=>placeholder.ready));for(const placeholder of placeholders)markPlaceholder(placeholder,this)}toolPlaceholder(tool,enabled){const metadata={name:tool.name,title:tool.title,description:tool.description,inputSchema:{},rawInputSchema:tool.inputSchema,rawOutputSchema:tool.outputSchema,annotations:tool.annotations,icons:tool.icons,_meta:tool._meta,tags:tool.tags,aliases:tool.aliases,visibility:tool.visibility,execution:tool.execution,output:tool.output,examples:tool.examples,availableWhen:tool.availableWhen,enabled};const placeholder=new ToolInstance({kind:"CLASS_TOKEN",provide:placeholderToolClass(this),metadata},this.ownProviders,this.appOwner);this.appTools.registerToolInstance(placeholder);return placeholder}resourcePlaceholder(resource,enabled){const{app:_app,owner:_owner,authorities:_authorities,enabled:_enabled,...listedFields}=resource;const metadata={...listedFields,enabled};const provide=placeholderResourceClass(this);const record="uriTemplate"in resource?{kind:"CLASS_TOKEN",provide,metadata}:{kind:"CLASS_TOKEN",provide,metadata};const placeholder=new ResourceInstance(record,this.ownProviders,this.appOwner);this.appResources.registerResourceInstance(placeholder);return placeholder}promptPlaceholder(prompt,enabled){const{app:_app,owner:_owner,authorities:_authorities,enabled:_enabled,...listedFields}=prompt;const metadata={...listedFields,arguments:listedFields.arguments??[],enabled};const provide=placeholderPromptClass(this);const placeholder=new PromptInstance({kind:"CLASS_TOKEN",provide,metadata},this.ownProviders,this.appOwner);this.appPrompts.registerPromptInstance(placeholder);return placeholder}get providers(){return this.ownProviders}get adapters(){return this.loaded?.adapters??this.noAdapters}get plugins(){return this.loaded?.plugins??this.noPlugins}get tools(){return this.appTools}get resources(){return this.appResources}get prompts(){return this.appPrompts}get skills(){return this.noSkills}}}});import"reflect-metadata";import{tokenName as tokenName19}from"@frontmcp/di";var AppRegistry;var init_app_registry=__esm({"libs/sdk/src/app/app.registry.ts"(){"use strict";init_common();init_errors();init_regsitry();init_app_utils();init_app_local_instance();AppRegistry=class extends RegistryAbstract{owner;logger;constructor(globalProviders,list,owner){super("AppRegistry",globalProviders,list);this.owner=owner;try{this.logger=globalProviders.get(FrontMcpLogger)?.child("AppRegistry")}catch{}}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;const configuredAppIds=new Set;const records=list.map(raw=>normalizeApp(raw));for(const rec of records){if(rec.kind==="REMOTE_VALUE"&&!rec.useValue||rec.kind==="LAZY_IMPORT"){const appId=appIdOf(rec.metadata);if(configuredAppIds.has(appId))throw new DuplicateAppIdError(appId);configuredAppIds.add(appId)}const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}for(const rec of records){if(rec.kind!=="LAZY_IMPORT")continue;const appId=appIdOf(rec.metadata);if(records.some(other=>other!==rec&&appIdOf(other.metadata)===appId)){throw new DuplicateAppIdError(appId)}}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);const deps=appDiscoveryDeps(rec);for(const d of deps){if(!this.providers.get(d)){throw new RegistryDependencyNotRegisteredError("App",tokenName19(token),tokenName19(d))}this.graph.get(token).add(d)}}}async initialize(){this.logger?.verbose(`AppRegistry: initializing ${this.tokens.size} app(s)`);const readyArr=[];for(const token of this.tokens){const rec=this.defs.get(token);let app;if(rec.kind==="LOCAL_CLASS"){app=new AppLocalInstance(rec,this.providers)}else if(rec.kind==="REMOTE_VALUE"){const remoteMeta=rec.metadata;if(remoteMeta.urlType==="npm"||remoteMeta.urlType==="esm"){const{AppEsmInstance:AppEsmInstance2}=await Promise.resolve().then(()=>(init_app_esm_instance(),app_esm_instance_exports));app=new AppEsmInstance2(rec,this.providers)}else{const{AppRemoteInstance:AppRemoteInstance2}=await Promise.resolve().then(()=>(init_app_remote_instance(),app_remote_instance_exports));app=new AppRemoteInstance2(rec,this.providers)}}else if(rec.kind==="LAZY_IMPORT"){const{AppLazyInstance:AppLazyInstance2}=await Promise.resolve().then(()=>(init_app_lazy_instance(),app_lazy_instance_exports));app=new AppLazyInstance2(rec,this.providers)}else{throw new InvalidRegistryKindError("app",rec.kind)}this.instances.set(token,app);readyArr.push(app.ready);this.logger?.verbose(`AppRegistry: registered ${rec.kind} app '${rec.metadata.name}'`)}const settled=await Promise.allSettled(readyArr);const failure=settled.find(result=>result.status==="rejected");if(failure)throw failure.reason;this.logger?.debug(`AppRegistry: initialization complete (${this.instances.size} app(s))`)}getApps(){return[...this.instances.values()]}}}});import{depsOfClass as depsOfClass11,getMetadata as getMetadata21,isClass as isClass19,tokenName as tokenName20}from"@frontmcp/di";function collectAuthMetadata(cls){return Object.entries(FrontMcpAuthProviderTokens).reduce((metadata,[key,token])=>{return Object.assign(metadata,{[key]:getMetadata21(token,cls)})},{})}function normalizeAuth(item){if(isClass19(item)){const metadata=collectAuthMetadata(item);return{kind:"CLASS_TOKEN",provide:item,metadata}}if(item&&typeof item==="object"){const{provide,useClass,useValue,useFactory,inject,...metadata}=item;if(!provide){const name52=item?.name??"[object]";throw new MissingProvideError("Auth",name52)}if(useClass){if(!isClass19(useClass)){throw new InvalidUseClassError("auth",tokenName20(provide))}return{kind:"CLASS",provide,useClass,metadata}}if(useFactory){if(typeof useFactory!=="function"){throw new InvalidUseFactoryError("auth",tokenName20(provide))}const inj=typeof inject==="function"?inject:()=>[];return{kind:"FACTORY",provide,inject:inj,useFactory,metadata}}if("useValue"in item){return{kind:"VALUE",provide,useValue,metadata}}}const name51=item?.name??String(item);throw new InvalidEntityError("auth",name51,"a class or an auth object")}function authDiscoveryDeps(rec){switch(rec.kind){case"VALUE":case"PRIMARY":return[];case"FACTORY":{return[...rec.inject()]}case"CLASS":return depsOfClass11(rec.useClass,"discovery");case"CLASS_TOKEN":return depsOfClass11(rec.provide,"discovery")}}var init_auth_utils=__esm({"libs/sdk/src/auth/auth.utils.ts"(){"use strict";init_common();init_errors()}});import{ORCHESTRATED_AUTH_ACCESSOR,NullOrchestratedAuthAccessor}from"@frontmcp/auth";var orchestratedAuthContextExtension;var init_orchestrated_context_extension=__esm({"libs/sdk/src/auth/authorization/orchestrated.context-extension.ts"(){"use strict";orchestratedAuthContextExtension={property:"orchestration",token:ORCHESTRATED_AUTH_ACCESSOR,errorMessage:"Orchestrated authorization not available. Ensure your server is configured with orchestrated mode and the user has completed authentication."}}});import"reflect-metadata";import{detectAuthProviders}from"@frontmcp/auth";import{tokenName as tokenName21}from"@frontmcp/di";var DEFAULT_AUTH_OPTIONS,AuthRegistry;var init_auth_registry=__esm({"libs/sdk/src/auth/auth.registry.ts"(){"use strict";init_app_utils();init_common();init_context_extension();init_errors();init_regsitry();init_auth_utils();init_orchestrated_context_extension();DEFAULT_AUTH_OPTIONS={mode:"public"};AuthRegistry=class extends RegistryAbstract{primary;parsedOptions;logger;owner;detection;requiresOrchestration;constructor(scope,providers,metadata,owner,primaryInput,createPrimaryAuth2){super("AuthRegistry",providers,metadata,false);this.owner=owner;this.logger=providers.get(FrontMcpLogger).child("AuthRegistry");this.parsedOptions=parseAuthOptions(primaryInput??DEFAULT_AUTH_OPTIONS);const appAuthInfos=this.extractAppAuthInfo(scope);this.detection=detectAuthProviders(this.parsedOptions,appAuthInfos);this.requiresOrchestration=this.detection.requiresOrchestration;this.logDetectionResults();this.validateConfiguration();this.primary=createPrimaryAuth2(scope,providers,this.parsedOptions);if(isOrchestratedMode(this.parsedOptions)){installContextExtensions("orchestrated-auth",[orchestratedAuthContextExtension])}const primaryRecord={kind:"PRIMARY",provide:FrontMcpAuth,useValue:this.primary,metadata:this.parsedOptions};this.tokens.add(FrontMcpAuth);this.defs.set(FrontMcpAuth,primaryRecord);this.graph.set(FrontMcpAuth,new Set);this.buildGraph();this.ready=this.initialize()}extractAppAuthInfo(scope){const apps=scope.metadata.apps||[];const result=[];for(const app of apps){const appMeta=this.getAppMetadata(app);if(appMeta){result.push({id:appMeta.id||appMeta.name,name:appMeta.name,auth:appMeta.auth,remoteAuthMode:appMeta.remoteAuthMode})}}return result}getAppMetadata(app){if(typeof app==="object"&&"name"in app){const appValue=app;return{id:appValue.id,name:appValue.name,auth:appValue.auth,remoteAuthMode:appValue.remoteAuth?.mode}}if(typeof app==="function"){const metadata=collectAppMetadata(app);if(metadata.name){return{id:metadata.id,name:metadata.name,auth:metadata.auth}}}return void 0}logDetectionResults(){const{providers,uniqueProviderCount,requiresOrchestration,warnings}=this.detection;if(uniqueProviderCount>1){this.logger.info(`Detected ${uniqueProviderCount} unique auth providers: ${[...providers.keys()].join(", ")}`)}if(requiresOrchestration){this.logger.info(`Orchestration required: Multiple auth providers detected across apps`)}for(const warning of warnings){this.logger.warn(warning)}}validateConfiguration(){const{validationErrors}=this.detection;if(validationErrors.length>0){for(const error of validationErrors){this.logger.error(`[AuthRegistry] ${error}`)}throw new AuthConfigurationError(`Invalid auth configuration: ${validationErrors[0]}`,{errors:validationErrors,suggestion:this.suggestionFor(validationErrors[0])})}}suggestionFor(error){if(error.includes("remoteAuth: { mode: 'forward' }")){return`Give the remote its own credentials, or run the server in transparent mode:
186
186
  App.remote(url, { remoteAuth: { mode: 'static', credentials: { type: 'bearer', value: '...' } } })`}if(error.startsWith("App-level auth is not enforced")){return`1. Serve the app on its own endpoint: @App({ standalone: true }) or @FrontMcp({ splitByApp: true })
187
187
  2. Or run the server in local or remote mode with incrementalAuth, which checks app grants per tool call`}const parentMode=isTransparentMode(this.parsedOptions)?"transparent":this.parsedOptions.mode;return`1. Change your parent auth mode from '${parentMode}' to 'local' or 'remote'
188
188
  2. Example:
@@ -464,14 +464,14 @@ __mountAuthPage(${exportName});`,mountNodeId:AUTH_MOUNT_ID,mountNodeInnerHtml:"<
464
464
  <a href="javascript:history.back()" class="retry-link">\u2190 Go Back</a>
465
465
  </div>
466
466
  </body>
467
- </html>`}htmlPage(markup,status=200){return httpRespond.html(markup,status,builtInAuthPageHeaders4())}getStateValidation(){const authOptions=this.scope.auth?.options;if(authOptions&&isOrchestratedMode(authOptions)){return authOptions.federatedAuth?.stateValidation??"strict"}return"strict"}};__decorateClass([Stage45("checkIpFilter")],OauthProviderCallbackFlow.prototype,"checkIpFilter",1);__decorateClass([Stage45("acquireQuota")],OauthProviderCallbackFlow.prototype,"acquireQuota",1);__decorateClass([Stage45("parseInput")],OauthProviderCallbackFlow.prototype,"parseInput",1);__decorateClass([Stage45("handleConsentSubmission")],OauthProviderCallbackFlow.prototype,"handleConsentSubmission",1);__decorateClass([Stage45("loadFederatedSession")],OauthProviderCallbackFlow.prototype,"loadFederatedSession",1);__decorateClass([Stage45("validateProviderCallback")],OauthProviderCallbackFlow.prototype,"validateProviderCallback",1);__decorateClass([Stage45("exchangeProviderCode")],OauthProviderCallbackFlow.prototype,"exchangeProviderCode",1);__decorateClass([Stage45("storeProviderTokens")],OauthProviderCallbackFlow.prototype,"storeProviderTokens",1);__decorateClass([Stage45("handleNextProviderOrComplete")],OauthProviderCallbackFlow.prototype,"handleNextProviderOrComplete",1);OauthProviderCallbackFlow=__decorateClass([FrontMcpFlow({name:name45,plan:plan45,inputSchema:inputSchema38,outputSchema:outputSchema37,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});import{internalZ as z125}from"@frontmcp/lazy-zod";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 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";init_common();extraInputSchema=httpInputSchema;extraStateSchema=z125.object({action:z125.string().optional(),pendingAuthId:z125.string().optional(),csrf:z125.string().optional(),payload:z125.record(z125.string(),z125.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))]}});import"reflect-metadata";import{JwksService as JwksService2}from"@frontmcp/auth";import{internalZ as z126}from"@frontmcp/lazy-zod";var inputSchema39,stateSchema41,outputSchema38,plan46,name46,Stage46,WellKnownJwksFlow;var init_well_known_jwks_flow=__esm({"libs/sdk/src/auth/flows/well-known.jwks.flow.ts"(){"use strict";init_common();init_auth_internal_errors();inputSchema39=httpInputSchema;stateSchema41=z126.object({isOrchestrated:z126.boolean()});outputSchema38=z126.union([HttpJsonSchema,HttpTextSchema,HttpRedirectSchema]);plan46={pre:["checkIpFilter","acquireQuota","parseInput","validateInput"],execute:["collectData"]};name46="well-known.jwks";Stage46=StageHookOf(name46);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(JwksService2);if(isOrchestrated){const keysDoc=await jwksSvc.getPublicJwks();if(!keysDoc?.keys||!Array.isArray(keysDoc.keys)){throw new OrchestratorJwksNotAvailableError}this.respond(httpRespond.json(keysDoc));return}const options=this.scope.auth.options;if(options&&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([Stage46("checkIpFilter")],WellKnownJwksFlow.prototype,"checkIpFilter",1);__decorateClass([Stage46("acquireQuota")],WellKnownJwksFlow.prototype,"acquireQuota",1);__decorateClass([Stage46("parseInput")],WellKnownJwksFlow.prototype,"parseInput",1);__decorateClass([Stage46("collectData")],WellKnownJwksFlow.prototype,"collectData",1);WellKnownJwksFlow=__decorateClass([FrontMcpFlow({name:name46,plan:plan46,inputSchema:inputSchema39,outputSchema:outputSchema38,access:"public",middleware:{method:"GET"}})],WellKnownJwksFlow)}});import"reflect-metadata";import{advertisedScopes,trimSlash}from"@frontmcp/auth";import{internalZ as z127}from"@frontmcp/lazy-zod";import{isProduction as isProduction6}from"@frontmcp/utils";function resolveDcrEnabled(auth){if(auth&&isLocalMode(auth)){const dcr=auth.dcr;if(dcr&&typeof dcr.enabled==="boolean"){return dcr.enabled}}return!isProduction6()}var inputSchema40,AuthServerMetadataSchema,outputSchema39,wellKnownAsStateSchema,wellKnownAsPlan,name47,Stage47,WellKnownAsFlow;var init_well_known_oauth_authorization_server_flow=__esm({"libs/sdk/src/auth/flows/well-known.oauth-authorization-server.flow.ts"(){"use strict";init_common();init_sdk_errors();inputSchema40=httpInputSchema;AuthServerMetadataSchema=z127.object({kind:z127.literal("json"),status:z127.literal(200),contentType:z127.literal("application/json; charset=utf-8"),headers:z127.record(z127.string(),z127.string()).optional(),body:z127.object({issuer:z127.string().min(1),authorization_endpoint:z127.string().min(1),token_endpoint:z127.string().min(1),userinfo_endpoint:z127.string().min(1).optional(),jwks_uri:z127.string().min(1),registration_endpoint:z127.string().min(1).optional(),token_endpoint_auth_methods_supported:z127.array(z127.enum(["client_secret_basic","client_secret_post","private_key_jwt"])).optional(),response_types_supported:z127.array(z127.enum(["code"])).default(["code"]),grant_types_supported:z127.array(z127.enum(["authorization_code","refresh_token"])).default(["authorization_code","refresh_token"]),scopes_supported:z127.array(z127.string()).default(["openid","profile","email"]),code_challenge_methods_supported:z127.array(z127.enum(["S256"])).default(["S256"])}).passthrough()});outputSchema39=z127.union([AuthServerMetadataSchema,HttpRedirectSchema,HttpTextSchema]);wellKnownAsStateSchema=z127.object({baseUrl:z127.string().min(1),issuer:z127.string().min(1).optional(),oauthBaseUrl:z127.string().min(1),scopesSupported:z127.array(z127.string()).default(["openid","profile","email"]),tokenEndpointAuthMethods:z127.array(z127.enum(["client_secret_basic","client_secret_post","private_key_jwt"])).default(["client_secret_basic","client_secret_post"]),dcrEnabled:z127.boolean().default(true),isOrchestrated:z127.boolean(),cimdEnabled:z127.boolean().default(true)});wellKnownAsPlan={pre:["checkIpFilter","acquireQuota","parseInput"],execute:["collectData"]};name47="well-known.oauth-authorization-server";Stage47=StageHookOf(name47);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);let cimdEnabled=true;if(metadata.auth&&isOrchestratedMode(metadata.auth)){cimdEnabled=metadata.auth.cimd?.enabled??true}this.state.set(wellKnownAsStateSchema.parse({baseUrl,issuer,oauthBaseUrl,scopesSupported:metadata.auth&&isOrchestratedMode(metadata.auth)?advertisedScopes(metadata.auth.allowedScopes):[],tokenEndpointAuthMethods:[],dcrEnabled:resolveDcrEnabled(metadata.auth),isOrchestrated:metadata.auth?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,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||!isTransparentMode(authOptions)){this.respond(httpRespond.notFound());return}this.respond(httpRespond.redirect(`${trimSlash(this.scope.auth.issuer)}/.well-known/oauth-authorization-server`))}};__decorateClass([Stage47("checkIpFilter")],WellKnownAsFlow.prototype,"checkIpFilter",1);__decorateClass([Stage47("acquireQuota")],WellKnownAsFlow.prototype,"acquireQuota",1);__decorateClass([Stage47("parseInput")],WellKnownAsFlow.prototype,"parseInput",1);__decorateClass([Stage47("collectData")],WellKnownAsFlow.prototype,"collectData",1);WellKnownAsFlow=__decorateClass([FrontMcpFlow({name:name47,plan:wellKnownAsPlan,inputSchema:inputSchema40,outputSchema:outputSchema39,access:"public",middleware:{method:"GET"}})],WellKnownAsFlow)}});import"reflect-metadata";import{resourceScopesFor}from"@frontmcp/auth";import{internalZ as z128}from"@frontmcp/lazy-zod";var inputSchema41,stateSchema42,outputSchema40,plan47,name48,Stage48,WellKnownPrmFlow;var init_well_known_prm_flow=__esm({"libs/sdk/src/auth/flows/well-known.prm.flow.ts"(){"use strict";init_common();init_sdk_errors();inputSchema41=httpInputSchema;stateSchema42=z128.object({resource:z128.string().min(1),baseUrl:z128.string().min(1),authorizationServer:z128.string().min(1).optional(),scopesSupported:z128.array(z128.string()),isOrchestrated:z128.boolean()});outputSchema40=HttpJsonSchema.extend({body:z128.object({resource:z128.string().min(1),authorization_servers:z128.array(z128.string().min(1)).min(1).optional(),scopes_supported:z128.array(z128.string()).optional(),bearer_methods_supported:z128.array(z128.string()).default(["header"])}).passthrough()});plan47={pre:["checkIpFilter","acquireQuota","parseInput"],execute:["collectData"],post:["validateOutput"]};name48="well-known.oauth-protected-resource";Stage48=StageHookOf(name48);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 authorizationServer=scope.auth?.issuerFor?.(request2)??baseUrl;const authOptions=scope.auth?.options??scope.metadata.auth;const granted=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(stateSchema42.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([Stage48("checkIpFilter")],WellKnownPrmFlow.prototype,"checkIpFilter",1);__decorateClass([Stage48("acquireQuota")],WellKnownPrmFlow.prototype,"acquireQuota",1);__decorateClass([Stage48("parseInput")],WellKnownPrmFlow.prototype,"parseInput",1);__decorateClass([Stage48("collectData")],WellKnownPrmFlow.prototype,"collectData",1);WellKnownPrmFlow=__decorateClass([FrontMcpFlow({name:name48,plan:plan47,inputSchema:inputSchema41,outputSchema:outputSchema40,access:"public",middleware:{method:"GET"}})],WellKnownPrmFlow)}});import{isAnonymousSubject as isAnonymousSubject8}from"@frontmcp/auth";function sessionScopeIdentity(ctx){const verified=ctx.verifiedSessionId;if(verified)return verified;const authInfo=ctx.authInfo??{};const extraUser=authInfo.extra?.["user"];const principal=[authInfo.user?.sub,extraUser?.sub,authInfo.clientId].find(candidate=>!isAnonymousSubject8(candidate));return principal?`principal:${principal}`:void 0}var init_session_scope_identity=__esm({"libs/sdk/src/auth/session-scope-identity.ts"(){"use strict"}});import{SECURE_STORE_ACCESSOR,SecureStoreAccessorImpl}from"@frontmcp/auth";import{ProviderScope as ProviderScope9}from"@frontmcp/di";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:ProviderScope9.GLOBAL,name:"SecureStoreBackend"};const accessorProvider={provide:SECURE_STORE_ACCESSOR,inject:()=>[FRONTMCP_CONTEXT,FrontMcpLogger],useFactory:(ctx,logger)=>new SecureStoreAccessorImpl({backend,scope,resolveSub:()=>resolveRequestSub(ctx),resolveSessionId:()=>resolveRequestSessionId(ctx),ttlMs,logger:logger.child("SecureStore")}),scope:ProviderScope9.CONTEXT,name:"SecureStoreAccessor"};return[backendProvider,accessorProvider]}var SECURE_STORE_BACKEND;var init_secure_store_providers=__esm({"libs/sdk/src/auth/secure-store/secure-store.providers.ts"(){"use strict";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")}});import{SECURE_STORE_ACCESSOR as SECURE_STORE_ACCESSOR2}from"@frontmcp/auth";var secureStoreContextExtension;var init_secure_store_context_extension=__esm({"libs/sdk/src/auth/secure-store/secure-store.context-extension.ts"(){"use strict";secureStoreContextExtension={property:"secureStore",token:SECURE_STORE_ACCESSOR2,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()}});import{createSecureStore,createTokenStorageAdapter,DcrClientRegistry,deriveAuthorizationId as deriveAuthorizationId2,InMemoryAuthorizationStore,InMemoryConsentStore,InMemoryFederatedAuthSessionStore,InMemoryOrchestratedTokenStore,isPersistentTokenStorage,isRedisTokenStorage,isSqliteTokenStorage,JwksService as JwksService3,SessionCredentialVault,StorageAuthorizationStore,StorageConsentStore,StorageFederatedAuthSessionStore,StorageOrchestratedTokenStore,TokenNotAvailableError as TokenNotAvailableError2,verifyPkce}from"@frontmcp/auth";import{getEnv as getEnv17,isProduction as isProduction7,MemoryStorageAdapter,randomBytes as randomBytes11,randomUUID as randomUUID29,StorageNotSupportedError}from"@frontmcp/utils";function loadJose(){jose??=importWithRequireFallback(()=>import("jose"),()=>__require("jose")).catch(error=>{jose=void 0;throw error});return jose}function getDefaultNoAuthSecret(){if(!defaultNoAuthSecret){defaultNoAuthSecret=randomBytes11(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 StorageNotSupportedError}function originOf2(value){try{const origin=new URL(value).origin;return origin==="null"?void 0:origin}catch{return void 0}}var 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";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=getEnv17("FRONTMCP_PUBLIC_HOST")?.trim()||"localhost";this.issuer=this.deriveIssuer(options);this.publicHostPinned=!!getEnv17("FRONTMCP_PUBLIC_HOST")?.trim();const jwtSecret=getEnv17("JWT_SECRET");const hasJwtSecret=!!jwtSecret?.trim();if(hasJwtSecret&&jwtSecret){const encoded=new TextEncoder().encode(jwtSecret);if(encoded.length<MIN_HS256_SECRET_BYTES){if(isProduction7())throw new 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(isProduction7()&&isOrchestratedMode(options)){throw new JwtSecretRequiredError(options.mode)}else{if(!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.tokenStorage=this.readTokenStorage(options);this.authorizationStoreImpl=new InMemoryAuthorizationStore;this.federatedSessionStoreImpl=new InMemoryFederatedAuthSessionStore;this.orchestratedTokenStoreImpl=new InMemoryOrchestratedTokenStore({encryptionKey:this.secret,refreshSkewMs:this.providerRefreshSkewMs()});this.consentStoreImpl=new InMemoryConsentStore;this.scope.onDispose(()=>this.releaseResources());this.dcrClientRegistryImpl=new DcrClientRegistry(this.getDcrConfig()??{});if(isOrchestratedMode(options)){const cimdConfig=options.cimd;this.cimdService=new CimdService(this.logger,cimdConfig)}this.ready=this.initialize()}scope;providers;host;port;issuer;publicHostPinned;keys=[];secret;logger;jwks=new JwksService3;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(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!isProduction7()}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}`}configuredIssuer(options){const configured=isPublicMode(options)?options.issuer: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||!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}async initializeStores(){if(!isPersistentTokenStorage(this.tokenStorage)){return}try{const adapter=await createTokenStorageAdapter(this.tokenStorage);this.storageAdapter=adapter;this.storageClosers.push(()=>adapter.disconnect());this.disposeInMemoryStores();this.authorizationStoreImpl=new StorageAuthorizationStore(adapter);this.federatedSessionStoreImpl=new StorageFederatedAuthSessionStore(adapter);this.orchestratedTokenStoreImpl=new StorageOrchestratedTokenStore(adapter,{encryptionKey:this.secret,refreshSkewMs:this.providerRefreshSkewMs()});this.consentStoreImpl=new StorageConsentStore(adapter);const backend=isSqliteTokenStorage(this.tokenStorage)?"sqlite":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){const key=`incremental-ticket:${jti}`;const nonce=randomUUID29();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(`Incremental ticket replay guard unavailable: ${String(error)}`);return false}this.logger.warn("Incremental ticket 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(`Incremental ticket replay guard unavailable: ${String(fallbackError)}`);return false}}try{return await storage.get(key)===nonce}catch(error){this.logger.warn(`Incremental ticket replay guard unavailable: ${String(error)}`);return false}}getTicketReplayStorage(){if(!this.ticketReplayStorage){if(this.storageAdapter){this.ticketReplayStorage=Promise.resolve(this.storageAdapter)}else{this.logger.debug("Incremental ticket 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 MemoryStorageAdapter;await memory.connect();this.storageClosers.push(()=>memory.disconnect());return memory})();this.ticketReplayStorage=pending;return pending}async initializeCredentialVault(){if(isPublicMode(this.options)){return}let storage;if(this.storageAdapter){storage=this.storageAdapter}else{const memory=new MemoryStorageAdapter;await memory.connect();this.storageClosers.push(()=>memory.disconnect());storage=memory}const pepper=getEnv17("VAULT_SECRET")??getEnv17("JWT_SECRET")??void 0;this.credentialVaultImpl=new 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(isPublicMode(this.options)){return}const config=this.readSecureStoreConfig();const reuseAdapter=this.storageAdapter&&this.secureStoreSharesTokenStorage(config)?this.storageAdapter:void 0;const pepper=getEnv17("VAULT_SECRET")??getEnv17("JWT_SECRET")??new TextDecoder().decode(this.secret);const resolved=await 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 InMemoryFederatedAuthSessionStore){this.federatedSessionStoreImpl.dispose()}if(this.orchestratedTokenStoreImpl instanceof 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 isSqliteTokenStorage(this.tokenStorage);if("redis"in config&&config.redis)return isRedisTokenStorage(this.tokenStorage);return false}async signAnonymousJwt(options={}){const{SignJWT}=await loadJose();const jwt=new SignJWT({sub:`anon:${randomUUID29()}`,anonymous:true,scope:this.anonymousScopes().join(" ")}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setIssuer(options.issuer??this.issuer).setExpirationTime(`${this.anonymousTokenTtlSeconds()}s`).setJti(randomUUID29());if(options.audience)jwt.setAudience(options.audience);return jwt.sign(this.secret)}anonymousTokenTtlSeconds(){return 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{jwtVerify}=await loadJose();const{payload,protectedHeader}=await jwtVerify(token,this.secret,{algorithms:["HS256"],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 claims2={sub:user.sub,scope:scopes.join(" ")};if(user.email)claims2["email"]=user.email;if(user.name)claims2["name"]=user.name;if(user.picture)claims2["picture"]=user.picture;if(user.roles)claims2["roles"]=user.roles;if(consentMetadata){if(consentMetadata.consentEnabled){claims2["consent"]={enabled:true,selectedTools:consentMetadata.selectedToolIds??[]}}if(consentMetadata.federatedLoginUsed){claims2["federated"]={enabled:true,selectedProviders:consentMetadata.selectedProviderIds??[],skippedProviders:consentMetadata.skippedProviderIds??[]}}if(consentMetadata.authorizedAppIds){claims2["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}claims2[key]=value}}}const{SignJWT}=await loadJose();const jwt=new SignJWT(claims2).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setIssuer(issuer??this.issuer).setExpirationTime(`${this.accessTokenTtlSeconds}s`).setJti(randomUUID29());if(audience){jwt.setAudience(audience)}return jwt.sign(this.secret)}async exchangeCode(code,clientId,redirectUri,codeVerifier,clientSecret,defaultAudience,issuer){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 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(!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)}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);this.logger.info(`Tokens issued for user: ${user.sub}`);return{access_token:accessToken,token_type:"Bearer",expires_in:this.accessTokenTtlSeconds,refresh_token:refreshTokenRecord.token,scope:codeRecord.scopes.join(" ")}}async moveProviderTokens(fromAuthorizationId,accessToken){const toAuthorizationId=deriveAuthorizationId2(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=deriveAuthorizationId2(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){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 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.initializeStores();this.registerConfiguredProviders();this.registerRemoteProvider();await this.initializeCredentialVault();await this.initializeSecureStore();this.providers.injectProvider({value:this.jwks,metadata:{scope:ProviderScope2.GLOBAL,name:"auth:jwk-service"},provide:JwksService3});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:ProviderScope2.GLOBAL,name:"auth:cimd-service"},provide: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(!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})}}registerRemoteProvider(){if(!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;if(!options.clientId){this.logger.warn(`Remote mode: no clientId configured for provider "${id}"; upstream OAuth is not available (DCR is not yet wired)`);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:options.clientId,clientSecret:options.clientSecret,scopes:options.scopes??["openid"],callbackUrl:`${this.issuer}/oauth/provider/${id}/callback`,issuer:options.provider,additionalIssuers:cfg?.additionalIssuers,verifyIssuer:cfg?.verifyIssuer})}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 claims2=await this.verifyProviderIdToken(config,idToken);const sub=typeof claims2?.["sub"]==="string"&&claims2["sub"].trim()?claims2["sub"]:void 0;if(claims2&&sub){return{sub,email:claims2["email"],name:claims2["name"],picture:claims2["picture"],claims:claims2}}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(!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 TokenNotAvailableError2(`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(!isOrchestratedMode(this.options)||this.options.refresh?.enabled===false)return 0;return(this.options.refresh?.skewSeconds??60)*1e3}}}});import{JwksService as JwksService4}from"@frontmcp/auth";var RemotePrimaryAuth;var init_instance_remote_primary_auth=__esm({"libs/sdk/src/auth/instances/instance.remote-primary-auth.ts"(){"use strict";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 JwksService4;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:ProviderScope2.GLOBAL,name:"auth:jwk-service"},provide:JwksService4});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(isPublicMode(options)){return new LocalPrimaryAuth(scope,providers,options)}if(isStaticMode(options)){return new LocalPrimaryAuth(scope,providers,options)}if(isTransparentMode(options)){return new RemotePrimaryAuth(scope,providers,options)}if(isOrchestratedMode(options)){if(isOrchestratedLocal(options)){return new LocalPrimaryAuth(scope,providers,options)}else{return new LocalPrimaryAuth(scope,providers,options)}}const defaultOptions=parseAuthOptions({mode:"public"});return new LocalPrimaryAuth(scope,providers,defaultOptions)}}});var ui_option_warnings_exports={};__export(ui_option_warnings_exports,{describeIgnoredUiOptions:()=>describeIgnoredUiOptions,describeServingModeDefault:()=>describeServingModeDefault});import{validateCSPDomain as validateCSPDomain2}from"@frontmcp/uipack/shell";function describeIgnoredUiOptions(toolName,ui){if(!ui)return[];const messages=[];const ignored=IGNORED_UI_OPTIONS.filter(key=>ui[key]!==void 0);if(ignored.length>0){messages.push(`Tool "${toolName}": \`ui.${ignored.join("`, `ui.")}\` ${ignored.length===1?"is":"are"} accepted but not used yet, so ${ignored.length===1?"it has":"they have"} no effect.`)}const mode=ui["servingMode"];if(UNSUPPORTED_SERVING_MODES.includes(mode)){messages.push(`Tool "${toolName}": \`ui.servingMode: '${String(mode)}'\` is not implemented; the widget is served inline, as with \`servingMode: 'inline'\`.`)}messages.push(...describeInvalidCspOrigins(toolName,ui["csp"]));if(mode==="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(UNSUPPORTED_SERVING_MODES.includes(mode)){return[`${owner}: \`ui.servingMode: '${String(mode)}'\` is not implemented; tools that inherit it are served inline, as with \`servingMode: 'inline'\`.`]}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"&&validateCSPDomain2(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 IGNORED_UI_OPTIONS,UNSUPPORTED_SERVING_MODES;var init_ui_option_warnings=__esm({"libs/sdk/src/tool/ui/ui-option-warnings.ts"(){"use strict";IGNORED_UI_OPTIONS=["contentSecurity","hydrate","runtimeOptions","mdxComponents","bundlingMode","uiType","htmlResponsePrefix"];UNSUPPORTED_SERVING_MODES=["direct-url","custom-url"]}});import"reflect-metadata";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 RESOURCE_DECORATOR_BASENAMES,Resource,_ResourceTemplate;var init_resource_decorator=__esm({"libs/sdk/src/common/decorators/resource.decorator.ts"(){"use strict";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}});import{escapeHtml as escapeHtml6}from"@frontmcp/uipack/utils";import{createTemplateHelpers}from"@frontmcp/uipack/shell";var init_template_helpers=__esm({"libs/sdk/src/tool/ui/template-helpers.ts"(){"use strict"}});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>
467
+ </html>`}htmlPage(markup,status=200){return httpRespond.html(markup,status,builtInAuthPageHeaders4())}getStateValidation(){const authOptions=this.scope.auth?.options;if(authOptions&&isOrchestratedMode(authOptions)){return authOptions.federatedAuth?.stateValidation??"strict"}return"strict"}};__decorateClass([Stage45("checkIpFilter")],OauthProviderCallbackFlow.prototype,"checkIpFilter",1);__decorateClass([Stage45("acquireQuota")],OauthProviderCallbackFlow.prototype,"acquireQuota",1);__decorateClass([Stage45("parseInput")],OauthProviderCallbackFlow.prototype,"parseInput",1);__decorateClass([Stage45("handleConsentSubmission")],OauthProviderCallbackFlow.prototype,"handleConsentSubmission",1);__decorateClass([Stage45("loadFederatedSession")],OauthProviderCallbackFlow.prototype,"loadFederatedSession",1);__decorateClass([Stage45("validateProviderCallback")],OauthProviderCallbackFlow.prototype,"validateProviderCallback",1);__decorateClass([Stage45("exchangeProviderCode")],OauthProviderCallbackFlow.prototype,"exchangeProviderCode",1);__decorateClass([Stage45("storeProviderTokens")],OauthProviderCallbackFlow.prototype,"storeProviderTokens",1);__decorateClass([Stage45("handleNextProviderOrComplete")],OauthProviderCallbackFlow.prototype,"handleNextProviderOrComplete",1);OauthProviderCallbackFlow=__decorateClass([FrontMcpFlow({name:name45,plan:plan45,inputSchema:inputSchema38,outputSchema:outputSchema37,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});import{internalZ as z125}from"@frontmcp/lazy-zod";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 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";init_common();extraInputSchema=httpInputSchema;extraStateSchema=z125.object({action:z125.string().optional(),pendingAuthId:z125.string().optional(),csrf:z125.string().optional(),payload:z125.record(z125.string(),z125.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))]}});import"reflect-metadata";import{JwksService as JwksService2}from"@frontmcp/auth";import{internalZ as z126}from"@frontmcp/lazy-zod";var inputSchema39,stateSchema41,outputSchema38,plan46,name46,Stage46,WellKnownJwksFlow;var init_well_known_jwks_flow=__esm({"libs/sdk/src/auth/flows/well-known.jwks.flow.ts"(){"use strict";init_common();init_auth_internal_errors();inputSchema39=httpInputSchema;stateSchema41=z126.object({isOrchestrated:z126.boolean()});outputSchema38=z126.union([HttpJsonSchema,HttpTextSchema,HttpRedirectSchema]);plan46={pre:["checkIpFilter","acquireQuota","parseInput","validateInput"],execute:["collectData"]};name46="well-known.jwks";Stage46=StageHookOf(name46);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(JwksService2);if(isOrchestrated){const keysDoc=await jwksSvc.getPublicJwks();if(!keysDoc?.keys||!Array.isArray(keysDoc.keys)){throw new OrchestratorJwksNotAvailableError}this.respond(httpRespond.json(keysDoc));return}const options=this.scope.auth.options;if(options&&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([Stage46("checkIpFilter")],WellKnownJwksFlow.prototype,"checkIpFilter",1);__decorateClass([Stage46("acquireQuota")],WellKnownJwksFlow.prototype,"acquireQuota",1);__decorateClass([Stage46("parseInput")],WellKnownJwksFlow.prototype,"parseInput",1);__decorateClass([Stage46("collectData")],WellKnownJwksFlow.prototype,"collectData",1);WellKnownJwksFlow=__decorateClass([FrontMcpFlow({name:name46,plan:plan46,inputSchema:inputSchema39,outputSchema:outputSchema38,access:"public",middleware:{method:"GET"}})],WellKnownJwksFlow)}});import"reflect-metadata";import{advertisedScopes,trimSlash}from"@frontmcp/auth";import{internalZ as z127}from"@frontmcp/lazy-zod";import{isProduction as isProduction7}from"@frontmcp/utils";function resolveDcrEnabled(auth){if(auth&&isLocalMode(auth)){const dcr=auth.dcr;if(dcr&&typeof dcr.enabled==="boolean"){return dcr.enabled}}return!isProduction7()}var inputSchema40,AuthServerMetadataSchema,outputSchema39,wellKnownAsStateSchema,wellKnownAsPlan,name47,Stage47,WellKnownAsFlow;var init_well_known_oauth_authorization_server_flow=__esm({"libs/sdk/src/auth/flows/well-known.oauth-authorization-server.flow.ts"(){"use strict";init_common();init_sdk_errors();inputSchema40=httpInputSchema;AuthServerMetadataSchema=z127.object({kind:z127.literal("json"),status:z127.literal(200),contentType:z127.literal("application/json; charset=utf-8"),headers:z127.record(z127.string(),z127.string()).optional(),body:z127.object({issuer:z127.string().min(1),authorization_endpoint:z127.string().min(1),token_endpoint:z127.string().min(1),userinfo_endpoint:z127.string().min(1).optional(),jwks_uri:z127.string().min(1),registration_endpoint:z127.string().min(1).optional(),token_endpoint_auth_methods_supported:z127.array(z127.enum(["client_secret_basic","client_secret_post","private_key_jwt"])).optional(),response_types_supported:z127.array(z127.enum(["code"])).default(["code"]),grant_types_supported:z127.array(z127.enum(["authorization_code","refresh_token"])).default(["authorization_code","refresh_token"]),scopes_supported:z127.array(z127.string()).default(["openid","profile","email"]),code_challenge_methods_supported:z127.array(z127.enum(["S256"])).default(["S256"])}).passthrough()});outputSchema39=z127.union([AuthServerMetadataSchema,HttpRedirectSchema,HttpTextSchema]);wellKnownAsStateSchema=z127.object({baseUrl:z127.string().min(1),issuer:z127.string().min(1).optional(),oauthBaseUrl:z127.string().min(1),scopesSupported:z127.array(z127.string()).default(["openid","profile","email"]),tokenEndpointAuthMethods:z127.array(z127.enum(["client_secret_basic","client_secret_post","private_key_jwt"])).default(["client_secret_basic","client_secret_post"]),dcrEnabled:z127.boolean().default(true),isOrchestrated:z127.boolean(),cimdEnabled:z127.boolean().default(true)});wellKnownAsPlan={pre:["checkIpFilter","acquireQuota","parseInput"],execute:["collectData"]};name47="well-known.oauth-authorization-server";Stage47=StageHookOf(name47);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);let cimdEnabled=true;if(metadata.auth&&isOrchestratedMode(metadata.auth)){cimdEnabled=metadata.auth.cimd?.enabled??true}this.state.set(wellKnownAsStateSchema.parse({baseUrl,issuer,oauthBaseUrl,scopesSupported:metadata.auth&&isOrchestratedMode(metadata.auth)?advertisedScopes(metadata.auth.allowedScopes):[],tokenEndpointAuthMethods:[],dcrEnabled:resolveDcrEnabled(metadata.auth),isOrchestrated:metadata.auth?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,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||!isTransparentMode(authOptions)){this.respond(httpRespond.notFound());return}this.respond(httpRespond.redirect(`${trimSlash(this.scope.auth.issuer)}/.well-known/oauth-authorization-server`))}};__decorateClass([Stage47("checkIpFilter")],WellKnownAsFlow.prototype,"checkIpFilter",1);__decorateClass([Stage47("acquireQuota")],WellKnownAsFlow.prototype,"acquireQuota",1);__decorateClass([Stage47("parseInput")],WellKnownAsFlow.prototype,"parseInput",1);__decorateClass([Stage47("collectData")],WellKnownAsFlow.prototype,"collectData",1);WellKnownAsFlow=__decorateClass([FrontMcpFlow({name:name47,plan:wellKnownAsPlan,inputSchema:inputSchema40,outputSchema:outputSchema39,access:"public",middleware:{method:"GET"}})],WellKnownAsFlow)}});import"reflect-metadata";import{resourceScopesFor}from"@frontmcp/auth";import{internalZ as z128}from"@frontmcp/lazy-zod";var inputSchema41,stateSchema42,outputSchema40,plan47,name48,Stage48,WellKnownPrmFlow;var init_well_known_prm_flow=__esm({"libs/sdk/src/auth/flows/well-known.prm.flow.ts"(){"use strict";init_common();init_sdk_errors();inputSchema41=httpInputSchema;stateSchema42=z128.object({resource:z128.string().min(1),baseUrl:z128.string().min(1),authorizationServer:z128.string().min(1).optional(),scopesSupported:z128.array(z128.string()),isOrchestrated:z128.boolean()});outputSchema40=HttpJsonSchema.extend({body:z128.object({resource:z128.string().min(1),authorization_servers:z128.array(z128.string().min(1)).min(1).optional(),scopes_supported:z128.array(z128.string()).optional(),bearer_methods_supported:z128.array(z128.string()).default(["header"])}).passthrough()});plan47={pre:["checkIpFilter","acquireQuota","parseInput"],execute:["collectData"],post:["validateOutput"]};name48="well-known.oauth-protected-resource";Stage48=StageHookOf(name48);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 authorizationServer=scope.auth?.issuerFor?.(request2)??baseUrl;const authOptions=scope.auth?.options??scope.metadata.auth;const granted=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(stateSchema42.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([Stage48("checkIpFilter")],WellKnownPrmFlow.prototype,"checkIpFilter",1);__decorateClass([Stage48("acquireQuota")],WellKnownPrmFlow.prototype,"acquireQuota",1);__decorateClass([Stage48("parseInput")],WellKnownPrmFlow.prototype,"parseInput",1);__decorateClass([Stage48("collectData")],WellKnownPrmFlow.prototype,"collectData",1);WellKnownPrmFlow=__decorateClass([FrontMcpFlow({name:name48,plan:plan47,inputSchema:inputSchema41,outputSchema:outputSchema40,access:"public",middleware:{method:"GET"}})],WellKnownPrmFlow)}});import{isAnonymousSubject as isAnonymousSubject8}from"@frontmcp/auth";function sessionScopeIdentity(ctx){const verified=ctx.verifiedSessionId;if(verified)return verified;const authInfo=ctx.authInfo??{};const extraUser=authInfo.extra?.["user"];const principal=[authInfo.user?.sub,extraUser?.sub,authInfo.clientId].find(candidate=>!isAnonymousSubject8(candidate));return principal?`principal:${principal}`:void 0}var init_session_scope_identity=__esm({"libs/sdk/src/auth/session-scope-identity.ts"(){"use strict"}});import{SECURE_STORE_ACCESSOR,SecureStoreAccessorImpl}from"@frontmcp/auth";import{ProviderScope as ProviderScope9}from"@frontmcp/di";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:ProviderScope9.GLOBAL,name:"SecureStoreBackend"};const accessorProvider={provide:SECURE_STORE_ACCESSOR,inject:()=>[FRONTMCP_CONTEXT,FrontMcpLogger],useFactory:(ctx,logger)=>new SecureStoreAccessorImpl({backend,scope,resolveSub:()=>resolveRequestSub(ctx),resolveSessionId:()=>resolveRequestSessionId(ctx),ttlMs,logger:logger.child("SecureStore")}),scope:ProviderScope9.CONTEXT,name:"SecureStoreAccessor"};return[backendProvider,accessorProvider]}var SECURE_STORE_BACKEND;var init_secure_store_providers=__esm({"libs/sdk/src/auth/secure-store/secure-store.providers.ts"(){"use strict";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")}});import{SECURE_STORE_ACCESSOR as SECURE_STORE_ACCESSOR2}from"@frontmcp/auth";var secureStoreContextExtension;var init_secure_store_context_extension=__esm({"libs/sdk/src/auth/secure-store/secure-store.context-extension.ts"(){"use strict";secureStoreContextExtension={property:"secureStore",token:SECURE_STORE_ACCESSOR2,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()}});import{createSecureStore,createTokenStorageAdapter,DcrClientRegistry,deriveAuthorizationId as deriveAuthorizationId2,InMemoryAuthorizationStore,InMemoryConsentStore,InMemoryFederatedAuthSessionStore,InMemoryOrchestratedTokenStore,isPersistentTokenStorage,isRedisTokenStorage,isSqliteTokenStorage,JwksService as JwksService3,SessionCredentialVault,StorageAuthorizationStore,StorageConsentStore,StorageFederatedAuthSessionStore,StorageOrchestratedTokenStore,TokenNotAvailableError as TokenNotAvailableError2,verifyPkce}from"@frontmcp/auth";import{getEnv as getEnv17,isProduction as isProduction8,MemoryStorageAdapter,randomBytes as randomBytes11,randomUUID as randomUUID29,StorageNotSupportedError}from"@frontmcp/utils";function loadJose(){jose??=importWithRequireFallback(()=>import("jose"),()=>__require("jose")).catch(error=>{jose=void 0;throw error});return jose}function getDefaultNoAuthSecret(){if(!defaultNoAuthSecret){defaultNoAuthSecret=randomBytes11(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 StorageNotSupportedError}function originOf2(value){try{const origin=new URL(value).origin;return origin==="null"?void 0:origin}catch{return void 0}}var 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";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=getEnv17("FRONTMCP_PUBLIC_HOST")?.trim()||"localhost";this.issuer=this.deriveIssuer(options);this.publicHostPinned=!!getEnv17("FRONTMCP_PUBLIC_HOST")?.trim();const jwtSecret=getEnv17("JWT_SECRET");const hasJwtSecret=!!jwtSecret?.trim();if(hasJwtSecret&&jwtSecret){const encoded=new TextEncoder().encode(jwtSecret);if(encoded.length<MIN_HS256_SECRET_BYTES){if(isProduction8())throw new 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(isProduction8()&&isOrchestratedMode(options)){throw new JwtSecretRequiredError(options.mode)}else{if(!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.tokenStorage=this.readTokenStorage(options);this.authorizationStoreImpl=new InMemoryAuthorizationStore;this.federatedSessionStoreImpl=new InMemoryFederatedAuthSessionStore;this.orchestratedTokenStoreImpl=new InMemoryOrchestratedTokenStore({encryptionKey:this.secret,refreshSkewMs:this.providerRefreshSkewMs()});this.consentStoreImpl=new InMemoryConsentStore;this.scope.onDispose(()=>this.releaseResources());this.dcrClientRegistryImpl=new DcrClientRegistry(this.getDcrConfig()??{});if(isOrchestratedMode(options)){const cimdConfig=options.cimd;this.cimdService=new CimdService(this.logger,cimdConfig)}this.ready=this.initialize()}scope;providers;host;port;issuer;publicHostPinned;keys=[];secret;logger;jwks=new JwksService3;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(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!isProduction8()}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}`}configuredIssuer(options){const configured=isPublicMode(options)?options.issuer: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||!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}async initializeStores(){if(!isPersistentTokenStorage(this.tokenStorage)){return}try{const adapter=await createTokenStorageAdapter(this.tokenStorage);this.storageAdapter=adapter;this.storageClosers.push(()=>adapter.disconnect());this.disposeInMemoryStores();this.authorizationStoreImpl=new StorageAuthorizationStore(adapter);this.federatedSessionStoreImpl=new StorageFederatedAuthSessionStore(adapter);this.orchestratedTokenStoreImpl=new StorageOrchestratedTokenStore(adapter,{encryptionKey:this.secret,refreshSkewMs:this.providerRefreshSkewMs()});this.consentStoreImpl=new StorageConsentStore(adapter);const backend=isSqliteTokenStorage(this.tokenStorage)?"sqlite":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){const key=`incremental-ticket:${jti}`;const nonce=randomUUID29();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(`Incremental ticket replay guard unavailable: ${String(error)}`);return false}this.logger.warn("Incremental ticket 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(`Incremental ticket replay guard unavailable: ${String(fallbackError)}`);return false}}try{return await storage.get(key)===nonce}catch(error){this.logger.warn(`Incremental ticket replay guard unavailable: ${String(error)}`);return false}}getTicketReplayStorage(){if(!this.ticketReplayStorage){if(this.storageAdapter){this.ticketReplayStorage=Promise.resolve(this.storageAdapter)}else{this.logger.debug("Incremental ticket 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 MemoryStorageAdapter;await memory.connect();this.storageClosers.push(()=>memory.disconnect());return memory})();this.ticketReplayStorage=pending;return pending}async initializeCredentialVault(){if(isPublicMode(this.options)){return}let storage;if(this.storageAdapter){storage=this.storageAdapter}else{const memory=new MemoryStorageAdapter;await memory.connect();this.storageClosers.push(()=>memory.disconnect());storage=memory}const pepper=getEnv17("VAULT_SECRET")??getEnv17("JWT_SECRET")??void 0;this.credentialVaultImpl=new 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(isPublicMode(this.options)){return}const config=this.readSecureStoreConfig();const reuseAdapter=this.storageAdapter&&this.secureStoreSharesTokenStorage(config)?this.storageAdapter:void 0;const pepper=getEnv17("VAULT_SECRET")??getEnv17("JWT_SECRET")??new TextDecoder().decode(this.secret);const resolved=await 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 InMemoryFederatedAuthSessionStore){this.federatedSessionStoreImpl.dispose()}if(this.orchestratedTokenStoreImpl instanceof 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 isSqliteTokenStorage(this.tokenStorage);if("redis"in config&&config.redis)return isRedisTokenStorage(this.tokenStorage);return false}async signAnonymousJwt(options={}){const{SignJWT}=await loadJose();const jwt=new SignJWT({sub:`anon:${randomUUID29()}`,anonymous:true,scope:this.anonymousScopes().join(" ")}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setIssuer(options.issuer??this.issuer).setExpirationTime(`${this.anonymousTokenTtlSeconds()}s`).setJti(randomUUID29());if(options.audience)jwt.setAudience(options.audience);return jwt.sign(this.secret)}anonymousTokenTtlSeconds(){return 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{jwtVerify}=await loadJose();const{payload,protectedHeader}=await jwtVerify(token,this.secret,{algorithms:["HS256"],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 claims2={sub:user.sub,scope:scopes.join(" ")};if(user.email)claims2["email"]=user.email;if(user.name)claims2["name"]=user.name;if(user.picture)claims2["picture"]=user.picture;if(user.roles)claims2["roles"]=user.roles;if(consentMetadata){if(consentMetadata.consentEnabled){claims2["consent"]={enabled:true,selectedTools:consentMetadata.selectedToolIds??[]}}if(consentMetadata.federatedLoginUsed){claims2["federated"]={enabled:true,selectedProviders:consentMetadata.selectedProviderIds??[],skippedProviders:consentMetadata.skippedProviderIds??[]}}if(consentMetadata.authorizedAppIds){claims2["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}claims2[key]=value}}}const{SignJWT}=await loadJose();const jwt=new SignJWT(claims2).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setIssuer(issuer??this.issuer).setExpirationTime(`${this.accessTokenTtlSeconds}s`).setJti(randomUUID29());if(audience){jwt.setAudience(audience)}return jwt.sign(this.secret)}async exchangeCode(code,clientId,redirectUri,codeVerifier,clientSecret,defaultAudience,issuer){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 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(!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)}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);this.logger.info(`Tokens issued for user: ${user.sub}`);return{access_token:accessToken,token_type:"Bearer",expires_in:this.accessTokenTtlSeconds,refresh_token:refreshTokenRecord.token,scope:codeRecord.scopes.join(" ")}}async moveProviderTokens(fromAuthorizationId,accessToken){const toAuthorizationId=deriveAuthorizationId2(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=deriveAuthorizationId2(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){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 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.initializeStores();this.registerConfiguredProviders();this.registerRemoteProvider();await this.initializeCredentialVault();await this.initializeSecureStore();this.providers.injectProvider({value:this.jwks,metadata:{scope:ProviderScope2.GLOBAL,name:"auth:jwk-service"},provide:JwksService3});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:ProviderScope2.GLOBAL,name:"auth:cimd-service"},provide: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(!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})}}registerRemoteProvider(){if(!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;if(!options.clientId){this.logger.warn(`Remote mode: no clientId configured for provider "${id}"; upstream OAuth is not available (DCR is not yet wired)`);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:options.clientId,clientSecret:options.clientSecret,scopes:options.scopes??["openid"],callbackUrl:`${this.issuer}/oauth/provider/${id}/callback`,issuer:options.provider,additionalIssuers:cfg?.additionalIssuers,verifyIssuer:cfg?.verifyIssuer})}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 claims2=await this.verifyProviderIdToken(config,idToken);const sub=typeof claims2?.["sub"]==="string"&&claims2["sub"].trim()?claims2["sub"]:void 0;if(claims2&&sub){return{sub,email:claims2["email"],name:claims2["name"],picture:claims2["picture"],claims:claims2}}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(!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 TokenNotAvailableError2(`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(!isOrchestratedMode(this.options)||this.options.refresh?.enabled===false)return 0;return(this.options.refresh?.skewSeconds??60)*1e3}}}});import{JwksService as JwksService4}from"@frontmcp/auth";var RemotePrimaryAuth;var init_instance_remote_primary_auth=__esm({"libs/sdk/src/auth/instances/instance.remote-primary-auth.ts"(){"use strict";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 JwksService4;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:ProviderScope2.GLOBAL,name:"auth:jwk-service"},provide:JwksService4});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(isPublicMode(options)){return new LocalPrimaryAuth(scope,providers,options)}if(isStaticMode(options)){return new LocalPrimaryAuth(scope,providers,options)}if(isTransparentMode(options)){return new RemotePrimaryAuth(scope,providers,options)}if(isOrchestratedMode(options)){if(isOrchestratedLocal(options)){return new LocalPrimaryAuth(scope,providers,options)}else{return new LocalPrimaryAuth(scope,providers,options)}}const defaultOptions=parseAuthOptions({mode:"public"});return new LocalPrimaryAuth(scope,providers,defaultOptions)}}});var ui_option_warnings_exports={};__export(ui_option_warnings_exports,{describeIgnoredUiOptions:()=>describeIgnoredUiOptions,describeServingModeDefault:()=>describeServingModeDefault});import{validateCSPDomain as validateCSPDomain2}from"@frontmcp/uipack/shell";function describeIgnoredUiOptions(toolName,ui){if(!ui)return[];const messages=[];const ignored=IGNORED_UI_OPTIONS.filter(key=>ui[key]!==void 0);if(ignored.length>0){messages.push(`Tool "${toolName}": \`ui.${ignored.join("`, `ui.")}\` ${ignored.length===1?"is":"are"} accepted but not used yet, so ${ignored.length===1?"it has":"they have"} no effect.`)}const mode=ui["servingMode"];if(UNSUPPORTED_SERVING_MODES.includes(mode)){messages.push(`Tool "${toolName}": \`ui.servingMode: '${String(mode)}'\` is not implemented; the widget is served inline, as with \`servingMode: 'inline'\`.`)}messages.push(...describeInvalidCspOrigins(toolName,ui["csp"]));if(mode==="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(UNSUPPORTED_SERVING_MODES.includes(mode)){return[`${owner}: \`ui.servingMode: '${String(mode)}'\` is not implemented; tools that inherit it are served inline, as with \`servingMode: 'inline'\`.`]}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"&&validateCSPDomain2(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 IGNORED_UI_OPTIONS,UNSUPPORTED_SERVING_MODES;var init_ui_option_warnings=__esm({"libs/sdk/src/tool/ui/ui-option-warnings.ts"(){"use strict";IGNORED_UI_OPTIONS=["contentSecurity","hydrate","runtimeOptions","mdxComponents","bundlingMode","uiType","htmlResponsePrefix"];UNSUPPORTED_SERVING_MODES=["direct-url","custom-url"]}});import"reflect-metadata";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 RESOURCE_DECORATOR_BASENAMES,Resource,_ResourceTemplate;var init_resource_decorator=__esm({"libs/sdk/src/common/decorators/resource.decorator.ts"(){"use strict";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}});import{escapeHtml as escapeHtml6}from"@frontmcp/uipack/utils";import{createTemplateHelpers}from"@frontmcp/uipack/shell";var init_template_helpers=__esm({"libs/sdk/src/tool/ui/template-helpers.ts"(){"use strict"}});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>
468
468
  <html>
469
469
  <head><title>Widget Placeholder</title></head>
470
470
  <body>
471
471
  <p>Widget for tool: ${escapeHtml6(String(params["toolName"]||"unknown"))}</p>
472
472
  <p>This is a placeholder. The actual widget HTML is served from the ToolUIRegistry cache.</p>
473
473
  </body>
474
- </html>`}]}})}});var authorities_engine_exports={};__export(authorities_engine_exports,{authoritiesFromConfig:()=>authoritiesFromConfig,createAuthoritiesEngine:()=>createAuthoritiesEngine});import{AuthoritiesContextBuilder,AuthoritiesEngine,AuthoritiesEvaluatorRegistry,AuthoritiesProfileRegistry}from"@frontmcp/auth";function createAuthoritiesEngine(config){const profileRegistry=new AuthoritiesProfileRegistry;if(config["profiles"]){profileRegistry.registerAll(config["profiles"])}const evaluatorRegistry=new AuthoritiesEvaluatorRegistry;if(config["evaluators"]){evaluatorRegistry.registerAll(config["evaluators"])}return new AuthoritiesEngine(profileRegistry,evaluatorRegistry)}function authoritiesFromConfig(config){return{engine:createAuthoritiesEngine(config),contextBuilder:new AuthoritiesContextBuilder({claimsMapping:config["claimsMapping"],claimsResolver:config["claimsResolver"],relationshipResolver:config["relationshipResolver"]}),scopeMapping:config["scopeMapping"]}}var init_authorities_engine=__esm({"libs/sdk/src/front-mcp/authorities-engine.ts"(){"use strict"}});var send_elicitation_result_tool_exports={};__export(send_elicitation_result_tool_exports,{SendElicitationResultTool:()=>SendElicitationResultTool});import{internalZ as z129}from"@frontmcp/lazy-zod";var inputSchema42,SendElicitationResultTool;var init_send_elicitation_result_tool=__esm({"libs/sdk/src/elicitation/send-elicitation-result.tool.ts"(){"use strict";init_common();init_call_surface();init_errors();init_fallback_helper();inputSchema42={elicitId:z129.string().describe("The elicitation ID from the pending request"),action:z129.enum(["accept","cancel","decline"]).describe("User action: accept (submit), cancel, or decline"),content:z129.unknown().optional().describe("User response content (required for accept action)")};SendElicitationResultTool=class extends ToolContext{async execute(input){const{elicitId,action,content}=input;this.logger.info("sendElicitationResult: processing",{elicitId,action});const store=this.scope.elicitationStore;if(!store){this.logger.error("sendElicitationResult: scope or elicitationStore not available");return{content:[{type:"text",text:"Error: Elicitation store not available. Server may not be properly configured."}],isError:true}}const pending=await store.getPendingFallback(elicitId);if(!pending){this.logger.warn("sendElicitationResult: no pending elicitation found",{elicitId});return{content:[{type:"text",text:`Error: No pending elicitation found for ID: ${elicitId}. The request may have expired or already been processed.`}],isError:true}}const caller=resolveElicitationOwner(this.tryGetContext());if(!pending.owner||pending.owner!==caller){this.logger.warn("sendElicitationResult: refused a result from a caller the elicitation was not asked of",{elicitId});throw new ElicitationNotOwnedError(elicitId)}if(Date.now()>pending.expiresAt){await store.deletePendingFallback(elicitId);this.logger.warn("sendElicitationResult: elicitation expired",{elicitId});return{content:[{type:"text",text:`Error: Elicitation request has expired. Please try the original operation again.`}],isError:true}}const elicitResult={status:action,...action==="accept"&&content!==void 0&&{content}};await store.setResolvedResult(elicitId,elicitResult,pending.sessionId);await store.deletePendingFallback(elicitId);this.logger.info("sendElicitationResult: re-invoking original tool",{elicitId,toolName:pending.toolName});const ctx=this.tryGetContext();if(ctx){ctx.setPreResolvedElicitResult(elicitResult)}try{const toolResult=await this.scope.runFlowForOutput("tools:call-tool",{request:{method:"tools/call",params:{name:pending.toolName,arguments:pending.toolInput}},ctx:{authInfo:this.authInfo,requestId:this.tryGetContext()?.requestId??this.runId,surface:getCallSurface(),...this.signal?{signal:this.signal}:{}}});this.logger.info("sendElicitationResult: original tool completed",{elicitId,toolName:pending.toolName});await store.publishFallbackResult(elicitId,pending.sessionId,{success:true,result:toolResult});await store.deleteResolvedResult(elicitId);return toolResult}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);await store.publishFallbackResult(elicitId,pending.sessionId,{success:false,error:errorMessage2});await store.deleteResolvedResult(elicitId);this.logger.error("sendElicitationResult: original tool failed",{elicitId,toolName:pending.toolName,error:errorMessage2});return{content:[{type:"text",text:`Error re-invoking ${pending.toolName}: ${errorMessage2}`}],isError:true}}}};SendElicitationResultTool=__decorateClass([Tool({name:"sendElicitationResult",description:'Submit user response for a pending elicitation request. Use this after collecting user input for a tool that requested elicitation. Actions: "accept" (user submitted response), "cancel" (user cancelled), "decline" (user declined to answer).',inputSchema:inputSchema42,hideFromDiscovery:true})],SendElicitationResultTool)}});import"reflect-metadata";import{createGuardManager}from"@frontmcp/guard";import{createRedisClient as createRedisClient3,getEnvFlag,getMachineId as getMachineId5,getRuntimeContext as getRuntimeContext22,isEdgeRuntime,mkdir as mkdir2}from"@frontmcp/utils";var SCOPE_NON_DISPATCHABLE_FLOWS,Scope;var init_scope_instance=__esm({"libs/sdk/src/scope/scope.instance.ts"(){"use strict";init_adapter_registry();init_agent_registry();init_app_registry();init_auth_registry();init_direct_public_auth();init_channel_utils();init_common();init_sqlite();init_forward_headers_utils();init_path_utils();init_complete_flow();init_context();init_metadata_utils();init_errors();init_plugin_errors();init_flow_registry();init_authorities_rules_check();init_detached_job_flag();init_direct_only_flag();init_hook_order();init_hook_registry();init_hooks_utils();init_job_utils();init_set_level_flow();init_instructions_budget_check();init_notification();init_offload_service();init_enforced_metadata_check();init_plugin_registry();init_prompt_registry();init_provider_registry();init_materialized_resources();init_resource_registry();init_skill_validation_error();init_skill_scope_helper();init_skill_registry();init_live_surface();init_task_backend_utils();init_tool_output_policy();init_tool_instance();init_tool_registry();init_tool_utils();init_serving_mode_default();init_ui_shared();init_request_state();init_session_mode_check();init_browser_stores();init_dev_events_observability();init_server_entries_helper();init_startup_report_helper();SCOPE_NON_DISPATCHABLE_FLOWS=new Set(["http:request"]);Scope=class _Scope extends ScopeEntry{id;globalProviders;logger;scopeProviders;scopeAuth;scopeFlows;scopeApps;scopeHooks;scopeTools;scopeResources;scopePrompts;scopeAgents;scopeSkills;scopePlugins;transportService;notificationService;liveSurface;haRedisClient;haSubscriberClient;transportBus;sessionRelayHandle;toolUIRegistry;authUiRegistry;entryPath;routeBase;orchestrated=false;server;registeredHttpRoutes=[];httpRouteRegistrar={registerRoute:(method,path4,handler)=>{this.registeredHttpRoutes.push({method,path:path4,handler});return this.server.registerRoute(method,path4,handler)}};_elicitationStore;elicitationBackendType;_persistentQuestions;_taskStore;taskBackendType;_taskRegistry;_skillSession;_eventStore;_scopeJobs;_scopeWorkflows;_jobExecutionManager;_jobStateStore;_jobDefinitionStore;_rateLimitManager;_publicAccessGuard;lateGuardSetup=Promise.resolve();_authoritiesEngine;_authoritiesContextBuilder;_authoritiesScopeMapping;scopeAdapters;_scopeChannels;_channelNotificationService;_channelEventBus;_channelTeardown;_healthService;cliMode;directOnly;constructor(rec,globalProviders){super(rec,rec.provide);this.id=rec.metadata.id;this.logger=globalProviders.get(FrontMcpLogger).child("FrontMcp.MultiAppScope");this.globalProviders=globalProviders;this.server=this.globalProviders.get(FrontMcpServer);this.entryPath=resolveEntryPath(rec.metadata.http?.entryPath);if(rec.kind==="SPLIT_BY_APP"){this.routeBase=`/${rec.metadata.id}`}else{this.routeBase=""}this.cliMode=!!rec.metadata["__cliMode"];this.directOnly=isDirectOnly(rec.metadata);const distributedMode=rec.metadata.transport?.distributedMode;const providerCaching=rec.metadata.transport?.providerCaching;const userProviders=rec.metadata.providers??[];this.scopeProviders=new ProviderRegistry([...userProviders,...this.defaultScopeProviders],globalProviders,{distributedMode,providerCaching});this.ready=this.initialize()}async initialize(){const startedAt=Date.now();await this.scopeProviders.ready;const scopeRef={kind:"scope",id:this.id,ref:_Scope};const scopeProviders=this.scopeProviders;const perf=getEnvFlag("FRONTMCP_PERF");const t0=perf?performance.now():0;const mark=perf?label=>this.logger.info(`[PERF] ${label}: ${(performance.now()-t0).toFixed(1)}ms`):()=>{};await refuseStoresInBrowser(this.metadata);const httpServing=this.directOnly?void 0:await Promise.resolve().then(()=>(init_http_scope_helper(),http_scope_helper_exports));const createPrimaryAuth2=await this.primaryAuthFactory();this.scopeHooks=new HookRegistry(scopeProviders,[]);this.scopeFlows=new FlowRegistry(scopeProviders,httpServing?[httpServing.HttpRouteFlow,httpServing.HttpRequestFlow,httpServing.HttpIpFilterFlow]:[]);this.scopeAuth=new AuthRegistry(this,scopeProviders,[],scopeRef,this.metadata.auth,createPrimaryAuth2);this.scopeApps=new AppRegistry(this.scopeProviders,this.metadata.apps,scopeRef);this.logger.info(`Initializing ${this.metadata.apps.length} app(s)...`);const transportConfig=this.metadata.transport;const isDistributed=getRuntimeContext22().deployment==="distributed";if(isDistributed&&this.metadata.redis&&!this.cliMode&&!this.directOnly){const ha=await Promise.resolve().then(()=>(init_ha(),ha_exports));try{const haRedis=this.createHaRedisClient();const haSubscriber=this.createHaRedisClient("ha-subscriber");this.haManager=ha.HaManager.create({redis:haRedis,pubsubPublisher:haRedis,pubsubSubscriber:haSubscriber,nodeId:getMachineId5(),config:ha.resolveHaConfigFromEnv(),logger:this.logger});await this.haManager.start();this.logger.info("[HA] Manager started for distributed deployment")}catch(err){this.logger.warn("[HA] Failed to start HA manager \u2014 running without HA",{error:err});this.haManager=void 0;await this.closeHaRedisClient()}}let transportBus;if(this.haManager&&this.haRedisClient&&isDistributed){const bus=await Promise.resolve().then(()=>(init_bus(),bus_exports));const haConfig=this.haManager.getConfig();transportBus=new bus.RedisTransportBus(this.haRedisClient,getMachineId5(),{haKeyPrefix:haConfig.redisKeyPrefix,retryAfterSeconds:Math.ceil(haConfig.heartbeatTtlMs/1e3),logger:this.logger});this.transportBus=transportBus;this.logger.info("[HA] Transport bus created for distributed session routing")}const resolvedTopLevelSqlite=await this.resolveTopLevelSqlite();let effectivePersistence=transportConfig?.persistence;if(effectivePersistence===void 0&&resolvedTopLevelSqlite){effectivePersistence={sqlite:resolvedTopLevelSqlite}}if(httpServing){const service=new httpServing.TransportService(this,effectivePersistence,transportBus);this.transportService=service;this.onDispose(()=>service.destroy());httpServing.loadStreamableHttpTransportOnStart(this)}warnIfRequestStateKeyNotShared({logger:this.logger,metadata:this.metadata});warnIfSessionModeIgnored({logger:this.logger,transport:transportConfig,session:this.metadata.session});const transportService=this.transportService;if(this.haManager&&isDistributed&&transportService?.getBackendKind()==="redis"){this.haManager.startOrphanScanner({sessionKeyPrefix:transportService.getSessionKeyPrefix(),onOrphan:(sessionId,previousNodeId,session)=>transportService.adoptClaimedSession(sessionId,previousNodeId,session)})}if(getRuntimeContext22().deployment==="serverless"){const protocolCfg=transportConfig?.protocol;const hasSSE=typeof protocolCfg==="string"?protocolCfg!=="stateless-api":protocolCfg?.sse===true;if(hasSSE){this.logger.warn('[Deployment] SSE transport is not supported in serverless deployments. Consider using protocol: "stateless-api" for serverless targets.')}}const effectiveEventStoreConfig=transportConfig?.eventStore??(isDistributed&&this.metadata.redis&&!this.cliMode&&!this.directOnly?{enabled:true,provider:"redis",redis:this.metadata.redis}:void 0);if(effectiveEventStoreConfig?.enabled&&!this.cliMode&&!this.directOnly){const{createEventStore:createEventStore2}=await Promise.resolve().then(()=>(init_event_stores(),event_stores_exports));const{eventStore}=createEventStore2(effectiveEventStoreConfig,this.logger);this._eventStore=eventStore;this.logger.info("EventStore initialized for SSE resumability",{provider:effectiveEventStoreConfig.provider??"memory",autoEnabled:!transportConfig?.eventStore&&isDistributed})}const elicitationEnabled=this.metadata.elicitation?.enabled===true&&!this.cliMode;const elicitationPromise=elicitationEnabled?(async()=>{const inheritedRedis=this.metadata.elicitation?.redis??this.metadata.redis;const elicitationInMemory=this.metadata.elicitation?.store===false;const elicitationRedis=elicitationInMemory?void 0:inheritedRedis;const elicitationSqlite=elicitationInMemory||elicitationRedis?void 0:resolvedTopLevelSqlite;const persistent=this.metadata.elicitation?.persistent;const questionsHelper=persistent?await Promise.resolve().then(()=>(init_question_scope_helper(),question_scope_helper_exports)):void 0;const onEdgeRuntime2=isEdgeRuntime();const questionsStorage=questionsHelper?.persistentQuestionsSettings(persistent,onEdgeRuntime2).storage;const questionsRedis=!elicitationInMemory&&!elicitationRedis&&questionsStorage?.type==="redis"?questionsStorage:void 0;const{createElicitationStore:createElicitationStore2}=await Promise.resolve().then(()=>(init_elicitation_store_factory(),elicitation_store_factory_exports));const{store:elicitStore,type:elicitType,storage:elicitStorage}=await createElicitationStore2({redis:elicitationRedis,storage:elicitationInMemory?{type:"memory"}:questionsRedis,sqlite:elicitationSqlite,keyPrefix:elicitationRedis?.keyPrefix??"mcp:elicit:",logger:this.logger,isEdgeRuntime:onEdgeRuntime2});this._elicitationStore=elicitStore;this.elicitationBackendType=elicitType;if(elicitStorage){this.onDispose(async()=>{await elicitStore.destroy?.();await elicitStorage.disconnect()})}if(questionsHelper){const questions=await questionsHelper.openPersistentQuestions({persistent,serverName:this.metadata.info.name,redis:inheritedRedis,sqlite:resolvedTopLevelSqlite,onEdgeRuntime:onEdgeRuntime2,logger:this.logger});this._persistentQuestions=questions;if(questions)this.onDispose(()=>questions.store.close())}})():void 0;const tasksConfig=this.metadata.tasks;const tasksInMemory=tasksConfig?.store===false;const tasksMemoryStorage=tasksInMemory?{type:"memory"}:void 0;const serverRedisForTasks=tasksInMemory?void 0:this.metadata.redis;const serverSqliteForTasks=tasksInMemory?void 0:resolvedTopLevelSqlite;const tasksExplicitlyDisabled=tasksConfig?.enabled===false;const tasksExplicitlyEnabled=tasksConfig?.enabled===true;const isTaskWorker=!!this.metadata["__taskWorkerMode"];const hasPersistentBackend=Boolean(tasksConfig?.sqlite||tasksConfig?.redis||serverRedisForTasks||serverSqliteForTasks);const tasksEnabledForCli=this.cliMode&&hasPersistentBackend;const hasDistributedTaskBackend=Boolean(tasksConfig?.redis??serverRedisForTasks);const onEdgeRuntime=isEdgeRuntime();const tasksUnavailableOnEdge=onEdgeRuntime&&!hasDistributedTaskBackend&&!tasksExplicitlyEnabled;if(tasksUnavailableOnEdge){this.logger.info("[tasks] Background tasks are unavailable on this edge/serverless runtime: the in-process runner cannot continue past the HTTP response, and an in-memory store is not shared between isolates. Serving without tasks. Configure `tasks.redis` (Upstash Redis over HTTP works on Workers) to enable them.")}const gateTasksRedis=tasksConfig?.redis??serverRedisForTasks;const tasksUseSqlite=Boolean(tasksConfig?.sqlite??(gateTasksRedis?void 0:serverSqliteForTasks));const tasksUnavailableOnVercelKv=!tasksExplicitlyEnabled&&!tasksUseSqlite&&resolvesToVercelKvTaskBackend(gateTasksRedis,tasksMemoryStorage);if(tasksUnavailableOnVercelKv&&!tasksExplicitlyDisabled){this.logger.warn("[tasks] Background tasks are disabled: Vercel KV has no pub/sub, which task results and cancellation require. Serving without tasks. Configure `tasks.redis` with Redis or Upstash to enable them.")}const shouldInitTasks=!tasksExplicitlyDisabled&&!tasksUnavailableOnEdge&&!tasksUnavailableOnVercelKv&&(!this.cliMode||tasksEnabledForCli||isTaskWorker);const useCliRunner=!isTaskWorker&&tasksConfig?.runner==="cli";let taskModule;let cliTaskRunner;const tasksPromise=shouldInitTasks?(async()=>{taskModule=await Promise.resolve().then(()=>(init_task_scope_runtime(),task_scope_runtime_exports));if(useCliRunner)cliTaskRunner=(await Promise.resolve().then(()=>(init_cli_task_runner(),cli_task_runner_exports))).CliTaskRunner;const tasksRedis=tasksConfig?.redis??serverRedisForTasks;const tasksSqlite=tasksConfig?.sqlite??(tasksRedis?void 0:serverSqliteForTasks);const onEdge=onEdgeRuntime;if(onEdge){const msg="[tasks] Background tasks are enabled on an edge/serverless runtime. The in-process runner cannot continue past the HTTP response on this platform \u2014 task bodies will not execute. Run on a long-lived Node process, or set `tasks.enabled: false`.";if(tasksConfig?.strict){throw new Error(msg+" (tasks.strict: true refuses startup)")}this.logger.warn(msg)}const{store:taskStore,type:taskType,storage:taskStorage}=await taskModule.createTaskStore({storage:tasksMemoryStorage,redis:tasksRedis,sqlite:tasksSqlite,keyPrefix:tasksConfig?.keyPrefix??"mcp:task:",logger:this.logger,isEdgeRuntime:onEdge});this._taskStore=taskStore;this.onDispose(async()=>{await taskStore.destroy?.();await taskStorage?.disconnect()});this.taskBackendType=taskType;this._taskRegistry=new taskModule.TaskRegistry({enabled:tasksConfig?.enabled,defaultTtlMs:tasksConfig?.defaultTtlMs,maxTtlMs:tasksConfig?.maxTtlMs,defaultPollIntervalMs:tasksConfig?.defaultPollIntervalMs,maxConcurrentPerSession:tasksConfig?.maxConcurrentPerSession,keyPrefix:tasksConfig?.keyPrefix,strict:tasksConfig?.strict,sqlite:tasksConfig?.sqlite,cliRunnerCommand:tasksConfig?.cliRunnerCommand},this.logger)})():void 0;const installTaskRunner=shouldInitTasks?()=>{const tasks=taskModule;if(!this._taskStore||!this._taskRegistry||!tasks)return;if(useCliRunner&&!tasksConfig?.sqlite&&!tasksConfig?.redis&&!serverRedisForTasks&&!serverSqliteForTasks){throw new Error('[tasks] runner: "cli" requires a persistent backend (`tasks.sqlite`, `tasks.redis`, or a top-level `sqlite` without `tasks.store: false`) \u2014 the detached worker cannot share an in-memory store with this host.')}const runner=cliTaskRunner?new cliTaskRunner({store:this._taskStore,command:tasksConfig?.cliRunnerCommand,logger:this.logger}):new tasks.InProcessTaskRunner({scope:this,store:this._taskStore,registry:this._taskRegistry,notifier:new tasks.TaskNotifier(this.notificationService,this.logger),logger:this.logger});this._taskRegistry.setRunner(runner);this.logger.info(`[tasks] runner installed: ${runner.kind}`)}:void 0;const throttleConfig=this.metadata.throttle;const rateLimitPromise=throttleConfig?.enabled&&!this.cliMode?createGuardManager({config:throttleConfig,logger:this.logger}).then(mgr=>{this._rateLimitManager=mgr}):void 0;const batch1=[this.scopeHooks.ready,this.scopeFlows.ready,this.scopeAuth.ready,this.scopeApps.ready];if(elicitationPromise)batch1.push(elicitationPromise);if(tasksPromise)batch1.push(tasksPromise);if(rateLimitPromise)batch1.push(rateLimitPromise);await Promise.all(batch1);const serverHooks=serverProviderHooks(this.scopeProviders,this.metadata.providers,scopeRef);if(serverHooks.length>0)await this.scopeHooks.registerHooks(false,...serverHooks);this.logger.verbose("HookRegistry initialized");this.logger.verbose("FlowRegistry initialized");if(this.transportService)this.logger.verbose("TransportService initialized");this.logger.verbose("AuthRegistry initialized");mark("batch1:parallel (hooks+flows+auth+apps)");let topLevelSqliteUsed=this.transportService?.isSessionStoreConfigured()===true&&this.transportService.getBackendKind()==="sqlite"||this.taskBackendType==="sqlite"||this.elicitationBackendType==="sqlite"||this._persistentQuestions?.type==="sqlite";const serverPlugins=[...this.metadata.plugins??[]];const appPlugins=this.scopeApps.getApps().flatMap(app=>"plugins"in app.metadata?app.metadata.plugins??[]:[]);const impliedObservability=this.metadata.observability===void 0?devEventsObservabilityConfig([...serverPlugins,...appPlugins]):void 0;const observabilityConfig=this.metadata.observability??impliedObservability;if(observabilityConfig){const{observabilityPlugins:observabilityPlugins2}=await Promise.resolve().then(()=>(init_observability_scope_helper(),observability_scope_helper_exports));serverPlugins.push(...observabilityPlugins2({config:observabilityConfig,logger:this.logger,globalProviders:this.globalProviders,implied:impliedObservability!==void 0}))}if(serverPlugins.length>0){const serverPluginScopeInfo={ownScope:this,parentScope:void 0,isStandaloneApp:false};this.scopePlugins=new PluginRegistry(this.scopeProviders,serverPlugins,scopeRef,serverPluginScopeInfo)}if(this.scopePlugins){await this.scopePlugins.ready}if(this.metadata.adapters?.length){const scopeAdapters=new AdapterRegistry(this.scopeProviders,this.metadata.adapters);this.scopeAdapters=scopeAdapters;await scopeAdapters.ready;this.onDispose(()=>scopeAdapters.dispose())}await registerServerEntries(this.scopeProviders,this.metadata,this.scopeApps.getApps().map(app=>app.id));await this.initAuthoritiesFromConfig();this.scopeTools=new ToolRegistry(this.scopeProviders,[],scopeRef);this.scopeResources=new ResourceRegistry(this.scopeProviders,[],scopeRef);this.scopePrompts=new PromptRegistry(this.scopeProviders,[],scopeRef);this.scopeAgents=new AgentRegistry(this.scopeProviders,[],scopeRef);const skillsConfig=this.metadata.skillsConfig;this.scopeSkills=new SkillRegistry(this.scopeProviders,this.metadata.skills??[],scopeRef,{...skillsConfig?.scoring?{scoring:skillsConfig.scoring}:{},...skillsConfig?.failOnInvalidSkills!==void 0&&{failOnInvalidSkills:skillsConfig.failOnInvalidSkills}});await Promise.all([this.scopeTools.ready,this.scopeResources.ready,this.scopePrompts.ready,this.scopeAgents.ready,this.scopeSkills.ready]);if(this.scopePlugins){const pluginNames=this.scopePlugins.getPluginNames();this.logger.verbose(`PluginRegistry initialized (${pluginNames.length} plugin(s): [${pluginNames.join(", ")}])`)}const toolNames=this.scopeTools.getTools(true).map(t=>t.metadata.name);this.logger.verbose(`ToolRegistry initialized with initial ${toolNames.length} tool(s): [${toolNames.join(", ")}]`);this.logger.verbose(`ResourceRegistry initialized (${this.scopeResources.getResources().length} resource(s))`);this.logger.verbose(`PromptRegistry initialized (${this.scopePrompts.getPrompts().length} prompt(s))`);this.logger.verbose(`AgentRegistry initialized (${this.scopeAgents.getAgents().length} agent(s))`);this.logger.verbose(`SkillRegistry initialized (${this.scopeSkills.getSkills().length} skill(s))`);mark("batch2:parallel (tools+resources+prompts+agents+skills+plugins)");this.validateAuthoritiesConfig();this.validateEnforcedMetadata();checkHookOrder(hookRunsOf(this.scopeHooks),message=>this.logger.warn(message));for(const message of describeUnlistedOutputSchemas(this))this.logger.warn(message);await this.initGuardForDeclaredLimits();if(elicitationEnabled){await this.registerSendElicitationResultTool(scopeRef)}let uiResolver;if(!this.cliMode){const cdnOverrides=this.metadata.ui?.cdnOverrides;if(cdnOverrides&&Object.keys(cdnOverrides).length>0){const{createResolverWithOverrides:createResolverWithOverrides2}=__require("@frontmcp/uipack/resolver");uiResolver=createResolverWithOverrides2(cdnOverrides);this.logger.verbose("Created UI resolver with CDN overrides",{overrides:Object.keys(cdnOverrides)})}}this.toolUIRegistry=new ToolUIRegistry(uiResolver,{escapeStringResults:this.metadata.ui?.escapeStringResults,logger:this.logger});if(!this.cliMode){await this.compileUIWidgets()}if(!this.cliMode){await this.buildAuthUiRegistry()}const dynamicSkills=pluginsRegisterDynamicSkills([...serverPlugins,...appPlugins]);if(this.scopeSkills.hasAny()||dynamicSkills){const[skillSession,{createSkillToolGuardHook:createSkillToolGuardHook2}]=await Promise.all([Promise.resolve().then(()=>(init_session2(),session_exports)),Promise.resolve().then(()=>(init_hooks(),hooks_exports))]);const store=skillSession.createSkillSessionStore({type:"memory"});this._skillSession=new skillSession.SkillSessionManager({defaultPolicyMode:"permissive"},this.logger,store);const GuardHookClass=createSkillToolGuardHook2(this._skillSession,{logger:this.logger,trackToolCalls:true});const guardHookInstance=new GuardHookClass;const hookRecords=normalizeHooksFromCls(guardHookInstance);if(hookRecords.length>0){await this.scopeHooks.registerHooks(false,...hookRecords);this.logger.verbose("Skill tool authorization guard hook registered")}this.logger.verbose("Skill session manager initialized",{storeType:store.type})}if(this.scopeSkills.hasAny()){try{const report=await this.scopeSkills.validateAllTools();if(report.warningCount>0){this.logger.verbose("Skill validation completed with warnings",{totalSkills:report.totalSkills,warningCount:report.warningCount})}}catch(error){if(error instanceof SkillValidationError){this.logger.error("Skill validation failed",{failedSkills:error.failedSkills.map(s=>({name:s.skillName,missingTools:s.missingTools}))});throw error}throw error}}await registerSkillCapabilities({skillRegistry:this.scopeSkills,flowRegistry:this.scopeFlows,resourceRegistry:this.scopeResources,providers:this.scopeProviders,skillsConfig:this.metadata.skillsConfig,logger:this.logger,dynamicSkills});const jobsConfig=this.metadata.jobs;const metaRecord=this.metadata;const jobsList=metaRecord["jobTypes"]??[];const workflowsList=metaRecord["workflowTypes"]??[];const{items:appJobs,providers:jobProviders}=this.appEntryProviders("jobs",normalizeJob);const appWorkflows=[];for(const app of this.scopeApps.getApps()){const appMeta=app.metadata;if(Array.isArray(appMeta["workflows"]))appWorkflows.push(...appMeta["workflows"])}const allJobs=[...jobsList,...appJobs];const allWorkflows=[...workflowsList,...appWorkflows];const hasJobDeclarations=allJobs.length>0||allWorkflows.length>0;const explicitlyDisabled=jobsConfig?.enabled===false;const explicitlyEnabled=jobsConfig?.enabled===true;const autoEnabled=!explicitlyEnabled&&!explicitlyDisabled&&hasJobDeclarations;const effectivelyEnabled=explicitlyEnabled||autoEnabled;if(explicitlyDisabled&&hasJobDeclarations){this.logger.warn(`Jobs are explicitly disabled but ${allJobs.length} job(s) and ${allWorkflows.length} workflow(s) were declared on @App. Agents will NOT be able to invoke them \u2014 remove jobs.enabled: false or drop the @App({ jobs }) declarations.`)}if(effectivelyEnabled){if(autoEnabled){this.logger.info(`Jobs auto-enabled: detected ${allJobs.length} job(s) and ${allWorkflows.length} workflow(s) in @App declarations. Their runs are kept in jobs.store, else the top-level redis or sqlite, else in memory.`)}const notifyFn=async data=>{if(this.notificationService){this.logger.debug("Job notification",data)}};const{registerJobCapabilities:registerJobCapabilities2,resolveJobsStore:resolveJobsStore2,jobsServerStore:jobsServerStore2}=await Promise.resolve().then(()=>(init_job_scope_helper(),job_scope_helper_exports));refuseServerStoresInBrowser({jobs:jobsServerStore2(jobsConfig?.store,this.metadata)});const jobsStore2=resolveJobsStore2(jobsConfig?.store,{redis:this.metadata.redis,sqlite:resolvedTopLevelSqlite});const effectiveConfig={...jobsConfig??{},enabled:true,store:jobsStore2};topLevelSqliteUsed||=Boolean(resolvedTopLevelSqlite)&&jobsStore2?.sqlite===resolvedTopLevelSqlite;const result=await registerJobCapabilities2({providers:this.scopeProviders,flowRegistry:this.scopeFlows,owner:scopeRef,jobsList:allJobs,jobProviders,workflowsList:allWorkflows,jobsConfig:effectiveConfig,logger:this.logger,notifyFn,entryServer:isEntryServer(this.metadata),jobWorker:isJobWorker(this.metadata)});this._scopeJobs=result.jobRegistry;this._scopeWorkflows=result.workflowRegistry;this._jobExecutionManager=result.executionManager;this._jobStateStore=result.stateStore;this._jobDefinitionStore=result.definitionStore;for(const toolCls of result.managementTools){try{const toolRecord=normalizeTool(toolCls);const toolInstance=new ToolInstance(toolRecord,this.scopeProviders,{kind:"scope",id:"_jobs",ref:toolCls});this.scopeTools.registerToolInstance(toolInstance)}catch(error){this.logger.warn(`Failed to register job management tool: ${error instanceof Error?error.message:String(error)}`)}}this.logger.info(`Jobs system initialized: ${this._scopeJobs.getJobs().length} jobs, ${this._scopeWorkflows.getWorkflows().length} workflows`)}if(this.metadata.sqlite&&!topLevelSqliteUsed&&getRuntimeContext22().runtime!=="browser"){this.logger.warn("[FrontMcp] Top-level `sqlite` config was provided but no subsystem consumes it (transport persistence, tasks, elicitation and jobs were all disabled or pre-configured with a different backend). Sessions will use in-memory storage. Remove the `sqlite` block or enable one of the subsystems.")}this.notificationService=new NotificationService(this);await this.notificationService.initialize();this.logger.verbose("NotificationService initialized");const liveSurface=new LiveSurface(this);liveSurface.start();this.liveSurface=liveSurface;this.onDispose(()=>liveSurface.stop());const materializedResources=new MaterializedResources(this);await materializedResources.start();this.onDispose(()=>materializedResources.stop());installTaskRunner?.();await this.scopeFlows.registryFlows([SetLevelFlow,CompleteFlow]);if(this.scopeAgents.listAllInstances().length>0){const{CallAgentFlow:CallAgentFlow2}=await Promise.resolve().then(()=>(init_flows2(),flows_exports2));await this.scopeFlows.registryFlows([CallAgentFlow2])}if(this.metadata.elicitation?.enabled===true){const{ElicitationRequestFlow:ElicitationRequestFlow2,ElicitationResultFlow:ElicitationResultFlow2}=await Promise.resolve().then(()=>(init_flows3(),flows_exports3));await this.scopeFlows.registryFlows([ElicitationRequestFlow2,ElicitationResultFlow2])}if(taskModule){const{TasksGetFlow:TasksGetFlow2,TasksResultFlow:TasksResultFlow2,TasksCancelFlow:TasksCancelFlow2,TasksListFlow:TasksListFlow2}=taskModule;await this.scopeFlows.registryFlows([TasksGetFlow2,TasksResultFlow2,TasksCancelFlow2,TasksListFlow2])}if(this.metadata.registry){const{registerMcpRegistryFlows:registerMcpRegistryFlows2}=await Promise.resolve().then(()=>(init_mcp_registry_scope_helper(),mcp_registry_scope_helper_exports));await registerMcpRegistryFlows2({flowRegistry:this.scopeFlows,registryOptions:this.metadata.registry,servesServerEndpoint:this.routeBase===""&&this.metadata.apps.length>0})}await this.auth.ready;await transportService?.ready;if(this.haManager&&this.transportBus&&transportService){const{wireSessionRelay:wireSessionRelay2}=await Promise.resolve().then(()=>(init_relay_scope_helper(),relay_scope_helper_exports));this.sessionRelayHandle=wireSessionRelay2({nodeId:getMachineId5(),haManager:this.haManager,bus:this.transportBus,transportService,notifications:this.notificationService,flows:{runFlow:(name51,input)=>this.runFlow(name51,input)},logger:this.logger})}if(httpServing){httpServing.attachHttpRoutes(this,this.globalProviders);httpServing.registerCustomHttpRoutes({routes:this.metadata.http?.routes,server:this.httpRouteRegistrar,verifySession:request2=>this.runFlow("session:verify",{request:request2}),checkClientIp:(request2,response)=>this.runFlow("http:ip-filter",{request:request2,response}),entryPath:this.entryPath,routeBase:this.routeBase,healthPaths:httpServing.servedHealthPaths(this.metadata.health),logger:this.logger})}const channelsConfig=this.metadata.channels;if(channelsConfig?.enabled){const{items:appChannels,providers:channelProviders}=this.appEntryProviders("channels",normalizeChannel);const{registerChannelCapabilities:registerChannelCapabilities2}=await Promise.resolve().then(()=>(init_channel_scope_helper(),channel_scope_helper_exports));const channelResult=await registerChannelCapabilities2({providers:this.scopeProviders,owner:scopeRef,channelsList:appChannels,channelProviders,channelsConfig,notificationService:this.notificationService,flowRegistry:this.scopeFlows,toolRegistry:this.scopeTools,http:httpServing&&{server:this.httpRouteRegistrar,checkClientIp:(request2,response)=>this.runFlow("http:ip-filter",{request:request2,response}),entryPath:this.entryPath,routeBase:this.routeBase,healthPaths:httpServing.servedHealthPaths(this.metadata.health)},logger:this.logger});this._scopeChannels=channelResult.channelRegistry;this._channelNotificationService=channelResult.channelNotificationService;this._channelEventBus=channelResult.channelEventBus;this._channelTeardown=channelResult.teardown;this.onDispose(()=>this.teardownChannels());if(!isJobWorker(this.metadata))await channelResult.connectServices()}if(httpServing&&this.metadata.health?.enabled!==false){this._healthService=new httpServing.HealthService(this.metadata.health??{},this.metadata.info);this._healthService.autoDiscoverProbes(this);this.logger.verbose(`HealthService initialized (${this._healthService.getProbeCount()} probe(s))`)}for(const message of await describeBudgetOverruns(this))this.logger.warn(message);mark("batch3:finalization");this.logger.info(`Scope ready \u2014 ${this.formatScopeSummary()}`);reportStartup(this.scopePlugins,{toolsCount:this.scopeTools.getTools(true).length,resourcesCount:this.scopeResources.getResources().length,promptsCount:this.scopePrompts.getPrompts().length,durationMs:Date.now()-startedAt,scopeId:this.id},this.logger)}async primaryAuthFactory(){if(this.directOnly&&this.metadata.auth===void 0){return(scope,_providers,options)=>new DirectPublicAuth(scope,options)}const{createPrimaryAuth:createPrimaryAuth2}=await Promise.resolve().then(()=>(init_primary_auth_factory(),primary_auth_factory_exports));return createPrimaryAuth2}async resolveTopLevelSqlite(){const raw=this.metadata.sqlite;if(!raw||getRuntimeContext22().runtime==="browser")return void 0;let finalPath=raw.path;if(!finalPath||finalPath.length===0){finalPath=resolveDefaultSqlitePath({appName:this.metadata.info?.name,cliMode:this.cliMode});this.logger.info("[FrontMcp] No `sqlite.path` set \u2014 using default",{path:finalPath})}try{const{dirname:dirname10}=__require("path");await mkdir2(dirname10(finalPath),{recursive:true})}catch(err){this.logger.warn("[FrontMcp] Could not ensure sqlite parent directory exists",{path:finalPath,error:err.message})}return{...raw,path:finalPath}}async compileUIWidgets(){const toolsWithUI=this.scopeTools.getTools(true).filter(t=>hasUIConfig(t.metadata));if(toolsWithUI.length===0)return;const[{describeIgnoredUiOptions:describeIgnoredUiOptions2,describeServingModeDefault:describeServingModeDefault2},{StaticWidgetResourceTemplate:StaticWidgetResourceTemplate2}]=await Promise.all([Promise.resolve().then(()=>(init_ui_option_warnings(),ui_option_warnings_exports)),Promise.resolve().then(()=>(init_ui_resource_template(),ui_resource_template_exports)),this.toolUIRegistry.load()]);for(const tool of toolsWithUI){const resourceUri=tool.metadata.ui?.resourceUri;this.toolUIRegistry.registerTool(tool.metadata.name,typeof resourceUri==="string"?resourceUri:void 0);this.toolUIRegistry.checkTemplate(tool.metadata.name,tool.metadata.ui?.template);for(const message of describeIgnoredUiOptions2(tool.metadata.name,tool.metadata.ui)){this.logger.warn(message)}}for(const message of describeServingModeDefault2("`@FrontMcp({ ui })`",this.metadata.ui?.servingMode)){this.logger.warn(message)}for(const app of this.apps.getApps()){const appMode=app.metadata.ui?.servingMode;for(const message of describeServingModeDefault2(`App "${app.id}" \`@App({ ui })\``,appMode)){this.logger.warn(message)}}this.scopeResources.registerDynamicResource(StaticWidgetResourceTemplate2);this.logger.verbose(`Registered UI resource template for ${toolsWithUI.length} tool(s) with UI configs`);const servingModes=new Map(toolsWithUI.map(t=>[t,toolServingMode(t,this)]));const staticModeTools=toolsWithUI.filter(t=>t.metadata.ui&&servingModes.get(t)==="static"&&t.metadata.ui.template);if(staticModeTools.length>0){let staticCompiledCount=0;await Promise.all(staticModeTools.map(async tool=>{const uiConfig=tool.metadata.ui;if(!uiConfig?.template){this.logger.warn(`Skipping static widget pre-compile for tool "${tool.metadata.name}" due to missing ui.template`);return}try{await this.toolUIRegistry.compileStaticWidgetAsync({toolName:tool.metadata.name,template:uiConfig.template,uiConfig});staticCompiledCount++;this.logger.verbose(`Compiled static widget for tool: ${tool.metadata.name}`)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.error(`Failed to compile static widget for tool "${tool.metadata.name}": ${errorMessage2}`)}}));this.logger.info(`Pre-compiled ${staticCompiledCount}/${staticModeTools.length} static widget(s) for static mode tools`)}const inlineTools=toolsWithUI.filter(t=>{const mode=servingModes.get(t);return t.metadata.ui&&(mode==="inline"||mode==="auto")&&t.metadata.ui.template});if(inlineTools.length>0){let inlineCompiledCount=0;await Promise.all(inlineTools.map(async tool=>{const uiConfig=tool.metadata.ui;if(!uiConfig){this.logger.warn(`Skipping lean widget pre-compile for tool "${tool.metadata.name}" due to missing ui config`);return}try{await this.toolUIRegistry.compileLeanWidgetAsync({toolName:tool.metadata.name,uiConfig});inlineCompiledCount++;this.logger.verbose(`Compiled lean widget shell for tool: ${tool.metadata.name}`)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.error(`Failed to compile lean widget shell for tool "${tool.metadata.name}": ${errorMessage2}`)}}));this.logger.info(`Pre-compiled ${inlineCompiledCount}/${inlineTools.length} lean widget shell(s) for inline mode tools`)}const hybridTools=toolsWithUI.filter(t=>t.metadata.ui&&servingModes.get(t)==="hybrid"&&t.metadata.ui.template);if(hybridTools.length>0){let hybridCompiledCount=0;await Promise.all(hybridTools.map(async tool=>{const uiConfig=tool.metadata.ui;if(!uiConfig){this.logger.warn(`Skipping hybrid widget pre-compile for tool "${tool.metadata.name}" due to missing ui config`);return}try{await this.toolUIRegistry.compileHybridWidgetAsync({toolName:tool.metadata.name,template:uiConfig.template,uiConfig});hybridCompiledCount++;this.logger.verbose(`Compiled hybrid widget shell for tool: ${tool.metadata.name}`)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.error(`Failed to compile hybrid widget shell for tool "${tool.metadata.name}": ${errorMessage2}`)}}));this.logger.info(`Pre-compiled ${hybridCompiledCount}/${hybridTools.length} hybrid widget shell(s) for hybrid mode tools`)}}async buildAuthUiRegistry(){const auth=this.metadata.auth;const authUi=auth?.ui;const authExtras=auth?.extras;const uiSlotCount=authUi?Object.keys(authUi).length:0;const extraCount=authExtras?Object.keys(authExtras).length:0;if(uiSlotCount===0&&extraCount===0)return;let sourceDir=this.metadata.__sourceDir;if(!sourceDir){sourceDir=process.cwd();if(uiSlotCount>0){this.logger.warn(`auth.ui paths will resolve against process.cwd() ("${sourceDir}") \u2014 the declaring @FrontMcp/@App source directory could not be captured. Use absolute paths if this is wrong.`)}}const{AuthUiRegistry:AuthUiRegistry2}=await Promise.resolve().then(()=>(init_auth_ui(),auth_ui_exports));const registry=new AuthUiRegistry2(this.logger);registry.registerAuthUiMap(authUi,sourceDir);registry.registerAuthExtrasMap(authExtras);const cdnOverrides=this.metadata.ui?.cdnOverrides;if(cdnOverrides&&Object.keys(cdnOverrides).length>0){registry.setResolverOverrides(cdnOverrides)}try{await registry.warmup()}catch(error){this.logger.warn("Auth-UI registry warmup encountered errors \u2014 affected custom pages will fall back to built-in",{error:error instanceof Error?error.message:String(error)})}this.authUiRegistry=registry;this.logger.verbose(`Auth-UI registry initialized (${uiSlotCount} slot file(s), ${extraCount} extra(s))`)}formatScopeSummary(){const entries=[];const add=(count,label)=>{if(count>0)entries.push(`${count} ${label}${count!==1?"s":""}`)};add(this.scopeApps.getApps().length,"app");add(this.scopeTools.getTools(true).length,"tool");add(this.scopeResources.getResources().length,"resource");add(this.scopePrompts.getPrompts().length,"prompt");add(this.scopeAgents.getAgents().length,"agent");add(this.scopeSkills.getSkills().length,"skill");if(this._scopeJobs)add(this._scopeJobs.getJobs().length,"job");if(this._scopeWorkflows)add(this._scopeWorkflows.getWorkflows().length,"workflow");if(this._scopeChannels)add(this._scopeChannels.size,"channel");return entries.length>0?entries.join(", "):"empty"}get defaultScopeProviders(){return[{scope:ProviderScope2.GLOBAL,name:"ScopeEntry",provide:ScopeEntry,useValue:this},{scope:ProviderScope2.GLOBAL,name:"Scope",provide:_Scope,useValue:this},{scope:ProviderScope2.GLOBAL,name:"FrontMcpLogger",provide:FrontMcpLogger,useValue:this.logger},{scope:ProviderScope2.GLOBAL,name:"FrontMcpContextStorage",provide:FrontMcpContextStorage,useValue:new FrontMcpContextStorage().configure(this.metadata.fetch,{...proxyTrustOf(this.metadata.throttle),forwardsHeader:createHeaderForwarder(this.metadata.http?.forwardHeaders)})},FrontMcpContextProvider,{scope:ProviderScope2.GLOBAL,name:"OffloadService",provide:OffloadService,useValue:new OffloadService(this.metadata.offload,this.logger)}]}get auth(){return this.scopeAuth.getPrimary()}get hooks(){return this.scopeHooks}get authProviders(){return this.scopeAuth}get providers(){return this.scopeProviders}get apps(){return this.scopeApps}get tools(){return this.scopeTools}get toolUI(){return this.toolUIRegistry}get authUi(){return this.authUiRegistry}get resources(){return this.scopeResources}get prompts(){return this.scopePrompts}get agents(){return this.scopeAgents}get skills(){return this.scopeSkills}get jobs(){return this._scopeJobs}get workflows(){return this._scopeWorkflows}get channels(){return this._scopeChannels}get channelNotifications(){return this._channelNotificationService}get channelEventBus(){return this._channelEventBus}get skillSession(){return this._skillSession}get plugins(){return this.scopePlugins}get notifications(){return this.notificationService}get surface(){return this.liveSurface}get elicitationStore(){return this._elicitationStore}get persistentQuestions(){return this._persistentQuestions}get taskStore(){return this._taskStore}get tasks(){return this._taskRegistry}get eventStore(){return this._eventStore}get rateLimitManager(){return this._rateLimitManager}get publicAccessGuard(){return this._rateLimitManager??this._publicAccessGuard}get httpRoutes(){return this.registeredHttpRoutes}get healthService(){return this._healthService}get authoritiesEngine(){return this._authoritiesEngine}get authoritiesContextBuilder(){return this._authoritiesContextBuilder}get authoritiesScopeMapping(){return this._authoritiesScopeMapping}getAllSupportedScopes(){const scopes=new Set;const collectScopes=metadata=>{const authProviders=metadata?.["authProviders"];if(!Array.isArray(authProviders))return;for(const ap of authProviders){if(typeof ap==="object"&&ap!==null&&"scopes"in ap){const apScopes=ap["scopes"];if(Array.isArray(apScopes)){apScopes.forEach(s=>{if(typeof s==="string")scopes.add(s)})}}}};for(const tool of this.scopeTools.getTools(true)){collectScopes(tool.metadata)}for(const resource of this.scopeResources.getResources()){collectScopes(resource.metadata)}for(const prompt of this.scopePrompts.getPrompts()){collectScopes(prompt.metadata)}for(const agent of this.scopeAgents.getAgents()){collectScopes(agent["metadata"])}return[...scopes].sort()}registerAuthoritiesEngine(engine,contextBuilder){this._authoritiesEngine=engine;this._authoritiesContextBuilder=contextBuilder}async initAuthoritiesFromConfig(){const config=this.metadata["authorities"];if(!config)return;try{const{authoritiesFromConfig:authoritiesFromConfig2}=await Promise.resolve().then(()=>(init_authorities_engine(),authorities_engine_exports));const authorities=authoritiesFromConfig2(config);this._authoritiesEngine=authorities.engine;this._authoritiesContextBuilder=authorities.contextBuilder;this._authoritiesScopeMapping=authorities.scopeMapping;this.logger.verbose("Scope: authorities engine initialized from config")}catch(error){const msg=error instanceof Error?error.message:String(error);this.logger.warn(`Scope: authorities init failed \u2014 ${msg}`)}}appEntryProviders(key,normalize){const items=[];const providers=new Map;for(const app of this.scopeApps.getApps()){const declared=app.metadata[key];if(!Array.isArray(declared))continue;for(const item of declared){items.push(item);providers.set(normalize(item).provide,app.providers)}}return{items,providers}}async initGuardForDeclaredLimits(lateTools=[]){const throttleConfig=this.metadata.throttle;if(this._rateLimitManager||this.cliMode)return;if(throttleConfig?.enabled===false){await this.initPublicAccessGuard(throttleConfig.storage);return}const guardedEntries=[...this.scopeTools.getTools(true),...lateTools,...this.scopeAgents.getAgents(true)];const declaresLimits=guardedEntries.some(entry=>entry.metadata.rateLimit||entry.metadata.concurrency)||!!this.auth.options?.publicAccess||this.scopeAgents.listAllInstances().some(agent=>agent.declaresScopedLimits());if(!declaresLimits)return;this._rateLimitManager=await createGuardManager({config:{...throttleConfig,enabled:true},logger:this.logger})}async initPublicAccessGuard(storage){const publicAccess=this.auth.options?.publicAccess;if(!publicAccess?.rateLimit||this._publicAccessGuard)return;this._publicAccessGuard=await createGuardManager({config:{enabled:true,storage},logger:this.logger})}collectEntriesWithAuthorities(){const entries=[];const add=(label,metadata)=>{const authorities=metadata?.["authorities"];if(authorities!==void 0&&authorities!==null&&authorities!==false){entries.push({label,authorities})}};for(const tool of this.scopeTools.getTools(true)){add(`Tool "${tool.name}"`,tool.metadata)}for(const resource of this.scopeResources.getResources(true)){add(`Resource "${resource.name}"`,resource.metadata)}for(const template of this.scopeResources.getResourceTemplates()){add(`Resource template "${template.name}"`,template.metadata)}for(const prompt of this.scopePrompts.getPrompts(true)){add(`Prompt "${prompt.name}"`,prompt.metadata)}for(const agent of this.scopeAgents.getAgents(true)){add(`Agent "${agent.name}"`,agent.metadata);for(const metadata of agentToolMetadata(agent)){add(`Tool "${agent.name}:${metadata.name}"`,metadata)}}for(const skill of this.scopeSkills.getSkills(true)){add(`Skill "${skill.name}"`,skill.metadata)}return entries}validateAuthoritiesConfig(){const entries=this.collectEntriesWithAuthorities();const engine=this._authoritiesEngine;if(!engine||!this._authoritiesContextBuilder){if(entries.length===0)return;const names=entries.slice(0,5).map(entry=>entry.label).join(", ");const suffix=entries.length>5?` and ${entries.length-5} more`:"";throw new AuthConfigurationError(`Authorities configuration required: ${names}${suffix} declare 'authorities' metadata but authorities enforcement is not fully configured (engine/context builder missing). Add 'authorities: { claimsMapping: {...}, profiles: {...} }' to your @FrontMcp() decorator to enable enforcement, or remove 'authorities' from entry metadata.`,{suggestion:"Add authorities config to @FrontMcp() or remove authorities from entry metadata"})}assertAuthoritiesRules(engine,entries)}async checkLateApp(app){const{tools,resources,prompts,agents,skills}=app;const problems=findUnenforcedMetadata({hooks:this.scopeHooks,tools,resources,prompts,agents,skills});if(problems.length>0)throw new UnenforcedMetadataError(problems);checkHookOrder(hookRunsOf(this.scopeHooks),message=>this.logger.warn(message));const setup=this.lateGuardSetup.then(()=>this.initGuardForDeclaredLimits(tools.getTools(true)));this.lateGuardSetup=setup.catch(()=>void 0);await setup}validateEnforcedMetadata(){const problems=findUnenforcedMetadata({hooks:this.scopeHooks,tools:this.scopeTools,resources:this.scopeResources,prompts:this.scopePrompts,agents:this.scopeAgents,skills:this.scopeSkills});if(problems.length>0)throw new UnenforcedMetadataError(problems)}async registerSendElicitationResultTool(_scopeRef){try{const{SendElicitationResultTool:SendElicitationResultTool2}=await Promise.resolve().then(()=>(init_send_elicitation_result_tool(),send_elicitation_result_tool_exports));const toolRecord=normalizeTool(SendElicitationResultTool2);const systemToolEntry=new ToolInstance(toolRecord,this.scopeProviders,{kind:"scope",id:"_system",ref:SendElicitationResultTool2});this.scopeTools.registerToolInstance(systemToolEntry);this.logger.verbose("Registered sendElicitationResult system tool")}catch(error){this.logger.warn(`Failed to register sendElicitationResult tool: ${error instanceof Error?error.message:String(error)}`)}}get pagination(){return this.metadata.pagination}registryFlows(...flows){return this.scopeFlows.registryFlows(flows)}runFlow(name51,input,deps){return this.scopeFlows.runFlow(name51,input,deps)}async findHttpFlowName(request2){return this.scopeFlows.findHttpFlowName(request2,SCOPE_NON_DISPATCHABLE_FLOWS)}async runFlowForOutput(name51,input,deps){const result=await this.scopeFlows.runFlow(name51,input,deps);if(result){return result}throw new FlowExitedWithoutOutputError}createHaRedisClient(label="ha"){const redis=this.metadata.redis;if(!redis||redis.provider==="vercel-kv"){throw new Error("Distributed HA requires a TCP Redis (ioredis); Vercel KV over REST has no Lua/pub-sub support")}const client=createRedisClient3({...redis,label,logger:this.logger});if(label==="ha-subscriber")this.haSubscriberClient=client;else this.haRedisClient=client;return client}async closeHaRedisClient(){const clients=[this.haRedisClient,this.haSubscriberClient];this.haRedisClient=void 0;this.haSubscriberClient=void 0;for(const client of clients){if(!client)continue;try{await client.quit()}catch{client.disconnect()}}}async shutdown(){if(this.sessionRelayHandle){try{await this.sessionRelayHandle.close()}catch(err){this.logger.error("[HA] Session relay shutdown failed",{error:err})}this.sessionRelayHandle=void 0}if(this.haManager){try{await this.haManager.stop()}catch(err){this.logger.error("[HA] Manager shutdown failed",{error:err})}}await this.closeHaRedisClient();await this.teardownChannels();this.httpRouteTable?.closeStreams()}async teardownChannels(){const teardown=this._channelTeardown;if(!teardown)return;this._channelTeardown=void 0;try{await teardown()}catch(err){this.logger.error("Channel teardown failed",{error:err})}}async dispose(){await this.emitDispose();await this.scopeProviders.runShutdownHooks(this.logger);this.scopeProviders.dispose();if(this.notificationService){await this.notificationService.destroy()}}}}});var init_scope=__esm({"libs/sdk/src/scope/index.ts"(){"use strict";init_scope_instance()}});function isProbe(property){return property==="then"||property==="toJSON"||property.startsWith("on")}function storeProvider(provider){storeFactories.add(provider.useFactory);return provider}function opensStore(factory){return typeof factory==="function"&&storeFactories.has(factory)}function storeNotOpened(name51){return new Proxy({},{get:(target,property,receiver)=>typeof property==="symbol"||isProbe(property)||property in target?Reflect.get(target,property,receiver):()=>{throw new StoreNotOpenedInBuildError(name51)}})}var storeFactories;var init_store_provider=__esm({"libs/sdk/src/provider/store.provider.ts"(){"use strict";init_build_store_errors();storeFactories=new WeakSet}});import{randomUUID as randomUUID30}from"@frontmcp/utils";function messageOf6(error){return error instanceof Error?error.message:String(error)}var DutyRunner;var init_duty_runner=__esm({"libs/sdk/src/duty/duty.runner.ts"(){"use strict";DutyRunner=class{constructor(options){this.options=options;this.holder=randomUUID30();this.leaseSeconds=Math.ceil(options.leaseMs/1e3);this.ranKey=`${options.key}:ran`}options;holder;leaseSeconds;ranKey;holding=false;stopped=false;reportedHeldElsewhere=false;leaseCheck;leaseTimer;leaseDeadline;tickTimer;inFlight;async start(){this.leaseCheck=this.checkLease();await this.leaseCheck}async stop(){this.stopped=true;clearTimeout(this.tickTimer);this.inFlight?.controller.abort();await this.inFlight?.done;clearTimeout(this.leaseTimer);await this.leaseCheck;clearTimeout(this.leaseDeadline);if(!this.holding)return;this.holding=false;try{await this.options.storage.deleteIfEquals(this.options.key,this.holder)}catch(error){this.options.logger.warn(`Duty "${this.options.name}": the lease store failed: ${messageOf6(error)}`)}}async checkLease(){try{if(this.holding){if(!await this.renew())this.lose("lost its lease; another process runs it now")}else if(!this.stopped){if(await this.acquire())await this.hold();else this.reportHeldElsewhere()}}catch(error){this.options.logger.warn(`Duty "${this.options.name}": the lease store failed: ${messageOf6(error)}`)}if(this.stopped&&!this.inFlight)return;this.leaseTimer=setTimeout(()=>{this.leaseCheck=this.checkLease()},this.options.leaseMs/3);this.leaseTimer.unref?.()}async acquire(){await this.options.storage.set(this.options.key,this.holder,{ttlSeconds:this.leaseSeconds,ifNotExists:true});this.holding=await this.renew();return this.holding}async renew(){const sentAt=performance.now();const renewed=await this.options.storage.expireIfEquals(this.options.key,this.holder,this.leaseSeconds);if(renewed)this.holdUntil(sentAt+this.options.leaseMs);return renewed}holdUntil(deadline){clearTimeout(this.leaseDeadline);this.leaseDeadline=setTimeout(()=>this.lose(`could not renew its lease within ${this.options.leaseMs} ms; it stops here until it gets the lease again`),deadline-performance.now());this.leaseDeadline.unref?.()}reportHeldElsewhere(){if(this.reportedHeldElsewhere)return;this.reportedHeldElsewhere=true;this.options.logger.info(`Duty "${this.options.name}" already runs elsewhere (lease "${this.options.key}"); this one takes it over if that one stops`)}async hold(){this.options.logger.info(`Duty "${this.options.name}" runs in this process every ${this.options.everyMs} ms`);const remainingSeconds=await this.options.storage.ttl(this.ranKey).catch(()=>void 0);if(this.stopped||!this.holding)return;if(remainingSeconds===void 0)return this.scheduleTick(this.options.everyMs);this.scheduleTick(Math.min(Math.max(0,remainingSeconds??0)*1e3,this.options.everyMs))}lose(reason){if(!this.holding)return;this.holding=false;clearTimeout(this.tickTimer);clearTimeout(this.leaseDeadline);this.inFlight?.controller.abort();this.options.logger.warn(`Duty "${this.options.name}" ${reason}`)}scheduleTick(delayMs){this.tickTimer=setTimeout(()=>{this.scheduleTick(this.options.everyMs);void this.tick()},delayMs);this.tickTimer.unref?.()}async tick(){if(this.inFlight){this.options.logger.verbose(`Duty "${this.options.name}" is still running; skipping this run`);return}const controller=new AbortController;const done=this.runIfHeld(controller.signal);this.inFlight={controller,done};await done;this.inFlight=void 0}async runIfHeld(signal){if(!await this.claimRun())return;try{await this.options.run({signal})}catch(error){this.options.logger.error(`Duty "${this.options.name}" failed: ${messageOf6(error)}`)}}async claimRun(){try{if(!await this.renew()){this.lose("lost its lease; another process runs it now");return false}if(this.stopped)return false;const intervalSeconds=Math.max(1,Math.ceil(this.options.everyMs/1e3));await this.options.storage.set(this.ranKey,this.holder,{ttlSeconds:intervalSeconds});return true}catch(error){this.options.logger.warn(`Duty "${this.options.name}": the lease store failed: ${messageOf6(error)}`);return false}}}}});var duty_lifecycle_exports={};__export(duty_lifecycle_exports,{DutyLifecycle:()=>DutyLifecycle,dutyLifecycleOf:()=>dutyLifecycleOf,dutyStorageConfig:()=>dutyStorageConfig,startDuties:()=>startDuties});import{createStorage as createStorage6,getEnv as getEnv18,getRuntimeContext as getRuntimeContext23,mkdir as mkdir3,realpath as realpath2,sha256Hex as sha256Hex20,stat as stat4,writeFile as writeFile2}from"@frontmcp/utils";function nodeOs3(){return __require("os")}function nodePath3(){return __require("path")}function dutyLifecycleOf(duty,metadata,providers){let lifecycle=lifecycles.get(duty);if(!lifecycle){lifecycle=new DutyLifecycle(duty,metadata,providers);lifecycles.set(duty,lifecycle)}return lifecycle}async function startDuties(providers){for(const instance of providers.getAllSingletons().values()){if(typeof instance==="object"&&instance!==null)await lifecycles.get(instance)?.onReady()}}function dutyStorageConfig(redis){const parsed=redis===void 0?void 0:redisOptionsSchema.safeParse(redis);if(parsed?.success&&isRedisProvider(parsed.data)){const{host,port,password,db,tls}=parsed.data;return{type:"redis",redis:{config:{host,port,password,db,tls}},prefix:`frontmcp:duty:${nodeOs3().hostname()}:`,fallback:"error"}}const home=getEnv18("FRONTMCP_HOME")||nodePath3().join(nodeOs3().homedir(),".frontmcp");return{type:"sqlite",sqlite:{path:nodePath3().join(home,"duties.sqlite")},prefix:"frontmcp:duty:",fallback:"error"}}function leaseKey({name:name51,scope},serverName){const key=[serverName,name51].map(encodeURIComponent).join(":");if(scope==="machine")return key;const cwd=process.cwd();return`${key}:${sha256Hex20(findProjectRoot(cwd)??cwd)}`}async function prepareLeaseFile(file){const directory=nodePath3().dirname(file);await mkdir3(directory,{recursive:true,mode:OWNER_ONLY_DIRECTORY2});if(process.platform!=="win32"){const realDirectory=await realpath2(directory);const replaceable=await findReplaceableDirectory(directory)??(realDirectory===directory?void 0:await findReplaceableDirectory(realDirectory));if(replaceable)throw new UnsafeDutyStoreError(replaceable.directory,replaceable.mode,replaceable.ownerUid);const{mode}=await stat4(realDirectory);if(mode&GROUP_OR_OTHER_WRITE2)throw new UnsafeDutyStoreError(directory,mode)}await writeFile2(file,"",{mode:OWNER_ONLY_FILE2,flag:"a"})}var lifecycles,claims,OWNER_ONLY_DIRECTORY2,OWNER_ONLY_FILE2,GROUP_OR_OTHER_WRITE2,DutyLifecycle;var init_duty_lifecycle=__esm({"libs/sdk/src/duty/duty.lifecycle.ts"(){"use strict";init_common();init_resolve();init_duty_errors();init_front_mcp_tokens2();init_replaceable_directory();init_duty_runner();lifecycles=new WeakMap;claims=new Map;OWNER_ONLY_DIRECTORY2=448;OWNER_ONLY_FILE2=384;GROUP_OR_OTHER_WRITE2=18;DutyLifecycle=class{constructor(duty,metadata,providers){this.duty=duty;this.metadata=metadata;this.providers=providers}duty;metadata;providers;started;claimedKey;async onBootstrap(){await this.duty.onBootstrap?.()}async onReady(){await this.duty.onReady?.();this.started??=this.startRunner();await this.started}async onShutdown(){const started=await this.started?.catch(()=>void 0);if(started){await started.runner.stop();await started.storage.disconnect()}this.releaseClaim();await this.duty.onShutdown?.()}async startRunner(){const{name:name51,everyMs,leaseMs}=this.metadata;const logger=this.providers.get(FrontMcpLogger);const{runtime,deployment}=getRuntimeContext23();if(deployment==="serverless"||runtime==="edge"||runtime==="browser"){logger.warn(`Duty "${name51}" does not run in a serverless or edge deployment: it needs a long-lived process`);return void 0}const config=this.providers.get(FrontMcpConfig);const serverName=config.info?.name??"frontmcp";const key=leaseKey(this.metadata,serverName);this.claim(key,serverName);const storageConfig=dutyStorageConfig(config.redis);if(storageConfig.sqlite)await prepareLeaseFile(storageConfig.sqlite.path);const storage=await createStorage6(storageConfig);const runner=new DutyRunner({name:name51,everyMs,leaseMs,storage,logger,key,run:context=>this.duty.run(context)});await runner.start();return{runner,storage}}claim(key,serverName){const type=this.duty.constructor;const claim=claims.get(key);if(claim&&claim.type!==type){throw new DutyNameConflictError(this.metadata.name,serverName,claim.typeName,type.name)}claims.set(key,{type,typeName:type.name,instances:(claim?.instances??0)+1});this.claimedKey=key}releaseClaim(){const key=this.claimedKey;this.claimedKey=void 0;const claim=key===void 0?void 0:claims.get(key);if(key===void 0||!claim)return;claim.instances--;if(claim.instances===0)claims.delete(key)}}}});import"reflect-metadata";import{depsOfClass as depsOfClass12,hasAsyncWith,isClass as isClass20,isPromise,ProviderKind as ProviderKind4,ProviderScope as ProviderScope10,tokenName as tokenName22}from"@frontmcp/di";function verifiedSessionOf2(requestContext){const{authInfo}=requestContext;const verified=authInfo.sessionId??authInfo.extra?.["sessionId"];return typeof verified==="string"&&verified.length>0&&verified!==STATELESS_SESSION_ID?verified:void 0}function requestScopedTokens(contextProviders){const requestContext=contextProviders?.get(FRONTMCP_CONTEXT);const carriedTokens=requestContext instanceof FrontMcpContext?requestContext.getContextTokens().keys():[];return new Set([FRONTMCP_CONTEXT,...carriedTokens])}function newProviderStore(){return{providers:new Map,bySource:new Map,lastAccess:Date.now()}}var ProviderRegistry,REQUEST_PROVIDER_STORES;var init_provider_registry=__esm({"libs/sdk/src/provider/provider.registry.ts"(){"use strict";init_common();init_transport();init_frontmcp_context();init_frontmcp_context_provider();init_errors();init_front_mcp_tokens2();init_manifest_mode_flag();init_regsitry();init_scope();init_transport_types();init_provider_lifecycle();init_provider_utils();init_store_provider();ProviderRegistry=class _ProviderRegistry extends RegistryAbstract{constructor(list,parentProviders,options){super("ProviderRegistry",parentProviders,list,false);this.parentProviders=parentProviders;parentProviders?.childRegistries.add(this);this.providedBy=new Map;const configured=options?.distributedMode!==void 0||options?.providerCaching!==void 0;this.sessionCacheEnabled=!configured&&parentProviders?parentProviders.sessionCacheEnabled:shouldCacheProviders(options?.distributedMode,options?.providerCaching);this.sharedLifecycles=parentProviders?.sharedLifecycles??new WeakMap;this.shutdownHookTimeoutMs=options?.shutdownHookTimeoutMs??parentProviders?.shutdownHookTimeoutMs??DEFAULT_SHUTDOWN_HOOK_TIMEOUT_MS;this.buildGraph();this.topoSort();this.ready=this.initialize()}parentProviders;providedBy;visibleOnlyBelow=new Map;order=new Set;registries=new Map;sessionStores=new Map;sessionBuildLocks=new Map;static MAX_SESSION_CACHE_SIZE=1e4;static SESSION_CACHE_TTL_MS=36e5;static SESSION_CLEANUP_INTERVAL_MS=6e4;sessionCleanupInterval=null;sessionCacheEnabled;childRegistries=new Set;lifecycleEntries=[];heldEntries=[];sharedLifecycles;shutdownHookTimeoutMs;readyHooksRun;shutdownHooksRun;getProviders(){return[...this.instances.values()]}lookupDefInHierarchy(token,requester=this){const rec=this.defs.get(token);if(rec&&!this.hidesFrom(token,requester))return{registry:this,rec};return this.providers?.lookupDefInHierarchy(token,requester)}hidesFrom(token,requester){const roots=this.visibleOnlyBelow.get(token);if(!roots||requester===this)return false;for(const root of roots){if(requester.isWithin(root))return false}return true}isWithin(root){return this===root||(this.parentProviders?.isWithin(root)??false)}subtreeBelow(ancestor){if(this.parentProviders===ancestor)return this;return this.parentProviders?.subtreeBelow(ancestor)}resolveDefaultFromHierarchy(token){const found=this.lookupDefInHierarchy(token);if(!found)throw new ProviderNotRegisteredError(tokenName22(token),"not registered in hierarchy");const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==ProviderScope10.GLOBAL){const scName=ProviderScope10[sc];throw new ProviderScopeMismatchError(tokenName22(token),scName,registry.constructor.name)}const inst=registry.instances.get(token);if(inst===void 0){throw new ProviderNotInstantiatedError(tokenName22(token),"DEFAULT",registry.constructor.name)}return inst}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;for(const raw of list){const rec=normalizeProvider(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);const deps=this.discoveryDeps(rec);for(const d of deps){const isLocal=this.tokens.has(d);const up=isLocal?void 0:this.lookupDefInHierarchy(d);if(!isLocal&&!up){throw new ProviderDependencyError(`Provider ${tokenName22(token)} depends on ${tokenName22(d)}, which is not registered (local or parent).`)}const depRec=isLocal?this.defs.get(d):up.rec;const depScope=isLocal?this.getProviderScope(depRec):up.registry.getProviderScope(depRec);if(this.getProviderScope(rec)===ProviderScope10.GLOBAL&&depScope!==ProviderScope10.GLOBAL){throw new InvalidDependencyScopeError(`Invalid dependency: DEFAULT-scoped provider ${tokenName22(token)} cannot depend on scoped provider ${tokenName22(d)}.`)}if(isLocal)this.graph.get(token).add(d)}}}topoSort(){const WHITE=0,GRAY=1,BLACK=2;const color=new Map;const order=new Set;const path4=[];const dfs=n=>{color.set(n,GRAY);path4.push(n);for(const dep of this.graph.get(n)??[]){const c=color.get(dep)??WHITE;if(c===GRAY){const idx=path4.findIndex(p=>p===dep);const cycle=[...path4.slice(idx),dep].map(t=>tokenName22(t)).join(" -> ");throw new DependencyCycleError(cycle)}if(c===WHITE)dfs(dep)}color.set(n,BLACK);order.add(n);path4.pop()};for(const n of this.graph.keys())if((color.get(n)??WHITE)===WHITE)dfs(n);this.order=order}async initialize(opts){const force=!!opts?.force;const only=opts?.onlyTokens?new Set(opts.onlyTokens):null;for(const token of this.order){const rec=this.defs.get(token);if(this.getProviderScope(rec)!==ProviderScope10.GLOBAL)continue;if(only&&!only.has(token))continue;if(!force&&this.instances.has(token))continue;if(force&&this.instances.has(token)){this.instances.delete(token)}try{await this.initiateOne(token,rec)}catch(e){const msg=e?.message??e;console.error(`Failed instantiating:`,msg);throw new ProviderConstructionError(tokenName22(token),e instanceof Error?e:msg)}await this.bootstrapBuilt(token)}if(this.parentProviders){this.startSessionCleanup()}}async bootstrapBuilt(token){const built=this.instances.get(token);const instance=lifecycleHooksOf(await this.dutyLifecycleOf(built)??built);if(!instance||this.heldEntries.some(held=>held.instance===instance))return;const entry={token,instance};const shared=this.sharedLifecycles.get(instance);const lifecycle=shared??{holders:0,bootstrapped:bootstrapProvider(entry)};if(!shared)this.sharedLifecycles.set(instance,lifecycle);lifecycle.holders++;await lifecycle.bootstrapped;if(!shared)this.lifecycleEntries.push(entry);this.heldEntries.push(entry)}async dutyLifecycleOf(built){const metadata=dutyMetadataOf(built);if(!metadata||typeof built!=="object"||built===null)return void 0;const{dutyLifecycleOf:dutyLifecycleOf2}=await Promise.resolve().then(()=>(init_duty_lifecycle(),duty_lifecycle_exports));return dutyLifecycleOf2(built,metadata,this)}runReadyHooks(logger){this.readyHooksRun??=this.readyHereAndBelow(logger);return this.readyHooksRun}runShutdownHooks(logger){this.shutdownHooksRun??=this.shutdownBelowAndHere(logger);return this.shutdownHooksRun}async readyHereAndBelow(logger){await readyProviders(this.lifecycleEntries,logger);for(const child of[...this.childRegistries])await child.runReadyHooks(logger)}async shutdownBelowAndHere(logger){for(const child of[...this.childRegistries].reverse())await child.runShutdownHooks(logger);const lastHeld=this.heldEntries.filter(entry=>this.releaseLifecycleHold(entry.instance));await shutdownProviders(lastHeld,this.shutdownHookTimeoutMs,logger)}releaseLifecycleHold(instance){const lifecycle=this.sharedLifecycles.get(instance);if(!lifecycle)return true;lifecycle.holders--;return lifecycle.holders===0}getAllSingletons(){return this.instances}getContextScopedClasses(){const out=[];for(const[token,rec]of this.defs){if(this.getProviderScope(rec)!==ProviderScope10.CONTEXT)continue;if(rec.kind===ProviderKind4.CLASS)out.push({token,cls:rec.useClass});else if(rec.kind===ProviderKind4.CLASS_TOKEN)out.push({token,cls:rec.provide})}return out}discoveryDeps(rec){return providerDiscoveryDeps(rec,this.tokens,(k,phase)=>depsOfClass12(k,phase))}invocationTokens(_token,rec){return providerInvocationTokens(rec,(k,phase)=>depsOfClass12(k,phase))}normalizeScope(scope){switch(scope){case ProviderScope10.SESSION:case ProviderScope10.REQUEST:return ProviderScope10.CONTEXT;default:return scope}}getProviderScope(rec){const rawScope=rec.metadata?.scope??ProviderScope10.GLOBAL;return this.normalizeScope(rawScope)}getScope(){return this.getActiveScope()}async withTimeout(p,ms,label){if(ms<=0||!Number.isFinite(ms))return p;let timer;try{const tm=new Promise((_,rej)=>timer=setTimeout(()=>rej(new Error(`Timeout after ${ms}ms: ${label}`)),ms));return await Promise.race([p,tm])}finally{clearTimeout(timer)}}async resolveFactoryArg(t,store,scopeKey){if(store.has(t))return store.get(t);if(this.instances.has(t))return this.instances.get(t);const rec=this.defs.get(t);if(rec){const sc=this.getProviderScope(rec);if(sc===ProviderScope10.GLOBAL){if(!this.instances.has(t)){throw new ProviderNotInstantiatedError(tokenName22(t),"DEFAULT")}return this.instances.get(t)}else{await this.buildIntoStore(t,rec,store,scopeKey);return store.get(t)}}const up=this.lookupDefInHierarchy(t);if(up){const sc=up.registry.getProviderScope(up.rec);if(sc===ProviderScope10.GLOBAL){const inst=up.registry.instances.get(t);if(inst===void 0){throw new ProviderNotInstantiatedError(tokenName22(t),"DEFAULT","parent")}return inst}else{await up.registry.buildIntoStore(t,up.rec,store,scopeKey);return store.get(t)}}if(isClass20(t)){if(hasAsyncWith(t)){const out=t.with();return isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${t.name}.with(...)`):out}const instance=new t;const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${t.name}.init()`)}return instance}throw new ProviderNotRegisteredError(tokenName22(t),"not registered in hierarchy and not constructable")}bootsForBuild(){const config=this.lookupDefInHierarchy(FrontMcpConfig)?.rec;return config?.kind===ProviderKind4.VALUE&&typeof config.useValue==="object"&&config.useValue!==null&&isManifestMode(config.useValue)}async initiateOne(token,rec){switch(rec.kind){case ProviderKind4.VALUE:{this.instances.set(token,rec.useValue);return}case ProviderKind4.FACTORY:{if(opensStore(rec.useFactory)&&this.bootsForBuild()){this.instances.set(token,storeNotOpened(rec.metadata?.name??tokenName22(token)));return}const deps=this.invocationTokens(token,rec);const args=[];for(const d of deps)args.push(await this.resolveFactoryArg(d,this.instances));const out=rec.useFactory(...args);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${tokenName22(token)}.useFactory(...)`):out;this.instances.set(token,val);return}case ProviderKind4.CLASS:{const depTokens=this.invocationTokens(token,rec);const deps=depTokens.map(t=>this.resolveDefaultFromHierarchy(t));const klass=rec.useClass;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;this.instances.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}this.instances.set(token,instance)}return}case ProviderKind4.CLASS_TOKEN:{const depTokens=this.invocationTokens(token,rec);const deps=depTokens.map(t=>this.resolveDefaultFromHierarchy(t));const klass=rec.provide;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;this.instances.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}this.instances.set(token,instance)}return}}}async buildIntoStore(token,rec,store,scopeKey,injectedDeps){if(store.has(token))return;try{switch(rec.kind){case ProviderKind4.VALUE:{store.set(token,rec.useValue);return}case ProviderKind4.FACTORY:{const deps=this.invocationTokens(token,rec);const args=[];for(const d of deps)args.push(await this.resolveFactoryArg(d,store,scopeKey));const out=rec.useFactory(...args);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${tokenName22(token)}.useFactory(...)`):out;store.set(token,val);return}case ProviderKind4.CLASS:{const depsTokens=this.invocationTokens(token,rec);const deps=[];for(const d of depsTokens)deps.push(await this.resolveManagedForClass(d,store,scopeKey));const klass=rec.useClass;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;store.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}store.set(token,instance)}return}case ProviderKind4.CLASS_TOKEN:{const depsTokens=this.invocationTokens(token,rec);const deps=injectedDeps??[];for(const d of depsTokens)deps.push(await this.resolveManagedForClass(d,store,scopeKey));const klass=rec.provide;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;store.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}store.set(token,instance)}return}}}catch(e){const msg=e?.message??e;console.error(`Failed constructing:`,msg);throw new ProviderConstructionError(tokenName22(token),e instanceof Error?e:msg,"scoped")}}async resolveManagedForClass(d,store,scopeKey){if(store.has(d))return store.get(d);if(this.instances.has(d))return this.instances.get(d);const depRec=this.defs.get(d);if(depRec){const sc=this.getProviderScope(depRec);if(sc===ProviderScope10.GLOBAL){const v=this.instances.get(d);if(v===void 0)throw new ProviderNotInstantiatedError(tokenName22(d),"DEFAULT");return v}else{await this.buildIntoStore(d,depRec,store,scopeKey);return store.get(d)}}const up=this.lookupDefInHierarchy(d);if(up){const sc=up.registry.getProviderScope(up.rec);if(sc===ProviderScope10.GLOBAL){const v=up.registry.instances.get(d);if(v===void 0)throw new ProviderNotInstantiatedError(tokenName22(d),"DEFAULT","parent");return v}else{await up.registry.buildIntoStore(d,up.rec,store,scopeKey);return store.get(d)}}throw new ProviderNotInstantiatedError(tokenName22(d))}get(token){return this.getFor(token,this)}getFor(token,requester){const visible=!this.hidesFrom(token,requester);if(visible&&this.instances.has(token))return this.instances.get(token);const rec=visible?this.defs.get(token):void 0;if(rec&&this.getProviderScope(rec)!==ProviderScope10.GLOBAL){const scName=ProviderScope10[this.getProviderScope(rec)];throw new ProviderScopedAccessError(tokenName22(token),scName)}if(this.providers)return this.providers.getFor(token,requester);throw new ProviderNotAvailableError(tokenName22(token),"not found in local or parent registries")}addRegistry(type,value){let registry=this.registries.get(type);if(!registry){this.registries.set(type,new Set);registry=this.registries.get(type)}registry.add(value)}getRegistries(type){return[...this.registries.get(type)??[]]}getHooksRegistry(){return this.getRegistries("HookRegistry")[0]}getScopeRegistry(){return this.getRegistries("ScopeRegistry")[0]}async resolveBootstrapDep(t){if(this.instances.has(t))return this.instances.get(t);if(this.registries.has(t))return this.registries.get(t);const found=this.lookupDefInHierarchy(t);if(found){const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==ProviderScope10.GLOBAL)throw new PluginDependencyError(`Plugin dependency ${tokenName22(t)} must be DEFAULT-scoped at bootstrap`);const v=registry.instances.get(t);if(v===void 0)throw new PluginDependencyError(`Plugin dependency ${tokenName22(t)} (DEFAULT scope) is not instantiated`);return v}throw new PluginDependencyError(`Cannot resolve plugin dependency ${tokenName22(t)} (local or parent)`)}resolve(cls){const found=this.lookupDefInHierarchy(cls);if(found){const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==ProviderScope10.GLOBAL){const scName=ProviderScope10[sc];throw new ProviderScopedAccessError(tokenName22(cls),scName)}if(!registry.instances.has(cls)){throw new ProviderNotInstantiatedError(tokenName22(cls),"DEFAULT","Call providers.instantiate() first")}return registry.instances.get(cls)}if(isClass20(cls)){const instance=new cls;const init=instance?.init;if(typeof init==="function"){init.call(instance)}return instance}throw new ProviderNotRegisteredError(tokenName22(cls),"not a registered DEFAULT provider and not a constructable class")}mergeFromRegistry(providedBy,exported,visibleBelow){for(const{token,def,instance}of exported){if(visibleBelow){if(this.defs.has(token)&&!this.visibleOnlyBelow.has(token))continue;const roots=this.visibleOnlyBelow.get(token)??new Set;roots.add(visibleBelow);this.visibleOnlyBelow.set(token,roots)}else{this.visibleOnlyBelow.delete(token)}const scope=def.metadata.scope??ProviderScope10.GLOBAL;if(scope===ProviderScope10.GLOBAL&&instance!==void 0){this.instances.set(token,instance)}this.defs.set(token,def);this.providedBy.set(token,providedBy)}}getProviderInfo(token){const def=this.defs.get(token);if(!def)throw new ProviderNotRegisteredError(tokenName22(token),"not a registered DEFAULT provider and not a constructable class");const instance=this.instances.get(token);return{token,def,instance}}injectProvider(injected){const rec={...injected,kind:ProviderKind4.INJECTED};this.tokens.add(rec.provide);this.defs.set(rec.provide,rec);this.graph.set(rec.provide,new Set);this.instances.set(rec.provide,rec.value)}async addDynamicProviders(dynamicProviders){const normalized2=dynamicProviders.map(p=>normalizeProvider(p));for(const rec of normalized2){const provide=rec.provide;this.tokens.add(provide);this.defs.set(provide,rec);if(!this.graph.has(provide)){this.graph.set(provide,new Set)}const deps=this.discoveryDeps(rec);for(const d of deps){if(this.tokens.has(d)){this.graph.get(provide).add(d)}}}const globalProviders=normalized2.filter(rec=>this.getProviderScope(rec)===ProviderScope10.GLOBAL);return Promise.all(globalProviders.map(async rec=>{await this.initiateOne(rec.provide,rec);await this.bootstrapBuilt(rec.provide)}))}getWithParents(token){if(this.instances.has(token)){return this.get(token)}const parent=this.parentProviders;if(!parent){return this.get(token)}return parent.getWithParents(token)}getActiveScope(){return this.getWithParents(Scope)}getActiveServer(){return this.getWithParents(FrontMcpServer)}cleanupSession(sessionKey){this.sessionStores.delete(sessionKey);const lock=this.sessionBuildLocks.get(sessionKey);if(lock){lock.resolve();this.sessionBuildLocks.delete(sessionKey)}}cleanupExpiredSessions(){const now=Date.now();const cutoff=now-_ProviderRegistry.SESSION_CACHE_TTL_MS;let cleaned=0;for(const[key,entry]of this.sessionStores){if(entry.lastAccess<cutoff){this.sessionStores.delete(key);const lock=this.sessionBuildLocks.get(key);if(lock){lock.resolve();this.sessionBuildLocks.delete(key)}cleaned++}}return cleaned}startSessionCleanup(){if(this.sessionCleanupInterval){return}this.sessionCleanupInterval=setInterval(()=>{const cleaned=this.cleanupExpiredSessions();if(cleaned>0){console.debug(`[ProviderRegistry] Cleaned up ${cleaned} expired sessions`)}},_ProviderRegistry.SESSION_CLEANUP_INTERVAL_MS);if(this.sessionCleanupInterval.unref){this.sessionCleanupInterval.unref()}}stopSessionCleanup(){if(this.sessionCleanupInterval){clearInterval(this.sessionCleanupInterval);this.sessionCleanupInterval=null}}dispose(){for(const child of[...this.childRegistries])child.dispose();this.parentProviders?.childRegistries.delete(this);this.stopSessionCleanup();this.sessionStores.clear();for(const lock of this.sessionBuildLocks.values()){lock.resolve()}this.sessionBuildLocks.clear()}getSessionCacheStats(){return{enabled:this.sessionCacheEnabled,size:this.sessionStores.size,maxSize:_ProviderRegistry.MAX_SESSION_CACHE_SIZE,ttlMs:_ProviderRegistry.SESSION_CACHE_TTL_MS}}isSessionCacheEnabled(){return this.sessionCacheEnabled}async buildViews(sessionKey,contextProviders,contextSource){validateSessionId(sessionKey);const global=this.getAllSingletons();const ownDefs=(contextSource&&this.defsBelow(contextSource))??new Map;const cached=this.providerStoreFor(sessionKey,contextProviders?.get(FRONTMCP_CONTEXT));let sessionProviders=cached.providers;if(contextSource&&ownDefs.size>0){let bySource=cached.bySource.get(contextSource);if(!bySource){bySource=new Map;cached.bySource.set(contextSource,bySource)}sessionProviders=bySource}const requestTokens=requestScopedTokens(contextProviders);const contextStore=new Map(sessionProviders);const sourceRegistry=contextSource instanceof _ProviderRegistry&&contextSource!==this?contextSource:void 0;for(const[token,instance]of contextProviders??[]){if(ownDefs.has(token)||sourceRegistry?.hidesFrom(token,this))continue;contextStore.set(token,instance)}for(const token of this.order){const rec=this.defs.get(token);if(!rec)continue;if(this.getProviderScope(rec)!==ProviderScope10.CONTEXT)continue;if(contextStore.has(token))continue;await this.buildIntoStoreWithViews(token,rec,contextStore,sessionKey,contextStore,global)}for(const[token,rec]of this.defs){if(this.order.has(token))continue;if(this.getProviderScope(rec)!==ProviderScope10.CONTEXT)continue;if(contextStore.has(token))continue;await this.buildIntoStoreWithViews(token,rec,contextStore,sessionKey,contextStore,global)}for(const[token,{registry,rec}]of ownDefs){if(registry===this||contextStore.has(token))continue;if(registry.getProviderScope(rec)!==ProviderScope10.CONTEXT)continue;await registry.buildIntoStoreWithViews(token,rec,contextStore,sessionKey,contextStore,registry.getAllSingletons())}for(const[token,instance]of contextStore){if(!sessionProviders.has(token)&&!this.dependsOnAny(token,requestTokens)){sessionProviders.set(token,instance)}}return{global,context:contextStore}}providerStoreFor(sessionKey,requestContext){if(!(requestContext instanceof FrontMcpContext)){return newProviderStore()}if(!this.sessionCacheEnabled||verifiedSessionOf2(requestContext)!==sessionKey){let stores=requestContext.get(REQUEST_PROVIDER_STORES);if(!stores){stores=new WeakMap;requestContext.set(REQUEST_PROVIDER_STORES,stores)}let store=stores.get(this);if(!store){store=newProviderStore();stores.set(this,store)}return store}let cached=this.sessionStores.get(sessionKey);if(!cached){cached=newProviderStore();this.sessionStores.set(sessionKey,cached)}else{cached.lastAccess=Date.now()}return cached}defsBelow(ancestor){if(this===ancestor)return new Map;const owned=this.parentProviders?.defsBelow(ancestor);if(!owned)return void 0;for(const[token,rec]of this.defs)owned.set(token,{registry:this,rec});return owned}dependsOnAny(token,targets,visited=new Set){if(targets.has(token))return true;if(visited.has(token))return false;visited.add(token);const found=this.lookupDefInHierarchy(token);if(!found)return false;return found.registry.discoveryDeps(found.rec).some(dep=>this.dependsOnAny(dep,targets,visited))}async buildIntoStoreWithViews(token,rec,store,scopeKey,contextStore,globalStore){if(store.has(token))return;try{switch(rec.kind){case ProviderKind4.VALUE:{store.set(token,rec.useValue);return}case ProviderKind4.FACTORY:{const deps=this.invocationTokens(token,rec);const args=[];for(const d of deps){args.push(await this.resolveFromViews(d,contextStore,globalStore,scopeKey))}const out=rec.useFactory(...args);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${tokenName22(token)}.useFactory(...)`):out;store.set(token,val);return}case ProviderKind4.CLASS:case ProviderKind4.CLASS_TOKEN:{const depsTokens=this.invocationTokens(token,rec);const deps=[];for(const d of depsTokens){deps.push(await this.resolveFromViews(d,contextStore,globalStore,scopeKey))}const klass=rec.kind===ProviderKind4.CLASS?rec.useClass:rec.provide;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;store.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}store.set(token,instance)}return}}}catch(e){const msg=e?.message??e;console.error(`Failed constructing (context-scoped):`,msg);throw new ProviderConstructionError(tokenName22(token),e instanceof Error?e:msg,"context-scoped")}}async resolveFromViews(token,contextStore,globalStore,scopeKey){if(contextStore.has(token))return contextStore.get(token);if(globalStore.has(token))return globalStore.get(token);if(this.instances.has(token))return this.instances.get(token);const rec=this.defs.get(token);if(rec){const scope=this.getProviderScope(rec);if(scope===ProviderScope10.GLOBAL){throw new ProviderNotInstantiatedError(tokenName22(token),"GLOBAL")}else{await this.buildIntoStoreWithViews(token,rec,contextStore,scopeKey,contextStore,globalStore);return contextStore.get(token)}}const up=this.lookupDefInHierarchy(token);if(up){const sc=up.registry.getProviderScope(up.rec);if(sc===ProviderScope10.GLOBAL){const v=up.registry.instances.get(token);if(v!==void 0)return v;throw new ProviderNotInstantiatedError(tokenName22(token),"GLOBAL","parent")}await up.registry.buildIntoStoreWithViews(token,up.rec,contextStore,scopeKey,contextStore,up.registry.getAllSingletons());return contextStore.get(token)}throw new ProviderDependencyError(`Cannot resolve dependency ${tokenName22(token)} from views`)}getScoped(token,views){if(views.context.has(token))return views.context.get(token);if(views.global.has(token))return views.global.get(token);if(this.instances.has(token))return this.instances.get(token);throw new ProviderNotAvailableError(tokenName22(token),"not found in views. Ensure it was built via buildViews()")}};REQUEST_PROVIDER_STORES=Symbol("frontmcp:request-provider-stores")}});import{depsOfClass as depsOfClass13}from"@frontmcp/di";function normalizeAppScope(appItem,metadata){const app=normalizeApp(appItem);const appMetadata=app.metadata;if(metadata.splitByApp===true&&appMetadata.standalone==="includeInParent"){throw new ScopeConfigurationError("standalone: includeInParent is not supported for splitByApp scope")}const scopeId=appMetadata.id??appMetadata.name;const token=Symbol(scopeId);return{kind:"SPLIT_BY_APP",provide:token,metadata:{...metadata,id:scopeId,apps:[appItem],auth:appMetadata.auth??metadata.auth,__sourceDir:appMetadata.__sourceDir??metadata.__sourceDir}}}function normalizeMultiAppScope(includedApps,metadata){return{kind:"MULTI_APP",provide:Scope,metadata:{...metadata,id:"root",apps:includedApps}}}function scopeDiscoveryDeps(rec){switch(rec.kind){case"MULTI_APP":return depsOfClass13(rec.provide,"discovery").slice(1);case"SPLIT_BY_APP":return[]}}var init_scope_utils=__esm({"libs/sdk/src/scope/scope.utils.ts"(){"use strict";init_app_utils();init_errors();init_scope_instance()}});import"reflect-metadata";import{tokenName as tokenName23}from"@frontmcp/di";var ScopeRegistry;var init_scope_registry=__esm({"libs/sdk/src/scope/scope.registry.ts"(){"use strict";init_app_utils();init_common();init_errors();init_front_mcp_tokens2();init_regsitry();init_scope_instance();init_scope_utils();ScopeRegistry=class extends RegistryAbstract{logger;constructor(globalProviders){const metadata=globalProviders.get(FrontMcpConfig);super("ScopeRegistry",globalProviders,metadata);this.logger=globalProviders.get(FrontMcpLogger)?.child("ScopeRegistry")}buildMap(metadata){const tokens=new Set;const defs=new Map;const graph=new Map;if(metadata.splitByApp){for(const raw of metadata.apps){const rec=normalizeAppScope(raw,metadata);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}}else{const includeInParent=[];for(const raw of metadata.apps){const app=normalizeApp(raw);const appMetadata=app.metadata;if(appMetadata.standalone===false){includeInParent.push(raw);continue}if(appMetadata.standalone==="includeInParent"){includeInParent.push(raw)}const appScopeRec=normalizeAppScope(raw,metadata);const provide2=appScopeRec.provide;tokens.add(provide2);defs.set(provide2,appScopeRec);graph.set(provide2,new Set)}const rec=normalizeMultiAppScope(includeInParent,metadata);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);const deps=scopeDiscoveryDeps(rec).slice(1);for(const d of deps){if(!this.providers.get(d)){throw new RegistryDependencyNotRegisteredError("Scope",tokenName23(token),tokenName23(d))}this.graph.get(token).add(d)}}}async initialize(){this.logger?.verbose(`ScopeRegistry: initializing ${this.tokens.size} scope(s)`);for(const token of this.tokens){const rec=this.defs.get(token);let scope;switch(rec.kind){case"SPLIT_BY_APP":scope=new Scope(rec,this.providers);break;case"MULTI_APP":scope=new rec.provide(rec,this.providers);break;default:throw new InvalidRegistryKindError("scope",String(rec.kind))}try{await scope.ready}finally{this.instances.set(token,scope)}this.logger?.verbose(`ScopeRegistry: initialized scope '${tokenName23(token)}'`)}this.logger?.verbose(`ScopeRegistry: initialization complete (${this.instances.size} scope(s))`)}getScopes(){return[...this.instances.values()]}getPrimaryScope(){const scopes=this.getScopes();const multiApp=scopes.find(scope=>scope.record.kind==="MULTI_APP");if(multiApp&&multiApp.apps.getApps().length>0)return multiApp;return scopes[0]}}}});var NoopFrontMcpServer;var init_noop_server=__esm({"libs/sdk/src/server/noop-server.ts"(){"use strict";init_common();NoopFrontMcpServer=class extends FrontMcpServer{registerMiddleware(_entryPath,_handler){}registerRoute(_method,_path2,_handler){}prepare(){}getHandler(){return void 0}async start(){}}}});var MetricsPathConflictError,MetricsTokenNotConfiguredError;var init_metrics_errors=__esm({"libs/sdk/src/metrics/metrics.errors.ts"(){"use strict";init_mcp_error();MetricsPathConflictError=class extends InternalMcpError{conflictingPath;constructor(conflictingPath){super(`metrics.path "${conflictingPath}" conflicts with an MCP transport route. Pick a non-MCP path (e.g. "/metrics", "/internal/metrics").`,"METRICS_PATH_CONFLICT");this.conflictingPath=conflictingPath}};MetricsTokenNotConfiguredError=class extends InternalMcpError{tokenEnv;constructor(tokenEnv){super(`metrics.auth is "token" but env var "${tokenEnv}" is not set. Set the env var or switch metrics.auth to "public" / { token: "..." }.`,"METRICS_TOKEN_NOT_CONFIGURED");this.tokenEnv=tokenEnv}}}});function loadObservability(){if(!observabilityRuntime){observabilityRuntime=requireOptionalModule("@frontmcp/observability",()=>__require("@frontmcp/observability"))}return observabilityRuntime}function createProcessStatsCollectorIfEnabled(config){const include=config.include;const processEnabled=!include||include.length===0||include.includes("process");if(!processEnabled)return void 0;const obs=loadObservability();return new obs.ProcessStatsCollector({options:config.process})}var PROMETHEUS_CONTENT_TYPE,observabilityRuntime,MCP_RESERVED_PATH_PREFIXES,COUNTER_CATEGORY_PREFIX,MetricsService;var init_metrics_service=__esm({"libs/sdk/src/metrics/metrics.service.ts"(){"use strict";init_optional_dependency_util();init_metrics_errors();PROMETHEUS_CONTENT_TYPE="text/plain; version=0.0.4; charset=utf-8";MCP_RESERVED_PATH_PREFIXES=["/mcp","/sse","/messages"];COUNTER_CATEGORY_PREFIX={process:["frontmcp_process_","frontmcp_nodejs_","frontmcp_event_loop_"],skills:["frontmcp_skills_"],tools:["frontmcp_tool_"],resources:["frontmcp_resource_"],http:["frontmcp_http_"],storage:["frontmcp_storage_"],auth:["frontmcp_auth_"],sessions:["frontmcp_session_"]};MetricsService=class{config;processCollector;snapshotSource;resolvedToken;constructor(config,processCollector,options={}){this.config=config;this.processCollector=processCollector;this.snapshotSource=options.snapshotSource??(()=>loadObservability().getMetricSnapshot());const path4=config.path??"/metrics";for(const prefix of MCP_RESERVED_PATH_PREFIXES){if(path4===prefix||path4.startsWith(`${prefix}/`)){throw new MetricsPathConflictError(path4)}}if(config.auth==="token"){const envName=config.tokenEnv??"FRONTMCP_METRICS_TOKEN";const value=process.env[envName];if(!value){throw new MetricsTokenNotConfiguredError(envName)}this.resolvedToken=value}else if(typeof config.auth==="object"&&config.auth!==null&&"token"in config.auth){this.resolvedToken=config.auth.token}}getMetrics(){const format=this.config.format??"prometheus";const include=this.config.include;let counters=this.snapshotSource();let gauges=this.processCollector?.collect()??[];if(include&&include.length>0){const includeSet=new Set(include);const allowedPrefixes=include.flatMap(category=>COUNTER_CATEGORY_PREFIX[category]??[]);const matchesAllowed=name51=>allowedPrefixes.some(prefix=>name51.startsWith(prefix));counters=counters.filter(c=>matchesAllowed(c.name));if(!includeSet.has("process")){gauges=[]}else{gauges=gauges.filter(g=>matchesAllowed(g.name))}}const obs=loadObservability();if(format==="json"){return{contentType:"application/json",body:JSON.stringify(obs.renderJsonExposition(counters,gauges))}}return{contentType:PROMETHEUS_CONTENT_TYPE,body:obs.renderPrometheusExposition(counters,gauges)}}authorize(authorizationHeader){const auth=this.config.auth??"public";if(auth==="public")return 200;if(!authorizationHeader)return 401;const expected=this.resolvedToken;if(!expected)return 401;const match=/^Bearer\s+(.+)$/i.exec(authorizationHeader);if(!match)return 401;return match[1]===expected?200:403}}}});function readAuthorizationHeader(headers){if(!headers)return void 0;const raw=headers["authorization"]??headers["Authorization"];if(Array.isArray(raw))return raw[0];return typeof raw==="string"?raw:void 0}function metricsPath(config){return config.path??"/metrics"}function renderMetricsScrape(service,config,authorizationHeader){const status=service.authorize(authorizationHeader);if(status!==200){return{status,headers:{"Cache-Control":"no-store"},kind:"json",body:{error:status===401?"unauthorized":"forbidden",message:status===401?"Missing or malformed Authorization header":"Bearer token did not match the configured metrics token"}}}const result=service.getMetrics();const headers={"Cache-Control":"no-store","Content-Type":result.contentType};if((config.format??"prometheus")!=="json"){return{status:200,headers,kind:"text",body:result.body}}try{return{status:200,headers,kind:"json",body:JSON.parse(result.body)}}catch{return{status:500,headers,kind:"json",body:{error:"internal_error",message:"Failed to serialise metrics JSON"}}}}function registerMetricsRoutes(server,service,config){if(config.enabled!==true)return;server.registerRoute("GET",metricsPath(config),async(req,res)=>{const result=renderMetricsScrape(service,config,readAuthorizationHeader(req.headers));for(const[name51,value]of Object.entries(result.headers))res.setHeader?.(name51,value);if(result.kind==="json"){res.status(result.status).json(result.body);return}if(typeof res.send==="function"){res.status(result.status);res.send(result.body);return}res.status(500).json({error:"internal_error",message:'Server adapter does not support Prometheus text format. Use `format: "json"` or upgrade the adapter.'})})}var init_metrics_routes=__esm({"libs/sdk/src/metrics/metrics.routes.ts"(){"use strict"}});var metrics_exports={};__export(metrics_exports,{MetricsPathConflictError:()=>MetricsPathConflictError,MetricsService:()=>MetricsService,MetricsTokenNotConfiguredError:()=>MetricsTokenNotConfiguredError,createProcessStatsCollectorIfEnabled:()=>createProcessStatsCollectorIfEnabled,metricsPath:()=>metricsPath,registerMetricsRoutes:()=>registerMetricsRoutes,renderMetricsScrape:()=>renderMetricsScrape});var init_metrics2=__esm({"libs/sdk/src/metrics/index.ts"(){"use strict";init_metrics_service();init_metrics_routes();init_metrics_errors()}});import{getEnv as getEnv19}from"@frontmcp/utils";function readCorsFromEnv(){const rawOrigins=getEnv19("FRONTMCP_CORS_ORIGINS");if(!rawOrigins)return void 0;let origins;try{origins=JSON.parse(rawOrigins)}catch{origins=rawOrigins.split(",")}const list=(Array.isArray(origins)?origins:[origins]).filter(origin=>typeof origin==="string").map(origin=>origin.trim()).filter(origin=>origin.length>0);if(list.length===0)return void 0;const cors2={origin:list.includes("*")?true:list};const credentials=getEnv19("FRONTMCP_CORS_CREDENTIALS");if(credentials!==void 0)cors2.credentials=credentials==="true"||credentials==="1";const maxAge=Number(getEnv19("FRONTMCP_CORS_MAX_AGE"));if(Number.isFinite(maxAge)&&maxAge>0)cors2.maxAge=maxAge;return cors2}function resolveHttpCors(cors2){return cors2!==void 0?cors2:readCorsFromEnv()}var init_cors_env=__esm({"libs/sdk/src/server/middleware/cors-env.ts"(){"use strict"}});function auditSecurityDefaults(config,isProduction9){const findings=[];if(!isProduction9&&config.deploymentMode!=="distributed"){return findings}const strict=config.security?.strict===true;const cors2=resolveHttpCors(config.cors);const corsOrigin=cors2===false?void 0:cors2?.origin;if(corsOrigin===void 0||corsOrigin===false){findings.push({level:"info",code:"CORS_DISABLED",message:"No CORS headers are sent, so a browser will not let a page on another origin read the response. CORS is not server-side access control: on a routable bind, cross-origin requests still reach the server."})}else if(corsOrigin===true){findings.push({level:"warn",code:"CORS_ORIGIN_TRUE",message:"CORS origin=true allows all origins to make cross-origin requests.",recommendation:"Set cors.origin to specific allowed origins."})}else{findings.push({level:"info",code:"CORS_CONFIGURED",message:"CORS is explicitly configured."})}const bindAddress=config.resolvedBindAddress??"127.0.0.1";if(bindAddress==="0.0.0.0"||bindAddress==="::"){if(config.deploymentMode!=="distributed"){findings.push({level:"warn",code:"BIND_ALL_INTERFACES",message:`Server bound to ${bindAddress} \u2014 accessible from all network interfaces.`,recommendation:"Set security.bindAddress to 'loopback' or '127.0.0.1' for local-only access, or configure a reverse proxy. Distributed deployments require 'all' (0.0.0.0)."})}else{findings.push({level:"info",code:"BIND_ALL_INTERFACES_DISTRIBUTED",message:`Server bound to ${bindAddress} (expected for distributed deployment).`})}}else{findings.push({level:"info",code:"BIND_RESTRICTED",message:`Server bound to ${bindAddress}.`})}findings.push(auditDnsRebinding(config,bindAddress));if(config.security?.strict){findings.push({level:"info",code:"STRICT_MODE_ENABLED",message:config.deploymentMode==="distributed"?"Strict security mode is enabled: DNS rebinding protection. Binding is unchanged for a distributed deployment \u2014 it still listens on all interfaces so peers can reach it.":"Strict security mode is enabled: loopback binding and DNS rebinding protection."})}else{findings.push({level:"info",code:"STRICT_MODE_HINT",message:"To enable strict security defaults, set security.strict = true in HttpOptions."})}return findings}function auditDnsRebinding(config,bindAddress){const protection=config.security?.dnsRebindingProtection;if(protection?.enabled===false){return{level:"warn",code:"DNS_REBINDING_UNPROTECTED",message:"DNS rebinding protection is disabled (security.dnsRebindingProtection.enabled is false).",recommendation:"Remove `enabled: false` to turn DNS rebinding protection back on (an allowedHosts list is ignored while it is set). On a routable bind, also set security.dnsRebindingProtection.allowedHosts (or FRONTMCP_ALLOWED_HOSTS) to your public hostname(s)."}}const explicitHosts=protection?.allowedHosts??allowedHostsFromEnv();if(explicitHosts?.length||protection?.allowedOrigins?.length){return{level:"info",code:"DNS_REBINDING_PROTECTED",message:"DNS rebinding protection is enabled: Host/Origin headers are checked against the configured allow-list."}}if(config.socketPath){return{level:"info",code:"DNS_REBINDING_NOT_APPLICABLE",message:"Server listens on a Unix socket: there is no TCP Host to check; the socket permissions are the boundary."}}if(!isRoutableBind(bindAddress)){return{level:"info",code:"DNS_REBINDING_PROTECTED",message:corsAllowedOrigins(resolveHttpCors(config.cors))?`DNS rebinding protection is enabled: Host and Origin headers are checked against the loopback names for ${bindAddress}. A request with no Origin header is allowed.`:`DNS rebinding protection is enabled: Host headers are checked against the loopback names for ${bindAddress}. Origin is not checked: CORS admits every origin.`}}return{level:"info",code:"DNS_REBINDING_NOT_ENFORCED",message:`DNS rebinding protection is on, but no Host allow-list is enforced: the server binds ${bindAddress} and no allowed hosts are configured.`,recommendation:"Set security.dnsRebindingProtection.allowedHosts (or FRONTMCP_ALLOWED_HOSTS) to your public hostname(s)."}}function logSecurityFindings(findings,logger){if(findings.length===0)return;for(const finding of findings){const prefix=`[Security] ${finding.code}:`;const message=finding.recommendation?`${prefix} ${finding.message} ${finding.recommendation}`:`${prefix} ${finding.message}`;if(finding.level==="warn"){logger.warn(message)}else{logger.info(message)}}}function toBindAddress(value){if(value==="loopback")return"127.0.0.1";if(value==="all")return"0.0.0.0";return value}function resolveBindAddress(security,deploymentMode){if(security?.bindAddress){return toBindAddress(security.bindAddress)}const envBindAddress=process.env["FRONTMCP_BIND_ADDRESS"]?.trim();if(envBindAddress){return toBindAddress(envBindAddress)}if(security?.strict){return deploymentMode==="distributed"?"0.0.0.0":"127.0.0.1"}if(deploymentMode==="distributed")return"0.0.0.0";return"127.0.0.1"}var init_security_audit=__esm({"libs/sdk/src/server/security/security-audit.ts"(){"use strict";init_cors_env();init_resolve_allowed_hosts()}});import{getEnv as getEnv20,getEnvFlag as getEnvFlag2}from"@frontmcp/utils";function readCspFromEnv(){if(!getEnvFlag2("FRONTMCP_CSP_ENABLED"))return void 0;const rawDirectives=getEnv20("FRONTMCP_CSP_DIRECTIVES")??"";const directives={};for(const part of rawDirectives.split(";")){const trimmed=part.trim();if(!trimmed)continue;const spaceIdx=trimmed.indexOf(" ");if(spaceIdx>0){directives[trimmed.slice(0,spaceIdx)]=trimmed.slice(spaceIdx+1)}else{directives[trimmed]=""}}return{enabled:true,directives,reportUri:getEnv20("FRONTMCP_CSP_REPORT_URI"),reportOnly:getEnvFlag2("FRONTMCP_CSP_REPORT_ONLY")}}function buildCspHeaderValue(options){const parts=[];for(const[directive,value]of Object.entries(options.directives)){parts.push(value?`${directive} ${value}`:directive)}if(options.reportUri){parts.push(`report-uri ${options.reportUri}`)}return parts.join("; ")}function getCspHeaderName(reportOnly){return reportOnly?"Content-Security-Policy-Report-Only":"Content-Security-Policy"}function readSecurityHeadersFromEnv(){return{hsts:readHeaderEnv("FRONTMCP_HSTS"),contentTypeOptions:readHeaderEnv("FRONTMCP_CONTENT_TYPE_OPTIONS","nosniff"),frameOptions:readHeaderEnv("FRONTMCP_FRAME_OPTIONS","DENY"),custom:readCustomHeadersFromEnv()}}function readHeaderEnv(name51,fallback){const value=getEnv20(name51);if(value===void 0||value==="")return fallback;return["off","false","none"].includes(value.trim().toLowerCase())?void 0:value}function readCustomHeadersFromEnv(){const raw=getEnv20("FRONTMCP_HEADERS_CUSTOM");if(!raw)return void 0;try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))return void 0;return Object.fromEntries(Object.entries(parsed).filter(entry=>typeof entry[1]==="string"))}catch{return void 0}}function applySecurityHeaders(res,headers,csp){if(headers.hsts){res.setHeader("Strict-Transport-Security",headers.hsts)}if(headers.contentTypeOptions){res.setHeader("X-Content-Type-Options",headers.contentTypeOptions)}if(headers.frameOptions){res.setHeader("X-Frame-Options",headers.frameOptions)}if(headers.custom){for(const[name51,value]of Object.entries(headers.custom)){res.setHeader(name51,value)}}if(csp?.enabled){const headerName=getCspHeaderName(csp.reportOnly);const headerValue=buildCspHeaderValue(csp);if(headerValue){res.setHeader(headerName,headerValue)}}}function resolveSecurityHeaders(options={}){const env=readSecurityHeadersFromEnv();const pick=(explicit,fromEnv)=>explicit===false?void 0:explicit??fromEnv;const resolved={hsts:pick(options.hsts,env.hsts),contentTypeOptions:pick(options.contentTypeOptions,env.contentTypeOptions),frameOptions:pick(options.frameOptions,env.frameOptions),custom:{...env.custom,...options.custom}};let csp;if(options.csp?.enabled===false){csp=void 0}else if(options.csp?.enabled===true){const directives={};for(const[name51,value]of Object.entries(options.csp.directives??{})){directives[name51]=Array.isArray(value)?value.join(" "):value}csp={enabled:true,directives,reportUri:options.csp.reportUri,reportOnly:options.csp.reportOnly??false}}else{csp=readCspFromEnv()}const headers={};applySecurityHeaders({setHeader:(name51,value)=>void(headers[name51]=value)},resolved,csp);return headers}var init_csp_middleware=__esm({"libs/sdk/src/server/middleware/csp.middleware.ts"(){"use strict"}});function createHostValidationMiddleware(options){if(!options.enabled){return(_req,_res,next)=>next()}const compiled=compileHostValidation({allowedHosts:options.allowedHosts,allowedOrigins:options.allowedOrigins});return(req,res,next)=>{const rejection=validateHostHeaders({host:req.headers?.["host"],forwardedHost:req.headers?.["x-forwarded-host"],origin:req.headers?.["origin"]},compiled);if(rejection){res.status(rejection.status).json({error:rejection.error,message:rejection.message});return}next()}}var init_host_validation_middleware=__esm({"libs/sdk/src/server/middleware/host-validation.middleware.ts"(){"use strict";init_host_validation()}});import cluster from"node:cluster";import*as net from"node:net";import*as path from"node:path";import{chmod,lstat as lstat2,realpath as realpath3,stat as stat5,unlink}from"@frontmcp/utils";function hasSocketFileMode(){return process.platform!=="win32"}function errorCode(error){return error?.code}async function assertSafeSocketDirectory(socketPath){const socketDirectory=path.dirname(path.resolve(socketPath));const realSocketDirectory=await realpath3(socketDirectory);await assertNoOtherUserCanReplace2(socketDirectory);if(realSocketDirectory!==socketDirectory)await assertNoOtherUserCanReplace2(realSocketDirectory);if(canBindOwnerOnly())return;const{mode}=await stat5(socketDirectory);if(mode&GROUP_OR_OTHER_ACCESS2){throw new SocketPermissionError(socketPath,`the umask cannot be set here (a worker thread, or a cluster worker whose primary binds the socket), so its directory ${socketDirectory} must be owner-only (0700), not 0${(mode&511).toString(8)}`)}}async function assertNoOtherUserCanReplace2(start){const replaceable=await findReplaceableDirectory(start);if(replaceable)throw new UnsafeSocketDirectoryError(replaceable.directory,replaceable.mode,replaceable.ownerUid)}function canBindOwnerOnly(){if(cluster.isWorker)return false;const previousUmask=setUmask(OWNER_ONLY_UMASK);if(previousUmask===void 0)return false;setUmask(previousUmask);return true}function probe(socketPath){return new Promise((resolve4,reject)=>{const socket=net.connect(socketPath);socket.once("connect",()=>{socket.destroy();resolve4("live")});socket.once("error",error=>{const code=errorCode(error);if(code==="ECONNREFUSED")resolve4("stale");else if(code==="ENOENT")resolve4("gone");else reject(new SocketPathConflictError(socketPath,`connecting to it failed (${code??error.message})`))})})}async function clearStaleSocket(socketPath){let stats;try{stats=await lstat2(socketPath)}catch(error){if(errorCode(error)==="ENOENT")return;throw error}if(!stats.isSocket())throw new SocketPathConflictError(socketPath,"it is not a socket");if(stats.uid!==process.getuid?.()){throw new SocketPathConflictError(socketPath,`it belongs to another user (uid ${stats.uid})`)}const state=await probe(socketPath);if(state==="live")throw new SocketInUseError(socketPath);if(state==="stale")await unlink(socketPath)}function listenOwnerOnly(server,socketPath,onListening){const previousUmask=setUmask(OWNER_ONLY_UMASK);try{server.listen(socketPath,onListening)}finally{if(previousUmask!==void 0)setUmask(previousUmask)}}function setUmask(mask){try{return process.umask(mask)}catch{return void 0}}async function enforceOwnerOnly(socketPath){try{await chmod(socketPath,OWNER_ONLY_MODE)}catch(error){throw new SocketPermissionError(socketPath,`chmod failed (${errorCode(error)??String(error)})`)}const mode=(await lstat2(socketPath)).mode&511;if(mode!==OWNER_ONLY_MODE)throw new SocketPermissionError(socketPath,`its mode is 0${mode.toString(8)}`)}var OWNER_ONLY_MODE,OWNER_ONLY_UMASK,GROUP_OR_OTHER_ACCESS2;var init_unix_socket_guard=__esm({"libs/sdk/src/server/security/unix-socket-guard.ts"(){"use strict";init_transport_errors();init_replaceable_directory();OWNER_ONLY_MODE=384;OWNER_ONLY_UMASK=63;GROUP_OR_OTHER_ACCESS2=63}});var HostServerAdapter;var init_base_host_adapter=__esm({"libs/sdk/src/server/adapters/base.host.adapter.ts"(){"use strict";init_common();HostServerAdapter=class extends FrontMcpServer{}}});import express from"express";function utf8JsonParser(limit){const readBody=express.raw({limit,type:isUtf8Json});return(req,res,next)=>{const unparsedBody=req.body;readBody(req,res,readError=>{if(readError||req.body===unparsedBody||!Buffer.isBuffer(req.body)){next(readError);return}const text=decodeUtf8(req.body);try{req.body=parseStrictJson(text)}catch(error){req.body=unparsedBody;next(Object.assign(error,parseFailure(text)));return}next()})}}function decodeUtf8(body){const text=body.toString("utf8");return text.charCodeAt(0)===65279?text.slice(1):text}function parseStrictJson(text){if(text.length===0)return{};const first3=FIRST_NON_WHITESPACE.exec(text)?.[1];if(first3!=="{"&&first3!=="[")throw strictSyntaxError(text,first3);return JSON.parse(text)}function strictSyntaxError(text,first3){const index=first3===void 0?-1:text.indexOf(first3);const error=jsonParseError(index===-1?"":text.slice(0,index).padEnd(text.length,"#"));const message=error.message.replace(/#+/g,mask=>text.substring(index,index+mask.length));error.stack=error.stack?.replace(error.message,message);error.message=message;return error}function jsonParseError(invalidJson){try{JSON.parse(invalidJson)}catch(error){return error}return new SyntaxError(`Expected invalid JSON: ${invalidJson}`)}var UTF8_JSON_TYPE,FIRST_NON_WHITESPACE,isUtf8Json,parseFailure;var init_utf8_json_parser=__esm({"libs/sdk/src/server/adapters/utf8-json.parser.ts"(){"use strict";UTF8_JSON_TYPE=/^application\/json(?:; ?charset=utf-8)?$/i;FIRST_NON_WHITESPACE=/^[ \t\n\r]*([^ \t\n\r])/;isUtf8Json=req=>UTF8_JSON_TYPE.test(req.headers["content-type"]??"");parseFailure=body=>({expose:true,statusCode:400,status:400,body,type:"entity.parse.failed"})}});import*as http from"node:http";import cors from"cors";import express2 from"express";var SERVER_DRAIN_MS,DEFAULT_EXPRESS_BODY_LIMIT,ExpressHostAdapter;var init_express_host_adapter=__esm({"libs/sdk/src/server/adapters/express.host.adapter.ts"(){"use strict";init_mcp_error();init_ha_headers();init_csp_middleware();init_host_validation_middleware();init_resolve_allowed_hosts();init_unix_socket_guard();init_base_host_adapter();init_utf8_json_parser();SERVER_DRAIN_MS=5e3;DEFAULT_EXPRESS_BODY_LIMIT="4mb";ExpressHostAdapter=class extends HostServerAdapter{app=express2();router=express2.Router();prepared=false;httpServer;hostValidation;deriveHostValidation;constructor(options){super();this.app.disable("x-powered-by");const securityHeaders=resolveSecurityHeaders(options?.securityHeaders);this.app.use((_req,res,next)=>{for(const[name51,value]of Object.entries(securityHeaders))res.setHeader(name51,value);applyMachineIdHeader(res);next()});const corsOptions=options?.cors;const corsEnabled=corsOptions?.origin!==void 0&&corsOptions.origin!==false;if(corsEnabled){const configuredCors=cors({origin:corsOptions.origin,credentials:corsOptions.credentials??false,maxAge:corsOptions.maxAge??300});const publicCorsPaths=new Set(options?.publicCorsPaths);this.app.use((req,res,next)=>publicCorsPaths.has(req.path)?next():configuredCors(req,res,next))}this.installHostValidation(options);const jsonLimit=options?.bodyLimit??DEFAULT_EXPRESS_BODY_LIMIT;const formLimit=options?.urlencodedLimit??jsonLimit;const headerContains=(req,needle)=>(req.headers["content-type"]??"").toLowerCase().includes(needle);const isUrlencoded=req=>headerContains(req,"application/x-www-form-urlencoded");const isJson=req=>headerContains(req,"application/json")&&!isUrlencoded(req);this.app.use(express2.urlencoded({extended:true,limit:formLimit,type:isUrlencoded}));this.app.use(utf8JsonParser(jsonLimit));this.app.use(express2.json({limit:jsonLimit,type:isJson}));this.app.use((err,_req,res,next)=>{const e=err;if(e?.type==="entity.too.large"){const payloadError=new PayloadTooLargeError(e.limit,e.length);res.status(payloadError.statusCode).json({jsonrpc:"2.0",id:null,error:payloadError.toJsonRpcError()});return}next(err)});this.app.use((req,res,next)=>{if(corsEnabled){res.setHeader("Access-Control-Expose-Headers","WWW-Authenticate, Mcp-Session-Id")}res.setHeader("Cache-Control","no-cache, no-transform");res.setHeader("Content-Type","application/json; charset=utf-8");next()})}installHostValidation(options){const protection=options?.security?.dnsRebindingProtection;if(protection?.enabled===false)return;const allowedOrigins=protection?.allowedOrigins;const explicitHosts=protection?.allowedHosts??allowedHostsFromEnv();if(explicitHosts?.length||allowedOrigins?.length){this.hostValidation=createHostValidationMiddleware({enabled:true,allowedHosts:explicitHosts?.length?explicitHosts:void 0,allowedOrigins})}else{this.deriveHostValidation=(portOrSocketPath,bindAddress)=>{if(typeof portOrSocketPath==="string")return void 0;const derivation={bindAddress:bindAddress??"127.0.0.1",port:portOrSocketPath,issuer:options?.listen?.issuer};if(!shouldEnforceDerivedHosts(derivation)){console.warn(`[frontmcp] DNS-rebinding protection is not enforcing a Host allow-list: the server binds a routable address (${derivation.bindAddress}) and no allowed hosts are configured. Set security.dnsRebindingProtection.allowedHosts (or FRONTMCP_ALLOWED_HOSTS) to your public hostname(s).`);return void 0}const allowedHosts=deriveAllowedHosts(derivation);if(!allowedHosts.length)return void 0;const corsOrigins=corsAllowedOrigins(options?.cors);const allowedOrigins2=isLoopbackAddress(derivation.bindAddress)&&corsOrigins?deriveAllowedOrigins({port:derivation.port,issuer:derivation.issuer,extraOrigins:corsOrigins}):void 0;return createHostValidationMiddleware({enabled:true,allowedHosts,allowedOrigins:allowedOrigins2})}}this.app.use(((req,res,next)=>{const validate=this.hostValidation;if(!validate)return next();return validate(req,res,next)}))}enableDerivedHostValidation(portOrSocketPath,bindAddress){if(this.hostValidation||!this.deriveHostValidation)return;this.hostValidation=this.deriveHostValidation(portOrSocketPath,bindAddress);this.deriveHostValidation=void 0}registerRoute(method,path4,handler){this.router[method.toLowerCase()](path4,this.enhancedHandler(handler))}registerMiddleware(entryPath,handler){this.router.use(entryPath,handler)}enhancedHandler(handler){return(req,res,next)=>{const request2=req;const response=res;return handler(request2,response,next)}}prepare(){if(this.prepared)return;this.prepared=true;this.app.use("/",this.router)}getHandler(){this.prepare();return this.app}async start(portOrSocketPath,bindAddress){this.prepare();const server=http.createServer(this.app);this.httpServer=server;server.requestTimeout=0;server.headersTimeout=0;server.keepAliveTimeout=75e3;if(typeof portOrSocketPath==="string"){const ownerOnly=hasSocketFileMode();if(ownerOnly){await assertSafeSocketDirectory(portOrSocketPath);await clearStaleSocket(portOrSocketPath)}this.enableDerivedHostValidation(portOrSocketPath);await new Promise((resolve4,reject)=>{server.on("error",reject);if(ownerOnly)listenOwnerOnly(server,portOrSocketPath,resolve4);else server.listen(portOrSocketPath,resolve4)});if(ownerOnly){try{await enforceOwnerOnly(portOrSocketPath)}catch(error){await this.stop(0);throw error}}console.log(`MCP HTTP (Express) on unix://${portOrSocketPath}`)}else{const host=bindAddress??"127.0.0.1";await new Promise((resolve4,reject)=>{server.on("error",reject);server.listen(portOrSocketPath,host,()=>{const bound=server.address();const boundPort=typeof bound==="object"&&bound?bound.port:portOrSocketPath;const boundAddress=typeof bound==="object"&&bound?bound.address:host;this.enableDerivedHostValidation(boundPort,boundAddress);console.log(`MCP HTTP (Express) on ${host}:${boundPort}`);resolve4()})})}}async stop(drainMs=SERVER_DRAIN_MS){const server=this.httpServer;if(!server)return;this.httpServer=void 0;const closed=new Promise(resolve4=>server.close(()=>resolve4()));server.closeIdleConnections();const forceClose=setTimeout(()=>server.closeAllConnections(),drainMs);try{await closed}finally{clearTimeout(forceClose)}}}}});var node_express_host_exports={};__export(node_express_host_exports,{DEFAULT_EXPRESS_BODY_LIMIT:()=>DEFAULT_EXPRESS_BODY_LIMIT,ExpressHostAdapter:()=>ExpressHostAdapter});var init_node_express_host=__esm({"libs/sdk/src/server/adapters/polyfills/node-express-host.ts"(){"use strict";init_express_host_adapter()}});var server_instance_exports={};__export(server_instance_exports,{FrontMcpServerInstance:()=>FrontMcpServerInstance});import{getRuntimeContext as getRuntimeContext24,isProduction as isProduction8}from"@frontmcp/utils";var DEFAULT_CORS,FrontMcpServerInstance;var init_server_instance=__esm({"libs/sdk/src/server/server.instance.ts"(){"use strict";init_common();init_path_utils();init_health2();init_mcp_registry_utils();init_metrics2();init_cors_env();init_security_audit();DEFAULT_CORS=void 0;FrontMcpServerInstance=class extends FrontMcpServer{config;host;healthRouteRegistered=false;_healthService;_healthConfig;metricsRouteRegistered=false;_metricsService;_metricsConfig;constructor(httpConfig){super();this.config=httpConfig;this.setupDefaults()}setupDefaults(){if(typeof this.config.hostFactory==="function"){const{hostFactory,...config}=this.config;this.host=this.config.hostFactory(config)}else if(this.config.hostFactory!==void 0){this.host=this.config.hostFactory}else{const cors2=resolveHttpCors(this.config.cors);const corsConfig=cors2===false?void 0:cors2??DEFAULT_CORS;const{ExpressHostAdapter:ExpressHostAdapter2}=(init_node_express_host(),__toCommonJS(node_express_host_exports));this.host=new ExpressHostAdapter2({...corsConfig?{cors:corsConfig}:{},publicCorsPaths:[serverCardPath({entryPath:resolveEntryPath(this.config.entryPath),routeBase:""})],...this.config.security?{security:this.config.security}:{},...this.config.securityHeaders?{securityHeaders:this.config.securityHeaders}:{},...this.config.bodyLimit!==void 0?{bodyLimit:this.config.bodyLimit}:{},...this.config.urlencodedLimit!==void 0?{urlencodedLimit:this.config.urlencodedLimit}:{}})}}registerMiddleware(entryPath,handler){return this.host.registerMiddleware(entryPath,handler)}registerRoute(method,path4,handler){return this.host.registerRoute(method,path4,handler)}setHealthService(healthService,healthConfig){this._healthService=healthService;this._healthConfig=healthConfig}setHealthConfig(healthConfig){this._healthConfig=healthConfig}setMetricsService(metricsService,metricsConfig){this._metricsService=metricsService;this._metricsConfig=metricsConfig}setMetricsConfig(metricsConfig){this._metricsConfig=metricsConfig}prepare(){if(!this.healthRouteRegistered){this.healthRouteRegistered=true;if(this._healthService&&this._healthConfig){registerHealthRoutes(this,this._healthService,this._healthConfig)}else if(this._healthConfig?.enabled===false){}else{this.registerRoute("GET","/health",async(req,res)=>{res.status(200).json({status:"ok"})})}}if(!this.metricsRouteRegistered){this.metricsRouteRegistered=true;if(this._metricsService&&this._metricsConfig?.enabled===true){registerMetricsRoutes(this,this._metricsService,this._metricsConfig)}}this.host.prepare()}getHandler(){return this.host.getHandler()}async start(){this.prepare();const deploymentMode=getRuntimeContext24().deployment;const bindAddress=resolveBindAddress(this.config.security,deploymentMode);const findings=auditSecurityDefaults({cors:this.config.cors,security:this.config.security,resolvedBindAddress:bindAddress,socketPath:this.config.socketPath,deploymentMode},isProduction8());logSecurityFindings(findings,console);await this.host.start(this.config.socketPath??this.config.port,bindAddress)}async stop(){await this.host.stop()}}}});import{ProviderScope as ProviderScope11}from"@frontmcp/di";function createMcpGlobalProviders(metadata){const isCli=!!metadata["__cliMode"];const isNoServe=metadata.serve===false;const serverProvider=isCli||isNoServe?noopServer:frontMcpServer;return[frontMcpConfig.with(metadata),serverProvider,FrontMcpContextStorage]}var frontMcpConfig,defaultHttpOptions,frontMcpServer,noopServer;var init_front_mcp_providers=__esm({"libs/sdk/src/front-mcp/front-mcp.providers.ts"(){"use strict";init_common();init_context();init_noop_server();init_front_mcp_tokens2();frontMcpConfig={with:metadata=>({name:"frontmcp:config",provide:FrontMcpConfig,scope:ProviderScope11.GLOBAL,useValue:metadata})};defaultHttpOptions=()=>({port:defaultHttpPort(),entryPath:"/mcp"});frontMcpServer=AsyncProvider({name:"frontmcp:server",scope:ProviderScope11.GLOBAL,provide:FrontMcpServer,inject:()=>[FrontMcpConfig],useFactory:async config=>{const{FrontMcpServerInstance:FrontMcpServerInstance2}=await Promise.resolve().then(()=>(init_server_instance(),server_instance_exports));return new FrontMcpServerInstance2(config.http??defaultHttpOptions())}});noopServer={name:"frontmcp:server:noop",provide:FrontMcpServer,scope:ProviderScope11.GLOBAL,useValue:new NoopFrontMcpServer}}});import{watchParent}from"@frontmcp/utils";function exitOnShutdownSignals(shutdown,options={}){const target=options.target??process;const deadlineMs=options.deadlineMs??DEFAULT_SHUTDOWN_DEADLINE_MS;let shuttingDown=false;let watcher;const begin=trigger=>{if(shuttingDown)return;shuttingDown=true;watcher?.close();const deadline=setTimeout(()=>target.exit(1),deadlineMs);shutdown(trigger).then(()=>{clearTimeout(deadline);target.exit(0)},error=>{clearTimeout(deadline);options.logger?.error("Graceful shutdown failed",error);target.exit(1)})};const onSignal=()=>begin("signal");for(const signal of SHUTDOWN_SIGNALS)target.on(signal,onSignal);if(options.whenOrphaned){watcher=watchParent({stdin:options.whenOrphaned.stdin,onGone:reason=>{options.logger?.info?.(ORPHANED_MESSAGES[reason]);begin(reason)}})}return()=>{watcher?.close();for(const signal of SHUTDOWN_SIGNALS)target.removeListener(signal,onSignal)}}var SHUTDOWN_SIGNALS,ORPHANED_MESSAGES,DEFAULT_SHUTDOWN_DEADLINE_MS,STDIO_SHUTDOWN_DEADLINE_MS,STDIO_DRAIN_MS;var init_shutdown_signals=__esm({"libs/sdk/src/front-mcp/shutdown-signals.ts"(){"use strict";SHUTDOWN_SIGNALS=["SIGTERM","SIGINT"];ORPHANED_MESSAGES={"parent-exited":"The parent process exited; shutting down","stdin-ended":"stdin ended; shutting down"};DEFAULT_SHUTDOWN_DEADLINE_MS=1e4;STDIO_SHUTDOWN_DEADLINE_MS=5e3;STDIO_DRAIN_MS=2e3}});function redirectConsoleToStderr(){const{Console}=__require("node:console");const stderrConsole=new Console({stdout:process.stderr,stderr:process.stderr});console.log=stderrConsole.log.bind(stderrConsole);console.info=stderrConsole.info.bind(stderrConsole);console.debug=stderrConsole.debug.bind(stderrConsole);console.dir=stderrConsole.dir.bind(stderrConsole);console.table=stderrConsole.table.bind(stderrConsole);console.time=stderrConsole.time.bind(stderrConsole);console.timeLog=stderrConsole.timeLog.bind(stderrConsole);console.group=stderrConsole.group.bind(stderrConsole);console.groupEnd=stderrConsole.groupEnd.bind(stderrConsole);console.count=stderrConsole.count.bind(stderrConsole)}var init_stdio_console=__esm({"libs/sdk/src/front-mcp/stdio-console.ts"(){"use strict"}});var instance_file_logger_exports={};__export(instance_file_logger_exports,{FileLogTransportInstance:()=>FileLogTransportInstance});function getFs(){return _fs??=__require("fs")}function getOs(){return _os??=__require("os")}function getPath(){return _path??=__require("path")}function stripAnsi(str){return str.split(ESC).map(s=>s.replace(/\[[0-9;]*m/,"")).join("")}var _fs,_os,_path,LOG_LEVEL_LABELS,ESC,DEFAULT_LOGS_MAX,FileLogTransportInstance;var init_instance_file_logger=__esm({"libs/sdk/src/logger/instances/instance.file-logger.ts"(){"use strict";init_common();LOG_LEVEL_LABELS={[100]:"OFF",[0]:"DEBUG",[1]:"VERBOSE",[2]:"INFO",[3]:"WARN",[4]:"ERROR"};ESC=String.fromCharCode(27);DEFAULT_LOGS_MAX=25;FileLogTransportInstance=class extends LogTransportInterface{fd;logDir;appName;constructor(){super();const rawAppName=process.env["FRONTMCP_APP_NAME"]||"frontmcp";const sanitized=rawAppName.replace(/[^a-zA-Z0-9._-]/g,"_");this.appName=sanitized.length>0?sanitized:"frontmcp";this.logDir=process.env["FRONTMCP_LOG_DIR"]||getPath().join(process.env["FRONTMCP_HOME"]||getPath().join(getOs().homedir(),".frontmcp"),"logs");const logsMax=parseInt(process.env["FRONTMCP_LOGS_MAX"]||"",10);if(logsMax===0){this.fd=void 0;return}try{getFs().mkdirSync(this.logDir,{recursive:true});const ts=new Date().toISOString().replace(/:/g,"_");const filePath=getPath().join(this.logDir,`${this.appName}-${ts}.log`);this.fd=getFs().openSync(filePath,"a");this.rotate(isNaN(logsMax)?DEFAULT_LOGS_MAX:logsMax)}catch{this.fd=void 0}}close(){if(this.fd!==void 0){try{getFs().closeSync(this.fd)}catch{}this.fd=void 0}}log(rec){if(this.fd===void 0)return;const ts=rec.timestamp.toISOString();const level=LOG_LEVEL_LABELS[rec.level]??"INFO";const prefix=rec.prefix?` [${rec.prefix}]`:"";const message=stripAnsi(String(rec.message));const line=`[${ts}] ${level}${prefix} ${message}
474
+ </html>`}]}})}});var authorities_engine_exports={};__export(authorities_engine_exports,{authoritiesFromConfig:()=>authoritiesFromConfig,createAuthoritiesEngine:()=>createAuthoritiesEngine});import{AuthoritiesContextBuilder,AuthoritiesEngine,AuthoritiesEvaluatorRegistry,AuthoritiesProfileRegistry}from"@frontmcp/auth";function createAuthoritiesEngine(config){const profileRegistry=new AuthoritiesProfileRegistry;if(config["profiles"]){profileRegistry.registerAll(config["profiles"])}const evaluatorRegistry=new AuthoritiesEvaluatorRegistry;if(config["evaluators"]){evaluatorRegistry.registerAll(config["evaluators"])}return new AuthoritiesEngine(profileRegistry,evaluatorRegistry)}function authoritiesFromConfig(config){return{engine:createAuthoritiesEngine(config),contextBuilder:new AuthoritiesContextBuilder({claimsMapping:config["claimsMapping"],claimsResolver:config["claimsResolver"],relationshipResolver:config["relationshipResolver"]}),scopeMapping:config["scopeMapping"]}}var init_authorities_engine=__esm({"libs/sdk/src/front-mcp/authorities-engine.ts"(){"use strict"}});var send_elicitation_result_tool_exports={};__export(send_elicitation_result_tool_exports,{SendElicitationResultTool:()=>SendElicitationResultTool});import{internalZ as z129}from"@frontmcp/lazy-zod";var inputSchema42,SendElicitationResultTool;var init_send_elicitation_result_tool=__esm({"libs/sdk/src/elicitation/send-elicitation-result.tool.ts"(){"use strict";init_common();init_call_surface();init_errors();init_fallback_helper();inputSchema42={elicitId:z129.string().describe("The elicitation ID from the pending request"),action:z129.enum(["accept","cancel","decline"]).describe("User action: accept (submit), cancel, or decline"),content:z129.unknown().optional().describe("User response content (required for accept action)")};SendElicitationResultTool=class extends ToolContext{async execute(input){const{elicitId,action,content}=input;this.logger.info("sendElicitationResult: processing",{elicitId,action});const store=this.scope.elicitationStore;if(!store){this.logger.error("sendElicitationResult: scope or elicitationStore not available");return{content:[{type:"text",text:"Error: Elicitation store not available. Server may not be properly configured."}],isError:true}}const pending=await store.getPendingFallback(elicitId);if(!pending){this.logger.warn("sendElicitationResult: no pending elicitation found",{elicitId});return{content:[{type:"text",text:`Error: No pending elicitation found for ID: ${elicitId}. The request may have expired or already been processed.`}],isError:true}}const caller=resolveElicitationOwner(this.tryGetContext());if(!pending.owner||pending.owner!==caller){this.logger.warn("sendElicitationResult: refused a result from a caller the elicitation was not asked of",{elicitId});throw new ElicitationNotOwnedError(elicitId)}if(Date.now()>pending.expiresAt){await store.deletePendingFallback(elicitId);this.logger.warn("sendElicitationResult: elicitation expired",{elicitId});return{content:[{type:"text",text:`Error: Elicitation request has expired. Please try the original operation again.`}],isError:true}}const elicitResult={status:action,...action==="accept"&&content!==void 0&&{content}};await store.setResolvedResult(elicitId,elicitResult,pending.sessionId);await store.deletePendingFallback(elicitId);this.logger.info("sendElicitationResult: re-invoking original tool",{elicitId,toolName:pending.toolName});const ctx=this.tryGetContext();if(ctx){ctx.setPreResolvedElicitResult(elicitResult)}try{const toolResult=await this.scope.runFlowForOutput("tools:call-tool",{request:{method:"tools/call",params:{name:pending.toolName,arguments:pending.toolInput}},ctx:{authInfo:this.authInfo,requestId:this.tryGetContext()?.requestId??this.runId,surface:getCallSurface(),...this.signal?{signal:this.signal}:{}}});this.logger.info("sendElicitationResult: original tool completed",{elicitId,toolName:pending.toolName});await store.publishFallbackResult(elicitId,pending.sessionId,{success:true,result:toolResult});await store.deleteResolvedResult(elicitId);return toolResult}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);await store.publishFallbackResult(elicitId,pending.sessionId,{success:false,error:errorMessage2});await store.deleteResolvedResult(elicitId);this.logger.error("sendElicitationResult: original tool failed",{elicitId,toolName:pending.toolName,error:errorMessage2});return{content:[{type:"text",text:`Error re-invoking ${pending.toolName}: ${errorMessage2}`}],isError:true}}}};SendElicitationResultTool=__decorateClass([Tool({name:"sendElicitationResult",description:'Submit user response for a pending elicitation request. Use this after collecting user input for a tool that requested elicitation. Actions: "accept" (user submitted response), "cancel" (user cancelled), "decline" (user declined to answer).',inputSchema:inputSchema42,hideFromDiscovery:true})],SendElicitationResultTool)}});import"reflect-metadata";import{createGuardManager}from"@frontmcp/guard";import{createRedisClient as createRedisClient3,getEnvFlag,getMachineId as getMachineId5,getRuntimeContext as getRuntimeContext22,isEdgeRuntime,mkdir as mkdir2}from"@frontmcp/utils";var SCOPE_NON_DISPATCHABLE_FLOWS,Scope;var init_scope_instance=__esm({"libs/sdk/src/scope/scope.instance.ts"(){"use strict";init_adapter_registry();init_agent_registry();init_app_registry();init_auth_registry();init_direct_public_auth();init_channel_utils();init_common();init_sqlite();init_forward_headers_utils();init_path_utils();init_complete_flow();init_context();init_metadata_utils();init_errors();init_plugin_errors();init_flow_registry();init_authorities_rules_check();init_detached_job_flag();init_direct_only_flag();init_hook_order();init_hook_registry();init_hooks_utils();init_job_utils();init_set_level_flow();init_instructions_budget_check();init_notification();init_offload_service();init_enforced_metadata_check();init_plugin_registry();init_prompt_registry();init_provider_registry();init_materialized_resources();init_resource_registry();init_skill_validation_error();init_skill_scope_helper();init_skill_registry();init_live_surface();init_task_backend_utils();init_tool_output_policy();init_tool_instance();init_tool_registry();init_tool_utils();init_serving_mode_default();init_ui_shared();init_request_state();init_session_mode_check();init_browser_stores();init_dev_events_observability();init_server_entries_helper();init_startup_report_helper();SCOPE_NON_DISPATCHABLE_FLOWS=new Set(["http:request"]);Scope=class _Scope extends ScopeEntry{id;globalProviders;logger;scopeProviders;scopeAuth;scopeFlows;scopeApps;scopeHooks;scopeTools;scopeResources;scopePrompts;scopeAgents;scopeSkills;scopePlugins;transportService;notificationService;liveSurface;haRedisClient;haSubscriberClient;transportBus;sessionRelayHandle;toolUIRegistry;authUiRegistry;entryPath;routeBase;orchestrated=false;server;registeredHttpRoutes=[];httpRouteRegistrar={registerRoute:(method,path4,handler)=>{this.registeredHttpRoutes.push({method,path:path4,handler});return this.server.registerRoute(method,path4,handler)}};_elicitationStore;elicitationBackendType;_persistentQuestions;_taskStore;taskBackendType;_taskRegistry;_skillSession;_eventStore;_scopeJobs;_scopeWorkflows;_jobExecutionManager;_jobStateStore;_jobDefinitionStore;_rateLimitManager;_publicAccessGuard;lateGuardSetup=Promise.resolve();_authoritiesEngine;_authoritiesContextBuilder;_authoritiesScopeMapping;scopeAdapters;_scopeChannels;_channelNotificationService;_channelEventBus;_channelTeardown;_healthService;cliMode;directOnly;constructor(rec,globalProviders){super(rec,rec.provide);this.id=rec.metadata.id;this.logger=globalProviders.get(FrontMcpLogger).child("FrontMcp.MultiAppScope");this.globalProviders=globalProviders;this.server=this.globalProviders.get(FrontMcpServer);this.entryPath=resolveEntryPath(rec.metadata.http?.entryPath);if(rec.kind==="SPLIT_BY_APP"){this.routeBase=`/${rec.metadata.id}`}else{this.routeBase=""}this.cliMode=!!rec.metadata["__cliMode"];this.directOnly=isDirectOnly(rec.metadata);const distributedMode=rec.metadata.transport?.distributedMode;const providerCaching=rec.metadata.transport?.providerCaching;const userProviders=rec.metadata.providers??[];this.scopeProviders=new ProviderRegistry([...userProviders,...this.defaultScopeProviders],globalProviders,{distributedMode,providerCaching});this.ready=this.initialize()}async initialize(){const startedAt=Date.now();await this.scopeProviders.ready;const scopeRef={kind:"scope",id:this.id,ref:_Scope};const scopeProviders=this.scopeProviders;const perf=getEnvFlag("FRONTMCP_PERF");const t0=perf?performance.now():0;const mark=perf?label=>this.logger.info(`[PERF] ${label}: ${(performance.now()-t0).toFixed(1)}ms`):()=>{};await refuseStoresInBrowser(this.metadata);const httpServing=this.directOnly?void 0:await Promise.resolve().then(()=>(init_http_scope_helper(),http_scope_helper_exports));const createPrimaryAuth2=await this.primaryAuthFactory();this.scopeHooks=new HookRegistry(scopeProviders,[]);this.scopeFlows=new FlowRegistry(scopeProviders,httpServing?[httpServing.HttpRouteFlow,httpServing.HttpRequestFlow,httpServing.HttpIpFilterFlow]:[]);this.scopeAuth=new AuthRegistry(this,scopeProviders,[],scopeRef,this.metadata.auth,createPrimaryAuth2);this.scopeApps=new AppRegistry(this.scopeProviders,this.metadata.apps,scopeRef);this.logger.info(`Initializing ${this.metadata.apps.length} app(s)...`);const transportConfig=this.metadata.transport;const isDistributed=getRuntimeContext22().deployment==="distributed";if(isDistributed&&this.metadata.redis&&!this.cliMode&&!this.directOnly){const ha=await Promise.resolve().then(()=>(init_ha(),ha_exports));try{const haRedis=this.createHaRedisClient();const haSubscriber=this.createHaRedisClient("ha-subscriber");this.haManager=ha.HaManager.create({redis:haRedis,pubsubPublisher:haRedis,pubsubSubscriber:haSubscriber,nodeId:getMachineId5(),config:ha.resolveHaConfigFromEnv(),logger:this.logger});await this.haManager.start();this.logger.info("[HA] Manager started for distributed deployment")}catch(err){this.logger.warn("[HA] Failed to start HA manager \u2014 running without HA",{error:err});this.haManager=void 0;await this.closeHaRedisClient()}}let transportBus;if(this.haManager&&this.haRedisClient&&isDistributed){const bus=await Promise.resolve().then(()=>(init_bus(),bus_exports));const haConfig=this.haManager.getConfig();transportBus=new bus.RedisTransportBus(this.haRedisClient,getMachineId5(),{haKeyPrefix:haConfig.redisKeyPrefix,retryAfterSeconds:Math.ceil(haConfig.heartbeatTtlMs/1e3),logger:this.logger});this.transportBus=transportBus;this.logger.info("[HA] Transport bus created for distributed session routing")}const resolvedTopLevelSqlite=await this.resolveTopLevelSqlite();let effectivePersistence=transportConfig?.persistence;if(effectivePersistence===void 0&&resolvedTopLevelSqlite){effectivePersistence={sqlite:resolvedTopLevelSqlite}}if(httpServing){const service=new httpServing.TransportService(this,effectivePersistence,transportBus);this.transportService=service;this.onDispose(()=>service.destroy());httpServing.loadStreamableHttpTransportOnStart(this)}warnIfRequestStateKeyNotShared({logger:this.logger,metadata:this.metadata});warnIfSessionModeIgnored({logger:this.logger,transport:transportConfig,session:this.metadata.session});const transportService=this.transportService;if(this.haManager&&isDistributed&&transportService?.getBackendKind()==="redis"){this.haManager.startOrphanScanner({sessionKeyPrefix:transportService.getSessionKeyPrefix(),onOrphan:(sessionId,previousNodeId,session)=>transportService.adoptClaimedSession(sessionId,previousNodeId,session)})}if(getRuntimeContext22().deployment==="serverless"){const protocolCfg=transportConfig?.protocol;const hasSSE=typeof protocolCfg==="string"?protocolCfg!=="stateless-api":protocolCfg?.sse===true;if(hasSSE){this.logger.warn('[Deployment] SSE transport is not supported in serverless deployments. Consider using protocol: "stateless-api" for serverless targets.')}}const effectiveEventStoreConfig=transportConfig?.eventStore??(isDistributed&&this.metadata.redis&&!this.cliMode&&!this.directOnly?{enabled:true,provider:"redis",redis:this.metadata.redis}:void 0);if(effectiveEventStoreConfig?.enabled&&!this.cliMode&&!this.directOnly){const{createEventStore:createEventStore2}=await Promise.resolve().then(()=>(init_event_stores(),event_stores_exports));const{eventStore}=createEventStore2(effectiveEventStoreConfig,this.logger);this._eventStore=eventStore;this.logger.info("EventStore initialized for SSE resumability",{provider:effectiveEventStoreConfig.provider??"memory",autoEnabled:!transportConfig?.eventStore&&isDistributed})}const elicitationEnabled=this.metadata.elicitation?.enabled===true&&!this.cliMode;const elicitationPromise=elicitationEnabled?(async()=>{const inheritedRedis=this.metadata.elicitation?.redis??this.metadata.redis;const elicitationInMemory=this.metadata.elicitation?.store===false;const elicitationRedis=elicitationInMemory?void 0:inheritedRedis;const elicitationSqlite=elicitationInMemory||elicitationRedis?void 0:resolvedTopLevelSqlite;const persistent=this.metadata.elicitation?.persistent;const questionsHelper=persistent?await Promise.resolve().then(()=>(init_question_scope_helper(),question_scope_helper_exports)):void 0;const onEdgeRuntime2=isEdgeRuntime();const questionsStorage=questionsHelper?.persistentQuestionsSettings(persistent,onEdgeRuntime2).storage;const questionsRedis=!elicitationInMemory&&!elicitationRedis&&questionsStorage?.type==="redis"?questionsStorage:void 0;const{createElicitationStore:createElicitationStore2}=await Promise.resolve().then(()=>(init_elicitation_store_factory(),elicitation_store_factory_exports));const{store:elicitStore,type:elicitType,storage:elicitStorage}=await createElicitationStore2({redis:elicitationRedis,storage:elicitationInMemory?{type:"memory"}:questionsRedis,sqlite:elicitationSqlite,keyPrefix:elicitationRedis?.keyPrefix??"mcp:elicit:",logger:this.logger,isEdgeRuntime:onEdgeRuntime2});this._elicitationStore=elicitStore;this.elicitationBackendType=elicitType;if(elicitStorage){this.onDispose(async()=>{await elicitStore.destroy?.();await elicitStorage.disconnect()})}if(questionsHelper){const questions=await questionsHelper.openPersistentQuestions({persistent,serverName:this.metadata.info.name,redis:inheritedRedis,sqlite:resolvedTopLevelSqlite,onEdgeRuntime:onEdgeRuntime2,logger:this.logger});this._persistentQuestions=questions;if(questions)this.onDispose(()=>questions.store.close())}})():void 0;const tasksConfig=this.metadata.tasks;const tasksInMemory=tasksConfig?.store===false;const tasksMemoryStorage=tasksInMemory?{type:"memory"}:void 0;const serverRedisForTasks=tasksInMemory?void 0:this.metadata.redis;const serverSqliteForTasks=tasksInMemory?void 0:resolvedTopLevelSqlite;const tasksExplicitlyDisabled=tasksConfig?.enabled===false;const tasksExplicitlyEnabled=tasksConfig?.enabled===true;const isTaskWorker=!!this.metadata["__taskWorkerMode"];const hasPersistentBackend=Boolean(tasksConfig?.sqlite||tasksConfig?.redis||serverRedisForTasks||serverSqliteForTasks);const tasksEnabledForCli=this.cliMode&&hasPersistentBackend;const hasDistributedTaskBackend=Boolean(tasksConfig?.redis??serverRedisForTasks);const onEdgeRuntime=isEdgeRuntime();const tasksUnavailableOnEdge=onEdgeRuntime&&!hasDistributedTaskBackend&&!tasksExplicitlyEnabled;if(tasksUnavailableOnEdge){this.logger.info("[tasks] Background tasks are unavailable on this edge/serverless runtime: the in-process runner cannot continue past the HTTP response, and an in-memory store is not shared between isolates. Serving without tasks. Configure `tasks.redis` (Upstash Redis over HTTP works on Workers) to enable them.")}const gateTasksRedis=tasksConfig?.redis??serverRedisForTasks;const tasksUseSqlite=Boolean(tasksConfig?.sqlite??(gateTasksRedis?void 0:serverSqliteForTasks));const tasksUnavailableOnVercelKv=!tasksExplicitlyEnabled&&!tasksUseSqlite&&resolvesToVercelKvTaskBackend(gateTasksRedis,tasksMemoryStorage);if(tasksUnavailableOnVercelKv&&!tasksExplicitlyDisabled){this.logger.warn("[tasks] Background tasks are disabled: Vercel KV has no pub/sub, which task results and cancellation require. Serving without tasks. Configure `tasks.redis` with Redis or Upstash to enable them.")}const shouldInitTasks=!tasksExplicitlyDisabled&&!tasksUnavailableOnEdge&&!tasksUnavailableOnVercelKv&&(!this.cliMode||tasksEnabledForCli||isTaskWorker);const useCliRunner=!isTaskWorker&&tasksConfig?.runner==="cli";let taskModule;let cliTaskRunner;const tasksPromise=shouldInitTasks?(async()=>{taskModule=await Promise.resolve().then(()=>(init_task_scope_runtime(),task_scope_runtime_exports));if(useCliRunner)cliTaskRunner=(await Promise.resolve().then(()=>(init_cli_task_runner(),cli_task_runner_exports))).CliTaskRunner;const tasksRedis=tasksConfig?.redis??serverRedisForTasks;const tasksSqlite=tasksConfig?.sqlite??(tasksRedis?void 0:serverSqliteForTasks);const onEdge=onEdgeRuntime;if(onEdge){const msg="[tasks] Background tasks are enabled on an edge/serverless runtime. The in-process runner cannot continue past the HTTP response on this platform \u2014 task bodies will not execute. Run on a long-lived Node process, or set `tasks.enabled: false`.";if(tasksConfig?.strict){throw new Error(msg+" (tasks.strict: true refuses startup)")}this.logger.warn(msg)}const{store:taskStore,type:taskType,storage:taskStorage}=await taskModule.createTaskStore({storage:tasksMemoryStorage,redis:tasksRedis,sqlite:tasksSqlite,keyPrefix:tasksConfig?.keyPrefix??"mcp:task:",logger:this.logger,isEdgeRuntime:onEdge});this._taskStore=taskStore;this.onDispose(async()=>{await taskStore.destroy?.();await taskStorage?.disconnect()});this.taskBackendType=taskType;this._taskRegistry=new taskModule.TaskRegistry({enabled:tasksConfig?.enabled,defaultTtlMs:tasksConfig?.defaultTtlMs,maxTtlMs:tasksConfig?.maxTtlMs,defaultPollIntervalMs:tasksConfig?.defaultPollIntervalMs,maxConcurrentPerSession:tasksConfig?.maxConcurrentPerSession,keyPrefix:tasksConfig?.keyPrefix,strict:tasksConfig?.strict,sqlite:tasksConfig?.sqlite,cliRunnerCommand:tasksConfig?.cliRunnerCommand},this.logger)})():void 0;const installTaskRunner=shouldInitTasks?()=>{const tasks=taskModule;if(!this._taskStore||!this._taskRegistry||!tasks)return;if(useCliRunner&&!tasksConfig?.sqlite&&!tasksConfig?.redis&&!serverRedisForTasks&&!serverSqliteForTasks){throw new Error('[tasks] runner: "cli" requires a persistent backend (`tasks.sqlite`, `tasks.redis`, or a top-level `sqlite` without `tasks.store: false`) \u2014 the detached worker cannot share an in-memory store with this host.')}const runner=cliTaskRunner?new cliTaskRunner({store:this._taskStore,command:tasksConfig?.cliRunnerCommand,logger:this.logger}):new tasks.InProcessTaskRunner({scope:this,store:this._taskStore,registry:this._taskRegistry,notifier:new tasks.TaskNotifier(this.notificationService,this.logger),logger:this.logger});this._taskRegistry.setRunner(runner);this.logger.info(`[tasks] runner installed: ${runner.kind}`)}:void 0;const throttleConfig=this.metadata.throttle;const rateLimitPromise=throttleConfig?.enabled&&!this.cliMode?createGuardManager({config:{...throttleConfig,storage:guardStorageInBrowser(throttleConfig.storage,this.logger)},logger:this.logger}).then(mgr=>{this._rateLimitManager=mgr}):void 0;const batch1=[this.scopeHooks.ready,this.scopeFlows.ready,this.scopeAuth.ready,this.scopeApps.ready];if(elicitationPromise)batch1.push(elicitationPromise);if(tasksPromise)batch1.push(tasksPromise);if(rateLimitPromise)batch1.push(rateLimitPromise);await Promise.all(batch1);const serverHooks=serverProviderHooks(this.scopeProviders,this.metadata.providers,scopeRef);if(serverHooks.length>0)await this.scopeHooks.registerHooks(false,...serverHooks);this.logger.verbose("HookRegistry initialized");this.logger.verbose("FlowRegistry initialized");if(this.transportService)this.logger.verbose("TransportService initialized");this.logger.verbose("AuthRegistry initialized");mark("batch1:parallel (hooks+flows+auth+apps)");let topLevelSqliteUsed=this.transportService?.isSessionStoreConfigured()===true&&this.transportService.getBackendKind()==="sqlite"||this.taskBackendType==="sqlite"||this.elicitationBackendType==="sqlite"||this._persistentQuestions?.type==="sqlite";const serverPlugins=[...this.metadata.plugins??[]];const appPlugins=this.scopeApps.getApps().flatMap(app=>"plugins"in app.metadata?app.metadata.plugins??[]:[]);const impliedObservability=this.metadata.observability===void 0?devEventsObservabilityConfig([...serverPlugins,...appPlugins]):void 0;const observabilityConfig=this.metadata.observability??impliedObservability;if(observabilityConfig){const{observabilityPlugins:observabilityPlugins2}=await Promise.resolve().then(()=>(init_observability_scope_helper(),observability_scope_helper_exports));serverPlugins.push(...observabilityPlugins2({config:observabilityConfig,logger:this.logger,globalProviders:this.globalProviders,implied:impliedObservability!==void 0}))}if(serverPlugins.length>0){const serverPluginScopeInfo={ownScope:this,parentScope:void 0,isStandaloneApp:false};this.scopePlugins=new PluginRegistry(this.scopeProviders,serverPlugins,scopeRef,serverPluginScopeInfo)}if(this.scopePlugins){await this.scopePlugins.ready}if(this.metadata.adapters?.length){const scopeAdapters=new AdapterRegistry(this.scopeProviders,this.metadata.adapters);this.scopeAdapters=scopeAdapters;await scopeAdapters.ready;this.onDispose(()=>scopeAdapters.dispose())}await registerServerEntries(this.scopeProviders,this.metadata,this.scopeApps.getApps().map(app=>app.id));await this.initAuthoritiesFromConfig();this.scopeTools=new ToolRegistry(this.scopeProviders,[],scopeRef);this.scopeResources=new ResourceRegistry(this.scopeProviders,[],scopeRef);this.scopePrompts=new PromptRegistry(this.scopeProviders,[],scopeRef);this.scopeAgents=new AgentRegistry(this.scopeProviders,[],scopeRef);const skillsConfig=this.metadata.skillsConfig;this.scopeSkills=new SkillRegistry(this.scopeProviders,this.metadata.skills??[],scopeRef,{...skillsConfig?.scoring?{scoring:skillsConfig.scoring}:{},...skillsConfig?.failOnInvalidSkills!==void 0&&{failOnInvalidSkills:skillsConfig.failOnInvalidSkills}});await Promise.all([this.scopeTools.ready,this.scopeResources.ready,this.scopePrompts.ready,this.scopeAgents.ready,this.scopeSkills.ready]);if(this.scopePlugins){const pluginNames=this.scopePlugins.getPluginNames();this.logger.verbose(`PluginRegistry initialized (${pluginNames.length} plugin(s): [${pluginNames.join(", ")}])`)}const toolNames=this.scopeTools.getTools(true).map(t=>t.metadata.name);this.logger.verbose(`ToolRegistry initialized with initial ${toolNames.length} tool(s): [${toolNames.join(", ")}]`);this.logger.verbose(`ResourceRegistry initialized (${this.scopeResources.getResources().length} resource(s))`);this.logger.verbose(`PromptRegistry initialized (${this.scopePrompts.getPrompts().length} prompt(s))`);this.logger.verbose(`AgentRegistry initialized (${this.scopeAgents.getAgents().length} agent(s))`);this.logger.verbose(`SkillRegistry initialized (${this.scopeSkills.getSkills().length} skill(s))`);mark("batch2:parallel (tools+resources+prompts+agents+skills+plugins)");this.validateAuthoritiesConfig();this.validateEnforcedMetadata();checkHookOrder(hookRunsOf(this.scopeHooks),message=>this.logger.warn(message));for(const message of describeUnlistedOutputSchemas(this))this.logger.warn(message);await this.initGuardForDeclaredLimits();if(elicitationEnabled){await this.registerSendElicitationResultTool(scopeRef)}let uiResolver;if(!this.cliMode){const cdnOverrides=this.metadata.ui?.cdnOverrides;if(cdnOverrides&&Object.keys(cdnOverrides).length>0){const{createResolverWithOverrides:createResolverWithOverrides2}=__require("@frontmcp/uipack/resolver");uiResolver=createResolverWithOverrides2(cdnOverrides);this.logger.verbose("Created UI resolver with CDN overrides",{overrides:Object.keys(cdnOverrides)})}}this.toolUIRegistry=new ToolUIRegistry(uiResolver,{escapeStringResults:this.metadata.ui?.escapeStringResults,logger:this.logger});if(!this.cliMode){await this.compileUIWidgets()}if(!this.cliMode){await this.buildAuthUiRegistry()}const dynamicSkills=pluginsRegisterDynamicSkills([...serverPlugins,...appPlugins]);if(this.scopeSkills.hasAny()||dynamicSkills){const[skillSession,{createSkillToolGuardHook:createSkillToolGuardHook2}]=await Promise.all([Promise.resolve().then(()=>(init_session2(),session_exports)),Promise.resolve().then(()=>(init_hooks(),hooks_exports))]);const store=skillSession.createSkillSessionStore({type:"memory"});this._skillSession=new skillSession.SkillSessionManager({defaultPolicyMode:"permissive"},this.logger,store);const GuardHookClass=createSkillToolGuardHook2(this._skillSession,{logger:this.logger,trackToolCalls:true});const guardHookInstance=new GuardHookClass;const hookRecords=normalizeHooksFromCls(guardHookInstance);if(hookRecords.length>0){await this.scopeHooks.registerHooks(false,...hookRecords);this.logger.verbose("Skill tool authorization guard hook registered")}this.logger.verbose("Skill session manager initialized",{storeType:store.type})}if(this.scopeSkills.hasAny()){try{const report=await this.scopeSkills.validateAllTools();if(report.warningCount>0){this.logger.verbose("Skill validation completed with warnings",{totalSkills:report.totalSkills,warningCount:report.warningCount})}}catch(error){if(error instanceof SkillValidationError){this.logger.error("Skill validation failed",{failedSkills:error.failedSkills.map(s=>({name:s.skillName,missingTools:s.missingTools}))});throw error}throw error}}await registerSkillCapabilities({skillRegistry:this.scopeSkills,flowRegistry:this.scopeFlows,resourceRegistry:this.scopeResources,providers:this.scopeProviders,skillsConfig:this.metadata.skillsConfig,logger:this.logger,dynamicSkills});const jobsConfig=this.metadata.jobs;const metaRecord=this.metadata;const jobsList=metaRecord["jobTypes"]??[];const workflowsList=metaRecord["workflowTypes"]??[];const{items:appJobs,providers:jobProviders}=this.appEntryProviders("jobs",normalizeJob);const appWorkflows=[];for(const app of this.scopeApps.getApps()){const appMeta=app.metadata;if(Array.isArray(appMeta["workflows"]))appWorkflows.push(...appMeta["workflows"])}const allJobs=[...jobsList,...appJobs];const allWorkflows=[...workflowsList,...appWorkflows];const hasJobDeclarations=allJobs.length>0||allWorkflows.length>0;const explicitlyDisabled=jobsConfig?.enabled===false;const explicitlyEnabled=jobsConfig?.enabled===true;const autoEnabled=!explicitlyEnabled&&!explicitlyDisabled&&hasJobDeclarations;const effectivelyEnabled=explicitlyEnabled||autoEnabled;if(explicitlyDisabled&&hasJobDeclarations){this.logger.warn(`Jobs are explicitly disabled but ${allJobs.length} job(s) and ${allWorkflows.length} workflow(s) were declared on @App. Agents will NOT be able to invoke them \u2014 remove jobs.enabled: false or drop the @App({ jobs }) declarations.`)}if(effectivelyEnabled){if(autoEnabled){this.logger.info(`Jobs auto-enabled: detected ${allJobs.length} job(s) and ${allWorkflows.length} workflow(s) in @App declarations. Their runs are kept in jobs.store, else the top-level redis or sqlite, else in memory.`)}const notifyFn=async data=>{if(this.notificationService){this.logger.debug("Job notification",data)}};const{registerJobCapabilities:registerJobCapabilities2,resolveJobsStore:resolveJobsStore2,jobsServerStore:jobsServerStore2}=await Promise.resolve().then(()=>(init_job_scope_helper(),job_scope_helper_exports));refuseServerStoresInBrowser({jobs:jobsServerStore2(jobsConfig?.store,this.metadata)});const jobsStore2=resolveJobsStore2(jobsConfig?.store,{redis:this.metadata.redis,sqlite:resolvedTopLevelSqlite});const effectiveConfig={...jobsConfig??{},enabled:true,store:jobsStore2};topLevelSqliteUsed||=Boolean(resolvedTopLevelSqlite)&&jobsStore2?.sqlite===resolvedTopLevelSqlite;const result=await registerJobCapabilities2({providers:this.scopeProviders,flowRegistry:this.scopeFlows,owner:scopeRef,jobsList:allJobs,jobProviders,workflowsList:allWorkflows,jobsConfig:effectiveConfig,logger:this.logger,notifyFn,entryServer:isEntryServer(this.metadata),jobWorker:isJobWorker(this.metadata)});this._scopeJobs=result.jobRegistry;this._scopeWorkflows=result.workflowRegistry;this._jobExecutionManager=result.executionManager;this._jobStateStore=result.stateStore;this._jobDefinitionStore=result.definitionStore;for(const toolCls of result.managementTools){try{const toolRecord=normalizeTool(toolCls);const toolInstance=new ToolInstance(toolRecord,this.scopeProviders,{kind:"scope",id:"_jobs",ref:toolCls});this.scopeTools.registerToolInstance(toolInstance)}catch(error){this.logger.warn(`Failed to register job management tool: ${error instanceof Error?error.message:String(error)}`)}}this.logger.info(`Jobs system initialized: ${this._scopeJobs.getJobs().length} jobs, ${this._scopeWorkflows.getWorkflows().length} workflows`)}if(this.metadata.sqlite&&!topLevelSqliteUsed&&getRuntimeContext22().runtime!=="browser"){this.logger.warn("[FrontMcp] Top-level `sqlite` config was provided but no subsystem consumes it (transport persistence, tasks, elicitation and jobs were all disabled or pre-configured with a different backend). Sessions will use in-memory storage. Remove the `sqlite` block or enable one of the subsystems.")}this.notificationService=new NotificationService(this);await this.notificationService.initialize();this.logger.verbose("NotificationService initialized");const liveSurface=new LiveSurface(this);liveSurface.start();this.liveSurface=liveSurface;this.onDispose(()=>liveSurface.stop());const materializedResources=new MaterializedResources(this);await materializedResources.start();this.onDispose(()=>materializedResources.stop());installTaskRunner?.();await this.scopeFlows.registryFlows([SetLevelFlow,CompleteFlow]);if(this.scopeAgents.listAllInstances().length>0){const{CallAgentFlow:CallAgentFlow2}=await Promise.resolve().then(()=>(init_flows2(),flows_exports2));await this.scopeFlows.registryFlows([CallAgentFlow2])}if(this.metadata.elicitation?.enabled===true){const{ElicitationRequestFlow:ElicitationRequestFlow2,ElicitationResultFlow:ElicitationResultFlow2}=await Promise.resolve().then(()=>(init_flows3(),flows_exports3));await this.scopeFlows.registryFlows([ElicitationRequestFlow2,ElicitationResultFlow2])}if(taskModule){const{TasksGetFlow:TasksGetFlow2,TasksResultFlow:TasksResultFlow2,TasksCancelFlow:TasksCancelFlow2,TasksListFlow:TasksListFlow2}=taskModule;await this.scopeFlows.registryFlows([TasksGetFlow2,TasksResultFlow2,TasksCancelFlow2,TasksListFlow2])}if(this.metadata.registry){const{registerMcpRegistryFlows:registerMcpRegistryFlows2}=await Promise.resolve().then(()=>(init_mcp_registry_scope_helper(),mcp_registry_scope_helper_exports));await registerMcpRegistryFlows2({flowRegistry:this.scopeFlows,registryOptions:this.metadata.registry,servesServerEndpoint:this.routeBase===""&&this.metadata.apps.length>0})}await this.auth.ready;await transportService?.ready;if(this.haManager&&this.transportBus&&transportService){const{wireSessionRelay:wireSessionRelay2}=await Promise.resolve().then(()=>(init_relay_scope_helper(),relay_scope_helper_exports));this.sessionRelayHandle=wireSessionRelay2({nodeId:getMachineId5(),haManager:this.haManager,bus:this.transportBus,transportService,notifications:this.notificationService,flows:{runFlow:(name51,input)=>this.runFlow(name51,input)},logger:this.logger})}if(httpServing){httpServing.attachHttpRoutes(this,this.globalProviders);httpServing.registerCustomHttpRoutes({routes:this.metadata.http?.routes,server:this.httpRouteRegistrar,verifySession:request2=>this.runFlow("session:verify",{request:request2}),checkClientIp:(request2,response)=>this.runFlow("http:ip-filter",{request:request2,response}),entryPath:this.entryPath,routeBase:this.routeBase,healthPaths:httpServing.servedHealthPaths(this.metadata.health),logger:this.logger})}const channelsConfig=this.metadata.channels;if(channelsConfig?.enabled){const{items:appChannels,providers:channelProviders}=this.appEntryProviders("channels",normalizeChannel);const{registerChannelCapabilities:registerChannelCapabilities2}=await Promise.resolve().then(()=>(init_channel_scope_helper(),channel_scope_helper_exports));const channelResult=await registerChannelCapabilities2({providers:this.scopeProviders,owner:scopeRef,channelsList:appChannels,channelProviders,channelsConfig,notificationService:this.notificationService,flowRegistry:this.scopeFlows,toolRegistry:this.scopeTools,http:httpServing&&{server:this.httpRouteRegistrar,checkClientIp:(request2,response)=>this.runFlow("http:ip-filter",{request:request2,response}),entryPath:this.entryPath,routeBase:this.routeBase,healthPaths:httpServing.servedHealthPaths(this.metadata.health)},logger:this.logger});this._scopeChannels=channelResult.channelRegistry;this._channelNotificationService=channelResult.channelNotificationService;this._channelEventBus=channelResult.channelEventBus;this._channelTeardown=channelResult.teardown;this.onDispose(()=>this.teardownChannels());if(!isJobWorker(this.metadata))await channelResult.connectServices()}if(httpServing&&this.metadata.health?.enabled!==false){this._healthService=new httpServing.HealthService(this.metadata.health??{},this.metadata.info);this._healthService.autoDiscoverProbes(this);this.logger.verbose(`HealthService initialized (${this._healthService.getProbeCount()} probe(s))`)}for(const message of await describeBudgetOverruns(this))this.logger.warn(message);mark("batch3:finalization");this.logger.info(`Scope ready \u2014 ${this.formatScopeSummary()}`);reportStartup(this.scopePlugins,{toolsCount:this.scopeTools.getTools(true).length,resourcesCount:this.scopeResources.getResources().length,promptsCount:this.scopePrompts.getPrompts().length,durationMs:Date.now()-startedAt,scopeId:this.id},this.logger)}async primaryAuthFactory(){if(this.directOnly&&this.metadata.auth===void 0){return(scope,_providers,options)=>new DirectPublicAuth(scope,options)}const{createPrimaryAuth:createPrimaryAuth2}=await Promise.resolve().then(()=>(init_primary_auth_factory(),primary_auth_factory_exports));return createPrimaryAuth2}async resolveTopLevelSqlite(){const raw=this.metadata.sqlite;if(!raw||getRuntimeContext22().runtime==="browser")return void 0;let finalPath=raw.path;if(!finalPath||finalPath.length===0){finalPath=resolveDefaultSqlitePath({appName:this.metadata.info?.name,cliMode:this.cliMode});this.logger.info("[FrontMcp] No `sqlite.path` set \u2014 using default",{path:finalPath})}try{const{dirname:dirname10}=__require("path");await mkdir2(dirname10(finalPath),{recursive:true})}catch(err){this.logger.warn("[FrontMcp] Could not ensure sqlite parent directory exists",{path:finalPath,error:err.message})}return{...raw,path:finalPath}}async compileUIWidgets(){const toolsWithUI=this.scopeTools.getTools(true).filter(t=>hasUIConfig(t.metadata));if(toolsWithUI.length===0)return;const[{describeIgnoredUiOptions:describeIgnoredUiOptions2,describeServingModeDefault:describeServingModeDefault2},{StaticWidgetResourceTemplate:StaticWidgetResourceTemplate2}]=await Promise.all([Promise.resolve().then(()=>(init_ui_option_warnings(),ui_option_warnings_exports)),Promise.resolve().then(()=>(init_ui_resource_template(),ui_resource_template_exports)),this.toolUIRegistry.load()]);for(const tool of toolsWithUI){const resourceUri=tool.metadata.ui?.resourceUri;this.toolUIRegistry.registerTool(tool.metadata.name,typeof resourceUri==="string"?resourceUri:void 0);this.toolUIRegistry.checkTemplate(tool.metadata.name,tool.metadata.ui?.template);for(const message of describeIgnoredUiOptions2(tool.metadata.name,tool.metadata.ui)){this.logger.warn(message)}}for(const message of describeServingModeDefault2("`@FrontMcp({ ui })`",this.metadata.ui?.servingMode)){this.logger.warn(message)}for(const app of this.apps.getApps()){const appMode=app.metadata.ui?.servingMode;for(const message of describeServingModeDefault2(`App "${app.id}" \`@App({ ui })\``,appMode)){this.logger.warn(message)}}this.scopeResources.registerDynamicResource(StaticWidgetResourceTemplate2);this.logger.verbose(`Registered UI resource template for ${toolsWithUI.length} tool(s) with UI configs`);const servingModes=new Map(toolsWithUI.map(t=>[t,toolServingMode(t,this)]));const staticModeTools=toolsWithUI.filter(t=>t.metadata.ui&&servingModes.get(t)==="static"&&t.metadata.ui.template);if(staticModeTools.length>0){let staticCompiledCount=0;await Promise.all(staticModeTools.map(async tool=>{const uiConfig=tool.metadata.ui;if(!uiConfig?.template){this.logger.warn(`Skipping static widget pre-compile for tool "${tool.metadata.name}" due to missing ui.template`);return}try{await this.toolUIRegistry.compileStaticWidgetAsync({toolName:tool.metadata.name,template:uiConfig.template,uiConfig});staticCompiledCount++;this.logger.verbose(`Compiled static widget for tool: ${tool.metadata.name}`)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.error(`Failed to compile static widget for tool "${tool.metadata.name}": ${errorMessage2}`)}}));this.logger.info(`Pre-compiled ${staticCompiledCount}/${staticModeTools.length} static widget(s) for static mode tools`)}const inlineTools=toolsWithUI.filter(t=>{const mode=servingModes.get(t);return t.metadata.ui&&(mode==="inline"||mode==="auto")&&t.metadata.ui.template});if(inlineTools.length>0){let inlineCompiledCount=0;await Promise.all(inlineTools.map(async tool=>{const uiConfig=tool.metadata.ui;if(!uiConfig){this.logger.warn(`Skipping lean widget pre-compile for tool "${tool.metadata.name}" due to missing ui config`);return}try{await this.toolUIRegistry.compileLeanWidgetAsync({toolName:tool.metadata.name,uiConfig});inlineCompiledCount++;this.logger.verbose(`Compiled lean widget shell for tool: ${tool.metadata.name}`)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.error(`Failed to compile lean widget shell for tool "${tool.metadata.name}": ${errorMessage2}`)}}));this.logger.info(`Pre-compiled ${inlineCompiledCount}/${inlineTools.length} lean widget shell(s) for inline mode tools`)}const hybridTools=toolsWithUI.filter(t=>t.metadata.ui&&servingModes.get(t)==="hybrid"&&t.metadata.ui.template);if(hybridTools.length>0){let hybridCompiledCount=0;await Promise.all(hybridTools.map(async tool=>{const uiConfig=tool.metadata.ui;if(!uiConfig){this.logger.warn(`Skipping hybrid widget pre-compile for tool "${tool.metadata.name}" due to missing ui config`);return}try{await this.toolUIRegistry.compileHybridWidgetAsync({toolName:tool.metadata.name,template:uiConfig.template,uiConfig});hybridCompiledCount++;this.logger.verbose(`Compiled hybrid widget shell for tool: ${tool.metadata.name}`)}catch(error){const errorMessage2=error instanceof Error?error.message:String(error);this.logger.error(`Failed to compile hybrid widget shell for tool "${tool.metadata.name}": ${errorMessage2}`)}}));this.logger.info(`Pre-compiled ${hybridCompiledCount}/${hybridTools.length} hybrid widget shell(s) for hybrid mode tools`)}}async buildAuthUiRegistry(){const auth=this.metadata.auth;const authUi=auth?.ui;const authExtras=auth?.extras;const uiSlotCount=authUi?Object.keys(authUi).length:0;const extraCount=authExtras?Object.keys(authExtras).length:0;if(uiSlotCount===0&&extraCount===0)return;let sourceDir=this.metadata.__sourceDir;if(!sourceDir){sourceDir=process.cwd();if(uiSlotCount>0){this.logger.warn(`auth.ui paths will resolve against process.cwd() ("${sourceDir}") \u2014 the declaring @FrontMcp/@App source directory could not be captured. Use absolute paths if this is wrong.`)}}const{AuthUiRegistry:AuthUiRegistry2}=await Promise.resolve().then(()=>(init_auth_ui(),auth_ui_exports));const registry=new AuthUiRegistry2(this.logger);registry.registerAuthUiMap(authUi,sourceDir);registry.registerAuthExtrasMap(authExtras);const cdnOverrides=this.metadata.ui?.cdnOverrides;if(cdnOverrides&&Object.keys(cdnOverrides).length>0){registry.setResolverOverrides(cdnOverrides)}try{await registry.warmup()}catch(error){this.logger.warn("Auth-UI registry warmup encountered errors \u2014 affected custom pages will fall back to built-in",{error:error instanceof Error?error.message:String(error)})}this.authUiRegistry=registry;this.logger.verbose(`Auth-UI registry initialized (${uiSlotCount} slot file(s), ${extraCount} extra(s))`)}formatScopeSummary(){const entries=[];const add=(count,label)=>{if(count>0)entries.push(`${count} ${label}${count!==1?"s":""}`)};add(this.scopeApps.getApps().length,"app");add(this.scopeTools.getTools(true).length,"tool");add(this.scopeResources.getResources().length,"resource");add(this.scopePrompts.getPrompts().length,"prompt");add(this.scopeAgents.getAgents().length,"agent");add(this.scopeSkills.getSkills().length,"skill");if(this._scopeJobs)add(this._scopeJobs.getJobs().length,"job");if(this._scopeWorkflows)add(this._scopeWorkflows.getWorkflows().length,"workflow");if(this._scopeChannels)add(this._scopeChannels.size,"channel");return entries.length>0?entries.join(", "):"empty"}get defaultScopeProviders(){return[{scope:ProviderScope2.GLOBAL,name:"ScopeEntry",provide:ScopeEntry,useValue:this},{scope:ProviderScope2.GLOBAL,name:"Scope",provide:_Scope,useValue:this},{scope:ProviderScope2.GLOBAL,name:"FrontMcpLogger",provide:FrontMcpLogger,useValue:this.logger},{scope:ProviderScope2.GLOBAL,name:"FrontMcpContextStorage",provide:FrontMcpContextStorage,useValue:new FrontMcpContextStorage().configure(this.metadata.fetch,{...proxyTrustOf(this.metadata.throttle),forwardsHeader:createHeaderForwarder(this.metadata.http?.forwardHeaders)})},FrontMcpContextProvider,{scope:ProviderScope2.GLOBAL,name:"OffloadService",provide:OffloadService,useValue:new OffloadService(this.metadata.offload,this.logger)}]}get auth(){return this.scopeAuth.getPrimary()}get hooks(){return this.scopeHooks}get authProviders(){return this.scopeAuth}get providers(){return this.scopeProviders}get apps(){return this.scopeApps}get tools(){return this.scopeTools}get toolUI(){return this.toolUIRegistry}get authUi(){return this.authUiRegistry}get resources(){return this.scopeResources}get prompts(){return this.scopePrompts}get agents(){return this.scopeAgents}get skills(){return this.scopeSkills}get jobs(){return this._scopeJobs}get workflows(){return this._scopeWorkflows}get channels(){return this._scopeChannels}get channelNotifications(){return this._channelNotificationService}get channelEventBus(){return this._channelEventBus}get skillSession(){return this._skillSession}get plugins(){return this.scopePlugins}get notifications(){return this.notificationService}get surface(){return this.liveSurface}get elicitationStore(){return this._elicitationStore}get persistentQuestions(){return this._persistentQuestions}get taskStore(){return this._taskStore}get tasks(){return this._taskRegistry}get eventStore(){return this._eventStore}get rateLimitManager(){return this._rateLimitManager}get publicAccessGuard(){return this._rateLimitManager??this._publicAccessGuard}get httpRoutes(){return this.registeredHttpRoutes}get healthService(){return this._healthService}get authoritiesEngine(){return this._authoritiesEngine}get authoritiesContextBuilder(){return this._authoritiesContextBuilder}get authoritiesScopeMapping(){return this._authoritiesScopeMapping}getAllSupportedScopes(){const scopes=new Set;const collectScopes=metadata=>{const authProviders=metadata?.["authProviders"];if(!Array.isArray(authProviders))return;for(const ap of authProviders){if(typeof ap==="object"&&ap!==null&&"scopes"in ap){const apScopes=ap["scopes"];if(Array.isArray(apScopes)){apScopes.forEach(s=>{if(typeof s==="string")scopes.add(s)})}}}};for(const tool of this.scopeTools.getTools(true)){collectScopes(tool.metadata)}for(const resource of this.scopeResources.getResources()){collectScopes(resource.metadata)}for(const prompt of this.scopePrompts.getPrompts()){collectScopes(prompt.metadata)}for(const agent of this.scopeAgents.getAgents()){collectScopes(agent["metadata"])}return[...scopes].sort()}registerAuthoritiesEngine(engine,contextBuilder){this._authoritiesEngine=engine;this._authoritiesContextBuilder=contextBuilder}async initAuthoritiesFromConfig(){const config=this.metadata["authorities"];if(!config)return;try{const{authoritiesFromConfig:authoritiesFromConfig2}=await Promise.resolve().then(()=>(init_authorities_engine(),authorities_engine_exports));const authorities=authoritiesFromConfig2(config);this._authoritiesEngine=authorities.engine;this._authoritiesContextBuilder=authorities.contextBuilder;this._authoritiesScopeMapping=authorities.scopeMapping;this.logger.verbose("Scope: authorities engine initialized from config")}catch(error){const msg=error instanceof Error?error.message:String(error);this.logger.warn(`Scope: authorities init failed \u2014 ${msg}`)}}appEntryProviders(key,normalize){const items=[];const providers=new Map;for(const app of this.scopeApps.getApps()){const declared=app.metadata[key];if(!Array.isArray(declared))continue;for(const item of declared){items.push(item);providers.set(normalize(item).provide,app.providers)}}return{items,providers}}async initGuardForDeclaredLimits(lateTools=[]){const throttleConfig=this.metadata.throttle;if(this._rateLimitManager||this.cliMode)return;if(throttleConfig?.enabled===false){await this.initPublicAccessGuard(throttleConfig.storage);return}const guardedEntries=[...this.scopeTools.getTools(true),...lateTools,...this.scopeAgents.getAgents(true)];const declaresLimits=guardedEntries.some(entry=>entry.metadata.rateLimit||entry.metadata.concurrency)||!!this.auth.options?.publicAccess||this.scopeAgents.listAllInstances().some(agent=>agent.declaresScopedLimits());if(!declaresLimits)return;this._rateLimitManager=await createGuardManager({config:{...throttleConfig,enabled:true,storage:guardStorageInBrowser(throttleConfig?.storage,this.logger)},logger:this.logger})}async initPublicAccessGuard(storage){const publicAccess=this.auth.options?.publicAccess;if(!publicAccess?.rateLimit||this._publicAccessGuard)return;this._publicAccessGuard=await createGuardManager({config:{enabled:true,storage:guardStorageInBrowser(storage,this.logger)},logger:this.logger})}collectEntriesWithAuthorities(){const entries=[];const add=(label,metadata)=>{const authorities=metadata?.["authorities"];if(authorities!==void 0&&authorities!==null&&authorities!==false){entries.push({label,authorities})}};for(const tool of this.scopeTools.getTools(true)){add(`Tool "${tool.name}"`,tool.metadata)}for(const resource of this.scopeResources.getResources(true)){add(`Resource "${resource.name}"`,resource.metadata)}for(const template of this.scopeResources.getResourceTemplates()){add(`Resource template "${template.name}"`,template.metadata)}for(const prompt of this.scopePrompts.getPrompts(true)){add(`Prompt "${prompt.name}"`,prompt.metadata)}for(const agent of this.scopeAgents.getAgents(true)){add(`Agent "${agent.name}"`,agent.metadata);for(const metadata of agentToolMetadata(agent)){add(`Tool "${agent.name}:${metadata.name}"`,metadata)}}for(const skill of this.scopeSkills.getSkills(true)){add(`Skill "${skill.name}"`,skill.metadata)}return entries}validateAuthoritiesConfig(){const entries=this.collectEntriesWithAuthorities();const engine=this._authoritiesEngine;if(!engine||!this._authoritiesContextBuilder){if(entries.length===0)return;const names=entries.slice(0,5).map(entry=>entry.label).join(", ");const suffix=entries.length>5?` and ${entries.length-5} more`:"";throw new AuthConfigurationError(`Authorities configuration required: ${names}${suffix} declare 'authorities' metadata but authorities enforcement is not fully configured (engine/context builder missing). Add 'authorities: { claimsMapping: {...}, profiles: {...} }' to your @FrontMcp() decorator to enable enforcement, or remove 'authorities' from entry metadata.`,{suggestion:"Add authorities config to @FrontMcp() or remove authorities from entry metadata"})}assertAuthoritiesRules(engine,entries)}async checkLateApp(app){const{tools,resources,prompts,agents,skills}=app;const problems=findUnenforcedMetadata({hooks:this.scopeHooks,tools,resources,prompts,agents,skills});if(problems.length>0)throw new UnenforcedMetadataError(problems);checkHookOrder(hookRunsOf(this.scopeHooks),message=>this.logger.warn(message));const setup=this.lateGuardSetup.then(()=>this.initGuardForDeclaredLimits(tools.getTools(true)));this.lateGuardSetup=setup.catch(()=>void 0);await setup}validateEnforcedMetadata(){const problems=findUnenforcedMetadata({hooks:this.scopeHooks,tools:this.scopeTools,resources:this.scopeResources,prompts:this.scopePrompts,agents:this.scopeAgents,skills:this.scopeSkills});if(problems.length>0)throw new UnenforcedMetadataError(problems)}async registerSendElicitationResultTool(_scopeRef){try{const{SendElicitationResultTool:SendElicitationResultTool2}=await Promise.resolve().then(()=>(init_send_elicitation_result_tool(),send_elicitation_result_tool_exports));const toolRecord=normalizeTool(SendElicitationResultTool2);const systemToolEntry=new ToolInstance(toolRecord,this.scopeProviders,{kind:"scope",id:"_system",ref:SendElicitationResultTool2});this.scopeTools.registerToolInstance(systemToolEntry);this.logger.verbose("Registered sendElicitationResult system tool")}catch(error){this.logger.warn(`Failed to register sendElicitationResult tool: ${error instanceof Error?error.message:String(error)}`)}}get pagination(){return this.metadata.pagination}registryFlows(...flows){return this.scopeFlows.registryFlows(flows)}runFlow(name51,input,deps){return this.scopeFlows.runFlow(name51,input,deps)}async findHttpFlowName(request2){return this.scopeFlows.findHttpFlowName(request2,SCOPE_NON_DISPATCHABLE_FLOWS)}async runFlowForOutput(name51,input,deps){const result=await this.scopeFlows.runFlow(name51,input,deps);if(result){return result}throw new FlowExitedWithoutOutputError}createHaRedisClient(label="ha"){const redis=this.metadata.redis;if(!redis||redis.provider==="vercel-kv"){throw new Error("Distributed HA requires a TCP Redis (ioredis); Vercel KV over REST has no Lua/pub-sub support")}const client=createRedisClient3({...redis,label,logger:this.logger});if(label==="ha-subscriber")this.haSubscriberClient=client;else this.haRedisClient=client;return client}async closeHaRedisClient(){const clients=[this.haRedisClient,this.haSubscriberClient];this.haRedisClient=void 0;this.haSubscriberClient=void 0;for(const client of clients){if(!client)continue;try{await client.quit()}catch{client.disconnect()}}}async shutdown(){if(this.sessionRelayHandle){try{await this.sessionRelayHandle.close()}catch(err){this.logger.error("[HA] Session relay shutdown failed",{error:err})}this.sessionRelayHandle=void 0}if(this.haManager){try{await this.haManager.stop()}catch(err){this.logger.error("[HA] Manager shutdown failed",{error:err})}}await this.closeHaRedisClient();await this.teardownChannels();this.httpRouteTable?.closeStreams()}async teardownChannels(){const teardown=this._channelTeardown;if(!teardown)return;this._channelTeardown=void 0;try{await teardown()}catch(err){this.logger.error("Channel teardown failed",{error:err})}}async dispose(){await this.emitDispose();await this.scopeProviders.runShutdownHooks(this.logger);this.scopeProviders.dispose();if(this.notificationService){await this.notificationService.destroy()}}}}});var init_scope=__esm({"libs/sdk/src/scope/index.ts"(){"use strict";init_scope_instance()}});function isProbe(property){return property==="then"||property==="toJSON"||property.startsWith("on")}function storeProvider(provider){storeFactories.add(provider.useFactory);return provider}function opensStore(factory){return typeof factory==="function"&&storeFactories.has(factory)}function storeNotOpened(name51){return new Proxy({},{get:(target,property,receiver)=>typeof property==="symbol"||isProbe(property)||property in target?Reflect.get(target,property,receiver):()=>{throw new StoreNotOpenedInBuildError(name51)}})}var storeFactories;var init_store_provider=__esm({"libs/sdk/src/provider/store.provider.ts"(){"use strict";init_build_store_errors();storeFactories=new WeakSet}});import{randomUUID as randomUUID30}from"@frontmcp/utils";function messageOf6(error){return error instanceof Error?error.message:String(error)}var DutyRunner;var init_duty_runner=__esm({"libs/sdk/src/duty/duty.runner.ts"(){"use strict";DutyRunner=class{constructor(options){this.options=options;this.holder=randomUUID30();this.leaseSeconds=Math.ceil(options.leaseMs/1e3);this.ranKey=`${options.key}:ran`}options;holder;leaseSeconds;ranKey;holding=false;stopped=false;reportedHeldElsewhere=false;leaseCheck;leaseTimer;leaseDeadline;tickTimer;inFlight;async start(){this.leaseCheck=this.checkLease();await this.leaseCheck}async stop(){this.stopped=true;clearTimeout(this.tickTimer);this.inFlight?.controller.abort();await this.inFlight?.done;clearTimeout(this.leaseTimer);await this.leaseCheck;clearTimeout(this.leaseDeadline);if(!this.holding)return;this.holding=false;try{await this.options.storage.deleteIfEquals(this.options.key,this.holder)}catch(error){this.options.logger.warn(`Duty "${this.options.name}": the lease store failed: ${messageOf6(error)}`)}}async checkLease(){try{if(this.holding){if(!await this.renew())this.lose("lost its lease; another process runs it now")}else if(!this.stopped){if(await this.acquire())await this.hold();else this.reportHeldElsewhere()}}catch(error){this.options.logger.warn(`Duty "${this.options.name}": the lease store failed: ${messageOf6(error)}`)}if(this.stopped&&!this.inFlight)return;this.leaseTimer=setTimeout(()=>{this.leaseCheck=this.checkLease()},this.options.leaseMs/3);this.leaseTimer.unref?.()}async acquire(){await this.options.storage.set(this.options.key,this.holder,{ttlSeconds:this.leaseSeconds,ifNotExists:true});this.holding=await this.renew();return this.holding}async renew(){const sentAt=performance.now();const renewed=await this.options.storage.expireIfEquals(this.options.key,this.holder,this.leaseSeconds);if(renewed)this.holdUntil(sentAt+this.options.leaseMs);return renewed}holdUntil(deadline){clearTimeout(this.leaseDeadline);this.leaseDeadline=setTimeout(()=>this.lose(`could not renew its lease within ${this.options.leaseMs} ms; it stops here until it gets the lease again`),deadline-performance.now());this.leaseDeadline.unref?.()}reportHeldElsewhere(){if(this.reportedHeldElsewhere)return;this.reportedHeldElsewhere=true;this.options.logger.info(`Duty "${this.options.name}" already runs elsewhere (lease "${this.options.key}"); this one takes it over if that one stops`)}async hold(){this.options.logger.info(`Duty "${this.options.name}" runs in this process every ${this.options.everyMs} ms`);const remainingSeconds=await this.options.storage.ttl(this.ranKey).catch(()=>void 0);if(this.stopped||!this.holding)return;if(remainingSeconds===void 0)return this.scheduleTick(this.options.everyMs);this.scheduleTick(Math.min(Math.max(0,remainingSeconds??0)*1e3,this.options.everyMs))}lose(reason){if(!this.holding)return;this.holding=false;clearTimeout(this.tickTimer);clearTimeout(this.leaseDeadline);this.inFlight?.controller.abort();this.options.logger.warn(`Duty "${this.options.name}" ${reason}`)}scheduleTick(delayMs){this.tickTimer=setTimeout(()=>{this.scheduleTick(this.options.everyMs);void this.tick()},delayMs);this.tickTimer.unref?.()}async tick(){if(this.inFlight){this.options.logger.verbose(`Duty "${this.options.name}" is still running; skipping this run`);return}const controller=new AbortController;const done=this.runIfHeld(controller.signal);this.inFlight={controller,done};await done;this.inFlight=void 0}async runIfHeld(signal){if(!await this.claimRun())return;try{await this.options.run({signal})}catch(error){this.options.logger.error(`Duty "${this.options.name}" failed: ${messageOf6(error)}`)}}async claimRun(){try{if(!await this.renew()){this.lose("lost its lease; another process runs it now");return false}if(this.stopped)return false;const intervalSeconds=Math.max(1,Math.ceil(this.options.everyMs/1e3));await this.options.storage.set(this.ranKey,this.holder,{ttlSeconds:intervalSeconds});return true}catch(error){this.options.logger.warn(`Duty "${this.options.name}": the lease store failed: ${messageOf6(error)}`);return false}}}}});var duty_lifecycle_exports={};__export(duty_lifecycle_exports,{DutyLifecycle:()=>DutyLifecycle,dutyLifecycleOf:()=>dutyLifecycleOf,dutyStorageConfig:()=>dutyStorageConfig,startDuties:()=>startDuties});import{createStorage as createStorage6,getEnv as getEnv18,getRuntimeContext as getRuntimeContext23,mkdir as mkdir3,realpath as realpath2,sha256Hex as sha256Hex20,stat as stat4,writeFile as writeFile2}from"@frontmcp/utils";function nodeOs3(){return __require("os")}function nodePath3(){return __require("path")}function dutyLifecycleOf(duty,metadata,providers){let lifecycle=lifecycles.get(duty);if(!lifecycle){lifecycle=new DutyLifecycle(duty,metadata,providers);lifecycles.set(duty,lifecycle)}return lifecycle}async function startDuties(providers){for(const instance of providers.getAllSingletons().values()){if(typeof instance==="object"&&instance!==null)await lifecycles.get(instance)?.onReady()}}function dutyStorageConfig(redis){const parsed=redis===void 0?void 0:redisOptionsSchema.safeParse(redis);if(parsed?.success&&isRedisProvider(parsed.data)){const{host,port,password,db,tls}=parsed.data;return{type:"redis",redis:{config:{host,port,password,db,tls}},prefix:`frontmcp:duty:${nodeOs3().hostname()}:`,fallback:"error"}}const home=getEnv18("FRONTMCP_HOME")||nodePath3().join(nodeOs3().homedir(),".frontmcp");return{type:"sqlite",sqlite:{path:nodePath3().join(home,"duties.sqlite")},prefix:"frontmcp:duty:",fallback:"error"}}function leaseKey({name:name51,scope},serverName){const key=[serverName,name51].map(encodeURIComponent).join(":");if(scope==="machine")return key;const cwd=process.cwd();return`${key}:${sha256Hex20(findProjectRoot(cwd)??cwd)}`}async function prepareLeaseFile(file){const directory=nodePath3().dirname(file);await mkdir3(directory,{recursive:true,mode:OWNER_ONLY_DIRECTORY2});if(process.platform!=="win32"){const realDirectory=await realpath2(directory);const replaceable=await findReplaceableDirectory(directory)??(realDirectory===directory?void 0:await findReplaceableDirectory(realDirectory));if(replaceable)throw new UnsafeDutyStoreError(replaceable.directory,replaceable.mode,replaceable.ownerUid);const{mode}=await stat4(realDirectory);if(mode&GROUP_OR_OTHER_WRITE2)throw new UnsafeDutyStoreError(directory,mode)}await writeFile2(file,"",{mode:OWNER_ONLY_FILE2,flag:"a"})}var lifecycles,claims,OWNER_ONLY_DIRECTORY2,OWNER_ONLY_FILE2,GROUP_OR_OTHER_WRITE2,DutyLifecycle;var init_duty_lifecycle=__esm({"libs/sdk/src/duty/duty.lifecycle.ts"(){"use strict";init_common();init_resolve();init_duty_errors();init_front_mcp_tokens2();init_replaceable_directory();init_duty_runner();lifecycles=new WeakMap;claims=new Map;OWNER_ONLY_DIRECTORY2=448;OWNER_ONLY_FILE2=384;GROUP_OR_OTHER_WRITE2=18;DutyLifecycle=class{constructor(duty,metadata,providers){this.duty=duty;this.metadata=metadata;this.providers=providers}duty;metadata;providers;started;claimedKey;async onBootstrap(){await this.duty.onBootstrap?.()}async onReady(){await this.duty.onReady?.();this.started??=this.startRunner();await this.started}async onShutdown(){const started=await this.started?.catch(()=>void 0);if(started){await started.runner.stop();await started.storage.disconnect()}this.releaseClaim();await this.duty.onShutdown?.()}async startRunner(){const{name:name51,everyMs,leaseMs}=this.metadata;const logger=this.providers.get(FrontMcpLogger);const{runtime,deployment}=getRuntimeContext23();if(deployment==="serverless"||runtime==="edge"||runtime==="browser"){logger.warn(`Duty "${name51}" does not run in a serverless or edge deployment: it needs a long-lived process`);return void 0}const config=this.providers.get(FrontMcpConfig);const serverName=config.info?.name??"frontmcp";const key=leaseKey(this.metadata,serverName);this.claim(key,serverName);const storageConfig=dutyStorageConfig(config.redis);if(storageConfig.sqlite)await prepareLeaseFile(storageConfig.sqlite.path);const storage=await createStorage6(storageConfig);const runner=new DutyRunner({name:name51,everyMs,leaseMs,storage,logger,key,run:context=>this.duty.run(context)});await runner.start();return{runner,storage}}claim(key,serverName){const type=this.duty.constructor;const claim=claims.get(key);if(claim&&claim.type!==type){throw new DutyNameConflictError(this.metadata.name,serverName,claim.typeName,type.name)}claims.set(key,{type,typeName:type.name,instances:(claim?.instances??0)+1});this.claimedKey=key}releaseClaim(){const key=this.claimedKey;this.claimedKey=void 0;const claim=key===void 0?void 0:claims.get(key);if(key===void 0||!claim)return;claim.instances--;if(claim.instances===0)claims.delete(key)}}}});import"reflect-metadata";import{depsOfClass as depsOfClass12,hasAsyncWith,isClass as isClass20,isPromise,ProviderKind as ProviderKind4,ProviderScope as ProviderScope10,tokenName as tokenName22}from"@frontmcp/di";function verifiedSessionOf2(requestContext){const{authInfo}=requestContext;const verified=authInfo.sessionId??authInfo.extra?.["sessionId"];return typeof verified==="string"&&verified.length>0&&verified!==STATELESS_SESSION_ID?verified:void 0}function requestScopedTokens(contextProviders){const requestContext=contextProviders?.get(FRONTMCP_CONTEXT);const carriedTokens=requestContext instanceof FrontMcpContext?requestContext.getContextTokens().keys():[];return new Set([FRONTMCP_CONTEXT,...carriedTokens])}function newProviderStore(){return{providers:new Map,bySource:new Map,lastAccess:Date.now()}}var ProviderRegistry,REQUEST_PROVIDER_STORES;var init_provider_registry=__esm({"libs/sdk/src/provider/provider.registry.ts"(){"use strict";init_common();init_transport();init_frontmcp_context();init_frontmcp_context_provider();init_errors();init_front_mcp_tokens2();init_manifest_mode_flag();init_regsitry();init_scope();init_transport_types();init_provider_lifecycle();init_provider_utils();init_store_provider();ProviderRegistry=class _ProviderRegistry extends RegistryAbstract{constructor(list,parentProviders,options){super("ProviderRegistry",parentProviders,list,false);this.parentProviders=parentProviders;parentProviders?.childRegistries.add(this);this.providedBy=new Map;const configured=options?.distributedMode!==void 0||options?.providerCaching!==void 0;this.sessionCacheEnabled=!configured&&parentProviders?parentProviders.sessionCacheEnabled:shouldCacheProviders(options?.distributedMode,options?.providerCaching);this.sharedLifecycles=parentProviders?.sharedLifecycles??new WeakMap;this.shutdownHookTimeoutMs=options?.shutdownHookTimeoutMs??parentProviders?.shutdownHookTimeoutMs??DEFAULT_SHUTDOWN_HOOK_TIMEOUT_MS;this.buildGraph();this.topoSort();this.ready=this.initialize()}parentProviders;providedBy;visibleOnlyBelow=new Map;order=new Set;registries=new Map;sessionStores=new Map;sessionBuildLocks=new Map;static MAX_SESSION_CACHE_SIZE=1e4;static SESSION_CACHE_TTL_MS=36e5;static SESSION_CLEANUP_INTERVAL_MS=6e4;sessionCleanupInterval=null;sessionCacheEnabled;childRegistries=new Set;lifecycleEntries=[];heldEntries=[];sharedLifecycles;shutdownHookTimeoutMs;readyHooksRun;shutdownHooksRun;getProviders(){return[...this.instances.values()]}lookupDefInHierarchy(token,requester=this){const rec=this.defs.get(token);if(rec&&!this.hidesFrom(token,requester))return{registry:this,rec};return this.providers?.lookupDefInHierarchy(token,requester)}hidesFrom(token,requester){const roots=this.visibleOnlyBelow.get(token);if(!roots||requester===this)return false;for(const root of roots){if(requester.isWithin(root))return false}return true}isWithin(root){return this===root||(this.parentProviders?.isWithin(root)??false)}subtreeBelow(ancestor){if(this.parentProviders===ancestor)return this;return this.parentProviders?.subtreeBelow(ancestor)}resolveDefaultFromHierarchy(token){const found=this.lookupDefInHierarchy(token);if(!found)throw new ProviderNotRegisteredError(tokenName22(token),"not registered in hierarchy");const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==ProviderScope10.GLOBAL){const scName=ProviderScope10[sc];throw new ProviderScopeMismatchError(tokenName22(token),scName,registry.constructor.name)}const inst=registry.instances.get(token);if(inst===void 0){throw new ProviderNotInstantiatedError(tokenName22(token),"DEFAULT",registry.constructor.name)}return inst}buildMap(list){const tokens=new Set;const defs=new Map;const graph=new Map;for(const raw of list){const rec=normalizeProvider(raw);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);const deps=this.discoveryDeps(rec);for(const d of deps){const isLocal=this.tokens.has(d);const up=isLocal?void 0:this.lookupDefInHierarchy(d);if(!isLocal&&!up){throw new ProviderDependencyError(`Provider ${tokenName22(token)} depends on ${tokenName22(d)}, which is not registered (local or parent).`)}const depRec=isLocal?this.defs.get(d):up.rec;const depScope=isLocal?this.getProviderScope(depRec):up.registry.getProviderScope(depRec);if(this.getProviderScope(rec)===ProviderScope10.GLOBAL&&depScope!==ProviderScope10.GLOBAL){throw new InvalidDependencyScopeError(`Invalid dependency: DEFAULT-scoped provider ${tokenName22(token)} cannot depend on scoped provider ${tokenName22(d)}.`)}if(isLocal)this.graph.get(token).add(d)}}}topoSort(){const WHITE=0,GRAY=1,BLACK=2;const color=new Map;const order=new Set;const path4=[];const dfs=n=>{color.set(n,GRAY);path4.push(n);for(const dep of this.graph.get(n)??[]){const c=color.get(dep)??WHITE;if(c===GRAY){const idx=path4.findIndex(p=>p===dep);const cycle=[...path4.slice(idx),dep].map(t=>tokenName22(t)).join(" -> ");throw new DependencyCycleError(cycle)}if(c===WHITE)dfs(dep)}color.set(n,BLACK);order.add(n);path4.pop()};for(const n of this.graph.keys())if((color.get(n)??WHITE)===WHITE)dfs(n);this.order=order}async initialize(opts){const force=!!opts?.force;const only=opts?.onlyTokens?new Set(opts.onlyTokens):null;for(const token of this.order){const rec=this.defs.get(token);if(this.getProviderScope(rec)!==ProviderScope10.GLOBAL)continue;if(only&&!only.has(token))continue;if(!force&&this.instances.has(token))continue;if(force&&this.instances.has(token)){this.instances.delete(token)}try{await this.initiateOne(token,rec)}catch(e){const msg=e?.message??e;console.error(`Failed instantiating:`,msg);throw new ProviderConstructionError(tokenName22(token),e instanceof Error?e:msg)}await this.bootstrapBuilt(token)}if(this.parentProviders){this.startSessionCleanup()}}async bootstrapBuilt(token){const built=this.instances.get(token);const instance=lifecycleHooksOf(await this.dutyLifecycleOf(built)??built);if(!instance||this.heldEntries.some(held=>held.instance===instance))return;const entry={token,instance};const shared=this.sharedLifecycles.get(instance);const lifecycle=shared??{holders:0,bootstrapped:bootstrapProvider(entry)};if(!shared)this.sharedLifecycles.set(instance,lifecycle);lifecycle.holders++;await lifecycle.bootstrapped;if(!shared)this.lifecycleEntries.push(entry);this.heldEntries.push(entry)}async dutyLifecycleOf(built){const metadata=dutyMetadataOf(built);if(!metadata||typeof built!=="object"||built===null)return void 0;const{dutyLifecycleOf:dutyLifecycleOf2}=await Promise.resolve().then(()=>(init_duty_lifecycle(),duty_lifecycle_exports));return dutyLifecycleOf2(built,metadata,this)}runReadyHooks(logger){this.readyHooksRun??=this.readyHereAndBelow(logger);return this.readyHooksRun}runShutdownHooks(logger){this.shutdownHooksRun??=this.shutdownBelowAndHere(logger);return this.shutdownHooksRun}async readyHereAndBelow(logger){await readyProviders(this.lifecycleEntries,logger);for(const child of[...this.childRegistries])await child.runReadyHooks(logger)}async shutdownBelowAndHere(logger){for(const child of[...this.childRegistries].reverse())await child.runShutdownHooks(logger);const lastHeld=this.heldEntries.filter(entry=>this.releaseLifecycleHold(entry.instance));await shutdownProviders(lastHeld,this.shutdownHookTimeoutMs,logger)}releaseLifecycleHold(instance){const lifecycle=this.sharedLifecycles.get(instance);if(!lifecycle)return true;lifecycle.holders--;return lifecycle.holders===0}getAllSingletons(){return this.instances}getContextScopedClasses(){const out=[];for(const[token,rec]of this.defs){if(this.getProviderScope(rec)!==ProviderScope10.CONTEXT)continue;if(rec.kind===ProviderKind4.CLASS)out.push({token,cls:rec.useClass});else if(rec.kind===ProviderKind4.CLASS_TOKEN)out.push({token,cls:rec.provide})}return out}discoveryDeps(rec){return providerDiscoveryDeps(rec,this.tokens,(k,phase)=>depsOfClass12(k,phase))}invocationTokens(_token,rec){return providerInvocationTokens(rec,(k,phase)=>depsOfClass12(k,phase))}normalizeScope(scope){switch(scope){case ProviderScope10.SESSION:case ProviderScope10.REQUEST:return ProviderScope10.CONTEXT;default:return scope}}getProviderScope(rec){const rawScope=rec.metadata?.scope??ProviderScope10.GLOBAL;return this.normalizeScope(rawScope)}getScope(){return this.getActiveScope()}async withTimeout(p,ms,label){if(ms<=0||!Number.isFinite(ms))return p;let timer;try{const tm=new Promise((_,rej)=>timer=setTimeout(()=>rej(new Error(`Timeout after ${ms}ms: ${label}`)),ms));return await Promise.race([p,tm])}finally{clearTimeout(timer)}}async resolveFactoryArg(t,store,scopeKey){if(store.has(t))return store.get(t);if(this.instances.has(t))return this.instances.get(t);const rec=this.defs.get(t);if(rec){const sc=this.getProviderScope(rec);if(sc===ProviderScope10.GLOBAL){if(!this.instances.has(t)){throw new ProviderNotInstantiatedError(tokenName22(t),"DEFAULT")}return this.instances.get(t)}else{await this.buildIntoStore(t,rec,store,scopeKey);return store.get(t)}}const up=this.lookupDefInHierarchy(t);if(up){const sc=up.registry.getProviderScope(up.rec);if(sc===ProviderScope10.GLOBAL){const inst=up.registry.instances.get(t);if(inst===void 0){throw new ProviderNotInstantiatedError(tokenName22(t),"DEFAULT","parent")}return inst}else{await up.registry.buildIntoStore(t,up.rec,store,scopeKey);return store.get(t)}}if(isClass20(t)){if(hasAsyncWith(t)){const out=t.with();return isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${t.name}.with(...)`):out}const instance=new t;const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${t.name}.init()`)}return instance}throw new ProviderNotRegisteredError(tokenName22(t),"not registered in hierarchy and not constructable")}bootsForBuild(){const config=this.lookupDefInHierarchy(FrontMcpConfig)?.rec;return config?.kind===ProviderKind4.VALUE&&typeof config.useValue==="object"&&config.useValue!==null&&isManifestMode(config.useValue)}async initiateOne(token,rec){switch(rec.kind){case ProviderKind4.VALUE:{this.instances.set(token,rec.useValue);return}case ProviderKind4.FACTORY:{if(opensStore(rec.useFactory)&&this.bootsForBuild()){this.instances.set(token,storeNotOpened(rec.metadata?.name??tokenName22(token)));return}const deps=this.invocationTokens(token,rec);const args=[];for(const d of deps)args.push(await this.resolveFactoryArg(d,this.instances));const out=rec.useFactory(...args);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${tokenName22(token)}.useFactory(...)`):out;this.instances.set(token,val);return}case ProviderKind4.CLASS:{const depTokens=this.invocationTokens(token,rec);const deps=depTokens.map(t=>this.resolveDefaultFromHierarchy(t));const klass=rec.useClass;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;this.instances.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}this.instances.set(token,instance)}return}case ProviderKind4.CLASS_TOKEN:{const depTokens=this.invocationTokens(token,rec);const deps=depTokens.map(t=>this.resolveDefaultFromHierarchy(t));const klass=rec.provide;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;this.instances.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}this.instances.set(token,instance)}return}}}async buildIntoStore(token,rec,store,scopeKey,injectedDeps){if(store.has(token))return;try{switch(rec.kind){case ProviderKind4.VALUE:{store.set(token,rec.useValue);return}case ProviderKind4.FACTORY:{const deps=this.invocationTokens(token,rec);const args=[];for(const d of deps)args.push(await this.resolveFactoryArg(d,store,scopeKey));const out=rec.useFactory(...args);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${tokenName22(token)}.useFactory(...)`):out;store.set(token,val);return}case ProviderKind4.CLASS:{const depsTokens=this.invocationTokens(token,rec);const deps=[];for(const d of depsTokens)deps.push(await this.resolveManagedForClass(d,store,scopeKey));const klass=rec.useClass;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;store.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}store.set(token,instance)}return}case ProviderKind4.CLASS_TOKEN:{const depsTokens=this.invocationTokens(token,rec);const deps=injectedDeps??[];for(const d of depsTokens)deps.push(await this.resolveManagedForClass(d,store,scopeKey));const klass=rec.provide;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;store.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}store.set(token,instance)}return}}}catch(e){const msg=e?.message??e;console.error(`Failed constructing:`,msg);throw new ProviderConstructionError(tokenName22(token),e instanceof Error?e:msg,"scoped")}}async resolveManagedForClass(d,store,scopeKey){if(store.has(d))return store.get(d);if(this.instances.has(d))return this.instances.get(d);const depRec=this.defs.get(d);if(depRec){const sc=this.getProviderScope(depRec);if(sc===ProviderScope10.GLOBAL){const v=this.instances.get(d);if(v===void 0)throw new ProviderNotInstantiatedError(tokenName22(d),"DEFAULT");return v}else{await this.buildIntoStore(d,depRec,store,scopeKey);return store.get(d)}}const up=this.lookupDefInHierarchy(d);if(up){const sc=up.registry.getProviderScope(up.rec);if(sc===ProviderScope10.GLOBAL){const v=up.registry.instances.get(d);if(v===void 0)throw new ProviderNotInstantiatedError(tokenName22(d),"DEFAULT","parent");return v}else{await up.registry.buildIntoStore(d,up.rec,store,scopeKey);return store.get(d)}}throw new ProviderNotInstantiatedError(tokenName22(d))}get(token){return this.getFor(token,this)}getFor(token,requester){const visible=!this.hidesFrom(token,requester);if(visible&&this.instances.has(token))return this.instances.get(token);const rec=visible?this.defs.get(token):void 0;if(rec&&this.getProviderScope(rec)!==ProviderScope10.GLOBAL){const scName=ProviderScope10[this.getProviderScope(rec)];throw new ProviderScopedAccessError(tokenName22(token),scName)}if(this.providers)return this.providers.getFor(token,requester);throw new ProviderNotAvailableError(tokenName22(token),"not found in local or parent registries")}addRegistry(type,value){let registry=this.registries.get(type);if(!registry){this.registries.set(type,new Set);registry=this.registries.get(type)}registry.add(value)}getRegistries(type){return[...this.registries.get(type)??[]]}getHooksRegistry(){return this.getRegistries("HookRegistry")[0]}getScopeRegistry(){return this.getRegistries("ScopeRegistry")[0]}async resolveBootstrapDep(t){if(this.instances.has(t))return this.instances.get(t);if(this.registries.has(t))return this.registries.get(t);const found=this.lookupDefInHierarchy(t);if(found){const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==ProviderScope10.GLOBAL)throw new PluginDependencyError(`Plugin dependency ${tokenName22(t)} must be DEFAULT-scoped at bootstrap`);const v=registry.instances.get(t);if(v===void 0)throw new PluginDependencyError(`Plugin dependency ${tokenName22(t)} (DEFAULT scope) is not instantiated`);return v}throw new PluginDependencyError(`Cannot resolve plugin dependency ${tokenName22(t)} (local or parent)`)}resolve(cls){const found=this.lookupDefInHierarchy(cls);if(found){const{registry,rec}=found;const sc=registry.getProviderScope(rec);if(sc!==ProviderScope10.GLOBAL){const scName=ProviderScope10[sc];throw new ProviderScopedAccessError(tokenName22(cls),scName)}if(!registry.instances.has(cls)){throw new ProviderNotInstantiatedError(tokenName22(cls),"DEFAULT","Call providers.instantiate() first")}return registry.instances.get(cls)}if(isClass20(cls)){const instance=new cls;const init=instance?.init;if(typeof init==="function"){init.call(instance)}return instance}throw new ProviderNotRegisteredError(tokenName22(cls),"not a registered DEFAULT provider and not a constructable class")}mergeFromRegistry(providedBy,exported,visibleBelow){for(const{token,def,instance}of exported){if(visibleBelow){if(this.defs.has(token)&&!this.visibleOnlyBelow.has(token))continue;const roots=this.visibleOnlyBelow.get(token)??new Set;roots.add(visibleBelow);this.visibleOnlyBelow.set(token,roots)}else{this.visibleOnlyBelow.delete(token)}const scope=def.metadata.scope??ProviderScope10.GLOBAL;if(scope===ProviderScope10.GLOBAL&&instance!==void 0){this.instances.set(token,instance)}this.defs.set(token,def);this.providedBy.set(token,providedBy)}}getProviderInfo(token){const def=this.defs.get(token);if(!def)throw new ProviderNotRegisteredError(tokenName22(token),"not a registered DEFAULT provider and not a constructable class");const instance=this.instances.get(token);return{token,def,instance}}injectProvider(injected){const rec={...injected,kind:ProviderKind4.INJECTED};this.tokens.add(rec.provide);this.defs.set(rec.provide,rec);this.graph.set(rec.provide,new Set);this.instances.set(rec.provide,rec.value)}async addDynamicProviders(dynamicProviders){const normalized2=dynamicProviders.map(p=>normalizeProvider(p));for(const rec of normalized2){const provide=rec.provide;this.tokens.add(provide);this.defs.set(provide,rec);if(!this.graph.has(provide)){this.graph.set(provide,new Set)}const deps=this.discoveryDeps(rec);for(const d of deps){if(this.tokens.has(d)){this.graph.get(provide).add(d)}}}const globalProviders=normalized2.filter(rec=>this.getProviderScope(rec)===ProviderScope10.GLOBAL);return Promise.all(globalProviders.map(async rec=>{await this.initiateOne(rec.provide,rec);await this.bootstrapBuilt(rec.provide)}))}getWithParents(token){if(this.instances.has(token)){return this.get(token)}const parent=this.parentProviders;if(!parent){return this.get(token)}return parent.getWithParents(token)}getActiveScope(){return this.getWithParents(Scope)}getActiveServer(){return this.getWithParents(FrontMcpServer)}cleanupSession(sessionKey){this.sessionStores.delete(sessionKey);const lock=this.sessionBuildLocks.get(sessionKey);if(lock){lock.resolve();this.sessionBuildLocks.delete(sessionKey)}}cleanupExpiredSessions(){const now=Date.now();const cutoff=now-_ProviderRegistry.SESSION_CACHE_TTL_MS;let cleaned=0;for(const[key,entry]of this.sessionStores){if(entry.lastAccess<cutoff){this.sessionStores.delete(key);const lock=this.sessionBuildLocks.get(key);if(lock){lock.resolve();this.sessionBuildLocks.delete(key)}cleaned++}}return cleaned}startSessionCleanup(){if(this.sessionCleanupInterval){return}this.sessionCleanupInterval=setInterval(()=>{const cleaned=this.cleanupExpiredSessions();if(cleaned>0){console.debug(`[ProviderRegistry] Cleaned up ${cleaned} expired sessions`)}},_ProviderRegistry.SESSION_CLEANUP_INTERVAL_MS);if(this.sessionCleanupInterval.unref){this.sessionCleanupInterval.unref()}}stopSessionCleanup(){if(this.sessionCleanupInterval){clearInterval(this.sessionCleanupInterval);this.sessionCleanupInterval=null}}dispose(){for(const child of[...this.childRegistries])child.dispose();this.parentProviders?.childRegistries.delete(this);this.stopSessionCleanup();this.sessionStores.clear();for(const lock of this.sessionBuildLocks.values()){lock.resolve()}this.sessionBuildLocks.clear()}getSessionCacheStats(){return{enabled:this.sessionCacheEnabled,size:this.sessionStores.size,maxSize:_ProviderRegistry.MAX_SESSION_CACHE_SIZE,ttlMs:_ProviderRegistry.SESSION_CACHE_TTL_MS}}isSessionCacheEnabled(){return this.sessionCacheEnabled}async buildViews(sessionKey,contextProviders,contextSource){validateSessionId(sessionKey);const global=this.getAllSingletons();const ownDefs=(contextSource&&this.defsBelow(contextSource))??new Map;const cached=this.providerStoreFor(sessionKey,contextProviders?.get(FRONTMCP_CONTEXT));let sessionProviders=cached.providers;if(contextSource&&ownDefs.size>0){let bySource=cached.bySource.get(contextSource);if(!bySource){bySource=new Map;cached.bySource.set(contextSource,bySource)}sessionProviders=bySource}const requestTokens=requestScopedTokens(contextProviders);const contextStore=new Map(sessionProviders);const sourceRegistry=contextSource instanceof _ProviderRegistry&&contextSource!==this?contextSource:void 0;for(const[token,instance]of contextProviders??[]){if(ownDefs.has(token)||sourceRegistry?.hidesFrom(token,this))continue;contextStore.set(token,instance)}for(const token of this.order){const rec=this.defs.get(token);if(!rec)continue;if(this.getProviderScope(rec)!==ProviderScope10.CONTEXT)continue;if(contextStore.has(token))continue;await this.buildIntoStoreWithViews(token,rec,contextStore,sessionKey,contextStore,global)}for(const[token,rec]of this.defs){if(this.order.has(token))continue;if(this.getProviderScope(rec)!==ProviderScope10.CONTEXT)continue;if(contextStore.has(token))continue;await this.buildIntoStoreWithViews(token,rec,contextStore,sessionKey,contextStore,global)}for(const[token,{registry,rec}]of ownDefs){if(registry===this||contextStore.has(token))continue;if(registry.getProviderScope(rec)!==ProviderScope10.CONTEXT)continue;await registry.buildIntoStoreWithViews(token,rec,contextStore,sessionKey,contextStore,registry.getAllSingletons())}for(const[token,instance]of contextStore){if(!sessionProviders.has(token)&&!this.dependsOnAny(token,requestTokens)){sessionProviders.set(token,instance)}}return{global,context:contextStore}}providerStoreFor(sessionKey,requestContext){if(!(requestContext instanceof FrontMcpContext)){return newProviderStore()}if(!this.sessionCacheEnabled||verifiedSessionOf2(requestContext)!==sessionKey){let stores=requestContext.get(REQUEST_PROVIDER_STORES);if(!stores){stores=new WeakMap;requestContext.set(REQUEST_PROVIDER_STORES,stores)}let store=stores.get(this);if(!store){store=newProviderStore();stores.set(this,store)}return store}let cached=this.sessionStores.get(sessionKey);if(!cached){cached=newProviderStore();this.sessionStores.set(sessionKey,cached)}else{cached.lastAccess=Date.now()}return cached}defsBelow(ancestor){if(this===ancestor)return new Map;const owned=this.parentProviders?.defsBelow(ancestor);if(!owned)return void 0;for(const[token,rec]of this.defs)owned.set(token,{registry:this,rec});return owned}dependsOnAny(token,targets,visited=new Set){if(targets.has(token))return true;if(visited.has(token))return false;visited.add(token);const found=this.lookupDefInHierarchy(token);if(!found)return false;return found.registry.discoveryDeps(found.rec).some(dep=>this.dependsOnAny(dep,targets,visited))}async buildIntoStoreWithViews(token,rec,store,scopeKey,contextStore,globalStore){if(store.has(token))return;try{switch(rec.kind){case ProviderKind4.VALUE:{store.set(token,rec.useValue);return}case ProviderKind4.FACTORY:{const deps=this.invocationTokens(token,rec);const args=[];for(const d of deps){args.push(await this.resolveFromViews(d,contextStore,globalStore,scopeKey))}const out=rec.useFactory(...args);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${tokenName22(token)}.useFactory(...)`):out;store.set(token,val);return}case ProviderKind4.CLASS:case ProviderKind4.CLASS_TOKEN:{const depsTokens=this.invocationTokens(token,rec);const deps=[];for(const d of depsTokens){deps.push(await this.resolveFromViews(d,contextStore,globalStore,scopeKey))}const klass=rec.kind===ProviderKind4.CLASS?rec.useClass:rec.provide;if(hasAsyncWith(klass)){const out=klass.with(...deps);const val=isPromise(out)?await this.withTimeout(out,this.asyncTimeoutMs,`${klass.name}.with(...)`):out;store.set(token,val)}else{const instance=new klass(...deps);const init=instance?.init;if(typeof init==="function"){const ret=init.call(instance);if(isPromise(ret))await this.withTimeout(ret,this.asyncTimeoutMs,`${klass.name}.init()`)}store.set(token,instance)}return}}}catch(e){const msg=e?.message??e;console.error(`Failed constructing (context-scoped):`,msg);throw new ProviderConstructionError(tokenName22(token),e instanceof Error?e:msg,"context-scoped")}}async resolveFromViews(token,contextStore,globalStore,scopeKey){if(contextStore.has(token))return contextStore.get(token);if(globalStore.has(token))return globalStore.get(token);if(this.instances.has(token))return this.instances.get(token);const rec=this.defs.get(token);if(rec){const scope=this.getProviderScope(rec);if(scope===ProviderScope10.GLOBAL){throw new ProviderNotInstantiatedError(tokenName22(token),"GLOBAL")}else{await this.buildIntoStoreWithViews(token,rec,contextStore,scopeKey,contextStore,globalStore);return contextStore.get(token)}}const up=this.lookupDefInHierarchy(token);if(up){const sc=up.registry.getProviderScope(up.rec);if(sc===ProviderScope10.GLOBAL){const v=up.registry.instances.get(token);if(v!==void 0)return v;throw new ProviderNotInstantiatedError(tokenName22(token),"GLOBAL","parent")}await up.registry.buildIntoStoreWithViews(token,up.rec,contextStore,scopeKey,contextStore,up.registry.getAllSingletons());return contextStore.get(token)}throw new ProviderDependencyError(`Cannot resolve dependency ${tokenName22(token)} from views`)}getScoped(token,views){if(views.context.has(token))return views.context.get(token);if(views.global.has(token))return views.global.get(token);if(this.instances.has(token))return this.instances.get(token);throw new ProviderNotAvailableError(tokenName22(token),"not found in views. Ensure it was built via buildViews()")}};REQUEST_PROVIDER_STORES=Symbol("frontmcp:request-provider-stores")}});import{depsOfClass as depsOfClass13}from"@frontmcp/di";function normalizeAppScope(appItem,metadata){const app=normalizeApp(appItem);const appMetadata=app.metadata;if(metadata.splitByApp===true&&appMetadata.standalone==="includeInParent"){throw new ScopeConfigurationError("standalone: includeInParent is not supported for splitByApp scope")}const scopeId=appMetadata.id??appMetadata.name;const token=Symbol(scopeId);return{kind:"SPLIT_BY_APP",provide:token,metadata:{...metadata,id:scopeId,apps:[appItem],auth:appMetadata.auth??metadata.auth,__sourceDir:appMetadata.__sourceDir??metadata.__sourceDir}}}function normalizeMultiAppScope(includedApps,metadata){return{kind:"MULTI_APP",provide:Scope,metadata:{...metadata,id:"root",apps:includedApps}}}function scopeDiscoveryDeps(rec){switch(rec.kind){case"MULTI_APP":return depsOfClass13(rec.provide,"discovery").slice(1);case"SPLIT_BY_APP":return[]}}var init_scope_utils=__esm({"libs/sdk/src/scope/scope.utils.ts"(){"use strict";init_app_utils();init_errors();init_scope_instance()}});import"reflect-metadata";import{tokenName as tokenName23}from"@frontmcp/di";var ScopeRegistry;var init_scope_registry=__esm({"libs/sdk/src/scope/scope.registry.ts"(){"use strict";init_app_utils();init_common();init_errors();init_front_mcp_tokens2();init_regsitry();init_scope_instance();init_scope_utils();ScopeRegistry=class extends RegistryAbstract{logger;constructor(globalProviders){const metadata=globalProviders.get(FrontMcpConfig);super("ScopeRegistry",globalProviders,metadata);this.logger=globalProviders.get(FrontMcpLogger)?.child("ScopeRegistry")}buildMap(metadata){const tokens=new Set;const defs=new Map;const graph=new Map;if(metadata.splitByApp){for(const raw of metadata.apps){const rec=normalizeAppScope(raw,metadata);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}}else{const includeInParent=[];for(const raw of metadata.apps){const app=normalizeApp(raw);const appMetadata=app.metadata;if(appMetadata.standalone===false){includeInParent.push(raw);continue}if(appMetadata.standalone==="includeInParent"){includeInParent.push(raw)}const appScopeRec=normalizeAppScope(raw,metadata);const provide2=appScopeRec.provide;tokens.add(provide2);defs.set(provide2,appScopeRec);graph.set(provide2,new Set)}const rec=normalizeMultiAppScope(includeInParent,metadata);const provide=rec.provide;tokens.add(provide);defs.set(provide,rec);graph.set(provide,new Set)}return{tokens,defs,graph}}buildGraph(){for(const token of this.tokens){const rec=this.defs.get(token);const deps=scopeDiscoveryDeps(rec).slice(1);for(const d of deps){if(!this.providers.get(d)){throw new RegistryDependencyNotRegisteredError("Scope",tokenName23(token),tokenName23(d))}this.graph.get(token).add(d)}}}async initialize(){this.logger?.verbose(`ScopeRegistry: initializing ${this.tokens.size} scope(s)`);for(const token of this.tokens){const rec=this.defs.get(token);let scope;switch(rec.kind){case"SPLIT_BY_APP":scope=new Scope(rec,this.providers);break;case"MULTI_APP":scope=new rec.provide(rec,this.providers);break;default:throw new InvalidRegistryKindError("scope",String(rec.kind))}try{await scope.ready}finally{this.instances.set(token,scope)}this.logger?.verbose(`ScopeRegistry: initialized scope '${tokenName23(token)}'`)}this.logger?.verbose(`ScopeRegistry: initialization complete (${this.instances.size} scope(s))`)}getScopes(){return[...this.instances.values()]}getPrimaryScope(){const scopes=this.getScopes();const multiApp=scopes.find(scope=>scope.record.kind==="MULTI_APP");if(multiApp&&multiApp.apps.getApps().length>0)return multiApp;return scopes[0]}}}});var NoopFrontMcpServer;var init_noop_server=__esm({"libs/sdk/src/server/noop-server.ts"(){"use strict";init_common();NoopFrontMcpServer=class extends FrontMcpServer{registerMiddleware(_entryPath,_handler){}registerRoute(_method,_path2,_handler){}prepare(){}getHandler(){return void 0}async start(){}}}});var MetricsPathConflictError,MetricsTokenNotConfiguredError;var init_metrics_errors=__esm({"libs/sdk/src/metrics/metrics.errors.ts"(){"use strict";init_mcp_error();MetricsPathConflictError=class extends InternalMcpError{conflictingPath;constructor(conflictingPath){super(`metrics.path "${conflictingPath}" conflicts with an MCP transport route. Pick a non-MCP path (e.g. "/metrics", "/internal/metrics").`,"METRICS_PATH_CONFLICT");this.conflictingPath=conflictingPath}};MetricsTokenNotConfiguredError=class extends InternalMcpError{tokenEnv;constructor(tokenEnv){super(`metrics.auth is "token" but env var "${tokenEnv}" is not set. Set the env var or switch metrics.auth to "public" / { token: "..." }.`,"METRICS_TOKEN_NOT_CONFIGURED");this.tokenEnv=tokenEnv}}}});function loadObservability(){if(!observabilityRuntime){observabilityRuntime=requireOptionalModule("@frontmcp/observability",()=>__require("@frontmcp/observability"))}return observabilityRuntime}function createProcessStatsCollectorIfEnabled(config){const include=config.include;const processEnabled=!include||include.length===0||include.includes("process");if(!processEnabled)return void 0;const obs=loadObservability();return new obs.ProcessStatsCollector({options:config.process})}var PROMETHEUS_CONTENT_TYPE,observabilityRuntime,MCP_RESERVED_PATH_PREFIXES,COUNTER_CATEGORY_PREFIX,MetricsService;var init_metrics_service=__esm({"libs/sdk/src/metrics/metrics.service.ts"(){"use strict";init_optional_dependency_util();init_metrics_errors();PROMETHEUS_CONTENT_TYPE="text/plain; version=0.0.4; charset=utf-8";MCP_RESERVED_PATH_PREFIXES=["/mcp","/sse","/messages"];COUNTER_CATEGORY_PREFIX={process:["frontmcp_process_","frontmcp_nodejs_","frontmcp_event_loop_"],skills:["frontmcp_skills_"],tools:["frontmcp_tool_"],resources:["frontmcp_resource_"],http:["frontmcp_http_"],storage:["frontmcp_storage_"],auth:["frontmcp_auth_"],sessions:["frontmcp_session_"]};MetricsService=class{config;processCollector;snapshotSource;resolvedToken;constructor(config,processCollector,options={}){this.config=config;this.processCollector=processCollector;this.snapshotSource=options.snapshotSource??(()=>loadObservability().getMetricSnapshot());const path4=config.path??"/metrics";for(const prefix of MCP_RESERVED_PATH_PREFIXES){if(path4===prefix||path4.startsWith(`${prefix}/`)){throw new MetricsPathConflictError(path4)}}if(config.auth==="token"){const envName=config.tokenEnv??"FRONTMCP_METRICS_TOKEN";const value=process.env[envName];if(!value){throw new MetricsTokenNotConfiguredError(envName)}this.resolvedToken=value}else if(typeof config.auth==="object"&&config.auth!==null&&"token"in config.auth){this.resolvedToken=config.auth.token}}getMetrics(){const format=this.config.format??"prometheus";const include=this.config.include;let counters=this.snapshotSource();let gauges=this.processCollector?.collect()??[];if(include&&include.length>0){const includeSet=new Set(include);const allowedPrefixes=include.flatMap(category=>COUNTER_CATEGORY_PREFIX[category]??[]);const matchesAllowed=name51=>allowedPrefixes.some(prefix=>name51.startsWith(prefix));counters=counters.filter(c=>matchesAllowed(c.name));if(!includeSet.has("process")){gauges=[]}else{gauges=gauges.filter(g=>matchesAllowed(g.name))}}const obs=loadObservability();if(format==="json"){return{contentType:"application/json",body:JSON.stringify(obs.renderJsonExposition(counters,gauges))}}return{contentType:PROMETHEUS_CONTENT_TYPE,body:obs.renderPrometheusExposition(counters,gauges)}}authorize(authorizationHeader){const auth=this.config.auth??"public";if(auth==="public")return 200;if(!authorizationHeader)return 401;const expected=this.resolvedToken;if(!expected)return 401;const match=/^Bearer\s+(.+)$/i.exec(authorizationHeader);if(!match)return 401;return match[1]===expected?200:403}}}});function readAuthorizationHeader(headers){if(!headers)return void 0;const raw=headers["authorization"]??headers["Authorization"];if(Array.isArray(raw))return raw[0];return typeof raw==="string"?raw:void 0}function metricsPath(config){return config.path??"/metrics"}function renderMetricsScrape(service,config,authorizationHeader){const status=service.authorize(authorizationHeader);if(status!==200){return{status,headers:{"Cache-Control":"no-store"},kind:"json",body:{error:status===401?"unauthorized":"forbidden",message:status===401?"Missing or malformed Authorization header":"Bearer token did not match the configured metrics token"}}}const result=service.getMetrics();const headers={"Cache-Control":"no-store","Content-Type":result.contentType};if((config.format??"prometheus")!=="json"){return{status:200,headers,kind:"text",body:result.body}}try{return{status:200,headers,kind:"json",body:JSON.parse(result.body)}}catch{return{status:500,headers,kind:"json",body:{error:"internal_error",message:"Failed to serialise metrics JSON"}}}}function registerMetricsRoutes(server,service,config){if(config.enabled!==true)return;server.registerRoute("GET",metricsPath(config),async(req,res)=>{const result=renderMetricsScrape(service,config,readAuthorizationHeader(req.headers));for(const[name51,value]of Object.entries(result.headers))res.setHeader?.(name51,value);if(result.kind==="json"){res.status(result.status).json(result.body);return}if(typeof res.send==="function"){res.status(result.status);res.send(result.body);return}res.status(500).json({error:"internal_error",message:'Server adapter does not support Prometheus text format. Use `format: "json"` or upgrade the adapter.'})})}var init_metrics_routes=__esm({"libs/sdk/src/metrics/metrics.routes.ts"(){"use strict"}});var metrics_exports={};__export(metrics_exports,{MetricsPathConflictError:()=>MetricsPathConflictError,MetricsService:()=>MetricsService,MetricsTokenNotConfiguredError:()=>MetricsTokenNotConfiguredError,createProcessStatsCollectorIfEnabled:()=>createProcessStatsCollectorIfEnabled,metricsPath:()=>metricsPath,registerMetricsRoutes:()=>registerMetricsRoutes,renderMetricsScrape:()=>renderMetricsScrape});var init_metrics2=__esm({"libs/sdk/src/metrics/index.ts"(){"use strict";init_metrics_service();init_metrics_routes();init_metrics_errors()}});import{getEnv as getEnv19}from"@frontmcp/utils";function readCorsFromEnv(){const rawOrigins=getEnv19("FRONTMCP_CORS_ORIGINS");if(!rawOrigins)return void 0;let origins;try{origins=JSON.parse(rawOrigins)}catch{origins=rawOrigins.split(",")}const list=(Array.isArray(origins)?origins:[origins]).filter(origin=>typeof origin==="string").map(origin=>origin.trim()).filter(origin=>origin.length>0);if(list.length===0)return void 0;const cors2={origin:list.includes("*")?true:list};const credentials=getEnv19("FRONTMCP_CORS_CREDENTIALS");if(credentials!==void 0)cors2.credentials=credentials==="true"||credentials==="1";const maxAge=Number(getEnv19("FRONTMCP_CORS_MAX_AGE"));if(Number.isFinite(maxAge)&&maxAge>0)cors2.maxAge=maxAge;return cors2}function resolveHttpCors(cors2){return cors2!==void 0?cors2:readCorsFromEnv()}var init_cors_env=__esm({"libs/sdk/src/server/middleware/cors-env.ts"(){"use strict"}});function auditSecurityDefaults(config,isProduction10){const findings=[];if(!isProduction10&&config.deploymentMode!=="distributed"){return findings}const strict=config.security?.strict===true;const cors2=resolveHttpCors(config.cors);const corsOrigin=cors2===false?void 0:cors2?.origin;if(corsOrigin===void 0||corsOrigin===false){findings.push({level:"info",code:"CORS_DISABLED",message:"No CORS headers are sent, so a browser will not let a page on another origin read the response. CORS is not server-side access control: on a routable bind, cross-origin requests still reach the server."})}else if(corsOrigin===true){findings.push({level:"warn",code:"CORS_ORIGIN_TRUE",message:"CORS origin=true allows all origins to make cross-origin requests.",recommendation:"Set cors.origin to specific allowed origins."})}else{findings.push({level:"info",code:"CORS_CONFIGURED",message:"CORS is explicitly configured."})}const bindAddress=config.resolvedBindAddress??"127.0.0.1";if(bindAddress==="0.0.0.0"||bindAddress==="::"){if(config.deploymentMode!=="distributed"){findings.push({level:"warn",code:"BIND_ALL_INTERFACES",message:`Server bound to ${bindAddress} \u2014 accessible from all network interfaces.`,recommendation:"Set security.bindAddress to 'loopback' or '127.0.0.1' for local-only access, or configure a reverse proxy. Distributed deployments require 'all' (0.0.0.0)."})}else{findings.push({level:"info",code:"BIND_ALL_INTERFACES_DISTRIBUTED",message:`Server bound to ${bindAddress} (expected for distributed deployment).`})}}else{findings.push({level:"info",code:"BIND_RESTRICTED",message:`Server bound to ${bindAddress}.`})}findings.push(auditDnsRebinding(config,bindAddress));if(config.security?.strict){findings.push({level:"info",code:"STRICT_MODE_ENABLED",message:config.deploymentMode==="distributed"?"Strict security mode is enabled: DNS rebinding protection. Binding is unchanged for a distributed deployment \u2014 it still listens on all interfaces so peers can reach it.":"Strict security mode is enabled: loopback binding and DNS rebinding protection."})}else{findings.push({level:"info",code:"STRICT_MODE_HINT",message:"To enable strict security defaults, set security.strict = true in HttpOptions."})}return findings}function auditDnsRebinding(config,bindAddress){const protection=config.security?.dnsRebindingProtection;if(protection?.enabled===false){return{level:"warn",code:"DNS_REBINDING_UNPROTECTED",message:"DNS rebinding protection is disabled (security.dnsRebindingProtection.enabled is false).",recommendation:"Remove `enabled: false` to turn DNS rebinding protection back on (an allowedHosts list is ignored while it is set). On a routable bind, also set security.dnsRebindingProtection.allowedHosts (or FRONTMCP_ALLOWED_HOSTS) to your public hostname(s)."}}const explicitHosts=protection?.allowedHosts??allowedHostsFromEnv();if(explicitHosts?.length||protection?.allowedOrigins?.length){return{level:"info",code:"DNS_REBINDING_PROTECTED",message:"DNS rebinding protection is enabled: Host/Origin headers are checked against the configured allow-list."}}if(config.socketPath){return{level:"info",code:"DNS_REBINDING_NOT_APPLICABLE",message:"Server listens on a Unix socket: there is no TCP Host to check; the socket permissions are the boundary."}}if(!isRoutableBind(bindAddress)){return{level:"info",code:"DNS_REBINDING_PROTECTED",message:corsAllowedOrigins(resolveHttpCors(config.cors))?`DNS rebinding protection is enabled: Host and Origin headers are checked against the loopback names for ${bindAddress}. A request with no Origin header is allowed.`:`DNS rebinding protection is enabled: Host headers are checked against the loopback names for ${bindAddress}. Origin is not checked: CORS admits every origin.`}}return{level:"info",code:"DNS_REBINDING_NOT_ENFORCED",message:`DNS rebinding protection is on, but no Host allow-list is enforced: the server binds ${bindAddress} and no allowed hosts are configured.`,recommendation:"Set security.dnsRebindingProtection.allowedHosts (or FRONTMCP_ALLOWED_HOSTS) to your public hostname(s)."}}function logSecurityFindings(findings,logger){if(findings.length===0)return;for(const finding of findings){const prefix=`[Security] ${finding.code}:`;const message=finding.recommendation?`${prefix} ${finding.message} ${finding.recommendation}`:`${prefix} ${finding.message}`;if(finding.level==="warn"){logger.warn(message)}else{logger.info(message)}}}function toBindAddress(value){if(value==="loopback")return"127.0.0.1";if(value==="all")return"0.0.0.0";return value}function resolveBindAddress(security,deploymentMode){if(security?.bindAddress){return toBindAddress(security.bindAddress)}const envBindAddress=process.env["FRONTMCP_BIND_ADDRESS"]?.trim();if(envBindAddress){return toBindAddress(envBindAddress)}if(security?.strict){return deploymentMode==="distributed"?"0.0.0.0":"127.0.0.1"}if(deploymentMode==="distributed")return"0.0.0.0";return"127.0.0.1"}var init_security_audit=__esm({"libs/sdk/src/server/security/security-audit.ts"(){"use strict";init_cors_env();init_resolve_allowed_hosts()}});import{getEnv as getEnv20,getEnvFlag as getEnvFlag2}from"@frontmcp/utils";function readCspFromEnv(){if(!getEnvFlag2("FRONTMCP_CSP_ENABLED"))return void 0;const rawDirectives=getEnv20("FRONTMCP_CSP_DIRECTIVES")??"";const directives={};for(const part of rawDirectives.split(";")){const trimmed=part.trim();if(!trimmed)continue;const spaceIdx=trimmed.indexOf(" ");if(spaceIdx>0){directives[trimmed.slice(0,spaceIdx)]=trimmed.slice(spaceIdx+1)}else{directives[trimmed]=""}}return{enabled:true,directives,reportUri:getEnv20("FRONTMCP_CSP_REPORT_URI"),reportOnly:getEnvFlag2("FRONTMCP_CSP_REPORT_ONLY")}}function buildCspHeaderValue(options){const parts=[];for(const[directive,value]of Object.entries(options.directives)){parts.push(value?`${directive} ${value}`:directive)}if(options.reportUri){parts.push(`report-uri ${options.reportUri}`)}return parts.join("; ")}function getCspHeaderName(reportOnly){return reportOnly?"Content-Security-Policy-Report-Only":"Content-Security-Policy"}function readSecurityHeadersFromEnv(){return{hsts:readHeaderEnv("FRONTMCP_HSTS"),contentTypeOptions:readHeaderEnv("FRONTMCP_CONTENT_TYPE_OPTIONS","nosniff"),frameOptions:readHeaderEnv("FRONTMCP_FRAME_OPTIONS","DENY"),custom:readCustomHeadersFromEnv()}}function readHeaderEnv(name51,fallback){const value=getEnv20(name51);if(value===void 0||value==="")return fallback;return["off","false","none"].includes(value.trim().toLowerCase())?void 0:value}function readCustomHeadersFromEnv(){const raw=getEnv20("FRONTMCP_HEADERS_CUSTOM");if(!raw)return void 0;try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))return void 0;return Object.fromEntries(Object.entries(parsed).filter(entry=>typeof entry[1]==="string"))}catch{return void 0}}function applySecurityHeaders(res,headers,csp){if(headers.hsts){res.setHeader("Strict-Transport-Security",headers.hsts)}if(headers.contentTypeOptions){res.setHeader("X-Content-Type-Options",headers.contentTypeOptions)}if(headers.frameOptions){res.setHeader("X-Frame-Options",headers.frameOptions)}if(headers.custom){for(const[name51,value]of Object.entries(headers.custom)){res.setHeader(name51,value)}}if(csp?.enabled){const headerName=getCspHeaderName(csp.reportOnly);const headerValue=buildCspHeaderValue(csp);if(headerValue){res.setHeader(headerName,headerValue)}}}function resolveSecurityHeaders(options={}){const env=readSecurityHeadersFromEnv();const pick=(explicit,fromEnv)=>explicit===false?void 0:explicit??fromEnv;const resolved={hsts:pick(options.hsts,env.hsts),contentTypeOptions:pick(options.contentTypeOptions,env.contentTypeOptions),frameOptions:pick(options.frameOptions,env.frameOptions),custom:{...env.custom,...options.custom}};let csp;if(options.csp?.enabled===false){csp=void 0}else if(options.csp?.enabled===true){const directives={};for(const[name51,value]of Object.entries(options.csp.directives??{})){directives[name51]=Array.isArray(value)?value.join(" "):value}csp={enabled:true,directives,reportUri:options.csp.reportUri,reportOnly:options.csp.reportOnly??false}}else{csp=readCspFromEnv()}const headers={};applySecurityHeaders({setHeader:(name51,value)=>void(headers[name51]=value)},resolved,csp);return headers}var init_csp_middleware=__esm({"libs/sdk/src/server/middleware/csp.middleware.ts"(){"use strict"}});function createHostValidationMiddleware(options){if(!options.enabled){return(_req,_res,next)=>next()}const compiled=compileHostValidation({allowedHosts:options.allowedHosts,allowedOrigins:options.allowedOrigins});return(req,res,next)=>{const rejection=validateHostHeaders({host:req.headers?.["host"],forwardedHost:req.headers?.["x-forwarded-host"],origin:req.headers?.["origin"]},compiled);if(rejection){res.status(rejection.status).json({error:rejection.error,message:rejection.message});return}next()}}var init_host_validation_middleware=__esm({"libs/sdk/src/server/middleware/host-validation.middleware.ts"(){"use strict";init_host_validation()}});import cluster from"node:cluster";import*as net from"node:net";import*as path from"node:path";import{chmod,lstat as lstat2,realpath as realpath3,stat as stat5,unlink}from"@frontmcp/utils";function hasSocketFileMode(){return process.platform!=="win32"}function errorCode(error){return error?.code}async function assertSafeSocketDirectory(socketPath){const socketDirectory=path.dirname(path.resolve(socketPath));const realSocketDirectory=await realpath3(socketDirectory);await assertNoOtherUserCanReplace2(socketDirectory);if(realSocketDirectory!==socketDirectory)await assertNoOtherUserCanReplace2(realSocketDirectory);if(canBindOwnerOnly())return;const{mode}=await stat5(socketDirectory);if(mode&GROUP_OR_OTHER_ACCESS2){throw new SocketPermissionError(socketPath,`the umask cannot be set here (a worker thread, or a cluster worker whose primary binds the socket), so its directory ${socketDirectory} must be owner-only (0700), not 0${(mode&511).toString(8)}`)}}async function assertNoOtherUserCanReplace2(start){const replaceable=await findReplaceableDirectory(start);if(replaceable)throw new UnsafeSocketDirectoryError(replaceable.directory,replaceable.mode,replaceable.ownerUid)}function canBindOwnerOnly(){if(cluster.isWorker)return false;const previousUmask=setUmask(OWNER_ONLY_UMASK);if(previousUmask===void 0)return false;setUmask(previousUmask);return true}function probe(socketPath){return new Promise((resolve4,reject)=>{const socket=net.connect(socketPath);socket.once("connect",()=>{socket.destroy();resolve4("live")});socket.once("error",error=>{const code=errorCode(error);if(code==="ECONNREFUSED")resolve4("stale");else if(code==="ENOENT")resolve4("gone");else reject(new SocketPathConflictError(socketPath,`connecting to it failed (${code??error.message})`))})})}async function clearStaleSocket(socketPath){let stats;try{stats=await lstat2(socketPath)}catch(error){if(errorCode(error)==="ENOENT")return;throw error}if(!stats.isSocket())throw new SocketPathConflictError(socketPath,"it is not a socket");if(stats.uid!==process.getuid?.()){throw new SocketPathConflictError(socketPath,`it belongs to another user (uid ${stats.uid})`)}const state=await probe(socketPath);if(state==="live")throw new SocketInUseError(socketPath);if(state==="stale")await unlink(socketPath)}function listenOwnerOnly(server,socketPath,onListening){const previousUmask=setUmask(OWNER_ONLY_UMASK);try{server.listen(socketPath,onListening)}finally{if(previousUmask!==void 0)setUmask(previousUmask)}}function setUmask(mask){try{return process.umask(mask)}catch{return void 0}}async function enforceOwnerOnly(socketPath){try{await chmod(socketPath,OWNER_ONLY_MODE)}catch(error){throw new SocketPermissionError(socketPath,`chmod failed (${errorCode(error)??String(error)})`)}const mode=(await lstat2(socketPath)).mode&511;if(mode!==OWNER_ONLY_MODE)throw new SocketPermissionError(socketPath,`its mode is 0${mode.toString(8)}`)}var OWNER_ONLY_MODE,OWNER_ONLY_UMASK,GROUP_OR_OTHER_ACCESS2;var init_unix_socket_guard=__esm({"libs/sdk/src/server/security/unix-socket-guard.ts"(){"use strict";init_transport_errors();init_replaceable_directory();OWNER_ONLY_MODE=384;OWNER_ONLY_UMASK=63;GROUP_OR_OTHER_ACCESS2=63}});var HostServerAdapter;var init_base_host_adapter=__esm({"libs/sdk/src/server/adapters/base.host.adapter.ts"(){"use strict";init_common();HostServerAdapter=class extends FrontMcpServer{}}});import express from"express";function utf8JsonParser(limit){const readBody=express.raw({limit,type:isUtf8Json});return(req,res,next)=>{const unparsedBody=req.body;readBody(req,res,readError=>{if(readError||req.body===unparsedBody||!Buffer.isBuffer(req.body)){next(readError);return}const text=decodeUtf8(req.body);try{req.body=parseStrictJson(text)}catch(error){req.body=unparsedBody;next(Object.assign(error,parseFailure(text)));return}next()})}}function decodeUtf8(body){const text=body.toString("utf8");return text.charCodeAt(0)===65279?text.slice(1):text}function parseStrictJson(text){if(text.length===0)return{};const first3=FIRST_NON_WHITESPACE.exec(text)?.[1];if(first3!=="{"&&first3!=="[")throw strictSyntaxError(text,first3);return JSON.parse(text)}function strictSyntaxError(text,first3){const index=first3===void 0?-1:text.indexOf(first3);const error=jsonParseError(index===-1?"":text.slice(0,index).padEnd(text.length,"#"));const message=error.message.replace(/#+/g,mask=>text.substring(index,index+mask.length));error.stack=error.stack?.replace(error.message,message);error.message=message;return error}function jsonParseError(invalidJson){try{JSON.parse(invalidJson)}catch(error){return error}return new SyntaxError(`Expected invalid JSON: ${invalidJson}`)}var UTF8_JSON_TYPE,FIRST_NON_WHITESPACE,isUtf8Json,parseFailure;var init_utf8_json_parser=__esm({"libs/sdk/src/server/adapters/utf8-json.parser.ts"(){"use strict";UTF8_JSON_TYPE=/^application\/json(?:; ?charset=utf-8)?$/i;FIRST_NON_WHITESPACE=/^[ \t\n\r]*([^ \t\n\r])/;isUtf8Json=req=>UTF8_JSON_TYPE.test(req.headers["content-type"]??"");parseFailure=body=>({expose:true,statusCode:400,status:400,body,type:"entity.parse.failed"})}});import*as http from"node:http";import cors from"cors";import express2 from"express";var SERVER_DRAIN_MS,DEFAULT_EXPRESS_BODY_LIMIT,ExpressHostAdapter;var init_express_host_adapter=__esm({"libs/sdk/src/server/adapters/express.host.adapter.ts"(){"use strict";init_mcp_error();init_ha_headers();init_csp_middleware();init_host_validation_middleware();init_resolve_allowed_hosts();init_unix_socket_guard();init_base_host_adapter();init_utf8_json_parser();SERVER_DRAIN_MS=5e3;DEFAULT_EXPRESS_BODY_LIMIT="4mb";ExpressHostAdapter=class extends HostServerAdapter{app=express2();router=express2.Router();prepared=false;httpServer;hostValidation;deriveHostValidation;constructor(options){super();this.app.disable("x-powered-by");const securityHeaders=resolveSecurityHeaders(options?.securityHeaders);this.app.use((_req,res,next)=>{for(const[name51,value]of Object.entries(securityHeaders))res.setHeader(name51,value);applyMachineIdHeader(res);next()});const corsOptions=options?.cors;const corsEnabled=corsOptions?.origin!==void 0&&corsOptions.origin!==false;if(corsEnabled){const configuredCors=cors({origin:corsOptions.origin,credentials:corsOptions.credentials??false,maxAge:corsOptions.maxAge??300});const publicCorsPaths=new Set(options?.publicCorsPaths);this.app.use((req,res,next)=>publicCorsPaths.has(req.path)?next():configuredCors(req,res,next))}this.installHostValidation(options);const jsonLimit=options?.bodyLimit??DEFAULT_EXPRESS_BODY_LIMIT;const formLimit=options?.urlencodedLimit??jsonLimit;const headerContains=(req,needle)=>(req.headers["content-type"]??"").toLowerCase().includes(needle);const isUrlencoded=req=>headerContains(req,"application/x-www-form-urlencoded");const isJson=req=>headerContains(req,"application/json")&&!isUrlencoded(req);this.app.use(express2.urlencoded({extended:true,limit:formLimit,type:isUrlencoded}));this.app.use(utf8JsonParser(jsonLimit));this.app.use(express2.json({limit:jsonLimit,type:isJson}));this.app.use((err,_req,res,next)=>{const e=err;if(e?.type==="entity.too.large"){const payloadError=new PayloadTooLargeError(e.limit,e.length);res.status(payloadError.statusCode).json({jsonrpc:"2.0",id:null,error:payloadError.toJsonRpcError()});return}next(err)});this.app.use((req,res,next)=>{if(corsEnabled){res.setHeader("Access-Control-Expose-Headers","WWW-Authenticate, Mcp-Session-Id")}res.setHeader("Cache-Control","no-cache, no-transform");res.setHeader("Content-Type","application/json; charset=utf-8");next()})}installHostValidation(options){const protection=options?.security?.dnsRebindingProtection;if(protection?.enabled===false)return;const allowedOrigins=protection?.allowedOrigins;const explicitHosts=protection?.allowedHosts??allowedHostsFromEnv();if(explicitHosts?.length||allowedOrigins?.length){this.hostValidation=createHostValidationMiddleware({enabled:true,allowedHosts:explicitHosts?.length?explicitHosts:void 0,allowedOrigins})}else{this.deriveHostValidation=(portOrSocketPath,bindAddress)=>{if(typeof portOrSocketPath==="string")return void 0;const derivation={bindAddress:bindAddress??"127.0.0.1",port:portOrSocketPath,issuer:options?.listen?.issuer};if(!shouldEnforceDerivedHosts(derivation)){console.warn(`[frontmcp] DNS-rebinding protection is not enforcing a Host allow-list: the server binds a routable address (${derivation.bindAddress}) and no allowed hosts are configured. Set security.dnsRebindingProtection.allowedHosts (or FRONTMCP_ALLOWED_HOSTS) to your public hostname(s).`);return void 0}const allowedHosts=deriveAllowedHosts(derivation);if(!allowedHosts.length)return void 0;const corsOrigins=corsAllowedOrigins(options?.cors);const allowedOrigins2=isLoopbackAddress(derivation.bindAddress)&&corsOrigins?deriveAllowedOrigins({port:derivation.port,issuer:derivation.issuer,extraOrigins:corsOrigins}):void 0;return createHostValidationMiddleware({enabled:true,allowedHosts,allowedOrigins:allowedOrigins2})}}this.app.use(((req,res,next)=>{const validate=this.hostValidation;if(!validate)return next();return validate(req,res,next)}))}enableDerivedHostValidation(portOrSocketPath,bindAddress){if(this.hostValidation||!this.deriveHostValidation)return;this.hostValidation=this.deriveHostValidation(portOrSocketPath,bindAddress);this.deriveHostValidation=void 0}registerRoute(method,path4,handler){this.router[method.toLowerCase()](path4,this.enhancedHandler(handler))}registerMiddleware(entryPath,handler){this.router.use(entryPath,handler)}enhancedHandler(handler){return(req,res,next)=>{const request2=req;const response=res;return handler(request2,response,next)}}prepare(){if(this.prepared)return;this.prepared=true;this.app.use("/",this.router)}getHandler(){this.prepare();return this.app}async start(portOrSocketPath,bindAddress){this.prepare();const server=http.createServer(this.app);this.httpServer=server;server.requestTimeout=0;server.headersTimeout=0;server.keepAliveTimeout=75e3;if(typeof portOrSocketPath==="string"){const ownerOnly=hasSocketFileMode();if(ownerOnly){await assertSafeSocketDirectory(portOrSocketPath);await clearStaleSocket(portOrSocketPath)}this.enableDerivedHostValidation(portOrSocketPath);await new Promise((resolve4,reject)=>{server.on("error",reject);if(ownerOnly)listenOwnerOnly(server,portOrSocketPath,resolve4);else server.listen(portOrSocketPath,resolve4)});if(ownerOnly){try{await enforceOwnerOnly(portOrSocketPath)}catch(error){await this.stop(0);throw error}}console.log(`MCP HTTP (Express) on unix://${portOrSocketPath}`)}else{const host=bindAddress??"127.0.0.1";await new Promise((resolve4,reject)=>{server.on("error",reject);server.listen(portOrSocketPath,host,()=>{const bound=server.address();const boundPort=typeof bound==="object"&&bound?bound.port:portOrSocketPath;const boundAddress=typeof bound==="object"&&bound?bound.address:host;this.enableDerivedHostValidation(boundPort,boundAddress);console.log(`MCP HTTP (Express) on ${host}:${boundPort}`);resolve4()})})}}async stop(drainMs=SERVER_DRAIN_MS){const server=this.httpServer;if(!server)return;this.httpServer=void 0;const closed=new Promise(resolve4=>server.close(()=>resolve4()));server.closeIdleConnections();const forceClose=setTimeout(()=>server.closeAllConnections(),drainMs);try{await closed}finally{clearTimeout(forceClose)}}}}});var node_express_host_exports={};__export(node_express_host_exports,{DEFAULT_EXPRESS_BODY_LIMIT:()=>DEFAULT_EXPRESS_BODY_LIMIT,ExpressHostAdapter:()=>ExpressHostAdapter});var init_node_express_host=__esm({"libs/sdk/src/server/adapters/polyfills/node-express-host.ts"(){"use strict";init_express_host_adapter()}});var server_instance_exports={};__export(server_instance_exports,{FrontMcpServerInstance:()=>FrontMcpServerInstance});import{getRuntimeContext as getRuntimeContext24,isProduction as isProduction9}from"@frontmcp/utils";var DEFAULT_CORS,FrontMcpServerInstance;var init_server_instance=__esm({"libs/sdk/src/server/server.instance.ts"(){"use strict";init_common();init_path_utils();init_health2();init_mcp_registry_utils();init_metrics2();init_cors_env();init_security_audit();DEFAULT_CORS=void 0;FrontMcpServerInstance=class extends FrontMcpServer{config;host;healthRouteRegistered=false;_healthService;_healthConfig;metricsRouteRegistered=false;_metricsService;_metricsConfig;constructor(httpConfig){super();this.config=httpConfig;this.setupDefaults()}setupDefaults(){if(typeof this.config.hostFactory==="function"){const{hostFactory,...config}=this.config;this.host=this.config.hostFactory(config)}else if(this.config.hostFactory!==void 0){this.host=this.config.hostFactory}else{const cors2=resolveHttpCors(this.config.cors);const corsConfig=cors2===false?void 0:cors2??DEFAULT_CORS;const{ExpressHostAdapter:ExpressHostAdapter2}=(init_node_express_host(),__toCommonJS(node_express_host_exports));this.host=new ExpressHostAdapter2({...corsConfig?{cors:corsConfig}:{},publicCorsPaths:[serverCardPath({entryPath:resolveEntryPath(this.config.entryPath),routeBase:""})],...this.config.security?{security:this.config.security}:{},...this.config.securityHeaders?{securityHeaders:this.config.securityHeaders}:{},...this.config.bodyLimit!==void 0?{bodyLimit:this.config.bodyLimit}:{},...this.config.urlencodedLimit!==void 0?{urlencodedLimit:this.config.urlencodedLimit}:{}})}}registerMiddleware(entryPath,handler){return this.host.registerMiddleware(entryPath,handler)}registerRoute(method,path4,handler){return this.host.registerRoute(method,path4,handler)}setHealthService(healthService,healthConfig){this._healthService=healthService;this._healthConfig=healthConfig}setHealthConfig(healthConfig){this._healthConfig=healthConfig}setMetricsService(metricsService,metricsConfig){this._metricsService=metricsService;this._metricsConfig=metricsConfig}setMetricsConfig(metricsConfig){this._metricsConfig=metricsConfig}prepare(){if(!this.healthRouteRegistered){this.healthRouteRegistered=true;if(this._healthService&&this._healthConfig){registerHealthRoutes(this,this._healthService,this._healthConfig)}else if(this._healthConfig?.enabled===false){}else{this.registerRoute("GET","/health",async(req,res)=>{res.status(200).json({status:"ok"})})}}if(!this.metricsRouteRegistered){this.metricsRouteRegistered=true;if(this._metricsService&&this._metricsConfig?.enabled===true){registerMetricsRoutes(this,this._metricsService,this._metricsConfig)}}this.host.prepare()}getHandler(){return this.host.getHandler()}async start(){this.prepare();const deploymentMode=getRuntimeContext24().deployment;const bindAddress=resolveBindAddress(this.config.security,deploymentMode);const findings=auditSecurityDefaults({cors:this.config.cors,security:this.config.security,resolvedBindAddress:bindAddress,socketPath:this.config.socketPath,deploymentMode},isProduction9());logSecurityFindings(findings,console);await this.host.start(this.config.socketPath??this.config.port,bindAddress)}async stop(){await this.host.stop()}}}});import{ProviderScope as ProviderScope11}from"@frontmcp/di";function createMcpGlobalProviders(metadata){const isCli=!!metadata["__cliMode"];const isNoServe=metadata.serve===false;const serverProvider=isCli||isNoServe?noopServer:frontMcpServer;return[frontMcpConfig.with(metadata),serverProvider,FrontMcpContextStorage]}var frontMcpConfig,defaultHttpOptions,frontMcpServer,noopServer;var init_front_mcp_providers=__esm({"libs/sdk/src/front-mcp/front-mcp.providers.ts"(){"use strict";init_common();init_context();init_noop_server();init_front_mcp_tokens2();frontMcpConfig={with:metadata=>({name:"frontmcp:config",provide:FrontMcpConfig,scope:ProviderScope11.GLOBAL,useValue:metadata})};defaultHttpOptions=()=>({port:defaultHttpPort(),entryPath:"/mcp"});frontMcpServer=AsyncProvider({name:"frontmcp:server",scope:ProviderScope11.GLOBAL,provide:FrontMcpServer,inject:()=>[FrontMcpConfig],useFactory:async config=>{const{FrontMcpServerInstance:FrontMcpServerInstance2}=await Promise.resolve().then(()=>(init_server_instance(),server_instance_exports));return new FrontMcpServerInstance2(config.http??defaultHttpOptions())}});noopServer={name:"frontmcp:server:noop",provide:FrontMcpServer,scope:ProviderScope11.GLOBAL,useValue:new NoopFrontMcpServer}}});import{watchParent}from"@frontmcp/utils";function exitOnShutdownSignals(shutdown,options={}){const target=options.target??process;const deadlineMs=options.deadlineMs??DEFAULT_SHUTDOWN_DEADLINE_MS;let shuttingDown=false;let watcher;const begin=trigger=>{if(shuttingDown)return;shuttingDown=true;watcher?.close();const deadline=setTimeout(()=>target.exit(1),deadlineMs);shutdown(trigger).then(()=>{clearTimeout(deadline);target.exit(0)},error=>{clearTimeout(deadline);options.logger?.error("Graceful shutdown failed",error);target.exit(1)})};const onSignal=()=>begin("signal");for(const signal of SHUTDOWN_SIGNALS)target.on(signal,onSignal);if(options.whenOrphaned){watcher=watchParent({stdin:options.whenOrphaned.stdin,onGone:reason=>{options.logger?.info?.(ORPHANED_MESSAGES[reason]);begin(reason)}})}return()=>{watcher?.close();for(const signal of SHUTDOWN_SIGNALS)target.removeListener(signal,onSignal)}}var SHUTDOWN_SIGNALS,ORPHANED_MESSAGES,DEFAULT_SHUTDOWN_DEADLINE_MS,STDIO_SHUTDOWN_DEADLINE_MS,STDIO_DRAIN_MS;var init_shutdown_signals=__esm({"libs/sdk/src/front-mcp/shutdown-signals.ts"(){"use strict";SHUTDOWN_SIGNALS=["SIGTERM","SIGINT"];ORPHANED_MESSAGES={"parent-exited":"The parent process exited; shutting down","stdin-ended":"stdin ended; shutting down"};DEFAULT_SHUTDOWN_DEADLINE_MS=1e4;STDIO_SHUTDOWN_DEADLINE_MS=5e3;STDIO_DRAIN_MS=2e3}});function redirectConsoleToStderr(){const{Console}=__require("node:console");const stderrConsole=new Console({stdout:process.stderr,stderr:process.stderr});console.log=stderrConsole.log.bind(stderrConsole);console.info=stderrConsole.info.bind(stderrConsole);console.debug=stderrConsole.debug.bind(stderrConsole);console.dir=stderrConsole.dir.bind(stderrConsole);console.table=stderrConsole.table.bind(stderrConsole);console.time=stderrConsole.time.bind(stderrConsole);console.timeLog=stderrConsole.timeLog.bind(stderrConsole);console.group=stderrConsole.group.bind(stderrConsole);console.groupEnd=stderrConsole.groupEnd.bind(stderrConsole);console.count=stderrConsole.count.bind(stderrConsole)}var init_stdio_console=__esm({"libs/sdk/src/front-mcp/stdio-console.ts"(){"use strict"}});var instance_file_logger_exports={};__export(instance_file_logger_exports,{FileLogTransportInstance:()=>FileLogTransportInstance});function getFs(){return _fs??=__require("fs")}function getOs(){return _os??=__require("os")}function getPath(){return _path??=__require("path")}function stripAnsi(str){return str.split(ESC).map(s=>s.replace(/\[[0-9;]*m/,"")).join("")}var _fs,_os,_path,LOG_LEVEL_LABELS,ESC,DEFAULT_LOGS_MAX,FileLogTransportInstance;var init_instance_file_logger=__esm({"libs/sdk/src/logger/instances/instance.file-logger.ts"(){"use strict";init_common();LOG_LEVEL_LABELS={[100]:"OFF",[0]:"DEBUG",[1]:"VERBOSE",[2]:"INFO",[3]:"WARN",[4]:"ERROR"};ESC=String.fromCharCode(27);DEFAULT_LOGS_MAX=25;FileLogTransportInstance=class extends LogTransportInterface{fd;logDir;appName;constructor(){super();const rawAppName=process.env["FRONTMCP_APP_NAME"]||"frontmcp";const sanitized=rawAppName.replace(/[^a-zA-Z0-9._-]/g,"_");this.appName=sanitized.length>0?sanitized:"frontmcp";this.logDir=process.env["FRONTMCP_LOG_DIR"]||getPath().join(process.env["FRONTMCP_HOME"]||getPath().join(getOs().homedir(),".frontmcp"),"logs");const logsMax=parseInt(process.env["FRONTMCP_LOGS_MAX"]||"",10);if(logsMax===0){this.fd=void 0;return}try{getFs().mkdirSync(this.logDir,{recursive:true});const ts=new Date().toISOString().replace(/:/g,"_");const filePath=getPath().join(this.logDir,`${this.appName}-${ts}.log`);this.fd=getFs().openSync(filePath,"a");this.rotate(isNaN(logsMax)?DEFAULT_LOGS_MAX:logsMax)}catch{this.fd=void 0}}close(){if(this.fd!==void 0){try{getFs().closeSync(this.fd)}catch{}this.fd=void 0}}log(rec){if(this.fd===void 0)return;const ts=rec.timestamp.toISOString();const level=LOG_LEVEL_LABELS[rec.level]??"INFO";const prefix=rec.prefix?` [${rec.prefix}]`:"";const message=stripAnsi(String(rec.message));const line=`[${ts}] ${level}${prefix} ${message}
475
475
  `;try{getFs().writeSync(this.fd,line)}catch{}}rotate(maxFiles){try{const prefix=`${this.appName}-`;const files=getFs().readdirSync(this.logDir).filter(f=>f.startsWith(prefix)&&f.endsWith(".log")).sort();const excess=files.length-maxFiles;if(excess<=0)return;for(let i=0;i<excess;i++){try{getFs().unlinkSync(getPath().join(this.logDir,files[i]))}catch{}}}catch{}}};FileLogTransportInstance=__decorateClass([FrontMcpLogTransport({name:"FileLogger",description:"Writes logs to a file for CLI mode diagnostics"})],FileLogTransportInstance)}});var detached_job_worker_exports={};__export(detached_job_worker_exports,{runDetachedJob:()=>runDetachedJob});async function runDetachedJob(config,runId,boot=bootRunner){delete process.env[RUN_JOB_ENV_VAR];let host;try{host=await boot(config)}catch(error){await reportBootFailure(config,runId,error);return 1}const stop=()=>void host.shutdown().catch(()=>void 0);process.once("SIGTERM",stop);process.once("SIGINT",stop);const keepAlive=setInterval(()=>void 0,6e4);try{await(await managerOf(host,runId))?.runDetached(runId);return 0}finally{clearInterval(keepAlive);process.off("SIGTERM",stop);process.off("SIGINT",stop);await host.shutdown().catch(()=>void 0)}}async function bootRunner(config){const{FrontMcpInstance:FrontMcpInstance2}=await Promise.resolve().then(()=>(init_front_mcp(),front_mcp_exports));const parsed=frontMcpMetadataSchema.parse({...config,http:void 0,serve:false});markDirectOnly(parsed);parsed[JOB_WORKER_FLAG]=true;const instance=new FrontMcpInstance2(parsed);await instance.ready;return instance}async function managerOf(host,runId){for(const scope of host.getScopes()){const manager=jobExecutionManagerOf(scope);const record=await manager?.getStatus(runId);if(record&&(record.scopeId===void 0||record.scopeId===scope.id))return manager}return void 0}async function reportBootFailure(config,runId,cause){const sqlite=config.sqlite&&{...config.sqlite,path:config.sqlite.path||resolveDefaultSqlitePath({appName:config.info?.name,cliMode:false})};const jobs=config.jobs;const store=resolveJobsStore(jobs?.store,{redis:config.redis,sqlite});try{const{store:stateStore}=await createJobStateStore({redis:store?.redis,sqlite:store?.sqlite,keyPrefix:store?.keyPrefix??"mcp:jobs:"});try{const record=await stateStore.getRun(runId);if(!record||FINISHED_JOB_STATES.has(record.state)||await stateStore.isCancelRequested?.(runId))return;const error=new JobRunnerBootError(runId,toJobError(cause).message);await stateStore.updateRun(runId,{state:"failed",error:{name:error.name,message:error.message},completedAt:Date.now()})}finally{await stateStore.dispose()}}catch{}}var init_detached_job_worker=__esm({"libs/sdk/src/job/runner/detached-job.worker.ts"(){"use strict";init_common();init_resolve();init_errors();init_detached_job_flag();init_direct_only_flag();init_job_attempt();init_job_run_access();init_job_scope_helper();init_job_state_store_factory();init_job_state_interface()}});function toByteStream(streamLike){const iter=streamLike[Symbol.asyncIterator];if(typeof iter!=="function"){return new ReadableStream({start:c=>c.close()})}const it=iter.call(streamLike);return new ReadableStream({async pull(controller){const{value,done}=await it.next();if(done){controller.close();return}controller.enqueue(typeof value==="string"?encoder7.encode(value):value)},async cancel(){await it.return?.(void 0)}})}function bytesFrom(body,encoding){if(typeof body!=="string")return body;if(encoding==="base64")return Uint8Array.from(atob(body),c=>c.charCodeAt(0));if(encoding==="hex"){if(body.length%2!==0||!/^[0-9a-fA-F]*$/.test(body)){throw new TypeError("Invalid hex-encoded body")}const out=new Uint8Array(body.length/2);for(let i=0;i<out.length;i++)out[i]=parseInt(body.slice(i*2,i*2+2),16);return out}return encoder7.encode(body)}function buildHeaders(out,contentType2){const headers=new Headers;if(contentType2)headers.set("Content-Type",contentType2);const extra=out["headers"];if(extra)for(const[k,v]of Object.entries(extra))headers.set(k,v);const cookies=out["cookies"];if(Array.isArray(cookies)){for(const c of cookies)headers.append("Set-Cookie",typeof c==="string"?c:serializeHttpCookie(c))}return headers}function renderHttpOutputToWebResponse(output){const out=output;switch(out.kind){case"web-response":return out.response;case"next":case"consumed":return void 0;case"redirect":{const headers=buildHeaders(out);headers.set("Location",out.location);return new Response(null,{status:out.status,headers})}case"json":case"jsonrpc":case"problem":return new Response(JSON.stringify(out.body),{status:out.status,headers:buildHeaders(out,out.contentType)});case"text":case"html":return new Response(out.body,{status:out.status,headers:buildHeaders(out,out.contentType)});case"binary":case"image":{const headers=buildHeaders(out,out.contentType);headers.set("Content-Disposition",out.filename?`${out.disposition}; filename="${out.filename}"`:out.disposition);return new Response(bytesFrom(out.body,out.encoding),{status:out.status,headers})}case"stream":case"sse":{const headers=buildHeaders(out,out.contentType);if(out.kind==="sse"&&!headers.has("Cache-Control"))headers.set("Cache-Control","no-cache");return new Response(toByteStream(out.stream),{status:out.status,headers})}case"empty":return new Response(null,{status:out.status,headers:buildHeaders(out)});default:return void 0}}var encoder7;var init_web_response_renderer=__esm({"libs/sdk/src/transport/web-response.renderer.ts"(){"use strict";init_http_output_schema();encoder7=new TextEncoder}});import{runRequestExclusive as runRequestExclusive6}from"@frontmcp/utils";function findRoute(routes,request2){for(const route of routes){if(route.method!==request2.method)continue;const params=matchRoutePath(route.path,request2.path);if(params)return{route,params}}return void 0}function createWebRouteResponse(){let controller;const body=new ReadableStream({start:streamController=>controller=streamController});let resolveRendered=()=>void 0;const rendered=new Promise(resolve4=>resolveRendered=resolve4);const response=new RelayServerResponse({head(status,headers){const webHeaders=new Headers;for(const[name51,value]of Object.entries(headers)){for(const item of Array.isArray(value)?value:[value])webHeaders.append(name51,item)}resolveRendered(new Response(BODYLESS_STATUSES.has(status)?null:body,{status,headers:webHeaders}))},data(chunk){const data=decodeRelayChunk(chunk);controller?.enqueue(typeof data==="string"?encoder8.encode(data):data)},end(){controller?.close()}});const failBody=error=>{response.destroy();controller?.error(error)};return{response,rendered,failBody}}function failureResponse(error){const output=flowErrorToHttpOutput(error);return output?renderHttpOutputToWebResponse(output):Response.json({error:"Internal Server Error"},{status:500})}function serveHttpRouteWeb(routes,request2,logger){const match=findRoute(routes,request2);if(!match)return Promise.resolve(void 0);request2.params={...match.params,...request2.params};const{response,rendered,failBody}=createWebRouteResponse();return new Promise(resolve4=>{void rendered.then(resolve4);const passOn=()=>resolve4(void 0);runRequestExclusive6(async()=>match.route.handler(request2,response.asServerResponse(),passOn)).catch(error=>{if(!response.headersSent){resolve4(failureResponse(error));return}logger.error(`HTTP route ${match.route.method} ${match.route.path} failed after its response started`,error);failBody(error)})})}var encoder8,BODYLESS_STATUSES;var init_web_http_route=__esm({"libs/sdk/src/transport/web-http-route.ts"(){"use strict";init_flow_http_path();init_flow_error_output();init_relay_http();init_web_response_renderer();encoder8=new TextEncoder;BODYLESS_STATUSES=new Set([101,204,205,304])}});var web_fetch_handler_exports={};__export(web_fetch_handler_exports,{createDeferredServerBuild:()=>createDeferredServerBuild,createServerFetchHandler:()=>createServerFetchHandler,createWebFetchHandler:()=>createWebFetchHandler,misconfigurationResponse:()=>misconfigurationResponse,runHttpRequestFlowWeb:()=>runHttpRequestFlowWeb,runMatchingHttpFlowWeb:()=>runMatchingHttpFlowWeb,startupFailureResponse:()=>startupFailureResponse});import{runRequestExclusive as runRequestExclusive7}from"@frontmcp/utils";function isCloudflareWorkersRuntime(request2){if(typeof navigator!=="undefined"&&navigator.userAgent===CLOUDFLARE_WORKERS_USER_AGENT)return true;const cloudflareProperties=request2.cf;return typeof cloudflareProperties==="object"&&cloudflareProperties!==null}function resolvePeerAddress(request2,ctx){if(carriedPeerAddresses.has(request2))return carriedPeerAddresses.get(request2);if(typeof ctx?.requestIP==="function")return ctx.requestIP(request2)?.address;if(typeof ctx?.remoteAddr?.hostname==="string")return ctx.remoteAddr.hostname;if(isCloudflareWorkersRuntime(request2))return request2.headers.get("cf-connecting-ip")??void 0;return void 0}function mapHttpCors(httpCors,scope){if(!httpCors)return void 0;const{origin,credentials,maxAge}=httpCors;if(typeof origin==="function"){scope.logger.warn("[web-fetch] http.cors.origin is a function, which the worker adapter cannot replay \u2014 CORS left disabled. Use a static origin (true / string / string[]).");return void 0}return{origin,credentials,maxAge}}function metricsResponse(result){if(result.kind==="json")return Response.json(result.body,{status:result.status,headers:result.headers});return new Response(result.body,{status:result.status,headers:result.headers})}function createWebFetchHandler(scope,options={}){return buildWebFetchHandler(scope,options)}function buildWebFetchHandler(scope,options,listedEntryPaths){const httpConfig=scope.metadata.http;const healthConfig=scope.metadata.health??{};const healthEnabled=healthConfig.enabled!==false;const healthzPath=healthConfig.healthzPath??"/healthz";const readyzPath=healthConfig.readyzPath??"/readyz";const readyzEnabled=isReadyzEnabled(healthConfig);const bodyLimit=parseByteLimit(httpConfig?.bodyLimit);const securityHeaders=resolveSecurityHeaders(httpConfig?.securityHeaders);const normalizePath=p=>{const withSlash=p.startsWith("/")?p:`/${p}`;let end=withSlash.length;while(end>1&&withSlash.charCodeAt(end-1)===47)end--;return withSlash.slice(0,end)};const rawEntry=options.entryPath??(normalizeEntryPrefix(resolveEntryPath(httpConfig?.entryPath))||"/");const entryPaths=new Set((Array.isArray(rawEntry)?rawEntry:[rawEntry]).map(normalizePath));const cors2=options.cors??mapHttpCors(resolveHttpCors(httpConfig?.cors),scope);const corsEnabled=cors2?.origin!==void 0&&cors2.origin!==false;const rebinding=httpConfig?.security?.dnsRebindingProtection;const hostValidation=rebinding?.enabled===false||!rebinding?.allowedHosts?.length&&!rebinding?.allowedOrigins?.length?void 0:compileHostValidation({allowedHosts:rebinding.allowedHosts,allowedOrigins:rebinding.allowedOrigins});const corsHeadersFor=request2=>{if(!corsEnabled)return{};const reqOrigin=request2.headers.get("origin")??"";let allowOrigin;if(cors2.origin===true)allowOrigin=reqOrigin||"*";else if(cors2.origin==="*"||cors2.origin===reqOrigin)allowOrigin=cors2.origin;else if(typeof cors2.origin==="string")allowOrigin=cors2.origin;else if(Array.isArray(cors2.origin))allowOrigin=cors2.origin.includes(reqOrigin)?reqOrigin:void 0;if(!allowOrigin)return{};const h2={"Access-Control-Allow-Origin":allowOrigin,"Access-Control-Allow-Methods":(cors2.methods??["GET","POST","OPTIONS","DELETE"]).join(", "),"Access-Control-Allow-Headers":(cors2.headers??[request2.headers.get("access-control-request-headers")||"content-type, authorization, mcp-session-id, mcp-protocol-version, last-event-id"]).join(", "),"Access-Control-Expose-Headers":(cors2.exposeHeaders??["Mcp-Session-Id","WWW-Authenticate"]).join(", ")};if(cors2.credentials)h2["Access-Control-Allow-Credentials"]="true";if(cors2.maxAge!==void 0)h2["Access-Control-Max-Age"]=String(cors2.maxAge);if(allowOrigin!=="*")h2["Vary"]="Origin";return h2};const withCors=(response,request2)=>{if(!corsEnabled||response.headers.has("access-control-allow-origin"))return response;const headers=new Headers(response.headers);for(const[k,v]of Object.entries(corsHeadersFor(request2)))headers.set(k,v);return new Response(response.body,{status:response.status,statusText:response.statusText,headers})};const metrics=options.metrics?.config.enabled===true?options.metrics:void 0;const metricsEndpoint=metrics?normalizePath(metricsPath(metrics.config)):void 0;if(metrics&&metricsEndpoint&&entryPaths.has(metricsEndpoint)){throw new MetricsPathConflictError(metricsPath(metrics.config))}const withSecurityHeaders=response=>{const headers=new Headers(response.headers);for(const[k,v]of Object.entries(securityHeaders))if(!headers.has(k))headers.set(k,v);const machineId=machineIdHeader();if(machineId)headers.set(machineId[0],machineId[1]);headers.delete("x-powered-by");return new Response(response.body,{status:response.status,statusText:response.statusText,headers})};const handleRequest=async(request2,ctx,env)=>{const url=new URL(request2.url);if(hostValidation){const rejection=validateHostHeaders({host:request2.headers.get("host")??url.host,forwardedHost:request2.headers.get("x-forwarded-host")??void 0,origin:request2.headers.get("origin")??void 0},hostValidation);if(rejection){return Response.json({error:rejection.error,message:rejection.message},{status:rejection.status})}}const limited=await enforceBodyLimit(request2,bodyLimit,ctx);if(limited instanceof Response)return withCors(limited,request2);request2=limited;if(corsEnabled&&request2.method==="OPTIONS"&&url.pathname!==serverCardPath(scope)){return new Response(null,{status:204,headers:corsHeadersFor(request2)})}if(options.healthPaths?options.healthPaths.includes(url.pathname):healthEnabled){const isReadyz=!options.healthPaths&&url.pathname===readyzPath&&readyzEnabled;const isHealthz=options.healthPaths?url.pathname!=="/readyz":url.pathname===healthzPath||url.pathname==="/health";if(isReadyz&&scope.healthService){const readiness=await scope.healthService.getReadyz();return withCors(Response.json({...readiness,transport:"web-fetch"},{status:readiness.status==="ready"?200:503,headers:{"Cache-Control":"no-store"}}),request2)}if(isHealthz||isReadyz||options.healthPaths){return withCors(Response.json({status:"ok",server:scope.metadata.info,transport:"web-fetch"},{headers:{"Cache-Control":"no-store"}}),request2)}}if(metrics&&metricsEndpoint===normalizePath(url.pathname)&&request2.method==="GET"){const scrape=renderMetricsScrape(metrics.service,metrics.config,request2.headers.get("authorization")??void 0);return withCors(metricsResponse(scrape),request2)}const onEntryPath=entryPaths.has(normalizePath(url.pathname));if(!onEntryPath||claimedByHttpRoute(scope,request2,url)){const flowResponse=await runMatchingHttpFlowWeb(scope,request2,{ctx,env});if(flowResponse)return withCors(flowResponse,request2)}if(!onEntryPath){return withCors(Response.json({error:"Not Found",entryPaths:listedEntryPaths??[...entryPaths]},{status:404}),request2)}if(options.sessionRouter){const routed=await options.sessionRouter(request2,env,ctx);if(routed)return withCors(routed,request2)}const rendered=await runHttpRequestFlowWeb(scope,request2,{ctx,env});return withCors(rendered??Response.json({error:"Not Found"},{status:404}),request2)};return async function handle(request2,ctx,env){return withSecurityHeaders(await handleRequest(request2,ctx,env))}}function createServerFetchHandler(primary,scopes,options={}){const routes=scopes.map(scope=>({scope,basePath:`${normalizeEntryPrefix(scope.entryPath)}${normalizeScopeBase(scope.routeBase)}`})).sort((a,b)=>b.basePath.length-a.basePath.length);const endpointPaths=routes.map(({basePath})=>basePath||"/");const handlers=routes.map(({scope,basePath})=>{const scopeOptions={...options,entryPath:basePath||"/",...scope!==primary&&{metrics:void 0}};return{scope,basePath,handler:buildWebFetchHandler(scope,scopeOptions,endpointPaths)}});const primaryRoute=handlers.find(route=>route.scope===primary)??handlers[handlers.length-1];const inScopeOrder=scopes.flatMap(scope=>handlers.filter(route=>route.scope===scope));const isUnder=(path4,basePath)=>basePath!==""&&(path4===basePath||path4.startsWith(`${basePath}/`));const metricsConfig=options.metrics?.config;if(metricsConfig?.enabled===true){const metricsEndpoint=normalizeEntryPrefix(metricsPath(metricsConfig));if(handlers.some(({scope,basePath})=>scope!==primary&&isUnder(metricsEndpoint,basePath))){throw new MetricsPathConflictError(metricsPath(metricsConfig))}}return(request2,ctx,env)=>{const url=new URL(request2.url);const path4=scopePathOf(url.pathname);const route=inScopeOrder.find(({scope})=>claimedByHttpRoute(scope,request2,url))??handlers.find(({basePath})=>isUnder(path4,basePath))??handlers.find(({basePath})=>basePath==="")??primaryRoute;return route.handler(request2,ctx,env)}}function scopePathOf(pathname){return pathname.replace(WELL_KNOWN_SEGMENT,"")||"/"}function payloadTooLarge(limit,length){const error=new PayloadTooLargeError(limit,length);return Response.json({jsonrpc:"2.0",error:error.toJsonRpcError(),id:null},{status:413})}async function enforceBodyLimit(request2,limit,ctx){const method=request2.method.toUpperCase();if(method==="GET"||method==="HEAD"||method==="OPTIONS"||!request2.body)return request2;const declared=request2.headers.get("content-length");if(declared!==null){const length=Number(declared);if(Number.isFinite(length)&&length>limit)return payloadTooLarge(limit,length)}const peerAddress=resolvePeerAddress(request2,ctx);const reader=request2.body.getReader();const chunks=[];let total=0;for(;;){const{done,value}=await reader.read();if(done)break;total+=value.byteLength;if(total>limit){await reader.cancel().catch(()=>void 0);return payloadTooLarge(limit,total)}chunks.push(value)}const buffered=new Uint8Array(total);let offset=0;for(const chunk of chunks){buffered.set(chunk,offset);offset+=chunk.byteLength}const rebuilt=new Request(request2.url,{method:request2.method,headers:request2.headers,body:buffered});carriedPeerAddresses.set(rebuilt,peerAddress);return rebuilt}async function runHttpRequestFlowWeb(scope,request2,opts={}){const url=new URL(request2.url);const serverRequest=await toServerRequest(request2,url,opts.ctx,opts.persistent,opts.env);let output;try{output=await runRequestExclusive7(()=>scope.runFlow("http:request",{request:serverRequest,response:{}}))}catch(error){output=flowErrorToHttpOutput(error)}return output?renderHttpOutputToWebResponse(output):void 0}async function runMatchingHttpFlowWeb(scope,request2,opts={}){const url=new URL(request2.url);const serverRequest=await toServerRequest(request2,url,opts.ctx,void 0,opts.env);const flowName=await scope.findHttpFlowName(serverRequest);if(!flowName)return serveHttpRouteWeb(scope.httpRoutes,serverRequest,scope.logger);let output;try{output=await runRequestExclusive7(()=>scope.runFlow(flowName,{request:serverRequest,response:{}}))}catch(error){output=flowErrorToHttpOutput(error)}return output?renderHttpOutputToWebResponse(output):void 0}function claimedByHttpRoute(scope,request2,url){const table=scope.httpRouteTable;if(!table)return false;const headers={};request2.headers.forEach((value,name51)=>headers[name51]=value);return table.match({method:request2.method,path:url.pathname,headers})!==void 0}async function toServerRequest(request2,url,ctx,persistent,env){const headers={};request2.headers.forEach((v,k)=>{headers[k]=v});headers["host"]=url.host;const query={};url.searchParams.forEach((v,k)=>{const existing=query[k];if(existing===void 0)query[k]=v;else if(Array.isArray(existing))existing.push(v);else query[k]=[existing,v]});const method=request2.method.toUpperCase();const hasBody=method!=="GET"&&method!=="HEAD";let rawBody="";if(hasBody){try{rawBody=await request2.text()}catch{rawBody=""}}let body;if(rawBody){try{body=JSON.parse(rawBody)}catch{body=rawBody}}const init={method:request2.method,headers:request2.headers};if(rawBody)init.body=rawBody;const webRequest=new Request(url.toString(),init);const serverRequest={method,protocol:url.protocol.slice(0,-1),path:url.pathname,url:url.pathname+url.search,headers,query,body,socket:{remoteAddress:resolvePeerAddress(request2,ctx)}};const tokenized=serverRequest;tokenized[ServerRequestTokens.webRequest]=webRequest;tokenized[ServerRequestTokens.webCtx]=ctx;tokenized[ServerRequestTokens.webEnv]=env;if(persistent)tokenized[ServerRequestTokens.webTransport]=persistent;return serverRequest}function misconfigurationResponse(error){const misconfiguration=findMisconfiguration(error);if(!misconfiguration)return void 0;return Response.json(misconfigurationBody(misconfiguration),{status:500})}function createDeferredServerBuild(build,options={}){const now=options.now??Date.now;let built;let inFlight;let failure;return{get(arg){if(built)return Promise.resolve(built.value);if(inFlight)return inFlight;if(failure&&now()<failure.retryAt)return Promise.reject(failure.error);const failures=failure?.count??0;inFlight=build(arg).then(value=>{built={value};failure=void 0;inFlight=void 0;return value},error=>{const delay=Math.min(STARTUP_RETRY_MAX_MS,STARTUP_RETRY_MIN_MS*2**failures);failure={error,retryAt:now()+delay,count:failures+1};inFlight=void 0;options.onFailure?.(error);throw error});return inFlight},retryAfterSeconds(){if(!failure)return 0;return Math.max(1,Math.ceil((failure.retryAt-now())/1e3))}}}function startupFailureResponse(error,retryAfterSeconds=1){const misconfigured=misconfigurationResponse(error);if(misconfigured)return misconfigured;return Response.json({error:"server_unavailable",code:"SERVER_START_FAILED",message:"The server failed to start, so it refuses requests. Its log has the cause; a request after the Retry-After delay tries to start it again."},{status:503,headers:{"Retry-After":String(Math.max(1,retryAfterSeconds))}})}var CLOUDFLARE_WORKERS_USER_AGENT,carriedPeerAddresses,WELL_KNOWN_SEGMENT,STARTUP_RETRY_MIN_MS,STARTUP_RETRY_MAX_MS;var init_web_fetch_handler=__esm({"libs/sdk/src/transport/web-fetch-handler.ts"(){"use strict";init_server_tokens();init_path_utils();init_errors();init_misconfiguration();init_ha_headers();init_health_routes();init_mcp_registry_utils();init_metrics_errors();init_metrics_routes();init_cors_env();init_csp_middleware();init_host_validation();init_body_limit();init_flow_error_output();init_web_http_route();init_web_response_renderer();CLOUDFLARE_WORKERS_USER_AGENT="Cloudflare-Workers";carriedPeerAddresses=new WeakMap;WELL_KNOWN_SEGMENT=/\/\.well-known\/[^/]+/;STARTUP_RETRY_MIN_MS=1e3;STARTUP_RETRY_MAX_MS=6e4}});var static_startup_check_exports={};__export(static_startup_check_exports,{assertStaticStartupConfig:()=>assertStaticStartupConfig});function tryNormalize(normalize){try{return normalize()}catch{return void 0}}function asMetadata(value){return value!==null&&typeof value==="object"?value:void 0}function isServedEverywhere(metadata){const availability=asMetadata(metadata["availableWhen"]);if(!availability)return true;return Object.entries(availability).every(([axis,value])=>value===void 0||axis==="surface"&&Array.isArray(value)&&value.length>0)}function pluginClassOf(record){switch(record.kind){case"CLASS_TOKEN":return record.provide;case"CLASS":return record.useClass;case"VALUE":return record.useValue?.constructor;default:return void 0}}function pluginHooksOf(record){const pluginClass=pluginClassOf(record);if(!pluginClass)return void 0;return[...collectHook(pluginClass),...peekPendingTC39HooksForClass(pluginClass)]}function keysEnforcedByPlugins2(plugins,into=new Set){for(const plugin of plugins??[]){const record=tryNormalize(()=>normalizePlugin(plugin));if(!record)continue;for(const key of record.metadata.enforcesMetadata??[])into.add(key);keysEnforcedByPlugins2(record.metadata.plugins,into)}return into}function collectStaticEntries(config){const found=[];const everyAppKeys=new Set;const ownAppKeys=new Map;const add=(label,metadata,reach)=>{const fields=asMetadata(metadata);if(!fields||!isServedEverywhere(fields))return false;found.push({label,metadata:fields,reach});return true};const keysOfApp=app=>{const keys=ownAppKeys.get(app)??new Set;ownAppKeys.set(app,keys);return keys};const visitPlugins=(plugins,app)=>{for(const plugin of plugins??[]){const record=tryNormalize(()=>normalizePlugin(plugin));if(!record)continue;const hooks=pluginHooksOf(record);if(hooks===void 0||hooks.length>0){const gatesOnlyItsApp=record.metadata.scope!=="server"&&hooks!==void 0&&!hooks.some(hook=>hook.appliesTo==="uncovered-apps"||hook.appliesTo==="all-apps");const keys=app&&gatesOnlyItsApp?keysOfApp(app):everyAppKeys;for(const key of record.metadata.enforcesMetadata??[])keys.add(key)}visitEntries(record.metadata,app)}};const visitEntries=(owner,app)=>{const reach=app?{app}:"every-plugin";const toolReach=app?{app}:"every-app";for(const item of owner.tools??[]){const record=tryNormalize(()=>normalizeTool(item));if(record)add(`Tool "${record.metadata.id||record.metadata.name}"`,record.metadata,toolReach)}for(const item of owner.resources??[]){if(tryNormalize(()=>isResourceTemplate(item))){const record=tryNormalize(()=>normalizeResourceTemplate(item));if(record)add(`Resource template "${record.metadata.name}"`,record.metadata,reach)}else{const record=tryNormalize(()=>normalizeResource(item));if(record)add(`Resource "${record.metadata.name}"`,record.metadata,reach)}}for(const item of owner.prompts??[]){const record=tryNormalize(()=>normalizePrompt(item));if(record)add(`Prompt "${record.metadata.name}"`,record.metadata,reach)}for(const item of owner.agents??[]){const record=tryNormalize(()=>normalizeAgent(item));if(!record)continue;const agentName=record.metadata.id??record.metadata.name;if(!add(`Agent "${agentName}"`,record.metadata,reach))continue;const usesToolFlow=record.metadata.execution?.useToolFlow!==false;const agentKeys=usesToolFlow?keysEnforcedByPlugins2(record.metadata.plugins):new Set;const toolReachInAgent=usesToolFlow&&record.metadata.execution?.inheritPlugins===true?{agentKeys,inherits:toolReach}:{agentKeys};for(const toolItem of record.metadata.tools??[]){const toolRecord=tryNormalize(()=>normalizeTool(toolItem));if(toolRecord)add(`Tool "${agentName}:${toolRecord.metadata.name}"`,toolRecord.metadata,toolReachInAgent)}}for(const item of owner.skills??[]){const record=tryNormalize(()=>normalizeSkill(item));if(record)add(`Skill "${record.metadata.id??record.metadata.name}"`,record.metadata,"every-plugin")}visitPlugins(owner.plugins,app)};const server=config;visitEntries({tools:server.tools,resources:server.resources,skills:server.skills,plugins:server.plugins},void 0);for(const app of server.apps??[]){const record=tryNormalize(()=>normalizeApp(app));if(record?.kind==="LOCAL_CLASS")visitEntries(record.metadata,record)}const everyPluginKeys=new Set([...everyAppKeys,...[...ownAppKeys.values()].flatMap(keys=>[...keys])]);const keysReaching=reach=>{if(reach==="every-plugin")return everyPluginKeys;if(reach==="every-app")return everyAppKeys;if("agentKeys"in reach){return reach.inherits?new Set([...reach.agentKeys,...keysReaching(reach.inherits)]):reach.agentKeys}return new Set([...everyAppKeys,...ownAppKeys.get(reach.app)??[]])};return found.map(({label,metadata,reach})=>({label,metadata,enforcedBy:keysReaching(reach)}))}function assertStaticStartupConfig(config){const entries=collectStaticEntries(config);if(!config.authorities){const labels=entries.filter(({metadata})=>isEnforcementRequested(metadata["authorities"])).map(({label})=>label);if(labels.length>0){const names=labels.slice(0,5).join(", ");const suffix=labels.length>5?` and ${labels.length-5} more`:"";throw new AuthConfigurationError(`Authorities configuration required: ${names}${suffix} declare 'authorities' metadata but authorities enforcement is not fully configured (engine/context builder missing). Add 'authorities: { claimsMapping: {...}, profiles: {...} }' to your @FrontMcp() decorator to enable enforcement, or remove 'authorities' from entry metadata.`,{suggestion:"Add authorities config to @FrontMcp() or remove authorities from entry metadata"})}}const authoritiesConfig=config.authorities;if(authoritiesConfig){const declared=entries.filter(({metadata})=>isEnforcementRequested(metadata["authorities"])).map(({label,metadata})=>({label,authorities:metadata["authorities"]}));assertAuthoritiesRules(createAuthoritiesEngine(authoritiesConfig),declared)}const problems=entries.flatMap(({label,metadata,enforcedBy})=>getEnforcedMetadataKeys().filter(key=>isEnforcementRequested(metadata[key])&&!enforcedBy.has(key)).map(key=>{const enforcer=describeMetadataEnforcer(key);return`${label} declares '${key}'${enforcer?` (enforced by ${enforcer})`:""}`}));if(problems.length>0)throw new UnenforcedMetadataError(problems)}var init_static_startup_check=__esm({"libs/sdk/src/front-mcp/static-startup.check.ts"(){"use strict";init_agent_utils();init_app_utils();init_hook_decorator();init_enforced_metadata_utils();init_errors();init_hooks_utils();init_plugin_utils();init_prompt_utils();init_resource_utils();init_skill_utils();init_tool_utils();init_authorities_engine();init_authorities_rules_check()}});var ipc_server_transport_exports={};__export(ipc_server_transport_exports,{IPC_READY_MESSAGE:()=>IPC_READY_MESSAGE,IpcServerTransport:()=>IpcServerTransport,isIpcStdioRequested:()=>isIpcStdioRequested});function isIpcStdioRequested(){return!!process.env["FRONTMCP_DEV_STDIO_FD"]&&typeof process.send==="function"}var IPC_READY_MESSAGE,IpcServerTransport;var init_ipc_server_transport=__esm({"libs/sdk/src/transport/ipc-server.transport.ts"(){"use strict";IPC_READY_MESSAGE={__frontmcp:"ready"};IpcServerTransport=class{onclose;onerror;onmessage;started=false;handleMessage=raw=>{if(!raw||typeof raw!=="object"||raw.__frontmcp!==void 0)return;this.onmessage?.(raw)};handleDisconnect=()=>{this.onclose?.()};async start(){if(this.started)throw new Error("IpcServerTransport already started");if(typeof process.send!=="function"){throw new Error("IpcServerTransport requires a process forked with an IPC channel")}this.started=true;process.on("message",this.handleMessage);process.once("disconnect",this.handleDisconnect);process.send(IPC_READY_MESSAGE)}async send(message){const send=process.send;if(!process.connected||typeof send!=="function"){throw new Error("IPC channel is closed")}await new Promise((resolve4,reject)=>{send.call(process,message,err=>err?reject(err):resolve4())})}async close(){process.off("message",this.handleMessage);process.off("disconnect",this.handleDisconnect);this.started=false;this.onclose?.()}}}});var stdio_revision_router_exports={};__export(stdio_revision_router_exports,{StdioRevisionRouter:()=>StdioRevisionRouter});import{isJSONRPCErrorResponse,isJSONRPCNotification,isJSONRPCRequest,isJSONRPCResultResponse}from"@frontmcp/protocol";function eventData(event){return event.split("\n").filter(line=>line.startsWith(EVENT_DATA_FIELD)).map(line=>line.slice(EVENT_DATA_FIELD.length).trimStart()).join("\n")}async function*eventStreamMessages(stream){const decoder2=new TextDecoder;let pending="";for await(const chunk of stream){pending+=decoder2.decode(chunk,{stream:true});let boundary=pending.indexOf(EVENT_SEPARATOR);while(boundary!==-1){const data=eventData(pending.slice(0,boundary));pending=pending.slice(boundary+EVENT_SEPARATOR.length);if(data)yield JSON.parse(data);boundary=pending.indexOf(EVENT_SEPARATOR)}}}function isAsyncIterable(stream){return Symbol.asyncIterator in stream}function cancelledRequestId(message){if(!isJSONRPCNotification(message)||message.method!=="notifications/cancelled")return void 0;const requestId=message.params?.["requestId"];return typeof requestId==="string"||typeof requestId==="number"?requestId:void 0}function internalError(id){return{jsonrpc:"2.0",id,error:{code:-32603,message:"Internal error"}}}var LISTEN_METHOD,EVENT_SEPARATOR,EVENT_DATA_FIELD,StdioRevisionRouter;var init_stdio_revision_router=__esm({"libs/sdk/src/transport/stdio-revision-router.ts"(){"use strict";init_common();init_flow_error_output();init_mcp_20260728();LISTEN_METHOD="subscriptions/listen";EVENT_SEPARATOR="\n\n";EVENT_DATA_FIELD="data:";StdioRevisionRouter=class{constructor(inner,options){this.inner=inner;this.options=options}inner;options;onclose;onerror;onmessage;inFlight=new Map;awaitingReply=new Set;idleWaiters=new Set;era="unknown";async start(){this.inner.onmessage=(message,extra)=>this.route(message,extra);this.inner.onerror=error=>this.onerror?.(error);this.inner.onclose=()=>{this.cancelAll();this.onclose?.()};await this.inner.start()}async send(message,options){if(this.era==="modern"&&isJSONRPCNotification(message))return;try{await this.inner.send(message,options)}finally{const repliedTo=isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)?message.id:void 0;if(repliedTo!==void 0)this.replied(repliedTo)}}async close(){this.cancelAll();await this.inner.close()}whenIdle(timeoutMs){if(this.awaitingReply.size===0)return Promise.resolve();return new Promise(resolve4=>{const done=()=>{clearTimeout(timer);this.idleWaiters.delete(done);resolve4()};const timer=setTimeout(done,timeoutMs);this.idleWaiters.add(done)})}replied(id){this.awaitingReply.delete(id);if(this.awaitingReply.size===0)for(const done of[...this.idleWaiters])done()}route(message,extra){if(isJSONRPCRequest(message)&&message.method!==LISTEN_METHOD)this.awaitingReply.add(message.id);const cancelled=cancelledRequestId(message);if(cancelled!==void 0){this.replied(cancelled);if(this.abortsModernRequest(cancelled))return}if((isJSONRPCRequest(message)||isJSONRPCNotification(message))&&this.servesModern(message)){if(this.era==="unknown")this.era="modern";void this.serveModern(message);return}if(isJSONRPCRequest(message)&&message.method==="initialize")this.era="legacy";this.onmessage?.(message,extra)}servesModern(message){const configured=this.options.scope.metadata.transport?.defaultProtocolVersion??"legacy";return isProtocol20260728Request({headers:void 0,body:message,defaultVersion:this.era==="legacy"?"legacy":configured})}abortsModernRequest(requestId){const controller=this.inFlight.get(requestId);if(!controller)return false;this.inFlight.delete(requestId);controller.abort();return true}async serveModern(message){const id=isJSONRPCRequest(message)?message.id:void 0;const controller=new AbortController;if(id!==void 0)this.inFlight.set(id,controller);try{const output=await this.runFlow(message,controller.signal);if(id!==void 0)await this.reply(output,id,controller.signal)}catch(error){this.options.scope.logger.child("StdioRevisionRouter").error("failed to serve a 2026-07-28 message",{method:message.method,error:error instanceof Error?error.message:String(error)})}finally{if(id!==void 0){if(this.inFlight.get(id)===controller)this.inFlight.delete(id);this.replied(id)}}}async runFlow(message,signal){const origin={principal:this.options.principal,signal};const request2={method:"POST",path:"/",url:"/",headers:{},query:{},body:message,[ServerRequestTokens.stdio]:origin};try{return await this.options.scope.runFlow("handle:mcp-202607280728",{request:request2,response:{}})}catch(error){return flowErrorToHttpOutput(error)}}async reply(output,id,signal){if(output?.kind==="sse"&&isAsyncIterable(output.stream)){for await(const message of eventStreamMessages(output.stream)){if(signal.aborted)return;await this.inner.send(message)}return}if(signal.aborted)return;const body=output?.kind==="json"?output.body:void 0;const isReply=isJSONRPCResultResponse(body)||isJSONRPCErrorResponse(body);await this.inner.send(isReply?body:internalError(id))}cancelAll(){for(const controller of this.inFlight.values())controller.abort();this.inFlight.clear();for(const id of[...this.awaitingReply])this.replied(id)}}}});import*as http2 from"node:http";import{Readable}from"node:stream";function headersOf(init){const headers={};new Headers(init?.headers).forEach((value,name51)=>{headers[name51]=value});return headers}function unixSocketFetch(socketPath){return(input,init)=>new Promise((resolve4,reject)=>{const url=new URL(input instanceof Request?input.url:String(input));const request2=http2.request({socketPath,agent:false,path:`${url.pathname}${url.search}`,method:init?.method??"GET",headers:headersOf(init),signal:init?.signal??void 0},response=>{const headers=new Headers;for(const[name51,value]of Object.entries(response.headers)){if(value!==void 0)headers.set(name51,Array.isArray(value)?value.join(", "):value)}const status=response.statusCode??502;if(status===204||status===304||response.headers["content-length"]==="0"){response.resume();resolve4(new Response(null,{status,headers}));return}resolve4(new Response(Readable.toWeb(response),{status,headers}))});request2.on("error",reject);request2.end(typeof init?.body==="string"?init.body:void 0)})}var init_unix_socket_fetch=__esm({"libs/sdk/src/shared/unix-socket-fetch.ts"(){"use strict"}});import{createSharedServerNonce,verifySharedServerIdentity}from"@frontmcp/auth";function unixEndpoint(socketPath){return{id:`unix:${socketPath}`,baseUrl:"http://localhost",fetch:unixSocketFetch(socketPath)}}function httpEndpoint(port){const baseUrl=`http://127.0.0.1:${port}`;return{id:baseUrl,baseUrl,fetch:(input,init)=>fetch(input,init)}}async function readAnswer(response){const length=Number(response.headers.get("content-length")??Number.NaN);if(!(length<=MAX_ANSWER_BYTES)){await response.body?.cancel();return void 0}return response.json().catch(()=>void 0)}function isSharedVersion(value){return typeof value==="string"&&/^[\x20-\x7e]+$/.test(value)&&value.length<=MAX_SHARED_VERSION_LENGTH}async function identifySharedServer(endpoint,proofKey,timeoutMs=IDENTIFY_TIMEOUT_MS){const nonce=createSharedServerNonce();let response;try{response=await endpoint.fetch(`${endpoint.baseUrl}${SHARED_IDENTIFY_PATH}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({nonce}),signal:AbortSignal.timeout(Math.min(timeoutMs,IDENTIFY_TIMEOUT_MS))})}catch{return{outcome:"unreachable"}}if(!response.ok){await response.body?.cancel();const exiting=response.status===503&&response.headers.get(SHARED_STATE_HEADER)===SHARED_EXITING;return{outcome:exiting?"exiting":"refused"}}const answer=await readAnswer(response);const{proof,version}=typeof answer==="object"&&answer!==null?answer:{};if(isSharedVersion(version)&&verifySharedServerIdentity(proofKey,{endpoint:endpoint.id,nonce,version},proof)){return{outcome:"verified",version}}return{outcome:"refused"}}function fetchAfterIdentity(endpoint,proofKey){return async(input,init)=>{const{outcome}=await identifySharedServer(endpoint,proofKey);if(outcome!=="verified")throw new SharedServerIdentityError(endpoint.id);return endpoint.fetch(input,init)}}async function requestSharedServerDrain(server,version){try{const response=await server.fetch(`${server.endpoint.baseUrl}${SHARED_DRAIN_PATH}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${server.token}`},body:JSON.stringify({version}),signal:AbortSignal.timeout(IDENTIFY_TIMEOUT_MS)});await response.body?.cancel();return response.status===202}catch{return false}}var SHARED_IDENTIFY_PATH,SHARED_DRAIN_PATH,SHARED_STATE_HEADER,SHARED_EXITING,MAX_SHARED_VERSION_LENGTH,IDENTIFY_TIMEOUT_MS,MAX_ANSWER_BYTES;var init_shared_endpoint=__esm({"libs/sdk/src/shared/shared-endpoint.ts"(){"use strict";init_shared_server_errors();init_unix_socket_fetch();SHARED_IDENTIFY_PATH="/.well-known/frontmcp-shared-server";SHARED_DRAIN_PATH=`${SHARED_IDENTIFY_PATH}/drain`;SHARED_STATE_HEADER="x-frontmcp-shared-server";SHARED_EXITING="exiting";MAX_SHARED_VERSION_LENGTH=256;IDENTIFY_TIMEOUT_MS=5e3;MAX_ANSWER_BYTES=1024}});import*as os from"node:os";import*as path2 from"node:path";import{z as z130}from"@frontmcp/lazy-zod";import{getEnv as getEnv21,lstat as lstat3,mkdir as mkdir4,readFile as readFile7,realpath as realpath4,rename,unlink as unlink2,writeFile as writeFile3}from"@frontmcp/utils";function checksFileModes(){return process.platform!=="win32"}function isMissing(error){return error?.code==="ENOENT"}function sharedServerFiles(key){const home=getEnv21("FRONTMCP_HOME")||path2.join(os.homedir(),".frontmcp");const directory=path2.join(path2.resolve(home),"shared",key);return{directory,recordFile:path2.join(directory,"server.json"),socketPath:path2.join(directory,"server.sock"),lockFile:path2.join(directory,"start-lock.sqlite")}}function assertSocketPathFits(files){if(new TextEncoder().encode(files.socketPath).length<=MAX_SOCKET_PATH_BYTES)return;throw new InvalidSharedServerOptionsError(`transport: the socket path ${files.socketPath} is longer than ${MAX_SOCKET_PATH_BYTES} bytes; use a shorter key or FRONTMCP_HOME, or transport 'http'`)}async function prepareSharedDirectory(files){await mkdir4(files.directory,{recursive:true,mode:OWNER_ONLY_DIRECTORY3});if(!checksFileModes())return;for(const directory of new Set([files.directory,await realpath4(files.directory)])){const replaceable=await findReplaceableDirectory(directory);if(!replaceable)continue;const{ownerUid}=replaceable;throw new UnsafeSharedServerDirectoryError(replaceable.directory,replaceable.mode,ownerUid===void 0?"the group or others can write to it":`it belongs to another user (uid ${ownerUid})`)}}async function writeServerRecord(files,record){const temporary=`${files.recordFile}.${process.pid}.tmp`;await unlink2(temporary).catch(error=>{if(!isMissing(error))throw error});await writeFile3(temporary,JSON.stringify(record),{mode:OWNER_ONLY_FILE3,flag:"wx"});await rename(temporary,files.recordFile)}function unsafeFileReason(stats){if(!stats.isFile())return"it is not a regular file";if(stats.uid!==process.getuid?.())return`it belongs to another user (uid ${stats.uid})`;if(stats.mode&GROUP_OR_OTHER_ACCESS3)return"the group or others can read it";return void 0}async function readServerRecord(files){let stats;try{stats=await lstat3(files.recordFile)}catch(error){if(isMissing(error))return void 0;throw error}const unsafe=checksFileModes()?unsafeFileReason(stats):void 0;if(unsafe)throw new UnsafeSharedServerDirectoryError(files.recordFile,stats.mode,unsafe);let content;try{content=JSON.parse(await readFile7(files.recordFile))}catch{return void 0}const parsed=serverRecordSchema.safeParse(content);return parsed.success?parsed.data:void 0}async function removeServerRecord(files,pid){const record=await readServerRecord(files).catch(()=>void 0);if(record?.pid!==pid)return;await unlink2(files.recordFile).catch(error=>{if(!isMissing(error))throw error})}var OWNER_ONLY_DIRECTORY3,OWNER_ONLY_FILE3,GROUP_OR_OTHER_ACCESS3,MAX_SOCKET_PATH_BYTES,serverRecordSchema;var init_shared_files=__esm({"libs/sdk/src/shared/shared-files.ts"(){"use strict";init_shared_server_errors();init_replaceable_directory();OWNER_ONLY_DIRECTORY3=448;OWNER_ONLY_FILE3=384;GROUP_OR_OTHER_ACCESS3=63;MAX_SOCKET_PATH_BYTES=103;serverRecordSchema=z130.object({name:z130.string(),transport:z130.enum(["unix","http"]),port:z130.number().int().min(1).max(65535).optional(),path:z130.string().startsWith("/"),pid:z130.number().int().positive(),secret:z130.string().regex(/^[A-Za-z0-9_-]{43}$/)}).strict().refine(({transport,port})=>transport==="http"===(port!==void 0))}});function compareSharedVersions(version,own){if(version===own)return 0;if(!isValidVersion(version)||!isValidVersion(own))return void 0;return compareVersions(version,own)}var init_shared_version=__esm({"libs/sdk/src/shared/shared-version.ts"(){"use strict";init_semver_utils()}});import{deriveSharedServerKeys}from"@frontmcp/auth";import{getSpawnFn,randomBytes as randomBytes12}from"@frontmcp/utils";function endpointOf(files,record){if(record.transport==="unix")return unixEndpoint(files.socketPath);return record.port===void 0?void 0:httpEndpoint(record.port)}async function findRunning(options,refused2,timeoutMs){const record=await readServerRecord(options.files);if(!record||record.transport!==options.transport)return void 0;const endpoint=endpointOf(options.files,record);if(!endpoint)return void 0;const{proofKey,token}=deriveSharedServerKeys(record.secret);const identified=await identifySharedServer(endpoint,proofKey,timeoutMs);if(identified.outcome==="verified"){const send=record.transport==="http"?fetchAfterIdentity(endpoint,proofKey):endpoint.fetch;const url=`${endpoint.baseUrl}${record.path}`;const server={url,token,pid:record.pid,version:identified.version,endpoint,fetch:send};return{server,name:record.name,proofKey}}if(identified.outcome==="refused"&&!refused2.has(endpoint.id)){refused2.add(endpoint.id);options.logger.warn(`the process at ${endpoint.id} did not prove it is the shared server "${options.key}"; it was not sent the token`)}return void 0}function skewOf(found,options){if(found.name!==options.name){return{embedded:"its key is taken by a server of another info.name; give each server a key of its own"}}const{version}=found.server;const order=compareSharedVersions(version,options.version);if(order===void 0){return{embedded:`the shared server runs version ${version}, which can't be ordered against this session's ${options.version}`}}if(order>=0)return"attach";if(options.replaceOlder)return"replace";return{embedded:`the shared server runs version ${version}, older than this session's ${options.version}, and replaceOlder is off`}}async function ensureSharedServer(options){const{key,budgetMs,pollMs=POLL_MS}=options;const deadline=Date.now()+budgetMs;const remaining=()=>Math.max(deadline-Date.now(),1);const refused2=new Set;let handle;let holding=false;let spawned;let draining;try{for(;;){const found=await findRunning(options,refused2,remaining());const skew=found&&skewOf(found,options);if(found&&skew==="attach")return{server:found.server};if(typeof skew==="object")return skew;handle??=await options.openLock();holding=holding?await handle.lock.renew():await handle.lock.acquire();if(holding&&found){if(draining?.server.endpoint.id!==found.server.endpoint.id){if(await requestSharedServerDrain(found.server,options.version))draining=found}}else if(holding&&!spawned&&!await endpointHeld(options,draining,remaining())){spawned=options.spawnServer(handle.lock.holder)}if(spawned?.exitReason){if(holding)throw new SharedServerStartError(key,spawned.exitReason);spawned=void 0}if(Date.now()>=deadline){throw new SharedServerStartError(key,`no server proved its identity within ${budgetMs} ms`)}await new Promise(resolve4=>setTimeout(resolve4,Math.min(pollMs,remaining())))}}finally{if(holding)await handle?.lock.release().catch(()=>void 0);await handle?.close()}}async function endpointHeld(options,drained,timeoutMs){if(drained){const{outcome:outcome2}=await identifySharedServer(drained.server.endpoint,drained.proofKey,timeoutMs);return outcome2==="verified"||outcome2==="exiting"}if(options.transport!=="unix")return false;const{outcome}=await identifySharedServer(unixEndpoint(options.files.socketPath),randomBytes12(32),timeoutMs);return outcome==="exiting"}function spawnSharedServer(key,startLockHolder){const spawned={exitReason:void 0};const child=getSpawnFn()(process.execPath,[...process.execArgv,...process.argv.slice(1)],{cwd:process.cwd(),detached:true,stdio:"ignore",windowsHide:true,env:{...process.env,[SHARED_SERVE_ENV]:key,[SHARED_START_LOCK_ENV]:startLockHolder}});child.once("error",error=>{spawned.exitReason=`it could not be started (${error.message})`});child.once("exit",(code,signal)=>{spawned.exitReason??=`it exited with ${signal??`code ${code}`}`});child.unref();return spawned}var SHARED_SERVE_ENV,SHARED_START_LOCK_ENV,POLL_MS;var init_ensure_shared_server=__esm({"libs/sdk/src/shared/ensure-shared-server.ts"(){"use strict";init_shared_server_errors();init_shared_endpoint();init_shared_files();init_shared_version();SHARED_SERVE_ENV="FRONTMCP_SHARED_SERVE";SHARED_START_LOCK_ENV="FRONTMCP_SHARED_START_LOCK";POLL_MS=100}});import{createStorage as createStorage7,randomUUID as randomUUID31,writeFile as writeFile4}from"@frontmcp/utils";async function holdStartLock(files,key,holder,ttlSeconds=DEFAULT_TTL_SECONDS){const storage=await openStartLockStorage(files);const lock=new SharedStartLock(storage,key,ttlSeconds,holder);let lost=false;const keep=async()=>{if(!lost&&!await lock.acquire())lost=true;return!lost};let renewing=Promise.resolve();const renewal=setInterval(()=>{renewing=keep().catch(()=>void 0)},ttlSeconds*1e3/5);renewal.unref();return{held:keep,release:async()=>{clearInterval(renewal);await renewing;await lock.release().catch(()=>void 0);await storage.disconnect()}}}async function openStartLockStorage(files){await writeFile4(files.lockFile,"",{mode:OWNER_ONLY_FILE4,flag:"a"});return createStorage7({type:"sqlite",sqlite:{path:files.lockFile},prefix:"frontmcp:shared:",fallback:"error"})}var DEFAULT_TTL_SECONDS,OWNER_ONLY_FILE4,SharedStartLock;var init_start_lock=__esm({"libs/sdk/src/shared/start-lock.ts"(){"use strict";DEFAULT_TTL_SECONDS=10;OWNER_ONLY_FILE4=384;SharedStartLock=class{constructor(storage,key,ttlSeconds=DEFAULT_TTL_SECONDS,holder=randomUUID31()){this.storage=storage;this.ttlSeconds=ttlSeconds;this.holder=holder;this.lockKey=`${key}:start`}storage;ttlSeconds;holder;lockKey;async acquire(){await this.storage.set(this.lockKey,this.holder,{ttlSeconds:this.ttlSeconds,ifNotExists:true});return this.renew()}renew(){return this.storage.expireIfEquals(this.lockKey,this.holder,this.ttlSeconds)}async release(){await this.storage.deleteIfEquals(this.lockKey,this.holder)}}}});import{createBridgeStateMachine,createHttpUpstream,createStdioFramer,listChangedNotifications}from"@frontmcp/utils";function stderrLogger(){const ignore=()=>void 0;const write=level=>(message,data)=>{process.stderr.write(`[frontmcp shared] ${level} ${message}${data?` ${JSON.stringify(data)}`:""}
476
476
  `)};return{path:void 0,debug:ignore,info:ignore,reloadEvent:ignore,warn:write("warn"),error:write("error"),close:async()=>void 0}}function messageOf7(error){return error instanceof Error?error.message:String(error)}function codeOf(error){const code=error?.code;return code??error?.cause?.code}function towardsServer(send){return async(input,init)=>{let response;try{response=await send(input,init)}catch(error){if(init?.signal?.aborted)throw error;const neverSent=error instanceof SharedServerIdentityError||NOT_SENT_CODES.has(String(codeOf(error)));throw new SharedServerLostError(!neverSent,messageOf7(error))}const exiting=response.status===503&&response.headers.get(SHARED_STATE_HEADER)===SHARED_EXITING;if(response.status!==401&&!exiting)return response;await response.body?.cancel();throw new SharedServerLostError(false,exiting?"it is exiting":"it no longer knows the token")}}async function connect3(options,logger){const files=sharedServerFiles(options.key);if(options.transport==="unix")assertSocketPathFits(files);await prepareSharedDirectory(files);try{return await ensureSharedServer({key:options.key,transport:options.transport,files,logger,name:options.name,version:options.version,replaceOlder:options.replaceOlder,budgetMs:options.attachBudgetMs,spawnServer:options.spawnServer??(startLockHolder=>spawnSharedServer(options.key,startLockHolder)),openLock:async()=>{const storage=await openStartLockStorage(files);return{lock:new SharedStartLock(storage,options.key),close:()=>storage.disconnect()}}})}catch(error){if(error instanceof SharedServerStartError)return{embedded:error.message};throw error}}function attachSharedSession(options){const log=stderrLogger();let upstream;let embedded;let stopping;let clientInitialize;let clientInitialized=false;const resends=new WeakMap;const framer=createStdioFramer({input:options.input,output:options.output,log,onFrame:frame3=>fsm.enqueue(frame3)});const fsm=createBridgeStateMachine({log,bufferSize:BUFFER_SIZE,reloadDeadlineMs:options.attachBudgetMs+RELOAD_MARGIN_MS,respond:frame3=>framer.write(frame3),forward});async function forward(frame3){if(frame3.method==="initialize"&&frame3.id!==void 0&&frame3.id!==null){clientInitialize=frame3;clientInitialized=false}else if(frame3.method==="notifications/initialized"){clientInitialized=true}const current=upstream;if(!current)throw new Error("the session has not reached its shared server");try{await current.send(frame3)}catch(error){if(!(error instanceof SharedServerLostError))throw error;lose(current,error);if(frame3===clientInitialize)clientInitialize=void 0;const resent=resends.get(frame3)??0;if(error.reached||resent>=MAX_RESENDS)throw error;resends.set(frame3,resent+1);await fsm.requeue(frame3)}}function lose(lost,error){if(upstream!==lost||stopping)return;upstream=void 0;log.warn("reaching the next shared server",{reason:error.message});fsm.onUpstreamLost(error.message);reach().catch(fail)}function fail(error){const message=messageOf7(error);log.error("attach-failed",{error:message});fsm.onReloadDeadline({error:message})}async function serverToReach(){if(embedded)return embedded;const attachment=await connect3(options,log);if("server"in attachment){const{url,token,fetch:send}=attachment.server;return{url,headers:{authorization:`Bearer ${token}`},fetch:send}}log.warn(`running the shared server "${options.key}" in this process: ${attachment.embedded}`);embedded=await options.embed();return embedded}async function reach(){for(let replays=0;;replays++){const server=await serverToReach();if(stopping){await embedded?.close();return}const next=createHttpUpstream({url:server.url,headers:server.headers,fetch:towardsServer(server.fetch),log,onFrame:frame3=>fsm.relayUpstream(frame3)});try{if(clientInitialize){const result=await next.reinitialize(clientInitialize,clientInitialized);for(const notification of listChangedNotifications(result))await framer.write(notification)}}catch(error){await next.close();if(error instanceof SharedServerLostError&&replays<MAX_RESENDS)continue;throw error}upstream=next;fsm.onChildReady();return}}framer.start();fsm.onBootStart();const attached=reach().catch(error=>{fail(error);throw error});attached.catch(()=>void 0);async function shutdown(){await fsm.stop();await upstream?.endSession();await upstream?.close();await embedded?.close();framer.stop()}return{attached,stop:async()=>{stopping??=shutdown();await stopping}}}var BUFFER_SIZE,RELOAD_MARGIN_MS,MAX_RESENDS,NOT_SENT_CODES,SharedServerLostError;var init_shared_attach=__esm({"libs/sdk/src/shared/shared-attach.ts"(){"use strict";init_mcp_error();init_shared_server_errors();init_ensure_shared_server();init_shared_endpoint();init_shared_files();init_start_lock();BUFFER_SIZE=16;RELOAD_MARGIN_MS=3e4;MAX_RESENDS=3;NOT_SENT_CODES=new Set(["ECONNREFUSED","ENOENT"]);SharedServerLostError=class extends InternalMcpError{constructor(reached,reason){super(`the shared server went away: ${reason}`,"SHARED_SERVER_LOST");this.reached=reached}reached}}});import{proveSharedServerIdentity}from"@frontmcp/auth";import{sha256 as sha2563,timingSafeEqual as timingSafeEqual5}from"@frontmcp/utils";var BEARER,SharedServerIdentity;var init_shared_server_identity=__esm({"libs/sdk/src/shared/shared-server.identity.ts"(){"use strict";BEARER="Bearer ";SharedServerIdentity=class{constructor(keys,endpoint,version){this.endpoint=endpoint;this.version=version;this.#proofKey=keys.proofKey;this.#tokenDigest=sha2563(keys.token)}endpoint;version;#proofKey;#tokenDigest;prove(nonce){const proof=proveSharedServerIdentity(this.#proofKey,{endpoint:this.endpoint,nonce,version:this.version});return{proof,version:this.version}}acceptsToken(authorization){if(typeof authorization!=="string"||!authorization.startsWith(BEARER))return false;return timingSafeEqual5(sha2563(authorization.slice(BEARER.length)),this.#tokenDigest)}}}});function exitingResponse(){return httpRespond.json({error:"the shared server is exiting"},{status:503,headers:{"retry-after":"1",[SHARED_STATE_HEADER]:SHARED_EXITING}})}var Will2,SharedServerLifecycle;var init_shared_server_lifecycle=__esm({"libs/sdk/src/shared/shared-server.lifecycle.ts"(){"use strict";init_common();init_shared_endpoint();({Will:Will2}=FlowHooksOf("http:request"));SharedServerLifecycle=class{#inFlight=0;#lastActivity=Date.now();#exitReason;#settledWaiters=new Set;#resolveExit=()=>void 0;exiting=new Promise(resolve4=>{this.#resolveExit=resolve4});get isExiting(){return this.#exitReason!==void 0}exit(reason){if(this.#exitReason!==void 0)return;this.#exitReason=reason;this.#resolveExit(reason)}touch(){this.#lastActivity=Date.now()}idleFor(now=Date.now()){return this.#inFlight>0?0:now-this.#lastActivity}settled(timeoutMs){if(this.#inFlight===0)return Promise.resolve();return new Promise(resolve4=>{const done=()=>{clearTimeout(timer);this.#settledWaiters.delete(done);resolve4()};const timer=setTimeout(done,timeoutMs);this.#settledWaiters.add(done)})}trackRequest(run){if(run.state.get("verifyResult")?.kind!=="authorized")return;if(this.isExiting)run.respond(exitingResponse());this.#inFlight++;this.#lastActivity=Date.now();const response=run.rawInput.response;if(typeof response?.once==="function")response.once("close",()=>this.finishRequest());else this.finishRequest()}finishRequest(){this.#inFlight--;this.#lastActivity=Date.now();if(this.#inFlight>0)return;for(const done of[...this.#settledWaiters])done()}};__decorateClass([Will2("router")],SharedServerLifecycle.prototype,"trackRequest",1)}});var inputSchema43,outputSchema41,plan48,name49,Stage49,SharedDrainFlow;var init_shared_drain_flow=__esm({"libs/sdk/src/shared/flows/shared.drain.flow.ts"(){"use strict";init_common();init_shared_endpoint();init_shared_server_identity();init_shared_server_lifecycle();init_shared_version();inputSchema43=httpInputSchema;outputSchema41=HttpJsonSchema;plan48={pre:["checkIpFilter","acquireQuota","authorize"],execute:["drain"]};name49="shared:drain";Stage49=StageHookOf(name49);SharedDrainFlow=class extends FlowBase{static canActivate(request2){return request2.path===SHARED_DRAIN_PATH}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async authorize(){if(!this.get(SharedServerIdentity).acceptsToken(this.rawInput.request?.headers?.["authorization"])){this.respond(httpRespond.unauthorized())}}async drain(){const version=this.rawInput.request?.body?.version;if(!isSharedVersion(version)){this.respond(httpRespond.json({error:"version must be the version of the session"},{status:400}));return}const own=this.get(SharedServerIdentity).version;if(!((compareSharedVersions(version,own)??0)>0)){this.respond(httpRespond.json({error:"only a session of a newer version replaces this server",version:own},{status:409}));return}this.get(SharedServerLifecycle).exit(`a session of version ${version} replaces it`);this.respond(httpRespond.json({draining:true},{status:202}))}};__decorateClass([Stage49("checkIpFilter")],SharedDrainFlow.prototype,"checkIpFilter",1);__decorateClass([Stage49("acquireQuota")],SharedDrainFlow.prototype,"acquireQuota",1);__decorateClass([Stage49("authorize")],SharedDrainFlow.prototype,"authorize",1);__decorateClass([Stage49("drain")],SharedDrainFlow.prototype,"drain",1);SharedDrainFlow=__decorateClass([FrontMcpFlow({name:name49,plan:plan48,inputSchema:inputSchema43,outputSchema:outputSchema41,access:"public",middleware:{method:"POST"}})],SharedDrainFlow)}});import{isSharedServerNonce}from"@frontmcp/auth";var inputSchema44,outputSchema42,plan49,name50,Stage50,SharedIdentifyFlow;var init_shared_identify_flow=__esm({"libs/sdk/src/shared/flows/shared.identify.flow.ts"(){"use strict";init_common();init_shared_endpoint();init_shared_server_identity();init_shared_server_lifecycle();inputSchema44=httpInputSchema;outputSchema42=HttpJsonSchema;plan49={pre:["checkIpFilter","acquireQuota"],execute:["prove"]};name50="shared:identify";Stage50=StageHookOf(name50);SharedIdentifyFlow=class extends FlowBase{static canActivate(request2){return request2.path===SHARED_IDENTIFY_PATH}async checkIpFilter(){enforceIpFilter(this.scope,this.tryGetContext()?.metadata.clientIp)}async acquireQuota(){await enforceGlobalRateLimit(this.scope,this.tryGetContext())}async prove(){const nonce=this.rawInput.request?.body?.nonce;if(!isSharedServerNonce(nonce)){this.respond(httpRespond.json({error:"nonce must be 32 random bytes in base64url"},{status:400}));return}const lifecycle=this.get(SharedServerLifecycle);if(lifecycle.isExiting)this.respond(exitingResponse());lifecycle.touch();this.respond(httpRespond.json(this.get(SharedServerIdentity).prove(nonce)))}};__decorateClass([Stage50("checkIpFilter")],SharedIdentifyFlow.prototype,"checkIpFilter",1);__decorateClass([Stage50("acquireQuota")],SharedIdentifyFlow.prototype,"acquireQuota",1);__decorateClass([Stage50("prove")],SharedIdentifyFlow.prototype,"prove",1);SharedIdentifyFlow=__decorateClass([FrontMcpFlow({name:name50,plan:plan49,inputSchema:inputSchema44,outputSchema:outputSchema42,access:"public",middleware:{method:"POST"}})],SharedIdentifyFlow)}});import*as net2 from"node:net";import{createSharedServerSecret,deriveSharedServerKeys as deriveSharedServerKeys2,isStaticMode as isStaticMode2}from"@frontmcp/auth";import{ProviderScope as ProviderScope12}from"@frontmcp/di";import{watchPath}from"@frontmcp/utils";function freeLoopbackPort(){return new Promise((resolve4,reject)=>{const probe2=net2.createServer();probe2.once("error",reject);probe2.listen(0,LOOPBACK,()=>{const{port}=probe2.address();probe2.close(()=>resolve4(port))})})}function sharedHttpOptions(files,port){if(port===void 0)return{socketPath:files.socketPath,cors:false};return{port,cors:false,security:{bindAddress:LOOPBACK,dnsRebindingProtection:{enabled:true,allowedHosts:deriveAllowedHosts({bindAddress:LOOPBACK,port}),allowedOrigins:[]}}}}function withFileLogging(logging){const transports=logging?.transports??[];return{...logging,transports:transports.includes(FileLogTransportInstance)?transports:[...transports,FileLogTransportInstance]}}function assertTokenGuardsEveryScope(instance,key,token){for(const scope of instance.getScopes()){const auth=scope.auth.options;if(isStaticMode2(auth)&&auth.tokens.length===1&&auth.tokens[0]===token)continue;throw new SharedServerStartError(key,`app "${scope.id}" has auth of its own (mode ${auth.mode}), which the shared server's token would not guard; remove auth from its @App, or serve it without runShared()`)}}async function serveShared(serve){const{options}=serve;const files=sharedServerFiles(options.key);if(options.transport==="unix")assertSocketPathFits(files);await prepareSharedDirectory(files);const startLock=await holdStartLock(files,options.key,serve.startLockHolder);try{if(!await startLock.held())throw new SharedServerStartError(options.key,ANOTHER_START);return await startSharedServer(serve,files,startLock)}finally{await startLock.release()}}async function startSharedServer(serve,files,startLock){const{config,options}=serve;const secret=createSharedServerSecret();const keys=deriveSharedServerKeys2(secret);const port=options.transport==="http"?await freeLoopbackPort():void 0;const endpoint=port===void 0?unixEndpoint(files.socketPath):httpEndpoint(port);const lifecycle=new SharedServerLifecycle;const instance=serve.create(frontMcpMetadataSchema.parse({...config,serve:true,http:sharedHttpOptions(files,port),auth:{mode:"static",tokens:[keys.token]},logging:withFileLogging(config.logging),providers:[...config.providers??[],{name:"frontmcp:shared-server-identity",provide:SharedServerIdentity,scope:ProviderScope12.GLOBAL,useValue:new SharedServerIdentity(keys,endpoint.id,config.info.version)},{name:"frontmcp:shared-server-lifecycle",provide:SharedServerLifecycle,scope:ProviderScope12.GLOBAL,useValue:lifecycle}]}));await instance.ready;let scope;try{const primary=instance.getPrimaryScope();if(!primary)throw new InternalMcpError("No scopes initialized. Ensure at least one app is configured.");scope=primary;await scope.registryFlows(SharedIdentifyFlow,SharedDrainFlow);assertTokenGuardsEveryScope(instance,options.key,keys.token);await instance.start();if(!await startLock.held())throw new SharedServerStartError(options.key,ANOTHER_START);await writeServerRecord(files,{name:config.info.name,transport:options.transport,...port===void 0?{}:{port},path:scope.fullPath||"/",pid:process.pid,secret})}catch(error){await instance.shutdown().catch(()=>void 0);throw error}return runUntilExit(serve,files,instance,scope,lifecycle)}function watchForExit(serve,lifecycle){const{idleTimeoutMs,checkout}=serve.options;const intervalMs=serve.watchIntervalMs??WATCH_INTERVAL_MS;const stops=[];if(idleTimeoutMs!==false){const startedAt=Date.now();const timer=setInterval(()=>{if(Math.min(lifecycle.idleFor(),Date.now()-startedAt)<idleTimeoutMs)return;lifecycle.exit(`it had no request for ${idleTimeoutMs} ms`)},Math.min(intervalMs,idleTimeoutMs));timer.unref();stops.push(()=>clearInterval(timer))}if(checkout!==false){const watcher=watchPath(checkout,{intervalMs,onGone:()=>lifecycle.exit(`its checkout ${checkout} was removed`)});stops.push(()=>watcher.close())}return()=>{for(const stop of stops)stop()}}function runUntilExit(serve,files,instance,scope,lifecycle){const stopWatching=watchForExit(serve,lifecycle);let closing;const close=()=>{closing??=(async()=>{lifecycle.exit("it was stopped");stopWatching();await removeServerRecord(files,process.pid).catch(()=>void 0);await Promise.all([lifecycle.settled(DRAIN_MS),new Promise(resolve4=>setTimeout(resolve4,EXIT_GRACE_MS))]);await instance.shutdown()})();return closing};void lifecycle.exiting.then(reason=>{if(closing)return;scope.logger.info(`The shared server "${serve.options.key}" exits: ${reason}`);const deadline=setTimeout(()=>serve.exit(1),EXIT_DEADLINE_MS);close().then(()=>{clearTimeout(deadline);serve.exit(0)},()=>{clearTimeout(deadline);serve.exit(1)})});return{close}}var LOOPBACK,ANOTHER_START,DRAIN_MS,EXIT_GRACE_MS,EXIT_DEADLINE_MS,WATCH_INTERVAL_MS;var init_shared_serve=__esm({"libs/sdk/src/shared/shared-serve.ts"(){"use strict";init_common();init_errors();init_shared_server_errors();init_instance_file_logger();init_resolve_allowed_hosts();init_shared_drain_flow();init_shared_identify_flow();init_shared_endpoint();init_shared_files();init_shared_server_identity();init_shared_server_lifecycle();init_start_lock();LOOPBACK="127.0.0.1";ANOTHER_START="another session is starting it";DRAIN_MS=5e3;EXIT_GRACE_MS=250;EXIT_DEADLINE_MS=15e3;WATCH_INTERVAL_MS=1e3}});import{createSharedServerSecret as createSharedServerSecret2,deriveSharedServerKeys as deriveSharedServerKeys3}from"@frontmcp/auth";async function runEmbeddedServer(config,key,create2){const{token}=deriveSharedServerKeys3(createSharedServerSecret2());const instance=create2(frontMcpMetadataSchema.parse({...config,serve:false,auth:{mode:"static",tokens:[token]}}));await instance.ready;try{const scope=instance.getPrimaryScope();if(!scope)throw new InternalMcpError("No scopes initialized. Ensure at least one app is configured.");assertTokenGuardsEveryScope(instance,key,token);await instance.emitProvidersReady();const handler=createServerFetchHandler(scope,instance.getScopes());return{url:`http://localhost${scope.fullPath||"/"}`,headers:{authorization:`Bearer ${token}`},fetch:(input,init)=>handler(new Request(input,init)),close:()=>instance.shutdown()}}catch(error){await instance.shutdown().catch(()=>void 0);throw error}}var init_shared_embedded=__esm({"libs/sdk/src/shared/shared-embedded.ts"(){"use strict";init_common();init_errors();init_web_fetch_handler();init_shared_serve()}});import*as path3 from"node:path";import{z as z131}from"@frontmcp/lazy-zod";function milliseconds(max,message){return z131.number({message}).int(message).min(1,message).max(max,message)}function parseSharedServerOptions(input,platform=process.platform,entry){const result=sharedServerOptionsSchema.safeParse(input);if(!result.success){const issues=result.error.issues.map(({path:at,message})=>at.length?`${at.join(".")}: ${message}`:message);throw new InvalidSharedServerOptionsError(issues.join("; "))}const{key,transport=platform==="win32"?"http":"unix",checkout}=result.data;if(transport==="unix"&&platform==="win32"){throw new InvalidSharedServerOptionsError("transport: a Unix socket can't be kept owner-only on Windows; use transport 'http'")}return{key,transport,attachBudgetMs:result.data.attachBudgetMs??DEFAULT_ATTACH_BUDGET_MS,replaceOlder:result.data.replaceOlder??true,idleTimeoutMs:result.data.idleTimeoutMs??DEFAULT_IDLE_TIMEOUT_MS2,checkout:checkout===false?false:path3.resolve(checkout??(entry?path3.dirname(entry):process.cwd()))}}var DEFAULT_ATTACH_BUDGET_MS,MAX_ATTACH_BUDGET_MS,DEFAULT_IDLE_TIMEOUT_MS2,MAX_IDLE_TIMEOUT_MS,KEY_FORMAT,WINDOWS_DEVICE,ATTACH_BUDGET,IDLE_TIMEOUT,CHECKOUT,sharedServerOptionsSchema;var init_shared_server_options=__esm({"libs/sdk/src/shared/shared-server.options.ts"(){"use strict";init_shared_server_errors();DEFAULT_ATTACH_BUDGET_MS=15e3;MAX_ATTACH_BUDGET_MS=6e5;DEFAULT_IDLE_TIMEOUT_MS2=6e5;MAX_IDLE_TIMEOUT_MS=6048e5;KEY_FORMAT='key must be 1 to 64 lowercase letters, digits, ".", "_" or "-", starting and ending with a letter or digit';WINDOWS_DEVICE="key can't be a device name Windows reserves (con, prn, aux, nul, com0-9 and lpt0-9)";ATTACH_BUDGET=`attachBudgetMs must be a whole number of milliseconds from 1 to ${MAX_ATTACH_BUDGET_MS}`;IDLE_TIMEOUT=`idleTimeoutMs must be a whole number of milliseconds from 1 to ${MAX_IDLE_TIMEOUT_MS}, or false`;CHECKOUT="checkout must be the path of a folder, or false";sharedServerOptionsSchema=z131.object({key:z131.string({message:"key is required"}).regex(/^[a-z0-9]([a-z0-9._-]{0,62}[a-z0-9])?$/,KEY_FORMAT).refine(key=>!/^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/.test(key),WINDOWS_DEVICE),transport:z131.enum(["unix","http"],{message:"transport must be 'unix' or 'http'"}).optional(),attachBudgetMs:milliseconds(MAX_ATTACH_BUDGET_MS,ATTACH_BUDGET).optional(),replaceOlder:z131.boolean({message:"replaceOlder must be true or false"}).optional(),idleTimeoutMs:z131.union([milliseconds(MAX_IDLE_TIMEOUT_MS,IDLE_TIMEOUT),z131.literal(false)],{message:IDLE_TIMEOUT}).optional(),checkout:z131.union([z131.string().min(1,CHECKOUT).refine(folder=>!folder.includes("\0"),CHECKOUT),z131.literal(false)],{message:CHECKOUT}).optional()}).strict()}});var shared_exports={};__export(shared_exports,{runShared:()=>runShared});import{getEnv as getEnv22,stat as stat6}from"@frontmcp/utils";async function isFolder(folder){try{return(await stat6(folder)).isDirectory()}catch{return false}}async function runShared(config,sharedOptions,create2){const options=parseSharedServerOptions(sharedOptions,process.platform,process.argv[1]);const version=config.info?.version;if(!isSharedVersion(version)){throw new InvalidSharedServerOptionsError(`info.version: a shared server states its version, which must be 1 to ${MAX_SHARED_VERSION_LENGTH} printable ASCII characters`)}if(options.checkout!==false&&!await isFolder(options.checkout)){throw new InvalidSharedServerOptionsError(`checkout: ${options.checkout} is not a folder`)}if(getEnv22(SHARED_SERVE_ENV)===options.key){const startLockHolder=getEnv22(SHARED_START_LOCK_ENV);delete process.env[SHARED_SERVE_ENV];delete process.env[SHARED_START_LOCK_ENV];const server=await serveShared({config,options,create:create2,startLockHolder,exit:code=>process.exit(code)});exitOnShutdownSignals(()=>server.close());return}redirectConsoleToStderr();const session=attachSharedSession({...options,name:config.info.name,version,input:process.stdin,output:process.stdout,embed:()=>runEmbeddedServer(config,options.key,create2)});exitOnShutdownSignals(()=>session.stop(),{deadlineMs:STDIO_SHUTDOWN_DEADLINE_MS,whenOrphaned:{stdin:process.stdin}});await session.attached}var init_shared=__esm({"libs/sdk/src/shared/index.ts"(){"use strict";init_shared_server_errors();init_shutdown_signals();init_stdio_console();init_ensure_shared_server();init_shared_attach();init_shared_embedded();init_shared_endpoint();init_shared_serve();init_shared_server_options()}});var front_mcp_exports={};__export(front_mcp_exports,{FrontMcpInstance:()=>FrontMcpInstance});import{StdioServerTransport}from"@frontmcp/protocol";import{getEnv as getEnv23,getEnvFlag as getEnvFlag3,getRuntimeContext as getRuntimeContext25,isEdgeRuntime as isEdgeRuntime2,randomUUID as randomUUID32}from"@frontmcp/utils";function resolveConfigInput(optionsOrClass){if(typeof optionsOrClass==="function"){const stored=getDecoratorConfig(optionsOrClass);if(stored)return stored;throw new InternalMcpError("runStdio() received a class without @FrontMcp() metadata. Pass a @FrontMcp-decorated class, or the same config object you pass to @FrontMcp().")}return optionsOrClass}function isSchemaExtraction(){return getEnvFlag3("FRONTMCP_SCHEMA_EXTRACT")}async function loadFileLogTransport(){return(await Promise.resolve().then(()=>(init_instance_file_logger(),instance_file_logger_exports))).FileLogTransportInstance}async function parseCliConfig(options,{fileLog}){const parsedConfig=parseFrontMcpConfigLite(options);const fileLogTransport=fileLog?await loadFileLogTransport():void 0;parsedConfig["__cliMode"]=true;const verbose=process.env["FRONTMCP_CLI_VERBOSE"]==="1";if(parsedConfig.logging){parsedConfig.logging.enableConsole=verbose;const transports=parsedConfig.logging.transports??[];if(fileLogTransport&&!transports.includes(fileLogTransport)){transports.push(fileLogTransport)}parsedConfig.logging.transports=transports}else{parsedConfig["logging"]={enableConsole:verbose,transports:fileLogTransport?[fileLogTransport]:[]}}return parsedConfig}async function exitAfterDetachedRun(config,runId){const{runDetachedJob:runDetachedJob2}=await Promise.resolve().then(()=>(init_detached_job_worker(),detached_job_worker_exports));process.exit(await runDetachedJob2(config,runId))}var stdioServing,FrontMcpInstance;var init_front_mcp=__esm({"libs/sdk/src/front-mcp/front-mcp.ts"(){"use strict";init_common();init_front_mcp_stores();init_direct();init_errors();init_logger_registry();init_provider_registry();init_scope_registry();init_skill_instructions_helper();init_task_scope_helper();init_mcp_server_factory();init_detached_job_flag();init_direct_only_flag();init_front_mcp_providers();init_manifest_mode_flag();init_shutdown_signals();init_stdio_console();stdioServing=false;FrontMcpInstance=class _FrontMcpInstance{config;ready;logger;providers;scopes;log;shutdownPromise;initialization;constructor(config){this.config=config;this.initialization=this.initialize();this.ready=this.initialization.catch(error=>this.releaseFailedStart(error))}async releaseFailedStart(error){await this.releaseWithin(DEFAULT_SHUTDOWN_DEADLINE_MS);throw error}async releaseWithin(deadlineMs){let deadline;const outlasted=new Promise(resolve4=>{deadline=setTimeout(()=>resolve4(true),deadlineMs)});const released=this.shutdown().then(()=>false,()=>false);if(await Promise.race([released,outlasted])){this.log?.error(`Releasing a server that failed to start did not finish within ${deadlineMs} ms`)}clearTimeout(deadline)}async initialize(){this.providers=new ProviderRegistry([...createMcpGlobalProviders(this.config)],void 0,{shutdownHookTimeoutMs:this.config.lifecycle?.shutdownHookTimeoutMs});await this.providers.ready;this.logger=new LoggerRegistry(this.providers);await this.logger.ready;this.log=this.providers.get(FrontMcpLogger);const name51=this.config.info?.name;const version=this.config.info?.version;const tag=[name51,version].filter(Boolean).join(" v");this.log?.info(`Initializing FrontMCP${tag?` "${tag}"`:""}...`);this.scopes=new ScopeRegistry(this.providers);await this.scopes.ready}async start(){this.log?.info("Starting FrontMCP server...");const server=this.providers.get(FrontMcpServer);if(!server){throw new ServerNotFoundError}await this.wireHealthService(server);await this.wireMetricsService(server);await server.start();for(const scope of this.getScopes()){await scope.emitServerStarted()}await this.emitProvidersReady();if(getEnv23("FRONTMCP_DEV_BOOTSTRAP_SENTINEL")==="1"){process.stderr.write(`__FRONTMCP_BOOTSTRAP_COMPLETE__ ${JSON.stringify(this.devListenerInfo(server))}
477
477
  `)}}async startOrRelease(){try{await this.start()}catch(error){return this.releaseFailedStart(error)}}devListenerInfo(server){const http3=server.config;const path4=this.getPrimaryScope()?.fullPath||"/";if(http3?.socketPath)return{socketPath:http3.socketPath,path:path4};return typeof http3?.port==="number"?{port:http3.port,path:path4}:{path:path4}}getConfig(){return this.config}getScopes(){return this.scopes.getScopes()}async emitProvidersReady(){for(const scope of this.getScopes()){await scope.providers.runReadyHooks(scope.logger)}}shutdown(){this.shutdownPromise??=this.runShutdown();return this.shutdownPromise}async runShutdown(){await this.initialization.catch(()=>void 0);const scopes=this.scopes?.getScopes()??[];const failures=[];const serverStopped=this.providers?.get(FrontMcpServer)?.stop();for(const scope of scopes){await this.bestEffort("scope shutdown",()=>scope.shutdown(),failures)}await this.bestEffort("server stop",()=>serverStopped,failures);for(const scope of scopes){await this.bestEffort("scope dispose",()=>scope.dispose(),failures)}if(failures.length===1)throw failures[0];if(failures.length>1)throw new AggregateError(failures,`Graceful shutdown: ${failures.length} steps failed`)}async bestEffort(step,run,failures){try{await run()}catch(error){failures.push(error);this.log?.error(`Graceful shutdown: ${step} failed`,error)}}getPrimaryScope(){return this.scopes.getPrimaryScope()}getAppScope(app){const appScopes=this.getScopes().filter(scope2=>scope2.routeBase!=="");const scope=appScopes.find(candidate=>candidate.id===app);if(scope)return scope;const known=appScopes.map(candidate=>`"${candidate.id}"`).join(", ")||"none";throw new ScopeConfigurationError(`No endpoint serves app "${app}" on its own. Apps with an endpoint of their own (splitByApp or standalone): ${known}`)}async wireHealthService(server){const serverInstance=server;if(typeof serverInstance.setHealthService!=="function")return;const healthConfig=this.config.health??{};const scopes=this.getScopes();const scopeServices=scopes.map(s=>s.healthService).filter(hs=>hs!==void 0);if(scopeServices.length===1){serverInstance.setHealthService(scopeServices[0],healthConfig)}else if(scopeServices.length>1){const{HealthService:HealthService2}=await Promise.resolve().then(()=>(init_health2(),health_exports));const composite=new HealthService2(healthConfig,this.config.info);for(const scopeService of scopeServices){for(const probe2 of scopeService.getProbes()){composite.registerProbe(probe2)}}const primaryScope=this.getPrimaryScope();if(primaryScope){composite.setScopeView(primaryScope)}serverInstance.setHealthService(composite,healthConfig)}else{serverInstance.setHealthConfig(healthConfig)}}async wireMetricsService(server){const serverInstance=server;if(typeof serverInstance.setMetricsService!=="function")return;const metricsConfig=this.config.metrics;const service=await this.createMetricsService();if(!metricsConfig||!service){serverInstance.setMetricsConfig(metricsConfig??{});return}serverInstance.setMetricsService(service,metricsConfig)}async createMetricsService(){const metricsConfig=this.config.metrics;if(!metricsConfig||metricsConfig.enabled!==true)return void 0;const{createProcessStatsCollectorIfEnabled:createProcessStatsCollectorIfEnabled2,MetricsService:MetricsService2}=await Promise.resolve().then(()=>(init_metrics2(),metrics_exports));try{const processCollector=createProcessStatsCollectorIfEnabled2(metricsConfig);return new MetricsService2(metricsConfig,processCollector)}catch(err){this.log?.error?.("Failed to wire /metrics endpoint",err);throw err}}static async bootstrap(options){if(isSchemaExtraction())return void 0;const sqlitePath=process.env["FRONTMCP_SQLITE_PATH"];const parsedConfig=frontMcpMetadataSchema.parse(sqlitePath?{...options,sqlite:{...options.sqlite??{},path:sqlitePath}}:options);const detachedRunId=detachedJobRunId();if(detachedRunId){await exitAfterDetachedRun(parsedConfig,detachedRunId);return void 0}const daemonSocket=process.env["FRONTMCP_DAEMON_SOCKET"];if(daemonSocket){await _FrontMcpInstance.runUnixSocket({...parsedConfig,socketPath:daemonSocket});return void 0}markEntryServer(parsedConfig);const frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready;await frontMcp.startOrRelease();exitOnShutdownSignals(()=>frontMcp.shutdown(),{logger:frontMcp.log,whenOrphaned:parsedConfig.lifecycle?.exitWhenOrphaned?{}:void 0});frontMcp.log?.info("FrontMCP bootstrap complete");return frontMcp}static async createHandler(options){const frontMcp=new _FrontMcpInstance(frontMcpMetadataSchema.parse(options));await frontMcp.ready;const server=frontMcp.providers.get(FrontMcpServer);if(!server){throw new ServerNotFoundError}await frontMcp.wireHealthService(server);await frontMcp.wireMetricsService(server);server.prepare();await frontMcp.emitProvidersReady();frontMcp.log?.info("FrontMCP handler created (serverless mode)");return server.getHandler()}static async createFetchHandler(options){const{createDeferredServerBuild:createDeferredServerBuild2,createServerFetchHandler:createServerFetchHandler2,startupFailureResponse:startupFailureResponse2}=await Promise.resolve().then(()=>(init_web_fetch_handler(),web_fetch_handler_exports));const build=async deferred=>{let frontMcp;try{frontMcp=new _FrontMcpInstance(frontMcpMetadataSchema.parse({...options,serve:false}));await frontMcp.ready}catch(err){if(deferred){const configIssues=describeConfigIssues(err);const message="FrontMCP failed to start; requests are refused until a retry succeeds"+(configIssues?`. Invalid configuration: ${configIssues}`:"");if(frontMcp?.log)frontMcp.log.error(message,err);else console.error(`[frontmcp] ${message}`,err)}throw err}const scope=frontMcp.getPrimaryScope();if(!scope){throw new ServerNotFoundError}const metricsService=await frontMcp.createMetricsService();const metricsConfig=frontMcp.config.metrics;await frontMcp.emitProvidersReady();frontMcp.log?.info("FrontMCP fetch handler created (web-standard transport)");return createServerFetchHandler2(scope,frontMcp.getScopes(),metricsService&&metricsConfig?{metrics:{service:metricsService,config:metricsConfig}}:{})};if(!isEdgeRuntime2())return build(false);const{assertStaticStartupConfig:assertStaticStartupConfig2}=await Promise.resolve().then(()=>(init_static_startup_check(),static_startup_check_exports));assertStaticStartupConfig2(options);const server=createDeferredServerBuild2(()=>build(true));return async(request2,ctx,env)=>{let inner;try{inner=await server.get()}catch(err){return startupFailureResponse2(err,server.retryAfterSeconds())}return inner(request2,ctx,env)}}static async createForGraph(options){const parsedConfig=frontMcpMetadataSchema.parse({...options,serve:false});const frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready;return frontMcp}static async createForConnect(options){const parsedConfig=frontMcpMetadataSchema.parse({...options,serve:false});markDirectOnly(parsedConfig);const frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready;return frontMcp}static async createForCli(options){const config=getEnvFlag3("FRONTMCP_BUILD_EXTRACT")?frontMcpMetadataSchema.parse(options):options;const frontMcp=new _FrontMcpInstance(await parseCliConfig(config,{fileLog:true}));await frontMcp.ready;return frontMcp}static async createForManifest(options){const parsedConfig=await parseCliConfig(withoutStores(options),{fileLog:false});markDirectOnly(parsedConfig);markManifestMode(parsedConfig);const frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready;return frontMcp}static async createDirect(options,endpoint){const{workerEnv,...config}=options;const parsedConfig=frontMcpMetadataSchema.parse({...config,http:void 0,serve:false});markDirectOnly(parsedConfig);const frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready;try{const scope=endpoint?.app===void 0?frontMcp.getPrimaryScope():frontMcp.getAppScope(endpoint.app);if(!scope){throw new InternalMcpError("No scopes initialized. Ensure at least one app is configured.")}frontMcp.log?.info("FrontMCP direct server created");const server=new DirectMcpServerImpl(scope,()=>frontMcp.shutdown(),{workerEnv});await frontMcp.emitProvidersReady();return server}catch(error){await frontMcp.shutdown().catch(()=>void 0);throw error}}static async runUnixSocket(options){if(isSchemaExtraction())return{close:async()=>void 0};if(getRuntimeContext25().runtime==="browser"){const{BrowserEntryPointUnavailableError:BrowserEntryPointUnavailableError2}=await Promise.resolve().then(()=>(init_browser_entry_point_errors(),browser_entry_point_errors_exports));throw new BrowserEntryPointUnavailableError2("runUnixSocket")}const{socketPath,sqlite,...configInput}=options;const detachedRunId=detachedJobRunId();if(detachedRunId){await exitAfterDetachedRun({...configInput,...sqlite?{sqlite}:{}},detachedRunId);return{close:async()=>void 0}}const parsedConfig=frontMcpMetadataSchema.parse({...configInput,http:{...configInput.http??{},socketPath},...sqlite?{sqlite}:{}});markEntryServer(parsedConfig);const frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready;await frontMcp.startOrRelease();frontMcp.log?.info(`MCP server listening on unix://${socketPath}`);const shutdown=()=>frontMcp.shutdown();const removeSignalHandlers=exitOnShutdownSignals(shutdown,{logger:frontMcp.log,whenOrphaned:parsedConfig.lifecycle?.exitWhenOrphaned?{}:void 0});const close=async()=>{removeSignalHandlers();await shutdown()};return{close}}static async runStdio(optionsOrClass){if(isSchemaExtraction())return;const options=resolveConfigInput(optionsOrClass);const detachedRunId=detachedJobRunId();if(detachedRunId)return exitAfterDetachedRun(options,detachedRunId);redirectConsoleToStderr();process.env["FRONTMCP_STDIO"]="1";if(stdioServing){console.error("[FrontMCP] runStdio() called more than once; ignoring the duplicate stdio connection.");return}stdioServing=true;let startupSucceeded=false;const startupCleanups=[];try{const parsedConfig=frontMcpMetadataSchema.parse({...options,http:void 0,serve:false});const fileLogTransport=await loadFileLogTransport();if(parsedConfig.logging){parsedConfig.logging.enableConsole=true;const transports=parsedConfig.logging.transports??[];if(!transports.includes(fileLogTransport)){transports.push(fileLogTransport)}parsedConfig.logging.transports=transports}else{parsedConfig["logging"]={enableConsole:true,transports:[fileLogTransport]}}markEntryServer(parsedConfig);const frontMcp=new _FrontMcpInstance(parsedConfig);await frontMcp.ready;startupCleanups.push(()=>frontMcp.releaseWithin(STDIO_SHUTDOWN_DEADLINE_MS));const primaryScope=frontMcp.getPrimaryScope();if(!primaryScope){throw new InternalMcpError("No scopes initialized. Ensure at least one app is configured.")}const scope=primaryScope;const{createMcpHandlers:createMcpHandlers2}=await Promise.resolve().then(()=>(init_mcp_handlers(),mcp_handlers_exports));const hasRemoteApps=scope.apps?.getApps().some(app=>app.isRemote)??false;const hasResources=scope.resources.hasAny()||hasRemoteApps;const hasPrompts=scope.prompts.hasAny()||hasRemoteApps;const completionsCapability=hasPrompts||hasResources?{completions:{}}:{};const remoteCapabilities=hasRemoteApps?{tools:{listChanged:true},resources:{subscribe:true,listChanged:true},prompts:{listChanged:true}}:{};const channelCapabilities=scope.channels?.getCapabilities()??{};const composeInstructions=(caller,clientName)=>composeCallerInstructions(scope,{ctx:caller,clientName});const instructions="";const serverOptions={instructions,capabilities:{...remoteCapabilities,...scope.tools.getCapabilities(),...scope.resources.getCapabilities(),...scope.prompts.getCapabilities(),...scope.agents.getCapabilities(),...channelCapabilities,...completionsCapability,...computeTaskCapabilities(scope),logging:{}},serverInfo:scope.metadata.info};const mcpServer=createMcpServer(scope.metadata.info,serverOptions);startupCleanups.push(()=>mcpServer.close());const sessionId=`stdio:${randomUUID32()}`;const handlers=createMcpHandlers2({scope,serverOptions,composeInstructions});for(const handler of handlers){const originalHandler=handler.handler;const wrappedHandler=async(request2,ctx)=>{const existingAuthInfo=ctx?.["authInfo"];const enrichedCtx={...ctx,authInfo:{...existingAuthInfo,sessionId}};return originalHandler(request2,enrichedCtx)};mcpServer.setRequestHandler(handler.requestSchema,wrappedHandler)}const{IpcServerTransport:IpcServerTransport2,isIpcStdioRequested:isIpcStdioRequested2}=await Promise.resolve().then(()=>(init_ipc_server_transport(),ipc_server_transport_exports));const{StdioRevisionRouter:StdioRevisionRouter2}=await Promise.resolve().then(()=>(init_stdio_revision_router(),stdio_revision_router_exports));const overIpc=isIpcStdioRequested2();const stdioTransport=overIpc?new IpcServerTransport2:new StdioServerTransport;const transport=new StdioRevisionRouter2(stdioTransport,{scope,principal:sessionId});startupCleanups.push(()=>transport.close());await mcpServer.connect(transport);startupSucceeded=true;scope.notifications.registerServer(sessionId,mcpServer);if(scope.channels?.hasAny()){const channelNames=scope.channels.getChannelInstances().map(ch=>ch.name);scope.notifications.subscribeAllChannels(sessionId,channelNames)}await frontMcp.emitProvidersReady();exitOnShutdownSignals(async trigger=>{if(trigger==="stdin-ended")await transport.whenIdle(STDIO_DRAIN_MS);scope.notifications.unregisterServer(sessionId);try{await frontMcp.shutdown()}finally{await mcpServer.close()}},{logger:frontMcp.log,deadlineMs:STDIO_SHUTDOWN_DEADLINE_MS,whenOrphaned:parsedConfig.lifecycle?.exitWhenOrphaned===false?void 0:{stdin:overIpc?void 0:process.stdin}})}finally{if(!startupSucceeded){for(const cleanup of startupCleanups.reverse()){try{await cleanup()}catch{}}stdioServing=false}}}static async runShared(optionsOrClass,shared){if(isSchemaExtraction())return;const options=resolveConfigInput(optionsOrClass);const{runShared:runShared2}=await Promise.resolve().then(()=>(init_shared(),shared_exports));await runShared2(options,shared,config=>new _FrontMcpInstance(config))}}}});function isTaskWorkerProcess(){return typeof process!=="undefined"&&process.env?.[RUN_TASK_ENV_VAR]!==void 0}var TASK_WORKER_MODE_FLAG;var init_execute_task_flag=__esm({"libs/sdk/src/task/runtime/execute-task-flag.ts"(){"use strict";init_cli_task_runner();TASK_WORKER_MODE_FLAG="__taskWorkerMode"}});var execute_task_exports={};__export(execute_task_exports,{executeTaskWorker:()=>executeTaskWorker});import{getHostname as getHostname4}from"@frontmcp/utils";async function executeTaskWorker(options,taskId){const parsedConfig=frontMcpMetadataSchema.parse({...options,http:void 0});parsedConfig[TASK_WORKER_MODE_FLAG]=true;parsedConfig["__cliMode"]=true;if(parsedConfig.logging){parsedConfig.logging.enableConsole=false;const transports=parsedConfig.logging.transports??[];if(!transports.includes(FileLogTransportInstance))transports.push(FileLogTransportInstance);parsedConfig.logging.transports=transports}else{parsedConfig["logging"]={enableConsole:false,transports:[FileLogTransportInstance]}}const instance=new FrontMcpInstance(parsedConfig);await instance.ready;const primary=instance.getPrimaryScope();if(!primary)return fatal("no scope initialized in task worker",instance);const logger=primary.logger.child("task-worker");const scopes=instance.getScopes();const store=primary.taskStore;if(!store||!primary.tasks){return fatal("task worker booted without a task store \u2014 did you forget `tasks.sqlite` in config?",instance,logger)}const anyStore=store;let sessionId;if(typeof anyStore.getDatabase==="function"){const db=anyStore.getDatabase();const row=db.prepare("SELECT session_id FROM mcp_tasks WHERE task_id = ?").get(taskId);sessionId=row?.session_id}if(!sessionId){logger.warn("task worker: task record not found",{taskId});await shutdownScopeResources(scopes);return 0}const record=await store.get(taskId,sessionId);if(!record){logger.warn("task worker: task record missing after session resolution",{taskId});await shutdownScopeResources(scopes);return 0}if(isTerminal(record.status)){logger.info("task worker: record already terminal, nothing to do",{taskId,status:record.status});await shutdownScopeResources(scopes);return 0}const scope=record.scopeId===void 0?primary:scopes.find(candidate=>candidate.id===record.scopeId);const registry=scope?.tasks;if(!scope||!scope.taskStore||!registry){logger.error("task worker: the scope that created the task is not on this server",{taskId,scopeId:record.scopeId});const message="The server no longer has the app that created this task.";const failed=await store.update(taskId,sessionId,{status:"failed",statusMessage:message,outcome:{kind:"error",error:{code:MCP_ERROR_CODES.INTERNAL_ERROR,message}}});if(failed)await store.publishTerminal(failed).catch(()=>void 0);await shutdownScopeResources(scopes);return 1}const taskStore=scope.taskStore;await taskStore.update(taskId,sessionId,{executor:{host:"cli",pid:process.pid,spawnedAt:new Date().toISOString(),hostname:getHostname4()}});const onSignal=()=>registry.abort(taskId,"SIGTERM");process.on("SIGTERM",onSignal);process.on("SIGINT",onSignal);const notifier=new TaskNotifier(scope.notifications,logger);try{await runTaskInBackground({record,cleanedRequestParams:record.request.params,ctx:{authInfo:{sessionId},...record.surface!==void 0&&{surface:record.surface}},scope,store:taskStore,registry,notifier,logger});return 0}catch(err){logger.error("task worker: runner threw",{taskId,error:err instanceof Error?err.message:String(err)});return 1}finally{process.off("SIGTERM",onSignal);process.off("SIGINT",onSignal);await shutdownScopeResources(scopes)}}function fatal(message,_instance,logger){if(logger)logger.error(message);else console.error(`[task-worker] ${message}`);return 2}async function shutdownScopeResources(scopes){for(const scope of scopes){const storeAny=scope.taskStore;if(storeAny?.destroy){try{await storeAny.destroy()}catch{}}}}var init_execute_task=__esm({"libs/sdk/src/task/runtime/execute-task.ts"(){"use strict";init_common();init_mcp_error();init_front_mcp();init_instance_file_logger();init_task_notifier();init_task_runner();init_task_types();init_execute_task_flag()}});import"reflect-metadata";import{getEnvFlag as getEnvFlag4}from"@frontmcp/utils";function getDecoratorConfig(target){if(typeof target!=="function")return void 0;if(typeof Reflect==="undefined")return void 0;const reflect=Reflect;if(typeof reflect.getMetadata!=="function")return void 0;const config=reflect.getMetadata(FRONTMCP_CONFIG_METADATA_KEY,target);return config??void 0}function loadFrontMcpInstance(){return Promise.resolve().then(()=>(init_front_mcp(),front_mcp_exports)).then(({FrontMcpInstance:FrontMcpInstance2})=>FrontMcpInstance2)}function FrontMcp(providedMetadata){const sourceDir=captureCallerDir(FRONT_MCP_DECORATOR_BASENAMES);return target=>{const withSourceDir=sourceDir&&!providedMetadata.__sourceDir?{...providedMetadata,__sourceDir:sourceDir}:providedMetadata;const isBuildExtract=getEnvFlag4("FRONTMCP_BUILD_EXTRACT");const{error,data:parsed}=frontMcpMetadataSchema.safeParse(isBuildExtract?withoutStores(withSourceDir):withSourceDir);if(error){const formatted=error.format();if(formatted.apps){throw new InvalidDecoratorMetadataError("FrontMcp","apps",JSON.stringify(formatted.apps,null,2))}if(formatted.providers){throw new InvalidDecoratorMetadataError("FrontMcp","providers",JSON.stringify(formatted.providers,null,2))}for(const field of["skillsConfig","http","output","clients","offload","instructionsBudget"]){if(formatted[field]){throw new InvalidDecoratorMetadataError("FrontMcp",field,JSON.stringify(formatted[field],null,2))}}const loggingFormat=formatted["logging"];if(loggingFormat?.["transports"]){throw new InvalidDecoratorMetadataError("FrontMcp","logging.transports",JSON.stringify(loggingFormat["transports"],null,2))}throw error}const metadata=isBuildExtract?withStoresOf(parsed,withSourceDir):parsed;Reflect.defineMetadata(FrontMcpTokens.type,true,target);for(const property in metadata){Reflect.defineMetadata(FrontMcpTokens[property]??property,metadata[property],target)}Reflect.defineMetadata(FRONTMCP_CONFIG_METADATA_KEY,metadata,target);const isServerless2=getEnvFlag4("FRONTMCP_SERVERLESS");const isSchemaExtract=getEnvFlag4("FRONTMCP_SCHEMA_EXTRACT");const isStdio=getEnvFlag4("FRONTMCP_STDIO");const taskWorkerId=typeof process!=="undefined"?process.env?.["FRONTMCP_RUN_TASK_ID"]:void 0;if(taskWorkerId&&metadata.serve!==false){void(async()=>{try{const{executeTaskWorker:executeTaskWorker2}=await Promise.resolve().then(()=>(init_execute_task(),execute_task_exports));const code=await executeTaskWorker2(metadata,taskWorkerId);process.exit(code)}catch(err){console.error("[FrontMCP] task worker failed:",err);process.exit(2)}})();return}if(isSchemaExtract||isOffloadWorker()){}else if(isStdio){if(metadata.serve){loadFrontMcpInstance().then(FrontMcpInstance2=>FrontMcpInstance2.runStdio(metadata)).catch(err=>{console.error("[FrontMCP] stdio server failed:",err);process.exit(1)})}}else if(isServerless2){const isWorker=getEnvFlag4("FRONTMCP_WORKER");const handlerPromise=loadFrontMcpInstance().then(FrontMcpInstance2=>isWorker?FrontMcpInstance2.createFetchHandler(metadata):FrontMcpInstance2.createHandler(metadata));setServerlessHandlerPromise(handlerPromise);handlerPromise.then(setServerlessHandler).catch(err=>{const e=err instanceof Error?err:new InternalMcpError(String(err),"SERVERLESS_INIT_FAILED");setServerlessHandlerError(e);console.error("[FrontMCP] Serverless initialization failed:",e)})}else if(metadata.serve){loadFrontMcpInstance().then(FrontMcpInstance2=>FrontMcpInstance2.bootstrap(metadata)).catch(err=>{console.error("[FrontMCP] server failed to start:",err);process.exit(1)})}}}var FRONT_MCP_DECORATOR_BASENAMES,FRONTMCP_CONFIG_METADATA_KEY;var init_front_mcp_decorator=__esm({"libs/sdk/src/common/decorators/front-mcp.decorator.ts"(){"use strict";init_decorator_errors();init_mcp_error();init_serverless_handler();init_offload_worker_globals();init_metadata();init_front_mcp_stores();init_tokens();init_caller_dir_utils();FRONT_MCP_DECORATOR_BASENAMES=["front-mcp.decorator.ts","front-mcp.decorator.js"];FRONTMCP_CONFIG_METADATA_KEY="__frontmcp:config"}});function FrontMcpFlow(providedMetadata){return target=>{const metadata=frontMcpFlowMetadataSchema.parse(providedMetadata);Reflect.defineMetadata(FrontMcpFlowTokens.type,true,target);for(const property in metadata){Reflect.defineMetadata(FrontMcpFlowTokens[property]??property,metadata[property],target)}}}var init_flow_decorator=__esm({"libs/sdk/src/common/decorators/flow.decorator.ts"(){"use strict";init_metadata();init_tokens()}});import"reflect-metadata";import{idFromString as idFromString3}from"@frontmcp/utils";function FrontMcpApp(providedMetadata){const sourceDir=captureCallerDir(APP_DECORATOR_BASENAMES);return target=>{const withSourceDir=sourceDir&&!providedMetadata.__sourceDir?{...providedMetadata,__sourceDir:sourceDir}:providedMetadata;const{error,data:metadata}=frontMcpLocalAppMetadataSchema.safeParse(withSourceDir);if(error){const formatted=error.format();if(formatted.plugins){throw new InvalidDecoratorMetadataError("App","plugins",JSON.stringify(formatted.plugins,null,2))}if(formatted.providers){throw new InvalidDecoratorMetadataError("App","providers",JSON.stringify(formatted.providers,null,2))}if(formatted.authProviders){throw new InvalidDecoratorMetadataError("App","authProviders",JSON.stringify(formatted.authProviders,null,2))}if(formatted.adapters){throw new InvalidDecoratorMetadataError("App","adapters",JSON.stringify(formatted.adapters,null,2))}if(formatted.tools){throw new InvalidDecoratorMetadataError("App","tools",JSON.stringify(formatted.tools,null,2))}if(formatted.resources){throw new InvalidDecoratorMetadataError("App","resources",JSON.stringify(formatted.resources,null,2))}if(formatted.prompts){throw new InvalidDecoratorMetadataError("App","prompts",JSON.stringify(formatted.prompts,null,2))}throw error}Reflect.defineMetadata(FrontMcpLocalAppTokens.type,true,target);for(const property in metadata){Reflect.defineMetadata(FrontMcpLocalAppTokens[property]??property,metadata[property],target)}}}function namespaceIdOf(options){return options?.name===void 0&&options?.namespace?{id:idFromString3(options.namespace)}:{}}function esmApp(specifier,options){const parsed=parsePackageSpecifier(specifier);const packageConfig={};let hasPackageConfig=false;if(options?.loader){packageConfig.loader=options.loader;hasPackageConfig=true}if(options?.autoUpdate){packageConfig.autoUpdate=options.autoUpdate;hasPackageConfig=true}if(options?.cacheTTL!==void 0){packageConfig.cacheTTL=options.cacheTTL;hasPackageConfig=true}if(options?.importMap){packageConfig.importMap=options.importMap;hasPackageConfig=true}return{name:options?.name??parsed.fullName,...namespaceIdOf(options),urlType:"esm",url:specifier,namespace:options?.namespace,description:options?.description,standalone:options?.standalone??false,filter:options?.filter,...hasPackageConfig?{packageConfig}:{}}}function remoteApp(url,options){validateRemoteUrl(url);let derivedName;try{const parsed=new URL(url);derivedName=parsed.hostname.split(".")[0]}catch{derivedName=url}return{name:options?.name??derivedName,...namespaceIdOf(options),urlType:"url",url,namespace:options?.namespace,description:options?.description,standalone:options?.standalone??false,transportOptions:options?.transportOptions,remoteAuth:options?.remoteAuth,refreshInterval:options?.refreshInterval,cacheTTL:options?.cacheTTL,filter:options?.filter}}function frontMcpApp(metadata){const FunctionalApp=class{};FrontMcpApp(metadata)(FunctionalApp);return FunctionalApp}var APP_DECORATOR_BASENAMES,App;var init_app_decorator=__esm({"libs/sdk/src/common/decorators/app.decorator.ts"(){"use strict";init_decorator_errors();init_package_specifier();init_metadata();init_tokens();init_caller_dir_utils();init_validate_remote_url();APP_DECORATOR_BASENAMES=["app.decorator.ts","app.decorator.js"];Object.assign(FrontMcpApp,{esm:esmApp,remote:remoteApp});App=FrontMcpApp}});import"reflect-metadata";function FrontMcpAuthProvider(providedMetadata){return target=>{const metadata=frontMcpAuthProviderMetadataSchema.parse(providedMetadata);Reflect.defineMetadata(FrontMcpAuthProviderTokens.type,true,target);for(const property in metadata){Reflect.defineMetadata(FrontMcpAuthProviderTokens[property]??property,metadata[property],target)}}}var init_auth_provider_decorator=__esm({"libs/sdk/src/common/decorators/auth-provider.decorator.ts"(){"use strict";init_metadata();init_tokens()}});import"reflect-metadata";function FrontMcpAdapter(providedMetadata){return target=>{const metadata=frontMcpAdapterMetadataSchema.parse(providedMetadata);Reflect.defineMetadata(FrontMcpAdapterTokens.type,true,target);for(const property in metadata){Reflect.defineMetadata(FrontMcpAdapterTokens[property]??property,metadata[property],target)}}}var init_adapter_decorator=__esm({"libs/sdk/src/common/decorators/adapter.decorator.ts"(){"use strict";init_metadata();init_tokens()}});import"reflect-metadata";function FrontMcpPlugin(providedMetadata){return target=>{const{error,data:metadata}=frontMcpPluginMetadataSchema.safeParse(providedMetadata);if(error){const formatted=error.format();if(formatted.providers){throw new InvalidDecoratorMetadataError("Plugin","providers",JSON.stringify(formatted.providers,null,2))}if(formatted.adapters){throw new InvalidDecoratorMetadataError("Plugin","adapters",JSON.stringify(formatted.adapters,null,2))}if(formatted.tools){throw new InvalidDecoratorMetadataError("Plugin","tools",JSON.stringify(formatted.tools,null,2))}if(formatted.resources){throw new InvalidDecoratorMetadataError("Plugin","resources",JSON.stringify(formatted.resources,null,2))}if(formatted.prompts){throw new InvalidDecoratorMetadataError("Plugin","prompts",JSON.stringify(formatted.prompts,null,2))}throw error}Reflect.defineMetadata(FrontMcpPluginTokens.type,true,target);for(const property in metadata){Reflect.defineMetadata(FrontMcpPluginTokens[property]??property,metadata[property],target)}if(metadata.enforcesMetadata?.length){registerEnforcedMetadataKeys(metadata.enforcesMetadata,`plugin "${metadata.name}"`)}}}var init_plugin_decorator=__esm({"libs/sdk/src/common/decorators/plugin.decorator.ts"(){"use strict";init_decorator_errors();init_metadata();init_tokens();init_enforced_metadata_utils()}});import"reflect-metadata";function FrontMcpPrompt(providedMetadata){return target=>{const metadata=frontMcpPromptMetadataSchema.parse(providedMetadata);Reflect.defineMetadata(FrontMcpPromptTokens.type,true,target);const extended={};for(const property in metadata){if(FrontMcpPromptTokens[property]){Reflect.defineMetadata(FrontMcpPromptTokens[property],metadata[property],target)}else{extended[property]=metadata[property]}}Reflect.defineMetadata(extendedPromptMetadata,extended,target)}}function frontMcpPrompt(providedMetadata){return execute=>{const metadata=frontMcpPromptMetadataSchema.parse(providedMetadata);const toolFunction=function(){return execute};Object.assign(toolFunction,{[FrontMcpPromptTokens.type]:"function-prompt",[FrontMcpPromptTokens.metadata]:metadata});return toolFunction}}function promptEsm(specifier,targetName,options){const parsed=parsePackageSpecifier(specifier);return{kind:"ESM",provide:Symbol(`esm-prompt:${parsed.fullName}:${targetName}`),specifier:parsed,targetName,options,metadata:{name:targetName,description:`Prompt "${targetName}" from ${parsed.fullName}`,arguments:[],...options?.metadata}}}function promptRemote(url,targetName,options){validateRemoteUrl(url);return{kind:"REMOTE",provide:Symbol(`remote-prompt:${url}:${targetName}`),url,targetName,transportOptions:options?.transportOptions,remoteAuth:options?.remoteAuth,options,metadata:{name:targetName,description:`Remote prompt "${targetName}" from ${url}`,arguments:[],...options?.metadata}}}var Prompt;var init_prompt_decorator=__esm({"libs/sdk/src/common/decorators/prompt.decorator.ts"(){"use strict";init_package_specifier();init_metadata();init_tokens();init_validate_remote_url();Object.assign(FrontMcpPrompt,{esm:promptEsm,remote:promptRemote});Prompt=FrontMcpPrompt}});import"reflect-metadata";function FrontMcpLogTransport(providedMetadata){return target=>{const{error,data:metadata}=frontMcpLogTransportMetadataSchema.safeParse(providedMetadata);Reflect.defineMetadata(FrontMcpLogTransportTokens.type,true,target);for(const property in metadata){Reflect.defineMetadata(FrontMcpLogTransportTokens[property]??property,metadata[property],target)}}}var init_logger_decorator=__esm({"libs/sdk/src/common/decorators/logger.decorator.ts"(){"use strict";init_metadata();init_tokens()}});import"reflect-metadata";function FrontMcpAgent(providedMetadata){return target=>{const metadata=frontMcpAgentMetadataSchema.parse(providedMetadata);Reflect.defineMetadata(FrontMcpAgentTokens.type,true,target);const extended={};for(const property in metadata){if(FrontMcpAgentTokens[property]){Reflect.defineMetadata(FrontMcpAgentTokens[property],metadata[property],target)}else{extended[property]=metadata[property]}}Reflect.defineMetadata(extendedAgentMetadata,extended,target)}}function frontMcpAgent(providedMetadata){return execute=>{const metadata=frontMcpAgentMetadataSchema.parse(providedMetadata);const agentFunction=function(){return execute};Object.assign(agentFunction,{[FrontMcpAgentTokens.type]:"function-agent",[FrontMcpAgentTokens.metadata]:metadata});return agentFunction}}function agentEsm(specifier,targetName,options){const parsed=parsePackageSpecifier(specifier);return{kind:"ESM",provide:Symbol(`esm-agent:${parsed.fullName}:${targetName}`),specifier:parsed,targetName,options,metadata:{name:targetName,description:`Agent "${targetName}" from ${parsed.fullName}`,llm:{adapter:"placeholder"},...options?.metadata}}}function agentRemote(url,targetName,options){validateRemoteUrl(url);return{kind:"REMOTE",provide:Symbol(`remote-agent:${url}:${targetName}`),url,targetName,transportOptions:options?.transportOptions,remoteAuth:options?.remoteAuth,metadata:{name:targetName,description:`Remote agent "${targetName}" from ${url}`,llm:{adapter:"placeholder"},...options?.metadata}}}var Agent;var init_agent_decorator=__esm({"libs/sdk/src/common/decorators/agent.decorator.ts"(){"use strict";init_package_specifier();init_metadata();init_tokens();init_validate_remote_url();Object.assign(FrontMcpAgent,{esm:agentEsm,remote:agentRemote});Agent=FrontMcpAgent}});import"reflect-metadata";function FrontMcpSkill(providedMetadata){const callerDir=resolveCallerDir();return target=>{const metadata=skillMetadataSchema.parse(providedMetadata);Reflect.defineMetadata(FrontMcpSkillTokens.type,true,target);const extended={};for(const property in metadata){const tokenKey=property;if(FrontMcpSkillTokens[tokenKey]){Reflect.defineMetadata(FrontMcpSkillTokens[tokenKey],metadata[property],target)}else{extended[property]=metadata[property]}}Reflect.defineMetadata(extendedSkillMetadata,extended,target);if(callerDir){Reflect.defineMetadata(skillCallerDir,callerDir,target)}}}function frontMcpSkill(providedMetadata){const parsedMetadata=skillMetadataSchema.parse(providedMetadata);const skillToken=Symbol(`skill:${parsedMetadata.name}`);const callerDir=resolveCallerDir();return{kind:"VALUE",provide:skillToken,metadata:parsedMetadata,callerDir}}function resolveCallerDir(){return captureCallerDir(SKILL_DECORATOR_BASENAMES)}function skillEsm(specifier,targetName,options){const parsed=parsePackageSpecifier(specifier);return{kind:"ESM",provide:Symbol(`esm-skill:${parsed.fullName}:${targetName}`),specifier:parsed,targetName,options,metadata:{name:targetName,description:`Skill "${targetName}" from ${parsed.fullName}`,instructions:options?.metadata?.instructions??"",...options?.metadata}}}function skillRemote(url,targetName,options){validateRemoteUrl(url);return{kind:"REMOTE",provide:Symbol(`remote-skill:${url}:${targetName}`),url,targetName,transportOptions:options?.transportOptions,remoteAuth:options?.remoteAuth,metadata:{name:targetName,description:`Remote skill "${targetName}" from ${url}`,instructions:options?.metadata?.instructions??"",...options?.metadata}}}function isSkillDecorated(target){return Reflect.getMetadata(FrontMcpSkillTokens.type,target)===true}function getSkillMetadata(target){if(!isSkillDecorated(target)){return void 0}const metadata={};for(const[key,token]of Object.entries(FrontMcpSkillTokens)){if(key==="type"||key==="metadata")continue;const value=Reflect.getMetadata(token,target);if(value!==void 0){metadata[key]=value}}const extended=Reflect.getMetadata(extendedSkillMetadata,target);if(extended){Object.assign(metadata,extended)}return metadata}var SKILL_DECORATOR_BASENAMES,Skill;var init_skill_decorator=__esm({"libs/sdk/src/common/decorators/skill.decorator.ts"(){"use strict";init_package_specifier();init_metadata();init_tokens();init_caller_dir_utils();init_validate_remote_url();SKILL_DECORATOR_BASENAMES=["skill.decorator.ts","skill.decorator.js"];Object.assign(FrontMcpSkill,{esm:skillEsm,remote:skillRemote});Skill=FrontMcpSkill}});import"reflect-metadata";function _FrontMcpJob(providedMetadata){const declaringModule=captureCallerFile(JOB_DECORATOR_BASENAMES);return target=>{const metadata=frontMcpJobMetadataSchema.parse(providedMetadata);registerWorkerJob(target,providedMetadata,declaringModule);Reflect.defineMetadata(FrontMcpJobTokens.type,true,target);const extended={};for(const property in metadata){if(FrontMcpJobTokens[property]){Reflect.defineMetadata(FrontMcpJobTokens[property],metadata[property],target)}else{extended[property]=metadata[property]}}Reflect.defineMetadata(extendedJobMetadata,extended,target)}}function frontMcpJob(providedMetadata){const declaringModule=captureCallerFile(JOB_DECORATOR_BASENAMES);return execute=>{const metadata=frontMcpJobMetadataSchema.parse(providedMetadata);registerWorkerJob(execute,providedMetadata,declaringModule);const jobFunction=function(){return execute};Object.assign(jobFunction,{[FrontMcpJobTokens.type]:"function-job",[FrontMcpJobTokens.metadata]:metadata});return jobFunction}}function jobEsm(specifier,targetName,options){const parsed=parsePackageSpecifier(specifier);return{kind:"ESM",provide:Symbol(`esm-job:${parsed.fullName}:${targetName}`),specifier:parsed,targetName,options,metadata:{name:targetName,description:`Job "${targetName}" from ${parsed.fullName}`,inputSchema:{},outputSchema:{},...options?.metadata}}}function jobRemote(url,targetName,options){validateRemoteUrl(url);return{kind:"REMOTE",provide:Symbol(`remote-job:${url}:${targetName}`),url,targetName,transportOptions:options?.transportOptions,remoteAuth:options?.remoteAuth,metadata:{name:targetName,description:`Remote job "${targetName}" from ${url}`,inputSchema:{},outputSchema:{},...options?.metadata}}}var JOB_DECORATOR_BASENAMES,FrontMcpJob,Job;var init_job_decorator=__esm({"libs/sdk/src/common/decorators/job.decorator.ts"(){"use strict";init_package_specifier();init_worker_jobs();init_job_metadata();init_tokens();init_caller_dir_utils();init_validate_remote_url();JOB_DECORATOR_BASENAMES=["job.decorator.ts","job.decorator.js","job.decorator.mjs","job.decorator.cjs"];Object.assign(_FrontMcpJob,{esm:jobEsm,remote:jobRemote});FrontMcpJob=_FrontMcpJob;Job=_FrontMcpJob}});import"reflect-metadata";function FrontMcpWorkflow(providedMetadata){return target=>{const metadata=frontMcpWorkflowMetadataSchema.parse(providedMetadata);Reflect.defineMetadata(FrontMcpWorkflowTokens.type,true,target);const extended={};for(const property in metadata){if(FrontMcpWorkflowTokens[property]){Reflect.defineMetadata(FrontMcpWorkflowTokens[property],metadata[property],target)}else{extended[property]=metadata[property]}}Reflect.defineMetadata(extendedWorkflowMetadata,extended,target)}}function frontMcpWorkflow(providedMetadata){const metadata=frontMcpWorkflowMetadataSchema.parse(providedMetadata);const workflowFunction=function(){return metadata};Object.assign(workflowFunction,{[FrontMcpWorkflowTokens.type]:"value-workflow",[FrontMcpWorkflowTokens.metadata]:metadata});return workflowFunction}var init_workflow_decorator=__esm({"libs/sdk/src/common/decorators/workflow.decorator.ts"(){"use strict";init_workflow_metadata();init_tokens()}});import"reflect-metadata";function Duty(metadata){return target=>{const result=dutyMetadataSchema.safeParse(metadata);if(!result.success){const[issue]=result.error.issues;throw new InvalidDecoratorMetadataError("Duty",issue.path.join("."),issue.message)}if(typeof target.prototype?.run!=="function"){throw new InvalidDecoratorMetadataError("Duty","run",`${target.name} has no run() method`)}const{name:name51=target.name,every:everyMs,scope,leaseMs}=result.data;const defaultLeaseMs=Math.min(Math.max(3*everyMs,3e3),6e4);Reflect.defineMetadata(FrontMcpProviderTokens.type,true,target);defineDutyMetadata(target,{name:name51,everyMs,scope,leaseMs:leaseMs??defaultLeaseMs})}}var init_duty_decorator=__esm({"libs/sdk/src/common/decorators/duty.decorator.ts"(){"use strict";init_decorator_errors();init_duty_metadata();init_tokens()}});import"reflect-metadata";import{z as z132}from"@frontmcp/lazy-zod";function HttpRoute(metadata){return target=>{const result=httpRouteMetadataSchema.safeParse(metadata);if(!result.success){const[issue]=result.error.issues;throw new InvalidDecoratorMetadataError("HttpRoute",issue.path.join(".")||"metadata",issue.message)}if(typeof target.prototype?.handle!=="function"){throw new InvalidDecoratorMetadataError("HttpRoute","handle",`${target.name} has no handle() method`)}defineHttpRouteMetadata(target,result.data)}}var httpRouteMetadataSchema;var init_http_route_decorator=__esm({"libs/sdk/src/common/decorators/http-route.decorator.ts"(){"use strict";init_decorator_errors();init_http_route_metadata();httpRouteMetadataSchema=z132.object({method:z132.enum(["GET","POST","PUT","PATCH","DELETE"],{message:"method must be 'GET', 'POST', 'PUT', 'PATCH' or 'DELETE'"}),path:z132.custom(value=>typeof value==="function"||isHttpRoutePath(value),{message:HTTP_ROUTE_PATH_MESSAGE}),auth:z132.enum(["people","subject","public"],{message:"auth must be 'people', 'subject' or 'public'"}).optional(),sse:z132.object({store:z132.custom(value=>typeof value?.subscribe==="function",{message:"sse.store must have subscribe(topic, listener), such as a resourceStore()"}),topics:z132.array(z132.string().min(1,"a topic must not be empty")).min(1,"sse.topics must name at least one topic"),coalesceMs:z132.number().int().nonnegative("sse.coalesceMs must not be negative").default(50),heartbeatMs:z132.number().int().positive("sse.heartbeatMs must be greater than 0").default(15e3)}).strict().optional()}).strict().refine(metadata=>!metadata.sse||metadata.method==="GET",{message:"an sse route must use method GET",path:["sse"]})}});var init_decorators=__esm({"libs/sdk/src/common/decorators/index.ts"(){"use strict";init_front_mcp_decorator();init_flow_decorator();init_hook_decorator();init_app_decorator();init_provider_decorator();init_auth_provider_decorator();init_adapter_decorator();init_plugin_decorator();init_tool_decorator();init_resource_decorator();init_prompt_decorator();init_logger_decorator();init_agent_decorator();init_skill_decorator();init_job_decorator();init_workflow_decorator();init_channel_decorator();init_duty_decorator();init_http_route_decorator()}});var init_dynamic=__esm({"libs/sdk/src/common/dynamic/index.ts"(){"use strict";init_dynamic_adapter();init_dynamic_plugin()}});var ScopeEntry;var init_scope_entry=__esm({"libs/sdk/src/common/entries/scope.entry.ts"(){"use strict";init_utils3();init_base_entry();ScopeEntry=class extends BaseEntry{get fullPath(){const prefix=normalizeEntryPrefix(this.entryPath??"");const scope=normalizeScopeBase(this.routeBase??"");return`${prefix}${scope}`}haManager;lifecycleCallbacks=[];onServerStarted(callback){this.lifecycleCallbacks.push(callback)}async emitServerStarted(){for(const cb of this.lifecycleCallbacks){await cb()}}disposeCallbacks=[];disposeEmitted=false;get isDisposed(){return this.disposeEmitted}onDispose(callback){if(this.disposeEmitted){void this.runDisposeCallback(callback);return()=>void 0}this.disposeCallbacks.push(callback);return()=>{const index=this.disposeCallbacks.indexOf(callback);if(index!==-1)this.disposeCallbacks.splice(index,1)}}async emitDispose(){if(this.disposeEmitted)return;this.disposeEmitted=true;const callbacks=this.disposeCallbacks.splice(0).reverse();for(const cb of callbacks){await this.runDisposeCallback(cb)}}async runDisposeCallback(callback){try{await callback()}catch(error){this.logger.warn(`Scope dispose callback failed: ${error instanceof Error?error.message:String(error)}`)}}}}});import"reflect-metadata";var FlowEntry;var init_flow_entry=__esm({"libs/sdk/src/common/entries/flow.entry.ts"(){"use strict";init_base_entry();FlowEntry=class extends BaseEntry{name;path;method;scope;constructor(scope,record,token,metadata){super(record,token,metadata);const{path:path4,method}=record.metadata.middleware??metadata?.middleware??{};this.name=metadata?.name??record.metadata?.name;this.path=path4;this.method=method;this.scope=scope}}}});var HookEntry;var init_hook_entry=__esm({"libs/sdk/src/common/entries/hook.entry.ts"(){"use strict";init_base_entry();HookEntry=class extends BaseEntry{scope;providers;options;constructor(scope,providers,record,token,metadata){super(record,token,metadata);this.scope=scope;this.providers=providers;this.options={filter:metadata.filter,priority:metadata.priority}}}}});var AppEntry;var init_app_entry=__esm({"libs/sdk/src/common/entries/app.entry.ts"(){"use strict";init_base_entry();AppEntry=class extends BaseEntry{id;get isRemote(){return false}}}});var ProviderEntry;var init_provider_entry=__esm({"libs/sdk/src/common/entries/provider.entry.ts"(){"use strict";init_base_entry();ProviderEntry=class extends BaseEntry{}}});var AuthProviderEntry;var init_auth_provider_entry=__esm({"libs/sdk/src/common/entries/auth-provider.entry.ts"(){"use strict";init_base_entry();AuthProviderEntry=class extends BaseEntry{}}});var PluginEntry;var init_plugin_entry=__esm({"libs/sdk/src/common/entries/plugin.entry.ts"(){"use strict";init_base_entry();PluginEntry=class extends BaseEntry{}}});var AdapterEntry;var init_adapter_entry=__esm({"libs/sdk/src/common/entries/adapter.entry.ts"(){"use strict";init_base_entry();AdapterEntry=class extends BaseEntry{}}});import{toJSONSchema as toJSONSchema8,internalZ as z133}from"@frontmcp/lazy-zod";import{isDebug as isDebug3,isDevelopment as isDevelopment6}from"@frontmcp/utils";function asObjectOutputSchema(json){if(json["type"]==="object")return json;return isObjectSchema(json,json["$defs"],new Set)?{type:"object",...json}:null}function isObjectSchema(schema,definitions,followedRefs){if(typeof schema!=="object"||schema===null)return false;const node=schema;if(node["type"]==="object")return true;const ref=node["$ref"];if(typeof ref==="string"){if(!ref.startsWith(DEFINITION_REF_PREFIX)||followedRefs.has(ref))return false;const definition=definitions?.[ref.slice(DEFINITION_REF_PREFIX.length)];return isObjectSchema(definition,definitions,new Set([...followedRefs,ref]))}const members=node["anyOf"]??node["oneOf"];return Array.isArray(members)&&members.length>0&&members.every(member=>isObjectSchema(member,definitions,followedRefs))}var PRIMITIVE_ZOD_OUTPUT_TYPES,DEFINITION_REF_PREFIX,ToolEntry;var init_tool_entry=__esm({"libs/sdk/src/common/entries/tool.entry.ts"(){"use strict";init_base_entry();PRIMITIVE_ZOD_OUTPUT_TYPES=new Set(["string","number","boolean","bigint","date"]);DEFINITION_REF_PREFIX="#/$defs/";ToolEntry=class extends BaseEntry{owner;name;fullName;inputSchema;rawInputSchema;outputSchema;rawOutputSchema;getOutputSchema(){return this.outputSchema}getRawOutputSchema(){return this.rawOutputSchema}_cachedInputJsonSchema;getInputJsonSchema(){if(this._cachedInputJsonSchema!==void 0)return this._cachedInputJsonSchema;const result=this.computeInputJsonSchema();this._cachedInputJsonSchema=result;return result}computeInputJsonSchema(){if(this.rawInputSchema){if(typeof this.rawInputSchema==="object"&&this.rawInputSchema!==null&&!Array.isArray(this.rawInputSchema)){return this.rawInputSchema}}if(this.inputSchema&&Object.keys(this.inputSchema).length>0){try{return toJSONSchema8(z133.object(this.inputSchema),{io:"input",unrepresentable:"any"})}catch(error){if(isDebug3()||isDevelopment6()){console.warn("[ToolEntry] Failed to convert Zod schema to JSON Schema:",error)}return{type:"object",properties:{}}}}return null}outputJsonSchemaResolution;getOutputJsonSchema(){return this.resolveOutputJsonSchema().schema}getUnlistedOutputSchemaReason(){return this.resolveOutputJsonSchema().unlistedReason}resolveOutputJsonSchema(){this.outputJsonSchemaResolution??=this.computeOutputJsonSchema();return this.outputJsonSchemaResolution}computeOutputJsonSchema(){if(typeof this.rawOutputSchema==="object"&&this.rawOutputSchema!==null&&!Array.isArray(this.rawOutputSchema)){return{schema:this.rawOutputSchema}}const schema=this.outputSchema;if(!schema||typeof schema==="string"||Array.isArray(schema)){return{schema:null}}const isZodSchema=typeof schema.safeParse==="function"&&typeof schema.parse==="function";if(!isZodSchema&&Object.keys(schema).length===0){return{schema:null}}if(isZodSchema&&PRIMITIVE_ZOD_OUTPUT_TYPES.has(schema.type)){return{schema:null}}try{const zodSchema=isZodSchema?schema:z133.object(schema);const objectSchema=asObjectOutputSchema(toJSONSchema8(zodSchema));return objectSchema?{schema:objectSchema}:{schema:null,unlistedReason:"it is not an object schema or a union of object schemas"}}catch(error){const message=error instanceof Error?error.message:String(error);return{schema:null,unlistedReason:`it cannot be converted to JSON Schema (${message})`}}}}}});var ResourceEntry;var init_resource_entry=__esm({"libs/sdk/src/common/entries/resource.entry.ts"(){"use strict";init_base_entry();ResourceEntry=class extends BaseEntry{owner;name;fullName;uri;uriTemplate;isTemplate;getArgumentCompleter(_argName){return null}}}});var PromptEntry;var init_prompt_entry=__esm({"libs/sdk/src/common/entries/prompt.entry.ts"(){"use strict";init_base_entry();PromptEntry=class extends BaseEntry{owner;name;fullName}}});var LoggerEntry;var init_logger_entry=__esm({"libs/sdk/src/common/entries/logger.entry.ts"(){"use strict";init_base_entry();LoggerEntry=class extends BaseEntry{}}});var AgentEntry;var init_agent_entry=__esm({"libs/sdk/src/common/entries/agent.entry.ts"(){"use strict";init_base_entry();AgentEntry=class extends BaseEntry{owner;name;fullName;id;inputSchema;rawInputSchema;outputSchema;systemInstructions;getInputSchema(){return this.inputSchema}getOutputSchema(){return this.outputSchema}}}});var SkillEntry;var init_skill_entry=__esm({"libs/sdk/src/common/entries/skill.entry.ts"(){"use strict";init_metadata();init_base_entry();SkillEntry=class extends BaseEntry{owner;name;fullName;getToolRefs(){const tools=this.metadata.tools;if(!tools)return[];return tools.map(t=>normalizeToolRef(t))}getToolNames(){return this.getToolRefs().map(t=>t.name)}getTags(){return this.metadata.tags??[]}isHidden(){return this.metadata.hideFromDiscovery===true}isAlwaysLoaded(){return this.metadata.alwaysLoad===true}getReferencedOperations(){return this.metadata.referencedOperations??[]}isExecutable(){const hasTools=(this.metadata.tools?.length??0)>0;const hasOps=(this.metadata.referencedOperations?.length??0)>0;return hasTools||hasOps}isKnowledgeOnly(){return!this.isExecutable()}getPriority(){return this.metadata.priority??0}getLicense(){return this.metadata.license}getCompatibility(){return this.metadata.compatibility}getSpecMetadata(){return this.metadata.specMetadata}getAllowedTools(){return this.metadata.allowedTools}getResources(){return this.metadata.resources}getSkillPathSegments(){return this.metadata.skillPath&&this.metadata.skillPath.length>0?[...this.metadata.skillPath]:[this.metadata.name]}getSkillPath(){return this.getSkillPathSegments().join("/")}}}});var ChannelEntry;var init_channel_entry=__esm({"libs/sdk/src/common/entries/channel.entry.ts"(){"use strict";init_base_entry();ChannelEntry=class extends BaseEntry{owner;name;fullName;get source(){return this.metadata.source}get twoWay(){return this.metadata.twoWay===true}get staticMeta(){return this.metadata.meta}getTags(){return this.metadata.tags??[]}}}});var init_entries=__esm({"libs/sdk/src/common/entries/index.ts"(){"use strict";init_base_entry();init_scope_entry();init_flow_entry();init_hook_entry();init_app_entry();init_provider_entry();init_auth_provider_entry();init_plugin_entry();init_adapter_entry();init_tool_entry();init_resource_entry();init_prompt_entry();init_logger_entry();init_agent_entry();init_skill_entry();init_job_entry();init_workflow_entry();init_channel_entry()}});import{internalZ as z134}from"@frontmcp/lazy-zod";function parseListInput(rawInput,schema,expectedMethod){let method;let params;try{const inputData=schema.parse(rawInput);method=inputData.request.method;params=inputData.request.params??{}}catch(e){throw new InvalidInputError("Invalid request format",e instanceof z134.ZodError?e.issues:void 0)}if(method!==expectedMethod){throw new InvalidMethodError(method,expectedMethod)}return{cursor:params?.["cursor"],params}}function resolveNameConflicts(entries,getBaseName){const counts=new Map;for(const{entry}of entries){const baseName=getBaseName(entry);counts.set(baseName,(counts.get(baseName)??0)+1)}const conflicts=new Set([...counts.entries()].filter(([,n])=>n>1).map(([k])=>k));return entries.map(({ownerName,entry})=>{const baseName=getBaseName(entry);const finalName=conflicts.has(baseName)?`${ownerName}:${baseName}`:baseName;return{ownerName,entry,finalName}})}function previewItems(items,getName,n=5){const names=items.slice(0,n).map(getName);const preview=names.join(", ");const extra=items.length>n?`, +${items.length-n} more`:"";return`${preview}${extra}`}function detectConflicts(entries,getBaseName){const counts=new Map;for(const entry of entries){const baseName=getBaseName(entry);counts.set(baseName,(counts.get(baseName)??0)+1)}const conflictNames=[...counts.entries()].filter(([,n])=>n>1).map(([k])=>k);return{count:conflictNames.length,names:conflictNames}}var init_flow_utils3=__esm({"libs/sdk/src/common/flow/flow.utils.ts"(){"use strict";init_errors()}});var ToolHookStage;var init_tool_hook_interface=__esm({"libs/sdk/src/common/interfaces/tool-hook.interface.ts"(){"use strict";ToolHookStage=(ToolHookStage2=>{ToolHookStage2["willBindProviders"]="willBindProviders";ToolHookStage2["willCreateInvokeContext"]="willCreateInvokeContext";ToolHookStage2["didCreateInvokeContext"]="didCreateInvokeContext";ToolHookStage2["willAuthorize"]="willAuthorize";ToolHookStage2["willCheckConsent"]="willCheckConsent";ToolHookStage2["willCheckFeatureFlags"]="willCheckFeatureFlags";ToolHookStage2["willAcquireQuota"]="willAcquireQuota";ToolHookStage2["didReleaseQuota"]="didReleaseQuota";ToolHookStage2["willAcquireSemaphore"]="willAcquireSemaphore";ToolHookStage2["didReleaseSemaphore"]="didReleaseSemaphore";ToolHookStage2["willParseInput"]="willParseInput";ToolHookStage2["willValidateInput"]="willValidateInput";ToolHookStage2["willNormalizeInput"]="willNormalizeInput";ToolHookStage2["willRedactInput"]="willRedactInput";ToolHookStage2["willInjectSecrets"]="willInjectSecrets";ToolHookStage2["willReadCache"]="willReadCache";ToolHookStage2["didCacheHit"]="didCacheHit";ToolHookStage2["didCacheMiss"]="didCacheMiss";ToolHookStage2["willWriteCache"]="willWriteCache";ToolHookStage2["aroundExecute"]="aroundExecute";ToolHookStage2["willExecute"]="willExecute";ToolHookStage2["didExecute"]="didExecute";ToolHookStage2["willRedactOutput"]="willRedactOutput";ToolHookStage2["willValidateOutput"]="willValidateOutput";ToolHookStage2["willTransformOutput"]="willTransformOutput";ToolHookStage2["onRetry"]="onRetry";ToolHookStage2["onGiveUp"]="onGiveUp";ToolHookStage2["willAudit"]="willAudit";ToolHookStage2["didAudit"]="didAudit";ToolHookStage2["onMetrics"]="onMetrics";ToolHookStage2["onError"]="onError";ToolHookStage2["willFinalizeInvoke"]="willFinalizeInvoke";return ToolHookStage2})(ToolHookStage||{})}});var SessionHookStage;var init_session_hook_interface=__esm({"libs/sdk/src/common/interfaces/session-hook.interface.ts"(){"use strict";SessionHookStage=(SessionHookStage2=>{SessionHookStage2["willCreateSession"]="willCreateSession";SessionHookStage2["didCreateSession"]="didCreateSession";SessionHookStage2["willBindProviders"]="willBindProviders";SessionHookStage2["willBeginAuth"]="willBeginAuth";SessionHookStage2["willAuthorize"]="willAuthorize";SessionHookStage2["willExchangeToken"]="willExchangeToken";SessionHookStage2["didIssueSecureJwt"]="didIssueSecureJwt";SessionHookStage2["willStoreTokens"]="willStoreTokens";SessionHookStage2["willGetSession"]="willGetSession";SessionHookStage2["didGetSession"]="didGetSession";SessionHookStage2["willDisposeSession"]="willDisposeSession";SessionHookStage2["didDisposeSession"]="didDisposeSession";SessionHookStage2["willFinalize"]="willFinalize";SessionHookStage2["onError"]="onError";SessionHookStage2["willAudit"]="willAudit";SessionHookStage2["didAudit"]="didAudit";SessionHookStage2["onMetrics"]="onMetrics";return SessionHookStage2})(SessionHookStage||{})}});var AuthHookStage;var init_auth_hook_interface=__esm({"libs/sdk/src/common/interfaces/auth-hook.interface.ts"(){"use strict";AuthHookStage=(AuthHookStage2=>{AuthHookStage2["willCreateSession"]="willCreateSession";AuthHookStage2["didCreateSession"]="didCreateSession";AuthHookStage2["willBindProviders"]="willBindProviders";AuthHookStage2["willBeginAuth"]="willBeginAuth";AuthHookStage2["willAuthorize"]="willAuthorize";AuthHookStage2["willExchangeToken"]="willExchangeToken";AuthHookStage2["didIssueSecureJwt"]="didIssueSecureJwt";AuthHookStage2["willStoreTokens"]="willStoreTokens";AuthHookStage2["willGetSession"]="willGetSession";AuthHookStage2["didGetSession"]="didGetSession";AuthHookStage2["willDisposeSession"]="willDisposeSession";AuthHookStage2["didDisposeSession"]="didDisposeSession";AuthHookStage2["willFinalize"]="willFinalize";AuthHookStage2["onError"]="onError";AuthHookStage2["willAudit"]="willAudit";AuthHookStage2["didAudit"]="didAudit";AuthHookStage2["onMetrics"]="onMetrics";return AuthHookStage2})(AuthHookStage||{})}});var BaseConfig;var init_base_config_provider=__esm({"libs/sdk/src/common/providers/base-config.provider.ts"(){"use strict";init_errors();BaseConfig=class{config;constructor(config){this.config=config}getAll(){return this.config}get(path4,defaultValue){const keys=path4.split(".");let result=this.config;for(const key of keys){if(result&&typeof result==="object"&&key in result){result=result[key]}else{return defaultValue!==void 0?defaultValue:void 0}}const value=result;return value!==void 0?value:defaultValue!==void 0?defaultValue:void 0}has(path4){const keys=path4.split(".");let result=this.config;for(const key of keys){if(result&&typeof result==="object"&&key in result){result=result[key]}else{return false}}return result!==void 0}getOrDefault(path4,defaultValue){const value=this.get(path4);return value!==void 0?value:defaultValue}getRequired(path4){const value=this.get(path4);if(value===void 0){throw new RequiredConfigUndefinedError(path4)}return value}getOrThrow(path4){return this.getRequired(path4)}getSection(section){return this.config[section]}matches(path4,value){return this.get(path4)===value}getMany(paths){const result={};for(const path4 of paths){result[path4]=this.get(path4)}return result}toJSON(){return this.config}toString(){return JSON.stringify(this.config,null,2)}}}});var init_common=__esm({"libs/sdk/src/common/index.ts"(){"use strict";init_decorators();init_types();init_metadata();init_interfaces2();init_tokens();init_dynamic();init_records();init_entries();init_utils3();init_schemas();init_flow_utils3();init_tool_hook_interface();init_session_hook_interface();init_auth_hook_interface();init_base_config_provider()}});init_common();import"reflect-metadata";init_front_mcp();init_front_mcp_tokens2();init_static_startup_check();init_optional_dependency_util();init_browser_stores();init_serverless_handler();init_common();init_answer();init_surface();init_materialized_resource_context();init_mcp_error();init_browser_stores();import{z as z135}from"@frontmcp/lazy-zod";import{createChangeFeed as createChangeFeed2,createStorage as createStorage8}from"@frontmcp/utils";var STORAGE_TYPES=["memory","redis","sqlite"];var resourceStoreOptionsSchema=z135.object({storage:z135.object({type:z135.enum(STORAGE_TYPES)}).passthrough().optional(),pollIntervalMs:z135.number().int().positive().optional(),coalesceMs:z135.number().int().nonnegative().optional(),onError:z135.custom(value=>typeof value==="function").optional()}).strict();var NAMESPACE="frontmcp-resources";var ResourceStore=class{constructor(options={}){this.options=options}options;opened;connections=0;backend={storage:async()=>(await this.open()).storage,reportError:error=>this.options.onError?.(error)};key(name51,options={}){if(typeof name51!=="string"||name51.length===0){throw new InvalidResourceStoreError('a key needs a name, such as key("board")')}let initialRecord;try{initialRecord=JSON.stringify({value:options.initial,revision:0})}catch(error){const reason=error instanceof Error?error.message:String(error);throw new InvalidResourceStoreError(`the initial value of key "${name51}" cannot be stored as JSON: ${reason}`)}return new StoredResourceKey(this,this.backend,name51,initialRecord)}subscribe(topic,listener){let stopped=false;let unsubscribe;this.open().then(({feed})=>{if(!stopped)unsubscribe=feed.subscribe(topic,listener)},error=>this.backend.reportError(error));return()=>{stopped=true;unsubscribe?.()}}async publish(topic){const{feed}=await this.open();await feed.publish(topic)}async connect(){this.connections++;try{await this.open()}catch(error){this.connections--;throw error}}async close(){if(this.connections>1){this.connections--;return}this.connections=0;const opened=this.opened;this.opened=void 0;if(!opened)return;const{feed,root}=await opened.catch(()=>({feed:void 0,root:void 0}));await feed?.close();await root?.disconnect()}open(){if(!this.opened){const opening=this.openStorage();opening.catch(()=>{if(this.opened===opening)this.opened=void 0});this.opened=opening}return this.opened}async openStorage(){const{storage={type:"memory"},pollIntervalMs,coalesceMs}=this.options;refuseServerStoresInBrowser({resourceStore:storage.type==="memory"?void 0:`storage: { type: '${storage.type}' }`});const root=await createStorage8({fallback:"error",...storage});const namespaced=root.namespace(NAMESPACE);const feed=createChangeFeed2(namespaced,{pollIntervalMs,coalesceMs,onError:error=>this.backend.reportError(error)});return{root,storage:namespaced,feed}}};var StoredResourceKey=class{constructor(store,backend,name51,initialRecord){this.store=store;this.backend=backend;this.name=name51;this.initialRecord=initialRecord;this.recordKey=`value:${name51}`}store;backend;name;initialRecord;recordKey;async get(){const storage=await this.backend.storage();return this.parse(await storage.get(this.recordKey))}set(value){return this.update(()=>value)}async update(change){const storage=await this.backend.storage();for(;;){const raw=await storage.get(this.recordKey);if(raw===null){await storage.set(this.recordKey,this.initialRecord,{ifNotExists:true});continue}const current=this.parse(raw);const next=JSON.stringify({value:await change(current.value),revision:current.revision+1,updatedAt:new Date().toISOString()});if(await storage.setIfEquals(this.recordKey,raw,next)){await this.store.publish(this.name).catch(error=>this.backend.reportError(error));return this.parse(next)}}}subscribe(listener){let active=true;let seen=this.get().then(snapshot=>snapshot.revision,()=>-1);const check=async revision=>{if(!active)return revision;let snapshot;try{snapshot=await this.get()}catch(error){this.backend.reportError(error);return revision}if(!active||snapshot.revision===revision)return snapshot.revision;try{listener(snapshot)}catch(error){this.backend.reportError(error)}return snapshot.revision};const stop=this.store.subscribe(this.name,()=>{seen=seen.then(check)});return()=>{active=false;stop()}}parse(raw){const record=JSON.parse(raw??this.initialRecord);return record.updatedAt===void 0?{value:record.value,revision:record.revision}:{value:record.value,revision:record.revision,updatedAt:record.updatedAt}}};function resourceStore(options={}){const parsed=resourceStoreOptionsSchema.safeParse(options);if(!parsed.success){const problems=parsed.error.issues.map(issue=>`${issue.path.join(".")||"options"}: ${issue.message}`);throw new InvalidResourceStoreError(problems.join("; "))}return new ResourceStore(options)}init_errors();init_hook_observers();init_elicitation_types();init_elicitation_fallback_schema();init_storage_elicitation_store();init_encrypted_elicitation_store();init_elicitation_encryption();init_elicitation_store_factory();init_helpers();init_question_inbox_routes();init_question_subject();init_question_store_factory();init_question_store();init_question_scope_helper();init_question_errors();init_task_types();init_storage_task_store();init_task_store_factory();init_task_registry();init_task_scope_helper();init_task_notifier();init_task_id();init_task_runner();init_in_process_task_runner();init_cli_task_runner();init_process_liveness();init_execute_task_flag();init_tasks_get_flow();init_tasks_result_flow();init_tasks_cancel_flow();init_tasks_list_flow();init_logger_registry();export*from"@frontmcp/guard";init_mcp_client_service();init_cache();init_resilience();init_factories();init_package_specifier();init_esm_auth_types();init_semver_utils();init_esm_cache();init_esm_manifest();init_version_resolver();init_esm_module_loader();init_version_poller();init_esm_context_factories();init_esm_record_builders();init_tool_instance();init_resource_instance();init_prompt_instance();init_esm_record_builders();function createEsmToolInstance(tool,providers,owner,namespace){const record=buildEsmToolRecord(tool,namespace);return new ToolInstance(record,providers,owner)}function createEsmResourceInstance(resource,providers,owner,namespace){const record=buildEsmResourceRecord(resource,namespace);return new ResourceInstance(record,providers,owner)}function createEsmPromptInstance(prompt,providers,owner,namespace){const record=buildEsmPromptRecord(prompt,namespace);return new PromptInstance(record,providers,owner)}init_mcp_stateless_client_adapter();init_job_registry();init_job_instance();init_job_events();init_job_utils();init_job_permission_guard();init_job_run_resource();init_job_scope_helper();init_job_execution_manager();init_list_jobs_tool();init_execute_job_tool();init_get_job_status_tool();init_cancel_job_tool();init_register_job_tool();init_remove_job_tool();init_workflow_registry();init_workflow_instance();init_workflow_events();init_workflow_utils();init_workflow_engine();init_workflow_step_executor();init_list_workflows_tool();init_execute_workflow_tool();init_get_workflow_status_tool();init_register_workflow_tool();init_remove_workflow_tool();init_streamable_http_transport();init_sse_transport();init_node_sse_transport();init_event_stores();init_channel_instance();init_channel_registry();init_channel_events();init_channel_notification_service();init_app_event_source();init_channel_reply_tool();init_context();init_tool_registry();init_tool_instance();init_provider_registry();import{default as default9}from"@frontmcp/lazy-zod";import{z as z138,eagerZ,lazyZ,isLazy,forceMaterialize,LazyZodSchema,toJSONSchema as toJSONSchema9,NEVER as NEVER2,ZodAny,ZodArray,ZodBigInt as ZodBigInt2,ZodBoolean as ZodBoolean2,ZodDate as ZodDate2,ZodDefault,ZodDiscriminatedUnion,ZodEnum,ZodError,ZodIntersection,ZodLiteral,ZodNever,ZodNull,ZodNullable,ZodNumber as ZodNumber2,ZodObject,ZodOptional,ZodRecord,ZodString as ZodString2,ZodSymbol,ZodTuple,ZodType,ZodUndefined,ZodUnion,ZodUnknown,ZodVoid}from"@frontmcp/lazy-zod";init_app_utils();init_common();init_errors();init_front_mcp_tokens2();init_logger_registry();init_provider_registry();import{isClass as isClass21}from"@frontmcp/di";import{z as z136}from"@frontmcp/lazy-zod";var createContainerOptionsSchema=z136.object({providers:z136.array(annotatedFrontMcpProvidersSchema).optional().default([]),apps:z136.array(annotatedFrontMcpAppSchema).optional().default([]),logging:loggingOptionsSchema.optional(),lifecycle:lifecycleOptionsSchema.optional(),runDuties:z136.boolean({message:"runDuties must be true or false"}).optional(),info:z136.object({name:z136.string().min(1,"info.name must not be empty")}).optional()}).refine(options=>!options.runDuties||options.info!==void 0,{message:"runDuties needs info.name: duties share their leases by server name",path:["info"]});async function createContainer(options){const{providers,apps,logging,lifecycle,runDuties}=createContainerOptionsSchema.parse(options);const root=new ProviderRegistry([{name:"frontmcp:config",provide:FrontMcpConfig,useValue:{...options,logging,lifecycle}}],void 0,{shutdownHookTimeoutMs:lifecycle?.shutdownHookTimeoutMs});await root.ready;const loggers=new LoggerRegistry(root);await loggers.ready;const logger=root.get(FrontMcpLogger);const dispose=async()=>{await root.runShutdownHooks(logger);root.dispose()};const registries=[];try{const serverProviders=new ProviderRegistry(providers,root);registries.push(serverProviders);await serverProviders.ready;for(const app of apps.filter(isClass21)){const appProviders=new ProviderRegistry(collectAppMetadata(app).providers??[],serverProviders);registries.push(appProviders);await appProviders.ready}if(runDuties){const{startDuties:startDuties2}=await Promise.resolve().then(()=>(init_duty_lifecycle(),duty_lifecycle_exports));for(const registry of registries)await startDuties2(registry)}}catch(error){await dispose();throw error}const get=token=>{let missing;for(const registry of registries){try{return registry.get(token)}catch(error){if(!(error instanceof ProviderNotAvailableError))throw error;missing=error}}throw missing};const tryGet=token=>{try{return get(token)}catch(error){if(error instanceof ProviderNotAvailableError)return void 0;throw error}};return{get,tryGet,dispose}}init_store_provider();init_common();init_store_provider();init_browser_stores();import{createStorage as createStorage9}from"@frontmcp/utils";var SqliteStorageToken=Symbol.for("frontmcp:storage.sqlite");function sqliteStorageProvider(options){const{prefix,provide=SqliteStorageToken,...sqlite}=options;return storeProvider({name:"storage.sqlite",scope:ProviderScope2.GLOBAL,provide,inject:()=>[],useFactory:async()=>{refuseServerStoresInBrowser({sqliteStorage:"sqliteStorageProvider()"});const storage=await createStorage9({type:"sqlite",sqlite,prefix,fallback:"error"});return Object.assign(storage,{onShutdown:()=>storage.disconnect()})}})}init_detached_job_flag();init_skill_registry();init_skill_instance();init_skill_events();init_memory_skill_provider();function createEmptySyncState(){return{version:1,lastFullSync:0,entries:new Map}}init_skill_hash();init_errors();var ExternalSkillProviderBase=class{type="external";mode;syncState=null;syncStateStore;logger;defaultTopK;defaultMinScore;initialized=false;constructor(options){this.mode=options.mode;this.syncStateStore=options.syncStateStore;this.logger=options.logger;this.defaultTopK=options.defaultTopK??10;this.defaultMinScore=options.defaultMinScore??.1;if(this.mode==="persistent"&&!this.syncStateStore){this.logger?.warn("[ExternalSkillProvider] Persistent mode without syncStateStore - sync state will not persist across restarts")}}async initialize(){if(this.initialized){return}if(this.mode==="persistent"&&this.syncStateStore){this.syncState=await this.syncStateStore.load();this.logger?.debug("[ExternalSkillProvider] Loaded sync state",{entriesCount:this.syncState?.entries.size??0,lastFullSync:this.syncState?.lastFullSync??"never"})}this.initialized=true;this.logger?.info("[ExternalSkillProvider] Initialized",{mode:this.mode})}async search(query,options){return this.searchExternal(query,{...options,topK:options?.topK??this.defaultTopK,minScore:options?.minScore??this.defaultMinScore})}async load(skillId){const skill=await this.fetchSkill(skillId);if(!skill){return null}const toolNames=skill.tools.map(t=>t.name);return{skill,availableTools:toolNames,missingTools:[],isComplete:true}}async list(options){const skills=await this.fetchSkills(options);const total=await this.countExternal({tags:options?.tags,includeHidden:options?.includeHidden});const offset=options?.offset??0;const limit=options?.limit??50;return{skills:skills.map(s=>this.skillToMetadata(s)),total,hasMore:offset+skills.length<total}}async exists(skillId){return this.existsExternal(skillId)}async count(options){return this.countExternal(options)}async dispose(){this.initialized=false;this.syncState=null;this.logger?.debug("[ExternalSkillProvider] Disposed")}async syncSkills(localSkills){if(this.mode!=="persistent"){throw new PublicMcpError("[ExternalSkillProvider] syncSkills is only available in persistent mode",String(MCP_ERROR_CODES.INVALID_REQUEST),400)}if(!this.syncState){await this.initialize()}const startTime=Date.now();this.logger?.info("[ExternalSkillProvider] Starting skill sync",{skillCount:localSkills.length});const prevState=this.syncState??createEmptySyncState();const newState=createEmptySyncState();newState.version=prevState.version;const added=[];const updated=[];const unchanged=[];const removed=[];const failed=[];const currentIds=new Set(localSkills.map(s=>s.id));for(const skill of localSkills){const hash=computeSkillHash(skill);const prevEntry=prevState.entries.get(skill.id);try{if(!prevEntry){await this.upsertSkill(skill);added.push(skill.id);this.logger?.debug("[ExternalSkillProvider] Added skill",{skillId:skill.id})}else if(prevEntry.hash!==hash){await this.upsertSkill(skill);updated.push(skill.id);this.logger?.debug("[ExternalSkillProvider] Updated skill",{skillId:skill.id})}else{unchanged.push(skill.id)}const entry={skillId:skill.id,hash,lastSyncedAt:Date.now(),status:"synced",externalId:prevEntry?.externalId};newState.entries.set(skill.id,entry)}catch(error){const errorMsg=error instanceof Error?error.message:String(error);failed.push({skillId:skill.id,error:errorMsg});const entry={skillId:skill.id,hash,lastSyncedAt:prevEntry?.lastSyncedAt??0,status:"failed",error:errorMsg};newState.entries.set(skill.id,entry);this.logger?.error("[ExternalSkillProvider] Failed to sync skill",{skillId:skill.id,error:errorMsg})}}for(const[skillId,entry]of prevState.entries){if(!currentIds.has(skillId)){try{await this.deleteSkill(skillId);removed.push(skillId);this.logger?.debug("[ExternalSkillProvider] Removed skill",{skillId})}catch(error){const errorMsg=error instanceof Error?error.message:String(error);failed.push({skillId,error:errorMsg});newState.entries.set(skillId,{...entry,status:"failed",error:errorMsg});this.logger?.error("[ExternalSkillProvider] Failed to remove skill",{skillId,error:errorMsg})}}}newState.lastFullSync=Date.now();this.syncState=newState;if(this.syncStateStore){await this.syncStateStore.save(newState)}const durationMs=Date.now()-startTime;this.logger?.info("[ExternalSkillProvider] Skill sync complete",{added:added.length,updated:updated.length,unchanged:unchanged.length,removed:removed.length,failed:failed.length,durationMs});return{added,updated,unchanged,removed,failed,durationMs}}getSyncState(){if(!this.syncState){return null}const clonedEntries=new Map([...this.syncState.entries].map(([key,value])=>[key,{...value}]));return{...this.syncState,entries:clonedEntries}}async clearSyncState(){this.syncState=null;if(this.syncStateStore){await this.syncStateStore.clear()}this.logger?.info("[ExternalSkillProvider] Sync state cleared")}isReadOnly(){return this.mode==="read-only"}isPersistent(){return this.mode==="persistent"}skillToMetadata(skill){return{id:skill.id,name:skill.name,description:skill.description,instructions:skill.instructions,tools:skill.tools.map(t=>{if(t.purpose||t.required){return{name:t.name,...t.purpose&&{purpose:t.purpose},...t.required&&{required:t.required}}}return t.name}),parameters:skill.parameters,examples:skill.examples}}};init_skill_validator();init_errors();init_memory_skill_provider();init_skill_validator();function createSkillStorageProvider(options={}){const{provider:providerType="memory",memory,externalProvider,toolRegistry,logger}=options;let toolValidator;if(toolRegistry){toolValidator=new SkillToolValidator(toolRegistry)}let provider;let type;let extProvider;switch(providerType){case"external":{if(!externalProvider){logger?.error("[SkillStorageFactory] External provider type requires externalProvider instance to be passed");throw new PublicMcpError("External provider type requires externalProvider instance. Create a class extending ExternalSkillProviderBase and pass it via externalProvider option.",String(MCP_ERROR_CODES.INVALID_PARAMS),500)}provider=externalProvider;extProvider=externalProvider;type="external";logger?.debug("[SkillStorageFactory] Using external skill provider",{mode:externalProvider.isReadOnly()?"read-only":"persistent"});break}case"vectordb":{try{logger?.warn("[SkillStorageFactory] VectorDB provider not yet implemented, falling back to memory provider");provider=new MemorySkillProvider({...memory,toolValidator});type="memory"}catch(error){logger?.warn("[SkillStorageFactory] Failed to create VectorDB provider, falling back to memory",{error:error instanceof Error?error.message:String(error)});provider=new MemorySkillProvider({...memory,toolValidator});type="memory"}break}case"memory":default:{provider=new MemorySkillProvider({...memory,toolValidator});type="memory";break}}logger?.debug("[SkillStorageFactory] Created skill storage provider",{type,hasToolValidator:!!toolValidator,hasExternalProvider:!!extProvider});return{provider,type,toolValidator,externalProvider:extProvider}}function createMemorySkillProvider(options={}){const{toolRegistry,defaultTopK,defaultMinScore,logger}=options;let toolValidator;if(toolRegistry){toolValidator=new SkillToolValidator(toolRegistry)}const provider=new MemorySkillProvider({defaultTopK,defaultMinScore,toolValidator});logger?.debug("[SkillStorageFactory] Created explicit memory skill provider");return{provider,type:"memory",toolValidator}}init_skill_utils();init_skill_metadata();import{basename as basename3,fileExists as fileExists7,isAbsolute as isAbsolute5,pathJoin as pathJoin4,pathResolve as pathResolve8,readdir as readdir2,readFile as readFile8,stat as stat7}from"@frontmcp/utils";init_caller_dir_utils();init_sdk_errors();init_skill_md_parser();async function scanSkillResources(dirPath){const resources={};const scriptsPath=pathJoin4(dirPath,"scripts");const referencesPath=pathJoin4(dirPath,"references");const assetsPath=pathJoin4(dirPath,"assets");const examplesPath=pathJoin4(dirPath,"examples");const checks=await Promise.all([checkDirectory(scriptsPath),checkDirectory(referencesPath),checkDirectory(assetsPath),checkDirectory(examplesPath),fileExists7(pathJoin4(dirPath,"SKILL.md"))]);if(checks[0])resources.scripts=scriptsPath;if(checks[1])resources.references=referencesPath;if(checks[2])resources.assets=assetsPath;if(checks[3])resources.examples=examplesPath;return{resources,hasSkillMd:checks[4]}}async function checkDirectory(path4){try{const s=await stat7(path4);return s.isDirectory()}catch(err){if(err.code==="ENOENT")return false;throw err}}async function findNestedSkillMd(dirPath,maxDepth=Number.POSITIVE_INFINITY){const found=[];async function walk(current,depth2,relPath){if(depth2>maxDepth)return;let entries;try{entries=await readdir2(current)}catch(err){if(err.code==="ENOENT")return;throw err}for(const entry of entries){const full=pathJoin4(current,entry);let entryStat;try{entryStat=await stat7(full)}catch(err){if(err.code==="ENOENT")continue;throw err}if(entryStat.isDirectory()){await walk(full,depth2+1,relPath?`${relPath}/${entry}`:entry)}else if(entryStat.isFile()&&entry==="SKILL.md"&&depth2>0){found.push(relPath?`${relPath}/SKILL.md`:"SKILL.md")}}}await walk(dirPath,0,"");return found.sort()}var SKILL_DIRECTORY_LOADER_BASENAMES=["skill-directory-loader.ts","skill-directory-loader.js"];async function resolveSkillDirectory(dirPath,callerDir){if(isAbsolute5(dirPath))return dirPath;const fromCaller=callerDir?pathResolve8(callerDir,dirPath):void 0;if(fromCaller&&await fileExists7(pathJoin4(fromCaller,"SKILL.md")))return fromCaller;const fromCwd=pathResolve8(dirPath);if(await fileExists7(pathJoin4(fromCwd,"SKILL.md")))return fromCwd;return fromCaller??fromCwd}async function loadSkillDirectory(dirPath,logger){return loadResolvedSkillDirectory(await resolveSkillDirectory(dirPath,captureCallerDir(SKILL_DIRECTORY_LOADER_BASENAMES)),logger)}async function loadResolvedSkillDirectory(dirPath,logger){const skillMdPath=pathJoin4(dirPath,"SKILL.md");const exists=await fileExists7(skillMdPath);if(!exists){throw new InvalidSkillError(basename3(dirPath),"SKILL.md not found in directory")}let content;let partialMetadata;try{content=await readFile8(skillMdPath,"utf-8");const{frontmatter,body}=parseSkillMdFrontmatter(content);partialMetadata=skillMdFrontmatterToMetadata(frontmatter,body)}catch(err){const name51=basename3(dirPath);const message=err instanceof Error?err.message:String(err);throw new InvalidSkillError(name51,`Failed to read or parse SKILL.md: ${message}`)}const{resources}=await scanSkillResources(dirPath);const hasResources=resources.scripts||resources.references||resources.assets||resources.examples;if(hasResources){partialMetadata.resources=resources}const nested=await findNestedSkillMd(dirPath);if(nested.length>0){const skillName2=partialMetadata.name??basename3(dirPath);throw new InvalidSkillError(skillName2,`Skill directory contains nested SKILL.md files (forbidden by SEP-2640 \xA7Resource Mapping): ${nested.join(", ")}`)}const dirName=basename3(dirPath);if(partialMetadata.name&&dirName&&partialMetadata.name!==dirName){const msg=`Skill name "${partialMetadata.name}" does not match directory name "${dirName}"`;if(logger){logger.warn(msg,{skillName:partialMetadata.name,dirName})}else{console.warn(msg)}}if(!partialMetadata.name){throw new InvalidSkillError("unknown","SKILL.md is missing required 'name' field in frontmatter")}const skillName=partialMetadata.name;if(!partialMetadata.description){throw new InvalidSkillError(skillName,"SKILL.md is missing required 'description' field in frontmatter")}if(!partialMetadata.instructions){throw new InvalidSkillError(skillName,"SKILL.md has no body content for instructions")}const metadata=partialMetadata;const parsed=skillMetadataSchema.safeParse(metadata);if(!parsed.success){const issues=parsed.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join("; ");throw new InvalidSkillError(partialMetadata.name??"unknown",issues)}return{kind:"FILE",provide:Symbol(`skill:${metadata.name}`),metadata:parsed.data,filePath:skillMdPath}}async function skillDir(dirPath,logger){return loadSkillDirectory(dirPath,logger)}init_skill_filter_helper();init_skill_validation_error();init_skill_audit_helper();init_skill_instructions_helper();init_auth3();init_agent_events();init_agent_utils();init_agent_execution_loop();init_flows2();init_adapters();init_agent_interface();init_agent_metadata();init_agent_decorator();init_adapters();import{LoopbackTokenAuth as LoopbackTokenAuth4,PEOPLE_SESSION_COOKIE as PEOPLE_SESSION_COOKIE2}from"@frontmcp/auth";init_lineage_utils();function gateOf(scope,entry){if("tool"in entry){return{flow:"tools:call-tool",ownerId:hookOwnerIdOf(scope.tools.lineageOf(entry.tool)??[],entry.tool.owner)}}if("resource"in entry){return{flow:"resources:read-resource",ownerId:appOwnerIdOf(scope.resources.lineageOf(entry.resource)??[],entry.resource.owner)}}if("prompt"in entry){return{flow:"prompts:get-prompt",ownerId:appOwnerIdOf(scope.prompts.lineageOf(entry.prompt)??[],entry.prompt.owner)}}return{flow:"skills:filter",ownerId:appOwnerIdOf(scope.skills.lineageOf?.(entry.skill)??[],entry.skill.owner)}}function isEntryGatedBy(scope,entry,target){const{flow,ownerId}=gateOf(scope,entry);return scope.hooks.getFlowHooksForOwner(flow,ownerId).some(hook=>hook.metadata.target===target)}init_config();init_common();init_errors();init_request_log_redaction();init_call_tool_error_utils();init_mcp_error_utils();import{McpError as ProtocolMcpError}from"@frontmcp/protocol";import{redactJson}from"@frontmcp/utils";var RECORDED_METHODS=["tools/call","resources/read","prompts/get"];var CALL_RECORD_VERSION=1;import{appendFile,chmod as chmod2,dirname as dirname9,ensureDir,fileExists as fileExists8,stat as stat8}from"@frontmcp/utils";var encoder9=new TextEncoder;var CallRecordWriter=class{constructor(options,logger){this.options=options;this.logger=logger}options;logger;pending=Promise.resolve();pendingBytes=0;full=false;failureLogged=false;backlogLogged=false;ownerOnly=false;write(line){if(this.full)return;const bytes=encoder9.encode(line).byteLength;if(this.pendingBytes>0&&this.pendingBytes+bytes>this.options.maxBytes){this.reportBacklog();return}this.pendingBytes+=bytes;this.pending=this.pending.then(()=>this.append(line,bytes)).catch(error=>this.reportFailure(error)).finally(()=>{this.pendingBytes-=bytes})}reportFailure(error){if(this.failureLogged)return;this.failureLogged=true;const reason=error instanceof Error?error.message:String(error);this.logger.warn(`Could not record a call to ${this.options.path}; later failures are not logged: ${reason}`)}async onShutdown(){await this.pending}reportBacklog(){if(this.backlogLogged)return;this.backlogLogged=true;this.logger.warn(`Dropped a call: ${this.pendingBytes} bytes of calls are still waiting to be written to ${this.options.path}; later drops are not logged`)}async append(line,bytes){if(this.full)return;const{path:path4,maxBytes}=this.options;if(await this.sizeOnDisk(path4)+bytes>maxBytes){this.full=true;this.logger.warn(`Stopped recording calls: ${path4} reached its maxBytes of ${maxBytes} bytes`);return}await appendFile(path4,line,{mode:384})}async sizeOnDisk(path4){if(await fileExists8(path4)){if(!this.ownerOnly)await chmod2(path4,384);this.ownerOnly=true;return(await stat8(path4)).size}await ensureDir(dirname9(path4));return 0}};init_errors();import{z as z137}from"@frontmcp/lazy-zod";var fieldNames=z137.array(z137.string().min(1,{message:"must not be empty"})).default([]);var callRecorderOptionsSchema=z137.object({path:z137.string().min(1,{message:"must be a file path"}).default(".frontmcp/calls.jsonl"),methods:z137.array(z137.enum(RECORDED_METHODS,{message:`must be one of ${RECORDED_METHODS.join(", ")}`})).min(1,{message:"must name at least one method"}).default([...RECORDED_METHODS]),redactFields:fieldNames,keepFields:fieldNames,maxBytes:z137.number().int({message:"must be a whole number of bytes, at least 1"}).min(1,{message:"must be a whole number of bytes, at least 1"}).default(10*1024*1024)}).strict();function parseCallRecorderOptions(input){const result=callRecorderOptionsSchema.safeParse(input);if(result.success)return result.data;const problems=result.error.issues.map(issue=>issue.path.length>0?`${issue.path.join(".")}: ${issue.message}`:issue.message);throw new CallRecorderConfigurationError(`Invalid CallRecorderPlugin options: ${problems.join("; ")}`)}var ToolHook=FlowHooksOf("tools:call-tool");var ResourceHook=FlowHooksOf("resources:read-resource");var PromptHook=FlowHooksOf("prompts:get-prompt");var productionErrorHandler=new ErrorHandler({isDevelopment:false});var REDACTED2="[REDACTED]";var RESULT_HANDLE_META_KEY="frontmcp/result-handle";var UUID=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;var REMEMBERED_HANDLES=1e3;function isRecord4(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function requestParamsOf(rawInput){const request2=isRecord4(rawInput)?rawInput["request"]:void 0;const params=isRecord4(request2)?request2["params"]:void 0;return isRecord4(params)?params:{}}function resultHandleOf(answer){const meta=isRecord4(answer)&&isRecord4(answer["_meta"])?answer["_meta"][RESULT_HANDLE_META_KEY]:void 0;const handle=isRecord4(meta)?meta["handle"]:void 0;return typeof handle==="string"&&handle.length>0?handle:void 0}function textOf(answer){return answer.content.map(block=>block.type==="text"?block.text:"").join("\n")}function jsonRpcErrorOf(error){const{code,message}=toSdkMcpError(error);const reported=toReportedError(error);const isPublic=reported instanceof ProtocolMcpError||reported.isPublic;return isPublic?{code,message:message.replace(/^MCP error -?\d+: /,"")}:{code}}function recordedErrorOf(method,error){if(method!=="tools/call")return jsonRpcErrorOf(error);let answer;try{answer=toolCallErrorResult(error,{errorHandler:productionErrorHandler,toolName:""})}catch{return jsonRpcErrorOf(error)}const reported=toMcpError(error);const code=answer._meta?.["code"];return{code:typeof code==="string"?code:reported.code,...reported.isPublic&&{message:textOf(answer)}}}var CallRecorderPlugin=class extends DynamicPlugin{options;openCalls=new WeakMap;redacted;kept;resultHandles=new Set;constructor(options={}){super();this.options=parseCallRecorderOptions(options);this.redacted=new Set(this.options.redactFields.map(field=>field.toLowerCase()));this.kept=new Set(this.options.keepFields.map(field=>field.toLowerCase()))}openToolCall(flow){const createsTask=requestParamsOf(flow.rawInput)["task"]!==void 0;if(flow.isClientCall()&&!createsTask)this.open(flow,"tools/call")}openResourceRead(flow){this.open(flow,"resources/read")}openPromptGet(flow){this.open(flow,"prompts/get")}recordFailedCall(run){if(run.error)this.record(run)}recordCall(run){if(run.error||run.state.output!==void 0)this.record(run)}open(flow,method){if(this.options.methods.includes(method))this.openCalls.set(flow,{method,startedAt:Date.now()})}record(run){const call=this.openCalls.get(run);if(!call)return;this.openCalls.delete(run);const writer=this.get(CallRecordWriter);try{writer.write(this.lineOf(run,call))}catch(error){writer.reportFailure(error)}}lineOf(run,call){const handle=run.error?void 0:resultHandleOf(run.state.output);if(handle)this.rememberResultHandle(handle);let line=JSON.stringify(this.recordOf(run,call));if(handle)line=line.split(handle).join(REDACTED2);if(this.resultHandles.size>0){line=line.replace(UUID,id=>this.resultHandles.has(id)?REDACTED2:id)}return`${line}