@smythos/sre 1.5.1 → 1.5.4

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 (193) hide show
  1. package/LICENSE +18 -0
  2. package/dist/index.js +22329 -4
  3. package/dist/index.js.map +1 -1
  4. package/dist/types/subsystems/IO/VectorDB.service/connectors/PineconeVectorDB.class.d.ts +2 -2
  5. package/dist/types/subsystems/IO/VectorDB.service/embed/BaseEmbedding.d.ts +11 -7
  6. package/dist/types/types/VectorDB.types.d.ts +13 -11
  7. package/package.json +102 -127
  8. package/src/Components/APICall/APICall.class.ts +155 -0
  9. package/src/Components/APICall/AccessTokenManager.ts +130 -0
  10. package/src/Components/APICall/ArrayBufferResponse.helper.ts +58 -0
  11. package/src/Components/APICall/OAuth.helper.ts +294 -0
  12. package/src/Components/APICall/mimeTypeCategories.ts +46 -0
  13. package/src/Components/APICall/parseData.ts +167 -0
  14. package/src/Components/APICall/parseHeaders.ts +41 -0
  15. package/src/Components/APICall/parseProxy.ts +68 -0
  16. package/src/Components/APICall/parseUrl.ts +91 -0
  17. package/src/Components/APIEndpoint.class.ts +234 -0
  18. package/src/Components/APIOutput.class.ts +58 -0
  19. package/src/Components/AgentPlugin.class.ts +102 -0
  20. package/src/Components/Async.class.ts +155 -0
  21. package/src/Components/Await.class.ts +90 -0
  22. package/src/Components/Classifier.class.ts +158 -0
  23. package/src/Components/Component.class.ts +94 -0
  24. package/src/Components/ComponentHost.class.ts +38 -0
  25. package/src/Components/DataSourceCleaner.class.ts +92 -0
  26. package/src/Components/DataSourceIndexer.class.ts +181 -0
  27. package/src/Components/DataSourceLookup.class.ts +141 -0
  28. package/src/Components/FEncDec.class.ts +29 -0
  29. package/src/Components/FHash.class.ts +33 -0
  30. package/src/Components/FSign.class.ts +80 -0
  31. package/src/Components/FSleep.class.ts +25 -0
  32. package/src/Components/FTimestamp.class.ts +25 -0
  33. package/src/Components/FileStore.class.ts +75 -0
  34. package/src/Components/ForEach.class.ts +97 -0
  35. package/src/Components/GPTPlugin.class.ts +70 -0
  36. package/src/Components/GenAILLM.class.ts +395 -0
  37. package/src/Components/HuggingFace.class.ts +314 -0
  38. package/src/Components/Image/imageSettings.config.ts +70 -0
  39. package/src/Components/ImageGenerator.class.ts +407 -0
  40. package/src/Components/JSONFilter.class.ts +54 -0
  41. package/src/Components/LLMAssistant.class.ts +213 -0
  42. package/src/Components/LogicAND.class.ts +28 -0
  43. package/src/Components/LogicAtLeast.class.ts +85 -0
  44. package/src/Components/LogicAtMost.class.ts +86 -0
  45. package/src/Components/LogicOR.class.ts +29 -0
  46. package/src/Components/LogicXOR.class.ts +34 -0
  47. package/src/Components/MCPClient.class.ts +112 -0
  48. package/src/Components/PromptGenerator.class.ts +122 -0
  49. package/src/Components/ScrapflyWebScrape.class.ts +159 -0
  50. package/src/Components/TavilyWebSearch.class.ts +98 -0
  51. package/src/Components/index.ts +77 -0
  52. package/src/Core/AgentProcess.helper.ts +240 -0
  53. package/src/Core/Connector.class.ts +123 -0
  54. package/src/Core/ConnectorsService.ts +192 -0
  55. package/src/Core/DummyConnector.ts +49 -0
  56. package/src/Core/HookService.ts +105 -0
  57. package/src/Core/SmythRuntime.class.ts +292 -0
  58. package/src/Core/SystemEvents.ts +15 -0
  59. package/src/Core/boot.ts +55 -0
  60. package/src/config.ts +15 -0
  61. package/src/constants.ts +125 -0
  62. package/src/data/hugging-face.params.json +580 -0
  63. package/src/helpers/BinaryInput.helper.ts +324 -0
  64. package/src/helpers/Conversation.helper.ts +1094 -0
  65. package/src/helpers/JsonContent.helper.ts +97 -0
  66. package/src/helpers/LocalCache.helper.ts +97 -0
  67. package/src/helpers/Log.helper.ts +234 -0
  68. package/src/helpers/OpenApiParser.helper.ts +150 -0
  69. package/src/helpers/S3Cache.helper.ts +129 -0
  70. package/src/helpers/SmythURI.helper.ts +5 -0
  71. package/src/helpers/TemplateString.helper.ts +243 -0
  72. package/src/helpers/TypeChecker.helper.ts +329 -0
  73. package/src/index.ts +179 -0
  74. package/src/index.ts.bak +179 -0
  75. package/src/subsystems/AgentManager/Agent.class.ts +1108 -0
  76. package/src/subsystems/AgentManager/Agent.helper.ts +3 -0
  77. package/src/subsystems/AgentManager/AgentData.service/AgentDataConnector.ts +230 -0
  78. package/src/subsystems/AgentManager/AgentData.service/connectors/CLIAgentDataConnector.class.ts +66 -0
  79. package/src/subsystems/AgentManager/AgentData.service/connectors/LocalAgentDataConnector.class.ts +142 -0
  80. package/src/subsystems/AgentManager/AgentData.service/connectors/NullAgentData.class.ts +39 -0
  81. package/src/subsystems/AgentManager/AgentData.service/index.ts +18 -0
  82. package/src/subsystems/AgentManager/AgentLogger.class.ts +297 -0
  83. package/src/subsystems/AgentManager/AgentRequest.class.ts +51 -0
  84. package/src/subsystems/AgentManager/AgentRuntime.class.ts +559 -0
  85. package/src/subsystems/AgentManager/AgentSSE.class.ts +101 -0
  86. package/src/subsystems/AgentManager/AgentSettings.class.ts +52 -0
  87. package/src/subsystems/AgentManager/Component.service/ComponentConnector.ts +32 -0
  88. package/src/subsystems/AgentManager/Component.service/connectors/LocalComponentConnector.class.ts +59 -0
  89. package/src/subsystems/AgentManager/Component.service/index.ts +11 -0
  90. package/src/subsystems/AgentManager/EmbodimentSettings.class.ts +47 -0
  91. package/src/subsystems/AgentManager/ForkedAgent.class.ts +153 -0
  92. package/src/subsystems/AgentManager/OSResourceMonitor.ts +77 -0
  93. package/src/subsystems/ComputeManager/Code.service/CodeConnector.ts +99 -0
  94. package/src/subsystems/ComputeManager/Code.service/connectors/AWSLambdaCode.class.ts +63 -0
  95. package/src/subsystems/ComputeManager/Code.service/index.ts +11 -0
  96. package/src/subsystems/IO/CLI.service/CLIConnector.ts +47 -0
  97. package/src/subsystems/IO/CLI.service/index.ts +9 -0
  98. package/src/subsystems/IO/Log.service/LogConnector.ts +32 -0
  99. package/src/subsystems/IO/Log.service/connectors/ConsoleLog.class.ts +28 -0
  100. package/src/subsystems/IO/Log.service/index.ts +13 -0
  101. package/src/subsystems/IO/NKV.service/NKVConnector.ts +41 -0
  102. package/src/subsystems/IO/NKV.service/connectors/NKVRAM.class.ts +204 -0
  103. package/src/subsystems/IO/NKV.service/connectors/NKVRedis.class.ts +182 -0
  104. package/src/subsystems/IO/NKV.service/index.ts +12 -0
  105. package/src/subsystems/IO/Router.service/RouterConnector.ts +21 -0
  106. package/src/subsystems/IO/Router.service/connectors/ExpressRouter.class.ts +48 -0
  107. package/src/subsystems/IO/Router.service/connectors/NullRouter.class.ts +40 -0
  108. package/src/subsystems/IO/Router.service/index.ts +11 -0
  109. package/src/subsystems/IO/Storage.service/SmythFS.class.ts +472 -0
  110. package/src/subsystems/IO/Storage.service/StorageConnector.ts +66 -0
  111. package/src/subsystems/IO/Storage.service/connectors/LocalStorage.class.ts +305 -0
  112. package/src/subsystems/IO/Storage.service/connectors/S3Storage.class.ts +418 -0
  113. package/src/subsystems/IO/Storage.service/index.ts +13 -0
  114. package/src/subsystems/IO/VectorDB.service/VectorDBConnector.ts +108 -0
  115. package/src/subsystems/IO/VectorDB.service/connectors/MilvusVectorDB.class.ts +454 -0
  116. package/src/subsystems/IO/VectorDB.service/connectors/PineconeVectorDB.class.ts +384 -0
  117. package/src/subsystems/IO/VectorDB.service/connectors/RAMVecrtorDB.class.ts +421 -0
  118. package/src/subsystems/IO/VectorDB.service/embed/BaseEmbedding.ts +107 -0
  119. package/src/subsystems/IO/VectorDB.service/embed/OpenAIEmbedding.ts +109 -0
  120. package/src/subsystems/IO/VectorDB.service/embed/index.ts +21 -0
  121. package/src/subsystems/IO/VectorDB.service/index.ts +14 -0
  122. package/src/subsystems/LLMManager/LLM.helper.ts +221 -0
  123. package/src/subsystems/LLMManager/LLM.inference.ts +335 -0
  124. package/src/subsystems/LLMManager/LLM.service/LLMConnector.ts +375 -0
  125. package/src/subsystems/LLMManager/LLM.service/LLMCredentials.helper.ts +145 -0
  126. package/src/subsystems/LLMManager/LLM.service/connectors/Anthropic.class.ts +632 -0
  127. package/src/subsystems/LLMManager/LLM.service/connectors/Bedrock.class.ts +405 -0
  128. package/src/subsystems/LLMManager/LLM.service/connectors/Echo.class.ts +81 -0
  129. package/src/subsystems/LLMManager/LLM.service/connectors/GoogleAI.class.ts +689 -0
  130. package/src/subsystems/LLMManager/LLM.service/connectors/Groq.class.ts +257 -0
  131. package/src/subsystems/LLMManager/LLM.service/connectors/OpenAI.class.ts +848 -0
  132. package/src/subsystems/LLMManager/LLM.service/connectors/Perplexity.class.ts +255 -0
  133. package/src/subsystems/LLMManager/LLM.service/connectors/VertexAI.class.ts +193 -0
  134. package/src/subsystems/LLMManager/LLM.service/index.ts +43 -0
  135. package/src/subsystems/LLMManager/ModelsProvider.service/ModelsProviderConnector.ts +281 -0
  136. package/src/subsystems/LLMManager/ModelsProvider.service/connectors/SmythModelsProvider.class.ts +229 -0
  137. package/src/subsystems/LLMManager/ModelsProvider.service/index.ts +11 -0
  138. package/src/subsystems/LLMManager/custom-models.ts +854 -0
  139. package/src/subsystems/LLMManager/models.ts +2539 -0
  140. package/src/subsystems/LLMManager/paramMappings.ts +69 -0
  141. package/src/subsystems/MemoryManager/Cache.service/CacheConnector.ts +86 -0
  142. package/src/subsystems/MemoryManager/Cache.service/connectors/LocalStorageCache.class.ts +297 -0
  143. package/src/subsystems/MemoryManager/Cache.service/connectors/RAMCache.class.ts +201 -0
  144. package/src/subsystems/MemoryManager/Cache.service/connectors/RedisCache.class.ts +252 -0
  145. package/src/subsystems/MemoryManager/Cache.service/connectors/S3Cache.class.ts +373 -0
  146. package/src/subsystems/MemoryManager/Cache.service/index.ts +15 -0
  147. package/src/subsystems/MemoryManager/LLMCache.ts +72 -0
  148. package/src/subsystems/MemoryManager/LLMContext.ts +125 -0
  149. package/src/subsystems/MemoryManager/RuntimeContext.ts +249 -0
  150. package/src/subsystems/Security/AccessControl/ACL.class.ts +208 -0
  151. package/src/subsystems/Security/AccessControl/AccessCandidate.class.ts +76 -0
  152. package/src/subsystems/Security/AccessControl/AccessRequest.class.ts +52 -0
  153. package/src/subsystems/Security/Account.service/AccountConnector.ts +41 -0
  154. package/src/subsystems/Security/Account.service/connectors/AWSAccount.class.ts +76 -0
  155. package/src/subsystems/Security/Account.service/connectors/DummyAccount.class.ts +130 -0
  156. package/src/subsystems/Security/Account.service/connectors/JSONFileAccount.class.ts +159 -0
  157. package/src/subsystems/Security/Account.service/index.ts +14 -0
  158. package/src/subsystems/Security/Credentials.helper.ts +62 -0
  159. package/src/subsystems/Security/ManagedVault.service/ManagedVaultConnector.ts +34 -0
  160. package/src/subsystems/Security/ManagedVault.service/connectors/NullManagedVault.class.ts +57 -0
  161. package/src/subsystems/Security/ManagedVault.service/connectors/SecretManagerManagedVault.ts +154 -0
  162. package/src/subsystems/Security/ManagedVault.service/index.ts +12 -0
  163. package/src/subsystems/Security/SecureConnector.class.ts +110 -0
  164. package/src/subsystems/Security/Vault.service/Vault.helper.ts +30 -0
  165. package/src/subsystems/Security/Vault.service/VaultConnector.ts +26 -0
  166. package/src/subsystems/Security/Vault.service/connectors/HashicorpVault.class.ts +46 -0
  167. package/src/subsystems/Security/Vault.service/connectors/JSONFileVault.class.ts +166 -0
  168. package/src/subsystems/Security/Vault.service/connectors/NullVault.class.ts +54 -0
  169. package/src/subsystems/Security/Vault.service/connectors/SecretsManager.class.ts +140 -0
  170. package/src/subsystems/Security/Vault.service/index.ts +12 -0
  171. package/src/types/ACL.types.ts +104 -0
  172. package/src/types/AWS.types.ts +9 -0
  173. package/src/types/Agent.types.ts +61 -0
  174. package/src/types/AgentLogger.types.ts +17 -0
  175. package/src/types/Cache.types.ts +1 -0
  176. package/src/types/Common.types.ts +3 -0
  177. package/src/types/LLM.types.ts +419 -0
  178. package/src/types/Redis.types.ts +8 -0
  179. package/src/types/SRE.types.ts +64 -0
  180. package/src/types/Security.types.ts +18 -0
  181. package/src/types/Storage.types.ts +5 -0
  182. package/src/types/VectorDB.types.ts +86 -0
  183. package/src/utils/base64.utils.ts +275 -0
  184. package/src/utils/cli.utils.ts +68 -0
  185. package/src/utils/data.utils.ts +263 -0
  186. package/src/utils/date-time.utils.ts +22 -0
  187. package/src/utils/general.utils.ts +238 -0
  188. package/src/utils/index.ts +12 -0
  189. package/src/utils/numbers.utils.ts +13 -0
  190. package/src/utils/oauth.utils.ts +35 -0
  191. package/src/utils/string.utils.ts +414 -0
  192. package/src/utils/url.utils.ts +19 -0
  193. package/src/utils/validation.utils.ts +74 -0
