@smythos/sre 1.5.1 → 1.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/LICENSE +18 -0
  2. package/dist/index.js +22329 -4
  3. package/dist/index.js.map +1 -1
  4. package/dist/types/subsystems/IO/VectorDB.service/connectors/PineconeVectorDB.class.d.ts +2 -2
  5. package/dist/types/subsystems/IO/VectorDB.service/embed/BaseEmbedding.d.ts +11 -7
  6. package/dist/types/types/VectorDB.types.d.ts +13 -11
  7. package/package.json +102 -127
  8. package/src/Components/APICall/APICall.class.ts +155 -0
  9. package/src/Components/APICall/AccessTokenManager.ts +130 -0
  10. package/src/Components/APICall/ArrayBufferResponse.helper.ts +58 -0
  11. package/src/Components/APICall/OAuth.helper.ts +294 -0
  12. package/src/Components/APICall/mimeTypeCategories.ts +46 -0
  13. package/src/Components/APICall/parseData.ts +167 -0
  14. package/src/Components/APICall/parseHeaders.ts +41 -0
  15. package/src/Components/APICall/parseProxy.ts +68 -0
  16. package/src/Components/APICall/parseUrl.ts +91 -0
  17. package/src/Components/APIEndpoint.class.ts +234 -0
  18. package/src/Components/APIOutput.class.ts +58 -0
  19. package/src/Components/AgentPlugin.class.ts +102 -0
  20. package/src/Components/Async.class.ts +155 -0
  21. package/src/Components/Await.class.ts +90 -0
  22. package/src/Components/Classifier.class.ts +158 -0
  23. package/src/Components/Component.class.ts +94 -0
  24. package/src/Components/ComponentHost.class.ts +38 -0
  25. package/src/Components/DataSourceCleaner.class.ts +92 -0
  26. package/src/Components/DataSourceIndexer.class.ts +181 -0
  27. package/src/Components/DataSourceLookup.class.ts +141 -0
  28. package/src/Components/FEncDec.class.ts +29 -0
  29. package/src/Components/FHash.class.ts +33 -0
  30. package/src/Components/FSign.class.ts +80 -0
  31. package/src/Components/FSleep.class.ts +25 -0
  32. package/src/Components/FTimestamp.class.ts +25 -0
  33. package/src/Components/FileStore.class.ts +75 -0
  34. package/src/Components/ForEach.class.ts +97 -0
  35. package/src/Components/GPTPlugin.class.ts +70 -0
  36. package/src/Components/GenAILLM.class.ts +395 -0
  37. package/src/Components/HuggingFace.class.ts +314 -0
  38. package/src/Components/Image/imageSettings.config.ts +70 -0
  39. package/src/Components/ImageGenerator.class.ts +407 -0
  40. package/src/Components/JSONFilter.class.ts +54 -0
  41. package/src/Components/LLMAssistant.class.ts +213 -0
  42. package/src/Components/LogicAND.class.ts +28 -0
  43. package/src/Components/LogicAtLeast.class.ts +85 -0
  44. package/src/Components/LogicAtMost.class.ts +86 -0
  45. package/src/Components/LogicOR.class.ts +29 -0
  46. package/src/Components/LogicXOR.class.ts +34 -0
  47. package/src/Components/MCPClient.class.ts +112 -0
  48. package/src/Components/PromptGenerator.class.ts +122 -0
  49. package/src/Components/ScrapflyWebScrape.class.ts +159 -0
  50. package/src/Components/TavilyWebSearch.class.ts +98 -0
  51. package/src/Components/index.ts +77 -0
  52. package/src/Core/AgentProcess.helper.ts +240 -0
  53. package/src/Core/Connector.class.ts +123 -0
  54. package/src/Core/ConnectorsService.ts +192 -0
  55. package/src/Core/DummyConnector.ts +49 -0
  56. package/src/Core/HookService.ts +105 -0
  57. package/src/Core/SmythRuntime.class.ts +292 -0
  58. package/src/Core/SystemEvents.ts +15 -0
  59. package/src/Core/boot.ts +55 -0
  60. package/src/config.ts +15 -0
  61. package/src/constants.ts +125 -0
  62. package/src/data/hugging-face.params.json +580 -0
  63. package/src/helpers/BinaryInput.helper.ts +324 -0
  64. package/src/helpers/Conversation.helper.ts +1094 -0
  65. package/src/helpers/JsonContent.helper.ts +97 -0
  66. package/src/helpers/LocalCache.helper.ts +97 -0
  67. package/src/helpers/Log.helper.ts +234 -0
  68. package/src/helpers/OpenApiParser.helper.ts +150 -0
  69. package/src/helpers/S3Cache.helper.ts +129 -0
  70. package/src/helpers/SmythURI.helper.ts +5 -0
  71. package/src/helpers/TemplateString.helper.ts +243 -0
  72. package/src/helpers/TypeChecker.helper.ts +329 -0
  73. package/src/index.ts +179 -0
  74. package/src/index.ts.bak +179 -0
  75. package/src/subsystems/AgentManager/Agent.class.ts +1108 -0
  76. package/src/subsystems/AgentManager/Agent.helper.ts +3 -0
  77. package/src/subsystems/AgentManager/AgentData.service/AgentDataConnector.ts +230 -0
  78. package/src/subsystems/AgentManager/AgentData.service/connectors/CLIAgentDataConnector.class.ts +66 -0
  79. package/src/subsystems/AgentManager/AgentData.service/connectors/LocalAgentDataConnector.class.ts +142 -0
  80. package/src/subsystems/AgentManager/AgentData.service/connectors/NullAgentData.class.ts +39 -0
  81. package/src/subsystems/AgentManager/AgentData.service/index.ts +18 -0
  82. package/src/subsystems/AgentManager/AgentLogger.class.ts +297 -0
  83. package/src/subsystems/AgentManager/AgentRequest.class.ts +51 -0
  84. package/src/subsystems/AgentManager/AgentRuntime.class.ts +559 -0
  85. package/src/subsystems/AgentManager/AgentSSE.class.ts +101 -0
  86. package/src/subsystems/AgentManager/AgentSettings.class.ts +52 -0
  87. package/src/subsystems/AgentManager/Component.service/ComponentConnector.ts +32 -0
  88. package/src/subsystems/AgentManager/Component.service/connectors/LocalComponentConnector.class.ts +59 -0
  89. package/src/subsystems/AgentManager/Component.service/index.ts +11 -0
  90. package/src/subsystems/AgentManager/EmbodimentSettings.class.ts +47 -0
  91. package/src/subsystems/AgentManager/ForkedAgent.class.ts +153 -0
  92. package/src/subsystems/AgentManager/OSResourceMonitor.ts +77 -0
  93. package/src/subsystems/ComputeManager/Code.service/CodeConnector.ts +99 -0
  94. package/src/subsystems/ComputeManager/Code.service/connectors/AWSLambdaCode.class.ts +63 -0
  95. package/src/subsystems/ComputeManager/Code.service/index.ts +11 -0
  96. package/src/subsystems/IO/CLI.service/CLIConnector.ts +47 -0
  97. package/src/subsystems/IO/CLI.service/index.ts +9 -0
  98. package/src/subsystems/IO/Log.service/LogConnector.ts +32 -0
  99. package/src/subsystems/IO/Log.service/connectors/ConsoleLog.class.ts +28 -0
  100. package/src/subsystems/IO/Log.service/index.ts +13 -0
  101. package/src/subsystems/IO/NKV.service/NKVConnector.ts +41 -0
  102. package/src/subsystems/IO/NKV.service/connectors/NKVRAM.class.ts +204 -0
  103. package/src/subsystems/IO/NKV.service/connectors/NKVRedis.class.ts +182 -0
  104. package/src/subsystems/IO/NKV.service/index.ts +12 -0
  105. package/src/subsystems/IO/Router.service/RouterConnector.ts +21 -0
  106. package/src/subsystems/IO/Router.service/connectors/ExpressRouter.class.ts +48 -0
  107. package/src/subsystems/IO/Router.service/connectors/NullRouter.class.ts +40 -0
  108. package/src/subsystems/IO/Router.service/index.ts +11 -0
  109. package/src/subsystems/IO/Storage.service/SmythFS.class.ts +472 -0
  110. package/src/subsystems/IO/Storage.service/StorageConnector.ts +66 -0
  111. package/src/subsystems/IO/Storage.service/connectors/LocalStorage.class.ts +305 -0
  112. package/src/subsystems/IO/Storage.service/connectors/S3Storage.class.ts +418 -0
  113. package/src/subsystems/IO/Storage.service/index.ts +13 -0
  114. package/src/subsystems/IO/VectorDB.service/VectorDBConnector.ts +108 -0
  115. package/src/subsystems/IO/VectorDB.service/connectors/MilvusVectorDB.class.ts +454 -0
  116. package/src/subsystems/IO/VectorDB.service/connectors/PineconeVectorDB.class.ts +384 -0
  117. package/src/subsystems/IO/VectorDB.service/connectors/RAMVecrtorDB.class.ts +421 -0
  118. package/src/subsystems/IO/VectorDB.service/embed/BaseEmbedding.ts +107 -0
  119. package/src/subsystems/IO/VectorDB.service/embed/OpenAIEmbedding.ts +109 -0
  120. package/src/subsystems/IO/VectorDB.service/embed/index.ts +21 -0
  121. package/src/subsystems/IO/VectorDB.service/index.ts +14 -0
  122. package/src/subsystems/LLMManager/LLM.helper.ts +221 -0
  123. package/src/subsystems/LLMManager/LLM.inference.ts +335 -0
  124. package/src/subsystems/LLMManager/LLM.service/LLMConnector.ts +375 -0
  125. package/src/subsystems/LLMManager/LLM.service/LLMCredentials.helper.ts +145 -0
  126. package/src/subsystems/LLMManager/LLM.service/connectors/Anthropic.class.ts +632 -0
  127. package/src/subsystems/LLMManager/LLM.service/connectors/Bedrock.class.ts +405 -0
  128. package/src/subsystems/LLMManager/LLM.service/connectors/Echo.class.ts +81 -0
  129. package/src/subsystems/LLMManager/LLM.service/connectors/GoogleAI.class.ts +689 -0
  130. package/src/subsystems/LLMManager/LLM.service/connectors/Groq.class.ts +257 -0
  131. package/src/subsystems/LLMManager/LLM.service/connectors/OpenAI.class.ts +848 -0
  132. package/src/subsystems/LLMManager/LLM.service/connectors/Perplexity.class.ts +255 -0
  133. package/src/subsystems/LLMManager/LLM.service/connectors/VertexAI.class.ts +193 -0
  134. package/src/subsystems/LLMManager/LLM.service/index.ts +43 -0
  135. package/src/subsystems/LLMManager/ModelsProvider.service/ModelsProviderConnector.ts +281 -0
  136. package/src/subsystems/LLMManager/ModelsProvider.service/connectors/SmythModelsProvider.class.ts +229 -0
  137. package/src/subsystems/LLMManager/ModelsProvider.service/index.ts +11 -0
  138. package/src/subsystems/LLMManager/custom-models.ts +854 -0
  139. package/src/subsystems/LLMManager/models.ts +2539 -0
  140. package/src/subsystems/LLMManager/paramMappings.ts +69 -0
  141. package/src/subsystems/MemoryManager/Cache.service/CacheConnector.ts +86 -0
  142. package/src/subsystems/MemoryManager/Cache.service/connectors/LocalStorageCache.class.ts +297 -0
  143. package/src/subsystems/MemoryManager/Cache.service/connectors/RAMCache.class.ts +201 -0
  144. package/src/subsystems/MemoryManager/Cache.service/connectors/RedisCache.class.ts +252 -0
  145. package/src/subsystems/MemoryManager/Cache.service/connectors/S3Cache.class.ts +373 -0
  146. package/src/subsystems/MemoryManager/Cache.service/index.ts +15 -0
  147. package/src/subsystems/MemoryManager/LLMCache.ts +72 -0
  148. package/src/subsystems/MemoryManager/LLMContext.ts +125 -0
  149. package/src/subsystems/MemoryManager/RuntimeContext.ts +249 -0
  150. package/src/subsystems/Security/AccessControl/ACL.class.ts +208 -0
  151. package/src/subsystems/Security/AccessControl/AccessCandidate.class.ts +76 -0
  152. package/src/subsystems/Security/AccessControl/AccessRequest.class.ts +52 -0
  153. package/src/subsystems/Security/Account.service/AccountConnector.ts +41 -0
  154. package/src/subsystems/Security/Account.service/connectors/AWSAccount.class.ts +76 -0
  155. package/src/subsystems/Security/Account.service/connectors/DummyAccount.class.ts +130 -0
  156. package/src/subsystems/Security/Account.service/connectors/JSONFileAccount.class.ts +159 -0
  157. package/src/subsystems/Security/Account.service/index.ts +14 -0
  158. package/src/subsystems/Security/Credentials.helper.ts +62 -0
  159. package/src/subsystems/Security/ManagedVault.service/ManagedVaultConnector.ts +34 -0
  160. package/src/subsystems/Security/ManagedVault.service/connectors/NullManagedVault.class.ts +57 -0
  161. package/src/subsystems/Security/ManagedVault.service/connectors/SecretManagerManagedVault.ts +154 -0
  162. package/src/subsystems/Security/ManagedVault.service/index.ts +12 -0
  163. package/src/subsystems/Security/SecureConnector.class.ts +110 -0
  164. package/src/subsystems/Security/Vault.service/Vault.helper.ts +30 -0
  165. package/src/subsystems/Security/Vault.service/VaultConnector.ts +26 -0
  166. package/src/subsystems/Security/Vault.service/connectors/HashicorpVault.class.ts +46 -0
  167. package/src/subsystems/Security/Vault.service/connectors/JSONFileVault.class.ts +166 -0
  168. package/src/subsystems/Security/Vault.service/connectors/NullVault.class.ts +54 -0
  169. package/src/subsystems/Security/Vault.service/connectors/SecretsManager.class.ts +140 -0
  170. package/src/subsystems/Security/Vault.service/index.ts +12 -0
  171. package/src/types/ACL.types.ts +104 -0
  172. package/src/types/AWS.types.ts +9 -0
  173. package/src/types/Agent.types.ts +61 -0
  174. package/src/types/AgentLogger.types.ts +17 -0
  175. package/src/types/Cache.types.ts +1 -0
  176. package/src/types/Common.types.ts +3 -0
  177. package/src/types/LLM.types.ts +419 -0
  178. package/src/types/Redis.types.ts +8 -0
  179. package/src/types/SRE.types.ts +64 -0
  180. package/src/types/Security.types.ts +18 -0
  181. package/src/types/Storage.types.ts +5 -0
  182. package/src/types/VectorDB.types.ts +86 -0
  183. package/src/utils/base64.utils.ts +275 -0
  184. package/src/utils/cli.utils.ts +68 -0
  185. package/src/utils/data.utils.ts +263 -0
  186. package/src/utils/date-time.utils.ts +22 -0
  187. package/src/utils/general.utils.ts +238 -0
  188. package/src/utils/index.ts +12 -0
  189. package/src/utils/numbers.utils.ts +13 -0
  190. package/src/utils/oauth.utils.ts +35 -0
  191. package/src/utils/string.utils.ts +414 -0
  192. package/src/utils/url.utils.ts +19 -0
  193. package/src/utils/validation.utils.ts +74 -0
