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

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 (125) hide show
  1. package/README.md +44 -2
  2. package/dist/AgentRunner.d.ts +96 -3
  3. package/dist/AgentRunner.d.ts.map +1 -1
  4. package/dist/AgentRunner.js +438 -34
  5. package/dist/AgentRunner.js.map +1 -1
  6. package/dist/AgentWakeTriggerService.d.ts.map +1 -1
  7. package/dist/AgentWakeTriggerService.js +8 -1
  8. package/dist/AgentWakeTriggerService.js.map +1 -1
  9. package/dist/MJAIAgentRequestEntityServer.d.ts +15 -1
  10. package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
  11. package/dist/MJAIAgentRequestEntityServer.js +43 -3
  12. package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
  13. package/dist/MemoryWriteManager.d.ts +12 -0
  14. package/dist/MemoryWriteManager.d.ts.map +1 -1
  15. package/dist/MemoryWriteManager.js +18 -3
  16. package/dist/MemoryWriteManager.js.map +1 -1
  17. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  18. package/dist/agent-pre-execution-rag.js +1 -0
  19. package/dist/agent-pre-execution-rag.js.map +1 -1
  20. package/dist/agent-run-watchdog.d.ts +51 -13
  21. package/dist/agent-run-watchdog.d.ts.map +1 -1
  22. package/dist/agent-run-watchdog.js +89 -21
  23. package/dist/agent-run-watchdog.js.map +1 -1
  24. package/dist/agent-types/flow-agent-type.d.ts +6 -0
  25. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  26. package/dist/agent-types/flow-agent-type.js +70 -6
  27. package/dist/agent-types/flow-agent-type.js.map +1 -1
  28. package/dist/agent-types/loop-agent-prompt-params.d.ts +46 -3
  29. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  30. package/dist/agent-types/loop-agent-prompt-params.js +9 -4
  31. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  32. package/dist/agent-types/loop-agent-response-type.d.ts +35 -4
  33. package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
  34. package/dist/agent-types/loop-agent-response-type.js +1 -1
  35. package/dist/agent-types/loop-agent-response-type.js.map +1 -1
  36. package/dist/agent-types/loop-agent-type.d.ts +27 -4
  37. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  38. package/dist/agent-types/loop-agent-type.js +121 -18
  39. package/dist/agent-types/loop-agent-type.js.map +1 -1
  40. package/dist/base-agent.d.ts +390 -37
  41. package/dist/base-agent.d.ts.map +1 -1
  42. package/dist/base-agent.js +2046 -433
  43. package/dist/base-agent.js.map +1 -1
  44. package/dist/catalog-narrowing.d.ts.map +1 -1
  45. package/dist/catalog-narrowing.js +6 -3
  46. package/dist/catalog-narrowing.js.map +1 -1
  47. package/dist/client-tool-results.d.ts +12 -0
  48. package/dist/client-tool-results.d.ts.map +1 -1
  49. package/dist/client-tool-results.js +21 -0
  50. package/dist/client-tool-results.js.map +1 -1
  51. package/dist/handoff-target.d.ts +80 -0
  52. package/dist/handoff-target.d.ts.map +1 -0
  53. package/dist/handoff-target.js +158 -0
  54. package/dist/handoff-target.js.map +1 -0
  55. package/dist/index.d.ts +4 -0
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +4 -0
  58. package/dist/index.js.map +1 -1
  59. package/dist/memory-manager-agent.d.ts.map +1 -1
  60. package/dist/memory-manager-agent.js +2 -0
  61. package/dist/memory-manager-agent.js.map +1 -1
  62. package/dist/native-tools/action-tool-builder.d.ts +6 -0
  63. package/dist/native-tools/action-tool-builder.d.ts.map +1 -1
  64. package/dist/native-tools/action-tool-builder.js +21 -5
  65. package/dist/native-tools/action-tool-builder.js.map +1 -1
  66. package/dist/native-tools/control-tools.d.ts +15 -4
  67. package/dist/native-tools/control-tools.d.ts.map +1 -1
  68. package/dist/native-tools/control-tools.js +31 -14
  69. package/dist/native-tools/control-tools.js.map +1 -1
  70. package/dist/pipeline/pipeline-registry.d.ts +5 -12
  71. package/dist/pipeline/pipeline-registry.d.ts.map +1 -1
  72. package/dist/pipeline/pipeline-registry.js +28 -2
  73. package/dist/pipeline/pipeline-registry.js.map +1 -1
  74. package/dist/pipeline/providers/serialize.d.ts +7 -3
  75. package/dist/pipeline/providers/serialize.d.ts.map +1 -1
  76. package/dist/pipeline/providers/serialize.js +9 -5
  77. package/dist/pipeline/providers/serialize.js.map +1 -1
  78. package/dist/realtime/bridge-realtime-session-factory.d.ts +3 -3
  79. package/dist/realtime/bridge-realtime-session-factory.d.ts.map +1 -1
  80. package/dist/realtime/bridge-realtime-session-factory.js +12 -6
  81. package/dist/realtime/bridge-realtime-session-factory.js.map +1 -1
  82. package/dist/realtime/bridge-room-transcript-sink.js +2 -0
  83. package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
  84. package/dist/realtime/realtime-client-session-service.d.ts +72 -25
  85. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  86. package/dist/realtime/realtime-client-session-service.js +154 -54
  87. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  88. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  89. package/dist/realtime/realtime-coagent-config.js +2 -28
  90. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  91. package/dist/realtime/realtime-platform-credentials.d.ts +65 -0
  92. package/dist/realtime/realtime-platform-credentials.d.ts.map +1 -0
  93. package/dist/realtime/realtime-platform-credentials.js +148 -0
  94. package/dist/realtime/realtime-platform-credentials.js.map +1 -0
  95. package/dist/realtime/realtime-recording-capture.d.ts +1 -0
  96. package/dist/realtime/realtime-recording-capture.d.ts.map +1 -1
  97. package/dist/realtime/realtime-recording-capture.js +17 -3
  98. package/dist/realtime/realtime-recording-capture.js.map +1 -1
  99. package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -1
  100. package/dist/realtime/realtime-recording-opus-assembly.js +9 -4
  101. package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -1
  102. package/dist/realtime/realtime-session-runner.d.ts.map +1 -1
  103. package/dist/realtime/realtime-session-runner.js +5 -7
  104. package/dist/realtime/realtime-session-runner.js.map +1 -1
  105. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  106. package/dist/realtime/realtime-turn-moderator.js +1 -0
  107. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  108. package/dist/realtime/realtime-vendor-resolution.d.ts +41 -2
  109. package/dist/realtime/realtime-vendor-resolution.d.ts.map +1 -1
  110. package/dist/realtime/realtime-vendor-resolution.js +86 -4
  111. package/dist/realtime/realtime-vendor-resolution.js.map +1 -1
  112. package/dist/rubric-evaluation-agent-runner.js +1 -0
  113. package/dist/rubric-evaluation-agent-runner.js.map +1 -1
  114. package/dist/runtime-state-fragment.d.ts.map +1 -1
  115. package/dist/runtime-state-fragment.js +3 -0
  116. package/dist/runtime-state-fragment.js.map +1 -1
  117. package/dist/sub-agent-consult.d.ts +75 -0
  118. package/dist/sub-agent-consult.d.ts.map +1 -0
  119. package/dist/sub-agent-consult.js +193 -0
  120. package/dist/sub-agent-consult.js.map +1 -0
  121. package/dist/volatile-child-prompt.d.ts +7 -0
  122. package/dist/volatile-child-prompt.d.ts.map +1 -1
  123. package/dist/volatile-child-prompt.js +8 -0
  124. package/dist/volatile-child-prompt.js.map +1 -1
  125. package/package.json +20 -20
