@memberjunction/ai-agents 2.111.1 → 2.112.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.
@@ -24,10 +24,10 @@ var __importStar = (this && this.__importStar) || function (mod) {
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.BaseAgent = void 0;
27
- const core_1 = require("@memberjunction/core");
27
+ const global_1 = require("@memberjunction/global");
28
28
  const ai_prompts_1 = require("@memberjunction/ai-prompts");
29
29
  const base_agent_type_1 = require("./agent-types/base-agent-type");
30
- const global_1 = require("@memberjunction/global");
30
+ const global_2 = require("@memberjunction/global");
31
31
  const aiengine_1 = require("@memberjunction/aiengine");
32
32
  const actions_1 = require("@memberjunction/actions");
33
33
  const ai_engine_base_1 = require("@memberjunction/ai-engine-base");
@@ -39,7 +39,7 @@ const _ = __importStar(require("lodash"));
39
39
  class BaseAgent {
40
40
  constructor() {
41
41
  this._promptRunner = new ai_prompts_1.AIPromptRunner();
42
- this._metadata = new core_1.Metadata();
42
+ this._metadata = new global_1.Metadata();
43
43
  this._agentTypeState = null;
44
44
  this._executionCounts = new Map();
45
45
  this._generalValidationRetryCount = 0;
@@ -67,21 +67,21 @@ class BaseAgent {
67
67
  }
68
68
  logStatus(message, verboseOnly = false, params) {
69
69
  if (verboseOnly) {
70
- (0, core_1.LogStatusEx)({
70
+ (0, global_1.LogStatusEx)({
71
71
  message,
72
72
  verboseOnly: true,
73
- isVerboseEnabled: () => params?.verbose === true || (0, core_1.IsVerboseLoggingEnabled)()
73
+ isVerboseEnabled: () => params?.verbose === true || (0, global_1.IsVerboseLoggingEnabled)(),
74
74
  });
75
75
  }
76
76
  else {
77
- (0, core_1.LogStatus)(message);
77
+ (0, global_1.LogStatus)(message);
78
78
  }
79
79
  }
80
80
  logError(error, options) {
81
81
  const errorMessage = error instanceof Error ? error.message : error;
82
82
  const errorObj = error instanceof Error ? error : undefined;
83
83
  const metadata = {
84
- ...options?.metadata
84
+ ...options?.metadata,
85
85
  };
86
86
  if (options?.agent) {
87
87
  metadata.agentId = options.agent.ID;
@@ -91,12 +91,12 @@ class BaseAgent {
91
91
  metadata.agentTypeId = options.agentType.ID;
92
92
  metadata.agentTypeName = options.agentType.Name;
93
93
  }
94
- (0, core_1.LogErrorEx)({
94
+ (0, global_1.LogErrorEx)({
95
95
  message: errorMessage,
96
96
  error: errorObj,
97
97
  category: options?.category || 'BaseAgent',
98
98
  severity: options?.severity || 'error',
99
- metadata: Object.keys(metadata).length > 0 ? metadata : undefined
99
+ metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
100
100
  });
101
101
  }
102
102
  wrapProgressCallback(originalCallback) {
@@ -107,15 +107,15 @@ class BaseAgent {
107
107
  ...progress,
108
108
  timestamp: new Date(),
109
109
  agentHierarchy: this._agentHierarchy || [],
110
- depth: this._depth || 0
110
+ depth: this._depth || 0,
111
111
  });
112
112
  try {
113
113
  const enhancedProgress = {
114
114
  ...progress,
115
115
  metadata: {
116
116
  ...progress.metadata,
117
- agentRun: this._agentRun
118
- }
117
+ agentRun: this._agentRun,
118
+ },
119
119
  };
120
120
  originalCallback(enhancedProgress);
121
121
  }
@@ -124,8 +124,8 @@ class BaseAgent {
124
124
  category: 'ProgressEnhancement',
125
125
  metadata: {
126
126
  progress: progress,
127
- agentRunId: this._agentRun?.ID || 'N/A'
128
- }
127
+ agentRunId: this._agentRun?.ID || 'N/A',
128
+ },
129
129
  });
130
130
  originalCallback(progress);
131
131
  }
@@ -159,15 +159,15 @@ class BaseAgent {
159
159
  this.logStatus(`📊 Preloaded ${totalSources} data source(s) for agent '${params.agent.Name}': ${destinations.join(', ')}`, true, params);
160
160
  params.data = {
161
161
  ...preloadedResult.data,
162
- ...params.data
162
+ ...params.data,
163
163
  };
164
164
  params.context = {
165
165
  ...preloadedResult.context,
166
- ...params.context
166
+ ...params.context,
167
167
  };
168
168
  params.payload = {
169
169
  ...preloadedResult.payload,
170
- ...params.payload
170
+ ...params.payload,
171
171
  };
172
172
  }
173
173
  else {
@@ -178,7 +178,7 @@ class BaseAgent {
178
178
  this.logError(`Failed to preload data for agent '${params.agent.Name}': ${error.message}`, {
179
179
  agent: params.agent,
180
180
  category: 'DataPreloading',
181
- severity: 'warning'
181
+ severity: 'warning',
182
182
  });
183
183
  }
184
184
  }
@@ -193,7 +193,7 @@ class BaseAgent {
193
193
  }
194
194
  const wrappedParams = {
195
195
  ...params,
196
- onProgress: this.wrapProgressCallback(params.onProgress)
196
+ onProgress: this.wrapProgressCallback(params.onProgress),
197
197
  };
198
198
  await this.initializeStartingPayload(wrappedParams);
199
199
  if (params.cancellationToken?.aborted) {
@@ -203,7 +203,7 @@ class BaseAgent {
203
203
  wrappedParams.onProgress?.({
204
204
  step: 'initialization',
205
205
  percentage: 0,
206
- message: this.formatHierarchicalMessage(`Initializing ${params.agent.Name} agent and preparing execution environment`)
206
+ message: this.formatHierarchicalMessage(`Initializing ${params.agent.Name} agent and preparing execution environment`),
207
207
  });
208
208
  await this.initializeAgentRun(wrappedParams);
209
209
  this._validationRetryCount = 0;
@@ -221,7 +221,7 @@ class BaseAgent {
221
221
  wrappedParams.onProgress?.({
222
222
  step: 'validation',
223
223
  percentage: 10,
224
- message: this.formatHierarchicalMessage('Validating agent configuration and loading prompts')
224
+ message: this.formatHierarchicalMessage('Validating agent configuration and loading prompts'),
225
225
  });
226
226
  const validationResult = await this.validateAgentWithTracking(params.agent, params.contextUser);
227
227
  if (validationResult)
@@ -231,7 +231,7 @@ class BaseAgent {
231
231
  if (!config.success) {
232
232
  this.logError(`Failed to load agent configuration: ${config.errorMessage}`, {
233
233
  agent: params.agent,
234
- category: 'AgentConfiguration'
234
+ category: 'AgentConfiguration',
235
235
  });
236
236
  return await this.createFailureResult(config.errorMessage || 'Failed to load agent configuration', params.contextUser);
237
237
  }
@@ -243,7 +243,7 @@ class BaseAgent {
243
243
  step: 'finalization',
244
244
  percentage: 95,
245
245
  metadata: { result: executionResult },
246
- message: this.formatHierarchicalMessage('Finalizing agent execution')
246
+ message: this.formatHierarchicalMessage('Finalizing agent execution'),
247
247
  });
248
248
  this.logStatus(`✅ Finalizing execution for agent '${params.agent.Name}'`, true, params);
249
249
  const finalPayload = executionResult.finalStep.newPayload || executionResult.finalStep.previousPayload;
@@ -257,7 +257,7 @@ class BaseAgent {
257
257
  this.logError(error, {
258
258
  agent: params.agent,
259
259
  category: 'AgentExecution',
260
- severity: 'critical'
260
+ severity: 'critical',
261
261
  });
262
262
  return await this.createFailureResult(error.message, params.contextUser);
263
263
  }
@@ -312,11 +312,11 @@ class BaseAgent {
312
312
  throw new Error(`Run chain exceeds maximum length of ${maxChainLength}. This may indicate a data issue.`);
313
313
  }
314
314
  visitedRunIds.add(currentRunId);
315
- const rv = new core_1.RunView();
315
+ const rv = new global_1.RunView();
316
316
  const result = await rv.RunView({
317
317
  EntityName: 'MJ: AI Agent Runs',
318
318
  ExtraFilter: `ID='${currentRunId}'`,
319
- ResultType: 'simple'
319
+ ResultType: 'simple',
320
320
  }, contextUser);
321
321
  if (!result.Success || result.Results.length === 0) {
322
322
  break;
@@ -334,7 +334,7 @@ class BaseAgent {
334
334
  }
335
335
  return {
336
336
  success: false,
337
- agentRun: this._agentRun
337
+ agentRun: this._agentRun,
338
338
  };
339
339
  }
340
340
  return null;
@@ -355,16 +355,16 @@ class BaseAgent {
355
355
  metadata: {
356
356
  agentName: agent.Name,
357
357
  agentId: agent.ID,
358
- validationSchema: agent.StartingPayloadValidation
359
- }
358
+ validationSchema: agent.StartingPayloadValidation,
359
+ },
360
360
  });
361
361
  return null;
362
362
  }
363
363
  let payloadToValidate = params.payload;
364
- const jsonValidator = new global_1.JSONValidator();
364
+ const jsonValidator = new global_2.JSONValidator();
365
365
  const validationResult = jsonValidator.validate(payloadToValidate, validationSchema);
366
366
  if (!validationResult.Success) {
367
- const errorMessages = validationResult.Errors.map(e => e.Message);
367
+ const errorMessages = validationResult.Errors.map((e) => e.Message);
368
368
  return this.handleStartingValidationFailure(params, errorMessages);
369
369
  }
370
370
  this.logStatus(`✅ Starting payload validation passed for agent ${agent.Name}`, true, params);
@@ -376,8 +376,8 @@ class BaseAgent {
376
376
  metadata: {
377
377
  agentName: agent.Name,
378
378
  agentId: agent.ID,
379
- error: error.message
380
- }
379
+ error: error.message,
380
+ },
381
381
  });
382
382
  return null;
383
383
  }
@@ -389,7 +389,7 @@ class BaseAgent {
389
389
  this.logError(`Starting payload validation failed for agent ${params.agent.Name}`, {
390
390
  agent: params.agent,
391
391
  category: 'StartingPayloadValidation',
392
- metadata: { errors: errorMessages }
392
+ metadata: { errors: errorMessages },
393
393
  });
394
394
  if (this._agentRun) {
395
395
  this._agentRun.ErrorMessage = validationFeedback;
@@ -400,7 +400,7 @@ class BaseAgent {
400
400
  return {
401
401
  success: false,
402
402
  agentRun: this._agentRun,
403
- payload: params.payload
403
+ payload: params.payload,
404
404
  };
405
405
  }
406
406
  else {
@@ -415,43 +415,41 @@ class BaseAgent {
415
415
  this.logStatus(`🔧 Using custom driver class '${agent.DriverClass}' for agent '${agent.Name}'`, true);
416
416
  metadataOptional = true;
417
417
  }
418
- const agentType = engine.AgentTypes.find(at => at.ID === agent.TypeID);
418
+ const agentType = engine.AgentTypes.find((at) => at.ID === agent.TypeID);
419
419
  if (!agentType && !metadataOptional) {
420
420
  return {
421
421
  success: false,
422
- errorMessage: `Agent type not found for ID: ${agent.TypeID}`
422
+ errorMessage: `Agent type not found for ID: ${agent.TypeID}`,
423
423
  };
424
424
  }
425
- const systemPrompt = engine.Prompts.find(p => p.ID === agentType.SystemPromptID);
425
+ const systemPrompt = engine.Prompts.find((p) => p.ID === agentType.SystemPromptID);
426
426
  if (!systemPrompt)
427
427
  metadataOptional = true;
428
- const agentPrompt = engine.AgentPrompts
429
- .filter(ap => ap.AgentID === agent.ID && ap.Status === 'Active')
430
- .sort((a, b) => a.ExecutionOrder - b.ExecutionOrder)[0];
428
+ const agentPrompt = engine.AgentPrompts.filter((ap) => ap.AgentID === agent.ID && ap.Status === 'Active').sort((a, b) => a.ExecutionOrder - b.ExecutionOrder)[0];
431
429
  if (!agentPrompt && !metadataOptional) {
432
430
  return {
433
431
  success: false,
434
- errorMessage: `No prompts configured for agent: ${agent.Name}`
432
+ errorMessage: `No prompts configured for agent: ${agent.Name}`,
435
433
  };
436
434
  }
437
- const childPrompt = engine.Prompts.find(p => p.ID === agentPrompt?.PromptID);
435
+ const childPrompt = engine.Prompts.find((p) => p.ID === agentPrompt?.PromptID);
438
436
  if (!childPrompt && !metadataOptional) {
439
437
  return {
440
438
  success: false,
441
- errorMessage: `Child prompt not found for ID: ${agentPrompt?.PromptID}`
439
+ errorMessage: `Child prompt not found for ID: ${agentPrompt?.PromptID}`,
442
440
  };
443
441
  }
444
442
  if (!agentType.AgentPromptPlaceholder && !metadataOptional) {
445
443
  return {
446
444
  success: false,
447
- errorMessage: `Agent type '${agentType.Name}' does not have AgentPromptPlaceholder configured.`
445
+ errorMessage: `Agent type '${agentType.Name}' does not have AgentPromptPlaceholder configured.`,
448
446
  };
449
447
  }
450
448
  return {
451
449
  success: true,
452
450
  agentType,
453
451
  systemPrompt,
454
- childPrompt
452
+ childPrompt,
455
453
  };
456
454
  }
457
455
  async preparePromptParams(config, payload, params) {
@@ -490,7 +488,7 @@ class BaseAgent {
490
488
  const atInstance = await base_agent_type_1.BaseAgentType.GetAgentTypeInstance(config.agentType);
491
489
  await atInstance.InjectPayload(payload, this.AgentTypeState, promptParams, {
492
490
  agentId: params.agent.ID,
493
- agentRunId: this._agentRun?.ID
491
+ agentRunId: this._agentRun?.ID,
494
492
  });
495
493
  if (systemPrompt) {
496
494
  const childPromptParams = {
@@ -500,7 +498,7 @@ class BaseAgent {
500
498
  conversationMessages: params.conversationMessages,
501
499
  templateMessageRole: 'user',
502
500
  verbose: params.verbose,
503
- agentRunId: this.AgentRun?.ID
501
+ agentRunId: this.AgentRun?.ID,
504
502
  };
505
503
  if (params.effortLevel !== undefined && params.effortLevel !== null) {
506
504
  childPromptParams.effortLevel = params.effortLevel;
@@ -515,9 +513,7 @@ class BaseAgent {
515
513
  promptParams.configurationId = params.configurationId;
516
514
  childPromptParams.configurationId = params.configurationId;
517
515
  }
518
- promptParams.childPrompts = [
519
- new ai_core_plus_1.ChildPromptParam(childPromptParams, agentType.AgentPromptPlaceholder)
520
- ];
516
+ promptParams.childPrompts = [new ai_core_plus_1.ChildPromptParam(childPromptParams, agentType.AgentPromptPlaceholder)];
521
517
  }
522
518
  else {
523
519
  if (params.apiKeys && params.apiKeys.length > 0) {
@@ -544,7 +540,7 @@ class BaseAgent {
544
540
  async executePrompt(promptParams) {
545
541
  const newParams = {
546
542
  ...promptParams,
547
- attemptJSONRepair: true
543
+ attemptJSONRepair: true,
548
544
  };
549
545
  return await this._promptRunner.ExecutePrompt(newParams);
550
546
  }
@@ -574,23 +570,23 @@ class BaseAgent {
574
570
  default:
575
571
  this.logError(`Invalid next step '${nextStep.step}' for agent '${params.agent.Name}'`, {
576
572
  agent: params.agent,
577
- category: 'NextStepValidation'
573
+ category: 'NextStepValidation',
578
574
  });
579
575
  return {
580
576
  step: 'Failed',
581
577
  terminate: true,
582
- errorMessage: `Invalid next step '${nextStep.step}'`
578
+ errorMessage: `Invalid next step '${nextStep.step}'`,
583
579
  };
584
580
  }
585
581
  }
586
582
  async validateSubAgentNextStep(params, nextStep, currentPayload, agentRun, currentStep) {
587
583
  const name = nextStep.subAgent?.name;
588
584
  const curAgentSubAgents = aiengine_1.AIEngine.Instance.GetSubAgents(params.agent.ID, 'Active');
589
- const subAgent = curAgentSubAgents.find(a => a.Name.trim().toLowerCase() === name?.trim().toLowerCase());
585
+ const subAgent = curAgentSubAgents.find((a) => a.Name.trim().toLowerCase() === name?.trim().toLowerCase());
590
586
  if (!name || !subAgent) {
591
587
  this.logError(`Sub-agent '${name}' not found or not active for agent '${params.agent.Name}'`, {
592
588
  agent: params.agent,
593
- category: 'SubAgentExecution'
589
+ category: 'SubAgentExecution',
594
590
  });
595
591
  if (nextStep.step !== 'Retry') {
596
592
  this._generalValidationRetryCount++;
@@ -598,7 +594,7 @@ class BaseAgent {
598
594
  return {
599
595
  step: 'Retry',
600
596
  terminate: false,
601
- errorMessage: `Sub-agent '${name}' not found or not active`
597
+ errorMessage: `Sub-agent '${name}' not found or not active`,
602
598
  };
603
599
  }
604
600
  if (subAgent.MaxExecutionsPerRun != null) {
@@ -610,8 +606,8 @@ class BaseAgent {
610
606
  metadata: {
611
607
  subAgentName: name,
612
608
  executionCount,
613
- maxExecutions: subAgent.MaxExecutionsPerRun
614
- }
609
+ maxExecutions: subAgent.MaxExecutionsPerRun,
610
+ },
615
611
  });
616
612
  if (nextStep.step !== 'Retry') {
617
613
  this._generalValidationRetryCount++;
@@ -619,20 +615,20 @@ class BaseAgent {
619
615
  return {
620
616
  step: 'Retry',
621
617
  terminate: false,
622
- errorMessage: `Sub-agent '${name}' has reached its maximum execution limit of ${subAgent.MaxExecutionsPerRun}`
618
+ errorMessage: `Sub-agent '${name}' has reached its maximum execution limit of ${subAgent.MaxExecutionsPerRun}`,
623
619
  };
624
620
  }
625
621
  }
626
622
  return nextStep;
627
623
  }
628
624
  async validateActionsNextStep(params, nextStep, currentPayload, agentRun, currentStep) {
629
- const curAgentActions = aiengine_1.AIEngine.Instance.AgentActions.filter(aa => aa.AgentID === params.agent.ID && aa.Status === 'Active');
630
- const missingActions = nextStep.actions?.filter(action => {
625
+ const curAgentActions = aiengine_1.AIEngine.Instance.AgentActions.filter((aa) => aa.AgentID === params.agent.ID && aa.Status === 'Active');
626
+ const missingActions = nextStep.actions?.filter((action) => {
631
627
  const actionName = action.name.trim().toLowerCase();
632
- const exactMatch = curAgentActions.find(aa => aa.Action.trim().toLowerCase() === actionName);
628
+ const exactMatch = curAgentActions.find((aa) => aa.Action.trim().toLowerCase() === actionName);
633
629
  if (exactMatch)
634
630
  return false;
635
- const containsMatches = curAgentActions.filter(aa => aa.Action.trim().toLowerCase().includes(actionName));
631
+ const containsMatches = curAgentActions.filter((aa) => aa.Action.trim().toLowerCase().includes(actionName));
636
632
  if (containsMatches.length === 1) {
637
633
  const correctedName = containsMatches[0].Action;
638
634
  this.logStatus(`Action name fuzzy matched: '${action.name}' → '${correctedName}'`, true, params);
@@ -640,15 +636,15 @@ class BaseAgent {
640
636
  return false;
641
637
  }
642
638
  if (containsMatches.length > 1) {
643
- this.logStatus(`Ambiguous action name '${action.name}' matches ${containsMatches.length} actions: ${containsMatches.map(a => a.Action).join(', ')}`, true, params);
639
+ this.logStatus(`Ambiguous action name '${action.name}' matches ${containsMatches.length} actions: ${containsMatches.map((a) => a.Action).join(', ')}`, true, params);
644
640
  }
645
641
  return true;
646
642
  });
647
643
  if (missingActions && missingActions.length > 0) {
648
- const missingActionNames = missingActions.map(a => a.name).join(', ');
644
+ const missingActionNames = missingActions.map((a) => a.name).join(', ');
649
645
  this.logError(`Actions '${missingActionNames}' not found or not active for agent '${params.agent.Name}'`, {
650
646
  agent: params.agent,
651
- category: 'ActionExecution'
647
+ category: 'ActionExecution',
652
648
  });
653
649
  if (nextStep.step !== 'Retry') {
654
650
  this._generalValidationRetryCount++;
@@ -656,13 +652,13 @@ class BaseAgent {
656
652
  return {
657
653
  step: 'Retry',
658
654
  terminate: false,
659
- errorMessage: `Actions '${missingActionNames}' not found or not active`
655
+ errorMessage: `Actions '${missingActionNames}' not found or not active`,
660
656
  };
661
657
  }
662
658
  if (nextStep.actions) {
663
659
  const violatedActions = [];
664
660
  for (const action of nextStep.actions) {
665
- const agentAction = curAgentActions.find(aa => aa.Action.trim().toLowerCase() === action.name.trim().toLowerCase());
661
+ const agentAction = curAgentActions.find((aa) => aa.Action.trim().toLowerCase() === action.name.trim().toLowerCase());
666
662
  if (agentAction && agentAction.MaxExecutionsPerRun != null) {
667
663
  const executionCount = await this.getActionExecutionCount(agentRun.ID, agentAction.ActionID);
668
664
  if (executionCount >= agentAction.MaxExecutionsPerRun) {
@@ -676,8 +672,8 @@ class BaseAgent {
676
672
  agent: params.agent,
677
673
  category: 'ActionExecution',
678
674
  metadata: {
679
- violatedActions
680
- }
675
+ violatedActions,
676
+ },
681
677
  });
682
678
  if (nextStep.step !== 'Retry') {
683
679
  this._generalValidationRetryCount++;
@@ -685,7 +681,7 @@ class BaseAgent {
685
681
  return {
686
682
  step: 'Retry',
687
683
  terminate: false,
688
- errorMessage: violationMessage
684
+ errorMessage: violationMessage,
689
685
  };
690
686
  }
691
687
  }
@@ -697,7 +693,7 @@ class BaseAgent {
697
693
  const violationMessage = `Minimum execution requirements not met:\n${minViolations.join('\n')}`;
698
694
  this.logError(violationMessage, {
699
695
  agent: params.agent,
700
- category: 'MinimumExecutionValidation'
696
+ category: 'MinimumExecutionValidation',
701
697
  });
702
698
  if (nextStep.step !== 'Retry') {
703
699
  this._generalValidationRetryCount++;
@@ -705,7 +701,7 @@ class BaseAgent {
705
701
  return {
706
702
  step: 'Retry',
707
703
  terminate: false,
708
- errorMessage: violationMessage
704
+ errorMessage: violationMessage,
709
705
  };
710
706
  }
711
707
  const agent = params.agent;
@@ -723,8 +719,8 @@ class BaseAgent {
723
719
  metadata: {
724
720
  agentName: agent.Name,
725
721
  agentId: agent.ID,
726
- validationSchema: agent.FinalPayloadValidation
727
- }
722
+ validationSchema: agent.FinalPayloadValidation,
723
+ },
728
724
  });
729
725
  return nextStep;
730
726
  }
@@ -736,11 +732,11 @@ class BaseAgent {
736
732
  return this.handleFinalPayloadValidationFailure(params, nextStep, currentPayload, agent.FinalPayloadValidationMode || 'Retry', [errorMessage], agentRun, currentStep);
737
733
  }
738
734
  }
739
- const jsonValidator = new global_1.JSONValidator();
735
+ const jsonValidator = new global_2.JSONValidator();
740
736
  const validationResult = jsonValidator.validate(payloadToValidate, validationSchema);
741
737
  if (!validationResult.Success) {
742
738
  const mode = agent.FinalPayloadValidationMode || 'Retry';
743
- const errorMessages = validationResult.Errors.map(e => e.Message);
739
+ const errorMessages = validationResult.Errors.map((e) => e.Message);
744
740
  this.logStatus(`⚠️ Final payload validation failed for agent ${agent.Name} (mode: ${mode}):`, true, params);
745
741
  errorMessages.forEach((error, index) => {
746
742
  this.logStatus(` ${index + 1}. ${error}`, true, params);
@@ -756,7 +752,7 @@ class BaseAgent {
756
752
  catch (error) {
757
753
  this.logError(`Failed to save validation success result: ${error.message}`, {
758
754
  category: 'PayloadValidation',
759
- metadata: { stepId: currentStep.ID }
755
+ metadata: { stepId: currentStep.ID },
760
756
  });
761
757
  }
762
758
  return nextStep;
@@ -767,8 +763,8 @@ class BaseAgent {
767
763
  metadata: {
768
764
  agentName: agent.Name,
769
765
  agentId: agent.ID,
770
- error: error.message
771
- }
766
+ error: error.message,
767
+ },
772
768
  });
773
769
  return nextStep;
774
770
  }
@@ -789,7 +785,7 @@ class BaseAgent {
789
785
  ...nextStep,
790
786
  step: 'Failed',
791
787
  message: `${validationFeedback}\n\nMax validation retries (${maxRetries}) exceeded.`,
792
- terminate: true
788
+ terminate: true,
793
789
  };
794
790
  }
795
791
  currentStep.FinalPayloadValidationResult = 'Retry';
@@ -799,7 +795,7 @@ class BaseAgent {
799
795
  ...nextStep,
800
796
  step: 'Retry',
801
797
  retryInstructions: `${validationFeedback}\n\nRetry attempt ${this._validationRetryCount} of ${maxRetries}`,
802
- terminate: false
798
+ terminate: false,
803
799
  };
804
800
  case 'Fail':
805
801
  currentStep.FinalPayloadValidationResult = 'Fail';
@@ -808,7 +804,7 @@ class BaseAgent {
808
804
  ...nextStep,
809
805
  step: 'Failed',
810
806
  message: validationFeedback,
811
- terminate: true
807
+ terminate: true,
812
808
  };
813
809
  case 'Warn':
814
810
  this.logStatus(`⚠️ WARNING: ${validationFeedback}`, false, params);
@@ -823,21 +819,23 @@ class BaseAgent {
823
819
  ...nextStep,
824
820
  step: 'Retry',
825
821
  retryInstructions: validationFeedback,
826
- terminate: false
822
+ terminate: false,
827
823
  };
828
824
  }
829
825
  }
830
826
  catch (error) {
831
827
  this.logError(`Failed to save validation results: ${error.message}`, {
832
828
  category: 'PayloadValidation',
833
- metadata: { stepId: currentStep.ID }
829
+ metadata: { stepId: currentStep.ID },
834
830
  });
835
- return mode === 'Warn' ? nextStep : {
836
- ...nextStep,
837
- step: mode === 'Fail' ? 'Failed' : 'Retry',
838
- message: validationFeedback,
839
- terminate: mode === 'Fail'
840
- };
831
+ return mode === 'Warn'
832
+ ? nextStep
833
+ : {
834
+ ...nextStep,
835
+ step: mode === 'Fail' ? 'Failed' : 'Retry',
836
+ message: validationFeedback,
837
+ terminate: mode === 'Fail',
838
+ };
841
839
  }
842
840
  }
843
841
  async validateFailedNextStep(params, nextStep, currentPayload, agentRun, currentStep) {
@@ -861,15 +859,15 @@ class BaseAgent {
861
859
  mappedStep = 'Retry';
862
860
  break;
863
861
  default:
864
- (0, core_1.LogError)(`Invalid ChatHandlingOption value: ${chatHandlingOption}. Expected 'Success', 'Failed', or 'Retry'. Treating as null and allowing Chat to propagate.`);
862
+ (0, global_1.LogError)(`Invalid ChatHandlingOption value: ${chatHandlingOption}. Expected 'Success', 'Failed', or 'Retry'. Treating as null and allowing Chat to propagate.`);
865
863
  return nextStep;
866
864
  }
867
865
  const remappedStep = {
868
866
  ...nextStep,
869
- step: mappedStep
867
+ step: mappedStep,
870
868
  };
871
- if (params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)()) {
872
- (0, core_1.LogStatus)(`Remapping Chat step to ${chatHandlingOption} based on agent's ChatHandlingOption`);
869
+ if (params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)()) {
870
+ (0, global_1.LogStatus)(`Remapping Chat step to ${chatHandlingOption} based on agent's ChatHandlingOption`);
873
871
  }
874
872
  return await this.validateNextStep(params, remappedStep, currentPayload, agentRun, currentStep);
875
873
  }
@@ -891,15 +889,15 @@ class BaseAgent {
891
889
  limit: guardrailResult.limit,
892
890
  current: guardrailResult.current,
893
891
  reason: guardrailResult.reason,
894
- timestamp: new Date().toISOString()
895
- }
892
+ timestamp: new Date().toISOString(),
893
+ },
896
894
  });
897
895
  await currentStep.Save();
898
896
  }
899
897
  catch (error) {
900
898
  this.logError(`Failed to save guardrail violation to step: ${error.message}`, {
901
899
  category: 'Guardrails',
902
- metadata: { stepId: currentStep.ID }
900
+ metadata: { stepId: currentStep.ID },
903
901
  });
904
902
  }
905
903
  return {
@@ -907,7 +905,7 @@ class BaseAgent {
907
905
  step: 'Failed',
908
906
  terminate: true,
909
907
  message: guardrailResult.reason,
910
- errorMessage: guardrailResult.reason
908
+ errorMessage: guardrailResult.reason,
911
909
  };
912
910
  }
913
911
  return nextStep;
@@ -921,7 +919,7 @@ class BaseAgent {
921
919
  type: 'cost',
922
920
  limit: agent.MaxCostPerRun,
923
921
  current: agentRun.TotalCost,
924
- reason: `Maximum cost limit of $${agent.MaxCostPerRun} exceeded. Current cost: $${agentRun.TotalCost.toFixed(4)}`
922
+ reason: `Maximum cost limit of $${agent.MaxCostPerRun} exceeded. Current cost: $${agentRun.TotalCost.toFixed(4)}`,
925
923
  };
926
924
  }
927
925
  }
@@ -932,7 +930,7 @@ class BaseAgent {
932
930
  type: 'tokens',
933
931
  limit: agent.MaxTokensPerRun,
934
932
  current: agentRun.TotalTokensUsed,
935
- reason: `Maximum token limit of ${agent.MaxTokensPerRun} exceeded. Current tokens: ${agentRun.TotalTokensUsed}`
933
+ reason: `Maximum token limit of ${agent.MaxTokensPerRun} exceeded. Current tokens: ${agentRun.TotalTokensUsed}`,
936
934
  };
937
935
  }
938
936
  }
@@ -943,7 +941,7 @@ class BaseAgent {
943
941
  type: 'iterations',
944
942
  limit: agent.MaxIterationsPerRun,
945
943
  current: agentRun.TotalPromptIterations,
946
- reason: `Maximum iteration limit of ${agent.MaxIterationsPerRun} exceeded. Current iterations: ${agentRun.TotalPromptIterations}`
944
+ reason: `Maximum iteration limit of ${agent.MaxIterationsPerRun} exceeded. Current iterations: ${agentRun.TotalPromptIterations}`,
947
945
  };
948
946
  }
949
947
  }
@@ -955,7 +953,7 @@ class BaseAgent {
955
953
  type: 'time',
956
954
  limit: agent.MaxTimePerRun,
957
955
  current: elapsedSeconds,
958
- reason: `Maximum time limit of ${agent.MaxTimePerRun} seconds exceeded. Elapsed time: ${elapsedSeconds} seconds`
956
+ reason: `Maximum time limit of ${agent.MaxTimePerRun} seconds exceeded. Elapsed time: ${elapsedSeconds} seconds`,
959
957
  };
960
958
  }
961
959
  }
