@memberjunction/ai-agents 2.59.0 → 2.60.0
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.
- package/README.md +182 -1357
- package/dist/AgentRunner.d.ts.map +1 -1
- package/dist/AgentRunner.js +10 -5
- package/dist/AgentRunner.js.map +1 -1
- package/dist/PayloadManager.d.ts +16 -0
- package/dist/PayloadManager.d.ts.map +1 -0
- package/dist/PayloadManager.js +340 -0
- package/dist/PayloadManager.js.map +1 -0
- package/dist/agent-types/base-agent-type.d.ts +8 -2
- package/dist/agent-types/base-agent-type.d.ts.map +1 -1
- package/dist/agent-types/base-agent-type.js +28 -0
- package/dist/agent-types/base-agent-type.js.map +1 -1
- package/dist/agent-types/loop-agent-response-type.d.ts +1 -1
- package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-type.d.ts +5 -2
- package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-type.js +63 -30
- package/dist/agent-types/loop-agent-type.js.map +1 -1
- package/dist/base-agent.d.ts +21 -19
- package/dist/base-agent.d.ts.map +1 -1
- package/dist/base-agent.js +330 -520
- package/dist/base-agent.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/package.json +12 -10
package/dist/base-agent.js
CHANGED
|
@@ -9,15 +9,51 @@ const aiengine_1 = require("@memberjunction/aiengine");
|
|
|
9
9
|
const actions_1 = require("@memberjunction/actions");
|
|
10
10
|
const ai_core_plus_1 = require("@memberjunction/ai-core-plus");
|
|
11
11
|
const AgentRunner_1 = require("./AgentRunner");
|
|
12
|
+
const PayloadManager_1 = require("./PayloadManager");
|
|
12
13
|
class BaseAgent {
|
|
13
14
|
constructor() {
|
|
14
15
|
this._promptRunner = new ai_prompts_1.AIPromptRunner();
|
|
15
16
|
this._metadata = new core_1.Metadata();
|
|
16
|
-
this._runContext = null;
|
|
17
17
|
this._agentRun = null;
|
|
18
|
-
this.
|
|
18
|
+
this._agentHierarchy = [];
|
|
19
|
+
this._depth = 0;
|
|
19
20
|
this._allProgressSteps = [];
|
|
20
21
|
this._subAgentRuns = [];
|
|
22
|
+
this._payloadManager = new PayloadManager_1.PayloadManager();
|
|
23
|
+
}
|
|
24
|
+
logStatus(message, verboseOnly = false, params) {
|
|
25
|
+
if (verboseOnly) {
|
|
26
|
+
(0, core_1.LogStatusEx)({
|
|
27
|
+
message,
|
|
28
|
+
verboseOnly: true,
|
|
29
|
+
isVerboseEnabled: () => params?.verbose === true || (0, core_1.IsVerboseLoggingEnabled)()
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
(0, core_1.LogStatus)(message);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
logError(error, options) {
|
|
37
|
+
const errorMessage = error instanceof Error ? error.message : error;
|
|
38
|
+
const errorObj = error instanceof Error ? error : undefined;
|
|
39
|
+
const metadata = {
|
|
40
|
+
...options?.metadata
|
|
41
|
+
};
|
|
42
|
+
if (options?.agent) {
|
|
43
|
+
metadata.agentId = options.agent.ID;
|
|
44
|
+
metadata.agentName = options.agent.Name;
|
|
45
|
+
}
|
|
46
|
+
if (options?.agentType) {
|
|
47
|
+
metadata.agentTypeId = options.agentType.ID;
|
|
48
|
+
metadata.agentTypeName = options.agentType.Name;
|
|
49
|
+
}
|
|
50
|
+
(0, core_1.LogErrorEx)({
|
|
51
|
+
message: errorMessage,
|
|
52
|
+
error: errorObj,
|
|
53
|
+
category: options?.category || 'BaseAgent',
|
|
54
|
+
severity: options?.severity || 'error',
|
|
55
|
+
metadata: Object.keys(metadata).length > 0 ? metadata : undefined
|
|
56
|
+
});
|
|
21
57
|
}
|
|
22
58
|
wrapProgressCallback(originalCallback) {
|
|
23
59
|
if (!originalCallback)
|
|
@@ -26,19 +62,40 @@ class BaseAgent {
|
|
|
26
62
|
this._allProgressSteps.push({
|
|
27
63
|
...progress,
|
|
28
64
|
timestamp: new Date(),
|
|
29
|
-
agentHierarchy: this.
|
|
30
|
-
depth: this.
|
|
65
|
+
agentHierarchy: this._agentHierarchy || [],
|
|
66
|
+
depth: this._depth || 0
|
|
31
67
|
});
|
|
32
|
-
|
|
68
|
+
try {
|
|
69
|
+
const enhancedProgress = {
|
|
70
|
+
...progress,
|
|
71
|
+
metadata: {
|
|
72
|
+
...progress.metadata,
|
|
73
|
+
agentRun: this._agentRun
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
originalCallback(enhancedProgress);
|
|
77
|
+
}
|
|
78
|
+
catch (e) {
|
|
79
|
+
this.logError(`Failed to enhance progress with agent run: ${e instanceof Error ? e.message : e}`, {
|
|
80
|
+
category: 'ProgressEnhancement',
|
|
81
|
+
metadata: {
|
|
82
|
+
progress: progress,
|
|
83
|
+
agentRunId: this._agentRun?.ID || 'N/A'
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
originalCallback(progress);
|
|
87
|
+
}
|
|
33
88
|
};
|
|
34
89
|
}
|
|
35
90
|
async Execute(params) {
|
|
36
91
|
try {
|
|
92
|
+
this.logStatus(`🤖 Starting execution of agent '${params.agent.Name}'`, true, params);
|
|
37
93
|
const wrappedParams = {
|
|
38
94
|
...params,
|
|
39
95
|
onProgress: this.wrapProgressCallback(params.onProgress)
|
|
40
96
|
};
|
|
41
97
|
if (params.cancellationToken?.aborted) {
|
|
98
|
+
this.logStatus(`⚠️ Agent '${params.agent.Name}' execution cancelled before start`, true, params);
|
|
42
99
|
return await this.createCancelledResult('Cancelled before execution started', params.contextUser);
|
|
43
100
|
}
|
|
44
101
|
wrappedParams.onProgress?.({
|
|
@@ -59,22 +116,36 @@ class BaseAgent {
|
|
|
59
116
|
const validationResult = await this.validateAgentWithTracking(params.agent, params.contextUser);
|
|
60
117
|
if (validationResult)
|
|
61
118
|
return validationResult;
|
|
119
|
+
this.logStatus(`📋 Loading configuration for agent '${params.agent.Name}'`, true, params);
|
|
62
120
|
const config = await this.loadAgentConfiguration(params.agent);
|
|
63
121
|
if (!config.success) {
|
|
122
|
+
this.logError(`Failed to load agent configuration: ${config.errorMessage}`, {
|
|
123
|
+
agent: params.agent,
|
|
124
|
+
category: 'AgentConfiguration'
|
|
125
|
+
});
|
|
64
126
|
return await this.createFailureResult(config.errorMessage || 'Failed to load agent configuration', params.contextUser);
|
|
65
127
|
}
|
|
128
|
+
this.logStatus(`🚀 Executing agent '${params.agent.Name}' internal logic`, true, params);
|
|
66
129
|
const executionResult = await this.executeAgentInternal(wrappedParams, config);
|
|
67
130
|
wrappedParams.onProgress?.({
|
|
68
131
|
step: 'finalization',
|
|
69
132
|
percentage: 95,
|
|
133
|
+
metadata: { result: executionResult },
|
|
70
134
|
message: this.formatHierarchicalMessage('Finalizing agent execution')
|
|
71
135
|
});
|
|
72
|
-
|
|
136
|
+
this.logStatus(`✅ Finalizing execution for agent '${params.agent.Name}'`, true, params);
|
|
137
|
+
return await this.finalizeAgentRun(executionResult.finalStep, executionResult.finalStep.payload, params.contextUser);
|
|
73
138
|
}
|
|
74
139
|
catch (error) {
|
|
75
140
|
if (params.cancellationToken?.aborted || error.message === 'Cancelled during execution') {
|
|
141
|
+
this.logStatus(`⚠️ Agent '${params.agent.Name}' execution cancelled: ${error.message}`, true, params);
|
|
76
142
|
return await this.createCancelledResult(error.message || 'Cancelled due to error during execution', params.contextUser);
|
|
77
143
|
}
|
|
144
|
+
this.logError(error, {
|
|
145
|
+
agent: params.agent,
|
|
146
|
+
category: 'AgentExecution',
|
|
147
|
+
severity: 'critical'
|
|
148
|
+
});
|
|
78
149
|
return await this.createFailureResult(error.message, params.contextUser);
|
|
79
150
|
}
|
|
80
151
|
}
|
|
@@ -86,14 +157,17 @@ class BaseAgent {
|
|
|
86
157
|
if (params.cancellationToken?.aborted) {
|
|
87
158
|
throw new Error('Cancelled during execution');
|
|
88
159
|
}
|
|
160
|
+
this.logStatus(`🔄 Executing step ${stepCount + 1} for agent '${params.agent.Name}'`, true, params);
|
|
89
161
|
const nextStep = await this.executeNextStep(params, config, currentNextStep);
|
|
90
162
|
stepCount++;
|
|
91
163
|
if (nextStep.terminate) {
|
|
92
164
|
continueExecution = false;
|
|
93
165
|
currentNextStep = nextStep;
|
|
166
|
+
this.logStatus(`🏁 Agent '${params.agent.Name}' terminating after ${stepCount} steps with result: ${nextStep.step}`, true, params);
|
|
94
167
|
}
|
|
95
168
|
else {
|
|
96
169
|
currentNextStep = nextStep;
|
|
170
|
+
this.logStatus(`➡️ Agent '${params.agent.Name}' continuing to next step: ${nextStep.step}`, true, params);
|
|
97
171
|
}
|
|
98
172
|
}
|
|
99
173
|
return { finalStep: currentNextStep, stepCount };
|
|
@@ -104,12 +178,15 @@ class BaseAgent {
|
|
|
104
178
|
}
|
|
105
179
|
async validateAgent(agent) {
|
|
106
180
|
if (agent.Status !== 'Active') {
|
|
181
|
+
if (this._agentRun) {
|
|
182
|
+
this._agentRun.ErrorMessage = `Agent '${agent.Name}' is not active. Current status: ${agent.Status}`;
|
|
183
|
+
this._agentRun.Status = 'Failed';
|
|
184
|
+
this._agentRun.Success = false;
|
|
185
|
+
this._agentRun.FinalStep = 'Failed';
|
|
186
|
+
}
|
|
107
187
|
return {
|
|
108
188
|
success: false,
|
|
109
|
-
|
|
110
|
-
errorMessage: `Agent '${agent.Name}' is not active. Current status: ${agent.Status}`,
|
|
111
|
-
agentRun: this._agentRun,
|
|
112
|
-
executionTree: []
|
|
189
|
+
agentRun: this._agentRun
|
|
113
190
|
};
|
|
114
191
|
}
|
|
115
192
|
return null;
|
|
@@ -159,7 +236,10 @@ class BaseAgent {
|
|
|
159
236
|
childPrompt
|
|
160
237
|
};
|
|
161
238
|
}
|
|
162
|
-
async preparePromptParams(
|
|
239
|
+
async preparePromptParams(config, payload, params) {
|
|
240
|
+
const agentType = config.agentType;
|
|
241
|
+
const systemPrompt = config.systemPrompt;
|
|
242
|
+
const childPrompt = config.childPrompt;
|
|
163
243
|
const promptTemplateData = await this.gatherPromptTemplateData(params.agent, params.contextUser, params.data);
|
|
164
244
|
const promptParams = new ai_core_plus_1.AIPromptParams();
|
|
165
245
|
promptParams.prompt = systemPrompt;
|
|
@@ -167,22 +247,28 @@ class BaseAgent {
|
|
|
167
247
|
promptParams.contextUser = params.contextUser;
|
|
168
248
|
promptParams.conversationMessages = params.conversationMessages;
|
|
169
249
|
promptParams.templateMessageRole = 'system';
|
|
250
|
+
promptParams.verbose = params.verbose;
|
|
251
|
+
if (payload) {
|
|
252
|
+
const atInstance = await base_agent_type_1.BaseAgentType.GetAgentTypeInstance(config.agentType);
|
|
253
|
+
await atInstance.InjectPayload(payload, promptParams);
|
|
254
|
+
}
|
|
170
255
|
promptParams.childPrompts = [
|
|
171
256
|
new ai_core_plus_1.ChildPromptParam({
|
|
172
257
|
prompt: childPrompt,
|
|
173
258
|
data: promptTemplateData,
|
|
174
259
|
contextUser: params.contextUser,
|
|
175
260
|
conversationMessages: params.conversationMessages,
|
|
176
|
-
templateMessageRole: 'user'
|
|
261
|
+
templateMessageRole: 'user',
|
|
262
|
+
verbose: params.verbose
|
|
177
263
|
}, agentType.AgentPromptPlaceholder)
|
|
178
264
|
];
|
|
179
265
|
if (params.agent.ModelSelectionMode === 'Agent') {
|
|
180
266
|
promptParams.modelSelectionPrompt = childPrompt;
|
|
181
|
-
|
|
267
|
+
this.logStatus(`🎯 Agent '${params.agent.Name}' configured to use its own prompt for model selection`, true, params);
|
|
182
268
|
}
|
|
183
269
|
if (params.override) {
|
|
184
270
|
promptParams.override = params.override;
|
|
185
|
-
|
|
271
|
+
this.logStatus(`🎯 Using runtime override: ${params.override.modelId || 'model'} ${params.override.vendorId ? `from vendor ${params.override.vendorId}` : ''}`, true, params);
|
|
186
272
|
}
|
|
187
273
|
return promptParams;
|
|
188
274
|
}
|
|
@@ -190,18 +276,11 @@ class BaseAgent {
|
|
|
190
276
|
return await this._promptRunner.ExecutePrompt(promptParams);
|
|
191
277
|
}
|
|
192
278
|
async processNextStep(params, agentType, promptResult) {
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
}
|
|
197
|
-
catch (error) {
|
|
198
|
-
return {
|
|
199
|
-
terminate: false,
|
|
200
|
-
step: 'failed',
|
|
201
|
-
errorMessage: error.message
|
|
202
|
-
};
|
|
203
|
-
}
|
|
279
|
+
this.logStatus(`🤔 Processing next step for agent '${params.agent.Name}' with agent type '${agentType.Name}'`, true, params);
|
|
280
|
+
const agentTypeInstance = await base_agent_type_1.BaseAgentType.GetAgentTypeInstance(agentType);
|
|
281
|
+
this.logStatus(`🎯 Agent type '${agentType.Name}' determining next step`, true, params);
|
|
204
282
|
const nextStep = await agentTypeInstance.DetermineNextStep(promptResult);
|
|
283
|
+
this.logStatus(`📌 Next step determined: ${nextStep.step}${nextStep.terminate ? ' (terminating)' : ''}`, true, params);
|
|
205
284
|
return nextStep;
|
|
206
285
|
}
|
|
207
286
|
createActionResultMessage(actions, results) {
|
|
@@ -261,37 +340,16 @@ class BaseAgent {
|
|
|
261
340
|
throw new Error(`Error gathering context data: ${error.message}`);
|
|
262
341
|
}
|
|
263
342
|
}
|
|
264
|
-
async
|
|
265
|
-
return this.getAgentInstanceWithDriverClass(agentType.DriverClass || agentType.Name);
|
|
266
|
-
}
|
|
267
|
-
async getAgentInstanceWithDriverClass(driverClass) {
|
|
268
|
-
const instance = global_1.MJGlobal.Instance.ClassFactory.CreateInstance(base_agent_type_1.BaseAgentType, driverClass);
|
|
269
|
-
if (!instance) {
|
|
270
|
-
throw new Error(`No implementation found for agent with DriverClass '${driverClass}'. Please ensure the class is registered with the ClassFactory.`);
|
|
271
|
-
}
|
|
272
|
-
return instance;
|
|
273
|
-
}
|
|
274
|
-
async ExecuteSingleAction(params, action, contextUser) {
|
|
343
|
+
async ExecuteSingleAction(params, action, actionEntity, contextUser) {
|
|
275
344
|
try {
|
|
345
|
+
this.logStatus(`⚡ Executing action '${action.name}'`, true, params);
|
|
276
346
|
const actionEngine = actions_1.ActionEngineServer.Instance;
|
|
277
|
-
if (!action.id) {
|
|
278
|
-
throw new Error(`Action ID is required for action: ${action.name || 'unknown'}`);
|
|
279
|
-
}
|
|
280
|
-
const actionEntity = actionEngine.Actions.find(a => a.ID === action.id);
|
|
281
|
-
if (!actionEntity) {
|
|
282
|
-
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
283
|
-
if (!uuidRegex.test(action.id)) {
|
|
284
|
-
throw new Error(`${action.id} is not a valid UUID and must be a UUID representing the Action ID`);
|
|
285
|
-
}
|
|
286
|
-
else {
|
|
287
|
-
throw new Error(`Action with ID ${action.id} not found in the action table`);
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
347
|
const actionParams = Object.entries(action.params || {}).map(([key, value]) => ({
|
|
291
348
|
Name: key,
|
|
292
349
|
Value: value,
|
|
293
350
|
Type: 'Input'
|
|
294
351
|
}));
|
|
352
|
+
this.logStatus(`📥 Action parameters: ${JSON.stringify(action.params)}`, true, params);
|
|
295
353
|
const result = await actionEngine.RunAction({
|
|
296
354
|
Action: actionEntity,
|
|
297
355
|
Params: actionParams,
|
|
@@ -303,28 +361,23 @@ class BaseAgent {
|
|
|
303
361
|
if (!result.Success) {
|
|
304
362
|
throw new Error(`Action '${action.name}' failed: ${result.Message || 'Unknown error'}`);
|
|
305
363
|
}
|
|
364
|
+
this.logStatus(`✅ Action '${action.name}' completed successfully`, true, params);
|
|
306
365
|
return result;
|
|
307
366
|
}
|
|
308
367
|
catch (error) {
|
|
368
|
+
this.logError(error, {
|
|
369
|
+
category: 'ActionExecution',
|
|
370
|
+
metadata: {
|
|
371
|
+
actionName: action.name,
|
|
372
|
+
actionParams: action.params
|
|
373
|
+
}
|
|
374
|
+
});
|
|
309
375
|
throw new Error(`Error executing actions: ${error.message}`);
|
|
310
376
|
}
|
|
311
377
|
}
|
|
312
|
-
async ExecuteSubAgent(params, subAgentRequest) {
|
|
378
|
+
async ExecuteSubAgent(params, subAgentRequest, subAgent, stepEntity, payload) {
|
|
313
379
|
try {
|
|
314
|
-
|
|
315
|
-
if (!subAgentRequest.id) {
|
|
316
|
-
throw new Error('Sub-agent ID is required');
|
|
317
|
-
}
|
|
318
|
-
const subAgent = engine.Agents.find(a => a.ID === subAgentRequest.id);
|
|
319
|
-
if (!subAgent) {
|
|
320
|
-
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
321
|
-
if (!uuidRegex.test(subAgentRequest.id)) {
|
|
322
|
-
throw new Error(`${subAgentRequest.id} is not a valid UUID and must be a UUID representing the Agent ID`);
|
|
323
|
-
}
|
|
324
|
-
else {
|
|
325
|
-
throw new Error(`Sub-agent with ID ${subAgentRequest.id} not found in the agent table`);
|
|
326
|
-
}
|
|
327
|
-
}
|
|
380
|
+
this.logStatus(`🤖 Executing sub-agent '${subAgentRequest.name}'`, true, params);
|
|
328
381
|
const runner = new AgentRunner_1.AgentRunner();
|
|
329
382
|
const subAgentMessages = [
|
|
330
383
|
{
|
|
@@ -332,6 +385,10 @@ class BaseAgent {
|
|
|
332
385
|
content: subAgentRequest.message
|
|
333
386
|
}
|
|
334
387
|
];
|
|
388
|
+
this.logStatus(`📨 Sub-agent message: "${subAgentRequest.message}"`, true, params);
|
|
389
|
+
if (subAgentRequest.templateParameters) {
|
|
390
|
+
this.logStatus(`📎 Template parameters: ${JSON.stringify(subAgentRequest.templateParameters)}`, true, params);
|
|
391
|
+
}
|
|
335
392
|
const result = await runner.RunAgent({
|
|
336
393
|
agent: subAgent,
|
|
337
394
|
conversationMessages: subAgentMessages,
|
|
@@ -339,24 +396,34 @@ class BaseAgent {
|
|
|
339
396
|
cancellationToken: params.cancellationToken,
|
|
340
397
|
onProgress: params.onProgress,
|
|
341
398
|
onStreaming: params.onStreaming,
|
|
342
|
-
parentAgentHierarchy: this.
|
|
343
|
-
parentDepth: this.
|
|
399
|
+
parentAgentHierarchy: this._agentHierarchy,
|
|
400
|
+
parentDepth: this._depth,
|
|
344
401
|
parentRun: this._agentRun,
|
|
402
|
+
payload: payload,
|
|
345
403
|
data: subAgentRequest.templateParameters,
|
|
346
|
-
context: params.context
|
|
404
|
+
context: params.context,
|
|
405
|
+
verbose: params.verbose
|
|
347
406
|
});
|
|
348
407
|
if (!result.success) {
|
|
349
|
-
throw new Error(`Sub-agent '${subAgentRequest.name}' failed: ${result.
|
|
408
|
+
throw new Error(`Sub-agent '${subAgentRequest.name}' failed: ${result.agentRun?.ErrorMessage || 'Unknown error'}`);
|
|
350
409
|
}
|
|
410
|
+
this.logStatus(`✅ Sub-agent '${subAgentRequest.name}' completed successfully`, true, params);
|
|
351
411
|
return result;
|
|
352
412
|
}
|
|
353
413
|
catch (error) {
|
|
414
|
+
this.logError(error, {
|
|
415
|
+
category: 'SubAgentExecution',
|
|
416
|
+
metadata: {
|
|
417
|
+
agentName: params.agent.Name,
|
|
418
|
+
subAgentName: subAgentRequest.name,
|
|
419
|
+
message: subAgentRequest.message
|
|
420
|
+
}
|
|
421
|
+
});
|
|
354
422
|
throw new Error(`Error executing sub-agent: ${error.message}`);
|
|
355
423
|
}
|
|
356
424
|
}
|
|
357
425
|
formatSubAgentDetails(subAgents) {
|
|
358
426
|
return JSON.stringify(subAgents.map(sa => ({
|
|
359
|
-
ID: sa.ID,
|
|
360
427
|
Name: sa.Name,
|
|
361
428
|
Description: sa.Description,
|
|
362
429
|
Type: sa.TypeID ? this.getAgentTypeName(sa.TypeID) : 'Unknown',
|
|
@@ -390,7 +457,6 @@ class BaseAgent {
|
|
|
390
457
|
}
|
|
391
458
|
formatActionDetails(actions) {
|
|
392
459
|
return JSON.stringify(actions.map(action => ({
|
|
393
|
-
ID: action.ID,
|
|
394
460
|
Name: action.Name,
|
|
395
461
|
Description: action.Description,
|
|
396
462
|
Parameters: {
|
|
@@ -405,7 +471,6 @@ class BaseAgent {
|
|
|
405
471
|
Code: rc.ResultCode,
|
|
406
472
|
IsSuccess: rc.IsSuccess,
|
|
407
473
|
Description: rc.Description || 'No description provided',
|
|
408
|
-
Usage: this.inferResultCodeUsage(rc.ResultCode, rc.IsSuccess)
|
|
409
474
|
})),
|
|
410
475
|
Category: action.CategoryID ? this.getActionCategoryName(action.CategoryID) : null,
|
|
411
476
|
Status: action.Status
|
|
@@ -432,34 +497,6 @@ class BaseAgent {
|
|
|
432
497
|
getActionCategoryName(categoryID) {
|
|
433
498
|
return 'General';
|
|
434
499
|
}
|
|
435
|
-
inferResultCodeUsage(resultCode, isSuccess) {
|
|
436
|
-
if (resultCode === 'SUCCESS') {
|
|
437
|
-
return 'Returned when the action completes successfully';
|
|
438
|
-
}
|
|
439
|
-
else if (resultCode === 'FAILED') {
|
|
440
|
-
return 'Generic failure - check error message for details';
|
|
441
|
-
}
|
|
442
|
-
else if (resultCode.includes('MISSING_PARAMETERS')) {
|
|
443
|
-
return 'Returned when required parameters are not provided';
|
|
444
|
-
}
|
|
445
|
-
else if (resultCode.includes('INVALID')) {
|
|
446
|
-
return 'Returned when input validation fails';
|
|
447
|
-
}
|
|
448
|
-
else if (resultCode.includes('NOT_FOUND')) {
|
|
449
|
-
return 'Returned when the requested resource cannot be found';
|
|
450
|
-
}
|
|
451
|
-
else if (resultCode.includes('TIMEOUT')) {
|
|
452
|
-
return 'Returned when the operation times out';
|
|
453
|
-
}
|
|
454
|
-
else if (resultCode.includes('PERMISSION') || resultCode.includes('UNAUTHORIZED')) {
|
|
455
|
-
return 'Returned when permission is denied';
|
|
456
|
-
}
|
|
457
|
-
else {
|
|
458
|
-
return isSuccess
|
|
459
|
-
? 'Specific success condition - see description'
|
|
460
|
-
: 'Specific error condition - see description';
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
500
|
async initializeAgentRun(params) {
|
|
464
501
|
this._agentRun = await this._metadata.GetEntityObject('MJ: AI Agent Runs', params.contextUser);
|
|
465
502
|
this._agentRun.AgentID = params.agent.ID;
|
|
@@ -471,68 +508,21 @@ class BaseAgent {
|
|
|
471
508
|
const errorMessage = JSON.stringify((0, global_1.CopyScalarsAndArrays)(this._agentRun.LatestResult));
|
|
472
509
|
throw new Error(`Failed to create agent run record: Details: ${errorMessage}`);
|
|
473
510
|
}
|
|
474
|
-
this.
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
? [...params.parentAgentHierarchy, params.agent.Name || 'Unknown Agent']
|
|
479
|
-
: [params.agent.Name || 'Unknown Agent'],
|
|
480
|
-
depth: params.parentDepth !== undefined ? params.parentDepth + 1 : 0,
|
|
481
|
-
conversationId: undefined,
|
|
482
|
-
userId: params.contextUser?.ID,
|
|
483
|
-
agentState: {}
|
|
484
|
-
};
|
|
485
|
-
this._executionChain = [];
|
|
511
|
+
this._agentHierarchy = params.parentAgentHierarchy
|
|
512
|
+
? [...params.parentAgentHierarchy, params.agent.Name || 'Unknown Agent']
|
|
513
|
+
: [params.agent.Name || 'Unknown Agent'];
|
|
514
|
+
this._depth = params.parentDepth !== undefined ? params.parentDepth + 1 : 0;
|
|
486
515
|
this._allProgressSteps = [];
|
|
487
516
|
}
|
|
488
517
|
async validateAgentWithTracking(agent, contextUser) {
|
|
489
|
-
const startTime = new Date();
|
|
490
518
|
try {
|
|
491
519
|
const validationResult = await this.validateAgent(agent);
|
|
492
520
|
if (validationResult) {
|
|
493
|
-
const stepEntity = await this.createStepEntity('
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
validationTarget: 'agent configuration',
|
|
497
|
-
result: { valid: false, errors: [validationResult.errorMessage || 'Validation failed'] }
|
|
498
|
-
};
|
|
499
|
-
const nextStepDecision = {
|
|
500
|
-
decision: 'failed',
|
|
501
|
-
reasoning: 'Agent validation failed',
|
|
502
|
-
nextStepDetails: { type: 'complete' }
|
|
503
|
-
};
|
|
504
|
-
this._executionChain.push({
|
|
505
|
-
stepEntity,
|
|
506
|
-
executionType: 'validation',
|
|
507
|
-
executionResult,
|
|
508
|
-
nextStepDecision,
|
|
509
|
-
startTime,
|
|
510
|
-
endTime: new Date(),
|
|
511
|
-
durationMs: new Date().getTime() - startTime.getTime()
|
|
512
|
-
});
|
|
513
|
-
await this.finalizeStepEntity(stepEntity, false, validationResult.errorMessage);
|
|
514
|
-
return await this.createFailureResult(validationResult.errorMessage || 'Validation failed', contextUser);
|
|
521
|
+
const stepEntity = await this.createStepEntity('Validation', 'Agent Validation', contextUser);
|
|
522
|
+
await this.finalizeStepEntity(stepEntity, false, validationResult.agentRun?.ErrorMessage);
|
|
523
|
+
return await this.createFailureResult(validationResult.agentRun?.ErrorMessage || 'Validation failed', contextUser);
|
|
515
524
|
}
|
|
516
|
-
const stepEntity = await this.createStepEntity('
|
|
517
|
-
const executionResult = {
|
|
518
|
-
type: 'validation',
|
|
519
|
-
validationTarget: 'agent configuration',
|
|
520
|
-
result: { valid: true }
|
|
521
|
-
};
|
|
522
|
-
const nextStepDecision = {
|
|
523
|
-
decision: 'success',
|
|
524
|
-
reasoning: 'Agent validation passed',
|
|
525
|
-
nextStepDetails: { type: 'prompt', promptId: agent.ID, promptName: 'Initial Prompt' }
|
|
526
|
-
};
|
|
527
|
-
this._executionChain.push({
|
|
528
|
-
stepEntity,
|
|
529
|
-
executionType: 'validation',
|
|
530
|
-
executionResult,
|
|
531
|
-
nextStepDecision,
|
|
532
|
-
startTime,
|
|
533
|
-
endTime: new Date(),
|
|
534
|
-
durationMs: new Date().getTime() - startTime.getTime()
|
|
535
|
-
});
|
|
525
|
+
const stepEntity = await this.createStepEntity('Validation', 'Agent Validation', contextUser);
|
|
536
526
|
await this.finalizeStepEntity(stepEntity, true);
|
|
537
527
|
return null;
|
|
538
528
|
}
|
|
@@ -543,7 +533,7 @@ class BaseAgent {
|
|
|
543
533
|
async createStepEntity(stepType, stepName, contextUser, targetId, inputData, targetLogId) {
|
|
544
534
|
const stepEntity = await this._metadata.GetEntityObject('MJ: AI Agent Run Steps', contextUser);
|
|
545
535
|
stepEntity.AgentRunID = this._agentRun.ID;
|
|
546
|
-
stepEntity.StepNumber = this.
|
|
536
|
+
stepEntity.StepNumber = (this._agentRun.Steps?.length || 0) + 1;
|
|
547
537
|
stepEntity.StepType = stepType;
|
|
548
538
|
stepEntity.StepName = this.formatHierarchicalMessage(stepName);
|
|
549
539
|
if (targetId && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(targetId)) {
|
|
@@ -559,8 +549,8 @@ class BaseAgent {
|
|
|
559
549
|
stepEntity.InputData = JSON.stringify({
|
|
560
550
|
...inputData,
|
|
561
551
|
context: {
|
|
562
|
-
agentHierarchy: this.
|
|
563
|
-
depth: this.
|
|
552
|
+
agentHierarchy: this._agentHierarchy,
|
|
553
|
+
depth: this._depth,
|
|
564
554
|
stepNumber: stepEntity.StepNumber
|
|
565
555
|
}
|
|
566
556
|
});
|
|
@@ -568,7 +558,9 @@ class BaseAgent {
|
|
|
568
558
|
if (!await stepEntity.Save()) {
|
|
569
559
|
throw new Error(`Failed to create agent run step record: ${JSON.stringify(stepEntity.LatestResult)}`);
|
|
570
560
|
}
|
|
571
|
-
this.
|
|
561
|
+
if (this._agentRun) {
|
|
562
|
+
this._agentRun.Steps.push(stepEntity);
|
|
563
|
+
}
|
|
572
564
|
return stepEntity;
|
|
573
565
|
}
|
|
574
566
|
async finalizeStepEntity(stepEntity, success, errorMessage, outputData) {
|
|
@@ -591,45 +583,64 @@ class BaseAgent {
|
|
|
591
583
|
}
|
|
592
584
|
}
|
|
593
585
|
formatHierarchicalMessage(baseMessage) {
|
|
594
|
-
if (this.
|
|
595
|
-
const breadcrumb = this.
|
|
586
|
+
if (this._depth > 0) {
|
|
587
|
+
const breadcrumb = this._agentHierarchy
|
|
596
588
|
.slice(1)
|
|
597
589
|
.join(' → ');
|
|
598
590
|
return breadcrumb ? `${breadcrumb}: ${baseMessage}` : baseMessage;
|
|
599
591
|
}
|
|
600
592
|
return baseMessage;
|
|
601
593
|
}
|
|
594
|
+
getNextStepReasoning(nextStep) {
|
|
595
|
+
switch (nextStep.step) {
|
|
596
|
+
case 'Success':
|
|
597
|
+
return 'Agent completed task successfully';
|
|
598
|
+
case 'Failed':
|
|
599
|
+
return nextStep.errorMessage || 'Agent execution failed';
|
|
600
|
+
case 'Retry':
|
|
601
|
+
return nextStep.retryReason || 'Retrying with updated context';
|
|
602
|
+
case 'Sub-Agent':
|
|
603
|
+
return `Delegating to sub-agent: ${nextStep.subAgent?.name || 'Unknown'}`;
|
|
604
|
+
case 'Actions':
|
|
605
|
+
const actionCount = nextStep.actions?.length || 0;
|
|
606
|
+
return `Executing ${actionCount} action${actionCount !== 1 ? 's' : ''}`;
|
|
607
|
+
case 'Chat':
|
|
608
|
+
return 'Requesting user input';
|
|
609
|
+
default:
|
|
610
|
+
return 'Unknown decision';
|
|
611
|
+
}
|
|
612
|
+
}
|
|
602
613
|
async executeNextStep(params, config, previousDecision) {
|
|
603
614
|
if (!previousDecision) {
|
|
604
615
|
return await this.executePromptStep(params, config);
|
|
605
616
|
}
|
|
606
617
|
switch (previousDecision.step) {
|
|
607
|
-
case '
|
|
618
|
+
case 'Retry':
|
|
608
619
|
return await this.executePromptStep(params, config, previousDecision);
|
|
609
|
-
case '
|
|
610
|
-
return await this.executeSubAgentStep(params, previousDecision
|
|
611
|
-
case '
|
|
612
|
-
return await this.executeActionsStep(params, previousDecision
|
|
613
|
-
case '
|
|
614
|
-
return await this.executeChatStep(params, previousDecision
|
|
615
|
-
case '
|
|
620
|
+
case 'Sub-Agent':
|
|
621
|
+
return await this.executeSubAgentStep(params, previousDecision);
|
|
622
|
+
case 'Actions':
|
|
623
|
+
return await this.executeActionsStep(params, previousDecision);
|
|
624
|
+
case 'Chat':
|
|
625
|
+
return await this.executeChatStep(params, previousDecision);
|
|
626
|
+
case 'Success':
|
|
616
627
|
const pd = previousDecision;
|
|
617
|
-
if (pd.
|
|
628
|
+
if (pd.payload?.taskComplete === true && previousDecision.terminate) {
|
|
618
629
|
return {
|
|
619
630
|
terminate: true,
|
|
620
|
-
step: '
|
|
621
|
-
|
|
631
|
+
step: 'Success',
|
|
632
|
+
payload: previousDecision.payload
|
|
622
633
|
};
|
|
623
634
|
}
|
|
624
635
|
else {
|
|
625
636
|
return await this.executePromptStep(params, config, previousDecision);
|
|
626
637
|
}
|
|
627
|
-
case '
|
|
638
|
+
case 'Failed':
|
|
628
639
|
if (previousDecision.terminate) {
|
|
629
640
|
return {
|
|
630
641
|
terminate: true,
|
|
631
|
-
step: '
|
|
632
|
-
|
|
642
|
+
step: 'Failed',
|
|
643
|
+
payload: previousDecision.payload
|
|
633
644
|
};
|
|
634
645
|
}
|
|
635
646
|
else {
|
|
@@ -639,24 +650,22 @@ class BaseAgent {
|
|
|
639
650
|
throw new Error(`Unsupported next step: ${previousDecision.step}`);
|
|
640
651
|
}
|
|
641
652
|
}
|
|
642
|
-
async executePromptStep(params, config,
|
|
643
|
-
const startTime = new Date();
|
|
653
|
+
async executePromptStep(params, config, previousDecision) {
|
|
644
654
|
const inputData = {
|
|
645
655
|
promptId: config.childPrompt?.ID,
|
|
646
656
|
promptName: config.childPrompt?.Name,
|
|
647
|
-
isRetry: !!
|
|
648
|
-
retryContext:
|
|
649
|
-
reason:
|
|
650
|
-
instructions:
|
|
657
|
+
isRetry: !!previousDecision,
|
|
658
|
+
retryContext: previousDecision ? {
|
|
659
|
+
reason: previousDecision.retryReason,
|
|
660
|
+
instructions: previousDecision.retryInstructions
|
|
651
661
|
} : undefined,
|
|
652
662
|
conversationMessages: params.conversationMessages,
|
|
653
|
-
agentState: this._runContext?.agentState
|
|
654
663
|
};
|
|
655
|
-
const stepEntity = await this.createStepEntity('
|
|
664
|
+
const stepEntity = await this.createStepEntity('Prompt', 'Execute Agent Prompt', params.contextUser, config.childPrompt?.ID, inputData);
|
|
656
665
|
try {
|
|
657
|
-
const isRetry = !!
|
|
666
|
+
const isRetry = !!previousDecision;
|
|
658
667
|
const promptMessage = isRetry
|
|
659
|
-
? `Running ${params.agent.Name} with context from ${
|
|
668
|
+
? `Running ${params.agent.Name} with context from ${previousDecision.retryReason || 'previous actions'}`
|
|
660
669
|
: `Running ${params.agent.Name}'s initial prompt...`;
|
|
661
670
|
params.onProgress?.({
|
|
662
671
|
step: 'prompt_execution',
|
|
@@ -669,7 +678,11 @@ class BaseAgent {
|
|
|
669
678
|
},
|
|
670
679
|
displayMode: 'live'
|
|
671
680
|
});
|
|
672
|
-
const
|
|
681
|
+
const payload = previousDecision?.payload || params.payload;
|
|
682
|
+
if (stepEntity && payload) {
|
|
683
|
+
stepEntity.PayloadAtStart = JSON.stringify(payload);
|
|
684
|
+
}
|
|
685
|
+
const promptParams = await this.preparePromptParams(config, payload, params);
|
|
673
686
|
promptParams.cancellationToken = params.cancellationToken;
|
|
674
687
|
promptParams.onStreaming = params.onStreaming ? (chunk) => {
|
|
675
688
|
params.onStreaming({
|
|
@@ -681,7 +694,7 @@ class BaseAgent {
|
|
|
681
694
|
const promptResult = await this.executePrompt(promptParams);
|
|
682
695
|
if (promptResult.promptRun?.ID) {
|
|
683
696
|
stepEntity.TargetLogID = promptResult.promptRun.ID;
|
|
684
|
-
|
|
697
|
+
stepEntity.PromptRun = promptResult.promptRun;
|
|
685
698
|
}
|
|
686
699
|
if (params.cancellationToken?.aborted) {
|
|
687
700
|
await this.finalizeStepEntity(stepEntity, false, 'Cancelled during prompt execution');
|
|
@@ -689,16 +702,10 @@ class BaseAgent {
|
|
|
689
702
|
return {
|
|
690
703
|
...cancelledResult,
|
|
691
704
|
terminate: true,
|
|
692
|
-
step:
|
|
693
|
-
|
|
705
|
+
step: 'Failed',
|
|
706
|
+
payload: cancelledResult.payload,
|
|
694
707
|
};
|
|
695
708
|
}
|
|
696
|
-
const executionResult = {
|
|
697
|
-
type: 'prompt',
|
|
698
|
-
promptId: config.childPrompt.ID,
|
|
699
|
-
promptName: config.childPrompt.Name,
|
|
700
|
-
result: promptResult
|
|
701
|
-
};
|
|
702
709
|
params.onProgress?.({
|
|
703
710
|
step: 'decision_processing',
|
|
704
711
|
percentage: 70,
|
|
@@ -706,20 +713,6 @@ class BaseAgent {
|
|
|
706
713
|
displayMode: 'both'
|
|
707
714
|
});
|
|
708
715
|
const nextStep = await this.processNextStep(params, config.agentType, promptResult);
|
|
709
|
-
const nextStepDecision = {
|
|
710
|
-
decision: nextStep.step,
|
|
711
|
-
reasoning: this.getNextStepReasoning(nextStep),
|
|
712
|
-
nextStepDetails: this.getNextStepDetails(nextStep)
|
|
713
|
-
};
|
|
714
|
-
this._executionChain.push({
|
|
715
|
-
stepEntity,
|
|
716
|
-
executionType: 'prompt',
|
|
717
|
-
executionResult,
|
|
718
|
-
nextStepDecision,
|
|
719
|
-
startTime,
|
|
720
|
-
endTime: new Date(),
|
|
721
|
-
durationMs: new Date().getTime() - startTime.getTime()
|
|
722
|
-
});
|
|
723
716
|
const outputData = {
|
|
724
717
|
promptResult: {
|
|
725
718
|
success: promptResult.success,
|
|
@@ -730,14 +723,21 @@ class BaseAgent {
|
|
|
730
723
|
},
|
|
731
724
|
nextStep: {
|
|
732
725
|
decision: nextStep.step,
|
|
733
|
-
reasoning:
|
|
726
|
+
reasoning: this.getNextStepReasoning(nextStep),
|
|
727
|
+
payload: nextStep.payload
|
|
734
728
|
}
|
|
735
729
|
};
|
|
730
|
+
if (stepEntity && nextStep.payload) {
|
|
731
|
+
stepEntity.PayloadAtEnd = JSON.stringify(nextStep.payload);
|
|
732
|
+
}
|
|
733
|
+
if (this._agentRun && nextStep.payload) {
|
|
734
|
+
this._agentRun.FinalPayloadObject = nextStep.payload;
|
|
735
|
+
}
|
|
736
736
|
await this.finalizeStepEntity(stepEntity, promptResult.success, promptResult.success ? undefined : promptResult.errorMessage, outputData);
|
|
737
|
-
if (nextStep.step === '
|
|
737
|
+
if (nextStep.step === 'Chat') {
|
|
738
738
|
return { ...nextStep, terminate: true };
|
|
739
739
|
}
|
|
740
|
-
else if (nextStep.step === '
|
|
740
|
+
else if (nextStep.step === 'Success' || nextStep.step === 'Failed') {
|
|
741
741
|
return { ...nextStep, terminate: true };
|
|
742
742
|
}
|
|
743
743
|
else {
|
|
@@ -749,12 +749,13 @@ class BaseAgent {
|
|
|
749
749
|
const errString = error?.message || error || 'Unknown error';
|
|
750
750
|
return {
|
|
751
751
|
errorMessage: `Prompt execution failed: ${errString}`,
|
|
752
|
-
step: '
|
|
752
|
+
step: 'Failed',
|
|
753
753
|
terminate: false,
|
|
754
754
|
};
|
|
755
755
|
}
|
|
756
756
|
}
|
|
757
|
-
async executeSubAgentStep(params,
|
|
757
|
+
async executeSubAgentStep(params, previousDecision) {
|
|
758
|
+
const subAgentRequest = previousDecision.subAgent;
|
|
758
759
|
if (params.cancellationToken?.aborted) {
|
|
759
760
|
throw new Error('Cancelled before sub-agent execution');
|
|
760
761
|
}
|
|
@@ -763,7 +764,7 @@ class BaseAgent {
|
|
|
763
764
|
percentage: 60,
|
|
764
765
|
message: this.formatHierarchicalMessage(`Delegating to ${subAgentRequest.name} agent`),
|
|
765
766
|
metadata: {
|
|
766
|
-
|
|
767
|
+
agentName: params.agent.Name,
|
|
767
768
|
subAgentName: subAgentRequest.name,
|
|
768
769
|
reason: subAgentRequest.message
|
|
769
770
|
}
|
|
@@ -772,69 +773,79 @@ class BaseAgent {
|
|
|
772
773
|
role: 'assistant',
|
|
773
774
|
content: `I'm delegating this task to the "${subAgentRequest.name}" agent.\n\nReason: ${subAgentRequest.message}`
|
|
774
775
|
});
|
|
775
|
-
const startTime = new Date();
|
|
776
776
|
const inputData = {
|
|
777
|
-
|
|
777
|
+
agentName: params.agent.Name,
|
|
778
778
|
subAgentName: subAgentRequest.name,
|
|
779
779
|
message: subAgentRequest.message,
|
|
780
780
|
terminateAfter: subAgentRequest.terminateAfter,
|
|
781
781
|
conversationMessages: params.conversationMessages,
|
|
782
|
-
parentAgentHierarchy: this.
|
|
782
|
+
parentAgentHierarchy: this._agentHierarchy
|
|
783
783
|
};
|
|
784
|
-
const
|
|
784
|
+
const subAgentEntity = aiengine_1.AIEngine.Instance.Agents.find(a => a.Name === subAgentRequest.name &&
|
|
785
|
+
a.ParentID === params.agent.ID);
|
|
786
|
+
if (!subAgentEntity) {
|
|
787
|
+
throw new Error(`Sub-agent '${subAgentRequest.name}' not found`);
|
|
788
|
+
}
|
|
789
|
+
const stepEntity = await this.createStepEntity('Sub-Agent', `Execute Sub-Agent: ${subAgentRequest.name}`, params.contextUser, subAgentEntity.ID, inputData);
|
|
785
790
|
try {
|
|
786
|
-
|
|
791
|
+
let downstreamPaths = ['*'];
|
|
792
|
+
let upstreamPaths = ['*'];
|
|
793
|
+
try {
|
|
794
|
+
if (subAgentEntity.PayloadDownstreamPaths) {
|
|
795
|
+
downstreamPaths = JSON.parse(subAgentEntity.PayloadDownstreamPaths);
|
|
796
|
+
}
|
|
797
|
+
if (subAgentEntity.PayloadUpstreamPaths) {
|
|
798
|
+
upstreamPaths = JSON.parse(subAgentEntity.PayloadUpstreamPaths);
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
catch (parseError) {
|
|
802
|
+
this.logError(`Failed to parse payload paths for sub-agent ${subAgentRequest.name}: ${parseError.message}`, {
|
|
803
|
+
category: 'SubAgentExecution',
|
|
804
|
+
metadata: {
|
|
805
|
+
agentName: params.agent.Name,
|
|
806
|
+
subAgentName: subAgentRequest.name,
|
|
807
|
+
subAgentId: subAgentEntity.ID,
|
|
808
|
+
downstreamPaths: subAgentEntity.PayloadDownstreamPaths,
|
|
809
|
+
upstreamPaths: subAgentEntity.PayloadUpstreamPaths
|
|
810
|
+
}
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
const downstreamPayload = this._payloadManager.extractDownstreamPayload(subAgentRequest.name, previousDecision.payload, downstreamPaths);
|
|
814
|
+
stepEntity.PayloadAtStart = JSON.stringify(previousDecision.payload);
|
|
815
|
+
const subAgentResult = await this.ExecuteSubAgent(params, subAgentRequest, subAgentEntity, stepEntity, downstreamPayload);
|
|
816
|
+
const mergedPayload = this._payloadManager.mergeUpstreamPayload(subAgentRequest.name, previousDecision.payload, subAgentResult.payload, upstreamPaths);
|
|
787
817
|
if (subAgentResult.agentRun?.ID) {
|
|
788
818
|
stepEntity.TargetLogID = subAgentResult.agentRun.ID;
|
|
789
|
-
|
|
819
|
+
stepEntity.SubAgentRun = subAgentResult.agentRun;
|
|
820
|
+
stepEntity.PayloadAtEnd = JSON.stringify(mergedPayload);
|
|
790
821
|
}
|
|
791
822
|
if (params.cancellationToken?.aborted) {
|
|
792
823
|
await this.finalizeStepEntity(stepEntity, false, 'Cancelled during sub-agent execution');
|
|
793
824
|
throw new Error('Cancelled during sub-agent execution');
|
|
794
825
|
}
|
|
795
|
-
const executionResult = {
|
|
796
|
-
type: 'sub-agent',
|
|
797
|
-
subAgentId: subAgentRequest.id,
|
|
798
|
-
subAgentName: subAgentRequest.name,
|
|
799
|
-
result: subAgentResult
|
|
800
|
-
};
|
|
801
826
|
this._subAgentRuns.push(subAgentResult);
|
|
802
827
|
const shouldTerminate = subAgentRequest.terminateAfter;
|
|
803
|
-
const nextStepType = subAgentResult.returnValue?.step || 'retry';
|
|
804
|
-
const nextStepDecision = {
|
|
805
|
-
decision: shouldTerminate ? 'success' : 'retry',
|
|
806
|
-
reasoning: shouldTerminate ? 'Sub-agent execution completed, terminating as requested' : 'Sub-agent completed, continuing execution',
|
|
807
|
-
nextStepDetails: { type: nextStepType, returnValue: subAgentResult.returnValue }
|
|
808
|
-
};
|
|
809
|
-
this._executionChain.push({
|
|
810
|
-
stepEntity,
|
|
811
|
-
executionType: 'sub-agent',
|
|
812
|
-
executionResult,
|
|
813
|
-
nextStepDecision,
|
|
814
|
-
startTime,
|
|
815
|
-
endTime: new Date(),
|
|
816
|
-
durationMs: new Date().getTime() - startTime.getTime()
|
|
817
|
-
});
|
|
818
828
|
const outputData = {
|
|
819
829
|
subAgentResult: {
|
|
820
830
|
success: subAgentResult.success,
|
|
821
|
-
finalStep: subAgentResult.
|
|
822
|
-
|
|
823
|
-
errorMessage: subAgentResult.
|
|
831
|
+
finalStep: subAgentResult.agentRun?.FinalStep,
|
|
832
|
+
payload: subAgentResult.payload,
|
|
833
|
+
errorMessage: subAgentResult.agentRun?.ErrorMessage,
|
|
824
834
|
agentRunId: subAgentResult.agentRun?.ID,
|
|
825
|
-
stepCount:
|
|
835
|
+
stepCount: subAgentResult.agentRun?.Steps?.length || 0
|
|
826
836
|
},
|
|
827
837
|
shouldTerminate: shouldTerminate,
|
|
828
|
-
nextStep:
|
|
838
|
+
nextStep: shouldTerminate ? 'success' : 'retry'
|
|
829
839
|
};
|
|
830
|
-
await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.
|
|
840
|
+
await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
|
|
831
841
|
const subAgentSummary = {
|
|
842
|
+
agentName: params.agent.Name,
|
|
832
843
|
subAgentName: subAgentRequest.name,
|
|
833
|
-
subAgentId:
|
|
844
|
+
subAgentId: subAgentEntity.ID,
|
|
834
845
|
success: subAgentResult.success,
|
|
835
|
-
finalStep: subAgentResult.
|
|
836
|
-
|
|
837
|
-
errorMessage: subAgentResult.
|
|
846
|
+
finalStep: subAgentResult.agentRun?.FinalStep,
|
|
847
|
+
payload: subAgentResult.payload,
|
|
848
|
+
errorMessage: subAgentResult.agentRun?.ErrorMessage || null
|
|
838
849
|
};
|
|
839
850
|
const resultMessage = subAgentResult.success
|
|
840
851
|
? `Sub-agent completed successfully:\n${JSON.stringify(subAgentSummary, null, 2)}`
|
|
@@ -843,42 +854,37 @@ class BaseAgent {
|
|
|
843
854
|
role: 'user',
|
|
844
855
|
content: resultMessage
|
|
845
856
|
});
|
|
857
|
+
if (this._agentRun) {
|
|
858
|
+
this._agentRun.FinalPayloadObject = mergedPayload;
|
|
859
|
+
}
|
|
846
860
|
return {
|
|
847
861
|
...subAgentResult,
|
|
848
|
-
step: subAgentResult.success ? '
|
|
849
|
-
terminate: shouldTerminate
|
|
862
|
+
step: subAgentResult.success ? 'Success' : 'Failed',
|
|
863
|
+
terminate: shouldTerminate,
|
|
864
|
+
payload: mergedPayload
|
|
850
865
|
};
|
|
851
866
|
}
|
|
852
867
|
catch (error) {
|
|
853
868
|
await this.finalizeStepEntity(stepEntity, false, error.message);
|
|
854
869
|
return {
|
|
855
870
|
errorMessage: `Sub-agent execution failed: ${error.message}`,
|
|
856
|
-
step: '
|
|
871
|
+
step: 'Failed',
|
|
857
872
|
terminate: false,
|
|
858
873
|
};
|
|
859
874
|
}
|
|
860
875
|
}
|
|
861
|
-
async executeActionsStep(params,
|
|
876
|
+
async executeActionsStep(params, previousDecision) {
|
|
862
877
|
try {
|
|
878
|
+
const actions = previousDecision.actions || [];
|
|
863
879
|
if (params.cancellationToken?.aborted) {
|
|
864
880
|
throw new Error('Cancelled before action execution');
|
|
865
881
|
}
|
|
866
|
-
const actionEntities = actions.map(action => {
|
|
867
|
-
const actionEntity = actions_1.ActionEngineServer.Instance.Actions.find(a => a.ID.trim().toLowerCase() === action.id.trim().toLowerCase());
|
|
868
|
-
if (!actionEntity) {
|
|
869
|
-
throw new Error(`Action with ID ${action.id} and Name "${action.name}" not found`);
|
|
870
|
-
}
|
|
871
|
-
if (actionEntity.Name.trim().toLowerCase() !== action.name.trim().toLowerCase()) {
|
|
872
|
-
throw new Error(`Action with ID ${action.id} has a different name "${actionEntity.Name}" than provided "${action.name}"`);
|
|
873
|
-
}
|
|
874
|
-
return actionEntity;
|
|
875
|
-
});
|
|
876
882
|
let progressMessage;
|
|
877
883
|
if (actions.length === 1) {
|
|
878
|
-
const
|
|
879
|
-
progressMessage = `Executing action: **${
|
|
880
|
-
if (
|
|
881
|
-
const paramsList = Object.entries(
|
|
884
|
+
const aa = actions[0];
|
|
885
|
+
progressMessage = `Executing action: **${aa.name}**`;
|
|
886
|
+
if (aa.params && Object.keys(aa.params).length > 0) {
|
|
887
|
+
const paramsList = Object.entries(aa.params)
|
|
882
888
|
.map(([key, value]) => {
|
|
883
889
|
const displayValue = typeof value === 'object'
|
|
884
890
|
? JSON.stringify(value, null, 2)
|
|
@@ -891,10 +897,10 @@ class BaseAgent {
|
|
|
891
897
|
}
|
|
892
898
|
else {
|
|
893
899
|
progressMessage = `Executing ${actions.length} actions:`;
|
|
894
|
-
actions.forEach(
|
|
895
|
-
progressMessage += `\n\n• **${
|
|
896
|
-
if (
|
|
897
|
-
const paramsList = Object.entries(
|
|
900
|
+
actions.forEach(aa => {
|
|
901
|
+
progressMessage += `\n\n• **${aa.name}**`;
|
|
902
|
+
if (aa.params && Object.keys(aa.params).length > 0) {
|
|
903
|
+
const paramsList = Object.entries(aa.params)
|
|
898
904
|
.map(([key, value]) => {
|
|
899
905
|
const displayValue = typeof value === 'object'
|
|
900
906
|
? JSON.stringify(value, null, 2)
|
|
@@ -923,36 +929,21 @@ class BaseAgent {
|
|
|
923
929
|
role: 'assistant',
|
|
924
930
|
content: actionMessage
|
|
925
931
|
});
|
|
926
|
-
const
|
|
927
|
-
|
|
928
|
-
|
|
932
|
+
const actionEngine = actions_1.ActionEngineServer.Instance;
|
|
933
|
+
const agentActions = aiengine_1.AIEngine.Instance.AgentActions.filter(aa => aa.AgentID === params.agent.ID);
|
|
934
|
+
const actionPromises = actions.map(async (aa) => {
|
|
935
|
+
const actionEntity = actionEngine.Actions.find(a => a.Name === aa.name && agentActions.some(aa => aa.ActionID === a.ID));
|
|
936
|
+
if (!actionEntity) {
|
|
937
|
+
throw new Error(`Action "${aa.name}" Not Found for Agent "${params.agent.Name}"`);
|
|
938
|
+
}
|
|
939
|
+
const stepEntity = await this.createStepEntity('Actions', `Execute Action: ${aa.name}`, params.contextUser, actionEntity.ID);
|
|
929
940
|
let actionResult;
|
|
930
941
|
try {
|
|
931
|
-
actionResult = await this.ExecuteSingleAction(params,
|
|
942
|
+
actionResult = await this.ExecuteSingleAction(params, aa, actionEntity, params.contextUser);
|
|
932
943
|
if (actionResult.LogEntry?.ID) {
|
|
933
944
|
stepEntity.TargetLogID = actionResult.LogEntry.ID;
|
|
934
945
|
await stepEntity.Save();
|
|
935
946
|
}
|
|
936
|
-
const executionResult = {
|
|
937
|
-
type: 'action',
|
|
938
|
-
actionId: action.id,
|
|
939
|
-
actionName: action.name,
|
|
940
|
-
result: actionResult
|
|
941
|
-
};
|
|
942
|
-
const nextStepDecision = {
|
|
943
|
-
decision: 'retry',
|
|
944
|
-
reasoning: 'Action completed successfully',
|
|
945
|
-
nextStepDetails: undefined
|
|
946
|
-
};
|
|
947
|
-
this._executionChain.push({
|
|
948
|
-
stepEntity,
|
|
949
|
-
executionType: 'action',
|
|
950
|
-
executionResult,
|
|
951
|
-
nextStepDecision,
|
|
952
|
-
startTime,
|
|
953
|
-
endTime: new Date(),
|
|
954
|
-
durationMs: new Date().getTime() - startTime.getTime()
|
|
955
|
-
});
|
|
956
947
|
const outputData = {
|
|
957
948
|
actionResult: {
|
|
958
949
|
success: actionResult.Success,
|
|
@@ -962,11 +953,11 @@ class BaseAgent {
|
|
|
962
953
|
}
|
|
963
954
|
};
|
|
964
955
|
await this.finalizeStepEntity(stepEntity, actionResult.Success, actionResult.Success ? undefined : actionResult.Message, outputData);
|
|
965
|
-
return { success: true, result: actionResult, action, stepEntity };
|
|
956
|
+
return { success: true, result: actionResult, action: aa, actionEntity, stepEntity };
|
|
966
957
|
}
|
|
967
958
|
catch (error) {
|
|
968
959
|
await this.finalizeStepEntity(stepEntity, false, error.message);
|
|
969
|
-
return { success: false, result: actionResult, error: error.message, action, stepEntity };
|
|
960
|
+
return { success: false, result: actionResult, error: error.message, action: aa, actionEntity, stepEntity };
|
|
970
961
|
}
|
|
971
962
|
});
|
|
972
963
|
const actionResults = await Promise.all(actionPromises);
|
|
@@ -977,7 +968,7 @@ class BaseAgent {
|
|
|
977
968
|
const actionResult = result.success ? result.result : null;
|
|
978
969
|
return {
|
|
979
970
|
actionName: result.action.name,
|
|
980
|
-
actionId: result.
|
|
971
|
+
actionId: result.actionEntity?.ID,
|
|
981
972
|
params: result.result?.Params || {},
|
|
982
973
|
success: result.success,
|
|
983
974
|
resultCode: actionResult?.Result?.ResultCode || (result.success ? 'SUCCESS' : 'ERROR'),
|
|
@@ -994,8 +985,9 @@ class BaseAgent {
|
|
|
994
985
|
});
|
|
995
986
|
return {
|
|
996
987
|
terminate: false,
|
|
997
|
-
step: '
|
|
998
|
-
|
|
988
|
+
step: 'Retry',
|
|
989
|
+
payload: previousDecision?.payload || null,
|
|
990
|
+
priorStepResult: actionSummaries,
|
|
999
991
|
retryReason: failedActions.length > 0
|
|
1000
992
|
? `Processing results with ${failedActions.length} failed action(s): ${failedActions.map(a => a.actionName).join(', ')}`
|
|
1001
993
|
: `Analyzing results from ${actionSummaries.length} completed action(s) to formulate response`
|
|
@@ -1004,38 +996,22 @@ class BaseAgent {
|
|
|
1004
996
|
catch (e) {
|
|
1005
997
|
return {
|
|
1006
998
|
terminate: false,
|
|
1007
|
-
step: '
|
|
1008
|
-
|
|
999
|
+
step: 'Retry',
|
|
1000
|
+
payload: e && e.message ? e.message : e ? e : 'Unknown error execution actions',
|
|
1009
1001
|
retryReason: 'Error while processing actions, retry'
|
|
1010
1002
|
};
|
|
1011
1003
|
}
|
|
1012
1004
|
}
|
|
1013
|
-
async executeChatStep(params,
|
|
1014
|
-
const
|
|
1015
|
-
const stepEntity = await this.createStepEntity('chat', 'User Interaction', params.contextUser);
|
|
1016
|
-
const executionResult = {
|
|
1017
|
-
type: 'chat',
|
|
1018
|
-
userMessage,
|
|
1019
|
-
result: { success: false, continueExecution: false }
|
|
1020
|
-
};
|
|
1021
|
-
const nextStepDecision = {
|
|
1022
|
-
decision: 'failed',
|
|
1023
|
-
reasoning: 'Chat functionality not implemented in base agent'
|
|
1024
|
-
};
|
|
1025
|
-
this._executionChain.push({
|
|
1026
|
-
stepEntity,
|
|
1027
|
-
executionType: 'chat',
|
|
1028
|
-
executionResult,
|
|
1029
|
-
nextStepDecision,
|
|
1030
|
-
startTime,
|
|
1031
|
-
endTime: new Date(),
|
|
1032
|
-
durationMs: new Date().getTime() - startTime.getTime()
|
|
1033
|
-
});
|
|
1005
|
+
async executeChatStep(params, previousDecision) {
|
|
1006
|
+
const stepEntity = await this.createStepEntity('Chat', 'User Interaction', params.contextUser);
|
|
1034
1007
|
await this.finalizeStepEntity(stepEntity, false, 'Chat not implemented');
|
|
1035
1008
|
return {
|
|
1036
|
-
step: '
|
|
1009
|
+
step: 'Chat',
|
|
1037
1010
|
terminate: true,
|
|
1038
|
-
|
|
1011
|
+
priorStepResult: previousDecision.message,
|
|
1012
|
+
reasoning: previousDecision.reasoning,
|
|
1013
|
+
confidence: previousDecision.confidence,
|
|
1014
|
+
payload: previousDecision.payload,
|
|
1039
1015
|
};
|
|
1040
1016
|
}
|
|
1041
1017
|
async createFailureResult(errorMessage, contextUser) {
|
|
@@ -1053,10 +1029,7 @@ class BaseAgent {
|
|
|
1053
1029
|
}
|
|
1054
1030
|
return {
|
|
1055
1031
|
success: false,
|
|
1056
|
-
|
|
1057
|
-
errorMessage,
|
|
1058
|
-
agentRun: this._agentRun,
|
|
1059
|
-
executionTree: this.buildExecutionTree()
|
|
1032
|
+
agentRun: this._agentRun
|
|
1060
1033
|
};
|
|
1061
1034
|
}
|
|
1062
1035
|
async createCancelledResult(message, contextUser) {
|
|
@@ -1074,220 +1047,57 @@ class BaseAgent {
|
|
|
1074
1047
|
}
|
|
1075
1048
|
return {
|
|
1076
1049
|
success: false,
|
|
1077
|
-
|
|
1078
|
-
errorMessage: message,
|
|
1079
|
-
cancelled: true,
|
|
1080
|
-
cancellationReason: 'user_requested',
|
|
1081
|
-
agentRun: this._agentRun,
|
|
1082
|
-
executionTree: this.buildExecutionTree()
|
|
1050
|
+
agentRun: this._agentRun
|
|
1083
1051
|
};
|
|
1084
1052
|
}
|
|
1085
|
-
async finalizeAgentRun(finalStep,
|
|
1053
|
+
async finalizeAgentRun(finalStep, payload, contextUser) {
|
|
1086
1054
|
if (this._agentRun) {
|
|
1087
1055
|
this._agentRun.Status = 'Completed';
|
|
1088
1056
|
this._agentRun.CompletedAt = new Date();
|
|
1089
|
-
this._agentRun.Success = finalStep === '
|
|
1090
|
-
this._agentRun.Result =
|
|
1057
|
+
this._agentRun.Success = finalStep.step === 'Success' || finalStep.step === 'Chat';
|
|
1058
|
+
this._agentRun.Result = payload ? JSON.stringify(payload) : null;
|
|
1059
|
+
this._agentRun.FinalStep = finalStep.step;
|
|
1060
|
+
this._agentRun.Message = finalStep.message;
|
|
1061
|
+
this._agentRun.FinalPayloadObject = payload;
|
|
1091
1062
|
const tokenStats = this.calculateTokenStats();
|
|
1092
1063
|
this._agentRun.TotalTokensUsed = tokenStats.totalTokens;
|
|
1093
1064
|
this._agentRun.TotalPromptTokensUsed = tokenStats.promptTokens;
|
|
1094
1065
|
this._agentRun.TotalCompletionTokensUsed = tokenStats.completionTokens;
|
|
1095
1066
|
this._agentRun.TotalCost = tokenStats.totalCost;
|
|
1096
|
-
await this._agentRun.Save();
|
|
1067
|
+
const ok = await this._agentRun.Save();
|
|
1068
|
+
if (!ok) {
|
|
1069
|
+
(0, core_1.LogError)(`Failed to finalize agent run ${this._agentRun.ID}`);
|
|
1070
|
+
}
|
|
1097
1071
|
}
|
|
1098
1072
|
return {
|
|
1099
|
-
success: finalStep === '
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
agentRun: this._agentRun,
|
|
1103
|
-
executionTree: this.buildExecutionTree()
|
|
1073
|
+
success: finalStep.step === 'Success' || finalStep.step === 'Chat',
|
|
1074
|
+
payload,
|
|
1075
|
+
agentRun: this._agentRun
|
|
1104
1076
|
};
|
|
1105
1077
|
}
|
|
1106
|
-
countStepsInTree(nodes) {
|
|
1107
|
-
let count = 0;
|
|
1108
|
-
for (const node of nodes) {
|
|
1109
|
-
count++;
|
|
1110
|
-
if (node.children && node.children.length > 0) {
|
|
1111
|
-
count += this.countStepsInTree(node.children);
|
|
1112
|
-
}
|
|
1113
|
-
}
|
|
1114
|
-
return count;
|
|
1115
|
-
}
|
|
1116
1078
|
calculateTokenStats() {
|
|
1117
1079
|
let totalTokens = 0;
|
|
1118
1080
|
let promptTokens = 0;
|
|
1119
1081
|
let completionTokens = 0;
|
|
1120
1082
|
let totalCost = 0;
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
totalCost += promptResult.result.promptRun?.TotalCost || 0;
|
|
1083
|
+
if (this._agentRun?.Steps) {
|
|
1084
|
+
for (const step of this._agentRun.Steps) {
|
|
1085
|
+
if (step.StepType === 'Prompt' && step.PromptRun) {
|
|
1086
|
+
totalTokens += step.PromptRun.TokensUsedRollup || 0;
|
|
1087
|
+
promptTokens += step.PromptRun.TokensPromptRollup || 0;
|
|
1088
|
+
completionTokens += step.PromptRun.TokensCompletionRollup || 0;
|
|
1089
|
+
totalCost += step.PromptRun.TotalCost || 0;
|
|
1129
1090
|
}
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
promptTokens += subAgentResult.result.agentRun.TotalPromptTokensUsed || 0;
|
|
1136
|
-
completionTokens += subAgentResult.result.agentRun.TotalCompletionTokensUsed || 0;
|
|
1137
|
-
totalCost += subAgentResult.result.agentRun.TotalCost || 0;
|
|
1091
|
+
else if (step.StepType === 'Sub-Agent' && step.SubAgentRun) {
|
|
1092
|
+
totalTokens += step.SubAgentRun.TotalTokensUsed || 0;
|
|
1093
|
+
promptTokens += step.SubAgentRun.TotalPromptTokensUsed || 0;
|
|
1094
|
+
completionTokens += step.SubAgentRun.TotalCompletionTokensUsed || 0;
|
|
1095
|
+
totalCost += step.SubAgentRun.TotalCost || 0;
|
|
1138
1096
|
}
|
|
1139
1097
|
}
|
|
1140
1098
|
}
|
|
1141
1099
|
return { totalTokens, promptTokens, completionTokens, totalCost };
|
|
1142
1100
|
}
|
|
1143
|
-
buildExecutionTree() {
|
|
1144
|
-
const executionTree = [];
|
|
1145
|
-
const allEvents = [];
|
|
1146
|
-
let maxProgressStepNumber = 0;
|
|
1147
|
-
for (const progressStep of this._allProgressSteps) {
|
|
1148
|
-
allEvents.push({
|
|
1149
|
-
type: 'progress',
|
|
1150
|
-
timestamp: progressStep.timestamp,
|
|
1151
|
-
data: progressStep
|
|
1152
|
-
});
|
|
1153
|
-
}
|
|
1154
|
-
for (const chainStep of this._executionChain) {
|
|
1155
|
-
allEvents.push({
|
|
1156
|
-
type: 'execution',
|
|
1157
|
-
timestamp: chainStep.startTime,
|
|
1158
|
-
data: chainStep
|
|
1159
|
-
});
|
|
1160
|
-
}
|
|
1161
|
-
allEvents.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
|
|
1162
|
-
for (const event of allEvents) {
|
|
1163
|
-
if (event.type === 'progress') {
|
|
1164
|
-
const progressData = event.data;
|
|
1165
|
-
maxProgressStepNumber++;
|
|
1166
|
-
const progressNode = {
|
|
1167
|
-
step: {
|
|
1168
|
-
ID: `progress-${event.timestamp.getTime()}`,
|
|
1169
|
-
StepNumber: maxProgressStepNumber,
|
|
1170
|
-
StepName: progressData.message,
|
|
1171
|
-
StepType: progressData.step || 'progress',
|
|
1172
|
-
Status: 'Completed',
|
|
1173
|
-
StartedAt: event.timestamp,
|
|
1174
|
-
CompletedAt: event.timestamp
|
|
1175
|
-
},
|
|
1176
|
-
inputData: null,
|
|
1177
|
-
outputData: {
|
|
1178
|
-
percentage: progressData.percentage,
|
|
1179
|
-
metadata: progressData.metadata
|
|
1180
|
-
},
|
|
1181
|
-
executionType: progressData.step || 'progress',
|
|
1182
|
-
startTime: event.timestamp,
|
|
1183
|
-
endTime: event.timestamp,
|
|
1184
|
-
durationMs: 0,
|
|
1185
|
-
children: [],
|
|
1186
|
-
depth: progressData.depth || this._runContext?.depth || 0,
|
|
1187
|
-
parentStepId: null,
|
|
1188
|
-
agentHierarchy: progressData.agentHierarchy || this._runContext?.agentHierarchy || []
|
|
1189
|
-
};
|
|
1190
|
-
executionTree.push(progressNode);
|
|
1191
|
-
}
|
|
1192
|
-
else {
|
|
1193
|
-
const chainStep = event.data;
|
|
1194
|
-
const stepEntity = chainStep.stepEntity;
|
|
1195
|
-
let inputData = null;
|
|
1196
|
-
let outputData = null;
|
|
1197
|
-
try {
|
|
1198
|
-
if (stepEntity.InputData) {
|
|
1199
|
-
inputData = JSON.parse(stepEntity.InputData);
|
|
1200
|
-
}
|
|
1201
|
-
if (stepEntity.OutputData) {
|
|
1202
|
-
outputData = JSON.parse(stepEntity.OutputData);
|
|
1203
|
-
}
|
|
1204
|
-
}
|
|
1205
|
-
catch (e) {
|
|
1206
|
-
inputData = stepEntity.InputData;
|
|
1207
|
-
outputData = stepEntity.OutputData;
|
|
1208
|
-
}
|
|
1209
|
-
const node = {
|
|
1210
|
-
step: stepEntity,
|
|
1211
|
-
inputData,
|
|
1212
|
-
outputData,
|
|
1213
|
-
executionType: chainStep.executionType,
|
|
1214
|
-
startTime: chainStep.startTime,
|
|
1215
|
-
endTime: chainStep.endTime,
|
|
1216
|
-
durationMs: chainStep.durationMs,
|
|
1217
|
-
nextStepDecision: chainStep.nextStepDecision,
|
|
1218
|
-
children: [],
|
|
1219
|
-
depth: this._runContext?.depth || 0,
|
|
1220
|
-
parentStepId: null,
|
|
1221
|
-
agentHierarchy: this._runContext?.agentHierarchy || []
|
|
1222
|
-
};
|
|
1223
|
-
if (chainStep.executionType === 'sub-agent' && chainStep.executionResult?.type === 'sub-agent') {
|
|
1224
|
-
const subAgentResult = chainStep.executionResult.result;
|
|
1225
|
-
if (subAgentResult.executionTree) {
|
|
1226
|
-
node.children = subAgentResult.executionTree.map(childNode => ({
|
|
1227
|
-
...childNode,
|
|
1228
|
-
parentStepId: stepEntity.ID,
|
|
1229
|
-
depth: (this._runContext?.depth || 0) + 1
|
|
1230
|
-
}));
|
|
1231
|
-
this.sortExecutionTreeByStepNumber(node.children);
|
|
1232
|
-
}
|
|
1233
|
-
}
|
|
1234
|
-
executionTree.push(node);
|
|
1235
|
-
}
|
|
1236
|
-
}
|
|
1237
|
-
this.sortExecutionTreeByStepNumber(executionTree);
|
|
1238
|
-
return executionTree;
|
|
1239
|
-
}
|
|
1240
|
-
sortExecutionTreeByStepNumber(nodes) {
|
|
1241
|
-
nodes.sort((a, b) => {
|
|
1242
|
-
const aStepNumber = a.step?.StepNumber || 0;
|
|
1243
|
-
const bStepNumber = b.step?.StepNumber || 0;
|
|
1244
|
-
return aStepNumber - bStepNumber;
|
|
1245
|
-
});
|
|
1246
|
-
for (const node of nodes) {
|
|
1247
|
-
if (node.children && node.children.length > 0) {
|
|
1248
|
-
this.sortExecutionTreeByStepNumber(node.children);
|
|
1249
|
-
}
|
|
1250
|
-
}
|
|
1251
|
-
}
|
|
1252
|
-
getNextStepReasoning(nextStep) {
|
|
1253
|
-
switch (nextStep.step) {
|
|
1254
|
-
case 'success':
|
|
1255
|
-
return 'Agent completed successfully';
|
|
1256
|
-
case 'failed':
|
|
1257
|
-
return `Agent failed: ${nextStep.errorMessage || 'Unknown error'}`;
|
|
1258
|
-
case 'retry':
|
|
1259
|
-
return nextStep.retryReason || 'Retrying with additional context';
|
|
1260
|
-
case 'sub-agent':
|
|
1261
|
-
return `Invoking sub-agent: ${nextStep.subAgent?.name}`;
|
|
1262
|
-
case 'actions':
|
|
1263
|
-
return `Executing ${nextStep.actions?.length || 0} action(s)`;
|
|
1264
|
-
case 'chat':
|
|
1265
|
-
return 'User interaction required';
|
|
1266
|
-
default:
|
|
1267
|
-
return 'Unknown next step';
|
|
1268
|
-
}
|
|
1269
|
-
}
|
|
1270
|
-
getNextStepDetails(nextStep) {
|
|
1271
|
-
switch (nextStep.step) {
|
|
1272
|
-
case 'success':
|
|
1273
|
-
case 'failed':
|
|
1274
|
-
return { type: 'complete', returnValue: nextStep.returnValue };
|
|
1275
|
-
case 'retry':
|
|
1276
|
-
return {
|
|
1277
|
-
type: 'retry',
|
|
1278
|
-
retryReason: nextStep.retryReason || '',
|
|
1279
|
-
retryInstructions: nextStep.retryInstructions || ''
|
|
1280
|
-
};
|
|
1281
|
-
case 'sub-agent':
|
|
1282
|
-
return nextStep.subAgent ? { type: 'sub-agent', subAgent: nextStep.subAgent } : undefined;
|
|
1283
|
-
case 'actions':
|
|
1284
|
-
return nextStep.actions ? { type: 'action', actions: nextStep.actions } : undefined;
|
|
1285
|
-
case 'chat':
|
|
1286
|
-
return { type: 'chat', message: nextStep.userMessage || '' };
|
|
1287
|
-
default:
|
|
1288
|
-
return undefined;
|
|
1289
|
-
}
|
|
1290
|
-
}
|
|
1291
1101
|
}
|
|
1292
1102
|
exports.BaseAgent = BaseAgent;
|
|
1293
1103
|
//# sourceMappingURL=base-agent.js.map
|