@smythos/sre 1.5.41 → 1.5.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/types/Components/AgentPlugin.class.d.ts +1 -1
- package/dist/types/Components/GPTPlugin.class.d.ts +1 -1
- package/dist/types/Components/MCPClient.class.d.ts +1 -1
- package/dist/types/Components/OpenAPI.class.d.ts +1 -1
- package/dist/types/helpers/Conversation.helper.d.ts +2 -2
- package/package.json +1 -1
- package/src/helpers/Conversation.helper.ts +2 -2
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{encode,encodeChat}from"gpt-tokenizer";import path from"path";import os from"os";import"process";import mime from"mime";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}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{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.
|
|
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{encode,encodeChat}from"gpt-tokenizer";import path from"path";import os from"os";import"process";import mime from"mime";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}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{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.42";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,10 +24,10 @@ 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$z=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$z.info(`Starting ${this.name} connector ...`),this.started=!0}async stop(){console$z.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$y=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$y.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$y.warn(`Connector ${connectorType} not initialized returning DummyConnector`),printStackTrace(console$y,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$x=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 inputTokensObj=encode(typeof firstData.input=="string"?firstData.input:JSON.stringify(firstData.input)||""),outputTokensObj=encode(typeof firstData.output=="string"?firstData.output:JSON.stringify(firstData.output)||""),inputTokens=inputTokensObj.length||void 0,outputTokens=outputTokensObj.length||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$x.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$x.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);const console$w=Logger("RuntimeContext");class RuntimeContext extends EventEmitter$1{constructor(runtime){super(),this.runtime=runtime,__publicField$1E(this,"circularLimitReached",!1),__publicField$1E(this,"step",0),__publicField$1E(this,"sessionResult",!1),__publicField$1E(this,"sessionResults"),__publicField$1E(this,"components",{}),__publicField$1E(this,"checkRuntimeContext",null),__publicField$1E(this,"ctxFile",""),__publicField$1E(this,"_runtimeFileReady"),__publicField$1E(this,"_cacheConnector"),__publicField$1E(this,"_readyPromise");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$w.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,2),null,null,6*60*60)}this.deserialize(ctxData),this._runtimeFileReady=!0,this.emit("ready")})}async ready(){return this._runtimeFileReady?!0:this._readyPromise}async sync(){if(this.ctxFile)if(this.emit("syncing"),this.runtime.sessionClosed)await this._cacheConnector.requester(AccessCandidate.agent(this.runtime.agent.id)).exists(this.ctxFile)&&(console$w.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));else{const data=this.serialize();if(data){const serializedData=JSON.stringify(data,null,2);console$w.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)}}}incStep(){this.step++,this.sync()}updateComponent(componentId,data){const ctxData=this;if(!ctxData)return;const component=ctxData.components[componentId];component||(console$w.debug(">>>>>>> updateComponent Component debug data not found",componentId,component,AccessCandidate.agent(this.runtime.agent.id)),console$w.debug(">>> ctxFile",this.ctxFile,AccessCandidate.agent(this.runtime.agent.id)),console$w.debug(">>> ctxData",ctxData,AccessCandidate.agent(this.runtime.agent.id))),component.ctx={...component.ctx,...data,step:this.step},this.sync()}resetComponent(componentId){const ctxData=this,component=ctxData.components[componentId];component||(console$w.debug(">>>>>>> resetComponent Component debug data not found",componentId,component,AccessCandidate.agent(this.runtime.agent.id)),console$w.debug(">>> ctxFile",this.ctxFile,AccessCandidate.agent(this.runtime.agent.id)),console$w.debug(">>> ctxData",ctxData,AccessCandidate.agent(this.runtime.agent.id))),component.ctx.runtimeData={},component.ctx.active=!1,this.sync()}getComponentData(componentId){const ctxData=this;if(!ctxData)return null;const component=ctxData.components[componentId];return component||(console$w.debug(">>>>>>> getComponentData Component debug data not found",componentId,component,AccessCandidate.agent(this.runtime.agent.id)),console$w.debug(">>> ctxFile",this.ctxFile,AccessCandidate.agent(this.runtime.agent.id)),console$w.debug(">>> ctxData",ctxData,AccessCandidate.agent(this.runtime.agent.id))),component.ctx}}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);class LLMCache{constructor(candidate,cacheId,ttl=1*60*60){__publicField$1D(this,"_cacheConnector"),__publicField$1D(this,"_cacheId"),__publicField$1D(this,"_ttl"),__publicField$1D(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$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$v=Logger("AgentRuntime"),AgentRuntimeUnavailable=new Proxy({},{get:function(target,prop,receiver){return typeof target[prop]=="function"?target[prop]:function(){console$v.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$v.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.sync()}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$v.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$u=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$u.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$u.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$u.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$u.debug(output,AccessCandidate.agent(this.id))}catch(error){console$u.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$t=Logger("SecureConnector");class SecureConnector extends Connector{async start(){console$t.info(`Starting ${this.name} connector ...`)}async stop(){console$t.info(`Stopping ${this.name} connector ...`)}async hasAccess(acRequest){const aclHelper=await this.getResourceACL(acRequest.resourceId,acRequest.candidate).catch(error=>(console$t.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$t.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.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$s=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$s.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$s.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$s.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$s.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$s.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$s.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$s.warn("Max input context is 0, returning empty context window, This usually indicates a wrong model configuration");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$s.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$r=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$r.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$r.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.Content,content2=>{this.stop||(this._context?.messages?.[this._context?.messages?.length-1],_content+=content2,this.emit(TLLMEvent.Content,content2))});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
|
-
`)),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
|
|
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$u=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$u.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$u.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$u.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$u.debug(output,AccessCandidate.agent(this.id))}catch(error){console$u.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$t=Logger("SecureConnector");class SecureConnector extends Connector{async start(){console$t.info(`Starting ${this.name} connector ...`)}async stop(){console$t.info(`Stopping ${this.name} connector ...`)}async hasAccess(acRequest){const aclHelper=await this.getResourceACL(acRequest.resourceId,acRequest.candidate).catch(error=>(console$t.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$t.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.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$s=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$s.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$s.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$s.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$s.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$s.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$s.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$s.warn("Max input context is 0, returning empty context window, This usually indicates a wrong model configuration");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$s.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$r=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$r.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$r.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.Content,content=>{this.stop||(this._context?.messages?.[this._context?.messages?.length-1],_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
|
+
`)),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
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?(llmMessage.content+=`
|
|
30
|
-
`+passThroughContent,this._context.addToolMessage(llmMessage,processedToolsData,message_id)):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$r.error("Error in toolsPromise: ",error),this.emit(TLLMEvent.Error,error),""));_content+=toolsContent
|
|
30
|
+
`+passThroughContent,this._context.addToolMessage(llmMessage,processedToolsData,message_id)):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$r.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$r.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$r.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$r.log("RUNNING AGENT REMOTELY");let eventSource;if(reqConfig.headers["X-DEBUG"]&&reqConfig.headers["X-AGENT-ID"]||reqConfig.headers["X-MONITOR-ID"]){console$r.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$r.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&¶ms.agentCallback({content:event.data.replace(/\\n/g,`
|
|
31
31
|
`)})}),eventSource2.addEventListener("llm/passthrough/thinking",event=>{params.agentCallback&¶ms.agentCallback({thinking:event.data.replace(/\\n/g,`
|
|
32
32
|
`)})}),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$r.log("eventSource closed")),{data:response.data,error:null}}}catch(error){return console$r.warn("Failed to call Tool: ",baseUrl,endpoint),console$r.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}
|
|
33
33
|
|