@smythos/sre 1.5.63 → 1.5.64

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"dotenv/config";import winston from"winston";import Transport from"winston-transport";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 EventEmitter$1,{EventEmitter}from"events";import crypto$1,{createHash,randomUUID}from"crypto";import path from"path";import os from"os";import"process";import mime from"mime";import{encodeChat,encode}from"gpt-tokenizer";import{Readable}from"stream";import xxhash from"xxhashjs";import{jsonrepair}from"jsonrepair";import yaml from"js-yaml";import{EventSource}from"eventsource";import*as acorn from"acorn";import dayjs from"dayjs";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 zl from"zip-lib";import{LambdaClient,GetFunctionCommand,UpdateFunctionCodeCommand,Runtime,CreateFunctionCommand,InvokeCommand,UpdateFunctionConfigurationCommand}from"@aws-sdk/client-lambda";import{IAMClient,GetRoleCommand,CreateRoleCommand}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{GetBucketLifecycleConfigurationCommand,PutBucketLifecycleConfigurationCommand,S3Client,HeadObjectCommand,DeleteObjectCommand,GetObjectCommand,PutObjectCommand,PutObjectTaggingCommand,GetObjectTaggingCommand,CopyObjectCommand}from"@aws-sdk/client-s3";import"ses";import imageSize from"image-size";import{execSync}from"child_process";import{Pinecone}from"@pinecone-database/pinecone";import OpenAI,{toFile,OpenAI as OpenAI$1}from"openai";import{MilvusClient,DataType,ErrorCode}from"@zilliz/milvus2-sdk-node";import{GoogleGenerativeAI,FunctionCallingMode}from"@google/generative-ai";import{GoogleAIFileManager,FileState}from"@google/generative-ai/server";import{GoogleGenAI}from"@google/genai";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*as chokidar from"chokidar";import chokidar__default from"chokidar";import fs$1 from"fs/promises";import IORedis from"ioredis";import mysql from"mysql2/promise";import{SecretsManagerClient,ListSecretsCommand,GetSecretValueCommand,PutSecretValueCommand,CreateSecretCommand,DeleteSecretCommand}from"@aws-sdk/client-secrets-manager";import*as readlineSync from"readline-sync";var version="1.5.63",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}},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"dotenv/config";import winston from"winston";import Transport from"winston-transport";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 EventEmitter$1,{EventEmitter}from"events";import crypto$1,{createHash,randomUUID}from"crypto";import path from"path";import os from"os";import"process";import mime from"mime";import{encodeChat,encode}from"gpt-tokenizer";import{Readable}from"stream";import xxhash from"xxhashjs";import{jsonrepair}from"jsonrepair";import yaml from"js-yaml";import{EventSource}from"eventsource";import*as acorn from"acorn";import dayjs from"dayjs";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 zl from"zip-lib";import{LambdaClient,GetFunctionCommand,UpdateFunctionCodeCommand,Runtime,CreateFunctionCommand,InvokeCommand,UpdateFunctionConfigurationCommand}from"@aws-sdk/client-lambda";import{IAMClient,GetRoleCommand,CreateRoleCommand}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{GetBucketLifecycleConfigurationCommand,PutBucketLifecycleConfigurationCommand,S3Client,HeadObjectCommand,DeleteObjectCommand,GetObjectCommand,PutObjectCommand,PutObjectTaggingCommand,GetObjectTaggingCommand,CopyObjectCommand}from"@aws-sdk/client-s3";import"ses";import imageSize from"image-size";import{execSync}from"child_process";import{Pinecone}from"@pinecone-database/pinecone";import OpenAI,{toFile,OpenAI as OpenAI$1}from"openai";import{MilvusClient,DataType,ErrorCode}from"@zilliz/milvus2-sdk-node";import{GoogleGenerativeAI,FunctionCallingMode}from"@google/generative-ai";import{GoogleAIFileManager,FileState}from"@google/generative-ai/server";import{GoogleGenAI}from"@google/genai";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*as chokidar from"chokidar";import chokidar__default from"chokidar";import fs$1 from"fs/promises";import IORedis from"ioredis";import mysql from"mysql2/promise";import{SecretsManagerClient,ListSecretsCommand,GetSecretValueCommand,PutSecretValueCommand,CreateSecretCommand,DeleteSecretCommand}from"@aws-sdk/client-secrets-manager";import*as readlineSync from"readline-sync";var version="1.5.64",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}},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.
@@ -24,15 +24,15 @@ Call Stack:
24
24
  `);this._logger.log("error",formatLogMessage(...args),{...this.labels,stack,module}),this.emit("logged",{level:"error",message:formatLogMessage(...args)})}close(){this._logger.clear(),this._logger.close()}}winston.format.printf(info=>`${info.timestamp} ${winston.format.colorize().colorize(info.level,`${info.level}: ${info.message}`)}`);const MAX_LOG_MESSAGE_LENGTH=500;function redactLogMessage(logMessage){if(config.env.NODE_ENV!=="PROD"||logMessage.length>500)return logMessage;const sensitiveWords=["password","eyJ","token","email","secret","key","apikey","api_key","auth","credential"],obfuscatedString=" [!! SmythOS::REDACTED_DATA !!] ";for(const sensitiveWord of sensitiveWords){const regex=new RegExp(`(${sensitiveWord})((?:[^\\n]{0,29}(?=\\n))|(?:[^\\n]{30}\\S*))`,"gmi");logMessage=logMessage.replace(regex,`$1${obfuscatedString}`)}return logMessage}function createBaseLogger(memoryStore){const logger2=winston.createLogger({format:winston.format.combine(winston.format(info=>config.env.LOG_LEVEL=="none"||logLevel()=="none"||logLevel()==""?!1:(info.message=redactLogMessage(info.message),info))(),winston.format.timestamp(),winston.format.errors({stack:!0}),winston.format.splat(),winston.format.json()),transports:[new winston.transports.Console({level:"error",format:winston.format.combine(winston.format.printf(info=>{let message=info.message;return message=message?.length>MAX_LOG_MESSAGE_LENGTH?message.substring(0,MAX_LOG_MESSAGE_LENGTH)+"...":message,`${info.level}:${info.module||""} ${message} ${info.stack||""}`})),stderrLevels:["error"]}),new winston.transports.Console({level:logLevel(),format:winston.format.combine(namespaceFilter,winston.format.printf(info=>{const module=info.module?winston.format.colorize().colorize(info.level,` [${info.module}]`):"",ns=winston.format.colorize().colorize(info.level,`${info.level}${module}`);let message=info.message;return message=message?.length>MAX_LOG_MESSAGE_LENGTH?message.substring(0,MAX_LOG_MESSAGE_LENGTH)+"...":message,`${ns} - ${message}`}))})]});return Array.isArray(memoryStore)&&logger2.add(new ArrayTransport({level:"debug",logs:memoryStore})),logger2}function formatLogMessage(...args){return args.map(arg=>{if(typeof arg=="object"&&arg!==null&&!(arg instanceof Error))try{return JSON.stringify(arg,null,2)}catch{return String(arg)}return String(arg)}).join(" ")}function createLabeledLogger(labels,memoryStore){const _logger=createBaseLogger(memoryStore);return _logger.defaultMeta=labels,new LogHelper(_logger,memoryStore,labels)}function Logger(module,withMemoryStore=!1){return createLabeledLogger(typeof module=="string"?{module}:module,withMemoryStore?[]:void 0)}const DummyConnector=name=>{const logger2=Logger(`DummyConnector<${name}>`);return new Proxy({},{get:function(target,prop,receiver){return prop==="valid"?!1:typeof target[prop]=="function"?target[prop]:function(...args){const argsString=args.length>0?args.map(arg=>typeof arg=="object"?JSON.stringify(arg,null,0).slice(0,50)+"...":typeof arg=="string"?`"${arg.slice(0,50)}..."`:typeof arg=="number"||typeof arg=="boolean"||typeof arg=="function"||typeof arg=="symbol"?arg.toString():typeof arg>"u"?"undefined":String(arg)).join(", "):"(no arguments)";logger2.warn(`[!!] Unimplemented Connector tried to call: ${name}.${prop.toString()}(${argsString})`),printStackTrace(logger2,3,1)}}})};var __defProp$1J=Object.defineProperty,__defNormalProp$1J=(obj,key,value)=>key in obj?__defProp$1J(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1J=(obj,key,value)=>__defNormalProp$1J(obj,typeof key!="symbol"?key+"":key,value);class LocalCache{constructor(defaultTTL=60*60*1e3){__publicField$1J(this,"cache"),__publicField$1J(this,"expiryMap"),__publicField$1J(this,"timeouts"),__publicField$1J(this,"defaultTTL",60*60*1e3),this.defaultTTL=defaultTTL,this.cache=new Map,this.expiryMap=new Map,this.timeouts=new Map}set(key,value,ttlMs=this.defaultTTL){this.cache.set(key,value);const expiry=Date.now()+ttlMs;this.expiryMap.set(key,expiry),this.clearTimeout(key);const timeout=setTimeout(()=>{this.delete(key)},ttlMs);this.timeouts.set(key,timeout),timeout.unref()}updateTTL(key,ttlMs=this.defaultTTL){if(!this.has(key))return;const expiry=Date.now()+ttlMs;this.expiryMap.set(key,expiry),this.clearTimeout(key);const timeout=setTimeout(()=>{this.delete(key)},ttlMs);this.timeouts.set(key,timeout),timeout.unref()}get(key,ttlMs){if(!this.has(key))return;const value=this.cache.get(key);if(value!==void 0)return this.updateTTL(key,ttlMs),value}has(key){if(!this.cache.has(key))return!1;const expiry=this.expiryMap.get(key);return expiry&&Date.now()>expiry?(this.delete(key),!1):!0}delete(key){return this.clearTimeout(key),this.expiryMap.delete(key),this.cache.delete(key)}clear(){for(const key of this.cache.keys())this.clearTimeout(key);this.cache.clear(),this.expiryMap.clear(),this.timeouts.clear()}clearTimeout(key){const timeout=this.timeouts.get(key);timeout&&(clearTimeout(timeout),this.timeouts.delete(key))}}var __defProp$1I=Object.defineProperty,__defNormalProp$1I=(obj,key,value)=>key in obj?__defProp$1I(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1I=(obj,key,value)=>__defNormalProp$1I(obj,typeof key!="symbol"?key+"":key,value);const console$y=Logger("Connector"),_Connector=class _Connector2{constructor(_settings){this._settings=_settings,__publicField$1I(this,"name"),__publicField$1I(this,"started",!1),__publicField$1I(this,"_interactionHandler"),__publicField$1I(this,"_readyPromise")}get settings(){return this._settings}get interactionHandler(){return this._interactionHandler}get valid(){return!0}setInteraction(handler){this._interactionHandler=handler}instance(settings){const configHash=createHash("sha256").update(JSON.stringify(settings||{})).digest("hex"),key=`${this.name}-${configHash}`;if(_Connector2.lCache.has(key))return _Connector2.lCache.get(key);const constructor=this.constructor,instance=new constructor(settings);return _Connector2.lCache.set(key,instance,60*60*1e3),instance}static isValid(connector){return connector.name!==void 0&&connector.name!==null&&connector.name!==""}async start(){console$y.info(`Starting ${this.name} connector ...`),this.started=!0}async stop(){console$y.info(`Stopping ${this.name} connector ...`)}ready(){return this._readyPromise||(this._readyPromise=new Promise(resolve=>{let maxWait=6e4;const tick=100;if(this.started)resolve(!0);else{const interval=setInterval(()=>{this.started&&(clearInterval(interval),resolve(!0)),maxWait-=tick,maxWait<=0&&(clearInterval(interval),resolve(!1))},tick)}})),this._readyPromise}requester(candidate){return null}user(candidate){return typeof candidate=="string"?this.requester(AccessCandidate.user(candidate)):this.requester(candidate)}team(teamId){return this.requester(AccessCandidate.team(teamId))}agent(agentId){return this.requester(AccessCandidate.agent(agentId))}};__publicField$1I(_Connector,"lCache",new LocalCache);let Connector=_Connector;const SystemEvents=new EventEmitter;var __defProp$1H=Object.defineProperty,__defNormalProp$1H=(obj,key,value)=>key in obj?__defProp$1H(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1H=(obj,key,value)=>__defNormalProp$1H(obj,typeof key!="symbol"?key+"":key,value);const console$x=Logger("ConnectorService");let ServiceRegistry={},_ready=!1;SystemEvents.on("SRE:Booted",services=>{ServiceRegistry=services,_ready=!0});const _ConnectorService=class _ConnectorService2{static get ready(){return _ready}static get service(){return ServiceRegistry}static register(connectorType,connectorName,connectorConstructor){if(typeof connectorConstructor!="function"||!isSubclassOf(connectorConstructor,Connector)){console$x.error(`Invalid Connector ${connectorType}:${connectorName}`);return}_ConnectorService2.Connectors[connectorType]||(_ConnectorService2.Connectors[connectorType]={}),_ConnectorService2.Connectors[connectorType][connectorName]=connectorConstructor}static init(connectorType,connectorName,connectorId,settings={},isDefault=!1){if(_ConnectorService2.ConnectorInstances[connectorType]?.[connectorName])throw new Error(`Connector ${connectorType}:${connectorName} already initialized`);const entry=_ConnectorService2.Connectors[connectorType];if(!entry)return;const connectorConstructor=entry[connectorName];if(connectorConstructor){const connector=new connectorConstructor(settings);connector.interactionHandler&&connector.interactionHandler(),connector.start(),_ConnectorService2.ConnectorInstances[connectorType]||(_ConnectorService2.ConnectorInstances[connectorType]={});const id=connectorId||connectorName;return _ConnectorService2.ConnectorInstances[connectorType][id]=connector,!_ConnectorService2.ConnectorInstances[connectorType].default&&isDefault&&(_ConnectorService2.ConnectorInstances[connectorType].default=connector),connector}}static async _stop(){for(let connectorName in _ConnectorService2.ConnectorInstances){let allConnectors=Object.values(_ConnectorService2.ConnectorInstances[connectorName]);allConnectors=allConnectors.filter((value,index,self)=>self.indexOf(value)===index);for(let connector of allConnectors)connector.stop()}}static getInstance(connectorType,connectorName="default"){return _ConnectorService2.ConnectorInstances[connectorType]?.[connectorName||"default"]||(console$x.warn(`Connector ${connectorType} not initialized returning DummyConnector`),printStackTrace(console$x,5),DummyConnector(connectorType))}static getStorageConnector(name){return _ConnectorService2.getInstance(TConnectorService.Storage,name)}static getCacheConnector(name){return _ConnectorService2.getInstance(TConnectorService.Cache,name)}static getVectorDBConnector(name){return _ConnectorService2.getInstance(TConnectorService.VectorDB,name)}static getNKVConnector(name){return _ConnectorService2.getInstance(TConnectorService.NKV,name)}static getLLMConnector(name){return _ConnectorService2.getInstance(TConnectorService.LLM,name)}static getVaultConnector(name){return _ConnectorService2.getInstance(TConnectorService.Vault,name)}static getManagedVaultConnector(name){return _ConnectorService2.getInstance(TConnectorService.ManagedVault,name)}static getAccountConnector(name){return _ConnectorService2.getInstance(TConnectorService.Account,name)}static getAgentDataConnector(name){return _ConnectorService2.getInstance(TConnectorService.AgentData,name)}static getCLIConnector(name){return _ConnectorService2.getInstance(TConnectorService.CLI,name)}static getLogConnector(name){return _ConnectorService2.getInstance(TConnectorService.Log,name)}static getComponentConnector(name){return _ConnectorService2.getInstance(TConnectorService.Component,name)}static getModelsProviderConnector(name){return _ConnectorService2.getInstance(TConnectorService.ModelsProvider,name)}static hasInstance(connectorType,connectorName="default"){const instance=_ConnectorService2.ConnectorInstances[connectorType]?.[connectorName];return instance&&instance.valid}static getRouterConnector(name){return _ConnectorService2.getInstance(TConnectorService.Router,name)}static getCodeConnector(name){return _ConnectorService2.getInstance(TConnectorService.Code,name)}};__publicField$1H(_ConnectorService,"Connectors",{}),__publicField$1H(_ConnectorService,"ConnectorInstances",{});let ConnectorService=_ConnectorService;class ConnectorServiceProvider{init(){}constructor(){this.register()}}class VaultHelper{static async getTeamKey(key,teamId){return await ConnectorService.getVaultConnector().requester(AccessCandidate.team(teamId)).get(key)}static async getUserKey(key,userId){const vaultConnector=ConnectorService.getVaultConnector(),teamId=await ConnectorService.getAccountConnector().getCandidateTeam(AccessCandidate.user(userId));return await vaultConnector.requester(AccessCandidate.team(teamId)).get(key)}static async getAgentKey(key,agentId){const vaultConnector=ConnectorService.getVaultConnector(),teamId=await ConnectorService.getAccountConnector().getCandidateTeam(AccessCandidate.agent(agentId));return await vaultConnector.requester(AccessCandidate.team(teamId)).get(key)}}var __defProp$1G=Object.defineProperty,__defNormalProp$1G=(obj,key,value)=>key in obj?__defProp$1G(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1G=(obj,key,value)=>__defNormalProp$1G(obj,typeof key!="symbol"?key+"":key,value);const Match={default:/{{(.*?)}}/g,doubleCurly:/{{(.*?)}}/g,singleCurly:/{(.*?)}/g,doubleCurlyForSingleMatch:/{{(.*?)}}/,templateVariables:/{{([A-Z]+):([\w\s]+):[\[{](.*?)[\]}]}}/gm,prefix(prefix){return new RegExp(`{{${prefix}(.*?)}}`,"g")},suffix(suffix){return new RegExp(`{{(.*?)${suffix}}}`,"g")},prefSuf(prefix,suffix){return new RegExp(`{{${prefix}(.*?)${suffix}}}`,"g")},fn(name){return new RegExp(`{{${name}\\((.*?)\\)}}`,"g")}},TPLProcessor={vaultTeam(teamId){return async token=>{try{return await VaultHelper.getTeamKey(token,teamId)}catch{return token}}},componentTemplateVar(templateSettings){return async(token,matches)=>{try{const label=matches[2];if(!label)return token;const entry=Object.values(templateSettings).find(o=>o.label==label);return entry?`{{${entry.id}}}`:token}catch{return token}}}};class TemplateStringHelper{constructor(templateString){this.templateString=templateString,__publicField$1G(this,"_current"),__publicField$1G(this,"_promiseQueue",[]),this._current=templateString}get result(){if(this._promiseQueue.length<=0)return this._current;throw new Error("This template object has async results, you should use .asyncResult with await instead of .result")}get asyncResult(){return new Promise(async(resolve,reject)=>{await Promise.all(this._promiseQueue),resolve(this._current)})}static create(templateString){return new TemplateStringHelper(templateString)}parse(data,regex=Match.default){return typeof this._current!="string"||typeof data!="object"?this:(this._current=this._current.replace(regex,(match,token)=>{const val=data?.[token]??match;return typeof val=="object"?JSON.stringify(val):escapeJsonField(val)}),this)}parseRaw(data,regex=Match.doubleCurlyForSingleMatch){if(typeof this._current!="string"||typeof data!="object")return this;const match=this._current.match(regex),key=match?match[1]:"";if(key){const value=data?.[key];this._current=value}return this}parseTeamKeysAsync(teamId){return this.process(TPLProcessor.vaultTeam(teamId),Match.fn("KEY"))}parseComponentTemplateVarsAsync(templateSettings){return this.process(TPLProcessor.componentTemplateVar(templateSettings),Match.templateVariables)}process(processor,regex=Match.default){if(typeof this._current!="string")return this;let tokens={},match;const prosessorPromises=[];for(;(match=regex.exec(this._current))!==null;){const token=match[1];tokens[token]=match[0];const _processor=processor(token,match);_processor instanceof Promise?(_processor.then(result=>{if(result===void 0)return match?.[0];tokens[token]=result}),prosessorPromises.push(_processor)):tokens[token]=_processor}return prosessorPromises.length>0?(new Promise(async(resolve,reject)=>{await Promise.all(prosessorPromises),this.parse(tokens,regex),resolve(!0)}),this._promiseQueue.push(Promise.all(prosessorPromises))):this.parse(tokens,regex),this}clean(regex=Match.default,replaceWith=""){return typeof this._current!="string"?this:(this._current=this._current.replace(regex,replaceWith),this)}}function escapeString(str){return str&&str.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}function escapeJsonField(str){return typeof str!="string"?str:str.replace(/\\"/g,'"').replace(/"/g,'\\"')}function TemplateString(templateString){return TemplateStringHelper.create(templateString)}var __defProp$1F=Object.defineProperty,__defNormalProp$1F=(obj,key,value)=>key in obj?__defProp$1F(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1F=(obj,key,value)=>__defNormalProp$1F(obj,typeof key!="symbol"?key+"":key,value);const console$w=Logger("AgentLogger.class");class LogTransaction{constructor(agent,trId){this.agent=agent,this.trId=trId,__publicField$1F(this,"_callId",""),__publicField$1F(this,"queue",[]),__publicField$1F(this,"_isProcessing",!1),__publicField$1F(this,"_lastPush",0),__publicField$1F(this,"storage"),this.storage=ConnectorService.getStorageConnector()}async getCallId(){return this._callId}push(logData){ConnectorService.getLogConnector().valid&&(this.queue.push(logData),this._lastPush=Date.now(),this.processQueue())}formatData(data,maxLength=1e3){if(!data)return;let result=typeof data=="string"?data:JSON.stringify(data);return result.length>maxLength&&(result=result.substr(0,maxLength)+"..."),result}getDataFilePath(data,maxLength=1e3){if(data){if((typeof data=="string"?data:JSON.stringify(data)).length>maxLength){const dayFolder=getDayFormattedDate(),trId="L"+uid().toUpperCase();return`${dayFolder}/${trId}`}return null}}prepareData(firstData){let sourceId=firstData.sourceId,componentId=firstData.componentId,input=firstData.input?{preview:this.formatData(firstData.input),full:this.getDataFilePath(firstData.input),action:firstData.input.__action,status:firstData.input.__status}:void 0,output=firstData.output?{preview:this.formatData(firstData.output),full:this.getDataFilePath(firstData.output)}:void 0,domain=firstData.domain,inputTimestamp=firstData.inputTimestamp,outputTimestamp=firstData.outputTimestamp,result=firstData.result?JSON.stringify({preview:this.formatData(firstData.result),full:this.getDataFilePath(firstData.result)}):void 0,sessionID=firstData.sessionID;const sourceData=this.agent.components[sourceId],componentData=this.agent.components[componentId],sourceCptName=sourceData?.name,componentCptName=componentData?.name,sourceName=sourceData?.displayName||sourceData?.name||sourceId,componentName=componentData?.displayName||componentData?.name||componentId,curStepOrder=firstData.step||this.agent?.agentRuntime?.curStep||"",nextStepOrder=curStepOrder+1;sourceCptName&&(sourceId+=`@${sourceCptName}@${curStepOrder}`),componentCptName&&(componentId+=`@${componentCptName}@${nextStepOrder}`);const inputTokens=void 0,outputTokens=void 0,tags=firstData.tags||"";let raw_error=firstData.error||firstData?.output?.error||firstData?.output?._error||firstData?.result?.error||firstData?.result?.result?.error||firstData?.result?._error||firstData?.result?.result?._error;const error=raw_error?JSON.stringify({preview:this.formatData(raw_error),full:this.getDataFilePath(raw_error)}):void 0;return{sourceId,componentId,domain,input,output,inputTimestamp,outputTimestamp,result,error,sourceName,componentName,sessionID,inputTokens,outputTokens,tags,workflowID:firstData.workflowID,processID:firstData.processID,raw_input:firstData.input,raw_output:firstData.output,raw_result:firstData.result,raw_error}}async storeLogData(filePath,content){const logConnector=ConnectorService.getLogConnector();if(!(!logConnector.valid||logConnector.name=="ConsoleLog")&&filePath)try{const body=typeof content=="string"?content:JSON.stringify(content),storagePath=path.posix.join("teams",this.agent.teamId,`logs/${this.agent.id}/${filePath}`),metadata={teamid:this.agent.teamId,agentid:this.agent.id,ContentType:"text/plain"};await this.storage.requester(AccessCandidate.agent(this.agent.id)).write(storagePath,body,void 0,metadata)}catch(error){console$w.error("Error storing Log File : ",filePath,error)}}async processQueue(){const logConnector=ConnectorService.getLogConnector();if(!(!logConnector.valid||this.queue.length<=0||this._isProcessing)){this._isProcessing=!0;try{if(this._callId)for(;this.queue.length>0;){const logData=this.queue.shift(),data=this.prepareData(logData);Object.keys(data).forEach(key=>{data[key]||delete data[key]});const raw_input=data.raw_input,raw_output=data.raw_output,raw_result=data.raw_result,raw_error=data.raw_error;delete data.raw_input,delete data.raw_output,delete data.raw_result,delete data.raw_error;const resultObj=data.result?JSON.parse(data.result):void 0,errorObj=data.error?JSON.parse(data.error):void 0;await this.storeLogData(data?.input?.full,raw_input),await this.storeLogData(data?.output?.full,raw_output),await this.storeLogData(resultObj?.full,raw_result),await this.storeLogData(errorObj?.full,raw_error),await logConnector.requester(AccessCandidate.agent(this.agent.id)).log(data,this._callId)}else{const firstData=this.queue.shift(),data=this.prepareData(firstData),raw_input=data.raw_input,raw_output=data.raw_output,raw_result=data.raw_result,raw_error=data.raw_error;delete data.raw_input,delete data.raw_output,delete data.raw_result,delete data.raw_error;const resultObj=data.result?JSON.parse(data.result):void 0,errorObj=data.error?JSON.parse(data.error):void 0;await this.storeLogData(data?.input?.full,raw_input),await this.storeLogData(data?.output?.full,raw_output),await this.storeLogData(resultObj?.full,raw_result),await this.storeLogData(errorObj?.full,raw_error);const logResult=await logConnector.requester(AccessCandidate.agent(this.agent.id)).log(data);this._callId=logResult?.data?.log?.id}}catch(error){console$w.error("Error processing log queue:",error?.response?.data?.message||error)}this._isProcessing=!1,debounce(this.processQueue.bind(this),1e3,{leading:!0,maxWait:1e4}),await delay(1e3),this.processQueue()}}canDelete(){return this.queue.length>0?(this.processQueue(),!1):this._lastPush!=0&&this._lastPush+1e3*60*60*1<Date.now()}}const _AgentLogger=class _AgentLogger2{constructor(agent){this.agent=agent}static async cleanup(){if(!ConnectorService.getLogConnector().valid)return;const trIds=Object.keys(_AgentLogger2.transactions);for(const trId of trIds)_AgentLogger2.transactions[trId].canDelete()&&delete _AgentLogger2.transactions[trId]}static log(agent,trId,logData){if(ConnectorService.getLogConnector().valid)return agent.agentRuntime.debug&&(logData.tags="DEBUG "),trId||(trId="log-"+uid()),this.transactions[trId]||(this.transactions[trId]=new LogTransaction(agent,trId)),this.transactions[trId].push(logData),debounce(this.cleanup.bind(this),1e3,{leading:!0,maxWait:1e4*1}),trId}static async logTask(agent,tasks){const logConnector=ConnectorService.getLogConnector();logConnector.valid&&(agent.usingTestDomain||await logConnector.requester(AccessCandidate.agent(agent.id)).logTask(tasks,agent.usingTestDomain),debounce(this.cleanup.bind(this),1e3,{leading:!0,maxWait:1e4*1}))}};__publicField$1F(_AgentLogger,"transactions",{}),__publicField$1F(_AgentLogger,"cleanupInterval");let AgentLogger=_AgentLogger;var __defProp$1E=Object.defineProperty,__defNormalProp$1E=(obj,key,value)=>key in obj?__defProp$1E(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1E=(obj,key,value)=>__defNormalProp$1E(obj,typeof key!="symbol"?key+"":key,value);class LLMCache{constructor(candidate,cacheId,ttl=1*60*60){__publicField$1E(this,"_cacheConnector"),__publicField$1E(this,"_cacheId"),__publicField$1E(this,"_ttl"),__publicField$1E(this,"_candidate"),this._cacheConnector=ConnectorService.getCacheConnector(),this._cacheId=cacheId||"llm_cache_"+uid(),this._ttl=ttl,this._candidate=candidate}get id(){return this._cacheId}async set(key,data){this._cacheConnector.valid&&await this._cacheConnector.requester(this._candidate).set(`${this._cacheId}:${key}`,typeof data=="object"?JSON.stringify(data):data,null,null,this._ttl)}async get(key,format="json"){if(!this._cacheConnector.valid)return;const obj=await this._cacheConnector.requester(this._candidate).get(`${this._cacheId}:${key}`);let result;if(format==="json")try{result=JSON.parse(obj)}catch{console.warn(`Invalid JSON data for key ${key}`),result=null}else result=obj;return result}async delete(key){this._cacheConnector.valid&&await this._cacheConnector.requester(this._candidate).delete(`${this._cacheId}:${key}`)}async clear(){this._cacheConnector.valid&&await this._cacheConnector.requester(this._candidate).delete(this._cacheId)}}var __defProp$1D=Object.defineProperty,__defNormalProp$1D=(obj,key,value)=>key in obj?__defProp$1D(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1D=(obj,key,value)=>__defNormalProp$1D(obj,typeof key!="symbol"?key+"":key,value);const console$v=Logger("RuntimeContext");class RuntimeContext extends EventEmitter$1{constructor(runtime){super(),this.runtime=runtime,__publicField$1D(this,"circularLimitReached",!1),__publicField$1D(this,"step",0),__publicField$1D(this,"sessionResult",!1),__publicField$1D(this,"sessionResults"),__publicField$1D(this,"components",{}),__publicField$1D(this,"checkRuntimeContext",null),__publicField$1D(this,"ctxFile",""),__publicField$1D(this,"_runtimeFileReady"),__publicField$1D(this,"_cacheConnector"),__publicField$1D(this,"_readyPromise"),__publicField$1D(this,"_syncQueue",Promise.resolve());const agent=runtime.agent;this._cacheConnector=ConnectorService.getCacheConnector();const reqId=(runtime.processID?.split(":")[0]||"")==runtime.xDebugId?"":"."+uid()+runtime.reqTag;this.ctxFile=`${runtime.xDebugId}${reqId}${agent.jobID?`-job-${agent.jobID}`:""}`,this._readyPromise=new Promise((resolve,reject)=>{let resolved=!1;this.on("ready",()=>{resolved=!0,resolve(!0)}),setTimeout(()=>{resolved||reject(new Error("Agent Runtime context initialization timeout"))},5*60*1e3).unref()}),this.initRuntimeContext()}serialize(){return{step:this.step,sessionResult:this.sessionResult,sessionResults:this.sessionResults,components:this.components}}deserialize(data){this.step=data.step,this.sessionResult=data.sessionResult,this.sessionResults=data.sessionResults,this.components=data.components}reset(){this.step=0,this.sessionResult=!1,this.sessionResults=null,this.components={}}initRuntimeContext(){if(this._runtimeFileReady)return;const endpointDBGCall=this.runtime.xDebugId?.startsWith("dbg-");console$v.debug("Init Agent Context",this.ctxFile,AccessCandidate.agent(this.runtime.agent.id));const agent=this.runtime.agent;let method=(agent.agentRequest.method||"POST").toUpperCase();const endpoint=agent.endpoints?.[agent.agentRequest.path]?.[method];let ctxData={};this._cacheConnector.requester(AccessCandidate.agent(this.runtime.agent.id)).get(this.ctxFile).then(async data=>{if(data)ctxData=JSON.parse(data),ctxData.step||(ctxData.step=0);else{ctxData=JSON.parse(JSON.stringify({components:agent.components,connections:agent.connections,timestamp:Date.now()})),ctxData.step||(ctxData.step=0);for(let cptId in ctxData.components){ctxData.components[cptId]={id:cptId,name:ctxData.components[cptId].name,ctx:{active:!1,name:ctxData.components[cptId].name}};const cpt=ctxData.components[cptId];endpoint&&endpoint.id!=null&&cpt.id==endpoint.id&&endpointDBGCall&&(cpt.ctx.active=!0)}await this._cacheConnector.requester(AccessCandidate.agent(this.runtime.agent.id)).set(this.ctxFile,JSON.stringify(ctxData),null,null,1*60*60)}this.deserialize(ctxData),this._runtimeFileReady=!0,this.emit("ready")})}async ready(){return this._runtimeFileReady?!0:this._readyPromise}async sync(){if(!this.ctxFile)return;this.emit("syncing");const deleteSession=this.runtime.sessionClosed,data=this.serialize();if(data){let serializedData=JSON.stringify(data);console$v.debug("Agent Context Size",this.ctxFile,serializedData.length,AccessCandidate.agent(this.runtime.agent.id)),await this._cacheConnector.requester(AccessCandidate.agent(this.runtime.agent.id)).set(this.ctxFile,serializedData,null,null,3*60*60);const cooldown=serializedData.length/1024/1024/10*1e3;serializedData=null,await delay(cooldown)}deleteSession&&await this._cacheConnector.requester(AccessCandidate.agent(this.runtime.agent.id)).exists(this.ctxFile)&&(console$v.debug("Agent Context Delete",this.ctxFile,AccessCandidate.agent(this.runtime.agent.id)),this.runtime.debug?this._cacheConnector.requester(AccessCandidate.agent(this.runtime.agent.id)).updateTTL(this.ctxFile,5*60):this._cacheConnector.requester(AccessCandidate.agent(this.runtime.agent.id)).delete(this.ctxFile),this.ctxFile=null)}enqueueSync(){this.ctxFile&&(console$v.log("ENQUEUE SYNC"),this._syncQueue=this._syncQueue.then(()=>this.sync()).catch(err=>{console$v.error("Error syncing context",err)}))}incStep(){this.step++}updateComponent(componentId,data){const ctxData=this;if(!ctxData)return;const component=ctxData.components[componentId];component||(console$v.debug(">>>>>>> updateComponent Component debug data not found",componentId,component,AccessCandidate.agent(this.runtime.agent.id)),console$v.debug(">>> ctxFile",this.ctxFile,AccessCandidate.agent(this.runtime.agent.id)),console$v.debug(">>> ctxData",ctxData,AccessCandidate.agent(this.runtime.agent.id))),component.ctx||(component.ctx={active:!1,name:"",step:0}),Object.assign(component.ctx,data),component.ctx.step=this.step,this.enqueueSync()}resetComponent(componentId){const ctxData=this,component=ctxData.components[componentId];component||(console$v.debug(">>>>>>> resetComponent Component debug data not found",componentId,component,AccessCandidate.agent(this.runtime.agent.id)),console$v.debug(">>> ctxFile",this.ctxFile,AccessCandidate.agent(this.runtime.agent.id)),console$v.debug(">>> ctxData",ctxData,AccessCandidate.agent(this.runtime.agent.id))),component.ctx.runtimeData={},component.ctx.active=!1,this.runtime.debug||(component.ctx.input=void 0,component.ctx.output=void 0),this.enqueueSync()}getComponentData(componentId){const ctxData=this;if(!ctxData)return null;const component=ctxData.components[componentId];return component||(console$v.debug(">>>>>>> getComponentData Component debug data not found",componentId,component,AccessCandidate.agent(this.runtime.agent.id)),console$v.debug(">>> ctxFile",this.ctxFile,AccessCandidate.agent(this.runtime.agent.id)),console$v.debug(">>> ctxData",ctxData,AccessCandidate.agent(this.runtime.agent.id))),component.ctx}}var __defProp$1C=Object.defineProperty,__defNormalProp$1C=(obj,key,value)=>key in obj?__defProp$1C(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1C=(obj,key,value)=>__defNormalProp$1C(obj,typeof key!="symbol"?key+"":key,value);const console$u=Logger("AgentRuntime"),AgentRuntimeUnavailable=new Proxy({},{get:function(target,prop,receiver){return typeof target[prop]=="function"?target[prop]:function(){console$u.warn(`AgentRuntime Unavailable tried to call : ${prop.toString()}`)}}}),_AgentRuntime=class _AgentRuntime2{constructor(agent){this.agent=agent,__publicField$1C(this,"agentContext"),__publicField$1C(this,"llmCache"),__publicField$1C(this,"xDebugRun",""),__publicField$1C(this,"xDebugInject",""),__publicField$1C(this,"xDebugRead",""),__publicField$1C(this,"xDebugStop",""),__publicField$1C(this,"xDebugPendingInject",null),__publicField$1C(this,"xMockDataInject",null),__publicField$1C(this,"xDebugId",""),__publicField$1C(this,"xDebugCmd",""),__publicField$1C(this,"_debugActive",!1),__publicField$1C(this,"_runtimeFileReady",!1),__publicField$1C(this,"sessionClosed",!1),__publicField$1C(this,"reqTagOwner",!1),__publicField$1C(this,"reqTag"),__publicField$1C(this,"processID"),__publicField$1C(this,"workflowReqId"),__publicField$1C(this,"alwaysActiveComponents",{}),__publicField$1C(this,"exclusiveComponents",{}),__publicField$1C(this,"checkRuntimeContext",null),this.reqTag=agent.agentRequest.header("X-REQUEST-TAG");const isNestedProcess=!!this.reqTag;this.reqTag?(this.xDebugStop=void 0,this.xDebugRun=void 0,this.xDebugInject=void 0,this.xDebugRead=void 0):(this.xDebugStop=agent.agentRequest.header("X-DEBUG-STOP"),this.xDebugRun=agent.agentRequest.header("X-DEBUG-RUN"),this.xDebugInject=agent.agentRequest.header("X-DEBUG-INJ"),this.xDebugRead=agent.agentRequest.header("X-DEBUG-READ"),this.reqTag="xTAG-"+uid(),this.reqTagOwner=!0),this.xDebugId=this.xDebugStop||this.xDebugRun||this.xDebugRead,!this.xDebugId&&agent.agentRequest.body&&(this.xDebugInject!=null&&this.xDebugInject!=null?(this.xDebugPendingInject=agent.agentRequest.body,this.xDebugRun=this.xDebugInject||"inj-"+uid()):this.xDebugRun==""&&(this.xDebugRun="dbg-"+uid()),this.xDebugId=this.xDebugRun),agent.agentRequest.header("X-MOCK-DATA-INJ")!==void 0&&(this.xMockDataInject=agent.agentRequest.body),this.processID=this.xDebugId,this.xDebugId||(this.xDebugId=agent.sessionId,this.processID=this.reqTag),isNestedProcess&&(this.processID+=`:${Math.floor(1e3+Math.random()*9e3)}`),this.workflowReqId=this.xDebugRun||this.xDebugStop||this.reqTag,_AgentRuntime2.tagsData[this.reqTag]||(_AgentRuntime2.tagsData[this.reqTag]={}),_AgentRuntime2.processResults[this.processID]||(_AgentRuntime2.processResults[this.processID]={timestamp:Date.now(),errorResults:[],sessionResults:[]}),this.agentContext=new RuntimeContext(this),this.agentContext.on("ready",()=>{this.alwaysActiveComponents={},this.exclusiveComponents={};for(let component of this.agent.data.components){const cpt=this.agent.ComponentInstances[component.name];if(!cpt){console$u.warn(`Component ${component.name} Exists in agent but has no implementation`,AccessCandidate.agent(this.agent.id));continue}if(cpt.alwaysActive){this.alwaysActiveComponents[component.id]=cpt,this.updateComponent(component.id,{active:!0,alwaysActive:!0});const runtimeData={...this.getRuntimeData(component.id)};this.saveRuntimeComponentData(component.id,runtimeData)}if(cpt.exclusive){this.exclusiveComponents[component.id]=cpt,this.updateComponent(component.id,{exclusive:!0});const runtimeData={...this.getRuntimeData(component.id)};this.saveRuntimeComponentData(component.id,runtimeData)}}}),this._debugActive=this.xDebugId!=agent.sessionId;const xCacheId=agent.agentRequest.header("X-CACHE-ID")||"";this.llmCache=new LLMCache(AccessCandidate.agent(this.agent.id),xCacheId)}get circularLimitReached(){return this.agentContext?.circularLimitReached||!1}set circularLimitReached(value){this.agentContext&&(this.agentContext.circularLimitReached=value)}get debug(){return this._debugActive}get curStep(){return this.agentContext?.step||0}async ready(){return this.agentContext.ready()}destroy(){this.sessionClosed=!0,this.sync()}incTag(componentId){_AgentRuntime2.tagsData[this.reqTag][componentId]||(_AgentRuntime2.tagsData[this.reqTag][componentId]=0),_AgentRuntime2.tagsData[this.reqTag][componentId]++}async sync(){(this.reqTagOwner&&this.sessionClosed||this.circularLimitReached)&&delete _AgentRuntime2.tagsData[this.reqTag],this.agentContext.enqueueSync()}getWaitingComponents(){const ctxData=this.agentContext;return Object.values(ctxData?.components||[]).filter(c=>c?.ctx?.active==!0).filter(c=>c?.ctx?.status&&typeof c?.ctx?.output!==void 0)}getExclusiveActiveComponents(){const ctxData=this.agentContext;return Object.values(ctxData?.components||[]).filter(c=>c?.ctx?.active==!0).filter(c=>c?.ctx?.exclusive==!0)}readState(stateId,deltaOnly=!1){if(!this._debugActive||!stateId)return null;const runtime=this,agent=this.agent,ctxData=runtime.agentContext,dbgAllComponents=runtime.xDebugPendingInject||Object.values(ctxData?.components||[]);let dbgActiveComponents;dbgActiveComponents=dbgAllComponents.filter(c=>c?.ctx?.active==!0&&c?.ctx?.exclusive==!0),(!dbgActiveComponents||dbgActiveComponents.length==0)&&(dbgActiveComponents=dbgAllComponents.filter(c=>c?.ctx?.active==!0||!c?.ctx?.output?._error&&Array.isArray(c?.ctx?._job_components)&&c?.ctx?._job_components.length>0)),dbgAllComponents.filter(c=>c?.ctx?.active==!0&&c?.ctx?.status&&typeof c?.ctx?.output!==void 0),dbgAllComponents.filter(c=>c?.ctx?.active==!0&&!c?.ctx?.status);let state={};for(let dbgComponent of dbgAllComponents)state[dbgComponent.id]=dbgComponent.ctx;let dbgSession=stateId;(!dbgActiveComponents||dbgActiveComponents.length==0)&&(dbgSession=null,runtime.sessionClosed=!0);const remainingActiveComponents=Object.values(ctxData?.components||[]).filter(c=>c?.ctx?.active==!0&&!c?.ctx?.alwaysActive),activeAsyncComponents=Object.values(ctxData?.components||[]).filter(c=>!c?.ctx?.output?._error&&Array.isArray(c?.ctx?._job_components)&&c?.ctx?._job_components.length>0);if(remainingActiveComponents.length==0&&activeAsyncComponents.length==0&&(runtime.sessionClosed=!0),runtime.circularLimitReached){const error=`Circular Calls Limit Reached on ${runtime.checkCircularLimit()}. Current agent circular limit is ${agent.circularLimit}`;return runtime.sessionClosed=!0,{state,dbgSession,sessionClosed:runtime.sessionClosed,error}}const step=this.curStep>=1?this.curStep-1:0;if(deltaOnly){const delta={};for(let cptId in state){const cpt=state[cptId];cpt.step>=step&&(delta[cptId]=cpt)}state=delta}return{state,dbgSession,sessionClosed:runtime.sessionClosed,step}}async runCycle(){console$u.debug(`runCycle agentId=${this.agent.id} wfReqId=${this.workflowReqId} reqTag=${this.reqTag} session=${this.xDebugRun} cycleId=${this.processID}`,AccessCandidate.agent(this.agent.id));const runtime=this,agent=this.agent,ctxData=runtime.agentContext,dbgAllComponents=runtime.xDebugPendingInject||Object.values(ctxData?.components||[]);let dbgActiveComponents;dbgActiveComponents=dbgAllComponents.filter(c=>c?.ctx?.active==!0&&c?.ctx?.exclusive==!0),(!dbgActiveComponents||dbgActiveComponents.length==0)&&(dbgActiveComponents=dbgAllComponents.filter(c=>c?.ctx?.active==!0||!c?.ctx?.output?._error&&Array.isArray(c?.ctx?._job_components)&&c?.ctx?._job_components.length>0));const dbgActiveWaitingComponents=dbgAllComponents.filter(c=>c?.ctx?.active==!0&&c?.ctx?.status&&typeof c?.ctx?.output!==void 0),dbgActiveReadyComponents=dbgAllComponents.filter(c=>c?.ctx?.active==!0&&!c?.ctx?.status||!c?.ctx?.output?._error&&Array.isArray(c?.ctx?._job_components)&&c?.ctx?._job_components.length>0);let step;if((!dbgActiveComponents||dbgActiveComponents.length==0)&&(runtime.sessionClosed=!0,step={state:{sessionClosed:!0},dbgSession:null,expiredDbgSession:runtime.xDebugId,sessionClosed:!0}),!step&&dbgActiveComponents.length==dbgActiveWaitingComponents.length&&ctxData.sessionResult&&(runtime.sessionClosed=!0,step={state:{sessionClosed:!0},dbgSession:null,expiredDbgSession:runtime.xDebugId,sessionClosed:!0}),!step&&dbgActiveReadyComponents.length>0){const promises=[];for(let dbgComponent of dbgActiveReadyComponents){const injectInput=runtime.xDebugPendingInject?dbgComponent.ctx.input:void 0;promises.push(agent.callComponent(dbgComponent.ctx.sourceId,dbgComponent.id,injectInput))}const dbgResults=await Promise.all(promises),state=dbgResults.length==1?dbgResults[0]:dbgResults;runtime.xDebugPendingInject=null;const remainingActiveComponents=Object.values(ctxData?.components||[]).filter(c=>c?.ctx?.active==!0),activeAsyncComponents=Object.values(ctxData?.components||[]).filter(c=>!c?.ctx?.output?._error&&Array.isArray(c?.ctx?._job_components)&&c?.ctx?._job_components.length>0);dbgAllComponents.filter(c=>c?.ctx?.status&&typeof c?.ctx?.output!==void 0).length==remainingActiveComponents.length&&(ctxData.sessionResult=!0);let sessionResults=dbgResults.flat().filter(e=>e.id&&e.result&&!e.result._missing_inputs&&!agent.connections.find(c=>c.sourceId==e.id)),errorResults=dbgResults.flat().filter(e=>e.id&&(e.error||e.result?._error));errorResults=errorResults.filter(e=>!ctxData?.components?.[e.id]?.ctx?.runtimeData?._ChildLoopData),ctxData.sessionResult&&sessionResults.length==0&&runtime.sessionClosed&&(sessionResults=errorResults),ctxData.sessionResults=sessionResults,step={state,dbgSession:runtime.xDebugRun,sessionResult:runtime.agentContext.sessionResult,sessionResults:runtime.agentContext.sessionResults,errorResults,sessionClosed:remainingActiveComponents.length==0&&activeAsyncComponents.length==0}}else runtime.sessionClosed=!0,step={state:{sessionClosed:!0},dbgSession:null,expiredDbgSession:runtime.xDebugId,sessionClosed:!0};if(this.checkCircularLimit(),step.sessionResults&&_AgentRuntime2.processResults[this.processID].sessionResults.push(step.sessionResults),step.errorResults&&_AgentRuntime2.processResults[this.processID].errorResults.push(step.errorResults),step?.sessionClosed||this.circularLimitReached){const finalResult=this.processResults();step.finalResult=finalResult,runtime.sessionClosed=!0}return this.incStep(),this.sync(),step}processResults(){let result={error:"Error processing results"};const sessionResults=_AgentRuntime2.processResults[this.processID].sessionResults,errorResults=_AgentRuntime2.processResults[this.processID].errorResults;if(this.circularLimitReached)result={error:`Circular Calls Limit Reached on ${this.circularLimitReached}. Current circular limit is ${this.agent.circularLimit}`};else{let state=[sessionResults,errorResults].flat(1/0);(!state||state.length==0)&&(state=errorResults.flat(1/0)),result=state.reduce((acc,current)=>(acc.seen[current.id]||(acc.result.push(current),acc.seen[current.id]=!0),acc),{seen:{},result:[]}).result.filter(e=>!e.result?._exclude)}return delete _AgentRuntime2.processResults[this.processID],this.sync(),result}checkCircularLimit(){if(this.circularLimitReached)return this.agentContext.circularLimitReached;for(let componentId in _AgentRuntime2.tagsData[this.reqTag])if(_AgentRuntime2.tagsData[this.reqTag][componentId]>this.agent.circularLimit)return this.sessionClosed=!0,this.agentContext.circularLimitReached=componentId,componentId;return!1}async injectDebugOutput(componentId){let component={};if(this.xDebugPendingInject?component=this.xDebugPendingInject?.find(c=>c.id==componentId):this.xMockDataInject&&(component=this.xMockDataInject?.find(c=>c.id==componentId)),component?.ctx?.output){let allEmpty=!0;for(let key in component.ctx.output)if(component.ctx.output[key]!=""){allEmpty=!1;break}return allEmpty?null:component.ctx.output}}getRuntimeData(componentId){const componentData=this.getComponentData(componentId);return componentData?componentData.runtimeData||{}:{}}updateRuntimeData(componentId,data){const componentData=this.getComponentData(componentId);componentData&&(componentData.runtimeData={...componentData.runtimeData,...data},this.sync())}saveRuntimeComponentData(componentId,data){this.updateComponent(componentId,{runtimeData:data})}incStep(){this.agentContext.incStep()}updateComponent(componentId,data){this.agentContext.updateComponent(componentId,data)}resetComponent(componentId){this.agentContext.resetComponent(componentId)}getComponentData(componentId){return this.agentContext.getComponentData(componentId)}};__publicField$1C(_AgentRuntime,"processResults",{}),__publicField$1C(_AgentRuntime,"tagsData",{}),__publicField$1C(_AgentRuntime,"dummy",AgentRuntimeUnavailable);let AgentRuntime=_AgentRuntime;const OSResourceMonitor={mem:getMemoryUsage(),cpu:getCpuUsage()};function getCpuUsage(){const cpus=os.cpus();let user=0,nice=0,sys=0,idle=0,irq=0,total=0;for(let cpu of cpus)user+=cpu.times.user,nice+=cpu.times.nice,sys+=cpu.times.sys,idle+=cpu.times.idle,irq+=cpu.times.irq;return total=user+nice+sys+idle+irq,{user:user/total*100,sys:sys/total*100,idle:idle/total*100,load:100-idle/total*100}}function getMemoryUsage(){const totalMemory=os.totalmem(),freeMemory=os.freemem(),usedMemory=totalMemory-freeMemory;return{totalMemory:(totalMemory/1024**3).toFixed(2)+" GB",freeMemory:(freeMemory/1024**3).toFixed(2)+" GB",usedMemory:(usedMemory/1024**3).toFixed(2)+" GB",memoryUsagePercentage:(usedMemory/totalMemory*100).toFixed(2)}}var __defProp$1B=Object.defineProperty,__defNormalProp$1B=(obj,key,value)=>key in obj?__defProp$1B(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1B=(obj,key,value)=>__defNormalProp$1B(obj,key+"",value);class AgentSSE{constructor(agent){this.agent=agent,__publicField$1B(this,"connections",new Map)}add(res,monitorId){this.connections.set(monitorId,res)}[Symbol.iterator](){return this.connections.entries()}async send(_type,_data){if(!_type||!_data)return;const data=typeof _data=="string"?_data:JSON.stringify(_data),message=`event: ${_type}
25
25
  data: ${data}
26
26
 
27
- `;for(const[id,connection]of this.connections.entries())try{connection&&!connection.finished?connection.write(message):this.connections.delete(id)}catch(error){console.error(`Error sending SSE to connection ${id}:`,error),this.connections.delete(id)}}remove(connectionId){const connection=this.connections.get(connectionId);if(connection){try{connection&&!connection.finished&&connection.end()}catch(error){console.error(`Error closing connection ${connectionId}:`,error)}return this.connections.delete(connectionId)}return!1}async close(){for(const[id,connection]of this.connections.entries())try{connection&&!connection.finished&&(connection.end(),console.log("Delibertly shutting down sse connection with id: ",id))}catch(error){console.error(`Error closing connection ${id}:`,error)}this.connections.clear()}getConnectionCount(){return this.connections.size}}var __defProp$1A=Object.defineProperty,__defNormalProp$1A=(obj,key,value)=>key in obj?__defProp$1A(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1A=(obj,key,value)=>__defNormalProp$1A(obj,typeof key!="symbol"?key+"":key,value);const console$t=Logger("Agent"),idPromise=id=>id,MAX_LATENCY=50;class Agent{constructor(id,agentData,agentSettings,agentRequest){this.id=id,this.agentSettings=agentSettings,__publicField$1A(this,"name"),__publicField$1A(this,"data"),__publicField$1A(this,"teamId"),__publicField$1A(this,"components"),__publicField$1A(this,"connections"),__publicField$1A(this,"endpoints",{}),__publicField$1A(this,"sessionId"),__publicField$1A(this,"sessionTag",""),__publicField$1A(this,"callerSessionId"),__publicField$1A(this,"apiBasePath","/api"),__publicField$1A(this,"agentRuntime"),__publicField$1A(this,"usingTestDomain",!1),__publicField$1A(this,"domain",""),__publicField$1A(this,"debugSessionEnabled",!1),__publicField$1A(this,"circularLimit",100),__publicField$1A(this,"version",""),__publicField$1A(this,"agentVariables",{}),__publicField$1A(this,"_kill",!1),__publicField$1A(this,"async",!1),__publicField$1A(this,"jobID",""),__publicField$1A(this,"planInfo",{}),__publicField$1A(this,"callback"),__publicField$1A(this,"agentRequest"),__publicField$1A(this,"sse"),__publicField$1A(this,"modelsProvider"),__publicField$1A(this,"_componentInstance",{}),__publicField$1A(this,"_componentInstancesLoader",new ControlledPromise(()=>{}));const json=typeof agentData=="string"?JSON.parse(agentData):agentData;this.data=json.connections&&json.components?json:json.data,this.data||(this.data={name:"",connections:[],components:[]}),this.name=this.data.name,this.version=this.data.agentVersion||"",this.teamId=this.data.teamId,this.connections=this.data.connections,this.debugSessionEnabled=this.data.debugSessionEnabled,this.usingTestDomain=this.data.usingTestDomain,this.agentVariables=this.data.variables||{};const endpoints=this.data.components.filter(c=>c.name=="APIEndpoint");for(let endpoint of endpoints){let method=endpoint.data.method||"POST";method=method.toUpperCase(),this.endpoints[`${this.apiBasePath}/${endpoint.data.endpoint}`]||(this.endpoints[`${this.apiBasePath}/${endpoint.data.endpoint}`]={}),this.endpoints[`${this.apiBasePath}/${endpoint.data.endpoint}`][method]=endpoint}this.components={};for(let component of this.data.components)this.components[component.id]=component;for(let connection of this.data.connections){const sourceComponent=this.components[connection.sourceId],targetComponent=this.components[connection.targetId],sourceIndex=typeof connection.sourceIndex=="number"?connection.sourceIndex:sourceComponent.outputs.findIndex(o=>o.name==connection.sourceIndex),targetIndex=typeof connection.targetIndex=="number"?connection.targetIndex:targetComponent.inputs.findIndex(i=>i.name==connection.targetIndex);connection.sourceIndex=sourceIndex,connection.targetIndex=targetIndex;const output=sourceComponent.outputs[sourceIndex];output.index=sourceIndex;const input=targetComponent.inputs[targetIndex];input.index=targetIndex,output.next||(output.next=[]),output.next.push(targetComponent.id),input.prev||(input.prev=[]),input.prev.push(sourceComponent.id)}this.tagAsyncComponents(),agentRequest&&this.setRequest(agentRequest),this.sse=new AgentSSE(this);try{ConnectorService.getComponentConnector().requester(AccessCandidate.agent(id)).getAll().then(customComponents=>{this._componentInstance={...this._componentInstance,...customComponents},this._componentInstancesLoader.resolve(!0)})}catch{console$t.warn("Could not load custom components",AccessCandidate.agent(this.id)),this._componentInstancesLoader.reject("Could not load custom components")}const modelsProvider=ConnectorService.getModelsProviderConnector();modelsProvider.valid&&(this.modelsProvider=modelsProvider.agent(id))}get ComponentInstances(){return this._componentInstance}addSSE(sseSource,monitorId){if(sseSource instanceof AgentSSE)for(const[monitorId2,res]of sseSource)this.sse.add(res,monitorId2);else{const id=monitorId||Math.random().toString(36).substring(2,15);this.sse.add(sseSource,id)}}setRequest(agentRequest){if(this.agentRequest)return;this.agentRequest=agentRequest,this.agentRequest=agentRequest;const dateTime=getCurrentFormattedDate();this.sessionId="rt-"+(this.agentRequest.sessionID||dateTime+"."+uid());const sessionTags=this?.agentRequest?.headers["x-session-tag"];sessionTags&&(this.sessionTag+=this.sessionTag?`,${sessionTags}`:sessionTags);var regex=new RegExp(`^/v[0-9]+(.[0-9]+)?${this.apiBasePath}/(.*)`);this.agentRequest?.path?.startsWith(`${this.apiBasePath}/`)||this.agentRequest?.path?.match(regex)?(this.agentRuntime=new AgentRuntime(this),this.callerSessionId=this?.agentRequest?.headers["x-caller-session-id"]?.substring(0,256)||this.agentRuntime.workflowReqId||this.sessionId):this.agentRuntime=AgentRuntime.dummy}setCallback(callback){this.callback=callback}kill(){this._kill=!0}isKilled(){return this._kill}async parseVariables(){if(typeof this.agentVariables=="object")for(let key in this.agentVariables){const value=this.agentVariables[key];value.startsWith("{{")&&value.endsWith("}}")&&(this.agentVariables[key]=await TemplateString(value).parseTeamKeysAsync(this.teamId).asyncResult)}}async process(endpointPath,input){await this.agentRuntime.ready();let result,dbgSession=null,sessionClosed=!1;const eventId="e-"+uid(),startTime=Date.now();this.sse.send("agent",{eventId,action:"callStart",endpointPath,id:this.id,name:this.name,startTime,input});const logId=AgentLogger.log(this,null,{sourceId:endpointPath,componentId:"AGENT",domain:this.domain,input,workflowID:this.agentRuntime.workflowReqId,processID:this.agentRuntime.processID,inputTimestamp:new Date().toISOString(),sessionID:this.callerSessionId,tags:this.sessionTag}),method=this.agentRequest.method.toUpperCase(),endpoint=this.endpoints[endpointPath]?.[method];if(this.agentRuntime.debug){if(!endpoint&&this.agentRequest.path!="/api/")throw logId&&AgentLogger.log(this,logId,{error:`Endpoint ${method} ${endpointPath} Not Found`}),new Error(`Endpoint ${method} ${endpointPath} Not Found`);let dbgResult;if(dbgResult||(dbgResult=await this.agentRuntime.runCycle()),dbgResult&&typeof dbgResult?.state<"u")return this.agentRuntime.sync(),dbgResult?.finalResult&&(dbgResult.finalResult=await this.postProcess(dbgResult.finalResult).catch(error=>({error}))),dbgResult}if(!endpoint){logId&&AgentLogger.log(this,logId,{error:`Endpoint ${method} ${endpointPath} Not Found`});const endTime2=Date.now(),duration2=endTime2-startTime;throw this.sse.send("agent",{eventId,action:"callStop",endpointPath,id:this.id,name:this.name,startTime,endTime:endTime2,duration:duration2,input,error:`Endpoint ${method} ${endpointPath} Not Found`}),new Error(`Endpoint ${method} ${endpointPath} Not Found`)}this.agentRuntime.updateComponent(endpoint.id,{active:!0,input,sourceId:null});let step;do{step=await this.agentRuntime.runCycle();const qosLatency=Math.floor(OSResourceMonitor.cpu.load*MAX_LATENCY||0);await delay(10+qosLatency)}while(!step?.finalResult&&!this._kill);if(this._kill){const endTime2=Date.now(),duration2=endTime2-startTime;return this.sse.send("agent",{eventId,action:"callStop",endpointPath,id:this.id,name:this.name,startTime,endTime:endTime2,duration:duration2,input,error:"Agent killed"}),console$t.warn(`Agent ${this.id} was killed`,AccessCandidate.agent(this.id)),{error:"Agent killed"}}if(result=await this.postProcess(step?.finalResult).catch(error=>({error})),this.agentRuntime.circularLimitReached){const circularLimitData=this.agentRuntime.circularLimitReached;result={error:`Circular Calls Limit Reached on ${circularLimitData}. Current circular limit is ${this.circularLimit}`};const endTime2=Date.now(),duration2=endTime2-startTime;throw this.sse.send("agent",{eventId,action:"callStop",endpointPath,id:this.id,name:this.name,startTime,endTime:endTime2,duration:duration2,input,error:result.error}),new Error(`Circular Calls Limit Reached on ${circularLimitData}. Current circular limit is ${this.circularLimit}`)}logId&&AgentLogger.log(this,logId,{outputTimestamp:""+Date.now(),result}),this.updateTasksCount();const endTime=Date.now(),duration=endTime-startTime;return this.sse.send("agent",{eventId,action:"callStop",endpointPath,id:this.id,name:this.name,startTime,endTime,duration,input,result}),this.agentRuntime.debug?{state:result,dbgSession,sessionClosed}:result}async updateTasksCount(){}async postProcess(result){Array.isArray(result)&&(result=result.flat(1/0)),Array.isArray(result)||(result=[result]),result=result.filter(r=>!(r?.result?._error&&r?.result?._error_handled));for(let i=0;i<result.length;i++){const _result=result[i];if(!_result)continue;_result._debug&&delete _result._debug,_result._debug_time&&delete _result._debug_time;const _componentData=this.components[_result.id];if(!_componentData)continue;const _component=this._componentInstance[_componentData.name];if(!_component)continue;const postProcessResult=await _component.postProcess(_result,_componentData,this).catch(error=>({error}));result[i]=postProcessResult}return result.length==1&&(result=result[0]),result}hasLoopAncestor(inputEntry){if(!inputEntry.prev)return!1;for(let prevId of inputEntry.prev){const prevComponentData=this.components[prevId];if(prevComponentData.name=="ForEach")return!0;for(let inputEntry2 of prevComponentData.inputs)if(this.hasLoopAncestor(inputEntry2))return!0}}clearChildLoopRuntimeComponentData(componentId){const componentData=this.components[componentId],runtimeData=this.agentRuntime.getRuntimeData(componentId);if(runtimeData._ChildLoopData)for(let inputEntry of componentData.inputs)this.hasLoopAncestor(inputEntry)&&delete runtimeData.input[inputEntry.name]}getComponentMissingInputs(componentId,_input){let missingInputs=[];const componentData=this.components[componentId];if(this._componentInstance[componentData.name].alwaysActive)return missingInputs;const readablePredecessors=this.findReadablePredecessors(componentId),readableInputNames={};for(let pred of readablePredecessors)pred&&(readableInputNames[pred.input.name]=pred);const allInputIndexes=this.connections.filter(c=>c.targetId==componentId).map(e=>e.targetIndex),allInputs=componentData.inputs.filter(r=>allInputIndexes.includes(r.index));if(Array.isArray(allInputs)&&allInputs.length>0){for(let input of allInputs)if(!input.optional){if(readableInputNames[input.name]){const pred=readableInputNames[input.name],component2=pred.component,predComponentData=this.components[pred.id];if(component2.hasOutput(pred.output.name,predComponentData,this))continue}typeof _input[input.name]>"u"&&missingInputs.push(input.name)}}return missingInputs}findReadablePredecessors(componentId){const componentData=this.components[componentId];return this._componentInstance[componentData.name],this.connections.filter(c=>c.targetId==componentId).map(c=>{const sourceComponentData=this.components[c.sourceId],sourceComponent=this._componentInstance[sourceComponentData.name],output=sourceComponentData.outputs[c.sourceIndex],input=componentData.inputs[c.targetIndex];return sourceComponent.hasReadOutput?{output,input,component:sourceComponent,id:c.sourceId}:null}).filter(e=>e!=null)}updateStep(sourceId,componentId){const agentRuntime=this.agentRuntime,step=agentRuntime.curStep;agentRuntime.updateComponent(componentId,{step})}async callComponent(sourceId,componentId,input){const startTime=Date.now(),agentRuntime=this.agentRuntime,componentData=this.components[componentId],component=this._componentInstance[componentData.name],eventId="e-"+uid();if(this.sse.send("component",{eventId,action:"callStart",sourceId,id:componentId,name:componentData.displayName,title:componentData.title,startTime,input}),this._kill){console$t.warn(`Agent ${this.id} was killed, skipping component ${componentData.name}`,AccessCandidate.agent(this.id));const output2={id:componentData.id,name:componentData.displayName,result:null,error:"Agent killed"},endTime2=Date.now(),duration2=endTime2-startTime;return this.sse.send("component",{eventId,action:"callStop",sourceId,id:componentId,name:componentData.displayName,title:componentData.title,startTime,endTime:endTime2,duration:duration2,output:output2}),output2}if(!component){const endTime2=Date.now(),duration2=endTime2-startTime;throw this.sse.send("component",{eventId,action:"callStop",sourceId,id:componentId,name:componentData.displayName,title:componentData.title,startTime,endTime:endTime2,duration:duration2,output:{error:"Component not found"}}),new Error(`Component ${componentData.name} not found`)}if(this.agentRuntime.incTag(componentId),this.agentRuntime.checkCircularLimit(),this.agentRuntime.circularLimitReached){const endTime2=Date.now(),duration2=endTime2-startTime;return this.sse.send("component",{eventId,action:"callStop",sourceId,id:componentId,name:componentData.displayName,title:componentData.title,startTime,endTime:endTime2,duration:duration2,output:{error:"Circular Calls Reached"}}),{error:"Circular Calls Reached"}}agentRuntime.getComponentData(componentId)?.output?._missing_inputs&&agentRuntime.updateComponent(componentId,{output:{}});const _input=this.prepareComponentInput(componentId,input),logId=AgentLogger.log(this,null,{sourceId:sourceId||"AGENT",componentId,domain:this.domain,workflowID:this.agentRuntime.workflowReqId,processID:this.agentRuntime.processID,input:componentData.name=="APIEndpoint"?this.agentRequest.method=="GET"?this.agentRequest.query:this.agentRequest.body:_input,inputTimestamp:new Date().toISOString(),sessionID:this.callerSessionId,tags:this.sessionTag});let output=null,missingInputs=[];if(this.updateStep(sourceId,componentId),agentRuntime.debug&&(output=await agentRuntime.injectDebugOutput(componentId)),!output){if(missingInputs=this.getComponentMissingInputs(componentId,_input),missingInputs.length>0){agentRuntime.updateComponent(componentId,{active:!0,status:"waiting"});const connections=this.connections.filter(c=>c.sourceId==componentId)||[];for(let connection of connections)if(componentData.outputs[connection.sourceIndex].name=="_error")break;output={_error:"Missing inputs : "+JSON.stringify(missingInputs),_missing_inputs:missingInputs}}if(!output){const validationResult=await component.validateConfig(componentData);if(validationResult._error)output=validationResult;else try{await this.parseVariables(),output=await component.process({...this.agentVariables,..._input},{...componentData,eventId},this),console$t.debug(output,AccessCandidate.agent(this.id))}catch(error){console$t.error("Error on component process: ",{componentId,name:componentData.name,input:_input},error,AccessCandidate.agent(this.id)),error?.message?output={Response:void 0,_error:error.message,_debug:error.message}:output={Response:void 0,_error:error.toString(),_debug:error.toString()}}}}const runtimeData=this.agentRuntime.getRuntimeData(componentId);if(agentRuntime.updateComponent(componentId,{output}),output._in_progress&&agentRuntime.updateComponent(componentId,{active:!0,status:"in_progress"}),(output.error||output._error)&&(runtimeData?._ChildLoopData?._in_progress||this.agentRuntime.resetComponent(componentId),logId&&AgentLogger.log(this,logId,{error:output.error||output._error}),output.error)){const endTime2=Date.now(),duration2=endTime2-startTime;return this.sse.send("component",{eventId,action:"callStop",sourceId,id:componentId,name:componentData.displayName,title:componentData.title,startTime,endTime:endTime2,duration:duration2,output:{error:output.error||output._error}}),[{id:componentData.id,name:componentData.displayName,result:null,error:output.error||output._error,_debug:output.error||output._error}]}let results=[];if(output&&!output._missing_inputs){if(AgentLogger.logTask(this,1),results=await this.callNextComponents(componentId,output).catch(error=>({error,id:componentData.id,name:componentData.displayName})),runtimeData._LoopData&&output._in_progress&&runtimeData._LoopData.branches==null){const branches=Array.isArray(results)?results.length:1;output._in_progress&&(runtimeData._LoopData.branches=branches,agentRuntime.updateRuntimeData(componentId,{_LoopData:runtimeData._LoopData}))}if(results._is_leaf){delete results._is_leaf;const _ChildLoopData=runtimeData._ChildLoopData;if(_ChildLoopData&&_ChildLoopData.parentId){const parentId=_ChildLoopData.parentId,_LoopData=this.agentRuntime.getRuntimeData(parentId)._LoopData;if(_LoopData){_LoopData.result||(_LoopData.result=[]);let resultsCopy=JSON.parse(JSON.stringify(results));results.result&&(results.result._exclude=!0),resultsCopy=await component.postProcess(resultsCopy,componentData,this),_LoopData.result.push(resultsCopy),_LoopData.branches--,_LoopData.branches<=0&&agentRuntime.updateComponent(parentId,{active:!0,status:""}),agentRuntime.updateRuntimeData(parentId,{_LoopData})}}else{const _LoopData=this.agentRuntime.getRuntimeData(componentId)._LoopData;_LoopData&&_LoopData.loopIndex==1&&(_LoopData._in_progress=!1,output._in_progress=!1,agentRuntime.updateComponent(componentId,{active:!0,status:""}),agentRuntime.updateRuntimeData(componentId,{_LoopData}))}}}!output._missing_inputs&&!output._in_progress&&(runtimeData?._ChildLoopData?._in_progress&&runtimeData._ChildLoopData?.loopIndex<runtimeData._ChildLoopData?.loopLength?(this.clearChildLoopRuntimeComponentData(componentId),agentRuntime.updateComponent(componentId,{active:!0,status:"waiting"})):this.agentRuntime.resetComponent(componentId)),Array.isArray(results)&&(results=results.flat(1/0).filter(r=>r.result!=null)),logId&&AgentLogger.log(this,logId,{output,outputTimestamp:""+Date.now()});const endTime=Date.now(),duration=endTime-startTime;return this.sse.send("component",{eventId,action:"callStop",sourceId,id:componentId,name:componentData.displayName,title:componentData.title,startTime,endTime,duration,output}),[results,{id:componentData.id,name:componentData.displayName,result:output}]}JSONExpression(obj,propertyString){const properties=propertyString.split(/\.|\[|\]\.|\]\[|\]/).filter(Boolean);let currentProperty=obj;for(let property of properties){if(currentProperty==null)return;currentProperty=currentProperty[property]}return currentProperty}async callNextComponents(componentId,output){const agentRuntime=this.agentRuntime,componentData=this.components[componentId];this._componentInstance[componentData.name];let connections=this.connections.filter(c=>c.sourceId==componentId).map(c=>({...c,output,componentData}));const waitingComponents=agentRuntime.getWaitingComponents(),waitingComponentIds=waitingComponents.map(e=>e.id),alwaysActiveIds=Object.keys(this.agentRuntime.alwaysActiveComponents),alwaysActiveConnections=this.connections.filter(c=>alwaysActiveIds.includes(c.sourceId)&&waitingComponentIds.includes(c.targetId)).map(c=>{const output2={};waitingComponents.find(e=>e.id==c.targetId);const prevComponentData=this.components[c.sourceId],prevComponent=this._componentInstance[prevComponentData.name],outputEndpoint=prevComponentData.outputs[c.sourceIndex];return output2[outputEndpoint.name]=prevComponent.readOutput(outputEndpoint.name,prevComponentData,this),{...c,output:output2,componentData:this.components[c.sourceId]}});if(connections=[...connections,...alwaysActiveConnections],!Array.isArray(connections)||connections.length==0)return{id:componentData.id,name:componentData.name,result:output,_is_leaf:!0};const targetComponents=connections.reduce((acc,obj)=>{let key=obj.targetId;return acc[key]||(acc[key]=[]),acc[key].push(obj),acc},{}),promises=[];for(let targetId in targetComponents){const targetComponentData=this.components[targetId];if(!this.async&&targetComponentData.async&&targetComponentData.name!=="Async")continue;this._componentInstance[targetComponentData.name];const connections2=targetComponents[targetId];let _isErrorHandler=!1;if(Array.isArray(connections2)&&connections2.length>0){const nextInput={};for(let connection of connections2){const output2=connection.output,componentData2=connection.componentData,outputEndpoint=componentData2.outputs[connection.sourceIndex],inputEndpoint=targetComponentData.inputs[connection.targetIndex],outputExpression=outputEndpoint.expression||outputEndpoint.name,outputParts=outputExpression.split("."),defaultOutputs=componentData2.outputs.find(c=>c.default);let value;if(outputEndpoint.name=="_error"&&(_isErrorHandler=!0),outputEndpoint.default?value=output2[outputEndpoint.name]:defaultOutputs&&(value=output2[defaultOutputs.name]?.[outputEndpoint.name]),value===void 0&&outputParts.length>=1){let val=this.JSONExpression(output2,outputExpression);val!==void 0&&(value=val)}if(value!==void 0){let combinedInput=_mergeInputs(nextInput[inputEndpoint.name],value).filter(e=>e!==void 0);nextInput[inputEndpoint.name]=combinedInput.length===1?combinedInput[0]:combinedInput}}if(!nextInput||JSON.stringify(nextInput)=="{}")continue;const input=this.prepareComponentInput(targetId,nextInput),targetComponent2=this.components[targetId];_isErrorHandler&&targetComponent2&&(output._error_handled=!0);const status=this.getComponentMissingInputs(targetId,input).length>0?"waiting":void 0,sourceRuntimeData=this.agentRuntime.getRuntimeData(componentId);let _ChildLoopData=sourceRuntimeData._LoopData;(!_ChildLoopData||!_ChildLoopData._in_progress)&&(_ChildLoopData=sourceRuntimeData._ChildLoopData),agentRuntime.updateComponent(targetId,{active:!0,input:nextInput,sourceId:componentId,status}),agentRuntime.updateRuntimeData(targetId,{_ChildLoopData,_LoopData:null}),promises.push(idPromise({id:targetId,name:targetComponent2.name,inputs:nextInput})),status&&AgentLogger.log(this,null,{sourceId:componentId,componentId:targetId,step:this.agentRuntime.curStep+1,domain:this.domain,workflowID:this.agentRuntime.workflowReqId,processID:this.agentRuntime.processID,input:{__action:"status_update",__status:status,data:nextInput},inputTimestamp:new Date().toISOString(),sessionID:this.callerSessionId,tags:this.sessionTag})}}if(promises.length==0)return{id:componentData.id,name:componentData.name,result:output,_is_leaf:!0};const results=await Promise.all(promises);return results.length==1?results[0]:results}prepareComponentInput(targetId,inputs){const rData=this.agentRuntime.getRuntimeData(targetId),componentData=this.components[targetId],rDataInput=rData?.input||{};let _input={...rDataInput};if(inputs)for(let key in inputs){let value=inputs[key];_input[key]=_mergeInputs(rDataInput[key],value).filter(e=>e!==void 0),_input[key].length==1&&(_input[key]=_input[key][0])}const readablePredecessors=this.findReadablePredecessors(targetId);for(let c of readablePredecessors)if(c){const predComponentData=this.components[c.id],value=c.component.readOutput(c.output.name,predComponentData,this);value&&c.input?.name&&(_input||(_input={}),_input[c.input.name]=value)}this.agentRuntime.updateRuntimeData(targetId,{input:_input});for(let input of componentData.inputs)input.defaultVal&&_input[input.name]===void 0&&(_input[input.name]=TemplateString(input.defaultVal).parse(this.agentVariables).result);return _input}getConnectionSource(connection){return this.components[connection.sourceId].inputs.find(e=>e.index===connection.sourceIndex)}getConnectionTarget(connection){return this.components[connection.targetId].inputs.find(e=>e.index===connection.targetIndex)}recursiveTagAsyncComponents(component){const agent=this;for(let output of component.outputs){if(component.name=="Async"&&output.name==="JobID")continue;const connected=agent.connections.filter(c=>c.sourceId===component.id&&c.sourceIndex===output.index);if(connected)for(let con of connected){const targetComponent=agent.components[con.targetId];targetComponent&&(targetComponent.async=!0,this.recursiveTagAsyncComponents(targetComponent))}}}tagAsyncComponents(){const AsyncComponents=Object.values(this.components).filter(c=>c.name==="Async");if(!(!AsyncComponents||AsyncComponents.length==0))for(let AsyncComponent of AsyncComponents)AsyncComponent.async=!0,this.recursiveTagAsyncComponents(AsyncComponent)}}function _mergeInputs(existing,newValue){return existing===void 0?[newValue]:(Array.isArray(existing)||(existing=[existing]),[...existing,newValue])}var __defProp$1z=Object.defineProperty,__defNormalProp$1z=(obj,key,value)=>key in obj?__defProp$1z(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1z=(obj,key,value)=>__defNormalProp$1z(obj,typeof key!="symbol"?key+"":key,value);class AgentRequest{constructor(req){if(__publicField$1z(this,"headers"),__publicField$1z(this,"body"),__publicField$1z(this,"query"),__publicField$1z(this,"params"),__publicField$1z(this,"method","GET"),__publicField$1z(this,"path",""),__publicField$1z(this,"sessionID",""),__publicField$1z(this,"res",null),__publicField$1z(this,"req",null),__publicField$1z(this,"files",[]),__publicField$1z(this,"_agent_authinfo"),!req)return;this.headers=JSON.parse(JSON.stringify(req.headers||{})),this.body=JSON.parse(JSON.stringify(req.body||req.data||{})),this.query=JSON.parse(JSON.stringify(req.query||{})),this.params=JSON.parse(JSON.stringify(req.params||{}));const lowerCaseHeaders=Object.fromEntries(Object.entries(this.headers).map(([key,value])=>[key.toLowerCase(),value]));if(this.headers={...lowerCaseHeaders,...this.headers},req?.url)try{const url=new URL(req.url);this.path=url.pathname,this.query={...this.query,...Object.fromEntries(url.searchParams)}}catch{}req?.path&&(this.path=req.path),this.method=req.method,this.sessionID=req.sessionID,this.files=req.files||[],this._agent_authinfo=req._agent_authinfo,this.req=req instanceof AgentRequest?req?.req:req,this.res=req?.res||null}header(name){return this.headers[name.toLowerCase()]}}var __defProp$1y=Object.defineProperty,__defNormalProp$1y=(obj,key,value)=>key in obj?__defProp$1y(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1y=(obj,key,value)=>__defNormalProp$1y(obj,typeof key!="symbol"?key+"":key,value);Logger("EmbodimentSettings");class EmbodimentSettings{constructor(agentId){__publicField$1y(this,"_embodiments"),__publicField$1y(this,"_ready",!1),this.init(agentId)}async init(agentId){const agentDataConnector=ConnectorService.getAgentDataConnector();this._embodiments=await agentDataConnector.getAgentEmbodiments(agentId).catch(error=>[]),this._ready=!0}ready(maxWait=1e4){return new Promise((resolve,reject)=>{const interval=setInterval(()=>{this._ready&&(clearInterval(interval),resolve(!0)),maxWait-=100},100);setTimeout(()=>{clearInterval(interval),reject(!1)},maxWait)})}get(embodimentType,key){if(!this._embodiments)return;const _embodiment=this._embodiments.find(embodiment=>embodiment.type?.toLowerCase()===embodimentType.toLowerCase());return key?_embodiment?.properties?.[key]:_embodiment?.properties}}var __defProp$1x=Object.defineProperty,__defNormalProp$1x=(obj,key,value)=>key in obj?__defProp$1x(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1x=(obj,key,value)=>__defNormalProp$1x(obj,typeof key!="symbol"?key+"":key,value);Logger("AgentSettings");class AgentSettings{constructor(agentId){__publicField$1x(this,"_settings"),__publicField$1x(this,"embodiments"),__publicField$1x(this,"_ready",!1),agentId&&this.init(agentId)}async init(agentId){this.embodiments=new EmbodimentSettings(agentId);const agentDataConnector=ConnectorService.getAgentDataConnector();this._settings=await agentDataConnector.getAgentSettings(agentId).catch(e=>{})||{},this._ready=!0}ready(maxWait=1e4){return new Promise((resolve,reject)=>{const interval=setInterval(()=>{this._ready&&(clearInterval(interval),resolve(!0)),maxWait-=100},100);setTimeout(()=>{clearInterval(interval),reject(!1)},maxWait)})}get(key){return this._settings?.[key]||""}set(key,value){this._settings[key]=value}has(key){return this._settings[key]}}var __defProp$1w=Object.defineProperty,__defNormalProp$1w=(obj,key,value)=>key in obj?__defProp$1w(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1w=(obj,key,value)=>__defNormalProp$1w(obj,typeof key!="symbol"?key+"":key,value);class AgentProcess{constructor(agentData,agentVersion){this.agentData=agentData,this.agentVersion=agentVersion,__publicField$1w(this,"agent"),__publicField$1w(this,"_loadPromise"),this.initAgent(agentData,agentVersion)}async initAgent(agentData,agentVersion){let data,agentId;if(typeof agentData=="object")data=agentData,data.components&&data.connections&&(data={data,version:"1.0"}),agentId=data.data.id||"tmp-"+uid();else{const jsonRegex=/^{.*}$/g,jsonData=agentData.match(jsonRegex)?.[0],idRegex=/^[a-zA-Z0-9\-]+$/g;agentId=agentData.match(idRegex)?.[0],agentId&&(data=await ConnectorService.getAgentDataConnector().getAgentData(agentId,agentVersion)),!data&&jsonData&&(data=JSON.parse(jsonData),agentId=data.id||"tmp-"+uid(),data.components&&data.connections&&(data={data,version:"1.0"}))}const agentSettings=new AgentSettings(agentId);this.agent=new Agent(agentId,data,agentSettings)}async ready(){return this._loadPromise?this._loadPromise:this._loadPromise=new Promise(resolve=>{let maxWait=1e4;const itv=setInterval(()=>{this.agent&&(clearInterval(itv),resolve(!0)),maxWait-=100,maxWait<=0&&(clearInterval(itv),resolve(!1))},100)})}static load(agentData,agentVersion){return new AgentProcess(agentData,agentVersion)}async run(reqConfig,callback){if(await this.ready(),!this.agent)throw new Error("Failed to load agent");let request=this.parseReqConfig(reqConfig);this.agent.setRequest(request),typeof callback=="function"&&this.agent.setCallback(callback);const pathMatches=request.path.match(/(^\/v[0-9]+\.[0-9]+?)?(\/api\/(.+)?)/);if(!pathMatches||!pathMatches[2])return{status:404,data:{error:"Endpoint not found"}};const endpointPath=pathMatches[2],input=request.method=="GET"?request.query:request.body;return{data:await this.agent.process(endpointPath,input).catch(error=>({error:error.message}))}}reset(){this.initAgent(this.agentData)}parseReqConfig(reqConfig){return reqConfig instanceof AgentRequest?reqConfig:Array.isArray(reqConfig)?this.parseCLI(reqConfig):new AgentRequest(reqConfig)}parseCLI(argList){const cliConnector=ConnectorService.getCLIConnector(),methods=["get","post","put","delete","patch","head","options"],cli=cliConnector.parse(argList,["endpoint","post","get","put","delete","patch","head","options","headers","session"]),usedMethod=methods.find(method=>cli[method]),req=new AgentRequest;switch(req.method=usedMethod?.toUpperCase()||"GET",req.body={},req.query={},usedMethod){case"get":case"delete":case"head":case"options":req.query=cli[usedMethod];break;case"post":case"put":case"patch":req.body=cli[usedMethod];break}req.path=`/api/${cli.endpoint}`,req.params=cli.endpoint?.split("/"),req.headers=cli.headers||{};for(let key in req.headers)req.headers[key.toLowerCase()]=req.headers[key],delete req.headers[key];if(req.sessionID=cli.session||uid(),req.files=[],req.body)for(let entry in req.body){let value=req.body[entry];const filePath=path.join(process.cwd(),value),fileName=path.basename(filePath);if(fs__default.existsSync(filePath))try{const fileBuffer=fs__default.readFileSync(filePath),ext=fileName.split(".").pop(),fileObj={fieldname:entry,originalname:fileName,buffer:fileBuffer,mimetype:mime.getType(ext)||"application/octet-stream"};delete req.body[entry],req.files.push(fileObj),FileType.fileTypeFromBuffer(fileBuffer).then(fileType=>{fileType&&(fileObj.mimetype=fileType.mime)})}catch(error){console.warn("Coud not read file",filePath,error.message)}}return req}async post(path2,input,headers){return this.run({method:"POST",path:path2,body:input||{},headers})}async get(path2,query,headers){return this.run({method:"GET",path:path2,query,headers})}async readDebugState(stateId,reqConfig){if(await this.ready(),!this.agent)throw new Error("Failed to load agent");let request=this.parseReqConfig(reqConfig);return this.agent.setRequest(request),await this.agent.agentRuntime.ready(),this.agent.agentRuntime.readState(stateId,!0)}}var __defProp$1v=Object.defineProperty,__defNormalProp$1v=(obj,key,value)=>key in obj?__defProp$1v(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1v=(obj,key,value)=>__defNormalProp$1v(obj,typeof key!="symbol"?key+"":key,value);const ACLHashAlgo={none:source=>source,xxh3:source=>{const h64=xxhash.h64();return source?h64.update(source.toString()).digest().toString(16):null}};class ACL{constructor(acl){__publicField$1v(this,"hashAlgorithm"),__publicField$1v(this,"entries"),__publicField$1v(this,"migrated"),typeof acl=="string"?this.deserializeACL(acl):(this.hashAlgorithm=acl?.hashAlgorithm,this.entries=acl?.entries?JSON.parse(JSON.stringify(acl?.entries)):{},this.migrated=acl?.migrated),this.hashAlgorithm||(this.hashAlgorithm="xxh3"),this.entries||(this.entries={})}get ACL(){return{hashAlgorithm:this.hashAlgorithm,entries:JSON.parse(JSON.stringify(this.entries)),migrated:this.migrated}}get serializedACL(){return this.serializeACL(this)}static from(acl){return new ACL(acl)}checkExactAccess(acRequest){if(!this?.entries)return!1;const role=this?.entries[acRequest.candidate.role];if(!role)return!1;let entryId=acRequest.candidate.id;if(!ACLHashAlgo[this.hashAlgorithm])throw new Error(`Hash algorithm ${this.hashAlgorithm} not supported`);entryId=ACLHashAlgo[this.hashAlgorithm](entryId);const access=role[entryId];return access?(Array.isArray(acRequest.level)?acRequest.level:[acRequest.level]).every(level=>access.includes(level)):!1}addPublicAccess(level){if(this?.entries[TAccessRole.Public]||(this.entries[TAccessRole.Public]={}),!ACLHashAlgo[this.hashAlgorithm])throw new Error(`Hash algorithm ${this.hashAlgorithm} not supported`);const ownerId=TAccessRole.Public,hashedOwner=ACLHashAlgo[this.hashAlgorithm](ownerId);this?.entries[TAccessRole.Public][hashedOwner]||(this.entries[TAccessRole.Public][hashedOwner]=[]);const curLevel=this.entries[TAccessRole.Public][hashedOwner];return this.entries[TAccessRole.Public][hashedOwner]=[...curLevel,...level],this}removePublicAccess(level){if(!this?.entries[TAccessRole.Public])return this;const ownerId=TAccessRole.Public,hashedOwner=ACLHashAlgo[this.hashAlgorithm](ownerId),curLevel=this[TAccessRole.Public][hashedOwner];return this[TAccessRole.Public][hashedOwner]=curLevel.filter(l=>!level.includes(l)),this}addAccess(role,ownerId,level){if(role===TAccessRole.Public)throw new Error("Adding public access using addAccess method is not allowed. Use addPublicAccess method instead.");const _level=Array.isArray(level)?level:[level];if(this?.entries[role]||(this.entries[role]={}),!ACLHashAlgo[this.hashAlgorithm])throw new Error(`Hash algorithm ${this.hashAlgorithm} not supported`);const hashedOwner=ACLHashAlgo[this.hashAlgorithm](ownerId);if(!hashedOwner)throw new Error(`Invalid ownerId: ${role}:${ownerId}`);this?.entries[role][hashedOwner]||(this.entries[role][hashedOwner]=[]);const curLevel=this.entries[role][hashedOwner];return this.entries[role][hashedOwner]=[...curLevel,..._level],this}static addAccess(role,ownerId,level){return ACL.from().addAccess(role,ownerId,level)}removeAccess(role,ownerId,level){const _level=Array.isArray(level)?level:[level];if(!this[role])return this;if(!this[role][ownerId])return this;const curLevel=this[role][ownerId];return this[role][ownerId]=curLevel.filter(l=>!_level.includes(l)),this}serializeACL(tacl){let compressed="";if(tacl.hashAlgorithm&&(compressed+=`h:${tacl.hashAlgorithm}|`),tacl.entries)for(const[role,entries]of Object.entries(tacl.entries)){const roleShort=RoleMap[role],entriesArray=[];for(const[hashedOwnerKey,accessLevels]of Object.entries(entries||{}))if(accessLevels){const accessLevelsShort=accessLevels.map(level=>LevelMap[level]).join("");entriesArray.push(`${hashedOwnerKey}/${accessLevelsShort}`)}entriesArray.length>0&&(compressed+=`${roleShort}:${entriesArray.join(",")}|`)}return compressed.endsWith("|")&&(compressed=compressed.slice(0,-1)),compressed}deserializeACL(compressed){const parts=compressed.split("|");this.hashAlgorithm="",this.entries={};for(const part of parts)if(part.startsWith("h:"))this.hashAlgorithm=part.substring(2);else{const[roleShort,entries]=part.split(":"),role=ReverseRoleMap[roleShort];if(role){const entriesObj={},entriesArray=entries.split(",");for(const entry of entriesArray){const[hashedOwnerKey,accessLevelsShort]=entry.split("/"),accessLevels=accessLevelsShort.split("").map(short=>ReverseLevelMap[short]);entriesObj[hashedOwnerKey]=accessLevels}this.entries[role]=entriesObj}}}}const console$s=Logger("SecureConnector");class SecureConnector extends Connector{async start(){console$s.info(`Starting ${this.name} connector ...`)}async stop(){console$s.info(`Stopping ${this.name} connector ...`)}async hasAccess(acRequest){const aclHelper=await this.getResourceACL(acRequest.resourceId,acRequest.candidate).catch(error=>(console$s.error(`Error getting ACL for ${acRequest.resourceId}: ${error}`),null));if(!aclHelper)return!1;if(aclHelper.checkExactAccess(acRequest))return!0;const ownerRequest=AccessRequest.clone(acRequest).setLevel(TAccessLevel.Owner);if(aclHelper.checkExactAccess(ownerRequest))return!0;const publicRequest=AccessRequest.clone(acRequest).setCandidate(AccessCandidate.public());if(aclHelper.checkExactAccess(publicRequest))return!0;const teamId=await ConnectorService.getAccountConnector().getCandidateTeam(acRequest.candidate),teamRequest=AccessRequest.clone(acRequest).setCandidate(AccessCandidate.team(teamId));if(aclHelper.checkExactAccess(teamRequest))return!0;const teamOwnerRequest=AccessRequest.clone(teamRequest).setLevel(TAccessLevel.Owner);return!!aclHelper.checkExactAccess(teamOwnerRequest)}async getAccessTicket(resourceId,request){const sysAcRequest=AccessRequest.clone(request).resource(resourceId);return{request,access:await this.hasAccess(sysAcRequest)?TAccessResult.Granted:TAccessResult.Denied}}static AccessControl(target,propertyKey,descriptor){const originalMethod=descriptor.value;return descriptor.value=async function(...args){const[acRequest,resourceId]=args;if(resourceId!==void 0&&(await this.getAccessTicket(resourceId,acRequest)).access!==TAccessResult.Granted)throw console$s.error(`Access denied for ${acRequest.candidate.id} on ${resourceId}`),new ACLAccessDeniedError("Access Denied");return originalMethod.apply(this,args)},descriptor}}class StorageConnector extends SecureConnector{requester(candidate){return{write:async(resourceId,value,acl,metadata)=>await this.write(candidate.writeRequest,resourceId,value,acl,metadata),read:async resourceId=>await this.read(candidate.readRequest,resourceId),delete:async resourceId=>{await this.delete(candidate.readRequest,resourceId)},exists:async resourceId=>await this.exists(candidate.readRequest,resourceId),getMetadata:async resourceId=>await this.getMetadata(candidate.readRequest,resourceId),setMetadata:async(resourceId,metadata)=>{await this.setMetadata(candidate.writeRequest,resourceId,metadata)},getACL:async resourceId=>await this.getACL(candidate.readRequest,resourceId),setACL:async(resourceId,acl)=>await this.setACL(candidate.writeRequest,resourceId,acl),expire:async(resourceId,ttl)=>await this.expire(candidate.writeRequest,resourceId,ttl)}}}class CacheConnector extends SecureConnector{requester(candidate){return{get:async key=>await this.get(candidate.readRequest,key),set:async(key,data,acl,metadata,ttl)=>await this.set(candidate.writeRequest,key,data,acl,metadata,ttl),delete:async key=>{await this.delete(candidate.writeRequest,key)},exists:async key=>await this.exists(candidate.readRequest,key),getMetadata:async key=>await this.getMetadata(candidate.readRequest,key),setMetadata:async(key,metadata)=>{await this.setMetadata(candidate.writeRequest,key,metadata)},updateTTL:async(key,ttl)=>{await this.updateTTL(candidate.writeRequest,key,ttl)},getTTL:async key=>await this.getTTL(candidate.readRequest,key),getACL:async key=>await this.getACL(candidate.readRequest,key),setACL:async(key,acl)=>{await this.setACL(candidate.writeRequest,key,acl)}}}}var __defProp$1u=Object.defineProperty,__defNormalProp$1u=(obj,key,value)=>key in obj?__defProp$1u(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1u=(obj,key,value)=>__defNormalProp$1u(obj,key+"",value);class JSONContentHelper{constructor(dataString){this.dataString=dataString,__publicField$1u(this,"_current"),this._current=dataString}get result(){return this._current}static create(dataString){return new JSONContentHelper(dataString)}tryParse(){const strInput=this._current;if(!isValidString(strInput)||isDigits(strInput)||isSafeNumber(strInput))return strInput;let str=strInput.trim();if(str.startsWith("{")&&str.endsWith("}")||str.startsWith("[")&&str.endsWith("]"))try{return JSON.parse(str)}catch{try{const repairedJson=jsonrepair(str);return JSON.parse(repairedJson)}catch{}}if(str=(this.extractJsonFromString(strInput)||strInput).trim(),isDigits(str)&&!isSafeNumber(str)||!str.startsWith("{")&&!str.startsWith("["))return str;try{return JSON.parse(str)}catch{try{const repairedJson=jsonrepair(str);return JSON.parse(repairedJson)}catch{return strInput}}}tryFullParse(){const str=this._current;if(!str||isDigits(str)&&!isSafeNumber(str)||!str.startsWith("{")&&!str.startsWith("["))return str;try{return JSON.parse(str)}catch{try{return JSON.parse(jsonrepair(str))}catch(e2){return console.warn("Error on parseJson: ",e2.toString()),console.warn(" Tried to parse: ",str),{result:str,error:e2.toString()}}}}extractJsonFromString(str){try{const regex=/(\{.*\})/s;return str.match(regex)?.[1]}catch{return null}}}function JSONContent(dataString){return JSONContentHelper.create(dataString)}var __defProp$1t=Object.defineProperty,__defNormalProp$1t=(obj,key,value)=>key in obj?__defProp$1t(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1t=(obj,key,value)=>__defNormalProp$1t(obj,typeof key!="symbol"?key+"":key,value);const _SmythFS=class _SmythFS2{constructor(storage,cache){if(this.storage=storage,this.cache=cache,__publicField$1t(this,"hash"),!ConnectorService.ready)throw new Error("SRE not available");this.hash=_SmythFS2.generateInstanceHash(this.storage.name,this.cache.name)}static generateInstanceHash(storageName,cacheName){const instanceProps=`${storageName}:${cacheName}`;return crypto$1.createHash("sha256").update(instanceProps).digest("hex").substring(0,6)}static get Instance(){return _SmythFS2.getInstance()}static getInstance(storageProvider="",cacheProvider=""){const storage=storageProvider instanceof StorageConnector?storageProvider:ConnectorService.getStorageConnector(storageProvider),cache=cacheProvider instanceof CacheConnector?cacheProvider:ConnectorService.getCacheConnector(cacheProvider),hash=_SmythFS2.generateInstanceHash(storage.name,cache.name);if(_SmythFS2.instances[hash])return _SmythFS2.instances[hash];const instance=new _SmythFS2(storage,cache),router=ConnectorService.getRouterConnector();return router&&router?.get instanceof Function&&(router.get(`/_temp/${hash}/:uid`,instance.serveTempContent.bind(instance)),router.get(`/storage/${hash}/:file_id`,instance.serveResource.bind(instance))),_SmythFS2.instances[hash]=instance,instance}getBaseUri(candidate){return`smythfs://${candidate.id}.${candidate.role}`}async read(uri,candidate){const smythURI=await this.URIParser(uri);if(!smythURI)throw new Error("Invalid Resource URI");if(candidate=candidate||smythURI.defaultCandidate,!await ConnectorService.getAccountConnector().isTeamMember(smythURI.team,candidate))throw new Error("Access Denied");const resourceId=`teams/${smythURI.team}${smythURI.path}`,_candidate=candidate instanceof AccessCandidate?candidate:new AccessCandidate(candidate),data=await this.storage.requester(_candidate).read(resourceId);return data?this.toBuffer(data):null}async getMetadata(uri,candidate){const smythURI=await this.URIParser(uri);if(!smythURI)throw new Error("Invalid Resource URI");if(candidate=candidate||smythURI.defaultCandidate,!await ConnectorService.getAccountConnector().isTeamMember(smythURI.team,candidate))throw new Error("Access Denied");const resourceId=`teams/${smythURI.team}${smythURI.path}`,_candidate=candidate instanceof AccessCandidate?candidate:new AccessCandidate(candidate);return await this.storage.requester(_candidate).getMetadata(resourceId)}async write(uri,data,candidate,metadata,ttl){const smythURI=await this.URIParser(uri);if(!smythURI)throw new Error("Invalid Resource URI");if(candidate=candidate||smythURI.defaultCandidate,!await ConnectorService.getAccountConnector().isTeamMember(smythURI.team,candidate))throw new Error("Access Denied");const resourceId=`teams/${smythURI.team}${smythURI.path}`,_candidate=candidate instanceof AccessCandidate?candidate:new AccessCandidate(candidate);let acl;if(smythURI.team&&smythURI.team!==DEFAULT_TEAM_ID&&(acl=new ACL().addAccess(TAccessRole.Team,smythURI.team,TAccessLevel.Read).ACL),metadata||(metadata={}),!metadata?.ContentType&&(metadata.ContentType=await getMimeType(data),!metadata.ContentType)){const ext=uri.split(".").pop();ext&&(metadata.ContentType=mime.getType(ext)||"application/octet-stream")}await this.storage.requester(_candidate).write(resourceId,data,acl,metadata),ttl&&await this.storage.requester(_candidate).expire(resourceId,ttl)}async delete(uri,candidate){const smythURI=await this.URIParser(uri);if(!smythURI)throw new Error("Invalid Resource URI");if(candidate=candidate||smythURI.defaultCandidate,!await ConnectorService.getAccountConnector().isTeamMember(smythURI.team,candidate))throw new Error("Access Denied");const resourceId=`teams/${smythURI.team}${smythURI.path}`,_candidate=candidate instanceof AccessCandidate?candidate:new AccessCandidate(candidate);await this.storage.requester(_candidate).delete(resourceId)}async exists(uri,candidate){const smythURI=await this.URIParser(uri);if(!smythURI)throw new Error("Invalid Resource URI");if(candidate=candidate||smythURI.defaultCandidate,!await ConnectorService.getAccountConnector().isTeamMember(smythURI.team,candidate))throw new Error("Access Denied");const resourceId=`teams/${smythURI.team}${smythURI.path}`,_candidate=candidate instanceof AccessCandidate?candidate:new AccessCandidate(candidate);return await this.storage.requester(_candidate).exists(resourceId)}async genTempUrl(uri,candidate,ttlSeconds=3600){const smythURI=await this.URIParser(uri);if(!smythURI)throw new Error("Invalid Resource URI");if(candidate=candidate||smythURI.defaultCandidate,!await ConnectorService.getAccountConnector().isTeamMember(smythURI.team,candidate))throw new Error("Access Denied");if(!await this.exists(uri,candidate))throw new Error("Resource does not exist");const _candidate=candidate instanceof AccessCandidate?candidate:new AccessCandidate(candidate),resourceId=`teams/${smythURI.team}${smythURI.path}`,resourceMetadata=await this.storage.requester(_candidate).getMetadata(resourceId),uid2=crypto$1.randomUUID(),tempUserCandidate=AccessCandidate.user(`system-${uid2}`);return await this.cache.requester(tempUserCandidate).set(`pub_url:${uid2}`,JSON.stringify({accessCandidate:_candidate,uri,contentType:resourceMetadata?.ContentType}),void 0,void 0,ttlSeconds),`${ConnectorService.getRouterConnector().baseUrl}/_temp/${this.hash}/${uid2}`}async destroyTempUrl(url,{delResource}={delResource:!1}){const tempPath=url.split("/_temp/")[1];if(!tempPath)throw new Error("Invalid Temp URL format");const uid2=tempPath.split("/")[1]?.split("?")[0];if(!uid2)throw new Error("Invalid Temp URL format");let cacheVal=await this.cache.requester(AccessCandidate.user(`system-${uid2}`)).get(`pub_url:${uid2}`);if(!cacheVal)throw new Error("Invalid Temp URL");cacheVal=JSONContentHelper.create(cacheVal).tryParse(),await this.cache.requester(AccessCandidate.user(`system-${uid2}`)).delete(`pub_url:${uid2}`),delResource&&await this.delete(cacheVal.uri,AccessCandidate.clone(cacheVal.accessCandidate))}async serveTempContent(req,res){try{const{uid:uid2}=req.params;let cacheVal=await this.cache.requester(AccessCandidate.user(`system-${uid2}`)).get(`pub_url:${uid2}`);if(!cacheVal){res.writeHead(404,{"Content-Type":"text/plain"}),res.end("Invalid Temp URL");return}cacheVal=JSONContentHelper.create(cacheVal).tryParse();const content=await this.read(cacheVal.uri,AccessCandidate.clone(cacheVal.accessCandidate)),contentBuffer=Buffer.isBuffer(content)?content:Buffer.from(content,"binary"),contentType=cacheVal.contentType||"application/octet-stream";res.writeHead(200,{"Content-Type":contentType,"Content-Disposition":"inline","Content-Length":contentBuffer.length}),res.end(contentBuffer)}catch(error){console.error("Error serving temp content:",error),res.writeHead(500,{"Content-Type":"text/plain"}),res.end("Internal Server Error")}}async genResourceUrl(uri,candidate){const smythURI=await this.URIParser(uri);if(!smythURI)throw new Error("Invalid Resource URI");if(candidate=candidate||smythURI.defaultCandidate,!await ConnectorService.getAccountConnector().isTeamMember(smythURI.team,candidate))throw new Error("Access Denied");if(!await this.exists(uri,candidate))throw new Error("Resource does not exist");const _candidate=candidate instanceof AccessCandidate?candidate:new AccessCandidate(candidate);if(_candidate.role!==TAccessRole.Agent)throw new Error("Only agents can generate resource urls");const agentId=_candidate.id,resourceId=`teams/${smythURI.team}${smythURI.path}`,resourceMetadata=await this.storage.requester(_candidate).getMetadata(resourceId),uid2=crypto$1.randomUUID(),tempUserCandidate=AccessCandidate.user(`system-${uid2}`);await this.cache.requester(tempUserCandidate).set(`storage_url-${uid2}`,JSON.stringify({accessCandidate:_candidate,uri,contentType:resourceMetadata?.ContentType}),void 0,void 0);const contentType=resourceMetadata?.ContentType,ext=contentType?mime.getExtension(contentType):void 0,agentDataConnector=ConnectorService.getAgentDataConnector(),baseUrl=ConnectorService.getRouterConnector().baseUrl;return`${agentDataConnector.getAgentConfig(agentId)?.agentStageDomain?`https://${agentDataConnector.getAgentConfig(agentId).agentStageDomain}`:baseUrl}/storage/${this.hash}/${uid2}${ext?`.${ext}`:""}`}async destroyResourceUrl(url,{delResource}={delResource:!1}){}async serveResource(req,res){try{const{file_id}=req.params,[uid2,extention]=file_id.split(".");let cacheVal=await this.cache.requester(AccessCandidate.user(`system-${uid2}`)).get(`storage_url-${uid2}`);if(!cacheVal){res.writeHead(404,{"Content-Type":"text/plain"}),res.end("Invalid Resource URL");return}cacheVal=JSONContentHelper.create(cacheVal).tryParse();const content=await this.read(cacheVal.uri,AccessCandidate.clone(cacheVal.accessCandidate)),contentBuffer=Buffer.isBuffer(content)?content:Buffer.from(content,"binary"),contentType=cacheVal.contentType||"application/octet-stream";res.writeHead(200,{"Content-Type":contentType,"Content-Disposition":"inline","Content-Length":contentBuffer.length}),res.end(contentBuffer)}catch(error){console.error("Error serving storage resource content:",error),res.writeHead(500,{"Content-Type":"text/plain"}),res.end("Internal Server Error")}}async URIParser(uri){const parts=uri.split("://");if(parts.length!==2||parts[0].toLowerCase()!=="smythfs")return;const parsed=this.CaseSensitiveURL(`http://${parts[1]}`),tld=parsed.hostname.split(".").pop();if(tld!=="team"&&tld!=="user"&&tld!=="agent"&&tld!=="smyth")throw new Error("Invalid Resource URI");let team=tld==="team"?parsed.hostname.replace(`.${tld}`,""):void 0;const user=tld==="user"?parsed.hostname.replace(`.${tld}`,""):void 0,agent=tld==="agent"?parsed.hostname.replace(`.${tld}`,""):void 0,smyth=tld==="smyth"?parsed.hostname.replace(`.${tld}`,""):void 0;let basePath="";if(!team){let candidate;user?(candidate=AccessCandidate.user(user),basePath=".user/"+user):agent&&(candidate=AccessCandidate.agent(agent),basePath=".agent/"+agent),candidate&&(team=await ConnectorService.getAccountConnector().getCandidateTeam(candidate))}let defaultCandidate;return team?defaultCandidate=AccessCandidate.team(team):user?defaultCandidate=AccessCandidate.user(user):agent&&(defaultCandidate=AccessCandidate.agent(agent)),{hash:parsed.hash,team,user,agent,smyth,defaultCandidate,path:basePath+parsed.pathname}}CaseSensitiveURL(urlString){const parts=urlString.split("://");if(parts.length!==2)return null;const afterProtocol=parts[1],hostnameEnd=Math.min(...[afterProtocol.indexOf("/"),afterProtocol.indexOf("?"),afterProtocol.indexOf("#"),afterProtocol.length].filter(i=>i>=0)),originalHostnamePart=afterProtocol.substring(0,hostnameEnd),[originalHostname,originalPort]=originalHostnamePart.split(":"),parsed=new URL(urlString);return{protocol:parsed.protocol,hostname:originalHostname,port:parsed.port,pathname:parsed.pathname,search:parsed.search,searchParams:parsed.searchParams,hash:parsed.hash,href:parsed.href,origin:parsed.origin,host:originalHostname+(parsed.port?`:${parsed.port}`:""),originalPort:originalPort||null}}async toBuffer(data){if(Buffer.isBuffer(data))return data;if(typeof data=="string")return Buffer.from(data,"utf-8");if(data instanceof Uint8Array)return Buffer.from(data);if(data instanceof Readable)return new Promise((resolve,reject)=>{const chunks=[];data.on("data",chunk=>{chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk))}),data.on("end",()=>{resolve(Buffer.concat(chunks))}),data.on("error",err=>{reject(err)})});throw new Error("Unsupported data type")}};__publicField$1t(_SmythFS,"instances",{});let SmythFS=_SmythFS;var __defProp$1s=Object.defineProperty,__defNormalProp$1s=(obj,key,value)=>key in obj?__defProp$1s(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1s=(obj,key,value)=>__defNormalProp$1s(obj,typeof key!="symbol"?key+"":key,value);class BinaryInput{constructor(data,_name,mimetype,candidate){this._name=_name,this.mimetype=mimetype,this.candidate=candidate,__publicField$1s(this,"size"),__publicField$1s(this,"url"),__publicField$1s(this,"_ready"),__publicField$1s(this,"_readyPromise"),__publicField$1s(this,"_source"),__publicField$1s(this,"_uploading",!1),_name||(_name=uid()),this._name=_name,this.load(data,_name,mimetype,candidate)}async ready(){return this._ready?!0:(this._readyPromise||(this._readyPromise=new Promise(resolve=>{const interval=setInterval(()=>{this._ready&&(clearInterval(interval),resolve(!0))},100)})),this._readyPromise)}async load(data,name,mimetype,candidate){const ext=name.split(".")?.length>1?name.split(".").pop():"";if(this.mimetype=mimetype||mime.getType(ext)||"",this.url="",typeof data=="object"&&data.url&&data.mimetype&&data.size){this.mimetype=data.mimetype,this.size=data.size,this.url=data.url;const ext2=mime.getExtension(this.mimetype);this._name.endsWith(`.${ext2}`)||(this._name+=`.${ext2}`),candidate?this._source=await SmythFS.Instance.read(this.url,candidate).finally(()=>{this._ready=!0}):this._ready=!0;return}if(typeof data=="string"&&data.startsWith("smythfs://")){if(this.url=data,candidate)try{this._source=await SmythFS.Instance.read(this.url,candidate),this.mimetype=await getMimeType(this._source),this.size=this._source.byteLength,this.mimetype||(this.mimetype=mime.getType(this.url)||mime.getType(this._name)||"");const ext2=mime.getExtension(this.mimetype);this._name.endsWith(`.${ext2}`)||(this._name+=`.${ext2}`)}finally{this._ready=!0}else this._ready=!0;return}if(isUrl(data)){try{const response=await axios({method:"get",url:data,responseType:"arraybuffer"});this.size=response.data.byteLength,this._source=Buffer.from(response.data,"binary");let mimetype2=response.headers?.["content-type"]||"";const urlPath=new URL(data).pathname;let extension=urlPath.split(".")?.length>1?urlPath.split(".").pop():"";(!mimetype2||mimetype2.startsWith("binary/octet-stream"))&&(mimetype2=extension?mime.getType(extension):""),mimetype2||(mimetype2=(await fileTypeFromBuffer(this._source))?.mime||""),this.mimetype=mimetype2,extension=extension||mime.getExtension(this.mimetype),this._name.endsWith(`.${extension}`)||(this._name+=`.${extension}`)}catch(error){console.error("Error loading binary data from url:",data.url,error)}this._ready=!0;return}const base64FileInfo=await getBase64FileInfo(data);if(base64FileInfo){this.mimetype||(this.mimetype=base64FileInfo.mimetype),this.size=base64FileInfo.size,this._source=Buffer.from(base64FileInfo.data,"base64");const ext2=mime.getExtension(this.mimetype);this._name.endsWith(`.${ext2}`)||(this._name+=`.${ext2}`),this._ready=!0;return}if(typeof data=="string"){this._source=Buffer.from(data),this.size=data.length,this.mimetype="text/plain",this._name.endsWith(".txt")||(this._name+=".txt"),this._ready=!0;return}if(Buffer.isBuffer(data)){this._source=data,this.size=getSizeFromBinary(data),this.mimetype||(this.mimetype=await getMimeType(data));const ext2=mime.getExtension(this.mimetype);this._name.endsWith(`.${ext2}`)||(this._name+=`.${ext2}`),this._ready=!0;return}if(data instanceof Blob){this._source=Buffer.from(await data.arrayBuffer()),this.size=data.size,this.mimetype=data.type,this._ready=!0;return}}async getUrlInfo(url){try{const response=await axios.get(url),contentType=response.headers["content-type"],contentLength=response.headers["content-length"];return{contentType,contentLength}}catch{return{contentType:"",contentLength:0}}}static from(data,name,mimetype,candidate){return data instanceof BinaryInput?data:new BinaryInput(data,name,mimetype,candidate)}async upload(candidate,ttl){if(await this.ready(),!this._uploading)try{if(this._uploading=!0,this.url)this._uploading=!1;else{const teamId=await ConnectorService.getAccountConnector().getCandidateTeam(candidate);this.url=`smythfs://${teamId}.team/${candidate.id}/_temp/${this._name}`,await SmythFS.Instance.write(this.url,this._source,candidate,void 0,ttl),this._uploading=!1}}catch(error){console.error("Error uploading binary data:",error),this._uploading=!1}}async getJsonData(candidate,ttl){return await this.upload(candidate,ttl),{mimetype:this.mimetype,size:this.size,url:this.url,name:this._name}}async readData(candidate){if(await this.ready(),!this.url)throw new Error("Binary data not ready");return await SmythFS.Instance.read(this.url,candidate)}async getName(){return await this.ready(),this._name}async getBuffer(){return await this.ready(),this._source}async getReadStream(){return await this.ready(),Readable.from(this._source)}}var TLLMCredentials=(TLLMCredentials2=>(TLLMCredentials2.Vault="vault",TLLMCredentials2.Internal="internal",TLLMCredentials2.BedrockVault="bedrock_vault",TLLMCredentials2.VertexAIVault="vertexai_vault",TLLMCredentials2.None="none",TLLMCredentials2))(TLLMCredentials||{});const BuiltinLLMProviders={Echo:"Echo",OpenAI:"OpenAI",DeepSeek:"DeepSeek",GoogleAI:"GoogleAI",Anthropic:"Anthropic",Groq:"Groq",TogetherAI:"TogetherAI",Bedrock:"Bedrock",VertexAI:"VertexAI",xAI:"xAI",Perplexity:"Perplexity"},TLLMProvider=BuiltinLLMProviders;var TLLMMessageRole=(TLLMMessageRole2=>(TLLMMessageRole2.User="user",TLLMMessageRole2.Assistant="assistant",TLLMMessageRole2.System="system",TLLMMessageRole2.Model="model",TLLMMessageRole2.Tool="tool",TLLMMessageRole2.Function="function",TLLMMessageRole2))(TLLMMessageRole||{}),APIKeySource=(APIKeySource2=>(APIKeySource2.Smyth="smyth-managed",APIKeySource2.User="user-managed",APIKeySource2.Custom="custom",APIKeySource2))(APIKeySource||{}),TLLMEvent=(TLLMEvent2=>(TLLMEvent2.Data="data",TLLMEvent2.Content="content",TLLMEvent2.Thinking="thinking",TLLMEvent2.End="end",TLLMEvent2.Error="error",TLLMEvent2.ToolInfo="toolInfo",TLLMEvent2.ToolCall="toolCall",TLLMEvent2.ToolResult="toolResult",TLLMEvent2.Usage="usage",TLLMEvent2.Interrupted="interrupted",TLLMEvent2))(TLLMEvent||{});function isAgent(agent){return typeof agent=="object"&&agent.id&&typeof agent.callComponent=="function"}var __defProp$1r=Object.defineProperty,__defNormalProp$1r=(obj,key,value)=>key in obj?__defProp$1r(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1r=(obj,key,value)=>__defNormalProp$1r(obj,typeof key!="symbol"?key+"":key,value);const console$r=Logger("LLMInference");let LLMInference$1=class LLMInference{constructor(){__publicField$1r(this,"model"),__publicField$1r(this,"llmConnector"),__publicField$1r(this,"modelProviderReq"),__publicField$1r(this,"teamId")}static async getInstance(model,candidate){const modelsProvider=ConnectorService.getModelsProviderConnector();if(!modelsProvider.valid)throw new Error("Model provider Not available, cannot create LLM instance");const teamId=await ConnectorService.getAccountConnector().requester(candidate).getTeam(),llmInference=new LLMInference;llmInference.teamId=teamId,llmInference.modelProviderReq=modelsProvider.requester(candidate);const llmProvider=await llmInference.modelProviderReq.getProvider(model);return llmProvider&&(llmInference.llmConnector=ConnectorService.getLLMConnector(llmProvider)),llmInference.llmConnector||console$r.error(`Model ${model} unavailable for team ${teamId}`),llmInference.model=model,llmInference}static user(candidate){}get connector(){return this.llmConnector}async prompt({query,contextWindow,files,params}){let messages=contextWindow||[];if(query){const content=this.llmConnector.enhancePrompt(query,params);messages.push({role:TLLMMessageRole.User,content})}params.model||(params.model=this.model),params.messages=messages,params.files=files;try{let response=await this.llmConnector.requester(AccessCandidate.agent(params.agentId)).request(params);const result=this.llmConnector.postProcess(response?.content);if(result.error)throw response.finishReason!=="stop"?new Error("The model stopped before completing the response, this is usually due to output token limit reached."):new Error(result.error);return result}catch(error){throw console$r.error("Error in chatRequest: ",error),error}}async promptStream({query,contextWindow,files,params}){let messages=contextWindow||[];if(query){const content=this.llmConnector.enhancePrompt(query,params);messages.push({role:TLLMMessageRole.User,content})}params.model||(params.model=this.model),params.messages=messages,params.files=files;try{return await this.llmConnector.user(AccessCandidate.agent(params.agentId)).streamRequest(params)}catch(error){console$r.error("Error in streamRequest:",error);const dummyEmitter=new EventEmitter;return process.nextTick(()=>{dummyEmitter.emit("error",error),dummyEmitter.emit("end")}),dummyEmitter}}async imageGenRequest({query,files,params}){return params.prompt=query,this.llmConnector.user(AccessCandidate.agent(params.agentId)).imageGenRequest(params)}async imageEditRequest({query,files,params}){return params.prompt=query,params.files=files,this.llmConnector.user(AccessCandidate.agent(params.agentId)).imageEditRequest(params)}async streamRequest(params,agent){const agentId=isAgent(agent)?agent.id:agent;try{if(!params.messages||!params.messages?.length)throw new Error("Input messages are required.");const model=params.model||this.model;return await this.llmConnector.user(AccessCandidate.agent(agentId)).streamRequest({...params,model})}catch(error){console$r.error("Error in streamRequest:",error);const dummyEmitter=new EventEmitter;return process.nextTick(()=>{dummyEmitter.emit("error",error),dummyEmitter.emit("end")}),dummyEmitter}}async multimodalStreamRequest(params,fileSources,agent){const agentId=isAgent(agent)?agent.id:agent,promises=[],_fileSources=[];for(let file of fileSources){const binaryInput=BinaryInput.from(file);_fileSources.push(binaryInput),promises.push(binaryInput.upload(AccessCandidate.agent(agentId)))}await Promise.all(promises),params.fileSources=_fileSources;try{const prompt=(Array.isArray(params.messages)?params.messages.pop():{})?.content||"",model=params.model||this.model;return await this.llmConnector.user(AccessCandidate.agent(agentId)).multimodalStreamRequest(prompt,{...params,model})}catch(error){throw console$r.error("Error in multimodalRequest: ",error),error}}async multimodalStreamRequestLegacy(prompt,files,config2={},agent){const agentId=isAgent(agent)?agent.id:agent,promises=[],_files=[];for(let file of files){const binaryInput=BinaryInput.from(file);_files.push(binaryInput),promises.push(binaryInput.upload(AccessCandidate.agent(agentId)))}await Promise.all(promises);const params=config2.data;params.files=_files;try{prompt=this.llmConnector.enhancePrompt(prompt,config2);const model=params.model||this.model;return await this.llmConnector.user(AccessCandidate.agent(agentId)).multimodalStreamRequest(prompt,{...params,model})}catch(error){throw console$r.error("Error in multimodalRequest: ",error),error}}async getContextWindow(systemPrompt,_messages,maxTokens,maxOutputTokens=1024){const modelInfo=await this.modelProviderReq.getModelInfo(this.model,!0);let maxModelContext=modelInfo?.tokens,maxModelOutputTokens=modelInfo?.completionTokens||modelInfo?.tokens,maxInputContext=Math.min(maxTokens,maxModelContext),maxOutputContext=Math.min(maxOutputTokens,maxModelOutputTokens||0);maxInputContext+maxOutputContext>maxModelContext&&(maxInputContext-=maxInputContext+maxOutputContext-maxModelContext),maxInputContext<=0&&console$r.warn("Max input context is 0, returning empty context window, This usually indicates a wrong model configuration"),console$r.debug(`Context Window Configuration: Max Input Tokens: ${maxInputContext}, Max Output Tokens: ${maxOutputContext}, Max Model Tokens: ${maxModelContext}`);const systemMessage={role:"system",content:systemPrompt};let smythContextWindow=[],tokensCount=encodeChat([systemMessage],"gpt-4o").length;for(let i=_messages?.length-1;i>=0;i--){const curMessage=_messages[i];if(curMessage.role!=="system"){if(tokensCount=0,curMessage?.content&&(tokensCount+=countTokens(curMessage.content)),curMessage?.messageBlock?.content&&(tokensCount+=countTokens(curMessage.messageBlock.content)),curMessage.toolsData)for(let tool of curMessage.toolsData)tokensCount+=countTokens(tool.result);if(tokensCount>maxInputContext)break;smythContextWindow.unshift(curMessage)}}smythContextWindow.unshift(systemMessage);let modelContextWindow=[];for(let message of smythContextWindow)if(message.role&&message.content&&modelContextWindow.push({role:message.role,content:message.content}),message.messageBlock&&message.toolsData){const internal_message=this.connector.transformToolMessageBlocks({messageBlock:message?.messageBlock,toolsData:message?.toolsData});modelContextWindow.push(...internal_message)}return modelContextWindow=this.connector.getConsistentMessages(modelContextWindow),modelContextWindow}};function countTokens(content,model="gpt-4o"){try{const _stringifiedContent=typeof content=="string"?content:JSON.stringify(content);return encodeChat([{role:"user",content:_stringifiedContent}],model).length}catch(error){return console$r.warn("Error in countTokens: ",error),0}}var __defProp$1q=Object.defineProperty,__defNormalProp$1q=(obj,key,value)=>key in obj?__defProp$1q(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1q=(obj,key,value)=>__defNormalProp$1q(obj,typeof key!="symbol"?key+"":key,value);class LLMContext{constructor(llmInference,_systemPrompt="",llmContextStore){this.llmInference=llmInference,__publicField$1q(this,"_systemPrompt",""),__publicField$1q(this,"_llmContextStore"),__publicField$1q(this,"_llmCache"),__publicField$1q(this,"contextLength"),__publicField$1q(this,"_messages",[]),this._llmCache=new LLMCache(AccessCandidate.team(this.llmInference.teamId)),this.systemPrompt=_systemPrompt,llmContextStore&&(this._llmContextStore=llmContextStore,this._llmContextStore.load().then(messages=>{this._messages=messages,this._llmCache.set("messages",this._messages)}))}get systemPrompt(){return this._systemPrompt}set systemPrompt(systemPrompt){this._systemPrompt=systemPrompt,this._llmCache?.set("systemPrompt",this.systemPrompt)}get llmCache(){return this._llmCache}get messages(){return this._messages}get model(){return this.llmInference.model}push(...message){this._messages.push(...message),this._llmContextStore&&this._llmContextStore.save(this._messages),this._llmCache.set("messages",this._messages)}addUserMessage(content,message_id,metadata){const lastMessage=this._messages[this._messages.length-1];lastMessage&&(lastMessage.__smyth_data__?.next||(lastMessage.__smyth_data__.next=[]),lastMessage.__smyth_data__.next.push(message_id));const prev=lastMessage?.__smyth_data__?.message_id,next=[];this.push({role:"user",content,__smyth_data__:{message_id,...metadata,prev,next}})}addAssistantMessage(content,message_id,metadata){const lastMessage=this._messages[this._messages.length-1];lastMessage&&(lastMessage.__smyth_data__?.next||(lastMessage.__smyth_data__.next=[]),lastMessage.__smyth_data__.next.push(message_id));const prev=lastMessage?.__smyth_data__?.message_id,next=[];this.push({role:"assistant",content,__smyth_data__:{message_id,...metadata,prev,next}})}addToolMessage(messageBlock,toolsData,message_id,metadata){const lastMessage=this._messages[this._messages.length-1];lastMessage&&(lastMessage.__smyth_data__?.next||(lastMessage.__smyth_data__.next=[]),lastMessage.__smyth_data__.next.push(message_id));const prev=lastMessage?.__smyth_data__?.message_id,next=[];this.push({messageBlock,toolsData,__smyth_data__:{message_id,...metadata,prev,next}})}async getContextWindow(maxTokens,maxOutputTokens=1024){const messages=JSON.parse(JSON.stringify(this._messages));return this.llmInference.getContextWindow(this.systemPrompt,messages,maxTokens,maxOutputTokens)}}const dereferenceSchema=async(schema,root=schema)=>{if(typeof schema!="object"||schema===null)return schema;if(schema.$ref){const ref=schema.$ref,path2=ref.replace(/^#\//,"").split("/");let resolved=root;for(const segment of path2){if(resolved[segment]===void 0)throw new Error(`Could not resolve $ref: ${ref}`);resolved=resolved[segment]}return dereferenceSchema(resolved,root)}if(Array.isArray(schema))return Promise.all(schema.map(item=>dereferenceSchema(item,root)));const result={};for(const key of Object.keys(schema))result[key]=await dereferenceSchema(schema[key],root);return result};class OpenAPIParser{static mapReqMethods(paths){const methods=new Map;for(const path2 in paths){const pathData=paths[path2];for(const method in pathData){const data=pathData[method];REQUEST_METHODS.includes(method.toUpperCase())&&methods.set(data?.operationId,method)}}return methods}static mapEndpoints(paths){const operationIds=new Map;for(const path2 in paths){const pathData=paths[path2];for(const method in pathData){const data=pathData[method];REQUEST_METHODS.includes(method.toUpperCase())&&operationIds.set(data?.operationId,path2)}}return operationIds}static async yamlToJson(yamlData){const data=yaml.load(yamlData);return await dereferenceSchema(data)}static async getJson(data){try{let parsedData=data;return typeof data=="string"&&(parsedData=JSON.parse(data)),await dereferenceSchema(parsedData)}catch{try{return await OpenAPIParser.yamlToJson(data)}catch{throw new Error("Invalid OpenAPI specification or JSON data format")}}}static async getJsonFromUrl(url){const data=(await axios.get(url)).data;return OpenAPIParser.getJson(data)}static isValidOpenAPI(data){return data?.openapi&&data?.paths&&data?.servers}}const hooks={};class HookService{static register(hookName,callback){if(typeof callback!="function")throw new Error("Hook callback must be a function");hooks[hookName]||(hooks[hookName]=[]),hooks[hookName].push(callback)}static trigger(hookName,...args){hooks[hookName]&&hooks[hookName].forEach(callback=>callback(...args))}}function hook(hookName){return function(target,propertyKey,descriptor){const originalMethod=descriptor.value;return descriptor.value=function(...args){return hooks[hookName]&&hooks[hookName].forEach(callback=>{callback.apply(this,args)}),originalMethod.apply(this,args)},descriptor}}function hookAsync(hookName){return function(target,propertyKey,descriptor){const originalMethod=descriptor.value;return descriptor.value=async function(...args){return hooks[hookName]&&await Promise.all(hooks[hookName].map(callback=>callback.apply(this,args))),originalMethod.apply(this,args)},descriptor}}function hookAsyncWithContext(hookName,contextFn){return function(target,propertyKey,descriptor){const originalMethod=descriptor.value;return descriptor.value=async function(...args){if(hooks[hookName]){const additionalContext=typeof contextFn=="function"?await contextFn(this):{};await Promise.all(hooks[hookName].map(callback=>callback.apply(this,[additionalContext,...args])))}return originalMethod.apply(this,args)},descriptor}}var __defProp$1p=Object.defineProperty,__getOwnPropDesc$l=Object.getOwnPropertyDescriptor,__defNormalProp$1p=(obj,key,value)=>key in obj?__defProp$1p(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__decorateClass$l=(decorators,target,key,kind)=>{for(var result=__getOwnPropDesc$l(target,key),i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=decorator(target,key,result)||result);return result&&__defProp$1p(target,key,result),result},__publicField$1p=(obj,key,value)=>__defNormalProp$1p(obj,typeof key!="symbol"?key+"":key,value);const console$q=Logger("ConversationHelper");class Conversation extends EventEmitter$1{constructor(_model,_specSource,_settings){super(),this._model=_model,this._specSource=_specSource,this._settings=_settings,__publicField$1p(this,"_agentId",""),__publicField$1p(this,"_systemPrompt"),__publicField$1p(this,"userDefinedSystemPrompt",""),__publicField$1p(this,"toolChoice","auto"),__publicField$1p(this,"assistantName"),__publicField$1p(this,"_reqMethods"),__publicField$1p(this,"_toolsConfig"),__publicField$1p(this,"_endpoints"),__publicField$1p(this,"_baseUrl"),__publicField$1p(this,"_status",""),__publicField$1p(this,"_currentWaitPromise"),__publicField$1p(this,"_llmContextStore"),__publicField$1p(this,"_context"),__publicField$1p(this,"_maxContextSize",1024*128),__publicField$1p(this,"_maxOutputTokens",1024*8),__publicField$1p(this,"_teamId"),__publicField$1p(this,"_agentVersion"),__publicField$1p(this,"agentData"),__publicField$1p(this,"_lastError"),__publicField$1p(this,"_spec"),__publicField$1p(this,"_customToolsDeclarations",[]),__publicField$1p(this,"_customToolsHandlers",{}),__publicField$1p(this,"stop",!1),this.on("error",error=>{this._lastError=error,console$q.warn("Conversation Error: ",error?.message)}),this._maxContextSize=_settings.maxContextSize||this._model.tokens||this._model.keyOptions?.tokens||this._maxContextSize,this._maxOutputTokens=_settings.maxOutputTokens||this._model.completionTokens||this._model.keyOptions?.completionTokens||this._maxOutputTokens,_settings?.systemPrompt&&(this.userDefinedSystemPrompt=_settings.systemPrompt),_settings?.toolChoice&&(this.toolChoice=_settings.toolChoice),_settings?.store&&(this._llmContextStore=_settings.store),this._agentVersion=_settings?.agentVersion,(async()=>_specSource?this.loadSpecFromSource(_specSource).then(async spec=>{if(!spec)throw this._status="error",this.emit("error","Unable to parse OpenAPI specifications"),new Error("Invalid OpenAPI specification data format");this._spec=spec,!this._agentId&&_settings?.agentId&&(this._agentId=_settings.agentId),this._agentId||(this._agentId="FAKE-AGENT-ID"),await this.assignTeamIdFromAgentId(this._agentId),await this.updateModel(this._model),this._status="ready"}).catch(error=>{this._status="error",this.emit("error",error)}):(await this.updateModel(this._model),this._status="ready"))()}get systemPrompt(){return this._systemPrompt}set systemPrompt(systemPrompt){this._systemPrompt=systemPrompt,this._context&&(this._context.systemPrompt=systemPrompt)}get context(){return this._context}set spec(specSource){this.ready.then(()=>{this._status="",this.loadSpecFromSource(specSource).then(async spec=>{if(!spec)throw this._status="error",this.emit("error","Invalid OpenAPI specification data format"),new Error("Invalid OpenAPI specification data format");this._spec=spec,await this.assignTeamIdFromAgentId(this._agentId),await this.updateModel(this._model),this._status="ready"})})}set model(model){this.ready.then(async()=>{this._status="",await this.updateModel(model),this._status="ready"})}get model(){return this._model}get ready(){return this._currentWaitPromise?this._currentWaitPromise:(this._currentWaitPromise=new Promise((resolve,reject)=>{if(this._status)return resolve(this._status);const maxWaitTime=3e4;let waitTime=0;const interval=100,wait=setInterval(()=>{if(this._status)return clearInterval(wait),resolve(this._status);if(waitTime+=interval,waitTime>=maxWaitTime)return clearInterval(wait),reject("Timeout: Failed to prepare data")},interval)}),this._currentWaitPromise)}async prompt(message,toolHeaders={},concurrentToolCalls=4,abortSignal){let error=null;const errListener=err=>error=err;this.once("error",errListener);const result=await this.streamPrompt(message,toolHeaders,concurrentToolCalls,abortSignal);if(error)throw error;return this.removeListener("error",errListener),result}async streamPrompt(message,toolHeaders={},concurrentToolCalls=4,abortSignal){let options=typeof message=="object"?message:{message};message=options?.message;const files=options?.files;if(message&&(this.stop=!1),this.stop){this.emit("interrupted","interrupted"),this.emit("end");return}await this.ready,abortSignal&&abortSignal.addEventListener("abort",()=>{this.emit("aborted","Aborted by user!")});const passThroughtContinueMessage="Continue with the next tool call if there are any, or just inform the user that you are done";let _content="";const reqMethods=this._reqMethods,toolsConfig=this._toolsConfig,endpoints=this._endpoints,baseUrl=this._baseUrl,message_id="msg_"+randomUUID();toolHeaders["X-DEBUG"];const llmInference=await LLMInference$1.getInstance(this.model,AccessCandidate.team(this._teamId));message&&this._context.addUserMessage(message,message_id);const contextWindow=await this._context.getContextWindow(this._maxContextSize,this._maxOutputTokens);let maxTokens=this._maxOutputTokens;typeof this.model=="object"&&this.model?.params?.maxTokens&&(maxTokens=this.model.params.maxTokens);const eventEmitter=await llmInference.promptStream({contextWindow,files,params:{model:this.model,toolsConfig:this._settings?.toolsStrategy?this._settings.toolsStrategy(toolsConfig):toolsConfig,maxTokens,cache:this._settings?.experimentalCache,agentId:this._agentId,abortSignal}}).catch(error=>{console$q.error("Error on promptStream: ",error),this.emit(TLLMEvent.Error,error)});if(abortSignal&&abortSignal.addEventListener("abort",()=>{eventEmitter.removeAllListeners()}),!eventEmitter||eventEmitter.error)throw new Error("[LLM Request Error]");message&&this.emit("start"),eventEmitter.on("data",data=>{this.stop||this.emit("data",data)}),eventEmitter.on(TLLMEvent.Thinking,thinking=>{this.stop||this.emit(TLLMEvent.Thinking,thinking)}),eventEmitter.on(TLLMEvent.Data,data=>{this.stop||this.emit(TLLMEvent.Data,data)}),eventEmitter.on(TLLMEvent.Content,content=>{this.stop||(_content+=content,this.emit(TLLMEvent.Content,content))});let finishReason="stop";const toolsContent=await new Promise((resolve,reject)=>{let hasTools=!1,hasError=!1,passThroughContent="";eventEmitter.on(TLLMEvent.Error,error=>{hasError=!0,reject(error)}),eventEmitter.on(TLLMEvent.ToolInfo,async(toolsData,thinkingBlocks=[])=>{if(this.stop)return;hasTools=!0;let llmMessage={role:"assistant",content:_content,tool_calls:[]};thinkingBlocks?.length>0&&(this.emit("thoughtProcess",thinkingBlocks.filter(block=>block.type==="thinking").map(block=>block.thinking||"").join(`
27
+ `;for(const[id,connection]of this.connections.entries())try{connection&&!connection.finished?connection.write(message):this.connections.delete(id)}catch(error){console.error(`Error sending SSE to connection ${id}:`,error),this.connections.delete(id)}}remove(connectionId){const connection=this.connections.get(connectionId);if(connection){try{connection&&!connection.finished&&connection.end()}catch(error){console.error(`Error closing connection ${connectionId}:`,error)}return this.connections.delete(connectionId)}return!1}async close(){for(const[id,connection]of this.connections.entries())try{connection&&!connection.finished&&(connection.end(),console.log("Delibertly shutting down sse connection with id: ",id))}catch(error){console.error(`Error closing connection ${id}:`,error)}this.connections.clear()}getConnectionCount(){return this.connections.size}}var __defProp$1A=Object.defineProperty,__defNormalProp$1A=(obj,key,value)=>key in obj?__defProp$1A(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1A=(obj,key,value)=>__defNormalProp$1A(obj,typeof key!="symbol"?key+"":key,value);const console$t=Logger("Agent"),idPromise=id=>id,MAX_LATENCY=50;class Agent{constructor(id,agentData,agentSettings,agentRequest){this.id=id,this.agentSettings=agentSettings,__publicField$1A(this,"name"),__publicField$1A(this,"data"),__publicField$1A(this,"teamId"),__publicField$1A(this,"components"),__publicField$1A(this,"connections"),__publicField$1A(this,"endpoints",{}),__publicField$1A(this,"sessionId"),__publicField$1A(this,"sessionTag",""),__publicField$1A(this,"callerSessionId"),__publicField$1A(this,"apiBasePath","/api"),__publicField$1A(this,"agentRuntime"),__publicField$1A(this,"usingTestDomain",!1),__publicField$1A(this,"domain",""),__publicField$1A(this,"debugSessionEnabled",!1),__publicField$1A(this,"circularLimit",100),__publicField$1A(this,"version",""),__publicField$1A(this,"agentVariables",{}),__publicField$1A(this,"_kill",!1),__publicField$1A(this,"async",!1),__publicField$1A(this,"jobID",""),__publicField$1A(this,"planInfo",{}),__publicField$1A(this,"callback"),__publicField$1A(this,"agentRequest"),__publicField$1A(this,"sse"),__publicField$1A(this,"modelsProvider"),__publicField$1A(this,"_componentInstance",{}),__publicField$1A(this,"_componentInstancesLoader",new ControlledPromise(()=>{}));const json=typeof agentData=="string"?JSON.parse(agentData):agentData;this.data=json.connections&&json.components?json:json.data,this.data||(this.data={name:"",connections:[],components:[]}),this.name=this.data.name,this.version=this.data.agentVersion||"",this.teamId=this.data.teamId,this.connections=this.data.connections,this.debugSessionEnabled=this.data.debugSessionEnabled,this.usingTestDomain=this.data.usingTestDomain,this.agentVariables=this.data.variables||{};const endpoints=this.data.components.filter(c=>c.name=="APIEndpoint");for(let endpoint of endpoints){let method=endpoint.data.method||"POST";method=method.toUpperCase(),this.endpoints[`${this.apiBasePath}/${endpoint.data.endpoint}`]||(this.endpoints[`${this.apiBasePath}/${endpoint.data.endpoint}`]={}),this.endpoints[`${this.apiBasePath}/${endpoint.data.endpoint}`][method]=endpoint}this.components={};for(let component of this.data.components)this.components[component.id]=component;for(let connection of this.data.connections){const sourceComponent=this.components[connection.sourceId],targetComponent=this.components[connection.targetId],sourceIndex=typeof connection.sourceIndex=="number"?connection.sourceIndex:sourceComponent.outputs.findIndex(o=>o.name==connection.sourceIndex),targetIndex=typeof connection.targetIndex=="number"?connection.targetIndex:targetComponent.inputs.findIndex(i=>i.name==connection.targetIndex);connection.sourceIndex=sourceIndex,connection.targetIndex=targetIndex;const output=sourceComponent.outputs[sourceIndex];output.index=sourceIndex;const input=targetComponent.inputs[targetIndex];input.index=targetIndex,output.next||(output.next=[]),output.next.push(targetComponent.id),input.prev||(input.prev=[]),input.prev.push(sourceComponent.id)}this.tagAsyncComponents(),agentRequest&&this.setRequest(agentRequest),this.sse=new AgentSSE(this);try{ConnectorService.getComponentConnector().requester(AccessCandidate.agent(id)).getAll().then(customComponents=>{this._componentInstance={...this._componentInstance,...customComponents},this._componentInstancesLoader.resolve(!0)})}catch{console$t.warn("Could not load custom components",AccessCandidate.agent(this.id)),this._componentInstancesLoader.reject("Could not load custom components")}const modelsProvider=ConnectorService.getModelsProviderConnector();modelsProvider.valid&&(this.modelsProvider=modelsProvider.agent(id))}get ComponentInstances(){return this._componentInstance}addSSE(sseSource,monitorId){if(sseSource instanceof AgentSSE)for(const[monitorId2,res]of sseSource)this.sse.add(res,monitorId2);else{const id=monitorId||Math.random().toString(36).substring(2,15);this.sse.add(sseSource,id)}}setRequest(agentRequest){if(this.agentRequest)return;this.agentRequest=agentRequest,this.agentRequest=agentRequest;const dateTime=getCurrentFormattedDate();this.sessionId="rt-"+(this.agentRequest.sessionID||dateTime+"."+uid());const sessionTags=this?.agentRequest?.headers["x-session-tag"];sessionTags&&(this.sessionTag+=this.sessionTag?`,${sessionTags}`:sessionTags);var regex=new RegExp(`^/v[0-9]+(.[0-9]+)?${this.apiBasePath}/(.*)`);this.agentRequest?.path?.startsWith(`${this.apiBasePath}/`)||this.agentRequest?.path?.match(regex)?(this.agentRuntime=new AgentRuntime(this),this.callerSessionId=this?.agentRequest?.headers["x-caller-session-id"]?.substring(0,256)||this.agentRuntime.workflowReqId||this.sessionId):this.agentRuntime=AgentRuntime.dummy}setCallback(callback){this.callback=callback}kill(){this._kill=!0}isKilled(){return this._kill}async parseVariables(){if(typeof this.agentVariables=="object")for(let key in this.agentVariables){const value=this.agentVariables[key];value.startsWith("{{")&&value.endsWith("}}")&&(this.agentVariables[key]=await TemplateString(value).parseTeamKeysAsync(this.teamId).asyncResult)}}async process(endpointPath,input){await this.agentRuntime.ready();let result,dbgSession=null,sessionClosed=!1;const eventId="e-"+uid(),startTime=Date.now();this.sse.send("agent",{eventId,action:"callStart",endpointPath,id:this.id,name:this.name,startTime,input});const logId=AgentLogger.log(this,null,{sourceId:endpointPath,componentId:"AGENT",domain:this.domain,input,workflowID:this.agentRuntime.workflowReqId,processID:this.agentRuntime.processID,inputTimestamp:new Date().toISOString(),sessionID:this.callerSessionId,tags:this.sessionTag}),method=this.agentRequest.method.toUpperCase(),endpoint=this.endpoints[endpointPath]?.[method];if(this.agentRuntime.debug){if(!endpoint&&this.agentRequest.path!="/api/")throw logId&&AgentLogger.log(this,logId,{error:`Endpoint ${method} ${endpointPath} Not Found`}),new Error(`Endpoint ${method} ${endpointPath} Not Found`);let dbgResult;if(dbgResult||(dbgResult=await this.agentRuntime.runCycle()),dbgResult&&typeof dbgResult?.state<"u")return this.agentRuntime.sync(),dbgResult?.finalResult&&(dbgResult.finalResult=await this.postProcess(dbgResult.finalResult).catch(error=>({error}))),dbgResult}if(!endpoint){logId&&AgentLogger.log(this,logId,{error:`Endpoint ${method} ${endpointPath} Not Found`});const endTime2=Date.now(),duration2=endTime2-startTime;throw this.sse.send("agent",{eventId,action:"callStop",endpointPath,id:this.id,name:this.name,startTime,endTime:endTime2,duration:duration2,input,error:`Endpoint ${method} ${endpointPath} Not Found`}),new Error(`Endpoint ${method} ${endpointPath} Not Found`)}this.agentRuntime.updateComponent(endpoint.id,{active:!0,input,sourceId:null});let step;do{step=await this.agentRuntime.runCycle();const qosLatency=Math.floor(OSResourceMonitor.cpu.load*MAX_LATENCY||0);await delay(10+qosLatency)}while(!step?.finalResult&&!this._kill);if(this._kill){const endTime2=Date.now(),duration2=endTime2-startTime;return this.sse.send("agent",{eventId,action:"callStop",endpointPath,id:this.id,name:this.name,startTime,endTime:endTime2,duration:duration2,input,error:"Agent killed"}),console$t.warn(`Agent ${this.id} was killed`,AccessCandidate.agent(this.id)),{error:"Agent killed"}}if(result=await this.postProcess(step?.finalResult).catch(error=>({error})),this.agentRuntime.circularLimitReached){const circularLimitData=this.agentRuntime.circularLimitReached;result={error:`Circular Calls Limit Reached on ${circularLimitData}. Current circular limit is ${this.circularLimit}`};const endTime2=Date.now(),duration2=endTime2-startTime;throw this.sse.send("agent",{eventId,action:"callStop",endpointPath,id:this.id,name:this.name,startTime,endTime:endTime2,duration:duration2,input,error:result.error}),new Error(`Circular Calls Limit Reached on ${circularLimitData}. Current circular limit is ${this.circularLimit}`)}logId&&AgentLogger.log(this,logId,{outputTimestamp:""+Date.now(),result}),this.updateTasksCount();const endTime=Date.now(),duration=endTime-startTime;return this.sse.send("agent",{eventId,action:"callStop",endpointPath,id:this.id,name:this.name,startTime,endTime,duration,input,result}),this.agentRuntime.debug?{state:result,dbgSession,sessionClosed}:result}async updateTasksCount(){}async postProcess(result){Array.isArray(result)&&(result=result.flat(1/0)),Array.isArray(result)||(result=[result]),result=result.filter(r=>!(r?.result?._error&&r?.result?._error_handled));for(let i=0;i<result.length;i++){const _result=result[i];if(!_result)continue;_result._debug&&delete _result._debug,_result._debug_time&&delete _result._debug_time;const _componentData=this.components[_result.id];if(!_componentData)continue;const _component=this._componentInstance[_componentData.name];if(!_component)continue;const postProcessResult=await _component.postProcess(_result,_componentData,this).catch(error=>({error}));result[i]=postProcessResult}return result.length==1&&(result=result[0]),result}hasLoopAncestor(inputEntry){if(!inputEntry.prev)return!1;for(let prevId of inputEntry.prev){const prevComponentData=this.components[prevId];if(prevComponentData.name=="ForEach")return!0;for(let inputEntry2 of prevComponentData.inputs)if(this.hasLoopAncestor(inputEntry2))return!0}}clearChildLoopRuntimeComponentData(componentId){const componentData=this.components[componentId],runtimeData=this.agentRuntime.getRuntimeData(componentId);if(runtimeData._ChildLoopData)for(let inputEntry of componentData.inputs)this.hasLoopAncestor(inputEntry)&&delete runtimeData.input[inputEntry.name]}getComponentMissingInputs(componentId,_input){let missingInputs=[];const componentData=this.components[componentId];if(this._componentInstance[componentData.name].alwaysActive)return missingInputs;const readablePredecessors=this.findReadablePredecessors(componentId),readableInputNames={};for(let pred of readablePredecessors)pred&&(readableInputNames[pred.input.name]=pred);const allInputIndexes=this.connections.filter(c=>c.targetId==componentId).map(e=>e.targetIndex),allInputs=componentData.inputs.filter(r=>allInputIndexes.includes(r.index));if(Array.isArray(allInputs)&&allInputs.length>0){for(let input of allInputs)if(!input.optional){if(readableInputNames[input.name]){const pred=readableInputNames[input.name],component2=pred.component,predComponentData=this.components[pred.id];if(component2.hasOutput(pred.output.name,predComponentData,this))continue}typeof _input[input.name]>"u"&&missingInputs.push(input.name)}}return missingInputs}findReadablePredecessors(componentId){const componentData=this.components[componentId];return this._componentInstance[componentData.name],this.connections.filter(c=>c.targetId==componentId).map(c=>{const sourceComponentData=this.components[c.sourceId],sourceComponent=this._componentInstance[sourceComponentData.name],output=sourceComponentData.outputs[c.sourceIndex],input=componentData.inputs[c.targetIndex];return sourceComponent.hasReadOutput?{output,input,component:sourceComponent,id:c.sourceId}:null}).filter(e=>e!=null)}updateStep(sourceId,componentId){const agentRuntime=this.agentRuntime,step=agentRuntime.curStep;agentRuntime.updateComponent(componentId,{step})}async callComponent(sourceId,componentId,input){const startTime=Date.now(),agentRuntime=this.agentRuntime,componentData=this.components[componentId],component=this._componentInstance[componentData.name],eventId="e-"+uid();if(this.sse.send("component",{eventId,action:"callStart",sourceId,id:componentId,name:componentData.displayName,title:componentData.title,startTime,input}),this._kill){console$t.warn(`Agent ${this.id} was killed, skipping component ${componentData.name}`,AccessCandidate.agent(this.id));const output2={id:componentData.id,name:componentData.displayName,result:null,error:"Agent killed"},endTime2=Date.now(),duration2=endTime2-startTime;return this.sse.send("component",{eventId,action:"callStop",sourceId,id:componentId,name:componentData.displayName,title:componentData.title,startTime,endTime:endTime2,duration:duration2,output:output2}),output2}if(!component){const endTime2=Date.now(),duration2=endTime2-startTime;throw this.sse.send("component",{eventId,action:"callStop",sourceId,id:componentId,name:componentData.displayName,title:componentData.title,startTime,endTime:endTime2,duration:duration2,output:{error:"Component not found"}}),new Error(`Component ${componentData.name} not found`)}if(this.agentRuntime.incTag(componentId),this.agentRuntime.checkCircularLimit(),this.agentRuntime.circularLimitReached){const endTime2=Date.now(),duration2=endTime2-startTime;return this.sse.send("component",{eventId,action:"callStop",sourceId,id:componentId,name:componentData.displayName,title:componentData.title,startTime,endTime:endTime2,duration:duration2,output:{error:"Circular Calls Reached"}}),{error:"Circular Calls Reached"}}agentRuntime.getComponentData(componentId)?.output?._missing_inputs&&agentRuntime.updateComponent(componentId,{output:{}});const _input=this.prepareComponentInput(componentId,input),logId=AgentLogger.log(this,null,{sourceId:sourceId||"AGENT",componentId,domain:this.domain,workflowID:this.agentRuntime.workflowReqId,processID:this.agentRuntime.processID,input:componentData.name=="APIEndpoint"?this.agentRequest.method=="GET"?this.agentRequest.query:this.agentRequest.body:_input,inputTimestamp:new Date().toISOString(),sessionID:this.callerSessionId,tags:this.sessionTag});let output=null,missingInputs=[];if(this.updateStep(sourceId,componentId),agentRuntime.debug&&(output=await agentRuntime.injectDebugOutput(componentId)),!output){if(missingInputs=this.getComponentMissingInputs(componentId,_input),missingInputs.length>0){agentRuntime.updateComponent(componentId,{active:!0,status:"waiting"});const connections=this.connections.filter(c=>c.sourceId==componentId)||[];for(let connection of connections)if(componentData.outputs[connection.sourceIndex].name=="_error")break;output={_error:"Missing inputs : "+JSON.stringify(missingInputs),_missing_inputs:missingInputs}}if(!output){const validationResult=await component.validateConfig(componentData);if(validationResult._error)output=validationResult;else try{await this.parseVariables(),output=await component.process({...this.agentVariables,..._input},{...componentData,eventId},this),console$t.debug(output,AccessCandidate.agent(this.id))}catch(error){console$t.error("Error on component process: ",{componentId,name:componentData.name,input:_input},error,AccessCandidate.agent(this.id)),error?.message?output={Response:void 0,_error:error.message,_debug:error.message}:output={Response:void 0,_error:error.toString(),_debug:error.toString()}}}}const runtimeData=this.agentRuntime.getRuntimeData(componentId);if(agentRuntime.updateComponent(componentId,{output}),output._in_progress&&agentRuntime.updateComponent(componentId,{active:!0,status:"in_progress"}),(output.error||output._error)&&(runtimeData?._ChildLoopData?._in_progress||this.agentRuntime.resetComponent(componentId),logId&&AgentLogger.log(this,logId,{error:output.error||output._error}),output.error)){const endTime2=Date.now(),duration2=endTime2-startTime;return this.sse.send("component",{eventId,action:"callStop",sourceId,id:componentId,name:componentData.displayName,title:componentData.title,startTime,endTime:endTime2,duration:duration2,output:{error:output.error||output._error}}),[{id:componentData.id,name:componentData.displayName,result:null,error:output.error||output._error,_debug:output.error||output._error}]}let results=[];if(output&&!output._missing_inputs){if(AgentLogger.logTask(this,1),results=await this.callNextComponents(componentId,output).catch(error=>({error,id:componentData.id,name:componentData.displayName})),runtimeData._LoopData&&output._in_progress&&runtimeData._LoopData.branches==null){const branches=Array.isArray(results)?results.length:1;output._in_progress&&(runtimeData._LoopData.branches=branches,agentRuntime.updateRuntimeData(componentId,{_LoopData:runtimeData._LoopData}))}if(results._is_leaf){delete results._is_leaf;const _ChildLoopData=runtimeData._ChildLoopData;if(_ChildLoopData&&_ChildLoopData.parentId){const parentId=_ChildLoopData.parentId,_LoopData=this.agentRuntime.getRuntimeData(parentId)._LoopData;if(_LoopData){_LoopData.result||(_LoopData.result=[]);let resultsCopy=JSON.parse(JSON.stringify(results));results.result&&(results.result._exclude=!0),resultsCopy=await component.postProcess(resultsCopy,componentData,this),_LoopData.result.push(resultsCopy),_LoopData.branches--,_LoopData.branches<=0&&agentRuntime.updateComponent(parentId,{active:!0,status:""}),agentRuntime.updateRuntimeData(parentId,{_LoopData})}}else{const _LoopData=this.agentRuntime.getRuntimeData(componentId)._LoopData;_LoopData&&_LoopData.loopIndex==1&&(_LoopData._in_progress=!1,output._in_progress=!1,agentRuntime.updateComponent(componentId,{active:!0,status:""}),agentRuntime.updateRuntimeData(componentId,{_LoopData}))}}}!output._missing_inputs&&!output._in_progress&&(runtimeData?._ChildLoopData?._in_progress&&runtimeData._ChildLoopData?.loopIndex<runtimeData._ChildLoopData?.loopLength?(this.clearChildLoopRuntimeComponentData(componentId),agentRuntime.updateComponent(componentId,{active:!0,status:"waiting"})):this.agentRuntime.resetComponent(componentId)),Array.isArray(results)&&(results=results.flat(1/0).filter(r=>r.result!=null)),logId&&AgentLogger.log(this,logId,{output,outputTimestamp:""+Date.now()});const endTime=Date.now(),duration=endTime-startTime;return this.sse.send("component",{eventId,action:"callStop",sourceId,id:componentId,name:componentData.displayName,title:componentData.title,startTime,endTime,duration,output}),[results,{id:componentData.id,name:componentData.displayName,result:output}]}JSONExpression(obj,propertyString){const properties=propertyString.split(/\.|\[|\]\.|\]\[|\]/).filter(Boolean);let currentProperty=obj;for(let property of properties){if(currentProperty==null)return;currentProperty=currentProperty[property]}return currentProperty}async callNextComponents(componentId,output){const agentRuntime=this.agentRuntime,componentData=this.components[componentId];this._componentInstance[componentData.name];let connections=this.connections.filter(c=>c.sourceId==componentId).map(c=>({...c,output,componentData}));const waitingComponents=agentRuntime.getWaitingComponents(),waitingComponentIds=waitingComponents.map(e=>e.id),alwaysActiveIds=Object.keys(this.agentRuntime.alwaysActiveComponents),alwaysActiveConnections=this.connections.filter(c=>alwaysActiveIds.includes(c.sourceId)&&waitingComponentIds.includes(c.targetId)).map(c=>{const output2={};waitingComponents.find(e=>e.id==c.targetId);const prevComponentData=this.components[c.sourceId],prevComponent=this._componentInstance[prevComponentData.name],outputEndpoint=prevComponentData.outputs[c.sourceIndex];return output2[outputEndpoint.name]=prevComponent.readOutput(outputEndpoint.name,prevComponentData,this),{...c,output:output2,componentData:this.components[c.sourceId]}});if(connections=[...connections,...alwaysActiveConnections],!Array.isArray(connections)||connections.length==0)return{id:componentData.id,name:componentData.name,result:output,_is_leaf:!0};const targetComponents=connections.reduce((acc,obj)=>{let key=obj.targetId;return acc[key]||(acc[key]=[]),acc[key].push(obj),acc},{}),promises=[];for(let targetId in targetComponents){const targetComponentData=this.components[targetId];if(!this.async&&targetComponentData.async&&targetComponentData.name!=="Async")continue;this._componentInstance[targetComponentData.name];const connections2=targetComponents[targetId];let _isErrorHandler=!1;if(Array.isArray(connections2)&&connections2.length>0){const nextInput={};for(let connection of connections2){const output2=connection.output,componentData2=connection.componentData,outputEndpoint=componentData2.outputs[connection.sourceIndex],inputEndpoint=targetComponentData.inputs[connection.targetIndex],outputExpression=outputEndpoint.expression||outputEndpoint.name,outputParts=outputExpression.split("."),defaultOutputs=componentData2.outputs.find(c=>c.default);let value;if(outputEndpoint.name=="_error"&&(_isErrorHandler=!0),outputEndpoint.default?value=output2[outputEndpoint.name]:defaultOutputs&&(value=output2[defaultOutputs.name]?.[outputEndpoint.name]),value===void 0&&outputParts.length>=1){let val=this.JSONExpression(output2,outputExpression);val!==void 0&&(value=val)}if(value!==void 0){let combinedInput=_mergeInputs(nextInput[inputEndpoint.name],value).filter(e=>e!==void 0);nextInput[inputEndpoint.name]=combinedInput.length===1?combinedInput[0]:combinedInput}}if(!nextInput||JSON.stringify(nextInput)=="{}")continue;const input=this.prepareComponentInput(targetId,nextInput),targetComponent2=this.components[targetId];_isErrorHandler&&targetComponent2&&(output._error_handled=!0);const status=this.getComponentMissingInputs(targetId,input).length>0?"waiting":void 0,sourceRuntimeData=this.agentRuntime.getRuntimeData(componentId);let _ChildLoopData=sourceRuntimeData._LoopData;(!_ChildLoopData||!_ChildLoopData._in_progress)&&(_ChildLoopData=sourceRuntimeData._ChildLoopData),agentRuntime.updateComponent(targetId,{active:!0,input:nextInput,sourceId:componentId,status}),agentRuntime.updateRuntimeData(targetId,{_ChildLoopData,_LoopData:null}),promises.push(idPromise({id:targetId,name:targetComponent2.name,inputs:nextInput})),status&&AgentLogger.log(this,null,{sourceId:componentId,componentId:targetId,step:this.agentRuntime.curStep+1,domain:this.domain,workflowID:this.agentRuntime.workflowReqId,processID:this.agentRuntime.processID,input:{__action:"status_update",__status:status,data:nextInput},inputTimestamp:new Date().toISOString(),sessionID:this.callerSessionId,tags:this.sessionTag})}}if(promises.length==0)return{id:componentData.id,name:componentData.name,result:output,_is_leaf:!0};const results=await Promise.all(promises);return results.length==1?results[0]:results}prepareComponentInput(targetId,inputs){const rData=this.agentRuntime.getRuntimeData(targetId),componentData=this.components[targetId],rDataInput=rData?.input||{};let _input={...rDataInput};if(inputs)for(let key in inputs){let value=inputs[key];_input[key]=_mergeInputs(rDataInput[key],value).filter(e=>e!==void 0),_input[key].length==1&&(_input[key]=_input[key][0])}const readablePredecessors=this.findReadablePredecessors(targetId);for(let c of readablePredecessors)if(c){const predComponentData=this.components[c.id],value=c.component.readOutput(c.output.name,predComponentData,this);value&&c.input?.name&&(_input||(_input={}),_input[c.input.name]=value)}this.agentRuntime.updateRuntimeData(targetId,{input:_input});for(let input of componentData.inputs)input.defaultVal&&_input[input.name]===void 0&&(_input[input.name]=TemplateString(input.defaultVal).parse(this.agentVariables).result);return _input}getConnectionSource(connection){return this.components[connection.sourceId].inputs.find(e=>e.index===connection.sourceIndex)}getConnectionTarget(connection){return this.components[connection.targetId].inputs.find(e=>e.index===connection.targetIndex)}recursiveTagAsyncComponents(component){const agent=this;for(let output of component.outputs){if(component.name=="Async"&&output.name==="JobID")continue;const connected=agent.connections.filter(c=>c.sourceId===component.id&&c.sourceIndex===output.index);if(connected)for(let con of connected){const targetComponent=agent.components[con.targetId];targetComponent&&(targetComponent.async=!0,this.recursiveTagAsyncComponents(targetComponent))}}}tagAsyncComponents(){const AsyncComponents=Object.values(this.components).filter(c=>c.name==="Async");if(!(!AsyncComponents||AsyncComponents.length==0))for(let AsyncComponent of AsyncComponents)AsyncComponent.async=!0,this.recursiveTagAsyncComponents(AsyncComponent)}}function _mergeInputs(existing,newValue){return existing===void 0?[newValue]:(Array.isArray(existing)||(existing=[existing]),[...existing,newValue])}var __defProp$1z=Object.defineProperty,__defNormalProp$1z=(obj,key,value)=>key in obj?__defProp$1z(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1z=(obj,key,value)=>__defNormalProp$1z(obj,typeof key!="symbol"?key+"":key,value);class AgentRequest{constructor(req){if(__publicField$1z(this,"headers"),__publicField$1z(this,"body"),__publicField$1z(this,"query"),__publicField$1z(this,"params"),__publicField$1z(this,"method","GET"),__publicField$1z(this,"path",""),__publicField$1z(this,"sessionID",""),__publicField$1z(this,"res",null),__publicField$1z(this,"req",null),__publicField$1z(this,"files",[]),__publicField$1z(this,"_agent_authinfo"),!req)return;this.headers=JSON.parse(JSON.stringify(req.headers||{})),this.body=JSON.parse(JSON.stringify(req.body||req.data||{})),this.query=JSON.parse(JSON.stringify(req.query||{})),this.params=JSON.parse(JSON.stringify(req.params||{}));const lowerCaseHeaders=Object.fromEntries(Object.entries(this.headers).map(([key,value])=>[key.toLowerCase(),value]));if(this.headers={...lowerCaseHeaders,...this.headers},req?.url)try{const url=new URL(req.url);this.path=url.pathname,this.query={...this.query,...Object.fromEntries(url.searchParams)}}catch{}req?.path&&(this.path=req.path),this.method=req.method,this.sessionID=req.sessionID,this.files=req.files||[],this._agent_authinfo=req._agent_authinfo,this.req=req instanceof AgentRequest?req?.req:req,this.res=req?.res||null}header(name){return this.headers[name.toLowerCase()]}}var __defProp$1y=Object.defineProperty,__defNormalProp$1y=(obj,key,value)=>key in obj?__defProp$1y(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1y=(obj,key,value)=>__defNormalProp$1y(obj,typeof key!="symbol"?key+"":key,value);Logger("EmbodimentSettings");class EmbodimentSettings{constructor(agentId){__publicField$1y(this,"_embodiments"),__publicField$1y(this,"_ready",!1),this.init(agentId)}async init(agentId){const agentDataConnector=ConnectorService.getAgentDataConnector();this._embodiments=await agentDataConnector.getAgentEmbodiments(agentId).catch(error=>[]),this._ready=!0}ready(maxWait=1e4){return new Promise((resolve,reject)=>{const interval=setInterval(()=>{this._ready&&(clearInterval(interval),resolve(!0)),maxWait-=100},100);setTimeout(()=>{clearInterval(interval),reject(!1)},maxWait)})}get(embodimentType,key){if(!this._embodiments)return;const _embodiment=this._embodiments.find(embodiment=>embodiment.type?.toLowerCase()===embodimentType.toLowerCase());return key?_embodiment?.properties?.[key]:_embodiment?.properties}}var __defProp$1x=Object.defineProperty,__defNormalProp$1x=(obj,key,value)=>key in obj?__defProp$1x(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1x=(obj,key,value)=>__defNormalProp$1x(obj,typeof key!="symbol"?key+"":key,value);Logger("AgentSettings");class AgentSettings{constructor(agentId){__publicField$1x(this,"_settings"),__publicField$1x(this,"embodiments"),__publicField$1x(this,"_ready",!1),agentId&&this.init(agentId)}async init(agentId){this.embodiments=new EmbodimentSettings(agentId);const agentDataConnector=ConnectorService.getAgentDataConnector();this._settings=await agentDataConnector.getAgentSettings(agentId).catch(e=>{})||{},this._ready=!0}ready(maxWait=1e4){return new Promise((resolve,reject)=>{const interval=setInterval(()=>{this._ready&&(clearInterval(interval),resolve(!0)),maxWait-=100},100);setTimeout(()=>{clearInterval(interval),reject(!1)},maxWait)})}get(key){return this._settings?.[key]||""}set(key,value){this._settings[key]=value}has(key){return this._settings[key]}}var __defProp$1w=Object.defineProperty,__defNormalProp$1w=(obj,key,value)=>key in obj?__defProp$1w(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1w=(obj,key,value)=>__defNormalProp$1w(obj,typeof key!="symbol"?key+"":key,value);class AgentProcess{constructor(agentData,agentVersion){this.agentData=agentData,this.agentVersion=agentVersion,__publicField$1w(this,"agent"),__publicField$1w(this,"_loadPromise"),this.initAgent(agentData,agentVersion)}async initAgent(agentData,agentVersion){let data,agentId;if(typeof agentData=="object")data=agentData,data.components&&data.connections&&(data={data,version:"1.0"}),agentId=data.data.id||"tmp-"+uid();else{const jsonRegex=/^{.*}$/g,jsonData=agentData.match(jsonRegex)?.[0],idRegex=/^[a-zA-Z0-9\-]+$/g;agentId=agentData.match(idRegex)?.[0],agentId&&(data=await ConnectorService.getAgentDataConnector().getAgentData(agentId,agentVersion)),!data&&jsonData&&(data=JSON.parse(jsonData),agentId=data.id||"tmp-"+uid(),data.components&&data.connections&&(data={data,version:"1.0"}))}const agentSettings=new AgentSettings(agentId);this.agent=new Agent(agentId,data,agentSettings)}async ready(){return this._loadPromise?this._loadPromise:this._loadPromise=new Promise(resolve=>{let maxWait=1e4;const itv=setInterval(()=>{this.agent&&(clearInterval(itv),resolve(!0)),maxWait-=100,maxWait<=0&&(clearInterval(itv),resolve(!1))},100)})}static load(agentData,agentVersion){return new AgentProcess(agentData,agentVersion)}async run(reqConfig,callback){if(await this.ready(),!this.agent)throw new Error("Failed to load agent");let request=this.parseReqConfig(reqConfig);this.agent.setRequest(request),typeof callback=="function"&&this.agent.setCallback(callback);const pathMatches=request.path.match(/(^\/v[0-9]+\.[0-9]+?)?(\/api\/(.+)?)/);if(!pathMatches||!pathMatches[2])return{status:404,data:{error:"Endpoint not found"}};const endpointPath=pathMatches[2],input=request.method=="GET"?request.query:request.body;return{data:await this.agent.process(endpointPath,input).catch(error=>({error:error.message}))}}reset(){this.initAgent(this.agentData)}parseReqConfig(reqConfig){return reqConfig instanceof AgentRequest?reqConfig:Array.isArray(reqConfig)?this.parseCLI(reqConfig):new AgentRequest(reqConfig)}parseCLI(argList){const cliConnector=ConnectorService.getCLIConnector(),methods=["get","post","put","delete","patch","head","options"],cli=cliConnector.parse(argList,["endpoint","post","get","put","delete","patch","head","options","headers","session"]),usedMethod=methods.find(method=>cli[method]),req=new AgentRequest;switch(req.method=usedMethod?.toUpperCase()||"GET",req.body={},req.query={},usedMethod){case"get":case"delete":case"head":case"options":req.query=cli[usedMethod];break;case"post":case"put":case"patch":req.body=cli[usedMethod];break}req.path=`/api/${cli.endpoint}`,req.params=cli.endpoint?.split("/"),req.headers=cli.headers||{};for(let key in req.headers)req.headers[key.toLowerCase()]=req.headers[key],delete req.headers[key];if(req.sessionID=cli.session||uid(),req.files=[],req.body)for(let entry in req.body){let value=req.body[entry];const filePath=path.join(process.cwd(),value),fileName=path.basename(filePath);if(fs__default.existsSync(filePath))try{const fileBuffer=fs__default.readFileSync(filePath),ext=fileName.split(".").pop(),fileObj={fieldname:entry,originalname:fileName,buffer:fileBuffer,mimetype:mime.getType(ext)||"application/octet-stream"};delete req.body[entry],req.files.push(fileObj),FileType.fileTypeFromBuffer(fileBuffer).then(fileType=>{fileType&&(fileObj.mimetype=fileType.mime)})}catch(error){console.warn("Coud not read file",filePath,error.message)}}return req}async post(path2,input,headers){return this.run({method:"POST",path:path2,body:input||{},headers})}async get(path2,query,headers){return this.run({method:"GET",path:path2,query,headers})}async readDebugState(stateId,reqConfig){if(await this.ready(),!this.agent)throw new Error("Failed to load agent");let request=this.parseReqConfig(reqConfig);return this.agent.setRequest(request),await this.agent.agentRuntime.ready(),this.agent.agentRuntime.readState(stateId,!0)}}var __defProp$1v=Object.defineProperty,__defNormalProp$1v=(obj,key,value)=>key in obj?__defProp$1v(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1v=(obj,key,value)=>__defNormalProp$1v(obj,typeof key!="symbol"?key+"":key,value);const ACLHashAlgo={none:source=>source,xxh3:source=>{const h64=xxhash.h64();return source?h64.update(source.toString()).digest().toString(16):null}};class ACL{constructor(acl){__publicField$1v(this,"hashAlgorithm"),__publicField$1v(this,"entries"),__publicField$1v(this,"migrated"),typeof acl=="string"?this.deserializeACL(acl):(this.hashAlgorithm=acl?.hashAlgorithm,this.entries=acl?.entries?JSON.parse(JSON.stringify(acl?.entries)):{},this.migrated=acl?.migrated),this.hashAlgorithm||(this.hashAlgorithm="xxh3"),this.entries||(this.entries={})}get ACL(){return{hashAlgorithm:this.hashAlgorithm,entries:JSON.parse(JSON.stringify(this.entries)),migrated:this.migrated}}get serializedACL(){return this.serializeACL(this)}static from(acl){return new ACL(acl)}checkExactAccess(acRequest){if(!this?.entries)return!1;const role=this?.entries[acRequest.candidate.role];if(!role)return!1;let entryId=acRequest.candidate.id;if(!ACLHashAlgo[this.hashAlgorithm])throw new Error(`Hash algorithm ${this.hashAlgorithm} not supported`);entryId=ACLHashAlgo[this.hashAlgorithm](entryId);const access=role[entryId];return access?(Array.isArray(acRequest.level)?acRequest.level:[acRequest.level]).every(level=>access.includes(level)):!1}addPublicAccess(level){if(this?.entries[TAccessRole.Public]||(this.entries[TAccessRole.Public]={}),!ACLHashAlgo[this.hashAlgorithm])throw new Error(`Hash algorithm ${this.hashAlgorithm} not supported`);const ownerId=TAccessRole.Public,hashedOwner=ACLHashAlgo[this.hashAlgorithm](ownerId);this?.entries[TAccessRole.Public][hashedOwner]||(this.entries[TAccessRole.Public][hashedOwner]=[]);const curLevel=this.entries[TAccessRole.Public][hashedOwner];return this.entries[TAccessRole.Public][hashedOwner]=[...curLevel,...level],this}removePublicAccess(level){if(!this?.entries[TAccessRole.Public])return this;const ownerId=TAccessRole.Public,hashedOwner=ACLHashAlgo[this.hashAlgorithm](ownerId),curLevel=this[TAccessRole.Public][hashedOwner];return this[TAccessRole.Public][hashedOwner]=curLevel.filter(l=>!level.includes(l)),this}addAccess(role,ownerId,level){if(role===TAccessRole.Public)throw new Error("Adding public access using addAccess method is not allowed. Use addPublicAccess method instead.");const _level=Array.isArray(level)?level:[level];if(this?.entries[role]||(this.entries[role]={}),!ACLHashAlgo[this.hashAlgorithm])throw new Error(`Hash algorithm ${this.hashAlgorithm} not supported`);const hashedOwner=ACLHashAlgo[this.hashAlgorithm](ownerId);if(!hashedOwner)throw new Error(`Invalid ownerId: ${role}:${ownerId}`);this?.entries[role][hashedOwner]||(this.entries[role][hashedOwner]=[]);const curLevel=this.entries[role][hashedOwner];return this.entries[role][hashedOwner]=[...curLevel,..._level],this}static addAccess(role,ownerId,level){return ACL.from().addAccess(role,ownerId,level)}removeAccess(role,ownerId,level){const _level=Array.isArray(level)?level:[level];if(!this[role])return this;if(!this[role][ownerId])return this;const curLevel=this[role][ownerId];return this[role][ownerId]=curLevel.filter(l=>!_level.includes(l)),this}serializeACL(tacl){let compressed="";if(tacl.hashAlgorithm&&(compressed+=`h:${tacl.hashAlgorithm}|`),tacl.entries)for(const[role,entries]of Object.entries(tacl.entries)){const roleShort=RoleMap[role],entriesArray=[];for(const[hashedOwnerKey,accessLevels]of Object.entries(entries||{}))if(accessLevels){const accessLevelsShort=accessLevels.map(level=>LevelMap[level]).join("");entriesArray.push(`${hashedOwnerKey}/${accessLevelsShort}`)}entriesArray.length>0&&(compressed+=`${roleShort}:${entriesArray.join(",")}|`)}return compressed.endsWith("|")&&(compressed=compressed.slice(0,-1)),compressed}deserializeACL(compressed){const parts=compressed.split("|");this.hashAlgorithm="",this.entries={};for(const part of parts)if(part.startsWith("h:"))this.hashAlgorithm=part.substring(2);else{const[roleShort,entries]=part.split(":"),role=ReverseRoleMap[roleShort];if(role){const entriesObj={},entriesArray=entries.split(",");for(const entry of entriesArray){const[hashedOwnerKey,accessLevelsShort]=entry.split("/"),accessLevels=accessLevelsShort.split("").map(short=>ReverseLevelMap[short]);entriesObj[hashedOwnerKey]=accessLevels}this.entries[role]=entriesObj}}}}const console$s=Logger("SecureConnector");class SecureConnector extends Connector{async start(){console$s.info(`Starting ${this.name} connector ...`)}async stop(){console$s.info(`Stopping ${this.name} connector ...`)}async hasAccess(acRequest){const aclHelper=await this.getResourceACL(acRequest.resourceId,acRequest.candidate).catch(error=>(console$s.error(`Error getting ACL for ${acRequest.resourceId}: ${error}`),null));if(!aclHelper)return!1;if(aclHelper.checkExactAccess(acRequest))return!0;const ownerRequest=AccessRequest.clone(acRequest).setLevel(TAccessLevel.Owner);if(aclHelper.checkExactAccess(ownerRequest))return!0;const publicRequest=AccessRequest.clone(acRequest).setCandidate(AccessCandidate.public());if(aclHelper.checkExactAccess(publicRequest))return!0;const teamId=await ConnectorService.getAccountConnector().getCandidateTeam(acRequest.candidate),teamRequest=AccessRequest.clone(acRequest).setCandidate(AccessCandidate.team(teamId));if(aclHelper.checkExactAccess(teamRequest))return!0;const teamOwnerRequest=AccessRequest.clone(teamRequest).setLevel(TAccessLevel.Owner);return!!aclHelper.checkExactAccess(teamOwnerRequest)}async getAccessTicket(resourceId,request){const sysAcRequest=AccessRequest.clone(request).resource(resourceId);return{request,access:await this.hasAccess(sysAcRequest)?TAccessResult.Granted:TAccessResult.Denied}}static AccessControl(target,propertyKey,descriptor){const originalMethod=descriptor.value;return descriptor.value=async function(...args){const[acRequest,resourceId]=args;if(resourceId!==void 0&&(await this.getAccessTicket(resourceId,acRequest)).access!==TAccessResult.Granted)throw console$s.error(`Access denied for ${acRequest.candidate.id} on ${resourceId}`),new ACLAccessDeniedError("Access Denied");return originalMethod.apply(this,args)},descriptor}}class StorageConnector extends SecureConnector{requester(candidate){return{write:async(resourceId,value,acl,metadata)=>await this.write(candidate.writeRequest,resourceId,value,acl,metadata),read:async resourceId=>await this.read(candidate.readRequest,resourceId),delete:async resourceId=>{await this.delete(candidate.readRequest,resourceId)},exists:async resourceId=>await this.exists(candidate.readRequest,resourceId),getMetadata:async resourceId=>await this.getMetadata(candidate.readRequest,resourceId),setMetadata:async(resourceId,metadata)=>{await this.setMetadata(candidate.writeRequest,resourceId,metadata)},getACL:async resourceId=>await this.getACL(candidate.readRequest,resourceId),setACL:async(resourceId,acl)=>await this.setACL(candidate.writeRequest,resourceId,acl),expire:async(resourceId,ttl)=>await this.expire(candidate.writeRequest,resourceId,ttl)}}}class CacheConnector extends SecureConnector{requester(candidate){return{get:async key=>await this.get(candidate.readRequest,key),set:async(key,data,acl,metadata,ttl)=>await this.set(candidate.writeRequest,key,data,acl,metadata,ttl),delete:async key=>{await this.delete(candidate.writeRequest,key)},exists:async key=>await this.exists(candidate.readRequest,key),getMetadata:async key=>await this.getMetadata(candidate.readRequest,key),setMetadata:async(key,metadata)=>{await this.setMetadata(candidate.writeRequest,key,metadata)},updateTTL:async(key,ttl)=>{await this.updateTTL(candidate.writeRequest,key,ttl)},getTTL:async key=>await this.getTTL(candidate.readRequest,key),getACL:async key=>await this.getACL(candidate.readRequest,key),setACL:async(key,acl)=>{await this.setACL(candidate.writeRequest,key,acl)}}}}var __defProp$1u=Object.defineProperty,__defNormalProp$1u=(obj,key,value)=>key in obj?__defProp$1u(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1u=(obj,key,value)=>__defNormalProp$1u(obj,key+"",value);class JSONContentHelper{constructor(dataString){this.dataString=dataString,__publicField$1u(this,"_current"),this._current=dataString}get result(){return this._current}static create(dataString){return new JSONContentHelper(dataString)}tryParse(){const strInput=this._current;if(!isValidString(strInput)||isDigits(strInput)||isSafeNumber(strInput))return strInput;let str=strInput.trim();if(str.startsWith("{")&&str.endsWith("}")||str.startsWith("[")&&str.endsWith("]"))try{return JSON.parse(str)}catch{try{const repairedJson=jsonrepair(str);return JSON.parse(repairedJson)}catch{}}if(str=(this.extractJsonFromString(strInput)||strInput).trim(),isDigits(str)&&!isSafeNumber(str)||!str.startsWith("{")&&!str.startsWith("["))return str;try{return JSON.parse(str)}catch{try{const repairedJson=jsonrepair(str);return JSON.parse(repairedJson)}catch{return strInput}}}tryFullParse(){const str=this._current;if(!str||isDigits(str)&&!isSafeNumber(str)||!str.startsWith("{")&&!str.startsWith("["))return str;try{return JSON.parse(str)}catch{try{return JSON.parse(jsonrepair(str))}catch(e2){return console.warn("Error on parseJson: ",e2.toString()),console.warn(" Tried to parse: ",str),{result:str,error:e2.toString()}}}}extractJsonFromString(str){try{const regex=/(\{.*\})/s;return str.match(regex)?.[1]}catch{return null}}}function JSONContent(dataString){return JSONContentHelper.create(dataString)}var __defProp$1t=Object.defineProperty,__defNormalProp$1t=(obj,key,value)=>key in obj?__defProp$1t(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1t=(obj,key,value)=>__defNormalProp$1t(obj,typeof key!="symbol"?key+"":key,value);const _SmythFS=class _SmythFS2{constructor(storage,cache){if(this.storage=storage,this.cache=cache,__publicField$1t(this,"hash"),!ConnectorService.ready)throw new Error("SRE not available");this.hash=_SmythFS2.generateInstanceHash(this.storage.name,this.cache.name)}static generateInstanceHash(storageName,cacheName){const instanceProps=`${storageName}:${cacheName}`;return crypto$1.createHash("sha256").update(instanceProps).digest("hex").substring(0,6)}static get Instance(){return _SmythFS2.getInstance()}static getInstance(storageProvider="",cacheProvider=""){const storage=storageProvider instanceof StorageConnector?storageProvider:ConnectorService.getStorageConnector(storageProvider),cache=cacheProvider instanceof CacheConnector?cacheProvider:ConnectorService.getCacheConnector(cacheProvider),hash=_SmythFS2.generateInstanceHash(storage.name,cache.name);if(_SmythFS2.instances[hash])return _SmythFS2.instances[hash];const instance=new _SmythFS2(storage,cache),router=ConnectorService.getRouterConnector();return router&&router?.get instanceof Function&&(router.get(`/_temp/${hash}/:uid`,instance.serveTempContent.bind(instance)),router.get(`/storage/${hash}/:file_id`,instance.serveResource.bind(instance))),_SmythFS2.instances[hash]=instance,instance}getBaseUri(candidate){return`smythfs://${candidate.id}.${candidate.role}`}async read(uri,candidate){const smythURI=await this.URIParser(uri);if(!smythURI)throw new Error("Invalid Resource URI");if(candidate=candidate||smythURI.defaultCandidate,!await ConnectorService.getAccountConnector().isTeamMember(smythURI.team,candidate))throw new Error("Access Denied");const resourceId=`teams/${smythURI.team}${smythURI.path}`,_candidate=candidate instanceof AccessCandidate?candidate:new AccessCandidate(candidate),data=await this.storage.requester(_candidate).read(resourceId);return data?this.toBuffer(data):null}async getMetadata(uri,candidate){const smythURI=await this.URIParser(uri);if(!smythURI)throw new Error("Invalid Resource URI");if(candidate=candidate||smythURI.defaultCandidate,!await ConnectorService.getAccountConnector().isTeamMember(smythURI.team,candidate))throw new Error("Access Denied");const resourceId=`teams/${smythURI.team}${smythURI.path}`,_candidate=candidate instanceof AccessCandidate?candidate:new AccessCandidate(candidate);return await this.storage.requester(_candidate).getMetadata(resourceId)}async write(uri,data,candidate,metadata,ttl){const smythURI=await this.URIParser(uri);if(!smythURI)throw new Error("Invalid Resource URI");if(candidate=candidate||smythURI.defaultCandidate,!await ConnectorService.getAccountConnector().isTeamMember(smythURI.team,candidate))throw new Error("Access Denied");const resourceId=`teams/${smythURI.team}${smythURI.path}`,_candidate=candidate instanceof AccessCandidate?candidate:new AccessCandidate(candidate);let acl;if(smythURI.team&&smythURI.team!==DEFAULT_TEAM_ID&&(acl=new ACL().addAccess(TAccessRole.Team,smythURI.team,TAccessLevel.Read).ACL),metadata||(metadata={}),!metadata?.ContentType&&(metadata.ContentType=await getMimeType(data),!metadata.ContentType)){const ext=uri.split(".").pop();ext&&(metadata.ContentType=mime.getType(ext)||"application/octet-stream")}await this.storage.requester(_candidate).write(resourceId,data,acl,metadata),ttl&&await this.storage.requester(_candidate).expire(resourceId,ttl)}async delete(uri,candidate){const smythURI=await this.URIParser(uri);if(!smythURI)throw new Error("Invalid Resource URI");if(candidate=candidate||smythURI.defaultCandidate,!await ConnectorService.getAccountConnector().isTeamMember(smythURI.team,candidate))throw new Error("Access Denied");const resourceId=`teams/${smythURI.team}${smythURI.path}`,_candidate=candidate instanceof AccessCandidate?candidate:new AccessCandidate(candidate);await this.storage.requester(_candidate).delete(resourceId)}async exists(uri,candidate){const smythURI=await this.URIParser(uri);if(!smythURI)throw new Error("Invalid Resource URI");if(candidate=candidate||smythURI.defaultCandidate,!await ConnectorService.getAccountConnector().isTeamMember(smythURI.team,candidate))throw new Error("Access Denied");const resourceId=`teams/${smythURI.team}${smythURI.path}`,_candidate=candidate instanceof AccessCandidate?candidate:new AccessCandidate(candidate);return await this.storage.requester(_candidate).exists(resourceId)}async genTempUrl(uri,candidate,ttlSeconds=3600){const smythURI=await this.URIParser(uri);if(!smythURI)throw new Error("Invalid Resource URI");if(candidate=candidate||smythURI.defaultCandidate,!await ConnectorService.getAccountConnector().isTeamMember(smythURI.team,candidate))throw new Error("Access Denied");if(!await this.exists(uri,candidate))throw new Error("Resource does not exist");const _candidate=candidate instanceof AccessCandidate?candidate:new AccessCandidate(candidate),resourceId=`teams/${smythURI.team}${smythURI.path}`,resourceMetadata=await this.storage.requester(_candidate).getMetadata(resourceId),uid2=crypto$1.randomUUID(),tempUserCandidate=AccessCandidate.user(`system-${uid2}`);return await this.cache.requester(tempUserCandidate).set(`pub_url:${uid2}`,JSON.stringify({accessCandidate:_candidate,uri,contentType:resourceMetadata?.ContentType}),void 0,void 0,ttlSeconds),`${ConnectorService.getRouterConnector().baseUrl}/_temp/${this.hash}/${uid2}`}async destroyTempUrl(url,{delResource}={delResource:!1}){const tempPath=url.split("/_temp/")[1];if(!tempPath)throw new Error("Invalid Temp URL format");const uid2=tempPath.split("/")[1]?.split("?")[0];if(!uid2)throw new Error("Invalid Temp URL format");let cacheVal=await this.cache.requester(AccessCandidate.user(`system-${uid2}`)).get(`pub_url:${uid2}`);if(!cacheVal)throw new Error("Invalid Temp URL");cacheVal=JSONContentHelper.create(cacheVal).tryParse(),await this.cache.requester(AccessCandidate.user(`system-${uid2}`)).delete(`pub_url:${uid2}`),delResource&&await this.delete(cacheVal.uri,AccessCandidate.clone(cacheVal.accessCandidate))}async serveTempContent(req,res){try{const{uid:uid2}=req.params;let cacheVal=await this.cache.requester(AccessCandidate.user(`system-${uid2}`)).get(`pub_url:${uid2}`);if(!cacheVal){res.writeHead(404,{"Content-Type":"text/plain"}),res.end("Invalid Temp URL");return}cacheVal=JSONContentHelper.create(cacheVal).tryParse();const content=await this.read(cacheVal.uri,AccessCandidate.clone(cacheVal.accessCandidate)),contentBuffer=Buffer.isBuffer(content)?content:Buffer.from(content,"binary"),contentType=cacheVal.contentType||"application/octet-stream";res.writeHead(200,{"Content-Type":contentType,"Content-Disposition":"inline","Content-Length":contentBuffer.length}),res.end(contentBuffer)}catch(error){console.error("Error serving temp content:",error),res.writeHead(500,{"Content-Type":"text/plain"}),res.end("Internal Server Error")}}async genResourceUrl(uri,candidate){const smythURI=await this.URIParser(uri);if(!smythURI)throw new Error("Invalid Resource URI");if(candidate=candidate||smythURI.defaultCandidate,!await ConnectorService.getAccountConnector().isTeamMember(smythURI.team,candidate))throw new Error("Access Denied");if(!await this.exists(uri,candidate))throw new Error("Resource does not exist");const _candidate=candidate instanceof AccessCandidate?candidate:new AccessCandidate(candidate);if(_candidate.role!==TAccessRole.Agent)throw new Error("Only agents can generate resource urls");const agentId=_candidate.id,resourceId=`teams/${smythURI.team}${smythURI.path}`,resourceMetadata=await this.storage.requester(_candidate).getMetadata(resourceId),uid2=crypto$1.randomUUID(),tempUserCandidate=AccessCandidate.user(`system-${uid2}`);await this.cache.requester(tempUserCandidate).set(`storage_url-${uid2}`,JSON.stringify({accessCandidate:_candidate,uri,contentType:resourceMetadata?.ContentType}),void 0,void 0);const contentType=resourceMetadata?.ContentType,ext=contentType?mime.getExtension(contentType):void 0,agentDataConnector=ConnectorService.getAgentDataConnector(),baseUrl=ConnectorService.getRouterConnector().baseUrl;return`${agentDataConnector.getAgentConfig(agentId)?.agentStageDomain?`https://${agentDataConnector.getAgentConfig(agentId).agentStageDomain}`:baseUrl}/storage/${this.hash}/${uid2}${ext?`.${ext}`:""}`}async destroyResourceUrl(url,{delResource}={delResource:!1}){}async serveResource(req,res){try{const{file_id}=req.params,[uid2,extention]=file_id.split(".");let cacheVal=await this.cache.requester(AccessCandidate.user(`system-${uid2}`)).get(`storage_url-${uid2}`);if(!cacheVal){res.writeHead(404,{"Content-Type":"text/plain"}),res.end("Invalid Resource URL");return}cacheVal=JSONContentHelper.create(cacheVal).tryParse();const content=await this.read(cacheVal.uri,AccessCandidate.clone(cacheVal.accessCandidate)),contentBuffer=Buffer.isBuffer(content)?content:Buffer.from(content,"binary"),contentType=cacheVal.contentType||"application/octet-stream";res.writeHead(200,{"Content-Type":contentType,"Content-Disposition":"inline","Content-Length":contentBuffer.length}),res.end(contentBuffer)}catch(error){console.error("Error serving storage resource content:",error),res.writeHead(500,{"Content-Type":"text/plain"}),res.end("Internal Server Error")}}async URIParser(uri){const parts=uri.split("://");if(parts.length!==2||parts[0].toLowerCase()!=="smythfs")return;const parsed=this.CaseSensitiveURL(`http://${parts[1]}`),tld=parsed.hostname.split(".").pop();if(tld!=="team"&&tld!=="user"&&tld!=="agent"&&tld!=="smyth")throw new Error("Invalid Resource URI");let team=tld==="team"?parsed.hostname.replace(`.${tld}`,""):void 0;const user=tld==="user"?parsed.hostname.replace(`.${tld}`,""):void 0,agent=tld==="agent"?parsed.hostname.replace(`.${tld}`,""):void 0,smyth=tld==="smyth"?parsed.hostname.replace(`.${tld}`,""):void 0;let basePath="";if(!team){let candidate;user?(candidate=AccessCandidate.user(user),basePath=".user/"+user):agent&&(candidate=AccessCandidate.agent(agent),basePath=".agent/"+agent),candidate&&(team=await ConnectorService.getAccountConnector().getCandidateTeam(candidate))}let defaultCandidate;return team?defaultCandidate=AccessCandidate.team(team):user?defaultCandidate=AccessCandidate.user(user):agent&&(defaultCandidate=AccessCandidate.agent(agent)),{hash:parsed.hash,team,user,agent,smyth,defaultCandidate,path:basePath+parsed.pathname}}CaseSensitiveURL(urlString){const parts=urlString.split("://");if(parts.length!==2)return null;const afterProtocol=parts[1],hostnameEnd=Math.min(...[afterProtocol.indexOf("/"),afterProtocol.indexOf("?"),afterProtocol.indexOf("#"),afterProtocol.length].filter(i=>i>=0)),originalHostnamePart=afterProtocol.substring(0,hostnameEnd),[originalHostname,originalPort]=originalHostnamePart.split(":"),parsed=new URL(urlString);return{protocol:parsed.protocol,hostname:originalHostname,port:parsed.port,pathname:parsed.pathname,search:parsed.search,searchParams:parsed.searchParams,hash:parsed.hash,href:parsed.href,origin:parsed.origin,host:originalHostname+(parsed.port?`:${parsed.port}`:""),originalPort:originalPort||null}}async toBuffer(data){if(Buffer.isBuffer(data))return data;if(typeof data=="string")return Buffer.from(data,"utf-8");if(data instanceof Uint8Array)return Buffer.from(data);if(data instanceof Readable)return new Promise((resolve,reject)=>{const chunks=[];data.on("data",chunk=>{chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk))}),data.on("end",()=>{resolve(Buffer.concat(chunks))}),data.on("error",err=>{reject(err)})});throw new Error("Unsupported data type")}};__publicField$1t(_SmythFS,"instances",{});let SmythFS=_SmythFS;var __defProp$1s=Object.defineProperty,__defNormalProp$1s=(obj,key,value)=>key in obj?__defProp$1s(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1s=(obj,key,value)=>__defNormalProp$1s(obj,typeof key!="symbol"?key+"":key,value);class BinaryInput{constructor(data,_name,mimetype,candidate){this._name=_name,this.mimetype=mimetype,this.candidate=candidate,__publicField$1s(this,"size"),__publicField$1s(this,"url"),__publicField$1s(this,"_ready"),__publicField$1s(this,"_readyPromise"),__publicField$1s(this,"_source"),__publicField$1s(this,"_uploading",!1),_name||(_name=uid()),this._name=_name,this.load(data,_name,mimetype,candidate)}async ready(){return this._ready?!0:(this._readyPromise||(this._readyPromise=new Promise(resolve=>{const interval=setInterval(()=>{this._ready&&(clearInterval(interval),resolve(!0))},100)})),this._readyPromise)}async load(data,name,mimetype,candidate){const ext=name.split(".")?.length>1?name.split(".").pop():"";if(this.mimetype=mimetype||mime.getType(ext)||"",this.url="",typeof data=="object"&&data.url&&data.mimetype&&data.size){this.mimetype=data.mimetype,this.size=data.size,this.url=data.url;const ext2=mime.getExtension(this.mimetype);this._name.endsWith(`.${ext2}`)||(this._name+=`.${ext2}`),candidate?this._source=await SmythFS.Instance.read(this.url,candidate).finally(()=>{this._ready=!0}):this._ready=!0;return}if(typeof data=="string"&&data.startsWith("smythfs://")){if(this.url=data,candidate)try{this._source=await SmythFS.Instance.read(this.url,candidate),this.mimetype=await getMimeType(this._source),this.size=this._source.byteLength,this.mimetype||(this.mimetype=mime.getType(this.url)||mime.getType(this._name)||"");const ext2=mime.getExtension(this.mimetype);this._name.endsWith(`.${ext2}`)||(this._name+=`.${ext2}`)}finally{this._ready=!0}else this._ready=!0;return}if(isUrl(data)){try{const response=await axios({method:"get",url:data,responseType:"arraybuffer"});this.size=response.data.byteLength,this._source=Buffer.from(response.data,"binary");let mimetype2=response.headers?.["content-type"]||"";const urlPath=new URL(data).pathname;let extension=urlPath.split(".")?.length>1?urlPath.split(".").pop():"";(!mimetype2||mimetype2.startsWith("binary/octet-stream"))&&(mimetype2=extension?mime.getType(extension):""),mimetype2||(mimetype2=(await fileTypeFromBuffer(this._source))?.mime||""),this.mimetype=mimetype2,extension=extension||mime.getExtension(this.mimetype),this._name.endsWith(`.${extension}`)||(this._name+=`.${extension}`)}catch(error){console.error("Error loading binary data from url:",data.url,error)}this._ready=!0;return}const base64FileInfo=await getBase64FileInfo(data);if(base64FileInfo){this.mimetype||(this.mimetype=base64FileInfo.mimetype),this.size=base64FileInfo.size,this._source=Buffer.from(base64FileInfo.data,"base64");const ext2=mime.getExtension(this.mimetype);this._name.endsWith(`.${ext2}`)||(this._name+=`.${ext2}`),this._ready=!0;return}if(typeof data=="string"){this._source=Buffer.from(data),this.size=data.length,this.mimetype="text/plain",this._name.endsWith(".txt")||(this._name+=".txt"),this._ready=!0;return}if(Buffer.isBuffer(data)){this._source=data,this.size=getSizeFromBinary(data),this.mimetype||(this.mimetype=await getMimeType(data));const ext2=mime.getExtension(this.mimetype);this._name.endsWith(`.${ext2}`)||(this._name+=`.${ext2}`),this._ready=!0;return}if(data instanceof Blob){this._source=Buffer.from(await data.arrayBuffer()),this.size=data.size,this.mimetype=data.type,this._ready=!0;return}}async getUrlInfo(url){try{const response=await axios.get(url),contentType=response.headers["content-type"],contentLength=response.headers["content-length"];return{contentType,contentLength}}catch{return{contentType:"",contentLength:0}}}static from(data,name,mimetype,candidate){return data instanceof BinaryInput?data:new BinaryInput(data,name,mimetype,candidate)}async upload(candidate,ttl){if(await this.ready(),!this._uploading)try{if(this._uploading=!0,this.url)this._uploading=!1;else{const teamId=await ConnectorService.getAccountConnector().getCandidateTeam(candidate);this.url=`smythfs://${teamId}.team/${candidate.id}/_temp/${this._name}`,await SmythFS.Instance.write(this.url,this._source,candidate,void 0,ttl),this._uploading=!1}}catch(error){console.error("Error uploading binary data:",error),this._uploading=!1}}async getJsonData(candidate,ttl){return await this.upload(candidate,ttl),{mimetype:this.mimetype,size:this.size,url:this.url,name:this._name}}async readData(candidate){if(await this.ready(),!this.url)throw new Error("Binary data not ready");return await SmythFS.Instance.read(this.url,candidate)}async getName(){return await this.ready(),this._name}async getBuffer(){return await this.ready(),this._source}async getReadStream(){return await this.ready(),Readable.from(this._source)}}var TLLMCredentials=(TLLMCredentials2=>(TLLMCredentials2.Vault="vault",TLLMCredentials2.Internal="internal",TLLMCredentials2.BedrockVault="bedrock_vault",TLLMCredentials2.VertexAIVault="vertexai_vault",TLLMCredentials2.None="none",TLLMCredentials2))(TLLMCredentials||{});const BuiltinLLMProviders={Echo:"Echo",OpenAI:"OpenAI",DeepSeek:"DeepSeek",GoogleAI:"GoogleAI",Anthropic:"Anthropic",Groq:"Groq",TogetherAI:"TogetherAI",Bedrock:"Bedrock",VertexAI:"VertexAI",xAI:"xAI",Perplexity:"Perplexity"},TLLMProvider=BuiltinLLMProviders;var TLLMMessageRole=(TLLMMessageRole2=>(TLLMMessageRole2.User="user",TLLMMessageRole2.Assistant="assistant",TLLMMessageRole2.System="system",TLLMMessageRole2.Model="model",TLLMMessageRole2.Tool="tool",TLLMMessageRole2.Function="function",TLLMMessageRole2))(TLLMMessageRole||{}),APIKeySource=(APIKeySource2=>(APIKeySource2.Smyth="smyth-managed",APIKeySource2.User="user-managed",APIKeySource2.Custom="custom",APIKeySource2))(APIKeySource||{}),TLLMEvent=(TLLMEvent2=>(TLLMEvent2.Data="data",TLLMEvent2.Content="content",TLLMEvent2.Thinking="thinking",TLLMEvent2.End="end",TLLMEvent2.Error="error",TLLMEvent2.ToolInfo="toolInfo",TLLMEvent2.ToolCall="toolCall",TLLMEvent2.ToolResult="toolResult",TLLMEvent2.Usage="usage",TLLMEvent2.Interrupted="interrupted",TLLMEvent2))(TLLMEvent||{});function isAgent(agent){return typeof agent=="object"&&agent.id&&typeof agent.callComponent=="function"}var __defProp$1r=Object.defineProperty,__defNormalProp$1r=(obj,key,value)=>key in obj?__defProp$1r(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1r=(obj,key,value)=>__defNormalProp$1r(obj,typeof key!="symbol"?key+"":key,value);const console$r=Logger("LLMInference");let LLMInference$1=class LLMInference{constructor(){__publicField$1r(this,"model"),__publicField$1r(this,"llmConnector"),__publicField$1r(this,"modelProviderReq"),__publicField$1r(this,"teamId")}static async getInstance(model,candidate){const modelsProvider=ConnectorService.getModelsProviderConnector();if(!modelsProvider.valid)throw new Error("Model provider Not available, cannot create LLM instance");const teamId=await ConnectorService.getAccountConnector().requester(candidate).getTeam(),llmInference=new LLMInference;llmInference.teamId=teamId,llmInference.modelProviderReq=modelsProvider.requester(candidate);const llmProvider=await llmInference.modelProviderReq.getProvider(model);return llmProvider&&(llmInference.llmConnector=ConnectorService.getLLMConnector(llmProvider)),llmInference.llmConnector||console$r.error(`Model ${model} unavailable for team ${teamId}`),llmInference.model=model,llmInference}static user(candidate){}get connector(){return this.llmConnector}async prompt({query,contextWindow,files,params}){let messages=contextWindow||[];if(query){const content=this.llmConnector.enhancePrompt(query,params);messages.push({role:TLLMMessageRole.User,content})}params.model||(params.model=this.model),params.messages=messages,params.files=files;try{let response=await this.llmConnector.requester(AccessCandidate.agent(params.agentId)).request(params);const result=this.llmConnector.postProcess(response?.content);if(result.error)throw response.finishReason!=="stop"?new Error("The model stopped before completing the response, this is usually due to output token limit reached."):new Error(result.error);return result}catch(error){throw console$r.error("Error in chatRequest: ",error),error}}async promptStream({query,contextWindow,files,params}){let messages=contextWindow||[];if(query){const content=this.llmConnector.enhancePrompt(query,params);messages.push({role:TLLMMessageRole.User,content})}params.model||(params.model=this.model),params.messages=messages,params.files=files;try{return await this.llmConnector.user(AccessCandidate.agent(params.agentId)).streamRequest(params)}catch(error){console$r.error("Error in streamRequest:",error);const dummyEmitter=new EventEmitter;return process.nextTick(()=>{dummyEmitter.emit("error",error),dummyEmitter.emit("end")}),dummyEmitter}}async imageGenRequest({query,files,params}){return params.prompt=query,this.llmConnector.user(AccessCandidate.agent(params.agentId)).imageGenRequest(params)}async imageEditRequest({query,files,params}){return params.prompt=query,params.files=files,this.llmConnector.user(AccessCandidate.agent(params.agentId)).imageEditRequest(params)}async streamRequest(params,agent){const agentId=isAgent(agent)?agent.id:agent;try{if(!params.messages||!params.messages?.length)throw new Error("Input messages are required.");const model=params.model||this.model;return await this.llmConnector.user(AccessCandidate.agent(agentId)).streamRequest({...params,model})}catch(error){console$r.error("Error in streamRequest:",error);const dummyEmitter=new EventEmitter;return process.nextTick(()=>{dummyEmitter.emit("error",error),dummyEmitter.emit("end")}),dummyEmitter}}async multimodalStreamRequest(params,fileSources,agent){const agentId=isAgent(agent)?agent.id:agent,promises=[],_fileSources=[];for(let file of fileSources){const binaryInput=BinaryInput.from(file);_fileSources.push(binaryInput),promises.push(binaryInput.upload(AccessCandidate.agent(agentId)))}await Promise.all(promises),params.fileSources=_fileSources;try{const prompt=(Array.isArray(params.messages)?params.messages.pop():{})?.content||"",model=params.model||this.model;return await this.llmConnector.user(AccessCandidate.agent(agentId)).multimodalStreamRequest(prompt,{...params,model})}catch(error){throw console$r.error("Error in multimodalRequest: ",error),error}}async multimodalStreamRequestLegacy(prompt,files,config2={},agent){const agentId=isAgent(agent)?agent.id:agent,promises=[],_files=[];for(let file of files){const binaryInput=BinaryInput.from(file);_files.push(binaryInput),promises.push(binaryInput.upload(AccessCandidate.agent(agentId)))}await Promise.all(promises);const params=config2.data;params.files=_files;try{prompt=this.llmConnector.enhancePrompt(prompt,config2);const model=params.model||this.model;return await this.llmConnector.user(AccessCandidate.agent(agentId)).multimodalStreamRequest(prompt,{...params,model})}catch(error){throw console$r.error("Error in multimodalRequest: ",error),error}}async getContextWindow(systemPrompt,_messages,maxTokens,maxOutputTokens=1024){const modelInfo=await this.modelProviderReq.getModelInfo(this.model,!0);let maxModelContext=modelInfo?.tokens,maxModelOutputTokens=modelInfo?.completionTokens||modelInfo?.tokens,maxInputContext=Math.min(maxTokens,maxModelContext),maxOutputContext=Math.min(maxOutputTokens,maxModelOutputTokens||0);maxInputContext+maxOutputContext>maxModelContext&&(maxInputContext-=maxInputContext+maxOutputContext-maxModelContext),maxInputContext<=0&&console$r.warn("Max input context is 0, returning empty context window, This usually indicates a wrong model configuration"),console$r.debug(`Context Window Configuration: Max Input Tokens: ${maxInputContext}, Max Output Tokens: ${maxOutputContext}, Max Model Tokens: ${maxModelContext}`);const systemMessage={role:"system",content:systemPrompt};let smythContextWindow=[],tokensCount=encodeChat([systemMessage],"gpt-4o").length;for(let i=_messages?.length-1;i>=0;i--){const curMessage=_messages[i];if(curMessage.role!=="system"){if(tokensCount=0,curMessage?.content&&(tokensCount+=countTokens(curMessage.content)),curMessage?.messageBlock?.content&&(tokensCount+=countTokens(curMessage.messageBlock.content)),curMessage.toolsData)for(let tool of curMessage.toolsData)tokensCount+=countTokens(tool.result);if(tokensCount>maxInputContext)break;smythContextWindow.unshift(curMessage)}}smythContextWindow.unshift(systemMessage);let modelContextWindow=[];for(let message of smythContextWindow)if(message.role&&message.content&&modelContextWindow.push({role:message.role,content:message.content}),message.messageBlock&&message.toolsData){const internal_message=this.connector.transformToolMessageBlocks({messageBlock:message?.messageBlock,toolsData:message?.toolsData});modelContextWindow.push(...internal_message)}return modelContextWindow=this.connector.getConsistentMessages(modelContextWindow),modelContextWindow}};function countTokens(content,model="gpt-4o"){try{const _stringifiedContent=typeof content=="string"?content:JSON.stringify(content);return encodeChat([{role:"user",content:_stringifiedContent}],model).length}catch(error){return console$r.warn("Error in countTokens: ",error),0}}var __defProp$1q=Object.defineProperty,__defNormalProp$1q=(obj,key,value)=>key in obj?__defProp$1q(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1q=(obj,key,value)=>__defNormalProp$1q(obj,typeof key!="symbol"?key+"":key,value);class LLMContext{constructor(llmInference,_systemPrompt="",llmContextStore){this.llmInference=llmInference,__publicField$1q(this,"_systemPrompt",""),__publicField$1q(this,"_llmContextStore"),__publicField$1q(this,"_llmCache"),__publicField$1q(this,"contextLength"),__publicField$1q(this,"_messages",[]),this._llmCache=new LLMCache(AccessCandidate.team(this.llmInference.teamId)),this.systemPrompt=_systemPrompt,llmContextStore&&(this._llmContextStore=llmContextStore,this._llmContextStore.load().then(messages=>{this._messages=messages,this._llmCache.set("messages",this._messages)}))}get systemPrompt(){return this._systemPrompt}set systemPrompt(systemPrompt){this._systemPrompt=systemPrompt,this._llmCache?.set("systemPrompt",this.systemPrompt)}get llmCache(){return this._llmCache}get messages(){return this._messages}get model(){return this.llmInference.model}push(...message){this._messages.push(...message),this._llmContextStore&&this._llmContextStore.save(this._messages),this._llmCache.set("messages",this._messages)}addUserMessage(content,message_id,metadata){const lastMessage=this._messages[this._messages.length-1];lastMessage&&(lastMessage.__smyth_data__?.next||(lastMessage.__smyth_data__.next=[]),lastMessage.__smyth_data__.next.push(message_id));const prev=lastMessage?.__smyth_data__?.message_id,next=[];this.push({role:"user",content,__smyth_data__:{message_id,...metadata,prev,next}})}addAssistantMessage(content,message_id,metadata){const lastMessage=this._messages[this._messages.length-1];lastMessage&&(lastMessage.__smyth_data__?.next||(lastMessage.__smyth_data__.next=[]),lastMessage.__smyth_data__.next.push(message_id));const prev=lastMessage?.__smyth_data__?.message_id,next=[];this.push({role:"assistant",content,__smyth_data__:{message_id,...metadata,prev,next}})}addToolMessage(messageBlock,toolsData,message_id,metadata){const lastMessage=this._messages[this._messages.length-1];lastMessage&&(lastMessage.__smyth_data__?.next||(lastMessage.__smyth_data__.next=[]),lastMessage.__smyth_data__.next.push(message_id));const prev=lastMessage?.__smyth_data__?.message_id,next=[];this.push({messageBlock,toolsData,__smyth_data__:{message_id,...metadata,prev,next}})}async getContextWindow(maxTokens,maxOutputTokens=1024){const messages=JSON.parse(JSON.stringify(this._messages));return this.llmInference.getContextWindow(this.systemPrompt,messages,maxTokens,maxOutputTokens)}}const dereferenceSchema=async(schema,root=schema)=>{if(typeof schema!="object"||schema===null)return schema;if(schema.$ref){const ref=schema.$ref,path2=ref.replace(/^#\//,"").split("/");let resolved=root;for(const segment of path2){if(resolved[segment]===void 0)throw new Error(`Could not resolve $ref: ${ref}`);resolved=resolved[segment]}return dereferenceSchema(resolved,root)}if(Array.isArray(schema))return Promise.all(schema.map(item=>dereferenceSchema(item,root)));const result={};for(const key of Object.keys(schema))result[key]=await dereferenceSchema(schema[key],root);return result};class OpenAPIParser{static mapReqMethods(paths){const methods=new Map;for(const path2 in paths){const pathData=paths[path2];for(const method in pathData){const data=pathData[method];REQUEST_METHODS.includes(method.toUpperCase())&&methods.set(data?.operationId,method)}}return methods}static mapEndpoints(paths){const operationIds=new Map;for(const path2 in paths){const pathData=paths[path2];for(const method in pathData){const data=pathData[method];REQUEST_METHODS.includes(method.toUpperCase())&&operationIds.set(data?.operationId,path2)}}return operationIds}static async yamlToJson(yamlData){const data=yaml.load(yamlData);return await dereferenceSchema(data)}static async getJson(data){try{let parsedData=data;return typeof data=="string"&&(parsedData=JSON.parse(data)),await dereferenceSchema(parsedData)}catch{try{return await OpenAPIParser.yamlToJson(data)}catch{throw new Error("Invalid OpenAPI specification or JSON data format")}}}static async getJsonFromUrl(url){const data=(await axios.get(url)).data;return OpenAPIParser.getJson(data)}static isValidOpenAPI(data){return data?.openapi&&data?.paths&&data?.servers}}const hooks={};class HookService{static register(hookName,callback){if(typeof callback!="function")throw new Error("Hook callback must be a function");hooks[hookName]||(hooks[hookName]=[]),hooks[hookName].push(callback)}static trigger(hookName,...args){hooks[hookName]&&hooks[hookName].forEach(callback=>callback(...args))}}function hook(hookName){return function(target,propertyKey,descriptor){const originalMethod=descriptor.value;return descriptor.value=function(...args){return hooks[hookName]&&hooks[hookName].forEach(callback=>{callback.apply(this,args)}),originalMethod.apply(this,args)},descriptor}}function hookAsync(hookName){return function(target,propertyKey,descriptor){const originalMethod=descriptor.value;return descriptor.value=async function(...args){return hooks[hookName]&&await Promise.all(hooks[hookName].map(callback=>callback.apply(this,args))),originalMethod.apply(this,args)},descriptor}}function hookAsyncWithContext(hookName,contextFn){return function(target,propertyKey,descriptor){const originalMethod=descriptor.value;return descriptor.value=async function(...args){if(hooks[hookName]){const additionalContext=typeof contextFn=="function"?await contextFn(this):{};await Promise.all(hooks[hookName].map(callback=>callback.apply(this,[additionalContext,...args])))}return originalMethod.apply(this,args)},descriptor}}var __defProp$1p=Object.defineProperty,__getOwnPropDesc$l=Object.getOwnPropertyDescriptor,__defNormalProp$1p=(obj,key,value)=>key in obj?__defProp$1p(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__decorateClass$l=(decorators,target,key,kind)=>{for(var result=__getOwnPropDesc$l(target,key),i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=decorator(target,key,result)||result);return result&&__defProp$1p(target,key,result),result},__publicField$1p=(obj,key,value)=>__defNormalProp$1p(obj,typeof key!="symbol"?key+"":key,value);const console$q=Logger("ConversationHelper");class Conversation extends EventEmitter$1{constructor(_model,_specSource,_settings){super(),this._model=_model,this._specSource=_specSource,this._settings=_settings,__publicField$1p(this,"_agentId",""),__publicField$1p(this,"_systemPrompt"),__publicField$1p(this,"userDefinedSystemPrompt",""),__publicField$1p(this,"toolChoice","auto"),__publicField$1p(this,"assistantName"),__publicField$1p(this,"_reqMethods"),__publicField$1p(this,"_toolsConfig"),__publicField$1p(this,"_toolStatusMap",{}),__publicField$1p(this,"_endpoints"),__publicField$1p(this,"_baseUrl"),__publicField$1p(this,"_status",""),__publicField$1p(this,"_currentWaitPromise"),__publicField$1p(this,"_llmContextStore"),__publicField$1p(this,"_context"),__publicField$1p(this,"_maxContextSize",1024*128),__publicField$1p(this,"_maxOutputTokens",1024*8),__publicField$1p(this,"_teamId"),__publicField$1p(this,"_agentVersion"),__publicField$1p(this,"agentData"),__publicField$1p(this,"_lastError"),__publicField$1p(this,"_spec"),__publicField$1p(this,"_customToolsDeclarations",[]),__publicField$1p(this,"_customToolsHandlers",{}),__publicField$1p(this,"stop",!1),this.on("error",error=>{this._lastError=error,console$q.warn("Conversation Error: ",error?.message)}),this._maxContextSize=_settings.maxContextSize||this._model.tokens||this._model.keyOptions?.tokens||this._maxContextSize,this._maxOutputTokens=_settings.maxOutputTokens||this._model.completionTokens||this._model.keyOptions?.completionTokens||this._maxOutputTokens,_settings?.systemPrompt&&(this.userDefinedSystemPrompt=_settings.systemPrompt),_settings?.toolChoice&&(this.toolChoice=_settings.toolChoice),_settings?.store&&(this._llmContextStore=_settings.store),this._agentVersion=_settings?.agentVersion,(async()=>_specSource?this.loadSpecFromSource(_specSource).then(async spec=>{if(!spec)throw this._status="error",this.emit("error","Unable to parse OpenAPI specifications"),new Error("Invalid OpenAPI specification data format");this._spec=spec,!this._agentId&&_settings?.agentId&&(this._agentId=_settings.agentId),this._agentId||(this._agentId="FAKE-AGENT-ID"),await this.assignTeamIdFromAgentId(this._agentId),await this.updateModel(this._model),this._status="ready"}).catch(error=>{this._status="error",this.emit("error",error)}):(await this.updateModel(this._model),this._status="ready"))()}get systemPrompt(){return this._systemPrompt}set systemPrompt(systemPrompt){this._systemPrompt=systemPrompt,this._context&&(this._context.systemPrompt=systemPrompt)}get context(){return this._context}set spec(specSource){this.ready.then(()=>{this._status="",this.loadSpecFromSource(specSource).then(async spec=>{if(!spec)throw this._status="error",this.emit("error","Invalid OpenAPI specification data format"),new Error("Invalid OpenAPI specification data format");this._spec=spec,await this.assignTeamIdFromAgentId(this._agentId),await this.updateModel(this._model),this._status="ready"})})}set model(model){this.ready.then(async()=>{this._status="",await this.updateModel(model),this._status="ready"})}get model(){return this._model}get ready(){return this._currentWaitPromise?this._currentWaitPromise:(this._currentWaitPromise=new Promise((resolve,reject)=>{if(this._status)return resolve(this._status);const maxWaitTime=3e4;let waitTime=0;const interval=100,wait=setInterval(()=>{if(this._status)return clearInterval(wait),resolve(this._status);if(waitTime+=interval,waitTime>=maxWaitTime)return clearInterval(wait),reject("Timeout: Failed to prepare data")},interval)}),this._currentWaitPromise)}async prompt(message,toolHeaders={},concurrentToolCalls=4,abortSignal){let error=null;const errListener=err=>error=err;this.once("error",errListener);const result=await this.streamPrompt(message,toolHeaders,concurrentToolCalls,abortSignal);if(error)throw error;return this.removeListener("error",errListener),result}async streamPrompt(message,toolHeaders={},concurrentToolCalls=4,abortSignal){let options=typeof message=="object"?message:{message};message=options?.message;const files=options?.files;if(message&&(this.stop=!1),this.stop){this.emit("interrupted","interrupted"),this.emit("end");return}await this.ready,abortSignal&&abortSignal.addEventListener("abort",()=>{this.emit("aborted","Aborted by user!")});const passThroughtContinueMessage="Continue with the next tool call if there are any, or just inform the user that you are done";let _content="";const reqMethods=this._reqMethods,toolsConfig=this._toolsConfig,endpoints=this._endpoints,baseUrl=this._baseUrl,message_id="msg_"+randomUUID();toolHeaders["X-DEBUG"];const llmInference=await LLMInference$1.getInstance(this.model,AccessCandidate.team(this._teamId));message&&this._context.addUserMessage(message,message_id);const contextWindow=await this._context.getContextWindow(this._maxContextSize,this._maxOutputTokens);let maxTokens=this._maxOutputTokens;typeof this.model=="object"&&this.model?.params?.maxTokens&&(maxTokens=this.model.params.maxTokens);const eventEmitter=await llmInference.promptStream({contextWindow,files,params:{model:this.model,toolsConfig:this._settings?.toolsStrategy?this._settings.toolsStrategy(toolsConfig):toolsConfig,maxTokens,cache:this._settings?.experimentalCache,agentId:this._agentId,abortSignal}}).catch(error=>{console$q.error("Error on promptStream: ",error),this.emit(TLLMEvent.Error,error)});if(abortSignal&&abortSignal.addEventListener("abort",()=>{eventEmitter.removeAllListeners()}),!eventEmitter||eventEmitter.error)throw new Error("[LLM Request Error]");message&&this.emit("start"),eventEmitter.on("data",data=>{this.stop||this.emit("data",data)}),eventEmitter.on(TLLMEvent.Thinking,thinking=>{this.stop||this.emit(TLLMEvent.Thinking,thinking)}),eventEmitter.on(TLLMEvent.Data,data=>{this.stop||this.emit(TLLMEvent.Data,data)}),eventEmitter.on(TLLMEvent.Content,content=>{this.stop||(_content+=content,this.emit(TLLMEvent.Content,content))});let finishReason="stop";const toolsContent=await new Promise((resolve,reject)=>{let hasTools=!1,hasError=!1,passThroughContent="";eventEmitter.on(TLLMEvent.Error,error=>{hasError=!0,reject(error)}),eventEmitter.on(TLLMEvent.ToolInfo,async(toolsData,thinkingBlocks=[])=>{if(this.stop)return;hasTools=!0;let llmMessage={role:"assistant",content:_content,tool_calls:[]};thinkingBlocks?.length>0&&(this.emit("thoughtProcess",thinkingBlocks.filter(block=>block.type==="thinking").map(block=>block.thinking||"").join(`
28
28
  `)),llmMessage.thinkingBlocks=thinkingBlocks),llmMessage.tool_calls=toolsData.map(tool=>({id:tool.id,type:tool.type,function:{name:tool.name,arguments:tool.arguments}})),this.emit(TLLMEvent.ToolInfo,toolsData);const _agentCallback=data=>{if(this.stop)return;let content="",thinking="";if(typeof data=="object"){data.content&&(content=data.content,passThroughContent+=content,eventEmitter.emit(TLLMEvent.Content,content)),data.thinking&&(thinking=data.thinking,eventEmitter.emit(TLLMEvent.Thinking,thinking));return}typeof data=="string"&&(passThroughContent+=data,eventEmitter.emit(TLLMEvent.Content,data))},toolProcessingTasks=toolsData.map(tool=>async()=>{const endpoint=endpoints?.get(tool?.name)||tool?.name;let args=typeof tool?.arguments=="string"?JSONContent(tool?.arguments).tryParse()||{}:tool?.arguments;if(args?.error)throw new Error(`[Tool] Arguments Parsing Error
29
- `+JSON.stringify({message:args?.error}));this.emit("beforeToolCall",{tool,args},llmMessage),this.emit(TLLMEvent.ToolCall,{tool,_llmRequest:llmMessage});const toolArgs={type:tool?.type,method:reqMethods?.get(tool?.name),endpoint,args,baseUrl,headers:toolHeaders,agentCallback:_agentCallback};let{data:functionResponse,error}=await this.useTool(toolArgs,abortSignal);error&&(functionResponse=typeof error=="object"&&typeof error!==null?JSON.stringify(error):error);const result=functionResponse;return functionResponse=typeof functionResponse=="object"&&typeof functionResponse!==null?JSON.stringify(functionResponse):functionResponse,this.emit("afterToolCall",{tool,args},functionResponse),this.emit(TLLMEvent.ToolResult,{tool,result}),{...tool,result:functionResponse}}),processedToolsData=await processWithConcurrencyLimit(toolProcessingTasks,concurrentToolCalls);passThroughContent?this._context.addToolMessage(llmMessage,processedToolsData,message_id,{passThrough:!0}):this._context.addToolMessage(llmMessage,processedToolsData,message_id),this.streamPrompt(null,toolHeaders,concurrentToolCalls,abortSignal).then(resolve).catch(reject)}),eventEmitter.on(TLLMEvent.End,async(toolsData,usage_data,_finishReason)=>{if(_finishReason&&(finishReason=_finishReason),usage_data&&this.emit(TLLMEvent.Usage,usage_data),!hasError&&(!hasTools||passThroughContent)){const lastMessage=this._context?.messages?.[this._context?.messages?.length-1];let metadata;lastMessage?.content?.includes(passThroughtContinueMessage)&&lastMessage?.__smyth_data__?.internal&&(metadata={internal:!0}),this._context.addAssistantMessage(_content,message_id,metadata),resolve("")}})}).catch(error=>(console$q.error("Error in toolsPromise: ",error),this.emit(TLLMEvent.Error,error),""));return _content+=toolsContent,message&&(finishReason!=="stop"&&this.emit(TLLMEvent.Interrupted,finishReason),this.emit(TLLMEvent.End)),_content}resolveToolEndpoint(baseUrl,method,endpoint,params){let templateParams={};if(params){const parameters=this._spec?.paths?.[endpoint]?.[method.toLowerCase()]?.parameters||[];for(let p of parameters)p.in==="path"&&(templateParams[p.name]=params[p.name]||"",delete params[p.name])}const parsedEndpoint=TemplateString(endpoint).parse(templateParams,Match.singleCurly).clean().result,url=new URL(parsedEndpoint,baseUrl);return Object.keys(params).forEach(key=>{url.searchParams.append(key,params[key])}),url.toString()}async useTool(params,abortSignal){if(this.stop)return{data:null,error:"Conversation Interrupted"};const{type,endpoint,args,method,baseUrl,headers={},agentCallback}=params;if(type==="function"){const toolHandler=this._customToolsHandlers[endpoint];if(toolHandler)try{return{data:await toolHandler(args),error:null}}catch(error){return{data:null,error:error?.message||"Custom tool handler failed"}}try{const url=this.resolveToolEndpoint(baseUrl,method,endpoint,method=="get"?args:{}),reqConfig={method,url,headers:{...headers},signal:abortSignal};method!=="get"&&(Object.keys(args).length&&(reqConfig.data=args),reqConfig.headers["Content-Type"]="application/json"),console$q.debug("Calling tool: ",reqConfig),reqConfig.headers["X-CACHE-ID"]=this._context?.llmCache?.id;const requiresRemoteCall=reqConfig.headers["X-DEBUG"]!==void 0||reqConfig.headers["X-MONITOR-ID"]!==void 0||reqConfig.headers["X-AGENT-REMOTE-CALL"]!==void 0;if(reqConfig.url.includes("localhost")||reqConfig.headers["X-AGENT-ID"]&&!requiresRemoteCall){console$q.log("RUNNING AGENT LOCALLY");let agentProcess;return this.agentData===this._specSource?agentProcess=AgentProcess.load(this.agentData,this._agentVersion):agentProcess=AgentProcess.load(reqConfig.headers["X-AGENT-ID"]||this._agentId,reqConfig.headers["X-AGENT-VERSION"]||this._agentVersion),{data:(await agentProcess.run(reqConfig,agentCallback)).data,error:null}}else{console$q.log("RUNNING AGENT REMOTELY");let eventSource;if(reqConfig.headers["X-DEBUG"]&&reqConfig.headers["X-AGENT-ID"]||reqConfig.headers["X-MONITOR-ID"]){console$q.log("ATTACHING MONITOR TO REMOTE AGENT CALL");const monitUrl=reqConfig.url.split("/api")[0]+"/agent/"+reqConfig.headers["X-AGENT-ID"]+"/monitor",customFetch=(url2,init)=>fetch(url2,{...init,headers:{...init?.headers||{},...Object.fromEntries(Object.entries(reqConfig.headers).map(([k,v])=>[k,String(v)]))}}),eventSource2=new EventSource(monitUrl,{fetch:customFetch});let monitorId="";eventSource2.addEventListener("init",event=>{monitorId=event.data,console$q.log("monitorId",monitorId),reqConfig.headers["X-MONITOR-ID"]?reqConfig.headers["X-MONITOR-ID"]=`${reqConfig.headers["X-MONITOR-ID"]},${monitorId}`:reqConfig.headers["X-MONITOR-ID"]=monitorId}),eventSource2.addEventListener("llm/passthrough/content",event=>{params.agentCallback&&params.agentCallback({content:event.data.replace(/\\n/g,`
29
+ `+JSON.stringify({message:args?.error}));this.emit("beforeToolCall",{tool,args},llmMessage);const status=tool.name?this._toolStatusMap?.[tool.name]:void 0;this.emit(TLLMEvent.ToolCall,{tool,status,_llmRequest:llmMessage});const toolArgs={type:tool?.type,method:reqMethods?.get(tool?.name),endpoint,args,baseUrl,headers:toolHeaders,agentCallback:_agentCallback};let{data:functionResponse,error}=await this.useTool(toolArgs,abortSignal);error&&(functionResponse=typeof error=="object"&&typeof error!==null?JSON.stringify(error):error);const result=functionResponse;return functionResponse=typeof functionResponse=="object"&&typeof functionResponse!==null?JSON.stringify(functionResponse):functionResponse,this.emit("afterToolCall",{tool,args},functionResponse),this.emit(TLLMEvent.ToolResult,{tool,result}),{...tool,result:functionResponse}}),processedToolsData=await processWithConcurrencyLimit(toolProcessingTasks,concurrentToolCalls);passThroughContent?this._context.addToolMessage(llmMessage,processedToolsData,message_id,{passThrough:!0}):this._context.addToolMessage(llmMessage,processedToolsData,message_id),this.streamPrompt(null,toolHeaders,concurrentToolCalls,abortSignal).then(resolve).catch(reject)}),eventEmitter.on(TLLMEvent.End,async(toolsData,usage_data,_finishReason)=>{if(_finishReason&&(finishReason=_finishReason),usage_data&&this.emit(TLLMEvent.Usage,usage_data),!hasError&&(!hasTools||passThroughContent)){const lastMessage=this._context?.messages?.[this._context?.messages?.length-1];let metadata;lastMessage?.content?.includes(passThroughtContinueMessage)&&lastMessage?.__smyth_data__?.internal&&(metadata={internal:!0}),this._context.addAssistantMessage(_content,message_id,metadata),resolve("")}})}).catch(error=>(console$q.error("Error in toolsPromise: ",error),this.emit(TLLMEvent.Error,error),""));return _content+=toolsContent,message&&(finishReason!=="stop"&&this.emit(TLLMEvent.Interrupted,finishReason),this.emit(TLLMEvent.End)),_content}resolveToolEndpoint(baseUrl,method,endpoint,params){let templateParams={};if(params){const parameters=this._spec?.paths?.[endpoint]?.[method.toLowerCase()]?.parameters||[];for(let p of parameters)p.in==="path"&&(templateParams[p.name]=params[p.name]||"",delete params[p.name])}const parsedEndpoint=TemplateString(endpoint).parse(templateParams,Match.singleCurly).clean().result,url=new URL(parsedEndpoint,baseUrl);return Object.keys(params).forEach(key=>{url.searchParams.append(key,params[key])}),url.toString()}async useTool(params,abortSignal){if(this.stop)return{data:null,error:"Conversation Interrupted"};const{type,endpoint,args,method,baseUrl,headers={},agentCallback}=params;if(type==="function"){const toolHandler=this._customToolsHandlers[endpoint];if(toolHandler)try{return{data:await toolHandler(args),error:null}}catch(error){return{data:null,error:error?.message||"Custom tool handler failed"}}try{const url=this.resolveToolEndpoint(baseUrl,method,endpoint,method=="get"?args:{}),reqConfig={method,url,headers:{...headers},signal:abortSignal};method!=="get"&&(Object.keys(args).length&&(reqConfig.data=args),reqConfig.headers["Content-Type"]="application/json"),console$q.debug("Calling tool: ",reqConfig),reqConfig.headers["X-CACHE-ID"]=this._context?.llmCache?.id;const requiresRemoteCall=reqConfig.headers["X-DEBUG"]!==void 0||reqConfig.headers["X-MONITOR-ID"]!==void 0||reqConfig.headers["X-AGENT-REMOTE-CALL"]!==void 0;if(reqConfig.url.includes("localhost")||reqConfig.headers["X-AGENT-ID"]&&!requiresRemoteCall){console$q.log("RUNNING AGENT LOCALLY");let agentProcess;return this.agentData===this._specSource?agentProcess=AgentProcess.load(this.agentData,this._agentVersion):agentProcess=AgentProcess.load(reqConfig.headers["X-AGENT-ID"]||this._agentId,reqConfig.headers["X-AGENT-VERSION"]||this._agentVersion),{data:(await agentProcess.run(reqConfig,agentCallback)).data,error:null}}else{console$q.log("RUNNING AGENT REMOTELY");let eventSource;if(reqConfig.headers["X-DEBUG"]&&reqConfig.headers["X-AGENT-ID"]||reqConfig.headers["X-MONITOR-ID"]){console$q.log("ATTACHING MONITOR TO REMOTE AGENT CALL");const monitUrl=reqConfig.url.split("/api")[0]+"/agent/"+reqConfig.headers["X-AGENT-ID"]+"/monitor",customFetch=(url2,init)=>fetch(url2,{...init,headers:{...init?.headers||{},...Object.fromEntries(Object.entries(reqConfig.headers).map(([k,v])=>[k,String(v)]))}}),eventSource2=new EventSource(monitUrl,{fetch:customFetch});let monitorId="";eventSource2.addEventListener("init",event=>{monitorId=event.data,console$q.log("monitorId",monitorId),reqConfig.headers["X-MONITOR-ID"]?reqConfig.headers["X-MONITOR-ID"]=`${reqConfig.headers["X-MONITOR-ID"]},${monitorId}`:reqConfig.headers["X-MONITOR-ID"]=monitorId}),eventSource2.addEventListener("llm/passthrough/content",event=>{params.agentCallback&&params.agentCallback({content:event.data.replace(/\\n/g,`
30
30
  `)})}),eventSource2.addEventListener("llm/passthrough/thinking",event=>{params.agentCallback&&params.agentCallback({thinking:event.data.replace(/\\n/g,`
31
31
  `)})}),await new Promise(resolve=>{let maxTime=5e3,itv=setInterval(()=>{(monitorId||maxTime<=0)&&(clearInterval(itv),resolve(!0)),maxTime-=100},100)})}const response=await axios.request(reqConfig);return eventSource&&(eventSource.close(),console$q.log("eventSource closed")),{data:response.data,error:null}}}catch(error){return console$q.warn("Failed to call Tool: ",baseUrl,endpoint),console$q.warn(" ====>",error),{data:null,error:error?.response?.data||error?.message}}}return{data:null,error:`'${type}' tool type not supported at the moment`}}async addTool(tool){if(!tool.arguments){const toolFunction=tool.handler,openApiArgs=this.extractArgsAsOpenAPI(toolFunction),_arguments={};for(let arg of openApiArgs)if(_arguments[arg.name]=arg.schema,tool.inputs&&arg.schema.properties){const required=[];for(let prop in arg.schema.properties){const input=tool.inputs?.find(i=>i.name===prop);arg.schema.properties[prop].description||(arg.schema.properties[prop].description=input?.description),input?.optional||required.push(prop)}required.length&&(arg.schema.required=required)}tool.arguments=_arguments,tool.handler=async argsObj=>{const args=Object.values(argsObj);return await toolFunction(...args)}}const requiredFields=Object.values(tool.arguments).map(arg=>arg.required?arg.name:null).filter(arg=>arg),properties={};for(let entry in tool.arguments)properties[entry]={type:tool.arguments[entry].type||"string",properties:tool.arguments[entry].properties,description:tool.arguments[entry].description,...tool.arguments[entry].type==="array"?{items:{type:tool.arguments[entry].items?.type||"string"}}:{}};const toolDefinition={name:tool.name,description:tool.description,properties,requiredFields};this._customToolsDeclarations.push(toolDefinition),this._customToolsHandlers[tool.name]=tool.handler;const toolsConfig=(await LLMInference$1.getInstance(this.model,AccessCandidate.team(this._teamId))).connector.formatToolsConfig({type:"function",toolDefinitions:[toolDefinition],toolChoice:this.toolChoice});this._toolsConfig?this._toolsConfig.tools.push(...toolsConfig?.tools):this._toolsConfig=toolsConfig}async updateModel(model){try{if(this._model=model,this._spec){this._reqMethods=OpenAPIParser.mapReqMethods(this._spec?.paths),this._endpoints=OpenAPIParser.mapEndpoints(this._spec?.paths),this._baseUrl=this._spec?.servers?.[0].url;const functionDeclarations=this.getFunctionDeclarations(this._spec);functionDeclarations.push(...this._customToolsDeclarations);const llmInference=await LLMInference$1.getInstance(this._model,AccessCandidate.team(this._teamId));if(!llmInference.connector){this.emit("error","No connector found for model: "+this._model);return}this._toolsConfig=llmInference.connector.formatToolsConfig({type:"function",toolDefinitions:functionDeclarations,toolChoice:this.toolChoice});let messages=[];this._context&&(messages=this._context.messages),this._context=new LLMContext(llmInference,this.systemPrompt,this._llmContextStore)}else this._toolsConfig=null,this._reqMethods=null,this._endpoints=null,this._baseUrl=null}catch(error){this.emit("error",error)}}patchSpec(spec){const paths=spec?.paths;for(const path2 in paths){const pathData=paths[path2];for(const key in pathData){const data=pathData[key];data?.operationId||(data.operationId=path2.replace(/\//g,"_").replace(/{|}/g,"").replace(/\./g,"_"))}}return spec}async loadSpecFromSource(specSource){if(typeof specSource=="object")return OpenAPIParser.isValidOpenAPI(specSource)?(this.systemPrompt=specSource?.info?.description||"",this.patchSpec(specSource)):typeof specSource?.behavior=="string"&&specSource?.components&&specSource?.connections?(this.agentData=specSource,await this.loadSpecFromAgent(specSource)):null;if(typeof specSource=="string"){if(isUrl(specSource)){const spec2=await OpenAPIParser.getJsonFromUrl(specSource);spec2.info?.description&&(this.systemPrompt=spec2.info.description),this.userDefinedSystemPrompt&&(this.systemPrompt=this.userDefinedSystemPrompt),spec2.info?.title&&(this.assistantName=spec2.info.title);const defaultBaseUrl=new URL(specSource).origin;return spec2?.servers||(spec2.servers=[{url:defaultBaseUrl}]),spec2.servers?.length==0&&(spec2.servers=[{url:defaultBaseUrl}]),this.assistantName&&(this.systemPrompt=`Assistant Name : ${this.assistantName}
32
32
 
33
33
  ${this.systemPrompt}`),this.patchSpec(spec2)}const agentDataConnector=ConnectorService.getAgentDataConnector(),agentId=specSource;if(this._agentId=agentId,this._agentVersion===void 0){const isDeployed=await agentDataConnector.isDeployed(agentId);this._agentVersion=isDeployed?"latest":""}return this.agentData=await agentDataConnector.getAgentData(agentId,this._agentVersion).catch(error=>null),this.agentData?await this.loadSpecFromAgent(this.agentData):null}}async loadSpecFromAgent(agentData){agentData?.components&&(agentData={name:agentData?.name,data:agentData,version:"1.0.0"});const agentDataConnector=ConnectorService.getAgentDataConnector();this.systemPrompt=agentData?.data?.behavior||this.systemPrompt,this.userDefinedSystemPrompt&&(this.systemPrompt=this.userDefinedSystemPrompt),this.assistantName=agentData?.data?.name||agentData?.data?.templateInfo?.name||this.assistantName,this.assistantName&&(this.systemPrompt=`Assistant Name : ${this.assistantName}
34
34
 
35
- ${this.systemPrompt}`);const spec=await agentDataConnector.getOpenAPIJSON(agentData,"http://localhost/",this._agentVersion,!0).catch(error=>null);return this.patchSpec(spec)}getFunctionDeclarations(spec){const paths=spec?.paths,reqMethods=OpenAPIParser.mapReqMethods(paths);let declarations=[];for(const path2 in paths){const pathData=paths[path2];for(const key in pathData){const data=pathData[key];if(!data?.operationId)continue;const method=reqMethods.get(data?.operationId)||"get";let properties={},requiredFields=[];if(method.toLowerCase()==="get"){const params=data?.parameters||[];for(const prop of params)properties[prop.name]={...prop.schema,description:prop.description},prop.required===!0&&requiredFields.push(prop?.name||"")}else{properties=data?.requestBody?.content?.["application/json"]?.schema?.properties,requiredFields=data?.requestBody?.content?.["application/json"]?.schema?.required;for(const prop in properties)delete properties[prop]?.required}properties||(properties={}),requiredFields||(requiredFields=[]);const declaration={name:data?.operationId,description:data?.description||data?.summary||"",properties,requiredFields};declarations.push(declaration)}}return declarations}async assignTeamIdFromAgentId(agentId){if(agentId){const teamId=await ConnectorService.getAccountConnector().getCandidateTeam(AccessCandidate.agent(agentId))?.catch(()=>"");this._teamId=teamId||""}}extractArgsAsOpenAPI(fn){const params=acorn.parse(`(${fn.toString()})`,{ecmaVersion:"latest"}).body[0].expression.params;let counter=0;function handleParam(param){if(param.type==="Identifier")return{name:param.name,in:"query",required:!0,schema:{type:"string",name:param.name,required:!0}};if(param.type==="AssignmentPattern"&&param.left.type==="Identifier")return{name:param.left.name,in:"query",required:!1,schema:{type:"string",name:param.left.name,required:!1}};if(param.type==="RestElement"&&param.argument.type==="Identifier")return{name:param.argument.name,in:"query",required:!1,schema:{type:"array",items:{type:"string"}}};if(param.type==="ObjectPattern"){const name2=`object___${counter++}`;return{name:name2,in:"query",required:!0,schema:{type:"object",required:!0,name:name2,properties:Object.fromEntries(param.properties.map(prop=>[prop.key.name||"[unknown]",{type:"string"}]))}}}const name=`unknown___${counter++}`;return{name,in:"query",required:!0,schema:{type:"string",name,required:!0}}}return params.map(handleParam)}}__decorateClass$l([hookAsyncWithContext("Conversation.prompt",async instance=>(await instance.ready,{teamId:instance._teamId,agentId:instance._agentId,model:instance._model}))],Conversation.prototype,"prompt"),__decorateClass$l([hookAsyncWithContext("Conversation.streamPrompt",async instance=>(await instance.ready,{teamId:instance._teamId,agentId:instance._agentId,model:instance._model}))],Conversation.prototype,"streamPrompt");const inputErrMsg=(type,name)=>`Invalid ${type} value for Input: ${name}`,logger$b=Logger("TypeChecker.helper"),InferenceStrategies={any:inferAnyType,string:inferStringType,number:inferNumberType,integer:inferIntegerType,boolean:inferBooleanType,array:inferArrayType,object:inferObjectType,date:inferDateType,binary:inferBinaryType,text:inferStringType,image:inferBinaryType,audio:inferBinaryType,video:inferBinaryType};async function performTypeInference(inputs,inputConfig,agent){try{if(!inputConfig||Object.keys(inputConfig)?.length===0)return inputs;const _inputs={...inputs},_inputConfig={};for(const input of inputConfig)input?.name&&(_inputConfig[input.name]={...input});for(const[key,config2]of Object.entries(_inputConfig)){let value=inputs?.[key]||"";if(!value)continue;const type=config2?.type?.toLowerCase()||"any";if(!InferenceStrategies[type]){logger$b.warn(`Unsupported type: ${type} for Input: ${key} for agent: ${agent?.id} input: ${key}`);continue}_inputs[key]=await InferenceStrategies[type](value,key,agent)}return _inputs}catch(error){throw error}}async function inferStringType(value,key,agent){if(value==null||value==="null"||value==="undefined")return"";if(isBase64(value)||isBase64DataUrl(value))return value;if(isSmythFileObject(value)){const file=await _createBinaryInput(value,key),base64=(await file.getBuffer()).toString("base64");return file.mimetype?`data:${file.mimetype};base64,${base64}`:base64}else return typeof value=="object"||Array.isArray(value)?JSON.stringify(value):String(value)}async function inferNumberType(value,key,agent){const floatVal=parseFloat(value);if(isNaN(floatVal))throw new Error("Invalid Number value");return floatVal}async function inferIntegerType(value,key,agent){const intVal=parseInt(value);if(isNaN(intVal))throw new Error("Invalid Integer value");return intVal}async function inferBooleanType(value,key,agent){if(typeof value=="boolean")return value;if(typeof value=="string"||typeof value=="number"){const lowerCaseValue=String(value).toLowerCase();if(["true","1"].includes(lowerCaseValue))return!0;if(["false","0"].includes(lowerCaseValue))return!1;throw new Error("Invalid Boolean value")}else throw new Error("Invalid Boolean value")}async function inferArrayType(value,key,agent){try{if(Array.isArray(value))return value;if(typeof value!="string")throw new Error("Invalid Array value");try{return value.trim().startsWith("[")?JSONContent(value).tryParse():value.split(",")}catch{throw new Error("Invalid Array value")}}catch{throw new Error("Invalid Array value")}}async function inferObjectType(value,key,agent){try{const obj=isPlainObject(value)?value:JSONContent(value).tryParse();if(!isPlainObject(obj))throw new Error("Invalid Object value");return obj}catch{throw new Error("Invalid Object value")}}function extractSmythFsAgentId(url){if(!url?.startsWith("smythfs://"))return null;try{const segments=url.split("/");return segments.length<4?null:segments[3]}catch{return null}}async function _createBinaryInput(value,key,agent){if(value instanceof BinaryInput)return value;let candidate,agentId="",data,mimetype="",fileName=`${uid()}-${key}`;if(value&&typeof value=="object"&&value?.url&&value?.mimetype){const url=value?.url;mimetype=value?.mimetype,value?.name&&(fileName=value?.name),url?.startsWith("smythfs://")?(data=value,agentId=extractSmythFsAgentId(url)):data=url}else typeof value=="string"&&value.startsWith("smythfs://")&&(agentId=extractSmythFsAgentId(value)),data=value;agentId&&(candidate=AccessCandidate.agent(agentId));const binaryInput=BinaryInput.from(data,fileName,mimetype,candidate);return await binaryInput.ready(),binaryInput}async function inferBinaryType(value,key,agent){try{let binarySource=value;if(typeof value=="string"){const normalizedValue=value.trim();if(isUrl(normalizedValue)||isSmythFsUrl(normalizedValue)||isBase64(value)||isBase64DataUrl(value))binarySource=normalizedValue;else{const extractedUrls=_extractUrls(value);extractedUrls.length>0&&(binarySource=extractedUrls)}}return Array.isArray(binarySource)?await Promise.all(binarySource.map(item=>_createBinaryInput(item,key,agent))):await _createBinaryInput(binarySource,key,agent)}catch(error){return logger$b.warn("Error processing binary input",{key,error:error.message}),null}}async function inferDateType(value,key,agent){const errMsg=`Invalid Date value
35
+ ${this.systemPrompt}`),this._toolStatusMap=agentData?.data?.components?.filter(component=>component.name==="APIEndpoint").reduce((map,component)=>(component?.data?.endpoint&&(map[component.data.endpoint]=component?.data?.status_message||`Calling ${component?.data?.endpointLabel||component.data.endpoint}`),map),{});const spec=await agentDataConnector.getOpenAPIJSON(agentData,"http://localhost/",this._agentVersion,!0).catch(error=>null);return this.patchSpec(spec)}getFunctionDeclarations(spec){const paths=spec?.paths,reqMethods=OpenAPIParser.mapReqMethods(paths);let declarations=[];for(const path2 in paths){const pathData=paths[path2];for(const key in pathData){const data=pathData[key];if(!data?.operationId)continue;const method=reqMethods.get(data?.operationId)||"get";let properties={},requiredFields=[];if(method.toLowerCase()==="get"){const params=data?.parameters||[];for(const prop of params)properties[prop.name]={...prop.schema,description:prop.description},prop.required===!0&&requiredFields.push(prop?.name||"")}else{properties=data?.requestBody?.content?.["application/json"]?.schema?.properties,requiredFields=data?.requestBody?.content?.["application/json"]?.schema?.required;for(const prop in properties)delete properties[prop]?.required}properties||(properties={}),requiredFields||(requiredFields=[]);const declaration={name:data?.operationId,description:data?.description||data?.summary||"",properties,requiredFields};declarations.push(declaration)}}return declarations}async assignTeamIdFromAgentId(agentId){if(agentId){const teamId=await ConnectorService.getAccountConnector().getCandidateTeam(AccessCandidate.agent(agentId))?.catch(()=>"");this._teamId=teamId||""}}extractArgsAsOpenAPI(fn){const params=acorn.parse(`(${fn.toString()})`,{ecmaVersion:"latest"}).body[0].expression.params;let counter=0;function handleParam(param){if(param.type==="Identifier")return{name:param.name,in:"query",required:!0,schema:{type:"string",name:param.name,required:!0}};if(param.type==="AssignmentPattern"&&param.left.type==="Identifier")return{name:param.left.name,in:"query",required:!1,schema:{type:"string",name:param.left.name,required:!1}};if(param.type==="RestElement"&&param.argument.type==="Identifier")return{name:param.argument.name,in:"query",required:!1,schema:{type:"array",items:{type:"string"}}};if(param.type==="ObjectPattern"){const name2=`object___${counter++}`;return{name:name2,in:"query",required:!0,schema:{type:"object",required:!0,name:name2,properties:Object.fromEntries(param.properties.map(prop=>[prop.key.name||"[unknown]",{type:"string"}]))}}}const name=`unknown___${counter++}`;return{name,in:"query",required:!0,schema:{type:"string",name,required:!0}}}return params.map(handleParam)}}__decorateClass$l([hookAsyncWithContext("Conversation.prompt",async instance=>(await instance.ready,{teamId:instance._teamId,agentId:instance._agentId,model:instance._model}))],Conversation.prototype,"prompt"),__decorateClass$l([hookAsyncWithContext("Conversation.streamPrompt",async instance=>(await instance.ready,{teamId:instance._teamId,agentId:instance._agentId,model:instance._model}))],Conversation.prototype,"streamPrompt");const inputErrMsg=(type,name)=>`Invalid ${type} value for Input: ${name}`,logger$b=Logger("TypeChecker.helper"),InferenceStrategies={any:inferAnyType,string:inferStringType,number:inferNumberType,integer:inferIntegerType,boolean:inferBooleanType,array:inferArrayType,object:inferObjectType,date:inferDateType,binary:inferBinaryType,text:inferStringType,image:inferBinaryType,audio:inferBinaryType,video:inferBinaryType};async function performTypeInference(inputs,inputConfig,agent){try{if(!inputConfig||Object.keys(inputConfig)?.length===0)return inputs;const _inputs={...inputs},_inputConfig={};for(const input of inputConfig)input?.name&&(_inputConfig[input.name]={...input});for(const[key,config2]of Object.entries(_inputConfig)){let value=inputs?.[key]||"";if(!value)continue;const type=config2?.type?.toLowerCase()||"any";if(!InferenceStrategies[type]){logger$b.warn(`Unsupported type: ${type} for Input: ${key} for agent: ${agent?.id} input: ${key}`);continue}_inputs[key]=await InferenceStrategies[type](value,key,agent)}return _inputs}catch(error){throw error}}async function inferStringType(value,key,agent){if(value==null||value==="null"||value==="undefined")return"";if(isBase64(value)||isBase64DataUrl(value))return value;if(isSmythFileObject(value)){const file=await _createBinaryInput(value,key),base64=(await file.getBuffer()).toString("base64");return file.mimetype?`data:${file.mimetype};base64,${base64}`:base64}else return typeof value=="object"||Array.isArray(value)?JSON.stringify(value):String(value)}async function inferNumberType(value,key,agent){const floatVal=parseFloat(value);if(isNaN(floatVal))throw new Error("Invalid Number value");return floatVal}async function inferIntegerType(value,key,agent){const intVal=parseInt(value);if(isNaN(intVal))throw new Error("Invalid Integer value");return intVal}async function inferBooleanType(value,key,agent){if(typeof value=="boolean")return value;if(typeof value=="string"||typeof value=="number"){const lowerCaseValue=String(value).toLowerCase();if(["true","1"].includes(lowerCaseValue))return!0;if(["false","0"].includes(lowerCaseValue))return!1;throw new Error("Invalid Boolean value")}else throw new Error("Invalid Boolean value")}async function inferArrayType(value,key,agent){try{if(Array.isArray(value))return value;if(typeof value!="string")throw new Error("Invalid Array value");try{return value.trim().startsWith("[")?JSONContent(value).tryParse():value.split(",")}catch{throw new Error("Invalid Array value")}}catch{throw new Error("Invalid Array value")}}async function inferObjectType(value,key,agent){try{const obj=isPlainObject(value)?value:JSONContent(value).tryParse();if(!isPlainObject(obj))throw new Error("Invalid Object value");return obj}catch{throw new Error("Invalid Object value")}}function extractSmythFsAgentId(url){if(!url?.startsWith("smythfs://"))return null;try{const segments=url.split("/");return segments.length<4?null:segments[3]}catch{return null}}async function _createBinaryInput(value,key,agent){if(value instanceof BinaryInput)return value;let candidate,agentId="",data,mimetype="",fileName=`${uid()}-${key}`;if(value&&typeof value=="object"&&value?.url&&value?.mimetype){const url=value?.url;mimetype=value?.mimetype,value?.name&&(fileName=value?.name),url?.startsWith("smythfs://")?(data=value,agentId=extractSmythFsAgentId(url)):data=url}else typeof value=="string"&&value.startsWith("smythfs://")&&(agentId=extractSmythFsAgentId(value)),data=value;agentId&&(candidate=AccessCandidate.agent(agentId));const binaryInput=BinaryInput.from(data,fileName,mimetype,candidate);return await binaryInput.ready(),binaryInput}async function inferBinaryType(value,key,agent){try{let binarySource=value;if(typeof value=="string"){const normalizedValue=value.trim();if(isUrl(normalizedValue)||isSmythFsUrl(normalizedValue)||isBase64(value)||isBase64DataUrl(value))binarySource=normalizedValue;else{const extractedUrls=_extractUrls(value);extractedUrls.length>0&&(binarySource=extractedUrls)}}return Array.isArray(binarySource)?await Promise.all(binarySource.map(item=>_createBinaryInput(item,key,agent))):await _createBinaryInput(binarySource,key,agent)}catch(error){return logger$b.warn("Error processing binary input",{key,error:error.message}),null}}async function inferDateType(value,key,agent){const errMsg=`Invalid Date value
36
36
  The date string is expected to be in a format commonly used in English-speaking countries.`;if(typeof value!="string"&&typeof value!="number")throw new Error(errMsg);let date;if(typeof value=="string"&&isNaN(Number(value)))date=dayjs(value).locale("en");else{const timestamp=typeof value=="number"?value:Number(value);date=dayjs.unix(timestamp/1e3)}if(!date.isValid())throw new Error(errMsg);return date.toISOString()}async function inferAnyType(value){return value}function _extractUrls(value){if(typeof value!="string")return[];try{const parsedValue=JSONContent(value).tryParse();if(typeof parsedValue=="object")return Object.values(parsedValue).map(val=>String(val).trim()).filter(val=>isUrl(val)||isSmythFsUrl(val));const urls=new Set([...value.split(",").map(val=>val.trim()).filter(val=>val&&(isUrl(val)||isSmythFsUrl(val))),...value.split(`
37
37
  `).map(val=>val.trim()).filter(val=>val&&(isUrl(val)||isSmythFsUrl(val)))]);return Array.from(urls)}catch(error){return logger$b.warn("Error extracting URLs from value",{error}),[]}}var __defProp$1o=Object.defineProperty,__getOwnPropDesc$k=Object.getOwnPropertyDescriptor,__defNormalProp$1o=(obj,key,value)=>key in obj?__defProp$1o(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__decorateClass$k=(decorators,target,key,kind)=>{for(var result=__getOwnPropDesc$k(target,key),i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=decorator(target,key,result)||result);return result&&__defProp$1o(target,key,result),result},__publicField$1o=(obj,key,value)=>__defNormalProp$1o(obj,typeof key!="symbol"?key+"":key,value);class Component{constructor(){__publicField$1o(this,"hasReadOutput",!1),__publicField$1o(this,"hasPostProcess",!0),__publicField$1o(this,"alwaysActive",!1),__publicField$1o(this,"exclusive",!1),__publicField$1o(this,"schema",{name:"Component",settings:{},inputs:{}}),__publicField$1o(this,"configSchema")}init(){}createComponentLogger(agent,configuration){const logger2=Logger((configuration.name||this.constructor.name)+`,agent<${agent.id}>`,agent?.agentRuntime?.debug);return logger2.on("logged",info=>{agent.sse&&configuration.eventId&&agent.sse.send("component",{eventId:configuration.eventId,action:"log",name:configuration.name||this.constructor.name,title:configuration.title,logs:[{level:info.level,message:info.message}]})}),logger2}filterConfigBySchema(data,schema){if(!schema||!data)return data;const schemaDescription=schema.describe();if(schemaDescription.type!=="object"||!schemaDescription.keys)return data;const allowedKeys=Object.keys(schemaDescription.keys),filteredData={};for(const key of allowedKeys)key in data&&(filteredData[key]=data[key]);return data._templateVars&&(filteredData._templateVars=data._templateVars),filteredData}async validateConfig(config2){if(!this.configSchema)return{};let workingSchema=this.configSchema;if(config2.data._templateVars)for(let tplVar in config2.data._templateVars)workingSchema=workingSchema.append({[tplVar]:Joi.any()});const filteredData=this.filterConfigBySchema(config2.data,workingSchema),valid=await workingSchema.validate(filteredData);return valid.error?{id:config2.id,name:config2.name,_error:`Schema Validation error: ${valid?.error?.message} on component ${config2.displayName}:${config2.title}`,_debug:`Schema Validation error: ${valid?.error?.message} on component ${config2.displayName}:${config2.title}`}:{}}async process(input,config2,agent){if(agent.isKilled())throw new Error("Agent killed");const _input=await performTypeInference(input,config2?.inputs,agent);for(const[key,value]of Object.entries(_input))input[key]=value}async postProcess(output,config2,agent){return output?.result&&(delete output?.result?._debug,output?.result?._error||delete output?.result?._error),output}async enable(config2,agent){}async disable(config2,agent){}readOutput(id,config2,agent){return null}hasOutput(id,config2,agent){return!1}}__decorateClass$k([hookAsync("Component.process")],Component.prototype,"process");var __defProp$1n=Object.defineProperty,__defNormalProp$1n=(obj,key,value)=>key in obj?__defProp$1n(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$1n=(obj,key,value)=>__defNormalProp$1n(obj,key+"",value);class AgentPlugin extends Component{constructor(){super(),__publicField$1n(this,"configSchema",Joi.object({agentId:Joi.string().max(200).required(),openAiModel:Joi.string().max(200).optional(),model:Joi.string().max(200).optional(),descForModel:Joi.string().max(5e3).allow("").label("Description for Model"),id:Joi.string().max(200),name:Joi.string().max(500),desc:Joi.string().max(5e3).allow("").label("Description"),logoUrl:Joi.string().max(8192).allow(""),version:Joi.string().max(100).allow(""),domain:Joi.string().max(253).allow("")}))}async process(input,config2,agent){await super.process(input,config2,agent);const logger2=this.createComponentLogger(agent,config2);logger2.debug("=== Agent Plugin Log ===");try{const subAgentId=config2.data?.agentId;if(!subAgentId)return{_error:"Agent Component ID is required!",_debug:logger2.output};const reqTag=agent.agentRuntime?.reqTag,model=config2?.data?.model||config2?.data?.openAiModel,descForModel=TemplateString(config2?.data?.descForModel).parse(input).result,prompt=typeof input?.Prompt=="string"?input?.Prompt:JSON.stringify(input?.Prompt),agentDataConnector=ConnectorService.getAgentDataConnector(),isSubAgentDeployed=await agentDataConnector.isDeployed(subAgentId);let version2=config2.data?.version||"";if(logger2.debug("Version: ",version2),version2==="same-as-parent")if(await agentDataConnector.isDeployed(agent?.id))if(isSubAgentDeployed)version2="latest";else return{_error:`Call failed, Agent '${config2.data?.name}' (${subAgentId}) is not deployed. Please deploy the agent and try again.`,_debug:logger2.output};else version2="";else if(version2==="dev-latest")version2="";else if(version2==="prod-latest")if(isSubAgentDeployed)version2="latest";else return{_error:`Call failed, Agent '${config2.data?.name}' (${subAgentId}) is not deployed. Please deploy the agent and try again.`,_debug:logger2.output};const result=await new Conversation(model,subAgentId,{systemPrompt:descForModel,agentVersion:version2}).prompt(prompt,{"X-AGENT-ID":subAgentId,"X-AGENT-VERSION":version2,"X-REQUEST-TAG":reqTag,"x-caller-session-id":agent.callerSessionId});return logger2.debug(`Response:
38
38
  `,result,`
@@ -110,7 +110,7 @@ ${error?.message||JSON.stringify(error)}`,_debug:logger2.output}}}}const imageGe
110
110
  ${revised_prompt}`),imageGenerator.reportUsage({cost},{modelEntryName:model,keySource:APIKeySource.Smyth,agentId:agent.id,teamId:agent.teamId}),{output}},runware:async({model,prompt,config:config2,agent,input})=>{const teamId=agent.teamId,apiKey=await getCredentials(AccessCandidate.team(teamId),"runware");if(!apiKey)throw new Error("Runware API key is missing. Please provide a valid key to continue.");const runware=new Runware({apiKey});await runware.ensureConnection();const negativePrompt=config2?.data?.negativePrompt||"",files=parseFiles(input,config2);let seedImage=Array.isArray(files)?files[0]:files;seedImage=await normalizeImageInput(seedImage);const imageRequestArgs={model:await agent.modelsProvider.getModelId(model),positivePrompt:prompt,width:+config2?.data?.width||1024,height:+config2?.data?.height||1024,numberResults:1,outputType:"URL",outputFormat:config2?.data?.outputFormat||"JPEG",includeCost:!0};seedImage&&(imageRequestArgs.seedImage=seedImage,imageRequestArgs.strength=+config2?.data?.strength||.5),negativePrompt&&(imageRequestArgs.negativePrompt=negativePrompt);try{const firstImage=(await runware.requestImages(imageRequestArgs))[0];let output=firstImage.imageURL;return imageGenerator.reportUsage({cost:firstImage.cost},{modelEntryName:model,keySource:APIKeySource.Smyth,agentId:agent.id,teamId:agent.teamId}),{output}}catch(error){throw new Error(`Runware Image Generation Error: ${error?.message||JSON.stringify(error)}`)}finally{await runware.disconnect()}},imagen:async({model,prompt,config:config2,logger:logger2,agent,input})=>{try{const llmInference=await LLMInference$1.getInstance(model,AccessCandidate.agent(agent.id));if(!llmInference.connector)return{_error:`The model '${model}' is not available. Please try a different one.`,_debug:logger2.output};if(parseFiles(input,config2).length>0)throw new Error("Google AI Image Generation Error: Image editing is not supported. Imagen models only support image generation.");let args={model,aspectRatio:config2?.data?.aspectRatio||config2?.data?.size||"1:1",numberOfImages:config2?.data?.numberOfImages||1,personGeneration:config2?.data?.personGeneration||"allow_adult"};const response=await llmInference.imageGenRequest({query:prompt,params:{...args,agentId:agent.id}}),modelName=model.replace(BUILT_IN_MODEL_PREFIX,""),cost=IMAGEN_4_COST_MAP[modelName];if(cost&&cost>0){const numberOfImages=args.numberOfImages||1,totalCost=cost*numberOfImages;imageGenerator.reportUsage({cost:totalCost},{modelEntryName:model,keySource:model.startsWith(BUILT_IN_MODEL_PREFIX)?APIKeySource.Smyth:APIKeySource.User,agentId:agent.id,teamId:agent.teamId})}let output=response?.data?.[0]?.b64_json;if(output){const binaryInput=BinaryInput.from(output),agentId=typeof agent=="object"&&agent.id?agent.id:agent;return{output:await binaryInput.getJsonData(AccessCandidate.agent(agentId))}}else return output=response?.data?.[0]?.url,{output}}catch(error){throw new Error(`Google AI Image Generation Error: ${error?.message||JSON.stringify(error)}`)}},reportTokenUsage(usage,metadata){const usageData={sourceId:`api:imagegen.${metadata.modelEntryName.replace(BUILT_IN_MODEL_PREFIX,"")}`,keySource:metadata.keySource,input_tokens_txt:usage?.input_tokens_details?.text_tokens||0,input_tokens_img:usage?.input_tokens_details?.image_tokens||0,output_tokens:usage?.output_tokens,input_tokens_cache_read:usage?.prompt_tokens_details?.cached_tokens||0,agentId:metadata.agentId,teamId:metadata.teamId};return SystemEvents.emit("USAGE:API",usageData),usageData},reportUsage(usage,metadata){const usageData={sourceId:"api:imagegen.smyth",keySource:metadata.keySource,cost:usage?.cost,agentId:metadata.agentId,teamId:metadata.teamId};return SystemEvents.emit("USAGE:API",usageData),usageData},isValidImageFile(provider,mimetype){return SUPPORTED_MIME_TYPES_MAP[provider]?.imageGen?.includes(mimetype)}};async function getModelFamily(model,agent){return await isGPTModel(model)?"gpt":await isRunwareModel(model,agent)?"runware":await isDallEModel(model)?"dall-e":await isGoogleAIModel(model,agent)?"imagen":null}function isGPTModel(model){return model?.replace(BUILT_IN_MODEL_PREFIX,"")?.startsWith("gpt")}async function isRunwareModel(model,agent){const provider=await agent.modelsProvider.getProvider(model);return provider==="Runware"||provider?.toLowerCase()==="Runware".toLowerCase()}function isDallEModel(model){return model?.replace(BUILT_IN_MODEL_PREFIX,"")?.startsWith("dall-e")}async function isGoogleAIModel(model,agent){const provider=await agent.modelsProvider.getProvider(model);return provider==="GoogleAI"||provider?.toLowerCase()==="GoogleAI".toLowerCase()||model?.replace(BUILT_IN_MODEL_PREFIX,"")?.includes("imagen")}function parseFiles(input,config2){const mediaTypes=["Image","Audio","Video","Binary"];return config2.inputs?.filter(_input=>mediaTypes.includes(_input.type))?.flatMap(_input=>{const value=input[_input.name];return Array.isArray(value)?value.map(item=>TemplateString(item).parseRaw(input).result):TemplateString(value).parseRaw(input).result})?.filter(file=>file)||[]}var __defProp$16=Object.defineProperty,__defNormalProp$16=(obj,key,value)=>key in obj?__defProp$16(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$16=(obj,key,value)=>__defNormalProp$16(obj,key+"",value);class PromptGenerator extends Component{constructor(){super(),__publicField$16(this,"configSchema",Joi.object({model:Joi.string().max(200).required(),prompt:Joi.string().required().max(8e6).label("Prompt"),temperature:Joi.number().min(0).max(5).label("Temperature"),maxTokens:Joi.number().min(1).label("Maximum Tokens"),stopSequences:Joi.string().allow("").max(400).label("Stop Sequences"),topP:Joi.number().min(0).max(1).label("Top P"),topK:Joi.number().min(0).max(500).label("Top K"),frequencyPenalty:Joi.number().min(0).max(2).label("Frequency Penalty"),presencePenalty:Joi.number().min(0).max(2).label("Presence Penalty"),responseFormat:Joi.string().valid("json","text").optional().label("Response Format"),passthrough:Joi.boolean().optional().label("Passthrough")}))}init(){}async process(input,config2,agent){await super.process(input,config2,agent);const logger2=this.createComponentLogger(agent,config2);try{logger2.debug("=== LLM Prompt Log ===");let teamId=agent?.teamId;const passThrough=config2.data.passthrough||!1,model=config2.data.model||"echo",llmInference=await LLMInference$1.getInstance(model,AccessCandidate.agent(agent.id));if(!llmInference.connector)return{_error:`The model '${model}' is not available. Please try a different one.`,_debug:logger2.output};const modelId=await agent.modelsProvider.getModelId(model);logger2.debug(` Model : ${modelId||model}`);let prompt=TemplateString(config2.data.prompt).parse(input).result;logger2.debug(` Prompt
111
111
  `,prompt,`
112
112
  `),config2.data.responseFormat=config2.data?.responseFormat||"json";let response;if(passThrough?response=await new Promise(async(resolve,reject)=>{let _content="";const eventEmitter=await llmInference.promptStream({query:prompt,params:{...config2,model,agentId:agent.id}}).catch(error=>{console.error("Error on promptStream: ",error),reject(error)});eventEmitter.on("content",content=>{typeof agent.callback=="function"&&agent.callback({content}),agent.sse.send("llm/passthrough/content",content),_content+=content}),eventEmitter.on("thinking",thinking=>{typeof agent.callback=="function"&&agent.callback({thinking}),agent.sse.send("llm/passthrough/thinking",thinking)}),eventEmitter.on("end",()=>{console.log("end"),resolve(_content)})}):response=await llmInference.prompt({query:prompt,params:{...config2,agentId:agent.id}}).catch(error=>({error})),!response)return{_error:" LLM Error = Empty Response!",_debug:logger2.output};if(response?.error){const error=response?.error+" "+(response?.details||"");return logger2.error(" LLM Error=",error),{Reply:response?.data,_error:error,_debug:logger2.output}}logger2.debug(` Response
113
- `,response);const result={Reply:response};return result._debug=logger2.output,result}catch(error){return{_error:error.message,_debug:logger2.output}}}}async function parseHeaders(input,config2,agent){const teamId=agent?agent.teamId:null,templateSettings=config2?.template?.settings||{},contentType=config2?.data?.contentType||REQUEST_CONTENT_TYPES.none;let headers=typeof config2?.data?.headers=="object"?JSON.stringify(config2?.data?.headers):config2?.data?.headers||"{}";config2.data._templateVars&&templateSettings&&(headers=await TemplateString(headers).parseComponentTemplateVarsAsync(templateSettings).asyncResult,headers=await TemplateString(headers).parse(config2.data._templateVars).result),headers=await TemplateString(headers).parseTeamKeysAsync(teamId).asyncResult,headers=TemplateString(headers).parse(input).clean().result;let jsonHeaders=JSONContent(headers).tryParse();return typeof jsonHeaders!="object"&&(jsonHeaders={"x-smyth-error":"Error parsing headers"}),jsonHeaders=Object.fromEntries(Object.entries(jsonHeaders).map(([key,value])=>[key.toLowerCase(),value])),!jsonHeaders["content-type"]&&contentType!=="none"&&(jsonHeaders["content-type"]=contentType),new AxiosHeaders(jsonHeaders)}async function parseUrl(input,config2,agent){const teamId=agent?agent.teamId:null,templateSettings=config2?.template?.settings||{};let url=config2?.data?.url.replace(/\+/g,"%20");return config2.data._templateVars&&templateSettings&&(url=await TemplateString(url).parseComponentTemplateVarsAsync(templateSettings).asyncResult,url=await TemplateString(url).parse(config2.data._templateVars).result),url=await TemplateString(url).parseTeamKeysAsync(teamId).asyncResult,url=TemplateString(url).parse(input).clean().result,new URL(url).href}async function parseSmythFsUrl(url,agent){const urlObj=new URL(url),searchParams=urlObj.searchParams,publicUrls=[];for(const[key,value]of searchParams.entries())if(value.startsWith("smythfs://")){const pubUrl=await SmythFS.Instance.genTempUrl(value,AccessCandidate.agent(agent.id));publicUrls.push(pubUrl),searchParams.set(key,pubUrl)}return{url:urlObj.href,publicUrls}}async function destroyPublicUrls(publicUrls){try{await Promise.all(publicUrls.map(url=>SmythFS.Instance.destroyTempUrl(url))),console.log("Successfully cleaned up all temp urls for API Call Component")}catch(error){console.warn("Failed to clean up temp urls for API Call Component:",error)}return!0}async function parseData(input,config2,agent){const teamId=agent?agent.teamId:null,templateSettings=config2?.template?.settings||{},contentType=config2?.data?.contentType||REQUEST_CONTENT_TYPES.none;let body=typeof config2?.data?.body=="string"?config2?.data?.body?.trim():config2?.data?.body;if(!body)return{data:null,headers:{}};config2.data._templateVars&&templateSettings&&(body=await TemplateString(body).parseComponentTemplateVarsAsync(templateSettings).asyncResult),body=await TemplateString(body).parseTeamKeysAsync(teamId).asyncResult;const handler={[REQUEST_CONTENT_TYPES.json]:handleJson,[REQUEST_CONTENT_TYPES.urlEncodedFormData]:handleUrlEncoded,[REQUEST_CONTENT_TYPES.multipartFormData]:handleMultipartFormData,[REQUEST_CONTENT_TYPES.binary]:handleBinary,[REQUEST_CONTENT_TYPES.text]:handleText,[REQUEST_CONTENT_TYPES.none]:handleNone}[contentType]||handleNone,{data=null,headers={}}=await handler(body,input,config2,agent);return{data,headers}}async function handleJson(body,input,config2,agent){const data=TemplateString(body).parse(config2.data._templateVars).parse(input).clean().result;return{data:JSONContent(data).tryParse()}}async function handleUrlEncoded(body,input,config2,agent){const data=TemplateString(body).parse(config2.data._templateVars).parse(input).clean().result,jsonData=JSONContent(data).tryParse();if(typeof jsonData=="object"){const params=new URLSearchParams;for(const key in jsonData)params.append(key,String(jsonData[key]));return{data:params.toString()}}return{data:jsonData}}async function handleMultipartFormData(body,input,config2,agent){const formData=new FormData,_body=typeof body=="string"?JSON.parse(body):body;for(const key in _body){let value=_body[key];if(value=typeof value=="boolean"?String(value):value,value=TemplateString(value).parseRaw(input).result,value instanceof BinaryInput){const buffer=await value.getBuffer(),bufferStream=new Readable;bufferStream.push(buffer||null),bufferStream.push(null);const filename=await value.getName()||key;formData.append(key,bufferStream,{filename,contentType:value.mimetype})}else if(value&&typeof value=="object"&&value?.url){const binaryInput=await BinaryInput.from(value.url,"",value?.mimetype),buffer=await binaryInput.getBuffer(),bufferStream=new Readable;bufferStream.push(buffer||null),bufferStream.push(null);const filename=await binaryInput.getName()||key;formData.append(key,bufferStream,{filename,contentType:binaryInput.mimetype})}else value=TemplateString(value).parse(config2.data._templateVars).parse(input).clean().result,value&&formData.append(key,value)}return{data:formData,headers:formData.getHeaders()}}async function handleBinary(body,input,config2,agent){const value=TemplateString(body).parseRaw(input).result;if(value&&value instanceof BinaryInput)return{data:await value.getBuffer(),headers:{"Content-Type":value.mimetype}};if(value&&typeof value=="object"&&value?.url){const binaryInput=await BinaryInput.from(value.url,"",value?.mimetype);return{data:await binaryInput.getBuffer(),headers:{"Content-Type":binaryInput.mimetype}}}return{data:Buffer.from([]),headers:{}}}async function handleNone(body,input,config2,agent){return{data:typeof body=="string"?body:JSON.stringify(body),headers:{}}}function handleText(body,input,config2,agent){return{data:TemplateString(body).parse(config2.data._templateVars).parse(input).clean().result}}async function parseProxy(input,config2,agent){const teamId=agent?agent.teamId:null,templateSettings=config2?.template?.settings||{};let proxy=config2?.data?.proxy;if(!proxy)return!1;proxy=decodeURIComponent(proxy),config2.data._templateVars&&templateSettings&&(proxy=await TemplateString(proxy).parseComponentTemplateVarsAsync(templateSettings).parse(config2.data._templateVars).asyncResult),proxy=await TemplateString(proxy).parseTeamKeysAsync(teamId).asyncResult,proxy=TemplateString(proxy).parse(input).clean().result;const proxyList=proxy.split(/\n|\\n/).filter(p=>p)||[],randomIdx=Math.floor(Math.random()*proxyList?.length),proxyUrl=proxyList[randomIdx]?.trim(),urlObj=new URL(proxyUrl),protocol=urlObj.protocol.replace(":","");let proxyConfig;if(urlObj.protocol.startsWith("socks")){let proxyUrlString=`${protocol}://${urlObj.hostname}:${urlObj.port}`;(protocol==="socks4"||protocol==="socks4a")&&urlObj.username?proxyUrlString=`${protocol}://${urlObj.username}@${urlObj.hostname}:${urlObj.port}`:protocol==="socks5"&&urlObj.username&&(proxyUrlString=`${protocol}://${urlObj.username}:${urlObj.password}@${urlObj.hostname}:${urlObj.port}`),proxyConfig=new SocksProxyAgent(proxyUrlString)}else proxyConfig={protocol,host:urlObj.hostname,port:parseInt(urlObj.port),auth:urlObj.username?{username:urlObj.username,password:urlObj.password}:void 0};return proxyConfig}const mimeTypeCategories={binary:["image/","multipart/form-data","video/","application/msword","application/octet-stream","application/pdf","application/vnd.ms-excel","application/vnd.ms-powerpoint","application/vnd.oasis.opendocument.text","application/vnd.openxmlformats-officedocument","application/zip","application/x-7z-compressed","application/x-rar-compressed","application/x-tar","application/x-bzip","application/x-bzip2","application/x-gzip","application/vnd.android.package-archive","application/vnd.visio","application/x-deb","application/x-rpm","application/x-executable","font/ttf","font/otf","font/woff","font/woff2","model/"],json:["application/graphql","application/json","application/ld+json","application/vnd.api+json"],text:["text/","application/xml","application/xhtml+xml","application/csv","application/x-www-form-urlencoded","application/x-yaml","application/yaml","application/javascript","application/sql","application/rtf"]},contentHandlers={json:parseJson,text:parseText,binary:parseBinary};function parseJson(data){return JSON.parse(Buffer.from(data).toString("utf8")||"{}")}function parseText(data){return Buffer.from(data).toString("utf8")}async function parseBinary(data,contentType,agentId){return await BinaryInput.from(data,null,contentType).getJsonData(AccessCandidate.agent(agentId))}async function parseArrayBufferResponse(response,agent){if(!response?.data)return null;const data=response.data,contentType=response.headers["content-type"],cleanContentType=contentType?.split(";")[0];let handlerType=Object.keys(mimeTypeCategories).find(type=>mimeTypeCategories[type].includes(cleanContentType));handlerType||(handlerType=Object.keys(mimeTypeCategories).find(type=>mimeTypeCategories[type].some(prefix=>cleanContentType?.startsWith(prefix))));const handler=contentHandlers[handlerType];return handler?handler(data,contentType,agent.id):isBinaryMimeType(contentType)||isBinaryData(data)?parseBinary(data,contentType,agent.id):parseText(data)}var __defProp$15=Object.defineProperty,__defNormalProp$15=(obj,key,value)=>key in obj?__defProp$15(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$15=(obj,key,value)=>__defNormalProp$15(obj,typeof key!="symbol"?key+"":key,value);const console$p=Logger("AccessTokenManager");let managedVault$1;SystemEvents.on("SRE:Booted",()=>{managedVault$1=ConnectorService.getManagedVaultConnector()});class AccessTokenManager{constructor(clientId,clientSecret,secondaryToken,tokenUrl,expires_in,primaryToken,tokensData,keyId,logger2,agent,isNewStructure=!1){__publicField$15(this,"clientId"),__publicField$15(this,"clientSecret"),__publicField$15(this,"primaryToken"),__publicField$15(this,"secondaryToken"),__publicField$15(this,"tokenUrl"),__publicField$15(this,"expires_in"),__publicField$15(this,"tokensData"),__publicField$15(this,"keyId"),__publicField$15(this,"logger"),__publicField$15(this,"agent"),__publicField$15(this,"isNewStructure"),this.clientId=clientId,this.clientSecret=clientSecret,this.primaryToken=primaryToken,this.secondaryToken=secondaryToken,this.tokenUrl=tokenUrl,this.expires_in=expires_in,this.tokensData=tokensData,this.keyId=keyId,this.logger=logger2,this.agent=agent,this.isNewStructure=isNewStructure}async getAccessToken(){try{const currentTime=new Date().getTime();if(!this.secondaryToken&&!this.expires_in)return console$p.log("Using long-lived access token"),this.logger.debug("Using long-lived access token. If authentication failes, please re-authenticate and try again"),this.primaryToken;if(!this.expires_in||currentTime>=Number(this.expires_in)){if(!this.secondaryToken)throw this.logger.debug("Refresh token is missing. Please re authenticate"),console$p.log("Refresh token is missing. Please re authenticate..."),new Error("Reauthentication required");return this.logger.debug("Access token is expired or missing. Refreshing access token..."),console$p.log("Access token is expired or missing. Refreshing access token..."),await this.refreshAccessToken()}else return console$p.log("Access token is still valid"),this.logger.debug("Access token is still valid."),this.primaryToken}catch(error){throw console$p.error("Error fetching access token:",error),this.logger.debug("Error fetching access token"),error}}async refreshAccessToken(){try{const response=await axios.post(this.tokenUrl,new URLSearchParams({client_id:this.clientId,client_secret:this.clientSecret,refresh_token:this.secondaryToken,grant_type:"refresh_token"}).toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded"}}),newAccessToken=response?.data?.access_token;console$p.log("Access token refreshed successfully."),this.logger.debug("Access token refreshed successfully.");const expiresInMilliseconds=response?.data?.expires_in?response?.data?.expires_in*1e3:response?.data?.expires_in,expirationTimestamp=expiresInMilliseconds&&new Date().getTime()+expiresInMilliseconds;let updatedData;this.isNewStructure?updatedData={...this.tokensData,auth_data:{...this.tokensData?.auth_data??{},primary:newAccessToken,secondary:response?.data?.refresh_token??this.secondaryToken,expires_in:(expirationTimestamp??void 0)!==void 0?String(expirationTimestamp):void 0}}:(updatedData={...this.tokensData,primary:newAccessToken,expires_in:(expirationTimestamp??void 0)!==void 0?String(expirationTimestamp):void 0},updatedData.secondary=response?.data?.refresh_token??this.secondaryToken);const save=await managedVault$1.user(AccessCandidate.agent(this.agent.id)).set(this.keyId,JSON.stringify(updatedData));return save&&save.status===200?(console$p.log("Access token value is updated successfully."),this.logger.debug("Access token value is updated successfully.")):(console$p.log("Warning: new access token value is not updated."),this.logger.debug("Warning: new access token value is not updated.")),this.tokensData=updatedData,this.primaryToken=newAccessToken,this.secondaryToken=response?.data?.refresh_token??this.secondaryToken,this.expires_in=(expirationTimestamp??void 0)!==void 0?String(expirationTimestamp):void 0,newAccessToken}catch(error){throw console$p.error("Failed to refresh access token:",error),this.logger.debug(`Failed to refresh access token: ${error}`),new Error("Failed to refresh access token.")}}}const console$o=Logger("OAuth.helper");let managedVault;SystemEvents.on("SRE:Booted",()=>{try{managedVault=ConnectorService.getManagedVaultConnector()}catch{console$o.warn("Could not find a compatible ManagedVault connector, OAuth APICalls will not work")}});function extractAdditionalParamsForOAuth1(reqConfig={}){let additionalParams={};reqConfig.url&&(reqConfig.url.includes("{{")||reqConfig.url.includes("${{"))&&console$o.warn("Warning: URL contains unresolved template variables for OAuth1 signature:",reqConfig.url);try{const searchParams=new URL(reqConfig.url).searchParams;additionalParams=Object.fromEntries(searchParams.entries()),searchParams.toString()&&console$o.debug("OAuth1: Found query parameters:",Object.keys(additionalParams))}catch(error){console$o.warn("Failed to parse URL for OAuth1 parameters:",error)}const headers=reqConfig.headers||{};let contentType="";if(Array.isArray(headers)){const contentTypeHeader=headers.find(h=>Object.keys(h).some(k=>k.toLowerCase()==="content-type"));if(contentTypeHeader){const key=Object.keys(contentTypeHeader).find(k=>k.toLowerCase()==="content-type");contentType=contentTypeHeader[key]}}else contentType=headers["Content-Type"]||headers["content-type"]||"";const method=(reqConfig.method||"GET").toUpperCase();if(contentType.includes(REQUEST_CONTENT_TYPES.urlEncodedFormData)){if(reqConfig.data){let formParams={};if(typeof reqConfig.data=="string"){(reqConfig.data.includes("{{")||reqConfig.data.includes("${{"))&&console$o.warn("Warning: Form data contains unresolved template variables for OAuth1 signature");const formData=new URLSearchParams(reqConfig.data);formParams=Object.fromEntries(formData.entries())}else reqConfig.data instanceof URLSearchParams?formParams=Object.fromEntries(reqConfig.data.entries()):typeof reqConfig.data=="object"&&(formParams=reqConfig.data);console$o.debug("OAuth1: Including form parameters in signature:",Object.keys(formParams)),additionalParams={...additionalParams,...formParams}}}else if(contentType.includes(REQUEST_CONTENT_TYPES.json)||contentType.includes("application/")||contentType.includes("text/")){if(reqConfig.data&&method!=="GET"&&method!=="HEAD"){let bodyString="";typeof reqConfig.data=="string"?bodyString=reqConfig.data:bodyString=JSON.stringify(reqConfig.data),(bodyString.includes("{{")||bodyString.includes("${{"))&&console$o.warn("Warning: Request body contains unresolved template variables for OAuth1 signature");const hash=crypto$1.createHash("sha1").update(bodyString).digest("base64");additionalParams.oauth_body_hash=hash,console$o.debug("OAuth1: Added oauth_body_hash for",contentType)}}else if(contentType.includes(REQUEST_CONTENT_TYPES.multipartFormData)){if(reqConfig.data&&typeof reqConfig.data=="object"&&"entries"in reqConfig.data){const formData=reqConfig.data;for(const[key,value]of formData.entries())if(typeof value=="string")additionalParams[key]=value;else{if(typeof value=="object"&&value!==null&&("size"in value||"type"in value))continue;additionalParams[key]=String(value)}}}else if(!contentType&&(method==="POST"||method==="PUT"||method==="PATCH")&&reqConfig.data){const bodyString=typeof reqConfig.data=="string"?reqConfig.data:JSON.stringify(reqConfig.data),hash=crypto$1.createHash("sha1").update(bodyString).digest("base64");additionalParams.oauth_body_hash=hash}return console$o.debug("OAuth1: Total parameters for signature:",Object.keys(additionalParams).length),additionalParams}const buildOAuth1Header=(url,method,oauth1Credentials,additionalParams={})=>{const oauth=new OAuth({consumer:{key:oauth1Credentials.consumerKey,secret:oauth1Credentials.consumerSecret},signature_method:"HMAC-SHA1",hash_function(base_string,key){return crypto$1.createHmac("sha1",key).update(base_string).digest("base64")}});let baseUrl=url;try{const urlObj=new URL(url);baseUrl=`${urlObj.protocol}//${urlObj.host}${urlObj.pathname}`,console$o.debug("OAuth1: Base URL for signature:",baseUrl)}catch(error){console$o.warn("Failed to parse URL for OAuth1 signature:",error)}const requestData={url:baseUrl,method:method.toUpperCase(),data:additionalParams},token=oauth1Credentials.token&&oauth1Credentials.token!==""?{key:oauth1Credentials.token,secret:oauth1Credentials.tokenSecret||""}:null,signedRequest=oauth.authorize(requestData,token);return oauth.toHeader(signedRequest)},retrieveOAuthTokens=async(agent,config2)=>{let tokenKey=null;try{tokenKey=config2?.data?.oauth_con_id||`OAUTH_${config2?.id}_TOKENS`;try{const result=await managedVault.user(AccessCandidate.agent(agent.id)).get(tokenKey),tokensData=typeof result=="object"?result:JSON.parse(result||"{}");if(!tokensData)throw new Error("Failed to retrieve OAuth tokens from vault. Please authenticate ...");const isNewStructure=tokensData.auth_data!==void 0&&tokensData.auth_settings!==void 0,primaryToken=isNewStructure?tokensData.auth_data?.primary:tokensData.primary,secondaryToken=isNewStructure?tokensData.auth_data?.secondary:tokensData.secondary,expiresIn=isNewStructure?tokensData.auth_data?.expires_in:tokensData.expires_in,type=isNewStructure?tokensData.auth_settings?.type:tokensData.type||tokensData.oauth_info?.type,service=isNewStructure?tokensData.auth_settings?.service:tokensData.oauth_info?.service;if(type==="oauth2"&&service!=="oauth2_client_credentials"&&(secondaryToken||console$o.warn("Warning: refresh_token is missing for OAuth2"),expiresIn||console$o.warn("Warning: expires_in is missing for OAuth2.")),service!=="oauth2_client_credentials"&&!primaryToken)throw new Error("Retrieved OAuth tokens do not exist, invalid OR incomplete. Please authenticate ...");const responseData={primaryToken,secondaryToken,type,service};return type==="oauth"?(isNewStructure?(responseData.consumerKey=tokensData.auth_settings?.consumerKey,responseData.consumerSecret=tokensData.auth_settings?.consumerSecret,responseData.tokenURL=tokensData.auth_settings?.tokenURL):(responseData.consumerKey=tokensData.consumerKey||tokensData.oauth_info?.consumerKey,responseData.consumerSecret=tokensData.consumerSecret||tokensData.oauth_info?.consumerSecret,responseData.tokenURL=tokensData.tokenURL||tokensData.oauth_info?.tokenURL),responseData.team=tokensData.team||agent.teamId):type==="oauth2"&&(isNewStructure?(responseData.tokenURL=tokensData.auth_settings?.tokenURL,responseData.clientID=tokensData.auth_settings?.clientID,responseData.clientSecret=tokensData.auth_settings?.clientSecret):(responseData.tokenURL=tokensData.tokenURL||tokensData.oauth_info?.tokenURL,responseData.clientID=tokensData.clientID||tokensData.oauth_info?.clientID,responseData.clientSecret=tokensData.clientSecret||tokensData.oauth_info?.clientSecret),responseData.expiresIn=expiresIn??0,responseData.team=tokensData.team||agent.teamId),{responseData,tokensData,keyId:tokenKey,isNewStructure}}catch(error){throw new Error(`Failed to parse retrieved tokens: ${error}`)}}catch(error){throw console$o.error("Error retrieving OAuth tokens:",error),error}},handleOAuthHeaders=async(agent,config2,reqConfig,logger2,additionalParams={})=>{let headers={};const{responseData:oauthTokens,tokensData,keyId,isNewStructure}=await retrieveOAuthTokens(agent,config2);try{let oAuthConfigString=JSON.stringify({consumerKey:oauthTokens.consumerKey||"",consumerSecret:oauthTokens.consumerSecret||"",clientID:oauthTokens.clientID||"",clientSecret:oauthTokens.clientSecret||"",tokenURL:oauthTokens.tokenURL||""});oAuthConfigString=await TemplateString(oAuthConfigString).parseTeamKeysAsync(oauthTokens.team||agent.teamId).asyncResult;const oAuthConfig=JSON.parse(oAuthConfigString);if(oauthTokens.service==="oauth2_client_credentials"){const accessToken=await getClientCredentialToken(tokensData,logger2,keyId,oauthTokens,config2,agent,isNewStructure);headers.Authorization=`Bearer ${accessToken}`}else if(oauthTokens.type==="oauth"){const oauthHeader=buildOAuth1Header(reqConfig.url,reqConfig.method,{consumerKey:oAuthConfig.consumerKey,consumerSecret:oAuthConfig.consumerSecret,token:oauthTokens.primaryToken,tokenSecret:oauthTokens.secondaryToken},additionalParams);headers={...reqConfig.headers,...oauthHeader},logger2.debug("OAuth1 access token check success.")}else if(oauthTokens.type==="oauth2"){const accessToken=await new AccessTokenManager(oAuthConfig.clientID,oAuthConfig.clientSecret,oauthTokens.secondaryToken,oAuthConfig.tokenURL,oauthTokens.expiresIn,oauthTokens.primaryToken,tokensData,keyId,logger2,agent,isNewStructure).getAccessToken();headers.Authorization=`Bearer ${accessToken}`}return headers}catch(error){throw logger2.error(`Access token check failed: ${error}`),error}};async function getClientCredentialToken(tokensData,logger2,keyId,oauthTokens,config2,agent,isNewStructure=!1){const logAndThrowError=message=>{throw logger2.debug(message),new Error(message)};try{const{clientID,clientSecret,tokenURL}=oauthTokens,currentTime=new Date().getTime();if(!oauthTokens.expiresIn||currentTime>=Number(oauthTokens.expiresIn)){(!clientID||!clientSecret||!tokenURL)&&logAndThrowError("Missing client_id, client_secret OR token_url");const params=new URLSearchParams({grant_type:"client_credentials",client_id:clientID,client_secret:clientSecret}),response=await axios.post(tokenURL,params.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded"}});console$o.log("Access token refreshed successfully."),logger2.debug("Access token refreshed successfully.");const newAccessToken=response.data.access_token,expiresInMilliseconds=response.data.expires_in*1e3,expirationTimestamp=currentTime+expiresInMilliseconds;let updatedData;if(isNewStructure){const parts=String(config2?.data?.oauth_con_id??"").split("_"),prefixSuffix=parts.length>1?parts[1]:parts[0],oauthKeysPrefix=prefixSuffix?`OAUTH_${prefixSuffix}`:void 0;updatedData={...tokensData||{},auth_data:{...tokensData?.auth_data||{},primary:newAccessToken,expires_in:expirationTimestamp.toString()},auth_settings:{...tokensData?.auth_settings||{},type:"oauth2",tokenURL,clientID,clientSecret,...oauthKeysPrefix?{oauth_keys_prefix:oauthKeysPrefix}:{},service:"oauth2_client_credentials"}}}else updatedData={...tokensData,primary:newAccessToken,expires_in:expirationTimestamp.toString()},updatedData.type||(updatedData.type="oauth2"),updatedData.tokenURL||(updatedData.tokenURL=tokenURL),updatedData.team||(updatedData.team=agent.teamId),updatedData.oauth_info||(updatedData.oauth_info={oauth_keys_prefix:`OAUTH_${config2?.data?.oauth_con_id?.split("_")[1]||config2?.id}`,service:"oauth2_client_credentials",tokenURL,clientID,clientSecret});return await managedVault.user(AccessCandidate.agent(agent.id)).set(keyId,JSON.stringify(updatedData)),newAccessToken}else return console$o.log("Access token value is still valid."),logger2.debug("Access token value is still valid."),oauthTokens.primaryToken}catch(error){logAndThrowError(`Failed to refresh access token: ${error}`)}}var __defProp$14=Object.defineProperty,__defNormalProp$14=(obj,key,value)=>key in obj?__defProp$14(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$14=(obj,key,value)=>__defNormalProp$14(obj,typeof key!="symbol"?key+"":key,value);class APICall extends Component{constructor(){super(),__publicField$14(this,"schema",{name:"APICall",description:"Use this component to make an API call",inputs:{},outputs:{Headers:{description:"The headers of the API call response",default:!0},Response:{description:"The response of the API call",default:!0}}}),__publicField$14(this,"configSchema",Joi.object({method:Joi.string().valid("GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS").required().label("Method"),url:Joi.string().max(8192).required().label("URL"),headers:Joi.any().allow("").label("Headers"),contentType:Joi.string().valid("none","application/json","multipart/form-data","binary","application/x-www-form-urlencoded","text/plain","application/xml").label("Content-Type"),body:Joi.any().allow("").label("Body"),_templateSettings:Joi.object().allow(null).label("Template Settings"),_templateVars:Joi.object().allow(null).label("Template Variables"),proxy:Joi.string().allow("").label("Proxy"),oauthService:Joi.string().allow("").label("OAuth Service"),scope:Joi.string().allow("").label("Scope"),authorizationURL:Joi.string().allow("").label("Authorization URL"),tokenURL:Joi.string().allow("").label("Token URL"),clientID:Joi.string().allow("").label("Client ID"),clientSecret:Joi.string().allow("").label("Client Secret"),oauth2CallbackURL:Joi.string().allow("").label("OAuth2 Callback URL"),callbackURL:Joi.string().allow("").label("Callback URL"),requestTokenURL:Joi.string().allow("").label("Request Token URL"),accessTokenURL:Joi.string().allow("").label("Access Token URL"),userAuthorizationURL:Joi.string().allow("").label("User Authorization URL"),consumerKey:Joi.string().allow("").label("Consumer Key"),consumerSecret:Joi.string().allow("").label("Consumer Secret"),oauth1CallbackURL:Joi.string().allow("").label("OAuth1 Callback URL"),authenticate:Joi.string().allow("").label("Authenticate"),oauth_con_id:Joi.string().allow("").label("OAuth Connection ID")}))}init(){}async process(input,config2,agent){await super.process(input,config2,agent);const logger2=this.createComponentLogger(agent,config2);let publicUrls=[];try{logger2.debug("=== API Call Log ===");const method=config2?.data?.method||"get",reqConfig={};reqConfig.method=method,reqConfig.url=await parseUrl(input,config2,agent),{url:reqConfig.url,publicUrls}=await parseSmythFsUrl(reqConfig.url,agent);const{data,headers}=await parseData(input,config2,agent);let dataForDebug;data&&(reqConfig.data=data,dataForDebug=await formatDataForDebug(data,AccessCandidate.agent(agent.id))),reqConfig.headers=(await parseHeaders(input,config2,agent)).concat({...headers});const proxyConfig=await parseProxy(input,config2,agent);if(proxyConfig)if(proxyConfig instanceof SocksProxyAgent){const isSecureEndpoint=reqConfig.url?.startsWith("https://");reqConfig[isSecureEndpoint?"httpsAgent":"httpAgent"]=proxyConfig}else reqConfig.proxy=proxyConfig;let Response={},Headers={},_error;try{if(logger2.debug("checking oauth config",config2?.data?.oauth_con_id,config2?.data?.oauthService),config2?.data?.oauth_con_id!==void 0&&config2?.data?.oauth_con_id!==""&&config2?.data?.oauth_con_id!=="None"||config2?.data?.oauthService!==""&&config2.data.oauthService!=="None"){const additionalParams=extractAdditionalParamsForOAuth1(reqConfig),oauthHeaders=await handleOAuthHeaders(agent,config2,reqConfig,logger2,additionalParams);reqConfig.headers=reqConfig.headers.concat({...oauthHeaders})}reqConfig.responseType="arraybuffer",logger2.debug("Making API call",{...reqConfig,data:dataForDebug});const response=await axios.request(reqConfig),parsedRes=await parseArrayBufferResponse(response,agent);logger2.debug("API call Response Headers",response.headers),Response=parsedRes,logger2.debug(`API call Response
113
+ `,response);const result={Reply:response};return result._debug=logger2.output,result}catch(error){return{_error:error.message,_debug:logger2.output}}}}async function parseHeaders(input,config2,agent){const teamId=agent?agent.teamId:null,templateSettings=config2?.template?.settings||{},contentType=config2?.data?.contentType||REQUEST_CONTENT_TYPES.none;let headers=typeof config2?.data?.headers=="object"?JSON.stringify(config2?.data?.headers):config2?.data?.headers||"{}";config2.data._templateVars&&templateSettings&&(headers=await TemplateString(headers).parseComponentTemplateVarsAsync(templateSettings).asyncResult,headers=await TemplateString(headers).parse(config2.data._templateVars).result),headers=await TemplateString(headers).parseTeamKeysAsync(teamId).asyncResult,headers=TemplateString(headers).parse(input).clean().result;let jsonHeaders=JSONContent(headers).tryParse();return typeof jsonHeaders!="object"&&(jsonHeaders={"x-smyth-error":"Error parsing headers"}),jsonHeaders=Object.fromEntries(Object.entries(jsonHeaders).map(([key,value])=>[key.toLowerCase(),value])),!jsonHeaders["content-type"]&&contentType!=="none"&&(jsonHeaders["content-type"]=contentType),new AxiosHeaders(jsonHeaders)}async function parseUrl(input,config2,agent){const teamId=agent?agent.teamId:null,templateSettings=config2?.template?.settings||{};let url=config2?.data?.url.replace(/\+/g,"%20");return config2.data._templateVars&&templateSettings&&(url=await TemplateString(url).parseComponentTemplateVarsAsync(templateSettings).asyncResult,url=await TemplateString(url).parse(config2.data._templateVars).result),url=await TemplateString(url).parseTeamKeysAsync(teamId).asyncResult,url=TemplateString(url).parse(input).clean().result,new URL(url).href}async function parseSmythFsUrl(url,agent){const urlObj=new URL(url),searchParams=urlObj.searchParams,publicUrls=[];for(const[key,value]of searchParams.entries())if(value.startsWith("smythfs://")){const pubUrl=await SmythFS.Instance.genTempUrl(value,AccessCandidate.agent(agent.id));publicUrls.push(pubUrl),searchParams.set(key,pubUrl)}return{url:urlObj.href,publicUrls}}async function destroyPublicUrls(publicUrls){try{await Promise.all(publicUrls.map(url=>SmythFS.Instance.destroyTempUrl(url))),console.log("Successfully cleaned up all temp urls for API Call Component")}catch(error){console.warn("Failed to clean up temp urls for API Call Component:",error)}return!0}async function parseData(input,config2,agent){const teamId=agent?agent.teamId:null,templateSettings=config2?.template?.settings||{},contentType=config2?.data?.contentType||REQUEST_CONTENT_TYPES.none;let body=typeof config2?.data?.body=="string"?config2?.data?.body?.trim():config2?.data?.body;if(!body)return{data:null,headers:{}};config2.data._templateVars&&templateSettings&&(body=await TemplateString(body).parseComponentTemplateVarsAsync(templateSettings).asyncResult),body=await TemplateString(body).parseTeamKeysAsync(teamId).asyncResult;const handler={[REQUEST_CONTENT_TYPES.json]:handleJson,[REQUEST_CONTENT_TYPES.urlEncodedFormData]:handleUrlEncoded,[REQUEST_CONTENT_TYPES.multipartFormData]:handleMultipartFormData,[REQUEST_CONTENT_TYPES.binary]:handleBinary,[REQUEST_CONTENT_TYPES.text]:handleText,[REQUEST_CONTENT_TYPES.none]:handleNone}[contentType]||handleNone,{data=null,headers={}}=await handler(body,input,config2,agent);return{data,headers}}async function handleJson(body,input,config2,agent){const data=TemplateString(body).parse(config2.data._templateVars).parse(input).clean().result;return{data:JSONContent(data).tryParse()}}async function handleUrlEncoded(body,input,config2,agent){const data=TemplateString(body).parse(config2.data._templateVars).parse(input).clean().result,jsonData=JSONContent(data).tryParse();if(typeof jsonData=="object"){const params=new URLSearchParams;for(const key in jsonData)params.append(key,String(jsonData[key]));return{data:params.toString()}}return{data:jsonData}}async function handleMultipartFormData(body,input,config2,agent){const formData=new FormData,_body=typeof body=="string"?JSON.parse(body):body;for(const key in _body){let value=_body[key];if(value=typeof value=="boolean"?String(value):value,value=TemplateString(value).parseRaw(input).result,value instanceof BinaryInput){const buffer=await value.getBuffer(),bufferStream=new Readable;bufferStream.push(buffer||null),bufferStream.push(null);const filename=await value.getName()||key;formData.append(key,bufferStream,{filename,contentType:value.mimetype})}else if(value&&typeof value=="object"&&value?.url){const binaryInput=await BinaryInput.from(value.url,"",value?.mimetype),buffer=await binaryInput.getBuffer(),bufferStream=new Readable;bufferStream.push(buffer||null),bufferStream.push(null);const filename=await binaryInput.getName()||key;formData.append(key,bufferStream,{filename,contentType:binaryInput.mimetype})}else value=TemplateString(value).parse(config2.data._templateVars).parse(input).clean().result,value&&formData.append(key,value)}return{data:formData,headers:formData.getHeaders()}}async function handleBinary(body,input,config2,agent){const value=TemplateString(body).parseRaw(input).result;if(value&&value instanceof BinaryInput)return{data:await value.getBuffer(),headers:{"Content-Type":value.mimetype}};if(value&&typeof value=="object"&&value?.url){const binaryInput=await BinaryInput.from(value.url,"",value?.mimetype);return{data:await binaryInput.getBuffer(),headers:{"Content-Type":binaryInput.mimetype}}}return{data:Buffer.from([]),headers:{}}}async function handleNone(body,input,config2,agent){return{data:typeof body=="string"?body:JSON.stringify(body),headers:{}}}function handleText(body,input,config2,agent){return{data:TemplateString(body).parse(config2.data._templateVars).parse(input).clean().result}}async function parseProxy(input,config2,agent){const teamId=agent?agent.teamId:null,templateSettings=config2?.template?.settings||{};let proxy=config2?.data?.proxy;if(!proxy)return!1;proxy=decodeURIComponent(proxy),config2.data._templateVars&&templateSettings&&(proxy=await TemplateString(proxy).parseComponentTemplateVarsAsync(templateSettings).parse(config2.data._templateVars).asyncResult),proxy=await TemplateString(proxy).parseTeamKeysAsync(teamId).asyncResult,proxy=TemplateString(proxy).parse(input).clean().result;const proxyList=proxy.split(/\n|\\n/).filter(p=>p)||[],randomIdx=Math.floor(Math.random()*proxyList?.length),proxyUrl=proxyList[randomIdx]?.trim(),urlObj=new URL(proxyUrl),protocol=urlObj.protocol.replace(":","");let proxyConfig;if(urlObj.protocol.startsWith("socks")){let proxyUrlString=`${protocol}://${urlObj.hostname}:${urlObj.port}`;(protocol==="socks4"||protocol==="socks4a")&&urlObj.username?proxyUrlString=`${protocol}://${urlObj.username}@${urlObj.hostname}:${urlObj.port}`:protocol==="socks5"&&urlObj.username&&(proxyUrlString=`${protocol}://${urlObj.username}:${urlObj.password}@${urlObj.hostname}:${urlObj.port}`),proxyConfig=new SocksProxyAgent(proxyUrlString)}else proxyConfig={protocol,host:urlObj.hostname,port:parseInt(urlObj.port),auth:urlObj.username?{username:urlObj.username,password:urlObj.password}:void 0};return proxyConfig}const mimeTypeCategories={binary:["image/","multipart/form-data","video/","application/msword","application/octet-stream","application/pdf","application/vnd.ms-excel","application/vnd.ms-powerpoint","application/vnd.oasis.opendocument.text","application/vnd.openxmlformats-officedocument","application/zip","application/x-7z-compressed","application/x-rar-compressed","application/x-tar","application/x-bzip","application/x-bzip2","application/x-gzip","application/vnd.android.package-archive","application/vnd.visio","application/x-deb","application/x-rpm","application/x-executable","font/ttf","font/otf","font/woff","font/woff2","model/"],json:["application/graphql","application/json","application/ld+json","application/vnd.api+json"],text:["text/","application/xml","application/xhtml+xml","application/csv","application/x-www-form-urlencoded","application/x-yaml","application/yaml","application/javascript","application/sql","application/rtf"]},contentHandlers={json:parseJson,text:parseText,binary:parseBinary};function parseJson(data){return JSON.parse(Buffer.from(data).toString("utf8")||"{}")}function parseText(data){return Buffer.from(data).toString("utf8")}async function parseBinary(data,contentType,agentId){return await BinaryInput.from(data,null,contentType).getJsonData(AccessCandidate.agent(agentId))}async function parseArrayBufferResponse(response,agent){if(!response?.data)return null;const data=response.data,contentType=response.headers["content-type"],cleanContentType=contentType?.split(";")[0];let handlerType=Object.keys(mimeTypeCategories).find(type=>mimeTypeCategories[type].includes(cleanContentType));handlerType||(handlerType=Object.keys(mimeTypeCategories).find(type=>mimeTypeCategories[type].some(prefix=>cleanContentType?.startsWith(prefix))));const handler=contentHandlers[handlerType];return handler?handler(data,contentType,agent.id):isBinaryMimeType(contentType)||isBinaryData(data)?parseBinary(data,contentType,agent.id):parseText(data)}var __defProp$15=Object.defineProperty,__defNormalProp$15=(obj,key,value)=>key in obj?__defProp$15(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$15=(obj,key,value)=>__defNormalProp$15(obj,typeof key!="symbol"?key+"":key,value);const console$p=Logger("AccessTokenManager");let managedVault$1;SystemEvents.on("SRE:Booted",()=>{managedVault$1=ConnectorService.getManagedVaultConnector()});class AccessTokenManager{constructor(clientId,clientSecret,secondaryToken,tokenUrl,expires_in,primaryToken,tokensData,keyId,logger2,agent,isNewStructure=!1){__publicField$15(this,"clientId"),__publicField$15(this,"clientSecret"),__publicField$15(this,"primaryToken"),__publicField$15(this,"secondaryToken"),__publicField$15(this,"tokenUrl"),__publicField$15(this,"expires_in"),__publicField$15(this,"tokensData"),__publicField$15(this,"keyId"),__publicField$15(this,"logger"),__publicField$15(this,"agent"),__publicField$15(this,"isNewStructure"),this.clientId=clientId,this.clientSecret=clientSecret,this.primaryToken=primaryToken,this.secondaryToken=secondaryToken,this.tokenUrl=tokenUrl,this.expires_in=expires_in,this.tokensData=tokensData,this.keyId=keyId,this.logger=logger2,this.agent=agent,this.isNewStructure=isNewStructure}async getAccessToken(){try{const currentTime=new Date().getTime();if(!this.secondaryToken&&!this.expires_in)return console$p.log("Using long-lived access token"),this.logger.debug("Using long-lived access token. If authentication failes, please re-authenticate and try again"),this.primaryToken;if(!this.expires_in||currentTime>=Number(this.expires_in)){if(!this.secondaryToken)throw this.logger.debug("Refresh token is missing. Please re authenticate"),console$p.log("Refresh token is missing. Please re authenticate..."),new Error("Reauthentication required");return this.logger.debug("Access token is expired or missing. Refreshing access token..."),console$p.log("Access token is expired or missing. Refreshing access token..."),await this.refreshAccessToken()}else return console$p.log("Access token is still valid"),this.logger.debug("Access token is still valid."),this.primaryToken}catch(error){throw console$p.error("Error fetching access token:",error),this.logger.debug("Error fetching access token"),error}}async refreshAccessToken(){try{const response=await axios.post(this.tokenUrl,new URLSearchParams({client_id:this.clientId,client_secret:this.clientSecret,refresh_token:this.secondaryToken,grant_type:"refresh_token"}).toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded"}}),newAccessToken=response?.data?.access_token;console$p.log("Access token refreshed successfully."),this.logger.debug("Access token refreshed successfully.");const expiresInMilliseconds=response?.data?.expires_in?response?.data?.expires_in*1e3:response?.data?.expires_in,expirationTimestamp=expiresInMilliseconds&&new Date().getTime()+expiresInMilliseconds;let updatedData;this.isNewStructure?updatedData={...this.tokensData,auth_data:{...this.tokensData?.auth_data??{},primary:newAccessToken,secondary:response?.data?.refresh_token??this.secondaryToken,expires_in:(expirationTimestamp??void 0)!==void 0?String(expirationTimestamp):void 0}}:(updatedData={...this.tokensData,primary:newAccessToken,expires_in:(expirationTimestamp??void 0)!==void 0?String(expirationTimestamp):void 0},updatedData.secondary=response?.data?.refresh_token??this.secondaryToken);const save=await managedVault$1.user(AccessCandidate.agent(this.agent.id)).set(this.keyId,JSON.stringify(updatedData));return save&&save.status===200?(console$p.log("Access token value is updated successfully."),this.logger.debug("Access token value is updated successfully.")):(console$p.log("Warning: new access token value is not updated."),this.logger.debug("Warning: new access token value is not updated.")),this.tokensData=updatedData,this.primaryToken=newAccessToken,this.secondaryToken=response?.data?.refresh_token??this.secondaryToken,this.expires_in=(expirationTimestamp??void 0)!==void 0?String(expirationTimestamp):void 0,newAccessToken}catch(error){throw console$p.error("Failed to refresh access token:",error),this.logger.debug(`Failed to refresh access token: ${error}`),new Error("Failed to refresh access token.")}}}const console$o=Logger("OAuth.helper");let managedVault;SystemEvents.on("SRE:Booted",()=>{try{managedVault=ConnectorService.getManagedVaultConnector()}catch{console$o.warn("Could not find a compatible ManagedVault connector, OAuth APICalls will not work")}});function extractAdditionalParamsForOAuth1(reqConfig={}){let additionalParams={};reqConfig.url&&(reqConfig.url.includes("{{")||reqConfig.url.includes("${{"))&&console$o.warn("Warning: URL contains unresolved template variables for OAuth1 signature:",reqConfig.url);try{const searchParams=new URL(reqConfig.url).searchParams;additionalParams=Object.fromEntries(searchParams.entries()),searchParams.toString()&&console$o.debug("OAuth1: Found query parameters:",Object.keys(additionalParams))}catch(error){console$o.warn("Failed to parse URL for OAuth1 parameters:",error)}const headers=reqConfig.headers||{};let contentType="";if(Array.isArray(headers)){const contentTypeHeader=headers.find(h=>Object.keys(h).some(k=>k.toLowerCase()==="content-type"));if(contentTypeHeader){const key=Object.keys(contentTypeHeader).find(k=>k.toLowerCase()==="content-type");contentType=contentTypeHeader[key]}}else contentType=headers["Content-Type"]||headers["content-type"]||"";const method=(reqConfig.method||"GET").toUpperCase();if(contentType.includes(REQUEST_CONTENT_TYPES.urlEncodedFormData)){if(reqConfig.data){let formParams={};if(typeof reqConfig.data=="string"){(reqConfig.data.includes("{{")||reqConfig.data.includes("${{"))&&console$o.warn("Warning: Form data contains unresolved template variables for OAuth1 signature");const formData=new URLSearchParams(reqConfig.data);formParams=Object.fromEntries(formData.entries())}else reqConfig.data instanceof URLSearchParams?formParams=Object.fromEntries(reqConfig.data.entries()):typeof reqConfig.data=="object"&&(formParams=reqConfig.data);console$o.debug("OAuth1: Including form parameters in signature:",Object.keys(formParams)),additionalParams={...additionalParams,...formParams}}}else if(contentType.includes(REQUEST_CONTENT_TYPES.json)||contentType.includes("application/")||contentType.includes("text/")){if(reqConfig.data&&method!=="GET"&&method!=="HEAD"){let bodyString="";typeof reqConfig.data=="string"?bodyString=reqConfig.data:bodyString=JSON.stringify(reqConfig.data),(bodyString.includes("{{")||bodyString.includes("${{"))&&console$o.warn("Warning: Request body contains unresolved template variables for OAuth1 signature");const hash=crypto$1.createHash("sha1").update(bodyString).digest("base64");additionalParams.oauth_body_hash=hash,console$o.debug("OAuth1: Added oauth_body_hash for",contentType)}}else if(contentType.includes(REQUEST_CONTENT_TYPES.multipartFormData)){if(reqConfig.data&&typeof reqConfig.data=="object"&&"entries"in reqConfig.data){const formData=reqConfig.data;for(const[key,value]of formData.entries())if(typeof value=="string")additionalParams[key]=value;else{if(typeof value=="object"&&value!==null&&("size"in value||"type"in value))continue;additionalParams[key]=String(value)}}}else if(!contentType&&(method==="POST"||method==="PUT"||method==="PATCH")&&reqConfig.data){const bodyString=typeof reqConfig.data=="string"?reqConfig.data:JSON.stringify(reqConfig.data),hash=crypto$1.createHash("sha1").update(bodyString).digest("base64");additionalParams.oauth_body_hash=hash}return console$o.debug("OAuth1: Total parameters for signature:",Object.keys(additionalParams).length),additionalParams}const buildOAuth1Header=(url,method,oauth1Credentials,additionalParams={})=>{const oauth=new OAuth({consumer:{key:oauth1Credentials.consumerKey,secret:oauth1Credentials.consumerSecret},signature_method:"HMAC-SHA1",hash_function(base_string,key){return crypto$1.createHmac("sha1",key).update(base_string).digest("base64")}});let baseUrl=url;try{const urlObj=new URL(url);baseUrl=`${urlObj.protocol}//${urlObj.host}${urlObj.pathname}`,console$o.debug("OAuth1: Base URL for signature:",baseUrl)}catch(error){console$o.warn("Failed to parse URL for OAuth1 signature:",error)}const requestData={url:baseUrl,method:method.toUpperCase(),data:additionalParams},token=oauth1Credentials.token&&oauth1Credentials.token!==""?{key:oauth1Credentials.token,secret:oauth1Credentials.tokenSecret||""}:null,signedRequest=oauth.authorize(requestData,token);return oauth.toHeader(signedRequest)},retrieveOAuthTokens=async(agent,config2)=>{let tokenKey=null;try{tokenKey=config2?.data?.oauth_con_id||`OAUTH_${config2?.id}_TOKENS`;try{const result=await managedVault.user(AccessCandidate.agent(agent.id)).get(tokenKey),tokensData=typeof result=="object"?result:JSON.parse(result||"{}");if(!tokensData)throw new Error("Failed to retrieve OAuth tokens from vault. Please authenticate ...");const isNewStructure=tokensData.auth_data!==void 0&&tokensData.auth_settings!==void 0,primaryToken=isNewStructure?tokensData.auth_data?.primary:tokensData.primary,secondaryToken=isNewStructure?tokensData.auth_data?.secondary:tokensData.secondary,expiresIn=isNewStructure?tokensData.auth_data?.expires_in:tokensData.expires_in,type=isNewStructure?tokensData.auth_settings?.type:tokensData.type||tokensData.oauth_info?.type,service=isNewStructure?tokensData.auth_settings?.service:tokensData.oauth_info?.service;if(type==="oauth2"&&service!=="oauth2_client_credentials"&&(secondaryToken||console$o.warn("Warning: refresh_token is missing for OAuth2"),expiresIn||console$o.warn("Warning: expires_in is missing for OAuth2.")),service!=="oauth2_client_credentials"&&!primaryToken)throw new Error("Retrieved OAuth tokens do not exist, invalid OR incomplete. Please authenticate ...");const responseData={primaryToken,secondaryToken,type,service};return type==="oauth"?(isNewStructure?(responseData.consumerKey=tokensData.auth_settings?.consumerKey,responseData.consumerSecret=tokensData.auth_settings?.consumerSecret,responseData.tokenURL=tokensData.auth_settings?.tokenURL):(responseData.consumerKey=tokensData.consumerKey||tokensData.oauth_info?.consumerKey,responseData.consumerSecret=tokensData.consumerSecret||tokensData.oauth_info?.consumerSecret,responseData.tokenURL=tokensData.tokenURL||tokensData.oauth_info?.tokenURL),responseData.team=tokensData.team||agent.teamId):type==="oauth2"&&(isNewStructure?(responseData.tokenURL=tokensData.auth_settings?.tokenURL,responseData.clientID=tokensData.auth_settings?.clientID,responseData.clientSecret=tokensData.auth_settings?.clientSecret):(responseData.tokenURL=tokensData.tokenURL||tokensData.oauth_info?.tokenURL,responseData.clientID=tokensData.clientID||tokensData.oauth_info?.clientID,responseData.clientSecret=tokensData.clientSecret||tokensData.oauth_info?.clientSecret),responseData.expiresIn=expiresIn??0,responseData.team=tokensData.team||agent.teamId),{responseData,tokensData,keyId:tokenKey,isNewStructure}}catch(error){throw new Error(`Failed to parse retrieved tokens: ${error}`)}}catch(error){throw console$o.error("Error retrieving OAuth tokens:",error),error}},handleOAuthHeaders=async(agent,config2,reqConfig,logger2,additionalParams={})=>{let headers={};const{responseData:oauthTokens,tokensData,keyId,isNewStructure}=await retrieveOAuthTokens(agent,config2);try{let oAuthConfigString=JSON.stringify({consumerKey:oauthTokens.consumerKey||"",consumerSecret:oauthTokens.consumerSecret||"",clientID:oauthTokens.clientID||"",clientSecret:oauthTokens.clientSecret||"",tokenURL:oauthTokens.tokenURL||""});oAuthConfigString=await TemplateString(oAuthConfigString).parseTeamKeysAsync(oauthTokens.team||agent.teamId).asyncResult;const oAuthConfig=JSON.parse(oAuthConfigString);if(oauthTokens.service==="oauth2_client_credentials"){const accessToken=await getClientCredentialToken(tokensData,logger2,keyId,oauthTokens,config2,agent,isNewStructure);headers.Authorization=`Bearer ${accessToken}`}else if(oauthTokens.type==="oauth"){const oauthHeader=buildOAuth1Header(reqConfig.url,reqConfig.method,{consumerKey:oAuthConfig.consumerKey,consumerSecret:oAuthConfig.consumerSecret,token:oauthTokens.primaryToken,tokenSecret:oauthTokens.secondaryToken},additionalParams);headers={...reqConfig.headers,...oauthHeader},logger2.debug("OAuth1 access token check success.")}else if(oauthTokens.type==="oauth2"){const accessToken=await new AccessTokenManager(oAuthConfig.clientID,oAuthConfig.clientSecret,oauthTokens.secondaryToken,oAuthConfig.tokenURL,oauthTokens.expiresIn,oauthTokens.primaryToken,tokensData,keyId,logger2,agent,isNewStructure).getAccessToken();headers.Authorization=`Bearer ${accessToken}`}return headers}catch(error){throw logger2.error(`Access token check failed: ${error}`),error}};async function getClientCredentialToken(tokensData,logger2,keyId,oauthTokens,config2,agent,isNewStructure=!1){const logAndThrowError=message=>{throw logger2.debug(message),new Error(message)};try{const{clientID,clientSecret,tokenURL}=oauthTokens,currentTime=new Date().getTime();if(!oauthTokens.expiresIn||currentTime>=Number(oauthTokens.expiresIn)){(!clientID||!clientSecret||!tokenURL)&&logAndThrowError("Missing client_id, client_secret OR token_url");const params=new URLSearchParams({grant_type:"client_credentials",client_id:clientID,client_secret:clientSecret}),response=await axios.post(tokenURL,params.toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded"}});console$o.log("Access token refreshed successfully."),logger2.debug("Access token refreshed successfully.");const newAccessToken=response.data.access_token,expiresInMilliseconds=response.data.expires_in*1e3,expirationTimestamp=currentTime+expiresInMilliseconds;let updatedData;if(isNewStructure){const parts=String(config2?.data?.oauth_con_id??"").split("_"),prefixSuffix=parts.length>1?parts[1]:parts[0],oauthKeysPrefix=prefixSuffix?`OAUTH_${prefixSuffix}`:void 0;updatedData={...tokensData||{},auth_data:{...tokensData?.auth_data||{},primary:newAccessToken,expires_in:expirationTimestamp.toString()},auth_settings:{...tokensData?.auth_settings||{},type:"oauth2",tokenURL,clientID,clientSecret,...oauthKeysPrefix?{oauth_keys_prefix:oauthKeysPrefix}:{},service:"oauth2_client_credentials"}}}else updatedData={...tokensData,primary:newAccessToken,expires_in:expirationTimestamp.toString()},updatedData.type||(updatedData.type="oauth2"),updatedData.tokenURL||(updatedData.tokenURL=tokenURL),updatedData.team||(updatedData.team=agent.teamId),updatedData.oauth_info||(updatedData.oauth_info={oauth_keys_prefix:`OAUTH_${config2?.data?.oauth_con_id?.split("_")[1]||config2?.id}`,service:"oauth2_client_credentials",tokenURL,clientID,clientSecret});return await managedVault.user(AccessCandidate.agent(agent.id)).set(keyId,JSON.stringify(updatedData)),newAccessToken}else return console$o.log("Access token value is still valid."),logger2.debug("Access token value is still valid."),oauthTokens.primaryToken}catch(error){logAndThrowError(`Failed to refresh access token: ${error}`)}}var __defProp$14=Object.defineProperty,__defNormalProp$14=(obj,key,value)=>key in obj?__defProp$14(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$14=(obj,key,value)=>__defNormalProp$14(obj,typeof key!="symbol"?key+"":key,value);class APICall extends Component{constructor(){super(),__publicField$14(this,"schema",{name:"APICall",description:"Use this component to make an API call",inputs:{},outputs:{Headers:{description:"The headers of the API call response",default:!0},Response:{description:"The response of the API call",default:!0}}}),__publicField$14(this,"configSchema",Joi.object({method:Joi.string().valid("GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS").required().label("Method"),url:Joi.string().max(8192).required().label("URL"),headers:Joi.any().allow("").label("Headers"),contentType:Joi.string().valid("none","application/json","multipart/form-data","binary","application/x-www-form-urlencoded","text/plain","application/xml").label("Content-Type"),body:Joi.any().allow("").label("Body"),_templateSettings:Joi.object().allow(null).label("Template Settings"),_templateVars:Joi.object().allow(null).label("Template Variables"),proxy:Joi.string().allow("").label("Proxy"),oauthService:Joi.string().allow("").label("OAuth Service"),scope:Joi.string().allow("").label("Scope"),authorizationURL:Joi.string().allow("").label("Authorization URL"),tokenURL:Joi.string().allow("").label("Token URL"),clientID:Joi.string().allow("").label("Client ID"),clientSecret:Joi.string().allow("").label("Client Secret"),oauth2CallbackURL:Joi.string().allow("").label("OAuth2 Callback URL"),callbackURL:Joi.string().allow("").label("Callback URL"),requestTokenURL:Joi.string().allow("").label("Request Token URL"),accessTokenURL:Joi.string().allow("").label("Access Token URL"),userAuthorizationURL:Joi.string().allow("").label("User Authorization URL"),consumerKey:Joi.string().allow("").label("Consumer Key"),consumerSecret:Joi.string().allow("").label("Consumer Secret"),oauth1CallbackURL:Joi.string().allow("").label("OAuth1 Callback URL"),authenticate:Joi.string().allow("").label("Authenticate"),oauth_con_id:Joi.string().allow("").label("OAuth Connection ID")}))}init(){}async process(input,config2,agent){await super.process(input,config2,agent);const logger2=this.createComponentLogger(agent,config2);let publicUrls=[];try{logger2.debug("=== API Call Log ===");const method=config2?.data?.method||"get",reqConfig={};reqConfig.method=method,reqConfig.url=await parseUrl(input,config2,agent),{url:reqConfig.url,publicUrls}=await parseSmythFsUrl(reqConfig.url,agent);const{data,headers}=await parseData(input,config2,agent);let dataForDebug;data&&(reqConfig.data=data,dataForDebug=await formatDataForDebug(data,AccessCandidate.agent(agent.id))),reqConfig.headers=(await parseHeaders(input,config2,agent)).concat({...headers});const proxyConfig=await parseProxy(input,config2,agent);if(proxyConfig)if(proxyConfig instanceof SocksProxyAgent){const isSecureEndpoint=reqConfig.url?.startsWith("https://");reqConfig[isSecureEndpoint?"httpsAgent":"httpAgent"]=proxyConfig}else reqConfig.proxy=proxyConfig;let Response={},Headers={},_error;try{if(logger2.debug("checking oauth config",config2?.data?.oauth_con_id,config2?.data?.oauthService),config2?.data?.oauth_con_id&&config2.data.oauth_con_id!=="None"||config2?.data?.oauthService&&config2.data.oauthService!=="None"){const additionalParams=extractAdditionalParamsForOAuth1(reqConfig),oauthHeaders=await handleOAuthHeaders(agent,config2,reqConfig,logger2,additionalParams);reqConfig.headers=reqConfig.headers.concat({...oauthHeaders})}reqConfig.responseType="arraybuffer",logger2.debug("Making API call",{...reqConfig,data:dataForDebug});const response=await axios.request(reqConfig),parsedRes=await parseArrayBufferResponse(response,agent);logger2.debug("API call Response Headers",response.headers),Response=parsedRes,logger2.debug(`API call Response
114
114
  `,Response),Headers=Object.fromEntries(Object.entries(response.headers))}catch(error){logger2.debug(`Error making API call: ${error.message}`),Headers=error?.response?.headers?Object.fromEntries(Object.entries(error.response.headers)):{},Response=await parseArrayBufferResponse(error.response,agent),_error=error.message}return{Response,Headers,_error,_debug:logger2.output}}catch(error){return{_error:error.message,_debug:logger2.output}}finally{publicUrls.length>0&&await destroyPublicUrls(publicUrls)}}}var __defProp$13=Object.defineProperty,__defNormalProp$13=(obj,key,value)=>key in obj?__defProp$13(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value,__publicField$13=(obj,key,value)=>__defNormalProp$13(obj,key+"",value);class VisionLLM extends Component{constructor(){super(),__publicField$13(this,"configSchema",Joi.object({prompt:Joi.string().required().max(8e6).label("Prompt"),maxTokens:Joi.number().min(1).label("Maximum Tokens"),model:Joi.string().max(200).required(),passthrough:Joi.boolean().optional().label("Passthrough")}))}init(){}async process(input,config2,agent){await super.process(input,config2,agent);const logger2=this.createComponentLogger(agent,config2);try{logger2.debug("=== Vision LLM Log ===");const passThrough=config2.data.passthrough||!1,model=config2.data?.model,llmInference=await LLMInference$1.getInstance(model,AccessCandidate.agent(agent.id));if(!llmInference.connector)return{_error:`The model '${model}' is not available. Please try a different one.`,_debug:logger2.output};const modelId=await agent.modelsProvider.getModelId(model);logger2.debug(` Model : ${modelId||model}`);let prompt=TemplateString(config2.data.prompt).parse(input).result;logger2.debug(` Prompt
115
115
  `,prompt,`
116
116
  `);const files=Array.isArray(input.Images)?input.Images:[input.Images];let response;if(passThrough?response=await new Promise(async(resolve,reject)=>{let _content="";const eventEmitter=await llmInference.multimodalStreamRequestLegacy(prompt,files,config2,agent).catch(error=>{console.error("Error on multimodalStreamRequest: ",error),reject(error)});eventEmitter.on("content",content=>{typeof agent.callback=="function"&&agent.callback({content}),agent.sse.send("llm/passthrough/content",content),_content+=content}),eventEmitter.on("thinking",thinking=>{typeof agent.callback=="function"&&agent.callback({thinking}),agent.sse.send("llm/passthrough/thinking",thinking)}),eventEmitter.on("end",()=>{console.log("end"),resolve(_content)})}):response=await llmInference.prompt({query:prompt,files,params:{...config2,agentId:agent.id}}),!response)return{_error:" LLM Error = Empty Response!",_debug:logger2.output};if(response?.error){const error=response?.error+" "+(response?.details||"");return logger2.error(" LLM Error=",error),{Reply:response?.data,_error:error,_debug:logger2.output}}logger2.debug(` Response