@smythos/sre 1.6.8 → 1.6.9

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 (239) hide show
  1. package/CHANGELOG +111 -111
  2. package/LICENSE +18 -18
  3. package/README.md +135 -135
  4. package/dist/bundle-analysis-lazy.html +4949 -0
  5. package/dist/bundle-analysis.html +4949 -0
  6. package/dist/index.js +2 -2
  7. package/dist/index.js.map +1 -1
  8. package/dist/types/Components/Triggers/Gmail.trigger.d.ts +58 -0
  9. package/dist/types/Components/Triggers/GmailTrigger.class.d.ts +44 -0
  10. package/dist/types/Components/Triggers/Trigger.class.d.ts +21 -0
  11. package/dist/types/Components/Triggers/WhatsApp.trigger.d.ts +22 -0
  12. package/dist/types/helpers/AIPerformanceAnalyzer.helper.d.ts +45 -0
  13. package/dist/types/helpers/AIPerformanceCollector.helper.d.ts +111 -0
  14. package/dist/types/subsystems/IO/Storage.service/connectors/AzureBlobStorage.class.d.ts +211 -0
  15. package/dist/types/subsystems/IO/VectorDB.service/connectors/WeaviateVectorDB.class.d.ts +187 -0
  16. package/dist/types/subsystems/PerformanceManager/Performance.service/PerformanceConnector.d.ts +102 -0
  17. package/dist/types/subsystems/PerformanceManager/Performance.service/connectors/LocalPerformanceConnector.class.d.ts +100 -0
  18. package/dist/types/subsystems/PerformanceManager/Performance.service/index.d.ts +22 -0
  19. package/dist/types/subsystems/Security/Credentials/Credentials.class.d.ts +2 -0
  20. package/dist/types/subsystems/Security/Credentials/ManagedOAuth2Credentials.class.d.ts +18 -0
  21. package/dist/types/subsystems/Security/Credentials/OAuth2Credentials.class.d.ts +14 -0
  22. package/dist/types/types/Performance.types.d.ts +468 -0
  23. package/dist/types/utils/package-manager.utils.d.ts +26 -0
  24. package/package.json +1 -1
  25. package/src/Components/APICall/APICall.class.ts +161 -161
  26. package/src/Components/APICall/AccessTokenManager.ts +166 -166
  27. package/src/Components/APICall/ArrayBufferResponse.helper.ts +58 -58
  28. package/src/Components/APICall/OAuth.helper.ts +447 -447
  29. package/src/Components/APICall/mimeTypeCategories.ts +46 -46
  30. package/src/Components/APICall/parseData.ts +167 -167
  31. package/src/Components/APICall/parseHeaders.ts +41 -41
  32. package/src/Components/APICall/parseProxy.ts +68 -68
  33. package/src/Components/APICall/parseUrl.ts +91 -91
  34. package/src/Components/APIEndpoint.class.ts +234 -234
  35. package/src/Components/APIOutput.class.ts +58 -58
  36. package/src/Components/AgentPlugin.class.ts +102 -102
  37. package/src/Components/Async.class.ts +155 -155
  38. package/src/Components/Await.class.ts +90 -90
  39. package/src/Components/Classifier.class.ts +158 -158
  40. package/src/Components/Component.class.ts +147 -147
  41. package/src/Components/ComponentHost.class.ts +38 -38
  42. package/src/Components/DataSourceCleaner.class.ts +92 -92
  43. package/src/Components/DataSourceIndexer.class.ts +181 -181
  44. package/src/Components/DataSourceLookup.class.ts +161 -161
  45. package/src/Components/ECMASandbox.class.ts +72 -72
  46. package/src/Components/FEncDec.class.ts +29 -29
  47. package/src/Components/FHash.class.ts +33 -33
  48. package/src/Components/FSign.class.ts +80 -80
  49. package/src/Components/FSleep.class.ts +25 -25
  50. package/src/Components/FTimestamp.class.ts +66 -66
  51. package/src/Components/FileStore.class.ts +78 -78
  52. package/src/Components/ForEach.class.ts +97 -97
  53. package/src/Components/GPTPlugin.class.ts +70 -70
  54. package/src/Components/GenAILLM.class.ts +586 -586
  55. package/src/Components/HuggingFace.class.ts +313 -313
  56. package/src/Components/Image/imageSettings.config.ts +70 -70
  57. package/src/Components/ImageGenerator.class.ts +483 -483
  58. package/src/Components/JSONFilter.class.ts +54 -54
  59. package/src/Components/LLMAssistant.class.ts +213 -213
  60. package/src/Components/LogicAND.class.ts +28 -28
  61. package/src/Components/LogicAtLeast.class.ts +85 -85
  62. package/src/Components/LogicAtMost.class.ts +86 -86
  63. package/src/Components/LogicOR.class.ts +29 -29
  64. package/src/Components/LogicXOR.class.ts +34 -34
  65. package/src/Components/MCPClient.class.ts +137 -137
  66. package/src/Components/MemoryDeleteKeyVal.class.ts +70 -70
  67. package/src/Components/MemoryReadKeyVal.class.ts +67 -67
  68. package/src/Components/MemoryWriteKeyVal.class.ts +62 -62
  69. package/src/Components/MemoryWriteObject.class.ts +97 -97
  70. package/src/Components/MultimodalLLM.class.ts +128 -128
  71. package/src/Components/OpenAPI.class.ts +72 -72
  72. package/src/Components/PromptGenerator.class.ts +122 -122
  73. package/src/Components/ScrapflyWebScrape.class.ts +183 -183
  74. package/src/Components/ServerlessCode.class.ts +123 -123
  75. package/src/Components/TavilyWebSearch.class.ts +103 -103
  76. package/src/Components/VisionLLM.class.ts +104 -104
  77. package/src/Components/ZapierAction.class.ts +127 -127
  78. package/src/Components/index.ts +97 -97
  79. package/src/Core/AgentProcess.helper.ts +240 -240
  80. package/src/Core/Connector.class.ts +123 -123
  81. package/src/Core/ConnectorsService.ts +197 -197
  82. package/src/Core/DummyConnector.ts +49 -49
  83. package/src/Core/HookService.ts +105 -105
  84. package/src/Core/SmythRuntime.class.ts +241 -241
  85. package/src/Core/SystemEvents.ts +16 -16
  86. package/src/Core/boot.ts +56 -56
  87. package/src/config.ts +15 -15
  88. package/src/constants.ts +126 -126
  89. package/src/data/hugging-face.params.json +579 -579
  90. package/src/helpers/AWSLambdaCode.helper.ts +624 -624
  91. package/src/helpers/BinaryInput.helper.ts +331 -331
  92. package/src/helpers/Conversation.helper.ts +1157 -1157
  93. package/src/helpers/ECMASandbox.helper.ts +64 -64
  94. package/src/helpers/JsonContent.helper.ts +97 -97
  95. package/src/helpers/LocalCache.helper.ts +97 -97
  96. package/src/helpers/Log.helper.ts +274 -274
  97. package/src/helpers/OpenApiParser.helper.ts +150 -150
  98. package/src/helpers/S3Cache.helper.ts +147 -147
  99. package/src/helpers/SmythURI.helper.ts +5 -5
  100. package/src/helpers/Sysconfig.helper.ts +95 -95
  101. package/src/helpers/TemplateString.helper.ts +243 -243
  102. package/src/helpers/TypeChecker.helper.ts +329 -329
  103. package/src/index.ts +3 -3
  104. package/src/index.ts.bak +3 -3
  105. package/src/subsystems/AgentManager/Agent.class.ts +1114 -1114
  106. package/src/subsystems/AgentManager/Agent.helper.ts +3 -3
  107. package/src/subsystems/AgentManager/AgentData.service/AgentDataConnector.ts +230 -230
  108. package/src/subsystems/AgentManager/AgentData.service/connectors/CLIAgentDataConnector.class.ts +66 -66
  109. package/src/subsystems/AgentManager/AgentData.service/connectors/LocalAgentDataConnector.class.ts +145 -145
  110. package/src/subsystems/AgentManager/AgentData.service/connectors/NullAgentData.class.ts +39 -39
  111. package/src/subsystems/AgentManager/AgentData.service/index.ts +18 -18
  112. package/src/subsystems/AgentManager/AgentLogger.class.ts +301 -301
  113. package/src/subsystems/AgentManager/AgentRequest.class.ts +51 -51
  114. package/src/subsystems/AgentManager/AgentRuntime.class.ts +557 -557
  115. package/src/subsystems/AgentManager/AgentSSE.class.ts +101 -101
  116. package/src/subsystems/AgentManager/AgentSettings.class.ts +52 -52
  117. package/src/subsystems/AgentManager/Component.service/ComponentConnector.ts +32 -32
  118. package/src/subsystems/AgentManager/Component.service/connectors/LocalComponentConnector.class.ts +60 -60
  119. package/src/subsystems/AgentManager/Component.service/index.ts +11 -11
  120. package/src/subsystems/AgentManager/EmbodimentSettings.class.ts +47 -47
  121. package/src/subsystems/AgentManager/ForkedAgent.class.ts +154 -154
  122. package/src/subsystems/AgentManager/OSResourceMonitor.ts +77 -77
  123. package/src/subsystems/ComputeManager/Code.service/CodeConnector.ts +98 -98
  124. package/src/subsystems/ComputeManager/Code.service/connectors/AWSLambdaCode.class.ts +171 -171
  125. package/src/subsystems/ComputeManager/Code.service/connectors/ECMASandbox.class.ts +131 -131
  126. package/src/subsystems/ComputeManager/Code.service/index.ts +13 -13
  127. package/src/subsystems/IO/CLI.service/CLIConnector.ts +47 -47
  128. package/src/subsystems/IO/CLI.service/index.ts +9 -9
  129. package/src/subsystems/IO/Log.service/LogConnector.ts +32 -32
  130. package/src/subsystems/IO/Log.service/connectors/ConsoleLog.class.ts +28 -28
  131. package/src/subsystems/IO/Log.service/index.ts +13 -13
  132. package/src/subsystems/IO/NKV.service/NKVConnector.ts +43 -43
  133. package/src/subsystems/IO/NKV.service/connectors/NKVLocalStorage.class.ts +234 -234
  134. package/src/subsystems/IO/NKV.service/connectors/NKVRAM.class.ts +204 -204
  135. package/src/subsystems/IO/NKV.service/connectors/NKVRedis.class.ts +182 -182
  136. package/src/subsystems/IO/NKV.service/index.ts +14 -14
  137. package/src/subsystems/IO/Router.service/RouterConnector.ts +21 -21
  138. package/src/subsystems/IO/Router.service/connectors/ExpressRouter.class.ts +48 -48
  139. package/src/subsystems/IO/Router.service/connectors/NullRouter.class.ts +40 -40
  140. package/src/subsystems/IO/Router.service/index.ts +11 -11
  141. package/src/subsystems/IO/Storage.service/SmythFS.class.ts +488 -488
  142. package/src/subsystems/IO/Storage.service/StorageConnector.ts +66 -66
  143. package/src/subsystems/IO/Storage.service/connectors/LocalStorage.class.ts +327 -327
  144. package/src/subsystems/IO/Storage.service/connectors/S3Storage.class.ts +482 -482
  145. package/src/subsystems/IO/Storage.service/index.ts +13 -13
  146. package/src/subsystems/IO/VectorDB.service/VectorDBConnector.ts +108 -108
  147. package/src/subsystems/IO/VectorDB.service/connectors/MilvusVectorDB.class.ts +465 -465
  148. package/src/subsystems/IO/VectorDB.service/connectors/PineconeVectorDB.class.ts +387 -387
  149. package/src/subsystems/IO/VectorDB.service/connectors/RAMVecrtorDB.class.ts +408 -408
  150. package/src/subsystems/IO/VectorDB.service/embed/BaseEmbedding.ts +107 -107
  151. package/src/subsystems/IO/VectorDB.service/embed/GoogleEmbedding.ts +118 -118
  152. package/src/subsystems/IO/VectorDB.service/embed/OpenAIEmbedding.ts +109 -109
  153. package/src/subsystems/IO/VectorDB.service/embed/index.ts +26 -26
  154. package/src/subsystems/IO/VectorDB.service/index.ts +14 -14
  155. package/src/subsystems/LLMManager/LLM.helper.ts +251 -251
  156. package/src/subsystems/LLMManager/LLM.inference.ts +345 -345
  157. package/src/subsystems/LLMManager/LLM.service/LLMConnector.ts +492 -492
  158. package/src/subsystems/LLMManager/LLM.service/LLMCredentials.helper.ts +171 -171
  159. package/src/subsystems/LLMManager/LLM.service/connectors/Anthropic.class.ts +666 -666
  160. package/src/subsystems/LLMManager/LLM.service/connectors/Bedrock.class.ts +407 -407
  161. package/src/subsystems/LLMManager/LLM.service/connectors/Echo.class.ts +92 -92
  162. package/src/subsystems/LLMManager/LLM.service/connectors/GoogleAI.class.ts +983 -983
  163. package/src/subsystems/LLMManager/LLM.service/connectors/Groq.class.ts +319 -319
  164. package/src/subsystems/LLMManager/LLM.service/connectors/Ollama.class.ts +361 -361
  165. package/src/subsystems/LLMManager/LLM.service/connectors/Perplexity.class.ts +257 -257
  166. package/src/subsystems/LLMManager/LLM.service/connectors/VertexAI.class.ts +430 -430
  167. package/src/subsystems/LLMManager/LLM.service/connectors/openai/OpenAIConnector.class.ts +503 -503
  168. package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/ChatCompletionsApiInterface.ts +524 -524
  169. package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/OpenAIApiInterface.ts +100 -100
  170. package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/OpenAIApiInterfaceFactory.ts +81 -81
  171. package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/ResponsesApiInterface.ts +1145 -1145
  172. package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/constants.ts +13 -13
  173. package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/index.ts +4 -4
  174. package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/utils.ts +11 -11
  175. package/src/subsystems/LLMManager/LLM.service/connectors/openai/types.ts +32 -32
  176. package/src/subsystems/LLMManager/LLM.service/connectors/xAI.class.ts +478 -478
  177. package/src/subsystems/LLMManager/LLM.service/index.ts +47 -47
  178. package/src/subsystems/LLMManager/ModelsProvider.service/ModelsProviderConnector.ts +303 -303
  179. package/src/subsystems/LLMManager/ModelsProvider.service/connectors/JSONModelsProvider.class.ts +277 -271
  180. package/src/subsystems/LLMManager/ModelsProvider.service/index.ts +11 -11
  181. package/src/subsystems/LLMManager/custom-models.ts +854 -854
  182. package/src/subsystems/LLMManager/models.ts +2540 -2540
  183. package/src/subsystems/LLMManager/paramMappings.ts +69 -69
  184. package/src/subsystems/MemoryManager/Cache.service/CacheConnector.ts +86 -86
  185. package/src/subsystems/MemoryManager/Cache.service/connectors/LocalStorageCache.class.ts +297 -297
  186. package/src/subsystems/MemoryManager/Cache.service/connectors/RAMCache.class.ts +214 -214
  187. package/src/subsystems/MemoryManager/Cache.service/connectors/RedisCache.class.ts +252 -252
  188. package/src/subsystems/MemoryManager/Cache.service/connectors/S3Cache.class.ts +373 -373
  189. package/src/subsystems/MemoryManager/Cache.service/index.ts +15 -15
  190. package/src/subsystems/MemoryManager/LLMCache.ts +72 -72
  191. package/src/subsystems/MemoryManager/LLMContext.ts +124 -124
  192. package/src/subsystems/MemoryManager/LLMMemory.service/LLMMemoryConnector.ts +26 -26
  193. package/src/subsystems/MemoryManager/RuntimeContext.ts +277 -277
  194. package/src/subsystems/Security/AccessControl/ACL.class.ts +208 -208
  195. package/src/subsystems/Security/AccessControl/AccessCandidate.class.ts +82 -82
  196. package/src/subsystems/Security/AccessControl/AccessRequest.class.ts +52 -52
  197. package/src/subsystems/Security/Account.service/AccountConnector.ts +44 -44
  198. package/src/subsystems/Security/Account.service/connectors/DummyAccount.class.ts +130 -130
  199. package/src/subsystems/Security/Account.service/connectors/JSONFileAccount.class.ts +170 -170
  200. package/src/subsystems/Security/Account.service/connectors/MySQLAccount.class.ts +76 -76
  201. package/src/subsystems/Security/Account.service/index.ts +14 -14
  202. package/src/subsystems/Security/Credentials.helper.ts +62 -62
  203. package/src/subsystems/Security/ManagedVault.service/ManagedVaultConnector.ts +38 -38
  204. package/src/subsystems/Security/ManagedVault.service/connectors/NullManagedVault.class.ts +53 -53
  205. package/src/subsystems/Security/ManagedVault.service/connectors/SecretManagerManagedVault.ts +154 -154
  206. package/src/subsystems/Security/ManagedVault.service/index.ts +12 -12
  207. package/src/subsystems/Security/SecureConnector.class.ts +110 -110
  208. package/src/subsystems/Security/Vault.service/Vault.helper.ts +30 -30
  209. package/src/subsystems/Security/Vault.service/VaultConnector.ts +29 -29
  210. package/src/subsystems/Security/Vault.service/connectors/HashicorpVault.class.ts +46 -46
  211. package/src/subsystems/Security/Vault.service/connectors/JSONFileVault.class.ts +221 -221
  212. package/src/subsystems/Security/Vault.service/connectors/NullVault.class.ts +54 -54
  213. package/src/subsystems/Security/Vault.service/connectors/SecretsManager.class.ts +140 -140
  214. package/src/subsystems/Security/Vault.service/index.ts +12 -12
  215. package/src/types/ACL.types.ts +104 -104
  216. package/src/types/AWS.types.ts +10 -10
  217. package/src/types/Agent.types.ts +61 -61
  218. package/src/types/AgentLogger.types.ts +17 -17
  219. package/src/types/Cache.types.ts +1 -1
  220. package/src/types/Common.types.ts +2 -2
  221. package/src/types/LLM.types.ts +520 -520
  222. package/src/types/Redis.types.ts +8 -8
  223. package/src/types/SRE.types.ts +64 -64
  224. package/src/types/Security.types.ts +14 -14
  225. package/src/types/Storage.types.ts +5 -5
  226. package/src/types/VectorDB.types.ts +86 -86
  227. package/src/utils/base64.utils.ts +275 -275
  228. package/src/utils/cli.utils.ts +68 -68
  229. package/src/utils/data.utils.ts +322 -322
  230. package/src/utils/date-time.utils.ts +22 -22
  231. package/src/utils/general.utils.ts +238 -238
  232. package/src/utils/index.ts +12 -12
  233. package/src/utils/lazy-client.ts +261 -261
  234. package/src/utils/numbers.utils.ts +13 -13
  235. package/src/utils/oauth.utils.ts +35 -35
  236. package/src/utils/string.utils.ts +414 -414
  237. package/src/utils/url.utils.ts +19 -19
  238. package/src/utils/validation.utils.ts +74 -74
  239. package/dist/types/subsystems/LLMManager/ModelsProvider.service/connectors/SmythModelsProvider.class.d.ts +0 -39
