@smythos/sre 1.7.41 → 1.7.42

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/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import dotenv from"dotenv";import Joi from"joi";import pLimit from"p-limit";import axios,{AxiosHeaders}from"axios";import*as fs from"fs";import fs__default,{existsSync,mkdirSync,writeFileSync,readFileSync,unlinkSync}from"fs";import*as FileType from"file-type";import{fileTypeFromBuffer}from"file-type";import{isBinaryFileSync}from"isbinaryfile";import*as readlineSync from"readline-sync";import{stdin,stdout}from"process";import"dotenv/config";import winston from"winston";import Transport from"winston-transport";import EventEmitter$1,{EventEmitter}from"events";import crypto$1,{createHash,randomUUID,createHmac,timingSafeEqual}from"crypto";import path from"path";import os from"os";import mime from"mime";import{encodeChat,encode}from"gpt-tokenizer";import{Readable}from"stream";import{jsonrepair}from"jsonrepair";import xxhash from"xxhashjs";import yaml from"js-yaml";import{EventSource}from"eventsource";import*as acorn from"acorn";import dayjs from"dayjs";import imageSize from"image-size";import querystring from"querystring";import{HfInference}from"@huggingface/inference";import{Runware}from"@runware/sdk-js";import FormData from"form-data";import{SocksProxyAgent}from"socks-proxy-agent";import OAuth from"oauth-1.0a";import OpenAI$1,{OpenAI,toFile}from"openai";import{GoogleGenAI}from"@google/genai";import zl from"zip-lib";import{GetFunctionCommand,UpdateFunctionCodeCommand,Runtime,InvokeCommand,LambdaClient,UpdateFunctionConfigurationCommand,CreateFunctionCommand}from"@aws-sdk/client-lambda";import{GetRoleCommand,CreateRoleCommand,IAMClient}from"@aws-sdk/client-iam";import{Client}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{findAll,isTag,removeElement,innerText}from"domutils";import{parseDocument}from"htmlparser2";import{GetBucketLifecycleConfigurationCommand,PutBucketLifecycleConfigurationCommand,S3Client,HeadObjectCommand,DeleteObjectCommand,GetObjectCommand,PutObjectCommand,PutObjectTaggingCommand,GetObjectTaggingCommand,CopyObjectCommand}from"@aws-sdk/client-s3";import{createServer}from"http";import{WebSocketServer}from"ws";import"ses";import{execSync}from"child_process";import{Pinecone}from"@pinecone-database/pinecone";import{MilvusClient,DataType,ErrorCode}from"@zilliz/milvus2-sdk-node";import{GoogleGenAI as GoogleGenAI$1,FunctionCallingConfigMode,FileState}from"@google/genai/node";import Anthropic from"@anthropic-ai/sdk";import Groq from"groq-sdk";import{BedrockRuntimeClient,ConverseCommand,ConverseStreamCommand}from"@aws-sdk/client-bedrock-runtime";import{VertexAI}from"@google-cloud/vertexai";import{Ollama}from"ollama";import*as chokidar from"chokidar";import chokidar__default from"chokidar";import fs$1 from"fs/promises";import IORedis from"ioredis";import{trace,context,propagation,SpanStatusCode}from"@opentelemetry/api";import{logs,SeverityNumber}from"@opentelemetry/api-logs";import{resourceFromAttributes}from"@opentelemetry/resources";import{ATTR_SERVICE_VERSION,ATTR_SERVICE_NAME}from"@opentelemetry/semantic-conventions";import{BatchSpanProcessor,NodeTracerProvider}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter}from"@opentelemetry/exporter-trace-otlp-http";import{BatchLogRecordProcessor,LoggerProvider}from"@opentelemetry/sdk-logs";import{OTLPLogExporter}from"@opentelemetry/exporter-logs-otlp-http";import mysql from"mysql2/promise";import{SecretsManagerClient,ListSecretsCommand,GetSecretValueCommand,PutSecretValueCommand,CreateSecretCommand,DescribeSecretCommand,RestoreSecretCommand,DeleteSecretCommand}from"@aws-sdk/client-secrets-manager";var version="1.7.41",pkg={version};dotenv.config();const config={env:{LOG_LEVEL:process.env.LOG_LEVEL||"none",LOG_FILTER:process.env.LOG_FILTER||"",NODE_ENV:process.env?.NODE_ENV,ROLLOUT_RAG_V2:process.env.ROLLOUT_RAG_V2}},REQUEST_METHODS=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],REQUEST_CONTENT_TYPES={none:"none",urlEncodedFormData:"application/x-www-form-urlencoded",multipartFormData:"multipart/form-data",json:"application/json",text:"text/plain",xml:"application/xml",binary:"binary"};var EMBODIMENT_TYPES=(EMBODIMENT_TYPES2=>(EMBODIMENT_TYPES2.ChatBot="chatBot",EMBODIMENT_TYPES2.ChatGPT="chatGPT",EMBODIMENT_TYPES2))(EMBODIMENT_TYPES||{});const ERR_MSG_INVALID_IMAGE_SOURCE="Please provide a valid Image Source. Supported image sources are: HTTP(S) URL, Base64 string, Data URL, Output Image from other component(s).",ERR_MSG_INVALID_BINARY="Please provide a valid data that is either a Blob, SmythFileObject (Binary Output from any Component), ArrayBuffer, Buffer, Base64 string, Data URL, or HTTP(s) URL",ERR_MSG_MAX_DEPTH="The maximum depth has been exceeded for the provided array or object.",ERR_MSG_MAX_ARRAY_SIZE="The maximum array size has been exceeded for the provided array.",ERR_MSG_MAX_OBJECT_SIZE="The maximum object size has been exceeded for the provided object.",MAX_DEPTH=10,MAX_OBJECT_SIZE=1e3,MAX_ARRAY_SIZE=1e3,MAX_FILE_SIZE=10*1024*1024,MAX_FILE_COUNT=10,DEFAULT_MAX_TOKENS_FOR_LLM=2048,S3_DAILY_PURGE_LIFECYCLE_TAG="ExpirationPolicy=DeleteDaily",S3_WEEKLY_PURGE_LIFECYCLE_TAG="ExpirationPolicy=DeleteWeekly",S3_MONTHLY_PURGE_LIFECYCLE_TAG="ExpirationPolicy=DeleteMonthly",TOOL_USE_DEFAULT_MODEL="gpt-4o-mini",COMP_NAMES={apiCall:"APICall",code:"Code",llmPrompt:"PromptGenerator",visionLLM:"VisionLLM"},JSON_RESPONSE_INSTRUCTION=`
1
+ import dotenv from"dotenv";import Joi from"joi";import pLimit from"p-limit";import axios,{AxiosHeaders}from"axios";import*as fs from"fs";import fs__default,{existsSync,mkdirSync,writeFileSync,readFileSync,unlinkSync}from"fs";import*as FileType from"file-type";import{fileTypeFromBuffer}from"file-type";import{isBinaryFileSync}from"isbinaryfile";import*as readlineSync from"readline-sync";import{stdin,stdout}from"process";import"dotenv/config";import winston from"winston";import Transport from"winston-transport";import EventEmitter$1,{EventEmitter}from"events";import crypto$1,{createHash,randomUUID,createHmac,timingSafeEqual}from"crypto";import path from"path";import os from"os";import mime from"mime";import{encodeChat,encode}from"gpt-tokenizer";import{Readable}from"stream";import{jsonrepair}from"jsonrepair";import xxhash from"xxhashjs";import yaml from"js-yaml";import{EventSource}from"eventsource";import*as acorn from"acorn";import dayjs from"dayjs";import imageSize from"image-size";import querystring from"querystring";import{HfInference}from"@huggingface/inference";import{Runware}from"@runware/sdk-js";import FormData from"form-data";import{SocksProxyAgent}from"socks-proxy-agent";import OAuth from"oauth-1.0a";import OpenAI$1,{OpenAI,toFile}from"openai";import{GoogleGenAI}from"@google/genai";import zl from"zip-lib";import{GetFunctionCommand,UpdateFunctionCodeCommand,Runtime,InvokeCommand,LambdaClient,UpdateFunctionConfigurationCommand,CreateFunctionCommand}from"@aws-sdk/client-lambda";import{GetRoleCommand,CreateRoleCommand,IAMClient}from"@aws-sdk/client-iam";import{Client}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{findAll,isTag,removeElement,innerText}from"domutils";import{parseDocument}from"htmlparser2";import{GetBucketLifecycleConfigurationCommand,PutBucketLifecycleConfigurationCommand,S3Client,HeadObjectCommand,DeleteObjectCommand,GetObjectCommand,PutObjectCommand,PutObjectTaggingCommand,GetObjectTaggingCommand,CopyObjectCommand}from"@aws-sdk/client-s3";import{createServer}from"http";import{WebSocketServer}from"ws";import"ses";import{execSync}from"child_process";import{Pinecone}from"@pinecone-database/pinecone";import{MilvusClient,DataType,ErrorCode}from"@zilliz/milvus2-sdk-node";import{GoogleGenAI as GoogleGenAI$1,FunctionCallingConfigMode,FileState}from"@google/genai/node";import Anthropic from"@anthropic-ai/sdk";import Groq from"groq-sdk";import{BedrockRuntimeClient,ConverseCommand,ConverseStreamCommand}from"@aws-sdk/client-bedrock-runtime";import{VertexAI}from"@google-cloud/vertexai";import{Ollama}from"ollama";import*as chokidar from"chokidar";import chokidar__default from"chokidar";import fs$1 from"fs/promises";import IORedis from"ioredis";import{trace,context,propagation,SpanStatusCode}from"@opentelemetry/api";import{logs,SeverityNumber}from"@opentelemetry/api-logs";import{resourceFromAttributes}from"@opentelemetry/resources";import{ATTR_SERVICE_VERSION,ATTR_SERVICE_NAME}from"@opentelemetry/semantic-conventions";import{BatchSpanProcessor,NodeTracerProvider}from"@opentelemetry/sdk-trace-node";import{OTLPTraceExporter}from"@opentelemetry/exporter-trace-otlp-http";import{BatchLogRecordProcessor,LoggerProvider}from"@opentelemetry/sdk-logs";import{OTLPLogExporter}from"@opentelemetry/exporter-logs-otlp-http";import mysql from"mysql2/promise";import{SecretsManagerClient,ListSecretsCommand,GetSecretValueCommand,PutSecretValueCommand,CreateSecretCommand,DescribeSecretCommand,RestoreSecretCommand,DeleteSecretCommand}from"@aws-sdk/client-secrets-manager";var version="1.7.42",pkg={version};dotenv.config();const config={env:{LOG_LEVEL:process.env.LOG_LEVEL||"none",LOG_FILTER:process.env.LOG_FILTER||"",NODE_ENV:process.env?.NODE_ENV,ROLLOUT_RAG_V2:process.env.ROLLOUT_RAG_V2}},REQUEST_METHODS=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],REQUEST_CONTENT_TYPES={none:"none",urlEncodedFormData:"application/x-www-form-urlencoded",multipartFormData:"multipart/form-data",json:"application/json",text:"text/plain",xml:"application/xml",binary:"binary"};var EMBODIMENT_TYPES=(EMBODIMENT_TYPES2=>(EMBODIMENT_TYPES2.ChatBot="chatBot",EMBODIMENT_TYPES2.ChatGPT="chatGPT",EMBODIMENT_TYPES2))(EMBODIMENT_TYPES||{});const ERR_MSG_INVALID_IMAGE_SOURCE="Please provide a valid Image Source. Supported image sources are: HTTP(S) URL, Base64 string, Data URL, Output Image from other component(s).",ERR_MSG_INVALID_BINARY="Please provide a valid data that is either a Blob, SmythFileObject (Binary Output from any Component), ArrayBuffer, Buffer, Base64 string, Data URL, or HTTP(s) URL",ERR_MSG_MAX_DEPTH="The maximum depth has been exceeded for the provided array or object.",ERR_MSG_MAX_ARRAY_SIZE="The maximum array size has been exceeded for the provided array.",ERR_MSG_MAX_OBJECT_SIZE="The maximum object size has been exceeded for the provided object.",MAX_DEPTH=10,MAX_OBJECT_SIZE=1e3,MAX_ARRAY_SIZE=1e3,MAX_FILE_SIZE=10*1024*1024,MAX_FILE_COUNT=10,DEFAULT_MAX_TOKENS_FOR_LLM=2048,S3_DAILY_PURGE_LIFECYCLE_TAG="ExpirationPolicy=DeleteDaily",S3_WEEKLY_PURGE_LIFECYCLE_TAG="ExpirationPolicy=DeleteWeekly",S3_MONTHLY_PURGE_LIFECYCLE_TAG="ExpirationPolicy=DeleteMonthly",TOOL_USE_DEFAULT_MODEL="gpt-4o-mini",COMP_NAMES={apiCall:"APICall",code:"Code",llmPrompt:"PromptGenerator",visionLLM:"VisionLLM"},JSON_RESPONSE_INSTRUCTION=`
2
2
  Respond ONLY with a valid, parsable JSON object. Follow these strict guidelines:
3
3
  1. The response must begin with '{' and end with '}'.
4
4
  2. Use double quotes for all keys and string values.
@@ -290,5 +290,5 @@ ${error}
290
290
  const result = await main(${getParametersString(parameters,inputs)});
291
291
  return result;
292
292
  })();
