@smythos/sre 1.5.0 → 1.5.2

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.
Files changed (189) hide show
  1. package/CHANGELOG +62 -0
  2. package/LICENSE +18 -0
  3. package/package.json +127 -115
  4. package/src/Components/APICall/APICall.class.ts +155 -0
  5. package/src/Components/APICall/AccessTokenManager.ts +130 -0
  6. package/src/Components/APICall/ArrayBufferResponse.helper.ts +58 -0
  7. package/src/Components/APICall/OAuth.helper.ts +294 -0
  8. package/src/Components/APICall/mimeTypeCategories.ts +46 -0
  9. package/src/Components/APICall/parseData.ts +167 -0
  10. package/src/Components/APICall/parseHeaders.ts +41 -0
  11. package/src/Components/APICall/parseProxy.ts +68 -0
  12. package/src/Components/APICall/parseUrl.ts +91 -0
  13. package/src/Components/APIEndpoint.class.ts +234 -0
  14. package/src/Components/APIOutput.class.ts +58 -0
  15. package/src/Components/AgentPlugin.class.ts +102 -0
  16. package/src/Components/Async.class.ts +155 -0
  17. package/src/Components/Await.class.ts +90 -0
  18. package/src/Components/Classifier.class.ts +158 -0
  19. package/src/Components/Component.class.ts +94 -0
  20. package/src/Components/ComponentHost.class.ts +38 -0
  21. package/src/Components/DataSourceCleaner.class.ts +92 -0
  22. package/src/Components/DataSourceIndexer.class.ts +181 -0
  23. package/src/Components/DataSourceLookup.class.ts +141 -0
  24. package/src/Components/FEncDec.class.ts +29 -0
  25. package/src/Components/FHash.class.ts +33 -0
  26. package/src/Components/FSign.class.ts +80 -0
  27. package/src/Components/FSleep.class.ts +25 -0
  28. package/src/Components/FTimestamp.class.ts +25 -0
  29. package/src/Components/FileStore.class.ts +75 -0
  30. package/src/Components/ForEach.class.ts +97 -0
  31. package/src/Components/GPTPlugin.class.ts +70 -0
  32. package/src/Components/GenAILLM.class.ts +395 -0
  33. package/src/Components/HuggingFace.class.ts +314 -0
  34. package/src/Components/Image/imageSettings.config.ts +70 -0
  35. package/src/Components/ImageGenerator.class.ts +407 -0
  36. package/src/Components/JSONFilter.class.ts +54 -0
  37. package/src/Components/LLMAssistant.class.ts +213 -0
  38. package/src/Components/LogicAND.class.ts +28 -0
  39. package/src/Components/LogicAtLeast.class.ts +85 -0
  40. package/src/Components/LogicAtMost.class.ts +86 -0
  41. package/src/Components/LogicOR.class.ts +29 -0
  42. package/src/Components/LogicXOR.class.ts +34 -0
  43. package/src/Components/MCPClient.class.ts +112 -0
  44. package/src/Components/PromptGenerator.class.ts +122 -0
  45. package/src/Components/ScrapflyWebScrape.class.ts +159 -0
  46. package/src/Components/TavilyWebSearch.class.ts +98 -0
  47. package/src/Components/index.ts +77 -0
  48. package/src/Core/AgentProcess.helper.ts +240 -0
  49. package/src/Core/Connector.class.ts +123 -0
  50. package/src/Core/ConnectorsService.ts +192 -0
  51. package/src/Core/DummyConnector.ts +49 -0
  52. package/src/Core/HookService.ts +105 -0
  53. package/src/Core/SmythRuntime.class.ts +292 -0
  54. package/src/Core/SystemEvents.ts +15 -0
  55. package/src/Core/boot.ts +55 -0
  56. package/src/config.ts +15 -0
  57. package/src/constants.ts +125 -0
  58. package/src/data/hugging-face.params.json +580 -0
  59. package/src/helpers/BinaryInput.helper.ts +324 -0
  60. package/src/helpers/Conversation.helper.ts +1094 -0
  61. package/src/helpers/JsonContent.helper.ts +97 -0
  62. package/src/helpers/LocalCache.helper.ts +97 -0
  63. package/src/helpers/Log.helper.ts +234 -0
  64. package/src/helpers/OpenApiParser.helper.ts +150 -0
  65. package/src/helpers/S3Cache.helper.ts +129 -0
  66. package/src/helpers/SmythURI.helper.ts +5 -0
  67. package/src/helpers/TemplateString.helper.ts +243 -0
  68. package/src/helpers/TypeChecker.helper.ts +329 -0
  69. package/src/index.ts +179 -0
  70. package/src/index.ts.bak +179 -0
  71. package/src/subsystems/AgentManager/Agent.class.ts +1108 -0
  72. package/src/subsystems/AgentManager/Agent.helper.ts +3 -0
  73. package/src/subsystems/AgentManager/AgentData.service/AgentDataConnector.ts +230 -0
  74. package/src/subsystems/AgentManager/AgentData.service/connectors/CLIAgentDataConnector.class.ts +66 -0
  75. package/src/subsystems/AgentManager/AgentData.service/connectors/LocalAgentDataConnector.class.ts +142 -0
  76. package/src/subsystems/AgentManager/AgentData.service/connectors/NullAgentData.class.ts +39 -0
  77. package/src/subsystems/AgentManager/AgentData.service/index.ts +18 -0
  78. package/src/subsystems/AgentManager/AgentLogger.class.ts +297 -0
  79. package/src/subsystems/AgentManager/AgentRequest.class.ts +51 -0
  80. package/src/subsystems/AgentManager/AgentRuntime.class.ts +559 -0
  81. package/src/subsystems/AgentManager/AgentSSE.class.ts +101 -0
  82. package/src/subsystems/AgentManager/AgentSettings.class.ts +52 -0
  83. package/src/subsystems/AgentManager/Component.service/ComponentConnector.ts +32 -0
  84. package/src/subsystems/AgentManager/Component.service/connectors/LocalComponentConnector.class.ts +59 -0
  85. package/src/subsystems/AgentManager/Component.service/index.ts +11 -0
  86. package/src/subsystems/AgentManager/EmbodimentSettings.class.ts +47 -0
  87. package/src/subsystems/AgentManager/ForkedAgent.class.ts +153 -0
  88. package/src/subsystems/AgentManager/OSResourceMonitor.ts +77 -0
  89. package/src/subsystems/ComputeManager/Code.service/CodeConnector.ts +99 -0
  90. package/src/subsystems/ComputeManager/Code.service/connectors/AWSLambdaCode.class.ts +63 -0
  91. package/src/subsystems/ComputeManager/Code.service/index.ts +11 -0
  92. package/src/subsystems/IO/CLI.service/CLIConnector.ts +47 -0
  93. package/src/subsystems/IO/CLI.service/index.ts +9 -0
  94. package/src/subsystems/IO/Log.service/LogConnector.ts +32 -0
  95. package/src/subsystems/IO/Log.service/connectors/ConsoleLog.class.ts +28 -0
  96. package/src/subsystems/IO/Log.service/index.ts +13 -0
  97. package/src/subsystems/IO/NKV.service/NKVConnector.ts +41 -0
  98. package/src/subsystems/IO/NKV.service/connectors/NKVRAM.class.ts +204 -0
  99. package/src/subsystems/IO/NKV.service/connectors/NKVRedis.class.ts +182 -0
  100. package/src/subsystems/IO/NKV.service/index.ts +12 -0
  101. package/src/subsystems/IO/Router.service/RouterConnector.ts +21 -0
  102. package/src/subsystems/IO/Router.service/connectors/ExpressRouter.class.ts +48 -0
  103. package/src/subsystems/IO/Router.service/connectors/NullRouter.class.ts +40 -0
  104. package/src/subsystems/IO/Router.service/index.ts +11 -0
  105. package/src/subsystems/IO/Storage.service/SmythFS.class.ts +472 -0
  106. package/src/subsystems/IO/Storage.service/StorageConnector.ts +66 -0
  107. package/src/subsystems/IO/Storage.service/connectors/LocalStorage.class.ts +305 -0
  108. package/src/subsystems/IO/Storage.service/connectors/S3Storage.class.ts +418 -0
  109. package/src/subsystems/IO/Storage.service/index.ts +13 -0
  110. package/src/subsystems/IO/VectorDB.service/VectorDBConnector.ts +108 -0
  111. package/src/subsystems/IO/VectorDB.service/connectors/MilvusVectorDB.class.ts +450 -0
  112. package/src/subsystems/IO/VectorDB.service/connectors/PineconeVectorDB.class.ts +373 -0
  113. package/src/subsystems/IO/VectorDB.service/connectors/RAMVecrtorDB.class.ts +420 -0
  114. package/src/subsystems/IO/VectorDB.service/embed/BaseEmbedding.ts +106 -0
  115. package/src/subsystems/IO/VectorDB.service/embed/OpenAIEmbedding.ts +109 -0
  116. package/src/subsystems/IO/VectorDB.service/embed/index.ts +21 -0
  117. package/src/subsystems/IO/VectorDB.service/index.ts +14 -0
  118. package/src/subsystems/LLMManager/LLM.helper.ts +221 -0
  119. package/src/subsystems/LLMManager/LLM.inference.ts +335 -0
  120. package/src/subsystems/LLMManager/LLM.service/LLMConnector.ts +374 -0
  121. package/src/subsystems/LLMManager/LLM.service/LLMCredentials.helper.ts +145 -0
  122. package/src/subsystems/LLMManager/LLM.service/connectors/Anthropic.class.ts +632 -0
  123. package/src/subsystems/LLMManager/LLM.service/connectors/Bedrock.class.ts +405 -0
  124. package/src/subsystems/LLMManager/LLM.service/connectors/Echo.class.ts +81 -0
  125. package/src/subsystems/LLMManager/LLM.service/connectors/GoogleAI.class.ts +689 -0
  126. package/src/subsystems/LLMManager/LLM.service/connectors/Groq.class.ts +257 -0
  127. package/src/subsystems/LLMManager/LLM.service/connectors/OpenAI.class.ts +848 -0
  128. package/src/subsystems/LLMManager/LLM.service/connectors/Perplexity.class.ts +255 -0
  129. package/src/subsystems/LLMManager/LLM.service/connectors/VertexAI.class.ts +193 -0
  130. package/src/subsystems/LLMManager/LLM.service/index.ts +43 -0
  131. package/src/subsystems/LLMManager/ModelsProvider.service/ModelsProviderConnector.ts +281 -0
  132. package/src/subsystems/LLMManager/ModelsProvider.service/connectors/SmythModelsProvider.class.ts +229 -0
  133. package/src/subsystems/LLMManager/ModelsProvider.service/index.ts +11 -0
  134. package/src/subsystems/LLMManager/custom-models.ts +854 -0
  135. package/src/subsystems/LLMManager/models.ts +2539 -0
  136. package/src/subsystems/LLMManager/paramMappings.ts +69 -0
  137. package/src/subsystems/MemoryManager/Cache.service/CacheConnector.ts +86 -0
  138. package/src/subsystems/MemoryManager/Cache.service/connectors/LocalStorageCache.class.ts +297 -0
  139. package/src/subsystems/MemoryManager/Cache.service/connectors/RAMCache.class.ts +201 -0
  140. package/src/subsystems/MemoryManager/Cache.service/connectors/RedisCache.class.ts +252 -0
  141. package/src/subsystems/MemoryManager/Cache.service/connectors/S3Cache.class.ts +373 -0
  142. package/src/subsystems/MemoryManager/Cache.service/index.ts +15 -0
  143. package/src/subsystems/MemoryManager/LLMCache.ts +72 -0
  144. package/src/subsystems/MemoryManager/LLMContext.ts +125 -0
  145. package/src/subsystems/MemoryManager/RuntimeContext.ts +249 -0
  146. package/src/subsystems/Security/AccessControl/ACL.class.ts +208 -0
  147. package/src/subsystems/Security/AccessControl/AccessCandidate.class.ts +76 -0
  148. package/src/subsystems/Security/AccessControl/AccessRequest.class.ts +52 -0
  149. package/src/subsystems/Security/Account.service/AccountConnector.ts +41 -0
  150. package/src/subsystems/Security/Account.service/connectors/AWSAccount.class.ts +76 -0
  151. package/src/subsystems/Security/Account.service/connectors/DummyAccount.class.ts +130 -0
  152. package/src/subsystems/Security/Account.service/connectors/JSONFileAccount.class.ts +159 -0
  153. package/src/subsystems/Security/Account.service/index.ts +14 -0
  154. package/src/subsystems/Security/Credentials.helper.ts +62 -0
  155. package/src/subsystems/Security/ManagedVault.service/ManagedVaultConnector.ts +34 -0
  156. package/src/subsystems/Security/ManagedVault.service/connectors/NullManagedVault.class.ts +57 -0
  157. package/src/subsystems/Security/ManagedVault.service/connectors/SecretManagerManagedVault.ts +154 -0
  158. package/src/subsystems/Security/ManagedVault.service/index.ts +12 -0
  159. package/src/subsystems/Security/SecureConnector.class.ts +110 -0
  160. package/src/subsystems/Security/Vault.service/Vault.helper.ts +30 -0
  161. package/src/subsystems/Security/Vault.service/VaultConnector.ts +26 -0
  162. package/src/subsystems/Security/Vault.service/connectors/HashicorpVault.class.ts +46 -0
  163. package/src/subsystems/Security/Vault.service/connectors/JSONFileVault.class.ts +166 -0
  164. package/src/subsystems/Security/Vault.service/connectors/NullVault.class.ts +54 -0
  165. package/src/subsystems/Security/Vault.service/connectors/SecretsManager.class.ts +140 -0
  166. package/src/subsystems/Security/Vault.service/index.ts +12 -0
  167. package/src/types/ACL.types.ts +104 -0
  168. package/src/types/AWS.types.ts +9 -0
  169. package/src/types/Agent.types.ts +61 -0
  170. package/src/types/AgentLogger.types.ts +17 -0
  171. package/src/types/Cache.types.ts +1 -0
  172. package/src/types/Common.types.ts +3 -0
  173. package/src/types/LLM.types.ts +419 -0
  174. package/src/types/Redis.types.ts +8 -0
  175. package/src/types/SRE.types.ts +64 -0
  176. package/src/types/Security.types.ts +18 -0
  177. package/src/types/Storage.types.ts +5 -0
  178. package/src/types/VectorDB.types.ts +78 -0
  179. package/src/utils/base64.utils.ts +275 -0
  180. package/src/utils/cli.utils.ts +68 -0
  181. package/src/utils/data.utils.ts +263 -0
  182. package/src/utils/date-time.utils.ts +22 -0
  183. package/src/utils/general.utils.ts +238 -0
  184. package/src/utils/index.ts +12 -0
  185. package/src/utils/numbers.utils.ts +13 -0
  186. package/src/utils/oauth.utils.ts +35 -0
  187. package/src/utils/string.utils.ts +414 -0
  188. package/src/utils/url.utils.ts +19 -0
  189. package/src/utils/validation.utils.ts +74 -0
