@memberjunction/ai-agents 2.112.0 → 2.113.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.
Files changed (43) hide show
  1. package/README.md +2 -2
  2. package/dist/AgentDataPreloader.d.ts +1 -1
  3. package/dist/AgentDataPreloader.d.ts.map +1 -1
  4. package/dist/AgentDataPreloader.js +26 -26
  5. package/dist/AgentDataPreloader.js.map +1 -1
  6. package/dist/AgentRunner.d.ts.map +1 -1
  7. package/dist/AgentRunner.js +9 -9
  8. package/dist/AgentRunner.js.map +1 -1
  9. package/dist/PayloadChangeAnalyzer.d.ts.map +1 -1
  10. package/dist/PayloadChangeAnalyzer.js +43 -30
  11. package/dist/PayloadChangeAnalyzer.js.map +1 -1
  12. package/dist/PayloadFeedbackManager.d.ts.map +1 -1
  13. package/dist/PayloadFeedbackManager.js +18 -18
  14. package/dist/PayloadFeedbackManager.js.map +1 -1
  15. package/dist/PayloadManager.d.ts.map +1 -1
  16. package/dist/PayloadManager.js +57 -45
  17. package/dist/PayloadManager.js.map +1 -1
  18. package/dist/agent-context-injector.d.ts +34 -0
  19. package/dist/agent-context-injector.d.ts.map +1 -0
  20. package/dist/agent-context-injector.js +170 -0
  21. package/dist/agent-context-injector.js.map +1 -0
  22. package/dist/agent-types/base-agent-type.d.ts.map +1 -1
  23. package/dist/agent-types/base-agent-type.js +7 -7
  24. package/dist/agent-types/base-agent-type.js.map +1 -1
  25. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  26. package/dist/agent-types/flow-agent-type.js +77 -80
  27. package/dist/agent-types/flow-agent-type.js.map +1 -1
  28. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  29. package/dist/agent-types/loop-agent-type.js +30 -28
  30. package/dist/agent-types/loop-agent-type.js.map +1 -1
  31. package/dist/base-agent.d.ts +33 -6
  32. package/dist/base-agent.d.ts.map +1 -1
  33. package/dist/base-agent.js +821 -539
  34. package/dist/base-agent.js.map +1 -1
  35. package/dist/index.d.ts +2 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +2 -0
  38. package/dist/index.js.map +1 -1
  39. package/dist/memory-manager-agent.d.ts +17 -0
  40. package/dist/memory-manager-agent.d.ts.map +1 -0
  41. package/dist/memory-manager-agent.js +344 -0
  42. package/dist/memory-manager-agent.js.map +1 -0
  43. package/package.json +10 -9
@@ -24,13 +24,14 @@ 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 global_1 = require("@memberjunction/global");
27
+ const core_1 = require("@memberjunction/core");
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_2 = require("@memberjunction/global");
30
+ const global_1 = 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");
34
+ const agent_context_injector_1 = require("./agent-context-injector");
34
35
  const ai_core_plus_1 = require("@memberjunction/ai-core-plus");
35
36
  const AgentRunner_1 = require("./AgentRunner");
36
37
  const PayloadManager_1 = require("./PayloadManager");
