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

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 (161) hide show
  1. package/README.md +154 -7
  2. package/dist/AgentDataPreloader.d.ts +4 -2
  3. package/dist/AgentDataPreloader.d.ts.map +1 -1
  4. package/dist/AgentDataPreloader.js +21 -12
  5. package/dist/AgentDataPreloader.js.map +1 -1
  6. package/dist/AgentRunner.d.ts +61 -6
  7. package/dist/AgentRunner.d.ts.map +1 -1
  8. package/dist/AgentRunner.js +313 -68
  9. package/dist/AgentRunner.js.map +1 -1
  10. package/dist/AgentWakeTriggerService.d.ts +183 -0
  11. package/dist/AgentWakeTriggerService.d.ts.map +1 -0
  12. package/dist/AgentWakeTriggerService.js +478 -0
  13. package/dist/AgentWakeTriggerService.js.map +1 -0
  14. package/dist/ArtifactToolManager.d.ts +12 -3
  15. package/dist/ArtifactToolManager.d.ts.map +1 -1
  16. package/dist/ArtifactToolManager.js +77 -6
  17. package/dist/ArtifactToolManager.js.map +1 -1
  18. package/dist/ClientToolRequestManager.d.ts +11 -1
  19. package/dist/ClientToolRequestManager.d.ts.map +1 -1
  20. package/dist/ClientToolRequestManager.js +19 -6
  21. package/dist/ClientToolRequestManager.js.map +1 -1
  22. package/dist/ConversationToolManager.d.ts +1 -1
  23. package/dist/ConversationToolManager.d.ts.map +1 -1
  24. package/dist/ConversationToolManager.js +10 -4
  25. package/dist/ConversationToolManager.js.map +1 -1
  26. package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
  27. package/dist/MJAIAgentRequestEntityServer.js +20 -0
  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 +38 -6
  45. package/dist/agent-context-injector.d.ts.map +1 -1
  46. package/dist/agent-context-injector.js +72 -20
  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 +14 -5
  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 +227 -29
  55. package/dist/agent-pre-execution-rag.js.map +1 -1
  56. package/dist/agent-run-watchdog.d.ts +23 -8
  57. package/dist/agent-run-watchdog.d.ts.map +1 -1
  58. package/dist/agent-run-watchdog.js +141 -76
  59. package/dist/agent-run-watchdog.js.map +1 -1
  60. package/dist/agent-types/flow-agent-type.d.ts +15 -0
  61. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  62. package/dist/agent-types/flow-agent-type.js +129 -13
  63. package/dist/agent-types/flow-agent-type.js.map +1 -1
  64. package/dist/agent-types/loop-agent-prompt-params.d.ts +6 -2
  65. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  66. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  67. package/dist/agent-types/loop-agent-response-type.d.ts +8 -2
  68. package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
  69. package/dist/agent-types/loop-agent-response-type.js.map +1 -1
  70. package/dist/agent-types/loop-agent-type.d.ts +85 -7
  71. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  72. package/dist/agent-types/loop-agent-type.js +290 -66
  73. package/dist/agent-types/loop-agent-type.js.map +1 -1
  74. package/dist/base-agent.d.ts +809 -38
  75. package/dist/base-agent.d.ts.map +1 -1
  76. package/dist/base-agent.js +3308 -609
  77. package/dist/base-agent.js.map +1 -1
  78. package/dist/bound-action-params.d.ts +57 -0
  79. package/dist/bound-action-params.d.ts.map +1 -0
  80. package/dist/bound-action-params.js +91 -0
  81. package/dist/bound-action-params.js.map +1 -0
  82. package/dist/index.d.ts +9 -0
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +9 -0
  85. package/dist/index.js.map +1 -1
  86. package/dist/memory-cleanup-agent.d.ts.map +1 -1
  87. package/dist/memory-cleanup-agent.js +3 -0
  88. package/dist/memory-cleanup-agent.js.map +1 -1
  89. package/dist/memory-manager-agent.d.ts.map +1 -1
  90. package/dist/memory-manager-agent.js +52 -35
  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/agent-tools.d.ts +64 -0
  101. package/dist/native-tools/agent-tools.d.ts.map +1 -0
  102. package/dist/native-tools/agent-tools.js +23 -0
  103. package/dist/native-tools/agent-tools.js.map +1 -0
  104. package/dist/native-tools/control-tools.d.ts +26 -4
  105. package/dist/native-tools/control-tools.d.ts.map +1 -1
  106. package/dist/native-tools/control-tools.js +114 -42
  107. package/dist/native-tools/control-tools.js.map +1 -1
  108. package/dist/native-tools/framework-tools.d.ts +47 -0
  109. package/dist/native-tools/framework-tools.d.ts.map +1 -0
  110. package/dist/native-tools/framework-tools.js +187 -0
  111. package/dist/native-tools/framework-tools.js.map +1 -0
  112. package/dist/native-tools/json-argument.d.ts +41 -0
  113. package/dist/native-tools/json-argument.d.ts.map +1 -0
  114. package/dist/native-tools/json-argument.js +79 -0
  115. package/dist/native-tools/json-argument.js.map +1 -0
  116. package/dist/native-tools/native-control-config.d.ts +93 -0
  117. package/dist/native-tools/native-control-config.d.ts.map +1 -0
  118. package/dist/native-tools/native-control-config.js +104 -0
  119. package/dist/native-tools/native-control-config.js.map +1 -0
  120. package/dist/native-tools/tool-result-turns.d.ts +41 -8
  121. package/dist/native-tools/tool-result-turns.d.ts.map +1 -1
  122. package/dist/native-tools/tool-result-turns.js +76 -2
  123. package/dist/native-tools/tool-result-turns.js.map +1 -1
  124. package/dist/native-tools/turn-mode.d.ts +8 -0
  125. package/dist/native-tools/turn-mode.d.ts.map +1 -0
  126. package/dist/native-tools/turn-mode.js +14 -0
  127. package/dist/native-tools/turn-mode.js.map +1 -0
  128. package/dist/query-builder-agent.d.ts +33 -5
  129. package/dist/query-builder-agent.d.ts.map +1 -1
  130. package/dist/query-builder-agent.js +137 -30
  131. package/dist/query-builder-agent.js.map +1 -1
  132. package/dist/realtime/bridge-room-transcript-sink.js +1 -0
  133. package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
  134. package/dist/realtime/bridge-session-transcript-sink.js +1 -0
  135. package/dist/realtime/bridge-session-transcript-sink.js.map +1 -1
  136. package/dist/realtime/realtime-client-session-service.d.ts +5 -4
  137. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  138. package/dist/realtime/realtime-client-session-service.js +42 -30
  139. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  140. package/dist/realtime/realtime-coagent-config.d.ts +8 -1
  141. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  142. package/dist/realtime/realtime-coagent-config.js +17 -1
  143. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  144. package/dist/realtime/realtime-recording-ledger.d.ts +150 -0
  145. package/dist/realtime/realtime-recording-ledger.d.ts.map +1 -0
  146. package/dist/realtime/realtime-recording-ledger.js +206 -0
  147. package/dist/realtime/realtime-recording-ledger.js.map +1 -0
  148. package/dist/realtime/realtime-recording-opus-assembly.d.ts +211 -0
  149. package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -0
  150. package/dist/realtime/realtime-recording-opus-assembly.js +706 -0
  151. package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -0
  152. package/dist/realtime/realtime-recording-store.d.ts +44 -6
  153. package/dist/realtime/realtime-recording-store.d.ts.map +1 -1
  154. package/dist/realtime/realtime-recording-store.js +105 -51
  155. package/dist/realtime/realtime-recording-store.js.map +1 -1
  156. package/dist/realtime/realtime-turn-moderator.d.ts +2 -1
  157. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  158. package/dist/realtime/realtime-turn-moderator.js +7 -1
  159. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  160. package/dist/volatile-child-prompt.js +3 -3
  161. package/package.json +21 -19
@@ -10,8 +10,11 @@
10
10
  * @author MemberJunction.com
11
11
  * @since 2.49.0
12
12
  */
13
- import { MJAIAgentTypeEntity, MJTemplateParamEntity, MJAIAgentRelationshipEntity, MJAIAgentNoteEntity, MJAIAgentExampleEntity, MJAISkillEntity, MJAIVendorEntity, type ConversationBranchRow } 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
+ import { type NativeControlConfig } from './native-tools/native-control-config.js';
16
+ import type { AgentToolDefinition } from './native-tools/agent-tools.js';
17
+ import { type NativeToolResult } from './native-tools/tool-result-turns.js';
15
18
  import { MJAIAgentRunEntityExtended, MJAIAgentRunStepEntityExtended, MJAIPromptEntityExtended, MJAIAgentEntityExtended, MJAIModelEntityExtended, MJAIPromptRunEntityExtended } from "@memberjunction/ai-core-plus";
16
19
  import { UserInfo, IMetadataProvider } from '@memberjunction/core';
17
20
  import { AIDecisionRunResult } from '@memberjunction/ai-prompts';
@@ -26,9 +29,10 @@ import { CompactionOutcome, EffectiveContextBudget } from './ConversationCompact
26
29
  import { ConversationToolCall, ConversationToolExecutionResult, ConversationToolSummaryHost } from './ConversationToolManager.js';
27
30
  import { CarryForwardStepRecord, StoppedRunStepRecord } from './tool-result-format.js';
28
31
  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, StopContinuationMode } from '@memberjunction/ai-core-plus';
32
+ import { AIPromptParams, AIPromptRunResult, ExecuteAgentParams, AgentTreeBudget, AgentConfiguration, ExecuteAgentResult, AgentAction, AgentSubAgentRequest, BaseAgentNextStep, MessageLifecycleEvent, AgentChatMessage, AgentChatMessageMetadata, AgentToolCallRequest, AIModelSelectionInfo, ActionChange, ActionChangeScope, SubAgentChange, MediaOutput, FileOutputRef, SecondaryScopeConfig, SecondaryScopeValue, AgentResponseForm, AgentPipelineRequest, AgentSkillActivationRequest, AgentSkillInvocation, SkillAvailabilityPurpose, AgentDecisionRequest, AgentDecisionResult, AgentDecisionAnswerSummary, StopContinuationMode } from '@memberjunction/ai-core-plus';
30
33
  import { MJActionEntityExtended, ActionResult, ActionParam, AIDirective } from '@memberjunction/actions-base';
31
34
  import { RuntimeStateDateTime, RuntimeStateScratchpad } from './runtime-state-fragment.js';
35
+ import { ScratchpadManager } from './ScratchpadManager.js';
32
36
  import { ArtifactToolCall, StoredToolResult } from './ArtifactToolManager.js';
33
37
  import { MemoryWriteRequest, MemoryWriteResult } from './MemoryWriteManager.js';
34
38
  import { AgentDecisionService } from './AgentDecisionService.js';
@@ -78,6 +82,11 @@ export interface ActionResultCrushConfig {
78
82
  * applies. Opt in per agent type via the `crushCodeLang` prompt param or a subclass override.
79
83
  */
80
84
  codeLang: CodeLang | undefined;
85
+ /**
86
+ * Actions whose results are never crushed, by Action name — large exact payloads such as code
87
+ * or specifications the model must read verbatim. Set with the `uncrushedActions` prompt param.
88
+ */
89
+ exemptActions?: ReadonlySet<string>;
81
90
  }
82
91
  /**
83
92
  * Options for {@link BaseAgent.ExecuteSingleAction}.
@@ -95,18 +104,27 @@ export interface ExecuteSingleActionOptions {
95
104
  * call too.
96
105
  */