@@ -965,7 +963,7 @@ class BaseAgent {
965
963
  type: 'iterations',
966
964
  limit: BaseAgent.MAX_VALIDATION_RETRIES,
967
965
  current: this._generalValidationRetryCount,
968
- reason: `Maximum validation retries of ${BaseAgent.MAX_VALIDATION_RETRIES} exceeded. The agent is unable to produce valid output after ${this._generalValidationRetryCount} validation failures.`
966
+ reason: `Maximum validation retries of ${BaseAgent.MAX_VALIDATION_RETRIES} exceeded. The agent is unable to produce valid output after ${this._generalValidationRetryCount} validation failures.`,
969
967
  };
970
968
  }
971
969
  return { exceeded: false };
@@ -981,7 +979,7 @@ class BaseAgent {
981
979
  const fatalErrorTypes = [
982
980
  'ContextLengthExceeded',
983
981
  'Authentication',
984
- 'InvalidRequest'
982
+ 'InvalidRequest',
985
983
  ];
986
984
  return fatalErrorTypes.includes(errorInfo.errorType);
987
985
  }
@@ -989,12 +987,14 @@ class BaseAgent {
989
987
  if (typeof content === 'string') {
990
988
  return content;
991
989
  }
992
- return content.map((block) => {
990
+ return content
991
+ .map((block) => {
993
992
  if (block.type === 'text') {
994
993
  return block.content;
995
994
  }
996
995
  return `[${block.type}: ${block.content}]`;
997
- }).join('\n');
996
+ })
997
+ .join('\n');
998
998
  }