@@ -39,7 +40,7 @@ const _ = __importStar(require("lodash"));
39
40
  class BaseAgent {
40
41
  constructor() {
41
42
  this._promptRunner = new ai_prompts_1.AIPromptRunner();
42
- this._metadata = new global_1.Metadata();
43
+ this._metadata = new core_1.Metadata();
43
44
  this._agentTypeState = null;
44
45
  this._executionCounts = new Map();
45
46
  this._generalValidationRetryCount = 0;
@@ -51,7 +52,10 @@ class BaseAgent {
51
52
  this._subAgentRuns = [];
52
53
  this._payloadManager = new PayloadManager_1.PayloadManager();
53
54
  this._validationRetryCount = 0;
54
- this._contextRecoveryAttempted = false;
55
+ this._contextRecoveryAttempts = 0;
56
+ this.MAX_RECOVERY_ATTEMPTS = 1;
57
+ this._memoryContext = '';
58
+ this._injectedMemory = { notes: [], examples: [] };
55
59
  }
56
60
  get AgentTypeState() {
57
61
  return this._agentTypeState;
@@ -67,21 +71,21 @@ class BaseAgent {
67
71
  }
68
72
  logStatus(message, verboseOnly = false, params) {
69
73
  if (verboseOnly) {
70
- (0, global_1.LogStatusEx)({
74
+ (0, core_1.LogStatusEx)({
71
75
  message,
72
76
  verboseOnly: true,
73
- isVerboseEnabled: () => params?.verbose === true || (0, global_1.IsVerboseLoggingEnabled)(),
77
+ isVerboseEnabled: () => params?.verbose === true || (0, core_1.IsVerboseLoggingEnabled)()
74
78
  });
75
79
  }
76
80
  else {
77
- (0, global_1.LogStatus)(message);
81
+ (0, core_1.LogStatus)(message);
78
82
  }
79
83
  }
80
84
  logError(error, options) {
81
85
  const errorMessage = error instanceof Error ? error.message : error;
82
86
  const errorObj = error instanceof Error ? error : undefined;
83
87
  const metadata = {
84
- ...options?.metadata,
88
+ ...options?.metadata
85
89
  };
86
90
  if (options?.agent) {
87
91
  metadata.agentId = options.agent.ID;
@@ -91,12 +95,12 @@ class BaseAgent {
91
95
  metadata.agentTypeId = options.agentType.ID;
92
96
  metadata.agentTypeName = options.agentType.Name;
93
97
  }
94
- (0, global_1.LogErrorEx)({
98
+ (0, core_1.LogErrorEx)({
95
99
  message: errorMessage,
96
100
  error: errorObj,
97
101
  category: options?.category || 'BaseAgent',
98
102
  severity: options?.severity || 'error',
99
- metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
103
+ metadata: Object.keys(metadata).length > 0 ? metadata : undefined
100
104
  });
101
105
  }
102
106
  wrapProgressCallback(originalCallback) {
@@ -107,15 +111,15 @@ class BaseAgent {
107
111
  ...progress,
108
112
  timestamp: new Date(),
109
113
  agentHierarchy: this._agentHierarchy || [],
110
- depth: this._depth || 0,
114
+ depth: this._depth || 0
111
115
  });
112
116
  try {
113
117
  const enhancedProgress = {
114
118
  ...progress,
115
119
  metadata: {
116
120
  ...progress.metadata,
117
- agentRun: this._agentRun,
118
- },
121
+ agentRun: this._agentRun
122
+ }
119
123
  };
120
124
  originalCallback(enhancedProgress);
121
125
  }
@@ -124,8 +128,8 @@ class BaseAgent {
124
128
  category: 'ProgressEnhancement',
125
129
  metadata: {
126
130
  progress: progress,
127
- agentRunId: this._agentRun?.ID || 'N/A',
128
- },
131
+ agentRunId: this._agentRun?.ID || 'N/A'
132
+ }
129
133
  });
130
134
  originalCallback(progress);
131
135
  }
@@ -159,15 +163,15 @@ class BaseAgent {
159
163
  this.logStatus(`📊 Preloaded ${totalSources} data source(s) for agent '${params.agent.Name}': ${destinations.join(', ')}`, true, params);
160
164
  params.data = {
161
165
  ...preloadedResult.data,
162
- ...params.data,
166
+ ...params.data
163
167
  };
164
168
  params.context = {
165
169
  ...preloadedResult.context,
166
- ...params.context,
170
+ ...params.context
167
171
  };
168
172
  params.payload = {
169
173
  ...preloadedResult.payload,
170
- ...params.payload,
174
+ ...params.payload
171
175
  };
172
176
  }
173
177
  else {
@@ -178,7 +182,7 @@ class BaseAgent {
178
182
  this.logError(`Failed to preload data for agent '${params.agent.Name}': ${error.message}`, {
179
183
  agent: params.agent,
180
184
  category: 'DataPreloading',
181
- severity: 'warning',
185
+ severity: 'warning'
182
186
  });
183
187
  }
184
188
  }
@@ -193,7 +197,7 @@ class BaseAgent {
193
197
  }
194
198
  const wrappedParams = {
195
199
  ...params,
196
- onProgress: this.wrapProgressCallback(params.onProgress),
200
+ onProgress: this.wrapProgressCallback(params.onProgress)
197
201
  };
198
202
  await this.initializeStartingPayload(wrappedParams);
199
203
  if (params.cancellationToken?.aborted) {
@@ -203,12 +207,12 @@ class BaseAgent {
203
207
  wrappedParams.onProgress?.({
204
208
  step: 'initialization',
205
209
  percentage: 0,
206
- message: this.formatHierarchicalMessage(`Initializing ${params.agent.Name} agent and preparing execution environment`),
210
+ message: this.formatHierarchicalMessage(`Initializing ${params.agent.Name} agent and preparing execution environment`)
207
211
  });
208
212
  await this.initializeAgentRun(wrappedParams);
209
213
  this._validationRetryCount = 0;
210
214
  this._generalValidationRetryCount = 0;
211
- this._contextRecoveryAttempted = false;
215
+ this._contextRecoveryAttempts = 0;
212
216
  this._messageLifecycleCallback = params.onMessageLifecycle;
213
217
  await this.initializeEngines(params.contextUser);
214
218
  if (params.cancellationToken?.aborted) {
@@ -221,7 +225,7 @@ class BaseAgent {
221
225
  wrappedParams.onProgress?.({
222
226
  step: 'validation',
223
227
  percentage: 10,
224
- message: this.formatHierarchicalMessage('Validating agent configuration and loading prompts'),
228
+ message: this.formatHierarchicalMessage('Validating agent configuration and loading prompts')
225
229
  });
226
230
  const validationResult = await this.validateAgentWithTracking(params.agent, params.contextUser);
227
231
  if (validationResult)
@@ -231,19 +235,26 @@ class BaseAgent {
231
235
  if (!config.success) {
232
236
  this.logError(`Failed to load agent configuration: ${config.errorMessage}`, {
233
237
  agent: params.agent,
234
- category: 'AgentConfiguration',
238
+ category: 'AgentConfiguration'
235
239
  });
236
240
  return await this.createFailureResult(config.errorMessage || 'Failed to load agent configuration', params.contextUser);
237
241
  }
238
242
  await this.preloadAgentData(wrappedParams);
239
243
  await this.initializeAgentType(wrappedParams, config);
244
+ const userId = params.userId || params.contextUser?.ID;
245
+ const companyId = params.companyId;
246
+ const lastUserMessage = params.conversationMessages
247
+ .filter(m => m.role === 'user')
248
+ .pop();
249
+ const inputText = lastUserMessage?.content || '';
250
+ await this.InjectContextMemory(typeof inputText === 'string' ? inputText : '', params.agent, userId, companyId, params.contextUser, wrappedParams.conversationMessages);
240
251
  this.logStatus(`🚀 Executing agent '${params.agent.Name}' internal logic`, true, params);
241
252
  const executionResult = await this.executeAgentInternal(wrappedParams, config);
242
253
  wrappedParams.onProgress?.({
243
254
  step: 'finalization',
244
255
  percentage: 95,
245
256
  metadata: { result: executionResult },
246
- message: this.formatHierarchicalMessage('Finalizing agent execution'),
257
+ message: this.formatHierarchicalMessage('Finalizing agent execution')
247
258
  });
248
259
  this.logStatus(`✅ Finalizing execution for agent '${params.agent.Name}'`, true, params);
249
260
  const finalPayload = executionResult.finalStep.newPayload || executionResult.finalStep.previousPayload;
@@ -257,7 +268,7 @@ class BaseAgent {
257
268
  this.logError(error, {
258
269
  agent: params.agent,
259
270
  category: 'AgentExecution',
260
- severity: 'critical',
271
+ severity: 'critical'
261
272
  });
262
273
  return await this.createFailureResult(error.message, params.contextUser);
263
274
  }
@@ -298,6 +309,50 @@ class BaseAgent {
298
309
  await aiengine_1.AIEngine.Instance.Config(false, contextUser);
299
310
  await actions_1.ActionEngineServer.Instance.Config(false, contextUser);
300
311
  }
312
+ async InjectContextMemory(input, agent, userId, companyId, contextUser, conversationMessages) {
313
+ if (!agent.InjectNotes && !agent.InjectExamples) {
314
+ return { notes: [], examples: [] };
315
+ }
316
+ const injector = new agent_context_injector_1.AgentContextInjector();
317
+ const notes = agent.InjectNotes
318
+ ? await injector.GetNotesForContext({
319
+ agentId: agent.ID,
320
+ userId,
321
+ companyId,
322
+ currentInput: input,
323
+ strategy: agent.NoteInjectionStrategy,
324
+ maxNotes: agent.MaxNotesToInject || 5,
325
+ contextUser: contextUser
326
+ })
327
+ : [];
328
+ const examples = agent.InjectExamples
329
+ ? await injector.GetExamplesForContext({
330
+ agentId: agent.ID,
331
+ userId,
332
+ companyId,
333
+ currentInput: input,
334
+ strategy: agent.ExampleInjectionStrategy,
335
+ maxExamples: agent.MaxExamplesToInject || 3,
336
+ contextUser: contextUser
337
+ })
338
+ : [];
339
+ if ((notes.length > 0 || examples.length > 0) && conversationMessages) {
340
+ const notesText = injector.FormatNotesForInjection(notes);
341
+ const examplesText = injector.FormatExamplesForInjection(examples);
342
+ this._memoryContext = '';
343
+ if (notesText)
344
+ this._memoryContext += notesText + '\n\n';
345
+ if (examplesText)
346
+ this._memoryContext += examplesText + '\n\n';
347
+ conversationMessages.unshift({
348
+ role: 'system',
349
+ content: this._memoryContext
350
+ });
351
+ this.logStatus(`💾 Injected ${notes.length} notes and ${examples.length} examples into conversation context`, true);
352
+ }
353
+ this._injectedMemory = { notes, examples };
354
+ return { notes, examples };
355
+ }
301
356
  async validateRunChain(lastRunId, contextUser) {
302
357
  const visitedRunIds = new Set();
303
358
  visitedRunIds.add(this._agentRun.ID);
@@ -312,11 +367,11 @@ class BaseAgent {
312
367
  throw new Error(`Run chain exceeds maximum length of ${maxChainLength}. This may indicate a data issue.`);
313
368
  }
314
369
  visitedRunIds.add(currentRunId);
315
- const rv = new global_1.RunView();
370
+ const rv = new core_1.RunView();
316
371
  const result = await rv.RunView({
317
372
  EntityName: 'MJ: AI Agent Runs',
318
373
  ExtraFilter: `ID='${currentRunId}'`,
319
- ResultType: 'simple',
374
+ ResultType: 'simple'
320
375
  }, contextUser);
321
376
  if (!result.Success || result.Results.length === 0) {
322
377
  break;
@@ -334,7 +389,7 @@ class BaseAgent {
334
389
  }
335
390
  return {
336
391
  success: false,
337
- agentRun: this._agentRun,
392
+ agentRun: this._agentRun
338
393
  };
339
394
  }
340
395
  return null;
@@ -355,16 +410,16 @@ class BaseAgent {
355
410
  metadata: {
356
411
  agentName: agent.Name,
357
412
  agentId: agent.ID,
358
- validationSchema: agent.StartingPayloadValidation,
359
- },
413
+ validationSchema: agent.StartingPayloadValidation
414
+ }
360
415
  });
361
416
  return null;
362
417
  }
363
418
  let payloadToValidate = params.payload;
364
- const jsonValidator = new global_2.JSONValidator();
419
+ const jsonValidator = new global_1.JSONValidator();
365
420
  const validationResult = jsonValidator.validate(payloadToValidate, validationSchema);
366
421
  if (!validationResult.Success) {
367
- const errorMessages = validationResult.Errors.map((e) => e.Message);
422
+ const errorMessages = validationResult.Errors.map(e => e.Message);
368
423
  return this.handleStartingValidationFailure(params, errorMessages);
369
424
  }
370
425
  this.logStatus(`✅ Starting payload validation passed for agent ${agent.Name}`, true, params);
@@ -376,8 +431,8 @@ class BaseAgent {
376
431
  metadata: {
377
432
  agentName: agent.Name,
378
433
  agentId: agent.ID,
379
- error: error.message,
380
- },
434
+ error: error.message
435
+ }
381
436
  });
382
437
  return null;
383
438
  }
@@ -389,7 +444,7 @@ class BaseAgent {
389
444
  this.logError(`Starting payload validation failed for agent ${params.agent.Name}`, {
390
445
  agent: params.agent,
391
446
  category: 'StartingPayloadValidation',
392
- metadata: { errors: errorMessages },
447
+ metadata: { errors: errorMessages }
393
448
  });
394
449
  if (this._agentRun) {
395
450
  this._agentRun.ErrorMessage = validationFeedback;
@@ -400,7 +455,7 @@ class BaseAgent {
400
455
  return {
401
456
  success: false,
402
457
  agentRun: this._agentRun,
403
- payload: params.payload,
458
+ payload: params.payload
404
459
  };
405
460
  }
406
461
  else {
@@ -415,41 +470,43 @@ class BaseAgent {
415
470
  this.logStatus(`🔧 Using custom driver class '${agent.DriverClass}' for agent '${agent.Name}'`, true);
416
471
  metadataOptional = true;
417
472
  }
418
- const agentType = engine.AgentTypes.find((at) => at.ID === agent.TypeID);
473
+ const agentType = engine.AgentTypes.find(at => at.ID === agent.TypeID);
419
474
  if (!agentType && !metadataOptional) {
420
475
  return {
421
476
  success: false,
422
- errorMessage: `Agent type not found for ID: ${agent.TypeID}`,
477
+ errorMessage: `Agent type not found for ID: ${agent.TypeID}`
423
478
  };
424
479
  }
425
- const systemPrompt = engine.Prompts.find((p) => p.ID === agentType.SystemPromptID);
480
+ const systemPrompt = engine.Prompts.find(p => p.ID === agentType.SystemPromptID);
426
481
  if (!systemPrompt)
427
482
  metadataOptional = true;
428
- const agentPrompt = engine.AgentPrompts.filter((ap) => ap.AgentID === agent.ID && ap.Status === 'Active').sort((a, b) => a.ExecutionOrder - b.ExecutionOrder)[0];
483
+ const agentPrompt = engine.AgentPrompts
484
+ .filter(ap => ap.AgentID === agent.ID && ap.Status === 'Active')
485
+ .sort((a, b) => a.ExecutionOrder - b.ExecutionOrder)[0];
429
486
  if (!agentPrompt && !metadataOptional) {
430
487
  return {
431
488
  success: false,
432
- errorMessage: `No prompts configured for agent: ${agent.Name}`,
489
+ errorMessage: `No prompts configured for agent: ${agent.Name}`
433
490
  };
434
491
  }
435
- const childPrompt = engine.Prompts.find((p) => p.ID === agentPrompt?.PromptID);
492
+ const childPrompt = engine.Prompts.find(p => p.ID === agentPrompt?.PromptID);
436
493
  if (!childPrompt && !metadataOptional) {
437
494
  return {
438
495
  success: false,
439
- errorMessage: `Child prompt not found for ID: ${agentPrompt?.PromptID}`,
496
+ errorMessage: `Child prompt not found for ID: ${agentPrompt?.PromptID}`
440
497
  };
441
498
  }
442
499
  if (!agentType.AgentPromptPlaceholder && !metadataOptional) {
443
500
  return {
444
501
  success: false,
445
- errorMessage: `Agent type '${agentType.Name}' does not have AgentPromptPlaceholder configured.`,
502
+ errorMessage: `Agent type '${agentType.Name}' does not have AgentPromptPlaceholder configured.`
446
503
  };
447
504
  }
448
505
  return {
449
506
  success: true,
450
507
  agentType,
451
508
  systemPrompt,
452
- childPrompt,
509
+ childPrompt
453
510
  };
454
511
  }
455
512
  async preparePromptParams(config, payload, params) {
@@ -488,7 +545,7 @@ class BaseAgent {
488
545
  const atInstance = await base_agent_type_1.BaseAgentType.GetAgentTypeInstance(config.agentType);
489
546
  await atInstance.InjectPayload(payload, this.AgentTypeState, promptParams, {
490
547
  agentId: params.agent.ID,
491
- agentRunId: this._agentRun?.ID,
548
+ agentRunId: this._agentRun?.ID
492
549
  });
493
550
  if (systemPrompt) {
494
551
  const childPromptParams = {
@@ -498,7 +555,7 @@ class BaseAgent {
498
555
  conversationMessages: params.conversationMessages,
499
556
  templateMessageRole: 'user',
500
557
  verbose: params.verbose,
501
- agentRunId: this.AgentRun?.ID,
558
+ agentRunId: this.AgentRun?.ID
502
559
  };
503
560
  if (params.effortLevel !== undefined && params.effortLevel !== null) {
504
561
  childPromptParams.effortLevel = params.effortLevel;
@@ -513,7 +570,9 @@ class BaseAgent {
513
570
  promptParams.configurationId = params.configurationId;
514
571
  childPromptParams.configurationId = params.configurationId;
515
572
  }
516
- promptParams.childPrompts = [new ai_core_plus_1.ChildPromptParam(childPromptParams, agentType.AgentPromptPlaceholder)];
573
+ promptParams.childPrompts = [
574
+ new ai_core_plus_1.ChildPromptParam(childPromptParams, agentType.AgentPromptPlaceholder)
575
+ ];
517
576
  }
518
577
  else {
519
578
  if (params.apiKeys && params.apiKeys.length > 0) {
@@ -540,7 +599,7 @@ class BaseAgent {
540
599
  async executePrompt(promptParams) {
541
600
  const newParams = {
542
601
  ...promptParams,
543
- attemptJSONRepair: true,
602
+ attemptJSONRepair: true
544
603
  };
545
604
  return await this._promptRunner.ExecutePrompt(newParams);
546
605
  }
@@ -570,23 +629,23 @@ class BaseAgent {
570
629
  default:
571
630
  this.logError(`Invalid next step '${nextStep.step}' for agent '${params.agent.Name}'`, {
572
631
  agent: params.agent,
573
- category: 'NextStepValidation',
632
+ category: 'NextStepValidation'
574
633
  });
575
634
  return {
576
635
  step: 'Failed',
577
636
  terminate: true,
578
- errorMessage: `Invalid next step '${nextStep.step}'`,
637
+ errorMessage: `Invalid next step '${nextStep.step}'`
579
638
  };
580
639
  }
581
640
  }
582
641
  async validateSubAgentNextStep(params, nextStep, currentPayload, agentRun, currentStep) {
583
642
  const name = nextStep.subAgent?.name;
584
643
  const curAgentSubAgents = aiengine_1.AIEngine.Instance.GetSubAgents(params.agent.ID, 'Active');
585
- const subAgent = curAgentSubAgents.find((a) => a.Name.trim().toLowerCase() === name?.trim().toLowerCase());
644
+ const subAgent = curAgentSubAgents.find(a => a.Name.trim().toLowerCase() === name?.trim().toLowerCase());
586
645
  if (!name || !subAgent) {
587
646
  this.logError(`Sub-agent '${name}' not found or not active for agent '${params.agent.Name}'`, {
588
647
  agent: params.agent,
589
- category: 'SubAgentExecution',
648
+ category: 'SubAgentExecution'
590
649
  });
591
650
  if (nextStep.step !== 'Retry') {
592
651
  this._generalValidationRetryCount++;
@@ -594,7 +653,7 @@ class BaseAgent {
594
653
  return {
595
654
  step: 'Retry',
596
655
  terminate: false,
597
- errorMessage: `Sub-agent '${name}' not found or not active`,
656
+ errorMessage: `Sub-agent '${name}' not found or not active`
598
657
  };
599
658
  }
600
659
  if (subAgent.MaxExecutionsPerRun != null) {
@@ -606,8 +665,8 @@ class BaseAgent {
606
665
  metadata: {
607
666
  subAgentName: name,
608
667
  executionCount,
609
- maxExecutions: subAgent.MaxExecutionsPerRun,
610
- },
668
+ maxExecutions: subAgent.MaxExecutionsPerRun
669
+ }
611
670
  });
612
671
  if (nextStep.step !== 'Retry') {
613
672
  this._generalValidationRetryCount++;
@@ -615,20 +674,20 @@ class BaseAgent {
615
674
  return {
616
675
  step: 'Retry',
617
676
  terminate: false,
618
- errorMessage: `Sub-agent '${name}' has reached its maximum execution limit of ${subAgent.MaxExecutionsPerRun}`,
677
+ errorMessage: `Sub-agent '${name}' has reached its maximum execution limit of ${subAgent.MaxExecutionsPerRun}`
619
678
  };
620
679
  }
621
680
  }
622
681
  return nextStep;
623
682
  }
624
683
  async validateActionsNextStep(params, nextStep, currentPayload, agentRun, currentStep) {
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) => {
684
+ const curAgentActions = aiengine_1.AIEngine.Instance.AgentActions.filter(aa => aa.AgentID === params.agent.ID && aa.Status === 'Active');
685
+ const missingActions = nextStep.actions?.filter(action => {
627
686
  const actionName = action.name.trim().toLowerCase();
628
- const exactMatch = curAgentActions.find((aa) => aa.Action.trim().toLowerCase() === actionName);
687
+ const exactMatch = curAgentActions.find(aa => aa.Action.trim().toLowerCase() === actionName);
629
688
  if (exactMatch)
630
689
  return false;
631
- const containsMatches = curAgentActions.filter((aa) => aa.Action.trim().toLowerCase().includes(actionName));
690
+ const containsMatches = curAgentActions.filter(aa => aa.Action.trim().toLowerCase().includes(actionName));
632
691
  if (containsMatches.length === 1) {
633
692
  const correctedName = containsMatches[0].Action;
634
693
  this.logStatus(`Action name fuzzy matched: '${action.name}' → '${correctedName}'`, true, params);
@@ -636,15 +695,15 @@ class BaseAgent {
636
695
  return false;
637
696
  }
638
697
  if (containsMatches.length > 1) {
639
- this.logStatus(`Ambiguous action name '${action.name}' matches ${containsMatches.length} actions: ${containsMatches.map((a) => a.Action).join(', ')}`, true, params);
698
+ this.logStatus(`Ambiguous action name '${action.name}' matches ${containsMatches.length} actions: ${containsMatches.map(a => a.Action).join(', ')}`, true, params);
640
699
  }
641
700
  return true;
642
701
  });
643
702
  if (missingActions && missingActions.length > 0) {
644
- const missingActionNames = missingActions.map((a) => a.name).join(', ');
703
+ const missingActionNames = missingActions.map(a => a.name).join(', ');
645
704
  this.logError(`Actions '${missingActionNames}' not found or not active for agent '${params.agent.Name}'`, {
646
705
  agent: params.agent,
647
- category: 'ActionExecution',
706
+ category: 'ActionExecution'
648
707
  });
649
708
  if (nextStep.step !== 'Retry') {
650
709
  this._generalValidationRetryCount++;
@@ -652,13 +711,13 @@ class BaseAgent {
652
711
  return {
653
712
  step: 'Retry',
654
713
  terminate: false,
655
- errorMessage: `Actions '${missingActionNames}' not found or not active`,
714
+ errorMessage: `Actions '${missingActionNames}' not found or not active`
656
715
  };
657
716
  }
658
717
  if (nextStep.actions) {
659
718
  const violatedActions = [];
660
719
  for (const action of nextStep.actions) {
661
- const agentAction = curAgentActions.find((aa) => aa.Action.trim().toLowerCase() === action.name.trim().toLowerCase());
720
+ const agentAction = curAgentActions.find(aa => aa.Action.trim().toLowerCase() === action.name.trim().toLowerCase());
662
721
  if (agentAction && agentAction.MaxExecutionsPerRun != null) {
663
722
  const executionCount = await this.getActionExecutionCount(agentRun.ID, agentAction.ActionID);
664
723
  if (executionCount >= agentAction.MaxExecutionsPerRun) {
@@ -672,8 +731,8 @@ class BaseAgent {
672
731
  agent: params.agent,
673
732
  category: 'ActionExecution',
674
733
  metadata: {
675
- violatedActions,
676
- },
734
+ violatedActions
735
+ }
677
736
  });
678
737
  if (nextStep.step !== 'Retry') {
679
738
  this._generalValidationRetryCount++;
@@ -681,7 +740,7 @@ class BaseAgent {
681
740
  return {
682
741
  step: 'Retry',
683
742
  terminate: false,
684
- errorMessage: violationMessage,
743
+ errorMessage: violationMessage
685
744
  };
686
745
  }
687
746
  }
@@ -693,7 +752,7 @@ class BaseAgent {
693
752
  const violationMessage = `Minimum execution requirements not met:\n${minViolations.join('\n')}`;
694
753
  this.logError(violationMessage, {
695
754
  agent: params.agent,
696
- category: 'MinimumExecutionValidation',
755
+ category: 'MinimumExecutionValidation'
697
756
  });
698
757
  if (nextStep.step !== 'Retry') {
699
758
  this._generalValidationRetryCount++;
@@ -701,7 +760,7 @@ class BaseAgent {
701
760
  return {
702
761
  step: 'Retry',
703
762
  terminate: false,
704
- errorMessage: violationMessage,
763
+ errorMessage: violationMessage
705
764
  };
706
765
  }
707
766
  const agent = params.agent;
@@ -719,8 +778,8 @@ class BaseAgent {
719
778
  metadata: {
720
779
  agentName: agent.Name,
721
780
  agentId: agent.ID,
722
- validationSchema: agent.FinalPayloadValidation,
723
- },
781
+ validationSchema: agent.FinalPayloadValidation
782
+ }
724
783
  });
725
784
  return nextStep;
726
785
  }
@@ -732,11 +791,11 @@ class BaseAgent {
732
791
  return this.handleFinalPayloadValidationFailure(params, nextStep, currentPayload, agent.FinalPayloadValidationMode || 'Retry', [errorMessage], agentRun, currentStep);
733
792
  }
734
793
  }
735
- const jsonValidator = new global_2.JSONValidator();
794
+ const jsonValidator = new global_1.JSONValidator();
736
795
  const validationResult = jsonValidator.validate(payloadToValidate, validationSchema);
737
796
  if (!validationResult.Success) {
738
797
  const mode = agent.FinalPayloadValidationMode || 'Retry';
739
- const errorMessages = validationResult.Errors.map((e) => e.Message);
798
+ const errorMessages = validationResult.Errors.map(e => e.Message);
740
799
  this.logStatus(`⚠️ Final payload validation failed for agent ${agent.Name} (mode: ${mode}):`, true, params);
741
800
  errorMessages.forEach((error, index) => {
742
801
  this.logStatus(` ${index + 1}. ${error}`, true, params);
@@ -752,7 +811,7 @@ class BaseAgent {
752
811
  catch (error) {
753
812
  this.logError(`Failed to save validation success result: ${error.message}`, {
754
813
  category: 'PayloadValidation',
755
- metadata: { stepId: currentStep.ID },
814
+ metadata: { stepId: currentStep.ID }
756
815
  });
757
816
  }
758
817
  return nextStep;
@@ -763,8 +822,8 @@ class BaseAgent {
763
822
  metadata: {
764
823
  agentName: agent.Name,
765
824
  agentId: agent.ID,
766
- error: error.message,
767
- },
825
+ error: error.message
826
+ }
768
827
  });
769
828
  return nextStep;
770
829
  }
@@ -785,7 +844,7 @@ class BaseAgent {
785
844
  ...nextStep,
786
845
  step: 'Failed',
787
846
  message: `${validationFeedback}\n\nMax validation retries (${maxRetries}) exceeded.`,
788
- terminate: true,
847
+ terminate: true
789
848
  };
790
849
  }
791
850
  currentStep.FinalPayloadValidationResult = 'Retry';
@@ -795,7 +854,7 @@ class BaseAgent {
795
854
  ...nextStep,
796
855
  step: 'Retry',
797
856
  retryInstructions: `${validationFeedback}\n\nRetry attempt ${this._validationRetryCount} of ${maxRetries}`,
798
- terminate: false,
857
+ terminate: false
799
858
  };
800
859
  case 'Fail':
801
860
  currentStep.FinalPayloadValidationResult = 'Fail';
@@ -804,7 +863,7 @@ class BaseAgent {
804
863
  ...nextStep,
805
864
  step: 'Failed',
806
865
  message: validationFeedback,
807
- terminate: true,
866
+ terminate: true
808
867
  };
809
868
  case 'Warn':
810
869
  this.logStatus(`⚠️ WARNING: ${validationFeedback}`, false, params);
@@ -819,23 +878,21 @@ class BaseAgent {
819
878
  ...nextStep,
820
879
  step: 'Retry',
821
880
  retryInstructions: validationFeedback,
822
- terminate: false,
881
+ terminate: false
823
882
  };
824
883
  }
825
884
  }
826
885
  catch (error) {
827
886
  this.logError(`Failed to save validation results: ${error.message}`, {
828
887
  category: 'PayloadValidation',
829
- metadata: { stepId: currentStep.ID },
888
+ metadata: { stepId: currentStep.ID }
830
889
  });
831
- return mode === 'Warn'
832
- ? nextStep
833
- : {
834
- ...nextStep,
835
- step: mode === 'Fail' ? 'Failed' : 'Retry',
836
- message: validationFeedback,
837
- terminate: mode === 'Fail',
838
- };
890
+ return mode === 'Warn' ? nextStep : {
891
+ ...nextStep,
892
+ step: mode === 'Fail' ? 'Failed' : 'Retry',
893
+ message: validationFeedback,
894
+ terminate: mode === 'Fail'
895
+ };
839
896
  }
840
897
  }
841
898
  async validateFailedNextStep(params, nextStep, currentPayload, agentRun, currentStep) {
@@ -859,15 +916,15 @@ class BaseAgent {
859
916
  mappedStep = 'Retry';
860
917
  break;
861
918
  default:
862
- (0, global_1.LogError)(`Invalid ChatHandlingOption value: ${chatHandlingOption}. Expected 'Success', 'Failed', or 'Retry'. Treating as null and allowing Chat to propagate.`);
919
+ (0, core_1.LogError)(`Invalid ChatHandlingOption value: ${chatHandlingOption}. Expected 'Success', 'Failed', or 'Retry'. Treating as null and allowing Chat to propagate.`);
863
920
  return nextStep;
864
921
  }
865
922
  const remappedStep = {
866
923
  ...nextStep,
867
- step: mappedStep,
924
+ step: mappedStep
868
925
  };
869
- if (params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)()) {
870
- (0, global_1.LogStatus)(`Remapping Chat step to ${chatHandlingOption} based on agent's ChatHandlingOption`);
926
+ if (params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)()) {
927
+ (0, core_1.LogStatus)(`Remapping Chat step to ${chatHandlingOption} based on agent's ChatHandlingOption`);
871
928
  }
872
929
  return await this.validateNextStep(params, remappedStep, currentPayload, agentRun, currentStep);
873
930
  }
@@ -889,15 +946,15 @@ class BaseAgent {
889
946
  limit: guardrailResult.limit,
890
947
  current: guardrailResult.current,
891
948
  reason: guardrailResult.reason,
892
- timestamp: new Date().toISOString(),
893
- },
949
+ timestamp: new Date().toISOString()
950
+ }
894
951
  });
895
952
  await currentStep.Save();
896
953
  }
897
954
  catch (error) {
898
955
  this.logError(`Failed to save guardrail violation to step: ${error.message}`, {
899
956
  category: 'Guardrails',
900
- metadata: { stepId: currentStep.ID },
957
+ metadata: { stepId: currentStep.ID }
901
958
  });
902
959
  }
903
960
  return {
@@ -905,7 +962,7 @@ class BaseAgent {
905
962
  step: 'Failed',
906
963
  terminate: true,
907
964
  message: guardrailResult.reason,
908
- errorMessage: guardrailResult.reason,
965
+ errorMessage: guardrailResult.reason
909
966
  };
910
967
  }
911
968
  return nextStep;
@@ -919,7 +976,7 @@ class BaseAgent {
919
976
  type: 'cost',
920
977
  limit: agent.MaxCostPerRun,
921
978
  current: agentRun.TotalCost,
922
- reason: `Maximum cost limit of $${agent.MaxCostPerRun} exceeded. Current cost: $${agentRun.TotalCost.toFixed(4)}`,
979
+ reason: `Maximum cost limit of $${agent.MaxCostPerRun} exceeded. Current cost: $${agentRun.TotalCost.toFixed(4)}`
923
980
  };
924
981
  }
925
982
  }
@@ -930,7 +987,7 @@ class BaseAgent {
930
987
  type: 'tokens',
931
988
  limit: agent.MaxTokensPerRun,
932
989
  current: agentRun.TotalTokensUsed,
933
- reason: `Maximum token limit of ${agent.MaxTokensPerRun} exceeded. Current tokens: ${agentRun.TotalTokensUsed}`,
990
+ reason: `Maximum token limit of ${agent.MaxTokensPerRun} exceeded. Current tokens: ${agentRun.TotalTokensUsed}`
934
991
  };
935
992
  }
936
993
  }
@@ -941,7 +998,7 @@ class BaseAgent {
941
998
  type: 'iterations',
942
999
  limit: agent.MaxIterationsPerRun,
943
1000
  current: agentRun.TotalPromptIterations,
944
- reason: `Maximum iteration limit of ${agent.MaxIterationsPerRun} exceeded. Current iterations: ${agentRun.TotalPromptIterations}`,
1001
+ reason: `Maximum iteration limit of ${agent.MaxIterationsPerRun} exceeded. Current iterations: ${agentRun.TotalPromptIterations}`
945
1002
  };
946
1003
  }
947
1004
  }
@@ -953,7 +1010,7 @@ class BaseAgent {
953
1010
  type: 'time',
954
1011
  limit: agent.MaxTimePerRun,
955
1012
  current: elapsedSeconds,
956
- reason: `Maximum time limit of ${agent.MaxTimePerRun} seconds exceeded. Elapsed time: ${elapsedSeconds} seconds`,
1013
+ reason: `Maximum time limit of ${agent.MaxTimePerRun} seconds exceeded. Elapsed time: ${elapsedSeconds} seconds`
957
1014
  };
958
1015
  }
959
1016
  }
@@ -963,7 +1020,7 @@ class BaseAgent {
963
1020
  type: 'iterations',
964
1021
  limit: BaseAgent.MAX_VALIDATION_RETRIES,
965
1022
  current: this._generalValidationRetryCount,
966
- reason: `Maximum validation retries of ${BaseAgent.MAX_VALIDATION_RETRIES} exceeded. The agent is unable to produce valid output after ${this._generalValidationRetryCount} validation failures.`,
1023
+ reason: `Maximum validation retries of ${BaseAgent.MAX_VALIDATION_RETRIES} exceeded. The agent is unable to produce valid output after ${this._generalValidationRetryCount} validation failures.`
967
1024
  };
968
1025
  }