97
106
  skipCircuitBreaker?: boolean;
107
+ /**
108
+ * The run step (`MJ: AI Agent Run Steps`) this call is recorded under, named in the audit lines
109
+ * written when a bound parameter (`ExecuteAgentParams.boundActionParams`) overrides a value the
110
+ * model sent or refuses the call. Set by the actions step; a direct caller may leave it out.
111
+ */
112
+ StepID?: string;
98
113
  }
99
114
  /**
100
115
  * Which circuit-breaker rule blocked an action call without dispatching it.
101
116
  *
102
117
  * - `'fatal'` — the action failed earlier in the run with a configuration or credential error and is
103
118
  * locked out for the rest of the run.
119
+ * - `'audience'` — the action engine refused the action for the run's audience (`AUDIENCE_UNSUPPORTED`): it cannot
120
+ * limit what it returns to what everyone in a shared conversation may see, so it is locked out for the run. Not a
121
+ * configuration or credential error, and the model is told so.
104
122
  * - `'identical-arguments'` — the action already failed {@link IDENTICAL_FAILURE_THRESHOLD} times
105
123
  * with these exact arguments.
106
124
  * - `'attempts-exhausted'` — the action has failed {@link ACTION_FAILURE_BUDGET} consecutive times
107
125
  * across any arguments.
108
126
  */
109
- export type ActionCircuitBreakerReason = 'fatal' | 'identical-arguments' | 'attempts-exhausted';
127
+ export type ActionCircuitBreakerReason = 'fatal' | 'audience' | 'identical-arguments' | 'attempts-exhausted';
110
128
  /** Identical-arguments rule: this many failures with the same arguments block further identical calls. */
111
129
  export declare const IDENTICAL_FAILURE_THRESHOLD = 2;
112
130
  /** Attempt budget: this many consecutive failures, across any arguments, disable the action for the run. */
