@memberjunction/ai-agents 6.2.2 → 6.3.0-edge.1

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 (250) hide show
  1. package/README.md +29 -6
  2. package/dist/AgentContextAssembler.d.ts +127 -0
  3. package/dist/AgentContextAssembler.d.ts.map +1 -0
  4. package/dist/AgentContextAssembler.js +482 -0
  5. package/dist/AgentContextAssembler.js.map +1 -0
  6. package/dist/AgentDataPreloader.d.ts +14 -3
  7. package/dist/AgentDataPreloader.d.ts.map +1 -1
  8. package/dist/AgentDataPreloader.js +147 -22
  9. package/dist/AgentDataPreloader.js.map +1 -1
  10. package/dist/AgentDecisionService.d.ts +10 -1
  11. package/dist/AgentDecisionService.d.ts.map +1 -1
  12. package/dist/AgentDecisionService.js +28 -13
  13. package/dist/AgentDecisionService.js.map +1 -1
  14. package/dist/AgentFeedbackCoordinator.d.ts +169 -0
  15. package/dist/AgentFeedbackCoordinator.d.ts.map +1 -0
  16. package/dist/AgentFeedbackCoordinator.js +593 -0
  17. package/dist/AgentFeedbackCoordinator.js.map +1 -0
  18. package/dist/AgentRunner.d.ts +57 -15
  19. package/dist/AgentRunner.d.ts.map +1 -1
  20. package/dist/AgentRunner.js +692 -101
  21. package/dist/AgentRunner.js.map +1 -1
  22. package/dist/AgentStepDispatcher.d.ts +211 -0
  23. package/dist/AgentStepDispatcher.d.ts.map +1 -0
  24. package/dist/AgentStepDispatcher.js +729 -0
  25. package/dist/AgentStepDispatcher.js.map +1 -0
  26. package/dist/AgentTreeBudgetTracker.d.ts +163 -0
  27. package/dist/AgentTreeBudgetTracker.d.ts.map +1 -0
  28. package/dist/AgentTreeBudgetTracker.js +415 -0
  29. package/dist/AgentTreeBudgetTracker.js.map +1 -0
  30. package/dist/AgentWakeTriggerService.d.ts +41 -1
  31. package/dist/AgentWakeTriggerService.d.ts.map +1 -1
  32. package/dist/AgentWakeTriggerService.js +154 -8
  33. package/dist/AgentWakeTriggerService.js.map +1 -1
  34. package/dist/ArtifactToolManager.d.ts +134 -39
  35. package/dist/ArtifactToolManager.d.ts.map +1 -1
  36. package/dist/ArtifactToolManager.js +2761 -321
  37. package/dist/ArtifactToolManager.js.map +1 -1
  38. package/dist/GovernedArtifactService.d.ts +367 -0
  39. package/dist/GovernedArtifactService.d.ts.map +1 -0
  40. package/dist/GovernedArtifactService.js +2569 -0
  41. package/dist/GovernedArtifactService.js.map +1 -0
  42. package/dist/MJAIAgentRequestEntityServer.d.ts +32 -1
  43. package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
  44. package/dist/MJAIAgentRequestEntityServer.js +105 -3
  45. package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
  46. package/dist/SkillMarkdownConverter.d.ts +1 -1
  47. package/dist/SkillMarkdownConverter.d.ts.map +1 -1
  48. package/dist/SkillMarkdownConverter.js +8 -6
  49. package/dist/SkillMarkdownConverter.js.map +1 -1
  50. package/dist/agent-context-injector.d.ts +2 -25
  51. package/dist/agent-context-injector.d.ts.map +1 -1
  52. package/dist/agent-context-injector.js +38 -153
  53. package/dist/agent-context-injector.js.map +1 -1
  54. package/dist/agent-instance.d.ts +28 -0
  55. package/dist/agent-instance.d.ts.map +1 -0
  56. package/dist/agent-instance.js +39 -0
  57. package/dist/agent-instance.js.map +1 -0
  58. package/dist/agent-memory-context-builder.d.ts.map +1 -1
  59. package/dist/agent-memory-context-builder.js +46 -42
  60. package/dist/agent-memory-context-builder.js.map +1 -1
  61. package/dist/agent-pre-execution-rag.d.ts +5 -0
  62. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  63. package/dist/agent-pre-execution-rag.js +10 -0
  64. package/dist/agent-pre-execution-rag.js.map +1 -1
  65. package/dist/agent-run-watchdog.d.ts +38 -6
  66. package/dist/agent-run-watchdog.d.ts.map +1 -1
  67. package/dist/agent-run-watchdog.js +75 -13
  68. package/dist/agent-run-watchdog.js.map +1 -1
  69. package/dist/agent-types/flow-agent-type.d.ts +6 -1
  70. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  71. package/dist/agent-types/flow-agent-type.js +30 -7
  72. package/dist/agent-types/flow-agent-type.js.map +1 -1
  73. package/dist/agent-types/loop-agent-prompt-params.d.ts +18 -0
  74. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  75. package/dist/agent-types/loop-agent-prompt-params.js +2 -0
  76. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  77. package/dist/agent-types/loop-agent-type.d.ts +4 -0
  78. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  79. package/dist/agent-types/loop-agent-type.js +29 -0
  80. package/dist/agent-types/loop-agent-type.js.map +1 -1
  81. package/dist/artifact-presence-locator.d.ts +132 -0
  82. package/dist/artifact-presence-locator.d.ts.map +1 -0
  83. package/dist/artifact-presence-locator.js +472 -0
  84. package/dist/artifact-presence-locator.js.map +1 -0
  85. package/dist/artifact-tools/CSVToolLibrary.d.ts +2 -2
  86. package/dist/artifact-tools/CSVToolLibrary.d.ts.map +1 -1
  87. package/dist/artifact-tools/CSVToolLibrary.js +41 -14
  88. package/dist/artifact-tools/CSVToolLibrary.js.map +1 -1
  89. package/dist/artifact-tools/DataSnapshotToolLibrary.d.ts +2 -2
  90. package/dist/artifact-tools/DataSnapshotToolLibrary.d.ts.map +1 -1
  91. package/dist/artifact-tools/DataSnapshotToolLibrary.js +53 -21
  92. package/dist/artifact-tools/DataSnapshotToolLibrary.js.map +1 -1
  93. package/dist/artifact-tools/DocumentToolLibrary.d.ts +101 -0
  94. package/dist/artifact-tools/DocumentToolLibrary.d.ts.map +1 -0
  95. package/dist/artifact-tools/DocumentToolLibrary.js +1846 -0
  96. package/dist/artifact-tools/DocumentToolLibrary.js.map +1 -0
  97. package/dist/artifact-tools/DocxToolLibrary.d.ts +2 -4
  98. package/dist/artifact-tools/DocxToolLibrary.d.ts.map +1 -1
  99. package/dist/artifact-tools/DocxToolLibrary.js +42 -30
  100. package/dist/artifact-tools/DocxToolLibrary.js.map +1 -1
  101. package/dist/artifact-tools/ExcelToolLibrary.d.ts +2 -3
  102. package/dist/artifact-tools/ExcelToolLibrary.d.ts.map +1 -1
  103. package/dist/artifact-tools/ExcelToolLibrary.js +105 -49
  104. package/dist/artifact-tools/ExcelToolLibrary.js.map +1 -1
  105. package/dist/artifact-tools/GenericBinaryToolLibrary.d.ts +2 -2
  106. package/dist/artifact-tools/GenericBinaryToolLibrary.d.ts.map +1 -1
  107. package/dist/artifact-tools/GenericBinaryToolLibrary.js +3 -2
  108. package/dist/artifact-tools/GenericBinaryToolLibrary.js.map +1 -1
  109. package/dist/artifact-tools/JSONToolLibrary.d.ts +4 -4
  110. package/dist/artifact-tools/JSONToolLibrary.d.ts.map +1 -1
  111. package/dist/artifact-tools/JSONToolLibrary.js +32 -11
  112. package/dist/artifact-tools/JSONToolLibrary.js.map +1 -1
  113. package/dist/artifact-tools/PDFToolLibrary.d.ts +27 -3
  114. package/dist/artifact-tools/PDFToolLibrary.d.ts.map +1 -1
  115. package/dist/artifact-tools/PDFToolLibrary.js +36 -21
  116. package/dist/artifact-tools/PDFToolLibrary.js.map +1 -1
  117. package/dist/artifact-tools/SearchResultSetToolLibrary.d.ts +2 -2
  118. package/dist/artifact-tools/SearchResultSetToolLibrary.d.ts.map +1 -1
  119. package/dist/artifact-tools/SearchResultSetToolLibrary.js +83 -24
  120. package/dist/artifact-tools/SearchResultSetToolLibrary.js.map +1 -1
  121. package/dist/artifact-tools/SlideDeckToolLibrary.d.ts +50 -0
  122. package/dist/artifact-tools/SlideDeckToolLibrary.d.ts.map +1 -0
  123. package/dist/artifact-tools/SlideDeckToolLibrary.js +1617 -0
  124. package/dist/artifact-tools/SlideDeckToolLibrary.js.map +1 -0
  125. package/dist/artifact-tools/SpreadsheetToolLibrary.d.ts +87 -0
  126. package/dist/artifact-tools/SpreadsheetToolLibrary.d.ts.map +1 -0
  127. package/dist/artifact-tools/SpreadsheetToolLibrary.js +3351 -0
  128. package/dist/artifact-tools/SpreadsheetToolLibrary.js.map +1 -0
  129. package/dist/artifact-tools/TextToolLibrary.d.ts +3 -3
  130. package/dist/artifact-tools/TextToolLibrary.d.ts.map +1 -1
  131. package/dist/artifact-tools/TextToolLibrary.js +34 -24
  132. package/dist/artifact-tools/TextToolLibrary.js.map +1 -1
  133. package/dist/artifact-tools/WhiteboardToolLibrary.d.ts +69 -0
  134. package/dist/artifact-tools/WhiteboardToolLibrary.d.ts.map +1 -0
  135. package/dist/artifact-tools/WhiteboardToolLibrary.js +555 -0
  136. package/dist/artifact-tools/WhiteboardToolLibrary.js.map +1 -0
  137. package/dist/artifact-tools/artifact-comment-suggestion-helper.d.ts +98 -0
  138. package/dist/artifact-tools/artifact-comment-suggestion-helper.d.ts.map +1 -0
  139. package/dist/artifact-tools/artifact-comment-suggestion-helper.js +851 -0
  140. package/dist/artifact-tools/artifact-comment-suggestion-helper.js.map +1 -0
  141. package/dist/artifact-tools/artifact-tool-helpers.d.ts +21 -0
  142. package/dist/artifact-tools/artifact-tool-helpers.d.ts.map +1 -0
  143. package/dist/artifact-tools/artifact-tool-helpers.js +74 -0
  144. package/dist/artifact-tools/artifact-tool-helpers.js.map +1 -0
  145. package/dist/artifact-tools/grepHelper.d.ts +27 -0
  146. package/dist/artifact-tools/grepHelper.d.ts.map +1 -0
  147. package/dist/artifact-tools/grepHelper.js +229 -0
  148. package/dist/artifact-tools/grepHelper.js.map +1 -0
  149. package/dist/artifact-tools/node-vm-safe-regex.d.ts +10 -0
  150. package/dist/artifact-tools/node-vm-safe-regex.d.ts.map +1 -0
  151. package/dist/artifact-tools/node-vm-safe-regex.js +148 -0
  152. package/dist/artifact-tools/node-vm-safe-regex.js.map +1 -0
  153. package/dist/base-agent.d.ts +151 -137
  154. package/dist/base-agent.d.ts.map +1 -1
  155. package/dist/base-agent.js +727 -1550
  156. package/dist/base-agent.js.map +1 -1
  157. package/dist/catalog-narrowing.d.ts +112 -5
  158. package/dist/catalog-narrowing.d.ts.map +1 -1
  159. package/dist/catalog-narrowing.js +181 -6
  160. package/dist/catalog-narrowing.js.map +1 -1
  161. package/dist/decision-discovery.d.ts +42 -15
  162. package/dist/decision-discovery.d.ts.map +1 -1
  163. package/dist/decision-discovery.js +90 -20
  164. package/dist/decision-discovery.js.map +1 -1
  165. package/dist/index.d.ts +17 -2
  166. package/dist/index.d.ts.map +1 -1
  167. package/dist/index.js +17 -3
  168. package/dist/index.js.map +1 -1
  169. package/dist/memory-decision-uses.d.ts +206 -0
  170. package/dist/memory-decision-uses.d.ts.map +1 -0
  171. package/dist/memory-decision-uses.js +259 -0
  172. package/dist/memory-decision-uses.js.map +1 -0
  173. package/dist/memory-manager-agent.d.ts +66 -6
  174. package/dist/memory-manager-agent.d.ts.map +1 -1
  175. package/dist/memory-manager-agent.js +184 -31
  176. package/dist/memory-manager-agent.js.map +1 -1
  177. package/dist/memory-note-gate.d.ts +12 -9
  178. package/dist/memory-note-gate.d.ts.map +1 -1
  179. package/dist/memory-note-gate.js +16 -11
  180. package/dist/memory-note-gate.js.map +1 -1
  181. package/dist/native-tools/control-tools.d.ts +8 -1
  182. package/dist/native-tools/control-tools.d.ts.map +1 -1
  183. package/dist/native-tools/control-tools.js +38 -5
  184. package/dist/native-tools/control-tools.js.map +1 -1
  185. package/dist/native-tools/framework-tools.d.ts +3 -3
  186. package/dist/native-tools/framework-tools.d.ts.map +1 -1
  187. package/dist/native-tools/framework-tools.js +20 -8
  188. package/dist/native-tools/framework-tools.js.map +1 -1
  189. package/dist/pipeline/operators.d.ts.map +1 -1
  190. package/dist/pipeline/operators.js +1 -1
  191. package/dist/pipeline/operators.js.map +1 -1
  192. package/dist/pipeline/pipeline-executor.d.ts +29 -1
  193. package/dist/pipeline/pipeline-executor.d.ts.map +1 -1
  194. package/dist/pipeline/pipeline-executor.js +159 -2
  195. package/dist/pipeline/pipeline-executor.js.map +1 -1
  196. package/dist/pipeline/pipeline.types.d.ts +19 -1
  197. package/dist/pipeline/pipeline.types.d.ts.map +1 -1
  198. package/dist/pipeline/template.d.ts +16 -0
  199. package/dist/pipeline/template.d.ts.map +1 -1
  200. package/dist/pipeline/template.js +55 -6
  201. package/dist/pipeline/template.js.map +1 -1
  202. package/dist/realtime/artifact-workspace-channel-server.d.ts +27 -0
  203. package/dist/realtime/artifact-workspace-channel-server.d.ts.map +1 -0
  204. package/dist/realtime/artifact-workspace-channel-server.js +43 -0
  205. package/dist/realtime/artifact-workspace-channel-server.js.map +1 -0
  206. package/dist/realtime/bridge-realtime-session-factory.d.ts +2 -2
  207. package/dist/realtime/bridge-realtime-session-factory.d.ts.map +1 -1
  208. package/dist/realtime/bridge-realtime-session-factory.js +7 -56
  209. package/dist/realtime/bridge-realtime-session-factory.js.map +1 -1
  210. package/dist/realtime/bridge-room-transcript-sink.d.ts.map +1 -1
  211. package/dist/realtime/bridge-room-transcript-sink.js +28 -1
  212. package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
  213. package/dist/realtime/media-channel-server.js +1 -1
  214. package/dist/realtime/media-channel-server.js.map +1 -1
  215. package/dist/realtime/realtime-artifact-helpers.d.ts +37 -0
  216. package/dist/realtime/realtime-artifact-helpers.d.ts.map +1 -0
  217. package/dist/realtime/realtime-artifact-helpers.js +150 -0
  218. package/dist/realtime/realtime-artifact-helpers.js.map +1 -0
  219. package/dist/realtime/realtime-client-session-service.d.ts +209 -19
  220. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  221. package/dist/realtime/realtime-client-session-service.js +670 -41
  222. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  223. package/dist/realtime/realtime-coagent-config.d.ts +26 -9
  224. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  225. package/dist/realtime/realtime-coagent-config.js +47 -60
  226. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  227. package/dist/realtime/realtime-delegation-narrator.js +1 -1
  228. package/dist/realtime/realtime-delegation-narrator.js.map +1 -1
  229. package/dist/realtime/realtime-moderator-decision.d.ts +86 -0
  230. package/dist/realtime/realtime-moderator-decision.d.ts.map +1 -0
  231. package/dist/realtime/realtime-moderator-decision.js +131 -0
  232. package/dist/realtime/realtime-moderator-decision.js.map +1 -0
  233. package/dist/realtime/realtime-session-runner.d.ts +2 -0
  234. package/dist/realtime/realtime-session-runner.d.ts.map +1 -1
  235. package/dist/realtime/realtime-session-runner.js +24 -3
  236. package/dist/realtime/realtime-session-runner.js.map +1 -1
  237. package/dist/realtime/realtime-tool-broker.d.ts +6 -0
  238. package/dist/realtime/realtime-tool-broker.d.ts.map +1 -1
  239. package/dist/realtime/realtime-tool-broker.js +4 -2
  240. package/dist/realtime/realtime-tool-broker.js.map +1 -1
  241. package/dist/realtime/realtime-turn-moderator.d.ts +20 -0
  242. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  243. package/dist/realtime/realtime-turn-moderator.js +63 -8
  244. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  245. package/dist/repeated-failing-step.d.ts +50 -0
  246. package/dist/repeated-failing-step.d.ts.map +1 -0
  247. package/dist/repeated-failing-step.js +130 -0
  248. package/dist/repeated-failing-step.js.map +1 -0
  249. package/dist/tsconfig.tsbuildinfo +1 -0
  250. package/package.json +20 -20
@@ -12,7 +12,6 @@
12
12
  */
13
13
  import { MJEnvironmentEntityExtended, ConversationEngine } from '@memberjunction/core-entities';
14
14
  import { BuildActionToolSet, CoerceActionArguments, FilterDeclarableActions, SanitizeToolName } from './native-tools/action-tool-builder.js';
15
- import { DescribeValueSchemaInline, GetStoredValueSchema } from './native-tools/action-param-schema.js';
16
15
  import { ApplyBoundActionParams, BindingsForAction, IsBoundParamName, UnboundParams } from './bound-action-params.js';
17
16
  import { BuildNativeToolSet, COMPLETE_TASK_TOOL, SUB_AGENT_TOOL_PREFIX } from './native-tools/control-tools.js';
18
17
  import { TurnToolCallingMode } from './native-tools/turn-mode.js';
@@ -22,19 +21,21 @@ import { BuildFrameworkTools } from './native-tools/framework-tools.js';
22
21
  import { BuildAssistantToolCallTurn, BuildToolResultTurn, CompactAnsweredToolCallArguments, CompactToolResultContent, CompactToolResultContentAsync } from './native-tools/tool-result-turns.js';
23
22
  import { LooksLikeLoopEnvelope } from './native-tools/dual-channel.js';
24
23
  import { MJAIAgentRunEntityExtended, ResolvePromptRunUserID, ResolvePayloadAtEnd } from "@memberjunction/ai-core-plus";
25
- import { Metadata, RunView, LogStatus, LogStatusEx, LogError, LogErrorEx, IsVerboseLoggingEnabled, DatabaseProviderBase, ToPlainJSON } from '@memberjunction/core';
24
+ import { GovernedArtifactService, MergeTouchedArtifactSummary } from './GovernedArtifactService.js';
25
+ import { CollectDelegatedRunArtifactsSafely, ExtractDirectActionArtifacts } from './realtime/realtime-artifact-helpers.js';
26
+ import { Metadata, RunView, LogStatus, LogStatusEx, LogError, LogErrorEx, IsVerboseLoggingEnabled, DatabaseProviderBase, ServerOperationScopeManager } from '@memberjunction/core';
26
27
  import { AgentRunWatchdog } from './agent-run-watchdog.js';
27
28
  import { AIPromptRunner, GetToolCallingDecision, GetSentPrefixFingerprint } from '@memberjunction/ai-prompts';
28
- import { BaseLLM, BaseRealtimeModel, GetAIAPIKey, CredentialScopeAllows, MakeAIAPIKeyResolver, IsPrefixPromptCache } from '@memberjunction/ai';
29
+ import { BaseRealtimeModel, GetAIAPIKey, CredentialScopeAllows, MakeAIAPIKeyResolver } from '@memberjunction/ai';
29
30
  import { BaseAgentType } from './agent-types/base-agent-type.js';
30
31
  import { LoopAgentType } from './agent-types/loop-agent-type.js';
32
+ import { CreateAgentInstance } from './agent-instance.js';
33
+ import { FailingStepError, IsPromptTurnStep, MAX_REPEATED_FAILING_STEP, RepeatedFailingStepTracker } from './repeated-failing-step.js';
31
34
  import { ProviderRubricEngine } from '@memberjunction/rubrics';
32
35
  import { ExecuteSelfCheck, PickSelfCheckLink } from './self-check.js';
33
36
  import { CopyScalarsAndArrays, GroupByUUID, IndexByUUID, JSONValidator, MJGlobal, NormalizeUUID, SafeExpressionEvaluator, UUIDsEqual, UUIDSet, EscapeSQLString, IsPlainObject, CleanAndParseJSON, IsValidUUID } from '@memberjunction/global';
34
37
  // token optimization via @memberjunction/context-crush (SmartCrusher/CacheAligner-inspired)
35
- import { CrushJSON, DescribeCrush, PartitionStablePrefix } from '@memberjunction/context-crush';
36
- // AST-aware code reduction (CodeCompressor-inspired) — opt-in per agent type
37
- import { CrushCode } from '@memberjunction/context-crush/code';
38
+ import { PartitionStablePrefix } from '@memberjunction/context-crush';
38
39
  import { RealtimeSessionRunner } from './realtime/realtime-session-runner.js';
39
40
  import { ResolveNarrationInstructionsTemplate } from './realtime/realtime-narration.js';
40
41
  import { BuildRealtimeOverridesJson, BuildVoiceMannerSection, GetNarrationPaceMs, GetProviderVoiceSettings, GetSessionTuningSettings, GetModelCatalogSessionSettings, DeepMergeConfigs, ResolveEffectiveRealtimeConfig } from './realtime/realtime-coagent-config.js';
