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

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 (105) hide show
  1. package/README.md +29 -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/agent-pre-execution-rag.d.ts.map +1 -1
  14. package/dist/agent-pre-execution-rag.js +1 -0
  15. package/dist/agent-pre-execution-rag.js.map +1 -1
  16. package/dist/agent-run-watchdog.d.ts +51 -13
  17. package/dist/agent-run-watchdog.d.ts.map +1 -1
  18. package/dist/agent-run-watchdog.js +89 -21
  19. package/dist/agent-run-watchdog.js.map +1 -1
  20. package/dist/agent-types/flow-agent-type.d.ts +6 -0
  21. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  22. package/dist/agent-types/flow-agent-type.js +70 -6
  23. package/dist/agent-types/flow-agent-type.js.map +1 -1
  24. package/dist/agent-types/loop-agent-prompt-params.d.ts +26 -3
  25. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  26. package/dist/agent-types/loop-agent-prompt-params.js +5 -3
  27. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  28. package/dist/agent-types/loop-agent-response-type.d.ts +35 -4
  29. package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
  30. package/dist/agent-types/loop-agent-response-type.js +1 -1
  31. package/dist/agent-types/loop-agent-response-type.js.map +1 -1
  32. package/dist/agent-types/loop-agent-type.d.ts +27 -4
  33. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  34. package/dist/agent-types/loop-agent-type.js +121 -18
  35. package/dist/agent-types/loop-agent-type.js.map +1 -1
  36. package/dist/base-agent.d.ts +306 -33
  37. package/dist/base-agent.d.ts.map +1 -1
  38. package/dist/base-agent.js +1733 -366
  39. package/dist/base-agent.js.map +1 -1
  40. package/dist/catalog-narrowing.d.ts.map +1 -1
  41. package/dist/catalog-narrowing.js +6 -3
  42. package/dist/catalog-narrowing.js.map +1 -1
  43. package/dist/handoff-target.d.ts +80 -0
  44. package/dist/handoff-target.d.ts.map +1 -0
  45. package/dist/handoff-target.js +158 -0
  46. package/dist/handoff-target.js.map +1 -0
  47. package/dist/index.d.ts +2 -0
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +2 -0
  50. package/dist/index.js.map +1 -1
  51. package/dist/memory-manager-agent.d.ts.map +1 -1
  52. package/dist/memory-manager-agent.js +2 -0
  53. package/dist/memory-manager-agent.js.map +1 -1
  54. package/dist/native-tools/action-tool-builder.d.ts +6 -0
  55. package/dist/native-tools/action-tool-builder.d.ts.map +1 -1
  56. package/dist/native-tools/action-tool-builder.js +21 -5
  57. package/dist/native-tools/action-tool-builder.js.map +1 -1
  58. package/dist/native-tools/control-tools.d.ts +15 -4
  59. package/dist/native-tools/control-tools.d.ts.map +1 -1
  60. package/dist/native-tools/control-tools.js +31 -14
  61. package/dist/native-tools/control-tools.js.map +1 -1
  62. package/dist/pipeline/pipeline-registry.d.ts +5 -12
  63. package/dist/pipeline/pipeline-registry.d.ts.map +1 -1
  64. package/dist/pipeline/pipeline-registry.js +28 -2
  65. package/dist/pipeline/pipeline-registry.js.map +1 -1
  66. package/dist/pipeline/providers/serialize.d.ts +7 -3
  67. package/dist/pipeline/providers/serialize.d.ts.map +1 -1
  68. package/dist/pipeline/providers/serialize.js +9 -5
  69. package/dist/pipeline/providers/serialize.js.map +1 -1
  70. package/dist/realtime/bridge-room-transcript-sink.js +2 -0
  71. package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
  72. package/dist/realtime/realtime-client-session-service.d.ts +22 -2
  73. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  74. package/dist/realtime/realtime-client-session-service.js +70 -10
  75. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  76. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  77. package/dist/realtime/realtime-coagent-config.js +2 -28
  78. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  79. package/dist/realtime/realtime-recording-capture.d.ts +1 -0
  80. package/dist/realtime/realtime-recording-capture.d.ts.map +1 -1
  81. package/dist/realtime/realtime-recording-capture.js +17 -3
  82. package/dist/realtime/realtime-recording-capture.js.map +1 -1
  83. package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -1
  84. package/dist/realtime/realtime-recording-opus-assembly.js +9 -4
  85. package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -1
  86. package/dist/realtime/realtime-session-runner.d.ts.map +1 -1
  87. package/dist/realtime/realtime-session-runner.js +5 -7
  88. package/dist/realtime/realtime-session-runner.js.map +1 -1
  89. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  90. package/dist/realtime/realtime-turn-moderator.js +1 -0
  91. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  92. package/dist/rubric-evaluation-agent-runner.js +1 -0
  93. package/dist/rubric-evaluation-agent-runner.js.map +1 -1
  94. package/dist/runtime-state-fragment.d.ts.map +1 -1
  95. package/dist/runtime-state-fragment.js +3 -0
  96. package/dist/runtime-state-fragment.js.map +1 -1
  97. package/dist/sub-agent-consult.d.ts +75 -0
  98. package/dist/sub-agent-consult.d.ts.map +1 -0
  99. package/dist/sub-agent-consult.js +193 -0
  100. package/dist/sub-agent-consult.js.map +1 -0
  101. package/dist/volatile-child-prompt.d.ts +7 -0
  102. package/dist/volatile-child-prompt.d.ts.map +1 -1
  103. package/dist/volatile-child-prompt.js +8 -0
  104. package/dist/volatile-child-prompt.js.map +1 -1
  105. 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';