999
999
  smartTrimContent(content, maxLength = 1000) {
1000
1000
  const originalLength = content.length;
@@ -1009,7 +1009,7 @@ class BaseAgent {
1009
1009
  return {
1010
1010
  trimmed,
1011
1011
  strategy: 'JSON array truncation',
1012
- originalLength
1012
+ originalLength,
1013
1013
  };
1014
1014
  }
1015
1015
  }
@@ -1036,7 +1036,7 @@ class BaseAgent {
1036
1036
  return {
1037
1037
  trimmed: JSON.stringify(truncated, null, 2),
1038
1038
  strategy: 'JSON object field truncation',
1039
- originalLength
1039
+ originalLength,
1040
1040
  };
1041
1041
  }
1042
1042
  }
@@ -1055,7 +1055,7 @@ class BaseAgent {
1055
1055
  return {
1056
1056
  trimmed,
1057
1057
  strategy: 'CSV row truncation',
1058
- originalLength
1058
+ originalLength,
1059
1059
  };
1060
1060
  }
1061
1061
  }
@@ -1064,13 +1064,13 @@ class BaseAgent {
1064
1064
  return {
1065
1065
  trimmed: content.substring(0, maxLength) + '\n\n... (truncated due to context length)',
1066
1066
  strategy: 'character truncation',
1067
- originalLength
1067
+ originalLength,
1068
1068
  };
1069
1069
  }
1070
1070
  return {
1071
1071
  trimmed: content,
1072
1072
  strategy: 'no truncation needed',
1073
- originalLength
1073
+ originalLength,
1074
1074
  };
1075
1075
  }
1076
1076
  async attemptContextRecovery(params, payload, errorMessage) {
@@ -1090,7 +1090,7 @@ class BaseAgent {
1090
1090
  step: 'Failed',
1091
1091
  terminate: true,
1092
1092
  previousPayload: payload,
1093
- newPayload: payload
1093
+ newPayload: payload,
1094
1094
  };
1095
1095
  }
1096
1096
  const originalMessage = messages[lastUserMessageIndex];
@@ -1116,7 +1116,7 @@ RECOMMENDED ACTIONS:
1116
1116
  3. Ask the user to clarify scope to narrow the query
1117
1117
  4. If you need the full data, acknowledge the limitation and ask the user how to proceed
1118
1118
 
1119
- Please choose an alternative approach to complete your task.`
1119
+ Please choose an alternative approach to complete your task.`,
1120
1120
  };
1121
1121
  return {
1122
1122
  step: 'Retry',
@@ -1124,17 +1124,18 @@ Please choose an alternative approach to complete your task.`
1124
1124
  retryInstructions: 'The previous action result exceeded context limits. Use more specific filters or request data in smaller batches.',
1125
1125
  terminate: false,
1126
1126
  previousPayload: payload,
1127
- newPayload: payload
1127
+ newPayload: payload,
1128
1128
  };
1129
1129
  }
1130
1130
  async processNextStep(nextStep, params, agentType, promptResult, currentPayload, currentStep) {
1131
1131
  const validatedNextStep = await this.validateNextStep(params, nextStep, currentPayload, this._agentRun, currentStep);
1132
1132
  const guardrailCheckedStep = await this.checkExecutionGuardrails(params, validatedNextStep, currentPayload, this._agentRun, currentStep);
1133
1133
  this.logStatus(`📌 Next step determined: ${guardrailCheckedStep.step}${guardrailCheckedStep.terminate ? ' (terminating)' : ''}`, true, params);
1134
- if (guardrailCheckedStep.step === 'Retry' && (guardrailCheckedStep.message || guardrailCheckedStep.errorMessage || guardrailCheckedStep.retryInstructions)) {
1134
+ if (guardrailCheckedStep.step === 'Retry' &&
1135
+ (guardrailCheckedStep.message || guardrailCheckedStep.errorMessage || guardrailCheckedStep.retryInstructions)) {
1135
1136
  params.conversationMessages.push({
1136
1137
  role: 'user',
1137
- content: `Retrying due to: ${guardrailCheckedStep.retryInstructions || guardrailCheckedStep.message || guardrailCheckedStep.errorMessage}`
1138
+ content: `Retrying due to: ${guardrailCheckedStep.retryInstructions || guardrailCheckedStep.message || guardrailCheckedStep.errorMessage}`,
1138
1139
  });
1139
1140
  }
1140
1141
  return guardrailCheckedStep;
@@ -1151,37 +1152,36 @@ Please choose an alternative approach to complete your task.`
1151
1152
  outputs: outputParams.reduce((acc, param) => {
1152
1153
  acc[param.Name] = param.Value;
1153
1154
  return acc;
1154
- }, {})
1155
+ }, {}),
1155
1156
  };
1156
1157
  });
1157
1158
  return {
1158
1159
  role: 'user',
1159
- content: `Action results:\n${JSON.stringify(resultSummary, null, 2)}`
1160
+ content: `Action results:\n${JSON.stringify(resultSummary, null, 2)}`,
1160
1161
  };
1161
1162
  }
1162
1163
  createSubAgentResultMessage(subAgent, result) {
1163
1164
  return {
1164
1165
  role: 'user',
1165
- content: `Sub-agent '${subAgent.name}' result:\n${typeof result === 'string' ? result : JSON.stringify(result, null, 2)}`
1166
+ content: `Sub-agent '${subAgent.name}' result:\n${typeof result === 'string' ? result : JSON.stringify(result, null, 2)}`,
1166
1167
  };
1167
1168
  }
1168
1169
  async gatherPromptTemplateData(agent, _contextUser, extraData) {
1169
1170
  try {
1170
1171
  const engine = aiengine_1.AIEngine.Instance;
1171
- const activeSubAgents = engine.Agents.filter(a => a.ParentID === agent.ID && a.Status === 'Active')
1172
- .sort((a, b) => a.ExecutionOrder - b.ExecutionOrder);
1173
- const activeAgentRelationships = engine.AgentRelationships.filter(ar => ar.AgentID === agent.ID && ar.Status === 'Active');
1172
+ const activeSubAgents = engine.Agents.filter((a) => a.ParentID === agent.ID && a.Status === 'Active').sort((a, b) => a.ExecutionOrder - b.ExecutionOrder);
1173
+ const activeAgentRelationships = engine.AgentRelationships.filter((ar) => ar.AgentID === agent.ID && ar.Status === 'Active');
1174
1174
  const uniqueActiveSubAgentIDs = new Set();
1175
- activeSubAgents.forEach(a => uniqueActiveSubAgentIDs.add(a.ID));
1176
- activeAgentRelationships.forEach(ar => uniqueActiveSubAgentIDs.add(ar.SubAgentID));
1177
- const uniqueActiveSubAgents = Array.from(uniqueActiveSubAgentIDs).map(id => engine.Agents.find(a => a.ID === id));
1178
- const agentActions = engine.AgentActions.filter(aa => aa.AgentID === agent.ID && aa.Status === 'Active');
1179
- const actions = actions_1.ActionEngineServer.Instance.Actions.filter(a => agentActions.some(aa => aa.ActionID === a.ID));
1180
- const activeActions = actions.filter(a => a.Status === 'Active');
1175
+ activeSubAgents.forEach((a) => uniqueActiveSubAgentIDs.add(a.ID));
1176
+ activeAgentRelationships.forEach((ar) => uniqueActiveSubAgentIDs.add(ar.SubAgentID));
1177
+ const uniqueActiveSubAgents = Array.from(uniqueActiveSubAgentIDs).map((id) => engine.Agents.find((a) => a.ID === id));
1178
+ const agentActions = engine.AgentActions.filter((aa) => aa.AgentID === agent.ID && aa.Status === 'Active');
1179
+ const actions = actions_1.ActionEngineServer.Instance.Actions.filter((a) => agentActions.some((aa) => aa.ActionID === a.ID));
1180
+ const activeActions = actions.filter((a) => a.Status === 'Active');
1181
1181
  const contextData = {
1182
1182
  agentName: agent.Name,
1183
1183
  agentDescription: agent.Description,
1184
- parentAgentName: agent.Parent ? agent.Parent.trim() : "",
1184
+ parentAgentName: agent.Parent ? agent.Parent.trim() : '',
1185
1185
  subAgentCount: uniqueActiveSubAgents.length,
1186
1186
  subAgentDetails: this.formatSubAgentDetails(uniqueActiveSubAgents),
1187
1187
  actionCount: actions.length,
@@ -1190,7 +1190,7 @@ Please choose an alternative approach to complete your task.`
1190
1190
  if (extraData) {
1191
1191
  return {
1192
1192
  ...contextData,
1193
- ...extraData
1193
+ ...extraData,
1194
1194
  };
1195
1195
  }
1196
1196
  else {
@@ -1207,7 +1207,7 @@ Please choose an alternative approach to complete your task.`
1207
1207
  const actionParams = Object.entries(action.params || {}).map(([key, value]) => ({
1208
1208
  Name: key,
1209
1209
  Value: value,
1210
- Type: 'Input'
1210
+ Type: 'Input',
1211
1211
  }));
1212
1212
  const result = await actionEngine.RunAction({
1213
1213
  Action: actionEntity,
@@ -1215,7 +1215,7 @@ Please choose an alternative approach to complete your task.`
1215
1215
  ContextUser: contextUser,
1216
1216
  Filters: [],
1217
1217
  SkipActionLog: false,
1218
- Context: params.context
1218
+ Context: params.context,
1219
1219
  });
1220
1220
  if (result.Success) {
1221
1221
  this.logStatus(` ✅ Action '${action.name}' completed successfully`, true, params);
@@ -1230,8 +1230,8 @@ Please choose an alternative approach to complete your task.`
1230
1230
  category: 'ActionExecution',
1231
1231
  metadata: {
1232
1232
  actionName: action.name,
1233
- actionParams: action.params
1234
- }
1233
+ actionParams: action.params,
1234
+ },
1235
1235
  });
1236
1236
  throw new Error(`Error executing actions: ${error.message}`);
1237
1237
  }
@@ -1246,7 +1246,7 @@ Please choose an alternative approach to complete your task.`
1246
1246
  }
1247
1247
  subAgentMessages.push({
1248
1248
  role: 'user',
1249
- content: subAgentRequest.message
1249
+ content: subAgentRequest.message,
1250
1250
  });
1251
1251
  this.logStatus(`📨 Sub-agent message: "${subAgentRequest.message}"`, true, params);
1252
1252
  if (subAgentRequest.templateParameters) {
@@ -1277,7 +1277,7 @@ Please choose an alternative approach to complete your task.`
1277
1277
  onAgentRunCreated: async (agentRunId) => {
1278
1278
  stepEntity.TargetLogID = agentRunId;
1279
1279
  await stepEntity.Save();
1280
- }
1280
+ },
1281
1281
  });
1282
1282
  if (result.success) {
1283
1283
  this.logStatus(`✅ Sub-agent '${subAgentRequest.name}' completed successfully`, true, params);
@@ -1293,17 +1293,17 @@ Please choose an alternative approach to complete your task.`
1293
1293
  metadata: {
1294
1294
  agentName: params.agent.Name,
1295
1295
  subAgentName: subAgentRequest.name,
1296
- message: subAgentRequest.message
1297
- }
1296
+ message: subAgentRequest.message,
1297
+ },
1298
1298
  });
1299
1299
  throw new Error(`Error executing sub-agent: ${error.message}`);
1300
1300
  }
1301
1301
  }
1302
1302
  formatSubAgentDetails(subAgents) {
1303
- return JSON.stringify(subAgents.map(sa => {
1303
+ return JSON.stringify(subAgents.map((sa) => {
1304
1304
  const result = {
1305
1305
  Name: sa.Name,
1306
- Description: sa.Description
1306
+ Description: sa.Description,
1307
1307
  };
1308
1308
  if (sa.ExecutionMode !== 'Sequential') {
1309
1309
  result['ExecutionMode'] = sa.ExecutionMode;
@@ -1314,45 +1314,39 @@ Please choose an alternative approach to complete your task.`
1314
1314
  }
1315
1315
  getAgentPromptParameters(agent) {
1316
1316
  const engine = aiengine_1.AIEngine.Instance;
1317
- const agentPrompt = engine.AgentPrompts
1318
- .filter(ap => ap.AgentID === agent.ID && ap.Status === 'Active')
1319
- .sort((a, b) => a.ExecutionOrder - b.ExecutionOrder)[0];
1317
+ const agentPrompt = engine.AgentPrompts.filter((ap) => ap.AgentID === agent.ID && ap.Status === 'Active').sort((a, b) => a.ExecutionOrder - b.ExecutionOrder)[0];
1320
1318
  if (!agentPrompt)
1321
1319
  return [];
1322
- const prompt = engine.Prompts.find(p => p.ID === agentPrompt.PromptID);
1320
+ const prompt = engine.Prompts.find((p) => p.ID === agentPrompt.PromptID);
1323
1321
  if (!prompt)
1324
1322
  return [];
1325
1323
  return prompt.TemplateParams;
1326
1324
  }