969
1026
  return { exceeded: false };
@@ -979,7 +1036,7 @@ class BaseAgent {
979
1036
  const fatalErrorTypes = [
980
1037
  'ContextLengthExceeded',
981
1038
  'Authentication',
982
- 'InvalidRequest',
1039
+ 'InvalidRequest'
983
1040
  ];
984
1041
  return fatalErrorTypes.includes(errorInfo.errorType);
985
1042
  }
@@ -987,14 +1044,12 @@ class BaseAgent {
987
1044
  if (typeof content === 'string') {
988
1045
  return content;
989
1046
  }
990
- return content
991
- .map((block) => {
1047
+ return content.map((block) => {
992
1048
  if (block.type === 'text') {
993
1049
  return block.content;
994
1050
  }
995
1051
  return `[${block.type}: ${block.content}]`;
996
- })
997
- .join('\n');
1052
+ }).join('\n');
998
1053
  }
999
1054
  smartTrimContent(content, maxLength = 1000) {
1000
1055
  const originalLength = content.length;
@@ -1009,7 +1064,7 @@ class BaseAgent {
1009
1064
  return {
1010
1065
  trimmed,
1011
1066
  strategy: 'JSON array truncation',
1012
- originalLength,
1067
+ originalLength
1013
1068
  };
1014
1069
  }
1015
1070
  }
@@ -1036,7 +1091,7 @@ class BaseAgent {
1036
1091
  return {
1037
1092
  trimmed: JSON.stringify(truncated, null, 2),
1038
1093
  strategy: 'JSON object field truncation',
1039
- originalLength,
1094
+ originalLength
1040
1095
  };
1041
1096
  }
1042
1097
  }
@@ -1055,7 +1110,7 @@ class BaseAgent {
1055
1110
  return {
1056
1111
  trimmed,
1057
1112
  strategy: 'CSV row truncation',
1058
- originalLength,
1113
+ originalLength
1059
1114
  };
1060
1115
  }
1061
1116
  }
@@ -1064,78 +1119,264 @@ class BaseAgent {
1064
1119
  return {
1065
1120
  trimmed: content.substring(0, maxLength) + '\n\n... (truncated due to context length)',
1066
1121
  strategy: 'character truncation',
1067
- originalLength,
1122
+ originalLength
1068
1123
  };
1069
1124
  }
1070
1125
  return {
1071
1126
  trimmed: content,
1072
1127
  strategy: 'no truncation needed',
1073
- originalLength,
1128
+ originalLength
1129
+ };
1130
+ }
1131
+ recoveryStrategy_RemoveOldestActionResults(params, tokensToSave, currentStepCount, minAge = 5) {
1132
+ let tokensSaved = 0;
1133
+ const removedIndices = [];
1134
+ const candidates = params.conversationMessages
1135
+ .map((msg, index) => ({
1136
+ message: msg,
1137
+ index: index,
1138
+ age: msg.metadata?.turnAdded
1139
+ ? currentStepCount - msg.metadata.turnAdded
1140
+ : 0,
1141
+ tokens: this.estimateTokens(msg.content),
1142
+ isActionResult: msg.metadata?.messageType === 'action-result'
1143
+ }))
1144
+ .filter(c => c.isActionResult && c.age >= minAge)
1145
+ .sort((a, b) => b.age - a.age);
1146
+ for (const candidate of candidates) {
1147
+ if (tokensSaved >= tokensToSave)
1148
+ break;
1149
+ removedIndices.push(candidate.index);
1150
+ tokensSaved += candidate.tokens;
1151
+ this.logStatus(`Removing action-result from ${candidate.age} turns ago (${candidate.tokens} tokens)`, true, params);
1152
+ }
1153
+ removedIndices.sort((a, b) => b - a).forEach(index => {
1154
+ const removed = params.conversationMessages.splice(index, 1)[0];
1155
+ this.emitMessageLifecycleEvent({
1156
+ type: 'message-removed',
1157
+ turn: currentStepCount,
1158
+ messageIndex: index,
1159
+ message: removed,
1160
+ reason: 'Context recovery - oldest action results',
1161
+ tokensSaved: this.estimateTokens(removed.content)
1162
+ });
1163
+ });
1164
+ return {
1165
+ tokensSaved,
1166
+ strategyName: `Removed ${removedIndices.length} old action-results (${minAge}+ turns)`
1167
+ };
1168
+ }
1169
+ async recoveryStrategy_CompactOldActionResults(params, tokensToSave, currentStepCount, minAge = 3) {
1170
+ let tokensSaved = 0;
1171
+ let compactedCount = 0;
1172
+ const candidates = params.conversationMessages
1173
+ .map((msg, index) => ({
1174
+ message: msg,
1175
+ index: index,
1176
+ age: msg.metadata?.turnAdded
1177
+ ? currentStepCount - msg.metadata.turnAdded
1178
+ : 0,
1179
+ tokens: this.estimateTokens(msg.content),
1180
+ isActionResult: msg.metadata?.messageType === 'action-result',
1181
+ alreadyCompacted: msg.metadata?.wasCompacted === true
1182
+ }))
1183
+ .filter(c => c.isActionResult && c.age >= minAge && !c.alreadyCompacted)
1184
+ .sort((a, b) => b.age - a.age);
1185
+ for (const candidate of candidates) {
1186
+ if (tokensSaved >= tokensToSave)
1187
+ break;
1188
+ const originalTokens = candidate.tokens;
1189
+ const originalMessage = candidate.message;
1190
+ const originalContent = typeof originalMessage.content === 'string'
1191
+ ? originalMessage.content
1192
+ : JSON.stringify(originalMessage.content);
1193
+ const compactedContent = await this.compactMessage(originalMessage, {
1194
+ compactMode: 'First N Chars',
1195
+ compactLength: 500,
1196
+ compactPromptId: '',
1197
+ originalLength: originalContent.length
1198
+ }, params);
1199
+ const newTokens = this.estimateTokens(compactedContent);
1200
+ const saved = originalTokens - newTokens;
1201
+ if (saved > 0) {
1202
+ params.conversationMessages[candidate.index] = {
1203
+ ...originalMessage,
1204
+ content: compactedContent,
1205
+ metadata: {
1206
+ ...originalMessage.metadata,
1207
+ wasCompacted: true,
1208
+ originalLength: originalContent.length,
1209
+ tokensSaved: saved
1210
+ }
1211
+ };
1212
+ tokensSaved += saved;
1213
+ compactedCount++;
1214
+ this.logStatus(`Compacted action-result from ${candidate.age} turns ago (saved ${saved} tokens)`, true, params);
1215
+ }
1216
+ }
1217
+ return {
1218
+ tokensSaved,
1219
+ strategyName: `Compacted ${compactedCount} old action-results (${minAge}+ turns)`
1074
1220
  };
1075
1221
  }
