@frontmcp/plugin-codecall 1.10.15 → 1.11.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/esm/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;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};import CachePlugin from"@frontmcp/plugin-cache";import{DynamicPlugin,FrontMcpLogger,FrontMcpToolTokens,isEntryGatedBy,ListToolsHook,Plugin,resolveToolVisibility,ScopeEntry,ToolHook,ToolNotFoundError}from"@frontmcp/sdk";import{z}from"@frontmcp/lazy-zod";var directCallsFilterSchema=z.custom(val=>typeof val==="function",{message:"filter must be a function with signature (tool: DirectCallsFilterToolInfo) => boolean"});var includeToolsFilterSchema=z.custom(val=>typeof val==="function",{message:"includeTools must be a function with signature (tool: IncludeToolsFilterToolInfo) => boolean"});var codeCallModeSchema=z.enum(["codecall_only","codecall_opt_in","metadata_driven"]).default("codecall_only");var codeCallVmPresetSchema=z.enum(["locked_down","secure","balanced","experimental"]).default("secure");var DEFAULT_VM_OPTIONS={preset:"secure"};var codeCallVmOptionsSchema=z.object({preset:codeCallVmPresetSchema,timeoutMs:z.number().positive().optional(),allowLoops:z.boolean().optional(),maxSteps:z.number().positive().optional(),disabledBuiltins:z.array(z.string()).optional(),disabledGlobals:z.array(z.string()).optional(),allowConsole:z.boolean().optional(),maxSanitizeDepth:z.number().positive().optional(),maxSanitizeProperties:z.number().positive().optional(),rapidEnumerationThreshold:z.number().int().positive().optional(),rapidEnumerationOverrides:z.record(z.string(),z.number().int().positive()).optional()}).default(()=>DEFAULT_VM_OPTIONS);var codeCallDirectCallsOptionsSchema=z.object({enabled:z.boolean(),allowedTools:z.array(z.string()).optional(),filter:directCallsFilterSchema.optional()});var embeddingStrategySchema=z.enum(["tfidf","ml"]).default("tfidf");var synonymExpansionConfigSchema=z.object({enabled:z.boolean().default(true),additionalSynonyms:z.array(z.array(z.string())).optional(),replaceDefaults:z.boolean().default(false),maxExpansionsPerTerm: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=z.object({strategy:embeddingStrategySchema.optional(),modelName:z.string().optional(),cacheDir:z.string().optional(),useHNSW:z.boolean().optional(),synonymExpansion:z.union([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=z.object({enabled:z.boolean().default(false),maxTotalSize:z.number().positive().optional(),maxReferenceSize:z.number().positive().optional(),extractionThreshold:z.number().positive().optional(),maxResolvedSize:z.number().positive().optional(),allowComposites:z.boolean().optional(),maxScriptLengthWhenDisabled:z.number().positive().nullable().default(64*1024)}).default(()=>({enabled:false,maxScriptLengthWhenDisabled:64*1024}));var codeCallPluginOptionsObjectSchema=z.object({mode:codeCallModeSchema,appIds:z.array(z.string()).optional(),topK:z.number().positive().default(8),maxDefinitions: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);import{BaseConfig,Provider,ProviderScope}from"@frontmcp/sdk";var CodeCallConfig=class extends BaseConfig{constructor(options={}){const parsedConfig=codeCallPluginOptionsSchema.parse(options);const resolvedVm=resolveVmOptions(parsedConfig.vm);super({...parsedConfig,resolvedVm})}};CodeCallConfig=__decorateClass([Provider({name:"codecall:config",description:"CodeCall plugin configuration with validated defaults",scope: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}}}import{getRunningTool}from"@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(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 typedScope=scope;const alias=/[-_]/.test(name)?name.includes("_")?name.replace(/_/g,"-"):name.replace(/-/g,"_"):void 0;const candidates=alias?[name,alias]:[name];const matches=entry=>candidates.includes(entry.fullName)||candidates.includes(entry.name);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)}}import{Provider as Provider2,ProviderScope as ProviderScope2}from"@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([Provider2({name:"codecall:audit-logger",scope:ProviderScope2.GLOBAL})],AuditLoggerService);import{TFIDFVectoria,VectoriaDB}from"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 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 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 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 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 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 VectoriaDB){return this.vectorDB.size()}else{return this.vectorDB.getDocumentCount()}}hasTool(toolName,surface){const indexed=this.vectorDB instanceof 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}};import{Enclave}from"@enclave-vm/core";import{Provider as Provider3,ProviderScope as ProviderScope3}from"@frontmcp/sdk";import{ForbiddenLoopRule,JSAstValidator,ValidationSeverity}from"@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
|
+
var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;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};import CachePlugin from"@frontmcp/plugin-cache";import{DynamicPlugin,FrontMcpLogger,FrontMcpToolTokens,isEntryGatedBy,ListToolsHook,Plugin,resolveToolVisibility,ScopeEntry,ToolHook,ToolNotFoundError}from"@frontmcp/sdk";import{z}from"@frontmcp/lazy-zod";var directCallsFilterSchema=z.custom(val=>typeof val==="function",{message:"filter must be a function with signature (tool: DirectCallsFilterToolInfo) => boolean"});var includeToolsFilterSchema=z.custom(val=>typeof val==="function",{message:"includeTools must be a function with signature (tool: IncludeToolsFilterToolInfo) => boolean"});var codeCallModeSchema=z.enum(["codecall_only","codecall_opt_in","metadata_driven"]).default("codecall_only");var codeCallVmPresetSchema=z.enum(["locked_down","secure","balanced","experimental"]).default("secure");var DEFAULT_VM_OPTIONS={preset:"secure"};var codeCallVmOptionsSchema=z.object({preset:codeCallVmPresetSchema,timeoutMs:z.number().positive().optional(),allowLoops:z.boolean().optional(),maxSteps:z.number().positive().optional(),disabledBuiltins:z.array(z.string()).optional(),disabledGlobals:z.array(z.string()).optional(),allowConsole:z.boolean().optional(),maxSanitizeDepth:z.number().positive().optional(),maxSanitizeProperties:z.number().positive().optional(),rapidEnumerationThreshold:z.number().int().positive().optional(),rapidEnumerationOverrides:z.record(z.string(),z.number().int().positive()).optional()}).default(()=>DEFAULT_VM_OPTIONS);var codeCallDirectCallsOptionsSchema=z.object({enabled:z.boolean(),allowedTools:z.array(z.string()).optional(),filter:directCallsFilterSchema.optional()});var embeddingStrategySchema=z.enum(["tfidf","ml"]).default("tfidf");var synonymExpansionConfigSchema=z.object({enabled:z.boolean().default(true),additionalSynonyms:z.array(z.array(z.string())).optional(),replaceDefaults:z.boolean().default(false),maxExpansionsPerTerm: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=z.object({strategy:embeddingStrategySchema.optional(),modelName:z.string().optional(),cacheDir:z.string().optional(),useHNSW:z.boolean().optional(),synonymExpansion:z.union([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=z.object({enabled:z.boolean().default(false),maxTotalSize:z.number().positive().optional(),maxReferenceSize:z.number().positive().optional(),extractionThreshold:z.number().positive().optional(),maxResolvedSize:z.number().positive().optional(),allowComposites:z.boolean().optional(),maxScriptLengthWhenDisabled:z.number().positive().nullable().default(64*1024)}).default(()=>({enabled:false,maxScriptLengthWhenDisabled:64*1024}));var codeCallPluginOptionsObjectSchema=z.object({mode:codeCallModeSchema,appIds:z.array(z.string()).optional(),topK:z.number().positive().default(8),maxDefinitions: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);import{BaseConfig,Provider,ProviderScope}from"@frontmcp/sdk";var CodeCallConfig=class extends BaseConfig{constructor(options={}){const parsedConfig=codeCallPluginOptionsSchema.parse(options);const resolvedVm=resolveVmOptions(parsedConfig.vm);super({...parsedConfig,resolvedVm})}};CodeCallConfig=__decorateClass([Provider({name:"codecall:config",description:"CodeCall plugin configuration with validated defaults",scope: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}}}import{getRunningTool}from"@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(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)}}import{Provider as Provider2,ProviderScope as ProviderScope2}from"@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([Provider2({name:"codecall:audit-logger",scope:ProviderScope2.GLOBAL})],AuditLoggerService);import{TFIDFVectoria,VectoriaDB}from"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 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 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 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 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 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 VectoriaDB){return this.vectorDB.size()}else{return this.vectorDB.getDocumentCount()}}hasTool(toolName,surface){const indexed=this.vectorDB instanceof 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}};import{Enclave}from"@enclave-vm/core";import{Provider as Provider3,ProviderScope as ProviderScope3}from"@frontmcp/sdk";import{ForbiddenLoopRule,JSAstValidator,ValidationSeverity}from"@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
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=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 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 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}import{isWrappedInMain,transformAgentScript}from"@enclave-vm/ast";import*as acorn from"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}
|
package/esm/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@frontmcp/plugin-codecall",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.11.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",
|
|
@@ -53,17 +53,17 @@
|
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@enclave-vm/ast": "^2.17.0",
|
|
55
55
|
"@enclave-vm/core": "^2.17.0",
|
|
56
|
-
"@frontmcp/protocol": "1.
|
|
56
|
+
"@frontmcp/protocol": "1.11.0-rc.1",
|
|
57
57
|
"acorn": "^8.15.0",
|
|
58
58
|
"vectoriadb": "^2.3.3"
|
|
59
59
|
},
|
|
60
60
|
"peerDependencies": {
|
|
61
|
-
"@frontmcp/lazy-zod": "1.
|
|
62
|
-
"@frontmcp/plugin-cache": "1.
|
|
63
|
-
"@frontmcp/sdk": "1.
|
|
61
|
+
"@frontmcp/lazy-zod": "1.11.0-rc.1",
|
|
62
|
+
"@frontmcp/plugin-cache": "1.11.0-rc.1",
|
|
63
|
+
"@frontmcp/sdk": "1.11.0-rc.1"
|
|
64
64
|
},
|
|
65
65
|
"devDependencies": {
|
|
66
|
-
"@frontmcp/sdk": "1.
|
|
66
|
+
"@frontmcp/sdk": "1.11.0-rc.1",
|
|
67
67
|
"reflect-metadata": "^0.2.2"
|
|
68
68
|
}
|
|
69
69
|
}
|
package/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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 typedScope=scope;const alias=/[-_]/.test(name)?name.includes("_")?name.replace(/_/g,"-"):name.replace(/-/g,"_"):void 0;const candidates=alias?[name,alias]:[name];const matches=entry=>candidates.includes(entry.fullName)||candidates.includes(entry.name);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_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__() {
|
|
2
2
|
${code}
|
|
3
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__() {
|
|
4
4
|
${script}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@frontmcp/plugin-codecall",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.11.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",
|
|
@@ -53,17 +53,17 @@
|
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@enclave-vm/ast": "^2.17.0",
|
|
55
55
|
"@enclave-vm/core": "^2.17.0",
|
|
56
|
-
"@frontmcp/protocol": "1.
|
|
56
|
+
"@frontmcp/protocol": "1.11.0-rc.1",
|
|
57
57
|
"acorn": "^8.15.0",
|
|
58
58
|
"vectoriadb": "^2.3.3"
|
|
59
59
|
},
|
|
60
60
|
"peerDependencies": {
|
|
61
|
-
"@frontmcp/lazy-zod": "1.
|
|
62
|
-
"@frontmcp/plugin-cache": "1.
|
|
63
|
-
"@frontmcp/sdk": "1.
|
|
61
|
+
"@frontmcp/lazy-zod": "1.11.0-rc.1",
|
|
62
|
+
"@frontmcp/plugin-cache": "1.11.0-rc.1",
|
|
63
|
+
"@frontmcp/sdk": "1.11.0-rc.1"
|
|
64
64
|
},
|
|
65
65
|
"devDependencies": {
|
|
66
|
-
"@frontmcp/sdk": "1.
|
|
66
|
+
"@frontmcp/sdk": "1.11.0-rc.1",
|
|
67
67
|
"reflect-metadata": "^0.2.2"
|
|
68
68
|
}
|
|
69
69
|
}
|
|
@@ -10,6 +10,7 @@ export interface CodeCallPolicyEntry {
|
|
|
10
10
|
fullName: string;
|
|
11
11
|
owner?: CodeCallPolicyOwner;
|
|
12
12
|
metadata?: {
|
|
13
|
+
aliases?: readonly string[];
|
|
13
14
|
description?: string;
|
|
14
15
|
tags?: string[];
|
|
15
16
|
hideFromDiscovery?: boolean;
|
|
@@ -121,17 +122,19 @@ export declare function denyUnknownTool(name: string): {
|
|
|
121
122
|
interface ResolvableEntry {
|
|
122
123
|
name: string;
|
|
123
124
|
fullName: string;
|
|
125
|
+
metadata?: {
|
|
126
|
+
aliases?: readonly string[];
|
|
127
|
+
};
|
|
124
128
|
}
|
|
125
129
|
/**
|
|
126
130
|
* Resolve a tool name exactly as `call-tool.flow.ts` `findTool` does.
|
|
127
131
|
*
|
|
128
132
|
* MUST mirror that stage. The policy has to evaluate the same entry the flow will execute:
|
|
129
133
|
* resolve more narrowly and legitimate remote-app tools get denied; resolve more loosely and
|
|
130
|
-
* a tool reachable only through the flow's fallback escapes the policy entirely.
|
|
131
|
-
*
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
* 3. remote app registries, for tools whose subscription has not yet propagated.
|
|
134
|
+
* a tool reachable only through the flow's fallback escapes the policy entirely. Like the flow,
|
|
135
|
+
* this matches a tool's declared aliases (`@Tool({ aliases })`) first, then its name or a
|
|
136
|
+
* hyphen <-> underscore spelling of it (issue #408), each in the scope registry and then in
|
|
137
|
+
* remote app registries, for tools whose subscription has not yet propagated.
|
|
135
138
|
*/
|
|
136
139
|
export declare function resolveCodeCallTool<T extends ResolvableEntry>(scope: unknown, name: string): T | undefined;
|
|
137
140
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codecall-tool-policy.d.ts","sourceRoot":"","sources":["../../src/security/codecall-tool-policy.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EACV,6BAA6B,EAC7B,0BAA0B,EAC1B,YAAY,EACZ,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,0BAA0B,EAC3B,MAAM,mBAAmB,CAAC;AAK3B,oFAAoF;AACpF,UAAU,mBAAmB;IAC3B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,EAAE,CAAC,EAAE,MAAM,CAAC;CACb;AAED,2FAA2F;AAC3F,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,mBAAmB,CAAC;IAC5B,QAAQ,CAAC,EAAE;QACT,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;QAChB,iBAAiB,CAAC,EAAE,OAAO,CAAC;QAC5B,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,QAAQ,CAAC,EAAE,oBAAoB,CAAC;QAChC,WAAW,CAAC,EAAE,6BAA6B,CAAC;QAC5C,aAAa,CAAC,EAAE;YAAE,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;SAAE,CAAC;KACjD,CAAC;CACH;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,aAAa,EAAE;IAAE,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,GAAG,SAAS,EAC1D,OAAO,EAAE,MAAM,GAAG,SAAS,GAC1B,OAAO,CAGT;AAED,2EAA2E;AAC3E,MAAM,WAAW,kBAAkB;IACjC,kFAAkF;IAClF,IAAI,EAAE,MAAM,CAAC;IACb,kFAAkF;IAClF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,EAAE,oBAAoB,CAAC;IAChC,+EAA+E;IAC/E,WAAW,CAAC,EAAE,6BAA6B,CAAC;IAC5C,iFAAiF;IACjF,QAAQ,CAAC,EAAE,0BAA0B,CAAC;CACvC;AAED,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,YAAY,CAAC;IACnB,YAAY,CAAC,EAAE,oBAAoB,CAAC;CACrC;AAED,wFAAwF;AACxF,MAAM,WAAW,yBAAyB;IACxC,OAAO,EAAE,OAAO,CAAC;IACjB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,MAAM,CAAC,EAAE,mBAAmB,CAAC;CAC9B;AAED,MAAM,MAAM,sBAAsB,GAAG;IAAE,OAAO,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,OAAO,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAE5F,+FAA+F;AAC/F,MAAM,MAAM,kBAAkB,CAAC,CAAC,IAAI;IAAE,OAAO,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,GAAG;IAAE,OAAO,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAYrG;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,mBAAmB,GAAG,MAAM,GAAG,SAAS,CAI9F;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,mBAAmB,EAC1B,aAAa,CAAC,EAAE,MAAM,EACtB,KAAK,CAAC,EAAE,OAAO,GACd,kBAAkB,CAgBpB;AAkCD;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,kBAAkB,GAAG,0BAA0B,CAgBrF;AAMD;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACrC,IAAI,EAAE,kBAAkB,EACxB,MAAM,EAAE,oBAAoB,GAC3B,sBAAsB,CA4CxB;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,OAAO,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAEhF;AAED,UAAU,eAAe;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"codecall-tool-policy.d.ts","sourceRoot":"","sources":["../../src/security/codecall-tool-policy.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EACV,6BAA6B,EAC7B,0BAA0B,EAC1B,YAAY,EACZ,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,0BAA0B,EAC3B,MAAM,mBAAmB,CAAC;AAK3B,oFAAoF;AACpF,UAAU,mBAAmB;IAC3B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,EAAE,CAAC,EAAE,MAAM,CAAC;CACb;AAED,2FAA2F;AAC3F,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,mBAAmB,CAAC;IAC5B,QAAQ,CAAC,EAAE;QACT,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;QAC5B,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;QAChB,iBAAiB,CAAC,EAAE,OAAO,CAAC;QAC5B,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,QAAQ,CAAC,EAAE,oBAAoB,CAAC;QAChC,WAAW,CAAC,EAAE,6BAA6B,CAAC;QAC5C,aAAa,CAAC,EAAE;YAAE,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;SAAE,CAAC;KACjD,CAAC;CACH;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,aAAa,EAAE;IAAE,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,GAAG,SAAS,EAC1D,OAAO,EAAE,MAAM,GAAG,SAAS,GAC1B,OAAO,CAGT;AAED,2EAA2E;AAC3E,MAAM,WAAW,kBAAkB;IACjC,kFAAkF;IAClF,IAAI,EAAE,MAAM,CAAC;IACb,kFAAkF;IAClF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,EAAE,oBAAoB,CAAC;IAChC,+EAA+E;IAC/E,WAAW,CAAC,EAAE,6BAA6B,CAAC;IAC5C,iFAAiF;IACjF,QAAQ,CAAC,EAAE,0BAA0B,CAAC;CACvC;AAED,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,YAAY,CAAC;IACnB,YAAY,CAAC,EAAE,oBAAoB,CAAC;CACrC;AAED,wFAAwF;AACxF,MAAM,WAAW,yBAAyB;IACxC,OAAO,EAAE,OAAO,CAAC;IACjB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,MAAM,CAAC,EAAE,mBAAmB,CAAC;CAC9B;AAED,MAAM,MAAM,sBAAsB,GAAG;IAAE,OAAO,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,OAAO,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAE5F,+FAA+F;AAC/F,MAAM,MAAM,kBAAkB,CAAC,CAAC,IAAI;IAAE,OAAO,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,GAAG;IAAE,OAAO,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAYrG;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,mBAAmB,GAAG,MAAM,GAAG,SAAS,CAI9F;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,mBAAmB,EAC1B,aAAa,CAAC,EAAE,MAAM,EACtB,KAAK,CAAC,EAAE,OAAO,GACd,kBAAkB,CAgBpB;AAkCD;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,kBAAkB,GAAG,0BAA0B,CAgBrF;AAMD;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACrC,IAAI,EAAE,kBAAkB,EACxB,MAAM,EAAE,oBAAoB,GAC3B,sBAAsB,CA4CxB;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,OAAO,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAEhF;AAED,UAAU,eAAe;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;KAAE,CAAC;CAC5C;AAWD;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,SAAS,eAAe,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,GAAG,CAAC,GAAG,SAAS,CAW1G;AAsBD;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,kBAAkB,EACxB,WAAW,EAAE,yBAAyB,GAAG,SAAS,GACjD,sBAAsB,CAmBxB;AAED,UAAU,kBAAkB;IAC1B,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CAC3B;AAED,2DAA2D;AAC3D,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,kBAAkB,GAAG,oBAAoB,CAQzF;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,uBAAuB,CAAC,CAAC,SAAS,mBAAmB,GAAG,mBAAmB,EACzF,KAAK,EAAE,OAAO,EACd,MAAM,EAAE,kBAAkB,EAC1B,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,OAAO,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAO,GACvD,kBAAkB,CAAC,CAAC,CAAC,CAsBvB"}
|