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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/README.md +100 -7
  2. package/dist/AgentRunner.d.ts +55 -5
  3. package/dist/AgentRunner.d.ts.map +1 -1
  4. package/dist/AgentRunner.js +277 -59
  5. package/dist/AgentRunner.js.map +1 -1
  6. package/dist/ArtifactToolManager.d.ts +11 -3
  7. package/dist/ArtifactToolManager.d.ts.map +1 -1
  8. package/dist/ArtifactToolManager.js +72 -6
  9. package/dist/ArtifactToolManager.js.map +1 -1
  10. package/dist/ClientToolRequestManager.d.ts +11 -1
  11. package/dist/ClientToolRequestManager.d.ts.map +1 -1
  12. package/dist/ClientToolRequestManager.js +19 -6
  13. package/dist/ClientToolRequestManager.js.map +1 -1
  14. package/dist/ConversationCompactionManager.d.ts +2 -0
  15. package/dist/ConversationCompactionManager.d.ts.map +1 -1
  16. package/dist/ConversationCompactionManager.js +2 -2
  17. package/dist/ConversationCompactionManager.js.map +1 -1
  18. package/dist/ConversationToolManager.d.ts +13 -2
  19. package/dist/ConversationToolManager.d.ts.map +1 -1
  20. package/dist/ConversationToolManager.js +19 -3
  21. package/dist/ConversationToolManager.js.map +1 -1
  22. package/dist/KnowledgeAgent.d.ts.map +1 -1
  23. package/dist/KnowledgeAgent.js +6 -1
  24. package/dist/KnowledgeAgent.js.map +1 -1
  25. package/dist/MJAIAgentRequestEntityServer.d.ts +6 -0
  26. package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
  27. package/dist/MJAIAgentRequestEntityServer.js +26 -1
  28. package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
  29. package/dist/PayloadChangeAnalyzer.d.ts.map +1 -1
  30. package/dist/PayloadChangeAnalyzer.js +53 -30
  31. package/dist/PayloadChangeAnalyzer.js.map +1 -1
  32. package/dist/PayloadManager.d.ts +35 -2
  33. package/dist/PayloadManager.d.ts.map +1 -1
  34. package/dist/PayloadManager.js +250 -149
  35. package/dist/PayloadManager.js.map +1 -1
  36. package/dist/ScratchpadManager.d.ts +18 -0
  37. package/dist/ScratchpadManager.d.ts.map +1 -1
  38. package/dist/ScratchpadManager.js +61 -0
  39. package/dist/ScratchpadManager.js.map +1 -1
  40. package/dist/agent-audience.d.ts +38 -0
  41. package/dist/agent-audience.d.ts.map +1 -0
  42. package/dist/agent-audience.js +99 -0
  43. package/dist/agent-audience.js.map +1 -0
  44. package/dist/agent-context-injector.d.ts +17 -2
  45. package/dist/agent-context-injector.d.ts.map +1 -1
  46. package/dist/agent-context-injector.js +23 -7
  47. package/dist/agent-context-injector.js.map +1 -1
  48. package/dist/agent-memory-context-builder.d.ts +7 -2
  49. package/dist/agent-memory-context-builder.d.ts.map +1 -1
  50. package/dist/agent-memory-context-builder.js +12 -3
  51. package/dist/agent-memory-context-builder.js.map +1 -1
  52. package/dist/agent-pre-execution-rag.d.ts +101 -9
  53. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  54. package/dist/agent-pre-execution-rag.js +224 -23
  55. package/dist/agent-pre-execution-rag.js.map +1 -1
  56. package/dist/agent-run-watchdog.d.ts +65 -5
  57. package/dist/agent-run-watchdog.d.ts.map +1 -1
  58. package/dist/agent-run-watchdog.js +143 -28
  59. package/dist/agent-run-watchdog.js.map +1 -1
  60. package/dist/agent-types/flow-agent-type.d.ts +8 -0
  61. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  62. package/dist/agent-types/flow-agent-type.js +48 -6
  63. package/dist/agent-types/flow-agent-type.js.map +1 -1
  64. package/dist/agent-types/loop-agent-prompt-params.d.ts +7 -0
  65. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  66. package/dist/agent-types/loop-agent-prompt-params.js +1 -0
  67. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  68. package/dist/agent-types/loop-agent-response-type.d.ts +8 -2
  69. package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
  70. package/dist/agent-types/loop-agent-response-type.js.map +1 -1
  71. package/dist/agent-types/loop-agent-type.d.ts +9 -2
  72. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  73. package/dist/agent-types/loop-agent-type.js +60 -16
  74. package/dist/agent-types/loop-agent-type.js.map +1 -1
  75. package/dist/artifact-tools/SearchResultSetToolLibrary.js +4 -4
  76. package/dist/artifact-tools/SearchResultSetToolLibrary.js.map +1 -1
  77. package/dist/base-agent.d.ts +837 -43
  78. package/dist/base-agent.d.ts.map +1 -1
  79. package/dist/base-agent.js +3081 -663
  80. package/dist/base-agent.js.map +1 -1
  81. package/dist/client-tool-results.d.ts +45 -0
  82. package/dist/client-tool-results.d.ts.map +1 -0
  83. package/dist/client-tool-results.js +94 -0
  84. package/dist/client-tool-results.js.map +1 -0
  85. package/dist/index.d.ts +9 -0
  86. package/dist/index.d.ts.map +1 -1
  87. package/dist/index.js +9 -0
  88. package/dist/index.js.map +1 -1
  89. package/dist/memory-manager-agent.d.ts.map +1 -1
  90. package/dist/memory-manager-agent.js +46 -34
  91. package/dist/memory-manager-agent.js.map +1 -1
  92. package/dist/native-tools/action-param-schema.d.ts +57 -0
  93. package/dist/native-tools/action-param-schema.d.ts.map +1 -0
  94. package/dist/native-tools/action-param-schema.js +238 -0
  95. package/dist/native-tools/action-param-schema.js.map +1 -0
  96. package/dist/native-tools/action-tool-builder.d.ts +5 -4
  97. package/dist/native-tools/action-tool-builder.d.ts.map +1 -1
  98. package/dist/native-tools/action-tool-builder.js +29 -71
  99. package/dist/native-tools/action-tool-builder.js.map +1 -1
  100. package/dist/native-tools/json-argument.d.ts +41 -0
  101. package/dist/native-tools/json-argument.d.ts.map +1 -0
  102. package/dist/native-tools/json-argument.js +79 -0
  103. package/dist/native-tools/json-argument.js.map +1 -0
  104. package/dist/prior-turn-tool-result-cache.d.ts +31 -12
  105. package/dist/prior-turn-tool-result-cache.d.ts.map +1 -1
  106. package/dist/prior-turn-tool-result-cache.js +59 -16
  107. package/dist/prior-turn-tool-result-cache.js.map +1 -1
  108. package/dist/query-builder-agent.d.ts +13 -4
  109. package/dist/query-builder-agent.d.ts.map +1 -1
  110. package/dist/query-builder-agent.js +102 -27
  111. package/dist/query-builder-agent.js.map +1 -1
  112. package/dist/realtime/bridge-realtime-session-factory.d.ts +44 -2
  113. package/dist/realtime/bridge-realtime-session-factory.d.ts.map +1 -1
  114. package/dist/realtime/bridge-realtime-session-factory.js +68 -20
  115. package/dist/realtime/bridge-realtime-session-factory.js.map +1 -1
  116. package/dist/realtime/bridge-realtime-usage-recorder.d.ts +81 -0
  117. package/dist/realtime/bridge-realtime-usage-recorder.d.ts.map +1 -0
  118. package/dist/realtime/bridge-realtime-usage-recorder.js +194 -0
  119. package/dist/realtime/bridge-realtime-usage-recorder.js.map +1 -0
  120. package/dist/realtime/client-only-channel-server.d.ts +83 -0
  121. package/dist/realtime/client-only-channel-server.d.ts.map +1 -0
  122. package/dist/realtime/client-only-channel-server.js +107 -0
  123. package/dist/realtime/client-only-channel-server.js.map +1 -0
  124. package/dist/realtime/identity-verification-channel-server.d.ts +50 -0
  125. package/dist/realtime/identity-verification-channel-server.d.ts.map +1 -0
  126. package/dist/realtime/identity-verification-channel-server.js +66 -0
  127. package/dist/realtime/identity-verification-channel-server.js.map +1 -0
  128. package/dist/realtime/interactive-component-channel-server.d.ts +39 -0
  129. package/dist/realtime/interactive-component-channel-server.d.ts.map +1 -0
  130. package/dist/realtime/interactive-component-channel-server.js +55 -0
  131. package/dist/realtime/interactive-component-channel-server.js.map +1 -0
  132. package/dist/realtime/realtime-avatar-resolution.d.ts +194 -0
  133. package/dist/realtime/realtime-avatar-resolution.d.ts.map +1 -0
  134. package/dist/realtime/realtime-avatar-resolution.js +208 -0
  135. package/dist/realtime/realtime-avatar-resolution.js.map +1 -0
  136. package/dist/realtime/realtime-channel-policy.d.ts +81 -0
  137. package/dist/realtime/realtime-channel-policy.d.ts.map +1 -0
  138. package/dist/realtime/realtime-channel-policy.js +91 -0
  139. package/dist/realtime/realtime-channel-policy.js.map +1 -0
  140. package/dist/realtime/realtime-channel-server-host.d.ts +14 -0
  141. package/dist/realtime/realtime-channel-server-host.d.ts.map +1 -1
  142. package/dist/realtime/realtime-channel-server-host.js +35 -0
  143. package/dist/realtime/realtime-channel-server-host.js.map +1 -1
  144. package/dist/realtime/realtime-client-session-service.d.ts +435 -34
  145. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  146. package/dist/realtime/realtime-client-session-service.js +806 -139
  147. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  148. package/dist/realtime/realtime-coagent-config.d.ts +102 -16
  149. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  150. package/dist/realtime/realtime-coagent-config.js +126 -5
  151. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  152. package/dist/realtime/realtime-recording-ledger.d.ts +130 -0
  153. package/dist/realtime/realtime-recording-ledger.d.ts.map +1 -0
  154. package/dist/realtime/realtime-recording-ledger.js +190 -0
  155. package/dist/realtime/realtime-recording-ledger.js.map +1 -0
  156. package/dist/realtime/realtime-recording-opus-assembly.d.ts +211 -0
  157. package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -0
  158. package/dist/realtime/realtime-recording-opus-assembly.js +706 -0
  159. package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -0
  160. package/dist/realtime/realtime-recording-store.d.ts +174 -17
  161. package/dist/realtime/realtime-recording-store.d.ts.map +1 -1
  162. package/dist/realtime/realtime-recording-store.js +552 -58
  163. package/dist/realtime/realtime-recording-store.js.map +1 -1
  164. package/dist/realtime/realtime-session-runner.js +4 -4
  165. package/dist/realtime/realtime-session-runner.js.map +1 -1
  166. package/dist/realtime/realtime-turn-moderator.d.ts +2 -1
  167. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  168. package/dist/realtime/realtime-turn-moderator.js +7 -1
  169. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  170. package/dist/realtime/realtime-vendor-resolution.d.ts +9 -0
  171. package/dist/realtime/realtime-vendor-resolution.d.ts.map +1 -1
  172. package/dist/realtime/realtime-vendor-resolution.js +16 -5
  173. package/dist/realtime/realtime-vendor-resolution.js.map +1 -1
  174. package/dist/realtime/realtime-video-output-gate.d.ts +83 -0
  175. package/dist/realtime/realtime-video-output-gate.d.ts.map +1 -0
  176. package/dist/realtime/realtime-video-output-gate.js +79 -0
  177. package/dist/realtime/realtime-video-output-gate.js.map +1 -0
  178. package/dist/tool-result-format.d.ts +14 -0
  179. package/dist/tool-result-format.d.ts.map +1 -1
  180. package/dist/tool-result-format.js.map +1 -1
  181. package/dist/volatile-child-prompt.js +3 -3
  182. package/package.json +21 -19
@@ -10,7 +10,7 @@
10
10
  * @author MemberJunction.com
11
11
  * @since 2.49.0
