@memberjunction/ai-agents 2.59.0 → 2.61.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.
@@ -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._executionChain = [];
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._runContext?.agentHierarchy || [],
30
- depth: this._runContext?.depth || 0
65
+ agentHierarchy: this._agentHierarchy || [],
66
+ depth: this._depth || 0
31
67
  });
32
- originalCallback(progress);
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
- return await this.finalizeAgentRun(executionResult.finalStep.step, executionResult.finalStep.returnValue, params.contextUser);
136
+ this.logStatus(`✅ Finalizing execution for agent '${params.agent.Name}'`, true, params);
137
+ return await this.finalizeAgentRun(executionResult.finalStep, executionResult.finalStep.previousPayload, 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
- finalStep: 'failed',
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(agentType, systemPrompt, childPrompt, params) {
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,26 @@ 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
+ const atInstance = await base_agent_type_1.BaseAgentType.GetAgentTypeInstance(config.agentType);
252
+ await atInstance.InjectPayload(payload, promptParams);
170
253
  promptParams.childPrompts = [
171
254
  new ai_core_plus_1.ChildPromptParam({
172
255
  prompt: childPrompt,
173
256
  data: promptTemplateData,
174
257
  contextUser: params.contextUser,
175
258
  conversationMessages: params.conversationMessages,
176
- templateMessageRole: 'user'
259
+ templateMessageRole: 'user',
260
+ verbose: params.verbose
177
261
  }, agentType.AgentPromptPlaceholder)
178
262
  ];
179
263
  if (params.agent.ModelSelectionMode === 'Agent') {
180
264
  promptParams.modelSelectionPrompt = childPrompt;
181
- (0, core_1.LogStatus)(`🎯 Agent '${params.agent.Name}' configured to use its own prompt for model selection`);
265
+ this.logStatus(`🎯 Agent '${params.agent.Name}' configured to use its own prompt for model selection`, true, params);
182
266
  }
183
267
  if (params.override) {
184
268
  promptParams.override = params.override;
185
- (0, core_1.LogStatus)(`🎯 Using runtime override: ${params.override.modelId || 'model'} ${params.override.vendorId ? `from vendor ${params.override.vendorId}` : ''}`);
269
+ this.logStatus(`🎯 Using runtime override: ${params.override.modelId || 'model'} ${params.override.vendorId ? `from vendor ${params.override.vendorId}` : ''}`, true, params);
186
270
  }
187
271
  return promptParams;
188
272
  }
@@ -190,18 +274,11 @@ class BaseAgent {
190
274
  return await this._promptRunner.ExecutePrompt(promptParams);
191
275
  }
192
276
  async processNextStep(params, agentType, promptResult) {
193
- let agentTypeInstance;
194
- try {
195
- agentTypeInstance = await this.getAgentTypeInstance(agentType);
196
- }
197
- catch (error) {
198
- return {
199
- terminate: false,
200
- step: 'failed',
201
- errorMessage: error.message
202
- };
203
- }
277
+ this.logStatus(`🤔 Processing next step for agent '${params.agent.Name}' with agent type '${agentType.Name}'`, true, params);
278
+ const agentTypeInstance = await base_agent_type_1.BaseAgentType.GetAgentTypeInstance(agentType);
279
+ this.logStatus(`🎯 Agent type '${agentType.Name}' determining next step`, true, params);
204
280
  const nextStep = await agentTypeInstance.DetermineNextStep(promptResult);
281
+ this.logStatus(`📌 Next step determined: ${nextStep.step}${nextStep.terminate ? ' (terminating)' : ''}`, true, params);
205
282
  return nextStep;
206
283
  }
207
284
  createActionResultMessage(actions, results) {
@@ -261,37 +338,16 @@ class BaseAgent {
261
338
  throw new Error(`Error gathering context data: ${error.message}`);
262
339
  }
263
340
  }
264
- async getAgentTypeInstance(agentType) {
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) {
341
+ async ExecuteSingleAction(params, action, actionEntity, contextUser) {
275
342
  try {
343
+ this.logStatus(`⚡ Executing action '${action.name}'`, true, params);
276
344
  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
345
  const actionParams = Object.entries(action.params || {}).map(([key, value]) => ({
291
346
  Name: key,
292
347
  Value: value,
293
348
  Type: 'Input'
294
349
  }));
350
+ this.logStatus(`📥 Action parameters: ${JSON.stringify(action.params)}`, true, params);
295
351
  const result = await actionEngine.RunAction({
296
352
  Action: actionEntity,
297
353
  Params: actionParams,
@@ -303,28 +359,23 @@ class BaseAgent {
303
359
  if (!result.Success) {
304
360
  throw new Error(`Action '${action.name}' failed: ${result.Message || 'Unknown error'}`);
305
361
  }
362
+ this.logStatus(`✅ Action '${action.name}' completed successfully`, true, params);
306
363
  return result;
307
364
  }
308
365
  catch (error) {
366
+ this.logError(error, {
367
+ category: 'ActionExecution',
368
+ metadata: {
369
+ actionName: action.name,
370
+ actionParams: action.params
371
+ }
372
+ });
309
373
  throw new Error(`Error executing actions: ${error.message}`);
310
374
  }
311
375
  }
312
- async ExecuteSubAgent(params, subAgentRequest) {
376
+ async ExecuteSubAgent(params, subAgentRequest, subAgent, stepEntity, payload) {
313
377
  try {
314
- const engine = aiengine_1.AIEngine.Instance;
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
- }
378
+ this.logStatus(`🤖 Executing sub-agent '${subAgentRequest.name}'`, true, params);
328
379
  const runner = new AgentRunner_1.AgentRunner();
329
380
  const subAgentMessages = [
330
381
  {
@@ -332,6 +383,10 @@ class BaseAgent {
332
383
  content: subAgentRequest.message
333
384
  }
334
385
  ];
386
+ this.logStatus(`📨 Sub-agent message: "${subAgentRequest.message}"`, true, params);
387
+ if (subAgentRequest.templateParameters) {
388
+ this.logStatus(`📎 Template parameters: ${JSON.stringify(subAgentRequest.templateParameters)}`, true, params);
389
+ }
335
390
  const result = await runner.RunAgent({
336
391
  agent: subAgent,
337
392
  conversationMessages: subAgentMessages,
@@ -339,24 +394,34 @@ class BaseAgent {
339
394
  cancellationToken: params.cancellationToken,
340
395
  onProgress: params.onProgress,
341
396
  onStreaming: params.onStreaming,
342
- parentAgentHierarchy: this._runContext?.agentHierarchy,
343
- parentDepth: this._runContext?.depth,
397
+ parentAgentHierarchy: this._agentHierarchy,
398
+ parentDepth: this._depth,
344
399
  parentRun: this._agentRun,
400
+ payload: payload,
345
401
  data: subAgentRequest.templateParameters,
346
- context: params.context
402
+ context: params.context,
403
+ verbose: params.verbose
347
404
  });
348
405
  if (!result.success) {
349
- throw new Error(`Sub-agent '${subAgentRequest.name}' failed: ${result.errorMessage || 'Unknown error'}`);
406
+ throw new Error(`Sub-agent '${subAgentRequest.name}' failed: ${result.agentRun?.ErrorMessage || 'Unknown error'}`);
350
407
  }
408
+ this.logStatus(`✅ Sub-agent '${subAgentRequest.name}' completed successfully`, true, params);
351
409
  return result;
352
410
  }
353
411
  catch (error) {
412
+ this.logError(error, {
413
+ category: 'SubAgentExecution',
414
+ metadata: {
415
+ agentName: params.agent.Name,
416
+ subAgentName: subAgentRequest.name,
417
+ message: subAgentRequest.message
418
+ }
419
+ });
354
420
  throw new Error(`Error executing sub-agent: ${error.message}`);
355
421
  }
356
422
  }
357
423
  formatSubAgentDetails(subAgents) {
358
424
  return JSON.stringify(subAgents.map(sa => ({
359
- ID: sa.ID,
360
425
  Name: sa.Name,
361
426
  Description: sa.Description,
362
427
  Type: sa.TypeID ? this.getAgentTypeName(sa.TypeID) : 'Unknown',
@@ -390,7 +455,6 @@ class BaseAgent {
390
455
  }
391
456
  formatActionDetails(actions) {
392
457
  return JSON.stringify(actions.map(action => ({
393
- ID: action.ID,
394
458
  Name: action.Name,
395
459
  Description: action.Description,
396
460
  Parameters: {
@@ -405,7 +469,6 @@ class BaseAgent {
405
469
  Code: rc.ResultCode,
406
470
  IsSuccess: rc.IsSuccess,
407
471
  Description: rc.Description || 'No description provided',
408
- Usage: this.inferResultCodeUsage(rc.ResultCode, rc.IsSuccess)
409
472
  })),
410
473
  Category: action.CategoryID ? this.getActionCategoryName(action.CategoryID) : null,
411
474
  Status: action.Status
@@ -432,34 +495,6 @@ class BaseAgent {
432
495
  getActionCategoryName(categoryID) {
433
496
  return 'General';
434
497
  }
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
498
  async initializeAgentRun(params) {
464
499
  this._agentRun = await this._metadata.GetEntityObject('MJ: AI Agent Runs', params.contextUser);
465
500
  this._agentRun.AgentID = params.agent.ID;
@@ -471,68 +506,21 @@ class BaseAgent {
471
506
  const errorMessage = JSON.stringify((0, global_1.CopyScalarsAndArrays)(this._agentRun.LatestResult));
472
507
  throw new Error(`Failed to create agent run record: Details: ${errorMessage}`);
473
508
  }
474
- this._runContext = {
475
- currentStepIndex: 0,
476
- parentRunStack: [],
477
- agentHierarchy: params.parentAgentHierarchy
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 = [];
509
+ this._agentHierarchy = params.parentAgentHierarchy
510
+ ? [...params.parentAgentHierarchy, params.agent.Name || 'Unknown Agent']
511
+ : [params.agent.Name || 'Unknown Agent'];
512
+ this._depth = params.parentDepth !== undefined ? params.parentDepth + 1 : 0;
486
513
  this._allProgressSteps = [];
487
514
  }
488
515
  async validateAgentWithTracking(agent, contextUser) {
489
- const startTime = new Date();
490
516
  try {
491
517
  const validationResult = await this.validateAgent(agent);
492
518
  if (validationResult) {
493
- const stepEntity = await this.createStepEntity('validation', 'Agent Validation', contextUser);
494
- const executionResult = {
495
- type: 'validation',
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);
519
+ const stepEntity = await this.createStepEntity('Validation', 'Agent Validation', contextUser);
520
+ await this.finalizeStepEntity(stepEntity, false, validationResult.agentRun?.ErrorMessage);
521
+ return await this.createFailureResult(validationResult.agentRun?.ErrorMessage || 'Validation failed', contextUser);
515
522
  }
516
- const stepEntity = await this.createStepEntity('validation', 'Agent Validation', contextUser);
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
- });
523
+ const stepEntity = await this.createStepEntity('Validation', 'Agent Validation', contextUser);
536
524
  await this.finalizeStepEntity(stepEntity, true);
537
525
  return null;
538
526
  }
@@ -543,7 +531,7 @@ class BaseAgent {
543
531
  async createStepEntity(stepType, stepName, contextUser, targetId, inputData, targetLogId) {
544
532
  const stepEntity = await this._metadata.GetEntityObject('MJ: AI Agent Run Steps', contextUser);
545
533
  stepEntity.AgentRunID = this._agentRun.ID;
546
- stepEntity.StepNumber = this._runContext.currentStepIndex + 1;
534
+ stepEntity.StepNumber = (this._agentRun.Steps?.length || 0) + 1;
547
535
  stepEntity.StepType = stepType;
548
536
  stepEntity.StepName = this.formatHierarchicalMessage(stepName);
549
537
  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 +547,8 @@ class BaseAgent {
559
547
  stepEntity.InputData = JSON.stringify({
560
548
  ...inputData,
561
549
  context: {
562
- agentHierarchy: this._runContext.agentHierarchy,
563
- depth: this._runContext.depth,
550
+ agentHierarchy: this._agentHierarchy,
551
+ depth: this._depth,
564
552
  stepNumber: stepEntity.StepNumber
565
553
  }
566
554
  });
@@ -568,7 +556,9 @@ class BaseAgent {
568
556
  if (!await stepEntity.Save()) {
569
557
  throw new Error(`Failed to create agent run step record: ${JSON.stringify(stepEntity.LatestResult)}`);
570
558
  }
571
- this._runContext.currentStepIndex++;
559
+ if (this._agentRun) {
560
+ this._agentRun.Steps.push(stepEntity);
561
+ }
572
562
  return stepEntity;
573
563
  }
574
564
  async finalizeStepEntity(stepEntity, success, errorMessage, outputData) {
@@ -591,45 +581,64 @@ class BaseAgent {
591
581
  }
592
582
  }
593
583
  formatHierarchicalMessage(baseMessage) {
594
- if (this._runContext && this._runContext.depth > 0) {
595
- const breadcrumb = this._runContext.agentHierarchy
584
+ if (this._depth > 0) {
585
+ const breadcrumb = this._agentHierarchy
596
586
  .slice(1)
597
587
  .join(' → ');
598
588
  return breadcrumb ? `${breadcrumb}: ${baseMessage}` : baseMessage;
599
589
  }
600
590
  return baseMessage;
601
591
  }
592
+ getNextStepReasoning(nextStep) {
593
+ switch (nextStep.step) {
594
+ case 'Success':
595
+ return 'Agent completed task successfully';
596
+ case 'Failed':
597
+ return nextStep.errorMessage || 'Agent execution failed';
598
+ case 'Retry':
599
+ return nextStep.retryReason || 'Retrying with updated context';
600
+ case 'Sub-Agent':
601
+ return `Delegating to sub-agent: ${nextStep.subAgent?.name || 'Unknown'}`;
602
+ case 'Actions':
603
+ const actionCount = nextStep.actions?.length || 0;
604
+ return `Executing ${actionCount} action${actionCount !== 1 ? 's' : ''}`;
605
+ case 'Chat':
606
+ return 'Requesting user input';
607
+ default:
608
+ return 'Unknown decision';
609
+ }
610
+ }
602
611
  async executeNextStep(params, config, previousDecision) {
603
612
  if (!previousDecision) {
604
613
  return await this.executePromptStep(params, config);
605
614
  }
606
615
  switch (previousDecision.step) {
607
- case 'retry':
616
+ case 'Retry':
608
617
  return await this.executePromptStep(params, config, previousDecision);
609
- case 'sub-agent':
610
- return await this.executeSubAgentStep(params, previousDecision.subAgent);
611
- case 'actions':
612
- return await this.executeActionsStep(params, previousDecision.actions);
613
- case 'chat':
614
- return await this.executeChatStep(params, previousDecision.userMessage);
615
- case 'success':
618
+ case 'Sub-Agent':
619
+ return await this.executeSubAgentStep(params, previousDecision);
620
+ case 'Actions':
621
+ return await this.executeActionsStep(params, previousDecision);
622
+ case 'Chat':
623
+ return await this.executeChatStep(params, previousDecision);
624
+ case 'Success':
616
625
  const pd = previousDecision;
617
- if (pd.returnValue?.taskComplete === true && previousDecision.terminate) {
626
+ if (pd.previousPayload?.taskComplete === true && previousDecision.terminate) {
618
627
  return {
619
628
  terminate: true,
620
- step: 'success',
621
- returnValue: previousDecision.returnValue
629
+ step: 'Success',
630
+ previousPayload: previousDecision.previousPayload
622
631
  };
623
632
  }
624
633
  else {
625
634
  return await this.executePromptStep(params, config, previousDecision);
626
635
  }
627
- case 'failed':
636
+ case 'Failed':
628
637
  if (previousDecision.terminate) {
629
638
  return {
630
639
  terminate: true,
631
- step: 'failed',
632
- returnValue: previousDecision.returnValue
640
+ step: 'Failed',
641
+ previousPayload: previousDecision.previousPayload
633
642
  };
634
643
  }
635
644
  else {
@@ -639,24 +648,22 @@ class BaseAgent {
639
648
  throw new Error(`Unsupported next step: ${previousDecision.step}`);
640
649
  }
641
650
  }
642
- async executePromptStep(params, config, retryContext) {
643
- const startTime = new Date();
651
+ async executePromptStep(params, config, previousDecision) {
644
652
  const inputData = {
645
653
  promptId: config.childPrompt?.ID,
646
654
  promptName: config.childPrompt?.Name,
647
- isRetry: !!retryContext,
648
- retryContext: retryContext ? {
649
- reason: retryContext.retryReason,
650
- instructions: retryContext.retryInstructions
655
+ isRetry: !!previousDecision,
656
+ retryContext: previousDecision ? {
657
+ reason: previousDecision.retryReason,
658
+ instructions: previousDecision.retryInstructions
651
659
  } : undefined,
652
660
  conversationMessages: params.conversationMessages,
653
- agentState: this._runContext?.agentState
654
661
  };
655
- const stepEntity = await this.createStepEntity('prompt', 'Execute Agent Prompt', params.contextUser, config.childPrompt?.ID, inputData);
662
+ const stepEntity = await this.createStepEntity('Prompt', 'Execute Agent Prompt', params.contextUser, config.childPrompt?.ID, inputData);
656
663
  try {
657
- const isRetry = !!retryContext;
664
+ const isRetry = !!previousDecision;
658
665
  const promptMessage = isRetry
659
- ? `Running ${params.agent.Name} with context from ${retryContext.retryReason || 'previous actions'}`
666
+ ? `Running ${params.agent.Name} with context from ${previousDecision.retryReason || 'previous actions'}`
660
667
  : `Running ${params.agent.Name}'s initial prompt...`;
661
668
  params.onProgress?.({
662
669
  step: 'prompt_execution',
@@ -669,7 +676,11 @@ class BaseAgent {
669
676
  },
670
677
  displayMode: 'live'
671
678
  });
672
- const promptParams = await this.preparePromptParams(config.agentType, config.systemPrompt, config.childPrompt, params);
679
+ const payload = previousDecision?.previousPayload || params.payload;
680
+ if (stepEntity && payload) {
681
+ stepEntity.PayloadAtStart = JSON.stringify(payload);
682
+ }
683
+ const promptParams = await this.preparePromptParams(config, payload, params);
673
684
  promptParams.cancellationToken = params.cancellationToken;
674
685
  promptParams.onStreaming = params.onStreaming ? (chunk) => {
675
686
  params.onStreaming({
@@ -681,7 +692,7 @@ class BaseAgent {
681
692
  const promptResult = await this.executePrompt(promptParams);
682
693
  if (promptResult.promptRun?.ID) {
683
694
  stepEntity.TargetLogID = promptResult.promptRun.ID;
684
- await stepEntity.Save();
695
+ stepEntity.PromptRun = promptResult.promptRun;
685
696
  }
686
697
  if (params.cancellationToken?.aborted) {
687
698
  await this.finalizeStepEntity(stepEntity, false, 'Cancelled during prompt execution');
@@ -689,16 +700,10 @@ class BaseAgent {
689
700
  return {
690
701
  ...cancelledResult,
691
702
  terminate: true,
692
- step: cancelledResult.finalStep,
693
- returnValue: cancelledResult.returnValue,
703
+ step: 'Failed',
704
+ previousPayload: cancelledResult.payload,
694
705
  };
695
706
  }
696
- const executionResult = {
697
- type: 'prompt',
698
- promptId: config.childPrompt.ID,
699
- promptName: config.childPrompt.Name,
700
- result: promptResult
701
- };
702
707
  params.onProgress?.({
703
708
  step: 'decision_processing',
704
709
  percentage: 70,
@@ -706,20 +711,18 @@ class BaseAgent {
706
711
  displayMode: 'both'
707
712
  });
708
713
  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
- });
714
+ let finalPayload = payload;
715
+ if (nextStep.payloadChangeRequest) {
716
+ const changeResult = this._payloadManager.applyAgentChangeRequest(payload, nextStep.payloadChangeRequest, {
717
+ validateChanges: true,
718
+ logChanges: true,
719
+ agentName: params.agent.Name
720
+ });
721
+ if (changeResult.warnings.length > 0) {
722
+ (0, core_1.LogStatus)(`Payload warnings: ${changeResult.warnings.join('; ')}`);
723
+ }
724
+ finalPayload = changeResult.result;
725
+ }
723
726
  const outputData = {
724
727
  promptResult: {
725
728
  success: promptResult.success,
@@ -730,14 +733,22 @@ class BaseAgent {
730
733
  },
731
734
  nextStep: {
732
735
  decision: nextStep.step,
733
- reasoning: nextStepDecision.reasoning
736
+ reasoning: this.getNextStepReasoning(nextStep),
737
+ payload: finalPayload
734
738
  }
735
739
  };
740
+ if (stepEntity && finalPayload) {
741
+ stepEntity.PayloadAtEnd = JSON.stringify(finalPayload);
742
+ }
743
+ if (this._agentRun && finalPayload) {
744
+ this._agentRun.FinalPayloadObject = finalPayload;
745
+ }
746
+ nextStep.previousPayload = finalPayload;
736
747
  await this.finalizeStepEntity(stepEntity, promptResult.success, promptResult.success ? undefined : promptResult.errorMessage, outputData);
737
- if (nextStep.step === 'chat') {
748
+ if (nextStep.step === 'Chat') {
738
749
  return { ...nextStep, terminate: true };
739
750
  }
740
- else if (nextStep.step === 'success' || nextStep.step === 'failed') {
751
+ else if (nextStep.step === 'Success' || nextStep.step === 'Failed') {
741
752
  return { ...nextStep, terminate: true };
742
753
  }
743
754
  else {
@@ -749,12 +760,13 @@ class BaseAgent {
749
760
  const errString = error?.message || error || 'Unknown error';
750
761
  return {
751
762
  errorMessage: `Prompt execution failed: ${errString}`,
752
- step: 'failed',
763
+ step: 'Failed',
753
764
  terminate: false,
754
765
  };
755
766
  }
756
767
  }
757
- async executeSubAgentStep(params, subAgentRequest) {
768
+ async executeSubAgentStep(params, previousDecision) {
769
+ const subAgentRequest = previousDecision.subAgent;
758
770
  if (params.cancellationToken?.aborted) {
759
771
  throw new Error('Cancelled before sub-agent execution');
760
772
  }
@@ -763,7 +775,7 @@ class BaseAgent {
763
775
  percentage: 60,
764
776
  message: this.formatHierarchicalMessage(`Delegating to ${subAgentRequest.name} agent`),
765
777
  metadata: {
766
- subAgentId: subAgentRequest.id,
778
+ agentName: params.agent.Name,
767
779
  subAgentName: subAgentRequest.name,
768
780
  reason: subAgentRequest.message
769
781
  }
@@ -772,69 +784,79 @@ class BaseAgent {
772
784
  role: 'assistant',
773
785
  content: `I'm delegating this task to the "${subAgentRequest.name}" agent.\n\nReason: ${subAgentRequest.message}`
774
786
  });
775
- const startTime = new Date();
776
787
  const inputData = {
777
- subAgentId: subAgentRequest.id,
788
+ agentName: params.agent.Name,
778
789
  subAgentName: subAgentRequest.name,
779
790
  message: subAgentRequest.message,
780
791
  terminateAfter: subAgentRequest.terminateAfter,
781
792
  conversationMessages: params.conversationMessages,
782
- parentAgentHierarchy: this._runContext?.agentHierarchy
793
+ parentAgentHierarchy: this._agentHierarchy
783
794
  };
784
- const stepEntity = await this.createStepEntity('subagent', `Execute Sub-Agent: ${subAgentRequest.name}`, params.contextUser, subAgentRequest.id, inputData);
795
+ const subAgentEntity = aiengine_1.AIEngine.Instance.Agents.find(a => a.Name === subAgentRequest.name &&
796
+ a.ParentID === params.agent.ID);
797
+ if (!subAgentEntity) {
798
+ throw new Error(`Sub-agent '${subAgentRequest.name}' not found`);
799
+ }
800
+ const stepEntity = await this.createStepEntity('Sub-Agent', `Execute Sub-Agent: ${subAgentRequest.name}`, params.contextUser, subAgentEntity.ID, inputData);
785
801
  try {
786
- const subAgentResult = await this.ExecuteSubAgent(params, subAgentRequest);
802
+ let downstreamPaths = ['*'];
803
+ let upstreamPaths = ['*'];
804
+ try {
805
+ if (subAgentEntity.PayloadDownstreamPaths) {
806
+ downstreamPaths = JSON.parse(subAgentEntity.PayloadDownstreamPaths);
807
+ }
808
+ if (subAgentEntity.PayloadUpstreamPaths) {
809
+ upstreamPaths = JSON.parse(subAgentEntity.PayloadUpstreamPaths);
810
+ }
811
+ }
812
+ catch (parseError) {
813
+ this.logError(`Failed to parse payload paths for sub-agent ${subAgentRequest.name}: ${parseError.message}`, {
814
+ category: 'SubAgentExecution',
815
+ metadata: {
816
+ agentName: params.agent.Name,
817
+ subAgentName: subAgentRequest.name,
818
+ subAgentId: subAgentEntity.ID,
819
+ downstreamPaths: subAgentEntity.PayloadDownstreamPaths,
820
+ upstreamPaths: subAgentEntity.PayloadUpstreamPaths
821
+ }
822
+ });
823
+ }
824
+ const downstreamPayload = this._payloadManager.extractDownstreamPayload(subAgentRequest.name, previousDecision.previousPayload, downstreamPaths);
825
+ stepEntity.PayloadAtStart = JSON.stringify(previousDecision.previousPayload);
826
+ const subAgentResult = await this.ExecuteSubAgent(params, subAgentRequest, subAgentEntity, stepEntity, downstreamPayload);
827
+ const mergedPayload = this._payloadManager.mergeUpstreamPayload(subAgentRequest.name, previousDecision.previousPayload, subAgentResult.payload, upstreamPaths);
787
828
  if (subAgentResult.agentRun?.ID) {
788
829
  stepEntity.TargetLogID = subAgentResult.agentRun.ID;
789
- await stepEntity.Save();
830
+ stepEntity.SubAgentRun = subAgentResult.agentRun;
831
+ stepEntity.PayloadAtEnd = JSON.stringify(mergedPayload);
790
832
  }
791
833
  if (params.cancellationToken?.aborted) {
792
834
  await this.finalizeStepEntity(stepEntity, false, 'Cancelled during sub-agent execution');
793
835
  throw new Error('Cancelled during sub-agent execution');
794
836
  }
795
- const executionResult = {
796
- type: 'sub-agent',
797
- subAgentId: subAgentRequest.id,
798
- subAgentName: subAgentRequest.name,
799
- result: subAgentResult
800
- };
801
837
  this._subAgentRuns.push(subAgentResult);
802
838
  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
839
  const outputData = {
819
840
  subAgentResult: {
820
841
  success: subAgentResult.success,
821
- finalStep: subAgentResult.finalStep,
822
- returnValue: subAgentResult.returnValue,
823
- errorMessage: subAgentResult.errorMessage,
842
+ finalStep: subAgentResult.agentRun?.FinalStep,
843
+ payload: subAgentResult.payload,
844
+ errorMessage: subAgentResult.agentRun?.ErrorMessage,
824
845
  agentRunId: subAgentResult.agentRun?.ID,
825
- stepCount: this.countStepsInTree(subAgentResult.executionTree)
846
+ stepCount: subAgentResult.agentRun?.Steps?.length || 0
826
847
  },
827
848
  shouldTerminate: shouldTerminate,
828
- nextStep: nextStepDecision.decision
849
+ nextStep: shouldTerminate ? 'success' : 'retry'
829
850
  };
830
- await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.errorMessage, outputData);
851
+ await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
831
852
  const subAgentSummary = {
853
+ agentName: params.agent.Name,
832
854
  subAgentName: subAgentRequest.name,
833
- subAgentId: subAgentRequest.id,
855
+ subAgentId: subAgentEntity.ID,
834
856
  success: subAgentResult.success,
835
- finalStep: subAgentResult.finalStep,
836
- returnValue: subAgentResult.returnValue,
837
- errorMessage: subAgentResult.errorMessage || null
857
+ finalStep: subAgentResult.agentRun?.FinalStep,
858
+ payload: subAgentResult.payload,
859
+ errorMessage: subAgentResult.agentRun?.ErrorMessage || null
838
860
  };
839
861
  const resultMessage = subAgentResult.success
840
862
  ? `Sub-agent completed successfully:\n${JSON.stringify(subAgentSummary, null, 2)}`
@@ -843,42 +865,40 @@ class BaseAgent {
843
865
  role: 'user',
844
866
  content: resultMessage
845
867
  });
868
+ if (stepEntity) {
869
+ stepEntity.PayloadAtEnd = JSON.stringify(mergedPayload);
870
+ }
871
+ if (this._agentRun) {
872
+ this._agentRun.FinalPayloadObject = mergedPayload;
873
+ }
846
874
  return {
847
875
  ...subAgentResult,
848
- step: subAgentResult.success ? 'success' : 'failed',
849
- terminate: shouldTerminate
876
+ step: subAgentResult.success ? 'Success' : 'Failed',
877
+ terminate: shouldTerminate,
878
+ previousPayload: mergedPayload
850
879
  };
851
880
  }
852
881
  catch (error) {
853
882
  await this.finalizeStepEntity(stepEntity, false, error.message);
854
883
  return {
855
884
  errorMessage: `Sub-agent execution failed: ${error.message}`,
856
- step: 'failed',
885
+ step: 'Failed',
857
886
  terminate: false,
858
887
  };
859
888
  }
860
889
  }
861
- async executeActionsStep(params, actions) {
890
+ async executeActionsStep(params, previousDecision) {
862
891
  try {
892
+ const actions = previousDecision.actions || [];
863
893
  if (params.cancellationToken?.aborted) {
864
894
  throw new Error('Cancelled before action execution');
865
895
  }
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
896
  let progressMessage;
877
897
  if (actions.length === 1) {
878
- const action = actions[0];
879
- progressMessage = `Executing action: **${action.name}**`;
880
- if (action.params && Object.keys(action.params).length > 0) {
881
- const paramsList = Object.entries(action.params)
898
+ const aa = actions[0];
899
+ progressMessage = `Executing action: **${aa.name}**`;
900
+ if (aa.params && Object.keys(aa.params).length > 0) {
901
+ const paramsList = Object.entries(aa.params)
882
902
  .map(([key, value]) => {
883
903
  const displayValue = typeof value === 'object'
884
904
  ? JSON.stringify(value, null, 2)
@@ -891,10 +911,10 @@ class BaseAgent {
891
911
  }
892
912
  else {
893
913
  progressMessage = `Executing ${actions.length} actions:`;
894
- actions.forEach(action => {
895
- progressMessage += `\n\n• **${action.name}**`;
896
- if (action.params && Object.keys(action.params).length > 0) {
897
- const paramsList = Object.entries(action.params)
914
+ actions.forEach(aa => {
915
+ progressMessage += `\n\n• **${aa.name}**`;
916
+ if (aa.params && Object.keys(aa.params).length > 0) {
917
+ const paramsList = Object.entries(aa.params)
898
918
  .map(([key, value]) => {
899
919
  const displayValue = typeof value === 'object'
900
920
  ? JSON.stringify(value, null, 2)
@@ -923,36 +943,21 @@ class BaseAgent {
923
943
  role: 'assistant',
924
944
  content: actionMessage
925
945
  });
926
- const actionPromises = actions.map(async (action) => {
927
- const startTime = new Date();
928
- const stepEntity = await this.createStepEntity('action', `Execute Action: ${action.name}`, params.contextUser, action.id);
946
+ const actionEngine = actions_1.ActionEngineServer.Instance;
947
+ const agentActions = aiengine_1.AIEngine.Instance.AgentActions.filter(aa => aa.AgentID === params.agent.ID);
948
+ const actionPromises = actions.map(async (aa) => {
949
+ const actionEntity = actionEngine.Actions.find(a => a.Name === aa.name && agentActions.some(aa => aa.ActionID === a.ID));
950
+ if (!actionEntity) {
951
+ throw new Error(`Action "${aa.name}" Not Found for Agent "${params.agent.Name}"`);
952
+ }
953
+ const stepEntity = await this.createStepEntity('Actions', `Execute Action: ${aa.name}`, params.contextUser, actionEntity.ID);
929
954
  let actionResult;
930
955
  try {
931
- actionResult = await this.ExecuteSingleAction(params, action, params.contextUser);
956
+ actionResult = await this.ExecuteSingleAction(params, aa, actionEntity, params.contextUser);
932
957
  if (actionResult.LogEntry?.ID) {
933
958
  stepEntity.TargetLogID = actionResult.LogEntry.ID;
934
959
  await stepEntity.Save();
935
960
  }
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
961
  const outputData = {
957
962
  actionResult: {
958
963
  success: actionResult.Success,
@@ -962,11 +967,11 @@ class BaseAgent {
962
967
  }
963
968
  };
964
969
  await this.finalizeStepEntity(stepEntity, actionResult.Success, actionResult.Success ? undefined : actionResult.Message, outputData);
965
- return { success: true, result: actionResult, action, stepEntity };
970
+ return { success: true, result: actionResult, action: aa, actionEntity, stepEntity };
966
971
  }
967
972
  catch (error) {
968
973
  await this.finalizeStepEntity(stepEntity, false, error.message);
969
- return { success: false, result: actionResult, error: error.message, action, stepEntity };
974
+ return { success: false, result: actionResult, error: error.message, action: aa, actionEntity, stepEntity };
970
975
  }
971
976
  });
972
977
  const actionResults = await Promise.all(actionPromises);
@@ -977,7 +982,7 @@ class BaseAgent {
977
982
  const actionResult = result.success ? result.result : null;
978
983
  return {
979
984
  actionName: result.action.name,
980
- actionId: result.action.id,
985
+ actionId: result.actionEntity?.ID,
981
986
  params: result.result?.Params || {},
982
987
  success: result.success,
983
988
  resultCode: actionResult?.Result?.ResultCode || (result.success ? 'SUCCESS' : 'ERROR'),
@@ -994,8 +999,9 @@ class BaseAgent {
994
999
  });
995
1000
  return {
996
1001
  terminate: false,
997
- step: 'retry',
998
- returnValue: actionSummaries,
1002
+ step: 'Retry',
1003
+ previousPayload: previousDecision?.previousPayload || null,
1004
+ priorStepResult: actionSummaries,
999
1005
  retryReason: failedActions.length > 0
1000
1006
  ? `Processing results with ${failedActions.length} failed action(s): ${failedActions.map(a => a.actionName).join(', ')}`
1001
1007
  : `Analyzing results from ${actionSummaries.length} completed action(s) to formulate response`
@@ -1004,38 +1010,22 @@ class BaseAgent {
1004
1010
  catch (e) {
1005
1011
  return {
1006
1012
  terminate: false,
1007
- step: 'retry',
1008
- returnValue: e && e.message ? e.message : e ? e : 'Unknown error execution actions',
1013
+ step: 'Retry',
1014
+ errorMessage: e && e.message ? e.message : e ? e : 'Unknown error execution actions',
1009
1015
  retryReason: 'Error while processing actions, retry'
1010
1016
  };
1011
1017
  }
1012
1018
  }
1013
- async executeChatStep(params, userMessage) {
1014
- const startTime = new Date();
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
- });
1019
+ async executeChatStep(params, previousDecision) {
1020
+ const stepEntity = await this.createStepEntity('Chat', 'User Interaction', params.contextUser);
1034
1021
  await this.finalizeStepEntity(stepEntity, false, 'Chat not implemented');
1035
1022
  return {
1036
- step: 'chat',
1023
+ step: 'Chat',
1037
1024
  terminate: true,
1038
- returnValue: userMessage,
1025
+ priorStepResult: previousDecision.message,
1026
+ reasoning: previousDecision.reasoning,
1027
+ confidence: previousDecision.confidence,
1028
+ previousPayload: previousDecision.previousPayload,
1039
1029
  };
1040
1030
  }
1041
1031
  async createFailureResult(errorMessage, contextUser) {
@@ -1053,10 +1043,7 @@ class BaseAgent {
1053
1043
  }
1054
1044
  return {
1055
1045
  success: false,
1056
- finalStep: 'failed',
1057
- errorMessage,
1058
- agentRun: this._agentRun,
1059
- executionTree: this.buildExecutionTree()
1046
+ agentRun: this._agentRun
1060
1047
  };
1061
1048
  }
1062
1049
  async createCancelledResult(message, contextUser) {
@@ -1074,220 +1061,57 @@ class BaseAgent {
1074
1061
  }
1075
1062
  return {
1076
1063
  success: false,
1077
- finalStep: 'failed',
1078
- errorMessage: message,
1079
- cancelled: true,
1080
- cancellationReason: 'user_requested',
1081
- agentRun: this._agentRun,
1082
- executionTree: this.buildExecutionTree()
1064
+ agentRun: this._agentRun
1083
1065
  };
1084
1066
  }
1085
- async finalizeAgentRun(finalStep, returnValue, contextUser) {
1067
+ async finalizeAgentRun(finalStep, payload, contextUser) {
1086
1068
  if (this._agentRun) {
1087
1069
  this._agentRun.Status = 'Completed';
1088
1070
  this._agentRun.CompletedAt = new Date();
1089
- this._agentRun.Success = finalStep === 'success';
1090
- this._agentRun.Result = returnValue ? JSON.stringify(returnValue) : null;
1071
+ this._agentRun.Success = finalStep.step === 'Success' || finalStep.step === 'Chat';
1072
+ this._agentRun.Result = payload ? JSON.stringify(payload) : null;
1073
+ this._agentRun.FinalStep = finalStep.step;
1074
+ this._agentRun.Message = finalStep.message;
1075
+ this._agentRun.FinalPayloadObject = payload;
1091
1076
  const tokenStats = this.calculateTokenStats();
1092
1077
  this._agentRun.TotalTokensUsed = tokenStats.totalTokens;
1093
1078
  this._agentRun.TotalPromptTokensUsed = tokenStats.promptTokens;
1094
1079
  this._agentRun.TotalCompletionTokensUsed = tokenStats.completionTokens;
1095
1080
  this._agentRun.TotalCost = tokenStats.totalCost;
1096
- await this._agentRun.Save();
1081
+ const ok = await this._agentRun.Save();
1082
+ if (!ok) {
1083
+ (0, core_1.LogError)(`Failed to finalize agent run ${this._agentRun.ID}`);
1084
+ }
1097
1085
  }
1098
1086
  return {
1099
- success: finalStep === 'success' || finalStep === 'chat',
1100
- finalStep,
1101
- returnValue,
1102
- agentRun: this._agentRun,
1103
- executionTree: this.buildExecutionTree()
1087
+ success: finalStep.step === 'Success' || finalStep.step === 'Chat',
1088
+ payload,
1089
+ agentRun: this._agentRun
1104
1090
  };
1105
1091
  }
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
1092
  calculateTokenStats() {
1117
1093
  let totalTokens = 0;
1118
1094
  let promptTokens = 0;
1119
1095
  let completionTokens = 0;
1120
1096
  let totalCost = 0;
1121
- for (const step of this._executionChain) {
1122
- if (step.executionType === 'prompt' && step.executionResult.type === 'prompt') {
1123
- const promptResult = step.executionResult;
1124
- if (promptResult.result) {
1125
- totalTokens += promptResult.result.tokensUsed || 0;
1126
- promptTokens += promptResult.result.promptTokens || 0;
1127
- completionTokens += promptResult.result.completionTokens || 0;
1128
- totalCost += promptResult.result.promptRun?.TotalCost || 0;
1097
+ if (this._agentRun?.Steps) {
1098
+ for (const step of this._agentRun.Steps) {
1099
+ if (step.StepType === 'Prompt' && step.PromptRun) {
1100
+ totalTokens += step.PromptRun.TokensUsedRollup || 0;
1101
+ promptTokens += step.PromptRun.TokensPromptRollup || 0;
1102
+ completionTokens += step.PromptRun.TokensCompletionRollup || 0;
1103
+ totalCost += step.PromptRun.TotalCost || 0;
1129
1104
  }
1130
- }
1131
- else if (step.executionType === 'sub-agent' && step.executionResult.type === 'sub-agent') {
1132
- const subAgentResult = step.executionResult;
1133
- if (subAgentResult.result?.agentRun) {
1134
- totalTokens += subAgentResult.result.agentRun.TotalTokensUsed || 0;
1135
- promptTokens += subAgentResult.result.agentRun.TotalPromptTokensUsed || 0;
1136
- completionTokens += subAgentResult.result.agentRun.TotalCompletionTokensUsed || 0;
1137
- totalCost += subAgentResult.result.agentRun.TotalCost || 0;
1105
+ else if (step.StepType === 'Sub-Agent' && step.SubAgentRun) {
1106
+ totalTokens += step.SubAgentRun.TotalTokensUsed || 0;
1107
+ promptTokens += step.SubAgentRun.TotalPromptTokensUsed || 0;
1108
+ completionTokens += step.SubAgentRun.TotalCompletionTokensUsed || 0;
1109
+ totalCost += step.SubAgentRun.TotalCost || 0;
1138
1110
  }
1139
1111
  }
1140
1112
  }
1141
1113
  return { totalTokens, promptTokens, completionTokens, totalCost };
1142
1114
  }
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
1115
  }
1292
1116
  exports.BaseAgent = BaseAgent;
1293
1117
  //# sourceMappingURL=base-agent.js.map