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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +94 -7
  2. package/dist/AgentRunner.d.ts +6 -3
  3. package/dist/AgentRunner.d.ts.map +1 -1
  4. package/dist/AgentRunner.js +163 -38
  5. package/dist/AgentRunner.js.map +1 -1
  6. package/dist/ArtifactToolManager.d.ts +11 -3
  7. package/dist/ArtifactToolManager.d.ts.map +1 -1
  8. package/dist/ArtifactToolManager.js +72 -6
  9. package/dist/ArtifactToolManager.js.map +1 -1
  10. package/dist/ClientToolRequestManager.d.ts +11 -1
  11. package/dist/ClientToolRequestManager.d.ts.map +1 -1
  12. package/dist/ClientToolRequestManager.js +19 -6
  13. package/dist/ClientToolRequestManager.js.map +1 -1
  14. package/dist/PayloadChangeAnalyzer.d.ts.map +1 -1
  15. package/dist/PayloadChangeAnalyzer.js +53 -30
  16. package/dist/PayloadChangeAnalyzer.js.map +1 -1
  17. package/dist/PayloadManager.d.ts +35 -2
  18. package/dist/PayloadManager.d.ts.map +1 -1
  19. package/dist/PayloadManager.js +250 -149
  20. package/dist/PayloadManager.js.map +1 -1
  21. package/dist/ScratchpadManager.d.ts +18 -0
  22. package/dist/ScratchpadManager.d.ts.map +1 -1
  23. package/dist/ScratchpadManager.js +61 -0
  24. package/dist/ScratchpadManager.js.map +1 -1
  25. package/dist/agent-audience.d.ts +38 -0
  26. package/dist/agent-audience.d.ts.map +1 -0
  27. package/dist/agent-audience.js +99 -0
  28. package/dist/agent-audience.js.map +1 -0
  29. package/dist/agent-context-injector.d.ts +17 -2
  30. package/dist/agent-context-injector.d.ts.map +1 -1
  31. package/dist/agent-context-injector.js +23 -7
  32. package/dist/agent-context-injector.js.map +1 -1
  33. package/dist/agent-memory-context-builder.d.ts +7 -2
  34. package/dist/agent-memory-context-builder.d.ts.map +1 -1
  35. package/dist/agent-memory-context-builder.js +12 -3
  36. package/dist/agent-memory-context-builder.js.map +1 -1
  37. package/dist/agent-pre-execution-rag.d.ts +101 -9
  38. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  39. package/dist/agent-pre-execution-rag.js +224 -23
  40. package/dist/agent-pre-execution-rag.js.map +1 -1
  41. package/dist/agent-types/flow-agent-type.d.ts +8 -0
  42. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  43. package/dist/agent-types/flow-agent-type.js +48 -6
  44. package/dist/agent-types/flow-agent-type.js.map +1 -1
  45. package/dist/agent-types/loop-agent-response-type.d.ts +8 -2
  46. package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
  47. package/dist/agent-types/loop-agent-response-type.js.map +1 -1
  48. package/dist/agent-types/loop-agent-type.d.ts +9 -2
  49. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  50. package/dist/agent-types/loop-agent-type.js +60 -16
  51. package/dist/agent-types/loop-agent-type.js.map +1 -1
  52. package/dist/base-agent.d.ts +568 -31
  53. package/dist/base-agent.d.ts.map +1 -1
  54. package/dist/base-agent.js +2294 -421
  55. package/dist/base-agent.js.map +1 -1
  56. package/dist/index.d.ts +4 -0
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +4 -0
  59. package/dist/index.js.map +1 -1
  60. package/dist/memory-manager-agent.d.ts.map +1 -1
  61. package/dist/memory-manager-agent.js +46 -34
  62. package/dist/memory-manager-agent.js.map +1 -1
  63. package/dist/native-tools/action-param-schema.d.ts +57 -0
  64. package/dist/native-tools/action-param-schema.d.ts.map +1 -0
  65. package/dist/native-tools/action-param-schema.js +238 -0
  66. package/dist/native-tools/action-param-schema.js.map +1 -0
  67. package/dist/native-tools/action-tool-builder.d.ts +5 -4
  68. package/dist/native-tools/action-tool-builder.d.ts.map +1 -1
  69. package/dist/native-tools/action-tool-builder.js +29 -71
  70. package/dist/native-tools/action-tool-builder.js.map +1 -1
  71. package/dist/native-tools/json-argument.d.ts +41 -0
  72. package/dist/native-tools/json-argument.d.ts.map +1 -0
  73. package/dist/native-tools/json-argument.js +79 -0
  74. package/dist/native-tools/json-argument.js.map +1 -0
  75. package/dist/query-builder-agent.d.ts +13 -4
  76. package/dist/query-builder-agent.d.ts.map +1 -1
  77. package/dist/query-builder-agent.js +102 -27
  78. package/dist/query-builder-agent.js.map +1 -1
  79. package/dist/realtime/realtime-client-session-service.d.ts +5 -4
  80. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  81. package/dist/realtime/realtime-client-session-service.js +42 -30
  82. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  83. package/dist/realtime/realtime-coagent-config.d.ts +8 -1
  84. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  85. package/dist/realtime/realtime-coagent-config.js +17 -1
  86. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  87. package/dist/realtime/realtime-recording-ledger.d.ts +130 -0
  88. package/dist/realtime/realtime-recording-ledger.d.ts.map +1 -0
  89. package/dist/realtime/realtime-recording-ledger.js +190 -0
  90. package/dist/realtime/realtime-recording-ledger.js.map +1 -0
  91. package/dist/realtime/realtime-recording-opus-assembly.d.ts +211 -0
  92. package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -0
  93. package/dist/realtime/realtime-recording-opus-assembly.js +706 -0
  94. package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -0
  95. package/dist/realtime/realtime-recording-store.d.ts +38 -1
  96. package/dist/realtime/realtime-recording-store.d.ts.map +1 -1
  97. package/dist/realtime/realtime-recording-store.js +58 -30
  98. package/dist/realtime/realtime-recording-store.js.map +1 -1
  99. package/dist/realtime/realtime-turn-moderator.d.ts +2 -1
  100. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  101. package/dist/realtime/realtime-turn-moderator.js +7 -1
  102. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  103. package/dist/volatile-child-prompt.js +3 -3
  104. package/package.json +21 -19
@@ -10,7 +10,7 @@
10
10
  * @author MemberJunction.com
11
11
  * @since 2.49.0
12
12
  */