12
12
  */
13
- import { MJAIAgentTypeEntity, MJTemplateParamEntity, MJAIAgentRelationshipEntity, MJAIAgentNoteEntity, MJAIAgentExampleEntity, MJAISkillEntity, MJAIVendorEntity } from '@memberjunction/core-entities';
13
+ import { MJAIAgentTypeEntity, MJTemplateParamEntity, MJAIAgentRelationshipEntity, MJAIAgentNoteEntity, MJAIAgentExampleEntity, MJAISkillEntity, MJAIVendorEntity, MJAIPromptRunEntity, type ConversationBranchRow } from '@memberjunction/core-entities';
14
14
  import { type NativeToolBinding } from './native-tools/control-tools.js';
15
15
  import { MJAIAgentRunEntityExtended, MJAIAgentRunStepEntityExtended, MJAIPromptEntityExtended, MJAIAgentEntityExtended, MJAIModelEntityExtended, MJAIPromptRunEntityExtended } from "@memberjunction/ai-core-plus";
16
16
  import { UserInfo, IMetadataProvider } from '@memberjunction/core';
@@ -24,11 +24,12 @@ import { AIEngine } from '@memberjunction/aiengine';
24
24
  import { AgentMemoryObservability } from './agent-memory-context-builder.js';
25
25
  import { CompactionOutcome, EffectiveContextBudget } from './ConversationCompactionManager.js';
26
26
  import { ConversationToolCall, ConversationToolExecutionResult, ConversationToolSummaryHost } from './ConversationToolManager.js';
27
- import { CarryForwardStepRecord } from './tool-result-format.js';
27
+ import { CarryForwardStepRecord, StoppedRunStepRecord } from './tool-result-format.js';
28
28
  import { AgentPreExecutionRAGResult } from './agent-pre-execution-rag.js';
29
- import { AIPromptParams, AIPromptRunResult, ExecuteAgentParams, AgentConfiguration, ExecuteAgentResult, AgentAction, AgentSubAgentRequest, BaseAgentNextStep, MessageLifecycleEvent, AgentChatMessage, AgentChatMessageMetadata, AIModelSelectionInfo, ActionChange, ActionChangeScope, SubAgentChange, MediaOutput, FileOutputRef, SecondaryScopeConfig, SecondaryScopeValue, AgentResponseForm, AgentPipelineRequest, AgentSkillActivationRequest, AgentSkillInvocation, SkillAvailabilityPurpose, AgentDecisionRequest, AgentDecisionResult, AgentDecisionAnswerSummary } from '@memberjunction/ai-core-plus';
29
+ import { AIPromptParams, AIPromptRunResult, ExecuteAgentParams, AgentTreeBudget, AgentConfiguration, ExecuteAgentResult, AgentAction, AgentSubAgentRequest, BaseAgentNextStep, MessageLifecycleEvent, AgentChatMessage, AgentChatMessageMetadata, AIModelSelectionInfo, ActionChange, ActionChangeScope, SubAgentChange, MediaOutput, FileOutputRef, SecondaryScopeConfig, SecondaryScopeValue, AgentResponseForm, AgentPipelineRequest, AgentSkillActivationRequest, AgentSkillInvocation, SkillAvailabilityPurpose, AgentDecisionRequest, AgentDecisionResult, AgentDecisionAnswerSummary, StopContinuationMode } from '@memberjunction/ai-core-plus';
30
30
  import { MJActionEntityExtended, ActionResult, ActionParam, AIDirective } from '@memberjunction/actions-base';
31
31
  import { RuntimeStateDateTime, RuntimeStateScratchpad } from './runtime-state-fragment.js';
32
+ import { ScratchpadManager } from './ScratchpadManager.js';
32
33
  import { ArtifactToolCall, StoredToolResult } from './ArtifactToolManager.js';
33
34
  import { MemoryWriteRequest, MemoryWriteResult } from './MemoryWriteManager.js';
34
35
  import { AgentDecisionService } from './AgentDecisionService.js';
@@ -37,6 +38,21 @@ import { PipelineToolRegistry, PipelineExecutionResult } from './pipeline/index.
37
38
  * Compact representation of a single action's execution result, used for
38
39
  * building the markdown summary that goes into conversation messages.
39
40
  */
