@memberjunction/ai-agents 6.2.0-edge.6 → 6.2.0-edge.7

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 (105) hide show
  1. package/README.md +29 -2
  2. package/dist/AgentRunner.d.ts +96 -3
  3. package/dist/AgentRunner.d.ts.map +1 -1
  4. package/dist/AgentRunner.js +438 -34
  5. package/dist/AgentRunner.js.map +1 -1
  6. package/dist/AgentWakeTriggerService.d.ts.map +1 -1
  7. package/dist/AgentWakeTriggerService.js +8 -1
  8. package/dist/AgentWakeTriggerService.js.map +1 -1
  9. package/dist/MJAIAgentRequestEntityServer.d.ts +15 -1
  10. package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
  11. package/dist/MJAIAgentRequestEntityServer.js +43 -3
  12. package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
  13. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  14. package/dist/agent-pre-execution-rag.js +1 -0
  15. package/dist/agent-pre-execution-rag.js.map +1 -1
  16. package/dist/agent-run-watchdog.d.ts +51 -13
  17. package/dist/agent-run-watchdog.d.ts.map +1 -1
  18. package/dist/agent-run-watchdog.js +89 -21
  19. package/dist/agent-run-watchdog.js.map +1 -1
  20. package/dist/agent-types/flow-agent-type.d.ts +6 -0
  21. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  22. package/dist/agent-types/flow-agent-type.js +70 -6
  23. package/dist/agent-types/flow-agent-type.js.map +1 -1
  24. package/dist/agent-types/loop-agent-prompt-params.d.ts +26 -3
  25. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  26. package/dist/agent-types/loop-agent-prompt-params.js +5 -3
  27. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  28. package/dist/agent-types/loop-agent-response-type.d.ts +35 -4
  29. package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
  30. package/dist/agent-types/loop-agent-response-type.js +1 -1
  31. package/dist/agent-types/loop-agent-response-type.js.map +1 -1
  32. package/dist/agent-types/loop-agent-type.d.ts +27 -4
  33. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  34. package/dist/agent-types/loop-agent-type.js +121 -18
  35. package/dist/agent-types/loop-agent-type.js.map +1 -1
  36. package/dist/base-agent.d.ts +306 -33
  37. package/dist/base-agent.d.ts.map +1 -1
  38. package/dist/base-agent.js +1733 -366
  39. package/dist/base-agent.js.map +1 -1
  40. package/dist/catalog-narrowing.d.ts.map +1 -1
  41. package/dist/catalog-narrowing.js +6 -3
  42. package/dist/catalog-narrowing.js.map +1 -1
  43. package/dist/handoff-target.d.ts +80 -0
  44. package/dist/handoff-target.d.ts.map +1 -0
  45. package/dist/handoff-target.js +158 -0
  46. package/dist/handoff-target.js.map +1 -0
  47. package/dist/index.d.ts +2 -0
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +2 -0
  50. package/dist/index.js.map +1 -1
  51. package/dist/memory-manager-agent.d.ts.map +1 -1
  52. package/dist/memory-manager-agent.js +2 -0
  53. package/dist/memory-manager-agent.js.map +1 -1
  54. package/dist/native-tools/action-tool-builder.d.ts +6 -0
  55. package/dist/native-tools/action-tool-builder.d.ts.map +1 -1
  56. package/dist/native-tools/action-tool-builder.js +21 -5
  57. package/dist/native-tools/action-tool-builder.js.map +1 -1
  58. package/dist/native-tools/control-tools.d.ts +15 -4
  59. package/dist/native-tools/control-tools.d.ts.map +1 -1
  60. package/dist/native-tools/control-tools.js +31 -14
  61. package/dist/native-tools/control-tools.js.map +1 -1
  62. package/dist/pipeline/pipeline-registry.d.ts +5 -12
  63. package/dist/pipeline/pipeline-registry.d.ts.map +1 -1
  64. package/dist/pipeline/pipeline-registry.js +28 -2
  65. package/dist/pipeline/pipeline-registry.js.map +1 -1
  66. package/dist/pipeline/providers/serialize.d.ts +7 -3
  67. package/dist/pipeline/providers/serialize.d.ts.map +1 -1
  68. package/dist/pipeline/providers/serialize.js +9 -5
  69. package/dist/pipeline/providers/serialize.js.map +1 -1
  70. package/dist/realtime/bridge-room-transcript-sink.js +2 -0
  71. package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
  72. package/dist/realtime/realtime-client-session-service.d.ts +22 -2
  73. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  74. package/dist/realtime/realtime-client-session-service.js +70 -10
  75. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  76. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  77. package/dist/realtime/realtime-coagent-config.js +2 -28
  78. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  79. package/dist/realtime/realtime-recording-capture.d.ts +1 -0
  80. package/dist/realtime/realtime-recording-capture.d.ts.map +1 -1
  81. package/dist/realtime/realtime-recording-capture.js +17 -3
  82. package/dist/realtime/realtime-recording-capture.js.map +1 -1
  83. package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -1
  84. package/dist/realtime/realtime-recording-opus-assembly.js +9 -4
  85. package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -1
  86. package/dist/realtime/realtime-session-runner.d.ts.map +1 -1
  87. package/dist/realtime/realtime-session-runner.js +5 -7
  88. package/dist/realtime/realtime-session-runner.js.map +1 -1
  89. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  90. package/dist/realtime/realtime-turn-moderator.js +1 -0
  91. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  92. package/dist/rubric-evaluation-agent-runner.js +1 -0
  93. package/dist/rubric-evaluation-agent-runner.js.map +1 -1
  94. package/dist/runtime-state-fragment.d.ts.map +1 -1
  95. package/dist/runtime-state-fragment.js +3 -0
  96. package/dist/runtime-state-fragment.js.map +1 -1
  97. package/dist/sub-agent-consult.d.ts +75 -0
  98. package/dist/sub-agent-consult.d.ts.map +1 -0
  99. package/dist/sub-agent-consult.js +193 -0
  100. package/dist/sub-agent-consult.js.map +1 -0
  101. package/dist/volatile-child-prompt.d.ts +7 -0
  102. package/dist/volatile-child-prompt.d.ts.map +1 -1
  103. package/dist/volatile-child-prompt.js +8 -0
  104. package/dist/volatile-child-prompt.js.map +1 -1
  105. package/package.json +20 -20
@@ -26,9 +26,10 @@ import { AgentRunWatchdog } from './agent-run-watchdog.js';
26
26
  import { AIPromptRunner, GetToolCallingDecision, GetSentPrefixFingerprint } from '@memberjunction/ai-prompts';
27
27
  import { BaseLLM, BaseRealtimeModel, GetAIAPIKey, CredentialScopeAllows, MakeAIAPIKeyResolver, IsPrefixPromptCache } from '@memberjunction/ai';
28
28
  import { BaseAgentType } from './agent-types/base-agent-type.js';
29
+ import { LoopAgentType } from './agent-types/loop-agent-type.js';
29
30
  import { ProviderRubricEngine } from '@memberjunction/rubrics';
30
31
  import { ExecuteSelfCheck, PickSelfCheckLink } from './self-check.js';
31
- import { CopyScalarsAndArrays, JSONValidator, MJGlobal, NormalizeUUID, SafeExpressionEvaluator, UUIDsEqual, UUIDSet, EscapeSQLString, IsPlainObject, CleanAndParseJSON, IsValidUUID, IndexByUUID } from '@memberjunction/global';
32
+ import { CopyScalarsAndArrays, GroupByUUID, IndexByUUID, JSONValidator, MJGlobal, NormalizeUUID, SafeExpressionEvaluator, UUIDsEqual, UUIDSet, EscapeSQLString, IsPlainObject, CleanAndParseJSON, IsValidUUID } from '@memberjunction/global';
32
33
  // token optimization via @memberjunction/context-crush (SmartCrusher/CacheAligner-inspired)
33
34
  import { CrushJSON, DescribeCrush, PartitionStablePrefix } from '@memberjunction/context-crush';
34
35
  // AST-aware code reduction (CodeCompressor-inspired) — opt-in per agent type
