@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.
- package/README.md +44 -2
- package/dist/AgentRunner.d.ts +96 -3
- package/dist/AgentRunner.d.ts.map +1 -1
- package/dist/AgentRunner.js +438 -34
- package/dist/AgentRunner.js.map +1 -1
- package/dist/AgentWakeTriggerService.d.ts.map +1 -1
- package/dist/AgentWakeTriggerService.js +8 -1
- package/dist/AgentWakeTriggerService.js.map +1 -1
- package/dist/MJAIAgentRequestEntityServer.d.ts +15 -1
- package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
- package/dist/MJAIAgentRequestEntityServer.js +43 -3
- package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
- package/dist/MemoryWriteManager.d.ts +12 -0
- package/dist/MemoryWriteManager.d.ts.map +1 -1
- package/dist/MemoryWriteManager.js +18 -3
- package/dist/MemoryWriteManager.js.map +1 -1
- package/dist/agent-pre-execution-rag.d.ts.map +1 -1
- package/dist/agent-pre-execution-rag.js +1 -0
- package/dist/agent-pre-execution-rag.js.map +1 -1
- package/dist/agent-run-watchdog.d.ts +51 -13
- package/dist/agent-run-watchdog.d.ts.map +1 -1
- package/dist/agent-run-watchdog.js +89 -21
- package/dist/agent-run-watchdog.js.map +1 -1
- package/dist/agent-types/flow-agent-type.d.ts +6 -0
- package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
- package/dist/agent-types/flow-agent-type.js +70 -6
- package/dist/agent-types/flow-agent-type.js.map +1 -1
- package/dist/agent-types/loop-agent-prompt-params.d.ts +46 -3
- package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-prompt-params.js +9 -4
- package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
- package/dist/agent-types/loop-agent-response-type.d.ts +35 -4
- package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-response-type.js +1 -1
- package/dist/agent-types/loop-agent-response-type.js.map +1 -1
- package/dist/agent-types/loop-agent-type.d.ts +27 -4
- package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-type.js +121 -18
- package/dist/agent-types/loop-agent-type.js.map +1 -1
- package/dist/base-agent.d.ts +390 -37
- package/dist/base-agent.d.ts.map +1 -1
- package/dist/base-agent.js +2046 -433
- package/dist/base-agent.js.map +1 -1
- package/dist/catalog-narrowing.d.ts.map +1 -1
- package/dist/catalog-narrowing.js +6 -3
- package/dist/catalog-narrowing.js.map +1 -1
- package/dist/client-tool-results.d.ts +12 -0
- package/dist/client-tool-results.d.ts.map +1 -1
- package/dist/client-tool-results.js +21 -0
- package/dist/client-tool-results.js.map +1 -1
- package/dist/handoff-target.d.ts +80 -0
- package/dist/handoff-target.d.ts.map +1 -0
- package/dist/handoff-target.js +158 -0
- package/dist/handoff-target.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/memory-manager-agent.d.ts.map +1 -1
- package/dist/memory-manager-agent.js +2 -0
- package/dist/memory-manager-agent.js.map +1 -1
- package/dist/native-tools/action-tool-builder.d.ts +6 -0
- package/dist/native-tools/action-tool-builder.d.ts.map +1 -1
- package/dist/native-tools/action-tool-builder.js +21 -5
- package/dist/native-tools/action-tool-builder.js.map +1 -1
- package/dist/native-tools/control-tools.d.ts +15 -4
- package/dist/native-tools/control-tools.d.ts.map +1 -1
- package/dist/native-tools/control-tools.js +31 -14
- package/dist/native-tools/control-tools.js.map +1 -1
- package/dist/pipeline/pipeline-registry.d.ts +5 -12
- package/dist/pipeline/pipeline-registry.d.ts.map +1 -1
- package/dist/pipeline/pipeline-registry.js +28 -2
- package/dist/pipeline/pipeline-registry.js.map +1 -1
- package/dist/pipeline/providers/serialize.d.ts +7 -3
- package/dist/pipeline/providers/serialize.d.ts.map +1 -1
- package/dist/pipeline/providers/serialize.js +9 -5
- package/dist/pipeline/providers/serialize.js.map +1 -1
- package/dist/realtime/bridge-realtime-session-factory.d.ts +3 -3
- package/dist/realtime/bridge-realtime-session-factory.d.ts.map +1 -1
- package/dist/realtime/bridge-realtime-session-factory.js +12 -6
- package/dist/realtime/bridge-realtime-session-factory.js.map +1 -1
- package/dist/realtime/bridge-room-transcript-sink.js +2 -0
- package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
- package/dist/realtime/realtime-client-session-service.d.ts +72 -25
- package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
- package/dist/realtime/realtime-client-session-service.js +154 -54
- package/dist/realtime/realtime-client-session-service.js.map +1 -1
- package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
- package/dist/realtime/realtime-coagent-config.js +2 -28
- package/dist/realtime/realtime-coagent-config.js.map +1 -1
- package/dist/realtime/realtime-platform-credentials.d.ts +65 -0
- package/dist/realtime/realtime-platform-credentials.d.ts.map +1 -0
- package/dist/realtime/realtime-platform-credentials.js +148 -0
- package/dist/realtime/realtime-platform-credentials.js.map +1 -0
- package/dist/realtime/realtime-recording-capture.d.ts +1 -0
- package/dist/realtime/realtime-recording-capture.d.ts.map +1 -1
- package/dist/realtime/realtime-recording-capture.js +17 -3
- package/dist/realtime/realtime-recording-capture.js.map +1 -1
- package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -1
- package/dist/realtime/realtime-recording-opus-assembly.js +9 -4
- package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -1
- package/dist/realtime/realtime-session-runner.d.ts.map +1 -1
- package/dist/realtime/realtime-session-runner.js +5 -7
- package/dist/realtime/realtime-session-runner.js.map +1 -1
- package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
- package/dist/realtime/realtime-turn-moderator.js +1 -0
- package/dist/realtime/realtime-turn-moderator.js.map +1 -1
- package/dist/realtime/realtime-vendor-resolution.d.ts +41 -2
- package/dist/realtime/realtime-vendor-resolution.d.ts.map +1 -1
- package/dist/realtime/realtime-vendor-resolution.js +86 -4
- package/dist/realtime/realtime-vendor-resolution.js.map +1 -1
- package/dist/rubric-evaluation-agent-runner.js +1 -0
- package/dist/rubric-evaluation-agent-runner.js.map +1 -1
- package/dist/runtime-state-fragment.d.ts.map +1 -1
- package/dist/runtime-state-fragment.js +3 -0
- package/dist/runtime-state-fragment.js.map +1 -1
- package/dist/sub-agent-consult.d.ts +75 -0
- package/dist/sub-agent-consult.d.ts.map +1 -0
- package/dist/sub-agent-consult.js +193 -0
- package/dist/sub-agent-consult.js.map +1 -0
- package/dist/volatile-child-prompt.d.ts +7 -0
- package/dist/volatile-child-prompt.d.ts.map +1 -1
- package/dist/volatile-child-prompt.js +8 -0
- package/dist/volatile-child-prompt.js.map +1 -1
- package/package.json +20 -20
package/dist/base-agent.js
CHANGED
|
@@ -26,9 +26,10 @@ import { AgentRunWatchdog } from './agent-run-watchdog.js';
|
|
|
26
26
|
import { AIPromptRunner, GetToolCallingDecision, GetSentPrefixFingerprint } from '@memberjunction/ai-prompts';
|
|
27
27
|
import { BaseLLM, BaseRealtimeModel, GetAIAPIKey, CredentialScopeAllows, MakeAIAPIKeyResolver, IsPrefixPromptCache } from '@memberjunction/ai';
|
|
28
28
|
import { BaseAgentType } from './agent-types/base-agent-type.js';
|
|
29
|
+
import { LoopAgentType } from './agent-types/loop-agent-type.js';
|
|
29
30
|
import { ProviderRubricEngine } from '@memberjunction/rubrics';
|
|
30
31
|
import { ExecuteSelfCheck, PickSelfCheckLink } from './self-check.js';
|
|
31
|
-
import { CopyScalarsAndArrays, JSONValidator, MJGlobal, NormalizeUUID, SafeExpressionEvaluator, UUIDsEqual, UUIDSet, EscapeSQLString, IsPlainObject, CleanAndParseJSON, IsValidUUID
|
|
32
|
+
import { CopyScalarsAndArrays, GroupByUUID, IndexByUUID, JSONValidator, MJGlobal, NormalizeUUID, SafeExpressionEvaluator, UUIDsEqual, UUIDSet, EscapeSQLString, IsPlainObject, CleanAndParseJSON, IsValidUUID } from '@memberjunction/global';
|
|
32
33
|
// token optimization via @memberjunction/context-crush (SmartCrusher/CacheAligner-inspired)
|
|
33
34
|
import { CrushJSON, DescribeCrush, PartitionStablePrefix } from '@memberjunction/context-crush';
|
|
34
35
|
// AST-aware code reduction (CodeCompressor-inspired) — opt-in per agent type
|
|
@@ -36,7 +37,8 @@ import { CrushCode } from '@memberjunction/context-crush/code';
|
|
|
36
37
|
import { RealtimeSessionRunner } from './realtime/realtime-session-runner.js';
|
|
37
38
|
import { ResolveNarrationInstructionsTemplate } from './realtime/realtime-narration.js';
|
|
38
39
|
import { BuildRealtimeOverridesJson, BuildVoiceMannerSection, GetNarrationPaceMs, GetProviderVoiceSettings, GetSessionTuningSettings, GetModelCatalogSessionSettings, DeepMergeConfigs, ResolveEffectiveRealtimeConfig } from './realtime/realtime-coagent-config.js';
|
|
39
|
-
import { ListRealtimeVendorsForModel, SelectRealtimeVendorForModel } from './realtime/realtime-vendor-resolution.js';
|
|
40
|
+
import { ListRealtimeVendorsForModel, RealtimeKeyFixHint, SelectRealtimeVendorForModel } from './realtime/realtime-vendor-resolution.js';
|
|
41
|
+
import { ResolveRealtimePlatformCredentials } from './realtime/realtime-platform-credentials.js';
|
|
40
42
|
import { ChooseRealtimeVendorForAvatar, RealtimeModelShowsAvatar } from './realtime/realtime-video-output-gate.js';
|
|
41
43
|
import { RealtimeSessionCanShowAvatar } from './realtime/realtime-avatar-resolution.js';
|
|
42
44
|
import { RealtimeClientSessionService, WarnOnUnmatchedProviderVoice } from './realtime/realtime-client-session-service.js';
|
|
@@ -54,8 +56,8 @@ import { FormatToolResultSection, FormatToolErrorSection, RenderToolResultData,
|
|
|
54
56
|
import { PriorTurnToolResultCache } from './prior-turn-tool-result-cache.js';
|
|
55
57
|
import { PromptComponentResolver, InjectScopedPromptParts } from './prompt-component-resolver.js';
|
|
56
58
|
import { ScopedPromptConfigResolver, ApplyScopedPromptConfig } from './scoped-prompt-config-resolver.js';
|
|
57
|
-
import { StringifyForPersistence, AIPromptParams, ChildPromptParam, ConversationUtility, ParseFileOutputRef, parseAssignmentStrategy, ResolveClientTools, initAgentRunStep, finalizeAgentRunStep, AgentRunStepSaveQueue, ExtractPromptResultText, GetTaskGraphSubmitter, SummarizeDecisionAnswers, SystemPlaceholderManager, WithoutHostOnlyAgentRunDataKeys, WithAgentRunDataTrustApplied, AgentUserPolicyEngine, ConfigOf } from '@memberjunction/ai-core-plus';
|
|
58
|
-
import { ActionResult, RunActionParams, AUDIENCE_UNSUPPORTED_RESULT_CODE, ActionRunScopeIsBounded } from '@memberjunction/actions-base';
|
|
59
|
+
import { StringifyForPersistence, AIPromptParams, ChildPromptParam, ConversationUtility, ParseFileOutputRef, parseAssignmentStrategy, ResolveClientTools, initAgentRunStep, finalizeAgentRunStep, AgentRunStepSaveQueue, ExtractPromptResultText, GetTaskGraphSubmitter, SummarizeDecisionAnswers, SystemPlaceholderManager, WithoutHostOnlyAgentRunDataKeys, WithAgentRunDataTrustApplied, AgentUserPolicyEngine, ApplyOutputMapping, BuildActionOutputObject, ConfigOf, ResolveLoopBodyParams, ValidateLoopOperationStructure } from '@memberjunction/ai-core-plus';
|
|
60
|
+
import { ActionEngineBase, ActionResult, RunActionParams, AUDIENCE_UNSUPPORTED_RESULT_CODE, ActionRunScopeIsBounded } from '@memberjunction/actions-base';
|
|
59
61
|
import { UserCache } from '@memberjunction/generic-database-provider';
|
|
60
62
|
import { AgentAudienceAddsReader, AgentAudienceProblem, AgentAudienceReaderIDs, MatchAudienceUsers } from './agent-audience.js';
|
|
61
63
|
import { TemplateEngineServer } from '@memberjunction/templates';
|
|
@@ -72,7 +74,8 @@ import { PayloadFeedbackManager } from './PayloadFeedbackManager.js';
|
|
|
72
74
|
import { DEFAULT_LOOP_AGENT_PROMPT_PARAMS, MAX_DECISION_CALLS_PER_TURN, MAX_DECISION_REQUESTS_PER_TURN, ResolveFinishIfMode } from './agent-types/loop-agent-prompt-params.js';
|
|
73
75
|
import { FinishIfModeWarnings } from './finish-if-mode-warnings.js';
|
|
74
76
|
import { ApplyCatalogNarrowing, BuildCatalogNarrowingQuestions, CatalogNarrowingCandidatesToAsk, CatalogNarrowingNote, CATALOG_NARROWING_FIND_ACTIONS, IsAlwaysShownAction, IsCatalogListNarrowed, NoCatalogNarrowing, OpeningRequestText, ReachableCatalogNarrowingLimits, ResolveCatalogNarrowingLimits, SelectCatalogNarrowing, } from './catalog-narrowing.js';
|
|
75
|
-
import { BuildDecisionDiscoveryOptionSet, BuildDecisionDiscoveryQuestions, CanSearchEntities, DECISION_DISCOVERY_MAX_RECORDED_IDS, DECISION_DISCOVERY_MIN_CONFIDENCE, DECISION_DISCOVERY_MIN_OPTIONS, DECISION_DISCOVERY_TIMEOUT_MS, DecisionDiscoveryAgentSearch, DecisionDiscoveryFromResult, DecisionDiscoveryRunnableAgents, DecisionPromptOptionCap, FailedDecisionDiscovery, HostAllowedAgentIDs, IsDecisionDiscoveryOn, IsOpeningTurn, MentionsAgent, } from './decision-discovery.js';
|
|
77
|
+
import { BuildDecisionDiscoveryOptionSet, BuildDecisionDiscoveryQuestions, CanSearchEntities, DECISION_DISCOVERY_MAX_RECORDED_IDS, DECISION_DISCOVERY_MIN_CONFIDENCE, DECISION_DISCOVERY_MIN_OPTIONS, DECISION_DISCOVERY_TIMEOUT_MS, DecisionDiscoveryAgentSearch, DecisionDiscoveryFromResult, DecisionDiscoveryRunnableAgents, DecisionPromptOptionCap, FailedDecisionDiscovery, HostAllowedAgentIDs, IsDecisionDiscoveryOn, IsOpeningTurn, KeepHostAllowedAgents, MentionsAgent, } from './decision-discovery.js';
|
|
78
|
+
import { ResolveHandoffTarget } from './handoff-target.js';
|
|
76
79
|
import { BuildFinishIfQuestions, CapFinishIfState, FINISH_IF_STATE_EXCERPT, FormatActionForFinishIf, FormatSubAgentForFinishIf, JudgeFinishIf } from './finish-if-state.js';
|
|
77
80
|
import { PipelineExecutor, PipelineToolRegistry, ActionInvocable, ArtifactToolInvocable, BuildPipelineToolDocs, formatFinalOutput, summarizePipelineStages, } from './pipeline/index.js';
|
|
78
81
|
// The ONE payload-mapping dialect. Loop agents and the task-graph dispatcher read the same authored
|
|
@@ -80,7 +83,8 @@ import { PipelineExecutor, PipelineToolRegistry, ActionInvocable, ArtifactToolIn
|
|
|
80
83
|
import { GetValueFromPath, SetMappedValue } from '@memberjunction/ai-core-plus';
|
|
81
84
|
import { AgentDataPreloader } from './AgentDataPreloader.js';
|
|
82
85
|
import { ClientToolRequestManager } from './ClientToolRequestManager.js';
|
|
83
|
-
import { BuildClientToolResultMessage, ResolveClientToolResultMaxChars, ReplaceMediaBlocksWithStubs, IsMediaBlock, IMAGE_BLOCK_TOKEN_ESTIMATE } from './client-tool-results.js';
|
|
86
|
+
import { BuildClientToolResultMessage, ResolveClientToolResultMaxChars, ReplaceMediaBlocksWithStubs, IsMediaBlock, IMAGE_BLOCK_TOKEN_ESTIMATE, WrapUntrustedExternalData } from './client-tool-results.js';
|
|
87
|
+
import { CanAgentOwnSubAgentConsults, DEFAULT_MAX_SUB_AGENT_CONSULT_ROUNDS, FormatReloadedConsultsMessage, FormatResponseFormSummary, FormatSubAgentConsultMessage, LoadOpenSubAgentConsults } from './sub-agent-consult.js';
|
|
84
88
|
import { ConversationMessageResolver } from './utils/ConversationMessageResolver.js';
|
|
85
89
|
import _ from 'lodash';
|
|
86
90
|
/**
|
|
@@ -132,6 +136,27 @@ import _ from 'lodash';
|
|
|
132
136
|
* one) from saturating the model API / DB pool with N concurrent runs.
|
|
133
137
|
*/
|
|
134
138
|
const PARALLEL_SUBAGENT_CONCURRENCY_LIMIT = 5;
|
|
139
|
+
/** Result codes that are structurally non-retryable (permission or run-scope refusals). */
|
|
140
|
+
export const NON_RETRYABLE_RESULT_CODES = new Set([
|
|
141
|
+
'PERMISSION_DENIED',
|
|
142
|
+
'RUN_SCOPE_UNSUPPORTED',
|
|
143
|
+
]);
|
|
144
|
+
/** Result code of a call the user's agent policy denies outright (`checkUserActionPolicy`). */
|
|
145
|
+
export const POLICY_DENIED_RESULT_CODE = 'POLICY_DENIED';
|
|
146
|
+
/** Result code of a call the user's agent policy allows only with the user's approval. */
|
|
147
|
+
export const POLICY_APPROVAL_REQUIRED_RESULT_CODE = 'POLICY_APPROVAL_REQUIRED';
|
|
148
|
+
/** Result code of a call the user's agent policy defers to its next allowed time window. */
|
|
149
|
+
export const POLICY_DEFERRED_RESULT_CODE = 'POLICY_DEFERRED_OUTSIDE_TIME_WINDOW';
|
|
150
|
+
/**
|
|
151
|
+
* The result codes `checkUserActionPolicy` returns when the user's agent policy refuses a call. None of them is
|
|
152
|
+
* fixed by retrying: approval cannot be granted inside the run, a time window does not open by asking again, and
|
|
153
|
+
* a denial repeats for the same call.
|
|
154
|
+
*/
|
|
155
|
+
const POLICY_REFUSAL_RESULT_CODES = new Set([
|
|
156
|
+
POLICY_DENIED_RESULT_CODE,
|
|
157
|
+
POLICY_APPROVAL_REQUIRED_RESULT_CODE,
|
|
158
|
+
POLICY_DEFERRED_RESULT_CODE,
|
|
159
|
+
]);
|
|
135
160
|
/** Identical-arguments rule: this many failures with the same arguments block further identical calls. */
|
|
136
161
|
export const IDENTICAL_FAILURE_THRESHOLD = 2;
|
|
137
162
|
/** Attempt budget: this many consecutive failures, across any arguments, disable the action for the run. */
|
|
@@ -201,6 +226,13 @@ export class BaseAgent {
|
|
|
201
226
|
* @private
|
|
202
227
|
*/
|
|
203
228
|
this._audienceLockedActions = new Set();
|
|
229
|
+
/**
|
|
230
|
+
* External/untrusted data sources ingested during the current agent run (Primitive 2).
|
|
231
|
+
* Once non-empty, {@link IsRunTainted} is true for the remainder of the run and any memory
|
|
232
|
+
* notes written by the run land as `Status = 'Pending'` with taint provenance in `Comments`.
|
|
233
|
+
* @protected
|
|
234
|
+
*/
|
|
235
|
+
this._taintedSources = [];
|
|
204
236
|
/**
|
|
205
237
|
* Parameter-aware failure tracking per action name for the current agent run.
|
|
206
238
|
* Differentiates identical retries (which trip quickly) from parameter modifications (which allow self-correction).
|
|
@@ -264,6 +296,15 @@ export class BaseAgent {
|
|
|
264
296
|
* @private
|
|
265
297
|
*/
|
|
266
298
|
this._feedbackRequestId = null;
|
|
299
|
+
/**
|
|
300
|
+
* Stores the handoff outcome when a Handoff step fires.
|
|
301
|
+
* Populated by executeHandoffStep(), returned in ExecuteAgentResult.handoff.
|
|
302
|
+
*/
|
|
303
|
+
this._handoffResult = null;
|
|
304
|
+
/**
|
|
305
|
+
* Stores the target agent resolved during validateHandoffNextStep() for executeHandoffStep().
|
|
306
|
+
*/
|
|
307
|
+
this._resolvedHandoffTarget = null;
|
|
267
308
|
this._resolvedStorageAccountId = null;
|
|
268
309
|
/**
|
|
269
310
|
* Most recent artifactDirective returned by a child or related sub-agent during this run.
|
|
@@ -375,6 +416,14 @@ export class BaseAgent {
|
|
|
375
416
|
* @private
|
|
376
417
|
*/
|
|
377
418
|
this._effectiveSubAgents = [];
|
|
419
|
+
/**
|
|
420
|
+
* True once gatherPromptTemplateData() has computed {@link _effectiveActions} and
|
|
421
|
+
* {@link _effectiveSubAgents} for this run. An empty list is then authoritative: a host's
|
|
422
|
+
* `actionChanges` that remove every action leave the run with none, instead of falling back to
|
|
423
|
+
* the agent's database configuration as an uncomputed list does.
|
|
424
|
+
* @private
|
|
425
|
+
*/
|
|
426
|
+
this._effectiveCatalogComputed = false;
|
|
378
427
|
/**
|
|
379
428
|
* The request that opened the run: the last user message when it started, before the framework
|
|
380
429
|
* added anything. Catalog narrowing judges the catalog against it.
|
|
@@ -472,6 +521,29 @@ export class BaseAgent {
|
|
|
472
521
|
* @private
|
|
473
522
|
*/
|
|
474
523
|
this._validationRetryCount = 0;
|
|
524
|
+
/**
|
|
525
|
+
* Per-parent-run consultation round counter keyed by `subAgentEntity.ID`.
|
|
526
|
+
* Tracks how many times each sub-agent has returned `FinalStep === 'Chat'`
|
|
527
|
+
* under `ChatHandlingOption = 'Consult'` during this run.
|
|
528
|
+
* Reset at the start of each agent run.
|
|
529
|
+
* @private
|
|
530
|
+
*/
|
|
531
|
+
this._subAgentConsultRounds = new Map();
|
|
532
|
+
/**
|
|
533
|
+
* Open sub-agent consultations keyed by `childRunId`.
|
|
534
|
+
* Populated when a child sub-agent pauses with `FinalStep === 'Chat'` under `'Consult'`,
|
|
535
|
+
* and removed when the parent resumes that child run.
|
|
536
|
+
* Reset at the start of each agent run.
|
|
537
|
+
* @private
|
|
538
|
+
*/
|
|
539
|
+
this._openSubAgentConsults = new Map();
|
|
540
|
+
/**
|
|
541
|
+
* Tracks whether we have already logged the warning that `'Consult'` is not
|
|
542
|
+
* supported on agent types where `InjectLoopResultsAsMessage` is `false`.
|
|
543
|
+
* Reset at the start of each agent run.
|
|
544
|
+
* @private
|
|
545
|
+
*/
|
|
546
|
+
this._loggedConsultUnsupportedAgentType = false;
|
|
475
547
|
/**
|
|
476
548
|
* Counter tracking the number of context recovery attempts made in this run.
|
|
477
549
|
* Context recovery removes/compacts old messages when context length is exceeded.
|
|
@@ -601,6 +673,19 @@ export class BaseAgent {
|
|
|
601
673
|
get TreeBudget() {
|
|
602
674
|
return this._treeBudget;
|
|
603
675
|
}
|
|
676
|
+
/**
|
|
677
|
+
* True when the current agent run has ingested at least one `'Untrusted'` or `'SemiTrusted'`
|
|
678
|
+
* action or client-tool result.
|
|
679
|
+
*/
|
|
680
|
+
get IsRunTainted() {
|
|
681
|
+
return this._taintedSources.length > 0;
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Read-only view of all `'Untrusted'` and `'SemiTrusted'` sources ingested during the current run.
|
|
685
|
+
*/
|
|
686
|
+
get TaintedSources() {
|
|
687
|
+
return this._taintedSources;
|
|
688
|
+
}
|
|
604
689
|
/**
|
|
605
690
|
* The identity of one action call's arguments, for the circuit breaker's identical-arguments
|
|
606
691
|
* rule: two calls with the same normalized string are "the same call", whatever order the model
|
|
@@ -973,22 +1058,61 @@ export class BaseAgent {
|
|
|
973
1058
|
return 'fatal';
|
|
974
1059
|
}
|
|
975
1060
|
const record = this._actionFailureHistory.get(summary.actionName);
|
|
976
|
-
if (
|
|
977
|
-
return 'warning';
|
|
978
|
-
}
|
|
979
|
-
if (record.totalConsecutiveFailures >= ACTION_FAILURE_BUDGET) {
|
|
1061
|
+
if (record && record.totalConsecutiveFailures >= ACTION_FAILURE_BUDGET) {
|
|
980
1062
|
return 'attempts-exhausted';
|
|
981
1063
|
}
|
|
982
|
-
|
|
1064
|
+
// A policy refusal still counts in the history, so the budget above stays as the backstop; but it
|
|
1065
|
+
// outranks the identical-arguments rule, whose guidance ("adjust your parameters") is exactly what
|
|
1066
|
+
// a refused call must not be told. Approval and a time window do not come from different arguments.
|
|
1067
|
+
if (POLICY_REFUSAL_RESULT_CODES.has(summary.resultCode)) {
|
|
1068
|
+
return 'policy';
|
|
1069
|
+
}
|
|
1070
|
+
if (NON_RETRYABLE_RESULT_CODES.has(summary.resultCode) || summary.errorRecovery?.Retryable === false) {
|
|
1071
|
+
return 'non-retryable';
|
|
1072
|
+
}
|
|
1073
|
+
if (record && record.identicalFailures >= IDENTICAL_FAILURE_THRESHOLD) {
|
|
983
1074
|
return 'identical-arguments';
|
|
984
1075
|
}
|
|
985
1076
|
return 'warning';
|
|
986
1077
|
}
|
|
1078
|
+
/**
|
|
1079
|
+
* The guidance line for a call the user's agent policy refused. The default `[WARNING/ACTION_FAILURE]`
|
|
1080
|
+
* line tells the model to adjust its parameters and try again, up to the budget; a refusal is not a
|
|
1081
|
+
* parameter error, and a retry burns the budget without ever succeeding.
|
|
1082
|
+
*/
|
|
1083
|
+
formatPolicyRefusalDirective(summary) {
|
|
1084
|
+
const name = summary.actionName;
|
|
1085
|
+
switch (summary.resultCode) {
|
|
1086
|
+
case POLICY_APPROVAL_REQUIRED_RESULT_CODE:
|
|
1087
|
+
return `[CRITICAL/POLICY_APPROVAL_REQUIRED] Action '${name}' requires the user's approval under their agent policy: "${summary.message}". ` +
|
|
1088
|
+
`Approval cannot be granted inside this run, so DO NOT retry '${name}'. Tell the user exactly what you intended to do and why, ` +
|
|
1089
|
+
'and ask them to approve it or do it themselves.';
|
|
1090
|
+
case POLICY_DEFERRED_RESULT_CODE:
|
|
1091
|
+
return `[CRITICAL/POLICY_DEFERRED] Action '${name}' is outside the time window the user's agent policy allows: "${summary.message}". ` +
|
|
1092
|
+
`Retrying now will not help; DO NOT call '${name}' again during this run. Tell the user it was deferred and when it can run.`;
|
|
1093
|
+
default:
|
|
1094
|
+
return `[CRITICAL/POLICY_DENIED] Action '${name}' was refused by the user's agent policy: "${summary.message}". ` +
|
|
1095
|
+
'This is a governance decision, not a problem with your arguments: the same call will be refused again. ' +
|
|
1096
|
+
`Call '${name}' again only with materially different parameters, and only if the reason says the refusal depends on them; ` +
|
|
1097
|
+
'otherwise use another tool or tell the user what you could not do.';
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
987
1100
|
/** The guidance line appended to the history for one failed action. */
|
|
988
1101
|
formatActionFailureDirective(summary) {
|
|
989
1102
|
const name = summary.actionName;
|
|
990
1103
|
const record = this._actionFailureHistory.get(name);
|
|
991
1104
|
switch (this.classifyActionFailure(summary)) {
|
|
1105
|
+
case 'policy':
|
|
1106
|
+
return this.formatPolicyRefusalDirective(summary);
|
|
1107
|
+
case 'non-retryable': {
|
|
1108
|
+
const suggestion = summary.errorRecovery?.RecoverySuggestion
|
|
1109
|
+
? ` ${summary.errorRecovery.RecoverySuggestion}`
|
|
1110
|
+
: '';
|
|
1111
|
+
const nextActions = summary.errorRecovery?.SuggestedNextActions?.length
|
|
1112
|
+
? ` Suggested alternative actions: ${summary.errorRecovery.SuggestedNextActions.map(a => `\`${a}\``).join(', ')}.`
|
|
1113
|
+
: '';
|
|
1114
|
+
return `[CRITICAL/NON_RETRYABLE_FAILURE] Action '${name}' failed with non-retryable error (${summary.resultCode}): "${summary.message}".${suggestion}${nextActions} DO NOT retry '${name}' against the same target or with the same parameters; pivot to an alternative tool, a different target, or inform the user.`;
|
|
1115
|
+
}
|
|
992
1116
|
case 'audience':
|
|
993
1117
|
return `[CRITICAL/NOT_AVAILABLE_IN_SHARED_CONVERSATION] Action '${name}' is not available in this shared conversation: what it ` +
|
|
994
1118
|
`returns could not be limited to what everyone in it may see ("${summary.message}"). It is not broken or misconfigured. ` +
|
|
@@ -999,8 +1123,86 @@ export class BaseAgent {
|
|
|
999
1123
|
return `[CRITICAL/ATTEMPTS_EXHAUSTED] Action '${name}' has failed ${record?.totalConsecutiveFailures ?? ACTION_FAILURE_BUDGET} consecutive times: "${summary.message}". Retries for this action are exhausted. You MUST pivot to an alternative tool or continue with available data.`;
|
|
1000
1124
|
case 'identical-arguments':
|
|
1001
1125
|
return `[CRITICAL/REPEATED_IDENTICAL_CALL] Action '${name}' failed again with the EXACT SAME arguments: "${summary.message}". Calling '${name}' with these parameters will not work. You MUST either adjust your parameters or pivot to an alternative tool.`;
|
|
1002
|
-
default:
|
|
1003
|
-
|
|
1126
|
+
default: {
|
|
1127
|
+
const suggestion = summary.errorRecovery?.RecoverySuggestion
|
|
1128
|
+
? ` ${summary.errorRecovery.RecoverySuggestion}`
|
|
1129
|
+
: '';
|
|
1130
|
+
const suggestedValues = summary.errorRecovery?.SuggestedValues?.length
|
|
1131
|
+
? ` Valid alternatives: ${summary.errorRecovery.SuggestedValues.join(', ')}.`
|
|
1132
|
+
: '';
|
|
1133
|
+
return `[WARNING/ACTION_FAILURE] Action '${name}' failed: "${summary.message}".${suggestion}${suggestedValues} Review the error and adjust your input parameters (attempt ${record?.totalConsecutiveFailures ?? 1} of ${ACTION_FAILURE_BUDGET}). DO NOT retry calling '${name}' with identical arguments.`;
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
/**
|
|
1138
|
+
* Resolves the output trust classification for an action from its `MJ: Actions` metadata
|
|
1139
|
+
* (`actionEntity.Config_Object?.outputTrustLevel`), with per-agent or per-run overrides via
|
|
1140
|
+
* `AgentTypePromptParams`.
|
|
1141
|
+
*
|
|
1142
|
+
* Precedence:
|
|
1143
|
+
* 1. An explicit per-action `actionTrustLevels` entry in `AgentTypePromptParams` — the operator's last word
|
|
1144
|
+
* 2. The `trustedActionNames` / `untrustedActionNames` lists in `AgentTypePromptParams`
|
|
1145
|
+
* 3. The action's metadata catalog setting (`Action.Config_Object?.outputTrustLevel`, looking up the
|
|
1146
|
+
* action by name in `ActionEngineBase.Instance.Actions` when `actionEntity` is omitted)
|
|
1147
|
+
* 4. `'Trusted'`
|
|
1148
|
+
* @protected
|
|
1149
|
+
*/
|
|
1150
|
+
resolveActionTrustLevel(actionName, actionEntity, params) {
|
|
1151
|
+
const normalizedName = actionName.trim().toLowerCase();
|
|
1152
|
+
const entity = actionEntity ?? ActionEngineBase.Instance.Actions?.find(a => a.Name?.trim().toLowerCase() === normalizedName);
|
|
1153
|
+
const entityName = entity?.Name?.trim().toLowerCase();
|
|
1154
|
+
const namesAction = (candidate) => {
|
|
1155
|
+
const n = candidate.trim().toLowerCase();
|
|
1156
|
+
return n === normalizedName || (entityName !== undefined && n === entityName);
|
|
1157
|
+
};
|
|
1158
|
+
const isLevel = (v) => v === 'Trusted' || v === 'SemiTrusted' || v === 'Untrusted';
|
|
1159
|
+
const promptParams = (params?.data?.__agentTypePromptParams ?? this._agentTypePromptParams);
|
|
1160
|
+
// 1. Explicit per-action override
|
|
1161
|
+
if (promptParams?.actionTrustLevels && typeof promptParams.actionTrustLevels === 'object') {
|
|
1162
|
+
for (const [key, level] of Object.entries(promptParams.actionTrustLevels)) {
|
|
1163
|
+
if (namesAction(key) && isLevel(level)) {
|
|
1164
|
+
return level;
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
// 2. Per-agent / per-run name lists
|
|
1169
|
+
if (Array.isArray(promptParams?.trustedActionNames) && promptParams.trustedActionNames.some(namesAction)) {
|
|
1170
|
+
return 'Trusted';
|
|
1171
|
+
}
|
|
1172
|
+
if (Array.isArray(promptParams?.untrustedActionNames) && promptParams.untrustedActionNames.some(namesAction)) {
|
|
1173
|
+
return 'Untrusted';
|
|
1174
|
+
}
|
|
1175
|
+
// 3. Action metadata catalog setting (Action.Config_Object?.outputTrustLevel)
|
|
1176
|
+
const metadataLevel = entity?.Config_Object?.outputTrustLevel;
|
|
1177
|
+
if (isLevel(metadataLevel)) {
|
|
1178
|
+
return metadataLevel;
|
|
1179
|
+
}
|
|
1180
|
+
if (typeof entity?.Config_ === 'string' && entity.Config_.trim().length > 0) {
|
|
1181
|
+
const parsed = CleanAndParseJSON(entity.Config_, false);
|
|
1182
|
+
if (parsed && isLevel(parsed.outputTrustLevel)) {
|
|
1183
|
+
return parsed.outputTrustLevel;
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
return 'Trusted';
|
|
1187
|
+
}
|
|
1188
|
+
/**
|
|
1189
|
+
* Records a tainted source ingested during the current agent run.
|
|
1190
|
+
* @protected
|
|
1191
|
+
*/
|
|
1192
|
+
recordTaintedSource(stepNumber, sourceName, trustLevel) {
|
|
1193
|
+
if (!this._taintedSources.some(s => s.stepNumber === stepNumber && s.sourceName === sourceName && s.trustLevel === trustLevel)) {
|
|
1194
|
+
this._taintedSources.push({ stepNumber, sourceName, trustLevel });
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
/**
|
|
1198
|
+
* Folds a finished sub-agent's tainted sources into this run's, attributed to the sub-agent step,
|
|
1199
|
+
* so delegating a web search taints the parent exactly as searching itself would. Runs whether or
|
|
1200
|
+
* not the child succeeded: a failed child may still have read external content.
|
|
1201
|
+
* @protected
|
|
1202
|
+
*/
|
|
1203
|
+
absorbSubAgentTaint(subAgentName, subAgentResult, stepNumber) {
|
|
1204
|
+
for (const source of subAgentResult.taintedSources ?? []) {
|
|
1205
|
+
this.recordTaintedSource(stepNumber, `sub-agent:${subAgentName}/${source.sourceName}`, source.trustLevel);
|
|
1004
1206
|
}
|
|
1005
1207
|
}
|
|
1006
1208
|
/**
|
|
@@ -1221,8 +1423,8 @@ export class BaseAgent {
|
|
|
1221
1423
|
let extractedCount = 0;
|
|
1222
1424
|
for (let i = 0; i < mediaItems.length; i++) {
|
|
1223
1425
|
const media = mediaItems[i];
|
|
1224
|
-
//
|
|
1225
|
-
if (media.data && media.data.length > BaseAgent.LARGE_BINARY_THRESHOLD) {
|
|
1426
|
+
// Intercept when already stored in MJ Storage (fileId) or when inline data exceeds threshold
|
|
1427
|
+
if (media.fileId || (media.data && media.data.length > BaseAgent.LARGE_BINARY_THRESHOLD)) {
|
|
1226
1428
|
// Generate unique reference ID
|
|
1227
1429
|
const refId = `media-${Date.now().toString(36)}-${i}-${Math.random().toString(36).substring(2, 8)}`;
|
|
1228
1430
|
// Store in unified media outputs — always persisted by AgentRunner.
|
|
@@ -1279,19 +1481,20 @@ export class BaseAgent {
|
|
|
1279
1481
|
}
|
|
1280
1482
|
/**
|
|
1281
1483
|
* Substitutes `${media:<refId>}` placeholders in a string with the actual
|
|
1282
|
-
* data URI (`data:<mime>;base64,<bytes>`)
|
|
1484
|
+
* data URI (`data:<mime>;base64,<bytes>`) or stored `fileId` (for `fileId`-only
|
|
1485
|
+
* media items) of the matching intercepted media item.
|
|
1283
1486
|
*
|
|
1284
1487
|
* Used for payload / actionable-command resolution at the terminal step, where the
|
|
1285
|
-
* LLM wants to embed image (or other media) data inline at a
|
|
1286
|
-
* its structured output rather than as a trailing
|
|
1287
|
-
* variant of placeholder resolution; recursive walker
|
|
1288
|
-
* {@link resolveMediaPlaceholdersInPayload}.
|
|
1488
|
+
* LLM wants to embed image (or other media) data or a stored file ID inline at a
|
|
1489
|
+
* specific position in its structured output rather than only as a trailing
|
|
1490
|
+
* attachment card. The string variant of placeholder resolution; recursive walker
|
|
1491
|
+
* lives in {@link resolveMediaPlaceholdersInPayload}.
|
|
1289
1492
|
*
|
|
1290
1493
|
* This function only does substitution — it has no persistence side effects.
|
|
1291
1494
|
*
|
|
1292
1495
|
* @param text - The string that may contain media placeholders
|
|
1293
|
-
* @returns String with placeholders resolved to
|
|
1294
|
-
* placeholder if the refId is unknown — defensive, shouldn't happen)
|
|
1496
|
+
* @returns String with placeholders resolved to data URIs or stored file IDs (or the
|
|
1497
|
+
* original placeholder if the refId is unknown — defensive, shouldn't happen)
|
|
1295
1498
|
* @private
|
|
1296
1499
|
* @since 3.1.0
|
|
1297
1500
|
*/
|
|
@@ -1309,6 +1512,9 @@ export class BaseAgent {
|
|
|
1309
1512
|
if (media?.data) {
|
|
1310
1513
|
return `data:${media.mimeType};base64,${media.data}`;
|
|
1311
1514
|
}
|
|
1515
|
+
if (media?.fileId) {
|
|
1516
|
+
return media.fileId;
|
|
1517
|
+
}
|
|
1312
1518
|
// Unknown refId — leave the placeholder in place rather than emit a broken
|
|
1313
1519
|
// data URI. Defensive; this branch should not fire in normal flow.
|
|
1314
1520
|
this.logStatus(`⚠️ Media reference '${refId}' not found in registry`, true);
|
|
@@ -1894,10 +2100,18 @@ export class BaseAgent {
|
|
|
1894
2100
|
this._validationRetryCount = 0;
|
|
1895
2101
|
this._generalValidationRetryCount = 0;
|
|
1896
2102
|
this._contextRecoveryAttempts = 0;
|
|
2103
|
+
this._subAgentConsultRounds.clear();
|
|
2104
|
+
this._openSubAgentConsults.clear();
|
|
2105
|
+
this._loggedConsultUnsupportedAgentType = false;
|
|
1897
2106
|
this._effectiveActions = [];
|
|
2107
|
+
this._effectiveSubAgents = [];
|
|
2108
|
+
this._effectiveCatalogComputed = false;
|
|
1898
2109
|
this._dynamicActionLimits = {};
|
|
1899
2110
|
this._mediaOutputs = [];
|
|
2111
|
+
this._handoffResult = null;
|
|
2112
|
+
this._resolvedHandoffTarget = null;
|
|
1900
2113
|
this._lastSubAgentArtifactDirective = undefined;
|
|
2114
|
+
this._taintedSources = [];
|
|
1901
2115
|
this._messageLifecycleCallback = params.onMessageLifecycle;
|
|
1902
2116
|
this._catalogNarrowing = undefined;
|
|
1903
2117
|
this._openingRequest = OpeningRequestText(params.conversationMessages);
|
|
@@ -1944,21 +2158,26 @@ export class BaseAgent {
|
|
|
1944
2158
|
const userId = params.userId || params.contextUser?.ID;
|
|
1945
2159
|
const companyId = params.companyId;
|
|
1946
2160
|
const lastUserMessage = params.conversationMessages.filter(m => m.role === 'user').pop();
|
|
1947
|
-
const inputText = lastUserMessage?.content || '';
|
|
2161
|
+
const inputText = lastUserMessage?.metadata?.rawContent ?? (lastUserMessage?.content || '');
|
|
1948
2162
|
// The run's scope exactly as initializeAgentRun validated it in Phase 1 — what the run row records and every
|
|
1949
2163
|
// action is handed — so notes, RAG and scoped prompt parts search the same tenant and dimensions.
|
|
1950
2164
|
const runScope = this.runScopeForContext(params);
|
|
1951
2165
|
// The user's new message, captured by identity before anything below adds to the list, so a
|
|
1952
2166
|
// resumed stopped run can be spliced in ahead of it once the parallel phase settles.
|
|
1953
2167
|
const continuationMessage = wrappedParams.conversationMessages[wrappedParams.conversationMessages.length - 1];
|
|
1954
|
-
//
|
|
1955
|
-
|
|
2168
|
+
// Stage Phase 2 system message injections in isolated arrays so their prefix order is
|
|
2169
|
+
// 100% deterministic regardless of Promise.all completion timing (Lesson 1 Vector 5).
|
|
2170
|
+
const memoryStagedMessages = [];
|
|
2171
|
+
const ragStagedMessages = [];
|
|
2172
|
+
const discoveryStagedMessages = [];
|
|
2173
|
+
// Positions matter: [0] is the config, [5] the stopped-run continuation, and [7] open sub-agent consults.
|
|
2174
|
+
const [config, , , , , stoppedRunContinuation, , openConsults] = await Promise.all([
|
|
1956
2175
|
this.loadAgentConfiguration(params.agent),
|
|
1957
2176
|
this.preloadAgentData(wrappedParams),
|
|
1958
|
-
this.InjectContextMemory(typeof inputText === 'string' ? inputText : '', params.agent, userId, companyId, params.contextUser,
|
|
2177
|
+
this.InjectContextMemory(typeof inputText === 'string' ? inputText : '', params.agent, userId, companyId, params.contextUser, memoryStagedMessages, runScope.EntityID, runScope.RecordID, runScope.Secondary, this.parseSecondaryScopeConfig(params.agent),
|
|
1959
2178
|
// Under an audience, one user's notes and examples are not shown to the room.
|
|
1960
2179
|
this.runAudienceAddsReader(params)),
|
|
1961
|
-
this.InjectPreExecutionRAG(typeof inputText === 'string' ? inputText : '', params.agent, params.contextUser,
|
|
2180
|
+
this.InjectPreExecutionRAG(typeof inputText === 'string' ? inputText : '', params.agent, params.contextUser, ragStagedMessages, params.conversationMessages, runScope.EntityID, runScope.RecordID, runScope.Secondary, params.payload,
|
|
1962
2181
|
// Phase 1 has already activated requested + persisted conversation skills.
|
|
1963
2182
|
this.activeSkillIDsForRun(params),
|
|
1964
2183
|
// Each reader must pass the scope gate; the search keeps what every one of them may read.
|
|
@@ -1972,8 +2191,14 @@ export class BaseAgent {
|
|
|
1972
2191
|
this.loadStoppedRunContinuation(wrappedParams),
|
|
1973
2192
|
// Decision discovery (plan Task 3.1), off unless the decisionsEnabled and decisionDiscovery prompt
|
|
1974
2193
|
// params are true: may add a <suggested_agent> system message, within DECISION_DISCOVERY_TIMEOUT_MS.
|
|
1975
|
-
this.InjectDecisionDiscovery(params.agent, params.contextUser,
|
|
2194
|
+
this.InjectDecisionDiscovery(params.agent, params.contextUser, discoveryStagedMessages, params.data),
|
|
2195
|
+
// If this run resumes a prior run that paused with FinalStep === 'Chat', reload any unanswered
|
|
2196
|
+
// sub-agent consults so the caller's answer can be relayed back to the waiting sub-agent.
|
|
2197
|
+
this.loadOpenConsults(wrappedParams)
|
|
1976
2198
|
]);
|
|
2199
|
+
if (memoryStagedMessages.length > 0 || ragStagedMessages.length > 0 || discoveryStagedMessages.length > 0) {
|
|
2200
|
+
wrappedParams.conversationMessages.unshift(...memoryStagedMessages, ...ragStagedMessages, ...discoveryStagedMessages);
|
|
2201
|
+
}
|
|
1977
2202
|
// Resume (or summarize) a run the user stopped, now that nothing else is writing the list.
|
|
1978
2203
|
this.applyStoppedRunContinuation(wrappedParams, stoppedRunContinuation, continuationMessage);
|
|
1979
2204
|
// Inject scope-resolved prompt parts (role-faithful) for this agent's prompt, alongside
|
|
@@ -1981,6 +2206,9 @@ export class BaseAgent {
|
|
|
1981
2206
|
const messagesBeforeParts = new Set(wrappedParams.conversationMessages);
|
|
1982
2207
|
this.InjectScopedPromptParts(params.agent, wrappedParams.conversationMessages, runScope.EntityID, runScope.RecordID, runScope.Secondary);
|
|
1983
2208
|
await this.replaceScopedPartPlaceholders(wrappedParams.conversationMessages, messagesBeforeParts, params.contextUser);
|
|
2209
|
+
// Restore open sub-agent consults from a resumed Chat run and splice the reminder immediately
|
|
2210
|
+
// before the caller's answer (continuationMessage).
|
|
2211
|
+
this.applyOpenConsults(wrappedParams, openConsults, continuationMessage);
|
|
1984
2212
|
if (!config.success) {
|
|
1985
2213
|
this.logError(`Failed to load agent configuration: ${config.errorMessage}`, {
|
|
1986
2214
|
agent: params.agent,
|
|
@@ -2071,17 +2299,25 @@ export class BaseAgent {
|
|
|
2071
2299
|
// passed in, not our chained signal.
|
|
2072
2300
|
params.cancellationToken = upstreamToken;
|
|
2073
2301
|
this._runAbortController = null;
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2302
|
+
await this.endRun(params);
|
|
2303
|
+
}
|
|
2304
|
+
}
|
|
2305
|
+
/**
|
|
2306
|
+
* {@link Execute}'s per-run teardown, called from its top-level `finally` on every exit path.
|
|
2307
|
+
* The run leaves the watchdog first, before the subclass {@link finalizeRun} hook, so a hook
|
|
2308
|
+
* that throws can never leave a finished run being heart-beaten for the life of the process.
|
|
2309
|
+
*/
|
|
2310
|
+
async endRun(params) {
|
|
2311
|
+
if (this._agentRun?.ID) {
|
|
2312
|
+
AgentRunWatchdog.Instance.Untrack(this._agentRun.ID);
|
|
2084
2313
|
}
|
|
2314
|
+
// A cancellation, or an error thrown out of the step loop, leaves any held decision
|
|
2315
|
+
// requests unasked. The terminate path has already logged and cleared its own.
|
|
2316
|
+
this.skipHeldDecisions(params, this.runEndForHeldDecisions());
|
|
2317
|
+
this.releasePerRunDataCache();
|
|
2318
|
+
await this.finalizeRun(this.deriveRunOutcome());
|
|
2319
|
+
// The run is over: a later direct ExecuteSingleAction resolves the scope and the audience from its own params.
|
|
2320
|
+
this.clearRunBoundState();
|
|
2085
2321
|
}
|
|
2086
2322
|
/**
|
|
2087
2323
|
* Fails the run at its start, before any prompt: marks the already-created AgentRun Failed with the message
|
|
@@ -2174,13 +2410,18 @@ export class BaseAgent {
|
|
|
2174
2410
|
* (`TaskGraphAgentRunner`) that carries neither the audience nor the scope. So graphs are withheld when the
|
|
2175
2411
|
* audience adds a reader, and when the run's validated scope carries a tenant or a secondary dimension
|
|
2176
2412
|
* (`ActionRunScopeIsBounded`): a model-written Scoped Search node would search outside the run's tenant, and an
|
|
2177
|
-
* agent node would drop it.
|
|
2413
|
+
* agent node would drop it. Likewise when the host assigned the run's search scopes (`SearchScopeIDs`): a graph's
|
|
2414
|
+
* Scoped Search node would fall back to the agent's own search access.
|
|
2178
2415
|
*/
|
|
2179
2416
|
taskGraphWithholdingReason(params) {
|
|
2180
2417
|
if (this.runAudienceAddsReader(params)) {
|
|
2181
2418
|
return 'a run with an audience';
|
|
2182
2419
|
}
|
|
2183
|
-
|
|
2420
|
+
const scope = this._runScope ?? this.validatedRunScope(params);
|
|
2421
|
+
if (scope?.SearchScopeIDs?.length) {
|
|
2422
|
+
return 'a run with host-assigned search scopes';
|
|
2423
|
+
}
|
|
2424
|
+
return ActionRunScopeIsBounded(scope) ? 'a tenant-scoped run' : null;
|
|
2184
2425
|
}
|
|
2185
2426
|
/** Whether this run withholds task graphs ({@link taskGraphWithholdingReason}). */
|
|
2186
2427
|
runWithholdsTaskGraphs(params) {
|
|
@@ -2206,12 +2447,34 @@ export class BaseAgent {
|
|
|
2206
2447
|
};
|
|
2207
2448
|
}
|
|
2208
2449
|
/**
|
|
2209
|
-
*
|
|
2210
|
-
*
|
|
2211
|
-
*
|
|
2450
|
+
* Whether this run withholds Handoff (`enableHandoff` off and the `handoff` response section hidden).
|
|
2451
|
+
* True when the run has a `parentRun` (sub-agents cannot transfer the conversation), has no
|
|
2452
|
+
* `conversationDetailId` (there is no conversation reply row to hand over), has no `handoffChain`
|
|
2453
|
+
* (the host does not carry out handoffs), or runs for an anonymous/widget guest without a trusted
|
|
2454
|
+
* host allow-list (`TrustReservedRunData === true` and `HostAllowedAgentIDs(params.data)` defined).
|
|
2455
|
+
*/
|
|
2456
|
+
runWithholdsHandoff(params) {
|
|
2457
|
+
const hasTrustedHostAllowList = params.TrustReservedRunData === true &&
|
|
2458
|
+
HostAllowedAgentIDs(params.data) !== undefined;
|
|
2459
|
+
const isUnscopedGuest = Boolean(params.contextUser?.IsMagicLinkAnonymous || params.contextUser?.WidgetGuestContext) &&
|
|
2460
|
+
!hasTrustedHostAllowList;
|
|
2461
|
+
return (Boolean(params.parentRun) ||
|
|
2462
|
+
!params.conversationDetailId ||
|
|
2463
|
+
!Array.isArray(params.handoffChain) ||
|
|
2464
|
+
isUnscopedGuest);
|
|
2465
|
+
}
|
|
2466
|
+
/**
|
|
2467
|
+
* What this run's prompt leaves out: task graphs ({@link taskGraphWithholdingReason}), handoff
|
|
2468
|
+
* ({@link runWithholdsHandoff}), and — when the audience adds a reader — the caller's own browser
|
|
2469
|
+
* and view (`CallerContext`): client tools run in the caller's browser and what they return reaches
|
|
2470
|
+
* the room, and the app context (`data.appContext`, with its `AdditionalContext`) is the caller's screen.
|
|
2212
2471
|
*/
|
|
2213
2472
|
promptWithholding(params) {
|
|
2214
|
-
return {
|
|
2473
|
+
return {
|
|
2474
|
+
TaskGraphs: this.runWithholdsTaskGraphs(params),
|
|
2475
|
+
Handoff: this.runWithholdsHandoff(params),
|
|
2476
|
+
CallerContext: this.runAudienceAddsReader(params)
|
|
2477
|
+
};
|
|
2215
2478
|
}
|
|
2216
2479
|
/**
|
|
2217
2480
|
* The client-tools and app-context prompt sections ({@link buildClientToolPromptSection}, {@link buildAppContextSection}),
|
|
@@ -2261,6 +2524,16 @@ export class BaseAgent {
|
|
|
2261
2524
|
: {};
|
|
2262
2525
|
return { ...promptParams, enableTaskGraphs: false, includeResponseTypeDefinition: { ...responseType, tasks: false } };
|
|
2263
2526
|
}
|
|
2527
|
+
/**
|
|
2528
|
+
* A copy of the agent-type prompt params with handoff withheld (`enableHandoff` off and the `handoff`
|
|
2529
|
+
* response section hidden). A copy, never a write: the input may be the process-wide cached base.
|
|
2530
|
+
*/
|
|
2531
|
+
withoutHandoff(promptParams) {
|
|
2532
|
+
const responseType = IsPlainObject(promptParams.includeResponseTypeDefinition)
|
|
2533
|
+
? promptParams.includeResponseTypeDefinition
|
|
2534
|
+
: {};
|
|
2535
|
+
return { ...promptParams, enableHandoff: false, includeResponseTypeDefinition: { ...responseType, handoff: false } };
|
|
2536
|
+
}
|
|
2264
2537
|
/**
|
|
2265
2538
|
* Why a session-driven (realtime / voice / bridge) run is refused, or null. A live session speaks and calls
|
|
2266
2539
|
* tools outside the gates that hold a run to its audience, so a run whose audience adds a reader is refused.
|
|
@@ -2338,9 +2611,8 @@ export class BaseAgent {
|
|
|
2338
2611
|
const modelResolution = await this.resolveRealtimeModel(params);
|
|
2339
2612
|
if (!modelResolution) {
|
|
2340
2613
|
const message = `Agent '${params.agent.Name}' is session-driven (Realtime) but no usable Realtime model could be ` +
|
|
2341
|
-
`resolved
|
|
2342
|
-
`
|
|
2343
|
-
`and model metadata are provisioned.`;
|
|
2614
|
+
`resolved: no active vendor of an active model of AIModelType 'Realtime' has a usable key and ` +
|
|
2615
|
+
`driver. ${RealtimeKeyFixHint(params.CredentialScope)}`;
|
|
2344
2616
|
this.logError(message, { agent: params.agent, category: 'RealtimeSession' });
|
|
2345
2617
|
return await this.createFailureResult(message, params.contextUser);
|
|
2346
2618
|
}
|
|
@@ -2462,9 +2734,9 @@ export class BaseAgent {
|
|
|
2462
2734
|
HostFraming: ReadTrimmedString(params.data?.realtimeHostFraming, 'realtimeHostFraming'),
|
|
2463
2735
|
PriorTranscript: ReadTrimmedString(params.data?.realtimePriorTranscript, 'realtimePriorTranscript'),
|
|
2464
2736
|
ConversationID: ReadTrimmedString(params.data?.conversationId, 'conversationId'),
|
|
2465
|
-
// The run's runtime API keys
|
|
2466
|
-
// the
|
|
2467
|
-
//
|
|
2737
|
+
// The run's runtime API keys. The session service resolves each vendor's key in a prompt's
|
|
2738
|
+
// order: the platform's MJ Credential for the vendor, then these keys, then the environment
|
|
2739
|
+
// ('RuntimeOnly' scope: these keys alone). Absent ⇒ platform credentials, then the environment.
|
|
2468
2740
|
// CreateBridgeRealtimeSession (the LiveKit / telephony factory) passes no apiKeys today.
|
|
2469
2741
|
APIKeys: params.apiKeys,
|
|
2470
2742
|
CredentialScope: params.CredentialScope,
|
|
@@ -2512,21 +2784,25 @@ export class BaseAgent {
|
|
|
2512
2784
|
// would dead-end whenever the top model lacked a key — e.g. a power-11 model with no env key
|
|
2513
2785
|
// (Inworld/AssemblyAI) outranking GPT Realtime — and surface "No usable Realtime model" even though
|
|
2514
2786
|
// a usable model exists. This mirrors the same fix in RealtimeClientSessionService.
|
|
2515
|
-
//
|
|
2516
|
-
//
|
|
2517
|
-
//
|
|
2787
|
+
// Keys resolve per vendor in the order a prompt's do: the platform's MJ Credential for the vendor
|
|
2788
|
+
// (AICredentialBindings on the model-vendor row, then the vendor, then the vendor's default
|
|
2789
|
+
// credential), then the run's key for the driver class, then the environment. A run whose
|
|
2790
|
+
// CredentialScope is 'RuntimeOnly' skips the platform credential and the environment.
|
|
2518
2791
|
//
|
|
2519
2792
|
// This also affects WHICH vendor runs the session, deliberately. Vendor selection walks
|
|
2520
|
-
// candidates by priority and takes the first whose key resolves, so
|
|
2521
|
-
//
|
|
2522
|
-
|
|
2523
|
-
const resolveAPIKey = MakeAIAPIKeyResolver(params.apiKeys, undefined, params.CredentialScope);
|
|
2793
|
+
// candidates by priority and takes the first whose key resolves, so a vendor reachable only
|
|
2794
|
+
// through a bound credential or the run's own key is still reached.
|
|
2795
|
+
const runThenEnvironment = MakeAIAPIKeyResolver(params.apiKeys, undefined, params.CredentialScope);
|
|
2524
2796
|
// The vendor follows whether the run will show an avatar, by the co-agent session prep's rule: a vendor that
|
|
2525
2797
|
// renders avatars (Vertex AI for Gemini 3.8 Live) only when it will, or when it is the only keyed vendor.
|
|
2526
2798
|
const showsAvatar = this.realtimeRunShowsAvatar(params);
|
|
2527
2799
|
const candidates = this.selectRealtimeModelCandidates(params.agent, overrideModelID);
|
|
2800
|
+
// Credential resolution is async and vendor selection is not, so every candidate's credentials
|
|
2801
|
+
// are resolved first; selection and the mint then read the same answer.
|
|
2802
|
+
const platform = await this.resolveRealtimePlatformCredentials(candidates.map(m => m.ID), params);
|
|
2528
2803
|
for (const model of candidates) {
|
|
2529
|
-
const
|
|
2804
|
+
const resolveAPIKey = platform.ResolverFor(model.ID, runThenEnvironment);
|
|
2805
|
+
const vendor = SelectRealtimeVendorForModel(model.ID, resolveAPIKey, params.CredentialScope);
|
|
2530
2806
|
const first = vendor ? this.instantiateRealtimeRunVendor(model.ID, vendor, resolveAPIKey) : null;
|
|
2531
2807
|
if (!vendor || !first) {
|
|
2532
2808
|
continue;
|
|
@@ -2555,6 +2831,17 @@ export class BaseAgent {
|
|
|
2555
2831
|
PhoneCall: params.data?.realtimePhoneCall === true,
|
|
2556
2832
|
});
|
|
2557
2833
|
}
|
|
2834
|
+
/**
|
|
2835
|
+
* The platform MJ Credentials of the candidate realtime models' vendors, read as the run's user.
|
|
2836
|
+
* **Overridable seam** so tests can supply credentials without a credential store. Under a
|
|
2837
|
+
* `'RuntimeOnly'` scope it resolves none.
|
|
2838
|
+
*
|
|
2839
|
+
* @param modelIDs The candidate `MJ: AI Models` row ids.
|
|
2840
|
+
* @param params The execution parameters (context user and credential scope).
|
|
2841
|
+
*/
|
|
2842
|
+
async resolveRealtimePlatformCredentials(modelIDs, params) {
|
|
2843
|
+
return ResolveRealtimePlatformCredentials(modelIDs, params.contextUser, params.CredentialScope);
|
|
2844
|
+
}
|
|
2558
2845
|
/**
|
|
2559
2846
|
* A vendor's realtime driver on its key, with the model and vendor identifiers a run resolves to; `null` when the
|
|
2560
2847
|
* key or the driver is missing.
|
|
@@ -2790,7 +3077,7 @@ export class BaseAgent {
|
|
|
2790
3077
|
*/
|
|
2791
3078
|
async assembleRealtimeContext(params) {
|
|
2792
3079
|
const lastUserMessage = params.conversationMessages.filter(m => m.role === 'user').pop();
|
|
2793
|
-
const inputText = typeof lastUserMessage?.content === 'string' ? lastUserMessage.content : '';
|
|
3080
|
+
const inputText = lastUserMessage?.metadata?.rawContent ?? (typeof lastUserMessage?.content === 'string' ? lastUserMessage.content : '');
|
|
2794
3081
|
const scratch = [];
|
|
2795
3082
|
const builder = new AgentMemoryContextBuilder();
|
|
2796
3083
|
await builder.InjectContextMemory(inputText, params.agent, params.userId || params.contextUser?.ID, params.companyId, params.contextUser, scratch, undefined, undefined, undefined, null, undefined, (message, verboseOnly) => this.logStatus(message, verboseOnly ?? false, params),
|
|
@@ -2844,6 +3131,7 @@ export class BaseAgent {
|
|
|
2844
3131
|
apiKeys: params.apiKeys,
|
|
2845
3132
|
CredentialScope: params.CredentialScope,
|
|
2846
3133
|
Audience: params.Audience, // the target answers the same people, so it is bounded the same way
|
|
3134
|
+
SearchScopeIDs: params.SearchScopeIDs, // and searches what the host assigned (never read from data)
|
|
2847
3135
|
data: params.data,
|
|
2848
3136
|
TrustReservedRunData: params.TrustReservedRunData, // the session's data, already vetted when it started
|
|
2849
3137
|
verbose: params.verbose,
|
|
@@ -3368,7 +3656,11 @@ export class BaseAgent {
|
|
|
3368
3656
|
// Prune and compact expired messages before executing the next step.
|
|
3369
3657
|
// Uses _promptTurnCount (not stepCount) so expiration is measured in prompt
|
|
3370
3658
|
// executions, not all steps (which include actions, loops, sub-agents, etc.)
|
|
3371
|
-
|
|
3659
|
+
// Rewriting an earlier turn costs the cached prefix, so unless the caller asked for it
|
|
3660
|
+
// (messageExpirationOverride) it waits until the window reaches the compaction trigger.
|
|
3661
|
+
if (params.messageExpirationOverride || this.isMidLoopCompactionThresholdReached(params)) {
|
|
3662
|
+
await this.pruneAndCompactExpiredMessages(params, this._promptTurnCount);
|
|
3663
|
+
}
|
|
3372
3664
|
// Execute the current step based on previous decision or initial prompt
|
|
3373
3665
|
this.logStatus(`🔄 Executing step ${stepCount + 1} for agent '${params.agent.Name}'`, true, params);
|
|
3374
3666
|
const nextStep = await this.executeNextStep(params, config, currentNextStep, stepCount);
|
|
@@ -3975,6 +4267,11 @@ export class BaseAgent {
|
|
|
3975
4267
|
}
|
|
3976
4268
|
}
|
|
3977
4269
|
}
|
|
4270
|
+
// Also convert rawContent in metadata when speaker attribution is active
|
|
4271
|
+
const agentMessage = message;
|
|
4272
|
+
if (typeof agentMessage.metadata?.rawContent === 'string') {
|
|
4273
|
+
agentMessage.metadata.rawContent = ConversationUtility.ToPlainText(agentMessage.metadata.rawContent);
|
|
4274
|
+
}
|
|
3978
4275
|
}
|
|
3979
4276
|
}
|
|
3980
4277
|
/**
|
|
@@ -4504,7 +4801,13 @@ export class BaseAgent {
|
|
|
4504
4801
|
const frameworkTools = control.NativeOnly
|
|
4505
4802
|
? BuildFrameworkTools(this.frameworkToolHost(params), this.frameworkToolAvailability(promptParams, params))
|
|
4506
4803
|
: [];
|
|
4507
|
-
const toolSet = BuildNativeToolSet(actionSet, subAgents, control, agentTools, frameworkTools)
|
|
4804
|
+
const toolSet = BuildNativeToolSet(actionSet, subAgents, control, agentTools, frameworkTools, (sa) => {
|
|
4805
|
+
const presetNames = (AIEngine.Instance.GetAgentConfigurationPresets?.(sa.ID, true) ?? []).map(p => p.Name);
|
|
4806
|
+
return {
|
|
4807
|
+
consultEnabled: this.isSubAgentConsultEnabledForSubAgent(params.agent, sa),
|
|
4808
|
+
...(presetNames.length > 0 ? { presetNames } : {})
|
|
4809
|
+
};
|
|
4810
|
+
});
|
|
4508
4811
|
if (control.NativeOnly && promptParams.data) {
|
|
4509
4812
|
// The template renders the tools-only prompt when this is set AND the runner resolves implicit control flow.
|
|
4510
4813
|
promptParams.data[NATIVE_ONLY_TEMPLATE_FLAG] = true;
|
|
@@ -4829,7 +5132,7 @@ export class BaseAgent {
|
|
|
4829
5132
|
const systemPrompt = config.systemPrompt;
|
|
4830
5133
|
const childPrompt = config.childPrompt;
|
|
4831
5134
|
// Gather context data (including runtime action changes)
|
|
4832
|
-
const promptTemplateData = await this.gatherPromptTemplateData(params.agent, params.contextUser, params.data, params.actionChanges, params.subAgentChanges, params.boundActionParams, this.promptWithholding(params));
|
|
5135
|
+
const promptTemplateData = await this.gatherPromptTemplateData(params.agent, params.contextUser, params.data, params.actionChanges, params.subAgentChanges, params.boundActionParams, this.promptWithholding(params), params.parentRun);
|
|
4833
5136
|
// Set up the hierarchical prompt execution
|
|
4834
5137
|
const promptParams = new AIPromptParams();
|
|
4835
5138
|
// Attribute the resulting AIPromptRun to this agent. Agents share agent-type-level system
|
|
@@ -4855,9 +5158,12 @@ export class BaseAgent {
|
|
|
4855
5158
|
// Last gate before the history goes back to the model: no tool call may be left dangling.
|
|
4856
5159
|
this.reconcileUnansweredToolCalls(params);
|
|
4857
5160
|
if (this.GetNativeControlConfig(params).CompactToolArguments) {
|
|
4858
|
-
const
|
|
4859
|
-
if (
|
|
4860
|
-
|
|
5161
|
+
const compactionBudget = this.resolveCompactionBudget(params, config);
|
|
5162
|
+
if (compactionBudget.BoundedBy === 'Default' || this.isMidLoopCompactionThresholdReached(params)) {
|
|
5163
|
+
const compacted = CompactAnsweredToolCallArguments(params.conversationMessages);
|
|
5164
|
+
if (compacted > 0) {
|
|
5165
|
+
this.logStatus(`[NativeTools] Compacted the large arguments of ${compacted} older tool call(s)`, true, params);
|
|
5166
|
+
}
|
|
4861
5167
|
}
|
|
4862
5168
|
}
|
|
4863
5169
|
promptParams.conversationMessages = params.conversationMessages;
|
|
@@ -5115,12 +5421,19 @@ export class BaseAgent {
|
|
|
5115
5421
|
* Keeps the system-prompt-and-tools fingerprint of the request just sent, for the next one. When
|
|
5116
5422
|
* it changed, the runner sent this request without replayed reasoning; the history drops it too,
|
|
5117
5423
|
* so no later request replays a block made under the old prompt or tools.
|
|
5424
|
+
*
|
|
5425
|
+
* A result with no fingerprint (a request that failed before or while it was sent, such as a
|
|
5426
|
+
* failover that ran out of candidates) leaves the baseline as it was. Clearing it would let the
|
|
5427
|
+
* next request skip the comparison and replay thinking made under a prompt or tools it no longer has.
|
|
5118
5428
|
*/
|
|
5119
5429
|
trackSentPrefix(params, promptResult) {
|
|
5120
5430
|
const sent = GetSentPrefixFingerprint(promptResult.chatResult);
|
|
5431
|
+
if (sent === undefined) {
|
|
5432
|
+
return;
|
|
5433
|
+
}
|
|
5121
5434
|
const previous = this._lastSentPrefix;
|
|
5122
5435
|
this._lastSentPrefix = sent;
|
|
5123
|
-
if (previous === undefined || sent ===
|
|
5436
|
+
if (previous === undefined || sent === previous || !this.replaysPrefixBoundReasoning()) {
|
|
5124
5437
|
return;
|
|
5125
5438
|
}
|
|
5126
5439
|
params.conversationMessages.forEach((m, i) => {
|
|
@@ -5199,8 +5512,10 @@ export class BaseAgent {
|
|
|
5199
5512
|
* declares native tools to a driver whose replayed reasoning needs the history before it
|
|
5200
5513
|
* unchanged is append-only too (see {@link ResolveAppendOnlyState}).
|
|
5201
5514
|
*
|
|
5202
|
-
* Decided ONCE per run. An explicit `trailingStateMode`
|
|
5203
|
-
*
|
|
5515
|
+
* Decided ONCE per run. An explicit `trailingStateMode` answers immediately, and so does a runtime
|
|
5516
|
+
* model override that names a vendor, or whose catalog says the cache is a byte-prefix cache.
|
|
5517
|
+
* Otherwise (no override, or one that names no vendor and whose catalog does not say yes) the
|
|
5518
|
+
* answer is frozen at the first model selection and reused for every
|
|
5204
5519
|
* later turn, so a failover to another vendor cannot flip the layout mid-run — a flip after turn 2
|
|
5205
5520
|
* would leave stale fragments in the history or, worse, restore the wrong turn's fragment. On turn 1,
|
|
5206
5521
|
* before any selection is known, the answer is replace-in-place: turn 1's fragment is kept and, if
|
|
@@ -5537,7 +5852,9 @@ export class BaseAgent {
|
|
|
5537
5852
|
// (schema defaults -> agent.AgentTypePromptParams -> runtime override) without mutating
|
|
5538
5853
|
// the caller's ExecuteAgentParams or params.data object.
|
|
5539
5854
|
this.logStatus(`🎯 Agent type '${agentType.Name}' determining next step`, true, params);
|
|
5540
|
-
const
|
|
5855
|
+
const stepParams = this._agentTypePromptParams &&
|
|
5856
|
+
this.AgentTypeInstance instanceof LoopAgentType &&
|
|
5857
|
+
params?.data?.__agentTypePromptParams === undefined
|
|
5541
5858
|
? {
|
|
5542
5859
|
...params,
|
|
5543
5860
|
data: {
|
|
@@ -5546,7 +5863,7 @@ export class BaseAgent {
|
|
|
5546
5863
|
},
|
|
5547
5864
|
}
|
|
5548
5865
|
: params;
|
|
5549
|
-
const nextStep = await this.AgentTypeInstance.DetermineNextStep(promptResult,
|
|
5866
|
+
const nextStep = await this.AgentTypeInstance.DetermineNextStep(promptResult, stepParams, currentPayload, this.AgentTypeState, this._nativeToolBindings);
|
|
5550
5867
|
return nextStep;
|
|
5551
5868
|
}
|
|
5552
5869
|
/**
|
|
@@ -5579,6 +5896,27 @@ export class BaseAgent {
|
|
|
5579
5896
|
// for next step, let's do a little quick validation here for sub-agent and actions to ensure requests are valid
|
|
5580
5897
|
switch (nextStep.step) {
|
|
5581
5898
|
case 'Sub-Agent':
|
|
5899
|
+
if (nextStep.taskGraph?.folded &&
|
|
5900
|
+
nextStep.subAgent?.name &&
|
|
5901
|
+
Boolean(GetTaskGraphSubmitter()) &&
|
|
5902
|
+
!this.resolveSubAgentByName(params, nextStep.subAgent.name)) {
|
|
5903
|
+
const activeAgentExists = AIEngine.Instance.Agents.some((a) => a.Status === 'Active' &&
|
|
5904
|
+
a.Name === nextStep.subAgent.name &&
|
|
5905
|
+
!UUIDsEqual(a.ID, params.agent.ID));
|
|
5906
|
+
if (activeAgentExists) {
|
|
5907
|
+
this.logStatus(`target is not a sub-agent of ${params.agent.Name}; submitting durably`, false, params);
|
|
5908
|
+
const unfolded = {
|
|
5909
|
+
...nextStep,
|
|
5910
|
+
step: 'Tasks',
|
|
5911
|
+
subAgent: undefined,
|
|
5912
|
+
taskGraph: {
|
|
5913
|
+
spec: nextStep.taskGraph.spec,
|
|
5914
|
+
folded: false,
|
|
5915
|
+
},
|
|
5916
|
+
};
|
|
5917
|
+
return this.validateTasksNextStep(params, unfolded, currentPayload, agentRun, currentStep);
|
|
5918
|
+
}
|
|
5919
|
+
}
|
|
5582
5920
|
return this.validateSubAgentNextStep(params, nextStep, currentPayload, agentRun, currentStep);
|
|
5583
5921
|
case 'Actions':
|
|
5584
5922
|
return this.validateActionsNextStep(params, nextStep, currentPayload, agentRun, currentStep);
|
|
@@ -5615,6 +5953,10 @@ export class BaseAgent {
|
|
|
5615
5953
|
// Retry step instead of hard-failing the run in executeTasksStep.
|
|
5616
5954
|
case 'Tasks':
|
|
5617
5955
|
return this.validateTasksNextStep(params, nextStep, currentPayload, agentRun, currentStep);
|
|
5956
|
+
// Type assertion required because 'Handoff' is not part of the BaseAgentNextStep step
|
|
5957
|
+
// union (transfer-and-detach — the terminal step it produces is 'Success').
|
|
5958
|
+
case 'Handoff':
|
|
5959
|
+
return this.validateHandoffNextStep(params, nextStep, currentPayload, agentRun, currentStep);
|
|
5618
5960
|
default:
|
|
5619
5961
|
// if we get here, the next step is not recognized, we can return a retry step
|
|
5620
5962
|
this.logError(`Invalid next step '${nextStep.step}' for agent '${params.agent.Name}'`, {
|
|
@@ -5655,7 +5997,7 @@ export class BaseAgent {
|
|
|
5655
5997
|
}
|
|
5656
5998
|
async validateSubAgentNextStep(params, nextStep, currentPayload, agentRun, currentStep) {
|
|
5657
5999
|
const curAgentSubAgents = this.getEffectiveSubAgentsForValidation(params.agent.ID);
|
|
5658
|
-
const allowFoldedTaskGraphTarget = nextStep.taskGraph?.folded === true;
|
|
6000
|
+
const allowFoldedTaskGraphTarget = nextStep.taskGraph?.folded === true && !GetTaskGraphSubmitter();
|
|
5659
6001
|
// Collect requested sub-agents. Prefer plural `subAgents` (parallel fan-out);
|
|
5660
6002
|
// fall back to singular `subAgent` for the classic single-sub-agent next step.
|
|
5661
6003
|
const requested = this.getRequestedSubAgents(nextStep);
|
|
@@ -5674,12 +6016,19 @@ export class BaseAgent {
|
|
|
5674
6016
|
};
|
|
5675
6017
|
}
|
|
5676
6018
|
// Validate each requested sub-agent: existence + user run permission + MaxExecutionsPerRun
|
|
6019
|
+
const seenResumeRunIds = new Set();
|
|
6020
|
+
const openConsultsBySubAgent = GroupByUUID(this._openSubAgentConsults.values(), c => c.subAgentId);
|
|
5677
6021
|
for (const req of requested) {
|
|
5678
6022
|
const name = req?.name;
|
|
5679
6023
|
const normalizedName = name?.trim().toLowerCase();
|
|
5680
|
-
const directSubAgent = curAgentSubAgents.find(a => a.Name.trim().toLowerCase() === normalizedName)
|
|
5681
|
-
|
|
5682
|
-
|
|
6024
|
+
const directSubAgent = curAgentSubAgents.find(a => a.Name.trim().toLowerCase() === normalizedName)
|
|
6025
|
+
?? (name ? this.matchNamedBySanitizedToolName(name, curAgentSubAgents, true).match : undefined);
|
|
6026
|
+
const activeCatalogAgents = allowFoldedTaskGraphTarget
|
|
6027
|
+
? AIEngine.Instance.Agents.filter(a => a.Status === 'Active')
|
|
6028
|
+
: [];
|
|
6029
|
+
const catalogSubAgent = !directSubAgent && allowFoldedTaskGraphTarget && name
|
|
6030
|
+
? (activeCatalogAgents.find(a => a.Name.trim().toLowerCase() === normalizedName)
|
|
6031
|
+
?? this.matchNamedBySanitizedToolName(name, activeCatalogAgents, true).match)
|
|
5683
6032
|
: undefined;
|
|
5684
6033
|
const subAgent = directSubAgent ?? catalogSubAgent;
|
|
5685
6034
|
const hasRunPermission = subAgent && catalogSubAgent && params.contextUser
|
|
@@ -5724,10 +6073,117 @@ export class BaseAgent {
|
|
|
5724
6073
|
};
|
|
5725
6074
|
}
|
|
5726
6075
|
}
|
|
6076
|
+
if (req.resumeRunId != null && req.resumeRunId !== '') {
|
|
6077
|
+
const openForSubAgent = openConsultsBySubAgent.Get(subAgent.ID) ?? [];
|
|
6078
|
+
const matchingConsult = IsValidUUID(req.resumeRunId)
|
|
6079
|
+
? IndexByUUID(openForSubAgent, c => c.childRunId).Get(req.resumeRunId)
|
|
6080
|
+
: undefined;
|
|
6081
|
+
if (!matchingConsult) {
|
|
6082
|
+
const openIds = openForSubAgent.length > 0
|
|
6083
|
+
? openForSubAgent.map(c => c.childRunId).join(', ')
|
|
6084
|
+
: 'none';
|
|
6085
|
+
const errorMessage = `Invalid resumeRunId '${req.resumeRunId}' for sub-agent '${subAgent.Name}'. Open consult run IDs for '${subAgent.Name}': ${openIds}`;
|
|
6086
|
+
this.logError(errorMessage, {
|
|
6087
|
+
agent: params.agent,
|
|
6088
|
+
category: 'SubAgentExecution',
|
|
6089
|
+
metadata: {
|
|
6090
|
+
subAgentName: name,
|
|
6091
|
+
resumeRunId: req.resumeRunId,
|
|
6092
|
+
openConsultIds: openIds
|
|
6093
|
+
}
|
|
6094
|
+
});
|
|
6095
|
+
if (nextStep.step !== 'Retry') {
|
|
6096
|
+
this._generalValidationRetryCount++;
|
|
6097
|
+
}
|
|
6098
|
+
return {
|
|
6099
|
+
step: 'Retry',
|
|
6100
|
+
terminate: false,
|
|
6101
|
+
errorMessage
|
|
6102
|
+
};
|
|
6103
|
+
}
|
|
6104
|
+
const normalizedResumeId = matchingConsult.childRunId.trim().toLowerCase();
|
|
6105
|
+
if (seenResumeRunIds.has(normalizedResumeId)) {
|
|
6106
|
+
const errorMessage = `resumeRunId '${req.resumeRunId}' is used more than once`;
|
|
6107
|
+
this.logError(errorMessage, {
|
|
6108
|
+
agent: params.agent,
|
|
6109
|
+
category: 'SubAgentExecution',
|
|
6110
|
+
metadata: {
|
|
6111
|
+
subAgentName: name,
|
|
6112
|
+
resumeRunId: req.resumeRunId
|
|
6113
|
+
}
|
|
6114
|
+
});
|
|
6115
|
+
if (nextStep.step !== 'Retry') {
|
|
6116
|
+
this._generalValidationRetryCount++;
|
|
6117
|
+
}
|
|
6118
|
+
return {
|
|
6119
|
+
step: 'Retry',
|
|
6120
|
+
terminate: false,
|
|
6121
|
+
errorMessage
|
|
6122
|
+
};
|
|
6123
|
+
}
|
|
6124
|
+
seenResumeRunIds.add(normalizedResumeId);
|
|
6125
|
+
}
|
|
6126
|
+
if (req.presetName != null && req.presetName.trim() !== '') {
|
|
6127
|
+
const matchedPreset = AIEngine.Instance.FindActiveAgentConfigurationPreset(subAgent.ID, req.presetName);
|
|
6128
|
+
if (!matchedPreset) {
|
|
6129
|
+
const availablePresets = AIEngine.Instance.GetAgentConfigurationPresets(subAgent.ID, true)
|
|
6130
|
+
.map(p => p.Name);
|
|
6131
|
+
const availableList = availablePresets.length > 0 ? availablePresets.join(', ') : 'none';
|
|
6132
|
+
const errorMessage = `Sub-agent '${subAgent.Name}' has no preset '${req.presetName}'. Available: ${availableList}.`;
|
|
6133
|
+
this.logError(errorMessage, {
|
|
6134
|
+
agent: params.agent,
|
|
6135
|
+
category: 'SubAgentExecution',
|
|
6136
|
+
metadata: {
|
|
6137
|
+
subAgentName: name,
|
|
6138
|
+
presetName: req.presetName,
|
|
6139
|
+
availablePresets: availableList
|
|
6140
|
+
}
|
|
6141
|
+
});
|
|
6142
|
+
if (nextStep.step !== 'Retry') {
|
|
6143
|
+
this._generalValidationRetryCount++;
|
|
6144
|
+
}
|
|
6145
|
+
return {
|
|
6146
|
+
...nextStep,
|
|
6147
|
+
step: 'Retry',
|
|
6148
|
+
terminate: false,
|
|
6149
|
+
errorMessage
|
|
6150
|
+
};
|
|
6151
|
+
}
|
|
6152
|
+
}
|
|
5727
6153
|
}
|
|
5728
6154
|
// All requested sub-agents are valid
|
|
5729
6155
|
return nextStep;
|
|
5730
6156
|
}
|
|
6157
|
+
/**
|
|
6158
|
+
* Strips an optional `delegate_to_` native sub-agent tool prefix when a model running
|
|
6159
|
+
* with native tool calling references a sub-agent by its declared tool name inside an
|
|
6160
|
+
* envelope primitive (`Sub-Agent`, `ForEach`, `While`, or `Tasks`).
|
|
6161
|
+
*/
|
|
6162
|
+
stripSubAgentToolPrefix(rawName) {
|
|
6163
|
+
const trimmed = rawName.trim();
|
|
6164
|
+
return trimmed.toLowerCase().startsWith(SUB_AGENT_TOOL_PREFIX)
|
|
6165
|
+
? trimmed.slice(SUB_AGENT_TOOL_PREFIX.length)
|
|
6166
|
+
: trimmed;
|
|
6167
|
+
}
|
|
6168
|
+
/**
|
|
6169
|
+
* Resolves a unique entity from `pool` whose sanitized native tool name matches `rawName`.
|
|
6170
|
+
* Returns `{ ambiguous }` when multiple entities collide on the same sanitized name.
|
|
6171
|
+
*/
|
|
6172
|
+
matchNamedBySanitizedToolName(rawName, pool, stripSubAgentPrefix = false) {
|
|
6173
|
+
const candidate = stripSubAgentPrefix ? this.stripSubAgentToolPrefix(rawName) : rawName.trim();
|
|
6174
|
+
const sanitized = SanitizeToolName(candidate);
|
|
6175
|
+
if (!sanitized) {
|
|
6176
|
+
return {};
|
|
6177
|
+
}
|
|
6178
|
+
const matches = pool.filter(item => item.Name && SanitizeToolName(item.Name) === sanitized);
|
|
6179
|
+
if (matches.length === 1) {
|
|
6180
|
+
return { match: matches[0] };
|
|
6181
|
+
}
|
|
6182
|
+
if (matches.length > 1) {
|
|
6183
|
+
return { ambiguous: matches };
|
|
6184
|
+
}
|
|
6185
|
+
return {};
|
|
6186
|
+
}
|
|
5731
6187
|
/**
|
|
5732
6188
|
* Builds a compact hint listing the current user's permitted runnable agents when a
|
|
5733
6189
|
* task-graph or folded sub-agent step references an unknown or inaccessible agent name.
|
|
@@ -5747,11 +6203,9 @@ export class BaseAgent {
|
|
|
5747
6203
|
* Validates a `'Tasks'` next step before `executeTasksStep` submits the graph.
|
|
5748
6204
|
*
|
|
5749
6205
|
* Verifies that every referenced `Agent` (including `ForEach`/`While` loop sub-agents) is
|
|
5750
|
-
* active and runnable by `params.contextUser`, and that every referenced `Action`
|
|
5751
|
-
*
|
|
5752
|
-
* `
|
|
5753
|
-
* terminate the entire agent run as `Failed`. Never reveals whether an invalid agent name was
|
|
5754
|
-
* nonexistent versus restricted by permissions.
|
|
6206
|
+
* active and runnable by `params.contextUser`, and that every referenced `Action` (including
|
|
6207
|
+
* multi-step `steps[]` loop bodies) is active. Accepts sanitized native tool names
|
|
6208
|
+
* (`calculate_expression`, `delegate_to_query_builder`) and canonicalizes them in place.
|
|
5755
6209
|
*/
|
|
5756
6210
|
async validateTasksNextStep(params, nextStep, _currentPayload, _agentRun, _currentStep) {
|
|
5757
6211
|
const spec = nextStep.taskGraph?.spec;
|
|
@@ -5764,16 +6218,27 @@ export class BaseAgent {
|
|
|
5764
6218
|
};
|
|
5765
6219
|
const extractNodeActionNames = (node) => {
|
|
5766
6220
|
const loopOp = ConfigOf(node, 'ForEach') ?? ConfigOf(node, 'While');
|
|
5767
|
-
return [
|
|
6221
|
+
return [
|
|
6222
|
+
ConfigOf(node, 'Action')?.actionName,
|
|
6223
|
+
loopOp?.action?.name,
|
|
6224
|
+
...(loopOp?.steps?.map((s) => s.name) ?? [])
|
|
6225
|
+
].filter((n) => typeof n === 'string' && n.trim().length > 0);
|
|
5768
6226
|
};
|
|
5769
6227
|
const referencedAgents = [...new Set(spec.tasks.flatMap(extractNodeAgentNames))];
|
|
5770
6228
|
const referencedActions = [...new Set(spec.tasks.flatMap(extractNodeActionNames))];
|
|
6229
|
+
const hostAllowedIds = HostAllowedAgentIDs(params.data);
|
|
6230
|
+
const disallowedAgents = [];
|
|
5771
6231
|
const invalidAgents = [];
|
|
5772
|
-
const
|
|
5773
|
-
if (referencedAgents.length > 0 &&
|
|
6232
|
+
const activeAgents = (AIEngine.Instance?.Agents ?? []).filter(a => a.Status === 'Active');
|
|
6233
|
+
if (referencedAgents.length > 0 && (activeAgents.length > 0 || hostAllowedIds !== undefined)) {
|
|
5774
6234
|
for (const agentName of referencedAgents) {
|
|
5775
6235
|
const normalized = agentName.trim().toLowerCase();
|
|
5776
|
-
const matched =
|
|
6236
|
+
const matched = activeAgents.find(a => a.Name?.trim().toLowerCase() === normalized)
|
|
6237
|
+
?? this.matchNamedBySanitizedToolName(agentName, activeAgents, true).match;
|
|
6238
|
+
if (hostAllowedIds !== undefined && (!matched || KeepHostAllowedAgents([matched], hostAllowedIds).length === 0)) {
|
|
6239
|
+
disallowedAgents.push(agentName);
|
|
6240
|
+
continue;
|
|
6241
|
+
}
|
|
5777
6242
|
const permitted = matched
|
|
5778
6243
|
? params.contextUser
|
|
5779
6244
|
? await AIAgentPermissionHelper.HasPermission(matched.ID, params.contextUser, 'run')
|
|
@@ -5784,12 +6249,31 @@ export class BaseAgent {
|
|
|
5784
6249
|
}
|
|
5785
6250
|
}
|
|
5786
6251
|
}
|
|
6252
|
+
if (disallowedAgents.length > 0) {
|
|
6253
|
+
const subject = disallowedAgents.join(', ');
|
|
6254
|
+
const refusalMessage = disallowedAgents.length === 1
|
|
6255
|
+
? `${subject} isn't available in this chat, so it didn't run.`
|
|
6256
|
+
: `${subject} aren't available in this chat, so they didn't run.`;
|
|
6257
|
+
this.logError(refusalMessage, {
|
|
6258
|
+
agent: params.agent,
|
|
6259
|
+
category: 'NextStepValidation'
|
|
6260
|
+
});
|
|
6261
|
+
return {
|
|
6262
|
+
step: 'Failed',
|
|
6263
|
+
terminate: true,
|
|
6264
|
+
message: refusalMessage,
|
|
6265
|
+
errorMessage: refusalMessage,
|
|
6266
|
+
previousPayload: nextStep.previousPayload,
|
|
6267
|
+
newPayload: nextStep.newPayload || nextStep.previousPayload
|
|
6268
|
+
};
|
|
6269
|
+
}
|
|
5787
6270
|
const invalidActions = [];
|
|
5788
|
-
const
|
|
5789
|
-
if (referencedActions.length > 0 &&
|
|
6271
|
+
const activeActions = (ActionEngineServer.Instance?.Actions ?? []).filter(act => act.Status === 'Active');
|
|
6272
|
+
if (referencedActions.length > 0 && activeActions.length > 0) {
|
|
5790
6273
|
for (const actionName of referencedActions) {
|
|
5791
6274
|
const normalized = actionName.trim().toLowerCase();
|
|
5792
|
-
const matched =
|
|
6275
|
+
const matched = activeActions.find(act => act.Name?.trim().toLowerCase() === normalized)
|
|
6276
|
+
?? this.matchNamedBySanitizedToolName(actionName, activeActions).match;
|
|
5793
6277
|
if (!matched) {
|
|
5794
6278
|
invalidActions.push(actionName);
|
|
5795
6279
|
}
|
|
@@ -5832,28 +6316,16 @@ export class BaseAgent {
|
|
|
5832
6316
|
*/
|
|
5833
6317
|
async validateActionsNextStep(params, nextStep, currentPayload, agentRun, currentStep) {
|
|
5834
6318
|
// Use effective actions which includes runtime action changes (populated in gatherPromptTemplateData)
|
|
5835
|
-
//
|
|
6319
|
+
// Falls back to database-configured actions only when the list was never computed for this run
|
|
5836
6320
|
const effectiveActions = this.getEffectiveActionsForValidation(params.agent.ID);
|
|
5837
6321
|
// Also get the database-configured agent actions for MaxExecutionsPerRun lookup
|
|
5838
6322
|
const dbAgentActions = AIEngine.Instance.AgentActions.filter(aa => UUIDsEqual(aa.AgentID, params.agent.ID) && aa.Status === 'Active');
|
|
6323
|
+
const resolvedByAction = new Map();
|
|
5839
6324
|
const missingActions = nextStep.actions?.filter(action => {
|
|
5840
|
-
const
|
|
5841
|
-
|
|
5842
|
-
|
|
5843
|
-
|
|
5844
|
-
return false; // Found exact match, not missing
|
|
5845
|
-
// Fallback: Try CONTAINS search for partial matches
|
|
5846
|
-
const containsMatches = effectiveActions.filter(a => a.Name.trim().toLowerCase().includes(actionName));
|
|
5847
|
-
if (containsMatches.length === 1) {
|
|
5848
|
-
// Exactly one partial match - use it and update action name
|
|
5849
|
-
const correctedName = containsMatches[0].Name;
|
|
5850
|
-
this.logStatus(`Action name fuzzy matched: '${action.name}' → '${correctedName}'`, true, params);
|
|
5851
|
-
action.name = correctedName; // Update to correct full name
|
|
5852
|
-
return false; // Found via contains, not missing
|
|
5853
|
-
}
|
|
5854
|
-
// No matches or ambiguous (multiple matches) - it's missing
|
|
5855
|
-
if (containsMatches.length > 1) {
|
|
5856
|
-
this.logStatus(`Ambiguous action name '${action.name}' matches ${containsMatches.length} actions: ${containsMatches.map(a => a.Name).join(', ')}`, true, params);
|
|
6325
|
+
const matched = this.resolveActionEntityForAgent(action.name, effectiveActions, params, true);
|
|
6326
|
+
if (matched) {
|
|
6327
|
+
resolvedByAction.set(action, matched);
|
|
6328
|
+
return false;
|
|
5857
6329
|
}
|
|
5858
6330
|
return true;
|
|
5859
6331
|
});
|
|
@@ -5879,7 +6351,8 @@ export class BaseAgent {
|
|
|
5879
6351
|
if (nextStep.actions) {
|
|
5880
6352
|
const violatedActions = [];
|
|
5881
6353
|
for (const action of nextStep.actions) {
|
|
5882
|
-
const actionEntity =
|
|
6354
|
+
const actionEntity = resolvedByAction.get(action)
|
|
6355
|
+
?? effectiveActions.find(a => a.Name.trim().toLowerCase() === action.name.trim().toLowerCase());
|
|
5883
6356
|
if (!actionEntity)
|
|
5884
6357
|
continue;
|
|
5885
6358
|
// Check for limit from database-configured agent action
|
|
@@ -5925,7 +6398,8 @@ export class BaseAgent {
|
|
|
5925
6398
|
}
|
|
5926
6399
|
/**
|
|
5927
6400
|
* Gets the effective actions for validation, using runtime changes if available.
|
|
5928
|
-
* Falls back to database-configured actions
|
|
6401
|
+
* Falls back to database-configured actions only when the list was never computed for this run;
|
|
6402
|
+
* a computed empty list (a host's actionChanges removed every action) is returned as-is.
|
|
5929
6403
|
*
|
|
5930
6404
|
* @param agentId - The ID of the agent to get actions for
|
|
5931
6405
|
* @returns Array of effective actions available to the agent
|
|
@@ -5933,16 +6407,172 @@ export class BaseAgent {
|
|
|
5933
6407
|
* @since 2.123.0
|
|
5934
6408
|
*/
|
|
5935
6409
|
getEffectiveActionsForValidation(agentId) {
|
|
5936
|
-
if (this._effectiveActions.length > 0) {
|
|
6410
|
+
if (this._effectiveCatalogComputed || this._effectiveActions.length > 0) {
|
|
5937
6411
|
return this._effectiveActions;
|
|
5938
6412
|
}
|
|
5939
6413
|
// Fallback: compute from database configuration
|
|
5940
6414
|
const agentActions = AIEngine.Instance.AgentActions.filter(aa => UUIDsEqual(aa.AgentID, agentId) && aa.Status === 'Active');
|
|
5941
6415
|
return ActionEngineServer.Instance.Actions.filter(a => agentActions.some(aa => UUIDsEqual(aa.ActionID, a.ID)) && a.Status === 'Active');
|
|
5942
6416
|
}
|
|
6417
|
+
/**
|
|
6418
|
+
* Returns active actions referenced directly by an agent's Flow steps (`AIAgentStep.ActionID`
|
|
6419
|
+
* plus any `steps[].name` inside a `ForEach`/`While` Flow step's `Configuration` JSON).
|
|
6420
|
+
* Flow agents bind actions on `AIAgentStep` rather than `AIAgentAction`, so in-run Flow loops
|
|
6421
|
+
* need these actions in scope alongside {@link getEffectiveActionsForValidation}.
|
|
6422
|
+
*/
|
|
6423
|
+
getFlowStepActions(agentId) {
|
|
6424
|
+
const allActions = ActionEngineServer.Instance?.Actions;
|
|
6425
|
+
if (!Array.isArray(allActions) || allActions.length === 0 || !agentId) {
|
|
6426
|
+
return [];
|
|
6427
|
+
}
|
|
6428
|
+
const agentSteps = AIEngine.Instance.GetAgentSteps?.(agentId) || [];
|
|
6429
|
+
if (agentSteps.length === 0) {
|
|
6430
|
+
return [];
|
|
6431
|
+
}
|
|
6432
|
+
const stepActionIds = new UUIDSet(agentSteps.map((s) => s.ActionID).filter((id) => typeof id === 'string' && id.length > 0));
|
|
6433
|
+
const stepActionNamesLower = new Set();
|
|
6434
|
+
const stepActionNamesSanitized = new Set();
|
|
6435
|
+
for (const s of agentSteps) {
|
|
6436
|
+
if (!s.Configuration)
|
|
6437
|
+
continue;
|
|
6438
|
+
try {
|
|
6439
|
+
const cfg = JSON.parse(s.Configuration);
|
|
6440
|
+
if (Array.isArray(cfg?.steps)) {
|
|
6441
|
+
for (const bodyStep of cfg.steps) {
|
|
6442
|
+
const raw = bodyStep?.name?.trim();
|
|
6443
|
+
if (raw) {
|
|
6444
|
+
stepActionNamesLower.add(raw.toLowerCase());
|
|
6445
|
+
const san = SanitizeToolName(raw);
|
|
6446
|
+
if (san)
|
|
6447
|
+
stepActionNamesSanitized.add(san);
|
|
6448
|
+
}
|
|
6449
|
+
}
|
|
6450
|
+
}
|
|
6451
|
+
}
|
|
6452
|
+
catch {
|
|
6453
|
+
// Malformed step configuration JSON is reported by FlowAgentType when that step runs.
|
|
6454
|
+
}
|
|
6455
|
+
}
|
|
6456
|
+
return allActions.filter((a) => a.Status !== 'Disabled' &&
|
|
6457
|
+
(stepActionIds.Has(a.ID) ||
|
|
6458
|
+
stepActionNamesLower.has(a.Name.trim().toLowerCase()) ||
|
|
6459
|
+
stepActionNamesSanitized.has(SanitizeToolName(a.Name))));
|
|
6460
|
+
}
|
|
6461
|
+
/**
|
|
6462
|
+
* Combines {@link getEffectiveActionsForValidation} with {@link getFlowStepActions} (deduplicated
|
|
6463
|
+
* by `ID`) so both Loop agents (strictly `AIAgentAction` / `_effectiveActions`) and Flow agents
|
|
6464
|
+
* (`AIAgentStep` / `Configuration.steps[]`) resolve permitted actions consistently.
|
|
6465
|
+
*/
|
|
6466
|
+
getAvailableActionsForAgent(agentId) {
|
|
6467
|
+
const effective = this.getEffectiveActionsForValidation(agentId);
|
|
6468
|
+
const flowActions = this.getFlowStepActions(agentId);
|
|
6469
|
+
if (flowActions.length === 0) {
|
|
6470
|
+
return effective;
|
|
6471
|
+
}
|
|
6472
|
+
const seen = new UUIDSet(effective.map((a) => a.ID));
|
|
6473
|
+
const combined = [...effective];
|
|
6474
|
+
for (const fa of flowActions) {
|
|
6475
|
+
if (!seen.Has(fa.ID)) {
|
|
6476
|
+
seen.Add(fa.ID);
|
|
6477
|
+
combined.push(fa);
|
|
6478
|
+
}
|
|
6479
|
+
}
|
|
6480
|
+
return combined;
|
|
6481
|
+
}
|
|
6482
|
+
/**
|
|
6483
|
+
* Resolves an action name against `pool` without mutating caller objects:
|
|
6484
|
+
* 1) exact case-insensitive match, 2) unambiguous sanitized native tool-name match,
|
|
6485
|
+
* 3) unambiguous CONTAINS partial match.
|
|
6486
|
+
*/
|
|
6487
|
+
resolveActionEntityForAgent(rawName, pool, params, logMatches = false) {
|
|
6488
|
+
const trimmedLower = rawName.trim().toLowerCase();
|
|
6489
|
+
if (!trimmedLower) {
|
|
6490
|
+
return undefined;
|
|
6491
|
+
}
|
|
6492
|
+
const exact = pool.find((a) => a.Name.trim().toLowerCase() === trimmedLower);
|
|
6493
|
+
if (exact) {
|
|
6494
|
+
return exact;
|
|
6495
|
+
}
|
|
6496
|
+
const sanitizedMatch = this.matchNamedBySanitizedToolName(rawName, pool);
|
|
6497
|
+
if (sanitizedMatch.match) {
|
|
6498
|
+
if (logMatches && params) {
|
|
6499
|
+
this.logStatus(`Action native tool name matched: '${rawName}' → '${sanitizedMatch.match.Name}'`, true, params);
|
|
6500
|
+
}
|
|
6501
|
+
return sanitizedMatch.match;
|
|
6502
|
+
}
|
|
6503
|
+
if (sanitizedMatch.ambiguous) {
|
|
6504
|
+
if (logMatches && params) {
|
|
6505
|
+
this.logStatus(`Ambiguous action tool name '${rawName}' matches ${sanitizedMatch.ambiguous.length} actions: ${sanitizedMatch.ambiguous.map((a) => a.Name).join(', ')}`, true, params);
|
|
6506
|
+
}
|
|
6507
|
+
return undefined;
|
|
6508
|
+
}
|
|
6509
|
+
const containsMatches = pool.filter((a) => a.Name.trim().toLowerCase().includes(trimmedLower));
|
|
6510
|
+
if (containsMatches.length === 1) {
|
|
6511
|
+
if (logMatches && params) {
|
|
6512
|
+
this.logStatus(`Action name fuzzy matched: '${rawName}' → '${containsMatches[0].Name}'`, true, params);
|
|
6513
|
+
}
|
|
6514
|
+
return containsMatches[0];
|
|
6515
|
+
}
|
|
6516
|
+
if (containsMatches.length > 1 && logMatches && params) {
|
|
6517
|
+
this.logStatus(`Ambiguous action name '${rawName}' matches ${containsMatches.length} actions: ${containsMatches.map((a) => a.Name).join(', ')}`, true, params);
|
|
6518
|
+
}
|
|
6519
|
+
return undefined;
|
|
6520
|
+
}
|
|
6521
|
+
/**
|
|
6522
|
+
* Returns a deep-cloned `TaskGraphSpec` with sanitized native tool names (`calculate_expression`,
|
|
6523
|
+
* `delegate_to_query_builder`) canonicalized to exact metadata names before durable submission,
|
|
6524
|
+
* without mutating the caller's `spec`.
|
|
6525
|
+
*/
|
|
6526
|
+
canonicalizeTaskGraphSpec(spec) {
|
|
6527
|
+
const cloned = this.cloneSubAgentPayload(spec);
|
|
6528
|
+
const activeAgents = (AIEngine.Instance?.Agents ?? []).filter((a) => a.Status === 'Active');
|
|
6529
|
+
const activeActions = (ActionEngineServer.Instance?.Actions ?? []).filter((act) => act.Status === 'Active');
|
|
6530
|
+
const resolveAgent = (name) => {
|
|
6531
|
+
if (!name)
|
|
6532
|
+
return name;
|
|
6533
|
+
const lower = name.trim().toLowerCase();
|
|
6534
|
+
const found = activeAgents.find((a) => a.Name?.trim().toLowerCase() === lower)
|
|
6535
|
+
?? this.matchNamedBySanitizedToolName(name, activeAgents, true).match;
|
|
6536
|
+
return found?.Name ?? name;
|
|
6537
|
+
};
|
|
6538
|
+
const resolveAction = (name) => {
|
|
6539
|
+
if (!name)
|
|
6540
|
+
return name;
|
|
6541
|
+
const lower = name.trim().toLowerCase();
|
|
6542
|
+
const found = activeActions.find((act) => act.Name?.trim().toLowerCase() === lower)
|
|
6543
|
+
?? this.matchNamedBySanitizedToolName(name, activeActions).match;
|
|
6544
|
+
return found?.Name ?? name;
|
|
6545
|
+
};
|
|
6546
|
+
for (const node of cloned.tasks ?? []) {
|
|
6547
|
+
const agentCfg = ConfigOf(node, 'Agent');
|
|
6548
|
+
if (agentCfg?.agentName) {
|
|
6549
|
+
agentCfg.agentName = resolveAgent(agentCfg.agentName);
|
|
6550
|
+
}
|
|
6551
|
+
const actionCfg = ConfigOf(node, 'Action');
|
|
6552
|
+
if (actionCfg?.actionName) {
|
|
6553
|
+
actionCfg.actionName = resolveAction(actionCfg.actionName);
|
|
6554
|
+
}
|
|
6555
|
+
const loopOp = ConfigOf(node, 'ForEach') ?? ConfigOf(node, 'While');
|
|
6556
|
+
if (loopOp?.subAgent?.name) {
|
|
6557
|
+
loopOp.subAgent.name = resolveAgent(loopOp.subAgent.name);
|
|
6558
|
+
}
|
|
6559
|
+
if (loopOp?.action?.name) {
|
|
6560
|
+
loopOp.action.name = resolveAction(loopOp.action.name);
|
|
6561
|
+
}
|
|
6562
|
+
if (Array.isArray(loopOp?.steps)) {
|
|
6563
|
+
for (const step of loopOp.steps) {
|
|
6564
|
+
if (step.name) {
|
|
6565
|
+
step.name = resolveAction(step.name);
|
|
6566
|
+
}
|
|
6567
|
+
}
|
|
6568
|
+
}
|
|
6569
|
+
}
|
|
6570
|
+
return cloned;
|
|
6571
|
+
}
|
|
5943
6572
|
/**
|
|
5944
6573
|
* Gets the effective sub-agents for validation, using runtime subAgentChanges if available.
|
|
5945
|
-
* Falls back to the database-configured relationship set
|
|
6574
|
+
* Falls back to the database-configured relationship set only when the list was never computed
|
|
6575
|
+
* for this run; a computed empty list is returned as-is.
|
|
5946
6576
|
* Mirrors {@link getEffectiveActionsForValidation}.
|
|
5947
6577
|
*
|
|
5948
6578
|
* @param agentId - The ID of the agent to get sub-agents for
|
|
@@ -5950,7 +6580,7 @@ export class BaseAgent {
|
|
|
5950
6580
|
* @protected
|
|
5951
6581
|
*/
|
|
5952
6582
|
getEffectiveSubAgentsForValidation(agentId) {
|
|
5953
|
-
if (this._effectiveSubAgents.length > 0) {
|
|
6583
|
+
if (this._effectiveCatalogComputed || this._effectiveSubAgents.length > 0) {
|
|
5954
6584
|
return this._effectiveSubAgents;
|
|
5955
6585
|
}
|
|
5956
6586
|
// Fallback: compute from database configuration (ParentID children + AgentRelationships)
|
|
@@ -6058,34 +6688,112 @@ export class BaseAgent {
|
|
|
6058
6688
|
return nextStep;
|
|
6059
6689
|
}
|
|
6060
6690
|
/**
|
|
6061
|
-
* Validates
|
|
6062
|
-
*
|
|
6063
|
-
* @
|
|
6064
|
-
*
|
|
6065
|
-
*
|
|
6691
|
+
* Validates a `'Handoff'` next step: re-checks the runtime withholding conditions (sub-agent run,
|
|
6692
|
+
* missing `conversationDetailId`, or missing `handoffChain`) and validates the requested target
|
|
6693
|
+
* via {@link ResolveHandoffTarget} (Active status, `'view'` and `'run'` permissions, direct
|
|
6694
|
+
* discoverability, host allow-list, cycle check, and hop limit). On refusal, writes a Failed
|
|
6695
|
+
* `'Handoff'` step and returns a `'Retry'` step naming up to 20 candidate agents; on approval,
|
|
6696
|
+
* stores the resolved target ID and name for {@link executeHandoffStep}.
|
|
6697
|
+
*
|
|
6698
|
+
* @protected
|
|
6066
6699
|
*/
|
|
6067
|
-
async
|
|
6068
|
-
|
|
6069
|
-
const minViolations = await this.checkMinimumExecutionRequirements(params.agent, agentRun);
|
|
6070
|
-
if (minViolations.length > 0) {
|
|
6071
|
-
const violationMessage = `Minimum execution requirements not met:\n${minViolations.join('\n')}`;
|
|
6072
|
-
this.logError(violationMessage, {
|
|
6073
|
-
agent: params.agent,
|
|
6074
|
-
category: 'MinimumExecutionValidation'
|
|
6075
|
-
});
|
|
6076
|
-
// Increment validation retry count since we're changing to Retry
|
|
6700
|
+
async validateHandoffNextStep(params, nextStep, _currentPayload, _agentRun, _currentStep) {
|
|
6701
|
+
if (this.runWithholdsHandoff(params)) {
|
|
6077
6702
|
if (nextStep.step !== 'Retry') {
|
|
6078
6703
|
this._generalValidationRetryCount++;
|
|
6079
6704
|
}
|
|
6080
|
-
// A native complete_task keeps its turn and call id, so the refusal answers that call.
|
|
6081
6705
|
return {
|
|
6082
6706
|
step: 'Retry',
|
|
6083
6707
|
terminate: false,
|
|
6084
|
-
|
|
6085
|
-
|
|
6708
|
+
message: 'Handoff is not available here, so nextStep.type must never be "Handoff". ' +
|
|
6709
|
+
'Answer directly, or use nextStep.type "Sub-Agent" or "Actions" instead.',
|
|
6710
|
+
errorMessage: 'Handoff is not available on this run'
|
|
6086
6711
|
};
|
|
6087
6712
|
}
|
|
6088
|
-
|
|
6713
|
+
const requestedName = nextStep.handoff?.agentName ?? '';
|
|
6714
|
+
const brief = nextStep.handoff?.brief ?? '';
|
|
6715
|
+
const reason = nextStep.handoff?.reason ?? '';
|
|
6716
|
+
const data = WithAgentRunDataTrustApplied(params).Params.data;
|
|
6717
|
+
const resolution = await ResolveHandoffTarget({
|
|
6718
|
+
AgentName: requestedName,
|
|
6719
|
+
SourceAgentID: params.agent.ID,
|
|
6720
|
+
HandoffChain: params.handoffChain ?? [],
|
|
6721
|
+
HostAllowedIDs: HostAllowedAgentIDs(data),
|
|
6722
|
+
ContextUser: params.contextUser,
|
|
6723
|
+
Agents: AIEngine.Instance.Agents,
|
|
6724
|
+
});
|
|
6725
|
+
if (resolution.Refusal) {
|
|
6726
|
+
const refusal = resolution.Refusal;
|
|
6727
|
+
this.logError(`Handoff target agent '${requestedName}' refused (${refusal.Reason}) for agent '${params.agent.Name}': ${refusal.Message}`, {
|
|
6728
|
+
agent: params.agent,
|
|
6729
|
+
category: 'NextStepValidation'
|
|
6730
|
+
});
|
|
6731
|
+
await this.createStepEntity({
|
|
6732
|
+
stepType: 'Handoff',
|
|
6733
|
+
stepName: `Handoff: ${requestedName.trim() || '(unknown)'}`,
|
|
6734
|
+
contextUser: params.contextUser,
|
|
6735
|
+
inputData: {
|
|
6736
|
+
agentName: requestedName,
|
|
6737
|
+
brief,
|
|
6738
|
+
reason
|
|
6739
|
+
},
|
|
6740
|
+
completed: {
|
|
6741
|
+
success: false,
|
|
6742
|
+
errorMessage: refusal.Message,
|
|
6743
|
+
outputData: {
|
|
6744
|
+
RefusalReason: refusal.Reason,
|
|
6745
|
+
AgentName: requestedName,
|
|
6746
|
+
Brief: brief,
|
|
6747
|
+
Reason: reason
|
|
6748
|
+
}
|
|
6749
|
+
}
|
|
6750
|
+
});
|
|
6751
|
+
if (nextStep.step !== 'Retry') {
|
|
6752
|
+
this._generalValidationRetryCount++;
|
|
6753
|
+
}
|
|
6754
|
+
return {
|
|
6755
|
+
step: 'Retry',
|
|
6756
|
+
terminate: false,
|
|
6757
|
+
message: refusal.Message,
|
|
6758
|
+
errorMessage: refusal.Message
|
|
6759
|
+
};
|
|
6760
|
+
}
|
|
6761
|
+
const target = resolution.Target;
|
|
6762
|
+
this._resolvedHandoffTarget = { id: target.ID, name: target.Name };
|
|
6763
|
+
if (nextStep.handoff) {
|
|
6764
|
+
nextStep.handoff = { ...nextStep.handoff, agentName: target.Name };
|
|
6765
|
+
}
|
|
6766
|
+
return nextStep;
|
|
6767
|
+
}
|
|
6768
|
+
/**
|
|
6769
|
+
* Validates that the Success next step is valid and can be executed by the current agent. Subclasses can override
|
|
6770
|
+
* this method to implement custom validation logic if needed.
|
|
6771
|
+
* @param params
|
|
6772
|
+
* @param nextStep
|
|
6773
|
+
* @returns
|
|
6774
|
+
*/
|
|
6775
|
+
async validateSuccessNextStep(params, nextStep, currentPayload, agentRun, currentStep) {
|
|
6776
|
+
// First check minimum execution requirements
|
|
6777
|
+
const minViolations = await this.checkMinimumExecutionRequirements(params.agent, agentRun);
|
|
6778
|
+
if (minViolations.length > 0) {
|
|
6779
|
+
const violationMessage = `Minimum execution requirements not met:\n${minViolations.join('\n')}`;
|
|
6780
|
+
this.logError(violationMessage, {
|
|
6781
|
+
agent: params.agent,
|
|
6782
|
+
category: 'MinimumExecutionValidation'
|
|
6783
|
+
});
|
|
6784
|
+
// Increment validation retry count since we're changing to Retry
|
|
6785
|
+
if (nextStep.step !== 'Retry') {
|
|
6786
|
+
this._generalValidationRetryCount++;
|
|
6787
|
+
}
|
|
6788
|
+
// A native complete_task keeps its turn and call id, so the refusal answers that call.
|
|
6789
|
+
return {
|
|
6790
|
+
step: 'Retry',
|
|
6791
|
+
terminate: false,
|
|
6792
|
+
errorMessage: violationMessage,
|
|
6793
|
+
...(nextStep.nativeTurn ? { nativeTurn: nextStep.nativeTurn, payloadToolCallId: nextStep.payloadToolCallId } : {})
|
|
6794
|
+
};
|
|
6795
|
+
}
|
|
6796
|
+
// Check if the agent has FinalPayloadValidation configured
|
|
6089
6797
|
const agent = params.agent;
|
|
6090
6798
|
if (!agent.FinalPayloadValidation || !currentPayload) {
|
|
6091
6799
|
// No validation configured or no payload to validate
|
|
@@ -6277,22 +6985,89 @@ export class BaseAgent {
|
|
|
6277
6985
|
// currently the base class doesn't do anything, subclasses can implement any custom logic in their override
|
|
6278
6986
|
return nextStep;
|
|
6279
6987
|
}
|
|
6988
|
+
/**
|
|
6989
|
+
* Resolves the effective `ChatHandlingOption` for a sub-agent execution:
|
|
6990
|
+
* `relationship?.ChatHandlingOption ?? parentAgent.ChatHandlingOption ?? null`.
|
|
6991
|
+
* @private
|
|
6992
|
+
*/
|
|
6993
|
+
resolveSubAgentChatHandlingOption(parentAgent, relationship) {
|
|
6994
|
+
return relationship?.ChatHandlingOption ?? parentAgent.ChatHandlingOption ?? null;
|
|
6995
|
+
}
|
|
6996
|
+
/**
|
|
6997
|
+
* Returns `true` only when `resolvedOption === 'Consult'` AND the parent agent's
|
|
6998
|
+
* type supports injecting loop/consult messages into conversation history
|
|
6999
|
+
* (`this.AgentTypeInstance?.InjectLoopResultsAsMessage !== false`).
|
|
7000
|
+
*
|
|
7001
|
+
* When `resolvedOption === 'Consult'` and `this.AgentTypeInstance?.InjectLoopResultsAsMessage === false`
|
|
7002
|
+
* (e.g., a Flow parent), logs a warning once per run and returns `false` so `'Consult'`
|
|
7003
|
+
* is treated as `null` (propagate).
|
|
7004
|
+
* @private
|
|
7005
|
+
*/
|
|
7006
|
+
isSubAgentConsultActive(resolvedOption, params) {
|
|
7007
|
+
if (resolvedOption !== 'Consult') {
|
|
7008
|
+
return false;
|
|
7009
|
+
}
|
|
7010
|
+
if (this.AgentTypeInstance?.InjectLoopResultsAsMessage === false) {
|
|
7011
|
+
if (!this._loggedConsultUnsupportedAgentType) {
|
|
7012
|
+
this._loggedConsultUnsupportedAgentType = true;
|
|
7013
|
+
this.logStatus("⚠️ ChatHandlingOption 'Consult' is not supported for agent types where InjectLoopResultsAsMessage is false; treating as null (propagate).", false, params);
|
|
7014
|
+
}
|
|
7015
|
+
return false;
|
|
7016
|
+
}
|
|
7017
|
+
return true;
|
|
7018
|
+
}
|
|
7019
|
+
/**
|
|
7020
|
+
* Resolves the sub-agent `ChatHandlingOption` and downgrades `'Consult'` to `null`
|
|
7021
|
+
* when `isSubAgentConsultActive` returns `false` (e.g., on Flow parents).
|
|
7022
|
+
* @private
|
|
7023
|
+
*/
|
|
7024
|
+
effectiveSubAgentChatHandlingOption(parentAgent, relationship, params) {
|
|
7025
|
+
const resolved = this.resolveSubAgentChatHandlingOption(parentAgent, relationship);
|
|
7026
|
+
if (resolved === 'Consult' && !this.isSubAgentConsultActive(resolved, params)) {
|
|
7027
|
+
return null;
|
|
7028
|
+
}
|
|
7029
|
+
return resolved;
|
|
7030
|
+
}
|
|
7031
|
+
/**
|
|
7032
|
+
* Side-effect-free check used during prompt and native-tool construction to determine
|
|
7033
|
+
* whether `'Consult'` is active for a specific sub-agent of `parentAgent`.
|
|
7034
|
+
* @private
|
|
7035
|
+
*/
|
|
7036
|
+
isSubAgentConsultEnabledForSubAgent(parentAgent, subAgent) {
|
|
7037
|
+
if (this.AgentTypeInstance?.InjectLoopResultsAsMessage === false) {
|
|
7038
|
+
return false;
|
|
7039
|
+
}
|
|
7040
|
+
const isDirectChild = subAgent.ParentID != null && UUIDsEqual(subAgent.ParentID, parentAgent.ID);
|
|
7041
|
+
const relationship = isDirectChild
|
|
7042
|
+
? undefined
|
|
7043
|
+
: (AIEngine.Instance.AgentRelationships ?? []).find(r => UUIDsEqual(r.AgentID, parentAgent.ID) && UUIDsEqual(r.SubAgentID, subAgent.ID) && r.Status === 'Active');
|
|
7044
|
+
return this.resolveSubAgentChatHandlingOption(parentAgent, relationship) === 'Consult';
|
|
7045
|
+
}
|
|
6280
7046
|
/**
|
|
6281
7047
|
* Validates that the Chat next step is valid and can be executed by the current agent.
|
|
6282
|
-
* Implements ChatHandlingOption remapping logic - if the agent
|
|
6283
|
-
*
|
|
7048
|
+
* Implements ChatHandlingOption remapping logic - if the agent (or sub-agent relationship)
|
|
7049
|
+
* has ChatHandlingOption set:
|
|
7050
|
+
* - `'Consult'`: leaves the Chat step unchanged (an agent's own Chat propagates to its caller;
|
|
7051
|
+
* sub-agent Consult is intercepted before this validator).
|
|
7052
|
+
* - `'Success'` / `'Failed'`: remaps `step` while preserving `terminate: true` to end the run.
|
|
7053
|
+
* - `'Retry'`: remaps `step` to `'Retry'`, sets `terminate: false` so the loop continues, and
|
|
7054
|
+
* populates `errorMessage` so the unproductive-retry safety net bounds repeated Chat attempts.
|
|
6284
7055
|
* Subclasses can override this method to implement custom validation logic if needed.
|
|
6285
7056
|
* @param params
|
|
6286
7057
|
* @param nextStep
|
|
6287
7058
|
* @returns
|
|
6288
7059
|
*/
|
|
6289
|
-
async validateChatNextStep(params, nextStep, currentPayload, agentRun, currentStep) {
|
|
6290
|
-
//
|
|
6291
|
-
const
|
|
6292
|
-
|
|
7060
|
+
async validateChatNextStep(params, nextStep, currentPayload, agentRun, currentStep, chatHandlingOption) {
|
|
7061
|
+
// Use caller-resolved option when provided; otherwise fall back to params.agent.ChatHandlingOption
|
|
7062
|
+
const effectiveOption = chatHandlingOption !== undefined
|
|
7063
|
+
? chatHandlingOption
|
|
7064
|
+
: params.agent.ChatHandlingOption;
|
|
7065
|
+
if (effectiveOption) {
|
|
6293
7066
|
// Use a switch to validate and map the ChatHandlingOption value
|
|
6294
7067
|
let mappedStep;
|
|
6295
|
-
switch (
|
|
7068
|
+
switch (effectiveOption) {
|
|
7069
|
+
case 'Consult':
|
|
7070
|
+
return nextStep;
|
|
6296
7071
|
case 'Success':
|
|
6297
7072
|
mappedStep = 'Success';
|
|
6298
7073
|
break;
|
|
@@ -6304,17 +7079,26 @@ export class BaseAgent {
|
|
|
6304
7079
|
break;
|
|
6305
7080
|
default:
|
|
6306
7081
|
// Log error and treat as null (default behavior)
|
|
6307
|
-
LogError(`Invalid ChatHandlingOption value: ${
|
|
7082
|
+
LogError(`Invalid ChatHandlingOption value: ${effectiveOption}. Expected 'Consult', 'Success', 'Failed', or 'Retry'. Treating as null and allowing Chat to propagate.`);
|
|
6308
7083
|
return nextStep;
|
|
6309
7084
|
}
|
|
6310
|
-
// Remap the Chat step to the configured option
|
|
6311
|
-
|
|
6312
|
-
|
|
6313
|
-
|
|
6314
|
-
|
|
7085
|
+
// Remap the Chat step to the configured option.
|
|
7086
|
+
// Retry sets terminate to false so the loop continues and sets errorMessage so the
|
|
7087
|
+
// unproductive-retry cap bounds a model that repeatedly emits Chat.
|
|
7088
|
+
const remappedStep = mappedStep === 'Retry'
|
|
7089
|
+
? {
|
|
7090
|
+
...nextStep,
|
|
7091
|
+
step: 'Retry',
|
|
7092
|
+
terminate: false,
|
|
7093
|
+
errorMessage: nextStep.errorMessage || 'Chat was remapped to Retry by ChatHandlingOption'
|
|
7094
|
+
}
|
|
7095
|
+
: {
|
|
7096
|
+
...nextStep,
|
|
7097
|
+
step: mappedStep
|
|
7098
|
+
};
|
|
6315
7099
|
// Log the remapping for debugging
|
|
6316
7100
|
if (params.verbose === true || IsVerboseLoggingEnabled()) {
|
|
6317
|
-
LogStatus(`Remapping Chat step to ${
|
|
7101
|
+
LogStatus(`Remapping Chat step to ${effectiveOption} based on agent's ChatHandlingOption`);
|
|
6318
7102
|
}
|
|
6319
7103
|
// Re-validate the remapped step using the appropriate validator
|
|
6320
7104
|
return await this.validateNextStep(params, remappedStep, currentPayload, agentRun, currentStep);
|
|
@@ -7524,7 +8308,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
7524
8308
|
async processNextStep(nextStep, params, agentType, promptResult, currentPayload, currentStep) {
|
|
7525
8309
|
const validatedNextStep = await this.validateNextStep(params, nextStep, currentPayload, this._agentRun, currentStep);
|
|
7526
8310
|
// Check guardrails if next step would continue execution
|
|
7527
|
-
const guardrailCheckedStep = await this.checkExecutionGuardrails(params, validatedNextStep, currentPayload, this._agentRun, currentStep);
|
|
8311
|
+
const guardrailCheckedStep = this.noteDiscardedCompletionChange(nextStep, await this.checkExecutionGuardrails(params, validatedNextStep, currentPayload, this._agentRun, currentStep));
|
|
7528
8312
|
this.logStatus(`📌 Next step determined: ${guardrailCheckedStep.step}${guardrailCheckedStep.terminate ? ' (terminating)' : ''}`, true, params);
|
|
7529
8313
|
// the model's own call turn goes into history before anything answers it.
|
|
7530
8314
|
this.appendNativeAssistantTurn(params, guardrailCheckedStep);
|
|
@@ -7568,6 +8352,25 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
7568
8352
|
// Return the next step directly - execution handling is done in execute NextStep
|
|
7569
8353
|
return guardrailCheckedStep;
|
|
7570
8354
|
}
|
|
8355
|
+
/**
|
|
8356
|
+
* A completion refused with a payload change in hand: the change is discarded (the prompt step
|
|
8357
|
+
* commits it only for an accepted completion), so the refusal the model reads says so, and asks
|
|
8358
|
+
* for the change again with the next completion. Otherwise the model would take the change as
|
|
8359
|
+
* saved and its work would be lost. The change is removed from the step, so nothing later
|
|
8360
|
+
* applies it. Any other step is returned as it is.
|
|
8361
|
+
*/
|
|
8362
|
+
noteDiscardedCompletionChange(original, step) {
|
|
8363
|
+
if (!BaseAgent.carriesCompletionChange(original) || step.step === 'Success') {
|
|
8364
|
+
return step;
|
|
8365
|
+
}
|
|
8366
|
+
const native = !!step.payloadToolCallId && this.nativeToolNameForCall(step, step.payloadToolCallId) === COMPLETE_TASK_TOOL;
|
|
8367
|
+
const note = native
|
|
8368
|
+
? 'The payloadChangeRequest sent with this complete_task call was NOT applied. Send it again with your next complete_task call.'
|
|
8369
|
+
: 'The payloadChangeRequest sent with this completion was NOT applied. Send it again with your next completion.';
|
|
8370
|
+
const field = step.retryInstructions ? 'retryInstructions' : step.message ? 'message' : 'errorMessage';
|
|
8371
|
+
const { payloadChangeRequest: _discarded, ...rest } = step;
|
|
8372
|
+
return { ...rest, [field]: step[field] ? `${step[field]}\n\n${note}` : note };
|
|
8373
|
+
}
|
|
7571
8374
|
/**
|
|
7572
8375
|
* Answers a retried native tool-call turn in the protocol itself: every call gets an `is_error`
|
|
7573
8376
|
* result carrying the retry reason, and no user message follows.
|
|
@@ -7794,6 +8597,101 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
7794
8597
|
this.logStatus(`[StoppedRunResults] Skipped (contained error): ${error instanceof Error ? error.message : error}`, true, params);
|
|
7795
8598
|
}
|
|
7796
8599
|
}
|
|
8600
|
+
/**
|
|
8601
|
+
* Loads unanswered sub-agent consultations (`OutputData.consult`) from `params.lastRunId` when that
|
|
8602
|
+
* prior run paused with `FinalStep === 'Chat'` (and was not stopped by the user). Runs at any depth
|
|
8603
|
+
* so a middle agent resumed via `resumeRunId` also reloads its own open child consults. Fail-soft.
|
|
8604
|
+
* @private
|
|
8605
|
+
*/
|
|
8606
|
+
async loadOpenConsults(params) {
|
|
8607
|
+
if (!params.lastRunId || !IsValidUUID(params.lastRunId) || !CanAgentOwnSubAgentConsults(params.agent)) {
|
|
8608
|
+
return [];
|
|
8609
|
+
}
|
|
8610
|
+
try {
|
|
8611
|
+
const rv = RunView.FromMetadataProvider(this.ProviderToUse);
|
|
8612
|
+
const runResult = await rv.RunView({
|
|
8613
|
+
EntityName: 'MJ: AI Agent Runs',
|
|
8614
|
+
ExtraFilter: `ID='${params.lastRunId}'`,
|
|
8615
|
+
MaxRows: 1,
|
|
8616
|
+
Fields: ['ID', 'FinalStep', 'Status', 'CancellationReason'],
|
|
8617
|
+
ResultType: 'simple',
|
|
8618
|
+
BypassCache: true,
|
|
8619
|
+
}, params.contextUser);
|
|
8620
|
+
const priorRun = runResult.Success ? runResult.Results?.[0] : undefined;
|
|
8621
|
+
if (!priorRun ||
|
|
8622
|
+
priorRun.FinalStep !== 'Chat' ||
|
|
8623
|
+
MJAIAgentRunEntityExtended.IsUserStopped(priorRun.Status, priorRun.CancellationReason)) {
|
|
8624
|
+
return [];
|
|
8625
|
+
}
|
|
8626
|
+
return await LoadOpenSubAgentConsults(this.ProviderToUse, params.lastRunId, params.contextUser);
|
|
8627
|
+
}
|
|
8628
|
+
catch (error) {
|
|
8629
|
+
this.logStatus(`[SubAgentConsult] Skipped loading open consults (contained error): ${error instanceof Error ? error.message : error}`, true, params);
|
|
8630
|
+
return [];
|
|
8631
|
+
}
|
|
8632
|
+
}
|
|
8633
|
+
/**
|
|
8634
|
+
* Restores reloaded open sub-agent consults into `this._openSubAgentConsults` (so `resumeRunId`
|
|
8635
|
+
* validation accepts them) and splices a `sub-agent-consult` reminder message immediately before
|
|
8636
|
+
* `continuationMessage` (the caller's answer). Fail-soft.
|
|
8637
|
+
* @private
|
|
8638
|
+
*/
|
|
8639
|
+
applyOpenConsults(params, openConsults, continuationMessage) {
|
|
8640
|
+
if (!openConsults || openConsults.length === 0) {
|
|
8641
|
+
return;
|
|
8642
|
+
}
|
|
8643
|
+
try {
|
|
8644
|
+
for (const consult of openConsults) {
|
|
8645
|
+
if (consult.childRunId) {
|
|
8646
|
+
this._openSubAgentConsults.set(consult.childRunId, consult);
|
|
8647
|
+
}
|
|
8648
|
+
}
|
|
8649
|
+
const content = FormatReloadedConsultsMessage(openConsults);
|
|
8650
|
+
if (!content) {
|
|
8651
|
+
return;
|
|
8652
|
+
}
|
|
8653
|
+
const metadata = {
|
|
8654
|
+
turnAdded: 0,
|
|
8655
|
+
messageType: 'sub-agent-consult',
|
|
8656
|
+
...(openConsults.length === 1
|
|
8657
|
+
? {
|
|
8658
|
+
subAgentName: openConsults[0].subAgentName,
|
|
8659
|
+
subAgentId: openConsults[0].subAgentId,
|
|
8660
|
+
}
|
|
8661
|
+
: {}),
|
|
8662
|
+
expirationTurns: 3,
|
|
8663
|
+
expirationMode: 'Remove',
|
|
8664
|
+
};
|
|
8665
|
+
const consultReminder = {
|
|
8666
|
+
role: 'user',
|
|
8667
|
+
content,
|
|
8668
|
+
metadata,
|
|
8669
|
+
};
|
|
8670
|
+
const at = continuationMessage ? params.conversationMessages.indexOf(continuationMessage) : -1;
|
|
8671
|
+
if (at >= 0) {
|
|
8672
|
+
params.conversationMessages.splice(at, 0, consultReminder);
|
|
8673
|
+
}
|
|
8674
|
+
else {
|
|
8675
|
+
let lastUserIdx = -1;
|
|
8676
|
+
for (let i = params.conversationMessages.length - 1; i >= 0; i--) {
|
|
8677
|
+
if (params.conversationMessages[i].role === 'user') {
|
|
8678
|
+
lastUserIdx = i;
|
|
8679
|
+
break;
|
|
8680
|
+
}
|
|
8681
|
+
}
|
|
8682
|
+
if (lastUserIdx >= 0) {
|
|
8683
|
+
params.conversationMessages.splice(lastUserIdx, 0, consultReminder);
|
|
8684
|
+
}
|
|
8685
|
+
else {
|
|
8686
|
+
params.conversationMessages.push(consultReminder);
|
|
8687
|
+
}
|
|
8688
|
+
}
|
|
8689
|
+
this.logStatus(`[SubAgentConsult] Reloaded ${openConsults.length} open consult(s) from prior run ${params.lastRunId}`, true, params);
|
|
8690
|
+
}
|
|
8691
|
+
catch (error) {
|
|
8692
|
+
this.logStatus(`[SubAgentConsult] Skipped applying open consults (contained error): ${error instanceof Error ? error.message : error}`, true, params);
|
|
8693
|
+
}
|
|
8694
|
+
}
|
|
7797
8695
|
/**
|
|
7798
8696
|
* The full-stack half of {@link applyStoppedRunContinuation}: true when the stopped run's turns were
|
|
7799
8697
|
* spliced in. Any failure leaves the messages untouched and returns false, so the caller carries
|
|
@@ -8078,6 +8976,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
8078
8976
|
ExtraFilter: MJAIAgentRunEntityExtended.BuildStoppedPredecessorFilter(params.conversationId, params.agent.ID, params.ConversationBranchID ?? null, this._conversationBranches),
|
|
8079
8977
|
OrderBy: '__mj_CreatedAt DESC',
|
|
8080
8978
|
MaxRows: 1,
|
|
8979
|
+
SkipTotalRowCount: true,
|
|
8081
8980
|
Fields: ['ID', 'Status', 'CancellationReason'],
|
|
8082
8981
|
ResultType: 'simple',
|
|
8083
8982
|
// The row this looks for was written by the Stop button moments ago; read the database, not a cache.
|
|
@@ -8102,6 +9001,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
8102
9001
|
EntityName: 'MJ: AI Agent Runs',
|
|
8103
9002
|
ExtraFilter: `ID='${runId}'`,
|
|
8104
9003
|
MaxRows: 1,
|
|
9004
|
+
SkipTotalRowCount: true,
|
|
8105
9005
|
Fields: ['ID', 'Status', 'CancellationReason'],
|
|
8106
9006
|
ResultType: 'simple',
|
|
8107
9007
|
// The row this checks was written by the Stop button moments ago; read the database, not a cache.
|
|
@@ -8266,6 +9166,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
8266
9166
|
ExtraFilter: BaseAgent.BuildPriorTurnRunFilter(params.conversationId, params.agent.ID, branchId, this._conversationBranches, statusList),
|
|
8267
9167
|
OrderBy: '__mj_CreatedAt DESC',
|
|
8268
9168
|
MaxRows: 1,
|
|
9169
|
+
SkipTotalRowCount: true,
|
|
8269
9170
|
Fields: ['ID'],
|
|
8270
9171
|
ResultType: 'simple',
|
|
8271
9172
|
}, params.contextUser);
|
|
@@ -8657,6 +9558,8 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
8657
9558
|
companyId: params.companyId,
|
|
8658
9559
|
verbose: params.verbose,
|
|
8659
9560
|
provider: this.ProviderToUse,
|
|
9561
|
+
isRunTainted: this.IsRunTainted,
|
|
9562
|
+
taintedSources: this._taintedSources,
|
|
8660
9563
|
};
|
|
8661
9564
|
}
|
|
8662
9565
|
/**
|
|
@@ -9456,7 +10359,12 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
9456
10359
|
*
|
|
9457
10360
|
* @private
|
|
9458
10361
|
*/
|
|
9459
|
-
async gatherPromptTemplateData(agent, _contextUser, extraData, actionChanges, subAgentChanges, boundActionParams,
|
|
10362
|
+
async gatherPromptTemplateData(agent, _contextUser, extraData, actionChanges, subAgentChanges, boundActionParams, withholdingOrParentRun, parentRun) {
|
|
10363
|
+
const isWithholdingShape = (val) => typeof val === 'object' && val !== null && 'TaskGraphs' in val;
|
|
10364
|
+
const withholding = isWithholdingShape(withholdingOrParentRun) ? withholdingOrParentRun : undefined;
|
|
10365
|
+
const resolvedParentRun = isWithholdingShape(withholdingOrParentRun)
|
|
10366
|
+
? parentRun
|
|
10367
|
+
: (parentRun ?? withholdingOrParentRun);
|
|
9460
10368
|
try {
|
|
9461
10369
|
const engine = AIEngine.Instance;
|
|
9462
10370
|
// Build (or reuse) the agent-invariant base catalog. This is process-wide cached on
|
|
@@ -9513,6 +10421,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
9513
10421
|
this._effectiveActions = activeActions;
|
|
9514
10422
|
// Store for later validation in validateSubAgentNextStep (see getEffectiveSubAgentsForValidation)
|
|
9515
10423
|
this._effectiveSubAgents = uniqueActiveSubAgents;
|
|
10424
|
+
this._effectiveCatalogComputed = true;
|
|
9516
10425
|
// Agent type prompt params: reuse cached base merge unless a runtime override is present.
|
|
9517
10426
|
const runtimePromptParamOverrides = extraData?.__agentTypePromptParams;
|
|
9518
10427
|
let agentTypePromptParams;
|
|
@@ -9534,6 +10443,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
9534
10443
|
if (withholding?.TaskGraphs || this.hasBoundActionParams(boundActionParams)) {
|
|
9535
10444
|
agentTypePromptParams = this.withoutTaskGraphs(agentTypePromptParams);
|
|
9536
10445
|
}
|
|
10446
|
+
if (withholding?.Handoff) {
|
|
10447
|
+
agentTypePromptParams = this.withoutHandoff(agentTypePromptParams);
|
|
10448
|
+
}
|
|
9537
10449
|
// Store for the finishIf gate, which runs after this prompt in executeActionsStep / executeNextStep
|
|
9538
10450
|
this._agentTypePromptParams = agentTypePromptParams;
|
|
9539
10451
|
// Skill catalog (name + description only — progressive disclosure). This is the
|
|
@@ -9557,6 +10469,20 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
9557
10469
|
const skillsCatalog = this.narrowedCatalogSection('skill', availableSkills, this.formatSkillsCatalog(availableSkills), shown => this.formatSkillsCatalog(shown));
|
|
9558
10470
|
// The client tools and the app context (per-run, from extraData) — neither under an audience (callerContextSections).
|
|
9559
10471
|
const { clientToolDetails, appContext } = this.callerContextSections(agent, extraData, withholding?.CallerContext === true);
|
|
10472
|
+
const subAgentConsultEnabled = uniqueActiveSubAgents.some(sa => this.isSubAgentConsultEnabledForSubAgent(agent, sa));
|
|
10473
|
+
const subAgentPresetsAvailable = uniqueActiveSubAgents.some(sa => AIEngine.Instance.GetAgentConfigurationPresets(sa.ID, true).length > 0);
|
|
10474
|
+
let parentConsults = false;
|
|
10475
|
+
const effectiveParentRun = resolvedParentRun ?? this._executeParams?.parentRun;
|
|
10476
|
+
if (!isRoot && effectiveParentRun?.AgentID) {
|
|
10477
|
+
const parentAgent = (engine.Agents ?? []).find(a => UUIDsEqual(a.ID, effectiveParentRun.AgentID));
|
|
10478
|
+
if (parentAgent) {
|
|
10479
|
+
const isDirectChild = agent.ParentID != null && UUIDsEqual(agent.ParentID, parentAgent.ID);
|
|
10480
|
+
const relationship = isDirectChild
|
|
10481
|
+
? undefined
|
|
10482
|
+
: (engine.AgentRelationships ?? []).find(r => UUIDsEqual(r.AgentID, parentAgent.ID) && UUIDsEqual(r.SubAgentID, agent.ID) && r.Status === 'Active');
|
|
10483
|
+
parentConsults = this.resolveSubAgentChatHandlingOption(parentAgent, relationship) === 'Consult';
|
|
10484
|
+
}
|
|
10485
|
+
}
|
|
9560
10486
|
const cachedUserPolicy = _contextUser?.ID
|
|
9561
10487
|
? AgentUserPolicyEngine.Instance.GetCachedPolicy(agent.ID, _contextUser.ID)
|
|
9562
10488
|
: null;
|
|
@@ -9585,6 +10511,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
9585
10511
|
skillsCatalog: skillsCatalog,
|
|
9586
10512
|
planModeActive: this._planModeActive,
|
|
9587
10513
|
planApproved: this._planApproved,
|
|
10514
|
+
...(subAgentConsultEnabled ? { subAgentConsultEnabled: true } : {}),
|
|
10515
|
+
...(parentConsults ? { parentConsults: true } : {}),
|
|
10516
|
+
...(subAgentPresetsAvailable ? { subAgentPresetsAvailable: true } : {}),
|
|
9588
10517
|
appContext: appContext,
|
|
9589
10518
|
};
|
|
9590
10519
|
// Build the final result with __agentTypePromptParams injected
|
|
@@ -10125,7 +11054,8 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10125
11054
|
// that loop's `else` branch defaults an unset key to true, which is exactly what a gated
|
|
10126
11055
|
// capability must never do.
|
|
10127
11056
|
const gateMappings = [
|
|
10128
|
-
{ gateFlag: 'enableTaskGraphs', responseTypeKey: 'tasks' }
|
|
11057
|
+
{ gateFlag: 'enableTaskGraphs', responseTypeKey: 'tasks' },
|
|
11058
|
+
{ gateFlag: 'enableHandoff', responseTypeKey: 'handoff' }
|
|
10129
11059
|
];
|
|
10130
11060
|
for (const { gateFlag, responseTypeKey } of gateMappings) {
|
|
10131
11061
|
const wasExplicitlySet = explicitResponseType &&
|
|
@@ -10602,7 +11532,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10602
11532
|
const secondary = scope.SecondaryScopes
|
|
10603
11533
|
? Object.fromEntries(Object.entries(scope.SecondaryScopes).map(([key, value]) => [key, Array.isArray(value) ? [...value] : value]))
|
|
10604
11534
|
: null;
|
|
10605
|
-
return { ...scope, SecondaryScopes: secondary };
|
|
11535
|
+
return { ...scope, SecondaryScopes: secondary, ...(scope.SearchScopeIDs ? { SearchScopeIDs: [...scope.SearchScopeIDs] } : {}) };
|
|
10606
11536
|
}
|
|
10607
11537
|
/**
|
|
10608
11538
|
* Logs one dispatched call's outcome and feeds the run-scoped circuit breaker, unless the caller does its own
|
|
@@ -10739,10 +11669,10 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10739
11669
|
return null;
|
|
10740
11670
|
}
|
|
10741
11671
|
const resultCode = evaluation.verdict === 'Deny'
|
|
10742
|
-
?
|
|
11672
|
+
? POLICY_DENIED_RESULT_CODE
|
|
10743
11673
|
: evaluation.verdict === 'DeferUntilNextWindow'
|
|
10744
|
-
?
|
|
10745
|
-
:
|
|
11674
|
+
? POLICY_DEFERRED_RESULT_CODE
|
|
11675
|
+
: POLICY_APPROVAL_REQUIRED_RESULT_CODE;
|
|
10746
11676
|
return {
|
|
10747
11677
|
Success: false,
|
|
10748
11678
|
ResultCode: resultCode,
|
|
@@ -10841,11 +11771,12 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10841
11771
|
* @param {AgentSubAgentRequest} subAgentRequest - Sub-agent request details
|
|
10842
11772
|
* @param {MJAIAgentEntityExtended} subAgent - The sub-agent entity
|
|
10843
11773
|
* @param {ChatMessage | undefined} contextMessage - Optional context from SubAgentContextPaths
|
|
11774
|
+
* @param {string | null | undefined} consultQuestion - Optional open-consult question when resuming a child run
|
|
10844
11775
|
* @returns {ChatMessage[]} Prepared message array for sub-agent execution
|
|
10845
11776
|
*
|
|
10846
11777
|
* @protected
|
|
10847
11778
|
*/
|
|
10848
|
-
prepareSubAgentMessages(params, subAgentRequest, subAgent, contextMessage) {
|
|
11779
|
+
prepareSubAgentMessages(params, subAgentRequest, subAgent, contextMessage, consultQuestion) {
|
|
10849
11780
|
const engine = AIEngine.Instance;
|
|
10850
11781
|
let messages = [];
|
|
10851
11782
|
// Check for related sub-agent configuration (AIAgentRelationship)
|
|
@@ -10902,6 +11833,13 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10902
11833
|
if (contextMessage) {
|
|
10903
11834
|
messages.push(contextMessage);
|
|
10904
11835
|
}
|
|
11836
|
+
// On resume, insert the consult's question as an assistant turn right before the request message
|
|
11837
|
+
if (consultQuestion) {
|
|
11838
|
+
messages.push({
|
|
11839
|
+
role: 'assistant',
|
|
11840
|
+
content: consultQuestion
|
|
11841
|
+
});
|
|
11842
|
+
}
|
|
10905
11843
|
if (subAgentRequest.message) {
|
|
10906
11844
|
messages.push({
|
|
10907
11845
|
role: 'user',
|
|
@@ -10941,8 +11879,29 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10941
11879
|
this.logStatus(`🤖 Executing sub-agent '${subAgentRequest.name}'`, true, params);
|
|
10942
11880
|
// Create a new AgentRunner instance with the same isolated provider
|
|
10943
11881
|
const runner = new AgentRunner(params.provider || this._activeProvider);
|
|
11882
|
+
// Look up an open consult matching both childRunId and subAgent.ID once.
|
|
11883
|
+
// Only resume when the consult is open for this sub-agent; otherwise log an error and run fresh.
|
|
11884
|
+
const requestedResumeRunId = subAgentRequest.resumeRunId?.trim() || undefined;
|
|
11885
|
+
let matchedConsult;
|
|
11886
|
+
if (requestedResumeRunId) {
|
|
11887
|
+
matchedConsult = Array.from(this._openSubAgentConsults.values()).find(c => UUIDsEqual(c.childRunId, requestedResumeRunId) && UUIDsEqual(c.subAgentId, subAgent.ID));
|
|
11888
|
+
if (matchedConsult) {
|
|
11889
|
+
this._openSubAgentConsults.delete(matchedConsult.childRunId);
|
|
11890
|
+
}
|
|
11891
|
+
else {
|
|
11892
|
+
this.logError(`ExecuteSubAgent: ignoring unknown or mismatched resumeRunId '${requestedResumeRunId}' for sub-agent '${subAgent.Name}'`, {
|
|
11893
|
+
agent: params.agent,
|
|
11894
|
+
category: 'SubAgentExecution',
|
|
11895
|
+
metadata: {
|
|
11896
|
+
subAgentName: subAgent.Name,
|
|
11897
|
+
resumeRunId: requestedResumeRunId
|
|
11898
|
+
}
|
|
11899
|
+
});
|
|
11900
|
+
}
|
|
11901
|
+
}
|
|
11902
|
+
const verifiedResumeRunId = matchedConsult?.childRunId;
|
|
10944
11903
|
// Prepare messages for sub-agent using database-configured message mode
|
|
10945
|
-
const subAgentMessages = this.prepareSubAgentMessages(params, subAgentRequest, subAgent, contextMessage);
|
|
11904
|
+
const subAgentMessages = this.prepareSubAgentMessages(params, subAgentRequest, subAgent, contextMessage, matchedConsult?.question);
|
|
10946
11905
|
// Set parent run ID in the sub-agent's execution
|
|
10947
11906
|
// This would need to be passed through the AgentRunner in a real implementation
|
|
10948
11907
|
// For now, we execute normally and the sub-agent will track its parent relationship
|
|
@@ -10962,6 +11921,17 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10962
11921
|
// Use subAgentRequest.context if provided, otherwise fall back to params.context
|
|
10963
11922
|
// This allows Flow agents and Loop agents to propagate context through sub-agent requests
|
|
10964
11923
|
const subAgentContext = subAgentRequest.context !== undefined ? subAgentRequest.context : params.context;
|
|
11924
|
+
const resolvedConfig = this.resolveSubAgentConfiguration(params, subAgentRequest, subAgent);
|
|
11925
|
+
if (resolvedConfig.presetId && stepEntity) {
|
|
11926
|
+
const parsedInput = stepEntity.InputData
|
|
11927
|
+
? JSON.parse(stepEntity.InputData)
|
|
11928
|
+
: {};
|
|
11929
|
+
parsedInput.presetName = resolvedConfig.presetName;
|
|
11930
|
+
parsedInput.presetId = resolvedConfig.presetId;
|
|
11931
|
+
const updatedInputJson = JSON.stringify(parsedInput);
|
|
11932
|
+
stepEntity.InputData = updatedInputJson;
|
|
11933
|
+
this.queueStepSave(stepEntity, (s) => { s.InputData = updatedInputJson; });
|
|
11934
|
+
}
|
|
10965
11935
|
const result = await runner.RunAgent({
|
|
10966
11936
|
agent: subAgent,
|
|
10967
11937
|
conversationMessages: subAgentMessages,
|
|
@@ -10974,8 +11944,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10974
11944
|
parentStepCounts: parentStepCountsToPass,
|
|
10975
11945
|
parentRun: this._agentRun,
|
|
10976
11946
|
parentActivatedSkillIDs: this.activeSkillIDsForRun(params), // the root's active skills reach the sub-agent's actions
|
|
10977
|
-
payload: payload, //
|
|
10978
|
-
|
|
11947
|
+
payload: verifiedResumeRunId ? undefined : payload, // on resume, ignore computed/mapped payload so autoPopulateLastRunPayload loads the child's prior FinalPayload
|
|
11948
|
+
...(verifiedResumeRunId ? { lastRunId: verifiedResumeRunId, autoPopulateLastRunPayload: true } : {}),
|
|
11949
|
+
configurationId: resolvedConfig.configurationId, // resolved preset configuration ID or inherited parent configurationId
|
|
10979
11950
|
effortLevel: params.effortLevel, // propagate effort level to sub-agent
|
|
10980
11951
|
apiKeys: params.apiKeys, // propagate API keys to sub-agent
|
|
10981
11952
|
CredentialScope: params.CredentialScope, // a sub-agent may not spend keys its parent could not
|
|
@@ -10996,6 +11967,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10996
11967
|
PrimaryScopeRecordID: params.PrimaryScopeRecordID,
|
|
10997
11968
|
companyId: params.companyId,
|
|
10998
11969
|
SecondaryScopes: params.SecondaryScopes,
|
|
11970
|
+
SearchScopeIDs: params.SearchScopeIDs, // the host's search scopes bound the sub-agent too
|
|
10999
11971
|
conversationDetailId: params.conversationDetailId, // propagate conversationDetailId so sub-agent task graphs attach to the chat message
|
|
11000
11972
|
onAgentRunCreated: async (agentRunId) => {
|
|
11001
11973
|
stepEntity.TargetLogID = agentRunId;
|
|
@@ -11026,6 +11998,47 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11026
11998
|
throw new Error(`Error executing sub-agent: ${error.message}`);
|
|
11027
11999
|
}
|
|
11028
12000
|
}
|
|
12001
|
+
/**
|
|
12002
|
+
* Resolves the configuration to pass to a sub-agent run in precedence order:
|
|
12003
|
+
* 1. Per-call `subAgentRequest.presetName` -> matching Active preset of `subAgent`.
|
|
12004
|
+
* 2. Active `AIAgentRelationship.ConfigurationPresetID` -> that preset if Active and owned by `subAgent`;
|
|
12005
|
+
* otherwise logs a warning and falls through.
|
|
12006
|
+
* 3. Inherit `params.configurationId`.
|
|
12007
|
+
*
|
|
12008
|
+
* When a preset is selected, `configurationId` is `preset.AIConfigurationID ?? undefined` (a NULL
|
|
12009
|
+
* `AIConfigurationID` means default rows and intentionally does NOT inherit `params.configurationId`).
|
|
12010
|
+
*/
|
|
12011
|
+
resolveSubAgentConfiguration(params, subAgentRequest, subAgent) {
|
|
12012
|
+
if (subAgentRequest.presetName != null && subAgentRequest.presetName.trim() !== '') {
|
|
12013
|
+
const preset = AIEngine.Instance.FindActiveAgentConfigurationPreset(subAgent.ID, subAgentRequest.presetName);
|
|
12014
|
+
if (preset) {
|
|
12015
|
+
return {
|
|
12016
|
+
configurationId: preset.AIConfigurationID ?? undefined,
|
|
12017
|
+
presetName: preset.Name,
|
|
12018
|
+
presetId: preset.ID
|
|
12019
|
+
};
|
|
12020
|
+
}
|
|
12021
|
+
this.logStatus(`⚠️ Sub-agent '${subAgent.Name}' has no active preset matching '${subAgentRequest.presetName}'; falling through.`, false, params);
|
|
12022
|
+
}
|
|
12023
|
+
const isDirectChild = subAgent.ParentID != null && UUIDsEqual(subAgent.ParentID, params.agent.ID);
|
|
12024
|
+
if (!isDirectChild) {
|
|
12025
|
+
const relationship = AIEngine.Instance.AgentRelationships.find(r => UUIDsEqual(r.AgentID, params.agent.ID) &&
|
|
12026
|
+
UUIDsEqual(r.SubAgentID, subAgent.ID) &&
|
|
12027
|
+
r.Status === 'Active');
|
|
12028
|
+
if (relationship?.ConfigurationPresetID) {
|
|
12029
|
+
const preset = AIEngine.Instance.AgentConfigurations.find(p => UUIDsEqual(p.ID, relationship.ConfigurationPresetID));
|
|
12030
|
+
if (preset && preset.Status === 'Active' && UUIDsEqual(preset.AgentID, subAgent.ID)) {
|
|
12031
|
+
return {
|
|
12032
|
+
configurationId: preset.AIConfigurationID ?? undefined,
|
|
12033
|
+
presetName: preset.Name,
|
|
12034
|
+
presetId: preset.ID
|
|
12035
|
+
};
|
|
12036
|
+
}
|
|
12037
|
+
this.logStatus(`⚠️ Sub-agent relationship for '${subAgent.Name}' references preset '${relationship.ConfigurationPresetID}' which is missing, inactive, or belongs to another agent; inheriting parent configuration.`, false, params);
|
|
12038
|
+
}
|
|
12039
|
+
}
|
|
12040
|
+
return { configurationId: params.configurationId };
|
|
12041
|
+
}
|
|
11029
12042
|
/**
|
|
11030
12043
|
* A sub-agent request's template parameters without the host-only run-data keys
|
|
11031
12044
|
* (`HOST_ONLY_AGENT_RUN_DATA_KEYS` in `@memberjunction/ai-core-plus`: the reserved scope family and
|
|
@@ -11061,6 +12074,23 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11061
12074
|
if (sa.ExecutionMode !== 'Sequential') {
|
|
11062
12075
|
line += ` _(${sa.ExecutionMode}, order: ${sa.ExecutionOrder})_`;
|
|
11063
12076
|
}
|
|
12077
|
+
const presets = AIEngine.Instance.GetAgentConfigurationPresets(sa.ID, true);
|
|
12078
|
+
if (presets.length > 0) {
|
|
12079
|
+
const presetSummary = presets.map(p => {
|
|
12080
|
+
const desc = p.Description?.trim();
|
|
12081
|
+
if (p.IsDefault && desc) {
|
|
12082
|
+
return `${p.Name} (default: ${desc})`;
|
|
12083
|
+
}
|
|
12084
|
+
if (p.IsDefault) {
|
|
12085
|
+
return `${p.Name} (default)`;
|
|
12086
|
+
}
|
|
12087
|
+
if (desc) {
|
|
12088
|
+
return `${p.Name} (${desc})`;
|
|
12089
|
+
}
|
|
12090
|
+
return p.Name;
|
|
12091
|
+
}).join(', ');
|
|
12092
|
+
line += `\n Presets: ${presetSummary}`;
|
|
12093
|
+
}
|
|
11064
12094
|
return line;
|
|
11065
12095
|
}).join('\n');
|
|
11066
12096
|
}
|
|
@@ -11152,6 +12182,35 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11152
12182
|
return lines.join('\n');
|
|
11153
12183
|
}).join('\n\n');
|
|
11154
12184
|
}
|
|
12185
|
+
/**
|
|
12186
|
+
* The client tools in force for a run: the agent's static metadata tools under the session, app
|
|
12187
|
+
* and override tiers, merged by {@link ResolveClientTools} with its fixed precedence. The prompt
|
|
12188
|
+
* section and the client-tool step both resolve through here, so the tools the model is offered
|
|
12189
|
+
* and the metadata its results are classified against are one list.
|
|
12190
|
+
*
|
|
12191
|
+
* @param data - The run's data bag: `sessionID` selects the session tier, `appContext` the app
|
|
12192
|
+
* tier, `clientTools` the override tier.
|
|
12193
|
+
*/
|
|
12194
|
+
resolveClientToolsForRun(agent, data) {
|
|
12195
|
+
// Static tier — agent's metadata tools from the AI Agent Client Tools junction.
|
|
12196
|
+
const staticTools = AIEngine.Instance.GetClientToolsForAgent(agent.ID).map(tool => ({
|
|
12197
|
+
Name: tool.Name,
|
|
12198
|
+
Description: tool.Description,
|
|
12199
|
+
InputSchema: tool.InputSchemaJSON ? JSON.parse(tool.InputSchemaJSON) : {},
|
|
12200
|
+
OutputSchema: tool.OutputSchemaJSON ? JSON.parse(tool.OutputSchemaJSON) : undefined,
|
|
12201
|
+
Category: tool.Category || undefined,
|
|
12202
|
+
DefaultTimeoutMs: tool.DefaultTimeoutMs || undefined
|
|
12203
|
+
}));
|
|
12204
|
+
// Dynamic (session) tier — client-SDK enriched tools for this session.
|
|
12205
|
+
const sessionID = data?.sessionID;
|
|
12206
|
+
const sessionTools = sessionID ? ClientToolRequestManager.Instance.GetSessionTools(sessionID) : [];
|
|
12207
|
+
// App tier — tools the active surface published in the app-context capability manifest.
|
|
12208
|
+
const appContext = data?.appContext;
|
|
12209
|
+
const appTools = appContext?.Capabilities?.Tools ?? [];
|
|
12210
|
+
// Override tier — tools passed directly in the run's data.
|
|
12211
|
+
const overrideTools = data?.clientTools ?? [];
|
|
12212
|
+
return ResolveClientTools({ agentId: agent.ID, staticTools, sessionTools, appTools, overrideTools });
|
|
12213
|
+
}
|
|
11155
12214
|
/**
|
|
11156
12215
|
* Build the client tool prompt section for system prompt injection.
|
|
11157
12216
|
*
|
|
@@ -11171,25 +12230,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11171
12230
|
* static metadata tool of the same name. Collisions are rare in practice.
|
|
11172
12231
|
*/
|
|
11173
12232
|
buildClientToolPromptSection(agent, extraData) {
|
|
11174
|
-
|
|
11175
|
-
const engine = AIEngine.Instance;
|
|
11176
|
-
const staticTools = engine.GetClientToolsForAgent(agent.ID).map(tool => ({
|
|
11177
|
-
Name: tool.Name,
|
|
11178
|
-
Description: tool.Description,
|
|
11179
|
-
InputSchema: tool.InputSchemaJSON ? JSON.parse(tool.InputSchemaJSON) : {},
|
|
11180
|
-
OutputSchema: tool.OutputSchemaJSON ? JSON.parse(tool.OutputSchemaJSON) : undefined,
|
|
11181
|
-
Category: tool.Category || undefined,
|
|
11182
|
-
DefaultTimeoutMs: tool.DefaultTimeoutMs || undefined
|
|
11183
|
-
}));
|
|
11184
|
-
// Dynamic (session) tier — client-SDK enriched tools for this session.
|
|
11185
|
-
const sessionID = extraData?.sessionID;
|
|
11186
|
-
const sessionTools = sessionID ? ClientToolRequestManager.Instance.GetSessionTools(sessionID) : [];
|
|
11187
|
-
// App tier — tools the active surface published in the app-context capability manifest.
|
|
11188
|
-
const appContext = extraData?.appContext;
|
|
11189
|
-
const appTools = appContext?.Capabilities?.Tools ?? [];
|
|
11190
|
-
// Override tier — tools passed directly in the run's data.
|
|
11191
|
-
const overrideTools = extraData?.clientTools ?? [];
|
|
11192
|
-
const tools = ResolveClientTools({ agentId: agent.ID, staticTools, sessionTools, appTools, overrideTools });
|
|
12233
|
+
const tools = this.resolveClientToolsForRun(agent, extraData);
|
|
11193
12234
|
if (tools.length === 0) {
|
|
11194
12235
|
return ''; // No client tools available
|
|
11195
12236
|
}
|
|
@@ -11358,7 +12399,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11358
12399
|
*
|
|
11359
12400
|
* @param actionSummaries - The action summary objects built by executeActionStep
|
|
11360
12401
|
* @returns Compact markdown string
|
|
11361
|
-
* @
|
|
12402
|
+
* @protected
|
|
11362
12403
|
*/
|
|
11363
12404
|
formatActionResultsAsMarkdown(actionSummaries) {
|
|
11364
12405
|
return actionSummaries.map(a => {
|
|
@@ -11366,6 +12407,30 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11366
12407
|
const lines = [];
|
|
11367
12408
|
lines.push(`## ${a.actionName} ${marker}`);
|
|
11368
12409
|
lines.push(`**Result:** ${a.resultCode} — ${a.message || '(no message)'}`);
|
|
12410
|
+
if (!a.success && a.errorRecovery) {
|
|
12411
|
+
const er = a.errorRecovery;
|
|
12412
|
+
if (er.Retryable !== undefined) {
|
|
12413
|
+
lines.push(`**Retryable:** ${er.Retryable ? 'Yes (adjust parameters before retrying)' : 'No (do not retry this action with the same goal)'}`);
|
|
12414
|
+
}
|
|
12415
|
+
if (er.RecoverySuggestion) {
|
|
12416
|
+
lines.push(`**How to Recover:** ${er.RecoverySuggestion}`);
|
|
12417
|
+
}
|
|
12418
|
+
if (er.SuggestedValues && er.SuggestedValues.length > 0) {
|
|
12419
|
+
lines.push(`**Did You Mean:** ${er.SuggestedValues.map(v => `\`${v}\``).join(', ')}`);
|
|
12420
|
+
}
|
|
12421
|
+
if (er.InvalidParams && er.InvalidParams.length > 0) {
|
|
12422
|
+
lines.push('**Invalid Parameters:**');
|
|
12423
|
+
for (const ip of er.InvalidParams) {
|
|
12424
|
+
lines.push(`• \`${ip.ParamName}\`: ${ip.Reason}`);
|
|
12425
|
+
}
|
|
12426
|
+
}
|
|
12427
|
+
if (er.ValidParameterExample) {
|
|
12428
|
+
lines.push(`**Valid Example:** \`${JSON.stringify(er.ValidParameterExample)}\``);
|
|
12429
|
+
}
|
|
12430
|
+
if (er.SuggestedNextActions && er.SuggestedNextActions.length > 0) {
|
|
12431
|
+
lines.push(`**Suggested Next Actions:** ${er.SuggestedNextActions.map(v => `\`${v}\``).join(', ')}`);
|
|
12432
|
+
}
|
|
12433
|
+
}
|
|
11369
12434
|
// Format output params as bullet list. An exempt action's values go out verbatim.
|
|
11370
12435
|
if (a.params && a.params.length > 0) {
|
|
11371
12436
|
const crush = !this._actionResultCrush?.exemptActions?.has(a.actionName);
|
|
@@ -11374,7 +12439,11 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11374
12439
|
lines.push(`• \`${p.Name}\`: ${this.formatParamValueForResult(p.Value, 0, crush)}`);
|
|
11375
12440
|
}
|
|
11376
12441
|
}
|
|
11377
|
-
|
|
12442
|
+
const formatted = lines.join('\n');
|
|
12443
|
+
if (a.trustLevel === 'Untrusted' || a.trustLevel === 'SemiTrusted') {
|
|
12444
|
+
return WrapUntrustedExternalData(formatted, `action:${a.actionName}`, a.trustLevel);
|
|
12445
|
+
}
|
|
12446
|
+
return formatted;
|
|
11378
12447
|
}).join('\n\n');
|
|
11379
12448
|
}
|
|
11380
12449
|
/**
|
|
@@ -11395,6 +12464,16 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11395
12464
|
// Status / error from the agent run
|
|
11396
12465
|
const status = result.agentRun?.Status || (result.success ? 'Completed' : 'Failed');
|
|
11397
12466
|
lines.push(`**Status:** ${status}`);
|
|
12467
|
+
if (result.agentRun?.FinalStep) {
|
|
12468
|
+
lines.push(`**Final step:** ${result.agentRun.FinalStep}`);
|
|
12469
|
+
}
|
|
12470
|
+
if (result.agentRun?.Message) {
|
|
12471
|
+
lines.push(`**Message:** ${result.agentRun.Message}`);
|
|
12472
|
+
}
|
|
12473
|
+
const formSummary = FormatResponseFormSummary(result.responseForm);
|
|
12474
|
+
if (formSummary) {
|
|
12475
|
+
lines.push(`**Form:**\n${formSummary}`);
|
|
12476
|
+
}
|
|
11398
12477
|
if (!result.success && result.agentRun?.ErrorMessage) {
|
|
11399
12478
|
lines.push(`**Error:** ${result.agentRun.ErrorMessage}`);
|
|
11400
12479
|
}
|
|
@@ -11776,6 +12855,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11776
12855
|
this._templateEngineConfiguredForRun = false;
|
|
11777
12856
|
this._heldDecisions = undefined;
|
|
11778
12857
|
this._awaitingWorkflowTaskID = null;
|
|
12858
|
+
this._taintedSources = [];
|
|
11779
12859
|
// Resolve action-result compression config for this run (default on; opt out via
|
|
11780
12860
|
// crushActionResults: false in the agent-type prompt params).
|
|
11781
12861
|
this._actionResultCrush = this.resolveActionResultCrush(params);
|
|
@@ -11970,6 +13050,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11970
13050
|
Fields: ['Status', 'OriginatingAgentRunStepID'],
|
|
11971
13051
|
OrderBy: '__mj_CreatedAt DESC',
|
|
11972
13052
|
MaxRows: 1,
|
|
13053
|
+
SkipTotalRowCount: true,
|
|
11973
13054
|
ResultType: 'simple'
|
|
11974
13055
|
}, params.contextUser);
|
|
11975
13056
|
if (!requestResult.Success || requestResult.Results.length === 0) {
|
|
@@ -11988,6 +13069,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11988
13069
|
ExtraFilter: `ID='${request.OriginatingAgentRunStepID}'`,
|
|
11989
13070
|
Fields: ['StepType'],
|
|
11990
13071
|
MaxRows: 1,
|
|
13072
|
+
SkipTotalRowCount: true,
|
|
11991
13073
|
ResultType: 'simple'
|
|
11992
13074
|
}, params.contextUser);
|
|
11993
13075
|
const approved = stepResult.Success
|
|
@@ -12807,6 +13889,11 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12807
13889
|
// durable task graph. executeTasksStep detaches (see its doc comment).
|
|
12808
13890
|
case 'Tasks':
|
|
12809
13891
|
return await this.executeTasksStep(params, previousDecision);
|
|
13892
|
+
// Type assertion required because 'Handoff' is not part of the BaseAgentNextStep step
|
|
13893
|
+
// union — LoopAgentType.DetermineNextStep() emits it when an opted-in agent transfers
|
|
13894
|
+
// the conversation to another agent. executeHandoffStep records the step and ends Success.
|
|
13895
|
+
case 'Handoff':
|
|
13896
|
+
return await this.executeHandoffStep(params, previousDecision);
|
|
12810
13897
|
// Type assertion required because 'ClientTools' is not part of the BaseAgentNextStep
|
|
12811
13898
|
// step union — LoopAgentType.DetermineNextStep() emits it when the LLM chooses client tools.
|
|
12812
13899
|
case 'ClientTools':
|
|
@@ -12953,6 +14040,64 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12953
14040
|
*
|
|
12954
14041
|
* @private
|
|
12955
14042
|
*/
|
|
14043
|
+
/** Whether a step is a completion that carries a payload change, which is held until the completion is accepted. */
|
|
14044
|
+
static carriesCompletionChange(step) {
|
|
14045
|
+
return step.step === 'Success' && !!step.payloadChangeRequest;
|
|
14046
|
+
}
|
|
14047
|
+
/**
|
|
14048
|
+
* Applies a turn's `payloadChangeRequest` to `current` and returns the result; `current` is not
|
|
14049
|
+
* changed. Honours `PayloadSelfWritePaths`. A brand-new artifact whose payload is still the one
|
|
14050
|
+
* inherited from a prior run (or that uses `replaceElements`) is built on an empty object, so
|
|
14051
|
+
* keys from the previous artifact cannot bleed in.
|
|
14052
|
+
*/
|
|
14053
|
+
applyTurnPayloadChange(params, step, current, isUnmodifiedInheritedPayload) {
|
|
14054
|
+
const change = step.payloadChangeRequest;
|
|
14055
|
+
const allowedPaths = params.agent.PayloadSelfWritePaths
|
|
14056
|
+
? JSON.parse(params.agent.PayloadSelfWritePaths)
|
|
14057
|
+
: this.getDefaultPayloadSelfWritePaths();
|
|
14058
|
+
const basePayload = (step.artifactDirective?.behavior === 'create-new'
|
|
14059
|
+
&& (this._promptTurnCount <= 1 || isUnmodifiedInheritedPayload || Boolean(change.replaceElements)))
|
|
14060
|
+
? {}
|
|
14061
|
+
: current;
|
|
14062
|
+
const changeResult = this._payloadManager.applyAgentChangeRequest(basePayload, change, {
|
|
14063
|
+
validateChanges: true,
|
|
14064
|
+
logChanges: true,
|
|
14065
|
+
agentName: params.agent.Name,
|
|
14066
|
+
analyzeChanges: true,
|
|
14067
|
+
generateDiff: true,
|
|
14068
|
+
allowedPaths,
|
|
14069
|
+
verbose: params.verbose === true || IsVerboseLoggingEnabled()
|
|
14070
|
+
});
|
|
14071
|
+
if (changeResult.warnings.length > 0 && (params.verbose === true || IsVerboseLoggingEnabled())) {
|
|
14072
|
+
LogStatus(`Payload warnings: ${changeResult.warnings.join('; ')}`);
|
|
14073
|
+
}
|
|
14074
|
+
return changeResult;
|
|
14075
|
+
}
|
|
14076
|
+
/**
|
|
14077
|
+
* The payload a completion would leave behind: the committed payload with the completion's
|
|
14078
|
+
* change applied. Success validation (the minimum-execution check, then `FinalPayloadValidation`)
|
|
14079
|
+
* checks this draft, and it becomes the payload only if the completion is accepted. The
|
|
14080
|
+
* opt-in payload change check is not asked here: it never runs on a step that ends the run.
|
|
14081
|
+
*/
|
|
14082
|
+
buildCompletionDraft(params, step, committed, isUnmodifiedInheritedPayload) {
|
|
14083
|
+
const changeResult = this.applyTurnPayloadChange(params, step, committed, isUnmodifiedInheritedPayload);
|
|
14084
|
+
return { payload: changeResult.result, summary: this.buildPayloadChangeResultSummary(changeResult) };
|
|
14085
|
+
}
|
|
14086
|
+
/**
|
|
14087
|
+
* The payload a turn leaves behind. A held completion draft is committed only when the step is
|
|
14088
|
+
* still `Success` after validation; on a refusal the committed payload stands (a subclass that
|
|
14089
|
+
* set a payload of its own still wins). Without a draft, a subclass's `newPayload` wins as before.
|
|
14090
|
+
*/
|
|
14091
|
+
resolveTurnPayload(step, committed, draft) {
|
|
14092
|
+
if (!draft) {
|
|
14093
|
+
return { payload: step.newPayload || committed, committedDraft: false };
|
|
14094
|
+
}
|
|
14095
|
+
if (step.step === 'Success') {
|
|
14096
|
+
return { payload: step.newPayload || draft.payload, committedDraft: true };
|
|
14097
|
+
}
|
|
14098
|
+
const own = step.newPayload && step.newPayload !== draft.payload ? step.newPayload : undefined;
|
|
14099
|
+
return { payload: own || committed, committedDraft: false };
|
|
14100
|
+
}
|
|
12956
14101
|
async executePromptStep(params, config, previousDecision, stepCount = 0) {
|
|
12957
14102
|
// Decisions the last prompt held back: the step that carried them did not end the run, so
|
|
12958
14103
|
// answer them now, where this prompt will read the answers
|
|
@@ -13184,36 +14329,14 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
13184
14329
|
? {}
|
|
13185
14330
|
: payload; // Start with current payload
|
|
13186
14331
|
let currentStepPayloadChangeResult = undefined;
|
|
13187
|
-
|
|
13188
|
-
|
|
13189
|
-
|
|
13190
|
-
|
|
13191
|
-
|
|
13192
|
-
//
|
|
13193
|
-
// payload from a prior conversation run (even if read-only action steps ran first) or when
|
|
13194
|
-
// replaceElements is used with behavior='create-new', apply against a clean empty object
|
|
13195
|
-
// so keys from the previous artifact cannot bleed in.
|
|
13196
|
-
const basePayload = (initialNextStep.artifactDirective?.behavior === 'create-new'
|
|
13197
|
-
&& (this._promptTurnCount <= 1 || isUnmodifiedInheritedPayload || Boolean(initialNextStep.payloadChangeRequest.replaceElements)))
|
|
13198
|
-
? {}
|
|
13199
|
-
: payload;
|
|
13200
|
-
// Apply the changes to the payload with operation control
|
|
13201
|
-
const changeResult = this._payloadManager.applyAgentChangeRequest(basePayload, initialNextStep.payloadChangeRequest, {
|
|
13202
|
-
validateChanges: true,
|
|
13203
|
-
logChanges: true,
|
|
13204
|
-
agentName: params.agent.Name,
|
|
13205
|
-
analyzeChanges: true,
|
|
13206
|
-
generateDiff: true,
|
|
13207
|
-
allowedPaths: allowedPaths,
|
|
13208
|
-
verbose: params.verbose === true || IsVerboseLoggingEnabled()
|
|
13209
|
-
});
|
|
13210
|
-
if (changeResult.warnings.length > 0 && (params.verbose === true || IsVerboseLoggingEnabled())) {
|
|
13211
|
-
LogStatus(`Payload warnings: ${changeResult.warnings.join('; ')}`);
|
|
13212
|
-
}
|
|
13213
|
-
// Store payload change metadata for audit trail
|
|
13214
|
-
// This will be merged into outputData later
|
|
14332
|
+
// A completion's payload change is held as a draft until Success validation accepts it
|
|
14333
|
+
// (see buildCompletionDraft); every other step's change is applied now, as it always was.
|
|
14334
|
+
const holdsCompletionChange = BaseAgent.carriesCompletionChange(initialNextStep);
|
|
14335
|
+
if (initialNextStep.payloadChangeRequest && !holdsCompletionChange) {
|
|
14336
|
+
const changeResult = this.applyTurnPayloadChange(params, initialNextStep, payload, isUnmodifiedInheritedPayload);
|
|
14337
|
+
// Store payload change metadata for audit trail; merged into outputData later
|
|
13215
14338
|
currentStepPayloadChangeResult = this.buildPayloadChangeResultSummary(changeResult);
|
|
13216
|
-
//
|
|
14339
|
+
// The changeResult already respects the allowed paths
|
|
13217
14340
|
finalPayload = changeResult.result;
|
|
13218
14341
|
// Opt-in payload change check: asks whether the flagged changes were intended. It never
|
|
13219
14342
|
// reverts or blocks a change; the agent reads the result on its next turn.
|
|
@@ -13297,11 +14420,22 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
13297
14420
|
const agentTypePromptParams = promptParams.data?.__agentTypePromptParams;
|
|
13298
14421
|
await this.processTurnDecisions(decisions, initialNextStep, finalPayload, agentTypePromptParams, params);
|
|
13299
14422
|
}
|
|
14423
|
+
// A completion's change is validated as a draft (the committed payload with the change
|
|
14424
|
+
// applied), and committed only if the completion is accepted.
|
|
14425
|
+
const draft = holdsCompletionChange && initialNextStep.step === 'Success'
|
|
14426
|
+
? this.buildCompletionDraft(params, initialNextStep, finalPayload, finalPayload === params.payload)
|
|
14427
|
+
: undefined;
|
|
14428
|
+
currentStepPayloadChangeResult = draft?.summary ?? currentStepPayloadChangeResult;
|
|
13300
14429
|
// now that we have processed the payload, we can process the next step which does validation and changes the next step if
|
|
13301
14430
|
// validation fails
|
|
13302
|
-
const updatedNextStep = await this.processNextStep(initialNextStep, params, config.agentType, promptResult, finalPayload, stepEntity);
|
|
14431
|
+
const updatedNextStep = await this.processNextStep(initialNextStep, params, config.agentType, promptResult, draft ? draft.payload : finalPayload, stepEntity);
|
|
13303
14432
|
// sub-classes may have modified the payload, and we allow that, and so we need to update finalPayload to map to the updatedNextStep.newPayload
|
|
13304
|
-
|
|
14433
|
+
const resolved = this.resolveTurnPayload(updatedNextStep, finalPayload, draft);
|
|
14434
|
+
finalPayload = resolved.payload;
|
|
14435
|
+
const discardedCompletionChange = holdsCompletionChange && !resolved.committedDraft;
|
|
14436
|
+
if (discardedCompletionChange && currentStepPayloadChangeResult) {
|
|
14437
|
+
currentStepPayloadChangeResult = { ...currentStepPayloadChangeResult, applied: { additions: 0, updates: 0, deletions: 0 } };
|
|
14438
|
+
}
|
|
13305
14439
|
// Prepare output data, these are simple elements of the state that are not typically
|
|
13306
14440
|
// included in payload but are helpful. We do not include the prompt result here
|
|
13307
14441
|
// or the payload as those are stored already(prompt result via TargetLogID -> MJAIPromptRunEntityExtended)
|
|
@@ -13315,6 +14449,10 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
13315
14449
|
...(currentStepPayloadChangeResult && {
|
|
13316
14450
|
payloadChangeResult: currentStepPayloadChangeResult
|
|
13317
14451
|
}),
|
|
14452
|
+
// A completion's change that was not applied because the completion was refused
|
|
14453
|
+
...(discardedCompletionChange && {
|
|
14454
|
+
payloadChangeDiscarded: 'The payload change was sent with a completion that was refused, so it was not applied.'
|
|
14455
|
+
}),
|
|
13318
14456
|
// Include scratchpad snapshot after changes for audit/training data
|
|
13319
14457
|
...(this._scratchpadManager.HasContent() && {
|
|
13320
14458
|
scratchpad: this._scratchpadManager.ToJSON()
|
|
@@ -13579,6 +14717,8 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
13579
14717
|
subAgentName: subAgentRequest.name,
|
|
13580
14718
|
message: subAgentRequest.message,
|
|
13581
14719
|
terminateAfter: subAgentRequest.terminateAfter,
|
|
14720
|
+
...(subAgentRequest.resumeRunId ? { resumeRunId: subAgentRequest.resumeRunId } : {}),
|
|
14721
|
+
...(subAgentRequest.presetName ? { presetName: subAgentRequest.presetName } : {}),
|
|
13582
14722
|
parentAgentHierarchy: this._agentHierarchy
|
|
13583
14723
|
};
|
|
13584
14724
|
// Get sub-agent entity to access payload paths. Prefer the entity the caller already
|
|
@@ -13620,6 +14760,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
13620
14760
|
// Child sub-agents don't use context messages (they inherit payload directly)
|
|
13621
14761
|
const subAgentResult = await this.ExecuteSubAgent(params, subAgentRequest, subAgentEntity, stepEntity, scopedPayload, undefined, // No context message for child sub-agents
|
|
13622
14762
|
stepCount);
|
|
14763
|
+
this.absorbSubAgentTaint(subAgentRequest.name, subAgentResult, stepEntity?.StepNumber ?? (stepCount + 1));
|
|
13623
14764
|
let mergedPayload = previousDecision.newPayload; // Start with the original payload
|
|
13624
14765
|
let currentStepPayloadChangeResult = undefined;
|
|
13625
14766
|
if (subAgentResult.success) {
|
|
@@ -13761,27 +14902,12 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
13761
14902
|
payloadChangeResult: currentStepPayloadChangeResult
|
|
13762
14903
|
})
|
|
13763
14904
|
};
|
|
13764
|
-
//
|
|
13765
|
-
await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
|
|
13766
|
-
// Check if sub-agent returned a Chat step
|
|
14905
|
+
// Check if sub-agent returned a Chat step (handled before finalizeStepEntity so Consult can update outputData)
|
|
13767
14906
|
if (subAgentResult.agentRun?.FinalStep === 'Chat') {
|
|
13768
|
-
|
|
13769
|
-
// This allows parent agents to remap Chat -> Success/Failed/Retry if configured
|
|
13770
|
-
const chatStep = {
|
|
13771
|
-
step: 'Chat',
|
|
13772
|
-
terminate: true,
|
|
13773
|
-
message: subAgentResult.agentRun?.Message || null,
|
|
13774
|
-
previousPayload: previousDecision?.newPayload,
|
|
13775
|
-
newPayload: mergedPayload, // Preserve sub-agent payload changes
|
|
13776
|
-
responseForm: subAgentResult.responseForm,
|
|
13777
|
-
actionableCommands: subAgentResult.actionableCommands,
|
|
13778
|
-
automaticCommands: subAgentResult.automaticCommands,
|
|
13779
|
-
artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective
|
|
13780
|
-
};
|
|
13781
|
-
// Validate through parent's ChatHandlingOption (if configured)
|
|
13782
|
-
// This ensures parent agents can override child Chat steps
|
|
13783
|
-
return await this.validateChatNextStep(params, chatStep, mergedPayload, this._agentRun, stepEntity);
|
|
14907
|
+
return await this.handleSingleSubAgentChatStep(params, previousDecision, subAgentRequest, subAgentEntity, undefined, subAgentResult, mergedPayload, stepEntity, outputData);
|
|
13784
14908
|
}
|
|
14909
|
+
// Finalize step entity
|
|
14910
|
+
await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
|
|
13785
14911
|
// When a sub-agent (e.g. Workflow Planner) submits a durable task graph, its run parks
|
|
13786
14912
|
// with Status === 'Paused'. Propagate the parked state to the parent run and terminate
|
|
13787
14913
|
// immediately with the sub-agent's workflow launch message so the parent orchestrator
|
|
@@ -13801,44 +14927,14 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
13801
14927
|
responseForm: subAgentResult.responseForm,
|
|
13802
14928
|
actionableCommands: subAgentResult.actionableCommands,
|
|
13803
14929
|
automaticCommands: subAgentResult.automaticCommands,
|
|
13804
|
-
artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective
|
|
14930
|
+
artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective,
|
|
14931
|
+
handoff: undefined
|
|
13805
14932
|
};
|
|
13806
14933
|
}
|
|
13807
14934
|
// Add user message with the sub-agent results using markdown format
|
|
13808
14935
|
// and expiration metadata so it persists across multiple prompt turns
|
|
13809
14936
|
const resultMessage = this.formatSubAgentResultAsMarkdown(subAgentRequest.name, subAgentResult);
|
|
13810
|
-
|
|
13811
|
-
turnAdded: this._promptTurnCount,
|
|
13812
|
-
messageType: 'sub-agent-result',
|
|
13813
|
-
subAgentName: subAgentRequest.name,
|
|
13814
|
-
subAgentId: subAgentEntity.ID,
|
|
13815
|
-
// Default: keep sub-agent results for 3 turns then remove
|
|
13816
|
-
expirationTurns: 3,
|
|
13817
|
-
expirationMode: 'Remove'
|
|
13818
|
-
};
|
|
13819
|
-
// Apply global override if configured
|
|
13820
|
-
if (params.messageExpirationOverride) {
|
|
13821
|
-
const override = params.messageExpirationOverride;
|
|
13822
|
-
if (override.expirationTurns != null) {
|
|
13823
|
-
subAgentMetadata.expirationTurns = override.expirationTurns;
|
|
13824
|
-
subAgentMetadata.expirationMode = override.expirationMode || 'Remove';
|
|
13825
|
-
subAgentMetadata.compactMode = override.compactMode;
|
|
13826
|
-
subAgentMetadata.compactLength = override.compactLength;
|
|
13827
|
-
subAgentMetadata.compactPromptId = override.compactPromptId;
|
|
13828
|
-
}
|
|
13829
|
-
}
|
|
13830
|
-
if (previousDecision?.nativeTurn?.sendResultsNatively && subAgentRequest.toolCallId) {
|
|
13831
|
-
// the delegate_to_* call is answered as a tool result.
|
|
13832
|
-
this.PushToolResultTurn(params, BuildToolResultTurn([...this.payloadToolResult(previousDecision), {
|
|
13833
|
-
toolCallId: subAgentRequest.toolCallId,
|
|
13834
|
-
toolName: `${SUB_AGENT_TOOL_PREFIX}${SanitizeToolName(subAgentRequest.name)}`,
|
|
13835
|
-
content: resultMessage,
|
|
13836
|
-
isError: !subAgentResult.success
|
|
13837
|
-
}], subAgentMetadata));
|
|
13838
|
-
}
|
|
13839
|
-
else {
|
|
13840
|
-
params.conversationMessages.push({ role: 'user', content: resultMessage, metadata: subAgentMetadata });
|
|
13841
|
-
}
|
|
14937
|
+
this.pushSubAgentConversationMessage(params, previousDecision, subAgentRequest, subAgentEntity, resultMessage, 'sub-agent-result', !subAgentResult.success);
|
|
13842
14938
|
// Update the agent run's current payload with the merged result
|
|
13843
14939
|
if (this._agentRun) {
|
|
13844
14940
|
this._agentRun.FinalPayloadObject = mergedPayload;
|
|
@@ -13864,7 +14960,8 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
13864
14960
|
// terminates the parent run directly (shouldTerminate=true), carry the terminal
|
|
13865
14961
|
// sub-agent's directive if the parent did not specify one.
|
|
13866
14962
|
artifactDirective: previousDecision?.artifactDirective
|
|
13867
|
-
?? (shouldTerminate ? subAgentResult.artifactDirective : undefined)
|
|
14963
|
+
?? (shouldTerminate ? subAgentResult.artifactDirective : undefined),
|
|
14964
|
+
handoff: undefined
|
|
13868
14965
|
};
|
|
13869
14966
|
}
|
|
13870
14967
|
catch (error) {
|
|
@@ -13944,11 +15041,23 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
13944
15041
|
};
|
|
13945
15042
|
}
|
|
13946
15043
|
const resolved = this.resolveSubAgentByName(params, name, previousDecision.taskGraph?.folded === true);
|
|
13947
|
-
if (resolved?.relationship) {
|
|
13948
|
-
return await this.executeRelatedSubAgentStep(params, previousDecision, resolved.subAgentEntity, resolved.relationship, parentStepId, subAgentPayloadOverride, stepCount);
|
|
13949
|
-
}
|
|
13950
15044
|
if (resolved) {
|
|
13951
|
-
|
|
15045
|
+
const canonicalName = resolved.subAgentEntity.Name || name;
|
|
15046
|
+
const canonicalDecision = canonicalName !== name
|
|
15047
|
+
? {
|
|
15048
|
+
...previousDecision,
|
|
15049
|
+
...(previousDecision.subAgent
|
|
15050
|
+
? { subAgent: { ...previousDecision.subAgent, name: canonicalName } }
|
|
15051
|
+
: {}),
|
|
15052
|
+
...(previousDecision.subAgents
|
|
15053
|
+
? { subAgents: [{ ...subAgentRequest, name: canonicalName }] }
|
|
15054
|
+
: {}),
|
|
15055
|
+
}
|
|
15056
|
+
: previousDecision;
|
|
15057
|
+
if (resolved.relationship) {
|
|
15058
|
+
return await this.executeRelatedSubAgentStep(params, canonicalDecision, resolved.subAgentEntity, resolved.relationship, parentStepId, subAgentPayloadOverride, stepCount);
|
|
15059
|
+
}
|
|
15060
|
+
return await this.executeChildSubAgentStep(params, canonicalDecision, parentStepId, subAgentPayloadOverride, stepCount, resolved.subAgentEntity);
|
|
13952
15061
|
}
|
|
13953
15062
|
// Execution-time resolution failure. Count it against the shared validation-retry cap
|
|
13954
15063
|
// (MAX_VALIDATION_RETRIES) so a model that keeps picking an unresolvable sub-agent fails
|
|
@@ -13986,19 +15095,28 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
13986
15095
|
*/
|
|
13987
15096
|
resolveSubAgentByName(params, name, allowAnyActiveAgent = false) {
|
|
13988
15097
|
const normalized = name.trim().toLowerCase();
|
|
13989
|
-
const
|
|
13990
|
-
|
|
13991
|
-
|
|
15098
|
+
const activeChildAgents = AIEngine.Instance.Agents.filter(a => UUIDsEqual(a.ParentID, params.agent.ID) && a.Status === 'Active');
|
|
15099
|
+
const childAgent = activeChildAgents.find(a => a.Name.trim().toLowerCase() === normalized)
|
|
15100
|
+
?? this.matchNamedBySanitizedToolName(name, activeChildAgents, true).match;
|
|
13992
15101
|
if (childAgent) {
|
|
13993
15102
|
return { subAgentEntity: childAgent };
|
|
13994
15103
|
}
|
|
13995
15104
|
const activeRelationships = AIEngine.Instance.AgentRelationships.filter(ar => UUIDsEqual(ar.AgentID, params.agent.ID) && ar.Status === 'Active');
|
|
15105
|
+
const relatedPairs = [];
|
|
13996
15106
|
for (const rel of activeRelationships) {
|
|
13997
|
-
const relatedAgent = AIEngine.Instance.Agents.find(a => UUIDsEqual(a.ID, rel.SubAgentID) &&
|
|
13998
|
-
a.Status === 'Active' &&
|
|
13999
|
-
a.Name.trim().toLowerCase() === normalized);
|
|
15107
|
+
const relatedAgent = AIEngine.Instance.Agents.find(a => UUIDsEqual(a.ID, rel.SubAgentID) && a.Status === 'Active');
|
|
14000
15108
|
if (relatedAgent) {
|
|
14001
|
-
|
|
15109
|
+
if (relatedAgent.Name.trim().toLowerCase() === normalized) {
|
|
15110
|
+
return { subAgentEntity: relatedAgent, relationship: rel };
|
|
15111
|
+
}
|
|
15112
|
+
relatedPairs.push({ agent: relatedAgent, rel });
|
|
15113
|
+
}
|
|
15114
|
+
}
|
|
15115
|
+
const sanitizedRelated = this.matchNamedBySanitizedToolName(name, relatedPairs.map(p => p.agent), true).match;
|
|
15116
|
+
if (sanitizedRelated) {
|
|
15117
|
+
const matchedPair = relatedPairs.find(p => UUIDsEqual(p.agent.ID, sanitizedRelated.ID));
|
|
15118
|
+
if (matchedPair) {
|
|
15119
|
+
return { subAgentEntity: matchedPair.agent, relationship: matchedPair.rel };
|
|
14002
15120
|
}
|
|
14003
15121
|
}
|
|
14004
15122
|
// 3) Runtime-granted sub-agents (skill activation / caller subAgentChanges): resolve from
|
|
@@ -14007,7 +15125,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14007
15125
|
// or not active") — and because the catalog keeps offering it, the model re-picks the same
|
|
14008
15126
|
// sub-agent forever (observed live: Research Agent looping 36+ turns on the skill-granted
|
|
14009
15127
|
// Infographic Agent). No relationship row exists for these, so they dispatch child-style.
|
|
14010
|
-
const
|
|
15128
|
+
const effectivePool = this.getEffectiveSubAgentsForValidation(params.agent.ID).filter(a => a.Status === 'Active');
|
|
15129
|
+
const effectiveAgent = effectivePool.find(a => a.Name.trim().toLowerCase() === normalized)
|
|
15130
|
+
?? this.matchNamedBySanitizedToolName(name, effectivePool, true).match;
|
|
14011
15131
|
if (effectiveAgent) {
|
|
14012
15132
|
return { subAgentEntity: effectiveAgent };
|
|
14013
15133
|
}
|
|
@@ -14016,7 +15136,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14016
15136
|
// LoopAgentType folds that 1-node graph into an in-run Sub-Agent step (`taskGraph.folded === true`),
|
|
14017
15137
|
// so allow resolving any active agent in AIEngine.Instance.Agents.
|
|
14018
15138
|
if (allowAnyActiveAgent) {
|
|
14019
|
-
const
|
|
15139
|
+
const allActive = AIEngine.Instance.Agents.filter(a => a.Status === 'Active');
|
|
15140
|
+
const anyActiveAgent = allActive.find(a => a.Name.trim().toLowerCase() === normalized)
|
|
15141
|
+
?? this.matchNamedBySanitizedToolName(name, allActive, true).match;
|
|
14020
15142
|
if (anyActiveAgent) {
|
|
14021
15143
|
return { subAgentEntity: anyActiveAgent };
|
|
14022
15144
|
}
|
|
@@ -14095,13 +15217,16 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14095
15217
|
return undefined;
|
|
14096
15218
|
}
|
|
14097
15219
|
const { subAgentEntity, relationship } = resolved;
|
|
15220
|
+
const canonicalRequest = subAgentEntity.Name && request.name !== subAgentEntity.Name
|
|
15221
|
+
? { ...request, name: subAgentEntity.Name }
|
|
15222
|
+
: request;
|
|
14098
15223
|
this.safeOnProgress(params, {
|
|
14099
15224
|
step: 'subagent_execution',
|
|
14100
|
-
message: this.formatHierarchicalMessage(`Delegating to parallel sub-agent ${
|
|
15225
|
+
message: this.formatHierarchicalMessage(`Delegating to parallel sub-agent ${canonicalRequest.name}`),
|
|
14101
15226
|
metadata: {
|
|
14102
15227
|
agentName: params.agent.Name,
|
|
14103
|
-
subAgentName:
|
|
14104
|
-
reason:
|
|
15228
|
+
subAgentName: canonicalRequest.name,
|
|
15229
|
+
reason: canonicalRequest.message,
|
|
14105
15230
|
relationshipType: relationship ? 'related' : 'child',
|
|
14106
15231
|
stepCount: stepCount + 1,
|
|
14107
15232
|
hierarchicalStep: this.buildHierarchicalStep(stepCount + 1, this._parentStepCounts)
|
|
@@ -14111,13 +15236,13 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14111
15236
|
// single-delegation push above for why framework prose must not be stored as assistant turns.
|
|
14112
15237
|
// skipped when the call is natively recorded and will be answered by a tool result (see the
|
|
14113
15238
|
// single-delegation push for why a user turn between call and result must not be inserted).
|
|
14114
|
-
if (!(nativeResults &&
|
|
15239
|
+
if (!(nativeResults && canonicalRequest.toolCallId)) {
|
|
14115
15240
|
params.conversationMessages.push({
|
|
14116
15241
|
role: 'user',
|
|
14117
|
-
content: `[You delegated this task to the parallel sub-agent "${
|
|
15242
|
+
content: `[You delegated this task to the parallel sub-agent "${canonicalRequest.name}". Reason: ${canonicalRequest.message}]`
|
|
14118
15243
|
});
|
|
14119
15244
|
}
|
|
14120
|
-
return { request:
|
|
15245
|
+
return { request: canonicalRequest, subAgentEntity, relationship };
|
|
14121
15246
|
}
|
|
14122
15247
|
/**
|
|
14123
15248
|
* Computes the per-sub-agent input payload + context message based on whether
|
|
@@ -14217,13 +15342,30 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14217
15342
|
return executions
|
|
14218
15343
|
.map(execution => {
|
|
14219
15344
|
const statusEmoji = execution.result.success ? '✅' : '❌';
|
|
14220
|
-
const
|
|
14221
|
-
|
|
14222
|
-
`*
|
|
15345
|
+
const lines = [
|
|
15346
|
+
`${statusEmoji} **Sub-Agent: ${execution.request.name}**`,
|
|
15347
|
+
`* Message: "${execution.request.message}"`,
|
|
15348
|
+
`* Status: ${execution.result.agentRun?.FinalStep || 'Failed'}`
|
|
15349
|
+
];
|
|
15350
|
+
const isChat = execution.result.agentRun?.FinalStep === 'Chat';
|
|
15351
|
+
const question = execution.result.agentRun?.Message;
|
|
15352
|
+
if (execution.consult) {
|
|
15353
|
+
const maxRounds = execution.maxConsultRounds ?? DEFAULT_MAX_SUB_AGENT_CONSULT_ROUNDS;
|
|
15354
|
+
lines.push(`* Question (round ${execution.consult.round} of ${maxRounds}): ${question?.trim() ? question : '(no message provided)'}`);
|
|
15355
|
+
const formSummary = FormatResponseFormSummary(execution.result.responseForm);
|
|
15356
|
+
if (formSummary) {
|
|
15357
|
+
lines.push(`* Form:\n${formSummary}`);
|
|
15358
|
+
}
|
|
15359
|
+
lines.push(`* Child run ID: ${execution.consult.childRunId || '(unknown)'}`);
|
|
15360
|
+
lines.push(`* To answer, call ${execution.request.name} again with resumeRunId: "${execution.consult.childRunId}" and your answer as the message.`);
|
|
15361
|
+
}
|
|
15362
|
+
else if (isChat && question?.trim()) {
|
|
15363
|
+
lines.push(`* Question: ${question}`);
|
|
15364
|
+
}
|
|
14223
15365
|
if (execution.result.agentRun?.ErrorMessage) {
|
|
14224
|
-
|
|
15366
|
+
lines.push(`* Error: ${execution.result.agentRun.ErrorMessage}`);
|
|
14225
15367
|
}
|
|
14226
|
-
return
|
|
15368
|
+
return lines.join('\n');
|
|
14227
15369
|
})
|
|
14228
15370
|
.join('\n\n---\n\n');
|
|
14229
15371
|
}
|
|
@@ -14270,6 +15412,8 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14270
15412
|
subAgentName: request.name,
|
|
14271
15413
|
message: request.message,
|
|
14272
15414
|
terminateAfter: request.terminateAfter,
|
|
15415
|
+
...(request.resumeRunId ? { resumeRunId: request.resumeRunId } : {}),
|
|
15416
|
+
...(request.presetName ? { presetName: request.presetName } : {}),
|
|
14273
15417
|
parentAgentHierarchy: this._agentHierarchy,
|
|
14274
15418
|
relationshipType: relationship ? 'related' : 'child'
|
|
14275
15419
|
},
|
|
@@ -14326,6 +15470,30 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14326
15470
|
this._mediaOutputs.push(...execution.result.mediaOutputs);
|
|
14327
15471
|
if (execution.result.fileOutputs?.length)
|
|
14328
15472
|
this._fileOutputs.push(...execution.result.fileOutputs);
|
|
15473
|
+
if (execution.result.agentRun?.FinalStep === 'Chat') {
|
|
15474
|
+
const resolvedOption = this.resolveSubAgentChatHandlingOption(params.agent, execution.relationship);
|
|
15475
|
+
if (this.isSubAgentConsultActive(resolvedOption, params)) {
|
|
15476
|
+
const round = (this._subAgentConsultRounds.get(execution.subAgentEntity.ID) ?? 0) + 1;
|
|
15477
|
+
this._subAgentConsultRounds.set(execution.subAgentEntity.ID, round);
|
|
15478
|
+
const maxRounds = params.agent.MaxSubAgentConsultRounds ?? DEFAULT_MAX_SUB_AGENT_CONSULT_ROUNDS;
|
|
15479
|
+
if (round <= maxRounds) {
|
|
15480
|
+
const childRunId = execution.result.agentRun?.ID || '';
|
|
15481
|
+
const question = execution.result.agentRun?.Message || null;
|
|
15482
|
+
const consultRecord = {
|
|
15483
|
+
childRunId,
|
|
15484
|
+
subAgentId: execution.subAgentEntity.ID,
|
|
15485
|
+
subAgentName: execution.request.name,
|
|
15486
|
+
round,
|
|
15487
|
+
question
|
|
15488
|
+
};
|
|
15489
|
+
if (childRunId) {
|
|
15490
|
+
this._openSubAgentConsults.set(childRunId, consultRecord);
|
|
15491
|
+
}
|
|
15492
|
+
execution.consult = consultRecord;
|
|
15493
|
+
execution.maxConsultRounds = maxRounds;
|
|
15494
|
+
}
|
|
15495
|
+
}
|
|
15496
|
+
}
|
|
14329
15497
|
const { mergedPayload: newMerged, stepPayloadAtEnd } = this.mergeParallelSubAgentResult(params, execution, mergedPayload);
|
|
14330
15498
|
mergedPayload = newMerged;
|
|
14331
15499
|
allExecutions.push(execution);
|
|
@@ -14344,6 +15512,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14344
15512
|
if (!execution.stepEntity)
|
|
14345
15513
|
return;
|
|
14346
15514
|
execution.stepEntity.PayloadAtEnd = this.serializePayloadAtEnd(stepPayloadAtEnd);
|
|
15515
|
+
const shouldTerminate = execution.request.terminateAfter === true && !execution.consult;
|
|
14347
15516
|
await this.finalizeStepEntity(execution.stepEntity, execution.result.success, execution.result.agentRun?.ErrorMessage, {
|
|
14348
15517
|
subAgentResult: {
|
|
14349
15518
|
success: execution.result.success,
|
|
@@ -14351,8 +15520,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14351
15520
|
errorMessage: execution.result.agentRun?.ErrorMessage,
|
|
14352
15521
|
stepCount: execution.result.agentRun?.Steps?.length || 0,
|
|
14353
15522
|
},
|
|
14354
|
-
shouldTerminate
|
|
14355
|
-
nextStep:
|
|
15523
|
+
shouldTerminate,
|
|
15524
|
+
nextStep: shouldTerminate ? 'success' : 'retry',
|
|
15525
|
+
...(execution.consult && { consult: execution.consult })
|
|
14356
15526
|
});
|
|
14357
15527
|
}
|
|
14358
15528
|
async executeParallelSubAgents(params, subAgentRequests, previousDecision, parentStepId, subAgentPayloadOverride, stepCount = 0) {
|
|
@@ -14392,9 +15562,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14392
15562
|
}
|
|
14393
15563
|
// Termination semantics: matches the single sub-agent path —
|
|
14394
15564
|
// `terminateAfter` triggers parent termination regardless of the child's
|
|
14395
|
-
// success/failure
|
|
14396
|
-
//
|
|
14397
|
-
const shouldTerminateParent = allExecutions.some(e => e.request.terminateAfter === true);
|
|
15565
|
+
// success/failure, EXCEPT when a Chat child is handled under Consult
|
|
15566
|
+
// (the parent must get its turn to answer).
|
|
15567
|
+
const shouldTerminateParent = allExecutions.some(e => e.request.terminateAfter === true && !e.consult);
|
|
14398
15568
|
const subAgentNames = allExecutions.map(e => e.request.name).join(', ');
|
|
14399
15569
|
return {
|
|
14400
15570
|
step: anyFailure ? 'Failed' : (shouldTerminateParent ? 'Success' : 'Retry'),
|
|
@@ -14406,6 +15576,134 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14406
15576
|
previousPayload: previousDecision.newPayload
|
|
14407
15577
|
};
|
|
14408
15578
|
}
|
|
15579
|
+
/**
|
|
15580
|
+
* Pushes a sub-agent result or consult message to the parent's conversation history,
|
|
15581
|
+
* answering natively-invoked `delegate_to_*` calls as a tool-result turn when applicable
|
|
15582
|
+
* and applying expiration defaults / overrides.
|
|
15583
|
+
*
|
|
15584
|
+
* @private
|
|
15585
|
+
*/
|
|
15586
|
+
pushSubAgentConversationMessage(params, previousDecision, subAgentRequest, subAgentEntity, messageContent, messageType, isError) {
|
|
15587
|
+
const metadata = {
|
|
15588
|
+
turnAdded: this._promptTurnCount,
|
|
15589
|
+
messageType,
|
|
15590
|
+
subAgentName: subAgentRequest.name,
|
|
15591
|
+
subAgentId: subAgentEntity.ID,
|
|
15592
|
+
expirationTurns: 3,
|
|
15593
|
+
expirationMode: 'Remove'
|
|
15594
|
+
};
|
|
15595
|
+
if (params.messageExpirationOverride) {
|
|
15596
|
+
const override = params.messageExpirationOverride;
|
|
15597
|
+
if (override.expirationTurns != null) {
|
|
15598
|
+
metadata.expirationTurns = override.expirationTurns;
|
|
15599
|
+
metadata.expirationMode = override.expirationMode || 'Remove';
|
|
15600
|
+
metadata.compactMode = override.compactMode;
|
|
15601
|
+
metadata.compactLength = override.compactLength;
|
|
15602
|
+
metadata.compactPromptId = override.compactPromptId;
|
|
15603
|
+
}
|
|
15604
|
+
}
|
|
15605
|
+
if (previousDecision?.nativeTurn?.sendResultsNatively && subAgentRequest.toolCallId) {
|
|
15606
|
+
this.PushToolResultTurn(params, BuildToolResultTurn([
|
|
15607
|
+
...this.payloadToolResult(previousDecision),
|
|
15608
|
+
{
|
|
15609
|
+
toolCallId: subAgentRequest.toolCallId,
|
|
15610
|
+
toolName: `${SUB_AGENT_TOOL_PREFIX}${SanitizeToolName(subAgentRequest.name)}`,
|
|
15611
|
+
content: messageContent,
|
|
15612
|
+
isError
|
|
15613
|
+
}
|
|
15614
|
+
], metadata));
|
|
15615
|
+
}
|
|
15616
|
+
else {
|
|
15617
|
+
params.conversationMessages.push({
|
|
15618
|
+
role: 'user',
|
|
15619
|
+
content: messageContent,
|
|
15620
|
+
metadata
|
|
15621
|
+
});
|
|
15622
|
+
}
|
|
15623
|
+
}
|
|
15624
|
+
/**
|
|
15625
|
+
* Unified handler for a single sub-agent (child, related, or runtime-granted) that
|
|
15626
|
+
* finished with `FinalStep === 'Chat'`. Resolves `ChatHandlingOption` for the pairing,
|
|
15627
|
+
* runs the consult flow when `'Consult'` is active and within the per-sub-agent round
|
|
15628
|
+
* bound, and otherwise finalizes the step and delegates to `validateChatNextStep`.
|
|
15629
|
+
*
|
|
15630
|
+
* @private
|
|
15631
|
+
*/
|
|
15632
|
+
async handleSingleSubAgentChatStep(params, previousDecision, subAgentRequest, subAgentEntity, relationship, subAgentResult, mergedPayload, stepEntity, outputData) {
|
|
15633
|
+
const resolvedOption = this.resolveSubAgentChatHandlingOption(params.agent, relationship);
|
|
15634
|
+
if (this.isSubAgentConsultActive(resolvedOption, params)) {
|
|
15635
|
+
const round = (this._subAgentConsultRounds.get(subAgentEntity.ID) ?? 0) + 1;
|
|
15636
|
+
this._subAgentConsultRounds.set(subAgentEntity.ID, round);
|
|
15637
|
+
const maxRounds = params.agent.MaxSubAgentConsultRounds ?? DEFAULT_MAX_SUB_AGENT_CONSULT_ROUNDS;
|
|
15638
|
+
const childRunId = subAgentResult.agentRun?.ID || '';
|
|
15639
|
+
const question = subAgentResult.agentRun?.Message || null;
|
|
15640
|
+
const consultRecord = {
|
|
15641
|
+
childRunId,
|
|
15642
|
+
subAgentId: subAgentEntity.ID,
|
|
15643
|
+
subAgentName: subAgentRequest.name,
|
|
15644
|
+
round,
|
|
15645
|
+
question
|
|
15646
|
+
};
|
|
15647
|
+
if (childRunId) {
|
|
15648
|
+
this._openSubAgentConsults.set(childRunId, consultRecord);
|
|
15649
|
+
}
|
|
15650
|
+
outputData.consult = consultRecord;
|
|
15651
|
+
if (round <= maxRounds) {
|
|
15652
|
+
outputData.shouldTerminate = false;
|
|
15653
|
+
outputData.nextStep = 'retry';
|
|
15654
|
+
await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
|
|
15655
|
+
const consultMessage = FormatSubAgentConsultMessage({
|
|
15656
|
+
subAgentName: subAgentRequest.name,
|
|
15657
|
+
round,
|
|
15658
|
+
maxRounds,
|
|
15659
|
+
question,
|
|
15660
|
+
responseForm: subAgentResult.responseForm,
|
|
15661
|
+
childRunId
|
|
15662
|
+
});
|
|
15663
|
+
this.pushSubAgentConversationMessage(params, previousDecision, subAgentRequest, subAgentEntity, consultMessage, 'sub-agent-consult', false);
|
|
15664
|
+
if (this._agentRun) {
|
|
15665
|
+
this._agentRun.FinalPayloadObject = mergedPayload;
|
|
15666
|
+
}
|
|
15667
|
+
this.warnIfDiscardingSubAgentArtifactDirective(subAgentResult, subAgentRequest.name);
|
|
15668
|
+
return {
|
|
15669
|
+
...subAgentResult,
|
|
15670
|
+
step: 'Success',
|
|
15671
|
+
errorMessage: undefined,
|
|
15672
|
+
terminate: false,
|
|
15673
|
+
previousPayload: previousDecision?.newPayload,
|
|
15674
|
+
newPayload: mergedPayload,
|
|
15675
|
+
artifactDirective: undefined,
|
|
15676
|
+
handoff: undefined
|
|
15677
|
+
};
|
|
15678
|
+
}
|
|
15679
|
+
}
|
|
15680
|
+
// Not under active Consult (or round exceeded bound): finalize step and validate/propagate Chat
|
|
15681
|
+
await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
|
|
15682
|
+
const chatStep = {
|
|
15683
|
+
step: 'Chat',
|
|
15684
|
+
terminate: true,
|
|
15685
|
+
message: subAgentResult.agentRun?.Message || null,
|
|
15686
|
+
previousPayload: previousDecision?.newPayload,
|
|
15687
|
+
newPayload: mergedPayload,
|
|
15688
|
+
responseForm: subAgentResult.responseForm,
|
|
15689
|
+
actionableCommands: subAgentResult.actionableCommands,
|
|
15690
|
+
automaticCommands: subAgentResult.automaticCommands,
|
|
15691
|
+
artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective
|
|
15692
|
+
};
|
|
15693
|
+
const effectiveOption = this.effectiveSubAgentChatHandlingOption(params.agent, relationship, params);
|
|
15694
|
+
const validatedStep = await this.validateChatNextStep(params, chatStep, mergedPayload, this._agentRun, stepEntity, effectiveOption);
|
|
15695
|
+
if (validatedStep.step === 'Chat' && effectiveOption === 'Consult' && this._depth === 0) {
|
|
15696
|
+
await this.raiseFeedbackRequest(params, stepEntity, chatStep);
|
|
15697
|
+
}
|
|
15698
|
+
else if (validatedStep.step === 'Retry') {
|
|
15699
|
+
const resultMessage = this.formatSubAgentResultAsMarkdown(subAgentRequest.name, subAgentResult);
|
|
15700
|
+
this.pushSubAgentConversationMessage(params, previousDecision, subAgentRequest, subAgentEntity, resultMessage, 'sub-agent-result', !subAgentResult.success);
|
|
15701
|
+
if (this._agentRun) {
|
|
15702
|
+
this._agentRun.FinalPayloadObject = mergedPayload;
|
|
15703
|
+
}
|
|
15704
|
+
}
|
|
15705
|
+
return validatedStep;
|
|
15706
|
+
}
|
|
14409
15707
|
/**
|
|
14410
15708
|
* Executes a related sub-agent step (AgentRelationships) and tracks it.
|
|
14411
15709
|
* Related agents use message-based communication with independent payloads.
|
|
@@ -14453,6 +15751,8 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14453
15751
|
subAgentName: subAgentRequest.name,
|
|
14454
15752
|
message: subAgentRequest.message,
|
|
14455
15753
|
terminateAfter: subAgentRequest.terminateAfter,
|
|
15754
|
+
...(subAgentRequest.resumeRunId ? { resumeRunId: subAgentRequest.resumeRunId } : {}),
|
|
15755
|
+
...(subAgentRequest.presetName ? { presetName: subAgentRequest.presetName } : {}),
|
|
14456
15756
|
parentAgentHierarchy: this._agentHierarchy,
|
|
14457
15757
|
relationshipType: 'related'
|
|
14458
15758
|
};
|
|
@@ -14560,27 +15860,12 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14560
15860
|
if (stepEntity) {
|
|
14561
15861
|
stepEntity.PayloadAtEnd = this.serializePayloadAtEnd(mergedPayload);
|
|
14562
15862
|
}
|
|
14563
|
-
//
|
|
14564
|
-
await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
|
|
14565
|
-
// Check if sub-agent returned a Chat step
|
|
15863
|
+
// Check if sub-agent returned a Chat step (handled before finalizeStepEntity so Consult can update outputData)
|
|
14566
15864
|
if (subAgentResult.agentRun?.FinalStep === 'Chat') {
|
|
14567
|
-
|
|
14568
|
-
// This allows parent agents to remap Chat -> Success/Failed/Retry if configured
|
|
14569
|
-
const chatStep = {
|
|
14570
|
-
step: 'Chat',
|
|
14571
|
-
terminate: true,
|
|
14572
|
-
message: subAgentResult.agentRun?.Message || null,
|
|
14573
|
-
previousPayload: previousDecision?.newPayload,
|
|
14574
|
-
newPayload: mergedPayload, // Preserve sub-agent payload changes
|
|
14575
|
-
responseForm: subAgentResult.responseForm,
|
|
14576
|
-
actionableCommands: subAgentResult.actionableCommands,
|
|
14577
|
-
automaticCommands: subAgentResult.automaticCommands,
|
|
14578
|
-
artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective
|
|
14579
|
-
};
|
|
14580
|
-
// Validate through parent's ChatHandlingOption (if configured)
|
|
14581
|
-
// This ensures parent agents can override child Chat steps
|
|
14582
|
-
return await this.validateChatNextStep(params, chatStep, mergedPayload, this._agentRun, stepEntity);
|
|
15865
|
+
return await this.handleSingleSubAgentChatStep(params, previousDecision, subAgentRequest, subAgentEntity, relationship, subAgentResult, mergedPayload, stepEntity, outputData);
|
|
14583
15866
|
}
|
|
15867
|
+
// Finalize step entity
|
|
15868
|
+
await this.finalizeStepEntity(stepEntity, subAgentResult.success, subAgentResult.agentRun?.ErrorMessage, outputData);
|
|
14584
15869
|
// When a related sub-agent submits a durable task graph, its run parks with Status === 'Paused'.
|
|
14585
15870
|
// Propagate the parked state to the parent run and terminate immediately with the sub-agent's
|
|
14586
15871
|
// workflow launch message instead of continuing the parent loop.
|
|
@@ -14599,46 +15884,14 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14599
15884
|
responseForm: subAgentResult.responseForm,
|
|
14600
15885
|
actionableCommands: subAgentResult.actionableCommands,
|
|
14601
15886
|
automaticCommands: subAgentResult.automaticCommands,
|
|
14602
|
-
artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective
|
|
15887
|
+
artifactDirective: previousDecision?.artifactDirective ?? subAgentResult.artifactDirective,
|
|
15888
|
+
handoff: undefined
|
|
14603
15889
|
};
|
|
14604
15890
|
}
|
|
14605
15891
|
// Add sub-agent result to conversation as user message using markdown format
|
|
14606
15892
|
// and expiration metadata so it persists across multiple prompt turns
|
|
14607
15893
|
const relatedResultMessage = this.formatSubAgentResultAsMarkdown(subAgentRequest.name, subAgentResult);
|
|
14608
|
-
|
|
14609
|
-
turnAdded: this._promptTurnCount,
|
|
14610
|
-
messageType: 'sub-agent-result',
|
|
14611
|
-
subAgentName: subAgentRequest.name,
|
|
14612
|
-
subAgentId: subAgentEntity.ID,
|
|
14613
|
-
expirationTurns: 3,
|
|
14614
|
-
expirationMode: 'Remove'
|
|
14615
|
-
};
|
|
14616
|
-
if (params.messageExpirationOverride) {
|
|
14617
|
-
const override = params.messageExpirationOverride;
|
|
14618
|
-
if (override.expirationTurns != null) {
|
|
14619
|
-
relatedMetadata.expirationTurns = override.expirationTurns;
|
|
14620
|
-
relatedMetadata.expirationMode = override.expirationMode || 'Remove';
|
|
14621
|
-
relatedMetadata.compactMode = override.compactMode;
|
|
14622
|
-
relatedMetadata.compactLength = override.compactLength;
|
|
14623
|
-
relatedMetadata.compactPromptId = override.compactPromptId;
|
|
14624
|
-
}
|
|
14625
|
-
}
|
|
14626
|
-
if (previousDecision.nativeTurn?.sendResultsNatively && subAgentRequest.toolCallId) {
|
|
14627
|
-
// the delegate_to_* call is answered as a tool result (same as the child path).
|
|
14628
|
-
this.PushToolResultTurn(params, BuildToolResultTurn([...this.payloadToolResult(previousDecision), {
|
|
14629
|
-
toolCallId: subAgentRequest.toolCallId,
|
|
14630
|
-
toolName: `${SUB_AGENT_TOOL_PREFIX}${SanitizeToolName(subAgentRequest.name)}`,
|
|
14631
|
-
content: relatedResultMessage,
|
|
14632
|
-
isError: !subAgentResult.success
|
|
14633
|
-
}], relatedMetadata));
|
|
14634
|
-
}
|
|
14635
|
-
else {
|
|
14636
|
-
params.conversationMessages.push({
|
|
14637
|
-
role: 'user',
|
|
14638
|
-
content: relatedResultMessage,
|
|
14639
|
-
metadata: relatedMetadata
|
|
14640
|
-
});
|
|
14641
|
-
}
|
|
15894
|
+
this.pushSubAgentConversationMessage(params, previousDecision, subAgentRequest, subAgentEntity, relatedResultMessage, 'sub-agent-result', !subAgentResult.success);
|
|
14642
15895
|
// Update the agent run's current payload
|
|
14643
15896
|
if (this._agentRun) {
|
|
14644
15897
|
this._agentRun.FinalPayloadObject = mergedPayload;
|
|
@@ -14658,7 +15911,8 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14658
15911
|
previousPayload: previousDecision?.newPayload,
|
|
14659
15912
|
newPayload: mergedPayload,
|
|
14660
15913
|
artifactDirective: previousDecision?.artifactDirective
|
|
14661
|
-
?? (shouldTerminate ? subAgentResult.artifactDirective : undefined)
|
|
15914
|
+
?? (shouldTerminate ? subAgentResult.artifactDirective : undefined),
|
|
15915
|
+
handoff: undefined
|
|
14662
15916
|
};
|
|
14663
15917
|
}
|
|
14664
15918
|
catch (error) {
|
|
@@ -14895,7 +16149,11 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14895
16149
|
async executeActionsStep(params, previousDecision, parentStepId, addConversationMessage = true, stepCount = 0, actionOptions) {
|
|
14896
16150
|
try {
|
|
14897
16151
|
const currentPayload = previousDecision?.newPayload || previousDecision?.previousPayload || params.payload;
|
|
14898
|
-
const
|
|
16152
|
+
const availableForExecution = this.getAvailableActionsForAgent(params.agent.ID);
|
|
16153
|
+
const actions = (previousDecision.actions || []).map((a) => {
|
|
16154
|
+
const matched = this.resolveActionEntityForAgent(a.name, availableForExecution, params, false);
|
|
16155
|
+
return matched && matched.Name !== a.name ? { ...a, name: matched.Name } : { ...a };
|
|
16156
|
+
});
|
|
14899
16157
|
// Check for cancellation before starting
|
|
14900
16158
|
if (params.cancellationToken?.aborted) {
|
|
14901
16159
|
throw new Error('Cancelled before action execution');
|
|
@@ -14978,14 +16236,12 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14978
16236
|
});
|
|
14979
16237
|
}
|
|
14980
16238
|
}
|
|
14981
|
-
const actionEngine = ActionEngineServer.Instance;
|
|
14982
16239
|
// Get the AIAgentAction metadata records for this agent (used for expiration settings)
|
|
14983
16240
|
const agentActions = AIEngine.Instance.AgentActions.filter(aa => UUIDsEqual(aa.AgentID, params.agent.ID));
|
|
14984
16241
|
// Use _effectiveActions which includes runtime action changes applied in gatherPromptTemplateData
|
|
14985
|
-
//
|
|
14986
|
-
|
|
14987
|
-
|
|
14988
|
-
: (actionEngine.Actions || []).filter(a => agentActions.some(aa => UUIDsEqual(aa.ActionID, a.ID)));
|
|
16242
|
+
// getEffectiveActionsForValidation falls back to the configured actions only when none were computed;
|
|
16243
|
+
// an empty computed list (a host's actionChanges removed every action) is authoritative
|
|
16244
|
+
const effectiveActions = this.getEffectiveActionsForValidation(params.agent.ID);
|
|
14989
16245
|
// Call agent type's pre-processing for actions
|
|
14990
16246
|
try {
|
|
14991
16247
|
const currentPayload = previousDecision?.newPayload || previousDecision?.previousPayload || params.payload;
|
|
@@ -14998,17 +16254,19 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14998
16254
|
}
|
|
14999
16255
|
// Track step numbers for parallel actions
|
|
15000
16256
|
let numActionsProcessed = 0;
|
|
15001
|
-
const baseStepNumber = (this._agentRun
|
|
16257
|
+
const baseStepNumber = (this._agentRun?.Steps?.length || 0) + 1;
|
|
15002
16258
|
// Execute all actions in parallel
|
|
15003
16259
|
let lastStep = undefined;
|
|
16260
|
+
const flowStepActions = this.getFlowStepActions(params.agent.ID);
|
|
15004
16261
|
const actionPromises = actions.map(async (aa) => {
|
|
15005
16262
|
// Find action entity from the effective actions (which includes runtime changes),
|
|
15006
|
-
// or from actions referenced directly by this agent's Flow steps (AIAgentStep.ActionID)
|
|
15007
|
-
let actionEntity =
|
|
15008
|
-
if (!actionEntity &&
|
|
15009
|
-
|
|
15010
|
-
|
|
15011
|
-
|
|
16263
|
+
// or from actions referenced directly by this agent's Flow steps (AIAgentStep.ActionID / Configuration.steps[])
|
|
16264
|
+
let actionEntity = this.resolveActionEntityForAgent(aa.name, effectiveActions, params, false);
|
|
16265
|
+
if (!actionEntity && flowStepActions.length > 0) {
|
|
16266
|
+
actionEntity = this.resolveActionEntityForAgent(aa.name, flowStepActions, params, false);
|
|
16267
|
+
}
|
|
16268
|
+
if (actionEntity && aa.name !== actionEntity.Name) {
|
|
16269
|
+
aa.name = actionEntity.Name;
|
|
15012
16270
|
}
|
|
15013
16271
|
if (!actionEntity) {
|
|
15014
16272
|
throw new Error(`Action "${aa.name}" Not Found for Agent "${params.agent.Name}". Available actions: ${effectiveActions.map(a => a.Name).join(', ')}`);
|
|
@@ -15077,14 +16335,25 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15077
16335
|
// Collect file outputs (PDF, Excel, Word, etc.) for post-run artifact processing
|
|
15078
16336
|
const fileOutputs = this.detectFileOutputs(outputParams);
|
|
15079
16337
|
this._fileOutputs.push(...fileOutputs);
|
|
16338
|
+
const trustLevel = this.resolveActionTrustLevel(result.action.name, result.actionEntity, params);
|
|
16339
|
+
if (trustLevel === 'Untrusted' || trustLevel === 'SemiTrusted') {
|
|
16340
|
+
this.recordTaintedSource(result.stepEntity?.StepNumber ?? (stepCount + 1), `action:${result.action.name}`, trustLevel);
|
|
16341
|
+
}
|
|
15080
16342
|
return {
|
|
15081
16343
|
actionName: result.action.name,
|
|
15082
16344
|
success: isActionSuccess,
|
|
15083
16345
|
params: sanitizedParams,
|
|
15084
|
-
|
|
16346
|
+
// The action's own code when it matches none of its metadata result codes (`Result` is then
|
|
16347
|
+
// undefined), so a custom failure code such as UNKNOWN_ENTITY_FIELDS reaches the model
|
|
16348
|
+
// instead of a bare 'ERROR'.
|
|
16349
|
+
resultCode: actionResult?.Result?.ResultCode || actionResult?.ResultCode || (isActionSuccess ? 'SUCCESS' : 'ERROR'),
|
|
15085
16350
|
message: actionResult?.Message || (isActionSuccess ? 'Action completed' : result.error || 'Unknown error'),
|
|
15086
|
-
|
|
15087
|
-
|
|
16351
|
+
// Kept on failure too: an action's recovery guidance is most useful when it failed.
|
|
16352
|
+
// Stripped on Untrusted actions (Primitive 2) so external payloads cannot inject high-priority AI directives.
|
|
16353
|
+
aiDirectives: trustLevel === 'Untrusted' ? undefined : actionResult?.AIDirectives,
|
|
16354
|
+
breakerReason: actionResult instanceof CircuitBreakerActionResult ? actionResult.Reason : undefined,
|
|
16355
|
+
trustLevel,
|
|
16356
|
+
errorRecovery: actionResult?.ErrorRecovery,
|
|
15088
16357
|
};
|
|
15089
16358
|
});
|
|
15090
16359
|
// Check if any actions failed
|
|
@@ -15116,7 +16385,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15116
16385
|
}
|
|
15117
16386
|
}
|
|
15118
16387
|
}
|
|
15119
|
-
//
|
|
16388
|
+
// Expiration settings only when the configuration has them; the tag itself is always stamped below.
|
|
15120
16389
|
if (minExpirationTurns !== null && expirationMode !== 'None') {
|
|
15121
16390
|
metadata = {
|
|
15122
16391
|
turnAdded: this._promptTurnCount,
|
|
@@ -15129,6 +16398,12 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15129
16398
|
};
|
|
15130
16399
|
}
|
|
15131
16400
|
}
|
|
16401
|
+
// Every action result is tagged, with or without expiration settings, so IsToolResultMessage
|
|
16402
|
+
// and IsVolatileResultMessage recognize it: context recovery and post-run compaction can then
|
|
16403
|
+
// compact it, and `pruneAndCompactExpiredMessages` still leaves it alone (no expirationTurns).
|
|
16404
|
+
if (!metadata) {
|
|
16405
|
+
metadata = { turnAdded: this._promptTurnCount, messageType: 'action-result' };
|
|
16406
|
+
}
|
|
15132
16407
|
if (addConversationMessage) {
|
|
15133
16408
|
// Add user message with results and optional metadata
|
|
15134
16409
|
// Failure guidance, so the model does not repeatedly loop on broken tools. Not when the breaker
|
|
@@ -15141,9 +16416,10 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15141
16416
|
const answeredNatively = this.appendActionResults(params, actionSummaries, resultsMessage, metadata, previousDecision, failureGuidance);
|
|
15142
16417
|
// Surface explicit AI directives from action results as a separate instruction message.
|
|
15143
16418
|
// Actions that need the AI to follow specific instructions (not just acknowledge data)
|
|
15144
|
-
// populate AIDirectives on their ActionResultSimple return value.
|
|
16419
|
+
// populate AIDirectives on their ActionResultSimple return value. Failed actions are
|
|
16420
|
+
// included: a directive on a failure is the action telling the model how to recover.
|
|
15145
16421
|
const allDirectives = actionSummaries
|
|
15146
|
-
.filter(a => a.
|
|
16422
|
+
.filter(a => a.aiDirectives && a.aiDirectives.length > 0)
|
|
15147
16423
|
.flatMap(a => a.aiDirectives);
|
|
15148
16424
|
if (allDirectives.length > 0) {
|
|
15149
16425
|
const directiveText = allDirectives
|
|
@@ -15305,6 +16581,10 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15305
16581
|
const defaultTimeout = params.clientToolTimeoutMs ?? 30_000;
|
|
15306
16582
|
const results = [];
|
|
15307
16583
|
const agentRunID = this._agentRun?.ID ?? 'unknown';
|
|
16584
|
+
// Resolved once: the same tiers and precedence the prompt offered the model, keyed by name so each
|
|
16585
|
+
// result can read the tool's declared TrustLevel.
|
|
16586
|
+
const toolsByName = new Map(this.resolveClientToolsForRun(params.agent, { ...(params.data ?? {}), sessionID: params.sessionID })
|
|
16587
|
+
.map(t => [t.Name.trim().toLowerCase(), t]));
|
|
15308
16588
|
// Execute tools sequentially (client may not support parallel UI operations)
|
|
15309
16589
|
for (const tool of clientTools) {
|
|
15310
16590
|
const stepEntity = await this.createStepEntity({
|
|
@@ -15321,12 +16601,21 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15321
16601
|
result: response.Result,
|
|
15322
16602
|
media: response.Media?.map(m => ({ mimeType: m.MimeType, bytes: Math.floor((m.Base64.length * 3) / 4), width: m.Width, height: m.Height }))
|
|
15323
16603
|
});
|
|
16604
|
+
const matchedClientToolMeta = toolsByName.get(tool.Name.trim().toLowerCase());
|
|
16605
|
+
const resolvedActionTrust = this.resolveActionTrustLevel(tool.Name, undefined, params);
|
|
16606
|
+
const clientToolTrustLevel = resolvedActionTrust !== 'Trusted'
|
|
16607
|
+
? resolvedActionTrust
|
|
16608
|
+
: (matchedClientToolMeta?.TrustLevel ?? 'Trusted');
|
|
16609
|
+
if (clientToolTrustLevel === 'Untrusted' || clientToolTrustLevel === 'SemiTrusted') {
|
|
16610
|
+
this.recordTaintedSource(stepEntity?.StepNumber ?? (stepCount + 1), `client-tool:${tool.Name}`, clientToolTrustLevel);
|
|
16611
|
+
}
|
|
15324
16612
|
results.push({
|
|
15325
16613
|
ToolName: tool.Name,
|
|
15326
16614
|
Success: response.Success,
|
|
15327
16615
|
Result: response.Result,
|
|
15328
16616
|
Media: response.Media,
|
|
15329
|
-
ErrorMessage: response.ErrorMessage
|
|
16617
|
+
ErrorMessage: response.ErrorMessage,
|
|
16618
|
+
TrustLevel: clientToolTrustLevel,
|
|
15330
16619
|
});
|
|
15331
16620
|
}
|
|
15332
16621
|
// Format results as conversation message
|
|
@@ -15600,7 +16889,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15600
16889
|
const existing = await rv.RunView({
|
|
15601
16890
|
EntityName: 'MJ: Conversation Skills',
|
|
15602
16891
|
ExtraFilter: `ConversationID = '${EscapeSQLString(conversationId)}' AND SkillID = '${EscapeSQLString(skill.ID)}'`,
|
|
15603
|
-
ResultType: 'entity_object', MaxRows: 1,
|
|
16892
|
+
ResultType: 'entity_object', MaxRows: 1, SkipTotalRowCount: true,
|
|
15604
16893
|
}, params.contextUser);
|
|
15605
16894
|
if (!existing.Success) {
|
|
15606
16895
|
LogErrorEx({ message: `Could not read conversation skill '${skill.Name}': ${existing.ErrorMessage}`, severity: 'warning', category: 'AgentSkills' });
|
|
@@ -15638,7 +16927,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15638
16927
|
const existing = await rv.RunView({
|
|
15639
16928
|
EntityName: 'MJ: Conversation Skills',
|
|
15640
16929
|
ExtraFilter: `ConversationID = '${EscapeSQLString(conversationId)}' AND SkillID = '${EscapeSQLString(skillId)}' AND Status = 'Active'`,
|
|
15641
|
-
ResultType: 'entity_object', MaxRows: 1,
|
|
16930
|
+
ResultType: 'entity_object', MaxRows: 1, SkipTotalRowCount: true,
|
|
15642
16931
|
}, contextUser);
|
|
15643
16932
|
const row = existing.Success ? existing.Results?.[0] : undefined;
|
|
15644
16933
|
if (!row)
|
|
@@ -15921,8 +17210,8 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15921
17210
|
*/
|
|
15922
17211
|
async executeTasksStep(params, previousDecision) {
|
|
15923
17212
|
const graph = previousDecision.taskGraph;
|
|
15924
|
-
const
|
|
15925
|
-
if (!
|
|
17213
|
+
const rawSpec = graph?.spec;
|
|
17214
|
+
if (!rawSpec) {
|
|
15926
17215
|
return {
|
|
15927
17216
|
step: 'Failed',
|
|
15928
17217
|
terminate: true,
|
|
@@ -15931,6 +17220,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15931
17220
|
newPayload: previousDecision.newPayload || previousDecision.previousPayload
|
|
15932
17221
|
};
|
|
15933
17222
|
}
|
|
17223
|
+
const spec = this.canonicalizeTaskGraphSpec(rawSpec);
|
|
15934
17224
|
// Fail closed under bound parameters (ExecuteAgentParams.boundActionParams): a graph's action nodes
|
|
15935
17225
|
// are dispatched by the task-graph runner with the inputs the model authored, outside
|
|
15936
17226
|
// ExecuteSingleAction, so nothing would hide or apply a binding. The response type already withholds
|
|
@@ -15973,6 +17263,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15973
17263
|
EnvironmentID: MJEnvironmentEntityExtended.DefaultEnvironmentID,
|
|
15974
17264
|
ConversationDetailID: params.conversationDetailId ?? null,
|
|
15975
17265
|
AgentRunID: this._agentRun?.ID ?? null,
|
|
17266
|
+
ParentAgentHierarchy: this._agentHierarchy.length > 0 ? [...this._agentHierarchy] : undefined,
|
|
15976
17267
|
// If THIS run was itself started by a finished graph, the graph it emits inherits that
|
|
15977
17268
|
// depth + 1. Without this the chain restarts at zero on every hop and
|
|
15978
17269
|
// MAX_REINVOKE_DEPTH never fires — a graph reinvoking an agent that emits a graph would
|
|
@@ -16019,6 +17310,73 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16019
17310
|
newPayload: previousDecision.newPayload || previousDecision.previousPayload
|
|
16020
17311
|
};
|
|
16021
17312
|
}
|
|
17313
|
+
/**
|
|
17314
|
+
* Executes a `'Handoff'` next step: records the `'Handoff'` step entity with the resolved
|
|
17315
|
+
* target agent ID, stores {@link _handoffResult} for {@link ExecuteAgentResult.handoff},
|
|
17316
|
+
* and ends this run `'Success'` with the handoff message so the host can invoke the target agent.
|
|
17317
|
+
*
|
|
17318
|
+
* @protected
|
|
17319
|
+
*/
|
|
17320
|
+
async executeHandoffStep(params, previousDecision) {
|
|
17321
|
+
const handoff = previousDecision.handoff;
|
|
17322
|
+
const resolved = this._resolvedHandoffTarget;
|
|
17323
|
+
if (!handoff || !resolved) {
|
|
17324
|
+
return {
|
|
17325
|
+
step: 'Failed',
|
|
17326
|
+
terminate: true,
|
|
17327
|
+
errorMessage: 'A Handoff step reached execution without a validated handoff target.',
|
|
17328
|
+
previousPayload: previousDecision.previousPayload,
|
|
17329
|
+
newPayload: previousDecision.newPayload || previousDecision.previousPayload
|
|
17330
|
+
};
|
|
17331
|
+
}
|
|
17332
|
+
if (this.runWithholdsHandoff(params)) {
|
|
17333
|
+
return {
|
|
17334
|
+
step: 'Failed',
|
|
17335
|
+
terminate: true,
|
|
17336
|
+
errorMessage: 'Handoff is not available on this run.',
|
|
17337
|
+
previousPayload: previousDecision.previousPayload,
|
|
17338
|
+
newPayload: previousDecision.newPayload || previousDecision.previousPayload
|
|
17339
|
+
};
|
|
17340
|
+
}
|
|
17341
|
+
const stepEntity = await this.createStepEntity({
|
|
17342
|
+
stepType: 'Handoff',
|
|
17343
|
+
stepName: `Handoff: ${resolved.name}`,
|
|
17344
|
+
targetId: resolved.id,
|
|
17345
|
+
contextUser: params.contextUser,
|
|
17346
|
+
inputData: {
|
|
17347
|
+
agentName: handoff.agentName,
|
|
17348
|
+
brief: handoff.brief,
|
|
17349
|
+
reason: handoff.reason
|
|
17350
|
+
}
|
|
17351
|
+
});
|
|
17352
|
+
const chain = [...(params.handoffChain ?? []), params.agent.ID];
|
|
17353
|
+
const hop = chain.length;
|
|
17354
|
+
await this.finalizeStepEntity(stepEntity, true, undefined, {
|
|
17355
|
+
HandoffToAgentID: resolved.id,
|
|
17356
|
+
TargetAgentName: resolved.name,
|
|
17357
|
+
Brief: handoff.brief,
|
|
17358
|
+
Reason: handoff.reason,
|
|
17359
|
+
Hop: hop,
|
|
17360
|
+
Chain: chain
|
|
17361
|
+
});
|
|
17362
|
+
this._handoffResult = {
|
|
17363
|
+
targetAgentId: resolved.id,
|
|
17364
|
+
targetAgentName: resolved.name,
|
|
17365
|
+
sourceAgentId: params.agent.ID,
|
|
17366
|
+
brief: handoff.brief,
|
|
17367
|
+
reason: handoff.reason,
|
|
17368
|
+
runStepId: stepEntity.ID
|
|
17369
|
+
};
|
|
17370
|
+
return {
|
|
17371
|
+
step: 'Success',
|
|
17372
|
+
terminate: true,
|
|
17373
|
+
message: previousDecision.message || `Transferring you to **${resolved.name}**…`,
|
|
17374
|
+
reasoning: previousDecision.reasoning,
|
|
17375
|
+
confidence: previousDecision.confidence,
|
|
17376
|
+
previousPayload: previousDecision.previousPayload,
|
|
17377
|
+
newPayload: previousDecision.newPayload || previousDecision.previousPayload
|
|
17378
|
+
};
|
|
17379
|
+
}
|
|
16022
17380
|
/**
|
|
16023
17381
|
* Records a constant-folded task graph (D9) without submitting it.
|
|
16024
17382
|
*
|
|
@@ -16408,7 +17766,6 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16408
17766
|
}
|
|
16409
17767
|
/**
|
|
16410
17768
|
* Executes a ForEach loop with actual for loop
|
|
16411
|
-
* @private
|
|
16412
17769
|
*/
|
|
16413
17770
|
async executeForEachLoop(params, config, previousDecision) {
|
|
16414
17771
|
const forEach = previousDecision.forEach;
|
|
@@ -16417,64 +17774,91 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16417
17774
|
// ForEach step with no details into a Retry whose errorMessage the model is shown.
|
|
16418
17775
|
return this.createFailedStep('ForEach configuration missing', previousDecision);
|
|
16419
17776
|
}
|
|
16420
|
-
const
|
|
16421
|
-
|
|
16422
|
-
|
|
17777
|
+
const primaryActionName = forEach.action?.name ?? forEach.steps?.[0]?.name;
|
|
17778
|
+
const headerMessage = this.validateForEachHeader(forEach);
|
|
17779
|
+
if (headerMessage) {
|
|
17780
|
+
return this.failLoopBeforeFirstIteration('ForEach', forEach.collectionPath, `ForEach configuration invalid: ${headerMessage}`, previousDecision, params, primaryActionName);
|
|
16423
17781
|
}
|
|
16424
17782
|
const currentPayload = previousDecision.newPayload || previousDecision.previousPayload;
|
|
16425
17783
|
const collection = this.getCollectionFromPayload(currentPayload, forEach.collectionPath);
|
|
16426
17784
|
if (!collection) {
|
|
16427
|
-
return this.failLoopBeforeFirstIteration('ForEach', forEach.collectionPath, `Collection path "${forEach.collectionPath}" not an array`, previousDecision, params,
|
|
17785
|
+
return this.failLoopBeforeFirstIteration('ForEach', forEach.collectionPath, `Collection path "${forEach.collectionPath}" not an array`, previousDecision, params, primaryActionName);
|
|
17786
|
+
}
|
|
17787
|
+
const agentId = params.agent?.ID ?? this._agentRun?.AgentID ?? '';
|
|
17788
|
+
const bodyMessage = this.validateLoopBodyOperation('ForEach', forEach, agentId);
|
|
17789
|
+
if (bodyMessage) {
|
|
17790
|
+
return this.failLoopBeforeFirstIteration('ForEach', forEach.collectionPath, `ForEach configuration invalid: ${bodyMessage}`, previousDecision, params, primaryActionName);
|
|
16428
17791
|
}
|
|
16429
17792
|
const loopStepEntity = await this.createForEachLoopStep(forEach, collection, currentPayload, params);
|
|
16430
17793
|
const loopResults = await this.executeForEachIterations(forEach, collection, currentPayload, loopStepEntity.ID, params, config);
|
|
16431
17794
|
return this.completeForEachLoop(forEach, loopStepEntity, loopResults, previousDecision, params);
|
|
16432
17795
|
}
|
|
16433
|
-
validateWhileOperation(whileOp) {
|
|
17796
|
+
validateWhileOperation(whileOp, agentId = this._agentRun?.AgentID ?? '') {
|
|
16434
17797
|
if (!whileOp.condition || whileOp.condition.trim() === '') {
|
|
16435
17798
|
return 'Condition is required';
|
|
16436
17799
|
}
|
|
16437
17800
|
if (!whileOp.itemVariable || whileOp.itemVariable.trim() === '') {
|
|
16438
17801
|
return 'Item variable is required';
|
|
16439
17802
|
}
|
|
16440
|
-
|
|
16441
|
-
if (whileOp.action) {
|
|
16442
|
-
return this.validateActionInAgent(whileOp.action.name);
|
|
16443
|
-
}
|
|
16444
|
-
else if (whileOp.subAgent) {
|
|
16445
|
-
// check to make sure sub-agent is valid
|
|
16446
|
-
return this.validateSubAgentInAgent(whileOp.subAgent.name);
|
|
16447
|
-
}
|
|
16448
|
-
// if we get here, all good
|
|
16449
|
-
return null;
|
|
17803
|
+
return this.validateLoopBodyOperation('While', whileOp, agentId);
|
|
16450
17804
|
}
|
|
16451
|
-
|
|
16452
|
-
// make sure that for actions it is valid action and for sub-agents it is valid sub-agent
|
|
17805
|
+
validateForEachHeader(forEach) {
|
|
16453
17806
|
if (!forEach.itemVariable || forEach.itemVariable.trim() === '') {
|
|
16454
17807
|
return 'Item variable is required';
|
|
16455
17808
|
}
|
|
16456
17809
|
if (!forEach.collectionPath || forEach.collectionPath.trim() === '') {
|
|
16457
17810
|
return 'Collection path is required';
|
|
16458
17811
|
}
|
|
16459
|
-
|
|
16460
|
-
|
|
17812
|
+
return null;
|
|
17813
|
+
}
|
|
17814
|
+
/**
|
|
17815
|
+
* Validates the loop body arm (`action` | `steps` | `subAgent`) shared by `ForEach` and `While`.
|
|
17816
|
+
* Structural validation is delegated to CorePlus {@link ValidateLoopOperationStructure} so in-turn
|
|
17817
|
+
* and durable loops enforce one identical contract; runtime action/sub-agent membership is checked
|
|
17818
|
+
* here without mutating `op`.
|
|
17819
|
+
*/
|
|
17820
|
+
validateLoopBodyOperation(kind, op, agentId = this._agentRun?.AgentID ?? '') {
|
|
17821
|
+
const structuralErrors = ValidateLoopOperationStructure(kind, op);
|
|
17822
|
+
if (structuralErrors.length > 0) {
|
|
17823
|
+
return structuralErrors[0].Message;
|
|
16461
17824
|
}
|
|
16462
|
-
|
|
16463
|
-
|
|
16464
|
-
|
|
17825
|
+
if (op.prompt) {
|
|
17826
|
+
return 'Prompt loop bodies are only supported in durable TaskGraph execution';
|
|
17827
|
+
}
|
|
17828
|
+
if (op.action) {
|
|
17829
|
+
return this.validateActionInAgent(op.action.name, agentId);
|
|
17830
|
+
}
|
|
17831
|
+
if (op.steps !== undefined) {
|
|
17832
|
+
for (const step of op.steps) {
|
|
17833
|
+
const actionErr = this.validateActionInAgent(step.name, agentId);
|
|
17834
|
+
if (actionErr) {
|
|
17835
|
+
return actionErr;
|
|
17836
|
+
}
|
|
17837
|
+
}
|
|
17838
|
+
return null;
|
|
17839
|
+
}
|
|
17840
|
+
if (op.subAgent) {
|
|
17841
|
+
return this.validateSubAgentInAgent(op.subAgent.name, agentId);
|
|
16465
17842
|
}
|
|
16466
|
-
// if we get here, all good
|
|
16467
17843
|
return null;
|
|
16468
17844
|
}
|
|
16469
|
-
validateActionInAgent(actionName) {
|
|
16470
|
-
// Use effective actions
|
|
16471
|
-
const effectiveActions = this.
|
|
17845
|
+
validateActionInAgent(actionName, agentId = this._agentRun?.AgentID ?? '') {
|
|
17846
|
+
// Use effective actions + any Flow step actions configured for this agent
|
|
17847
|
+
const effectiveActions = this.getAvailableActionsForAgent(agentId);
|
|
16472
17848
|
const normalizedName = actionName.trim().toLowerCase();
|
|
16473
17849
|
// Try exact match first
|
|
16474
17850
|
const exactMatch = effectiveActions.find(a => a.Name.trim().toLowerCase() === normalizedName);
|
|
16475
17851
|
if (exactMatch) {
|
|
16476
17852
|
return null; // Valid
|
|
16477
17853
|
}
|
|
17854
|
+
// Try sanitized native tool-name match
|
|
17855
|
+
const sanitizedMatch = this.matchNamedBySanitizedToolName(actionName, effectiveActions);
|
|
17856
|
+
if (sanitizedMatch.match) {
|
|
17857
|
+
return null;
|
|
17858
|
+
}
|
|
17859
|
+
if (sanitizedMatch.ambiguous) {
|
|
17860
|
+
return `Ambiguous action '${actionName}' specified. Matches: ${sanitizedMatch.ambiguous.map(a => a.Name).join(', ')}`;
|
|
17861
|
+
}
|
|
16478
17862
|
// Try partial/contains match
|
|
16479
17863
|
const partialMatches = effectiveActions.filter(a => a.Name.trim().toLowerCase().includes(normalizedName));
|
|
16480
17864
|
if (partialMatches.length === 1) {
|
|
@@ -16487,24 +17871,37 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16487
17871
|
return `No action '${actionName}' found. Available: ${effectiveActions.map(a => a.Name).join(', ')}`;
|
|
16488
17872
|
}
|
|
16489
17873
|
}
|
|
16490
|
-
validateSubAgentInAgent(subAgentName) {
|
|
17874
|
+
validateSubAgentInAgent(subAgentName, agentId = this._agentRun?.AgentID ?? '') {
|
|
16491
17875
|
// check to make sure sub-agent is valid
|
|
16492
|
-
const relatedAgents = AIEngine.Instance.AgentRelationships.filter(ar => UUIDsEqual(ar.AgentID,
|
|
16493
|
-
const childAgents = AIEngine.Instance.Agents.filter(a => UUIDsEqual(a.ParentID,
|
|
16494
|
-
|
|
16495
|
-
|
|
17876
|
+
const relatedAgents = AIEngine.Instance.AgentRelationships.filter(ar => UUIDsEqual(ar.AgentID, agentId));
|
|
17877
|
+
const childAgents = AIEngine.Instance.Agents.filter(a => UUIDsEqual(a.ParentID, agentId));
|
|
17878
|
+
const candidate = this.stripSubAgentToolPrefix(subAgentName);
|
|
17879
|
+
const lower = candidate.toLowerCase();
|
|
17880
|
+
const sanitized = SanitizeToolName(candidate);
|
|
17881
|
+
// Check relatedAgents: exact -> sanitized native tool name -> partial
|
|
17882
|
+
let subAgent = relatedAgents.filter(ra => ra.SubAgent?.trim().toLowerCase() === lower);
|
|
17883
|
+
if (subAgent.length === 0 && sanitized) {
|
|
17884
|
+
subAgent = relatedAgents.filter(ra => Boolean(ra.SubAgent && SanitizeToolName(ra.SubAgent) === sanitized));
|
|
17885
|
+
}
|
|
17886
|
+
if (subAgent.length > 1) {
|
|
17887
|
+
return `Ambiguous sub-agent '${subAgentName}' specified`;
|
|
17888
|
+
}
|
|
16496
17889
|
if (subAgent.length === 0) {
|
|
16497
|
-
|
|
16498
|
-
subAgent = relatedAgents.filter(ra => ra.SubAgent?.trim().toLowerCase().includes(subAgentName.trim().toLowerCase() || ''));
|
|
17890
|
+
subAgent = relatedAgents.filter(ra => ra.SubAgent?.trim().toLowerCase().includes(lower || ''));
|
|
16499
17891
|
if (subAgent.length > 1) {
|
|
16500
17892
|
return `Ambiguous sub-agent '${subAgentName}' specified`;
|
|
16501
17893
|
}
|
|
16502
|
-
|
|
16503
|
-
// try child agents
|
|
16504
|
-
let childAgent = childAgents.filter(ca => ca.Name?.trim().toLowerCase() ===
|
|
17894
|
+
if (subAgent.length === 0) {
|
|
17895
|
+
// try child agents: exact -> sanitized native tool name -> partial
|
|
17896
|
+
let childAgent = childAgents.filter(ca => ca.Name?.trim().toLowerCase() === lower);
|
|
17897
|
+
if (childAgent.length === 0 && sanitized) {
|
|
17898
|
+
childAgent = childAgents.filter(ca => Boolean(ca.Name && SanitizeToolName(ca.Name) === sanitized));
|
|
17899
|
+
}
|
|
17900
|
+
if (childAgent.length > 1) {
|
|
17901
|
+
return `Ambiguous child agent '${subAgentName}' specified`;
|
|
17902
|
+
}
|
|
16505
17903
|
if (childAgent.length === 0) {
|
|
16506
|
-
|
|
16507
|
-
childAgent = childAgents.filter(ca => ca.Name?.trim().toLowerCase().includes(subAgentName.trim().toLowerCase() || ''));
|
|
17904
|
+
childAgent = childAgents.filter(ca => ca.Name?.trim().toLowerCase().includes(lower || ''));
|
|
16508
17905
|
if (childAgent.length > 1) {
|
|
16509
17906
|
return `Ambiguous child agent '${subAgentName}' specified`;
|
|
16510
17907
|
}
|
|
@@ -16512,9 +17909,6 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16512
17909
|
return `No child agent '${subAgentName}' found`;
|
|
16513
17910
|
}
|
|
16514
17911
|
}
|
|
16515
|
-
else {
|
|
16516
|
-
// we have one match, so we're good here
|
|
16517
|
-
}
|
|
16518
17912
|
}
|
|
16519
17913
|
}
|
|
16520
17914
|
// if we get here, all good
|
|
@@ -16618,7 +18012,8 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16618
18012
|
index,
|
|
16619
18013
|
result: iterResult.result,
|
|
16620
18014
|
error: iterResult.error,
|
|
16621
|
-
payload: iterResult.payload
|
|
18015
|
+
payload: iterResult.payload,
|
|
18016
|
+
appliedFolds: iterResult.appliedFolds
|
|
16622
18017
|
})));
|
|
16623
18018
|
const batchResults = await Promise.all(batchPromises);
|
|
16624
18019
|
allResults.push(...batchResults);
|
|
@@ -16660,7 +18055,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16660
18055
|
let currentPayload = initialPayload;
|
|
16661
18056
|
const results = [];
|
|
16662
18057
|
const errors = [];
|
|
16663
|
-
for (const { result, error, payload } of sortedResults) {
|
|
18058
|
+
for (const { result, error, payload, appliedFolds } of sortedResults) {
|
|
16664
18059
|
if (error) {
|
|
16665
18060
|
errors.push(error);
|
|
16666
18061
|
if (!continueOnError) {
|
|
@@ -16669,17 +18064,131 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16669
18064
|
}
|
|
16670
18065
|
else if (result) {
|
|
16671
18066
|
results.push(result);
|
|
16672
|
-
|
|
16673
|
-
|
|
18067
|
+
if (appliedFolds && appliedFolds.length > 0) {
|
|
18068
|
+
for (const fold of appliedFolds) {
|
|
18069
|
+
currentPayload = this.applyLoopOutputFold(currentPayload, fold.output, fold.mapping);
|
|
18070
|
+
}
|
|
18071
|
+
}
|
|
18072
|
+
else {
|
|
18073
|
+
// Apply payload change from this iteration
|
|
18074
|
+
currentPayload = payload || currentPayload;
|
|
18075
|
+
}
|
|
16674
18076
|
}
|
|
16675
18077
|
}
|
|
16676
18078
|
return { results, errors, finalPayload: currentPayload };
|
|
16677
18079
|
}
|
|
18080
|
+
extractActionOutputObject(summaries) {
|
|
18081
|
+
return BuildActionOutputObject(summaries[0]?.params, summaries[0]?.message);
|
|
18082
|
+
}
|
|
18083
|
+
applyLoopOutputFold(basePayload, output, mapping) {
|
|
18084
|
+
const target = IsPlainObject(basePayload)
|
|
18085
|
+
? this.cloneSubAgentPayload(basePayload)
|
|
18086
|
+
: {};
|
|
18087
|
+
const mapped = ApplyOutputMapping(output, mapping, target);
|
|
18088
|
+
return mapped.updates;
|
|
18089
|
+
}
|
|
18090
|
+
/**
|
|
18091
|
+
* Executes an ordered sequence of `LoopBodyActionStep` actions inside a single `ForEach` or `While`
|
|
18092
|
+
* iteration, chaining step outputs under `steps.<id>.*` / `steps.step_<index>.*`, evaluating optional
|
|
18093
|
+
* per-step `condition` expressions, folding optional per-step `outputMapping` onto the working payload,
|
|
18094
|
+
* and halting remaining steps in the pass if any step fails.
|
|
18095
|
+
*/
|
|
18096
|
+
async executeLoopStepsIteration(args) {
|
|
18097
|
+
const { steps, item, itemVariable, index, attemptContext, currentPayload, parentStepId, params } = args;
|
|
18098
|
+
const stepsOutputs = {};
|
|
18099
|
+
const appliedFolds = [];
|
|
18100
|
+
const aggregatedSummaries = [];
|
|
18101
|
+
const evaluator = new SafeExpressionEvaluator();
|
|
18102
|
+
let workingPayload = IsPlainObject(currentPayload)
|
|
18103
|
+
? this.cloneSubAgentPayload(currentPayload)
|
|
18104
|
+
: {};
|
|
18105
|
+
for (let stepIdx = 0; stepIdx < steps.length; stepIdx++) {
|
|
18106
|
+
const step = steps[stepIdx];
|
|
18107
|
+
const stepKey = step.id?.trim() || `step_${stepIdx}`;
|
|
18108
|
+
const stepBindings = {
|
|
18109
|
+
...(attemptContext ? { attemptNumber: attemptContext.attemptNumber, totalAttempts: attemptContext.totalAttempts } : {}),
|
|
18110
|
+
item,
|
|
18111
|
+
[itemVariable]: item,
|
|
18112
|
+
index,
|
|
18113
|
+
steps: stepsOutputs
|
|
18114
|
+
};
|
|
18115
|
+
if (step.condition?.trim()) {
|
|
18116
|
+
const conditionScope = {
|
|
18117
|
+
...workingPayload,
|
|
18118
|
+
...stepBindings,
|
|
18119
|
+
payload: { ...workingPayload, ...stepBindings },
|
|
18120
|
+
steps: stepsOutputs,
|
|
18121
|
+
index,
|
|
18122
|
+
iteration: index,
|
|
18123
|
+
...(params.data !== undefined ? { data: params.data } : {}),
|
|
18124
|
+
...(params.context !== undefined ? { context: params.context } : {})
|
|
18125
|
+
};
|
|
18126
|
+
const evalResult = evaluator.evaluate(step.condition.trim(), conditionScope);
|
|
18127
|
+
if (!evalResult.success) {
|
|
18128
|
+
throw new Error(`Loop step "${stepKey}" condition "${step.condition}" could not be evaluated: ${evalResult.error ?? 'unknown error'}`);
|
|
18129
|
+
}
|
|
18130
|
+
if (!evalResult.value) {
|
|
18131
|
+
continue;
|
|
18132
|
+
}
|
|
18133
|
+
}
|
|
18134
|
+
const matchedAction = this.findAgentActionForLoop(step.name, params.agent.ID, params.agent.Name, params);
|
|
18135
|
+
const stepPayload = { ...workingPayload, ...stepBindings };
|
|
18136
|
+
const resolvedParams = ResolveLoopBodyParams(step.params ?? {}, stepBindings, { payload: stepPayload, data: params.data, context: params.context });
|
|
18137
|
+
const actionStep = {
|
|
18138
|
+
step: 'Actions',
|
|
18139
|
+
actions: [{ name: matchedAction.Action, params: resolvedParams }],
|
|
18140
|
+
newPayload: workingPayload,
|
|
18141
|
+
previousPayload: workingPayload,
|
|
18142
|
+
terminate: false
|
|
18143
|
+
};
|
|
18144
|
+
const stepResult = await this.executeActionsStep(params, actionStep, parentStepId, false, 0, { skipCircuitBreaker: true });
|
|
18145
|
+
const summaries = Array.isArray(stepResult.priorStepResult)
|
|
18146
|
+
? stepResult.priorStepResult
|
|
18147
|
+
: [];
|
|
18148
|
+
aggregatedSummaries.push(...summaries);
|
|
18149
|
+
const failedSummary = summaries.find((s) => !s.success);
|
|
18150
|
+
if (failedSummary) {
|
|
18151
|
+
throw new Error(`Loop step "${stepKey}" (${matchedAction.Action}) failed: ${failedSummary.message || failedSummary.resultCode || 'Action failed'}`);
|
|
18152
|
+
}
|
|
18153
|
+
const stepOutput = this.extractActionOutputObject(summaries);
|
|
18154
|
+
stepsOutputs[stepKey] = stepOutput;
|
|
18155
|
+
if (stepKey !== `step_${stepIdx}`) {
|
|
18156
|
+
stepsOutputs[`step_${stepIdx}`] ??= stepOutput;
|
|
18157
|
+
}
|
|
18158
|
+
if (step.outputMapping?.trim()) {
|
|
18159
|
+
workingPayload = this.applyLoopOutputFold(workingPayload, stepOutput, step.outputMapping);
|
|
18160
|
+
appliedFolds.push({ output: stepOutput, mapping: step.outputMapping });
|
|
18161
|
+
}
|
|
18162
|
+
else if (IsPlainObject(stepResult.newPayload)) {
|
|
18163
|
+
workingPayload = stepResult.newPayload;
|
|
18164
|
+
}
|
|
18165
|
+
}
|
|
18166
|
+
const outPayload = IsPlainObject(currentPayload) || appliedFolds.length > 0 ? workingPayload : currentPayload;
|
|
18167
|
+
const syntheticStep = {
|
|
18168
|
+
step: 'Retry',
|
|
18169
|
+
terminate: false,
|
|
18170
|
+
previousPayload: currentPayload,
|
|
18171
|
+
newPayload: outPayload,
|
|
18172
|
+
priorStepResult: aggregatedSummaries
|
|
18173
|
+
};
|
|
18174
|
+
return { payload: outPayload, result: syntheticStep, appliedFolds };
|
|
18175
|
+
}
|
|
16678
18176
|
/**
|
|
16679
18177
|
* Helper: Execute single ForEach iteration
|
|
16680
18178
|
*/
|
|
16681
|
-
async executeSingleForEachIteration(forEach, item, index, currentPayload, parentStepId, params,
|
|
18179
|
+
async executeSingleForEachIteration(forEach, item, index, currentPayload, parentStepId, params, _config) {
|
|
16682
18180
|
try {
|
|
18181
|
+
if (Array.isArray(forEach.steps) && forEach.steps.length > 0) {
|
|
18182
|
+
return await this.executeLoopStepsIteration({
|
|
18183
|
+
steps: forEach.steps,
|
|
18184
|
+
item,
|
|
18185
|
+
itemVariable: forEach.itemVariable || 'item',
|
|
18186
|
+
index,
|
|
18187
|
+
currentPayload,
|
|
18188
|
+
parentStepId,
|
|
18189
|
+
params
|
|
18190
|
+
});
|
|
18191
|
+
}
|
|
16683
18192
|
// Resolve params via BeforeLoopIteration hook
|
|
16684
18193
|
const beforeHook = this.AgentTypeInstance.BeforeLoopIteration?.({ item, itemVariable: forEach.itemVariable, index, payload: currentPayload, loopType: 'ForEach', actionParams: forEach.action?.params || {} });
|
|
16685
18194
|
let resolvedParams = beforeHook?.actionParams || forEach.action?.params || {};
|
|
@@ -16713,12 +18222,24 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16713
18222
|
result.priorStepResult = this.formatSubAgentResultAsMarkdown(forEach.subAgent.name, result);
|
|
16714
18223
|
}
|
|
16715
18224
|
else {
|
|
16716
|
-
throw new Error('ForEach missing action/subAgent');
|
|
18225
|
+
throw new Error('ForEach missing action/steps/subAgent');
|
|
16717
18226
|
}
|
|
16718
|
-
// Apply AfterLoopIteration hook
|
|
18227
|
+
// Apply AfterLoopIteration hook (or ApplyOutputMapping fallback when LoopAgentType has no hook)
|
|
16719
18228
|
const iterPayload = result.newPayload || currentPayload;
|
|
16720
18229
|
const afterHook = this.AgentTypeInstance.AfterLoopIteration?.({ currentPayload: iterPayload, item, itemVariable: forEach.itemVariable, index, loopContext: { actionOutputMapping: forEach.action?.outputMapping } });
|
|
16721
|
-
|
|
18230
|
+
if (afterHook) {
|
|
18231
|
+
return { payload: afterHook, result };
|
|
18232
|
+
}
|
|
18233
|
+
if (forEach.action?.outputMapping?.trim() && Array.isArray(result.priorStepResult)) {
|
|
18234
|
+
const stepOutput = this.extractActionOutputObject(result.priorStepResult);
|
|
18235
|
+
const folded = this.applyLoopOutputFold(iterPayload, stepOutput, forEach.action.outputMapping);
|
|
18236
|
+
return {
|
|
18237
|
+
payload: folded,
|
|
18238
|
+
result,
|
|
18239
|
+
appliedFolds: [{ output: stepOutput, mapping: forEach.action.outputMapping }]
|
|
18240
|
+
};
|
|
18241
|
+
}
|
|
18242
|
+
return { payload: iterPayload, result };
|
|
16722
18243
|
}
|
|
16723
18244
|
catch (error) {
|
|
16724
18245
|
return { error: { index, item, message: error.message } };
|
|
@@ -16732,7 +18253,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16732
18253
|
loopStepEntity.PayloadAtEnd = this.serializePayloadAtEnd(loopResults.finalPayload);
|
|
16733
18254
|
await this.finalizeStepEntity(loopStepEntity, loopResults.errors.length === 0, this.formatLoopErrors(loopResults.errors), loopResults);
|
|
16734
18255
|
if (this.AgentTypeInstance.InjectLoopResultsAsMessage) {
|
|
16735
|
-
this.injectLoopResultsMessage('ForEach', forEach.collectionPath, loopResults.results, loopResults.errors, params, forEach.action?.name);
|
|
18256
|
+
this.injectLoopResultsMessage('ForEach', forEach.collectionPath, loopResults.results, loopResults.errors, params, forEach.action?.name ?? forEach.steps?.[0]?.name);
|
|
16736
18257
|
}
|
|
16737
18258
|
return {
|
|
16738
18259
|
step: 'Retry',
|
|
@@ -16858,10 +18379,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16858
18379
|
// Look up the loop's action config for expiration settings
|
|
16859
18380
|
if (actionName) {
|
|
16860
18381
|
const agentActions = AIEngine.Instance.AgentActions.filter(aa => UUIDsEqual(aa.AgentID, params.agent.ID));
|
|
16861
|
-
const effectiveActions = this.
|
|
16862
|
-
|
|
16863
|
-
|
|
16864
|
-
const matchedAction = effectiveActions.find(a => a.Name.trim().toLowerCase() === actionName.trim().toLowerCase());
|
|
18382
|
+
const effectiveActions = this.getEffectiveActionsForValidation(params.agent.ID);
|
|
18383
|
+
const matchedAction = effectiveActions.find(a => a.Name.trim().toLowerCase() === actionName.trim().toLowerCase())
|
|
18384
|
+
?? this.matchNamedBySanitizedToolName(actionName, effectiveActions).match;
|
|
16865
18385
|
if (matchedAction) {
|
|
16866
18386
|
const agentAction = agentActions.find(aa => UUIDsEqual(aa.ActionID, matchedAction.ID));
|
|
16867
18387
|
if (agentAction?.ResultExpirationTurns != null && agentAction.ResultExpirationMode !== 'None') {
|
|
@@ -16891,11 +18411,22 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16891
18411
|
* @since 2.123.0 - Updated to use _effectiveActions for dynamic action support
|
|
16892
18412
|
*/
|
|
16893
18413
|
findAgentActionForLoop(actionName, agentId, agentName, params) {
|
|
16894
|
-
// Use effective actions
|
|
16895
|
-
const effectiveActions = this.
|
|
18414
|
+
// Use effective actions + Flow step actions configured for this agent
|
|
18415
|
+
const effectiveActions = this.getAvailableActionsForAgent(agentId);
|
|
16896
18416
|
const normalizedName = actionName.trim().toLowerCase();
|
|
16897
18417
|
// Try exact match first
|
|
16898
18418
|
let matchedAction = effectiveActions.find(a => a.Name.trim().toLowerCase() === normalizedName);
|
|
18419
|
+
// Try sanitized native tool-name match
|
|
18420
|
+
if (!matchedAction) {
|
|
18421
|
+
const sanitizedMatch = this.matchNamedBySanitizedToolName(actionName, effectiveActions);
|
|
18422
|
+
if (sanitizedMatch.match) {
|
|
18423
|
+
matchedAction = sanitizedMatch.match;
|
|
18424
|
+
this.logStatus(`Action native tool name matched: '${actionName}' → '${matchedAction.Name}'`, true, params);
|
|
18425
|
+
}
|
|
18426
|
+
else if (sanitizedMatch.ambiguous) {
|
|
18427
|
+
throw new Error(`Ambiguous action '${actionName}'. Matches: ${sanitizedMatch.ambiguous.map(a => a.Name).join(', ')}`);
|
|
18428
|
+
}
|
|
18429
|
+
}
|
|
16899
18430
|
// Fallback: CONTAINS search
|
|
16900
18431
|
if (!matchedAction) {
|
|
16901
18432
|
const containsMatches = effectiveActions.filter(a => a.Name.trim().toLowerCase().includes(normalizedName));
|
|
@@ -16927,7 +18458,6 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16927
18458
|
}
|
|
16928
18459
|
/**
|
|
16929
18460
|
* Executes a While loop with actual while loop
|
|
16930
|
-
* @private
|
|
16931
18461
|
*/
|
|
16932
18462
|
async executeWhileLoop(params, config, previousDecision) {
|
|
16933
18463
|
const whileOp = previousDecision.while;
|
|
@@ -16936,9 +18466,11 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16936
18466
|
// While step with no details into a Retry whose errorMessage the model is shown.
|
|
16937
18467
|
return this.createFailedStep('While configuration missing', previousDecision);
|
|
16938
18468
|
}
|
|
16939
|
-
const
|
|
18469
|
+
const primaryActionName = whileOp.action?.name ?? whileOp.steps?.[0]?.name;
|
|
18470
|
+
const agentId = params.agent?.ID ?? this._agentRun?.AgentID ?? '';
|
|
18471
|
+
const validationMessage = this.validateWhileOperation(whileOp, agentId);
|
|
16940
18472
|
if (validationMessage) {
|
|
16941
|
-
return this.failLoopBeforeFirstIteration('While', whileOp.condition, `While configuration invalid: ${validationMessage}`, previousDecision, params,
|
|
18473
|
+
return this.failLoopBeforeFirstIteration('While', whileOp.condition, `While configuration invalid: ${validationMessage}`, previousDecision, params, primaryActionName);
|
|
16942
18474
|
}
|
|
16943
18475
|
const currentPayload = previousDecision.newPayload || previousDecision.previousPayload;
|
|
16944
18476
|
const loopStepEntity = await this.createWhileLoopStep(whileOp, currentPayload, params);
|
|
@@ -17004,8 +18536,21 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17004
18536
|
/**
|
|
17005
18537
|
* Helper: Execute single While iteration
|
|
17006
18538
|
*/
|
|
17007
|
-
async executeSingleWhileIteration(whileOp, attemptContext, index, currentPayload, parentStepId, params,
|
|
18539
|
+
async executeSingleWhileIteration(whileOp, attemptContext, index, currentPayload, parentStepId, params, _config) {
|
|
17008
18540
|
try {
|
|
18541
|
+
if (Array.isArray(whileOp.steps) && whileOp.steps.length > 0) {
|
|
18542
|
+
const stepsOutcome = await this.executeLoopStepsIteration({
|
|
18543
|
+
steps: whileOp.steps,
|
|
18544
|
+
item: attemptContext,
|
|
18545
|
+
itemVariable: whileOp.itemVariable || 'attempt',
|
|
18546
|
+
index,
|
|
18547
|
+
attemptContext,
|
|
18548
|
+
currentPayload,
|
|
18549
|
+
parentStepId,
|
|
18550
|
+
params
|
|
18551
|
+
});
|
|
18552
|
+
return { payload: stepsOutcome.payload, result: stepsOutcome.result };
|
|
18553
|
+
}
|
|
17009
18554
|
// Resolve params via BeforeLoopIteration hook
|
|
17010
18555
|
const beforeHook = this.AgentTypeInstance.BeforeLoopIteration?.({ item: attemptContext, index, itemVariable: whileOp.itemVariable, payload: currentPayload, loopType: 'While', actionParams: whileOp.action?.params || {} });
|
|
17011
18556
|
let resolvedParams = beforeHook?.actionParams || whileOp.action?.params || {};
|
|
@@ -17038,12 +18583,20 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17038
18583
|
result.priorStepResult = this.formatSubAgentResultAsMarkdown(whileOp.subAgent.name, result);
|
|
17039
18584
|
}
|
|
17040
18585
|
else {
|
|
17041
|
-
throw new Error('While missing action/subAgent');
|
|
18586
|
+
throw new Error('While missing action/steps/subAgent');
|
|
17042
18587
|
}
|
|
17043
|
-
// Apply AfterLoopIteration hook
|
|
18588
|
+
// Apply AfterLoopIteration hook (or ApplyOutputMapping fallback when LoopAgentType has no hook)
|
|
17044
18589
|
const iterPayload = result.newPayload || currentPayload;
|
|
17045
18590
|
const afterHook = this.AgentTypeInstance.AfterLoopIteration?.({ currentPayload: iterPayload, item: attemptContext, itemVariable: whileOp.itemVariable, index, loopContext: { actionOutputMapping: whileOp.action?.outputMapping } });
|
|
17046
|
-
|
|
18591
|
+
if (afterHook) {
|
|
18592
|
+
return { payload: afterHook, result };
|
|
18593
|
+
}
|
|
18594
|
+
if (whileOp.action?.outputMapping?.trim() && Array.isArray(result.priorStepResult)) {
|
|
18595
|
+
const stepOutput = this.extractActionOutputObject(result.priorStepResult);
|
|
18596
|
+
const folded = this.applyLoopOutputFold(iterPayload, stepOutput, whileOp.action.outputMapping);
|
|
18597
|
+
return { payload: folded, result };
|
|
18598
|
+
}
|
|
18599
|
+
return { payload: iterPayload, result };
|
|
17047
18600
|
}
|
|
17048
18601
|
catch (error) {
|
|
17049
18602
|
return { error: { index, item: attemptContext, message: error.message } };
|
|
@@ -17058,7 +18611,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17058
18611
|
// Inject before the early return below: a Loop agent re-prompts after a Failed step, and the
|
|
17059
18612
|
// loop-results message (the condition error, under Errors) is the only way the model learns why.
|
|
17060
18613
|
if (this.AgentTypeInstance.InjectLoopResultsAsMessage) {
|
|
17061
|
-
this.injectLoopResultsMessage('While', whileOp.condition, loopResults.results, loopResults.errors, params, whileOp.action?.name);
|
|
18614
|
+
this.injectLoopResultsMessage('While', whileOp.condition, loopResults.results, loopResults.errors, params, whileOp.action?.name ?? whileOp.steps?.[0]?.name);
|
|
17062
18615
|
}
|
|
17063
18616
|
// A condition that never evaluated means the loop never ran: fail the step rather than
|
|
17064
18617
|
// report a completed zero-iteration loop.
|
|
@@ -17117,6 +18670,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17117
18670
|
}
|
|
17118
18671
|
return {
|
|
17119
18672
|
success: false,
|
|
18673
|
+
taintedSources: this._taintedSources.length > 0 ? [...this._taintedSources] : undefined,
|
|
17120
18674
|
agentRun: this._agentRun
|
|
17121
18675
|
};
|
|
17122
18676
|
}
|
|
@@ -17162,6 +18716,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17162
18716
|
}
|
|
17163
18717
|
return {
|
|
17164
18718
|
success: false,
|
|
18719
|
+
taintedSources: this._taintedSources.length > 0 ? [...this._taintedSources] : undefined,
|
|
17165
18720
|
agentRun: this._agentRun
|
|
17166
18721
|
};
|
|
17167
18722
|
}
|
|
@@ -17349,6 +18904,8 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17349
18904
|
mediaOutputs: this._mediaOutputs.length > 0 ? this._mediaOutputs : undefined,
|
|
17350
18905
|
fileOutputs: this._fileOutputs.length > 0 ? this._fileOutputs : undefined,
|
|
17351
18906
|
feedbackRequestId: this._feedbackRequestId || undefined,
|
|
18907
|
+
taintedSources: this._taintedSources.length > 0 ? [...this._taintedSources] : undefined,
|
|
18908
|
+
handoff: this._handoffResult || undefined,
|
|
17352
18909
|
resolvedStorageAccountId: this._resolvedStorageAccountId || undefined
|
|
17353
18910
|
};
|
|
17354
18911
|
}
|
|
@@ -17488,6 +19045,40 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17488
19045
|
}
|
|
17489
19046
|
return violations;
|
|
17490
19047
|
}
|
|
19048
|
+
/**
|
|
19049
|
+
* Whether the window has reached the compaction trigger the operator configured — the same
|
|
19050
|
+
* `CompactionTriggerPercent` (agent, then agent type, then the default) that drives cross-turn
|
|
19051
|
+
* compaction, resolved by {@link resolveCompactionBudget} into `TriggerTokens`. Below it, the
|
|
19052
|
+
* mid-loop rewrites of earlier turns (shortening replayed tool-call arguments, expiring old action
|
|
19053
|
+
* results) are deferred, so routine tool loops keep the provider's byte-exact prompt-cache prefix.
|
|
19054
|
+
* One knob governs both kinds of compaction on purpose: a second number would be one more thing
|
|
19055
|
+
* to tune, and an in-run rewrite is only worth a cache miss once the window is actually filling up.
|
|
19056
|
+
* @protected
|
|
19057
|
+
*/
|
|
19058
|
+
isMidLoopCompactionThresholdReached(params) {
|
|
19059
|
+
const messages = params?.conversationMessages;
|
|
19060
|
+
if (!Array.isArray(messages) || messages.length === 0) {
|
|
19061
|
+
return false;
|
|
19062
|
+
}
|
|
19063
|
+
const budget = this.resolveCompactionBudget(params, this._agentConfig);
|
|
19064
|
+
if (!budget.TriggerTokens || budget.TriggerTokens <= 0) {
|
|
19065
|
+
return false;
|
|
19066
|
+
}
|
|
19067
|
+
// estimateConversationTokens counts message content only. The arguments of replayed tool calls
|
|
19068
|
+
// travel on every turn too, so they are added here; nothing is counted twice.
|
|
19069
|
+
let estimatedTokens = this.estimateConversationTokens(messages);
|
|
19070
|
+
for (const msg of messages) {
|
|
19071
|
+
const toolCalls = msg.toolCalls;
|
|
19072
|
+
if (Array.isArray(toolCalls) && toolCalls.length > 0) {
|
|
19073
|
+
for (const call of toolCalls) {
|
|
19074
|
+
if (call?.arguments !== undefined) {
|
|
19075
|
+
estimatedTokens += this.estimateTokens(JSON.stringify(call.arguments));
|
|
19076
|
+
}
|
|
19077
|
+
}
|
|
19078
|
+
}
|
|
19079
|
+
}
|
|
19080
|
+
return estimatedTokens >= budget.TriggerTokens;
|
|
19081
|
+
}
|
|
17491
19082
|
/**
|
|
17492
19083
|
* Prunes and compacts expired messages in the conversation based on configured expiration rules.
|
|
17493
19084
|
* Processes messages in three phases: identification, compaction, and removal.
|
|
@@ -18292,6 +19883,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
18292
19883
|
|| messageType === 'client-tool-result'
|
|
18293
19884
|
|| messageType === BaseAgent.toolResultMessageType
|
|
18294
19885
|
|| messageType === 'sub-agent-result'
|
|
19886
|
+
|| messageType === 'sub-agent-consult'
|
|
18295
19887
|
|| messageType === 'loop-result';
|
|
18296
19888
|
}
|
|
18297
19889
|
estimateTokens(content, modelName) {
|
|
@@ -18483,7 +20075,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
18483
20075
|
// we only do this if the string starts and ends with the {{ }} pattern
|
|
18484
20076
|
// and we trim whitespace first
|
|
18485
20077
|
const trimmedValue = value.trim();
|
|
18486
|
-
if (trimmedValue.startsWith('{{') && trimmedValue.endsWith('}}')) {
|
|
20078
|
+
if (trimmedValue.startsWith('{{') && trimmedValue.endsWith('}}') && !trimmedValue.slice(2, -2).includes('{{')) {
|
|
18487
20079
|
// Single-variable case: "{{city.name}}" — strip wrappers, fall through to
|
|
18488
20080
|
// single-variable resolution below which can return non-string types (objects, numbers)
|
|
18489
20081
|
value = trimmedValue.substring(2, trimmedValue.length - 2).trim();
|
|
@@ -18626,16 +20218,37 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
18626
20218
|
*/
|
|
18627
20219
|
validatedRunScope(params) {
|
|
18628
20220
|
const inputs = this.runScopeInputs(params);
|
|
20221
|
+
// Only a run whose host assigned scopes carries the key, so every other run keeps the shape it had
|
|
20222
|
+
const searchScopeIDs = this.hostSearchScopeIDs(params);
|
|
20223
|
+
const hostScopes = searchScopeIDs ? { SearchScopeIDs: searchScopeIDs } : {};
|
|
18629
20224
|
if (!inputs.EntityName && !inputs.RecordID && !inputs.Secondary) {
|
|
18630
|
-
return { PrimaryScopeEntityName: null, PrimaryScopeRecordID: null, SecondaryScopes: null };
|
|
20225
|
+
return { PrimaryScopeEntityName: null, PrimaryScopeRecordID: null, SecondaryScopes: null, ...hostScopes };
|
|
18631
20226
|
}
|
|
18632
20227
|
const secondary = this.validateAndApplySecondaryScopes(inputs.Secondary, this.parseSecondaryScopeConfig(params.agent), params.agent.Name);
|
|
18633
20228
|
return {
|
|
18634
20229
|
PrimaryScopeEntityName: inputs.EntityName ?? null,
|
|
18635
20230
|
PrimaryScopeRecordID: inputs.RecordID ?? null,
|
|
18636
20231
|
SecondaryScopes: secondary && Object.keys(secondary).length > 0 ? secondary : null,
|
|
20232
|
+
...hostScopes,
|
|
18637
20233
|
};
|
|
18638
20234
|
}
|
|
20235
|
+
/**
|
|
20236
|
+
* The search scopes the host assigned this run ({@link ExecuteAgentParams.SearchScopeIDs}): trimmed, de-duplicated,
|
|
20237
|
+
* in the host's order, or `null` for none. Read from the first-class parameter only — never from `data`, which a
|
|
20238
|
+
* caller could otherwise use to hand an agent a scope its own SearchScopeAccess refuses.
|
|
20239
|
+
*/
|
|
20240
|
+
hostSearchScopeIDs(params) {
|
|
20241
|
+
const seen = new UUIDSet();
|
|
20242
|
+
const ids = [];
|
|
20243
|
+
for (const id of params.SearchScopeIDs ?? []) {
|
|
20244
|
+
const trimmed = typeof id === 'string' ? id.trim() : '';
|
|
20245
|
+
if (trimmed && !seen.Has(trimmed)) {
|
|
20246
|
+
seen.Add(trimmed);
|
|
20247
|
+
ids.push(trimmed);
|
|
20248
|
+
}
|
|
20249
|
+
}
|
|
20250
|
+
return ids.length > 0 ? ids : null;
|
|
20251
|
+
}
|
|
18639
20252
|
/**
|
|
18640
20253
|
* Writes the validated run scope onto the run row: the primary entity resolved to its ID (logged when it is
|
|
18641
20254
|
* not in metadata), the tenant record ID and the secondary dimensions as JSON. A secondary-only scope on an
|