@frontmcp/plugin-codecall 1.11.2 → 1.12.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,9 +1,9 @@
1
- "use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var __decorateClass=(decorators,target,key,kind)=>{var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target;for(var i=decorators.length-1,decorator;i>=0;i--)if(decorator=decorators[i])result=(kind?decorator(target,key,result):decorator(result))||result;if(kind&&result)__defProp(target,key,result);return result};var index_exports={};__export(index_exports,{AUDIT_EVENT_TYPES:()=>AUDIT_EVENT_TYPES,AuditLoggerService:()=>AuditLoggerService,CodeCallPlugin:()=>CodeCallPlugin,codeCallDirectCallsOptionsSchema:()=>codeCallDirectCallsOptionsSchema,codeCallEmbeddingOptionsSchema:()=>codeCallEmbeddingOptionsSchema,codeCallModeSchema:()=>codeCallModeSchema,codeCallPluginOptionsSchema:()=>codeCallPluginOptionsSchema,codeCallSidecarOptionsSchema:()=>codeCallSidecarOptionsSchema,codeCallVmOptionsSchema:()=>codeCallVmOptionsSchema,codeCallVmPresetSchema:()=>codeCallVmPresetSchema,default:()=>CodeCallPlugin,embeddingStrategySchema:()=>embeddingStrategySchema,synonymExpansionConfigSchema:()=>synonymExpansionConfigSchema});module.exports=__toCommonJS(index_exports);var import_plugin_cache=__toESM(require("@frontmcp/plugin-cache"));var import_sdk11=require("@frontmcp/sdk");var import_lazy_zod=require("@frontmcp/lazy-zod");var directCallsFilterSchema=import_lazy_zod.z.custom(val=>typeof val==="function",{message:"filter must be a function with signature (tool: DirectCallsFilterToolInfo) => boolean"});var includeToolsFilterSchema=import_lazy_zod.z.custom(val=>typeof val==="function",{message:"includeTools must be a function with signature (tool: IncludeToolsFilterToolInfo) => boolean"});var codeCallModeSchema=import_lazy_zod.z.enum(["codecall_only","codecall_opt_in","metadata_driven"]).default("codecall_only");var codeCallVmPresetSchema=import_lazy_zod.z.enum(["locked_down","secure","balanced","experimental"]).default("secure");var DEFAULT_VM_OPTIONS={preset:"secure"};var codeCallVmOptionsSchema=import_lazy_zod.z.object({preset:codeCallVmPresetSchema,timeoutMs:import_lazy_zod.z.number().positive().optional(),allowLoops:import_lazy_zod.z.boolean().optional(),maxSteps:import_lazy_zod.z.number().positive().optional(),disabledBuiltins:import_lazy_zod.z.array(import_lazy_zod.z.string()).optional(),disabledGlobals:import_lazy_zod.z.array(import_lazy_zod.z.string()).optional(),allowConsole:import_lazy_zod.z.boolean().optional(),maxSanitizeDepth:import_lazy_zod.z.number().positive().optional(),maxSanitizeProperties:import_lazy_zod.z.number().positive().optional(),rapidEnumerationThreshold:import_lazy_zod.z.number().int().positive().optional(),rapidEnumerationOverrides:import_lazy_zod.z.record(import_lazy_zod.z.string(),import_lazy_zod.z.number().int().positive()).optional()}).default(()=>DEFAULT_VM_OPTIONS);var codeCallDirectCallsOptionsSchema=import_lazy_zod.z.object({enabled:import_lazy_zod.z.boolean(),allowedTools:import_lazy_zod.z.array(import_lazy_zod.z.string()).optional(),filter:directCallsFilterSchema.optional()});var embeddingStrategySchema=import_lazy_zod.z.enum(["tfidf","ml"]).default("tfidf");var synonymExpansionConfigSchema=import_lazy_zod.z.object({enabled:import_lazy_zod.z.boolean().default(true),additionalSynonyms:import_lazy_zod.z.array(import_lazy_zod.z.array(import_lazy_zod.z.string())).optional(),replaceDefaults:import_lazy_zod.z.boolean().default(false),maxExpansionsPerTerm:import_lazy_zod.z.number().positive().default(5)}).default({enabled:true,replaceDefaults:false,maxExpansionsPerTerm:5});var DEFAULT_EMBEDDING_OPTIONS={strategy:"tfidf",modelName:"Xenova/all-MiniLM-L6-v2",cacheDir:"./.cache/transformers",useHNSW:false,synonymExpansion:{enabled:true,replaceDefaults:false,maxExpansionsPerTerm:5}};var codeCallEmbeddingOptionsSchema=import_lazy_zod.z.object({strategy:embeddingStrategySchema.optional(),modelName:import_lazy_zod.z.string().optional(),cacheDir:import_lazy_zod.z.string().optional(),useHNSW:import_lazy_zod.z.boolean().optional(),synonymExpansion:import_lazy_zod.z.union([import_lazy_zod.z.literal(false),synonymExpansionConfigSchema]).optional()}).optional().transform(opts=>({strategy:opts?.strategy??DEFAULT_EMBEDDING_OPTIONS.strategy,modelName:opts?.modelName??DEFAULT_EMBEDDING_OPTIONS.modelName,cacheDir:opts?.cacheDir??DEFAULT_EMBEDDING_OPTIONS.cacheDir,useHNSW:opts?.useHNSW??DEFAULT_EMBEDDING_OPTIONS.useHNSW,synonymExpansion:opts?.synonymExpansion??DEFAULT_EMBEDDING_OPTIONS.synonymExpansion}));var codeCallSidecarOptionsSchema=import_lazy_zod.z.object({enabled:import_lazy_zod.z.boolean().default(false),maxTotalSize:import_lazy_zod.z.number().positive().optional(),maxReferenceSize:import_lazy_zod.z.number().positive().optional(),extractionThreshold:import_lazy_zod.z.number().positive().optional(),maxResolvedSize:import_lazy_zod.z.number().positive().optional(),allowComposites:import_lazy_zod.z.boolean().optional(),maxScriptLengthWhenDisabled:import_lazy_zod.z.number().positive().nullable().default(64*1024)}).default(()=>({enabled:false,maxScriptLengthWhenDisabled:64*1024}));var codeCallPluginOptionsObjectSchema=import_lazy_zod.z.object({mode:codeCallModeSchema,appIds:import_lazy_zod.z.array(import_lazy_zod.z.string()).optional(),topK:import_lazy_zod.z.number().positive().default(8),maxDefinitions:import_lazy_zod.z.number().int().positive().default(8),includeTools:includeToolsFilterSchema.optional(),directCalls:codeCallDirectCallsOptionsSchema.optional(),vm:codeCallVmOptionsSchema,embedding:codeCallEmbeddingOptionsSchema,sidecar:codeCallSidecarOptionsSchema});var DEFAULT_PLUGIN_OPTIONS={mode:"codecall_only",topK:8,maxDefinitions:8,vm:DEFAULT_VM_OPTIONS,embedding:DEFAULT_EMBEDDING_OPTIONS,sidecar:{enabled:false,maxScriptLengthWhenDisabled:64*1024}};var codeCallPluginOptionsSchema=codeCallPluginOptionsObjectSchema.prefault(DEFAULT_PLUGIN_OPTIONS);var import_sdk=require("@frontmcp/sdk");var CodeCallConfig=class extends import_sdk.BaseConfig{constructor(options={}){const parsedConfig=codeCallPluginOptionsSchema.parse(options);const resolvedVm=resolveVmOptions(parsedConfig.vm);super({...parsedConfig,resolvedVm})}};CodeCallConfig=__decorateClass([(0,import_sdk.Provider)({name:"codecall:config",description:"CodeCall plugin configuration with validated defaults",scope:import_sdk.ProviderScope.GLOBAL})],CodeCallConfig);var MAX_ITERATIONS_PER_LOOP=1e4;function maxToolCallsOf(vmOptions){return vmOptions.maxSteps||100}var SANDBOX_RAPID_ENUMERATION_THRESHOLD=30;function rapidEnumerationThresholdOf(vmOptions){return vmOptions.rapidEnumerationThreshold??SANDBOX_RAPID_ENUMERATION_THRESHOLD}function resolveVmOptions(vmOptions){const preset=vmOptions?.preset??"secure";const base=presetDefaults(preset);return{...base,...vmOptions,disabledBuiltins:vmOptions?.disabledBuiltins??base.disabledBuiltins,disabledGlobals:vmOptions?.disabledGlobals??base.disabledGlobals}}function presetDefaults(preset){switch(preset){case"locked_down":return{preset,timeoutMs:2e3,allowLoops:false,allowConsole:false,maxSteps:2e3,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process","fetch","setTimeout","setInterval","setImmediate","global","globalThis"],maxSanitizeDepth:10,maxSanitizeProperties:1e3};case"balanced":return{preset,timeoutMs:5e3,allowLoops:true,allowConsole:true,maxSteps:1e4,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process","fetch"],maxSanitizeDepth:50,maxSanitizeProperties:5e3};case"experimental":return{preset,timeoutMs:1e4,allowLoops:true,allowConsole:true,maxSteps:2e4,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process"],maxSanitizeDepth:100,maxSanitizeProperties:2e4};case"secure":default:return{preset:"secure",timeoutMs:3500,allowLoops:false,allowConsole:true,maxSteps:5e3,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process","fetch","setTimeout","setInterval","setImmediate","global","globalThis"],maxSanitizeDepth:50,maxSanitizeProperties:2e3}}}var import_sdk2=require("@frontmcp/sdk");var CODECALL_DISPATCH=Symbol("frontmcp.codecall.dispatch");function asCodeCallDispatch(ctx){return Object.defineProperty(ctx,CODECALL_DISPATCH,{value:true,enumerable:false})}function isInProcessDispatch(ctx){if((0,import_sdk2.getRunningTool)())return true;if(typeof ctx!=="object"||ctx===null)return false;const marks=ctx;return marks[CODECALL_DISPATCH]===true||marks.internalCall===true}var BLOCKED_NAMESPACE_PATTERNS=Object.freeze([/^system:/,/^internal:/,/^__/]);function isOfferedToCaller(availableWhen,surface){const offered=availableWhen?.surface;return offered===void 0||surface===void 0||offered.includes(surface)}var ALLOWED={allowed:true};function deny(reason){return{allowed:false,reason}}function codeCallAppIdOf(scope,entry){const lineage=scope?.tools?.lineageOf?.(entry)??[];const owners=entry.owner?[...lineage,entry.owner]:lineage;return owners.find(owner=>owner.kind==="app")?.id}function toCodeCallPolicyTool(entry,requestedName,scope){const{metadata}=entry;return{name:entry.name||entry.fullName,fullName:entry.fullName,aliases:requestedName?[requestedName]:void 0,appId:codeCallAppIdOf(scope,entry),description:metadata?.description,tags:metadata?.tags,hidden:metadata?.hideFromDiscovery===true||metadata?.visibility==="hidden"||metadata?.visibility==="internal",codecall:metadata?.codecall,annotations:metadata?.annotations,metadata}}function isPlainData(value){if(Array.isArray(value))return true;const proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null}function readOnlyCopy(value,copies){if(typeof value!=="object"||value===null||!isPlainData(value))return value;const existing=copies.get(value);if(existing!==void 0)return existing;const copy=Array.isArray(value)?[]:Object.create(Object.getPrototypeOf(value));copies.set(value,copy);for(const key of Reflect.ownKeys(value)){if(!Object.prototype.propertyIsEnumerable.call(value,key))continue;Object.defineProperty(copy,key,{value:readOnlyCopy(Reflect.get(value,key),copies),enumerable:true,writable:true,configurable:true})}return Object.freeze(copy)}function toToolFilterInfo(tool){const copies=new WeakMap;const annotations=readOnlyCopy(tool.annotations,copies);const metadata=tool.metadata?readOnlyCopy({...tool.metadata,...annotations?{annotations:tool.annotations}:{}},copies):void 0;return{name:tool.name,fullName:tool.fullName,appId:tool.appId,source:tool.codecall?.source,description:tool.description,tags:readOnlyCopy(tool.codecall?.tags??tool.tags,copies),annotations,metadata}}function ownNamesOf(tool){return[tool.name,tool.fullName].filter(candidate=>!!candidate)}function checkCodeCallToolPolicy(tool,config){const{name}=tool;const spellings=[...ownNamesOf(tool),...tool.aliases??[]];if(spellings.some(candidate=>candidate.startsWith("codecall:"))){return deny("CodeCall meta-tools are not callable from CodeCall")}for(const candidate of spellings){if(BLOCKED_NAMESPACE_PATTERNS.some(pattern=>pattern.test(candidate))){return deny(`Tool "${candidate}" is in a namespace CodeCall never calls`)}}if(tool.hidden===true){return deny(`Tool "${name}" is hidden from discovery`)}const enabled=tool.codecall?.enabledInCodeCall;switch(config.mode){case"codecall_only":case"metadata_driven":if(enabled===false){return deny(`Tool "${name}" sets enabledInCodeCall: false`)}break;case"codecall_opt_in":if(enabled!==true){return deny(`Tool "${name}" has not opted in to CodeCall`)}break;default:return deny(`Unknown CodeCall mode: ${String(config.mode)}`)}if(config.includeTools&&!config.includeTools(toToolFilterInfo(tool))){return deny(`Tool "${name}" is excluded by the includeTools filter`)}return ALLOWED}function denyUnknownTool(name){return deny(`Tool "${name}" is not available through CodeCall`)}function resolveCodeCallTool(scope,name){const otherSpelling=/[-_]/.test(name)?name.includes("_")?name.replace(/_/g,"-"):name.replace(/-/g,"_"):void 0;const candidates=otherSpelling?[name,otherSpelling]:[name];const declaresAlias=entry=>entry.metadata?.aliases?.includes(name)===true;const matches=entry=>candidates.includes(entry.fullName)||candidates.includes(entry.name);return findResolvableTool(scope,declaresAlias)??findResolvableTool(scope,matches)}function findResolvableTool(scope,matches){const typedScope=scope;const local=typedScope.tools?.getTools(true)?.find(matches);if(local)return local;const registries=typedScope.providers?.getRegistries?.("AppRegistry")??[];for(const registry of registries){for(const app of registry.getApps()){if(!app.isRemote)continue;const remote=app.tools.getTools(true).find(matches);if(remote)return remote}}return void 0}function checkDirectCallPolicy(tool,directCalls){if(!directCalls)return ALLOWED;if(directCalls.enabled===false){return deny("Direct tool invocation is disabled")}const{allowedTools}=directCalls;if(allowedTools&&!ownNamesOf(tool).some(ownName=>allowedTools.includes(ownName))){return deny(`Tool "${tool.name}" is not in the direct-call allowlist`)}if(directCalls.filter&&!directCalls.filter(toToolFilterInfo(tool))){return deny(`Tool "${tool.name}" is excluded by the directCalls filter`)}return ALLOWED}function readCodeCallPolicyConfig(config){return{mode:config.get("mode")??"codecall_only",includeTools:config.get("includeTools")}}function checkCodeCallToolAccess(scope,config,name,options={}){const entry=resolveCodeCallTool(scope,name);if(!entry)return denyUnknownTool(name);if(!isOfferedToCaller(entry.metadata?.availableWhen,options.surface)){return deny(`Tool "${name}" is not offered on the caller's surface "${options.surface}"`)}const policyTool=toCodeCallPolicyTool(entry,name,scope);const baseDecision=checkCodeCallToolPolicy(policyTool,readCodeCallPolicyConfig(config));if(!baseDecision.allowed)return baseDecision;if(options.directCall){const directDecision=checkDirectCallPolicy(policyTool,config.get("directCalls"));if(!directDecision.allowed)return directDecision}return{allowed:true,entry}}var EMBEDDED_STACK_FRAME_RE=/\n[ \t]*at\s[^\n]*/g;var QUOTED_PATH_RE=/(['"`])((?:~?\/|[A-Za-z]:[\\/]|\\\\)[^\s'"`\\/][^'"`\n]*)\1/g;var URL_RE=/\b[A-Za-z][A-Za-z0-9+.-]{1,31}:\/\/(?:[^\s'"`<>,;]|[,;](?!~?\/|[A-Za-z]:[\\/]|\\\\))*/g;var QUERY_PATH_VALUE_RE=/([?&][^=&#]*=)(?:~?\/|[A-Za-z]:[\\/]|\\\\)[^&#]*/g;var POSIX_SEGMENT=String.raw`[^\s/\\'"\x60<>|,;:()\[\]{}]+`;var WINDOWS_SEGMENT=String.raw`[^\s/\\'"\x60<>|,;:*?]+`;function segments(segment,separator){const spaced=`${segment}(?: ${segment}){0,2}`;return`(?:(?:${spaced}${separator})+(?:${segment})?|${segment})`}var UNQUOTED_PATH_RE=new RegExp([String.raw`(?<![\w.~/\\)\]-])~?/+${segments(POSIX_SEGMENT,"/+")}`,String.raw`(?<![\w\\/])[A-Za-z]:[\\/]+${segments(WINDOWS_SEGMENT,String.raw`[\\/]+`)}?`,String.raw`(?<![\w\\])\\\\${segments(WINDOWS_SEGMENT,String.raw`[\\/]+`)}`].join("|"),"g");function redactPaths(text){return text.replace(QUOTED_PATH_RE,"$1[path]$1").replace(UNQUOTED_PATH_RE,"[path]")}function toClientErrorMessage(message){if(!message)return"";return redactAbsolutePaths(message.replace(EMBEDDED_STACK_FRAME_RE,""))}function redactAbsolutePaths(text){let result="";let last=0;for(const match of text.matchAll(URL_RE)){const start=match.index??0;result+=redactPaths(text.slice(last,start));result+=/^file:/i.test(match[0])?"[path]":match[0].replace(QUERY_PATH_VALUE_RE,"$1[path]");last=start+match[0].length}return result+redactPaths(text.slice(last))}var TOOL_CALL_ERROR_CODES={NOT_FOUND:"NOT_FOUND",VALIDATION:"VALIDATION",EXECUTION:"EXECUTION",TIMEOUT:"TIMEOUT",ACCESS_DENIED:"ACCESS_DENIED",RATE_LIMITED:"RATE_LIMITED",SELF_REFERENCE:"SELF_REFERENCE"};function createToolCallError(code,toolName,rawMessage){const sanitizedMessage=getSanitizedMessage(code,toolName,rawMessage);return Object.freeze({code,message:sanitizedMessage,toolName})}function getSanitizedMessage(code,toolName,rawMessage){switch(code){case TOOL_CALL_ERROR_CODES.NOT_FOUND:return`Tool "${toolName}" was not found`;case TOOL_CALL_ERROR_CODES.VALIDATION:return rawMessage?sanitizeValidationMessage(rawMessage):`Input validation failed for tool "${toolName}"`;case TOOL_CALL_ERROR_CODES.EXECUTION:return`Tool "${toolName}" execution failed`;case TOOL_CALL_ERROR_CODES.TIMEOUT:return`Tool "${toolName}" execution timed out`;case TOOL_CALL_ERROR_CODES.ACCESS_DENIED:return`Access denied for tool "${toolName}"`;case TOOL_CALL_ERROR_CODES.RATE_LIMITED:return`Tool "${toolName}" was rate limited`;case TOOL_CALL_ERROR_CODES.SELF_REFERENCE:return`Cannot call CodeCall tools from within AgentScript`;default:return`An error occurred while calling "${toolName}"`}}function sanitizeValidationMessage(message){let sanitized=toClientErrorMessage(message);sanitized=sanitized.replace(/\bat line \d+/gi,"");sanitized=sanitized.replace(/\bline \d+/gi,"");sanitized=sanitized.replace(/:\d+:\d+/g,"");if(sanitized.length>200){sanitized=sanitized.substring(0,200)+"..."}return sanitized.trim()}var SelfReferenceError=class extends Error{code=TOOL_CALL_ERROR_CODES.SELF_REFERENCE;toolName;constructor(toolName){super(`Self-reference attack: Attempted to call CodeCall tool "${toolName}" from within AgentScript`);this.name="SelfReferenceError";this.toolName=toolName;Object.freeze(this)}};var CODECALL_TOOL_PREFIX="codecall:";var BLOCKED_CODECALL_TOOLS=Object.freeze(new Set(["codecall:search","codecall:describe","codecall:execute","codecall:invoke"]));function isBlockedSelfReference(toolName){const normalizedName=toolName.toLowerCase().trim();if(normalizedName.startsWith(CODECALL_TOOL_PREFIX)){return true}if(BLOCKED_CODECALL_TOOLS.has(toolName)){return true}return false}function assertNotSelfReference(toolName){if(isBlockedSelfReference(toolName)){throw new SelfReferenceError(toolName)}}var import_sdk3=require("@frontmcp/sdk");var AUDIT_EVENT_TYPES={EXECUTION_START:"codecall:execution:start",EXECUTION_SUCCESS:"codecall:execution:success",EXECUTION_FAILURE:"codecall:execution:failure",EXECUTION_TIMEOUT:"codecall:execution:timeout",TOOL_CALL_START:"codecall:tool:call:start",TOOL_CALL_SUCCESS:"codecall:tool:call:success",TOOL_CALL_FAILURE:"codecall:tool:call:failure",SECURITY_SELF_REFERENCE:"codecall:security:self-reference",SECURITY_ACCESS_DENIED:"codecall:security:access-denied",SECURITY_AST_BLOCKED:"codecall:security:ast-blocked",SEARCH_PERFORMED:"codecall:search:performed",DESCRIBE_PERFORMED:"codecall:describe:performed",INVOKE_PERFORMED:"codecall:invoke:performed"};var AuditLoggerService=class{listeners=new Set;executionCounter=0;subscribe(listener){this.listeners.add(listener);return()=>{this.listeners.delete(listener)}}generateExecutionId(){const timestamp=Date.now().toString(36);const counter=(++this.executionCounter).toString(36).padStart(4,"0");const random=Math.random().toString(36).substring(2,8);return`exec_${timestamp}_${counter}_${random}`}logExecutionStart(executionId,script){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_START,timestamp:new Date().toISOString(),executionId,data:{scriptHash:this.hashScript(script),scriptLength:script.length}})}logExecutionSuccess(executionId,script,durationMs,toolCallCount){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_SUCCESS,timestamp:new Date().toISOString(),executionId,durationMs,data:{scriptHash:this.hashScript(script),scriptLength:script.length,toolCallCount}})}logExecutionFailure(executionId,script,durationMs,error){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_FAILURE,timestamp:new Date().toISOString(),executionId,durationMs,data:{scriptHash:this.hashScript(script),scriptLength:script.length,error:this.sanitizeError(error)}})}logExecutionTimeout(executionId,script,durationMs){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_TIMEOUT,timestamp:new Date().toISOString(),executionId,durationMs,data:{scriptHash:this.hashScript(script),scriptLength:script.length}})}logToolCallStart(executionId,toolName,callDepth){this.emit({type:AUDIT_EVENT_TYPES.TOOL_CALL_START,timestamp:new Date().toISOString(),executionId,data:{toolName,callDepth}})}logToolCallSuccess(executionId,toolName,callDepth,durationMs){this.emit({type:AUDIT_EVENT_TYPES.TOOL_CALL_SUCCESS,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolName,callDepth}})}logToolCallFailure(executionId,toolName,callDepth,durationMs,errorCode){this.emit({type:AUDIT_EVENT_TYPES.TOOL_CALL_FAILURE,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolName,callDepth,errorCode}})}logSecuritySelfReference(executionId,toolName){this.emit({type:AUDIT_EVENT_TYPES.SECURITY_SELF_REFERENCE,timestamp:new Date().toISOString(),executionId,data:{blocked:toolName,reason:"Self-reference attack: attempted to call CodeCall tool from within AgentScript"}})}logSecurityAccessDenied(executionId,toolName,reason){this.emit({type:AUDIT_EVENT_TYPES.SECURITY_ACCESS_DENIED,timestamp:new Date().toISOString(),executionId,data:{blocked:toolName,reason:this.sanitizeError(reason)}})}logSecurityAstBlocked(executionId,pattern,reason){this.emit({type:AUDIT_EVENT_TYPES.SECURITY_AST_BLOCKED,timestamp:new Date().toISOString(),executionId,data:{blocked:pattern,reason:this.sanitizeError(reason)}})}logSearch(executionId,query,resultCount,durationMs){this.emit({type:AUDIT_EVENT_TYPES.SEARCH_PERFORMED,timestamp:new Date().toISOString(),executionId,durationMs,data:{queryLength:query.length,resultCount}})}logDescribe(executionId,toolNames,durationMs){this.emit({type:AUDIT_EVENT_TYPES.DESCRIBE_PERFORMED,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolCount:toolNames.length,toolNames:toolNames.slice(0,10)}})}logInvoke(executionId,toolName,success,durationMs){this.emit({type:AUDIT_EVENT_TYPES.INVOKE_PERFORMED,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolName,success}})}emit(event){const frozenEvent=Object.freeze({...event,data:Object.freeze({...event.data})});for(const listener of this.listeners){try{listener(frozenEvent)}catch{}}}hashScript(script){let hash=0;for(let i=0;i<script.length;i++){const char=script.charCodeAt(i);hash=(hash<<5)-hash+char;hash=hash&hash}return`sh_${(hash>>>0).toString(16).padStart(8,"0")}`}sanitizeError(error){if(!error)return"Unknown error";let sanitized=toClientErrorMessage(error);sanitized=sanitized.replace(/:\d+:\d+/g,"");if(sanitized.length>200){sanitized=sanitized.substring(0,200)+"..."}return sanitized.trim()}};AuditLoggerService=__decorateClass([(0,import_sdk3.Provider)({name:"codecall:audit-logger",scope:import_sdk3.ProviderScope.GLOBAL})],AuditLoggerService);var import_vectoriadb=require("vectoriadb");var DEFAULT_SYNONYM_GROUPS=[["create","add","new","insert","make","append","register","generate","produce","build","construct","provision","instantiate","define","compose","draft"],["delete","remove","destroy","drop","erase","clear","purge","discard","eliminate","nuke","unbind","unregister"],["get","fetch","retrieve","read","obtain","load","pull","access","grab","snag","receive"],["update","edit","modify","change","patch","alter","revise","refresh","correct","amend","adjust","tweak","rectify","refine"],["list","show","display","enumerate","browse","view","peek","index","catalog","survey","inspect","ls","dir"],["find","search","lookup","query","locate","filter","scan","explore","investigate","detect","scout","seek"],["archive","shelve","retire","hide","suppress","mute"],["unarchive","restore","recover","undelete","unhide"],["enable","activate","start","turn on","switch on","boot","init","initialize","setup","spin up","resume","unpause"],["disable","deactivate","stop","turn off","switch off","shutdown","halt","kill","terminate","suspend","pause","cease"],["run","execute","invoke","trigger","launch","call","perform","operate","handle","process","fire"],["restart","reboot","reset","reload","bounce","recycle","refresh"],["validate","verify","check","confirm","assert","test","audit","assess","healthcheck","ping"],["analyze","interpret","diagnose","evaluate","review","summarize","count","calculate","compute","measure","aggregate","summarise"],["copy","duplicate","clone","replicate","mirror","fork","repro"],["move","transfer","migrate","relocate","rename","shift","mv","slide"],["save","store","write","persist","commit","stash","record","log"],["sync","synchronize","resync","reconcile","align","pair"],["import","ingest","upload","push","feed"],["export","download","dump","backup","extract"],["connect","link","bind","attach","join","bridge","associate","mount","map"],["disconnect","unlink","unbind","detach","leave","dissociate","unmount","unmap"],["login","log in","sign in","authenticate","auth"],["logout","log out","sign out","disconnect"],["approve","authorize","grant","permit","allow","sanction","whitelist"],["deny","reject","revoke","forbid","block","ban","blacklist"],["encrypt","secure","lock","seal","protect","scramble","hash"],["decrypt","unlock","unseal","reveal","decode"],["deploy","release","ship","publish","roll out","promote","distribute","install"],["debug","troubleshoot","fix","repair","resolve","trace"],["compile","transpile","build","assemble","package","bundle","minify"],["buy","purchase","order","pay","checkout","spend"],["sell","refund","reimburse","charge","invoice","bill"],["subscribe","upgrade","upsell"],["unsubscribe","cancel","downgrade"],["schedule","book","appoint","reserve","plan","calendar"],["reschedule","postpone","delay","defer"],["send","dispatch","deliver","transmit","post","broadcast","notify","alert","email","text","message","chat"],["reply","respond","answer","retort"],["share","forward","retweet","repost"],["like","favorite","star","upvote","heart"],["dislike","downvote"],["follow","watch","track"],["unfollow","ignore","mute"],["user","account","member","profile","identity","customer","principal","admin","operator","client","employee","staff"],["role","group","team","squad","unit","department"],["file","document","attachment","blob","asset","object","resource","content","media"],["image","picture","photo","screenshot"],["video","clip","recording","footage"],["message","notification","alert","event","signal","webhook","ping"],["log","trace","metric","telemetry","audit trail","history"],["settings","config","configuration","preferences","options","params","env","environment","variables"],["permission","privilege","access right","policy","rule","scope"],["organization","company","tenant","workspace","org","project","repo","repository"],["product","item","sku","inventory","stock"],["task","ticket","issue","bug","story","epic","todo","job","workitem"],["id","identifier","key","uuid","guid","token","hash","fingerprint"]];var SynonymExpansionService=class{synonymMap;maxExpansions;constructor(config={}){this.maxExpansions=config.maxExpansionsPerTerm??5;const groups=config.replaceDefaults?config.additionalSynonyms||[]:[...DEFAULT_SYNONYM_GROUPS,...config.additionalSynonyms||[]];this.synonymMap=this.buildSynonymMap(groups)}buildSynonymMap(groups){const map=new Map;for(const group of groups){const normalizedGroup=group.map(term=>term.toLowerCase());for(const term of normalizedGroup){if(!map.has(term)){map.set(term,new Set)}const synonyms=map.get(term);for(const synonym of normalizedGroup){if(synonym!==term){synonyms.add(synonym)}}}}return map}getSynonyms(term){const normalized=term.toLowerCase();const synonyms=this.synonymMap.get(normalized);if(!synonyms){return[]}return Array.from(synonyms).slice(0,this.maxExpansions)}expandQuery(query){const terms=query.toLowerCase().split(/\s+/).filter(term=>term.length>1);const expandedTerms=[];for(const term of terms){expandedTerms.push(term);const synonyms=this.getSynonyms(term);expandedTerms.push(...synonyms)}return expandedTerms.join(" ")}hasExpansions(query){const terms=query.toLowerCase().split(/\s+/);return terms.some(term=>this.synonymMap.has(term))}getStats(){const termCount=this.synonymMap.size;let totalSynonyms=0;for(const synonyms of this.synonymMap.values()){totalSynonyms+=synonyms.size}return{termCount,avgSynonymsPerTerm:termCount>0?totalSynonyms/termCount:0}}};var STOP_WORDS=new Set(["the","a","an","this","that","these","those","in","on","at","to","for","of","with","by","from","into","over","after","before","between","under","about","against","during","through","and","or","but","nor","so","yet","as","than","if","because","while","when","where","unless","i","me","my","mine","myself","you","your","yours","yourself","he","him","his","himself","she","her","hers","herself","it","its","itself","we","us","our","ours","ourselves","they","them","their","theirs","themselves","who","whom","whose","which","what","is","was","are","were","been","be","being","have","has","had","having","do","does","did","doing","will","would","shall","should","can","could","may","might","must","all","any","both","each","few","more","most","other","some","such","no","nor","not","only","own","same","too","very","just","even","please","pls","plz","thanks","thank","thx","hello","hi","hey","ok","okay","yes","no","actually","basically","literally","maybe","perhaps","now","then","here","there","again","once","back","example","context","optionally","optional","etc","ie","eg"]);var DEFAULT_EMBEDDING_MODEL="Xenova/all-MiniLM-L6-v2";function messageOf(error){return error instanceof Error?error.message:String(error)}var ToolSearchService=class _ToolSearchService{static MAX_SUBSCRIPTION_RETRIES=100;static INITIAL_RETRY_DELAY_MS=10;static MAX_RETRY_DELAY_MS=1e3;vectorDB;strategy;initialized=false;mlInitialized=false;config;scope;unsubscribe;synonymService=null;synonymExpansion;indexing;subscriptionPromise;subscriptionResolved=false;subscriptionResolve=null;subscriptionReject=null;retryTimeoutId=null;disposed=false;availabilityByTool=new Map;constructor(config={},scope){this.scope=scope;const embeddingOptions=config.embeddingOptions||{strategy:"tfidf",modelName:DEFAULT_EMBEDDING_MODEL,cacheDir:"./.cache/transformers",useHNSW:false,synonymExpansion:{enabled:true,replaceDefaults:false,maxExpansionsPerTerm:5}};this.strategy=config.strategy||embeddingOptions.strategy||"tfidf";this.config={strategy:this.strategy,embeddingOptions,defaultTopK:config.defaultTopK??8,defaultSimilarityThreshold:config.defaultSimilarityThreshold??0,mode:config.mode??"codecall_only",includeTools:config.includeTools};const validModes=["codecall_only","codecall_opt_in","metadata_driven"];if(!validModes.includes(this.config.mode)){throw new Error(`Invalid CodeCall mode: ${this.config.mode}. Valid modes: ${validModes.join(", ")}`)}if(this.strategy==="ml"){this.vectorDB=new import_vectoriadb.VectoriaDB({modelName:embeddingOptions.modelName||DEFAULT_EMBEDDING_MODEL,cacheDir:embeddingOptions.cacheDir||"./.cache/transformers",defaultTopK:this.config.defaultTopK,defaultSimilarityThreshold:this.config.defaultSimilarityThreshold,useHNSW:embeddingOptions.useHNSW||false})}else{this.vectorDB=this.createTfidfIndex()}this.synonymExpansion=config.synonymExpansion??embeddingOptions.synonymExpansion;if(this.strategy==="tfidf"){this.synonymService=this.createSynonymService()}this.subscriptionPromise=new Promise((resolve,reject)=>{this.subscriptionResolve=resolve;this.subscriptionReject=reject});this.setupSubscription()}createTfidfIndex(){return new import_vectoriadb.TFIDFVectoria({defaultTopK:this.config.defaultTopK,defaultSimilarityThreshold:this.config.defaultSimilarityThreshold})}createSynonymService(){const synonymExpansion=this.synonymExpansion;if(synonymExpansion===false||synonymExpansion?.enabled===false)return null;return new SynonymExpansionService(synonymExpansion??{})}async ensureSubscribed(){if(this.subscriptionResolved){return}await this.subscriptionPromise}setupSubscription(retryCount=0,delayMs=_ToolSearchService.INITIAL_RETRY_DELAY_MS){if(this.scope.tools){this.subscribeToToolChanges();return}if(retryCount>=_ToolSearchService.MAX_SUBSCRIPTION_RETRIES){this.scope.logger.warn("ToolSearchService: scope.tools not available after max retries. Tool search will return incomplete results until tools are registered.");this.markSubscribed();return}const nextDelay=Math.min(delayMs*2,_ToolSearchService.MAX_RETRY_DELAY_MS);this.retryTimeoutId=setTimeout(()=>{this.retryTimeoutId=null;if(this.disposed){return}this.setupSubscription(retryCount+1,nextDelay)},delayMs)}subscribeToToolChanges(){this.unsubscribe=this.scope.tools.subscribe({immediate:true},event=>{this.queueReindex(event.snapshot)});this.markSubscribed()}queueReindex(tools){const reindex=()=>this.handleToolChange(tools);const run=(this.indexing?this.indexing.then(reindex):reindex()).catch(error=>{this.scope.logger.warn(`CodeCall tool search could not index the tools: ${messageOf(error)}`)});this.indexing=run;void run.then(()=>{if(this.indexing===run)this.indexing=void 0})}markSubscribed(){this.subscriptionResolved=true;if(this.subscriptionResolve){this.subscriptionResolve();this.subscriptionResolve=null}}async handleToolChange(tools){if(tools.length>0&&!this.mlInitialized&&this.strategy==="ml"&&this.vectorDB instanceof import_vectoriadb.VectoriaDB){try{await this.vectorDB.initialize();this.mlInitialized=true}catch(error){this.fallBackToTfidf(error)}}const availabilityByTool=new Map;const documents=tools.flatMap(tool=>this.toDocuments(tool,availabilityByTool));await this.replaceIndex(documents);this.availabilityByTool=availabilityByTool;this.initialized=true}toDocuments(tool,availabilityByTool){try{if(!this.shouldIndexTool(tool))return[];const toolName=tool.name;const document={id:toolName,text:this.extractSearchableText(tool),metadata:{id:toolName,toolName,qualifiedName:tool.fullName||toolName,appId:this.extractAppId(tool),toolInstance:tool}};availabilityByTool.set(toolName,tool.metadata.availableWhen);return[document]}catch(error){this.scope.logger.warn(`CodeCall tool search skipped tool "${tool.name}": ${messageOf(error)}`);return[]}}async replaceIndex(documents){if(this.vectorDB instanceof import_vectoriadb.VectoriaDB){try{this.vectorDB.clear();if(documents.length>0)await this.vectorDB.addMany(documents);return}catch(error){this.fallBackToTfidf(error)}}const index=this.createTfidfIndex();index.addDocuments(documents);index.reindex();this.vectorDB=index}fallBackToTfidf(error){const modelName=this.config.embeddingOptions.modelName||DEFAULT_EMBEDDING_MODEL;this.scope.logger.warn(`CodeCall could not use embedding model "${modelName}" (${messageOf(error)}); tool search uses TF-IDF instead`);this.strategy="tfidf";this.vectorDB=this.createTfidfIndex();this.synonymService=this.createSynonymService()}shouldIndexTool(tool){return checkCodeCallToolPolicy(toCodeCallPolicyTool(tool,void 0,this.scope),this.config).allowed}async initialize(){}dispose(){this.disposed=true;if(this.retryTimeoutId){clearTimeout(this.retryTimeoutId);this.retryTimeoutId=null}if(this.subscriptionReject){this.subscriptionReject(new Error("ToolSearchService disposed before subscription completed"));this.subscriptionReject=null;this.subscriptionResolve=null}if(this.unsubscribe){this.unsubscribe();this.unsubscribe=void 0}}extractSearchableText(tool){const parts=[];if(tool.name){const nameParts=tool.name.split(/[:\-_.]/).filter(Boolean);for(const part of nameParts){parts.push(part,part)}}if(tool.metadata.description){const description=tool.metadata.description;parts.push(description,description,description);const keyTerms=description.toLowerCase().split(/\s+/).filter(word=>word.length>=4&&!this.isStopWord(word));parts.push(...keyTerms)}if(tool.metadata.tags&&tool.metadata.tags.length>0){for(const tag of tool.metadata.tags){parts.push(tag,tag)}}if(tool.rawInputSchema&&typeof tool.rawInputSchema==="object"){const schema=tool.rawInputSchema;if(schema.properties){parts.push(...Object.keys(schema.properties))}}const examples=tool.metadata?.examples;if(examples&&Array.isArray(examples)){for(const ex of examples){if(ex.description){parts.push(ex.description,ex.description)}if(ex.input&&typeof ex.input==="object"){for(const[key,value]of Object.entries(ex.input)){parts.push(key);if(typeof value==="string"){parts.push(value)}}}}}return parts.join(" ")}isStopWord(word){return STOP_WORDS.has(word)}extractAppId(tool){return codeCallAppIdOf(this.scope,tool)}async search(query,options={}){await this.ensureSubscribed();await this.indexing;const{topK=this.config.defaultTopK,appIds,excludeToolNames=[],surface}=options;const minScore=this.config.defaultSimilarityThreshold;const filter=metadata=>{if(excludeToolNames.includes(metadata.toolName)){return false}if(!isOfferedToCaller(metadata.toolInstance.metadata.availableWhen,surface)){return false}if(appIds&&appIds.length>0){if(!metadata.appId||!appIds.includes(metadata.appId)){return false}}return true};const effectiveQuery=this.synonymService?this.synonymService.expandQuery(query):query;const results=await this.vectorDB.search(effectiveQuery,{topK,threshold:minScore,filter});return results.map(result=>({toolName:result.metadata.toolName,appId:result.metadata.appId,description:result.metadata.toolInstance.metadata.description||"",relevanceScore:result.score}))}getAllToolNames(){if(this.vectorDB instanceof import_vectoriadb.VectoriaDB){return this.vectorDB.getAll().map(doc=>doc.id)}else{return this.vectorDB.getAllDocumentIds()}}getTotalCount(surface){if(surface!==void 0){return this.getAllToolNames().filter(toolName=>this.hasTool(toolName,surface)).length}if(this.vectorDB instanceof import_vectoriadb.VectoriaDB){return this.vectorDB.size()}else{return this.vectorDB.getDocumentCount()}}hasTool(toolName,surface){const indexed=this.vectorDB instanceof import_vectoriadb.VectoriaDB?this.vectorDB.has(toolName):this.vectorDB.hasDocument(toolName);return indexed&&isOfferedToCaller(this.availabilityByTool.get(toolName),surface)}clear(){this.vectorDB.clear();this.availabilityByTool=new Map;this.initialized=false}getStrategy(){return this.strategy}isInitialized(){return this.initialized}};var import_core=require("@enclave-vm/core");var import_sdk4=require("@frontmcp/sdk");var import_ast=require("@enclave-vm/ast");var AGENTSCRIPT_PARSE_OPTIONS={ecmaVersion:"latest",sourceType:"script",allowReturnOutsideFunction:true,allowAwaitOutsideFunction:true};var PARSE_ATTEMPTS=[{wrap:code=>code,parseOptions:AGENTSCRIPT_PARSE_OPTIONS,lineOffset:0},{wrap:code=>code,parseOptions:{...AGENTSCRIPT_PARSE_OPTIONS,sourceType:"module"},lineOffset:0},{wrap:code=>`async function __temp__() {
1
+ "use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var __decorateClass=(decorators,target,key,kind)=>{var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target;for(var i=decorators.length-1,decorator;i>=0;i--)if(decorator=decorators[i])result=(kind?decorator(target,key,result):decorator(result))||result;if(kind&&result)__defProp(target,key,result);return result};var index_exports={};__export(index_exports,{AUDIT_EVENT_TYPES:()=>AUDIT_EVENT_TYPES,AuditLoggerService:()=>AuditLoggerService,CodeCallPlugin:()=>CodeCallPlugin,codeCallDirectCallsOptionsSchema:()=>codeCallDirectCallsOptionsSchema,codeCallEmbeddingOptionsSchema:()=>codeCallEmbeddingOptionsSchema,codeCallModeSchema:()=>codeCallModeSchema,codeCallPluginOptionsSchema:()=>codeCallPluginOptionsSchema,codeCallSidecarOptionsSchema:()=>codeCallSidecarOptionsSchema,codeCallVmOptionsSchema:()=>codeCallVmOptionsSchema,codeCallVmPresetSchema:()=>codeCallVmPresetSchema,default:()=>CodeCallPlugin,embeddingStrategySchema:()=>embeddingStrategySchema,synonymExpansionConfigSchema:()=>synonymExpansionConfigSchema});module.exports=__toCommonJS(index_exports);var import_plugin_cache=__toESM(require("@frontmcp/plugin-cache"));var import_sdk12=require("@frontmcp/sdk");var import_lazy_zod=require("@frontmcp/lazy-zod");var directCallsFilterSchema=import_lazy_zod.z.custom(val=>typeof val==="function",{message:"filter must be a function with signature (tool: DirectCallsFilterToolInfo) => boolean"});var includeToolsFilterSchema=import_lazy_zod.z.custom(val=>typeof val==="function",{message:"includeTools must be a function with signature (tool: IncludeToolsFilterToolInfo) => boolean"});var codeCallModeSchema=import_lazy_zod.z.enum(["codecall_only","codecall_opt_in","metadata_driven"]).default("codecall_only");var codeCallVmPresetSchema=import_lazy_zod.z.enum(["locked_down","secure","balanced","experimental"]).default("secure");var DEFAULT_VM_OPTIONS={preset:"secure"};var codeCallVmOptionsSchema=import_lazy_zod.z.object({preset:codeCallVmPresetSchema,timeoutMs:import_lazy_zod.z.number().positive().optional(),allowLoops:import_lazy_zod.z.boolean().optional(),maxSteps:import_lazy_zod.z.number().positive().optional(),disabledBuiltins:import_lazy_zod.z.array(import_lazy_zod.z.string()).optional(),disabledGlobals:import_lazy_zod.z.array(import_lazy_zod.z.string()).optional(),allowConsole:import_lazy_zod.z.boolean().optional(),maxSanitizeDepth:import_lazy_zod.z.number().positive().optional(),maxSanitizeProperties:import_lazy_zod.z.number().positive().optional(),rapidEnumerationThreshold:import_lazy_zod.z.number().int().positive().optional(),rapidEnumerationOverrides:import_lazy_zod.z.record(import_lazy_zod.z.string(),import_lazy_zod.z.number().int().positive()).optional()}).default(()=>DEFAULT_VM_OPTIONS);var codeCallDirectCallsOptionsSchema=import_lazy_zod.z.object({enabled:import_lazy_zod.z.boolean(),allowedTools:import_lazy_zod.z.array(import_lazy_zod.z.string()).optional(),filter:directCallsFilterSchema.optional()});var embeddingStrategySchema=import_lazy_zod.z.enum(["tfidf","ml"]).default("tfidf");var synonymExpansionConfigSchema=import_lazy_zod.z.object({enabled:import_lazy_zod.z.boolean().default(true),additionalSynonyms:import_lazy_zod.z.array(import_lazy_zod.z.array(import_lazy_zod.z.string())).optional(),replaceDefaults:import_lazy_zod.z.boolean().default(false),maxExpansionsPerTerm:import_lazy_zod.z.number().positive().default(5)}).default({enabled:true,replaceDefaults:false,maxExpansionsPerTerm:5});var DEFAULT_EMBEDDING_OPTIONS={strategy:"tfidf",modelName:"Xenova/all-MiniLM-L6-v2",cacheDir:"./.cache/transformers",useHNSW:false,synonymExpansion:{enabled:true,replaceDefaults:false,maxExpansionsPerTerm:5}};var codeCallEmbeddingOptionsSchema=import_lazy_zod.z.object({strategy:embeddingStrategySchema.optional(),modelName:import_lazy_zod.z.string().optional(),cacheDir:import_lazy_zod.z.string().optional(),useHNSW:import_lazy_zod.z.boolean().optional(),synonymExpansion:import_lazy_zod.z.union([import_lazy_zod.z.literal(false),synonymExpansionConfigSchema]).optional()}).optional().transform(opts=>({strategy:opts?.strategy??DEFAULT_EMBEDDING_OPTIONS.strategy,modelName:opts?.modelName??DEFAULT_EMBEDDING_OPTIONS.modelName,cacheDir:opts?.cacheDir??DEFAULT_EMBEDDING_OPTIONS.cacheDir,useHNSW:opts?.useHNSW??DEFAULT_EMBEDDING_OPTIONS.useHNSW,synonymExpansion:opts?.synonymExpansion??DEFAULT_EMBEDDING_OPTIONS.synonymExpansion}));var codeCallSidecarOptionsSchema=import_lazy_zod.z.object({enabled:import_lazy_zod.z.boolean().default(false),maxTotalSize:import_lazy_zod.z.number().positive().optional(),maxReferenceSize:import_lazy_zod.z.number().positive().optional(),extractionThreshold:import_lazy_zod.z.number().positive().optional(),maxResolvedSize:import_lazy_zod.z.number().positive().optional(),allowComposites:import_lazy_zod.z.boolean().optional(),maxScriptLengthWhenDisabled:import_lazy_zod.z.number().positive().nullable().default(64*1024)}).default(()=>({enabled:false,maxScriptLengthWhenDisabled:64*1024}));var codeCallPluginOptionsObjectSchema=import_lazy_zod.z.object({mode:codeCallModeSchema,appIds:import_lazy_zod.z.array(import_lazy_zod.z.string()).optional(),topK:import_lazy_zod.z.number().positive().default(8),maxDefinitions:import_lazy_zod.z.number().int().positive().default(8),includeTools:includeToolsFilterSchema.optional(),directCalls:codeCallDirectCallsOptionsSchema.optional(),vm:codeCallVmOptionsSchema,embedding:codeCallEmbeddingOptionsSchema,sidecar:codeCallSidecarOptionsSchema});var DEFAULT_PLUGIN_OPTIONS={mode:"codecall_only",topK:8,maxDefinitions:8,vm:DEFAULT_VM_OPTIONS,embedding:DEFAULT_EMBEDDING_OPTIONS,sidecar:{enabled:false,maxScriptLengthWhenDisabled:64*1024}};var codeCallPluginOptionsSchema=codeCallPluginOptionsObjectSchema.prefault(DEFAULT_PLUGIN_OPTIONS);var import_sdk=require("@frontmcp/sdk");var CodeCallConfig=class extends import_sdk.BaseConfig{constructor(options={}){const parsedConfig=codeCallPluginOptionsSchema.parse(options);const resolvedVm=resolveVmOptions(parsedConfig.vm);super({...parsedConfig,resolvedVm})}};CodeCallConfig=__decorateClass([(0,import_sdk.Provider)({name:"codecall:config",description:"CodeCall plugin configuration with validated defaults",scope:import_sdk.ProviderScope.GLOBAL})],CodeCallConfig);var MAX_ITERATIONS_PER_LOOP=1e4;function maxToolCallsOf(vmOptions){return vmOptions.maxSteps||100}var SANDBOX_RAPID_ENUMERATION_THRESHOLD=30;function rapidEnumerationThresholdOf(vmOptions){return vmOptions.rapidEnumerationThreshold??SANDBOX_RAPID_ENUMERATION_THRESHOLD}function resolveVmOptions(vmOptions){const preset=vmOptions?.preset??"secure";const base=presetDefaults(preset);return{...base,...vmOptions,disabledBuiltins:vmOptions?.disabledBuiltins??base.disabledBuiltins,disabledGlobals:vmOptions?.disabledGlobals??base.disabledGlobals,allowConsole:vmOptions?.allowConsole===true}}function presetDefaults(preset){switch(preset){case"locked_down":return{preset,timeoutMs:2e3,allowLoops:false,allowConsole:false,maxSteps:2e3,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process","fetch","setTimeout","setInterval","setImmediate","global","globalThis"],maxSanitizeDepth:10,maxSanitizeProperties:1e3};case"balanced":return{preset,timeoutMs:5e3,allowLoops:true,allowConsole:false,maxSteps:1e4,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process","fetch"],maxSanitizeDepth:50,maxSanitizeProperties:5e3};case"experimental":return{preset,timeoutMs:1e4,allowLoops:true,allowConsole:false,maxSteps:2e4,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process"],maxSanitizeDepth:100,maxSanitizeProperties:2e4};case"secure":default:return{preset:"secure",timeoutMs:3500,allowLoops:false,allowConsole:false,maxSteps:5e3,disabledBuiltins:["eval","Function","AsyncFunction"],disabledGlobals:["require","process","fetch","setTimeout","setInterval","setImmediate","global","globalThis"],maxSanitizeDepth:50,maxSanitizeProperties:2e3}}}var import_sdk2=require("@frontmcp/sdk");var CODECALL_DISPATCH=Symbol("frontmcp.codecall.dispatch");function asCodeCallDispatch(ctx){return Object.defineProperty(ctx,CODECALL_DISPATCH,{value:true,enumerable:false})}function isInProcessDispatch(ctx){if((0,import_sdk2.getRunningTool)())return true;if(typeof ctx!=="object"||ctx===null)return false;const marks=ctx;return marks[CODECALL_DISPATCH]===true||marks.internalCall===true}var BLOCKED_NAMESPACE_PATTERNS=Object.freeze([/^system:/,/^internal:/,/^__/]);function isOfferedToCaller(availableWhen,surface){const offered=availableWhen?.surface;return offered===void 0||surface===void 0||offered.includes(surface)}var ALLOWED={allowed:true};function deny(reason){return{allowed:false,reason}}function codeCallAppIdOf(scope,entry){const lineage=scope?.tools?.lineageOf?.(entry)??[];const owners=entry.owner?[...lineage,entry.owner]:lineage;return owners.find(owner=>owner.kind==="app")?.id}function toCodeCallPolicyTool(entry,requestedName,scope){const{metadata}=entry;return{name:entry.name||entry.fullName,fullName:entry.fullName,aliases:requestedName?[requestedName]:void 0,appId:codeCallAppIdOf(scope,entry),description:metadata?.description,tags:metadata?.tags,hidden:metadata?.hideFromDiscovery===true||metadata?.visibility==="hidden"||metadata?.visibility==="internal",codecall:metadata?.codecall,annotations:metadata?.annotations,metadata}}function isPlainData(value){if(Array.isArray(value))return true;const proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null}function readOnlyCopy(value,copies){if(typeof value!=="object"||value===null||!isPlainData(value))return value;const existing=copies.get(value);if(existing!==void 0)return existing;const copy=Array.isArray(value)?[]:Object.create(Object.getPrototypeOf(value));copies.set(value,copy);for(const key of Reflect.ownKeys(value)){if(!Object.prototype.propertyIsEnumerable.call(value,key))continue;Object.defineProperty(copy,key,{value:readOnlyCopy(Reflect.get(value,key),copies),enumerable:true,writable:true,configurable:true})}return Object.freeze(copy)}function toToolFilterInfo(tool){const copies=new WeakMap;const annotations=readOnlyCopy(tool.annotations,copies);const metadata=tool.metadata?readOnlyCopy({...tool.metadata,...annotations?{annotations:tool.annotations}:{}},copies):void 0;return{name:tool.name,fullName:tool.fullName,appId:tool.appId,source:tool.codecall?.source,description:tool.description,tags:readOnlyCopy(tool.codecall?.tags??tool.tags,copies),annotations,metadata}}function ownNamesOf(tool){return[tool.name,tool.fullName].filter(candidate=>!!candidate)}function checkCodeCallToolPolicy(tool,config){const{name}=tool;const spellings=[...ownNamesOf(tool),...tool.aliases??[]];if(spellings.some(candidate=>candidate.startsWith("codecall:"))){return deny("CodeCall meta-tools are not callable from CodeCall")}for(const candidate of spellings){if(BLOCKED_NAMESPACE_PATTERNS.some(pattern=>pattern.test(candidate))){return deny(`Tool "${candidate}" is in a namespace CodeCall never calls`)}}if(tool.hidden===true){return deny(`Tool "${name}" is hidden from discovery`)}const enabled=tool.codecall?.enabledInCodeCall;switch(config.mode){case"codecall_only":case"metadata_driven":if(enabled===false){return deny(`Tool "${name}" sets enabledInCodeCall: false`)}break;case"codecall_opt_in":if(enabled!==true){return deny(`Tool "${name}" has not opted in to CodeCall`)}break;default:return deny(`Unknown CodeCall mode: ${String(config.mode)}`)}if(config.includeTools&&!config.includeTools(toToolFilterInfo(tool))){return deny(`Tool "${name}" is excluded by the includeTools filter`)}return ALLOWED}function denyUnknownTool(name){return deny(`Tool "${name}" is not available through CodeCall`)}function resolveCodeCallTool(scope,name){const otherSpelling=/[-_]/.test(name)?name.includes("_")?name.replace(/_/g,"-"):name.replace(/-/g,"_"):void 0;const candidates=otherSpelling?[name,otherSpelling]:[name];const declaresAlias=entry=>entry.metadata?.aliases?.includes(name)===true;const matches=entry=>candidates.includes(entry.fullName)||candidates.includes(entry.name);return findResolvableTool(scope,declaresAlias)??findResolvableTool(scope,matches)}function findResolvableTool(scope,matches){const typedScope=scope;const local=typedScope.tools?.getTools(true)?.find(matches);if(local)return local;const registries=typedScope.providers?.getRegistries?.("AppRegistry")??[];for(const registry of registries){for(const app of registry.getApps()){if(!app.isRemote)continue;const remote=app.tools.getTools(true).find(matches);if(remote)return remote}}return void 0}function checkDirectCallPolicy(tool,directCalls){if(!directCalls)return ALLOWED;if(directCalls.enabled===false){return deny("Direct tool invocation is disabled")}const{allowedTools}=directCalls;if(allowedTools&&!ownNamesOf(tool).some(ownName=>allowedTools.includes(ownName))){return deny(`Tool "${tool.name}" is not in the direct-call allowlist`)}if(directCalls.filter&&!directCalls.filter(toToolFilterInfo(tool))){return deny(`Tool "${tool.name}" is excluded by the directCalls filter`)}return ALLOWED}function readCodeCallPolicyConfig(config){return{mode:config.get("mode")??"codecall_only",includeTools:config.get("includeTools")}}function checkCodeCallToolAccess(scope,config,name,options={}){const entry=resolveCodeCallTool(scope,name);if(!entry)return denyUnknownTool(name);if(!isOfferedToCaller(entry.metadata?.availableWhen,options.surface)){return deny(`Tool "${name}" is not offered on the caller's surface "${options.surface}"`)}const policyTool=toCodeCallPolicyTool(entry,name,scope);const baseDecision=checkCodeCallToolPolicy(policyTool,readCodeCallPolicyConfig(config));if(!baseDecision.allowed)return baseDecision;if(options.directCall){const directDecision=checkDirectCallPolicy(policyTool,config.get("directCalls"));if(!directDecision.allowed)return directDecision}return{allowed:true,entry}}var EMBEDDED_STACK_FRAME_RE=/\n[ \t]*at\s[^\n]*/g;var QUOTED_PATH_RE=/(['"`])((?:~?\/|[A-Za-z]:[\\/]|\\\\)[^\s'"`\\/][^'"`\n]*)\1/g;var URL_RE=/\b[A-Za-z][A-Za-z0-9+.-]{1,31}:\/\/(?:[^\s'"`<>,;]|[,;](?!~?\/|[A-Za-z]:[\\/]|\\\\))*/g;var QUERY_PATH_VALUE_RE=/([?&][^=&#]*=)(?:~?\/|[A-Za-z]:[\\/]|\\\\)[^&#]*/g;var POSIX_SEGMENT=String.raw`[^\s/\\'"\x60<>|,;:()\[\]{}]+`;var WINDOWS_SEGMENT=String.raw`[^\s/\\'"\x60<>|,;:*?]+`;function segments(segment,separator){const spaced=`${segment}(?: ${segment}){0,2}`;return`(?:(?:${spaced}${separator})+(?:${segment})?|${segment})`}var UNQUOTED_PATH_RE=new RegExp([String.raw`(?<![\w.~/\\)\]-])~?/+${segments(POSIX_SEGMENT,"/+")}`,String.raw`(?<![\w\\/])[A-Za-z]:[\\/]+${segments(WINDOWS_SEGMENT,String.raw`[\\/]+`)}?`,String.raw`(?<![\w\\])\\\\${segments(WINDOWS_SEGMENT,String.raw`[\\/]+`)}`].join("|"),"g");function redactPaths(text){return text.replace(QUOTED_PATH_RE,"$1[path]$1").replace(UNQUOTED_PATH_RE,"[path]")}function toClientErrorMessage(message){if(!message)return"";return redactAbsolutePaths(message.replace(EMBEDDED_STACK_FRAME_RE,""))}function redactAbsolutePaths(text){let result="";let last=0;for(const match of text.matchAll(URL_RE)){const start=match.index??0;result+=redactPaths(text.slice(last,start));result+=/^file:/i.test(match[0])?"[path]":match[0].replace(QUERY_PATH_VALUE_RE,"$1[path]");last=start+match[0].length}return result+redactPaths(text.slice(last))}var TOOL_CALL_ERROR_CODES={NOT_FOUND:"NOT_FOUND",VALIDATION:"VALIDATION",EXECUTION:"EXECUTION",TIMEOUT:"TIMEOUT",ACCESS_DENIED:"ACCESS_DENIED",RATE_LIMITED:"RATE_LIMITED",SELF_REFERENCE:"SELF_REFERENCE"};function createToolCallError(code,toolName,rawMessage){const sanitizedMessage=getSanitizedMessage(code,toolName,rawMessage);return Object.freeze({code,message:sanitizedMessage,toolName})}function createPublicToolCallError(code,toolName,publicMessage){return Object.freeze({code,message:toClientErrorMessage(publicMessage).trim()||getSanitizedMessage(code,toolName),toolName})}function getSanitizedMessage(code,toolName,rawMessage){switch(code){case TOOL_CALL_ERROR_CODES.NOT_FOUND:return`Tool "${toolName}" was not found`;case TOOL_CALL_ERROR_CODES.VALIDATION:return rawMessage?sanitizeValidationMessage(rawMessage):`Input validation failed for tool "${toolName}"`;case TOOL_CALL_ERROR_CODES.EXECUTION:return`Tool "${toolName}" execution failed`;case TOOL_CALL_ERROR_CODES.TIMEOUT:return`Tool "${toolName}" execution timed out`;case TOOL_CALL_ERROR_CODES.ACCESS_DENIED:return`Access denied for tool "${toolName}"`;case TOOL_CALL_ERROR_CODES.RATE_LIMITED:return`Tool "${toolName}" was rate limited`;case TOOL_CALL_ERROR_CODES.SELF_REFERENCE:return`Cannot call CodeCall tools from within AgentScript`;default:return`An error occurred while calling "${toolName}"`}}function sanitizeValidationMessage(message){let sanitized=toClientErrorMessage(message);sanitized=sanitized.replace(/\bat line \d+/gi,"");sanitized=sanitized.replace(/\bline \d+/gi,"");sanitized=sanitized.replace(/:\d+:\d+/g,"");if(sanitized.length>200){sanitized=sanitized.substring(0,200)+"..."}return sanitized.trim()}var SelfReferenceError=class extends Error{code=TOOL_CALL_ERROR_CODES.SELF_REFERENCE;toolName;constructor(toolName){super(`Self-reference attack: Attempted to call CodeCall tool "${toolName}" from within AgentScript`);this.name="SelfReferenceError";this.toolName=toolName;Object.freeze(this)}};var CODECALL_TOOL_PREFIX="codecall:";var BLOCKED_CODECALL_TOOLS=Object.freeze(new Set(["codecall:search","codecall:describe","codecall:execute","codecall:invoke"]));function isBlockedSelfReference(toolName){const normalizedName=toolName.toLowerCase().trim();if(normalizedName.startsWith(CODECALL_TOOL_PREFIX)){return true}if(BLOCKED_CODECALL_TOOLS.has(toolName)){return true}return false}function assertNotSelfReference(toolName){if(isBlockedSelfReference(toolName)){throw new SelfReferenceError(toolName)}}var import_sdk3=require("@frontmcp/sdk");var AUDIT_EVENT_TYPES={EXECUTION_START:"codecall:execution:start",EXECUTION_SUCCESS:"codecall:execution:success",EXECUTION_FAILURE:"codecall:execution:failure",EXECUTION_TIMEOUT:"codecall:execution:timeout",TOOL_CALL_START:"codecall:tool:call:start",TOOL_CALL_SUCCESS:"codecall:tool:call:success",TOOL_CALL_FAILURE:"codecall:tool:call:failure",SECURITY_SELF_REFERENCE:"codecall:security:self-reference",SECURITY_ACCESS_DENIED:"codecall:security:access-denied",SECURITY_AST_BLOCKED:"codecall:security:ast-blocked",SEARCH_PERFORMED:"codecall:search:performed",DESCRIBE_PERFORMED:"codecall:describe:performed",INVOKE_PERFORMED:"codecall:invoke:performed"};var AuditLoggerService=class{listeners=new Set;executionCounter=0;subscribe(listener){this.listeners.add(listener);return()=>{this.listeners.delete(listener)}}generateExecutionId(){const timestamp=Date.now().toString(36);const counter=(++this.executionCounter).toString(36).padStart(4,"0");const random=Math.random().toString(36).substring(2,8);return`exec_${timestamp}_${counter}_${random}`}logExecutionStart(executionId,script){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_START,timestamp:new Date().toISOString(),executionId,data:{scriptHash:this.hashScript(script),scriptLength:script.length}})}logExecutionSuccess(executionId,script,durationMs,toolCallCount){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_SUCCESS,timestamp:new Date().toISOString(),executionId,durationMs,data:{scriptHash:this.hashScript(script),scriptLength:script.length,toolCallCount}})}logExecutionFailure(executionId,script,durationMs,error){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_FAILURE,timestamp:new Date().toISOString(),executionId,durationMs,data:{scriptHash:this.hashScript(script),scriptLength:script.length,error:this.sanitizeError(error)}})}logExecutionTimeout(executionId,script,durationMs){this.emit({type:AUDIT_EVENT_TYPES.EXECUTION_TIMEOUT,timestamp:new Date().toISOString(),executionId,durationMs,data:{scriptHash:this.hashScript(script),scriptLength:script.length}})}logToolCallStart(executionId,toolName,callDepth){this.emit({type:AUDIT_EVENT_TYPES.TOOL_CALL_START,timestamp:new Date().toISOString(),executionId,data:{toolName,callDepth}})}logToolCallSuccess(executionId,toolName,callDepth,durationMs){this.emit({type:AUDIT_EVENT_TYPES.TOOL_CALL_SUCCESS,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolName,callDepth}})}logToolCallFailure(executionId,toolName,callDepth,durationMs,errorCode){this.emit({type:AUDIT_EVENT_TYPES.TOOL_CALL_FAILURE,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolName,callDepth,errorCode}})}logSecuritySelfReference(executionId,toolName){this.emit({type:AUDIT_EVENT_TYPES.SECURITY_SELF_REFERENCE,timestamp:new Date().toISOString(),executionId,data:{blocked:toolName,reason:"Self-reference attack: attempted to call CodeCall tool from within AgentScript"}})}logSecurityAccessDenied(executionId,toolName,reason){this.emit({type:AUDIT_EVENT_TYPES.SECURITY_ACCESS_DENIED,timestamp:new Date().toISOString(),executionId,data:{blocked:toolName,reason:this.sanitizeError(reason)}})}logSecurityAstBlocked(executionId,pattern,reason){this.emit({type:AUDIT_EVENT_TYPES.SECURITY_AST_BLOCKED,timestamp:new Date().toISOString(),executionId,data:{blocked:pattern,reason:this.sanitizeError(reason)}})}logSearch(executionId,query,resultCount,durationMs){this.emit({type:AUDIT_EVENT_TYPES.SEARCH_PERFORMED,timestamp:new Date().toISOString(),executionId,durationMs,data:{queryLength:query.length,resultCount}})}logDescribe(executionId,toolNames,durationMs){this.emit({type:AUDIT_EVENT_TYPES.DESCRIBE_PERFORMED,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolCount:toolNames.length,toolNames:toolNames.slice(0,10)}})}logInvoke(executionId,toolName,success,durationMs){this.emit({type:AUDIT_EVENT_TYPES.INVOKE_PERFORMED,timestamp:new Date().toISOString(),executionId,durationMs,data:{toolName,success}})}emit(event){const frozenEvent=Object.freeze({...event,data:Object.freeze({...event.data})});for(const listener of this.listeners){try{listener(frozenEvent)}catch{}}}hashScript(script){let hash=0;for(let i=0;i<script.length;i++){const char=script.charCodeAt(i);hash=(hash<<5)-hash+char;hash=hash&hash}return`sh_${(hash>>>0).toString(16).padStart(8,"0")}`}sanitizeError(error){if(!error)return"Unknown error";let sanitized=toClientErrorMessage(error);sanitized=sanitized.replace(/:\d+:\d+/g,"");if(sanitized.length>200){sanitized=sanitized.substring(0,200)+"..."}return sanitized.trim()}};AuditLoggerService=__decorateClass([(0,import_sdk3.Provider)({name:"codecall:audit-logger",scope:import_sdk3.ProviderScope.GLOBAL})],AuditLoggerService);var import_vectoriadb2=require("vectoriadb");var DEFAULT_SYNONYM_GROUPS=[["create","add","new","insert","make","append","register","generate","produce","build","construct","provision","instantiate","define","compose","draft"],["delete","remove","destroy","drop","erase","clear","purge","discard","eliminate","nuke","unbind","unregister"],["get","fetch","retrieve","read","obtain","load","pull","access","grab","snag","receive"],["update","edit","modify","change","patch","alter","revise","refresh","correct","amend","adjust","tweak","rectify","refine"],["list","show","display","enumerate","browse","view","peek","index","catalog","survey","inspect","ls","dir"],["find","search","lookup","query","locate","filter","scan","explore","investigate","detect","scout","seek"],["archive","shelve","retire","hide","suppress","mute"],["unarchive","restore","recover","undelete","unhide"],["enable","activate","start","turn on","switch on","boot","init","initialize","setup","spin up","resume","unpause"],["disable","deactivate","stop","turn off","switch off","shutdown","halt","kill","terminate","suspend","pause","cease"],["run","execute","invoke","trigger","launch","call","perform","operate","handle","process","fire"],["restart","reboot","reset","reload","bounce","recycle","refresh"],["validate","verify","check","confirm","assert","test","audit","assess","healthcheck","ping"],["analyze","interpret","diagnose","evaluate","review","summarize","count","calculate","compute","measure","aggregate","summarise"],["copy","duplicate","clone","replicate","mirror","fork","repro"],["move","transfer","migrate","relocate","rename","shift","mv","slide"],["save","store","write","persist","commit","stash","record","log"],["sync","synchronize","resync","reconcile","align","pair"],["import","ingest","upload","push","feed"],["export","download","dump","backup","extract"],["connect","link","bind","attach","join","bridge","associate","mount","map"],["disconnect","unlink","unbind","detach","leave","dissociate","unmount","unmap"],["login","log in","sign in","authenticate","auth"],["logout","log out","sign out","disconnect"],["approve","authorize","grant","permit","allow","sanction","whitelist"],["deny","reject","revoke","forbid","block","ban","blacklist"],["encrypt","secure","lock","seal","protect","scramble","hash"],["decrypt","unlock","unseal","reveal","decode"],["deploy","release","ship","publish","roll out","promote","distribute","install"],["debug","troubleshoot","fix","repair","resolve","trace"],["compile","transpile","build","assemble","package","bundle","minify"],["buy","purchase","order","pay","checkout","spend"],["sell","refund","reimburse","charge","invoice","bill"],["subscribe","upgrade","upsell"],["unsubscribe","cancel","downgrade"],["schedule","book","appoint","reserve","plan","calendar"],["reschedule","postpone","delay","defer"],["send","dispatch","deliver","transmit","post","broadcast","notify","alert","email","text","message","chat"],["reply","respond","answer","retort"],["share","forward","retweet","repost"],["like","favorite","star","upvote","heart"],["dislike","downvote"],["follow","watch","track"],["unfollow","ignore","mute"],["user","account","member","profile","identity","customer","principal","admin","operator","client","employee","staff"],["role","group","team","squad","unit","department"],["file","document","attachment","blob","asset","object","resource","content","media"],["image","picture","photo","screenshot"],["video","clip","recording","footage"],["message","notification","alert","event","signal","webhook","ping"],["log","trace","metric","telemetry","audit trail","history"],["settings","config","configuration","preferences","options","params","env","environment","variables"],["permission","privilege","access right","policy","rule","scope"],["organization","company","tenant","workspace","org","project","repo","repository"],["product","item","sku","inventory","stock"],["task","ticket","issue","bug","story","epic","todo","job","workitem"],["id","identifier","key","uuid","guid","token","hash","fingerprint"]];var SynonymExpansionService=class{synonymMap;maxExpansions;constructor(config={}){this.maxExpansions=config.maxExpansionsPerTerm??5;const groups=config.replaceDefaults?config.additionalSynonyms||[]:[...DEFAULT_SYNONYM_GROUPS,...config.additionalSynonyms||[]];this.synonymMap=this.buildSynonymMap(groups)}buildSynonymMap(groups){const map=new Map;for(const group of groups){const normalizedGroup=group.map(term=>term.toLowerCase());for(const term of normalizedGroup){if(!map.has(term)){map.set(term,new Set)}const synonyms=map.get(term);for(const synonym of normalizedGroup){if(synonym!==term){synonyms.add(synonym)}}}}return map}getSynonyms(term){const normalized=term.toLowerCase();const synonyms=this.synonymMap.get(normalized);if(!synonyms){return[]}return Array.from(synonyms).slice(0,this.maxExpansions)}expandQuery(query){const terms=query.toLowerCase().split(/\s+/).filter(term=>term.length>1);const expandedTerms=[];for(const term of terms){expandedTerms.push(term);const synonyms=this.getSynonyms(term);expandedTerms.push(...synonyms)}return expandedTerms.join(" ")}hasExpansions(query){const terms=query.toLowerCase().split(/\s+/);return terms.some(term=>this.synonymMap.has(term))}getStats(){const termCount=this.synonymMap.size;let totalSynonyms=0;for(const synonyms of this.synonymMap.values()){totalSynonyms+=synonyms.size}return{termCount,avgSynonymsPerTerm:termCount>0?totalSynonyms/termCount:0}}};var import_vectoriadb=require("vectoriadb");function stemTerm(term){if(term.length<=3)return term;if(term.endsWith("ies"))return`${term.slice(0,-3)}y`;if(/(?:x|ch|sh|ss)es$/.test(term))return term.slice(0,-2);if(!term.endsWith("s")||/(?:ss|us|is)$/.test(term))return term;return term.slice(0,-1)}function dotProduct(left,right){let sum=0;for(const[term,weight]of left){sum+=weight*(right.get(term)??0)}return sum}var ToolTfidfIndex=class{constructor(documents=[],stopWords=new Set){this.stopWords=stopWords;const termsOf=documents.map(document=>this.tokenize(document.text));const documentFrequency=new Map;for(const terms of termsOf){for(const term of new Set(terms)){documentFrequency.set(term,(documentFrequency.get(term)??0)+1)}}for(const[term,frequency]of documentFrequency){this.idf.set(term,Math.log((1+documents.length)/(1+frequency))+1)}documents.forEach((document,index)=>{this.vectors.set(document.id,{metadata:document.metadata,vector:this.vectorOf(termsOf[index])})})}stopWords;idf=new Map;vectors=new Map;search(query,{topK,threshold,filter}){const queryVector=this.vectorOf(this.tokenize(query));const results=[];for(const[id,{metadata,vector}]of this.vectors){if(filter&&!filter(metadata))continue;const score=dotProduct(queryVector,vector);if(score>=threshold)results.push({id,metadata,score})}return results.sort((left,right)=>right.score-left.score).slice(0,topK)}getAllDocumentIds(){return[...this.vectors.keys()]}getDocumentCount(){return this.vectors.size}hasDocument(id){return this.vectors.has(id)}tokenize(text){return(0,import_vectoriadb.defaultTokenizer)(text).filter(term=>!this.stopWords.has(term)).map(stemTerm)}vectorOf(terms){const vector=new Map;for(const term of terms){const idf=this.idf.get(term);if(idf!==void 0)vector.set(term,(vector.get(term)??0)+idf)}const norm=Math.sqrt([...vector.values()].reduce((sum,weight)=>sum+weight*weight,0));if(norm===0)return vector;for(const[term,weight]of vector){vector.set(term,weight/norm)}return vector}};var STOP_WORDS=new Set(["the","a","an","this","that","these","those","in","on","at","to","for","of","with","by","from","into","over","after","before","between","under","about","against","during","through","and","or","but","nor","so","yet","as","than","if","because","while","when","where","unless","i","me","my","mine","myself","you","your","yours","yourself","he","him","his","himself","she","her","hers","herself","it","its","itself","we","us","our","ours","ourselves","they","them","their","theirs","themselves","who","whom","whose","which","what","is","was","are","were","been","be","being","have","has","had","having","do","does","did","doing","will","would","shall","should","can","could","may","might","must","all","any","both","each","few","more","most","other","some","such","no","nor","not","only","own","same","too","very","just","even","please","pls","plz","thanks","thank","thx","hello","hi","hey","ok","okay","yes","no","actually","basically","literally","maybe","perhaps","now","then","here","there","again","once","back","example","context","optionally","optional","etc","ie","eg"]);var DEFAULT_EMBEDDING_MODEL="Xenova/all-MiniLM-L6-v2";function messageOf(error){return error instanceof Error?error.message:String(error)}var ToolSearchService=class _ToolSearchService{static MAX_SUBSCRIPTION_RETRIES=100;static INITIAL_RETRY_DELAY_MS=10;static MAX_RETRY_DELAY_MS=1e3;vectorDB;strategy;initialized=false;mlInitialized=false;config;scope;unsubscribe;synonymService=null;synonymExpansion;indexing;subscriptionPromise;subscriptionResolved=false;subscriptionResolve=null;subscriptionReject=null;retryTimeoutId=null;disposed=false;availabilityByTool=new Map;constructor(config={},scope){this.scope=scope;const embeddingOptions=config.embeddingOptions||{strategy:"tfidf",modelName:DEFAULT_EMBEDDING_MODEL,cacheDir:"./.cache/transformers",useHNSW:false,synonymExpansion:{enabled:true,replaceDefaults:false,maxExpansionsPerTerm:5}};this.strategy=config.strategy||embeddingOptions.strategy||"tfidf";this.config={strategy:this.strategy,embeddingOptions,defaultTopK:config.defaultTopK??8,defaultSimilarityThreshold:config.defaultSimilarityThreshold??0,mode:config.mode??"codecall_only",includeTools:config.includeTools};const validModes=["codecall_only","codecall_opt_in","metadata_driven"];if(!validModes.includes(this.config.mode)){throw new Error(`Invalid CodeCall mode: ${this.config.mode}. Valid modes: ${validModes.join(", ")}`)}if(this.strategy==="ml"){this.vectorDB=new import_vectoriadb2.VectoriaDB({modelName:embeddingOptions.modelName||DEFAULT_EMBEDDING_MODEL,cacheDir:embeddingOptions.cacheDir||"./.cache/transformers",defaultTopK:this.config.defaultTopK,defaultSimilarityThreshold:this.config.defaultSimilarityThreshold,useHNSW:embeddingOptions.useHNSW||false})}else{this.vectorDB=this.createTfidfIndex()}this.synonymExpansion=config.synonymExpansion??embeddingOptions.synonymExpansion;if(this.strategy==="tfidf"){this.synonymService=this.createSynonymService()}this.subscriptionPromise=new Promise((resolve,reject)=>{this.subscriptionResolve=resolve;this.subscriptionReject=reject});this.setupSubscription()}createTfidfIndex(documents=[]){return new ToolTfidfIndex(documents,STOP_WORDS)}createSynonymService(){const synonymExpansion=this.synonymExpansion;if(synonymExpansion===false||synonymExpansion?.enabled===false)return null;return new SynonymExpansionService(synonymExpansion??{})}async ensureSubscribed(){if(this.subscriptionResolved){return}await this.subscriptionPromise}setupSubscription(retryCount=0,delayMs=_ToolSearchService.INITIAL_RETRY_DELAY_MS){if(this.scope.tools){this.subscribeToToolChanges();return}if(retryCount>=_ToolSearchService.MAX_SUBSCRIPTION_RETRIES){this.scope.logger.warn("ToolSearchService: scope.tools not available after max retries. Tool search will return incomplete results until tools are registered.");this.markSubscribed();return}const nextDelay=Math.min(delayMs*2,_ToolSearchService.MAX_RETRY_DELAY_MS);this.retryTimeoutId=setTimeout(()=>{this.retryTimeoutId=null;if(this.disposed){return}this.setupSubscription(retryCount+1,nextDelay)},delayMs)}subscribeToToolChanges(){this.unsubscribe=this.scope.tools.subscribe({immediate:true},event=>{this.queueReindex(event.snapshot)});this.markSubscribed()}queueReindex(tools){const reindex=()=>this.handleToolChange(tools);const run=(this.indexing?this.indexing.then(reindex):reindex()).catch(error=>{this.scope.logger.warn(`CodeCall tool search could not index the tools: ${messageOf(error)}`)});this.indexing=run;void run.then(()=>{if(this.indexing===run)this.indexing=void 0})}markSubscribed(){this.subscriptionResolved=true;if(this.subscriptionResolve){this.subscriptionResolve();this.subscriptionResolve=null}}async handleToolChange(tools){if(tools.length>0&&!this.mlInitialized&&this.strategy==="ml"&&this.vectorDB instanceof import_vectoriadb2.VectoriaDB){try{await this.vectorDB.initialize();this.mlInitialized=true}catch(error){this.fallBackToTfidf(error)}}const availabilityByTool=new Map;const documents=tools.flatMap(tool=>this.toDocuments(tool,availabilityByTool));await this.replaceIndex(documents);this.availabilityByTool=availabilityByTool;this.initialized=true}toDocuments(tool,availabilityByTool){try{if(!this.shouldIndexTool(tool))return[];const toolName=tool.name;const document={id:toolName,text:this.extractSearchableText(tool),metadata:{id:toolName,toolName,qualifiedName:tool.fullName||toolName,appId:this.extractAppId(tool),toolInstance:tool}};availabilityByTool.set(toolName,tool.metadata.availableWhen);return[document]}catch(error){this.scope.logger.warn(`CodeCall tool search skipped tool "${tool.name}": ${messageOf(error)}`);return[]}}async replaceIndex(documents){if(this.vectorDB instanceof import_vectoriadb2.VectoriaDB){try{this.vectorDB.clear();if(documents.length>0)await this.vectorDB.addMany(documents);return}catch(error){this.fallBackToTfidf(error)}}this.vectorDB=this.createTfidfIndex(documents)}fallBackToTfidf(error){const modelName=this.config.embeddingOptions.modelName||DEFAULT_EMBEDDING_MODEL;this.scope.logger.warn(`CodeCall could not use embedding model "${modelName}" (${messageOf(error)}); tool search uses TF-IDF instead`);this.strategy="tfidf";this.vectorDB=this.createTfidfIndex();this.synonymService=this.createSynonymService()}shouldIndexTool(tool){return checkCodeCallToolPolicy(toCodeCallPolicyTool(tool,void 0,this.scope),this.config).allowed}async initialize(){}dispose(){this.disposed=true;if(this.retryTimeoutId){clearTimeout(this.retryTimeoutId);this.retryTimeoutId=null}if(this.subscriptionReject){this.subscriptionReject(new Error("ToolSearchService disposed before subscription completed"));this.subscriptionReject=null;this.subscriptionResolve=null}if(this.unsubscribe){this.unsubscribe();this.unsubscribe=void 0}}extractSearchableText(tool){const parts=[];if(tool.name){const nameParts=tool.name.split(/[:\-_.]/).filter(Boolean);for(const part of nameParts){parts.push(part,part)}}if(tool.metadata.description){const description=tool.metadata.description;parts.push(description,description,description);const keyTerms=description.toLowerCase().split(/\s+/).filter(word=>word.length>=4&&!this.isStopWord(word));parts.push(...keyTerms)}if(tool.metadata.tags&&tool.metadata.tags.length>0){for(const tag of tool.metadata.tags){parts.push(tag,tag)}}if(tool.rawInputSchema&&typeof tool.rawInputSchema==="object"){const schema=tool.rawInputSchema;if(schema.properties){parts.push(...Object.keys(schema.properties))}}const examples=tool.metadata?.examples;if(examples&&Array.isArray(examples)){for(const ex of examples){if(ex.description){parts.push(ex.description,ex.description)}if(ex.input&&typeof ex.input==="object"){for(const[key,value]of Object.entries(ex.input)){parts.push(key);if(typeof value==="string"){parts.push(value)}}}}}return parts.join(" ")}isStopWord(word){return STOP_WORDS.has(word)}extractAppId(tool){return codeCallAppIdOf(this.scope,tool)}async search(query,options={}){await this.ensureSubscribed();await this.indexing;const{topK=this.config.defaultTopK,appIds,excludeToolNames=[],surface}=options;const minScore=this.config.defaultSimilarityThreshold;const filter=metadata=>{if(excludeToolNames.includes(metadata.toolName)){return false}if(!isOfferedToCaller(metadata.toolInstance.metadata.availableWhen,surface)){return false}if(appIds&&appIds.length>0){if(!metadata.appId||!appIds.includes(metadata.appId)){return false}}return true};const effectiveQuery=this.synonymService?this.synonymService.expandQuery(query):query;const results=await this.vectorDB.search(effectiveQuery,{topK,threshold:minScore,filter});return results.map(result=>({toolName:result.metadata.toolName,appId:result.metadata.appId,description:result.metadata.toolInstance.metadata.description||"",relevanceScore:result.score}))}getAllToolNames(){if(this.vectorDB instanceof import_vectoriadb2.VectoriaDB){return this.vectorDB.getAll().map(doc=>doc.id)}else{return this.vectorDB.getAllDocumentIds()}}getTotalCount(surface){if(surface!==void 0){return this.getAllToolNames().filter(toolName=>this.hasTool(toolName,surface)).length}if(this.vectorDB instanceof import_vectoriadb2.VectoriaDB){return this.vectorDB.size()}else{return this.vectorDB.getDocumentCount()}}hasTool(toolName,surface){const indexed=this.vectorDB instanceof import_vectoriadb2.VectoriaDB?this.vectorDB.has(toolName):this.vectorDB.hasDocument(toolName);return indexed&&isOfferedToCaller(this.availabilityByTool.get(toolName),surface)}clear(){if(this.vectorDB instanceof import_vectoriadb2.VectoriaDB){this.vectorDB.clear()}else{this.vectorDB=this.createTfidfIndex()}this.availabilityByTool=new Map;this.initialized=false}getStrategy(){return this.strategy}isInitialized(){return this.initialized}};var import_core=require("@enclave-vm/core");var import_sdk4=require("@frontmcp/sdk");var import_ast=require("@enclave-vm/ast");var AGENTSCRIPT_PARSE_OPTIONS={ecmaVersion:"latest",sourceType:"script",allowReturnOutsideFunction:true,allowAwaitOutsideFunction:true};var PARSE_ATTEMPTS=[{wrap:code=>code,parseOptions:AGENTSCRIPT_PARSE_OPTIONS,lineOffset:0},{wrap:code=>code,parseOptions:{...AGENTSCRIPT_PARSE_OPTIONS,sourceType:"module"},lineOffset:0},{wrap:code=>`async function __temp__() {
2
2
  ${code}
3
- }`,parseOptions:AGENTSCRIPT_PARSE_OPTIONS,lineOffset:1}];var NON_REFERENCE_KEYS=new Set(["type","loc","start","end","range","label"]);function isAstNode(value){return typeof value==="object"&&value!==null&&typeof value.type==="string"}function isPropertyName(parent,key){if(!parent||parent["computed"])return false;if(parent.type==="MemberExpression")return key==="property";return key==="key"&&["Property","MethodDefinition","PropertyDefinition"].includes(parent.type)}function visitIdentifierReferences(node,visit,parent,key=""){if(node.type==="Identifier"){if(!isPropertyName(parent,key))visit(node);return}for(const[childKey,child]of Object.entries(node)){if(NON_REFERENCE_KEYS.has(childKey))continue;const children=Array.isArray(child)?child:[child];for(const childNode of children){if(isAstNode(childNode))visitIdentifierReferences(childNode,visit,node,childKey)}}}var DisallowedGlobalsRule=class{constructor(messages){this.messages=messages}messages;name="codecall-disallowed-globals";description="Globals CodeCall scripts may not use";defaultSeverity=import_ast.ValidationSeverity.ERROR;enabledByDefault=true;validate(context){visitIdentifierReferences(context.ast,identifier=>{const message=identifier.name===void 0?void 0:this.messages.get(identifier.name);if(message===void 0)return;context.report({code:"DISALLOWED_IDENTIFIER",message,location:identifier.loc?{line:identifier.loc.start.line,column:identifier.loc.start.column}:void 0,data:{identifier:identifier.name}})})}};function disallowedGlobalMessages({disabledBuiltins,disabledGlobals}){return new Map([...disabledBuiltins.map(name=>[name,`${name} is disabled by vm.disabledBuiltins`]),...disabledGlobals.map(name=>[name,`${name} is disabled by vm.disabledGlobals`]),["console","console is not available in CodeCall scripts; use mcpLog(level, message)"]])}function scriptPolicyRules(options){const rules=[new DisallowedGlobalsRule(disallowedGlobalMessages(options))];if(!options.allowLoops){rules.push(new import_ast.ForbiddenLoopRule({allowFor:false,allowForOf:true,allowWhile:false,allowDoWhile:false,allowForIn:false,message:"Only for-of loops are allowed (vm.allowLoops is false)"}))}return rules}async function findScriptPolicyIssues(code,options){const validator=new import_ast.JSAstValidator(scriptPolicyRules(options));for(const attempt of PARSE_ATTEMPTS){const result=await validator.validate(attempt.wrap(code),{parseOptions:attempt.parseOptions,preScan:{enabled:false}});if(result.parseError)continue;return result.issues.map(issue=>issue.location&&attempt.lineOffset>0?{...issue,location:{...issue.location,line:issue.location.line-attempt.lineOffset}}:issue)}return[]}var IDENT_RE=/^[A-Za-z_$][A-Za-z0-9_$]*$/;var PROTOTYPE_KEYS=new Set(["__proto__","constructor","prototype"]);var RESERVED_NAMESPACES=new Set(["console","Math","JSON","Object","Array","String","Number","Boolean","Promise","Symbol","Map","Set","WeakMap","WeakSet","Date","Error","RegExp","globalThis","global","window","self","undefined","null","true","false","callTool","getTool","mcpLog","mcpNotify"]);var UNBINDABLE_NAMESPACES=new Set(["break case catch class const continue debugger default delete do else enum export extends finally for","function if import in instanceof new return super switch this throw try typeof var void while with yield","let static implements interface package private protected public await eval arguments NaN Infinity","parallel isNaN isFinite parseInt parseFloat encodeURI encodeURIComponent decodeURI decodeURIComponent","process require module exports Buffer Function AsyncFunction GeneratorFunction Reflect Proxy TypeError","ReferenceError SyntaxError RangeError URIError EvalError AggregateError fetch XMLHttpRequest WebSocket","localStorage sessionStorage indexedDB crypto performance structuredClone AbortController AbortSignal","MessageChannel MessagePort BroadcastChannel TextEncoder TextDecoder Intl setTimeout setInterval","setImmediate clearTimeout clearInterval clearImmediate queueMicrotask WebAssembly Worker SharedWorker","ServiceWorker WeakRef FinalizationRegistry BigInt Atomics SharedArrayBuffer ArrayBuffer DataView","importScripts ShadowRealm Iterator AsyncIterator"].join(" ").split(" "));var UNCALLABLE_METHODS=new Set(["process require module exports Buffer eval Function AsyncFunction GeneratorFunction arguments RegExp","Promise Symbol Proxy Reflect Error TypeError ReferenceError SyntaxError RangeError URIError EvalError","AggregateError fetch XMLHttpRequest WebSocket localStorage sessionStorage indexedDB crypto performance","structuredClone AbortController AbortSignal MessageChannel MessagePort BroadcastChannel TextEncoder","TextDecoder Intl setTimeout setInterval setImmediate clearTimeout clearInterval clearImmediate","queueMicrotask WebAssembly Worker SharedWorker ServiceWorker WeakMap WeakSet WeakRef FinalizationRegistry","Map Set Atomics SharedArrayBuffer importScripts ShadowRealm Iterator AsyncIterator"].join(" ").split(" "));var SANDBOX_TOOL_NAME_RE=/^[a-zA-Z][a-zA-Z0-9:._-]*$/;var MAX_SANDBOX_TOOL_NAME_LENGTH=256;function isBindableNamespace(ns,reservedGlobals){return IDENT_RE.test(ns)&&!PROTOTYPE_KEYS.has(ns)&&!ns.startsWith("__")&&!RESERVED_NAMESPACES.has(ns)&&!UNBINDABLE_NAMESPACES.has(ns)&&!reservedGlobals.has(ns)}function isBindableMethod(ns,method,toolName){return IDENT_RE.test(method)&&!PROTOTYPE_KEYS.has(method)&&!method.startsWith("__")&&!UNCALLABLE_METHODS.has(method)&&toolName===`${ns}.${method}`&&toolName.length<=MAX_SANDBOX_TOOL_NAME_LENGTH&&SANDBOX_TOOL_NAME_RE.test(toolName)}function buildToolNamespaces(tools){const namespaces=Object.create(null);const skipped=[];for(const tool of tools){const name=tool?.name;if(typeof name!=="string"||name.length===0)continue;const dot=name.indexOf(".");if(dot<=0||dot===name.length-1){skipped.push({name,reason:"no-namespace-prefix"});continue}const ns=name.slice(0,dot);const method=name.slice(dot+1);if(!IDENT_RE.test(ns)||!IDENT_RE.test(method)){skipped.push({name,reason:"invalid-identifier"});continue}if(PROTOTYPE_KEYS.has(ns)||PROTOTYPE_KEYS.has(method)){skipped.push({name,reason:"prototype-key"});continue}if(RESERVED_NAMESPACES.has(ns)||UNBINDABLE_NAMESPACES.has(ns)||ns.startsWith("__")){skipped.push({name,reason:"reserved-namespace"});continue}if(!isBindableMethod(ns,method,name)){skipped.push({name,reason:"unsupported-name"});continue}const bucket=namespaces[ns]??(namespaces[ns]=Object.create(null));if(Object.prototype.hasOwnProperty.call(bucket,method)){skipped.push({name,reason:"duplicate-method"});continue}bucket[method]=name}return{namespaces,skipped}}function toSandboxToolNamespaces(namespaces,reservedGlobals=[]){if(!namespaces)return void 0;const reserved=new Set(reservedGlobals);const bindable=Object.create(null);let count=0;for(const ns of Object.keys(namespaces)){if(!isBindableNamespace(ns,reserved))continue;const methods=namespaces[ns];const bucket=Object.create(null);let methodCount=0;for(const method of Object.keys(methods)){const toolName=methods[method];if(typeof toolName!=="string"||!isBindableMethod(ns,method,toolName))continue;bucket[method]=toolName;methodCount+=1}if(methodCount>0){bindable[ns]=bucket;count+=1}}return count>0?bindable:void 0}var import_ast2=require("@enclave-vm/ast");var acorn=__toESM(require("acorn"));var PARSE_OPTIONS={ecmaVersion:"latest",locations:true};var NON_CHILD_KEYS=new Set(["type","loc","start","end","range"]);function isNode(value){return typeof value==="object"&&value!==null&&typeof value.type==="string"}function isAddedByTransform(node){if(node.type==="VariableDeclaration"){const[declaration]=node["declarations"]??[];const id=declaration?.["id"];return typeof id?.["name"]==="string"&&id["name"].startsWith("__iter_")}if(node.type==="IfStatement"){const right=node["test"]?.["right"];return right?.type==="Identifier"&&right["name"]==="__maxIterations"}return false}function parseScript(script){try{return{body:parseBody(script,"script"),offset:0}}catch{try{return{body:parseBody(script,"module"),offset:0}}catch{const wrapped=parseBody(`async function __temp__() {
3
+ }`,parseOptions:AGENTSCRIPT_PARSE_OPTIONS,lineOffset:1}];var NON_REFERENCE_KEYS=new Set(["type","loc","start","end","range","label"]);function isAstNode(value){return typeof value==="object"&&value!==null&&typeof value.type==="string"}function isPropertyName(parent,key){if(!parent||parent["computed"])return false;if(parent.type==="MemberExpression")return key==="property";return key==="key"&&["Property","MethodDefinition","PropertyDefinition"].includes(parent.type)}function visitIdentifierReferences(node,visit,parent,key=""){if(node.type==="Identifier"){if(!isPropertyName(parent,key))visit(node);return}for(const[childKey,child]of Object.entries(node)){if(NON_REFERENCE_KEYS.has(childKey))continue;const children=Array.isArray(child)?child:[child];for(const childNode of children){if(isAstNode(childNode))visitIdentifierReferences(childNode,visit,node,childKey)}}}var DisallowedGlobalsRule=class{constructor(messages){this.messages=messages}messages;name="codecall-disallowed-globals";description="Globals CodeCall scripts may not use";defaultSeverity=import_ast.ValidationSeverity.ERROR;enabledByDefault=true;validate(context){visitIdentifierReferences(context.ast,identifier=>{const message=identifier.name===void 0?void 0:this.messages.get(identifier.name);if(message===void 0)return;context.report({code:"DISALLOWED_IDENTIFIER",message,location:identifier.loc?{line:identifier.loc.start.line,column:identifier.loc.start.column}:void 0,data:{identifier:identifier.name}})})}};function disallowedGlobalMessages({disabledBuiltins,disabledGlobals,allowConsole}){const messages=new Map([...disabledBuiltins.map(name=>[name,`${name} is disabled by vm.disabledBuiltins`]),...disabledGlobals.map(name=>[name,`${name} is disabled by vm.disabledGlobals`])]);if(!allowConsole){messages.set("console","console is not available in CodeCall scripts unless vm.allowConsole is true; use mcpLog(level, message)")}return messages}function scriptPolicyRules(options){const rules=[new DisallowedGlobalsRule(disallowedGlobalMessages(options))];if(!options.allowLoops){rules.push(new import_ast.ForbiddenLoopRule({allowFor:false,allowForOf:true,allowWhile:false,allowDoWhile:false,allowForIn:false,message:"Only for-of loops are allowed (vm.allowLoops is false)"}))}return rules}async function findScriptPolicyIssues(code,options){const validator=new import_ast.JSAstValidator(scriptPolicyRules(options));for(const attempt of PARSE_ATTEMPTS){const result=await validator.validate(attempt.wrap(code),{parseOptions:attempt.parseOptions,preScan:{enabled:false}});if(result.parseError)continue;return result.issues.map(issue=>issue.location&&attempt.lineOffset>0?{...issue,location:{...issue.location,line:issue.location.line-attempt.lineOffset}}:issue)}return[]}var IDENT_RE=/^[A-Za-z_$][A-Za-z0-9_$]*$/;var PROTOTYPE_KEYS=new Set(["__proto__","constructor","prototype"]);var RESERVED_NAMESPACES=new Set(["console","Math","JSON","Object","Array","String","Number","Boolean","Promise","Symbol","Map","Set","WeakMap","WeakSet","Date","Error","RegExp","globalThis","global","window","self","undefined","null","true","false","callTool","getTool","mcpLog","mcpNotify"]);var UNBINDABLE_NAMESPACES=new Set(["break case catch class const continue debugger default delete do else enum export extends finally for","function if import in instanceof new return super switch this throw try typeof var void while with yield","let static implements interface package private protected public await eval arguments NaN Infinity","parallel isNaN isFinite parseInt parseFloat encodeURI encodeURIComponent decodeURI decodeURIComponent","process require module exports Buffer Function AsyncFunction GeneratorFunction Reflect Proxy TypeError","ReferenceError SyntaxError RangeError URIError EvalError AggregateError fetch XMLHttpRequest WebSocket","localStorage sessionStorage indexedDB crypto performance structuredClone AbortController AbortSignal","MessageChannel MessagePort BroadcastChannel TextEncoder TextDecoder Intl setTimeout setInterval","setImmediate clearTimeout clearInterval clearImmediate queueMicrotask WebAssembly Worker SharedWorker","ServiceWorker WeakRef FinalizationRegistry BigInt Atomics SharedArrayBuffer ArrayBuffer DataView","importScripts ShadowRealm Iterator AsyncIterator"].join(" ").split(" "));var UNCALLABLE_METHODS=new Set(["process require module exports Buffer eval Function AsyncFunction GeneratorFunction arguments RegExp","Promise Symbol Proxy Reflect Error TypeError ReferenceError SyntaxError RangeError URIError EvalError","AggregateError fetch XMLHttpRequest WebSocket localStorage sessionStorage indexedDB crypto performance","structuredClone AbortController AbortSignal MessageChannel MessagePort BroadcastChannel TextEncoder","TextDecoder Intl setTimeout setInterval setImmediate clearTimeout clearInterval clearImmediate","queueMicrotask WebAssembly Worker SharedWorker ServiceWorker WeakMap WeakSet WeakRef FinalizationRegistry","Map Set Atomics SharedArrayBuffer importScripts ShadowRealm Iterator AsyncIterator"].join(" ").split(" "));var SANDBOX_TOOL_NAME_RE=/^[a-zA-Z][a-zA-Z0-9:._-]*$/;var MAX_SANDBOX_TOOL_NAME_LENGTH=256;function isBindableNamespace(ns,reservedGlobals){return IDENT_RE.test(ns)&&!PROTOTYPE_KEYS.has(ns)&&!ns.startsWith("__")&&!RESERVED_NAMESPACES.has(ns)&&!UNBINDABLE_NAMESPACES.has(ns)&&!reservedGlobals.has(ns)}function isBindableMethod(ns,method,toolName){return IDENT_RE.test(method)&&!PROTOTYPE_KEYS.has(method)&&!method.startsWith("__")&&!UNCALLABLE_METHODS.has(method)&&toolName===`${ns}.${method}`&&toolName.length<=MAX_SANDBOX_TOOL_NAME_LENGTH&&SANDBOX_TOOL_NAME_RE.test(toolName)}function buildToolNamespaces(tools){const namespaces=Object.create(null);const skipped=[];for(const tool of tools){const name=tool?.name;if(typeof name!=="string"||name.length===0)continue;const dot=name.indexOf(".");if(dot<=0||dot===name.length-1){skipped.push({name,reason:"no-namespace-prefix"});continue}const ns=name.slice(0,dot);const method=name.slice(dot+1);if(!IDENT_RE.test(ns)||!IDENT_RE.test(method)){skipped.push({name,reason:"invalid-identifier"});continue}if(PROTOTYPE_KEYS.has(ns)||PROTOTYPE_KEYS.has(method)){skipped.push({name,reason:"prototype-key"});continue}if(RESERVED_NAMESPACES.has(ns)||UNBINDABLE_NAMESPACES.has(ns)||ns.startsWith("__")){skipped.push({name,reason:"reserved-namespace"});continue}if(!isBindableMethod(ns,method,name)){skipped.push({name,reason:"unsupported-name"});continue}const bucket=namespaces[ns]??(namespaces[ns]=Object.create(null));if(Object.prototype.hasOwnProperty.call(bucket,method)){skipped.push({name,reason:"duplicate-method"});continue}bucket[method]=name}return{namespaces,skipped}}function toSandboxToolNamespaces(namespaces,reservedGlobals=[]){if(!namespaces)return void 0;const reserved=new Set(reservedGlobals);const bindable=Object.create(null);let count=0;for(const ns of Object.keys(namespaces)){if(!isBindableNamespace(ns,reserved))continue;const methods=namespaces[ns];const bucket=Object.create(null);let methodCount=0;for(const method of Object.keys(methods)){const toolName=methods[method];if(typeof toolName!=="string"||!isBindableMethod(ns,method,toolName))continue;bucket[method]=toolName;methodCount+=1}if(methodCount>0){bindable[ns]=bucket;count+=1}}return count>0?bindable:void 0}var import_ast2=require("@enclave-vm/ast");var acorn=__toESM(require("acorn"));var PARSE_OPTIONS={ecmaVersion:"latest",locations:true};var NON_CHILD_KEYS=new Set(["type","loc","start","end","range"]);function isNode(value){return typeof value==="object"&&value!==null&&typeof value.type==="string"}function isAddedByTransform(node){if(node.type==="VariableDeclaration"){const[declaration]=node["declarations"]??[];const id=declaration?.["id"];return typeof id?.["name"]==="string"&&id["name"].startsWith("__iter_")}if(node.type==="IfStatement"){const right=node["test"]?.["right"];return right?.type==="Identifier"&&right["name"]==="__maxIterations"}return false}function parseScript(script){try{return{body:parseBody(script,"script"),offset:0}}catch{try{return{body:parseBody(script,"module"),offset:0}}catch{const wrapped=parseBody(`async function __temp__() {
4
4
  ${script}
5
- }`,"script");const fn=wrapped[0];const block=fn?.["body"];return{body:block?.["body"]??[],offset:1}}}}function parseBody(code,sourceType){const program=acorn.parse(code,{...PARSE_OPTIONS,sourceType});return program["body"]??[]}function treesOf(script){try{const wrap=!(0,import_ast2.isWrappedInMain)(script);const printed=parseBody((0,import_ast2.transformAgentScript)(script,{wrapInMain:wrap}),"script");const{body,offset}=parseScript(script);if(!wrap)return{printed,script:body,offset};const main=printed[0]?.["body"];return{printed:main?.["body"]??[],script:body,offset}}catch{return void 0}}function pairLists(printed,script,depth,out,offset){const kept=printed.filter(node=>!(isNode(node)&&isAddedByTransform(node)));if(kept.length!==script.length)return;kept.forEach((node,index)=>{const own=script[index];if(isNode(node)&&isNode(own))pairNodes(node,own,depth,out,offset)})}function pairNodes(printed,script,depth,out,offset){if(printed.type==="ReturnStatement"&&script.type==="ExpressionStatement"){record(printed,script,depth,out,offset);const argument=printed["argument"];const expression=script["expression"];if(isNode(argument)&&isNode(expression))pairNodes(argument,expression,depth+1,out,offset);return}if(printed.type!==script.type)return;record(printed,script,depth,out,offset);for(const key of Object.keys(printed)){if(NON_CHILD_KEYS.has(key))continue;const printedChild=printed[key];const scriptChild=script[key];if(Array.isArray(printedChild)&&Array.isArray(scriptChild)){pairLists(printedChild,scriptChild,depth+1,out,offset)}else if(isNode(printedChild)&&isNode(scriptChild)){pairNodes(printedChild,scriptChild,depth+1,out,offset)}}}function record(printed,script,depth,out,offset){if(!printed.loc||!script.loc)return;out.push({printedStart:printed.loc.start.line,printedEnd:printed.loc.end.line,scriptLine:script.loc.start.line-offset,depth})}function validatedLineMapper(script){const trees=treesOf(script);if(!trees)return()=>void 0;const pairs=[];pairLists(trees.printed,trees.script,0,pairs,trees.offset);return printedLine=>{const starting=pairs.filter(pair=>pair.printedStart===printedLine);const candidates=starting.length>0?starting:pairs.filter(pair=>pair.printedStart<=printedLine&&printedLine<=pair.printedEnd);const best=candidates.reduce((deepest,pair)=>!deepest||pair.depth>deepest.depth?pair:deepest,void 0);return best&&best.scriptLine>=1?best.scriptLine:void 0}}var ISSUE_LINE_RE=/ \(line (\d+)\)/g;function withScriptLines(message,script){if(!message.includes("(line "))return message;const lineOf=validatedLineMapper(script);return message.replace(ISSUE_LINE_RE,(_match,printed)=>{const line=lineOf(Number(printed));return line===void 0?"":` (line ${line})`})}function toolFailureMessage(error,toolName){if(typeof error==="string"&&error)return error;const message=error?.message;return typeof message==="string"&&message?message:`Tool call failed: ${toolName}`}function toolFailureName(error){const name=error&&typeof error==="object"?error.name:void 0;return typeof name==="string"&&name?name.slice(0,128):"ToolError"}var ITERATION_LIMIT_PREFIX="Maximum iteration limit exceeded";var ITERATION_LIMIT_ERROR={name:"Error",message:`${ITERATION_LIMIT_PREFIX} (${MAX_ITERATIONS_PER_LOOP}). This limit prevents infinite loops.`};var PARSE_FAILURE_PREFIX="Failed to parse AgentScript code: ";var PARSE_POSITION_RE=/\((\d+):(\d+)\)$/;function parseFailureOf(message){const match=PARSE_POSITION_RE.exec(message);const line=match?Number(match[1])-1:0;if(!match||line<1)return{message};const column=Number(match[2]);return{message:`${message.slice(0,match.index)}(${line}:${column})`,location:{line,column}}}var ScriptTooLargeError=class extends Error{code="SCRIPT_TOO_LARGE";scriptLength;maxLength;constructor(scriptLength,maxLength){super(`Script length (${scriptLength} characters) exceeds maximum allowed length (${maxLength} characters). Enable sidecar to handle large data, or reduce script size.`);this.name="ScriptTooLargeError";this.scriptLength=scriptLength;this.maxLength=maxLength}};var EnclaveService=class{vmOptions;sidecarOptions;constructor(config){const all=config.getAll();this.vmOptions=all.resolvedVm;this.sidecarOptions=all.sidecar}async execute(code,environment){const logs=[];if(!this.sidecarOptions.enabled&&this.sidecarOptions.maxScriptLengthWhenDisabled!==null){const maxLength=this.sidecarOptions.maxScriptLengthWhenDisabled;if(code.length>maxLength){throw new ScriptTooLargeError(code.length,maxLength)}}const policyIssues=await findScriptPolicyIssues(code,this.vmOptions);if(policyIssues.length>0){return{success:false,error:{message:`AgentScript validation failed:
6
- ${policyIssues.map(issue=>`${issue.code}${issue.location?` (line ${issue.location.line})`:""}: ${issue.message}`).join("\n")}`,name:"ValidationError",code:"VALIDATION_ERROR",blockedPatterns:[...new Set(policyIssues.map(issue=>issue.code))]},logs,timedOut:false,stats:{duration:0,toolCallCount:0,iterationCount:0}}}const toolFailures=[];const toolHandler=async(toolName,args)=>{try{return await environment.callTool(toolName,args)}catch(error){const code2=error?.code;toolFailures.push({toolName,name:toolFailureName(error),message:toolFailureMessage(error,toolName),...typeof code2==="string"?{code:code2}:{}});throw error}};const sidecar=this.sidecarOptions.enabled?{enabled:true,maxTotalSize:this.sidecarOptions.maxTotalSize,maxReferenceSize:this.sidecarOptions.maxReferenceSize,extractionThreshold:this.sidecarOptions.extractionThreshold,maxResolvedSize:this.sidecarOptions.maxResolvedSize,allowComposites:this.sidecarOptions.allowComposites}:void 0;const{mcpLog,mcpNotify}=environment;const globals={getTool:environment.getTool,...mcpLog?{mcpLog:(level,message,metadata)=>{mcpLog(level,message,metadata);logs.push(`[mcp:${level}] ${message}`)}}:{},...mcpNotify?{mcpNotify:(event,payload)=>{mcpNotify(event,payload);logs.push(`[notify] ${event}`)}}:{}};const{rapidEnumerationThreshold,rapidEnumerationOverrides}=this.vmOptions;const options={timeout:this.vmOptions.timeoutMs,maxToolCalls:maxToolCallsOf(this.vmOptions),maxIterations:MAX_ITERATIONS_PER_LOOP,maxSanitizeDepth:this.vmOptions.maxSanitizeDepth,maxSanitizeProperties:this.vmOptions.maxSanitizeProperties,toolHandler,validate:true,transform:true,sidecar,sanitizeStackTraces:true,allowFunctionsInGlobals:true,globals,toolNamespaces:toSandboxToolNamespaces(environment.toolNamespaces,Object.keys(globals)),doubleVm:{parentValidation:{...rapidEnumerationThreshold!==void 0&&{rapidEnumerationThreshold},...rapidEnumerationOverrides!==void 0&&{rapidEnumerationOverrides}}}};const enclave=createEnclave(options);try{const result=await enclave.run(code);return this.mapEnclaveResult(result,logs,toolFailures,code)}finally{enclave.dispose()}}mapEnclaveResult(result,logs,toolFailures=[],script=""){const stats={duration:result.stats.duration,toolCallCount:result.stats.toolCallCount,iterationCount:result.stats.iterationCount};if(result.success){return{success:true,result:result.value,logs,timedOut:false,stats}}const reportedError=result.error??{name:"Error",message:"Script execution failed"};const toolFailure=[...toolFailures].reverse().find(failure=>failure.message===reportedError.message&&failure.name===reportedError.name);const error=!toolFailure&&reportedError.message?.startsWith(ITERATION_LIMIT_PREFIX)?{...reportedError,...ITERATION_LIMIT_ERROR}:reportedError;if(error.code==="ENCLAVE_ERROR"&&error.message?.startsWith(PARSE_FAILURE_PREFIX)){const{message,location}=parseFailureOf(error.message);return{success:false,error:{message,name:"SyntaxError",code:"SYNTAX_ERROR",...location?{location}:{}},logs,timedOut:false,stats}}if(toolFailure){return{success:false,error:{message:error.message,name:error.name,...toolFailure.code?{code:toolFailure.code}:{},toolName:toolFailure.toolName},logs,timedOut:false,stats}}const timedOut=error.message?.includes("timed out")||error.code==="TIMEOUT";if(error.code==="VALIDATION_ERROR"){const issues=error.data?.issues??[];const blockedPatterns=[...new Set(issues.map(issue=>issue.code).filter(code=>!!code))];return{success:false,error:{message:withScriptLines(error.message,script),name:"ValidationError",code:error.code,...blockedPatterns.length>0?{blockedPatterns}:{}},logs,timedOut:false,stats}}return{success:false,error:{message:error.message,name:error.name,stack:error.stack,code:error.code},logs,timedOut,stats}}};EnclaveService=__decorateClass([(0,import_sdk4.Provider)({name:"codecall:enclave",description:"Executes AgentScript code in a secure enclave",scope:import_sdk4.ProviderScope.GLOBAL})],EnclaveService);function createEnclave(options){try{return new import_core.Enclave(options)}catch(error){if(!options.toolNamespaces||!(error instanceof TypeError)||!error.message.startsWith("Invalid toolNamespaces")){throw error}return new import_core.Enclave({...options,toolNamespaces:void 0})}}var import_sdk5=require("@frontmcp/sdk");var import_lazy_zod2=require("@frontmcp/lazy-zod");var DEFAULT_MIN_RELEVANCE_SCORE=.1;function buildSearchToolDescription(topK){return`Find tools by splitting user request into atomic actions.
5
+ }`,"script");const fn=wrapped[0];const block=fn?.["body"];return{body:block?.["body"]??[],offset:1}}}}function parseBody(code,sourceType){const program=acorn.parse(code,{...PARSE_OPTIONS,sourceType});return program["body"]??[]}function treesOf(script){try{const wrap=!(0,import_ast2.isWrappedInMain)(script);const printed=parseBody((0,import_ast2.transformAgentScript)(script,{wrapInMain:wrap}),"script");const{body,offset}=parseScript(script);if(!wrap)return{printed,script:body,offset};const main=printed[0]?.["body"];return{printed:main?.["body"]??[],script:body,offset}}catch{return void 0}}function pairLists(printed,script,depth,out,offset){const kept=printed.filter(node=>!(isNode(node)&&isAddedByTransform(node)));if(kept.length!==script.length)return;kept.forEach((node,index)=>{const own=script[index];if(isNode(node)&&isNode(own))pairNodes(node,own,depth,out,offset)})}function pairNodes(printed,script,depth,out,offset){if(printed.type==="ReturnStatement"&&script.type==="ExpressionStatement"){record(printed,script,depth,out,offset);const argument=printed["argument"];const expression=script["expression"];if(isNode(argument)&&isNode(expression))pairNodes(argument,expression,depth+1,out,offset);return}if(printed.type!==script.type)return;record(printed,script,depth,out,offset);for(const key of Object.keys(printed)){if(NON_CHILD_KEYS.has(key))continue;const printedChild=printed[key];const scriptChild=script[key];if(Array.isArray(printedChild)&&Array.isArray(scriptChild)){pairLists(printedChild,scriptChild,depth+1,out,offset)}else if(isNode(printedChild)&&isNode(scriptChild)){pairNodes(printedChild,scriptChild,depth+1,out,offset)}}}function record(printed,script,depth,out,offset){if(!printed.loc||!script.loc)return;out.push({printedStart:printed.loc.start.line,printedEnd:printed.loc.end.line,scriptLine:script.loc.start.line-offset,depth})}function validatedLineMapper(script){const trees=treesOf(script);if(!trees)return()=>void 0;const pairs=[];pairLists(trees.printed,trees.script,0,pairs,trees.offset);return printedLine=>{const starting=pairs.filter(pair=>pair.printedStart===printedLine);const candidates=starting.length>0?starting:pairs.filter(pair=>pair.printedStart<=printedLine&&printedLine<=pair.printedEnd);const best=candidates.reduce((deepest,pair)=>!deepest||pair.depth>deepest.depth?pair:deepest,void 0);return best&&best.scriptLine>=1?best.scriptLine:void 0}}var ISSUE_LINE_RE=/ \(line (\d+)\)/g;function withScriptLines(message,script){if(!message.includes("(line "))return message;const lineOf=validatedLineMapper(script);return message.replace(ISSUE_LINE_RE,(_match,printed)=>{const line=lineOf(Number(printed));return line===void 0?"":` (line ${line})`})}var SCRIPT_CONSOLE_LINES_PER_SECOND=50;var WINDOW_MS=1e3;var LOGGER_LEVEL={log:"info",info:"info",warn:"warn",error:"error",debug:"debug"};var ScriptConsoleLog=class{constructor(logger,linesPerSecond=SCRIPT_CONSOLE_LINES_PER_SECOND,now=Date.now){this.logger=logger;this.linesPerSecond=linesPerSecond;this.now=now}logger;linesPerSecond;now;windowStart=Number.NEGATIVE_INFINITY;written=0;dropped=0;write=(level,message)=>{const now=this.now();if(now-this.windowStart>=WINDOW_MS){this.windowStart=now;this.written=0;this.dropped=0}if(this.written>=this.linesPerSecond){this.dropped++;if(this.dropped===1){this.logger.warn(`Dropping script console output: more than ${this.linesPerSecond} lines a second`)}return}this.written++;this.logger[LOGGER_LEVEL[level]](message)}};function toolFailureMessage(error,toolName){if(typeof error==="string"&&error)return error;const message=error?.message;return typeof message==="string"&&message?message:`Tool call failed: ${toolName}`}function toolFailureName(error){const name=error&&typeof error==="object"?error.name:void 0;return typeof name==="string"&&name?name.slice(0,128):"ToolError"}var ITERATION_LIMIT_PREFIX="Maximum iteration limit exceeded";var ITERATION_LIMIT_ERROR={name:"Error",message:`${ITERATION_LIMIT_PREFIX} (${MAX_ITERATIONS_PER_LOOP}). This limit prevents infinite loops.`};var PARSE_FAILURE_PREFIX="Failed to parse AgentScript code: ";var PARSE_POSITION_RE=/\((\d+):(\d+)\)$/;function parseFailureOf(message){const match=PARSE_POSITION_RE.exec(message);const line=match?Number(match[1])-1:0;if(!match||line<1)return{message};const column=Number(match[2]);return{message:`${message.slice(0,match.index)}(${line}:${column})`,location:{line,column}}}var ScriptTooLargeError=class extends Error{code="SCRIPT_TOO_LARGE";scriptLength;maxLength;constructor(scriptLength,maxLength){super(`Script length (${scriptLength} characters) exceeds maximum allowed length (${maxLength} characters). Enable sidecar to handle large data, or reduce script size.`);this.name="ScriptTooLargeError";this.scriptLength=scriptLength;this.maxLength=maxLength}};var EnclaveService=class{vmOptions;sidecarOptions;consoleHandler;constructor(config,scriptLogger){const all=config.getAll();this.vmOptions=all.resolvedVm;this.sidecarOptions=all.sidecar;if(this.vmOptions.allowConsole&&scriptLogger){this.consoleHandler=new ScriptConsoleLog(scriptLogger).write}}async execute(code,environment){const logs=[];if(!this.sidecarOptions.enabled&&this.sidecarOptions.maxScriptLengthWhenDisabled!==null){const maxLength=this.sidecarOptions.maxScriptLengthWhenDisabled;if(code.length>maxLength){throw new ScriptTooLargeError(code.length,maxLength)}}const policyIssues=await findScriptPolicyIssues(code,{...this.vmOptions,allowConsole:this.consoleHandler!==void 0});if(policyIssues.length>0){return{success:false,error:{message:`AgentScript validation failed:
6
+ ${policyIssues.map(issue=>`${issue.code}${issue.location?` (line ${issue.location.line})`:""}: ${issue.message}`).join("\n")}`,name:"ValidationError",code:"VALIDATION_ERROR",blockedPatterns:[...new Set(policyIssues.map(issue=>issue.code))]},logs,timedOut:false,stats:{duration:0,toolCallCount:0,iterationCount:0}}}const toolFailures=[];const toolHandler=async(toolName,args)=>{try{return await environment.callTool(toolName,args)}catch(error){const code2=error?.code;toolFailures.push({toolName,name:toolFailureName(error),message:toolFailureMessage(error,toolName),...typeof code2==="string"?{code:code2}:{}});throw error}};const sidecar=this.sidecarOptions.enabled?{enabled:true,maxTotalSize:this.sidecarOptions.maxTotalSize,maxReferenceSize:this.sidecarOptions.maxReferenceSize,extractionThreshold:this.sidecarOptions.extractionThreshold,maxResolvedSize:this.sidecarOptions.maxResolvedSize,allowComposites:this.sidecarOptions.allowComposites}:void 0;const{mcpLog,mcpNotify}=environment;const globals={getTool:environment.getTool,...mcpLog?{mcpLog:(level,message,metadata)=>{mcpLog(level,message,metadata);logs.push(`[mcp:${level}] ${message}`)}}:{},...mcpNotify?{mcpNotify:(event,payload)=>{mcpNotify(event,payload);logs.push(`[notify] ${event}`)}}:{}};const{rapidEnumerationThreshold,rapidEnumerationOverrides}=this.vmOptions;const options={timeout:this.vmOptions.timeoutMs,maxToolCalls:maxToolCallsOf(this.vmOptions),maxIterations:MAX_ITERATIONS_PER_LOOP,maxSanitizeDepth:this.vmOptions.maxSanitizeDepth,maxSanitizeProperties:this.vmOptions.maxSanitizeProperties,toolHandler,validate:true,transform:true,sidecar,sanitizeStackTraces:true,allowFunctionsInGlobals:true,consoleHandler:this.consoleHandler,globals,toolNamespaces:toSandboxToolNamespaces(environment.toolNamespaces,Object.keys(globals)),doubleVm:{parentValidation:{...rapidEnumerationThreshold!==void 0&&{rapidEnumerationThreshold},...rapidEnumerationOverrides!==void 0&&{rapidEnumerationOverrides}}}};const enclave=createEnclave(options);try{const result=await enclave.run(code);return this.mapEnclaveResult(result,logs,toolFailures,code)}finally{enclave.dispose()}}mapEnclaveResult(result,logs,toolFailures=[],script=""){const stats={duration:result.stats.duration,toolCallCount:result.stats.toolCallCount,iterationCount:result.stats.iterationCount};if(result.success){return{success:true,result:result.value,logs,timedOut:false,stats}}const reportedError=result.error??{name:"Error",message:"Script execution failed"};const toolFailure=[...toolFailures].reverse().find(failure=>failure.message===reportedError.message&&failure.name===reportedError.name);const error=!toolFailure&&reportedError.message?.startsWith(ITERATION_LIMIT_PREFIX)?{...reportedError,...ITERATION_LIMIT_ERROR}:reportedError;if(error.code==="ENCLAVE_ERROR"&&error.message?.startsWith(PARSE_FAILURE_PREFIX)){const{message,location}=parseFailureOf(error.message);return{success:false,error:{message,name:"SyntaxError",code:"SYNTAX_ERROR",...location?{location}:{}},logs,timedOut:false,stats}}if(toolFailure){return{success:false,error:{message:error.message,name:error.name,...toolFailure.code?{code:toolFailure.code}:{},toolName:toolFailure.toolName},logs,timedOut:false,stats}}const timedOut=error.message?.includes("timed out")||error.code==="TIMEOUT";if(error.code==="VALIDATION_ERROR"){const issues=error.data?.issues??[];const blockedPatterns=[...new Set(issues.map(issue=>issue.code).filter(code=>!!code))];return{success:false,error:{message:withScriptLines(error.message,script),name:"ValidationError",code:error.code,...blockedPatterns.length>0?{blockedPatterns}:{}},logs,timedOut:false,stats}}return{success:false,error:{message:error.message,name:error.name,stack:error.stack,code:error.code},logs,timedOut,stats}}};EnclaveService=__decorateClass([(0,import_sdk4.Provider)({name:"codecall:enclave",description:"Executes AgentScript code in a secure enclave",scope:import_sdk4.ProviderScope.GLOBAL})],EnclaveService);function createEnclave(options){try{return new import_core.Enclave(options)}catch(error){if(!options.toolNamespaces||!(error instanceof TypeError)||!error.message.startsWith("Invalid toolNamespaces")){throw error}return new import_core.Enclave({...options,toolNamespaces:void 0})}}var import_sdk5=require("@frontmcp/sdk");var import_lazy_zod2=require("@frontmcp/lazy-zod");var DEFAULT_MIN_RELEVANCE_SCORE=.1;function buildSearchToolDescription(topK){return`Find tools by splitting user request into atomic actions.
7
7
 