1076
- async attemptContextRecovery(params, payload, errorMessage) {
1077
- this.logStatus(`⚠️ Context length exceeded - attempting recovery by trimming conversation messages`, true, params);
1078
- const messages = params.conversationMessages;
1222
+ async recoveryStrategy_CompactAllActionResults(params, tokensToSave) {
1223
+ let tokensSaved = 0;
1224
+ let compactedCount = 0;
1225
+ const candidates = params.conversationMessages
1226
+ .map((msg, index) => ({
1227
+ message: msg,
1228
+ index: index,
1229
+ tokens: this.estimateTokens(msg.content),
1230
+ isActionResult: msg.metadata?.messageType === 'action-result',
1231
+ alreadyCompacted: msg.metadata?.wasCompacted === true
1232
+ }))
1233
+ .filter(c => c.isActionResult && !c.alreadyCompacted && c.tokens > 200)
1234
+ .sort((a, b) => b.tokens - a.tokens);
1235
+ for (const candidate of candidates) {
1236
+ if (tokensSaved >= tokensToSave)
1237
+ break;
1238
+ const originalTokens = candidate.tokens;
1239
+ const originalMessage = candidate.message;
1240
+ const originalContent = typeof originalMessage.content === 'string'
1241
+ ? originalMessage.content
1242
+ : JSON.stringify(originalMessage.content);
1243
+ const compactedContent = await this.compactMessage(originalMessage, {
1244
+ compactMode: 'First N Chars',
1245
+ compactLength: 200,
1246
+ compactPromptId: '',
1247
+ originalLength: originalContent.length
1248
+ }, params);
1249
+ const newTokens = this.estimateTokens(compactedContent);
1250
+ const saved = originalTokens - newTokens;
1251
+ if (saved > 0) {
1252
+ params.conversationMessages[candidate.index] = {
1253
+ ...originalMessage,
1254
+ content: compactedContent,
1255
+ metadata: {
1256
+ ...originalMessage.metadata,
1257
+ wasCompacted: true,
1258
+ originalLength: originalContent.length,
1259
+ tokensSaved: saved
1260
+ }
1261
+ };
1262
+ tokensSaved += saved;
1263
+ compactedCount++;
1264
+ }
1265
+ }
1266
+ return {
1267
+ tokensSaved,
1268
+ strategyName: `Aggressively compacted ${compactedCount} action-results`
1269
+ };
1270
+ }
1271
+ recoveryStrategy_TrimLastUserMessage(params, tokensToSave) {
1079
1272
  let lastUserMessageIndex = -1;
1080
- for (let i = messages.length - 1; i >= 0; i--) {
1081
- if (messages[i].role === 'user') {
1273
+ for (let i = params.conversationMessages.length - 1; i >= 0; i--) {
1274
+ if (params.conversationMessages[i].role === 'user') {
1082
1275
  lastUserMessageIndex = i;
1083
1276
  break;
1084
1277
  }
1085
1278
  }
1086
1279
  if (lastUserMessageIndex === -1) {
1087
- this.logStatus(`❌ Context recovery failed: No trimmable user messages found`, true, params);
1280
+ return { tokensSaved: 0, strategyName: 'No user message to trim' };
1281
+ }
1282
+ const lastUserMessage = params.conversationMessages[lastUserMessageIndex];
1283
+ const originalTokens = this.estimateTokens(lastUserMessage.content);
1284
+ const contentString = this.contentToString(lastUserMessage.content);
1285
+ const targetChars = 1000;
1286
+ if (contentString.length <= targetChars) {
1287
+ return { tokensSaved: 0, strategyName: 'User message already short' };
1288
+ }
1289
+ const trimResult = this.smartTrimContent(contentString, targetChars);
1290
+ const newContent = trimResult.trimmed +
1291
+ '\n\n<CONTEXT_LIMIT_REACHED>\n' +
1292
+ 'Note: The conversation has exceeded the model\'s context window. ' +
1293
+ 'The remainder of your message was trimmed to fit within the limit. ' +
1294
+ 'The beginning of your request (shown above) has been preserved.\n' +
1295
+ '</CONTEXT_LIMIT_REACHED>';
1296
+ const newTokens = this.estimateTokens(newContent);
1297
+ const saved = originalTokens - newTokens;
1298
+ if (saved > 0) {
1299
+ params.conversationMessages[lastUserMessageIndex] = {
1300
+ ...lastUserMessage,
1301
+ content: newContent
1302
+ };
1303
+ }
1304
+ return {
1305
+ tokensSaved: saved,
1306
+ strategyName: 'Preserved beginning of user message with context limit marker'
1307
+ };
1308
+ }
1309
+ async attemptContextRecovery(params, payload, errorMessage, modelSelectionInfo) {
1310
+ this.logStatus(`⚠️ Context length exceeded - attempting recovery with multi-strategy approach`, true, params);
1311
+ const modelLimit = this.getModelContextLimit(modelSelectionInfo);
1312
+ const currentTokens = this.estimateConversationTokens(params.conversationMessages);
1313
+ const tokensToSave = currentTokens - Math.floor(modelLimit * 0.9);
1314
+ this.logStatus(`Need to save ~${tokensToSave} tokens (current: ${currentTokens}, limit: ${modelLimit})`, true, params);
1315
+ if (tokensToSave <= 0) {
1316
+ this.logStatus(`Already under context limit, retrying...`, true, params);
1317
+ return {
1318
+ step: 'Retry',
1319
+ retryReason: 'Context recovery - already under limit',
1320
+ retryInstructions: 'The context is now within limits.',
1321
+ terminate: false,
1322
+ previousPayload: payload,
1323
+ newPayload: payload
1324
+ };
1325
+ }
1326
+ const currentStepCount = this._agentRun?.Steps?.length || 0;
1327
+ const strategies = [
1328
+ () => this.recoveryStrategy_RemoveOldestActionResults(params, tokensToSave, currentStepCount, 5),
1329
+ () => this.recoveryStrategy_CompactOldActionResults(params, tokensToSave, currentStepCount, 3),
1330
+ () => this.recoveryStrategy_RemoveOldestActionResults(params, tokensToSave, currentStepCount, 2),
1331
+ () => this.recoveryStrategy_CompactAllActionResults(params, tokensToSave),
1332
+ () => Promise.resolve(this.recoveryStrategy_TrimLastUserMessage(params, tokensToSave))
1333
+ ];
1334
+ let tokensSaved = 0;
1335
+ const strategiesUsed = [];
1336
+ for (const strategy of strategies) {
1337
+ const result = await strategy();
1338
+ tokensSaved += result.tokensSaved;
1339
+ if (result.tokensSaved > 0) {
1340
+ strategiesUsed.push(result.strategyName);
1341
+ this.logStatus(`${result.strategyName}: saved ${result.tokensSaved} tokens`, true, params);
1342
+ }
1343
+ if (tokensSaved >= tokensToSave) {
1344
+ break;
1345
+ }
1346
+ }
1347
+ if (tokensSaved < tokensToSave * 0.5) {
1348
+ this.logStatus(`❌ Context recovery insufficient: only saved ${tokensSaved}/${tokensToSave} tokens`, true, params);
1088
1349
  return {
1089
- errorMessage: `Context overflow with no trimmable messages: ${errorMessage}`,
1350
+ errorMessage: `Context recovery failed: only saved ${tokensSaved}/${tokensToSave} tokens. ${errorMessage}`,
1090
1351
  step: 'Failed',
1091
1352
  terminate: true,
1092
1353
  previousPayload: payload,
1093
- newPayload: payload,
1354
+ newPayload: payload
1094
1355
  };
1095
1356
  }
1096
- const originalMessage = messages[lastUserMessageIndex];
1097
- const contentString = this.contentToString(originalMessage.content);
1098
- const trimResult = this.smartTrimContent(contentString, 1000);
1099
- this.logStatus(`✂️ Trimmed message from ${trimResult.originalLength.toLocaleString()} to ${trimResult.trimmed.length.toLocaleString()} characters using ${trimResult.strategy}`, true, params);
1100
- messages[lastUserMessageIndex] = {
1101
- role: 'user',
1102
- content: `⚠️ CONTEXT OVERFLOW RECOVERY ⚠️
1103
-
1104
- The previous step returned a result that exceeded the context window (${(trimResult.originalLength - trimResult.trimmed.length).toLocaleString()} characters truncated).
1105
-
1106
- Here is a PARTIAL result from the previous action:
1107
- ---
1108
- ${trimResult.trimmed}
1109
- ---
1110
-
1111
- ❗ THE ABOVE IS INCOMPLETE - the full result was too large for the context window.
1112
-
1113
- RECOMMENDED ACTIONS:
1114
- 1. Use a different action with more specific filters to get smaller result sets
1115
- 2. Request data in batches or pages instead of all at once
1116
- 3. Ask the user to clarify scope to narrow the query
1117
- 4. If you need the full data, acknowledge the limitation and ask the user how to proceed
1118
-
1119
- Please choose an alternative approach to complete your task.`,
1120
- };
1357
+ this.logStatus(`✅ Context recovery successful: saved ${tokensSaved} tokens using ${strategiesUsed.length} strategies`, true, params);
1358
+ const strategyDescriptions = strategiesUsed.map((strategy, index) => `${index + 1}. ${strategy}`).join('\n');
1121
1359
  return {
1122
1360
  step: 'Retry',
1123
- retryReason: 'Context length recovery - previous result too large',
1124
- retryInstructions: 'The previous action result exceeded context limits. Use more specific filters or request data in smaller batches.',
1361
+ retryReason: `Context recovery successful - ${tokensSaved} tokens freed`,
1362
+ retryInstructions: `The conversation exceeded the model's context limit (${modelLimit} tokens). I've applied the following context recovery strategies to free up ${tokensSaved} tokens:
1363
+
1364
+ ${strategyDescriptions}
1365
+
1366
+ The context is now within limits. Please retry your request with the recovered context.`,
1125
1367
  terminate: false,
1126
1368
  previousPayload: payload,
1127
- newPayload: payload,
1369
+ newPayload: payload
1128
1370
  };
1129
1371
  }
1130
1372
  async processNextStep(nextStep, params, agentType, promptResult, currentPayload, currentStep) {
1131
1373
  const validatedNextStep = await this.validateNextStep(params, nextStep, currentPayload, this._agentRun, currentStep);
1132
1374
  const guardrailCheckedStep = await this.checkExecutionGuardrails(params, validatedNextStep, currentPayload, this._agentRun, currentStep);
1133
1375
  this.logStatus(`📌 Next step determined: ${guardrailCheckedStep.step}${guardrailCheckedStep.terminate ? ' (terminating)' : ''}`, true, params);
1134
- if (guardrailCheckedStep.step === 'Retry' &&
1135
- (guardrailCheckedStep.message || guardrailCheckedStep.errorMessage || guardrailCheckedStep.retryInstructions)) {
1376
+ if (guardrailCheckedStep.step === 'Retry' && (guardrailCheckedStep.message || guardrailCheckedStep.errorMessage || guardrailCheckedStep.retryInstructions)) {
1136
1377
  params.conversationMessages.push({
1137
1378
  role: 'user',
1138
- content: `Retrying due to: ${guardrailCheckedStep.retryInstructions || guardrailCheckedStep.message || guardrailCheckedStep.errorMessage}`,
1379
+ content: `Retrying due to: ${guardrailCheckedStep.retryInstructions || guardrailCheckedStep.message || guardrailCheckedStep.errorMessage}`
1139
1380
  });
1140
1381
  }
1141
1382
  return guardrailCheckedStep;
@@ -1152,36 +1393,37 @@ Please choose an alternative approach to complete your task.`,
1152
1393
  outputs: outputParams.reduce((acc, param) => {
1153
1394
  acc[param.Name] = param.Value;
1154
1395
  return acc;
1155
- }, {}),
1396
+ }, {})
1156
1397
  };
1157
1398
  });
1158
1399
  return {
1159
1400
  role: 'user',
1160
- content: `Action results:\n${JSON.stringify(resultSummary, null, 2)}`,
1401
+ content: `Action results:\n${JSON.stringify(resultSummary, null, 2)}`
1161
1402
  };
1162
1403
  }
1163
1404
  createSubAgentResultMessage(subAgent, result) {
1164
1405
  return {
1165
1406
  role: 'user',
1166
- content: `Sub-agent '${subAgent.name}' result:\n${typeof result === 'string' ? result : JSON.stringify(result, null, 2)}`,
1407
+ content: `Sub-agent '${subAgent.name}' result:\n${typeof result === 'string' ? result : JSON.stringify(result, null, 2)}`
1167
1408
  };
1168
1409
  }
1169
1410
  async gatherPromptTemplateData(agent, _contextUser, extraData) {
1170
1411
  try {
1171
1412
  const engine = aiengine_1.AIEngine.Instance;
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');
1413
+ const activeSubAgents = engine.Agents.filter(a => a.ParentID === agent.ID && a.Status === 'Active')
1414
+ .sort((a, b) => a.ExecutionOrder - b.ExecutionOrder);
1415
+ const activeAgentRelationships = engine.AgentRelationships.filter(ar => ar.AgentID === agent.ID && ar.Status === 'Active');
1174
1416
  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');
1417
+ activeSubAgents.forEach(a => uniqueActiveSubAgentIDs.add(a.ID));
1418
+ activeAgentRelationships.forEach(ar => uniqueActiveSubAgentIDs.add(ar.SubAgentID));
1419
+ const uniqueActiveSubAgents = Array.from(uniqueActiveSubAgentIDs).map(id => engine.Agents.find(a => a.ID === id));
1420
+ const agentActions = engine.AgentActions.filter(aa => aa.AgentID === agent.ID && aa.Status === 'Active');
1421
+ const actions = actions_1.ActionEngineServer.Instance.Actions.filter(a => agentActions.some(aa => aa.ActionID === a.ID));
1422
+ const activeActions = actions.filter(a => a.Status === 'Active');
1181
1423
  const contextData = {
1182
1424
  agentName: agent.Name,
1183
1425
  agentDescription: agent.Description,
1184
- parentAgentName: agent.Parent ? agent.Parent.trim() : '',
1426
+ parentAgentName: agent.Parent ? agent.Parent.trim() : "",
1185
1427
  subAgentCount: uniqueActiveSubAgents.length,
1186
1428
  subAgentDetails: this.formatSubAgentDetails(uniqueActiveSubAgents),
1187
1429
  actionCount: actions.length,
@@ -1190,7 +1432,7 @@ Please choose an alternative approach to complete your task.`,
1190
1432
  if (extraData) {
1191
1433
  return {
1192
1434
  ...contextData,
1193
- ...extraData,
1435
+ ...extraData
1194
1436
  };
1195
1437
  }
1196
1438
  else {
@@ -1207,7 +1449,7 @@ Please choose an alternative approach to complete your task.`,
1207
1449
  const actionParams = Object.entries(action.params || {}).map(([key, value]) => ({
1208
1450
  Name: key,
1209
1451
  Value: value,
1210
- Type: 'Input',
1452
+ Type: 'Input'
1211
1453
  }));
1212
1454
  const result = await actionEngine.RunAction({
1213
1455
  Action: actionEntity,
@@ -1215,7 +1457,7 @@ Please choose an alternative approach to complete your task.`,
1215
1457
  ContextUser: contextUser,
1216
1458
  Filters: [],
1217
1459
  SkipActionLog: false,
1218
- Context: params.context,
1460
+ Context: params.context
1219
1461
  });
1220
1462
  if (result.Success) {
1221
1463
  this.logStatus(` ✅ Action '${action.name}' completed successfully`, true, params);
@@ -1230,24 +1472,67 @@ Please choose an alternative approach to complete your task.`,
1230
1472
  category: 'ActionExecution',
1231
1473
  metadata: {
1232
1474
  actionName: action.name,
1233
- actionParams: action.params,
1234
- },
1475
+ actionParams: action.params
1476
+ }
1235
1477
  });
1236
1478
  throw new Error(`Error executing actions: ${error.message}`);
1237
1479
  }
1238
1480
  }
1481
+ prepareSubAgentMessages(params, subAgentRequest, subAgent, contextMessage) {
1482
+ const engine = aiengine_1.AIEngine.Instance;
1483
+ let messages = [];
1484
+ const relationship = engine.AgentRelationships.find(r => r.AgentID === params.agent.ID && r.SubAgentID === subAgent.ID);
1485
+ let messageMode = relationship?.MessageMode || subAgent.MessageMode || 'None';
1486
+ let maxMessages = relationship?.MaxMessages || subAgent.MaxMessages || null;
1487
+ switch (messageMode) {
1488
+ case 'None':
1489
+ break;
1490
+ case 'All':
1491
+ messages = [...params.conversationMessages];
1492
+ break;
1493
+ case 'Latest':
1494
+ if (maxMessages && maxMessages > 0) {
1495
+ messages = params.conversationMessages.slice(-maxMessages);
1496
+ }
1497
+ else {
1498
+ messages = [...params.conversationMessages];
1499
+ }
1500
+ break;
1501
+ case 'Bookend':
1502
+ if (maxMessages && maxMessages > 2 && params.conversationMessages.length > maxMessages) {
1503
+ const firstTwo = params.conversationMessages.slice(0, 2);
1504
+ const remaining = params.conversationMessages.slice(-(maxMessages - 2));
1505
+ const omittedCount = params.conversationMessages.length - maxMessages;
1506
+ messages = [
1507
+ ...firstTwo,
1508
+ {
1509
+ role: 'system',
1510
+ content: `[${omittedCount} messages omitted for context management]`
1511
+ },
1512
+ ...remaining
1513
+ ];
1514
+ }
1515
+ else {
1516
+ messages = [...params.conversationMessages];
1517
+ }
1518
+ break;
1519
+ default:
1520
+ break;
1521
+ }
1522
+ if (contextMessage) {
1523
+ messages.push(contextMessage);
1524
+ }
1525
+ messages.push({
1526
+ role: 'user',
1527
+ content: subAgentRequest.message
1528
+ });
1529
+ return messages;
1530
+ }
1239
1531
  async ExecuteSubAgent(params, subAgentRequest, subAgent, stepEntity, payload, contextMessage) {
1240
1532
  try {
1241
1533
  this.logStatus(`🤖 Executing sub-agent '${subAgentRequest.name}'`, true, params);
1242
1534
  const runner = new AgentRunner_1.AgentRunner();
1243
- const subAgentMessages = [];
1244
- if (contextMessage) {
1245
- subAgentMessages.push(contextMessage);
1246
- }
1247
- subAgentMessages.push({
1248
- role: 'user',
1249
- content: subAgentRequest.message,
1250
- });
1535
+ const subAgentMessages = this.prepareSubAgentMessages(params, subAgentRequest, subAgent, contextMessage);
1251
1536
  this.logStatus(`📨 Sub-agent message: "${subAgentRequest.message}"`, true, params);
1252
1537
  if (subAgentRequest.templateParameters) {
1253
1538
  this.logStatus(`📎 Template parameters: ${JSON.stringify(subAgentRequest.templateParameters)}`, true, params);
@@ -1277,7 +1562,7 @@ Please choose an alternative approach to complete your task.`,
1277
1562
  onAgentRunCreated: async (agentRunId) => {
1278
1563
  stepEntity.TargetLogID = agentRunId;
1279
1564
  await stepEntity.Save();
1280
- },
1565
+ }
1281
1566
  });
1282
1567
  if (result.success) {
1283
1568
  this.logStatus(`✅ Sub-agent '${subAgentRequest.name}' completed successfully`, true, params);
@@ -1293,17 +1578,17 @@ Please choose an alternative approach to complete your task.`,
1293
1578
  metadata: {
1294
1579
  agentName: params.agent.Name,
1295
1580
  subAgentName: subAgentRequest.name,
1296
- message: subAgentRequest.message,
1297
- },
1581
+ message: subAgentRequest.message
1582
+ }
1298
1583
  });
1299
1584
  throw new Error(`Error executing sub-agent: ${error.message}`);
1300
1585
  }
1301
1586
  }
1302
1587
  formatSubAgentDetails(subAgents) {
1303
- return JSON.stringify(subAgents.map((sa) => {
1588
+ return JSON.stringify(subAgents.map(sa => {
1304
1589
  const result = {
1305
1590
  Name: sa.Name,
1306
- Description: sa.Description,
1591
+ Description: sa.Description
1307
1592
  };
1308
1593
  if (sa.ExecutionMode !== 'Sequential') {
1309
1594
  result['ExecutionMode'] = sa.ExecutionMode;
@@ -1314,39 +1599,45 @@ Please choose an alternative approach to complete your task.`,
1314
1599
  }
1315
1600
  getAgentPromptParameters(agent) {
1316
1601
  const engine = aiengine_1.AIEngine.Instance;
1317
- const agentPrompt = engine.AgentPrompts.filter((ap) => ap.AgentID === agent.ID && ap.Status === 'Active').sort((a, b) => a.ExecutionOrder - b.ExecutionOrder)[0];
1602
+ const agentPrompt = engine.AgentPrompts
1603
+ .filter(ap => ap.AgentID === agent.ID && ap.Status === 'Active')
1604
+ .sort((a, b) => a.ExecutionOrder - b.ExecutionOrder)[0];
1318
1605
  if (!agentPrompt)
1319
1606
  return [];
1320
- const prompt = engine.Prompts.find((p) => p.ID === agentPrompt.PromptID);
1607
+ const prompt = engine.Prompts.find(p => p.ID === agentPrompt.PromptID);
1321
1608
  if (!prompt)
1322
1609
  return [];
1323
1610
  return prompt.TemplateParams;
1324
1611
  }
1325
1612
  getAgentPromptParametersJSON(agent) {
1326
1613
  const params = this.getAgentPromptParameters(agent);
1327
- return JSON.stringify(params.map((param) => ({
1614
+ return JSON.stringify(params.map(param => ({
1328
1615
  Name: param.Name,
1329
1616
  Type: param.Type,
1330
1617
  IsRequired: param.IsRequired,
1331
1618
  DefaultValue: param.DefaultValue,
1332
- Description: param.Description,
1619
+ Description: param.Description
1333
1620
  })), null, 2);
1334
1621
  }
1335
1622
  formatActionDetails(actions) {
1336
- return JSON.stringify(actions.map((action) => ({
1623
+ return JSON.stringify(actions.map(action => ({
1337
1624
  Name: action.Name,
1338
1625
  Description: action.Description,
1339
1626
  Parameters: {
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)),
1627
+ Input: action.Params
1628
+ .filter(p => p.Type.trim().toLowerCase() === 'input' || p.Type.trim().toLowerCase() === 'both')
1629
+ .map(param => this.formatActionParameter(param)),
1630
+ Output: action.Params
1631
+ .filter(p => p.Type.trim().toLowerCase() === 'output' || p.Type.trim().toLowerCase() === 'both')
1632
+ .map(param => this.formatActionParameter(param))
1342
1633
  },
1343
- ResultCodes: action.ResultCodes.map((rc) => ({
1634
+ ResultCodes: action.ResultCodes.map(rc => ({
1344
1635
  Code: rc.ResultCode,
1345
1636
  IsSuccess: rc.IsSuccess,
1346
1637
  Description: rc.Description || 'No description provided',
1347
1638
  })),
1348
1639
  Category: action.CategoryID ? this.getActionCategoryName(action.CategoryID) : null,
1349
- Status: action.Status,
1640
+ Status: action.Status
1350
1641
  })), null, 2);
1351
1642
  }
1352
1643
  formatActionParameter(param) {
@@ -1357,7 +1648,7 @@ Please choose an alternative approach to complete your task.`,
1357
1648
  IsArray: param.IsArray,
1358
1649
  DefaultValue: param.DefaultValue,
1359
1650
  Description: param.Description,
1360
- ValueType: param.ValueType,
1651
+ ValueType: param.ValueType
1361
1652
  };
1362
1653
  }
1363
1654
  formatParamValueForMessage(value, maxLength = 100) {
@@ -1380,7 +1671,7 @@ Please choose an alternative approach to complete your task.`,
1380
1671
  return `\`${stringValue}\``;
1381
1672
  }
1382
1673
  getAgentTypeName(typeID) {
1383
- const agentType = aiengine_1.AIEngine.Instance.AgentTypes.find((at) => at.ID === typeID);
1674
+ const agentType = aiengine_1.AIEngine.Instance.AgentTypes.find(at => at.ID === typeID);
1384
1675
  return agentType?.Name || 'Unknown';
1385
1676
  }
1386
1677
  getValueListItems(valueListID) {
@@ -1392,11 +1683,11 @@ Please choose an alternative approach to complete your task.`,
1392
1683
  async initializeAgentRun(params) {
1393
1684
  let modifiedParams = params;
1394
1685
  if (params.lastRunId && params.autoPopulateLastRunPayload) {
1395
- const rv = new global_1.RunView();
1686
+ const rv = new core_1.RunView();
1396
1687
  const lastRunResult = await rv.RunView({
1397
1688
  EntityName: 'MJ: AI Agent Runs',
1398
1689
  ExtraFilter: `ID='${params.lastRunId}'`,
1399
- ResultType: 'simple',
1690
+ ResultType: 'simple'
1400
1691
  }, params.contextUser);
1401
1692
  if (lastRunResult.Success && lastRunResult.Results.length > 0) {
1402
1693
  const lastRun = lastRunResult.Results[0];
@@ -1406,14 +1697,14 @@ Please choose an alternative approach to complete your task.`,
1406
1697
  if (!params.payload) {
1407
1698
  modifiedParams = {
1408
1699
  ...params,
1409
- payload: lastPayload,
1700
+ payload: lastPayload
1410
1701
  };
1411
1702
  }
1412
1703
  }
1413
1704
  catch (e) {
1414
1705
  this.logError(`Failed to parse FinalPayload from last run: ${e}`, {
1415
1706
  category: 'LastRunPayload',
1416
- metadata: { lastRunId: params.lastRunId },
1707
+ metadata: { lastRunId: params.lastRunId }
1417
1708
  });
1418
1709
  }
1419
1710
  }
@@ -1454,8 +1745,8 @@ Please choose an alternative approach to complete your task.`,
1454
1745
  this._agentRun.Data = JSON.stringify(params.data);
1455
1746
  }
1456
1747
  this._agentRun.Verbose = params.verbose || false;
1457
- if (!(await this._agentRun.Save())) {
1458
- const errorMessage = JSON.stringify((0, global_2.CopyScalarsAndArrays)(this._agentRun.LatestResult));
1748
+ if (!await this._agentRun.Save()) {
1749
+ const errorMessage = JSON.stringify((0, global_1.CopyScalarsAndArrays)(this._agentRun.LatestResult));
1459
1750
  throw new Error(`Failed to create agent run record: Details: ${errorMessage}`);
1460
1751
  }
1461
1752
  if (modifiedParams.onAgentRunCreated) {
@@ -1463,7 +1754,7 @@ Please choose an alternative approach to complete your task.`,
1463
1754
  await modifiedParams.onAgentRunCreated(this._agentRun.ID);
1464
1755
  }
1465
1756
  catch (callbackError) {
1466
- (0, global_1.LogStatus)(`Error in onAgentRunCreated callback: ${callbackError.message}`);
1757
+ (0, core_1.LogStatus)(`Error in onAgentRunCreated callback: ${callbackError.message}`);
1467
1758
  }
1468
1759
  }
1469
1760
  this._agentHierarchy = params.parentAgentHierarchy
@@ -1515,11 +1806,11 @@ Please choose an alternative approach to complete your task.`,
1515
1806
  context: {
1516
1807
  agentHierarchy: this._agentHierarchy,
1517
1808
  depth: this._depth,
1518
- stepNumber: stepEntity.StepNumber,
1519
- },
1809
+ stepNumber: stepEntity.StepNumber
1810
+ }
1520
1811
  });
1521
1812
  }
1522
- if (!(await stepEntity.Save())) {
1813
+ if (!await stepEntity.Save()) {
1523
1814
  throw new Error(`Failed to create agent run step record: ${JSON.stringify(stepEntity.LatestResult)}`);
1524
1815
  }
1525
1816
  if (this._agentRun) {
@@ -1533,35 +1824,29 @@ Please choose an alternative approach to complete your task.`,
1533
1824
  warnings: changeResult.warnings,
1534
1825
  requiresFeedback: changeResult.requiresFeedback,
1535
1826
  timestamp: changeResult.timestamp,
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,
1827
+ payloadValidation: changeResult.blockedOperations && changeResult.blockedOperations.length > 0 ? {
1828
+ selfWriteViolations: {
1829
+ deniedOperations: changeResult.blockedOperations,
1830
+ timestamp: changeResult.timestamp.toISOString()
1831
+ }
1832
+ } : undefined,
1833
+ analysis: changeResult.analysis ? {
1834
+ totalWarnings: changeResult.analysis.summary.totalWarnings,
1835
+ warningsByType: changeResult.analysis.summary.warningsByType,
1836
+ suspiciousChanges: changeResult.analysis.summary.suspiciousChanges,
1837
+ criticalWarnings: changeResult.analysis.criticalWarnings.map(w => ({
1838
+ type: w.type,
1839
+ severity: w.severity,
1840
+ path: w.path,
1841
+ message: w.message
1842
+ }))
1843
+ } : undefined,
1844
+ diffSummary: changeResult.diff ? {
1845
+ added: changeResult.diff.summary.added,
1846
+ removed: changeResult.diff.summary.removed,
1847
+ modified: changeResult.diff.summary.modified,
1848
+ totalChanges: changeResult.diff.summary.totalPaths
1849
+ } : undefined
1565
1850
  };
1566
1851
  }
1567
1852
  async finalizeStepEntity(stepEntity, success, errorMessage, outputData) {
@@ -1575,11 +1860,11 @@ Please choose an alternative approach to complete your task.`,
1575
1860
  context: {
1576
1861
  success,
1577
1862
  durationMs: stepEntity.CompletedAt.getTime() - stepEntity.StartedAt.getTime(),
1578
- errorMessage,
1579
- },
1863
+ errorMessage
1864
+ }
1580
1865
  });
1581
1866
  }
1582
- if (!(await stepEntity.Save())) {
1867
+ if (!await stepEntity.Save()) {
1583
1868
  console.error('Failed to update agent run step record');
1584
1869
  }
1585
1870
  }
@@ -1645,7 +1930,9 @@ Please choose an alternative approach to complete your task.`,
1645
1930
  }
1646
1931
  formatHierarchicalMessage(baseMessage) {
1647
1932
  if (this._depth > 0) {
1648
- const breadcrumb = this._agentHierarchy.slice(1).join(' → ');
1933
+ const breadcrumb = this._agentHierarchy
1934
+ .slice(1)
1935
+ .join(' → ');
1649
1936
  return breadcrumb ? `${breadcrumb}: ${baseMessage}` : baseMessage;
1650
1937
  }
1651
1938
  return baseMessage;
@@ -1691,7 +1978,7 @@ Please choose an alternative approach to complete your task.`,
1691
1978
  terminate: true,
1692
1979
  step: 'Success',
1693
1980
  previousPayload: previousDecision.previousPayload,
1694
- newPayload: previousDecision.newPayload,
1981
+ newPayload: previousDecision.newPayload
1695
1982
  };
1696
1983
  }
1697
1984
  else {
@@ -1703,7 +1990,7 @@ Please choose an alternative approach to complete your task.`,
1703
1990
  terminate: true,
1704
1991
  step: 'Failed',
1705
1992
  previousPayload: previousDecision.previousPayload,
1706
- newPayload: previousDecision.newPayload,
1993
+ newPayload: previousDecision.newPayload
1707
1994
  };
1708
1995
  }
1709
1996
  else {
@@ -1725,23 +2012,14 @@ Please choose an alternative approach to complete your task.`,
1725
2012
  promptId: promptId,
1726
2013
  promptName: promptName,
1727
2014
  isRetry: !!previousDecision,
1728
- retryContext: previousDecision
1729
- ? {
1730
- reason: previousDecision.retryReason,
1731
- instructions: previousDecision.retryInstructions,
1732
- }
1733
- : undefined,
2015
+ retryContext: previousDecision ? {
2016
+ reason: previousDecision.retryReason,
2017
+ instructions: previousDecision.retryInstructions
2018
+ } : undefined,
1734
2019
  conversationMessages: params.conversationMessages,
1735
2020
  };
1736
2021
  const payload = previousDecision?.newPayload || params.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
- });
2022
+ const stepEntity = await this.createStepEntity({ stepType: 'Prompt', stepName: 'Execute Agent Prompt', contextUser: params.contextUser, targetId: promptId, inputData, payloadAtStart: payload });
1745
2023
  try {
1746
2024
  const isRetry = !!previousDecision;
1747
2025
  const promptMessage = isRetry
@@ -1754,9 +2032,9 @@ Please choose an alternative approach to complete your task.`,
1754
2032
  metadata: {
1755
2033
  promptId: promptId,
1756
2034
  isRetry,
1757
- promptName: promptName,
2035
+ promptName: promptName
1758
2036
  },
1759
- displayMode: 'live',
2037
+ displayMode: 'live'
1760
2038
  });
1761
2039
  if (stepEntity && payload) {
1762
2040
  stepEntity.PayloadAtStart = JSON.stringify(payload);
@@ -1766,36 +2044,32 @@ Please choose an alternative approach to complete your task.`,
1766
2044
  const downstreamPaths = JSON.parse(params.agent.PayloadSelfReadPaths);
1767
2045
  downstreamPayload = this._payloadManager.extractDownstreamPayload(`Self: ${params.agent.Name}`, payload, downstreamPaths);
1768
2046
  }
1769
- const promptConfig = promptToUse && promptToUse !== config.childPrompt
1770
- ? {
1771
- ...config,
1772
- childPrompt: promptToUse,
1773
- systemPrompt: null,
1774
- }
1775
- : config;
2047
+ const promptConfig = (promptToUse && promptToUse !== config.childPrompt) ? {
2048
+ ...config,
2049
+ childPrompt: promptToUse,
2050
+ systemPrompt: null
2051
+ } : config;
1776
2052
  if (this._agentRun) {
1777
2053
  this._agentRun.TotalPromptIterations = (this._agentRun.TotalPromptIterations || 0) + 1;
1778
2054
  }
1779
2055
  const promptParams = await this.preparePromptParams(promptConfig, downstreamPayload, params);
1780
2056
  promptParams.cancellationToken = params.cancellationToken;
1781
- promptParams.onStreaming = params.onStreaming
1782
- ? (chunk) => {
1783
- params.onStreaming({
1784
- ...chunk,
1785
- stepType: 'prompt',
1786
- stepEntityId: stepEntity.ID,
1787
- });
1788
- }
1789
- : undefined;
2057
+ promptParams.onStreaming = params.onStreaming ? (chunk) => {
2058
+ params.onStreaming({
2059
+ ...chunk,
2060
+ stepType: 'prompt',
2061
+ stepEntityId: stepEntity.ID
2062
+ });
2063
+ } : undefined;
1790
2064
  promptParams.onPromptRunCreated = async (promptRunId) => {
1791
2065
  stepEntity.TargetLogID = promptRunId;
1792
2066
  await stepEntity.Save();
1793
2067
  };
1794
2068
  const promptResult = await this.executePrompt(promptParams);
1795
- const loopMsgIndex = params.conversationMessages.findIndex((m) => m.metadata?._loopResults === true);
1796
- if (loopMsgIndex !== -1) {
1797
- params.conversationMessages.splice(loopMsgIndex, 1);
1798
- }
2069
+ params.conversationMessages = params.conversationMessages.filter(m => {
2070
+ const metadata = m.metadata;
2071
+ return !metadata?._loopResults && !metadata?._subAgentResult;
2072
+ });
1799
2073
  if (promptResult.promptRun?.ID) {
1800
2074
  stepEntity.TargetLogID = promptResult.promptRun.ID;
1801
2075
  stepEntity.PromptRun = promptResult.promptRun;
@@ -1803,11 +2077,12 @@ Please choose an alternative approach to complete your task.`,
1803
2077
  if (!promptResult.success) {
1804
2078
  await this.finalizeStepEntity(stepEntity, false, promptResult.errorMessage);
1805
2079
  const isFatal = this.isFatalPromptError(promptResult);
1806
- const isContextOverflow = isFatal && promptResult.chatResult?.errorInfo?.errorType === 'ContextLengthExceeded';
1807
- if (isContextOverflow && !this._contextRecoveryAttempted) {
1808
- this._contextRecoveryAttempted = true;
2080
+ const isContextOverflow = isFatal &&
2081
+ promptResult.chatResult?.errorInfo?.errorType === 'ContextLengthExceeded';
2082
+ if (isContextOverflow && this._contextRecoveryAttempts < this.MAX_RECOVERY_ATTEMPTS) {
2083
+ this._contextRecoveryAttempts++;
1809
2084
  this.logStatus(`⚠️ Context length exceeded - attempting recovery by trimming conversation`, true, params);
1810
- return await this.attemptContextRecovery(params, payload, promptResult.errorMessage || 'Context length exceeded');
2085
+ return await this.attemptContextRecovery(params, payload, promptResult.errorMessage || 'Context length exceeded', promptResult.modelSelectionInfo);
1811
2086
  }
1812
2087
  this.logStatus(`❌ Prompt execution failed: ${promptResult.errorMessage} (fatal: ${isFatal})`, true, params);
1813
2088
  return {
@@ -1815,7 +2090,7 @@ Please choose an alternative approach to complete your task.`,
1815
2090
  step: 'Failed',
1816
2091
  terminate: isFatal,
1817
2092
  previousPayload: payload,
1818
- newPayload: payload,
2093
+ newPayload: payload
1819
2094
  };
1820
2095
  }
1821
2096
  if (params.cancellationToken?.aborted) {
@@ -1826,20 +2101,22 @@ Please choose an alternative approach to complete your task.`,
1826
2101
  terminate: true,
1827
2102
  step: 'Failed',
1828
2103
  previousPayload: cancelledResult.payload,
1829
- newPayload: cancelledResult.payload,
2104
+ newPayload: cancelledResult.payload
1830
2105
  };
1831
2106
  }
1832
2107
  params.onProgress?.({
1833
2108
  step: 'decision_processing',
1834
2109
  percentage: 70,
1835
2110
  message: this.formatHierarchicalMessage('Analyzing response and determining next steps'),
1836
- displayMode: 'both',
2111
+ displayMode: 'both'
1837
2112
  });
1838
2113
  const initialNextStep = await this.determineNextStep(params, config.agentType, promptResult, payload);
1839
2114
  let finalPayload = payload;
1840
2115
  let currentStepPayloadChangeResult = undefined;
1841
2116
  if (initialNextStep.payloadChangeRequest) {
1842
- const allowedPaths = params.agent.PayloadSelfWritePaths ? JSON.parse(params.agent.PayloadSelfWritePaths) : undefined;
2117
+ const allowedPaths = params.agent.PayloadSelfWritePaths
2118
+ ? JSON.parse(params.agent.PayloadSelfWritePaths)
2119
+ : undefined;
1843
2120
  const changeResult = this._payloadManager.applyAgentChangeRequest(payload, initialNextStep.payloadChangeRequest, {
1844
2121
  validateChanges: true,
1845
2122
  logChanges: true,
@@ -1847,10 +2124,10 @@ Please choose an alternative approach to complete your task.`,
1847
2124
  analyzeChanges: true,
1848
2125
  generateDiff: true,
1849
2126
  allowedPaths: allowedPaths,
1850
- verbose: params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)(),
2127
+ verbose: params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)()
1851
2128
  });
1852
- if (changeResult.warnings.length > 0 && (params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)())) {
1853
- (0, global_1.LogStatus)(`Payload warnings: ${changeResult.warnings.join('; ')}`);
2129
+ if (changeResult.warnings.length > 0 && (params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)())) {
2130
+ (0, core_1.LogStatus)(`Payload warnings: ${changeResult.warnings.join('; ')}`);
1854
2131
  }
1855
2132
  currentStepPayloadChangeResult = this.buildPayloadChangeResultSummary(changeResult);
1856
2133
  finalPayload = changeResult.result;
@@ -1863,8 +2140,8 @@ Please choose an alternative approach to complete your task.`,
1863
2140
  reasoning: this.getNextStepReasoning(updatedNextStep),
1864
2141
  },
1865
2142
  ...(currentStepPayloadChangeResult && {
1866
- payloadChangeResult: currentStepPayloadChangeResult,
1867
- }),
2143
+ payloadChangeResult: currentStepPayloadChangeResult
2144
+ })
1868
2145
  };
1869
2146
  if (stepEntity && finalPayload) {
1870
2147
  stepEntity.PayloadAtEnd = JSON.stringify(finalPayload);
@@ -1895,12 +2172,13 @@ Please choose an alternative approach to complete your task.`,
1895
2172
  step: 'Failed',
1896
2173
  terminate: false,
1897
2174
  previousPayload: payload,
1898
- newPayload: payload,
2175
+ newPayload: payload
1899
2176
  };
1900
2177
  const guardailCheck = await this.hasExceededAgentRunGuardrails(params, this.AgentRun);
1901
2178
  if (guardailCheck && guardailCheck.exceeded) {
1902
2179
  errorNextStep.terminate = true;
1903
2180
  }
2181
+ ;
1904
2182
  return errorNextStep;
1905
2183
  }
1906
2184
  }
@@ -1916,12 +2194,12 @@ Please choose an alternative approach to complete your task.`,
1916
2194
  metadata: {
1917
2195
  agentName: params.agent.Name,
1918
2196
  subAgentName: subAgentRequest.name,
1919
- reason: subAgentRequest.message,
1920
- },
2197
+ reason: subAgentRequest.message
2198
+ }
1921
2199
  });
1922
2200
  params.conversationMessages.push({
1923
2201
  role: 'assistant',
1924
- content: `I'm delegating this task to the "${subAgentRequest.name}" agent.\n\nReason: ${subAgentRequest.message}`,
2202
+ content: `I'm delegating this task to the "${subAgentRequest.name}" agent.\n\nReason: ${subAgentRequest.message}`
1925
2203
  });
1926
2204
  const inputData = {
1927
2205
  agentName: params.agent.Name,
@@ -1929,20 +2207,14 @@ Please choose an alternative approach to complete your task.`,
1929
2207
  message: subAgentRequest.message,
1930
2208
  terminateAfter: subAgentRequest.terminateAfter,
1931
2209
  conversationMessages: params.conversationMessages,
1932
- parentAgentHierarchy: this._agentHierarchy,
2210
+ parentAgentHierarchy: this._agentHierarchy
1933
2211
  };
1934
- const subAgentEntity = aiengine_1.AIEngine.Instance.Agents.find((a) => a.Name === subAgentRequest.name && a.ParentID === params.agent.ID);
2212
+ const subAgentEntity = aiengine_1.AIEngine.Instance.Agents.find(a => a.Name === subAgentRequest.name &&
2213
+ a.ParentID === params.agent.ID);
1935
2214
  if (!subAgentEntity) {
1936
2215
  throw new Error(`Sub-agent '${subAgentRequest.name}' not found`);
1937
2216
  }
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
- });
2217
+ const stepEntity = await this.createStepEntity({ stepType: 'Sub-Agent', stepName: `Execute Sub-Agent: ${subAgentRequest.name}`, contextUser: params.contextUser, targetId: subAgentEntity.ID, inputData, payloadAtStart: previousDecision.newPayload });
1946
2218
  this.incrementExecutionCount(subAgentEntity.ID);
1947
2219
  try {
1948
2220
  let downstreamPaths = ['*'];
@@ -1963,8 +2235,8 @@ Please choose an alternative approach to complete your task.`,
1963
2235
  subAgentName: subAgentRequest.name,
1964
2236
  subAgentId: subAgentEntity.ID,
1965
2237
  downstreamPaths: subAgentEntity.PayloadDownstreamPaths,
1966
- upstreamPaths: subAgentEntity.PayloadUpstreamPaths,
1967
- },
2238
+ upstreamPaths: subAgentEntity.PayloadUpstreamPaths
2239
+ }
1968
2240
  });
