@memberjunction/ai-agents 6.2.0-edge.4 → 6.2.0-edge.5

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 (104) hide show
  1. package/README.md +94 -7
  2. package/dist/AgentRunner.d.ts +6 -3
  3. package/dist/AgentRunner.d.ts.map +1 -1
  4. package/dist/AgentRunner.js +163 -38
  5. package/dist/AgentRunner.js.map +1 -1
  6. package/dist/ArtifactToolManager.d.ts +11 -3
  7. package/dist/ArtifactToolManager.d.ts.map +1 -1
  8. package/dist/ArtifactToolManager.js +72 -6
  9. package/dist/ArtifactToolManager.js.map +1 -1
  10. package/dist/ClientToolRequestManager.d.ts +11 -1
  11. package/dist/ClientToolRequestManager.d.ts.map +1 -1
  12. package/dist/ClientToolRequestManager.js +19 -6
  13. package/dist/ClientToolRequestManager.js.map +1 -1
  14. package/dist/PayloadChangeAnalyzer.d.ts.map +1 -1
  15. package/dist/PayloadChangeAnalyzer.js +53 -30
  16. package/dist/PayloadChangeAnalyzer.js.map +1 -1
  17. package/dist/PayloadManager.d.ts +35 -2
  18. package/dist/PayloadManager.d.ts.map +1 -1
  19. package/dist/PayloadManager.js +250 -149
  20. package/dist/PayloadManager.js.map +1 -1
  21. package/dist/ScratchpadManager.d.ts +18 -0
  22. package/dist/ScratchpadManager.d.ts.map +1 -1
  23. package/dist/ScratchpadManager.js +61 -0
  24. package/dist/ScratchpadManager.js.map +1 -1
  25. package/dist/agent-audience.d.ts +38 -0
  26. package/dist/agent-audience.d.ts.map +1 -0
  27. package/dist/agent-audience.js +99 -0
  28. package/dist/agent-audience.js.map +1 -0
  29. package/dist/agent-context-injector.d.ts +17 -2
  30. package/dist/agent-context-injector.d.ts.map +1 -1
  31. package/dist/agent-context-injector.js +23 -7
  32. package/dist/agent-context-injector.js.map +1 -1
  33. package/dist/agent-memory-context-builder.d.ts +7 -2
  34. package/dist/agent-memory-context-builder.d.ts.map +1 -1
  35. package/dist/agent-memory-context-builder.js +12 -3
  36. package/dist/agent-memory-context-builder.js.map +1 -1
  37. package/dist/agent-pre-execution-rag.d.ts +101 -9
  38. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  39. package/dist/agent-pre-execution-rag.js +224 -23
  40. package/dist/agent-pre-execution-rag.js.map +1 -1
  41. package/dist/agent-types/flow-agent-type.d.ts +8 -0
  42. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  43. package/dist/agent-types/flow-agent-type.js +48 -6
  44. package/dist/agent-types/flow-agent-type.js.map +1 -1
  45. package/dist/agent-types/loop-agent-response-type.d.ts +8 -2
  46. package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
  47. package/dist/agent-types/loop-agent-response-type.js.map +1 -1
  48. package/dist/agent-types/loop-agent-type.d.ts +9 -2
  49. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  50. package/dist/agent-types/loop-agent-type.js +60 -16
  51. package/dist/agent-types/loop-agent-type.js.map +1 -1
  52. package/dist/base-agent.d.ts +568 -31
  53. package/dist/base-agent.d.ts.map +1 -1
  54. package/dist/base-agent.js +2294 -421
  55. package/dist/base-agent.js.map +1 -1
  56. package/dist/index.d.ts +4 -0
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +4 -0
  59. package/dist/index.js.map +1 -1
  60. package/dist/memory-manager-agent.d.ts.map +1 -1
  61. package/dist/memory-manager-agent.js +46 -34
  62. package/dist/memory-manager-agent.js.map +1 -1
  63. package/dist/native-tools/action-param-schema.d.ts +57 -0
  64. package/dist/native-tools/action-param-schema.d.ts.map +1 -0
  65. package/dist/native-tools/action-param-schema.js +238 -0
  66. package/dist/native-tools/action-param-schema.js.map +1 -0
  67. package/dist/native-tools/action-tool-builder.d.ts +5 -4
  68. package/dist/native-tools/action-tool-builder.d.ts.map +1 -1
  69. package/dist/native-tools/action-tool-builder.js +29 -71
  70. package/dist/native-tools/action-tool-builder.js.map +1 -1
  71. package/dist/native-tools/json-argument.d.ts +41 -0
  72. package/dist/native-tools/json-argument.d.ts.map +1 -0
  73. package/dist/native-tools/json-argument.js +79 -0
  74. package/dist/native-tools/json-argument.js.map +1 -0
  75. package/dist/query-builder-agent.d.ts +13 -4
  76. package/dist/query-builder-agent.d.ts.map +1 -1
  77. package/dist/query-builder-agent.js +102 -27
  78. package/dist/query-builder-agent.js.map +1 -1
  79. package/dist/realtime/realtime-client-session-service.d.ts +5 -4
  80. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  81. package/dist/realtime/realtime-client-session-service.js +42 -30
  82. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  83. package/dist/realtime/realtime-coagent-config.d.ts +8 -1
  84. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  85. package/dist/realtime/realtime-coagent-config.js +17 -1
  86. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  87. package/dist/realtime/realtime-recording-ledger.d.ts +130 -0
  88. package/dist/realtime/realtime-recording-ledger.d.ts.map +1 -0
  89. package/dist/realtime/realtime-recording-ledger.js +190 -0
  90. package/dist/realtime/realtime-recording-ledger.js.map +1 -0
  91. package/dist/realtime/realtime-recording-opus-assembly.d.ts +211 -0
  92. package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -0
  93. package/dist/realtime/realtime-recording-opus-assembly.js +706 -0
  94. package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -0
  95. package/dist/realtime/realtime-recording-store.d.ts +38 -1
  96. package/dist/realtime/realtime-recording-store.d.ts.map +1 -1
  97. package/dist/realtime/realtime-recording-store.js +58 -30
  98. package/dist/realtime/realtime-recording-store.js.map +1 -1
  99. package/dist/realtime/realtime-turn-moderator.d.ts +2 -1
  100. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  101. package/dist/realtime/realtime-turn-moderator.js +7 -1
  102. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  103. package/dist/volatile-child-prompt.js +3 -3
  104. package/package.json +21 -19
@@ -11,11 +11,12 @@
11
11
  * @since 2.49.0
12
12
  */
13
13
  import { MJEnvironmentEntityExtended, ConversationEngine } from '@memberjunction/core-entities';
14
- import { BuildActionToolSet, FilterDeclarableActions, SanitizeToolName } from './native-tools/action-tool-builder.js';
14
+ import { BuildActionToolSet, CoerceActionArguments, FilterDeclarableActions, SanitizeToolName } from './native-tools/action-tool-builder.js';
15
+ import { DescribeValueSchemaInline, GetStoredValueSchema } from './native-tools/action-param-schema.js';
15
16
  import { BuildNativeToolSet, COMPLETE_TASK_TOOL, SUB_AGENT_TOOL_PREFIX } from './native-tools/control-tools.js';
16
17
  import { BuildAssistantToolCallTurn, BuildToolResultTurn, CompactToolResultContent } from './native-tools/tool-result-turns.js';
17
18
  import { LooksLikeLoopEnvelope } from './native-tools/dual-channel.js';
18
- import { MJAIAgentRunEntityExtended, ResolvePromptRunUserID } from "@memberjunction/ai-core-plus";
19
+ import { MJAIAgentRunEntityExtended, ResolvePromptRunUserID, ResolvePayloadAtEnd } from "@memberjunction/ai-core-plus";
19
20
  import { Metadata, RunView, LogStatus, LogStatusEx, LogError, LogErrorEx, IsVerboseLoggingEnabled, DatabaseProviderBase, ToPlainJSON } from '@memberjunction/core';
20
21
  import { AgentRunWatchdog } from './agent-run-watchdog.js';
21
22
  import { AIPromptRunner, GetToolCallingDecision } from '@memberjunction/ai-prompts';