8
8
  DECOMPOSE: "delete users and send email" \u2192 queries: ["delete user", "send email"]
9
9
  DECOMPOSE: "get order and refund" \u2192 queries: ["get order", "calculate refund"]
@@ -46,7 +46,7 @@ INPUT:
46
46
 
47
47
  OUTPUT: Deduplicated knowledge skill list with description + tags. To read the body, follow up with describe(skillName) or the skill:// resource URI.
48
48
 
49
- FLOW: searchKnowledge \u2192 describe (for body) \u2192 continue with searchSkills`;var searchKnowledgeToolInputSchema={queries:import_lazy_zod4.z.array(import_lazy_zod4.z.string().min(2).max(256)).min(1).max(10).describe("Atomic context queries."),tags:import_lazy_zod4.z.array(import_lazy_zod4.z.string().min(1).max(64)).max(16).optional().describe("Filter to skills with any of these tags"),excludeSkillNames:import_lazy_zod4.z.array(import_lazy_zod4.z.string()).max(50).optional().describe("Skip already-loaded knowledge skill names"),topK:import_lazy_zod4.z.number().int().positive().max(50).optional().default(5).describe("Results per query (default 5)"),minRelevanceScore:import_lazy_zod4.z.number().min(0).max(1).optional().default(.1).describe("Minimum relevance threshold (default 0.1)")};var knowledgeHitSchema=import_lazy_zod4.z.object({name:import_lazy_zod4.z.string().describe("Skill name"),description:import_lazy_zod4.z.string().describe("Short description of what the knowledge covers"),tags:import_lazy_zod4.z.array(import_lazy_zod4.z.string()).describe("Tags carried by the skill"),relevanceScore:import_lazy_zod4.z.number().min(0).max(1).describe("Match score (0-1)"),matchedQueries:import_lazy_zod4.z.array(import_lazy_zod4.z.string()).describe("Which queries matched this knowledge"),source:import_lazy_zod4.z.enum(["local","external"]).describe("Where the skill was loaded from")});var searchKnowledgeToolOutputSchema=import_lazy_zod4.z.object({knowledge:import_lazy_zod4.z.array(knowledgeHitSchema).describe("Deduplicated knowledge skills, sorted by relevance"),warnings:import_lazy_zod4.z.array(import_lazy_zod4.z.object({type:import_lazy_zod4.z.enum(["no_results","low_relevance","excluded_skill_not_found"]).describe("Warning type"),message:import_lazy_zod4.z.string().describe("Warning message"),affectedSkills:import_lazy_zod4.z.array(import_lazy_zod4.z.string()).optional().describe("Affected skill names")})).describe("Search warnings"),totalKnowledgeSkills:import_lazy_zod4.z.number().int().nonnegative().describe("Total knowledge-only skills available")});var SearchKnowledgeTool=class extends import_sdk7.ToolContext{async execute(input){const{queries,tags,excludeSkillNames=[],topK=5,minRelevanceScore=.1}=input;const skillRegistry=this.scope.skills;const knowledgeSkills=await(0,import_sdk7.filterServableSkills)(this.scope,skillRegistry.getKnowledgeOnlySkills());const knowledgeSet=new Set(knowledgeSkills.map(s=>s.name));const totalKnowledgeSkills=knowledgeSkills.length;const warnings=[];const nonExistentExcluded=excludeSkillNames.filter(n=>!knowledgeSet.has(n));if(nonExistentExcluded.length>0){warnings.push({type:"excluded_skill_not_found",message:`Excluded knowledge skills not found: ${nonExistentExcluded.join(", ")}`,affectedSkills:nonExistentExcluded})}const matches=new Map;let lowRelevanceCount=0;const excludedSet=new Set(excludeSkillNames);const perQueryResults=await Promise.all(queries.map(query=>skillRegistry.search(query,{topK,tags,minScore:minRelevanceScore}).then(results=>({query,results}))));for(const{query,results}of perQueryResults){for(const result of results){const name=result.metadata.name;if(!knowledgeSet.has(name))continue;if(excludedSet.has(name))continue;if(result.score<minRelevanceScore){lowRelevanceCount++;continue}const existing=matches.get(name);if(existing){existing.matchedQueries.push(query);existing.relevanceScore=Math.max(existing.relevanceScore,result.score)}else{matches.set(name,{name,description:result.metadata.description,tags:result.metadata.tags??[],relevanceScore:result.score,matchedQueries:[query],source:result.source})}}}const knowledge=Array.from(matches.values()).sort((a,b)=>b.relevanceScore-a.relevanceScore);if(knowledge.length===0){warnings.push({type:"no_results",message:`No knowledge skills found for queries: ${queries.join(", ")}${tags?.length?` with tags: ${tags.join(", ")}`:""}`})}if(lowRelevanceCount>0&&knowledge.length>0){warnings.push({type:"low_relevance",message:`${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`})}return{knowledge,warnings,totalKnowledgeSkills}}};SearchKnowledgeTool=__decorateClass([(0,import_sdk7.Tool)({name:"codecall:searchKnowledge",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:searchKnowledgeToolDescription,inputSchema:searchKnowledgeToolInputSchema,outputSchema:searchKnowledgeToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],SearchKnowledgeTool);var import_lazy_zod6=require("@frontmcp/lazy-zod");var import_sdk8=require("@frontmcp/sdk");var INTENT_PATTERNS={create:/^(create|add|new|insert|make|append|register|generate|produce|build|construct|provision|instantiate|define|compose|draft)/i,delete:/^(delete|remove|destroy|drop|erase|clear|purge|discard|eliminate|unbind|unregister)/i,get:/^(get|fetch|retrieve|read|obtain|load|pull|access|grab|receive)/i,update:/^(update|edit|modify|change|patch|set|alter|revise|adjust|amend|correct|fix|refresh|sync|upgrade|downgrade)/i,list:/^(list|all|index|enumerate|show|display|view|browse|scan|inventory)/i,search:/^(search|find|query|lookup|locate|discover|explore|seek|match|filter)/i};function detectToolIntent(toolName,description){const parts=toolName.split(":");const actionPart=parts.length>1?parts[parts.length-1]:toolName;for(const[intent,pattern]of Object.entries(INTENT_PATTERNS)){if(pattern.test(actionPart)){return intent}}if(description){const descLower=description.toLowerCase();if(/creates?\s|adding\s|inserts?/i.test(descLower))return"create";if(/deletes?\s|removes?\s|destroys?/i.test(descLower))return"delete";if(/gets?\s|fetche?s?\s|retrieves?/i.test(descLower))return"get";if(/updates?\s|modif(?:y|ies)\s|edits?/i.test(descLower))return"update";if(/lists?\s|shows?\s|displays?/i.test(descLower))return"list";if(/search(?:es)?\s|find(?:s)?\s|quer(?:y|ies)/i.test(descLower))return"search"}return"unknown"}function generateBasicExample(toolName,inputSchema){const params=generateSampleParams(inputSchema);const paramsStr=params?JSON.stringify(params,null,2):"{}";return{description:`Basic usage of ${toolName}`,code:`const result = await callTool('${toolName}', ${paramsStr});
49
+ FLOW: searchKnowledge \u2192 describe (for body) \u2192 continue with searchSkills`;var searchKnowledgeToolInputSchema={queries:import_lazy_zod4.z.array(import_lazy_zod4.z.string().min(2).max(256)).min(1).max(10).describe("Atomic context queries."),tags:import_lazy_zod4.z.array(import_lazy_zod4.z.string().min(1).max(64)).max(16).optional().describe("Filter to skills with any of these tags"),excludeSkillNames:import_lazy_zod4.z.array(import_lazy_zod4.z.string()).max(50).optional().describe("Skip already-loaded knowledge skill names"),topK:import_lazy_zod4.z.number().int().positive().max(50).optional().default(5).describe("Results per query (default 5)"),minRelevanceScore:import_lazy_zod4.z.number().min(0).max(1).optional().default(.1).describe("Minimum relevance threshold (default 0.1)")};var knowledgeHitSchema=import_lazy_zod4.z.object({name:import_lazy_zod4.z.string().describe("Skill name"),description:import_lazy_zod4.z.string().describe("Short description of what the knowledge covers"),tags:import_lazy_zod4.z.array(import_lazy_zod4.z.string()).describe("Tags carried by the skill"),relevanceScore:import_lazy_zod4.z.number().min(0).max(1).describe("Match score (0-1)"),matchedQueries:import_lazy_zod4.z.array(import_lazy_zod4.z.string()).describe("Which queries matched this knowledge"),source:import_lazy_zod4.z.enum(["local","external"]).describe("Where the skill was loaded from")});var searchKnowledgeToolOutputSchema=import_lazy_zod4.z.object({knowledge:import_lazy_zod4.z.array(knowledgeHitSchema).describe("Deduplicated knowledge skills, sorted by relevance"),warnings:import_lazy_zod4.z.array(import_lazy_zod4.z.object({type:import_lazy_zod4.z.enum(["no_results","low_relevance","excluded_skill_not_found"]).describe("Warning type"),message:import_lazy_zod4.z.string().describe("Warning message"),affectedSkills:import_lazy_zod4.z.array(import_lazy_zod4.z.string()).optional().describe("Affected skill names")})).describe("Search warnings"),totalKnowledgeSkills:import_lazy_zod4.z.number().int().nonnegative().describe("Total knowledge-only skills available")});var SearchKnowledgeTool=class extends import_sdk7.ToolContext{async execute(input){const{queries,tags,excludeSkillNames=[],topK=5,minRelevanceScore=.1}=input;const skillRegistry=this.scope.skills;const knowledgeSkills=await(0,import_sdk7.filterServableSkills)(this.scope,skillRegistry.getKnowledgeOnlySkills());const knowledgeSet=new Set(knowledgeSkills.map(s=>s.name));const totalKnowledgeSkills=knowledgeSkills.length;const warnings=[];const nonExistentExcluded=excludeSkillNames.filter(n=>!knowledgeSet.has(n));if(nonExistentExcluded.length>0){warnings.push({type:"excluded_skill_not_found",message:`Excluded knowledge skills not found: ${nonExistentExcluded.join(", ")}`,affectedSkills:nonExistentExcluded})}const matches=new Map;let lowRelevanceCount=0;const excludedSet=new Set(excludeSkillNames);const perQueryResults=await Promise.all(queries.map(query=>skillRegistry.search(query,{topK,tags,minScore:minRelevanceScore}).then(results=>({query,results}))));for(const{query,results}of perQueryResults){for(const result of results){const name=result.metadata.name;if(!knowledgeSet.has(name))continue;if(excludedSet.has(name))continue;if(result.score<minRelevanceScore){lowRelevanceCount++;continue}const existing=matches.get(name);if(existing){existing.matchedQueries.push(query);existing.relevanceScore=Math.max(existing.relevanceScore,result.score)}else{matches.set(name,{name,description:result.metadata.description,tags:result.metadata.tags??[],relevanceScore:result.score,matchedQueries:[query],source:result.source})}}}const knowledge=Array.from(matches.values()).sort((a,b)=>b.relevanceScore-a.relevanceScore);if(knowledge.length===0){warnings.push({type:"no_results",message:`No knowledge skills found for queries: ${queries.join(", ")}${tags?.length?` with tags: ${tags.join(", ")}`:""}`})}if(lowRelevanceCount>0&&knowledge.length>0){warnings.push({type:"low_relevance",message:`${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`})}return{knowledge,warnings,totalKnowledgeSkills}}};SearchKnowledgeTool=__decorateClass([(0,import_sdk7.Tool)({name:"codecall:searchKnowledge",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:searchKnowledgeToolDescription,inputSchema:searchKnowledgeToolInputSchema,outputSchema:searchKnowledgeToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],SearchKnowledgeTool);var import_lazy_zod6=require("@frontmcp/lazy-zod");var import_sdk9=require("@frontmcp/sdk");var INTENT_PATTERNS={create:/^(create|add|new|insert|make|append|register|generate|produce|build|construct|provision|instantiate|define|compose|draft)/i,delete:/^(delete|remove|destroy|drop|erase|clear|purge|discard|eliminate|unbind|unregister)/i,get:/^(get|fetch|retrieve|read|obtain|load|pull|access|grab|receive)/i,update:/^(update|edit|modify|change|patch|set|alter|revise|adjust|amend|correct|fix|refresh|sync|upgrade|downgrade)/i,list:/^(list|all|index|enumerate|show|display|view|browse|scan|inventory)/i,search:/^(search|find|query|lookup|locate|discover|explore|seek|match|filter)/i};function detectToolIntent(toolName,description){const parts=toolName.split(":");const actionPart=parts.length>1?parts[parts.length-1]:toolName;for(const[intent,pattern]of Object.entries(INTENT_PATTERNS)){if(pattern.test(actionPart)){return intent}}if(description){const descLower=description.toLowerCase();if(/creates?\s|adding\s|inserts?/i.test(descLower))return"create";if(/deletes?\s|removes?\s|destroys?/i.test(descLower))return"delete";if(/gets?\s|fetche?s?\s|retrieves?/i.test(descLower))return"get";if(/updates?\s|modif(?:y|ies)\s|edits?/i.test(descLower))return"update";if(/lists?\s|shows?\s|displays?/i.test(descLower))return"list";if(/search(?:es)?\s|find(?:s)?\s|quer(?:y|ies)/i.test(descLower))return"search"}return"unknown"}function generateBasicExample(toolName,inputSchema){const params=generateSampleParams(inputSchema);const paramsStr=params?JSON.stringify(params,null,2):"{}";return{description:`Basic usage of ${toolName}`,code:`const result = await callTool('${toolName}', ${paramsStr});
50
50
  return result;`}}function generateSampleParams(schema){if(!schema||schema.type!=="object"||!schema.properties){return null}const params={};const required=new Set(schema.required||[]);for(const[key,propSchema]of Object.entries(schema.properties)){if(typeof propSchema==="boolean")continue;if(!required.has(key))continue;params[key]=getSampleValue(propSchema,key)}return Object.keys(params).length>0?params:null}function fitString(schema,value){let fitted=value;if(schema.maxLength!==void 0&&fitted.length>schema.maxLength){fitted=fitted.slice(0,Math.max(0,schema.maxLength))}if(schema.minLength!==void 0&&fitted.length<schema.minLength){fitted=fitted.padEnd(schema.minLength,"x")}return fitted}function isFreeTextString(schema){return schema?.type==="string"&&schema.enum===void 0&&schema.const===void 0&&schema.default===void 0&&schema.pattern===void 0&&schema.format===void 0}function acceptsNumber(schema,value){if(schema.const!==void 0)return schema.const===value;if(schema.enum!==void 0)return schema.enum.includes(value);if(schema.minimum!==void 0&&value<schema.minimum)return false;if(schema.maximum!==void 0&&value>schema.maximum)return false;return true}function pickNumber(schema,preferred){const accepted=preferred.find(value=>acceptsNumber(schema,value));if(accepted!==void 0)return accepted;const named=[schema.const,schema.enum?.[0],schema.minimum,schema.maximum].find(value=>typeof value==="number"&&acceptsNumber(schema,value));return named}function formatInlineArgs(args){const entries=Object.entries(args).map(([key,value])=>{const name=/^[A-Za-z_$][\w$]*$/.test(key)?key:JSON.stringify(key);const plain=typeof value==="string"&&[...value].every(ch=>ch!=="'"&&ch!=="\\"&&ch>=" ");const literal=plain?`'${value}'`:JSON.stringify(value);return`${name}: ${literal}`});return entries.length>0?`{ ${entries.join(", ")} }`:"{}"}function getSampleValue(schema,key){if(schema.default!==void 0){return schema.default}if(schema.enum&&schema.enum.length>0){return schema.enum[0]}if(schema.const!==void 0){return schema.const}const type=Array.isArray(schema.type)?schema.type[0]:schema.type;switch(type){case"string":if(key.toLowerCase().includes("id"))return fitString(schema,"abc123");if(key.toLowerCase().includes("email"))return fitString(schema,"user@example.com");if(key.toLowerCase().includes("name"))return fitString(schema,"Example");if(key.toLowerCase().includes("url"))return fitString(schema,"https://example.com");return fitString(schema,"string");case"number":case"integer":if(key.toLowerCase().includes("limit"))return 10;if(key.toLowerCase().includes("offset"))return 0;if(key.toLowerCase().includes("page"))return 1;return 0;case"boolean":return true;case"array":return[];case"object":return{};default:return null}}var PAGINATION_PROPERTIES=["limit","offset","page","pagesize","cursor"];function isPaginationProperty(name){return PAGINATION_PROPERTIES.includes(name.toLowerCase())}function hasPaginationParams(schema){if(!schema||schema.type!=="object"||!schema.properties){return false}return Object.keys(schema.properties).some(isPaginationProperty)}function inputProperties(schema){if(!schema||schema.type!=="object"||!schema.properties){return{}}const properties={};for(const[key,propSchema]of Object.entries(schema.properties)){if(typeof propSchema!=="boolean")properties[key]=propSchema}return properties}function buildExampleArgs(schema,keys,values={}){const properties=inputProperties(schema);const args={};for(const key of[...keys,...schema?.required??[]]){const propSchema=properties[key];if(!propSchema||key in args)continue;args[key]=key in values?values[key]:getSampleValue(propSchema,key)}return args}function formatExampleArgs(args){return Object.keys(args).length>0?JSON.stringify(args,null,2):"{}"}function getFilterProperties(schema){if(!schema||schema.type!=="object"||!schema.properties){return[]}return Object.keys(schema.properties).filter(p=>p.toLowerCase().includes("filter")||p.toLowerCase().includes("query")||p.toLowerCase().includes("search")||p.toLowerCase()==="status"||p.toLowerCase()==="type"||p.toLowerCase()==="role")}function generatePaginationExample(toolName,inputSchema){const description=`Pagination example for ${toolName}`;const props=Object.keys(inputProperties(inputSchema));const limitKey=props.find(p=>p.toLowerCase()==="limit");const offsetKey=props.find(p=>p.toLowerCase()==="offset");if(limitKey&&offsetKey){const properties=inputProperties(inputSchema);const limit=pickNumber(properties[limitKey],[10]);const firstOffset=pickNumber(properties[offsetKey],[0]);const values={};if(limit!==void 0)values[limitKey]=limit;if(firstOffset!==void 0)values[offsetKey]=firstOffset;const firstPage=buildExampleArgs(inputSchema,[limitKey,offsetKey],values);const nextOffset=[limit??10,10,20,...properties[offsetKey].enum??[]].find(value=>typeof value==="number"&&value!==firstPage[offsetKey]&&acceptsNumber(properties[offsetKey],value));if(nextOffset!==void 0){const secondPage={...firstPage,[offsetKey]:nextOffset};return{description,code:`// Fetch first page
51
51
  const page1 = await callTool('${toolName}', ${formatExampleArgs(firstPage)});
52
52
 
@@ -68,14 +68,14 @@ return updated;`}}return{description:`Update ${entity}`,code:`const updated = aw
68
68
  return updated;`}}function generateDeleteExample(toolName,inputSchema){const entity=extractEntityName(toolName);const idParam=findIdParameter(inputSchema);if(idParam){return{description:`Delete ${entity} by ${idParam}`,code:`const result = await callTool('${toolName}', ${formatInlineArgs(idArgs(inputSchema,idParam))});
69
69
  return result;`}}const params=generateSampleParams(inputSchema);const paramsStr=params?JSON.stringify(params,null,2):"{ /* identifier */ }";return{description:`Delete ${entity}`,code:`const result = await callTool('${toolName}', ${paramsStr});
70
70
  return result;`}}function generateSearchExample(toolName,inputSchema){const entity=extractEntityName(toolName);const searchParam=findQueryParameter(inputSchema)??getFilterProperties(inputSchema)[0];const searchSchema=searchParam?inputProperties(inputSchema)[searchParam]:void 0;const required=new Set(inputSchema?.required??[]);const unfillable=searchSchema?.type==="string"&&(searchSchema.pattern!==void 0||searchSchema.format!==void 0)&&searchSchema.enum===void 0&&searchSchema.const===void 0&&searchSchema.default===void 0&&!required.has(searchParam??"");const args=searchParam&&!unfillable?buildExampleArgs(inputSchema,[searchParam],isFreeTextString(searchSchema)&&searchSchema?{[searchParam]:fitString(searchSchema,"search term")}:{}):buildExampleArgs(inputSchema,[]);return{description:`Search for ${entity}s`,code:`const results = await callTool('${toolName}', ${formatExampleArgs(args)});
71
- return results.items || results;`}}function findIdParameter(schema){if(!schema||schema.type!=="object"||!schema.properties){return null}const props=Object.keys(schema.properties);const required=new Set(schema.required||[]);const idPatterns=["id","Id","ID","_id","uuid","key"];for(const pattern of idPatterns){const found=props.find(p=>(p===pattern||p.endsWith(pattern))&&required.has(p));if(found)return found}for(const pattern of idPatterns){const found=props.find(p=>p===pattern||p.endsWith(pattern));if(found)return found}return null}function findQueryParameter(schema){if(!schema||schema.type!=="object"||!schema.properties){return null}const props=Object.keys(schema.properties);const queryPatterns=["query","search","q","term","keyword","filter"];for(const pattern of queryPatterns){const found=props.find(p=>p.toLowerCase()===pattern||p.toLowerCase().includes(pattern));if(found)return found}return null}function generateUpdateFields(schema){if(!schema||schema.type!=="object"||!schema.properties){return null}const fields={};const idPatterns=["id","Id","ID","_id","uuid","key"];for(const[key,propSchema]of Object.entries(schema.properties)){if(typeof propSchema==="boolean")continue;const isIdField=idPatterns.some(p=>key===p||key.endsWith(p));if(isIdField)continue;if(Object.keys(fields).length<2){fields[key]=getSampleValue(propSchema,key)}}return Object.keys(fields).length>0?fields:null}function generateSmartExample(toolName,inputSchema,description){const intent=detectToolIntent(toolName,description);switch(intent){case"create":return generateCreateExample(toolName,inputSchema);case"get":return generateGetExample(toolName,inputSchema);case"list":return hasPaginationParams(inputSchema)?generatePaginationExample(toolName,inputSchema):generateListExample(toolName,inputSchema);case"update":return generateUpdateExample(toolName,inputSchema);case"delete":return generateDeleteExample(toolName,inputSchema);case"search":return generateSearchExample(toolName,inputSchema);default:return generateBasicExample(toolName,inputSchema)}}function toPlainJson(value){try{const serialized=JSON.stringify(value);if(serialized===void 0)return void 0;return JSON.parse(serialized)}catch{return void 0}}function extractResultFromCallToolResult(mcpResult){if(mcpResult.isError){const errorContent=mcpResult.content?.[0];if(errorContent&&"text"in errorContent){throw new Error(errorContent.text)}throw new Error("Tool execution failed")}const content=mcpResult.content;if(!content||content.length===0){return void 0}if(content.length===1&&content[0].type==="text"){try{return JSON.parse(content[0].text)}catch{return content[0].text}}return toPlainJson(content)}var import_lazy_zod5=require("@frontmcp/lazy-zod");var import_protocol=require("@frontmcp/protocol");var describeToolDescription=`Get input/output schemas for tools from search results.
71
+ return results.items || results;`}}function findIdParameter(schema){if(!schema||schema.type!=="object"||!schema.properties){return null}const props=Object.keys(schema.properties);const required=new Set(schema.required||[]);const idPatterns=["id","Id","ID","_id","uuid","key"];for(const pattern of idPatterns){const found=props.find(p=>(p===pattern||p.endsWith(pattern))&&required.has(p));if(found)return found}for(const pattern of idPatterns){const found=props.find(p=>p===pattern||p.endsWith(pattern));if(found)return found}return null}function findQueryParameter(schema){if(!schema||schema.type!=="object"||!schema.properties){return null}const props=Object.keys(schema.properties);const queryPatterns=["query","search","q","term","keyword","filter"];for(const pattern of queryPatterns){const found=props.find(p=>p.toLowerCase()===pattern||p.toLowerCase().includes(pattern));if(found)return found}return null}function generateUpdateFields(schema){if(!schema||schema.type!=="object"||!schema.properties){return null}const fields={};const idPatterns=["id","Id","ID","_id","uuid","key"];for(const[key,propSchema]of Object.entries(schema.properties)){if(typeof propSchema==="boolean")continue;const isIdField=idPatterns.some(p=>key===p||key.endsWith(p));if(isIdField)continue;if(Object.keys(fields).length<2){fields[key]=getSampleValue(propSchema,key)}}return Object.keys(fields).length>0?fields:null}function generateSmartExample(toolName,inputSchema,description){const intent=detectToolIntent(toolName,description);switch(intent){case"create":return generateCreateExample(toolName,inputSchema);case"get":return generateGetExample(toolName,inputSchema);case"list":return hasPaginationParams(inputSchema)?generatePaginationExample(toolName,inputSchema):generateListExample(toolName,inputSchema);case"update":return generateUpdateExample(toolName,inputSchema);case"delete":return generateDeleteExample(toolName,inputSchema);case"search":return generateSearchExample(toolName,inputSchema);default:return generateBasicExample(toolName,inputSchema)}}var import_sdk8=require("@frontmcp/sdk");function toPlainJson(value){try{const serialized=JSON.stringify(value);if(serialized===void 0)return void 0;return JSON.parse(serialized)}catch{return void 0}}function extractResultFromCallToolResult(mcpResult){if(mcpResult.isError){const errorContent=mcpResult.content?.[0];const message=errorContent&&"text"in errorContent?errorContent.text:"Tool execution failed";const code=mcpResult._meta?.["code"];throw new import_sdk8.PublicMcpError(message,typeof code==="string"?code:"TOOL_ERROR_RESULT")}const content=mcpResult.content;if(!content||content.length===0){return void 0}if(content.length===1&&content[0].type==="text"){try{return JSON.parse(content[0].text)}catch{return content[0].text}}return toPlainJson(content)}var import_lazy_zod5=require("@frontmcp/lazy-zod");var import_protocol=require("@frontmcp/protocol");var describeToolDescription=`Get input/output schemas for tools from search results.
72
72
 
73
73
  INPUT: toolNames: string[] - tool names from search, at most the server's maxDefinitions (8 unless configured) per call
74
74
  OUTPUT per tool: inputSchema (JSON Schema), outputSchema (JSON Schema), usageExamples (up to 5 callTool examples)
75
75
 
76
76
  IMPORTANT: If notFound array is non-empty \u2192 re-search with corrected queries.
77
- FLOW: search \u2192 describe \u2192 execute/invoke`;var describeToolInputSchema={toolNames:import_lazy_zod5.z.array(import_lazy_zod5.z.string()).min(1).superRefine((toolNames,ctx)=>{const seen=new Set;const duplicates=new Set;for(const name of toolNames){if(seen.has(name)){duplicates.add(name)}seen.add(name)}if(duplicates.size>0){ctx.addIssue({code:import_lazy_zod5.z.ZodIssueCode.custom,message:`Duplicate tool names are not allowed: ${Array.from(duplicates).join(", ")}`})}}).describe('Array of unique tool names (from codecall:search results) to fetch their detailed schemas and usage examples. Example: ["users:list", "billing:getInvoice"]')};var describeToolOutputSchema=import_lazy_zod5.z.object({tools:import_lazy_zod5.z.array(import_lazy_zod5.z.object({name:import_lazy_zod5.z.string().describe("Tool name to be used in callTool() within codecall:execute scripts"),appId:import_lazy_zod5.z.string().describe("The app ID this tool belongs to"),description:import_lazy_zod5.z.string().describe("Detailed description of what this tool does"),inputSchema:import_lazy_zod5.z.record(import_lazy_zod5.z.string(),import_lazy_zod5.z.unknown()).nullable().describe("JSON Schema object describing the tool input parameters"),outputSchema:import_lazy_zod5.z.record(import_lazy_zod5.z.string(),import_lazy_zod5.z.unknown()).nullable().describe("JSON Schema object describing the tool output structure"),annotations:import_protocol.ToolAnnotationsSchema.optional().describe("MCP tool annotations (metadata)"),usageExamples:import_lazy_zod5.z.array(import_lazy_zod5.z.object({description:import_lazy_zod5.z.string().describe("Description of what this example demonstrates"),code:import_lazy_zod5.z.string().describe('JavaScript code example showing how to call this tool using callTool(). Format: const result = await callTool("tool:name", { ...params });')})).max(5).describe("Up to 5 practical examples of how to use this tool in a codecall:execute script")})).describe("Array of tool descriptions with schemas and usage examples"),notFound:import_lazy_zod5.z.array(import_lazy_zod5.z.string()).optional().describe("Tool names that were requested but not found in the index. Check these for typos.")});var DescribeTool=class extends import_sdk8.ToolContext{async execute(input){const{toolNames}=input;const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const startedAt=Date.now();const config=this.get(CodeCallConfig);const maxDefinitions=config.get("maxDefinitions");const tools=[];const notFound=[];const surface=(0,import_sdk8.getCallSurface)();for(const toolName of toolNames){if(isBlockedSelfReference(toolName)){notFound.push(toolName);continue}const access=checkCodeCallToolAccess(this.scope,config,toolName,{surface});if(!access.allowed){audit?.logSecurityAccessDenied(executionId,toolName,access.reason);notFound.push(toolName);continue}const tool=access.entry;if(tools.length>=maxDefinitions){throw new import_sdk8.InvalidInputError(`codecall:describe describes at most ${maxDefinitions} tools per call; describe the rest in another call`)}const appId=this.extractAppId(tool);const inputSchema=this.getInputSchema(tool);const outputSchema=this.toJsonSchema(tool.rawOutputSchema??tool.outputSchema);const usageExamples=this.generateExamples(tool,inputSchema??void 0);tools.push({name:tool.name,appId,description:tool.metadata?.description||`Tool: ${tool.name}`,inputSchema:inputSchema||null,outputSchema:outputSchema||null,annotations:tool.metadata?.annotations,usageExamples})}audit?.logDescribe(executionId,toolNames,Date.now()-startedAt);return{tools,notFound:notFound.length>0?notFound:void 0}}getInputSchema(tool){if(tool.inputSchema&&typeof tool.inputSchema==="object"&&Object.keys(tool.inputSchema).length>0){try{const firstValue=Object.values(tool.inputSchema)[0];if(firstValue instanceof import_lazy_zod6.ZodType){return(0,import_lazy_zod6.toJSONSchema)(import_lazy_zod6.z.object(tool.inputSchema))}}catch{}}if(tool.rawInputSchema){return tool.rawInputSchema}return null}toJsonSchema(schema){if(!schema){return null}if(schema instanceof import_lazy_zod6.ZodType){try{return(0,import_lazy_zod6.toJSONSchema)(schema)}catch{return null}}if(typeof schema==="object"&&schema!==null&&!Array.isArray(schema)){const obj=schema;const firstValue=Object.values(obj)[0];if(firstValue instanceof import_lazy_zod6.ZodType){try{return(0,import_lazy_zod6.toJSONSchema)(import_lazy_zod6.z.object(obj))}catch{return null}}if("type"in obj||"properties"in obj||"$schema"in obj){return schema}}if(typeof schema==="string"){return null}if(Array.isArray(schema)){return null}return null}extractAppId(tool){if(tool.metadata?.codecall?.appId){return tool.metadata.codecall.appId}if(tool.metadata?.source){return tool.metadata.source}if(tool.owner?.id){return tool.owner.id}const nameParts=tool.name?.split(":");if(nameParts&&nameParts.length>1){return nameParts[0]}return"unknown"}generateExamples(tool,inputSchema){const result=[];const examples=tool.metadata?.examples;if(examples&&Array.isArray(examples)){for(const ex of examples.slice(0,5)){result.push({description:ex.description||"Example usage",code:`const result = await callTool('${tool.name}', ${JSON.stringify(ex.input,null,2)});
78
- return result;`})}}if(result.length===0){result.push(generateSmartExample(tool.name,inputSchema,tool.metadata?.description))}return result.slice(0,5)}};DescribeTool=__decorateClass([(0,import_sdk8.Tool)({name:"codecall:describe",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:describeToolDescription,inputSchema:describeToolInputSchema,outputSchema:describeToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],DescribeTool);var import_sdk9=require("@frontmcp/sdk");var import_lazy_zod7=require("@frontmcp/lazy-zod");var MIN_EXECUTE_SCRIPT_LENGTH='return callTool("a",{})'.length;var ALWAYS_BLOCKED_NAMES=["eval","require","fetch","setTimeout","process","globalThis"];function buildExecuteToolDescription(vmOptions){const loops=vmOptions.allowLoops?"for, for-of":"for-of";const blockedLoops=vmOptions.allowLoops?"while, do-while":"while, do-while, for";const blockedNames=new Set([...ALWAYS_BLOCKED_NAMES,...vmOptions.disabledBuiltins,...vmOptions.disabledGlobals]);const namespaces=["Math","JSON"].filter(name=>!blockedNames.has(name)).map(name=>`${name}.*, `);const timeoutSeconds=vmOptions.timeoutMs/1e3;const maxToolCalls=maxToolCallsOf(vmOptions);const callsPerTool=rapidEnumerationThresholdOf(vmOptions);return`Execute AgentScript (safe JS subset) for multi-tool orchestration.
77
+ FLOW: search \u2192 describe \u2192 execute/invoke`;var describeToolInputSchema={toolNames:import_lazy_zod5.z.array(import_lazy_zod5.z.string()).min(1).superRefine((toolNames,ctx)=>{const seen=new Set;const duplicates=new Set;for(const name of toolNames){if(seen.has(name)){duplicates.add(name)}seen.add(name)}if(duplicates.size>0){ctx.addIssue({code:import_lazy_zod5.z.ZodIssueCode.custom,message:`Duplicate tool names are not allowed: ${Array.from(duplicates).join(", ")}`})}}).describe('Array of unique tool names (from codecall:search results) to fetch their detailed schemas and usage examples. Example: ["users:list", "billing:getInvoice"]')};var describeToolOutputSchema=import_lazy_zod5.z.object({tools:import_lazy_zod5.z.array(import_lazy_zod5.z.object({name:import_lazy_zod5.z.string().describe("Tool name to be used in callTool() within codecall:execute scripts"),appId:import_lazy_zod5.z.string().describe("The app ID this tool belongs to"),description:import_lazy_zod5.z.string().describe("Detailed description of what this tool does"),inputSchema:import_lazy_zod5.z.record(import_lazy_zod5.z.string(),import_lazy_zod5.z.unknown()).nullable().describe("JSON Schema object describing the tool input parameters"),outputSchema:import_lazy_zod5.z.record(import_lazy_zod5.z.string(),import_lazy_zod5.z.unknown()).nullable().describe("JSON Schema object describing the tool output structure"),annotations:import_protocol.ToolAnnotationsSchema.optional().describe("MCP tool annotations (metadata)"),usageExamples:import_lazy_zod5.z.array(import_lazy_zod5.z.object({description:import_lazy_zod5.z.string().describe("Description of what this example demonstrates"),code:import_lazy_zod5.z.string().describe('JavaScript code example showing how to call this tool using callTool(). Format: const result = await callTool("tool:name", { ...params });')})).max(5).describe("Up to 5 practical examples of how to use this tool in a codecall:execute script")})).describe("Array of tool descriptions with schemas and usage examples"),notFound:import_lazy_zod5.z.array(import_lazy_zod5.z.string()).optional().describe("Tool names that were requested but not found in the index. Check these for typos.")});var DescribeTool=class extends import_sdk9.ToolContext{async execute(input){const{toolNames}=input;const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const startedAt=Date.now();const config=this.get(CodeCallConfig);const maxDefinitions=config.get("maxDefinitions");const tools=[];const notFound=[];const surface=(0,import_sdk9.getCallSurface)();for(const toolName of toolNames){if(isBlockedSelfReference(toolName)){notFound.push(toolName);continue}const access=checkCodeCallToolAccess(this.scope,config,toolName,{surface});if(!access.allowed){audit?.logSecurityAccessDenied(executionId,toolName,access.reason);notFound.push(toolName);continue}const tool=access.entry;if(tools.length>=maxDefinitions){throw new import_sdk9.InvalidInputError(`codecall:describe describes at most ${maxDefinitions} tools per call; describe the rest in another call`)}const appId=this.extractAppId(tool);const inputSchema=this.getInputSchema(tool);const outputSchema=this.toJsonSchema(tool.rawOutputSchema??tool.outputSchema);const usageExamples=this.generateExamples(tool,inputSchema??void 0);tools.push({name:tool.name,appId,description:tool.metadata?.description||`Tool: ${tool.name}`,inputSchema:inputSchema||null,outputSchema:outputSchema||null,annotations:tool.metadata?.annotations,usageExamples})}audit?.logDescribe(executionId,toolNames,Date.now()-startedAt);return{tools,notFound:notFound.length>0?notFound:void 0}}getInputSchema(tool){if(tool.inputSchema&&typeof tool.inputSchema==="object"&&Object.keys(tool.inputSchema).length>0){try{const firstValue=Object.values(tool.inputSchema)[0];if(firstValue instanceof import_lazy_zod6.ZodType){return(0,import_lazy_zod6.toJSONSchema)(import_lazy_zod6.z.object(tool.inputSchema))}}catch{}}if(tool.rawInputSchema){return tool.rawInputSchema}return null}toJsonSchema(schema){if(!schema){return null}if(schema instanceof import_lazy_zod6.ZodType){try{return(0,import_lazy_zod6.toJSONSchema)(schema)}catch{return null}}if(typeof schema==="object"&&schema!==null&&!Array.isArray(schema)){const obj=schema;const firstValue=Object.values(obj)[0];if(firstValue instanceof import_lazy_zod6.ZodType){try{return(0,import_lazy_zod6.toJSONSchema)(import_lazy_zod6.z.object(obj))}catch{return null}}if("type"in obj||"properties"in obj||"$schema"in obj){return schema}}if(typeof schema==="string"){return null}if(Array.isArray(schema)){return null}return null}extractAppId(tool){if(tool.metadata?.codecall?.appId){return tool.metadata.codecall.appId}if(tool.metadata?.source){return tool.metadata.source}if(tool.owner?.id){return tool.owner.id}const nameParts=tool.name?.split(":");if(nameParts&&nameParts.length>1){return nameParts[0]}return"unknown"}generateExamples(tool,inputSchema){const result=[];const examples=tool.metadata?.examples;if(examples&&Array.isArray(examples)){for(const ex of examples.slice(0,5)){result.push({description:ex.description||"Example usage",code:`const result = await callTool('${tool.name}', ${JSON.stringify(ex.input,null,2)});
78
+ return result;`})}}if(result.length===0){result.push(generateSmartExample(tool.name,inputSchema,tool.metadata?.description))}return result.slice(0,5)}};DescribeTool=__decorateClass([(0,import_sdk9.Tool)({name:"codecall:describe",cache:{ttl:60,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:describeToolDescription,inputSchema:describeToolInputSchema,outputSchema:describeToolOutputSchema,annotations:{readOnlyHint:true,openWorldHint:true}})],DescribeTool);var import_sdk10=require("@frontmcp/sdk");var import_lazy_zod7=require("@frontmcp/lazy-zod");var MIN_EXECUTE_SCRIPT_LENGTH='return callTool("a",{})'.length;var ALWAYS_BLOCKED_NAMES=["eval","require","fetch","setTimeout","process","globalThis"];function buildExecuteToolDescription(vmOptions){const loops=vmOptions.allowLoops?"for, for-of":"for-of";const blockedLoops=vmOptions.allowLoops?"while, do-while":"while, do-while, for";const blockedNames=new Set([...ALWAYS_BLOCKED_NAMES,...vmOptions.disabledBuiltins,...vmOptions.disabledGlobals]);const namespaces=["Math","JSON"].filter(name=>!blockedNames.has(name)).map(name=>`${name}.*, `);const timeoutSeconds=vmOptions.timeoutMs/1e3;const maxToolCalls=maxToolCallsOf(vmOptions);const callsPerTool=rapidEnumerationThresholdOf(vmOptions);const blockedConsole=vmOptions.allowConsole?"":"console (use mcpLog), ";const consoleLine=vmOptions.allowConsole?"\nLOGGING: console.log/info/warn/error/debug or mcpLog(level, message)":"";return`Execute AgentScript (safe JS subset) for multi-tool orchestration.
79
79
 
80
80
  API: await callTool(name, args, opts?)
81
81
  - Default: throws on error
@@ -91,11 +91,11 @@ for (const u of users.items) {
91
91
  return results;
92
92
 
93
93
  ALLOWED: ${loops}, arrow fn, map/filter/reduce/find, ${namespaces.join("")}if/else, destructuring, spread, template literals
94
- BLOCKED: ${blockedLoops}, console (use mcpLog), function decl, ${[...blockedNames].join(", ")}
94
+ BLOCKED: ${blockedLoops}, ${blockedConsole}function decl, ${[...blockedNames].join(", ")}${consoleLine}
95
95
 
96
96
  ERRORS: NOT_FOUND | VALIDATION | EXECUTION | TIMEOUT | ACCESS_DENIED | RATE_LIMITED
97
97
  STATUS: ok | syntax_error | illegal_access | runtime_error | tool_error | timeout
98
- LIMITS: ${MAX_ITERATIONS_PER_LOOP} iterations per loop, ${timeoutSeconds}s timeout, ${maxToolCalls} tool calls, ${callsPerTool} calls to one tool per 2s (parallel() included)`}var executeToolDescription=buildExecuteToolDescription(resolveVmOptions());var executeToolInputSchema={script:import_lazy_zod7.z.string().min(MIN_EXECUTE_SCRIPT_LENGTH).max(100*1024).describe("JavaScript code to execute in the sandbox. Must return a value (implicitly or via explicit return). Use callTool(name, input) to invoke tools."),allowedTools:import_lazy_zod7.z.array(import_lazy_zod7.z.string()).optional().describe('Optional whitelist of tool names that can be called from this script. If not provided, all indexed tools are available. Example: ["users:list", "billing:getInvoice"]')};var syntaxErrorPayloadSchema=import_lazy_zod7.z.object({message:import_lazy_zod7.z.string(),location:import_lazy_zod7.z.object({line:import_lazy_zod7.z.number(),column:import_lazy_zod7.z.number()}).optional()});var illegalAccessErrorPayloadSchema=import_lazy_zod7.z.object({message:import_lazy_zod7.z.string(),kind:import_lazy_zod7.z.union([import_lazy_zod7.z.literal("IllegalBuiltinAccess"),import_lazy_zod7.z.literal("DisallowedGlobal"),import_lazy_zod7.z.string()])});var runtimeErrorPayloadSchema=import_lazy_zod7.z.object({source:import_lazy_zod7.z.literal("script"),message:import_lazy_zod7.z.string(),name:import_lazy_zod7.z.string().optional(),stack:import_lazy_zod7.z.string().optional()});var toolErrorPayloadSchema=import_lazy_zod7.z.object({source:import_lazy_zod7.z.literal("tool"),toolName:import_lazy_zod7.z.string(),toolInput:import_lazy_zod7.z.unknown().optional(),message:import_lazy_zod7.z.string(),code:import_lazy_zod7.z.string().optional(),details:import_lazy_zod7.z.unknown().optional()});var timeoutErrorPayloadSchema=import_lazy_zod7.z.object({message:import_lazy_zod7.z.string()});var codeCallOkResultSchema=import_lazy_zod7.z.object({status:import_lazy_zod7.z.literal("ok"),result:import_lazy_zod7.z.unknown(),logs:import_lazy_zod7.z.array(import_lazy_zod7.z.string()).optional()});var codeCallSyntaxErrorResultSchema=import_lazy_zod7.z.object({status:import_lazy_zod7.z.literal("syntax_error"),error:syntaxErrorPayloadSchema});var codeCallIllegalAccessResultSchema=import_lazy_zod7.z.object({status:import_lazy_zod7.z.literal("illegal_access"),error:illegalAccessErrorPayloadSchema});var codeCallRuntimeErrorResultSchema=import_lazy_zod7.z.object({status:import_lazy_zod7.z.literal("runtime_error"),error:runtimeErrorPayloadSchema});var codeCallToolErrorResultSchema=import_lazy_zod7.z.object({status:import_lazy_zod7.z.literal("tool_error"),error:toolErrorPayloadSchema});var codeCallTimeoutResultSchema=import_lazy_zod7.z.object({status:import_lazy_zod7.z.literal("timeout"),error:timeoutErrorPayloadSchema});var executeToolOutputSchema=import_lazy_zod7.z.discriminatedUnion("status",[codeCallOkResultSchema,codeCallSyntaxErrorResultSchema,codeCallIllegalAccessResultSchema,codeCallRuntimeErrorResultSchema,codeCallToolErrorResultSchema,codeCallTimeoutResultSchema]);function getErrorCode(error){if(!(error instanceof Error)){return TOOL_CALL_ERROR_CODES.EXECUTION}const{code,statusCode}=error;if(code==="INVALID_INPUT"){return TOOL_CALL_ERROR_CODES.VALIDATION}if(statusCode===429){return TOOL_CALL_ERROR_CODES.RATE_LIMITED}if(error.name==="ZodError"||error.message?.includes("validation")){return TOOL_CALL_ERROR_CODES.VALIDATION}if(error.message?.includes("timeout")||error.message?.includes("timed out")){return TOOL_CALL_ERROR_CODES.TIMEOUT}if(error.name==="ToolNotFoundError"||error.message?.includes("not found")){return TOOL_CALL_ERROR_CODES.NOT_FOUND}return TOOL_CALL_ERROR_CODES.EXECUTION}function publicMessageOf(error){const{getPublicMessage}=error;return typeof getPublicMessage==="function"?getPublicMessage.call(error):error.message}var ExecuteTool=class extends import_sdk9.ToolContext{checkToolPolicy(name,surface){return checkCodeCallToolAccess(this.scope,this.get(CodeCallConfig),name,{surface})}async execute(input){const{script,allowedTools}=input;const callerSurface=(0,import_sdk9.getCallSurface)();const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const callDepth=1;let toolCallCount=0;const allowedToolSet=allowedTools?new Set(allowedTools):null;const environment={callTool:async(name,toolInput,options)=>{const throwOnError=options?.throwOnError!==false;if(isBlockedSelfReference(name)){audit?.logSecuritySelfReference(executionId,name)}assertNotSelfReference(name);const decision=this.checkToolPolicy(name,callerSurface);if(!decision.allowed){audit?.logSecurityAccessDenied(executionId,name,decision.reason);const error=createToolCallError(TOOL_CALL_ERROR_CODES.ACCESS_DENIED,name,decision.reason);if(throwOnError){throw error}return{success:false,error}}if(allowedToolSet&&!allowedToolSet.has(name)){audit?.logSecurityAccessDenied(executionId,name,"not in the caller-supplied allowedTools list");const error=createToolCallError(TOOL_CALL_ERROR_CODES.ACCESS_DENIED,name);if(throwOnError){throw error}return{success:false,error}}toolCallCount+=1;audit?.logToolCallStart(executionId,name,callDepth);const toolCallStartedAt=Date.now();try{const request={method:"tools/call",params:{name,arguments:toolInput}};const ctx=asCodeCallDispatch({authInfo:this.authInfo,surface:callerSurface});const mcpResult=await this.scope.runFlow("tools:call-tool",{request,ctx});if(!mcpResult){audit?.logToolCallFailure(executionId,name,callDepth,Date.now()-toolCallStartedAt,TOOL_CALL_ERROR_CODES.EXECUTION);const error=createToolCallError(TOOL_CALL_ERROR_CODES.EXECUTION,name,"Flow returned no result");if(throwOnError){throw error}return{success:false,error}}const result=extractResultFromCallToolResult(mcpResult);audit?.logToolCallSuccess(executionId,name,callDepth,Date.now()-toolCallStartedAt);if(throwOnError){return result}return{success:true,data:result}}catch(error){const errorCode=getErrorCode(error);const rawMessage=error instanceof Error?publicMessageOf(error):void 0;audit?.logToolCallFailure(executionId,name,callDepth,Date.now()-toolCallStartedAt,errorCode);const sanitizedError=createToolCallError(errorCode,name,rawMessage);if(throwOnError){throw sanitizedError}return{success:false,error:sanitizedError}}},getTool:name=>{try{if(isBlockedSelfReference(name)){audit?.logSecuritySelfReference(executionId,name);return void 0}const introspectionAccess=this.checkToolPolicy(name,callerSurface);if(!introspectionAccess.allowed){audit?.logSecurityAccessDenied(executionId,name,introspectionAccess.reason);return void 0}if(allowedToolSet&&!allowedToolSet.has(name))return void 0;const tool=introspectionAccess.entry;return toPlainJson({name:tool.name,description:tool.metadata?.description,inputSchema:tool.getInputJsonSchema?.()??null,outputSchema:tool.getOutputJsonSchema?.()??null})}catch{return void 0}},console:this.get(CodeCallConfig).get("resolvedVm.allowConsole")?console:void 0,mcpLog:(level,message,metadata)=>{this.logger?.[level](message,metadata)},mcpNotify:(event,payload)=>{this.logger?.debug("Notification sent",{event,payload})}};try{const policyConfig=readCodeCallPolicyConfig(this.get(CodeCallConfig));const callableTools=this.scope.tools.getTools(true).filter(tool=>checkCodeCallToolPolicy(toCodeCallPolicyTool(tool,void 0,this.scope),policyConfig).allowed);const{namespaces,skipped}=buildToolNamespaces(callableTools);environment.toolNamespaces=namespaces;if(skipped.length>0){this.logger?.debug?.("codecall: tools skipped during namespace generation",{count:skipped.length,sample:skipped.slice(0,25)})}}catch(error){this.logger?.warn?.("codecall: failed to build tool namespaces",{error:error instanceof Error?error.message:String(error)})}const enclaveService=this.get(EnclaveService);const config=this.get(CodeCallConfig);const startedAt=Date.now();const elapsed=reported=>reported??Date.now()-startedAt;audit?.logExecutionStart(executionId,script);try{const executionResult=await enclaveService.execute(script,environment);const durationMs=elapsed(executionResult.stats?.duration);if(executionResult.timedOut){audit?.logExecutionTimeout(executionId,script,durationMs);return{status:"timeout",error:{message:`Script execution timed out after ${config.getAll().resolvedVm.timeoutMs}ms`}}}if(!executionResult.success){const error=executionResult.error;if(error.code==="SYNTAX_ERROR"){audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"syntax_error",error:{message:toClientErrorMessage(error.message)||"Syntax error in script",...error.location?{location:error.location}:{}}}}if(error.code==="VALIDATION_ERROR"||error.name==="ValidationError"){audit?.logSecurityAstBlocked(executionId,error.blockedPatterns?.join(", ")??"UNKNOWN",error.message);audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"illegal_access",error:{kind:"IllegalBuiltinAccess",message:error.message}}}if(error.toolName){audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"tool_error",error:{source:"tool",toolName:error.toolName,message:toClientErrorMessage(error.message),code:error.code}}}audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"runtime_error",error:{source:"script",message:toClientErrorMessage(error.message),name:error.name}}}audit?.logExecutionSuccess(executionId,script,durationMs,toolCallCount);return{status:"ok",result:executionResult.result,logs:executionResult.logs.length>0?executionResult.logs:void 0}}catch(error){const errorName=error instanceof Error?error.name:"Error";const errorMessage=error instanceof Error?error.message:String(error);audit?.logExecutionFailure(executionId,script,elapsed(),errorMessage);const errorLoc=error.loc;if(errorName==="SyntaxError"||errorMessage?.includes("syntax")){return{status:"syntax_error",error:{message:toClientErrorMessage(errorMessage)||"Syntax error in script",location:errorLoc?{line:errorLoc.line,column:errorLoc.column}:void 0}}}return{status:"runtime_error",error:{source:"script",message:toClientErrorMessage(errorMessage)||"An unexpected error occurred during script execution",name:errorName}}}}};ExecuteTool=__decorateClass([(0,import_sdk9.Tool)({name:"codecall:execute",cache:{ttl:0,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:executeToolDescription,inputSchema:executeToolInputSchema,outputSchema:executeToolOutputSchema})],ExecuteTool);var import_sdk10=require("@frontmcp/sdk");var import_lazy_zod8=require("@frontmcp/lazy-zod");var invokeToolDescription=`Call ONE tool directly. Returns standard MCP CallToolResult.
98
+ LIMITS: ${MAX_ITERATIONS_PER_LOOP} iterations per loop, ${timeoutSeconds}s timeout, ${maxToolCalls} tool calls, ${callsPerTool} calls to one tool per 2s (parallel() included)`}var executeToolDescription=buildExecuteToolDescription(resolveVmOptions());var executeToolInputSchema={script:import_lazy_zod7.z.string().min(MIN_EXECUTE_SCRIPT_LENGTH).max(100*1024).describe("JavaScript code to execute in the sandbox. Must return a value (implicitly or via explicit return). Use callTool(name, input) to invoke tools."),allowedTools:import_lazy_zod7.z.array(import_lazy_zod7.z.string()).optional().describe('Optional whitelist of tool names that can be called from this script. If not provided, all indexed tools are available. Example: ["users:list", "billing:getInvoice"]')};var syntaxErrorPayloadSchema=import_lazy_zod7.z.object({message:import_lazy_zod7.z.string(),location:import_lazy_zod7.z.object({line:import_lazy_zod7.z.number(),column:import_lazy_zod7.z.number()}).optional()});var illegalAccessErrorPayloadSchema=import_lazy_zod7.z.object({message:import_lazy_zod7.z.string(),kind:import_lazy_zod7.z.union([import_lazy_zod7.z.literal("IllegalBuiltinAccess"),import_lazy_zod7.z.literal("DisallowedGlobal"),import_lazy_zod7.z.string()])});var runtimeErrorPayloadSchema=import_lazy_zod7.z.object({source:import_lazy_zod7.z.literal("script"),message:import_lazy_zod7.z.string(),name:import_lazy_zod7.z.string().optional(),stack:import_lazy_zod7.z.string().optional()});var toolErrorPayloadSchema=import_lazy_zod7.z.object({source:import_lazy_zod7.z.literal("tool"),toolName:import_lazy_zod7.z.string(),toolInput:import_lazy_zod7.z.unknown().optional(),message:import_lazy_zod7.z.string(),code:import_lazy_zod7.z.string().optional(),details:import_lazy_zod7.z.unknown().optional()});var timeoutErrorPayloadSchema=import_lazy_zod7.z.object({message:import_lazy_zod7.z.string()});var codeCallOkResultSchema=import_lazy_zod7.z.object({status:import_lazy_zod7.z.literal("ok"),result:import_lazy_zod7.z.unknown(),logs:import_lazy_zod7.z.array(import_lazy_zod7.z.string()).optional()});var codeCallSyntaxErrorResultSchema=import_lazy_zod7.z.object({status:import_lazy_zod7.z.literal("syntax_error"),error:syntaxErrorPayloadSchema});var codeCallIllegalAccessResultSchema=import_lazy_zod7.z.object({status:import_lazy_zod7.z.literal("illegal_access"),error:illegalAccessErrorPayloadSchema});var codeCallRuntimeErrorResultSchema=import_lazy_zod7.z.object({status:import_lazy_zod7.z.literal("runtime_error"),error:runtimeErrorPayloadSchema});var codeCallToolErrorResultSchema=import_lazy_zod7.z.object({status:import_lazy_zod7.z.literal("tool_error"),error:toolErrorPayloadSchema});var codeCallTimeoutResultSchema=import_lazy_zod7.z.object({status:import_lazy_zod7.z.literal("timeout"),error:timeoutErrorPayloadSchema});var executeToolOutputSchema=import_lazy_zod7.z.discriminatedUnion("status",[codeCallOkResultSchema,codeCallSyntaxErrorResultSchema,codeCallIllegalAccessResultSchema,codeCallRuntimeErrorResultSchema,codeCallToolErrorResultSchema,codeCallTimeoutResultSchema]);function getErrorCode(error,clientError){if(error instanceof Error&&error.name==="ZodError"){return TOOL_CALL_ERROR_CODES.VALIDATION}switch(clientError.code){case"INVALID_INPUT":return TOOL_CALL_ERROR_CODES.VALIDATION;case"TOOL_NOT_FOUND":return TOOL_CALL_ERROR_CODES.NOT_FOUND;case"EXECUTION_TIMEOUT":return TOOL_CALL_ERROR_CODES.TIMEOUT;case"RATE_LIMIT_EXCEEDED":case"QUOTA_EXCEEDED":case"CONCURRENCY_LIMIT":case"QUEUE_TIMEOUT":return TOOL_CALL_ERROR_CODES.RATE_LIMITED}return clientError.statusCode===429?TOOL_CALL_ERROR_CODES.RATE_LIMITED:TOOL_CALL_ERROR_CODES.EXECUTION}function toolCallErrorOf(error,toolName){const clientError=(0,import_sdk10.toMcpError)(error);const code=getErrorCode(error,clientError);return clientError.isPublic?createPublicToolCallError(code,toolName,clientError.getPublicMessage()):createToolCallError(code,toolName)}var ExecuteTool=class extends import_sdk10.ToolContext{checkToolPolicy(name,surface){return checkCodeCallToolAccess(this.scope,this.get(CodeCallConfig),name,{surface})}async execute(input){const{script,allowedTools}=input;const callerSurface=(0,import_sdk10.getCallSurface)();const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const callDepth=1;let toolCallCount=0;const allowedToolSet=allowedTools?new Set(allowedTools):null;const environment={callTool:async(name,toolInput,options)=>{const throwOnError=options?.throwOnError!==false;if(isBlockedSelfReference(name)){audit?.logSecuritySelfReference(executionId,name)}assertNotSelfReference(name);const decision=this.checkToolPolicy(name,callerSurface);if(!decision.allowed){audit?.logSecurityAccessDenied(executionId,name,decision.reason);const error=createToolCallError(TOOL_CALL_ERROR_CODES.ACCESS_DENIED,name,decision.reason);if(throwOnError){throw error}return{success:false,error}}if(allowedToolSet&&!allowedToolSet.has(name)){audit?.logSecurityAccessDenied(executionId,name,"not in the caller-supplied allowedTools list");const error=createToolCallError(TOOL_CALL_ERROR_CODES.ACCESS_DENIED,name);if(throwOnError){throw error}return{success:false,error}}toolCallCount+=1;audit?.logToolCallStart(executionId,name,callDepth);const toolCallStartedAt=Date.now();try{const request={method:"tools/call",params:{name,arguments:toolInput}};const ctx=asCodeCallDispatch({authInfo:this.authInfo,surface:callerSurface});const mcpResult=await this.scope.runFlow("tools:call-tool",{request,ctx});if(!mcpResult){audit?.logToolCallFailure(executionId,name,callDepth,Date.now()-toolCallStartedAt,TOOL_CALL_ERROR_CODES.EXECUTION);const error=createToolCallError(TOOL_CALL_ERROR_CODES.EXECUTION,name,"Flow returned no result");if(throwOnError){throw error}return{success:false,error}}const result=extractResultFromCallToolResult(mcpResult);audit?.logToolCallSuccess(executionId,name,callDepth,Date.now()-toolCallStartedAt);if(throwOnError){return result}return{success:true,data:result}}catch(error){const sanitizedError=toolCallErrorOf(error,name);audit?.logToolCallFailure(executionId,name,callDepth,Date.now()-toolCallStartedAt,sanitizedError.code);if(throwOnError){throw sanitizedError}return{success:false,error:sanitizedError}}},getTool:name=>{try{if(isBlockedSelfReference(name)){audit?.logSecuritySelfReference(executionId,name);return void 0}const introspectionAccess=this.checkToolPolicy(name,callerSurface);if(!introspectionAccess.allowed){audit?.logSecurityAccessDenied(executionId,name,introspectionAccess.reason);return void 0}if(allowedToolSet&&!allowedToolSet.has(name))return void 0;const tool=introspectionAccess.entry;return toPlainJson({name:tool.name,description:tool.metadata?.description,inputSchema:tool.getInputJsonSchema?.()??null,outputSchema:tool.getOutputJsonSchema?.()??null})}catch{return void 0}},mcpLog:(level,message,metadata)=>{this.logger?.[level](message,metadata)},mcpNotify:(event,payload)=>{this.logger?.debug("Notification sent",{event,payload})}};try{const policyConfig=readCodeCallPolicyConfig(this.get(CodeCallConfig));const callableTools=this.scope.tools.getTools(true).filter(tool=>checkCodeCallToolPolicy(toCodeCallPolicyTool(tool,void 0,this.scope),policyConfig).allowed);const{namespaces,skipped}=buildToolNamespaces(callableTools);environment.toolNamespaces=namespaces;if(skipped.length>0){this.logger?.debug?.("codecall: tools skipped during namespace generation",{count:skipped.length,sample:skipped.slice(0,25)})}}catch(error){this.logger?.warn?.("codecall: failed to build tool namespaces",{error:error instanceof Error?error.message:String(error)})}const enclaveService=this.get(EnclaveService);const config=this.get(CodeCallConfig);const startedAt=Date.now();const elapsed=reported=>reported??Date.now()-startedAt;audit?.logExecutionStart(executionId,script);try{const executionResult=await enclaveService.execute(script,environment);const durationMs=elapsed(executionResult.stats?.duration);if(executionResult.timedOut){audit?.logExecutionTimeout(executionId,script,durationMs);return{status:"timeout",error:{message:`Script execution timed out after ${config.getAll().resolvedVm.timeoutMs}ms`}}}if(!executionResult.success){const error=executionResult.error;if(error.code==="SYNTAX_ERROR"){audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"syntax_error",error:{message:toClientErrorMessage(error.message)||"Syntax error in script",...error.location?{location:error.location}:{}}}}if(error.code==="VALIDATION_ERROR"||error.name==="ValidationError"){audit?.logSecurityAstBlocked(executionId,error.blockedPatterns?.join(", ")??"UNKNOWN",error.message);audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"illegal_access",error:{kind:"IllegalBuiltinAccess",message:error.message}}}if(error.toolName){audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"tool_error",error:{source:"tool",toolName:error.toolName,message:toClientErrorMessage(error.message),code:error.code}}}audit?.logExecutionFailure(executionId,script,durationMs,error.message);return{status:"runtime_error",error:{source:"script",message:toClientErrorMessage(error.message),name:error.name}}}audit?.logExecutionSuccess(executionId,script,durationMs,toolCallCount);return{status:"ok",result:executionResult.result,logs:executionResult.logs.length>0?executionResult.logs:void 0}}catch(error){const errorName=error instanceof Error?error.name:"Error";const errorMessage=error instanceof Error?error.message:String(error);audit?.logExecutionFailure(executionId,script,elapsed(),errorMessage);const errorLoc=error.loc;if(errorName==="SyntaxError"||errorMessage?.includes("syntax")){return{status:"syntax_error",error:{message:toClientErrorMessage(errorMessage)||"Syntax error in script",location:errorLoc?{line:errorLoc.line,column:errorLoc.column}:void 0}}}return{status:"runtime_error",error:{source:"script",message:toClientErrorMessage(errorMessage)||"An unexpected error occurred during script execution",name:errorName}}}}};ExecuteTool=__decorateClass([(0,import_sdk10.Tool)({name:"codecall:execute",cache:{ttl:0,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:executeToolDescription,inputSchema:executeToolInputSchema,outputSchema:executeToolOutputSchema})],ExecuteTool);var import_sdk11=require("@frontmcp/sdk");var import_lazy_zod8=require("@frontmcp/lazy-zod");var invokeToolDescription=`Call ONE tool directly. Returns standard MCP CallToolResult.
99
99
 
100
100
  USE invoke: single tool, no transformation
101
101
  USE execute: multiple tools, loops, filtering, joining
@@ -104,4 +104,4 @@ INPUT: tool (string), input (object matching tool schema)
104
104
  OUTPUT: MCP CallToolResult (same as standard tool call)
105
105
  ERRORS: tool_not_found (\u2192 re-search) | validation_error | execution_error | permission_denied
106
106
 
107
- FLOW: search \u2192 describe \u2192 invoke`;var invokeToolInputSchema={tool:import_lazy_zod8.z.string().describe('The name of the tool to invoke (e.g., "users:getById", "billing:getInvoice"). Must be a tool you discovered via codecall:search.'),input:import_lazy_zod8.z.record(import_lazy_zod8.z.string(),import_lazy_zod8.z.unknown()).describe("The input parameters for the tool. Structure must match the tool's input schema (check codecall:describe for schema details).")};function buildErrorResult(message){return{content:[{type:"text",text:message}],isError:true}}var InvokeTool=class extends import_sdk10.ToolContext{async execute(input){const{tool:toolName,input:toolInput}=input;const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const startedAt=Date.now();if(isBlockedSelfReference(toolName)){audit?.logSecuritySelfReference(executionId,toolName);return buildErrorResult(`Tool "${toolName}" cannot be invoked directly. CodeCall tools are internal and not accessible via codecall:invoke.`)}const surface=(0,import_sdk10.getCallSurface)();const decision=checkCodeCallToolAccess(this.scope,this.get(CodeCallConfig),toolName,{directCall:true,surface});if(!decision.allowed){audit?.logSecurityAccessDenied(executionId,toolName,decision.reason);return buildErrorResult(`Tool "${toolName}" is not available. Use codecall:search to discover available tools.`)}const request={method:"tools/call",params:{name:toolName,arguments:toolInput}};const ctx=asCodeCallDispatch({authInfo:this.authInfo,surface});const result=await this.scope.runFlow("tools:call-tool",{request,ctx});if(!result){audit?.logInvoke(executionId,toolName,false,Date.now()-startedAt);return buildErrorResult(`Tool "${toolName}" not found. Use codecall:search to discover available tools.`)}audit?.logInvoke(executionId,toolName,true,Date.now()-startedAt);return result}};InvokeTool=__decorateClass([(0,import_sdk10.Tool)({name:"codecall:invoke",cache:{ttl:0,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:invokeToolDescription,inputSchema:invokeToolInputSchema})],InvokeTool);function auditLogFields(event){const{executionId,durationMs,data}=event;return durationMs===void 0?{executionId,...data}:{executionId,durationMs,...data}}function callContextOf(flowCtx){const rawInput=flowCtx.rawInput;return typeof rawInput==="object"&&rawInput!==null?rawInput.ctx:void 0}var CodeCallPlugin=class extends import_sdk11.DynamicPlugin{options;cachedLogger;getLogger(){if(!this.cachedLogger){this.cachedLogger=this.get(import_sdk11.FrontMcpLogger).child("CodeCall")}return this.cachedLogger}constructor(options={}){super();this.options=codeCallPluginOptionsSchema.parse(options)}static dynamicProviders(options){const parsedOptions=codeCallPluginOptionsSchema.parse(options);const config=new CodeCallConfig(parsedOptions);return[{name:"codecall:config",provide:CodeCallConfig,useValue:config},{name:"codecall:enclave",provide:EnclaveService,inject:()=>[CodeCallConfig],useFactory:async cfg=>{return new EnclaveService(cfg)}},{name:"codecall:audit-logger",provide:AuditLoggerService,inject:()=>[import_sdk11.ScopeEntry],useFactory:scope=>{const audit=new AuditLoggerService;const logger=scope.logger.child("codecall:audit");audit.subscribe(event=>logger.info(event.type,auditLogFields(event)));return audit}},{name:"codecall:tool-search",provide:ToolSearchService,inject:()=>[import_sdk11.ScopeEntry],useFactory:async scope=>{return new ToolSearchService({embeddingOptions:parsedOptions.embedding,defaultTopK:parsedOptions.topK,mode:parsedOptions.mode,includeTools:parsedOptions["includeTools"]},scope)}}]}static dynamicTools(options){const config=new CodeCallConfig(codeCallPluginOptionsSchema.parse(options)).getAll();class ConfiguredSearchTool extends SearchTool{}class ConfiguredExecuteTool extends ExecuteTool{}Reflect.defineMetadata(import_sdk11.FrontMcpToolTokens.description,buildSearchToolDescription(config.topK),ConfiguredSearchTool);Reflect.defineMetadata(import_sdk11.FrontMcpToolTokens.description,buildExecuteToolDescription(config.resolvedVm),ConfiguredExecuteTool);return[ConfiguredSearchTool,SearchSkillsTool,SearchKnowledgeTool,DescribeTool,ConfiguredExecuteTool,InvokeTool]}async adjustListTools(flowCtx){const logger=this.getLogger();const{resolvedTools}=flowCtx.state;logger.verbose("adjustListTools hook called",{mode:this.options.mode});logger.verbose("adjustListTools: tools before filter",{count:resolvedTools?.length??0});if(!resolvedTools||resolvedTools.length===0){logger.verbose("adjustListTools: no tools to filter, returning early");return}const scope=this.tryGetScope();const filteredTools=resolvedTools.filter(({tool})=>!this.judges(scope,{tool})||this.shouldShowInListTools(tool,this.options.mode));logger.verbose("adjustListTools: tools after filter",{count:filteredTools.length});flowCtx.state.set("resolvedTools",filteredTools)}async refuseDirectCallOfHiddenTool(flowCtx){const{tool}=flowCtx.state;if(!tool||tool.owner?.kind==="scope")return;if(this.isDirectlyCallable(tool))return;if(isInProcessDispatch(callContextOf(flowCtx)))return;this.getLogger().verbose("refused a direct tools/call of a tool CodeCall hides",{tool:tool.fullName});throw new import_sdk11.ToolNotFoundError(flowCtx.state.input?.name??tool.name)}isDirectlyCallable(tool){if(!this.managesApp(tool))return true;if(!this.shouldShowInListTools(tool,this.options.mode))return false;if((0,import_sdk11.resolveToolVisibility)(tool.metadata)!=="hidden")return true;return this.getCodeCallMetadata(tool)?.visibleInListTools===true}managesApp(tool){const managedAppIds=this.options.appIds;if(this.options.mode!=="codecall_only"||!managedAppIds||managedAppIds.length===0)return true;const toolOwnerAppId=tool.owner?.kind==="app"?tool.owner.id:void 0;return toolOwnerAppId!==void 0&&managedAppIds.includes(toolOwnerAppId)}judges(scope,entry){return!scope?.hooks||(0,import_sdk11.isEntryGatedBy)(scope,entry,this)}tryGetScope(){try{return this.get(import_sdk11.ScopeEntry)}catch{return void 0}}shouldShowInListTools(tool,mode){if(this.isCodeCallTool(tool)){return true}const codecallMeta=this.getCodeCallMetadata(tool);switch(mode){case"codecall_only":return!this.managesApp(tool)||codecallMeta?.visibleInListTools===true;case"codecall_opt_in":case"metadata_driven":return codecallMeta?.visibleInListTools!==false;default:return true}}isCodeCallTool(tool){const name=tool.name||tool.fullName;return typeof name==="string"&&name.startsWith("codecall:")}getCodeCallMetadata(tool){return tool.metadata?.["codecall"]}};__decorateClass([import_sdk11.ListToolsHook.Did("resolveConflicts",{priority:1e3})],CodeCallPlugin.prototype,"adjustListTools",1);__decorateClass([import_sdk11.ToolHook.Did("findTool",{priority:10,appliesTo:"uncovered-apps"})],CodeCallPlugin.prototype,"refuseDirectCallOfHiddenTool",1);CodeCallPlugin=__decorateClass([(0,import_sdk11.Plugin)({name:"codecall",description:"CodeCall plugin: AgentScript-based meta-tools for orchestrating MCP tools",providers:[],plugins:[import_plugin_cache.default]})],CodeCallPlugin);0&&(module.exports={AUDIT_EVENT_TYPES,AuditLoggerService,CodeCallPlugin,codeCallDirectCallsOptionsSchema,codeCallEmbeddingOptionsSchema,codeCallModeSchema,codeCallPluginOptionsSchema,codeCallSidecarOptionsSchema,codeCallVmOptionsSchema,codeCallVmPresetSchema,embeddingStrategySchema,synonymExpansionConfigSchema});
107
+ FLOW: search \u2192 describe \u2192 invoke`;var invokeToolInputSchema={tool:import_lazy_zod8.z.string().describe('The name of the tool to invoke (e.g., "users:getById", "billing:getInvoice"). Must be a tool you discovered via codecall:search.'),input:import_lazy_zod8.z.record(import_lazy_zod8.z.string(),import_lazy_zod8.z.unknown()).describe("The input parameters for the tool. Structure must match the tool's input schema (check codecall:describe for schema details).")};function buildErrorResult(message){return{content:[{type:"text",text:message}],isError:true}}var InvokeTool=class extends import_sdk11.ToolContext{async execute(input){const{tool:toolName,input:toolInput}=input;const audit=this.tryGet(AuditLoggerService);const executionId=audit?audit.generateExecutionId():"";const startedAt=Date.now();if(isBlockedSelfReference(toolName)){audit?.logSecuritySelfReference(executionId,toolName);return buildErrorResult(`Tool "${toolName}" cannot be invoked directly. CodeCall tools are internal and not accessible via codecall:invoke.`)}const surface=(0,import_sdk11.getCallSurface)();const decision=checkCodeCallToolAccess(this.scope,this.get(CodeCallConfig),toolName,{directCall:true,surface});if(!decision.allowed){audit?.logSecurityAccessDenied(executionId,toolName,decision.reason);return buildErrorResult(`Tool "${toolName}" is not available. Use codecall:search to discover available tools.`)}const request={method:"tools/call",params:{name:toolName,arguments:toolInput}};const ctx=asCodeCallDispatch({authInfo:this.authInfo,surface});const result=await this.scope.runFlow("tools:call-tool",{request,ctx});if(!result){audit?.logInvoke(executionId,toolName,false,Date.now()-startedAt);return buildErrorResult(`Tool "${toolName}" not found. Use codecall:search to discover available tools.`)}audit?.logInvoke(executionId,toolName,true,Date.now()-startedAt);return result}};InvokeTool=__decorateClass([(0,import_sdk11.Tool)({name:"codecall:invoke",cache:{ttl:0,slideWindow:false},codecall:{enabledInCodeCall:false,visibleInListTools:true},description:invokeToolDescription,inputSchema:invokeToolInputSchema})],InvokeTool);function auditLogFields(event){const{executionId,durationMs,data}=event;return durationMs===void 0?{executionId,...data}:{executionId,durationMs,...data}}function callContextOf(flowCtx){const rawInput=flowCtx.rawInput;return typeof rawInput==="object"&&rawInput!==null?rawInput.ctx:void 0}var CodeCallPlugin=class extends import_sdk12.DynamicPlugin{options;cachedLogger;getLogger(){if(!this.cachedLogger){this.cachedLogger=this.get(import_sdk12.FrontMcpLogger).child("CodeCall")}return this.cachedLogger}constructor(options={}){super();this.options=codeCallPluginOptionsSchema.parse(options)}static dynamicProviders(options){const parsedOptions=codeCallPluginOptionsSchema.parse(options);const config=new CodeCallConfig(parsedOptions);return[{name:"codecall:config",provide:CodeCallConfig,useValue:config},{name:"codecall:enclave",provide:EnclaveService,inject:()=>[CodeCallConfig,import_sdk12.ScopeEntry],useFactory:async(cfg,scope)=>{return new EnclaveService(cfg,scope.logger.child("CodeCall:script"))}},{name:"codecall:audit-logger",provide:AuditLoggerService,inject:()=>[import_sdk12.ScopeEntry],useFactory:scope=>{const audit=new AuditLoggerService;const logger=scope.logger.child("codecall:audit");audit.subscribe(event=>logger.info(event.type,auditLogFields(event)));return audit}},{name:"codecall:tool-search",provide:ToolSearchService,inject:()=>[import_sdk12.ScopeEntry],useFactory:async scope=>{return new ToolSearchService({embeddingOptions:parsedOptions.embedding,defaultTopK:parsedOptions.topK,mode:parsedOptions.mode,includeTools:parsedOptions["includeTools"]},scope)}}]}static dynamicTools(options){const config=new CodeCallConfig(codeCallPluginOptionsSchema.parse(options)).getAll();class ConfiguredSearchTool extends SearchTool{}class ConfiguredExecuteTool extends ExecuteTool{}Reflect.defineMetadata(import_sdk12.FrontMcpToolTokens.description,buildSearchToolDescription(config.topK),ConfiguredSearchTool);Reflect.defineMetadata(import_sdk12.FrontMcpToolTokens.description,buildExecuteToolDescription(config.resolvedVm),ConfiguredExecuteTool);return[ConfiguredSearchTool,SearchSkillsTool,SearchKnowledgeTool,DescribeTool,ConfiguredExecuteTool,InvokeTool]}async adjustListTools(flowCtx){const logger=this.getLogger();const{resolvedTools}=flowCtx.state;logger.verbose("adjustListTools hook called",{mode:this.options.mode});logger.verbose("adjustListTools: tools before filter",{count:resolvedTools?.length??0});if(!resolvedTools||resolvedTools.length===0){logger.verbose("adjustListTools: no tools to filter, returning early");return}const scope=this.tryGetScope();const filteredTools=resolvedTools.filter(({tool})=>!this.judges(scope,{tool})||this.shouldShowInListTools(tool,this.options.mode));logger.verbose("adjustListTools: tools after filter",{count:filteredTools.length});flowCtx.state.set("resolvedTools",filteredTools)}async refuseDirectCallOfHiddenTool(flowCtx){const{tool}=flowCtx.state;if(!tool||tool.owner?.kind==="scope")return;if(this.isDirectlyCallable(tool))return;if(isInProcessDispatch(callContextOf(flowCtx)))return;this.getLogger().verbose("refused a direct tools/call of a tool CodeCall hides",{tool:tool.fullName});throw new import_sdk12.ToolNotFoundError(flowCtx.state.input?.name??tool.name)}isDirectlyCallable(tool){if(!this.managesApp(tool))return true;if(!this.shouldShowInListTools(tool,this.options.mode))return false;if((0,import_sdk12.resolveToolVisibility)(tool.metadata)!=="hidden")return true;return this.getCodeCallMetadata(tool)?.visibleInListTools===true}managesApp(tool){const managedAppIds=this.options.appIds;if(this.options.mode!=="codecall_only"||!managedAppIds||managedAppIds.length===0)return true;const toolOwnerAppId=tool.owner?.kind==="app"?tool.owner.id:void 0;return toolOwnerAppId!==void 0&&managedAppIds.includes(toolOwnerAppId)}judges(scope,entry){return!scope?.hooks||(0,import_sdk12.isEntryGatedBy)(scope,entry,this)}tryGetScope(){try{return this.get(import_sdk12.ScopeEntry)}catch{return void 0}}shouldShowInListTools(tool,mode){if(this.isCodeCallTool(tool)){return true}const codecallMeta=this.getCodeCallMetadata(tool);switch(mode){case"codecall_only":return!this.managesApp(tool)||codecallMeta?.visibleInListTools===true;case"codecall_opt_in":case"metadata_driven":return codecallMeta?.visibleInListTools!==false;default:return true}}isCodeCallTool(tool){const name=tool.name||tool.fullName;return typeof name==="string"&&name.startsWith("codecall:")}getCodeCallMetadata(tool){return tool.metadata?.["codecall"]}};__decorateClass([import_sdk12.ListToolsHook.Did("resolveConflicts",{priority:1e3})],CodeCallPlugin.prototype,"adjustListTools",1);__decorateClass([import_sdk12.ToolHook.Did("findTool",{priority:10,appliesTo:"uncovered-apps"})],CodeCallPlugin.prototype,"refuseDirectCallOfHiddenTool",1);CodeCallPlugin=__decorateClass([(0,import_sdk12.Plugin)({name:"codecall",description:"CodeCall plugin: AgentScript-based meta-tools for orchestrating MCP tools",providers:[],plugins:[import_plugin_cache.default]})],CodeCallPlugin);0&&(module.exports={AUDIT_EVENT_TYPES,AuditLoggerService,CodeCallPlugin,codeCallDirectCallsOptionsSchema,codeCallEmbeddingOptionsSchema,codeCallModeSchema,codeCallPluginOptionsSchema,codeCallSidecarOptionsSchema,codeCallVmOptionsSchema,codeCallVmPresetSchema,embeddingStrategySchema,synonymExpansionConfigSchema});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frontmcp/plugin-codecall",
3
- "version": "1.11.2",
3
+ "version": "1.12.0-rc.1",
4
4
  "description": "CodeCall plugin for FrontMCP: puts many tools behind search, describe, invoke and execute meta-tools, and runs scripts that call them in a sandbox",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "license": "Apache-2.0",
@@ -51,19 +51,19 @@
51
51
  }
52
52
  },
53
53
  "dependencies": {
54
- "@enclave-vm/ast": "^2.17.0",
55
- "@enclave-vm/core": "^2.17.0",
56
- "@frontmcp/protocol": "1.11.2",
54
+ "@enclave-vm/ast": "^2.18.0",
55
+ "@enclave-vm/core": "^2.18.0",
56
+ "@frontmcp/protocol": "1.12.0-rc.1",
57
57
  "acorn": "^8.15.0",
58
58
  "vectoriadb": "^2.3.4"
59
59
  },
60
60
  "peerDependencies": {
61
- "@frontmcp/lazy-zod": "1.11.2",
62
- "@frontmcp/plugin-cache": "1.11.2",
63
- "@frontmcp/sdk": "1.11.2"
61
+ "@frontmcp/lazy-zod": "1.12.0-rc.1",
62
+ "@frontmcp/plugin-cache": "1.12.0-rc.1",
63
+ "@frontmcp/sdk": "1.12.0-rc.1"
64
64
  },
65
65
  "devDependencies": {
66
- "@frontmcp/sdk": "1.11.2",
66
+ "@frontmcp/sdk": "1.12.0-rc.1",
67
67
  "reflect-metadata": "^0.2.2"
68
68
  }
69
69
  }