@@ -1,624 +1,624 @@
1
- import crypto from 'crypto';
2
- import { ConnectorService } from '@sre/Core/ConnectorsService';
3
- import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
4
- import zl from 'zip-lib';
5
- import {
6
- InvokeCommand,
7
- Runtime,
8
- LambdaClient,
9
- UpdateFunctionCodeCommand,
10
- CreateFunctionCommand,
11
- GetFunctionCommand,
12
- GetFunctionCommandOutput,
13
- InvokeCommandOutput,
14
- UpdateFunctionConfigurationCommand,
15
- } from '@aws-sdk/client-lambda';
16
- import { GetRoleCommand, CreateRoleCommand, IAMClient, GetRoleCommandOutput, CreateRoleCommandOutput } from '@aws-sdk/client-iam';
17
- import fs from 'fs';
18
- import { AWSConfig, AWSCredentials, AWSRegionConfig } from '@sre/types/AWS.types';
19
- import { VaultHelper } from '@sre/Security/Vault.service/Vault.helper';
20
- import { IAgent } from '@sre/types/Agent.types';
21
- import { SystemEvents } from '@sre/Core/SystemEvents';
22
- import * as acorn from 'acorn';
23
-
24
- export const cachePrefix = 'serverless_code';
25
- export const cacheTTL = 60 * 60 * 24 * 16; // 16 days
26
- const PER_SECOND_COST = 0.0001;
27
-
28
- export function getLambdaFunctionName(agentId: string, componentId: string) {
29
- return `${agentId}-${componentId}`;
30
- }
31
-
32
- export function generateCodeHash(code_body: string, codeInputs: string[], envVariables: string[]) {
33
- const bodyHash = getSanitizeCodeHash(code_body);
34
- const inputsHash = getSanitizeCodeHash(JSON.stringify(codeInputs));
35
- const envVariablesHash = getSanitizeCodeHash(JSON.stringify(envVariables));
36
- return `body-${bodyHash}__inputs-${inputsHash}__env-${envVariablesHash}`;
37
- }
38
-
39
- export function getSanitizeCodeHash(rawCode: string) {
40
- const code = replaceVaultKeysTemplateVars(rawCode, {});
41
- let output = '';
42
- let isSingleQuote = false;
43
- let isDoubleQuote = false;
44
- let isTemplateLiteral = false;
45
- let isRegex = false;
46
- let isComment = false;
47
- let prevChar = '';
48
-
49
- for (let i = 0; i < code.length; i++) {
50
- let char = code[i];
51
- let nextChar = code[i + 1];
52
-
53
- // Toggle string flags
54
- if (char === "'" && !isDoubleQuote && !isTemplateLiteral && prevChar !== '\\') isSingleQuote = !isSingleQuote;
55
- if (char === '"' && !isSingleQuote && !isTemplateLiteral && prevChar !== '\\') isDoubleQuote = !isDoubleQuote;
56
- if (char === '`' && !isSingleQuote && !isDoubleQuote && prevChar !== '\\') isTemplateLiteral = !isTemplateLiteral;
57
-
58
- // Handle regex cases
59
- if (char === '/' && nextChar === '/' && !isSingleQuote && !isDoubleQuote && !isTemplateLiteral && !isRegex) {
60
- isComment = true; // Single-line comment
61
- }
62
- if (char === '/' && nextChar === '*' && !isSingleQuote && !isDoubleQuote && !isTemplateLiteral) {
63
- isComment = true; // Multi-line comment start
64
- }
65
- if (char === '*' && nextChar === '/' && isComment) {
66
- isComment = false; // Multi-line comment end
67
- i++; // Skip ending slash
68
- continue;
69
- }
70
- if (char === '\n' && isComment) {
71
- isComment = false; // End single-line comment
72
- }
73
-
74
- if (!isComment) {
75
- output += char;
76
- }
77
- prevChar = char;
78
- }
79
-
80
- return crypto.createHash('md5').update(output.replace(/\s+/g, ' ').trim()).digest('hex');
81
- }
82
-
83
- export async function getDeployedCodeHash(agentId: string, componentId: string) {
84
- const redisCache = ConnectorService.getCacheConnector();
85
- const cachedCodeHash = await redisCache.user(AccessCandidate.agent(agentId)).get(`${cachePrefix}_${agentId}-${componentId}`);
86
- return cachedCodeHash;
87
- }
88
-
89
- export async function setDeployedCodeHash(agentId: string, componentId: string, codeHash: string) {
90
- const redisCache = ConnectorService.getCacheConnector();
91
- await redisCache.user(AccessCandidate.agent(agentId)).set(`${cachePrefix}_${agentId}-${componentId}`, codeHash, null, null, cacheTTL);
92
- }
93
-
94
- function replaceVaultKeysTemplateVars(code: string, envVariables: Record<string, string>) {
95
- const regex = /\{\{KEY\((.*?)\)\}\}/g;
96
- return code.replaceAll(regex, (match, p1) => `process.env.${p1}`);
97
- }
98
-
99
- export function generateLambdaCode(code: string, parameters: string[], envVariables: Record<string, string>) {
100
- const codeWithEnvVariables = envVariables && Object.keys(envVariables).length ? replaceVaultKeysTemplateVars(code, envVariables) : code;
101
- const lambdaCode = `
102
- ${codeWithEnvVariables}
103
- export const handler = async (event, context) => {
104
- try {
105
- context.callbackWaitsForEmptyEventLoop = false;
106
- let startTime = Date.now();
107
-
108
- ${parameters && parameters.length ? parameters.map((variable) => `const ${variable} = event.${variable};`).join('\n') : ''}
109
- const result = await main(${parameters.join(', ')});
110
-
111
- let endTime = Date.now();
112
- return {
113
- result,
114
- executionTime: endTime - startTime
115
- }
116
- } catch (e) {
117
- throw e;
118
- }
119
- };`;
120
- return lambdaCode;
121
- }
122
-
123
- export async function zipCode(directory: string) {
124
- return new Promise((resolve, reject) => {
125
- zl.archiveFolder(directory, `${directory}.zip`).then(
126
- function () {
127
- resolve(`${directory}.zip`);
128
- },
129
- function (err) {
130
- reject(err);
131
- }
132
- );
133
- });
134
- }
135
-
136
- export async function createOrUpdateLambdaFunction(functionName, zipFilePath, awsConfigs, envVariables: Record<string, string>) {
137
- const client = new LambdaClient({
138
- region: awsConfigs.region,
139
- credentials: {
140
- accessKeyId: awsConfigs.accessKeyId,
141
- secretAccessKey: awsConfigs.secretAccessKey,
142
- },
143
- });
144
- const functionContent = fs.readFileSync(zipFilePath);
145
-
146
- try {
147
- // Check if the function exists
148
- const exisitingFunction = await getDeployedFunction(functionName, awsConfigs);
149
- if (exisitingFunction) {
150
- if (exisitingFunction.status === 'InProgress') {
151
- await verifyFunctionDeploymentStatus(functionName, client);
152
- }
153
- // Update function code if it exists
154
- const updateCodeParams = {
155
- FunctionName: functionName,
156
- ZipFile: functionContent,
157
- };
158
- const updateFunctionCodeCommand = new UpdateFunctionCodeCommand(updateCodeParams);
159
- await client.send(updateFunctionCodeCommand);
160
- await verifyFunctionDeploymentStatus(functionName, client);
161
-
162
- if (envVariables && Object.keys(envVariables).length) {
163
- await updateLambdaFunctionConfiguration(client, functionName, envVariables);
164
- await verifyFunctionDeploymentStatus(functionName, client);
165
- }
166
- } else {
167
- // Create function if it does not exist
168
- let roleArn = '';
169
- // check if the role exists
170
- try {
171
- const iamClient = new IAMClient({
172
- region: awsConfigs.region,
173
- credentials: { accessKeyId: awsConfigs.accessKeyId, secretAccessKey: awsConfigs.secretAccessKey },
174
- });
175
- const getRoleCommand = new GetRoleCommand({ RoleName: `smyth-${functionName}-role` });
176
- const roleResponse: GetRoleCommandOutput = await iamClient.send(getRoleCommand);
177
- roleArn = roleResponse.Role.Arn;
178
- } catch (error) {
179
- if (error.name === 'NoSuchEntityException') {
180
- // create role
181
- const iamClient = new IAMClient({
182
- region: awsConfigs.region,
183
- credentials: { accessKeyId: awsConfigs.accessKeyId, secretAccessKey: awsConfigs.secretAccessKey },
184
- });
185
- const createRoleCommand = new CreateRoleCommand({
186
- RoleName: `smyth-${functionName}-role`,
187
- AssumeRolePolicyDocument: getLambdaRolePolicy(),
188
- });
189
- const roleResponse: CreateRoleCommandOutput = await iamClient.send(createRoleCommand);
190
-
191
- await waitForRoleDeploymentStatus(`smyth-${functionName}-role`, iamClient);
192
- roleArn = roleResponse.Role.Arn;
193
- } else {
194
- throw error;
195
- }
196
- }
197
-
198
- const functionParams = {
199
- Code: { ZipFile: functionContent },
200
- FunctionName: functionName,
201
- Handler: 'index.handler',
202
- Role: roleArn,
203
- Runtime: Runtime.nodejs18x,
204
- Layers: [],
205
- Timeout: 900,
206
- Tags: {
207
- 'auto-delete': 'true',
208
- },
209
- MemorySize: 256,
210
- ...(envVariables && Object.keys(envVariables).length ? { Environment: { Variables: envVariables } } : {}),
211
- };
212
- // Retry mechanism for Lambda function creation with exponential backoff
213
- await createLambdaFunction(client, functionParams);
214
- await verifyFunctionDeploymentStatus(functionName, client);
215
- }
216
- } catch (error) {
217
- throw error;
218
- }
219
- }
220
-
221
- function updateLambdaFunctionConfiguration(client: LambdaClient, functionName: string, envVariables: Record<string, string>) {
222
- const updateFunctionConfigurationParams = {
223
- FunctionName: functionName,
224
- Environment: {
225
- Variables: envVariables,
226
- },
227
- };
228
- const updateFunctionConfigurationCommand = new UpdateFunctionConfigurationCommand(updateFunctionConfigurationParams);
229
- return client.send(updateFunctionConfigurationCommand);
230
- }
231
-
232
- async function createLambdaFunction(client: LambdaClient, functionParams: any, maxRetries: number = 5): Promise<void> {
233
- let lastError: Error | null = null;
234
-
235
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
236
- try {
237
- const functionCreateCommand = new CreateFunctionCommand(functionParams);
238
- await client.send(functionCreateCommand);
239
- return; // Success, exit the retry loop
240
- } catch (error) {
241
- lastError = error;
242
- // Check if this is a role trust policy error
243
- if (error?.message?.includes('cannot be assumed by Lambda')) {
244
-
245
- if (attempt < maxRetries) {
246
- // Exponential backoff: 2^attempt seconds (2, 4, 8, 16, 32 seconds)
247
- const waitTime = Math.pow(2, attempt) * 1000;
248
- await new Promise(resolve => setTimeout(resolve, waitTime));
249
- continue;
250
- }
251
- }
252
-
253
- // For other errors or if we've exhausted retries, throw immediately
254
- throw error;
255
- }
256
- }
257
-
258
- // If we get here, all retries failed
259
- throw lastError || new Error('Lambda function creation failed after all retry attempts');
260
- }
261
-
262
- export async function waitForRoleDeploymentStatus(roleName, client): Promise<boolean> {
263
- return new Promise((resolve, reject) => {
264
- const interval = setInterval(async () => {
265
- const getRoleCommand = new GetRoleCommand({ RoleName: roleName });
266
- const roleResponse = await client.send(getRoleCommand);
267
-
268
- // Check if role exists and has assume role policy document
269
- if (roleResponse.Role && roleResponse.Role.AssumeRolePolicyDocument) {
270
- clearInterval(interval);
271
- setTimeout(() => resolve(true), 2000);
272
- return;
273
- }
274
- }, 2000); // Check every 2 seconds
275
- });
276
- }
277
-
278
- export async function verifyFunctionDeploymentStatus(functionName, client): Promise<boolean> {
279
- return new Promise((resolve, reject) => {
280
- try {
281
- let interval = setInterval(async () => {
282
- const getFunctionCommand = new GetFunctionCommand({ FunctionName: functionName });
283
- const lambdaResponse = await client.send(getFunctionCommand);
284
-
285
- if (lambdaResponse.Configuration.LastUpdateStatus === 'Successful') {
286
- clearInterval(interval);
287
- return resolve(true);
288
- }
289
- }, 5000);
290
- } catch (error) {
291
- return false;
292
- }
293
- });
294
- }
295
-
296
- export function getLambdaRolePolicy() {
297
- return JSON.stringify({
298
- Version: '2012-10-17',
299
- Statement: [
300
- {
301
- Effect: 'Allow',
302
- Principal: {
303
- Service: 'lambda.amazonaws.com',
304
- },
305
- Action: 'sts:AssumeRole',
306
- },
307
- ],
308
- });
309
- }
310
-
311
- export async function updateDeployedCodeTTL(agentId: string, componentId: string, ttl: number) {
312
- const redisCache = ConnectorService.getCacheConnector();
313
- await redisCache.user(AccessCandidate.agent(agentId)).updateTTL(`${cachePrefix}_${agentId}-${componentId}`, ttl);
314
- }
315
-
316
- export async function invokeLambdaFunction(
317
- functionName: string,
318
- inputs: { [key: string]: any },
319
- awsCredentials: AWSCredentials & AWSRegionConfig
320
- ): Promise<any> {
321
- try {
322
- const client = new LambdaClient({
323
- region: awsCredentials.region as string,
324
- ...(awsCredentials.accessKeyId && {
325
- credentials: {
326
- accessKeyId: awsCredentials.accessKeyId as string,
327
- secretAccessKey: awsCredentials.secretAccessKey as string,
328
- },
329
- }),
330
- });
331
-
332
- const invokeCommand = new InvokeCommand({
333
- FunctionName: functionName,
334
- Payload: new TextEncoder().encode(`${JSON.stringify(inputs)}`),
335
- InvocationType: 'RequestResponse',
336
- });
337
-
338
- const response: InvokeCommandOutput = await client.send(invokeCommand);
339
- if (response.FunctionError) {
340
- throw new Error(new TextDecoder().decode(response.Payload));
341
- }
342
- return new TextDecoder().decode(response.Payload);
343
- } catch (error) {
344
- throw error;
345
- }
346
- }
347
-
348
- export async function getDeployedFunction(functionName: string, awsConfigs: AWSCredentials & AWSRegionConfig) {
349
- try {
350
- const client = new LambdaClient({
351
- region: awsConfigs.region as string,
352
- credentials: {
353
- accessKeyId: awsConfigs.accessKeyId as string,
354
- secretAccessKey: awsConfigs.secretAccessKey as string,
355
- },
356
- });
357
- const getFunctionCommand = new GetFunctionCommand({ FunctionName: functionName });
358
- const lambdaResponse: GetFunctionCommandOutput = await client.send(getFunctionCommand);
359
- return {
360
- status: lambdaResponse.Configuration.LastUpdateStatus,
361
- functionName: lambdaResponse.Configuration.FunctionName,
362
- functionVersion: lambdaResponse.Configuration.Version,
363
- updatedAt: lambdaResponse.Configuration.LastModified,
364
- role: lambdaResponse.Configuration.Role,
365
- runtime: lambdaResponse.Configuration.Runtime,
366
- version: lambdaResponse.Configuration.Version,
367
- };
368
- } catch (error) {
369
- return null;
370
- }
371
- }
372
-
373
- export async function getLambdaCredentials(agent: IAgent, config: any): Promise<AWSConfig & { isUserProvidedKeys: boolean }> {
374
- let awsAccessKeyId = null;
375
- let awsSecretAccessKey = null;
376
- let awsRegion = null;
377
- let userProvidedKeys = false;
378
- if (config.data.accessKeyId && config.data.secretAccessKey && config.data.region && config.data.use_own_keys) {
379
- userProvidedKeys = true;
380
- [awsAccessKeyId, awsSecretAccessKey] = await Promise.all([
381
- VaultHelper.getTeamKey(extractKeyFromTemplateVar(config.data.accessKeyId), agent?.teamId),
382
- VaultHelper.getTeamKey(extractKeyFromTemplateVar(config.data.secretAccessKey), agent?.teamId),
383
- ]);
384
- awsRegion = config.data.region;
385
- }
386
- const awsCredentials = {
387
- accessKeyId: awsAccessKeyId,
388
- secretAccessKey: awsSecretAccessKey,
389
- region: awsRegion,
390
- isUserProvidedKeys: userProvidedKeys,
391
- };
392
- return awsCredentials;
393
- }
394
-
395
- export function calculateExecutionCost(executionTime: number) {
396
- // executionTime in milliseconds
397
- const cost = (executionTime / 1000) * Number(PER_SECOND_COST);
398
- return cost;
399
- }
400
-
401
- export function extractKeyFromTemplateVar(input: string) {
402
- const regex = /\{\{KEY\((.*?)\)\}\}/;
403
- const match = input.match(regex);
404
- return match ? match[1] : input;
405
- }
406
-
407
- export function reportUsage({ cost, agentId, teamId }: { cost: number; agentId: string; teamId: string }) {
408
- SystemEvents.emit('USAGE:API', {
409
- sourceId: 'api:serverless_code.smyth',
410
- cost,
411
- agentId,
412
- teamId,
413
- });
414
- }
415
-
416
- export function validateAsyncMainFunction(rawCode: string): { isValid: boolean; error?: string; parameters?: string[]; dependencies?: string[] } {
417
- try {
418
- const code = replaceVaultKeysTemplateVars(rawCode.trim(), {});
419
- // Parse the code using acorn
420
- const ast = acorn.parse(code, {
421
- ecmaVersion: 'latest',
422
- sourceType: 'module',
423
- });
424
-
425
- // Extract library imports
426
- const libraries = new Set<string>();
427
- function extractPackageName(modulePath: string): string {
428
- if (modulePath.startsWith('@')) {
429
- // Handle scoped packages (e.g., @babel/core)
430
- return modulePath.split('/').slice(0, 2).join('/');
431
- }
432
- return modulePath.split('/')[0]; // Extract the first part (main package)
433
- }
434
-
435
- function processNodeForImports(node: any): void {
436
- if (!node) return;
437
-
438
- // Handle ImportDeclaration (ES6 imports)
439
- if (node.type === 'ImportDeclaration') {
440
- const modulePath = node.source.value;
441
- if (modulePath && !modulePath.startsWith('.') && !modulePath.startsWith('/')) {
442
- // Skip relative imports and absolute paths
443
- libraries.add(extractPackageName(modulePath));
444
- }
445
- }
446
-
447
- // Handle CallExpression (require() calls)
448
- if (
449
- node.type === 'CallExpression' &&
450
- node.callee.type === 'Identifier' &&
451
- node.callee.name === 'require' &&
452
- node.arguments.length > 0 &&
453
- node.arguments[0].type === 'Literal'
454
- ) {
455
- const modulePath = node.arguments[0].value;
456
- if (modulePath && !modulePath.startsWith('.') && !modulePath.startsWith('/')) {
457
- libraries.add(extractPackageName(modulePath));
458
- }
459
- }
460
-
461
- // Handle dynamic import() calls
462
- if (
463
- node.type === 'CallExpression' &&
464
- node.callee.type === 'Import' &&
465
- node.arguments.length > 0 &&
466
- node.arguments[0].type === 'Literal'
467
- ) {
468
- const modulePath = node.arguments[0].value;
469
- if (modulePath && !modulePath.startsWith('.') && !modulePath.startsWith('/')) {
470
- libraries.add(extractPackageName(modulePath));
471
- }
472
- }
473
-
474
- // Recursively process child nodes
475
- for (const key in node) {
476
- if (node[key] && typeof node[key] === 'object') {
477
- if (Array.isArray(node[key])) {
478
- (node[key] as any[]).forEach(processNodeForImports);
479
- } else {
480
- processNodeForImports(node[key]);
481
- }
482
- }
483
- }
484
- }
485
-
486
- // Extract dependencies from the entire AST
487
- processNodeForImports(ast);
488
- const dependencies = Array.from(libraries) as string[];
489
-
490
- // Check if there's a function declaration or function expression named 'main' at the root level
491
- let hasAsyncMain = false;
492
- let hasMain = false;
493
- let mainParameters: string[] = [];
494
-
495
- for (const node of ast.body) {
496
- if (node.type === 'FunctionDeclaration') {
497
- if (node.id?.name === 'main') {
498
- hasMain = true;
499
- if (node.async) {
500
- hasAsyncMain = true;
501
- mainParameters = extractParameters(node.params);
502
- break;
503
- }
504
- }
505
- } else if (node.type === 'VariableDeclaration') {
506
- // Check for const/let/var main = async function() or const/let/var main = async () =>
507
- for (const declarator of node.declarations) {
508
- if (declarator.id.type === 'Identifier' && declarator.id.name === 'main') {
509
- hasMain = true;
510
- if (declarator.init) {
511
- if (declarator.init.type === 'FunctionExpression' && declarator.init.async) {
512
- hasAsyncMain = true;
513
- mainParameters = extractParameters(declarator.init.params);
514
- break;
515
- } else if (declarator.init.type === 'ArrowFunctionExpression' && declarator.init.async) {
516
- hasAsyncMain = true;
517
- mainParameters = extractParameters(declarator.init.params);
518
- break;
519
- }
520
- }
521
- }
522
- }
523
- } else if (node.type === 'ExpressionStatement' && node.expression.type === 'AssignmentExpression') {
524
- // Check for main = async function() or main = async () =>
525
- if (node.expression.left.type === 'Identifier' && node.expression.left.name === 'main') {
526
- hasMain = true;
527
- const right = node.expression.right;
528
- if ((right.type === 'FunctionExpression' || right.type === 'ArrowFunctionExpression') && right.async) {
529
- hasAsyncMain = true;
530
- mainParameters = extractParameters(right.params);
531
- break;
532
- }
533
- }
534
- }
535
- }
536
-
537
- if (!hasMain) {
538
- return {
539
- isValid: false,
540
- error: 'No main function found at root level',
541
- dependencies,
542
- };
543
- }
544
-
545
- if (!hasAsyncMain) {
546
- return {
547
- isValid: false,
548
- error: 'Main function exists but is not async',
549
- dependencies,
550
- };
551
- }
552
-
553
- return { isValid: true, parameters: mainParameters, dependencies };
554
- } catch (error) {
555
- return {
556
- isValid: false,
557
- error: `Failed to parse code: ${error.message}`,
558
- };
559
- }
560
- }
561
-
562
- function extractParameters(params: any[]): string[] {
563
- return params.map((param: any): string => {
564
- if (param.type === 'Identifier') {
565
- return param.name;
566
- } else if (param.type === 'AssignmentPattern' && param.left.type === 'Identifier') {
567
- return param.left.name;
568
- } else if (param.type === 'RestElement' && param.argument.type === 'Identifier') {
569
- return param.argument.name;
570
- } else if (param.type === 'ObjectPattern') {
571
- // For destructured objects, return the object name or a placeholder
572
- return param.name || '[object]';
573
- } else if (param.type === 'ArrayPattern') {
574
- // For destructured arrays, return a placeholder
575
- return '[array]';
576
- }
577
- return '[unknown]';
578
- });
579
- }
580
-
581
- export function generateCodeFromLegacyComponent(code_body: string, code_imports: string, codeInputs: string[]) {
582
- const code = `
583
- ${code_imports}
584
- async function main(${codeInputs.join(', ')}) {
585
- ${code_body}
586
- }
587
- `;
588
- return code;
589
- }
590
-
591
- export function extractAllKeyNamesFromTemplateVars(input: string): string[] {
592
- const regex = /\{\{KEY\((.*?)\)\}\}/g;
593
- const matches = [];
594
- let match;
595
- while ((match = regex.exec(input)) !== null) {
596
- if (match[1]) {
597
- matches.push(match[1]);
598
- }
599
- }
600
- return matches;
601
- }
602
-
603
- async function fetchVaultSecret(keyName: string, agentTeamId: string): Promise<{ value: string; key: string }> {
604
- const vaultSecret = await VaultHelper.getAgentKey(keyName, agentTeamId);
605
- return {
606
- value: vaultSecret,
607
- key: keyName,
608
- };
609
- }
610
-
611
- export async function getCurrentEnvironmentVariables(agentTeamId: string, code: string): Promise<Record<string, string>> {
612
- const allKeyNames = extractAllKeyNamesFromTemplateVars(code);
613
- const envVariables: Record<string, string> = {};
614
- const vaultSecrets = await Promise.all(allKeyNames.map((keyName) => fetchVaultSecret(keyName, agentTeamId)));
615
- vaultSecrets.forEach((secret) => {
616
- envVariables[secret.key] = secret.value;
617
- });
618
- return envVariables;
619
- }
620
-
621
- export function getSortedObjectValues(obj: Record<string, string>): string[] {
622
- const sortedKeys = Object.keys(obj).sort();
623
- return sortedKeys.map((key) => obj[key]);
624
- }
1
+ import crypto from 'crypto';
2
+ import { ConnectorService } from '@sre/Core/ConnectorsService';
3
+ import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
4
+ import zl from 'zip-lib';
5
+ import {
6
+ InvokeCommand,
7
+ Runtime,
8
+ LambdaClient,
9
+ UpdateFunctionCodeCommand,
10
+ CreateFunctionCommand,
11
+ GetFunctionCommand,
12
+ GetFunctionCommandOutput,
13
+ InvokeCommandOutput,
14
+ UpdateFunctionConfigurationCommand,
15
+ } from '@aws-sdk/client-lambda';
16
+ import { GetRoleCommand, CreateRoleCommand, IAMClient, GetRoleCommandOutput, CreateRoleCommandOutput } from '@aws-sdk/client-iam';
17
+ import fs from 'fs';
18
+ import { AWSConfig, AWSCredentials, AWSRegionConfig } from '@sre/types/AWS.types';
19
+ import { VaultHelper } from '@sre/Security/Vault.service/Vault.helper';
20
+ import { IAgent } from '@sre/types/Agent.types';
21
+ import { SystemEvents } from '@sre/Core/SystemEvents';
22
+ import * as acorn from 'acorn';
23
+
24
+ export const cachePrefix = 'serverless_code';
25
+ export const cacheTTL = 60 * 60 * 24 * 16; // 16 days
26
+ const PER_SECOND_COST = 0.0001;
27
+
28
+ export function getLambdaFunctionName(agentId: string, componentId: string) {
29
+ return `${agentId}-${componentId}`;
30
+ }
31
+
32
+ export function generateCodeHash(code_body: string, codeInputs: string[], envVariables: string[]) {
33
+ const bodyHash = getSanitizeCodeHash(code_body);
34
+ const inputsHash = getSanitizeCodeHash(JSON.stringify(codeInputs));
35
+ const envVariablesHash = getSanitizeCodeHash(JSON.stringify(envVariables));
36
+ return `body-${bodyHash}__inputs-${inputsHash}__env-${envVariablesHash}`;
37
+ }
38
+
39
+ export function getSanitizeCodeHash(rawCode: string) {
40
+ const code = replaceVaultKeysTemplateVars(rawCode, {});
41
+ let output = '';
42
+ let isSingleQuote = false;
43
+ let isDoubleQuote = false;
44
+ let isTemplateLiteral = false;
45
+ let isRegex = false;
46
+ let isComment = false;
47
+ let prevChar = '';
48
+
49
+ for (let i = 0; i < code.length; i++) {
50
+ let char = code[i];
51
+ let nextChar = code[i + 1];
52
+
53
+ // Toggle string flags
54
+ if (char === "'" && !isDoubleQuote && !isTemplateLiteral && prevChar !== '\\') isSingleQuote = !isSingleQuote;
55
+ if (char === '"' && !isSingleQuote && !isTemplateLiteral && prevChar !== '\\') isDoubleQuote = !isDoubleQuote;
56
+ if (char === '`' && !isSingleQuote && !isDoubleQuote && prevChar !== '\\') isTemplateLiteral = !isTemplateLiteral;
57
+
58
+ // Handle regex cases
59
+ if (char === '/' && nextChar === '/' && !isSingleQuote && !isDoubleQuote && !isTemplateLiteral && !isRegex) {
60
+ isComment = true; // Single-line comment
61
+ }
62
+ if (char === '/' && nextChar === '*' && !isSingleQuote && !isDoubleQuote && !isTemplateLiteral) {
63
+ isComment = true; // Multi-line comment start
64
+ }
65
+ if (char === '*' && nextChar === '/' && isComment) {
66
+ isComment = false; // Multi-line comment end
67
+ i++; // Skip ending slash
68
+ continue;
69
+ }
70
+ if (char === '\n' && isComment) {
71
+ isComment = false; // End single-line comment
72
+ }
73
+
74
+ if (!isComment) {
75
+ output += char;
76
+ }
77
+ prevChar = char;
78
+ }
79
+
80
+ return crypto.createHash('md5').update(output.replace(/\s+/g, ' ').trim()).digest('hex');
81
+ }
82
+
83
+ export async function getDeployedCodeHash(agentId: string, componentId: string) {
84
+ const redisCache = ConnectorService.getCacheConnector();
85
+ const cachedCodeHash = await redisCache.user(AccessCandidate.agent(agentId)).get(`${cachePrefix}_${agentId}-${componentId}`);
86
+ return cachedCodeHash;
87
+ }
88
+
89
+ export async function setDeployedCodeHash(agentId: string, componentId: string, codeHash: string) {
90
+ const redisCache = ConnectorService.getCacheConnector();
91
+ await redisCache.user(AccessCandidate.agent(agentId)).set(`${cachePrefix}_${agentId}-${componentId}`, codeHash, null, null, cacheTTL);
92
+ }
93
+
94
+ function replaceVaultKeysTemplateVars(code: string, envVariables: Record<string, string>) {
95
+ const regex = /\{\{KEY\((.*?)\)\}\}/g;
96
+ return code.replaceAll(regex, (match, p1) => `process.env.${p1}`);
97
+ }
98
+
99
+ export function generateLambdaCode(code: string, parameters: string[], envVariables: Record<string, string>) {
100
+ const codeWithEnvVariables = envVariables && Object.keys(envVariables).length ? replaceVaultKeysTemplateVars(code, envVariables) : code;
101
+ const lambdaCode = `
102
+ ${codeWithEnvVariables}
103
+ export const handler = async (event, context) => {
104
+ try {
105
+ context.callbackWaitsForEmptyEventLoop = false;
106
+ let startTime = Date.now();
107
+
108
+ ${parameters && parameters.length ? parameters.map((variable) => `const ${variable} = event.${variable};`).join('\n') : ''}
109
+ const result = await main(${parameters.join(', ')});
110
+
111
+ let endTime = Date.now();
112
+ return {
113
+ result,
114
+ executionTime: endTime - startTime
115
+ }
116
+ } catch (e) {
117
+ throw e;
118
+ }
119
+ };`;
120
+ return lambdaCode;
121
+ }
122
+
123
+ export async function zipCode(directory: string) {
124
+ return new Promise((resolve, reject) => {
125
+ zl.archiveFolder(directory, `${directory}.zip`).then(
126
+ function () {
127
+ resolve(`${directory}.zip`);
128
+ },
129
+ function (err) {
130
+ reject(err);
131
+ }
132
+ );
133
+ });
134
+ }
135
+
136
+ export async function createOrUpdateLambdaFunction(functionName, zipFilePath, awsConfigs, envVariables: Record<string, string>) {
137
+ const client = new LambdaClient({
138
+ region: awsConfigs.region,
139
+ credentials: {
140
+ accessKeyId: awsConfigs.accessKeyId,
141
+ secretAccessKey: awsConfigs.secretAccessKey,
142
+ },
143
+ });
144
+ const functionContent = fs.readFileSync(zipFilePath);
145
+
146
+ try {
147
+ // Check if the function exists
148
+ const exisitingFunction = await getDeployedFunction(functionName, awsConfigs);
149
+ if (exisitingFunction) {
150
+ if (exisitingFunction.status === 'InProgress') {
151
+ await verifyFunctionDeploymentStatus(functionName, client);
152
+ }
153
+ // Update function code if it exists
154
+ const updateCodeParams = {
155
+ FunctionName: functionName,
156
+ ZipFile: functionContent,
157
+ };
158
+ const updateFunctionCodeCommand = new UpdateFunctionCodeCommand(updateCodeParams);
159
+ await client.send(updateFunctionCodeCommand);
160
+ await verifyFunctionDeploymentStatus(functionName, client);
161
+
162
+ if (envVariables && Object.keys(envVariables).length) {
163
+ await updateLambdaFunctionConfiguration(client, functionName, envVariables);
164
+ await verifyFunctionDeploymentStatus(functionName, client);
165
+ }
166
+ } else {
167
+ // Create function if it does not exist
168
+ let roleArn = '';
169
+ // check if the role exists
170
+ try {
171
+ const iamClient = new IAMClient({
172
+ region: awsConfigs.region,
173
+ credentials: { accessKeyId: awsConfigs.accessKeyId, secretAccessKey: awsConfigs.secretAccessKey },
174
+ });
175
+ const getRoleCommand = new GetRoleCommand({ RoleName: `smyth-${functionName}-role` });
176
+ const roleResponse: GetRoleCommandOutput = await iamClient.send(getRoleCommand);
177
+ roleArn = roleResponse.Role.Arn;
178
+ } catch (error) {
179
+ if (error.name === 'NoSuchEntityException') {
180
+ // create role
181
+ const iamClient = new IAMClient({
182
+ region: awsConfigs.region,
183
+ credentials: { accessKeyId: awsConfigs.accessKeyId, secretAccessKey: awsConfigs.secretAccessKey },
184
+ });
185
+ const createRoleCommand = new CreateRoleCommand({
186
+ RoleName: `smyth-${functionName}-role`,
187
+ AssumeRolePolicyDocument: getLambdaRolePolicy(),
188
+ });
189
+ const roleResponse: CreateRoleCommandOutput = await iamClient.send(createRoleCommand);
190
+
191
+ await waitForRoleDeploymentStatus(`smyth-${functionName}-role`, iamClient);
192
+ roleArn = roleResponse.Role.Arn;
193
+ } else {
194
+ throw error;
195
+ }
196
+ }
197
+
198
+ const functionParams = {
199
+ Code: { ZipFile: functionContent },
200
+ FunctionName: functionName,
201
+ Handler: 'index.handler',
202
+ Role: roleArn,
203
+ Runtime: Runtime.nodejs18x,
204
+ Layers: [],
205
+ Timeout: 900,
206
+ Tags: {
207
+ 'auto-delete': 'true',
208
+ },
209
+ MemorySize: 256,
210
+ ...(envVariables && Object.keys(envVariables).length ? { Environment: { Variables: envVariables } } : {}),
211
+ };
212
+ // Retry mechanism for Lambda function creation with exponential backoff
213
+ await createLambdaFunction(client, functionParams);
214
+ await verifyFunctionDeploymentStatus(functionName, client);
215
+ }
216
+ } catch (error) {
217
+ throw error;
218
+ }
219
+ }
220
+
221
+ function updateLambdaFunctionConfiguration(client: LambdaClient, functionName: string, envVariables: Record<string, string>) {
222
+ const updateFunctionConfigurationParams = {
223
+ FunctionName: functionName,
224
+ Environment: {
225
+ Variables: envVariables,
226
+ },
227
+ };
228
+ const updateFunctionConfigurationCommand = new UpdateFunctionConfigurationCommand(updateFunctionConfigurationParams);
229
+ return client.send(updateFunctionConfigurationCommand);
230
+ }
231
+
232
+ async function createLambdaFunction(client: LambdaClient, functionParams: any, maxRetries: number = 5): Promise<void> {
233
+ let lastError: Error | null = null;
234
+
235
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
236
+ try {
237
+ const functionCreateCommand = new CreateFunctionCommand(functionParams);
238
+ await client.send(functionCreateCommand);
239
+ return; // Success, exit the retry loop
240
+ } catch (error) {
241
+ lastError = error;
242
+ // Check if this is a role trust policy error
243
+ if (error?.message?.includes('cannot be assumed by Lambda')) {
244
+
245
+ if (attempt < maxRetries) {
246
+ // Exponential backoff: 2^attempt seconds (2, 4, 8, 16, 32 seconds)
247
+ const waitTime = Math.pow(2, attempt) * 1000;
248
+ await new Promise(resolve => setTimeout(resolve, waitTime));
249
+ continue;
250
+ }
251
+ }
252
+
253
+ // For other errors or if we've exhausted retries, throw immediately
254
+ throw error;
255
+ }
256
+ }
257
+
258
+ // If we get here, all retries failed
259
+ throw lastError || new Error('Lambda function creation failed after all retry attempts');
260
+ }
261
+
262
+ export async function waitForRoleDeploymentStatus(roleName, client): Promise<boolean> {
263
+ return new Promise((resolve, reject) => {
264
+ const interval = setInterval(async () => {
265
+ const getRoleCommand = new GetRoleCommand({ RoleName: roleName });
266
+ const roleResponse = await client.send(getRoleCommand);
267
+
268
+ // Check if role exists and has assume role policy document
269
+ if (roleResponse.Role && roleResponse.Role.AssumeRolePolicyDocument) {
270
+ clearInterval(interval);
271
+ setTimeout(() => resolve(true), 2000);
272
+ return;
273
+ }
274
+ }, 2000); // Check every 2 seconds
275
+ });
276
+ }
277
+
278
+ export async function verifyFunctionDeploymentStatus(functionName, client): Promise<boolean> {
279
+ return new Promise((resolve, reject) => {
280
+ try {
281
+ let interval = setInterval(async () => {
282
+ const getFunctionCommand = new GetFunctionCommand({ FunctionName: functionName });
283
+ const lambdaResponse = await client.send(getFunctionCommand);
284
+
285
+ if (lambdaResponse.Configuration.LastUpdateStatus === 'Successful') {
286
+ clearInterval(interval);
287
+ return resolve(true);
288
+ }
289
+ }, 5000);
290
+ } catch (error) {
291
+ return false;
292
+ }
293
+ });
294
+ }
295
+
296
+ export function getLambdaRolePolicy() {
297
+ return JSON.stringify({
298
+ Version: '2012-10-17',
299
+ Statement: [
300
+ {
301
+ Effect: 'Allow',
302
+ Principal: {
303
+ Service: 'lambda.amazonaws.com',
304
+ },
305
+ Action: 'sts:AssumeRole',
306
+ },
307
+ ],
308
+ });
309
+ }
310
+
311
+ export async function updateDeployedCodeTTL(agentId: string, componentId: string, ttl: number) {
312
+ const redisCache = ConnectorService.getCacheConnector();
313
+ await redisCache.user(AccessCandidate.agent(agentId)).updateTTL(`${cachePrefix}_${agentId}-${componentId}`, ttl);
314
+ }
315
+
316
+ export async function invokeLambdaFunction(
317
+ functionName: string,
318
+ inputs: { [key: string]: any },
319
+ awsCredentials: AWSCredentials & AWSRegionConfig
320
+ ): Promise<any> {
321
+ try {
322
+ const client = new LambdaClient({
323
+ region: awsCredentials.region as string,
324
+ ...(awsCredentials.accessKeyId && {
325
+ credentials: {
326
+ accessKeyId: awsCredentials.accessKeyId as string,
327
+ secretAccessKey: awsCredentials.secretAccessKey as string,
328
+ },
329
+ }),
330
+ });
331
+
332
+ const invokeCommand = new InvokeCommand({
333
+ FunctionName: functionName,
334
+ Payload: new TextEncoder().encode(`${JSON.stringify(inputs)}`),
335
+ InvocationType: 'RequestResponse',
336
+ });
337
+
338
+ const response: InvokeCommandOutput = await client.send(invokeCommand);
339
+ if (response.FunctionError) {
340
+ throw new Error(new TextDecoder().decode(response.Payload));
341
+ }
342
+ return new TextDecoder().decode(response.Payload);
343
+ } catch (error) {
344
+ throw error;
345
+ }
346
+ }
347
+
348
+ export async function getDeployedFunction(functionName: string, awsConfigs: AWSCredentials & AWSRegionConfig) {
349
+ try {
350
+ const client = new LambdaClient({
351
+ region: awsConfigs.region as string,
352
+ credentials: {
353
+ accessKeyId: awsConfigs.accessKeyId as string,
354
+ secretAccessKey: awsConfigs.secretAccessKey as string,
355
+ },
356
+ });
357
+ const getFunctionCommand = new GetFunctionCommand({ FunctionName: functionName });
358
+ const lambdaResponse: GetFunctionCommandOutput = await client.send(getFunctionCommand);
359
+ return {
360
+ status: lambdaResponse.Configuration.LastUpdateStatus,
361
+ functionName: lambdaResponse.Configuration.FunctionName,
362
+ functionVersion: lambdaResponse.Configuration.Version,
363
+ updatedAt: lambdaResponse.Configuration.LastModified,
364
+ role: lambdaResponse.Configuration.Role,
365
+ runtime: lambdaResponse.Configuration.Runtime,
366
+ version: lambdaResponse.Configuration.Version,
367
+ };
368
+ } catch (error) {
369
+ return null;
370
+ }
371
+ }
372
+
373
+ export async function getLambdaCredentials(agent: IAgent, config: any): Promise<AWSConfig & { isUserProvidedKeys: boolean }> {
374
+ let awsAccessKeyId = null;
375
+ let awsSecretAccessKey = null;
376
+ let awsRegion = null;
377
+ let userProvidedKeys = false;
378
+ if (config.data.accessKeyId && config.data.secretAccessKey && config.data.region && config.data.use_own_keys) {
379
+ userProvidedKeys = true;
380
+ [awsAccessKeyId, awsSecretAccessKey] = await Promise.all([
381
+ VaultHelper.getTeamKey(extractKeyFromTemplateVar(config.data.accessKeyId), agent?.teamId),
382
+ VaultHelper.getTeamKey(extractKeyFromTemplateVar(config.data.secretAccessKey), agent?.teamId),
383
+ ]);
384
+ awsRegion = config.data.region;
385
+ }
386
+ const awsCredentials = {
387
+ accessKeyId: awsAccessKeyId,
388
+ secretAccessKey: awsSecretAccessKey,
389
+ region: awsRegion,
390
+ isUserProvidedKeys: userProvidedKeys,
391
+ };
392
+ return awsCredentials;
393
+ }
394
+
395
+ export function calculateExecutionCost(executionTime: number) {
396
+ // executionTime in milliseconds
397
+ const cost = (executionTime / 1000) * Number(PER_SECOND_COST);
398
+ return cost;
399
+ }
400
+
401
+ export function extractKeyFromTemplateVar(input: string) {
402
+ const regex = /\{\{KEY\((.*?)\)\}\}/;
403
+ const match = input.match(regex);
404
+ return match ? match[1] : input;
405
+ }
406
+
407
+ export function reportUsage({ cost, agentId, teamId }: { cost: number; agentId: string; teamId: string }) {
408
+ SystemEvents.emit('USAGE:API', {
409
+ sourceId: 'api:serverless_code.smyth',
410
+ cost,
411
+ agentId,
412
+ teamId,
413
+ });
414
+ }
415
+
416
+ export function validateAsyncMainFunction(rawCode: string): { isValid: boolean; error?: string; parameters?: string[]; dependencies?: string[] } {
417
+ try {
418
+ const code = replaceVaultKeysTemplateVars(rawCode.trim(), {});
419
+ // Parse the code using acorn
420
+ const ast = acorn.parse(code, {
421
+ ecmaVersion: 'latest',
422
+ sourceType: 'module',
423
+ });
424
+
425
+ // Extract library imports
426
+ const libraries = new Set<string>();
427
+ function extractPackageName(modulePath: string): string {
428
+ if (modulePath.startsWith('@')) {
429
+ // Handle scoped packages (e.g., @babel/core)
430
+ return modulePath.split('/').slice(0, 2).join('/');
431
+ }
432
+ return modulePath.split('/')[0]; // Extract the first part (main package)
433
+ }
434
+
435
+ function processNodeForImports(node: any): void {
436
+ if (!node) return;
437
+
438
+ // Handle ImportDeclaration (ES6 imports)
439
+ if (node.type === 'ImportDeclaration') {
440
+ const modulePath = node.source.value;
441
+ if (modulePath && !modulePath.startsWith('.') && !modulePath.startsWith('/')) {
442
+ // Skip relative imports and absolute paths
443
+ libraries.add(extractPackageName(modulePath));
444
+ }
445
+ }
446
+
447
+ // Handle CallExpression (require() calls)
448
+ if (
449
+ node.type === 'CallExpression' &&
450
+ node.callee.type === 'Identifier' &&
451
+ node.callee.name === 'require' &&
452
+ node.arguments.length > 0 &&
453
+ node.arguments[0].type === 'Literal'
454
+ ) {
455
+ const modulePath = node.arguments[0].value;
456
+ if (modulePath && !modulePath.startsWith('.') && !modulePath.startsWith('/')) {
457
+ libraries.add(extractPackageName(modulePath));
458
+ }
459
+ }
460
+
461
+ // Handle dynamic import() calls
462
+ if (
463
+ node.type === 'CallExpression' &&
464
+ node.callee.type === 'Import' &&
465
+ node.arguments.length > 0 &&
466
+ node.arguments[0].type === 'Literal'
467
+ ) {
468
+ const modulePath = node.arguments[0].value;
469
+ if (modulePath && !modulePath.startsWith('.') && !modulePath.startsWith('/')) {
470
+ libraries.add(extractPackageName(modulePath));
471
+ }
472
+ }
473
+
474
+ // Recursively process child nodes
475
+ for (const key in node) {
476
+ if (node[key] && typeof node[key] === 'object') {
477
+ if (Array.isArray(node[key])) {
478
+ (node[key] as any[]).forEach(processNodeForImports);
479
+ } else {
480
+ processNodeForImports(node[key]);
481
+ }
482
+ }
483
+ }
484
+ }
485
+
486
+ // Extract dependencies from the entire AST
487
+ processNodeForImports(ast);
488
+ const dependencies = Array.from(libraries) as string[];
489
+
490
+ // Check if there's a function declaration or function expression named 'main' at the root level
491
+ let hasAsyncMain = false;
492
+ let hasMain = false;
493
+ let mainParameters: string[] = [];
494
+
495
+ for (const node of ast.body) {
496
+ if (node.type === 'FunctionDeclaration') {
497
+ if (node.id?.name === 'main') {
498
+ hasMain = true;
499
+ if (node.async) {
500
+ hasAsyncMain = true;
501
+ mainParameters = extractParameters(node.params);
502
+ break;
503
+ }
504
+ }
505
+ } else if (node.type === 'VariableDeclaration') {
506
+ // Check for const/let/var main = async function() or const/let/var main = async () =>
507
+ for (const declarator of node.declarations) {
508
+ if (declarator.id.type === 'Identifier' && declarator.id.name === 'main') {
509
+ hasMain = true;
510
+ if (declarator.init) {
511
+ if (declarator.init.type === 'FunctionExpression' && declarator.init.async) {
512
+ hasAsyncMain = true;
513
+ mainParameters = extractParameters(declarator.init.params);
514
+ break;
515
+ } else if (declarator.init.type === 'ArrowFunctionExpression' && declarator.init.async) {
516
+ hasAsyncMain = true;
517
+ mainParameters = extractParameters(declarator.init.params);
518
+ break;
519
+ }
520
+ }
521
+ }
522
+ }
523
+ } else if (node.type === 'ExpressionStatement' && node.expression.type === 'AssignmentExpression') {
524
+ // Check for main = async function() or main = async () =>
525
+ if (node.expression.left.type === 'Identifier' && node.expression.left.name === 'main') {
526
+ hasMain = true;
527
+ const right = node.expression.right;
528
+ if ((right.type === 'FunctionExpression' || right.type === 'ArrowFunctionExpression') && right.async) {
529
+ hasAsyncMain = true;
530
+ mainParameters = extractParameters(right.params);
531
+ break;
532
+ }
533
+ }
534
+ }
535
+ }
536
+
537
+ if (!hasMain) {
538
+ return {
539
+ isValid: false,
540
+ error: 'No main function found at root level',
541
+ dependencies,
542
+ };
543
+ }
544
+
545
+ if (!hasAsyncMain) {
546
+ return {
547
+ isValid: false,
548
+ error: 'Main function exists but is not async',
549
+ dependencies,
550
+ };
551
+ }
552
+
553
+ return { isValid: true, parameters: mainParameters, dependencies };
554
+ } catch (error) {
555
+ return {
556
+ isValid: false,
557
+ error: `Failed to parse code: ${error.message}`,
558
+ };
559
+ }
560
+ }
561
+
562
+ function extractParameters(params: any[]): string[] {
563
+ return params.map((param: any): string => {
564
+ if (param.type === 'Identifier') {
565
+ return param.name;
566
+ } else if (param.type === 'AssignmentPattern' && param.left.type === 'Identifier') {
567
+ return param.left.name;
568
+ } else if (param.type === 'RestElement' && param.argument.type === 'Identifier') {
569
+ return param.argument.name;
570
+ } else if (param.type === 'ObjectPattern') {
571
+ // For destructured objects, return the object name or a placeholder
572
+ return param.name || '[object]';
573
+ } else if (param.type === 'ArrayPattern') {
574
+ // For destructured arrays, return a placeholder
575
+ return '[array]';
576
+ }
577
+ return '[unknown]';
578
+ });
579
+ }
580
+
581
+ export function generateCodeFromLegacyComponent(code_body: string, code_imports: string, codeInputs: string[]) {
582
+ const code = `
583
+ ${code_imports}
584
+ async function main(${codeInputs.join(', ')}) {
585
+ ${code_body}
586
+ }
587
+ `;
588
+ return code;
589
+ }
590
+
591
+ export function extractAllKeyNamesFromTemplateVars(input: string): string[] {
592
+ const regex = /\{\{KEY\((.*?)\)\}\}/g;
593
+ const matches = [];
594
+ let match;
595
+ while ((match = regex.exec(input)) !== null) {
596
+ if (match[1]) {
597
+ matches.push(match[1]);
598
+ }
599
+ }
600
+ return matches;
601
+ }
602
+
603
+ async function fetchVaultSecret(keyName: string, agentTeamId: string): Promise<{ value: string; key: string }> {
604
+ const vaultSecret = await VaultHelper.getAgentKey(keyName, agentTeamId);
605
+ return {
606
+ value: vaultSecret,
607
+ key: keyName,
608
+ };
609
+ }
610
+
611
+ export async function getCurrentEnvironmentVariables(agentTeamId: string, code: string): Promise<Record<string, string>> {
612
+ const allKeyNames = extractAllKeyNamesFromTemplateVars(code);
613
+ const envVariables: Record<string, string> = {};
614
+ const vaultSecrets = await Promise.all(allKeyNames.map((keyName) => fetchVaultSecret(keyName, agentTeamId)));
615
+ vaultSecrets.forEach((secret) => {
616
+ envVariables[secret.key] = secret.value;
617
+ });
618
+ return envVariables;
619
+ }
620
+
621
+ export function getSortedObjectValues(obj: Record<string, string>): string[] {
622
+ const sortedKeys = Object.keys(obj).sort();
623
+ return sortedKeys.map((key) => obj[key]);
624
+ }