41
+ /**
42
+ * A stopped run's step with its outcome. The full-stack resume reads every step of the run, not
43
+ * only completed results: it needs the prompt steps' recorded message stacks, and it needs to
44
+ * know which requested actions finished before the stop.
45
+ */
46
+ export interface StoppedRunStackStepRecord extends StoppedRunStepRecord {
47
+ Status: MJAIAgentRunStepEntityExtended['Status'];
48
+ Success: MJAIAgentRunStepEntityExtended['Success'];
49
+ }
50
+ /** What the pre-execution phase loaded about a user-stopped predecessor, applied once the phase settles. */
51
+ interface StoppedRunContinuation {
52
+ RunID: string;
53
+ Mode: StopContinuationMode;
54
+ Steps: StoppedRunStackStepRecord[];
55
+ }
40
56
  interface ActionResultSummary {
41
57
  actionName: string;
42
58
  success: boolean;
@@ -86,12 +102,15 @@ export interface ExecuteSingleActionOptions {
86
102
  *
87
103
  * - `'fatal'` — the action failed earlier in the run with a configuration or credential error and is
88
104
  * locked out for the rest of the run.
105
+ * - `'audience'` — the action engine refused the action for the run's audience (`AUDIENCE_UNSUPPORTED`): it cannot
106
+ * limit what it returns to what everyone in a shared conversation may see, so it is locked out for the run. Not a
107
+ * configuration or credential error, and the model is told so.
89
108
  * - `'identical-arguments'` — the action already failed {@link IDENTICAL_FAILURE_THRESHOLD} times
90
109
  * with these exact arguments.
91
110
  * - `'attempts-exhausted'` — the action has failed {@link ACTION_FAILURE_BUDGET} consecutive times
92
111
  * across any arguments.
93
112
  */
94
- export type ActionCircuitBreakerReason = 'fatal' | 'identical-arguments' | 'attempts-exhausted';
113
+ export type ActionCircuitBreakerReason = 'fatal' | 'audience' | 'identical-arguments' | 'attempts-exhausted';
95
114
  /** Identical-arguments rule: this many failures with the same arguments block further identical calls. */
96
115
  export declare const IDENTICAL_FAILURE_THRESHOLD = 2;
97
116
  /** Attempt budget: this many consecutive failures, across any arguments, disable the action for the run. */
@@ -188,6 +207,18 @@ export declare class BaseAgent {
188
207
  * @private
189
208
  */
190
209
  private _executeParams;
210
+ /**
211
+ * Shared root-tree cumulative budget tracking object for the current execution tree.
212
+ * Initialized at the start of {@link Execute} (or inherited from `params.treeBudget`
213
+ * when running as a sub-agent) and forwarded to all child and related sub-agent runs.
214
+ * @protected
215
+ */
216
+ protected _treeBudget: AgentTreeBudget | undefined;
217
+ /**
218
+ * Gets the shared {@link AgentTreeBudget} tracking cumulative steps, tokens, cost,
219
+ * and elapsed wall-clock duration across the root agent and all descendant sub-agents.
220
+ */
221
+ get TreeBudget(): AgentTreeBudget | undefined;
191
222
  /**
192
223
  * The agent configuration loaded for the current run — captured so the cross-turn
193
224
  * compaction hooks can resolve type-level budget defaults without re-loading.
@@ -226,6 +257,30 @@ export declare class BaseAgent {
226
257
  * @private
227
258
  */
228
259
  private _fatalActionFailures;
260
+ /**
261
+ * Actions the action engine refused for the run's audience (`AUDIENCE_UNSUPPORTED`) during the current run —
262
+ * locked out like {@link _fatalActionFailures}, under their own breaker reason (`'audience'`) so the model is
263
+ * told the action is unavailable in a shared conversation rather than misconfigured.
264
+ * @private
265
+ */
266
+ private _audienceLockedActions;
267
+ /**
268
+ * The run's audience readers beyond the caller (`ExecuteAgentParams.Audience`), hydrated from the user cache:
269
+ * `[]` when the audience adds nobody, `undefined` until hydrated for this run. Set after the permission check
270
+ * in {@link Execute}; {@link ExecuteSingleAction}, which is also called directly, hydrates it lazily.
271
+ * @private
272
+ */
273
+ private _audienceReaders;
274
+ /** The `ExecuteAgentParams.Audience` that {@link _audienceReaders} was hydrated from, so a different one re-hydrates. */
275
+ private _audienceSource;
276
+ /**
277
+ * The scope of the run in progress, exactly as {@link initializeAgentRun} validated and wrote it to the run row
278
+ * (nulls when the run is unscoped) — what every action dispatch is handed as `RunActionParams.RunScope`.
279
+ * `undefined` outside {@link Execute}: {@link ExecuteSingleAction}, which is also called directly, then
280
+ * resolves the scope from its params the same way.
281
+ * @private
282
+ */
283
+ private _runScope;
229
284
  /**
230
285
  * Parameter-aware failure tracking per action name for the current agent run.
231
286
  * Differentiates identical retries (which trip quickly) from parameter modifications (which allow self-correction).
@@ -308,6 +363,18 @@ export declare class BaseAgent {
308
363
  * consecutive-attempt budget.
309
364
  */
310
365
  protected recordActionFailure(action: AgentAction, actionEntity: MJActionEntityExtended | undefined, message: string | null | undefined, normalizedParams: string): void;
366
+ /**
367
+ * Locks an action out for the rest of the run: later calls short-circuit on the breaker's `'fatal'` rule, or on
368
+ * its `'audience'` rule for an action the engine refused for the run's audience.
369
+ */
370
+ private lockOutAction;
371
+ /** Clears the run-scoped circuit-breaker state (both lockouts and the failure history) for a new run. */
372
+ private resetActionCircuitBreaker;
373
+ /**
374
+ * The blocked result for an action locked out for the run — refused for the audience (`'audience'`), or failed
375
+ * with an unrecoverable configuration or credential error (`'fatal'`) — or null when it is not locked out.
376
+ */
377
+ private lockedOutActionResult;
311
378
  /**
312
379
  * Clears the parameter-aware failure history for an action after it succeeds, so the
313
380
  * identical-arguments rule and the consecutive-attempt budget start over.
@@ -316,7 +383,7 @@ export declare class BaseAgent {
316
383
  /**
317
384
  * Applies the three circuit-breaker rules to a call that is about to be dispatched. Returns a
318
385
  * blocked result, with the rule that fired, when the call must not go to the action engine;
319
- * null when it may proceed. Rules are checked fatal → identical-arguments → budget.
386
+ * null when it may proceed. Rules are checked audience → fatal → identical-arguments → budget.
320
387
  */
321
388
  protected checkActionCircuitBreaker(params: ExecuteAgentParams, action: AgentAction, actionEntity: MJActionEntityExtended, normalizedParams: string): CircuitBreakerActionResult | null;
322
389
  /** The failed {@link ActionResult} a blocked call returns in place of dispatching. */
@@ -388,6 +455,19 @@ export declare class BaseAgent {
388
455
  */
389
456
  protected static readonly DEFAULT_ABSOLUTE_MAX_ITERATIONS = 5000;
390
457
  private _agentRun;
458
+ /**
459
+ * The prefix of the abort reason the wall-clock guard in {@link Execute} raises when a run
460
+ * outlives `maxExecutionTimeMs`. The guard appends the agent and the budget after it; a reader
461
+ * ({@link CancellationReasonForAbort}) checks the prefix, never the wording after it.
462
+ */
463
+ static readonly AgentTimeoutAbortReason = "Agent execution exceeded maxExecutionTimeMs";
464
+ /**
465
+ * The abort controller that governs the current `Execute` call (the merged timeout/upstream
466
+ * signal). Held so {@link initializeAgentRun} can register it with the watchdog's stop relay:
467
+ * when someone marks this run's row `Cancelled`, the watchdog aborts it and the loop's
468
+ * existing cancellation checks end the run. Null outside an execution.
469
+ */
470
+ private _runAbortController;
391
471
  /**
392
472
  * The task graph this run submitted and is now waiting on, or null.
393
473
  *
@@ -419,6 +499,14 @@ export declare class BaseAgent {
419
499
  */
420
500
  private _feedbackRequestId;
421
501
  private _resolvedStorageAccountId;
502
+ /**
503
+ * Most recent artifactDirective returned by a child or related sub-agent during this run.
504
+ * Preserved as a fallback in {@link finalizeAgentRun} when an orchestrator (e.g. Sage) wraps
505
+ * up a delegated sub-agent's response on the subsequent turn without re-emitting its own
506
+ * artifactDirective.
507
+ * @private
508
+ */
509
+ private _lastSubAgentArtifactDirective;
422
510
  /**
423
511
  * The resolved FileStorageAccount ID for this agent run. Set during Execute()
424
512
  * via the hierarchical resolution chain (Runtime → Agent → Category → Type → fallback).
@@ -653,6 +741,11 @@ export declare class BaseAgent {
653
741
  * @since 2.46.0
654
742
  */
655
743
  private _scratchpadManager;
744
+ /**
745
+ * Protected accessor for the run's scratchpad manager.
746
+ * @protected
747
+ */
748
+ protected get scratchpadManager(): ScratchpadManager;
656
749
  /**
657
750
  * Manages artifact tools for the current agent run.
658
751
  * Allows agents to explore input artifacts on demand.
@@ -677,6 +770,11 @@ export declare class BaseAgent {
677
770
  * Armed only when the run has a conversationId (the cross-turn context gate).
678
771
  */
679
772
  private _conversationToolManager;
773
+ /**
774
+ * The conversation's branch rows for the current run, loaded once when the run is on a
775
+ * branch (`ExecuteAgentParams.ConversationBranchID`). Empty on the trunk.
776
+ */
777
+ private _conversationBranches;
680
778
  /**
681
779
  * Manages in-flight durable memory writes for the current agent run.
682
780
  * Only consulted when the agent has AllowMemoryWrite enabled.
@@ -805,6 +903,12 @@ export declare class BaseAgent {
805
903
  * prompt execution occurred after them.
806
904
  */
807
905
  private _promptTurnCount;
906
+ /**
907
+ * The non-volatile stack the previous Prompt step of the current run recorded: each message's
908
+ * reference and its serialized form. A later Prompt step records only a delta when its stack
909
+ * extends this one append-only; otherwise it records the full stack.
910
+ */
911
+ private _lastRecordedPromptStack;
808
912
  /**
809
913
  * Per-run config for structurally compressing inline action-result payloads.
810
914
  * Resolved once at run start from the agent-type prompt params (default on);
@@ -891,6 +995,14 @@ export declare class BaseAgent {
891
995
  * @private
892
996
  */
893
997
  private preloadAgentData;
998
+ /**
999
+ * The params a run executes with: `params` itself, or, when the caller did not set
1000
+ * `ExecuteAgentParams.TrustReservedRunData` and `data` carries reserved keys, a copy whose `data` lacks them
1001
+ * (`WithAgentRunDataTrustApplied` in `@memberjunction/ai-core-plus`). {@link Execute} applies it first, so it
1002
+ * holds for every entry point: AgentRunner, the Execute Agent action, MCP, A2A, Runtime Actions, sub-agents.
1003
+ * The removed keys are logged once with the agent and user, never their values.
1004
+ */
1005
+ private withRunDataTrustApplied;
894
1006
  /**
895
1007
  * Executes an AI agent using hierarchical prompt composition.
896
1008
  *
@@ -927,6 +1039,92 @@ export declare class BaseAgent {
927
1039
  */
928
1040
  protected get DefaultAgentTimeoutMS(): number;
929
1041
  Execute<C = any, R = any>(params: ExecuteAgentParams<C>): Promise<ExecuteAgentResult<R>>;
1042
+ /**
1043
+ * Fails the run at its start, before any prompt: marks the already-created AgentRun Failed with the message
1044
+ * (so it never shows as a phantom "running" record) and throws, which {@link Execute} turns into a failure
1045
+ * result. Used by the permission check and the audience check.
1046
+ */
1047
+ private failRunAtStart;
1048
+ /**
1049
+ * The run's audience readers beyond the caller, hydrated once per run and audience: from the per-run state
1050
+ * when it was hydrated from this same `params.Audience`, else validated and loaded now. `{ Error }` names
1051
+ * what makes the audience unusable. `{ Readers: [] }` when the audience adds nobody.
1052
+ */
1053
+ private audienceReadersFor;
1054
+ /**
1055
+ * Validates `params.Audience` ({@link AgentAudienceProblem}) and loads a hydrated user for each reader it adds
1056
+ * beyond the caller ({@link ResolveAudienceUsers}). An ID no user has is refused, never skipped: a skipped
1057
+ * reader would restrict nothing, and the room would see the caller's whole reach.
1058
+ */
1059
+ private resolveRunAudience;
1060
+ /**
1061
+ * Loads the hydrated user (with its `UserRoles`) for each audience ID, from the server's `UserCache`. When an
1062
+ * ID is missing the cache is refreshed once — a user created since it loaded is then found, as MJServer's
1063
+ * authentication does for a user it does not know — and looked up again. Returns the users found; an ID left
1064
+ * out refuses the run. Override to resolve readers from another directory; never build `UserInfo` by hand.
1065
+ *
1066
+ * An inactive user is accepted as a reader, deliberately: a reader can only narrow what the run shows (each one is
1067
+ * another permission check every result must pass), never widen it, so a deactivated participant still listed in
1068
+ * the room restricts the run rather than failing it.
1069
+ *
1070
+ * @param ids The reader IDs the audience adds beyond the caller (normalized, distinct).
1071
+ * @param params The run's parameters (for the request-scoped provider the refresh reads through).
1072
+ */
1073
+ protected ResolveAudienceUsers(ids: string[], params: ExecuteAgentParams): Promise<UserInfo[]>;
1074
+ /**
1075
+ * Whether this run's audience adds a reader beyond the caller — the condition every audience gate asks.
1076
+ * A malformed audience counts as adding one (the run fails before the gates are reached anyway).
1077
+ */
1078
+ private runAudienceAddsReader;
1079
+ /**
1080
+ * Why this run is not offered task graphs and refuses one the model writes, or null when it may use them — the one
1081
+ * predicate, so every condition that withholds graphs is added in one place. A graph runs outside the run: its
1082
+ * action nodes are dispatched by the task-graph runner (MJServer's `TaskGraphActionRunner`) with no `Audience`,
1083
+ * no `RunScope` and no run `Context`, outside {@link ExecuteSingleAction}, and an agent node starts a run
1084
+ * (`TaskGraphAgentRunner`) that carries neither the audience nor the scope. So graphs are withheld when the
1085
+ * audience adds a reader, and when the run's validated scope carries a tenant or a secondary dimension
1086
+ * (`ActionRunScopeIsBounded`): a model-written Scoped Search node would search outside the run's tenant, and an
1087
+ * agent node would drop it.
1088
+ */
1089
+ private taskGraphWithholdingReason;
1090
+ /** Whether this run withholds task graphs ({@link taskGraphWithholdingReason}). */
1091
+ private runWithholdsTaskGraphs;
1092
+ /**
1093
+ * The `Failed` step for a task graph the model wrote although this run withholds them ({@link taskGraphWithholdingReason}),
1094
+ * or null when graphs are allowed. The response type already hides `tasks`; this is the gate for a model that emits one
1095
+ * anyway. Written before any step: nothing is submitted.
1096
+ */
1097
+ private taskGraphRefusal;
1098
+ /**
1099
+ * What this run's prompt leaves out: task graphs ({@link taskGraphWithholdingReason}), and — when the audience adds a
1100
+ * reader — the caller's own browser and view (`CallerContext`): client tools run in the caller's browser and what they
1101
+ * return reaches the room, and the app context (`data.appContext`, with its `AdditionalContext`) is the caller's screen.
1102
+ */
1103
+ private promptWithholding;
1104
+ /**
1105
+ * The client-tools and app-context prompt sections ({@link buildClientToolPromptSection}, {@link buildAppContextSection}),
1106
+ * both empty when the caller's context is withheld ({@link promptWithholding}): the prompt then offers no client tool
1107
+ * and none of the caller's app context. {@link executeClientToolsStep} refuses a client-tools step emitted anyway.
1108
+ */
1109
+ private callerContextSections;
1110
+ /**
1111
+ * The `Failed` step for a client-tools step under an audience, or null. Client tools run in the caller's browser and
1112
+ * what they return comes back into a run whose output reaches the room; the prompt does not offer them then
1113
+ * ({@link callerContextSections}), and this refuses a step the model emits anyway, as {@link taskGraphRefusal} does a graph.
1114
+ */
1115
+ private clientToolsRefusal;
1116
+ /** Clears what bounds one run — its validated scope and its hydrated audience — once the run is over. */
1117
+ private clearRunBoundState;
1118
+ /**
1119
+ * A copy of the agent-type prompt params with task graphs withheld (`enableTaskGraphs` off and the `tasks`
1120
+ * response section hidden). A copy, never a write: the input may be the process-wide cached base.
1121
+ */
1122
+ private withoutTaskGraphs;
1123
+ /**
1124
+ * Why a session-driven (realtime / voice / bridge) run is refused, or null. A live session speaks and calls
1125
+ * tools outside the gates that hold a run to its audience, so a run whose audience adds a reader is refused.
1126
+ */
1127
+ private sessionAudienceRefusal;
930
1128
  /**
931
1129
  * Releases this run's PerRun-scoped preloaded-data cache entry. `preloadAgentData()`
932
1130
  * (Phase 2 of `Execute()`) may have populated one keyed by `this._agentRun.ID`; without
@@ -1053,7 +1251,8 @@ export declare class BaseAgent {
1053
1251
  * without provider SDKs or DB metadata.
1054
1252
  *
1055
1253
  * Production resolution: pick the highest-power active model of AIModelType `Realtime`; then
1056
- * pick its highest-priority active vendor whose `DriverClass` has a resolvable API key; then
1254
+ * pick its highest-priority active vendor whose `DriverClass` has a resolvable API key, unless another keyed
1255
+ * vendor matches whether the run will show an avatar better ({@link ChooseRealtimeVendorForAvatar}); then
1057
1256
  * instantiate the driver via the `ClassFactory`. Returns `null` (never throws) if any step
1058
1257
  * can't be satisfied — the caller turns that into a clean FAILED result. (Per-agent realtime
1059
1258
  * model preference can later be wired through the agent's prompt-model config, the same path
@@ -1070,6 +1269,19 @@ export declare class BaseAgent {
1070
1269
  apiName: string;
1071
1270
  driverClass?: string;
1072
1271
  } | null>;
1272
+ /**
1273
+ * Whether a session-driven run will show an avatar: the agent's video setting is on and the run could show one
1274
+ * ({@link RealtimeSessionCanShowAvatar}) — a server-side session, so only when its host publishes the avatar into a
1275
+ * room (`params.data.realtimeAvatarDelivery` `'room'`) and it is not a phone call (`params.data.realtimePhoneCall`).
1276
+ *
1277
+ * @param params The execution parameters.
1278
+ */
1279
+ private realtimeRunShowsAvatar;
1280
+ /**
1281
+ * A vendor's realtime driver on its key, with the model and vendor identifiers a run resolves to; `null` when the
1282
+ * key or the driver is missing.
1283
+ */
1284
+ private instantiateRealtimeRunVendor;
1073
1285
  /**
1074
1286
  * The active `Realtime`-AIModelType models to try, in resolution order — the candidate list
1075
1287
  * {@link resolveRealtimeModel} walks until one yields a usable vendor + key + driver. Returns ALL
@@ -1400,9 +1612,10 @@ export declare class BaseAgent {
1400
1612
  * @param primaryScopeRecordId - Optional primary scope record ID for multi-tenant filtering
1401
1613
  * @param secondaryScopes - Optional secondary scope dimensions for multi-tenant filtering
1402
1614
  * @param secondaryScopeConfig - Optional agent-level scope config for per-dimension inheritance
1615
+ * @param sharedOnly - Inject only shared notes and examples (no `UserID`); set when the run's audience adds a reader
1403
1616
  * @returns Object containing injected notes and examples
1404
1617
  */
1405
- protected InjectContextMemory(input: string, agent: MJAIAgentEntityExtended, userId?: string, companyId?: string, contextUser?: UserInfo, conversationMessages?: ChatMessage[], primaryScopeEntityId?: string, primaryScopeRecordId?: string, secondaryScopes?: Record<string, SecondaryScopeValue>, secondaryScopeConfig?: SecondaryScopeConfig | null): Promise<{
1618
+ protected InjectContextMemory(input: string, agent: MJAIAgentEntityExtended, userId?: string, companyId?: string, contextUser?: UserInfo, conversationMessages?: ChatMessage[], primaryScopeEntityId?: string, primaryScopeRecordId?: string, secondaryScopes?: Record<string, SecondaryScopeValue>, secondaryScopeConfig?: SecondaryScopeConfig | null, sharedOnly?: boolean): Promise<{
1406
1619
  notes: MJAIAgentNoteEntity[];
1407
1620
  examples: MJAIAgentExampleEntity[];
1408
1621
  }>;
@@ -1413,9 +1626,18 @@ export declare class BaseAgent {
1413
1626
  * primary prompt under the run's polymorphic scope (the SAME PrimaryScope/SecondaryScopes the
1414
1627
  * runtime threads for memory), and unshifts the assembled role-tagged messages onto
1415
1628
  * `conversationMessages`. In-memory + synchronous (parts are cached on `AIEngine`). No-op when
1416
- * the agent has no active prompt or no parts resolve for the scope.
1629
+ * the agent has no active prompt or no parts resolve for the scope. System placeholders in the
1630
+ * messages it adds are replaced afterwards ({@link replaceScopedPartPlaceholders}), so an override
1631
+ * gets that too.
1417
1632
  */
1418
1633
  protected InjectScopedPromptParts(agent: MJAIAgentEntityExtended, conversationMessages: ChatMessage[], primaryScopeEntityId?: string, primaryScopeRecordId?: string, secondaryScopes?: Record<string, SecondaryScopeValue>): void;
1634
+ /**
1635
+ * Replace system placeholders such as `{{ _CURRENT_DATE }}` in the messages that
1636
+ * {@link InjectScopedPromptParts} added, meaning every message not in `before`. Part text is not a
1637
+ * template: see {@link SystemPlaceholderManager.ReplaceAvailablePlaceholders} for what resolves.
1638
+ * On failure the parts are kept as written.
1639
+ */
1640
+ private replaceScopedPartPlaceholders;
1419
1641
  /**
1420
1642
  * Inject pre-execution RAG context for this agent using scoped search.
1421
1643
  *
@@ -1439,9 +1661,12 @@ export declare class BaseAgent {
1439
1661
  * @param primaryScopeRecordId - Multi-tenant primary scope record ID.
1440
1662
  * @param secondaryScopes - Multi-tenant secondary scope dimensions.
1441
1663
  * @param payload - The agent's current payload (for template rendering).
1664
+ * @param activeSkillIDs - The skills active for this run; a lone active skill is the search's skill principal.
1665
+ * @param audienceReaders - The run's audience readers beyond the caller (`ExecuteAgentParams.Audience`,
1666
+ * hydrated): each must pass the scope gate, and only results every one of them may read are injected.
1442
1667
  * @returns The structured RAG result, or `null` if no scopes produced results.
1443
1668
  */
1444
- protected InjectPreExecutionRAG(lastUserMessage: string, agent: MJAIAgentEntityExtended, contextUser: UserInfo | undefined, conversationMessages: ChatMessage[] | undefined, originalMessages: ChatMessage[] | undefined, primaryScopeEntityId?: string, primaryScopeRecordId?: string, secondaryScopes?: Record<string, SecondaryScopeValue>, payload?: unknown): Promise<AgentPreExecutionRAGResult | null>;
1669
+ protected InjectPreExecutionRAG(lastUserMessage: string, agent: MJAIAgentEntityExtended, contextUser: UserInfo | undefined, conversationMessages: ChatMessage[] | undefined, originalMessages: ChatMessage[] | undefined, primaryScopeEntityId?: string, primaryScopeRecordId?: string, secondaryScopes?: Record<string, SecondaryScopeValue>, payload?: unknown, activeSkillIDs?: string[], audienceReaders?: UserInfo[]): Promise<AgentPreExecutionRAGResult | null>;
1445
1670
  /**
1446
1671
  * Decision discovery (plan Task 3.1): suggests the agent to delegate to before the first prompt.
1447
1672
  *
@@ -1551,6 +1776,7 @@ export declare class BaseAgent {
1551
1776
  *
1552
1777
  * @param {string} lastRunId - The ID of the last run to check
1553
1778
  * @param {UserInfo} [contextUser] - Optional user context
1779
+ * @param {{ LastRunID?: string | null } | null} [preloadedLastRun] - Optional preloaded row for `lastRunId` (or null when already queried and not found) to avoid a duplicate RunView call
1554
1780
  * @private
1555
1781
  */
1556
1782
  private validateRunChain;
@@ -1817,17 +2043,26 @@ export declare class BaseAgent {
1817
2043
  * when it stays in the system prompt.
1818
2044
  */
1819
2045
  protected resolveRelocatedSpecialization(promptParams: AIPromptParams, childPrompt: MJAIPromptEntityExtended | undefined, agentType: MJAIAgentTypeEntity, contextUser: UserInfo): Promise<string | null>;
2046
+ /**
2047
+ * Per-instance memoization for runtime-state template delivery analysis and template-array indexing
2048
+ * so multi-turn agent loops do not repeatedly scan template collections and strings on every turn.
2049
+ * @private
2050
+ */
2051
+ private _lastRuntimeStateDeliveryCache;
2052
+ private _cachedTemplatesArrayRef;
2053
+ private _templateByIdMap;
2054
+ private _templateEngineConfiguredForRun;
1820
2055
  /**
1821
2056
  * Decides, from the system prompt's UNRENDERED template text, whether the trailing runtime-state
1822
2057
  * fragment belongs on this request:
1823
2058
  *
1824
2059
  * - `'trailing'` — the template carries the `<mj-runtime-state>` pointer, so the model is told where
1825
- * the state lives. The Loop agent system prompt.
2060
+ * the state lives. The Loop and Flow agent system prompts.
1826
2061
  * - `'embedded'` — the template still renders the state blocks itself (an environment whose
1827
- * TemplateContent has not synced the new Loop template, or the Flow template, which embeds the
2062
+ * TemplateContent has not synced the new system template, or a custom template that embeds the
1828
2063
  * payload). Emitting the fragment would deliver the same state twice.
1829
2064
  * - `'unsupported'` — the template has neither. The Harness system prompt, or a custom prompt run
1830
- * without the Loop system prompt. The model would receive an unexplained block.
2065
+ * without a system prompt carrying the pointer. The model would receive an unexplained block.
1831
2066
  * - `'unknown'` — no template text to inspect (no TemplateID, or the lookup failed). The caller
1832
2067
  * fails OPEN here: a Loop agent losing its payload from the model's view is far worse than a
1833
2068
  * non-Loop agent receiving an unexplained fragment, and in practice every agent type's system
@@ -1920,6 +2155,22 @@ export declare class BaseAgent {
1920
2155
  */
1921
2156
  protected getRequestedSubAgents<P, C>(nextStep: BaseAgentNextStep<P, C> | undefined | null): AgentSubAgentRequest<C>[];
1922
2157
  protected validateSubAgentNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2158
+ /**
2159
+ * Builds a compact hint listing the current user's permitted runnable agents when a
2160
+ * task-graph or folded sub-agent step references an unknown or inaccessible agent name.
2161
+ */
2162
+ protected buildAvailableRunnableAgentsHint(contextUser?: UserInfo): string;
2163
+ /**
2164
+ * Validates a `'Tasks'` next step before `executeTasksStep` submits the graph.
2165
+ *
2166
+ * Verifies that every referenced `Agent` (including `ForEach`/`While` loop sub-agents) is
2167
+ * active and runnable by `params.contextUser`, and that every referenced `Action` is active.
2168
+ * When an agent or action name is unknown or inaccessible, converts the step to a self-correcting
2169
+ * `Retry` with the user's permitted runnable agent list instead of letting `TaskGraphService.Submit`
2170
+ * terminate the entire agent run as `Failed`. Never reveals whether an invalid agent name was
2171
+ * nonexistent versus restricted by permissions.
2172
+ */
2173
+ protected validateTasksNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, _currentPayload: P, _agentRun: MJAIAgentRunEntityExtended, _currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
1923
2174
  /**
1924
2175
  * Validates that the actions next step is valid and can be executed by the current agent. Subclasses can override
1925
2176
  * this method to implement custom validation logic if needed.
@@ -2046,6 +2297,58 @@ export declare class BaseAgent {
2046
2297
  current?: number;
2047
2298
  reason?: string;
2048
2299
  }>;
2300
+ /**
2301
+ * Ensures that a shared {@link AgentTreeBudget} instance exists for the current execution tree
2302
+ * and is attached to both `this._treeBudget` and `params.treeBudget`.
2303
+ *
2304
+ * - When `params.treeBudget` is already provided (for example, propagated by a parent agent
2305
+ * in {@link ExecuteSubAgent} or supplied directly by a caller), that exact object reference
2306
+ * is reused so all root, sequential child, and parallel child runs mutate the same shared
2307
+ * counters (`totalSteps`, `totalTokens`, `totalCost`, `startedAtMs`, `breachedReason`).
2308
+ * - When `params.treeBudget` is absent (root run), a new {@link AgentTreeBudget} is created
2309
+ * and seeded with any top-level convenience ceilings (`maxTreeSteps`, `maxTreeTokens`,
2310
+ * `maxTreeCost`, `maxTreeDurationMs`) declared on `params`.
2311
+ *
2312
+ * @param params - Optional execution parameters for the current run.
2313
+ * @returns The shared {@link AgentTreeBudget} instance for the execution tree.
2314
+ * @protected
2315
+ */
2316
+ protected ensureTreeBudget(params?: ExecuteAgentParams): AgentTreeBudget;
2317
+ /**
2318
+ * Accumulates token and cost usage from a completed prompt execution into the shared
2319
+ * {@link AgentTreeBudget} for the execution tree.
2320
+ *
2321
+ * Prefers rollup figures on `promptRun` (`TokensUsedRollup` / `TokensPromptRollup` +
2322
+ * `TokensCompletionRollup` and `TotalCost`) so hierarchical child prompts are counted,
2323
+ * falling back to direct `promptRun` columns (`TokensUsed` / `TokensPrompt` + `TokensCompletion`
2324
+ * and `Cost`) or the `AIPromptRunResult` summary fields when `promptRun` is not populated.
2325
+ *
2326
+ * @param promptRun - The persisted or in-memory `MJAIPromptRunEntity` from the prompt execution, if any.
2327
+ * @param promptResult - Optional `AIPromptRunResult` carrying direct token/cost metrics.
2328
+ * @param params - Optional execution parameters for the current run.
2329
+ * @protected
2330
+ */
2331
+ protected recordPromptUsageInTreeBudget(promptRun?: MJAIPromptRunEntity | null, promptResult?: AIPromptRunResult<unknown>, params?: ExecuteAgentParams): void;
2332
+ /**
2333
+ * Evaluates whether any root-tree cumulative budget ceiling (`maxTreeSteps`, `maxTreeTokens`,
2334
+ * `maxTreeCost`, `maxTreeDurationMs`) on the shared {@link AgentTreeBudget} has been reached
2335
+ * or exceeded.
2336
+ *
2337
+ * When a ceiling is breached, sets `budget.breachedReason` with a descriptive diagnostic
2338
+ * message so both the breaching agent and any ancestor agents in the call tree can terminate
2339
+ * immediately with `step: 'Failed'` and `terminate: true`.
2340
+ *
2341
+ * @param params - Optional execution parameters for the current run.
2342
+ * @returns Guardrail evaluation result indicating whether a tree budget limit was exceeded.
2343
+ * @protected
2344
+ */
2345
+ protected checkTreeBudgetLimit(params?: ExecuteAgentParams): {
2346
+ exceeded: boolean;
2347
+ type?: 'cost' | 'tokens' | 'iterations' | 'time';
2348
+ limit?: number;
2349
+ current?: number;
2350
+ reason?: string;
2351
+ };
2049
2352
  /**
2050
2353
  * Determines if a prompt execution error is fatal and should stop agent execution.
2051
2354
  * Fatal errors are those that won't be resolved by retrying, such as context length
@@ -2076,7 +2379,8 @@ export declare class BaseAgent {
2076
2379
  };
2077
2380
  /**
2078
2381
  * Converts ChatMessageContent to a string representation.
2079
- * Handles both simple strings and content block arrays.
2382
+ * Handles both simple strings and content block arrays. Text blocks keep their text;
2383
+ * image, audio, video and file blocks become a short stub instead of their base64.
2080
2384
  *
2081
2385
  * @param content - The message content to convert
2082
2386
  * @returns String representation of the content
@@ -2248,10 +2552,184 @@ export declare class BaseAgent {
2248
2552
  *
2249
2553
  * Gated on conversationId + root depth — programmatic runs and sub-agents skip it.
2250
2554
  * Skipped under a history floor (`ConversationHistoryFrom`): the previous run's tool
2251
- * results can quote messages from before the floor.
2555
+ * results can quote messages from before the floor. Skipped under an audience
2556
+ * (`ExecuteAgentParams.Audience`) too: the previous run's results were fetched for
2557
+ * whoever ran it, not for this room.
2252
2558
  * @protected
2253
2559
  */
2254
2560
  protected injectPriorTurnToolResults(params: ExecuteAgentParams): Promise<void>;
2561
+ /**
2562
+ * Carries a STOPPED previous turn's completed results forward into this run's context.
2563
+ *
2564
+ * {@link injectPriorTurnToolResults} covers the normal case: the previous run settled and
2565
+ * its inline tool results ride along one turn. A run the user stopped never settles, so
2566
+ * that path skips it, and the next turn would redo every action the stopped run had already
2567
+ * finished (observed: a stopped Sage run had five weather lookups and fifteen searches done;
2568
+ * "keep going" redid all of them). This path looks at the newest root run for this agent in
2569
+ * the conversation and, when it is one the user stopped, carries it forward per
2570
+ * {@link ExecuteAgentParams.stopContinuationMode}: by default its own message stack is resumed
2571
+ * so the agent picks up where it stopped; in summary mode its completed Actions and Tool results
2572
+ * go in as one transient message that says to continue, not restart. A settled newest run means
2573
+ * the normal path already has the context, so nothing is added here. During execution the two
2574
+ * halves run separately: {@link loadStoppedRunContinuation} in the parallel phase, then
2575
+ * {@link applyStoppedRunContinuation} once it settles.
2576
+ *
2577
+ * Same gates as the sibling: root depth, a conversation, no history floor. Fail-soft.
2578
+ * @protected
2579
+ */
2580
+ protected injectStoppedRunResults(params: ExecuteAgentParams): Promise<void>;
2581
+ /**
2582
+ * The I/O half of {@link injectStoppedRunResults}: finds a user-stopped predecessor and loads its
2583
+ * steps (every step for the full-stack resume, only completed results for the summary). Runs inside
2584
+ * the pre-execution parallel phase; nothing here touches the message list.
2585
+ * @protected
2586
+ */
2587
+ protected loadStoppedRunContinuation(params: ExecuteAgentParams): Promise<StoppedRunContinuation | null>;
2588
+ /**
2589
+ * The message half of {@link injectStoppedRunResults}, applied once the pre-execution phase has
2590
+ * settled so it never races the memory and RAG injections running beside the load.
2591
+ *
2592
+ * Full stack: the stopped run's own turns are spliced in ahead of the user's new message, in the
2593
+ * shape the loop built while running, so the agent resumes where it stopped. When the stack cannot
2594
+ * be resumed (no recorded prompt, or its anchor is missing) this falls back to the summary.
2595
+ * Summary: the completed results go in as one carried-forward message. Fail-soft.
2596
+ * @protected
2597
+ */
2598
+ protected applyStoppedRunContinuation(params: ExecuteAgentParams, continuation: StoppedRunContinuation | null, continuationMessage: ChatMessage | undefined): void;
2599
+ /**
2600
+ * The full-stack half of {@link applyStoppedRunContinuation}: true when the stopped run's turns were
2601
+ * spliced in. Any failure leaves the messages untouched and returns false, so the caller carries
2602
+ * the results as a summary instead of losing them.
2603
+ * @private
2604
+ */
2605
+ private tryResumeStoppedRunStack;
2606
+ /** The mode a run uses when the caller does not set {@link ExecuteAgentParams.stopContinuationMode}. */
2607
+ static readonly DefaultStopContinuationMode: StopContinuationMode;
2608
+ /**
2609
+ * Placed just before the user's new message when a stopped run's stack is resumed, so the model
2610
+ * knows the turns above it were interrupted and what follows is how to continue.
2611
+ */
2612
+ static readonly StoppedRunResumeNotice = "[Note: The user stopped the previous execution at this point. The instruction that follows is the continuation request.]";
2613
+ /** Result code and message for an action the stopped run requested but never ran. */
2614
+ private static readonly stoppedBeforeRunResultCode;
2615
+ private static readonly stoppedBeforeRunMessage;
2616
+ /**
2617
+ * The stopped run's turns in the shape the loop builds, or null when they cannot be recovered.
2618
+ *
2619
+ * The latest prompt step that recorded a full stack holds the run's whole message stack as it went
2620
+ * into that prompt; the prompt steps after it recorded only the messages appended since (see
2621
+ * {@link capturePromptStepMessages}). The first prompt step recorded the stack the run started from
2622
+ * (history plus this run's injections, which the new run adds for itself). The difference is the
2623
+ * run's own turns. If the last prompt completed, its decision and the steps after it are rebuilt
2624
+ * with the loop's own builders.
2625
+ * @protected
2626
+ */
2627
+ protected buildResumedStoppedRunTurns(steps: StoppedRunStackStepRecord[], params: ExecuteAgentParams): AgentChatMessage[] | null;
2628
+ /**
2629
+ * The run's own turns: what follows the run's starting message in its last recorded stack, minus
2630
+ * the per-request runtime-state fragments (the new run appends its own). The starting message is
2631
+ * matched at its original position first, so a repeated message earlier in the history ("keep
2632
+ * going" twice) cannot be mistaken for it. Null when it cannot be found.
2633
+ */
2634
+ static ExtractStoppedRunLoopTurns(firstStack: AgentChatMessage[] | null, lastStack: AgentChatMessage[] | null): AgentChatMessage[] | null;
2635
+ /**
2636
+ * Inserts resumed turns ahead of the user's new message (and ahead of the stopped run's own reply
2637
+ * to the user, when that sits right before it), followed by {@link StoppedRunResumeNotice}. The new
2638
+ * message is found by identity, captured before the pre-execution phase added anything. Returns
2639
+ * false, changing nothing, when it is not a user message still in the list.
2640
+ */
2641
+ static SpliceResumedTurns(messages: ChatMessage[], resumed: AgentChatMessage[], continuationMessage: ChatMessage | undefined): boolean;
2642
+ /**
2643
+ * What the stopped run's last completed prompt decided, rebuilt as the loop would have written it:
2644
+ * the model's native call turn when results go back natively, the invocation record and the results
2645
+ * of the actions that finished (and a not-executed result for the ones that did not) for an Actions
2646
+ * turn, otherwise the completed results as a carried-forward message. Any native call left without
2647
+ * a result is then answered, so the history is valid for every provider.
2648
+ * @protected
2649
+ */
2650
+ protected buildStoppedRunTail(decision: BaseAgentNextStep | null, tailSteps: StoppedRunStackStepRecord[], params: ExecuteAgentParams): AgentChatMessage[];
2651
+ /** One result per requested action, in request order: its completed step's result, or not executed. @private */
2652
+ private summarizeStoppedRunActions;
2653
+ /**
2654
+ * A completed action step as the loop summarizes a live action result: output parameters only,
2655
+ * with large media swapped for placeholders. Null when the step's output cannot be read.
2656
+ * @private
2657
+ */
2658
+ private summarizeStoppedActionStep;
2659
+ /** The message stack a prompt step recorded as its input, or null. @private */
2660
+ private static readPromptStepStack;
2661
+ /** True when a prompt step recorded only the per-turn message delta instead of the full history stack. @private */
2662
+ private static isPromptStepDelta;
2663
+ /** The decision a completed prompt step recorded, or null. @private */
2664
+ private static readPromptStepDecision;
2665
+ /** The action an Actions step ran, from its recorded input, or null. @private */
2666
+ private static readStoppedActionName;
2667
+ /**
2668
+ * A resumed turn re-dated to this run's first turn. The stopped run's turn numbers mean nothing
2669
+ * to this run's counter, and expiry compares the two, so a resumed result ages from now.
2670
+ * @private
2671
+ */
2672
+ private static restampResumedTurn;
2673
+ /** A step whose result the summary carries: a completed, successful Actions or Tool step. @private */
2674
+ private static isCarriedForwardResultStep;
2675
+ /**
2676
+ * A carried-forward results message: a user-role message that expires after two turns and
2677
+ * compacts to its head, so results reused once never compound across the conversation. Shared
2678
+ * by the settled-run and stopped-run carry-forwards so the two cannot age differently.
2679
+ * @private
2680
+ */
2681
+ private buildCarryForwardMessage;
2682
+ /**
2683
+ * The ID of this agent's newest root run on this turn's branch path IF the user stopped it,
2684
+ * else null. One query over the runs that could be the predecessor (settled, or stopped by
2685
+ * the user): the newest decides. A stopped run older than a settled one is history the
2686
+ * settled run already built on, so it is not carried again. The path scopes it the same way
2687
+ * as {@link loadPriorTurnToolResultSteps}: a run stopped on a sibling branch is never resumed.
2688
+ * @private
2689
+ */
2690
+ private findUserStoppedPredecessorRunId;
2691
+ /**
2692
+ * `runId` if that run is one the user stopped, else null. The chained-run counterpart of
2693
+ * {@link findUserStoppedPredecessorRunId}: one primary-key read of the named run instead of a
2694
+ * search of the conversation, so a run the resolver already resolved is not looked up twice,
2695
+ * and a run chained to a settled predecessor (an ordinary continuation) resumes nothing.
2696
+ * @private
2697
+ */
2698
+ private userStoppedRunIdIfStopped;
2699
+ /**
2700
+ * Every step of a stopped run, in step order: the full-stack resume reads the prompt steps'
2701
+ * recorded stacks and which requested actions completed. Read from the database, since the run
2702
+ * was stopped moments ago.
2703
+ * @private
2704
+ */
2705
+ private loadStoppedRunStack;
2706
+ /** The completed, successful Actions and Tool steps of a stopped run, in step order. @private */
2707
+ private loadStoppedRunResultSteps;
2708
+ /**
2709
+ * Budget for the stopped-run carry-forward message. Smaller than a standalone tool result on
2710
+ * purpose: this rides at the front of a continuation turn's context, and a stopped run can
2711
+ * hold dozens of search results. ~7k tokens keeps the useful values and drops the long tails.
2712
+ */
2713
+ protected static readonly maxStoppedRunResultChars = 28000;
2714
+ /**
2715
+ * Renders a stopped run's completed step results into the carried-forward message body.
2716
+ * Pure and static for testability. An Actions step renders as the action call (name and
2717
+ * params) with its output parameters, or its message when it produced none; a Tool step
2718
+ * renders under the same contract as {@link BuildPriorTurnToolResultsMessage}. Failed or
2719
+ * unparseable steps are skipped. Each section is capped at an even share of `maxChars`
2720
+ * (never below a readable floor) and the whole body at `maxChars`, with a note for anything
2721
+ * dropped. Returns null when nothing usable remains.
2722
+ */
2723
+ static BuildStoppedRunResultsMessage(steps: ReadonlyArray<StoppedRunStepRecord>, maxChars: number): string | null;
2724
+ /** One stopped-run step as a result section, or null when it carries nothing reusable. @private */
2725
+ private static renderStoppedRunStep;
2726
+ /**
2727
+ * The `MJ: AI Agent Runs` predicate for this agent's previous settled root run on one
2728
+ * branch path: the run's reply row must be on that path, so a run made on a sibling
2729
+ * branch is never carried forward, and not replaced by a rerun of its turn, so a replaced
2730
+ * answer's tool results are never carried forward.
2731
+ */
2732
+ static BuildPriorTurnRunFilter(conversationId: string, agentId: string, branchId: string | null, branches: ReadonlyArray<ConversationBranchRow>, statusList: string): string;
2255
2733
  /**
2256
2734
  * Loads this agent's previous settled root run's Tool steps for this conversation
2257
2735
  * (settled = {@link settledRunStatuses}: Completed or AwaitingFeedback).
@@ -2274,9 +2752,11 @@ export declare class BaseAgent {
2274
2752
  * only when the run row settled as {@link settledRunStatuses} (Completed OR
2275
2753
  * AwaitingFeedback — the normal chat-turn ending) — a failed run leaves the previous
2276
2754
  * settled run's entry standing, just as the RunView filter would. Scoped to this
2277
- * run's agent (cache key = conversation + agent) so parallel agents in one
2278
- * conversation never cross-pollinate. An empty projection is cached too (the
2279
- * negative-cache case that spares tool-free conversations the queries every turn).
2755
+ * run's agent and branch (cache key = conversation + agent + branch) so parallel
2756
+ * agents in one conversation, and sibling branches, never cross-pollinate. An empty
2757
+ * projection is cached too (the negative-cache case that spares tool-free
2758
+ * conversations the queries every turn). The run's reply row is stored with the entry,
2759
+ * so the entry is no longer served once a rerun of its turn replaces that row.
2280
2760
  * Same-node edge semantics (failed step INSERTs, concurrent completions) are
2281
2761
  * documented on the cache class. Called from {@link finalizeAgentRun}.
2282
2762
  * @private
@@ -2320,6 +2800,16 @@ export declare class BaseAgent {
2320
2800
  * not here.
2321
2801
  */
2322
2802
  private static readonly carryForwardPredicate;
2803
+ /**
2804
+ * The row predicate for the stopped-run carry-forward's step query: the completed, successful
2805
+ * Actions and Tool steps of the run the user stopped. Declared beside
2806
+ * {@link carryForwardPredicate} for the same reason it is: one place to change what counts.
2807
+ */
2808
+ private static readonly stoppedRunCarryForwardPredicate;
2809
+ /** An action parameter's direction, as the action executor stamps it. */
2810
+ private static readonly actionOutputParamType;
2811
+ /** A stopped-run result section is never cut below this many characters, whatever the budget. */
2812
+ private static readonly minStoppedRunSectionChars;
2323
2813
  /**
2324
2814
  * Display name of the seeded system prompt behind summarizeRange's recursive
2325
2815
  * sub-call (see metadata/prompts/.summarize-range-prompt.json). Resolved with a
@@ -2427,15 +2917,39 @@ export declare class BaseAgent {
2427
2917
  protected executeMemoryWritesAsSteps(writes: MemoryWriteRequest[], params: ExecuteAgentParams): Promise<MemoryWriteResult[]>;
2428
2918
  /**
2429
2919
  * Turn-loop entry point for in-flight memory writes, gated on the agent's
2430
- * AllowMemoryWrite flag. When disabled but the LLM emitted writes anyway
2431
- * (prompt drift / injection attempt), records ONE summary skip step —
2432
- * observable without per-write noise — and tells the agent the memories
2433
- * were NOT saved so it stops re-emitting. When enabled, executes the
2920
+ * AllowMemoryWrite flag and on the run's audience ({@link memoryWriteSkip}).
2921
+ * When refused but the LLM emitted writes anyway (prompt drift / injection
2922
+ * attempt), records ONE summary skip step and tells the agent the memories
2923
+ * were NOT saved ({@link skipMemoryWrites}). Otherwise executes the
2434
2924
  * writes as run steps and injects the results message.
2435
2925
  *
2436
2926
  * @protected
2437
2927
  */
2438
2928
  protected processMemoryWritesForTurn(memoryWrites: MemoryWriteRequest[], params: ExecuteAgentParams): Promise<void>;
2929
+ /**
2930
+ * Determines whether artifact creation/lifecycle support (`artifactDirective`) is enabled for
2931
+ * the given agent so the Loop Agent system prompt includes `artifactDirective` and its lifecycle
2932
+ * instructions only when relevant.
2933
+ *
2934
+ * Returns `true` when:
2935
+ * - `agent.ArtifactCreationMode` is not `'Never'`, OR
2936
+ * - Conversation artifacts are already loaded in `_artifactToolManager`, OR
2937
+ * - The agent is an embedded sub-agent (`agent.ParentID`) whose parent agent creates artifacts
2938
+ * (`parentAgent.ArtifactCreationMode === 'Always'`) and relies on the sub-agent's payload/directive.
2939
+ */
2940
+ protected isArtifactSupportEnabled(agent: MJAIAgentEntityExtended): boolean;
2941
+ /**
2942
+ * Why this run saves no memory writes, or null when it may: the agent has not opted in (`AllowMemoryWrite`), or the
2943
+ * run's audience adds a reader. A write is the caller's note, and its reply — saved, superseded, "already exists
2944
+ * verbatim" — is read against the caller's own notes, so in a shared conversation it would tell the room what the
2945
+ * caller has noted. The memory-writes docs are left out of the prompt for the same reasons.
2946
+ */
2947
+ private memoryWriteSkip;
2948
+ /**
2949
+ * Records ONE summary skip step for a turn's refused memory writes — observable without per-write noise — and tells
2950
+ * the agent the memories were NOT saved, so it stops re-emitting them.
2951
+ */
2952
+ private skipMemoryWrites;
2439
2953
  /**
2440
2954
  * Pushes a single user-role message containing memory-write outcomes into
2441
2955
  * the conversation, mirroring `injectArtifactToolResultsMessage`'s
@@ -2659,6 +3173,7 @@ export declare class BaseAgent {
2659
3173
  * @param {UserInfo} [_contextUser] - Optional user context (reserved for future use)
2660
3174
  * @param {any} [extraData] - Optional extra data to include in the context, if provided and keys conflict within the agent context data, the extraData will override the agent context data.
2661
3175
  * @param {ActionChange[]} [actionChanges] - Optional runtime action modifications
3176
+ * @param {PromptWithholding} [withholding] - What this run's prompt leaves out (see `promptWithholding`)
2662
3177
  *
2663
3178
  * @returns {Promise<AgentContextData>} Structured context data for prompts
2664
3179
  *
@@ -2929,6 +3444,41 @@ export declare class BaseAgent {
2929
3444
  * class (never the key), so a run's log shows which action drew which credential.
2930
3445
  */
2931
3446
  private buildRuntimeAPIKeyResolver;
3447
+ /** The model's arguments as the engine's input parameters. */
3448
+ private toEngineActionParams;
3449
+ /**
3450
+ * The action context for one dispatch: the agent's own context object, by reference (do NOT spread —
3451
+ * spreading destroys class instances, losing getters/methods on typed contexts like SkipAgentContext),
3452
+ * stamped with the calling agent's identity, the run's active skills and its resolved storage account.
3453
+ */
3454
+ private stampActionContext;
3455
+ /**
3456
+ * The run's bounds handed to ONE action dispatch, beside its parameters. Per dispatch on purpose: the action
3457
+ * context IS params.context, shared by every action in the run (parallel ones included) and copied into
3458
+ * sub-agent runs, so anything stamped there would name the wrong action under parallel dispatch and travel
3459
+ * further than the action it was meant for. The model sets none of these.
3460
+ */
3461
+ private runBoundDispatchParams;
3462
+ /**
3463
+ * The audience readers for one dispatch: everyone who will see the result besides the user the action RUNS AS
3464
+ * ({@link ExecuteSingleAction}'s `contextUser`), which need not be the run's caller. The run's readers leave the
3465
+ * caller out; when the action runs as someone else, the caller sees its result too and is added, and the user it
3466
+ * runs as is left out (as the engine does). A run whose audience adds no reader stays without one.
3467
+ */
3468
+ private dispatchReaders;
3469
+ /**
3470
+ * The scope an action dispatch is handed: the run's, as {@link initializeAgentRun} validated and recorded it,
3471
+ * or — when {@link ExecuteSingleAction} is called outside {@link Execute} (the realtime tool path, tests,
3472
+ * harnesses) — resolved from these params the same way ({@link validatedRunScope}). A copy each time, so an
3473
+ * action cannot change what the next one sees.
3474
+ */
3475
+ private runScopeFor;
3476
+ /**
3477
+ * Logs one dispatched call's outcome and feeds the run-scoped circuit breaker, unless the caller does its own
3478
+ * failure accounting (`skipCircuitBreaker`). An `AUDIENCE_UNSUPPORTED` refusal locks the action out for the
3479
+ * run: no argument changes it, and the model is told the action is unavailable rather than to retry.
3480
+ */
3481
+ private recordDispatchOutcome;
2932
3482
  /**
2933
3483
  * This method executes one action using the MemberJunction Actions framework.
2934
3484
  * The full ActionResult objects are returned, allowing the caller to access result codes, output parameters,
@@ -2945,6 +3495,12 @@ export declare class BaseAgent {
2945
3495
  * @throws {Error} If the action fails to execute
2946
3496
  */
2947
3497
  ExecuteSingleAction(params: ExecuteAgentParams, action: AgentAction, actionEntity: MJActionEntityExtended, contextUser?: UserInfo, options?: ExecuteSingleActionOptions): Promise<ActionResult>;
3498
+ /**
3499
+ * Checks per-(Agent, User) action policy narrowing rules (`MJ: AI Agent User Policies`)
3500
+ * before dispatching an action. Returns a synthetic ActionResult when the action is denied,
3501
+ * deferred outside a configured time window, or requires explicit user approval.
3502
+ */
3503
+ protected checkUserActionPolicy(params: ExecuteAgentParams, action: AgentAction, actionEntity: MJActionEntityExtended, contextUser?: UserInfo): ActionResult | null;
2948
3504
  /**
2949
3505
  * Makes a SLICED conversation window safe to send on its own.
2950
3506
  *
@@ -3021,6 +3577,18 @@ export declare class BaseAgent {
3021
3577
  * ```
3022
3578
  */
3023
3579
  protected ExecuteSubAgent<SC = any, SR = any>(params: ExecuteAgentParams<SC>, subAgentRequest: AgentSubAgentRequest<SC>, subAgent: MJAIAgentEntityExtended, stepEntity: MJAIAgentRunStepEntityExtended, payload?: SR, contextMessage?: ChatMessage, stepCount?: number): Promise<ExecuteAgentResult<SR>>;
3580
+ /**
3581
+ * A sub-agent request's template parameters without the host-only run-data keys
3582
+ * (`HOST_ONLY_AGENT_RUN_DATA_KEYS` in `@memberjunction/ai-core-plus`: the reserved scope family and
3583
+ * `__agentTypePromptParams`, and the browser, conversation and realtime controls — `clientTools`, `sessionID`,
3584
+ * `appContext`, `applicationId`, `conversationId`, `targetAgentID`, `agentSessionId`, `recording`, `realtime*`).
3585
+ * They are merged into the child's `data`, which `BaseAgent` reads for all of these, and inside a Loop agent they
3586
+ * are written by the model — so left in, a model could set a sub-agent's tenant (whenever the parent's run trusts
3587
+ * its `data`), offer it client tools, inject an app context, or point it at another conversation. The child
3588
+ * inherits the parent's values instead (its own params, and the parent's `data` as is). What was removed is
3589
+ * logged once, by key only — never the values.
3590
+ */
3591
+ private subAgentTemplateParameters;
3024
3592
  /**
3025
3593
  * Formats sub-agent details as compact markdown for inclusion in prompt context.
3026
3594
  *
@@ -3091,6 +3659,19 @@ export declare class BaseAgent {
3091
3659
  * @private
3092
3660
  */
3093
3661
  private formatActionParameter;
3662
+ /**
3663
+ * The `user`-role record of what the model asked to run on an Actions turn ("[You invoked ...]").
3664
+ * Shared by the live Actions step and the stopped-run resume, so a resumed turn reads exactly
3665
+ * like one the loop wrote. See the Actions step for why it is a user-role annotation.
3666
+ * @protected
3667
+ */
3668
+ protected buildActionInvocationMessage(actions: AgentAction[]): string;
3669
+ /**
3670
+ * The action-results message body: a header naming any failures, then each result in the
3671
+ * compact markdown shape. Shared by the live Actions step and the stopped-run resume.
3672
+ * @protected
3673
+ */
3674
+ protected buildActionResultsMessage(actionSummaries: ActionResultSummary[]): string;
3094
3675
  /**
3095
3676
  * Formats an array of action result summaries as compact markdown instead of
3096
3677
  * pretty-printed JSON. This typically saves 60-70 % of the tokens that the
@@ -3242,6 +3823,12 @@ export declare class BaseAgent {
3242
3823
  * @private
3243
3824
  */
3244
3825
  private getActionCategoryName;
3826
+ /**
3827
+ * Throws unless `lastRunId` is absent or a UUID. The value can come from a client, and the run
3828
+ * initialization places it in `ExtraFilter` clauses (the payload lookup, {@link validateRunChain}
3829
+ * and {@link resolvePlanModeGate}).
3830
+ */
3831
+ private assertLastRunIdIsUUID;
3245
3832
  /**
3246
3833
  * Initializes the agent run tracking by creating MJAIAgentRunEntityExtended and setting up context.
3247
3834
  *
@@ -3333,20 +3920,77 @@ export declare class BaseAgent {
3333
3920
  };
3334
3921
  }): Promise<MJAIAgentRunStepEntityExtended>;
3335
3922
  /**
3336
- * Finalizes a step entity with completion status.
3923
+ * Finds the step whose `PayloadAtEnd` a new step's start payload repeats, so the new step stores a
3924
+ * pointer to it (`PayloadAtStartSourceStepID`) instead of a second copy. Call it before the new step
3925
+ * is added to the run's `Steps`.
3337
3926
  *
3338
- * @private
3339
- * @param {MJAIAgentRunStepEntityExtended} stepEntity - The step entity to finalize
3340
- * @param {boolean} success - Whether the step was successful
3341
- * @param {string} [errorMessage] - Optional error message
3342
- * @param {any} [outputData] - Optional output data to capture for this step
3927
+ * The candidate is the latest step in the run that is not `Running` and has a `PayloadAtEnd` (or
3928
+ * `PayloadAtEndSourceStepID`). Only that step is compared. If that step itself points to an earlier
3929
+ * step via `PayloadAtEndSourceStepID`, the pointer resolves in one hop to the step that actually
3930
+ * holds the stored `PayloadAtEnd`.
3931
+ * - Running steps are skipped because their end can still change: parallel sub-agent siblings write
3932
+ * their own result as `PayloadAtEnd` when they finish, and a ForEach step writes its end after all
3933
+ * of its child steps.
3934
+ * - Finished steps with no end (tool, compaction and finish-check steps) are skipped because they never
3935
+ * get one, and would hide the step that produced the payload.
3936
+ * - If the matching candidate's INSERT is still in flight (`!step.IsSaved`), {@link createStepEntity}
3937
+ * chains the new step's INSERT after `step` on {@link _stepSaveQueue} (and falls back to storing inline
3938
+ * `PayloadAtStart` if the candidate's INSERT fails) so `FK_AIAgentRunStep_PayloadAtStartSourceStepID`
3939
+ * is always satisfied without sacrificing deduplication on fast back-to-back turns.
3940
+ *
3941
+ * Rule: a step's `PayloadAtEnd` must not change after a later step points at it, because readers take
3942
+ * the pointing step's start payload from it. The comparison uses the in-memory end, so the saved end
3943
+ * must match it: `finalizeStepEntity` re-applies the end after the INSERT lands, and an end set after
3944
+ * `finalizeStepEntity` is saved with `queueStepSave`.
3945
+ *
3946
+ * @param serializedStart The new step's start payload, already serialized.
3947
+ * @returns The step to point at, or undefined when the start payload must be stored.
3948
+ */
3949
+ private findPayloadAtStartSource;
3950
+ /**
3951
+ * Finds the earlier step whose stored `PayloadAtEnd` this step's end payload repeats, so the step
3952
+ * stores a one-hop pointer (`PayloadAtEndSourceStepID`) instead of a second copy.
3953
+ */
3954
+ private findPayloadAtEndSource;
3955
+ private findPayloadEndSourceBefore;
3956
+ /**
3957
+ * Returns true when neither `serializePayloadAtStart` nor `serializePayloadAtEnd` has been
3958
+ * overridden by a subclass, allowing unchanged start payloads to be reused as end payloads
3959
+ * without a second `JSON.stringify` pass.
3960
+ */
3961
+ private hasDefaultPayloadSerializers;
3962
+ /**
3963
+ * Resolves a step's start payload from its own `PayloadAtStart` or the step referenced by
3964
+ * `PayloadAtStartSourceStepID`.
3343
3965
  */
3966
+ private resolveStepPayloadAtStart;
3967
+ /**
3968
+ * Resolves a step's end payload from its own `PayloadAtEnd` or the step referenced by
3969
+ * `PayloadAtEndSourceStepID`.
3970
+ */
3971
+ private resolveStepPayloadAtEnd;
3344
3972
  /**
3345
3973
  * Builds a summary of payload change results for storage
3346
3974
  * @param changeResult The result from PayloadManager operations
3347
3975
  * @returns A serializable summary object
3348
3976
  */
3349
3977
  private buildPayloadChangeResultSummary;
3978
+ /**
3979
+ * Captures the conversation messages for a `Prompt` step's `InputData` without
3980
+ * persisting volatile `<mj-runtime-state>` envelopes or repeating messages already
3981
+ * recorded in an earlier `Prompt` step of the current run.
3982
+ *
3983
+ * - When the non-volatile stack extends the previous Prompt step's recorded stack append-only (the
3984
+ * same messages, unchanged, at the same positions), only the appended messages are stored, tagged
3985
+ * with `conversationMessagesDelta: true`.
3986
+ * - Otherwise (the first Prompt step of the run, or a message was replaced, removed or changed by
3987
+ * expiry, compaction or expansion) the full non-volatile stack is stored, with no delta flag.
3988
+ *
3989
+ * {@link buildResumedStoppedRunTurns} rebuilds the stack from the latest full stack plus the deltas after it.
3990
+ */
3991
+ private capturePromptStepMessages;
3992
+ /** True when `current` starts with every message of `previous`, by reference and unchanged in place. @private */
3993
+ private static isAppendOnlyExtension;
3350
3994
  /**
3351
3995
  * Finalizes a step entity with completion status. Pairs with `createStepEntity`
3352
3996
  * — drivers that create custom steps should also finalize them through this
@@ -3354,6 +3998,9 @@ export declare class BaseAgent {
3354
3998
  * populated consistently and the UPDATE is sequenced behind the INSERT via
3355
3999
  * `queueStepSave`.
3356
4000
  *
4001
+ * Set `PayloadAtEnd` before calling it: the queued UPDATE re-applies the end the step has now.
4002
+ * An end set later must be saved with `queueStepSave`.
4003
+ *
3357
4004
  * @protected
3358
4005
  */
3359
4006
  protected finalizeStepEntity(stepEntity: MJAIAgentRunStepEntityExtended, success: boolean, errorMessage?: string, outputData?: any): Promise<void>;
@@ -3396,6 +4043,29 @@ export declare class BaseAgent {
3396
4043
  * @returns {string} - The formatted message with hierarchy breadcrumb
3397
4044
  */
3398
4045
  protected formatHierarchicalMessage(baseMessage: string): string;
4046
+ /**
4047
+ * Builds the user-oriented initialization progress message for an agent run.
4048
+ *
4049
+ * - Root agent (`_depth === 0`): `'Getting ready...'`
4050
+ * - Direct sub-agent (`_depth === 1`): `'Starting <SubAgentName>...'`
4051
+ * - Nested sub-agent (`_depth > 1`): `'<ParentBreadcrumb>: Starting <SubAgentName>...'`
4052
+ *
4053
+ * @protected
4054
+ * @param {ExecuteAgentParams} params - Execution parameters for the current agent
4055
+ * @returns {string} Formatted initialization progress message
4056
+ */
4057
+ protected buildInitializationProgressMessage(params: ExecuteAgentParams): string;
4058
+ /**
4059
+ * Builds a user-oriented progress message for a prompt execution step without
4060
+ * exposing internal framework terminology ("initial prompt", "payload", "context")
4061
+ * or duplicating the sub-agent name when prefixed by {@link formatHierarchicalMessage}.
4062
+ *
4063
+ * @protected
4064
+ * @param {ExecuteAgentParams} params - Execution parameters for the current agent
4065
+ * @param {BaseAgentNextStep | null} [previousDecision] - Previous step decision when re-prompting
4066
+ * @returns {string} Base progress message (before `formatHierarchicalMessage` breadcrumb prefixing)
4067
+ */
4068
+ protected buildPromptProgressMessage(params: ExecuteAgentParams, previousDecision?: BaseAgentNextStep | null): string;
3399
4069
  /**
3400
4070
  * Trims a step name to what `AIAgentRunStep.StepName` can hold. Step names are built from free
3401
4071
  * text — a termination message quoting a provider's error, a tool name with its arguments, the
@@ -3502,6 +4172,14 @@ export declare class BaseAgent {
3502
4172
  * @param subAgentPayloadOverride - Optional payload override for sub-agent execution, if provided the normal payload computation is skipped
3503
4173
  */
3504
4174
  private executeChildSubAgentStep;
4175
+ /**
4176
+ * Extracts the workflow root task ID (`parentTaskID`) from a sub-agent run that parked on a
4177
+ * durable task graph (`Status === 'Paused'`), falling back to the sub-agent run ID so the
4178
+ * parent run's `_awaitingWorkflowTaskID` is guaranteed non-null when parking.
4179
+ *
4180
+ * @protected
4181
+ */
4182
+ protected extractSubAgentWorkflowTaskID(subAgentRun: MJAIAgentRunEntityExtended | undefined): string;
3505
4183
  /**
3506
4184
  * Routes sub-agent execution to the appropriate handler based on relationship type.
3507
4185
  * Child agents (ParentID) use direct payload coupling.
@@ -3526,7 +4204,7 @@ export declare class BaseAgent {
3526
4204
  *
3527
4205
  * @protected
3528
4206
  */
3529
- protected resolveSubAgentByName(params: ExecuteAgentParams, name: string): {
4207
+ protected resolveSubAgentByName(params: ExecuteAgentParams, name: string, allowAnyActiveAgent?: boolean): {
3530
4208
  subAgentEntity: MJAIAgentEntityExtended;
3531
4209
  relationship?: MJAIAgentRelationshipEntity;
3532
4210
  } | undefined;
@@ -3760,16 +4438,15 @@ export declare class BaseAgent {
3760
4438
  *
3761
4439
  * @private
3762
4440
  */
4441
+ /** The assistant message describing a client-tools step's invocations. */
4442
+ private describeClientToolInvocations;
3763
4443
  /**
3764
4444
  * Execute client-side tools requested by the agent.
3765
4445
  * Sends each tool invocation via PubSub, awaits the client's response
3766
4446
  * (or timeout), then adds results to the conversation and continues.
4447
+ * Refused under an audience ({@link clientToolsRefusal}).
3767
4448
  */
3768
4449
  private executeClientToolsStep;
3769
- /**
3770
- * Format client tool results as a compact markdown summary for the conversation.
3771
- */
3772
- private formatClientToolResultsAsMarkdown;
3773
4450
  /**
3774
4451
  * Executes a 'Skill' next step: activates one or more skills the LLM requested by name.
3775
4452
  * Activating a skill (1) appends its full `Instructions` to the conversation so they take
@@ -4051,6 +4728,15 @@ export declare class BaseAgent {
4051
4728
  */
4052
4729
  protected buildPlanApprovalForm(planText: string): AgentResponseForm;
4053
4730
  private executeChatStep;
4731
+ /**
4732
+ * Raises the persistent `MJ: AI Agent Requests` row for a root agent's Chat or Plan step ({@link createFeedbackRequest}),
4733
+ * so it can be answered outside the conversation — except when the run's audience adds a reader. A request answered
4734
+ * on the dashboard or through the API resumes the run (`MJAIAgentRequestEntityServer.resumeAgent`) as the responder,
4735
+ * in the original conversation, with no audience: neither the request nor the run row has a field that can carry
4736
+ * one without a new column. So a shared conversation's run raises none: its question or plan still reaches the room,
4737
+ * which answers in the conversation, where the host starts the next run with the room's audience.
4738
+ */
4739
+ private raiseFeedbackRequest;
4054
4740
  /**
4055
4741
  * Creates a persistent AIAgentRequest row when a Chat step fires.
4056
4742
  * Resolves the target user via the assignment chain:
@@ -4081,12 +4767,10 @@ export declare class BaseAgent {
4081
4767
  /**
4082
4768
  * Resolves the file storage account ID for this agent's file artifacts.
4083
4769
  *
4084
- * Resolution chain (first non-null wins):
4085
- * 1. Runtime override (`params.override?.storageAccountId`)
4086
- * 2. Agent-level (`params.agent.DefaultStorageAccountID`)
4087
- * 3. Category hierarchy — walks up the agent's category tree via `ParentID`
4088
- * 4. Agent Type-level (`agentType.DefaultStorageAccountID`)
4089
- * 5. System fallback — single active storage account, if only one exists
4770
+ * Delegates to {@link AIEngineBase.ResolveAgentStorageAccountID}, the shared golden path:
4771
+ * runtime override (`params.override?.storageAccountId`) → agent → category tree → agent type →
4772
+ * system fallback (the single active account, or the most recently updated one with a
4773
+ * once-per-agent warning when several are active).
4090
4774
  *
4091
4775
  * This method is `protected` so subclasses can override the resolution logic
4092
4776
  * for custom storage routing (e.g., routing by file type or tenant).
@@ -4252,25 +4936,55 @@ export declare class BaseAgent {
4252
4936
  */
4253
4937
  private completeWhileLoop;
4254
4938
  /**
4255
- * Creates a failure result with proper tracking.
4939
+ * Flushes any in-flight `MJAIPromptRunEntityExtended` saves queued on {@link _promptRunner}.
4940
+ * Tolerates lightweight test doubles on `_promptRunner` that may only implement
4941
+ * `WaitForPendingPromptRunSaves` or neither method.
4942
+ *
4943
+ * @private
4944
+ */
4945
+ private flushPromptRunnerSaves;
4946
+ /**
4947
+ * Creates a failure result with proper tracking, draining all queued step and prompt-run saves
4948
+ * before persisting the failed run row so no orphan step or prompt-run writes remain in flight.
4256
4949
  *
4257
4950
  * @private
4258
4951
  */
4259
4952
  private createFailureResult;
4260
4953
  /**
4261
- * Creates a cancelled result.
4954
+ * Creates a cancelled result, draining all queued step and prompt-run saves before persisting
4955
+ * the cancelled run row so no orphan step or prompt-run writes remain in flight.
4262
4956
  *
4263
4957
  * @private
4264
4958
  * @param {string} message - The cancellation message
4265
4959
  * @returns {Promise<ExecuteAgentResult>} The cancelled result
4266
4960
  */
4267
4961
  private createCancelledResult;
4962
+ /**
4963
+ * Maps the reason an abort signal carried to the run's `CancellationReason` value: the
4964
+ * watchdog's stop relay raises {@link AgentRunWatchdog.UserCancelAbortReason} for a row marked
4965
+ * `User Request`; the wall-clock guard's reason starts with {@link AgentTimeoutAbortReason};
4966
+ * anything else (an upstream caller's token, a shutdown) is `System`.
4967
+ */
4968
+ static CancellationReasonForAbort(reason: string | null | undefined): NonNullable<MJAIAgentRunEntityExtended['CancellationReason']>;
4969
+ /**
4970
+ * The payload recorded at the end of the latest step that recorded one, as its serialized
4971
+ * string, or null when no step has. Steps are examined from the highest `StepNumber` down
4972
+ * (array order is spawn order, which a sub-step can interleave).
4973
+ */
4974
+ static LastStepPayload(steps: ReadonlyArray<{
4975
+ ID?: string;
4976
+ StepNumber: number;
4977
+ PayloadAtStart?: string | null;
4978
+ PayloadAtEnd: string | null;
4979
+ PayloadAtStartSourceStepID?: string | null;
4980
+ PayloadAtEndSourceStepID?: string | null;
4981
+ }> | null | undefined): string | null;
4268
4982
  /**
4269
4983
  * Finalizes the agent run with success.
4270
4984
  *
4271
- * @private
4985
+ * @protected
4272
4986
  */
4273
- private finalizeAgentRun;
4987
+ protected finalizeAgentRun<P>(finalStep: BaseAgentNextStep, payload?: P, contextUser?: UserInfo): Promise<ExecuteAgentResult<P>>;
4274
4988
  /**
4275
4989
  * Calculate total token statistics from the agent run's persisted steps.
4276
4990
  *
@@ -4417,6 +5131,50 @@ export declare class BaseAgent {
4417
5131
  * @private
4418
5132
  */
4419
5133
  private applyCompactionToLiveMessages;
5134
+ /**
5135
+ * Executes post-run conversation message pre-compaction, scratchpad pruning, and
5136
+ * asynchronous memory extraction after an agent run completes (`finalizeAgentRun`).
5137
+ *
5138
+ * Shifting compaction and maintenance to the end of `finalizeAgentRun` removes
5139
+ * compaction latency from the next user turn's critical path so subsequent turns
5140
+ * start with a pre-compacted message window.
5141
+ *
5142
+ * ### Lifecycle Phases
5143
+ * 1. **Configuration Resolution**: Reads `params.compactAfterRun` (`boolean | AgentPostRunCompactionConfig`).
5144
+ * When `undefined`, `false`, or `{ enabled: false }`, returns immediately as a no-op.
5145
+ * When `true`, applies defaults `{ enabled: true, messageCountThreshold: 20, extractMemories: true }`.
5146
+ * 2. **Message Window Pre-Compaction**: When `params.conversationMessages.length >= messageCountThreshold`,
5147
+ * compacts older messages in `[1 .. length - preserveRecentCount - 1]` while preserving
5148
+ * the initial goal message (`index 0`) and the most recent messages intact. Delegates to
5149
+ * {@link compactMessage} (and {@link CompactToolResultContent} for native tool turns) so
5150
+ * behavior and expansion metadata (`wasCompacted`, `originalContent`, `canExpand`) are
5151
+ * 100% consistent with mid-run message compaction.
5152
+ * 3. **Scratchpad Pruning**: When `maxScratchpadNotes` is configured, prunes excess low-priority
5153
+ * scratchpad note lines (via {@link ScratchpadManager.PruneNotes}) and completed tasks
5154
+ * (via {@link ScratchpadManager.EnforceTaskLimit}) down to `maxScratchpadNotes`.
5155
+ * 4. **Memory Extraction Trigger**: When `extractMemories !== false` and `agentRun.Success` is `true`,
5156
+ * triggers asynchronous note/example extraction via {@link triggerPostRunMemoryExtraction}.
5157
+ *
5158
+ * Every phase is wrapped in its own `try/catch` block so an error in one phase is logged
5159
+ * via `LogError` without aborting the remaining phases or failing the completed agent run.
5160
+ *
5161
+ * @param params - The execution parameters for the completed agent run
5162
+ * @param agentRun - The finalized `MJAIAgentRunEntityExtended` record
5163
+ * @protected
5164
+ */
5165
+ protected runPostRunCompaction(params: ExecuteAgentParams, agentRun: MJAIAgentRunEntityExtended): Promise<void>;
5166
+ /**
5167
+ * Triggers asynchronous post-run note and example extraction via `MemoryManagerAgent`
5168
+ * when the executing agent has memory injection (`InjectNotes` or `InjectExamples`) enabled.
5169
+ *
5170
+ * No-ops when the executing agent itself is the `MemoryManagerAgent` (preventing recursion)
5171
+ * or when no active `MemoryManagerAgent` is registered in `AIEngine`.
5172
+ *
5173
+ * @param params - The execution parameters for the completed agent run
5174
+ * @param agentRun - The finalized `MJAIAgentRunEntityExtended` record
5175
+ * @protected
5176
+ */
5177
+ protected triggerPostRunMemoryExtraction(params: ExecuteAgentParams, agentRun: MJAIAgentRunEntityExtended): Promise<void>;
4420
5178
  /**
4421
5179
  * Creates an AIAgentRunStep for message compaction operations.
4422
5180
  * Records the compaction attempt with context about the message being compacted.
@@ -4439,7 +5197,7 @@ export declare class BaseAgent {
4439
5197
  */
4440
5198
  protected updateCompactionStep(step: MJAIAgentRunStepEntityExtended, result: AIPromptRunResult<{
4441
5199
  summary: string;
4442
- }>, message: AgentChatMessage, params: ExecuteAgentParams): Promise<void>;
5200
+ }>, message: AgentChatMessage, _params: ExecuteAgentParams): Promise<void>;
4443
5201
  /**
4444
5202
  * Compacts a message using configured compaction mode.
4445
5203
  *
@@ -4582,6 +5340,42 @@ export declare class BaseAgent {
4582
5340
  * for the paths where they differed.
4583
5341
  */
4584
5342
  protected getValueFromPath(obj: unknown, path: string): unknown;
5343
+ /**
5344
+ * The run's scope inputs: the explicit `ExecuteAgentParams` fields, else their `data` fallbacks, which count only
5345
+ * when the caller set `TrustReservedRunData`. {@link Execute} has already cleaned `data`; the rule is applied here
5346
+ * again for {@link ExecuteSingleAction} called outside a run (the realtime tool path, harnesses).
5347
+ */
5348
+ private runScopeInputs;
5349
+ /**
5350
+ * Secondary scopes as the run takes them: a plain object of dimension values, else none. A host assembles them at
5351
+ * runtime (often through `data`), so anything else — a JSON string, an array, a class instance — is not read as
5352
+ * dimensions (its keys would be character indexes or properties); it is logged and the run carries no secondary scope.
5353
+ */
5354
+ private scopeDimensions;
5355
+ /**
5356
+ * The run's scope as memory, retrieval and scoped prompt configuration take it: the scope {@link initializeAgentRun}
5357
+ * validated and wrote to the run row (`_runScope`; resolved the same way, {@link validatedRunScope}, outside a run),
5358
+ * with the primary entity resolved to its ID. One source, so notes and examples, pre-execution RAG, scoped prompt
5359
+ * parts and configs, the run row and every action dispatch see the same tenant and dimensions — trimmed, with the
5360
+ * agent's `ScopeConfig` defaults applied, and never a `data` scope the caller was not trusted to set.
5361
+ */
5362
+ private runScopeForContext;
5363
+ /** The run's scope ({@link runScopeForContext}) in the shape `ApplyScopedPromptConfig` takes. */
5364
+ private scopedPromptConfigScope;
5365
+ /** A scope identifier as text: a non-blank string (trimmed) or a number; anything else is no value. */
5366
+ private scopeText;
5367
+ /**
5368
+ * The run's scope as the run row records it and every action dispatch is handed it: the inputs from
5369
+ * {@link runScopeInputs}, the secondary dimensions validated with the agent's configured defaults applied
5370
+ * ({@link validateAndApplySecondaryScopes}), and `null` for whatever the run does not carry.
5371
+ */
5372
+ private validatedRunScope;
5373
+ /**
5374
+ * Writes the validated run scope onto the run row: the primary entity resolved to its ID (logged when it is
5375
+ * not in metadata), the tenant record ID and the secondary dimensions as JSON. A secondary-only scope on an
5376
+ * agent whose ScopeConfig does not allow one is logged, and still recorded.
5377
+ */
5378
+ private writeRunScope;
4585
5379
  /**
4586
5380
  * Parse the agent's SecondaryScopeConfig from the ScopeConfig field.
4587
5381
  * Returns null if not configured or invalid JSON.