@@ -0,0 +1,141 @@
1
+ import Joi from 'joi';
2
+ import { validateInteger } from '../utils';
3
+ import { jsonrepair } from 'jsonrepair';
4
+ import { TemplateString } from '@sre/helpers/TemplateString.helper';
5
+ import { JSONContent } from '@sre/helpers/JsonContent.helper';
6
+ import { ConnectorService } from '@sre/Core/ConnectorsService';
7
+ import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
8
+ import { IAgent as Agent } from '@sre/types/Agent.types';
9
+ import { Component } from './Component.class';
10
+
11
+ // Note: LLMHelper renamed to LLMInference
12
+ class LLMInference {
13
+ static async getInstance(model: string) {
14
+ throw new Error('Method not implemented.');
15
+ }
16
+ }
17
+
18
+ export class DataSourceLookup extends Component {
19
+ protected configSchema = Joi.object({
20
+ topK: Joi.string()
21
+ .custom(validateInteger({ min: 0 }), 'custom range validation')
22
+ .label('Result Count'),
23
+ model: Joi.string().valid('gpt-4o-mini', 'gpt-4', 'gpt-3.5-turbo', 'gpt-4', 'gpt-3.5-turbo-16k').optional(),
24
+ prompt: Joi.string().max(30000).allow('').label('Prompt').optional(),
25
+ postprocess: Joi.boolean().strict().optional(),
26
+ includeMetadata: Joi.boolean().strict().optional(),
27
+ namespace: Joi.string().allow('').max(80).messages({
28
+ // Need to reserve 30 characters for the prefixed unique id
29
+ 'string.max': `The length of the 'namespace' name must be 50 characters or fewer.`,
30
+ }),
31
+ });
32
+ constructor() {
33
+ super();
34
+ }
35
+ init() {}
36
+ async process(input, config, agent: Agent) {
37
+ await super.process(input, config, agent);
38
+ const componentId = config.id;
39
+ const component = agent.components[componentId];
40
+ const teamId = agent.teamId;
41
+ let debugOutput = agent.agentRuntime?.debug ? '== Data Source Lookup Log ==\n' : null;
42
+
43
+ const outputs = {};
44
+ for (let con of config.outputs) {
45
+ if (con.default) continue;
46
+ outputs[con.name] = '';
47
+ }
48
+
49
+ const namespace = config.data.namespace.split('_').slice(1).join('_') || config.data.namespace;
50
+ const model = config.data?.model || 'gpt-4o-mini';
51
+ const prompt = config.data?.prompt?.trim?.() || '';
52
+ const postprocess = config.data?.postprocess || false;
53
+ const includeMetadata = config.data?.includeMetadata || false;
54
+
55
+ const _input = typeof input.Query === 'string' ? input.Query : JSON.stringify(input.Query);
56
+
57
+ const topK = Math.max(config.data?.topK || 50, 50);
58
+
59
+ let vectorDbConnector = ConnectorService.getVectorDBConnector();
60
+ let existingNs = await vectorDbConnector.requester(AccessCandidate.team(teamId)).namespaceExists(namespace);
61
+
62
+ if (!existingNs) {
63
+ throw new Error(`Namespace ${namespace} does not exist`);
64
+ }
65
+
66
+ let results: string[] | { content: string; metadata: any }[];
67
+ let _error;
68
+ try {
69
+ const response = await vectorDbConnector
70
+ .requester(AccessCandidate.team(teamId))
71
+ .search(namespace, _input, { topK, includeMetadata: true });
72
+ results = response.slice(0, config.data.topK).map((result) => ({
73
+ content: result.metadata?.text,
74
+ metadata: result.metadata,
75
+ }));
76
+
77
+ if (includeMetadata) {
78
+ // only show user-level metadata
79
+ results = results.map((result) => ({
80
+ content: result.content,
81
+ //* legacy user-specific metadata key [result.metadata?.metadata]),
82
+ metadata: this.parseMetadata(result.metadata || result.metadata?.metadata),
83
+ }));
84
+ } else {
85
+ results = results.map((result) => result.content);
86
+ }
87
+ debugOutput += `[Results] \nLoaded ${results.length} results from namespace: ${namespace}\n\n`;
88
+ } catch (error) {
89
+ _error = error.toString();
90
+ }
91
+
92
+ //is there a post processing LLM?
93
+
94
+ //TODO : better handling of context window exceeding max length
95
+ if (postprocess && prompt) {
96
+ const promises: any = [];
97
+ for (let result of results) {
98
+ const _prompt = TemplateString(prompt.replace(/{{result}}/g, JSON.stringify(result))).parse(input).result;
99
+ const llmInference = await LLMInference.getInstance(model);
100
+ // const req = llmInference.prompt({ query: _prompt, params: { ...config, agentId: agent.id } }).catch((error) => ({ error: error }));
101
+ // promises.push(req);
102
+ }
103
+ results = await Promise.all(promises);
104
+ for (let i = 0; i < results.length; i++) {
105
+ if (typeof results[i] === 'string') {
106
+ // results[i] = parseJson(results[i]);
107
+ results[i] = JSONContent(results[i] as string).tryParse();
108
+ }
109
+ }
110
+ }
111
+
112
+ const totalLength = JSON.stringify(results).length;
113
+ debugOutput += `[Total Length] \n${totalLength}\n\n`;
114
+ return {
115
+ Results: results,
116
+ _error,
117
+ _debug: debugOutput,
118
+ //_debug: `Query: ${_input}. \nTotal Length = ${totalLength} \nResults: ${JSON.stringify(results)}`,
119
+ };
120
+ }
121
+
122
+ // private async checkIfTeamOwnsNamespace(teamId: string, namespaceId: string, token: string) {
123
+ // try {
124
+ // const res = await SmythAPIHelper.fromAuth({ token }).mwSysAPI.get(`/vectors/namespaces/${namespaceId}`);
125
+ // if (res.data?.namespace?.teamId !== teamId) {
126
+ // throw new Error(`Namespace does not exist`);
127
+ // }
128
+ // return true;
129
+ // } catch (err) {
130
+ // throw new Error(`Namespace does not exist`);
131
+ // }
132
+ // }
133
+
134
+ private parseMetadata(metadata: any) {
135
+ try {
136
+ return JSON.parse(jsonrepair(metadata));
137
+ } catch (err) {
138
+ return metadata;
139
+ }
140
+ }
141
+ }
@@ -0,0 +1,29 @@
1
+ import { Component } from './Component.class';
2
+ import { IAgent as Agent } from '@sre/types/Agent.types';
3
+
4
+ export class FEncDec extends Component {
5
+ constructor() {
6
+ super();
7
+ }
8
+ init() {}
9
+ async process(input, config, agent: Agent) {
10
+ await super.process(input, config, agent);
11
+ const logger = this.createComponentLogger(agent, config);
12
+ try {
13
+ const _error = undefined;
14
+
15
+ const data = input.Data;
16
+ const action = config.data.action || 'Encode';
17
+ const encoding = config.data.encoding;
18
+ logger.debug(`${encoding} ${action} data`);
19
+
20
+ const Output = action == 'Encode' ? Buffer.from(data).toString(encoding) : Buffer.from(data, encoding).toString('utf8');
21
+
22
+ return { Output, _error, _debug: logger.output };
23
+ } catch (err: any) {
24
+ const _error = err?.response?.data || err?.message || err.toString();
25
+ logger.error(` Error processing data \n${_error}\n`);
26
+ return { hash: undefined, _error, _debug: logger.output };
27
+ }
28
+ }
29
+ }
@@ -0,0 +1,33 @@
1
+ import { Component } from './Component.class';
2
+ import { IAgent as Agent } from '@sre/types/Agent.types';
3
+ import crypto from 'crypto';
4
+
5
+ export class FHash extends Component {
6
+ constructor() {
7
+ super();
8
+ }
9
+ init() {}
10
+ async process(input, config, agent: Agent) {
11
+ await super.process(input, config, agent);
12
+ const logger = this.createComponentLogger(agent, config);
13
+ try {
14
+ const _error = undefined;
15
+
16
+ const data = input.Data;
17
+ const algorithm = config.data.algorithm;
18
+ const encoding = config.data.encoding;
19
+ logger.debug(` Generating hash using ${algorithm} algorithm and ${encoding} encoding`);
20
+
21
+ const hashAlgo = crypto.createHash(algorithm);
22
+ hashAlgo.update(data);
23
+
24
+ const Hash = hashAlgo.digest(encoding);
25
+ logger.debug(` Generated hash: ${Hash}`);
26
+ return { Hash, _error, _debug: logger.output };
27
+ } catch (err: any) {
28
+ const _error = err?.response?.data || err?.message || err.toString();
29
+ logger.error(` Error generating hash \n${_error}\n`);
30
+ return { hash: undefined, _error, _debug: logger.output };
31
+ }
32
+ }
33
+ }
@@ -0,0 +1,80 @@
1
+ import { Component } from './Component.class';
2
+ import { IAgent as Agent } from '@sre/types/Agent.types';
3
+ import { TemplateString } from '@sre/helpers/TemplateString.helper';
4
+ import crypto from 'crypto';
5
+ import querystring from 'querystring';
6
+
7
+ export class FSign extends Component {
8
+ constructor() {
9
+ super();
10
+ }
11
+ init() {}
12
+ async process(input, config, agent: Agent) {
13
+ await super.process(input, config, agent);
14
+ const logger = this.createComponentLogger(agent, config);
15
+ try {
16
+ const _error = undefined;
17
+ const teamId = agent ? agent.teamId : null;
18
+
19
+ let data = input.Data;
20
+ //if (typeof data === 'object') data = JSON.stringify(data);
21
+ let signingKey = input.Key || config.data.key;
22
+ // signingKey = parseTemplate(signingKey, input, { processUnmatched: false });
23
+ // signingKey = await parseKey(signingKey, teamId);
24
+ signingKey = await TemplateString(signingKey).parse(input).parseTeamKeysAsync(teamId).asyncResult;
25
+
26
+ const signMethod = config.data.signMethod || 'HMAC';
27
+ const dataTransform = config.data.dataTransform || 'None';
28
+ const hashType = config.data.hashType || 'md5';
29
+ const RSA_padding = config.data.RSA_padding;
30
+ const RSA_saltLength = config.data.RSA_saltLength;
31
+ const encoding = config.data.encoding || 'hex';
32
+
33
+ if (typeof data != 'string') {
34
+ switch (dataTransform) {
35
+ case 'Stringify':
36
+ data = JSON.stringify(data);
37
+ break;
38
+ case 'Querystring':
39
+ data = querystring.stringify(data);
40
+ break;
41
+ }
42
+ }
43
+ logger.debug(' Data to sign = ', data);
44
+ logger.debug(` Signing data using ${signMethod} algorithm and ${encoding} encoding`);
45
+ const Signature = this.signData(data, signingKey, signMethod, encoding, { hashType, RSA_padding, RSA_saltLength });
46
+
47
+ logger.debug(` Signature generated: ${Signature}`);
48
+ return { Signature, _error, _debug: logger.output };
49
+ } catch (err: any) {
50
+ const _error = err?.response?.data || err?.message || err.toString();
51
+ logger.error(` Error generating hash \n${_error}\n`);
52
+ return { hash: undefined, _error, _debug: logger.output };
53
+ }
54
+ }
55
+
56
+ private signData(data, key, signMethod, encoding = 'hex', options: any = {}) {
57
+ // Determine if the algorithm is for HMAC or RSA/DSA/ECDSA
58
+ switch (signMethod) {
59
+ case 'RSA':
60
+ const algo = `${signMethod}-${options.hashType || 'md5'}`.toUpperCase();
61
+ const sign = crypto.createSign(algo);
62
+ sign.update(data);
63
+
64
+ const sign_options = {
65
+ key,
66
+ padding: options.RSA_padding ? crypto.constants[options.RSA_padding] : undefined,
67
+ saltLength: options.RSA_saltLength ? crypto.constants[options.RSA_saltLength] : undefined,
68
+ };
69
+ // For RSA/DSA/ECDSA, options may include padding and saltLength
70
+ return sign.sign(sign_options, encoding.toLowerCase() as crypto.BinaryToTextEncoding);
71
+
72
+ case 'HMAC':
73
+ const hmac = crypto.createHmac(options.hashType, key);
74
+ hmac.update(data);
75
+ return hmac.digest(encoding as crypto.BinaryToTextEncoding);
76
+ }
77
+
78
+ return null;
79
+ }
80
+ }
@@ -0,0 +1,25 @@
1
+ import { Component } from './Component.class';
2
+ import { IAgent as Agent } from '@sre/types/Agent.types';
3
+
4
+ export class FSleep extends Component {
5
+ constructor() {
6
+ super();
7
+ }
8
+ init() {}
9
+ async process(input, config, agent: Agent) {
10
+ await super.process(input, config, agent);
11
+ const logger = this.createComponentLogger(agent, config);
12
+ try {
13
+ const _error = undefined;
14
+ const delay = parseInt(config.data.delay || 1);
15
+ const Output = input.Input;
16
+ logger.debug(`Sleeping for ${delay} seconds`);
17
+ await new Promise((resolve) => setTimeout(resolve, delay * 1000));
18
+ return { Output, _error, _debug: logger.output, _debug_time: logger.elapsedTime };
19
+ } catch (err: any) {
20
+ const _error = err?.response?.data || err?.message || err.toString();
21
+ logger.error(` Error processing data \n${_error}\n`);
22
+ return { hash: undefined, _error, _debug: logger.output, _debug_time: logger.elapsedTime };
23
+ }
24
+ }
25
+ }
@@ -0,0 +1,25 @@
1
+ import { Component } from './Component.class';
2
+ import { IAgent as Agent } from '@sre/types/Agent.types';
3
+
4
+ export class FTimestamp extends Component {
5
+ constructor() {
6
+ super();
7
+ }
8
+ init() {}
9
+ async process(input, config, agent: Agent) {
10
+ await super.process(input, config, agent);
11
+ const logger = this.createComponentLogger(agent, config);
12
+ try {
13
+ const _error = undefined;
14
+ const format = config.data.format; //TODO set timestamp format
15
+ const Timestamp = Date.now();
16
+ logger.debug(`Timestamp : ${Timestamp}`);
17
+
18
+ return { Timestamp, _error, _debug: logger.output, _debug_time: logger.elapsedTime };
19
+ } catch (err: any) {
20
+ const _error = err?.response?.data || err?.message || err.toString();
21
+ logger.error(` Error processing data \n${_error}\n`);
22
+ return { hash: undefined, _error, _debug: logger.output, _debug_time: logger.elapsedTime };
23
+ }
24
+ }
25
+ }
@@ -0,0 +1,75 @@
1
+ import { IAgent as Agent } from '@sre/types/Agent.types';
2
+ import { Component } from './Component.class';
3
+ import Joi from 'joi';
4
+ import _config from '@sre/config';
5
+ import { S3Storage } from '@sre/IO/Storage.service/connectors/S3Storage.class';
6
+ import { ConnectorService } from '@sre/Core/ConnectorsService';
7
+ import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
8
+ import { BinaryInput } from '@sre/helpers/BinaryInput.helper';
9
+ import { TemplateString } from '@sre/helpers/TemplateString.helper';
10
+ import { SmythFS } from '@sre/IO/Storage.service/SmythFS.class';
11
+
12
+ export class FileStore extends Component {
13
+ protected configSchema = Joi.object({
14
+ name: Joi.string().max(1000).allow('').label('Name'),
15
+ ttl: Joi.number().integer().label('TTL'),
16
+ });
17
+ constructor() {
18
+ super();
19
+ }
20
+ init() {}
21
+ async process(input, config, agent: Agent) {
22
+ await super.process(input, config, agent);
23
+
24
+ const logger = this.createComponentLogger(agent, config);
25
+ try {
26
+ logger.debug(`=== File Store Log ===`);
27
+ let Output: any = {};
28
+ let _error = undefined;
29
+ let data = input.Data;
30
+ const accessCandidate = AccessCandidate.agent(agent.id);
31
+ const binaryData = await BinaryInput.from(data, null, null, accessCandidate);
32
+ const fileData = await binaryData.getJsonData(accessCandidate);
33
+ const buffer = await binaryData.getBuffer();
34
+ const customFileName = TemplateString(config.data.name).parse(input).result;
35
+ const metadata = {
36
+ ContentType: fileData.mimetype,
37
+ };
38
+ const ttl = config.data.ttl || 86400;
39
+ const extension = fileData.url?.split('.').pop();
40
+ const s3StorageConnector = ConnectorService.getStorageConnector('S3') as S3Storage;
41
+ const fileName = this.getFileName(customFileName, extension);
42
+ try {
43
+ const s3Key = `teams/${agent.teamId}/components_data/${fileName}`;
44
+
45
+ await s3StorageConnector.requester(AccessCandidate.agent(agent.teamId)).write(s3Key, buffer, null, metadata);
46
+ await s3StorageConnector.requester(AccessCandidate.agent(agent.teamId)).expire(s3Key, +ttl);
47
+ const smythFSUrl = `smythfs://${agent.teamId}.team/components_data/${fileName}`;
48
+ const url = await SmythFS.Instance.genResourceUrl(smythFSUrl, AccessCandidate.agent(agent.teamId));
49
+ Output = {
50
+ Url: url,
51
+ };
52
+ } catch (error: any) {
53
+ logger.error(`Error saving file \n${error}\n`);
54
+ _error = error?.response?.data || error?.message || error.toString();
55
+ Output = undefined; //prevents running next component if the code execution failed
56
+ }
57
+
58
+ return { ...Output, _error, _debug: logger.output };
59
+ } catch (err: any) {
60
+ const _error = err?.response?.data || err?.message || err.toString();
61
+ logger.error(` Error saving file \n${_error}\n`);
62
+ return { Output: undefined, _error, _debug: logger.output };
63
+ }
64
+ }
65
+
66
+ getExtension(mimeType: string) {
67
+ const extension = mimeType.split('/')[1];
68
+ return extension;
69
+ }
70
+
71
+ getFileName(customName: string, extension: string) {
72
+ const uniqueId = (() => btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(9)))).replace(/[+/=]/g, ''))();
73
+ return `${uniqueId}${customName ? `.${customName}` : ''}.${extension}`;
74
+ }
75
+ }
@@ -0,0 +1,97 @@
1
+ import { IAgent as Agent } from '@sre/types/Agent.types';
2
+ import { Component } from './Component.class';
3
+ import Joi from 'joi';
4
+ import { JSONContent } from '@sre/helpers/JsonContent.helper';
5
+
6
+ export class ForEach extends Component {
7
+ protected configSchema = null;
8
+ constructor() {
9
+ super();
10
+ }
11
+ init() {}
12
+ async process(input, config, agent: Agent) {
13
+ await super.process(input, config, agent);
14
+ let Loop = {};
15
+ let Result;
16
+ let _temp_result;
17
+ let _error = null;
18
+ let _in_progress = true;
19
+ const logger = this.createComponentLogger(agent, config);
20
+ try {
21
+ const inputObject = input.Input;
22
+ let inputArray;
23
+
24
+ //Try to parse multiple arrays formats since forEach always expects and array
25
+ if (Array.isArray(inputObject)) inputArray = inputObject;
26
+ else {
27
+ if (typeof inputObject === 'string') {
28
+ inputArray = inputObject.trim().startsWith('[') ? JSONContent(inputObject).tryParse() : inputObject.split(',');
29
+ } else {
30
+ inputArray = [inputObject];
31
+ }
32
+ }
33
+
34
+ if (!Array.isArray(inputArray) && typeof inputArray === 'object')
35
+ //if json object, use the values
36
+ inputArray = Object.values(inputArray);
37
+
38
+ const runtimeData = agent.agentRuntime.getRuntimeData(config.id);
39
+ const _ForEachData = runtimeData._LoopData || { parentId: config.id, loopIndex: 0, loopLength: inputArray.length };
40
+
41
+ logger.debug(`Loop: ${_ForEachData.loopIndex} / ${_ForEachData.loopLength}`);
42
+ delete _ForEachData.branches; //reset branches (the number of branches is calculated in CallComponent@Agent.class.ts )
43
+
44
+ if (_ForEachData.result) {
45
+ _temp_result = _ForEachData.result;
46
+ logger.debug(` => Loop Result : ${JSON.stringify(Loop, null, 2)}`);
47
+ logger.debug(`---------------------------------------------------`);
48
+ }
49
+
50
+ Loop = inputArray[_ForEachData.loopIndex];
51
+
52
+ logger.debug(` => Loop Data : ${JSON.stringify(Loop, null, 2)}`);
53
+
54
+ _in_progress = Loop !== undefined;
55
+ if (_in_progress) {
56
+ _ForEachData.loopIndex++;
57
+ }
58
+ _ForEachData._in_progress = _in_progress;
59
+
60
+ agent.agentRuntime.updateRuntimeData(config.id, { _LoopData: _ForEachData });
61
+ } catch (error: any) {
62
+ _error = error;
63
+ logger.error(error);
64
+ }
65
+ if (!_in_progress) {
66
+ Result = _temp_result || [];
67
+
68
+ switch (config?.data?.format) {
69
+ case 'minimal':
70
+ Result = Result.map((item) => cleanupResult(item.result));
71
+ break;
72
+ case 'results-array':
73
+ Result = Result.map((item) => Object.values(cleanupResult(item.result))).flat(Infinity);
74
+ break;
75
+ }
76
+ }
77
+
78
+ return { Loop, Result, _temp_result, _error, _in_progress, _debug: logger.output };
79
+ }
80
+ async postProcess(output, config, agent: Agent): Promise<any> {
81
+ output = await super.postProcess(output, config, agent);
82
+ if (output?.result) {
83
+ delete output.result._temp_result;
84
+ delete output.result._in_progress;
85
+ delete output.result.Loop;
86
+ }
87
+ return output;
88
+ }
89
+ }
90
+ function cleanupResult(result) {
91
+ if (typeof result !== 'object') return result;
92
+ if (result._debug) delete result._debug;
93
+ if (result._error) delete result._error;
94
+ if (result._temp_result) delete result._temp_result;
95
+ if (result._in_progress) delete result._in_progress;
96
+ return result;
97
+ }
@@ -0,0 +1,70 @@
1
+ import Joi from 'joi';
2
+
3
+ import { Agent } from '@sre/AgentManager/Agent.class';
4
+ import { Conversation } from '@sre/helpers/Conversation.helper';
5
+ import { TemplateString } from '@sre/helpers/TemplateString.helper';
6
+
7
+ import { Component } from './Component.class';
8
+
9
+ export class GPTPlugin extends Component {
10
+ protected configSchema = Joi.object({
11
+ model: Joi.string().optional(),
12
+ openAiModel: Joi.string().optional(), // for backward compatibility
13
+ specUrl: Joi.string().max(2048).uri().required().description('URL of the OpenAPI specification'),
14
+ descForModel: Joi.string().max(5000).required().allow('').label('Description for Model'),
15
+ name: Joi.string().max(500).required().allow(''),
16
+ desc: Joi.string().max(5000).required().allow('').label('Description'),
17
+ logoUrl: Joi.string().max(8192).allow(''),
18
+ id: Joi.string().max(200),
19
+ version: Joi.string().max(100).allow(''),
20
+ domain: Joi.string().max(253).allow(''),
21
+ });
22
+
23
+ constructor() {
24
+ super();
25
+ }
26
+
27
+ init() {}
28
+
29
+ async process(input, config, agent: Agent) {
30
+ await super.process(input, config, agent);
31
+ const logger = this.createComponentLogger(agent, config);
32
+
33
+ logger.debug(`=== Open API Log ===`);
34
+
35
+ try {
36
+ const specUrl = config?.data?.specUrl;
37
+
38
+ if (!specUrl) {
39
+ return { _error: 'Please provide a Open API Specification URL!', _debug: logger.output };
40
+ }
41
+
42
+ const model = config?.data?.model || config?.data?.openAiModel;
43
+ const descForModel = TemplateString(config?.data?.descForModel).parse(input).result;
44
+ let prompt = '';
45
+
46
+ if (input?.Prompt) {
47
+ prompt = typeof input?.Prompt === 'string' ? input?.Prompt : JSON.stringify(input?.Prompt);
48
+ } else if (input?.Query) {
49
+ prompt = typeof input?.Query === 'string' ? input?.Query : JSON.stringify(input?.Query);
50
+ }
51
+
52
+ if (!prompt) {
53
+ return { _error: 'Please provide a prompt', _debug: logger.output };
54
+ }
55
+
56
+ // TODO [Forhad]: Need to check and validate input prompt token
57
+
58
+ const conv = new Conversation(model, specUrl, { systemPrompt: descForModel, agentId: agent?.id });
59
+
60
+ const result = await conv.prompt(prompt);
61
+
62
+ logger.debug(`Response:\n`, result, '\n');
63
+
64
+ return { Output: result, _debug: logger.output };
65
+ } catch (error: any) {
66
+ console.error('Error on running Open API: ', error);
67
+ return { _error: `Error on running Open API!\n${error?.message || JSON.stringify(error)}`, _debug: logger.output };
68
+ }
69
+ }
70
+ }