1327
1325
  getAgentPromptParametersJSON(agent) {
1328
1326
  const params = this.getAgentPromptParameters(agent);
1329
- return JSON.stringify(params.map(param => ({
1327
+ return JSON.stringify(params.map((param) => ({
1330
1328
  Name: param.Name,
1331
1329
  Type: param.Type,
1332
1330
  IsRequired: param.IsRequired,
1333
1331
  DefaultValue: param.DefaultValue,
1334
- Description: param.Description
1332
+ Description: param.Description,
1335
1333
  })), null, 2);
1336
1334
  }
1337
1335
  formatActionDetails(actions) {
1338
- return JSON.stringify(actions.map(action => ({
1336
+ return JSON.stringify(actions.map((action) => ({
1339
1337
  Name: action.Name,
1340
1338
  Description: action.Description,
1341
1339
  Parameters: {
1342
- Input: action.Params
1343
- .filter(p => p.Type.trim().toLowerCase() === 'input' || p.Type.trim().toLowerCase() === 'both')
1344
- .map(param => this.formatActionParameter(param)),
1345
- Output: action.Params
1346
- .filter(p => p.Type.trim().toLowerCase() === 'output' || p.Type.trim().toLowerCase() === 'both')
1347
- .map(param => this.formatActionParameter(param))
1340
+ Input: action.Params.filter((p) => p.Type.trim().toLowerCase() === 'input' || p.Type.trim().toLowerCase() === 'both').map((param) => this.formatActionParameter(param)),
1341
+ Output: action.Params.filter((p) => p.Type.trim().toLowerCase() === 'output' || p.Type.trim().toLowerCase() === 'both').map((param) => this.formatActionParameter(param)),
1348
1342
  },
1349
- ResultCodes: action.ResultCodes.map(rc => ({
1343
+ ResultCodes: action.ResultCodes.map((rc) => ({
1350
1344
  Code: rc.ResultCode,
1351
1345
  IsSuccess: rc.IsSuccess,
1352
1346
  Description: rc.Description || 'No description provided',
1353
1347
  })),
1354
1348
  Category: action.CategoryID ? this.getActionCategoryName(action.CategoryID) : null,
1355
- Status: action.Status
1349
+ Status: action.Status,
1356
1350
  })), null, 2);
1357
1351
  }
1358
1352
  formatActionParameter(param) {
@@ -1363,7 +1357,7 @@ Please choose an alternative approach to complete your task.`
1363
1357
  IsArray: param.IsArray,
1364
1358
  DefaultValue: param.DefaultValue,
1365
1359
  Description: param.Description,
1366
- ValueType: param.ValueType
1360
+ ValueType: param.ValueType,
1367
1361
  };
1368
1362
  }
1369
1363
  formatParamValueForMessage(value, maxLength = 100) {
@@ -1386,7 +1380,7 @@ Please choose an alternative approach to complete your task.`
1386
1380
  return `\`${stringValue}\``;
1387
1381
  }
1388
1382
  getAgentTypeName(typeID) {
1389
- const agentType = aiengine_1.AIEngine.Instance.AgentTypes.find(at => at.ID === typeID);
1383
+ const agentType = aiengine_1.AIEngine.Instance.AgentTypes.find((at) => at.ID === typeID);
1390
1384
  return agentType?.Name || 'Unknown';
1391
1385
  }
1392
1386
  getValueListItems(valueListID) {
@@ -1398,11 +1392,11 @@ Please choose an alternative approach to complete your task.`
1398
1392
  async initializeAgentRun(params) {
1399
1393
  let modifiedParams = params;
1400
1394
  if (params.lastRunId && params.autoPopulateLastRunPayload) {
1401
- const rv = new core_1.RunView();
1395
+ const rv = new global_1.RunView();
1402
1396
  const lastRunResult = await rv.RunView({
1403
1397
  EntityName: 'MJ: AI Agent Runs',
1404
1398
  ExtraFilter: `ID='${params.lastRunId}'`,
1405
- ResultType: 'simple'
1399
+ ResultType: 'simple',
1406
1400
  }, params.contextUser);
1407
1401
  if (lastRunResult.Success && lastRunResult.Results.length > 0) {
1408
1402
  const lastRun = lastRunResult.Results[0];
@@ -1412,14 +1406,14 @@ Please choose an alternative approach to complete your task.`
1412
1406
  if (!params.payload) {
1413
1407
  modifiedParams = {
1414
1408
  ...params,
1415
- payload: lastPayload
1409
+ payload: lastPayload,
1416
1410
  };
1417
1411
  }
1418
1412
  }
1419
1413
  catch (e) {
1420
1414
  this.logError(`Failed to parse FinalPayload from last run: ${e}`, {
1421
1415
  category: 'LastRunPayload',
1422
- metadata: { lastRunId: params.lastRunId }
1416
+ metadata: { lastRunId: params.lastRunId },
1423
1417
  });
1424
1418
  }
1425
1419
  }
@@ -1460,8 +1454,8 @@ Please choose an alternative approach to complete your task.`
1460
1454
  this._agentRun.Data = JSON.stringify(params.data);
1461
1455
  }
1462
1456
  this._agentRun.Verbose = params.verbose || false;
1463
- if (!await this._agentRun.Save()) {
1464
- const errorMessage = JSON.stringify((0, global_1.CopyScalarsAndArrays)(this._agentRun.LatestResult));
1457
+ if (!(await this._agentRun.Save())) {
1458
+ const errorMessage = JSON.stringify((0, global_2.CopyScalarsAndArrays)(this._agentRun.LatestResult));
1465
1459
  throw new Error(`Failed to create agent run record: Details: ${errorMessage}`);
1466
1460
  }
1467
1461
  if (modifiedParams.onAgentRunCreated) {
@@ -1469,7 +1463,7 @@ Please choose an alternative approach to complete your task.`
1469
1463
  await modifiedParams.onAgentRunCreated(this._agentRun.ID);
1470
1464
  }
1471
1465
  catch (callbackError) {
1472
- (0, core_1.LogStatus)(`Error in onAgentRunCreated callback: ${callbackError.message}`);
1466
+ (0, global_1.LogStatus)(`Error in onAgentRunCreated callback: ${callbackError.message}`);
1473
1467
  }
1474
1468
  }
1475
1469
  this._agentHierarchy = params.parentAgentHierarchy
@@ -1521,11 +1515,11 @@ Please choose an alternative approach to complete your task.`
1521
1515
  context: {
1522
1516
  agentHierarchy: this._agentHierarchy,
1523
1517
  depth: this._depth,
1524
- stepNumber: stepEntity.StepNumber
1525
- }
1518
+ stepNumber: stepEntity.StepNumber,
1519
+ },
1526
1520
  });
1527
1521
  }
1528
- if (!await stepEntity.Save()) {
1522
+ if (!(await stepEntity.Save())) {
1529
1523
  throw new Error(`Failed to create agent run step record: ${JSON.stringify(stepEntity.LatestResult)}`);
1530
1524
  }
1531
1525
  if (this._agentRun) {
@@ -1539,29 +1533,35 @@ Please choose an alternative approach to complete your task.`
1539
1533
  warnings: changeResult.warnings,
1540
1534
  requiresFeedback: changeResult.requiresFeedback,
1541
1535
  timestamp: changeResult.timestamp,
1542
- payloadValidation: changeResult.blockedOperations && changeResult.blockedOperations.length > 0 ? {
1543
- selfWriteViolations: {
1544
- deniedOperations: changeResult.blockedOperations,
1545
- timestamp: changeResult.timestamp.toISOString()
1546
- }
1547
- } : undefined,
1548
- analysis: changeResult.analysis ? {
1549
- totalWarnings: changeResult.analysis.summary.totalWarnings,
1550
- warningsByType: changeResult.analysis.summary.warningsByType,
1551
- suspiciousChanges: changeResult.analysis.summary.suspiciousChanges,
1552
- criticalWarnings: changeResult.analysis.criticalWarnings.map(w => ({
1553
- type: w.type,
1554
- severity: w.severity,
1555
- path: w.path,
1556
- message: w.message
1557
- }))
1558
- } : undefined,
1559
- diffSummary: changeResult.diff ? {
1560
- added: changeResult.diff.summary.added,
1561
- removed: changeResult.diff.summary.removed,
1562
- modified: changeResult.diff.summary.modified,
1563
- totalChanges: changeResult.diff.summary.totalPaths
1564
- } : undefined
1536
+ payloadValidation: changeResult.blockedOperations && changeResult.blockedOperations.length > 0
1537
+ ? {
1538
+ selfWriteViolations: {
1539
+ deniedOperations: changeResult.blockedOperations,
1540
+ timestamp: changeResult.timestamp.toISOString(),
1541
+ },
1542
+ }
1543
+ : undefined,
1544
+ analysis: changeResult.analysis
1545
+ ? {
1546
+ totalWarnings: changeResult.analysis.summary.totalWarnings,
1547
+ warningsByType: changeResult.analysis.summary.warningsByType,
1548
+ suspiciousChanges: changeResult.analysis.summary.suspiciousChanges,
1549
+ criticalWarnings: changeResult.analysis.criticalWarnings.map((w) => ({
1550
+ type: w.type,
1551
+ severity: w.severity,
1552
+ path: w.path,
1553
+ message: w.message,
1554
+ })),
1555
+ }
1556
+ : undefined,
1557
+ diffSummary: changeResult.diff
1558
+ ? {
1559
+ added: changeResult.diff.summary.added,
1560
+ removed: changeResult.diff.summary.removed,
1561
+ modified: changeResult.diff.summary.modified,
1562
+ totalChanges: changeResult.diff.summary.totalPaths,
1563
+ }
1564
+ : undefined,
1565
1565
  };
1566
1566
  }
1567
1567
  async finalizeStepEntity(stepEntity, success, errorMessage, outputData) {
@@ -1575,11 +1575,11 @@ Please choose an alternative approach to complete your task.`
1575
1575
  context: {
1576
1576
  success,
1577
1577
  durationMs: stepEntity.CompletedAt.getTime() - stepEntity.StartedAt.getTime(),
1578
- errorMessage
1579
- }
1578
+ errorMessage,
1579
+ },
1580
1580
  });
1581
1581
  }
1582
- if (!await stepEntity.Save()) {
1582
+ if (!(await stepEntity.Save())) {
1583
1583
  console.error('Failed to update agent run step record');
1584
1584
  }
1585
1585
  }
@@ -1645,9 +1645,7 @@ Please choose an alternative approach to complete your task.`
1645
1645
  }
1646
1646
  formatHierarchicalMessage(baseMessage) {
1647
1647
  if (this._depth > 0) {
1648
- const breadcrumb = this._agentHierarchy
1649
- .slice(1)
1650
- .join(' → ');
1648
+ const breadcrumb = this._agentHierarchy.slice(1).join(' → ');
1651
1649
  return breadcrumb ? `${breadcrumb}: ${baseMessage}` : baseMessage;
1652
1650
  }
1653
1651
  return baseMessage;
@@ -1693,7 +1691,7 @@ Please choose an alternative approach to complete your task.`
1693
1691
  terminate: true,
1694
1692
  step: 'Success',
1695
1693
  previousPayload: previousDecision.previousPayload,
1696
- newPayload: previousDecision.newPayload
1694
+ newPayload: previousDecision.newPayload,
1697
1695
  };
1698
1696
  }
1699
1697
  else {
@@ -1705,7 +1703,7 @@ Please choose an alternative approach to complete your task.`
1705
1703
  terminate: true,
1706
1704
  step: 'Failed',
1707
1705
  previousPayload: previousDecision.previousPayload,
1708
- newPayload: previousDecision.newPayload
1706
+ newPayload: previousDecision.newPayload,
1709
1707
  };
1710
1708
  }
1711
1709
  else {
@@ -1727,14 +1725,23 @@ Please choose an alternative approach to complete your task.`
1727
1725
  promptId: promptId,
1728
1726
  promptName: promptName,
1729
1727
  isRetry: !!previousDecision,
1730
- retryContext: previousDecision ? {
1731
- reason: previousDecision.retryReason,
1732
- instructions: previousDecision.retryInstructions
1733
- } : undefined,
1728
+ retryContext: previousDecision
1729
+ ? {
1730
+ reason: previousDecision.retryReason,
1731
+ instructions: previousDecision.retryInstructions,
1732
+ }
1733
+ : undefined,
1734
1734
  conversationMessages: params.conversationMessages,
1735
1735
  };
1736
1736
  const payload = previousDecision?.newPayload || params.payload;
1737
- const stepEntity = await this.createStepEntity({ stepType: 'Prompt', stepName: 'Execute Agent Prompt', contextUser: params.contextUser, targetId: promptId, inputData, payloadAtStart: payload });
1737
+ const stepEntity = await this.createStepEntity({
1738
+ stepType: 'Prompt',
1739
+ stepName: 'Execute Agent Prompt',
1740
+ contextUser: params.contextUser,
1741
+ targetId: promptId,
1742
+ inputData,
1743
+ payloadAtStart: payload,
1744
+ });
1738
1745
  try {
1739
1746
  const isRetry = !!previousDecision;
1740
1747
  const promptMessage = isRetry
@@ -1747,9 +1754,9 @@ Please choose an alternative approach to complete your task.`
1747
1754
  metadata: {
1748
1755
  promptId: promptId,
1749
1756
  isRetry,
1750
- promptName: promptName
1757
+ promptName: promptName,
1751
1758
  },
1752
- displayMode: 'live'
1759
+ displayMode: 'live',
1753
1760
  });
1754
1761
  if (stepEntity && payload) {
1755
1762
  stepEntity.PayloadAtStart = JSON.stringify(payload);
@@ -1759,29 +1766,33 @@ Please choose an alternative approach to complete your task.`
1759
1766
  const downstreamPaths = JSON.parse(params.agent.PayloadSelfReadPaths);
1760
1767
  downstreamPayload = this._payloadManager.extractDownstreamPayload(`Self: ${params.agent.Name}`, payload, downstreamPaths);
1761
1768
  }
1762
- const promptConfig = (promptToUse && promptToUse !== config.childPrompt) ? {
1763
- ...config,
1764
- childPrompt: promptToUse,
1765
- systemPrompt: null
1766
- } : config;
1769
+ const promptConfig = promptToUse && promptToUse !== config.childPrompt
1770
+ ? {
1771
+ ...config,
1772
+ childPrompt: promptToUse,
1773
+ systemPrompt: null,
1774
+ }
1775
+ : config;
1767
1776
  if (this._agentRun) {
1768
1777
  this._agentRun.TotalPromptIterations = (this._agentRun.TotalPromptIterations || 0) + 1;
1769
1778
  }
1770
1779
  const promptParams = await this.preparePromptParams(promptConfig, downstreamPayload, params);
1771
1780
  promptParams.cancellationToken = params.cancellationToken;
1772
- promptParams.onStreaming = params.onStreaming ? (chunk) => {
1773
- params.onStreaming({
1774
- ...chunk,
1775
- stepType: 'prompt',
1776
- stepEntityId: stepEntity.ID
1777
- });
1778
- } : undefined;
1781
+ promptParams.onStreaming = params.onStreaming
1782
+ ? (chunk) => {
1783
+ params.onStreaming({
1784
+ ...chunk,
1785
+ stepType: 'prompt',
1786
+ stepEntityId: stepEntity.ID,
1787
+ });
1788
+ }
1789
+ : undefined;
1779
1790
  promptParams.onPromptRunCreated = async (promptRunId) => {
1780
1791
  stepEntity.TargetLogID = promptRunId;
1781
1792
  await stepEntity.Save();
1782
1793
  };
1783
1794
  const promptResult = await this.executePrompt(promptParams);
1784
- const loopMsgIndex = params.conversationMessages.findIndex(m => m.metadata?._loopResults === true);
1795
+ const loopMsgIndex = params.conversationMessages.findIndex((m) => m.metadata?._loopResults === true);
1785
1796
  if (loopMsgIndex !== -1) {
1786
1797
  params.conversationMessages.splice(loopMsgIndex, 1);
1787
1798
  }
@@ -1792,8 +1803,7 @@ Please choose an alternative approach to complete your task.`
1792
1803
  if (!promptResult.success) {
1793
1804
  await this.finalizeStepEntity(stepEntity, false, promptResult.errorMessage);
1794
1805
  const isFatal = this.isFatalPromptError(promptResult);
1795
- const isContextOverflow = isFatal &&
1796
- promptResult.chatResult?.errorInfo?.errorType === 'ContextLengthExceeded';
1806
+ const isContextOverflow = isFatal && promptResult.chatResult?.errorInfo?.errorType === 'ContextLengthExceeded';
1797
1807
  if (isContextOverflow && !this._contextRecoveryAttempted) {
1798
1808
  this._contextRecoveryAttempted = true;
1799
1809
  this.logStatus(`⚠️ Context length exceeded - attempting recovery by trimming conversation`, true, params);
@@ -1805,7 +1815,7 @@ Please choose an alternative approach to complete your task.`
1805
1815
  step: 'Failed',
1806
1816
  terminate: isFatal,
1807
1817
  previousPayload: payload,
1808
- newPayload: payload
1818
+ newPayload: payload,
1809
1819
  };
1810
1820
  }
1811
1821
  if (params.cancellationToken?.aborted) {
@@ -1816,22 +1826,20 @@ Please choose an alternative approach to complete your task.`
1816
1826
  terminate: true,
1817
1827
  step: 'Failed',
1818
1828
  previousPayload: cancelledResult.payload,
1819
- newPayload: cancelledResult.payload
1829
+ newPayload: cancelledResult.payload,
1820
1830
  };
1821
1831
  }
1822
1832
  params.onProgress?.({
1823
1833
  step: 'decision_processing',
1824
1834
  percentage: 70,
1825
1835
  message: this.formatHierarchicalMessage('Analyzing response and determining next steps'),
1826
- displayMode: 'both'
1836
+ displayMode: 'both',
1827
1837
  });
1828
1838
  const initialNextStep = await this.determineNextStep(params, config.agentType, promptResult, payload);
1829
1839
  let finalPayload = payload;
1830
1840
  let currentStepPayloadChangeResult = undefined;
1831
1841
  if (initialNextStep.payloadChangeRequest) {
1832
- const allowedPaths = params.agent.PayloadSelfWritePaths
1833
- ? JSON.parse(params.agent.PayloadSelfWritePaths)
1834
- : undefined;
1842
+ const allowedPaths = params.agent.PayloadSelfWritePaths ? JSON.parse(params.agent.PayloadSelfWritePaths) : undefined;
1835
1843
  const changeResult = this._payloadManager.applyAgentChangeRequest(payload, initialNextStep.payloadChangeRequest, {
1836
1844
  validateChanges: true,
1837
1845
  logChanges: true,
@@ -1839,10 +1847,10 @@ Please choose an alternative approach to complete your task.`
1839
1847
  analyzeChanges: true,
1840
1848
  generateDiff: true,
1841
1849
  allowedPaths: allowedPaths,
1842
- verbose: params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)()
1850
+ verbose: params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)(),
1843
1851
  });
1844
- if (changeResult.warnings.length > 0 && (params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)())) {
1845
- (0, core_1.LogStatus)(`Payload warnings: ${changeResult.warnings.join('; ')}`);
1852
+ if (changeResult.warnings.length > 0 && (params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)())) {
1853
+ (0, global_1.LogStatus)(`Payload warnings: ${changeResult.warnings.join('; ')}`);
1846
1854
  }
1847
1855
  currentStepPayloadChangeResult = this.buildPayloadChangeResultSummary(changeResult);
1848
1856
  finalPayload = changeResult.result;
@@ -1855,8 +1863,8 @@ Please choose an alternative approach to complete your task.`
1855
1863
  reasoning: this.getNextStepReasoning(updatedNextStep),
1856
1864
  },
1857
1865
  ...(currentStepPayloadChangeResult && {
1858
- payloadChangeResult: currentStepPayloadChangeResult
1859
- })
1866
+ payloadChangeResult: currentStepPayloadChangeResult,
1867
+ }),
1860
1868
  };
1861
1869
  if (stepEntity && finalPayload) {
1862
1870
  stepEntity.PayloadAtEnd = JSON.stringify(finalPayload);
@@ -1887,13 +1895,12 @@ Please choose an alternative approach to complete your task.`
1887
1895
  step: 'Failed',
1888
1896
  terminate: false,
1889
1897
  previousPayload: payload,
1890
- newPayload: payload
1898
+ newPayload: payload,
1891
1899
  };
1892
1900
  const guardailCheck = await this.hasExceededAgentRunGuardrails(params, this.AgentRun);
1893
1901
  if (guardailCheck && guardailCheck.exceeded) {
1894
1902
  errorNextStep.terminate = true;
1895
1903
  }
1896
- ;
1897
1904
  return errorNextStep;
1898
1905
  }
1899
1906
  }
@@ -1909,12 +1916,12 @@ Please choose an alternative approach to complete your task.`
1909
1916
  metadata: {
1910
1917
  agentName: params.agent.Name,
1911
1918
  subAgentName: subAgentRequest.name,
1912
- reason: subAgentRequest.message
1913
- }
1919
+ reason: subAgentRequest.message,
1920
+ },
1914
1921
  });
1915
1922
  params.conversationMessages.push({
1916
1923
  role: 'assistant',
1917
- content: `I'm delegating this task to the "${subAgentRequest.name}" agent.\n\nReason: ${subAgentRequest.message}`
1924
+ content: `I'm delegating this task to the "${subAgentRequest.name}" agent.\n\nReason: ${subAgentRequest.message}`,
1918
1925
  });
1919
1926
  const inputData = {
1920
1927
  agentName: params.agent.Name,
@@ -1922,14 +1929,20 @@ Please choose an alternative approach to complete your task.`
1922
1929
  message: subAgentRequest.message,
1923
1930
  terminateAfter: subAgentRequest.terminateAfter,
1924
1931
  conversationMessages: params.conversationMessages,
1925
- parentAgentHierarchy: this._agentHierarchy
1932
+ parentAgentHierarchy: this._agentHierarchy,
1926
1933
  };
1927
- const subAgentEntity = aiengine_1.AIEngine.Instance.Agents.find(a => a.Name === subAgentRequest.name &&
1928
- a.ParentID === params.agent.ID);
1934
+ const subAgentEntity = aiengine_1.AIEngine.Instance.Agents.find((a) => a.Name === subAgentRequest.name && a.ParentID === params.agent.ID);
1929
1935
  if (!subAgentEntity) {
1930
1936
  throw new Error(`Sub-agent '${subAgentRequest.name}' not found`);
1931
1937
  }
1932
- const stepEntity = await this.createStepEntity({ stepType: 'Sub-Agent', stepName: `Execute Sub-Agent: ${subAgentRequest.name}`, contextUser: params.contextUser, targetId: subAgentEntity.ID, inputData, payloadAtStart: previousDecision.newPayload });
1938
+ const stepEntity = await this.createStepEntity({
1939
+ stepType: 'Sub-Agent',
1940
+ stepName: `Execute Sub-Agent: ${subAgentRequest.name}`,
1941
+ contextUser: params.contextUser,
1942
+ targetId: subAgentEntity.ID,
1943
+ inputData,
1944
+ payloadAtStart: previousDecision.newPayload,
1945
+ });
1933
1946
  this.incrementExecutionCount(subAgentEntity.ID);
1934
1947
  try {
1935
1948
  let downstreamPaths = ['*'];
@@ -1950,8 +1963,8 @@ Please choose an alternative approach to complete your task.`
1950
1963
  subAgentName: subAgentRequest.name,
1951
1964
  subAgentId: subAgentEntity.ID,
1952
1965
  downstreamPaths: subAgentEntity.PayloadDownstreamPaths,
1953
- upstreamPaths: subAgentEntity.PayloadUpstreamPaths
1954
- }
1966
+ upstreamPaths: subAgentEntity.PayloadUpstreamPaths,
1967
+ },
1955
1968
  });