@@ -0,0 +1,1094 @@
1
+ import { AgentProcess } from '@sre/Core/AgentProcess.helper';
2
+ import { ConnectorService } from '@sre/Core/ConnectorsService';
3
+ import { Logger } from '@sre/helpers/Log.helper';
4
+ import { LLMInference } from '@sre/LLMManager/LLM.inference';
5
+ import { LLMContext } from '@sre/MemoryManager/LLMContext';
6
+ import { TAgentProcessParams } from '@sre/types/Agent.types';
7
+ import { ILLMContextStore, TLLMEvent, TLLMModel, ToolData } from '@sre/types/LLM.types';
8
+ import { isUrl } from '@sre/utils/data.utils';
9
+ import { processWithConcurrencyLimit, uid } from '@sre/utils/general.utils';
10
+ import axios, { AxiosRequestConfig } from 'axios';
11
+ import EventEmitter from 'events';
12
+ import { JSONContent } from './JsonContent.helper';
13
+ import { OpenAPIParser } from './OpenApiParser.helper';
14
+ import { Match, TemplateString } from './TemplateString.helper';
15
+ import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
16
+ import { delay } from '@sre/utils/date-time.utils';
17
+ import { EventSource, FetchLike } from 'eventsource';
18
+ import { hookAsyncWithContext } from '@sre/Core/HookService';
19
+ import { DEFAULT_TEAM_ID } from '@sre/types/ACL.types';
20
+ import { randomUUID } from 'crypto';
21
+ import * as acorn from 'acorn';
22
+
23
+ const console = Logger('ConversationHelper');
24
+ type FunctionDeclaration = {
25
+ name: string;
26
+ description: string;
27
+ properties: Record<string, any>;
28
+ requiredFields: string[];
29
+ };
30
+ type ToolParams = {
31
+ type: string;
32
+ endpoint: string;
33
+ args: Record<string, any>;
34
+ method: string;
35
+ baseUrl: string;
36
+ headers?: Record<string, string>;
37
+ agentCallback?: (data: any) => void;
38
+ };
39
+
40
+ //TODO: handle authentication
41
+ export class Conversation extends EventEmitter {
42
+ private _agentId: string = '';
43
+ private _systemPrompt;
44
+ private userDefinedSystemPrompt: string = '';
45
+ public toolChoice: string = 'auto';
46
+ public get systemPrompt() {
47
+ return this._systemPrompt;
48
+ }
49
+ public set systemPrompt(systemPrompt) {
50
+ this._systemPrompt = systemPrompt;
51
+ if (this._context) this._context.systemPrompt = systemPrompt;
52
+ }
53
+ public assistantName;
54
+
55
+ private _reqMethods;
56
+ private _toolsConfig;
57
+ private _endpoints;
58
+ private _baseUrl;
59
+
60
+ private _status = '';
61
+ private _currentWaitPromise;
62
+
63
+ private _llmContextStore: ILLMContextStore;
64
+ private _context: LLMContext;
65
+
66
+ private _maxContextSize = 1024 * 128;
67
+ private _maxOutputTokens = 1024 * 8;
68
+ private _teamId: string = undefined;
69
+ private _agentVersion: string = undefined;
70
+ public agentData: any;
71
+
72
+ public get context() {
73
+ return this._context;
74
+ }
75
+
76
+ private _lastError;
77
+ private _spec;
78
+ private _customToolsDeclarations: FunctionDeclaration[] = [];
79
+ private _customToolsHandlers: Record<string, (args: Record<string, any>) => Promise<any>> = {};
80
+ public stop = false;
81
+ public set spec(specSource) {
82
+ this.ready.then(() => {
83
+ this._status = '';
84
+ this.loadSpecFromSource(specSource).then(async (spec) => {
85
+ if (!spec) {
86
+ this._status = 'error';
87
+ this.emit('error', 'Invalid OpenAPI specification data format');
88
+ throw new Error('Invalid OpenAPI specification data format');
89
+ }
90
+ this._spec = spec;
91
+
92
+ // teamId is required to load custom LLMs, we must assign it before updateModel()
93
+ await this.assignTeamIdFromAgentId(this._agentId);
94
+
95
+ await this.updateModel(this._model);
96
+ this._status = 'ready';
97
+ });
98
+ });
99
+ }
100
+
101
+ public set model(model: string | TLLMModel) {
102
+ this.ready.then(async () => {
103
+ this._status = '';
104
+ await this.updateModel(model);
105
+ this._status = 'ready';
106
+ });
107
+ }
108
+ public get model() {
109
+ return this._model;
110
+ }
111
+
112
+ constructor(
113
+ private _model: string | TLLMModel,
114
+ private _specSource?: string | Record<string, any>,
115
+ private _settings?: {
116
+ maxContextSize?: number;
117
+ maxOutputTokens?: number;
118
+ systemPrompt?: string;
119
+ toolChoice?: string;
120
+ store?: ILLMContextStore;
121
+ experimentalCache?: boolean;
122
+ toolsStrategy?: (toolsConfig) => any;
123
+ agentId?: string;
124
+ agentVersion?: string;
125
+ }
126
+ ) {
127
+ //TODO: handle loading previous session (messages)
128
+ super();
129
+
130
+ //this event listener avoids unhandled errors that can cause crashes
131
+ this.on('error', (error) => {
132
+ this._lastError = error;
133
+ console.warn('Conversation Error: ', error?.message);
134
+ });
135
+ if (_settings?.maxContextSize) this._maxContextSize = _settings.maxContextSize;
136
+ if (_settings?.maxOutputTokens) this._maxOutputTokens = _settings.maxOutputTokens;
137
+ if (_settings?.systemPrompt) {
138
+ this.userDefinedSystemPrompt = _settings.systemPrompt;
139
+ }
140
+ if (_settings?.toolChoice) {
141
+ this.toolChoice = _settings.toolChoice;
142
+ }
143
+
144
+ if (_settings?.store) {
145
+ this._llmContextStore = _settings.store;
146
+ }
147
+
148
+ this._agentVersion = _settings?.agentVersion;
149
+
150
+ (async () => {
151
+ if (_specSource) {
152
+ this.loadSpecFromSource(_specSource)
153
+ .then(async (spec) => {
154
+ if (!spec) {
155
+ this._status = 'error';
156
+ this.emit('error', 'Unable to parse OpenAPI specifications');
157
+ throw new Error('Invalid OpenAPI specification data format');
158
+ }
159
+ this._spec = spec;
160
+
161
+ if (!this._agentId && _settings?.agentId) this._agentId = _settings.agentId;
162
+ if (!this._agentId) this._agentId = 'FAKE_AGENT_ID'; //We use a fake agent ID to avoid ACL check errors
163
+
164
+ // teamId is required to load custom LLMs, we must assign it before updateModel()
165
+ await this.assignTeamIdFromAgentId(this._agentId);
166
+
167
+ await this.updateModel(this._model);
168
+
169
+ this._status = 'ready';
170
+ })
171
+ .catch((error) => {
172
+ this._status = 'error';
173
+ this.emit('error', error);
174
+ });
175
+ } else {
176
+ await this.updateModel(this._model);
177
+ this._status = 'ready';
178
+ }
179
+ })();
180
+ }
181
+
182
+ public get ready() {
183
+ if (this._currentWaitPromise) return this._currentWaitPromise;
184
+ this._currentWaitPromise = new Promise((resolve, reject) => {
185
+ if (this._status) {
186
+ return resolve(this._status);
187
+ }
188
+
189
+ const maxWaitTime = 30000;
190
+ let waitTime = 0;
191
+ const interval = 100;
192
+
193
+ const wait = setInterval(() => {
194
+ if (this._status) {
195
+ clearInterval(wait);
196
+ return resolve(this._status);
197
+ } else {
198
+ waitTime += interval;
199
+ if (waitTime >= maxWaitTime) {
200
+ clearInterval(wait);
201
+ return reject('Timeout: Failed to prepare data');
202
+ }
203
+ }
204
+ }, interval);
205
+ });
206
+
207
+ return this._currentWaitPromise;
208
+ }
209
+
210
+ //TODO : handle attachments
211
+ @hookAsyncWithContext('Conversation.prompt', async (instance: Conversation) => {
212
+ await instance.ready;
213
+
214
+ return {
215
+ teamId: instance._teamId,
216
+ agentId: instance._agentId,
217
+ model: instance._model,
218
+ };
219
+ })
220
+ public async prompt(message?: string, toolHeaders = {}, concurrentToolCalls = 4, abortSignal?: AbortSignal) {
221
+ const result = await this.streamPrompt(message, toolHeaders, concurrentToolCalls, abortSignal);
222
+ return result;
223
+ }
224
+
225
+ //TODO : handle attachments
226
+ @hookAsyncWithContext('Conversation.streamPrompt', async (instance: Conversation) => {
227
+ await instance.ready;
228
+
229
+ return {
230
+ teamId: instance._teamId,
231
+ agentId: instance._agentId,
232
+ model: instance._model,
233
+ };
234
+ })
235
+ public async streamPrompt(message?: string, toolHeaders = {}, concurrentToolCalls = 4, abortSignal?: AbortSignal) {
236
+ if (message) {
237
+ //initial call, reset stop flag
238
+
239
+ this.stop = false;
240
+ }
241
+ if (this.stop) {
242
+ this.emit('interrupted', 'interrupted');
243
+ this.emit('end');
244
+ return;
245
+ }
246
+ await this.ready;
247
+
248
+ // Add an abort handler
249
+ if (abortSignal) {
250
+ abortSignal.addEventListener('abort', () => {
251
+ //this.emit('error', { name: 'AbortError', message: 'Request aborted by user!' });
252
+ this.emit('aborted', 'Aborted by user!');
253
+ //const error = new Error('Request aborted by user!');
254
+ //error.name = 'AbortError';
255
+ //throw error;
256
+ });
257
+ }
258
+
259
+ const passThroughtContinueMessage = 'Continue with the next tool call if there are any, or just inform the user that you are done';
260
+ //let promises = [];
261
+ let _content = '';
262
+ const reqMethods = this._reqMethods;
263
+ const toolsConfig = this._toolsConfig;
264
+ const endpoints = this._endpoints;
265
+ const baseUrl = this._baseUrl;
266
+ const message_id = 'msg_' + randomUUID();
267
+ const isDebugSession = toolHeaders['X-DEBUG'];
268
+
269
+ /* ==================== STEP ENTRY ==================== */
270
+ // console.debug('Request to LLM with the given model, messages and functions properties.', {
271
+ // model: this.model,
272
+ // message,
273
+ // toolsConfig,
274
+ // });
275
+ /* ==================== STEP ENTRY ==================== */
276
+ const llmInference: LLMInference = await LLMInference.getInstance(this.model, AccessCandidate.team(this._teamId));
277
+
278
+ if (message) this._context.addUserMessage(message, message_id);
279
+
280
+ const contextWindow = await this._context.getContextWindow(this._maxContextSize, this._maxOutputTokens);
281
+
282
+ let maxTokens = this._maxOutputTokens;
283
+ if (typeof this.model === 'object' && this.model?.params?.maxTokens) {
284
+ maxTokens = this.model.params.maxTokens;
285
+ }
286
+
287
+ const eventEmitter: any = await llmInference
288
+ .promptStream({
289
+ contextWindow,
290
+ params: {
291
+ model: this.model,
292
+ toolsConfig: this._settings?.toolsStrategy ? this._settings.toolsStrategy(toolsConfig) : toolsConfig,
293
+ maxTokens,
294
+ cache: this._settings?.experimentalCache,
295
+ agentId: this._agentId,
296
+ abortSignal,
297
+ },
298
+ })
299
+ .catch((error) => {
300
+ console.error('Error on promptStream: ', error);
301
+ this.emit(TLLMEvent.Error, error);
302
+ });
303
+
304
+ // remove listeners from llm event emitter to stop receiving stream data
305
+ if (abortSignal) {
306
+ abortSignal.addEventListener('abort', () => {
307
+ eventEmitter.removeAllListeners();
308
+ });
309
+ }
310
+ if (!eventEmitter || eventEmitter.error) {
311
+ throw new Error('[LLM Request Error]');
312
+ }
313
+
314
+ if (message) this.emit('start');
315
+ eventEmitter.on('data', (data) => {
316
+ if (this.stop) return;
317
+ this.emit('data', data);
318
+ });
319
+
320
+ eventEmitter.on(TLLMEvent.Thinking, (thinking) => {
321
+ if (this.stop) return;
322
+ this.emit(TLLMEvent.Thinking, thinking);
323
+ });
324
+
325
+ eventEmitter.on(TLLMEvent.Content, (content) => {
326
+ if (this.stop) return;
327
+ // if (toolHeaders['x-passthrough']) {
328
+ // console.log('Passthrough skiped content ', content);
329
+ // return;
330
+ // }
331
+ const lastMessage = this._context?.messages?.[this._context?.messages?.length - 1];
332
+ const skip = lastMessage?.content?.includes(passThroughtContinueMessage) && lastMessage?.__smyth_data__?.internal;
333
+
334
+ //skip if the content is the last generated message after a passthrough content
335
+ if (skip) return;
336
+ _content += content;
337
+ this.emit(TLLMEvent.Content, content);
338
+ });
339
+
340
+ let finishReason = 'stop';
341
+
342
+ let toolsPromise = new Promise((resolve, reject) => {
343
+ let hasTools = false;
344
+ let hasError = false;
345
+ let passThroughContent = '';
346
+
347
+ eventEmitter.on(TLLMEvent.Error, (error) => {
348
+ hasError = true;
349
+ reject(error);
350
+ });
351
+
352
+ eventEmitter.on(TLLMEvent.ToolInfo, async (toolsData, thinkingBlocks = []) => {
353
+ if (this.stop) return;
354
+ hasTools = true;
355
+ let llmMessage: any = {
356
+ role: 'assistant',
357
+ content: _content,
358
+ tool_calls: [],
359
+ };
360
+
361
+ if (thinkingBlocks?.length > 0) {
362
+ this.emit(
363
+ 'thoughtProcess',
364
+ thinkingBlocks
365
+ .filter((block) => block.type === 'thinking')
366
+ .map((block) => block.thinking || '')
367
+ .join('\n')
368
+ );
369
+
370
+ llmMessage.thinkingBlocks = thinkingBlocks;
371
+ }
372
+
373
+ llmMessage.tool_calls = toolsData.map((tool) => {
374
+ return {
375
+ id: tool.id,
376
+ type: tool.type,
377
+ function: {
378
+ name: tool.name,
379
+ arguments: tool.arguments,
380
+ },
381
+ };
382
+ });
383
+
384
+ //if (llmMessage.tool_calls?.length <= 0) return;
385
+
386
+ this.emit(TLLMEvent.ToolInfo, toolsData);
387
+
388
+ //initialize the agent callback logic
389
+ const _agentCallback = (data) => {
390
+ if (this.stop) return;
391
+ //if (typeof data !== 'string') return;
392
+ let content = '';
393
+ let thinking = '';
394
+ if (typeof data === 'object') {
395
+ if (data.content) {
396
+ content = data.content;
397
+
398
+ passThroughContent += content;
399
+ eventEmitter.emit(TLLMEvent.Content, content);
400
+ }
401
+ if (data.thinking) {
402
+ thinking = data.thinking;
403
+ eventEmitter.emit(TLLMEvent.Thinking, thinking);
404
+ }
405
+ return;
406
+ }
407
+ if (typeof data === 'string') {
408
+ passThroughContent += data;
409
+ eventEmitter.emit(TLLMEvent.Content, data);
410
+ }
411
+
412
+ //passThroughContent += data;
413
+ //this is currently used to handle agent callbacks when running local agents
414
+ //this.emit('agentCallback', data);
415
+
416
+ //this.emit('content', data);
417
+ //this.emit('content', data);
418
+ //eventEmitter.emit('content', data);
419
+ };
420
+
421
+ const toolProcessingTasks = toolsData.map(
422
+ (tool: { index: number; name: string; type: string; arguments: Record<string, any> }) => async () => {
423
+ const endpoint = endpoints?.get(tool?.name) || tool?.name;
424
+ // Sometimes we have object response from the LLM such as Anthropic
425
+
426
+ let args = typeof tool?.arguments === 'string' ? JSONContent(tool?.arguments).tryParse() || {} : tool?.arguments;
427
+
428
+ if (args?.error) {
429
+ throw new Error('[Tool] Arguments Parsing Error\n' + JSON.stringify({ message: args?.error }));
430
+ }
431
+
432
+ //await beforeFunctionCall(llmMessage, toolsData[tool.index]);
433
+ // TODO [Forhad]: Make sure toolsData[tool.index] and tool do the same thing
434
+ this.emit('beforeToolCall', { tool, args }, llmMessage); //deprecated
435
+ this.emit(TLLMEvent.ToolCall, { tool, _llmRequest: llmMessage });
436
+
437
+ const toolArgs = {
438
+ type: tool?.type,
439
+ method: reqMethods?.get(tool?.name),
440
+ endpoint,
441
+ args,
442
+ baseUrl,
443
+ headers: toolHeaders,
444
+ agentCallback: _agentCallback,
445
+ };
446
+
447
+ let { data: functionResponse, error } = await this.useTool(toolArgs, abortSignal);
448
+
449
+ if (error) {
450
+ functionResponse = typeof error === 'object' && typeof error !== null ? JSON.stringify(error) : error;
451
+ }
452
+
453
+ const result = functionResponse;
454
+
455
+ functionResponse =
456
+ typeof functionResponse === 'object' && typeof functionResponse !== null
457
+ ? JSON.stringify(functionResponse)
458
+ : functionResponse;
459
+
460
+ //await afterFunctionCall(functionResponse, toolsData[tool.index]);
461
+ this.emit('afterToolCall', { tool, args }, functionResponse); // Deprecated
462
+ this.emit(TLLMEvent.ToolResult, { tool, result });
463
+
464
+ return { ...tool, result: functionResponse };
465
+ }
466
+ );
467
+
468
+ const processedToolsData = await processWithConcurrencyLimit<ToolData>(toolProcessingTasks, concurrentToolCalls);
469
+
470
+ //if (!passThroughContent) {
471
+
472
+ if (!passThroughContent) {
473
+ this._context.addToolMessage(llmMessage, processedToolsData, message_id);
474
+ //delete toolHeaders['x-passthrough'];
475
+ } else {
476
+ //this._context.addAssistantMessage(passThroughContent, message_id);
477
+ llmMessage.content += '\n' + passThroughContent;
478
+ this._context.addToolMessage(llmMessage, processedToolsData, message_id);
479
+ //this should not be stored in the persistent conversation store
480
+ //it's just a workaround to avoid generating more content after passthrough content
481
+ this._context.addUserMessage(passThroughtContinueMessage, message_id, { internal: true });
482
+ //toolHeaders['x-passthrough'] = 'true';
483
+ }
484
+
485
+ this.streamPrompt(null, toolHeaders, concurrentToolCalls, abortSignal).then(resolve).catch(reject);
486
+
487
+ //} else {
488
+ //TODO : add passthrough content to the context window ??
489
+
490
+ //if passThroughContent is not empty, it means that the current agent streamed content through components
491
+ //resolve(passThroughContent);
492
+ //}
493
+ //const result = await resolve(await this.streamPrompt(null, toolHeaders, concurrentToolCalls));
494
+ //console.log('Result after tool call: ', result);
495
+ });
496
+
497
+ eventEmitter.on(TLLMEvent.End, async (toolsData, usage_data, _finishReason) => {
498
+ if (_finishReason) finishReason = _finishReason;
499
+ if (usage_data) {
500
+ //FIXME : normalize the usage data format
501
+ this.emit(TLLMEvent.Usage, usage_data);
502
+ }
503
+ if (hasError) return;
504
+
505
+ if (!hasTools || passThroughContent) {
506
+ //console.log(' ===> resolved content no tool', _content);
507
+ //this._context.push({ role: 'assistant', content: _content });
508
+ const lastMessage = this._context?.messages?.[this._context?.messages?.length - 1];
509
+ let metadata;
510
+ if (lastMessage?.content?.includes(passThroughtContinueMessage) && lastMessage?.__smyth_data__?.internal) {
511
+ metadata = { internal: true };
512
+ }
513
+ this._context.addAssistantMessage(_content, message_id, metadata);
514
+ resolve(''); //the content were already emitted through 'content' event
515
+ }
516
+ });
517
+ });
518
+
519
+ const toolsContent = await toolsPromise.catch((error) => {
520
+ console.error('Error in toolsPromise: ', error);
521
+ //this.emit('error', error);
522
+ this.emit(TLLMEvent.Error, error);
523
+ return '';
524
+ });
525
+ _content += toolsContent;
526
+ let content = JSONContent(_content).tryParse();
527
+
528
+ // let streamPromise = new Promise((resolve, reject) => {
529
+ // eventEmitter.on('end', async () => {
530
+ // if (toolsPromise) await toolsPromise;
531
+
532
+ // let content = JSONContent(_content).tryParse();
533
+ // resolve({ content });
534
+ // });
535
+ // });
536
+
537
+ // promises.push(streamPromise);
538
+
539
+ //await Promise.all(promises);
540
+ //return content;
541
+
542
+ if (message) {
543
+ //console.log('main content', content);
544
+ //this._context.push({ role: 'assistant', content: content });
545
+
546
+ if (finishReason !== 'stop') {
547
+ this.emit(TLLMEvent.Interrupted, finishReason);
548
+ }
549
+ this.emit(TLLMEvent.End);
550
+ } else {
551
+ //console.log('tool content', content);
552
+ }
553
+
554
+ return content;
555
+ }
556
+
557
+ private resolveToolEndpoint(baseUrl: string, method: string, endpoint: string, params: Record<string, any>): string {
558
+ //handle query params
559
+ let templateParams = {};
560
+ if (params) {
561
+ const parameters = this._spec?.paths?.[endpoint]?.[method.toLowerCase()]?.parameters || [];
562
+ for (let p of parameters) {
563
+ if (p.in === 'path') {
564
+ templateParams[p.name] = params[p.name] || '';
565
+ delete params[p.name];
566
+ }
567
+ }
568
+ }
569
+ const parsedEndpoint = TemplateString(endpoint).parse(templateParams, Match.singleCurly).clean().result;
570
+
571
+ // Create a new URL object using the base URL and endpoint
572
+ const url = new URL(parsedEndpoint, baseUrl);
573
+
574
+ // Iterate over the params object and append each key/value pair to the URL search parameters
575
+ Object.keys(params).forEach((key) => {
576
+ url.searchParams.append(key, params[key]);
577
+ });
578
+
579
+ // Return the full URL as a string
580
+ return url.toString();
581
+ }
582
+
583
+ private async useTool(
584
+ params: ToolParams,
585
+ abortSignal?: AbortSignal
586
+ ): Promise<{
587
+ data: any;
588
+ error;
589
+ }> {
590
+ if (this.stop) {
591
+ return { data: null, error: 'Conversation Interrupted' };
592
+ }
593
+
594
+ const { type, endpoint, args, method, baseUrl, headers = {}, agentCallback } = params;
595
+
596
+ if (type === 'function') {
597
+ const toolHandler = this._customToolsHandlers[endpoint];
598
+ if (toolHandler) {
599
+ try {
600
+ const result = await toolHandler(args);
601
+ return { data: result, error: null };
602
+ } catch (error) {
603
+ return { data: null, error: error?.message || 'Custom tool handler failed' };
604
+ }
605
+ }
606
+ try {
607
+ const url = this.resolveToolEndpoint(baseUrl, method, endpoint, method == 'get' ? args : {});
608
+
609
+ const reqConfig: AxiosRequestConfig = {
610
+ method,
611
+ url,
612
+ headers: {
613
+ ...headers,
614
+ },
615
+ signal: abortSignal,
616
+ };
617
+
618
+ if (method !== 'get') {
619
+ if (Object.keys(args).length) {
620
+ reqConfig.data = args;
621
+ }
622
+ //(reqConfig.headers as Record<string, unknown>)['Content-Type'] = 'application/json';
623
+ reqConfig.headers['Content-Type'] = 'application/json';
624
+ }
625
+
626
+ console.debug('Calling tool: ', reqConfig);
627
+
628
+ reqConfig.headers['X-CACHE-ID'] = this._context?.llmCache?.id;
629
+
630
+ /*
631
+ * Objective for the following conditions:
632
+ * - In case it is not a debug call and there is no monitor id, then we need to run the agent locally to reduce latency
633
+ * - but if it a debug call, we need to forward req to sre-builder-debugger since it holds the debug promises
634
+ * - or if there is a monitor id, we need to forward req to sre-builder-debugger since it holds the monitor SSE connections.
635
+ * - a remote call is often needed for file parsing be default agent we inject, it should not be loaded locally.
636
+ * So the objecive is mainly reducing latency when possible
637
+ */
638
+ //TODO : implement a timeout for the tool call
639
+ const requiresRemoteCall =
640
+ reqConfig.headers['X-DEBUG'] !== undefined ||
641
+ reqConfig.headers['X-MONITOR-ID'] !== undefined ||
642
+ reqConfig.headers['X-AGENT-REMOTE-CALL'] !== undefined;
643
+ if (
644
+ reqConfig.url.includes('localhost') ||
645
+ (reqConfig.headers['X-AGENT-ID'] && !requiresRemoteCall)
646
+ //empty string is accepted
647
+
648
+ // || reqConfig.url.includes('localagent') //* commented to allow debugging live sessions as the req needs to reach sre-builder-debugger
649
+ ) {
650
+ console.log('RUNNING AGENT LOCALLY');
651
+ let agentProcess;
652
+ if (this.agentData === this._specSource) {
653
+ //the agent was loaded from data
654
+ agentProcess = AgentProcess.load(this.agentData, this._agentVersion);
655
+ } else {
656
+ //the agent was loaded from a spec
657
+ agentProcess = AgentProcess.load(
658
+ reqConfig.headers['X-AGENT-ID'] || this._agentId,
659
+ reqConfig.headers['X-AGENT-VERSION'] || this._agentVersion
660
+ );
661
+ }
662
+ //if it's a local agent, invoke it directly
663
+
664
+ const response = await agentProcess.run(reqConfig as TAgentProcessParams, agentCallback);
665
+ return { data: response.data, error: null };
666
+ } else {
667
+ console.log('RUNNING AGENT REMOTELY');
668
+ let eventSource;
669
+
670
+ // if debug mode is on OR the user attached a monitor to the call, then we need to attach a monitor to the agent call
671
+ if ((reqConfig.headers['X-DEBUG'] && reqConfig.headers['X-AGENT-ID']) || reqConfig.headers['X-MONITOR-ID']) {
672
+ console.log('ATTACHING MONITOR TO REMOTE AGENT CALL');
673
+ const monitUrl = reqConfig.url.split('/api')[0] + '/agent/' + reqConfig.headers['X-AGENT-ID'] + '/monitor';
674
+
675
+ // Create custom fetch implementation that includes our headers
676
+ const customFetch: FetchLike = (url, init) => {
677
+ return fetch(url, {
678
+ ...init,
679
+ headers: {
680
+ ...(init?.headers || {}),
681
+ ...Object.fromEntries(Object.entries(reqConfig.headers).map(([k, v]) => [k, String(v)])),
682
+ },
683
+ });
684
+ };
685
+
686
+ const eventSource = new EventSource(monitUrl, {
687
+ fetch: customFetch,
688
+ });
689
+ let monitorId = '';
690
+
691
+ eventSource.addEventListener('init', (event) => {
692
+ monitorId = event.data;
693
+ console.log('monitorId', monitorId);
694
+ if (reqConfig.headers['X-MONITOR-ID']) {
695
+ // an external monitor was sent, so we do not override it
696
+ reqConfig.headers['X-MONITOR-ID'] = `${reqConfig.headers['X-MONITOR-ID']},${monitorId}`;
697
+ } else {
698
+ reqConfig.headers['X-MONITOR-ID'] = monitorId;
699
+ }
700
+ });
701
+ eventSource.addEventListener('llm/passthrough/content', (event: any) => {
702
+ if (params.agentCallback) params.agentCallback({ content: event.data.replace(/\\n/g, '\n') });
703
+ });
704
+ eventSource.addEventListener('llm/passthrough/thinking', (event: any) => {
705
+ if (params.agentCallback) params.agentCallback({ thinking: event.data.replace(/\\n/g, '\n') });
706
+ });
707
+
708
+ await new Promise((resolve) => {
709
+ let maxTime = 5 * 1000; //5 seconds
710
+ let itv = setInterval(() => {
711
+ if (monitorId || maxTime <= 0) {
712
+ clearInterval(itv);
713
+ resolve(true);
714
+ }
715
+ maxTime -= 100;
716
+ }, 100);
717
+ });
718
+ }
719
+
720
+ //if it's a remote agent, call the API via HTTP
721
+ const response = await axios.request(reqConfig);
722
+
723
+ if (eventSource) {
724
+ eventSource.close();
725
+ console.log('eventSource closed');
726
+ }
727
+ return { data: response.data, error: null };
728
+ }
729
+ } catch (error: any) {
730
+ console.warn('Failed to call Tool: ', baseUrl, endpoint);
731
+ console.warn(' ====>', error);
732
+ return { data: null, error: error?.response?.data || error?.message };
733
+ }
734
+ }
735
+
736
+ return { data: null, error: `'${type}' tool type not supported at the moment` };
737
+ }
738
+
739
+ public async addTool(tool: {
740
+ name: string;
741
+ description: string;
742
+ arguments?: Record<string, any> | string[];
743
+ handler: (args: Record<string, any>) => Promise<any>;
744
+ inputs?: any[];
745
+ }) {
746
+ if (!tool.arguments) {
747
+ //if no arguments are provided, we need to extract them from the function
748
+ const toolFunction = tool.handler as Function;
749
+ const openApiArgs = this.extractArgsAsOpenAPI(toolFunction);
750
+ const _arguments: any = {};
751
+ for (let arg of openApiArgs) {
752
+ _arguments[arg.name] = arg.schema;
753
+ if (tool.inputs && arg.schema.properties) {
754
+ const required = [];
755
+ for (let prop in arg.schema.properties) {
756
+ const input = tool.inputs?.find((i) => i.name === prop);
757
+ if (!arg.schema.properties[prop].description) {
758
+ arg.schema.properties[prop].description = input?.description;
759
+ }
760
+ if (!input?.optional) {
761
+ required.push(prop);
762
+ }
763
+ }
764
+ if (required.length) {
765
+ arg.schema.required = required;
766
+ }
767
+ }
768
+ }
769
+
770
+ tool.arguments = _arguments;
771
+ tool.handler = async (argsObj: any) => {
772
+ const args = Object.values(argsObj);
773
+ const result = await toolFunction(...args);
774
+ return result;
775
+ };
776
+ }
777
+
778
+ const requiredFields = Object.values(tool.arguments)
779
+ .map((arg) => (arg.required ? arg.name : null))
780
+ .filter((arg) => arg);
781
+
782
+ const properties = {};
783
+ for (let entry in tool.arguments) {
784
+ properties[entry] = {
785
+ type: tool.arguments[entry].type || 'string',
786
+ properties: tool.arguments[entry].properties,
787
+ description: tool.arguments[entry].description,
788
+ ...(tool.arguments[entry].type === 'array' ? { items: { type: tool.arguments[entry].items?.type || 'string' } } : {}),
789
+ };
790
+ }
791
+ const toolDefinition = {
792
+ name: tool.name,
793
+ description: tool.description,
794
+ properties,
795
+ requiredFields,
796
+ };
797
+ this._customToolsDeclarations.push(toolDefinition);
798
+ this._customToolsHandlers[tool.name] = tool.handler;
799
+
800
+ const llmInference: LLMInference = await LLMInference.getInstance(this.model, AccessCandidate.team(this._teamId));
801
+ const toolsConfig: any = llmInference.connector.formatToolsConfig({
802
+ type: 'function',
803
+ toolDefinitions: [toolDefinition],
804
+ toolChoice: this.toolChoice,
805
+ });
806
+
807
+ if (this._toolsConfig) this._toolsConfig.tools.push(...toolsConfig?.tools);
808
+ else this._toolsConfig = toolsConfig;
809
+ }
810
+ /**
811
+ * updates LLM model, if spec is available, it will update the tools config
812
+ * @param model
813
+ */
814
+ // TODO [Forhad]: For now updateModel does not required await, but when we will have tools implementation in custom model then we need to await for it
815
+ private async updateModel(model: string | TLLMModel) {
816
+ try {
817
+ this._model = model;
818
+
819
+ if (this._spec) {
820
+ this._reqMethods = OpenAPIParser.mapReqMethods(this._spec?.paths);
821
+ this._endpoints = OpenAPIParser.mapEndpoints(this._spec?.paths);
822
+ this._baseUrl = this._spec?.servers?.[0].url;
823
+
824
+ const functionDeclarations = this.getFunctionDeclarations(this._spec);
825
+ functionDeclarations.push(...this._customToolsDeclarations);
826
+ const llmInference: LLMInference = await LLMInference.getInstance(this._model, AccessCandidate.team(this._teamId));
827
+ if (!llmInference.connector) {
828
+ this.emit('error', 'No connector found for model: ' + this._model);
829
+ return;
830
+ }
831
+ this._toolsConfig = llmInference.connector.formatToolsConfig({
832
+ type: 'function',
833
+ toolDefinitions: functionDeclarations,
834
+ toolChoice: this.toolChoice,
835
+ });
836
+
837
+ let messages = [];
838
+ if (this._context) messages = this._context.messages; // preserve messages
839
+
840
+ this._context = new LLMContext(llmInference, this.systemPrompt, this._llmContextStore);
841
+ } else {
842
+ this._toolsConfig = null;
843
+ this._reqMethods = null;
844
+ this._endpoints = null;
845
+ this._baseUrl = null;
846
+ }
847
+ } catch (error) {
848
+ this.emit('error', error);
849
+ }
850
+ }
851
+
852
+ /**
853
+ * this function is used to patch the spec with missing fields that are required for the tool to work
854
+ * @param spec
855
+ */
856
+ private patchSpec(spec: Record<string, any>) {
857
+ const paths = spec?.paths;
858
+ for (const path in paths) {
859
+ const pathData = paths[path];
860
+
861
+ // it's possible we have multiple methods for a single path
862
+ for (const key in pathData) {
863
+ const data = pathData[key];
864
+ if (!data?.operationId) {
865
+ //normalize path and use it as operationId
866
+ data.operationId = path.replace(/\//g, '_').replace(/{|}/g, '').replace(/\./g, '_');
867
+ }
868
+ }
869
+ }
870
+ return spec;
871
+ }
872
+ /**
873
+ * Loads OpenAPI specification from source
874
+ * @param specSource
875
+ * @returns
876
+ */
877
+ private async loadSpecFromSource(specSource: string | Record<string, any>) {
878
+ if (typeof specSource === 'object') {
879
+ //is this a valid OpenAPI spec?
880
+ if (OpenAPIParser.isValidOpenAPI(specSource)) {
881
+ this.systemPrompt = specSource?.info?.description || '';
882
+ return this.patchSpec(specSource);
883
+ }
884
+ //is this a valid agent data?
885
+ if (typeof specSource?.behavior === 'string' && specSource?.components && specSource?.connections) {
886
+ this.agentData = specSource; //agent loaded from data directly
887
+ return await this.loadSpecFromAgent(specSource);
888
+ }
889
+
890
+ return null;
891
+ }
892
+
893
+ if (typeof specSource === 'string') {
894
+ //is this an openAPI url?
895
+ if (isUrl(specSource as string)) {
896
+ const spec = await OpenAPIParser.getJsonFromUrl(specSource as string);
897
+
898
+ if (spec.info?.description) this.systemPrompt = spec.info.description;
899
+
900
+ // we always overwrite system prompt with user defined one
901
+ if (this.userDefinedSystemPrompt) this.systemPrompt = this.userDefinedSystemPrompt;
902
+
903
+ if (spec.info?.title) this.assistantName = spec.info.title;
904
+
905
+ const specUrl = new URL(specSource as string);
906
+ const defaultBaseUrl = specUrl.origin;
907
+
908
+ if (!spec?.servers) spec.servers = [{ url: defaultBaseUrl }];
909
+ if (spec.servers?.length == 0) spec.servers = [{ url: defaultBaseUrl }];
910
+
911
+ if (this.assistantName) {
912
+ this.systemPrompt = `Assistant Name : ${this.assistantName}\n\n${this.systemPrompt}`;
913
+ }
914
+
915
+ //this._agentId = specUrl.hostname; //just set an agent ID in order to identify the agent in SRE //FIXME: maybe this requires a better solution
916
+ return this.patchSpec(spec);
917
+ }
918
+ //is this an agentId ?
919
+ const agentDataConnector = ConnectorService.getAgentDataConnector();
920
+ const agentId = specSource as string;
921
+ this._agentId = agentId;
922
+
923
+ if (this._agentVersion === undefined) {
924
+ const isDeployed = await agentDataConnector.isDeployed(agentId);
925
+ this._agentVersion = isDeployed ? 'latest' : '';
926
+ }
927
+
928
+ this.agentData = await agentDataConnector.getAgentData(agentId, this._agentVersion).catch((error) => null);
929
+ if (!this.agentData) return null;
930
+
931
+ const spec = await this.loadSpecFromAgent(this.agentData);
932
+ return spec;
933
+ }
934
+ }
935
+ private async loadSpecFromAgent(agentData: Record<string, any>) {
936
+ //handle the case where agentData object contains the agent schema directly
937
+ //agents retrieved from the database have a wrapping object with agent name and version number
938
+ //local agent might include the agent data directly
939
+ if (agentData?.components) {
940
+ agentData = { name: agentData?.name, data: agentData, version: '1.0.0' };
941
+ }
942
+
943
+ const agentDataConnector = ConnectorService.getAgentDataConnector();
944
+ this.systemPrompt = agentData?.data?.behavior || this.systemPrompt;
945
+
946
+ // we always overwrite system prompt with user defined one
947
+ if (this.userDefinedSystemPrompt) this.systemPrompt = this.userDefinedSystemPrompt;
948
+
949
+ this.assistantName = agentData?.data?.name || agentData?.data?.templateInfo?.name || this.assistantName;
950
+ if (this.assistantName) {
951
+ this.systemPrompt = `Assistant Name : ${this.assistantName}\n\n${this.systemPrompt}`;
952
+ }
953
+
954
+ const spec = await agentDataConnector.getOpenAPIJSON(agentData, 'http://localhost/', this._agentVersion, true).catch((error) => null);
955
+ return this.patchSpec(spec);
956
+ }
957
+
958
+ /**
959
+ * Extracts function declarations from OpenAPI specification
960
+ * @param spec
961
+ * @returns
962
+ */
963
+ private getFunctionDeclarations(spec): FunctionDeclaration[] {
964
+ const paths = spec?.paths;
965
+ const reqMethods = OpenAPIParser.mapReqMethods(paths);
966
+
967
+ let declarations: FunctionDeclaration[] = [];
968
+
969
+ for (const path in paths) {
970
+ const pathData = paths[path];
971
+
972
+ // it's possible we have multiple methods for a single path
973
+ for (const key in pathData) {
974
+ const data = pathData[key];
975
+
976
+ if (!data?.operationId) continue;
977
+
978
+ const method = reqMethods.get(data?.operationId) || 'get';
979
+
980
+ let properties = {};
981
+ let requiredFields: string[] = [];
982
+
983
+ if (method.toLowerCase() === 'get') {
984
+ const params = data?.parameters || [];
985
+ for (const prop of params) {
986
+ properties[prop.name] = {
987
+ ...prop.schema,
988
+ description: prop.description,
989
+ };
990
+
991
+ if (prop.required === true) {
992
+ requiredFields.push(prop?.name || '');
993
+ }
994
+ }
995
+ } else {
996
+ properties = data?.requestBody?.content?.['application/json']?.schema?.properties;
997
+ requiredFields = data?.requestBody?.content?.['application/json']?.schema?.required;
998
+
999
+ // Open AI doesn't support 'required' to be boolean inside property
1000
+ for (const prop in properties) {
1001
+ delete properties[prop]?.required;
1002
+ }
1003
+ }
1004
+
1005
+ if (!properties) properties = {};
1006
+ if (!requiredFields) requiredFields = [];
1007
+
1008
+ const declaration = {
1009
+ name: data?.operationId,
1010
+ description: data?.description || data?.summary || '',
1011
+ properties,
1012
+ requiredFields,
1013
+ };
1014
+ declarations.push(declaration);
1015
+ }
1016
+ }
1017
+
1018
+ return declarations;
1019
+ }
1020
+
1021
+ private async assignTeamIdFromAgentId(agentId: string) {
1022
+ if (agentId) {
1023
+ const accountConnector = ConnectorService.getAccountConnector();
1024
+ const teamId = await accountConnector.getCandidateTeam(AccessCandidate.agent(agentId))?.catch(() => '');
1025
+ this._teamId = teamId || '';
1026
+ }
1027
+ }
1028
+
1029
+ private extractArgsAsOpenAPI(fn) {
1030
+ const ast = acorn.parse(`(${fn.toString()})`, { ecmaVersion: 'latest' });
1031
+ const params = (ast.body[0] as any).expression.params;
1032
+
1033
+ let counter = 0;
1034
+ function handleParam(param) {
1035
+ if (param.type === 'Identifier') {
1036
+ return {
1037
+ name: param.name,
1038
+ in: 'query',
1039
+ required: true,
1040
+ schema: { type: 'string', name: param.name, required: true },
1041
+ };
1042
+ }
1043
+
1044
+ if (param.type === 'AssignmentPattern' && param.left.type === 'Identifier') {
1045
+ return {
1046
+ name: param.left.name,
1047
+ in: 'query',
1048
+ required: false,
1049
+ schema: { type: 'string', name: param.left.name, required: false },
1050
+ };
1051
+ }
1052
+
1053
+ if (param.type === 'RestElement' && param.argument.type === 'Identifier') {
1054
+ return {
1055
+ name: param.argument.name,
1056
+ in: 'query',
1057
+ required: false,
1058
+ schema: { type: 'array', items: { type: 'string' } },
1059
+ };
1060
+ }
1061
+
1062
+ if (param.type === 'ObjectPattern') {
1063
+ // For destructured objects, output as a single parameter with nested fields
1064
+ const name = `[object_${counter++}]`;
1065
+ return {
1066
+ name,
1067
+ in: 'query',
1068
+ required: true,
1069
+ schema: {
1070
+ type: 'object',
1071
+ required: true,
1072
+ name,
1073
+ properties: Object.fromEntries(
1074
+ param.properties.map((prop) => {
1075
+ const keyName = prop.key.name || '[unknown]';
1076
+ return [keyName, { type: 'string' }]; // default to string
1077
+ })
1078
+ ),
1079
+ },
1080
+ };
1081
+ }
1082
+
1083
+ const name = `[unknown_${counter++}]`;
1084
+ return {
1085
+ name,
1086
+ in: 'query',
1087
+ required: true,
1088
+ schema: { type: 'string', name, required: true },
1089
+ };
1090
+ }
1091
+
1092
+ return params.map(handleParam);
1093
+ }
1094
+ }