@smythos/sre 1.6.1 → 1.6.8

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