293
- `}var __defProp$7=Object.defineProperty,__defNormalProp$7=(obj,key,value)=>key in obj?__defProp$7(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$7=(obj,key,value)=>__defNormalProp$7(obj,typeof key!="symbol"?key+"":key,value);const console$2=Logger("ECMASandbox");class ECMASandbox2 extends CodeConnector{constructor(config2){super(config2),__publicField$7(this,"name","ECMASandbox"),__publicField$7(this,"sandboxUrl"),this.sandboxUrl=config2.sandboxUrl}async prepare(acRequest,codeUID,input,config2){return{prepared:!0,errors:[],warnings:[]}}async deploy(acRequest,codeUID,input,config2){return{id:codeUID,runtime:config2.runtime,createdAt:new Date,status:"Deployed"}}async execute(acRequest,codeUID,inputs,config2){try{const{isValid,error,parameters}=validateAsyncMainFunction(inputs.code);if(!isValid)return{output:void 0,executionTime:0,success:!1,errors:[error]};const executableCode=generateExecutableCode(inputs.code,parameters,inputs.inputs);if(this.sandboxUrl){console$2.debug("Running code in remote sandbox");const executionStartTime=Date.now(),result=await axios.post(this.sandboxUrl,{code:executableCode}).catch(error2=>({error:error2})),executionTime=Date.now()-executionStartTime;if(result.error){const error2=result.error?.response?.data||result.error?.message||result.error.toString()||"Unknown error";return console$2.error(`Error running code: ${JSON.stringify(error2,null,2)}`),{output:void 0,executionTime,success:!1,errors:[error2]}}else return console$2.debug(`Code result: ${result?.data?.Output}`),{output:result.data?.Output,executionTime,success:!0,errors:[]}}else{console$2.debug("Running code in isolated vm");const executionStartTime=Date.now(),result=await runJs(executableCode),executionTime=Date.now()-executionStartTime;return console$2.debug(`Code result: ${result}`),{output:result,executionTime,success:!0,errors:[]}}}catch(error){return console$2.error(`Error running code: ${error}`),{output:void 0,executionTime:0,success:!1,errors:[error]}}}async executeDeployment(acRequest,codeUID,deploymentId,inputs,config2){return await this.execute(acRequest,codeUID,inputs,config2)}async listDeployments(acRequest,codeUID,config2){return[]}async getDeployment(acRequest,codeUID,deploymentId,config2){return null}async deleteDeployment(acRequest,codeUID,deploymentId){}async getResourceACL(resourceId,candidate){const acl=new ACL;return acl.addAccess(candidate.role,candidate.id,TAccessLevel.Read),acl}}class CodeService extends ConnectorServiceProvider{register(){ConnectorService.register(TConnectorService.Code,"AWSLambda",AWSLambdaCode),ConnectorService.register(TConnectorService.Code,"ECMASandbox",ECMASandbox2)}}var __defProp$6=Object.defineProperty,__defNormalProp$6=(obj,key,value)=>key in obj?__defProp$6(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$6=(obj,key,value)=>__defNormalProp$6(obj,key+"",value);class SchedulerConnector extends SecureConnector{constructor(settings){super(settings),__publicField$6(this,"_eventEmitter"),this._eventEmitter=new EventEmitter$1}requester(candidate){return{list:async()=>await this.list(candidate.readRequest),add:async(jobId,job,schedule)=>{const accountConnector=ConnectorService.getAccountConnector(),agentTeam=await accountConnector.getCandidateTeam(AccessCandidate.agent(job.agentId)),candidateTeam=await accountConnector.getCandidateTeam(candidate);if(agentTeam!==candidateTeam)throw new Error(`Candidate ${candidate.id} is not authorized to schedule a job for agent ${job.agentId}`);await this.add(candidate.writeRequest,jobId,job,schedule)},delete:async jobId=>{await this.delete(candidate.writeRequest,jobId)},get:async jobId=>await this.get(candidate.readRequest,jobId),pause:async jobId=>{await this.pause(candidate.writeRequest,jobId)},resume:async jobId=>{await this.resume(candidate.writeRequest,jobId)},on:(event,listener)=>{this.on(event,listener)},off:(event,listener)=>{this.off(event,listener)}}}constructJobKey(candidate,jobId){return`${candidate.role}_${candidate.id}_${jobId}`}emit(event,...args){return this._eventEmitter.emit(event,...args)}on(event,listener){return this._eventEmitter.on(event,listener),this}off(event,listener){return this._eventEmitter.off(event,listener),this}}var __defProp$5=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__defNormalProp$5=(obj,key,value)=>key in obj?__defProp$5(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__decorateClass$1=(decorators,target,key,kind)=>{for(var result=__getOwnPropDesc$1(target,key),i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=decorator(target,key,result)||result);return result&&__defProp$5(target,key,result),result},__publicField$5=(obj,key,value)=>__defNormalProp$5(obj,typeof key!="symbol"?key+"":key,value);const logger$2=Logger("LocalScheduler"),_LocalScheduler=class _LocalScheduler2 extends SchedulerConnector{constructor(_settings){super(_settings),this._settings=_settings,__publicField$5(this,"name","LocalScheduler"),__publicField$5(this,"id","local"),__publicField$5(this,"folder"),__publicField$5(this,"jobsPrefix","jobs"),__publicField$5(this,"runtimePrefix",".jobs.runtime"),__publicField$5(this,"isInitialized",!1),__publicField$5(this,"config"),this.config={folder:_settings?.folder||"",runJobs:_settings?.runJobs!==!1,persistExecutionHistory:_settings?.persistExecutionHistory!==!1,maxHistoryEntries:_settings?.maxHistoryEntries||100},this.folder=this.findSchedulerFolder(this.config.folder),this.initialize(),fs__default.existsSync(this.folder)||logger$2.warn(`Invalid folder provided: ${this.folder}`)}findSchedulerFolder(folder){let _schedulerFolder=folder;return _schedulerFolder&&fs__default.existsSync(_schedulerFolder)?_schedulerFolder:(_schedulerFolder=findSmythPath("scheduler"),fs__default.existsSync(_schedulerFolder)?(logger$2.warn("Using alternative scheduler folder found in : ",_schedulerFolder),_schedulerFolder):(logger$2.warn("!!! All attempts to find an existing scheduler folder failed !!!"),logger$2.warn("!!! I will use this folder: ",_schedulerFolder),_schedulerFolder))}async initialize(){const jobsFolderPath=path.join(this.folder,this.jobsPrefix);fs__default.existsSync(jobsFolderPath)||(fs__default.mkdirSync(jobsFolderPath,{recursive:!0}),fs__default.writeFileSync(path.join(jobsFolderPath,"README_IMPORTANT.txt"),"This folder contains scheduler job configurations. Do not delete it."));const runtimeFolderPath=path.join(this.folder,this.runtimePrefix);fs__default.existsSync(runtimeFolderPath)||(fs__default.mkdirSync(runtimeFolderPath,{recursive:!0}),fs__default.writeFileSync(path.join(runtimeFolderPath,"README_IMPORTANT.txt"),"This folder contains scheduler runtime data and execution history. Safe to delete if needed.")),this.config.runJobs&&await this.loadJobsFromDisk(),this.isInitialized=!0,logger$2.info(`LocalScheduler initialized (runJobs: ${this.config.runJobs})`)}getCandidateFolderName(candidate){return`${candidate.id}.${candidate.role}`}getJobFilePath(candidate,jobId,createFoldersIfNotExists=!1){const candidateFolder=this.getCandidateFolderName(candidate),jobFilename=jobId,fullPath=path.join(this.folder,this.jobsPrefix,candidateFolder,`${jobFilename}.json`);if(createFoldersIfNotExists){const folder=path.dirname(fullPath);fs__default.existsSync(folder)||fs__default.mkdirSync(folder,{recursive:!0})}return fullPath}getRuntimeFilePath(candidate,jobId,createFoldersIfNotExists=!1){const candidateFolder=this.getCandidateFolderName(candidate),jobFilename=jobId,fullPath=path.join(this.folder,this.runtimePrefix,candidateFolder,`${jobFilename}.json`);if(createFoldersIfNotExists){const folder=path.dirname(fullPath);fs__default.existsSync(folder)||fs__default.mkdirSync(folder,{recursive:!0})}return fullPath}async loadJobsFromDisk(){try{const jobsFolderPath=path.join(this.folder,this.jobsPrefix);if(!fs__default.existsSync(jobsFolderPath))return;const candidateFolders=fs__default.readdirSync(jobsFolderPath).filter(f=>{const fullPath=path.join(jobsFolderPath,f);return fs__default.statSync(fullPath).isDirectory()});for(const candidateFolder of candidateFolders){const lastDotIndex=candidateFolder.lastIndexOf(".");if(lastDotIndex===-1){logger$2.warn(`Invalid candidate folder format: ${candidateFolder}`);continue}const candidateId=candidateFolder.substring(0,lastDotIndex),candidateRole=candidateFolder.substring(lastDotIndex+1),candidate={id:candidateId,role:candidateRole},candidatePath=path.join(jobsFolderPath,candidateFolder),jobFiles=fs__default.readdirSync(candidatePath).filter(f=>f.endsWith(".json"));for(const file of jobFiles)try{const filePath=path.join(candidatePath,file),data=fs__default.readFileSync(filePath,"utf-8"),jobConfig=JSON.parse(data),runtimeData=await this.loadRuntimeDataFromDisk(candidate,jobConfig.id),jobData={...jobConfig,...runtimeData,candidateRole:candidate.role,candidateId:candidate.id},jobKey=this.constructJobKey(candidate,jobData.id);_LocalScheduler2.jobs.set(jobKey,jobData),jobData.status==="active"&&(logger$2.info(`Job ${jobData.id} loaded from ${candidateFolder} and scheduled for execution`),await this.scheduleJob(jobData))}catch(error){logger$2.warn(`Error loading job file ${file} from ${candidateFolder}:`,error)}}logger$2.info(`Loaded ${_LocalScheduler2.jobs.size} jobs from disk`)}catch(error){logger$2.warn("Error loading jobs from disk",error)}}async saveJobToDisk(candidate,jobData){try{const filePath=this.getJobFilePath(candidate,jobData.id,!0),{executionHistory,lastRun,nextRun,candidateRole,candidateId,createdBy,...configData}=jobData;fs__default.writeFileSync(filePath,JSON.stringify(configData,null,2),"utf-8")}catch(error){throw logger$2.warn(`Error saving job ${jobData.id} to disk`,error),error}}async saveRuntimeDataToDisk(candidate,jobData){try{const filePath=this.getRuntimeFilePath(candidate,jobData.id,!0),runtimeData={executionHistory:jobData.executionHistory||[],lastRun:jobData.lastRun,nextRun:jobData.nextRun};fs__default.writeFileSync(filePath,JSON.stringify(runtimeData,null,2),"utf-8")}catch(error){logger$2.warn(`Error saving runtime data for job ${jobData.id}`,error);return}}async loadRuntimeDataFromDisk(candidate,jobId){try{const filePath=this.getRuntimeFilePath(candidate,jobId);if(!fs__default.existsSync(filePath))return{};const data=fs__default.readFileSync(filePath,"utf-8");return JSON.parse(data)}catch(error){return logger$2.warn(`Error loading runtime data for job ${jobId}`,error),{}}}async deleteJobFromDisk(candidate,jobId){try{const jobFilePath=this.getJobFilePath(candidate,jobId);fs__default.existsSync(jobFilePath)&&fs__default.unlinkSync(jobFilePath);const runtimeFilePath=this.getRuntimeFilePath(candidate,jobId);fs__default.existsSync(runtimeFilePath)&&fs__default.unlinkSync(runtimeFilePath)}catch(error){logger$2.warn(`Error deleting job ${jobId} from disk`,error);return}}async scheduleJob(jobData){if(jobData.status!=="active")return;const validation=Schedule.fromJSON(jobData.schedule).validate();if(!validation.valid)throw logger$2.warn(`Invalid schedule for job ${jobData.id}: ${validation.error}`),new Error(`Invalid schedule for job ${jobData.id}: ${validation.error}`);const jobKey=this.constructJobKey({role:jobData.candidateRole,id:jobData.candidateId},jobData.id),existingTimer=_LocalScheduler2.timers.get(jobKey);if(existingTimer&&(logger$2.info(`Clearing existing timer for job ${jobData.id} (overwriting duplicate schedule)`),clearInterval(existingTimer),_LocalScheduler2.timers.delete(jobKey)),jobData.schedule.interval){const intervalMs=Schedule.parseInterval(jobData.schedule.interval),timer=setInterval(async()=>{await this.executeJob(jobData)},intervalMs);timer.unref(),_LocalScheduler2.timers.set(jobKey,timer)}if(jobData.schedule.cron)throw logger$2.warn(`Cron scheduling not yet implemented for job ${jobData.id}`),new Error(`Cron scheduling not yet implemented for job ${jobData.id}`)}async unscheduleJob(jobKey){const timer=_LocalScheduler2.timers.get(jobKey);timer&&(clearInterval(timer),_LocalScheduler2.timers.delete(jobKey))}async executeJob(jobData){if(!jobData.jobConfig){logger$2.warn(`Skipping execution of job ${jobData.id}: job configuration not available.`);return}const schedule=Schedule.fromJSON(jobData.schedule);if(!schedule.shouldRun()){logger$2.info(`Job ${jobData.id} skipped - outside schedule window`);return}const job=Job.fromJSON(jobData.jobConfig);logger$2.debug(`Executing job ${jobData.id} with metadata:`,JSON.stringify(jobData.jobConfig.metadata));const owner=jobData.createdBy;this.emit("executing",{id:jobData.id,job,owner});const result=await job.executeWithRetry();this.emit("executed",{id:jobData.id,job,owner,result}),jobData.lastRun=new Date().toISOString();const nextRun=schedule.calculateNextRun(new Date(jobData.lastRun));jobData.nextRun=nextRun?nextRun.toISOString():void 0,result.success||logger$2.warn(`Job ${jobData.id} failed:`,result.error?.message),this.config.persistExecutionHistory&&(jobData.executionHistory||(jobData.executionHistory=[]),jobData.executionHistory.unshift({timestamp:new Date().toISOString(),success:result.success,error:result.error?.message,executionTime:result.executionTime,retries:result.retries}),jobData.executionHistory.length>this.config.maxHistoryEntries&&(jobData.executionHistory=jobData.executionHistory.slice(0,this.config.maxHistoryEntries)));const candidate={role:jobData.candidateRole,id:jobData.candidateId};await this.saveJobToDisk(candidate,jobData),this.config.persistExecutionHistory&&await this.saveRuntimeDataToDisk(candidate,jobData)}async getResourceACL(resourceId,candidate){this.isInitialized||await this.initialize();const accountConnector=ConnectorService.getAccountConnector(),teamId=await accountConnector.getCandidateTeam(candidate),jobKey=this.constructJobKey(candidate,resourceId),jobData=_LocalScheduler2.jobs.get(jobKey),jobAgentTeamId=jobData?.jobConfig?.agentId?await accountConnector.getCandidateTeam(AccessCandidate.agent(jobData?.jobConfig?.agentId)):null;return jobAgentTeamId&&teamId!==jobAgentTeamId?new ACL:jobData?ACL.from(jobData.acl):new ACL().addAccess(candidate.role,candidate.id,TAccessLevel.Owner)}async list(acRequest){this.isInitialized||await this.initialize();const result=[];for(const[key,jobData]of _LocalScheduler2.jobs)if(jobData.candidateRole===acRequest.candidate.role&&jobData.candidateId===acRequest.candidate.id){const{candidateRole,candidateId,...serializableData}=jobData;result.push(serializableData)}return result}async add(acRequest,jobId,job,schedule){this.isInitialized||await this.initialize();const validation=schedule.validate();if(!validation.valid){logger$2.warn(`Invalid schedule: ${validation.error}`);return}const jobKey=this.constructJobKey(acRequest.candidate,jobId),existingJob=_LocalScheduler2.jobs.get(jobKey);let acl;existingJob?acl=ACL.from(existingJob.acl).addAccess(acRequest.candidate.role,acRequest.candidate.id,TAccessLevel.Owner):acl=new ACL().addAccess(acRequest.candidate.role,acRequest.candidate.id,TAccessLevel.Owner);const nextRun=schedule.calculateNextRun(),jobData={id:jobId,schedule:schedule.toJSON(),jobConfig:job.toJSON(),acl:acl.ACL,status:"active",nextRun:nextRun?nextRun.toISOString():void 0,createdBy:{role:acRequest.candidate.role,id:acRequest.candidate.id},candidateRole:acRequest.candidate.role,candidateId:acRequest.candidate.id,executionHistory:existingJob?.executionHistory||[]};existingJob&&await this.unscheduleJob(jobKey),_LocalScheduler2.jobs.set(jobKey,jobData),await this.saveJobToDisk(acRequest.candidate,jobData),this.config.runJobs&&await this.scheduleJob(jobData),logger$2.info(`Job ${jobId} added successfully`)}async delete(acRequest,jobId){this.isInitialized||await this.initialize();const jobKey=this.constructJobKey(acRequest.candidate,jobId);if(!_LocalScheduler2.jobs.get(jobKey)){logger$2.warn(`Job ${jobId} not found`);return}await this.unscheduleJob(jobKey),_LocalScheduler2.jobs.delete(jobKey),await this.deleteJobFromDisk(acRequest.candidate,jobId),logger$2.info(`Job ${jobId} deleted successfully`)}async get(acRequest,jobId){this.isInitialized||await this.initialize();const jobKey=this.constructJobKey(acRequest.candidate,jobId),jobData=_LocalScheduler2.jobs.get(jobKey);if(!jobData)return;const{candidateRole,candidateId,...serializableData}=jobData;return serializableData}async pause(acRequest,jobId){this.isInitialized||await this.initialize();const jobKey=this.constructJobKey(acRequest.candidate,jobId),jobData=_LocalScheduler2.jobs.get(jobKey);if(!jobData){logger$2.warn(`Job ${jobId} not found`);return}jobData.status!=="paused"&&(await this.unscheduleJob(jobKey),jobData.status="paused",await this.saveJobToDisk(acRequest.candidate,jobData),logger$2.info(`Job ${jobId} paused`))}async resume(acRequest,jobId){this.isInitialized||await this.initialize();const jobKey=this.constructJobKey(acRequest.candidate,jobId),jobData=_LocalScheduler2.jobs.get(jobKey);if(!jobData){logger$2.warn(`Job ${jobId} not found`);return}jobData.status==="paused"&&(jobData.status="active",await this.saveJobToDisk(acRequest.candidate,jobData),this.config.runJobs&&await this.scheduleJob(jobData),logger$2.info(`Job ${jobId} resumed`))}async shutdown(){logger$2.info("Shutting down LocalScheduler...");const timerCount=_LocalScheduler2.timers.size;for(const[jobKey,timer]of _LocalScheduler2.timers)clearInterval(timer);_LocalScheduler2.timers.clear(),logger$2.info(`LocalScheduler shutdown complete (cleared ${timerCount} timers)`)}};__publicField$5(_LocalScheduler,"jobs",new Map),__publicField$5(_LocalScheduler,"timers",new Map),__decorateClass$1([SecureConnector.AccessControl],_LocalScheduler.prototype,"list"),__decorateClass$1([SecureConnector.AccessControl],_LocalScheduler.prototype,"add"),__decorateClass$1([SecureConnector.AccessControl],_LocalScheduler.prototype,"delete"),__decorateClass$1([SecureConnector.AccessControl],_LocalScheduler.prototype,"get"),__decorateClass$1([SecureConnector.AccessControl],_LocalScheduler.prototype,"pause"),__decorateClass$1([SecureConnector.AccessControl],_LocalScheduler.prototype,"resume");let LocalScheduler=_LocalScheduler;class SchedulerService extends ConnectorServiceProvider{register(){ConnectorService.register(TConnectorService.Scheduler,"LocalScheduler",LocalScheduler)}}class TelemetryConnector extends SecureConnector{constructor(){super()}requester(candidate){return{}}}var __defProp$4=Object.defineProperty,__defNormalProp$4=(obj,key,value)=>key in obj?__defProp$4(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$4=(obj,key,value)=>__defNormalProp$4(obj,key+"",value);class OTelContextRegistry{static key(agentId,processId){return`${agentId}:${processId}`}static startProcess(agentId,processId,span){this.registry.set(this.key(agentId,processId),{agentId,processId,rootSpan:span})}static get(agentId,processId){return this.registry.get(this.key(agentId,processId))}static update(agentId,processId,ctx){const key=this.key(agentId,processId),current=this.registry.get(key);current&&this.registry.set(key,{...current,...ctx})}static endProcess(agentId,processId){this.registry.delete(this.key(agentId,processId))}}__publicField$4(OTelContextRegistry,"registry",new Map);var __defProp$3=Object.defineProperty,__defNormalProp$3=(obj,key,value)=>key in obj?__defProp$3(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$3=(obj,key,value)=>__defNormalProp$3(obj,typeof key!="symbol"?key+"":key,value);const outputLogger=Logger("OTel");class OTel extends TelemetryConnector{constructor(_settings){if(super(),this._settings=_settings,__publicField$3(this,"name","OTel"),__publicField$3(this,"id"),__publicField$3(this,"tracer"),__publicField$3(this,"logger"),__publicField$3(this,"tracerProvider"),__publicField$3(this,"loggerProvider"),!_settings.endpoint){outputLogger.warn("OTel initialization skipped, endpoint is not set");return}outputLogger.log("Initializing Tracer ...");const traceExporter=new OTLPTraceExporter({url:`${_settings.endpoint}/v1/traces`,headers:_settings.headers}),spanProcessor=new BatchSpanProcessor(traceExporter),resource=resourceFromAttributes({[ATTR_SERVICE_NAME]:_settings.serviceName||"smythos",[ATTR_SERVICE_VERSION]:_settings.serviceVersion||"1.0.0"});this.tracerProvider=new NodeTracerProvider({resource,spanProcessors:[spanProcessor]}),this.tracerProvider.register(),outputLogger.log("Initializing Log Exporter ...");const logExporter=new OTLPLogExporter({url:`${_settings.endpoint}/v1/logs`,headers:_settings.headers}),logProcessor=new BatchLogRecordProcessor(logExporter);this.loggerProvider=new LoggerProvider({resource,processors:[logProcessor]}),logs.setGlobalLoggerProvider(this.loggerProvider),this.tracer=trace.getTracer("smythos.agent"),this.logger=logs.getLogger("smythos.agent"),this.id=`otel-${_settings.endpoint}`,this.setupHooks()}async stop(){outputLogger.log(`Stopping ${this.name} connector ...`),await this.tracerProvider.forceFlush?.().catch(error=>{outputLogger.error("Error forcing flush of tracer provider",error)}),await this.tracerProvider.shutdown?.().catch(error=>{outputLogger.error("Error shutting down tracer provider",error)}),await this.loggerProvider.forceFlush().catch(error=>{outputLogger.error("Error forcing flush of logger provider",error)}),await this.loggerProvider.shutdown().catch(error=>{outputLogger.error("Error shutting down logger provider",error)})}redactSensitiveData(data,redactFields){if(!redactFields||redactFields.length===0||typeof data!="object"||data===null)return data;const redacted=Array.isArray(data)?[...data]:{...data};for(const key in redacted)redactFields.some(field=>key.toLowerCase().includes(field.toLowerCase()))?redacted[key]="[REDACTED]":typeof redacted[key]=="object"&&redacted[key]!==null&&(redacted[key]=this.redactSensitiveData(redacted[key],redactFields));return redacted}formatOutputForLog(output,isError=!1){const config2=this._settings,maxSize=config2.maxOutputSize??10*1024;if((config2.fullOutputOnErrorOnly??!1)&&!isError)return;const redacted=this.redactSensitiveData(output,config2.redactFields),outputStr=JSON.stringify(redacted);return outputStr&&outputStr.length>maxSize?`${outputStr.substring(0,maxSize)}...[TRUNCATED: ${outputStr.length} bytes, limit: ${maxSize} bytes]`:outputStr}getResourceACL(resourceId,candidate){return Promise.resolve(new ACL)}log(acRequest,logData,callId){return Promise.resolve()}logTask(acRequest,tasks,isUsingTestDomain){return Promise.resolve()}prepareComponentData(data,prefix,maxEntryLength=200){const result={};for(let key in data)result[prefix?`${prefix}.${key}`:key]=(typeof data[key]=="object"?JSON.stringify(data[key]):data[key].toString()).substring(0,maxEntryLength);return result}setupHooks(){const tracer=this.tracer,logger2=this.logger,oTelInstance=this,createToolInfoHandler=function(hookContext){return function(toolInfo){const accessCandidate=AccessCandidate.agent(hookContext?.agentId);if(outputLogger.debug("createToolInfoHandler started",accessCandidate),!hookContext.curLLMGenSpan||!hookContext.convSpan)return;const modelId=toolInfo.model,lastContext=toolInfo.contextWindow.filter(context2=>context2.role==="user").slice(-2),toolNames=toolInfo.map(tool=>tool.name+"("+tool.arguments+")");hookContext.curLLMGenSpan.addEvent("llm.gen.tool.calls",{"tool.calls":toolNames.join(", "),"llm.model":modelId||"unknown","context.preview":JSON.stringify(lastContext).substring(0,200)});const spanContext=trace.setSpan(context.active(),hookContext.curLLMGenSpan);context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.INFO,severityText:"INFO",body:`LLM tool calls: ${toolNames.join(", ")}`,attributes:{"agent.id":hookContext.agentId,"conv.id":hookContext.processId,"llm.model":modelId||"unknown","context.preview":JSON.stringify(lastContext).substring(0,5e3)}})}),hookContext.curLLMGenSpan.end(),delete hookContext.curLLMGenSpan,outputLogger.debug("createToolInfoHandler completed",accessCandidate)}},createDataHandler=function(hookContext){return function(data,reqInfo){if(!hookContext.convSpan||hookContext.curLLMGenSpan)return;const accessCandidate=AccessCandidate.agent(hookContext?.agentId);outputLogger.debug("createDataHandler started",reqInfo?.requestId,accessCandidate);const modelId=reqInfo.model,lastContext=reqInfo.contextWindow.filter(context2=>context2.role==="user").slice(-2);if(hookContext?.latencySpans?.[reqInfo.requestId]){const ttfbSpan=hookContext.latencySpans[reqInfo.requestId];ttfbSpan.addEvent("llm.first.byte.received",{"request.id":reqInfo.requestId,"data.size":JSON.stringify(data||{}).length,"llm.model":modelId||"unknown"}),ttfbSpan.setStatus({code:SpanStatusCode.OK}),ttfbSpan.end(),delete hookContext.latencySpans[reqInfo.requestId]}const llmGenSpan=tracer.startSpan("Conv.GenAI",{attributes:{"agent.id":hookContext.agentId,"conv.id":hookContext.processId,"team.id":hookContext.teamId,"llm.model":modelId||"unknown"}},trace.setSpan(context.active(),hookContext.convSpan));llmGenSpan.addEvent("llm.gen.started",{"request.id":reqInfo.requestId,timestamp:Date.now(),"llm.model":modelId||"unknown","context.preview":JSON.stringify(lastContext).substring(0,200)}),hookContext.curLLMGenSpan=llmGenSpan,outputLogger.debug("createDataHandler completed",reqInfo?.requestId,accessCandidate)}},createRequestedHandler=function(hookContext){return function(reqInfo){if(!hookContext.convSpan)return;const accessCandidate=AccessCandidate.agent(hookContext?.agentId);outputLogger.debug("createRequestedHandler started",reqInfo?.requestId,accessCandidate),hookContext.latencySpans||(hookContext.latencySpans={});const lastContext=reqInfo.contextWindow.filter(context2=>context2.role==="user").slice(-2),modelId=reqInfo.model,llmGenLatencySpan=tracer.startSpan("Conv.GenAI.TTFB",{attributes:{"agent.id":hookContext.agentId,"conv.id":hookContext.processId,"team.id":hookContext.teamId,"request.id":reqInfo.requestId,"llm.model":modelId||"unknown","metric.type":"ttfb"}},trace.setSpan(context.active(),hookContext.convSpan));llmGenLatencySpan.addEvent("llm.requested",{"request.id":reqInfo.requestId,timestamp:Date.now(),"context.preview":JSON.stringify(lastContext).substring(0,200)}),hookContext.latencySpans[reqInfo.requestId]=llmGenLatencySpan,outputLogger.debug("createRequestedHandler completed",reqInfo?.requestId,accessCandidate)}};return HookService.register("Conversation.streamPrompt",async function(additionalContext,args){const conversation=this.instance,processId=conversation.storeId||conversation.id,agentId=conversation.agentId,message=typeof args=="object"?args?.message:args||null,hookContext=this.context,teamId=conversation.agentData.teamId,orgTier="standard",orgSlot=this.instance.agentData?.planInfo?.flags?`standard/${teamId}`:void 0,agentData=conversation.agentData||{},isDebugSession=agentData.debugSessionEnabled||!1,isTestDomain=agentData.usingTestDomain||!1,sessionId=processId,workflowId=agentData?.workflowReqId||agentData?.workflowID||agentData?.workflowId||void 0,logTags=agentData?.sessionTag||(isDebugSession?"DEBUG":void 0);if(message==null)return;const accessCandidate=AccessCandidate.agent(agentId);outputLogger.debug("Conversation.streamPrompt started",{processId,message},accessCandidate);const modelId=typeof conversation?.model=="string"?conversation?.model:conversation?.model?.modelId,convSpan=tracer.startSpan("Agent.Conv",{attributes:{"gen_ai.operation.name":"chat","gen_ai.provider.name":conversation?.llmInference?.llmProviderName||"unknown","gen_ai.conversation.id":processId,"gen_ai.request.model":modelId||"unknown","team.id":teamId,"org.tier":orgTier,"org.slot":orgSlot,"agent.id":agentId,"conv.id":processId,"llm.model":modelId||"unknown","agent.debug":isDebugSession,"agent.isTest":isTestDomain,"session.id":sessionId,"workflow.id":workflowId}});hookContext.convSpan=convSpan,hookContext.agentId=agentId,hookContext.processId=processId,hookContext.teamId=teamId,hookContext.orgSlot=orgSlot,hookContext.isDebugSession=isDebugSession,hookContext.isTestDomain=isTestDomain;let headers={};const traceContext=trace.setSpan(context.active(),convSpan);propagation.inject(traceContext,headers);for(let[key,value]of Object.entries(headers))conversation.headers[key]=value;outputLogger.debug("Injected trace headers into conversation",{processId,headers}),hookContext.dataHandler=createDataHandler(hookContext),conversation.on(TLLMEvent.Data,hookContext.dataHandler),hookContext.requestedHandler=createRequestedHandler(hookContext),conversation.on(TLLMEvent.Requested,hookContext.requestedHandler),hookContext.toolInfoHandler=createToolInfoHandler(hookContext),conversation.on(TLLMEvent.ToolInfo,hookContext.toolInfoHandler),convSpan.addEvent("skill.process.started",{"input.size":JSON.stringify(message||{}).length,"input.preview":message.substring(0,200),"llm.model":modelId||"unknown"}),OTelContextRegistry.startProcess(agentId,processId,convSpan);const spanCtx=convSpan.spanContext(),spanContext=trace.setSpan(context.active(),convSpan);context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.INFO,severityText:"INFO",body:`Conversation.streamPrompt started: ${processId}`,attributes:{trace_id:spanCtx.traceId,span_id:spanCtx.spanId,trace_flags:spanCtx.traceFlags,"team.id":teamId,"org.slot":orgSlot,"agent.id":agentId,"conv.id":processId,"input.size":JSON.stringify(message||{}).length,"input.preview":message.substring(0,2e3),"agent.debug":isDebugSession,"agent.isTest":isTestDomain,"session.id":sessionId,"workflow.id":workflowId,"log.tags":logTags}})})},THook.NonBlocking),HookService.registerAfter("Conversation.streamPrompt",async function({result,args,error}){const conversation=this.instance,processId=conversation.storeId||conversation.id,agentId=conversation.agentId,message=typeof args?.[0]=="object"?args?.[0]?.message:args?.[0]||null,hookContext=this.context,teamId=conversation.agentData.teamId,orgTier="standard",orgSlot=this.instance.agentData?.planInfo?.flags?`standard/${teamId}`:void 0,isDebugSession=hookContext.isDebugSession||conversation.agentData?.debugSessionEnabled||!1,isTestDomain=hookContext.isTestDomain||conversation.agentData?.usingTestDomain||!1,agentData=conversation.agentData||{},sessionId=processId,workflowId=agentData?.workflowReqId||agentData?.workflowID||agentData?.workflowId||void 0,logTags=agentData?.sessionTag||(isDebugSession?"DEBUG":void 0);if(message==null)return;const ctx=OTelContextRegistry.get(agentId,processId);if(!ctx)return;const accessCandidate=AccessCandidate.agent(agentId);outputLogger.debug("Conversation.streamPrompt completed",{processId},accessCandidate),hookContext.curLLMGenSpan&&(hookContext.curLLMGenSpan.addEvent("llm.gen.content",{"content.size":JSON.stringify(result||{}).length,"content.preview":result.substring(0,200)}),hookContext.curLLMGenSpan.end(),hookContext.toolInfoHandler&&conversation.off(TLLMEvent.ToolInfo,hookContext.toolInfoHandler),hookContext.dataHandler&&conversation.off(TLLMEvent.Data,hookContext.dataHandler),hookContext.requestedHandler&&conversation.off(TLLMEvent.Requested,hookContext.requestedHandler));const{rootSpan:convSpan}=ctx;convSpan.spanContext();const spanContext=trace.setSpan(context.active(),convSpan);context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.INFO,severityText:"INFO",body:`Conversation.streamPrompt completed: ${processId}`,attributes:{"agent.id":agentId,"conv.id":processId,"output.size":JSON.stringify(result||{}).length,"output.preview":result.substring(0,2e3),"team.id":teamId,"org.tier":orgTier,"org.slot":orgSlot,"agent.debug":isDebugSession,"agent.isTest":isTestDomain,"session.id":sessionId,"workflow.id":workflowId,"log.tags":logTags}})}),convSpan.end(),OTelContextRegistry.endProcess(agentId,processId)},THook.NonBlocking),HookService.register("SREAgent.process",async function(endpointPath,inputData){const agent=this.instance,agentProcessId=agent.agentRuntime.processID,conversationId=agent.conversationId||agent.agentRequest?.header("X-CONVERSATION-ID"),processId=agentProcessId.split(":").shift(),orgTier="standard",orgSlot=agent.data.planInfo?.flags?`standard/${agent.data.teamId}`:void 0,agentId=agent.id,agentRequest=agent.agentRequest,teamId=agent.teamId,_hookContext=this.context,sessionId=agent.callerSessionId||void 0,workflowId=agent.agentRuntime?.workflowReqId||void 0,isDebugSession=agent.debugSessionEnabled||agent.agentRuntime?.debug||!1,logTags=agent.sessionTag||(isDebugSession?"DEBUG":void 0),isTestDomain=agent.usingTestDomain||!1,domain=agent.domain||void 0,accessCandidate=AccessCandidate.agent(agentId);outputLogger.debug("SREAgent.process started",{processId,agentProcessId,endpointPath},accessCandidate);const body=oTelInstance.prepareComponentData(agentRequest.body||{}),query=oTelInstance.prepareComponentData(agentRequest.query||{}),headers=oTelInstance.prepareComponentData(agentRequest.headers||{}),agentInput=oTelInstance.prepareComponentData(inputData||{}),input={body,query,headers,processInput:agentInput};let convSpan,parentContext=context.active(),ctx=OTelContextRegistry.get(agentId,processId)||OTelContextRegistry.get(agentId,conversationId);if(ctx)convSpan=ctx.rootSpan,_hookContext.otelSpan=convSpan,parentContext=trace.setSpan(context.active(),convSpan);else{const extractedContext=propagation.extract(context.active(),agentRequest.headers),extractedSpan=trace.getSpan(extractedContext);extractedSpan&&(parentContext=extractedContext,outputLogger.debug("SREAgent.process extracted remote parent context from headers",{processId,traceId:extractedSpan.spanContext().traceId}))}const agentSpan=tracer.startSpan("Agent.Skill",{attributes:{"agent.id":agentId,"team.id":teamId,"conv.id":conversationId,"process.id":agentProcessId,"org.slot":orgSlot,"org.tier":orgTier,"session.id":sessionId,"workflow.id":workflowId,"agent.debug":isDebugSession,"agent.isTest":isTestDomain,"agent.domain":domain}},parentContext),inputPreview=JSON.stringify(input||{}).substring(0,200);agentSpan.addEvent("skill.process.started",{endpoint:endpointPath,"input.size":JSON.stringify(input||{}).length,"input.preview":inputPreview}),OTelContextRegistry.startProcess(agentId,agentProcessId,agentSpan);const spanCtx=agentSpan.spanContext(),spanContext=trace.setSpan(context.active(),agentSpan);context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.INFO,severityText:"INFO",body:`Agent Skill process started: ${processId}`,attributes:{trace_id:spanCtx.traceId,span_id:spanCtx.spanId,trace_flags:spanCtx.traceFlags,"agent.id":agentId,"process.id":agentProcessId,input:agentInput,body,query,headers,"team.id":teamId,"org.slot":orgSlot,"org.tier":orgTier,"conv.id":conversationId,"session.id":sessionId,"workflow.id":workflowId,"log.tags":logTags,"agent.debug":isDebugSession,"agent.isTest":isTestDomain,"agent.domain":domain}})})},THook.NonBlocking),HookService.registerAfter("SREAgent.process",async function({result,error}){const agent=this.instance,agentProcessId=agent.agentRuntime.processID,conversationId=agent.conversationId||agent.agentRequest?.header("X-CONVERSATION-ID"),agentId=agent.id;this.context;const teamId=agent.teamId,orgTier="standard",orgSlot=agent.data.planInfo?.flags?`standard/${agent.data.teamId}`:void 0,sessionId=agent.callerSessionId||void 0,workflowId=agent.agentRuntime?.workflowReqId||void 0,isDebugSession=agent.debugSessionEnabled||agent.agentRuntime?.debug||!1,logTags=agent.sessionTag||(isDebugSession?"DEBUG":void 0),isTestDomain=agent.usingTestDomain||!1,domain=agent.domain||void 0,ctx=OTelContextRegistry.get(agentId,agentProcessId);if(!ctx)return;const agentSpan=ctx.rootSpan;if(!agentSpan)return;const accessCandidate=AccessCandidate.agent(agentId);outputLogger.debug("SREAgent.process completed",{agentProcessId},accessCandidate),error?(agentSpan.recordException(error),agentSpan.setStatus({code:SpanStatusCode.ERROR,message:error.message}),agentSpan.addEvent("skill.process.error",{"error.message":error.message})):(agentSpan.setStatus({code:SpanStatusCode.OK}),agentSpan.addEvent("skill.process.completed",{"output.size":JSON.stringify(result||{}).length}),agentSpan.setAttributes({"output.size":JSON.stringify(result||{}).length}));const outputForLog=oTelInstance.formatOutputForLog(result,!!error),spanCtx=agentSpan.spanContext(),logAttributes={trace_id:spanCtx.traceId,span_id:spanCtx.spanId,trace_flags:spanCtx.traceFlags,"agent.id":agentId,"process.id":agentProcessId,hasError:!!error,"error.message":error?.message,"error.stack":error?.stack,"team.id":teamId,"org.slot":orgSlot,"org.tier":orgTier,"conv.id":conversationId,"session.id":sessionId,"workflow.id":workflowId,"log.tags":logTags,"agent.debug":isDebugSession,"agent.isTest":isTestDomain,"agent.domain":domain};outputForLog!==void 0&&(logAttributes["agent.output"]=outputForLog);const spanContext=trace.setSpan(context.active(),agentSpan);context.with(spanContext,()=>{logger2.emit({severityNumber:error?SeverityNumber.ERROR:SeverityNumber.INFO,severityText:error?"ERROR":"INFO",body:`Agent process ${error?"failed":"completed"}: ${agentProcessId}`,attributes:logAttributes})}),agentSpan.end(),OTelContextRegistry.endProcess(agentId,agentProcessId)},THook.NonBlocking),HookService.register("Component.process",async function(input,settings,agent){const processId=agent.agentRuntime.processID,agentId=agent.id;this.instance;const componentId=settings.id||"unknown",componentType=settings.name,componentName=settings.displayName||settings.name,eventId=settings.eventId,accessCandidate=AccessCandidate.agent(agentId),teamId=agent.teamId,orgTier="standard",orgSlot=agent.data.planInfo?.flags?`standard/${agent.data.teamId}`:void 0,sourceId=agent.agentRuntime?.getComponentData?.(componentId)?.sourceId||"AGENT",sourceComponentData=sourceId!=="AGENT"?agent.components?.[sourceId]:null,sourceName=sourceComponentData?.displayName||sourceComponentData?.name||sourceId,sessionId=agent.callerSessionId||void 0,workflowId=agent.agentRuntime?.workflowReqId||void 0,workflowStep=agent.agentRuntime?.curStep||void 0,isDebugSession=agent.debugSessionEnabled||agent.agentRuntime?.debug||!1,logTags=agent.sessionTag||(isDebugSession?"DEBUG":void 0),isTestDomain=agent.usingTestDomain||!1,inputAction=input?.__action||void 0,inputStatus=input?.__status||void 0;outputLogger.debug("Component.process started",{componentId,sourceId},accessCandidate);const parentSpan=OTelContextRegistry.get(agentId,processId)?.rootSpan,compSettingsData=oTelInstance.prepareComponentData(settings?.data||{},"cmp.settings"),spanName=`Component.${componentType}`,span=tracer.startSpan(spanName,{attributes:{"agent.id":agentId,"process.id":processId,"event.id":eventId,"cmp.id":componentId,"cmp.type":componentType,"cmp.name":componentName,"team.id":teamId,"org.tier":orgTier,"org.slot":orgSlot,"source.id":sourceId,"source.name":sourceName,"session.id":sessionId,"workflow.id":workflowId,"workflow.step":workflowStep,"agent.debug":isDebugSession,"agent.isTest":isTestDomain,...compSettingsData}},parentSpan?trace.setSpan(context.active(),parentSpan):void 0);JSON.stringify(input||{});const compInputData=oTelInstance.prepareComponentData(input||{});span.addEvent("cmp.call",{"event.id":eventId,"cmp.input.size":JSON.stringify(input||{}).length,"cmp.input":JSON.stringify(compInputData),"input.action":inputAction,"input.status":inputStatus});const spanContext=trace.setSpan(context.active(),span);context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.INFO,severityText:"INFO",body:`Component ${componentType} started`,attributes:{"agent.id":agentId,"process.id":processId,"event.id":eventId,"cmp.id":componentId,"cmp.type":componentType,"cmp.name":componentName,"cmp.input":input,"team.id":teamId,"org.slot":orgSlot,"org.tier":orgTier,"source.id":sourceId,"source.name":sourceName,"session.id":sessionId,"workflow.id":workflowId,"workflow.step":workflowStep,"log.tags":logTags,"agent.debug":isDebugSession,"agent.isTest":isTestDomain}})}),this.context.otelSpan=span},THook.NonBlocking),HookService.registerAfter("Component.process",async function({result,error,args}){const span=this.context.otelSpan;if(!span)return;const agent=args[2],settings=args[1],eventId=settings.eventId,processId=agent.agentRuntime.processID,agentId=agent.id;this.instance;const componentId=settings.id||"unknown",componentType=settings.name,componentName=settings.displayName||settings.name,teamId=agent.teamId,orgTier="standard",orgSlot=agent.data.planInfo?.flags?`standard/${agent.data.teamId}`:void 0,sourceId=agent.agentRuntime?.getComponentData?.(componentId)?.sourceId||"AGENT",sourceComponentData=sourceId!=="AGENT"?agent.components?.[sourceId]:null,sourceName=sourceComponentData?.displayName||sourceComponentData?.name||sourceId,sessionId=agent.callerSessionId||void 0,workflowId=agent.agentRuntime?.workflowReqId||void 0,workflowStep=agent.agentRuntime?.curStep||void 0,isDebugSession=agent.debugSessionEnabled||agent.agentRuntime?.debug||!1,logTags=agent.sessionTag||(isDebugSession?"DEBUG":void 0),isTestDomain=agent.usingTestDomain||!1,accessCandidate=AccessCandidate.agent(agentId);if(outputLogger.debug("Component.process completed",{componentId},accessCandidate),error){span.recordException(error),span.setStatus({code:SpanStatusCode.ERROR,message:error.message}),span.addEvent("cmp.call.error",{"event.id":eventId,"cmp.id":componentId,"cmp.type":componentType,"cmp.name":componentName,"error.type":error.name,"error.message":error.message,"error.stack":error.stack?.substring(0,500)});const spanContext=trace.setSpan(context.active(),span);context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.ERROR,severityText:"ERROR",body:`Component ${componentType} (${componentId}) failed: ${error.message}`,attributes:{"agent.id":agentId,"process.id":processId,"event.id":eventId,"cmp.id":componentId,"cmp.name":componentName,"cmp.type":componentType,"error.type":error.name,"error.message":error.message,"error.stack":error.stack,"team.id":teamId,"org.slot":orgSlot,"org.tier":orgTier,"source.id":sourceId,"source.name":sourceName,"session.id":sessionId,"workflow.id":workflowId,"workflow.step":workflowStep,"log.tags":logTags,"agent.debug":isDebugSession,"agent.isTest":isTestDomain}})})}else{span.setStatus({code:SpanStatusCode.OK});const resultStr=JSON.stringify(result||{});span.addEvent("cmp.call.result",{"output.size":resultStr.length,"output.preview":resultStr.substring(0,200)}),span.setAttributes({"output.size":JSON.stringify(result||{}).length,"output.has_error":!!result?._error}),oTelInstance.formatOutputForLog(result,!1);const logAttributes={"agent.id":agentId,"cmp.id":componentId,"cmp.type":componentType,"cmp.name":componentName,"process.id":processId,"event.id":eventId,"cmp.output":result,"team.id":teamId,"org.slot":orgSlot,"org.tier":orgTier,"source.id":sourceId,"source.name":sourceName,"session.id":sessionId,"workflow.id":workflowId,"workflow.step":workflowStep,"log.tags":logTags,"agent.debug":isDebugSession,"agent.isTest":isTestDomain},spanContext=trace.setSpan(context.active(),span);context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.INFO,severityText:"INFO",body:`Component ${componentType} (${componentId}) completed successfully`,attributes:logAttributes})})}span.end()},THook.NonBlocking),Promise.resolve()}}class TelemetryService extends ConnectorServiceProvider{register(){ConnectorService.register(TConnectorService.Telemetry,"OTel",OTel)}}const console$1=Logger("Boot");let _booted=!1;function boot(){if(_booted){console$1.warn("SRE already booted");return}_booted=!0,SystemEvents.emit("SRE:BootStart"),console$1.debug("SRE Boot sequence started");const service={};service.NKV=new NKVService,service.Account=new AccountService,service.Vault=new VaultService,service.ManagedVault=new ManagedVaultService,service.Cache=new CacheService,service.Storage=new StorageService,service.ModelsProvider=new ModelsProviderService,service.LLM=new LLMService,service.AgentData=new AgentDataService,service.CLI=new CLIService,service.VectorDB=new VectorDBService,service.Router=new RouterService,service.Log=new LogService,service.Component=new ComponentService,service.Code=new CodeService,service.Scheduler=new SchedulerService,service.Telemetry=new TelemetryService,SystemEvents.on("SRE:Initialized",()=>{console$1.debug("SRE Initialized");for(let key in service)service[key].init();SystemEvents.emit("SRE:Booted",service),console$1.debug("SRE Boot sequence completed")})}function generateServiceKey(serviceName){const secret=process.env.SRE_SECRET;if(!secret||secret.trim().length<32)throw new Error("SRE_SECRET must be at least 32 characters");return createHmac("sha256",secret).update(`sre-service:${serviceName}`).digest("hex")}function validateServiceKey(serviceName,providedKey){try{const expectedKey=generateServiceKey(serviceName);return timingSafeEqual(Buffer.from(expectedKey),Buffer.from(providedKey))}catch{return!1}}var __defProp$2=Object.defineProperty,__defNormalProp$2=(obj,key,value)=>key in obj?__defProp$2(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$2=(obj,key,value)=>__defNormalProp$2(obj,typeof key!="symbol"?key+"":key,value);const logger$1=Logger("ExternalEventsReceiver");class ExternalEventsReceiver{constructor(config2){if(__publicField$2(this,"server",null),__publicField$2(this,"wss",null),__publicField$2(this,"config"),__publicField$2(this,"isRunning",!1),this.config={enableHttp:!0,enableWebSocket:!0,path:"/ws",...config2},!this.config.authTokens||this.config.authTokens.length===0)throw logger$1.warn("At least one authentication token must be provided"),new Error("At least one authentication token must be provided")}async start(){if(this.isRunning){logger$1.warn("Server is already running");return}return this.server=createServer((req,res)=>this.handleHttpRequest(req,res)),this.config.enableWebSocket&&(this.wss=new WebSocketServer({server:this.server,path:this.config.path}),this.wss.on("connection",(ws,req)=>{this.handleWebSocketConnection(ws,req)})),new Promise((resolve,reject)=>{this.server.listen(this.config.port,"127.0.0.1",()=>{this.isRunning=!0,logger$1.debug(`Server started on port ${this.config.port}`+(this.config.enableHttp?" [HTTP]":"")+(this.config.enableWebSocket?` [WebSocket: ${this.config.path}]`:"")),resolve()}),this.server.on("error",error=>{logger$1.error("Server error",error),reject(error)})})}async stop(){if(this.isRunning)return new Promise((resolve,reject)=>{this.wss&&this.wss.close(err=>{err&&logger$1.error("Error closing WebSocket server",err)}),this.server?this.server.close(err=>{err?(logger$1.error("Error closing HTTP server",err),reject(err)):(this.isRunning=!1,logger$1.debug("Server stopped"),resolve())}):resolve()})}handleHttpRequest(req,res){if(!this.config.enableHttp){this.sendResponse(res,404,{error:"HTTP endpoint is disabled"});return}if(req.method!=="POST"){this.sendResponse(res,405,{error:"Method not allowed. Only POST requests are accepted."});return}const authResult=this.validateAuth(req.headers);if(!authResult.valid){this.sendResponse(res,401,{error:authResult.error});return}const connectorName=this.getConnectorName(req.headers);if(!connectorName){this.sendResponse(res,400,{error:"Missing x-connector-name header"});return}let body="";req.on("data",chunk=>{body+=chunk.toString()}),req.on("end",()=>{try{const data=body?JSON.parse(body):{};this.emitExternalEvent(connectorName,data),this.sendResponse(res,200,{success:!0,message:`Event EXT:${connectorName} emitted successfully`})}catch(error){logger$1.error("Error processing HTTP request",error),this.sendResponse(res,400,{error:"Invalid JSON payload"})}}),req.on("error",error=>{logger$1.error("HTTP request error",error),this.sendResponse(res,500,{error:"Internal server error"})})}handleWebSocketConnection(ws,req){logger$1.debug("New WebSocket connection");const authResult=this.validateAuth(req.headers);if(!authResult.valid){ws.close(1008,authResult.error);return}let connectorName=this.getConnectorName(req.headers);ws.on("message",message=>{try{const data=JSON.parse(message.toString());if(!connectorName&&(connectorName=data.connectorName||data["x-connector-name"],!connectorName)){ws.send(JSON.stringify({error:"Missing connector name in headers or message"}));return}this.emitExternalEvent(connectorName,data),ws.send(JSON.stringify({success:!0,message:`Event EXT:${connectorName} emitted successfully`}))}catch(error){logger$1.error("Error processing WebSocket message",error),ws.send(JSON.stringify({error:"Invalid JSON message"}))}}),ws.on("error",error=>{logger$1.error("WebSocket error",error)}),ws.on("close",()=>{logger$1.debug("WebSocket connection closed")})}validateAuth(headers){const authHeader=headers.authorization||headers.Authorization,serviceName=headers["x-service-name"]||headers["X-Service-Name"];if(!authHeader)return logger$1.warn("Missing Authorization header"),{valid:!1,error:"Missing Authorization header"};if(!serviceName||typeof serviceName!="string")return logger$1.warn("Missing or invalid X-Service-Name header"),{valid:!1,error:"Missing X-Service-Name header"};const token=authHeader.replace(/^Bearer\s+/i,"");return token?validateServiceKey(serviceName,token)?(logger$1.debug(`Authenticated service: ${serviceName}`),{valid:!0,serviceName}):(logger$1.warn(`Invalid key for service: ${serviceName}`),{valid:!1,error:"Invalid authentication"}):{valid:!1,error:"Invalid Authorization header format"}}getConnectorName(headers){const connectorName=headers["x-connector-name"]||headers["X-Connector-Name"];return typeof connectorName=="string"?connectorName:connectorName?.[0]||null}emitExternalEvent(connectorName,data){const eventName=`EXT:${connectorName}`,connector=ConnectorService.getInstance(TConnectorService[connectorName]);connector&&connector.handleEvent(eventName,data)}sendResponse(res,statusCode,body){res.statusCode=statusCode,res.setHeader("Content-Type","application/json"),res.end(JSON.stringify(body))}getStatus(){return{running:this.isRunning,port:this.config.port,config:this.config}}}var __defProp$1=Object.defineProperty,__defNormalProp$1=(obj,key,value)=>key in obj?__defProp$1(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1=(obj,key,value)=>__defNormalProp$1(obj,typeof key!="symbol"?key+"":key,value);const logger=Logger("SRE"),_SmythRuntime=class _SmythRuntime2{constructor(){__publicField$1(this,"started",!1),__publicField$1(this,"_smythDir"),__publicField$1(this,"_readyPromise"),__publicField$1(this,"_readyResolve"),__publicField$1(this,"defaultConfig",{Vault:{Connector:"JSONFileVault",Settings:{shared:"default"}},Account:{Connector:"DummyAccount"},Cache:{Connector:"RAM"},Storage:{Connector:"LocalStorage"},Code:{Connector:"DummyConnector"},NKV:{Connector:"LocalStorage"},VectorDB:{Connector:"RAMVec"},ModelsProvider:{Connector:"JSONModelsProvider"},AgentData:{Connector:"NullAgentData"},Component:{Connector:"LocalComponent"},ManagedVault:{Connector:"NullManagedVault"},Log:{Connector:"ConsoleLog"},Router:{Connector:"NullRouter"},Scheduler:{Connector:"LocalScheduler",Settings:{runJobs:!0,persistExecutionHistory:!0}}}),__publicField$1(this,"connectors",{}),__publicField$1(this,"connectorInstances",{}),__publicField$1(this,"_initializing",!1),__publicField$1(this,"_initialized",!1),__publicField$1(this,"_stopping",!1),this.started=!0,this._readyPromise=new Promise(resolve=>{this._readyResolve=resolve})}get smythDir(){return this._smythDir}get version(){return pkg.version}static get Instance(){return _SmythRuntime2.instance||(_SmythRuntime2.instance=new _SmythRuntime2),_SmythRuntime2.instance}get initializing(){return this._initializing}init(_config){if(logger.info(`SRE v${this.version} initializing...`),this._initialized)return console.warn("SRE already initialized ... skipping"),_SmythRuntime2.Instance;if(this._initializing)return console.warn("You tried to initialize SRE while it is already initializing ... skipping"),_SmythRuntime2.Instance;(!_config||JSON.stringify(_config)==="{}")&&(this._smythDir=findSmythPath(),logger.info(".smyth directory found in:",this._smythDir)),this._initializing=!0,SystemEvents.on("SRE:Booted",()=>{this._readyResolve(!0)}),boot();const config2=this.autoConf(_config);for(let connectorType in config2)for(let configEntry of config2[connectorType])ConnectorService.init(connectorType,configEntry.Connector,configEntry.Id,configEntry.Settings,configEntry.Default)||logger.warn(`Failed to initialize connector ${connectorType}:${configEntry.Id||configEntry.Connector}`);return this._initialized=!0,SystemEvents.emit("SRE:Initialized",_SmythRuntime2.Instance),this.setupShutdownHandlers(),_SmythRuntime2.Instance}autoConf(config2={}){const defaultConfig=JSON.parse(JSON.stringify(this.defaultConfig)),keys=Object.keys({...defaultConfig,...config2}),newConfig={};for(let connectorType of keys){newConfig[connectorType]=[];let entry=config2[connectorType]||defaultConfig[connectorType];Array.isArray(entry)||(entry=[entry]);let hasDefault=!1;for(let connector of entry){if(!connector.Connector){logger.warn(`Missing Connector Name in ${connectorType} entry ... it will be ignored`);continue}connector.Default&&(hasDefault&&logger.warn(`Entry ${connectorType} has more than one default Connector ... only the first one will be used`),hasDefault=!0),newConfig[connectorType].push(connector)}!hasDefault&&newConfig[connectorType].length>0&&(newConfig[connectorType][0].Default=!0)}return newConfig}ready(){return this._readyPromise}async _stop(){this._stopping||(this._stopping=!0,logger.info("Sending Shutdown Signals To All Subsystems..."),await ConnectorService._stop(),this.started=!1)}setupShutdownHandlers(){["SIGINT","SIGTERM"].forEach(signal=>{process.on(signal,async()=>{await shutdown(signal),process.exit(0)})}),process.on("beforeExit",code=>{shutdown("beforeExit")}),process.on("exit",code=>{logger.info("Goodbye!")})}};__publicField$1(_SmythRuntime,"instance");let SmythRuntime=_SmythRuntime;const SRE=SmythRuntime.Instance;let shuttingDown=!1;async function shutdown(reason){if(SmythRuntime.Instance.started&&!shuttingDown&&(shuttingDown=!0,logger.info(`Caught ${reason} ... Attempting graceful shutdown`),SmythRuntime.Instance))try{await SmythRuntime.Instance._stop()}catch(err){logger.error("Shutdown error:",err)}}class SmythURI{static agent(id){return`smyth:agent:${id}`}}class LLMMemoryConnector extends SecureConnector{requester(candidate){return{load:async messages=>await this.load(candidate.readRequest,messages)}}}var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__decorateClass=(decorators,target,key,kind)=>{for(var result=__getOwnPropDesc(target,key),i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=decorator(target,key,result)||result);return result&&__defProp(target,key,result),result},__publicField=(obj,key,value)=>__defNormalProp(obj,key+"",value);Logger("HashicorpVault");class HashicorpVault extends VaultConnector{constructor(_settings){super(_settings),this._settings=_settings,__publicField(this,"name","HashicorpVault")}async get(acRequest,keyId){return null}async exists(acRequest,keyId){return!1}async listKeys(acRequest){return[]}async getResourceACL(resourceId,candidate){const teamId=await ConnectorService.getAccountConnector().getCandidateTeam(candidate),acl=new ACL;return acl.addAccess(TAccessRole.Team,teamId,TAccessLevel.Owner).addAccess(TAccessRole.Team,teamId,TAccessLevel.Read).addAccess(TAccessRole.Team,teamId,TAccessLevel.Write),acl}}__decorateClass([SecureConnector.AccessControl],HashicorpVault.prototype,"get"),__decorateClass([SecureConnector.AccessControl],HashicorpVault.prototype,"exists"),__decorateClass([SecureConnector.AccessControl],HashicorpVault.prototype,"listKeys");export{ACL,ACLAccessDeniedError,APICall,APIEndpoint,APIKeySource,APIOutput,AWSLambdaCode,AccessCandidate,AccessRequest,AccountConnector,AccountService,Agent,AgentDataConnector,AgentDataService,AgentLogger,AgentPlugin,AgentProcess,AgentRequest,AgentRuntime,AgentSSE,AgentSettings,AnthropicConnector,Async,Await,BUILT_IN_MODEL_PREFIX,BaseEmbedding,BedrockConnector,BinaryInput,BuiltinLLMProviders,CLIAgentDataConnector,CLIConnector,CLIService,COMP_NAMES,CacheConnector,CacheService,Classifier,CodeConnector,CodeService,Component,ComponentConnector,ComponentHost,ComponentInputType,ComponentInstances,ComponentService,Connector,ConnectorService,ConnectorServiceProvider,ConsoleLog,Conversation,Credentials,DEFAULT_MAX_TOKENS_FOR_LLM,DEFAULT_SMYTHOS_LLM_PROVIDERS_SETTINGS,DEFAULT_TEAM_ID,DataSourceCleaner,DataSourceCompError,DataSourceComponent,DataSourceIndexer,DataSourceLookup,DummyAccount,DummyConnector,EMBODIMENT_TYPES,ENTERPRISE_MODELS_SETTING_KEY,ERR_MSG_INVALID_BINARY,ERR_MSG_INVALID_IMAGE_SOURCE,ERR_MSG_MAX_ARRAY_SIZE,ERR_MSG_MAX_DEPTH,ERR_MSG_MAX_OBJECT_SIZE,EchoConnector,EmbeddingsFactory,EmbodimentSettings,ExpressRouter,ExternalEventsReceiver,FEncDec,FHash,FSign,FSleep,FTimestamp,FileStore,ForEach,ForkedAgent,GPTPlugin,GenAILLM,GmailTrigger,GoogleAIConnector,GoogleEmbeds,GroqConnector,HashicorpVault,HookService,HuggingFace,ImageGenerator,ImageSettingsConfig,JSONContent,JSONContentHelper,JSONExpression$1 as JSONExpression,JSONFileAccount,JSONFileVault,JSONFilter,JSONModelsProvider,JSON_RESPONSE_INSTRUCTION,Job,JobSchedulerTrigger,LLMAssistant,LLMCache,LLMConnector,LLMContext,LLMHelper,LLMInference$1 as LLMInference,LLMInterface,LLMMemoryConnector,LLMService,LLMStream,LevelMap,LocalAgentDataConnector,LocalCache,LocalComponentConnector,LocalScheduler,LocalStorage,LocalStorageCache,LogConnector,LogHelper,LogService,Logger,LogicAND,LogicAtLeast,LogicAtMost,LogicOR,LogicXOR,MAX_ARRAY_SIZE,MAX_DEPTH,MAX_FILE_COUNT,MAX_FILE_SIZE,MAX_OBJECT_SIZE,MCPClient,MODELS_WITHOUT_JSON_RESPONSE_SUPPORT,MODELS_WITHOUT_SYSTEM_MESSAGE_SUPPORT,ManagedOAuth2Credentials,ManagedVaultConnector,ManagedVaultService,Match,MemoryDeleteKeyVal,MemoryReadKeyVal,MemoryWriteKeyVal,MemoryWriteObject,MilvusVectorDB,ModelsProviderConnector,ModelsProviderService,MultimodalLLM,MySQLAccount,NKVConnector,NKVLocalStorage,NKVRAM,NKVRedis,NKVService,NullAgentData,NullManagedVault,NullRouter,NullVault,O3_AND_O4_MODELS,O3_AND_O4_MODELS_PATTERN,OSResourceMonitor,OTel,OTelContextRegistry,OllamaConnector,OpenAIConnector,OpenAIEmbeds,OpenAPIParser,PerplexityConnector,PineconeVectorDB,PromptGenerator,RAMCache,RAMVectorDB,REQUEST_CONTENT_TYPES,REQUEST_METHODS,RedisCache,ReverseLevelMap,ReverseRoleMap,RoleMap,RouterConnector,RouterService,RuntimeContext,S3Cache,S3Storage,S3_DAILY_PURGE_LIFECYCLE_TAG,S3_MONTHLY_PURGE_LIFECYCLE_TAG,S3_WEEKLY_PURGE_LIFECYCLE_TAG,SEARCH_TOOL_COSTS,SRE,SUPPORTED_MIME_TYPES_MAP,Schedule,SchedulerConnector,SchedulerService,ScrapflyWebScrape,SecretManagerManagedVault,SecretsManager,SecureConnector,ServerlessCode,SmythFS,SmythRuntime,SmythURI,StorageConnector,StorageService,SystemEvents,TAccessLevel,TAccessResult,TAccessRole,TConnectorService,TDataSourceCompErrorCodes,THook,TLLMCredentials,TLLMEvent,TLLMMessageRole,TLLMProvider,TOOL_USE_DEFAULT_MODEL,TPLProcessor,TToolType,TavilyWebSearch,TelemetryConnector,TelemetryService,TemplateString,TemplateStringHelper,Trigger,USER_CUSTOM_MODELS_SETTING_KEY,VaultConnector,VaultHelper,VaultService,VectorDBConnector,VectorDBService,VertexAIConnector,VisionLLM,WhatsAppTrigger,ZapierAction,boot,buildOAuth1Header,cachePrefix,cacheTTL,calculateExecutionCost,checkAndInstallLifecycleRules,createOrUpdateLambdaFunction,customModels,destroyPublicUrls,escapeJsonField,escapeString,extractAdditionalParamsForOAuth1,extractAllKeyNamesFromTemplateVars,extractKeyFromTemplateVar,findSmythPath,findValidResourcePath,generateCodeFromLegacyComponent,generateCodeHash,generateExecutableCode,generateExpiryMetadata,generateLambdaCode,generateLifecycleRules,generateServiceKey,getCredentials,getCurrentEnvironmentVariables,getDeployedCodeHash,getDeployedFunction,getLLMCredentials,getLambdaCredentials,getLambdaFunctionName,getLambdaRolePolicy,getNonExistingRules,getSanitizeCodeHash,getSortedObjectValues,handleOAuthHeaders,hook,hookAsync,hookAsyncWithContext,hookableClass,inputErrMsg,invokeLambdaFunction,isAgent,isValidGroqReasoningEffort,isValidOpenAIReasoningEffort,models,parseArrayBufferResponse,parseData,parseHeaders,parseProxy,parseSmythFsUrl,parseUrl,performTypeInference,reportUsage,retrieveOAuthTokens,runJs,setDeployedCodeHash,ttlToExpiryDays,updateDeployedCodeTTL,validateAsyncMainFunction,validateServiceKey,verifyFunctionDeploymentStatus,version,waitForRoleDeploymentStatus,xAIConnector,zipCode};
293
+ `}var __defProp$7=Object.defineProperty,__defNormalProp$7=(obj,key,value)=>key in obj?__defProp$7(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$7=(obj,key,value)=>__defNormalProp$7(obj,typeof key!="symbol"?key+"":key,value);const console$2=Logger("ECMASandbox");class ECMASandbox2 extends CodeConnector{constructor(config2){super(config2),__publicField$7(this,"name","ECMASandbox"),__publicField$7(this,"sandboxUrl"),this.sandboxUrl=config2.sandboxUrl}async prepare(acRequest,codeUID,input,config2){return{prepared:!0,errors:[],warnings:[]}}async deploy(acRequest,codeUID,input,config2){return{id:codeUID,runtime:config2.runtime,createdAt:new Date,status:"Deployed"}}async execute(acRequest,codeUID,inputs,config2){try{const{isValid,error,parameters}=validateAsyncMainFunction(inputs.code);if(!isValid)return{output:void 0,executionTime:0,success:!1,errors:[error]};const executableCode=generateExecutableCode(inputs.code,parameters,inputs.inputs);if(this.sandboxUrl){console$2.debug("Running code in remote sandbox");const executionStartTime=Date.now(),result=await axios.post(this.sandboxUrl,{code:executableCode}).catch(error2=>({error:error2})),executionTime=Date.now()-executionStartTime;if(result.error){const error2=result.error?.response?.data||result.error?.message||result.error.toString()||"Unknown error";return console$2.error(`Error running code: ${JSON.stringify(error2,null,2)}`),{output:void 0,executionTime,success:!1,errors:[error2]}}else return console$2.debug(`Code result: ${result?.data?.Output}`),{output:result.data?.Output,executionTime,success:!0,errors:[]}}else{console$2.debug("Running code in isolated vm");const executionStartTime=Date.now(),result=await runJs(executableCode),executionTime=Date.now()-executionStartTime;return console$2.debug(`Code result: ${result}`),{output:result,executionTime,success:!0,errors:[]}}}catch(error){return console$2.error(`Error running code: ${error}`),{output:void 0,executionTime:0,success:!1,errors:[error]}}}async executeDeployment(acRequest,codeUID,deploymentId,inputs,config2){return await this.execute(acRequest,codeUID,inputs,config2)}async listDeployments(acRequest,codeUID,config2){return[]}async getDeployment(acRequest,codeUID,deploymentId,config2){return null}async deleteDeployment(acRequest,codeUID,deploymentId){}async getResourceACL(resourceId,candidate){const acl=new ACL;return acl.addAccess(candidate.role,candidate.id,TAccessLevel.Read),acl}}class CodeService extends ConnectorServiceProvider{register(){ConnectorService.register(TConnectorService.Code,"AWSLambda",AWSLambdaCode),ConnectorService.register(TConnectorService.Code,"ECMASandbox",ECMASandbox2)}}var __defProp$6=Object.defineProperty,__defNormalProp$6=(obj,key,value)=>key in obj?__defProp$6(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$6=(obj,key,value)=>__defNormalProp$6(obj,key+"",value);class SchedulerConnector extends SecureConnector{constructor(settings){super(settings),__publicField$6(this,"_eventEmitter"),this._eventEmitter=new EventEmitter$1}requester(candidate){return{list:async()=>await this.list(candidate.readRequest),add:async(jobId,job,schedule)=>{const accountConnector=ConnectorService.getAccountConnector(),agentTeam=await accountConnector.getCandidateTeam(AccessCandidate.agent(job.agentId)),candidateTeam=await accountConnector.getCandidateTeam(candidate);if(agentTeam!==candidateTeam)throw new Error(`Candidate ${candidate.id} is not authorized to schedule a job for agent ${job.agentId}`);await this.add(candidate.writeRequest,jobId,job,schedule)},delete:async jobId=>{await this.delete(candidate.writeRequest,jobId)},get:async jobId=>await this.get(candidate.readRequest,jobId),pause:async jobId=>{await this.pause(candidate.writeRequest,jobId)},resume:async jobId=>{await this.resume(candidate.writeRequest,jobId)},on:(event,listener)=>{this.on(event,listener)},off:(event,listener)=>{this.off(event,listener)}}}constructJobKey(candidate,jobId){return`${candidate.role}_${candidate.id}_${jobId}`}emit(event,...args){return this._eventEmitter.emit(event,...args)}on(event,listener){return this._eventEmitter.on(event,listener),this}off(event,listener){return this._eventEmitter.off(event,listener),this}}var __defProp$5=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__defNormalProp$5=(obj,key,value)=>key in obj?__defProp$5(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__decorateClass$1=(decorators,target,key,kind)=>{for(var result=__getOwnPropDesc$1(target,key),i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=decorator(target,key,result)||result);return result&&__defProp$5(target,key,result),result},__publicField$5=(obj,key,value)=>__defNormalProp$5(obj,typeof key!="symbol"?key+"":key,value);const logger$2=Logger("LocalScheduler"),_LocalScheduler=class _LocalScheduler2 extends SchedulerConnector{constructor(_settings){super(_settings),this._settings=_settings,__publicField$5(this,"name","LocalScheduler"),__publicField$5(this,"id","local"),__publicField$5(this,"folder"),__publicField$5(this,"jobsPrefix","jobs"),__publicField$5(this,"runtimePrefix",".jobs.runtime"),__publicField$5(this,"isInitialized",!1),__publicField$5(this,"config"),this.config={folder:_settings?.folder||"",runJobs:_settings?.runJobs!==!1,persistExecutionHistory:_settings?.persistExecutionHistory!==!1,maxHistoryEntries:_settings?.maxHistoryEntries||100},this.folder=this.findSchedulerFolder(this.config.folder),this.initialize(),fs__default.existsSync(this.folder)||logger$2.warn(`Invalid folder provided: ${this.folder}`)}findSchedulerFolder(folder){let _schedulerFolder=folder;return _schedulerFolder&&fs__default.existsSync(_schedulerFolder)?_schedulerFolder:(_schedulerFolder=findSmythPath("scheduler"),fs__default.existsSync(_schedulerFolder)?(logger$2.warn("Using alternative scheduler folder found in : ",_schedulerFolder),_schedulerFolder):(logger$2.warn("!!! All attempts to find an existing scheduler folder failed !!!"),logger$2.warn("!!! I will use this folder: ",_schedulerFolder),_schedulerFolder))}async initialize(){const jobsFolderPath=path.join(this.folder,this.jobsPrefix);fs__default.existsSync(jobsFolderPath)||(fs__default.mkdirSync(jobsFolderPath,{recursive:!0}),fs__default.writeFileSync(path.join(jobsFolderPath,"README_IMPORTANT.txt"),"This folder contains scheduler job configurations. Do not delete it."));const runtimeFolderPath=path.join(this.folder,this.runtimePrefix);fs__default.existsSync(runtimeFolderPath)||(fs__default.mkdirSync(runtimeFolderPath,{recursive:!0}),fs__default.writeFileSync(path.join(runtimeFolderPath,"README_IMPORTANT.txt"),"This folder contains scheduler runtime data and execution history. Safe to delete if needed.")),this.config.runJobs&&await this.loadJobsFromDisk(),this.isInitialized=!0,logger$2.info(`LocalScheduler initialized (runJobs: ${this.config.runJobs})`)}getCandidateFolderName(candidate){return`${candidate.id}.${candidate.role}`}getJobFilePath(candidate,jobId,createFoldersIfNotExists=!1){const candidateFolder=this.getCandidateFolderName(candidate),jobFilename=jobId,fullPath=path.join(this.folder,this.jobsPrefix,candidateFolder,`${jobFilename}.json`);if(createFoldersIfNotExists){const folder=path.dirname(fullPath);fs__default.existsSync(folder)||fs__default.mkdirSync(folder,{recursive:!0})}return fullPath}getRuntimeFilePath(candidate,jobId,createFoldersIfNotExists=!1){const candidateFolder=this.getCandidateFolderName(candidate),jobFilename=jobId,fullPath=path.join(this.folder,this.runtimePrefix,candidateFolder,`${jobFilename}.json`);if(createFoldersIfNotExists){const folder=path.dirname(fullPath);fs__default.existsSync(folder)||fs__default.mkdirSync(folder,{recursive:!0})}return fullPath}async loadJobsFromDisk(){try{const jobsFolderPath=path.join(this.folder,this.jobsPrefix);if(!fs__default.existsSync(jobsFolderPath))return;const candidateFolders=fs__default.readdirSync(jobsFolderPath).filter(f=>{const fullPath=path.join(jobsFolderPath,f);return fs__default.statSync(fullPath).isDirectory()});for(const candidateFolder of candidateFolders){const lastDotIndex=candidateFolder.lastIndexOf(".");if(lastDotIndex===-1){logger$2.warn(`Invalid candidate folder format: ${candidateFolder}`);continue}const candidateId=candidateFolder.substring(0,lastDotIndex),candidateRole=candidateFolder.substring(lastDotIndex+1),candidate={id:candidateId,role:candidateRole},candidatePath=path.join(jobsFolderPath,candidateFolder),jobFiles=fs__default.readdirSync(candidatePath).filter(f=>f.endsWith(".json"));for(const file of jobFiles)try{const filePath=path.join(candidatePath,file),data=fs__default.readFileSync(filePath,"utf-8"),jobConfig=JSON.parse(data),runtimeData=await this.loadRuntimeDataFromDisk(candidate,jobConfig.id),jobData={...jobConfig,...runtimeData,candidateRole:candidate.role,candidateId:candidate.id},jobKey=this.constructJobKey(candidate,jobData.id);_LocalScheduler2.jobs.set(jobKey,jobData),jobData.status==="active"&&(logger$2.info(`Job ${jobData.id} loaded from ${candidateFolder} and scheduled for execution`),await this.scheduleJob(jobData))}catch(error){logger$2.warn(`Error loading job file ${file} from ${candidateFolder}:`,error)}}logger$2.info(`Loaded ${_LocalScheduler2.jobs.size} jobs from disk`)}catch(error){logger$2.warn("Error loading jobs from disk",error)}}async saveJobToDisk(candidate,jobData){try{const filePath=this.getJobFilePath(candidate,jobData.id,!0),{executionHistory,lastRun,nextRun,candidateRole,candidateId,createdBy,...configData}=jobData;fs__default.writeFileSync(filePath,JSON.stringify(configData,null,2),"utf-8")}catch(error){throw logger$2.warn(`Error saving job ${jobData.id} to disk`,error),error}}async saveRuntimeDataToDisk(candidate,jobData){try{const filePath=this.getRuntimeFilePath(candidate,jobData.id,!0),runtimeData={executionHistory:jobData.executionHistory||[],lastRun:jobData.lastRun,nextRun:jobData.nextRun};fs__default.writeFileSync(filePath,JSON.stringify(runtimeData,null,2),"utf-8")}catch(error){logger$2.warn(`Error saving runtime data for job ${jobData.id}`,error);return}}async loadRuntimeDataFromDisk(candidate,jobId){try{const filePath=this.getRuntimeFilePath(candidate,jobId);if(!fs__default.existsSync(filePath))return{};const data=fs__default.readFileSync(filePath,"utf-8");return JSON.parse(data)}catch(error){return logger$2.warn(`Error loading runtime data for job ${jobId}`,error),{}}}async deleteJobFromDisk(candidate,jobId){try{const jobFilePath=this.getJobFilePath(candidate,jobId);fs__default.existsSync(jobFilePath)&&fs__default.unlinkSync(jobFilePath);const runtimeFilePath=this.getRuntimeFilePath(candidate,jobId);fs__default.existsSync(runtimeFilePath)&&fs__default.unlinkSync(runtimeFilePath)}catch(error){logger$2.warn(`Error deleting job ${jobId} from disk`,error);return}}async scheduleJob(jobData){if(jobData.status!=="active")return;const validation=Schedule.fromJSON(jobData.schedule).validate();if(!validation.valid)throw logger$2.warn(`Invalid schedule for job ${jobData.id}: ${validation.error}`),new Error(`Invalid schedule for job ${jobData.id}: ${validation.error}`);const jobKey=this.constructJobKey({role:jobData.candidateRole,id:jobData.candidateId},jobData.id),existingTimer=_LocalScheduler2.timers.get(jobKey);if(existingTimer&&(logger$2.info(`Clearing existing timer for job ${jobData.id} (overwriting duplicate schedule)`),clearInterval(existingTimer),_LocalScheduler2.timers.delete(jobKey)),jobData.schedule.interval){const intervalMs=Schedule.parseInterval(jobData.schedule.interval),timer=setInterval(async()=>{await this.executeJob(jobData)},intervalMs);timer.unref(),_LocalScheduler2.timers.set(jobKey,timer)}if(jobData.schedule.cron)throw logger$2.warn(`Cron scheduling not yet implemented for job ${jobData.id}`),new Error(`Cron scheduling not yet implemented for job ${jobData.id}`)}async unscheduleJob(jobKey){const timer=_LocalScheduler2.timers.get(jobKey);timer&&(clearInterval(timer),_LocalScheduler2.timers.delete(jobKey))}async executeJob(jobData){if(!jobData.jobConfig){logger$2.warn(`Skipping execution of job ${jobData.id}: job configuration not available.`);return}const schedule=Schedule.fromJSON(jobData.schedule);if(!schedule.shouldRun()){logger$2.info(`Job ${jobData.id} skipped - outside schedule window`);return}const job=Job.fromJSON(jobData.jobConfig);logger$2.debug(`Executing job ${jobData.id} with metadata:`,JSON.stringify(jobData.jobConfig.metadata));const owner=jobData.createdBy;this.emit("executing",{id:jobData.id,job,owner});const result=await job.executeWithRetry();this.emit("executed",{id:jobData.id,job,owner,result}),jobData.lastRun=new Date().toISOString();const nextRun=schedule.calculateNextRun(new Date(jobData.lastRun));jobData.nextRun=nextRun?nextRun.toISOString():void 0,result.success||logger$2.warn(`Job ${jobData.id} failed:`,result.error?.message),this.config.persistExecutionHistory&&(jobData.executionHistory||(jobData.executionHistory=[]),jobData.executionHistory.unshift({timestamp:new Date().toISOString(),success:result.success,error:result.error?.message,executionTime:result.executionTime,retries:result.retries}),jobData.executionHistory.length>this.config.maxHistoryEntries&&(jobData.executionHistory=jobData.executionHistory.slice(0,this.config.maxHistoryEntries)));const candidate={role:jobData.candidateRole,id:jobData.candidateId};await this.saveJobToDisk(candidate,jobData),this.config.persistExecutionHistory&&await this.saveRuntimeDataToDisk(candidate,jobData)}async getResourceACL(resourceId,candidate){this.isInitialized||await this.initialize();const accountConnector=ConnectorService.getAccountConnector(),teamId=await accountConnector.getCandidateTeam(candidate),jobKey=this.constructJobKey(candidate,resourceId),jobData=_LocalScheduler2.jobs.get(jobKey),jobAgentTeamId=jobData?.jobConfig?.agentId?await accountConnector.getCandidateTeam(AccessCandidate.agent(jobData?.jobConfig?.agentId)):null;return jobAgentTeamId&&teamId!==jobAgentTeamId?new ACL:jobData?ACL.from(jobData.acl):new ACL().addAccess(candidate.role,candidate.id,TAccessLevel.Owner)}async list(acRequest){this.isInitialized||await this.initialize();const result=[];for(const[key,jobData]of _LocalScheduler2.jobs)if(jobData.candidateRole===acRequest.candidate.role&&jobData.candidateId===acRequest.candidate.id){const{candidateRole,candidateId,...serializableData}=jobData;result.push(serializableData)}return result}async add(acRequest,jobId,job,schedule){this.isInitialized||await this.initialize();const validation=schedule.validate();if(!validation.valid){logger$2.warn(`Invalid schedule: ${validation.error}`);return}const jobKey=this.constructJobKey(acRequest.candidate,jobId),existingJob=_LocalScheduler2.jobs.get(jobKey);let acl;existingJob?acl=ACL.from(existingJob.acl).addAccess(acRequest.candidate.role,acRequest.candidate.id,TAccessLevel.Owner):acl=new ACL().addAccess(acRequest.candidate.role,acRequest.candidate.id,TAccessLevel.Owner);const nextRun=schedule.calculateNextRun(),jobData={id:jobId,schedule:schedule.toJSON(),jobConfig:job.toJSON(),acl:acl.ACL,status:"active",nextRun:nextRun?nextRun.toISOString():void 0,createdBy:{role:acRequest.candidate.role,id:acRequest.candidate.id},candidateRole:acRequest.candidate.role,candidateId:acRequest.candidate.id,executionHistory:existingJob?.executionHistory||[]};existingJob&&await this.unscheduleJob(jobKey),_LocalScheduler2.jobs.set(jobKey,jobData),await this.saveJobToDisk(acRequest.candidate,jobData),this.config.runJobs&&await this.scheduleJob(jobData),logger$2.info(`Job ${jobId} added successfully`)}async delete(acRequest,jobId){this.isInitialized||await this.initialize();const jobKey=this.constructJobKey(acRequest.candidate,jobId);if(!_LocalScheduler2.jobs.get(jobKey)){logger$2.warn(`Job ${jobId} not found`);return}await this.unscheduleJob(jobKey),_LocalScheduler2.jobs.delete(jobKey),await this.deleteJobFromDisk(acRequest.candidate,jobId),logger$2.info(`Job ${jobId} deleted successfully`)}async get(acRequest,jobId){this.isInitialized||await this.initialize();const jobKey=this.constructJobKey(acRequest.candidate,jobId),jobData=_LocalScheduler2.jobs.get(jobKey);if(!jobData)return;const{candidateRole,candidateId,...serializableData}=jobData;return serializableData}async pause(acRequest,jobId){this.isInitialized||await this.initialize();const jobKey=this.constructJobKey(acRequest.candidate,jobId),jobData=_LocalScheduler2.jobs.get(jobKey);if(!jobData){logger$2.warn(`Job ${jobId} not found`);return}jobData.status!=="paused"&&(await this.unscheduleJob(jobKey),jobData.status="paused",await this.saveJobToDisk(acRequest.candidate,jobData),logger$2.info(`Job ${jobId} paused`))}async resume(acRequest,jobId){this.isInitialized||await this.initialize();const jobKey=this.constructJobKey(acRequest.candidate,jobId),jobData=_LocalScheduler2.jobs.get(jobKey);if(!jobData){logger$2.warn(`Job ${jobId} not found`);return}jobData.status==="paused"&&(jobData.status="active",await this.saveJobToDisk(acRequest.candidate,jobData),this.config.runJobs&&await this.scheduleJob(jobData),logger$2.info(`Job ${jobId} resumed`))}async shutdown(){logger$2.info("Shutting down LocalScheduler...");const timerCount=_LocalScheduler2.timers.size;for(const[jobKey,timer]of _LocalScheduler2.timers)clearInterval(timer);_LocalScheduler2.timers.clear(),logger$2.info(`LocalScheduler shutdown complete (cleared ${timerCount} timers)`)}};__publicField$5(_LocalScheduler,"jobs",new Map),__publicField$5(_LocalScheduler,"timers",new Map),__decorateClass$1([SecureConnector.AccessControl],_LocalScheduler.prototype,"list"),__decorateClass$1([SecureConnector.AccessControl],_LocalScheduler.prototype,"add"),__decorateClass$1([SecureConnector.AccessControl],_LocalScheduler.prototype,"delete"),__decorateClass$1([SecureConnector.AccessControl],_LocalScheduler.prototype,"get"),__decorateClass$1([SecureConnector.AccessControl],_LocalScheduler.prototype,"pause"),__decorateClass$1([SecureConnector.AccessControl],_LocalScheduler.prototype,"resume");let LocalScheduler=_LocalScheduler;class SchedulerService extends ConnectorServiceProvider{register(){ConnectorService.register(TConnectorService.Scheduler,"LocalScheduler",LocalScheduler)}}class TelemetryConnector extends SecureConnector{constructor(){super()}requester(candidate){return{}}}var __defProp$4=Object.defineProperty,__defNormalProp$4=(obj,key,value)=>key in obj?__defProp$4(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$4=(obj,key,value)=>__defNormalProp$4(obj,key+"",value);class OTelContextRegistry{static key(agentId,processId){return`${agentId}:${processId}`}static startProcess(agentId,processId,span){this.registry.set(this.key(agentId,processId),{agentId,processId,rootSpan:span})}static get(agentId,processId){return this.registry.get(this.key(agentId,processId))}static update(agentId,processId,ctx){const key=this.key(agentId,processId),current=this.registry.get(key);current&&this.registry.set(key,{...current,...ctx})}static endProcess(agentId,processId){this.registry.delete(this.key(agentId,processId))}}__publicField$4(OTelContextRegistry,"registry",new Map);var __defProp$3=Object.defineProperty,__defNormalProp$3=(obj,key,value)=>key in obj?__defProp$3(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$3=(obj,key,value)=>__defNormalProp$3(obj,typeof key!="symbol"?key+"":key,value);const outputLogger=Logger("OTel");class OTel extends TelemetryConnector{constructor(_settings){if(super(),this._settings=_settings,__publicField$3(this,"name","OTel"),__publicField$3(this,"id"),__publicField$3(this,"tracer"),__publicField$3(this,"logger"),__publicField$3(this,"tracerProvider"),__publicField$3(this,"loggerProvider"),!_settings.endpoint){outputLogger.warn("OTel initialization skipped, endpoint is not set");return}outputLogger.log("Initializing Tracer ...");const traceExporter=new OTLPTraceExporter({url:`${_settings.endpoint}/v1/traces`,headers:_settings.headers}),spanProcessor=new BatchSpanProcessor(traceExporter),resource=resourceFromAttributes({[ATTR_SERVICE_NAME]:_settings.serviceName||"smythos",[ATTR_SERVICE_VERSION]:_settings.serviceVersion||"1.0.0"});this.tracerProvider=new NodeTracerProvider({resource,spanProcessors:[spanProcessor]}),this.tracerProvider.register(),outputLogger.log("Initializing Log Exporter ...");const logExporter=new OTLPLogExporter({url:`${_settings.endpoint}/v1/logs`,headers:_settings.headers}),logProcessor=new BatchLogRecordProcessor(logExporter);this.loggerProvider=new LoggerProvider({resource,processors:[logProcessor]}),logs.setGlobalLoggerProvider(this.loggerProvider),this.tracer=trace.getTracer("smythos.agent"),this.logger=logs.getLogger("smythos.agent"),this.id=`otel-${_settings.endpoint}`,this.setupHooks()}async stop(){outputLogger.log(`Stopping ${this.name} connector ...`),await this.tracerProvider.forceFlush?.().catch(error=>{outputLogger.error("Error forcing flush of tracer provider",error)}),await this.tracerProvider.shutdown?.().catch(error=>{outputLogger.error("Error shutting down tracer provider",error)}),await this.loggerProvider.forceFlush().catch(error=>{outputLogger.error("Error forcing flush of logger provider",error)}),await this.loggerProvider.shutdown().catch(error=>{outputLogger.error("Error shutting down logger provider",error)})}redactSensitiveData(data,redactFields){if(!redactFields||redactFields.length===0||typeof data!="object"||data===null)return data;const redacted=Array.isArray(data)?[...data]:{...data};for(const key in redacted)redactFields.some(field=>key.toLowerCase().includes(field.toLowerCase()))?redacted[key]="[REDACTED]":typeof redacted[key]=="object"&&redacted[key]!==null&&(redacted[key]=this.redactSensitiveData(redacted[key],redactFields));return redacted}formatOutputForLog(output,isError=!1){const config2=this._settings,maxSize=config2.maxOutputSize??10*1024;if((config2.fullOutputOnErrorOnly??!1)&&!isError)return;const redacted=this.redactSensitiveData(output,config2.redactFields),outputStr=JSON.stringify(redacted);return outputStr&&outputStr.length>maxSize?`${outputStr.substring(0,maxSize)}...[TRUNCATED: ${outputStr.length} bytes, limit: ${maxSize} bytes]`:outputStr}getResourceACL(resourceId,candidate){return Promise.resolve(new ACL)}log(acRequest,logData,callId){return Promise.resolve()}logTask(acRequest,tasks,isUsingTestDomain){return Promise.resolve()}prepareComponentData(data,prefix,maxEntryLength=200){const result={};for(let key in data)result[prefix?`${prefix}.${key}`:key]=(typeof data[key]=="object"?JSON.stringify(data[key]):data[key].toString()).substring(0,maxEntryLength);return result}setupHooks(){const tracer=this.tracer,logger2=this.logger,oTelInstance=this,createToolInfoHandler=function(hookContext){return function(toolInfo){const accessCandidate=AccessCandidate.agent(hookContext?.agentId);if(outputLogger.debug("createToolInfoHandler started",accessCandidate),!hookContext.curLLMGenSpan||!hookContext.convSpan)return;const modelId=toolInfo.model,lastContext=toolInfo.contextWindow.filter(context2=>context2.role==="user").slice(-2),toolNames=toolInfo.map(tool=>tool.name+"("+tool.arguments+")");hookContext.curLLMGenSpan.addEvent("llm.gen.tool.calls",{"tool.calls":toolNames.join(", "),"llm.model":modelId||"unknown","context.preview":JSON.stringify(lastContext).substring(0,200)});const spanContext=trace.setSpan(context.active(),hookContext.curLLMGenSpan);context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.INFO,severityText:"INFO",body:`LLM tool calls: ${toolNames.join(", ")}`,attributes:{"agent.id":hookContext.agentId,"conv.id":hookContext.processId,"llm.model":modelId||"unknown","context.preview":JSON.stringify(lastContext).substring(0,5e3)}})}),hookContext.curLLMGenSpan.end(),delete hookContext.curLLMGenSpan,outputLogger.debug("createToolInfoHandler completed",accessCandidate)}},createDataHandler=function(hookContext){return function(data,reqInfo){if(!hookContext.convSpan||hookContext.curLLMGenSpan)return;const accessCandidate=AccessCandidate.agent(hookContext?.agentId);outputLogger.debug("createDataHandler started",reqInfo?.requestId,accessCandidate);const modelId=reqInfo.model,lastContext=reqInfo.contextWindow.filter(context2=>context2.role==="user").slice(-2);if(hookContext?.latencySpans?.[reqInfo.requestId]){const ttfbSpan=hookContext.latencySpans[reqInfo.requestId];ttfbSpan.addEvent("llm.first.byte.received",{"request.id":reqInfo.requestId,"data.size":JSON.stringify(data||{}).length,"llm.model":modelId||"unknown"}),ttfbSpan.setStatus({code:SpanStatusCode.OK}),ttfbSpan.end(),delete hookContext.latencySpans[reqInfo.requestId]}const llmGenSpan=tracer.startSpan("Conv.GenAI",{attributes:{"agent.id":hookContext.agentId,"conv.id":hookContext.processId,"team.id":hookContext.teamId,"llm.model":modelId||"unknown"}},trace.setSpan(context.active(),hookContext.convSpan));llmGenSpan.addEvent("llm.gen.started",{"request.id":reqInfo.requestId,timestamp:Date.now(),"llm.model":modelId||"unknown","context.preview":JSON.stringify(lastContext).substring(0,200)}),hookContext.curLLMGenSpan=llmGenSpan,outputLogger.debug("createDataHandler completed",reqInfo?.requestId,accessCandidate)}},createRequestedHandler=function(hookContext){return function(reqInfo){if(!hookContext.convSpan)return;const accessCandidate=AccessCandidate.agent(hookContext?.agentId);outputLogger.debug("createRequestedHandler started",reqInfo?.requestId,accessCandidate),hookContext.latencySpans||(hookContext.latencySpans={});const lastContext=reqInfo.contextWindow.filter(context2=>context2.role==="user").slice(-2),modelId=reqInfo.model,llmGenLatencySpan=tracer.startSpan("Conv.GenAI.TTFB",{attributes:{"agent.id":hookContext.agentId,"conv.id":hookContext.processId,"team.id":hookContext.teamId,"request.id":reqInfo.requestId,"llm.model":modelId||"unknown","metric.type":"ttfb"}},trace.setSpan(context.active(),hookContext.convSpan));llmGenLatencySpan.addEvent("llm.requested",{"request.id":reqInfo.requestId,timestamp:Date.now(),"context.preview":JSON.stringify(lastContext).substring(0,200)}),hookContext.latencySpans[reqInfo.requestId]=llmGenLatencySpan,outputLogger.debug("createRequestedHandler completed",reqInfo?.requestId,accessCandidate)}};return HookService.register("Conversation.streamPrompt",async function(additionalContext,args){const conversation=this.instance,processId=conversation.storeId||conversation.id,agentId=conversation.agentId,message=typeof args=="object"?args?.message:args||null,hookContext=this.context,teamId=conversation.agentData.teamId,orgTier="standard",orgSlot=this.instance.agentData?.planInfo?.flags?`standard/${teamId}`:void 0,agentData=conversation.agentData||{},isDebugSession=agentData.debugSessionEnabled||!1,isTestDomain=agentData.usingTestDomain||!1,sessionId=processId,workflowId=agentData?.workflowReqId||agentData?.workflowID||agentData?.workflowId||void 0,logTags=agentData?.sessionTag||(isDebugSession?"DEBUG":void 0);if(message==null)return;const accessCandidate=AccessCandidate.agent(agentId);outputLogger.debug("Conversation.streamPrompt started",{processId,message},accessCandidate);const modelId=typeof conversation?.model=="string"?conversation?.model:conversation?.model?.modelId,convSpan=tracer.startSpan("Agent.Conv",{attributes:{"gen_ai.operation.name":"chat","gen_ai.provider.name":conversation?.llmInference?.llmProviderName||"unknown","gen_ai.conversation.id":processId,"gen_ai.request.model":modelId||"unknown","team.id":teamId,"org.tier":orgTier,"org.slot":orgSlot,"agent.id":agentId,"conv.id":processId,"llm.model":modelId||"unknown","agent.debug":isDebugSession,"agent.isTest":isTestDomain,"session.id":sessionId,"workflow.id":workflowId}});hookContext.convSpan=convSpan,hookContext.agentId=agentId,hookContext.processId=processId,hookContext.teamId=teamId,hookContext.orgSlot=orgSlot,hookContext.isDebugSession=isDebugSession,hookContext.isTestDomain=isTestDomain;let headers={};const traceContext=trace.setSpan(context.active(),convSpan);propagation.inject(traceContext,headers);for(let[key,value]of Object.entries(headers))conversation.headers[key]=value;outputLogger.debug("Injected trace headers into conversation",{processId,headers}),hookContext.dataHandler=createDataHandler(hookContext),conversation.on(TLLMEvent.Data,hookContext.dataHandler),hookContext.requestedHandler=createRequestedHandler(hookContext),conversation.on(TLLMEvent.Requested,hookContext.requestedHandler),hookContext.toolInfoHandler=createToolInfoHandler(hookContext),conversation.on(TLLMEvent.ToolInfo,hookContext.toolInfoHandler),convSpan.addEvent("skill.process.started",{"input.size":JSON.stringify(message||{}).length,"input.preview":message.substring(0,200),"llm.model":modelId||"unknown"}),OTelContextRegistry.startProcess(agentId,processId,convSpan);const spanCtx=convSpan.spanContext(),spanContext=trace.setSpan(context.active(),convSpan);context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.INFO,severityText:"INFO",body:`Conversation.streamPrompt started: ${processId}`,attributes:{trace_id:spanCtx.traceId,span_id:spanCtx.spanId,trace_flags:spanCtx.traceFlags,"team.id":teamId,"org.slot":orgSlot,"agent.id":agentId,"conv.id":processId,"input.size":JSON.stringify(message||{}).length,"input.preview":message.substring(0,2e3),"agent.debug":isDebugSession,"agent.isTest":isTestDomain,"session.id":sessionId,"workflow.id":workflowId,"log.tags":logTags}})})},THook.NonBlocking),HookService.registerAfter("Conversation.streamPrompt",async function({result,args,error}){const conversation=this.instance,processId=conversation.storeId||conversation.id,agentId=conversation.agentId,message=typeof args?.[0]=="object"?args?.[0]?.message:args?.[0]||null,hookContext=this.context,teamId=conversation.agentData.teamId,orgTier="standard",orgSlot=this.instance.agentData?.planInfo?.flags?`standard/${teamId}`:void 0,isDebugSession=hookContext.isDebugSession||conversation.agentData?.debugSessionEnabled||!1,isTestDomain=hookContext.isTestDomain||conversation.agentData?.usingTestDomain||!1,agentData=conversation.agentData||{},sessionId=processId,workflowId=agentData?.workflowReqId||agentData?.workflowID||agentData?.workflowId||void 0,logTags=agentData?.sessionTag||(isDebugSession?"DEBUG":void 0);if(message==null)return;const ctx=OTelContextRegistry.get(agentId,processId);if(!ctx)return;const accessCandidate=AccessCandidate.agent(agentId);outputLogger.debug("Conversation.streamPrompt completed",{processId},accessCandidate),hookContext.curLLMGenSpan&&(error&&hookContext.curLLMGenSpan.setStatus({code:SpanStatusCode.ERROR,message:error.message}),hookContext.curLLMGenSpan.addEvent("llm.gen.content",{"content.size":JSON.stringify(result||{}).length,"content.preview":typeof result=="string"?result.substring(0,200):JSON.stringify(result||{}).substring(0,200)}),hookContext.curLLMGenSpan.end(),hookContext.toolInfoHandler&&conversation.off(TLLMEvent.ToolInfo,hookContext.toolInfoHandler),hookContext.dataHandler&&conversation.off(TLLMEvent.Data,hookContext.dataHandler),hookContext.requestedHandler&&conversation.off(TLLMEvent.Requested,hookContext.requestedHandler));const{rootSpan:convSpan}=ctx,spanCtx=convSpan.spanContext(),spanContext=trace.setSpan(context.active(),convSpan);error?(convSpan.recordException(error),convSpan.setStatus({code:SpanStatusCode.ERROR,message:error.message}),convSpan.addEvent("conv.error",{"error.message":error.message}),context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.ERROR,severityText:"ERROR",body:`Conversation.streamPrompt failed: ${processId}`,attributes:{trace_id:spanCtx.traceId,span_id:spanCtx.spanId,trace_flags:spanCtx.traceFlags,"agent.id":agentId,"conv.id":processId,"error.message":error.message,"error.stack":error.stack,"team.id":teamId,"org.tier":orgTier,"org.slot":orgSlot,"agent.debug":isDebugSession,"agent.isTest":isTestDomain,"session.id":sessionId,"workflow.id":workflowId,"log.tags":logTags}})})):(convSpan.setStatus({code:SpanStatusCode.OK}),context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.INFO,severityText:"INFO",body:`Conversation.streamPrompt completed: ${processId}`,attributes:{"agent.id":agentId,"conv.id":processId,"output.size":JSON.stringify(result||{}).length,"output.preview":typeof result=="string"?result.substring(0,2e3):JSON.stringify(result||{}).substring(0,2e3),"team.id":teamId,"org.tier":orgTier,"org.slot":orgSlot,"agent.debug":isDebugSession,"agent.isTest":isTestDomain,"session.id":sessionId,"workflow.id":workflowId,"log.tags":logTags}})})),convSpan.end(),OTelContextRegistry.endProcess(agentId,processId)},THook.NonBlocking),HookService.register("SREAgent.process",async function(endpointPath,inputData){const agent=this.instance,agentProcessId=agent.agentRuntime.processID,conversationId=agent.conversationId||agent.agentRequest?.header("X-CONVERSATION-ID"),processId=agentProcessId.split(":").shift(),orgTier="standard",orgSlot=agent.data.planInfo?.flags?`standard/${agent.data.teamId}`:void 0,agentId=agent.id,agentRequest=agent.agentRequest,teamId=agent.teamId,_hookContext=this.context,sessionId=agent.callerSessionId||void 0,workflowId=agent.agentRuntime?.workflowReqId||void 0,isDebugSession=agent.debugSessionEnabled||agent.agentRuntime?.debug||!1,logTags=agent.sessionTag||(isDebugSession?"DEBUG":void 0),isTestDomain=agent.usingTestDomain||!1,domain=agent.domain||void 0,accessCandidate=AccessCandidate.agent(agentId);outputLogger.debug("SREAgent.process started",{processId,agentProcessId,endpointPath},accessCandidate);const body=oTelInstance.prepareComponentData(agentRequest.body||{}),query=oTelInstance.prepareComponentData(agentRequest.query||{}),headers=oTelInstance.prepareComponentData(agentRequest.headers||{}),agentInput=oTelInstance.prepareComponentData(inputData||{}),input={body,query,headers,processInput:agentInput};let convSpan,parentContext=context.active(),ctx=OTelContextRegistry.get(agentId,processId)||OTelContextRegistry.get(agentId,conversationId);if(ctx)convSpan=ctx.rootSpan,_hookContext.otelSpan=convSpan,parentContext=trace.setSpan(context.active(),convSpan);else{const extractedContext=propagation.extract(context.active(),agentRequest.headers),extractedSpan=trace.getSpan(extractedContext);extractedSpan&&(parentContext=extractedContext,outputLogger.debug("SREAgent.process extracted remote parent context from headers",{processId,traceId:extractedSpan.spanContext().traceId}))}const agentSpan=tracer.startSpan("Agent.Skill",{attributes:{"agent.id":agentId,"team.id":teamId,"conv.id":conversationId,"process.id":agentProcessId,"org.slot":orgSlot,"org.tier":orgTier,"session.id":sessionId,"workflow.id":workflowId,"agent.debug":isDebugSession,"agent.isTest":isTestDomain,"agent.domain":domain}},parentContext),inputPreview=JSON.stringify(input||{}).substring(0,200);agentSpan.addEvent("skill.process.started",{endpoint:endpointPath,"input.size":JSON.stringify(input||{}).length,"input.preview":inputPreview}),OTelContextRegistry.startProcess(agentId,agentProcessId,agentSpan);const spanCtx=agentSpan.spanContext(),spanContext=trace.setSpan(context.active(),agentSpan);context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.INFO,severityText:"INFO",body:`Agent Skill process started: ${processId}`,attributes:{trace_id:spanCtx.traceId,span_id:spanCtx.spanId,trace_flags:spanCtx.traceFlags,"agent.id":agentId,"process.id":agentProcessId,input:agentInput,body,query,headers,"team.id":teamId,"org.slot":orgSlot,"org.tier":orgTier,"conv.id":conversationId,"session.id":sessionId,"workflow.id":workflowId,"log.tags":logTags,"agent.debug":isDebugSession,"agent.isTest":isTestDomain,"agent.domain":domain}})})},THook.NonBlocking),HookService.registerAfter("SREAgent.process",async function({result,error}){const agent=this.instance,agentProcessId=agent.agentRuntime.processID,conversationId=agent.conversationId||agent.agentRequest?.header("X-CONVERSATION-ID"),agentId=agent.id;this.context;const teamId=agent.teamId,orgTier="standard",orgSlot=agent.data.planInfo?.flags?`standard/${agent.data.teamId}`:void 0,sessionId=agent.callerSessionId||void 0,workflowId=agent.agentRuntime?.workflowReqId||void 0,isDebugSession=agent.debugSessionEnabled||agent.agentRuntime?.debug||!1,logTags=agent.sessionTag||(isDebugSession?"DEBUG":void 0),isTestDomain=agent.usingTestDomain||!1,domain=agent.domain||void 0,ctx=OTelContextRegistry.get(agentId,agentProcessId);if(!ctx)return;const agentSpan=ctx.rootSpan;if(!agentSpan)return;const accessCandidate=AccessCandidate.agent(agentId);outputLogger.debug("SREAgent.process completed",{agentProcessId},accessCandidate);const hasResultError=!error&&(!!result?._error||!!result?.error),resultError=hasResultError?result._error||result.error:null,resultErrorMessage=resultError?.message||(typeof resultError=="string"?resultError:null),isError=!!error||hasResultError,errorMessage=error?.message||resultErrorMessage||"Process returned error";error?(agentSpan.recordException(error),agentSpan.setStatus({code:SpanStatusCode.ERROR,message:error.message}),agentSpan.addEvent("skill.process.error",{"error.message":error.message})):hasResultError?(agentSpan.setStatus({code:SpanStatusCode.ERROR,message:errorMessage}),agentSpan.addEvent("skill.process.error",{"error.message":errorMessage,"error.type":"result_error"}),agentSpan.setAttributes({"output.size":JSON.stringify(result||{}).length,"output.has_error":!0})):(agentSpan.setStatus({code:SpanStatusCode.OK}),agentSpan.addEvent("skill.process.completed",{"output.size":JSON.stringify(result||{}).length}),agentSpan.setAttributes({"output.size":JSON.stringify(result||{}).length}));const outputForLog=oTelInstance.formatOutputForLog(result,isError),spanCtx=agentSpan.spanContext(),logAttributes={trace_id:spanCtx.traceId,span_id:spanCtx.spanId,trace_flags:spanCtx.traceFlags,"agent.id":agentId,"process.id":agentProcessId,hasError:isError,"error.message":isError?errorMessage:void 0,"error.stack":error?.stack,"error.type":hasResultError?"result_error":void 0,"team.id":teamId,"org.slot":orgSlot,"org.tier":orgTier,"conv.id":conversationId,"session.id":sessionId,"workflow.id":workflowId,"log.tags":logTags,"agent.debug":isDebugSession,"agent.isTest":isTestDomain,"agent.domain":domain};outputForLog!==void 0&&(logAttributes["agent.output"]=outputForLog);const spanContext=trace.setSpan(context.active(),agentSpan);context.with(spanContext,()=>{logger2.emit({severityNumber:isError?SeverityNumber.ERROR:SeverityNumber.INFO,severityText:isError?"ERROR":"INFO",body:`Agent process ${isError?"failed":"completed"}: ${agentProcessId}`,attributes:logAttributes})}),agentSpan.end(),OTelContextRegistry.endProcess(agentId,agentProcessId)},THook.NonBlocking),HookService.register("Component.process",async function(input,settings,agent){const processId=agent.agentRuntime.processID,agentId=agent.id;this.instance;const componentId=settings.id||"unknown",componentType=settings.name,componentName=settings.displayName||settings.name,eventId=settings.eventId,accessCandidate=AccessCandidate.agent(agentId),teamId=agent.teamId,orgTier="standard",orgSlot=agent.data.planInfo?.flags?`standard/${agent.data.teamId}`:void 0,sourceId=agent.agentRuntime?.getComponentData?.(componentId)?.sourceId||"AGENT",sourceComponentData=sourceId!=="AGENT"?agent.components?.[sourceId]:null,sourceName=sourceComponentData?.displayName||sourceComponentData?.name||sourceId,sessionId=agent.callerSessionId||void 0,workflowId=agent.agentRuntime?.workflowReqId||void 0,workflowStep=agent.agentRuntime?.curStep||void 0,isDebugSession=agent.debugSessionEnabled||agent.agentRuntime?.debug||!1,logTags=agent.sessionTag||(isDebugSession?"DEBUG":void 0),isTestDomain=agent.usingTestDomain||!1,inputAction=input?.__action||void 0,inputStatus=input?.__status||void 0;outputLogger.debug("Component.process started",{componentId,sourceId},accessCandidate);const parentSpan=OTelContextRegistry.get(agentId,processId)?.rootSpan,compSettingsData=oTelInstance.prepareComponentData(settings?.data||{},"cmp.settings"),spanName=`Component.${componentType}`,span=tracer.startSpan(spanName,{attributes:{"agent.id":agentId,"process.id":processId,"event.id":eventId,"cmp.id":componentId,"cmp.type":componentType,"cmp.name":componentName,"team.id":teamId,"org.tier":orgTier,"org.slot":orgSlot,"source.id":sourceId,"source.name":sourceName,"session.id":sessionId,"workflow.id":workflowId,"workflow.step":workflowStep,"agent.debug":isDebugSession,"agent.isTest":isTestDomain,...compSettingsData}},parentSpan?trace.setSpan(context.active(),parentSpan):void 0);JSON.stringify(input||{});const compInputData=oTelInstance.prepareComponentData(input||{});span.addEvent("cmp.call",{"event.id":eventId,"cmp.input.size":JSON.stringify(input||{}).length,"cmp.input":JSON.stringify(compInputData),"input.action":inputAction,"input.status":inputStatus});const spanContext=trace.setSpan(context.active(),span);context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.INFO,severityText:"INFO",body:`Component ${componentType} started`,attributes:{"agent.id":agentId,"process.id":processId,"event.id":eventId,"cmp.id":componentId,"cmp.type":componentType,"cmp.name":componentName,"cmp.input":input,"team.id":teamId,"org.slot":orgSlot,"org.tier":orgTier,"source.id":sourceId,"source.name":sourceName,"session.id":sessionId,"workflow.id":workflowId,"workflow.step":workflowStep,"log.tags":logTags,"agent.debug":isDebugSession,"agent.isTest":isTestDomain}})}),this.context.otelSpan=span},THook.NonBlocking),HookService.registerAfter("Component.process",async function({result,error,args}){const span=this.context.otelSpan;if(!span)return;const agent=args[2],settings=args[1],eventId=settings.eventId,processId=agent.agentRuntime.processID,agentId=agent.id;this.instance;const componentId=settings.id||"unknown",componentType=settings.name,componentName=settings.displayName||settings.name,teamId=agent.teamId,orgTier="standard",orgSlot=agent.data.planInfo?.flags?`standard/${agent.data.teamId}`:void 0,sourceId=agent.agentRuntime?.getComponentData?.(componentId)?.sourceId||"AGENT",sourceComponentData=sourceId!=="AGENT"?agent.components?.[sourceId]:null,sourceName=sourceComponentData?.displayName||sourceComponentData?.name||sourceId,sessionId=agent.callerSessionId||void 0,workflowId=agent.agentRuntime?.workflowReqId||void 0,workflowStep=agent.agentRuntime?.curStep||void 0,isDebugSession=agent.debugSessionEnabled||agent.agentRuntime?.debug||!1,logTags=agent.sessionTag||(isDebugSession?"DEBUG":void 0),isTestDomain=agent.usingTestDomain||!1,accessCandidate=AccessCandidate.agent(agentId);if(outputLogger.debug("Component.process completed",{componentId},accessCandidate),error){span.recordException(error),span.setStatus({code:SpanStatusCode.ERROR,message:error.message}),span.addEvent("cmp.call.error",{"event.id":eventId,"cmp.id":componentId,"cmp.type":componentType,"cmp.name":componentName,"error.type":error.name,"error.message":error.message,"error.stack":error.stack?.substring(0,500)});const spanContext=trace.setSpan(context.active(),span);context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.ERROR,severityText:"ERROR",body:`Component ${componentType} (${componentId}) failed: ${error.message}`,attributes:{"agent.id":agentId,"process.id":processId,"event.id":eventId,"cmp.id":componentId,"cmp.name":componentName,"cmp.type":componentType,"error.type":error.name,"error.message":error.message,"error.stack":error.stack,"team.id":teamId,"org.slot":orgSlot,"org.tier":orgTier,"source.id":sourceId,"source.name":sourceName,"session.id":sessionId,"workflow.id":workflowId,"workflow.step":workflowStep,"log.tags":logTags,"agent.debug":isDebugSession,"agent.isTest":isTestDomain}})})}else{const hasResultError=!!result?._error||!!result?.error,resultStr=JSON.stringify(result||{});if(hasResultError){const resultError=result._error||result.error,errorMessage=resultError?.message||(typeof resultError=="string"?resultError:"Component returned error");span.setStatus({code:SpanStatusCode.ERROR,message:errorMessage}),span.addEvent("cmp.call.error",{"event.id":eventId,"cmp.id":componentId,"cmp.type":componentType,"cmp.name":componentName,"error.type":"result_error","error.message":errorMessage}),span.setAttributes({"output.size":resultStr.length,"output.has_error":!0});const spanContext=trace.setSpan(context.active(),span);context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.ERROR,severityText:"ERROR",body:`Component ${componentType} (${componentId}) failed: ${errorMessage}`,attributes:{"agent.id":agentId,"process.id":processId,"event.id":eventId,"cmp.id":componentId,"cmp.name":componentName,"cmp.type":componentType,"error.type":"result_error","error.message":errorMessage,"cmp.output":result,"team.id":teamId,"org.slot":orgSlot,"org.tier":orgTier,"source.id":sourceId,"source.name":sourceName,"session.id":sessionId,"workflow.id":workflowId,"workflow.step":workflowStep,"log.tags":logTags,"agent.debug":isDebugSession,"agent.isTest":isTestDomain}})})}else{span.setStatus({code:SpanStatusCode.OK}),span.addEvent("cmp.call.result",{"output.size":resultStr.length,"output.preview":resultStr.substring(0,200)}),span.setAttributes({"output.size":resultStr.length,"output.has_error":!1});const logAttributes={"agent.id":agentId,"cmp.id":componentId,"cmp.type":componentType,"cmp.name":componentName,"process.id":processId,"event.id":eventId,"cmp.output":result,"team.id":teamId,"org.slot":orgSlot,"org.tier":orgTier,"source.id":sourceId,"source.name":sourceName,"session.id":sessionId,"workflow.id":workflowId,"workflow.step":workflowStep,"log.tags":logTags,"agent.debug":isDebugSession,"agent.isTest":isTestDomain},spanContext=trace.setSpan(context.active(),span);context.with(spanContext,()=>{logger2.emit({severityNumber:SeverityNumber.INFO,severityText:"INFO",body:`Component ${componentType} (${componentId}) completed successfully`,attributes:logAttributes})})}}span.end()},THook.NonBlocking),Promise.resolve()}}class TelemetryService extends ConnectorServiceProvider{register(){ConnectorService.register(TConnectorService.Telemetry,"OTel",OTel)}}const console$1=Logger("Boot");let _booted=!1;function boot(){if(_booted){console$1.warn("SRE already booted");return}_booted=!0,SystemEvents.emit("SRE:BootStart"),console$1.debug("SRE Boot sequence started");const service={};service.NKV=new NKVService,service.Account=new AccountService,service.Vault=new VaultService,service.ManagedVault=new ManagedVaultService,service.Cache=new CacheService,service.Storage=new StorageService,service.ModelsProvider=new ModelsProviderService,service.LLM=new LLMService,service.AgentData=new AgentDataService,service.CLI=new CLIService,service.VectorDB=new VectorDBService,service.Router=new RouterService,service.Log=new LogService,service.Component=new ComponentService,service.Code=new CodeService,service.Scheduler=new SchedulerService,service.Telemetry=new TelemetryService,SystemEvents.on("SRE:Initialized",()=>{console$1.debug("SRE Initialized");for(let key in service)service[key].init();SystemEvents.emit("SRE:Booted",service),console$1.debug("SRE Boot sequence completed")})}function generateServiceKey(serviceName){const secret=process.env.SRE_SECRET;if(!secret||secret.trim().length<32)throw new Error("SRE_SECRET must be at least 32 characters");return createHmac("sha256",secret).update(`sre-service:${serviceName}`).digest("hex")}function validateServiceKey(serviceName,providedKey){try{const expectedKey=generateServiceKey(serviceName);return timingSafeEqual(Buffer.from(expectedKey),Buffer.from(providedKey))}catch{return!1}}var __defProp$2=Object.defineProperty,__defNormalProp$2=(obj,key,value)=>key in obj?__defProp$2(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$2=(obj,key,value)=>__defNormalProp$2(obj,typeof key!="symbol"?key+"":key,value);const logger$1=Logger("ExternalEventsReceiver");class ExternalEventsReceiver{constructor(config2){if(__publicField$2(this,"server",null),__publicField$2(this,"wss",null),__publicField$2(this,"config"),__publicField$2(this,"isRunning",!1),this.config={enableHttp:!0,enableWebSocket:!0,path:"/ws",...config2},!this.config.authTokens||this.config.authTokens.length===0)throw logger$1.warn("At least one authentication token must be provided"),new Error("At least one authentication token must be provided")}async start(){if(this.isRunning){logger$1.warn("Server is already running");return}return this.server=createServer((req,res)=>this.handleHttpRequest(req,res)),this.config.enableWebSocket&&(this.wss=new WebSocketServer({server:this.server,path:this.config.path}),this.wss.on("connection",(ws,req)=>{this.handleWebSocketConnection(ws,req)})),new Promise((resolve,reject)=>{this.server.listen(this.config.port,"127.0.0.1",()=>{this.isRunning=!0,logger$1.debug(`Server started on port ${this.config.port}`+(this.config.enableHttp?" [HTTP]":"")+(this.config.enableWebSocket?` [WebSocket: ${this.config.path}]`:"")),resolve()}),this.server.on("error",error=>{logger$1.error("Server error",error),reject(error)})})}async stop(){if(this.isRunning)return new Promise((resolve,reject)=>{this.wss&&this.wss.close(err=>{err&&logger$1.error("Error closing WebSocket server",err)}),this.server?this.server.close(err=>{err?(logger$1.error("Error closing HTTP server",err),reject(err)):(this.isRunning=!1,logger$1.debug("Server stopped"),resolve())}):resolve()})}handleHttpRequest(req,res){if(!this.config.enableHttp){this.sendResponse(res,404,{error:"HTTP endpoint is disabled"});return}if(req.method!=="POST"){this.sendResponse(res,405,{error:"Method not allowed. Only POST requests are accepted."});return}const authResult=this.validateAuth(req.headers);if(!authResult.valid){this.sendResponse(res,401,{error:authResult.error});return}const connectorName=this.getConnectorName(req.headers);if(!connectorName){this.sendResponse(res,400,{error:"Missing x-connector-name header"});return}let body="";req.on("data",chunk=>{body+=chunk.toString()}),req.on("end",()=>{try{const data=body?JSON.parse(body):{};this.emitExternalEvent(connectorName,data),this.sendResponse(res,200,{success:!0,message:`Event EXT:${connectorName} emitted successfully`})}catch(error){logger$1.error("Error processing HTTP request",error),this.sendResponse(res,400,{error:"Invalid JSON payload"})}}),req.on("error",error=>{logger$1.error("HTTP request error",error),this.sendResponse(res,500,{error:"Internal server error"})})}handleWebSocketConnection(ws,req){logger$1.debug("New WebSocket connection");const authResult=this.validateAuth(req.headers);if(!authResult.valid){ws.close(1008,authResult.error);return}let connectorName=this.getConnectorName(req.headers);ws.on("message",message=>{try{const data=JSON.parse(message.toString());if(!connectorName&&(connectorName=data.connectorName||data["x-connector-name"],!connectorName)){ws.send(JSON.stringify({error:"Missing connector name in headers or message"}));return}this.emitExternalEvent(connectorName,data),ws.send(JSON.stringify({success:!0,message:`Event EXT:${connectorName} emitted successfully`}))}catch(error){logger$1.error("Error processing WebSocket message",error),ws.send(JSON.stringify({error:"Invalid JSON message"}))}}),ws.on("error",error=>{logger$1.error("WebSocket error",error)}),ws.on("close",()=>{logger$1.debug("WebSocket connection closed")})}validateAuth(headers){const authHeader=headers.authorization||headers.Authorization,serviceName=headers["x-service-name"]||headers["X-Service-Name"];if(!authHeader)return logger$1.warn("Missing Authorization header"),{valid:!1,error:"Missing Authorization header"};if(!serviceName||typeof serviceName!="string")return logger$1.warn("Missing or invalid X-Service-Name header"),{valid:!1,error:"Missing X-Service-Name header"};const token=authHeader.replace(/^Bearer\s+/i,"");return token?validateServiceKey(serviceName,token)?(logger$1.debug(`Authenticated service: ${serviceName}`),{valid:!0,serviceName}):(logger$1.warn(`Invalid key for service: ${serviceName}`),{valid:!1,error:"Invalid authentication"}):{valid:!1,error:"Invalid Authorization header format"}}getConnectorName(headers){const connectorName=headers["x-connector-name"]||headers["X-Connector-Name"];return typeof connectorName=="string"?connectorName:connectorName?.[0]||null}emitExternalEvent(connectorName,data){const eventName=`EXT:${connectorName}`,connector=ConnectorService.getInstance(TConnectorService[connectorName]);connector&&connector.handleEvent(eventName,data)}sendResponse(res,statusCode,body){res.statusCode=statusCode,res.setHeader("Content-Type","application/json"),res.end(JSON.stringify(body))}getStatus(){return{running:this.isRunning,port:this.config.port,config:this.config}}}var __defProp$1=Object.defineProperty,__defNormalProp$1=(obj,key,value)=>key in obj?__defProp$1(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1=(obj,key,value)=>__defNormalProp$1(obj,typeof key!="symbol"?key+"":key,value);const logger=Logger("SRE"),_SmythRuntime=class _SmythRuntime2{constructor(){__publicField$1(this,"started",!1),__publicField$1(this,"_smythDir"),__publicField$1(this,"_readyPromise"),__publicField$1(this,"_readyResolve"),__publicField$1(this,"defaultConfig",{Vault:{Connector:"JSONFileVault",Settings:{shared:"default"}},Account:{Connector:"DummyAccount"},Cache:{Connector:"RAM"},Storage:{Connector:"LocalStorage"},Code:{Connector:"DummyConnector"},NKV:{Connector:"LocalStorage"},VectorDB:{Connector:"RAMVec"},ModelsProvider:{Connector:"JSONModelsProvider"},AgentData:{Connector:"NullAgentData"},Component:{Connector:"LocalComponent"},ManagedVault:{Connector:"NullManagedVault"},Log:{Connector:"ConsoleLog"},Router:{Connector:"NullRouter"},Scheduler:{Connector:"LocalScheduler",Settings:{runJobs:!0,persistExecutionHistory:!0}}}),__publicField$1(this,"connectors",{}),__publicField$1(this,"connectorInstances",{}),__publicField$1(this,"_initializing",!1),__publicField$1(this,"_initialized",!1),__publicField$1(this,"_stopping",!1),this.started=!0,this._readyPromise=new Promise(resolve=>{this._readyResolve=resolve})}get smythDir(){return this._smythDir}get version(){return pkg.version}static get Instance(){return _SmythRuntime2.instance||(_SmythRuntime2.instance=new _SmythRuntime2),_SmythRuntime2.instance}get initializing(){return this._initializing}init(_config){if(logger.info(`SRE v${this.version} initializing...`),this._initialized)return console.warn("SRE already initialized ... skipping"),_SmythRuntime2.Instance;if(this._initializing)return console.warn("You tried to initialize SRE while it is already initializing ... skipping"),_SmythRuntime2.Instance;(!_config||JSON.stringify(_config)==="{}")&&(this._smythDir=findSmythPath(),logger.info(".smyth directory found in:",this._smythDir)),this._initializing=!0,SystemEvents.on("SRE:Booted",()=>{this._readyResolve(!0)}),boot();const config2=this.autoConf(_config);for(let connectorType in config2)for(let configEntry of config2[connectorType])ConnectorService.init(connectorType,configEntry.Connector,configEntry.Id,configEntry.Settings,configEntry.Default)||logger.warn(`Failed to initialize connector ${connectorType}:${configEntry.Id||configEntry.Connector}`);return this._initialized=!0,SystemEvents.emit("SRE:Initialized",_SmythRuntime2.Instance),this.setupShutdownHandlers(),_SmythRuntime2.Instance}autoConf(config2={}){const defaultConfig=JSON.parse(JSON.stringify(this.defaultConfig)),keys=Object.keys({...defaultConfig,...config2}),newConfig={};for(let connectorType of keys){newConfig[connectorType]=[];let entry=config2[connectorType]||defaultConfig[connectorType];Array.isArray(entry)||(entry=[entry]);let hasDefault=!1;for(let connector of entry){if(!connector.Connector){logger.warn(`Missing Connector Name in ${connectorType} entry ... it will be ignored`);continue}connector.Default&&(hasDefault&&logger.warn(`Entry ${connectorType} has more than one default Connector ... only the first one will be used`),hasDefault=!0),newConfig[connectorType].push(connector)}!hasDefault&&newConfig[connectorType].length>0&&(newConfig[connectorType][0].Default=!0)}return newConfig}ready(){return this._readyPromise}async _stop(){this._stopping||(this._stopping=!0,logger.info("Sending Shutdown Signals To All Subsystems..."),await ConnectorService._stop(),this.started=!1)}setupShutdownHandlers(){["SIGINT","SIGTERM"].forEach(signal=>{process.on(signal,async()=>{await shutdown(signal),process.exit(0)})}),process.on("beforeExit",code=>{shutdown("beforeExit")}),process.on("exit",code=>{logger.info("Goodbye!")})}};__publicField$1(_SmythRuntime,"instance");let SmythRuntime=_SmythRuntime;const SRE=SmythRuntime.Instance;let shuttingDown=!1;async function shutdown(reason){if(SmythRuntime.Instance.started&&!shuttingDown&&(shuttingDown=!0,logger.info(`Caught ${reason} ... Attempting graceful shutdown`),SmythRuntime.Instance))try{await SmythRuntime.Instance._stop()}catch(err){logger.error("Shutdown error:",err)}}class SmythURI{static agent(id){return`smyth:agent:${id}`}}class LLMMemoryConnector extends SecureConnector{requester(candidate){return{load:async messages=>await this.load(candidate.readRequest,messages)}}}var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__decorateClass=(decorators,target,key,kind)=>{for(var result=__getOwnPropDesc(target,key),i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=decorator(target,key,result)||result);return result&&__defProp(target,key,result),result},__publicField=(obj,key,value)=>__defNormalProp(obj,key+"",value);Logger("HashicorpVault");class HashicorpVault extends VaultConnector{constructor(_settings){super(_settings),this._settings=_settings,__publicField(this,"name","HashicorpVault")}async get(acRequest,keyId){return null}async exists(acRequest,keyId){return!1}async listKeys(acRequest){return[]}async getResourceACL(resourceId,candidate){const teamId=await ConnectorService.getAccountConnector().getCandidateTeam(candidate),acl=new ACL;return acl.addAccess(TAccessRole.Team,teamId,TAccessLevel.Owner).addAccess(TAccessRole.Team,teamId,TAccessLevel.Read).addAccess(TAccessRole.Team,teamId,TAccessLevel.Write),acl}}__decorateClass([SecureConnector.AccessControl],HashicorpVault.prototype,"get"),__decorateClass([SecureConnector.AccessControl],HashicorpVault.prototype,"exists"),__decorateClass([SecureConnector.AccessControl],HashicorpVault.prototype,"listKeys");export{ACL,ACLAccessDeniedError,APICall,APIEndpoint,APIKeySource,APIOutput,AWSLambdaCode,AccessCandidate,AccessRequest,AccountConnector,AccountService,Agent,AgentDataConnector,AgentDataService,AgentLogger,AgentPlugin,AgentProcess,AgentRequest,AgentRuntime,AgentSSE,AgentSettings,AnthropicConnector,Async,Await,BUILT_IN_MODEL_PREFIX,BaseEmbedding,BedrockConnector,BinaryInput,BuiltinLLMProviders,CLIAgentDataConnector,CLIConnector,CLIService,COMP_NAMES,CacheConnector,CacheService,Classifier,CodeConnector,CodeService,Component,ComponentConnector,ComponentHost,ComponentInputType,ComponentInstances,ComponentService,Connector,ConnectorService,ConnectorServiceProvider,ConsoleLog,Conversation,Credentials,DEFAULT_MAX_TOKENS_FOR_LLM,DEFAULT_SMYTHOS_LLM_PROVIDERS_SETTINGS,DEFAULT_TEAM_ID,DataSourceCleaner,DataSourceCompError,DataSourceComponent,DataSourceIndexer,DataSourceLookup,DummyAccount,DummyConnector,EMBODIMENT_TYPES,ENTERPRISE_MODELS_SETTING_KEY,ERR_MSG_INVALID_BINARY,ERR_MSG_INVALID_IMAGE_SOURCE,ERR_MSG_MAX_ARRAY_SIZE,ERR_MSG_MAX_DEPTH,ERR_MSG_MAX_OBJECT_SIZE,EchoConnector,EmbeddingsFactory,EmbodimentSettings,ExpressRouter,ExternalEventsReceiver,FEncDec,FHash,FSign,FSleep,FTimestamp,FileStore,ForEach,ForkedAgent,GPTPlugin,GenAILLM,GmailTrigger,GoogleAIConnector,GoogleEmbeds,GroqConnector,HashicorpVault,HookService,HuggingFace,ImageGenerator,ImageSettingsConfig,JSONContent,JSONContentHelper,JSONExpression$1 as JSONExpression,JSONFileAccount,JSONFileVault,JSONFilter,JSONModelsProvider,JSON_RESPONSE_INSTRUCTION,Job,JobSchedulerTrigger,LLMAssistant,LLMCache,LLMConnector,LLMContext,LLMHelper,LLMInference$1 as LLMInference,LLMInterface,LLMMemoryConnector,LLMService,LLMStream,LevelMap,LocalAgentDataConnector,LocalCache,LocalComponentConnector,LocalScheduler,LocalStorage,LocalStorageCache,LogConnector,LogHelper,LogService,Logger,LogicAND,LogicAtLeast,LogicAtMost,LogicOR,LogicXOR,MAX_ARRAY_SIZE,MAX_DEPTH,MAX_FILE_COUNT,MAX_FILE_SIZE,MAX_OBJECT_SIZE,MCPClient,MODELS_WITHOUT_JSON_RESPONSE_SUPPORT,MODELS_WITHOUT_SYSTEM_MESSAGE_SUPPORT,ManagedOAuth2Credentials,ManagedVaultConnector,ManagedVaultService,Match,MemoryDeleteKeyVal,MemoryReadKeyVal,MemoryWriteKeyVal,MemoryWriteObject,MilvusVectorDB,ModelsProviderConnector,ModelsProviderService,MultimodalLLM,MySQLAccount,NKVConnector,NKVLocalStorage,NKVRAM,NKVRedis,NKVService,NullAgentData,NullManagedVault,NullRouter,NullVault,O3_AND_O4_MODELS,O3_AND_O4_MODELS_PATTERN,OSResourceMonitor,OTel,OTelContextRegistry,OllamaConnector,OpenAIConnector,OpenAIEmbeds,OpenAPIParser,PerplexityConnector,PineconeVectorDB,PromptGenerator,RAMCache,RAMVectorDB,REQUEST_CONTENT_TYPES,REQUEST_METHODS,RedisCache,ReverseLevelMap,ReverseRoleMap,RoleMap,RouterConnector,RouterService,RuntimeContext,S3Cache,S3Storage,S3_DAILY_PURGE_LIFECYCLE_TAG,S3_MONTHLY_PURGE_LIFECYCLE_TAG,S3_WEEKLY_PURGE_LIFECYCLE_TAG,SEARCH_TOOL_COSTS,SRE,SUPPORTED_MIME_TYPES_MAP,Schedule,SchedulerConnector,SchedulerService,ScrapflyWebScrape,SecretManagerManagedVault,SecretsManager,SecureConnector,ServerlessCode,SmythFS,SmythRuntime,SmythURI,StorageConnector,StorageService,SystemEvents,TAccessLevel,TAccessResult,TAccessRole,TConnectorService,TDataSourceCompErrorCodes,THook,TLLMCredentials,TLLMEvent,TLLMMessageRole,TLLMProvider,TOOL_USE_DEFAULT_MODEL,TPLProcessor,TToolType,TavilyWebSearch,TelemetryConnector,TelemetryService,TemplateString,TemplateStringHelper,Trigger,USER_CUSTOM_MODELS_SETTING_KEY,VaultConnector,VaultHelper,VaultService,VectorDBConnector,VectorDBService,VertexAIConnector,VisionLLM,WhatsAppTrigger,ZapierAction,boot,buildOAuth1Header,cachePrefix,cacheTTL,calculateExecutionCost,checkAndInstallLifecycleRules,createOrUpdateLambdaFunction,customModels,destroyPublicUrls,escapeJsonField,escapeString,extractAdditionalParamsForOAuth1,extractAllKeyNamesFromTemplateVars,extractKeyFromTemplateVar,findSmythPath,findValidResourcePath,generateCodeFromLegacyComponent,generateCodeHash,generateExecutableCode,generateExpiryMetadata,generateLambdaCode,generateLifecycleRules,generateServiceKey,getCredentials,getCurrentEnvironmentVariables,getDeployedCodeHash,getDeployedFunction,getLLMCredentials,getLambdaCredentials,getLambdaFunctionName,getLambdaRolePolicy,getNonExistingRules,getSanitizeCodeHash,getSortedObjectValues,handleOAuthHeaders,hook,hookAsync,hookAsyncWithContext,hookableClass,inputErrMsg,invokeLambdaFunction,isAgent,isValidGroqReasoningEffort,isValidOpenAIReasoningEffort,models,parseArrayBufferResponse,parseData,parseHeaders,parseProxy,parseSmythFsUrl,parseUrl,performTypeInference,reportUsage,retrieveOAuthTokens,runJs,setDeployedCodeHash,ttlToExpiryDays,updateDeployedCodeTTL,validateAsyncMainFunction,validateServiceKey,verifyFunctionDeploymentStatus,version,waitForRoleDeploymentStatus,xAIConnector,zipCode};
294
294
  //# sourceMappingURL=index.js.map