1969
2241
  }
1970
2242
  let downstreamPayload = this._payloadManager.extractDownstreamPayload(subAgentRequest.name, previousDecision.newPayload, downstreamPaths);
@@ -1979,8 +2251,8 @@ Please choose an alternative approach to complete your task.`,
1979
2251
  agentName: params.agent.Name,
1980
2252
  subAgentName: subAgentRequest.name,
1981
2253
  payloadScope: subAgentEntity.PayloadScope,
1982
- availableKeys: Object.keys(downstreamPayload || {}),
1983
- },
2254
+ availableKeys: Object.keys(downstreamPayload || {})
2255
+ }
1984
2256
  });
1985
2257
  throw new Error(errorMessage);
1986
2258
  }
@@ -1994,12 +2266,12 @@ Please choose an alternative approach to complete your task.`,
1994
2266
  if (subAgentEntity.PayloadScope) {
1995
2267
  resultPayloadForMerge = this._payloadManager.reversePayloadScope(subAgentResult.payload, subAgentEntity.PayloadScope);
1996
2268
  }
1997
- const mergeResult = this._payloadManager.mergeUpstreamPayload(subAgentRequest.name, previousDecision.newPayload, resultPayloadForMerge, upstreamPaths, params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)());
2269
+ const mergeResult = this._payloadManager.mergeUpstreamPayload(subAgentRequest.name, previousDecision.newPayload, resultPayloadForMerge, upstreamPaths, params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)());
1998
2270
  mergedPayload = mergeResult.result;
1999
2271
  const mergeChangeRequest = {
2000
2272
  newElements: {},
2001
2273
  updateElements: {},
2002
- removeElements: {},
2274
+ removeElements: {}
2003
2275
  };
2004
2276
  const originalKeys = Object.keys(previousDecision.newPayload || {});
2005
2277
  const mergedKeys = Object.keys(mergedPayload || {});
@@ -2025,7 +2297,7 @@ Please choose an alternative approach to complete your task.`,
2025
2297
  analyzeChanges: true,
2026
2298
  generateDiff: true,
2027
2299
  agentName: `${subAgentRequest.name} (upstream merge)`,
2028
- verbose: params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)(),
2300
+ verbose: params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)()
2029
2301
  });
2030
2302
  currentStepPayloadChangeResult = this.buildPayloadChangeResultSummary(mergeAnalysis);
2031
2303
  if (mergeResult.blockedOperations && mergeResult.blockedOperations.length > 0) {
@@ -2036,17 +2308,17 @@ Please choose an alternative approach to complete your task.`,
2036
2308
  subAgentName: subAgentRequest.name,
2037
2309
  attemptedOperations: mergeResult.blockedOperations,
2038
2310
  authorizedPaths: upstreamPaths,
2039
- timestamp: new Date().toISOString(),
2311
+ timestamp: new Date().toISOString()
2040
2312
  };
2041
2313
  }
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('; ')}`);
2314
+ if (mergeAnalysis.warnings.length > 0 && (params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)())) {
2315
+ (0, core_1.LogStatus)(`Sub-agent merge warnings: ${mergeAnalysis.warnings.join('; ')}`);
2044
2316
  }
2045
2317
  }
2046
2318
  }
2047
2319
  else {
2048
2320
  const msg = `Sub-agent '${subAgentRequest.name}' execution failed: ${subAgentResult.agentRun?.ErrorMessage || 'Unknown error'}`;
2049
- (0, global_1.LogError)(msg);
2321
+ (0, core_1.LogError)(msg);
2050
2322
  stepEntity.Success = false;
2051
2323
  stepEntity.ErrorMessage = msg;
2052
2324
  }
@@ -2071,8 +2343,8 @@ Please choose an alternative approach to complete your task.`,
2071
2343
  shouldTerminate: shouldTerminate,
2072
2344
  nextStep: shouldTerminate ? 'success' : 'retry',
2073
2345
  ...(currentStepPayloadChangeResult && {
2074
- payloadChangeResult: currentStepPayloadChangeResult,
2075
- }),
2346
+ payloadChangeResult: currentStepPayloadChangeResult
2347
+ })
2076
2348
  };
2077
2349
  await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
2078
2350
  if (subAgentResult.agentRun?.FinalStep === 'Chat') {
@@ -2081,7 +2353,7 @@ Please choose an alternative approach to complete your task.`,
2081
2353
  terminate: true,
2082
2354
  message: subAgentResult.agentRun?.Message || null,
2083
2355
  previousPayload: previousDecision?.newPayload,
2084
- newPayload: previousDecision?.newPayload,
2356
+ newPayload: previousDecision?.newPayload
2085
2357
  };
2086
2358
  }
2087
2359
  const subAgentSummary = {
@@ -2090,7 +2362,7 @@ Please choose an alternative approach to complete your task.`,
2090
2362
  subAgentId: subAgentEntity.ID,
2091
2363
  success: subAgentResult.success,
2092
2364
  finalStep: subAgentResult.agentRun?.FinalStep,
2093
- errorMessage: subAgentResult.agentRun?.ErrorMessage || null,
2365
+ errorMessage: subAgentResult.agentRun?.ErrorMessage || null
2094
2366
  };
2095
2367
  const resultMessage = subAgentResult.success
2096
2368
  ? `Sub-agent completed successfully:\n${JSON.stringify(subAgentSummary, null, 2)}`
