@memberjunction/ai-agents 6.3.0-edge.0 → 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 (211) hide show
  1. package/README.md +8 -5
  2. package/dist/AgentDataPreloader.d.ts +9 -2
  3. package/dist/AgentDataPreloader.d.ts.map +1 -1
  4. package/dist/AgentDataPreloader.js +134 -15
  5. package/dist/AgentDataPreloader.js.map +1 -1
  6. package/dist/AgentDecisionService.d.ts +10 -1
  7. package/dist/AgentDecisionService.d.ts.map +1 -1
  8. package/dist/AgentDecisionService.js +28 -13
  9. package/dist/AgentDecisionService.js.map +1 -1
  10. package/dist/AgentRunner.d.ts +57 -15
  11. package/dist/AgentRunner.d.ts.map +1 -1
  12. package/dist/AgentRunner.js +692 -101
  13. package/dist/AgentRunner.js.map +1 -1
  14. package/dist/ArtifactToolManager.d.ts +134 -39
  15. package/dist/ArtifactToolManager.d.ts.map +1 -1
  16. package/dist/ArtifactToolManager.js +2761 -321
  17. package/dist/ArtifactToolManager.js.map +1 -1
  18. package/dist/GovernedArtifactService.d.ts +367 -0
  19. package/dist/GovernedArtifactService.d.ts.map +1 -0
  20. package/dist/GovernedArtifactService.js +2569 -0
  21. package/dist/GovernedArtifactService.js.map +1 -0
  22. package/dist/PayloadManager.d.ts +46 -0
  23. package/dist/PayloadManager.d.ts.map +1 -1
  24. package/dist/PayloadManager.js +284 -66
  25. package/dist/PayloadManager.js.map +1 -1
  26. package/dist/SkillMarkdownConverter.d.ts.map +1 -1
  27. package/dist/SkillMarkdownConverter.js +4 -2
  28. package/dist/SkillMarkdownConverter.js.map +1 -1
  29. package/dist/agent-context-injector.d.ts +2 -25
  30. package/dist/agent-context-injector.d.ts.map +1 -1
  31. package/dist/agent-context-injector.js +38 -153
  32. package/dist/agent-context-injector.js.map +1 -1
  33. package/dist/agent-instance.d.ts +28 -0
  34. package/dist/agent-instance.d.ts.map +1 -0
  35. package/dist/agent-instance.js +39 -0
  36. package/dist/agent-instance.js.map +1 -0
  37. package/dist/agent-memory-context-builder.d.ts.map +1 -1
  38. package/dist/agent-memory-context-builder.js +46 -42
  39. package/dist/agent-memory-context-builder.js.map +1 -1
  40. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  41. package/dist/agent-pre-execution-rag.js +5 -0
  42. package/dist/agent-pre-execution-rag.js.map +1 -1
  43. package/dist/agent-run-watchdog.d.ts +38 -6
  44. package/dist/agent-run-watchdog.d.ts.map +1 -1
  45. package/dist/agent-run-watchdog.js +75 -13
  46. package/dist/agent-run-watchdog.js.map +1 -1
  47. package/dist/agent-types/flow-agent-type.d.ts +6 -1
  48. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  49. package/dist/agent-types/flow-agent-type.js +30 -7
  50. package/dist/agent-types/flow-agent-type.js.map +1 -1
  51. package/dist/agent-types/loop-agent-type.d.ts +4 -0
  52. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  53. package/dist/agent-types/loop-agent-type.js +29 -0
  54. package/dist/agent-types/loop-agent-type.js.map +1 -1
  55. package/dist/artifact-presence-locator.d.ts +132 -0
  56. package/dist/artifact-presence-locator.d.ts.map +1 -0
  57. package/dist/artifact-presence-locator.js +472 -0
  58. package/dist/artifact-presence-locator.js.map +1 -0
  59. package/dist/artifact-tools/CSVToolLibrary.d.ts +2 -2
  60. package/dist/artifact-tools/CSVToolLibrary.d.ts.map +1 -1
  61. package/dist/artifact-tools/CSVToolLibrary.js +41 -14
  62. package/dist/artifact-tools/CSVToolLibrary.js.map +1 -1
  63. package/dist/artifact-tools/DataSnapshotToolLibrary.d.ts +2 -2
  64. package/dist/artifact-tools/DataSnapshotToolLibrary.d.ts.map +1 -1
  65. package/dist/artifact-tools/DataSnapshotToolLibrary.js +53 -21
  66. package/dist/artifact-tools/DataSnapshotToolLibrary.js.map +1 -1
  67. package/dist/artifact-tools/DocumentToolLibrary.d.ts +101 -0
  68. package/dist/artifact-tools/DocumentToolLibrary.d.ts.map +1 -0
  69. package/dist/artifact-tools/DocumentToolLibrary.js +1846 -0
  70. package/dist/artifact-tools/DocumentToolLibrary.js.map +1 -0
  71. package/dist/artifact-tools/DocxToolLibrary.d.ts +2 -4
  72. package/dist/artifact-tools/DocxToolLibrary.d.ts.map +1 -1
  73. package/dist/artifact-tools/DocxToolLibrary.js +42 -30
  74. package/dist/artifact-tools/DocxToolLibrary.js.map +1 -1
  75. package/dist/artifact-tools/ExcelToolLibrary.d.ts +2 -3
  76. package/dist/artifact-tools/ExcelToolLibrary.d.ts.map +1 -1
  77. package/dist/artifact-tools/ExcelToolLibrary.js +105 -49
  78. package/dist/artifact-tools/ExcelToolLibrary.js.map +1 -1
  79. package/dist/artifact-tools/GenericBinaryToolLibrary.d.ts +2 -2
  80. package/dist/artifact-tools/GenericBinaryToolLibrary.d.ts.map +1 -1
  81. package/dist/artifact-tools/GenericBinaryToolLibrary.js +3 -2
  82. package/dist/artifact-tools/GenericBinaryToolLibrary.js.map +1 -1
  83. package/dist/artifact-tools/JSONToolLibrary.d.ts +4 -4
  84. package/dist/artifact-tools/JSONToolLibrary.d.ts.map +1 -1
  85. package/dist/artifact-tools/JSONToolLibrary.js +32 -11
  86. package/dist/artifact-tools/JSONToolLibrary.js.map +1 -1
  87. package/dist/artifact-tools/PDFToolLibrary.d.ts +27 -3
  88. package/dist/artifact-tools/PDFToolLibrary.d.ts.map +1 -1
  89. package/dist/artifact-tools/PDFToolLibrary.js +36 -21
  90. package/dist/artifact-tools/PDFToolLibrary.js.map +1 -1
  91. package/dist/artifact-tools/SearchResultSetToolLibrary.d.ts +2 -2
  92. package/dist/artifact-tools/SearchResultSetToolLibrary.d.ts.map +1 -1
  93. package/dist/artifact-tools/SearchResultSetToolLibrary.js +83 -24
  94. package/dist/artifact-tools/SearchResultSetToolLibrary.js.map +1 -1
  95. package/dist/artifact-tools/SlideDeckToolLibrary.d.ts +50 -0
  96. package/dist/artifact-tools/SlideDeckToolLibrary.d.ts.map +1 -0
  97. package/dist/artifact-tools/SlideDeckToolLibrary.js +1617 -0
  98. package/dist/artifact-tools/SlideDeckToolLibrary.js.map +1 -0
  99. package/dist/artifact-tools/SpreadsheetToolLibrary.d.ts +87 -0
  100. package/dist/artifact-tools/SpreadsheetToolLibrary.d.ts.map +1 -0
  101. package/dist/artifact-tools/SpreadsheetToolLibrary.js +3351 -0
  102. package/dist/artifact-tools/SpreadsheetToolLibrary.js.map +1 -0
  103. package/dist/artifact-tools/TextToolLibrary.d.ts +3 -3
  104. package/dist/artifact-tools/TextToolLibrary.d.ts.map +1 -1
  105. package/dist/artifact-tools/TextToolLibrary.js +34 -24
  106. package/dist/artifact-tools/TextToolLibrary.js.map +1 -1
  107. package/dist/artifact-tools/WhiteboardToolLibrary.d.ts +69 -0
  108. package/dist/artifact-tools/WhiteboardToolLibrary.d.ts.map +1 -0
  109. package/dist/artifact-tools/WhiteboardToolLibrary.js +555 -0
  110. package/dist/artifact-tools/WhiteboardToolLibrary.js.map +1 -0
  111. package/dist/artifact-tools/artifact-comment-suggestion-helper.d.ts +98 -0
  112. package/dist/artifact-tools/artifact-comment-suggestion-helper.d.ts.map +1 -0
  113. package/dist/artifact-tools/artifact-comment-suggestion-helper.js +851 -0
  114. package/dist/artifact-tools/artifact-comment-suggestion-helper.js.map +1 -0
  115. package/dist/artifact-tools/artifact-tool-helpers.d.ts +21 -0
  116. package/dist/artifact-tools/artifact-tool-helpers.d.ts.map +1 -0
  117. package/dist/artifact-tools/artifact-tool-helpers.js +74 -0
  118. package/dist/artifact-tools/artifact-tool-helpers.js.map +1 -0
  119. package/dist/artifact-tools/grepHelper.d.ts +27 -0
  120. package/dist/artifact-tools/grepHelper.d.ts.map +1 -0
  121. package/dist/artifact-tools/grepHelper.js +229 -0
  122. package/dist/artifact-tools/grepHelper.js.map +1 -0
  123. package/dist/artifact-tools/node-vm-safe-regex.d.ts +10 -0
  124. package/dist/artifact-tools/node-vm-safe-regex.d.ts.map +1 -0
  125. package/dist/artifact-tools/node-vm-safe-regex.js +148 -0
  126. package/dist/artifact-tools/node-vm-safe-regex.js.map +1 -0
  127. package/dist/base-agent.d.ts +119 -14
  128. package/dist/base-agent.d.ts.map +1 -1
  129. package/dist/base-agent.js +529 -112
  130. package/dist/base-agent.js.map +1 -1
  131. package/dist/decision-discovery.d.ts +42 -15
  132. package/dist/decision-discovery.d.ts.map +1 -1
  133. package/dist/decision-discovery.js +90 -20
  134. package/dist/decision-discovery.js.map +1 -1
  135. package/dist/index.d.ts +12 -1
  136. package/dist/index.d.ts.map +1 -1
  137. package/dist/index.js +12 -2
  138. package/dist/index.js.map +1 -1
  139. package/dist/memory-decision-uses.d.ts +206 -0
  140. package/dist/memory-decision-uses.d.ts.map +1 -0
  141. package/dist/memory-decision-uses.js +259 -0
  142. package/dist/memory-decision-uses.js.map +1 -0
  143. package/dist/memory-manager-agent.d.ts +66 -6
  144. package/dist/memory-manager-agent.d.ts.map +1 -1
  145. package/dist/memory-manager-agent.js +184 -31
  146. package/dist/memory-manager-agent.js.map +1 -1
  147. package/dist/memory-note-gate.d.ts +12 -9
  148. package/dist/memory-note-gate.d.ts.map +1 -1
  149. package/dist/memory-note-gate.js +16 -11
  150. package/dist/memory-note-gate.js.map +1 -1
  151. package/dist/native-tools/agent-tool-circuit-breaker.d.ts +44 -0
  152. package/dist/native-tools/agent-tool-circuit-breaker.d.ts.map +1 -0
  153. package/dist/native-tools/agent-tool-circuit-breaker.js +71 -0
  154. package/dist/native-tools/agent-tool-circuit-breaker.js.map +1 -0
  155. package/dist/native-tools/agent-tools.d.ts +7 -0
  156. package/dist/native-tools/agent-tools.d.ts.map +1 -1
  157. package/dist/native-tools/agent-tools.js.map +1 -1
  158. package/dist/native-tools/control-tools.d.ts +8 -1
  159. package/dist/native-tools/control-tools.d.ts.map +1 -1
  160. package/dist/native-tools/control-tools.js +38 -5
  161. package/dist/native-tools/control-tools.js.map +1 -1
  162. package/dist/native-tools/framework-tools.d.ts +3 -3
  163. package/dist/native-tools/framework-tools.d.ts.map +1 -1
  164. package/dist/native-tools/framework-tools.js +20 -8
  165. package/dist/native-tools/framework-tools.js.map +1 -1
  166. package/dist/payload-path-keys.d.ts +54 -0
  167. package/dist/payload-path-keys.d.ts.map +1 -0
  168. package/dist/payload-path-keys.js +126 -0
  169. package/dist/payload-path-keys.js.map +1 -0
  170. package/dist/pipeline/template.d.ts +9 -4
  171. package/dist/pipeline/template.d.ts.map +1 -1
  172. package/dist/pipeline/template.js +29 -30
  173. package/dist/pipeline/template.js.map +1 -1
  174. package/dist/realtime/artifact-workspace-channel-server.d.ts +27 -0
  175. package/dist/realtime/artifact-workspace-channel-server.d.ts.map +1 -0
  176. package/dist/realtime/artifact-workspace-channel-server.js +43 -0
  177. package/dist/realtime/artifact-workspace-channel-server.js.map +1 -0
  178. package/dist/realtime/bridge-realtime-session-factory.d.ts +2 -2
  179. package/dist/realtime/bridge-realtime-session-factory.d.ts.map +1 -1
  180. package/dist/realtime/bridge-realtime-session-factory.js +7 -56
  181. package/dist/realtime/bridge-realtime-session-factory.js.map +1 -1
  182. package/dist/realtime/realtime-artifact-helpers.d.ts +37 -0
  183. package/dist/realtime/realtime-artifact-helpers.d.ts.map +1 -0
  184. package/dist/realtime/realtime-artifact-helpers.js +150 -0
  185. package/dist/realtime/realtime-artifact-helpers.js.map +1 -0
  186. package/dist/realtime/realtime-client-session-service.d.ts +87 -17
  187. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  188. package/dist/realtime/realtime-client-session-service.js +259 -39
  189. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  190. package/dist/realtime/realtime-coagent-config.d.ts +22 -7
  191. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  192. package/dist/realtime/realtime-coagent-config.js +20 -22
  193. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  194. package/dist/realtime/realtime-moderator-decision.d.ts +86 -0
  195. package/dist/realtime/realtime-moderator-decision.d.ts.map +1 -0
  196. package/dist/realtime/realtime-moderator-decision.js +131 -0
  197. package/dist/realtime/realtime-moderator-decision.js.map +1 -0
  198. package/dist/realtime/realtime-tool-broker.d.ts +6 -0
  199. package/dist/realtime/realtime-tool-broker.d.ts.map +1 -1
  200. package/dist/realtime/realtime-tool-broker.js +4 -2
  201. package/dist/realtime/realtime-tool-broker.js.map +1 -1
  202. package/dist/realtime/realtime-turn-moderator.d.ts +20 -0
  203. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  204. package/dist/realtime/realtime-turn-moderator.js +63 -8
  205. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  206. package/dist/repeated-failing-step.d.ts +50 -0
  207. package/dist/repeated-failing-step.d.ts.map +1 -0
  208. package/dist/repeated-failing-step.js +130 -0
  209. package/dist/repeated-failing-step.js.map +1 -0
  210. package/dist/tsconfig.tsbuildinfo +1 -0
  211. package/package.json +20 -20