1956
1969
  }
1957
1970
  let downstreamPayload = this._payloadManager.extractDownstreamPayload(subAgentRequest.name, previousDecision.newPayload, downstreamPaths);
@@ -1966,8 +1979,8 @@ Please choose an alternative approach to complete your task.`
1966
1979
  agentName: params.agent.Name,
1967
1980
  subAgentName: subAgentRequest.name,
1968
1981
  payloadScope: subAgentEntity.PayloadScope,
1969
- availableKeys: Object.keys(downstreamPayload || {})
1970
- }
1982
+ availableKeys: Object.keys(downstreamPayload || {}),
1983
+ },
1971
1984
  });
1972
1985
  throw new Error(errorMessage);
1973
1986
  }
@@ -1981,12 +1994,12 @@ Please choose an alternative approach to complete your task.`
1981
1994
  if (subAgentEntity.PayloadScope) {
1982
1995
  resultPayloadForMerge = this._payloadManager.reversePayloadScope(subAgentResult.payload, subAgentEntity.PayloadScope);
1983
1996
  }
1984
- const mergeResult = this._payloadManager.mergeUpstreamPayload(subAgentRequest.name, previousDecision.newPayload, resultPayloadForMerge, upstreamPaths, params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)());
1997
+ const mergeResult = this._payloadManager.mergeUpstreamPayload(subAgentRequest.name, previousDecision.newPayload, resultPayloadForMerge, upstreamPaths, params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)());
1985
1998
  mergedPayload = mergeResult.result;
1986
1999
  const mergeChangeRequest = {
1987
2000
  newElements: {},
1988
2001
  updateElements: {},
1989
- removeElements: {}
2002
+ removeElements: {},
1990
2003
  };
1991
2004
  const originalKeys = Object.keys(previousDecision.newPayload || {});
1992
2005
  const mergedKeys = Object.keys(mergedPayload || {});
@@ -2012,7 +2025,7 @@ Please choose an alternative approach to complete your task.`
2012
2025
  analyzeChanges: true,
2013
2026
  generateDiff: true,
2014
2027
  agentName: `${subAgentRequest.name} (upstream merge)`,
2015
- verbose: params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)()
2028
+ verbose: params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)(),
2016
2029
  });
2017
2030
  currentStepPayloadChangeResult = this.buildPayloadChangeResultSummary(mergeAnalysis);
2018
2031
  if (mergeResult.blockedOperations && mergeResult.blockedOperations.length > 0) {
@@ -2023,17 +2036,17 @@ Please choose an alternative approach to complete your task.`
2023
2036
  subAgentName: subAgentRequest.name,
2024
2037
  attemptedOperations: mergeResult.blockedOperations,
2025
2038
  authorizedPaths: upstreamPaths,
2026
- timestamp: new Date().toISOString()
2039
+ timestamp: new Date().toISOString(),
2027
2040
  };
2028
2041
  }
2029
- if (mergeAnalysis.warnings.length > 0 && (params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)())) {
2030
- (0, core_1.LogStatus)(`Sub-agent merge warnings: ${mergeAnalysis.warnings.join('; ')}`);
2042
+ if (mergeAnalysis.warnings.length > 0 && (params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)())) {
2043
+ (0, global_1.LogStatus)(`Sub-agent merge warnings: ${mergeAnalysis.warnings.join('; ')}`);
2031
2044
  }
2032
2045
  }
2033
2046
  }
2034
2047
  else {
2035
2048
  const msg = `Sub-agent '${subAgentRequest.name}' execution failed: ${subAgentResult.agentRun?.ErrorMessage || 'Unknown error'}`;
2036
- (0, core_1.LogError)(msg);
2049
+ (0, global_1.LogError)(msg);
2037
2050
  stepEntity.Success = false;
2038
2051
  stepEntity.ErrorMessage = msg;
2039
2052
  }
@@ -2058,8 +2071,8 @@ Please choose an alternative approach to complete your task.`
2058
2071
  shouldTerminate: shouldTerminate,
2059
2072
  nextStep: shouldTerminate ? 'success' : 'retry',
2060
2073
  ...(currentStepPayloadChangeResult && {
2061
- payloadChangeResult: currentStepPayloadChangeResult
2062
- })
2074
+ payloadChangeResult: currentStepPayloadChangeResult,
2075
+ }),
2063
2076
  };
2064
2077
  await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
2065
2078
  if (subAgentResult.agentRun?.FinalStep === 'Chat') {
@@ -2068,7 +2081,7 @@ Please choose an alternative approach to complete your task.`
2068
2081
  terminate: true,
2069
2082
  message: subAgentResult.agentRun?.Message || null,
2070
2083
  previousPayload: previousDecision?.newPayload,
2071
- newPayload: previousDecision?.newPayload
2084
+ newPayload: previousDecision?.newPayload,
2072
2085
  };
2073
2086
  }
2074
2087
  const subAgentSummary = {
@@ -2077,14 +2090,14 @@ Please choose an alternative approach to complete your task.`
2077
2090
  subAgentId: subAgentEntity.ID,
2078
2091
  success: subAgentResult.success,
2079
2092
  finalStep: subAgentResult.agentRun?.FinalStep,
2080
- errorMessage: subAgentResult.agentRun?.ErrorMessage || null
2093
+ errorMessage: subAgentResult.agentRun?.ErrorMessage || null,
2081
2094
  };
2082
2095
  const resultMessage = subAgentResult.success
2083
2096
  ? `Sub-agent completed successfully:\n${JSON.stringify(subAgentSummary, null, 2)}`
2084
2097
  : `Sub-agent failed:\n${JSON.stringify(subAgentSummary, null, 2)}`;
2085
2098
  params.conversationMessages.push({
2086
2099
  role: 'user',
2087
- content: resultMessage
2100
+ content: resultMessage,
2088
2101
  });
2089
2102
  if (stepEntity) {
2090
2103
  stepEntity.PayloadAtEnd = JSON.stringify(mergedPayload);
@@ -2097,7 +2110,7 @@ Please choose an alternative approach to complete your task.`
2097
2110
  step: subAgentResult.success ? 'Success' : 'Failed',
2098
2111
  terminate: shouldTerminate,
2099
2112
  previousPayload: previousDecision?.newPayload,
2100
- newPayload: mergedPayload
2113
+ newPayload: mergedPayload,
2101
2114
  };
2102
2115
  }
2103
2116
  catch (error) {
@@ -2109,7 +2122,7 @@ Please choose an alternative approach to complete your task.`
2109
2122
  step: 'Failed',
2110
2123
  terminate: false,
2111
2124
  previousPayload: payload,
2112
- newPayload: payload
2125
+ newPayload: payload,
2113
2126
  };
2114
2127
  }
2115
2128
  }
@@ -2122,34 +2135,31 @@ Please choose an alternative approach to complete your task.`
2122
2135
  terminate: false,
2123
2136
  errorMessage: 'Sub-agent name is required',
2124
2137
  previousPayload: previousDecision?.newPayload,
2125
- newPayload: previousDecision?.newPayload
2138
+ newPayload: previousDecision?.newPayload,
2126
2139
  };
2127
2140
  }
2128
- const childAgents = aiengine_1.AIEngine.Instance.Agents.filter(a => a.ParentID === params.agent.ID &&
2129
- a.Status === 'Active');
2130
- const childAgent = childAgents.find(a => a.Name.trim().toLowerCase() === name.trim().toLowerCase());
2141
+ const childAgents = aiengine_1.AIEngine.Instance.Agents.filter((a) => a.ParentID === params.agent.ID && a.Status === 'Active');
2142
+ const childAgent = childAgents.find((a) => a.Name.trim().toLowerCase() === name.trim().toLowerCase());
2131
2143
  if (childAgent) {
2132
2144
  return await this.executeChildSubAgentStep(params, previousDecision);
2133
2145
  }
2134
- const activeRelationships = aiengine_1.AIEngine.Instance.AgentRelationships.filter(ar => ar.AgentID === params.agent.ID &&
2135
- ar.Status === 'Active');
2146
+ const activeRelationships = aiengine_1.AIEngine.Instance.AgentRelationships.filter((ar) => ar.AgentID === params.agent.ID && ar.Status === 'Active');
2136
2147
  for (const relationship of activeRelationships) {
2137
- const relatedAgent = aiengine_1.AIEngine.Instance.Agents.find(a => a.ID === relationship.SubAgentID &&
2138
- a.Status === 'Active');
2148
+ const relatedAgent = aiengine_1.AIEngine.Instance.Agents.find((a) => a.ID === relationship.SubAgentID && a.Status === 'Active');
2139
2149
  if (relatedAgent && relatedAgent.Name.trim().toLowerCase() === name.trim().toLowerCase()) {
2140
2150
  return await this.executeRelatedSubAgentStep(params, previousDecision, relatedAgent, relationship);
2141
2151
  }
2142
2152
  }
2143
2153
  this.logError(`Sub-agent '${name}' not found or not active for agent '${params.agent.Name}'`, {
2144
2154
  agent: params.agent,
2145
- category: 'SubAgentExecution'
2155
+ category: 'SubAgentExecution',
2146
2156
  });
2147
2157
  return {
2148
2158
  step: 'Retry',
2149
2159
  terminate: false,
2150
2160
  errorMessage: `Sub-agent '${name}' not found or not active`,
2151
2161
  previousPayload: previousDecision?.newPayload,
2152
- newPayload: previousDecision?.newPayload
2162
+ newPayload: previousDecision?.newPayload,
2153
2163
  };
2154
2164
  }
2155
2165
  async executeRelatedSubAgentStep(params, previousDecision, subAgentEntity, relationship) {
@@ -2165,12 +2175,12 @@ Please choose an alternative approach to complete your task.`
2165
2175
  agentName: params.agent.Name,
2166
2176
  subAgentName: subAgentRequest.name,
2167
2177
  reason: subAgentRequest.message,
2168
- relationshipType: 'related'
2169
- }
2178
+ relationshipType: 'related',
2179
+ },
2170
2180
  });
2171
2181
  params.conversationMessages.push({
2172
2182
  role: 'assistant',
2173
- content: `I'm delegating this task to the "${subAgentRequest.name}" agent.\n\nReason: ${subAgentRequest.message}`
2183
+ content: `I'm delegating this task to the "${subAgentRequest.name}" agent.\n\nReason: ${subAgentRequest.message}`,
2174
2184
  });
2175
2185
  const inputData = {
2176
2186
  agentName: params.agent.Name,
@@ -2179,7 +2189,7 @@ Please choose an alternative approach to complete your task.`
2179
2189
  terminateAfter: subAgentRequest.terminateAfter,
2180
2190
  conversationMessages: params.conversationMessages,
2181
2191
  parentAgentHierarchy: this._agentHierarchy,
2182
- relationshipType: 'related'
2192
+ relationshipType: 'related',
2183
2193
  };
2184
2194
  const stepEntity = await this.createStepEntity({
2185
2195
  stepType: 'Sub-Agent',
@@ -2187,7 +2197,7 @@ Please choose an alternative approach to complete your task.`
2187
2197
  contextUser: params.contextUser,
2188
2198
  targetId: subAgentEntity.ID,
2189
2199
  inputData,
2190
- payloadAtStart: previousDecision.newPayload
2200
+ payloadAtStart: previousDecision.newPayload,
2191
2201
  });
2192
2202
  this.incrementExecutionCount(subAgentEntity.ID);
2193
2203
  try {
@@ -2197,8 +2207,8 @@ Please choose an alternative approach to complete your task.`
2197
2207
  const mapped = this.applySubAgentInputMapping(previousDecision.newPayload, relationship.SubAgentInputMapping);
2198
2208
  if (mapped && Object.keys(mapped).length > 0) {
2199
2209
  initialSubAgentPayload = mapped;
2200
- if (params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)()) {
2201
- (0, core_1.LogStatus)(`Related sub-agent '${subAgentRequest.name}' receiving mapped payload: ${JSON.stringify(Object.keys(mapped))}`);
2210
+ if (params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)()) {
2211
+ (0, global_1.LogStatus)(`Related sub-agent '${subAgentRequest.name}' receiving mapped payload: ${JSON.stringify(Object.keys(mapped))}`);
2202
2212
  }
2203
2213
  }
2204
2214
  }
@@ -2208,12 +2218,12 @@ Please choose an alternative approach to complete your task.`
2208
2218
  contextPaths = JSON.parse(relationship.SubAgentContextPaths);
2209
2219
  }
2210
2220
  catch (parseError) {
2211
- (0, core_1.LogError)(`Failed to parse SubAgentContextPaths for sub-agent ${subAgentRequest.name}: ${parseError.message}`);
2221
+ (0, global_1.LogError)(`Failed to parse SubAgentContextPaths for sub-agent ${subAgentRequest.name}: ${parseError.message}`);
2212
2222
  }
2213
2223
  }
2214
2224
  const contextMessage = this.prepareRelatedSubAgentContextMessage(previousDecision.newPayload, contextPaths);
2215
- if (contextMessage && (params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)())) {
2216
- (0, core_1.LogStatus)(`Related sub-agent '${subAgentRequest.name}' receiving context from paths: ${contextPaths.join(', ')}`);
2225
+ if (contextMessage && (params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)())) {
2226
+ (0, global_1.LogStatus)(`Related sub-agent '${subAgentRequest.name}' receiving context from paths: ${contextPaths.join(', ')}`);
2217
2227
  }
2218
2228
  const subAgentResult = await this.ExecuteSubAgent(params, subAgentRequest, subAgentEntity, stepEntity, initialSubAgentPayload, contextMessage);
2219
2229
  let mergedPayload = previousDecision.newPayload;