@@ -2098,6 +2370,12 @@ Please choose an alternative approach to complete your task.`,
2098
2370
  params.conversationMessages.push({
2099
2371
  role: 'user',
2100
2372
  content: resultMessage,
2373
+ metadata: {
2374
+ _temporary: true,
2375
+ _subAgentResult: true,
2376
+ subAgentName: subAgentRequest.name,
2377
+ subAgentId: subAgentEntity.ID
2378
+ }
2101
2379
  });
2102
2380
  if (stepEntity) {
2103
2381
  stepEntity.PayloadAtEnd = JSON.stringify(mergedPayload);
@@ -2110,7 +2388,7 @@ Please choose an alternative approach to complete your task.`,
2110
2388
  step: subAgentResult.success ? 'Success' : 'Failed',
2111
2389
  terminate: shouldTerminate,
2112
2390
  previousPayload: previousDecision?.newPayload,
2113
- newPayload: mergedPayload,
2391
+ newPayload: mergedPayload
2114
2392
  };
2115
2393
  }
2116
2394
  catch (error) {
@@ -2122,7 +2400,7 @@ Please choose an alternative approach to complete your task.`,
2122
2400
  step: 'Failed',
2123
2401
  terminate: false,
2124
2402
  previousPayload: payload,
2125
- newPayload: payload,
2403
+ newPayload: payload
2126
2404
  };
2127
2405
  }
2128
2406
  }
@@ -2135,31 +2413,34 @@ Please choose an alternative approach to complete your task.`,
2135
2413
  terminate: false,
2136
2414
  errorMessage: 'Sub-agent name is required',
2137
2415
  previousPayload: previousDecision?.newPayload,
2138
- newPayload: previousDecision?.newPayload,
2416
+ newPayload: previousDecision?.newPayload
2139
2417
  };
2140
2418
  }
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());
2419
+ const childAgents = aiengine_1.AIEngine.Instance.Agents.filter(a => a.ParentID === params.agent.ID &&
2420
+ a.Status === 'Active');
2421
+ const childAgent = childAgents.find(a => a.Name.trim().toLowerCase() === name.trim().toLowerCase());
2143
2422
  if (childAgent) {
2144
2423
  return await this.executeChildSubAgentStep(params, previousDecision);
2145
2424
  }
2146
- const activeRelationships = aiengine_1.AIEngine.Instance.AgentRelationships.filter((ar) => ar.AgentID === params.agent.ID && ar.Status === 'Active');
2425
+ const activeRelationships = aiengine_1.AIEngine.Instance.AgentRelationships.filter(ar => ar.AgentID === params.agent.ID &&
2426
+ ar.Status === 'Active');
2147
2427
  for (const relationship of activeRelationships) {
2148
- const relatedAgent = aiengine_1.AIEngine.Instance.Agents.find((a) => a.ID === relationship.SubAgentID && a.Status === 'Active');
2428
+ const relatedAgent = aiengine_1.AIEngine.Instance.Agents.find(a => a.ID === relationship.SubAgentID &&
2429
+ a.Status === 'Active');
2149
2430
  if (relatedAgent && relatedAgent.Name.trim().toLowerCase() === name.trim().toLowerCase()) {
2150
2431
  return await this.executeRelatedSubAgentStep(params, previousDecision, relatedAgent, relationship);
2151
2432
  }
2152
2433
  }
2153
2434
  this.logError(`Sub-agent '${name}' not found or not active for agent '${params.agent.Name}'`, {
2154
2435
  agent: params.agent,
2155
- category: 'SubAgentExecution',
2436
+ category: 'SubAgentExecution'
2156
2437
  });
2157
2438
  return {
2158
2439
  step: 'Retry',
2159
2440
  terminate: false,
2160
2441
  errorMessage: `Sub-agent '${name}' not found or not active`,
2161
2442
  previousPayload: previousDecision?.newPayload,
2162
- newPayload: previousDecision?.newPayload,
2443
+ newPayload: previousDecision?.newPayload
2163
2444
  };
2164
2445
  }
2165
2446
  async executeRelatedSubAgentStep(params, previousDecision, subAgentEntity, relationship) {
@@ -2175,12 +2456,12 @@ Please choose an alternative approach to complete your task.`,
2175
2456
  agentName: params.agent.Name,
2176
2457
  subAgentName: subAgentRequest.name,
2177
2458
  reason: subAgentRequest.message,
2178
- relationshipType: 'related',
2179
- },
2459
+ relationshipType: 'related'
2460
+ }
2180
2461
  });
2181
2462
  params.conversationMessages.push({
2182
2463
  role: 'assistant',
2183
- content: `I'm delegating this task to the "${subAgentRequest.name}" agent.\n\nReason: ${subAgentRequest.message}`,
2464
+ content: `I'm delegating this task to the "${subAgentRequest.name}" agent.\n\nReason: ${subAgentRequest.message}`
2184
2465
  });
2185
2466
  const inputData = {
2186
2467
  agentName: params.agent.Name,
@@ -2189,7 +2470,7 @@ Please choose an alternative approach to complete your task.`,
2189
2470
  terminateAfter: subAgentRequest.terminateAfter,
2190
2471
  conversationMessages: params.conversationMessages,
2191
2472
  parentAgentHierarchy: this._agentHierarchy,
2192
- relationshipType: 'related',
2473
+ relationshipType: 'related'
2193
2474
  };
2194
2475
  const stepEntity = await this.createStepEntity({
2195
2476
  stepType: 'Sub-Agent',
@@ -2197,7 +2478,7 @@ Please choose an alternative approach to complete your task.`,
2197
2478
  contextUser: params.contextUser,
2198
2479
  targetId: subAgentEntity.ID,
2199
2480
  inputData,
2200
- payloadAtStart: previousDecision.newPayload,
2481
+ payloadAtStart: previousDecision.newPayload
2201
2482
  });
2202
2483
  this.incrementExecutionCount(subAgentEntity.ID);
2203
2484
  try {
@@ -2207,8 +2488,8 @@ Please choose an alternative approach to complete your task.`,
2207
2488
  const mapped = this.applySubAgentInputMapping(previousDecision.newPayload, relationship.SubAgentInputMapping);
2208
2489
  if (mapped && Object.keys(mapped).length > 0) {
2209
2490
  initialSubAgentPayload = 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))}`);
2491
+ if (params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)()) {
2492
+ (0, core_1.LogStatus)(`Related sub-agent '${subAgentRequest.name}' receiving mapped payload: ${JSON.stringify(Object.keys(mapped))}`);
2212
2493
  }
2213
2494
  }
2214
2495
  }
@@ -2218,12 +2499,12 @@ Please choose an alternative approach to complete your task.`,
2218
2499
  contextPaths = JSON.parse(relationship.SubAgentContextPaths);
2219
2500
  }
2220
2501
  catch (parseError) {
2221
- (0, global_1.LogError)(`Failed to parse SubAgentContextPaths for sub-agent ${subAgentRequest.name}: ${parseError.message}`);
2502
+ (0, core_1.LogError)(`Failed to parse SubAgentContextPaths for sub-agent ${subAgentRequest.name}: ${parseError.message}`);
2222
2503
  }
2223
2504
  }
2224
2505
  const contextMessage = this.prepareRelatedSubAgentContextMessage(previousDecision.newPayload, contextPaths);
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(', ')}`);
2506
+ if (contextMessage && (params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)())) {
2507
+ (0, core_1.LogStatus)(`Related sub-agent '${subAgentRequest.name}' receiving context from paths: ${contextPaths.join(', ')}`);
2227
2508
  }
2228
2509
  const subAgentResult = await this.ExecuteSubAgent(params, subAgentRequest, subAgentEntity, stepEntity, initialSubAgentPayload, contextMessage);
2229
2510
  let mergedPayload = previousDecision.newPayload;
@@ -2237,12 +2518,12 @@ Please choose an alternative approach to complete your task.`,
2237
2518
  analyzeChanges: true,
2238
2519
  generateDiff: true,
2239
2520
  agentName: `${subAgentRequest.name} (related agent mapping)`,
2240
- verbose: params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)(),
2521
+ verbose: params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)()
2241
2522
  });
2242
2523
  mergedPayload = mergeResult.result;
2243
2524
  currentStepPayloadChangeResult = this.buildPayloadChangeResultSummary(mergeResult);
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('; ')}`);
2525
+ if (mergeResult.warnings.length > 0 && (params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)())) {
2526
+ (0, core_1.LogStatus)(`Related sub-agent mapping warnings: ${mergeResult.warnings.join('; ')}`);
2246
2527
  }
2247
2528
  }
2248
2529
  }
@@ -2253,13 +2534,13 @@ Please choose an alternative approach to complete your task.`,
2253
2534
  finalStep: subAgentResult.agentRun?.FinalStep,
2254
2535
  errorMessage: subAgentResult.agentRun?.ErrorMessage,
2255
2536
  stepCount: subAgentResult.agentRun?.Steps?.length || 0,
2256
- hasMergedPayload: !!(relationship.SubAgentOutputMapping && mergedPayload !== previousDecision.newPayload),
2537
+ hasMergedPayload: !!(relationship.SubAgentOutputMapping && mergedPayload !== previousDecision.newPayload)
2257
2538
  },
2258
2539
  shouldTerminate: shouldTerminate,
2259
2540
  nextStep: shouldTerminate ? 'success' : 'retry',
2260
2541
  ...(currentStepPayloadChangeResult && {
2261
- payloadChangeResult: currentStepPayloadChangeResult,
2262
- }),
2542
+ payloadChangeResult: currentStepPayloadChangeResult
2543
+ })
2263
2544
  };
2264
2545
  if (stepEntity) {
2265
2546
  stepEntity.PayloadAtEnd = JSON.stringify(mergedPayload);
@@ -2271,7 +2552,7 @@ Please choose an alternative approach to complete your task.`,
2271
2552
  terminate: true,
2272
2553
  message: subAgentResult.agentRun?.Message || null,
2273
2554
  previousPayload: previousDecision?.newPayload,
2274
- newPayload: previousDecision?.newPayload,
2555
+ newPayload: previousDecision?.newPayload
2275
2556
  };
2276
2557
  }
2277
2558
  const subAgentSummary = {
@@ -2279,11 +2560,11 @@ Please choose an alternative approach to complete your task.`,
2279
2560
  subAgentName: subAgentRequest.name,
2280
2561
  success: subAgentResult.success,
2281
2562
  payload: subAgentResult.payload,
2282
- errorMessage: subAgentResult.agentRun?.ErrorMessage,
2563
+ errorMessage: subAgentResult.agentRun?.ErrorMessage
2283
2564
  };
2284
2565
  params.conversationMessages.push({
2285
2566
  role: 'user',
2286
- content: `Related sub-agent "${subAgentRequest.name}" completed:\n${JSON.stringify(subAgentSummary, null, 2)}`,
2567
+ content: `Related sub-agent "${subAgentRequest.name}" completed:\n${JSON.stringify(subAgentSummary, null, 2)}`
2287
2568
  });
2288
2569
  if (this._agentRun) {
2289
2570
  this._agentRun.FinalPayloadObject = mergedPayload;
@@ -2293,7 +2574,7 @@ Please choose an alternative approach to complete your task.`,
2293
2574
  step: subAgentResult.success ? 'Success' : 'Failed',
2294
2575
  terminate: shouldTerminate,
2295
2576
  previousPayload: previousDecision?.newPayload,
2296
- newPayload: mergedPayload,
2577
+ newPayload: mergedPayload
2297
2578
  };
2298
2579
  }
2299
2580
  catch (error) {
@@ -2305,7 +2586,7 @@ Please choose an alternative approach to complete your task.`,
2305
2586
  step: 'Failed',
2306
2587
  terminate: false,
2307
2588
  previousPayload: payload,
2308
- newPayload: payload,
2589
+ newPayload: payload
2309
2590
  };
2310
2591
  }
2311
2592
  }
@@ -2338,11 +2619,11 @@ Please choose an alternative approach to complete your task.`,
2338
2619
  return null;
2339
2620
  }
2340
2621
  return {
2341
- updateElements: updateObj,
2622
+ updateElements: updateObj
2342
2623
  };
2343
2624
  }
2344
2625
  catch (error) {
2345
- (0, global_1.LogError)(`Failed to parse SubAgentOutputMapping: ${error.message}`);
2626
+ (0, core_1.LogError)(`Failed to parse SubAgentOutputMapping: ${error.message}`);
2346
2627
  return null;
2347
2628
  }
2348
2629
  }
@@ -2377,7 +2658,7 @@ Please choose an alternative approach to complete your task.`,
2377
2658
  return subAgentPayload;
2378
2659
  }
2379
2660
  catch (error) {
2380
- (0, global_1.LogError)(`Failed to parse SubAgentInputMapping: ${error.message}`);
2661
+ (0, core_1.LogError)(`Failed to parse SubAgentInputMapping: ${error.message}`);
2381
2662
  return null;
2382
2663
  }
2383
2664
  }
@@ -2388,7 +2669,7 @@ Please choose an alternative approach to complete your task.`,
2388
2669
  if (contextPaths.includes('*')) {
2389
2670
  return {
2390
2671
  role: 'user',
2391
- content: `Parent Agent Context:\n\n${JSON.stringify(parentPayload, null, 2)}`,
2672
+ content: `Parent Agent Context:\n\n${JSON.stringify(parentPayload, null, 2)}`
2392
2673
  };
2393
2674
  }
2394
2675
  const contextData = {};
@@ -2402,12 +2683,14 @@ Please choose an alternative approach to complete your task.`,
2402
2683
  return null;
2403
2684
  }
2404
2685
  const contextLines = Object.entries(contextData).map(([key, value]) => {
2405
- const valueStr = typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value);
2686
+ const valueStr = typeof value === 'object'
2687
+ ? JSON.stringify(value, null, 2)
2688
+ : String(value);
2406
2689
  return `${key}:\n${valueStr}`;
2407
2690
  });
2408
2691
  return {
2409
2692
  role: 'user',
2410
- content: `Parent Agent Context:\n\n${contextLines.join('\n\n')}`,
2693
+ content: `Parent Agent Context:\n\n${contextLines.join('\n\n')}`
2411
2694
  };
2412
2695
  }
2413
2696
  async executeActionsStep(params, previousDecision, parentStepId, addConversationMessage = true) {
@@ -2435,23 +2718,19 @@ Please choose an alternative approach to complete your task.`,
2435
2718
  }
2436
2719
  }
2437
2720
  else {
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;
2721
+ progressMessage = `Executing **${actions.length} actions** in parallel:\n\n` + actions.map((aa, index) => {
2722
+ let actionText = `${index + 1}. **${aa.name}**`;
2723
+ if (aa.params && Object.keys(aa.params).length > 0) {
2724
+ const paramsList = Object.entries(aa.params)
2725
+ .map(([key, value]) => {
2726
+ const displayValue = this.formatParamValueForMessage(value);
2727
+ return ` • **${key}**: ${displayValue}`;
2453
2728
  })
2454
- .join('\n\n');
2729
+ .join('\n');
2730
+ actionText += `\n${paramsList}`;
2731
+ }
2732
+ return actionText;
2733
+ }).join('\n\n');
2455
2734
  }
2456
2735
  params.onProgress?.({
2457
2736
  step: 'action_execution',
@@ -2459,9 +2738,9 @@ Please choose an alternative approach to complete your task.`,
2459
2738
  message: this.formatHierarchicalMessage(progressMessage),
2460
2739
  metadata: {
2461
2740
  actionCount: actions.length,
2462
- actionNames: actions.map((a) => a.name),
2741
+ actionNames: actions.map(a => a.name)
2463
2742
  },
2464
- displayMode: 'live',
2743
+ displayMode: 'live'
2465
2744
  });
2466
2745
  let actionMessage;
2467
2746
  if (actions.length === 1) {
@@ -2481,61 +2760,48 @@ Please choose an alternative approach to complete your task.`,
2481
2760
  }
2482
2761
  }
2483
2762
  else {
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;
2763
+ actionMessage = `I'm executing **${actions.length} actions** in parallel:\n\n` + actions.map((aa, index) => {
2764
+ let actionText = `${index + 1}. **${aa.name}**`;
2765
+ if (aa.params && Object.keys(aa.params).length > 0) {
2766
+ const paramsList = Object.entries(aa.params)
2767
+ .map(([key, value]) => {
2768
+ const displayValue = this.formatParamValueForMessage(value);
2769
+ return ` • **${key}**: ${displayValue}`;
2499
2770
  })
2500
- .join('\n\n');
2771
+ .join('\n');
2772
+ actionText += `\n${paramsList}`;
2773
+ }
2774
+ return actionText;
2775
+ }).join('\n\n');
2501
2776
  }
2502
2777
  if (addConversationMessage) {
2503
2778
  params.conversationMessages.push({
2504
2779
  role: 'assistant',
2505
- content: actionMessage,
2780
+ content: actionMessage
2506
2781
  });
2507
2782
  }
2508
2783
  const actionEngine = actions_1.ActionEngineServer.Instance;
2509
- const agentActions = aiengine_1.AIEngine.Instance.AgentActions.filter((aa) => aa.AgentID === params.agent.ID);
2784
+ const agentActions = aiengine_1.AIEngine.Instance.AgentActions.filter(aa => aa.AgentID === params.agent.ID);
2510
2785
  try {
2511
2786
  const currentPayload = previousDecision?.newPayload || previousDecision?.previousPayload || params.payload;
2512
2787
  await this.AgentTypeInstance.PreProcessActionStep(actions, currentPayload, this.AgentTypeState, previousDecision);
2513
2788
  }
2514
2789
  catch (error) {
2515
- (0, global_1.LogError)(`Error in PreProcessActionStep: ${error.message}`);
2790
+ (0, core_1.LogError)(`Error in PreProcessActionStep: ${error.message}`);
2516
2791
  }
2517
2792
  let numActionsProcessed = 0;
2518
2793
  const baseStepNumber = (this._agentRun.Steps?.length || 0) + 1;
2519
2794
  let lastStep = undefined;
2520
2795
  const actionPromises = actions.map(async (aa) => {
2521
- const actionEntity = actionEngine.Actions.find((a) => a.Name === aa.name && agentActions.some((aa) => aa.ActionID === a.ID));
2796
+ const actionEntity = actionEngine.Actions.find(a => a.Name === aa.name && agentActions.some(aa => aa.ActionID === a.ID));
2522
2797
  if (!actionEntity) {
2523
2798
  throw new Error(`Action "${aa.name}" Not Found for Agent "${params.agent.Name}"`);
2524
2799
  }
2525
2800
  const actionInputData = {
2526
2801
  actionName: aa.name,
2527
- actionParams: aa.params,
2802
+ actionParams: aa.params
2528
2803
  };
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
- });
2804
+ 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 });
2539
2805
  lastStep = stepEntity;
2540
2806
  stepEntity.StepNumber = baseStepNumber + numActionsProcessed++;
2541
2807
  this.incrementExecutionCount(actionEntity.ID);