@@ -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, MJAIPromptRunEntity, type ConversationBranchRow } from '@memberjunction/core-entities';
13
+ import { MJAIAgentEntity, MJAIAgentTypeEntity, MJTemplateParamEntity, MJAIAgentRelationshipEntity, MJAIAgentConfigurationEntity, 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 { type NativeControlConfig } from './native-tools/native-control-config.js';
16
16
  import type { AgentToolDefinition } from './native-tools/agent-tools.js';
@@ -23,6 +23,7 @@ import { BaseAgentType } from './agent-types/base-agent-type.js';
23
23
  import { type CodeLang } from '@memberjunction/context-crush/code';
24
24
  import { RealtimeSessionRunnerDeps } from './realtime/realtime-session-runner.js';
25
25
  import { RealtimeCoAgentConfig } from './realtime/realtime-coagent-config.js';
26
+ import { RealtimePlatformCredentials } from './realtime/realtime-platform-credentials.js';
26
27
  import { AIEngine } from '@memberjunction/aiengine';
27
28
  import { AgentMemoryObservability } from './agent-memory-context-builder.js';
28
29
  import { CompactionOutcome, EffectiveContextBudget } from './ConversationCompactionManager.js';
@@ -30,13 +31,14 @@ import { ConversationToolCall, ConversationToolExecutionResult, ConversationTool
30
31
  import { CarryForwardStepRecord, StoppedRunStepRecord } from './tool-result-format.js';
31
32
  import { AgentPreExecutionRAGResult } from './agent-pre-execution-rag.js';
32
33
  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';
33
- import { MJActionEntityExtended, ActionResult, ActionParam, AIDirective } from '@memberjunction/actions-base';
34
+ import { MJActionEntityExtended, ActionResult, ActionParam, AIDirective, type ActionOutputTrustLevel, type ActionErrorRecovery } from '@memberjunction/actions-base';
34
35
  import { RuntimeStateDateTime, RuntimeStateScratchpad } from './runtime-state-fragment.js';
35
36
  import { ScratchpadManager } from './ScratchpadManager.js';
36
37
  import { ArtifactToolCall, StoredToolResult } from './ArtifactToolManager.js';
37
38
  import { MemoryWriteRequest, MemoryWriteResult } from './MemoryWriteManager.js';
38
39
  import { AgentDecisionService } from './AgentDecisionService.js';
39
40
  import { PipelineToolRegistry, PipelineExecutionResult } from './pipeline/index.js';
41
+ import type { AgentTaintedSource } from '@memberjunction/ai-core-plus';
40
42
  /**
41
43
  * Compact representation of a single action's execution result, used for
42
44
  * building the markdown summary that goes into conversation messages.
@@ -56,7 +58,7 @@ interface StoppedRunContinuation {
56
58
  Mode: StopContinuationMode;
57
59
  Steps: StoppedRunStackStepRecord[];
58
60
  }
59
- interface ActionResultSummary {
61
+ export interface ActionResultSummary {
60
62
  actionName: string;
61
63
  success: boolean;
62
64
  params: ActionParam[];
@@ -65,6 +67,10 @@ interface ActionResultSummary {
65
67
  aiDirectives?: AIDirective[];
66
68
  /** Set when the circuit breaker blocked the call without dispatching it. */
67
69
  breakerReason?: ActionCircuitBreakerReason;
70
+ /** Trust classification of the action's output ('Trusted' | 'SemiTrusted' | 'Untrusted'). */
71
+ trustLevel?: ActionOutputTrustLevel;
72
+ /** Structured recovery hints returned on action failure. */
73
+ errorRecovery?: ActionErrorRecovery;
68
74
  }
69
75
  /**
70
76
  * Resolved per-run configuration for structurally compressing inline action-result
@@ -125,6 +131,20 @@ export interface ExecuteSingleActionOptions {
125
131
  * across any arguments.
126
132
  */
127
133
  export type ActionCircuitBreakerReason = 'fatal' | 'audience' | 'identical-arguments' | 'attempts-exhausted';
134
+ /**
135
+ * What {@link BaseAgent.classifyActionFailure} names for a failed action: the breaker rule that fired, a refusal by
136
+ * the user's agent policy (`'policy'` — governance, not a parameter error, so the guidance must not tell the model
137
+ * to adjust its arguments and retry), or a plain `'warning'`.
138
+ */
139
+ export type ActionFailureClass = ActionCircuitBreakerReason | 'policy' | 'non-retryable' | 'warning';
140
+ /** Result codes that are structurally non-retryable (permission or run-scope refusals). */
141
+ export declare const NON_RETRYABLE_RESULT_CODES: ReadonlySet<string>;
142
+ /** Result code of a call the user's agent policy denies outright (`checkUserActionPolicy`). */
143
+ export declare const POLICY_DENIED_RESULT_CODE = "POLICY_DENIED";
144
+ /** Result code of a call the user's agent policy allows only with the user's approval. */
145
+ export declare const POLICY_APPROVAL_REQUIRED_RESULT_CODE = "POLICY_APPROVAL_REQUIRED";
146
+ /** Result code of a call the user's agent policy defers to its next allowed time window. */
147
+ export declare const POLICY_DEFERRED_RESULT_CODE = "POLICY_DEFERRED_OUTSIDE_TIME_WINDOW";
128
148
  /** Identical-arguments rule: this many failures with the same arguments block further identical calls. */
129
149
  export declare const IDENTICAL_FAILURE_THRESHOLD = 2;
130
150
  /** Attempt budget: this many consecutive failures, across any arguments, disable the action for the run. */
@@ -299,6 +319,22 @@ export declare class BaseAgent {
299
319
  * @private
300
320
  */
301
321
  private _runScope;
322
+ /**
323
+ * External/untrusted data sources ingested during the current agent run (Primitive 2).
324
+ * Once non-empty, {@link IsRunTainted} is true for the remainder of the run and any memory
325
+ * notes written by the run land as `Status = 'Pending'` with taint provenance in `Comments`.
326
+ * @protected
327
+ */
328
+ protected _taintedSources: AgentTaintedSource[];
329
+ /**
330
+ * True when the current agent run has ingested at least one `'Untrusted'` or `'SemiTrusted'`
331
+ * action or client-tool result.
332
+ */
333
+ get IsRunTainted(): boolean;
334
+ /**
335
+ * Read-only view of all `'Untrusted'` and `'SemiTrusted'` sources ingested during the current run.
336
+ */
337
+ get TaintedSources(): ReadonlyArray<AgentTaintedSource>;
302
338
  /**
303
339
  * Parameter-aware failure tracking per action name for the current agent run.
304
340
  * Differentiates identical retries (which trip quickly) from parameter modifications (which allow self-correction).
@@ -462,9 +498,41 @@ export declare class BaseAgent {
462
498
  * the action is blocked whatever the arguments are, and telling the model to change them
463
499
  * would send it in circles.
464
500
  */
465
- protected classifyActionFailure(summary: ActionResultSummary): ActionCircuitBreakerReason | 'warning';
501
+ protected classifyActionFailure(summary: ActionResultSummary): ActionFailureClass;
502
+ /**
503
+ * The guidance line for a call the user's agent policy refused. The default `[WARNING/ACTION_FAILURE]`
504
+ * line tells the model to adjust its parameters and try again, up to the budget; a refusal is not a
505
+ * parameter error, and a retry burns the budget without ever succeeding.
506
+ */
507
+ private formatPolicyRefusalDirective;
466
508
  /** The guidance line appended to the history for one failed action. */
467
509
  protected formatActionFailureDirective(summary: ActionResultSummary): string;
510
+ /**
511
+ * Resolves the output trust classification for an action from its `MJ: Actions` metadata
512
+ * (`actionEntity.Config_Object?.outputTrustLevel`), with per-agent or per-run overrides via
513
+ * `AgentTypePromptParams`.
514
+ *
515
+ * Precedence:
516
+ * 1. An explicit per-action `actionTrustLevels` entry in `AgentTypePromptParams` — the operator's last word
517
+ * 2. The `trustedActionNames` / `untrustedActionNames` lists in `AgentTypePromptParams`
518
+ * 3. The action's metadata catalog setting (`Action.Config_Object?.outputTrustLevel`, looking up the
519
+ * action by name in `ActionEngineBase.Instance.Actions` when `actionEntity` is omitted)
520
+ * 4. `'Trusted'`
521
+ * @protected
522
+ */
523
+ protected resolveActionTrustLevel(actionName: string, actionEntity?: MJActionEntityExtended, params?: ExecuteAgentParams): ActionOutputTrustLevel;
524
+ /**
525
+ * Records a tainted source ingested during the current agent run.
526
+ * @protected
527
+ */
528
+ protected recordTaintedSource(stepNumber: number, sourceName: string, trustLevel: AgentTaintedSource['trustLevel']): void;
529
+ /**
530
+ * Folds a finished sub-agent's tainted sources into this run's, attributed to the sub-agent step,
531
+ * so delegating a web search taints the parent exactly as searching itself would. Runs whether or
532
+ * not the child succeeded: a failed child may still have read external content.
533
+ * @protected
534
+ */
535
+ protected absorbSubAgentTaint(subAgentName: string, subAgentResult: Pick<ExecuteAgentResult, 'taintedSources'>, stepNumber: number): void;
468
536
  /**
469
537
  * Returns the active metadata provider for this agent run. Subclasses MUST
470
538
  * use this getter (rather than `new Metadata()` or `Metadata.Provider`) so
@@ -563,6 +631,15 @@ export declare class BaseAgent {
563
631
  * @private
564
632
  */
565
633
  private _feedbackRequestId;
634
+ /**
635
+ * Stores the handoff outcome when a Handoff step fires.
636
+ * Populated by executeHandoffStep(), returned in ExecuteAgentResult.handoff.
637
+ */
638
+ private _handoffResult;
639
+ /**
640
+ * Stores the target agent resolved during validateHandoffNextStep() for executeHandoffStep().
641
+ */
642
+ private _resolvedHandoffTarget;
566
643
  private _resolvedStorageAccountId;
567
644
  /**
568
645
  * Most recent artifactDirective returned by a child or related sub-agent during this run.
@@ -603,14 +680,14 @@ export declare class BaseAgent {
603
680
  * // Note: If no presets configured, returns empty array - agent will use default behavior
604
681
  * ```
605
682
  */
606
- GetConfigurationPresets(agentId: string): import("@memberjunction/core-entities").MJAIAgentConfigurationEntity[];
683
+ GetConfigurationPresets(agentId: string): MJAIAgentConfigurationEntity[];
607
684
  /**
608
685
  * Gets the default configuration preset for an agent.
609
686
  *
610
687
  * @param agentId - The ID of the agent to get the default preset for
611
688
  * @returns The default preset, or undefined if none configured
612
689
  */
613
- GetDefaultConfigurationPreset(agentId: string): import("@memberjunction/core-entities").MJAIAgentConfigurationEntity;
690
+ GetDefaultConfigurationPreset(agentId: string): MJAIAgentConfigurationEntity;
614
691
  /**
615
692
  * Promotes media outputs to the agent's final outputs.
616
693
  * Call this method to add generated images, audio, or video to the agent's outputs.
@@ -695,19 +772,20 @@ export declare class BaseAgent {
695
772
  private interceptLargeBinaryContent;
696
773
  /**
697
774
  * Substitutes `${media:<refId>}` placeholders in a string with the actual
698
- * data URI (`data:<mime>;base64,<bytes>`) of the matching intercepted media item.
775
+ * data URI (`data:<mime>;base64,<bytes>`) or stored `fileId` (for `fileId`-only
776
+ * media items) of the matching intercepted media item.
699
777
  *
700
778
  * Used for payload / actionable-command resolution at the terminal step, where the
701
- * LLM wants to embed image (or other media) data inline at a specific position in
702
- * its structured output rather than as a trailing attachment card. The string
703
- * variant of placeholder resolution; recursive walker lives in
704
- * {@link resolveMediaPlaceholdersInPayload}.
779
+ * LLM wants to embed image (or other media) data or a stored file ID inline at a
780
+ * specific position in its structured output rather than only as a trailing
781
+ * attachment card. The string variant of placeholder resolution; recursive walker
782
+ * lives in {@link resolveMediaPlaceholdersInPayload}.
705
783
  *
706
784
  * This function only does substitution — it has no persistence side effects.
707
785
  *
708
786
  * @param text - The string that may contain media placeholders
709
- * @returns String with placeholders resolved to actual data URIs (or the original
710
- * placeholder if the refId is unknown — defensive, shouldn't happen)
787
+ * @returns String with placeholders resolved to data URIs or stored file IDs (or the
788
+ * original placeholder if the refId is unknown — defensive, shouldn't happen)
711
789
  * @private
712
790
  * @since 3.1.0
713
791
  */
@@ -867,6 +945,14 @@ export declare class BaseAgent {
867
945
  * @private
868
946
  */
869
947
  private _effectiveSubAgents;
948
+ /**
949
+ * True once gatherPromptTemplateData() has computed {@link _effectiveActions} and
950
+ * {@link _effectiveSubAgents} for this run. An empty list is then authoritative: a host's
951
+ * `actionChanges` that remove every action leave the run with none, instead of falling back to
952
+ * the agent's database configuration as an uncomputed list does.
953
+ * @private
954
+ */
955
+ private _effectiveCatalogComputed;
870
956
  /**
871
957
  * The merged agent-type prompt params of the current step. Populated during
872
958
  * gatherPromptTemplateData() and read by the finishIf gate, which runs in executeActionsStep()
@@ -1002,6 +1088,29 @@ export declare class BaseAgent {
1002
1088
  * @private
1003
1089
  */
1004
1090
  private _validationRetryCount;
1091
+ /**
1092
+ * Per-parent-run consultation round counter keyed by `subAgentEntity.ID`.
1093
+ * Tracks how many times each sub-agent has returned `FinalStep === 'Chat'`
1094
+ * under `ChatHandlingOption = 'Consult'` during this run.
1095
+ * Reset at the start of each agent run.
1096
+ * @private
1097
+ */
1098
+ private _subAgentConsultRounds;
1099
+ /**
1100
+ * Open sub-agent consultations keyed by `childRunId`.
1101
+ * Populated when a child sub-agent pauses with `FinalStep === 'Chat'` under `'Consult'`,
1102
+ * and removed when the parent resumes that child run.
1103
+ * Reset at the start of each agent run.
1104
+ * @private
1105
+ */
1106
+ private _openSubAgentConsults;
1107
+ /**
1108
+ * Tracks whether we have already logged the warning that `'Consult'` is not
1109
+ * supported on agent types where `InjectLoopResultsAsMessage` is `false`.
1110
+ * Reset at the start of each agent run.
1111
+ * @private
1112
+ */
1113
+ private _loggedConsultUnsupportedAgentType;
1005
1114
  /**
1006
1115
  * Counter tracking the number of context recovery attempts made in this run.
1007
1116
  * Context recovery removes/compacts old messages when context length is exceeded.
@@ -1110,6 +1219,12 @@ export declare class BaseAgent {
1110
1219
  */
1111
1220
  protected get DefaultAgentTimeoutMS(): number;
1112
1221
  Execute<C = any, R = any>(params: ExecuteAgentParams<C>): Promise<ExecuteAgentResult<R>>;
1222
+ /**
1223
+ * {@link Execute}'s per-run teardown, called from its top-level `finally` on every exit path.
1224
+ * The run leaves the watchdog first, before the subclass {@link finalizeRun} hook, so a hook
1225
+ * that throws can never leave a finished run being heart-beaten for the life of the process.
1226
+ */
1227
+ private endRun;
1113
1228
  /**
1114
1229
  * Fails the run at its start, before any prompt: marks the already-created AgentRun Failed with the message
1115
1230
  * (so it never shows as a phantom "running" record) and throws, which {@link Execute} turns into a failure
@@ -1155,7 +1270,8 @@ export declare class BaseAgent {
1155
1270
  * (`TaskGraphAgentRunner`) that carries neither the audience nor the scope. So graphs are withheld when the
1156
1271
  * audience adds a reader, and when the run's validated scope carries a tenant or a secondary dimension
1157
1272
  * (`ActionRunScopeIsBounded`): a model-written Scoped Search node would search outside the run's tenant, and an
1158
- * agent node would drop it.
1273
+ * agent node would drop it. Likewise when the host assigned the run's search scopes (`SearchScopeIDs`): a graph's
1274
+ * Scoped Search node would fall back to the agent's own search access.
1159
1275
  */
1160
1276
  private taskGraphWithholdingReason;
1161
1277
  /** Whether this run withholds task graphs ({@link taskGraphWithholdingReason}). */
@@ -1167,9 +1283,18 @@ export declare class BaseAgent {
1167
1283
  */
1168
1284
  private taskGraphRefusal;
1169
1285
  /**
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.
1286
+ * Whether this run withholds Handoff (`enableHandoff` off and the `handoff` response section hidden).
1287
+ * True when the run has a `parentRun` (sub-agents cannot transfer the conversation), has no
1288
+ * `conversationDetailId` (there is no conversation reply row to hand over), has no `handoffChain`
1289
+ * (the host does not carry out handoffs), or runs for an anonymous/widget guest without a trusted
1290
+ * host allow-list (`TrustReservedRunData === true` and `HostAllowedAgentIDs(params.data)` defined).
1291
+ */
1292
+ private runWithholdsHandoff;
1293
+ /**
1294
+ * What this run's prompt leaves out: task graphs ({@link taskGraphWithholdingReason}), handoff
1295
+ * ({@link runWithholdsHandoff}), and — when the audience adds a reader — the caller's own browser
1296
+ * and view (`CallerContext`): client tools run in the caller's browser and what they return reaches
1297
+ * the room, and the app context (`data.appContext`, with its `AdditionalContext`) is the caller's screen.
1173
1298
  */
1174
1299
  private promptWithholding;
1175
1300
  /**
@@ -1191,6 +1316,11 @@ export declare class BaseAgent {
1191
1316
  * response section hidden). A copy, never a write: the input may be the process-wide cached base.
1192
1317
  */
1193
1318
  private withoutTaskGraphs;
1319
+ /**
1320
+ * A copy of the agent-type prompt params with handoff withheld (`enableHandoff` off and the `handoff`
1321
+ * response section hidden). A copy, never a write: the input may be the process-wide cached base.
1322
+ */
1323
+ private withoutHandoff;
1194
1324
  /**
1195
1325
  * Why a session-driven (realtime / voice / bridge) run is refused, or null. A live session speaks and calls
1196
1326
  * tools outside the gates that hold a run to its audience, so a run whose audience adds a reader is refused.
@@ -1348,6 +1478,15 @@ export declare class BaseAgent {
1348
1478
  * @param params The execution parameters.
1349
1479
  */
1350
1480
  private realtimeRunShowsAvatar;
1481
+ /**
1482
+ * The platform MJ Credentials of the candidate realtime models' vendors, read as the run's user.
1483
+ * **Overridable seam** so tests can supply credentials without a credential store. Under a
1484
+ * `'RuntimeOnly'` scope it resolves none.
1485
+ *
1486
+ * @param modelIDs The candidate `MJ: AI Models` row ids.
1487
+ * @param params The execution parameters (context user and credential scope).
1488
+ */
1489
+ protected resolveRealtimePlatformCredentials(modelIDs: string[], params: ExecuteAgentParams): Promise<RealtimePlatformCredentials>;
1351
1490
  /**
1352
1491
  * A vendor's realtime driver on its key, with the model and vendor identifiers a run resolves to; `null` when the
1353
1492
  * key or the driver is missing.
@@ -2139,6 +2278,10 @@ export declare class BaseAgent {
2139
2278
  * Keeps the system-prompt-and-tools fingerprint of the request just sent, for the next one. When
2140
2279
  * it changed, the runner sent this request without replayed reasoning; the history drops it too,
2141
2280
  * so no later request replays a block made under the old prompt or tools.
2281
+ *
2282
+ * A result with no fingerprint (a request that failed before or while it was sent, such as a
2283
+ * failover that ran out of candidates) leaves the baseline as it was. Clearing it would let the
2284
+ * next request skip the comparison and replay thinking made under a prompt or tools it no longer has.
2142
2285
  */
2143
2286
  private trackSentPrefix;
2144
2287
  /** What makes a message the same message to a provider — reasoning aside, which only this check removes. */
@@ -2188,8 +2331,10 @@ export declare class BaseAgent {
2188
2331
  * declares native tools to a driver whose replayed reasoning needs the history before it
2189
2332
  * unchanged is append-only too (see {@link ResolveAppendOnlyState}).
2190
2333
  *
2191
- * Decided ONCE per run. An explicit `trailingStateMode` or a runtime model override answers
2192
- * immediately. Otherwise the answer is frozen at the first model selection and reused for every
2334
+ * Decided ONCE per run. An explicit `trailingStateMode` answers immediately, and so does a runtime
2335
+ * model override that names a vendor, or whose catalog says the cache is a byte-prefix cache.
2336
+ * Otherwise (no override, or one that names no vendor and whose catalog does not say yes) the
2337
+ * answer is frozen at the first model selection and reused for every
2193
2338
  * later turn, so a failover to another vendor cannot flip the layout mid-run — a flip after turn 2
2194
2339
  * would leave stale fragments in the history or, worse, restore the wrong turn's fragment. On turn 1,
2195
2340
  * before any selection is known, the answer is replace-in-place: turn 1's fragment is kept and, if
@@ -2359,6 +2504,22 @@ export declare class BaseAgent {
2359
2504
  */
2360
2505
  protected getRequestedSubAgents<P, C>(nextStep: BaseAgentNextStep<P, C> | undefined | null): AgentSubAgentRequest<C>[];
2361
2506
  protected validateSubAgentNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2507
+ /**
2508
+ * Strips an optional `delegate_to_` native sub-agent tool prefix when a model running
2509
+ * with native tool calling references a sub-agent by its declared tool name inside an
2510
+ * envelope primitive (`Sub-Agent`, `ForEach`, `While`, or `Tasks`).
2511
+ */
2512
+ protected stripSubAgentToolPrefix(rawName: string): string;
2513
+ /**
2514
+ * Resolves a unique entity from `pool` whose sanitized native tool name matches `rawName`.
2515
+ * Returns `{ ambiguous }` when multiple entities collide on the same sanitized name.
2516
+ */
2517
+ protected matchNamedBySanitizedToolName<T extends {
2518
+ Name?: string | null;
2519
+ }>(rawName: string, pool: readonly T[], stripSubAgentPrefix?: boolean): {
2520
+ match?: T;
2521
+ ambiguous?: T[];
2522
+ };
2362
2523
  /**
2363
2524
  * Builds a compact hint listing the current user's permitted runnable agents when a
2364
2525
  * task-graph or folded sub-agent step references an unknown or inaccessible agent name.
@@ -2368,11 +2529,9 @@ export declare class BaseAgent {
2368
2529
  * Validates a `'Tasks'` next step before `executeTasksStep` submits the graph.
2369
2530
  *
2370
2531
  * 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.
2532
+ * active and runnable by `params.contextUser`, and that every referenced `Action` (including
2533
+ * multi-step `steps[]` loop bodies) is active. Accepts sanitized native tool names
2534
+ * (`calculate_expression`, `delegate_to_query_builder`) and canonicalizes them in place.
2376
2535
  */
2377
2536
  protected validateTasksNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, _currentPayload: P, _agentRun: MJAIAgentRunEntityExtended, _currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2378
2537
  /**
@@ -2385,7 +2544,8 @@ export declare class BaseAgent {
2385
2544
  protected validateActionsNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2386
2545
  /**
2387
2546
  * Gets the effective actions for validation, using runtime changes if available.
2388
- * Falls back to database-configured actions if _effectiveActions is empty.
2547
+ * Falls back to database-configured actions only when the list was never computed for this run;
2548
+ * a computed empty list (a host's actionChanges removed every action) is returned as-is.
2389
2549
  *
2390
2550
  * @param agentId - The ID of the agent to get actions for
2391
2551
  * @returns Array of effective actions available to the agent
@@ -2393,9 +2553,35 @@ export declare class BaseAgent {
2393
2553
  * @since 2.123.0
2394
2554
  */
2395
2555
  protected getEffectiveActionsForValidation(agentId: string): MJActionEntityExtended[];
2556
+ /**
2557
+ * Returns active actions referenced directly by an agent's Flow steps (`AIAgentStep.ActionID`
2558
+ * plus any `steps[].name` inside a `ForEach`/`While` Flow step's `Configuration` JSON).
2559
+ * Flow agents bind actions on `AIAgentStep` rather than `AIAgentAction`, so in-run Flow loops
2560
+ * need these actions in scope alongside {@link getEffectiveActionsForValidation}.
2561
+ */
2562
+ private getFlowStepActions;
2563
+ /**
2564
+ * Combines {@link getEffectiveActionsForValidation} with {@link getFlowStepActions} (deduplicated
2565
+ * by `ID`) so both Loop agents (strictly `AIAgentAction` / `_effectiveActions`) and Flow agents
2566
+ * (`AIAgentStep` / `Configuration.steps[]`) resolve permitted actions consistently.
2567
+ */
2568
+ private getAvailableActionsForAgent;
2569
+ /**
2570
+ * Resolves an action name against `pool` without mutating caller objects:
2571
+ * 1) exact case-insensitive match, 2) unambiguous sanitized native tool-name match,
2572
+ * 3) unambiguous CONTAINS partial match.
2573
+ */
2574
+ private resolveActionEntityForAgent;
2575
+ /**
2576
+ * Returns a deep-cloned `TaskGraphSpec` with sanitized native tool names (`calculate_expression`,
2577
+ * `delegate_to_query_builder`) canonicalized to exact metadata names before durable submission,
2578
+ * without mutating the caller's `spec`.
2579
+ */
2580
+ private canonicalizeTaskGraphSpec;
2396
2581
  /**
2397
2582
  * Gets the effective sub-agents for validation, using runtime subAgentChanges if available.
2398
- * Falls back to the database-configured relationship set if _effectiveSubAgents is empty.
2583
+ * Falls back to the database-configured relationship set only when the list was never computed
2584
+ * for this run; a computed empty list is returned as-is.
2399
2585
  * Mirrors {@link getEffectiveActionsForValidation}.
2400
2586
  *
2401
2587
  * @param agentId - The ID of the agent to get sub-agents for
@@ -2421,6 +2607,17 @@ export declare class BaseAgent {
2421
2607
  * @protected
2422
2608
  */
2423
2609
  protected validatePlanNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2610
+ /**
2611
+ * Validates a `'Handoff'` next step: re-checks the runtime withholding conditions (sub-agent run,
2612
+ * missing `conversationDetailId`, or missing `handoffChain`) and validates the requested target
2613
+ * via {@link ResolveHandoffTarget} (Active status, `'view'` and `'run'` permissions, direct
2614
+ * discoverability, host allow-list, cycle check, and hop limit). On refusal, writes a Failed
2615
+ * `'Handoff'` step and returns a `'Retry'` step naming up to 20 candidate agents; on approval,
2616
+ * stores the resolved target ID and name for {@link executeHandoffStep}.
2617
+ *
2618
+ * @protected
2619
+ */
2620
+ protected validateHandoffNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, _currentPayload: P, _agentRun: MJAIAgentRunEntityExtended, _currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2424
2621
  /**
2425
2622
  * Validates that the Success next step is valid and can be executed by the current agent. Subclasses can override
2426
2623
  * this method to implement custom validation logic if needed.
@@ -2457,16 +2654,50 @@ export declare class BaseAgent {
2457
2654
  * @returns
2458
2655
  */
2459
2656
  protected validateRetryNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2657
+ /**
2658
+ * Resolves the effective `ChatHandlingOption` for a sub-agent execution:
2659
+ * `relationship?.ChatHandlingOption ?? parentAgent.ChatHandlingOption ?? null`.
2660
+ * @private
2661
+ */
2662
+ private resolveSubAgentChatHandlingOption;
2663
+ /**
2664
+ * Returns `true` only when `resolvedOption === 'Consult'` AND the parent agent's
2665
+ * type supports injecting loop/consult messages into conversation history
2666
+ * (`this.AgentTypeInstance?.InjectLoopResultsAsMessage !== false`).
2667
+ *
2668
+ * When `resolvedOption === 'Consult'` and `this.AgentTypeInstance?.InjectLoopResultsAsMessage === false`
2669
+ * (e.g., a Flow parent), logs a warning once per run and returns `false` so `'Consult'`
2670
+ * is treated as `null` (propagate).
2671
+ * @private
2672
+ */
2673
+ private isSubAgentConsultActive;
2674
+ /**
2675
+ * Resolves the sub-agent `ChatHandlingOption` and downgrades `'Consult'` to `null`
2676
+ * when `isSubAgentConsultActive` returns `false` (e.g., on Flow parents).
2677
+ * @private
2678
+ */
2679
+ private effectiveSubAgentChatHandlingOption;
2680
+ /**
2681
+ * Side-effect-free check used during prompt and native-tool construction to determine
2682
+ * whether `'Consult'` is active for a specific sub-agent of `parentAgent`.
2683
+ * @private
2684
+ */
2685
+ private isSubAgentConsultEnabledForSubAgent;
2460
2686
  /**
2461
2687
  * Validates that the Chat next step is valid and can be executed by the current agent.
2462
- * Implements ChatHandlingOption remapping logic - if the agent has ChatHandlingOption set,
2463
- * the Chat step is remapped to the specified value (Success, Fail, or Retry).
2688
+ * Implements ChatHandlingOption remapping logic - if the agent (or sub-agent relationship)
2689
+ * has ChatHandlingOption set:
2690
+ * - `'Consult'`: leaves the Chat step unchanged (an agent's own Chat propagates to its caller;
2691
+ * sub-agent Consult is intercepted before this validator).
2692
+ * - `'Success'` / `'Failed'`: remaps `step` while preserving `terminate: true` to end the run.
2693
+ * - `'Retry'`: remaps `step` to `'Retry'`, sets `terminate: false` so the loop continues, and
2694
+ * populates `errorMessage` so the unproductive-retry safety net bounds repeated Chat attempts.
2464
2695
  * Subclasses can override this method to implement custom validation logic if needed.
2465
2696
  * @param params
2466
2697
  * @param nextStep
2467
2698
  * @returns
2468
2699
  */
2469
- protected validateChatNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2700
+ protected validateChatNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended, chatHandlingOption?: MJAIAgentEntity['ChatHandlingOption']): Promise<BaseAgentNextStep<P>>;
2470
2701
  /**
2471
2702
  * Checks execution guardrails and modifies next step if limits are exceeded.
2472
2703
  * This method is called after validation but before execution of non-terminal steps.
@@ -2729,6 +2960,14 @@ export declare class BaseAgent {
2729
2960
  * @protected
2730
2961
  */
2731
2962
  protected processNextStep<P>(nextStep: BaseAgentNextStep<P>, params: ExecuteAgentParams, agentType: MJAIAgentTypeEntity, promptResult: AIPromptRunResult, currentPayload: P, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2963
+ /**
2964
+ * A completion refused with a payload change in hand: the change is discarded (the prompt step
2965
+ * commits it only for an accepted completion), so the refusal the model reads says so, and asks
2966
+ * for the change again with the next completion. Otherwise the model would take the change as
2967
+ * saved and its work would be lost. The change is removed from the step, so nothing later
2968
+ * applies it. Any other step is returned as it is.
2969
+ */
2970
+ private noteDiscardedCompletionChange;
2732
2971
  /**
2733
2972
  * Answers a retried native tool-call turn in the protocol itself: every call gets an `is_error`
2734
2973
  * result carrying the retry reason, and no user message follows.
@@ -2820,6 +3059,20 @@ export declare class BaseAgent {
2820
3059
  * @protected
2821
3060
  */
2822
3061
  protected applyStoppedRunContinuation(params: ExecuteAgentParams, continuation: StoppedRunContinuation | null, continuationMessage: ChatMessage | undefined): void;
3062
+ /**
3063
+ * Loads unanswered sub-agent consultations (`OutputData.consult`) from `params.lastRunId` when that
3064
+ * prior run paused with `FinalStep === 'Chat'` (and was not stopped by the user). Runs at any depth
3065
+ * so a middle agent resumed via `resumeRunId` also reloads its own open child consults. Fail-soft.
3066
+ * @private
3067
+ */
3068
+ private loadOpenConsults;
3069
+ /**
3070
+ * Restores reloaded open sub-agent consults into `this._openSubAgentConsults` (so `resumeRunId`
3071
+ * validation accepts them) and splices a `sub-agent-consult` reminder message immediately before
3072
+ * `continuationMessage` (the caller's answer). Fail-soft.
3073
+ * @private
3074
+ */
3075
+ private applyOpenConsults;
2823
3076
  /**
2824
3077
  * The full-stack half of {@link applyStoppedRunContinuation}: true when the stopped run's turns were
2825
3078
  * spliced in. Any failure leaves the messages untouched and returns false, so the caller carries
@@ -3775,11 +4028,12 @@ export declare class BaseAgent {
3775
4028
  * @param {AgentSubAgentRequest} subAgentRequest - Sub-agent request details
3776
4029
  * @param {MJAIAgentEntityExtended} subAgent - The sub-agent entity
3777
4030
  * @param {ChatMessage | undefined} contextMessage - Optional context from SubAgentContextPaths
4031
+ * @param {string | null | undefined} consultQuestion - Optional open-consult question when resuming a child run
3778
4032
  * @returns {ChatMessage[]} Prepared message array for sub-agent execution
3779
4033
  *
3780
4034
  * @protected
3781
4035
  */
3782
- protected prepareSubAgentMessages(params: ExecuteAgentParams, subAgentRequest: AgentSubAgentRequest, subAgent: MJAIAgentEntityExtended, contextMessage?: ChatMessage): ChatMessage[];
4036
+ protected prepareSubAgentMessages(params: ExecuteAgentParams, subAgentRequest: AgentSubAgentRequest, subAgent: MJAIAgentEntityExtended, contextMessage?: ChatMessage, consultQuestion?: string | null): ChatMessage[];
3783
4037
  /**
3784
4038
  * Executes a sub-agent synchronously.
3785
4039
  *
@@ -3807,6 +4061,17 @@ export declare class BaseAgent {
3807
4061
  * ```
3808
4062
  */
3809
4063
  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>>;
4064
+ /**
4065
+ * Resolves the configuration to pass to a sub-agent run in precedence order:
4066
+ * 1. Per-call `subAgentRequest.presetName` -> matching Active preset of `subAgent`.
4067
+ * 2. Active `AIAgentRelationship.ConfigurationPresetID` -> that preset if Active and owned by `subAgent`;
4068
+ * otherwise logs a warning and falls through.
4069
+ * 3. Inherit `params.configurationId`.
4070
+ *
4071
+ * When a preset is selected, `configurationId` is `preset.AIConfigurationID ?? undefined` (a NULL
4072
+ * `AIConfigurationID` means default rows and intentionally does NOT inherit `params.configurationId`).
4073
+ */
4074
+ private resolveSubAgentConfiguration;
3810
4075
  /**
3811
4076
  * A sub-agent request's template parameters without the host-only run-data keys
3812
4077
  * (`HOST_ONLY_AGENT_RUN_DATA_KEYS` in `@memberjunction/ai-core-plus`: the reserved scope family and
@@ -3858,6 +4123,16 @@ export declare class BaseAgent {
3858
4123
  * @private
3859
4124
  */
3860
4125
  private formatActionDetails;
4126
+ /**
4127
+ * The client tools in force for a run: the agent's static metadata tools under the session, app
4128
+ * and override tiers, merged by {@link ResolveClientTools} with its fixed precedence. The prompt
4129
+ * section and the client-tool step both resolve through here, so the tools the model is offered
4130
+ * and the metadata its results are classified against are one list.
4131
+ *
4132
+ * @param data - The run's data bag: `sessionID` selects the session tier, `appContext` the app
4133
+ * tier, `clientTools` the override tier.
4134
+ */
4135
+ private resolveClientToolsForRun;
3861
4136
  /**
3862
4137
  * Build the client tool prompt section for system prompt injection.
3863
4138
  *
@@ -3925,9 +4200,9 @@ export declare class BaseAgent {
3925
4200
  *
3926
4201
  * @param actionSummaries - The action summary objects built by executeActionStep
3927
4202
  * @returns Compact markdown string
3928
- * @private
4203
+ * @protected
3929
4204
  */
3930
- private formatActionResultsAsMarkdown;
4205
+ protected formatActionResultsAsMarkdown(actionSummaries: ActionResultSummary[]): string;
3931
4206
  /**
3932
4207
  * Formats an ExecuteAgentResult as compact markdown for inclusion in
3933
4208
  * conversation messages. Extracts only the fields that are meaningful
@@ -4378,6 +4653,28 @@ export declare class BaseAgent {
4378
4653
  *
4379
4654
  * @private
4380
4655
  */
4656
+ /** Whether a step is a completion that carries a payload change, which is held until the completion is accepted. */
4657
+ private static carriesCompletionChange;
4658
+ /**
4659
+ * Applies a turn's `payloadChangeRequest` to `current` and returns the result; `current` is not
4660
+ * changed. Honours `PayloadSelfWritePaths`. A brand-new artifact whose payload is still the one
4661
+ * inherited from a prior run (or that uses `replaceElements`) is built on an empty object, so
4662
+ * keys from the previous artifact cannot bleed in.
4663
+ */
4664
+ private applyTurnPayloadChange;
4665
+ /**
4666
+ * The payload a completion would leave behind: the committed payload with the completion's
4667
+ * change applied. Success validation (the minimum-execution check, then `FinalPayloadValidation`)
4668
+ * checks this draft, and it becomes the payload only if the completion is accepted. The
4669
+ * opt-in payload change check is not asked here: it never runs on a step that ends the run.
4670
+ */
4671
+ private buildCompletionDraft;
4672
+ /**
4673
+ * The payload a turn leaves behind. A held completion draft is committed only when the step is
4674
+ * still `Success` after validation; on a refusal the committed payload stands (a subclass that
4675
+ * set a payload of its own still wins). Without a draft, a subclass's `newPayload` wins as before.
4676
+ */
4677
+ private resolveTurnPayload;
4381
4678
  private executePromptStep;
4382
4679
  /**
4383
4680
  * Computes the upstream and downstream paths for a sub-agent based on the agent's payload paths.
@@ -4568,6 +4865,23 @@ export declare class BaseAgent {
4568
4865
  */
4569
4866
  private recordParallelStepCompletion;
4570
4867
  private executeParallelSubAgents;
4868
+ /**
4869
+ * Pushes a sub-agent result or consult message to the parent's conversation history,
4870
+ * answering natively-invoked `delegate_to_*` calls as a tool-result turn when applicable
4871
+ * and applying expiration defaults / overrides.
4872
+ *
4873
+ * @private
4874
+ */
4875
+ private pushSubAgentConversationMessage;
4876
+ /**
4877
+ * Unified handler for a single sub-agent (child, related, or runtime-granted) that
4878
+ * finished with `FinalStep === 'Chat'`. Resolves `ChatHandlingOption` for the pairing,
4879
+ * runs the consult flow when `'Consult'` is active and within the per-sub-agent round
4880
+ * bound, and otherwise finalizes the step and delegates to `validateChatNextStep`.
4881
+ *
4882
+ * @private
4883
+ */
4884
+ private handleSingleSubAgentChatStep;
4571
4885
  /**
4572
4886
  * Executes a related sub-agent step (AgentRelationships) and tracks it.
4573
4887
  * Related agents use message-based communication with independent payloads.
@@ -4931,6 +5245,14 @@ export declare class BaseAgent {
4931
5245
  * @protected
4932
5246
  */
4933
5247
  protected executeTasksStep(params: ExecuteAgentParams, previousDecision: BaseAgentNextStep): Promise<BaseAgentNextStep>;
5248
+ /**
5249
+ * Executes a `'Handoff'` next step: records the `'Handoff'` step entity with the resolved
5250
+ * target agent ID, stores {@link _handoffResult} for {@link ExecuteAgentResult.handoff},
5251
+ * and ends this run `'Success'` with the handoff message so the host can invoke the target agent.
5252
+ *
5253
+ * @protected
5254
+ */
5255
+ protected executeHandoffStep(params: ExecuteAgentParams, previousDecision: BaseAgentNextStep): Promise<BaseAgentNextStep>;
4934
5256
  /**
4935
5257
  * Records a constant-folded task graph (D9) without submitting it.
4936
5258
  *
@@ -5041,13 +5363,19 @@ export declare class BaseAgent {
5041
5363
  private detectRequestTypeName;
5042
5364
  /**
5043
5365
  * Executes a ForEach loop with actual for loop
5044
- * @private
5045
5366
  */
5046
5367
  private executeForEachLoop;
5047
5368
  private validateWhileOperation;
5048
- private validateForEachOperation;
5049
- protected validateActionInAgent(actionName: string): string | null;
5050
- protected validateSubAgentInAgent(subAgentName: string): string | null;
5369
+ private validateForEachHeader;
5370
+ /**
5371
+ * Validates the loop body arm (`action` | `steps` | `subAgent`) shared by `ForEach` and `While`.
5372
+ * Structural validation is delegated to CorePlus {@link ValidateLoopOperationStructure} so in-turn
5373
+ * and durable loops enforce one identical contract; runtime action/sub-agent membership is checked
5374
+ * here without mutating `op`.
5375
+ */
5376
+ private validateLoopBodyOperation;
5377
+ protected validateActionInAgent(actionName: string, agentId?: string): string | null;
5378
+ protected validateSubAgentInAgent(subAgentName: string, agentId?: string): string | null;
5051
5379
  /**
5052
5380
  * Helper: Validate and extract collection from payload
5053
5381
  * Strips "payload." prefix if present (for LLM convenience)
@@ -5082,6 +5410,15 @@ export declare class BaseAgent {
5082
5410
  * This ensures payload changes are applied in order even when iterations ran in parallel.
5083
5411
  */
5084
5412
  private applyForEachResultsSequentially;
5413
+ private extractActionOutputObject;
5414
+ private applyLoopOutputFold;
5415
+ /**
5416
+ * Executes an ordered sequence of `LoopBodyActionStep` actions inside a single `ForEach` or `While`
5417
+ * iteration, chaining step outputs under `steps.<id>.*` / `steps.step_<index>.*`, evaluating optional
5418
+ * per-step `condition` expressions, folding optional per-step `outputMapping` onto the working payload,
5419
+ * and halting remaining steps in the pass if any step fails.
5420
+ */
5421
+ private executeLoopStepsIteration;
5085
5422
  /**
5086
5423
  * Helper: Execute single ForEach iteration
5087
5424
  */
@@ -5150,7 +5487,6 @@ export declare class BaseAgent {
5150
5487
  private createFailedStep;
5151
5488
  /**
5152
5489
  * Executes a While loop with actual while loop
5153
- * @private
5154
5490
  */
5155
5491
  private executeWhileLoop;
5156
5492
  /**
@@ -5282,6 +5618,17 @@ export declare class BaseAgent {
5282
5618
  * @returns Array of violation messages (empty if all requirements are met)
5283
5619
  */
5284
5620
  protected checkMinimumExecutionRequirements(agent: MJAIAgentEntityExtended, agentRun: MJAIAgentRunEntityExtended): Promise<string[]>;
5621
+ /**
5622
+ * Whether the window has reached the compaction trigger the operator configured — the same
5623
+ * `CompactionTriggerPercent` (agent, then agent type, then the default) that drives cross-turn
5624
+ * compaction, resolved by {@link resolveCompactionBudget} into `TriggerTokens`. Below it, the
5625
+ * mid-loop rewrites of earlier turns (shortening replayed tool-call arguments, expiring old action
5626
+ * results) are deferred, so routine tool loops keep the provider's byte-exact prompt-cache prefix.
5627
+ * One knob governs both kinds of compaction on purpose: a second number would be one more thing
5628
+ * to tune, and an in-run rewrite is only worth a cache miss once the window is actually filling up.
5629
+ * @protected
5630
+ */
5631
+ protected isMidLoopCompactionThresholdReached(params: ExecuteAgentParams): boolean;
5285
5632
  /**
5286
5633
  * Prunes and compacts expired messages in the conversation based on configured expiration rules.
5287
5634
  * Processes messages in three phases: identification, compaction, and removal.
@@ -5604,6 +5951,12 @@ export declare class BaseAgent {
5604
5951
  * ({@link validateAndApplySecondaryScopes}), and `null` for whatever the run does not carry.
5605
5952
  */
5606
5953
  private validatedRunScope;
5954
+ /**
5955
+ * The search scopes the host assigned this run ({@link ExecuteAgentParams.SearchScopeIDs}): trimmed, de-duplicated,
5956
+ * in the host's order, or `null` for none. Read from the first-class parameter only — never from `data`, which a
5957
+ * caller could otherwise use to hand an agent a scope its own SearchScopeAccess refuses.
5958
+ */
5959
+ private hostSearchScopeIDs;
5607
5960
  /**
5608
5961
  * Writes the validated run scope onto the run row: the primary entity resolved to its ID (logged when it is
5609
5962
  * not in metadata), the tenant record ID and the secondary dimensions as JSON. A secondary-only scope on an