@@ -2227,12 +2237,12 @@ Please choose an alternative approach to complete your task.`
2227
2237
  analyzeChanges: true,
2228
2238
  generateDiff: true,
2229
2239
  agentName: `${subAgentRequest.name} (related agent mapping)`,
2230
- verbose: params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)()
2240
+ verbose: params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)(),
2231
2241
  });
2232
2242
  mergedPayload = mergeResult.result;
2233
2243
  currentStepPayloadChangeResult = this.buildPayloadChangeResultSummary(mergeResult);
2234
- if (mergeResult.warnings.length > 0 && (params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)())) {
2235
- (0, core_1.LogStatus)(`Related sub-agent mapping warnings: ${mergeResult.warnings.join('; ')}`);
2244
+ if (mergeResult.warnings.length > 0 && (params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)())) {
2245
+ (0, global_1.LogStatus)(`Related sub-agent mapping warnings: ${mergeResult.warnings.join('; ')}`);
2236
2246
  }
2237
2247
  }
2238
2248
  }
@@ -2243,13 +2253,13 @@ Please choose an alternative approach to complete your task.`
2243
2253
  finalStep: subAgentResult.agentRun?.FinalStep,
2244
2254
  errorMessage: subAgentResult.agentRun?.ErrorMessage,
2245
2255
  stepCount: subAgentResult.agentRun?.Steps?.length || 0,
2246
- hasMergedPayload: !!(relationship.SubAgentOutputMapping && mergedPayload !== previousDecision.newPayload)
2256
+ hasMergedPayload: !!(relationship.SubAgentOutputMapping && mergedPayload !== previousDecision.newPayload),
2247
2257
  },
2248
2258
  shouldTerminate: shouldTerminate,
2249
2259
  nextStep: shouldTerminate ? 'success' : 'retry',
2250
2260
  ...(currentStepPayloadChangeResult && {
2251
- payloadChangeResult: currentStepPayloadChangeResult
2252
- })
2261
+ payloadChangeResult: currentStepPayloadChangeResult,
2262
+ }),
2253
2263
  };
2254
2264
  if (stepEntity) {
2255
2265
  stepEntity.PayloadAtEnd = JSON.stringify(mergedPayload);
@@ -2261,7 +2271,7 @@ Please choose an alternative approach to complete your task.`
2261
2271
  terminate: true,
2262
2272
  message: subAgentResult.agentRun?.Message || null,
2263
2273
  previousPayload: previousDecision?.newPayload,
2264
- newPayload: previousDecision?.newPayload
2274
+ newPayload: previousDecision?.newPayload,
2265
2275
  };
2266
2276
  }
2267
2277
  const subAgentSummary = {
@@ -2269,11 +2279,11 @@ Please choose an alternative approach to complete your task.`
2269
2279
  subAgentName: subAgentRequest.name,
2270
2280
  success: subAgentResult.success,
2271
2281
  payload: subAgentResult.payload,
2272
- errorMessage: subAgentResult.agentRun?.ErrorMessage
2282
+ errorMessage: subAgentResult.agentRun?.ErrorMessage,
2273
2283
  };
2274
2284
  params.conversationMessages.push({
2275
2285
  role: 'user',
2276
- content: `Related sub-agent "${subAgentRequest.name}" completed:\n${JSON.stringify(subAgentSummary, null, 2)}`
2286
+ content: `Related sub-agent "${subAgentRequest.name}" completed:\n${JSON.stringify(subAgentSummary, null, 2)}`,
2277
2287
  });
2278
2288
  if (this._agentRun) {
2279
2289
  this._agentRun.FinalPayloadObject = mergedPayload;
@@ -2283,7 +2293,7 @@ Please choose an alternative approach to complete your task.`
2283
2293
  step: subAgentResult.success ? 'Success' : 'Failed',
2284
2294
  terminate: shouldTerminate,
2285
2295
  previousPayload: previousDecision?.newPayload,
2286
- newPayload: mergedPayload
2296
+ newPayload: mergedPayload,
2287
2297
  };
2288
2298
  }
2289
2299
  catch (error) {
@@ -2295,7 +2305,7 @@ Please choose an alternative approach to complete your task.`
2295
2305
  step: 'Failed',
2296
2306
  terminate: false,
2297
2307
  previousPayload: payload,
2298
- newPayload: payload
2308
+ newPayload: payload,
2299
2309
  };
2300
2310
  }
2301
2311
  }
@@ -2328,11 +2338,11 @@ Please choose an alternative approach to complete your task.`
2328
2338
  return null;
2329
2339
  }
2330
2340
  return {
2331
- updateElements: updateObj
2341
+ updateElements: updateObj,
2332
2342
  };
2333
2343
  }
2334
2344
  catch (error) {
2335
- (0, core_1.LogError)(`Failed to parse SubAgentOutputMapping: ${error.message}`);
2345
+ (0, global_1.LogError)(`Failed to parse SubAgentOutputMapping: ${error.message}`);
2336
2346
  return null;
2337
2347
  }
2338
2348
  }
@@ -2367,7 +2377,7 @@ Please choose an alternative approach to complete your task.`
2367
2377
  return subAgentPayload;
2368
2378
  }
2369
2379
  catch (error) {
2370
- (0, core_1.LogError)(`Failed to parse SubAgentInputMapping: ${error.message}`);
2380
+ (0, global_1.LogError)(`Failed to parse SubAgentInputMapping: ${error.message}`);
2371
2381
  return null;
2372
2382
  }
2373
2383
  }
@@ -2378,7 +2388,7 @@ Please choose an alternative approach to complete your task.`
2378
2388
  if (contextPaths.includes('*')) {
2379
2389
  return {
2380
2390
  role: 'user',
2381
- content: `Parent Agent Context:\n\n${JSON.stringify(parentPayload, null, 2)}`
2391
+ content: `Parent Agent Context:\n\n${JSON.stringify(parentPayload, null, 2)}`,
2382
2392
  };
2383
2393
  }
2384
2394
  const contextData = {};
@@ -2392,14 +2402,12 @@ Please choose an alternative approach to complete your task.`
2392
2402
  return null;
2393
2403
  }
2394
2404
  const contextLines = Object.entries(contextData).map(([key, value]) => {
2395
- const valueStr = typeof value === 'object'
2396
- ? JSON.stringify(value, null, 2)
2397
- : String(value);
2405
+ const valueStr = typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value);
2398
2406
  return `${key}:\n${valueStr}`;
2399
2407
  });
2400
2408
  return {
2401
2409
  role: 'user',
2402
- content: `Parent Agent Context:\n\n${contextLines.join('\n\n')}`
2410
+ content: `Parent Agent Context:\n\n${contextLines.join('\n\n')}`,
2403
2411
  };
2404
2412
  }
2405
2413
  async executeActionsStep(params, previousDecision, parentStepId, addConversationMessage = true) {
@@ -2427,19 +2435,23 @@ Please choose an alternative approach to complete your task.`
2427
2435
  }
2428
2436
  }
2429
2437
  else {
2430
- progressMessage = `Executing **${actions.length} actions** in parallel:\n\n` + actions.map((aa, index) => {
2431
- let actionText = `${index + 1}. **${aa.name}**`;
2432
- if (aa.params && Object.keys(aa.params).length > 0) {
2433
- const paramsList = Object.entries(aa.params)
2434
- .map(([key, value]) => {
2435
- const displayValue = this.formatParamValueForMessage(value);
2436
- return ` • **${key}**: ${displayValue}`;
2438
+ progressMessage =
2439
+ `Executing **${actions.length} actions** in parallel:\n\n` +
2440
+ actions
2441
+ .map((aa, index) => {
2442
+ let actionText = `${index + 1}. **${aa.name}**`;
2443
+ if (aa.params && Object.keys(aa.params).length > 0) {
2444
+ const paramsList = Object.entries(aa.params)
2445
+ .map(([key, value]) => {
2446
+ const displayValue = this.formatParamValueForMessage(value);
2447
+ return ` • **${key}**: ${displayValue}`;
2448
+ })
2449
+ .join('\n');
2450
+ actionText += `\n${paramsList}`;
2451
+ }
2452
+ return actionText;
2437
2453
  })
2438
- .join('\n');
2439
- actionText += `\n${paramsList}`;
2440
- }
2441
- return actionText;
2442
- }).join('\n\n');
2454
+ .join('\n\n');
2443
2455
  }
2444
2456
  params.onProgress?.({
2445
2457
  step: 'action_execution',
@@ -2447,9 +2459,9 @@ Please choose an alternative approach to complete your task.`
2447
2459
  message: this.formatHierarchicalMessage(progressMessage),
2448
2460
  metadata: {
2449
2461
  actionCount: actions.length,
2450
- actionNames: actions.map(a => a.name)
2462
+ actionNames: actions.map((a) => a.name),
2451
2463
  },
2452
- displayMode: 'live'
2464
+ displayMode: 'live',
2453
2465
  });
2454
2466
  let actionMessage;
2455
2467
  if (actions.length === 1) {
@@ -2469,48 +2481,61 @@ Please choose an alternative approach to complete your task.`
2469
2481
  }
2470
2482
  }
2471
2483
  else {
2472
- actionMessage = `I'm executing **${actions.length} actions** in parallel:\n\n` + actions.map((aa, index) => {
2473
- let actionText = `${index + 1}. **${aa.name}**`;
2474
- if (aa.params && Object.keys(aa.params).length > 0) {
2475
- const paramsList = Object.entries(aa.params)
2476
- .map(([key, value]) => {
2477
- const displayValue = this.formatParamValueForMessage(value);
2478
- return ` • **${key}**: ${displayValue}`;
2484
+ actionMessage =
2485
+ `I'm executing **${actions.length} actions** in parallel:\n\n` +
2486
+ actions
2487
+ .map((aa, index) => {
2488
+ let actionText = `${index + 1}. **${aa.name}**`;
2489
+ if (aa.params && Object.keys(aa.params).length > 0) {
2490
+ const paramsList = Object.entries(aa.params)
2491
+ .map(([key, value]) => {
2492
+ const displayValue = this.formatParamValueForMessage(value);
2493
+ return ` • **${key}**: ${displayValue}`;
2494
+ })
2495
+ .join('\n');
2496
+ actionText += `\n${paramsList}`;
2497
+ }
2498
+ return actionText;
2479
2499
  })
2480
- .join('\n');
2481
- actionText += `\n${paramsList}`;
2482
- }
2483
- return actionText;
2484
- }).join('\n\n');
2500
+ .join('\n\n');
2485
2501
  }
2486
2502
  if (addConversationMessage) {
2487
2503
  params.conversationMessages.push({
2488
2504
  role: 'assistant',
2489
- content: actionMessage
2505
+ content: actionMessage,
2490
2506
  });
2491
2507
  }
2492
2508
  const actionEngine = actions_1.ActionEngineServer.Instance;
2493
- const agentActions = aiengine_1.AIEngine.Instance.AgentActions.filter(aa => aa.AgentID === params.agent.ID);
2509
+ const agentActions = aiengine_1.AIEngine.Instance.AgentActions.filter((aa) => aa.AgentID === params.agent.ID);
2494
2510
  try {
2495
2511
  const currentPayload = previousDecision?.newPayload || previousDecision?.previousPayload || params.payload;
2496
2512
  await this.AgentTypeInstance.PreProcessActionStep(actions, currentPayload, this.AgentTypeState, previousDecision);
2497
2513
  }
2498
2514
  catch (error) {
2499
- (0, core_1.LogError)(`Error in PreProcessActionStep: ${error.message}`);
2515
+ (0, global_1.LogError)(`Error in PreProcessActionStep: ${error.message}`);
2500
2516
  }
2501
2517
  let numActionsProcessed = 0;
2502
2518
  const baseStepNumber = (this._agentRun.Steps?.length || 0) + 1;
2503
2519
  let lastStep = undefined;