@@ -16,16 +16,21 @@ import { ApplyBoundActionParams, BindingsForAction, IsBoundParamName, UnboundPar
16
16
  import { BuildNativeToolSet, COMPLETE_TASK_TOOL, SUB_AGENT_TOOL_PREFIX } from './native-tools/control-tools.js';
17
17
  import { TurnToolCallingMode } from './native-tools/turn-mode.js';
18
18
  import { NATIVE_CONTROL_TEMPLATE_DATA, NATIVE_ONLY_TEMPLATE_FLAG, ResolveNativeControlConfig } from './native-tools/native-control-config.js';
19
+ import { AgentToolCircuitBreaker } from './native-tools/agent-tool-circuit-breaker.js';
19
20
  import { BuildFrameworkTools } from './native-tools/framework-tools.js';
20
21
  import { BuildAssistantToolCallTurn, BuildToolResultTurn, CompactAnsweredToolCallArguments, CompactToolResultContent, CompactToolResultContentAsync } from './native-tools/tool-result-turns.js';
21
22
  import { LooksLikeLoopEnvelope } from './native-tools/dual-channel.js';
22
23
  import { MJAIAgentRunEntityExtended, ResolvePromptRunUserID, ResolvePayloadAtEnd } from "@memberjunction/ai-core-plus";
24
+ import { GovernedArtifactService, MergeTouchedArtifactSummary } from './GovernedArtifactService.js';
25
+ import { CollectDelegatedRunArtifactsSafely, ExtractDirectActionArtifacts } from './realtime/realtime-artifact-helpers.js';
23
26
  import { Metadata, RunView, LogStatus, LogStatusEx, LogError, LogErrorEx, IsVerboseLoggingEnabled, DatabaseProviderBase, ServerOperationScopeManager } from '@memberjunction/core';
24
27
  import { AgentRunWatchdog } from './agent-run-watchdog.js';
25
28
  import { AIPromptRunner, GetToolCallingDecision, GetSentPrefixFingerprint } from '@memberjunction/ai-prompts';
26
29
  import { BaseRealtimeModel, GetAIAPIKey, CredentialScopeAllows, MakeAIAPIKeyResolver } from '@memberjunction/ai';
27
30
  import { BaseAgentType } from './agent-types/base-agent-type.js';
28
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';
29
34
  import { ProviderRubricEngine } from '@memberjunction/rubrics';
30
35
  import { ExecuteSelfCheck, PickSelfCheckLink } from './self-check.js';
31
36
  import { CopyScalarsAndArrays, GroupByUUID, IndexByUUID, JSONValidator, MJGlobal, NormalizeUUID, SafeExpressionEvaluator, UUIDsEqual, UUIDSet, EscapeSQLString, IsPlainObject, CleanAndParseJSON, IsValidUUID } from '@memberjunction/global';
@@ -53,7 +58,7 @@ import { FormatToolResultSection, FormatToolErrorSection, RenderToolResultData,
53
58
  import { PriorTurnToolResultCache } from './prior-turn-tool-result-cache.js';
54
59
  import { PromptComponentResolver, InjectScopedPromptParts } from './prompt-component-resolver.js';
55
60
  import { ScopedPromptConfigResolver, ApplyScopedPromptConfig } from './scoped-prompt-config-resolver.js';
56
- 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, } 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';
57
62
  import { ActionEngineBase, ActionResult, RunActionParams, AUDIENCE_UNSUPPORTED_RESULT_CODE, ActionRunScopeIsBounded } from '@memberjunction/actions-base';
58
63
  import { UserCache } from '@memberjunction/generic-database-provider';
59
64
  import { AgentAudienceAddsReader, AgentAudienceProblem, AgentAudienceReaderIDs, MatchAudienceUsers } from './agent-audience.js';
@@ -70,10 +75,11 @@ import { PayloadFeedbackManager } from './PayloadFeedbackManager.js';
70
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';
71
76
  import { FinishIfModeWarnings } from './finish-if-mode-warnings.js';
72
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';
73
- 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';
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';
74
79
  import { ResolveHandoffTarget } from './handoff-target.js';
75
80
  import { BuildFinishIfQuestions, CapFinishIfState, FINISH_IF_STATE_EXCERPT, FormatActionForFinishIf, FormatSubAgentForFinishIf, JudgeFinishIf } from './finish-if-state.js';
76
81
  import { PipelineExecutor, PipelineToolRegistry, ActionInvocable, ArtifactToolInvocable, BuildPipelineToolDocs, formatFinalOutput, summarizePipelineStages, } from './pipeline/index.js';
82
+ import { BuildTaskGraphStartDebug } from '@memberjunction/ai-core-plus';
77
83
  // The ONE payload-mapping dialect. Loop agents and the task-graph dispatcher read the same authored
78
84
  // mapping strings, so these must be the same functions rather than two copies that agree today.
79
85
  import { GetValueFromPath } from '@memberjunction/ai-core-plus';
@@ -206,6 +212,13 @@ export class BaseAgent {
206
212
  * @private
207
213
  */
208
214
  this._activeProvider = Metadata.Provider; // global-provider-ok: default until Execute() captures per-request provider
215
+ /**
216
+ * Payload changes sent with completions that were refused, in order. They are held, not
217
+ * committed: the next prompt sees the payload with them applied, and the next completion is
218
+ * built on top of them, so a model only has to send its corrections. They are committed with
219
+ * the next accepted completion, and dropped if the run ends without one.
220
+ */
221
+ this._heldCompletionChanges = [];
209
222
  /**
210
223
  * Index in conversationMessages where this agent run began, used to accurately restore
211
224
  * turn 1's trailing state message in append-only mode without corrupting prior chat turns.
@@ -245,6 +258,12 @@ export class BaseAgent {
245
258
  * @private
246
259
  */
247
260
  this._actionFailureHistory = new Map();
261
+ /**
262
+ * The same identical-arguments and attempt-budget rules for agent-local tools
263
+ * ({@link GetAgentTools}), which run outside the action dispatch path.
264
+ * @private
265
+ */
266
+ this._agentToolBreaker = new AgentToolCircuitBreaker(IDENTICAL_FAILURE_THRESHOLD, ACTION_FAILURE_BUDGET);
248
267
  /**
249
268
  * This is state information that is specific to the agent type. BaseAgent doesn't know what
250
269
  * this contains or care, it is just responsible for keeping this, giving the Agent Type the
@@ -875,6 +894,7 @@ export class BaseAgent {
875
894
  this._audienceLockedActions.clear();
876
895
  this._taintLockedActions.clear();
877
896
  this._actionFailureHistory.clear();
897
+ this._agentToolBreaker.Reset();
878
898
  }
879
899
  /**
880
900
  * The blocked result for an action locked out for the run — refused for the audience (`'audience'`), refused
@@ -1664,6 +1684,15 @@ export class BaseAgent {
1664
1684
  get scratchpadManager() {
1665
1685
  return this._scratchpadManager;
1666
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
+ }
1667
1696
  /** The longest the catalog narrowing decision may take before the run shows the full catalog. */
1668
1697
  static { this.CATALOG_NARROWING_TIMEOUT_MS = 30000; }
1669
1698
  /** The skills activated so far in this run (requested or self-activated), in activation order. */
@@ -1824,7 +1853,7 @@ export class BaseAgent {
1824
1853
  }
1825
1854
  try {
1826
1855
  // Load preloaded data using the singleton service
1827
- 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);
1828
1857
  const totalSources = Object.keys(preloadedResult.data).length +
1829
1858
  Object.keys(preloadedResult.context).length +
1830
1859
  Object.keys(preloadedResult.payload).length;
@@ -1873,37 +1902,34 @@ export class BaseAgent {
1873
1902
  this.logStatus(`📭 No data sources configured for agent '${params.agent.Name}'`, true, params);
1874
1903
  return; // No step needed when there are no data sources at all
1875
1904
  }
1876
- // Create a step entity to track data preloading in the agent run
1877
- const stepEntity = await this.createStepEntity({
1878
- stepType: 'Validation',
1879
- stepName: 'Data Source Preloading',
1880
- contextUser: params.contextUser
1881
- });
1882
- // Surface any data source failures in the agent run step and agent run record
1883
- if (preloadedResult.failedSources.length > 0) {
1905
+ const hasFailures = preloadedResult.failedSources.length > 0;
1906
+ let warningMessage;
1907
+ if (hasFailures) {
1884
1908
  const failureDetails = preloadedResult.failedSources
1885
1909
  .map(f => `${f.name}${f.entityName ? ` (Entity: ${f.entityName})` : ''}: ${f.errorMessage}`)
1886
1910
  .join('; ');
1887
- const warningMessage = `${preloadedResult.failedSources.length} data source(s) failed to load: ${failureDetails}`;
1888
- // Finalize step as completed but with error details captured
1889
- await this.finalizeStepEntity(stepEntity, true, warningMessage, {
1890
- loadedSources: preloadedResult.loadedSources,
1891
- failedSources: preloadedResult.failedSources
1892
- });
1893
- // Append warning to the agent run's ErrorMessage for top-level visibility
1894
- if (this._agentRun) {
1895
- const existing = this._agentRun.ErrorMessage || '';
1896
- this._agentRun.ErrorMessage = existing
1897
- ? `${existing}\n\n[Data Preloading Warning] ${warningMessage}`
1898
- : `[Data Preloading Warning] ${warningMessage}`;
1899
- await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
1900
- }
1911
+ warningMessage = `${preloadedResult.failedSources.length} data source(s) failed to load: ${failureDetails}`;
1901
1912
  }
1902
- else {
1903
- // All sources loaded successfully
1904
- await this.finalizeStepEntity(stepEntity, true, undefined, {
1905
- loadedSources: preloadedResult.loadedSources
1906
- });
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' });
1907
1933
  }
1908
1934
  }
1909
1935
  catch (error) {
@@ -2003,7 +2029,10 @@ export class BaseAgent {
2003
2029
  // `RunActionParams.AbortSignal` (see ActionEngine.RunAction) and are
2004
2030
  // unaffected by this wrapper — their timeout budget is independent.
2005
2031
  // =====================================================================================
2006
- 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;
2007
2036
  const upstreamToken = params.cancellationToken;
2008
2037
  const timeoutController = new AbortController();
2009
2038
  const relayUpstreamAbort = () => {
@@ -2078,6 +2107,7 @@ export class BaseAgent {
2078
2107
  this._agentConfig = undefined;
2079
2108
  this._lastModelSelectionInfo = undefined;
2080
2109
  this._lastVolatileStateMessage = undefined;
2110
+ this._heldCompletionChanges = [];
2081
2111
  this._resolvedTrailingStateMode = undefined;
2082
2112
  this._lastSentFingerprints = undefined;
2083
2113
  this._lastSentPrefix = undefined;
@@ -2107,12 +2137,18 @@ export class BaseAgent {
2107
2137
  // would otherwise serialize artifact bodies into the LLM payload. Only
2108
2138
  // the manifest (injected via _ARTIFACT_MANIFEST below) reaches the LLM.
2109
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
+ });
2110
2147
  if (inputArtifacts?.length) {
2111
- this._artifactToolManager.Initialize(inputArtifacts);
2112
2148
  this.logStatus(`[ArtifactTools] Initialized with ${inputArtifacts.length} artifact(s): ${inputArtifacts.map(a => `${a.typeName}:"${a.name}"`).join(', ')}`, true, params);
2113
2149
  }
2114
2150
  else {
2115
- 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);
2116
2152
  }
2117
2153
  // Initialize starting payload — must complete before AgentRun creation since the
2118
2154
  // run record stores the starting payload snapshot.
@@ -2165,7 +2201,7 @@ export class BaseAgent {
2165
2201
  if (this._agentRun) {
2166
2202
  this._agentRun.Status = 'Failed';
2167
2203
  this._agentRun.ErrorMessage = bindingError;
2168
- await this._agentRun.Save();
2204
+ this.releaseFinishedRun(await this._agentRun.Save());
2169
2205
  }
2170
2206
  throw new Error(bindingError);
2171
2207
  }
@@ -2392,6 +2428,12 @@ export class BaseAgent {
2392
2428
  // requests unasked. The terminate path has already logged and cleared its own.
2393
2429
  this.skipHeldDecisions(params, this.runEndForHeldDecisions());
2394
2430
  this.releasePerRunDataCache();
2431
+ try {
2432
+ await this._artifactToolManager.NotifyRunCompleted();
2433
+ }
2434
+ catch (presenceErr) {
2435
+ this.logError(presenceErr, { category: 'ArtifactPresenceExit' });
2436
+ }
2395
2437
  await this.finalizeRun(this.deriveRunOutcome());
2396
2438
  // The run is over: a later direct ExecuteSingleAction resolves the scope and the audience from its own params.
2397
2439
  this.clearRunBoundState();
@@ -2846,6 +2888,10 @@ export class BaseAgent {
2846
2888
  // CreateBridgeRealtimeSession (the LiveKit / telephony factory) passes no apiKeys today.
2847
2889
  APIKeys: params.apiKeys,
2848
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),
2849
2895
  AgentSessionID: params.data?.agentSessionId ?? '',
2850
2896
  PreferredModelID: modelID,
2851
2897
  ConfigOverridesJson: BuildRealtimeOverridesJson(modelID, voice) ?? undefined,
@@ -3223,7 +3269,8 @@ export class BaseAgent {
3223
3269
  }
3224
3270
  try {
3225
3271
  const requestText = this.parseDelegateRequestText(request.Arguments);
3226
- const runner = new AgentRunner(params.provider || this._activeProvider);
3272
+ const effectiveProvider = params.provider || this._activeProvider;
3273
+ const runner = new AgentRunner(effectiveProvider);
3227
3274
  const result = await runner.RunAgent({
3228
3275
  agent: targetAgent,
3229
3276
  conversationMessages: [{ role: 'user', content: requestText }],
@@ -3248,12 +3295,21 @@ export class BaseAgent {
3248
3295
  // host-level onProgress the parent execution carries.
3249
3296
  onProgress: this.combineProgressCallbacks(request.OnProgress, params.onProgress)
3250
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
+ });
3251
3305
  return {
3252
3306
  CallID: request.CallID,
3253
3307
  Success: result.success,
3254
3308
  Output: result.success
3255
3309
  ? (result.agentRun?.Message || 'The target agent completed the request.')
3256
- : (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 } : {}),
3257
3313
  };
3258
3314
  }
3259
3315
  catch (error) {
@@ -3310,7 +3366,7 @@ export class BaseAgent {
3310
3366
  parseDelegateRequestText(argumentsJson) {
3311
3367
  try {
3312
3368
  const parsed = JSON.parse(argumentsJson);
3313
- if (typeof parsed.request === 'string') {
3369
+ if (parsed && typeof parsed === 'object' && typeof parsed.request === 'string') {
3314
3370
  return parsed.request;
3315
3371
  }
3316
3372
  }
@@ -3343,10 +3399,12 @@ export class BaseAgent {
3343
3399
  try {
3344
3400
  const agentAction = { name: action.Name, params: this.parseRealtimeToolParams(call.Arguments) };
3345
3401
  const result = await this.ExecuteSingleAction(params, agentAction, action, params.contextUser);
3402
+ const actionArtifacts = ExtractDirectActionArtifacts(action.Name, result.Success, result.Params);
3346
3403
  return {
3347
3404
  CallID: call.CallID,
3348
3405
  Success: result.Success,
3349
- Output: result.Message || (result.Success ? 'Tool completed.' : 'Tool failed.')
3406
+ Output: result.Message || (result.Success ? 'Tool completed.' : 'Tool failed.'),
3407
+ ...(actionArtifacts ? { Artifacts: actionArtifacts } : {}),
3350
3408
  };
3351
3409
  }
3352
3410
  catch (error) {
@@ -3363,7 +3421,7 @@ export class BaseAgent {
3363
3421
  parseRealtimeToolParams(argumentsJson) {
3364
3422
  try {
3365
3423
  const parsed = JSON.parse(argumentsJson);
3366
- if (parsed && typeof parsed === 'object') {
3424
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
3367
3425
  return parsed;
3368
3426
  }
3369
3427
  }
@@ -3730,6 +3788,29 @@ export class BaseAgent {
3730
3788
  // the base class doesn't do anything here, this allows sub-classes
3731
3789
  // to do specialized initialization of the starting payload
3732
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
+ }
3733
3814
  /**
3734
3815
  * Executes the agent's internal logic.
3735
3816
  *
@@ -3754,6 +3835,9 @@ export class BaseAgent {
3754
3835
  let stepCount = 0;
3755
3836
  let consecutiveFailedSteps = 0;
3756
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();
3757
3841
  while (continueExecution) {
3758
3842
  // Check for cancellation before each step
3759
3843
  if (params.cancellationToken?.aborted) {
@@ -3769,6 +3853,7 @@ export class BaseAgent {
3769
3853
  }
3770
3854
  // Execute the current step based on previous decision or initial prompt
3771
3855
  this.logStatus(`🔄 Executing step ${stepCount + 1} for agent '${params.agent.Name}'`, true, params);
3856
+ const executedDecision = currentNextStep;
3772
3857
  const nextStep = await this.executeNextStep(params, config, currentNextStep, stepCount);
3773
3858
  stepCount++;
3774
3859
  // A failed step cut short by a cancellation is not a failure: end the run as cancelled
@@ -3804,6 +3889,9 @@ export class BaseAgent {
3804
3889
  else if (nextStep.step !== 'Failed') {
3805
3890
  consecutiveFailedSteps = 0;
3806
3891
  }
3892
+ if (repeatedFailures && executedDecision && !IsPromptTurnStep(executedDecision) && !nextStep.terminate) {
3893
+ this.checkRepeatedFailingStep(params, repeatedFailures, executedDecision, nextStep);
3894
+ }
3807
3895
  // Track consecutive *unproductive* retries to prevent infinite loops that the
3808
3896
  // consecutive-failed-steps net above cannot catch. A model that repeatedly returns
3809
3897
  // output we can't parse/validate (e.g. conversational prose instead of the required
@@ -4094,7 +4182,7 @@ export class BaseAgent {
4094
4182
  return;
4095
4183
  }
4096
4184
  const promptParams = this.decisionDiscoveryPromptParams(agent, overrides);
4097
- const outcome = await this.runDecisionDiscovery(agent, contextUser, promptParams, HostAllowedAgentIDs(data));
4185
+ const outcome = await this.runDecisionDiscovery(agent, contextUser, promptParams, HostAllowedAgentIDs(data), ReadEdgePreDiscoveryHint(data));
4098
4186
  if (outcome.Injected && outcome.Message) {
4099
4187
  conversationMessages.unshift({ role: 'system', content: outcome.Message });
4100
4188
  this.logStatus(`Decision discovery suggested '${outcome.Answer?.Agent.Name}' to '${agent.Name}'`, true);
@@ -4145,12 +4233,12 @@ export class BaseAgent {
4145
4233
  * answer from a model with no discovery calibration is warned about once per model, because
4146
4234
  * then discovery can never suggest anything.
4147
4235
  */
4148
- async runDecisionDiscovery(agent, contextUser, promptParams, hostAllowedIDs) {
4236
+ async runDecisionDiscovery(agent, contextUser, promptParams, hostAllowedIDs, rawEdgeHint) {
4149
4237
  const promptName = typeof promptParams.decisionPromptName === 'string'
4150
4238
  ? promptParams.decisionPromptName
4151
4239
  : AgentDecisionService.DEFAULT_PROMPT_NAME;
4152
4240
  const step = await this.startDecisionDiscoveryStep(contextUser, promptName);
4153
- 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);
4154
4242
  await this.finishDecisionDiscoveryStep(step, outcome);
4155
4243
  if (!outcome.Succeeded) {
4156
4244
  this.warnDecisionDiscovery(agent, outcome.Reason ?? 'unknown error');
@@ -4179,8 +4267,8 @@ export class BaseAgent {
4179
4267
  BaseAgent._uncalibratedDiscoveryModelsWarned.add(model);
4180
4268
  LogErrorEx({
4181
4269
  message: `Decision discovery answered by ${model} suggests nothing: the model has no discovery calibration `
4182
- + '(DECISION_DISCOVERY_CALIBRATION), so its answers are treated as unsure. Fit one with the agent-discovery '
4183
- + '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.',
4184
4272
  severity: 'warning',
4185
4273
  category: 'DecisionDiscovery',
4186
4274
  });
@@ -4229,10 +4317,47 @@ export class BaseAgent {
4229
4317
  * The discovery itself: the options, rebuilt from the permitted catalog, then one decision about
4230
4318
  * the opening request, and what its answer means. Never throws.
4231
4319
  */
4232
- async discoverAgent(agent, contextUser, promptName, hostAllowedIDs, signal) {
4320
+ async discoverAgent(agent, contextUser, promptName, hostAllowedIDs, rawEdgeHint, signal) {
4233
4321
  try {
4234
- const { Options: options, Error: optionsError, ...rest } = await this.decisionDiscoveryOptionSet(agent, contextUser, promptName, hostAllowedIDs);
4235
- 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
+ };
4236
4361
  if (optionsError) {
4237
4362
  return { ...FailedDecisionDiscovery(optionsError), ...sizes };
4238
4363
  }
@@ -4251,7 +4376,7 @@ export class BaseAgent {
4251
4376
  CancellationToken: signal,
4252
4377
  ExecutionScope: this._runExecutionScope,
4253
4378
  });
4254
- return { ...DecisionDiscoveryFromResult(result, options, DECISION_DISCOVERY_MIN_CONFIDENCE), ...sizes };
4379
+ return { ...DecisionDiscoveryFromResult(result, options, DECISION_DISCOVERY_MIN_CONFIDENCE), Source: 'decision-model', ...sizes };
4255
4380
  }
4256
4381
  catch (error) {
4257
4382
  return FailedDecisionDiscovery(error instanceof Error ? error.message : String(error));
@@ -4260,15 +4385,16 @@ export class BaseAgent {
4260
4385
  /**
4261
4386
  * The Choice's options, rebuilt on every call and never cached ({@link BuildDecisionDiscoveryOptionSet}):
4262
4387
  * from AIEngine's current catalog, the agents the user may run, the decision prompt's option cap,
4263
- * 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.
4264
4389
  */
4265
- async decisionDiscoveryOptionSet(agent, contextUser, promptName, hostAllowedIDs) {
4390
+ async decisionDiscoveryOptionSet(agent, contextUser, promptName, hostAllowedIDs, runnableAgents, declaredCap, preferredCandidateIDs) {
4266
4391
  const provider = this.ProviderToUse;
4267
4392
  return BuildDecisionDiscoveryOptionSet({
4268
- Agents: await DecisionDiscoveryRunnableAgents(AIEngine.Instance.Agents, contextUser),
4393
+ Agents: runnableAgents ?? await DecisionDiscoveryRunnableAgents(AIEngine.Instance.Agents, contextUser),
4269
4394
  RunningAgentID: agent.ID,
4270
4395
  HostAllowedIDs: hostAllowedIDs,
4271
- DeclaredCap: DecisionPromptOptionCap(AIEngine.Instance, promptName),
4396
+ DeclaredCap: declaredCap ?? DecisionPromptOptionCap(AIEngine.Instance, promptName),
4397
+ PreferredCandidateIDs: preferredCandidateIDs,
4272
4398
  Search: CanSearchEntities(provider) ? DecisionDiscoveryAgentSearch(provider, this._openingRequest, contextUser) : undefined,
4273
4399
  });
4274
4400
  }
@@ -4332,6 +4458,15 @@ export class BaseAgent {
4332
4458
  tokensUsed: result?.tokensUsed,
4333
4459
  model: result?.DecisionResult?.ResolvedModel ?? result?.modelInfo?.modelName,
4334
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
+ : {}),
4335
4470
  });
4336
4471
  }
4337
4472
  /** Logs that decision discovery failed, so nothing was suggested. */
@@ -4656,7 +4791,7 @@ export class BaseAgent {
4656
4791
  }
4657
4792
  // Counted only on the native path: null means "envelope", which is different from a
4658
4793
  // native turn where the model chose not to call anything (0).
4659
- if (mode === 'Native' || mode === 'NativeFallback' || mode === 'NativeImplicit') {
4794
+ if (mode === 'Native' || mode === 'NativeFallback' || mode === 'NativeImplicit' || mode === 'NativeRecovered') {
4660
4795
  const message = promptResult?.chatResult?.data?.choices?.[0]?.message;
4661
4796
  const callCount = message?.toolCalls?.length ?? 0;
4662
4797
  stepEntity.NativeToolCallCount = callCount;
@@ -4913,6 +5048,8 @@ export class BaseAgent {
4913
5048
  consultEnabled: this.isSubAgentConsultEnabledForSubAgent(params.agent, sa),
4914
5049
  ...(presetNames.length > 0 ? { presetNames } : {})
4915
5050
  };
5051
+ }, {
5052
+ IncludeArtifactDirective: control.NativeOnly && this.isArtifactSupportEnabled(params.agent)
4916
5053
  });
4917
5054
  if (control.NativeOnly && promptParams.data) {
4918
5055
  // The template renders the tools-only prompt when this is set AND the runner resolves implicit control flow.
@@ -4959,7 +5096,7 @@ export class BaseAgent {
4959
5096
  // Each gate matches the one that renders the tool's docs, so a tool is never taught but undeclared.
4960
5097
  Scratchpad: p?.includeScratchpadDocs !== false,
4961
5098
  MemoryWrites: p?.includeMemoryWritesDocs !== false && this.memoryWriteSkip(params) === null,
4962
- ArtifactTools: p?.includeArtifactToolsDocs !== false && this._artifactToolManager.HasArtifacts(),
5099
+ ArtifactTools: p?.includeArtifactToolsDocs !== false && this._artifactToolManager.IsWorkspaceEnabled(),
4963
5100
  ConversationTools: p?.includeConversationToolsDocs !== false && this._conversationToolManager.IsAvailable,
4964
5101
  Decisions: this.DecisionsEnabled(p) && p?.includeDecisionsDocs !== false
4965
5102
  };
@@ -5051,19 +5188,23 @@ export class BaseAgent {
5051
5188
  });
5052
5189
  // Whatever fails below, the step is finalized and the call answered — never left Running.
5053
5190
  let outcome = { payload, content: '', isError: true };
5191
+ const breakerKey = this.agentToolBreakerKey(call);
5054
5192
  try {
5055
- const ran = await this.runAgentTool(call, payload, params);
5056
- // payload_change_request keeps its single-call behaviour: the allowed parts apply.
5057
- const partial = this._nativeToolBindings?.get(call.toolName)?.kind === 'payloadChange';
5058
- const applied = !ran.IsError && ran.PayloadChange
5059
- ? this.applyAgentToolPayloadChange(payload, ran.PayloadChange, params, partial)
5060
- : { payload, error: undefined };
5061
- outcome = { payload: applied.payload, content: applied.error ?? ran.Content, isError: ran.IsError || applied.error !== undefined };
5193
+ const refusal = breakerKey === null ? null : this._agentToolBreaker.Check(call.toolName, breakerKey);
5194
+ if (refusal) {
5195
+ this.logStatus(` ⚡ Circuit breaker: agent tool '${call.toolName}' not run (0ms)`, false, params);
5196
+ outcome = { payload, content: refusal, isError: true };
5197
+ }
5198
+ else {
5199
+ outcome = await this.runAndApplyAgentTool(call, payload, params);
5200
+ this.recordAgentToolOutcome(call.toolName, breakerKey, outcome.isError);
5201
+ }
5062
5202
  }
5063
5203
  catch (error) {
5064
5204
  const message = error instanceof Error ? error.message : String(error);
5065
5205
  LogError(`Agent '${params.agent?.Name}': applying agent tool '${call.toolName}' failed: ${message}`);
5066
5206
  outcome = { payload, content: `The tool's change could not be applied: ${message}. Nothing was changed.`, isError: true };
5207
+ this.recordAgentToolOutcome(call.toolName, breakerKey, true);
5067
5208
  }
5068
5209
  finally {
5069
5210
  step.PayloadAtEnd = this.serializePayloadAtEnd(outcome.payload);
@@ -5071,6 +5212,44 @@ export class BaseAgent {
5071
5212
  }
5072
5213
  return { payload: outcome.payload, result: { toolCallId: call.toolCallId, toolName: call.toolName, content: outcome.content, isError: outcome.isError } };
5073
5214
  }
5215
+ /** Runs one call and applies its payload change; a refused change makes the call an error. */
5216
+ async runAndApplyAgentTool(call, payload, params) {
5217
+ const ran = await this.runAgentTool(call, payload, params);
5218
+ // payload_change_request keeps its single-call behaviour: the allowed parts apply.
5219
+ const partial = this._nativeToolBindings?.get(call.toolName)?.kind === 'payloadChange';
5220
+ const applied = !ran.IsError && ran.PayloadChange
5221
+ ? this.applyAgentToolPayloadChange(payload, ran.PayloadChange, params, partial)
5222
+ : { payload, error: undefined };
5223
+ return { payload: applied.payload, content: applied.error ?? ran.Content, isError: ran.IsError || applied.error !== undefined };
5224
+ }
5225
+ /**
5226
+ * The identity of a call's arguments for the agent-tool circuit breaker, or null when the call is
5227
+ * not tracked: it is not an agent tool (`payload_change_request`, an unknown name), the agent type
5228
+ * opted out of the breaker (`UsesActionCircuitBreaker === false`), or the tool did
5229
+ * (`UsesCircuitBreaker === false`). Arguments are normalized like an action's.
5230
+ */
5231
+ agentToolBreakerKey(call) {
5232
+ const binding = this._nativeToolBindings?.get(call.toolName);
5233
+ if (binding?.kind !== 'agentTool' || binding.definition.UsesCircuitBreaker === false) {
5234
+ return null;
5235
+ }
5236
+ if (this.AgentTypeInstance?.UsesActionCircuitBreaker === false) {
5237
+ return null;
5238
+ }
5239
+ return this.normalizeActionParams(call.arguments);
5240
+ }
5241
+ /** Updates the agent-tool circuit breaker after a call that ran (nothing for an untracked call). */
5242
+ recordAgentToolOutcome(toolName, breakerKey, isError) {
5243
+ if (breakerKey === null) {
5244
+ return;
5245
+ }
5246
+ if (isError) {
5247
+ this._agentToolBreaker.RecordFailure(toolName, breakerKey);
5248
+ }
5249
+ else {
5250
+ this._agentToolBreaker.RecordSuccess(toolName);
5251
+ }
5252
+ }
5074
5253
  /** Calls the tool's handler; an undeclared tool or a thrown error becomes an error result. */
5075
5254
  async runAgentTool(call, payload, params) {
5076
5255
  const binding = this._nativeToolBindings?.get(call.toolName);
@@ -5324,7 +5503,7 @@ export class BaseAgent {
5324
5503
  // via pruneAndCompactExpiredMessages — same lifecycle as action results.
5325
5504
  const artifactToolsEnabled = agentTypePromptParams?.includeArtifactToolsDocs !== false;
5326
5505
  promptParams.data['_ARTIFACTS_ENABLED'] = this.isArtifactSupportEnabled(params.agent);
5327
- if (artifactToolsEnabled && this._artifactToolManager.HasArtifacts()) {
5506
+ if (artifactToolsEnabled && this._artifactToolManager.IsWorkspaceEnabled()) {
5328
5507
  promptParams.data['_ARTIFACT_MANIFEST'] = this._artifactToolManager.ToManifestString();
5329
5508
  if (this.GetNativeControlConfig(params).NativeOnly) {
5330
5509
  // The native-only prompt (picked at render time) names the artifact_tool tool instead of artifactToolCalls.
@@ -5332,7 +5511,7 @@ export class BaseAgent {
5332
5511
  }
5333
5512
  promptParams.data['_ARTIFACT_TOOLS'] = this._artifactToolManager.GetToolDocumentation();
5334
5513
  promptParams.data['_ARTIFACT_TOOL_SUMMARY'] = this._artifactToolManager.GetSummary();
5335
- 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);
5336
5515
  }
5337
5516
  else if (this._artifactToolManager.HasArtifacts()) {
5338
5517
  this.logStatus(`[ArtifactTools] Artifacts present but tools disabled by agent config (includeArtifactToolsDocs=false)`, true, params);
@@ -5451,26 +5630,78 @@ export class BaseAgent {
5451
5630
  new ScopedPromptConfigResolver();
5452
5631
  ApplyScopedPromptConfig(configResolver, scopedConfigPromptId, this.scopedPromptConfigScope(params), promptParams);
5453
5632
  }
5633
+ return promptParams;
5634
+ }
5635
+ /**
5636
+ * Completes the prompt params once {@link preparePromptParams} — including any subclass override —
5637
+ * has returned: builds the trailing runtime-state message and checks the outgoing history for replayed
5638
+ * reasoning that no longer matches.
5639
+ *
5640
+ * This runs after the hook, not inside it, because building the trailing message can render the child
5641
+ * prompt (a relocated specialization) and caches that render for the prompt runner. Rendered inside the
5642
+ * hook, it would miss the template data a subclass adds after calling `super.preparePromptParams()`, and
5643
+ * the prompt would be sent without it. The history comes from `promptParams.conversationMessages`, so a
5644
+ * subclass's own changes to the outgoing messages are kept and the trailing message stays last.
5645
+ */
5646
+ async finalizePromptParams(promptParams, config, payload, params) {
5454
5647
  // Prompt-cache layout. The per-iteration state (and, when the child prompt is volatile, the
5455
5648
  // specialization) never lives in the system prompt; it rides as the FINAL message of THIS request.
5456
5649
  // In append-only mode (OpenAI prompt caching), prior runtime-state fragments are retained in history
5457
5650
  // so each turn extends the exact byte prefix of the previous request, maintaining ~93% cache hits.
5458
5651
  // In replace-in-place mode (Gemini/Cerebras), only the latest fragment is attached, keeping history lean.
5459
- const volatileStateMessage = await this.buildVolatileStateMessage(params, promptParams, payload, childPrompt, agentType, systemPrompt);
5652
+ const volatileStateMessage = await this.buildVolatileStateMessage(params, promptParams, payload, config.childPrompt, config.agentType, config.systemPrompt);
5460
5653
  if (volatileStateMessage) {
5461
5654
  const isAppendOnly = this.shouldUseAppendOnlyTrailingState(promptParams);
5462
5655
  this.restoreTurn1VolatileStateIfNeeded(params, isAppendOnly);
5463
- promptParams.conversationMessages = this.assembleOutgoingMessages(params.conversationMessages, volatileStateMessage, isAppendOnly);
5656
+ promptParams.conversationMessages = this.assembleOutgoingMessages(promptParams.conversationMessages ?? params.conversationMessages, volatileStateMessage, isAppendOnly);
5464
5657
  if (isAppendOnly) {
5465
5658
  params.conversationMessages.push(volatileStateMessage);
5466
5659
  }
5467
5660
  this._lastVolatileStateMessage = volatileStateMessage;
5661
+ if (promptParams.data?._SPECIALIZATION_RELOCATED === true) {
5662
+ promptParams.OnTemplateDataFinalized = (finalParams) => this.refreshRelocatedSpecialization(finalParams, config, payload, params, volatileStateMessage);
5663
+ }
5468
5664
  }
5469
5665
  if (promptParams.conversationMessages) {
5470
5666
  promptParams.conversationMessages = this.dropReasoningBehindChangedHistory(params, promptParams.conversationMessages, promptParams);
5471
5667
  }
5472
5668
  return promptParams;
5473
5669
  }
5670
+ /**
5671
+ * Renders the trailing message again once the prompt runner has set the native tool-calling flags,
5672
+ * and swaps it in when the text changed.
5673
+ *
5674
+ * A relocated specialization is pre-rendered here, before a model is selected, so it renders
5675
+ * without the flags the runner sets from the selected model's tool-calling decision — a child
5676
+ * prompt that words its instructions for the native or envelope path would get the envelope
5677
+ * wording while the system prompt gets the native one. The runner calls this through
5678
+ * {@link AIPromptParams.OnTemplateDataFinalized}. On any failure the message already built is kept.
5679
+ */
5680
+ async refreshRelocatedSpecialization(promptParams, config, payload, params, previous) {
5681
+ try {
5682
+ const rebuilt = await this.buildVolatileStateMessage(params, promptParams, payload, config.childPrompt, config.agentType, config.systemPrompt);
5683
+ if (!rebuilt || rebuilt.content === previous.content) {
5684
+ return;
5685
+ }
5686
+ const replace = (messages) => {
5687
+ const at = messages ? messages.indexOf(previous) : -1;
5688
+ if (messages && at >= 0) {
5689
+ messages[at] = rebuilt;
5690
+ }
5691
+ };
5692
+ replace(promptParams.conversationMessages);
5693
+ replace(params.conversationMessages);
5694
+ this._lastVolatileStateMessage = rebuilt;
5695
+ // The fingerprints were taken before the swap; without this, an append-only history
5696
+ // reads the swapped message as changed next turn and drops the reasoning after it.
5697
+ if (this._lastSentFingerprints !== undefined && promptParams.conversationMessages) {
5698
+ this._lastSentFingerprints = promptParams.conversationMessages.map(BaseAgent.messageFingerprint);
5699
+ }
5700
+ }
5701
+ catch (error) {
5702
+ this.logStatus(`Kept the trailing message as first built: re-rendering it with the final template data failed (${error instanceof Error ? error.message : String(error)})`, true, params);
5703
+ }
5704
+ }
5474
5705
  /**
5475
5706
  * Drops replayed reasoning that the history before it no longer matches.
5476
5707
  *
@@ -5484,6 +5715,10 @@ export class BaseAgent {
5484
5715
  * are not a change.
5485
5716
  */
5486
5717
  dropReasoningBehindChangedHistory(params, outgoing, promptParams) {
5718
+ if (!this.shouldTrackSentFingerprints(outgoing)) {
5719
+ this._lastSentFingerprints = undefined;
5720
+ return outgoing;
5721
+ }
5487
5722
  const fingerprints = outgoing.map(BaseAgent.messageFingerprint);
5488
5723
  const previous = this._lastSentFingerprints;
5489
5724
  this._lastSentFingerprints = fingerprints;
@@ -5523,6 +5758,20 @@ export class BaseAgent {
5523
5758
  return this._nativeToolBindings !== undefined
5524
5759
  && this.DriverRequiresStableReasoningPrefix(selection?.ModelSelected, selection?.vendorSelected);
5525
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
+ }
5526
5775
  /**
5527
5776
  * Keeps the system-prompt-and-tools fingerprint of the request just sent, for the next one. When
5528
5777
  * it changed, the runner sent this request without replayed reasoning; the history drops it too,
@@ -5550,9 +5799,22 @@ export class BaseAgent {
5550
5799
  }
5551
5800
  });
5552
5801
  }
5802
+ static { this._messageFingerprintCache = new WeakMap(); }
5553
5803
  /** What makes a message the same message to a provider — reasoning aside, which only this check removes. */
5554
5804
  static messageFingerprint(m) {
5555
- 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;
5556
5818
  }
5557
5819
  /**
5558
5820
  * In append-only mode, restores turn 1's volatile state fragment if mode resolution
@@ -6530,6 +6792,26 @@ export class BaseAgent {
6530
6792
  stepActionNamesLower.has(a.Name.trim().toLowerCase()) ||
6531
6793
  stepActionNamesSanitized.has(SanitizeToolName(a.Name))));
6532
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
+ }
6533
6815
  /**
6534
6816
  * Combines {@link getEffectiveActionsForValidation} with {@link getFlowStepActions} (deduplicated
6535
6817
  * by `ID`) so both Loop agents (strictly `AIAgentAction` / `_effectiveActions`) and Flow agents
@@ -8164,9 +8446,12 @@ The context is now within limits. Please retry your request with the recovered c
8164
8446
  * @protected
8165
8447
  */
8166
8448
  async processNextStep(nextStep, params, agentType, promptResult, currentPayload, currentStep) {
8449
+ // Read before validation: a subclass may change the step in place (turn a Chat into a Success),
8450
+ // and only a change the prompt step held as a completion draft can have been discarded.
8451
+ const heldCompletionChange = BaseAgent.carriesCompletionChange(nextStep) ? nextStep.payloadChangeRequest : undefined;
8167
8452
  const validatedNextStep = await this.validateNextStep(params, nextStep, currentPayload, this._agentRun, currentStep);
8168
8453
  // Check guardrails if next step would continue execution
8169
- const guardrailCheckedStep = this.noteDiscardedCompletionChange(nextStep, await this.checkExecutionGuardrails(params, validatedNextStep, currentPayload, this._agentRun, currentStep));
8454
+ const guardrailCheckedStep = this.noteHeldCompletionChange(heldCompletionChange, await this.checkExecutionGuardrails(params, validatedNextStep, currentPayload, this._agentRun, currentStep));
8170
8455
  this.logStatus(`📌 Next step determined: ${guardrailCheckedStep.step}${guardrailCheckedStep.terminate ? ' (terminating)' : ''}`, true, params);
8171
8456
  // the model's own call turn goes into history before anything answers it.
8172
8457
  this.appendNativeAssistantTurn(params, guardrailCheckedStep);
@@ -8211,22 +8496,26 @@ The context is now within limits. Please retry your request with the recovered c
8211
8496
  return guardrailCheckedStep;
8212
8497
  }
8213
8498
  /**
8214
- * A completion refused with a payload change in hand: the change is discarded (the prompt step
8215
- * commits it only for an accepted completion), so the refusal the model reads says so, and asks
8216
- * for the change again with the next completion. Otherwise the model would take the change as
8217
- * saved and its work would be lost. The change is removed from the step, so nothing later
8218
- * applies it. Any other step is returned as it is.
8499
+ * A completion refused with a payload change in hand: the change is held, not applied (see
8500
+ * {@link _heldCompletionChanges}), so the refusal the model reads says so and asks for the
8501
+ * corrections only. The model sees the payload with the held change applied from the next turn,
8502
+ * and its next completion's change is applied on top of it. The change is removed from the step,
8503
+ * so nothing later applies it a second time. Any other step is returned as it is.
8504
+ *
8505
+ * `heldChange` is the change the prompt step held as a draft, read from the step before
8506
+ * validation, so a step a subclass changed in place is judged by what the model sent.
8219
8507
  */
8220
- noteDiscardedCompletionChange(original, step) {
8221
- if (!BaseAgent.carriesCompletionChange(original) || step.step === 'Success') {
8508
+ noteHeldCompletionChange(heldChange, step) {
8509
+ if (!heldChange || step.step === 'Success') {
8222
8510
  return step;
8223
8511
  }
8224
8512
  const native = !!step.payloadToolCallId && this.nativeToolNameForCall(step, step.payloadToolCallId) === COMPLETE_TASK_TOOL;
8225
- const note = native
8226
- ? 'The payloadChangeRequest sent with this complete_task call was NOT applied. Send it again with your next complete_task call.'
8227
- : 'The payloadChangeRequest sent with this completion was NOT applied. Send it again with your next completion.';
8513
+ const call = native ? 'complete_task call' : 'completion';
8514
+ const note = `The payloadChangeRequest sent with this ${call} was not applied yet: it is held, and the payload you see `
8515
+ + `from now on includes it. It is applied together with your next ${call}. In that ${call}, send only the `
8516
+ + `corrections, not the whole change again.`;
8228
8517
  const field = step.retryInstructions ? 'retryInstructions' : step.message ? 'message' : 'errorMessage';
8229
- const { payloadChangeRequest: _discarded, ...rest } = step;
8518
+ const { payloadChangeRequest: _held, ...rest } = step;
8230
8519
  return { ...rest, [field]: step[field] ? `${step[field]}\n\n${note}` : note };
8231
8520
  }
8232
8521
  /**
@@ -11263,6 +11552,12 @@ The context is now within limits. Please retry your request with the recovered c
11263
11552
  stampActionContext(params) {
11264
11553
  const actionContext = (typeof params.context === 'object' && params.context ? params.context : {});
11265
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
+ }
11266
11561
  // The skills active in THIS run, as a fact the action can trust. An action that takes a
11267
11562
  // skill principal (Scoped Search's AISkillID) must not have to believe a parameter the model
11268
11563
  // authored: with this it can default the principal to the run's active skill and refuse a
@@ -11802,7 +12097,7 @@ The context is now within limits. Please retry your request with the recovered c
11802
12097
  apiKeys: params.apiKeys, // propagate API keys to sub-agent
11803
12098
  CredentialScope: params.CredentialScope, // a sub-agent may not spend keys its parent could not
11804
12099
  Audience: params.Audience, // a sub-agent's output reaches the same room; it re-hydrates the IDs itself
11805
- 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
11806
12101
  data: {
11807
12102
  ...params.data,
11808
12103
  ...templateParameters,
@@ -11831,6 +12126,9 @@ The context is now within limits. Please retry your request with the recovered c
11831
12126
  // Every sub-agent path (child, related, parallel) comes through here, so the child's taint reaches
11832
12127
  // the parent whichever path ran it.
11833
12128
  this.absorbSubAgentTaint(subAgentRequest.name, result, stepEntity?.StepNumber ?? (stepCount + 1));
12129
+ if (result.touchedArtifacts?.length) {
12130
+ this._artifactToolManager.AbsorbTouchedArtifacts(result.touchedArtifacts);
12131
+ }
11834
12132
  // Check if execution was successful
11835
12133
  if (result.success) {
11836
12134
  this.logStatus(`✅ Sub-agent '${subAgentRequest.name}' completed successfully`, true, params);
@@ -13277,7 +13575,12 @@ The context is now within limits. Please retry your request with the recovered c
13277
13575
  if (!previousDecision) {
13278
13576
  // First execution - ask the agent type what to do
13279
13577
  const initialStep = await this.AgentTypeInstance.DetermineInitialStep(params, params.payload, this.AgentTypeState);
13280
- 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
+ }
13281
13584
  if (initialStep) {
13282
13585
  // Agent type provided an initial step
13283
13586
  return initialStep;
@@ -13533,15 +13836,57 @@ The context is now within limits. Please retry your request with the recovered c
13533
13836
  return changeResult;
13534
13837
  }
13535
13838
  /**
13536
- * The payload a completion would leave behind: the committed payload with the completion's
13537
- * change applied. Success validation (the minimum-execution check, then `FinalPayloadValidation`)
13538
- * checks this draft, and it becomes the payload only if the completion is accepted. The
13539
- * opt-in payload change check is not asked here: it never runs on a step that ends the run.
13839
+ * The payload a completion would leave behind: the committed payload with the held changes and
13840
+ * then the completion's own change applied. Success validation (the minimum-execution check, then
13841
+ * `FinalPayloadValidation`) checks this draft, and it becomes the payload only if the completion is
13842
+ * accepted. A change identical to a held one is not applied again, so a model that resends its whole
13843
+ * refused change does not duplicate array elements. The opt-in payload change check is not asked
13844
+ * here: it never runs on a step that ends the run.
13540
13845
  */
13541
13846
  buildCompletionDraft(params, step, committed, isUnmodifiedInheritedPayload) {
13542
- const changeResult = this.applyTurnPayloadChange(params, step, committed, isUnmodifiedInheritedPayload);
13847
+ const working = this.withHeldCompletionChanges(params, committed);
13848
+ const change = step.payloadChangeRequest;
13849
+ if (!change || this.isHeldCompletionChange(change)) {
13850
+ return { payload: working, summary: undefined };
13851
+ }
13852
+ const changeResult = this.applyTurnPayloadChange(params, step, working, isUnmodifiedInheritedPayload && this._heldCompletionChanges.length === 0);
13543
13853
  return { payload: changeResult.result, summary: this.buildPayloadChangeResultSummary(changeResult) };
13544
13854
  }
13855
+ /** `payload` with the held completion changes applied in order; `payload` itself when none are held. */
13856
+ withHeldCompletionChanges(params, payload) {
13857
+ return this._heldCompletionChanges.reduce((current, held) => {
13858
+ const step = { step: 'Success', terminate: false, payloadChangeRequest: held.Change };
13859
+ return this.applyTurnPayloadChange(params, step, current, held.UnmodifiedInheritedPayload).result;
13860
+ }, payload);
13861
+ }
13862
+ /**
13863
+ * After a completion: an accepted one commits the held changes (they were in its draft), so the
13864
+ * list is cleared; a refused one adds its own change to the list, unless the same change is held.
13865
+ */
13866
+ updateHeldCompletionChanges(step, committedDraft, isUnmodifiedInheritedPayload) {
13867
+ if (committedDraft) {
13868
+ this._heldCompletionChanges = [];
13869
+ return;
13870
+ }
13871
+ const change = BaseAgent.carriesCompletionChange(step) ? step.payloadChangeRequest : undefined;
13872
+ if (change && !this.isHeldCompletionChange(change)) {
13873
+ this._heldCompletionChanges.push({
13874
+ Change: change,
13875
+ UnmodifiedInheritedPayload: isUnmodifiedInheritedPayload && this._heldCompletionChanges.length === 0
13876
+ });
13877
+ }
13878
+ }
13879
+ /** Whether `change` is, key order aside, one of the held completion changes. */
13880
+ isHeldCompletionChange(change) {
13881
+ const key = BaseAgent.stableJSON(change);
13882
+ return this._heldCompletionChanges.some((held) => BaseAgent.stableJSON(held.Change) === key);
13883
+ }
13884
+ /** JSON with object keys sorted, so two equal values serialize the same. */
13885
+ static stableJSON(value) {
13886
+ return JSON.stringify(value, (_key, v) => v && typeof v === 'object' && !Array.isArray(v)
13887
+ ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
13888
+ : v);
13889
+ }
13545
13890
  /**
13546
13891
  * The payload a turn leaves behind. A held completion draft is committed only when the step is
13547
13892
  * still `Success` after validation; on a refusal the committed payload stands (a subclass that
@@ -13600,11 +13945,13 @@ The context is now within limits. Please retry your request with the recovered c
13600
13945
  });
13601
13946
  // PayloadAtStart was already serialized from this same `payload` by createStepEntity
13602
13947
  // above (payloadAtStart: payload) — no need to re-serialize the (potentially large) payload here.
13603
- let downstreamPayload = payload; // Start with current payload
13948
+ // The model sees the payload with any held completion changes applied (see _heldCompletionChanges).
13949
+ const workingPayload = this.withHeldCompletionChanges(params, payload);
13950
+ let downstreamPayload = workingPayload; // Start with current payload
13604
13951
  if (params.agent.PayloadSelfReadPaths) {
13605
13952
  const downstreamPaths = JSON.parse(params.agent.PayloadSelfReadPaths);
13606
13953
  // Extract only allowed downstream payload
13607
- downstreamPayload = this._payloadManager.extractDownstreamPayload(`Self: ${params.agent.Name}`, payload, // our inbound payload before prompt
13954
+ downstreamPayload = this._payloadManager.extractDownstreamPayload(`Self: ${params.agent.Name}`, workingPayload, // our inbound payload before prompt
13608
13955
  downstreamPaths);
13609
13956
  }
13610
13957
  // now prep the params using the downstream payload - which is often the full
@@ -13622,7 +13969,7 @@ The context is now within limits. Please retry your request with the recovered c
13622
13969
  this._agentRun.TotalPromptIterations = (this._agentRun.TotalPromptIterations || 0) + 1;
13623
13970
  // don't need to save here, the run will be saved later
13624
13971
  }
13625
- const promptParams = await this.preparePromptParams(promptConfig, downstreamPayload, params);
13972
+ const promptParams = await this.finalizePromptParams(await this.preparePromptParams(promptConfig, downstreamPayload, params), promptConfig, downstreamPayload, params);
13626
13973
  // Pass cancellation token and streaming callbacks to prompt execution.
13627
13974
  // Coalesce rapid token chunks within a ~35ms window while emitting the first chunk immediately
13628
13975
  // and flushing synchronously on completion so downstream GraphQL/PubSub/WebSocket callbacks
@@ -13790,7 +14137,8 @@ The context is now within limits. Please retry your request with the recovered c
13790
14137
  let currentStepPayloadChangeResult = undefined;
13791
14138
  // A completion's payload change is held as a draft until Success validation accepts it
13792
14139
  // (see buildCompletionDraft); every other step's change is applied now, as it always was.
13793
- const holdsCompletionChange = BaseAgent.carriesCompletionChange(initialNextStep);
14140
+ const holdsCompletionChange = BaseAgent.carriesCompletionChange(initialNextStep)
14141
+ || (initialNextStep.step === 'Success' && this._heldCompletionChanges.length > 0);
13794
14142
  if (initialNextStep.payloadChangeRequest && !holdsCompletionChange) {
13795
14143
  const changeResult = this.applyTurnPayloadChange(params, initialNextStep, payload, isUnmodifiedInheritedPayload);
13796
14144
  // Store payload change metadata for audit trail; merged into outputData later
@@ -13891,8 +14239,9 @@ The context is now within limits. Please retry your request with the recovered c
13891
14239
  // sub-classes may have modified the payload, and we allow that, and so we need to update finalPayload to map to the updatedNextStep.newPayload
13892
14240
  const resolved = this.resolveTurnPayload(updatedNextStep, finalPayload, draft);
13893
14241
  finalPayload = resolved.payload;
13894
- const discardedCompletionChange = holdsCompletionChange && !resolved.committedDraft;
13895
- if (discardedCompletionChange && currentStepPayloadChangeResult) {
14242
+ const heldCompletionChange = holdsCompletionChange && !resolved.committedDraft;
14243
+ this.updateHeldCompletionChanges(initialNextStep, resolved.committedDraft, finalPayload === params.payload);
14244
+ if (heldCompletionChange && currentStepPayloadChangeResult) {
13896
14245
  currentStepPayloadChangeResult = { ...currentStepPayloadChangeResult, applied: { additions: 0, updates: 0, deletions: 0 } };
13897
14246
  }
13898
14247
  // Prepare output data, these are simple elements of the state that are not typically
@@ -13909,8 +14258,8 @@ The context is now within limits. Please retry your request with the recovered c
13909
14258
  payloadChangeResult: currentStepPayloadChangeResult
13910
14259
  }),
13911
14260
  // A completion's change that was not applied because the completion was refused
13912
- ...(discardedCompletionChange && {
13913
- payloadChangeDiscarded: 'The payload change was sent with a completion that was refused, so it was not applied.'
14261
+ ...(heldCompletionChange && {
14262
+ payloadChangeHeld: 'The completion was refused, so its payload change is held: it is applied with the next accepted completion, or dropped if the run ends without one.'
13914
14263
  }),
13915
14264
  // Include scratchpad snapshot after changes for audit/training data
13916
14265
  ...(this._scratchpadManager.HasContent() && {
@@ -13961,7 +14310,7 @@ The context is now within limits. Please retry your request with the recovered c
13961
14310
  // needs one more turn to see the results and incorporate them into its response.
13962
14311
  // Without this, the tool results are wasted because the run exits before
13963
14312
  // the LLM ever sees them.
13964
- if (artifactToolsExecutedThisTurn && this._artifactToolManager.HasArtifacts()) {
14313
+ if (artifactToolsExecutedThisTurn && this._artifactToolManager.IsWorkspaceEnabled()) {
13965
14314
  this.logStatus(`[ArtifactTools] Chat step included tool calls — forcing one more turn so LLM can use results`, true, params);
13966
14315
  return { ...updatedNextStep, terminate: false, step: 'Retry' };
13967
14316
  }
@@ -14539,7 +14888,8 @@ The context is now within limits. Please retry your request with the recovered c
14539
14888
  }
14540
14889
  /**
14541
14890
  * Finds a sub-agent by name, checking child agents (ParentID) first, then
14542
- * 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
14543
14893
  * doesn't resolve to an active agent reachable from `params.agent`.
14544
14894
  *
14545
14895
  * Used by both the single and parallel sub-agent dispatch paths so name
@@ -14577,7 +14927,18 @@ The context is now within limits. Please retry your request with the recovered c
14577
14927
  return { subAgentEntity: matchedPair.agent, relationship: matchedPair.rel };
14578
14928
  }
14579
14929
  }
14580
- // 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
14581
14942
  // the SAME effective set the prompt offered and validateSubAgentNextStep approved. Without
14582
14943
  // this branch, a skill-granted sub-agent passes validation but fails execution ("not found
14583
14944
  // or not active") — and because the catalog keeps offering it, the model re-picks the same
@@ -14589,7 +14950,7 @@ The context is now within limits. Please retry your request with the recovered c
14589
14950
  if (effectiveAgent) {
14590
14951
  return { subAgentEntity: effectiveAgent };
14591
14952
  }
14592
- // 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
14593
14954
  // any active peer agent via Find Candidate Agents and delegate a 1-node Tasks graph to it.
14594
14955
  // LoopAgentType folds that 1-node graph into an in-run Sub-Agent step (`taskGraph.folded === true`),
14595
14956
  // so allow resolving any active agent in AIEngine.Instance.Agents.
@@ -16577,7 +16938,7 @@ The context is now within limits. Please retry your request with the recovered c
16577
16938
  // path carried neither, so every documented `data.x` condition evaluated against the
16578
16939
  // origin step's output, found nothing, and silently took the other branch.
16579
16940
  Invocation: { Data: params.data, Context: params.context },
16580
- Debug: params.taskGraphDebug?.paused ? { paused: true } : undefined,
16941
+ Debug: BuildTaskGraphStartDebug(params.taskGraphDebug),
16581
16942
  ContextUser: params.contextUser,
16582
16943
  Provider: this.ProviderToUse,
16583
16944
  ...(securityEnvelope ? { SecurityEnvelope: securityEnvelope } : {}),
@@ -16866,6 +17227,10 @@ The context is now within limits. Please retry your request with the recovered c
16866
17227
  * @private
16867
17228
  */
16868
17229
  async createFeedbackRequest(params, stepEntity, previousDecision) {
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);
16869
17234
  const requestId = await this._feedbackCoordinator.CreateFeedbackRequest({
16870
17235
  Params: params,
16871
17236
  StepEntity: stepEntity,
@@ -17691,8 +18056,8 @@ The context is now within limits. Please retry your request with the recovered c
17691
18056
  : errorMessage;
17692
18057
  // Calculate total tokens even for failed runs
17693
18058
  this.applyTokenStatsToRun(this._agentRun, this.calculateTokenStats());
17694
- await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
17695
- AgentRunWatchdog.Instance.Untrack(this._agentRun.ID);
18059
+ const ok = await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
18060
+ this.releaseFinishedRun(ok);
17696
18061
  }
17697
18062
  return {
17698
18063
  success: false,
@@ -17709,6 +18074,12 @@ The context is now within limits. Please retry your request with the recovered c
17709
18074
  * @returns {Promise<ExecuteAgentResult>} The cancelled result
17710
18075
  */
17711
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
+ }
17712
18083
  const [{ failures }] = await Promise.all([
17713
18084
  this._stepSaveQueue.Flush(),
17714
18085
  this.flushPromptRunnerSaves(),
@@ -17737,8 +18108,8 @@ The context is now within limits. Please retry your request with the recovered c
17737
18108
  }
17738
18109
  // Calculate total tokens even for cancelled runs
17739
18110
  this.applyTokenStatsToRun(this._agentRun, this.calculateTokenStats());
17740
- await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
17741
- AgentRunWatchdog.Instance.Untrack(this._agentRun.ID);
18111
+ const ok = await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
18112
+ this.releaseFinishedRun(ok);
17742
18113
  }
17743
18114
  return {
17744
18115
  success: false,
@@ -17750,7 +18121,9 @@ The context is now within limits. Please retry your request with the recovered c
17750
18121
  * Maps the reason an abort signal carried to the run's `CancellationReason` value: the
17751
18122
  * watchdog's stop relay raises {@link AgentRunWatchdog.UserCancelAbortReason} for a row marked
17752
18123
  * `User Request`; the wall-clock guard's reason starts with {@link AgentTimeoutAbortReason};
17753
- * 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.
17754
18127
  */
17755
18128
  static CancellationReasonForAbort(reason) {
17756
18129
  if (reason === AgentRunWatchdog.UserCancelAbortReason) {
@@ -17785,6 +18158,18 @@ The context is now within limits. Please retry your request with the recovered c
17785
18158
  }
17786
18159
  return null;
17787
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
+ }
17788
18173
  /**
17789
18174
  * Finalizes the agent run with success.
17790
18175
  *
@@ -17869,7 +18254,7 @@ The context is now within limits. Please retry your request with the recovered c
17869
18254
  // Calculate total tokens from all prompts and sub-agents
17870
18255
  this.applyTokenStatsToRun(this._agentRun, this.calculateTokenStats());
17871
18256
  const ok = await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
17872
- AgentRunWatchdog.Instance.Untrack(this._agentRun.ID);
18257
+ this.releaseFinishedRun(ok);
17873
18258
  if (!ok) {
17874
18259
  LogError(`Failed to finalize agent run ${this._agentRun.ID}`);
17875
18260
  }
@@ -17916,6 +18301,16 @@ The context is now within limits. Please retry your request with the recovered c
17916
18301
  }
17917
18302
  // Return unified media outputs — all items are persisted by AgentRunner.
17918
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;
17919
18314
  return {
17920
18315
  success: finalStep.step === 'Success' || finalStep.step === 'Chat',
17921
18316
  payload: resolvedPayload,
@@ -17932,7 +18327,8 @@ The context is now within limits. Please retry your request with the recovered c
17932
18327
  feedbackRequestId: this._feedbackRequestId || undefined,
17933
18328
  taintedSources: this._taintedSources.length > 0 ? [...this._taintedSources] : undefined,
17934
18329
  handoff: this._handoffResult || undefined,
17935
- resolvedStorageAccountId: this._resolvedStorageAccountId || undefined
18330
+ resolvedStorageAccountId: this._resolvedStorageAccountId || undefined,
18331
+ ...(touchedArtifacts ? { touchedArtifacts } : {})
17936
18332
  };
17937
18333
  }
17938
18334
  /**
@@ -18659,9 +19055,17 @@ The context is now within limits. Please retry your request with the recovered c
18659
19055
  if (!memoryManagerEntity || !params.contextUser) {
18660
19056
  return;
18661
19057
  }
18662
- const driverKey = memoryManagerEntity.DriverClass || 'MemoryManagerAgent';
18663
- const memoryAgent = MJGlobal.Instance.ClassFactory.CreateInstance(BaseAgent, driverKey);
18664
- 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)}`);
18665
19069
  return;
18666
19070
  }
18667
19071
  void memoryAgent.Execute({
@@ -18888,16 +19292,29 @@ The context is now within limits. Please retry your request with the recovered c
18888
19292
  }
18889
19293
  /**
18890
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.
18891
19296
  * @param text - The text to estimate tokens for
18892
19297
  * @returns Estimated token count
18893
19298
  * @private
18894
19299
  */
18895
19300
  heuristicTokenCount(text) {
18896
- // More sophisticated heuristic
18897
19301
  const charCount = text.length;
18898
- // Count structural tokens (JSON syntax adds overhead)
18899
- const structuralChars = (text.match(/[\{\}\[\],:]/g) || []).length;
18900
- 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
+ }
18901
19318
  // Effective character count (whitespace counts less)
18902
19319
  const effectiveChars = charCount - (whitespaceChars * 0.5);
18903
19320
  // Base ratio: 4 chars per token