@@ -2551,8 +2817,8 @@ Please choose an alternative approach to complete your task.`,
2551
2817
  success: actionResult.Success,
2552
2818
  resultCode: actionResult.Result?.ResultCode,
2553
2819
  message: actionResult.Message,
2554
- parameters: actionResult.Params,
2555
- },
2820
+ parameters: actionResult.Params
2821
+ }
2556
2822
  };
2557
2823
  await this.finalizeStepEntity(stepEntity, actionResult.Success, actionResult.Success ? undefined : actionResult.Message, outputData);
2558
2824
  return { success: true, result: actionResult, action: aa, actionEntity, stepEntity };
@@ -2566,23 +2832,22 @@ Please choose an alternative approach to complete your task.`,
2566
2832
  if (params.cancellationToken?.aborted) {
2567
2833
  throw new Error('Cancelled after action execution');
2568
2834
  }
2569
- const actionSummaries = actionResults.map((result) => {
2835
+ const actionSummaries = actionResults.map(result => {
2570
2836
  const actionResult = result.success ? result.result : null;
2571
2837
  return {
2572
2838
  actionName: result.action.name,
2573
2839
  success: result.success,
2574
- params: result.result?.Params.filter((p) => p.Type === 'Both' || p.Type === 'Output'),
2840
+ params: result.result?.Params.filter(p => p.Type === 'Both' || p.Type === 'Output'),
2575
2841
  resultCode: actionResult?.Result?.ResultCode || (result.success ? 'SUCCESS' : 'ERROR'),
2576
- message: result.success ? actionResult?.Message || 'Action completed' : result.error,
2842
+ message: result.success ? actionResult?.Message || 'Action completed' : result.error
2577
2843
  };
2578
2844
  });
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)}`;
2845
+ const failedActions = actionSummaries.filter(a => !a.success);
2846
+ const resultsMessage = (failedActions.length > 0 ? `${failedActions.length} of ${actionSummaries.length} failed:` : `Action results:`) + `\n${JSON.stringify(actionSummaries, null, 2)}`;
2582
2847
  let metadata;
2583
2848
  const agentActionConfigs = actionResults
2584
- .map((r) => agentActions.find((aa) => aa.ActionID === r.actionEntity.ID))
2585
- .filter((aa) => aa != null);
2849
+ .map(r => agentActions.find(aa => aa.ActionID === r.actionEntity.ID))
2850
+ .filter(aa => aa != null);
2586
2851
  if (agentActionConfigs.length > 0) {
2587
2852
  let minExpirationTurns = null;
2588
2853
  let expirationMode = 'None';
@@ -2609,7 +2874,7 @@ Please choose an alternative approach to complete your task.`,
2609
2874
  expirationMode: expirationMode,
2610
2875
  compactMode: compactMode,
2611
2876
  compactLength: compactLength,
2612
- compactPromptId: compactPromptId,
2877
+ compactPromptId: compactPromptId
2613
2878
  };
2614
2879
  }
2615
2880
  }
@@ -2617,15 +2882,17 @@ Please choose an alternative approach to complete your task.`,
2617
2882
  params.conversationMessages.push({
2618
2883
  role: 'user',
2619
2884
  content: resultsMessage,
2620
- metadata: metadata,
2885
+ metadata: metadata
2621
2886
  });
2622
2887
  }
2623
2888
  let finalPayload = currentPayload;
2624
2889
  try {
2625
- const actionResultsOnly = actionResults.map((r) => r.result).filter((r) => r !== undefined);
2890
+ const actionResultsOnly = actionResults.map(r => r.result).filter(r => r !== undefined);
2626
2891
  const payloadChangeRequest = await this.AgentTypeInstance.PostProcessActionStep(actionResultsOnly, actions, currentPayload, this.AgentTypeState, previousDecision);
2627
2892
  if (payloadChangeRequest) {
2628
- const allowedPaths = params.agent.PayloadSelfWritePaths ? JSON.parse(params.agent.PayloadSelfWritePaths) : undefined;
2893
+ const allowedPaths = params.agent.PayloadSelfWritePaths
2894
+ ? JSON.parse(params.agent.PayloadSelfWritePaths)
2895
+ : undefined;
2629
2896
  const changeResult = this._payloadManager.applyAgentChangeRequest(currentPayload, payloadChangeRequest, {
2630
2897
  validateChanges: true,
2631
2898
  logChanges: true,
@@ -2633,20 +2900,20 @@ Please choose an alternative approach to complete your task.`,
2633
2900
  analyzeChanges: true,
2634
2901
  generateDiff: true,
2635
2902
  allowedPaths: allowedPaths,
2636
- verbose: params.verbose === true || (0, global_1.IsVerboseLoggingEnabled)(),
2903
+ verbose: params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)()
2637
2904
  });
2638
2905
  finalPayload = changeResult.result;
2639
2906
  if (lastStep) {
2640
2907
  lastStep.PayloadAtEnd = JSON.stringify(finalPayload);
2641
2908
  await lastStep.Save();
2642
2909
  }
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('; ')}`);
2910
+ if (changeResult.warnings.length > 0 && (params.verbose === true || (0, core_1.IsVerboseLoggingEnabled)())) {
2911
+ (0, core_1.LogStatus)(`Action post-processing payload warnings: ${changeResult.warnings.join('; ')}`);
2645
2912
  }
2646
2913
  }
2647
2914
  }
2648
2915
  catch (error) {
2649
- (0, global_1.LogError)(`Error in PostProcessActionStep: ${error.message}`);
2916
+ (0, core_1.LogError)(`Error in PostProcessActionStep: ${error.message}`);
2650
2917
  }
2651
2918
  return {
2652
2919
  terminate: false,
@@ -2655,8 +2922,8 @@ Please choose an alternative approach to complete your task.`,
2655
2922
  newPayload: finalPayload,
2656
2923
  priorStepResult: actionSummaries,
2657
2924
  retryReason: failedActions.length > 0
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`,
2925
+ ? `Processing results with ${failedActions.length} failed action(s): ${failedActions.map(a => a.actionName).join(', ')}`
2926
+ : `Analyzing results from ${actionSummaries.length} completed action(s) to formulate response`
2660
2927
  };
2661
2928
  }
2662
2929
  catch (e) {
@@ -2682,7 +2949,7 @@ Please choose an alternative approach to complete your task.`,
2682
2949
  confidence: previousDecision.confidence,
2683
2950
  previousPayload: previousDecision.previousPayload,
2684
2951
  newPayload: previousDecision.newPayload || previousDecision.previousPayload,
2685
- suggestedResponses: previousDecision.suggestedResponses,
2952
+ suggestedResponses: previousDecision.suggestedResponses
2686
2953
  };
2687
2954
  }
2688
2955
  async executeForEachLoop(params, config, previousDecision) {
@@ -2734,12 +3001,10 @@ Please choose an alternative approach to complete your task.`,
2734
3001
  return null;
2735
3002
  }
2736
3003
  validateActionInAgent(actionName) {
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());
3004
+ const aa = aiengine_1.AIEngine.Instance.AgentActions.filter(aa => aa.AgentID === this._agentRun.AgentID);
3005
+ let action = aa.filter(a => a.Agent?.trim().toLowerCase() === actionName.trim().toLowerCase());
2739
3006
  if (!action) {
2740
- const partialAction = aa.filter((a) => a.Agent?.trim()
2741
- .toLowerCase()
2742
- .includes(actionName.trim().toLowerCase() || ''));
3007
+ const partialAction = aa.filter(a => a.Agent?.trim().toLowerCase().includes(actionName.trim().toLowerCase() || ''));
2743
3008
  if (partialAction.length > 1) {
2744
3009
  return `Ambiguous action '${actionName}' specified`;
2745
3010
  }
@@ -2750,22 +3015,18 @@ Please choose an alternative approach to complete your task.`,
2750
3015
  return null;
2751
3016
  }
2752
3017
  validateSubAgentInAgent(subAgentName) {
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());
3018
+ const relatedAgents = aiengine_1.AIEngine.Instance.AgentRelationships.filter(ar => ar.AgentID === this._agentRun.AgentID);
3019
+ const childAgents = aiengine_1.AIEngine.Instance.Agents.filter(a => a.ParentID === this._agentRun.AgentID);
3020
+ let subAgent = relatedAgents.filter(ra => ra.SubAgent?.trim().toLowerCase() === subAgentName.trim().toLowerCase());
2756
3021
  if (subAgent.length === 0) {
2757
- subAgent = relatedAgents.filter((ra) => ra.SubAgent?.trim()
2758
- .toLowerCase()
2759
- .includes(subAgentName.trim().toLowerCase() || ''));
3022
+ subAgent = relatedAgents.filter(ra => ra.SubAgent?.trim().toLowerCase().includes(subAgentName.trim().toLowerCase() || ''));
2760
3023
  if (subAgent.length > 1) {
2761
3024
  return `Ambiguous sub-agent '${subAgentName}' specified`;
2762
3025
  }
2763
3026
  else if (subAgent.length === 0) {
2764
- let childAgent = childAgents.filter((ca) => ca.Name?.trim().toLowerCase() === subAgentName.trim().toLowerCase());
3027
+ let childAgent = childAgents.filter(ca => ca.Name?.trim().toLowerCase() === subAgentName.trim().toLowerCase());
2765
3028
  if (childAgent.length === 0) {
2766
- childAgent = childAgents.filter((ca) => ca.Name?.trim()
2767
- .toLowerCase()
2768
- .includes(subAgentName.trim().toLowerCase() || ''));
3029
+ childAgent = childAgents.filter(ca => ca.Name?.trim().toLowerCase().includes(subAgentName.trim().toLowerCase() || ''));
2769
3030
  if (childAgent.length > 1) {
2770
3031
  return `Ambiguous child agent '${subAgentName}' specified`;
2771
3032
  }
@@ -2780,7 +3041,9 @@ Please choose an alternative approach to complete your task.`,
2780
3041
  return null;
2781
3042
  }
2782
3043
  getCollectionFromPayload(payload, path) {
2783
- const cleanPath = path.toLowerCase().startsWith('payload.') ? path.substring(8) : path;
3044
+ const cleanPath = path.toLowerCase().startsWith('payload.')
3045
+ ? path.substring(8)
3046
+ : path;
2784
3047
  const value = this.getValueFromPath(payload, cleanPath);
2785
3048
  return Array.isArray(value) ? value : null;
2786
3049
  }
@@ -2790,7 +3053,7 @@ Please choose an alternative approach to complete your task.`,
2790
3053
  stepName: `ForEach: ${forEach.collectionPath} (${collection.length} items)`,
2791
3054
  contextUser: params.contextUser,
2792
3055
  inputData: { forEach, count: collection.length },
2793
- payloadAtStart: payload,
3056
+ payloadAtStart: payload
2794
3057
  });
2795
3058
  return stepEntity;
2796
3059
  }
@@ -2810,7 +3073,7 @@ Please choose an alternative approach to complete your task.`,
2810
3073
  const errors = [];
2811
3074
  for (let i = 0; i < Math.min(collection.length, maxIterations); i++) {
2812
3075
  if (i > 0 && forEach.delayBetweenIterationsMs) {
2813
- await new Promise((resolve) => setTimeout(resolve, forEach.delayBetweenIterationsMs));
3076
+ await new Promise(resolve => setTimeout(resolve, forEach.delayBetweenIterationsMs));
2814
3077
  }
2815
3078
  const iterResult = await this.executeSingleForEachIteration(forEach, collection[i], i, currentPayload, parentStepId, params, config);
2816
3079
  if (iterResult.error) {
@@ -2833,18 +3096,18 @@ Please choose an alternative approach to complete your task.`,
2833
3096
  const allResults = [];
2834
3097
  for (let batchIndex = 0; batchIndex < batches.length; batchIndex++) {
2835
3098
  const batch = batches[batchIndex];
2836
- const batchPromises = batch.map(({ item, index }) => this.executeSingleForEachIteration(forEach, item, index, initialPayload, parentStepId, params, config).then((iterResult) => ({
3099
+ const batchPromises = batch.map(({ item, index }) => this.executeSingleForEachIteration(forEach, item, index, initialPayload, parentStepId, params, config).then(iterResult => ({
2837
3100
  index,
2838
3101
  result: iterResult.result,
2839
3102
  error: iterResult.error,
2840
- payload: iterResult.payload,
3103
+ payload: iterResult.payload
2841
3104
  })));
2842
3105
  const batchResults = await Promise.all(batchPromises);
2843
3106
  allResults.push(...batchResults);
2844
3107
  if (forEach.delayBetweenIterationsMs && batchIndex < batches.length - 1) {
2845
- await new Promise((resolve) => setTimeout(resolve, forEach.delayBetweenIterationsMs));
3108
+ await new Promise(resolve => setTimeout(resolve, forEach.delayBetweenIterationsMs));
2846
3109
  }
2847
- const hasFailure = batchResults.some((r) => r.error);
3110
+ const hasFailure = batchResults.some(r => r.error);
2848
3111
  if (hasFailure && !forEach.continueOnError) {
2849
3112
  break;
2850
3113
  }
@@ -2857,7 +3120,7 @@ Please choose an alternative approach to complete your task.`,
2857
3120
  for (let i = 0; i < items.length; i += maxConcurrency) {
2858
3121
  const batch = items.slice(i, i + maxConcurrency).map((item, batchOffset) => ({
2859
3122
  item,
2860
- index: i + batchOffset,
3123
+ index: i + batchOffset
2861
3124
  }));
2862
3125
  batches.push(batch);
2863
3126
  }
@@ -2883,51 +3146,27 @@ Please choose an alternative approach to complete your task.`,
2883
3146
  }
2884
3147
  async executeSingleForEachIteration(forEach, item, index, currentPayload, parentStepId, params, config) {
2885
3148
  try {
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
- });
3149
+ const beforeHook = this.AgentTypeInstance.BeforeLoopIteration?.({ item, itemVariable: forEach.itemVariable, index, payload: currentPayload, loopType: 'ForEach', actionParams: forEach.action?.params || {} });
2894
3150
  const resolvedParams = beforeHook?.actionParams || forEach.action?.params || {};
2895
3151
  let result;
2896
3152
  if (forEach.action) {
2897
3153
  const matchedAction = this.findAgentActionForLoop(forEach.action.name, params.agent.ID, params.agent.Name, params);
2898
3154
  const resolvedAction = {
2899
3155
  name: matchedAction.Action,
2900
- params: resolvedParams,
2901
- };
2902
- const actionStep = {
2903
- step: 'Actions',
2904
- actions: [resolvedAction],
2905
- newPayload: currentPayload,
2906
- previousPayload: currentPayload,
2907
- terminate: false,
3156
+ params: resolvedParams
2908
3157
  };
3158
+ const actionStep = { step: 'Actions', actions: [resolvedAction], newPayload: currentPayload, previousPayload: currentPayload, terminate: false };
2909
3159
  result = await this.executeActionsStep(params, actionStep, parentStepId, false);
2910
3160
  }
2911
3161
  else if (forEach.subAgent) {
2912
- const subAgentStep = {
2913
- step: 'Sub-Agent',
2914
- subAgent: forEach.subAgent,
2915
- newPayload: currentPayload,
2916
- previousPayload: currentPayload,
2917
- };
3162
+ const subAgentStep = { step: 'Sub-Agent', subAgent: forEach.subAgent, newPayload: currentPayload, previousPayload: currentPayload };
2918
3163
  result = await this.processSubAgentStep(params, subAgentStep);
2919
3164
  }
2920
3165
  else {
2921
3166
  throw new Error('ForEach missing action/subAgent');
2922
3167
  }
2923
3168
  const iterPayload = result.newPayload || currentPayload;
2924
- const afterHook = this.AgentTypeInstance.AfterLoopIteration?.({
2925
- currentPayload: iterPayload,
2926
- item,
2927
- itemVariable: forEach.itemVariable,
2928
- index,
2929
- loopContext: { actionOutputMapping: forEach.action?.outputMapping },
2930
- });
3169
+ const afterHook = this.AgentTypeInstance.AfterLoopIteration?.({ currentPayload: iterPayload, item, itemVariable: forEach.itemVariable, index, loopContext: { actionOutputMapping: forEach.action?.outputMapping } });
2931
3170
  return { payload: afterHook || iterPayload, result };
2932
3171
  }
2933
3172
  catch (error) {
@@ -2945,31 +3184,31 @@ Please choose an alternative approach to complete your task.`,
2945
3184
  retryInstructions: `Completed ForEach loop request using collection at '${forEach.collectionPath}'`,
2946
3185
  terminate: false,
2947
3186
  newPayload: loopResults.finalPayload,
2948
- previousPayload: previousDecision.previousPayload,
3187
+ previousPayload: previousDecision.previousPayload
2949
3188
  };
2950
3189
  }
2951
3190
  injectLoopResultsMessage(loopType, collectionOrCondition, results, errors, params) {
2952
- const extractedResults = results.map((r) => r.priorStepResult);
3191
+ const extractedResults = results.map(r => r.priorStepResult);
2953
3192
  const label = loopType === 'ForEach' ? 'Collection' : 'Condition';
2954
3193
  params.conversationMessages.push({
2955
3194
  role: 'user',
2956
3195
  content: `## Loop Completed\n**Type:** ${loopType}\n**${label}:** ${collectionOrCondition}\n` +
2957
3196
  `**Processed:** ${results.length}, **Errors:** ${errors.length}\n\n` +
2958
3197
  `**Results:**\n\`\`\`json\n${JSON.stringify(extractedResults, null, 2)}\n\`\`\``,
2959
- metadata: { _temporary: true, _loopResults: true },
3198
+ metadata: { _temporary: true, _loopResults: true }
2960
3199
  });
2961
3200
  }
2962
3201
  findAgentActionForLoop(actionName, agentId, agentName, params) {
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());
3202
+ const agentActions = aiengine_1.AIEngine.Instance.AgentActions.filter(aa => aa.AgentID === agentId && aa.Status === 'Active');
3203
+ let matched = agentActions.find(aa => aa.Action.trim().toLowerCase() === actionName.trim().toLowerCase());
2965
3204
  if (!matched) {
2966
- const containsMatches = agentActions.filter((aa) => aa.Action.trim().toLowerCase().includes(actionName.trim().toLowerCase()));
3205
+ const containsMatches = agentActions.filter(aa => aa.Action.trim().toLowerCase().includes(actionName.trim().toLowerCase()));
2967
3206
  if (containsMatches.length === 1) {
2968
3207
  matched = containsMatches[0];
2969
3208
  this.logStatus(`Action fuzzy matched: '${actionName}' → '${matched.Action}'`, true, params);
2970
3209
  }
2971
3210
  else if (containsMatches.length > 1) {
2972
- throw new Error(`Ambiguous action '${actionName}'. Matches: ${containsMatches.map((a) => a.Action).join(', ')}`);
3211
+ throw new Error(`Ambiguous action '${actionName}'. Matches: ${containsMatches.map(a => a.Action).join(', ')}`);
2973
3212
  }
2974
3213
  else {
2975
3214
  throw new Error(`Action '${actionName}' not found for agent '${agentName}'`);
@@ -2983,7 +3222,7 @@ Please choose an alternative approach to complete your task.`,
2983
3222
  terminate: false,
2984
3223
  errorMessage,
2985
3224
  previousPayload: previousDecision.previousPayload,
2986
- newPayload: previousDecision.newPayload || previousDecision.previousPayload,
3225
+ newPayload: previousDecision.newPayload || previousDecision.previousPayload
2987
3226
  };
2988
3227
  }
2989
3228
  async executeWhileLoop(params, config, previousDecision) {
@@ -3006,7 +3245,7 @@ Please choose an alternative approach to complete your task.`,
3006
3245
  stepName: `While: ${whileOp.condition}`,
3007
3246
  contextUser: params.contextUser,
3008
3247
  inputData: { while: whileOp },
3009
- payloadAtStart: payload,
3248
+ payloadAtStart: payload
3010
3249
  });
3011
3250
  return stepEntity;
3012
3251
  }