@@ -0,0 +1,28 @@
1
+ import { IAgent as Agent } from '@sre/types/Agent.types';
2
+ import { Component } from './Component.class';
3
+
4
+ export class LogicAND 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
+ const result: any = { Output: true };
13
+
14
+ for (let cfgInput of config.inputs) {
15
+ // check if all inputs are set (expected inputs are in "config.inputs" actual inputs are in "input")
16
+ if (!input[cfgInput.name]) {
17
+ result.Output = undefined;
18
+ break;
19
+ }
20
+ }
21
+
22
+ result.Verified = result.Output !== undefined;
23
+ result.Unverified = !result.Verified;
24
+ if (!result.Verified) delete result.Verified;
25
+ if (!result.Unverified) delete result.Unverified;
26
+ return result;
27
+ }
28
+ }
@@ -0,0 +1,85 @@
1
+ import Joi from 'joi';
2
+
3
+ import { IAgent as Agent } from '@sre/types/Agent.types';
4
+ import { Component } from './Component.class';
5
+
6
+ export class LogicAtLeast extends Component {
7
+ protected configSchema = Joi.object({
8
+ // TODO (Forhad): Need to check if min and max work instead of the custom validateInteger
9
+ minSetInputs: Joi.string()
10
+ .custom(validateInteger({ min: 0, max: 9 }), 'custom range validation')
11
+ .label('Minimum Inputs'),
12
+ });
13
+ constructor() {
14
+ super();
15
+ }
16
+
17
+ init() {}
18
+
19
+ async process(input, config, agent: Agent) {
20
+ await super.process(input, config, agent);
21
+ const logger = this.createComponentLogger(agent, config);
22
+ const result: any = { Output: undefined };
23
+
24
+ if (typeof config.data.minSetInputs !== 'string' || config.data.minSetInputs.trim() === '' || isNaN(Number(config.data.minSetInputs))) {
25
+ return result;
26
+ }
27
+
28
+ const minSetInputs = Number(config.data.minSetInputs);
29
+ if (config.inputs.length < minSetInputs) {
30
+ return result;
31
+ }
32
+
33
+ let trueCount = 0;
34
+ for (let cfgInput of config.inputs) {
35
+ if (input[cfgInput.name]) {
36
+ trueCount++;
37
+ }
38
+ }
39
+
40
+ if (trueCount >= minSetInputs) {
41
+ result.Output = true;
42
+ }
43
+
44
+ result.Verified = result.Output !== undefined;
45
+ result.Unverified = !result.Verified;
46
+ if (!result.Verified) delete result.Verified;
47
+ if (!result.Unverified) delete result.Unverified;
48
+
49
+ return result;
50
+ }
51
+ }
52
+
53
+ interface RangeValidationArgs {
54
+ min?: number;
55
+ max?: number;
56
+ }
57
+
58
+ function validateInteger(args: RangeValidationArgs) {
59
+ return (value: string, helpers: any) => {
60
+ const numValue = Number(value);
61
+ const fieldName = helpers.schema._flags.label || helpers.state.path[helpers.state.path.length - 1];
62
+
63
+ // Check if the value is a number
64
+ if (isNaN(numValue)) {
65
+ throw new Error(`The value for '${fieldName}' must be a number`);
66
+ }
67
+
68
+ // Range validations
69
+ if (args.min !== undefined && args.max !== undefined) {
70
+ if (numValue < args.min || numValue > args.max) {
71
+ throw new Error(`The value for '${fieldName}' must be from ${args.min} to ${args.max}`);
72
+ }
73
+ } else if (args.min !== undefined) {
74
+ if (numValue < args.min) {
75
+ throw new Error(`The value for '${fieldName}' must be greater or equal to ${args.min}`);
76
+ }
77
+ } else if (args.max !== undefined) {
78
+ if (numValue > args.max) {
79
+ throw new Error(`The value for '${fieldName}' must be less or equal to ${args.max}`);
80
+ }
81
+ }
82
+
83
+ return value; // Value is valid
84
+ };
85
+ }
@@ -0,0 +1,86 @@
1
+ import Joi from 'joi';
2
+
3
+ import { IAgent as Agent } from '@sre/types/Agent.types';
4
+ import { Component } from './Component.class';
5
+
6
+ export class LogicAtMost extends Component {
7
+ protected configSchema = Joi.object({
8
+ // TODO (Forhad): Need to check if min and max work instead of the custom validateInteger
9
+ maxSetInputs: Joi.string()
10
+ .custom(validateInteger({ min: 0, max: 9 }), 'custom range validation')
11
+ .label('Maximum Inputs'),
12
+ });
13
+ constructor() {
14
+ super();
15
+ }
16
+
17
+ init() {}
18
+
19
+ async process(input, config, agent: Agent) {
20
+ await super.process(input, config, agent);
21
+ const result: any = { Output: undefined };
22
+
23
+ if (typeof config.data.maxSetInputs !== 'string' || config.data.maxSetInputs.trim() === '' || isNaN(Number(config.data.maxSetInputs))) {
24
+ return result;
25
+ }
26
+
27
+ const maxSetInputs = Number(config.data.maxSetInputs);
28
+ if (config.inputs.length < maxSetInputs) {
29
+ return result;
30
+ }
31
+
32
+ let trueCount = 0;
33
+ for (let cfgInput of config.inputs) {
34
+ if (input[cfgInput.name]) {
35
+ trueCount++;
36
+ if (trueCount > maxSetInputs) {
37
+ break;
38
+ }
39
+ }
40
+ }
41
+
42
+ if (trueCount <= maxSetInputs) {
43
+ result.Output = true;
44
+ }
45
+
46
+ result.Verified = result.Output !== undefined;
47
+ result.Unverified = !result.Verified;
48
+ if (!result.Verified) delete result.Verified;
49
+ if (!result.Unverified) delete result.Unverified;
50
+
51
+ return result;
52
+ }
53
+ }
54
+ interface RangeValidationArgs {
55
+ min?: number;
56
+ max?: number;
57
+ }
58
+
59
+ function validateInteger(args: RangeValidationArgs) {
60
+ return (value: string, helpers: any) => {
61
+ const numValue = Number(value);
62
+ const fieldName = helpers.schema._flags.label || helpers.state.path[helpers.state.path.length - 1];
63
+
64
+ // Check if the value is a number
65
+ if (isNaN(numValue)) {
66
+ throw new Error(`The value for '${fieldName}' must be a number`);
67
+ }
68
+
69
+ // Range validations
70
+ if (args.min !== undefined && args.max !== undefined) {
71
+ if (numValue < args.min || numValue > args.max) {
72
+ throw new Error(`The value for '${fieldName}' must be from ${args.min} to ${args.max}`);
73
+ }
74
+ } else if (args.min !== undefined) {
75
+ if (numValue < args.min) {
76
+ throw new Error(`The value for '${fieldName}' must be greater or equal to ${args.min}`);
77
+ }
78
+ } else if (args.max !== undefined) {
79
+ if (numValue > args.max) {
80
+ throw new Error(`The value for '${fieldName}' must be less or equal to ${args.max}`);
81
+ }
82
+ }
83
+
84
+ return value; // Value is valid
85
+ };
86
+ }
@@ -0,0 +1,29 @@
1
+ import { IAgent as Agent } from '@sre/types/Agent.types';
2
+ import { Component } from './Component.class';
3
+
4
+ export class LogicOR 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 result: any = { Output: undefined };
12
+ console.log(input);
13
+ console.log(config);
14
+ for (let cfgInput of config.inputs) {
15
+ // check if one of the inputs are set (expected inputs are in "config.inputs" actual inputs are in "input")
16
+ if (input[cfgInput.name]) {
17
+ result.Output = true;
18
+ break;
19
+ }
20
+ }
21
+
22
+ result.Verified = result.Output !== undefined;
23
+ result.Unverified = !result.Verified;
24
+ if (!result.Verified) delete result.Verified;
25
+ if (!result.Unverified) delete result.Unverified;
26
+
27
+ return result;
28
+ }
29
+ }
@@ -0,0 +1,34 @@
1
+ import { IAgent as Agent } from '@sre/types/Agent.types';
2
+ import { Component } from './Component.class';
3
+
4
+ export class LogicXOR extends Component {
5
+ constructor() {
6
+ super();
7
+ }
8
+
9
+ init() {}
10
+
11
+ async process(input, config, agent: Agent) {
12
+ await super.process(input, config, agent);
13
+ const result: any = { Output: undefined };
14
+ let trueCount = 0;
15
+
16
+ for (let cfgInput of config.inputs) {
17
+ // counts the number of set inputs
18
+ if (input[cfgInput.name]) {
19
+ trueCount++;
20
+ }
21
+ }
22
+ // checks if only one input is set, to trigger output
23
+ if (trueCount === 1) {
24
+ result.Output = true;
25
+ }
26
+
27
+ result.Verified = result.Output !== undefined;
28
+ result.Unverified = !result.Verified;
29
+ if (!result.Verified) delete result.Verified;
30
+ if (!result.Unverified) delete result.Unverified;
31
+
32
+ return result;
33
+ }
34
+ }
@@ -0,0 +1,112 @@
1
+ import Joi from 'joi';
2
+
3
+ import { IAgent as Agent } from '@sre/types/Agent.types';
4
+ import { Conversation } from '@sre/helpers/Conversation.helper';
5
+ import { TemplateString } from '@sre/helpers/TemplateString.helper';
6
+
7
+ import { Component } from './Component.class';
8
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
9
+ import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
10
+
11
+ export class MCPClient extends Component {
12
+ protected configSchema = Joi.object({
13
+ model: Joi.string().optional(),
14
+ openAiModel: Joi.string().optional(), // for backward compatibility
15
+ mcpUrl: Joi.string().max(2048).uri().required().description('URL of the MCP'),
16
+ descForModel: Joi.string().max(5000).required().allow('').label('Description for Model'),
17
+ name: Joi.string().max(500).required().allow(''),
18
+ desc: Joi.string().max(5000).required().allow('').label('Description'),
19
+ logoUrl: Joi.string().max(8192).allow(''),
20
+ id: Joi.string().max(200),
21
+ version: Joi.string().max(100).allow(''),
22
+ domain: Joi.string().max(253).allow(''),
23
+ prompt: Joi.string().max(5000).optional().allow('').label('Prompt'),
24
+ });
25
+
26
+ constructor() {
27
+ super();
28
+ }
29
+
30
+ init() {}
31
+
32
+ async process(input, config, agent: Agent) {
33
+ await super.process(input, config, agent);
34
+ const logger = this.createComponentLogger(agent, config);
35
+
36
+ logger.debug(`=== MCP Client Log ===`);
37
+
38
+ try {
39
+ const mcpUrl = config?.data?.mcpUrl;
40
+ if (!mcpUrl) {
41
+ return { _error: 'Please provide a MCP URL!', _debug: logger.output };
42
+ }
43
+
44
+ const model = config?.data?.model || config?.data?.openAiModel;
45
+ const descForModel = TemplateString(config?.data?.descForModel).parse(input).result;
46
+ let prompt = TemplateString(config?.data?.prompt).parse(input).result;
47
+
48
+ if (!prompt) {
49
+ return { _error: 'Please provide a prompt', _debug: logger.output };
50
+ }
51
+
52
+ // TODO [Forhad]: Need to check and validate input prompt token
53
+ const baseUrl = new URL(mcpUrl);
54
+ const transport = new SSEClientTransport(baseUrl);
55
+ const client = new Client({
56
+ name: 'sse-client',
57
+ version: '1.0.0',
58
+ });
59
+ await client.connect(transport);
60
+ const toolsData = await client.listTools();
61
+ const conv = new Conversation(
62
+ model,
63
+ {
64
+ openapi: '3.0.1',
65
+ info: {
66
+ title: `${agent?.name}`,
67
+ version: `${agent?.version}`,
68
+ description: descForModel,
69
+ },
70
+ servers: [
71
+ {
72
+ url: agent?.domain,
73
+ },
74
+ ],
75
+ paths: {},
76
+ },
77
+ { agentId: agent?.id },
78
+ );
79
+
80
+ for (const tool of toolsData.tools) {
81
+ let toolArgs = {};
82
+ Object.entries(tool.inputSchema.properties).forEach(([propName, propDetails]) => {
83
+ toolArgs[propName] = {
84
+ description: '',
85
+ required: ((tool.inputSchema.required as string[]) || []).includes(propName) || false,
86
+ type: (propDetails as any).type,
87
+ ...((propDetails as any).type === 'array' ? { items: { type: 'string' } } : {}),
88
+ };
89
+ });
90
+ await conv.addTool({
91
+ name: tool.name,
92
+ description: tool.description,
93
+ arguments: toolArgs,
94
+ handler: async (input) => {
95
+ const result = await client.callTool({
96
+ name: tool.name,
97
+ arguments: input,
98
+ });
99
+ return result;
100
+ },
101
+ });
102
+ }
103
+ const result = await conv.prompt(prompt);
104
+
105
+ logger.debug(`Response:\n`, result, '\n');
106
+
107
+ return { Output: result, _debug: logger.output };
108
+ } catch (error: any) {
109
+ return { _error: `Error on running MCP Client!\n${error?.message || JSON.stringify(error)}`, _debug: logger.output };
110
+ }
111
+ }
112
+ }
@@ -0,0 +1,122 @@
1
+ import Joi from 'joi';
2
+ import { IAgent as Agent } from '@sre/types/Agent.types';
3
+ import { LLMInference } from '@sre/LLMManager/LLM.inference';
4
+ import { TemplateString } from '@sre/helpers/TemplateString.helper';
5
+ import { Component } from './Component.class';
6
+ import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
7
+
8
+ //TODO : better handling of context window exceeding max length
9
+
10
+ export class PromptGenerator extends Component {
11
+ protected configSchema = Joi.object({
12
+ model: Joi.string().max(200).required(),
13
+ prompt: Joi.string().required().max(8_000_000).label('Prompt'), // 2M tokens is around 8M characters
14
+ temperature: Joi.number().min(0).max(5).label('Temperature'), // max temperature is 2 for OpenAI and togetherAI but 5 for cohere
15
+ maxTokens: Joi.number().min(1).label('Maximum Tokens'),
16
+ stopSequences: Joi.string().allow('').max(400).label('Stop Sequences'),
17
+ topP: Joi.number().min(0).max(1).label('Top P'),
18
+ topK: Joi.number().min(0).max(500).label('Top K'), // max top_k is 100 for togetherAI but 500 for cohere
19
+ frequencyPenalty: Joi.number().min(0).max(2).label('Frequency Penalty'),
20
+ presencePenalty: Joi.number().min(0).max(2).label('Presence Penalty'),
21
+ responseFormat: Joi.string().valid('json', 'text').optional().label('Response Format'),
22
+ passthrough: Joi.boolean().optional().label('Passthrough'),
23
+ });
24
+ constructor() {
25
+ super();
26
+ }
27
+ init() {}
28
+ async process(input, config, agent: Agent) {
29
+ await super.process(input, config, agent);
30
+
31
+ //let debugLog = agent.agentRuntime?.debug ? [] : undefined;
32
+ const logger = this.createComponentLogger(agent, config);
33
+
34
+ try {
35
+ logger.debug(`=== LLM Prompt Log ===`);
36
+ let teamId = agent?.teamId;
37
+
38
+ const passThrough: boolean = config.data.passthrough || false;
39
+ const model: string = config.data.model || 'echo';
40
+ const llmInference: LLMInference = await LLMInference.getInstance(model, AccessCandidate.agent(agent.id));
41
+
42
+ // if the llm is undefined, then it means we removed the model from our system
43
+ if (!llmInference.connector) {
44
+ return {
45
+ _error: `The model '${model}' is not available. Please try a different one.`,
46
+ _debug: logger.output,
47
+ };
48
+ }
49
+
50
+ const modelId = await agent.modelsProvider.getModelId(model);
51
+ logger.debug(` Model : ${modelId || model}`);
52
+
53
+ let prompt: any = TemplateString(config.data.prompt).parse(input).result;
54
+
55
+ logger.debug(` Prompt\n`, prompt, '\n');
56
+
57
+ // default to json response format
58
+ config.data.responseFormat = config.data?.responseFormat || 'json';
59
+
60
+ // request to LLM
61
+ let response: any;
62
+ if (passThrough) {
63
+ const contentPromise = new Promise(async (resolve, reject) => {
64
+ let _content = '';
65
+ const eventEmitter: any = await llmInference
66
+ .promptStream({
67
+ query: prompt,
68
+ params: { ...config, model, agentId: agent.id },
69
+ })
70
+ .catch((error) => {
71
+ console.error('Error on promptStream: ', error);
72
+ reject(error);
73
+ });
74
+ eventEmitter.on('content', (content) => {
75
+ if (typeof agent.callback === 'function') {
76
+ agent.callback({ content });
77
+ }
78
+ agent.sse.send('llm/passthrough/content', content);
79
+ _content += content;
80
+ });
81
+ eventEmitter.on('thinking', (thinking) => {
82
+ if (typeof agent.callback === 'function') {
83
+ agent.callback({ thinking });
84
+ }
85
+ agent.sse.send('llm/passthrough/thinking', thinking);
86
+ });
87
+ eventEmitter.on('end', () => {
88
+ console.log('end');
89
+ resolve(_content);
90
+ });
91
+ });
92
+ response = await contentPromise;
93
+ } else {
94
+ response = await llmInference
95
+ .prompt({ query: prompt, params: { ...config, agentId: agent.id } })
96
+ .catch((error) => ({ error: error }));
97
+ }
98
+
99
+ // in case we have the response but it's empty string, undefined or null
100
+ if (!response) {
101
+ return { _error: ' LLM Error = Empty Response!', _debug: logger.output };
102
+ }
103
+
104
+ if (response?.error) {
105
+ const error = response?.error + ' ' + (response?.details || '');
106
+ logger.error(` LLM Error=`, error);
107
+
108
+ return { Reply: response?.data, _error: error, _debug: logger.output };
109
+ }
110
+
111
+ logger.debug(' Response \n', response);
112
+
113
+ const result = { Reply: response };
114
+
115
+ result['_debug'] = logger.output;
116
+
117
+ return result;
118
+ } catch (error) {
119
+ return { _error: error.message, _debug: logger.output };
120
+ }
121
+ }
122
+ }
@@ -0,0 +1,159 @@
1
+ import { IAgent as Agent } from '@sre/types/Agent.types';
2
+ import { Component } from './Component.class';
3
+ import Joi from 'joi';
4
+ import SREConfig from '@sre/config';
5
+ import axios from 'axios';
6
+ import { SystemEvents } from '@sre/Core/SystemEvents';
7
+ import { AccessCandidate } from '../subsystems/Security/AccessControl/AccessCandidate.class';
8
+ import { getCredentials } from '../subsystems/Security/Credentials.helper';
9
+ // const CREDITS_PER_URL = 0.2;
10
+
11
+ export class ScrapflyWebScrape extends Component {
12
+ protected configSchema = Joi.object({
13
+ // includeImages: Joi.boolean().default(false).label('Include Image Results'),
14
+ antiScrapingProtection: Joi.boolean().default(false).label('Enable Anti-Scraping Protection'),
15
+ javascriptRendering: Joi.boolean().default(false).label('Enable JavaScript Rendering'),
16
+ autoScroll: Joi.boolean().default(false).label('Enable Auto Scroll'),
17
+ format: Joi.string().default('markdown').label('Format').optional(),
18
+ });
19
+
20
+ constructor() {
21
+ super();
22
+ }
23
+ init() {}
24
+ async process(input, config, agent: Agent) {
25
+ await super.process(input, config, agent);
26
+
27
+ const logger = this.createComponentLogger(agent, config);
28
+ try {
29
+ logger.debug(`=== Web Scrape Log ===`);
30
+ let Output: any = {};
31
+ let _error = undefined;
32
+ const scrapeUrls = this.extractUrls(input);
33
+ logger.debug('Payload:', JSON.stringify(config.data));
34
+ logger.debug(`Vaild URLs: ${JSON.stringify(scrapeUrls)}`);
35
+ const teamId = agent.teamId;
36
+ const key = await getCredentials(AccessCandidate.team(teamId), 'scrapfly');
37
+
38
+ const scrapeResults = await Promise.all(scrapeUrls.map((url) => this.scrapeURL(url, config.data, key)));
39
+ const results = scrapeResults
40
+ .filter((result) => result.success)
41
+ .map((result) => {
42
+ return { url: result.url, content: result.content };
43
+ });
44
+ const failedResults = scrapeResults
45
+ .filter((result) => !result.success)
46
+ .map((result) => {
47
+ return { url: result.url, error: result.error };
48
+ });
49
+
50
+ Output = { Results: results, FailedURLs: failedResults };
51
+ const totalCredits = scrapeResults.reduce((acc, result) => acc + (result.cost || 0), 0);
52
+ this.reportUsage({
53
+ urlsScraped: results?.length,
54
+ agentId: agent.id,
55
+ teamId: agent.teamId,
56
+ totalCredits,
57
+ });
58
+ return { ...Output, _error, _debug: logger.output };
59
+ } catch (err: any) {
60
+ const _error = err?.message || err?.response?.data || err.toString();
61
+ logger.error(` Error scraping web \n${_error}\n`);
62
+ return { Output: undefined, _error, _debug: logger.output };
63
+ }
64
+ }
65
+
66
+ async scrapeURL(url, data, key) {
67
+ try {
68
+ const response = await axios({
69
+ method: 'get',
70
+ url: 'https://api.scrapfly.io/scrape',
71
+ params: {
72
+ url: encodeURIComponent(url),
73
+ key,
74
+ cost_budget: 80,
75
+ ...(data.format ? { format: data.format } : { format: 'markdown' }),
76
+ ...(data.antiScrapingProtection && { asp: true }),
77
+ ...(data.javascriptRendering && { render_js: true }),
78
+ ...(data.autoScroll && { auto_scroll: true, render_js: true }),
79
+ },
80
+ });
81
+ return {
82
+ content: response.data?.result?.content,
83
+ success: true,
84
+ url,
85
+ cost: response.data?.context?.cost?.total || 0,
86
+ };
87
+ } catch (error) {
88
+ return {
89
+ content: undefined,
90
+ success: false,
91
+ error: error?.response?.data?.result?.error?.message || 'Failed to scrape URL',
92
+ url,
93
+ cost: 0,
94
+ };
95
+ }
96
+ }
97
+
98
+ extractUrls(input: any) {
99
+ const scrapeUrls = [];
100
+ for (const key in input) {
101
+ if (Object.prototype.hasOwnProperty.call(input, key)) {
102
+ const inputItem = input[key];
103
+ if (typeof inputItem === 'string') {
104
+ try {
105
+ let urls = JSON.parse(inputItem);
106
+ for (const url of urls) {
107
+ if (this.isValidUrl(url)) {
108
+ scrapeUrls.push(url.trim());
109
+ }
110
+ }
111
+ } catch (error) {
112
+ const commaSeparatedUrls = inputItem.split(',');
113
+ for (const url of commaSeparatedUrls) {
114
+ if (this.isValidUrl(url)) {
115
+ scrapeUrls.push(url.trim());
116
+ }
117
+ }
118
+ }
119
+ } else if (typeof inputItem === 'object') {
120
+ for (const url of inputItem) {
121
+ if (this.isValidUrl(url)) {
122
+ scrapeUrls.push(url.trim());
123
+ }
124
+ }
125
+ }
126
+ }
127
+ }
128
+ return scrapeUrls;
129
+ }
130
+
131
+ isValidUrl(urlString: string) {
132
+ try {
133
+ const urlToCheck = urlString;
134
+ new URL(urlToCheck);
135
+ return true;
136
+ } catch (error) {
137
+ return false;
138
+ }
139
+ }
140
+
141
+ protected reportUsage({
142
+ urlsScraped,
143
+ agentId,
144
+ teamId,
145
+ totalCredits,
146
+ }: {
147
+ urlsScraped: number;
148
+ agentId: string;
149
+ teamId: string;
150
+ totalCredits: number;
151
+ }) {
152
+ SystemEvents.emit('USAGE:API', {
153
+ sourceId: 'api:webscrape.smyth',
154
+ credits: totalCredits,
155
+ agentId,
156
+ teamId,
157
+ });
158
+ }
159
+ }