2504
2520
  const actionPromises = actions.map(async (aa) => {
2505
- const actionEntity = actionEngine.Actions.find(a => a.Name === aa.name && agentActions.some(aa => aa.ActionID === a.ID));
2521
+ const actionEntity = actionEngine.Actions.find((a) => a.Name === aa.name && agentActions.some((aa) => aa.ActionID === a.ID));
2506
2522
  if (!actionEntity) {
2507
2523
  throw new Error(`Action "${aa.name}" Not Found for Agent "${params.agent.Name}"`);
2508
2524
  }
2509
2525
  const actionInputData = {
2510
2526
  actionName: aa.name,
2511
- actionParams: aa.params
2527
+ actionParams: aa.params,
2512
2528
  };
2513
- const stepEntity = await this.createStepEntity({ stepType: 'Actions', stepName: `Execute Action: ${aa.name}`, contextUser: params.contextUser, targetId: actionEntity.ID, inputData: actionInputData, payloadAtStart: currentPayload, payloadAtEnd: currentPayload, parentId: parentStepId });
2529
+ const stepEntity = await this.createStepEntity({
2530
+ stepType: 'Actions',
2531
+ stepName: `Execute Action: ${aa.name}`,
2532
+ contextUser: params.contextUser,
2533
+ targetId: actionEntity.ID,
2534
+ inputData: actionInputData,
2535
+ payloadAtStart: currentPayload,
2536
+ payloadAtEnd: currentPayload,
2537
+ parentId: parentStepId,
2538
+ });
2514
2539
  lastStep = stepEntity;
2515
2540
  stepEntity.StepNumber = baseStepNumber + numActionsProcessed++;
2516
2541
  this.incrementExecutionCount(actionEntity.ID);
@@ -2526,8 +2551,8 @@ Please choose an alternative approach to complete your task.`
2526
2551
  success: actionResult.Success,
2527
2552
  resultCode: actionResult.Result?.ResultCode,
2528
2553
  message: actionResult.Message,
2529
- parameters: actionResult.Params
2530
- }
2554
+ parameters: actionResult.Params,
2555
+ },
2531
2556
  };
2532
2557
  await this.finalizeStepEntity(stepEntity, actionResult.Success, actionResult.Success ? undefined : actionResult.Message, outputData);
2533
2558
  return { success: true, result: actionResult, action: aa, actionEntity, stepEntity };
@@ -2541,22 +2566,23 @@ Please choose an alternative approach to complete your task.`
2541
2566
  if (params.cancellationToken?.aborted) {
2542
2567
  throw new Error('Cancelled after action execution');
2543
2568
  }
2544
- const actionSummaries = actionResults.map(result => {
2569
+ const actionSummaries = actionResults.map((result) => {
2545
2570
  const actionResult = result.success ? result.result : null;
2546
2571
  return {
2547
2572
  actionName: result.action.name,
2548
2573
  success: result.success,
2549
- params: result.result?.Params.filter(p => p.Type === 'Both' || p.Type === 'Output'),
2574
+ params: result.result?.Params.filter((p) => p.Type === 'Both' || p.Type === 'Output'),
2550
2575
  resultCode: actionResult?.Result?.ResultCode || (result.success ? 'SUCCESS' : 'ERROR'),
2551
- message: result.success ? actionResult?.Message || 'Action completed' : result.error
2576
+ message: result.success ? actionResult?.Message || 'Action completed' : result.error,
2552
2577
  };
2553
2578
  });
2554
- const failedActions = actionSummaries.filter(a => !a.success);
2555
- const resultsMessage = (failedActions.length > 0 ? `${failedActions.length} of ${actionSummaries.length} failed:` : `Action results:`) + `\n${JSON.stringify(actionSummaries, null, 2)}`;
2579
+ const failedActions = actionSummaries.filter((a) => !a.success);
2580
+ const resultsMessage = (failedActions.length > 0 ? `${failedActions.length} of ${actionSummaries.length} failed:` : `Action results:`) +
2581
+ `\n${JSON.stringify(actionSummaries, null, 2)}`;
2556
2582
  let metadata;
2557
2583
  const agentActionConfigs = actionResults
2558
- .map(r => agentActions.find(aa => aa.ActionID === r.actionEntity.ID))
2559
- .filter(aa => aa != null);
2584
+ .map((r) => agentActions.find((aa) => aa.ActionID === r.actionEntity.ID))
2585
+ .filter((aa) => aa != null);
2560
2586
  if (agentActionConfigs.length > 0) {
2561
2587
  let minExpirationTurns = null;
2562
2588
  let expirationMode = 'None';
@@ -2583,7 +2609,7 @@ Please choose an alternative approach to complete your task.`
2583
2609
  expirationMode: expirationMode,
2584
2610
  compactMode: compactMode,
2585
2611
  compactLength: compactLength,
2586
- compactPromptId: compactPromptId
2612
+ compactPromptId: compactPromptId,
2587
2613
  };
2588
2614
  }
2589
2615
  }
@@ -2591,17 +2617,15 @@ Please choose an alternative approach to complete your task.`
2591
2617
  params.conversationMessages.push({
2592
2618
  role: 'user',
2593
2619
  content: resultsMessage,
2594
- metadata: metadata
2620
+ metadata: metadata,
2595
2621
  });
2596
2622
  }
2597
2623
  let finalPayload = currentPayload;
2598
2624
  try {
2599
- const actionResultsOnly = actionResults.map(r => r.result).filter(r => r !== undefined);
2625
+ const actionResultsOnly = actionResults.map((r) => r.result).filter((r) => r !== undefined);
2600
2626
  const payloadChangeRequest = await this.AgentTypeInstance.PostProcessActionStep(actionResultsOnly, actions, currentPayload, this.AgentTypeState, previousDecision);
2601
2627
  if (payloadChangeRequest) {
2602
- const allowedPaths = params.agent.PayloadSelfWritePaths
2603
- ? JSON.parse(params.agent.PayloadSelfWritePaths)
2604
- : undefined;
2628
+ const allowedPaths = params.agent.PayloadSelfWritePaths ? JSON.parse(params.agent.PayloadSelfWritePaths) : undefined;
2605
2629
  const changeResult = this._payloadManager.applyAgentChangeRequest(currentPayload, payloadChangeRequest, {
2606
2630
  validateChanges: true,
2607
2631
  logChanges: true,
@@ -2609,20 +2633,20 @@ Please choose an alternative approach to complete your task.`
2609
2633
  analyzeChanges: true,
2610
2634
  generateDiff: true,
2611
2635
  allowedPaths: allowedPaths,
2612
- verbose: params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)()
2636
+ verbose: params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)(),
2613
2637
  });
2614
2638
  finalPayload = changeResult.result;
2615
2639
  if (lastStep) {
2616
2640
  lastStep.PayloadAtEnd = JSON.stringify(finalPayload);
2617
2641
  await lastStep.Save();
2618
2642
  }
2619
- if (changeResult.warnings.length > 0 && (params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)())) {
2620
- (0, core_1.LogStatus)(`Action post-processing payload warnings: ${changeResult.warnings.join('; ')}`);
2643
+ if (changeResult.warnings.length > 0 && (params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)())) {
2644
+ (0, global_1.LogStatus)(`Action post-processing payload warnings: ${changeResult.warnings.join('; ')}`);
2621
2645
  }
2622
2646
  }
2623
2647
  }
2624
2648
  catch (error) {
2625
- (0, core_1.LogError)(`Error in PostProcessActionStep: ${error.message}`);
2649
+ (0, global_1.LogError)(`Error in PostProcessActionStep: ${error.message}`);
2626
2650
  }
2627
2651
  return {
2628
2652
  terminate: false,
@@ -2631,8 +2655,8 @@ Please choose an alternative approach to complete your task.`
2631
2655
  newPayload: finalPayload,
2632
2656
  priorStepResult: actionSummaries,
2633
2657
  retryReason: failedActions.length > 0
2634
- ? `Processing results with ${failedActions.length} failed action(s): ${failedActions.map(a => a.actionName).join(', ')}`
2635
- : `Analyzing results from ${actionSummaries.length} completed action(s) to formulate response`
2658
+ ? `Processing results with ${failedActions.length} failed action(s): ${failedActions.map((a) => a.actionName).join(', ')}`
2659
+ : `Analyzing results from ${actionSummaries.length} completed action(s) to formulate response`,
2636
2660
  };
2637
2661
  }
2638
2662
  catch (e) {
@@ -2658,7 +2682,7 @@ Please choose an alternative approach to complete your task.`
2658
2682
  confidence: previousDecision.confidence,
2659
2683
  previousPayload: previousDecision.previousPayload,
2660
2684
  newPayload: previousDecision.newPayload || previousDecision.previousPayload,
2661
- suggestedResponses: previousDecision.suggestedResponses
2685
+ suggestedResponses: previousDecision.suggestedResponses,
2662
2686
  };
2663
2687
  }
2664
2688
  async executeForEachLoop(params, config, previousDecision) {
@@ -2710,10 +2734,12 @@ Please choose an alternative approach to complete your task.`
2710
2734
  return null;
2711
2735
  }
2712
2736
  validateActionInAgent(actionName) {
2713
- const aa = aiengine_1.AIEngine.Instance.AgentActions.filter(aa => aa.AgentID === this._agentRun.AgentID);
2714
- let action = aa.filter(a => a.Agent?.trim().toLowerCase() === actionName.trim().toLowerCase());
2737
+ const aa = aiengine_1.AIEngine.Instance.AgentActions.filter((aa) => aa.AgentID === this._agentRun.AgentID);
2738
+ let action = aa.filter((a) => a.Agent?.trim().toLowerCase() === actionName.trim().toLowerCase());
2715
2739
  if (!action) {
2716
- const partialAction = aa.filter(a => a.Agent?.trim().toLowerCase().includes(actionName.trim().toLowerCase() || ''));
2740
+ const partialAction = aa.filter((a) => a.Agent?.trim()
2741
+ .toLowerCase()
2742
+ .includes(actionName.trim().toLowerCase() || ''));
2717
2743
  if (partialAction.length > 1) {
2718
2744
  return `Ambiguous action '${actionName}' specified`;
2719
2745
  }
@@ -2724,18 +2750,22 @@ Please choose an alternative approach to complete your task.`
2724
2750
  return null;
2725
2751
  }
2726
2752
  validateSubAgentInAgent(subAgentName) {
2727
- const relatedAgents = aiengine_1.AIEngine.Instance.AgentRelationships.filter(ar => ar.AgentID === this._agentRun.AgentID);
2728
- const childAgents = aiengine_1.AIEngine.Instance.Agents.filter(a => a.ParentID === this._agentRun.AgentID);
2729
- let subAgent = relatedAgents.filter(ra => ra.SubAgent?.trim().toLowerCase() === subAgentName.trim().toLowerCase());
2753
+ const relatedAgents = aiengine_1.AIEngine.Instance.AgentRelationships.filter((ar) => ar.AgentID === this._agentRun.AgentID);
2754
+ const childAgents = aiengine_1.AIEngine.Instance.Agents.filter((a) => a.ParentID === this._agentRun.AgentID);
2755
+ let subAgent = relatedAgents.filter((ra) => ra.SubAgent?.trim().toLowerCase() === subAgentName.trim().toLowerCase());
2730
2756
  if (subAgent.length === 0) {
2731
- subAgent = relatedAgents.filter(ra => ra.SubAgent?.trim().toLowerCase().includes(subAgentName.trim().toLowerCase() || ''));
2757
+ subAgent = relatedAgents.filter((ra) => ra.SubAgent?.trim()
2758
+ .toLowerCase()
2759
+ .includes(subAgentName.trim().toLowerCase() || ''));
2732
2760
  if (subAgent.length > 1) {
2733
2761
  return `Ambiguous sub-agent '${subAgentName}' specified`;
2734
2762
  }
2735
2763
  else if (subAgent.length === 0) {
2736
- let childAgent = childAgents.filter(ca => ca.Name?.trim().toLowerCase() === subAgentName.trim().toLowerCase());
2764
+ let childAgent = childAgents.filter((ca) => ca.Name?.trim().toLowerCase() === subAgentName.trim().toLowerCase());
2737
2765
  if (childAgent.length === 0) {
2738
- childAgent = childAgents.filter(ca => ca.Name?.trim().toLowerCase().includes(subAgentName.trim().toLowerCase() || ''));
2766
+ childAgent = childAgents.filter((ca) => ca.Name?.trim()
2767
+ .toLowerCase()
2768
+ .includes(subAgentName.trim().toLowerCase() || ''));
2739
2769
  if (childAgent.length > 1) {
2740
2770
  return `Ambiguous child agent '${subAgentName}' specified`;
2741
2771
  }
@@ -2750,9 +2780,7 @@ Please choose an alternative approach to complete your task.`
2750
2780
  return null;
2751
2781
  }
2752
2782
  getCollectionFromPayload(payload, path) {
2753
- const cleanPath = path.toLowerCase().startsWith('payload.')
2754
- ? path.substring(8)
2755
- : path;
2783
+ const cleanPath = path.toLowerCase().startsWith('payload.') ? path.substring(8) : path;
2756
2784
  const value = this.getValueFromPath(payload, cleanPath);
2757
2785
  return Array.isArray(value) ? value : null;
2758
2786
  }
@@ -2762,7 +2790,7 @@ Please choose an alternative approach to complete your task.`
2762
2790
  stepName: `ForEach: ${forEach.collectionPath} (${collection.length} items)`,
2763
2791
  contextUser: params.contextUser,
2764
2792
  inputData: { forEach, count: collection.length },
2765
- payloadAtStart: payload
2793
+ payloadAtStart: payload,
2766
2794
  });
2767
2795
  return stepEntity;
2768
2796
  }
@@ -2782,7 +2810,7 @@ Please choose an alternative approach to complete your task.`
2782
2810
  const errors = [];
2783
2811
  for (let i = 0; i < Math.min(collection.length, maxIterations); i++) {
2784
2812
  if (i > 0 && forEach.delayBetweenIterationsMs) {
2785
- await new Promise(resolve => setTimeout(resolve, forEach.delayBetweenIterationsMs));
2813
+ await new Promise((resolve) => setTimeout(resolve, forEach.delayBetweenIterationsMs));
2786
2814
  }
2787
2815
  const iterResult = await this.executeSingleForEachIteration(forEach, collection[i], i, currentPayload, parentStepId, params, config);
2788
2816
  if (iterResult.error) {
@@ -2805,18 +2833,18 @@ Please choose an alternative approach to complete your task.`
2805
2833
  const allResults = [];
2806
2834
  for (let batchIndex = 0; batchIndex < batches.length; batchIndex++) {
2807
2835
  const batch = batches[batchIndex];
2808
- const batchPromises = batch.map(({ item, index }) => this.executeSingleForEachIteration(forEach, item, index, initialPayload, parentStepId, params, config).then(iterResult => ({
2836
+ const batchPromises = batch.map(({ item, index }) => this.executeSingleForEachIteration(forEach, item, index, initialPayload, parentStepId, params, config).then((iterResult) => ({
2809
2837
  index,
2810
2838
  result: iterResult.result,
2811
2839
  error: iterResult.error,
2812
- payload: iterResult.payload
2840
+ payload: iterResult.payload,
2813
2841
  })));
2814
2842
  const batchResults = await Promise.all(batchPromises);
2815
2843
  allResults.push(...batchResults);
2816
2844
  if (forEach.delayBetweenIterationsMs && batchIndex < batches.length - 1) {
2817
- await new Promise(resolve => setTimeout(resolve, forEach.delayBetweenIterationsMs));
2845
+ await new Promise((resolve) => setTimeout(resolve, forEach.delayBetweenIterationsMs));
2818
2846
  }
2819
- const hasFailure = batchResults.some(r => r.error);
2847
+ const hasFailure = batchResults.some((r) => r.error);
2820
2848
  if (hasFailure && !forEach.continueOnError) {
2821
2849
  break;
2822
2850
  }
@@ -2829,7 +2857,7 @@ Please choose an alternative approach to complete your task.`
2829
2857
  for (let i = 0; i < items.length; i += maxConcurrency) {
2830
2858
  const batch = items.slice(i, i + maxConcurrency).map((item, batchOffset) => ({
2831
2859
  item,
2832
- index: i + batchOffset
2860
+ index: i + batchOffset,
2833
2861
  }));
2834
2862
  batches.push(batch);
2835
2863
  }
@@ -2855,27 +2883,51 @@ Please choose an alternative approach to complete your task.`
2855
2883
  }
2856
2884
  async executeSingleForEachIteration(forEach, item, index, currentPayload, parentStepId, params, config) {
2857
2885
  try {
2858
- const beforeHook = this.AgentTypeInstance.BeforeLoopIteration?.({ item, itemVariable: forEach.itemVariable, index, payload: currentPayload, loopType: 'ForEach', actionParams: forEach.action?.params || {} });
2886
+ const beforeHook = this.AgentTypeInstance.BeforeLoopIteration?.({
2887
+ item,
2888
+ itemVariable: forEach.itemVariable,
2889
+ index,
2890
+ payload: currentPayload,
2891
+ loopType: 'ForEach',
2892
+ actionParams: forEach.action?.params || {},
2893
+ });
2859
2894
  const resolvedParams = beforeHook?.actionParams || forEach.action?.params || {};
2860
2895
  let result;
2861
2896
  if (forEach.action) {
2862
2897
  const matchedAction = this.findAgentActionForLoop(forEach.action.name, params.agent.ID, params.agent.Name, params);
2863
2898
  const resolvedAction = {
2864
2899
  name: matchedAction.Action,
2865
- params: resolvedParams
2900
+ params: resolvedParams,
2901
+ };
2902
+ const actionStep = {
2903
+ step: 'Actions',
2904
+ actions: [resolvedAction],
2905
+ newPayload: currentPayload,
2906
+ previousPayload: currentPayload,
2907
+ terminate: false,
2866
2908
  };
2867
- const actionStep = { step: 'Actions', actions: [resolvedAction], newPayload: currentPayload, previousPayload: currentPayload, terminate: false };
2868
2909
  result = await this.executeActionsStep(params, actionStep, parentStepId, false);
2869
2910
  }
2870
2911
  else if (forEach.subAgent) {
2871
- const subAgentStep = { step: 'Sub-Agent', subAgent: forEach.subAgent, newPayload: currentPayload, previousPayload: currentPayload };
2912
+ const subAgentStep = {
2913
+ step: 'Sub-Agent',
2914
+ subAgent: forEach.subAgent,
2915
+ newPayload: currentPayload,
2916
+ previousPayload: currentPayload,
2917
+ };
2872
2918
  result = await this.processSubAgentStep(params, subAgentStep);
2873
2919
  }
2874
2920
  else {
2875
2921
  throw new Error('ForEach missing action/subAgent');
2876
2922
  }
2877
2923
  const iterPayload = result.newPayload || currentPayload;
2878
- const afterHook = this.AgentTypeInstance.AfterLoopIteration?.({ currentPayload: iterPayload, item, itemVariable: forEach.itemVariable, index, loopContext: { actionOutputMapping: forEach.action?.outputMapping } });
2924
+ const afterHook = this.AgentTypeInstance.AfterLoopIteration?.({
2925
+ currentPayload: iterPayload,
2926
+ item,
2927
+ itemVariable: forEach.itemVariable,
2928
+ index,
2929
+ loopContext: { actionOutputMapping: forEach.action?.outputMapping },
2930
+ });
2879
2931
  return { payload: afterHook || iterPayload, result };
2880
2932
  }
2881
2933
  catch (error) {
@@ -2893,31 +2945,31 @@ Please choose an alternative approach to complete your task.`
2893
2945
  retryInstructions: `Completed ForEach loop request using collection at '${forEach.collectionPath}'`,
2894
2946
  terminate: false,
2895
2947
  newPayload: loopResults.finalPayload,
2896
- previousPayload: previousDecision.previousPayload
2948
+ previousPayload: previousDecision.previousPayload,
2897
2949
  };
2898
2950
  }
2899
2951
  injectLoopResultsMessage(loopType, collectionOrCondition, results, errors, params) {
2900
- const extractedResults = results.map(r => r.priorStepResult);
2952
+ const extractedResults = results.map((r) => r.priorStepResult);
2901
2953
  const label = loopType === 'ForEach' ? 'Collection' : 'Condition';
2902
2954
  params.conversationMessages.push({
2903
2955
  role: 'user',
2904
2956
  content: `## Loop Completed\n**Type:** ${loopType}\n**${label}:** ${collectionOrCondition}\n` +
2905
2957
  `**Processed:** ${results.length}, **Errors:** ${errors.length}\n\n` +
2906
2958
  `**Results:**\n\`\`\`json\n${JSON.stringify(extractedResults, null, 2)}\n\`\`\``,
2907
- metadata: { _temporary: true, _loopResults: true }
2959
+ metadata: { _temporary: true, _loopResults: true },
2908
2960
  });
2909
2961
  }
2910
2962
  findAgentActionForLoop(actionName, agentId, agentName, params) {
2911
- const agentActions = aiengine_1.AIEngine.Instance.AgentActions.filter(aa => aa.AgentID === agentId && aa.Status === 'Active');
2912
- let matched = agentActions.find(aa => aa.Action.trim().toLowerCase() === actionName.trim().toLowerCase());
2963
+ const agentActions = aiengine_1.AIEngine.Instance.AgentActions.filter((aa) => aa.AgentID === agentId && aa.Status === 'Active');
2964
+ let matched = agentActions.find((aa) => aa.Action.trim().toLowerCase() === actionName.trim().toLowerCase());
2913
2965
  if (!matched) {
2914
- const containsMatches = agentActions.filter(aa => aa.Action.trim().toLowerCase().includes(actionName.trim().toLowerCase()));
2966
+ const containsMatches = agentActions.filter((aa) => aa.Action.trim().toLowerCase().includes(actionName.trim().toLowerCase()));
2915
2967
  if (containsMatches.length === 1) {
2916
2968
  matched = containsMatches[0];
2917
2969
  this.logStatus(`Action fuzzy matched: '${actionName}' → '${matched.Action}'`, true, params);
2918
2970
  }
2919
2971
  else if (containsMatches.length > 1) {
2920
- throw new Error(`Ambiguous action '${actionName}'. Matches: ${containsMatches.map(a => a.Action).join(', ')}`);
2972
+ throw new Error(`Ambiguous action '${actionName}'. Matches: ${containsMatches.map((a) => a.Action).join(', ')}`);
2921
2973
  }
2922
2974
  else {
2923
2975
  throw new Error(`Action '${actionName}' not found for agent '${agentName}'`);
@@ -2931,7 +2983,7 @@ Please choose an alternative approach to complete your task.`
2931
2983
  terminate: false,
2932
2984
  errorMessage,
2933
2985
  previousPayload: previousDecision.previousPayload,
2934
- newPayload: previousDecision.newPayload || previousDecision.previousPayload
2986
+ newPayload: previousDecision.newPayload || previousDecision.previousPayload,
2935
2987
  };
2936
2988
  }
2937
2989
  async executeWhileLoop(params, config, previousDecision) {
@@ -2954,7 +3006,7 @@ Please choose an alternative approach to complete your task.`
2954
3006
  stepName: `While: ${whileOp.condition}`,
2955
3007
  contextUser: params.contextUser,
2956
3008
  inputData: { while: whileOp },
2957
- payloadAtStart: payload
3009
+ payloadAtStart: payload,
2958
3010
  });
2959
3011
  return stepEntity;
2960
3012
  }
@@ -2968,7 +3020,7 @@ Please choose an alternative approach to complete your task.`
2968
3020
  const evaluator = new SafeExpressionEvaluator();
2969
3021
  while (iterationCount < maxIterations) {
2970
3022
  if (iterationCount > 0 && whileOp.delayBetweenIterationsMs) {
2971
- await new Promise(resolve => setTimeout(resolve, whileOp.delayBetweenIterationsMs));
3023
+ await new Promise((resolve) => setTimeout(resolve, whileOp.delayBetweenIterationsMs));
2972
3024
  }
2973
3025
  const evalResult = evaluator.evaluate(whileOp.condition, { payload: currentPayload, results, errors });
2974
3026
  if (!evalResult.success || !evalResult.value) {
@@ -2991,27 +3043,51 @@ Please choose an alternative approach to complete your task.`
2991
3043
  }
2992
3044
  async executeSingleWhileIteration(whileOp, attemptContext, index, currentPayload, parentStepId, params, config) {
2993
3045
  try {
2994
- const beforeHook = this.AgentTypeInstance.BeforeLoopIteration?.({ item: attemptContext, index, itemVariable: whileOp.itemVariable, payload: currentPayload, loopType: 'While', actionParams: whileOp.action?.params || {} });
3046
+ const beforeHook = this.AgentTypeInstance.BeforeLoopIteration?.({
3047
+ item: attemptContext,
3048
+ index,
3049
+ itemVariable: whileOp.itemVariable,
3050
+ payload: currentPayload,
3051
+ loopType: 'While',
3052
+ actionParams: whileOp.action?.params || {},
3053
+ });
2995
3054
  const resolvedParams = beforeHook?.actionParams || whileOp.action?.params || {};
2996
3055
  let result;
2997
3056
  if (whileOp.action) {
2998
3057
  const matchedAction = this.findAgentActionForLoop(whileOp.action.name, params.agent.ID, params.agent.Name, params);
2999
3058
  const resolvedAction = {
3000
3059
  name: matchedAction.Action,
3001
- params: resolvedParams
3060
+ params: resolvedParams,
3061
+ };
3062
+ const actionStep = {
3063
+ step: 'Actions',
3064
+ actions: [resolvedAction],
3065
+ newPayload: currentPayload,
3066
+ previousPayload: currentPayload,
3067
+ terminate: false,
3002
3068
  };
3003
- const actionStep = { step: 'Actions', actions: [resolvedAction], newPayload: currentPayload, previousPayload: currentPayload, terminate: false };
3004
3069
  result = await this.executeActionsStep(params, actionStep, parentStepId, false);
3005
3070
  }
3006
3071
  else if (whileOp.subAgent) {
3007
- const subAgentStep = { step: 'Sub-Agent', subAgent: whileOp.subAgent, newPayload: currentPayload, previousPayload: currentPayload };
3072
+ const subAgentStep = {
3073
+ step: 'Sub-Agent',
3074
+ subAgent: whileOp.subAgent,
3075
+ newPayload: currentPayload,
3076
+ previousPayload: currentPayload,
3077
+ };
3008
3078
  result = await this.processSubAgentStep(params, subAgentStep);
3009
3079
  }
3010
3080
  else {
3011
3081
  throw new Error('While missing action/subAgent');
3012
3082
  }
3013
3083
  const iterPayload = result.newPayload || currentPayload;
3014
- const afterHook = this.AgentTypeInstance.AfterLoopIteration?.({ currentPayload: iterPayload, item: attemptContext, itemVariable: whileOp.itemVariable, index, loopContext: { actionOutputMapping: whileOp.action?.outputMapping } });
3084
+ const afterHook = this.AgentTypeInstance.AfterLoopIteration?.({
3085
+ currentPayload: iterPayload,
3086
+ item: attemptContext,
3087
+ itemVariable: whileOp.itemVariable,
3088
+ index,
3089
+ loopContext: { actionOutputMapping: whileOp.action?.outputMapping },
3090
+ });
3015
3091
  return { payload: afterHook || iterPayload, result };
3016
3092
  }
3017
3093
  catch (error) {
@@ -3029,7 +3105,7 @@ Please choose an alternative approach to complete your task.`
3029
3105
  retryInstructions: `Completed While loop request using condition '${whileOp.condition}' after ${loopResults.iterations} iteration(s)`,
3030
3106
  terminate: false,
3031
3107
  newPayload: loopResults.finalPayload,
3032
- previousPayload: previousDecision.previousPayload
3108
+ previousPayload: previousDecision.previousPayload,
3033
3109
  };
3034
3110
  }
3035
3111
  async createFailureResult(errorMessage, contextUser) {
@@ -3047,7 +3123,7 @@ Please choose an alternative approach to complete your task.`
3047
3123
  }
3048
3124
  return {
3049
3125
  success: false,
3050
- agentRun: this._agentRun
3126
+ agentRun: this._agentRun,
3051
3127
  };
3052
3128
  }
3053
3129
  async createCancelledResult(message, contextUser) {
@@ -3065,7 +3141,7 @@ Please choose an alternative approach to complete your task.`
3065
3141
  }
3066
3142
  return {
3067
3143
  success: false,
3068
- agentRun: this._agentRun
3144
+ agentRun: this._agentRun,
3069
3145
  };
3070
3146
  }
3071
3147
  async finalizeAgentRun(finalStep, payload, contextUser) {
@@ -3093,14 +3169,14 @@ Please choose an alternative approach to complete your task.`
3093
3169
  this._agentRun.TotalCost = tokenStats.totalCost;
3094
3170
  const ok = await this._agentRun.Save();
3095
3171
  if (!ok) {
3096
- (0, core_1.LogError)(`Failed to finalize agent run ${this._agentRun.ID}`);
3172
+ (0, global_1.LogError)(`Failed to finalize agent run ${this._agentRun.ID}`);
3097
3173
  }
3098
3174
  }
3099
3175
  return {
3100
3176
  success: finalStep.step === 'Success' || finalStep.step === 'Chat',
3101
3177
  payload,
3102
3178
  agentRun: this._agentRun,
3103
- suggestedResponses: finalStep.suggestedResponses
3179
+ suggestedResponses: finalStep.suggestedResponses,
3104
3180
  };
3105
3181
  }
3106
3182
  calculateTokenStats() {
@@ -3141,18 +3217,14 @@ Please choose an alternative approach to complete your task.`
3141
3217
  }
3142
3218
  async checkMinimumExecutionRequirements(agent, agentRun) {
3143
3219
  const violations = [];
3144
- const agentActions = aiengine_1.AIEngine.Instance.AgentActions.filter(aa => aa.AgentID === agent.ID &&
3145
- aa.Status === 'Active' &&
3146
- aa.MinExecutionsPerRun != null &&
3147
- aa.MinExecutionsPerRun > 0);
3220
+ const agentActions = aiengine_1.AIEngine.Instance.AgentActions.filter((aa) => aa.AgentID === agent.ID && aa.Status === 'Active' && aa.MinExecutionsPerRun != null && aa.MinExecutionsPerRun > 0);
3148
3221
  for (const agentAction of agentActions) {
3149
3222
  const executionCount = await this.getActionExecutionCount(agentRun.ID, agentAction.ActionID);
3150
3223
  if (executionCount < agentAction.MinExecutionsPerRun) {
3151
3224
  violations.push(`Action '${agentAction.Action}' requires ${agentAction.MinExecutionsPerRun} execution(s) but was executed ${executionCount} time(s)`);
3152
3225
  }
3153
3226
  }
3154
- const subAgents = aiengine_1.AIEngine.Instance.GetSubAgents(agent.ID, "Active").filter(a => a.MinExecutionsPerRun != null &&
3155
- a.MinExecutionsPerRun > 0);
3227
+ const subAgents = aiengine_1.AIEngine.Instance.GetSubAgents(agent.ID, 'Active').filter((a) => a.MinExecutionsPerRun != null && a.MinExecutionsPerRun > 0);
3156
3228
  for (const subAgent of subAgents) {
3157
3229
  const executionCount = await this.getSubAgentExecutionCount(agentRun.ID, subAgent.ID);
3158
3230
  if (executionCount < subAgent.MinExecutionsPerRun) {
@@ -3183,7 +3255,7 @@ Please choose an alternative approach to complete your task.`
3183
3255
  turn: currentTurn,
3184
3256
  messageIndex: i,
3185
3257
  message: msg,
3186
- reason: `Expired after ${turnsAlive} turns (limit: ${msg.metadata.expirationTurns})`
3258
+ reason: `Expired after ${turnsAlive} turns (limit: ${msg.metadata.expirationTurns})`,
3187
3259
  });
3188
3260
  }
3189
3261
  else if (msg.metadata.expirationMode === 'Compact') {
@@ -3195,10 +3267,8 @@ Please choose an alternative approach to complete your task.`
3195
3267
  compactMode: msg.metadata.compactMode,
3196
3268
  compactLength: msg.metadata.compactLength || 500,
3197
3269
  compactPromptId: msg.metadata.compactPromptId || '',
3198
- originalLength: typeof msg.content === 'string'
3199
- ? msg.content.length
3200
- : JSON.stringify(msg.content).length
3201
- }
3270
+ originalLength: typeof msg.content === 'string' ? msg.content.length : JSON.stringify(msg.content).length,
3271
+ },
3202
3272
  });
3203
3273
  }
3204
3274
  }
@@ -3220,8 +3290,8 @@ Please choose an alternative approach to complete your task.`
3220
3290
  originalContent: preserveOriginal ? originalContent : undefined,
3221
3291
  originalLength: item.metadata.originalLength,
3222
3292
  tokensSaved,
3223
- canExpand: preserveOriginal
3224
- }
3293
+ canExpand: preserveOriginal,
3294
+ },
3225
3295
  };
3226
3296
  this.emitMessageLifecycleEvent({
3227
3297
  type: 'message-compacted',
@@ -3229,7 +3299,7 @@ Please choose an alternative approach to complete your task.`
3229
3299
  messageIndex: item.index,
3230
3300
  message: params.conversationMessages[item.index],
3231
3301
  reason: `Compacted using ${item.metadata.compactMode} (saved ${tokensSaved} tokens)`,
3232
- tokensSaved
3302
+ tokensSaved,
3233
3303
  });
3234
3304
  }
3235
3305
  for (let i = messagesToRemove.length - 1; i >= 0; i--) {
@@ -3240,7 +3310,7 @@ Please choose an alternative approach to complete your task.`
3240
3310
  turn: currentTurn,
3241
3311
  messageIndex: index,
3242
3312
  message: removed,
3243
- reason: 'Removed due to expiration'
3313
+ reason: 'Removed due to expiration',
3244
3314
  });
3245
3315
  }