@@ -203,6 +221,18 @@ export declare class BaseAgent {
203
221
  * @private
204
222
  */
205
223
  private _executeParams;
224
+ /**
225
+ * Shared root-tree cumulative budget tracking object for the current execution tree.
226
+ * Initialized at the start of {@link Execute} (or inherited from `params.treeBudget`
227
+ * when running as a sub-agent) and forwarded to all child and related sub-agent runs.
228
+ * @protected
229
+ */
230
+ protected _treeBudget: AgentTreeBudget | undefined;
231
+ /**
232
+ * Gets the shared {@link AgentTreeBudget} tracking cumulative steps, tokens, cost,
233
+ * and elapsed wall-clock duration across the root agent and all descendant sub-agents.
234
+ */
235
+ get TreeBudget(): AgentTreeBudget | undefined;
206
236
  /**
207
237
  * The agent configuration loaded for the current run — captured so the cross-turn
208
238
  * compaction hooks can resolve type-level budget defaults without re-loading.
@@ -223,6 +253,10 @@ export declare class BaseAgent {
223
253
  * @private
224
254
  */
225
255
  private _lastVolatileStateMessage;
256
+ /** The previous request's outgoing messages, as {@link messageFingerprint}s. */
257
+ private _lastSentFingerprints;
258
+ /** The previous request's system-prompt-and-tools fingerprint, from the prompt runner. */
259
+ private _lastSentPrefix;
226
260
  /**
227
261
  * The trailing-state retention mode once it has been decided for this run, frozen at the first
228
262
  * model selection so the layout never flips again mid-run. Undefined until then (turn 1 only).
@@ -241,6 +275,30 @@ export declare class BaseAgent {
241
275
  * @private
242
276
  */
243
277
  private _fatalActionFailures;
278
+ /**
279
+ * Actions the action engine refused for the run's audience (`AUDIENCE_UNSUPPORTED`) during the current run —
280
+ * locked out like {@link _fatalActionFailures}, under their own breaker reason (`'audience'`) so the model is
281
+ * told the action is unavailable in a shared conversation rather than misconfigured.
282
+ * @private
283
+ */
284
+ private _audienceLockedActions;
285
+ /**
286
+ * The run's audience readers beyond the caller (`ExecuteAgentParams.Audience`), hydrated from the user cache:
287
+ * `[]` when the audience adds nobody, `undefined` until hydrated for this run. Set after the permission check
288
+ * in {@link Execute}; {@link ExecuteSingleAction}, which is also called directly, hydrates it lazily.
289
+ * @private
290
+ */
291
+ private _audienceReaders;
292
+ /** The `ExecuteAgentParams.Audience` that {@link _audienceReaders} was hydrated from, so a different one re-hydrates. */
293
+ private _audienceSource;
294
+ /**
295
+ * The scope of the run in progress, exactly as {@link initializeAgentRun} validated and wrote it to the run row
296
+ * (nulls when the run is unscoped) — what every action dispatch is handed as `RunActionParams.RunScope`.
297
+ * `undefined` outside {@link Execute}: {@link ExecuteSingleAction}, which is also called directly, then
298
+ * resolves the scope from its params the same way.
299
+ * @private
300
+ */
301
+ private _runScope;
244
302
  /**
245
303
  * Parameter-aware failure tracking per action name for the current agent run.
246
304
  * Differentiates identical retries (which trip quickly) from parameter modifications (which allow self-correction).
@@ -323,6 +381,18 @@ export declare class BaseAgent {
323
381
  * consecutive-attempt budget.
324
382
  */
325
383
  protected recordActionFailure(action: AgentAction, actionEntity: MJActionEntityExtended | undefined, message: string | null | undefined, normalizedParams: string): void;
384
+ /**
385
+ * Locks an action out for the rest of the run: later calls short-circuit on the breaker's `'fatal'` rule, or on
386
+ * its `'audience'` rule for an action the engine refused for the run's audience.
387
+ */
388
+ private lockOutAction;
389
+ /** Clears the run-scoped circuit-breaker state (both lockouts and the failure history) for a new run. */
390
+ private resetActionCircuitBreaker;
391
+ /**
392
+ * The blocked result for an action locked out for the run — refused for the audience (`'audience'`), or failed
393
+ * with an unrecoverable configuration or credential error (`'fatal'`) — or null when it is not locked out.
394
+ */
395
+ private lockedOutActionResult;
326
396
  /**
327
397
  * Clears the parameter-aware failure history for an action after it succeeds, so the
328
398
  * identical-arguments rule and the consecutive-attempt budget start over.
@@ -331,11 +401,58 @@ export declare class BaseAgent {
331
401
  /**
332
402
  * Applies the three circuit-breaker rules to a call that is about to be dispatched. Returns a
333
403
  * blocked result, with the rule that fired, when the call must not go to the action engine;
334
- * null when it may proceed. Rules are checked fatal → identical-arguments → budget.
404
+ * null when it may proceed. Rules are checked audience → fatal → identical-arguments → budget.
335
405
  */
336
406
  protected checkActionCircuitBreaker(params: ExecuteAgentParams, action: AgentAction, actionEntity: MJActionEntityExtended, normalizedParams: string): CircuitBreakerActionResult | null;
337
407
  /** The failed {@link ActionResult} a blocked call returns in place of dispatching. */
338
408
  protected buildBlockedActionResult(actionEntity: MJActionEntityExtended, reason: ActionCircuitBreakerReason, message: string): CircuitBreakerActionResult;
409
+ /**
410
+ * Applies the run's bound parameters to one call (`ExecuteAgentParams.boundActionParams`): a bound
411
+ * value replaces whatever the model sent under its name, and the override is logged with the run and
412
+ * step IDs. The rules are {@link ApplyBoundActionParams}'s; this adds only the log line.
413
+ */
414
+ private applyActionBindings;
415
+ /** "run <id>, step <id>" for an audit line. */
416
+ private whereInRun;
417
+ /**
418
+ * The `ActionParam` array for one dispatch. Coerced against each param's declared schema on every
419
+ * path — envelope, native and flow — so `"640"` reaches an integer param as 640 whichever protocol
420
+ * produced it, while bound parameters keep their exact host-supplied value and carry the `Bound`
421
+ * marker into the execution log.
422
+ */
423
+ private toActionParams;
424
+ /**
425
+ * A call its bindings refuse. The reason (a required parameter bound to nothing, or a binding that
426
+ * names no input of the action) is logged for the operator with the run and step IDs. The model is
427
+ * told only that the action is unavailable, because naming the parameter would reveal what is being
428
+ * hidden; and the action is locked out for the rest of the run the way a fatal configuration failure
429
+ * is, so the circuit breaker short-circuits every later call instead of the model being told to
430
+ * "adjust its parameters" for a refusal it cannot fix.
431
+ */
432
+ private refuseBoundAction;
433
+ /** True when the run binds a parameter on at least one of these actions. */
434
+ private bindsAnyAction;
435
+ /** True when the run has any bound action parameters at all. */
436
+ private hasBoundActionParams;
437
+ /**
438
+ * The error that fails a run at its start when `boundActionParams` names an action that does not
439
+ * exist, so a host that keyed by name or mistyped an ID finds out at once rather than having the
440
+ * parameter it meant to hide shown to the model. Root run only: a sub-agent inherits bindings that
441
+ * were already checked. Needs the action engine configured (Phase 1 of {@link Execute}).
442
+ */
443
+ private boundActionParamsError;
444
+ /**
445
+ * Gives a run that continues another (`lastRunId`) the earlier run's stored bindings, when its caller
446
+ * passed none (an empty object counts as none, as everywhere else). Fails closed: a prior run that
447
+ * can't be read, or whose stored bindings don't parse, fails this run rather than starting it unbound.
448
+ */
449
+ private inheritBoundActionParams;
450
+ /**
451
+ * The model's parameters for one action as the progress line and the model-facing invocation record
452
+ * show them: minus any name the run binds, since a value the model wrote for a bound parameter was
453
+ * discarded and must not be shown as if it had been used. With no bindings, `Object.entries(aa.params)`.
454
+ */
455
+ private shownActionParamEntries;
339
456
  /**
340
457
  * Names the rule behind a failed action summary so the directive matches what actually
341
458
  * happened. A blocked call reports the rule that blocked it. A dispatched failure is fatal if
@@ -447,6 +564,14 @@ export declare class BaseAgent {
447
564
  */
448
565
  private _feedbackRequestId;
449
566
  private _resolvedStorageAccountId;
567
+ /**
568
+ * Most recent artifactDirective returned by a child or related sub-agent during this run.
569
+ * Preserved as a fallback in {@link finalizeAgentRun} when an orchestrator (e.g. Sage) wraps
570
+ * up a delegated sub-agent's response on the subsequent turn without re-emitting its own
571
+ * artifactDirective.
572
+ * @private
573
+ */
574
+ private _lastSubAgentArtifactDirective;
450
575
  /**
451
576
  * The resolved FileStorageAccount ID for this agent run. Set during Execute()
452
577
  * via the hierarchical resolution chain (Runtime → Agent → Category → Type → fallback).
@@ -681,6 +806,11 @@ export declare class BaseAgent {
681
806
  * @since 2.46.0
682
807
  */
683
808
  private _scratchpadManager;
809
+ /**
810
+ * Protected accessor for the run's scratchpad manager.
811
+ * @protected
812
+ */
813
+ protected get scratchpadManager(): ScratchpadManager;
684
814
  /**
685
815
  * Manages artifact tools for the current agent run.
686
816
  * Allows agents to explore input artifacts on demand.
@@ -698,6 +828,12 @@ export declare class BaseAgent {
698
828
  * "Run Ad-hoc Query". Left undefined on the envelope path so the loop can tell the two apart.
699
829
  */
700
830
  protected _nativeToolBindings: ReadonlyMap<string, NativeToolBinding> | undefined;
831
+ /** Results of the agent-tool calls the current prompt step ran, waiting for their call turn to be replayed. */
832
+ private _pendingAgentToolResults;
833
+ /** conversation_tool calls made on the current prompt turn, for the per-turn cap. */
834
+ private _conversationToolTurn;
835
+ /** The parsed native control configuration, and the `TypeConfiguration` it was parsed from. */
836
+ private _nativeControl;
701
837
  /** the model turn whose assistant call message has already been replayed into history (by reference). */
702
838
  private _lastNativeTurnAppended;
703
839
  /**
@@ -838,6 +974,12 @@ export declare class BaseAgent {
838
974
  * prompt execution occurred after them.
839
975
  */
840
976
  private _promptTurnCount;
977
+ /**
978
+ * The non-volatile stack the previous Prompt step of the current run recorded: each message's
979
+ * reference and its serialized form. A later Prompt step records only a delta when its stack
980
+ * extends this one append-only; otherwise it records the full stack.
981
+ */
982
+ private _lastRecordedPromptStack;
841
983
  /**
842
984
  * Per-run config for structurally compressing inline action-result payloads.
843
985
  * Resolved once at run start from the agent-type prompt params (default on);
@@ -924,6 +1066,14 @@ export declare class BaseAgent {
924
1066
  * @private
925
1067
  */
926
1068
  private preloadAgentData;
1069
+ /**
1070
+ * The params a run executes with: `params` itself, or, when the caller did not set
1071
+ * `ExecuteAgentParams.TrustReservedRunData` and `data` carries reserved keys, a copy whose `data` lacks them
1072
+ * (`WithAgentRunDataTrustApplied` in `@memberjunction/ai-core-plus`). {@link Execute} applies it first, so it
1073
+ * holds for every entry point: AgentRunner, the Execute Agent action, MCP, A2A, Runtime Actions, sub-agents.
1074
+ * The removed keys are logged once with the agent and user, never their values.
1075
+ */
1076
+ private withRunDataTrustApplied;
927
1077
  /**
928
1078
  * Executes an AI agent using hierarchical prompt composition.
929
1079
  *
@@ -960,6 +1110,92 @@ export declare class BaseAgent {
960
1110
  */
961
1111
  protected get DefaultAgentTimeoutMS(): number;
962
1112
  Execute<C = any, R = any>(params: ExecuteAgentParams<C>): Promise<ExecuteAgentResult<R>>;
1113
+ /**
1114
+ * Fails the run at its start, before any prompt: marks the already-created AgentRun Failed with the message
1115
+ * (so it never shows as a phantom "running" record) and throws, which {@link Execute} turns into a failure
1116
+ * result. Used by the permission check and the audience check.
1117
+ */
1118
+ private failRunAtStart;
1119
+ /**
1120
+ * The run's audience readers beyond the caller, hydrated once per run and audience: from the per-run state
1121
+ * when it was hydrated from this same `params.Audience`, else validated and loaded now. `{ Error }` names
1122
+ * what makes the audience unusable. `{ Readers: [] }` when the audience adds nobody.
1123
+ */
1124
+ private audienceReadersFor;
1125
+ /**
1126
+ * Validates `params.Audience` ({@link AgentAudienceProblem}) and loads a hydrated user for each reader it adds
1127
+ * beyond the caller ({@link ResolveAudienceUsers}). An ID no user has is refused, never skipped: a skipped
1128
+ * reader would restrict nothing, and the room would see the caller's whole reach.
1129
+ */
1130
+ private resolveRunAudience;
1131
+ /**
1132
+ * Loads the hydrated user (with its `UserRoles`) for each audience ID, from the server's `UserCache`. When an
1133
+ * ID is missing the cache is refreshed once — a user created since it loaded is then found, as MJServer's
1134
+ * authentication does for a user it does not know — and looked up again. Returns the users found; an ID left
1135
+ * out refuses the run. Override to resolve readers from another directory; never build `UserInfo` by hand.
1136
+ *
1137
+ * An inactive user is accepted as a reader, deliberately: a reader can only narrow what the run shows (each one is
1138
+ * another permission check every result must pass), never widen it, so a deactivated participant still listed in
1139
+ * the room restricts the run rather than failing it.
1140
+ *
1141
+ * @param ids The reader IDs the audience adds beyond the caller (normalized, distinct).
1142
+ * @param params The run's parameters (for the request-scoped provider the refresh reads through).
1143
+ */
1144
+ protected ResolveAudienceUsers(ids: string[], params: ExecuteAgentParams): Promise<UserInfo[]>;
1145
+ /**
1146
+ * Whether this run's audience adds a reader beyond the caller — the condition every audience gate asks.
1147
+ * A malformed audience counts as adding one (the run fails before the gates are reached anyway).
1148
+ */
1149
+ private runAudienceAddsReader;
1150
+ /**
1151
+ * Why this run is not offered task graphs and refuses one the model writes, or null when it may use them — the one
1152
+ * predicate, so every condition that withholds graphs is added in one place. A graph runs outside the run: its
1153
+ * action nodes are dispatched by the task-graph runner (MJServer's `TaskGraphActionRunner`) with no `Audience`,
1154
+ * no `RunScope` and no run `Context`, outside {@link ExecuteSingleAction}, and an agent node starts a run
1155
+ * (`TaskGraphAgentRunner`) that carries neither the audience nor the scope. So graphs are withheld when the
1156
+ * audience adds a reader, and when the run's validated scope carries a tenant or a secondary dimension
1157
+ * (`ActionRunScopeIsBounded`): a model-written Scoped Search node would search outside the run's tenant, and an
1158
+ * agent node would drop it.
1159
+ */
1160
+ private taskGraphWithholdingReason;
1161
+ /** Whether this run withholds task graphs ({@link taskGraphWithholdingReason}). */
1162
+ private runWithholdsTaskGraphs;
1163
+ /**
1164
+ * The `Failed` step for a task graph the model wrote although this run withholds them ({@link taskGraphWithholdingReason}),
1165
+ * or null when graphs are allowed. The response type already hides `tasks`; this is the gate for a model that emits one
1166
+ * anyway. Written before any step: nothing is submitted.
1167
+ */
1168
+ private taskGraphRefusal;
1169
+ /**
1170
+ * What this run's prompt leaves out: task graphs ({@link taskGraphWithholdingReason}), and — when the audience adds a
1171
+ * reader — the caller's own browser and view (`CallerContext`): client tools run in the caller's browser and what they
1172
+ * return reaches the room, and the app context (`data.appContext`, with its `AdditionalContext`) is the caller's screen.
1173
+ */
1174
+ private promptWithholding;
1175
+ /**
1176
+ * The client-tools and app-context prompt sections ({@link buildClientToolPromptSection}, {@link buildAppContextSection}),
1177
+ * both empty when the caller's context is withheld ({@link promptWithholding}): the prompt then offers no client tool
1178
+ * and none of the caller's app context. {@link executeClientToolsStep} refuses a client-tools step emitted anyway.
1179
+ */
1180
+ private callerContextSections;
1181
+ /**
1182
+ * The `Failed` step for a client-tools step under an audience, or null. Client tools run in the caller's browser and
1183
+ * what they return comes back into a run whose output reaches the room; the prompt does not offer them then
1184
+ * ({@link callerContextSections}), and this refuses a step the model emits anyway, as {@link taskGraphRefusal} does a graph.
1185
+ */
1186
+ private clientToolsRefusal;
1187
+ /** Clears what bounds one run — its validated scope and its hydrated audience — once the run is over. */
1188
+ private clearRunBoundState;
1189
+ /**
1190
+ * A copy of the agent-type prompt params with task graphs withheld (`enableTaskGraphs` off and the `tasks`
1191
+ * response section hidden). A copy, never a write: the input may be the process-wide cached base.
1192
+ */
1193
+ private withoutTaskGraphs;
1194
+ /**
1195
+ * Why a session-driven (realtime / voice / bridge) run is refused, or null. A live session speaks and calls
1196
+ * tools outside the gates that hold a run to its audience, so a run whose audience adds a reader is refused.
1197
+ */
1198
+ private sessionAudienceRefusal;
963
1199
  /**
964
1200
  * Releases this run's PerRun-scoped preloaded-data cache entry. `preloadAgentData()`
965
1201
  * (Phase 2 of `Execute()`) may have populated one keyed by `this._agentRun.ID`; without
@@ -1447,9 +1683,10 @@ export declare class BaseAgent {
1447
1683
  * @param primaryScopeRecordId - Optional primary scope record ID for multi-tenant filtering
1448
1684
  * @param secondaryScopes - Optional secondary scope dimensions for multi-tenant filtering
1449
1685
  * @param secondaryScopeConfig - Optional agent-level scope config for per-dimension inheritance
1686
+ * @param sharedOnly - Inject only shared notes and examples (no `UserID`); set when the run's audience adds a reader
1450
1687
  * @returns Object containing injected notes and examples
1451
1688
  */
1452
- 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<{
1689
+ 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<{
1453
1690
  notes: MJAIAgentNoteEntity[];
1454
1691
  examples: MJAIAgentExampleEntity[];
1455
1692
  }>;
@@ -1460,9 +1697,18 @@ export declare class BaseAgent {
1460
1697
  * primary prompt under the run's polymorphic scope (the SAME PrimaryScope/SecondaryScopes the
1461
1698
  * runtime threads for memory), and unshifts the assembled role-tagged messages onto
1462
1699
  * `conversationMessages`. In-memory + synchronous (parts are cached on `AIEngine`). No-op when
1463
- * the agent has no active prompt or no parts resolve for the scope.
1700
+ * the agent has no active prompt or no parts resolve for the scope. System placeholders in the
1701
+ * messages it adds are replaced afterwards ({@link replaceScopedPartPlaceholders}), so an override
1702
+ * gets that too.
1464
1703
  */
1465
1704
  protected InjectScopedPromptParts(agent: MJAIAgentEntityExtended, conversationMessages: ChatMessage[], primaryScopeEntityId?: string, primaryScopeRecordId?: string, secondaryScopes?: Record<string, SecondaryScopeValue>): void;
1705
+ /**
1706
+ * Replace system placeholders such as `{{ _CURRENT_DATE }}` in the messages that
1707
+ * {@link InjectScopedPromptParts} added, meaning every message not in `before`. Part text is not a
1708
+ * template: see {@link SystemPlaceholderManager.ReplaceAvailablePlaceholders} for what resolves.
1709
+ * On failure the parts are kept as written.
1710
+ */
1711
+ private replaceScopedPartPlaceholders;
1466
1712
  /**
1467
1713
  * Inject pre-execution RAG context for this agent using scoped search.
1468
1714
  *
@@ -1486,9 +1732,12 @@ export declare class BaseAgent {
1486
1732
  * @param primaryScopeRecordId - Multi-tenant primary scope record ID.
1487
1733
  * @param secondaryScopes - Multi-tenant secondary scope dimensions.
1488
1734
  * @param payload - The agent's current payload (for template rendering).
1735
+ * @param activeSkillIDs - The skills active for this run; a lone active skill is the search's skill principal.
1736
+ * @param audienceReaders - The run's audience readers beyond the caller (`ExecuteAgentParams.Audience`,
1737
+ * hydrated): each must pass the scope gate, and only results every one of them may read are injected.
1489
1738
  * @returns The structured RAG result, or `null` if no scopes produced results.
1490
1739
  */
1491
- 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>;
1740
+ 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>;
1492
1741
  /**
1493
1742
  * Decision discovery (plan Task 3.1): suggests the agent to delegate to before the first prompt.
1494
1743
  *
@@ -1598,6 +1847,7 @@ export declare class BaseAgent {
1598
1847
  *
1599
1848
  * @param {string} lastRunId - The ID of the last run to check
1600
1849
  * @param {UserInfo} [contextUser] - Optional user context
1850
+ * @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
1601
1851
  * @private
1602
1852
  */
1603
1853
  private validateRunChain;
@@ -1692,8 +1942,14 @@ export declare class BaseAgent {
1692
1942
  * action results as ONE tool turn — a tool_result block per call, paired by id — when the
1693
1943
  * turn's results go back natively; otherwise the markdown user message as before. An action that
1694
1944
  * cannot be paired with a call id keeps the markdown message for itself.
1945
+ *
1946
+ * A failed action's guidance (from `failureGuidance`) rides inside its own error result, where
1947
+ * the model reads it as part of that call's outcome rather than as a separate instruction.
1948
+ *
1949
+ * @returns The summaries answered as native tool results — the caller still owes the rest any
1950
+ * guidance, as a message
1695
1951
  */
1696
- protected appendActionResults(params: ExecuteAgentParams, summaries: ActionResultSummary[], resultsMessage: string, metadata: AgentChatMessageMetadata | undefined, previousDecision: BaseAgentNextStep): void;
1952
+ protected appendActionResults(params: ExecuteAgentParams, summaries: ActionResultSummary[], resultsMessage: string, metadata: AgentChatMessageMetadata | undefined, previousDecision: BaseAgentNextStep, failureGuidance?: ReadonlyMap<ActionResultSummary, string>): ReadonlySet<ActionResultSummary>;
1697
1953
  /**
1698
1954
  * Answers any tool call the turn's own result path left dangling, immediately before the
1699
1955
  * history goes back to the model.
@@ -1712,12 +1968,89 @@ export declare class BaseAgent {
1712
1968
  * message the branch itself appended (the retry instructions, the chat question).
1713
1969
  */
1714
1970
  protected reconcileUnansweredToolCalls(params: ExecuteAgentParams): void;
1971
+ /**
1972
+ * Appends a tool turn answering the latest call turn. When that call turn is already followed
1973
+ * by a tool turn — declined calls, or agent-tool results, answered first — the results join it,
1974
+ * because Anthropic takes every result for a call turn from the one message that follows it.
1975
+ */
1976
+ protected PushToolResultTurn(params: ExecuteAgentParams, results: AgentChatMessage): void;
1977
+ /** The index of the most recent assistant turn that made tool calls, or -1. */
1978
+ private static lastToolCallTurnIndex;
1979
+ /** The call ids that already have a `tool_result` in some message after the call turn. */
1980
+ private static toolCallIdsAnsweredAfter;
1981
+ /**
1982
+ * Places a tool turn immediately after the assistant turn whose calls it answers.
1983
+ *
1984
+ * Anthropic requires every result for a call turn in the single message that follows it, and
1985
+ * OpenAI requires the call turn to be followed by its tool messages — so a result appended after
1986
+ * a retry message that already sits behind the call is rejected by both. When the message right
1987
+ * after the call turn is already a tool turn, the results merge into it instead of opening a
1988
+ * second one.
1989
+ */
1990
+ private static insertToolResultsAfterCallTurn;
1715
1991
  /**
1716
1992
  * a tool turn can never be REMOVED from history — that orphans the assistant call it
1717
1993
  * answers, which every provider rejects. Expiry and recovery stub its blocks instead.
1718
1994
  */
1719
1995
  private stubToolTurn;
1720
1996
  protected applyNativeTools(promptParams: AIPromptParams, params: ExecuteAgentParams): void;
1997
+ /**
1998
+ * The agent's own native tools — tools that read and write this agent's state, such as
1999
+ * `write_section` / `edit_section`. None by default; a driver class overrides this.
2000
+ *
2001
+ * Declared beside the agent's Actions whenever the run declares native tools, and dispatched in
2002
+ * every native mode. Each call runs as a `Tool` run step, in the order the model made the calls,
2003
+ * and its {@link AgentToolResult.PayloadChange} is applied before the next call runs. See
2004
+ * {@link AgentToolDefinition} for the contract.
2005
+ *
2006
+ * @param params The run parameters
2007
+ * @returns The tools to declare this turn
2008
+ */
2009
+ protected GetAgentTools(params: ExecuteAgentParams): AgentToolDefinition[];
2010
+ /**
2011
+ * Which framework capabilities a native-only agent gets as tools this turn — the same gates the
2012
+ * hybrid prompt applies to the matching envelope fields and their documentation.
2013
+ */
2014
+ private frameworkToolAvailability;
2015
+ /** The capabilities behind the framework tools, bound to this run. */
2016
+ private frameworkToolHost;
2017
+ private applyScratchpadFromTool;
2018
+ private writeMemoryFromTool;
2019
+ private runArtifactToolFromTool;
2020
+ private runConversationToolFromTool;
2021
+ private runDecisionsFromTool;
2022
+ /**
2023
+ * Runs the turn's agent-tool calls in order, each as its own `Tool` run step, threading the
2024
+ * payload through them so successive edits compose.
2025
+ *
2026
+ * @param calls The calls, in the order the model made them
2027
+ * @param payload The payload before the first call
2028
+ * @param params The run parameters
2029
+ * @returns The payload after the last call, and one result per call, in call order
2030
+ */
2031
+ protected ExecuteAgentToolCallsAsSteps<P>(calls: AgentToolCallRequest[], payload: P, params: ExecuteAgentParams): Promise<{
2032
+ payload: P;
2033
+ results: NativeToolResult[];
2034
+ }>;
2035
+ /** One agent-tool call as a `Tool` run step: run it, apply its payload change, record both. */
2036
+ private executeAgentToolCallAsStep;
2037
+ /** Calls the tool's handler; an undeclared tool or a thrown error becomes an error result. */
2038
+ private runAgentTool;
2039
+ /**
2040
+ * Applies an agent tool's payload change through PayloadManager, under the agent's
2041
+ * `PayloadSelfWritePaths`. A change that touches a path the agent may not write is rejected
2042
+ * whole — a partial write would leave the payload in a state the tool never described — and
2043
+ * the reason goes back to the model as the call's error result.
2044
+ *
2045
+ * @param partial Apply the allowed parts and report the rest, as a single `payload_change_request`
2046
+ * on a turn always has; the model wrote that change itself, path by path
2047
+ */
2048
+ private applyAgentToolPayloadChange;
2049
+ /**
2050
+ * Answers the turn's agent-tool calls, directly after the call turn the loop just replayed. When
2051
+ * the turn's results do not go back natively, the results become one user message instead.
2052
+ */
2053
+ private appendAgentToolResults;
1721
2054
  /**
1722
2055
  * The `tool_choice` for this turn (§8.3).
1723
2056
  *
@@ -1744,13 +2077,28 @@ export declare class BaseAgent {
1744
2077
  * address them. That belongs to the prompt, and is why the native-mode Actions section names
1745
2078
  * the cases explicitly.
1746
2079
  *
2080
+ * **A text-terminal agent** (`NativeControl.Terminal: 'text'`) declares no `complete_task`: its
2081
+ * answer is the plain-text reply, and its state changes went through its own tools on earlier
2082
+ * turns. Its final turn is `'none'`, which asks for exactly that reply.
2083
+ *
1747
2084
  * Subclasses may narrow this further; the base contract is that a forced terminal choice must
1748
2085
  * never be relaxed to `'auto'` on a turn the framework has already decided is terminal.
1749
2086
  *
1750
2087
  * @param params The run parameters, for the per-run iteration override
1751
- * @returns `{ name: 'complete_task' }` on the final permitted iteration, otherwise `'auto'`
2088
+ * @returns On the final permitted iteration, `{ name: 'complete_task' }`, or `'none'` for a
2089
+ * text-terminal agent; otherwise `'auto'`
1752
2090
  */
1753
2091
  protected resolveToolChoiceForTurn(params: ExecuteAgentParams): ChatToolChoice;
2092
+ /**
2093
+ * The agent's native control configuration — which control tools it declares and how its run
2094
+ * ends — from the `NativeControl` block of its `TypeConfiguration`. Defaults when there is none.
2095
+ *
2096
+ * Parsed once per distinct configuration; anything unusable is logged once and falls back to its
2097
+ * default, so a typo never fails a run.
2098
+ *
2099
+ * @param params The run parameters, for the agent
2100
+ */
2101
+ protected GetNativeControlConfig(params: ExecuteAgentParams): NativeControlConfig;
1754
2102
  /**
1755
2103
  * Whether the turn currently being prepared is the last one this run will be allowed.
1756
2104
  *
@@ -1772,6 +2120,29 @@ export declare class BaseAgent {
1772
2120
  */
1773
2121
  protected isFinalPermittedIteration(params: ExecuteAgentParams): boolean;
1774
2122
  protected preparePromptParams<P>(config: AgentConfiguration, payload: P, params: ExecuteAgentParams): Promise<AIPromptParams>;
2123
+ /**
2124
+ * Drops replayed reasoning that the history before it no longer matches.
2125
+ *
2126
+ * A driver with `ReplayedReasoningRequiresStablePrefix` accepts a replayed reasoning block
2127
+ * only while every message before it is exactly what was sent when the block was produced.
2128
+ * Expiry, compaction, message expansion and context recovery all rewrite earlier messages,
2129
+ * and each would make the request fail. So the outgoing messages are compared with the
2130
+ * previous request's: from the first message that was changed or removed, every call turn's
2131
+ * reasoning is dropped — in this request and in the history, so later requests stay
2132
+ * consistent. Messages the previous request did not have (the model's reply, new results)
2133
+ * are not a change.
2134
+ */
2135
+ private dropReasoningBehindChangedHistory;
2136
+ /** Whether this run replays reasoning to a driver that binds it to an unchanged request prefix. */
2137
+ private replaysPrefixBoundReasoning;
2138
+ /**
2139
+ * Keeps the system-prompt-and-tools fingerprint of the request just sent, for the next one. When
2140
+ * it changed, the runner sent this request without replayed reasoning; the history drops it too,
2141
+ * so no later request replays a block made under the old prompt or tools.
2142
+ */
2143
+ private trackSentPrefix;
2144
+ /** What makes a message the same message to a provider — reasoning aside, which only this check removes. */
2145
+ private static messageFingerprint;
1775
2146
  /**
1776
2147
  * In append-only mode, restores turn 1's volatile state fragment if mode resolution
1777
2148
  * was deferred until after turn 1 (e.g. dynamic model selection).
@@ -1813,7 +2184,9 @@ export declare class BaseAgent {
1813
2184
  * Which providers are which is METADATA, not code: the `PrefixPromptCache` flag in the model
1814
2185
  * catalog's `ModelConfiguration` cascade (Model Types < Models < Vendors' `Configuration.ModelDefaults`
1815
2186
  * < Model Vendors), read through {@link resolvePrefixPromptCache}. `true` means append-only;
1816
- * anything else means replace.
2187
+ * anything else means replace. One exception comes from the driver, not the catalog: a run that
2188
+ * declares native tools to a driver whose replayed reasoning needs the history before it
2189
+ * unchanged is append-only too (see {@link ResolveAppendOnlyState}).
1817
2190
  *
1818
2191
  * Decided ONCE per run. An explicit `trailingStateMode` or a runtime model override answers
1819
2192
  * immediately. Otherwise the answer is frozen at the first model selection and reused for every
@@ -1826,6 +2199,16 @@ export declare class BaseAgent {
1826
2199
  * guessing from them mis-pins runs that end up selecting another vendor.
1827
2200
  */
1828
2201
  protected shouldUseAppendOnlyTrailingState(promptParams: AIPromptParams): boolean;
2202
+ /**
2203
+ * Whether this run keeps its runtime-state fragments (append-only): the model sits behind a
2204
+ * byte-prefix prompt cache, or the run declares native tools to a driver whose replayed
2205
+ * reasoning is accepted only while the history before it is unchanged. In replace mode each
2206
+ * request drops the previous fragment, and a thinking block produced after it would be replayed
2207
+ * behind a changed history and rejected.
2208
+ */
2209
+ protected ResolveAppendOnlyState(model: MJAIModelEntityExtended | undefined, vendor: MJAIVendorEntity | undefined): boolean;
2210
+ /** Whether the driver serving `model` on `vendor` binds replayed reasoning to the unchanged history before it. */
2211
+ protected DriverRequiresStableReasoningPrefix(model: MJAIModelEntityExtended | undefined, vendor: MJAIVendorEntity | undefined): boolean;
1829
2212
  /**
1830
2213
  * Whether a model, as served by a vendor, sits behind a byte-prefix prompt cache
1831
2214
  * (`LLM.PrefixPromptCache`), read from the model catalog's `ModelConfiguration` cascade —
@@ -1864,17 +2247,26 @@ export declare class BaseAgent {
1864
2247
  * when it stays in the system prompt.
1865
2248
  */
1866
2249
  protected resolveRelocatedSpecialization(promptParams: AIPromptParams, childPrompt: MJAIPromptEntityExtended | undefined, agentType: MJAIAgentTypeEntity, contextUser: UserInfo): Promise<string | null>;
2250
+ /**
2251
+ * Per-instance memoization for runtime-state template delivery analysis and template-array indexing
2252
+ * so multi-turn agent loops do not repeatedly scan template collections and strings on every turn.
2253
+ * @private
2254
+ */
2255
+ private _lastRuntimeStateDeliveryCache;
2256
+ private _cachedTemplatesArrayRef;
2257
+ private _templateByIdMap;
2258
+ private _templateEngineConfiguredForRun;
1867
2259
  /**
1868
2260
  * Decides, from the system prompt's UNRENDERED template text, whether the trailing runtime-state
1869
2261
  * fragment belongs on this request:
1870
2262
  *
1871
2263
  * - `'trailing'` — the template carries the `<mj-runtime-state>` pointer, so the model is told where
1872
- * the state lives. The Loop agent system prompt.
2264
+ * the state lives. The Loop and Flow agent system prompts.
1873
2265
  * - `'embedded'` — the template still renders the state blocks itself (an environment whose
1874
- * TemplateContent has not synced the new Loop template, or the Flow template, which embeds the
2266
+ * TemplateContent has not synced the new system template, or a custom template that embeds the
1875
2267
  * payload). Emitting the fragment would deliver the same state twice.
1876
2268
  * - `'unsupported'` — the template has neither. The Harness system prompt, or a custom prompt run
1877
- * without the Loop system prompt. The model would receive an unexplained block.
2269
+ * without a system prompt carrying the pointer. The model would receive an unexplained block.
1878
2270
  * - `'unknown'` — no template text to inspect (no TemplateID, or the lookup failed). The caller
1879
2271
  * fails OPEN here: a Loop agent losing its payload from the model's view is far worse than a
1880
2272
  * non-Loop agent receiving an unexplained fragment, and in practice every agent type's system
@@ -1967,6 +2359,22 @@ export declare class BaseAgent {
1967
2359
  */
1968
2360
  protected getRequestedSubAgents<P, C>(nextStep: BaseAgentNextStep<P, C> | undefined | null): AgentSubAgentRequest<C>[];
1969
2361
  protected validateSubAgentNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2362
+ /**
2363
+ * Builds a compact hint listing the current user's permitted runnable agents when a
2364
+ * task-graph or folded sub-agent step references an unknown or inaccessible agent name.
2365
+ */
2366
+ protected buildAvailableRunnableAgentsHint(contextUser?: UserInfo): string;
2367
+ /**
2368
+ * Validates a `'Tasks'` next step before `executeTasksStep` submits the graph.
2369
+ *
2370
+ * Verifies that every referenced `Agent` (including `ForEach`/`While` loop sub-agents) is
2371
+ * active and runnable by `params.contextUser`, and that every referenced `Action` is active.
2372
+ * When an agent or action name is unknown or inaccessible, converts the step to a self-correcting
2373
+ * `Retry` with the user's permitted runnable agent list instead of letting `TaskGraphService.Submit`
2374
+ * terminate the entire agent run as `Failed`. Never reveals whether an invalid agent name was
2375
+ * nonexistent versus restricted by permissions.
2376
+ */
2377
+ protected validateTasksNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, _currentPayload: P, _agentRun: MJAIAgentRunEntityExtended, _currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
1970
2378
  /**
1971
2379
  * Validates that the actions next step is valid and can be executed by the current agent. Subclasses can override
1972
2380
  * this method to implement custom validation logic if needed.
@@ -2093,6 +2501,58 @@ export declare class BaseAgent {
2093
2501
  current?: number;
2094
2502
  reason?: string;
2095
2503
  }>;
2504
+ /**
2505
+ * Ensures that a shared {@link AgentTreeBudget} instance exists for the current execution tree
2506
+ * and is attached to both `this._treeBudget` and `params.treeBudget`.
2507
+ *
2508
+ * - When `params.treeBudget` is already provided (for example, propagated by a parent agent
2509
+ * in {@link ExecuteSubAgent} or supplied directly by a caller), that exact object reference
2510
+ * is reused so all root, sequential child, and parallel child runs mutate the same shared
2511
+ * counters (`totalSteps`, `totalTokens`, `totalCost`, `startedAtMs`, `breachedReason`).
2512
+ * - When `params.treeBudget` is absent (root run), a new {@link AgentTreeBudget} is created
2513
+ * and seeded with any top-level convenience ceilings (`maxTreeSteps`, `maxTreeTokens`,
2514
+ * `maxTreeCost`, `maxTreeDurationMs`) declared on `params`.
2515
+ *
2516
+ * @param params - Optional execution parameters for the current run.
2517
+ * @returns The shared {@link AgentTreeBudget} instance for the execution tree.
2518
+ * @protected
2519
+ */
2520
+ protected ensureTreeBudget(params?: ExecuteAgentParams): AgentTreeBudget;
2521
+ /**
2522
+ * Accumulates token and cost usage from a completed prompt execution into the shared
2523
+ * {@link AgentTreeBudget} for the execution tree.
2524
+ *
2525
+ * Prefers rollup figures on `promptRun` (`TokensUsedRollup` / `TokensPromptRollup` +
2526
+ * `TokensCompletionRollup` and `TotalCost`) so hierarchical child prompts are counted,
2527
+ * falling back to direct `promptRun` columns (`TokensUsed` / `TokensPrompt` + `TokensCompletion`
2528
+ * and `Cost`) or the `AIPromptRunResult` summary fields when `promptRun` is not populated.
2529
+ *
2530
+ * @param promptRun - The persisted or in-memory `MJAIPromptRunEntity` from the prompt execution, if any.
2531
+ * @param promptResult - Optional `AIPromptRunResult` carrying direct token/cost metrics.
2532
+ * @param params - Optional execution parameters for the current run.
2533
+ * @protected
2534
+ */
2535
+ protected recordPromptUsageInTreeBudget(promptRun?: MJAIPromptRunEntity | null, promptResult?: AIPromptRunResult<unknown>, params?: ExecuteAgentParams): void;
2536
+ /**
2537
+ * Evaluates whether any root-tree cumulative budget ceiling (`maxTreeSteps`, `maxTreeTokens`,
2538
+ * `maxTreeCost`, `maxTreeDurationMs`) on the shared {@link AgentTreeBudget} has been reached
2539
+ * or exceeded.
2540
+ *
2541
+ * When a ceiling is breached, sets `budget.breachedReason` with a descriptive diagnostic
2542
+ * message so both the breaching agent and any ancestor agents in the call tree can terminate
2543
+ * immediately with `step: 'Failed'` and `terminate: true`.
2544
+ *
2545
+ * @param params - Optional execution parameters for the current run.
2546
+ * @returns Guardrail evaluation result indicating whether a tree budget limit was exceeded.
2547
+ * @protected
2548
+ */
2549
+ protected checkTreeBudgetLimit(params?: ExecuteAgentParams): {
2550
+ exceeded: boolean;
2551
+ type?: 'cost' | 'tokens' | 'iterations' | 'time';
2552
+ limit?: number;
2553
+ current?: number;
2554
+ reason?: string;
2555
+ };
2096
2556
  /**
2097
2557
  * Determines if a prompt execution error is fatal and should stop agent execution.
2098
2558
  * Fatal errors are those that won't be resolved by retrying, such as context length
@@ -2269,6 +2729,26 @@ export declare class BaseAgent {
2269
2729
  * @protected
2270
2730
  */
2271
2731
  protected processNextStep<P>(nextStep: BaseAgentNextStep<P>, params: ExecuteAgentParams, agentType: MJAIAgentTypeEntity, promptResult: AIPromptRunResult, currentPayload: P, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2732
+ /**
2733
+ * Answers a retried native tool-call turn in the protocol itself: every call gets an `is_error`
2734
+ * result carrying the retry reason, and no user message follows.
2735
+ *
2736
+ * The call turn was just replayed by `appendNativeAssistantTurn`, so the result turn lands
2737
+ * directly behind it — the adjacency Anthropic and OpenAI both require. Calls the turn already
2738
+ * answered (its agent tools ran and reported) keep their results; the rest join that tool turn.
2739
+ * Returns false when the turn's results do not go back natively, or no call is left to answer;
2740
+ * the caller then sends the reason as a user message, and `reconcileUnansweredToolCalls`
2741
+ * closes any call still open.
2742
+ */
2743
+ private answerNativeRetryTurn;
2744
+ /**
2745
+ * A turn that wrote and then asked or completed, where a write failed: the question or
2746
+ * completion is declined, and the turn becomes a plain "go again" Retry. The model made that
2747
+ * call expecting its writes to land, so it reads the failure and decides again.
2748
+ *
2749
+ * @returns The step to process — `step` itself when nothing failed or it is not terminal
2750
+ */
2751
+ private declineTerminalAfterFailedWrite;
2272
2752
  /** The tool name the model used for a call on this turn — `payload_change_request` when it cannot be found. */
2273
2753
  private nativeToolNameForCall;
2274
2754
  /**
@@ -2296,7 +2776,9 @@ export declare class BaseAgent {
2296
2776
  *
2297
2777
  * Gated on conversationId + root depth — programmatic runs and sub-agents skip it.
2298
2778
  * Skipped under a history floor (`ConversationHistoryFrom`): the previous run's tool
2299
- * results can quote messages from before the floor.
2779
+ * results can quote messages from before the floor. Skipped under an audience
2780
+ * (`ExecuteAgentParams.Audience`) too: the previous run's results were fetched for
2781
+ * whoever ran it, not for this room.
2300
2782
  * @protected
2301
2783
  */
2302
2784
  protected injectPriorTurnToolResults(params: ExecuteAgentParams): Promise<void>;
@@ -2358,10 +2840,12 @@ export declare class BaseAgent {
2358
2840
  /**
2359
2841
  * The stopped run's turns in the shape the loop builds, or null when they cannot be recovered.
2360
2842
  *
2361
- * The last prompt step recorded the run's whole message stack as it went into that prompt; the
2362
- * first prompt step recorded the stack the run started from (history plus this run's injections,
2363
- * which the new run adds for itself). The difference is the run's own turns. If the last prompt
2364
- * completed, its decision and the steps after it are rebuilt with the loop's own builders.
2843
+ * The latest prompt step that recorded a full stack holds the run's whole message stack as it went
2844
+ * into that prompt; the prompt steps after it recorded only the messages appended since (see
2845
+ * {@link capturePromptStepMessages}). The first prompt step recorded the stack the run started from
2846
+ * (history plus this run's injections, which the new run adds for itself). The difference is the
2847
+ * run's own turns. If the last prompt completed, its decision and the steps after it are rebuilt
2848
+ * with the loop's own builders.
2365
2849
  * @protected
2366
2850
  */
2367
2851
  protected buildResumedStoppedRunTurns(steps: StoppedRunStackStepRecord[], params: ExecuteAgentParams): AgentChatMessage[] | null;
@@ -2398,6 +2882,8 @@ export declare class BaseAgent {
2398
2882
  private summarizeStoppedActionStep;
2399
2883
  /** The message stack a prompt step recorded as its input, or null. @private */
2400
2884
  private static readPromptStepStack;
2885
+ /** True when a prompt step recorded only the per-turn message delta instead of the full history stack. @private */
2886
+ private static isPromptStepDelta;
2401
2887
  /** The decision a completed prompt step recorded, or null. @private */
2402
2888
  private static readPromptStepDecision;
2403
2889
  /** The action an Actions step ran, from its recorded input, or null. @private */
@@ -2637,6 +3123,8 @@ export declare class BaseAgent {
2637
3123
  * @protected
2638
3124
  */
2639
3125
  protected capStandaloneToolResultText(text: string): string;
3126
+ /** Where and for whom a memory write lands — shared by the envelope field and the native tool. */
3127
+ private memoryWriteOptions;
2640
3128
  /**
2641
3129
  * Executes a batch of in-flight memory writes, recording each as its own
2642
3130
  * `Tool` AIAgentRunStep (a sibling of the Prompt step that requested them)
@@ -2655,15 +3143,39 @@ export declare class BaseAgent {
2655
3143
  protected executeMemoryWritesAsSteps(writes: MemoryWriteRequest[], params: ExecuteAgentParams): Promise<MemoryWriteResult[]>;
2656
3144
  /**
2657
3145
  * Turn-loop entry point for in-flight memory writes, gated on the agent's
2658
- * AllowMemoryWrite flag. When disabled but the LLM emitted writes anyway
2659
- * (prompt drift / injection attempt), records ONE summary skip step —
2660
- * observable without per-write noise — and tells the agent the memories
2661
- * were NOT saved so it stops re-emitting. When enabled, executes the
3146
+ * AllowMemoryWrite flag and on the run's audience ({@link memoryWriteSkip}).
3147
+ * When refused but the LLM emitted writes anyway (prompt drift / injection
3148
+ * attempt), records ONE summary skip step and tells the agent the memories
3149
+ * were NOT saved ({@link skipMemoryWrites}). Otherwise executes the
2662
3150
  * writes as run steps and injects the results message.
2663
3151
  *
2664
3152
  * @protected
2665
3153
  */
2666
3154
  protected processMemoryWritesForTurn(memoryWrites: MemoryWriteRequest[], params: ExecuteAgentParams): Promise<void>;
3155
+ /**
3156
+ * Determines whether artifact creation/lifecycle support (`artifactDirective`) is enabled for
3157
+ * the given agent so the Loop Agent system prompt includes `artifactDirective` and its lifecycle
3158
+ * instructions only when relevant.
3159
+ *
3160
+ * Returns `true` when:
3161
+ * - `agent.ArtifactCreationMode` is not `'Never'`, OR
3162
+ * - Conversation artifacts are already loaded in `_artifactToolManager`, OR
3163
+ * - The agent is an embedded sub-agent (`agent.ParentID`) whose parent agent creates artifacts
3164
+ * (`parentAgent.ArtifactCreationMode === 'Always'`) and relies on the sub-agent's payload/directive.
3165
+ */
3166
+ protected isArtifactSupportEnabled(agent: MJAIAgentEntityExtended): boolean;
3167
+ /**
3168
+ * Why this run saves no memory writes, or null when it may: the agent has not opted in (`AllowMemoryWrite`), or the
3169
+ * run's audience adds a reader. A write is the caller's note, and its reply — saved, superseded, "already exists
3170
+ * verbatim" — is read against the caller's own notes, so in a shared conversation it would tell the room what the
3171
+ * caller has noted. The memory-writes docs are left out of the prompt for the same reasons.
3172
+ */
3173
+ private memoryWriteSkip;
3174
+ /**
3175
+ * Records ONE summary skip step for a turn's refused memory writes — observable without per-write noise — and tells
3176
+ * the agent the memories were NOT saved, so it stops re-emitting them.
3177
+ */
3178
+ private skipMemoryWrites;
2667
3179
  /**
2668
3180
  * Pushes a single user-role message containing memory-write outcomes into
2669
3181
  * the conversation, mirroring `injectArtifactToolResultsMessage`'s
@@ -2887,6 +3399,7 @@ export declare class BaseAgent {
2887
3399
  * @param {UserInfo} [_contextUser] - Optional user context (reserved for future use)
2888
3400
  * @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.
2889
3401
  * @param {ActionChange[]} [actionChanges] - Optional runtime action modifications
3402
+ * @param {PromptWithholding} [withholding] - What this run's prompt leaves out (see `promptWithholding`)
2890
3403
  *
2891
3404
  * @returns {Promise<AgentContextData>} Structured context data for prompts
2892
3405
  *
@@ -3157,22 +3670,67 @@ export declare class BaseAgent {
3157
3670
  * class (never the key), so a run's log shows which action drew which credential.
3158
3671
  */
3159
3672
  private buildRuntimeAPIKeyResolver;
3673
+ /**
3674
+ * The action context for one dispatch: the agent's own context object, by reference (do NOT spread —
3675
+ * spreading destroys class instances, losing getters/methods on typed contexts like SkipAgentContext),
3676
+ * stamped with the calling agent's identity, the run's active skills and its resolved storage account.
3677
+ */
3678
+ private stampActionContext;
3679
+ /**
3680
+ * The run's bounds handed to ONE action dispatch, beside its parameters. Per dispatch on purpose: the action
3681
+ * context IS params.context, shared by every action in the run (parallel ones included) and copied into
3682
+ * sub-agent runs, so anything stamped there would name the wrong action under parallel dispatch and travel
3683
+ * further than the action it was meant for. The model sets none of these.
3684
+ */
3685
+ private runBoundDispatchParams;
3686
+ /**
3687
+ * The audience readers for one dispatch: everyone who will see the result besides the user the action RUNS AS
3688
+ * ({@link ExecuteSingleAction}'s `contextUser`), which need not be the run's caller. The run's readers leave the
3689
+ * caller out; when the action runs as someone else, the caller sees its result too and is added, and the user it
3690
+ * runs as is left out (as the engine does). A run whose audience adds no reader stays without one.
3691
+ */
3692
+ private dispatchReaders;
3693
+ /**
3694
+ * The scope an action dispatch is handed: the run's, as {@link initializeAgentRun} validated and recorded it,
3695
+ * or — when {@link ExecuteSingleAction} is called outside {@link Execute} (the realtime tool path, tests,
3696
+ * harnesses) — resolved from these params the same way ({@link validatedRunScope}). A copy each time, so an
3697
+ * action cannot change what the next one sees.
3698
+ */
3699
+ private runScopeFor;
3700
+ /**
3701
+ * Logs one dispatched call's outcome and feeds the run-scoped circuit breaker, unless the caller does its own
3702
+ * failure accounting (`skipCircuitBreaker`). An `AUDIENCE_UNSUPPORTED` refusal locks the action out for the
3703
+ * run: no argument changes it, and the model is told the action is unavailable rather than to retry.
3704
+ */
3705
+ private recordDispatchOutcome;
3160
3706
  /**
3161
3707
  * This method executes one action using the MemberJunction Actions framework.
3162
3708
  * The full ActionResult objects are returned, allowing the caller to access result codes, output parameters,
3163
3709
  * and other execution details.
3164
3710
  *
3711
+ * The run's bound parameters (`ExecuteAgentParams.boundActionParams`) are applied first: a bound value
3712
+ * replaces whatever the model sent under its name, and a call the bindings refuse (a required parameter
3713
+ * bound to nothing, a binding naming no input of the action) returns a blocked `'fatal'` result without
3714
+ * dispatching and locks the action out for the rest of the run.
3715
+ *
3165
3716
  * @param {ExecuteAgentParams} params - Parameters from agent execution for context passing
3166
3717
  * @param {AgentAction} action - Action to execute
3167
3718
  * @param {UserInfo} [contextUser] - Optional user context for permissions
3168
3719
  * @param {ExecuteSingleActionOptions} [options] - `skipCircuitBreaker` bypasses the run-scoped
3169
- * circuit breaker for callers that do their own failure accounting (the pipeline executor)
3720
+ * circuit breaker for callers that do their own failure accounting (the pipeline executor);
3721
+ * `StepID` names the run step in the audit lines a bound parameter writes
3170
3722
  *
3171
3723
  * @returns {Promise<ActionResult>} ActionResult object from the action execution
3172
3724
  *
3173
3725
  * @throws {Error} If the action fails to execute
3174
3726
  */
3175
3727
  ExecuteSingleAction(params: ExecuteAgentParams, action: AgentAction, actionEntity: MJActionEntityExtended, contextUser?: UserInfo, options?: ExecuteSingleActionOptions): Promise<ActionResult>;
3728
+ /**
3729
+ * Checks per-(Agent, User) action policy narrowing rules (`MJ: AI Agent User Policies`)
3730
+ * before dispatching an action. Returns a synthetic ActionResult when the action is denied,
3731
+ * deferred outside a configured time window, or requires explicit user approval.
3732
+ */
3733
+ protected checkUserActionPolicy(params: ExecuteAgentParams, action: AgentAction, actionEntity: MJActionEntityExtended, contextUser?: UserInfo): ActionResult | null;
3176
3734
  /**
3177
3735
  * Makes a SLICED conversation window safe to send on its own.
3178
3736
  *
@@ -3249,6 +3807,18 @@ export declare class BaseAgent {
3249
3807
  * ```
3250
3808
  */
3251
3809
  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>>;
3810
+ /**
3811
+ * A sub-agent request's template parameters without the host-only run-data keys
3812
+ * (`HOST_ONLY_AGENT_RUN_DATA_KEYS` in `@memberjunction/ai-core-plus`: the reserved scope family and
3813
+ * `__agentTypePromptParams`, and the browser, conversation and realtime controls — `clientTools`, `sessionID`,
3814
+ * `appContext`, `applicationId`, `conversationId`, `targetAgentID`, `agentSessionId`, `recording`, `realtime*`).
3815
+ * They are merged into the child's `data`, which `BaseAgent` reads for all of these, and inside a Loop agent they
3816
+ * are written by the model — so left in, a model could set a sub-agent's tenant (whenever the parent's run trusts
3817
+ * its `data`), offer it client tools, inject an app context, or point it at another conversation. The child
3818
+ * inherits the parent's values instead (its own params, and the parent's `data` as is). What was removed is
3819
+ * logged once, by key only — never the values.
3820
+ */
3821
+ private subAgentTemplateParameters;
3252
3822
  /**
3253
3823
  * Formats sub-agent details as compact markdown for inclusion in prompt context.
3254
3824
  *
@@ -3279,7 +3849,11 @@ export declare class BaseAgent {
3279
3849
  * Produces ~75% fewer tokens than the previous JSON format while preserving
3280
3850
  * all information the LLM needs to invoke actions correctly.
3281
3851
  *
3852
+ * A parameter the run binds (`ExecuteAgentParams.boundActionParams`) is left out, so the model is
3853
+ * never told it exists. With no bindings the output is the cached catalog's, unchanged.
3854
+ *
3282
3855
  * @param {MJActionEntityExtended[]} actions - Array of action entities
3856
+ * @param {BoundActionParams} [boundActionParams] - The run's bindings, when it has any
3283
3857
  * @returns {string} Markdown formatted string with action details
3284
3858
  * @private
3285
3859
  */
@@ -3325,7 +3899,7 @@ export declare class BaseAgent {
3325
3899
  * like one the loop wrote. See the Actions step for why it is a user-role annotation.
3326
3900
  * @protected
3327
3901
  */
3328
- protected buildActionInvocationMessage(actions: AgentAction[]): string;
3902
+ protected buildActionInvocationMessage(actions: AgentAction[], params: ExecuteAgentParams): string;
3329
3903
  /**
3330
3904
  * The action-results message body: a header naming any failures, then each result in the
3331
3905
  * compact markdown shape. Shared by the live Actions step and the stopped-run resume.
@@ -3580,20 +4154,77 @@ export declare class BaseAgent {
3580
4154
  };
3581
4155
  }): Promise<MJAIAgentRunStepEntityExtended>;
3582
4156
  /**
3583
- * Finalizes a step entity with completion status.
4157
+ * Finds the step whose `PayloadAtEnd` a new step's start payload repeats, so the new step stores a
4158
+ * pointer to it (`PayloadAtStartSourceStepID`) instead of a second copy. Call it before the new step
4159
+ * is added to the run's `Steps`.
3584
4160
  *
3585
- * @private
3586
- * @param {MJAIAgentRunStepEntityExtended} stepEntity - The step entity to finalize
3587
- * @param {boolean} success - Whether the step was successful
3588
- * @param {string} [errorMessage] - Optional error message
3589
- * @param {any} [outputData] - Optional output data to capture for this step
4161
+ * The candidate is the latest step in the run that is not `Running` and has a `PayloadAtEnd` (or
4162
+ * `PayloadAtEndSourceStepID`). Only that step is compared. If that step itself points to an earlier
4163
+ * step via `PayloadAtEndSourceStepID`, the pointer resolves in one hop to the step that actually
4164
+ * holds the stored `PayloadAtEnd`.
4165
+ * - Running steps are skipped because their end can still change: parallel sub-agent siblings write
4166
+ * their own result as `PayloadAtEnd` when they finish, and a ForEach step writes its end after all
4167
+ * of its child steps.
4168
+ * - Finished steps with no end (tool, compaction and finish-check steps) are skipped because they never
4169
+ * get one, and would hide the step that produced the payload.
4170
+ * - If the matching candidate's INSERT is still in flight (`!step.IsSaved`), {@link createStepEntity}
4171
+ * chains the new step's INSERT after `step` on {@link _stepSaveQueue} (and falls back to storing inline
4172
+ * `PayloadAtStart` if the candidate's INSERT fails) so `FK_AIAgentRunStep_PayloadAtStartSourceStepID`
4173
+ * is always satisfied without sacrificing deduplication on fast back-to-back turns.
4174
+ *
4175
+ * Rule: a step's `PayloadAtEnd` must not change after a later step points at it, because readers take
4176
+ * the pointing step's start payload from it. The comparison uses the in-memory end, so the saved end
4177
+ * must match it: `finalizeStepEntity` re-applies the end after the INSERT lands, and an end set after
4178
+ * `finalizeStepEntity` is saved with `queueStepSave`.
4179
+ *
4180
+ * @param serializedStart The new step's start payload, already serialized.
4181
+ * @returns The step to point at, or undefined when the start payload must be stored.
4182
+ */
4183
+ private findPayloadAtStartSource;
4184
+ /**
4185
+ * Finds the earlier step whose stored `PayloadAtEnd` this step's end payload repeats, so the step
4186
+ * stores a one-hop pointer (`PayloadAtEndSourceStepID`) instead of a second copy.
4187
+ */
4188
+ private findPayloadAtEndSource;
4189
+ private findPayloadEndSourceBefore;
4190
+ /**
4191
+ * Returns true when neither `serializePayloadAtStart` nor `serializePayloadAtEnd` has been
4192
+ * overridden by a subclass, allowing unchanged start payloads to be reused as end payloads
4193
+ * without a second `JSON.stringify` pass.
4194
+ */
4195
+ private hasDefaultPayloadSerializers;
4196
+ /**
4197
+ * Resolves a step's start payload from its own `PayloadAtStart` or the step referenced by
4198
+ * `PayloadAtStartSourceStepID`.
4199
+ */
4200
+ private resolveStepPayloadAtStart;
4201
+ /**
4202
+ * Resolves a step's end payload from its own `PayloadAtEnd` or the step referenced by
4203
+ * `PayloadAtEndSourceStepID`.
3590
4204
  */
4205
+ private resolveStepPayloadAtEnd;
3591
4206
  /**
3592
4207
  * Builds a summary of payload change results for storage
3593
4208
  * @param changeResult The result from PayloadManager operations
3594
4209
  * @returns A serializable summary object
3595
4210
  */
3596
4211
  private buildPayloadChangeResultSummary;
4212
+ /**
4213
+ * Captures the conversation messages for a `Prompt` step's `InputData` without
4214
+ * persisting volatile `<mj-runtime-state>` envelopes or repeating messages already
4215
+ * recorded in an earlier `Prompt` step of the current run.
4216
+ *
4217
+ * - When the non-volatile stack extends the previous Prompt step's recorded stack append-only (the
4218
+ * same messages, unchanged, at the same positions), only the appended messages are stored, tagged
4219
+ * with `conversationMessagesDelta: true`.
4220
+ * - Otherwise (the first Prompt step of the run, or a message was replaced, removed or changed by
4221
+ * expiry, compaction or expansion) the full non-volatile stack is stored, with no delta flag.
4222
+ *
4223
+ * {@link buildResumedStoppedRunTurns} rebuilds the stack from the latest full stack plus the deltas after it.
4224
+ */
4225
+ private capturePromptStepMessages;
4226
+ /** True when `current` starts with every message of `previous`, by reference and unchanged in place. @private */
4227
+ private static isAppendOnlyExtension;
3597
4228
  /**
3598
4229
  * Finalizes a step entity with completion status. Pairs with `createStepEntity`
3599
4230
  * — drivers that create custom steps should also finalize them through this
@@ -3601,6 +4232,9 @@ export declare class BaseAgent {
3601
4232
  * populated consistently and the UPDATE is sequenced behind the INSERT via
3602
4233
  * `queueStepSave`.
3603
4234
  *
4235
+ * Set `PayloadAtEnd` before calling it: the queued UPDATE re-applies the end the step has now.
4236
+ * An end set later must be saved with `queueStepSave`.
4237
+ *
3604
4238
  * @protected
3605
4239
  */
3606
4240
  protected finalizeStepEntity(stepEntity: MJAIAgentRunStepEntityExtended, success: boolean, errorMessage?: string, outputData?: any): Promise<void>;
@@ -3643,6 +4277,29 @@ export declare class BaseAgent {
3643
4277
  * @returns {string} - The formatted message with hierarchy breadcrumb
3644
4278
  */
3645
4279
  protected formatHierarchicalMessage(baseMessage: string): string;
4280
+ /**
4281
+ * Builds the user-oriented initialization progress message for an agent run.
4282
+ *
4283
+ * - Root agent (`_depth === 0`): `'Getting ready...'`
4284
+ * - Direct sub-agent (`_depth === 1`): `'Starting <SubAgentName>...'`
4285
+ * - Nested sub-agent (`_depth > 1`): `'<ParentBreadcrumb>: Starting <SubAgentName>...'`
4286
+ *
4287
+ * @protected
4288
+ * @param {ExecuteAgentParams} params - Execution parameters for the current agent
4289
+ * @returns {string} Formatted initialization progress message
4290
+ */
4291
+ protected buildInitializationProgressMessage(params: ExecuteAgentParams): string;
4292
+ /**
4293
+ * Builds a user-oriented progress message for a prompt execution step without
4294
+ * exposing internal framework terminology ("initial prompt", "payload", "context")
4295
+ * or duplicating the sub-agent name when prefixed by {@link formatHierarchicalMessage}.
4296
+ *
4297
+ * @protected
4298
+ * @param {ExecuteAgentParams} params - Execution parameters for the current agent
4299
+ * @param {BaseAgentNextStep | null} [previousDecision] - Previous step decision when re-prompting
4300
+ * @returns {string} Base progress message (before `formatHierarchicalMessage` breadcrumb prefixing)
4301
+ */
4302
+ protected buildPromptProgressMessage(params: ExecuteAgentParams, previousDecision?: BaseAgentNextStep | null): string;
3646
4303
  /**
3647
4304
  * Trims a step name to what `AIAgentRunStep.StepName` can hold. Step names are built from free
3648
4305
  * text — a termination message quoting a provider's error, a tool name with its arguments, the
@@ -3749,6 +4406,14 @@ export declare class BaseAgent {
3749
4406
  * @param subAgentPayloadOverride - Optional payload override for sub-agent execution, if provided the normal payload computation is skipped
3750
4407
  */
3751
4408
  private executeChildSubAgentStep;
4409
+ /**
4410
+ * Extracts the workflow root task ID (`parentTaskID`) from a sub-agent run that parked on a
4411
+ * durable task graph (`Status === 'Paused'`), falling back to the sub-agent run ID so the
4412
+ * parent run's `_awaitingWorkflowTaskID` is guaranteed non-null when parking.
4413
+ *
4414
+ * @protected
4415
+ */
4416
+ protected extractSubAgentWorkflowTaskID(subAgentRun: MJAIAgentRunEntityExtended | undefined): string;
3752
4417
  /**
3753
4418
  * Routes sub-agent execution to the appropriate handler based on relationship type.
3754
4419
  * Child agents (ParentID) use direct payload coupling.
@@ -3773,7 +4438,7 @@ export declare class BaseAgent {
3773
4438
  *
3774
4439
  * @protected
3775
4440
  */
3776
- protected resolveSubAgentByName(params: ExecuteAgentParams, name: string): {
4441
+ protected resolveSubAgentByName(params: ExecuteAgentParams, name: string, allowAnyActiveAgent?: boolean): {
3777
4442
  subAgentEntity: MJAIAgentEntityExtended;
3778
4443
  relationship?: MJAIAgentRelationshipEntity;
3779
4444
  } | undefined;
@@ -4007,10 +4672,13 @@ export declare class BaseAgent {
4007
4672
  *
4008
4673
  * @private
4009
4674
  */
4675
+ /** The assistant message describing a client-tools step's invocations. */
4676
+ private describeClientToolInvocations;
4010
4677
  /**
4011
4678
  * Execute client-side tools requested by the agent.
4012
4679
  * Sends each tool invocation via PubSub, awaits the client's response
4013
4680
  * (or timeout), then adds results to the conversation and continues.
4681
+ * Refused under an audience ({@link clientToolsRefusal}).
4014
4682
  */
4015
4683
  private executeClientToolsStep;
4016
4684
  /**
@@ -4294,6 +4962,15 @@ export declare class BaseAgent {
4294
4962
  */
4295
4963
  protected buildPlanApprovalForm(planText: string): AgentResponseForm;
4296
4964
  private executeChatStep;
4965
+ /**
4966
+ * Raises the persistent `MJ: AI Agent Requests` row for a root agent's Chat or Plan step ({@link createFeedbackRequest}),
4967
+ * so it can be answered outside the conversation — except when the run's audience adds a reader. A request answered
4968
+ * on the dashboard or through the API resumes the run (`MJAIAgentRequestEntityServer.resumeAgent`) as the responder,
4969
+ * in the original conversation, with no audience: neither the request nor the run row has a field that can carry
4970
+ * one without a new column. So a shared conversation's run raises none: its question or plan still reaches the room,
4971
+ * which answers in the conversation, where the host starts the next run with the room's audience.
4972
+ */
4973
+ private raiseFeedbackRequest;
4297
4974
  /**
4298
4975
  * Creates a persistent AIAgentRequest row when a Chat step fires.
4299
4976
  * Resolves the target user via the assignment chain:
@@ -4350,10 +5027,10 @@ export declare class BaseAgent {
4350
5027
  * - If there's a responseForm with fields, uses "Information"
4351
5028
  * - Otherwise defaults to "Information"
4352
5029
  *
4353
- * Caches the request type lookup for the duration of this agent execution.
5030
+ * Request types come from the AI engine's cached `MJ: AI Agent Request Types` rows
5031
+ * (`AIEngineBase.ResolveAgentRequestTypeID`), the same source the agent actions use.
4354
5032
  * @private
4355
5033
  */
4356
- private _requestTypeCache;
4357
5034
  private resolveRequestTypeId;
4358
5035
  /**
4359
5036
  * Inspects an AgentResponseForm to determine the best request type name.
@@ -4493,13 +5170,23 @@ export declare class BaseAgent {
4493
5170
  */
4494
5171
  private completeWhileLoop;
4495
5172
  /**
4496
- * Creates a failure result with proper tracking.
5173
+ * Flushes any in-flight `MJAIPromptRunEntityExtended` saves queued on {@link _promptRunner}.
5174
+ * Tolerates lightweight test doubles on `_promptRunner` that may only implement
5175
+ * `WaitForPendingPromptRunSaves` or neither method.
5176
+ *
5177
+ * @private
5178
+ */
5179
+ private flushPromptRunnerSaves;
5180
+ /**
5181
+ * Creates a failure result with proper tracking, draining all queued step and prompt-run saves
5182
+ * before persisting the failed run row so no orphan step or prompt-run writes remain in flight.
4497
5183
  *
4498
5184
  * @private
4499
5185
  */
4500
5186
  private createFailureResult;
4501
5187
  /**
4502
- * Creates a cancelled result.
5188
+ * Creates a cancelled result, draining all queued step and prompt-run saves before persisting
5189
+ * the cancelled run row so no orphan step or prompt-run writes remain in flight.
4503
5190
  *
4504
5191
  * @private
4505
5192
  * @param {string} message - The cancellation message
@@ -4519,15 +5206,19 @@ export declare class BaseAgent {
4519
5206
  * (array order is spawn order, which a sub-step can interleave).
4520
5207
  */
4521
5208
  static LastStepPayload(steps: ReadonlyArray<{
5209
+ ID?: string;
4522
5210
  StepNumber: number;
5211
+ PayloadAtStart?: string | null;
4523
5212
  PayloadAtEnd: string | null;
5213
+ PayloadAtStartSourceStepID?: string | null;
5214
+ PayloadAtEndSourceStepID?: string | null;
4524
5215
  }> | null | undefined): string | null;
4525
5216
  /**
4526
5217
  * Finalizes the agent run with success.
4527
5218
  *
4528
- * @private
5219
+ * @protected
4529
5220
  */
4530
- private finalizeAgentRun;
5221
+ protected finalizeAgentRun<P>(finalStep: BaseAgentNextStep, payload?: P, contextUser?: UserInfo): Promise<ExecuteAgentResult<P>>;
4531
5222
  /**
4532
5223
  * Calculate total token statistics from the agent run's persisted steps.
4533
5224
  *
@@ -4674,6 +5365,50 @@ export declare class BaseAgent {
4674
5365
  * @private
4675
5366
  */
4676
5367
  private applyCompactionToLiveMessages;
5368
+ /**
5369
+ * Executes post-run conversation message pre-compaction, scratchpad pruning, and
5370
+ * asynchronous memory extraction after an agent run completes (`finalizeAgentRun`).
5371
+ *
5372
+ * Shifting compaction and maintenance to the end of `finalizeAgentRun` removes
5373
+ * compaction latency from the next user turn's critical path so subsequent turns
5374
+ * start with a pre-compacted message window.
5375
+ *
5376
+ * ### Lifecycle Phases
5377
+ * 1. **Configuration Resolution**: Reads `params.compactAfterRun` (`boolean | AgentPostRunCompactionConfig`).
5378
+ * When `undefined`, `false`, or `{ enabled: false }`, returns immediately as a no-op.
5379
+ * When `true`, applies defaults `{ enabled: true, messageCountThreshold: 20, extractMemories: true }`.
5380
+ * 2. **Message Window Pre-Compaction**: When `params.conversationMessages.length >= messageCountThreshold`,
5381
+ * compacts older messages in `[1 .. length - preserveRecentCount - 1]` while preserving
5382
+ * the initial goal message (`index 0`) and the most recent messages intact. Delegates to
5383
+ * {@link compactMessage} (and {@link CompactToolResultContent} for native tool turns) so
5384
+ * behavior and expansion metadata (`wasCompacted`, `originalContent`, `canExpand`) are
5385
+ * 100% consistent with mid-run message compaction.
5386
+ * 3. **Scratchpad Pruning**: When `maxScratchpadNotes` is configured, prunes excess low-priority
5387
+ * scratchpad note lines (via {@link ScratchpadManager.PruneNotes}) and completed tasks
5388
+ * (via {@link ScratchpadManager.EnforceTaskLimit}) down to `maxScratchpadNotes`.
5389
+ * 4. **Memory Extraction Trigger**: When `extractMemories !== false` and `agentRun.Success` is `true`,
5390
+ * triggers asynchronous note/example extraction via {@link triggerPostRunMemoryExtraction}.
5391
+ *
5392
+ * Every phase is wrapped in its own `try/catch` block so an error in one phase is logged
5393
+ * via `LogError` without aborting the remaining phases or failing the completed agent run.
5394
+ *
5395
+ * @param params - The execution parameters for the completed agent run
5396
+ * @param agentRun - The finalized `MJAIAgentRunEntityExtended` record
5397
+ * @protected
5398
+ */
5399
+ protected runPostRunCompaction(params: ExecuteAgentParams, agentRun: MJAIAgentRunEntityExtended): Promise<void>;
5400
+ /**
5401
+ * Triggers asynchronous post-run note and example extraction via `MemoryManagerAgent`
5402
+ * when the executing agent has memory injection (`InjectNotes` or `InjectExamples`) enabled.
5403
+ *
5404
+ * No-ops when the executing agent itself is the `MemoryManagerAgent` (preventing recursion)
5405
+ * or when no active `MemoryManagerAgent` is registered in `AIEngine`.
5406
+ *
5407
+ * @param params - The execution parameters for the completed agent run
5408
+ * @param agentRun - The finalized `MJAIAgentRunEntityExtended` record
5409
+ * @protected
5410
+ */
5411
+ protected triggerPostRunMemoryExtraction(params: ExecuteAgentParams, agentRun: MJAIAgentRunEntityExtended): Promise<void>;
4677
5412
  /**
4678
5413
  * Creates an AIAgentRunStep for message compaction operations.
4679
5414
  * Records the compaction attempt with context about the message being compacted.
@@ -4696,7 +5431,7 @@ export declare class BaseAgent {
4696
5431
  */
4697
5432
  protected updateCompactionStep(step: MJAIAgentRunStepEntityExtended, result: AIPromptRunResult<{
4698
5433
  summary: string;
4699
- }>, message: AgentChatMessage, params: ExecuteAgentParams): Promise<void>;
5434
+ }>, message: AgentChatMessage, _params: ExecuteAgentParams): Promise<void>;
4700
5435
  /**
4701
5436
  * Compacts a message using configured compaction mode.
4702
5437
  *
@@ -4839,6 +5574,42 @@ export declare class BaseAgent {
4839
5574
  * for the paths where they differed.
4840
5575
  */
4841
5576
  protected getValueFromPath(obj: unknown, path: string): unknown;
5577
+ /**
5578
+ * The run's scope inputs: the explicit `ExecuteAgentParams` fields, else their `data` fallbacks, which count only
5579
+ * when the caller set `TrustReservedRunData`. {@link Execute} has already cleaned `data`; the rule is applied here
5580
+ * again for {@link ExecuteSingleAction} called outside a run (the realtime tool path, harnesses).
5581
+ */
5582
+ private runScopeInputs;
5583
+ /**
5584
+ * Secondary scopes as the run takes them: a plain object of dimension values, else none. A host assembles them at
5585
+ * runtime (often through `data`), so anything else — a JSON string, an array, a class instance — is not read as
5586
+ * dimensions (its keys would be character indexes or properties); it is logged and the run carries no secondary scope.
5587
+ */
5588
+ private scopeDimensions;
5589
+ /**
5590
+ * The run's scope as memory, retrieval and scoped prompt configuration take it: the scope {@link initializeAgentRun}
5591
+ * validated and wrote to the run row (`_runScope`; resolved the same way, {@link validatedRunScope}, outside a run),
5592
+ * with the primary entity resolved to its ID. One source, so notes and examples, pre-execution RAG, scoped prompt
5593
+ * parts and configs, the run row and every action dispatch see the same tenant and dimensions — trimmed, with the
5594
+ * agent's `ScopeConfig` defaults applied, and never a `data` scope the caller was not trusted to set.
5595
+ */
5596
+ private runScopeForContext;
5597
+ /** The run's scope ({@link runScopeForContext}) in the shape `ApplyScopedPromptConfig` takes. */
5598
+ private scopedPromptConfigScope;
5599
+ /** A scope identifier as text: a non-blank string (trimmed) or a number; anything else is no value. */
5600
+ private scopeText;
5601
+ /**
5602
+ * The run's scope as the run row records it and every action dispatch is handed it: the inputs from
5603
+ * {@link runScopeInputs}, the secondary dimensions validated with the agent's configured defaults applied
5604
+ * ({@link validateAndApplySecondaryScopes}), and `null` for whatever the run does not carry.
5605
+ */
5606
+ private validatedRunScope;
5607
+ /**
5608
+ * Writes the validated run scope onto the run row: the primary entity resolved to its ID (logged when it is
5609
+ * not in metadata), the tenant record ID and the secondary dimensions as JSON. A secondary-only scope on an
5610
+ * agent whose ScopeConfig does not allow one is logged, and still recorded.
5611
+ */
5612
+ private writeRunScope;
4842
5613
  /**
4843
5614
  * Parse the agent's SecondaryScopeConfig from the ScopeConfig field.
4844
5615
  * Returns null if not configured or invalid JSON.