@@ -1 +1 @@
1
- {"version":3,"file":"code-call.config.d.ts","sourceRoot":"","sources":["../../src/providers/code-call.config.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAA2B,MAAM,eAAe,CAAC;AAEpE,OAAO,EAAE,KAAK,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAEL,KAAK,qBAAqB,EAC1B,KAAK,iBAAiB,EAEvB,MAAM,mBAAmB,CAAC;AAE3B;;;;;;;;;;;;;;;;;;;;GAoBG;AAMH,MAAM,CAAC,OAAO,OAAO,cAAe,SAAQ,UAAU,CACpD,qBAAqB,GAAG;IAAE,UAAU,EAAE,yBAAyB,CAAA;CAAE,CAClE;gBACa,OAAO,GAAE,OAAO,CAAC,qBAAqB,CAAM;CASzD;AAED,6EAA6E;AAC7E,eAAO,MAAM,uBAAuB,QAAQ,CAAC;AAE7C,6DAA6D;AAC7D,wBAAgB,cAAc,CAAC,SAAS,EAAE,yBAAyB,GAAG,MAAM,CAE3E;AAKD,2GAA2G;AAC3G,wBAAgB,2BAA2B,CAAC,SAAS,EAAE,yBAAyB,GAAG,MAAM,CAExF;AAID,wBAAgB,gBAAgB,CAAC,SAAS,CAAC,EAAE,iBAAiB,GAAG,yBAAyB,CAWzF"}
1
+ {"version":3,"file":"code-call.config.d.ts","sourceRoot":"","sources":["../../src/providers/code-call.config.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAA2B,MAAM,eAAe,CAAC;AAEpE,OAAO,EAAE,KAAK,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAEL,KAAK,qBAAqB,EAC1B,KAAK,iBAAiB,EAEvB,MAAM,mBAAmB,CAAC;AAE3B;;;;;;;;;;;;;;;;;;;;GAoBG;AAMH,MAAM,CAAC,OAAO,OAAO,cAAe,SAAQ,UAAU,CACpD,qBAAqB,GAAG;IAAE,UAAU,EAAE,yBAAyB,CAAA;CAAE,CAClE;gBACa,OAAO,GAAE,OAAO,CAAC,qBAAqB,CAAM;CASzD;AAED,6EAA6E;AAC7E,eAAO,MAAM,uBAAuB,QAAQ,CAAC;AAE7C,6DAA6D;AAC7D,wBAAgB,cAAc,CAAC,SAAS,EAAE,yBAAyB,GAAG,MAAM,CAE3E;AAKD,2GAA2G;AAC3G,wBAAgB,2BAA2B,CAAC,SAAS,EAAE,yBAAyB,GAAG,MAAM,CAExF;AAID,wBAAgB,gBAAgB,CAAC,SAAS,CAAC,EAAE,iBAAiB,GAAG,yBAAyB,CAazF"}