3246
3316
  if (params.verbose && (messagesToCompact.length > 0 || messagesToRemove.length > 0)) {
@@ -3257,7 +3327,7 @@ Please choose an alternative approach to complete your task.`
3257
3327
  if (!this._agentRun) {
3258
3328
  throw new Error('Cannot create compaction step: agent run not initialized');
3259
3329
  }
3260
- const md = new core_1.Metadata();
3330
+ const md = new global_1.Metadata();
3261
3331
  const step = await md.GetEntityObject('MJ: AI Agent Run Steps', params.contextUser);
3262
3332
  step.NewRecord();
3263
3333
  step.AgentRunID = this._agentRun.ID;
@@ -3272,7 +3342,7 @@ Please choose an alternative approach to complete your task.`
3272
3342
  (typeof message.content === 'string' ? message.content.length : JSON.stringify(message.content).length),
3273
3343
  compactMode: 'AI Summary',
3274
3344
  promptId: prompt.ID,
3275
- promptName: prompt.Name
3345
+ promptName: prompt.Name,
3276
3346
  });
3277
3347
  await step.Save();
3278
3348
  return step;
@@ -3288,7 +3358,7 @@ Please choose an alternative approach to complete your task.`
3288
3358
  promptTokens,
3289
3359
  completionTokens,
3290
3360
  totalTokens: promptTokens + completionTokens,
3291
- cost: result.cost
3361
+ cost: result.cost,
3292
3362
  });
3293
3363
  if (!result.success) {
3294
3364
  step.ErrorMessage = result.errorMessage || 'AI Summary compaction failed';
@@ -3296,9 +3366,7 @@ Please choose an alternative approach to complete your task.`
3296
3366
  await step.Save();
3297
3367
  }
3298
3368
  async compactMessage(message, metadata, params) {
3299
- const originalContent = typeof message.content === 'string'
3300
- ? message.content
3301
- : JSON.stringify(message.content);
3369
+ const originalContent = typeof message.content === 'string' ? message.content : JSON.stringify(message.content);
3302
3370
  switch (metadata.compactMode) {
3303
3371
  case 'First N Chars': {
3304
3372
  const length = metadata.compactLength;
@@ -3311,7 +3379,7 @@ Please choose an alternative approach to complete your task.`
3311
3379
  case 'AI Summary': {
3312
3380
  try {
3313
3381
  const promptId = metadata.compactPromptId || this.getSystemDefaultCompactPromptId();
3314
- const prompt = aiengine_1.AIEngine.Instance.Prompts.find(p => p.ID === promptId);
3382
+ const prompt = aiengine_1.AIEngine.Instance.Prompts.find((p) => p.ID === promptId);
3315
3383
  if (!prompt) {
3316
3384
  console.warn(`Compact prompt ${promptId} not found, falling back to First N Chars`);
3317
3385
  return this.compactMessage(message, { ...metadata, compactMode: 'First N Chars' }, params);
@@ -3324,7 +3392,7 @@ Please choose an alternative approach to complete your task.`
3324
3392
  originalLength: metadata.originalLength,
3325
3393
  targetLength: metadata.compactLength || 500,
3326
3394
  messageType: message.metadata?.messageType || 'unknown',
3327
- turnAdded: message.metadata?.turnAdded || 0
3395
+ turnAdded: message.metadata?.turnAdded || 0,
3328
3396
  };
3329
3397
  promptParams.contextUser = params.contextUser;
3330
3398
  const runner = new ai_prompts_1.AIPromptRunner();
@@ -3346,7 +3414,7 @@ Please choose an alternative approach to complete your task.`
3346
3414
  }
3347
3415
  }
3348
3416
  getSystemDefaultCompactPromptId() {
3349
- const prompt = aiengine_1.AIEngine.Instance.Prompts.find(p => p.Name === 'Compact Agent Message');
3417
+ const prompt = aiengine_1.AIEngine.Instance.Prompts.find((p) => p.Name === 'Compact Agent Message');
3350
3418
  if (!prompt) {
3351
3419
  console.warn('System default compact prompt not found. Ensure "Compact Agent Message" prompt exists.');
3352
3420
  return '';
@@ -3354,9 +3422,7 @@ Please choose an alternative approach to complete your task.`
3354
3422
  return prompt.ID;
3355
3423
  }
3356
3424
  estimateTokens(content) {
3357
- const text = typeof content === 'string'
3358
- ? content
3359
- : JSON.stringify(content);
3425
+ const text = typeof content === 'string' ? content : JSON.stringify(content);
3360
3426
  return Math.ceil(text.length / 4);
3361
3427
  }
3362
3428
  emitMessageLifecycleEvent(event) {
@@ -3385,7 +3451,7 @@ Please choose an alternative approach to complete your task.`
3385
3451
  turn: currentTurn,
3386
3452
  messageIndex,
3387
3453
  message,
3388
- reason: reason || 'Agent requested expansion'
3454
+ reason: reason || 'Agent requested expansion',
3389
3455
  });
3390
3456
  if (params.verbose) {
3391
3457
  console.log(`[Turn ${currentTurn}] Expanded message at index ${messageIndex}`);