@@ -125,6 +125,18 @@ export interface ExecuteSingleActionOptions {
125
125
  * across any arguments.
126
126
  */
127
127
  export type ActionCircuitBreakerReason = 'fatal' | 'audience' | 'identical-arguments' | 'attempts-exhausted';
128
+ /**
129
+ * What {@link BaseAgent.classifyActionFailure} names for a failed action: the breaker rule that fired, a refusal by
130
+ * the user's agent policy (`'policy'` — governance, not a parameter error, so the guidance must not tell the model
131
+ * to adjust its arguments and retry), or a plain `'warning'`.
132
+ */
133
+ export type ActionFailureClass = ActionCircuitBreakerReason | 'policy' | 'warning';
134
+ /** Result code of a call the user's agent policy denies outright (`checkUserActionPolicy`). */
135
+ export declare const POLICY_DENIED_RESULT_CODE = "POLICY_DENIED";
136
+ /** Result code of a call the user's agent policy allows only with the user's approval. */
137
+ export declare const POLICY_APPROVAL_REQUIRED_RESULT_CODE = "POLICY_APPROVAL_REQUIRED";
138
+ /** Result code of a call the user's agent policy defers to its next allowed time window. */
139
+ export declare const POLICY_DEFERRED_RESULT_CODE = "POLICY_DEFERRED_OUTSIDE_TIME_WINDOW";
128
140
  /** Identical-arguments rule: this many failures with the same arguments block further identical calls. */
129
141
  export declare const IDENTICAL_FAILURE_THRESHOLD = 2;
130
142
  /** Attempt budget: this many consecutive failures, across any arguments, disable the action for the run. */
@@ -462,7 +474,13 @@ export declare class BaseAgent {
462
474
  * the action is blocked whatever the arguments are, and telling the model to change them
463
475
  * would send it in circles.
464
476
  */
465
- protected classifyActionFailure(summary: ActionResultSummary): ActionCircuitBreakerReason | 'warning';
477
+ protected classifyActionFailure(summary: ActionResultSummary): ActionFailureClass;
478
+ /**
479
+ * The guidance line for a call the user's agent policy refused. The default `[WARNING/ACTION_FAILURE]`
480
+ * line tells the model to adjust its parameters and try again, up to the budget; a refusal is not a
481
+ * parameter error, and a retry burns the budget without ever succeeding.
482
+ */
483
+ private formatPolicyRefusalDirective;
466
484
  /** The guidance line appended to the history for one failed action. */
467
485
  protected formatActionFailureDirective(summary: ActionResultSummary): string;
468
486
  /**
@@ -563,6 +581,15 @@ export declare class BaseAgent {
563
581
  * @private
564
582
  */
565
583
  private _feedbackRequestId;
584
+ /**
585
+ * Stores the handoff outcome when a Handoff step fires.
586
+ * Populated by executeHandoffStep(), returned in ExecuteAgentResult.handoff.
587
+ */
588
+ private _handoffResult;
589
+ /**
590
+ * Stores the target agent resolved during validateHandoffNextStep() for executeHandoffStep().
591
+ */
592
+ private _resolvedHandoffTarget;
566
593
  private _resolvedStorageAccountId;
567
594
  /**
568
595
  * Most recent artifactDirective returned by a child or related sub-agent during this run.
@@ -603,14 +630,14 @@ export declare class BaseAgent {
603
630
  * // Note: If no presets configured, returns empty array - agent will use default behavior
604
631
  * ```
605
632
  */
606
- GetConfigurationPresets(agentId: string): import("@memberjunction/core-entities").MJAIAgentConfigurationEntity[];
633
+ GetConfigurationPresets(agentId: string): MJAIAgentConfigurationEntity[];
607
634
  /**
608
635
  * Gets the default configuration preset for an agent.
609
636
  *
610
637
  * @param agentId - The ID of the agent to get the default preset for
611
638
  * @returns The default preset, or undefined if none configured
612
639
  */
613
- GetDefaultConfigurationPreset(agentId: string): import("@memberjunction/core-entities").MJAIAgentConfigurationEntity;
640
+ GetDefaultConfigurationPreset(agentId: string): MJAIAgentConfigurationEntity;
614
641
  /**
615
642
  * Promotes media outputs to the agent's final outputs.
616
643
  * Call this method to add generated images, audio, or video to the agent's outputs.
@@ -695,19 +722,20 @@ export declare class BaseAgent {
695
722
  private interceptLargeBinaryContent;
696
723
  /**
697
724
  * Substitutes `${media:<refId>}` placeholders in a string with the actual
698
- * data URI (`data:<mime>;base64,<bytes>`) of the matching intercepted media item.
725
+ * data URI (`data:<mime>;base64,<bytes>`) or stored `fileId` (for `fileId`-only
726
+ * media items) of the matching intercepted media item.
699
727
  *
700
728
  * 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}.
729
+ * LLM wants to embed image (or other media) data or a stored file ID inline at a
730
+ * specific position in its structured output rather than only as a trailing
731
+ * attachment card. The string variant of placeholder resolution; recursive walker
732
+ * lives in {@link resolveMediaPlaceholdersInPayload}.
705
733
  *
706
734
  * This function only does substitution — it has no persistence side effects.
707
735
  *
708
736
  * @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)
737
+ * @returns String with placeholders resolved to data URIs or stored file IDs (or the
738
+ * original placeholder if the refId is unknown — defensive, shouldn't happen)
711
739
  * @private
712
740
  * @since 3.1.0
713
741
  */
@@ -867,6 +895,14 @@ export declare class BaseAgent {
867
895
  * @private
868
896
  */
869
897
  private _effectiveSubAgents;
898
+ /**
899
+ * True once gatherPromptTemplateData() has computed {@link _effectiveActions} and
900
+ * {@link _effectiveSubAgents} for this run. An empty list is then authoritative: a host's
901
+ * `actionChanges` that remove every action leave the run with none, instead of falling back to
902
+ * the agent's database configuration as an uncomputed list does.
903
+ * @private
904
+ */
905
+ private _effectiveCatalogComputed;
870
906
  /**
871
907
  * The merged agent-type prompt params of the current step. Populated during
872
908
  * gatherPromptTemplateData() and read by the finishIf gate, which runs in executeActionsStep()
@@ -1002,6 +1038,29 @@ export declare class BaseAgent {
1002
1038
  * @private
1003
1039
  */
1004
1040
  private _validationRetryCount;
1041
+ /**
1042
+ * Per-parent-run consultation round counter keyed by `subAgentEntity.ID`.
1043
+ * Tracks how many times each sub-agent has returned `FinalStep === 'Chat'`
1044
+ * under `ChatHandlingOption = 'Consult'` during this run.
1045
+ * Reset at the start of each agent run.
1046
+ * @private
1047
+ */
1048
+ private _subAgentConsultRounds;
1049
+ /**
1050
+ * Open sub-agent consultations keyed by `childRunId`.
1051
+ * Populated when a child sub-agent pauses with `FinalStep === 'Chat'` under `'Consult'`,
1052
+ * and removed when the parent resumes that child run.
1053
+ * Reset at the start of each agent run.
1054
+ * @private
1055
+ */
1056
+ private _openSubAgentConsults;
1057
+ /**
1058
+ * Tracks whether we have already logged the warning that `'Consult'` is not
1059
+ * supported on agent types where `InjectLoopResultsAsMessage` is `false`.
1060
+ * Reset at the start of each agent run.
1061
+ * @private
1062
+ */
1063
+ private _loggedConsultUnsupportedAgentType;
1005
1064
  /**
1006
1065
  * Counter tracking the number of context recovery attempts made in this run.
1007
1066
  * Context recovery removes/compacts old messages when context length is exceeded.
@@ -1110,6 +1169,12 @@ export declare class BaseAgent {
1110
1169
  */
1111
1170
  protected get DefaultAgentTimeoutMS(): number;
1112
1171
  Execute<C = any, R = any>(params: ExecuteAgentParams<C>): Promise<ExecuteAgentResult<R>>;
1172
+ /**
1173
+ * {@link Execute}'s per-run teardown, called from its top-level `finally` on every exit path.
1174
+ * The run leaves the watchdog first, before the subclass {@link finalizeRun} hook, so a hook
1175
+ * that throws can never leave a finished run being heart-beaten for the life of the process.
1176
+ */
1177
+ private endRun;
1113
1178
  /**
1114
1179
  * Fails the run at its start, before any prompt: marks the already-created AgentRun Failed with the message
1115
1180
  * (so it never shows as a phantom "running" record) and throws, which {@link Execute} turns into a failure
@@ -1155,7 +1220,8 @@ export declare class BaseAgent {
1155
1220
  * (`TaskGraphAgentRunner`) that carries neither the audience nor the scope. So graphs are withheld when the
1156
1221
  * audience adds a reader, and when the run's validated scope carries a tenant or a secondary dimension
1157
1222
  * (`ActionRunScopeIsBounded`): a model-written Scoped Search node would search outside the run's tenant, and an
1158
- * agent node would drop it.
1223
+ * agent node would drop it. Likewise when the host assigned the run's search scopes (`SearchScopeIDs`): a graph's
1224
+ * Scoped Search node would fall back to the agent's own search access.
1159
1225
  */
1160
1226
  private taskGraphWithholdingReason;
1161
1227
  /** Whether this run withholds task graphs ({@link taskGraphWithholdingReason}). */
@@ -1167,9 +1233,18 @@ export declare class BaseAgent {
1167
1233
  */
1168
1234
  private taskGraphRefusal;
1169
1235
  /**
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.
1236
+ * Whether this run withholds Handoff (`enableHandoff` off and the `handoff` response section hidden).
1237
+ * True when the run has a `parentRun` (sub-agents cannot transfer the conversation), has no
1238
+ * `conversationDetailId` (there is no conversation reply row to hand over), has no `handoffChain`
1239
+ * (the host does not carry out handoffs), or runs for an anonymous/widget guest without a trusted
1240
+ * host allow-list (`TrustReservedRunData === true` and `HostAllowedAgentIDs(params.data)` defined).
1241
+ */
1242
+ private runWithholdsHandoff;
1243
+ /**
1244
+ * What this run's prompt leaves out: task graphs ({@link taskGraphWithholdingReason}), handoff
1245
+ * ({@link runWithholdsHandoff}), and — when the audience adds a reader — the caller's own browser
1246
+ * and view (`CallerContext`): client tools run in the caller's browser and what they return reaches
1247
+ * the room, and the app context (`data.appContext`, with its `AdditionalContext`) is the caller's screen.
1173
1248
  */
1174
1249
  private promptWithholding;
1175
1250
  /**
@@ -1191,6 +1266,11 @@ export declare class BaseAgent {
1191
1266
  * response section hidden). A copy, never a write: the input may be the process-wide cached base.
1192
1267
  */
1193
1268
  private withoutTaskGraphs;
1269
+ /**
1270
+ * A copy of the agent-type prompt params with handoff withheld (`enableHandoff` off and the `handoff`
1271
+ * response section hidden). A copy, never a write: the input may be the process-wide cached base.
1272
+ */
1273
+ private withoutHandoff;
1194
1274
  /**
1195
1275
  * Why a session-driven (realtime / voice / bridge) run is refused, or null. A live session speaks and calls
1196
1276
  * tools outside the gates that hold a run to its audience, so a run whose audience adds a reader is refused.
@@ -2139,6 +2219,10 @@ export declare class BaseAgent {
2139
2219
  * Keeps the system-prompt-and-tools fingerprint of the request just sent, for the next one. When
2140
2220
  * it changed, the runner sent this request without replayed reasoning; the history drops it too,
2141
2221
  * so no later request replays a block made under the old prompt or tools.
2222
+ *
2223
+ * A result with no fingerprint (a request that failed before or while it was sent, such as a
2224
+ * failover that ran out of candidates) leaves the baseline as it was. Clearing it would let the
2225
+ * next request skip the comparison and replay thinking made under a prompt or tools it no longer has.
2142
2226
  */
2143
2227
  private trackSentPrefix;
2144
2228
  /** What makes a message the same message to a provider — reasoning aside, which only this check removes. */
@@ -2188,8 +2272,10 @@ export declare class BaseAgent {
2188
2272
  * declares native tools to a driver whose replayed reasoning needs the history before it
2189
2273
  * unchanged is append-only too (see {@link ResolveAppendOnlyState}).
2190
2274
  *
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
2275
+ * Decided ONCE per run. An explicit `trailingStateMode` answers immediately, and so does a runtime
2276
+ * model override that names a vendor, or whose catalog says the cache is a byte-prefix cache.
2277
+ * Otherwise (no override, or one that names no vendor and whose catalog does not say yes) the
2278
+ * answer is frozen at the first model selection and reused for every
2193
2279
  * later turn, so a failover to another vendor cannot flip the layout mid-run — a flip after turn 2
2194
2280
  * would leave stale fragments in the history or, worse, restore the wrong turn's fragment. On turn 1,
2195
2281
  * before any selection is known, the answer is replace-in-place: turn 1's fragment is kept and, if
@@ -2359,6 +2445,22 @@ export declare class BaseAgent {
2359
2445
  */
2360
2446
  protected getRequestedSubAgents<P, C>(nextStep: BaseAgentNextStep<P, C> | undefined | null): AgentSubAgentRequest<C>[];
2361
2447
  protected validateSubAgentNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2448
+ /**
2449
+ * Strips an optional `delegate_to_` native sub-agent tool prefix when a model running
2450
+ * with native tool calling references a sub-agent by its declared tool name inside an
2451
+ * envelope primitive (`Sub-Agent`, `ForEach`, `While`, or `Tasks`).
2452
+ */
2453
+ protected stripSubAgentToolPrefix(rawName: string): string;
2454
+ /**
2455
+ * Resolves a unique entity from `pool` whose sanitized native tool name matches `rawName`.
2456
+ * Returns `{ ambiguous }` when multiple entities collide on the same sanitized name.
2457
+ */
2458
+ protected matchNamedBySanitizedToolName<T extends {
2459
+ Name?: string | null;
2460
+ }>(rawName: string, pool: readonly T[], stripSubAgentPrefix?: boolean): {
2461
+ match?: T;
2462
+ ambiguous?: T[];
2463
+ };
2362
2464
  /**
2363
2465
  * Builds a compact hint listing the current user's permitted runnable agents when a
2364
2466
  * task-graph or folded sub-agent step references an unknown or inaccessible agent name.
@@ -2368,11 +2470,9 @@ export declare class BaseAgent {
2368
2470
  * Validates a `'Tasks'` next step before `executeTasksStep` submits the graph.
2369
2471
  *
2370
2472
  * 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.
2473
+ * active and runnable by `params.contextUser`, and that every referenced `Action` (including
2474
+ * multi-step `steps[]` loop bodies) is active. Accepts sanitized native tool names
2475
+ * (`calculate_expression`, `delegate_to_query_builder`) and canonicalizes them in place.
2376
2476
  */
2377
2477
  protected validateTasksNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, _currentPayload: P, _agentRun: MJAIAgentRunEntityExtended, _currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2378
2478
  /**
@@ -2385,7 +2485,8 @@ export declare class BaseAgent {
2385
2485
  protected validateActionsNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2386
2486
  /**
2387
2487
  * Gets the effective actions for validation, using runtime changes if available.
2388
- * Falls back to database-configured actions if _effectiveActions is empty.
2488
+ * Falls back to database-configured actions only when the list was never computed for this run;
2489
+ * a computed empty list (a host's actionChanges removed every action) is returned as-is.
2389
2490
  *
2390
2491
  * @param agentId - The ID of the agent to get actions for
2391
2492
  * @returns Array of effective actions available to the agent
@@ -2393,9 +2494,35 @@ export declare class BaseAgent {
2393
2494
  * @since 2.123.0
2394
2495
  */
2395
2496
  protected getEffectiveActionsForValidation(agentId: string): MJActionEntityExtended[];
2497
+ /**
2498
+ * Returns active actions referenced directly by an agent's Flow steps (`AIAgentStep.ActionID`
2499
+ * plus any `steps[].name` inside a `ForEach`/`While` Flow step's `Configuration` JSON).
2500
+ * Flow agents bind actions on `AIAgentStep` rather than `AIAgentAction`, so in-run Flow loops
2501
+ * need these actions in scope alongside {@link getEffectiveActionsForValidation}.
2502
+ */
2503
+ private getFlowStepActions;
2504
+ /**
2505
+ * Combines {@link getEffectiveActionsForValidation} with {@link getFlowStepActions} (deduplicated
2506
+ * by `ID`) so both Loop agents (strictly `AIAgentAction` / `_effectiveActions`) and Flow agents
2507
+ * (`AIAgentStep` / `Configuration.steps[]`) resolve permitted actions consistently.
2508
+ */
2509
+ private getAvailableActionsForAgent;
2510
+ /**
2511
+ * Resolves an action name against `pool` without mutating caller objects:
2512
+ * 1) exact case-insensitive match, 2) unambiguous sanitized native tool-name match,
2513
+ * 3) unambiguous CONTAINS partial match.
2514
+ */
2515
+ private resolveActionEntityForAgent;
2516
+ /**
2517
+ * Returns a deep-cloned `TaskGraphSpec` with sanitized native tool names (`calculate_expression`,
2518
+ * `delegate_to_query_builder`) canonicalized to exact metadata names before durable submission,
2519
+ * without mutating the caller's `spec`.
2520
+ */
2521
+ private canonicalizeTaskGraphSpec;
2396
2522
  /**
2397
2523
  * 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.
2524
+ * Falls back to the database-configured relationship set only when the list was never computed
2525
+ * for this run; a computed empty list is returned as-is.
2399
2526
  * Mirrors {@link getEffectiveActionsForValidation}.
2400
2527
  *
2401
2528
  * @param agentId - The ID of the agent to get sub-agents for
@@ -2421,6 +2548,17 @@ export declare class BaseAgent {
2421
2548
  * @protected
2422
2549
  */
2423
2550
  protected validatePlanNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2551
+ /**
2552
+ * Validates a `'Handoff'` next step: re-checks the runtime withholding conditions (sub-agent run,
2553
+ * missing `conversationDetailId`, or missing `handoffChain`) and validates the requested target
2554
+ * via {@link ResolveHandoffTarget} (Active status, `'view'` and `'run'` permissions, direct
2555
+ * discoverability, host allow-list, cycle check, and hop limit). On refusal, writes a Failed
2556
+ * `'Handoff'` step and returns a `'Retry'` step naming up to 20 candidate agents; on approval,
2557
+ * stores the resolved target ID and name for {@link executeHandoffStep}.
2558
+ *
2559
+ * @protected
2560
+ */
2561
+ protected validateHandoffNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, _currentPayload: P, _agentRun: MJAIAgentRunEntityExtended, _currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2424
2562
  /**
2425
2563
  * Validates that the Success next step is valid and can be executed by the current agent. Subclasses can override
2426
2564
  * this method to implement custom validation logic if needed.
@@ -2457,16 +2595,50 @@ export declare class BaseAgent {
2457
2595
  * @returns
2458
2596
  */
2459
2597
  protected validateRetryNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2598
+ /**
2599
+ * Resolves the effective `ChatHandlingOption` for a sub-agent execution:
2600
+ * `relationship?.ChatHandlingOption ?? parentAgent.ChatHandlingOption ?? null`.
2601
+ * @private
2602
+ */
2603
+ private resolveSubAgentChatHandlingOption;
2604
+ /**
2605
+ * Returns `true` only when `resolvedOption === 'Consult'` AND the parent agent's
2606
+ * type supports injecting loop/consult messages into conversation history
2607
+ * (`this.AgentTypeInstance?.InjectLoopResultsAsMessage !== false`).
2608
+ *
2609
+ * When `resolvedOption === 'Consult'` and `this.AgentTypeInstance?.InjectLoopResultsAsMessage === false`
2610
+ * (e.g., a Flow parent), logs a warning once per run and returns `false` so `'Consult'`
2611
+ * is treated as `null` (propagate).
2612
+ * @private
2613
+ */
2614
+ private isSubAgentConsultActive;
2615
+ /**
2616
+ * Resolves the sub-agent `ChatHandlingOption` and downgrades `'Consult'` to `null`
2617
+ * when `isSubAgentConsultActive` returns `false` (e.g., on Flow parents).
2618
+ * @private
2619
+ */
2620
+ private effectiveSubAgentChatHandlingOption;
2621
+ /**
2622
+ * Side-effect-free check used during prompt and native-tool construction to determine
2623
+ * whether `'Consult'` is active for a specific sub-agent of `parentAgent`.
2624
+ * @private
2625
+ */
2626
+ private isSubAgentConsultEnabledForSubAgent;
2460
2627
  /**
2461
2628
  * 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).
2629
+ * Implements ChatHandlingOption remapping logic - if the agent (or sub-agent relationship)
2630
+ * has ChatHandlingOption set:
2631
+ * - `'Consult'`: leaves the Chat step unchanged (an agent's own Chat propagates to its caller;
2632
+ * sub-agent Consult is intercepted before this validator).
2633
+ * - `'Success'` / `'Failed'`: remaps `step` while preserving `terminate: true` to end the run.
2634
+ * - `'Retry'`: remaps `step` to `'Retry'`, sets `terminate: false` so the loop continues, and
2635
+ * populates `errorMessage` so the unproductive-retry safety net bounds repeated Chat attempts.
2464
2636
  * Subclasses can override this method to implement custom validation logic if needed.
2465
2637
  * @param params
2466
2638
  * @param nextStep
2467
2639
  * @returns
2468
2640
  */
2469
- protected validateChatNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2641
+ protected validateChatNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended, chatHandlingOption?: MJAIAgentEntity['ChatHandlingOption']): Promise<BaseAgentNextStep<P>>;
2470
2642
  /**
2471
2643
  * Checks execution guardrails and modifies next step if limits are exceeded.
2472
2644
  * This method is called after validation but before execution of non-terminal steps.
@@ -2729,6 +2901,14 @@ export declare class BaseAgent {
2729
2901
  * @protected
2730
2902
  */
2731
2903
  protected processNextStep<P>(nextStep: BaseAgentNextStep<P>, params: ExecuteAgentParams, agentType: MJAIAgentTypeEntity, promptResult: AIPromptRunResult, currentPayload: P, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
2904
+ /**
2905
+ * A completion refused with a payload change in hand: the change is discarded (the prompt step
2906
+ * commits it only for an accepted completion), so the refusal the model reads says so, and asks
2907
+ * for the change again with the next completion. Otherwise the model would take the change as
2908
+ * saved and its work would be lost. The change is removed from the step, so nothing later
2909
+ * applies it. Any other step is returned as it is.
2910
+ */
2911
+ private noteDiscardedCompletionChange;
2732
2912
  /**
2733
2913
  * Answers a retried native tool-call turn in the protocol itself: every call gets an `is_error`
2734
2914
  * result carrying the retry reason, and no user message follows.
@@ -2820,6 +3000,20 @@ export declare class BaseAgent {
2820
3000
  * @protected
2821
3001
  */
2822
3002
  protected applyStoppedRunContinuation(params: ExecuteAgentParams, continuation: StoppedRunContinuation | null, continuationMessage: ChatMessage | undefined): void;
3003
+ /**
3004
+ * Loads unanswered sub-agent consultations (`OutputData.consult`) from `params.lastRunId` when that
3005
+ * prior run paused with `FinalStep === 'Chat'` (and was not stopped by the user). Runs at any depth
3006
+ * so a middle agent resumed via `resumeRunId` also reloads its own open child consults. Fail-soft.
3007
+ * @private
3008
+ */
3009
+ private loadOpenConsults;
3010
+ /**
3011
+ * Restores reloaded open sub-agent consults into `this._openSubAgentConsults` (so `resumeRunId`
3012
+ * validation accepts them) and splices a `sub-agent-consult` reminder message immediately before
3013
+ * `continuationMessage` (the caller's answer). Fail-soft.
3014
+ * @private
3015
+ */
3016
+ private applyOpenConsults;
2823
3017
  /**
2824
3018
  * The full-stack half of {@link applyStoppedRunContinuation}: true when the stopped run's turns were
2825
3019
  * spliced in. Any failure leaves the messages untouched and returns false, so the caller carries
@@ -3775,11 +3969,12 @@ export declare class BaseAgent {
3775
3969
  * @param {AgentSubAgentRequest} subAgentRequest - Sub-agent request details
3776
3970
  * @param {MJAIAgentEntityExtended} subAgent - The sub-agent entity
3777
3971
  * @param {ChatMessage | undefined} contextMessage - Optional context from SubAgentContextPaths
3972
+ * @param {string | null | undefined} consultQuestion - Optional open-consult question when resuming a child run
3778
3973
  * @returns {ChatMessage[]} Prepared message array for sub-agent execution
3779
3974
  *
3780
3975
  * @protected
3781
3976
  */
3782
- protected prepareSubAgentMessages(params: ExecuteAgentParams, subAgentRequest: AgentSubAgentRequest, subAgent: MJAIAgentEntityExtended, contextMessage?: ChatMessage): ChatMessage[];
3977
+ protected prepareSubAgentMessages(params: ExecuteAgentParams, subAgentRequest: AgentSubAgentRequest, subAgent: MJAIAgentEntityExtended, contextMessage?: ChatMessage, consultQuestion?: string | null): ChatMessage[];
3783
3978
  /**
3784
3979
  * Executes a sub-agent synchronously.
3785
3980
  *
@@ -3807,6 +4002,17 @@ export declare class BaseAgent {
3807
4002
  * ```
3808
4003
  */
3809
4004
  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>>;
4005
+ /**
4006
+ * Resolves the configuration to pass to a sub-agent run in precedence order:
4007
+ * 1. Per-call `subAgentRequest.presetName` -> matching Active preset of `subAgent`.
4008
+ * 2. Active `AIAgentRelationship.ConfigurationPresetID` -> that preset if Active and owned by `subAgent`;
4009
+ * otherwise logs a warning and falls through.
4010
+ * 3. Inherit `params.configurationId`.
4011
+ *
4012
+ * When a preset is selected, `configurationId` is `preset.AIConfigurationID ?? undefined` (a NULL
4013
+ * `AIConfigurationID` means default rows and intentionally does NOT inherit `params.configurationId`).
4014
+ */
4015
+ private resolveSubAgentConfiguration;
3810
4016
  /**
3811
4017
  * A sub-agent request's template parameters without the host-only run-data keys
3812
4018
  * (`HOST_ONLY_AGENT_RUN_DATA_KEYS` in `@memberjunction/ai-core-plus`: the reserved scope family and
@@ -4378,6 +4584,28 @@ export declare class BaseAgent {
4378
4584
  *
4379
4585
  * @private
4380
4586
  */
4587
+ /** Whether a step is a completion that carries a payload change, which is held until the completion is accepted. */
4588
+ private static carriesCompletionChange;
4589
+ /**
4590
+ * Applies a turn's `payloadChangeRequest` to `current` and returns the result; `current` is not
4591
+ * changed. Honours `PayloadSelfWritePaths`. A brand-new artifact whose payload is still the one
4592
+ * inherited from a prior run (or that uses `replaceElements`) is built on an empty object, so
4593
+ * keys from the previous artifact cannot bleed in.
4594
+ */
4595
+ private applyTurnPayloadChange;
4596
+ /**
4597
+ * The payload a completion would leave behind: the committed payload with the completion's
4598
+ * change applied. Success validation (the minimum-execution check, then `FinalPayloadValidation`)
4599
+ * checks this draft, and it becomes the payload only if the completion is accepted. The
4600
+ * opt-in payload change check is not asked here: it never runs on a step that ends the run.
4601
+ */
4602
+ private buildCompletionDraft;
4603
+ /**
4604
+ * The payload a turn leaves behind. A held completion draft is committed only when the step is
4605
+ * still `Success` after validation; on a refusal the committed payload stands (a subclass that
4606
+ * set a payload of its own still wins). Without a draft, a subclass's `newPayload` wins as before.
4607
+ */
4608
+ private resolveTurnPayload;
4381
4609
  private executePromptStep;
4382
4610
  /**
4383
4611
  * Computes the upstream and downstream paths for a sub-agent based on the agent's payload paths.
@@ -4568,6 +4796,23 @@ export declare class BaseAgent {
4568
4796
  */
4569
4797
  private recordParallelStepCompletion;
4570
4798
  private executeParallelSubAgents;
4799
+ /**
4800
+ * Pushes a sub-agent result or consult message to the parent's conversation history,
4801
+ * answering natively-invoked `delegate_to_*` calls as a tool-result turn when applicable
4802
+ * and applying expiration defaults / overrides.
4803
+ *
4804
+ * @private
4805
+ */
4806
+ private pushSubAgentConversationMessage;
4807
+ /**
4808
+ * Unified handler for a single sub-agent (child, related, or runtime-granted) that
4809
+ * finished with `FinalStep === 'Chat'`. Resolves `ChatHandlingOption` for the pairing,
4810
+ * runs the consult flow when `'Consult'` is active and within the per-sub-agent round
4811
+ * bound, and otherwise finalizes the step and delegates to `validateChatNextStep`.
4812
+ *
4813
+ * @private
4814
+ */
4815
+ private handleSingleSubAgentChatStep;
4571
4816
  /**
4572
4817
  * Executes a related sub-agent step (AgentRelationships) and tracks it.
4573
4818
  * Related agents use message-based communication with independent payloads.
@@ -4931,6 +5176,14 @@ export declare class BaseAgent {
4931
5176
  * @protected
4932
5177
  */
4933
5178
  protected executeTasksStep(params: ExecuteAgentParams, previousDecision: BaseAgentNextStep): Promise<BaseAgentNextStep>;
5179
+ /**
5180
+ * Executes a `'Handoff'` next step: records the `'Handoff'` step entity with the resolved
5181
+ * target agent ID, stores {@link _handoffResult} for {@link ExecuteAgentResult.handoff},
5182
+ * and ends this run `'Success'` with the handoff message so the host can invoke the target agent.
5183
+ *
5184
+ * @protected
5185
+ */
5186
+ protected executeHandoffStep(params: ExecuteAgentParams, previousDecision: BaseAgentNextStep): Promise<BaseAgentNextStep>;
4934
5187
  /**
4935
5188
  * Records a constant-folded task graph (D9) without submitting it.
4936
5189
  *
@@ -5041,13 +5294,19 @@ export declare class BaseAgent {
5041
5294
  private detectRequestTypeName;
5042
5295
  /**
5043
5296
  * Executes a ForEach loop with actual for loop
5044
- * @private
5045
5297
  */
5046
5298
  private executeForEachLoop;
5047
5299
  private validateWhileOperation;
5048
- private validateForEachOperation;
5049
- protected validateActionInAgent(actionName: string): string | null;
5050
- protected validateSubAgentInAgent(subAgentName: string): string | null;
5300
+ private validateForEachHeader;
5301
+ /**
5302
+ * Validates the loop body arm (`action` | `steps` | `subAgent`) shared by `ForEach` and `While`.
5303
+ * Structural validation is delegated to CorePlus {@link ValidateLoopOperationStructure} so in-turn
5304
+ * and durable loops enforce one identical contract; runtime action/sub-agent membership is checked
5305
+ * here without mutating `op`.
5306
+ */
5307
+ private validateLoopBodyOperation;
5308
+ protected validateActionInAgent(actionName: string, agentId?: string): string | null;
5309
+ protected validateSubAgentInAgent(subAgentName: string, agentId?: string): string | null;
5051
5310
  /**
5052
5311
  * Helper: Validate and extract collection from payload
5053
5312
  * Strips "payload." prefix if present (for LLM convenience)
@@ -5082,6 +5341,15 @@ export declare class BaseAgent {
5082
5341
  * This ensures payload changes are applied in order even when iterations ran in parallel.
5083
5342
  */
5084
5343
  private applyForEachResultsSequentially;
5344
+ private extractActionOutputObject;
5345
+ private applyLoopOutputFold;
5346
+ /**
5347
+ * Executes an ordered sequence of `LoopBodyActionStep` actions inside a single `ForEach` or `While`
5348
+ * iteration, chaining step outputs under `steps.<id>.*` / `steps.step_<index>.*`, evaluating optional
5349
+ * per-step `condition` expressions, folding optional per-step `outputMapping` onto the working payload,
5350
+ * and halting remaining steps in the pass if any step fails.
5351
+ */
5352
+ private executeLoopStepsIteration;
5085
5353
  /**
5086
5354
  * Helper: Execute single ForEach iteration
5087
5355
  */
@@ -5150,7 +5418,6 @@ export declare class BaseAgent {
5150
5418
  private createFailedStep;
5151
5419
  /**
5152
5420
  * Executes a While loop with actual while loop
5153
- * @private
5154
5421
  */
5155
5422
  private executeWhileLoop;
5156
5423
  /**
@@ -5604,6 +5871,12 @@ export declare class BaseAgent {
5604
5871
  * ({@link validateAndApplySecondaryScopes}), and `null` for whatever the run does not carry.
5605
5872
  */
5606
5873
  private validatedRunScope;
5874
+ /**
5875
+ * The search scopes the host assigned this run ({@link ExecuteAgentParams.SearchScopeIDs}): trimmed, de-duplicated,
5876
+ * in the host's order, or `null` for none. Read from the first-class parameter only — never from `data`, which a
5877
+ * caller could otherwise use to hand an agent a scope its own SearchScopeAccess refuses.
5878
+ */
5879
+ private hostSearchScopeIDs;
5607
5880
  /**
5608
5881
  * Writes the validated run scope onto the run row: the primary entity resolved to its ID (logged when it is
5609
5882
  * not in metadata), the tenant record ID and the secondary dimensions as JSON. A secondary-only scope on an