@@ -23,7 +24,7 @@ import { BaseRealtimeModel, GetAIAPIKey, CredentialScopeAllows, MakeAIAPIKeyReso
23
24
  import { BaseAgentType } from './agent-types/base-agent-type.js';
24
25
  import { ProviderRubricEngine } from '@memberjunction/rubrics';
25
26
  import { ExecuteSelfCheck, PickSelfCheckLink } from './self-check.js';
26
- import { CopyScalarsAndArrays, JSONValidator, MJGlobal, NormalizeUUID, SafeExpressionEvaluator, UUIDsEqual, EscapeSQLString, IsPlainObject, CleanAndParseJSON, IsValidUUID } from '@memberjunction/global';
27
+ import { CopyScalarsAndArrays, JSONValidator, MJGlobal, NormalizeUUID, SafeExpressionEvaluator, UUIDsEqual, EscapeSQLString, IsPlainObject, CleanAndParseJSON, IsValidUUID, IndexByUUID } from '@memberjunction/global';
27
28
  // token optimization via @memberjunction/context-crush (SmartCrusher/CacheAligner-inspired)
28
29
  import { CrushJSON, DescribeCrush, PartitionStablePrefix } from '@memberjunction/context-crush';
29
30
  // AST-aware code reduction (CodeCompressor-inspired) — opt-in per agent type
@@ -49,8 +50,10 @@ import { FormatToolResultSection, FormatToolErrorSection, RenderToolResultData,
49
50
  import { PriorTurnToolResultCache } from './prior-turn-tool-result-cache.js';
50
51
  import { PromptComponentResolver, InjectScopedPromptParts } from './prompt-component-resolver.js';
51
52
  import { ScopedPromptConfigResolver, ApplyScopedPromptConfig } from './scoped-prompt-config-resolver.js';
52
- import { StringifyForPersistence, AIPromptParams, ChildPromptParam, ConversationUtility, ParseFileOutputRef, parseAssignmentStrategy, ResolveClientTools, initAgentRunStep, finalizeAgentRunStep, AgentRunStepSaveQueue, ExtractPromptResultText, GetTaskGraphSubmitter, SummarizeDecisionAnswers, SystemPlaceholderManager } from '@memberjunction/ai-core-plus';
53
- import { ActionResult, RunActionParams } from '@memberjunction/actions-base';
53
+ import { StringifyForPersistence, AIPromptParams, ChildPromptParam, ConversationUtility, ParseFileOutputRef, parseAssignmentStrategy, ResolveClientTools, initAgentRunStep, finalizeAgentRunStep, AgentRunStepSaveQueue, ExtractPromptResultText, GetTaskGraphSubmitter, SummarizeDecisionAnswers, SystemPlaceholderManager, WithoutHostOnlyAgentRunDataKeys, WithAgentRunDataTrustApplied, AgentUserPolicyEngine, ConfigOf } from '@memberjunction/ai-core-plus';
54
+ import { ActionResult, RunActionParams, AUDIENCE_UNSUPPORTED_RESULT_CODE, ActionRunScopeIsBounded } from '@memberjunction/actions-base';
55
+ import { UserCache } from '@memberjunction/generic-database-provider';
56
+ import { AgentAudienceAddsReader, AgentAudienceProblem, AgentAudienceReaderIDs, MatchAudienceUsers } from './agent-audience.js';
54
57
  import { TemplateEngineServer } from '@memberjunction/templates';
55
58
  import { RuntimeStateFragmentBuilder, EscapeRuntimeStateTagsInMessage } from './runtime-state-fragment.js';
56
59
  import { ResolveSpecializationPlacement } from './volatile-child-prompt.js';
@@ -187,6 +190,13 @@ export class BaseAgent {
187
190
  * @private
188
191
  */
189
192
  this._fatalActionFailures = new Set();
193
+ /**
194
+ * Actions the action engine refused for the run's audience (`AUDIENCE_UNSUPPORTED`) during the current run —
195
+ * locked out like {@link _fatalActionFailures}, under their own breaker reason (`'audience'`) so the model is
196
+ * told the action is unavailable in a shared conversation rather than misconfigured.
197
+ * @private
198
+ */
199
+ this._audienceLockedActions = new Set();
190
200
  /**
191
201
  * Parameter-aware failure tracking per action name for the current agent run.
192
202
  * Differentiates identical retries (which trip quickly) from parameter modifications (which allow self-correction).
@@ -251,6 +261,14 @@ export class BaseAgent {
251
261
  */
252
262
  this._feedbackRequestId = null;
253
263
  this._resolvedStorageAccountId = null;
264
+ /**
265
+ * Most recent artifactDirective returned by a child or related sub-agent during this run.
266
+ * Preserved as a fallback in {@link finalizeAgentRun} when an orchestrator (e.g. Sage) wraps
267
+ * up a delegated sub-agent's response on the subsequent turn without re-emitting its own
268
+ * artifactDirective.
269
+ * @private
270
+ */
271
+ this._lastSubAgentArtifactDirective = undefined;
254
272
  /**
255
273
  * Agent hierarchy for display purposes (e.g., ["Marketing Agent", "Copywriter Agent"]).
256
274
  * Tracked separately as it's display-only and doesn't need persistence.
@@ -422,6 +440,12 @@ export class BaseAgent {
422
440
  * prompt execution occurred after them.
423
441
  */
424
442
  this._promptTurnCount = 0;
443
+ /**
444
+ * The non-volatile stack the previous Prompt step of the current run recorded: each message's
445
+ * reference and its serialized form. A later Prompt step records only a delta when its stack
446
+ * extends this one append-only; otherwise it records the full stack.
447
+ */
448
+ this._lastRecordedPromptStack = null;
425
449
  /**
426
450
  * Per-run config for structurally compressing inline action-result payloads.
427
451
  * Resolved once at run start from the agent-type prompt params (default on);
@@ -514,6 +538,15 @@ export class BaseAgent {
514
538
  * unshifted onto `conversationMessages` by the shared {@link AgentMemoryContextBuilder}.
515
539
  */
516
540
  this._injectedRAG = null;
541
+ /**
542
+ * Per-instance memoization for runtime-state template delivery analysis and template-array indexing
543
+ * so multi-turn agent loops do not repeatedly scan template collections and strings on every turn.
544
+ * @private
545
+ */
546
+ this._lastRuntimeStateDeliveryCache = null;
547
+ this._cachedTemplatesArrayRef = null;
548
+ this._templateByIdMap = null;
549
+ this._templateEngineConfiguredForRun = false;
517
550
  /**
518
551
  * Checks execution guardrails and modifies next step if limits are exceeded.
519
552
  * This method is called after validation but before execution of non-terminal steps.
@@ -567,6 +600,13 @@ export class BaseAgent {
567
600
  * @private
568
601
  */
569
602
  static { this.MAX_CONSECUTIVE_UNPRODUCTIVE_RETRIES = 10; }
603
+ /**
604
+ * Gets the shared {@link AgentTreeBudget} tracking cumulative steps, tokens, cost,
605
+ * and elapsed wall-clock duration across the root agent and all descendant sub-agents.
606
+ */
607
+ get TreeBudget() {
608
+ return this._treeBudget;
609
+ }
570
610
  /**
571
611
  * The identity of one action call's arguments, for the circuit breaker's identical-arguments
572
612
  * rule: two calls with the same normalized string are "the same call", whatever order the model
@@ -697,10 +737,7 @@ export class BaseAgent {
697
737
  */
698
738
  recordActionFailure(action, actionEntity, message, normalizedParams) {
699
739
  if (this.isFatalActionError(message, action.params)) {
700
- this._fatalActionFailures.add(action.name);
701
- if (actionEntity?.Name) {
702
- this._fatalActionFailures.add(actionEntity.Name);
703
- }
740
+ this.lockOutAction(action, actionEntity);
704
741
  return;
705
742
  }
706
743
  const existing = this._actionFailureHistory.get(action.name) || (actionEntity?.Name ? this._actionFailureHistory.get(actionEntity.Name) : undefined);
@@ -715,6 +752,41 @@ export class BaseAgent {
715
752
  this._actionFailureHistory.set(actionEntity.Name, record);
716
753
  }
717
754
  }
755
+ /**
756
+ * Locks an action out for the rest of the run: later calls short-circuit on the breaker's `'fatal'` rule, or on
757
+ * its `'audience'` rule for an action the engine refused for the run's audience.
758
+ */
759
+ lockOutAction(action, actionEntity, reason = 'fatal') {
760
+ const lockouts = reason === 'audience' ? this._audienceLockedActions : this._fatalActionFailures;
761
+ lockouts.add(action.name);
762
+ if (actionEntity?.Name) {
763
+ lockouts.add(actionEntity.Name);
764
+ }
765
+ }
766
+ /** Clears the run-scoped circuit-breaker state (both lockouts and the failure history) for a new run. */
767
+ resetActionCircuitBreaker() {
768
+ this._fatalActionFailures.clear();
769
+ this._audienceLockedActions.clear();
770
+ this._actionFailureHistory.clear();
771
+ }
772
+ /**
773
+ * The blocked result for an action locked out for the run — refused for the audience (`'audience'`), or failed
774
+ * with an unrecoverable configuration or credential error (`'fatal'`) — or null when it is not locked out.
775
+ */
776
+ lockedOutActionResult(params, action, actionEntity) {
777
+ const isLocked = (lockouts) => lockouts.has(action.name) || (!!actionEntity?.Name && lockouts.has(actionEntity.Name));
778
+ if (isLocked(this._audienceLockedActions)) {
779
+ this.logStatus(` ⚡ Circuit breaker: Action '${action.name}' short-circuited (0ms): not available under this run's audience`, false, params);
780
+ return this.buildBlockedActionResult(actionEntity, 'audience', `Action '${action.name}' is not available in this shared conversation: what it returns could not be limited to what ` +
781
+ 'everyone here may see. Do not call it again in this run; use another tool or answer from what you have.');
782
+ }
783
+ if (isLocked(this._fatalActionFailures)) {
784
+ this.logStatus(` ⚡ Circuit breaker: Action '${action.name}' short-circuited (0ms): fatal configuration or credential error earlier in this run`, false, params);
785
+ return this.buildBlockedActionResult(actionEntity, 'fatal', `Action '${action.name}' is disabled for this run because it previously failed with an unrecoverable configuration or ` +
786
+ 'credential error. You must select an alternative action.');
787
+ }
788
+ return null;
789
+ }
718
790
  /**
719
791
  * Clears the parameter-aware failure history for an action after it succeeds, so the
720
792
  * identical-arguments rule and the consecutive-attempt budget start over.
@@ -728,14 +800,14 @@ export class BaseAgent {
728
800
  /**
729
801
  * Applies the three circuit-breaker rules to a call that is about to be dispatched. Returns a
730
802
  * blocked result, with the rule that fired, when the call must not go to the action engine;
731
- * null when it may proceed. Rules are checked fatal → identical-arguments → budget.
803
+ * null when it may proceed. Rules are checked audience → fatal → identical-arguments → budget.
732
804
  */
733
805
  checkActionCircuitBreaker(params, action, actionEntity, normalizedParams) {
734
- const entityKey = actionEntity?.Name;
735
- if (this._fatalActionFailures.has(action.name) || (entityKey && this._fatalActionFailures.has(entityKey))) {
736
- this.logStatus(` ⚡ Circuit breaker: Action '${action.name}' short-circuited (0ms): fatal configuration or credential error earlier in this run`, false, params);
737
- return this.buildBlockedActionResult(actionEntity, 'fatal', `Action '${action.name}' is disabled for this run because it previously failed with an unrecoverable configuration or credential error. You must select an alternative action.`);
806
+ const lockedOut = this.lockedOutActionResult(params, action, actionEntity);
807
+ if (lockedOut) {
808
+ return lockedOut;
738
809
  }
810
+ const entityKey = actionEntity?.Name;
739
811
  const record = this._actionFailureHistory.get(action.name) || (entityKey ? this._actionFailureHistory.get(entityKey) : undefined);
740
812
  if (!record) {
741
813
  return null;
@@ -773,6 +845,9 @@ export class BaseAgent {
773
845
  if (summary.breakerReason) {
774
846
  return summary.breakerReason;
775
847
  }
848
+ if (this._audienceLockedActions.has(summary.actionName)) {
849
+ return 'audience';
850
+ }
776
851
  if (this._fatalActionFailures.has(summary.actionName)) {
777
852
  return 'fatal';
778
853
  }
@@ -793,6 +868,10 @@ export class BaseAgent {
793
868
  const name = summary.actionName;
794
869
  const record = this._actionFailureHistory.get(name);
795
870
  switch (this.classifyActionFailure(summary)) {
871
+ case 'audience':
872
+ return `[CRITICAL/NOT_AVAILABLE_IN_SHARED_CONVERSATION] Action '${name}' is not available in this shared conversation: what it ` +
873
+ `returns could not be limited to what everyone in it may see ("${summary.message}"). It is not broken or misconfigured. ` +
874
+ `DO NOT call '${name}' again during this run. Use another tool, or answer from what you already have.`;
796
875
  case 'fatal':
797
876
  return `[CRITICAL/ACTION_UNAVAILABLE] Action '${name}' failed with an unrecoverable configuration or credential error: "${summary.message}". This action cannot execute in this environment. DO NOT call '${name}' again during this run. You MUST select an alternative tool or proceed with available data.`;
798
877
  case 'attempts-exhausted':
@@ -1183,6 +1262,13 @@ export class BaseAgent {
1183
1262
  * @protected
1184
1263
  */
1185
1264
  get FileOutputs() { return this._fileOutputs; }
1265
+ /**
1266
+ * Protected accessor for the run's scratchpad manager.
1267
+ * @protected
1268
+ */
1269
+ get scratchpadManager() {
1270
+ return this._scratchpadManager;
1271
+ }
1186
1272
  /** The longest the catalog narrowing decision may take before the run shows the full catalog. */
1187
1273
  static { this.CATALOG_NARROWING_TIMEOUT_MS = 30000; }
1188
1274
  /** The skills activated so far in this run (requested or self-activated), in activation order. */
@@ -1334,6 +1420,13 @@ export class BaseAgent {
1334
1420
  this.logStatus(`⏭️ Data preloading disabled for agent '${params.agent.Name}'`, true, params);
1335
1421
  return;
1336
1422
  }
1423
+ // Skipped under an audience: data sources load with the caller's rights alone, and what they load is
1424
+ // put in front of the model (or the actions) for a room that may not be allowed to see it.
1425
+ if (this.runAudienceAddsReader(params)) {
1426
+ this.logStatus(`⏭️ Data preloading skipped for agent '${params.agent.Name}': the run has an audience, ` +
1427
+ 'and preloaded data is loaded with the caller\'s rights alone', false, params);
1428
+ return;
1429
+ }
1337
1430
  try {
1338
1431
  // Load preloaded data using the singleton service
1339
1432
  const preloadedResult = await AgentDataPreloader.Instance.PreloadAgentData(params.agent.ID, params.contextUser, this._agentRun?.ID);
@@ -1408,7 +1501,7 @@ export class BaseAgent {
1408
1501
  this._agentRun.ErrorMessage = existing
1409
1502
  ? `${existing}\n\n[Data Preloading Warning] ${warningMessage}`
1410
1503
  : `[Data Preloading Warning] ${warningMessage}`;
1411
- await this._agentRun.Save();
1504
+ await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
1412
1505
  }
1413
1506
  }
1414
1507
  else {
@@ -1428,6 +1521,22 @@ export class BaseAgent {
1428
1521
  });
1429
1522
  }
1430
1523
  }
1524
+ /**
1525
+ * The params a run executes with: `params` itself, or, when the caller did not set
1526
+ * `ExecuteAgentParams.TrustReservedRunData` and `data` carries reserved keys, a copy whose `data` lacks them
1527
+ * (`WithAgentRunDataTrustApplied` in `@memberjunction/ai-core-plus`). {@link Execute} applies it first, so it
1528
+ * holds for every entry point: AgentRunner, the Execute Agent action, MCP, A2A, Runtime Actions, sub-agents.
1529
+ * The removed keys are logged once with the agent and user, never their values.
1530
+ */
1531
+ withRunDataTrustApplied(params) {
1532
+ const { Params, StrippedKeys } = WithAgentRunDataTrustApplied(params);
1533
+ if (StrippedKeys.length > 0) {
1534
+ this.logStatus(`🔒 Ignored reserved run-data key(s) ${StrippedKeys.join(', ')} for agent '${params.agent?.Name}' ` +
1535
+ `(user ${params.contextUser?.Email ?? 'unknown'}): a run's scope and agent-type parameters come from the ` +
1536
+ `ExecuteAgentParams fields, or from data only when the server sets TrustReservedRunData.`, false, params);
1537
+ }
1538
+ return Params;
1539
+ }
1431
1540
  /**
1432
1541
  * Executes an AI agent using hierarchical prompt composition.
1433
1542
  *
@@ -1466,6 +1575,14 @@ export class BaseAgent {
1466
1575
  return 2 * 60 * 60 * 1000;
1467
1576
  }
1468
1577
  async Execute(params) {
1578
+ // Initialize or inherit the shared root-tree cumulative budget before any shallow clone of
1579
+ // `params` occurs so that callers, parent agents, and child runs share one object reference.
1580
+ this._treeBudget = undefined;
1581
+ this.ensureTreeBudget(params);
1582
+ // Every run, whatever started it: the reserved data keys (scope, agent-type params) count only when the
1583
+ // caller set TrustReservedRunData. Everything below reads the cleaned params.
1584
+ params = this.withRunDataTrustApplied(params);
1585
+ this.ensureTreeBudget(params);
1469
1586
  // Capture per-request provider for the duration of this execution so all entity
1470
1587
  // saves go through the isolated provider, never the global singleton's transaction.
1471
1588
  this._activeProvider = params.provider ?? Metadata.Provider;
@@ -1551,13 +1668,14 @@ export class BaseAgent {
1551
1668
  // Capture for lifecycle hooks that don't receive params (post-turn compaction
1552
1669
  // inside finalizeAgentRun reads conversationId / verbose / provider from here).
1553
1670
  this._executeParams = wrappedParams;
1671
+ this.ensureTreeBudget(wrappedParams);
1554
1672
  this._agentConfig = undefined;
1555
1673
  this._lastModelSelectionInfo = undefined;
1556
1674
  this._lastVolatileStateMessage = undefined;
1557
1675
  this._resolvedTrailingStateMode = undefined;
1558
1676
  this._turn1InsertionIndex = -1;
1559
- this._fatalActionFailures.clear();
1560
- this._actionFailureHistory.clear();
1677
+ this._runScope = undefined; // set again by initializeAgentRun, in Phase 1
1678
+ this.resetActionCircuitBreaker();
1561
1679
  // Convert UI markup in conversation messages to plain text if requested (default: true)
1562
1680
  if (params.convertUIMarkupToPlainText !== false) {
1563
1681
  this.convertUIMarkupInMessages(wrappedParams.conversationMessages);
@@ -1605,7 +1723,7 @@ export class BaseAgent {
1605
1723
  // Report initialization progress
1606
1724
  wrappedParams.onProgress?.({
1607
1725
  step: 'initialization',
1608
- message: this.formatHierarchicalMessage(`Initializing ${params.agent.Name} agent and preparing execution environment`),
1726
+ message: this.buildInitializationProgressMessage(params),
1609
1727
  metadata: {
1610
1728
  stepCount: 0,
1611
1729
  hierarchicalStep: this.buildHierarchicalStep(0, this._parentStepCounts)
@@ -1629,26 +1747,30 @@ export class BaseAgent {
1629
1747
  // Permission denied — mark the already-created AgentRun as failed so it doesn't
1630
1748
  // appear as a phantom "running" record in the UI.
1631
1749
  const errorMessage = `User ${params.contextUser.Email} does not have permission to run agent '${params.agent.Name}' (ID: ${params.agent.ID})`;
1632
- this.logStatus(`🚫 ${errorMessage}`, false, params);
1633
- if (this._agentRun) {
1634
- this._agentRun.Status = 'Failed';
1635
- this._agentRun.ErrorMessage = errorMessage;
1636
- await this._agentRun.Save();
1637
- }
1638
- throw new Error(errorMessage);
1750
+ await this.failRunAtStart(errorMessage, params);
1639
1751
  }
1640
1752
  // Reset per-run state (sync, instant — no parallelization needed)
1753
+ this._audienceReaders = undefined;
1754
+ this._audienceSource = undefined;
1641
1755
  this._validationRetryCount = 0;
1642
1756
  this._generalValidationRetryCount = 0;
1643
1757
  this._contextRecoveryAttempts = 0;
1644
1758
  this._effectiveActions = [];
1645
1759
  this._dynamicActionLimits = {};
1646
1760
  this._mediaOutputs = [];
1761
+ this._lastSubAgentArtifactDirective = undefined;
1647
1762
  this._messageLifecycleCallback = params.onMessageLifecycle;
1648
1763
  this._catalogNarrowing = undefined;
1649
1764
  this._openingRequest = OpeningRequestText(params.conversationMessages);
1650
1765
  this._runExecutionScope = this.runPromptExecutionScope(params);
1651
1766
  this._isOpeningTurn = IsOpeningTurn(params.conversationMessages);
1767
+ // The run's audience: validated and hydrated before any memory, retrieval or prompt (Phase 2). A
1768
+ // malformed audience, or one naming a user who does not exist, fails the run here, as a refused
1769
+ // permission does — running without it would show the room the caller's whole reach.
1770
+ const audience = await this.audienceReadersFor(params);
1771
+ if ('Error' in audience) {
1772
+ await this.failRunAtStart(audience.Error, params);
1773
+ }
1652
1774
  // Resolve storage account for file artifacts
1653
1775
  this._resolvedStorageAccountId = await this.getStorageAccountID(wrappedParams);
1654
1776
  // Check for cancellation after Phase 1
@@ -1658,7 +1780,7 @@ export class BaseAgent {
1658
1780
  // Report validation progress
1659
1781
  wrappedParams.onProgress?.({
1660
1782
  step: 'validation',
1661
- message: this.formatHierarchicalMessage('Validating agent configuration and loading prompts'),
1783
+ message: this.formatHierarchicalMessage('Gathering context...'),
1662
1784
  metadata: {
1663
1785
  stepCount: 0,
1664
1786
  hierarchicalStep: this.buildHierarchicalStep(0, this._parentStepCounts)
@@ -1684,24 +1806,9 @@ export class BaseAgent {
1684
1806
  const companyId = params.companyId;
1685
1807
  const lastUserMessage = params.conversationMessages.filter(m => m.role === 'user').pop();
1686
1808
  const inputText = lastUserMessage?.content || '';
1687
- const scopeConfigJson = params.agent.ScopeConfig;
1688
- let scopeConfig = null;
1689
- if (scopeConfigJson) {
1690
- try {
1691
- scopeConfig = JSON.parse(scopeConfigJson);
1692
- }
1693
- catch { /* ignore bad JSON */ }
1694
- }
1695
- const primaryScopeEntityName = params.PrimaryScopeEntityName ?? params.data?.PrimaryScopeEntityName;
1696
- const primaryScopeRecordId = params.PrimaryScopeRecordID ?? params.data?.PrimaryScopeRecordID;
1697
- const secondaryScopes = params.SecondaryScopes ?? params.data?.SecondaryScopes;
1698
- let primaryScopeEntityId;
1699
- if (primaryScopeEntityName) {
1700
- const primaryEntity = this.ProviderToUse.EntityByName(primaryScopeEntityName);
1701
- if (primaryEntity) {
1702
- primaryScopeEntityId = primaryEntity.ID;
1703
- }
1704
- }
1809
+ // The run's scope exactly as initializeAgentRun validated it in Phase 1 — what the run row records and every
1810
+ // action is handed — so notes, RAG and scoped prompt parts search the same tenant and dimensions.
1811
+ const runScope = this.runScopeForContext(params);
1705
1812
  // The user's new message, captured by identity before anything below adds to the list, so a
1706
1813
  // resumed stopped run can be spliced in ahead of it once the parallel phase settles.
1707
1814
  const continuationMessage = wrappedParams.conversationMessages[wrappedParams.conversationMessages.length - 1];
@@ -1709,8 +1816,14 @@ export class BaseAgent {
1709
1816
  const [config, , , , , stoppedRunContinuation] = await Promise.all([
1710
1817
  this.loadAgentConfiguration(params.agent),
1711
1818
  this.preloadAgentData(wrappedParams),
1712
- this.InjectContextMemory(typeof inputText === 'string' ? inputText : '', params.agent, userId, companyId, params.contextUser, wrappedParams.conversationMessages, primaryScopeEntityId, primaryScopeRecordId, secondaryScopes, scopeConfig),
1713
- this.InjectPreExecutionRAG(typeof inputText === 'string' ? inputText : '', params.agent, params.contextUser, wrappedParams.conversationMessages, params.conversationMessages, primaryScopeEntityId, primaryScopeRecordId, secondaryScopes, params.payload),
1819
+ this.InjectContextMemory(typeof inputText === 'string' ? inputText : '', params.agent, userId, companyId, params.contextUser, wrappedParams.conversationMessages, runScope.EntityID, runScope.RecordID, runScope.Secondary, this.parseSecondaryScopeConfig(params.agent),
1820
+ // Under an audience, one user's notes and examples are not shown to the room.
1821
+ this.runAudienceAddsReader(params)),
1822
+ this.InjectPreExecutionRAG(typeof inputText === 'string' ? inputText : '', params.agent, params.contextUser, wrappedParams.conversationMessages, params.conversationMessages, runScope.EntityID, runScope.RecordID, runScope.Secondary, params.payload,
1823
+ // Phase 1 has already activated requested + persisted conversation skills.
1824
+ this.activeSkillIDsForRun(params),
1825
+ // Each reader must pass the scope gate; the search keeps what every one of them may read.
1826
+ this._audienceReaders ?? []),
1714
1827
  // Carry the previous turn's tool results forward (no-op without a
1715
1828
  // conversationId). Runs here so the results are in the messages before
1716
1829
  // the pre-turn compaction check and the first prompt.
@@ -1726,7 +1839,9 @@ export class BaseAgent {
1726
1839
  this.applyStoppedRunContinuation(wrappedParams, stoppedRunContinuation, continuationMessage);
1727
1840
  // Inject scope-resolved prompt parts (role-faithful) for this agent's prompt, alongside
1728
1841
  // memory/RAG. Synchronous — parts are cached on AIEngine. Uses the same run scope.
1729
- this.InjectScopedPromptParts(params.agent, wrappedParams.conversationMessages, primaryScopeEntityId, primaryScopeRecordId, secondaryScopes);
1842
+ const messagesBeforeParts = new Set(wrappedParams.conversationMessages);
1843
+ this.InjectScopedPromptParts(params.agent, wrappedParams.conversationMessages, runScope.EntityID, runScope.RecordID, runScope.Secondary);
1844
+ await this.replaceScopedPartPlaceholders(wrappedParams.conversationMessages, messagesBeforeParts, params.contextUser);
1730
1845
  if (!config.success) {
1731
1846
  this.logError(`Failed to load agent configuration: ${config.errorMessage}`, {
1732
1847
  agent: params.agent,
@@ -1751,6 +1866,11 @@ export class BaseAgent {
1751
1866
  // their execution falls through to `executeAgentInternal` below — byte-for-byte unchanged.
1752
1867
  // =====================================================================================
1753
1868
  if (this.isSessionDrivenAgentType(this.AgentTypeInstance)) {
1869
+ const audienceRefusal = this.sessionAudienceRefusal(params);
1870
+ if (audienceRefusal) {
1871
+ this.logError(audienceRefusal, { agent: params.agent, category: 'RealtimeSession' });
1872
+ return await this.createFailureResult(audienceRefusal, params.contextUser);
1873
+ }
1754
1874
  this.logStatus(`🎙️ Agent '${params.agent.Name}' is session-driven — routing to RealtimeSessionRunner`, true, params);
1755
1875
  return await this.executeRealtimeSession(wrappedParams, config);
1756
1876
  }
@@ -1769,7 +1889,7 @@ export class BaseAgent {
1769
1889
  stepCount: executionResult.stepCount,
1770
1890
  hierarchicalStep: this.buildHierarchicalStep(executionResult.stepCount, this._parentStepCounts)
1771
1891
  },
1772
- message: this.formatHierarchicalMessage('Finalizing agent execution')
1892
+ message: this.formatHierarchicalMessage('Wrapping up...')
1773
1893
  });
1774
1894
  // Finalize the agent run
1775
1895
  this.logStatus(`✅ Finalizing execution for agent '${params.agent.Name}'`, true, params);
@@ -1817,7 +1937,198 @@ export class BaseAgent {
1817
1937
  this.skipHeldDecisions(params, this.runEndForHeldDecisions());
1818
1938
  this.releasePerRunDataCache();
1819
1939
  await this.finalizeRun(this.deriveRunOutcome());
1940
+ // The run is over: a later direct ExecuteSingleAction resolves the scope and the audience from its own params.
1941
+ this.clearRunBoundState();
1942
+ }
1943
+ }
1944
+ /**
1945
+ * Fails the run at its start, before any prompt: marks the already-created AgentRun Failed with the message
1946
+ * (so it never shows as a phantom "running" record) and throws, which {@link Execute} turns into a failure
1947
+ * result. Used by the permission check and the audience check.
1948
+ */
1949
+ async failRunAtStart(errorMessage, params) {
1950
+ this.logStatus(`🚫 ${errorMessage}`, false, params);
1951
+ if (this._agentRun) {
1952
+ this._agentRun.Status = 'Failed';
1953
+ this._agentRun.ErrorMessage = errorMessage;
1954
+ await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
1955
+ }
1956
+ throw new Error(errorMessage);
1957
+ }
1958
+ /**
1959
+ * The run's audience readers beyond the caller, hydrated once per run and audience: from the per-run state
1960
+ * when it was hydrated from this same `params.Audience`, else validated and loaded now. `{ Error }` names
1961
+ * what makes the audience unusable. `{ Readers: [] }` when the audience adds nobody.
1962
+ */
1963
+ async audienceReadersFor(params) {
1964
+ if (this._audienceReaders && this._audienceSource === params.Audience) {
1965
+ return { Readers: this._audienceReaders };
1966
+ }
1967
+ const resolved = await this.resolveRunAudience(params);
1968
+ if ('Readers' in resolved) {
1969
+ this._audienceReaders = resolved.Readers;
1970
+ this._audienceSource = params.Audience;
1820
1971
  }
1972
+ return resolved;
1973
+ }
1974
+ /**
1975
+ * Validates `params.Audience` ({@link AgentAudienceProblem}) and loads a hydrated user for each reader it adds
1976
+ * beyond the caller ({@link ResolveAudienceUsers}). An ID no user has is refused, never skipped: a skipped
1977
+ * reader would restrict nothing, and the room would see the caller's whole reach.
1978
+ */
1979
+ async resolveRunAudience(params) {
1980
+ const problem = AgentAudienceProblem(params.Audience);
1981
+ if (problem) {
1982
+ return { Error: `Invalid Audience: ${problem}` };
1983
+ }
1984
+ const ids = AgentAudienceReaderIDs(params.Audience, params.contextUser?.ID);
1985
+ if (ids.length === 0) {
1986
+ return { Readers: [] };
1987
+ }
1988
+ const match = MatchAudienceUsers(ids, await this.ResolveAudienceUsers(ids, params));
1989
+ if (match.MissingIDs.length > 0) {
1990
+ return { Error: `Audience names user ID(s) that match no user: ${match.MissingIDs.join(', ')}. The run is refused rather than run without them.` };
1991
+ }
1992
+ this.logStatus(`👥 Run audience: ${match.Readers.length} reader(s) besides the caller — output limited to what every one of them may see`, true, params);
1993
+ return { Readers: match.Readers };
1994
+ }
1995
+ /**
1996
+ * Loads the hydrated user (with its `UserRoles`) for each audience ID, from the server's `UserCache`. When an
1997
+ * ID is missing the cache is refreshed once — a user created since it loaded is then found, as MJServer's
1998
+ * authentication does for a user it does not know — and looked up again. Returns the users found; an ID left
1999
+ * out refuses the run. Override to resolve readers from another directory; never build `UserInfo` by hand.
2000
+ *
2001
+ * An inactive user is accepted as a reader, deliberately: a reader can only narrow what the run shows (each one is
2002
+ * another permission check every result must pass), never widen it, so a deactivated participant still listed in
2003
+ * the room restricts the run rather than failing it.
2004
+ *
2005
+ * @param ids The reader IDs the audience adds beyond the caller (normalized, distinct).
2006
+ * @param params The run's parameters (for the request-scoped provider the refresh reads through).
2007
+ */
2008
+ async ResolveAudienceUsers(ids, params) {
2009
+ const cached = MatchAudienceUsers(ids, UserCache.Instance.Users);
2010
+ if (cached.MissingIDs.length === 0) {
2011
+ return cached.Readers;
2012
+ }
2013
+ const provider = params.provider ?? this.ProviderToUse;
2014
+ if (provider instanceof DatabaseProviderBase) {
2015
+ this.logStatus(`👥 ${cached.MissingIDs.length} audience reader(s) not in the user cache — refreshing it once`, true, params);
2016
+ await UserCache.Instance.Refresh(provider);
2017
+ }
2018
+ return MatchAudienceUsers(ids, UserCache.Instance.Users).Readers;
2019
+ }
2020
+ /**
2021
+ * Whether this run's audience adds a reader beyond the caller — the condition every audience gate asks.
2022
+ * A malformed audience counts as adding one (the run fails before the gates are reached anyway).
2023
+ */
2024
+ runAudienceAddsReader(params) {
2025
+ return AgentAudienceAddsReader(params.Audience, params.contextUser?.ID);
2026
+ }
2027
+ /**
2028
+ * Why this run is not offered task graphs and refuses one the model writes, or null when it may use them — the one
2029
+ * predicate, so every condition that withholds graphs is added in one place. A graph runs outside the run: its
2030
+ * action nodes are dispatched by the task-graph runner (MJServer's `TaskGraphActionRunner`) with no `Audience`,
2031
+ * no `RunScope` and no run `Context`, outside {@link ExecuteSingleAction}, and an agent node starts a run
2032
+ * (`TaskGraphAgentRunner`) that carries neither the audience nor the scope. So graphs are withheld when the
2033
+ * audience adds a reader, and when the run's validated scope carries a tenant or a secondary dimension
2034
+ * (`ActionRunScopeIsBounded`): a model-written Scoped Search node would search outside the run's tenant, and an
2035
+ * agent node would drop it.
2036
+ */
2037
+ taskGraphWithholdingReason(params) {
2038
+ if (this.runAudienceAddsReader(params)) {
2039
+ return 'a run with an audience';
2040
+ }
2041
+ return ActionRunScopeIsBounded(this._runScope ?? this.validatedRunScope(params)) ? 'a tenant-scoped run' : null;
2042
+ }
2043
+ /** Whether this run withholds task graphs ({@link taskGraphWithholdingReason}). */
2044
+ runWithholdsTaskGraphs(params) {
2045
+ return this.taskGraphWithholdingReason(params) !== null;
2046
+ }
2047
+ /**
2048
+ * The `Failed` step for a task graph the model wrote although this run withholds them ({@link taskGraphWithholdingReason}),
2049
+ * or null when graphs are allowed. The response type already hides `tasks`; this is the gate for a model that emits one
2050
+ * anyway. Written before any step: nothing is submitted.
2051
+ */
2052
+ taskGraphRefusal(params, previousDecision) {
2053
+ const reason = this.taskGraphWithholdingReason(params);
2054
+ if (!reason) {
2055
+ return null;
2056
+ }
2057
+ return {
2058
+ step: 'Failed',
2059
+ terminate: true,
2060
+ errorMessage: `Task graphs are not available in ${reason}: a graph dispatches its actions and agents outside the run, ` +
2061
+ "where nothing limits them to the run's audience or scope.",
2062
+ previousPayload: previousDecision.previousPayload,
2063
+ newPayload: previousDecision.newPayload || previousDecision.previousPayload
2064
+ };
2065
+ }
2066
+ /**
2067
+ * What this run's prompt leaves out: task graphs ({@link taskGraphWithholdingReason}), and — when the audience adds a
2068
+ * reader — the caller's own browser and view (`CallerContext`): client tools run in the caller's browser and what they
2069
+ * return reaches the room, and the app context (`data.appContext`, with its `AdditionalContext`) is the caller's screen.
2070
+ */
2071
+ promptWithholding(params) {
2072
+ return { TaskGraphs: this.runWithholdsTaskGraphs(params), CallerContext: this.runAudienceAddsReader(params) };
2073
+ }
2074
+ /**
2075
+ * The client-tools and app-context prompt sections ({@link buildClientToolPromptSection}, {@link buildAppContextSection}),
2076
+ * both empty when the caller's context is withheld ({@link promptWithholding}): the prompt then offers no client tool
2077
+ * and none of the caller's app context. {@link executeClientToolsStep} refuses a client-tools step emitted anyway.
2078
+ */
2079
+ callerContextSections(agent, extraData, withhold) {
2080
+ if (withhold) {
2081
+ return { clientToolDetails: '', appContext: '' };
2082
+ }
2083
+ return {
2084
+ clientToolDetails: this.buildClientToolPromptSection(agent, extraData),
2085
+ appContext: this.buildAppContextSection(extraData),
2086
+ };
2087
+ }
2088
+ /**
2089
+ * The `Failed` step for a client-tools step under an audience, or null. Client tools run in the caller's browser and
2090
+ * what they return comes back into a run whose output reaches the room; the prompt does not offer them then
2091
+ * ({@link callerContextSections}), and this refuses a step the model emits anyway, as {@link taskGraphRefusal} does a graph.
2092
+ */
2093
+ clientToolsRefusal(params, previousDecision) {
2094
+ if (!this.runAudienceAddsReader(params)) {
2095
+ return null;
2096
+ }
2097
+ return {
2098
+ step: 'Failed',
2099
+ terminate: true,
2100
+ errorMessage: "Client tools are not available in a run with an audience: they run in the caller's browser, " +
2101
+ 'and what they return would reach everyone in the conversation.',
2102
+ previousPayload: previousDecision.previousPayload,
2103
+ newPayload: previousDecision.newPayload || previousDecision.previousPayload
2104
+ };
2105
+ }
2106
+ /** Clears what bounds one run — its validated scope and its hydrated audience — once the run is over. */
2107
+ clearRunBoundState() {
2108
+ this._runScope = undefined;
2109
+ this._audienceReaders = undefined;
2110
+ this._audienceSource = undefined;
2111
+ }
2112
+ /**
2113
+ * A copy of the agent-type prompt params with task graphs withheld (`enableTaskGraphs` off and the `tasks`
2114
+ * response section hidden). A copy, never a write: the input may be the process-wide cached base.
2115
+ */
2116
+ withoutTaskGraphs(promptParams) {
2117
+ const responseType = IsPlainObject(promptParams.includeResponseTypeDefinition)
2118
+ ? promptParams.includeResponseTypeDefinition
2119
+ : {};
2120
+ return { ...promptParams, enableTaskGraphs: false, includeResponseTypeDefinition: { ...responseType, tasks: false } };
2121
+ }
2122
+ /**
2123
+ * Why a session-driven (realtime / voice / bridge) run is refused, or null. A live session speaks and calls
2124
+ * tools outside the gates that hold a run to its audience, so a run whose audience adds a reader is refused.
2125
+ */
2126
+ sessionAudienceRefusal(params) {
2127
+ if (!this.runAudienceAddsReader(params)) {
2128
+ return null;
2129
+ }
2130
+ return `Agent '${params.agent.Name}' is session-driven (realtime), and realtime sessions cannot yet be limited to an audience; ` +
2131
+ 'run it without an Audience, or use a non-realtime agent for a shared conversation.';
1821
2132
  }
1822
2133
  /**
1823
2134
  * Releases this run's PerRun-scoped preloaded-data cache entry. `preloadAgentData()`
@@ -1936,6 +2247,11 @@ export class BaseAgent {
1936
2247
  * @throws When the agent configuration fails to load or no usable Realtime model can be resolved.
1937
2248
  */
1938
2249
  async StartBridgeRealtimeSession(params) {
2250
+ // A bridged session is session-driven: refused under an audience that adds a reader, as Execute refuses one.
2251
+ const audienceRefusal = this.sessionAudienceRefusal(params);
2252
+ if (audienceRefusal) {
2253
+ throw new Error(audienceRefusal);
2254
+ }
1939
2255
  // Mirror Execute()'s provider wiring so the realtime helpers operate on the request-scoped provider.
1940
2256
  this._activeProvider = params.provider ?? Metadata.Provider;
1941
2257
  const provider = params.provider ?? Metadata.Provider;
@@ -2214,7 +2530,7 @@ export class BaseAgent {
2214
2530
  promptRun.StreamingEnabled = true;
2215
2531
  promptRun.Cancelled = false;
2216
2532
  promptRun.CacheHit = false;
2217
- if (!await promptRun.Save()) {
2533
+ if (!await promptRun.Save({ SaveReturnMode: 'datestamps_only' })) {
2218
2534
  this.logError(`Failed to create realtime AIPromptRun: ${promptRun.LatestResult?.CompleteMessage ?? 'unknown error'}`, {
2219
2535
  agent: params.agent,
2220
2536
  category: 'RealtimeSession'
@@ -2335,7 +2651,9 @@ export class BaseAgent {
2335
2651
  const inputText = typeof lastUserMessage?.content === 'string' ? lastUserMessage.content : '';
2336
2652
  const scratch = [];
2337
2653
  const builder = new AgentMemoryContextBuilder();
2338
- 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));
2654
+ 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),
2655
+ // Unreachable under an audience today (session-driven runs are refused); kept so it never leaks one.
2656
+ this.runAudienceAddsReader(params));
2339
2657
  return scratch
2340
2658
  .map(m => (typeof m.content === 'string' ? m.content : ''))
2341
2659
  .filter(c => c.length > 0)
@@ -2383,8 +2701,11 @@ export class BaseAgent {
2383
2701
  configurationId: params.configurationId,
2384
2702
  apiKeys: params.apiKeys,
2385
2703
  CredentialScope: params.CredentialScope,
2704
+ Audience: params.Audience, // the target answers the same people, so it is bounded the same way
2386
2705
  data: params.data,
2706
+ TrustReservedRunData: params.TrustReservedRunData, // the session's data, already vetted when it started
2387
2707
  verbose: params.verbose,
2708
+ treeBudget: this.ensureTreeBudget(params),
2388
2709
  // Progress streams BOTH to the runner's narration consumer (request.OnProgress —
2389
2710
  // it paces SendContextNote/RequestSpokenUpdate over the live socket) AND to any
2390
2711
  // host-level onProgress the parent execution carries.
@@ -2821,7 +3142,7 @@ export class BaseAgent {
2821
3142
  },
2822
3143
  });
2823
3144
  }
2824
- if (!await promptRun.Save()) {
3145
+ if (!await promptRun.Save({ SaveReturnMode: 'datestamps_only' })) {
2825
3146
  this.logError(`Failed to checkpoint realtime usage: ${promptRun.LatestResult?.CompleteMessage ?? 'unknown error'}`, {
2826
3147
  category: 'RealtimeSession'
2827
3148
  });
@@ -2906,6 +3227,13 @@ export class BaseAgent {
2906
3227
  this.logStatus(`🔄 Executing step ${stepCount + 1} for agent '${params.agent.Name}'`, true, params);
2907
3228
  const nextStep = await this.executeNextStep(params, config, currentNextStep, stepCount);
2908
3229
  stepCount++;
3230
+ // A failed step cut short by a cancellation is not a failure: end the run as cancelled
3231
+ // before the step is counted toward the consecutive-failure limit, which would end it as
3232
+ // Failed. A step that finished is kept: a final answer the user stopped too late to
3233
+ // prevent still completes the run.
3234
+ if (nextStep.step === 'Failed' && params.cancellationToken?.aborted) {
3235
+ throw new Error('Cancelled during execution');
3236
+ }
2909
3237
  // Promote any media outputs from this step to the agent's outputs
2910
3238
  if (nextStep.promoteMediaOutputs && nextStep.promoteMediaOutputs.length > 0) {
2911
3239
  this.PromoteMediaOutputs(nextStep.promoteMediaOutputs);
@@ -3075,14 +3403,15 @@ export class BaseAgent {
3075
3403
  * @param primaryScopeRecordId - Optional primary scope record ID for multi-tenant filtering
3076
3404
  * @param secondaryScopes - Optional secondary scope dimensions for multi-tenant filtering
3077
3405
  * @param secondaryScopeConfig - Optional agent-level scope config for per-dimension inheritance
3406
+ * @param sharedOnly - Inject only shared notes and examples (no `UserID`); set when the run's audience adds a reader
3078
3407
  * @returns Object containing injected notes and examples
3079
3408
  */
3080
- async InjectContextMemory(input, agent, userId, companyId, contextUser, conversationMessages, primaryScopeEntityId, primaryScopeRecordId, secondaryScopes, secondaryScopeConfig) {
3409
+ async InjectContextMemory(input, agent, userId, companyId, contextUser, conversationMessages, primaryScopeEntityId, primaryScopeRecordId, secondaryScopes, secondaryScopeConfig, sharedOnly) {
3081
3410
  // Delegate the orchestration to the shared, reusable builder so both BaseAgent and the
3082
3411
  // Realtime agent type inject memory identically. The observability context and verbose
3083
3412
  // status logging are derived from this instance and passed through.
3084
3413
  const observability = this.MemoryObservability(this._agentRun);
3085
- const result = await new AgentMemoryContextBuilder().InjectContextMemory(input, agent, userId, companyId, contextUser, conversationMessages, primaryScopeEntityId, primaryScopeRecordId, secondaryScopes, secondaryScopeConfig, observability, (message, verboseOnly) => this.logStatus(message, verboseOnly));
3414
+ const result = await new AgentMemoryContextBuilder().InjectContextMemory(input, agent, userId, companyId, contextUser, conversationMessages, primaryScopeEntityId, primaryScopeRecordId, secondaryScopes, secondaryScopeConfig, observability, (message, verboseOnly) => this.logStatus(message, verboseOnly), sharedOnly);
3086
3415
  // Store for inclusion in result (externally observable behavior preserved)
3087
3416
  this._injectedMemory = result;
3088
3417
  return result;
@@ -3094,7 +3423,9 @@ export class BaseAgent {
3094
3423
  * primary prompt under the run's polymorphic scope (the SAME PrimaryScope/SecondaryScopes the
3095
3424
  * runtime threads for memory), and unshifts the assembled role-tagged messages onto
3096
3425
  * `conversationMessages`. In-memory + synchronous (parts are cached on `AIEngine`). No-op when
3097
- * the agent has no active prompt or no parts resolve for the scope.
3426
+ * the agent has no active prompt or no parts resolve for the scope. System placeholders in the
3427
+ * messages it adds are replaced afterwards ({@link replaceScopedPartPlaceholders}), so an override
3428
+ * gets that too.
3098
3429
  */
3099
3430
  InjectScopedPromptParts(agent, conversationMessages, primaryScopeEntityId, primaryScopeRecordId, secondaryScopes) {
3100
3431
  try {
@@ -3113,6 +3444,28 @@ export class BaseAgent {
3113
3444
  this.logError(e instanceof Error ? e : new Error(String(e)), { category: 'ScopedPromptParts' });
3114
3445
  }
3115
3446
  }
3447
+ /**
3448
+ * Replace system placeholders such as `{{ _CURRENT_DATE }}` in the messages that
3449
+ * {@link InjectScopedPromptParts} added, meaning every message not in `before`. Part text is not a
3450
+ * template: see {@link SystemPlaceholderManager.ReplaceAvailablePlaceholders} for what resolves.
3451
+ * On failure the parts are kept as written.
3452
+ */
3453
+ async replaceScopedPartPlaceholders(messages, before, contextUser) {
3454
+ const added = messages.filter(m => !before.has(m));
3455
+ if (added.length === 0)
3456
+ return;
3457
+ try {
3458
+ const replaced = await SystemPlaceholderManager.ReplaceAvailablePlaceholders(added, { contextUser });
3459
+ let next = 0;
3460
+ for (let i = 0; i < messages.length; i++) {
3461
+ if (!before.has(messages[i]))
3462
+ messages[i] = replaced[next++];
3463
+ }
3464
+ }
3465
+ catch (e) {
3466
+ this.logError(e instanceof Error ? e : new Error(String(e)), { category: 'ScopedPromptParts' });
3467
+ }
3468
+ }
3116
3469
  /**
3117
3470
  * Inject pre-execution RAG context for this agent using scoped search.
3118
3471
  *
@@ -3136,12 +3489,15 @@ export class BaseAgent {
3136
3489
  * @param primaryScopeRecordId - Multi-tenant primary scope record ID.
3137
3490
  * @param secondaryScopes - Multi-tenant secondary scope dimensions.
3138
3491
  * @param payload - The agent's current payload (for template rendering).
3492
+ * @param activeSkillIDs - The skills active for this run; a lone active skill is the search's skill principal.
3493
+ * @param audienceReaders - The run's audience readers beyond the caller (`ExecuteAgentParams.Audience`,
3494
+ * hydrated): each must pass the scope gate, and only results every one of them may read are injected.
3139
3495
  * @returns The structured RAG result, or `null` if no scopes produced results.
3140
3496
  */
3141
- async InjectPreExecutionRAG(lastUserMessage, agent, contextUser, conversationMessages, originalMessages, primaryScopeEntityId, primaryScopeRecordId, secondaryScopes, payload) {
3497
+ async InjectPreExecutionRAG(lastUserMessage, agent, contextUser, conversationMessages, originalMessages, primaryScopeEntityId, primaryScopeRecordId, secondaryScopes, payload, activeSkillIDs, audienceReaders) {
3142
3498
  // Delegate to the shared builder so the Realtime agent type injects pre-execution RAG
3143
3499
  // identically. Verbose status + non-fatal error logging are threaded through from this instance.
3144
- const result = await new AgentMemoryContextBuilder().InjectPreExecutionRAG(lastUserMessage, agent, contextUser, conversationMessages, originalMessages, primaryScopeEntityId, primaryScopeRecordId, secondaryScopes, payload, (message, verboseOnly) => this.logStatus(message, verboseOnly), (error, options) => this.logError(error, options));
3500
+ const result = await new AgentMemoryContextBuilder().InjectPreExecutionRAG(lastUserMessage, agent, contextUser, conversationMessages, originalMessages, primaryScopeEntityId, primaryScopeRecordId, secondaryScopes, payload, (message, verboseOnly) => this.logStatus(message, verboseOnly), (error, options) => this.logError(error, options), activeSkillIDs, audienceReaders);
3145
3501
  // Store for inclusion in result (externally observable behavior preserved)
3146
3502
  this._injectedRAG = result;
3147
3503
  return result;
@@ -3481,14 +3837,16 @@ export class BaseAgent {
3481
3837
  *
3482
3838
  * @param {string} lastRunId - The ID of the last run to check
3483
3839
  * @param {UserInfo} [contextUser] - Optional user context
3840
+ * @param {{ LastRunID?: string | null } | null} [preloadedLastRun] - Optional preloaded row for `lastRunId` (or null when already queried and not found) to avoid a duplicate RunView call
3484
3841
  * @private
3485
3842
  */
3486
- async validateRunChain(lastRunId, contextUser) {
3843
+ async validateRunChain(lastRunId, contextUser, preloadedLastRun) {
3487
3844
  const visitedRunIds = new Set();
3488
3845
  visitedRunIds.add(this._agentRun.ID); // Add current run ID
3489
3846
  let currentRunId = lastRunId;
3490
3847
  const maxChainLength = 1000; // Reasonable limit to prevent infinite loops
3491
3848
  let chainLength = 0;
3849
+ let rv;
3492
3850
  while (currentRunId) {
3493
3851
  // Check if we've seen this run ID before
3494
3852
  if (visitedRunIds.has(currentRunId)) {
@@ -3499,8 +3857,16 @@ export class BaseAgent {
3499
3857
  throw new Error(`Run chain exceeds maximum length of ${maxChainLength}. This may indicate a data issue.`);
3500
3858
  }
3501
3859
  visitedRunIds.add(currentRunId);
3860
+ // Reuse the preloaded first-hop result when initializeAgentRun already queried lastRunId
3861
+ if (chainLength === 1 && preloadedLastRun !== undefined) {
3862
+ if (preloadedLastRun === null) {
3863
+ break;
3864
+ }
3865
+ currentRunId = preloadedLastRun.LastRunID;
3866
+ continue;
3867
+ }
3502
3868
  // Load the run to check its LastRunID
3503
- const rv = new RunView();
3869
+ rv ??= new RunView();
3504
3870
  const result = await rv.RunView({
3505
3871
  EntityName: 'MJ: AI Agent Runs',
3506
3872
  ExtraFilter: `ID='${currentRunId}'`,
@@ -4014,7 +4380,7 @@ export class BaseAgent {
4014
4380
  const systemPrompt = config.systemPrompt;
4015
4381
  const childPrompt = config.childPrompt;
4016
4382
  // Gather context data (including runtime action changes)
4017
- const promptTemplateData = await this.gatherPromptTemplateData(params.agent, params.contextUser, params.data, params.actionChanges, params.subAgentChanges);
4383
+ const promptTemplateData = await this.gatherPromptTemplateData(params.agent, params.contextUser, params.data, params.actionChanges, params.subAgentChanges, this.promptWithholding(params));
4018
4384
  // Set up the hierarchical prompt execution
4019
4385
  const promptParams = new AIPromptParams();
4020
4386
  // Attribute the resulting AIPromptRun to this agent. Agents share agent-type-level system
@@ -4090,6 +4456,7 @@ export class BaseAgent {
4090
4456
  // message at execution time (see injectArtifactToolResultsMessage) and decay
4091
4457
  // via pruneAndCompactExpiredMessages — same lifecycle as action results.
4092
4458
  const artifactToolsEnabled = agentTypePromptParams?.includeArtifactToolsDocs !== false;
4459
+ promptParams.data['_ARTIFACTS_ENABLED'] = this.isArtifactSupportEnabled(params.agent);
4093
4460
  if (artifactToolsEnabled && this._artifactToolManager.HasArtifacts()) {
4094
4461
  promptParams.data['_ARTIFACT_MANIFEST'] = this._artifactToolManager.ToManifestString();
4095
4462
  promptParams.data['_ARTIFACT_TOOLS'] = this._artifactToolManager.GetToolDocumentation();
@@ -4107,10 +4474,10 @@ export class BaseAgent {
4107
4474
  promptParams.data['_CONVERSATION_TOOLS'] = this._conversationToolManager.GetToolDocumentation();
4108
4475
  }
4109
4476
  // Enable the memory-writes response field + docs only for agents that opted in
4110
- // via AllowMemoryWrite. Disabled agents never see the docs, so a well-behaved
4111
- // LLM never emits the field (the turn loop still guards against drift).
4477
+ // via AllowMemoryWrite, and never under an audience (memoryWriteSkip). Disabled agents never
4478
+ // see the docs, so a well-behaved LLM never emits the field (the turn loop still guards against drift).
4112
4479
  const memoryWritesDocsEnabled = agentTypePromptParams?.includeMemoryWritesDocs !== false;
4113
- if (memoryWritesDocsEnabled && params.agent.AllowMemoryWrite === true) {
4480
+ if (memoryWritesDocsEnabled && this.memoryWriteSkip(params) === null) {
4114
4481
  promptParams.data['_MEMORY_WRITES_ENABLED'] = true;
4115
4482
  }
4116
4483
  // Inject pipeline tool docs when pipelines are enabled and at least one source exists.
@@ -4202,26 +4569,13 @@ export class BaseAgent {
4202
4569
  // Thread the per-request provider so prompt run records are saved through the isolated provider
4203
4570
  promptParams.provider = params.provider || this._activeProvider;
4204
4571
  // Overlay scope-resolved run settings (model / vendor / configuration / effort / sampling
4205
- // knobs) for this run's scope — the config sibling of scoped prompt parts. Uses the same
4206
- // run scope BaseAgent already carries; runtime-explicit values set above still win.
4572
+ // knobs) for this run's scope — the config sibling of scoped prompt parts. Uses the run's
4573
+ // validated scope (runScopeForContext); runtime-explicit values set above still win.
4207
4574
  const scopedConfigPromptId = promptParams.prompt?.ID;
4208
4575
  if (scopedConfigPromptId) {
4209
- const primaryScopeEntityName = params.PrimaryScopeEntityName ?? params.data?.PrimaryScopeEntityName;
4210
- let primaryScopeEntityId;
4211
- if (primaryScopeEntityName) {
4212
- const primaryEntity = this.ProviderToUse.EntityByName(primaryScopeEntityName);
4213
- if (primaryEntity) {
4214
- primaryScopeEntityId = primaryEntity.ID;
4215
- }
4216
- }
4217
4576
  const configResolver = MJGlobal.Instance.ClassFactory.CreateInstance(ScopedPromptConfigResolver) ??
4218
4577
  new ScopedPromptConfigResolver();
4219
- ApplyScopedPromptConfig(configResolver, scopedConfigPromptId, {
4220
- primaryScopeEntityId,
4221
- primaryScopeRecordId: params.PrimaryScopeRecordID ?? params.data?.PrimaryScopeRecordID,
4222
- secondaryScopes: params.SecondaryScopes ??
4223
- params.data?.SecondaryScopes,
4224
- }, promptParams);
4578
+ ApplyScopedPromptConfig(configResolver, scopedConfigPromptId, this.scopedPromptConfigScope(params), promptParams);
4225
4579
  }
4226
4580
  // Prompt-cache layout. The per-iteration state (and, when the child prompt is volatile, the
4227
4581
  // specialization) never lives in the system prompt; it rides as the FINAL message of THIS request.
@@ -4449,12 +4803,12 @@ export class BaseAgent {
4449
4803
  * fragment belongs on this request:
4450
4804
  *
4451
4805
  * - `'trailing'` — the template carries the `<mj-runtime-state>` pointer, so the model is told where
4452
- * the state lives. The Loop agent system prompt.
4806
+ * the state lives. The Loop and Flow agent system prompts.
4453
4807
  * - `'embedded'` — the template still renders the state blocks itself (an environment whose
4454
- * TemplateContent has not synced the new Loop template, or the Flow template, which embeds the
4808
+ * TemplateContent has not synced the new system template, or a custom template that embeds the
4455
4809
  * payload). Emitting the fragment would deliver the same state twice.
4456
4810
  * - `'unsupported'` — the template has neither. The Harness system prompt, or a custom prompt run
4457
- * without the Loop system prompt. The model would receive an unexplained block.
4811
+ * without a system prompt carrying the pointer. The model would receive an unexplained block.
4458
4812
  * - `'unknown'` — no template text to inspect (no TemplateID, or the lookup failed). The caller
4459
4813
  * fails OPEN here: a Loop agent losing its payload from the model's view is far worse than a
4460
4814
  * non-Loop agent receiving an unexplained fragment, and in practice every agent type's system
@@ -4465,10 +4819,17 @@ export class BaseAgent {
4465
4819
  if (templateText === null) {
4466
4820
  return 'unknown';
4467
4821
  }
4468
- if (this.templateTextEmbedsVolatileState(templateText)) {
4469
- return 'embedded';
4822
+ const markers = this.volatileTemplateMarkers;
4823
+ if (this._lastRuntimeStateDeliveryCache &&
4824
+ this._lastRuntimeStateDeliveryCache.templateText === templateText &&
4825
+ this._lastRuntimeStateDeliveryCache.markers === markers) {
4826
+ return this._lastRuntimeStateDeliveryCache.delivery;
4470
4827
  }
4471
- return templateText.includes(`<${RUNTIME_STATE_TAG}>`) ? 'trailing' : 'unsupported';
4828
+ const delivery = this.templateTextEmbedsVolatileState(templateText)
4829
+ ? 'embedded'
4830
+ : (templateText.includes(`<${RUNTIME_STATE_TAG}>`) ? 'trailing' : 'unsupported');
4831
+ this._lastRuntimeStateDeliveryCache = { templateText, markers, delivery };
4832
+ return delivery;
4472
4833
  }
4473
4834
  /**
4474
4835
  * The strings whose presence in a system prompt's unrendered template text means the template
@@ -4496,8 +4857,31 @@ export class BaseAgent {
4496
4857
  return null;
4497
4858
  }
4498
4859
  try {
4499
- await TemplateEngineServer.Instance.Config(false, contextUser);
4500
- const template = TemplateEngineServer.Instance.Templates?.find(t => UUIDsEqual(t.ID, prompt.TemplateID));
4860
+ if (!this._agentRun || !this._templateEngineConfiguredForRun) {
4861
+ await TemplateEngineServer.Instance.Config(false, contextUser);
4862
+ if (this._agentRun) {
4863
+ this._templateEngineConfiguredForRun = true;
4864
+ }
4865
+ }
4866
+ const templates = TemplateEngineServer.Instance.Templates;
4867
+ if (!templates) {
4868
+ return null;
4869
+ }
4870
+ let template;
4871
+ if (templates === this._cachedTemplatesArrayRef && this._templateByIdMap) {
4872
+ template = this._templateByIdMap.get(NormalizeUUID(prompt.TemplateID));
4873
+ }
4874
+ else {
4875
+ this._cachedTemplatesArrayRef = templates;
4876
+ const map = new Map();
4877
+ for (const t of templates) {
4878
+ if (t?.ID) {
4879
+ map.set(NormalizeUUID(t.ID), t);
4880
+ }
4881
+ }
4882
+ this._templateByIdMap = map;
4883
+ template = map.get(NormalizeUUID(prompt.TemplateID));
4884
+ }
4501
4885
  return template?.GetHighestPriorityContent()?.TemplateText ?? null;
4502
4886
  }
4503
4887
  catch (e) {
@@ -4575,9 +4959,20 @@ export class BaseAgent {
4575
4959
  * @returns
4576
4960
  */
4577
4961
  async determineNextStep(params, agentType, promptResult, currentPayload) {
4578
- // Let the agent type determine the next step
4962
+ // Let the agent type determine the next step. Pass the merged agent-type prompt params
4963
+ // (schema defaults -> agent.AgentTypePromptParams -> runtime override) without mutating
4964
+ // the caller's ExecuteAgentParams or params.data object.
4579
4965
  this.logStatus(`🎯 Agent type '${agentType.Name}' determining next step`, true, params);
4580
- const nextStep = await this.AgentTypeInstance.DetermineNextStep(promptResult, params, currentPayload, this.AgentTypeState, this._nativeToolBindings);
4966
+ const paramsForAgentType = this._agentTypePromptParams && params?.data?.__agentTypePromptParams === undefined
4967
+ ? {
4968
+ ...params,
4969
+ data: {
4970
+ ...(params.data ?? {}),
4971
+ __agentTypePromptParams: this._agentTypePromptParams,
4972
+ },
4973
+ }
4974
+ : params;
4975
+ const nextStep = await this.AgentTypeInstance.DetermineNextStep(promptResult, paramsForAgentType, currentPayload, this.AgentTypeState, this._nativeToolBindings);
4581
4976
  return nextStep;
4582
4977
  }
4583
4978
  /**
@@ -4640,11 +5035,12 @@ export class BaseAgent {
4640
5035
  // Client tools are valid - execution handled by executeClientToolsStep
4641
5036
  return nextStep;
4642
5037
  // Type assertion required because 'Tasks' is not part of the BaseAgentNextStep step
4643
- // union (submit-and-detach — the terminal step it produces is 'Success'). The graph was
4644
- // already validated against TaskGraphSpec by the agent type, so there is nothing left
4645
- // to check here; submission is handled by executeTasksStep.
5038
+ // union (submit-and-detach — the terminal step it produces is 'Success'). Pre-flight
5039
+ // validation checks that all referenced agents and actions exist and are runnable by
5040
+ // the context user so hallucinations or inaccessible targets convert to a self-correcting
5041
+ // Retry step instead of hard-failing the run in executeTasksStep.
4646
5042
  case 'Tasks':
4647
- return nextStep;
5043
+ return this.validateTasksNextStep(params, nextStep, currentPayload, agentRun, currentStep);
4648
5044
  default:
4649
5045
  // if we get here, the next step is not recognized, we can return a retry step
4650
5046
  this.logError(`Invalid next step '${nextStep.step}' for agent '${params.agent.Name}'`, {
@@ -4685,6 +5081,7 @@ export class BaseAgent {
4685
5081
  }
4686
5082
  async validateSubAgentNextStep(params, nextStep, currentPayload, agentRun, currentStep) {
4687
5083
  const curAgentSubAgents = this.getEffectiveSubAgentsForValidation(params.agent.ID);
5084
+ const allowFoldedTaskGraphTarget = nextStep.taskGraph?.folded === true;
4688
5085
  // Collect requested sub-agents. Prefer plural `subAgents` (parallel fan-out);
4689
5086
  // fall back to singular `subAgent` for the classic single-sub-agent next step.
4690
5087
  const requested = this.getRequestedSubAgents(nextStep);
@@ -4702,11 +5099,22 @@ export class BaseAgent {
4702
5099
  errorMessage: `Sub-agent 'undefined' not found or not active`
4703
5100
  };
4704
5101
  }
4705
- // Validate each requested sub-agent: existence + MaxExecutionsPerRun
5102
+ // Validate each requested sub-agent: existence + user run permission + MaxExecutionsPerRun
4706
5103
  for (const req of requested) {
4707
5104
  const name = req?.name;
4708
- const subAgent = curAgentSubAgents.find(a => a.Name.trim().toLowerCase() === name?.trim().toLowerCase());
4709
- if (!name || !subAgent) {
5105
+ const normalizedName = name?.trim().toLowerCase();
5106
+ const directSubAgent = curAgentSubAgents.find(a => a.Name.trim().toLowerCase() === normalizedName);
5107
+ const catalogSubAgent = !directSubAgent && allowFoldedTaskGraphTarget && normalizedName
5108
+ ? AIEngine.Instance.Agents.find(a => a.Status === 'Active' && a.Name.trim().toLowerCase() === normalizedName)
5109
+ : undefined;
5110
+ const subAgent = directSubAgent ?? catalogSubAgent;
5111
+ const hasRunPermission = subAgent && catalogSubAgent && params.contextUser
5112
+ ? await AIAgentPermissionHelper.HasPermission(subAgent.ID, params.contextUser, 'run')
5113
+ : true;
5114
+ if (!name || !subAgent || !hasRunPermission) {
5115
+ const availableHint = allowFoldedTaskGraphTarget
5116
+ ? this.buildAvailableRunnableAgentsHint(params.contextUser)
5117
+ : '';
4710
5118
  this.logError(`Sub-agent '${name}' not found or not active for agent '${params.agent.Name}'`, {
4711
5119
  agent: params.agent,
4712
5120
  category: 'SubAgentExecution'
@@ -4717,7 +5125,7 @@ export class BaseAgent {
4717
5125
  return {
4718
5126
  step: 'Retry',
4719
5127
  terminate: false,
4720
- errorMessage: `Sub-agent '${name}' not found or not active`
5128
+ errorMessage: `Sub-agent '${name}' not found or not active${availableHint}`
4721
5129
  };
4722
5130
  }
4723
5131
  if (subAgent.MaxExecutionsPerRun != null) {
@@ -4746,6 +5154,101 @@ export class BaseAgent {
4746
5154
  // All requested sub-agents are valid
4747
5155
  return nextStep;
4748
5156
  }
5157
+ /**
5158
+ * Builds a compact hint listing the current user's permitted runnable agents when a
5159
+ * task-graph or folded sub-agent step references an unknown or inaccessible agent name.
5160
+ */
5161
+ buildAvailableRunnableAgentsHint(contextUser) {
5162
+ const engine = AIEngine.Instance;
5163
+ if (typeof engine.GetUserRunnableAgentDirectory === 'function') {
5164
+ const runnable = engine.GetUserRunnableAgentDirectory(contextUser);
5165
+ if (runnable.length > 0) {
5166
+ const names = runnable.slice(0, 25).map(a => a.Name).join(', ');
5167
+ return `. Available runnable agents: ${names}`;
5168
+ }
5169
+ }
5170
+ return '';
5171
+ }
5172
+ /**
5173
+ * Validates a `'Tasks'` next step before `executeTasksStep` submits the graph.
5174
+ *
5175
+ * Verifies that every referenced `Agent` (including `ForEach`/`While` loop sub-agents) is
5176
+ * active and runnable by `params.contextUser`, and that every referenced `Action` is active.
5177
+ * When an agent or action name is unknown or inaccessible, converts the step to a self-correcting
5178
+ * `Retry` with the user's permitted runnable agent list instead of letting `TaskGraphService.Submit`
5179
+ * terminate the entire agent run as `Failed`. Never reveals whether an invalid agent name was
5180
+ * nonexistent versus restricted by permissions.
5181
+ */
5182
+ async validateTasksNextStep(params, nextStep, _currentPayload, _agentRun, _currentStep) {
5183
+ const spec = nextStep.taskGraph?.spec;
5184
+ if (!spec || !Array.isArray(spec.tasks) || spec.tasks.length === 0) {
5185
+ return nextStep;
5186
+ }
5187
+ const extractNodeAgentNames = (node) => {
5188
+ const loopOp = ConfigOf(node, 'ForEach') ?? ConfigOf(node, 'While');
5189
+ return [ConfigOf(node, 'Agent')?.agentName, loopOp?.subAgent?.name].filter((n) => typeof n === 'string' && n.trim().length > 0);
5190
+ };
5191
+ const extractNodeActionNames = (node) => {
5192
+ const loopOp = ConfigOf(node, 'ForEach') ?? ConfigOf(node, 'While');
5193
+ return [ConfigOf(node, 'Action')?.actionName, loopOp?.action?.name].filter((n) => typeof n === 'string' && n.trim().length > 0);
5194
+ };
5195
+ const referencedAgents = [...new Set(spec.tasks.flatMap(extractNodeAgentNames))];
5196
+ const referencedActions = [...new Set(spec.tasks.flatMap(extractNodeActionNames))];
5197
+ const invalidAgents = [];
5198
+ const allAgents = AIEngine.Instance?.Agents ?? [];
5199
+ if (referencedAgents.length > 0 && allAgents.length > 0) {
5200
+ for (const agentName of referencedAgents) {
5201
+ const normalized = agentName.trim().toLowerCase();
5202
+ const matched = allAgents.find(a => a.Status === 'Active' && a.Name?.trim().toLowerCase() === normalized);
5203
+ const permitted = matched
5204
+ ? params.contextUser
5205
+ ? await AIAgentPermissionHelper.HasPermission(matched.ID, params.contextUser, 'run')
5206
+ : true
5207
+ : false;
5208
+ if (!matched || !permitted) {
5209
+ invalidAgents.push(agentName);
5210
+ }
5211
+ }
5212
+ }
5213
+ const invalidActions = [];
5214
+ const allActions = ActionEngineServer.Instance?.Actions ?? [];
5215
+ if (referencedActions.length > 0 && allActions.length > 0) {
5216
+ for (const actionName of referencedActions) {
5217
+ const normalized = actionName.trim().toLowerCase();
5218
+ const matched = allActions.find(act => act.Status === 'Active' && act.Name?.trim().toLowerCase() === normalized);
5219
+ if (!matched) {
5220
+ invalidActions.push(actionName);
5221
+ }
5222
+ }
5223
+ }
5224
+ if (invalidAgents.length === 0 && invalidActions.length === 0) {
5225
+ return nextStep;
5226
+ }
5227
+ const errorParts = [];
5228
+ if (invalidAgents.length > 0) {
5229
+ const availableHint = this.buildAvailableRunnableAgentsHint(params.contextUser);
5230
+ errorParts.push(`Task graph "${spec.workflowName}" references unknown or inaccessible agent(s): ${invalidAgents.join(', ')}. ` +
5231
+ `Use only exact agent names from the Available Agents for Task Graph & Sub-Agent Delegation list ` +
5232
+ `(or discovered via "Find Candidate Agents")${availableHint}.`);
5233
+ }
5234
+ if (invalidActions.length > 0) {
5235
+ errorParts.push(`Task graph "${spec.workflowName}" references unknown or inactive action(s): ${invalidActions.join(', ')}. ` +
5236
+ `Use "Find Candidate Actions" first to discover exact action names.`);
5237
+ }
5238
+ const errorMessage = errorParts.join(' ');
5239
+ this.logError(errorMessage, {
5240
+ agent: params.agent,
5241
+ category: 'NextStepValidation'
5242
+ });
5243
+ if (nextStep.step !== 'Retry') {
5244
+ this._generalValidationRetryCount++;
5245
+ }
5246
+ return {
5247
+ step: 'Retry',
5248
+ terminate: false,
5249
+ errorMessage
5250
+ };
5251
+ }
4749
5252
  /**
4750
5253
  * Validates that the actions next step is valid and can be executed by the current agent. Subclasses can override
4751
5254
  * this method to implement custom validation logic if needed.
@@ -5056,11 +5559,14 @@ export class BaseAgent {
5056
5559
  }
5057
5560
  // Validation passed
5058
5561
  this.logStatus(`✅ Final payload validation passed for agent ${agent.Name}`, true, params);
5059
- // Save success result to step
5562
+ // Save success result to step via step save queue
5060
5563
  try {
5061
5564
  currentStep.FinalPayloadValidationResult = 'Pass';
5062
5565
  currentStep.FinalPayloadValidationMessages = null; // Clear any previous messages
5063
- await currentStep.Save();
5566
+ this.queueStepSave(currentStep, (s) => {
5567
+ s.FinalPayloadValidationResult = 'Pass';
5568
+ s.FinalPayloadValidationMessages = null;
5569
+ });
5064
5570
  }
5065
5571
  catch (error) {
5066
5572
  this.logError(`Failed to save validation success result: ${error.message}`, {
@@ -5095,9 +5601,17 @@ export class BaseAgent {
5095
5601
  */
5096
5602
  async handleFinalPayloadValidationFailure(params, nextStep, currentPayload, mode, errorMessages, agentRun, currentStep) {
5097
5603
  const validationFeedback = `Final payload validation failed:\n${errorMessages.map((e, i) => `${i + 1}. ${e}`).join('\n')}`;
5098
- // Always save validation results to the new fields
5604
+ // Always save validation results to the new fields via the step save queue
5099
5605
  try {
5100
- currentStep.FinalPayloadValidationMessages = errorMessages.join('; ');
5606
+ const joinedMessages = errorMessages.join('; ');
5607
+ currentStep.FinalPayloadValidationMessages = joinedMessages;
5608
+ const queueValidationUpdate = (resultValue) => {
5609
+ currentStep.FinalPayloadValidationResult = resultValue;
5610
+ this.queueStepSave(currentStep, (s) => {
5611
+ s.FinalPayloadValidationMessages = joinedMessages;
5612
+ s.FinalPayloadValidationResult = resultValue;
5613
+ });
5614
+ };
5101
5615
  switch (mode) {
5102
5616
  case 'Retry':
5103
5617
  // Increment retry counter
@@ -5107,8 +5621,7 @@ export class BaseAgent {
5107
5621
  if (this._validationRetryCount >= maxRetries) {
5108
5622
  // Max retries exceeded, force to Fail
5109
5623
  this.logStatus(`❌ Max validation retries (${maxRetries}) exceeded, forcing failure`, false, params);
5110
- currentStep.FinalPayloadValidationResult = 'Fail';
5111
- await currentStep.Save();
5624
+ queueValidationUpdate('Fail');
5112
5625
  return {
5113
5626
  ...nextStep,
5114
5627
  step: 'Failed',
@@ -5117,8 +5630,7 @@ export class BaseAgent {
5117
5630
  };
5118
5631
  }
5119
5632
  // Still have retries left
5120
- currentStep.FinalPayloadValidationResult = 'Retry';
5121
- await currentStep.Save();
5633
+ queueValidationUpdate('Retry');
5122
5634
  this.logStatus(`🔄 Validation retry ${this._validationRetryCount}/${maxRetries}`, true, params);
5123
5635
  return {
5124
5636
  ...nextStep,
@@ -5128,8 +5640,7 @@ export class BaseAgent {
5128
5640
  };
5129
5641
  case 'Fail':
5130
5642
  // Convert success to error
5131
- currentStep.FinalPayloadValidationResult = 'Fail';
5132
- await currentStep.Save();
5643
+ queueValidationUpdate('Fail');
5133
5644
  return {
5134
5645
  ...nextStep,
5135
5646
  step: 'Failed',
@@ -5139,14 +5650,12 @@ export class BaseAgent {
5139
5650
  case 'Warn':
5140
5651
  // Log warning but allow success
5141
5652
  this.logStatus(`⚠️ WARNING: ${validationFeedback}`, false, params);
5142
- currentStep.FinalPayloadValidationResult = 'Warn';
5143
- await currentStep.Save();
5653
+ queueValidationUpdate('Warn');
5144
5654
  return nextStep; // Return original success
5145
5655
  default:
5146
5656
  // Default to retry
5147
5657
  this._validationRetryCount++;
5148
- currentStep.FinalPayloadValidationResult = 'Retry';
5149
- await currentStep.Save();
5658
+ queueValidationUpdate('Retry');
5150
5659
  return {
5151
5660
  ...nextStep,
5152
5661
  step: 'Retry',
@@ -5314,7 +5823,7 @@ export class BaseAgent {
5314
5823
  }
5315
5824
  /** Runs the self-check when a success exit did not pass through the guardrail hook. */
5316
5825
  async selfCheckSuccess(params, step, payload) {
5317
- if (step.step !== 'Success' || !this._agentRun)
5826
+ if (step.step !== 'Success' || !this._agentRun || this._awaitingWorkflowTaskID)
5318
5827
  return step;
5319
5828
  const checked = await this.applySelfCheck(params, step, this._agentRun, payload);
5320
5829
  return checked ?? step;
@@ -5332,20 +5841,27 @@ export class BaseAgent {
5332
5841
  if (guardrailResult.exceeded) {
5333
5842
  // Log the guardrail violation
5334
5843
  this.logStatus(`⛔ Execution guardrail exceeded: ${guardrailResult.reason}`, false, params);
5335
- // Update the current step with guardrail information
5844
+ // Update the current step with guardrail information via the step save queue
5336
5845
  try {
5846
+ const guardrailExceeded = {
5847
+ type: guardrailResult.type,
5848
+ limit: guardrailResult.limit,
5849
+ current: guardrailResult.current,
5850
+ reason: guardrailResult.reason,
5851
+ timestamp: new Date().toISOString()
5852
+ };
5337
5853
  const outputData = currentStep.OutputData ? JSON.parse(currentStep.OutputData) : {};
5338
5854
  currentStep.OutputData = JSON.stringify({
5339
5855
  ...outputData,
5340
- guardrailExceeded: {
5341
- type: guardrailResult.type,
5342
- limit: guardrailResult.limit,
5343
- current: guardrailResult.current,
5344
- reason: guardrailResult.reason,
5345
- timestamp: new Date().toISOString()
5346
- }
5856
+ guardrailExceeded
5857
+ });
5858
+ this.queueStepSave(currentStep, (s) => {
5859
+ const existingOutput = s.OutputData ? JSON.parse(s.OutputData) : {};
5860
+ s.OutputData = JSON.stringify({
5861
+ ...existingOutput,
5862
+ guardrailExceeded
5863
+ });
5347
5864
  });
5348
- await currentStep.Save();
5349
5865
  }
5350
5866
  catch (error) {
5351
5867
  this.logError(`Failed to save guardrail violation to step: ${error.message}`, {
@@ -5469,9 +5985,222 @@ export class BaseAgent {
5469
5985
  reason: `Maximum validation retries of ${BaseAgent.MAX_VALIDATION_RETRIES} exceeded. The agent is unable to produce valid output after ${this._generalValidationRetryCount} validation failures.`
5470
5986
  };
5471
5987
  }
5988
+ // Synchronize shared tree budget floor with the current agentRun's metrics (handles both
5989
+ // multi-agent trees and direct guardrail invocations with pre-populated agentRun entities)
5990
+ // and evaluate cumulative root-tree ceilings (maxTreeSteps, maxTreeTokens, maxTreeCost, maxTreeDurationMs).
5991
+ const budget = this.ensureTreeBudget(params);
5992
+ if (agentRun) {
5993
+ const runStepsCount = Math.max(agentRun.Steps?.length ?? 0, agentRun.TotalPromptIterations ?? 0);
5994
+ if (runStepsCount > budget.totalSteps) {
5995
+ budget.totalSteps = runStepsCount;
5996
+ }
5997
+ if ((agentRun.TotalTokensUsed ?? 0) > budget.totalTokens) {
5998
+ budget.totalTokens = agentRun.TotalTokensUsed ?? 0;
5999
+ }
6000
+ if ((agentRun.TotalCost ?? 0) > budget.totalCost) {
6001
+ budget.totalCost = agentRun.TotalCost ?? 0;
6002
+ }
6003
+ }
6004
+ const treeBudgetCheck = this.checkTreeBudgetLimit(params);
6005
+ if (treeBudgetCheck.exceeded) {
6006
+ return treeBudgetCheck;
6007
+ }
5472
6008
  // No guardrails exceeded
5473
6009
  return { exceeded: false };
5474
6010
  }
6011
+ /**
6012
+ * Ensures that a shared {@link AgentTreeBudget} instance exists for the current execution tree
6013
+ * and is attached to both `this._treeBudget` and `params.treeBudget`.
6014
+ *
6015
+ * - When `params.treeBudget` is already provided (for example, propagated by a parent agent
6016
+ * in {@link ExecuteSubAgent} or supplied directly by a caller), that exact object reference
6017
+ * is reused so all root, sequential child, and parallel child runs mutate the same shared
6018
+ * counters (`totalSteps`, `totalTokens`, `totalCost`, `startedAtMs`, `breachedReason`).
6019
+ * - When `params.treeBudget` is absent (root run), a new {@link AgentTreeBudget} is created
6020
+ * and seeded with any top-level convenience ceilings (`maxTreeSteps`, `maxTreeTokens`,
6021
+ * `maxTreeCost`, `maxTreeDurationMs`) declared on `params`.
6022
+ *
6023
+ * @param params - Optional execution parameters for the current run.
6024
+ * @returns The shared {@link AgentTreeBudget} instance for the execution tree.
6025
+ * @protected
6026
+ */
6027
+ ensureTreeBudget(params) {
6028
+ const effectiveParams = params ?? this._executeParams;
6029
+ let budget = effectiveParams?.treeBudget ?? this._treeBudget;
6030
+ if (!budget) {
6031
+ budget = {
6032
+ maxTreeSteps: effectiveParams?.maxTreeSteps,
6033
+ maxTreeTokens: effectiveParams?.maxTreeTokens,
6034
+ maxTreeCost: effectiveParams?.maxTreeCost,
6035
+ maxTreeDurationMs: effectiveParams?.maxTreeDurationMs,
6036
+ totalSteps: 0,
6037
+ totalTokens: 0,
6038
+ totalCost: 0,
6039
+ startedAtMs: Date.now()
6040
+ };
6041
+ }
6042
+ else if (effectiveParams) {
6043
+ if (budget.maxTreeSteps === undefined && effectiveParams.maxTreeSteps !== undefined) {
6044
+ budget.maxTreeSteps = effectiveParams.maxTreeSteps;
6045
+ }
6046
+ if (budget.maxTreeTokens === undefined && effectiveParams.maxTreeTokens !== undefined) {
6047
+ budget.maxTreeTokens = effectiveParams.maxTreeTokens;
6048
+ }
6049
+ if (budget.maxTreeCost === undefined && effectiveParams.maxTreeCost !== undefined) {
6050
+ budget.maxTreeCost = effectiveParams.maxTreeCost;
6051
+ }
6052
+ if (budget.maxTreeDurationMs === undefined && effectiveParams.maxTreeDurationMs !== undefined) {
6053
+ budget.maxTreeDurationMs = effectiveParams.maxTreeDurationMs;
6054
+ }
6055
+ }
6056
+ this._treeBudget = budget;
6057
+ if (effectiveParams) {
6058
+ effectiveParams.treeBudget = budget;
6059
+ }
6060
+ if (this._executeParams && this._executeParams !== effectiveParams) {
6061
+ this._executeParams.treeBudget = budget;
6062
+ }
6063
+ return budget;
6064
+ }
6065
+ /**
6066
+ * Accumulates token and cost usage from a completed prompt execution into the shared
6067
+ * {@link AgentTreeBudget} for the execution tree.
6068
+ *
6069
+ * Prefers rollup figures on `promptRun` (`TokensUsedRollup` / `TokensPromptRollup` +
6070
+ * `TokensCompletionRollup` and `TotalCost`) so hierarchical child prompts are counted,
6071
+ * falling back to direct `promptRun` columns (`TokensUsed` / `TokensPrompt` + `TokensCompletion`
6072
+ * and `Cost`) or the `AIPromptRunResult` summary fields when `promptRun` is not populated.
6073
+ *
6074
+ * @param promptRun - The persisted or in-memory `MJAIPromptRunEntity` from the prompt execution, if any.
6075
+ * @param promptResult - Optional `AIPromptRunResult` carrying direct token/cost metrics.
6076
+ * @param params - Optional execution parameters for the current run.
6077
+ * @protected
6078
+ */
6079
+ recordPromptUsageInTreeBudget(promptRun, promptResult, params) {
6080
+ const budget = this.ensureTreeBudget(params);
6081
+ let tokensDelta = 0;
6082
+ if (promptRun) {
6083
+ if (promptRun.TokensUsedRollup != null && promptRun.TokensUsedRollup > 0) {
6084
+ tokensDelta = promptRun.TokensUsedRollup;
6085
+ }
6086
+ else if ((promptRun.TokensPromptRollup != null && promptRun.TokensPromptRollup > 0) ||
6087
+ (promptRun.TokensCompletionRollup != null && promptRun.TokensCompletionRollup > 0)) {
6088
+ tokensDelta = (promptRun.TokensPromptRollup ?? 0) + (promptRun.TokensCompletionRollup ?? 0);
6089
+ }
6090
+ else if (promptRun.TokensUsed != null && promptRun.TokensUsed > 0) {
6091
+ tokensDelta = promptRun.TokensUsed;
6092
+ }
6093
+ else if ((promptRun.TokensPrompt != null && promptRun.TokensPrompt > 0) ||
6094
+ (promptRun.TokensCompletion != null && promptRun.TokensCompletion > 0)) {
6095
+ tokensDelta = (promptRun.TokensPrompt ?? 0) + (promptRun.TokensCompletion ?? 0);
6096
+ }
6097
+ }
6098
+ if (tokensDelta === 0 && promptResult) {
6099
+ if (promptResult.combinedTokensUsed != null && promptResult.combinedTokensUsed > 0) {
6100
+ tokensDelta = promptResult.combinedTokensUsed;
6101
+ }
6102
+ else if ((promptResult.combinedPromptTokens != null && promptResult.combinedPromptTokens > 0) ||
6103
+ (promptResult.combinedCompletionTokens != null && promptResult.combinedCompletionTokens > 0)) {
6104
+ tokensDelta = (promptResult.combinedPromptTokens ?? 0) + (promptResult.combinedCompletionTokens ?? 0);
6105
+ }
6106
+ else if (promptResult.tokensUsed != null && promptResult.tokensUsed > 0) {
6107
+ tokensDelta = promptResult.tokensUsed;
6108
+ }
6109
+ else if ((promptResult.promptTokens != null && promptResult.promptTokens > 0) ||
6110
+ (promptResult.completionTokens != null && promptResult.completionTokens > 0)) {
6111
+ tokensDelta = (promptResult.promptTokens ?? 0) + (promptResult.completionTokens ?? 0);
6112
+ }
6113
+ }
6114
+ let costDelta = 0;
6115
+ if (promptRun) {
6116
+ if (promptRun.TotalCost != null && promptRun.TotalCost > 0) {
6117
+ costDelta = promptRun.TotalCost;
6118
+ }
6119
+ else if (promptRun.Cost != null && promptRun.Cost > 0) {
6120
+ costDelta = promptRun.Cost;
6121
+ }
6122
+ }
6123
+ if (costDelta === 0 && promptResult) {
6124
+ if (promptResult.combinedCost != null && promptResult.combinedCost > 0) {
6125
+ costDelta = promptResult.combinedCost;
6126
+ }
6127
+ else if (promptResult.cost != null && promptResult.cost > 0) {
6128
+ costDelta = promptResult.cost;
6129
+ }
6130
+ }
6131
+ budget.totalTokens += tokensDelta;
6132
+ budget.totalCost += costDelta;
6133
+ }
6134
+ /**
6135
+ * Evaluates whether any root-tree cumulative budget ceiling (`maxTreeSteps`, `maxTreeTokens`,
6136
+ * `maxTreeCost`, `maxTreeDurationMs`) on the shared {@link AgentTreeBudget} has been reached
6137
+ * or exceeded.
6138
+ *
6139
+ * When a ceiling is breached, sets `budget.breachedReason` with a descriptive diagnostic
6140
+ * message so both the breaching agent and any ancestor agents in the call tree can terminate
6141
+ * immediately with `step: 'Failed'` and `terminate: true`.
6142
+ *
6143
+ * @param params - Optional execution parameters for the current run.
6144
+ * @returns Guardrail evaluation result indicating whether a tree budget limit was exceeded.
6145
+ * @protected
6146
+ */
6147
+ checkTreeBudgetLimit(params) {
6148
+ const budget = this.ensureTreeBudget(params);
6149
+ if (budget.maxTreeSteps != null && budget.totalSteps >= budget.maxTreeSteps) {
6150
+ const reason = budget.breachedReason ?? `Agent tree step budget exceeded (${budget.totalSteps}/${budget.maxTreeSteps} total steps across tree)`;
6151
+ budget.breachedReason = reason;
6152
+ return {
6153
+ exceeded: true,
6154
+ type: 'iterations',
6155
+ limit: budget.maxTreeSteps,
6156
+ current: budget.totalSteps,
6157
+ reason
6158
+ };
6159
+ }
6160
+ if (budget.maxTreeTokens != null && budget.totalTokens >= budget.maxTreeTokens) {
6161
+ const reason = budget.breachedReason ?? `Agent tree token budget exceeded (${budget.totalTokens}/${budget.maxTreeTokens} total tokens across tree)`;
6162
+ budget.breachedReason = reason;
6163
+ return {
6164
+ exceeded: true,
6165
+ type: 'tokens',
6166
+ limit: budget.maxTreeTokens,
6167
+ current: budget.totalTokens,
6168
+ reason
6169
+ };
6170
+ }
6171
+ if (budget.maxTreeCost != null && budget.totalCost >= budget.maxTreeCost) {
6172
+ const reason = budget.breachedReason ?? `Agent tree cost budget exceeded ($${budget.totalCost.toFixed(4)}/$${budget.maxTreeCost.toFixed(4)} across tree)`;
6173
+ budget.breachedReason = reason;
6174
+ return {
6175
+ exceeded: true,
6176
+ type: 'cost',
6177
+ limit: budget.maxTreeCost,
6178
+ current: budget.totalCost,
6179
+ reason
6180
+ };
6181
+ }
6182
+ if (budget.maxTreeDurationMs != null) {
6183
+ const elapsedMs = Date.now() - budget.startedAtMs;
6184
+ if (elapsedMs >= budget.maxTreeDurationMs) {
6185
+ const reason = budget.breachedReason ?? `Agent tree duration budget exceeded (${elapsedMs}ms/${budget.maxTreeDurationMs}ms across tree)`;
6186
+ budget.breachedReason = reason;
6187
+ return {
6188
+ exceeded: true,
6189
+ type: 'time',
6190
+ limit: budget.maxTreeDurationMs,
6191
+ current: elapsedMs,
6192
+ reason
6193
+ };
6194
+ }
6195
+ }
6196
+ if (budget.breachedReason) {
6197
+ return {
6198
+ exceeded: true,
6199
+ reason: budget.breachedReason
6200
+ };
6201
+ }
6202
+ return { exceeded: false };
6203
+ }
5475
6204
  /**
5476
6205
  * Determines if a prompt execution error is fatal and should stop agent execution.
5477
6206
  * Fatal errors are those that won't be resolved by retrying, such as context length
@@ -6312,11 +7041,13 @@ The context is now within limits. Please retry your request with the recovered c
6312
7041
  *
6313
7042
  * Gated on conversationId + root depth — programmatic runs and sub-agents skip it.
6314
7043
  * Skipped under a history floor (`ConversationHistoryFrom`): the previous run's tool
6315
- * results can quote messages from before the floor.
7044
+ * results can quote messages from before the floor. Skipped under an audience
7045
+ * (`ExecuteAgentParams.Audience`) too: the previous run's results were fetched for
7046
+ * whoever ran it, not for this room.
6316
7047
  * @protected
6317
7048
  */
6318
7049
  async injectPriorTurnToolResults(params) {
6319
- if (!params.conversationId || this._depth !== 0 || params.ConversationHistoryFrom) {
7050
+ if (!params.conversationId || this._depth !== 0 || params.ConversationHistoryFrom || this.runAudienceAddsReader(params)) {
6320
7051
  return;
6321
7052
  }
6322
7053
  try {
@@ -6451,10 +7182,12 @@ The context is now within limits. Please retry your request with the recovered c
6451
7182
  /**
6452
7183
  * The stopped run's turns in the shape the loop builds, or null when they cannot be recovered.
6453
7184
  *
6454
- * The last prompt step recorded the run's whole message stack as it went into that prompt; the
6455
- * first prompt step recorded the stack the run started from (history plus this run's injections,
6456
- * which the new run adds for itself). The difference is the run's own turns. If the last prompt
6457
- * completed, its decision and the steps after it are rebuilt with the loop's own builders.
7185
+ * The latest prompt step that recorded a full stack holds the run's whole message stack as it went
7186
+ * into that prompt; the prompt steps after it recorded only the messages appended since (see
7187
+ * {@link capturePromptStepMessages}). The first prompt step recorded the stack the run started from
7188
+ * (history plus this run's injections, which the new run adds for itself). The difference is the
7189
+ * run's own turns. If the last prompt completed, its decision and the steps after it are rebuilt
7190
+ * with the loop's own builders.
6458
7191
  * @protected
6459
7192
  */
6460
7193
  buildResumedStoppedRunTurns(steps, params) {
@@ -6462,11 +7195,26 @@ The context is now within limits. Please retry your request with the recovered c
6462
7195
  if (prompts.length === 0) {
6463
7196
  return null;
6464
7197
  }
7198
+ const firstStack = BaseAgent.readPromptStepStack(prompts[0]);
7199
+ if (!firstStack?.length) {
7200
+ return null;
7201
+ }
6465
7202
  const lastPrompt = prompts[prompts.length - 1];
6466
- const loopTurns = BaseAgent.ExtractStoppedRunLoopTurns(BaseAgent.readPromptStepStack(prompts[0]), BaseAgent.readPromptStepStack(lastPrompt));
7203
+ let fullAt = prompts.length - 1;
7204
+ while (fullAt > 0 && BaseAgent.isPromptStepDelta(prompts[fullAt])) {
7205
+ fullAt--;
7206
+ }
7207
+ const loopTurns = BaseAgent.ExtractStoppedRunLoopTurns(firstStack, BaseAgent.readPromptStepStack(prompts[fullAt]));
6467
7208
  if (!loopTurns) {
6468
7209
  return null;
6469
7210
  }
7211
+ for (const prompt of prompts.slice(fullAt + 1)) {
7212
+ const delta = BaseAgent.readPromptStepStack(prompt);
7213
+ if (!delta) {
7214
+ return null;
7215
+ }
7216
+ loopTurns.push(...delta.filter(m => m.metadata?.volatileState !== true));
7217
+ }
6470
7218
  const decision = lastPrompt.Status === 'Completed' ? BaseAgent.readPromptStepDecision(lastPrompt) : null;
6471
7219
  const tail = this.buildStoppedRunTail(decision, steps.filter(s => s.StepNumber > lastPrompt.StepNumber), params);
6472
7220
  return [...loopTurns, ...tail].map(BaseAgent.restampResumedTurn);
@@ -6602,6 +7350,16 @@ The context is now within limits. Please retry your request with the recovered c
6602
7350
  return null;
6603
7351
  }
6604
7352
  }
7353
+ /** True when a prompt step recorded only the per-turn message delta instead of the full history stack. @private */
7354
+ static isPromptStepDelta(step) {
7355
+ try {
7356
+ const input = step.InputData ? JSON.parse(step.InputData) : {};
7357
+ return input.conversationMessagesDelta === true;
7358
+ }
7359
+ catch {
7360
+ return false;
7361
+ }
7362
+ }
6605
7363
  /** The decision a completed prompt step recorded, or null. @private */
6606
7364
  static readPromptStepDecision(step) {
6607
7365
  try {
@@ -7295,43 +8053,92 @@ The context is now within limits. Please retry your request with the recovered c
7295
8053
  }
7296
8054
  /**
7297
8055
  * Turn-loop entry point for in-flight memory writes, gated on the agent's
7298
- * AllowMemoryWrite flag. When disabled but the LLM emitted writes anyway
7299
- * (prompt drift / injection attempt), records ONE summary skip step —
7300
- * observable without per-write noise — and tells the agent the memories
7301
- * were NOT saved so it stops re-emitting. When enabled, executes the
8056
+ * AllowMemoryWrite flag and on the run's audience ({@link memoryWriteSkip}).
8057
+ * When refused but the LLM emitted writes anyway (prompt drift / injection
8058
+ * attempt), records ONE summary skip step and tells the agent the memories
8059
+ * were NOT saved ({@link skipMemoryWrites}). Otherwise executes the
7302
8060
  * writes as run steps and injects the results message.
7303
8061
  *
7304
8062
  * @protected
7305
8063
  */
7306
8064
  async processMemoryWritesForTurn(memoryWrites, params) {
7307
- if (params.agent.AllowMemoryWrite !== true) {
7308
- this.logStatus(`[MemoryWrites] LLM emitted ${memoryWrites.length} memory write(s) but AllowMemoryWrite=false — skipping`, true, params);
7309
- const skipStep = await this.createStepEntity({
7310
- stepType: 'Tool',
7311
- stepName: 'Memory Writes: skipped (AllowMemoryWrite=false)',
7312
- contextUser: params.contextUser,
7313
- inputData: { requestedWriteCount: memoryWrites.length },
7314
- });
7315
- await this.finalizeStepEntity(skipStep, true, undefined, { skipped: true, reason: 'AllowMemoryWrite=false' });
7316
- params.conversationMessages.push({
7317
- role: 'user',
7318
- content: 'Memory write result: this agent does not have durable memory writes enabled — the requested memories were NOT saved. Do not emit memoryWrites again.',
7319
- metadata: {
7320
- turnAdded: this._promptTurnCount,
7321
- messageType: 'tool-result',
7322
- expirationTurns: 3,
7323
- expirationMode: 'Compact',
7324
- compactMode: 'First N Chars',
7325
- compactLength: 200,
7326
- compactPromptId: '',
7327
- },
7328
- });
8065
+ const skip = this.memoryWriteSkip(params);
8066
+ if (skip) {
8067
+ await this.skipMemoryWrites(memoryWrites.length, skip, params);
7329
8068
  return;
7330
8069
  }
7331
8070
  this.logStatus(`[MemoryWrites] LLM requested ${memoryWrites.length} memory write(s)`, true, params);
7332
8071
  const writeResults = await this.executeMemoryWritesAsSteps(memoryWrites, params);
7333
8072
  this.injectMemoryWriteResultsMessage(params, writeResults);
7334
8073
  }
8074
+ /**
8075
+ * Determines whether artifact creation/lifecycle support (`artifactDirective`) is enabled for
8076
+ * the given agent so the Loop Agent system prompt includes `artifactDirective` and its lifecycle
8077
+ * instructions only when relevant.
8078
+ *
8079
+ * Returns `true` when:
8080
+ * - `agent.ArtifactCreationMode` is not `'Never'`, OR
8081
+ * - Conversation artifacts are already loaded in `_artifactToolManager`, OR
8082
+ * - The agent is an embedded sub-agent (`agent.ParentID`) whose parent agent creates artifacts
8083
+ * (`parentAgent.ArtifactCreationMode === 'Always'`) and relies on the sub-agent's payload/directive.
8084
+ */
8085
+ isArtifactSupportEnabled(agent) {
8086
+ if (!agent.ArtifactCreationMode || agent.ArtifactCreationMode !== 'Never') {
8087
+ return true;
8088
+ }
8089
+ if (this._artifactToolManager.HasArtifacts()) {
8090
+ return true;
8091
+ }
8092
+ if (agent.ParentID) {
8093
+ const parentAgent = AIEngine.Instance.Agents.find(a => UUIDsEqual(a.ID, agent.ParentID));
8094
+ if (parentAgent && parentAgent.ArtifactCreationMode === 'Always') {
8095
+ return true;
8096
+ }
8097
+ }
8098
+ return false;
8099
+ }
8100
+ /**
8101
+ * Why this run saves no memory writes, or null when it may: the agent has not opted in (`AllowMemoryWrite`), or the
8102
+ * run's audience adds a reader. A write is the caller's note, and its reply — saved, superseded, "already exists
8103
+ * verbatim" — is read against the caller's own notes, so in a shared conversation it would tell the room what the
8104
+ * caller has noted. The memory-writes docs are left out of the prompt for the same reasons.
8105
+ */
8106
+ memoryWriteSkip(params) {
8107
+ if (params.agent.AllowMemoryWrite !== true) {
8108
+ return { Reason: 'AllowMemoryWrite=false', Told: 'this agent does not have durable memory writes enabled' };
8109
+ }
8110
+ if (this.runAudienceAddsReader(params)) {
8111
+ return { Reason: 'shared conversation', Told: 'memory writes are not available in a shared conversation' };
8112
+ }
8113
+ return null;
8114
+ }
8115
+ /**
8116
+ * Records ONE summary skip step for a turn's refused memory writes — observable without per-write noise — and tells
8117
+ * the agent the memories were NOT saved, so it stops re-emitting them.
8118
+ */
8119
+ async skipMemoryWrites(requestedWriteCount, skip, params) {
8120
+ this.logStatus(`[MemoryWrites] LLM emitted ${requestedWriteCount} memory write(s) but ${skip.Reason} — skipping`, true, params);
8121
+ const skipStep = await this.createStepEntity({
8122
+ stepType: 'Tool',
8123
+ stepName: `Memory Writes: skipped (${skip.Reason})`,
8124
+ contextUser: params.contextUser,
8125
+ inputData: { requestedWriteCount },
8126
+ });
8127
+ await this.finalizeStepEntity(skipStep, true, undefined, { skipped: true, reason: skip.Reason });
8128
+ params.conversationMessages.push({
8129
+ role: 'user',
8130
+ content: `Memory write result: ${skip.Told} — the requested memories were NOT saved. Do not emit memoryWrites again.`,
8131
+ metadata: {
8132
+ turnAdded: this._promptTurnCount,
8133
+ messageType: 'tool-result',
8134
+ expirationTurns: 3,
8135
+ expirationMode: 'Compact',
8136
+ compactMode: 'First N Chars',
8137
+ compactLength: 200,
8138
+ compactPromptId: '',
8139
+ },
8140
+ });
8141
+ }
7335
8142
  /**
7336
8143
  * Pushes a single user-role message containing memory-write outcomes into
7337
8144
  * the conversation, mirroring `injectArtifactToolResultsMessage`'s
@@ -7772,6 +8579,9 @@ The context is now within limits. Please retry your request with the recovered c
7772
8579
  step.TargetLogID = result.promptRun.ID;
7773
8580
  step.PromptRun = result.promptRun; // transient related object (not a persisted field)
7774
8581
  }
8582
+ if (result.promptRun) {
8583
+ this.recordPromptUsageInTreeBudget(result.promptRun, undefined, this._executeParams);
8584
+ }
7775
8585
  }
7776
8586
  /**
7777
8587
  * Links the prompt run of a decision call the run stopped waiting for (a timeout or a cancellation)
@@ -7985,6 +8795,7 @@ The context is now within limits. Please retry your request with the recovered c
7985
8795
  * @param {UserInfo} [_contextUser] - Optional user context (reserved for future use)
7986
8796
  * @param {any} [extraData] - Optional extra data to include in the context, if provided and keys conflict within the agent context data, the extraData will override the agent context data.
7987
8797
  * @param {ActionChange[]} [actionChanges] - Optional runtime action modifications
8798
+ * @param {PromptWithholding} [withholding] - What this run's prompt leaves out (see `promptWithholding`)
7988
8799
  *
7989
8800
  * @returns {Promise<AgentContextData>} Structured context data for prompts
7990
8801
  *
@@ -7992,7 +8803,7 @@ The context is now within limits. Please retry your request with the recovered c
7992
8803
  *
7993
8804
  * @private
7994
8805
  */
7995
- async gatherPromptTemplateData(agent, _contextUser, extraData, actionChanges, subAgentChanges) {
8806
+ async gatherPromptTemplateData(agent, _contextUser, extraData, actionChanges, subAgentChanges, withholding) {
7996
8807
  try {
7997
8808
  const engine = AIEngine.Instance;
7998
8809
  // Build (or reuse) the agent-invariant base catalog. This is process-wide cached on
@@ -8057,6 +8868,11 @@ The context is now within limits. Please retry your request with the recovered c
8057
8868
  // and removes any cache-poisoning foot-gun should a future consumer write to it.
8058
8869
  agentTypePromptParams = { ...catalog.baseAgentTypePromptParams };
8059
8870
  }
8871
+ // A run that withholds task graphs (an audience or a tenant: see taskGraphWithholdingReason) is not offered
8872
+ // them; a copy, so the cached base is never written. executeTasksStep refuses a graph the model writes anyway.
8873
+ if (withholding?.TaskGraphs) {
8874
+ agentTypePromptParams = this.withoutTaskGraphs(agentTypePromptParams);
8875
+ }
8060
8876
  // Store for the finishIf gate, which runs after this prompt in executeActionsStep / executeNextStep
8061
8877
  this._agentTypePromptParams = agentTypePromptParams;
8062
8878
  // Skill catalog (name + description only — progressive disclosure). This is the
@@ -8078,16 +8894,29 @@ The context is now within limits. Please retry your request with the recovered c
8078
8894
  actionDetails = this.narrowedCatalogSection('action', activeActions, actionDetails, shown => this.formatActionDetails(shown));
8079
8895
  subAgentDetails = this.narrowedCatalogSection('agent', uniqueActiveSubAgents, subAgentDetails, shown => this.formatSubAgentDetails(shown));
8080
8896
  const skillsCatalog = this.narrowedCatalogSection('skill', availableSkills, this.formatSkillsCatalog(availableSkills), shown => this.formatSkillsCatalog(shown));
8081
- // Build client tool details for the prompt (per-run; depends on extraData)
8082
- const clientToolDetails = this.buildClientToolPromptSection(agent, extraData);
8083
- // Build app context section if provided in extraData
8084
- const appContext = this.buildAppContextSection(extraData);
8897
+ // The client tools and the app context (per-run, from extraData) — neither under an audience (callerContextSections).
8898
+ const { clientToolDetails, appContext } = this.callerContextSections(agent, extraData, withholding?.CallerContext === true);
8899
+ const cachedUserPolicy = _contextUser?.ID
8900
+ ? AgentUserPolicyEngine.Instance.GetCachedPolicy(agent.ID, _contextUser.ID)
8901
+ : null;
8902
+ const runnableAgentDirectory = typeof engine.GetUserRunnableAgentDirectory === 'function'
8903
+ ? engine.GetUserRunnableAgentDirectory(_contextUser)
8904
+ : [];
8905
+ const maxPreloadedAgents = 25;
8906
+ const visibleRunnableAgents = runnableAgentDirectory.slice(0, maxPreloadedAgents);
8907
+ const availableAgentLines = visibleRunnableAgents.map(a => a.Description ? `- **${a.Name}**: ${a.Description}` : `- **${a.Name}**`);
8908
+ if (runnableAgentDirectory.length > maxPreloadedAgents) {
8909
+ availableAgentLines.push(`*(Showing ${maxPreloadedAgents} of ${runnableAgentDirectory.length} runnable agents — use "Find Candidate Agents" to search the full catalog)*`);
8910
+ }
8911
+ const availableAgentDetails = availableAgentLines.join('\n');
8085
8912
  const contextData = {
8086
- agentName: agent.Name,
8913
+ agentName: cachedUserPolicy?.DisplayNameOverride?.trim() || agent.Name,
8087
8914
  agentDescription: agent.Description,
8088
8915
  parentAgentName: agent.Parent ? agent.Parent.trim() : "",
8089
8916
  subAgentCount: subAgentCount,
8090
8917
  subAgentDetails: subAgentDetails,
8918
+ availableAgentCount: runnableAgentDirectory.length,
8919
+ availableAgentDetails: availableAgentDetails,
8091
8920
  actionCount: activeActions.length,
8092
8921
  actionDetails: actionDetails,
8093
8922
  clientToolDetails: clientToolDetails,
@@ -8102,7 +8931,12 @@ The context is now within limits. Please retry your request with the recovered c
8102
8931
  // is built separately with proper merge precedence (schema < agent < runtime)
8103
8932
  const result = {
8104
8933
  ...contextData,
8105
- __agentTypePromptParams: agentTypePromptParams
8934
+ __agentTypePromptParams: agentTypePromptParams,
8935
+ ...(cachedUserPolicy
8936
+ ? {
8937
+ userPolicyContext: AgentUserPolicyEngine.Instance.BuildPromptPolicyContextBlock(cachedUserPolicy, _contextUser),
8938
+ }
8939
+ : {}),
8106
8940
  };
8107
8941
  if (extraData) {
8108
8942
  // Spread extraData but don't let it override __agentTypePromptParams
@@ -9033,6 +9867,111 @@ The context is now within limits. Please retry your request with the recovered c
9033
9867
  return key || undefined;
9034
9868
  };
9035
9869
  }
9870
+ /** The model's arguments as the engine's input parameters. */
9871
+ toEngineActionParams(action, actionEntity) {
9872
+ // Coerced against each param's declared schema on every path — envelope, native and flow —
9873
+ // so `"640"` reaches an integer param as 640 whichever protocol produced it. Harness
9874
+ // stand-ins may build an Action literal without the related-record collection.
9875
+ const coerced = CoerceActionArguments(actionEntity.Params?.Items ?? [], action.params);
9876
+ return Object.entries(coerced).map(([key, value]) => ({
9877
+ Name: key,
9878
+ Value: value,
9879
+ Type: 'Input'
9880
+ }));
9881
+ }
9882
+ /**
9883
+ * The action context for one dispatch: the agent's own context object, by reference (do NOT spread —
9884
+ * spreading destroys class instances, losing getters/methods on typed contexts like SkipAgentContext),
9885
+ * stamped with the calling agent's identity, the run's active skills and its resolved storage account.
9886
+ */
9887
+ stampActionContext(params) {
9888
+ const actionContext = (typeof params.context === 'object' && params.context ? params.context : {});
9889
+ actionContext.AgentID = params.agent.ID;
9890
+ // The skills active in THIS run, as a fact the action can trust. An action that takes a
9891
+ // skill principal (Scoped Search's AISkillID) must not have to believe a parameter the model
9892
+ // authored: with this it can default the principal to the run's active skill and refuse a
9893
+ // named skill the run never activated. Always stamped — an empty array means "inside an
9894
+ // agent run, with no skill active", which is a different fact from "no agent at all".
9895
+ actionContext.ActiveSkillIDs = this.activeSkillIDsForRun(params);
9896
+ if (this._resolvedStorageAccountId) {
9897
+ actionContext.__resolvedStorageAccountId = this._resolvedStorageAccountId;
9898
+ }
9899
+ return actionContext;
9900
+ }
9901
+ /**
9902
+ * The run's bounds handed to ONE action dispatch, beside its parameters. Per dispatch on purpose: the action
9903
+ * context IS params.context, shared by every action in the run (parallel ones included) and copied into
9904
+ * sub-agent runs, so anything stamped there would name the wrong action under parallel dispatch and travel
9905
+ * further than the action it was meant for. The model sets none of these.
9906
+ */
9907
+ runBoundDispatchParams(params, actionEntity, audienceReaders, runAs) {
9908
+ const readers = this.dispatchReaders(params, audienceReaders, runAs);
9909
+ return {
9910
+ // The run's RUNTIME API KEYS, as a RESOLVER bound to this one action — see buildRuntimeAPIKeyResolver().
9911
+ // Absent when the run has no keys, so the action uses GetAIAPIKey(driverClass) exactly as before —
9912
+ // unless the scope below is RuntimeOnly, which tells the action the resolver's answer (or its absence) is final.
9913
+ RuntimeAPIKeyResolver: params.apiKeys && params.apiKeys.length > 0 ? this.buildRuntimeAPIKeyResolver(params, actionEntity) : undefined,
9914
+ // AICredentialScope → actions-base's RuntimeCredentialScope mirror: a value added to the
9915
+ // former and not the latter fails to compile here, so the two cannot drift apart.
9916
+ CredentialScope: params.CredentialScope,
9917
+ // The run's audience (ExecuteAgentParams.Audience), when it adds a reader. The engine refuses an action
9918
+ // that cannot honour it (AUDIENCE_UNSUPPORTED — see recordDispatchOutcome); one that can returns only
9919
+ // what every reader may see.
9920
+ Audience: readers.length > 0 ? { Readers: readers } : undefined,
9921
+ // The run's scope (tenant + secondary dimensions), always present inside a run — nulls when it is
9922
+ // unscoped — so an action that scopes by tenant defaults to the run's and refuses one the model names.
9923
+ RunScope: this.runScopeFor(params),
9924
+ };
9925
+ }
9926
+ /**
9927
+ * The audience readers for one dispatch: everyone who will see the result besides the user the action RUNS AS
9928
+ * ({@link ExecuteSingleAction}'s `contextUser`), which need not be the run's caller. The run's readers leave the
9929
+ * caller out; when the action runs as someone else, the caller sees its result too and is added, and the user it
9930
+ * runs as is left out (as the engine does). A run whose audience adds no reader stays without one.
9931
+ */
9932
+ dispatchReaders(params, readers, runAs) {
9933
+ const caller = params.contextUser;
9934
+ if (readers.length === 0 || !caller || UUIDsEqual(runAs?.ID, caller.ID)) {
9935
+ return readers;
9936
+ }
9937
+ return [...readers.filter((reader) => !UUIDsEqual(reader.ID, runAs?.ID)), caller];
9938
+ }
9939
+ /**
9940
+ * The scope an action dispatch is handed: the run's, as {@link initializeAgentRun} validated and recorded it,
9941
+ * or — when {@link ExecuteSingleAction} is called outside {@link Execute} (the realtime tool path, tests,
9942
+ * harnesses) — resolved from these params the same way ({@link validatedRunScope}). A copy each time, so an
9943
+ * action cannot change what the next one sees.
9944
+ */
9945
+ runScopeFor(params) {
9946
+ const scope = this._runScope ?? this.validatedRunScope(params);
9947
+ const secondary = scope.SecondaryScopes
9948
+ ? Object.fromEntries(Object.entries(scope.SecondaryScopes).map(([key, value]) => [key, Array.isArray(value) ? [...value] : value]))
9949
+ : null;
9950
+ return { ...scope, SecondaryScopes: secondary };
9951
+ }
9952
+ /**
9953
+ * Logs one dispatched call's outcome and feeds the run-scoped circuit breaker, unless the caller does its own
9954
+ * failure accounting (`skipCircuitBreaker`). An `AUDIENCE_UNSUPPORTED` refusal locks the action out for the
9955
+ * run: no argument changes it, and the model is told the action is unavailable rather than to retry.
9956
+ */
9957
+ recordDispatchOutcome(params, action, actionEntity, result, normalizedParams, skipBreaker) {
9958
+ if (result.Success) {
9959
+ this.logStatus(` ✅ Action '${action.name}' completed successfully`, true, params);
9960
+ if (!skipBreaker) {
9961
+ this.clearActionFailureRecord(action, actionEntity);
9962
+ }
9963
+ return;
9964
+ }
9965
+ this.logStatus(` ❌ Action '${action.name}' failed: ${result.Message || 'Unknown error'}`, false, params);
9966
+ if (skipBreaker) {
9967
+ return;
9968
+ }
9969
+ if (result.ResultCode === AUDIENCE_UNSUPPORTED_RESULT_CODE) {
9970
+ this.lockOutAction(action, actionEntity, 'audience');
9971
+ return;
9972
+ }
9973
+ this.recordActionFailure(action, actionEntity, result.Message, normalizedParams);
9974
+ }
9036
9975
  /**
9037
9976
  * This method executes one action using the MemberJunction Actions framework.
9038
9977
  * The full ActionResult objects are returned, allowing the caller to access result codes, output parameters,
@@ -9059,62 +9998,29 @@ The context is now within limits. Please retry your request with the recovered c
9059
9998
  return blocked;
9060
9999
  }
9061
10000
  }
10001
+ // Enforce per-(Agent, User) action policy narrowing rules when a user policy is active
10002
+ const policyBlocked = this.checkUserActionPolicy(params, action, actionEntity, contextUser ?? params.contextUser);
10003
+ if (policyBlocked) {
10004
+ return policyBlocked;
10005
+ }
10006
+ // The run's audience, hydrated once per run — lazily here, since this method is also called outside
10007
+ // Execute (the pipeline executor, tests). An unusable audience refuses the call: nothing is dispatched.
10008
+ const audience = await this.audienceReadersFor(params);
10009
+ if ('Error' in audience) {
10010
+ throw new Error(audience.Error);
10011
+ }
9062
10012
  try {
9063
- const actionEngine = ActionEngineServer.Instance;
9064
- // Convert params object to ActionParam array
9065
- const actionParams = Object.entries(action.params || {}).map(([key, value]) => ({
9066
- Name: key,
9067
- Value: value,
9068
- Type: 'Input'
9069
- }));
9070
- // Build action context: preserve the agent's context by reference
9071
- // (do NOT spread — spreading destroys class instances, losing
9072
- // getters/methods on typed contexts like SkipAgentContext).
9073
- // Stamp the calling agent's identity and resolved storage account ID
9074
- // directly onto the original context object.
9075
- const actionContext = typeof params.context === 'object' && params.context ? params.context : {};
9076
- actionContext.AgentID = params.agent.ID;
9077
- // The skills active in THIS run, as a fact the action can trust. An action that takes a
9078
- // skill principal (Scoped Search's AISkillID) must not have to believe a parameter the model
9079
- // authored: with this it can default the principal to the run's active skill and refuse a
9080
- // named skill the run never activated. Always stamped — an empty array means "inside an
9081
- // agent run, with no skill active", which is a different fact from "no agent at all".
9082
- actionContext.ActiveSkillIDs = this.activeSkillIDsForRun(params);
9083
- if (this._resolvedStorageAccountId) {
9084
- actionContext.__resolvedStorageAccountId = this._resolvedStorageAccountId;
9085
- }
9086
10013
  // Execute the action and return the full ActionResult
9087
- const result = await actionEngine.RunAction({
10014
+ const result = await ActionEngineServer.Instance.RunAction({
9088
10015
  Action: actionEntity,
9089
- Params: actionParams,
10016
+ Params: this.toEngineActionParams(action, actionEntity),
9090
10017
  ContextUser: contextUser,
9091
10018
  Filters: [],
9092
10019
  SkipActionLog: false,
9093
- Context: actionContext,
9094
- // The run's RUNTIME API KEYS, as a RESOLVER bound to this one action — see
9095
- // buildRuntimeAPIKeyResolver(). Per dispatch on purpose: actionContext IS params.context,
9096
- // shared by every action in the run (parallel ones included) and copied into sub-agent
9097
- // runs, so anything stamped there would name the wrong action under parallel dispatch
9098
- // and travel further than the action it was meant for. Absent when the run has no keys,
9099
- // so the action uses GetAIAPIKey(driverClass) exactly as before — unless the scope below
9100
- // is RuntimeOnly, which tells the action the resolver's answer (or its absence) is final.
9101
- RuntimeAPIKeyResolver: params.apiKeys && params.apiKeys.length > 0 ? this.buildRuntimeAPIKeyResolver(params, actionEntity) : undefined,
9102
- // AICredentialScope → actions-base's RuntimeCredentialScope mirror: a value added to the
9103
- // former and not the latter fails to compile here, so the two cannot drift apart.
9104
- CredentialScope: params.CredentialScope,
10020
+ Context: this.stampActionContext(params),
10021
+ ...this.runBoundDispatchParams(params, actionEntity, audience.Readers, contextUser),
9105
10022
  });
9106
- if (result.Success) {
9107
- this.logStatus(` ✅ Action '${action.name}' completed successfully`, true, params);
9108
- if (!skipBreaker) {
9109
- this.clearActionFailureRecord(action, actionEntity);
9110
- }
9111
- }
9112
- else {
9113
- this.logStatus(` ❌ Action '${action.name}' failed: ${result.Message || 'Unknown error'}`, false, params);
9114
- if (!skipBreaker) {
9115
- this.recordActionFailure(action, actionEntity, result.Message, normalizedParams);
9116
- }
9117
- }
10023
+ this.recordDispatchOutcome(params, action, actionEntity, result, normalizedParams, skipBreaker);
9118
10024
  return result;
9119
10025
  }
9120
10026
  catch (error) {
@@ -9132,6 +10038,57 @@ The context is now within limits. Please retry your request with the recovered c
9132
10038
  throw new Error(`Error executing actions: ${error.message}`);
9133
10039
  }
9134
10040
  }
10041
+ /**
10042
+ * Checks per-(Agent, User) action policy narrowing rules (`MJ: AI Agent User Policies`)
10043
+ * before dispatching an action. Returns a synthetic ActionResult when the action is denied,
10044
+ * deferred outside a configured time window, or requires explicit user approval.
10045
+ */
10046
+ checkUserActionPolicy(params, action, actionEntity, contextUser) {
10047
+ if (!contextUser?.ID || !params?.agent?.ID) {
10048
+ return null;
10049
+ }
10050
+ const policy = AgentUserPolicyEngine.Instance.GetCachedPolicy(params.agent.ID, contextUser.ID);
10051
+ if (!policy) {
10052
+ return null;
10053
+ }
10054
+ const actionParamsRecord = {};
10055
+ if (action.params) {
10056
+ for (const [key, val] of Object.entries(action.params)) {
10057
+ if (val == null || typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean') {
10058
+ actionParamsRecord[key] = val;
10059
+ }
10060
+ else {
10061
+ actionParamsRecord[key] = JSON.stringify(val);
10062
+ }
10063
+ }
10064
+ }
10065
+ const evaluation = AgentUserPolicyEngine.Instance.EvaluateActionExecution({
10066
+ actionName: actionEntity.Name || action.name,
10067
+ params: actionParamsRecord,
10068
+ contextUser,
10069
+ policy,
10070
+ });
10071
+ if (evaluation.verdict === 'Allow') {
10072
+ return null;
10073
+ }
10074
+ const resultCode = evaluation.verdict === 'Deny'
10075
+ ? 'POLICY_DENIED'
10076
+ : evaluation.verdict === 'DeferUntilNextWindow'
10077
+ ? 'POLICY_DEFERRED_OUTSIDE_TIME_WINDOW'
10078
+ : 'POLICY_APPROVAL_REQUIRED';
10079
+ return {
10080
+ Success: false,
10081
+ ResultCode: resultCode,
10082
+ Message: evaluation.reason,
10083
+ Params: [],
10084
+ RunParams: {
10085
+ Action: actionEntity,
10086
+ Params: this.toEngineActionParams(action, actionEntity),
10087
+ ContextUser: contextUser,
10088
+ Filters: [],
10089
+ },
10090
+ };
10091
+ }
9135
10092
  /**
9136
10093
  * Makes a SLICED conversation window safe to send on its own.
9137
10094
  *
@@ -9322,8 +10279,9 @@ The context is now within limits. Please retry your request with the recovered c
9322
10279
  // This would need to be passed through the AgentRunner in a real implementation
9323
10280
  // For now, we execute normally and the sub-agent will track its parent relationship
9324
10281
  this.logStatus(`📨 Sub-agent message: "${subAgentRequest.message}"`, true, params);
9325
- if (subAgentRequest.templateParameters) {
9326
- this.logStatus(`📎 Template parameters: ${JSON.stringify(subAgentRequest.templateParameters)}`, true, params);
10282
+ const templateParameters = this.subAgentTemplateParameters(params, subAgentRequest);
10283
+ if (templateParameters) {
10284
+ this.logStatus(`📎 Template parameters: ${JSON.stringify(templateParameters)}`, true, params);
9327
10285
  }
9328
10286
  if (params.effortLevel !== undefined && params.effortLevel !== null) {
9329
10287
  this.logStatus(`🎯 Propagating effort level ${params.effortLevel} to sub-agent '${subAgentRequest.name}'`, true, params);
@@ -9353,19 +10311,23 @@ The context is now within limits. Please retry your request with the recovered c
9353
10311
  effortLevel: params.effortLevel, // propagate effort level to sub-agent
9354
10312
  apiKeys: params.apiKeys, // propagate API keys to sub-agent
9355
10313
  CredentialScope: params.CredentialScope, // a sub-agent may not spend keys its parent could not
10314
+ Audience: params.Audience, // a sub-agent's output reaches the same room; it re-hydrates the IDs itself
9356
10315
  inputArtifacts: params.inputArtifacts, // propagate input artifacts so sub-agents inherit the parent's artifact manifest + tools (e.g. a Codesmith delegate can read a Data Snapshot the parent references)
9357
10316
  data: {
9358
10317
  ...params.data,
9359
- ...subAgentRequest.templateParameters,
9360
- }, // merge parent data first, then override with template parameters so loop agents can dynamically override parent data
10318
+ ...templateParameters,
10319
+ }, // parent data first, then the template parameters (never a host-only key) so loop agents can override parent data
10320
+ TrustReservedRunData: params.TrustReservedRunData, // the reserved keys left in data are the parent's, already vetted
9361
10321
  context: subAgentContext, // use subAgentRequest.context if provided, otherwise params.context
9362
10322
  verbose: params.verbose, // pass verbose flag to sub-agent
10323
+ treeBudget: this.ensureTreeBudget(params), // propagate shared cumulative root-tree budget to sub-agent
9363
10324
  actionChanges: subAgentActionChanges, // propagate filtered action changes to sub-agent
9364
10325
  subAgentChanges: subAgentSubAgentChanges, // propagate filtered sub-agent changes to sub-agent
9365
10326
  PrimaryScopeEntityName: params.PrimaryScopeEntityName, // propagate scope to sub-agent
9366
10327
  PrimaryScopeRecordID: params.PrimaryScopeRecordID,
9367
10328
  companyId: params.companyId,
9368
10329
  SecondaryScopes: params.SecondaryScopes,
10330
+ conversationDetailId: params.conversationDetailId, // propagate conversationDetailId so sub-agent task graphs attach to the chat message
9369
10331
  onAgentRunCreated: async (agentRunId) => {
9370
10332
  stepEntity.TargetLogID = agentRunId;
9371
10333
  // Re-apply post-INSERT: this callback can fire while the step's INSERT is still in flight,
@@ -9395,6 +10357,28 @@ The context is now within limits. Please retry your request with the recovered c
9395
10357
  throw new Error(`Error executing sub-agent: ${error.message}`);
9396
10358
  }
9397
10359
  }
10360
+ /**
10361
+ * A sub-agent request's template parameters without the host-only run-data keys
10362
+ * (`HOST_ONLY_AGENT_RUN_DATA_KEYS` in `@memberjunction/ai-core-plus`: the reserved scope family and
10363
+ * `__agentTypePromptParams`, and the browser, conversation and realtime controls — `clientTools`, `sessionID`,
10364
+ * `appContext`, `applicationId`, `conversationId`, `targetAgentID`, `agentSessionId`, `recording`, `realtime*`).
10365
+ * They are merged into the child's `data`, which `BaseAgent` reads for all of these, and inside a Loop agent they
10366
+ * are written by the model — so left in, a model could set a sub-agent's tenant (whenever the parent's run trusts
10367
+ * its `data`), offer it client tools, inject an app context, or point it at another conversation. The child
10368
+ * inherits the parent's values instead (its own params, and the parent's `data` as is). What was removed is
10369
+ * logged once, by key only — never the values.
10370
+ */
10371
+ subAgentTemplateParameters(params, subAgentRequest) {
10372
+ if (!subAgentRequest.templateParameters) {
10373
+ return undefined;
10374
+ }
10375
+ const { Data, StrippedKeys } = WithoutHostOnlyAgentRunDataKeys(subAgentRequest.templateParameters);
10376
+ if (StrippedKeys.length > 0) {
10377
+ this.logStatus(`🔒 Ignored host-only key(s) ${StrippedKeys.join(', ')} in the template parameters for sub-agent '${subAgentRequest.name}': ` +
10378
+ `a sub-agent inherits its parent run's scope, agent-type parameters, conversation and browser context; the model cannot set them.`, false, params);
10379
+ }
10380
+ return Data;
10381
+ }
9398
10382
  /**
9399
10383
  * Formats sub-agent details as compact markdown for inclusion in prompt context.
9400
10384
  *
@@ -9623,8 +10607,14 @@ The context is now within limits. Please retry your request with the recovered c
9623
10607
  if (param.IsArray) {
9624
10608
  parts.push('array');
9625
10609
  }
10610
+ // A stored ValueSchema is the real type, so it replaces the coarse ValueType label — the
10611
+ // same information the native tool declaration carries.
10612
+ const valueSchema = GetStoredValueSchema(param);
9626
10613
  const vt = param.ValueType?.trim();
9627
- if (vt && vt !== 'Scalar' && vt !== 'Other') {
10614
+ if (valueSchema) {
10615
+ parts.push(DescribeValueSchemaInline(valueSchema));
10616
+ }
10617
+ else if (vt && vt !== 'Scalar' && vt !== 'Other') {
9628
10618
  parts.push(vt);
9629
10619
  }
9630
10620
  const suffix = parts.length > 0 ? ` (${parts.join(', ')})` : '';
@@ -9731,6 +10721,9 @@ The context is now within limits. Please retry your request with the recovered c
9731
10721
  if (!result.success && result.agentRun?.ErrorMessage) {
9732
10722
  lines.push(`**Error:** ${result.agentRun.ErrorMessage}`);
9733
10723
  }
10724
+ if (result.agentRun?.Message?.trim()) {
10725
+ lines.push(`**Message:**\n${result.agentRun.Message.trim()}`);
10726
+ }
9734
10727
  // Payload — the actual result data the parent agent cares about.
9735
10728
  // Not truncated by default — the expiration/compaction lifecycle handles
9736
10729
  // context window management. Truncating here permanently discards data
@@ -9801,7 +10794,7 @@ The context is now within limits. Please retry your request with the recovered c
9801
10794
  * @private
9802
10795
  */
9803
10796
  resolveActionResultCrush(params) {
9804
- const agentTypePromptParams = params.data?.__agentTypePromptParams;
10797
+ const agentTypePromptParams = (params.data?.__agentTypePromptParams ?? this._agentTypePromptParams);
9805
10798
  if (agentTypePromptParams?.crushActionResults === false) {
9806
10799
  return undefined;
9807
10800
  }
@@ -10062,6 +11055,7 @@ The context is now within limits. Please retry your request with the recovered c
10062
11055
  this.assertLastRunIdIsUUID(params.lastRunId);
10063
11056
  // Handle autoPopulateLastRunPayload if requested
10064
11057
  let modifiedParams = params;
11058
+ let preloadedLastRun;
10065
11059
  if (params.lastRunId && params.autoPopulateLastRunPayload) {
10066
11060
  // Load the last run to get its FinalPayload
10067
11061
  const rv = new RunView();
@@ -10072,6 +11066,9 @@ The context is now within limits. Please retry your request with the recovered c
10072
11066
  // A stopped predecessor wrote its FinalPayload moments ago; read the database, not a cache.
10073
11067
  BypassCache: true
10074
11068
  }, params.contextUser);
11069
+ if (lastRunResult.Success) {
11070
+ preloadedLastRun = lastRunResult.Results[0] ?? null;
11071
+ }
10075
11072
  if (lastRunResult.Success && lastRunResult.Results.length > 0) {
10076
11073
  const lastRun = lastRunResult.Results[0];
10077
11074
  if (lastRun.FinalPayload) {
@@ -10096,7 +11093,10 @@ The context is now within limits. Please retry your request with the recovered c
10096
11093
  }
10097
11094
  // Reset prompt turn counter for this execution
10098
11095
  this._promptTurnCount = 0;
11096
+ this._lastRecordedPromptStack = null;
11097
+ this._templateEngineConfiguredForRun = false;
10099
11098
  this._heldDecisions = undefined;
11099
+ this._awaitingWorkflowTaskID = null;
10100
11100
  // Resolve action-result compression config for this run (default on; opt out via
10101
11101
  // crushActionResults: false in the agent-type prompt params).
10102
11102
  this._actionResultCrush = this.resolveActionResultCrush(params);
@@ -10146,8 +11146,8 @@ The context is now within limits. Please retry your request with the recovered c
10146
11146
  this._agentRun.ContinuationDepth = params.continuationDepth ?? 0;
10147
11147
  // Set LastRunID for run chaining (different from ParentRunID)
10148
11148
  if (params.lastRunId) {
10149
- // Check for circular references in the run chain
10150
- await this.validateRunChain(params.lastRunId, params.contextUser);
11149
+ // Check for circular references in the run chain (reusing preloadedLastRun when available)
11150
+ await this.validateRunChain(params.lastRunId, params.contextUser, preloadedLastRun);
10151
11151
  this._agentRun.LastRunID = params.lastRunId;
10152
11152
  }
10153
11153
  // Set StartingPayload if we have a payload (either from params or auto-populated)
@@ -10184,45 +11184,23 @@ The context is now within limits. Please retry your request with the recovered c
10184
11184
  if (params.testRunId) {
10185
11185
  this._agentRun.TestRunID = params.testRunId;
10186
11186
  }
10187
- // Set scope for multi-tenant deployments
10188
- // Resolve from top-level params or data fallback (for GraphQL callers)
10189
- const primaryScopeEntityName = params.PrimaryScopeEntityName ?? params.data?.PrimaryScopeEntityName;
10190
- const primaryScopeRecordID = params.PrimaryScopeRecordID ?? params.data?.PrimaryScopeRecordID;
10191
- const secondaryScopes = params.SecondaryScopes ?? params.data?.SecondaryScopes;
10192
- if (primaryScopeEntityName || primaryScopeRecordID || secondaryScopes) {
10193
- // Parse agent's SecondaryScopeConfig from the ScopeConfig field
10194
- const scopeConfig = this.parseSecondaryScopeConfig(params.agent);
10195
- // Validate and apply secondary scopes with defaults
10196
- const validatedSecondary = this.validateAndApplySecondaryScopes(secondaryScopes, scopeConfig, params.agent.Name);
10197
- // Check if secondary-only is allowed
10198
- const hasSecondary = validatedSecondary && Object.keys(validatedSecondary).length > 0;
10199
- const hasPrimary = !!primaryScopeRecordID;
10200
- const allowSecondaryOnly = scopeConfig?.allowSecondaryOnly ?? false;
10201
- if (hasSecondary && !hasPrimary && !allowSecondaryOnly) {
10202
- LogError(`Scoping: Agent "${params.agent.Name}" requires primary scope when using secondary scopes. ` +
10203
- `Set allowSecondaryOnly=true in ScopeConfig to allow secondary-only scoping.`);
10204
- }
10205
- // Resolve primary entity ID from entity name
10206
- if (primaryScopeEntityName) {
10207
- const primaryEntity = this.ProviderToUse.EntityByName(primaryScopeEntityName);
10208
- if (primaryEntity) {
10209
- this._agentRun.PrimaryScopeEntityID = primaryEntity.ID;
10210
- }
10211
- else {
10212
- LogError(`Scoping: Entity "${primaryScopeEntityName}" not found in metadata`);
10213
- }
10214
- }
10215
- // Set primary scope record ID
10216
- if (primaryScopeRecordID) {
10217
- this._agentRun.PrimaryScopeRecordID = primaryScopeRecordID;
10218
- }
10219
- // Set secondary scopes as JSON (with defaults applied)
10220
- if (validatedSecondary && Object.keys(validatedSecondary).length > 0) {
10221
- this._agentRun.SecondaryScopes = JSON.stringify(validatedSecondary);
10222
- }
10223
- }
10224
- // Save the agent run
10225
- if (!await this._agentRun.Save()) {
11187
+ // Set scope for multi-tenant deployments: resolved once (the explicit params, else the `data` fallbacks
11188
+ // GraphQL callers use) and validated against the agent's SecondaryScopeConfig, written to the run row, and
11189
+ // kept as the scope every action dispatch is handed (RunActionParams.RunScope). Inside the run, that scope
11190
+ // — not a model-written action parameter — is the authority on the tenant.
11191
+ this._runScope = this.validatedRunScope(params);
11192
+ this.writeRunScope(params, this._runScope);
11193
+ // Initialize hierarchy tracking before resolvePlanModeGate (which reads _depth) so the
11194
+ // Plan Mode gate lookup can run concurrently with persisting the agent run record.
11195
+ this._agentHierarchy = params.parentAgentHierarchy
11196
+ ? [...params.parentAgentHierarchy, params.agent.Name || 'Unknown Agent']
11197
+ : [params.agent.Name || 'Unknown Agent'];
11198
+ this._depth = params.parentDepth !== undefined ? params.parentDepth + 1 : 0;
11199
+ this._parentStepCounts = params.parentStepCounts || [];
11200
+ const planModeGatePromise = this.resolvePlanModeGate(params);
11201
+ // Save the agent run while resolvePlanModeGate runs concurrently
11202
+ if (!await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' })) {
11203
+ await planModeGatePromise.catch(() => undefined);
10226
11204
  const errorMessage = JSON.stringify(CopyScalarsAndArrays(this._agentRun.LatestResult));
10227
11205
  throw new Error(`Failed to create agent run record: Details: ${errorMessage}`);
10228
11206
  }
@@ -10243,16 +11221,9 @@ The context is now within limits. Please retry your request with the recovered c
10243
11221
  // Don't fail the execution if callback fails
10244
11222
  }
10245
11223
  }
10246
- // Initialize hierarchy tracking
10247
- this._agentHierarchy = params.parentAgentHierarchy
10248
- ? [...params.parentAgentHierarchy, params.agent.Name || 'Unknown Agent']
10249
- : [params.agent.Name || 'Unknown Agent'];
10250
- this._depth = params.parentDepth !== undefined ? params.parentDepth + 1 : 0;
10251
- this._parentStepCounts = params.parentStepCounts || [];
10252
- // Resolve Plan Mode gate state for this run (must happen before the main loop starts —
10253
- // gatherPromptTemplateData/validateNextStep both read _planModeActive/_planApproved — and
10254
- // after _depth is set above, since the gate only applies to root agents).
10255
- const planModeGate = await this.resolvePlanModeGate(params);
11224
+ // Await Plan Mode gate state for this run (must happen before the main loop starts —
11225
+ // gatherPromptTemplateData/validateNextStep both read _planModeActive/_planApproved).
11226
+ const planModeGate = await planModeGatePromise;
10256
11227
  this._planModeActive = planModeGate.active;
10257
11228
  this._planApproved = planModeGate.approved;
10258
11229
  // Stamp the run record so the UX (run-header Plan Mode chip) and plan-drift audits can
@@ -10398,6 +11369,15 @@ The context is now within limits. Please retry your request with the recovered c
10398
11369
  if (params.targetId && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(params.targetId)) {
10399
11370
  console.warn(`Invalid target ID format: ${params.targetId}`);
10400
11371
  }
11372
+ // A start or end payload that repeats an earlier step's end is stored as a pointer to that step.
11373
+ const payloadAtStart = this.serializePayloadAtStart(params.payloadAtStart);
11374
+ const payloadAtStartSource = this.findPayloadAtStartSource(payloadAtStart);
11375
+ const payloadAtEnd = (params.payloadAtEnd !== undefined &&
11376
+ params.payloadAtEnd === params.payloadAtStart &&
11377
+ this.hasDefaultPayloadSerializers())
11378
+ ? payloadAtStart
11379
+ : this.serializePayloadAtEnd(params.payloadAtEnd);
11380
+ const payloadAtEndSource = this.findPayloadAtEndSource(payloadAtEnd);
10401
11381
  // Populate the started fields via the shared single-source-of-truth helper. Instance-specific
10402
11382
  // concerns (hierarchy breadcrumb, InputData context, payload serialization) are computed here.
10403
11383
  initAgentRunStep(stepEntity, {
@@ -10408,8 +11388,10 @@ The context is now within limits. Please retry your request with the recovered c
10408
11388
  TargetID: params.targetId,
10409
11389
  TargetLogID: params.targetLogId,
10410
11390
  ParentID: params.parentId, // Link to parent step (e.g., loop step)
10411
- PayloadAtStart: this.serializePayloadAtStart(params.payloadAtStart),
10412
- PayloadAtEnd: this.serializePayloadAtEnd(params.payloadAtEnd),
11391
+ PayloadAtStart: payloadAtStartSource ? null : payloadAtStart,
11392
+ PayloadAtStartSourceStepID: payloadAtStartSource?.ID ?? null,
11393
+ PayloadAtEnd: payloadAtEndSource ? null : payloadAtEnd,
11394
+ PayloadAtEndSourceStepID: payloadAtEndSource?.ID ?? null,
10413
11395
  InputData: params.inputData
10414
11396
  ? JSON.stringify({
10415
11397
  ...params.inputData,
@@ -10443,28 +11425,159 @@ The context is now within limits. Please retry your request with the recovered c
10443
11425
  }
10444
11426
  // Fire-and-forget the 'started' INSERT — the agent flow never blocks on a step save. The queue
10445
11427
  // tracks the INSERT so every later UPDATE (queueStepSave) chains AFTER it commits.
10446
- // When the step has a parent, chain the INSERT AFTER the parent's INSERT to satisfy the
10447
- // self-referencing FK_AIAgentRunStep_ParentID constraint — without this, a child INSERT that
10448
- // races the parent INSERT hits an FK violation (especially under large-payload parent INSERTs).
11428
+ // - When the step has a parent, chain the INSERT AFTER the parent's INSERT to satisfy the
11429
+ // self-referencing FK_AIAgentRunStep_ParentID constraint.
11430
+ // - When the step points PayloadAtStartSourceStepID at a predecessor whose INSERT is still in
11431
+ // flight (!payloadAtStartSource.IsSaved), ALSO chain the INSERT after payloadAtStartSource to
11432
+ // satisfy FK_AIAgentRunStep_PayloadAtStartSourceStepID, with a beforeInsert guard that falls
11433
+ // back to inline PayloadAtStart if the source step's INSERT failed. When payloadAtStartSource
11434
+ // is already saved (IsSaved === true), do NOT chain behind it so this step's INSERT never waits
11435
+ // behind a subsequent UPDATE on payloadAtStartSource.
10449
11436
  const parentStepEntity = params.parentId && this._agentRun?.Steps
10450
11437
  ? this._agentRun.Steps.find(s => UUIDsEqual(s.ID, params.parentId))
10451
11438
  : undefined;
10452
- this._stepSaveQueue.Insert(stepEntity, parentStepEntity);
11439
+ if (payloadAtStartSource && !payloadAtStartSource.IsSaved) {
11440
+ this._stepSaveQueue.Insert(stepEntity, [parentStepEntity, payloadAtStartSource], (s) => {
11441
+ if (!payloadAtStartSource.IsSaved) {
11442
+ s.PayloadAtStart = payloadAtStart;
11443
+ s.PayloadAtStartSourceStepID = null;
11444
+ }
11445
+ });
11446
+ }
11447
+ else {
11448
+ this._stepSaveQueue.Insert(stepEntity, parentStepEntity);
11449
+ }
10453
11450
  // Add the step to the agent run's Steps array
10454
11451
  if (this._agentRun) {
10455
11452
  this._agentRun.Steps.push(stepEntity);
10456
11453
  }
11454
+ // Increment cumulative step count on the shared root-tree budget
11455
+ this.ensureTreeBudget(this._executeParams).totalSteps += 1;
10457
11456
  return stepEntity;
10458
11457
  }
10459
11458
  /**
10460
- * Finalizes a step entity with completion status.
11459
+ * Finds the step whose `PayloadAtEnd` a new step's start payload repeats, so the new step stores a
11460
+ * pointer to it (`PayloadAtStartSourceStepID`) instead of a second copy. Call it before the new step
11461
+ * is added to the run's `Steps`.
10461
11462
  *
10462
- * @private
10463
- * @param {MJAIAgentRunStepEntityExtended} stepEntity - The step entity to finalize
10464
- * @param {boolean} success - Whether the step was successful
10465
- * @param {string} [errorMessage] - Optional error message
10466
- * @param {any} [outputData] - Optional output data to capture for this step
11463
+ * The candidate is the latest step in the run that is not `Running` and has a `PayloadAtEnd` (or
11464
+ * `PayloadAtEndSourceStepID`). Only that step is compared. If that step itself points to an earlier
11465
+ * step via `PayloadAtEndSourceStepID`, the pointer resolves in one hop to the step that actually
11466
+ * holds the stored `PayloadAtEnd`.
11467
+ * - Running steps are skipped because their end can still change: parallel sub-agent siblings write
11468
+ * their own result as `PayloadAtEnd` when they finish, and a ForEach step writes its end after all
11469
+ * of its child steps.
11470
+ * - Finished steps with no end (tool, compaction and finish-check steps) are skipped because they never
11471
+ * get one, and would hide the step that produced the payload.
11472
+ * - If the matching candidate's INSERT is still in flight (`!step.IsSaved`), {@link createStepEntity}
11473
+ * chains the new step's INSERT after `step` on {@link _stepSaveQueue} (and falls back to storing inline
11474
+ * `PayloadAtStart` if the candidate's INSERT fails) so `FK_AIAgentRunStep_PayloadAtStartSourceStepID`
11475
+ * is always satisfied without sacrificing deduplication on fast back-to-back turns.
11476
+ *
11477
+ * Rule: a step's `PayloadAtEnd` must not change after a later step points at it, because readers take
11478
+ * the pointing step's start payload from it. The comparison uses the in-memory end, so the saved end
11479
+ * must match it: `finalizeStepEntity` re-applies the end after the INSERT lands, and an end set after
11480
+ * `finalizeStepEntity` is saved with `queueStepSave`.
11481
+ *
11482
+ * @param serializedStart The new step's start payload, already serialized.
11483
+ * @returns The step to point at, or undefined when the start payload must be stored.
10467
11484
  */
11485
+ findPayloadAtStartSource(serializedStart) {
11486
+ return this.findPayloadEndSourceBefore(serializedStart);
11487
+ }
11488
+ /**
11489
+ * Finds the earlier step whose stored `PayloadAtEnd` this step's end payload repeats, so the step
11490
+ * stores a one-hop pointer (`PayloadAtEndSourceStepID`) instead of a second copy.
11491
+ */
11492
+ findPayloadAtEndSource(serializedEnd, beforeStep) {
11493
+ return this.findPayloadEndSourceBefore(serializedEnd, beforeStep);
11494
+ }
11495
+ findPayloadEndSourceBefore(serializedPayload, beforeStep) {
11496
+ if (serializedPayload == null) {
11497
+ return undefined;
11498
+ }
11499
+ const steps = this._agentRun?.Steps ?? [];
11500
+ let startIdx = steps.length - 1;
11501
+ if (beforeStep) {
11502
+ const foundIdx = steps.indexOf(beforeStep);
11503
+ if (foundIdx >= 0) {
11504
+ startIdx = foundIdx - 1;
11505
+ }
11506
+ }
11507
+ // When beforeStep is provided (findPayloadAtEndSource during finalizeStepEntity), the
11508
+ // source step must already be IsSaved because finalizeStepEntity queues an UPDATE rather
11509
+ // than an INSERT with prerequisite chaining. When beforeStep is omitted (findPayloadAtStartSource
11510
+ // during createStepEntity), an in-flight source step is allowed because createStepEntity chains
11511
+ // the new step's INSERT after the source step on _stepSaveQueue.
11512
+ const requireSavedSource = beforeStep != null;
11513
+ let candidateStep;
11514
+ for (let i = startIdx; i >= 0; i--) {
11515
+ const step = steps[i];
11516
+ if (step.Status !== 'Running' && (step.PayloadAtEnd != null || step.PayloadAtEndSourceStepID != null)) {
11517
+ candidateStep = step;
11518
+ break;
11519
+ }
11520
+ }
11521
+ if (!candidateStep) {
11522
+ return undefined;
11523
+ }
11524
+ if (requireSavedSource && !candidateStep.IsSaved) {
11525
+ return undefined;
11526
+ }
11527
+ const source = candidateStep.PayloadAtEndSourceStepID
11528
+ ? steps.find(s => UUIDsEqual(s.ID, candidateStep.PayloadAtEndSourceStepID))
11529
+ : candidateStep;
11530
+ if (!source) {
11531
+ return undefined;
11532
+ }
11533
+ if (requireSavedSource && !source.IsSaved) {
11534
+ return undefined;
11535
+ }
11536
+ return source.PayloadAtEnd === serializedPayload ? source : undefined;
11537
+ }
11538
+ /**
11539
+ * Returns true when neither `serializePayloadAtStart` nor `serializePayloadAtEnd` has been
11540
+ * overridden by a subclass, allowing unchanged start payloads to be reused as end payloads
11541
+ * without a second `JSON.stringify` pass.
11542
+ */
11543
+ hasDefaultPayloadSerializers() {
11544
+ return (this.serializePayloadAtStart === BaseAgent.prototype.serializePayloadAtStart &&
11545
+ this.serializePayloadAtEnd === BaseAgent.prototype.serializePayloadAtEnd);
11546
+ }
11547
+ /**
11548
+ * Resolves a step's start payload from its own `PayloadAtStart` or the step referenced by
11549
+ * `PayloadAtStartSourceStepID`.
11550
+ */
11551
+ resolveStepPayloadAtStart(step) {
11552
+ if (!step) {
11553
+ return null;
11554
+ }
11555
+ if (step.PayloadAtStart != null) {
11556
+ return step.PayloadAtStart;
11557
+ }
11558
+ if (step.PayloadAtStartSourceStepID) {
11559
+ const source = this._agentRun?.Steps?.find(s => UUIDsEqual(s.ID, step.PayloadAtStartSourceStepID));
11560
+ return source?.PayloadAtEnd ?? null;
11561
+ }
11562
+ return null;
11563
+ }
11564
+ /**
11565
+ * Resolves a step's end payload from its own `PayloadAtEnd` or the step referenced by
11566
+ * `PayloadAtEndSourceStepID`.
11567
+ */
11568
+ resolveStepPayloadAtEnd(step) {
11569
+ if (!step) {
11570
+ return null;
11571
+ }
11572
+ if (step.PayloadAtEnd != null) {
11573
+ return step.PayloadAtEnd;
11574
+ }
11575
+ if (step.PayloadAtEndSourceStepID) {
11576
+ const source = this._agentRun?.Steps?.find(s => UUIDsEqual(s.ID, step.PayloadAtEndSourceStepID));
11577
+ return source?.PayloadAtEnd ?? null;
11578
+ }
11579
+ return null;
11580
+ }
10468
11581
  /**
10469
11582
  * Builds a summary of payload change results for storage
10470
11583
  * @param changeResult The result from PayloadManager operations
@@ -10505,6 +11618,68 @@ The context is now within limits. Please retry your request with the recovered c
10505
11618
  } : undefined
10506
11619
  };
10507
11620
  }
11621
+ /**
11622
+ * Captures the conversation messages for a `Prompt` step's `InputData` without
11623
+ * persisting volatile `<mj-runtime-state>` envelopes or repeating messages already
11624
+ * recorded in an earlier `Prompt` step of the current run.
11625
+ *
11626
+ * - When the non-volatile stack extends the previous Prompt step's recorded stack append-only (the
11627
+ * same messages, unchanged, at the same positions), only the appended messages are stored, tagged
11628
+ * with `conversationMessagesDelta: true`.
11629
+ * - Otherwise (the first Prompt step of the run, or a message was replaced, removed or changed by
11630
+ * expiry, compaction or expansion) the full non-volatile stack is stored, with no delta flag.
11631
+ *
11632
+ * {@link buildResumedStoppedRunTurns} rebuilds the stack from the latest full stack plus the deltas after it.
11633
+ */
11634
+ capturePromptStepMessages(messages) {
11635
+ const nonVolatile = (messages ?? []).filter(m => m?.metadata?.volatileState !== true);
11636
+ const previous = this._lastRecordedPromptStack;
11637
+ const isExtension = previous !== null && BaseAgent.isAppendOnlyExtension(previous, nonVolatile);
11638
+ const recorded = new Array(nonVolatile.length);
11639
+ for (let i = 0; i < nonVolatile.length; i++) {
11640
+ if (isExtension && i < previous.length) {
11641
+ recorded[i] = previous[i];
11642
+ }
11643
+ else {
11644
+ const m = nonVolatile[i];
11645
+ const meta = m.metadata;
11646
+ recorded[i] = {
11647
+ Message: m,
11648
+ ContentRef: m.content,
11649
+ MetadataRef: meta,
11650
+ WasCompacted: meta?.wasCompacted,
11651
+ CanExpand: meta?.canExpand,
11652
+ IsExpired: meta?.isExpired,
11653
+ };
11654
+ }
11655
+ }
11656
+ this._lastRecordedPromptStack = recorded;
11657
+ if (isExtension) {
11658
+ return { conversationMessages: nonVolatile.slice(previous.length), conversationMessagesDelta: true };
11659
+ }
11660
+ return { conversationMessages: nonVolatile };
11661
+ }
11662
+ /** True when `current` starts with every message of `previous`, by reference and unchanged in place. @private */
11663
+ static isAppendOnlyExtension(previous, current) {
11664
+ if (current.length < previous.length) {
11665
+ return false;
11666
+ }
11667
+ for (let i = 0; i < previous.length; i++) {
11668
+ const p = previous[i];
11669
+ const c = current[i];
11670
+ if (c !== p.Message || c.content !== p.ContentRef) {
11671
+ return false;
11672
+ }
11673
+ const meta = c.metadata;
11674
+ if (meta !== p.MetadataRef ||
11675
+ meta?.wasCompacted !== p.WasCompacted ||
11676
+ meta?.canExpand !== p.CanExpand ||
11677
+ meta?.isExpired !== p.IsExpired) {
11678
+ return false;
11679
+ }
11680
+ }
11681
+ return true;
11682
+ }
10508
11683
  /**
10509
11684
  * Finalizes a step entity with completion status. Pairs with `createStepEntity`
10510
11685
  * — drivers that create custom steps should also finalize them through this
@@ -10512,31 +11687,82 @@ The context is now within limits. Please retry your request with the recovered c
10512
11687
  * populated consistently and the UPDATE is sequenced behind the INSERT via
10513
11688
  * `queueStepSave`.
10514
11689
  *
11690
+ * Set `PayloadAtEnd` before calling it: the queued UPDATE re-applies the end the step has now.
11691
+ * An end set later must be saved with `queueStepSave`.
11692
+ *
10515
11693
  * @protected
10516
11694
  */
10517
11695
  async finalizeStepEntity(stepEntity, success, errorMessage, outputData) {
10518
11696
  try {
11697
+ // Preserve any OutputData properties already stamped on the step prior to finalize
11698
+ // (e.g. guardrailExceeded written by checkExecutionGuardrails during processNextStep).
11699
+ let effectiveOutputData = outputData;
11700
+ const existingRawOutputData = stepEntity.OutputData;
11701
+ if (existingRawOutputData && outputData && typeof outputData === 'object') {
11702
+ try {
11703
+ const parsedExisting = JSON.parse(existingRawOutputData);
11704
+ if (parsedExisting && typeof parsedExisting === 'object' && !Array.isArray(parsedExisting)) {
11705
+ effectiveOutputData = {
11706
+ ...parsedExisting,
11707
+ ...outputData
11708
+ };
11709
+ }
11710
+ }
11711
+ catch {
11712
+ // Leave effectiveOutputData as-is if existing OutputData is not a JSON object
11713
+ }
11714
+ }
10519
11715
  // Capture the completion timestamp NOW so the duration is accurate regardless of when the
10520
11716
  // mutation is actually applied/persisted.
10521
11717
  const finalizeOpts = {
10522
11718
  success,
10523
11719
  errorMessage,
10524
- outputData: outputData ? CopyScalarsAndArrays(outputData, true) : undefined,
11720
+ outputData: effectiveOutputData ? CopyScalarsAndArrays(effectiveOutputData, true) : undefined,
10525
11721
  completedAt: new Date(),
10526
11722
  // Capture any TargetLogID already stamped on the entity (e.g. a prompt-run / sub-agent-run id
10527
11723
  // set before finalize) so the post-INSERT re-apply restores it too — otherwise the INSERT's
10528
11724
  // reload could leave it null on a fast step.
10529
11725
  targetLogID: stepEntity.TargetLogID ?? undefined
10530
11726
  };
11727
+ const finalPayloadValidationResult = stepEntity.FinalPayloadValidationResult;
11728
+ const finalPayloadValidationMessages = stepEntity.FinalPayloadValidationMessages;
11729
+ // Deduplicate PayloadAtEnd against the latest earlier finished, saved step when unchanged.
11730
+ if (stepEntity.PayloadAtEnd != null) {
11731
+ const endSource = this.findPayloadAtEndSource(stepEntity.PayloadAtEnd, stepEntity);
11732
+ if (endSource) {
11733
+ stepEntity.PayloadAtEnd = null;
11734
+ stepEntity.PayloadAtEndSourceStepID = endSource.ID;
11735
+ }
11736
+ else {
11737
+ stepEntity.PayloadAtEndSourceStepID = null;
11738
+ }
11739
+ }
11740
+ // Capture the end the step finished with for the same reason: a later step may point at this
11741
+ // step after comparing this end, so the saved row must end with it.
11742
+ const payloadAtEnd = stepEntity.PayloadAtEnd;
11743
+ const payloadAtEndSourceStepID = stepEntity.PayloadAtEndSourceStepID ?? null;
10531
11744
  // Apply to the in-memory entity NOW so the run's Steps array / UI see the terminal state
10532
11745
  // immediately. This in-memory copy can be reverted by the INSERT's post-save reload if the step
10533
11746
  // finished while its INSERT was still in flight, which is why we ALSO re-apply it inside the
10534
11747
  // post-INSERT continuation below (idempotent — same completedAt).
10535
11748
  finalizeAgentRunStep(stepEntity, finalizeOpts);
10536
- // Fire-and-forget the UPDATE, but re-assert the finalize state AFTER the INSERT (and its reload)
10537
- // lands so the force-persisted UPDATE never writes stale pre-finalize values. The agent flow
10538
- // never blocks on this UPDATE.
10539
- this.queueStepSave(stepEntity, (s) => finalizeAgentRunStep(s, finalizeOpts));
11749
+ // Fire-and-forget the UPDATE, but re-assert the finalize state and the end AFTER the INSERT (and
11750
+ // its reload) lands so the force-persisted UPDATE never writes stale pre-finalize values. The
11751
+ // agent flow never blocks on this UPDATE.
11752
+ this.queueStepSave(stepEntity, (s) => {
11753
+ if (finalizeOpts.outputData === undefined && existingRawOutputData != null) {
11754
+ s.OutputData = existingRawOutputData;
11755
+ }
11756
+ if (finalPayloadValidationResult !== undefined) {
11757
+ s.FinalPayloadValidationResult = finalPayloadValidationResult;
11758
+ }
11759
+ if (finalPayloadValidationMessages !== undefined) {
11760
+ s.FinalPayloadValidationMessages = finalPayloadValidationMessages;
11761
+ }
11762
+ finalizeAgentRunStep(s, finalizeOpts);
11763
+ s.PayloadAtEnd = payloadAtEnd;
11764
+ s.PayloadAtEndSourceStepID = payloadAtEndSourceStepID;
11765
+ });
10540
11766
  }
10541
11767
  catch (e) {
10542
11768
  LogError(`Failed to update agent run step record: ${e?.message ?? e}`, undefined, e);
@@ -10636,6 +11862,68 @@ The context is now within limits. Please retry your request with the recovered c
10636
11862
  }
10637
11863
  return baseMessage;
10638
11864
  }
11865
+ /**
11866
+ * Builds the user-oriented initialization progress message for an agent run.
11867
+ *
11868
+ * - Root agent (`_depth === 0`): `'Getting ready...'`
11869
+ * - Direct sub-agent (`_depth === 1`): `'Starting <SubAgentName>...'`
11870
+ * - Nested sub-agent (`_depth > 1`): `'<ParentBreadcrumb>: Starting <SubAgentName>...'`
11871
+ *
11872
+ * @protected
11873
+ * @param {ExecuteAgentParams} params - Execution parameters for the current agent
11874
+ * @returns {string} Formatted initialization progress message
11875
+ */
11876
+ buildInitializationProgressMessage(params) {
11877
+ if (this._depth === 0) {
11878
+ return 'Getting ready...';
11879
+ }
11880
+ const startPhrase = `Starting ${params.agent.Name}...`;
11881
+ const parentBreadcrumb = this._agentHierarchy.slice(1, -1).join(' → ');
11882
+ return parentBreadcrumb ? `${parentBreadcrumb}: ${startPhrase}` : startPhrase;
11883
+ }
11884
+ /**
11885
+ * Builds a user-oriented progress message for a prompt execution step without
11886
+ * exposing internal framework terminology ("initial prompt", "payload", "context")
11887
+ * or duplicating the sub-agent name when prefixed by {@link formatHierarchicalMessage}.
11888
+ *
11889
+ * @protected
11890
+ * @param {ExecuteAgentParams} params - Execution parameters for the current agent
11891
+ * @param {BaseAgentNextStep | null} [previousDecision] - Previous step decision when re-prompting
11892
+ * @returns {string} Base progress message (before `formatHierarchicalMessage` breadcrumb prefixing)
11893
+ */
11894
+ buildPromptProgressMessage(params, previousDecision) {
11895
+ if (!previousDecision) {
11896
+ return this._depth > 0
11897
+ ? 'Thinking...'
11898
+ : `${params.agent.Name} is thinking...`;
11899
+ }
11900
+ const retryReason = previousDecision.retryReason?.trim();
11901
+ if (retryReason) {
11902
+ if (retryReason === 'Payload change applied') {
11903
+ return this._depth > 0
11904
+ ? 'Thinking through the next steps...'
11905
+ : `${params.agent.Name} is thinking through the next steps...`;
11906
+ }
11907
+ if (retryReason.startsWith('Context recovery')) {
11908
+ return this._depth > 0
11909
+ ? 'Thinking...'
11910
+ : `${params.agent.Name} is thinking...`;
11911
+ }
11912
+ if (retryReason === 'Error while processing actions, retry') {
11913
+ return 'Recovering from an error and trying another approach...';
11914
+ }
11915
+ return retryReason;
11916
+ }
11917
+ const retryInstructions = previousDecision.retryInstructions?.trim();
11918
+ if (retryInstructions) {
11919
+ return this._depth > 0
11920
+ ? 'Reviewing batch results...'
11921
+ : `${params.agent.Name} is reviewing batch results...`;
11922
+ }
11923
+ return this._depth > 0
11924
+ ? 'Thinking through the next steps...'
11925
+ : `${params.agent.Name} is thinking through the next steps...`;
11926
+ }
10639
11927
  /**
10640
11928
  * Trims a step name to what `AIAgentRunStep.StepName` can hold. Step names are built from free
10641
11929
  * text — a termination message quoting a provider's error, a tool name with its arguments, the
@@ -10723,6 +12011,23 @@ The context is now within limits. Please retry your request with the recovered c
10723
12011
  * @returns {Promise<BaseAgentNextStep<P>>}
10724
12012
  */
10725
12013
  async executeNextStep(params, config, previousDecision, stepCount = 0) {
12014
+ // Enforce cumulative root-tree budget limits before executing any non-terminal step
12015
+ const currentPayload = (previousDecision?.newPayload ?? previousDecision?.previousPayload ?? params.payload);
12016
+ if (previousDecision?.step !== 'Chat' && previousDecision?.terminate !== true) {
12017
+ const treeBudgetResult = this.checkTreeBudgetLimit(params);
12018
+ if (treeBudgetResult.exceeded) {
12019
+ this.logStatus(`⛔ Execution guardrail exceeded: ${treeBudgetResult.reason}`, false, params);
12020
+ return {
12021
+ ...(previousDecision ?? {}),
12022
+ step: 'Failed',
12023
+ terminate: true,
12024
+ previousPayload: currentPayload,
12025
+ newPayload: currentPayload,
12026
+ message: treeBudgetResult.reason,
12027
+ errorMessage: treeBudgetResult.reason
12028
+ };
12029
+ }
12030
+ }
10726
12031
  // Determine what to execute
10727
12032
  if (!previousDecision) {
10728
12033
  // First execution - ask the agent type what to do
@@ -10768,6 +12073,16 @@ The context is now within limits. Please retry your request with the recovered c
10768
12073
  // so the run shows what was emitted even if the sub-agent then fails.
10769
12074
  await this.recordFoldedTaskGraph(params, previousDecision);
10770
12075
  const subAgentResult = await this.processSubAgentStep(params, previousDecision, undefined, undefined, stepCount);
12076
+ if (this._treeBudget?.breachedReason) {
12077
+ const breachedReason = this._treeBudget.breachedReason;
12078
+ return {
12079
+ ...subAgentResult,
12080
+ step: 'Failed',
12081
+ terminate: true,
12082
+ message: breachedReason,
12083
+ errorMessage: breachedReason
12084
+ };
12085
+ }
10771
12086
  const afterSubAgent = (await this.finishAfterSubAgent(params, previousDecision, subAgentResult)) ?? subAgentResult;
10772
12087
  return this.selfCheckSuccess(params, afterSubAgent, afterSubAgent.newPayload ?? subAgentResult.newPayload);
10773
12088
  }
@@ -10952,7 +12267,7 @@ The context is now within limits. Please retry your request with the recovered c
10952
12267
  reason: previousDecision.retryReason,
10953
12268
  instructions: previousDecision.retryInstructions
10954
12269
  } : undefined,
10955
- conversationMessages: params.conversationMessages,
12270
+ ...this.capturePromptStepMessages(params.conversationMessages),
10956
12271
  ...(scratchpadSnapshotBeforeStep && { scratchpad: scratchpadSnapshotBeforeStep }),
10957
12272
  };
10958
12273
  // Prepare prompt parameters
@@ -10961,9 +12276,7 @@ The context is now within limits. Please retry your request with the recovered c
10961
12276
  try {
10962
12277
  // Report prompt execution progress with context
10963
12278
  const isRetry = !!previousDecision;
10964
- const promptMessage = isRetry
10965
- ? `Running ${params.agent.Name} with context from ${previousDecision.retryReason || 'previous actions'}`
10966
- : `Running ${params.agent.Name}'s initial prompt...`;
12279
+ const promptMessage = this.buildPromptProgressMessage(params, previousDecision);
10967
12280
  const hierarchicalStepToEmit = this.buildHierarchicalStep(stepCount + 1, this._parentStepCounts);
10968
12281
  this.safeOnProgress(params, {
10969
12282
  step: 'prompt_execution',
@@ -11021,6 +12334,7 @@ The context is now within limits. Please retry your request with the recovered c
11021
12334
  };
11022
12335
  // Execute the prompt
11023
12336
  const promptResult = await this.executePrompt(promptParams);
12337
+ this.recordPromptUsageInTreeBudget(promptResult.promptRun, promptResult, params);
11024
12338
  this.recordToolCallingInstrumentation(stepEntity, promptResult);
11025
12339
  // Increment prompt-specific turn counter (used for expiration age calculations)
11026
12340
  this._promptTurnCount++;
@@ -11039,12 +12353,31 @@ The context is now within limits. Please retry your request with the recovered c
11039
12353
  if (promptResult.modelSelectionInfo) {
11040
12354
  this._lastModelSelectionInfo = promptResult.modelSelectionInfo;
11041
12355
  }
12356
+ // Check for cancellation after prompt execution — before the failure check, because a prompt
12357
+ // the caller cancelled comes back failed, and that is not a prompt failure. The step does not
12358
+ // terminate the loop: a terminating step would finalize the run as Failed. The loop's own
12359
+ // cancellation check, before the next step, ends the run as Cancelled.
12360
+ if (params.cancellationToken?.aborted) {
12361
+ if (stepEntity && payload) {
12362
+ stepEntity.PayloadAtEnd = (this.hasDefaultPayloadSerializers() ? this.resolveStepPayloadAtStart(stepEntity) : null)
12363
+ ?? this.serializePayloadAtEnd(payload);
12364
+ }
12365
+ await this.finalizeStepEntity(stepEntity, false, 'Cancelled during prompt execution');
12366
+ return {
12367
+ errorMessage: 'Cancelled during prompt execution',
12368
+ step: 'Failed',
12369
+ terminate: false,
12370
+ previousPayload: payload,
12371
+ newPayload: payload
12372
+ };
12373
+ }
11042
12374
  // Check if prompt execution failed
11043
12375
  if (!promptResult.success) {
11044
12376
  // CRITICAL FIX: Preserve payload before finalizing step
11045
12377
  // This matches the success path behavior where PayloadAtEnd is set before finalizeStepEntity
11046
12378
  if (stepEntity && payload) {
11047
- stepEntity.PayloadAtEnd = this.serializePayloadAtEnd(payload);
12379
+ stepEntity.PayloadAtEnd = (this.hasDefaultPayloadSerializers() ? this.resolveStepPayloadAtStart(stepEntity) : null)
12380
+ ?? this.serializePayloadAtEnd(payload);
11048
12381
  }
11049
12382
  await this.finalizeStepEntity(stepEntity, false, promptResult.errorMessage);
11050
12383
  // Check if this is a fatal error that shouldn't be retried
@@ -11067,22 +12400,6 @@ The context is now within limits. Please retry your request with the recovered c
11067
12400
  newPayload: payload
11068
12401
  };
11069
12402
  }
11070
- // Check for cancellation after prompt execution
11071
- if (params.cancellationToken?.aborted) {
11072
- // CRITICAL FIX: Preserve payload before finalizing step
11073
- if (stepEntity && payload) {
11074
- stepEntity.PayloadAtEnd = this.serializePayloadAtEnd(payload);
11075
- }
11076
- await this.finalizeStepEntity(stepEntity, false, 'Cancelled during prompt execution');
11077
- const cancelledResult = await this.createCancelledResult('Cancelled during prompt execution', params.contextUser);
11078
- return {
11079
- ...cancelledResult,
11080
- terminate: true,
11081
- step: 'Failed', // Cancelled is treated as failed
11082
- previousPayload: cancelledResult.payload,
11083
- newPayload: cancelledResult.payload // No changes, just return the same payload
11084
- };
11085
- }
11086
12403
  // Report decision processing progress
11087
12404
  this.safeOnProgress(params, {
11088
12405
  step: 'decision_processing',
@@ -11096,15 +12413,29 @@ The context is now within limits. Please retry your request with the recovered c
11096
12413
  // Determine next step using agent type, this doesn't validate, just gets the LLM response and then we can process payload changes
11097
12414
  const initialNextStep = await this.determineNextStep(params, config.agentType, promptResult, payload);
11098
12415
  // Apply payload changes if provided
11099
- let finalPayload = payload; // Start with current payload
12416
+ const isUnmodifiedInheritedPayload = payload === params.payload;
12417
+ let finalPayload = (initialNextStep.artifactDirective?.behavior === 'create-new'
12418
+ && !initialNextStep.payloadChangeRequest
12419
+ && initialNextStep.step === 'Sub-Agent'
12420
+ && (this._promptTurnCount <= 1 || isUnmodifiedInheritedPayload))
12421
+ ? {}
12422
+ : payload; // Start with current payload
11100
12423
  let currentStepPayloadChangeResult = undefined;
11101
12424
  if (initialNextStep.payloadChangeRequest) {
11102
12425
  // Parse the allowed paths if configured
11103
12426
  const allowedPaths = params.agent.PayloadSelfWritePaths
11104
12427
  ? JSON.parse(params.agent.PayloadSelfWritePaths)
11105
12428
  : this.getDefaultPayloadSelfWritePaths();
12429
+ // When creating a brand-new artifact where the current payload is still the inherited
12430
+ // payload from a prior conversation run (even if read-only action steps ran first) or when
12431
+ // replaceElements is used with behavior='create-new', apply against a clean empty object
12432
+ // so keys from the previous artifact cannot bleed in.
12433
+ const basePayload = (initialNextStep.artifactDirective?.behavior === 'create-new'
12434
+ && (this._promptTurnCount <= 1 || isUnmodifiedInheritedPayload || Boolean(initialNextStep.payloadChangeRequest.replaceElements)))
12435
+ ? {}
12436
+ : payload;
11106
12437
  // Apply the changes to the payload with operation control
11107
- const changeResult = this._payloadManager.applyAgentChangeRequest(payload, initialNextStep.payloadChangeRequest, {
12438
+ const changeResult = this._payloadManager.applyAgentChangeRequest(basePayload, initialNextStep.payloadChangeRequest, {
11108
12439
  validateChanges: true,
11109
12440
  logChanges: true,
11110
12441
  agentName: params.agent.Name,
@@ -11233,9 +12564,14 @@ The context is now within limits. Please retry your request with the recovered c
11233
12564
  }
11234
12565
  })
11235
12566
  };
11236
- // Set PayloadAtEnd with the final payload after changes
12567
+ // Set PayloadAtEnd with the final payload after changes (reusing serialized start when payload was not modified)
11237
12568
  if (stepEntity && finalPayload) {
11238
- stepEntity.PayloadAtEnd = this.serializePayloadAtEnd(finalPayload);
12569
+ const canReuseStartPayload = !initialNextStep.payloadChangeRequest &&
12570
+ updatedNextStep.newPayload === undefined &&
12571
+ finalPayload === payload &&
12572
+ this.hasDefaultPayloadSerializers();
12573
+ stepEntity.PayloadAtEnd = (canReuseStartPayload ? this.resolveStepPayloadAtStart(stepEntity) : null)
12574
+ ?? this.serializePayloadAtEnd(finalPayload);
11239
12575
  }
11240
12576
  // Update the agent run's current payload
11241
12577
  if (this._agentRun && finalPayload) {
@@ -11257,12 +12593,10 @@ The context is now within limits. Please retry your request with the recovered c
11257
12593
  return { ...updatedNextStep, terminate: false, step: 'Retry' };
11258
12594
  }
11259
12595
  // For root agents, create a persistent AIAgentRequest so the request is
11260
- // tracked in the dashboard and can be responded to outside a conversation.
11261
- // This is done here because Chat decisions from executePromptStep terminate
11262
- // immediately and never reach executeChatStep in the main loop.
11263
- if (this._depth === 0) {
11264
- await this.createFeedbackRequest(params, stepEntity, updatedNextStep);
11265
- }
12596
+ // tracked in the dashboard and can be responded to outside a conversation (none
12597
+ // under an audience: raiseFeedbackRequest). This is done here because Chat decisions
12598
+ // from executePromptStep terminate immediately and never reach executeChatStep in the main loop.
12599
+ await this.raiseFeedbackRequest(params, stepEntity, updatedNextStep);
11266
12600
  return { ...updatedNextStep, terminate: true };
11267
12601
  }
11268
12602
  else if (updatedNextStep.step === 'Success' || updatedNextStep.step === 'Failed') {
@@ -11287,10 +12621,14 @@ The context is now within limits. Please retry your request with the recovered c
11287
12621
  // in this case, we have a failed prompt execution. In this situation, let's make sure our payload at end isn't adjusted as
11288
12622
  // that affects downstream things in the agent run
11289
12623
  // Preserve payload on error
11290
- const payload = stepEntity.PayloadAtEnd
11291
- ? JSON.parse(stepEntity.PayloadAtEnd)
12624
+ const existingEnd = this.resolveStepPayloadAtEnd(stepEntity);
12625
+ const payload = existingEnd
12626
+ ? JSON.parse(existingEnd)
11292
12627
  : (previousDecision?.newPayload || params.payload);
11293
- stepEntity.PayloadAtEnd = this.serializePayloadAtEnd(payload);
12628
+ stepEntity.PayloadAtEnd = existingEnd
12629
+ ?? (this.hasDefaultPayloadSerializers() ? this.resolveStepPayloadAtStart(stepEntity) : null)
12630
+ ?? this.serializePayloadAtEnd(payload);
12631
+ stepEntity.PayloadAtEndSourceStepID = null;
11294
12632
  // we had an error, don't throw the exception as that will kill our overall execution/run
11295
12633
  // instead return a helpful message in our return value that the parent loop can review and adjust
11296
12634
  const errString = error?.message || error || 'Unknown error';
@@ -11465,7 +12803,6 @@ The context is now within limits. Please retry your request with the recovered c
11465
12803
  subAgentName: subAgentRequest.name,
11466
12804
  message: subAgentRequest.message,
11467
12805
  terminateAfter: subAgentRequest.terminateAfter,
11468
- conversationMessages: params.conversationMessages,
11469
12806
  parentAgentHierarchy: this._agentHierarchy
11470
12807
  };
11471
12808
  // Get sub-agent entity to access payload paths. Prefer the entity the caller already
@@ -11503,7 +12840,6 @@ The context is now within limits. Please retry your request with the recovered c
11503
12840
  else {
11504
12841
  scopedPayload = subAgentPayloadOverride; // we received a payload override, use it
11505
12842
  }
11506
- stepEntity.PayloadAtStart = this.serializePayloadAtStart(previousDecision.newPayload);
11507
12843
  // Execute sub-agent with scoped payload
11508
12844
  // Child sub-agents don't use context messages (they inherit payload directly)
11509
12845
  const subAgentResult = await this.ExecuteSubAgent(params, subAgentRequest, subAgentEntity, stepEntity, scopedPayload, undefined, // No context message for child sub-agents
@@ -11517,8 +12853,14 @@ The context is now within limits. Please retry your request with the recovered c
11517
12853
  // The sub-agent returned a scoped payload, we need to wrap it back
11518
12854
  resultPayloadForMerge = this._payloadManager.reversePayloadScope(subAgentResult.payload, subAgentEntity.PayloadScope);
11519
12855
  }
12856
+ // When either the parent or a terminal child sub-agent declared behavior='create-new',
12857
+ // merge the child's result against a clean empty object so prior-turn keys never bleed in.
12858
+ const mergeTargetPayload = (previousDecision?.artifactDirective?.behavior === 'create-new'
12859
+ || (subAgentRequest.terminateAfter && subAgentResult.artifactDirective?.behavior === 'create-new'))
12860
+ ? {}
12861
+ : previousDecision.newPayload;
11520
12862
  // Merge upstream changes back into parent payload
11521
- const mergeResult = this._payloadManager.mergeUpstreamPayload(subAgentRequest.name, previousDecision.newPayload, resultPayloadForMerge, upstreamPaths, params.verbose === true || IsVerboseLoggingEnabled());
12863
+ const mergeResult = this._payloadManager.mergeUpstreamPayload(subAgentRequest.name, mergeTargetPayload, resultPayloadForMerge, upstreamPaths, params.verbose === true || IsVerboseLoggingEnabled());
11522
12864
  // update the merged payload with the result
11523
12865
  mergedPayload = mergeResult.result;
11524
12866
  // Track the merge operation to detect what changed
@@ -11590,9 +12932,16 @@ The context is now within limits. Please retry your request with the recovered c
11590
12932
  stepEntity.TargetLogID = subAgentResult.agentRun.ID;
11591
12933
  // Set the SubAgentRun property for hierarchical tracking (transient related object)
11592
12934
  stepEntity.SubAgentRun = subAgentResult.agentRun;
11593
- stepEntity.PayloadAtEnd = this.serializePayloadAtEnd(mergedPayload);
11594
12935
  // saving happens later by calling finalizeStepEntity()
11595
12936
  }
12937
+ // Set PayloadAtEnd once with the merged payload (reusing serialized start when sub-agent failed or payload was not replaced)
12938
+ if (stepEntity) {
12939
+ const canReuseStartPayload = mergedPayload === previousDecision?.newPayload &&
12940
+ !currentStepPayloadChangeResult &&
12941
+ this.hasDefaultPayloadSerializers();
12942
+ stepEntity.PayloadAtEnd = (canReuseStartPayload ? this.resolveStepPayloadAtStart(stepEntity) : null)
12943
+ ?? this.serializePayloadAtEnd(mergedPayload);
12944
+ }
11596
12945
  // Check for cancellation after sub-agent execution
11597
12946
  if (params.cancellationToken?.aborted) {
11598
12947
  await this.finalizeStepEntity(stepEntity, false, 'Cancelled during sub-agent execution');
@@ -11614,8 +12963,9 @@ The context is now within limits. Please retry your request with the recovered c
11614
12963
  this._fileOutputs.push(...subAgentResult.fileOutputs);
11615
12964
  this.logStatus(`📄 Collected ${subAgentResult.fileOutputs.length} file output(s) from sub-agent '${subAgentRequest.name}'`, true);
11616
12965
  }
11617
- // Determine if we should terminate after sub-agent
11618
- const shouldTerminate = subAgentRequest.terminateAfter;
12966
+ // Determine if we should terminate after sub-agent (including when the sub-agent parked on a durable workflow)
12967
+ const subAgentParkedOnWorkflow = subAgentResult.agentRun?.Status === 'Paused';
12968
+ const shouldTerminate = subAgentRequest.terminateAfter || subAgentParkedOnWorkflow;
11619
12969
  // Prepare output data
11620
12970
  const outputData = {
11621
12971
  subAgentResult: {
@@ -11649,14 +12999,35 @@ The context is now within limits. Please retry your request with the recovered c
11649
12999
  newPayload: mergedPayload, // Preserve sub-agent payload changes
11650
13000
  responseForm: subAgentResult.responseForm,
11651
13001
  actionableCommands: subAgentResult.actionableCommands,
11652
- automaticCommands: subAgentResult.automaticCommands
11653
- // artifactDirective is deliberately NOT carried across the parent/child
11654
- // boundary — see warnIfDiscardingSubAgentArtifactDirective.
13002
+ automaticCommands: subAgentResult.automaticCommands,
13003
+ artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective
11655
13004
  };
11656
13005
  // Validate through parent's ChatHandlingOption (if configured)
11657
13006
  // This ensures parent agents can override child Chat steps
11658
13007
  return await this.validateChatNextStep(params, chatStep, mergedPayload, this._agentRun, stepEntity);
11659
13008
  }
13009
+ // When a sub-agent (e.g. Workflow Planner) submits a durable task graph, its run parks
13010
+ // with Status === 'Paused'. Propagate the parked state to the parent run and terminate
13011
+ // immediately with the sub-agent's workflow launch message so the parent orchestrator
13012
+ // does not continue looping or re-invoking the sub-agent while the workflow runs.
13013
+ if (subAgentParkedOnWorkflow) {
13014
+ this._awaitingWorkflowTaskID = this.extractSubAgentWorkflowTaskID(subAgentResult.agentRun);
13015
+ if (this._agentRun) {
13016
+ this._agentRun.FinalPayloadObject = mergedPayload;
13017
+ }
13018
+ return {
13019
+ ...subAgentResult,
13020
+ step: 'Success',
13021
+ terminate: true,
13022
+ message: subAgentResult.agentRun?.Message || null,
13023
+ previousPayload: previousDecision?.newPayload,
13024
+ newPayload: mergedPayload,
13025
+ responseForm: subAgentResult.responseForm,
13026
+ actionableCommands: subAgentResult.actionableCommands,
13027
+ automaticCommands: subAgentResult.automaticCommands,
13028
+ artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective
13029
+ };
13030
+ }
11660
13031
  // Add user message with the sub-agent results using markdown format
11661
13032
  // and expiration metadata so it persists across multiple prompt turns
11662
13033
  const resultMessage = this.formatSubAgentResultAsMarkdown(subAgentRequest.name, subAgentResult);
@@ -11692,38 +13063,42 @@ The context is now within limits. Please retry your request with the recovered c
11692
13063
  else {
11693
13064
  params.conversationMessages.push({ role: 'user', content: resultMessage, metadata: subAgentMetadata });
11694
13065
  }
11695
- // Set PayloadAtEnd with the merged payload
11696
- if (stepEntity) {
11697
- stepEntity.PayloadAtEnd = this.serializePayloadAtEnd(mergedPayload);
11698
- }
11699
13066
  // Update the agent run's current payload with the merged result
11700
13067
  if (this._agentRun) {
11701
13068
  this._agentRun.FinalPayloadObject = mergedPayload;
11702
13069
  }
11703
- this.warnIfDiscardingSubAgentArtifactDirective(subAgentResult, subAgentRequest.name);
13070
+ if (previousDecision?.taskGraph?.folded === true && subAgentResult.artifactDirective) {
13071
+ this._lastSubAgentArtifactDirective = subAgentResult.artifactDirective;
13072
+ }
13073
+ else if (!previousDecision?.artifactDirective && !shouldTerminate) {
13074
+ this.warnIfDiscardingSubAgentArtifactDirective(subAgentResult, subAgentRequest.name);
13075
+ }
11704
13076
  return {
11705
13077
  ...subAgentResult,
11706
13078
  step: subAgentResult.success ? 'Success' : 'Failed',
11707
13079
  // Capture error message from sub-agent run for proper error propagation
11708
13080
  errorMessage: subAgentResult.success ? undefined : (subAgentResult.agentRun?.ErrorMessage || 'Sub-agent failed with no error message'),
13081
+ retryReason: subAgentResult.success
13082
+ ? `Reviewing results from ${subAgentRequest.name}`
13083
+ : `Handling error from ${subAgentRequest.name}`,
11709
13084
  terminate: shouldTerminate,
11710
13085
  previousPayload: previousDecision?.newPayload,
11711
13086
  newPayload: mergedPayload,
11712
- // An artifact directive describes the payload of the agent that ISSUED it. What the
11713
- // parent returns here is `mergedPayload` — its own payload with the child's changes
11714
- // folded in — so letting the spread above carry the child's directive through would
11715
- // persist the PARENT's payload onto an artifact the CHILD named, silently and with no
11716
- // way for the parent to opt out. Dropped explicitly, which also matches the Chat
11717
- // mapping in this method and `executeChatStep`: neither ever carried it.
11718
- artifactDirective: undefined
13087
+ // Preserve the parent's own directive on this Sub-Agent step, or when the sub-agent
13088
+ // terminates the parent run directly (shouldTerminate=true), carry the terminal
13089
+ // sub-agent's directive if the parent did not specify one.
13090
+ artifactDirective: previousDecision?.artifactDirective
13091
+ ?? (shouldTerminate ? subAgentResult.artifactDirective : undefined)
11719
13092
  };
11720
13093
  }
11721
13094
  catch (error) {
11722
13095
  // Preserve payload on error
11723
- const payload = stepEntity.PayloadAtEnd
11724
- ? JSON.parse(stepEntity.PayloadAtEnd)
13096
+ const existingEnd = this.resolveStepPayloadAtEnd(stepEntity);
13097
+ const payload = existingEnd
13098
+ ? JSON.parse(existingEnd)
11725
13099
  : (previousDecision?.newPayload || params.payload);
11726
13100
  stepEntity.PayloadAtEnd = this.serializePayloadAtEnd(payload);
13101
+ stepEntity.PayloadAtEndSourceStepID = null;
11727
13102
  await this.finalizeStepEntity(stepEntity, false, error.message);
11728
13103
  // we had an error, don't throw the exception as that will kill our overall execution/run
11729
13104
  // instead retrun a helpful message in our return value that the parent loop can review and
@@ -11737,6 +13112,33 @@ The context is now within limits. Please retry your request with the recovered c
11737
13112
  };
11738
13113
  }
11739
13114
  }
13115
+ /**
13116
+ * Extracts the workflow root task ID (`parentTaskID`) from a sub-agent run that parked on a
13117
+ * durable task graph (`Status === 'Paused'`), falling back to the sub-agent run ID so the
13118
+ * parent run's `_awaitingWorkflowTaskID` is guaranteed non-null when parking.
13119
+ *
13120
+ * @protected
13121
+ */
13122
+ extractSubAgentWorkflowTaskID(subAgentRun) {
13123
+ if (subAgentRun?.Steps) {
13124
+ for (let i = subAgentRun.Steps.length - 1; i >= 0; i--) {
13125
+ const rawOutput = subAgentRun.Steps[i]?.OutputData;
13126
+ if (!rawOutput)
13127
+ continue;
13128
+ try {
13129
+ const parsed = JSON.parse(rawOutput);
13130
+ const candidate = parsed.parentTaskID ?? parsed.parentTaskId;
13131
+ if (typeof candidate === 'string' && candidate.length > 0) {
13132
+ return candidate;
13133
+ }
13134
+ }
13135
+ catch {
13136
+ // Ignore non-JSON step output
13137
+ }
13138
+ }
13139
+ }
13140
+ return subAgentRun?.ID || 'sub-agent-workflow';
13141
+ }
11740
13142
  /**
11741
13143
  * Routes sub-agent execution to the appropriate handler based on relationship type.
11742
13144
  * Child agents (ParentID) use direct payload coupling.
@@ -11765,7 +13167,7 @@ The context is now within limits. Please retry your request with the recovered c
11765
13167
  newPayload: previousDecision.newPayload
11766
13168
  };
11767
13169
  }
11768
- const resolved = this.resolveSubAgentByName(params, name);
13170
+ const resolved = this.resolveSubAgentByName(params, name, previousDecision.taskGraph?.folded === true);
11769
13171
  if (resolved?.relationship) {
11770
13172
  return await this.executeRelatedSubAgentStep(params, previousDecision, resolved.subAgentEntity, resolved.relationship, parentStepId, subAgentPayloadOverride, stepCount);
11771
13173
  }
@@ -11806,7 +13208,7 @@ The context is now within limits. Please retry your request with the recovered c
11806
13208
  *
11807
13209
  * @protected
11808
13210
  */
11809
- resolveSubAgentByName(params, name) {
13211
+ resolveSubAgentByName(params, name, allowAnyActiveAgent = false) {
11810
13212
  const normalized = name.trim().toLowerCase();
11811
13213
  const childAgent = AIEngine.Instance.Agents.find(a => UUIDsEqual(a.ParentID, params.agent.ID) &&
11812
13214
  a.Status === 'Active' &&
@@ -11833,6 +13235,16 @@ The context is now within limits. Please retry your request with the recovered c
11833
13235
  if (effectiveAgent) {
11834
13236
  return { subAgentEntity: effectiveAgent };
11835
13237
  }
13238
+ // 4) Single-node constant-folded task graphs (D9): an orchestrator (e.g. Sage) may discover
13239
+ // any active peer agent via Find Candidate Agents and delegate a 1-node Tasks graph to it.
13240
+ // LoopAgentType folds that 1-node graph into an in-run Sub-Agent step (`taskGraph.folded === true`),
13241
+ // so allow resolving any active agent in AIEngine.Instance.Agents.
13242
+ if (allowAnyActiveAgent) {
13243
+ const anyActiveAgent = AIEngine.Instance.Agents.find(a => a.Status === 'Active' && a.Name.trim().toLowerCase() === normalized);
13244
+ if (anyActiveAgent) {
13245
+ return { subAgentEntity: anyActiveAgent };
13246
+ }
13247
+ }
11836
13248
  return undefined;
11837
13249
  }
11838
13250
  /**
@@ -12082,7 +13494,6 @@ The context is now within limits. Please retry your request with the recovered c
12082
13494
  subAgentName: request.name,
12083
13495
  message: request.message,
12084
13496
  terminateAfter: request.terminateAfter,
12085
- conversationMessages: params.conversationMessages,
12086
13497
  parentAgentHierarchy: this._agentHierarchy,
12087
13498
  relationshipType: relationship ? 'related' : 'child'
12088
13499
  },
@@ -12208,8 +13619,12 @@ The context is now within limits. Please retry your request with the recovered c
12208
13619
  // success/failure. The parent's step reflects whether any child failed:
12209
13620
  // Failed if any did, Success if terminating cleanly, otherwise Retry.
12210
13621
  const shouldTerminateParent = allExecutions.some(e => e.request.terminateAfter === true);
13622
+ const subAgentNames = allExecutions.map(e => e.request.name).join(', ');
12211
13623
  return {
12212
13624
  step: anyFailure ? 'Failed' : (shouldTerminateParent ? 'Success' : 'Retry'),
13625
+ retryReason: anyFailure
13626
+ ? `Reviewing results and errors from ${subAgentNames}`
13627
+ : `Reviewing results from ${subAgentNames}`,
12213
13628
  terminate: shouldTerminateParent,
12214
13629
  newPayload: mergedPayload,
12215
13630
  previousPayload: previousDecision.newPayload
@@ -12262,7 +13677,6 @@ The context is now within limits. Please retry your request with the recovered c
12262
13677
  subAgentName: subAgentRequest.name,
12263
13678
  message: subAgentRequest.message,
12264
13679
  terminateAfter: subAgentRequest.terminateAfter,
12265
- conversationMessages: params.conversationMessages,
12266
13680
  parentAgentHierarchy: this._agentHierarchy,
12267
13681
  relationshipType: 'related'
12268
13682
  };
@@ -12282,7 +13696,6 @@ The context is now within limits. Please retry your request with the recovered c
12282
13696
  // Related agents can receive parent data in two ways:
12283
13697
  // 1. SubAgentInputMapping: Maps parent payload → sub-agent payload (structural data)
12284
13698
  // 2. SubAgentContextPaths: Parent payload → sub-agent conversation context (LLM awareness)
12285
- stepEntity.PayloadAtStart = this.serializePayloadAtStart(previousDecision.newPayload);
12286
13699
  // Prepare initial payload via input mapping (if configured)
12287
13700
  let initialSubAgentPayload = subAgentPayloadOverride;
12288
13701
  if (!initialSubAgentPayload && relationship.SubAgentInputMapping) {
@@ -12349,8 +13762,9 @@ The context is now within limits. Please retry your request with the recovered c
12349
13762
  }
12350
13763
  }
12351
13764
  }
12352
- // Check if we should terminate after this sub-agent
12353
- const shouldTerminate = subAgentRequest.terminateAfter === true;
13765
+ // Check if we should terminate after this sub-agent (including when the sub-agent parked on a durable workflow)
13766
+ const subAgentParkedOnWorkflow = subAgentResult.agentRun?.Status === 'Paused';
13767
+ const shouldTerminate = subAgentRequest.terminateAfter === true || subAgentParkedOnWorkflow;
12354
13768
  // Prepare output data
12355
13769
  const outputData = {
12356
13770
  subAgentResult: {
@@ -12384,14 +13798,34 @@ The context is now within limits. Please retry your request with the recovered c
12384
13798
  newPayload: mergedPayload, // Preserve sub-agent payload changes
12385
13799
  responseForm: subAgentResult.responseForm,
12386
13800
  actionableCommands: subAgentResult.actionableCommands,
12387
- automaticCommands: subAgentResult.automaticCommands
12388
- // artifactDirective is deliberately NOT carried across the parent/child
12389
- // boundary — see warnIfDiscardingSubAgentArtifactDirective.
13801
+ automaticCommands: subAgentResult.automaticCommands,
13802
+ artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective
12390
13803
  };
12391
13804
  // Validate through parent's ChatHandlingOption (if configured)
12392
13805
  // This ensures parent agents can override child Chat steps
12393
13806
  return await this.validateChatNextStep(params, chatStep, mergedPayload, this._agentRun, stepEntity);
12394
13807
  }
13808
+ // When a related sub-agent submits a durable task graph, its run parks with Status === 'Paused'.
13809
+ // Propagate the parked state to the parent run and terminate immediately with the sub-agent's
13810
+ // workflow launch message instead of continuing the parent loop.
13811
+ if (subAgentParkedOnWorkflow) {
13812
+ this._awaitingWorkflowTaskID = this.extractSubAgentWorkflowTaskID(subAgentResult.agentRun);
13813
+ if (this._agentRun) {
13814
+ this._agentRun.FinalPayloadObject = mergedPayload;
13815
+ }
13816
+ return {
13817
+ ...subAgentResult,
13818
+ step: 'Success',
13819
+ terminate: true,
13820
+ message: subAgentResult.agentRun?.Message || null,
13821
+ previousPayload: previousDecision?.newPayload,
13822
+ newPayload: mergedPayload,
13823
+ responseForm: subAgentResult.responseForm,
13824
+ actionableCommands: subAgentResult.actionableCommands,
13825
+ automaticCommands: subAgentResult.automaticCommands,
13826
+ artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective
13827
+ };
13828
+ }
12395
13829
  // Add sub-agent result to conversation as user message using markdown format
12396
13830
  // and expiration metadata so it persists across multiple prompt turns
12397
13831
  const relatedResultMessage = this.formatSubAgentResultAsMarkdown(subAgentRequest.name, subAgentResult);
@@ -12433,30 +13867,32 @@ The context is now within limits. Please retry your request with the recovered c
12433
13867
  if (this._agentRun) {
12434
13868
  this._agentRun.FinalPayloadObject = mergedPayload;
12435
13869
  }
12436
- this.warnIfDiscardingSubAgentArtifactDirective(subAgentResult, subAgentRequest.name);
13870
+ if (!previousDecision?.artifactDirective && !shouldTerminate) {
13871
+ this.warnIfDiscardingSubAgentArtifactDirective(subAgentResult, subAgentRequest.name);
13872
+ }
12437
13873
  return {
12438
13874
  ...subAgentResult,
12439
13875
  step: subAgentResult.success ? 'Success' : 'Failed',
12440
13876
  // Capture error message from sub-agent run for proper error propagation
12441
13877
  errorMessage: subAgentResult.success ? undefined : (subAgentResult.agentRun?.ErrorMessage || 'Related sub-agent failed with no error message'),
13878
+ retryReason: subAgentResult.success
13879
+ ? `Reviewing results from ${subAgentRequest.name}`
13880
+ : `Handling error from ${subAgentRequest.name}`,
12442
13881
  terminate: shouldTerminate,
12443
13882
  previousPayload: previousDecision?.newPayload,
12444
13883
  newPayload: mergedPayload,
12445
- // An artifact directive describes the payload of the agent that ISSUED it. What the
12446
- // parent returns here is `mergedPayload` — its own payload with the child's changes
12447
- // folded in — so letting the spread above carry the child's directive through would
12448
- // persist the PARENT's payload onto an artifact the CHILD named, silently and with no
12449
- // way for the parent to opt out. Dropped explicitly, which also matches the Chat
12450
- // mapping in this method and `executeChatStep`: neither ever carried it.
12451
- artifactDirective: undefined
13884
+ artifactDirective: previousDecision?.artifactDirective
13885
+ ?? (shouldTerminate ? subAgentResult.artifactDirective : undefined)
12452
13886
  };
12453
13887
  }
12454
13888
  catch (error) {
12455
13889
  // Preserve payload on error
12456
- const payload = stepEntity.PayloadAtEnd
12457
- ? JSON.parse(stepEntity.PayloadAtEnd)
13890
+ const existingEnd = this.resolveStepPayloadAtEnd(stepEntity);
13891
+ const payload = existingEnd
13892
+ ? JSON.parse(existingEnd)
12458
13893
  : (previousDecision?.newPayload || params.payload);
12459
13894
  stepEntity.PayloadAtEnd = this.serializePayloadAtEnd(payload);
13895
+ stepEntity.PayloadAtEndSourceStepID = null;
12460
13896
  await this.finalizeStepEntity(stepEntity, false, error.message);
12461
13897
  return {
12462
13898
  errorMessage: `Related sub-agent execution failed: ${error.message}`,
@@ -12956,8 +14392,17 @@ The context is now within limits. Please retry your request with the recovered c
12956
14392
  });
12957
14393
  finalPayload = changeResult.result;
12958
14394
  if (lastStep) {
12959
- lastStep.PayloadAtEnd = this.serializePayloadAtEnd(finalPayload);
12960
- await lastStep.Save();
14395
+ const serializedEnd = this.serializePayloadAtEnd(finalPayload);
14396
+ const endSource = this.findPayloadAtEndSource(serializedEnd, lastStep);
14397
+ const payloadAtEnd = endSource ? null : serializedEnd;
14398
+ const payloadAtEndSourceStepId = endSource ? endSource.ID : null;
14399
+ lastStep.PayloadAtEnd = payloadAtEnd;
14400
+ lastStep.PayloadAtEndSourceStepID = payloadAtEndSourceStepId;
14401
+ // Queued behind the step's earlier saves, so the saved row ends with this end.
14402
+ this.queueStepSave(lastStep, (s) => {
14403
+ s.PayloadAtEnd = payloadAtEnd;
14404
+ s.PayloadAtEndSourceStepID = payloadAtEndSourceStepId;
14405
+ });
12961
14406
  }
12962
14407
  if (changeResult.warnings.length > 0 && (params.verbose === true || IsVerboseLoggingEnabled())) {
12963
14408
  LogStatus(`Action post-processing payload warnings: ${changeResult.warnings.join('; ')}`);
@@ -12974,6 +14419,8 @@ The context is now within limits. Please retry your request with the recovered c
12974
14419
  // After actions complete, we need to process the results
12975
14420
  // The retry step is used to re-execute the prompt with the action results
12976
14421
  // This allows the agent to analyze the results and determine what to do next
14422
+ const failedNoun = failedActions.length === 1 ? 'action' : 'actions';
14423
+ const completedNoun = actionSummaries.length === 1 ? 'action' : 'actions';
12977
14424
  return {
12978
14425
  terminate: false,
12979
14426
  step: 'Retry',
@@ -12981,8 +14428,8 @@ The context is now within limits. Please retry your request with the recovered c
12981
14428
  newPayload: finalPayload, // Use the final payload after any post-processing
12982
14429
  priorStepResult: actionSummaries,
12983
14430
  retryReason: failedActions.length > 0
12984
- ? `Processing results with ${failedActions.length} failed action(s): ${failedActions.map(a => a.actionName).join(', ')}`
12985
- : `Analyzing results from ${actionSummaries.length} completed action(s) to formulate response`
14431
+ ? `Processing results with ${failedActions.length} failed ${failedNoun}: ${failedActions.map(a => a.actionName).join(', ')}`
14432
+ : `Analyzing results from ${actionSummaries.length} completed ${completedNoun}`
12986
14433
  };
12987
14434
  }
12988
14435
  catch (e) {
@@ -13010,12 +14457,24 @@ The context is now within limits. Please retry your request with the recovered c
13010
14457
  // ================================================================
13011
14458
  // Client Tools Step Execution
13012
14459
  // ================================================================
14460
+ /** The assistant message describing a client-tools step's invocations. */
14461
+ describeClientToolInvocations(clientTools) {
14462
+ return clientTools.length === 1
14463
+ ? `I'm invoking the **${clientTools[0].Name}** client tool${clientTools[0].Description ? ` — ${clientTools[0].Description}` : ''}.`
14464
+ : `I'm invoking **${clientTools.length} client tools**:\n\n` +
14465
+ clientTools.map((t, i) => `${i + 1}. **${t.Name}**${t.Description ? ` — ${t.Description}` : ''}`).join('\n');
14466
+ }
13013
14467
  /**
13014
14468
  * Execute client-side tools requested by the agent.
13015
14469
  * Sends each tool invocation via PubSub, awaits the client's response
13016
14470
  * (or timeout), then adds results to the conversation and continues.
14471
+ * Refused under an audience ({@link clientToolsRefusal}).
13017
14472
  */
13018
14473
  async executeClientToolsStep(params, config, previousDecision, stepCount = 0) {
14474
+ const refused = this.clientToolsRefusal(params, previousDecision);
14475
+ if (refused) {
14476
+ return refused;
14477
+ }
13019
14478
  const clientTools = previousDecision.clientTools ?? [];
13020
14479
  if (clientTools.length === 0) {
13021
14480
  // No tools to execute — continue with next prompt
@@ -13032,11 +14491,7 @@ The context is now within limits. Please retry your request with the recovered c
13032
14491
  return await this.executePromptStep(params, config, previousDecision, stepCount);
13033
14492
  }
13034
14493
  const currentPayload = previousDecision?.newPayload || previousDecision?.previousPayload || params.payload;
13035
- // Build assistant message describing the tool invocations
13036
- const toolMessage = clientTools.length === 1
13037
- ? `I'm invoking the **${clientTools[0].Name}** client tool${clientTools[0].Description ? ` — ${clientTools[0].Description}` : ''}.`
13038
- : `I'm invoking **${clientTools.length} client tools**:\n\n` +
13039
- clientTools.map((t, i) => `${i + 1}. **${t.Name}**${t.Description ? ` — ${t.Description}` : ''}`).join('\n');
14494
+ const toolMessage = this.describeClientToolInvocations(clientTools);
13040
14495
  params.conversationMessages.push({
13041
14496
  role: 'assistant',
13042
14497
  content: toolMessage
@@ -13680,6 +15135,11 @@ The context is now within limits. Please retry your request with the recovered c
13680
15135
  newPayload: previousDecision.newPayload || previousDecision.previousPayload
13681
15136
  };
13682
15137
  }
15138
+ // Fail closed under an audience or a tenant-scoped run (taskGraphRefusal): a graph runs outside the run's gates.
15139
+ const withheld = this.taskGraphRefusal(params, previousDecision);
15140
+ if (withheld) {
15141
+ return withheld;
15142
+ }
13683
15143
  const stepEntity = await this.createStepEntity({
13684
15144
  stepType: 'TaskGraph',
13685
15145
  stepName: `Task Graph: ${spec.workflowName}`,
@@ -13798,10 +15258,8 @@ The context is now within limits. Please retry your request with the recovered c
13798
15258
  responseForm
13799
15259
  };
13800
15260
  // For root agents, create a persistent AIAgentRequest so the request is tracked in the
13801
- // dashboard and can be responded to outside a conversation (mirrors executeChatStep).
13802
- if (this._depth === 0) {
13803
- await this.createFeedbackRequest(params, stepEntity, planPresentation);
13804
- }
15261
+ // dashboard and can be responded to outside a conversation (mirrors executeChatStep; none under an audience).
15262
+ await this.raiseFeedbackRequest(params, stepEntity, planPresentation);
13805
15263
  return {
13806
15264
  step: 'Chat',
13807
15265
  terminate: true,
@@ -13869,10 +15327,8 @@ The context is now within limits. Please retry your request with the recovered c
13869
15327
  // Chat steps are successful - they indicate a need for user interaction
13870
15328
  await this.finalizeStepEntity(stepEntity, true);
13871
15329
  // For root agents, create a persistent AIAgentRequest so the request is
13872
- // tracked in the dashboard and can be responded to outside a conversation.
13873
- if (this._depth === 0) {
13874
- await this.createFeedbackRequest(params, stepEntity, previousDecision);
13875
- }
15330
+ // tracked in the dashboard and can be responded to outside a conversation (none under an audience).
15331
+ await this.raiseFeedbackRequest(params, stepEntity, previousDecision);
13876
15332
  return {
13877
15333
  step: 'Chat',
13878
15334
  terminate: true,
@@ -13891,6 +15347,24 @@ The context is now within limits. Please retry your request with the recovered c
13891
15347
  artifactDirective: previousDecision.artifactDirective
13892
15348
  };
13893
15349
  }
15350
+ /**
15351
+ * Raises the persistent `MJ: AI Agent Requests` row for a root agent's Chat or Plan step ({@link createFeedbackRequest}),
15352
+ * so it can be answered outside the conversation — except when the run's audience adds a reader. A request answered
15353
+ * on the dashboard or through the API resumes the run (`MJAIAgentRequestEntityServer.resumeAgent`) as the responder,
15354
+ * in the original conversation, with no audience: neither the request nor the run row has a field that can carry
15355
+ * one without a new column. So a shared conversation's run raises none: its question or plan still reaches the room,
15356
+ * which answers in the conversation, where the host starts the next run with the room's audience.
15357
+ */
15358
+ async raiseFeedbackRequest(params, stepEntity, decision) {
15359
+ if (this._depth !== 0) {
15360
+ return;
15361
+ }
15362
+ if (this.runAudienceAddsReader(params)) {
15363
+ this.logStatus('📋 No feedback request raised: the run has an audience, so it is answered in the conversation, not resumed', true, params);
15364
+ return;
15365
+ }
15366
+ await this.createFeedbackRequest(params, stepEntity, decision);
15367
+ }
13894
15368
  /**
13895
15369
  * Creates a persistent AIAgentRequest row when a Chat step fires.
13896
15370
  * Resolves the target user via the assignment chain:
@@ -14782,19 +16256,42 @@ The context is now within limits. Please retry your request with the recovered c
14782
16256
  };
14783
16257
  }
14784
16258
  /**
14785
- * Creates a failure result with proper tracking.
16259
+ * Flushes any in-flight `MJAIPromptRunEntityExtended` saves queued on {@link _promptRunner}.
16260
+ * Tolerates lightweight test doubles on `_promptRunner` that may only implement
16261
+ * `WaitForPendingPromptRunSaves` or neither method.
16262
+ *
16263
+ * @private
16264
+ */
16265
+ async flushPromptRunnerSaves() {
16266
+ const runner = this._promptRunner;
16267
+ if (typeof runner?.FlushPendingSaves === 'function') {
16268
+ await runner.FlushPendingSaves();
16269
+ }
16270
+ else if (typeof runner?.WaitForPendingPromptRunSaves === 'function') {
16271
+ await runner.WaitForPendingPromptRunSaves();
16272
+ }
16273
+ }
16274
+ /**
16275
+ * Creates a failure result with proper tracking, draining all queued step and prompt-run saves
16276
+ * before persisting the failed run row so no orphan step or prompt-run writes remain in flight.
14786
16277
  *
14787
16278
  * @private
14788
16279
  */
14789
16280
  async createFailureResult(errorMessage, contextUser) {
16281
+ const [{ failures }] = await Promise.all([
16282
+ this._stepSaveQueue.Flush(),
16283
+ this.flushPromptRunnerSaves(),
16284
+ ]);
14790
16285
  if (this._agentRun) {
14791
16286
  this._agentRun.Status = 'Failed';
14792
16287
  this._agentRun.CompletedAt = new Date();
14793
16288
  this._agentRun.Success = false;
14794
- this._agentRun.ErrorMessage = errorMessage;
16289
+ this._agentRun.ErrorMessage = failures > 0
16290
+ ? `${errorMessage}\n${failures} step record save(s) failed during this run; see logs for details.`
16291
+ : errorMessage;
14795
16292
  // Calculate total tokens even for failed runs
14796
16293
  this.applyTokenStatsToRun(this._agentRun, this.calculateTokenStats());
14797
- await this._agentRun.Save();
16294
+ await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
14798
16295
  }
14799
16296
  return {
14800
16297
  success: false,
@@ -14802,18 +16299,25 @@ The context is now within limits. Please retry your request with the recovered c
14802
16299
  };
14803
16300
  }
14804
16301
  /**
14805
- * Creates a cancelled result.
16302
+ * Creates a cancelled result, draining all queued step and prompt-run saves before persisting
16303
+ * the cancelled run row so no orphan step or prompt-run writes remain in flight.
14806
16304
  *
14807
16305
  * @private
14808
16306
  * @param {string} message - The cancellation message
14809
16307
  * @returns {Promise<ExecuteAgentResult>} The cancelled result
14810
16308
  */
14811
16309
  async createCancelledResult(message, contextUser) {
16310
+ const [{ failures }] = await Promise.all([
16311
+ this._stepSaveQueue.Flush(),
16312
+ this.flushPromptRunnerSaves(),
16313
+ ]);
14812
16314
  if (this._agentRun) {
14813
16315
  this._agentRun.Status = 'Cancelled';
14814
16316
  this._agentRun.CompletedAt = new Date();
14815
16317
  this._agentRun.Success = false;
14816
- this._agentRun.ErrorMessage = message;
16318
+ this._agentRun.ErrorMessage = failures > 0
16319
+ ? `${message}\n${failures} step record save(s) failed during this run; see logs for details.`
16320
+ : message;
14817
16321
  // Save() writes every column, so an in-memory null here would overwrite the reason the
14818
16322
  // Stop button wrote on the row. Record the reason the abort signal carried instead. The
14819
16323
  // signal is consulted first because most call sites pass a fixed message naming WHERE
@@ -14831,7 +16335,7 @@ The context is now within limits. Please retry your request with the recovered c
14831
16335
  }
14832
16336
  // Calculate total tokens even for cancelled runs
14833
16337
  this.applyTokenStatsToRun(this._agentRun, this.calculateTokenStats());
14834
- await this._agentRun.Save();
16338
+ await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
14835
16339
  AgentRunWatchdog.Instance.Untrack(this._agentRun.ID);
14836
16340
  }
14837
16341
  return {
@@ -14864,19 +16368,33 @@ The context is now within limits. Please retry your request with the recovered c
14864
16368
  return null;
14865
16369
  }
14866
16370
  const ordered = [...steps].sort((a, b) => (b.StepNumber ?? 0) - (a.StepNumber ?? 0));
14867
- const withPayload = ordered.find(s => typeof s.PayloadAtEnd === 'string' && s.PayloadAtEnd.length > 0);
14868
- return withPayload?.PayloadAtEnd ?? null;
16371
+ for (const s of ordered) {
16372
+ if (typeof s.PayloadAtEnd === 'string' && s.PayloadAtEnd.length > 0) {
16373
+ return s.PayloadAtEnd;
16374
+ }
16375
+ if (s.PayloadAtEndSourceStepID && s.ID) {
16376
+ const stepsWithIds = steps.filter((item) => typeof item.ID === 'string' && item.ID.length > 0);
16377
+ const resolved = ResolvePayloadAtEnd(s, IndexByUUID(stepsWithIds));
16378
+ if (typeof resolved === 'string' && resolved.length > 0) {
16379
+ return resolved;
16380
+ }
16381
+ }
16382
+ }
16383
+ return null;
14869
16384
  }
14870
16385
  /**
14871
16386
  * Finalizes the agent run with success.
14872
16387
  *
14873
- * @private
16388
+ * @protected
14874
16389
  */
14875
16390
  async finalizeAgentRun(finalStep, payload, contextUser) {
14876
- // Flush every pending step save (success OR failure) via the shared queue, which allSettles so a
14877
- // single failure doesn't shadow the rest and drains itself so a reused instance doesn't leak
14878
- // settled promises. Surface the failure count on the run for visibility.
14879
- const { failures } = await this._stepSaveQueue.Flush();
16391
+ // Flush every pending step save AND prompt-run save (success OR failure) via their shared queues,
16392
+ // which allSettle so a single failure doesn't shadow the rest and drain themselves so a reused
16393
+ // instance doesn't leak settled promises. Surface the step failure count on the run for visibility.
16394
+ const [{ failures }] = await Promise.all([
16395
+ this._stepSaveQueue.Flush(),
16396
+ this.flushPromptRunnerSaves(),
16397
+ ]);
14880
16398
  if (failures > 0 && this._agentRun) {
14881
16399
  const note = `${failures} step record save(s) failed during this run; see logs for details.`;
14882
16400
  this._agentRun.ErrorMessage = this._agentRun.ErrorMessage
@@ -14936,10 +16454,8 @@ The context is now within limits. Please retry your request with the recovered c
14936
16454
  else {
14937
16455
  this._agentRun.Status = 'Completed';
14938
16456
  }
14939
- // Serialize the (largest-it-ever-gets) final payload ONCE and reuse for both
14940
- // Result and FinalPayload instead of stringifying the same object three times.
16457
+ // Serialize the (largest-it-ever-gets) final payload once for FinalPayload.
14941
16458
  const finalPayloadJson = resolvedPayload ? JSON.stringify(resolvedPayload) : null;
14942
- this._agentRun.Result = finalPayloadJson;
14943
16459
  this._agentRun.FinalStep = finalStep.step;
14944
16460
  this._agentRun.Message = finalStep.message;
14945
16461
  // Set the FinalPayloadObject (populates the object cache; its setter also writes
@@ -14949,7 +16465,7 @@ The context is now within limits. Please retry your request with the recovered c
14949
16465
  this._agentRun.FinalPayload = finalPayloadJson;
14950
16466
  // Calculate total tokens from all prompts and sub-agents
14951
16467
  this.applyTokenStatsToRun(this._agentRun, this.calculateTokenStats());
14952
- const ok = await this._agentRun.Save();
16468
+ const ok = await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
14953
16469
  if (!ok) {
14954
16470
  LogError(`Failed to finalize agent run ${this._agentRun.ID}`);
14955
16471
  }
@@ -14963,11 +16479,37 @@ The context is now within limits. Please retry your request with the recovered c
14963
16479
  // completion event. Errors are contained — a failed pass leaves the conversation
14964
16480
  // untouched and simply re-triggers on a later turn.
14965
16481
  this.startPostTurnCompaction();
16482
+ // Post-run conversation message pre-compaction, scratchpad pruning, and memory
16483
+ // extraction (when ExecuteAgentParams.compactAfterRun is enabled). Runs AFTER
16484
+ // _stepSaveQueue.Flush() and _agentRun.Save() inside a defensive try/catch so any
16485
+ // error in post-run maintenance is logged gracefully without turning a successful
16486
+ // agent run into a failure.
16487
+ if (this._executeParams) {
16488
+ try {
16489
+ await this.runPostRunCompaction(this._executeParams, this._agentRun);
16490
+ }
16491
+ catch (compactionError) {
16492
+ LogError(`Post-run compaction error for agent run ${this._agentRun.ID} (contained): ` +
16493
+ `${compactionError instanceof Error ? compactionError.message : String(compactionError)}`);
16494
+ }
16495
+ }
14966
16496
  }
14967
16497
  // Also promote any media from the final step's promoteMediaOutputs
14968
16498
  if (finalStep.promoteMediaOutputs && finalStep.promoteMediaOutputs.length > 0) {
14969
16499
  this.PromoteMediaOutputs(finalStep.promoteMediaOutputs);
14970
16500
  }
16501
+ // Resolve manifest alpha IDs (e.g. "A", "B") or version IDs in artifactDirective.targetArtifactId
16502
+ // to the underlying MJ: Artifacts record UUID before returning.
16503
+ let resolvedArtifactDirective = finalStep.artifactDirective ?? this._lastSubAgentArtifactDirective;
16504
+ if (resolvedArtifactDirective?.targetArtifactId) {
16505
+ const resolvedUuid = this._artifactToolManager.ResolveArtifactUuid(resolvedArtifactDirective.targetArtifactId);
16506
+ if (resolvedUuid) {
16507
+ resolvedArtifactDirective = {
16508
+ ...resolvedArtifactDirective,
16509
+ targetArtifactId: resolvedUuid
16510
+ };
16511
+ }
16512
+ }
14971
16513
  // Return unified media outputs — all items are persisted by AgentRunner.
14972
16514
  // Sub-agents pass their mediaOutputs to parent for merging and placeholder resolution.
14973
16515
  return {
@@ -14977,7 +16519,7 @@ The context is now within limits. Please retry your request with the recovered c
14977
16519
  responseForm: finalStep.responseForm,
14978
16520
  actionableCommands: resolvedActionableCommands,
14979
16521
  automaticCommands: finalStep.automaticCommands,
14980
- artifactDirective: finalStep.artifactDirective,
16522
+ artifactDirective: resolvedArtifactDirective,
14981
16523
  memoryContext: this._injectedMemory.notes.length > 0 || this._injectedMemory.examples.length > 0
14982
16524
  ? this._injectedMemory
14983
16525
  : undefined,
@@ -15441,10 +16983,15 @@ The context is now within limits. Please retry your request with the recovered c
15441
16983
  });
15442
16984
  if (outcome.PromptRun) {
15443
16985
  stepEntity.PromptRun = outcome.PromptRun;
16986
+ this.recordPromptUsageInTreeBudget(outcome.PromptRun, undefined, params);
15444
16987
  }
15445
16988
  if (phase === 'post-turn') {
15446
- // finalizeAgentRun's flush has already run — drain this step's INSERT now.
15447
- await this._stepSaveQueue.Flush();
16989
+ // finalizeAgentRun's flush has already run — drain this step's INSERT and the summary
16990
+ // prompt run's save now.
16991
+ await Promise.all([
16992
+ this._stepSaveQueue.Flush(),
16993
+ this.flushPromptRunnerSaves(),
16994
+ ]);
15448
16995
  await this.topUpRunTokenTotalsAfterPostTurnCompaction(outcome, params.contextUser);
15449
16996
  }
15450
16997
  }
@@ -15514,6 +17061,219 @@ The context is now within limits. Please retry your request with the recovered c
15514
17061
  messages.length = 0;
15515
17062
  messages.push(...retained);
15516
17063
  }
17064
+ /**
17065
+ * Executes post-run conversation message pre-compaction, scratchpad pruning, and
17066
+ * asynchronous memory extraction after an agent run completes (`finalizeAgentRun`).
17067
+ *
17068
+ * Shifting compaction and maintenance to the end of `finalizeAgentRun` removes
17069
+ * compaction latency from the next user turn's critical path so subsequent turns
17070
+ * start with a pre-compacted message window.
17071
+ *
17072
+ * ### Lifecycle Phases
17073
+ * 1. **Configuration Resolution**: Reads `params.compactAfterRun` (`boolean | AgentPostRunCompactionConfig`).
17074
+ * When `undefined`, `false`, or `{ enabled: false }`, returns immediately as a no-op.
17075
+ * When `true`, applies defaults `{ enabled: true, messageCountThreshold: 20, extractMemories: true }`.
17076
+ * 2. **Message Window Pre-Compaction**: When `params.conversationMessages.length >= messageCountThreshold`,
17077
+ * compacts older messages in `[1 .. length - preserveRecentCount - 1]` while preserving
17078
+ * the initial goal message (`index 0`) and the most recent messages intact. Delegates to
17079
+ * {@link compactMessage} (and {@link CompactToolResultContent} for native tool turns) so
17080
+ * behavior and expansion metadata (`wasCompacted`, `originalContent`, `canExpand`) are
17081
+ * 100% consistent with mid-run message compaction.
17082
+ * 3. **Scratchpad Pruning**: When `maxScratchpadNotes` is configured, prunes excess low-priority
17083
+ * scratchpad note lines (via {@link ScratchpadManager.PruneNotes}) and completed tasks
17084
+ * (via {@link ScratchpadManager.EnforceTaskLimit}) down to `maxScratchpadNotes`.
17085
+ * 4. **Memory Extraction Trigger**: When `extractMemories !== false` and `agentRun.Success` is `true`,
17086
+ * triggers asynchronous note/example extraction via {@link triggerPostRunMemoryExtraction}.
17087
+ *
17088
+ * Every phase is wrapped in its own `try/catch` block so an error in one phase is logged
17089
+ * via `LogError` without aborting the remaining phases or failing the completed agent run.
17090
+ *
17091
+ * @param params - The execution parameters for the completed agent run
17092
+ * @param agentRun - The finalized `MJAIAgentRunEntityExtended` record
17093
+ * @protected
17094
+ */
17095
+ async runPostRunCompaction(params, agentRun) {
17096
+ if (!params?.compactAfterRun) {
17097
+ return;
17098
+ }
17099
+ const rawConfig = params.compactAfterRun === true
17100
+ ? { enabled: true, messageCountThreshold: 20, extractMemories: true }
17101
+ : params.compactAfterRun;
17102
+ if (!rawConfig.enabled) {
17103
+ return;
17104
+ }
17105
+ const messageCountThreshold = rawConfig.messageCountThreshold ?? 20;
17106
+ const extractMemories = rawConfig.extractMemories ?? true;
17107
+ const maxScratchpadNotes = rawConfig.maxScratchpadNotes;
17108
+ if (params.onMessageLifecycle && !this._messageLifecycleCallback) {
17109
+ this._messageLifecycleCallback = params.onMessageLifecycle;
17110
+ }
17111
+ // 1. Message Window Pre-Compaction
17112
+ try {
17113
+ const messages = params.conversationMessages;
17114
+ if (Array.isArray(messages) && messages.length >= messageCountThreshold && messages.length >= 3) {
17115
+ const totalMessages = messages.length;
17116
+ const preserveRecentCount = totalMessages <= 3 ? 1 : (totalMessages < 9 ? 2 : 4);
17117
+ const compactEndIndex = totalMessages - preserveRecentCount;
17118
+ const preserveOriginal = params.messageExpirationOverride?.preserveOriginalContent !== false;
17119
+ let compactedCount = 0;
17120
+ let totalTokensSaved = 0;
17121
+ for (let i = 1; i < compactEndIndex; i++) {
17122
+ const msg = messages[i];
17123
+ const metaWithLegacyFlag = msg?.metadata;
17124
+ if (!msg ||
17125
+ msg.role === 'system' ||
17126
+ metaWithLegacyFlag?.wasCompacted === true ||
17127
+ metaWithLegacyFlag?.isCompacted === true ||
17128
+ metaWithLegacyFlag?.isConversationSummary === true ||
17129
+ metaWithLegacyFlag?.volatileState === true ||
17130
+ Boolean(msg.toolCalls?.length) ||
17131
+ !this.IsVolatileResultMessage(msg)) {
17132
+ continue;
17133
+ }
17134
+ const originalContent = msg.content;
17135
+ const originalText = ReplaceMediaBlocksWithStubs(originalContent);
17136
+ const compactMode = msg.metadata?.compactMode
17137
+ || params.messageExpirationOverride?.compactMode
17138
+ || 'First N Chars';
17139
+ const compactLength = msg.metadata?.compactLength
17140
+ || params.messageExpirationOverride?.compactLength
17141
+ || 200;
17142
+ const compactPromptId = msg.metadata?.compactPromptId
17143
+ || params.messageExpirationOverride?.compactPromptId
17144
+ || '';
17145
+ if (msg.role === 'tool') {
17146
+ const compactedTurn = CompactToolResultContent(msg, (t) => (t.length > compactLength ? `${t.slice(0, compactLength)}… [compacted from ${t.length} chars]` : t));
17147
+ const saved = Math.max(0, this.estimateTokens(originalContent) - this.estimateTokens(compactedTurn.content));
17148
+ messages[i] = {
17149
+ ...compactedTurn,
17150
+ metadata: {
17151
+ ...msg.metadata,
17152
+ wasCompacted: true,
17153
+ originalContent: preserveOriginal ? originalContent : undefined,
17154
+ originalLength: originalText.length,
17155
+ tokensSaved: saved,
17156
+ canExpand: preserveOriginal,
17157
+ },
17158
+ };
17159
+ totalTokensSaved += saved;
17160
+ compactedCount++;
17161
+ this.emitMessageLifecycleEvent({
17162
+ type: 'message-compacted',
17163
+ turn: 0,
17164
+ messageIndex: i,
17165
+ message: messages[i],
17166
+ reason: `Post-run compaction of tool turn (saved ${saved} tokens)`,
17167
+ tokensSaved: saved,
17168
+ });
17169
+ continue;
17170
+ }
17171
+ const compactedContent = await this.compactMessage(msg, {
17172
+ compactMode,
17173
+ compactLength,
17174
+ compactPromptId,
17175
+ originalLength: originalText.length,
17176
+ }, params);
17177
+ const originalTokens = this.estimateTokens(originalContent);
17178
+ const compactedTokens = this.estimateTokens(compactedContent);
17179
+ const tokensSaved = Math.max(0, originalTokens - compactedTokens);
17180
+ messages[i] = {
17181
+ ...msg,
17182
+ content: compactedContent,
17183
+ metadata: {
17184
+ ...msg.metadata,
17185
+ wasCompacted: true,
17186
+ originalContent: preserveOriginal ? originalContent : undefined,
17187
+ originalLength: originalText.length,
17188
+ tokensSaved,
17189
+ canExpand: preserveOriginal,
17190
+ },
17191
+ };
17192
+ totalTokensSaved += tokensSaved;
17193
+ compactedCount++;
17194
+ this.emitMessageLifecycleEvent({
17195
+ type: 'message-compacted',
17196
+ turn: 0,
17197
+ messageIndex: i,
17198
+ message: messages[i],
17199
+ reason: `Post-run compaction using ${compactMode} (saved ${tokensSaved} tokens)`,
17200
+ tokensSaved,
17201
+ });
17202
+ }
17203
+ if (compactedCount > 0) {
17204
+ this.logStatus(`🗜️ [PostRunCompaction] Compacted ${compactedCount} older message(s) (saved ~${totalTokensSaved} tokens; preserved index 0 and last ${preserveRecentCount} message(s))`, true, params);
17205
+ }
17206
+ }
17207
+ }
17208
+ catch (error) {
17209
+ LogError(`Post-run message window compaction failed (contained): ${error instanceof Error ? error.message : String(error)}`);
17210
+ }
17211
+ // 2. Scratchpad Pruning
17212
+ if (maxScratchpadNotes !== undefined && maxScratchpadNotes >= 0) {
17213
+ try {
17214
+ const prunedNotes = this._scratchpadManager.PruneNotes(maxScratchpadNotes);
17215
+ const prunedTasks = this._scratchpadManager.EnforceTaskLimit(maxScratchpadNotes);
17216
+ if (prunedNotes > 0 || prunedTasks > 0) {
17217
+ this.logStatus(`🧹 [PostRunCompaction] Pruned ${prunedNotes} scratchpad note line(s) and ${prunedTasks} completed task(s) (limit: ${maxScratchpadNotes})`, true, params);
17218
+ }
17219
+ }
17220
+ catch (error) {
17221
+ LogError(`Post-run scratchpad pruning failed (contained): ${error instanceof Error ? error.message : String(error)}`);
17222
+ }
17223
+ }
17224
+ // 3. Memory Extraction Trigger
17225
+ if (extractMemories && agentRun?.Success) {
17226
+ try {
17227
+ await this.triggerPostRunMemoryExtraction(params, agentRun);
17228
+ }
17229
+ catch (error) {
17230
+ LogError(`Post-run memory extraction failed (contained): ${error instanceof Error ? error.message : String(error)}`);
17231
+ }
17232
+ }
17233
+ }
17234
+ /**
17235
+ * Triggers asynchronous post-run note and example extraction via `MemoryManagerAgent`
17236
+ * when the executing agent has memory injection (`InjectNotes` or `InjectExamples`) enabled.
17237
+ *
17238
+ * No-ops when the executing agent itself is the `MemoryManagerAgent` (preventing recursion)
17239
+ * or when no active `MemoryManagerAgent` is registered in `AIEngine`.
17240
+ *
17241
+ * @param params - The execution parameters for the completed agent run
17242
+ * @param agentRun - The finalized `MJAIAgentRunEntityExtended` record
17243
+ * @protected
17244
+ */
17245
+ async triggerPostRunMemoryExtraction(params, agentRun) {
17246
+ const agent = params?.agent;
17247
+ if (!agent || (!agent.InjectNotes && !agent.InjectExamples)) {
17248
+ return;
17249
+ }
17250
+ if (agent.DriverClass === 'MemoryManagerAgent' || agent.Name === 'Memory Manager') {
17251
+ return;
17252
+ }
17253
+ const allAgents = AIEngine.Instance?.Agents ?? [];
17254
+ const memoryManagerEntity = allAgents.find(a => a.Status === 'Active' && (a.DriverClass === 'MemoryManagerAgent' || a.Name === 'Memory Manager'));
17255
+ if (!memoryManagerEntity || !params.contextUser) {
17256
+ return;
17257
+ }
17258
+ const driverKey = memoryManagerEntity.DriverClass || 'MemoryManagerAgent';
17259
+ const memoryAgent = MJGlobal.Instance.ClassFactory.CreateInstance(BaseAgent, driverKey);
17260
+ if (!memoryAgent) {
17261
+ return;
17262
+ }
17263
+ void memoryAgent.Execute({
17264
+ agent: memoryManagerEntity,
17265
+ conversationMessages: [],
17266
+ contextUser: params.contextUser,
17267
+ provider: params.provider,
17268
+ data: {
17269
+ sourceAgentId: agent.ID,
17270
+ sourceAgentRunId: agentRun.ID,
17271
+ conversationId: params.conversationId,
17272
+ },
17273
+ }).catch(error => {
17274
+ LogError(`Async post-run MemoryManager execution failed (contained): ${error instanceof Error ? error.message : String(error)}`);
17275
+ });
17276
+ }
15517
17277
  /**
15518
17278
  * Creates an AIAgentRunStep for message compaction operations.
15519
17279
  * Records the compaction attempt with context about the message being compacted.
@@ -15530,21 +17290,30 @@ The context is now within limits. Please retry your request with the recovered c
15530
17290
  }
15531
17291
  const step = await (params.provider || this._activeProvider).GetEntityObject('MJ: AI Agent Run Steps', params.contextUser);
15532
17292
  step.NewRecord();
15533
- step.AgentRunID = this._agentRun.ID;
15534
- step.StepType = 'Compaction';
15535
- step.Status = 'Running';
15536
- step.InputData = JSON.stringify({
15537
- stepName: 'Message Compaction',
15538
- description: `Compacting message using AI Summary (${message.metadata?.messageType || 'unknown'} from turn ${message.metadata?.turnAdded || 0})`,
15539
- messageType: message.metadata?.messageType,
15540
- turnAdded: message.metadata?.turnAdded,
15541
- originalLength: message.metadata?.originalLength ||
15542
- (typeof message.content === 'string' ? message.content.length : JSON.stringify(message.content).length),
15543
- compactMode: 'AI Summary',
15544
- promptId: prompt.ID,
15545
- promptName: prompt.Name
17293
+ const stepNumber = (this._agentRun.Steps?.length || 0) + 1;
17294
+ initAgentRunStep(step, {
17295
+ AgentRunID: this._agentRun.ID,
17296
+ StepNumber: stepNumber,
17297
+ StepType: 'Compaction',
17298
+ StepName: this.fitStepName(step, this.formatHierarchicalMessage('Message Compaction')),
17299
+ TargetID: prompt.ID,
17300
+ InputData: JSON.stringify({
17301
+ stepName: 'Message Compaction',
17302
+ description: `Compacting message using AI Summary (${message.metadata?.messageType || 'unknown'} from turn ${message.metadata?.turnAdded || 0})`,
17303
+ messageType: message.metadata?.messageType,
17304
+ turnAdded: message.metadata?.turnAdded,
17305
+ originalLength: message.metadata?.originalLength ||
17306
+ (typeof message.content === 'string' ? message.content.length : JSON.stringify(message.content).length),
17307
+ compactMode: 'AI Summary',
17308
+ promptId: prompt.ID,
17309
+ promptName: prompt.Name
17310
+ })
15546
17311
  });
15547
- await step.Save();
17312
+ this._stepSaveQueue.Insert(step);
17313
+ if (Array.isArray(this._agentRun.Steps)) {
17314
+ this._agentRun.Steps.push(step);
17315
+ }
17316
+ this.ensureTreeBudget(this._executeParams ?? params).totalSteps += 1;
15548
17317
  return step;
15549
17318
  }
15550
17319
  /**
@@ -15556,11 +17325,14 @@ The context is now within limits. Please retry your request with the recovered c
15556
17325
  * @param params - Agent execution parameters
15557
17326
  * @protected
15558
17327
  */
15559
- async updateCompactionStep(step, result, message, params) {
15560
- step.Status = result.success ? 'Completed' : 'Failed';
17328
+ async updateCompactionStep(step, result, message, _params) {
17329
+ if (result.promptRun?.ID) {
17330
+ step.TargetLogID = result.promptRun.ID;
17331
+ step.PromptRun = result.promptRun;
17332
+ }
15561
17333
  const promptTokens = result.promptTokens || 0;
15562
17334
  const completionTokens = result.completionTokens || 0;
15563
- step.OutputData = JSON.stringify({
17335
+ const outputData = {
15564
17336
  success: result.success,
15565
17337
  summaryLength: result.result?.summary?.length || 0,
15566
17338
  tokensSaved: message.metadata?.tokensSaved || 0,
@@ -15568,11 +17340,9 @@ The context is now within limits. Please retry your request with the recovered c
15568
17340
  completionTokens,
15569
17341
  totalTokens: promptTokens + completionTokens,
15570
17342
  cost: result.cost
15571
- });
15572
- if (!result.success) {
15573
- step.ErrorMessage = result.errorMessage || 'AI Summary compaction failed';
15574
- }
15575
- await step.Save();
17343
+ };
17344
+ const errorMessage = result.success ? undefined : (result.errorMessage || 'AI Summary compaction failed');
17345
+ await this.finalizeStepEntity(step, result.success, errorMessage, outputData);
15576
17346
  }
15577
17347
  /**
15578
17348
  * Compacts a message using configured compaction mode.
@@ -15627,8 +17397,12 @@ The context is now within limits. Please retry your request with the recovered c
15627
17397
  AgentRun: this._agentRun,
15628
17398
  ContextUser: params.contextUser,
15629
17399
  }) ?? undefined;
15630
- const runner = new AIPromptRunner();
15631
- const result = await runner.ExecutePrompt(promptParams);
17400
+ promptParams.onPromptRunCreated = async (promptRunId) => {
17401
+ step.TargetLogID = promptRunId;
17402
+ this.queueStepSave(step, (s) => { s.TargetLogID = promptRunId; });
17403
+ };
17404
+ const result = await this._promptRunner.ExecutePrompt(promptParams);
17405
+ this.recordPromptUsageInTreeBudget(result.promptRun, result, params);
15632
17406
  // Update step with result
15633
17407
  await this.updateCompactionStep(step, result, message, params);
15634
17408
  if (!result.success || !result.result?.summary) {
@@ -15963,6 +17737,105 @@ The context is now within limits. Please retry your request with the recovered c
15963
17737
  getValueFromPath(obj, path) {
15964
17738
  return GetValueFromPath(obj, path);
15965
17739
  }
17740
+ /**
17741
+ * The run's scope inputs: the explicit `ExecuteAgentParams` fields, else their `data` fallbacks, which count only
17742
+ * when the caller set `TrustReservedRunData`. {@link Execute} has already cleaned `data`; the rule is applied here
17743
+ * again for {@link ExecuteSingleAction} called outside a run (the realtime tool path, harnesses).
17744
+ */
17745
+ runScopeInputs(params) {
17746
+ const data = WithAgentRunDataTrustApplied(params).Params.data;
17747
+ return {
17748
+ EntityName: this.scopeText(params.PrimaryScopeEntityName ?? data?.PrimaryScopeEntityName),
17749
+ RecordID: this.scopeText(params.PrimaryScopeRecordID ?? data?.PrimaryScopeRecordID),
17750
+ Secondary: this.scopeDimensions(params.SecondaryScopes ?? data?.SecondaryScopes, params.agent?.Name),
17751
+ };
17752
+ }
17753
+ /**
17754
+ * Secondary scopes as the run takes them: a plain object of dimension values, else none. A host assembles them at
17755
+ * runtime (often through `data`), so anything else — a JSON string, an array, a class instance — is not read as
17756
+ * dimensions (its keys would be character indexes or properties); it is logged and the run carries no secondary scope.
17757
+ */
17758
+ scopeDimensions(value, agentName) {
17759
+ if (value === undefined || value === null) {
17760
+ return undefined;
17761
+ }
17762
+ if (!IsPlainObject(value)) {
17763
+ LogError(`Scoping: SecondaryScopes for agent "${agentName ?? 'unknown'}" must be a plain object of dimension values; ignored.`);
17764
+ return undefined;
17765
+ }
17766
+ return value;
17767
+ }
17768
+ /**
17769
+ * The run's scope as memory, retrieval and scoped prompt configuration take it: the scope {@link initializeAgentRun}
17770
+ * validated and wrote to the run row (`_runScope`; resolved the same way, {@link validatedRunScope}, outside a run),
17771
+ * with the primary entity resolved to its ID. One source, so notes and examples, pre-execution RAG, scoped prompt
17772
+ * parts and configs, the run row and every action dispatch see the same tenant and dimensions — trimmed, with the
17773
+ * agent's `ScopeConfig` defaults applied, and never a `data` scope the caller was not trusted to set.
17774
+ */
17775
+ runScopeForContext(params) {
17776
+ const scope = this._runScope ?? this.validatedRunScope(params);
17777
+ const entityName = scope.PrimaryScopeEntityName ?? undefined;
17778
+ return {
17779
+ EntityID: entityName ? this.ProviderToUse.EntityByName(entityName)?.ID : undefined,
17780
+ RecordID: scope.PrimaryScopeRecordID ?? undefined,
17781
+ Secondary: scope.SecondaryScopes ?? undefined,
17782
+ };
17783
+ }
17784
+ /** The run's scope ({@link runScopeForContext}) in the shape `ApplyScopedPromptConfig` takes. */
17785
+ scopedPromptConfigScope(params) {
17786
+ const scope = this.runScopeForContext(params);
17787
+ return { primaryScopeEntityId: scope.EntityID, primaryScopeRecordId: scope.RecordID, secondaryScopes: scope.Secondary };
17788
+ }
17789
+ /** A scope identifier as text: a non-blank string (trimmed) or a number; anything else is no value. */
17790
+ scopeText(value) {
17791
+ if (typeof value === 'number') {
17792
+ return String(value);
17793
+ }
17794
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
17795
+ }
17796
+ /**
17797
+ * The run's scope as the run row records it and every action dispatch is handed it: the inputs from
17798
+ * {@link runScopeInputs}, the secondary dimensions validated with the agent's configured defaults applied
17799
+ * ({@link validateAndApplySecondaryScopes}), and `null` for whatever the run does not carry.
17800
+ */
17801
+ validatedRunScope(params) {
17802
+ const inputs = this.runScopeInputs(params);
17803
+ if (!inputs.EntityName && !inputs.RecordID && !inputs.Secondary) {
17804
+ return { PrimaryScopeEntityName: null, PrimaryScopeRecordID: null, SecondaryScopes: null };
17805
+ }
17806
+ const secondary = this.validateAndApplySecondaryScopes(inputs.Secondary, this.parseSecondaryScopeConfig(params.agent), params.agent.Name);
17807
+ return {
17808
+ PrimaryScopeEntityName: inputs.EntityName ?? null,
17809
+ PrimaryScopeRecordID: inputs.RecordID ?? null,
17810
+ SecondaryScopes: secondary && Object.keys(secondary).length > 0 ? secondary : null,
17811
+ };
17812
+ }
17813
+ /**
17814
+ * Writes the validated run scope onto the run row: the primary entity resolved to its ID (logged when it is
17815
+ * not in metadata), the tenant record ID and the secondary dimensions as JSON. A secondary-only scope on an
17816
+ * agent whose ScopeConfig does not allow one is logged, and still recorded.
17817
+ */
17818
+ writeRunScope(params, scope) {
17819
+ if (scope.PrimaryScopeEntityName) {
17820
+ const primaryEntity = this.ProviderToUse.EntityByName(scope.PrimaryScopeEntityName);
17821
+ if (primaryEntity) {
17822
+ this._agentRun.PrimaryScopeEntityID = primaryEntity.ID;
17823
+ }
17824
+ else {
17825
+ LogError(`Scoping: Entity "${scope.PrimaryScopeEntityName}" not found in metadata`);
17826
+ }
17827
+ }
17828
+ if (scope.PrimaryScopeRecordID) {
17829
+ this._agentRun.PrimaryScopeRecordID = scope.PrimaryScopeRecordID;
17830
+ }
17831
+ if (scope.SecondaryScopes) {
17832
+ this._agentRun.SecondaryScopes = JSON.stringify(scope.SecondaryScopes);
17833
+ if (!scope.PrimaryScopeRecordID && !(this.parseSecondaryScopeConfig(params.agent)?.allowSecondaryOnly ?? false)) {
17834
+ LogError(`Scoping: Agent "${params.agent.Name}" requires primary scope when using secondary scopes. ` +
17835
+ `Set allowSecondaryOnly=true in ScopeConfig to allow secondary-only scoping.`);
17836
+ }
17837
+ }
17838
+ }
15966
17839
  /**
15967
17840
  * Parse the agent's SecondaryScopeConfig from the ScopeConfig field.
15968
17841
  * Returns null if not configured or invalid JSON.