@@ -3020,7 +3259,7 @@ Please choose an alternative approach to complete your task.`,
3020
3259
  const evaluator = new SafeExpressionEvaluator();
3021
3260
  while (iterationCount < maxIterations) {
3022
3261
  if (iterationCount > 0 && whileOp.delayBetweenIterationsMs) {
3023
- await new Promise((resolve) => setTimeout(resolve, whileOp.delayBetweenIterationsMs));
3262
+ await new Promise(resolve => setTimeout(resolve, whileOp.delayBetweenIterationsMs));
3024
3263
  }
3025
3264
  const evalResult = evaluator.evaluate(whileOp.condition, { payload: currentPayload, results, errors });
3026
3265
  if (!evalResult.success || !evalResult.value) {
@@ -3043,51 +3282,27 @@ Please choose an alternative approach to complete your task.`,
3043
3282
  }
3044
3283
  async executeSingleWhileIteration(whileOp, attemptContext, index, currentPayload, parentStepId, params, config) {
3045
3284
  try {
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
- });
3285
+ const beforeHook = this.AgentTypeInstance.BeforeLoopIteration?.({ item: attemptContext, index, itemVariable: whileOp.itemVariable, payload: currentPayload, loopType: 'While', actionParams: whileOp.action?.params || {} });
3054
3286
  const resolvedParams = beforeHook?.actionParams || whileOp.action?.params || {};
3055
3287
  let result;
3056
3288
  if (whileOp.action) {
3057
3289
  const matchedAction = this.findAgentActionForLoop(whileOp.action.name, params.agent.ID, params.agent.Name, params);
3058
3290
  const resolvedAction = {
3059
3291
  name: matchedAction.Action,
3060
- params: resolvedParams,
3061
- };
3062
- const actionStep = {
3063
- step: 'Actions',
3064
- actions: [resolvedAction],
3065
- newPayload: currentPayload,
3066
- previousPayload: currentPayload,
3067
- terminate: false,
3292
+ params: resolvedParams
3068
3293
  };
3294
+ const actionStep = { step: 'Actions', actions: [resolvedAction], newPayload: currentPayload, previousPayload: currentPayload, terminate: false };
3069
3295
  result = await this.executeActionsStep(params, actionStep, parentStepId, false);
3070
3296
  }
3071
3297
  else if (whileOp.subAgent) {
3072
- const subAgentStep = {
3073
- step: 'Sub-Agent',
3074
- subAgent: whileOp.subAgent,
3075
- newPayload: currentPayload,
3076
- previousPayload: currentPayload,
3077
- };
3298
+ const subAgentStep = { step: 'Sub-Agent', subAgent: whileOp.subAgent, newPayload: currentPayload, previousPayload: currentPayload };
3078
3299
  result = await this.processSubAgentStep(params, subAgentStep);
3079
3300
  }
3080
3301
  else {
3081
3302
  throw new Error('While missing action/subAgent');
3082
3303
  }
3083
3304
  const iterPayload = result.newPayload || currentPayload;
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
- });
3305
+ const afterHook = this.AgentTypeInstance.AfterLoopIteration?.({ currentPayload: iterPayload, item: attemptContext, itemVariable: whileOp.itemVariable, index, loopContext: { actionOutputMapping: whileOp.action?.outputMapping } });
3091
3306
  return { payload: afterHook || iterPayload, result };
3092
3307
  }
3093
3308
  catch (error) {
@@ -3105,7 +3320,7 @@ Please choose an alternative approach to complete your task.`,
3105
3320
  retryInstructions: `Completed While loop request using condition '${whileOp.condition}' after ${loopResults.iterations} iteration(s)`,
3106
3321
  terminate: false,
3107
3322
  newPayload: loopResults.finalPayload,
3108
- previousPayload: previousDecision.previousPayload,
3323
+ previousPayload: previousDecision.previousPayload
3109
3324
  };
3110
3325
  }
3111
3326
  async createFailureResult(errorMessage, contextUser) {
@@ -3123,7 +3338,7 @@ Please choose an alternative approach to complete your task.`,
3123
3338
  }
3124
3339
  return {
3125
3340
  success: false,
3126
- agentRun: this._agentRun,
3341
+ agentRun: this._agentRun
3127
3342
  };
3128
3343
  }
3129
3344
  async createCancelledResult(message, contextUser) {
@@ -3141,7 +3356,7 @@ Please choose an alternative approach to complete your task.`,
3141
3356
  }
3142
3357
  return {
3143
3358
  success: false,
3144
- agentRun: this._agentRun,
3359
+ agentRun: this._agentRun
3145
3360
  };
3146
3361
  }
3147
3362
  async finalizeAgentRun(finalStep, payload, contextUser) {
@@ -3169,7 +3384,7 @@ Please choose an alternative approach to complete your task.`,
3169
3384
  this._agentRun.TotalCost = tokenStats.totalCost;
3170
3385
  const ok = await this._agentRun.Save();
3171
3386
  if (!ok) {
3172
- (0, global_1.LogError)(`Failed to finalize agent run ${this._agentRun.ID}`);
3387
+ (0, core_1.LogError)(`Failed to finalize agent run ${this._agentRun.ID}`);
3173
3388
  }
3174
3389
  }
3175
3390
  return {
@@ -3177,6 +3392,9 @@ Please choose an alternative approach to complete your task.`,
3177
3392
  payload,
3178
3393
  agentRun: this._agentRun,
3179
3394
  suggestedResponses: finalStep.suggestedResponses,
3395
+ memoryContext: this._injectedMemory.notes.length > 0 || this._injectedMemory.examples.length > 0
3396
+ ? this._injectedMemory
3397
+ : undefined
3180
3398
  };
3181
3399
  }
3182
3400
  calculateTokenStats() {
@@ -3217,14 +3435,18 @@ Please choose an alternative approach to complete your task.`,
3217
3435
  }
3218
3436
  async checkMinimumExecutionRequirements(agent, agentRun) {
3219
3437
  const violations = [];
3220
- const agentActions = aiengine_1.AIEngine.Instance.AgentActions.filter((aa) => aa.AgentID === agent.ID && aa.Status === 'Active' && aa.MinExecutionsPerRun != null && aa.MinExecutionsPerRun > 0);
3438
+ const agentActions = aiengine_1.AIEngine.Instance.AgentActions.filter(aa => aa.AgentID === agent.ID &&
3439
+ aa.Status === 'Active' &&
3440
+ aa.MinExecutionsPerRun != null &&
3441
+ aa.MinExecutionsPerRun > 0);
3221
3442
  for (const agentAction of agentActions) {
3222
3443
  const executionCount = await this.getActionExecutionCount(agentRun.ID, agentAction.ActionID);
3223
3444
  if (executionCount < agentAction.MinExecutionsPerRun) {
3224
3445
  violations.push(`Action '${agentAction.Action}' requires ${agentAction.MinExecutionsPerRun} execution(s) but was executed ${executionCount} time(s)`);
3225
3446
  }
3226
3447
  }
3227
- const subAgents = aiengine_1.AIEngine.Instance.GetSubAgents(agent.ID, 'Active').filter((a) => a.MinExecutionsPerRun != null && a.MinExecutionsPerRun > 0);
3448
+ const subAgents = aiengine_1.AIEngine.Instance.GetSubAgents(agent.ID, "Active").filter(a => a.MinExecutionsPerRun != null &&
3449
+ a.MinExecutionsPerRun > 0);
3228
3450
  for (const subAgent of subAgents) {
3229
3451
  const executionCount = await this.getSubAgentExecutionCount(agentRun.ID, subAgent.ID);
3230
3452
  if (executionCount < subAgent.MinExecutionsPerRun) {
@@ -3255,7 +3477,7 @@ Please choose an alternative approach to complete your task.`,
3255
3477
  turn: currentTurn,
3256
3478
  messageIndex: i,
3257
3479
  message: msg,
3258
- reason: `Expired after ${turnsAlive} turns (limit: ${msg.metadata.expirationTurns})`,
3480
+ reason: `Expired after ${turnsAlive} turns (limit: ${msg.metadata.expirationTurns})`
3259
3481
  });
3260
3482
  }
3261
3483
  else if (msg.metadata.expirationMode === 'Compact') {
@@ -3267,8 +3489,10 @@ Please choose an alternative approach to complete your task.`,
3267
3489
  compactMode: msg.metadata.compactMode,
3268
3490
  compactLength: msg.metadata.compactLength || 500,
3269
3491
  compactPromptId: msg.metadata.compactPromptId || '',
3270
- originalLength: typeof msg.content === 'string' ? msg.content.length : JSON.stringify(msg.content).length,
3271
- },
3492
+ originalLength: typeof msg.content === 'string'
3493
+ ? msg.content.length
3494
+ : JSON.stringify(msg.content).length
3495
+ }
3272
3496
  });
3273
3497
  }
3274
3498
  }
@@ -3290,8 +3514,8 @@ Please choose an alternative approach to complete your task.`,
3290
3514
  originalContent: preserveOriginal ? originalContent : undefined,
3291
3515
  originalLength: item.metadata.originalLength,
3292
3516
  tokensSaved,
3293
- canExpand: preserveOriginal,
3294
- },
3517
+ canExpand: preserveOriginal
3518
+ }
3295
3519
  };
3296
3520
  this.emitMessageLifecycleEvent({
3297
3521
  type: 'message-compacted',
@@ -3299,7 +3523,7 @@ Please choose an alternative approach to complete your task.`,
3299
3523
  messageIndex: item.index,
3300
3524
  message: params.conversationMessages[item.index],
3301
3525
  reason: `Compacted using ${item.metadata.compactMode} (saved ${tokensSaved} tokens)`,
3302
- tokensSaved,
3526
+ tokensSaved
3303
3527
  });
3304
3528
  }
3305
3529
  for (let i = messagesToRemove.length - 1; i >= 0; i--) {
@@ -3310,7 +3534,7 @@ Please choose an alternative approach to complete your task.`,
3310
3534
  turn: currentTurn,
3311
3535
  messageIndex: index,
3312
3536
  message: removed,
3313
- reason: 'Removed due to expiration',
3537
+ reason: 'Removed due to expiration'
3314
3538
  });
3315
3539
  }
3316
3540
  if (params.verbose && (messagesToCompact.length > 0 || messagesToRemove.length > 0)) {
@@ -3327,7 +3551,7 @@ Please choose an alternative approach to complete your task.`,
3327
3551
  if (!this._agentRun) {
3328
3552
  throw new Error('Cannot create compaction step: agent run not initialized');
3329
3553
  }
3330
- const md = new global_1.Metadata();
3554
+ const md = new core_1.Metadata();
3331
3555
  const step = await md.GetEntityObject('MJ: AI Agent Run Steps', params.contextUser);
3332
3556
  step.NewRecord();
3333
3557
  step.AgentRunID = this._agentRun.ID;
@@ -3342,7 +3566,7 @@ Please choose an alternative approach to complete your task.`,
3342
3566
  (typeof message.content === 'string' ? message.content.length : JSON.stringify(message.content).length),
3343
3567
  compactMode: 'AI Summary',
3344
3568
  promptId: prompt.ID,
3345
- promptName: prompt.Name,
3569
+ promptName: prompt.Name
3346
3570
  });
3347
3571
  await step.Save();
3348
3572
  return step;
@@ -3358,7 +3582,7 @@ Please choose an alternative approach to complete your task.`,
3358
3582
  promptTokens,
3359
3583
  completionTokens,
3360
3584
  totalTokens: promptTokens + completionTokens,
3361
- cost: result.cost,
3585
+ cost: result.cost
3362
3586
  });
3363
3587
  if (!result.success) {
3364
3588
  step.ErrorMessage = result.errorMessage || 'AI Summary compaction failed';
@@ -3366,7 +3590,9 @@ Please choose an alternative approach to complete your task.`,
3366
3590
  await step.Save();
3367
3591
  }
3368
3592
  async compactMessage(message, metadata, params) {
3369
- const originalContent = typeof message.content === 'string' ? message.content : JSON.stringify(message.content);
3593
+ const originalContent = typeof message.content === 'string'
3594
+ ? message.content
3595
+ : JSON.stringify(message.content);
3370
3596
  switch (metadata.compactMode) {
3371
3597
  case 'First N Chars': {
3372
3598
  const length = metadata.compactLength;
@@ -3379,7 +3605,7 @@ Please choose an alternative approach to complete your task.`,
3379
3605
  case 'AI Summary': {
3380
3606
  try {
3381
3607
  const promptId = metadata.compactPromptId || this.getSystemDefaultCompactPromptId();
3382
- const prompt = aiengine_1.AIEngine.Instance.Prompts.find((p) => p.ID === promptId);
3608
+ const prompt = aiengine_1.AIEngine.Instance.Prompts.find(p => p.ID === promptId);
3383
3609
  if (!prompt) {
3384
3610
  console.warn(`Compact prompt ${promptId} not found, falling back to First N Chars`);
3385
3611
  return this.compactMessage(message, { ...metadata, compactMode: 'First N Chars' }, params);
@@ -3392,7 +3618,7 @@ Please choose an alternative approach to complete your task.`,
3392
3618
  originalLength: metadata.originalLength,
3393
3619
  targetLength: metadata.compactLength || 500,
3394
3620
  messageType: message.metadata?.messageType || 'unknown',
3395
- turnAdded: message.metadata?.turnAdded || 0,
3621
+ turnAdded: message.metadata?.turnAdded || 0
3396
3622
  };
3397
3623
  promptParams.contextUser = params.contextUser;
3398
3624
  const runner = new ai_prompts_1.AIPromptRunner();
@@ -3414,16 +3640,72 @@ Please choose an alternative approach to complete your task.`,
3414
3640
  }
3415
3641
  }
3416
3642
  getSystemDefaultCompactPromptId() {
3417
- const prompt = aiengine_1.AIEngine.Instance.Prompts.find((p) => p.Name === 'Compact Agent Message');
3643
+ const prompt = aiengine_1.AIEngine.Instance.Prompts.find(p => p.Name === 'Compact Agent Message');
3418
3644
  if (!prompt) {
3419
3645
  console.warn('System default compact prompt not found. Ensure "Compact Agent Message" prompt exists.');
3420
3646
  return '';
3421
3647
  }
3422
3648
  return prompt.ID;
3423
3649
  }
3424
- estimateTokens(content) {
3425
- const text = typeof content === 'string' ? content : JSON.stringify(content);
3426
- return Math.ceil(text.length / 4);
3650
+ estimateTokens(content, modelName) {
3651
+ const text = typeof content === 'string'
3652
+ ? content
3653
+ : JSON.stringify(content);
3654
+ return this.heuristicTokenCount(text);
3655
+ }
3656
+ heuristicTokenCount(text) {
3657
+ const charCount = text.length;
3658
+ const structuralChars = (text.match(/[\{\}\[\],:]/g) || []).length;
3659
+ const whitespaceChars = (text.match(/\s/g) || []).length;
3660
+ const effectiveChars = charCount - (whitespaceChars * 0.5);
3661
+ const baseTokens = effectiveChars / 4;
3662
+ const structuralTokens = structuralChars * 0.05;
3663
+ return Math.ceil(baseTokens + structuralTokens);
3664
+ }
3665
+ getModelContextLimit(modelSelectionInfo) {
3666
+ const DEFAULT_LIMIT = 8000;
3667
+ if (!modelSelectionInfo) {
3668
+ this.logStatus(`No model selection info available, using default limit: ${DEFAULT_LIMIT}`, true);
3669
+ return DEFAULT_LIMIT;
3670
+ }
3671
+ try {
3672
+ const modelSelected = modelSelectionInfo.modelSelected;
3673
+ const vendorSelected = modelSelectionInfo.vendorSelected;
3674
+ if (!modelSelected) {
3675
+ this.logStatus(`No model selected in model selection info, using default limit: ${DEFAULT_LIMIT}`, true);
3676
+ return DEFAULT_LIMIT;
3677
+ }
3678
+ if (!vendorSelected) {
3679
+ this.logStatus(`No vendor selected, using default limit: ${DEFAULT_LIMIT}`, true);
3680
+ return DEFAULT_LIMIT;
3681
+ }
3682
+ const modelVendors = modelSelected.ModelVendors;
3683
+ if (!modelVendors || modelVendors.length === 0) {
3684
+ this.logStatus(`No ModelVendors array found on model, using default limit: ${DEFAULT_LIMIT}`, true);
3685
+ return DEFAULT_LIMIT;
3686
+ }
3687
+ const vendorEntry = modelVendors.find((mv) => mv.VendorID === vendorSelected.ID);
3688
+ if (!vendorEntry) {
3689
+ this.logStatus(`No matching vendor entry found in ModelVendors, using default limit: ${DEFAULT_LIMIT}`, true);
3690
+ return DEFAULT_LIMIT;
3691
+ }
3692
+ const maxInputTokens = vendorEntry.MaxInputTokens;
3693
+ if (!maxInputTokens || maxInputTokens <= 0) {
3694
+ this.logStatus(`MaxInputTokens not set or invalid on vendor entry, using default limit: ${DEFAULT_LIMIT}`, true);
3695
+ return DEFAULT_LIMIT;
3696
+ }
3697
+ this.logStatus(`Using vendor-specific MaxInputTokens: ${maxInputTokens} (Model: ${modelSelected.Name}, Vendor: ${vendorSelected.Name})`, true);
3698
+ return maxInputTokens;
3699
+ }
3700
+ catch (error) {
3701
+ this.logStatus(`Error extracting model context limit: ${error}, using default limit: ${DEFAULT_LIMIT}`, true);
3702
+ return DEFAULT_LIMIT;
3703
+ }
3704
+ }
3705
+ estimateConversationTokens(messages) {
3706
+ return messages.reduce((total, msg) => {
3707
+ return total + this.estimateTokens(msg.content);
3708
+ }, 0);
3427
3709
  }
3428
3710
  emitMessageLifecycleEvent(event) {
3429
3711
  if (this._messageLifecycleCallback) {
@@ -3451,7 +3733,7 @@ Please choose an alternative approach to complete your task.`,
3451
3733
  turn: currentTurn,
3452
3734
  messageIndex,
3453
3735
  message,
3454
- reason: reason || 'Agent requested expansion',
3736
+ reason: reason || 'Agent requested expansion'
3455
3737
  });
3456
3738
  if (params.verbose) {
3457
3739
  console.log(`[Turn ${currentTurn}] Expanded message at index ${messageIndex}`);