13
- import { MJAIAgentTypeEntity, MJTemplateParamEntity, MJAIAgentRelationshipEntity, MJAIAgentNoteEntity, MJAIAgentExampleEntity, MJAISkillEntity, MJAIVendorEntity, 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
15
  import { MJAIAgentRunEntityExtended, MJAIAgentRunStepEntityExtended, MJAIPromptEntityExtended, MJAIAgentEntityExtended, MJAIModelEntityExtended, MJAIPromptRunEntityExtended } from "@memberjunction/ai-core-plus";
16
16
  import { UserInfo, IMetadataProvider } from '@memberjunction/core';
@@ -26,9 +26,10 @@ import { CompactionOutcome, EffectiveContextBudget } from './ConversationCompact
26
26
  import { ConversationToolCall, ConversationToolExecutionResult, ConversationToolSummaryHost } from './ConversationToolManager.js';
27
27
  import { CarryForwardStepRecord, StoppedRunStepRecord } from './tool-result-format.js';
28
28
  import { AgentPreExecutionRAGResult } from './agent-pre-execution-rag.js';
29
- import { AIPromptParams, AIPromptRunResult, ExecuteAgentParams, AgentConfiguration, ExecuteAgentResult, AgentAction, AgentSubAgentRequest, BaseAgentNextStep, MessageLifecycleEvent, AgentChatMessage, AgentChatMessageMetadata, AIModelSelectionInfo, ActionChange, ActionChangeScope, SubAgentChange, MediaOutput, FileOutputRef, SecondaryScopeConfig, SecondaryScopeValue, AgentResponseForm, AgentPipelineRequest, AgentSkillActivationRequest, AgentSkillInvocation, SkillAvailabilityPurpose, AgentDecisionRequest, AgentDecisionResult, AgentDecisionAnswerSummary, StopContinuationMode } from '@memberjunction/ai-core-plus';
29
+ import { AIPromptParams, AIPromptRunResult, ExecuteAgentParams, AgentTreeBudget, AgentConfiguration, ExecuteAgentResult, AgentAction, AgentSubAgentRequest, BaseAgentNextStep, MessageLifecycleEvent, AgentChatMessage, AgentChatMessageMetadata, AIModelSelectionInfo, ActionChange, ActionChangeScope, SubAgentChange, MediaOutput, FileOutputRef, SecondaryScopeConfig, SecondaryScopeValue, AgentResponseForm, AgentPipelineRequest, AgentSkillActivationRequest, AgentSkillInvocation, SkillAvailabilityPurpose, AgentDecisionRequest, AgentDecisionResult, AgentDecisionAnswerSummary, StopContinuationMode } from '@memberjunction/ai-core-plus';
30
30
  import { MJActionEntityExtended, ActionResult, ActionParam, AIDirective } from '@memberjunction/actions-base';
31
31
  import { RuntimeStateDateTime, RuntimeStateScratchpad } from './runtime-state-fragment.js';
32
+ import { ScratchpadManager } from './ScratchpadManager.js';
32
33
  import { ArtifactToolCall, StoredToolResult } from './ArtifactToolManager.js';
33
34
  import { MemoryWriteRequest, MemoryWriteResult } from './MemoryWriteManager.js';
34
35
  import { AgentDecisionService } from './AgentDecisionService.js';
@@ -101,12 +102,15 @@ export interface ExecuteSingleActionOptions {
101
102
  *
102
103
  * - `'fatal'` — the action failed earlier in the run with a configuration or credential error and is
103
104
  * locked out for the rest of the run.
105
+ * - `'audience'` — the action engine refused the action for the run's audience (`AUDIENCE_UNSUPPORTED`): it cannot
106
+ * limit what it returns to what everyone in a shared conversation may see, so it is locked out for the run. Not a
107
+ * configuration or credential error, and the model is told so.
104
108
  * - `'identical-arguments'` — the action already failed {@link IDENTICAL_FAILURE_THRESHOLD} times
105
109
  * with these exact arguments.
106
110
  * - `'attempts-exhausted'` — the action has failed {@link ACTION_FAILURE_BUDGET} consecutive times
107
111
  * across any arguments.
108
112
  */
109
- export type ActionCircuitBreakerReason = 'fatal' | 'identical-arguments' | 'attempts-exhausted';
113
+ export type ActionCircuitBreakerReason = 'fatal' | 'audience' | 'identical-arguments' | 'attempts-exhausted';
110
114
  /** Identical-arguments rule: this many failures with the same arguments block further identical calls. */
111
115
  export declare const IDENTICAL_FAILURE_THRESHOLD = 2;
112
116
  /** Attempt budget: this many consecutive failures, across any arguments, disable the action for the run. */
@@ -203,6 +207,18 @@ export declare class BaseAgent {
203
207
  * @private
204
208
  */
205
209
  private _executeParams;
210
+ /**
211
+ * Shared root-tree cumulative budget tracking object for the current execution tree.
212
+ * Initialized at the start of {@link Execute} (or inherited from `params.treeBudget`
213
+ * when running as a sub-agent) and forwarded to all child and related sub-agent runs.
214
+ * @protected
215
+ */
216
+ protected _treeBudget: AgentTreeBudget | undefined;
217
+ /**
218
+ * Gets the shared {@link AgentTreeBudget} tracking cumulative steps, tokens, cost,
219
+ * and elapsed wall-clock duration across the root agent and all descendant sub-agents.
220
+ */
221
+ get TreeBudget(): AgentTreeBudget | undefined;
206
222
  /**
207
223
  * The agent configuration loaded for the current run — captured so the cross-turn
208
224
  * compaction hooks can resolve type-level budget defaults without re-loading.
@@ -241,6 +257,30 @@ export declare class BaseAgent {
241
257
  * @private
242
258
  */
243
259
  private _fatalActionFailures;
260
+ /**
261
+ * Actions the action engine refused for the run's audience (`AUDIENCE_UNSUPPORTED`) during the current run —
262
+ * locked out like {@link _fatalActionFailures}, under their own breaker reason (`'audience'`) so the model is
263
+ * told the action is unavailable in a shared conversation rather than misconfigured.
264
+ * @private
265
+ */
266
+ private _audienceLockedActions;
267
+ /**
268
+ * The run's audience readers beyond the caller (`ExecuteAgentParams.Audience`), hydrated from the user cache:
269
+ * `[]` when the audience adds nobody, `undefined` until hydrated for this run. Set after the permission check
270
+ * in {@link Execute}; {@link ExecuteSingleAction}, which is also called directly, hydrates it lazily.
271
+ * @private
272
+ */
273
+ private _audienceReaders;
274
+ /** The `ExecuteAgentParams.Audience` that {@link _audienceReaders} was hydrated from, so a different one re-hydrates. */
275
+ private _audienceSource;
276
+ /**
277
+ * The scope of the run in progress, exactly as {@link initializeAgentRun} validated and wrote it to the run row
278
+ * (nulls when the run is unscoped) — what every action dispatch is handed as `RunActionParams.RunScope`.
279
+ * `undefined` outside {@link Execute}: {@link ExecuteSingleAction}, which is also called directly, then
280
+ * resolves the scope from its params the same way.
281
+ * @private
282
+ */
283
+ private _runScope;
244
284
  /**
245
285
  * Parameter-aware failure tracking per action name for the current agent run.
246
286
  * Differentiates identical retries (which trip quickly) from parameter modifications (which allow self-correction).
@@ -323,6 +363,18 @@ export declare class BaseAgent {
323
363
  * consecutive-attempt budget.
324
364
  */
325
365
  protected recordActionFailure(action: AgentAction, actionEntity: MJActionEntityExtended | undefined, message: string | null | undefined, normalizedParams: string): void;
366
+ /**
367
+ * Locks an action out for the rest of the run: later calls short-circuit on the breaker's `'fatal'` rule, or on
368
+ * its `'audience'` rule for an action the engine refused for the run's audience.
369
+ */
370
+ private lockOutAction;
371
+ /** Clears the run-scoped circuit-breaker state (both lockouts and the failure history) for a new run. */
372
+ private resetActionCircuitBreaker;
373
+ /**
374
+ * The blocked result for an action locked out for the run — refused for the audience (`'audience'`), or failed
375
+ * with an unrecoverable configuration or credential error (`'fatal'`) — or null when it is not locked out.
376
+ */
377
+ private lockedOutActionResult;
326
378
  /**
327
379
  * Clears the parameter-aware failure history for an action after it succeeds, so the
328
380
  * identical-arguments rule and the consecutive-attempt budget start over.
@@ -331,7 +383,7 @@ export declare class BaseAgent {
331
383
  /**
332
384
  * Applies the three circuit-breaker rules to a call that is about to be dispatched. Returns a
333
385
  * 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.
386
+ * null when it may proceed. Rules are checked audience → fatal → identical-arguments → budget.
335
387
  */
336
388
  protected checkActionCircuitBreaker(params: ExecuteAgentParams, action: AgentAction, actionEntity: MJActionEntityExtended, normalizedParams: string): CircuitBreakerActionResult | null;
337
389
  /** The failed {@link ActionResult} a blocked call returns in place of dispatching. */
@@ -447,6 +499,14 @@ export declare class BaseAgent {
447
499
  */
448
500
  private _feedbackRequestId;
449
501
  private _resolvedStorageAccountId;
502
+ /**
503
+ * Most recent artifactDirective returned by a child or related sub-agent during this run.
504
+ * Preserved as a fallback in {@link finalizeAgentRun} when an orchestrator (e.g. Sage) wraps
505
+ * up a delegated sub-agent's response on the subsequent turn without re-emitting its own
506
+ * artifactDirective.
507
+ * @private
508
+ */
509
+ private _lastSubAgentArtifactDirective;
450
510
  /**
451
511
  * The resolved FileStorageAccount ID for this agent run. Set during Execute()
452
512
  * via the hierarchical resolution chain (Runtime → Agent → Category → Type → fallback).
@@ -681,6 +741,11 @@ export declare class BaseAgent {
681
741
  * @since 2.46.0
682
742
  */
683
743
  private _scratchpadManager;
744
+ /**
745
+ * Protected accessor for the run's scratchpad manager.
746
+ * @protected
747
+ */
748
+ protected get scratchpadManager(): ScratchpadManager;
684
749
  /**
685
750
  * Manages artifact tools for the current agent run.
686
751
  * Allows agents to explore input artifacts on demand.
@@ -838,6 +903,12 @@ export declare class BaseAgent {
838
903
  * prompt execution occurred after them.
839
904
  */
840
905
  private _promptTurnCount;
906
+ /**
907
+ * The non-volatile stack the previous Prompt step of the current run recorded: each message's
908
+ * reference and its serialized form. A later Prompt step records only a delta when its stack
909
+ * extends this one append-only; otherwise it records the full stack.
910
+ */
911
+ private _lastRecordedPromptStack;
841
912
  /**
842
913
  * Per-run config for structurally compressing inline action-result payloads.
843
914
  * Resolved once at run start from the agent-type prompt params (default on);
@@ -924,6 +995,14 @@ export declare class BaseAgent {
924
995
  * @private
925
996
  */
926
997
  private preloadAgentData;
998
+ /**
999
+ * The params a run executes with: `params` itself, or, when the caller did not set
1000
+ * `ExecuteAgentParams.TrustReservedRunData` and `data` carries reserved keys, a copy whose `data` lacks them
1001
+ * (`WithAgentRunDataTrustApplied` in `@memberjunction/ai-core-plus`). {@link Execute} applies it first, so it
1002
+ * holds for every entry point: AgentRunner, the Execute Agent action, MCP, A2A, Runtime Actions, sub-agents.
1003
+ * The removed keys are logged once with the agent and user, never their values.
1004
+ */
1005
+ private withRunDataTrustApplied;
927
1006
  /**
928
1007
  * Executes an AI agent using hierarchical prompt composition.
929
1008
  *
@@ -960,6 +1039,92 @@ export declare class BaseAgent {
960
1039
  */
961
1040
  protected get DefaultAgentTimeoutMS(): number;
962
1041
  Execute<C = any, R = any>(params: ExecuteAgentParams<C>): Promise<ExecuteAgentResult<R>>;
1042
+ /**
1043
+ * Fails the run at its start, before any prompt: marks the already-created AgentRun Failed with the message
1044
+ * (so it never shows as a phantom "running" record) and throws, which {@link Execute} turns into a failure
1045
+ * result. Used by the permission check and the audience check.
1046
+ */
1047
+ private failRunAtStart;
1048
+ /**
1049
+ * The run's audience readers beyond the caller, hydrated once per run and audience: from the per-run state
1050
+ * when it was hydrated from this same `params.Audience`, else validated and loaded now. `{ Error }` names
1051
+ * what makes the audience unusable. `{ Readers: [] }` when the audience adds nobody.
1052
+ */
1053
+ private audienceReadersFor;
1054
+ /**
1055
+ * Validates `params.Audience` ({@link AgentAudienceProblem}) and loads a hydrated user for each reader it adds
1056
+ * beyond the caller ({@link ResolveAudienceUsers}). An ID no user has is refused, never skipped: a skipped
1057
+ * reader would restrict nothing, and the room would see the caller's whole reach.
1058
+ */
1059
+ private resolveRunAudience;
1060
+ /**
1061
+ * Loads the hydrated user (with its `UserRoles`) for each audience ID, from the server's `UserCache`. When an
1062
+ * ID is missing the cache is refreshed once — a user created since it loaded is then found, as MJServer's
1063
+ * authentication does for a user it does not know — and looked up again. Returns the users found; an ID left
1064
+ * out refuses the run. Override to resolve readers from another directory; never build `UserInfo` by hand.
1065
+ *
1066
+ * An inactive user is accepted as a reader, deliberately: a reader can only narrow what the run shows (each one is
1067
+ * another permission check every result must pass), never widen it, so a deactivated participant still listed in
1068
+ * the room restricts the run rather than failing it.
1069
+ *
1070
+ * @param ids The reader IDs the audience adds beyond the caller (normalized, distinct).
1071
+ * @param params The run's parameters (for the request-scoped provider the refresh reads through).
1072
+ */
1073
+ protected ResolveAudienceUsers(ids: string[], params: ExecuteAgentParams): Promise<UserInfo[]>;
1074
+ /**
1075
+ * Whether this run's audience adds a reader beyond the caller — the condition every audience gate asks.
1076
+ * A malformed audience counts as adding one (the run fails before the gates are reached anyway).
1077
+ */
1078
+ private runAudienceAddsReader;
1079
+ /**
1080
+ * Why this run is not offered task graphs and refuses one the model writes, or null when it may use them — the one
1081
+ * predicate, so every condition that withholds graphs is added in one place. A graph runs outside the run: its
1082
+ * action nodes are dispatched by the task-graph runner (MJServer's `TaskGraphActionRunner`) with no `Audience`,
1083
+ * no `RunScope` and no run `Context`, outside {@link ExecuteSingleAction}, and an agent node starts a run
1084
+ * (`TaskGraphAgentRunner`) that carries neither the audience nor the scope. So graphs are withheld when the
1085
+ * audience adds a reader, and when the run's validated scope carries a tenant or a secondary dimension
1086
+ * (`ActionRunScopeIsBounded`): a model-written Scoped Search node would search outside the run's tenant, and an
1087
+ * agent node would drop it.
1088
+ */
1089
+ private taskGraphWithholdingReason;
1090
+ /** Whether this run withholds task graphs ({@link taskGraphWithholdingReason}). */
1091
+ private runWithholdsTaskGraphs;
1092
+ /**
1093
+ * The `Failed` step for a task graph the model wrote although this run withholds them ({@link taskGraphWithholdingReason}),
1094
+ * or null when graphs are allowed. The response type already hides `tasks`; this is the gate for a model that emits one
1095
+ * anyway. Written before any step: nothing is submitted.
1096
+ */
1097
+ private taskGraphRefusal;
1098
+ /**
1099
+ * What this run's prompt leaves out: task graphs ({@link taskGraphWithholdingReason}), and — when the audience adds a
1100
+ * reader — the caller's own browser and view (`CallerContext`): client tools run in the caller's browser and what they
1101
+ * return reaches the room, and the app context (`data.appContext`, with its `AdditionalContext`) is the caller's screen.
1102
+ */
1103
+ private promptWithholding;
1104
+ /**
1105
+ * The client-tools and app-context prompt sections ({@link buildClientToolPromptSection}, {@link buildAppContextSection}),
1106
+ * both empty when the caller's context is withheld ({@link promptWithholding}): the prompt then offers no client tool
1107
+ * and none of the caller's app context. {@link executeClientToolsStep} refuses a client-tools step emitted anyway.
1108
+ */
1109
+ private callerContextSections;
1110
+ /**
1111
+ * The `Failed` step for a client-tools step under an audience, or null. Client tools run in the caller's browser and
1112
+ * what they return comes back into a run whose output reaches the room; the prompt does not offer them then
1113
+ * ({@link callerContextSections}), and this refuses a step the model emits anyway, as {@link taskGraphRefusal} does a graph.
1114
+ */
1115
+ private clientToolsRefusal;
1116
+ /** Clears what bounds one run — its validated scope and its hydrated audience — once the run is over. */
1117
+ private clearRunBoundState;
1118
+ /**
1119
+ * A copy of the agent-type prompt params with task graphs withheld (`enableTaskGraphs` off and the `tasks`
1120
+ * response section hidden). A copy, never a write: the input may be the process-wide cached base.
1121
+ */
1122
+ private withoutTaskGraphs;
1123
+ /**
1124
+ * Why a session-driven (realtime / voice / bridge) run is refused, or null. A live session speaks and calls
1125
+ * tools outside the gates that hold a run to its audience, so a run whose audience adds a reader is refused.
1126
+ */
1127
+ private sessionAudienceRefusal;
963
1128
  /**
964
1129
  * Releases this run's PerRun-scoped preloaded-data cache entry. `preloadAgentData()`
965
1130
  * (Phase 2 of `Execute()`) may have populated one keyed by `this._agentRun.ID`; without
@@ -1447,9 +1612,10 @@ export declare class BaseAgent {
1447
1612
  * @param primaryScopeRecordId - Optional primary scope record ID for multi-tenant filtering
1448
1613
  * @param secondaryScopes - Optional secondary scope dimensions for multi-tenant filtering
1449
1614
  * @param secondaryScopeConfig - Optional agent-level scope config for per-dimension inheritance
1615
+ * @param sharedOnly - Inject only shared notes and examples (no `UserID`); set when the run's audience adds a reader
1450
1616
  * @returns Object containing injected notes and examples
1451
1617
  */
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<{
1618
+ protected InjectContextMemory(input: string, agent: MJAIAgentEntityExtended, userId?: string, companyId?: string, contextUser?: UserInfo, conversationMessages?: ChatMessage[], primaryScopeEntityId?: string, primaryScopeRecordId?: string, secondaryScopes?: Record<string, SecondaryScopeValue>, secondaryScopeConfig?: SecondaryScopeConfig | null, sharedOnly?: boolean): Promise<{
1453
1619
  notes: MJAIAgentNoteEntity[];
1454
1620
  examples: MJAIAgentExampleEntity[];
1455
1621
  }>;
@@ -1460,9 +1626,18 @@ export declare class BaseAgent {
1460
1626
  * primary prompt under the run's polymorphic scope (the SAME PrimaryScope/SecondaryScopes the
1461
1627
  * runtime threads for memory), and unshifts the assembled role-tagged messages onto
1462
1628
  * `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.
1629
+ * the agent has no active prompt or no parts resolve for the scope. System placeholders in the
1630
+ * messages it adds are replaced afterwards ({@link replaceScopedPartPlaceholders}), so an override
1631
+ * gets that too.
1464
1632
  */
1465
1633
  protected InjectScopedPromptParts(agent: MJAIAgentEntityExtended, conversationMessages: ChatMessage[], primaryScopeEntityId?: string, primaryScopeRecordId?: string, secondaryScopes?: Record<string, SecondaryScopeValue>): void;
1634
+ /**
1635
+ * Replace system placeholders such as `{{ _CURRENT_DATE }}` in the messages that
1636
+ * {@link InjectScopedPromptParts} added, meaning every message not in `before`. Part text is not a
1637
+ * template: see {@link SystemPlaceholderManager.ReplaceAvailablePlaceholders} for what resolves.
1638
+ * On failure the parts are kept as written.
1639
+ */
1640
+ private replaceScopedPartPlaceholders;
1466
1641
  /**
1467
1642
  * Inject pre-execution RAG context for this agent using scoped search.
1468
1643
  *
@@ -1486,9 +1661,12 @@ export declare class BaseAgent {
1486
1661
  * @param primaryScopeRecordId - Multi-tenant primary scope record ID.
1487
1662
  * @param secondaryScopes - Multi-tenant secondary scope dimensions.
1488
1663
  * @param payload - The agent's current payload (for template rendering).
1664
+ * @param activeSkillIDs - The skills active for this run; a lone active skill is the search's skill principal.
1665
+ * @param audienceReaders - The run's audience readers beyond the caller (`ExecuteAgentParams.Audience`,
1666
+ * hydrated): each must pass the scope gate, and only results every one of them may read are injected.
1489
1667
  * @returns The structured RAG result, or `null` if no scopes produced results.
1490
1668
  */
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>;
1669
+ protected InjectPreExecutionRAG(lastUserMessage: string, agent: MJAIAgentEntityExtended, contextUser: UserInfo | undefined, conversationMessages: ChatMessage[] | undefined, originalMessages: ChatMessage[] | undefined, primaryScopeEntityId?: string, primaryScopeRecordId?: string, secondaryScopes?: Record<string, SecondaryScopeValue>, payload?: unknown, activeSkillIDs?: string[], audienceReaders?: UserInfo[]): Promise<AgentPreExecutionRAGResult | null>;
1492
1670
  /**
1493
1671
  * Decision discovery (plan Task 3.1): suggests the agent to delegate to before the first prompt.
1494
1672
  *
@@ -1598,6 +1776,7 @@ export declare class BaseAgent {
1598
1776
  *
1599
1777
  * @param {string} lastRunId - The ID of the last run to check
1600
1778
  * @param {UserInfo} [contextUser] - Optional user context
1779
+ * @param {{ LastRunID?: string | null } | null} [preloadedLastRun] - Optional preloaded row for `lastRunId` (or null when already queried and not found) to avoid a duplicate RunView call
1601
1780
  * @private
1602
1781
  */
1603
1782
  private validateRunChain;
@@ -1864,17 +2043,26 @@ export declare class BaseAgent {
1864
2043
  * when it stays in the system prompt.
1865
2044
  */
1866
2045
  protected resolveRelocatedSpecialization(promptParams: AIPromptParams, childPrompt: MJAIPromptEntityExtended | undefined, agentType: MJAIAgentTypeEntity, contextUser: UserInfo): Promise<string | null>;
2046
+ /**
2047
+ * Per-instance memoization for runtime-state template delivery analysis and template-array indexing
2048
+ * so multi-turn agent loops do not repeatedly scan template collections and strings on every turn.
2049
+ * @private
2050
+ */
2051
+ private _lastRuntimeStateDeliveryCache;
2052
+ private _cachedTemplatesArrayRef;
2053
+ private _templateByIdMap;
2054
+ private _templateEngineConfiguredForRun;
1867
2055
  /**
1868
2056
  * Decides, from the system prompt's UNRENDERED template text, whether the trailing runtime-state
1869
2057
  * fragment belongs on this request:
1870
2058
  *
1871
2059
  * - `'trailing'` — the template carries the `<mj-runtime-state>` pointer, so the model is told where
1872
- * the state lives. The Loop agent system prompt.
2060
+ * the state lives. The Loop and Flow agent system prompts.
1873
2061
  * - `'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
2062
+ * TemplateContent has not synced the new system template, or a custom template that embeds the
1875
2063
  * payload). Emitting the fragment would deliver the same state twice.
1876
2064
  * - `'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.
2065
+ * without a system prompt carrying the pointer. The model would receive an unexplained block.
1878
2066
  * - `'unknown'` — no template text to inspect (no TemplateID, or the lookup failed). The caller
1879
2067
  * fails OPEN here: a Loop agent losing its payload from the model's view is far worse than a
1880
2068
  * non-Loop agent receiving an unexplained fragment, and in practice every agent type's system
@@ -1967,6 +2155,22 @@ export declare class BaseAgent {
1967
2155
  */
1968
2156
  protected getRequestedSubAgents<P, C>(nextStep: BaseAgentNextStep<P, C> | undefined | null): AgentSubAgentRequest<C>[];
1969
2157
  protected validateSubAgentNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2158
+ /**
2159
+ * Builds a compact hint listing the current user's permitted runnable agents when a
2160
+ * task-graph or folded sub-agent step references an unknown or inaccessible agent name.
2161
+ */
2162
+ protected buildAvailableRunnableAgentsHint(contextUser?: UserInfo): string;
2163
+ /**
2164
+ * Validates a `'Tasks'` next step before `executeTasksStep` submits the graph.
2165
+ *
2166
+ * Verifies that every referenced `Agent` (including `ForEach`/`While` loop sub-agents) is
2167
+ * active and runnable by `params.contextUser`, and that every referenced `Action` is active.
2168
+ * When an agent or action name is unknown or inaccessible, converts the step to a self-correcting
2169
+ * `Retry` with the user's permitted runnable agent list instead of letting `TaskGraphService.Submit`
2170
+ * terminate the entire agent run as `Failed`. Never reveals whether an invalid agent name was
2171
+ * nonexistent versus restricted by permissions.
2172
+ */
2173
+ protected validateTasksNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, _currentPayload: P, _agentRun: MJAIAgentRunEntityExtended, _currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
1970
2174
  /**
1971
2175
  * Validates that the actions next step is valid and can be executed by the current agent. Subclasses can override
1972
2176
  * this method to implement custom validation logic if needed.
@@ -2093,6 +2297,58 @@ export declare class BaseAgent {
2093
2297
  current?: number;
2094
2298
  reason?: string;
2095
2299
  }>;
2300
+ /**
2301
+ * Ensures that a shared {@link AgentTreeBudget} instance exists for the current execution tree
2302
+ * and is attached to both `this._treeBudget` and `params.treeBudget`.
2303
+ *
2304
+ * - When `params.treeBudget` is already provided (for example, propagated by a parent agent
2305
+ * in {@link ExecuteSubAgent} or supplied directly by a caller), that exact object reference
2306
+ * is reused so all root, sequential child, and parallel child runs mutate the same shared
2307
+ * counters (`totalSteps`, `totalTokens`, `totalCost`, `startedAtMs`, `breachedReason`).
2308
+ * - When `params.treeBudget` is absent (root run), a new {@link AgentTreeBudget} is created
2309
+ * and seeded with any top-level convenience ceilings (`maxTreeSteps`, `maxTreeTokens`,
2310
+ * `maxTreeCost`, `maxTreeDurationMs`) declared on `params`.
2311
+ *
2312
+ * @param params - Optional execution parameters for the current run.
2313
+ * @returns The shared {@link AgentTreeBudget} instance for the execution tree.
2314
+ * @protected
2315
+ */
2316
+ protected ensureTreeBudget(params?: ExecuteAgentParams): AgentTreeBudget;
2317
+ /**
2318
+ * Accumulates token and cost usage from a completed prompt execution into the shared
2319
+ * {@link AgentTreeBudget} for the execution tree.
2320
+ *
2321
+ * Prefers rollup figures on `promptRun` (`TokensUsedRollup` / `TokensPromptRollup` +
2322
+ * `TokensCompletionRollup` and `TotalCost`) so hierarchical child prompts are counted,
2323
+ * falling back to direct `promptRun` columns (`TokensUsed` / `TokensPrompt` + `TokensCompletion`
2324
+ * and `Cost`) or the `AIPromptRunResult` summary fields when `promptRun` is not populated.
2325
+ *
2326
+ * @param promptRun - The persisted or in-memory `MJAIPromptRunEntity` from the prompt execution, if any.
2327
+ * @param promptResult - Optional `AIPromptRunResult` carrying direct token/cost metrics.
2328
+ * @param params - Optional execution parameters for the current run.
2329
+ * @protected
2330
+ */
2331
+ protected recordPromptUsageInTreeBudget(promptRun?: MJAIPromptRunEntity | null, promptResult?: AIPromptRunResult<unknown>, params?: ExecuteAgentParams): void;
2332
+ /**
2333
+ * Evaluates whether any root-tree cumulative budget ceiling (`maxTreeSteps`, `maxTreeTokens`,
2334
+ * `maxTreeCost`, `maxTreeDurationMs`) on the shared {@link AgentTreeBudget} has been reached
2335
+ * or exceeded.
2336
+ *
2337
+ * When a ceiling is breached, sets `budget.breachedReason` with a descriptive diagnostic
2338
+ * message so both the breaching agent and any ancestor agents in the call tree can terminate
2339
+ * immediately with `step: 'Failed'` and `terminate: true`.
2340
+ *
2341
+ * @param params - Optional execution parameters for the current run.
2342
+ * @returns Guardrail evaluation result indicating whether a tree budget limit was exceeded.
2343
+ * @protected
2344
+ */
2345
+ protected checkTreeBudgetLimit(params?: ExecuteAgentParams): {
2346
+ exceeded: boolean;
2347
+ type?: 'cost' | 'tokens' | 'iterations' | 'time';
2348
+ limit?: number;
2349
+ current?: number;
2350
+ reason?: string;
2351
+ };
2096
2352
  /**
2097
2353
  * Determines if a prompt execution error is fatal and should stop agent execution.
2098
2354
  * Fatal errors are those that won't be resolved by retrying, such as context length
@@ -2296,7 +2552,9 @@ export declare class BaseAgent {
2296
2552
  *
2297
2553
  * Gated on conversationId + root depth — programmatic runs and sub-agents skip it.
2298
2554
  * Skipped under a history floor (`ConversationHistoryFrom`): the previous run's tool
2299
- * results can quote messages from before the floor.
2555
+ * results can quote messages from before the floor. Skipped under an audience
2556
+ * (`ExecuteAgentParams.Audience`) too: the previous run's results were fetched for
2557
+ * whoever ran it, not for this room.
2300
2558
  * @protected
2301
2559
  */
2302
2560
  protected injectPriorTurnToolResults(params: ExecuteAgentParams): Promise<void>;
@@ -2358,10 +2616,12 @@ export declare class BaseAgent {
2358
2616
  /**
2359
2617
  * The stopped run's turns in the shape the loop builds, or null when they cannot be recovered.
2360
2618
  *
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.
2619
+ * The latest prompt step that recorded a full stack holds the run's whole message stack as it went
2620
+ * into that prompt; the prompt steps after it recorded only the messages appended since (see
2621
+ * {@link capturePromptStepMessages}). The first prompt step recorded the stack the run started from
2622
+ * (history plus this run's injections, which the new run adds for itself). The difference is the
2623
+ * run's own turns. If the last prompt completed, its decision and the steps after it are rebuilt
2624
+ * with the loop's own builders.
2365
2625
  * @protected
2366
2626
  */
2367
2627
  protected buildResumedStoppedRunTurns(steps: StoppedRunStackStepRecord[], params: ExecuteAgentParams): AgentChatMessage[] | null;
@@ -2398,6 +2658,8 @@ export declare class BaseAgent {
2398
2658
  private summarizeStoppedActionStep;
2399
2659
  /** The message stack a prompt step recorded as its input, or null. @private */
2400
2660
  private static readPromptStepStack;
2661
+ /** True when a prompt step recorded only the per-turn message delta instead of the full history stack. @private */
2662
+ private static isPromptStepDelta;
2401
2663
  /** The decision a completed prompt step recorded, or null. @private */
2402
2664
  private static readPromptStepDecision;
2403
2665
  /** The action an Actions step ran, from its recorded input, or null. @private */
@@ -2655,15 +2917,39 @@ export declare class BaseAgent {
2655
2917
  protected executeMemoryWritesAsSteps(writes: MemoryWriteRequest[], params: ExecuteAgentParams): Promise<MemoryWriteResult[]>;
2656
2918
  /**
2657
2919
  * 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
2920
+ * AllowMemoryWrite flag and on the run's audience ({@link memoryWriteSkip}).
2921
+ * When refused but the LLM emitted writes anyway (prompt drift / injection
2922
+ * attempt), records ONE summary skip step and tells the agent the memories
2923
+ * were NOT saved ({@link skipMemoryWrites}). Otherwise executes the
2662
2924
  * writes as run steps and injects the results message.
2663
2925
  *
2664
2926
  * @protected
2665
2927
  */
2666
2928
  protected processMemoryWritesForTurn(memoryWrites: MemoryWriteRequest[], params: ExecuteAgentParams): Promise<void>;
2929
+ /**
2930
+ * Determines whether artifact creation/lifecycle support (`artifactDirective`) is enabled for
2931
+ * the given agent so the Loop Agent system prompt includes `artifactDirective` and its lifecycle
2932
+ * instructions only when relevant.
2933
+ *
2934
+ * Returns `true` when:
2935
+ * - `agent.ArtifactCreationMode` is not `'Never'`, OR
2936
+ * - Conversation artifacts are already loaded in `_artifactToolManager`, OR
2937
+ * - The agent is an embedded sub-agent (`agent.ParentID`) whose parent agent creates artifacts
2938
+ * (`parentAgent.ArtifactCreationMode === 'Always'`) and relies on the sub-agent's payload/directive.
2939
+ */
2940
+ protected isArtifactSupportEnabled(agent: MJAIAgentEntityExtended): boolean;
2941
+ /**
2942
+ * Why this run saves no memory writes, or null when it may: the agent has not opted in (`AllowMemoryWrite`), or the
2943
+ * run's audience adds a reader. A write is the caller's note, and its reply — saved, superseded, "already exists
2944
+ * verbatim" — is read against the caller's own notes, so in a shared conversation it would tell the room what the
2945
+ * caller has noted. The memory-writes docs are left out of the prompt for the same reasons.
2946
+ */
2947
+ private memoryWriteSkip;
2948
+ /**
2949
+ * Records ONE summary skip step for a turn's refused memory writes — observable without per-write noise — and tells
2950
+ * the agent the memories were NOT saved, so it stops re-emitting them.
2951
+ */
2952
+ private skipMemoryWrites;
2667
2953
  /**
2668
2954
  * Pushes a single user-role message containing memory-write outcomes into
2669
2955
  * the conversation, mirroring `injectArtifactToolResultsMessage`'s
@@ -2887,6 +3173,7 @@ export declare class BaseAgent {
2887
3173
  * @param {UserInfo} [_contextUser] - Optional user context (reserved for future use)
2888
3174
  * @param {any} [extraData] - Optional extra data to include in the context, if provided and keys conflict within the agent context data, the extraData will override the agent context data.
2889
3175
  * @param {ActionChange[]} [actionChanges] - Optional runtime action modifications
3176
+ * @param {PromptWithholding} [withholding] - What this run's prompt leaves out (see `promptWithholding`)
2890
3177
  *
2891
3178
  * @returns {Promise<AgentContextData>} Structured context data for prompts
2892
3179
  *
@@ -3157,6 +3444,41 @@ export declare class BaseAgent {
3157
3444
  * class (never the key), so a run's log shows which action drew which credential.
3158
3445
  */
3159
3446
  private buildRuntimeAPIKeyResolver;
3447
+ /** The model's arguments as the engine's input parameters. */
3448
+ private toEngineActionParams;
3449
+ /**
3450
+ * The action context for one dispatch: the agent's own context object, by reference (do NOT spread —
3451
+ * spreading destroys class instances, losing getters/methods on typed contexts like SkipAgentContext),
3452
+ * stamped with the calling agent's identity, the run's active skills and its resolved storage account.
3453
+ */
3454
+ private stampActionContext;
3455
+ /**
3456
+ * The run's bounds handed to ONE action dispatch, beside its parameters. Per dispatch on purpose: the action
3457
+ * context IS params.context, shared by every action in the run (parallel ones included) and copied into
3458
+ * sub-agent runs, so anything stamped there would name the wrong action under parallel dispatch and travel
3459
+ * further than the action it was meant for. The model sets none of these.
3460
+ */
3461
+ private runBoundDispatchParams;
3462
+ /**
3463
+ * The audience readers for one dispatch: everyone who will see the result besides the user the action RUNS AS
3464
+ * ({@link ExecuteSingleAction}'s `contextUser`), which need not be the run's caller. The run's readers leave the
3465
+ * caller out; when the action runs as someone else, the caller sees its result too and is added, and the user it
3466
+ * runs as is left out (as the engine does). A run whose audience adds no reader stays without one.
3467
+ */
3468
+ private dispatchReaders;
3469
+ /**
3470
+ * The scope an action dispatch is handed: the run's, as {@link initializeAgentRun} validated and recorded it,
3471
+ * or — when {@link ExecuteSingleAction} is called outside {@link Execute} (the realtime tool path, tests,
3472
+ * harnesses) — resolved from these params the same way ({@link validatedRunScope}). A copy each time, so an
3473
+ * action cannot change what the next one sees.
3474
+ */
3475
+ private runScopeFor;
3476
+ /**
3477
+ * Logs one dispatched call's outcome and feeds the run-scoped circuit breaker, unless the caller does its own
3478
+ * failure accounting (`skipCircuitBreaker`). An `AUDIENCE_UNSUPPORTED` refusal locks the action out for the
3479
+ * run: no argument changes it, and the model is told the action is unavailable rather than to retry.
3480
+ */
3481
+ private recordDispatchOutcome;
3160
3482
  /**
3161
3483
  * This method executes one action using the MemberJunction Actions framework.
3162
3484
  * The full ActionResult objects are returned, allowing the caller to access result codes, output parameters,
@@ -3173,6 +3495,12 @@ export declare class BaseAgent {
3173
3495
  * @throws {Error} If the action fails to execute
3174
3496
  */
3175
3497
  ExecuteSingleAction(params: ExecuteAgentParams, action: AgentAction, actionEntity: MJActionEntityExtended, contextUser?: UserInfo, options?: ExecuteSingleActionOptions): Promise<ActionResult>;
3498
+ /**
3499
+ * Checks per-(Agent, User) action policy narrowing rules (`MJ: AI Agent User Policies`)
3500
+ * before dispatching an action. Returns a synthetic ActionResult when the action is denied,
3501
+ * deferred outside a configured time window, or requires explicit user approval.
3502
+ */
3503
+ protected checkUserActionPolicy(params: ExecuteAgentParams, action: AgentAction, actionEntity: MJActionEntityExtended, contextUser?: UserInfo): ActionResult | null;
3176
3504
  /**
3177
3505
  * Makes a SLICED conversation window safe to send on its own.
3178
3506
  *
@@ -3249,6 +3577,18 @@ export declare class BaseAgent {
3249
3577
  * ```
3250
3578
  */
3251
3579
  protected ExecuteSubAgent<SC = any, SR = any>(params: ExecuteAgentParams<SC>, subAgentRequest: AgentSubAgentRequest<SC>, subAgent: MJAIAgentEntityExtended, stepEntity: MJAIAgentRunStepEntityExtended, payload?: SR, contextMessage?: ChatMessage, stepCount?: number): Promise<ExecuteAgentResult<SR>>;
3580
+ /**
3581
+ * A sub-agent request's template parameters without the host-only run-data keys
3582
+ * (`HOST_ONLY_AGENT_RUN_DATA_KEYS` in `@memberjunction/ai-core-plus`: the reserved scope family and
3583
+ * `__agentTypePromptParams`, and the browser, conversation and realtime controls — `clientTools`, `sessionID`,
3584
+ * `appContext`, `applicationId`, `conversationId`, `targetAgentID`, `agentSessionId`, `recording`, `realtime*`).
3585
+ * They are merged into the child's `data`, which `BaseAgent` reads for all of these, and inside a Loop agent they
3586
+ * are written by the model — so left in, a model could set a sub-agent's tenant (whenever the parent's run trusts
3587
+ * its `data`), offer it client tools, inject an app context, or point it at another conversation. The child
3588
+ * inherits the parent's values instead (its own params, and the parent's `data` as is). What was removed is
3589
+ * logged once, by key only — never the values.
3590
+ */
3591
+ private subAgentTemplateParameters;
3252
3592
  /**
3253
3593
  * Formats sub-agent details as compact markdown for inclusion in prompt context.
3254
3594
  *
@@ -3580,20 +3920,77 @@ export declare class BaseAgent {
3580
3920
  };
3581
3921
  }): Promise<MJAIAgentRunStepEntityExtended>;
3582
3922
  /**
3583
- * Finalizes a step entity with completion status.
3923
+ * Finds the step whose `PayloadAtEnd` a new step's start payload repeats, so the new step stores a
3924
+ * pointer to it (`PayloadAtStartSourceStepID`) instead of a second copy. Call it before the new step
3925
+ * is added to the run's `Steps`.
3584
3926
  *
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
3927
+ * The candidate is the latest step in the run that is not `Running` and has a `PayloadAtEnd` (or
3928
+ * `PayloadAtEndSourceStepID`). Only that step is compared. If that step itself points to an earlier
3929
+ * step via `PayloadAtEndSourceStepID`, the pointer resolves in one hop to the step that actually
3930
+ * holds the stored `PayloadAtEnd`.
3931
+ * - Running steps are skipped because their end can still change: parallel sub-agent siblings write
3932
+ * their own result as `PayloadAtEnd` when they finish, and a ForEach step writes its end after all
3933
+ * of its child steps.
3934
+ * - Finished steps with no end (tool, compaction and finish-check steps) are skipped because they never
3935
+ * get one, and would hide the step that produced the payload.
3936
+ * - If the matching candidate's INSERT is still in flight (`!step.IsSaved`), {@link createStepEntity}
3937
+ * chains the new step's INSERT after `step` on {@link _stepSaveQueue} (and falls back to storing inline
3938
+ * `PayloadAtStart` if the candidate's INSERT fails) so `FK_AIAgentRunStep_PayloadAtStartSourceStepID`
3939
+ * is always satisfied without sacrificing deduplication on fast back-to-back turns.
3940
+ *
3941
+ * Rule: a step's `PayloadAtEnd` must not change after a later step points at it, because readers take
3942
+ * the pointing step's start payload from it. The comparison uses the in-memory end, so the saved end
3943
+ * must match it: `finalizeStepEntity` re-applies the end after the INSERT lands, and an end set after
3944
+ * `finalizeStepEntity` is saved with `queueStepSave`.
3945
+ *
3946
+ * @param serializedStart The new step's start payload, already serialized.
3947
+ * @returns The step to point at, or undefined when the start payload must be stored.
3948
+ */
3949
+ private findPayloadAtStartSource;
3950
+ /**
3951
+ * Finds the earlier step whose stored `PayloadAtEnd` this step's end payload repeats, so the step
3952
+ * stores a one-hop pointer (`PayloadAtEndSourceStepID`) instead of a second copy.
3590
3953
  */
3954
+ private findPayloadAtEndSource;
3955
+ private findPayloadEndSourceBefore;
3956
+ /**
3957
+ * Returns true when neither `serializePayloadAtStart` nor `serializePayloadAtEnd` has been
3958
+ * overridden by a subclass, allowing unchanged start payloads to be reused as end payloads
3959
+ * without a second `JSON.stringify` pass.
3960
+ */
3961
+ private hasDefaultPayloadSerializers;
3962
+ /**
3963
+ * Resolves a step's start payload from its own `PayloadAtStart` or the step referenced by
3964
+ * `PayloadAtStartSourceStepID`.
3965
+ */
3966
+ private resolveStepPayloadAtStart;
3967
+ /**
3968
+ * Resolves a step's end payload from its own `PayloadAtEnd` or the step referenced by
3969
+ * `PayloadAtEndSourceStepID`.
3970
+ */
3971
+ private resolveStepPayloadAtEnd;
3591
3972
  /**
3592
3973
  * Builds a summary of payload change results for storage
3593
3974
  * @param changeResult The result from PayloadManager operations
3594
3975
  * @returns A serializable summary object
3595
3976
  */
3596
3977
  private buildPayloadChangeResultSummary;
3978
+ /**
3979
+ * Captures the conversation messages for a `Prompt` step's `InputData` without
3980
+ * persisting volatile `<mj-runtime-state>` envelopes or repeating messages already
3981
+ * recorded in an earlier `Prompt` step of the current run.
3982
+ *
3983
+ * - When the non-volatile stack extends the previous Prompt step's recorded stack append-only (the
3984
+ * same messages, unchanged, at the same positions), only the appended messages are stored, tagged
3985
+ * with `conversationMessagesDelta: true`.
3986
+ * - Otherwise (the first Prompt step of the run, or a message was replaced, removed or changed by
3987
+ * expiry, compaction or expansion) the full non-volatile stack is stored, with no delta flag.
3988
+ *
3989
+ * {@link buildResumedStoppedRunTurns} rebuilds the stack from the latest full stack plus the deltas after it.
3990
+ */
3991
+ private capturePromptStepMessages;
3992
+ /** True when `current` starts with every message of `previous`, by reference and unchanged in place. @private */
3993
+ private static isAppendOnlyExtension;
3597
3994
  /**
3598
3995
  * Finalizes a step entity with completion status. Pairs with `createStepEntity`
3599
3996
  * — drivers that create custom steps should also finalize them through this
@@ -3601,6 +3998,9 @@ export declare class BaseAgent {
3601
3998
  * populated consistently and the UPDATE is sequenced behind the INSERT via
3602
3999
  * `queueStepSave`.
3603
4000
  *
4001
+ * Set `PayloadAtEnd` before calling it: the queued UPDATE re-applies the end the step has now.
4002
+ * An end set later must be saved with `queueStepSave`.
4003
+ *
3604
4004
  * @protected
3605
4005
  */
3606
4006
  protected finalizeStepEntity(stepEntity: MJAIAgentRunStepEntityExtended, success: boolean, errorMessage?: string, outputData?: any): Promise<void>;
@@ -3643,6 +4043,29 @@ export declare class BaseAgent {
3643
4043
  * @returns {string} - The formatted message with hierarchy breadcrumb
3644
4044
  */
3645
4045
  protected formatHierarchicalMessage(baseMessage: string): string;
4046
+ /**
4047
+ * Builds the user-oriented initialization progress message for an agent run.
4048
+ *
4049
+ * - Root agent (`_depth === 0`): `'Getting ready...'`
4050
+ * - Direct sub-agent (`_depth === 1`): `'Starting <SubAgentName>...'`
4051
+ * - Nested sub-agent (`_depth > 1`): `'<ParentBreadcrumb>: Starting <SubAgentName>...'`
4052
+ *
4053
+ * @protected
4054
+ * @param {ExecuteAgentParams} params - Execution parameters for the current agent
4055
+ * @returns {string} Formatted initialization progress message
4056
+ */
4057
+ protected buildInitializationProgressMessage(params: ExecuteAgentParams): string;
4058
+ /**
4059
+ * Builds a user-oriented progress message for a prompt execution step without
4060
+ * exposing internal framework terminology ("initial prompt", "payload", "context")
4061
+ * or duplicating the sub-agent name when prefixed by {@link formatHierarchicalMessage}.
4062
+ *
4063
+ * @protected
4064
+ * @param {ExecuteAgentParams} params - Execution parameters for the current agent
4065
+ * @param {BaseAgentNextStep | null} [previousDecision] - Previous step decision when re-prompting
4066
+ * @returns {string} Base progress message (before `formatHierarchicalMessage` breadcrumb prefixing)
4067
+ */
4068
+ protected buildPromptProgressMessage(params: ExecuteAgentParams, previousDecision?: BaseAgentNextStep | null): string;
3646
4069
  /**
3647
4070
  * Trims a step name to what `AIAgentRunStep.StepName` can hold. Step names are built from free
3648
4071
  * text — a termination message quoting a provider's error, a tool name with its arguments, the
@@ -3749,6 +4172,14 @@ export declare class BaseAgent {
3749
4172
  * @param subAgentPayloadOverride - Optional payload override for sub-agent execution, if provided the normal payload computation is skipped
3750
4173
  */
3751
4174
  private executeChildSubAgentStep;
4175
+ /**
4176
+ * Extracts the workflow root task ID (`parentTaskID`) from a sub-agent run that parked on a
4177
+ * durable task graph (`Status === 'Paused'`), falling back to the sub-agent run ID so the
4178
+ * parent run's `_awaitingWorkflowTaskID` is guaranteed non-null when parking.
4179
+ *
4180
+ * @protected
4181
+ */
4182
+ protected extractSubAgentWorkflowTaskID(subAgentRun: MJAIAgentRunEntityExtended | undefined): string;
3752
4183
  /**
3753
4184
  * Routes sub-agent execution to the appropriate handler based on relationship type.
3754
4185
  * Child agents (ParentID) use direct payload coupling.
@@ -3773,7 +4204,7 @@ export declare class BaseAgent {
3773
4204
  *
3774
4205
  * @protected
3775
4206
  */
3776
- protected resolveSubAgentByName(params: ExecuteAgentParams, name: string): {
4207
+ protected resolveSubAgentByName(params: ExecuteAgentParams, name: string, allowAnyActiveAgent?: boolean): {
3777
4208
  subAgentEntity: MJAIAgentEntityExtended;
3778
4209
  relationship?: MJAIAgentRelationshipEntity;
3779
4210
  } | undefined;
@@ -4007,10 +4438,13 @@ export declare class BaseAgent {
4007
4438
  *
4008
4439
  * @private
4009
4440
  */
4441
+ /** The assistant message describing a client-tools step's invocations. */
4442
+ private describeClientToolInvocations;
4010
4443
  /**
4011
4444
  * Execute client-side tools requested by the agent.
4012
4445
  * Sends each tool invocation via PubSub, awaits the client's response
4013
4446
  * (or timeout), then adds results to the conversation and continues.
4447
+ * Refused under an audience ({@link clientToolsRefusal}).
4014
4448
  */
4015
4449
  private executeClientToolsStep;
4016
4450
  /**
@@ -4294,6 +4728,15 @@ export declare class BaseAgent {
4294
4728
  */
4295
4729
  protected buildPlanApprovalForm(planText: string): AgentResponseForm;
4296
4730
  private executeChatStep;
4731
+ /**
4732
+ * Raises the persistent `MJ: AI Agent Requests` row for a root agent's Chat or Plan step ({@link createFeedbackRequest}),
4733
+ * so it can be answered outside the conversation — except when the run's audience adds a reader. A request answered
4734
+ * on the dashboard or through the API resumes the run (`MJAIAgentRequestEntityServer.resumeAgent`) as the responder,
4735
+ * in the original conversation, with no audience: neither the request nor the run row has a field that can carry
4736
+ * one without a new column. So a shared conversation's run raises none: its question or plan still reaches the room,
4737
+ * which answers in the conversation, where the host starts the next run with the room's audience.
4738
+ */
4739
+ private raiseFeedbackRequest;
4297
4740
  /**
4298
4741
  * Creates a persistent AIAgentRequest row when a Chat step fires.
4299
4742
  * Resolves the target user via the assignment chain:
@@ -4493,13 +4936,23 @@ export declare class BaseAgent {
4493
4936
  */
4494
4937
  private completeWhileLoop;
4495
4938
  /**
4496
- * Creates a failure result with proper tracking.
4939
+ * Flushes any in-flight `MJAIPromptRunEntityExtended` saves queued on {@link _promptRunner}.
4940
+ * Tolerates lightweight test doubles on `_promptRunner` that may only implement
4941
+ * `WaitForPendingPromptRunSaves` or neither method.
4942
+ *
4943
+ * @private
4944
+ */
4945
+ private flushPromptRunnerSaves;
4946
+ /**
4947
+ * Creates a failure result with proper tracking, draining all queued step and prompt-run saves
4948
+ * before persisting the failed run row so no orphan step or prompt-run writes remain in flight.
4497
4949
  *
4498
4950
  * @private
4499
4951
  */
4500
4952
  private createFailureResult;
4501
4953
  /**
4502
- * Creates a cancelled result.
4954
+ * Creates a cancelled result, draining all queued step and prompt-run saves before persisting
4955
+ * the cancelled run row so no orphan step or prompt-run writes remain in flight.
4503
4956
  *
4504
4957
  * @private
4505
4958
  * @param {string} message - The cancellation message
@@ -4519,15 +4972,19 @@ export declare class BaseAgent {
4519
4972
  * (array order is spawn order, which a sub-step can interleave).
4520
4973
  */
4521
4974
  static LastStepPayload(steps: ReadonlyArray<{
4975
+ ID?: string;
4522
4976
  StepNumber: number;
4977
+ PayloadAtStart?: string | null;
4523
4978
  PayloadAtEnd: string | null;
4979
+ PayloadAtStartSourceStepID?: string | null;
4980
+ PayloadAtEndSourceStepID?: string | null;
4524
4981
  }> | null | undefined): string | null;
4525
4982
  /**
4526
4983
  * Finalizes the agent run with success.
4527
4984
  *
4528
- * @private
4985
+ * @protected
4529
4986
  */
4530
- private finalizeAgentRun;
4987
+ protected finalizeAgentRun<P>(finalStep: BaseAgentNextStep, payload?: P, contextUser?: UserInfo): Promise<ExecuteAgentResult<P>>;
4531
4988
  /**
4532
4989
  * Calculate total token statistics from the agent run's persisted steps.
4533
4990
  *
@@ -4674,6 +5131,50 @@ export declare class BaseAgent {
4674
5131
  * @private
4675
5132
  */
4676
5133
  private applyCompactionToLiveMessages;
5134
+ /**
5135
+ * Executes post-run conversation message pre-compaction, scratchpad pruning, and
5136
+ * asynchronous memory extraction after an agent run completes (`finalizeAgentRun`).
5137
+ *
5138
+ * Shifting compaction and maintenance to the end of `finalizeAgentRun` removes
5139
+ * compaction latency from the next user turn's critical path so subsequent turns
5140
+ * start with a pre-compacted message window.
5141
+ *
5142
+ * ### Lifecycle Phases
5143
+ * 1. **Configuration Resolution**: Reads `params.compactAfterRun` (`boolean | AgentPostRunCompactionConfig`).
5144
+ * When `undefined`, `false`, or `{ enabled: false }`, returns immediately as a no-op.
5145
+ * When `true`, applies defaults `{ enabled: true, messageCountThreshold: 20, extractMemories: true }`.
5146
+ * 2. **Message Window Pre-Compaction**: When `params.conversationMessages.length >= messageCountThreshold`,
5147
+ * compacts older messages in `[1 .. length - preserveRecentCount - 1]` while preserving
5148
+ * the initial goal message (`index 0`) and the most recent messages intact. Delegates to
5149
+ * {@link compactMessage} (and {@link CompactToolResultContent} for native tool turns) so
5150
+ * behavior and expansion metadata (`wasCompacted`, `originalContent`, `canExpand`) are
5151
+ * 100% consistent with mid-run message compaction.
5152
+ * 3. **Scratchpad Pruning**: When `maxScratchpadNotes` is configured, prunes excess low-priority
5153
+ * scratchpad note lines (via {@link ScratchpadManager.PruneNotes}) and completed tasks
5154
+ * (via {@link ScratchpadManager.EnforceTaskLimit}) down to `maxScratchpadNotes`.
5155
+ * 4. **Memory Extraction Trigger**: When `extractMemories !== false` and `agentRun.Success` is `true`,
5156
+ * triggers asynchronous note/example extraction via {@link triggerPostRunMemoryExtraction}.
5157
+ *
5158
+ * Every phase is wrapped in its own `try/catch` block so an error in one phase is logged
5159
+ * via `LogError` without aborting the remaining phases or failing the completed agent run.
5160
+ *
5161
+ * @param params - The execution parameters for the completed agent run
5162
+ * @param agentRun - The finalized `MJAIAgentRunEntityExtended` record
5163
+ * @protected
5164
+ */
5165
+ protected runPostRunCompaction(params: ExecuteAgentParams, agentRun: MJAIAgentRunEntityExtended): Promise<void>;
5166
+ /**
5167
+ * Triggers asynchronous post-run note and example extraction via `MemoryManagerAgent`
5168
+ * when the executing agent has memory injection (`InjectNotes` or `InjectExamples`) enabled.
5169
+ *
5170
+ * No-ops when the executing agent itself is the `MemoryManagerAgent` (preventing recursion)
5171
+ * or when no active `MemoryManagerAgent` is registered in `AIEngine`.
5172
+ *
5173
+ * @param params - The execution parameters for the completed agent run
5174
+ * @param agentRun - The finalized `MJAIAgentRunEntityExtended` record
5175
+ * @protected
5176
+ */
5177
+ protected triggerPostRunMemoryExtraction(params: ExecuteAgentParams, agentRun: MJAIAgentRunEntityExtended): Promise<void>;
4677
5178
  /**
4678
5179
  * Creates an AIAgentRunStep for message compaction operations.
4679
5180
  * Records the compaction attempt with context about the message being compacted.
@@ -4696,7 +5197,7 @@ export declare class BaseAgent {
4696
5197
  */
4697
5198
  protected updateCompactionStep(step: MJAIAgentRunStepEntityExtended, result: AIPromptRunResult<{
4698
5199
  summary: string;
4699
- }>, message: AgentChatMessage, params: ExecuteAgentParams): Promise<void>;
5200
+ }>, message: AgentChatMessage, _params: ExecuteAgentParams): Promise<void>;
4700
5201
  /**
4701
5202
  * Compacts a message using configured compaction mode.
4702
5203
  *
@@ -4839,6 +5340,42 @@ export declare class BaseAgent {
4839
5340
  * for the paths where they differed.
4840
5341
  */
4841
5342
  protected getValueFromPath(obj: unknown, path: string): unknown;
5343
+ /**
5344
+ * The run's scope inputs: the explicit `ExecuteAgentParams` fields, else their `data` fallbacks, which count only
5345
+ * when the caller set `TrustReservedRunData`. {@link Execute} has already cleaned `data`; the rule is applied here
5346
+ * again for {@link ExecuteSingleAction} called outside a run (the realtime tool path, harnesses).
5347
+ */
5348
+ private runScopeInputs;
5349
+ /**
5350
+ * Secondary scopes as the run takes them: a plain object of dimension values, else none. A host assembles them at
5351
+ * runtime (often through `data`), so anything else — a JSON string, an array, a class instance — is not read as
5352
+ * dimensions (its keys would be character indexes or properties); it is logged and the run carries no secondary scope.
5353
+ */
5354
+ private scopeDimensions;
5355
+ /**
5356
+ * The run's scope as memory, retrieval and scoped prompt configuration take it: the scope {@link initializeAgentRun}
5357
+ * validated and wrote to the run row (`_runScope`; resolved the same way, {@link validatedRunScope}, outside a run),
5358
+ * with the primary entity resolved to its ID. One source, so notes and examples, pre-execution RAG, scoped prompt
5359
+ * parts and configs, the run row and every action dispatch see the same tenant and dimensions — trimmed, with the
5360
+ * agent's `ScopeConfig` defaults applied, and never a `data` scope the caller was not trusted to set.
5361
+ */
5362
+ private runScopeForContext;
5363
+ /** The run's scope ({@link runScopeForContext}) in the shape `ApplyScopedPromptConfig` takes. */
5364
+ private scopedPromptConfigScope;
5365
+ /** A scope identifier as text: a non-blank string (trimmed) or a number; anything else is no value. */
5366
+ private scopeText;
5367
+ /**
5368
+ * The run's scope as the run row records it and every action dispatch is handed it: the inputs from
5369
+ * {@link runScopeInputs}, the secondary dimensions validated with the agent's configured defaults applied
5370
+ * ({@link validateAndApplySecondaryScopes}), and `null` for whatever the run does not carry.
5371
+ */
5372
+ private validatedRunScope;
5373
+ /**
5374
+ * Writes the validated run scope onto the run row: the primary entity resolved to its ID (logged when it is
5375
+ * not in metadata), the tenant record ID and the secondary dimensions as JSON. A secondary-only scope on an
5376
+ * agent whose ScopeConfig does not allow one is logged, and still recorded.
5377
+ */
5378
+ private writeRunScope;
4842
5379
  /**
4843
5380
  * Parse the agent's SecondaryScopeConfig from the ScopeConfig field.
4844
5381
  * Returns null if not configured or invalid JSON.