@@ -57,14 +58,13 @@ import { FormatToolResultSection, FormatToolErrorSection, RenderToolResultData,
57
58
  import { PriorTurnToolResultCache } from './prior-turn-tool-result-cache.js';
58
59
  import { PromptComponentResolver, InjectScopedPromptParts } from './prompt-component-resolver.js';
59
60
  import { ScopedPromptConfigResolver, ApplyScopedPromptConfig } from './scoped-prompt-config-resolver.js';
60
- import { StringifyForPersistence, AIPromptParams, ChildPromptParam, ConversationUtility, ParseFileOutputRef, parseAssignmentStrategy, ResolveClientTools, initAgentRunStep, finalizeAgentRunStep, AgentRunStepSaveQueue, ExtractPromptResultText, GetTaskGraphSubmitter, SummarizeDecisionAnswers, SystemPlaceholderManager, WithoutHostOnlyAgentRunDataKeys, WithAgentRunDataTrustApplied, AgentUserPolicyEngine, ApplyOutputMapping, BuildActionOutputObject, ConfigOf, ResolveLoopBodyParams, ValidateLoopOperationStructure } from '@memberjunction/ai-core-plus';
61
+ import { StringifyForPersistence, AIPromptParams, ChildPromptParam, ConversationUtility, ParseFileOutputRef, initAgentRunStep, finalizeAgentRunStep, AgentRunStepSaveQueue, ExtractPromptResultText, GetTaskGraphSubmitter, SummarizeDecisionAnswers, SystemPlaceholderManager, WithoutHostOnlyAgentRunDataKeys, WithAgentRunDataTrustApplied, AgentUserPolicyEngine, ConfigOf, ResolveLoopBodyParams, ValidateLoopOperationStructure, BuildTaskSecurityEnvelope, MergeTaskSecurityEnvelopes, TAINTED_EGRESS_BLOCKED, TenantContextCarryProblem, ReadEdgePreDiscoveryHint, } from '@memberjunction/ai-core-plus';
61
62
  import { ActionEngineBase, ActionResult, RunActionParams, AUDIENCE_UNSUPPORTED_RESULT_CODE, ActionRunScopeIsBounded } from '@memberjunction/actions-base';
62
63
  import { UserCache } from '@memberjunction/generic-database-provider';
63
64
  import { AgentAudienceAddsReader, AgentAudienceProblem, AgentAudienceReaderIDs, MatchAudienceUsers } from './agent-audience.js';
64
65
  import { TemplateEngineServer } from '@memberjunction/templates';
65
- import { RuntimeStateFragmentBuilder, EscapeRuntimeStateTagsInMessage } from './runtime-state-fragment.js';
66
66
  import { ResolveSpecializationPlacement } from './volatile-child-prompt.js';
67
- import { CURRENT_DATE_PLACEHOLDER, CURRENT_DAY_OF_WEEK_PLACEHOLDER, CURRENT_TIME_PLACEHOLDER, RUNTIME_STATE_TAG, SCRATCHPAD_NOTES_PLACEHOLDER, SCRATCHPAD_TASK_SUMMARY_PLACEHOLDER, SCRATCHPAD_TASKS_PLACEHOLDER, VOLATILE_TEMPLATE_MARKERS, } from './constants.js';
67
+ import { RUNTIME_STATE_TAG, SCRATCHPAD_NOTES_PLACEHOLDER, SCRATCHPAD_TASK_SUMMARY_PLACEHOLDER, SCRATCHPAD_TASKS_PLACEHOLDER, VOLATILE_TEMPLATE_MARKERS, } from './constants.js';
68
68
  import { AgentRunner } from './AgentRunner.js';
69
69
  import { PayloadManager } from './PayloadManager.js';
70
70
  import { ScratchpadManager } from './ScratchpadManager.js';
@@ -74,19 +74,23 @@ import { AgentDecisionService } from './AgentDecisionService.js';
74
74
  import { PayloadFeedbackManager } from './PayloadFeedbackManager.js';
75
75
  import { DEFAULT_LOOP_AGENT_PROMPT_PARAMS, MAX_DECISION_CALLS_PER_TURN, MAX_DECISION_REQUESTS_PER_TURN, ResolveFinishIfMode } from './agent-types/loop-agent-prompt-params.js';
76
76
  import { FinishIfModeWarnings } from './finish-if-mode-warnings.js';
77
- import { ApplyCatalogNarrowing, BuildCatalogNarrowingQuestions, CatalogNarrowingCandidatesToAsk, CatalogNarrowingNote, CATALOG_NARROWING_FIND_ACTIONS, IsAlwaysShownAction, IsCatalogListNarrowed, NoCatalogNarrowing, OpeningRequestText, ReachableCatalogNarrowingLimits, ResolveCatalogNarrowingLimits, SelectCatalogNarrowing, } from './catalog-narrowing.js';
78
- import { BuildDecisionDiscoveryOptionSet, BuildDecisionDiscoveryQuestions, CanSearchEntities, DECISION_DISCOVERY_MAX_RECORDED_IDS, DECISION_DISCOVERY_MIN_CONFIDENCE, DECISION_DISCOVERY_MIN_OPTIONS, DECISION_DISCOVERY_TIMEOUT_MS, DecisionDiscoveryAgentSearch, DecisionDiscoveryFromResult, DecisionDiscoveryRunnableAgents, DecisionPromptOptionCap, FailedDecisionDiscovery, HostAllowedAgentIDs, IsDecisionDiscoveryOn, IsOpeningTurn, KeepHostAllowedAgents, MentionsAgent, } from './decision-discovery.js';
77
+ import { ApplyCatalogNarrowing, BuildCatalogNarrowingQuestions, CatalogNarrowingCandidatesToAsk, CatalogNarrowingNote, CATALOG_NARROWING_FIND_ACTIONS, CATALOG_NARROWING_FIND_SKILLS, DEFAULT_MAX_SKILL_DECISION_CANDIDATES, IsAlwaysShownAction, IsCatalogListNarrowed, NoCatalogNarrowing, OpeningRequestText, PreFilterSkillCandidatesForDecision, ReachableCatalogNarrowingLimits, ResolveCatalogNarrowingLimits, SelectCatalogNarrowing, } from './catalog-narrowing.js';
78
+ import { AgentsWithoutDescription, BuildDecisionDiscoveryOptionSet, BuildDecisionDiscoveryQuestions, CanSearchEntities, DECISION_DISCOVERY_MAX_RECORDED_IDS, DECISION_DISCOVERY_MIN_CONFIDENCE, DECISION_DISCOVERY_MIN_OPTIONS, DECISION_DISCOVERY_TIMEOUT_MS, DecisionDiscoveryAgentSearch, DecisionDiscoveryCatalog, DecisionDiscoveryFromResult, DecisionDiscoveryOptions, DecisionDiscoveryRunnableAgents, DecisionOptionLimit, DecisionPromptOptionCap, EvaluateEdgePreDiscoveryHint, FailedDecisionDiscovery, HostAllowedAgentIDs, IsDecisionDiscoveryOn, IsOpeningTurn, KeepHostAllowedAgents, MentionsAgent, } from './decision-discovery.js';
79
79
  import { ResolveHandoffTarget } from './handoff-target.js';
80
80
  import { BuildFinishIfQuestions, CapFinishIfState, FINISH_IF_STATE_EXCERPT, FormatActionForFinishIf, FormatSubAgentForFinishIf, JudgeFinishIf } from './finish-if-state.js';
81
81
  import { PipelineExecutor, PipelineToolRegistry, ActionInvocable, ArtifactToolInvocable, BuildPipelineToolDocs, formatFinalOutput, summarizePipelineStages, } from './pipeline/index.js';
82
+ import { BuildTaskGraphStartDebug } from '@memberjunction/ai-core-plus';
82
83
  // The ONE payload-mapping dialect. Loop agents and the task-graph dispatcher read the same authored
83
84
  // mapping strings, so these must be the same functions rather than two copies that agree today.
84
- import { GetValueFromPath, SetMappedValue } from '@memberjunction/ai-core-plus';
85
+ import { GetValueFromPath } from '@memberjunction/ai-core-plus';
85
86
  import { AgentDataPreloader } from './AgentDataPreloader.js';
86
87
  import { ClientToolRequestManager } from './ClientToolRequestManager.js';
87
- import { BuildClientToolResultMessage, ResolveClientToolResultMaxChars, ReplaceMediaBlocksWithStubs, IsMediaBlock, IMAGE_BLOCK_TOKEN_ESTIMATE, WrapUntrustedExternalData } from './client-tool-results.js';
88
+ import { BuildClientToolResultMessage, ResolveClientToolResultMaxChars, ReplaceMediaBlocksWithStubs, IsMediaBlock, IMAGE_BLOCK_TOKEN_ESTIMATE } from './client-tool-results.js';
88
89
  import { CanAgentOwnSubAgentConsults, DEFAULT_MAX_SUB_AGENT_CONSULT_ROUNDS, FormatReloadedConsultsMessage, FormatResponseFormSummary, FormatSubAgentConsultMessage, LoadOpenSubAgentConsults } from './sub-agent-consult.js';
89
- import { ConversationMessageResolver } from './utils/ConversationMessageResolver.js';
90
+ import { AgentTreeBudgetTracker } from './AgentTreeBudgetTracker.js';
91
+ import { AgentFeedbackCoordinator } from './AgentFeedbackCoordinator.js';
92
+ import { AgentContextAssembler } from './AgentContextAssembler.js';
93
+ import { AgentStepDispatcher } from './AgentStepDispatcher.js';
90
94
  import _ from 'lodash';
91
95
  /**
92
96
  * Base implementation for AI Agents in the MemberJunction framework.
@@ -234,6 +238,13 @@ export class BaseAgent {
234
238
  * @private
235
239
  */
236
240
  this._audienceLockedActions = new Set();
241
+ /**
242
+ * Actions refused because the run read untrusted content under a task-graph envelope (`TAINTED_EGRESS_BLOCKED`) —
243
+ * locked out like {@link _fatalActionFailures}, under their own breaker reason (`'tainted'`) so the model is told
244
+ * a person must review that content first rather than that the action is misconfigured.
245
+ * @private
246
+ */
247
+ this._taintLockedActions = new Set();
237
248
  /**
238
249
  * External/untrusted data sources ingested during the current agent run (Primitive 2).
239
250
  * Once non-empty, {@link IsRunTainted} is true for the remainder of the run and any memory
@@ -304,8 +315,8 @@ export class BaseAgent {
304
315
  */
305
316
  this._awaitingWorkflowTaskID = null;
306
317
  /**
307
- * Stores the ID of an AIAgentRequest created when a Chat step fires.
308
- * Populated by executeChatStep(), returned in ExecuteAgentResult.feedbackRequestId.
318
+ * Stores the ID of an AIAgentRequest created when a Chat or Plan step fires.
319
+ * Populated by createFeedbackRequest(), returned in ExecuteAgentResult.feedbackRequestId.
309
320
  * Only set for root agents (depth 0), not sub-agents.
310
321
  * @private
311
322
  */
@@ -680,6 +691,24 @@ export class BaseAgent {
680
691
  * @private
681
692
  */
682
693
  static { this.MAX_CONSECUTIVE_UNPRODUCTIVE_RETRIES = 10; }
694
+ /** Collaborator tracking hierarchical token, cost, wall-clock, and attempt budgets across the agent tree. */
695
+ get _budgetTracker() {
696
+ return (this.__budgetTracker ??= new AgentTreeBudgetTracker());
697
+ }
698
+ /** Collaborator coordinating HITL feedback requests, assignment strategy resolution, and List routing. */
699
+ get _feedbackCoordinator() {
700
+ return (this.__feedbackCoordinator ??= new AgentFeedbackCoordinator({
701
+ OnLogStatus: (message, isVerboseOnly, params) => this.logStatus(message, isVerboseOnly, params),
702
+ }));
703
+ }
704
+ /** Collaborator assembling outgoing message arrays, trailing runtime-state fragments, and prompt catalogs. */
705
+ get _contextAssembler() {
706
+ return (this.__contextAssembler ??= new AgentContextAssembler());
707
+ }
708
+ /** Collaborator dispatching step/loop formatting, payload mapping, and template resolution. */
709
+ get _stepDispatcher() {
710
+ return (this.__stepDispatcher ??= new AgentStepDispatcher());
711
+ }
683
712
  /**
684
713
  * Gets the shared {@link AgentTreeBudget} tracking cumulative steps, tokens, cost,
685
714
  * and elapsed wall-clock duration across the root agent and all descendant sub-agents.
@@ -846,11 +875,14 @@ export class BaseAgent {
846
875
  }
847
876
  }
848
877
  /**
849
- * Locks an action out for the rest of the run: later calls short-circuit on the breaker's `'fatal'` rule, or on
850
- * its `'audience'` rule for an action the engine refused for the run's audience.
878
+ * Locks an action out for the rest of the run: later calls short-circuit on the breaker's `'fatal'` rule, on
879
+ * its `'audience'` rule for an action the engine refused for the run's audience, or on its `'tainted'` rule for
880
+ * an action refused because the run read untrusted content.
851
881
  */
852
882
  lockOutAction(action, actionEntity, reason = 'fatal') {
853
- const lockouts = reason === 'audience' ? this._audienceLockedActions : this._fatalActionFailures;
883
+ const lockouts = reason === 'audience' ? this._audienceLockedActions
884
+ : reason === 'tainted' ? this._taintLockedActions
885
+ : this._fatalActionFailures;
854
886
  lockouts.add(action.name);
855
887
  if (actionEntity?.Name) {
856
888
  lockouts.add(actionEntity.Name);
@@ -860,12 +892,14 @@ export class BaseAgent {
860
892
  resetActionCircuitBreaker() {
861
893
  this._fatalActionFailures.clear();
862
894
  this._audienceLockedActions.clear();
895
+ this._taintLockedActions.clear();
863
896
  this._actionFailureHistory.clear();
864
897
  this._agentToolBreaker.Reset();
865
898
  }
866
899
  /**
867
- * The blocked result for an action locked out for the run — refused for the audience (`'audience'`), or failed
868
- * with an unrecoverable configuration or credential error (`'fatal'`) — or null when it is not locked out.
900
+ * The blocked result for an action locked out for the run — refused for the audience (`'audience'`), refused
901
+ * because the run read untrusted content (`'tainted'`), or failed with an unrecoverable configuration or
902
+ * credential error (`'fatal'`) — or null when it is not locked out.
869
903
  */
870
904
  lockedOutActionResult(params, action, actionEntity) {
871
905
  const isLocked = (lockouts) => lockouts.has(action.name) || (!!actionEntity?.Name && lockouts.has(actionEntity.Name));
@@ -874,6 +908,10 @@ export class BaseAgent {
874
908
  return this.buildBlockedActionResult(actionEntity, 'audience', `Action '${action.name}' is not available in this shared conversation: what it returns could not be limited to what ` +
875
909
  'everyone here may see. Do not call it again in this run; use another tool or answer from what you have.');
876
910
  }
911
+ if (isLocked(this._taintLockedActions)) {
912
+ this.logStatus(` ⚡ Circuit breaker: Action '${action.name}' short-circuited (0ms): this run read untrusted content`, false, params);
913
+ return this.buildBlockedActionResult(actionEntity, 'tainted', this.taintLockoutText(action.name));
914
+ }
877
915
  if (isLocked(this._fatalActionFailures)) {
878
916
  this.logStatus(` ⚡ Circuit breaker: Action '${action.name}' short-circuited (0ms): fatal configuration or credential error earlier in this run`, false, params);
879
917
  return this.buildBlockedActionResult(actionEntity, 'fatal', `Action '${action.name}' is disabled for this run because it previously failed with an unrecoverable configuration or ` +
@@ -881,6 +919,13 @@ export class BaseAgent {
881
919
  }
882
920
  return null;
883
921
  }
922
+ /** What the model is told about an action locked out because the run read untrusted content (`'tainted'`). */
923
+ taintLockoutText(name) {
924
+ return `Action '${name}' is not allowed in this run: the run has read untrusted content, and this action sends data ` +
925
+ 'out or cannot be undone, so it cannot run until a person reviews that content. It is not broken or misconfigured, ' +
926
+ `and no change to its arguments will help. DO NOT call '${name}' again during this run; use another tool, or tell ` +
927
+ 'the user it needs a person to review the content first.';
928
+ }
884
929
  /**
885
930
  * Clears the parameter-aware failure history for an action after it succeeds, so the
886
931
  * identical-arguments rule and the consecutive-attempt budget start over.
@@ -1069,6 +1114,9 @@ export class BaseAgent {
1069
1114
  if (this._audienceLockedActions.has(summary.actionName)) {
1070
1115
  return 'audience';
1071
1116
  }
1117
+ if (this._taintLockedActions.has(summary.actionName)) {
1118
+ return 'tainted';
1119
+ }
1072
1120
  if (this._fatalActionFailures.has(summary.actionName)) {
1073
1121
  return 'fatal';
1074
1122
  }
@@ -1132,6 +1180,8 @@ export class BaseAgent {
1132
1180
  return `[CRITICAL/NOT_AVAILABLE_IN_SHARED_CONVERSATION] Action '${name}' is not available in this shared conversation: what it ` +
1133
1181
  `returns could not be limited to what everyone in it may see ("${summary.message}"). It is not broken or misconfigured. ` +
1134
1182
  `DO NOT call '${name}' again during this run. Use another tool, or answer from what you already have.`;
1183
+ case 'tainted':
1184
+ return `[CRITICAL/NOT_ALLOWED_AFTER_UNTRUSTED_CONTENT] ${this.taintLockoutText(name)}`;
1135
1185
  case 'fatal':
1136
1186
  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.`;
1137
1187
  case 'attempts-exhausted':
@@ -1209,6 +1259,29 @@ export class BaseAgent {
1209
1259
  this._taintedSources.push({ stepNumber, sourceName, trustLevel });
1210
1260
  }
1211
1261
  }
1262
+ /**
1263
+ * Starts a run tainted when it executes a task-graph node whose input is tainted
1264
+ * (`ExecuteAgentParams.SecurityEnvelope.IsRunTainted`): the node's input derives from untrusted content no
1265
+ * completed Human step reviewed, so the run is tainted before it reads anything itself, exactly as the run
1266
+ * that ingested the content was. Private: a security seed is not an extension point, and an override that
1267
+ * skipped it would start a tainted run clean.
1268
+ */
1269
+ seedTaintFromSecurityEnvelope(params) {
1270
+ if (params.SecurityEnvelope?.IsRunTainted === true) {
1271
+ this.recordTaintedSource(0, 'task-graph:security-envelope', 'Untrusted');
1272
+ }
1273
+ }
1274
+ /**
1275
+ * Starts a sub-agent run tainted when its parent, running outside any task graph, was tainted
1276
+ * (`ExecuteAgentParams.ParentRunTainted`): it works from the parent's context. A sub-agent of a graph
1277
+ * node is seeded through its envelope instead ({@link seedTaintFromSecurityEnvelope}). Private for
1278
+ * the same reason.
1279
+ */
1280
+ seedTaintFromParentRun(params) {
1281
+ if (params.ParentRunTainted === true) {
1282
+ this.recordTaintedSource(0, 'parent-run', 'Untrusted');
1283
+ }
1284
+ }
1212
1285
  /**
1213
1286
  * Folds a finished sub-agent's tainted sources into this run's, attributed to the sub-agent step,
1214
1287
  * so delegating a web search taints the parent exactly as searching itself would. Runs whether or
@@ -1611,6 +1684,15 @@ export class BaseAgent {
1611
1684
  get scratchpadManager() {
1612
1685
  return this._scratchpadManager;
1613
1686
  }
1687
+ /**
1688
+ * The current run's {@link AIPromptExecutionScope} (its user, provider, configuration, runtime API
1689
+ * keys and credential scope), set when the run starts, or undefined before one has. A subclass that
1690
+ * asks a decision or runs a prompt outside the agent's own turn passes it on, so the call runs on
1691
+ * the run's keys and configuration rather than the platform's.
1692
+ */
1693
+ get RunExecutionScope() {
1694
+ return this._runExecutionScope;
1695
+ }
1614
1696
  /** The longest the catalog narrowing decision may take before the run shows the full catalog. */
1615
1697
  static { this.CATALOG_NARROWING_TIMEOUT_MS = 30000; }
1616
1698
  /** The skills activated so far in this run (requested or self-activated), in activation order. */
@@ -1771,7 +1853,7 @@ export class BaseAgent {
1771
1853
  }
1772
1854
  try {
1773
1855
  // Load preloaded data using the singleton service
1774
- const preloadedResult = await AgentDataPreloader.Instance.PreloadAgentData(params.agent.ID, params.contextUser, this._agentRun?.ID);
1856
+ const preloadedResult = await AgentDataPreloader.Instance.PreloadAgentData(params.agent.ID, params.contextUser, this._agentRun?.ID, params.provider || this._activeProvider);
1775
1857
  const totalSources = Object.keys(preloadedResult.data).length +
1776
1858
  Object.keys(preloadedResult.context).length +
1777
1859
  Object.keys(preloadedResult.payload).length;
@@ -1820,37 +1902,34 @@ export class BaseAgent {
1820
1902
  this.logStatus(`📭 No data sources configured for agent '${params.agent.Name}'`, true, params);
1821
1903
  return; // No step needed when there are no data sources at all
1822
1904
  }
1823
- // Create a step entity to track data preloading in the agent run
1824
- const stepEntity = await this.createStepEntity({
1825
- stepType: 'Validation',
1826
- stepName: 'Data Source Preloading',
1827
- contextUser: params.contextUser
1828
- });
1829
- // Surface any data source failures in the agent run step and agent run record
1830
- if (preloadedResult.failedSources.length > 0) {
1905
+ const hasFailures = preloadedResult.failedSources.length > 0;
1906
+ let warningMessage;
1907
+ if (hasFailures) {
1831
1908
  const failureDetails = preloadedResult.failedSources
1832
1909
  .map(f => `${f.name}${f.entityName ? ` (Entity: ${f.entityName})` : ''}: ${f.errorMessage}`)
1833
1910
  .join('; ');
1834
- const warningMessage = `${preloadedResult.failedSources.length} data source(s) failed to load: ${failureDetails}`;
1835
- // Finalize step as completed but with error details captured
1836
- await this.finalizeStepEntity(stepEntity, true, warningMessage, {
1837
- loadedSources: preloadedResult.loadedSources,
1838
- failedSources: preloadedResult.failedSources
1839
- });
1840
- // Append warning to the agent run's ErrorMessage for top-level visibility
1841
- if (this._agentRun) {
1842
- const existing = this._agentRun.ErrorMessage || '';
1843
- this._agentRun.ErrorMessage = existing
1844
- ? `${existing}\n\n[Data Preloading Warning] ${warningMessage}`
1845
- : `[Data Preloading Warning] ${warningMessage}`;
1846
- await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
1847
- }
1911
+ warningMessage = `${preloadedResult.failedSources.length} data source(s) failed to load: ${failureDetails}`;
1848
1912
  }
1849
- else {
1850
- // All sources loaded successfully
1851
- await this.finalizeStepEntity(stepEntity, true, undefined, {
1852
- loadedSources: preloadedResult.loadedSources
1853
- });
1913
+ // Record data preloading in a single INSERT now that its outcome is already known
1914
+ await this.createStepEntity({
1915
+ stepType: 'Validation',
1916
+ stepName: 'Data Source Preloading',
1917
+ contextUser: params.contextUser,
1918
+ completed: {
1919
+ success: true,
1920
+ errorMessage: warningMessage,
1921
+ outputData: hasFailures
1922
+ ? { loadedSources: preloadedResult.loadedSources, failedSources: preloadedResult.failedSources }
1923
+ : { loadedSources: preloadedResult.loadedSources }
1924
+ }
1925
+ });
1926
+ // Append warning to the agent run's ErrorMessage for top-level visibility
1927
+ if (hasFailures && this._agentRun && warningMessage) {
1928
+ const existing = this._agentRun.ErrorMessage || '';
1929
+ this._agentRun.ErrorMessage = existing
1930
+ ? `${existing}\n\n[Data Preloading Warning] ${warningMessage}`
1931
+ : `[Data Preloading Warning] ${warningMessage}`;
1932
+ await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
1854
1933
  }
1855
1934
  }
1856
1935
  catch (error) {
@@ -1917,6 +1996,13 @@ export class BaseAgent {
1917
1996
  return 2 * 60 * 60 * 1000;
1918
1997
  }
1919
1998
  async Execute(params) {
1999
+ // A run is server work even when a client's own request started it (a request answered through the
2000
+ // API resumes its agent without waiting): the async scope would otherwise carry the client's CRUD
2001
+ // boundary into the run, and a save the run makes would read as that person's own act (a task-graph
2002
+ // Human step's completer, an agent request's responder).
2003
+ return ServerOperationScopeManager.Instance.RunAsServerWork(() => this.executeRun(params));
2004
+ }
2005
+ async executeRun(params) {
1920
2006
  // Initialize or inherit the shared root-tree cumulative budget before any shallow clone of
1921
2007
  // `params` occurs so that callers, parent agents, and child runs share one object reference.
1922
2008
  this._treeBudget = undefined;
@@ -1943,7 +2029,10 @@ export class BaseAgent {
1943
2029
  // `RunActionParams.AbortSignal` (see ActionEngine.RunAction) and are
1944
2030
  // unaffected by this wrapper — their timeout budget is independent.
1945
2031
  // =====================================================================================
1946
- const agentTimeoutMS = params.maxExecutionTimeMs ?? this.DefaultAgentTimeoutMS;
2032
+ const configuredMaxTimeMs = params.agent?.MaxTimePerRun != null && params.agent.MaxTimePerRun > 0
2033
+ ? params.agent.MaxTimePerRun * 1000
2034
+ : undefined;
2035
+ const agentTimeoutMS = params.maxExecutionTimeMs ?? configuredMaxTimeMs ?? this.DefaultAgentTimeoutMS;
1947
2036
  const upstreamToken = params.cancellationToken;
1948
2037
  const timeoutController = new AbortController();
1949
2038
  const relayUpstreamAbort = () => {
@@ -2048,12 +2137,18 @@ export class BaseAgent {
2048
2137
  // would otherwise serialize artifact bodies into the LLM payload. Only
2049
2138
  // the manifest (injected via _ARTIFACT_MANIFEST below) reaches the LLM.
2050
2139
  const inputArtifacts = wrappedParams.inputArtifacts;
2140
+ this._artifactToolManager.Initialize(inputArtifacts ?? [], {
2141
+ contextUser: params.contextUser,
2142
+ provider: this.ProviderToUse,
2143
+ getAgentRun: () => this._agentRun,
2144
+ agentName: params.agent?.Name ?? undefined,
2145
+ workspaceEnabled: true,
2146
+ });
2051
2147
  if (inputArtifacts?.length) {
2052
- this._artifactToolManager.Initialize(inputArtifacts);
2053
2148
  this.logStatus(`[ArtifactTools] Initialized with ${inputArtifacts.length} artifact(s): ${inputArtifacts.map(a => `${a.typeName}:"${a.name}"`).join(', ')}`, true, params);
2054
2149
  }
2055
2150
  else {
2056
- this.logStatus(`[ArtifactTools] No input artifacts found for this run`, true, params);
2151
+ this.logStatus(`[ArtifactTools] Workspace enabled with 0 initial input artifacts`, true, params);
2057
2152
  }
2058
2153
  // Initialize starting payload — must complete before AgentRun creation since the
2059
2154
  // run record stores the starting payload snapshot.
@@ -2106,7 +2201,7 @@ export class BaseAgent {
2106
2201
  if (this._agentRun) {
2107
2202
  this._agentRun.Status = 'Failed';
2108
2203
  this._agentRun.ErrorMessage = bindingError;
2109
- await this._agentRun.Save();
2204
+ this.releaseFinishedRun(await this._agentRun.Save());
2110
2205
  }
2111
2206
  throw new Error(bindingError);
2112
2207
  }
@@ -2128,6 +2223,8 @@ export class BaseAgent {
2128
2223
  this._resolvedHandoffTarget = null;
2129
2224
  this._lastSubAgentArtifactDirective = undefined;
2130
2225
  this._taintedSources = [];
2226
+ this.seedTaintFromSecurityEnvelope(params);
2227
+ this.seedTaintFromParentRun(params);
2131
2228
  this._messageLifecycleCallback = params.onMessageLifecycle;
2132
2229
  this._catalogNarrowing = undefined;
2133
2230
  this._openingRequest = OpeningRequestText(params.conversationMessages);
@@ -2331,6 +2428,12 @@ export class BaseAgent {
2331
2428
  // requests unasked. The terminate path has already logged and cleared its own.
2332
2429
  this.skipHeldDecisions(params, this.runEndForHeldDecisions());
2333
2430
  this.releasePerRunDataCache();
2431
+ try {
2432
+ await this._artifactToolManager.NotifyRunCompleted();
2433
+ }
2434
+ catch (presenceErr) {
2435
+ this.logError(presenceErr, { category: 'ArtifactPresenceExit' });
2436
+ }
2334
2437
  await this.finalizeRun(this.deriveRunOutcome());
2335
2438
  // The run is over: a later direct ExecuteSingleAction resolves the scope and the audience from its own params.
2336
2439
  this.clearRunBoundState();
@@ -2419,17 +2522,13 @@ export class BaseAgent {
2419
2522
  return AgentAudienceAddsReader(params.Audience, params.contextUser?.ID);
2420
2523
  }
2421
2524
  /**
2422
- * Why this run is not offered task graphs and refuses one the model writes, or null when it may use them — the one
2423
- * predicate, so every condition that withholds graphs is added in one place. A graph runs outside the run: its
2424
- * action nodes are dispatched by the task-graph runner (MJServer's `TaskGraphActionRunner`) with no `Audience`,
2425
- * no `RunScope` and no run `Context`, outside {@link ExecuteSingleAction}, and an agent node starts a run
2426
- * (`TaskGraphAgentRunner`) that carries neither the audience nor the scope. So graphs are withheld when the
2427
- * audience adds a reader, and when the run's validated scope carries a tenant or a secondary dimension
2428
- * (`ActionRunScopeIsBounded`): a model-written Scoped Search node would search outside the run's tenant, and an
2429
- * agent node would drop it. Likewise when the host assigned the run's search scopes (`SearchScopeIDs`): a graph's
2430
- * Scoped Search node would fall back to the agent's own search access.
2525
+ * What this run carries that a graph would have to carry too, or null when nothing: an audience that adds a
2526
+ * reader, host-assigned search scopes, a tenant or secondary dimension (`ActionRunScopeIsBounded`), bound
2527
+ * action parameters, the caller's tenant context, or taint. A graph runs outside the run — its nodes are claimed later
2528
+ * by a dispatcher, as a background worker — so each of these is lost unless the graph's security envelope
2529
+ * carries it.
2431
2530
  */
2432
- taskGraphWithholdingReason(params) {
2531
+ taskGraphConstraint(params) {
2433
2532
  if (this.runAudienceAddsReader(params)) {
2434
2533
  return 'a run with an audience';
2435
2534
  }
@@ -2437,7 +2536,40 @@ export class BaseAgent {
2437
2536
  if (scope?.SearchScopeIDs?.length) {
2438
2537
  return 'a run with host-assigned search scopes';
2439
2538
  }
2440
- return ActionRunScopeIsBounded(scope) ? 'a tenant-scoped run' : null;
2539
+ if (ActionRunScopeIsBounded(scope)) {
2540
+ return 'a tenant-scoped run';
2541
+ }
2542
+ if (this.hasBoundActionParams(params.boundActionParams)) {
2543
+ return 'a run with bound action parameters';
2544
+ }
2545
+ if (params.contextUser?.TenantContext) {
2546
+ return 'a run with a tenant context';
2547
+ }
2548
+ // Taint alone is a constraint too: a graph is the run's work continued elsewhere, and only an
2549
+ // envelope-carrying submitter takes the taint along, so its nodes still refuse egress actions.
2550
+ return this.IsRunTainted || params.SecurityEnvelope?.IsRunTainted === true ? 'a run that ingested untrusted content' : null;
2551
+ }
2552
+ /**
2553
+ * Why this run is not offered task graphs and refuses one the model writes, or null when it may use them — the one
2554
+ * predicate, read by the prompt (`promptWithholding`) and by {@link executeTasksStep} alike, so the two cannot
2555
+ * disagree. A constrained run ({@link taskGraphConstraint}) may use graphs only when the registered submitter
2556
+ * enforces security envelopes (`TaskGraphSubmitter.SupportsSecurityEnvelope`): then the envelope carries the
2557
+ * audience, the validated run scope (tenant, dimensions and search scopes), the bound parameters, the caller's
2558
+ * tenant context and the taint into every node. Nothing the caller passes opens this gate. What the envelope
2559
+ * cannot carry keeps the refusal: a malformed audience, and a tenant context JSON would change.
2560
+ */
2561
+ taskGraphWithholdingReason(params) {
2562
+ const constraint = this.taskGraphConstraint(params);
2563
+ if (!constraint) {
2564
+ return null;
2565
+ }
2566
+ if (GetTaskGraphSubmitter()?.SupportsSecurityEnvelope !== true) {
2567
+ return constraint;
2568
+ }
2569
+ if (AgentAudienceProblem(params.Audience) !== null) {
2570
+ return 'a run with an audience';
2571
+ }
2572
+ return TenantContextCarryProblem(params.contextUser?.TenantContext) ? 'a run whose tenant context cannot be carried into a task graph' : null;
2441
2573
  }
2442
2574
  /** Whether this run withholds task graphs ({@link taskGraphWithholdingReason}). */
2443
2575
  runWithholdsTaskGraphs(params) {
@@ -2756,6 +2888,10 @@ export class BaseAgent {
2756
2888
  // CreateBridgeRealtimeSession (the LiveKit / telephony factory) passes no apiKeys today.
2757
2889
  APIKeys: params.apiKeys,
2758
2890
  CredentialScope: params.CredentialScope,
2891
+ // The run's validated scope and active skills, built here on the server (never read from the session's
2892
+ // Config), so the session's direct tool calls and delegated runs carry them (#5624).
2893
+ RunScope: this.runScopeFor(params),
2894
+ ActiveSkillIDs: this.activeSkillIDsForRun(params),
2759
2895
  AgentSessionID: params.data?.agentSessionId ?? '',
2760
2896
  PreferredModelID: modelID,
2761
2897
  ConfigOverridesJson: BuildRealtimeOverridesJson(modelID, voice) ?? undefined,
@@ -3133,7 +3269,8 @@ export class BaseAgent {
3133
3269
  }
3134
3270
  try {
3135
3271
  const requestText = this.parseDelegateRequestText(request.Arguments);
3136
- const runner = new AgentRunner(params.provider || this._activeProvider);
3272
+ const effectiveProvider = params.provider || this._activeProvider;
3273
+ const runner = new AgentRunner(effectiveProvider);
3137
3274
  const result = await runner.RunAgent({
3138
3275
  agent: targetAgent,
3139
3276
  conversationMessages: [{ role: 'user', content: requestText }],
@@ -3158,12 +3295,21 @@ export class BaseAgent {
3158
3295
  // host-level onProgress the parent execution carries.
3159
3296
  onProgress: this.combineProgressCallbacks(request.OnProgress, params.onProgress)
3160
3297
  });
3298
+ const artifacts = await CollectDelegatedRunArtifactsSafely({
3299
+ Result: result,
3300
+ ContextUser: params.contextUser,
3301
+ Provider: effectiveProvider,
3302
+ ProcessPayloadArtifacts: (r) => runner.ProcessAgentArtifacts(r, undefined, undefined, params.contextUser, effectiveProvider),
3303
+ logLabel: 'BaseAgent.delegateRealtimeToTarget',
3304
+ });
3161
3305
  return {
3162
3306
  CallID: request.CallID,
3163
3307
  Success: result.success,
3164
3308
  Output: result.success
3165
3309
  ? (result.agentRun?.Message || 'The target agent completed the request.')
3166
- : (result.agentRun?.ErrorMessage || 'The target agent failed to complete the request.')
3310
+ : (result.agentRun?.ErrorMessage || 'The target agent failed to complete the request.'),
3311
+ ...(result.agentRun?.ID ? { RunID: result.agentRun.ID } : {}),
3312
+ ...(artifacts ? { Artifacts: artifacts } : {}),
3167
3313
  };
3168
3314
  }
3169
3315
  catch (error) {
@@ -3220,7 +3366,7 @@ export class BaseAgent {
3220
3366
  parseDelegateRequestText(argumentsJson) {
3221
3367
  try {
3222
3368
  const parsed = JSON.parse(argumentsJson);
3223
- if (typeof parsed.request === 'string') {
3369
+ if (parsed && typeof parsed === 'object' && typeof parsed.request === 'string') {
3224
3370
  return parsed.request;
3225
3371
  }
3226
3372
  }
@@ -3253,10 +3399,12 @@ export class BaseAgent {
3253
3399
  try {
3254
3400
  const agentAction = { name: action.Name, params: this.parseRealtimeToolParams(call.Arguments) };
3255
3401
  const result = await this.ExecuteSingleAction(params, agentAction, action, params.contextUser);
3402
+ const actionArtifacts = ExtractDirectActionArtifacts(action.Name, result.Success, result.Params);
3256
3403
  return {
3257
3404
  CallID: call.CallID,
3258
3405
  Success: result.Success,
3259
- Output: result.Message || (result.Success ? 'Tool completed.' : 'Tool failed.')
3406
+ Output: result.Message || (result.Success ? 'Tool completed.' : 'Tool failed.'),
3407
+ ...(actionArtifacts ? { Artifacts: actionArtifacts } : {}),
3260
3408
  };
3261
3409
  }
3262
3410
  catch (error) {
@@ -3273,7 +3421,7 @@ export class BaseAgent {
3273
3421
  parseRealtimeToolParams(argumentsJson) {
3274
3422
  try {
3275
3423
  const parsed = JSON.parse(argumentsJson);
3276
- if (parsed && typeof parsed === 'object') {
3424
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
3277
3425
  return parsed;
3278
3426
  }
3279
3427
  }
@@ -3640,6 +3788,29 @@ export class BaseAgent {
3640
3788
  // the base class doesn't do anything here, this allows sub-classes
3641
3789
  // to do specialized initialization of the starting payload
3642
3790
  }
3791
+ /**
3792
+ * Feeds one executed decision (never a prompt turn) to the repeated-failing-step guard (#4832).
3793
+ * The consecutive-failed-steps counter cannot see a model that re-issues the same failing step:
3794
+ * the prompt between two failures returns a non-Failed decision and resets it. When the same
3795
+ * decision has failed {@link MAX_REPEATED_FAILING_STEP} times in a row, `nextStep` is turned
3796
+ * into a terminating Failed step naming the step type and the last error.
3797
+ */
3798
+ checkRepeatedFailingStep(params, tracker, executedDecision, nextStep) {
3799
+ const count = tracker.Observe(executedDecision, nextStep);
3800
+ if (count < MAX_REPEATED_FAILING_STEP) {
3801
+ return;
3802
+ }
3803
+ const lastError = FailingStepError(nextStep);
3804
+ const message = `Agent repeated the same failing ${executedDecision.step} step ${count} times. Last error: ${lastError}`;
3805
+ this.logError(`⛔ Agent '${params.agent.Name}': ${message}`, {
3806
+ agent: params.agent,
3807
+ category: 'ExecutionSafetyNet',
3808
+ metadata: { repeatedFailures: count, stepType: executedDecision.step, lastError }
3809
+ });
3810
+ nextStep.step = 'Failed';
3811
+ nextStep.terminate = true;
3812
+ nextStep.errorMessage = message;
3813
+ }
3643
3814
  /**
3644
3815
  * Executes the agent's internal logic.
3645
3816
  *
@@ -3664,6 +3835,9 @@ export class BaseAgent {
3664
3835
  let stepCount = 0;
3665
3836
  let consecutiveFailedSteps = 0;
3666
3837
  let consecutiveUnproductiveRetries = 0;
3838
+ // Model-driven types only: a Flow graph may re-run a failing node on purpose (see
3839
+ // BaseAgentType.UsesActionCircuitBreaker), and has no model that could repeat itself.
3840
+ const repeatedFailures = this.AgentTypeInstance?.UsesActionCircuitBreaker === false ? null : new RepeatedFailingStepTracker();
3667
3841
  while (continueExecution) {
3668
3842
  // Check for cancellation before each step
3669
3843
  if (params.cancellationToken?.aborted) {
@@ -3679,6 +3853,7 @@ export class BaseAgent {
3679
3853
  }
3680
3854
  // Execute the current step based on previous decision or initial prompt
3681
3855
  this.logStatus(`🔄 Executing step ${stepCount + 1} for agent '${params.agent.Name}'`, true, params);
3856
+ const executedDecision = currentNextStep;
3682
3857
  const nextStep = await this.executeNextStep(params, config, currentNextStep, stepCount);
3683
3858
  stepCount++;
3684
3859
  // A failed step cut short by a cancellation is not a failure: end the run as cancelled
@@ -3714,6 +3889,9 @@ export class BaseAgent {
3714
3889
  else if (nextStep.step !== 'Failed') {
3715
3890
  consecutiveFailedSteps = 0;
3716
3891
  }
3892
+ if (repeatedFailures && executedDecision && !IsPromptTurnStep(executedDecision) && !nextStep.terminate) {
3893
+ this.checkRepeatedFailingStep(params, repeatedFailures, executedDecision, nextStep);
3894
+ }
3717
3895
  // Track consecutive *unproductive* retries to prevent infinite loops that the
3718
3896
  // consecutive-failed-steps net above cannot catch. A model that repeatedly returns
3719
3897
  // output we can't parse/validate (e.g. conversational prose instead of the required
@@ -4004,7 +4182,7 @@ export class BaseAgent {
4004
4182
  return;
4005
4183
  }
4006
4184
  const promptParams = this.decisionDiscoveryPromptParams(agent, overrides);
4007
- const outcome = await this.runDecisionDiscovery(agent, contextUser, promptParams, HostAllowedAgentIDs(data));
4185
+ const outcome = await this.runDecisionDiscovery(agent, contextUser, promptParams, HostAllowedAgentIDs(data), ReadEdgePreDiscoveryHint(data));
4008
4186
  if (outcome.Injected && outcome.Message) {
4009
4187
  conversationMessages.unshift({ role: 'system', content: outcome.Message });
4010
4188
  this.logStatus(`Decision discovery suggested '${outcome.Answer?.Agent.Name}' to '${agent.Name}'`, true);
@@ -4055,12 +4233,12 @@ export class BaseAgent {
4055
4233
  * answer from a model with no discovery calibration is warned about once per model, because
4056
4234
  * then discovery can never suggest anything.
4057
4235
  */
4058
- async runDecisionDiscovery(agent, contextUser, promptParams, hostAllowedIDs) {
4236
+ async runDecisionDiscovery(agent, contextUser, promptParams, hostAllowedIDs, rawEdgeHint) {
4059
4237
  const promptName = typeof promptParams.decisionPromptName === 'string'
4060
4238
  ? promptParams.decisionPromptName
4061
4239
  : AgentDecisionService.DEFAULT_PROMPT_NAME;
4062
4240
  const step = await this.startDecisionDiscoveryStep(contextUser, promptName);
4063
- const outcome = await this.boundDecisionDiscovery(signal => this.discoverAgent(agent, contextUser, promptName, hostAllowedIDs, signal), step);
4241
+ const outcome = await this.boundDecisionDiscovery(signal => this.discoverAgent(agent, contextUser, promptName, hostAllowedIDs, rawEdgeHint, signal), step);
4064
4242
  await this.finishDecisionDiscoveryStep(step, outcome);
4065
4243
  if (!outcome.Succeeded) {
4066
4244
  this.warnDecisionDiscovery(agent, outcome.Reason ?? 'unknown error');
@@ -4089,8 +4267,8 @@ export class BaseAgent {
4089
4267
  BaseAgent._uncalibratedDiscoveryModelsWarned.add(model);
4090
4268
  LogErrorEx({
4091
4269
  message: `Decision discovery answered by ${model} suggests nothing: the model has no discovery calibration `
4092
- + '(DECISION_DISCOVERY_CALIBRATION), so its answers are treated as unsure. Fit one with the agent-discovery '
4093
- + 'Decision Eval, or check that the model was not renamed or moved to another version.',
4270
+ + "(use 'agent-discovery' in its ModelConfiguration.Decision.Calibrations), so its answers are treated as unsure. "
4271
+ + 'Fit one with the fit-decision-calibration rig, or check that the model was not renamed or moved to another version.',
4094
4272
  severity: 'warning',
4095
4273
  category: 'DecisionDiscovery',
4096
4274
  });
@@ -4139,10 +4317,47 @@ export class BaseAgent {
4139
4317
  * The discovery itself: the options, rebuilt from the permitted catalog, then one decision about
4140
4318
  * the opening request, and what its answer means. Never throws.
4141
4319
  */
4142
- async discoverAgent(agent, contextUser, promptName, hostAllowedIDs, signal) {
4320
+ async discoverAgent(agent, contextUser, promptName, hostAllowedIDs, rawEdgeHint, signal) {
4143
4321
  try {
4144
- const { Options: options, Error: optionsError, ...rest } = await this.decisionDiscoveryOptionSet(agent, contextUser, promptName, hostAllowedIDs);
4145
- const sizes = { ...rest, OptionCount: options.length };
4322
+ const runnableAgents = await DecisionDiscoveryRunnableAgents(AIEngine.Instance.Agents, contextUser);
4323
+ const catalog = KeepHostAllowedAgents(DecisionDiscoveryCatalog(runnableAgents, agent.ID), hostAllowedIDs);
4324
+ const fullOptions = DecisionDiscoveryOptions(catalog);
4325
+ const declaredCap = DecisionPromptOptionCap(AIEngine.Instance, promptName);
4326
+ const optionLimit = DecisionOptionLimit(declaredCap);
4327
+ if (fullOptions.length < DECISION_DISCOVERY_MIN_OPTIONS) {
4328
+ return {
4329
+ Injected: false,
4330
+ Succeeded: true,
4331
+ Reason: `there are ${fullOptions.length} agents to choose from, fewer than the ${DECISION_DISCOVERY_MIN_OPTIONS} a suggestion needs, so nothing was asked`,
4332
+ CatalogSize: catalog.length,
4333
+ HostAllowListSize: hostAllowedIDs?.length,
4334
+ WithoutDescription: AgentsWithoutDescription(catalog),
4335
+ OptionCount: fullOptions.length,
4336
+ OptionLimit: optionLimit,
4337
+ DeclaredOptionCap: declaredCap,
4338
+ };
4339
+ }
4340
+ // Server remains guard of truth: verify every hinted ID against the server-authoritative
4341
+ // permitted, runnable, directly-discoverable, host-allowed catalog before any fast-path or narrowing.
4342
+ const edgeEval = EvaluateEdgePreDiscoveryHint(rawEdgeHint, fullOptions);
4343
+ if (edgeEval.DirectOutcome) {
4344
+ return {
4345
+ ...edgeEval.DirectOutcome,
4346
+ CatalogSize: catalog.length,
4347
+ HostAllowListSize: hostAllowedIDs?.length,
4348
+ WithoutDescription: AgentsWithoutDescription(catalog),
4349
+ OptionCount: fullOptions.length,
4350
+ OptionLimit: optionLimit,
4351
+ DeclaredOptionCap: declaredCap,
4352
+ };
4353
+ }
4354
+ const { Options: options, Error: optionsError, ...rest } = await this.decisionDiscoveryOptionSet(agent, contextUser, promptName, hostAllowedIDs, runnableAgents, declaredCap, edgeEval.SanitizedHint?.CandidateAgentIds);
4355
+ const sizes = {
4356
+ ...rest,
4357
+ OptionCount: options.length,
4358
+ EdgeHintUsed: (edgeEval.SanitizedHint?.CandidateAgentIds.length ?? 0) > 0 && fullOptions.length > optionLimit,
4359
+ EdgeHintDiscardedCount: edgeEval.DiscardedCount,
4360
+ };
4146
4361
  if (optionsError) {
4147
4362
  return { ...FailedDecisionDiscovery(optionsError), ...sizes };
4148
4363
  }
@@ -4161,7 +4376,7 @@ export class BaseAgent {
4161
4376
  CancellationToken: signal,
4162
4377
  ExecutionScope: this._runExecutionScope,
4163
4378
  });
4164
- return { ...DecisionDiscoveryFromResult(result, options, DECISION_DISCOVERY_MIN_CONFIDENCE), ...sizes };
4379
+ return { ...DecisionDiscoveryFromResult(result, options, DECISION_DISCOVERY_MIN_CONFIDENCE), Source: 'decision-model', ...sizes };
4165
4380
  }
4166
4381
  catch (error) {
4167
4382
  return FailedDecisionDiscovery(error instanceof Error ? error.message : String(error));
@@ -4170,15 +4385,16 @@ export class BaseAgent {
4170
4385
  /**
4171
4386
  * The Choice's options, rebuilt on every call and never cached ({@link BuildDecisionDiscoveryOptionSet}):
4172
4387
  * from AIEngine's current catalog, the agents the user may run, the decision prompt's option cap,
4173
- * and the semantic search over the opening request when the provider can run it.
4388
+ * and the client's sanitized pre-filter or semantic search over the opening request when the provider can run it.
4174
4389
  */
4175
- async decisionDiscoveryOptionSet(agent, contextUser, promptName, hostAllowedIDs) {
4390
+ async decisionDiscoveryOptionSet(agent, contextUser, promptName, hostAllowedIDs, runnableAgents, declaredCap, preferredCandidateIDs) {
4176
4391
  const provider = this.ProviderToUse;
4177
4392
  return BuildDecisionDiscoveryOptionSet({
4178
- Agents: await DecisionDiscoveryRunnableAgents(AIEngine.Instance.Agents, contextUser),
4393
+ Agents: runnableAgents ?? await DecisionDiscoveryRunnableAgents(AIEngine.Instance.Agents, contextUser),
4179
4394
  RunningAgentID: agent.ID,
4180
4395
  HostAllowedIDs: hostAllowedIDs,
4181
- DeclaredCap: DecisionPromptOptionCap(AIEngine.Instance, promptName),
4396
+ DeclaredCap: declaredCap ?? DecisionPromptOptionCap(AIEngine.Instance, promptName),
4397
+ PreferredCandidateIDs: preferredCandidateIDs,
4182
4398
  Search: CanSearchEntities(provider) ? DecisionDiscoveryAgentSearch(provider, this._openingRequest, contextUser) : undefined,
4183
4399
  });
4184
4400
  }
@@ -4242,6 +4458,15 @@ export class BaseAgent {
4242
4458
  tokensUsed: result?.tokensUsed,
4243
4459
  model: result?.DecisionResult?.ResolvedModel ?? result?.modelInfo?.modelName,
4244
4460
  promptRunId: result?.promptRun?.ID,
4461
+ ...(outcome.Source === 'edge-pre-discovery' ? { source: outcome.Source } : {}),
4462
+ ...(outcome.EdgeHintUsed || (outcome.EdgeHintDiscardedCount ?? 0) > 0
4463
+ ? {
4464
+ edgePreDiscovery: {
4465
+ used: outcome.EdgeHintUsed ?? false,
4466
+ discardedCount: outcome.EdgeHintDiscardedCount ?? 0,
4467
+ },
4468
+ }
4469
+ : {}),
4245
4470
  });
4246
4471
  }
4247
4472
  /** Logs that decision discovery failed, so nothing was suggested. */
@@ -4566,7 +4791,7 @@ export class BaseAgent {
4566
4791
  }
4567
4792
  // Counted only on the native path: null means "envelope", which is different from a
4568
4793
  // native turn where the model chose not to call anything (0).
4569
- if (mode === 'Native' || mode === 'NativeFallback' || mode === 'NativeImplicit') {
4794
+ if (mode === 'Native' || mode === 'NativeFallback' || mode === 'NativeImplicit' || mode === 'NativeRecovered') {
4570
4795
  const message = promptResult?.chatResult?.data?.choices?.[0]?.message;
4571
4796
  const callCount = message?.toolCalls?.length ?? 0;
4572
4797
  stepEntity.NativeToolCallCount = callCount;
@@ -4823,6 +5048,8 @@ export class BaseAgent {
4823
5048
  consultEnabled: this.isSubAgentConsultEnabledForSubAgent(params.agent, sa),
4824
5049
  ...(presetNames.length > 0 ? { presetNames } : {})
4825
5050
  };
5051
+ }, {
5052
+ IncludeArtifactDirective: control.NativeOnly && this.isArtifactSupportEnabled(params.agent)
4826
5053
  });
4827
5054
  if (control.NativeOnly && promptParams.data) {
4828
5055
  // The template renders the tools-only prompt when this is set AND the runner resolves implicit control flow.
@@ -4869,7 +5096,7 @@ export class BaseAgent {
4869
5096
  // Each gate matches the one that renders the tool's docs, so a tool is never taught but undeclared.
4870
5097
  Scratchpad: p?.includeScratchpadDocs !== false,
4871
5098
  MemoryWrites: p?.includeMemoryWritesDocs !== false && this.memoryWriteSkip(params) === null,
4872
- ArtifactTools: p?.includeArtifactToolsDocs !== false && this._artifactToolManager.HasArtifacts(),
5099
+ ArtifactTools: p?.includeArtifactToolsDocs !== false && this._artifactToolManager.IsWorkspaceEnabled(),
4873
5100
  ConversationTools: p?.includeConversationToolsDocs !== false && this._conversationToolManager.IsAvailable,
4874
5101
  Decisions: this.DecisionsEnabled(p) && p?.includeDecisionsDocs !== false
4875
5102
  };
@@ -5276,7 +5503,7 @@ export class BaseAgent {
5276
5503
  // via pruneAndCompactExpiredMessages — same lifecycle as action results.
5277
5504
  const artifactToolsEnabled = agentTypePromptParams?.includeArtifactToolsDocs !== false;
5278
5505
  promptParams.data['_ARTIFACTS_ENABLED'] = this.isArtifactSupportEnabled(params.agent);
5279
- if (artifactToolsEnabled && this._artifactToolManager.HasArtifacts()) {
5506
+ if (artifactToolsEnabled && this._artifactToolManager.IsWorkspaceEnabled()) {
5280
5507
  promptParams.data['_ARTIFACT_MANIFEST'] = this._artifactToolManager.ToManifestString();
5281
5508
  if (this.GetNativeControlConfig(params).NativeOnly) {
5282
5509
  // The native-only prompt (picked at render time) names the artifact_tool tool instead of artifactToolCalls.
@@ -5284,7 +5511,7 @@ export class BaseAgent {
5284
5511
  }
5285
5512
  promptParams.data['_ARTIFACT_TOOLS'] = this._artifactToolManager.GetToolDocumentation();
5286
5513
  promptParams.data['_ARTIFACT_TOOL_SUMMARY'] = this._artifactToolManager.GetSummary();
5287
- this.logStatus(`[ArtifactTools] Injected manifest into prompt: ${this._artifactToolManager.GetSummary()}`, true, params);
5514
+ this.logStatus(`[ArtifactTools] Injected workspace/manifest into prompt: ${this._artifactToolManager.GetSummary() || 'workspace tools ready'}`, true, params);
5288
5515
  }
5289
5516
  else if (this._artifactToolManager.HasArtifacts()) {
5290
5517
  this.logStatus(`[ArtifactTools] Artifacts present but tools disabled by agent config (includeArtifactToolsDocs=false)`, true, params);
@@ -5467,7 +5694,7 @@ export class BaseAgent {
5467
5694
  this._lastVolatileStateMessage = rebuilt;
5468
5695
  // The fingerprints were taken before the swap; without this, an append-only history
5469
5696
  // reads the swapped message as changed next turn and drops the reasoning after it.
5470
- if (promptParams.conversationMessages) {
5697
+ if (this._lastSentFingerprints !== undefined && promptParams.conversationMessages) {
5471
5698
  this._lastSentFingerprints = promptParams.conversationMessages.map(BaseAgent.messageFingerprint);
5472
5699
  }
5473
5700
  }
@@ -5488,6 +5715,10 @@ export class BaseAgent {
5488
5715
  * are not a change.
5489
5716
  */
5490
5717
  dropReasoningBehindChangedHistory(params, outgoing, promptParams) {
5718
+ if (!this.shouldTrackSentFingerprints(outgoing)) {
5719
+ this._lastSentFingerprints = undefined;
5720
+ return outgoing;
5721
+ }
5491
5722
  const fingerprints = outgoing.map(BaseAgent.messageFingerprint);
5492
5723
  const previous = this._lastSentFingerprints;
5493
5724
  this._lastSentFingerprints = fingerprints;
@@ -5527,6 +5758,20 @@ export class BaseAgent {
5527
5758
  return this._nativeToolBindings !== undefined
5528
5759
  && this.DriverRequiresStableReasoningPrefix(selection?.ModelSelected, selection?.vendorSelected);
5529
5760
  }
5761
+ /**
5762
+ * Returns `true` when outgoing message fingerprinting is needed to detect prefix changes
5763
+ * for replayed reasoning blocks. Skips hashing on envelope runs (`_nativeToolBindings === undefined`)
5764
+ * and on subsequent turns once a non-prefix-bound model is selected and no message carries reasoning.
5765
+ */
5766
+ shouldTrackSentFingerprints(outgoing) {
5767
+ if (this._nativeToolBindings === undefined) {
5768
+ return false;
5769
+ }
5770
+ if (this._lastModelSelectionInfo === undefined || this.replaysPrefixBoundReasoning()) {
5771
+ return true;
5772
+ }
5773
+ return outgoing.some((m) => Boolean(m.reasoning?.length));
5774
+ }
5530
5775
  /**
5531
5776
  * Keeps the system-prompt-and-tools fingerprint of the request just sent, for the next one. When
5532
5777
  * it changed, the runner sent this request without replayed reasoning; the history drops it too,
@@ -5554,9 +5799,22 @@ export class BaseAgent {
5554
5799
  }
5555
5800
  });
5556
5801
  }
5802
+ static { this._messageFingerprintCache = new WeakMap(); }
5557
5803
  /** What makes a message the same message to a provider — reasoning aside, which only this check removes. */
5558
5804
  static messageFingerprint(m) {
5559
- return JSON.stringify([m.role, m.content, m.toolCalls?.map((c) => [c.id, c.name, c.arguments])]);
5805
+ const toolCalls = m.toolCalls;
5806
+ const cached = BaseAgent._messageFingerprintCache.get(m);
5807
+ if (cached && cached.role === m.role && cached.content === m.content && cached.toolCalls === toolCalls) {
5808
+ return cached.fingerprint;
5809
+ }
5810
+ const fingerprint = JSON.stringify([m.role, m.content, toolCalls?.map((c) => [c.id, c.name, c.arguments])]);
5811
+ BaseAgent._messageFingerprintCache.set(m, {
5812
+ role: m.role,
5813
+ content: m.content,
5814
+ toolCalls,
5815
+ fingerprint,
5816
+ });
5817
+ return fingerprint;
5560
5818
  }
5561
5819
  /**
5562
5820
  * In append-only mode, restores turn 1's volatile state fragment if mode resolution
@@ -5601,9 +5859,7 @@ export class BaseAgent {
5601
5859
  * and framework-authored volatile state messages are left alone.
5602
5860
  */
5603
5861
  assembleOutgoingMessages(history, fragment, isAppendOnly = false) {
5604
- const source = isAppendOnly ? history : history.filter(m => !m.metadata?.volatileState);
5605
- const sanitized = source.map(m => (m.role === 'system' || m.metadata?.volatileState ? m : EscapeRuntimeStateTagsInMessage(m)));
5606
- return [...sanitized, fragment];
5862
+ return this._contextAssembler.AssembleOutgoingMessages(history, fragment, isAppendOnly);
5607
5863
  }
5608
5864
  /**
5609
5865
  * Determines whether the current prompt execution should use append-only trailing state retention.
@@ -5684,17 +5940,7 @@ export class BaseAgent {
5684
5940
  }
5685
5941
  /** Whether the driver serving `model` on `vendor` binds replayed reasoning to the unchanged history before it. */
5686
5942
  DriverRequiresStableReasoningPrefix(model, vendor) {
5687
- if (!model || !vendor) {
5688
- return false;
5689
- }
5690
- const engine = AIEngine.Instance;
5691
- const modelVendor = (engine.ModelVendorsByModelID?.get(NormalizeUUID(model.ID)) ?? [])
5692
- .find(mv => UUIDsEqual(mv.VendorID, vendor.ID) && engine.IsInferenceProvider(mv));
5693
- if (!modelVendor?.DriverClass) {
5694
- return false;
5695
- }
5696
- const driver = MJGlobal.Instance.ClassFactory.GetRegistration(BaseLLM, modelVendor.DriverClass)?.SubClass;
5697
- return driver?.ReplayedReasoningRequiresStablePrefix === true;
5943
+ return this._contextAssembler.DriverRequiresStableReasoningPrefix(model, vendor);
5698
5944
  }
5699
5945
  /**
5700
5946
  * Whether a model, as served by a vendor, sits behind a byte-prefix prompt cache
@@ -5710,14 +5956,7 @@ export class BaseAgent {
5710
5956
  * rows carry no flag, say) can override this rather than the mode decision above.
5711
5957
  */
5712
5958
  resolvePrefixPromptCache(model, vendor) {
5713
- if (!model) {
5714
- return false;
5715
- }
5716
- const engine = AIEngine.Instance;
5717
- const modelVendor = vendor
5718
- ? (engine.ModelVendorsByModelID?.get(NormalizeUUID(model.ID)) ?? []).find(mv => UUIDsEqual(mv.VendorID, vendor.ID) && engine.IsInferenceProvider(mv))
5719
- : undefined;
5720
- return IsPrefixPromptCache(engine.GetEffectiveModelConfiguration(model.ID, modelVendor?.ID));
5959
+ return this._contextAssembler.ResolvePrefixPromptCache(model, vendor);
5721
5960
  }
5722
5961
  /**
5723
5962
  * Builds the framework-authored `user` message that carries the loop agent's volatile state as the
@@ -5753,11 +5992,12 @@ export class BaseAgent {
5753
5992
  const includeScratchpad = agentTypePromptParams?.includeScratchpadDocs !== false;
5754
5993
  const includePayload = agentTypePromptParams?.includePayloadInPrompt !== false;
5755
5994
  const specialization = await this.resolveRelocatedSpecialization(promptParams, childPrompt, agentType, params.contextUser);
5756
- const fragment = new RuntimeStateFragmentBuilder().Build({
5995
+ const fragment = this._contextAssembler.BuildRuntimeStateFragment({
5757
5996
  DateTime: includeDateTime ? await this.resolveFragmentDateTime(promptParams) : null,
5758
5997
  Scratchpad: includeScratchpad ? this.readScratchpadFromTemplateData(data) : null,
5759
5998
  // Same value the agent type injects for the template (`payload || {}`), so both placements agree.
5760
- Payload: includePayload ? { Value: payload || {} } : null,
5999
+ Payload: payload || {},
6000
+ IncludePayload: includePayload,
5761
6001
  Specialization: specialization,
5762
6002
  });
5763
6003
  if (!fragment) {
@@ -5845,7 +6085,7 @@ export class BaseAgent {
5845
6085
  * Loop layout, or any template that embeds the payload.
5846
6086
  */
5847
6087
  templateTextEmbedsVolatileState(templateText) {
5848
- return this.volatileTemplateMarkers.some(marker => templateText.includes(marker));
6088
+ return this._contextAssembler.TemplateTextEmbedsVolatileState(templateText, this.volatileTemplateMarkers);
5849
6089
  }
5850
6090
  /**
5851
6091
  * Raw template text (placeholders intact) for an AI prompt from the cached template engine.
@@ -5903,36 +6143,20 @@ export class BaseAgent {
5903
6143
  * on every loop iteration.
5904
6144
  */
5905
6145
  async resolveFragmentDateTime(promptParams) {
5906
- const resolve = async (name) => {
5907
- const placeholder = SystemPlaceholderManager.getPlaceholders().find(p => p.name === name);
5908
- if (!placeholder) {
5909
- return null;
5910
- }
5911
- try {
5912
- const value = await placeholder.getValue(promptParams);
5913
- return value == null ? null : String(value);
5914
- }
5915
- catch (e) {
5916
- this.logError(e instanceof Error ? e : String(e), { category: 'RuntimeStateFragment', severity: 'warning', metadata: { placeholder: name } });
5917
- return null;
5918
- }
5919
- };
5920
- const [date, dayOfWeek, time] = await Promise.all([resolve(CURRENT_DATE_PLACEHOLDER), resolve(CURRENT_DAY_OF_WEEK_PLACEHOLDER), resolve(CURRENT_TIME_PLACEHOLDER)]);
5921
- if (!date || !dayOfWeek || !time) {
5922
- return null;
5923
- }
5924
- return { Date: date, DayOfWeek: dayOfWeek, Time: time };
6146
+ return this._contextAssembler.ResolveFragmentDateTime(promptParams, (error, placeholder) => {
6147
+ this.logError(error instanceof Error ? error : String(error), {
6148
+ category: 'RuntimeStateFragment',
6149
+ severity: 'warning',
6150
+ metadata: { placeholder },
6151
+ });
6152
+ });
5925
6153
  }
5926
6154
  /**
5927
6155
  * The scratchpad strings already placed in the template data by the prep step (so the fragment shows
5928
6156
  * exactly what the template would have). Null when the scratchpad is disabled or absent.
5929
6157
  */
5930
6158
  readScratchpadFromTemplateData(data) {
5931
- const notes = data[SCRATCHPAD_NOTES_PLACEHOLDER], tasks = data[SCRATCHPAD_TASKS_PLACEHOLDER], summary = data[SCRATCHPAD_TASK_SUMMARY_PLACEHOLDER];
5932
- if (typeof notes !== 'string' || typeof tasks !== 'string' || typeof summary !== 'string') {
5933
- return null;
5934
- }
5935
- return { Notes: notes, Tasks: tasks, TaskSummary: summary };
6159
+ return this._contextAssembler.ReadScratchpadFromTemplateData(data);
5936
6160
  }
5937
6161
  /**
5938
6162
  * Executes the configured prompt. Always uses the attemptJSONRepair option to try to fix LLM
@@ -6568,6 +6792,26 @@ export class BaseAgent {
6568
6792
  stepActionNamesLower.has(a.Name.trim().toLowerCase()) ||
6569
6793
  stepActionNamesSanitized.has(SanitizeToolName(a.Name))));
6570
6794
  }
6795
+ /**
6796
+ * Returns the active agents named by an agent's own active Flow steps: a `Sub-Agent` step's
6797
+ * `SubAgentID`, or the `SubAgentID` of a `ForEach`/`While` step whose `LoopBodyType` is
6798
+ * `'Sub-Agent'`. Flow agents bind sub-agents on `AIAgentStep` rather than through `ParentID`
6799
+ * or `AIAgentRelationship`, so {@link resolveSubAgentByName} needs these in scope, as
6800
+ * {@link getFlowStepActions} does for actions.
6801
+ */
6802
+ getFlowStepSubAgents(agentId) {
6803
+ if (!agentId)
6804
+ return [];
6805
+ const steps = AIEngine.Instance.GetAgentSteps?.(agentId, 'Active') ?? [];
6806
+ const ids = new UUIDSet(steps
6807
+ .filter(s => s.StepType === 'Sub-Agent'
6808
+ || ((s.StepType === 'ForEach' || s.StepType === 'While') && s.LoopBodyType === 'Sub-Agent'))
6809
+ .map(s => s.SubAgentID)
6810
+ .filter((id) => typeof id === 'string' && id.length > 0));
6811
+ if (ids.Size === 0)
6812
+ return [];
6813
+ return AIEngine.Instance.Agents.filter(a => a.Status === 'Active' && ids.Has(a.ID));
6814
+ }
6571
6815
  /**
6572
6816
  * Combines {@link getEffectiveActionsForValidation} with {@link getFlowStepActions} (deduplicated
6573
6817
  * by `ID`) so both Loop agents (strictly `AIAgentAction` / `_effectiveActions`) and Flow agents
@@ -7361,7 +7605,6 @@ export class BaseAgent {
7361
7605
  * @protected
7362
7606
  */
7363
7607
  async hasExceededAgentRunGuardrails(params, agentRun) {
7364
- const agent = params.agent;
7365
7608
  // Refresh the run's accumulated cost/token actuals before comparing them to the agent's
7366
7609
  // static limits.
7367
7610
  //
@@ -7385,98 +7628,21 @@ export class BaseAgent {
7385
7628
  if (this._agentRun === agentRun) {
7386
7629
  this.applyTokenStatsToRun(agentRun, this.calculateTokenStats());
7387
7630
  }
7388
- // Check absolute maximum iterations (safety net to prevent infinite loops)
7389
7631
  const absoluteMaxIterations = params.absoluteMaxIterations ?? BaseAgent.DEFAULT_ABSOLUTE_MAX_ITERATIONS;
7390
- if (agentRun.TotalPromptIterations != null && agentRun.TotalPromptIterations >= absoluteMaxIterations) {
7391
- return {
7392
- exceeded: true,
7393
- type: 'iterations',
7394
- limit: absoluteMaxIterations,
7395
- current: agentRun.TotalPromptIterations,
7396
- reason: `Absolute maximum iteration safety limit of ${absoluteMaxIterations} exceeded. Current iterations: ${agentRun.TotalPromptIterations}. This is a system-wide safety measure to prevent infinite loops.`
7397
- };
7398
- }
7399
- // Check cost limit
7400
- if (agent.MaxCostPerRun != null && agentRun.TotalCost != null) {
7401
- if (agentRun.TotalCost >= agent.MaxCostPerRun) {
7402
- return {
7403
- exceeded: true,
7404
- type: 'cost',
7405
- limit: agent.MaxCostPerRun,
7406
- current: agentRun.TotalCost,
7407
- reason: `Maximum cost limit of $${agent.MaxCostPerRun} exceeded. Current cost: $${agentRun.TotalCost.toFixed(4)}`
7408
- };
7409
- }
7410
- }
7411
- // Check token limit
7412
- if (agent.MaxTokensPerRun != null && agentRun.TotalTokensUsed != null) {
7413
- if (agentRun.TotalTokensUsed >= agent.MaxTokensPerRun) {
7414
- return {
7415
- exceeded: true,
7416
- type: 'tokens',
7417
- limit: agent.MaxTokensPerRun,
7418
- current: agentRun.TotalTokensUsed,
7419
- reason: `Maximum token limit of ${agent.MaxTokensPerRun} exceeded. Current tokens: ${agentRun.TotalTokensUsed}`
7420
- };
7421
- }
7422
- }
7423
- // Check iteration limit
7424
- if (agent.MaxIterationsPerRun != null && agentRun.TotalPromptIterations != null) {
7425
- if (agentRun.TotalPromptIterations >= agent.MaxIterationsPerRun) {
7426
- return {
7427
- exceeded: true,
7428
- type: 'iterations',
7429
- limit: agent.MaxIterationsPerRun,
7430
- current: agentRun.TotalPromptIterations,
7431
- reason: `Maximum iteration limit of ${agent.MaxIterationsPerRun} exceeded. Current iterations: ${agentRun.TotalPromptIterations}`
7432
- };
7433
- }
7434
- }
7435
- // Check time limit
7436
- if (agent.MaxTimePerRun != null && agentRun.StartedAt) {
7437
- const elapsedSeconds = Math.floor((Date.now() - new Date(agentRun.StartedAt).getTime()) / 1000);
7438
- if (elapsedSeconds >= agent.MaxTimePerRun) {
7439
- return {
7440
- exceeded: true,
7441
- type: 'time',
7442
- limit: agent.MaxTimePerRun,
7443
- current: elapsedSeconds,
7444
- reason: `Maximum time limit of ${agent.MaxTimePerRun} seconds exceeded. Elapsed time: ${elapsedSeconds} seconds`
7445
- };
7446
- }
7447
- }
7448
- // Check validation retry limit
7449
- if (this._generalValidationRetryCount >= BaseAgent.MAX_VALIDATION_RETRIES) {
7450
- return {
7451
- exceeded: true,
7452
- type: 'iterations', // Using iterations type since validation retries are a form of iteration
7453
- limit: BaseAgent.MAX_VALIDATION_RETRIES,
7454
- current: this._generalValidationRetryCount,
7455
- reason: `Maximum validation retries of ${BaseAgent.MAX_VALIDATION_RETRIES} exceeded. The agent is unable to produce valid output after ${this._generalValidationRetryCount} validation failures.`
7456
- };
7457
- }
7458
- // Synchronize shared tree budget floor with the current agentRun's metrics (handles both
7459
- // multi-agent trees and direct guardrail invocations with pre-populated agentRun entities)
7460
- // and evaluate cumulative root-tree ceilings (maxTreeSteps, maxTreeTokens, maxTreeCost, maxTreeDurationMs).
7461
- const budget = this.ensureTreeBudget(params);
7462
- if (agentRun) {
7463
- const runStepsCount = Math.max(agentRun.Steps?.length ?? 0, agentRun.TotalPromptIterations ?? 0);
7464
- if (runStepsCount > budget.totalSteps) {
7465
- budget.totalSteps = runStepsCount;
7466
- }
7467
- if ((agentRun.TotalTokensUsed ?? 0) > budget.totalTokens) {
7468
- budget.totalTokens = agentRun.TotalTokensUsed ?? 0;
7469
- }
7470
- if ((agentRun.TotalCost ?? 0) > budget.totalCost) {
7471
- budget.totalCost = agentRun.TotalCost ?? 0;
7472
- }
7473
- }
7474
- const treeBudgetCheck = this.checkTreeBudgetLimit(params);
7475
- if (treeBudgetCheck.exceeded) {
7476
- return treeBudgetCheck;
7477
- }
7478
- // No guardrails exceeded
7479
- return { exceeded: false };
7632
+ const { Result, Budget } = this._budgetTracker.CheckRunAndTreeGuardrails({
7633
+ Params: params,
7634
+ AgentRun: agentRun,
7635
+ ActiveAgentRun: this._agentRun,
7636
+ CurrentBudget: this._treeBudget,
7637
+ FallbackParams: this._executeParams,
7638
+ AbsoluteMaxIterations: absoluteMaxIterations,
7639
+ ValidationRetryCount: this._generalValidationRetryCount,
7640
+ MaxValidationRetries: BaseAgent.MAX_VALIDATION_RETRIES,
7641
+ EnsureTreeBudgetFn: (p) => this.ensureTreeBudget(p),
7642
+ CheckTreeBudgetLimitFn: (p) => this.checkTreeBudgetLimit(p),
7643
+ });
7644
+ this._treeBudget = Budget;
7645
+ return this._budgetTracker.ToLegacyGuardrailVerdict(Result);
7480
7646
  }
7481
7647
  /**
7482
7648
  * Ensures that a shared {@link AgentTreeBudget} instance exists for the current execution tree
@@ -7495,41 +7661,8 @@ export class BaseAgent {
7495
7661
  * @protected
7496
7662
  */
7497
7663
  ensureTreeBudget(params) {
7498
- const effectiveParams = params ?? this._executeParams;
7499
- let budget = effectiveParams?.treeBudget ?? this._treeBudget;
7500
- if (!budget) {
7501
- budget = {
7502
- maxTreeSteps: effectiveParams?.maxTreeSteps,
7503
- maxTreeTokens: effectiveParams?.maxTreeTokens,
7504
- maxTreeCost: effectiveParams?.maxTreeCost,
7505
- maxTreeDurationMs: effectiveParams?.maxTreeDurationMs,
7506
- totalSteps: 0,
7507
- totalTokens: 0,
7508
- totalCost: 0,
7509
- startedAtMs: Date.now()
7510
- };
7511
- }
7512
- else if (effectiveParams) {
7513
- if (budget.maxTreeSteps === undefined && effectiveParams.maxTreeSteps !== undefined) {
7514
- budget.maxTreeSteps = effectiveParams.maxTreeSteps;
7515
- }
7516
- if (budget.maxTreeTokens === undefined && effectiveParams.maxTreeTokens !== undefined) {
7517
- budget.maxTreeTokens = effectiveParams.maxTreeTokens;
7518
- }
7519
- if (budget.maxTreeCost === undefined && effectiveParams.maxTreeCost !== undefined) {
7520
- budget.maxTreeCost = effectiveParams.maxTreeCost;
7521
- }
7522
- if (budget.maxTreeDurationMs === undefined && effectiveParams.maxTreeDurationMs !== undefined) {
7523
- budget.maxTreeDurationMs = effectiveParams.maxTreeDurationMs;
7524
- }
7525
- }
7664
+ const budget = this._budgetTracker.EnsureTreeBudget(params, this._treeBudget, this._executeParams);
7526
7665
  this._treeBudget = budget;
7527
- if (effectiveParams) {
7528
- effectiveParams.treeBudget = budget;
7529
- }
7530
- if (this._executeParams && this._executeParams !== effectiveParams) {
7531
- this._executeParams.treeBudget = budget;
7532
- }
7533
7666
  return budget;
7534
7667
  }
7535
7668
  /**
@@ -7548,58 +7681,7 @@ export class BaseAgent {
7548
7681
  */
7549
7682
  recordPromptUsageInTreeBudget(promptRun, promptResult, params) {
7550
7683
  const budget = this.ensureTreeBudget(params);
7551
- let tokensDelta = 0;
7552
- if (promptRun) {
7553
- if (promptRun.TokensUsedRollup != null && promptRun.TokensUsedRollup > 0) {
7554
- tokensDelta = promptRun.TokensUsedRollup;
7555
- }
7556
- else if ((promptRun.TokensPromptRollup != null && promptRun.TokensPromptRollup > 0) ||
7557
- (promptRun.TokensCompletionRollup != null && promptRun.TokensCompletionRollup > 0)) {
7558
- tokensDelta = (promptRun.TokensPromptRollup ?? 0) + (promptRun.TokensCompletionRollup ?? 0);
7559
- }
7560
- else if (promptRun.TokensUsed != null && promptRun.TokensUsed > 0) {
7561
- tokensDelta = promptRun.TokensUsed;
7562
- }
7563
- else if ((promptRun.TokensPrompt != null && promptRun.TokensPrompt > 0) ||
7564
- (promptRun.TokensCompletion != null && promptRun.TokensCompletion > 0)) {
7565
- tokensDelta = (promptRun.TokensPrompt ?? 0) + (promptRun.TokensCompletion ?? 0);
7566
- }
7567
- }
7568
- if (tokensDelta === 0 && promptResult) {
7569
- if (promptResult.combinedTokensUsed != null && promptResult.combinedTokensUsed > 0) {
7570
- tokensDelta = promptResult.combinedTokensUsed;
7571
- }
7572
- else if ((promptResult.combinedPromptTokens != null && promptResult.combinedPromptTokens > 0) ||
7573
- (promptResult.combinedCompletionTokens != null && promptResult.combinedCompletionTokens > 0)) {
7574
- tokensDelta = (promptResult.combinedPromptTokens ?? 0) + (promptResult.combinedCompletionTokens ?? 0);
7575
- }
7576
- else if (promptResult.tokensUsed != null && promptResult.tokensUsed > 0) {
7577
- tokensDelta = promptResult.tokensUsed;
7578
- }
7579
- else if ((promptResult.promptTokens != null && promptResult.promptTokens > 0) ||
7580
- (promptResult.completionTokens != null && promptResult.completionTokens > 0)) {
7581
- tokensDelta = (promptResult.promptTokens ?? 0) + (promptResult.completionTokens ?? 0);
7582
- }
7583
- }
7584
- let costDelta = 0;
7585
- if (promptRun) {
7586
- if (promptRun.TotalCost != null && promptRun.TotalCost > 0) {
7587
- costDelta = promptRun.TotalCost;
7588
- }
7589
- else if (promptRun.Cost != null && promptRun.Cost > 0) {
7590
- costDelta = promptRun.Cost;
7591
- }
7592
- }
7593
- if (costDelta === 0 && promptResult) {
7594
- if (promptResult.combinedCost != null && promptResult.combinedCost > 0) {
7595
- costDelta = promptResult.combinedCost;
7596
- }
7597
- else if (promptResult.cost != null && promptResult.cost > 0) {
7598
- costDelta = promptResult.cost;
7599
- }
7600
- }
7601
- budget.totalTokens += tokensDelta;
7602
- budget.totalCost += costDelta;
7684
+ this._budgetTracker.RecordPromptUsage(budget, promptRun, promptResult);
7603
7685
  }
7604
7686
  /**
7605
7687
  * Evaluates whether any root-tree cumulative budget ceiling (`maxTreeSteps`, `maxTreeTokens`,
@@ -7616,60 +7698,8 @@ export class BaseAgent {
7616
7698
  */
7617
7699
  checkTreeBudgetLimit(params) {
7618
7700
  const budget = this.ensureTreeBudget(params);
7619
- if (budget.maxTreeSteps != null && budget.totalSteps >= budget.maxTreeSteps) {
7620
- const reason = budget.breachedReason ?? `Agent tree step budget exceeded (${budget.totalSteps}/${budget.maxTreeSteps} total steps across tree)`;
7621
- budget.breachedReason = reason;
7622
- return {
7623
- exceeded: true,
7624
- type: 'iterations',
7625
- limit: budget.maxTreeSteps,
7626
- current: budget.totalSteps,
7627
- reason
7628
- };
7629
- }
7630
- if (budget.maxTreeTokens != null && budget.totalTokens >= budget.maxTreeTokens) {
7631
- const reason = budget.breachedReason ?? `Agent tree token budget exceeded (${budget.totalTokens}/${budget.maxTreeTokens} total tokens across tree)`;
7632
- budget.breachedReason = reason;
7633
- return {
7634
- exceeded: true,
7635
- type: 'tokens',
7636
- limit: budget.maxTreeTokens,
7637
- current: budget.totalTokens,
7638
- reason
7639
- };
7640
- }
7641
- if (budget.maxTreeCost != null && budget.totalCost >= budget.maxTreeCost) {
7642
- const reason = budget.breachedReason ?? `Agent tree cost budget exceeded ($${budget.totalCost.toFixed(4)}/$${budget.maxTreeCost.toFixed(4)} across tree)`;
7643
- budget.breachedReason = reason;
7644
- return {
7645
- exceeded: true,
7646
- type: 'cost',
7647
- limit: budget.maxTreeCost,
7648
- current: budget.totalCost,
7649
- reason
7650
- };
7651
- }
7652
- if (budget.maxTreeDurationMs != null) {
7653
- const elapsedMs = Date.now() - budget.startedAtMs;
7654
- if (elapsedMs >= budget.maxTreeDurationMs) {
7655
- const reason = budget.breachedReason ?? `Agent tree duration budget exceeded (${elapsedMs}ms/${budget.maxTreeDurationMs}ms across tree)`;
7656
- budget.breachedReason = reason;
7657
- return {
7658
- exceeded: true,
7659
- type: 'time',
7660
- limit: budget.maxTreeDurationMs,
7661
- current: elapsedMs,
7662
- reason
7663
- };
7664
- }
7665
- }
7666
- if (budget.breachedReason) {
7667
- return {
7668
- exceeded: true,
7669
- reason: budget.breachedReason
7670
- };
7671
- }
7672
- return { exceeded: false };
7701
+ const result = this._budgetTracker.CheckTreeBudgetLimit(budget);
7702
+ return this._budgetTracker.ToLegacyGuardrailVerdict(result);
7673
7703
  }
7674
7704
  /**
7675
7705
  * Determines if a prompt execution error is fatal and should stop agent execution.
@@ -9906,7 +9936,17 @@ The context is now within limits. Please retry your request with the recovered c
9906
9936
  // failure surfaces as a 'Failed' step (answering "do pipeline errors show as errors?": yes).
9907
9937
  let result;
9908
9938
  try {
9909
- result = await new PipelineExecutor(registry).Execute(pipeline.steps);
9939
+ // The run's audience (hydrated once per run): a graphExpand stage admits only nodes every reader
9940
+ // may see. An unusable audience refuses the pipeline, as it refuses an action call.
9941
+ const audience = await this.audienceReadersFor(params);
9942
+ if ('Error' in audience) {
9943
+ throw new Error(audience.Error);
9944
+ }
9945
+ result = await new PipelineExecutor(registry, undefined, {
9946
+ contextUser: params.contextUser,
9947
+ provider: this.ProviderToUse,
9948
+ audienceReaders: audience.Readers,
9949
+ }).Execute(pipeline.steps);
9910
9950
  }
9911
9951
  catch (e) {
9912
9952
  result = {
@@ -10553,11 +10593,10 @@ The context is now within limits. Please retry your request with the recovered c
10553
10593
  // and removes any cache-poisoning foot-gun should a future consumer write to it.
10554
10594
  agentTypePromptParams = { ...catalog.baseAgentTypePromptParams };
10555
10595
  }
10556
- // A run that withholds task graphs (an audience or a tenant: see taskGraphWithholdingReason) is not offered
10557
- // them; a copy, so the cached base is never written. executeTasksStep refuses a graph the model writes anyway.
10558
- // A bound run (ExecuteAgentParams.boundActionParams) is not offered them either: a graph's action
10559
- // nodes are dispatched outside the binding gate (executeTasksStep refuses one of those too).
10560
- if (withholding?.TaskGraphs || this.hasBoundActionParams(boundActionParams)) {
10596
+ // A run that withholds task graphs (taskGraphWithholdingReason: a constraint no security envelope will
10597
+ // carry) is not offered them; a copy, so the cached base is never written. executeTasksStep refuses a
10598
+ // graph the model writes anyway, through the same predicate.
10599
+ if (withholding?.TaskGraphs) {
10561
10600
  agentTypePromptParams = this.withoutTaskGraphs(agentTypePromptParams);
10562
10601
  }
10563
10602
  if (withholding?.Handoff) {
@@ -10687,10 +10726,32 @@ The context is now within limits. Please retry your request with the recovered c
10687
10726
  return;
10688
10727
  }
10689
10728
  try {
10690
- const candidates = this.catalogNarrowingCandidates(agent, actions, subAgents, skills);
10729
+ const rawCandidates = this.catalogNarrowingCandidates(agent, actions, subAgents, skills);
10730
+ const maxSkillDecisionCandidates = typeof promptParams.maxSkillDecisionCandidates === 'number' && promptParams.maxSkillDecisionCandidates >= 1
10731
+ ? Math.floor(promptParams.maxSkillDecisionCandidates)
10732
+ : DEFAULT_MAX_SKILL_DECISION_CANDIDATES;
10733
+ const { FilteredCandidates: candidates, PreHiddenSkillIDs: preHiddenSkillIDs } = PreFilterSkillCandidatesForDecision(rawCandidates, this._openingRequest ?? '', maxSkillDecisionCandidates);
10691
10734
  const asked = CatalogNarrowingCandidatesToAsk(candidates, limits);
10692
10735
  if (asked.length > 0) {
10693
- this._catalogNarrowing = await this.narrowCatalog(agent, contextUser, promptParams, candidates, asked, limits);
10736
+ const outcome = await this.narrowCatalog(agent, contextUser, promptParams, candidates, asked, limits);
10737
+ if (preHiddenSkillIDs.size > 0) {
10738
+ const mergedSkillHidden = new Set(outcome.Hidden.skill);
10739
+ for (const id of preHiddenSkillIDs) {
10740
+ mergedSkillHidden.add(id);
10741
+ }
10742
+ outcome.Hidden.skill = mergedSkillHidden;
10743
+ }
10744
+ this._catalogNarrowing = outcome;
10745
+ }
10746
+ else if (preHiddenSkillIDs.size > 0) {
10747
+ this._catalogNarrowing = {
10748
+ Hidden: {
10749
+ action: new Set(),
10750
+ agent: new Set(),
10751
+ skill: preHiddenSkillIDs,
10752
+ },
10753
+ Lists: {},
10754
+ };
10694
10755
  }
10695
10756
  }
10696
10757
  catch (error) {
@@ -10716,17 +10777,22 @@ The context is now within limits. Please retry your request with the recovered c
10716
10777
  }
10717
10778
  /**
10718
10779
  * Every item of the three lists as a narrowing candidate. An action or sub-agent with
10719
- * `MinExecutionsPerRun` set, and the Find Candidate tools, are pinned: always shown.
10780
+ * `MinExecutionsPerRun` set, explicitly assigned `MJ: AI Agent Skills` (when the agent also has
10781
+ * unpinned auto-activatable skills), and the Find Candidate tools, are pinned: always shown.
10720
10782
  */
10721
10783
  catalogNarrowingCandidates(agent, actions, subAgents, skills) {
10722
10784
  const requiredActionIDs = AIEngine.Instance.AgentActions
10723
10785
  .filter(aa => UUIDsEqual(aa.AgentID, agent.ID) && aa.Status === 'Active' && (aa.MinExecutionsPerRun ?? 0) > 0)
10724
10786
  .map(aa => aa.ActionID);
10787
+ const assignedSkillIDs = new UUIDSet((AIEngine.Instance.AgentSkills ?? [])
10788
+ .filter(as => UUIDsEqual(as.AgentID, agent.ID) && as.Status === 'Active')
10789
+ .map(as => as.SkillID));
10790
+ const hasUnpinnedSkills = skills.some(s => !assignedSkillIDs.Has(s.ID));
10725
10791
  const candidate = (kind, item, pinned) => ({ Kind: kind, ID: item.ID, Name: item.Name, Description: item.Description ?? '', Pinned: pinned });
10726
10792
  return [
10727
10793
  ...actions.map(a => candidate('action', a, IsAlwaysShownAction(a.Name) || requiredActionIDs.some(id => UUIDsEqual(id, a.ID)))),
10728
10794
  ...subAgents.filter(s => !!s).map(s => candidate('agent', s, (s.MinExecutionsPerRun ?? 0) > 0)),
10729
- ...skills.map(s => candidate('skill', s, false)),
10795
+ ...skills.map(s => candidate('skill', s, hasUnpinnedSkills && assignedSkillIDs.Has(s.ID))),
10730
10796
  ];
10731
10797
  }
10732
10798
  /**
@@ -10880,7 +10946,10 @@ The context is now within limits. Please retry your request with the recovered c
10880
10946
  }
10881
10947
  const shownSet = new Set(shown);
10882
10948
  const hiddenNames = items.filter(item => !shownSet.has(item)).map(item => item.Name);
10883
- return `${CatalogNarrowingNote(kind, hiddenNames)}\n\n${format(shown)}`;
10949
+ const hasFindCandidateSkills = kind === 'skill' &&
10950
+ this._effectiveActions.some(a => (a.Name ?? '').trim().toLowerCase() === CATALOG_NARROWING_FIND_SKILLS.toLowerCase());
10951
+ const note = CatalogNarrowingNote(kind, hiddenNames, hasFindCandidateSkills ? { hasFindCandidateSkills: true } : undefined);
10952
+ return `${note}\n\n${format(shown)}`;
10884
10953
  }
10885
10954
  catch (error) {
10886
10955
  LogErrorEx({
@@ -11098,89 +11167,7 @@ The context is now within limits. Please retry your request with the recovered c
11098
11167
  * @since 2.132.0
11099
11168
  */
11100
11169
  applyResponseTypeAutoAlignment(params, explicitResponseType) {
11101
- // Align a copy: the object may be the caller's per-run override, which sub-agents inherit with the
11102
- // run's data. Writing into it would turn a key "explicit" for every later merge of that override.
11103
- if (IsPlainObject(params.includeResponseTypeDefinition)) {
11104
- params.includeResponseTypeDefinition = { ...params.includeResponseTypeDefinition };
11105
- }
11106
- // Ensure includeResponseTypeDefinition is an object
11107
- else if (!params.includeResponseTypeDefinition || typeof params.includeResponseTypeDefinition !== 'object') {
11108
- params.includeResponseTypeDefinition = {
11109
- payload: true,
11110
- responseForms: true,
11111
- commands: true,
11112
- forEach: true,
11113
- while: true,
11114
- scratchpad: true,
11115
- decisions: true,
11116
- finishIf: true
11117
- };
11118
- }
11119
- const responseType = params.includeResponseTypeDefinition;
11120
- const decisionsEnabled = this.DecisionsEnabled(params);
11121
- // finishIf gates are opt-in (`finishIfMode`), and need the master switch. While off, the model is
11122
- // not taught to write one, whatever includeFinishIfDocs says, so the response field below follows it off too.
11123
- if (!decisionsEnabled || ResolveFinishIfMode(params.finishIfMode) === 'off') {
11124
- params.includeFinishIfDocs = false;
11125
- }
11126
- // `decisions` is opt-in too (`includeDecisionsDocs: true`), and needs the master switch. Its docs and
11127
- // types add about 1,200 tokens to every turn, and on the Prompt Eval corpus no model used it
11128
- // (typed-decision plan, Task 4.7). Unset means off, so the response field below follows it off too.
11129
- if (!decisionsEnabled || params.includeDecisionsDocs !== true) {
11130
- params.includeDecisionsDocs = false;
11131
- }
11132
- // Auto-alignment mappings: docs flag → response type property
11133
- const alignmentMappings = [
11134
- { docsFlag: 'includePayloadInPrompt', responseTypeKey: 'payload' },
11135
- { docsFlag: 'includeResponseFormDocs', responseTypeKey: 'responseForms' },
11136
- { docsFlag: 'includeCommandDocs', responseTypeKey: 'commands' },
11137
- { docsFlag: 'includeForEachDocs', responseTypeKey: 'forEach' },
11138
- { docsFlag: 'includeWhileDocs', responseTypeKey: 'while' },
11139
- { docsFlag: 'includeScratchpadDocs', responseTypeKey: 'scratchpad' },
11140
- { docsFlag: 'includeArtifactToolsDocs', responseTypeKey: 'artifactToolCalls' },
11141
- { docsFlag: 'includeConversationToolsDocs', responseTypeKey: 'conversationToolCalls' },
11142
- { docsFlag: 'includePipelineDocs', responseTypeKey: 'pipeline' },
11143
- { docsFlag: 'includeMemoryWritesDocs', responseTypeKey: 'memoryWrites' },
11144
- { docsFlag: 'includeDecisionsDocs', responseTypeKey: 'decisions' },
11145
- { docsFlag: 'includeFinishIfDocs', responseTypeKey: 'finishIf' }
11146
- ];
11147
- for (const { docsFlag, responseTypeKey } of alignmentMappings) {
11148
- // Check if the user explicitly set this response type property
11149
- // (not from schema defaults, which always provide true)
11150
- const wasExplicitlySet = explicitResponseType &&
11151
- Object.prototype.hasOwnProperty.call(explicitResponseType, responseTypeKey);
11152
- // Auto-align: if docs flag is false AND user didn't explicitly set the response type
11153
- // then auto-align the response type to false
11154
- if (params[docsFlag] === false && !wasExplicitlySet) {
11155
- responseType[responseTypeKey] = false;
11156
- }
11157
- // If user explicitly set the value, respect it regardless of docs flag
11158
- // Otherwise default to true if not set
11159
- else if (responseType[responseTypeKey] === undefined) {
11160
- responseType[responseTypeKey] = true;
11161
- }
11162
- }
11163
- // With the master switch off, neither decision field is offered, even when set explicitly: the
11164
- // model must not be invited to ask for something the run would refuse.
11165
- if (!decisionsEnabled) {
11166
- responseType.decisions = false;
11167
- responseType.finishIf = false;
11168
- }
11169
- // Capability gates align the OTHER way: default OFF, and the section appears only when the
11170
- // gate is explicitly on. Running these through the loop above would invert their meaning —
11171
- // that loop's `else` branch defaults an unset key to true, which is exactly what a gated
11172
- // capability must never do.
11173
- const gateMappings = [
11174
- { gateFlag: 'enableTaskGraphs', responseTypeKey: 'tasks' },
11175
- { gateFlag: 'enableHandoff', responseTypeKey: 'handoff' }
11176
- ];
11177
- for (const { gateFlag, responseTypeKey } of gateMappings) {
11178
- const wasExplicitlySet = explicitResponseType &&
11179
- Object.prototype.hasOwnProperty.call(explicitResponseType, responseTypeKey);
11180
- if (!wasExplicitlySet) {
11181
- responseType[responseTypeKey] = params[gateFlag] === true;
11182
- }
11183
- }
11170
+ this._contextAssembler.ApplyResponseTypeAutoAlignment(params, explicitResponseType, this.DecisionsEnabled(params));
11184
11171
  }
11185
11172
  /**
11186
11173
  * Extracts default values from a JSON Schema definition.
@@ -11192,25 +11179,7 @@ The context is now within limits. Please retry your request with the recovered c
11192
11179
  * @since 2.131.0
11193
11180
  */
11194
11181
  extractSchemaDefaults(schemaJson) {
11195
- if (!schemaJson)
11196
- return {};
11197
- try {
11198
- const schema = JSON.parse(schemaJson);
11199
- const defaults = {};
11200
- if (schema.properties) {
11201
- for (const [key, prop] of Object.entries(schema.properties)) {
11202
- const propDef = prop;
11203
- if (propDef.default !== undefined) {
11204
- defaults[key] = propDef.default;
11205
- }
11206
- }
11207
- }
11208
- return defaults;
11209
- }
11210
- catch (e) {
11211
- LogError(`Failed to parse PromptParamsSchema: ${e instanceof Error ? e.message : String(e)}`);
11212
- return {};
11213
- }
11182
+ return this._contextAssembler.ExtractSchemaDefaults(schemaJson);
11214
11183
  }
11215
11184
  /**
11216
11185
  * The finishIf settings of the current step, from its merged agent-type prompt params. A gate is
@@ -11583,6 +11552,12 @@ The context is now within limits. Please retry your request with the recovered c
11583
11552
  stampActionContext(params) {
11584
11553
  const actionContext = (typeof params.context === 'object' && params.context ? params.context : {});
11585
11554
  actionContext.AgentID = params.agent.ID;
11555
+ if (this._agentRun?.ID) {
11556
+ actionContext.AgentRunID = this._agentRun.ID;
11557
+ }
11558
+ if (params.agent?.Name) {
11559
+ actionContext.AgentName = params.agent.Name;
11560
+ }
11586
11561
  // The skills active in THIS run, as a fact the action can trust. An action that takes a
11587
11562
  // skill principal (Scoped Search's AISkillID) must not have to believe a parameter the model
11588
11563
  // authored: with this it can default the principal to the run's active skill and refuse a
@@ -11713,10 +11688,20 @@ The context is now within limits. Please retry your request with the recovered c
11713
11688
  }
11714
11689
  }
11715
11690
  // Enforce per-(Agent, User) action policy narrowing rules when a user policy is active
11716
- const policyBlocked = this.checkUserActionPolicy(params, action, actionEntity, contextUser ?? params.contextUser);
11691
+ const policyBlocked = await this.checkUserActionPolicy(params, action, actionEntity, contextUser ?? params.contextUser);
11717
11692
  if (policyBlocked) {
11718
11693
  return policyBlocked;
11719
11694
  }
11695
+ // A run under a task-graph envelope refuses egress once tainted, whenever the taint arrived. The run
11696
+ // stays tainted and no argument changes the refusal, so the action is locked out for the run, as a
11697
+ // refused binding is: the model is told to stop calling it, not to adjust its arguments and retry.
11698
+ const taintBlocked = this.checkTaintedEgress(params, action, actionEntity, contextUser ?? params.contextUser);
11699
+ if (taintBlocked) {
11700
+ if (!skipBreaker) {
11701
+ this.lockOutAction(action, actionEntity, 'tainted');
11702
+ }
11703
+ return taintBlocked;
11704
+ }
11720
11705
  // The run's audience, hydrated once per run — lazily here, since this method is also called outside
11721
11706
  // Execute (the pipeline executor, tests). An unusable audience refuses the call: nothing is dispatched.
11722
11707
  const audience = await this.audienceReadersFor(params);
@@ -11725,7 +11710,7 @@ The context is now within limits. Please retry your request with the recovered c
11725
11710
  }
11726
11711
  try {
11727
11712
  // Execute the action and return the full ActionResult
11728
- const result = await ActionEngineServer.Instance.RunAction({
11713
+ const result = await AgentUserPolicyEngine.Instance.RunWithExecutingAgentContext(params.agent?.ID ?? '', () => ActionEngineServer.Instance.RunAction({
11729
11714
  Action: actionEntity,
11730
11715
  Params: this.toActionParams(binding, actionEntity),
11731
11716
  ContextUser: contextUser,
@@ -11733,7 +11718,7 @@ The context is now within limits. Please retry your request with the recovered c
11733
11718
  SkipActionLog: false,
11734
11719
  Context: this.stampActionContext(params),
11735
11720
  ...this.runBoundDispatchParams(params, actionEntity, audience.Readers, contextUser),
11736
- });
11721
+ }));
11737
11722
  this.recordDispatchOutcome(params, action, actionEntity, result, normalizedParams, skipBreaker);
11738
11723
  return result;
11739
11724
  }
@@ -11752,16 +11737,60 @@ The context is now within limits. Please retry your request with the recovered c
11752
11737
  throw new Error(`Error executing actions: ${error.message}`);
11753
11738
  }
11754
11739
  }
11740
+ /**
11741
+ * Refuses a `disallowWhenTainted` action (`Action.Config_Object`) in a run that executes under a
11742
+ * task-graph security envelope (`ExecuteAgentParams.SecurityEnvelope`: a graph's agent node, its
11743
+ * continuation turn, or a sub-agent of either) once the run is tainted — checked on every call against
11744
+ * the run's current taint. The node's runner takes those actions away from a run that starts tainted;
11745
+ * this is what stops one that becomes tainted mid-run (it read a web page, then tries to send mail).
11746
+ */
11747
+ checkTaintedEgress(params, action, actionEntity, contextUser) {
11748
+ if (!params.SecurityEnvelope || !this.IsRunTainted || actionEntity.Config_Object?.disallowWhenTainted !== true) {
11749
+ return null;
11750
+ }
11751
+ return {
11752
+ Success: false,
11753
+ ResultCode: TAINTED_EGRESS_BLOCKED,
11754
+ Message: `Action "${actionEntity.Name}" was not run: this workflow step has read untrusted content, and the action ` +
11755
+ 'sends data out or cannot be undone. A person must review the content in a Human step before it can run.',
11756
+ Params: [],
11757
+ RunParams: {
11758
+ Action: actionEntity,
11759
+ Params: this.toActionParams({ Params: action.params ?? {}, Bound: [] }, actionEntity),
11760
+ ContextUser: contextUser,
11761
+ Filters: [],
11762
+ },
11763
+ };
11764
+ }
11755
11765
  /**
11756
11766
  * Checks per-(Agent, User) action policy narrowing rules (`MJ: AI Agent User Policies`)
11757
- * before dispatching an action. Returns a synthetic ActionResult when the action is denied,
11758
- * deferred outside a configured time window, or requires explicit user approval.
11767
+ * before dispatching an action. Loads the user's policy on cold cache (failing closed on
11768
+ * lookup error) and returns a synthetic ActionResult when the action is denied, deferred
11769
+ * outside a configured time window, or requires explicit user approval.
11759
11770
  */
11760
- checkUserActionPolicy(params, action, actionEntity, contextUser) {
11771
+ async checkUserActionPolicy(params, action, actionEntity, contextUser) {
11761
11772
  if (!contextUser?.ID || !params?.agent?.ID) {
11762
11773
  return null;
11763
11774
  }
11764
- const policy = AgentUserPolicyEngine.Instance.GetCachedPolicy(params.agent.ID, contextUser.ID);
11775
+ let policy = AgentUserPolicyEngine.Instance.GetCachedPolicy(params.agent.ID, contextUser.ID, params.provider);
11776
+ if (!policy) {
11777
+ const lookup = await AgentUserPolicyEngine.Instance.ResolvePolicyForAgentAndUser(params.agent.ID, contextUser.ID, contextUser, { provider: params.provider });
11778
+ if (lookup.status === 'error') {
11779
+ return {
11780
+ Success: false,
11781
+ ResultCode: POLICY_DENIED_RESULT_CODE,
11782
+ Message: `Action "${actionEntity.Name || action.name}" blocked (fail-closed): user policy lookup failed (${lookup.errorMessage}).`,
11783
+ Params: [],
11784
+ RunParams: {
11785
+ Action: actionEntity,
11786
+ Params: this.toActionParams({ Params: action.params ?? {}, Bound: [] }, actionEntity),
11787
+ ContextUser: contextUser,
11788
+ Filters: [],
11789
+ },
11790
+ };
11791
+ }
11792
+ policy = lookup.policy;
11793
+ }
11765
11794
  if (!policy) {
11766
11795
  return null;
11767
11796
  }
@@ -12068,7 +12097,7 @@ The context is now within limits. Please retry your request with the recovered c
12068
12097
  apiKeys: params.apiKeys, // propagate API keys to sub-agent
12069
12098
  CredentialScope: params.CredentialScope, // a sub-agent may not spend keys its parent could not
12070
12099
  Audience: params.Audience, // a sub-agent's output reaches the same room; it re-hydrates the IDs itself
12071
- 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)
12100
+ inputArtifacts: this._artifactToolManager.ExportInputArtifacts(params.inputArtifacts), // propagate input + workspace-created artifacts so sub-agents inherit the parent's manifest + tools
12072
12101
  data: {
12073
12102
  ...params.data,
12074
12103
  ...templateParameters,
@@ -12085,6 +12114,7 @@ The context is now within limits. Please retry your request with the recovered c
12085
12114
  companyId: params.companyId,
12086
12115
  SecondaryScopes: params.SecondaryScopes,
12087
12116
  SearchScopeIDs: params.SearchScopeIDs, // the host's search scopes bound the sub-agent too
12117
+ ...this.subAgentTaint(params), // a tainted parent's sub-agent starts tainted
12088
12118
  conversationDetailId: params.conversationDetailId, // propagate conversationDetailId so sub-agent task graphs attach to the chat message
12089
12119
  onAgentRunCreated: async (agentRunId) => {
12090
12120
  stepEntity.TargetLogID = agentRunId;
@@ -12093,6 +12123,12 @@ The context is now within limits. Please retry your request with the recovered c
12093
12123
  this.queueStepSave(stepEntity, (s) => { s.TargetLogID = agentRunId; });
12094
12124
  }
12095
12125
  });
12126
+ // Every sub-agent path (child, related, parallel) comes through here, so the child's taint reaches
12127
+ // the parent whichever path ran it.
12128
+ this.absorbSubAgentTaint(subAgentRequest.name, result, stepEntity?.StepNumber ?? (stepCount + 1));
12129
+ if (result.touchedArtifacts?.length) {
12130
+ this._artifactToolManager.AbsorbTouchedArtifacts(result.touchedArtifacts);
12131
+ }
12096
12132
  // Check if execution was successful
12097
12133
  if (result.success) {
12098
12134
  this.logStatus(`✅ Sub-agent '${subAgentRequest.name}' completed successfully`, true, params);
@@ -12186,30 +12222,7 @@ The context is now within limits. Please retry your request with the recovered c
12186
12222
  * @private
12187
12223
  */
12188
12224
  formatSubAgentDetails(subAgents) {
12189
- return subAgents.map(sa => {
12190
- let line = `- **${sa.Name}** — ${sa.Description}`;
12191
- if (sa.ExecutionMode !== 'Sequential') {
12192
- line += ` _(${sa.ExecutionMode}, order: ${sa.ExecutionOrder})_`;
12193
- }
12194
- const presets = AIEngine.Instance.GetAgentConfigurationPresets(sa.ID, true);
12195
- if (presets.length > 0) {
12196
- const presetSummary = presets.map(p => {
12197
- const desc = p.Description?.trim();
12198
- if (p.IsDefault && desc) {
12199
- return `${p.Name} (default: ${desc})`;
12200
- }
12201
- if (p.IsDefault) {
12202
- return `${p.Name} (default)`;
12203
- }
12204
- if (desc) {
12205
- return `${p.Name} (${desc})`;
12206
- }
12207
- return p.Name;
12208
- }).join(', ');
12209
- line += `\n Presets: ${presetSummary}`;
12210
- }
12211
- return line;
12212
- }).join('\n');
12225
+ return this._contextAssembler.FormatSubAgentDetails(subAgents);
12213
12226
  }
12214
12227
  /**
12215
12228
  * Formats the skill CATALOG as compact markdown — name + description ONLY. This is
@@ -12220,7 +12233,7 @@ The context is now within limits. Please retry your request with the recovered c
12220
12233
  * @private
12221
12234
  */
12222
12235
  formatSkillsCatalog(skills) {
12223
- return skills.map(s => `- **${s.Name}** — ${s.Description ?? '(no description)'}`).join('\n');
12236
+ return this._contextAssembler.FormatSkillsCatalog(skills);
12224
12237
  }
12225
12238
  /**
12226
12239
  * Utility method to get agent prompt parameters for a given agent. This gets the
@@ -12265,39 +12278,7 @@ The context is now within limits. Please retry your request with the recovered c
12265
12278
  * @private
12266
12279
  */
12267
12280
  formatActionDetails(actions, boundActionParams) {
12268
- return actions.map(action => {
12269
- const lines = [];
12270
- lines.push(`### ${action.Name}`);
12271
- lines.push(action.Description);
12272
- const visibleParams = UnboundParams(action.Params.Items, BindingsForAction(boundActionParams, action.ID));
12273
- const inputParams = visibleParams
12274
- .filter(p => {
12275
- const t = p.Type.trim().toLowerCase();
12276
- return t === 'input' || t === 'both';
12277
- });
12278
- const outputParams = visibleParams
12279
- .filter(p => {
12280
- const t = p.Type.trim().toLowerCase();
12281
- return t === 'output' || t === 'both';
12282
- });
12283
- if (inputParams.length > 0) {
12284
- lines.push(`**Input:** ${inputParams.map(p => this.formatActionParameter(p)).join(', ')}`);
12285
- }
12286
- if (outputParams.length > 0) {
12287
- lines.push(`**Output:** ${outputParams.map(p => this.formatActionParameter(p)).join(', ')}`);
12288
- }
12289
- if (action.ResultCodes.Items.length > 0) {
12290
- const rcParts = action.ResultCodes.Items.map(rc => {
12291
- const marker = rc.IsSuccess ? '✓' : '✗';
12292
- const desc = rc.Description && rc.Description.toLowerCase() !== rc.ResultCode.toLowerCase()
12293
- ? ` ${rc.Description}`
12294
- : '';
12295
- return `${rc.ResultCode} ${marker}${desc}`;
12296
- });
12297
- lines.push(`**Results:** ${rcParts.join(' · ')}`);
12298
- }
12299
- return lines.join('\n');
12300
- }).join('\n\n');
12281
+ return this._contextAssembler.FormatActionDetails(actions, boundActionParams);
12301
12282
  }
12302
12283
  /**
12303
12284
  * The client tools in force for a run: the agent's static metadata tools under the session, app
@@ -12309,24 +12290,7 @@ The context is now within limits. Please retry your request with the recovered c
12309
12290
  * tier, `clientTools` the override tier.
12310
12291
  */
12311
12292
  resolveClientToolsForRun(agent, data) {
12312
- // Static tier — agent's metadata tools from the AI Agent Client Tools junction.
12313
- const staticTools = AIEngine.Instance.GetClientToolsForAgent(agent.ID).map(tool => ({
12314
- Name: tool.Name,
12315
- Description: tool.Description,
12316
- InputSchema: tool.InputSchemaJSON ? JSON.parse(tool.InputSchemaJSON) : {},
12317
- OutputSchema: tool.OutputSchemaJSON ? JSON.parse(tool.OutputSchemaJSON) : undefined,
12318
- Category: tool.Category || undefined,
12319
- DefaultTimeoutMs: tool.DefaultTimeoutMs || undefined
12320
- }));
12321
- // Dynamic (session) tier — client-SDK enriched tools for this session.
12322
- const sessionID = data?.sessionID;
12323
- const sessionTools = sessionID ? ClientToolRequestManager.Instance.GetSessionTools(sessionID) : [];
12324
- // App tier — tools the active surface published in the app-context capability manifest.
12325
- const appContext = data?.appContext;
12326
- const appTools = appContext?.Capabilities?.Tools ?? [];
12327
- // Override tier — tools passed directly in the run's data.
12328
- const overrideTools = data?.clientTools ?? [];
12329
- return ResolveClientTools({ agentId: agent.ID, staticTools, sessionTools, appTools, overrideTools });
12293
+ return this._contextAssembler.ResolveClientToolsForRun(agent, data);
12330
12294
  }
12331
12295
  /**
12332
12296
  * Build the client tool prompt section for system prompt injection.
@@ -12347,35 +12311,7 @@ The context is now within limits. Please retry your request with the recovered c
12347
12311
  * static metadata tool of the same name. Collisions are rare in practice.
12348
12312
  */
12349
12313
  buildClientToolPromptSection(agent, extraData) {
12350
- const tools = this.resolveClientToolsForRun(agent, extraData);
12351
- if (tools.length === 0) {
12352
- return ''; // No client tools available
12353
- }
12354
- const lines = [];
12355
- lines.push('### Client Tools (execute in the user\'s browser)');
12356
- lines.push('Client tools run in the user\'s browser and interact with the UI. Use these when you need');
12357
- lines.push('to navigate the user somewhere, display a specific view, switch dashboard tabs, or show');
12358
- lines.push('records. When you choose client tools, set nextStep.type to "ClientTools".');
12359
- lines.push('');
12360
- lines.push('NOTE: Do NOT use client tools for asking the user questions or collecting input.');
12361
- lines.push('Use the "Chat" step for that. Client tools read and change the user\'s UI; some return an image.');
12362
- lines.push('');
12363
- for (const tool of tools) {
12364
- const categoryTag = tool.Category ? ` [${tool.Category}]` : '';
12365
- lines.push(`- **${tool.Name}**${categoryTag}: ${tool.Description}`);
12366
- // Show input parameters from InputSchema
12367
- const props = tool.InputSchema?.properties;
12368
- const required = tool.InputSchema?.required;
12369
- if (props) {
12370
- const paramParts = Object.entries(props).map(([name, schema]) => {
12371
- const req = required?.includes(name) ? '\\*' : '';
12372
- const desc = schema.description ? ` — ${schema.description}` : '';
12373
- return `\`${name}\`${req}${desc}`;
12374
- });
12375
- lines.push(` Inputs: ${paramParts.join(', ')}`);
12376
- }
12377
- }
12378
- return lines.join('\n');
12314
+ return this._contextAssembler.BuildClientToolPromptSection(agent, extraData);
12379
12315
  }
12380
12316
  /**
12381
12317
  * Build the app context section for system prompt injection.
@@ -12383,46 +12319,7 @@ The context is now within limits. Please retry your request with the recovered c
12383
12319
  * it as a concise markdown section the LLM can reference.
12384
12320
  */
12385
12321
  buildAppContextSection(extraData) {
12386
- const ctx = extraData?.appContext;
12387
- if (!ctx)
12388
- return '';
12389
- const app = ctx['App'];
12390
- const activeNav = ctx['ActiveNavItem'];
12391
- const otherNavs = ctx['OtherNavItems'];
12392
- const user = ctx['User'];
12393
- if (!app?.Name)
12394
- return '';
12395
- const lines = [];
12396
- lines.push('### Current Application Context');
12397
- lines.push(`The user is currently in the **${app.Name}** application${app.Description ? ` — ${app.Description}` : ''}.`);
12398
- if (activeNav?.Name) {
12399
- lines.push('');
12400
- lines.push(`**Active view:** ${activeNav.Name}${activeNav.Description ? ` — ${activeNav.Description}` : ''}${activeNav.ResourceType ? ` (${activeNav.ResourceType})` : ''}`);
12401
- }
12402
- if (otherNavs && otherNavs.length > 0) {
12403
- lines.push('');
12404
- lines.push('**Other views available in this app:**');
12405
- for (const nav of otherNavs) {
12406
- lines.push(`- ${nav.Name}${nav.Description ? ` — ${nav.Description}` : ''}`);
12407
- }
12408
- }
12409
- if (user?.Name) {
12410
- lines.push('');
12411
- lines.push(`**User:** ${user.Name}${user.Roles?.length ? ` (Roles: ${user.Roles.join(', ')})` : ''}`);
12412
- }
12413
- // Additional context reported by the active view/component
12414
- const dashboardCtx = ctx['AdditionalContext'];
12415
- if (dashboardCtx && Object.keys(dashboardCtx).length > 0) {
12416
- lines.push('');
12417
- lines.push('**Dashboard state:**');
12418
- for (const [key, value] of Object.entries(dashboardCtx)) {
12419
- if (value === null || value === undefined)
12420
- continue;
12421
- const displayValue = typeof value === 'object' ? JSON.stringify(value) : String(value);
12422
- lines.push(`- ${key}: ${displayValue}`);
12423
- }
12424
- }
12425
- return lines.join('\n');
12322
+ return this._contextAssembler.BuildAppContextSection(extraData);
12426
12323
  }
12427
12324
  /**
12428
12325
  * Formats a single action parameter as a compact inline string.
@@ -12434,28 +12331,7 @@ The context is now within limits. Please retry your request with the recovered c
12434
12331
  * @private
12435
12332
  */
12436
12333
  formatActionParameter(param) {
12437
- const requiredMarker = param.IsRequired ? '\\*' : '';
12438
- const parts = [];
12439
- if (param.IsArray) {
12440
- parts.push('array');
12441
- }
12442
- // A stored ValueSchema is the real type, so it replaces the coarse ValueType label — the
12443
- // same information the native tool declaration carries.
12444
- const valueSchema = GetStoredValueSchema(param);
12445
- const vt = param.ValueType?.trim();
12446
- if (valueSchema) {
12447
- parts.push(DescribeValueSchemaInline(valueSchema));
12448
- }
12449
- else if (vt && vt !== 'Scalar' && vt !== 'Other') {
12450
- parts.push(vt);
12451
- }
12452
- const suffix = parts.length > 0 ? ` (${parts.join(', ')})` : '';
12453
- let defaultStr = '';
12454
- if (param.DefaultValue != null && param.DefaultValue !== '') {
12455
- defaultStr = ` (default: ${JSON.stringify(param.DefaultValue)})`;
12456
- }
12457
- const desc = param.Description ? ` — ${param.Description}` : '';
12458
- return `\`${param.Name}\`${requiredMarker}${suffix}${desc}${defaultStr}`;
12334
+ return this._contextAssembler.FormatActionParameter(param);
12459
12335
  }
12460
12336
  /**
12461
12337
  * The `user`-role record of what the model asked to run on an Actions turn ("[You invoked ...]").
@@ -12464,28 +12340,7 @@ The context is now within limits. Please retry your request with the recovered c
12464
12340
  * @protected
12465
12341
  */
12466
12342
  buildActionInvocationMessage(actions, params) {
12467
- if (actions.length === 1) {
12468
- const aa = actions[0];
12469
- const shownParams = this.shownActionParamEntries(params, aa);
12470
- if (shownParams.length === 0) {
12471
- return `[You invoked the **${aa.name}** action.]`;
12472
- }
12473
- const paramsList = shownParams
12474
- .map(([key, value]) => `• **${key}**: ${this.formatParamValueForMessage(value)}`)
12475
- .join('\n');
12476
- return `[You invoked the **${aa.name}** action with parameters:\n${paramsList}\n]`;
12477
- }
12478
- return `[You invoked **${actions.length} actions** in parallel:\n\n` + actions.map((aa, index) => {
12479
- const actionText = `${index + 1}. **${aa.name}**`;
12480
- const shownParams = this.shownActionParamEntries(params, aa);
12481
- if (shownParams.length === 0) {
12482
- return actionText;
12483
- }
12484
- const paramsList = shownParams
12485
- .map(([key, value]) => ` • **${key}**: ${this.formatParamValueForMessage(value)}`)
12486
- .join('\n');
12487
- return `${actionText}\n${paramsList}`;
12488
- }).join('\n\n') + '\n]';
12343
+ return this._stepDispatcher.BuildActionInvocationMessage(actions, (aa) => this.shownActionParamEntries(params, aa));
12489
12344
  }
12490
12345
  /**
12491
12346
  * The action-results message body: a header naming any failures, then each result in the
@@ -12499,7 +12354,7 @@ The context is now within limits. Please retry your request with the recovered c
12499
12354
  }
12500
12355
  /**
12501
12356
  * Formats an array of action result summaries as compact markdown instead of
12502
- * pretty-printed JSON. This typically saves 60-70 % of the tokens that the
12357
+ * pretty-printed JSON. This typically saves 60-70 % of the tokens that the
12503
12358
  * old `JSON.stringify(actionSummaries, null, 2)` approach consumed, while
12504
12359
  * remaining equally parseable by LLMs.
12505
12360
  *
@@ -12519,53 +12374,11 @@ The context is now within limits. Please retry your request with the recovered c
12519
12374
  * @protected
12520
12375
  */
12521
12376
  formatActionResultsAsMarkdown(actionSummaries) {
12522
- return actionSummaries.map(a => {
12523
- const marker = a.success ? '✓' : '✗';
12524
- const lines = [];
12525
- lines.push(`## ${a.actionName} ${marker}`);
12526
- lines.push(`**Result:** ${a.resultCode} — ${a.message || '(no message)'}`);
12527
- if (!a.success && a.errorRecovery) {
12528
- const er = a.errorRecovery;
12529
- if (er.Retryable !== undefined) {
12530
- lines.push(`**Retryable:** ${er.Retryable ? 'Yes (adjust parameters before retrying)' : 'No (do not retry this action with the same goal)'}`);
12531
- }
12532
- if (er.RecoverySuggestion) {
12533
- lines.push(`**How to Recover:** ${er.RecoverySuggestion}`);
12534
- }
12535
- if (er.SuggestedValues && er.SuggestedValues.length > 0) {
12536
- lines.push(`**Did You Mean:** ${er.SuggestedValues.map(v => `\`${v}\``).join(', ')}`);
12537
- }
12538
- if (er.InvalidParams && er.InvalidParams.length > 0) {
12539
- lines.push('**Invalid Parameters:**');
12540
- for (const ip of er.InvalidParams) {
12541
- lines.push(`• \`${ip.ParamName}\`: ${ip.Reason}`);
12542
- }
12543
- }
12544
- if (er.ValidParameterExample) {
12545
- lines.push(`**Valid Example:** \`${JSON.stringify(er.ValidParameterExample)}\``);
12546
- }
12547
- if (er.SuggestedNextActions && er.SuggestedNextActions.length > 0) {
12548
- lines.push(`**Suggested Next Actions:** ${er.SuggestedNextActions.map(v => `\`${v}\``).join(', ')}`);
12549
- }
12550
- }
12551
- // Format output params as bullet list. An exempt action's values go out verbatim.
12552
- if (a.params && a.params.length > 0) {
12553
- const crush = !this._actionResultCrush?.exemptActions?.has(a.actionName);
12554
- lines.push('**Output:**');
12555
- for (const p of a.params) {
12556
- lines.push(`• \`${p.Name}\`: ${this.formatParamValueForResult(p.Value, 0, crush)}`);
12557
- }
12558
- }
12559
- const formatted = lines.join('\n');
12560
- if (a.trustLevel === 'Untrusted' || a.trustLevel === 'SemiTrusted') {
12561
- return WrapUntrustedExternalData(formatted, `action:${a.actionName}`, a.trustLevel);
12562
- }
12563
- return formatted;
12564
- }).join('\n\n');
12377
+ return this._stepDispatcher.FormatActionResultsAsMarkdown(actionSummaries, this._actionResultCrush);
12565
12378
  }
12566
12379
  /**
12567
12380
  * Formats an ExecuteAgentResult as compact markdown for inclusion in
12568
- * conversation messages. Extracts only the fields that are meaningful
12381
+ * conversation messages. Extracts only the fields that are meaningful
12569
12382
  * to the calling agent (success, status, error, and payload) and
12570
12383
  * presents them in a concise format.
12571
12384
  *
@@ -12575,90 +12388,7 @@ The context is now within limits. Please retry your request with the recovered c
12575
12388
  * @private
12576
12389
  */
12577
12390
  formatSubAgentResultAsMarkdown(subAgentName, result) {
12578
- const marker = result.success ? '✓' : '✗';
12579
- const lines = [];
12580
- lines.push(`## Sub-agent: ${subAgentName} ${marker}`);
12581
- // Status / error from the agent run
12582
- const status = result.agentRun?.Status || (result.success ? 'Completed' : 'Failed');
12583
- lines.push(`**Status:** ${status}`);
12584
- if (result.agentRun?.FinalStep) {
12585
- lines.push(`**Final step:** ${result.agentRun.FinalStep}`);
12586
- }
12587
- if (result.agentRun?.Message) {
12588
- lines.push(`**Message:** ${result.agentRun.Message}`);
12589
- }
12590
- const formSummary = FormatResponseFormSummary(result.responseForm);
12591
- if (formSummary) {
12592
- lines.push(`**Form:**\n${formSummary}`);
12593
- }
12594
- if (!result.success && result.agentRun?.ErrorMessage) {
12595
- lines.push(`**Error:** ${result.agentRun.ErrorMessage}`);
12596
- }
12597
- if (result.agentRun?.Message?.trim()) {
12598
- lines.push(`**Message:**\n${result.agentRun.Message.trim()}`);
12599
- }
12600
- // Payload — the actual result data the parent agent cares about.
12601
- // Not truncated by default — the expiration/compaction lifecycle handles
12602
- // context window management. Truncating here permanently discards data
12603
- // before the LLM ever sees it.
12604
- if (result.payload != null) {
12605
- const payloadStr = typeof result.payload === 'string'
12606
- ? result.payload
12607
- : JSON.stringify(result.payload);
12608
- lines.push(`**Payload:**\n${payloadStr}`);
12609
- }
12610
- return lines.join('\n');
12611
- }
12612
- /**
12613
- * Formats a single output parameter value for inclusion in action result
12614
- * markdown. Scalars are shown inline with backtick formatting; objects and
12615
- * arrays use compact (single-line) JSON to avoid the indentation overhead
12616
- * of pretty-printed JSON.
12617
- *
12618
- * By default, values are **not truncated** — the expiration/compaction lifecycle
12619
- * handles context window management. Truncating at formatting time permanently
12620
- * discards data before the LLM ever sees it. Pass an explicit maxLength only
12621
- * when you have a specific reason to limit output size.
12622
- *
12623
- * @param value - The parameter value (any type)
12624
- * @param maxLength - Maximum character length before truncation (0 = no limit, default 0)
12625
- * @returns Formatted string
12626
- * @private
12627
- */
12628
- formatParamValueForResult(value, maxLength = 0, crush = true) {
12629
- if (value === null || value === undefined) {
12630
- return '`null`';
12631
- }
12632
- if (typeof value === 'boolean' || typeof value === 'number') {
12633
- return `\`${String(value)}\``;
12634
- }
12635
- if (typeof value === 'string') {
12636
- // A string param may carry JSON (many actions JSON.stringify their payloads),
12637
- // SQL/TS code, or plain text. Try structural JSON compression first — it is a
12638
- // safe no-op on non-JSON (crushParamValue's internal JSON.parse failure is
12639
- // caught and returns null) — then opt-in AST code reduction (SQL/TS), then pass
12640
- // through (optionally length-capped).
12641
- const crushedJson = crush ? this.crushParamValue(value) : null;
12642
- if (crushedJson !== null) {
12643
- return crushedJson;
12644
- }
12645
- const crushedCode = crush ? this.crushCodeValue(value) : null;
12646
- if (crushedCode !== null) {
12647
- return crushedCode;
12648
- }
12649
- return maxLength > 0 && value.length > maxLength ? `${value.substring(0, maxLength)}…` : value;
12650
- }
12651
- // Objects/arrays: compact JSON (no pretty-printing), optionally structurally
12652
- // compressed via context-crush when crushing is enabled and the value is large.
12653
- const stringValue = JSON.stringify(value);
12654
- const crushed = crush ? this.crushParamValue(stringValue) : null;
12655
- if (crushed !== null) {
12656
- return crushed;
12657
- }
12658
- if (maxLength > 0 && stringValue.length > maxLength) {
12659
- return `${stringValue.substring(0, maxLength)}…`;
12660
- }
12661
- return stringValue;
12391
+ return this._stepDispatcher.FormatSubAgentResultAsMarkdown(subAgentName, result);
12662
12392
  }
12663
12393
  /**
12664
12394
  * Resolve the per-run action-result compression config from the agent-type prompt
@@ -12667,109 +12397,19 @@ The context is now within limits. Please retry your request with the recovered c
12667
12397
  * @private
12668
12398
  */
12669
12399
  resolveActionResultCrush(params) {
12670
- const agentTypePromptParams = (params.data?.__agentTypePromptParams ?? this._agentTypePromptParams);
12671
- if (agentTypePromptParams?.crushActionResults === false) {
12672
- return undefined;
12673
- }
12674
- const requestedLang = agentTypePromptParams?.crushCodeLang;
12675
- const codeLang = requestedLang === 'sql' || requestedLang === 'typescript' ? requestedLang : undefined;
12676
- const uncrushed = agentTypePromptParams?.uncrushedActions;
12677
- const exemptActions = new Set(Array.isArray(uncrushed) ? uncrushed.filter((name) => typeof name === 'string') : []);
12678
- return { threshold: BaseAgent.ACTION_RESULT_CRUSH_THRESHOLD, maxChars: undefined, codeLang, exemptActions };
12679
- }
12680
- /**
12681
- * AST-reduce a large code-string action-result value when the agent opted into a code
12682
- * language (via `crushCodeLang` or a subclass override) and the value clears the size
12683
- * threshold. Returns reduced code plus a one-line legend, or null to keep the string
12684
- * verbatim (crushing disabled, too small, or no net saving).
12685
- *
12686
- * token optimization via @memberjunction/context-crush (CodeCompressor-inspired)
12687
- * @private
12688
- */
12689
- crushCodeValue(stringValue) {
12690
- const config = this._actionResultCrush;
12691
- if (!config || !config.codeLang || stringValue.length < config.threshold) {
12692
- return null;
12693
- }
12694
- // Crushing is a best-effort optimization — it must never break an agent turn. Any
12695
- // failure falls back to the verbatim value.
12696
- try {
12697
- const result = CrushCode(stringValue, config.codeLang);
12698
- if (result.CrushedChars >= result.OriginalChars) {
12699
- return null;
12700
- }
12701
- const legend = DescribeCrush(result);
12702
- return legend ? `${result.Text}\n ↳ ${legend}` : result.Text;
12703
- }
12704
- catch {
12705
- return null;
12706
- }
12707
- }
12708
- /**
12709
- * Structurally compress a JSON action-result value when crushing is enabled for the run
12710
- * and the value clears the size threshold. Accepts either the `JSON.stringify` of an
12711
- * object/array param, or a raw string param that itself contains JSON (many actions
12712
- * stringify their payloads, e.g. `run-adhoc-query`'s `Results`). Returns crushed text
12713
- * plus a one-line legend, or null when crushing is disabled, the value is too small, the
12714
- * value isn't valid JSON, or compression wouldn't actually save characters — so callers
12715
- * fall back to verbatim (and, for strings, to code crushing) behavior.
12716
- *
12717
- * token optimization via @memberjunction/context-crush (SmartCrusher-inspired)
12718
- * @private
12719
- */
12720
- crushParamValue(stringValue) {
12721
- const config = this._actionResultCrush;
12722
- if (!config || stringValue.length < config.threshold) {
12723
- return null;
12724
- }
12725
- // Crushing is a best-effort optimization — it must never break an agent turn. Any
12726
- // failure (non-JSON input, pathologically deep payloads) falls back to verbatim.
12727
- try {
12728
- // Parse to a plain JSON value. This is the JSON.stringify of an object/array
12729
- // param, or a raw string param that contains JSON; non-JSON strings throw here
12730
- // and are caught below (caller then tries code crushing / verbatim).
12731
- const json = JSON.parse(stringValue);
12732
- const result = CrushJSON(json, { MaxChars: config.maxChars });
12733
- if (result.CrushedChars >= result.OriginalChars) {
12734
- return null; // no net saving — keep the verbatim JSON
12735
- }
12736
- const legend = DescribeCrush(result);
12737
- return legend ? `${result.Text}\n ↳ ${legend}` : result.Text;
12738
- }
12739
- catch {
12740
- return null;
12741
- }
12400
+ return this._stepDispatcher.ResolveActionResultCrush(params, this._agentTypePromptParams, BaseAgent.ACTION_RESULT_CRUSH_THRESHOLD);
12742
12401
  }
12743
12402
  /**
12744
12403
  * Formats a parameter value for display in action execution messages.
12745
12404
  * Truncates long strings and formats objects/arrays for readability.
12746
12405
  *
12747
- * @param {any} value - The parameter value to format
12406
+ * @param {unknown} value - The parameter value to format
12748
12407
  * @param {number} maxLength - Maximum length before truncation (default: 100)
12749
12408
  * @returns {string} Formatted value suitable for message display
12750
12409
  * @private
12751
12410
  */
12752
12411
  formatParamValueForMessage(value, maxLength = 100) {
12753
- if (value === null || value === undefined) {
12754
- return 'null';
12755
- }
12756
- let stringValue;
12757
- if (typeof value === 'string') {
12758
- stringValue = value;
12759
- }
12760
- else if (typeof value === 'object') {
12761
- // For objects/arrays, use compact JSON
12762
- stringValue = JSON.stringify(value);
12763
- }
12764
- else {
12765
- stringValue = String(value);
12766
- }
12767
- // Truncate if too long
12768
- if (stringValue.length > maxLength) {
12769
- return `\`${stringValue.substring(0, maxLength)}...\``;
12770
- }
12771
- // Use inline code formatting for values
12772
- return `\`${stringValue}\``;
12412
+ return this._stepDispatcher.FormatParamValueForMessage(value, maxLength);
12773
12413
  }
12774
12414
  /**
12775
12415
  * Gets the agent type name for a given type ID.
@@ -13935,7 +13575,12 @@ The context is now within limits. Please retry your request with the recovered c
13935
13575
  if (!previousDecision) {
13936
13576
  // First execution - ask the agent type what to do
13937
13577
  const initialStep = await this.AgentTypeInstance.DetermineInitialStep(params, params.payload, this.AgentTypeState);
13938
- await this.recordExecutionRouting(params);
13578
+ // A run refused before its first step (a dispatch refusal, a flow that does not compile)
13579
+ // never ran on either engine, so it gets no routing record: a completed Decision step
13580
+ // there would read as a successful dispatch (#4622).
13581
+ if (initialStep?.step !== 'Failed') {
13582
+ await this.recordExecutionRouting(params);
13583
+ }
13939
13584
  if (initialStep) {
13940
13585
  // Agent type provided an initial step
13941
13586
  return initialStep;
@@ -14665,7 +14310,7 @@ The context is now within limits. Please retry your request with the recovered c
14665
14310
  // needs one more turn to see the results and incorporate them into its response.
14666
14311
  // Without this, the tool results are wasted because the run exits before
14667
14312
  // the LLM ever sees them.
14668
- if (artifactToolsExecutedThisTurn && this._artifactToolManager.HasArtifacts()) {
14313
+ if (artifactToolsExecutedThisTurn && this._artifactToolManager.IsWorkspaceEnabled()) {
14669
14314
  this.logStatus(`[ArtifactTools] Chat step included tool calls — forcing one more turn so LLM can use results`, true, params);
14670
14315
  return { ...updatedNextStep, terminate: false, step: 'Retry' };
14671
14316
  }
@@ -14923,7 +14568,6 @@ The context is now within limits. Please retry your request with the recovered c
14923
14568
  // Child sub-agents don't use context messages (they inherit payload directly)
14924
14569
  const subAgentResult = await this.ExecuteSubAgent(params, subAgentRequest, subAgentEntity, stepEntity, scopedPayload, undefined, // No context message for child sub-agents
14925
14570
  stepCount);
14926
- this.absorbSubAgentTaint(subAgentRequest.name, subAgentResult, stepEntity?.StepNumber ?? (stepCount + 1));
14927
14571
  let mergedPayload = previousDecision.newPayload; // Start with the original payload
14928
14572
  let currentStepPayloadChangeResult = undefined;
14929
14573
  if (subAgentResult.success) {
@@ -15244,7 +14888,8 @@ The context is now within limits. Please retry your request with the recovered c
15244
14888
  }
15245
14889
  /**
15246
14890
  * Finds a sub-agent by name, checking child agents (ParentID) first, then
15247
- * related agents (AgentRelationships). Returns `undefined` when the name
14891
+ * related agents (AgentRelationships), then agents named on this agent's own
14892
+ * Flow steps, then runtime-granted sub-agents. Returns `undefined` when the name
15248
14893
  * doesn't resolve to an active agent reachable from `params.agent`.
15249
14894
  *
15250
14895
  * Used by both the single and parallel sub-agent dispatch paths so name
@@ -15282,7 +14927,18 @@ The context is now within limits. Please retry your request with the recovered c
15282
14927
  return { subAgentEntity: matchedPair.agent, relationship: matchedPair.rel };
15283
14928
  }
15284
14929
  }
15285
- // 3) Runtime-granted sub-agents (skill activation / caller subAgentChanges): resolve from
14930
+ // 3) Sub-agents named on this agent's own Flow steps (#1415). A Flow agent binds a sub-agent on
14931
+ // its step (`AIAgentStep.SubAgentID`, or a ForEach/While body with LoopBodyType 'Sub-Agent'),
14932
+ // not through ParentID or a relationship row, so without this tier an in-run Flow could not
14933
+ // reach the agent its own step names. The same reasoning as getFlowStepActions. A Loop agent
14934
+ // has no steps, so this adds nothing for it.
14935
+ const flowStepPool = this.getFlowStepSubAgents(params.agent.ID);
14936
+ const flowStepAgent = flowStepPool.find(a => a.Name.trim().toLowerCase() === normalized)
14937
+ ?? this.matchNamedBySanitizedToolName(name, flowStepPool, true).match;
14938
+ if (flowStepAgent) {
14939
+ return { subAgentEntity: flowStepAgent };
14940
+ }
14941
+ // 4) Runtime-granted sub-agents (skill activation / caller subAgentChanges): resolve from
15286
14942
  // the SAME effective set the prompt offered and validateSubAgentNextStep approved. Without
15287
14943
  // this branch, a skill-granted sub-agent passes validation but fails execution ("not found
15288
14944
  // or not active") — and because the catalog keeps offering it, the model re-picks the same
@@ -15294,7 +14950,7 @@ The context is now within limits. Please retry your request with the recovered c
15294
14950
  if (effectiveAgent) {
15295
14951
  return { subAgentEntity: effectiveAgent };
15296
14952
  }
15297
- // 4) Single-node constant-folded task graphs (D9): an orchestrator (e.g. Sage) may discover
14953
+ // 5) Single-node constant-folded task graphs (D9): an orchestrator (e.g. Sage) may discover
15298
14954
  // any active peer agent via Find Candidate Agents and delegate a 1-node Tasks graph to it.
15299
14955
  // LoopAgentType folds that 1-node graph into an in-run Sub-Agent step (`taskGraph.folded === true`),
15300
14956
  // so allow resolving any active agent in AIEngine.Instance.Agents.
@@ -15335,28 +14991,7 @@ The context is now within limits. Please retry your request with the recovered c
15335
14991
  * @protected
15336
14992
  */
15337
14993
  cloneSubAgentPayload(payload) {
15338
- if (payload === null || payload === undefined)
15339
- return payload;
15340
- if (typeof payload !== 'object')
15341
- return payload;
15342
- if (typeof globalThis.structuredClone === 'function') {
15343
- try {
15344
- return globalThis.structuredClone(payload);
15345
- }
15346
- catch {
15347
- // DataCloneError — typically a Proxy (a live JSONType `<Field>Object` view) or an
15348
- // object holding functions. Fall through to the JSON clone below; returning the
15349
- // original here would silently give the sub-agent the caller's LIVE object and lose
15350
- // payload isolation.
15351
- }
15352
- }
15353
- try {
15354
- return ToPlainJSON(payload);
15355
- }
15356
- catch (error) {
15357
- LogError(`BaseAgent.cloneSubAgentPayload: payload could not be cloned (${error instanceof Error ? error.message : String(error)}); sub-agent will share the caller's object`);
15358
- return payload;
15359
- }
14994
+ return this._stepDispatcher.CloneSubAgentPayload(payload);
15360
14995
  }
15361
14996
  /**
15362
14997
  * Pre-flight for one parallel sub-agent: resolve the entity, push the
@@ -16124,66 +15759,8 @@ The context is now within limits. Please retry your request with the recovered c
16124
15759
  *
16125
15760
  * @private
16126
15761
  */
16127
- applySubAgentOutputMapping(subAgentResult, _parentPayload, mappingConfig) {
16128
- try {
16129
- const mapping = JSON.parse(mappingConfig);
16130
- const updateObj = {};
16131
- for (const [subAgentPath, parentPath] of Object.entries(mapping)) {
16132
- let value;
16133
- if (subAgentPath === '*') {
16134
- // Wildcard - capture entire sub-agent result
16135
- value = subAgentResult;
16136
- }
16137
- else {
16138
- // Extract from sub-agent result using dot notation
16139
- value = this.getValueFromPath(subAgentResult, subAgentPath);
16140
- }
16141
- if (value !== undefined) {
16142
- // Parse the parent path and build nested object
16143
- const pathParts = parentPath.split('.');
16144
- let current = updateObj;
16145
- for (let i = 0; i < pathParts.length - 1; i++) {
16146
- const part = pathParts[i];
16147
- // Remove [] suffix for intermediate path parts
16148
- const cleanPart = part.endsWith('[]') ? part.slice(0, -2) : part;
16149
- if (!(cleanPart in current)) {
16150
- current[cleanPart] = {};
16151
- }
16152
- current = current[cleanPart];
16153
- }
16154
- // Use helper to support array append on final path part
16155
- this.setMappedValue(current, pathParts[pathParts.length - 1], value);
16156
- }
16157
- }
16158
- if (Object.keys(updateObj).length === 0) {
16159
- return null;
16160
- }
16161
- return {
16162
- updateElements: updateObj
16163
- };
16164
- }
16165
- catch (error) {
16166
- LogError(`Failed to parse SubAgentOutputMapping: ${error.message}`);
16167
- return null;
16168
- }
16169
- }
16170
- /**
16171
- * Sets a value in a target object, supporting array append operations.
16172
- * If the key ends with [], the value is appended to an array instead of replacing.
16173
- *
16174
- * @param target - Target object to modify
16175
- * @param key - Property key, optionally ending with [] for array append
16176
- * @param value - Value to set or append
16177
- * @private
16178
- */
16179
- /**
16180
- * Sets a value on a target object, honouring the `[]` array-append suffix.
16181
- *
16182
- * Delegates for the same reason as {@link getValueFromPath} — `results[]` must mean append in
16183
- * both engines, or a workflow accumulates in one and overwrites in the other.
16184
- */
16185
- setMappedValue(target, key, value) {
16186
- SetMappedValue(target, key, value);
15762
+ applySubAgentOutputMapping(subAgentResult, parentPayload, mappingConfig) {
15763
+ return this._stepDispatcher.ApplySubAgentOutputMapping(subAgentResult, parentPayload, mappingConfig, (obj, path) => this.getValueFromPath(obj, path));
16187
15764
  }
16188
15765
  /**
16189
15766
  * Applies sub-agent input mapping to prepare initial payload for related sub-agent.
@@ -16196,42 +15773,7 @@ The context is now within limits. Please retry your request with the recovered c
16196
15773
  * @private
16197
15774
  */
16198
15775
  applySubAgentInputMapping(parentPayload, mappingConfig) {
16199
- try {
16200
- const mapping = JSON.parse(mappingConfig);
16201
- const subAgentPayload = {};
16202
- for (const [parentPath, subAgentPath] of Object.entries(mapping)) {
16203
- let value;
16204
- if (parentPath === '*') {
16205
- // Wildcard - send entire parent payload to sub-agent
16206
- value = parentPayload;
16207
- }
16208
- else {
16209
- // Extract from parent payload using dot notation
16210
- value = this.getValueFromPath(parentPayload, parentPath);
16211
- }
16212
- if (value !== undefined) {
16213
- // Parse the sub-agent path and build nested object
16214
- const pathParts = subAgentPath.split('.');
16215
- let current = subAgentPayload;
16216
- for (let i = 0; i < pathParts.length - 1; i++) {
16217
- const part = pathParts[i];
16218
- if (!(part in current)) {
16219
- current[part] = {};
16220
- }
16221
- current = current[part];
16222
- }
16223
- current[pathParts[pathParts.length - 1]] = value;
16224
- }
16225
- }
16226
- if (Object.keys(subAgentPayload).length === 0) {
16227
- return null;
16228
- }
16229
- return subAgentPayload;
16230
- }
16231
- catch (error) {
16232
- LogError(`Failed to parse SubAgentInputMapping: ${error.message}`);
16233
- return null;
16234
- }
15776
+ return this._stepDispatcher.ApplySubAgentInputMapping(parentPayload, mappingConfig, (obj, path) => this.getValueFromPath(obj, path));
16235
15777
  }
16236
15778
  /**
16237
15779
  * Prepares a context message containing parent payload data for related sub-agent.
@@ -16249,46 +15791,7 @@ The context is now within limits. Please retry your request with the recovered c
16249
15791
  * @private
16250
15792
  */
16251
15793
  prepareRelatedSubAgentContextMessage(parentPayload, contextPaths, params) {
16252
- if (!contextPaths || contextPaths.length === 0) {
16253
- return null;
16254
- }
16255
- // Check for wildcard - send entire payload
16256
- if (contextPaths.includes('*')) {
16257
- return {
16258
- role: 'user',
16259
- content: `Parent Agent Context:\n\n${JSON.stringify(parentPayload, null, 2)}`
16260
- };
16261
- }
16262
- // Extract specific paths (supports both payload paths and conversation paths)
16263
- const contextData = {};
16264
- for (const path of contextPaths) {
16265
- let value;
16266
- // Check if this is a conversation reference
16267
- if (ConversationMessageResolver.isConversationReference(path) && params?.conversationMessages) {
16268
- value = ConversationMessageResolver.resolve(path, params.conversationMessages);
16269
- }
16270
- else {
16271
- // Regular payload path
16272
- value = this.getValueFromPath(parentPayload, path);
16273
- }
16274
- if (value !== undefined) {
16275
- contextData[path] = value;
16276
- }
16277
- }
16278
- if (Object.keys(contextData).length === 0) {
16279
- return null;
16280
- }
16281
- // Format as readable context
16282
- const contextLines = Object.entries(contextData).map(([key, value]) => {
16283
- const valueStr = typeof value === 'object'
16284
- ? JSON.stringify(value, null, 2)
16285
- : String(value);
16286
- return `${key}:\n${valueStr}`;
16287
- });
16288
- return {
16289
- role: 'user',
16290
- content: `Parent Agent Context:\n\n${contextLines.join('\n\n')}`
16291
- };
15794
+ return this._stepDispatcher.PrepareRelatedSubAgentContextMessage(parentPayload, contextPaths, params, (obj, path) => this.getValueFromPath(obj, path));
16292
15795
  }
16293
15796
  /**
16294
15797
  * Helper method to get a value from a nested object path.
@@ -17384,24 +16887,22 @@ The context is now within limits. Please retry your request with the recovered c
17384
16887
  };
17385
16888
  }
17386
16889
  const spec = this.canonicalizeTaskGraphSpec(rawSpec);
17387
- // Fail closed under bound parameters (ExecuteAgentParams.boundActionParams): a graph's action nodes
17388
- // are dispatched by the task-graph runner with the inputs the model authored, outside
17389
- // ExecuteSingleAction, so nothing would hide or apply a binding. The response type already withholds
17390
- // `tasks` from a bound run; this is the gate for a model that emits one anyway.
17391
- if (this.hasBoundActionParams(params.boundActionParams)) {
16890
+ // Fail closed on anything the graph could not carry (the same predicate the prompt used to hide `tasks`).
16891
+ const withheld = this.taskGraphRefusal(params, previousDecision);
16892
+ if (withheld) {
16893
+ return withheld;
16894
+ }
16895
+ const envelope = this.taskGraphSecurityEnvelope(params);
16896
+ if ('Refusal' in envelope) {
17392
16897
  return {
17393
16898
  step: 'Failed',
17394
16899
  terminate: true,
17395
- errorMessage: 'Task graphs are not available in a run with bound action parameters: a graph dispatches actions outside the binding gate.',
16900
+ errorMessage: `Task graph not submitted: ${envelope.Refusal}`,
17396
16901
  previousPayload: previousDecision.previousPayload,
17397
16902
  newPayload: previousDecision.newPayload || previousDecision.previousPayload
17398
16903
  };
17399
16904
  }
17400
- // Fail closed under an audience or a tenant-scoped run (taskGraphRefusal): a graph runs outside the run's gates.
17401
- const withheld = this.taskGraphRefusal(params, previousDecision);
17402
- if (withheld) {
17403
- return withheld;
17404
- }
16905
+ const securityEnvelope = envelope.Envelope;
17405
16906
  const stepEntity = await this.createStepEntity({
17406
16907
  stepType: 'TaskGraph',
17407
16908
  stepName: `Task Graph: ${spec.workflowName}`,
@@ -17437,9 +16938,10 @@ The context is now within limits. Please retry your request with the recovered c
17437
16938
  // path carried neither, so every documented `data.x` condition evaluated against the
17438
16939
  // origin step's output, found nothing, and silently took the other branch.
17439
16940
  Invocation: { Data: params.data, Context: params.context },
17440
- Debug: params.taskGraphDebug?.paused ? { paused: true } : undefined,
16941
+ Debug: BuildTaskGraphStartDebug(params.taskGraphDebug),
17441
16942
  ContextUser: params.contextUser,
17442
- Provider: this.ProviderToUse
16943
+ Provider: this.ProviderToUse,
16944
+ ...(securityEnvelope ? { SecurityEnvelope: securityEnvelope } : {}),
17443
16945
  });
17444
16946
  await this.finalizeStepEntity(stepEntity, outcome.Success, outcome.ErrorMessage, { spec, submitted: outcome.Success, parentTaskID: outcome.ParentTaskID });
17445
16947
  if (!outcome.Success) {
@@ -17473,6 +16975,44 @@ The context is now within limits. Please retry your request with the recovered c
17473
16975
  newPayload: previousDecision.newPayload || previousDecision.previousPayload
17474
16976
  };
17475
16977
  }
16978
+ /**
16979
+ * How a sub-agent run inherits this run's taint (S2). A sub-agent works from this run's context, so it
16980
+ * starts tainted when this run is tainted now, and carries the taint into its memory writes and any graph
16981
+ * it submits. When this run executes under a task-graph envelope (`params.SecurityEnvelope`), the
16982
+ * sub-agent gets that envelope with `IsRunTainted` set, and so refuses `disallowWhenTainted` actions as
16983
+ * an agent node does. A run outside any graph hands down only the taint (`ParentRunTainted`): its
16984
+ * sub-agent is held to what the run itself is, not to a gate the run is not under.
16985
+ */
16986
+ subAgentTaint(params) {
16987
+ const tainted = this.IsRunTainted || params.SecurityEnvelope?.IsRunTainted === true;
16988
+ if (params.SecurityEnvelope) {
16989
+ return { SecurityEnvelope: { ...params.SecurityEnvelope, IsRunTainted: tainted } };
16990
+ }
16991
+ return tainted ? { ParentRunTainted: true } : {};
16992
+ }
16993
+ /**
16994
+ * The security envelope a graph this run submits carries: the run's bound parameters, the readers its audience
16995
+ * adds, its validated scope exactly as each action dispatch is handed it ({@link runScopeFor}), the caller's
16996
+ * tenant context and its taint — merged with the envelope this run itself executes under, when it is a
16997
+ * task-graph node (`ExecuteAgentParams.SecurityEnvelope`), keeping the stricter of each part.
16998
+ */
16999
+ taskGraphSecurityEnvelope(params) {
17000
+ const scope = this.runScopeFor(params);
17001
+ const derived = BuildTaskSecurityEnvelope({
17002
+ BoundActionParams: params.boundActionParams,
17003
+ AudienceReaderUserIDs: AgentAudienceReaderIDs(params.Audience, params.contextUser?.ID),
17004
+ RunScope: {
17005
+ PrimaryScopeEntityName: scope.PrimaryScopeEntityName ?? null,
17006
+ PrimaryScopeRecordID: scope.PrimaryScopeRecordID,
17007
+ SecondaryScopes: scope.SecondaryScopes ?? null,
17008
+ ...(scope.SearchScopeIDs ? { SearchScopeIDs: scope.SearchScopeIDs } : {}),
17009
+ },
17010
+ CallerTenantContext: params.contextUser?.TenantContext,
17011
+ IsRunTainted: this.IsRunTainted,
17012
+ });
17013
+ const merged = MergeTaskSecurityEnvelopes(derived, params.SecurityEnvelope);
17014
+ return 'Reason' in merged ? { Refusal: merged.Reason } : { Envelope: merged.Envelope };
17015
+ }
17476
17016
  /**
17477
17017
  * Executes a `'Handoff'` next step: records the `'Handoff'` step entity with the resolved
17478
17018
  * target agent ID, stores {@link _handoffResult} for {@link ExecuteAgentResult.handoff},
@@ -17623,40 +17163,7 @@ The context is now within limits. Please retry your request with the recovered c
17623
17163
  * @protected
17624
17164
  */
17625
17165
  buildPlanApprovalForm(planText) {
17626
- return {
17627
- title: 'Review Plan',
17628
- description: 'Review the proposed plan below. Edit it if needed, then approve to proceed — or reject (with a note on what to change) and the agent will re-plan.',
17629
- submitLabel: 'Submit',
17630
- questions: [
17631
- {
17632
- id: 'plan',
17633
- label: 'Plan',
17634
- // markdown: agents author plans in Markdown (see the plan-mode prompt
17635
- // instructions); the UI renders a formatted preview with an Edit toggle.
17636
- type: { type: 'textarea', markdown: true },
17637
- defaultValue: planText,
17638
- required: true
17639
- },
17640
- {
17641
- id: 'reason',
17642
- label: 'Feedback',
17643
- type: { type: 'textarea', placeholder: 'Optional — if rejecting, tell the agent what to change and it will re-plan.' },
17644
- required: false
17645
- },
17646
- {
17647
- id: 'decision',
17648
- label: 'Decision',
17649
- type: {
17650
- type: 'buttongroup',
17651
- options: [
17652
- { value: 'approve', label: 'Approve' },
17653
- { value: 'reject', label: 'Reject' }
17654
- ]
17655
- },
17656
- required: true
17657
- }
17658
- ]
17659
- };
17166
+ return this._feedbackCoordinator.BuildPlanApprovalForm(planText);
17660
17167
  }
17661
17168
  async executeChatStep(params, previousDecision) {
17662
17169
  // Chat steps are successful immediately — record in a single INSERT instead of INSERT + UPDATE
@@ -17708,119 +17215,32 @@ The context is now within limits. Please retry your request with the recovered c
17708
17215
  await this.createFeedbackRequest(params, stepEntity, decision);
17709
17216
  }
17710
17217
  /**
17711
- * Creates a persistent AIAgentRequest row when a Chat step fires.
17712
- * Resolves the target user via the assignment chain:
17713
- * 1. contextUser (explicit caller)
17714
- * 2. AgentRun.UserID (run initiator)
17715
- * 3. Conversation.UserID (conversation fallback)
17716
- * 4. Agent.OwnerUserID (agent owner)
17717
- * 5. null (system-level, visible to admins)
17218
+ * Creates a persistent AIAgentRequest row when a Chat or Plan step fires.
17219
+ * Resolves the target user via the assignment chain (delegating to
17220
+ * {@link AgentFeedbackCoordinator.CreateFeedbackRequest}):
17221
+ * 1. ExecuteAgentParams.assignmentStrategy (per-invocation override)
17222
+ * 2. Agent Type's AssignmentStrategy
17223
+ * 3. Agent's Category AssignmentStrategy (walks up ParentID tree)
17224
+ * 4. Request Type's DefaultAssignmentStrategy
17225
+ * 5. Fallback: contextUser (explicit caller) or null (system-level, visible to admins)
17718
17226
  *
17719
17227
  * @private
17720
17228
  */
17721
17229
  async createFeedbackRequest(params, stepEntity, previousDecision) {
17722
- try {
17723
- const requestTypeId = await this.resolveRequestTypeId(previousDecision, params.contextUser);
17724
- const resolvedStrategy = await this.resolveAssignmentStrategy(params, requestTypeId);
17725
- const requestForUserId = this.resolveUserFromStrategy(resolvedStrategy, params);
17726
- const priority = resolvedStrategy?.priority ?? 50;
17727
- const expirationMinutes = resolvedStrategy?.expirationMinutes;
17728
- const request = await (params.provider || this._activeProvider).GetEntityObject('MJ: AI Agent Requests', params.contextUser);
17729
- request.NewRecord();
17730
- request.AgentID = params.agent.ID;
17731
- request.RequestedAt = new Date();
17732
- request.RequestForUserID = requestForUserId;
17733
- request.Status = 'Requested';
17734
- request.Request = previousDecision.message || 'Agent needs user input';
17735
- request.RequestTypeID = requestTypeId;
17736
- request.ResponseSchema = previousDecision.responseForm
17737
- ? JSON.stringify(previousDecision.responseForm)
17738
- : null;
17739
- request.Priority = priority;
17740
- request.OriginatingAgentRunID = this._agentRun?.ID || null;
17741
- request.OriginatingAgentRunStepID = stepEntity.ID;
17742
- if (expirationMinutes != null && expirationMinutes > 0) {
17743
- request.ExpiresAt = new Date(Date.now() + expirationMinutes * 60_000);
17744
- }
17745
- const saved = await request.Save();
17746
- if (saved) {
17747
- this._feedbackRequestId = request.ID;
17748
- this.logStatus(`📋 Created feedback request ${request.ID} for user ${requestForUserId || '(system)'}`, true, params);
17749
- }
17750
- else {
17751
- LogError(`Failed to save AIAgentRequest for agent ${params.agent.Name}`);
17752
- }
17753
- }
17754
- catch (error) {
17755
- // Don't let request creation failure break the agent execution
17756
- LogError(`Error creating feedback request: ${error.message}`);
17757
- }
17758
- }
17759
- /**
17760
- * Walks the assignment strategy resolution chain (bottom-up, first-non-null wins):
17761
- * 1. ExecuteAgentParams.assignmentStrategy (per-invocation)
17762
- * 2. Agent Type's AssignmentStrategy
17763
- * 3. Agent's Category AssignmentStrategy (walks up ParentID tree)
17764
- * 4. Request Type's DefaultAssignmentStrategy
17765
- * 5. Fallback: null (caller uses contextUser + warning)
17766
- * @private
17767
- */
17768
- async resolveAssignmentStrategy(params, requestTypeId) {
17769
- // 1. Per-invocation override (highest precedence)
17770
- if (params.assignmentStrategy) {
17771
- return params.assignmentStrategy;
17772
- }
17773
- // 2. Agent Type's AssignmentStrategy
17774
- const agentType = AIEngine.Instance.AgentTypes.find(at => UUIDsEqual(at.ID, params.agent.TypeID));
17775
- const typeStrategy = parseAssignmentStrategy(agentType?.AssignmentStrategy ?? null);
17776
- if (typeStrategy) {
17777
- return typeStrategy;
17778
- }
17779
- // 3. Agent's Category AssignmentStrategy (walk up ParentID tree)
17780
- const categoryStrategy = await this.resolveCategoryAssignmentStrategy(params);
17781
- if (categoryStrategy) {
17782
- return categoryStrategy;
17783
- }
17784
- // 4. Request Type's DefaultAssignmentStrategy (request types are cached on the AI engine)
17785
- if (requestTypeId) {
17786
- const requestType = AIEngine.Instance.AgentRequestTypes.find(t => UUIDsEqual(t.ID, requestTypeId));
17787
- if (requestType) {
17788
- const rtStrategy = parseAssignmentStrategy(requestType.DefaultAssignmentStrategy);
17789
- if (rtStrategy) {
17790
- return rtStrategy;
17791
- }
17792
- }
17793
- }
17794
- return null;
17795
- }
17796
- /**
17797
- * Walks up the agent's category hierarchy looking for an AssignmentStrategy.
17798
- * Uses AIEngine.Instance.AgentCategories (cached during engine Config).
17799
- */
17800
- async resolveCategoryAssignmentStrategy(params) {
17801
- const categoryId = params.agent.CategoryID;
17802
- if (!categoryId)
17803
- return null;
17804
- try {
17805
- const categories = AIEngine.Instance.AgentCategories;
17806
- // Walk up the tree from the agent's category to the root
17807
- let currentId = categoryId;
17808
- const visited = new Set(); // prevent infinite loops
17809
- while (currentId && !visited.has(currentId)) {
17810
- visited.add(currentId);
17811
- const cat = categories.find(c => UUIDsEqual(c.ID, currentId));
17812
- if (!cat)
17813
- break;
17814
- const strategy = parseAssignmentStrategy(cat.AssignmentStrategy);
17815
- if (strategy)
17816
- return strategy;
17817
- currentId = cat.ParentID;
17818
- }
17819
- }
17820
- catch (error) {
17821
- LogError(`Error resolving category assignment strategy: ${error.message}`);
17230
+ // The step's INSERT is fire-and-forget (createStepEntity), and the request row has a foreign key to it
17231
+ // (FK_AIAgentRequest_OriginatingStep). Without this wait the request's INSERT can reach the database
17232
+ // first and fail; the coordinator logs that and returns null, and the run pauses with no request to answer.
17233
+ await this._stepSaveQueue.Settled(stepEntity);
17234
+ const requestId = await this._feedbackCoordinator.CreateFeedbackRequest({
17235
+ Params: params,
17236
+ StepEntity: stepEntity,
17237
+ Decision: previousDecision,
17238
+ AgentRun: this._agentRun,
17239
+ Provider: params.provider || this._activeProvider,
17240
+ });
17241
+ if (requestId) {
17242
+ this._feedbackRequestId = requestId;
17822
17243
  }
17823
- return null;
17824
17244
  }
17825
17245
  /**
17826
17246
  * Resolves the file storage account ID for this agent's file artifacts.
@@ -17839,94 +17259,6 @@ The context is now within limits. Please retry your request with the recovered c
17839
17259
  async getStorageAccountID(params) {
17840
17260
  return AIEngine.Instance.ResolveAgentStorageAccountID(params.agent, params.override?.storageAccountId);
17841
17261
  }
17842
- /**
17843
- * Resolves the target user ID from a resolved assignment strategy.
17844
- * For simple strategies (RunUser, AgentOwner, SpecificUser), resolves immediately.
17845
- * For List/SharedInbox strategies, delegates to list-based resolution.
17846
- * Falls back to contextUser with a warning if no strategy is provided.
17847
- * @private
17848
- */
17849
- resolveUserFromStrategy(strategy, params) {
17850
- if (!strategy) {
17851
- // No strategy resolved anywhere — fall back to contextUser + warning
17852
- if (params.contextUser?.ID) {
17853
- LogStatus(`⚠️ No assignment strategy configured for agent ${params.agent.Name}; defaulting to context user`);
17854
- return params.contextUser.ID;
17855
- }
17856
- LogStatus(`⚠️ No assignment strategy and no context user for agent ${params.agent.Name}; request will be unassigned`);
17857
- return null;
17858
- }
17859
- switch (strategy.type) {
17860
- case 'RunUser':
17861
- return params.contextUser?.ID
17862
- ?? this._agentRun?.UserID
17863
- ?? null;
17864
- case 'AgentOwner':
17865
- return params.agent.OwnerUserID ?? null;
17866
- case 'SpecificUser':
17867
- return strategy.userID ?? null;
17868
- case 'List':
17869
- // List-based resolution (RoundRobin, LeastBusy, Random) requires async DB lookups.
17870
- // For now, fall back to contextUser. Full list resolution is a future enhancement
17871
- // that will query ListDetail records and track assignment state.
17872
- LogStatus(`ℹ️ List-based assignment strategy configured but not yet implemented; defaulting to context user`);
17873
- return params.contextUser?.ID ?? null;
17874
- case 'SharedInbox':
17875
- // SharedInbox means "unassigned — anyone in the list can claim it"
17876
- return null;
17877
- default:
17878
- return params.contextUser?.ID ?? null;
17879
- }
17880
- }
17881
- /**
17882
- * Determines the request type ID based on the Chat step's context.
17883
- * - If the responseForm has only approve/reject-style buttons, uses "Approval"
17884
- * - If there's a responseForm with fields, uses "Information"
17885
- * - Otherwise defaults to "Information"
17886
- *
17887
- * Request types come from the AI engine's cached `MJ: AI Agent Request Types` rows
17888
- * (`AIEngineBase.ResolveAgentRequestTypeID`), the same source the agent actions use.
17889
- * @private
17890
- */
17891
- async resolveRequestTypeId(previousDecision, contextUser) {
17892
- try {
17893
- // Determine type name based on responseForm content
17894
- let typeName = 'Information'; // default
17895
- if (previousDecision.responseForm) {
17896
- typeName = this.detectRequestTypeName(previousDecision.responseForm);
17897
- }
17898
- return await AIEngine.Instance.ResolveAgentRequestTypeID(typeName, contextUser);
17899
- }
17900
- catch (error) {
17901
- LogError(`Error resolving request type: ${error.message}`);
17902
- return null;
17903
- }
17904
- }
17905
- /**
17906
- * Inspects an AgentResponseForm to determine the best request type name.
17907
- * Returns "Approval" if the form is a simple two-option approve/reject pattern,
17908
- * otherwise returns "Information".
17909
- * @private
17910
- */
17911
- detectRequestTypeName(form) {
17912
- const q = form.questions?.[0];
17913
- if (!q || form.questions.length !== 1) {
17914
- return 'Information';
17915
- }
17916
- const qType = q.type;
17917
- if ((qType.type === 'buttongroup' || qType.type === 'radio') && 'options' in qType) {
17918
- const opts = qType.options;
17919
- if (opts.length === 2) {
17920
- const labels = opts.map(o => o.label.toLowerCase());
17921
- const hasPositive = labels.some(l => l.includes('approv') || l.includes('yes') || l.includes('accept'));
17922
- const hasNegative = labels.some(l => l.includes('reject') || l.includes('no') || l.includes('deny'));
17923
- if (hasPositive && hasNegative) {
17924
- return 'Approval';
17925
- }
17926
- }
17927
- }
17928
- return 'Information';
17929
- }
17930
17262
  /**
17931
17263
  * Executes a ForEach loop with actual for loop
17932
17264
  */
@@ -17957,22 +17289,10 @@ The context is now within limits. Please retry your request with the recovered c
17957
17289
  return this.completeForEachLoop(forEach, loopStepEntity, loopResults, previousDecision, params);
17958
17290
  }
17959
17291
  validateWhileOperation(whileOp, agentId = this._agentRun?.AgentID ?? '') {
17960
- if (!whileOp.condition || whileOp.condition.trim() === '') {
17961
- return 'Condition is required';
17962
- }
17963
- if (!whileOp.itemVariable || whileOp.itemVariable.trim() === '') {
17964
- return 'Item variable is required';
17965
- }
17966
- return this.validateLoopBodyOperation('While', whileOp, agentId);
17292
+ return this._stepDispatcher.ValidateWhileOperation(whileOp, (kind, op) => this.validateLoopBodyOperation(kind, op, agentId));
17967
17293
  }
17968
17294
  validateForEachHeader(forEach) {
17969
- if (!forEach.itemVariable || forEach.itemVariable.trim() === '') {
17970
- return 'Item variable is required';
17971
- }
17972
- if (!forEach.collectionPath || forEach.collectionPath.trim() === '') {
17973
- return 'Collection path is required';
17974
- }
17975
- return null;
17295
+ return this._stepDispatcher.ValidateForEachHeader(forEach);
17976
17296
  }
17977
17297
  /**
17978
17298
  * Validates the loop body arm (`action` | `steps` | `subAgent`) shared by `ForEach` and `While`.
@@ -18082,24 +17402,7 @@ The context is now within limits. Please retry your request with the recovered c
18082
17402
  * Strips "payload." prefix if present (for LLM convenience)
18083
17403
  */
18084
17404
  getCollectionFromPayload(payload, path) {
18085
- // Support a literal static collection: "static:[1,2,3,4,5]". This lets a ForEach iterate a
18086
- // fixed list/range without a prior step having to build the array in the payload first.
18087
- const trimmed = path.trim();
18088
- if (trimmed.toLowerCase().startsWith('static:')) {
18089
- try {
18090
- const parsed = JSON.parse(trimmed.substring(trimmed.indexOf(':') + 1).trim());
18091
- return Array.isArray(parsed) ? parsed : null;
18092
- }
18093
- catch {
18094
- return null;
18095
- }
18096
- }
18097
- // Remove "payload." prefix if present
18098
- const cleanPath = path.toLowerCase().startsWith('payload.')
18099
- ? path.substring(8)
18100
- : path;
18101
- const value = this.getValueFromPath(payload, cleanPath);
18102
- return Array.isArray(value) ? value : null;
17405
+ return this._stepDispatcher.GetCollectionFromPayload(payload, path, (obj, p) => this.getValueFromPath(obj, p));
18103
17406
  }
18104
17407
  /**
18105
17408
  * Helper: Create parent ForEach loop step (not finalized until loop completes)
@@ -18200,55 +17503,20 @@ The context is now within limits. Please retry your request with the recovered c
18200
17503
  * Each batch contains up to maxConcurrency items with their original indices.
18201
17504
  */
18202
17505
  createBatches(items, maxConcurrency) {
18203
- const batches = [];
18204
- for (let i = 0; i < items.length; i += maxConcurrency) {
18205
- const batch = items.slice(i, i + maxConcurrency).map((item, batchOffset) => ({
18206
- item,
18207
- index: i + batchOffset
18208
- }));
18209
- batches.push(batch);
18210
- }
18211
- return batches;
17506
+ return this._stepDispatcher.CreateBatches(items, maxConcurrency);
18212
17507
  }
18213
17508
  /**
18214
17509
  * Apply ForEach results sequentially to build final payload.
18215
17510
  * This ensures payload changes are applied in order even when iterations ran in parallel.
18216
17511
  */
18217
17512
  applyForEachResultsSequentially(sortedResults, initialPayload, continueOnError) {
18218
- let currentPayload = initialPayload;
18219
- const results = [];
18220
- const errors = [];
18221
- for (const { result, error, payload, appliedFolds } of sortedResults) {
18222
- if (error) {
18223
- errors.push(error);
18224
- if (!continueOnError) {
18225
- break;
18226
- }
18227
- }
18228
- else if (result) {
18229
- results.push(result);
18230
- if (appliedFolds && appliedFolds.length > 0) {
18231
- for (const fold of appliedFolds) {
18232
- currentPayload = this.applyLoopOutputFold(currentPayload, fold.output, fold.mapping);
18233
- }
18234
- }
18235
- else {
18236
- // Apply payload change from this iteration
18237
- currentPayload = payload || currentPayload;
18238
- }
18239
- }
18240
- }
18241
- return { results, errors, finalPayload: currentPayload };
17513
+ return this._stepDispatcher.ApplyForEachResultsSequentially(sortedResults, initialPayload, continueOnError, (p) => this.cloneSubAgentPayload(p));
18242
17514
  }
18243
17515
  extractActionOutputObject(summaries) {
18244
- return BuildActionOutputObject(summaries[0]?.params, summaries[0]?.message);
17516
+ return this._stepDispatcher.ExtractActionOutputObject(summaries);
18245
17517
  }
18246
17518
  applyLoopOutputFold(basePayload, output, mapping) {
18247
- const target = IsPlainObject(basePayload)
18248
- ? this.cloneSubAgentPayload(basePayload)
18249
- : {};
18250
- const mapped = ApplyOutputMapping(output, mapping, target);
18251
- return mapped.updates;
17519
+ return this._stepDispatcher.ApplyLoopOutputFold(basePayload, output, mapping, (p) => this.cloneSubAgentPayload(p));
18252
17520
  }
18253
17521
  /**
18254
17522
  * Executes an ordered sequence of `LoopBodyActionStep` actions inside a single `ForEach` or `While`
@@ -18458,24 +17726,16 @@ The context is now within limits. Please retry your request with the recovered c
18458
17726
  }
18459
17727
  return this.createFailedStep(errorMessage, previousDecision);
18460
17728
  }
18461
- /**
18462
- * One loop error as readable text. Joining the error objects directly wrote "[object Object]"
18463
- * into the step's ErrorMessage. Falls back to JSON when an iteration threw something with no
18464
- * message (a thrown non-Error).
18465
- */
18466
- describeLoopError(err) {
18467
- return err.message ? err.message : JSON.stringify(err);
18468
- }
18469
17729
  /** All loop errors as text for a step's ErrorMessage. */
18470
17730
  formatLoopErrors(errors) {
18471
- return errors.map(err => this.describeLoopError(err)).join('\n\n');
17731
+ return this._stepDispatcher.FormatLoopErrors(errors);
18472
17732
  }
18473
17733
  /**
18474
17734
  * Formats loop iteration results as markdown. Handles two distinct result shapes
18475
17735
  * depending on whether the loop body executed actions or sub-agents:
18476
17736
  *
18477
17737
  * - **Action iterations**: `priorStepResult` is an `ActionResultSummary[]`, set by
18478
- * `executeActionsStep()` (line ~7003). These are formatted via `formatActionResultsAsMarkdown()`.
17738
+ * `executeActionsStep()`. These are formatted via `formatActionResultsAsMarkdown()`.
18479
17739
  *
18480
17740
  * - **Sub-agent iterations**: `priorStepResult` is a **pre-formatted markdown string**,
18481
17741
  * set by the loop handlers (`executeSingleForEachIteration` / `executeSingleWhileIteration`)
@@ -18487,33 +17747,7 @@ The context is now within limits. Please retry your request with the recovered c
18487
17747
  * markdown style used by non-loop results, ensuring consistency across the codebase.
18488
17748
  */
18489
17749
  formatLoopResultsAsMarkdown(results, errors) {
18490
- const lines = [];
18491
- for (let i = 0; i < results.length; i++) {
18492
- const iterResult = results[i].priorStepResult;
18493
- // Action iterations: priorStepResult is ActionResultSummary[] — format via shared helper
18494
- if (Array.isArray(iterResult)) {
18495
- lines.push(`### Iteration ${i + 1}`);
18496
- lines.push(this.formatActionResultsAsMarkdown(iterResult));
18497
- }
18498
- else if (iterResult != null) {
18499
- // Sub-agent iterations: priorStepResult is already a markdown string from
18500
- // formatSubAgentResultAsMarkdown() called in the loop handler. Non-string
18501
- // results (edge cases) are JSON-stringified as a fallback.
18502
- lines.push(`### Iteration ${i + 1}`);
18503
- const text = typeof iterResult === 'string'
18504
- ? iterResult
18505
- : JSON.stringify(iterResult);
18506
- lines.push(text);
18507
- }
18508
- // null/undefined priorStepResult: iteration produced no output — skip silently
18509
- }
18510
- if (errors.length > 0) {
18511
- lines.push(`### Errors`);
18512
- for (const err of errors) {
18513
- lines.push(`• ✗ ${this.describeLoopError(err)}`);
18514
- }
18515
- }
18516
- return lines.join('\n');
17750
+ return this._stepDispatcher.FormatLoopResultsAsMarkdown(results, errors, this._actionResultCrush, (summaries) => this.formatActionResultsAsMarkdown(summaries));
18517
17751
  }
18518
17752
  /**
18519
17753
  * Resolves expiration/compaction metadata for loop result messages by looking up
@@ -18611,13 +17845,7 @@ The context is now within limits. Please retry your request with the recovered c
18611
17845
  * Helper: Create failed step
18612
17846
  */
18613
17847
  createFailedStep(errorMessage, previousDecision) {
18614
- return {
18615
- step: 'Failed',
18616
- terminate: false,
18617
- errorMessage,
18618
- previousPayload: previousDecision.previousPayload,
18619
- newPayload: previousDecision.newPayload || previousDecision.previousPayload
18620
- };
17848
+ return this._stepDispatcher.CreateFailedStep(errorMessage, previousDecision);
18621
17849
  }
18622
17850
  /**
18623
17851
  * Executes a While loop with actual while loop
@@ -18828,8 +18056,8 @@ The context is now within limits. Please retry your request with the recovered c
18828
18056
  : errorMessage;
18829
18057
  // Calculate total tokens even for failed runs
18830
18058
  this.applyTokenStatsToRun(this._agentRun, this.calculateTokenStats());
18831
- await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
18832
- AgentRunWatchdog.Instance.Untrack(this._agentRun.ID);
18059
+ const ok = await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
18060
+ this.releaseFinishedRun(ok);
18833
18061
  }
18834
18062
  return {
18835
18063
  success: false,
@@ -18846,6 +18074,12 @@ The context is now within limits. Please retry your request with the recovered c
18846
18074
  * @returns {Promise<ExecuteAgentResult>} The cancelled result
18847
18075
  */
18848
18076
  async createCancelledResult(message, contextUser) {
18077
+ // The watchdog aborts a run it force-failed with the row's own message (#4883). The row
18078
+ // already says Failed and clients were told so; finalizing Cancelled would contradict it.
18079
+ const abortReason = this._runAbortController?.signal.reason;
18080
+ if (AgentRunWatchdog.IsForceFailedAbortReason(typeof abortReason === 'string' ? abortReason : null)) {
18081
+ return this.createFailureResult(abortReason, contextUser);
18082
+ }
18849
18083
  const [{ failures }] = await Promise.all([
18850
18084
  this._stepSaveQueue.Flush(),
18851
18085
  this.flushPromptRunnerSaves(),
@@ -18874,8 +18108,8 @@ The context is now within limits. Please retry your request with the recovered c
18874
18108
  }
18875
18109
  // Calculate total tokens even for cancelled runs
18876
18110
  this.applyTokenStatsToRun(this._agentRun, this.calculateTokenStats());
18877
- await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
18878
- AgentRunWatchdog.Instance.Untrack(this._agentRun.ID);
18111
+ const ok = await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
18112
+ this.releaseFinishedRun(ok);
18879
18113
  }
18880
18114
  return {
18881
18115
  success: false,
@@ -18887,7 +18121,9 @@ The context is now within limits. Please retry your request with the recovered c
18887
18121
  * Maps the reason an abort signal carried to the run's `CancellationReason` value: the
18888
18122
  * watchdog's stop relay raises {@link AgentRunWatchdog.UserCancelAbortReason} for a row marked
18889
18123
  * `User Request`; the wall-clock guard's reason starts with {@link AgentTimeoutAbortReason};
18890
- * anything else (an upstream caller's token, a shutdown) is `System`.
18124
+ * anything else (an upstream caller's token, a shutdown) is `System`. A watchdog force-fail
18125
+ * ({@link AgentRunWatchdog.ForceFailedAbortReason}) never gets here: {@link createCancelledResult}
18126
+ * finalizes it `Failed`, with no cancellation reason.
18891
18127
  */
18892
18128
  static CancellationReasonForAbort(reason) {
18893
18129
  if (reason === AgentRunWatchdog.UserCancelAbortReason) {
@@ -18922,6 +18158,18 @@ The context is now within limits. Please retry your request with the recovered c
18922
18158
  }
18923
18159
  return null;
18924
18160
  }
18161
+ /**
18162
+ * Stops the watchdog guarding this run once its final state is saved. MJAPI's event-loop
18163
+ * stall warning names the runs "in flight" from the watchdog's tracked set, and the periodic
18164
+ * prune only drops finished runs every few minutes, so without this the warning would name
18165
+ * runs that ended long before the stall (MJ #5510). A failed save keeps the run tracked: the
18166
+ * watchdog's heartbeat and sweep still own a run whose final state never reached the database.
18167
+ */
18168
+ releaseFinishedRun(saved) {
18169
+ if (saved && this._agentRun?.ID && this._agentRun.Status !== 'Running') {
18170
+ AgentRunWatchdog.Instance.Untrack(this._agentRun.ID);
18171
+ }
18172
+ }
18925
18173
  /**
18926
18174
  * Finalizes the agent run with success.
18927
18175
  *
@@ -19006,7 +18254,7 @@ The context is now within limits. Please retry your request with the recovered c
19006
18254
  // Calculate total tokens from all prompts and sub-agents
19007
18255
  this.applyTokenStatsToRun(this._agentRun, this.calculateTokenStats());
19008
18256
  const ok = await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
19009
- AgentRunWatchdog.Instance.Untrack(this._agentRun.ID);
18257
+ this.releaseFinishedRun(ok);
19010
18258
  if (!ok) {
19011
18259
  LogError(`Failed to finalize agent run ${this._agentRun.ID}`);
19012
18260
  }
@@ -19053,6 +18301,16 @@ The context is now within limits. Please retry your request with the recovered c
19053
18301
  }
19054
18302
  // Return unified media outputs — all items are persisted by AgentRunner.
19055
18303
  // Sub-agents pass their mediaOutputs to parent for merging and placeholder resolution.
18304
+ const touchedMap = new Map();
18305
+ for (const item of this._artifactToolManager.GetTouchedArtifacts()) {
18306
+ const key = item.ArtifactID.trim().toLowerCase();
18307
+ touchedMap.set(key, MergeTouchedArtifactSummary(touchedMap.get(key), item));
18308
+ }
18309
+ for (const item of GovernedArtifactService.Instance.ConsumeTouchedArtifacts(this._agentRun?.ID)) {
18310
+ const key = item.ArtifactID.trim().toLowerCase();
18311
+ touchedMap.set(key, MergeTouchedArtifactSummary(touchedMap.get(key), item));
18312
+ }
18313
+ const touchedArtifacts = touchedMap.size > 0 ? Array.from(touchedMap.values()) : undefined;
19056
18314
  return {
19057
18315
  success: finalStep.step === 'Success' || finalStep.step === 'Chat',
19058
18316
  payload: resolvedPayload,
@@ -19069,7 +18327,8 @@ The context is now within limits. Please retry your request with the recovered c
19069
18327
  feedbackRequestId: this._feedbackRequestId || undefined,
19070
18328
  taintedSources: this._taintedSources.length > 0 ? [...this._taintedSources] : undefined,
19071
18329
  handoff: this._handoffResult || undefined,
19072
- resolvedStorageAccountId: this._resolvedStorageAccountId || undefined
18330
+ resolvedStorageAccountId: this._resolvedStorageAccountId || undefined,
18331
+ ...(touchedArtifacts ? { touchedArtifacts } : {})
19073
18332
  };
19074
18333
  }
19075
18334
  /**
@@ -19079,38 +18338,7 @@ The context is now within limits. Please retry your request with the recovered c
19079
18338
  * @private
19080
18339
  */
19081
18340
  calculateTokenStats() {
19082
- let totalTokens = 0;
19083
- let promptTokens = 0;
19084
- let completionTokens = 0;
19085
- let cacheReadTokens = 0;
19086
- let cacheWriteTokens = 0;
19087
- let totalCost = 0;
19088
- // Iterate through the agent run's steps to sum up tokens
19089
- if (this._agentRun?.Steps) {
19090
- for (const step of this._agentRun.Steps) {
19091
- if ((step.StepType === 'Prompt' || step.StepType === 'Compaction' || step.StepType === 'Decision') && step.PromptRun) {
19092
- // Add tokens from prompt runs (rollup fields include any nested child prompt runs).
19093
- // A Decision step carries its own decision call's run — the Finish check, a single-state
19094
- // request, or one item of a forEachItemIn request — so each call is counted once.
19095
- totalTokens += step.PromptRun.TokensUsedRollup || 0;
19096
- promptTokens += step.PromptRun.TokensPromptRollup || 0;
19097
- completionTokens += step.PromptRun.TokensCompletionRollup || 0;
19098
- cacheReadTokens += step.PromptRun.TokensCacheReadRollup || 0;
19099
- cacheWriteTokens += step.PromptRun.TokensCacheWriteRollup || 0;
19100
- totalCost += step.PromptRun.TotalCost || 0;
19101
- }
19102
- else if (step.StepType === 'Sub-Agent' && step.SubAgentRun) {
19103
- // Add tokens from sub-agent runs (these should already be calculated recursively)
19104
- totalTokens += step.SubAgentRun.TotalTokensUsed || 0;
19105
- promptTokens += step.SubAgentRun.TotalPromptTokensUsed || 0;
19106
- completionTokens += step.SubAgentRun.TotalCompletionTokensUsed || 0;
19107
- cacheReadTokens += step.SubAgentRun.TotalCacheReadTokensUsed || 0;
19108
- cacheWriteTokens += step.SubAgentRun.TotalCacheWriteTokensUsed || 0;
19109
- totalCost += step.SubAgentRun.TotalCost || 0;
19110
- }
19111
- }
19112
- }
19113
- return { totalTokens, promptTokens, completionTokens, cacheReadTokens, cacheWriteTokens, totalCost };
18341
+ return this._budgetTracker.CalculateRunTokenStats(this._agentRun);
19114
18342
  }
19115
18343
  /**
19116
18344
  * Applies a {@link calculateTokenStats} result to a run entity's six denormalized
@@ -19120,12 +18348,7 @@ The context is now within limits. Please retry your request with the recovered c
19120
18348
  * @private
19121
18349
  */
19122
18350
  applyTokenStatsToRun(run, tokenStats) {
19123
- run.TotalTokensUsed = tokenStats.totalTokens;
19124
- run.TotalPromptTokensUsed = tokenStats.promptTokens;
19125
- run.TotalCompletionTokensUsed = tokenStats.completionTokens;
19126
- run.TotalCacheReadTokensUsed = tokenStats.cacheReadTokens;
19127
- run.TotalCacheWriteTokensUsed = tokenStats.cacheWriteTokens;
19128
- run.TotalCost = tokenStats.totalCost;
18351
+ this._budgetTracker.ApplyTokenStatsToRun(run, tokenStats);
19129
18352
  }
19130
18353
  /**
19131
18354
  * Gets the count of how many times a specific action has been executed in this agent run.
@@ -19158,8 +18381,7 @@ The context is now within limits. Please retry your request with the recovered c
19158
18381
  * @protected
19159
18382
  */
19160
18383
  incrementExecutionCount(itemId) {
19161
- const currentCount = this._executionCounts.get(itemId) || 0;
19162
- this._executionCounts.set(itemId, currentCount + 1);
18384
+ this._budgetTracker.IncrementExecutionCount(this._executionCounts, itemId);
19163
18385
  }
19164
18386
  /**
19165
18387
  * Gets the execution count for an item (action or sub-agent).
@@ -19169,7 +18391,7 @@ The context is now within limits. Please retry your request with the recovered c
19169
18391
  * @protected
19170
18392
  */
19171
18393
  getExecutionCount(itemId) {
19172
- return this._executionCounts.get(itemId) || 0;
18394
+ return this._budgetTracker.GetExecutionCount(this._executionCounts, itemId);
19173
18395
  }
19174
18396
  /**
19175
18397
  * Checks if all minimum execution requirements are met for actions and sub-agents.
@@ -19833,9 +19055,17 @@ The context is now within limits. Please retry your request with the recovered c
19833
19055
  if (!memoryManagerEntity || !params.contextUser) {
19834
19056
  return;
19835
19057
  }
19836
- const driverKey = memoryManagerEntity.DriverClass || 'MemoryManagerAgent';
19837
- const memoryAgent = MJGlobal.Instance.ClassFactory.CreateInstance(BaseAgent, driverKey);
19838
- if (!memoryAgent) {
19058
+ // Resolved like every other agent (CreateAgentInstance); a Memory Manager row matched by name
19059
+ // with no DriverClass still runs its own class rather than the plain BaseAgent.
19060
+ let memoryAgent;
19061
+ try {
19062
+ memoryAgent = await CreateAgentInstance({
19063
+ Name: memoryManagerEntity.Name,
19064
+ DriverClass: memoryManagerEntity.DriverClass?.trim() || 'MemoryManagerAgent',
19065
+ });
19066
+ }
19067
+ catch (error) {
19068
+ LogError(`Post-run MemoryManager not started: ${error instanceof Error ? error.message : String(error)}`);
19839
19069
  return;
19840
19070
  }
19841
19071
  void memoryAgent.Execute({
@@ -20062,16 +19292,29 @@ The context is now within limits. Please retry your request with the recovered c
20062
19292
  }
20063
19293
  /**
20064
19294
  * Provides an improved heuristic token count when tokenizer is unavailable.
19295
+ * Zero-allocation scan over character codes to prevent multi-megabyte match arrays on large tool outputs.
20065
19296
  * @param text - The text to estimate tokens for
20066
19297
  * @returns Estimated token count
20067
19298
  * @private
20068
19299
  */
20069
19300
  heuristicTokenCount(text) {
20070
- // More sophisticated heuristic
20071
19301
  const charCount = text.length;
20072
- // Count structural tokens (JSON syntax adds overhead)
20073
- const structuralChars = (text.match(/[\{\}\[\],:]/g) || []).length;
20074
- const whitespaceChars = (text.match(/\s/g) || []).length;
19302
+ // Count structural tokens ({, }, [, ], ,, :) and whitespace characters without regex match arrays
19303
+ let structuralChars = 0;
19304
+ let whitespaceChars = 0;
19305
+ for (let i = 0; i < charCount; i++) {
19306
+ const code = text.charCodeAt(i);
19307
+ // Structural characters: { (123), } (125), [ (91), ] (93), , (44), : (58)
19308
+ if (code === 123 || code === 125 || code === 91 || code === 93 || code === 44 || code === 58) {
19309
+ structuralChars++;
19310
+ }
19311
+ else if (code === 32 || (code >= 9 && code <= 13)) {
19312
+ whitespaceChars++;
19313
+ }
19314
+ else if (code >= 0x00a0 && /\s/.test(text[i])) {
19315
+ whitespaceChars++;
19316
+ }
19317
+ }
20075
19318
  // Effective character count (whitespace counts less)
20076
19319
  const effectiveChars = charCount - (whitespaceChars * 0.5);
20077
19320
  // Base ratio: 4 chars per token
@@ -20197,22 +19440,7 @@ The context is now within limits. Please retry your request with the recovered c
20197
19440
  * Resolves templates like {{item.field}}, {{index}}, etc. in action parameters and sub-agent payloads
20198
19441
  */
20199
19442
  resolveTemplates(obj, context, itemVariable) {
20200
- const result = {};
20201
- for (const [key, value] of Object.entries(obj)) {
20202
- if (typeof value === 'string') {
20203
- result[key] = this.resolveValueFromContext(value, context, itemVariable);
20204
- }
20205
- else if (Array.isArray(value)) {
20206
- result[key] = value.map(v => typeof v === 'string' ? this.resolveValueFromContext(v, context, itemVariable) : v);
20207
- }
20208
- else if (typeof value === 'object' && value !== null) {
20209
- result[key] = this.resolveTemplates(value, context, itemVariable);
20210
- }
20211
- else {
20212
- result[key] = value;
20213
- }
20214
- }
20215
- return result;
19443
+ return this._stepDispatcher.ResolveTemplates(obj, context, itemVariable, (val, ctx, iv) => this.resolveValueFromContext(val, ctx, iv), (nested, ctx, iv) => this.resolveTemplates(nested, ctx, iv));
20216
19444
  }
20217
19445
  /**
20218
19446
  * Resolves a value from context using variable references - extracts from LoopAgentType
@@ -20233,52 +19461,10 @@ The context is now within limits. Please retry your request with the recovered c
20233
19461
  * Template: "{{user}}" → resolves to entire object {name: "Alice", age: 30}
20234
19462
  */
20235
19463
  resolveValueFromContext(value, context, itemVariable) {
20236
- // check to see if value is wrapped in a nunjucks style template like {{variable}} and
20237
- // if so, remove that wrapping to get the actual variable name.
20238
- // we only do this if the string starts and ends with the {{ }} pattern
20239
- // and we trim whitespace first
20240
- const trimmedValue = value.trim();
20241
- if (trimmedValue.startsWith('{{') && trimmedValue.endsWith('}}') && !trimmedValue.slice(2, -2).includes('{{')) {
20242
- // Single-variable case: "{{city.name}}" — strip wrappers, fall through to
20243
- // single-variable resolution below which can return non-string types (objects, numbers)
20244
- value = trimmedValue.substring(2, trimmedValue.length - 2).trim();
20245
- }
20246
- else if (trimmedValue.includes('{{')) {
20247
- // Inline template interpolation: "text {{var.prop}} more {{var2.field}}"
20248
- // The string contains embedded {{}} expressions mixed with literal text.
20249
- // Each expression is resolved individually and stringified back into the template.
20250
- return this.resolveInlineTemplateExpressions(trimmedValue, context, itemVariable);
20251
- }
20252
- // Check itemVariable reference (the custom loop variable name like "entityName" or "user")
20253
- // This handles both direct references and path-based property access
20254
- const ivToLower = itemVariable?.trim().toLowerCase();
20255
- const valueLower = value?.toLowerCase();
20256
- // CRITICAL: Check for exact match FIRST (handles scalar arrays and direct object references)
20257
- // Example: {{entityName}} where context.item = "Users" (scalar)
20258
- // Example: {{user}} where context.item = {name: "Alice", age: 30} (object)
20259
- if (valueLower === ivToLower) {
20260
- return context.item; // Return the current iteration item (scalar or object)
20261
- }
20262
- // Check for path notation (handles property access on object arrays)
20263
- // Example: {{entityName.property}} - won't work for scalars but handles objects
20264
- // Example: {{user.name}} where context.item = {name: "Alice"} → returns "Alice"
20265
- if (valueLower?.startsWith(`${ivToLower}.`)) {
20266
- const path = value.substring(ivToLower.length + 1);
20267
- return this.getValueFromPath(context.item, path);
20268
- }
20269
- // Check for direct context variable references (index, payload, data, etc.)
20270
- // These are the fixed context properties set up by the loop execution
20271
- for (const [varName, varValue] of Object.entries(context)) {
20272
- if (value === varName) {
20273
- return varValue;
20274
- }
20275
- if (value?.trim().toLowerCase().startsWith(`${varName}.`)) {
20276
- const path = value.substring(varName.length + 1);
20277
- return this.getValueFromPath(varValue, path);
20278
- }
20279
- }
20280
- // Static value - no variable reference found, return as literal string
20281
- return value;
19464
+ return this._stepDispatcher.ResolveValueFromContext(value, context, itemVariable, {
19465
+ resolveInline: (tpl, ctx, iv) => this.resolveInlineTemplateExpressions(tpl, ctx, iv),
19466
+ getPath: (obj, path) => this.getValueFromPath(obj, path),
19467
+ });
20282
19468
  }
20283
19469
  /**
20284
19470
  * Resolves multiple {{expression}} placeholders embedded within a literal string.
@@ -20295,16 +19481,7 @@ The context is now within limits. Please retry your request with the recovered c
20295
19481
  * // → "largest company in Tokyo Japan"
20296
19482
  */
20297
19483
  resolveInlineTemplateExpressions(template, context, itemVariable) {
20298
- const expressionPattern = /\{\{\s*([^}]+?)\s*\}\}/g;
20299
- return template.replace(expressionPattern, (_match, expr) => {
20300
- // Resolve each expression using the single-variable path (without {{ }} wrappers)
20301
- const resolved = this.resolveValueFromContext(expr.trim(), context, itemVariable);
20302
- // If the expression didn't resolve (returned unchanged), keep original {{ }} for transparency
20303
- if (resolved === expr.trim()) {
20304
- return _match;
20305
- }
20306
- return String(resolved ?? '');
20307
- });
19484
+ return this._stepDispatcher.ResolveInlineTemplateExpressions(template, context, itemVariable, (val, ctx, iv) => this.resolveValueFromContext(val, ctx, iv));
20308
19485
  }
20309
19486
  /**
20310
19487
  * Reads a value out of a nested object by dotted path, with `name[0]` array indexing.