@@ -54,7 +55,7 @@ import { FormatToolResultSection, FormatToolErrorSection, RenderToolResultData,
54
55
  import { PriorTurnToolResultCache } from './prior-turn-tool-result-cache.js';
55
56
  import { PromptComponentResolver, InjectScopedPromptParts } from './prompt-component-resolver.js';
56
57
  import { ScopedPromptConfigResolver, ApplyScopedPromptConfig } from './scoped-prompt-config-resolver.js';
57
- import { StringifyForPersistence, AIPromptParams, ChildPromptParam, ConversationUtility, ParseFileOutputRef, parseAssignmentStrategy, ResolveClientTools, initAgentRunStep, finalizeAgentRunStep, AgentRunStepSaveQueue, ExtractPromptResultText, GetTaskGraphSubmitter, SummarizeDecisionAnswers, SystemPlaceholderManager, WithoutHostOnlyAgentRunDataKeys, WithAgentRunDataTrustApplied, AgentUserPolicyEngine, ConfigOf } from '@memberjunction/ai-core-plus';
58
+ import { StringifyForPersistence, AIPromptParams, ChildPromptParam, ConversationUtility, ParseFileOutputRef, parseAssignmentStrategy, ResolveClientTools, initAgentRunStep, finalizeAgentRunStep, AgentRunStepSaveQueue, ExtractPromptResultText, GetTaskGraphSubmitter, SummarizeDecisionAnswers, SystemPlaceholderManager, WithoutHostOnlyAgentRunDataKeys, WithAgentRunDataTrustApplied, AgentUserPolicyEngine, ApplyOutputMapping, BuildActionOutputObject, ConfigOf, ResolveLoopBodyParams, ValidateLoopOperationStructure } from '@memberjunction/ai-core-plus';
58
59
  import { ActionResult, RunActionParams, AUDIENCE_UNSUPPORTED_RESULT_CODE, ActionRunScopeIsBounded } from '@memberjunction/actions-base';
59
60
  import { UserCache } from '@memberjunction/generic-database-provider';
60
61
  import { AgentAudienceAddsReader, AgentAudienceProblem, AgentAudienceReaderIDs, MatchAudienceUsers } from './agent-audience.js';
@@ -72,7 +73,8 @@ import { PayloadFeedbackManager } from './PayloadFeedbackManager.js';
72
73
  import { DEFAULT_LOOP_AGENT_PROMPT_PARAMS, MAX_DECISION_CALLS_PER_TURN, MAX_DECISION_REQUESTS_PER_TURN, ResolveFinishIfMode } from './agent-types/loop-agent-prompt-params.js';
73
74
  import { FinishIfModeWarnings } from './finish-if-mode-warnings.js';
74
75
  import { ApplyCatalogNarrowing, BuildCatalogNarrowingQuestions, CatalogNarrowingCandidatesToAsk, CatalogNarrowingNote, CATALOG_NARROWING_FIND_ACTIONS, IsAlwaysShownAction, IsCatalogListNarrowed, NoCatalogNarrowing, OpeningRequestText, ReachableCatalogNarrowingLimits, ResolveCatalogNarrowingLimits, SelectCatalogNarrowing, } from './catalog-narrowing.js';
75
- import { BuildDecisionDiscoveryOptionSet, BuildDecisionDiscoveryQuestions, CanSearchEntities, DECISION_DISCOVERY_MAX_RECORDED_IDS, DECISION_DISCOVERY_MIN_CONFIDENCE, DECISION_DISCOVERY_MIN_OPTIONS, DECISION_DISCOVERY_TIMEOUT_MS, DecisionDiscoveryAgentSearch, DecisionDiscoveryFromResult, DecisionDiscoveryRunnableAgents, DecisionPromptOptionCap, FailedDecisionDiscovery, HostAllowedAgentIDs, IsDecisionDiscoveryOn, IsOpeningTurn, MentionsAgent, } from './decision-discovery.js';
76
+ import { BuildDecisionDiscoveryOptionSet, BuildDecisionDiscoveryQuestions, CanSearchEntities, DECISION_DISCOVERY_MAX_RECORDED_IDS, DECISION_DISCOVERY_MIN_CONFIDENCE, DECISION_DISCOVERY_MIN_OPTIONS, DECISION_DISCOVERY_TIMEOUT_MS, DecisionDiscoveryAgentSearch, DecisionDiscoveryFromResult, DecisionDiscoveryRunnableAgents, DecisionPromptOptionCap, FailedDecisionDiscovery, HostAllowedAgentIDs, IsDecisionDiscoveryOn, IsOpeningTurn, KeepHostAllowedAgents, MentionsAgent, } from './decision-discovery.js';
77
+ import { ResolveHandoffTarget } from './handoff-target.js';
76
78
  import { BuildFinishIfQuestions, CapFinishIfState, FINISH_IF_STATE_EXCERPT, FormatActionForFinishIf, FormatSubAgentForFinishIf, JudgeFinishIf } from './finish-if-state.js';
77
79
  import { PipelineExecutor, PipelineToolRegistry, ActionInvocable, ArtifactToolInvocable, BuildPipelineToolDocs, formatFinalOutput, summarizePipelineStages, } from './pipeline/index.js';
78
80
  // The ONE payload-mapping dialect. Loop agents and the task-graph dispatcher read the same authored
@@ -81,6 +83,7 @@ import { GetValueFromPath, SetMappedValue } from '@memberjunction/ai-core-plus';
81
83
  import { AgentDataPreloader } from './AgentDataPreloader.js';
82
84
  import { ClientToolRequestManager } from './ClientToolRequestManager.js';
83
85
  import { BuildClientToolResultMessage, ResolveClientToolResultMaxChars, ReplaceMediaBlocksWithStubs, IsMediaBlock, IMAGE_BLOCK_TOKEN_ESTIMATE } from './client-tool-results.js';
86
+ import { CanAgentOwnSubAgentConsults, DEFAULT_MAX_SUB_AGENT_CONSULT_ROUNDS, FormatReloadedConsultsMessage, FormatResponseFormSummary, FormatSubAgentConsultMessage, LoadOpenSubAgentConsults } from './sub-agent-consult.js';
84
87
  import { ConversationMessageResolver } from './utils/ConversationMessageResolver.js';
85
88
  import _ from 'lodash';
86
89
  /**
@@ -132,6 +135,22 @@ import _ from 'lodash';
132
135
  * one) from saturating the model API / DB pool with N concurrent runs.
133
136
  */
134
137
  const PARALLEL_SUBAGENT_CONCURRENCY_LIMIT = 5;
138
+ /** Result code of a call the user's agent policy denies outright (`checkUserActionPolicy`). */
139
+ export const POLICY_DENIED_RESULT_CODE = 'POLICY_DENIED';
140
+ /** Result code of a call the user's agent policy allows only with the user's approval. */
141
+ export const POLICY_APPROVAL_REQUIRED_RESULT_CODE = 'POLICY_APPROVAL_REQUIRED';
142
+ /** Result code of a call the user's agent policy defers to its next allowed time window. */
143
+ export const POLICY_DEFERRED_RESULT_CODE = 'POLICY_DEFERRED_OUTSIDE_TIME_WINDOW';
144
+ /**
145
+ * The result codes `checkUserActionPolicy` returns when the user's agent policy refuses a call. None of them is
146
+ * fixed by retrying: approval cannot be granted inside the run, a time window does not open by asking again, and
147
+ * a denial repeats for the same call.
148
+ */
149
+ const POLICY_REFUSAL_RESULT_CODES = new Set([
150
+ POLICY_DENIED_RESULT_CODE,
151
+ POLICY_APPROVAL_REQUIRED_RESULT_CODE,
152
+ POLICY_DEFERRED_RESULT_CODE,
153
+ ]);
135
154
  /** Identical-arguments rule: this many failures with the same arguments block further identical calls. */
136
155
  export const IDENTICAL_FAILURE_THRESHOLD = 2;
137
156
  /** Attempt budget: this many consecutive failures, across any arguments, disable the action for the run. */
@@ -264,6 +283,15 @@ export class BaseAgent {
264
283
  * @private
265
284
  */
266
285
  this._feedbackRequestId = null;
286
+ /**
287
+ * Stores the handoff outcome when a Handoff step fires.
288
+ * Populated by executeHandoffStep(), returned in ExecuteAgentResult.handoff.
289
+ */
290
+ this._handoffResult = null;
291
+ /**
292
+ * Stores the target agent resolved during validateHandoffNextStep() for executeHandoffStep().
293
+ */
294
+ this._resolvedHandoffTarget = null;
267
295
  this._resolvedStorageAccountId = null;
268
296
  /**
269
297
  * Most recent artifactDirective returned by a child or related sub-agent during this run.
@@ -375,6 +403,14 @@ export class BaseAgent {
375
403
  * @private
376
404
  */
377
405
  this._effectiveSubAgents = [];
406
+ /**
407
+ * True once gatherPromptTemplateData() has computed {@link _effectiveActions} and
408
+ * {@link _effectiveSubAgents} for this run. An empty list is then authoritative: a host's
409
+ * `actionChanges` that remove every action leave the run with none, instead of falling back to
410
+ * the agent's database configuration as an uncomputed list does.
411
+ * @private
412
+ */
413
+ this._effectiveCatalogComputed = false;
378
414
  /**
379
415
  * The request that opened the run: the last user message when it started, before the framework
380
416
  * added anything. Catalog narrowing judges the catalog against it.
@@ -472,6 +508,29 @@ export class BaseAgent {
472
508
  * @private
473
509
  */
474
510
  this._validationRetryCount = 0;
511
+ /**
512
+ * Per-parent-run consultation round counter keyed by `subAgentEntity.ID`.
513
+ * Tracks how many times each sub-agent has returned `FinalStep === 'Chat'`
514
+ * under `ChatHandlingOption = 'Consult'` during this run.
515
+ * Reset at the start of each agent run.
516
+ * @private
517
+ */
518
+ this._subAgentConsultRounds = new Map();
519
+ /**
520
+ * Open sub-agent consultations keyed by `childRunId`.
521
+ * Populated when a child sub-agent pauses with `FinalStep === 'Chat'` under `'Consult'`,
522
+ * and removed when the parent resumes that child run.
523
+ * Reset at the start of each agent run.
524
+ * @private
525
+ */
526
+ this._openSubAgentConsults = new Map();
527
+ /**
528
+ * Tracks whether we have already logged the warning that `'Consult'` is not
529
+ * supported on agent types where `InjectLoopResultsAsMessage` is `false`.
530
+ * Reset at the start of each agent run.
531
+ * @private
532
+ */
533
+ this._loggedConsultUnsupportedAgentType = false;
475
534
  /**
476
535
  * Counter tracking the number of context recovery attempts made in this run.
477
536
  * Context recovery removes/compacts old messages when context length is exceeded.
@@ -973,22 +1032,49 @@ export class BaseAgent {
973
1032
  return 'fatal';
974
1033
  }
975
1034
  const record = this._actionFailureHistory.get(summary.actionName);
976
- if (!record) {
977
- return 'warning';
978
- }
979
- if (record.totalConsecutiveFailures >= ACTION_FAILURE_BUDGET) {
1035
+ if (record && record.totalConsecutiveFailures >= ACTION_FAILURE_BUDGET) {
980
1036
  return 'attempts-exhausted';
981
1037
  }
982
- if (record.identicalFailures >= IDENTICAL_FAILURE_THRESHOLD) {
1038
+ // A policy refusal still counts in the history, so the budget above stays as the backstop; but it
1039
+ // outranks the identical-arguments rule, whose guidance ("adjust your parameters") is exactly what
1040
+ // a refused call must not be told. Approval and a time window do not come from different arguments.
1041
+ if (POLICY_REFUSAL_RESULT_CODES.has(summary.resultCode)) {
1042
+ return 'policy';
1043
+ }
1044
+ if (record && record.identicalFailures >= IDENTICAL_FAILURE_THRESHOLD) {
983
1045
  return 'identical-arguments';
984
1046
  }
985
1047
  return 'warning';
986
1048
  }
1049
+ /**
1050
+ * The guidance line for a call the user's agent policy refused. The default `[WARNING/ACTION_FAILURE]`
1051
+ * line tells the model to adjust its parameters and try again, up to the budget; a refusal is not a
1052
+ * parameter error, and a retry burns the budget without ever succeeding.
1053
+ */
1054
+ formatPolicyRefusalDirective(summary) {
1055
+ const name = summary.actionName;
1056
+ switch (summary.resultCode) {
1057
+ case POLICY_APPROVAL_REQUIRED_RESULT_CODE:
1058
+ return `[CRITICAL/POLICY_APPROVAL_REQUIRED] Action '${name}' requires the user's approval under their agent policy: "${summary.message}". ` +
1059
+ `Approval cannot be granted inside this run, so DO NOT retry '${name}'. Tell the user exactly what you intended to do and why, ` +
1060
+ 'and ask them to approve it or do it themselves.';
1061
+ case POLICY_DEFERRED_RESULT_CODE:
1062
+ return `[CRITICAL/POLICY_DEFERRED] Action '${name}' is outside the time window the user's agent policy allows: "${summary.message}". ` +
1063
+ `Retrying now will not help; DO NOT call '${name}' again during this run. Tell the user it was deferred and when it can run.`;
1064
+ default:
1065
+ return `[CRITICAL/POLICY_DENIED] Action '${name}' was refused by the user's agent policy: "${summary.message}". ` +
1066
+ 'This is a governance decision, not a problem with your arguments: the same call will be refused again. ' +
1067
+ `Call '${name}' again only with materially different parameters, and only if the reason says the refusal depends on them; ` +
1068
+ 'otherwise use another tool or tell the user what you could not do.';
1069
+ }
1070
+ }
987
1071
  /** The guidance line appended to the history for one failed action. */
988
1072
  formatActionFailureDirective(summary) {
989
1073
  const name = summary.actionName;
990
1074
  const record = this._actionFailureHistory.get(name);
991
1075
  switch (this.classifyActionFailure(summary)) {
1076
+ case 'policy':
1077
+ return this.formatPolicyRefusalDirective(summary);
992
1078
  case 'audience':
993
1079
  return `[CRITICAL/NOT_AVAILABLE_IN_SHARED_CONVERSATION] Action '${name}' is not available in this shared conversation: what it ` +
994
1080
  `returns could not be limited to what everyone in it may see ("${summary.message}"). It is not broken or misconfigured. ` +
@@ -1221,8 +1307,8 @@ export class BaseAgent {
1221
1307
  let extractedCount = 0;
1222
1308
  for (let i = 0; i < mediaItems.length; i++) {
1223
1309
  const media = mediaItems[i];
1224
- // Only intercept if there's substantial data
1225
- if (media.data && media.data.length > BaseAgent.LARGE_BINARY_THRESHOLD) {
1310
+ // Intercept when already stored in MJ Storage (fileId) or when inline data exceeds threshold
1311
+ if (media.fileId || (media.data && media.data.length > BaseAgent.LARGE_BINARY_THRESHOLD)) {
1226
1312
  // Generate unique reference ID
1227
1313
  const refId = `media-${Date.now().toString(36)}-${i}-${Math.random().toString(36).substring(2, 8)}`;
1228
1314
  // Store in unified media outputs — always persisted by AgentRunner.
@@ -1279,19 +1365,20 @@ export class BaseAgent {
1279
1365
  }
1280
1366
  /**
1281
1367
  * Substitutes `${media:<refId>}` placeholders in a string with the actual
1282
- * data URI (`data:<mime>;base64,<bytes>`) of the matching intercepted media item.
1368
+ * data URI (`data:<mime>;base64,<bytes>`) or stored `fileId` (for `fileId`-only
1369
+ * media items) of the matching intercepted media item.
1283
1370
  *
1284
1371
  * Used for payload / actionable-command resolution at the terminal step, where the
1285
- * LLM wants to embed image (or other media) data inline at a specific position in
1286
- * its structured output rather than as a trailing attachment card. The string
1287
- * variant of placeholder resolution; recursive walker lives in
1288
- * {@link resolveMediaPlaceholdersInPayload}.
1372
+ * LLM wants to embed image (or other media) data or a stored file ID inline at a
1373
+ * specific position in its structured output rather than only as a trailing
1374
+ * attachment card. The string variant of placeholder resolution; recursive walker
1375
+ * lives in {@link resolveMediaPlaceholdersInPayload}.
1289
1376
  *
1290
1377
  * This function only does substitution — it has no persistence side effects.
1291
1378
  *
1292
1379
  * @param text - The string that may contain media placeholders
1293
- * @returns String with placeholders resolved to actual data URIs (or the original
1294
- * placeholder if the refId is unknown — defensive, shouldn't happen)
1380
+ * @returns String with placeholders resolved to data URIs or stored file IDs (or the
1381
+ * original placeholder if the refId is unknown — defensive, shouldn't happen)
1295
1382
  * @private
1296
1383
  * @since 3.1.0
1297
1384
  */
@@ -1309,6 +1396,9 @@ export class BaseAgent {
1309
1396
  if (media?.data) {
1310
1397
  return `data:${media.mimeType};base64,${media.data}`;
1311
1398
  }
1399
+ if (media?.fileId) {
1400
+ return media.fileId;
1401
+ }
1312
1402
  // Unknown refId — leave the placeholder in place rather than emit a broken
1313
1403
  // data URI. Defensive; this branch should not fire in normal flow.
1314
1404
  this.logStatus(`⚠️ Media reference '${refId}' not found in registry`, true);
@@ -1894,9 +1984,16 @@ export class BaseAgent {
1894
1984
  this._validationRetryCount = 0;
1895
1985
  this._generalValidationRetryCount = 0;
1896
1986
  this._contextRecoveryAttempts = 0;
1987
+ this._subAgentConsultRounds.clear();
1988
+ this._openSubAgentConsults.clear();
1989
+ this._loggedConsultUnsupportedAgentType = false;
1897
1990
  this._effectiveActions = [];
1991
+ this._effectiveSubAgents = [];
1992
+ this._effectiveCatalogComputed = false;
1898
1993
  this._dynamicActionLimits = {};
1899
1994
  this._mediaOutputs = [];
1995
+ this._handoffResult = null;
1996
+ this._resolvedHandoffTarget = null;
1900
1997
  this._lastSubAgentArtifactDirective = undefined;
1901
1998
  this._messageLifecycleCallback = params.onMessageLifecycle;
1902
1999
  this._catalogNarrowing = undefined;
@@ -1944,15 +2041,15 @@ export class BaseAgent {
1944
2041
  const userId = params.userId || params.contextUser?.ID;
1945
2042
  const companyId = params.companyId;
1946
2043
  const lastUserMessage = params.conversationMessages.filter(m => m.role === 'user').pop();
1947
- const inputText = lastUserMessage?.content || '';
2044
+ const inputText = lastUserMessage?.metadata?.rawContent ?? (lastUserMessage?.content || '');
1948
2045
  // The run's scope exactly as initializeAgentRun validated it in Phase 1 — what the run row records and every
1949
2046
  // action is handed — so notes, RAG and scoped prompt parts search the same tenant and dimensions.
1950
2047
  const runScope = this.runScopeForContext(params);
1951
2048
  // The user's new message, captured by identity before anything below adds to the list, so a
1952
2049
  // resumed stopped run can be spliced in ahead of it once the parallel phase settles.
1953
2050
  const continuationMessage = wrappedParams.conversationMessages[wrappedParams.conversationMessages.length - 1];
1954
- // Positions matter: [0] is the config and [5] the stopped-run continuation.
1955
- const [config, , , , , stoppedRunContinuation] = await Promise.all([
2051
+ // Positions matter: [0] is the config, [5] the stopped-run continuation, and [7] open sub-agent consults.
2052
+ const [config, , , , , stoppedRunContinuation, , openConsults] = await Promise.all([
1956
2053
  this.loadAgentConfiguration(params.agent),
1957
2054
  this.preloadAgentData(wrappedParams),
1958
2055
  this.InjectContextMemory(typeof inputText === 'string' ? inputText : '', params.agent, userId, companyId, params.contextUser, wrappedParams.conversationMessages, runScope.EntityID, runScope.RecordID, runScope.Secondary, this.parseSecondaryScopeConfig(params.agent),
@@ -1972,7 +2069,10 @@ export class BaseAgent {
1972
2069
  this.loadStoppedRunContinuation(wrappedParams),
1973
2070
  // Decision discovery (plan Task 3.1), off unless the decisionsEnabled and decisionDiscovery prompt
1974
2071
  // params are true: may add a <suggested_agent> system message, within DECISION_DISCOVERY_TIMEOUT_MS.
1975
- this.InjectDecisionDiscovery(params.agent, params.contextUser, wrappedParams.conversationMessages, params.data)
2072
+ this.InjectDecisionDiscovery(params.agent, params.contextUser, wrappedParams.conversationMessages, params.data),
2073
+ // If this run resumes a prior run that paused with FinalStep === 'Chat', reload any unanswered
2074
+ // sub-agent consults so the caller's answer can be relayed back to the waiting sub-agent.
2075
+ this.loadOpenConsults(wrappedParams)
1976
2076
  ]);
1977
2077
  // Resume (or summarize) a run the user stopped, now that nothing else is writing the list.
1978
2078
  this.applyStoppedRunContinuation(wrappedParams, stoppedRunContinuation, continuationMessage);
@@ -1981,6 +2081,9 @@ export class BaseAgent {
1981
2081
  const messagesBeforeParts = new Set(wrappedParams.conversationMessages);
1982
2082
  this.InjectScopedPromptParts(params.agent, wrappedParams.conversationMessages, runScope.EntityID, runScope.RecordID, runScope.Secondary);
1983
2083
  await this.replaceScopedPartPlaceholders(wrappedParams.conversationMessages, messagesBeforeParts, params.contextUser);
2084
+ // Restore open sub-agent consults from a resumed Chat run and splice the reminder immediately
2085
+ // before the caller's answer (continuationMessage).
2086
+ this.applyOpenConsults(wrappedParams, openConsults, continuationMessage);
1984
2087
  if (!config.success) {
1985
2088
  this.logError(`Failed to load agent configuration: ${config.errorMessage}`, {
1986
2089
  agent: params.agent,
@@ -2071,17 +2174,25 @@ export class BaseAgent {
2071
2174
  // passed in, not our chained signal.
2072
2175
  params.cancellationToken = upstreamToken;
2073
2176
  this._runAbortController = null;
2074
- // A cancellation, or an error thrown out of the step loop, leaves any held decision
2075
- // requests unasked. The terminate path has already logged and cleared its own.
2076
- this.skipHeldDecisions(params, this.runEndForHeldDecisions());
2077
- this.releasePerRunDataCache();
2078
- await this.finalizeRun(this.deriveRunOutcome());
2079
- if (this._agentRun?.ID) {
2080
- AgentRunWatchdog.Instance.Untrack(this._agentRun.ID);
2081
- }
2082
- // The run is over: a later direct ExecuteSingleAction resolves the scope and the audience from its own params.
2083
- this.clearRunBoundState();
2177
+ await this.endRun(params);
2178
+ }
2179
+ }
2180
+ /**
2181
+ * {@link Execute}'s per-run teardown, called from its top-level `finally` on every exit path.
2182
+ * The run leaves the watchdog first, before the subclass {@link finalizeRun} hook, so a hook
2183
+ * that throws can never leave a finished run being heart-beaten for the life of the process.
2184
+ */
2185
+ async endRun(params) {
2186
+ if (this._agentRun?.ID) {
2187
+ AgentRunWatchdog.Instance.Untrack(this._agentRun.ID);
2084
2188
  }
2189
+ // A cancellation, or an error thrown out of the step loop, leaves any held decision
2190
+ // requests unasked. The terminate path has already logged and cleared its own.
2191
+ this.skipHeldDecisions(params, this.runEndForHeldDecisions());
2192
+ this.releasePerRunDataCache();
2193
+ await this.finalizeRun(this.deriveRunOutcome());
2194
+ // The run is over: a later direct ExecuteSingleAction resolves the scope and the audience from its own params.
2195
+ this.clearRunBoundState();
2085
2196
  }
2086
2197
  /**
2087
2198
  * Fails the run at its start, before any prompt: marks the already-created AgentRun Failed with the message
@@ -2174,13 +2285,18 @@ export class BaseAgent {
2174
2285
  * (`TaskGraphAgentRunner`) that carries neither the audience nor the scope. So graphs are withheld when the
2175
2286
  * audience adds a reader, and when the run's validated scope carries a tenant or a secondary dimension
2176
2287
  * (`ActionRunScopeIsBounded`): a model-written Scoped Search node would search outside the run's tenant, and an
2177
- * agent node would drop it.
2288
+ * agent node would drop it. Likewise when the host assigned the run's search scopes (`SearchScopeIDs`): a graph's
2289
+ * Scoped Search node would fall back to the agent's own search access.
2178
2290
  */
2179
2291
  taskGraphWithholdingReason(params) {
2180
2292
  if (this.runAudienceAddsReader(params)) {
2181
2293
  return 'a run with an audience';
2182
2294
  }
2183
- return ActionRunScopeIsBounded(this._runScope ?? this.validatedRunScope(params)) ? 'a tenant-scoped run' : null;
2295
+ const scope = this._runScope ?? this.validatedRunScope(params);
2296
+ if (scope?.SearchScopeIDs?.length) {
2297
+ return 'a run with host-assigned search scopes';
2298
+ }
2299
+ return ActionRunScopeIsBounded(scope) ? 'a tenant-scoped run' : null;
2184
2300
  }
2185
2301
  /** Whether this run withholds task graphs ({@link taskGraphWithholdingReason}). */
2186
2302
  runWithholdsTaskGraphs(params) {
@@ -2206,12 +2322,34 @@ export class BaseAgent {
2206
2322
  };
2207
2323
  }
2208
2324
  /**
2209
- * What this run's prompt leaves out: task graphs ({@link taskGraphWithholdingReason}), and — when the audience adds a
2210
- * reader — the caller's own browser and view (`CallerContext`): client tools run in the caller's browser and what they
2211
- * return reaches the room, and the app context (`data.appContext`, with its `AdditionalContext`) is the caller's screen.
2325
+ * Whether this run withholds Handoff (`enableHandoff` off and the `handoff` response section hidden).
2326
+ * True when the run has a `parentRun` (sub-agents cannot transfer the conversation), has no
2327
+ * `conversationDetailId` (there is no conversation reply row to hand over), has no `handoffChain`
2328
+ * (the host does not carry out handoffs), or runs for an anonymous/widget guest without a trusted
2329
+ * host allow-list (`TrustReservedRunData === true` and `HostAllowedAgentIDs(params.data)` defined).
2330
+ */
2331
+ runWithholdsHandoff(params) {
2332
+ const hasTrustedHostAllowList = params.TrustReservedRunData === true &&
2333
+ HostAllowedAgentIDs(params.data) !== undefined;
2334
+ const isUnscopedGuest = Boolean(params.contextUser?.IsMagicLinkAnonymous || params.contextUser?.WidgetGuestContext) &&
2335
+ !hasTrustedHostAllowList;
2336
+ return (Boolean(params.parentRun) ||
2337
+ !params.conversationDetailId ||
2338
+ !Array.isArray(params.handoffChain) ||
2339
+ isUnscopedGuest);
2340
+ }
2341
+ /**
2342
+ * What this run's prompt leaves out: task graphs ({@link taskGraphWithholdingReason}), handoff
2343
+ * ({@link runWithholdsHandoff}), and — when the audience adds a reader — the caller's own browser
2344
+ * and view (`CallerContext`): client tools run in the caller's browser and what they return reaches
2345
+ * the room, and the app context (`data.appContext`, with its `AdditionalContext`) is the caller's screen.
2212
2346
  */
2213
2347
  promptWithholding(params) {
2214
- return { TaskGraphs: this.runWithholdsTaskGraphs(params), CallerContext: this.runAudienceAddsReader(params) };
2348
+ return {
2349
+ TaskGraphs: this.runWithholdsTaskGraphs(params),
2350
+ Handoff: this.runWithholdsHandoff(params),
2351
+ CallerContext: this.runAudienceAddsReader(params)
2352
+ };
2215
2353
  }
2216
2354
  /**
2217
2355
  * The client-tools and app-context prompt sections ({@link buildClientToolPromptSection}, {@link buildAppContextSection}),
@@ -2261,6 +2399,16 @@ export class BaseAgent {
2261
2399
  : {};
2262
2400
  return { ...promptParams, enableTaskGraphs: false, includeResponseTypeDefinition: { ...responseType, tasks: false } };
2263
2401
  }
2402
+ /**
2403
+ * A copy of the agent-type prompt params with handoff withheld (`enableHandoff` off and the `handoff`
2404
+ * response section hidden). A copy, never a write: the input may be the process-wide cached base.
2405
+ */
2406
+ withoutHandoff(promptParams) {
2407
+ const responseType = IsPlainObject(promptParams.includeResponseTypeDefinition)
2408
+ ? promptParams.includeResponseTypeDefinition
2409
+ : {};
2410
+ return { ...promptParams, enableHandoff: false, includeResponseTypeDefinition: { ...responseType, handoff: false } };
2411
+ }
2264
2412
  /**
2265
2413
  * Why a session-driven (realtime / voice / bridge) run is refused, or null. A live session speaks and calls
2266
2414
  * tools outside the gates that hold a run to its audience, so a run whose audience adds a reader is refused.
@@ -2790,7 +2938,7 @@ export class BaseAgent {
2790
2938
  */
2791
2939
  async assembleRealtimeContext(params) {
2792
2940
  const lastUserMessage = params.conversationMessages.filter(m => m.role === 'user').pop();
2793
- const inputText = typeof lastUserMessage?.content === 'string' ? lastUserMessage.content : '';
2941
+ const inputText = lastUserMessage?.metadata?.rawContent ?? (typeof lastUserMessage?.content === 'string' ? lastUserMessage.content : '');
2794
2942
  const scratch = [];
2795
2943
  const builder = new AgentMemoryContextBuilder();
2796
2944
  await builder.InjectContextMemory(inputText, params.agent, params.userId || params.contextUser?.ID, params.companyId, params.contextUser, scratch, undefined, undefined, undefined, null, undefined, (message, verboseOnly) => this.logStatus(message, verboseOnly ?? false, params),
@@ -2844,6 +2992,7 @@ export class BaseAgent {
2844
2992
  apiKeys: params.apiKeys,
2845
2993
  CredentialScope: params.CredentialScope,
2846
2994
  Audience: params.Audience, // the target answers the same people, so it is bounded the same way
2995
+ SearchScopeIDs: params.SearchScopeIDs, // and searches what the host assigned (never read from data)
2847
2996
  data: params.data,
2848
2997
  TrustReservedRunData: params.TrustReservedRunData, // the session's data, already vetted when it started
2849
2998
  verbose: params.verbose,
@@ -3975,6 +4124,11 @@ export class BaseAgent {
3975
4124
  }
3976
4125
  }
3977
4126
  }
4127
+ // Also convert rawContent in metadata when speaker attribution is active
4128
+ const agentMessage = message;
4129
+ if (typeof agentMessage.metadata?.rawContent === 'string') {
4130
+ agentMessage.metadata.rawContent = ConversationUtility.ToPlainText(agentMessage.metadata.rawContent);
4131
+ }
3978
4132
  }
3979
4133
  }
3980
4134
  /**
@@ -4504,7 +4658,13 @@ export class BaseAgent {
4504
4658
  const frameworkTools = control.NativeOnly
4505
4659
  ? BuildFrameworkTools(this.frameworkToolHost(params), this.frameworkToolAvailability(promptParams, params))
4506
4660
  : [];
4507
- const toolSet = BuildNativeToolSet(actionSet, subAgents, control, agentTools, frameworkTools);
4661
+ const toolSet = BuildNativeToolSet(actionSet, subAgents, control, agentTools, frameworkTools, (sa) => {
4662
+ const presetNames = (AIEngine.Instance.GetAgentConfigurationPresets?.(sa.ID, true) ?? []).map(p => p.Name);
4663
+ return {
4664
+ consultEnabled: this.isSubAgentConsultEnabledForSubAgent(params.agent, sa),
4665
+ ...(presetNames.length > 0 ? { presetNames } : {})
4666
+ };
4667
+ });
4508
4668
  if (control.NativeOnly && promptParams.data) {
4509
4669
  // The template renders the tools-only prompt when this is set AND the runner resolves implicit control flow.
4510
4670
  promptParams.data[NATIVE_ONLY_TEMPLATE_FLAG] = true;
@@ -4829,7 +4989,7 @@ export class BaseAgent {
4829
4989
  const systemPrompt = config.systemPrompt;
4830
4990
  const childPrompt = config.childPrompt;
4831
4991
  // Gather context data (including runtime action changes)
4832
- const promptTemplateData = await this.gatherPromptTemplateData(params.agent, params.contextUser, params.data, params.actionChanges, params.subAgentChanges, params.boundActionParams, this.promptWithholding(params));
4992
+ const promptTemplateData = await this.gatherPromptTemplateData(params.agent, params.contextUser, params.data, params.actionChanges, params.subAgentChanges, params.boundActionParams, this.promptWithholding(params), params.parentRun);
4833
4993
  // Set up the hierarchical prompt execution
4834
4994
  const promptParams = new AIPromptParams();
4835
4995
  // Attribute the resulting AIPromptRun to this agent. Agents share agent-type-level system
@@ -5115,12 +5275,19 @@ export class BaseAgent {
5115
5275
  * Keeps the system-prompt-and-tools fingerprint of the request just sent, for the next one. When
5116
5276
  * it changed, the runner sent this request without replayed reasoning; the history drops it too,
5117
5277
  * so no later request replays a block made under the old prompt or tools.
5278
+ *
5279
+ * A result with no fingerprint (a request that failed before or while it was sent, such as a
5280
+ * failover that ran out of candidates) leaves the baseline as it was. Clearing it would let the
5281
+ * next request skip the comparison and replay thinking made under a prompt or tools it no longer has.
5118
5282
  */
5119
5283
  trackSentPrefix(params, promptResult) {
5120
5284
  const sent = GetSentPrefixFingerprint(promptResult.chatResult);
5285
+ if (sent === undefined) {
5286
+ return;
5287
+ }
5121
5288
  const previous = this._lastSentPrefix;
5122
5289
  this._lastSentPrefix = sent;
5123
- if (previous === undefined || sent === undefined || sent === previous || !this.replaysPrefixBoundReasoning()) {
5290
+ if (previous === undefined || sent === previous || !this.replaysPrefixBoundReasoning()) {
5124
5291
  return;
5125
5292
  }
5126
5293
  params.conversationMessages.forEach((m, i) => {
@@ -5199,8 +5366,10 @@ export class BaseAgent {
5199
5366
  * declares native tools to a driver whose replayed reasoning needs the history before it
5200
5367
  * unchanged is append-only too (see {@link ResolveAppendOnlyState}).
5201
5368
  *
5202
- * Decided ONCE per run. An explicit `trailingStateMode` or a runtime model override answers
5203
- * immediately. Otherwise the answer is frozen at the first model selection and reused for every
5369
+ * Decided ONCE per run. An explicit `trailingStateMode` answers immediately, and so does a runtime
5370
+ * model override that names a vendor, or whose catalog says the cache is a byte-prefix cache.
5371
+ * Otherwise (no override, or one that names no vendor and whose catalog does not say yes) the
5372
+ * answer is frozen at the first model selection and reused for every
5204
5373
  * later turn, so a failover to another vendor cannot flip the layout mid-run — a flip after turn 2
5205
5374
  * would leave stale fragments in the history or, worse, restore the wrong turn's fragment. On turn 1,
5206
5375
  * before any selection is known, the answer is replace-in-place: turn 1's fragment is kept and, if
@@ -5537,7 +5706,9 @@ export class BaseAgent {
5537
5706
  // (schema defaults -> agent.AgentTypePromptParams -> runtime override) without mutating
5538
5707
  // the caller's ExecuteAgentParams or params.data object.
5539
5708
  this.logStatus(`🎯 Agent type '${agentType.Name}' determining next step`, true, params);
5540
- const paramsForAgentType = this._agentTypePromptParams && params?.data?.__agentTypePromptParams === undefined
5709
+ const stepParams = this._agentTypePromptParams &&
5710
+ this.AgentTypeInstance instanceof LoopAgentType &&
5711
+ params?.data?.__agentTypePromptParams === undefined
5541
5712
  ? {
5542
5713
  ...params,
5543
5714
  data: {
@@ -5546,7 +5717,7 @@ export class BaseAgent {
5546
5717
  },
5547
5718
  }
5548
5719
  : params;
5549
- const nextStep = await this.AgentTypeInstance.DetermineNextStep(promptResult, paramsForAgentType, currentPayload, this.AgentTypeState, this._nativeToolBindings);
5720
+ const nextStep = await this.AgentTypeInstance.DetermineNextStep(promptResult, stepParams, currentPayload, this.AgentTypeState, this._nativeToolBindings);
5550
5721
  return nextStep;
5551
5722
  }
5552
5723
  /**
@@ -5579,6 +5750,27 @@ export class BaseAgent {
5579
5750
  // for next step, let's do a little quick validation here for sub-agent and actions to ensure requests are valid
5580
5751
  switch (nextStep.step) {
5581
5752
  case 'Sub-Agent':
5753
+ if (nextStep.taskGraph?.folded &&
5754
+ nextStep.subAgent?.name &&
5755
+ Boolean(GetTaskGraphSubmitter()) &&
5756
+ !this.resolveSubAgentByName(params, nextStep.subAgent.name)) {
5757
+ const activeAgentExists = AIEngine.Instance.Agents.some((a) => a.Status === 'Active' &&
5758
+ a.Name === nextStep.subAgent.name &&
5759
+ !UUIDsEqual(a.ID, params.agent.ID));
5760
+ if (activeAgentExists) {
5761
+ this.logStatus(`target is not a sub-agent of ${params.agent.Name}; submitting durably`, false, params);
5762
+ const unfolded = {
5763
+ ...nextStep,
5764
+ step: 'Tasks',
5765
+ subAgent: undefined,
5766
+ taskGraph: {
5767
+ spec: nextStep.taskGraph.spec,
5768
+ folded: false,
5769
+ },
5770
+ };
5771
+ return this.validateTasksNextStep(params, unfolded, currentPayload, agentRun, currentStep);
5772
+ }
5773
+ }
5582
5774
  return this.validateSubAgentNextStep(params, nextStep, currentPayload, agentRun, currentStep);
5583
5775
  case 'Actions':
5584
5776
  return this.validateActionsNextStep(params, nextStep, currentPayload, agentRun, currentStep);
@@ -5615,6 +5807,10 @@ export class BaseAgent {
5615
5807
  // Retry step instead of hard-failing the run in executeTasksStep.
5616
5808
  case 'Tasks':
5617
5809
  return this.validateTasksNextStep(params, nextStep, currentPayload, agentRun, currentStep);
5810
+ // Type assertion required because 'Handoff' is not part of the BaseAgentNextStep step
5811
+ // union (transfer-and-detach — the terminal step it produces is 'Success').
5812
+ case 'Handoff':
5813
+ return this.validateHandoffNextStep(params, nextStep, currentPayload, agentRun, currentStep);
5618
5814
  default:
5619
5815
  // if we get here, the next step is not recognized, we can return a retry step
5620
5816
  this.logError(`Invalid next step '${nextStep.step}' for agent '${params.agent.Name}'`, {
@@ -5655,7 +5851,7 @@ export class BaseAgent {
5655
5851
  }
5656
5852
  async validateSubAgentNextStep(params, nextStep, currentPayload, agentRun, currentStep) {
5657
5853
  const curAgentSubAgents = this.getEffectiveSubAgentsForValidation(params.agent.ID);
5658
- const allowFoldedTaskGraphTarget = nextStep.taskGraph?.folded === true;
5854
+ const allowFoldedTaskGraphTarget = nextStep.taskGraph?.folded === true && !GetTaskGraphSubmitter();
5659
5855
  // Collect requested sub-agents. Prefer plural `subAgents` (parallel fan-out);
5660
5856
  // fall back to singular `subAgent` for the classic single-sub-agent next step.
5661
5857
  const requested = this.getRequestedSubAgents(nextStep);
@@ -5674,12 +5870,19 @@ export class BaseAgent {
5674
5870
  };
5675
5871
  }
5676
5872
  // Validate each requested sub-agent: existence + user run permission + MaxExecutionsPerRun
5873
+ const seenResumeRunIds = new Set();
5874
+ const openConsultsBySubAgent = GroupByUUID(this._openSubAgentConsults.values(), c => c.subAgentId);
5677
5875
  for (const req of requested) {
5678
5876
  const name = req?.name;
5679
5877
  const normalizedName = name?.trim().toLowerCase();
5680
- const directSubAgent = curAgentSubAgents.find(a => a.Name.trim().toLowerCase() === normalizedName);
5681
- const catalogSubAgent = !directSubAgent && allowFoldedTaskGraphTarget && normalizedName
5682
- ? AIEngine.Instance.Agents.find(a => a.Status === 'Active' && a.Name.trim().toLowerCase() === normalizedName)
5878
+ const directSubAgent = curAgentSubAgents.find(a => a.Name.trim().toLowerCase() === normalizedName)
5879
+ ?? (name ? this.matchNamedBySanitizedToolName(name, curAgentSubAgents, true).match : undefined);
5880
+ const activeCatalogAgents = allowFoldedTaskGraphTarget
5881
+ ? AIEngine.Instance.Agents.filter(a => a.Status === 'Active')
5882
+ : [];
5883
+ const catalogSubAgent = !directSubAgent && allowFoldedTaskGraphTarget && name
5884
+ ? (activeCatalogAgents.find(a => a.Name.trim().toLowerCase() === normalizedName)
5885
+ ?? this.matchNamedBySanitizedToolName(name, activeCatalogAgents, true).match)
5683
5886
  : undefined;
5684
5887
  const subAgent = directSubAgent ?? catalogSubAgent;
5685
5888
  const hasRunPermission = subAgent && catalogSubAgent && params.contextUser
@@ -5724,10 +5927,117 @@ export class BaseAgent {
5724
5927
  };
5725
5928
  }
5726
5929
  }
5930
+ if (req.resumeRunId != null && req.resumeRunId !== '') {
5931
+ const openForSubAgent = openConsultsBySubAgent.Get(subAgent.ID) ?? [];
5932
+ const matchingConsult = IsValidUUID(req.resumeRunId)
5933
+ ? IndexByUUID(openForSubAgent, c => c.childRunId).Get(req.resumeRunId)
5934
+ : undefined;
5935
+ if (!matchingConsult) {
5936
+ const openIds = openForSubAgent.length > 0
5937
+ ? openForSubAgent.map(c => c.childRunId).join(', ')
5938
+ : 'none';
5939
+ const errorMessage = `Invalid resumeRunId '${req.resumeRunId}' for sub-agent '${subAgent.Name}'. Open consult run IDs for '${subAgent.Name}': ${openIds}`;
5940
+ this.logError(errorMessage, {
5941
+ agent: params.agent,
5942
+ category: 'SubAgentExecution',
5943
+ metadata: {
5944
+ subAgentName: name,
5945
+ resumeRunId: req.resumeRunId,
5946
+ openConsultIds: openIds
5947
+ }
5948
+ });
5949
+ if (nextStep.step !== 'Retry') {
5950
+ this._generalValidationRetryCount++;
5951
+ }
5952
+ return {
5953
+ step: 'Retry',
5954
+ terminate: false,
5955
+ errorMessage
5956
+ };
5957
+ }
5958
+ const normalizedResumeId = matchingConsult.childRunId.trim().toLowerCase();
5959
+ if (seenResumeRunIds.has(normalizedResumeId)) {
5960
+ const errorMessage = `resumeRunId '${req.resumeRunId}' is used more than once`;
5961
+ this.logError(errorMessage, {
5962
+ agent: params.agent,
5963
+ category: 'SubAgentExecution',
5964
+ metadata: {
5965
+ subAgentName: name,
5966
+ resumeRunId: req.resumeRunId
5967
+ }
5968
+ });
5969
+ if (nextStep.step !== 'Retry') {
5970
+ this._generalValidationRetryCount++;
5971
+ }
5972
+ return {
5973
+ step: 'Retry',
5974
+ terminate: false,
5975
+ errorMessage
5976
+ };
5977
+ }
5978
+ seenResumeRunIds.add(normalizedResumeId);
5979
+ }
5980
+ if (req.presetName != null && req.presetName.trim() !== '') {
5981
+ const matchedPreset = AIEngine.Instance.FindActiveAgentConfigurationPreset(subAgent.ID, req.presetName);
5982
+ if (!matchedPreset) {
5983
+ const availablePresets = AIEngine.Instance.GetAgentConfigurationPresets(subAgent.ID, true)
5984
+ .map(p => p.Name);
5985
+ const availableList = availablePresets.length > 0 ? availablePresets.join(', ') : 'none';
5986
+ const errorMessage = `Sub-agent '${subAgent.Name}' has no preset '${req.presetName}'. Available: ${availableList}.`;
5987
+ this.logError(errorMessage, {
5988
+ agent: params.agent,
5989
+ category: 'SubAgentExecution',
5990
+ metadata: {
5991
+ subAgentName: name,
5992
+ presetName: req.presetName,
5993
+ availablePresets: availableList
5994
+ }
5995
+ });
5996
+ if (nextStep.step !== 'Retry') {
5997
+ this._generalValidationRetryCount++;
5998
+ }
5999
+ return {
6000
+ ...nextStep,
6001
+ step: 'Retry',
6002
+ terminate: false,
6003
+ errorMessage
6004
+ };
6005
+ }
6006
+ }
5727
6007
  }
5728
6008
  // All requested sub-agents are valid
5729
6009
  return nextStep;
5730
6010
  }
6011
+ /**
6012
+ * Strips an optional `delegate_to_` native sub-agent tool prefix when a model running
6013
+ * with native tool calling references a sub-agent by its declared tool name inside an
6014
+ * envelope primitive (`Sub-Agent`, `ForEach`, `While`, or `Tasks`).
6015
+ */
6016
+ stripSubAgentToolPrefix(rawName) {
6017
+ const trimmed = rawName.trim();
6018
+ return trimmed.toLowerCase().startsWith(SUB_AGENT_TOOL_PREFIX)
6019
+ ? trimmed.slice(SUB_AGENT_TOOL_PREFIX.length)
6020
+ : trimmed;
6021
+ }
6022
+ /**
6023
+ * Resolves a unique entity from `pool` whose sanitized native tool name matches `rawName`.
6024
+ * Returns `{ ambiguous }` when multiple entities collide on the same sanitized name.
6025
+ */
6026
+ matchNamedBySanitizedToolName(rawName, pool, stripSubAgentPrefix = false) {
6027
+ const candidate = stripSubAgentPrefix ? this.stripSubAgentToolPrefix(rawName) : rawName.trim();
6028
+ const sanitized = SanitizeToolName(candidate);
6029
+ if (!sanitized) {
6030
+ return {};
6031
+ }
6032
+ const matches = pool.filter(item => item.Name && SanitizeToolName(item.Name) === sanitized);
6033
+ if (matches.length === 1) {
6034
+ return { match: matches[0] };
6035
+ }
6036
+ if (matches.length > 1) {
6037
+ return { ambiguous: matches };
6038
+ }
6039
+ return {};
6040
+ }
5731
6041
  /**
5732
6042
  * Builds a compact hint listing the current user's permitted runnable agents when a
5733
6043
  * task-graph or folded sub-agent step references an unknown or inaccessible agent name.
@@ -5747,11 +6057,9 @@ export class BaseAgent {
5747
6057
  * Validates a `'Tasks'` next step before `executeTasksStep` submits the graph.
5748
6058
  *
5749
6059
  * Verifies that every referenced `Agent` (including `ForEach`/`While` loop sub-agents) is
5750
- * active and runnable by `params.contextUser`, and that every referenced `Action` is active.
5751
- * When an agent or action name is unknown or inaccessible, converts the step to a self-correcting
5752
- * `Retry` with the user's permitted runnable agent list instead of letting `TaskGraphService.Submit`
5753
- * terminate the entire agent run as `Failed`. Never reveals whether an invalid agent name was
5754
- * nonexistent versus restricted by permissions.
6060
+ * active and runnable by `params.contextUser`, and that every referenced `Action` (including
6061
+ * multi-step `steps[]` loop bodies) is active. Accepts sanitized native tool names
6062
+ * (`calculate_expression`, `delegate_to_query_builder`) and canonicalizes them in place.
5755
6063
  */
5756
6064
  async validateTasksNextStep(params, nextStep, _currentPayload, _agentRun, _currentStep) {
5757
6065
  const spec = nextStep.taskGraph?.spec;
@@ -5764,16 +6072,27 @@ export class BaseAgent {
5764
6072
  };
5765
6073
  const extractNodeActionNames = (node) => {
5766
6074
  const loopOp = ConfigOf(node, 'ForEach') ?? ConfigOf(node, 'While');
5767
- return [ConfigOf(node, 'Action')?.actionName, loopOp?.action?.name].filter((n) => typeof n === 'string' && n.trim().length > 0);
6075
+ return [
6076
+ ConfigOf(node, 'Action')?.actionName,
6077
+ loopOp?.action?.name,
6078
+ ...(loopOp?.steps?.map((s) => s.name) ?? [])
6079
+ ].filter((n) => typeof n === 'string' && n.trim().length > 0);
5768
6080
  };
5769
6081
  const referencedAgents = [...new Set(spec.tasks.flatMap(extractNodeAgentNames))];
5770
6082
  const referencedActions = [...new Set(spec.tasks.flatMap(extractNodeActionNames))];
6083
+ const hostAllowedIds = HostAllowedAgentIDs(params.data);
6084
+ const disallowedAgents = [];
5771
6085
  const invalidAgents = [];
5772
- const allAgents = AIEngine.Instance?.Agents ?? [];
5773
- if (referencedAgents.length > 0 && allAgents.length > 0) {
6086
+ const activeAgents = (AIEngine.Instance?.Agents ?? []).filter(a => a.Status === 'Active');
6087
+ if (referencedAgents.length > 0 && (activeAgents.length > 0 || hostAllowedIds !== undefined)) {
5774
6088
  for (const agentName of referencedAgents) {
5775
6089
  const normalized = agentName.trim().toLowerCase();
5776
- const matched = allAgents.find(a => a.Status === 'Active' && a.Name?.trim().toLowerCase() === normalized);
6090
+ const matched = activeAgents.find(a => a.Name?.trim().toLowerCase() === normalized)
6091
+ ?? this.matchNamedBySanitizedToolName(agentName, activeAgents, true).match;
6092
+ if (hostAllowedIds !== undefined && (!matched || KeepHostAllowedAgents([matched], hostAllowedIds).length === 0)) {
6093
+ disallowedAgents.push(agentName);
6094
+ continue;
6095
+ }
5777
6096
  const permitted = matched
5778
6097
  ? params.contextUser
5779
6098
  ? await AIAgentPermissionHelper.HasPermission(matched.ID, params.contextUser, 'run')
@@ -5784,12 +6103,31 @@ export class BaseAgent {
5784
6103
  }
5785
6104
  }
5786
6105
  }
6106
+ if (disallowedAgents.length > 0) {
6107
+ const subject = disallowedAgents.join(', ');
6108
+ const refusalMessage = disallowedAgents.length === 1
6109
+ ? `${subject} isn't available in this chat, so it didn't run.`
6110
+ : `${subject} aren't available in this chat, so they didn't run.`;
6111
+ this.logError(refusalMessage, {
6112
+ agent: params.agent,
6113
+ category: 'NextStepValidation'
6114
+ });
6115
+ return {
6116
+ step: 'Failed',
6117
+ terminate: true,
6118
+ message: refusalMessage,
6119
+ errorMessage: refusalMessage,
6120
+ previousPayload: nextStep.previousPayload,
6121
+ newPayload: nextStep.newPayload || nextStep.previousPayload
6122
+ };
6123
+ }
5787
6124
  const invalidActions = [];
5788
- const allActions = ActionEngineServer.Instance?.Actions ?? [];
5789
- if (referencedActions.length > 0 && allActions.length > 0) {
6125
+ const activeActions = (ActionEngineServer.Instance?.Actions ?? []).filter(act => act.Status === 'Active');
6126
+ if (referencedActions.length > 0 && activeActions.length > 0) {
5790
6127
  for (const actionName of referencedActions) {
5791
6128
  const normalized = actionName.trim().toLowerCase();
5792
- const matched = allActions.find(act => act.Status === 'Active' && act.Name?.trim().toLowerCase() === normalized);
6129
+ const matched = activeActions.find(act => act.Name?.trim().toLowerCase() === normalized)
6130
+ ?? this.matchNamedBySanitizedToolName(actionName, activeActions).match;
5793
6131
  if (!matched) {
5794
6132
  invalidActions.push(actionName);
5795
6133
  }
@@ -5832,28 +6170,16 @@ export class BaseAgent {
5832
6170
  */
5833
6171
  async validateActionsNextStep(params, nextStep, currentPayload, agentRun, currentStep) {
5834
6172
  // Use effective actions which includes runtime action changes (populated in gatherPromptTemplateData)
5835
- // Fall back to database-configured actions if _effectiveActions is empty
6173
+ // Falls back to database-configured actions only when the list was never computed for this run
5836
6174
  const effectiveActions = this.getEffectiveActionsForValidation(params.agent.ID);
5837
6175
  // Also get the database-configured agent actions for MaxExecutionsPerRun lookup
5838
6176
  const dbAgentActions = AIEngine.Instance.AgentActions.filter(aa => UUIDsEqual(aa.AgentID, params.agent.ID) && aa.Status === 'Active');
6177
+ const resolvedByAction = new Map();
5839
6178
  const missingActions = nextStep.actions?.filter(action => {
5840
- const actionName = action.name.trim().toLowerCase();
5841
- // Try exact match first against effective actions (by Name property)
5842
- const exactMatch = effectiveActions.find(a => a.Name.trim().toLowerCase() === actionName);
5843
- if (exactMatch)
5844
- return false; // Found exact match, not missing
5845
- // Fallback: Try CONTAINS search for partial matches
5846
- const containsMatches = effectiveActions.filter(a => a.Name.trim().toLowerCase().includes(actionName));
5847
- if (containsMatches.length === 1) {
5848
- // Exactly one partial match - use it and update action name
5849
- const correctedName = containsMatches[0].Name;
5850
- this.logStatus(`Action name fuzzy matched: '${action.name}' → '${correctedName}'`, true, params);
5851
- action.name = correctedName; // Update to correct full name
5852
- return false; // Found via contains, not missing
5853
- }
5854
- // No matches or ambiguous (multiple matches) - it's missing
5855
- if (containsMatches.length > 1) {
5856
- this.logStatus(`Ambiguous action name '${action.name}' matches ${containsMatches.length} actions: ${containsMatches.map(a => a.Name).join(', ')}`, true, params);
6179
+ const matched = this.resolveActionEntityForAgent(action.name, effectiveActions, params, true);
6180
+ if (matched) {
6181
+ resolvedByAction.set(action, matched);
6182
+ return false;
5857
6183
  }
5858
6184
  return true;
5859
6185
  });
@@ -5879,7 +6205,8 @@ export class BaseAgent {
5879
6205
  if (nextStep.actions) {
5880
6206
  const violatedActions = [];
5881
6207
  for (const action of nextStep.actions) {
5882
- const actionEntity = effectiveActions.find(a => a.Name.trim().toLowerCase() === action.name.trim().toLowerCase());
6208
+ const actionEntity = resolvedByAction.get(action)
6209
+ ?? effectiveActions.find(a => a.Name.trim().toLowerCase() === action.name.trim().toLowerCase());
5883
6210
  if (!actionEntity)
5884
6211
  continue;
5885
6212
  // Check for limit from database-configured agent action
@@ -5925,7 +6252,8 @@ export class BaseAgent {
5925
6252
  }
5926
6253
  /**
5927
6254
  * Gets the effective actions for validation, using runtime changes if available.
5928
- * Falls back to database-configured actions if _effectiveActions is empty.
6255
+ * Falls back to database-configured actions only when the list was never computed for this run;
6256
+ * a computed empty list (a host's actionChanges removed every action) is returned as-is.
5929
6257
  *
5930
6258
  * @param agentId - The ID of the agent to get actions for
5931
6259
  * @returns Array of effective actions available to the agent
@@ -5933,16 +6261,172 @@ export class BaseAgent {
5933
6261
  * @since 2.123.0
5934
6262
  */
5935
6263
  getEffectiveActionsForValidation(agentId) {
5936
- if (this._effectiveActions.length > 0) {
6264
+ if (this._effectiveCatalogComputed || this._effectiveActions.length > 0) {
5937
6265
  return this._effectiveActions;
5938
6266
  }
5939
6267
  // Fallback: compute from database configuration
5940
6268
  const agentActions = AIEngine.Instance.AgentActions.filter(aa => UUIDsEqual(aa.AgentID, agentId) && aa.Status === 'Active');
5941
6269
  return ActionEngineServer.Instance.Actions.filter(a => agentActions.some(aa => UUIDsEqual(aa.ActionID, a.ID)) && a.Status === 'Active');
5942
6270
  }
6271
+ /**
6272
+ * Returns active actions referenced directly by an agent's Flow steps (`AIAgentStep.ActionID`
6273
+ * plus any `steps[].name` inside a `ForEach`/`While` Flow step's `Configuration` JSON).
6274
+ * Flow agents bind actions on `AIAgentStep` rather than `AIAgentAction`, so in-run Flow loops
6275
+ * need these actions in scope alongside {@link getEffectiveActionsForValidation}.
6276
+ */
6277
+ getFlowStepActions(agentId) {
6278
+ const allActions = ActionEngineServer.Instance?.Actions;
6279
+ if (!Array.isArray(allActions) || allActions.length === 0 || !agentId) {
6280
+ return [];
6281
+ }
6282
+ const agentSteps = AIEngine.Instance.GetAgentSteps?.(agentId) || [];
6283
+ if (agentSteps.length === 0) {
6284
+ return [];
6285
+ }
6286
+ const stepActionIds = new UUIDSet(agentSteps.map((s) => s.ActionID).filter((id) => typeof id === 'string' && id.length > 0));
6287
+ const stepActionNamesLower = new Set();
6288
+ const stepActionNamesSanitized = new Set();
6289
+ for (const s of agentSteps) {
6290
+ if (!s.Configuration)
6291
+ continue;
6292
+ try {
6293
+ const cfg = JSON.parse(s.Configuration);
6294
+ if (Array.isArray(cfg?.steps)) {
6295
+ for (const bodyStep of cfg.steps) {
6296
+ const raw = bodyStep?.name?.trim();
6297
+ if (raw) {
6298
+ stepActionNamesLower.add(raw.toLowerCase());
6299
+ const san = SanitizeToolName(raw);
6300
+ if (san)
6301
+ stepActionNamesSanitized.add(san);
6302
+ }
6303
+ }
6304
+ }
6305
+ }
6306
+ catch {
6307
+ // Malformed step configuration JSON is reported by FlowAgentType when that step runs.
6308
+ }
6309
+ }
6310
+ return allActions.filter((a) => a.Status !== 'Disabled' &&
6311
+ (stepActionIds.Has(a.ID) ||
6312
+ stepActionNamesLower.has(a.Name.trim().toLowerCase()) ||
6313
+ stepActionNamesSanitized.has(SanitizeToolName(a.Name))));
6314
+ }
6315
+ /**
6316
+ * Combines {@link getEffectiveActionsForValidation} with {@link getFlowStepActions} (deduplicated
6317
+ * by `ID`) so both Loop agents (strictly `AIAgentAction` / `_effectiveActions`) and Flow agents
6318
+ * (`AIAgentStep` / `Configuration.steps[]`) resolve permitted actions consistently.
6319
+ */
6320
+ getAvailableActionsForAgent(agentId) {
6321
+ const effective = this.getEffectiveActionsForValidation(agentId);
6322
+ const flowActions = this.getFlowStepActions(agentId);
6323
+ if (flowActions.length === 0) {
6324
+ return effective;
6325
+ }
6326
+ const seen = new UUIDSet(effective.map((a) => a.ID));
6327
+ const combined = [...effective];
6328
+ for (const fa of flowActions) {
6329
+ if (!seen.Has(fa.ID)) {
6330
+ seen.Add(fa.ID);
6331
+ combined.push(fa);
6332
+ }
6333
+ }
6334
+ return combined;
6335
+ }
6336
+ /**
6337
+ * Resolves an action name against `pool` without mutating caller objects:
6338
+ * 1) exact case-insensitive match, 2) unambiguous sanitized native tool-name match,
6339
+ * 3) unambiguous CONTAINS partial match.
6340
+ */
6341
+ resolveActionEntityForAgent(rawName, pool, params, logMatches = false) {
6342
+ const trimmedLower = rawName.trim().toLowerCase();
6343
+ if (!trimmedLower) {
6344
+ return undefined;
6345
+ }
6346
+ const exact = pool.find((a) => a.Name.trim().toLowerCase() === trimmedLower);
6347
+ if (exact) {
6348
+ return exact;
6349
+ }
6350
+ const sanitizedMatch = this.matchNamedBySanitizedToolName(rawName, pool);
6351
+ if (sanitizedMatch.match) {
6352
+ if (logMatches && params) {
6353
+ this.logStatus(`Action native tool name matched: '${rawName}' → '${sanitizedMatch.match.Name}'`, true, params);
6354
+ }
6355
+ return sanitizedMatch.match;
6356
+ }
6357
+ if (sanitizedMatch.ambiguous) {
6358
+ if (logMatches && params) {
6359
+ this.logStatus(`Ambiguous action tool name '${rawName}' matches ${sanitizedMatch.ambiguous.length} actions: ${sanitizedMatch.ambiguous.map((a) => a.Name).join(', ')}`, true, params);
6360
+ }
6361
+ return undefined;
6362
+ }
6363
+ const containsMatches = pool.filter((a) => a.Name.trim().toLowerCase().includes(trimmedLower));
6364
+ if (containsMatches.length === 1) {
6365
+ if (logMatches && params) {
6366
+ this.logStatus(`Action name fuzzy matched: '${rawName}' → '${containsMatches[0].Name}'`, true, params);
6367
+ }
6368
+ return containsMatches[0];
6369
+ }
6370
+ if (containsMatches.length > 1 && logMatches && params) {
6371
+ this.logStatus(`Ambiguous action name '${rawName}' matches ${containsMatches.length} actions: ${containsMatches.map((a) => a.Name).join(', ')}`, true, params);
6372
+ }
6373
+ return undefined;
6374
+ }
6375
+ /**
6376
+ * Returns a deep-cloned `TaskGraphSpec` with sanitized native tool names (`calculate_expression`,
6377
+ * `delegate_to_query_builder`) canonicalized to exact metadata names before durable submission,
6378
+ * without mutating the caller's `spec`.
6379
+ */
6380
+ canonicalizeTaskGraphSpec(spec) {
6381
+ const cloned = this.cloneSubAgentPayload(spec);
6382
+ const activeAgents = (AIEngine.Instance?.Agents ?? []).filter((a) => a.Status === 'Active');
6383
+ const activeActions = (ActionEngineServer.Instance?.Actions ?? []).filter((act) => act.Status === 'Active');
6384
+ const resolveAgent = (name) => {
6385
+ if (!name)
6386
+ return name;
6387
+ const lower = name.trim().toLowerCase();
6388
+ const found = activeAgents.find((a) => a.Name?.trim().toLowerCase() === lower)
6389
+ ?? this.matchNamedBySanitizedToolName(name, activeAgents, true).match;
6390
+ return found?.Name ?? name;
6391
+ };
6392
+ const resolveAction = (name) => {
6393
+ if (!name)
6394
+ return name;
6395
+ const lower = name.trim().toLowerCase();
6396
+ const found = activeActions.find((act) => act.Name?.trim().toLowerCase() === lower)
6397
+ ?? this.matchNamedBySanitizedToolName(name, activeActions).match;
6398
+ return found?.Name ?? name;
6399
+ };
6400
+ for (const node of cloned.tasks ?? []) {
6401
+ const agentCfg = ConfigOf(node, 'Agent');
6402
+ if (agentCfg?.agentName) {
6403
+ agentCfg.agentName = resolveAgent(agentCfg.agentName);
6404
+ }
6405
+ const actionCfg = ConfigOf(node, 'Action');
6406
+ if (actionCfg?.actionName) {
6407
+ actionCfg.actionName = resolveAction(actionCfg.actionName);
6408
+ }
6409
+ const loopOp = ConfigOf(node, 'ForEach') ?? ConfigOf(node, 'While');
6410
+ if (loopOp?.subAgent?.name) {
6411
+ loopOp.subAgent.name = resolveAgent(loopOp.subAgent.name);
6412
+ }
6413
+ if (loopOp?.action?.name) {
6414
+ loopOp.action.name = resolveAction(loopOp.action.name);
6415
+ }
6416
+ if (Array.isArray(loopOp?.steps)) {
6417
+ for (const step of loopOp.steps) {
6418
+ if (step.name) {
6419
+ step.name = resolveAction(step.name);
6420
+ }
6421
+ }
6422
+ }
6423
+ }
6424
+ return cloned;
6425
+ }
5943
6426
  /**
5944
6427
  * Gets the effective sub-agents for validation, using runtime subAgentChanges if available.
5945
- * Falls back to the database-configured relationship set if _effectiveSubAgents is empty.
6428
+ * Falls back to the database-configured relationship set only when the list was never computed
6429
+ * for this run; a computed empty list is returned as-is.
5946
6430
  * Mirrors {@link getEffectiveActionsForValidation}.
5947
6431
  *
5948
6432
  * @param agentId - The ID of the agent to get sub-agents for
@@ -5950,7 +6434,7 @@ export class BaseAgent {
5950
6434
  * @protected
5951
6435
  */
5952
6436
  getEffectiveSubAgentsForValidation(agentId) {
5953
- if (this._effectiveSubAgents.length > 0) {
6437
+ if (this._effectiveCatalogComputed || this._effectiveSubAgents.length > 0) {
5954
6438
  return this._effectiveSubAgents;
5955
6439
  }
5956
6440
  // Fallback: compute from database configuration (ParentID children + AgentRelationships)
@@ -6057,6 +6541,84 @@ export class BaseAgent {
6057
6541
  }
6058
6542
  return nextStep;
6059
6543
  }
6544
+ /**
6545
+ * Validates a `'Handoff'` next step: re-checks the runtime withholding conditions (sub-agent run,
6546
+ * missing `conversationDetailId`, or missing `handoffChain`) and validates the requested target
6547
+ * via {@link ResolveHandoffTarget} (Active status, `'view'` and `'run'` permissions, direct
6548
+ * discoverability, host allow-list, cycle check, and hop limit). On refusal, writes a Failed
6549
+ * `'Handoff'` step and returns a `'Retry'` step naming up to 20 candidate agents; on approval,
6550
+ * stores the resolved target ID and name for {@link executeHandoffStep}.
6551
+ *
6552
+ * @protected
6553
+ */
6554
+ async validateHandoffNextStep(params, nextStep, _currentPayload, _agentRun, _currentStep) {
6555
+ if (this.runWithholdsHandoff(params)) {
6556
+ if (nextStep.step !== 'Retry') {
6557
+ this._generalValidationRetryCount++;
6558
+ }
6559
+ return {
6560
+ step: 'Retry',
6561
+ terminate: false,
6562
+ message: 'Handoff is not available here, so nextStep.type must never be "Handoff". ' +
6563
+ 'Answer directly, or use nextStep.type "Sub-Agent" or "Actions" instead.',
6564
+ errorMessage: 'Handoff is not available on this run'
6565
+ };
6566
+ }
6567
+ const requestedName = nextStep.handoff?.agentName ?? '';
6568
+ const brief = nextStep.handoff?.brief ?? '';
6569
+ const reason = nextStep.handoff?.reason ?? '';
6570
+ const data = WithAgentRunDataTrustApplied(params).Params.data;
6571
+ const resolution = await ResolveHandoffTarget({
6572
+ AgentName: requestedName,
6573
+ SourceAgentID: params.agent.ID,
6574
+ HandoffChain: params.handoffChain ?? [],
6575
+ HostAllowedIDs: HostAllowedAgentIDs(data),
6576
+ ContextUser: params.contextUser,
6577
+ Agents: AIEngine.Instance.Agents,
6578
+ });
6579
+ if (resolution.Refusal) {
6580
+ const refusal = resolution.Refusal;
6581
+ this.logError(`Handoff target agent '${requestedName}' refused (${refusal.Reason}) for agent '${params.agent.Name}': ${refusal.Message}`, {
6582
+ agent: params.agent,
6583
+ category: 'NextStepValidation'
6584
+ });
6585
+ await this.createStepEntity({
6586
+ stepType: 'Handoff',
6587
+ stepName: `Handoff: ${requestedName.trim() || '(unknown)'}`,
6588
+ contextUser: params.contextUser,
6589
+ inputData: {
6590
+ agentName: requestedName,
6591
+ brief,
6592
+ reason
6593
+ },
6594
+ completed: {
6595
+ success: false,
6596
+ errorMessage: refusal.Message,
6597
+ outputData: {
6598
+ RefusalReason: refusal.Reason,
6599
+ AgentName: requestedName,
6600
+ Brief: brief,
6601
+ Reason: reason
6602
+ }
6603
+ }
6604
+ });
6605
+ if (nextStep.step !== 'Retry') {
6606
+ this._generalValidationRetryCount++;
6607
+ }
6608
+ return {
6609
+ step: 'Retry',
6610
+ terminate: false,
6611
+ message: refusal.Message,
6612
+ errorMessage: refusal.Message
6613
+ };
6614
+ }
6615
+ const target = resolution.Target;
6616
+ this._resolvedHandoffTarget = { id: target.ID, name: target.Name };
6617
+ if (nextStep.handoff) {
6618
+ nextStep.handoff = { ...nextStep.handoff, agentName: target.Name };
6619
+ }
6620
+ return nextStep;
6621
+ }
6060
6622
  /**
6061
6623
  * Validates that the Success next step is valid and can be executed by the current agent. Subclasses can override
6062
6624
  * this method to implement custom validation logic if needed.
@@ -6277,22 +6839,89 @@ export class BaseAgent {
6277
6839
  // currently the base class doesn't do anything, subclasses can implement any custom logic in their override
6278
6840
  return nextStep;
6279
6841
  }
6842
+ /**
6843
+ * Resolves the effective `ChatHandlingOption` for a sub-agent execution:
6844
+ * `relationship?.ChatHandlingOption ?? parentAgent.ChatHandlingOption ?? null`.
6845
+ * @private
6846
+ */
6847
+ resolveSubAgentChatHandlingOption(parentAgent, relationship) {
6848
+ return relationship?.ChatHandlingOption ?? parentAgent.ChatHandlingOption ?? null;
6849
+ }
6850
+ /**
6851
+ * Returns `true` only when `resolvedOption === 'Consult'` AND the parent agent's
6852
+ * type supports injecting loop/consult messages into conversation history
6853
+ * (`this.AgentTypeInstance?.InjectLoopResultsAsMessage !== false`).
6854
+ *
6855
+ * When `resolvedOption === 'Consult'` and `this.AgentTypeInstance?.InjectLoopResultsAsMessage === false`
6856
+ * (e.g., a Flow parent), logs a warning once per run and returns `false` so `'Consult'`
6857
+ * is treated as `null` (propagate).
6858
+ * @private
6859
+ */
6860
+ isSubAgentConsultActive(resolvedOption, params) {
6861
+ if (resolvedOption !== 'Consult') {
6862
+ return false;
6863
+ }
6864
+ if (this.AgentTypeInstance?.InjectLoopResultsAsMessage === false) {
6865
+ if (!this._loggedConsultUnsupportedAgentType) {
6866
+ this._loggedConsultUnsupportedAgentType = true;
6867
+ this.logStatus("⚠️ ChatHandlingOption 'Consult' is not supported for agent types where InjectLoopResultsAsMessage is false; treating as null (propagate).", false, params);
6868
+ }
6869
+ return false;
6870
+ }
6871
+ return true;
6872
+ }
6873
+ /**
6874
+ * Resolves the sub-agent `ChatHandlingOption` and downgrades `'Consult'` to `null`
6875
+ * when `isSubAgentConsultActive` returns `false` (e.g., on Flow parents).
6876
+ * @private
6877
+ */
6878
+ effectiveSubAgentChatHandlingOption(parentAgent, relationship, params) {
6879
+ const resolved = this.resolveSubAgentChatHandlingOption(parentAgent, relationship);
6880
+ if (resolved === 'Consult' && !this.isSubAgentConsultActive(resolved, params)) {
6881
+ return null;
6882
+ }
6883
+ return resolved;
6884
+ }
6885
+ /**
6886
+ * Side-effect-free check used during prompt and native-tool construction to determine
6887
+ * whether `'Consult'` is active for a specific sub-agent of `parentAgent`.
6888
+ * @private
6889
+ */
6890
+ isSubAgentConsultEnabledForSubAgent(parentAgent, subAgent) {
6891
+ if (this.AgentTypeInstance?.InjectLoopResultsAsMessage === false) {
6892
+ return false;
6893
+ }
6894
+ const isDirectChild = subAgent.ParentID != null && UUIDsEqual(subAgent.ParentID, parentAgent.ID);
6895
+ const relationship = isDirectChild
6896
+ ? undefined
6897
+ : (AIEngine.Instance.AgentRelationships ?? []).find(r => UUIDsEqual(r.AgentID, parentAgent.ID) && UUIDsEqual(r.SubAgentID, subAgent.ID) && r.Status === 'Active');
6898
+ return this.resolveSubAgentChatHandlingOption(parentAgent, relationship) === 'Consult';
6899
+ }
6280
6900
  /**
6281
6901
  * Validates that the Chat next step is valid and can be executed by the current agent.
6282
- * Implements ChatHandlingOption remapping logic - if the agent has ChatHandlingOption set,
6283
- * the Chat step is remapped to the specified value (Success, Fail, or Retry).
6902
+ * Implements ChatHandlingOption remapping logic - if the agent (or sub-agent relationship)
6903
+ * has ChatHandlingOption set:
6904
+ * - `'Consult'`: leaves the Chat step unchanged (an agent's own Chat propagates to its caller;
6905
+ * sub-agent Consult is intercepted before this validator).
6906
+ * - `'Success'` / `'Failed'`: remaps `step` while preserving `terminate: true` to end the run.
6907
+ * - `'Retry'`: remaps `step` to `'Retry'`, sets `terminate: false` so the loop continues, and
6908
+ * populates `errorMessage` so the unproductive-retry safety net bounds repeated Chat attempts.
6284
6909
  * Subclasses can override this method to implement custom validation logic if needed.
6285
6910
  * @param params
6286
6911
  * @param nextStep
6287
6912
  * @returns
6288
6913
  */
6289
- async validateChatNextStep(params, nextStep, currentPayload, agentRun, currentStep) {
6290
- // Check if the agent has ChatHandlingOption configured
6291
- const chatHandlingOption = params.agent.ChatHandlingOption;
6292
- if (chatHandlingOption) {
6914
+ async validateChatNextStep(params, nextStep, currentPayload, agentRun, currentStep, chatHandlingOption) {
6915
+ // Use caller-resolved option when provided; otherwise fall back to params.agent.ChatHandlingOption
6916
+ const effectiveOption = chatHandlingOption !== undefined
6917
+ ? chatHandlingOption
6918
+ : params.agent.ChatHandlingOption;
6919
+ if (effectiveOption) {
6293
6920
  // Use a switch to validate and map the ChatHandlingOption value
6294
6921
  let mappedStep;
6295
- switch (chatHandlingOption) {
6922
+ switch (effectiveOption) {
6923
+ case 'Consult':
6924
+ return nextStep;
6296
6925
  case 'Success':
6297
6926
  mappedStep = 'Success';
6298
6927
  break;
@@ -6304,17 +6933,26 @@ export class BaseAgent {
6304
6933
  break;
6305
6934
  default:
6306
6935
  // Log error and treat as null (default behavior)
6307
- LogError(`Invalid ChatHandlingOption value: ${chatHandlingOption}. Expected 'Success', 'Failed', or 'Retry'. Treating as null and allowing Chat to propagate.`);
6936
+ LogError(`Invalid ChatHandlingOption value: ${effectiveOption}. Expected 'Consult', 'Success', 'Failed', or 'Retry'. Treating as null and allowing Chat to propagate.`);
6308
6937
  return nextStep;
6309
6938
  }
6310
- // Remap the Chat step to the configured option
6311
- const remappedStep = {
6312
- ...nextStep,
6313
- step: mappedStep
6314
- };
6939
+ // Remap the Chat step to the configured option.
6940
+ // Retry sets terminate to false so the loop continues and sets errorMessage so the
6941
+ // unproductive-retry cap bounds a model that repeatedly emits Chat.
6942
+ const remappedStep = mappedStep === 'Retry'
6943
+ ? {
6944
+ ...nextStep,
6945
+ step: 'Retry',
6946
+ terminate: false,
6947
+ errorMessage: nextStep.errorMessage || 'Chat was remapped to Retry by ChatHandlingOption'
6948
+ }
6949
+ : {
6950
+ ...nextStep,
6951
+ step: mappedStep
6952
+ };
6315
6953
  // Log the remapping for debugging
6316
6954
  if (params.verbose === true || IsVerboseLoggingEnabled()) {
6317
- LogStatus(`Remapping Chat step to ${chatHandlingOption} based on agent's ChatHandlingOption`);
6955
+ LogStatus(`Remapping Chat step to ${effectiveOption} based on agent's ChatHandlingOption`);
6318
6956
  }
6319
6957
  // Re-validate the remapped step using the appropriate validator
6320
6958
  return await this.validateNextStep(params, remappedStep, currentPayload, agentRun, currentStep);
@@ -7524,7 +8162,7 @@ The context is now within limits. Please retry your request with the recovered c
7524
8162
  async processNextStep(nextStep, params, agentType, promptResult, currentPayload, currentStep) {
7525
8163
  const validatedNextStep = await this.validateNextStep(params, nextStep, currentPayload, this._agentRun, currentStep);
7526
8164
  // Check guardrails if next step would continue execution
7527
- const guardrailCheckedStep = await this.checkExecutionGuardrails(params, validatedNextStep, currentPayload, this._agentRun, currentStep);
8165
+ const guardrailCheckedStep = this.noteDiscardedCompletionChange(nextStep, await this.checkExecutionGuardrails(params, validatedNextStep, currentPayload, this._agentRun, currentStep));
7528
8166
  this.logStatus(`📌 Next step determined: ${guardrailCheckedStep.step}${guardrailCheckedStep.terminate ? ' (terminating)' : ''}`, true, params);
7529
8167
  // the model's own call turn goes into history before anything answers it.
7530
8168
  this.appendNativeAssistantTurn(params, guardrailCheckedStep);
@@ -7568,6 +8206,25 @@ The context is now within limits. Please retry your request with the recovered c
7568
8206
  // Return the next step directly - execution handling is done in execute NextStep
7569
8207
  return guardrailCheckedStep;
7570
8208
  }
8209
+ /**
8210
+ * A completion refused with a payload change in hand: the change is discarded (the prompt step
8211
+ * commits it only for an accepted completion), so the refusal the model reads says so, and asks
8212
+ * for the change again with the next completion. Otherwise the model would take the change as
8213
+ * saved and its work would be lost. The change is removed from the step, so nothing later
8214
+ * applies it. Any other step is returned as it is.
8215
+ */
8216
+ noteDiscardedCompletionChange(original, step) {
8217
+ if (!BaseAgent.carriesCompletionChange(original) || step.step === 'Success') {
8218
+ return step;
8219
+ }
8220
+ const native = !!step.payloadToolCallId && this.nativeToolNameForCall(step, step.payloadToolCallId) === COMPLETE_TASK_TOOL;
8221
+ const note = native
8222
+ ? 'The payloadChangeRequest sent with this complete_task call was NOT applied. Send it again with your next complete_task call.'
8223
+ : 'The payloadChangeRequest sent with this completion was NOT applied. Send it again with your next completion.';
8224
+ const field = step.retryInstructions ? 'retryInstructions' : step.message ? 'message' : 'errorMessage';
8225
+ const { payloadChangeRequest: _discarded, ...rest } = step;
8226
+ return { ...rest, [field]: step[field] ? `${step[field]}\n\n${note}` : note };
8227
+ }
7571
8228
  /**
7572
8229
  * Answers a retried native tool-call turn in the protocol itself: every call gets an `is_error`
7573
8230
  * result carrying the retry reason, and no user message follows.
@@ -7794,6 +8451,101 @@ The context is now within limits. Please retry your request with the recovered c
7794
8451
  this.logStatus(`[StoppedRunResults] Skipped (contained error): ${error instanceof Error ? error.message : error}`, true, params);
7795
8452
  }
7796
8453
  }
8454
+ /**
8455
+ * Loads unanswered sub-agent consultations (`OutputData.consult`) from `params.lastRunId` when that
8456
+ * prior run paused with `FinalStep === 'Chat'` (and was not stopped by the user). Runs at any depth
8457
+ * so a middle agent resumed via `resumeRunId` also reloads its own open child consults. Fail-soft.
8458
+ * @private
8459
+ */
8460
+ async loadOpenConsults(params) {
8461
+ if (!params.lastRunId || !IsValidUUID(params.lastRunId) || !CanAgentOwnSubAgentConsults(params.agent)) {
8462
+ return [];
8463
+ }
8464
+ try {
8465
+ const rv = RunView.FromMetadataProvider(this.ProviderToUse);
8466
+ const runResult = await rv.RunView({
8467
+ EntityName: 'MJ: AI Agent Runs',
8468
+ ExtraFilter: `ID='${params.lastRunId}'`,
8469
+ MaxRows: 1,
8470
+ Fields: ['ID', 'FinalStep', 'Status', 'CancellationReason'],
8471
+ ResultType: 'simple',
8472
+ BypassCache: true,
8473
+ }, params.contextUser);
8474
+ const priorRun = runResult.Success ? runResult.Results?.[0] : undefined;
8475
+ if (!priorRun ||
8476
+ priorRun.FinalStep !== 'Chat' ||
8477
+ MJAIAgentRunEntityExtended.IsUserStopped(priorRun.Status, priorRun.CancellationReason)) {
8478
+ return [];
8479
+ }
8480
+ return await LoadOpenSubAgentConsults(this.ProviderToUse, params.lastRunId, params.contextUser);
8481
+ }
8482
+ catch (error) {
8483
+ this.logStatus(`[SubAgentConsult] Skipped loading open consults (contained error): ${error instanceof Error ? error.message : error}`, true, params);
8484
+ return [];
8485
+ }
8486
+ }
8487
+ /**
8488
+ * Restores reloaded open sub-agent consults into `this._openSubAgentConsults` (so `resumeRunId`
8489
+ * validation accepts them) and splices a `sub-agent-consult` reminder message immediately before
8490
+ * `continuationMessage` (the caller's answer). Fail-soft.
8491
+ * @private
8492
+ */
8493
+ applyOpenConsults(params, openConsults, continuationMessage) {
8494
+ if (!openConsults || openConsults.length === 0) {
8495
+ return;
8496
+ }
8497
+ try {
8498
+ for (const consult of openConsults) {
8499
+ if (consult.childRunId) {
8500
+ this._openSubAgentConsults.set(consult.childRunId, consult);
8501
+ }
8502
+ }
8503
+ const content = FormatReloadedConsultsMessage(openConsults);
8504
+ if (!content) {
8505
+ return;
8506
+ }
8507
+ const metadata = {
8508
+ turnAdded: 0,
8509
+ messageType: 'sub-agent-consult',
8510
+ ...(openConsults.length === 1
8511
+ ? {
8512
+ subAgentName: openConsults[0].subAgentName,
8513
+ subAgentId: openConsults[0].subAgentId,
8514
+ }
8515
+ : {}),
8516
+ expirationTurns: 3,
8517
+ expirationMode: 'Remove',
8518
+ };
8519
+ const consultReminder = {
8520
+ role: 'user',
8521
+ content,
8522
+ metadata,
8523
+ };
8524
+ const at = continuationMessage ? params.conversationMessages.indexOf(continuationMessage) : -1;
8525
+ if (at >= 0) {
8526
+ params.conversationMessages.splice(at, 0, consultReminder);
8527
+ }
8528
+ else {
8529
+ let lastUserIdx = -1;
8530
+ for (let i = params.conversationMessages.length - 1; i >= 0; i--) {
8531
+ if (params.conversationMessages[i].role === 'user') {
8532
+ lastUserIdx = i;
8533
+ break;
8534
+ }
8535
+ }
8536
+ if (lastUserIdx >= 0) {
8537
+ params.conversationMessages.splice(lastUserIdx, 0, consultReminder);
8538
+ }
8539
+ else {
8540
+ params.conversationMessages.push(consultReminder);
8541
+ }
8542
+ }
8543
+ this.logStatus(`[SubAgentConsult] Reloaded ${openConsults.length} open consult(s) from prior run ${params.lastRunId}`, true, params);
8544
+ }
8545
+ catch (error) {
8546
+ this.logStatus(`[SubAgentConsult] Skipped applying open consults (contained error): ${error instanceof Error ? error.message : error}`, true, params);
8547
+ }
8548
+ }
7797
8549
  /**
7798
8550
  * The full-stack half of {@link applyStoppedRunContinuation}: true when the stopped run's turns were
7799
8551
  * spliced in. Any failure leaves the messages untouched and returns false, so the caller carries
@@ -8078,6 +8830,7 @@ The context is now within limits. Please retry your request with the recovered c
8078
8830
  ExtraFilter: MJAIAgentRunEntityExtended.BuildStoppedPredecessorFilter(params.conversationId, params.agent.ID, params.ConversationBranchID ?? null, this._conversationBranches),
8079
8831
  OrderBy: '__mj_CreatedAt DESC',
8080
8832
  MaxRows: 1,
8833
+ SkipTotalRowCount: true,
8081
8834
  Fields: ['ID', 'Status', 'CancellationReason'],
8082
8835
  ResultType: 'simple',
8083
8836
  // The row this looks for was written by the Stop button moments ago; read the database, not a cache.
@@ -8102,6 +8855,7 @@ The context is now within limits. Please retry your request with the recovered c
8102
8855
  EntityName: 'MJ: AI Agent Runs',
8103
8856
  ExtraFilter: `ID='${runId}'`,
8104
8857
  MaxRows: 1,
8858
+ SkipTotalRowCount: true,
8105
8859
  Fields: ['ID', 'Status', 'CancellationReason'],
8106
8860
  ResultType: 'simple',
8107
8861
  // The row this checks was written by the Stop button moments ago; read the database, not a cache.
@@ -8266,6 +9020,7 @@ The context is now within limits. Please retry your request with the recovered c
8266
9020
  ExtraFilter: BaseAgent.BuildPriorTurnRunFilter(params.conversationId, params.agent.ID, branchId, this._conversationBranches, statusList),
8267
9021
  OrderBy: '__mj_CreatedAt DESC',
8268
9022
  MaxRows: 1,
9023
+ SkipTotalRowCount: true,
8269
9024
  Fields: ['ID'],
8270
9025
  ResultType: 'simple',
8271
9026
  }, params.contextUser);
@@ -9456,7 +10211,12 @@ The context is now within limits. Please retry your request with the recovered c
9456
10211
  *
9457
10212
  * @private
9458
10213
  */
9459
- async gatherPromptTemplateData(agent, _contextUser, extraData, actionChanges, subAgentChanges, boundActionParams, withholding) {
10214
+ async gatherPromptTemplateData(agent, _contextUser, extraData, actionChanges, subAgentChanges, boundActionParams, withholdingOrParentRun, parentRun) {
10215
+ const isWithholdingShape = (val) => typeof val === 'object' && val !== null && 'TaskGraphs' in val;
10216
+ const withholding = isWithholdingShape(withholdingOrParentRun) ? withholdingOrParentRun : undefined;
10217
+ const resolvedParentRun = isWithholdingShape(withholdingOrParentRun)
10218
+ ? parentRun
10219
+ : (parentRun ?? withholdingOrParentRun);
9460
10220
  try {
9461
10221
  const engine = AIEngine.Instance;
9462
10222
  // Build (or reuse) the agent-invariant base catalog. This is process-wide cached on
@@ -9513,6 +10273,7 @@ The context is now within limits. Please retry your request with the recovered c
9513
10273
  this._effectiveActions = activeActions;
9514
10274
  // Store for later validation in validateSubAgentNextStep (see getEffectiveSubAgentsForValidation)
9515
10275
  this._effectiveSubAgents = uniqueActiveSubAgents;
10276
+ this._effectiveCatalogComputed = true;
9516
10277
  // Agent type prompt params: reuse cached base merge unless a runtime override is present.
9517
10278
  const runtimePromptParamOverrides = extraData?.__agentTypePromptParams;
9518
10279
  let agentTypePromptParams;
@@ -9534,6 +10295,9 @@ The context is now within limits. Please retry your request with the recovered c
9534
10295
  if (withholding?.TaskGraphs || this.hasBoundActionParams(boundActionParams)) {
9535
10296
  agentTypePromptParams = this.withoutTaskGraphs(agentTypePromptParams);
9536
10297
  }
10298
+ if (withholding?.Handoff) {
10299
+ agentTypePromptParams = this.withoutHandoff(agentTypePromptParams);
10300
+ }
9537
10301
  // Store for the finishIf gate, which runs after this prompt in executeActionsStep / executeNextStep
9538
10302
  this._agentTypePromptParams = agentTypePromptParams;
9539
10303
  // Skill catalog (name + description only — progressive disclosure). This is the
@@ -9557,6 +10321,20 @@ The context is now within limits. Please retry your request with the recovered c
9557
10321
  const skillsCatalog = this.narrowedCatalogSection('skill', availableSkills, this.formatSkillsCatalog(availableSkills), shown => this.formatSkillsCatalog(shown));
9558
10322
  // The client tools and the app context (per-run, from extraData) — neither under an audience (callerContextSections).
9559
10323
  const { clientToolDetails, appContext } = this.callerContextSections(agent, extraData, withholding?.CallerContext === true);
10324
+ const subAgentConsultEnabled = uniqueActiveSubAgents.some(sa => this.isSubAgentConsultEnabledForSubAgent(agent, sa));
10325
+ const subAgentPresetsAvailable = uniqueActiveSubAgents.some(sa => AIEngine.Instance.GetAgentConfigurationPresets(sa.ID, true).length > 0);
10326
+ let parentConsults = false;
10327
+ const effectiveParentRun = resolvedParentRun ?? this._executeParams?.parentRun;
10328
+ if (!isRoot && effectiveParentRun?.AgentID) {
10329
+ const parentAgent = (engine.Agents ?? []).find(a => UUIDsEqual(a.ID, effectiveParentRun.AgentID));
10330
+ if (parentAgent) {
10331
+ const isDirectChild = agent.ParentID != null && UUIDsEqual(agent.ParentID, parentAgent.ID);
10332
+ const relationship = isDirectChild
10333
+ ? undefined
10334
+ : (engine.AgentRelationships ?? []).find(r => UUIDsEqual(r.AgentID, parentAgent.ID) && UUIDsEqual(r.SubAgentID, agent.ID) && r.Status === 'Active');
10335
+ parentConsults = this.resolveSubAgentChatHandlingOption(parentAgent, relationship) === 'Consult';
10336
+ }
10337
+ }
9560
10338
  const cachedUserPolicy = _contextUser?.ID
9561
10339
  ? AgentUserPolicyEngine.Instance.GetCachedPolicy(agent.ID, _contextUser.ID)
9562
10340
  : null;
@@ -9585,6 +10363,9 @@ The context is now within limits. Please retry your request with the recovered c
9585
10363
  skillsCatalog: skillsCatalog,
9586
10364
  planModeActive: this._planModeActive,
9587
10365
  planApproved: this._planApproved,
10366
+ ...(subAgentConsultEnabled ? { subAgentConsultEnabled: true } : {}),
10367
+ ...(parentConsults ? { parentConsults: true } : {}),
10368
+ ...(subAgentPresetsAvailable ? { subAgentPresetsAvailable: true } : {}),
9588
10369
  appContext: appContext,
9589
10370
  };
9590
10371
  // Build the final result with __agentTypePromptParams injected
@@ -10125,7 +10906,8 @@ The context is now within limits. Please retry your request with the recovered c
10125
10906
  // that loop's `else` branch defaults an unset key to true, which is exactly what a gated
10126
10907
  // capability must never do.
10127
10908
  const gateMappings = [
10128
- { gateFlag: 'enableTaskGraphs', responseTypeKey: 'tasks' }
10909
+ { gateFlag: 'enableTaskGraphs', responseTypeKey: 'tasks' },
10910
+ { gateFlag: 'enableHandoff', responseTypeKey: 'handoff' }
10129
10911
  ];
10130
10912
  for (const { gateFlag, responseTypeKey } of gateMappings) {
10131
10913
  const wasExplicitlySet = explicitResponseType &&
@@ -10602,7 +11384,7 @@ The context is now within limits. Please retry your request with the recovered c
10602
11384
  const secondary = scope.SecondaryScopes
10603
11385
  ? Object.fromEntries(Object.entries(scope.SecondaryScopes).map(([key, value]) => [key, Array.isArray(value) ? [...value] : value]))
10604
11386
  : null;
10605
- return { ...scope, SecondaryScopes: secondary };
11387
+ return { ...scope, SecondaryScopes: secondary, ...(scope.SearchScopeIDs ? { SearchScopeIDs: [...scope.SearchScopeIDs] } : {}) };
10606
11388
  }
10607
11389
  /**
10608
11390
  * Logs one dispatched call's outcome and feeds the run-scoped circuit breaker, unless the caller does its own
@@ -10739,10 +11521,10 @@ The context is now within limits. Please retry your request with the recovered c
10739
11521
  return null;
10740
11522
  }
10741
11523
  const resultCode = evaluation.verdict === 'Deny'
10742
- ? 'POLICY_DENIED'
11524
+ ? POLICY_DENIED_RESULT_CODE
10743
11525
  : evaluation.verdict === 'DeferUntilNextWindow'
10744
- ? 'POLICY_DEFERRED_OUTSIDE_TIME_WINDOW'
10745
- : 'POLICY_APPROVAL_REQUIRED';
11526
+ ? POLICY_DEFERRED_RESULT_CODE
11527
+ : POLICY_APPROVAL_REQUIRED_RESULT_CODE;
10746
11528
  return {
10747
11529
  Success: false,
10748
11530
  ResultCode: resultCode,
@@ -10841,11 +11623,12 @@ The context is now within limits. Please retry your request with the recovered c
10841
11623
  * @param {AgentSubAgentRequest} subAgentRequest - Sub-agent request details
10842
11624
  * @param {MJAIAgentEntityExtended} subAgent - The sub-agent entity
10843
11625
  * @param {ChatMessage | undefined} contextMessage - Optional context from SubAgentContextPaths
11626
+ * @param {string | null | undefined} consultQuestion - Optional open-consult question when resuming a child run
10844
11627
  * @returns {ChatMessage[]} Prepared message array for sub-agent execution
10845
11628
  *
10846
11629
  * @protected
10847
11630
  */
10848
- prepareSubAgentMessages(params, subAgentRequest, subAgent, contextMessage) {
11631
+ prepareSubAgentMessages(params, subAgentRequest, subAgent, contextMessage, consultQuestion) {
10849
11632
  const engine = AIEngine.Instance;
10850
11633
  let messages = [];
10851
11634
  // Check for related sub-agent configuration (AIAgentRelationship)
@@ -10902,6 +11685,13 @@ The context is now within limits. Please retry your request with the recovered c
10902
11685
  if (contextMessage) {
10903
11686
  messages.push(contextMessage);
10904
11687
  }
11688
+ // On resume, insert the consult's question as an assistant turn right before the request message
11689
+ if (consultQuestion) {
11690
+ messages.push({
11691
+ role: 'assistant',
11692
+ content: consultQuestion
11693
+ });
11694
+ }
10905
11695
  if (subAgentRequest.message) {
10906
11696
  messages.push({
10907
11697
  role: 'user',
@@ -10941,8 +11731,29 @@ The context is now within limits. Please retry your request with the recovered c
10941
11731
  this.logStatus(`🤖 Executing sub-agent '${subAgentRequest.name}'`, true, params);
10942
11732
  // Create a new AgentRunner instance with the same isolated provider
10943
11733
  const runner = new AgentRunner(params.provider || this._activeProvider);
11734
+ // Look up an open consult matching both childRunId and subAgent.ID once.
11735
+ // Only resume when the consult is open for this sub-agent; otherwise log an error and run fresh.
11736
+ const requestedResumeRunId = subAgentRequest.resumeRunId?.trim() || undefined;
11737
+ let matchedConsult;
11738
+ if (requestedResumeRunId) {
11739
+ matchedConsult = Array.from(this._openSubAgentConsults.values()).find(c => UUIDsEqual(c.childRunId, requestedResumeRunId) && UUIDsEqual(c.subAgentId, subAgent.ID));
11740
+ if (matchedConsult) {
11741
+ this._openSubAgentConsults.delete(matchedConsult.childRunId);
11742
+ }
11743
+ else {
11744
+ this.logError(`ExecuteSubAgent: ignoring unknown or mismatched resumeRunId '${requestedResumeRunId}' for sub-agent '${subAgent.Name}'`, {
11745
+ agent: params.agent,
11746
+ category: 'SubAgentExecution',
11747
+ metadata: {
11748
+ subAgentName: subAgent.Name,
11749
+ resumeRunId: requestedResumeRunId
11750
+ }
11751
+ });
11752
+ }
11753
+ }
11754
+ const verifiedResumeRunId = matchedConsult?.childRunId;
10944
11755
  // Prepare messages for sub-agent using database-configured message mode
10945
- const subAgentMessages = this.prepareSubAgentMessages(params, subAgentRequest, subAgent, contextMessage);
11756
+ const subAgentMessages = this.prepareSubAgentMessages(params, subAgentRequest, subAgent, contextMessage, matchedConsult?.question);
10946
11757
  // Set parent run ID in the sub-agent's execution
10947
11758
  // This would need to be passed through the AgentRunner in a real implementation
10948
11759
  // For now, we execute normally and the sub-agent will track its parent relationship
@@ -10962,6 +11773,17 @@ The context is now within limits. Please retry your request with the recovered c
10962
11773
  // Use subAgentRequest.context if provided, otherwise fall back to params.context
10963
11774
  // This allows Flow agents and Loop agents to propagate context through sub-agent requests
10964
11775
  const subAgentContext = subAgentRequest.context !== undefined ? subAgentRequest.context : params.context;
11776
+ const resolvedConfig = this.resolveSubAgentConfiguration(params, subAgentRequest, subAgent);
11777
+ if (resolvedConfig.presetId && stepEntity) {
11778
+ const parsedInput = stepEntity.InputData
11779
+ ? JSON.parse(stepEntity.InputData)
11780
+ : {};
11781
+ parsedInput.presetName = resolvedConfig.presetName;
11782
+ parsedInput.presetId = resolvedConfig.presetId;
11783
+ const updatedInputJson = JSON.stringify(parsedInput);
11784
+ stepEntity.InputData = updatedInputJson;
11785
+ this.queueStepSave(stepEntity, (s) => { s.InputData = updatedInputJson; });
11786
+ }
10965
11787
  const result = await runner.RunAgent({
10966
11788
  agent: subAgent,
10967
11789
  conversationMessages: subAgentMessages,
@@ -10974,8 +11796,9 @@ The context is now within limits. Please retry your request with the recovered c
10974
11796
  parentStepCounts: parentStepCountsToPass,
10975
11797
  parentRun: this._agentRun,
10976
11798
  parentActivatedSkillIDs: this.activeSkillIDsForRun(params), // the root's active skills reach the sub-agent's actions
10977
- payload: payload, // pass the payload if provided
10978
- configurationId: params.configurationId, // propagate configuration ID to sub-agent
11799
+ payload: verifiedResumeRunId ? undefined : payload, // on resume, ignore computed/mapped payload so autoPopulateLastRunPayload loads the child's prior FinalPayload
11800
+ ...(verifiedResumeRunId ? { lastRunId: verifiedResumeRunId, autoPopulateLastRunPayload: true } : {}),
11801
+ configurationId: resolvedConfig.configurationId, // resolved preset configuration ID or inherited parent configurationId
10979
11802
  effortLevel: params.effortLevel, // propagate effort level to sub-agent
10980
11803
  apiKeys: params.apiKeys, // propagate API keys to sub-agent
10981
11804
  CredentialScope: params.CredentialScope, // a sub-agent may not spend keys its parent could not
@@ -10996,6 +11819,7 @@ The context is now within limits. Please retry your request with the recovered c
10996
11819
  PrimaryScopeRecordID: params.PrimaryScopeRecordID,
10997
11820
  companyId: params.companyId,
10998
11821
  SecondaryScopes: params.SecondaryScopes,
11822
+ SearchScopeIDs: params.SearchScopeIDs, // the host's search scopes bound the sub-agent too
10999
11823
  conversationDetailId: params.conversationDetailId, // propagate conversationDetailId so sub-agent task graphs attach to the chat message
11000
11824
  onAgentRunCreated: async (agentRunId) => {
11001
11825
  stepEntity.TargetLogID = agentRunId;
@@ -11026,6 +11850,47 @@ The context is now within limits. Please retry your request with the recovered c
11026
11850
  throw new Error(`Error executing sub-agent: ${error.message}`);
11027
11851
  }
11028
11852
  }
11853
+ /**
11854
+ * Resolves the configuration to pass to a sub-agent run in precedence order:
11855
+ * 1. Per-call `subAgentRequest.presetName` -> matching Active preset of `subAgent`.
11856
+ * 2. Active `AIAgentRelationship.ConfigurationPresetID` -> that preset if Active and owned by `subAgent`;
11857
+ * otherwise logs a warning and falls through.
11858
+ * 3. Inherit `params.configurationId`.
11859
+ *
11860
+ * When a preset is selected, `configurationId` is `preset.AIConfigurationID ?? undefined` (a NULL
11861
+ * `AIConfigurationID` means default rows and intentionally does NOT inherit `params.configurationId`).
11862
+ */
11863
+ resolveSubAgentConfiguration(params, subAgentRequest, subAgent) {
11864
+ if (subAgentRequest.presetName != null && subAgentRequest.presetName.trim() !== '') {
11865
+ const preset = AIEngine.Instance.FindActiveAgentConfigurationPreset(subAgent.ID, subAgentRequest.presetName);
11866
+ if (preset) {
11867
+ return {
11868
+ configurationId: preset.AIConfigurationID ?? undefined,
11869
+ presetName: preset.Name,
11870
+ presetId: preset.ID
11871
+ };
11872
+ }
11873
+ this.logStatus(`⚠️ Sub-agent '${subAgent.Name}' has no active preset matching '${subAgentRequest.presetName}'; falling through.`, false, params);
11874
+ }
11875
+ const isDirectChild = subAgent.ParentID != null && UUIDsEqual(subAgent.ParentID, params.agent.ID);
11876
+ if (!isDirectChild) {
11877
+ const relationship = AIEngine.Instance.AgentRelationships.find(r => UUIDsEqual(r.AgentID, params.agent.ID) &&
11878
+ UUIDsEqual(r.SubAgentID, subAgent.ID) &&
11879
+ r.Status === 'Active');
11880
+ if (relationship?.ConfigurationPresetID) {
11881
+ const preset = AIEngine.Instance.AgentConfigurations.find(p => UUIDsEqual(p.ID, relationship.ConfigurationPresetID));
11882
+ if (preset && preset.Status === 'Active' && UUIDsEqual(preset.AgentID, subAgent.ID)) {
11883
+ return {
11884
+ configurationId: preset.AIConfigurationID ?? undefined,
11885
+ presetName: preset.Name,
11886
+ presetId: preset.ID
11887
+ };
11888
+ }
11889
+ this.logStatus(`⚠️ Sub-agent relationship for '${subAgent.Name}' references preset '${relationship.ConfigurationPresetID}' which is missing, inactive, or belongs to another agent; inheriting parent configuration.`, false, params);
11890
+ }
11891
+ }
11892
+ return { configurationId: params.configurationId };
11893
+ }
11029
11894
  /**
11030
11895
  * A sub-agent request's template parameters without the host-only run-data keys
11031
11896
  * (`HOST_ONLY_AGENT_RUN_DATA_KEYS` in `@memberjunction/ai-core-plus`: the reserved scope family and
@@ -11061,6 +11926,23 @@ The context is now within limits. Please retry your request with the recovered c
11061
11926
  if (sa.ExecutionMode !== 'Sequential') {
11062
11927
  line += ` _(${sa.ExecutionMode}, order: ${sa.ExecutionOrder})_`;
11063
11928
  }
11929
+ const presets = AIEngine.Instance.GetAgentConfigurationPresets(sa.ID, true);
11930
+ if (presets.length > 0) {
11931
+ const presetSummary = presets.map(p => {
11932
+ const desc = p.Description?.trim();
11933
+ if (p.IsDefault && desc) {
11934
+ return `${p.Name} (default: ${desc})`;
11935
+ }
11936
+ if (p.IsDefault) {
11937
+ return `${p.Name} (default)`;
11938
+ }
11939
+ if (desc) {
11940
+ return `${p.Name} (${desc})`;
11941
+ }
11942
+ return p.Name;
11943
+ }).join(', ');
11944
+ line += `\n Presets: ${presetSummary}`;
11945
+ }
11064
11946
  return line;
11065
11947
  }).join('\n');
11066
11948
  }
@@ -11395,6 +12277,16 @@ The context is now within limits. Please retry your request with the recovered c
11395
12277
  // Status / error from the agent run
11396
12278
  const status = result.agentRun?.Status || (result.success ? 'Completed' : 'Failed');
11397
12279
  lines.push(`**Status:** ${status}`);
12280
+ if (result.agentRun?.FinalStep) {
12281
+ lines.push(`**Final step:** ${result.agentRun.FinalStep}`);
12282
+ }
12283
+ if (result.agentRun?.Message) {
12284
+ lines.push(`**Message:** ${result.agentRun.Message}`);
12285
+ }
12286
+ const formSummary = FormatResponseFormSummary(result.responseForm);
12287
+ if (formSummary) {
12288
+ lines.push(`**Form:**\n${formSummary}`);
12289
+ }
11398
12290
  if (!result.success && result.agentRun?.ErrorMessage) {
11399
12291
  lines.push(`**Error:** ${result.agentRun.ErrorMessage}`);
11400
12292
  }
@@ -11970,6 +12862,7 @@ The context is now within limits. Please retry your request with the recovered c
11970
12862
  Fields: ['Status', 'OriginatingAgentRunStepID'],
11971
12863
  OrderBy: '__mj_CreatedAt DESC',
11972
12864
  MaxRows: 1,
12865
+ SkipTotalRowCount: true,
11973
12866
  ResultType: 'simple'
11974
12867
  }, params.contextUser);
11975
12868
  if (!requestResult.Success || requestResult.Results.length === 0) {
@@ -11988,6 +12881,7 @@ The context is now within limits. Please retry your request with the recovered c
11988
12881
  ExtraFilter: `ID='${request.OriginatingAgentRunStepID}'`,
11989
12882
  Fields: ['StepType'],
11990
12883
  MaxRows: 1,
12884
+ SkipTotalRowCount: true,
11991
12885
  ResultType: 'simple'
11992
12886
  }, params.contextUser);
11993
12887
  const approved = stepResult.Success
@@ -12807,6 +13701,11 @@ The context is now within limits. Please retry your request with the recovered c
12807
13701
  // durable task graph. executeTasksStep detaches (see its doc comment).
12808
13702
  case 'Tasks':
12809
13703
  return await this.executeTasksStep(params, previousDecision);
13704
+ // Type assertion required because 'Handoff' is not part of the BaseAgentNextStep step
13705
+ // union — LoopAgentType.DetermineNextStep() emits it when an opted-in agent transfers
13706
+ // the conversation to another agent. executeHandoffStep records the step and ends Success.
13707
+ case 'Handoff':
13708
+ return await this.executeHandoffStep(params, previousDecision);
12810
13709
  // Type assertion required because 'ClientTools' is not part of the BaseAgentNextStep
12811
13710
  // step union — LoopAgentType.DetermineNextStep() emits it when the LLM chooses client tools.
12812
13711
  case 'ClientTools':
@@ -12953,6 +13852,64 @@ The context is now within limits. Please retry your request with the recovered c
12953
13852
  *
12954
13853
  * @private
12955
13854
  */
13855
+ /** Whether a step is a completion that carries a payload change, which is held until the completion is accepted. */
13856
+ static carriesCompletionChange(step) {
13857
+ return step.step === 'Success' && !!step.payloadChangeRequest;
13858
+ }
13859
+ /**
13860
+ * Applies a turn's `payloadChangeRequest` to `current` and returns the result; `current` is not
13861
+ * changed. Honours `PayloadSelfWritePaths`. A brand-new artifact whose payload is still the one
13862
+ * inherited from a prior run (or that uses `replaceElements`) is built on an empty object, so
13863
+ * keys from the previous artifact cannot bleed in.
13864
+ */
13865
+ applyTurnPayloadChange(params, step, current, isUnmodifiedInheritedPayload) {
13866
+ const change = step.payloadChangeRequest;
13867
+ const allowedPaths = params.agent.PayloadSelfWritePaths
13868
+ ? JSON.parse(params.agent.PayloadSelfWritePaths)
13869
+ : this.getDefaultPayloadSelfWritePaths();
13870
+ const basePayload = (step.artifactDirective?.behavior === 'create-new'
13871
+ && (this._promptTurnCount <= 1 || isUnmodifiedInheritedPayload || Boolean(change.replaceElements)))
13872
+ ? {}
13873
+ : current;
13874
+ const changeResult = this._payloadManager.applyAgentChangeRequest(basePayload, change, {
13875
+ validateChanges: true,
13876
+ logChanges: true,
13877
+ agentName: params.agent.Name,
13878
+ analyzeChanges: true,
13879
+ generateDiff: true,
13880
+ allowedPaths,
13881
+ verbose: params.verbose === true || IsVerboseLoggingEnabled()
13882
+ });
13883
+ if (changeResult.warnings.length > 0 && (params.verbose === true || IsVerboseLoggingEnabled())) {
13884
+ LogStatus(`Payload warnings: ${changeResult.warnings.join('; ')}`);
13885
+ }
13886
+ return changeResult;
13887
+ }
13888
+ /**
13889
+ * The payload a completion would leave behind: the committed payload with the completion's
13890
+ * change applied. Success validation (the minimum-execution check, then `FinalPayloadValidation`)
13891
+ * checks this draft, and it becomes the payload only if the completion is accepted. The
13892
+ * opt-in payload change check is not asked here: it never runs on a step that ends the run.
13893
+ */
13894
+ buildCompletionDraft(params, step, committed, isUnmodifiedInheritedPayload) {
13895
+ const changeResult = this.applyTurnPayloadChange(params, step, committed, isUnmodifiedInheritedPayload);
13896
+ return { payload: changeResult.result, summary: this.buildPayloadChangeResultSummary(changeResult) };
13897
+ }
13898
+ /**
13899
+ * The payload a turn leaves behind. A held completion draft is committed only when the step is
13900
+ * still `Success` after validation; on a refusal the committed payload stands (a subclass that
13901
+ * set a payload of its own still wins). Without a draft, a subclass's `newPayload` wins as before.
13902
+ */
13903
+ resolveTurnPayload(step, committed, draft) {
13904
+ if (!draft) {
13905
+ return { payload: step.newPayload || committed, committedDraft: false };
13906
+ }
13907
+ if (step.step === 'Success') {
13908
+ return { payload: step.newPayload || draft.payload, committedDraft: true };
13909
+ }
13910
+ const own = step.newPayload && step.newPayload !== draft.payload ? step.newPayload : undefined;
13911
+ return { payload: own || committed, committedDraft: false };
13912
+ }
12956
13913
  async executePromptStep(params, config, previousDecision, stepCount = 0) {
12957
13914
  // Decisions the last prompt held back: the step that carried them did not end the run, so
12958
13915
  // answer them now, where this prompt will read the answers
@@ -13184,36 +14141,14 @@ The context is now within limits. Please retry your request with the recovered c
13184
14141
  ? {}
13185
14142
  : payload; // Start with current payload
13186
14143
  let currentStepPayloadChangeResult = undefined;
13187
- if (initialNextStep.payloadChangeRequest) {
13188
- // Parse the allowed paths if configured
13189
- const allowedPaths = params.agent.PayloadSelfWritePaths
13190
- ? JSON.parse(params.agent.PayloadSelfWritePaths)
13191
- : this.getDefaultPayloadSelfWritePaths();
13192
- // When creating a brand-new artifact where the current payload is still the inherited
13193
- // payload from a prior conversation run (even if read-only action steps ran first) or when
13194
- // replaceElements is used with behavior='create-new', apply against a clean empty object
13195
- // so keys from the previous artifact cannot bleed in.
13196
- const basePayload = (initialNextStep.artifactDirective?.behavior === 'create-new'
13197
- && (this._promptTurnCount <= 1 || isUnmodifiedInheritedPayload || Boolean(initialNextStep.payloadChangeRequest.replaceElements)))
13198
- ? {}
13199
- : payload;
13200
- // Apply the changes to the payload with operation control
13201
- const changeResult = this._payloadManager.applyAgentChangeRequest(basePayload, initialNextStep.payloadChangeRequest, {
13202
- validateChanges: true,
13203
- logChanges: true,
13204
- agentName: params.agent.Name,
13205
- analyzeChanges: true,
13206
- generateDiff: true,
13207
- allowedPaths: allowedPaths,
13208
- verbose: params.verbose === true || IsVerboseLoggingEnabled()
13209
- });
13210
- if (changeResult.warnings.length > 0 && (params.verbose === true || IsVerboseLoggingEnabled())) {
13211
- LogStatus(`Payload warnings: ${changeResult.warnings.join('; ')}`);
13212
- }
13213
- // Store payload change metadata for audit trail
13214
- // This will be merged into outputData later
14144
+ // A completion's payload change is held as a draft until Success validation accepts it
14145
+ // (see buildCompletionDraft); every other step's change is applied now, as it always was.
14146
+ const holdsCompletionChange = BaseAgent.carriesCompletionChange(initialNextStep);
14147
+ if (initialNextStep.payloadChangeRequest && !holdsCompletionChange) {
14148
+ const changeResult = this.applyTurnPayloadChange(params, initialNextStep, payload, isUnmodifiedInheritedPayload);
14149
+ // Store payload change metadata for audit trail; merged into outputData later
13215
14150
  currentStepPayloadChangeResult = this.buildPayloadChangeResultSummary(changeResult);
13216
- // Set the final payload - the changeResult already respects the allowed paths
14151
+ // The changeResult already respects the allowed paths
13217
14152
  finalPayload = changeResult.result;
13218
14153
  // Opt-in payload change check: asks whether the flagged changes were intended. It never
13219
14154
  // reverts or blocks a change; the agent reads the result on its next turn.
@@ -13297,11 +14232,22 @@ The context is now within limits. Please retry your request with the recovered c
13297
14232
  const agentTypePromptParams = promptParams.data?.__agentTypePromptParams;
13298
14233
  await this.processTurnDecisions(decisions, initialNextStep, finalPayload, agentTypePromptParams, params);
13299
14234
  }
14235
+ // A completion's change is validated as a draft (the committed payload with the change
14236
+ // applied), and committed only if the completion is accepted.
14237
+ const draft = holdsCompletionChange && initialNextStep.step === 'Success'
14238
+ ? this.buildCompletionDraft(params, initialNextStep, finalPayload, finalPayload === params.payload)
14239
+ : undefined;
14240
+ currentStepPayloadChangeResult = draft?.summary ?? currentStepPayloadChangeResult;
13300
14241
  // now that we have processed the payload, we can process the next step which does validation and changes the next step if
13301
14242
  // validation fails
13302
- const updatedNextStep = await this.processNextStep(initialNextStep, params, config.agentType, promptResult, finalPayload, stepEntity);
14243
+ const updatedNextStep = await this.processNextStep(initialNextStep, params, config.agentType, promptResult, draft ? draft.payload : finalPayload, stepEntity);
13303
14244
  // sub-classes may have modified the payload, and we allow that, and so we need to update finalPayload to map to the updatedNextStep.newPayload
13304
- finalPayload = updatedNextStep.newPayload || finalPayload;
14245
+ const resolved = this.resolveTurnPayload(updatedNextStep, finalPayload, draft);
14246
+ finalPayload = resolved.payload;
14247
+ const discardedCompletionChange = holdsCompletionChange && !resolved.committedDraft;
14248
+ if (discardedCompletionChange && currentStepPayloadChangeResult) {
14249
+ currentStepPayloadChangeResult = { ...currentStepPayloadChangeResult, applied: { additions: 0, updates: 0, deletions: 0 } };
14250
+ }
13305
14251
  // Prepare output data, these are simple elements of the state that are not typically
13306
14252
  // included in payload but are helpful. We do not include the prompt result here
13307
14253
  // or the payload as those are stored already(prompt result via TargetLogID -> MJAIPromptRunEntityExtended)
@@ -13315,6 +14261,10 @@ The context is now within limits. Please retry your request with the recovered c
13315
14261
  ...(currentStepPayloadChangeResult && {
13316
14262
  payloadChangeResult: currentStepPayloadChangeResult
13317
14263
  }),
14264
+ // A completion's change that was not applied because the completion was refused
14265
+ ...(discardedCompletionChange && {
14266
+ payloadChangeDiscarded: 'The payload change was sent with a completion that was refused, so it was not applied.'
14267
+ }),
13318
14268
  // Include scratchpad snapshot after changes for audit/training data
13319
14269
  ...(this._scratchpadManager.HasContent() && {
13320
14270
  scratchpad: this._scratchpadManager.ToJSON()
@@ -13579,6 +14529,8 @@ The context is now within limits. Please retry your request with the recovered c
13579
14529
  subAgentName: subAgentRequest.name,
13580
14530
  message: subAgentRequest.message,
13581
14531
  terminateAfter: subAgentRequest.terminateAfter,
14532
+ ...(subAgentRequest.resumeRunId ? { resumeRunId: subAgentRequest.resumeRunId } : {}),
14533
+ ...(subAgentRequest.presetName ? { presetName: subAgentRequest.presetName } : {}),
13582
14534
  parentAgentHierarchy: this._agentHierarchy
13583
14535
  };
13584
14536
  // Get sub-agent entity to access payload paths. Prefer the entity the caller already
@@ -13761,27 +14713,12 @@ The context is now within limits. Please retry your request with the recovered c
13761
14713
  payloadChangeResult: currentStepPayloadChangeResult
13762
14714
  })
13763
14715
  };
13764
- // Finalize step entity
13765
- await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
13766
- // Check if sub-agent returned a Chat step
14716
+ // Check if sub-agent returned a Chat step (handled before finalizeStepEntity so Consult can update outputData)
13767
14717
  if (subAgentResult.agentRun?.FinalStep === 'Chat') {
13768
- // Create Chat nextStep but validate it through parent's ChatHandlingOption
13769
- // This allows parent agents to remap Chat -> Success/Failed/Retry if configured
13770
- const chatStep = {
13771
- step: 'Chat',
13772
- terminate: true,
13773
- message: subAgentResult.agentRun?.Message || null,
13774
- previousPayload: previousDecision?.newPayload,
13775
- newPayload: mergedPayload, // Preserve sub-agent payload changes
13776
- responseForm: subAgentResult.responseForm,
13777
- actionableCommands: subAgentResult.actionableCommands,
13778
- automaticCommands: subAgentResult.automaticCommands,
13779
- artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective
13780
- };
13781
- // Validate through parent's ChatHandlingOption (if configured)
13782
- // This ensures parent agents can override child Chat steps
13783
- return await this.validateChatNextStep(params, chatStep, mergedPayload, this._agentRun, stepEntity);
14718
+ return await this.handleSingleSubAgentChatStep(params, previousDecision, subAgentRequest, subAgentEntity, undefined, subAgentResult, mergedPayload, stepEntity, outputData);
13784
14719
  }
14720
+ // Finalize step entity
14721
+ await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
13785
14722
  // When a sub-agent (e.g. Workflow Planner) submits a durable task graph, its run parks
13786
14723
  // with Status === 'Paused'. Propagate the parked state to the parent run and terminate
13787
14724
  // immediately with the sub-agent's workflow launch message so the parent orchestrator
@@ -13801,44 +14738,14 @@ The context is now within limits. Please retry your request with the recovered c
13801
14738
  responseForm: subAgentResult.responseForm,
13802
14739
  actionableCommands: subAgentResult.actionableCommands,
13803
14740
  automaticCommands: subAgentResult.automaticCommands,
13804
- artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective
14741
+ artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective,
14742
+ handoff: undefined
13805
14743
  };
13806
14744
  }
13807
14745
  // Add user message with the sub-agent results using markdown format
13808
14746
  // and expiration metadata so it persists across multiple prompt turns
13809
14747
  const resultMessage = this.formatSubAgentResultAsMarkdown(subAgentRequest.name, subAgentResult);
13810
- const subAgentMetadata = {
13811
- turnAdded: this._promptTurnCount,
13812
- messageType: 'sub-agent-result',
13813
- subAgentName: subAgentRequest.name,
13814
- subAgentId: subAgentEntity.ID,
13815
- // Default: keep sub-agent results for 3 turns then remove
13816
- expirationTurns: 3,
13817
- expirationMode: 'Remove'
13818
- };
13819
- // Apply global override if configured
13820
- if (params.messageExpirationOverride) {
13821
- const override = params.messageExpirationOverride;
13822
- if (override.expirationTurns != null) {
13823
- subAgentMetadata.expirationTurns = override.expirationTurns;
13824
- subAgentMetadata.expirationMode = override.expirationMode || 'Remove';
13825
- subAgentMetadata.compactMode = override.compactMode;
13826
- subAgentMetadata.compactLength = override.compactLength;
13827
- subAgentMetadata.compactPromptId = override.compactPromptId;
13828
- }
13829
- }
13830
- if (previousDecision?.nativeTurn?.sendResultsNatively && subAgentRequest.toolCallId) {
13831
- // the delegate_to_* call is answered as a tool result.
13832
- this.PushToolResultTurn(params, BuildToolResultTurn([...this.payloadToolResult(previousDecision), {
13833
- toolCallId: subAgentRequest.toolCallId,
13834
- toolName: `${SUB_AGENT_TOOL_PREFIX}${SanitizeToolName(subAgentRequest.name)}`,
13835
- content: resultMessage,
13836
- isError: !subAgentResult.success
13837
- }], subAgentMetadata));
13838
- }
13839
- else {
13840
- params.conversationMessages.push({ role: 'user', content: resultMessage, metadata: subAgentMetadata });
13841
- }
14748
+ this.pushSubAgentConversationMessage(params, previousDecision, subAgentRequest, subAgentEntity, resultMessage, 'sub-agent-result', !subAgentResult.success);
13842
14749
  // Update the agent run's current payload with the merged result
13843
14750
  if (this._agentRun) {
13844
14751
  this._agentRun.FinalPayloadObject = mergedPayload;
@@ -13864,7 +14771,8 @@ The context is now within limits. Please retry your request with the recovered c
13864
14771
  // terminates the parent run directly (shouldTerminate=true), carry the terminal
13865
14772
  // sub-agent's directive if the parent did not specify one.
13866
14773
  artifactDirective: previousDecision?.artifactDirective
13867
- ?? (shouldTerminate ? subAgentResult.artifactDirective : undefined)
14774
+ ?? (shouldTerminate ? subAgentResult.artifactDirective : undefined),
14775
+ handoff: undefined
13868
14776
  };
13869
14777
  }
13870
14778
  catch (error) {
@@ -13944,11 +14852,23 @@ The context is now within limits. Please retry your request with the recovered c
13944
14852
  };
13945
14853
  }
13946
14854
  const resolved = this.resolveSubAgentByName(params, name, previousDecision.taskGraph?.folded === true);
13947
- if (resolved?.relationship) {
13948
- return await this.executeRelatedSubAgentStep(params, previousDecision, resolved.subAgentEntity, resolved.relationship, parentStepId, subAgentPayloadOverride, stepCount);
13949
- }
13950
14855
  if (resolved) {
13951
- return await this.executeChildSubAgentStep(params, previousDecision, parentStepId, subAgentPayloadOverride, stepCount, resolved.subAgentEntity);
14856
+ const canonicalName = resolved.subAgentEntity.Name || name;
14857
+ const canonicalDecision = canonicalName !== name
14858
+ ? {
14859
+ ...previousDecision,
14860
+ ...(previousDecision.subAgent
14861
+ ? { subAgent: { ...previousDecision.subAgent, name: canonicalName } }
14862
+ : {}),
14863
+ ...(previousDecision.subAgents
14864
+ ? { subAgents: [{ ...subAgentRequest, name: canonicalName }] }
14865
+ : {}),
14866
+ }
14867
+ : previousDecision;
14868
+ if (resolved.relationship) {
14869
+ return await this.executeRelatedSubAgentStep(params, canonicalDecision, resolved.subAgentEntity, resolved.relationship, parentStepId, subAgentPayloadOverride, stepCount);
14870
+ }
14871
+ return await this.executeChildSubAgentStep(params, canonicalDecision, parentStepId, subAgentPayloadOverride, stepCount, resolved.subAgentEntity);
13952
14872
  }
13953
14873
  // Execution-time resolution failure. Count it against the shared validation-retry cap
13954
14874
  // (MAX_VALIDATION_RETRIES) so a model that keeps picking an unresolvable sub-agent fails
@@ -13986,19 +14906,28 @@ The context is now within limits. Please retry your request with the recovered c
13986
14906
  */
13987
14907
  resolveSubAgentByName(params, name, allowAnyActiveAgent = false) {
13988
14908
  const normalized = name.trim().toLowerCase();
13989
- const childAgent = AIEngine.Instance.Agents.find(a => UUIDsEqual(a.ParentID, params.agent.ID) &&
13990
- a.Status === 'Active' &&
13991
- a.Name.trim().toLowerCase() === normalized);
14909
+ const activeChildAgents = AIEngine.Instance.Agents.filter(a => UUIDsEqual(a.ParentID, params.agent.ID) && a.Status === 'Active');
14910
+ const childAgent = activeChildAgents.find(a => a.Name.trim().toLowerCase() === normalized)
14911
+ ?? this.matchNamedBySanitizedToolName(name, activeChildAgents, true).match;
13992
14912
  if (childAgent) {
13993
14913
  return { subAgentEntity: childAgent };
13994
14914
  }
13995
14915
  const activeRelationships = AIEngine.Instance.AgentRelationships.filter(ar => UUIDsEqual(ar.AgentID, params.agent.ID) && ar.Status === 'Active');
14916
+ const relatedPairs = [];
13996
14917
  for (const rel of activeRelationships) {
13997
- const relatedAgent = AIEngine.Instance.Agents.find(a => UUIDsEqual(a.ID, rel.SubAgentID) &&
13998
- a.Status === 'Active' &&
13999
- a.Name.trim().toLowerCase() === normalized);
14918
+ const relatedAgent = AIEngine.Instance.Agents.find(a => UUIDsEqual(a.ID, rel.SubAgentID) && a.Status === 'Active');
14000
14919
  if (relatedAgent) {
14001
- return { subAgentEntity: relatedAgent, relationship: rel };
14920
+ if (relatedAgent.Name.trim().toLowerCase() === normalized) {
14921
+ return { subAgentEntity: relatedAgent, relationship: rel };
14922
+ }
14923
+ relatedPairs.push({ agent: relatedAgent, rel });
14924
+ }
14925
+ }
14926
+ const sanitizedRelated = this.matchNamedBySanitizedToolName(name, relatedPairs.map(p => p.agent), true).match;
14927
+ if (sanitizedRelated) {
14928
+ const matchedPair = relatedPairs.find(p => UUIDsEqual(p.agent.ID, sanitizedRelated.ID));
14929
+ if (matchedPair) {
14930
+ return { subAgentEntity: matchedPair.agent, relationship: matchedPair.rel };
14002
14931
  }
14003
14932
  }
14004
14933
  // 3) Runtime-granted sub-agents (skill activation / caller subAgentChanges): resolve from
@@ -14007,7 +14936,9 @@ The context is now within limits. Please retry your request with the recovered c
14007
14936
  // or not active") — and because the catalog keeps offering it, the model re-picks the same
14008
14937
  // sub-agent forever (observed live: Research Agent looping 36+ turns on the skill-granted
14009
14938
  // Infographic Agent). No relationship row exists for these, so they dispatch child-style.
14010
- const effectiveAgent = this.getEffectiveSubAgentsForValidation(params.agent.ID).find(a => a.Status === 'Active' && a.Name.trim().toLowerCase() === normalized);
14939
+ const effectivePool = this.getEffectiveSubAgentsForValidation(params.agent.ID).filter(a => a.Status === 'Active');
14940
+ const effectiveAgent = effectivePool.find(a => a.Name.trim().toLowerCase() === normalized)
14941
+ ?? this.matchNamedBySanitizedToolName(name, effectivePool, true).match;
14011
14942
  if (effectiveAgent) {
14012
14943
  return { subAgentEntity: effectiveAgent };
14013
14944
  }
@@ -14016,7 +14947,9 @@ The context is now within limits. Please retry your request with the recovered c
14016
14947
  // LoopAgentType folds that 1-node graph into an in-run Sub-Agent step (`taskGraph.folded === true`),
14017
14948
  // so allow resolving any active agent in AIEngine.Instance.Agents.
14018
14949
  if (allowAnyActiveAgent) {
14019
- const anyActiveAgent = AIEngine.Instance.Agents.find(a => a.Status === 'Active' && a.Name.trim().toLowerCase() === normalized);
14950
+ const allActive = AIEngine.Instance.Agents.filter(a => a.Status === 'Active');
14951
+ const anyActiveAgent = allActive.find(a => a.Name.trim().toLowerCase() === normalized)
14952
+ ?? this.matchNamedBySanitizedToolName(name, allActive, true).match;
14020
14953
  if (anyActiveAgent) {
14021
14954
  return { subAgentEntity: anyActiveAgent };
14022
14955
  }
@@ -14095,13 +15028,16 @@ The context is now within limits. Please retry your request with the recovered c
14095
15028
  return undefined;
14096
15029
  }
14097
15030
  const { subAgentEntity, relationship } = resolved;
15031
+ const canonicalRequest = subAgentEntity.Name && request.name !== subAgentEntity.Name
15032
+ ? { ...request, name: subAgentEntity.Name }
15033
+ : request;
14098
15034
  this.safeOnProgress(params, {
14099
15035
  step: 'subagent_execution',
14100
- message: this.formatHierarchicalMessage(`Delegating to parallel sub-agent ${request.name}`),
15036
+ message: this.formatHierarchicalMessage(`Delegating to parallel sub-agent ${canonicalRequest.name}`),
14101
15037
  metadata: {
14102
15038
  agentName: params.agent.Name,
14103
- subAgentName: request.name,
14104
- reason: request.message,
15039
+ subAgentName: canonicalRequest.name,
15040
+ reason: canonicalRequest.message,
14105
15041
  relationshipType: relationship ? 'related' : 'child',
14106
15042
  stepCount: stepCount + 1,
14107
15043
  hierarchicalStep: this.buildHierarchicalStep(stepCount + 1, this._parentStepCounts)
@@ -14111,13 +15047,13 @@ The context is now within limits. Please retry your request with the recovered c
14111
15047
  // single-delegation push above for why framework prose must not be stored as assistant turns.
14112
15048
  // skipped when the call is natively recorded and will be answered by a tool result (see the
14113
15049
  // single-delegation push for why a user turn between call and result must not be inserted).
14114
- if (!(nativeResults && request.toolCallId)) {
15050
+ if (!(nativeResults && canonicalRequest.toolCallId)) {
14115
15051
  params.conversationMessages.push({
14116
15052
  role: 'user',
14117
- content: `[You delegated this task to the parallel sub-agent "${request.name}". Reason: ${request.message}]`
15053
+ content: `[You delegated this task to the parallel sub-agent "${canonicalRequest.name}". Reason: ${canonicalRequest.message}]`
14118
15054
  });
14119
15055
  }
14120
- return { request: request, subAgentEntity, relationship };
15056
+ return { request: canonicalRequest, subAgentEntity, relationship };
14121
15057
  }
14122
15058
  /**
14123
15059
  * Computes the per-sub-agent input payload + context message based on whether
@@ -14217,13 +15153,30 @@ The context is now within limits. Please retry your request with the recovered c
14217
15153
  return executions
14218
15154
  .map(execution => {
14219
15155
  const statusEmoji = execution.result.success ? '✅' : '❌';
14220
- const baseInfo = `${statusEmoji} **Sub-Agent: ${execution.request.name}**\n` +
14221
- `* Message: "${execution.request.message}"\n` +
14222
- `* Status: ${execution.result.agentRun?.FinalStep || 'Failed'}`;
15156
+ const lines = [
15157
+ `${statusEmoji} **Sub-Agent: ${execution.request.name}**`,
15158
+ `* Message: "${execution.request.message}"`,
15159
+ `* Status: ${execution.result.agentRun?.FinalStep || 'Failed'}`
15160
+ ];
15161
+ const isChat = execution.result.agentRun?.FinalStep === 'Chat';
15162
+ const question = execution.result.agentRun?.Message;
15163
+ if (execution.consult) {
15164
+ const maxRounds = execution.maxConsultRounds ?? DEFAULT_MAX_SUB_AGENT_CONSULT_ROUNDS;
15165
+ lines.push(`* Question (round ${execution.consult.round} of ${maxRounds}): ${question?.trim() ? question : '(no message provided)'}`);
15166
+ const formSummary = FormatResponseFormSummary(execution.result.responseForm);
15167
+ if (formSummary) {
15168
+ lines.push(`* Form:\n${formSummary}`);
15169
+ }
15170
+ lines.push(`* Child run ID: ${execution.consult.childRunId || '(unknown)'}`);
15171
+ lines.push(`* To answer, call ${execution.request.name} again with resumeRunId: "${execution.consult.childRunId}" and your answer as the message.`);
15172
+ }
15173
+ else if (isChat && question?.trim()) {
15174
+ lines.push(`* Question: ${question}`);
15175
+ }
14223
15176
  if (execution.result.agentRun?.ErrorMessage) {
14224
- return `${baseInfo}\n* Error: ${execution.result.agentRun.ErrorMessage}`;
15177
+ lines.push(`* Error: ${execution.result.agentRun.ErrorMessage}`);
14225
15178
  }
14226
- return baseInfo;
15179
+ return lines.join('\n');
14227
15180
  })
14228
15181
  .join('\n\n---\n\n');
14229
15182
  }
@@ -14270,6 +15223,8 @@ The context is now within limits. Please retry your request with the recovered c
14270
15223
  subAgentName: request.name,
14271
15224
  message: request.message,
14272
15225
  terminateAfter: request.terminateAfter,
15226
+ ...(request.resumeRunId ? { resumeRunId: request.resumeRunId } : {}),
15227
+ ...(request.presetName ? { presetName: request.presetName } : {}),
14273
15228
  parentAgentHierarchy: this._agentHierarchy,
14274
15229
  relationshipType: relationship ? 'related' : 'child'
14275
15230
  },
@@ -14326,6 +15281,30 @@ The context is now within limits. Please retry your request with the recovered c
14326
15281
  this._mediaOutputs.push(...execution.result.mediaOutputs);
14327
15282
  if (execution.result.fileOutputs?.length)
14328
15283
  this._fileOutputs.push(...execution.result.fileOutputs);
15284
+ if (execution.result.agentRun?.FinalStep === 'Chat') {
15285
+ const resolvedOption = this.resolveSubAgentChatHandlingOption(params.agent, execution.relationship);
15286
+ if (this.isSubAgentConsultActive(resolvedOption, params)) {
15287
+ const round = (this._subAgentConsultRounds.get(execution.subAgentEntity.ID) ?? 0) + 1;
15288
+ this._subAgentConsultRounds.set(execution.subAgentEntity.ID, round);
15289
+ const maxRounds = params.agent.MaxSubAgentConsultRounds ?? DEFAULT_MAX_SUB_AGENT_CONSULT_ROUNDS;
15290
+ if (round <= maxRounds) {
15291
+ const childRunId = execution.result.agentRun?.ID || '';
15292
+ const question = execution.result.agentRun?.Message || null;
15293
+ const consultRecord = {
15294
+ childRunId,
15295
+ subAgentId: execution.subAgentEntity.ID,
15296
+ subAgentName: execution.request.name,
15297
+ round,
15298
+ question
15299
+ };
15300
+ if (childRunId) {
15301
+ this._openSubAgentConsults.set(childRunId, consultRecord);
15302
+ }
15303
+ execution.consult = consultRecord;
15304
+ execution.maxConsultRounds = maxRounds;
15305
+ }
15306
+ }
15307
+ }
14329
15308
  const { mergedPayload: newMerged, stepPayloadAtEnd } = this.mergeParallelSubAgentResult(params, execution, mergedPayload);
14330
15309
  mergedPayload = newMerged;
14331
15310
  allExecutions.push(execution);
@@ -14344,6 +15323,7 @@ The context is now within limits. Please retry your request with the recovered c
14344
15323
  if (!execution.stepEntity)
14345
15324
  return;
14346
15325
  execution.stepEntity.PayloadAtEnd = this.serializePayloadAtEnd(stepPayloadAtEnd);
15326
+ const shouldTerminate = execution.request.terminateAfter === true && !execution.consult;
14347
15327
  await this.finalizeStepEntity(execution.stepEntity, execution.result.success, execution.result.agentRun?.ErrorMessage, {
14348
15328
  subAgentResult: {
14349
15329
  success: execution.result.success,
@@ -14351,8 +15331,9 @@ The context is now within limits. Please retry your request with the recovered c
14351
15331
  errorMessage: execution.result.agentRun?.ErrorMessage,
14352
15332
  stepCount: execution.result.agentRun?.Steps?.length || 0,
14353
15333
  },
14354
- shouldTerminate: execution.request.terminateAfter === true,
14355
- nextStep: execution.request.terminateAfter === true ? 'success' : 'retry'
15334
+ shouldTerminate,
15335
+ nextStep: shouldTerminate ? 'success' : 'retry',
15336
+ ...(execution.consult && { consult: execution.consult })
14356
15337
  });
14357
15338
  }
14358
15339
  async executeParallelSubAgents(params, subAgentRequests, previousDecision, parentStepId, subAgentPayloadOverride, stepCount = 0) {
@@ -14392,9 +15373,9 @@ The context is now within limits. Please retry your request with the recovered c
14392
15373
  }
14393
15374
  // Termination semantics: matches the single sub-agent path —
14394
15375
  // `terminateAfter` triggers parent termination regardless of the child's
14395
- // success/failure. The parent's step reflects whether any child failed:
14396
- // Failed if any did, Success if terminating cleanly, otherwise Retry.
14397
- const shouldTerminateParent = allExecutions.some(e => e.request.terminateAfter === true);
15376
+ // success/failure, EXCEPT when a Chat child is handled under Consult
15377
+ // (the parent must get its turn to answer).
15378
+ const shouldTerminateParent = allExecutions.some(e => e.request.terminateAfter === true && !e.consult);
14398
15379
  const subAgentNames = allExecutions.map(e => e.request.name).join(', ');
14399
15380
  return {
14400
15381
  step: anyFailure ? 'Failed' : (shouldTerminateParent ? 'Success' : 'Retry'),
@@ -14406,6 +15387,134 @@ The context is now within limits. Please retry your request with the recovered c
14406
15387
  previousPayload: previousDecision.newPayload
14407
15388
  };
14408
15389
  }
15390
+ /**
15391
+ * Pushes a sub-agent result or consult message to the parent's conversation history,
15392
+ * answering natively-invoked `delegate_to_*` calls as a tool-result turn when applicable
15393
+ * and applying expiration defaults / overrides.
15394
+ *
15395
+ * @private
15396
+ */
15397
+ pushSubAgentConversationMessage(params, previousDecision, subAgentRequest, subAgentEntity, messageContent, messageType, isError) {
15398
+ const metadata = {
15399
+ turnAdded: this._promptTurnCount,
15400
+ messageType,
15401
+ subAgentName: subAgentRequest.name,
15402
+ subAgentId: subAgentEntity.ID,
15403
+ expirationTurns: 3,
15404
+ expirationMode: 'Remove'
15405
+ };
15406
+ if (params.messageExpirationOverride) {
15407
+ const override = params.messageExpirationOverride;
15408
+ if (override.expirationTurns != null) {
15409
+ metadata.expirationTurns = override.expirationTurns;
15410
+ metadata.expirationMode = override.expirationMode || 'Remove';
15411
+ metadata.compactMode = override.compactMode;
15412
+ metadata.compactLength = override.compactLength;
15413
+ metadata.compactPromptId = override.compactPromptId;
15414
+ }
15415
+ }
15416
+ if (previousDecision?.nativeTurn?.sendResultsNatively && subAgentRequest.toolCallId) {
15417
+ this.PushToolResultTurn(params, BuildToolResultTurn([
15418
+ ...this.payloadToolResult(previousDecision),
15419
+ {
15420
+ toolCallId: subAgentRequest.toolCallId,
15421
+ toolName: `${SUB_AGENT_TOOL_PREFIX}${SanitizeToolName(subAgentRequest.name)}`,
15422
+ content: messageContent,
15423
+ isError
15424
+ }
15425
+ ], metadata));
15426
+ }
15427
+ else {
15428
+ params.conversationMessages.push({
15429
+ role: 'user',
15430
+ content: messageContent,
15431
+ metadata
15432
+ });
15433
+ }
15434
+ }
15435
+ /**
15436
+ * Unified handler for a single sub-agent (child, related, or runtime-granted) that
15437
+ * finished with `FinalStep === 'Chat'`. Resolves `ChatHandlingOption` for the pairing,
15438
+ * runs the consult flow when `'Consult'` is active and within the per-sub-agent round
15439
+ * bound, and otherwise finalizes the step and delegates to `validateChatNextStep`.
15440
+ *
15441
+ * @private
15442
+ */
15443
+ async handleSingleSubAgentChatStep(params, previousDecision, subAgentRequest, subAgentEntity, relationship, subAgentResult, mergedPayload, stepEntity, outputData) {
15444
+ const resolvedOption = this.resolveSubAgentChatHandlingOption(params.agent, relationship);
15445
+ if (this.isSubAgentConsultActive(resolvedOption, params)) {
15446
+ const round = (this._subAgentConsultRounds.get(subAgentEntity.ID) ?? 0) + 1;
15447
+ this._subAgentConsultRounds.set(subAgentEntity.ID, round);
15448
+ const maxRounds = params.agent.MaxSubAgentConsultRounds ?? DEFAULT_MAX_SUB_AGENT_CONSULT_ROUNDS;
15449
+ const childRunId = subAgentResult.agentRun?.ID || '';
15450
+ const question = subAgentResult.agentRun?.Message || null;
15451
+ const consultRecord = {
15452
+ childRunId,
15453
+ subAgentId: subAgentEntity.ID,
15454
+ subAgentName: subAgentRequest.name,
15455
+ round,
15456
+ question
15457
+ };
15458
+ if (childRunId) {
15459
+ this._openSubAgentConsults.set(childRunId, consultRecord);
15460
+ }
15461
+ outputData.consult = consultRecord;
15462
+ if (round <= maxRounds) {
15463
+ outputData.shouldTerminate = false;
15464
+ outputData.nextStep = 'retry';
15465
+ await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
15466
+ const consultMessage = FormatSubAgentConsultMessage({
15467
+ subAgentName: subAgentRequest.name,
15468
+ round,
15469
+ maxRounds,
15470
+ question,
15471
+ responseForm: subAgentResult.responseForm,
15472
+ childRunId
15473
+ });
15474
+ this.pushSubAgentConversationMessage(params, previousDecision, subAgentRequest, subAgentEntity, consultMessage, 'sub-agent-consult', false);
15475
+ if (this._agentRun) {
15476
+ this._agentRun.FinalPayloadObject = mergedPayload;
15477
+ }
15478
+ this.warnIfDiscardingSubAgentArtifactDirective(subAgentResult, subAgentRequest.name);
15479
+ return {
15480
+ ...subAgentResult,
15481
+ step: 'Success',
15482
+ errorMessage: undefined,
15483
+ terminate: false,
15484
+ previousPayload: previousDecision?.newPayload,
15485
+ newPayload: mergedPayload,
15486
+ artifactDirective: undefined,
15487
+ handoff: undefined
15488
+ };
15489
+ }
15490
+ }
15491
+ // Not under active Consult (or round exceeded bound): finalize step and validate/propagate Chat
15492
+ await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
15493
+ const chatStep = {
15494
+ step: 'Chat',
15495
+ terminate: true,
15496
+ message: subAgentResult.agentRun?.Message || null,
15497
+ previousPayload: previousDecision?.newPayload,
15498
+ newPayload: mergedPayload,
15499
+ responseForm: subAgentResult.responseForm,
15500
+ actionableCommands: subAgentResult.actionableCommands,
15501
+ automaticCommands: subAgentResult.automaticCommands,
15502
+ artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective
15503
+ };
15504
+ const effectiveOption = this.effectiveSubAgentChatHandlingOption(params.agent, relationship, params);
15505
+ const validatedStep = await this.validateChatNextStep(params, chatStep, mergedPayload, this._agentRun, stepEntity, effectiveOption);
15506
+ if (validatedStep.step === 'Chat' && effectiveOption === 'Consult' && this._depth === 0) {
15507
+ await this.raiseFeedbackRequest(params, stepEntity, chatStep);
15508
+ }
15509
+ else if (validatedStep.step === 'Retry') {
15510
+ const resultMessage = this.formatSubAgentResultAsMarkdown(subAgentRequest.name, subAgentResult);
15511
+ this.pushSubAgentConversationMessage(params, previousDecision, subAgentRequest, subAgentEntity, resultMessage, 'sub-agent-result', !subAgentResult.success);
15512
+ if (this._agentRun) {
15513
+ this._agentRun.FinalPayloadObject = mergedPayload;
15514
+ }
15515
+ }
15516
+ return validatedStep;
15517
+ }
14409
15518
  /**
14410
15519
  * Executes a related sub-agent step (AgentRelationships) and tracks it.
14411
15520
  * Related agents use message-based communication with independent payloads.
@@ -14453,6 +15562,8 @@ The context is now within limits. Please retry your request with the recovered c
14453
15562
  subAgentName: subAgentRequest.name,
14454
15563
  message: subAgentRequest.message,
14455
15564
  terminateAfter: subAgentRequest.terminateAfter,
15565
+ ...(subAgentRequest.resumeRunId ? { resumeRunId: subAgentRequest.resumeRunId } : {}),
15566
+ ...(subAgentRequest.presetName ? { presetName: subAgentRequest.presetName } : {}),
14456
15567
  parentAgentHierarchy: this._agentHierarchy,
14457
15568
  relationshipType: 'related'
14458
15569
  };
@@ -14560,27 +15671,12 @@ The context is now within limits. Please retry your request with the recovered c
14560
15671
  if (stepEntity) {
14561
15672
  stepEntity.PayloadAtEnd = this.serializePayloadAtEnd(mergedPayload);
14562
15673
  }
14563
- // Finalize step entity
14564
- await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
14565
- // Check if sub-agent returned a Chat step
15674
+ // Check if sub-agent returned a Chat step (handled before finalizeStepEntity so Consult can update outputData)
14566
15675
  if (subAgentResult.agentRun?.FinalStep === 'Chat') {
14567
- // Create Chat nextStep but validate it through parent's ChatHandlingOption
14568
- // This allows parent agents to remap Chat -> Success/Failed/Retry if configured
14569
- const chatStep = {
14570
- step: 'Chat',
14571
- terminate: true,
14572
- message: subAgentResult.agentRun?.Message || null,
14573
- previousPayload: previousDecision?.newPayload,
14574
- newPayload: mergedPayload, // Preserve sub-agent payload changes
14575
- responseForm: subAgentResult.responseForm,
14576
- actionableCommands: subAgentResult.actionableCommands,
14577
- automaticCommands: subAgentResult.automaticCommands,
14578
- artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective
14579
- };
14580
- // Validate through parent's ChatHandlingOption (if configured)
14581
- // This ensures parent agents can override child Chat steps
14582
- return await this.validateChatNextStep(params, chatStep, mergedPayload, this._agentRun, stepEntity);
15676
+ return await this.handleSingleSubAgentChatStep(params, previousDecision, subAgentRequest, subAgentEntity, relationship, subAgentResult, mergedPayload, stepEntity, outputData);
14583
15677
  }
15678
+ // Finalize step entity
15679
+ await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
14584
15680
  // When a related sub-agent submits a durable task graph, its run parks with Status === 'Paused'.
14585
15681
  // Propagate the parked state to the parent run and terminate immediately with the sub-agent's
14586
15682
  // workflow launch message instead of continuing the parent loop.
@@ -14599,46 +15695,14 @@ The context is now within limits. Please retry your request with the recovered c
14599
15695
  responseForm: subAgentResult.responseForm,
14600
15696
  actionableCommands: subAgentResult.actionableCommands,
14601
15697
  automaticCommands: subAgentResult.automaticCommands,
14602
- artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective
15698
+ artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective,
15699
+ handoff: undefined
14603
15700
  };
14604
15701
  }
14605
15702
  // Add sub-agent result to conversation as user message using markdown format
14606
15703
  // and expiration metadata so it persists across multiple prompt turns
14607
15704
  const relatedResultMessage = this.formatSubAgentResultAsMarkdown(subAgentRequest.name, subAgentResult);
14608
- const relatedMetadata = {
14609
- turnAdded: this._promptTurnCount,
14610
- messageType: 'sub-agent-result',
14611
- subAgentName: subAgentRequest.name,
14612
- subAgentId: subAgentEntity.ID,
14613
- expirationTurns: 3,
14614
- expirationMode: 'Remove'
14615
- };
14616
- if (params.messageExpirationOverride) {
14617
- const override = params.messageExpirationOverride;
14618
- if (override.expirationTurns != null) {
14619
- relatedMetadata.expirationTurns = override.expirationTurns;
14620
- relatedMetadata.expirationMode = override.expirationMode || 'Remove';
14621
- relatedMetadata.compactMode = override.compactMode;
14622
- relatedMetadata.compactLength = override.compactLength;
14623
- relatedMetadata.compactPromptId = override.compactPromptId;
14624
- }
14625
- }
14626
- if (previousDecision.nativeTurn?.sendResultsNatively && subAgentRequest.toolCallId) {
14627
- // the delegate_to_* call is answered as a tool result (same as the child path).
14628
- this.PushToolResultTurn(params, BuildToolResultTurn([...this.payloadToolResult(previousDecision), {
14629
- toolCallId: subAgentRequest.toolCallId,
14630
- toolName: `${SUB_AGENT_TOOL_PREFIX}${SanitizeToolName(subAgentRequest.name)}`,
14631
- content: relatedResultMessage,
14632
- isError: !subAgentResult.success
14633
- }], relatedMetadata));
14634
- }
14635
- else {
14636
- params.conversationMessages.push({
14637
- role: 'user',
14638
- content: relatedResultMessage,
14639
- metadata: relatedMetadata
14640
- });
14641
- }
15705
+ this.pushSubAgentConversationMessage(params, previousDecision, subAgentRequest, subAgentEntity, relatedResultMessage, 'sub-agent-result', !subAgentResult.success);
14642
15706
  // Update the agent run's current payload
14643
15707
  if (this._agentRun) {
14644
15708
  this._agentRun.FinalPayloadObject = mergedPayload;
@@ -14658,7 +15722,8 @@ The context is now within limits. Please retry your request with the recovered c
14658
15722
  previousPayload: previousDecision?.newPayload,
14659
15723
  newPayload: mergedPayload,
14660
15724
  artifactDirective: previousDecision?.artifactDirective
14661
- ?? (shouldTerminate ? subAgentResult.artifactDirective : undefined)
15725
+ ?? (shouldTerminate ? subAgentResult.artifactDirective : undefined),
15726
+ handoff: undefined
14662
15727
  };
14663
15728
  }
14664
15729
  catch (error) {
@@ -14895,7 +15960,11 @@ The context is now within limits. Please retry your request with the recovered c
14895
15960
  async executeActionsStep(params, previousDecision, parentStepId, addConversationMessage = true, stepCount = 0, actionOptions) {
14896
15961
  try {
14897
15962
  const currentPayload = previousDecision?.newPayload || previousDecision?.previousPayload || params.payload;
14898
- const actions = previousDecision.actions || [];
15963
+ const availableForExecution = this.getAvailableActionsForAgent(params.agent.ID);
15964
+ const actions = (previousDecision.actions || []).map((a) => {
15965
+ const matched = this.resolveActionEntityForAgent(a.name, availableForExecution, params, false);
15966
+ return matched && matched.Name !== a.name ? { ...a, name: matched.Name } : { ...a };
15967
+ });
14899
15968
  // Check for cancellation before starting
14900
15969
  if (params.cancellationToken?.aborted) {
14901
15970
  throw new Error('Cancelled before action execution');
@@ -14978,14 +16047,12 @@ The context is now within limits. Please retry your request with the recovered c
14978
16047
  });
14979
16048
  }
14980
16049
  }
14981
- const actionEngine = ActionEngineServer.Instance;
14982
16050
  // Get the AIAgentAction metadata records for this agent (used for expiration settings)
14983
16051
  const agentActions = AIEngine.Instance.AgentActions.filter(aa => UUIDsEqual(aa.AgentID, params.agent.ID));
14984
16052
  // Use _effectiveActions which includes runtime action changes applied in gatherPromptTemplateData
14985
- // Fall back to database-configured actions if _effectiveActions is empty (shouldn't happen in normal flow)
14986
- const effectiveActions = this._effectiveActions.length > 0
14987
- ? this._effectiveActions
14988
- : (actionEngine.Actions || []).filter(a => agentActions.some(aa => UUIDsEqual(aa.ActionID, a.ID)));
16053
+ // getEffectiveActionsForValidation falls back to the configured actions only when none were computed;
16054
+ // an empty computed list (a host's actionChanges removed every action) is authoritative
16055
+ const effectiveActions = this.getEffectiveActionsForValidation(params.agent.ID);
14989
16056
  // Call agent type's pre-processing for actions
14990
16057
  try {
14991
16058
  const currentPayload = previousDecision?.newPayload || previousDecision?.previousPayload || params.payload;
@@ -14998,17 +16065,19 @@ The context is now within limits. Please retry your request with the recovered c
14998
16065
  }
14999
16066
  // Track step numbers for parallel actions
15000
16067
  let numActionsProcessed = 0;
15001
- const baseStepNumber = (this._agentRun.Steps?.length || 0) + 1;
16068
+ const baseStepNumber = (this._agentRun?.Steps?.length || 0) + 1;
15002
16069
  // Execute all actions in parallel
15003
16070
  let lastStep = undefined;
16071
+ const flowStepActions = this.getFlowStepActions(params.agent.ID);
15004
16072
  const actionPromises = actions.map(async (aa) => {
15005
16073
  // Find action entity from the effective actions (which includes runtime changes),
15006
- // or from actions referenced directly by this agent's Flow steps (AIAgentStep.ActionID)
15007
- let actionEntity = effectiveActions.find(a => a.Name === aa.name);
15008
- if (!actionEntity && Array.isArray(actionEngine?.Actions)) {
15009
- const agentSteps = AIEngine.Instance.GetAgentSteps?.(params.agent.ID) || [];
15010
- const stepActionIds = new UUIDSet(agentSteps.map(s => s.ActionID));
15011
- actionEntity = actionEngine.Actions.find(a => a.Name === aa.name && stepActionIds.Has(a.ID));
16074
+ // or from actions referenced directly by this agent's Flow steps (AIAgentStep.ActionID / Configuration.steps[])
16075
+ let actionEntity = this.resolveActionEntityForAgent(aa.name, effectiveActions, params, false);
16076
+ if (!actionEntity && flowStepActions.length > 0) {
16077
+ actionEntity = this.resolveActionEntityForAgent(aa.name, flowStepActions, params, false);
16078
+ }
16079
+ if (actionEntity && aa.name !== actionEntity.Name) {
16080
+ aa.name = actionEntity.Name;
15012
16081
  }
15013
16082
  if (!actionEntity) {
15014
16083
  throw new Error(`Action "${aa.name}" Not Found for Agent "${params.agent.Name}". Available actions: ${effectiveActions.map(a => a.Name).join(', ')}`);
@@ -15081,9 +16150,13 @@ The context is now within limits. Please retry your request with the recovered c
15081
16150
  actionName: result.action.name,
15082
16151
  success: isActionSuccess,
15083
16152
  params: sanitizedParams,
15084
- resultCode: actionResult?.Result?.ResultCode || (isActionSuccess ? 'SUCCESS' : 'ERROR'),
16153
+ // The action's own code when it matches none of its metadata result codes (`Result` is then
16154
+ // undefined), so a custom failure code such as UNKNOWN_ENTITY_FIELDS reaches the model
16155
+ // instead of a bare 'ERROR'.
16156
+ resultCode: actionResult?.Result?.ResultCode || actionResult?.ResultCode || (isActionSuccess ? 'SUCCESS' : 'ERROR'),
15085
16157
  message: actionResult?.Message || (isActionSuccess ? 'Action completed' : result.error || 'Unknown error'),
15086
- aiDirectives: isActionSuccess ? actionResult?.AIDirectives : undefined,
16158
+ // Kept on failure too: an action's recovery guidance is most useful when it failed.
16159
+ aiDirectives: actionResult?.AIDirectives,
15087
16160
  breakerReason: actionResult instanceof CircuitBreakerActionResult ? actionResult.Reason : undefined
15088
16161
  };
15089
16162
  });
@@ -15116,7 +16189,7 @@ The context is now within limits. Please retry your request with the recovered c
15116
16189
  }
15117
16190
  }
15118
16191
  }
15119
- // Only add metadata if we have expiration settings
16192
+ // Expiration settings only when the configuration has them; the tag itself is always stamped below.
15120
16193
  if (minExpirationTurns !== null && expirationMode !== 'None') {
15121
16194
  metadata = {
15122
16195
  turnAdded: this._promptTurnCount,
@@ -15129,6 +16202,12 @@ The context is now within limits. Please retry your request with the recovered c
15129
16202
  };
15130
16203
  }
15131
16204
  }
16205
+ // Every action result is tagged, with or without expiration settings, so IsToolResultMessage
16206
+ // and IsVolatileResultMessage recognize it: context recovery and post-run compaction can then
16207
+ // compact it, and `pruneAndCompactExpiredMessages` still leaves it alone (no expirationTurns).
16208
+ if (!metadata) {
16209
+ metadata = { turnAdded: this._promptTurnCount, messageType: 'action-result' };
16210
+ }
15132
16211
  if (addConversationMessage) {
15133
16212
  // Add user message with results and optional metadata
15134
16213
  // Failure guidance, so the model does not repeatedly loop on broken tools. Not when the breaker
@@ -15141,9 +16220,10 @@ The context is now within limits. Please retry your request with the recovered c
15141
16220
  const answeredNatively = this.appendActionResults(params, actionSummaries, resultsMessage, metadata, previousDecision, failureGuidance);
15142
16221
  // Surface explicit AI directives from action results as a separate instruction message.
15143
16222
  // Actions that need the AI to follow specific instructions (not just acknowledge data)
15144
- // populate AIDirectives on their ActionResultSimple return value.
16223
+ // populate AIDirectives on their ActionResultSimple return value. Failed actions are
16224
+ // included: a directive on a failure is the action telling the model how to recover.
15145
16225
  const allDirectives = actionSummaries
15146
- .filter(a => a.success && a.aiDirectives && a.aiDirectives.length > 0)
16226
+ .filter(a => a.aiDirectives && a.aiDirectives.length > 0)
15147
16227
  .flatMap(a => a.aiDirectives);
15148
16228
  if (allDirectives.length > 0) {
15149
16229
  const directiveText = allDirectives
@@ -15600,7 +16680,7 @@ The context is now within limits. Please retry your request with the recovered c
15600
16680
  const existing = await rv.RunView({
15601
16681
  EntityName: 'MJ: Conversation Skills',
15602
16682
  ExtraFilter: `ConversationID = '${EscapeSQLString(conversationId)}' AND SkillID = '${EscapeSQLString(skill.ID)}'`,
15603
- ResultType: 'entity_object', MaxRows: 1,
16683
+ ResultType: 'entity_object', MaxRows: 1, SkipTotalRowCount: true,
15604
16684
  }, params.contextUser);
15605
16685
  if (!existing.Success) {
15606
16686
  LogErrorEx({ message: `Could not read conversation skill '${skill.Name}': ${existing.ErrorMessage}`, severity: 'warning', category: 'AgentSkills' });
@@ -15638,7 +16718,7 @@ The context is now within limits. Please retry your request with the recovered c
15638
16718
  const existing = await rv.RunView({
15639
16719
  EntityName: 'MJ: Conversation Skills',
15640
16720
  ExtraFilter: `ConversationID = '${EscapeSQLString(conversationId)}' AND SkillID = '${EscapeSQLString(skillId)}' AND Status = 'Active'`,
15641
- ResultType: 'entity_object', MaxRows: 1,
16721
+ ResultType: 'entity_object', MaxRows: 1, SkipTotalRowCount: true,
15642
16722
  }, contextUser);
15643
16723
  const row = existing.Success ? existing.Results?.[0] : undefined;
15644
16724
  if (!row)
@@ -15921,8 +17001,8 @@ The context is now within limits. Please retry your request with the recovered c
15921
17001
  */
15922
17002
  async executeTasksStep(params, previousDecision) {
15923
17003
  const graph = previousDecision.taskGraph;
15924
- const spec = graph?.spec;
15925
- if (!spec) {
17004
+ const rawSpec = graph?.spec;
17005
+ if (!rawSpec) {
15926
17006
  return {
15927
17007
  step: 'Failed',
15928
17008
  terminate: true,
@@ -15931,6 +17011,7 @@ The context is now within limits. Please retry your request with the recovered c
15931
17011
  newPayload: previousDecision.newPayload || previousDecision.previousPayload
15932
17012
  };
15933
17013
  }
17014
+ const spec = this.canonicalizeTaskGraphSpec(rawSpec);
15934
17015
  // Fail closed under bound parameters (ExecuteAgentParams.boundActionParams): a graph's action nodes
15935
17016
  // are dispatched by the task-graph runner with the inputs the model authored, outside
15936
17017
  // ExecuteSingleAction, so nothing would hide or apply a binding. The response type already withholds
@@ -15973,6 +17054,7 @@ The context is now within limits. Please retry your request with the recovered c
15973
17054
  EnvironmentID: MJEnvironmentEntityExtended.DefaultEnvironmentID,
15974
17055
  ConversationDetailID: params.conversationDetailId ?? null,
15975
17056
  AgentRunID: this._agentRun?.ID ?? null,
17057
+ ParentAgentHierarchy: this._agentHierarchy.length > 0 ? [...this._agentHierarchy] : undefined,
15976
17058
  // If THIS run was itself started by a finished graph, the graph it emits inherits that
15977
17059
  // depth + 1. Without this the chain restarts at zero on every hop and
15978
17060
  // MAX_REINVOKE_DEPTH never fires — a graph reinvoking an agent that emits a graph would
@@ -16019,6 +17101,73 @@ The context is now within limits. Please retry your request with the recovered c
16019
17101
  newPayload: previousDecision.newPayload || previousDecision.previousPayload
16020
17102
  };
16021
17103
  }
17104
+ /**
17105
+ * Executes a `'Handoff'` next step: records the `'Handoff'` step entity with the resolved
17106
+ * target agent ID, stores {@link _handoffResult} for {@link ExecuteAgentResult.handoff},
17107
+ * and ends this run `'Success'` with the handoff message so the host can invoke the target agent.
17108
+ *
17109
+ * @protected
17110
+ */
17111
+ async executeHandoffStep(params, previousDecision) {
17112
+ const handoff = previousDecision.handoff;
17113
+ const resolved = this._resolvedHandoffTarget;
17114
+ if (!handoff || !resolved) {
17115
+ return {
17116
+ step: 'Failed',
17117
+ terminate: true,
17118
+ errorMessage: 'A Handoff step reached execution without a validated handoff target.',
17119
+ previousPayload: previousDecision.previousPayload,
17120
+ newPayload: previousDecision.newPayload || previousDecision.previousPayload
17121
+ };
17122
+ }
17123
+ if (this.runWithholdsHandoff(params)) {
17124
+ return {
17125
+ step: 'Failed',
17126
+ terminate: true,
17127
+ errorMessage: 'Handoff is not available on this run.',
17128
+ previousPayload: previousDecision.previousPayload,
17129
+ newPayload: previousDecision.newPayload || previousDecision.previousPayload
17130
+ };
17131
+ }
17132
+ const stepEntity = await this.createStepEntity({
17133
+ stepType: 'Handoff',
17134
+ stepName: `Handoff: ${resolved.name}`,
17135
+ targetId: resolved.id,
17136
+ contextUser: params.contextUser,
17137
+ inputData: {
17138
+ agentName: handoff.agentName,
17139
+ brief: handoff.brief,
17140
+ reason: handoff.reason
17141
+ }
17142
+ });
17143
+ const chain = [...(params.handoffChain ?? []), params.agent.ID];
17144
+ const hop = chain.length;
17145
+ await this.finalizeStepEntity(stepEntity, true, undefined, {
17146
+ HandoffToAgentID: resolved.id,
17147
+ TargetAgentName: resolved.name,
17148
+ Brief: handoff.brief,
17149
+ Reason: handoff.reason,
17150
+ Hop: hop,
17151
+ Chain: chain
17152
+ });
17153
+ this._handoffResult = {
17154
+ targetAgentId: resolved.id,
17155
+ targetAgentName: resolved.name,
17156
+ sourceAgentId: params.agent.ID,
17157
+ brief: handoff.brief,
17158
+ reason: handoff.reason,
17159
+ runStepId: stepEntity.ID
17160
+ };
17161
+ return {
17162
+ step: 'Success',
17163
+ terminate: true,
17164
+ message: previousDecision.message || `Transferring you to **${resolved.name}**…`,
17165
+ reasoning: previousDecision.reasoning,
17166
+ confidence: previousDecision.confidence,
17167
+ previousPayload: previousDecision.previousPayload,
17168
+ newPayload: previousDecision.newPayload || previousDecision.previousPayload
17169
+ };
17170
+ }
16022
17171
  /**
16023
17172
  * Records a constant-folded task graph (D9) without submitting it.
16024
17173
  *
@@ -16408,7 +17557,6 @@ The context is now within limits. Please retry your request with the recovered c
16408
17557
  }
16409
17558
  /**
16410
17559
  * Executes a ForEach loop with actual for loop
16411
- * @private
16412
17560
  */
16413
17561
  async executeForEachLoop(params, config, previousDecision) {
16414
17562
  const forEach = previousDecision.forEach;
@@ -16417,64 +17565,91 @@ The context is now within limits. Please retry your request with the recovered c
16417
17565
  // ForEach step with no details into a Retry whose errorMessage the model is shown.
16418
17566
  return this.createFailedStep('ForEach configuration missing', previousDecision);
16419
17567
  }
16420
- const validationMessage = this.validateForEachOperation(forEach);
16421
- if (validationMessage) {
16422
- return this.failLoopBeforeFirstIteration('ForEach', forEach.collectionPath, `ForEach configuration invalid: ${validationMessage}`, previousDecision, params, forEach.action?.name);
17568
+ const primaryActionName = forEach.action?.name ?? forEach.steps?.[0]?.name;
17569
+ const headerMessage = this.validateForEachHeader(forEach);
17570
+ if (headerMessage) {
17571
+ return this.failLoopBeforeFirstIteration('ForEach', forEach.collectionPath, `ForEach configuration invalid: ${headerMessage}`, previousDecision, params, primaryActionName);
16423
17572
  }
16424
17573
  const currentPayload = previousDecision.newPayload || previousDecision.previousPayload;
16425
17574
  const collection = this.getCollectionFromPayload(currentPayload, forEach.collectionPath);
16426
17575
  if (!collection) {
16427
- return this.failLoopBeforeFirstIteration('ForEach', forEach.collectionPath, `Collection path "${forEach.collectionPath}" not an array`, previousDecision, params, forEach.action?.name);
17576
+ return this.failLoopBeforeFirstIteration('ForEach', forEach.collectionPath, `Collection path "${forEach.collectionPath}" not an array`, previousDecision, params, primaryActionName);
17577
+ }
17578
+ const agentId = params.agent?.ID ?? this._agentRun?.AgentID ?? '';
17579
+ const bodyMessage = this.validateLoopBodyOperation('ForEach', forEach, agentId);
17580
+ if (bodyMessage) {
17581
+ return this.failLoopBeforeFirstIteration('ForEach', forEach.collectionPath, `ForEach configuration invalid: ${bodyMessage}`, previousDecision, params, primaryActionName);
16428
17582
  }
16429
17583
  const loopStepEntity = await this.createForEachLoopStep(forEach, collection, currentPayload, params);
16430
17584
  const loopResults = await this.executeForEachIterations(forEach, collection, currentPayload, loopStepEntity.ID, params, config);
16431
17585
  return this.completeForEachLoop(forEach, loopStepEntity, loopResults, previousDecision, params);
16432
17586
  }
16433
- validateWhileOperation(whileOp) {
17587
+ validateWhileOperation(whileOp, agentId = this._agentRun?.AgentID ?? '') {
16434
17588
  if (!whileOp.condition || whileOp.condition.trim() === '') {
16435
17589
  return 'Condition is required';
16436
17590
  }
16437
17591
  if (!whileOp.itemVariable || whileOp.itemVariable.trim() === '') {
16438
17592
  return 'Item variable is required';
16439
17593
  }
16440
- // now validate the action or sub-agent
16441
- if (whileOp.action) {
16442
- return this.validateActionInAgent(whileOp.action.name);
16443
- }
16444
- else if (whileOp.subAgent) {
16445
- // check to make sure sub-agent is valid
16446
- return this.validateSubAgentInAgent(whileOp.subAgent.name);
16447
- }
16448
- // if we get here, all good
16449
- return null;
17594
+ return this.validateLoopBodyOperation('While', whileOp, agentId);
16450
17595
  }
16451
- validateForEachOperation(forEach) {
16452
- // make sure that for actions it is valid action and for sub-agents it is valid sub-agent
17596
+ validateForEachHeader(forEach) {
16453
17597
  if (!forEach.itemVariable || forEach.itemVariable.trim() === '') {
16454
17598
  return 'Item variable is required';
16455
17599
  }
16456
17600
  if (!forEach.collectionPath || forEach.collectionPath.trim() === '') {
16457
17601
  return 'Collection path is required';
16458
17602
  }
16459
- if (forEach.action) {
16460
- return this.validateActionInAgent(forEach.action.name);
17603
+ return null;
17604
+ }
17605
+ /**
17606
+ * Validates the loop body arm (`action` | `steps` | `subAgent`) shared by `ForEach` and `While`.
17607
+ * Structural validation is delegated to CorePlus {@link ValidateLoopOperationStructure} so in-turn
17608
+ * and durable loops enforce one identical contract; runtime action/sub-agent membership is checked
17609
+ * here without mutating `op`.
17610
+ */
17611
+ validateLoopBodyOperation(kind, op, agentId = this._agentRun?.AgentID ?? '') {
17612
+ const structuralErrors = ValidateLoopOperationStructure(kind, op);
17613
+ if (structuralErrors.length > 0) {
17614
+ return structuralErrors[0].Message;
16461
17615
  }
16462
- else if (forEach.subAgent) {
16463
- // check to make sure sub-agent is valid
16464
- return this.validateSubAgentInAgent(forEach.subAgent.name);
17616
+ if (op.prompt) {
17617
+ return 'Prompt loop bodies are only supported in durable TaskGraph execution';
17618
+ }
17619
+ if (op.action) {
17620
+ return this.validateActionInAgent(op.action.name, agentId);
17621
+ }
17622
+ if (op.steps !== undefined) {
17623
+ for (const step of op.steps) {
17624
+ const actionErr = this.validateActionInAgent(step.name, agentId);
17625
+ if (actionErr) {
17626
+ return actionErr;
17627
+ }
17628
+ }
17629
+ return null;
17630
+ }
17631
+ if (op.subAgent) {
17632
+ return this.validateSubAgentInAgent(op.subAgent.name, agentId);
16465
17633
  }
16466
- // if we get here, all good
16467
17634
  return null;
16468
17635
  }
16469
- validateActionInAgent(actionName) {
16470
- // Use effective actions which includes runtime action changes
16471
- const effectiveActions = this.getEffectiveActionsForValidation(this._agentRun.AgentID);
17636
+ validateActionInAgent(actionName, agentId = this._agentRun?.AgentID ?? '') {
17637
+ // Use effective actions + any Flow step actions configured for this agent
17638
+ const effectiveActions = this.getAvailableActionsForAgent(agentId);
16472
17639
  const normalizedName = actionName.trim().toLowerCase();
16473
17640
  // Try exact match first
16474
17641
  const exactMatch = effectiveActions.find(a => a.Name.trim().toLowerCase() === normalizedName);
16475
17642
  if (exactMatch) {
16476
17643
  return null; // Valid
16477
17644
  }
17645
+ // Try sanitized native tool-name match
17646
+ const sanitizedMatch = this.matchNamedBySanitizedToolName(actionName, effectiveActions);
17647
+ if (sanitizedMatch.match) {
17648
+ return null;
17649
+ }
17650
+ if (sanitizedMatch.ambiguous) {
17651
+ return `Ambiguous action '${actionName}' specified. Matches: ${sanitizedMatch.ambiguous.map(a => a.Name).join(', ')}`;
17652
+ }
16478
17653
  // Try partial/contains match
16479
17654
  const partialMatches = effectiveActions.filter(a => a.Name.trim().toLowerCase().includes(normalizedName));
16480
17655
  if (partialMatches.length === 1) {
@@ -16487,24 +17662,37 @@ The context is now within limits. Please retry your request with the recovered c
16487
17662
  return `No action '${actionName}' found. Available: ${effectiveActions.map(a => a.Name).join(', ')}`;
16488
17663
  }
16489
17664
  }
16490
- validateSubAgentInAgent(subAgentName) {
17665
+ validateSubAgentInAgent(subAgentName, agentId = this._agentRun?.AgentID ?? '') {
16491
17666
  // check to make sure sub-agent is valid
16492
- const relatedAgents = AIEngine.Instance.AgentRelationships.filter(ar => UUIDsEqual(ar.AgentID, this._agentRun.AgentID));
16493
- const childAgents = AIEngine.Instance.Agents.filter(a => UUIDsEqual(a.ParentID, this._agentRun.AgentID));
16494
- // now check to make sure that subAgentName is either in relatedAgents or childAgents
16495
- let subAgent = relatedAgents.filter(ra => ra.SubAgent?.trim().toLowerCase() === subAgentName.trim().toLowerCase());
17667
+ const relatedAgents = AIEngine.Instance.AgentRelationships.filter(ar => UUIDsEqual(ar.AgentID, agentId));
17668
+ const childAgents = AIEngine.Instance.Agents.filter(a => UUIDsEqual(a.ParentID, agentId));
17669
+ const candidate = this.stripSubAgentToolPrefix(subAgentName);
17670
+ const lower = candidate.toLowerCase();
17671
+ const sanitized = SanitizeToolName(candidate);
17672
+ // Check relatedAgents: exact -> sanitized native tool name -> partial
17673
+ let subAgent = relatedAgents.filter(ra => ra.SubAgent?.trim().toLowerCase() === lower);
17674
+ if (subAgent.length === 0 && sanitized) {
17675
+ subAgent = relatedAgents.filter(ra => Boolean(ra.SubAgent && SanitizeToolName(ra.SubAgent) === sanitized));
17676
+ }
17677
+ if (subAgent.length > 1) {
17678
+ return `Ambiguous sub-agent '${subAgentName}' specified`;
17679
+ }
16496
17680
  if (subAgent.length === 0) {
16497
- // no exact match, try for partial match
16498
- subAgent = relatedAgents.filter(ra => ra.SubAgent?.trim().toLowerCase().includes(subAgentName.trim().toLowerCase() || ''));
17681
+ subAgent = relatedAgents.filter(ra => ra.SubAgent?.trim().toLowerCase().includes(lower || ''));
16499
17682
  if (subAgent.length > 1) {
16500
17683
  return `Ambiguous sub-agent '${subAgentName}' specified`;
16501
17684
  }
16502
- else if (subAgent.length === 0) {
16503
- // try child agents now
16504
- let childAgent = childAgents.filter(ca => ca.Name?.trim().toLowerCase() === subAgentName.trim().toLowerCase());
17685
+ if (subAgent.length === 0) {
17686
+ // try child agents: exact -> sanitized native tool name -> partial
17687
+ let childAgent = childAgents.filter(ca => ca.Name?.trim().toLowerCase() === lower);
17688
+ if (childAgent.length === 0 && sanitized) {
17689
+ childAgent = childAgents.filter(ca => Boolean(ca.Name && SanitizeToolName(ca.Name) === sanitized));
17690
+ }
17691
+ if (childAgent.length > 1) {
17692
+ return `Ambiguous child agent '${subAgentName}' specified`;
17693
+ }
16505
17694
  if (childAgent.length === 0) {
16506
- // no exact match, try for partial match
16507
- childAgent = childAgents.filter(ca => ca.Name?.trim().toLowerCase().includes(subAgentName.trim().toLowerCase() || ''));
17695
+ childAgent = childAgents.filter(ca => ca.Name?.trim().toLowerCase().includes(lower || ''));
16508
17696
  if (childAgent.length > 1) {
16509
17697
  return `Ambiguous child agent '${subAgentName}' specified`;
16510
17698
  }
@@ -16512,9 +17700,6 @@ The context is now within limits. Please retry your request with the recovered c
16512
17700
  return `No child agent '${subAgentName}' found`;
16513
17701
  }
16514
17702
  }
16515
- else {
16516
- // we have one match, so we're good here
16517
- }
16518
17703
  }
16519
17704
  }
16520
17705
  // if we get here, all good
@@ -16618,7 +17803,8 @@ The context is now within limits. Please retry your request with the recovered c
16618
17803
  index,
16619
17804
  result: iterResult.result,
16620
17805
  error: iterResult.error,
16621
- payload: iterResult.payload
17806
+ payload: iterResult.payload,
17807
+ appliedFolds: iterResult.appliedFolds
16622
17808
  })));
16623
17809
  const batchResults = await Promise.all(batchPromises);
16624
17810
  allResults.push(...batchResults);
@@ -16660,7 +17846,7 @@ The context is now within limits. Please retry your request with the recovered c
16660
17846
  let currentPayload = initialPayload;
16661
17847
  const results = [];
16662
17848
  const errors = [];
16663
- for (const { result, error, payload } of sortedResults) {
17849
+ for (const { result, error, payload, appliedFolds } of sortedResults) {
16664
17850
  if (error) {
16665
17851
  errors.push(error);
16666
17852
  if (!continueOnError) {
@@ -16669,17 +17855,131 @@ The context is now within limits. Please retry your request with the recovered c
16669
17855
  }
16670
17856
  else if (result) {
16671
17857
  results.push(result);
16672
- // Apply payload change from this iteration
16673
- currentPayload = payload || currentPayload;
17858
+ if (appliedFolds && appliedFolds.length > 0) {
17859
+ for (const fold of appliedFolds) {
17860
+ currentPayload = this.applyLoopOutputFold(currentPayload, fold.output, fold.mapping);
17861
+ }
17862
+ }
17863
+ else {
17864
+ // Apply payload change from this iteration
17865
+ currentPayload = payload || currentPayload;
17866
+ }
16674
17867
  }
16675
17868
  }
16676
17869
  return { results, errors, finalPayload: currentPayload };
16677
17870
  }
17871
+ extractActionOutputObject(summaries) {
17872
+ return BuildActionOutputObject(summaries[0]?.params, summaries[0]?.message);
17873
+ }
17874
+ applyLoopOutputFold(basePayload, output, mapping) {
17875
+ const target = IsPlainObject(basePayload)
17876
+ ? this.cloneSubAgentPayload(basePayload)
17877
+ : {};
17878
+ const mapped = ApplyOutputMapping(output, mapping, target);
17879
+ return mapped.updates;
17880
+ }
17881
+ /**
17882
+ * Executes an ordered sequence of `LoopBodyActionStep` actions inside a single `ForEach` or `While`
17883
+ * iteration, chaining step outputs under `steps.<id>.*` / `steps.step_<index>.*`, evaluating optional
17884
+ * per-step `condition` expressions, folding optional per-step `outputMapping` onto the working payload,
17885
+ * and halting remaining steps in the pass if any step fails.
17886
+ */
17887
+ async executeLoopStepsIteration(args) {
17888
+ const { steps, item, itemVariable, index, attemptContext, currentPayload, parentStepId, params } = args;
17889
+ const stepsOutputs = {};
17890
+ const appliedFolds = [];
17891
+ const aggregatedSummaries = [];
17892
+ const evaluator = new SafeExpressionEvaluator();
17893
+ let workingPayload = IsPlainObject(currentPayload)
17894
+ ? this.cloneSubAgentPayload(currentPayload)
17895
+ : {};
17896
+ for (let stepIdx = 0; stepIdx < steps.length; stepIdx++) {
17897
+ const step = steps[stepIdx];
17898
+ const stepKey = step.id?.trim() || `step_${stepIdx}`;
17899
+ const stepBindings = {
17900
+ ...(attemptContext ? { attemptNumber: attemptContext.attemptNumber, totalAttempts: attemptContext.totalAttempts } : {}),
17901
+ item,
17902
+ [itemVariable]: item,
17903
+ index,
17904
+ steps: stepsOutputs
17905
+ };
17906
+ if (step.condition?.trim()) {
17907
+ const conditionScope = {
17908
+ ...workingPayload,
17909
+ ...stepBindings,
17910
+ payload: { ...workingPayload, ...stepBindings },
17911
+ steps: stepsOutputs,
17912
+ index,
17913
+ iteration: index,
17914
+ ...(params.data !== undefined ? { data: params.data } : {}),
17915
+ ...(params.context !== undefined ? { context: params.context } : {})
17916
+ };
17917
+ const evalResult = evaluator.evaluate(step.condition.trim(), conditionScope);
17918
+ if (!evalResult.success) {
17919
+ throw new Error(`Loop step "${stepKey}" condition "${step.condition}" could not be evaluated: ${evalResult.error ?? 'unknown error'}`);
17920
+ }
17921
+ if (!evalResult.value) {
17922
+ continue;
17923
+ }
17924
+ }
17925
+ const matchedAction = this.findAgentActionForLoop(step.name, params.agent.ID, params.agent.Name, params);
17926
+ const stepPayload = { ...workingPayload, ...stepBindings };
17927
+ const resolvedParams = ResolveLoopBodyParams(step.params ?? {}, stepBindings, { payload: stepPayload, data: params.data, context: params.context });
17928
+ const actionStep = {
17929
+ step: 'Actions',
17930
+ actions: [{ name: matchedAction.Action, params: resolvedParams }],
17931
+ newPayload: workingPayload,
17932
+ previousPayload: workingPayload,
17933
+ terminate: false
17934
+ };
17935
+ const stepResult = await this.executeActionsStep(params, actionStep, parentStepId, false, 0, { skipCircuitBreaker: true });
17936
+ const summaries = Array.isArray(stepResult.priorStepResult)
17937
+ ? stepResult.priorStepResult
17938
+ : [];
17939
+ aggregatedSummaries.push(...summaries);
17940
+ const failedSummary = summaries.find((s) => !s.success);
17941
+ if (failedSummary) {
17942
+ throw new Error(`Loop step "${stepKey}" (${matchedAction.Action}) failed: ${failedSummary.message || failedSummary.resultCode || 'Action failed'}`);
17943
+ }
17944
+ const stepOutput = this.extractActionOutputObject(summaries);
17945
+ stepsOutputs[stepKey] = stepOutput;
17946
+ if (stepKey !== `step_${stepIdx}`) {
17947
+ stepsOutputs[`step_${stepIdx}`] ??= stepOutput;
17948
+ }
17949
+ if (step.outputMapping?.trim()) {
17950
+ workingPayload = this.applyLoopOutputFold(workingPayload, stepOutput, step.outputMapping);
17951
+ appliedFolds.push({ output: stepOutput, mapping: step.outputMapping });
17952
+ }
17953
+ else if (IsPlainObject(stepResult.newPayload)) {
17954
+ workingPayload = stepResult.newPayload;
17955
+ }
17956
+ }
17957
+ const outPayload = IsPlainObject(currentPayload) || appliedFolds.length > 0 ? workingPayload : currentPayload;
17958
+ const syntheticStep = {
17959
+ step: 'Retry',
17960
+ terminate: false,
17961
+ previousPayload: currentPayload,
17962
+ newPayload: outPayload,
17963
+ priorStepResult: aggregatedSummaries
17964
+ };
17965
+ return { payload: outPayload, result: syntheticStep, appliedFolds };
17966
+ }
16678
17967
  /**
16679
17968
  * Helper: Execute single ForEach iteration
16680
17969
  */
16681
- async executeSingleForEachIteration(forEach, item, index, currentPayload, parentStepId, params, config) {
17970
+ async executeSingleForEachIteration(forEach, item, index, currentPayload, parentStepId, params, _config) {
16682
17971
  try {
17972
+ if (Array.isArray(forEach.steps) && forEach.steps.length > 0) {
17973
+ return await this.executeLoopStepsIteration({
17974
+ steps: forEach.steps,
17975
+ item,
17976
+ itemVariable: forEach.itemVariable || 'item',
17977
+ index,
17978
+ currentPayload,
17979
+ parentStepId,
17980
+ params
17981
+ });
17982
+ }
16683
17983
  // Resolve params via BeforeLoopIteration hook
16684
17984
  const beforeHook = this.AgentTypeInstance.BeforeLoopIteration?.({ item, itemVariable: forEach.itemVariable, index, payload: currentPayload, loopType: 'ForEach', actionParams: forEach.action?.params || {} });
16685
17985
  let resolvedParams = beforeHook?.actionParams || forEach.action?.params || {};
@@ -16713,12 +18013,24 @@ The context is now within limits. Please retry your request with the recovered c
16713
18013
  result.priorStepResult = this.formatSubAgentResultAsMarkdown(forEach.subAgent.name, result);
16714
18014
  }
16715
18015
  else {
16716
- throw new Error('ForEach missing action/subAgent');
18016
+ throw new Error('ForEach missing action/steps/subAgent');
16717
18017
  }
16718
- // Apply AfterLoopIteration hook
18018
+ // Apply AfterLoopIteration hook (or ApplyOutputMapping fallback when LoopAgentType has no hook)
16719
18019
  const iterPayload = result.newPayload || currentPayload;
16720
18020
  const afterHook = this.AgentTypeInstance.AfterLoopIteration?.({ currentPayload: iterPayload, item, itemVariable: forEach.itemVariable, index, loopContext: { actionOutputMapping: forEach.action?.outputMapping } });
16721
- return { payload: afterHook || iterPayload, result };
18021
+ if (afterHook) {
18022
+ return { payload: afterHook, result };
18023
+ }
18024
+ if (forEach.action?.outputMapping?.trim() && Array.isArray(result.priorStepResult)) {
18025
+ const stepOutput = this.extractActionOutputObject(result.priorStepResult);
18026
+ const folded = this.applyLoopOutputFold(iterPayload, stepOutput, forEach.action.outputMapping);
18027
+ return {
18028
+ payload: folded,
18029
+ result,
18030
+ appliedFolds: [{ output: stepOutput, mapping: forEach.action.outputMapping }]
18031
+ };
18032
+ }
18033
+ return { payload: iterPayload, result };
16722
18034
  }
16723
18035
  catch (error) {
16724
18036
  return { error: { index, item, message: error.message } };
@@ -16732,7 +18044,7 @@ The context is now within limits. Please retry your request with the recovered c
16732
18044
  loopStepEntity.PayloadAtEnd = this.serializePayloadAtEnd(loopResults.finalPayload);
16733
18045
  await this.finalizeStepEntity(loopStepEntity, loopResults.errors.length === 0, this.formatLoopErrors(loopResults.errors), loopResults);
16734
18046
  if (this.AgentTypeInstance.InjectLoopResultsAsMessage) {
16735
- this.injectLoopResultsMessage('ForEach', forEach.collectionPath, loopResults.results, loopResults.errors, params, forEach.action?.name);
18047
+ this.injectLoopResultsMessage('ForEach', forEach.collectionPath, loopResults.results, loopResults.errors, params, forEach.action?.name ?? forEach.steps?.[0]?.name);
16736
18048
  }
16737
18049
  return {
16738
18050
  step: 'Retry',
@@ -16858,10 +18170,9 @@ The context is now within limits. Please retry your request with the recovered c
16858
18170
  // Look up the loop's action config for expiration settings
16859
18171
  if (actionName) {
16860
18172
  const agentActions = AIEngine.Instance.AgentActions.filter(aa => UUIDsEqual(aa.AgentID, params.agent.ID));
16861
- const effectiveActions = this._effectiveActions.length > 0
16862
- ? this._effectiveActions
16863
- : ActionEngineServer.Instance.Actions.filter(a => agentActions.some(aa => UUIDsEqual(aa.ActionID, a.ID)));
16864
- const matchedAction = effectiveActions.find(a => a.Name.trim().toLowerCase() === actionName.trim().toLowerCase());
18173
+ const effectiveActions = this.getEffectiveActionsForValidation(params.agent.ID);
18174
+ const matchedAction = effectiveActions.find(a => a.Name.trim().toLowerCase() === actionName.trim().toLowerCase())
18175
+ ?? this.matchNamedBySanitizedToolName(actionName, effectiveActions).match;
16865
18176
  if (matchedAction) {
16866
18177
  const agentAction = agentActions.find(aa => UUIDsEqual(aa.ActionID, matchedAction.ID));
16867
18178
  if (agentAction?.ResultExpirationTurns != null && agentAction.ResultExpirationMode !== 'None') {
@@ -16891,11 +18202,22 @@ The context is now within limits. Please retry your request with the recovered c
16891
18202
  * @since 2.123.0 - Updated to use _effectiveActions for dynamic action support
16892
18203
  */
16893
18204
  findAgentActionForLoop(actionName, agentId, agentName, params) {
16894
- // Use effective actions which includes runtime action changes
16895
- const effectiveActions = this.getEffectiveActionsForValidation(agentId);
18205
+ // Use effective actions + Flow step actions configured for this agent
18206
+ const effectiveActions = this.getAvailableActionsForAgent(agentId);
16896
18207
  const normalizedName = actionName.trim().toLowerCase();
16897
18208
  // Try exact match first
16898
18209
  let matchedAction = effectiveActions.find(a => a.Name.trim().toLowerCase() === normalizedName);
18210
+ // Try sanitized native tool-name match
18211
+ if (!matchedAction) {
18212
+ const sanitizedMatch = this.matchNamedBySanitizedToolName(actionName, effectiveActions);
18213
+ if (sanitizedMatch.match) {
18214
+ matchedAction = sanitizedMatch.match;
18215
+ this.logStatus(`Action native tool name matched: '${actionName}' → '${matchedAction.Name}'`, true, params);
18216
+ }
18217
+ else if (sanitizedMatch.ambiguous) {
18218
+ throw new Error(`Ambiguous action '${actionName}'. Matches: ${sanitizedMatch.ambiguous.map(a => a.Name).join(', ')}`);
18219
+ }
18220
+ }
16899
18221
  // Fallback: CONTAINS search
16900
18222
  if (!matchedAction) {
16901
18223
  const containsMatches = effectiveActions.filter(a => a.Name.trim().toLowerCase().includes(normalizedName));
@@ -16927,7 +18249,6 @@ The context is now within limits. Please retry your request with the recovered c
16927
18249
  }
16928
18250
  /**
16929
18251
  * Executes a While loop with actual while loop
16930
- * @private
16931
18252
  */
16932
18253
  async executeWhileLoop(params, config, previousDecision) {
16933
18254
  const whileOp = previousDecision.while;
@@ -16936,9 +18257,11 @@ The context is now within limits. Please retry your request with the recovered c
16936
18257
  // While step with no details into a Retry whose errorMessage the model is shown.
16937
18258
  return this.createFailedStep('While configuration missing', previousDecision);
16938
18259
  }
16939
- const validationMessage = this.validateWhileOperation(whileOp);
18260
+ const primaryActionName = whileOp.action?.name ?? whileOp.steps?.[0]?.name;
18261
+ const agentId = params.agent?.ID ?? this._agentRun?.AgentID ?? '';
18262
+ const validationMessage = this.validateWhileOperation(whileOp, agentId);
16940
18263
  if (validationMessage) {
16941
- return this.failLoopBeforeFirstIteration('While', whileOp.condition, `While configuration invalid: ${validationMessage}`, previousDecision, params, whileOp.action?.name);
18264
+ return this.failLoopBeforeFirstIteration('While', whileOp.condition, `While configuration invalid: ${validationMessage}`, previousDecision, params, primaryActionName);
16942
18265
  }
16943
18266
  const currentPayload = previousDecision.newPayload || previousDecision.previousPayload;
16944
18267
  const loopStepEntity = await this.createWhileLoopStep(whileOp, currentPayload, params);
@@ -17004,8 +18327,21 @@ The context is now within limits. Please retry your request with the recovered c
17004
18327
  /**
17005
18328
  * Helper: Execute single While iteration
17006
18329
  */
17007
- async executeSingleWhileIteration(whileOp, attemptContext, index, currentPayload, parentStepId, params, config) {
18330
+ async executeSingleWhileIteration(whileOp, attemptContext, index, currentPayload, parentStepId, params, _config) {
17008
18331
  try {
18332
+ if (Array.isArray(whileOp.steps) && whileOp.steps.length > 0) {
18333
+ const stepsOutcome = await this.executeLoopStepsIteration({
18334
+ steps: whileOp.steps,
18335
+ item: attemptContext,
18336
+ itemVariable: whileOp.itemVariable || 'attempt',
18337
+ index,
18338
+ attemptContext,
18339
+ currentPayload,
18340
+ parentStepId,
18341
+ params
18342
+ });
18343
+ return { payload: stepsOutcome.payload, result: stepsOutcome.result };
18344
+ }
17009
18345
  // Resolve params via BeforeLoopIteration hook
17010
18346
  const beforeHook = this.AgentTypeInstance.BeforeLoopIteration?.({ item: attemptContext, index, itemVariable: whileOp.itemVariable, payload: currentPayload, loopType: 'While', actionParams: whileOp.action?.params || {} });
17011
18347
  let resolvedParams = beforeHook?.actionParams || whileOp.action?.params || {};
@@ -17038,12 +18374,20 @@ The context is now within limits. Please retry your request with the recovered c
17038
18374
  result.priorStepResult = this.formatSubAgentResultAsMarkdown(whileOp.subAgent.name, result);
17039
18375
  }
17040
18376
  else {
17041
- throw new Error('While missing action/subAgent');
18377
+ throw new Error('While missing action/steps/subAgent');
17042
18378
  }
17043
- // Apply AfterLoopIteration hook
18379
+ // Apply AfterLoopIteration hook (or ApplyOutputMapping fallback when LoopAgentType has no hook)
17044
18380
  const iterPayload = result.newPayload || currentPayload;
17045
18381
  const afterHook = this.AgentTypeInstance.AfterLoopIteration?.({ currentPayload: iterPayload, item: attemptContext, itemVariable: whileOp.itemVariable, index, loopContext: { actionOutputMapping: whileOp.action?.outputMapping } });
17046
- return { payload: afterHook || iterPayload, result };
18382
+ if (afterHook) {
18383
+ return { payload: afterHook, result };
18384
+ }
18385
+ if (whileOp.action?.outputMapping?.trim() && Array.isArray(result.priorStepResult)) {
18386
+ const stepOutput = this.extractActionOutputObject(result.priorStepResult);
18387
+ const folded = this.applyLoopOutputFold(iterPayload, stepOutput, whileOp.action.outputMapping);
18388
+ return { payload: folded, result };
18389
+ }
18390
+ return { payload: iterPayload, result };
17047
18391
  }
17048
18392
  catch (error) {
17049
18393
  return { error: { index, item: attemptContext, message: error.message } };
@@ -17058,7 +18402,7 @@ The context is now within limits. Please retry your request with the recovered c
17058
18402
  // Inject before the early return below: a Loop agent re-prompts after a Failed step, and the
17059
18403
  // loop-results message (the condition error, under Errors) is the only way the model learns why.
17060
18404
  if (this.AgentTypeInstance.InjectLoopResultsAsMessage) {
17061
- this.injectLoopResultsMessage('While', whileOp.condition, loopResults.results, loopResults.errors, params, whileOp.action?.name);
18405
+ this.injectLoopResultsMessage('While', whileOp.condition, loopResults.results, loopResults.errors, params, whileOp.action?.name ?? whileOp.steps?.[0]?.name);
17062
18406
  }
17063
18407
  // A condition that never evaluated means the loop never ran: fail the step rather than
17064
18408
  // report a completed zero-iteration loop.
@@ -17349,6 +18693,7 @@ The context is now within limits. Please retry your request with the recovered c
17349
18693
  mediaOutputs: this._mediaOutputs.length > 0 ? this._mediaOutputs : undefined,
17350
18694
  fileOutputs: this._fileOutputs.length > 0 ? this._fileOutputs : undefined,
17351
18695
  feedbackRequestId: this._feedbackRequestId || undefined,
18696
+ handoff: this._handoffResult || undefined,
17352
18697
  resolvedStorageAccountId: this._resolvedStorageAccountId || undefined
17353
18698
  };
17354
18699
  }
@@ -18292,6 +19637,7 @@ The context is now within limits. Please retry your request with the recovered c
18292
19637
  || messageType === 'client-tool-result'
18293
19638
  || messageType === BaseAgent.toolResultMessageType
18294
19639
  || messageType === 'sub-agent-result'
19640
+ || messageType === 'sub-agent-consult'
18295
19641
  || messageType === 'loop-result';
18296
19642
  }
18297
19643
  estimateTokens(content, modelName) {
@@ -18483,7 +19829,7 @@ The context is now within limits. Please retry your request with the recovered c
18483
19829
  // we only do this if the string starts and ends with the {{ }} pattern
18484
19830
  // and we trim whitespace first
18485
19831
  const trimmedValue = value.trim();
18486
- if (trimmedValue.startsWith('{{') && trimmedValue.endsWith('}}')) {
19832
+ if (trimmedValue.startsWith('{{') && trimmedValue.endsWith('}}') && !trimmedValue.slice(2, -2).includes('{{')) {
18487
19833
  // Single-variable case: "{{city.name}}" — strip wrappers, fall through to
18488
19834
  // single-variable resolution below which can return non-string types (objects, numbers)
18489
19835
  value = trimmedValue.substring(2, trimmedValue.length - 2).trim();
@@ -18626,16 +19972,37 @@ The context is now within limits. Please retry your request with the recovered c
18626
19972
  */
18627
19973
  validatedRunScope(params) {
18628
19974
  const inputs = this.runScopeInputs(params);
19975
+ // Only a run whose host assigned scopes carries the key, so every other run keeps the shape it had
19976
+ const searchScopeIDs = this.hostSearchScopeIDs(params);
19977
+ const hostScopes = searchScopeIDs ? { SearchScopeIDs: searchScopeIDs } : {};
18629
19978
  if (!inputs.EntityName && !inputs.RecordID && !inputs.Secondary) {
18630
- return { PrimaryScopeEntityName: null, PrimaryScopeRecordID: null, SecondaryScopes: null };
19979
+ return { PrimaryScopeEntityName: null, PrimaryScopeRecordID: null, SecondaryScopes: null, ...hostScopes };
18631
19980
  }
18632
19981
  const secondary = this.validateAndApplySecondaryScopes(inputs.Secondary, this.parseSecondaryScopeConfig(params.agent), params.agent.Name);
18633
19982
  return {
18634
19983
  PrimaryScopeEntityName: inputs.EntityName ?? null,
18635
19984
  PrimaryScopeRecordID: inputs.RecordID ?? null,
18636
19985
  SecondaryScopes: secondary && Object.keys(secondary).length > 0 ? secondary : null,
19986
+ ...hostScopes,
18637
19987
  };
18638
19988
  }
19989
+ /**
19990
+ * The search scopes the host assigned this run ({@link ExecuteAgentParams.SearchScopeIDs}): trimmed, de-duplicated,
19991
+ * in the host's order, or `null` for none. Read from the first-class parameter only — never from `data`, which a
19992
+ * caller could otherwise use to hand an agent a scope its own SearchScopeAccess refuses.
19993
+ */
19994
+ hostSearchScopeIDs(params) {
19995
+ const seen = new UUIDSet();
19996
+ const ids = [];
19997
+ for (const id of params.SearchScopeIDs ?? []) {
19998
+ const trimmed = typeof id === 'string' ? id.trim() : '';
19999
+ if (trimmed && !seen.Has(trimmed)) {
20000
+ seen.Add(trimmed);
20001
+ ids.push(trimmed);
20002
+ }
20003
+ }
20004
+ return ids.length > 0 ? ids : null;
20005
+ }
18639
20006
  /**
18640
20007
  * Writes the validated run scope onto the run row: the primary entity resolved to its ID (logged when it is
18641
20008
  * not in metadata), the tenant record ID and the secondary dimensions as JSON. A secondary-only scope on an