@memberjunction/ai-agents 6.2.0 → 6.3.0-edge.0
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 +21 -1
- package/dist/AgentContextAssembler.d.ts +127 -0
- package/dist/AgentContextAssembler.d.ts.map +1 -0
- package/dist/AgentContextAssembler.js +482 -0
- package/dist/AgentContextAssembler.js.map +1 -0
- package/dist/AgentDataPreloader.d.ts +5 -1
- package/dist/AgentDataPreloader.d.ts.map +1 -1
- package/dist/AgentDataPreloader.js +13 -7
- package/dist/AgentDataPreloader.js.map +1 -1
- package/dist/AgentFeedbackCoordinator.d.ts +169 -0
- package/dist/AgentFeedbackCoordinator.d.ts.map +1 -0
- package/dist/AgentFeedbackCoordinator.js +593 -0
- package/dist/AgentFeedbackCoordinator.js.map +1 -0
- package/dist/AgentStepDispatcher.d.ts +211 -0
- package/dist/AgentStepDispatcher.d.ts.map +1 -0
- package/dist/AgentStepDispatcher.js +729 -0
- package/dist/AgentStepDispatcher.js.map +1 -0
- package/dist/AgentTreeBudgetTracker.d.ts +163 -0
- package/dist/AgentTreeBudgetTracker.d.ts.map +1 -0
- package/dist/AgentTreeBudgetTracker.js +415 -0
- package/dist/AgentTreeBudgetTracker.js.map +1 -0
- package/dist/AgentWakeTriggerService.d.ts +41 -1
- package/dist/AgentWakeTriggerService.d.ts.map +1 -1
- package/dist/AgentWakeTriggerService.js +154 -8
- package/dist/AgentWakeTriggerService.js.map +1 -1
- package/dist/MJAIAgentRequestEntityServer.d.ts +32 -1
- package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
- package/dist/MJAIAgentRequestEntityServer.js +105 -3
- package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
- package/dist/PayloadManager.d.ts.map +1 -1
- package/dist/PayloadManager.js +14 -1
- package/dist/PayloadManager.js.map +1 -1
- package/dist/SkillMarkdownConverter.d.ts +1 -1
- package/dist/SkillMarkdownConverter.d.ts.map +1 -1
- package/dist/SkillMarkdownConverter.js +4 -4
- package/dist/SkillMarkdownConverter.js.map +1 -1
- package/dist/agent-pre-execution-rag.d.ts +5 -0
- package/dist/agent-pre-execution-rag.d.ts.map +1 -1
- package/dist/agent-pre-execution-rag.js +5 -0
- package/dist/agent-pre-execution-rag.js.map +1 -1
- package/dist/agent-types/base-agent-type.d.ts.map +1 -1
- package/dist/agent-types/base-agent-type.js +8 -1
- package/dist/agent-types/base-agent-type.js.map +1 -1
- package/dist/agent-types/loop-agent-prompt-params.d.ts +18 -0
- package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-prompt-params.js +2 -0
- package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
- package/dist/base-agent.d.ts +105 -133
- package/dist/base-agent.d.ts.map +1 -1
- package/dist/base-agent.js +395 -1472
- package/dist/base-agent.js.map +1 -1
- package/dist/catalog-narrowing.d.ts +112 -5
- package/dist/catalog-narrowing.d.ts.map +1 -1
- package/dist/catalog-narrowing.js +181 -6
- package/dist/catalog-narrowing.js.map +1 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/dist/pipeline/operators.d.ts.map +1 -1
- package/dist/pipeline/operators.js +1 -1
- package/dist/pipeline/operators.js.map +1 -1
- package/dist/pipeline/pipeline-executor.d.ts +29 -1
- package/dist/pipeline/pipeline-executor.d.ts.map +1 -1
- package/dist/pipeline/pipeline-executor.js +159 -2
- package/dist/pipeline/pipeline-executor.js.map +1 -1
- package/dist/pipeline/pipeline.types.d.ts +19 -1
- package/dist/pipeline/pipeline.types.d.ts.map +1 -1
- package/dist/pipeline/template.d.ts +11 -0
- package/dist/pipeline/template.d.ts.map +1 -1
- package/dist/pipeline/template.js +56 -6
- package/dist/pipeline/template.js.map +1 -1
- package/dist/realtime/bridge-room-transcript-sink.d.ts.map +1 -1
- package/dist/realtime/bridge-room-transcript-sink.js +28 -1
- package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
- package/dist/realtime/media-channel-server.js +1 -1
- package/dist/realtime/media-channel-server.js.map +1 -1
- package/dist/realtime/realtime-client-session-service.d.ts +122 -2
- package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
- package/dist/realtime/realtime-client-session-service.js +413 -4
- package/dist/realtime/realtime-client-session-service.js.map +1 -1
- package/dist/realtime/realtime-coagent-config.d.ts +4 -2
- package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
- package/dist/realtime/realtime-coagent-config.js +27 -38
- package/dist/realtime/realtime-coagent-config.js.map +1 -1
- package/dist/realtime/realtime-delegation-narrator.js +1 -1
- package/dist/realtime/realtime-delegation-narrator.js.map +1 -1
- package/dist/realtime/realtime-session-runner.d.ts +2 -0
- package/dist/realtime/realtime-session-runner.d.ts.map +1 -1
- package/dist/realtime/realtime-session-runner.js +24 -3
- package/dist/realtime/realtime-session-runner.js.map +1 -1
- package/dist/unsafe-object-keys.d.ts +20 -0
- package/dist/unsafe-object-keys.d.ts.map +1 -0
- package/dist/unsafe-object-keys.js +42 -0
- package/dist/unsafe-object-keys.js.map +1 -0
- package/package.json +20 -20
package/dist/base-agent.js
CHANGED
|
@@ -12,7 +12,6 @@
|
|
|
12
12
|
*/
|
|
13
13
|
import { MJEnvironmentEntityExtended, ConversationEngine } from '@memberjunction/core-entities';
|
|
14
14
|
import { BuildActionToolSet, CoerceActionArguments, FilterDeclarableActions, SanitizeToolName } from './native-tools/action-tool-builder.js';
|
|
15
|
-
import { DescribeValueSchemaInline, GetStoredValueSchema } from './native-tools/action-param-schema.js';
|
|
16
15
|
import { ApplyBoundActionParams, BindingsForAction, IsBoundParamName, UnboundParams } from './bound-action-params.js';
|
|
17
16
|
import { BuildNativeToolSet, COMPLETE_TASK_TOOL, SUB_AGENT_TOOL_PREFIX } from './native-tools/control-tools.js';
|
|
18
17
|
import { TurnToolCallingMode } from './native-tools/turn-mode.js';
|
|
@@ -21,19 +20,17 @@ import { BuildFrameworkTools } from './native-tools/framework-tools.js';
|
|
|
21
20
|
import { BuildAssistantToolCallTurn, BuildToolResultTurn, CompactAnsweredToolCallArguments, CompactToolResultContent, CompactToolResultContentAsync } from './native-tools/tool-result-turns.js';
|
|
22
21
|
import { LooksLikeLoopEnvelope } from './native-tools/dual-channel.js';
|
|
23
22
|
import { MJAIAgentRunEntityExtended, ResolvePromptRunUserID, ResolvePayloadAtEnd } from "@memberjunction/ai-core-plus";
|
|
24
|
-
import { Metadata, RunView, LogStatus, LogStatusEx, LogError, LogErrorEx, IsVerboseLoggingEnabled, DatabaseProviderBase,
|
|
23
|
+
import { Metadata, RunView, LogStatus, LogStatusEx, LogError, LogErrorEx, IsVerboseLoggingEnabled, DatabaseProviderBase, ServerOperationScopeManager } from '@memberjunction/core';
|
|
25
24
|
import { AgentRunWatchdog } from './agent-run-watchdog.js';
|
|
26
25
|
import { AIPromptRunner, GetToolCallingDecision, GetSentPrefixFingerprint } from '@memberjunction/ai-prompts';
|
|
27
|
-
import {
|
|
26
|
+
import { BaseRealtimeModel, GetAIAPIKey, CredentialScopeAllows, MakeAIAPIKeyResolver } from '@memberjunction/ai';
|
|
28
27
|
import { BaseAgentType } from './agent-types/base-agent-type.js';
|
|
29
28
|
import { LoopAgentType } from './agent-types/loop-agent-type.js';
|
|
30
29
|
import { ProviderRubricEngine } from '@memberjunction/rubrics';
|
|
31
30
|
import { ExecuteSelfCheck, PickSelfCheckLink } from './self-check.js';
|
|
32
31
|
import { CopyScalarsAndArrays, GroupByUUID, IndexByUUID, JSONValidator, MJGlobal, NormalizeUUID, SafeExpressionEvaluator, UUIDsEqual, UUIDSet, EscapeSQLString, IsPlainObject, CleanAndParseJSON, IsValidUUID } from '@memberjunction/global';
|
|
33
32
|
// token optimization via @memberjunction/context-crush (SmartCrusher/CacheAligner-inspired)
|
|
34
|
-
import {
|
|
35
|
-
// AST-aware code reduction (CodeCompressor-inspired) — opt-in per agent type
|
|
36
|
-
import { CrushCode } from '@memberjunction/context-crush/code';
|
|
33
|
+
import { PartitionStablePrefix } from '@memberjunction/context-crush';
|
|
37
34
|
import { RealtimeSessionRunner } from './realtime/realtime-session-runner.js';
|
|
38
35
|
import { ResolveNarrationInstructionsTemplate } from './realtime/realtime-narration.js';
|
|
39
36
|
import { BuildRealtimeOverridesJson, BuildVoiceMannerSection, GetNarrationPaceMs, GetProviderVoiceSettings, GetSessionTuningSettings, GetModelCatalogSessionSettings, DeepMergeConfigs, ResolveEffectiveRealtimeConfig } from './realtime/realtime-coagent-config.js';
|
|
@@ -56,14 +53,13 @@ import { FormatToolResultSection, FormatToolErrorSection, RenderToolResultData,
|
|
|
56
53
|
import { PriorTurnToolResultCache } from './prior-turn-tool-result-cache.js';
|
|
57
54
|
import { PromptComponentResolver, InjectScopedPromptParts } from './prompt-component-resolver.js';
|
|
58
55
|
import { ScopedPromptConfigResolver, ApplyScopedPromptConfig } from './scoped-prompt-config-resolver.js';
|
|
59
|
-
import { StringifyForPersistence, AIPromptParams, ChildPromptParam, ConversationUtility, ParseFileOutputRef,
|
|
56
|
+
import { StringifyForPersistence, AIPromptParams, ChildPromptParam, ConversationUtility, ParseFileOutputRef, initAgentRunStep, finalizeAgentRunStep, AgentRunStepSaveQueue, ExtractPromptResultText, GetTaskGraphSubmitter, SummarizeDecisionAnswers, SystemPlaceholderManager, WithoutHostOnlyAgentRunDataKeys, WithAgentRunDataTrustApplied, AgentUserPolicyEngine, ConfigOf, ResolveLoopBodyParams, ValidateLoopOperationStructure, BuildTaskSecurityEnvelope, MergeTaskSecurityEnvelopes, TAINTED_EGRESS_BLOCKED, TenantContextCarryProblem, } from '@memberjunction/ai-core-plus';
|
|
60
57
|
import { ActionEngineBase, ActionResult, RunActionParams, AUDIENCE_UNSUPPORTED_RESULT_CODE, ActionRunScopeIsBounded } from '@memberjunction/actions-base';
|
|
61
58
|
import { UserCache } from '@memberjunction/generic-database-provider';
|
|
62
59
|
import { AgentAudienceAddsReader, AgentAudienceProblem, AgentAudienceReaderIDs, MatchAudienceUsers } from './agent-audience.js';
|
|
63
60
|
import { TemplateEngineServer } from '@memberjunction/templates';
|
|
64
|
-
import { RuntimeStateFragmentBuilder, EscapeRuntimeStateTagsInMessage } from './runtime-state-fragment.js';
|
|
65
61
|
import { ResolveSpecializationPlacement } from './volatile-child-prompt.js';
|
|
66
|
-
import {
|
|
62
|
+
import { RUNTIME_STATE_TAG, SCRATCHPAD_NOTES_PLACEHOLDER, SCRATCHPAD_TASK_SUMMARY_PLACEHOLDER, SCRATCHPAD_TASKS_PLACEHOLDER, VOLATILE_TEMPLATE_MARKERS, } from './constants.js';
|
|
67
63
|
import { AgentRunner } from './AgentRunner.js';
|
|
68
64
|
import { PayloadManager } from './PayloadManager.js';
|
|
69
65
|
import { ScratchpadManager } from './ScratchpadManager.js';
|
|
@@ -73,19 +69,22 @@ import { AgentDecisionService } from './AgentDecisionService.js';
|
|
|
73
69
|
import { PayloadFeedbackManager } from './PayloadFeedbackManager.js';
|
|
74
70
|
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';
|
|
75
71
|
import { FinishIfModeWarnings } from './finish-if-mode-warnings.js';
|
|
76
|
-
import { ApplyCatalogNarrowing, BuildCatalogNarrowingQuestions, CatalogNarrowingCandidatesToAsk, CatalogNarrowingNote, CATALOG_NARROWING_FIND_ACTIONS, IsAlwaysShownAction, IsCatalogListNarrowed, NoCatalogNarrowing, OpeningRequestText, ReachableCatalogNarrowingLimits, ResolveCatalogNarrowingLimits, SelectCatalogNarrowing, } from './catalog-narrowing.js';
|
|
72
|
+
import { ApplyCatalogNarrowing, BuildCatalogNarrowingQuestions, CatalogNarrowingCandidatesToAsk, CatalogNarrowingNote, CATALOG_NARROWING_FIND_ACTIONS, CATALOG_NARROWING_FIND_SKILLS, DEFAULT_MAX_SKILL_DECISION_CANDIDATES, IsAlwaysShownAction, IsCatalogListNarrowed, NoCatalogNarrowing, OpeningRequestText, PreFilterSkillCandidatesForDecision, ReachableCatalogNarrowingLimits, ResolveCatalogNarrowingLimits, SelectCatalogNarrowing, } from './catalog-narrowing.js';
|
|
77
73
|
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
74
|
import { ResolveHandoffTarget } from './handoff-target.js';
|
|
79
75
|
import { BuildFinishIfQuestions, CapFinishIfState, FINISH_IF_STATE_EXCERPT, FormatActionForFinishIf, FormatSubAgentForFinishIf, JudgeFinishIf } from './finish-if-state.js';
|
|
80
76
|
import { PipelineExecutor, PipelineToolRegistry, ActionInvocable, ArtifactToolInvocable, BuildPipelineToolDocs, formatFinalOutput, summarizePipelineStages, } from './pipeline/index.js';
|
|
81
77
|
// The ONE payload-mapping dialect. Loop agents and the task-graph dispatcher read the same authored
|
|
82
78
|
// mapping strings, so these must be the same functions rather than two copies that agree today.
|
|
83
|
-
import { GetValueFromPath
|
|
79
|
+
import { GetValueFromPath } from '@memberjunction/ai-core-plus';
|
|
84
80
|
import { AgentDataPreloader } from './AgentDataPreloader.js';
|
|
85
81
|
import { ClientToolRequestManager } from './ClientToolRequestManager.js';
|
|
86
|
-
import { BuildClientToolResultMessage, ResolveClientToolResultMaxChars, ReplaceMediaBlocksWithStubs, IsMediaBlock, IMAGE_BLOCK_TOKEN_ESTIMATE
|
|
82
|
+
import { BuildClientToolResultMessage, ResolveClientToolResultMaxChars, ReplaceMediaBlocksWithStubs, IsMediaBlock, IMAGE_BLOCK_TOKEN_ESTIMATE } from './client-tool-results.js';
|
|
87
83
|
import { CanAgentOwnSubAgentConsults, DEFAULT_MAX_SUB_AGENT_CONSULT_ROUNDS, FormatReloadedConsultsMessage, FormatResponseFormSummary, FormatSubAgentConsultMessage, LoadOpenSubAgentConsults } from './sub-agent-consult.js';
|
|
88
|
-
import {
|
|
84
|
+
import { AgentTreeBudgetTracker } from './AgentTreeBudgetTracker.js';
|
|
85
|
+
import { AgentFeedbackCoordinator } from './AgentFeedbackCoordinator.js';
|
|
86
|
+
import { AgentContextAssembler } from './AgentContextAssembler.js';
|
|
87
|
+
import { AgentStepDispatcher } from './AgentStepDispatcher.js';
|
|
89
88
|
import _ from 'lodash';
|
|
90
89
|
/**
|
|
91
90
|
* Base implementation for AI Agents in the MemberJunction framework.
|
|
@@ -226,6 +225,13 @@ export class BaseAgent {
|
|
|
226
225
|
* @private
|
|
227
226
|
*/
|
|
228
227
|
this._audienceLockedActions = new Set();
|
|
228
|
+
/**
|
|
229
|
+
* Actions refused because the run read untrusted content under a task-graph envelope (`TAINTED_EGRESS_BLOCKED`) —
|
|
230
|
+
* locked out like {@link _fatalActionFailures}, under their own breaker reason (`'tainted'`) so the model is told
|
|
231
|
+
* a person must review that content first rather than that the action is misconfigured.
|
|
232
|
+
* @private
|
|
233
|
+
*/
|
|
234
|
+
this._taintLockedActions = new Set();
|
|
229
235
|
/**
|
|
230
236
|
* External/untrusted data sources ingested during the current agent run (Primitive 2).
|
|
231
237
|
* Once non-empty, {@link IsRunTainted} is true for the remainder of the run and any memory
|
|
@@ -290,8 +296,8 @@ export class BaseAgent {
|
|
|
290
296
|
*/
|
|
291
297
|
this._awaitingWorkflowTaskID = null;
|
|
292
298
|
/**
|
|
293
|
-
* Stores the ID of an AIAgentRequest created when a Chat step fires.
|
|
294
|
-
* Populated by
|
|
299
|
+
* Stores the ID of an AIAgentRequest created when a Chat or Plan step fires.
|
|
300
|
+
* Populated by createFeedbackRequest(), returned in ExecuteAgentResult.feedbackRequestId.
|
|
295
301
|
* Only set for root agents (depth 0), not sub-agents.
|
|
296
302
|
* @private
|
|
297
303
|
*/
|
|
@@ -666,6 +672,24 @@ export class BaseAgent {
|
|
|
666
672
|
* @private
|
|
667
673
|
*/
|
|
668
674
|
static { this.MAX_CONSECUTIVE_UNPRODUCTIVE_RETRIES = 10; }
|
|
675
|
+
/** Collaborator tracking hierarchical token, cost, wall-clock, and attempt budgets across the agent tree. */
|
|
676
|
+
get _budgetTracker() {
|
|
677
|
+
return (this.__budgetTracker ??= new AgentTreeBudgetTracker());
|
|
678
|
+
}
|
|
679
|
+
/** Collaborator coordinating HITL feedback requests, assignment strategy resolution, and List routing. */
|
|
680
|
+
get _feedbackCoordinator() {
|
|
681
|
+
return (this.__feedbackCoordinator ??= new AgentFeedbackCoordinator({
|
|
682
|
+
OnLogStatus: (message, isVerboseOnly, params) => this.logStatus(message, isVerboseOnly, params),
|
|
683
|
+
}));
|
|
684
|
+
}
|
|
685
|
+
/** Collaborator assembling outgoing message arrays, trailing runtime-state fragments, and prompt catalogs. */
|
|
686
|
+
get _contextAssembler() {
|
|
687
|
+
return (this.__contextAssembler ??= new AgentContextAssembler());
|
|
688
|
+
}
|
|
689
|
+
/** Collaborator dispatching step/loop formatting, payload mapping, and template resolution. */
|
|
690
|
+
get _stepDispatcher() {
|
|
691
|
+
return (this.__stepDispatcher ??= new AgentStepDispatcher());
|
|
692
|
+
}
|
|
669
693
|
/**
|
|
670
694
|
* Gets the shared {@link AgentTreeBudget} tracking cumulative steps, tokens, cost,
|
|
671
695
|
* and elapsed wall-clock duration across the root agent and all descendant sub-agents.
|
|
@@ -832,11 +856,14 @@ export class BaseAgent {
|
|
|
832
856
|
}
|
|
833
857
|
}
|
|
834
858
|
/**
|
|
835
|
-
* Locks an action out for the rest of the run: later calls short-circuit on the breaker's `'fatal'` rule,
|
|
836
|
-
* its `'audience'` rule for an action the engine refused for the run's audience
|
|
859
|
+
* Locks an action out for the rest of the run: later calls short-circuit on the breaker's `'fatal'` rule, on
|
|
860
|
+
* its `'audience'` rule for an action the engine refused for the run's audience, or on its `'tainted'` rule for
|
|
861
|
+
* an action refused because the run read untrusted content.
|
|
837
862
|
*/
|
|
838
863
|
lockOutAction(action, actionEntity, reason = 'fatal') {
|
|
839
|
-
const lockouts = reason === 'audience' ? this._audienceLockedActions
|
|
864
|
+
const lockouts = reason === 'audience' ? this._audienceLockedActions
|
|
865
|
+
: reason === 'tainted' ? this._taintLockedActions
|
|
866
|
+
: this._fatalActionFailures;
|
|
840
867
|
lockouts.add(action.name);
|
|
841
868
|
if (actionEntity?.Name) {
|
|
842
869
|
lockouts.add(actionEntity.Name);
|
|
@@ -846,11 +873,13 @@ export class BaseAgent {
|
|
|
846
873
|
resetActionCircuitBreaker() {
|
|
847
874
|
this._fatalActionFailures.clear();
|
|
848
875
|
this._audienceLockedActions.clear();
|
|
876
|
+
this._taintLockedActions.clear();
|
|
849
877
|
this._actionFailureHistory.clear();
|
|
850
878
|
}
|
|
851
879
|
/**
|
|
852
|
-
* The blocked result for an action locked out for the run — refused for the audience (`'audience'`),
|
|
853
|
-
*
|
|
880
|
+
* The blocked result for an action locked out for the run — refused for the audience (`'audience'`), refused
|
|
881
|
+
* because the run read untrusted content (`'tainted'`), or failed with an unrecoverable configuration or
|
|
882
|
+
* credential error (`'fatal'`) — or null when it is not locked out.
|
|
854
883
|
*/
|
|
855
884
|
lockedOutActionResult(params, action, actionEntity) {
|
|
856
885
|
const isLocked = (lockouts) => lockouts.has(action.name) || (!!actionEntity?.Name && lockouts.has(actionEntity.Name));
|
|
@@ -859,6 +888,10 @@ export class BaseAgent {
|
|
|
859
888
|
return this.buildBlockedActionResult(actionEntity, 'audience', `Action '${action.name}' is not available in this shared conversation: what it returns could not be limited to what ` +
|
|
860
889
|
'everyone here may see. Do not call it again in this run; use another tool or answer from what you have.');
|
|
861
890
|
}
|
|
891
|
+
if (isLocked(this._taintLockedActions)) {
|
|
892
|
+
this.logStatus(` ⚡ Circuit breaker: Action '${action.name}' short-circuited (0ms): this run read untrusted content`, false, params);
|
|
893
|
+
return this.buildBlockedActionResult(actionEntity, 'tainted', this.taintLockoutText(action.name));
|
|
894
|
+
}
|
|
862
895
|
if (isLocked(this._fatalActionFailures)) {
|
|
863
896
|
this.logStatus(` ⚡ Circuit breaker: Action '${action.name}' short-circuited (0ms): fatal configuration or credential error earlier in this run`, false, params);
|
|
864
897
|
return this.buildBlockedActionResult(actionEntity, 'fatal', `Action '${action.name}' is disabled for this run because it previously failed with an unrecoverable configuration or ` +
|
|
@@ -866,6 +899,13 @@ export class BaseAgent {
|
|
|
866
899
|
}
|
|
867
900
|
return null;
|
|
868
901
|
}
|
|
902
|
+
/** What the model is told about an action locked out because the run read untrusted content (`'tainted'`). */
|
|
903
|
+
taintLockoutText(name) {
|
|
904
|
+
return `Action '${name}' is not allowed in this run: the run has read untrusted content, and this action sends data ` +
|
|
905
|
+
'out or cannot be undone, so it cannot run until a person reviews that content. It is not broken or misconfigured, ' +
|
|
906
|
+
`and no change to its arguments will help. DO NOT call '${name}' again during this run; use another tool, or tell ` +
|
|
907
|
+
'the user it needs a person to review the content first.';
|
|
908
|
+
}
|
|
869
909
|
/**
|
|
870
910
|
* Clears the parameter-aware failure history for an action after it succeeds, so the
|
|
871
911
|
* identical-arguments rule and the consecutive-attempt budget start over.
|
|
@@ -1054,6 +1094,9 @@ export class BaseAgent {
|
|
|
1054
1094
|
if (this._audienceLockedActions.has(summary.actionName)) {
|
|
1055
1095
|
return 'audience';
|
|
1056
1096
|
}
|
|
1097
|
+
if (this._taintLockedActions.has(summary.actionName)) {
|
|
1098
|
+
return 'tainted';
|
|
1099
|
+
}
|
|
1057
1100
|
if (this._fatalActionFailures.has(summary.actionName)) {
|
|
1058
1101
|
return 'fatal';
|
|
1059
1102
|
}
|
|
@@ -1117,6 +1160,8 @@ export class BaseAgent {
|
|
|
1117
1160
|
return `[CRITICAL/NOT_AVAILABLE_IN_SHARED_CONVERSATION] Action '${name}' is not available in this shared conversation: what it ` +
|
|
1118
1161
|
`returns could not be limited to what everyone in it may see ("${summary.message}"). It is not broken or misconfigured. ` +
|
|
1119
1162
|
`DO NOT call '${name}' again during this run. Use another tool, or answer from what you already have.`;
|
|
1163
|
+
case 'tainted':
|
|
1164
|
+
return `[CRITICAL/NOT_ALLOWED_AFTER_UNTRUSTED_CONTENT] ${this.taintLockoutText(name)}`;
|
|
1120
1165
|
case 'fatal':
|
|
1121
1166
|
return `[CRITICAL/ACTION_UNAVAILABLE] Action '${name}' failed with an unrecoverable configuration or credential error: "${summary.message}". This action cannot execute in this environment. DO NOT call '${name}' again during this run. You MUST select an alternative tool or proceed with available data.`;
|
|
1122
1167
|
case 'attempts-exhausted':
|
|
@@ -1194,6 +1239,29 @@ export class BaseAgent {
|
|
|
1194
1239
|
this._taintedSources.push({ stepNumber, sourceName, trustLevel });
|
|
1195
1240
|
}
|
|
1196
1241
|
}
|
|
1242
|
+
/**
|
|
1243
|
+
* Starts a run tainted when it executes a task-graph node whose input is tainted
|
|
1244
|
+
* (`ExecuteAgentParams.SecurityEnvelope.IsRunTainted`): the node's input derives from untrusted content no
|
|
1245
|
+
* completed Human step reviewed, so the run is tainted before it reads anything itself, exactly as the run
|
|
1246
|
+
* that ingested the content was. Private: a security seed is not an extension point, and an override that
|
|
1247
|
+
* skipped it would start a tainted run clean.
|
|
1248
|
+
*/
|
|
1249
|
+
seedTaintFromSecurityEnvelope(params) {
|
|
1250
|
+
if (params.SecurityEnvelope?.IsRunTainted === true) {
|
|
1251
|
+
this.recordTaintedSource(0, 'task-graph:security-envelope', 'Untrusted');
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1255
|
+
* Starts a sub-agent run tainted when its parent, running outside any task graph, was tainted
|
|
1256
|
+
* (`ExecuteAgentParams.ParentRunTainted`): it works from the parent's context. A sub-agent of a graph
|
|
1257
|
+
* node is seeded through its envelope instead ({@link seedTaintFromSecurityEnvelope}). Private for
|
|
1258
|
+
* the same reason.
|
|
1259
|
+
*/
|
|
1260
|
+
seedTaintFromParentRun(params) {
|
|
1261
|
+
if (params.ParentRunTainted === true) {
|
|
1262
|
+
this.recordTaintedSource(0, 'parent-run', 'Untrusted');
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1197
1265
|
/**
|
|
1198
1266
|
* Folds a finished sub-agent's tainted sources into this run's, attributed to the sub-agent step,
|
|
1199
1267
|
* so delegating a web search taints the parent exactly as searching itself would. Runs whether or
|
|
@@ -1902,6 +1970,13 @@ export class BaseAgent {
|
|
|
1902
1970
|
return 2 * 60 * 60 * 1000;
|
|
1903
1971
|
}
|
|
1904
1972
|
async Execute(params) {
|
|
1973
|
+
// A run is server work even when a client's own request started it (a request answered through the
|
|
1974
|
+
// API resumes its agent without waiting): the async scope would otherwise carry the client's CRUD
|
|
1975
|
+
// boundary into the run, and a save the run makes would read as that person's own act (a task-graph
|
|
1976
|
+
// Human step's completer, an agent request's responder).
|
|
1977
|
+
return ServerOperationScopeManager.Instance.RunAsServerWork(() => this.executeRun(params));
|
|
1978
|
+
}
|
|
1979
|
+
async executeRun(params) {
|
|
1905
1980
|
// Initialize or inherit the shared root-tree cumulative budget before any shallow clone of
|
|
1906
1981
|
// `params` occurs so that callers, parent agents, and child runs share one object reference.
|
|
1907
1982
|
this._treeBudget = undefined;
|
|
@@ -2112,6 +2187,8 @@ export class BaseAgent {
|
|
|
2112
2187
|
this._resolvedHandoffTarget = null;
|
|
2113
2188
|
this._lastSubAgentArtifactDirective = undefined;
|
|
2114
2189
|
this._taintedSources = [];
|
|
2190
|
+
this.seedTaintFromSecurityEnvelope(params);
|
|
2191
|
+
this.seedTaintFromParentRun(params);
|
|
2115
2192
|
this._messageLifecycleCallback = params.onMessageLifecycle;
|
|
2116
2193
|
this._catalogNarrowing = undefined;
|
|
2117
2194
|
this._openingRequest = OpeningRequestText(params.conversationMessages);
|
|
@@ -2403,17 +2480,13 @@ export class BaseAgent {
|
|
|
2403
2480
|
return AgentAudienceAddsReader(params.Audience, params.contextUser?.ID);
|
|
2404
2481
|
}
|
|
2405
2482
|
/**
|
|
2406
|
-
*
|
|
2407
|
-
*
|
|
2408
|
-
* action
|
|
2409
|
-
*
|
|
2410
|
-
*
|
|
2411
|
-
* audience adds a reader, and when the run's validated scope carries a tenant or a secondary dimension
|
|
2412
|
-
* (`ActionRunScopeIsBounded`): a model-written Scoped Search node would search outside the run's tenant, and an
|
|
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.
|
|
2483
|
+
* What this run carries that a graph would have to carry too, or null when nothing: an audience that adds a
|
|
2484
|
+
* reader, host-assigned search scopes, a tenant or secondary dimension (`ActionRunScopeIsBounded`), bound
|
|
2485
|
+
* action parameters, the caller's tenant context, or taint. A graph runs outside the run — its nodes are claimed later
|
|
2486
|
+
* by a dispatcher, as a background worker — so each of these is lost unless the graph's security envelope
|
|
2487
|
+
* carries it.
|
|
2415
2488
|
*/
|
|
2416
|
-
|
|
2489
|
+
taskGraphConstraint(params) {
|
|
2417
2490
|
if (this.runAudienceAddsReader(params)) {
|
|
2418
2491
|
return 'a run with an audience';
|
|
2419
2492
|
}
|
|
@@ -2421,7 +2494,40 @@ export class BaseAgent {
|
|
|
2421
2494
|
if (scope?.SearchScopeIDs?.length) {
|
|
2422
2495
|
return 'a run with host-assigned search scopes';
|
|
2423
2496
|
}
|
|
2424
|
-
|
|
2497
|
+
if (ActionRunScopeIsBounded(scope)) {
|
|
2498
|
+
return 'a tenant-scoped run';
|
|
2499
|
+
}
|
|
2500
|
+
if (this.hasBoundActionParams(params.boundActionParams)) {
|
|
2501
|
+
return 'a run with bound action parameters';
|
|
2502
|
+
}
|
|
2503
|
+
if (params.contextUser?.TenantContext) {
|
|
2504
|
+
return 'a run with a tenant context';
|
|
2505
|
+
}
|
|
2506
|
+
// Taint alone is a constraint too: a graph is the run's work continued elsewhere, and only an
|
|
2507
|
+
// envelope-carrying submitter takes the taint along, so its nodes still refuse egress actions.
|
|
2508
|
+
return this.IsRunTainted || params.SecurityEnvelope?.IsRunTainted === true ? 'a run that ingested untrusted content' : null;
|
|
2509
|
+
}
|
|
2510
|
+
/**
|
|
2511
|
+
* Why this run is not offered task graphs and refuses one the model writes, or null when it may use them — the one
|
|
2512
|
+
* predicate, read by the prompt (`promptWithholding`) and by {@link executeTasksStep} alike, so the two cannot
|
|
2513
|
+
* disagree. A constrained run ({@link taskGraphConstraint}) may use graphs only when the registered submitter
|
|
2514
|
+
* enforces security envelopes (`TaskGraphSubmitter.SupportsSecurityEnvelope`): then the envelope carries the
|
|
2515
|
+
* audience, the validated run scope (tenant, dimensions and search scopes), the bound parameters, the caller's
|
|
2516
|
+
* tenant context and the taint into every node. Nothing the caller passes opens this gate. What the envelope
|
|
2517
|
+
* cannot carry keeps the refusal: a malformed audience, and a tenant context JSON would change.
|
|
2518
|
+
*/
|
|
2519
|
+
taskGraphWithholdingReason(params) {
|
|
2520
|
+
const constraint = this.taskGraphConstraint(params);
|
|
2521
|
+
if (!constraint) {
|
|
2522
|
+
return null;
|
|
2523
|
+
}
|
|
2524
|
+
if (GetTaskGraphSubmitter()?.SupportsSecurityEnvelope !== true) {
|
|
2525
|
+
return constraint;
|
|
2526
|
+
}
|
|
2527
|
+
if (AgentAudienceProblem(params.Audience) !== null) {
|
|
2528
|
+
return 'a run with an audience';
|
|
2529
|
+
}
|
|
2530
|
+
return TenantContextCarryProblem(params.contextUser?.TenantContext) ? 'a run whose tenant context cannot be carried into a task graph' : null;
|
|
2425
2531
|
}
|
|
2426
2532
|
/** Whether this run withholds task graphs ({@link taskGraphWithholdingReason}). */
|
|
2427
2533
|
runWithholdsTaskGraphs(params) {
|
|
@@ -5491,9 +5597,7 @@ export class BaseAgent {
|
|
|
5491
5597
|
* and framework-authored volatile state messages are left alone.
|
|
5492
5598
|
*/
|
|
5493
5599
|
assembleOutgoingMessages(history, fragment, isAppendOnly = false) {
|
|
5494
|
-
|
|
5495
|
-
const sanitized = source.map(m => (m.role === 'system' || m.metadata?.volatileState ? m : EscapeRuntimeStateTagsInMessage(m)));
|
|
5496
|
-
return [...sanitized, fragment];
|
|
5600
|
+
return this._contextAssembler.AssembleOutgoingMessages(history, fragment, isAppendOnly);
|
|
5497
5601
|
}
|
|
5498
5602
|
/**
|
|
5499
5603
|
* Determines whether the current prompt execution should use append-only trailing state retention.
|
|
@@ -5574,17 +5678,7 @@ export class BaseAgent {
|
|
|
5574
5678
|
}
|
|
5575
5679
|
/** Whether the driver serving `model` on `vendor` binds replayed reasoning to the unchanged history before it. */
|
|
5576
5680
|
DriverRequiresStableReasoningPrefix(model, vendor) {
|
|
5577
|
-
|
|
5578
|
-
return false;
|
|
5579
|
-
}
|
|
5580
|
-
const engine = AIEngine.Instance;
|
|
5581
|
-
const modelVendor = (engine.ModelVendorsByModelID?.get(NormalizeUUID(model.ID)) ?? [])
|
|
5582
|
-
.find(mv => UUIDsEqual(mv.VendorID, vendor.ID) && engine.IsInferenceProvider(mv));
|
|
5583
|
-
if (!modelVendor?.DriverClass) {
|
|
5584
|
-
return false;
|
|
5585
|
-
}
|
|
5586
|
-
const driver = MJGlobal.Instance.ClassFactory.GetRegistration(BaseLLM, modelVendor.DriverClass)?.SubClass;
|
|
5587
|
-
return driver?.ReplayedReasoningRequiresStablePrefix === true;
|
|
5681
|
+
return this._contextAssembler.DriverRequiresStableReasoningPrefix(model, vendor);
|
|
5588
5682
|
}
|
|
5589
5683
|
/**
|
|
5590
5684
|
* Whether a model, as served by a vendor, sits behind a byte-prefix prompt cache
|
|
@@ -5600,14 +5694,7 @@ export class BaseAgent {
|
|
|
5600
5694
|
* rows carry no flag, say) can override this rather than the mode decision above.
|
|
5601
5695
|
*/
|
|
5602
5696
|
resolvePrefixPromptCache(model, vendor) {
|
|
5603
|
-
|
|
5604
|
-
return false;
|
|
5605
|
-
}
|
|
5606
|
-
const engine = AIEngine.Instance;
|
|
5607
|
-
const modelVendor = vendor
|
|
5608
|
-
? (engine.ModelVendorsByModelID?.get(NormalizeUUID(model.ID)) ?? []).find(mv => UUIDsEqual(mv.VendorID, vendor.ID) && engine.IsInferenceProvider(mv))
|
|
5609
|
-
: undefined;
|
|
5610
|
-
return IsPrefixPromptCache(engine.GetEffectiveModelConfiguration(model.ID, modelVendor?.ID));
|
|
5697
|
+
return this._contextAssembler.ResolvePrefixPromptCache(model, vendor);
|
|
5611
5698
|
}
|
|
5612
5699
|
/**
|
|
5613
5700
|
* Builds the framework-authored `user` message that carries the loop agent's volatile state as the
|
|
@@ -5643,11 +5730,12 @@ export class BaseAgent {
|
|
|
5643
5730
|
const includeScratchpad = agentTypePromptParams?.includeScratchpadDocs !== false;
|
|
5644
5731
|
const includePayload = agentTypePromptParams?.includePayloadInPrompt !== false;
|
|
5645
5732
|
const specialization = await this.resolveRelocatedSpecialization(promptParams, childPrompt, agentType, params.contextUser);
|
|
5646
|
-
const fragment =
|
|
5733
|
+
const fragment = this._contextAssembler.BuildRuntimeStateFragment({
|
|
5647
5734
|
DateTime: includeDateTime ? await this.resolveFragmentDateTime(promptParams) : null,
|
|
5648
5735
|
Scratchpad: includeScratchpad ? this.readScratchpadFromTemplateData(data) : null,
|
|
5649
5736
|
// Same value the agent type injects for the template (`payload || {}`), so both placements agree.
|
|
5650
|
-
Payload:
|
|
5737
|
+
Payload: payload || {},
|
|
5738
|
+
IncludePayload: includePayload,
|
|
5651
5739
|
Specialization: specialization,
|
|
5652
5740
|
});
|
|
5653
5741
|
if (!fragment) {
|
|
@@ -5735,7 +5823,7 @@ export class BaseAgent {
|
|
|
5735
5823
|
* Loop layout, or any template that embeds the payload.
|
|
5736
5824
|
*/
|
|
5737
5825
|
templateTextEmbedsVolatileState(templateText) {
|
|
5738
|
-
return this.
|
|
5826
|
+
return this._contextAssembler.TemplateTextEmbedsVolatileState(templateText, this.volatileTemplateMarkers);
|
|
5739
5827
|
}
|
|
5740
5828
|
/**
|
|
5741
5829
|
* Raw template text (placeholders intact) for an AI prompt from the cached template engine.
|
|
@@ -5793,36 +5881,20 @@ export class BaseAgent {
|
|
|
5793
5881
|
* on every loop iteration.
|
|
5794
5882
|
*/
|
|
5795
5883
|
async resolveFragmentDateTime(promptParams) {
|
|
5796
|
-
|
|
5797
|
-
|
|
5798
|
-
|
|
5799
|
-
|
|
5800
|
-
|
|
5801
|
-
|
|
5802
|
-
|
|
5803
|
-
return value == null ? null : String(value);
|
|
5804
|
-
}
|
|
5805
|
-
catch (e) {
|
|
5806
|
-
this.logError(e instanceof Error ? e : String(e), { category: 'RuntimeStateFragment', severity: 'warning', metadata: { placeholder: name } });
|
|
5807
|
-
return null;
|
|
5808
|
-
}
|
|
5809
|
-
};
|
|
5810
|
-
const [date, dayOfWeek, time] = await Promise.all([resolve(CURRENT_DATE_PLACEHOLDER), resolve(CURRENT_DAY_OF_WEEK_PLACEHOLDER), resolve(CURRENT_TIME_PLACEHOLDER)]);
|
|
5811
|
-
if (!date || !dayOfWeek || !time) {
|
|
5812
|
-
return null;
|
|
5813
|
-
}
|
|
5814
|
-
return { Date: date, DayOfWeek: dayOfWeek, Time: time };
|
|
5884
|
+
return this._contextAssembler.ResolveFragmentDateTime(promptParams, (error, placeholder) => {
|
|
5885
|
+
this.logError(error instanceof Error ? error : String(error), {
|
|
5886
|
+
category: 'RuntimeStateFragment',
|
|
5887
|
+
severity: 'warning',
|
|
5888
|
+
metadata: { placeholder },
|
|
5889
|
+
});
|
|
5890
|
+
});
|
|
5815
5891
|
}
|
|
5816
5892
|
/**
|
|
5817
5893
|
* The scratchpad strings already placed in the template data by the prep step (so the fragment shows
|
|
5818
5894
|
* exactly what the template would have). Null when the scratchpad is disabled or absent.
|
|
5819
5895
|
*/
|
|
5820
5896
|
readScratchpadFromTemplateData(data) {
|
|
5821
|
-
|
|
5822
|
-
if (typeof notes !== 'string' || typeof tasks !== 'string' || typeof summary !== 'string') {
|
|
5823
|
-
return null;
|
|
5824
|
-
}
|
|
5825
|
-
return { Notes: notes, Tasks: tasks, TaskSummary: summary };
|
|
5897
|
+
return this._contextAssembler.ReadScratchpadFromTemplateData(data);
|
|
5826
5898
|
}
|
|
5827
5899
|
/**
|
|
5828
5900
|
* Executes the configured prompt. Always uses the attemptJSONRepair option to try to fix LLM
|
|
@@ -7251,7 +7323,6 @@ export class BaseAgent {
|
|
|
7251
7323
|
* @protected
|
|
7252
7324
|
*/
|
|
7253
7325
|
async hasExceededAgentRunGuardrails(params, agentRun) {
|
|
7254
|
-
const agent = params.agent;
|
|
7255
7326
|
// Refresh the run's accumulated cost/token actuals before comparing them to the agent's
|
|
7256
7327
|
// static limits.
|
|
7257
7328
|
//
|
|
@@ -7275,98 +7346,21 @@ export class BaseAgent {
|
|
|
7275
7346
|
if (this._agentRun === agentRun) {
|
|
7276
7347
|
this.applyTokenStatsToRun(agentRun, this.calculateTokenStats());
|
|
7277
7348
|
}
|
|
7278
|
-
// Check absolute maximum iterations (safety net to prevent infinite loops)
|
|
7279
7349
|
const absoluteMaxIterations = params.absoluteMaxIterations ?? BaseAgent.DEFAULT_ABSOLUTE_MAX_ITERATIONS;
|
|
7280
|
-
|
|
7281
|
-
|
|
7282
|
-
|
|
7283
|
-
|
|
7284
|
-
|
|
7285
|
-
|
|
7286
|
-
|
|
7287
|
-
|
|
7288
|
-
|
|
7289
|
-
|
|
7290
|
-
|
|
7291
|
-
|
|
7292
|
-
|
|
7293
|
-
|
|
7294
|
-
type: 'cost',
|
|
7295
|
-
limit: agent.MaxCostPerRun,
|
|
7296
|
-
current: agentRun.TotalCost,
|
|
7297
|
-
reason: `Maximum cost limit of $${agent.MaxCostPerRun} exceeded. Current cost: $${agentRun.TotalCost.toFixed(4)}`
|
|
7298
|
-
};
|
|
7299
|
-
}
|
|
7300
|
-
}
|
|
7301
|
-
// Check token limit
|
|
7302
|
-
if (agent.MaxTokensPerRun != null && agentRun.TotalTokensUsed != null) {
|
|
7303
|
-
if (agentRun.TotalTokensUsed >= agent.MaxTokensPerRun) {
|
|
7304
|
-
return {
|
|
7305
|
-
exceeded: true,
|
|
7306
|
-
type: 'tokens',
|
|
7307
|
-
limit: agent.MaxTokensPerRun,
|
|
7308
|
-
current: agentRun.TotalTokensUsed,
|
|
7309
|
-
reason: `Maximum token limit of ${agent.MaxTokensPerRun} exceeded. Current tokens: ${agentRun.TotalTokensUsed}`
|
|
7310
|
-
};
|
|
7311
|
-
}
|
|
7312
|
-
}
|
|
7313
|
-
// Check iteration limit
|
|
7314
|
-
if (agent.MaxIterationsPerRun != null && agentRun.TotalPromptIterations != null) {
|
|
7315
|
-
if (agentRun.TotalPromptIterations >= agent.MaxIterationsPerRun) {
|
|
7316
|
-
return {
|
|
7317
|
-
exceeded: true,
|
|
7318
|
-
type: 'iterations',
|
|
7319
|
-
limit: agent.MaxIterationsPerRun,
|
|
7320
|
-
current: agentRun.TotalPromptIterations,
|
|
7321
|
-
reason: `Maximum iteration limit of ${agent.MaxIterationsPerRun} exceeded. Current iterations: ${agentRun.TotalPromptIterations}`
|
|
7322
|
-
};
|
|
7323
|
-
}
|
|
7324
|
-
}
|
|
7325
|
-
// Check time limit
|
|
7326
|
-
if (agent.MaxTimePerRun != null && agentRun.StartedAt) {
|
|
7327
|
-
const elapsedSeconds = Math.floor((Date.now() - new Date(agentRun.StartedAt).getTime()) / 1000);
|
|
7328
|
-
if (elapsedSeconds >= agent.MaxTimePerRun) {
|
|
7329
|
-
return {
|
|
7330
|
-
exceeded: true,
|
|
7331
|
-
type: 'time',
|
|
7332
|
-
limit: agent.MaxTimePerRun,
|
|
7333
|
-
current: elapsedSeconds,
|
|
7334
|
-
reason: `Maximum time limit of ${agent.MaxTimePerRun} seconds exceeded. Elapsed time: ${elapsedSeconds} seconds`
|
|
7335
|
-
};
|
|
7336
|
-
}
|
|
7337
|
-
}
|
|
7338
|
-
// Check validation retry limit
|
|
7339
|
-
if (this._generalValidationRetryCount >= BaseAgent.MAX_VALIDATION_RETRIES) {
|
|
7340
|
-
return {
|
|
7341
|
-
exceeded: true,
|
|
7342
|
-
type: 'iterations', // Using iterations type since validation retries are a form of iteration
|
|
7343
|
-
limit: BaseAgent.MAX_VALIDATION_RETRIES,
|
|
7344
|
-
current: this._generalValidationRetryCount,
|
|
7345
|
-
reason: `Maximum validation retries of ${BaseAgent.MAX_VALIDATION_RETRIES} exceeded. The agent is unable to produce valid output after ${this._generalValidationRetryCount} validation failures.`
|
|
7346
|
-
};
|
|
7347
|
-
}
|
|
7348
|
-
// Synchronize shared tree budget floor with the current agentRun's metrics (handles both
|
|
7349
|
-
// multi-agent trees and direct guardrail invocations with pre-populated agentRun entities)
|
|
7350
|
-
// and evaluate cumulative root-tree ceilings (maxTreeSteps, maxTreeTokens, maxTreeCost, maxTreeDurationMs).
|
|
7351
|
-
const budget = this.ensureTreeBudget(params);
|
|
7352
|
-
if (agentRun) {
|
|
7353
|
-
const runStepsCount = Math.max(agentRun.Steps?.length ?? 0, agentRun.TotalPromptIterations ?? 0);
|
|
7354
|
-
if (runStepsCount > budget.totalSteps) {
|
|
7355
|
-
budget.totalSteps = runStepsCount;
|
|
7356
|
-
}
|
|
7357
|
-
if ((agentRun.TotalTokensUsed ?? 0) > budget.totalTokens) {
|
|
7358
|
-
budget.totalTokens = agentRun.TotalTokensUsed ?? 0;
|
|
7359
|
-
}
|
|
7360
|
-
if ((agentRun.TotalCost ?? 0) > budget.totalCost) {
|
|
7361
|
-
budget.totalCost = agentRun.TotalCost ?? 0;
|
|
7362
|
-
}
|
|
7363
|
-
}
|
|
7364
|
-
const treeBudgetCheck = this.checkTreeBudgetLimit(params);
|
|
7365
|
-
if (treeBudgetCheck.exceeded) {
|
|
7366
|
-
return treeBudgetCheck;
|
|
7367
|
-
}
|
|
7368
|
-
// No guardrails exceeded
|
|
7369
|
-
return { exceeded: false };
|
|
7350
|
+
const { Result, Budget } = this._budgetTracker.CheckRunAndTreeGuardrails({
|
|
7351
|
+
Params: params,
|
|
7352
|
+
AgentRun: agentRun,
|
|
7353
|
+
ActiveAgentRun: this._agentRun,
|
|
7354
|
+
CurrentBudget: this._treeBudget,
|
|
7355
|
+
FallbackParams: this._executeParams,
|
|
7356
|
+
AbsoluteMaxIterations: absoluteMaxIterations,
|
|
7357
|
+
ValidationRetryCount: this._generalValidationRetryCount,
|
|
7358
|
+
MaxValidationRetries: BaseAgent.MAX_VALIDATION_RETRIES,
|
|
7359
|
+
EnsureTreeBudgetFn: (p) => this.ensureTreeBudget(p),
|
|
7360
|
+
CheckTreeBudgetLimitFn: (p) => this.checkTreeBudgetLimit(p),
|
|
7361
|
+
});
|
|
7362
|
+
this._treeBudget = Budget;
|
|
7363
|
+
return this._budgetTracker.ToLegacyGuardrailVerdict(Result);
|
|
7370
7364
|
}
|
|
7371
7365
|
/**
|
|
7372
7366
|
* Ensures that a shared {@link AgentTreeBudget} instance exists for the current execution tree
|
|
@@ -7385,41 +7379,8 @@ export class BaseAgent {
|
|
|
7385
7379
|
* @protected
|
|
7386
7380
|
*/
|
|
7387
7381
|
ensureTreeBudget(params) {
|
|
7388
|
-
const
|
|
7389
|
-
let budget = effectiveParams?.treeBudget ?? this._treeBudget;
|
|
7390
|
-
if (!budget) {
|
|
7391
|
-
budget = {
|
|
7392
|
-
maxTreeSteps: effectiveParams?.maxTreeSteps,
|
|
7393
|
-
maxTreeTokens: effectiveParams?.maxTreeTokens,
|
|
7394
|
-
maxTreeCost: effectiveParams?.maxTreeCost,
|
|
7395
|
-
maxTreeDurationMs: effectiveParams?.maxTreeDurationMs,
|
|
7396
|
-
totalSteps: 0,
|
|
7397
|
-
totalTokens: 0,
|
|
7398
|
-
totalCost: 0,
|
|
7399
|
-
startedAtMs: Date.now()
|
|
7400
|
-
};
|
|
7401
|
-
}
|
|
7402
|
-
else if (effectiveParams) {
|
|
7403
|
-
if (budget.maxTreeSteps === undefined && effectiveParams.maxTreeSteps !== undefined) {
|
|
7404
|
-
budget.maxTreeSteps = effectiveParams.maxTreeSteps;
|
|
7405
|
-
}
|
|
7406
|
-
if (budget.maxTreeTokens === undefined && effectiveParams.maxTreeTokens !== undefined) {
|
|
7407
|
-
budget.maxTreeTokens = effectiveParams.maxTreeTokens;
|
|
7408
|
-
}
|
|
7409
|
-
if (budget.maxTreeCost === undefined && effectiveParams.maxTreeCost !== undefined) {
|
|
7410
|
-
budget.maxTreeCost = effectiveParams.maxTreeCost;
|
|
7411
|
-
}
|
|
7412
|
-
if (budget.maxTreeDurationMs === undefined && effectiveParams.maxTreeDurationMs !== undefined) {
|
|
7413
|
-
budget.maxTreeDurationMs = effectiveParams.maxTreeDurationMs;
|
|
7414
|
-
}
|
|
7415
|
-
}
|
|
7382
|
+
const budget = this._budgetTracker.EnsureTreeBudget(params, this._treeBudget, this._executeParams);
|
|
7416
7383
|
this._treeBudget = budget;
|
|
7417
|
-
if (effectiveParams) {
|
|
7418
|
-
effectiveParams.treeBudget = budget;
|
|
7419
|
-
}
|
|
7420
|
-
if (this._executeParams && this._executeParams !== effectiveParams) {
|
|
7421
|
-
this._executeParams.treeBudget = budget;
|
|
7422
|
-
}
|
|
7423
7384
|
return budget;
|
|
7424
7385
|
}
|
|
7425
7386
|
/**
|
|
@@ -7438,58 +7399,7 @@ export class BaseAgent {
|
|
|
7438
7399
|
*/
|
|
7439
7400
|
recordPromptUsageInTreeBudget(promptRun, promptResult, params) {
|
|
7440
7401
|
const budget = this.ensureTreeBudget(params);
|
|
7441
|
-
|
|
7442
|
-
if (promptRun) {
|
|
7443
|
-
if (promptRun.TokensUsedRollup != null && promptRun.TokensUsedRollup > 0) {
|
|
7444
|
-
tokensDelta = promptRun.TokensUsedRollup;
|
|
7445
|
-
}
|
|
7446
|
-
else if ((promptRun.TokensPromptRollup != null && promptRun.TokensPromptRollup > 0) ||
|
|
7447
|
-
(promptRun.TokensCompletionRollup != null && promptRun.TokensCompletionRollup > 0)) {
|
|
7448
|
-
tokensDelta = (promptRun.TokensPromptRollup ?? 0) + (promptRun.TokensCompletionRollup ?? 0);
|
|
7449
|
-
}
|
|
7450
|
-
else if (promptRun.TokensUsed != null && promptRun.TokensUsed > 0) {
|
|
7451
|
-
tokensDelta = promptRun.TokensUsed;
|
|
7452
|
-
}
|
|
7453
|
-
else if ((promptRun.TokensPrompt != null && promptRun.TokensPrompt > 0) ||
|
|
7454
|
-
(promptRun.TokensCompletion != null && promptRun.TokensCompletion > 0)) {
|
|
7455
|
-
tokensDelta = (promptRun.TokensPrompt ?? 0) + (promptRun.TokensCompletion ?? 0);
|
|
7456
|
-
}
|
|
7457
|
-
}
|
|
7458
|
-
if (tokensDelta === 0 && promptResult) {
|
|
7459
|
-
if (promptResult.combinedTokensUsed != null && promptResult.combinedTokensUsed > 0) {
|
|
7460
|
-
tokensDelta = promptResult.combinedTokensUsed;
|
|
7461
|
-
}
|
|
7462
|
-
else if ((promptResult.combinedPromptTokens != null && promptResult.combinedPromptTokens > 0) ||
|
|
7463
|
-
(promptResult.combinedCompletionTokens != null && promptResult.combinedCompletionTokens > 0)) {
|
|
7464
|
-
tokensDelta = (promptResult.combinedPromptTokens ?? 0) + (promptResult.combinedCompletionTokens ?? 0);
|
|
7465
|
-
}
|
|
7466
|
-
else if (promptResult.tokensUsed != null && promptResult.tokensUsed > 0) {
|
|
7467
|
-
tokensDelta = promptResult.tokensUsed;
|
|
7468
|
-
}
|
|
7469
|
-
else if ((promptResult.promptTokens != null && promptResult.promptTokens > 0) ||
|
|
7470
|
-
(promptResult.completionTokens != null && promptResult.completionTokens > 0)) {
|
|
7471
|
-
tokensDelta = (promptResult.promptTokens ?? 0) + (promptResult.completionTokens ?? 0);
|
|
7472
|
-
}
|
|
7473
|
-
}
|
|
7474
|
-
let costDelta = 0;
|
|
7475
|
-
if (promptRun) {
|
|
7476
|
-
if (promptRun.TotalCost != null && promptRun.TotalCost > 0) {
|
|
7477
|
-
costDelta = promptRun.TotalCost;
|
|
7478
|
-
}
|
|
7479
|
-
else if (promptRun.Cost != null && promptRun.Cost > 0) {
|
|
7480
|
-
costDelta = promptRun.Cost;
|
|
7481
|
-
}
|
|
7482
|
-
}
|
|
7483
|
-
if (costDelta === 0 && promptResult) {
|
|
7484
|
-
if (promptResult.combinedCost != null && promptResult.combinedCost > 0) {
|
|
7485
|
-
costDelta = promptResult.combinedCost;
|
|
7486
|
-
}
|
|
7487
|
-
else if (promptResult.cost != null && promptResult.cost > 0) {
|
|
7488
|
-
costDelta = promptResult.cost;
|
|
7489
|
-
}
|
|
7490
|
-
}
|
|
7491
|
-
budget.totalTokens += tokensDelta;
|
|
7492
|
-
budget.totalCost += costDelta;
|
|
7402
|
+
this._budgetTracker.RecordPromptUsage(budget, promptRun, promptResult);
|
|
7493
7403
|
}
|
|
7494
7404
|
/**
|
|
7495
7405
|
* Evaluates whether any root-tree cumulative budget ceiling (`maxTreeSteps`, `maxTreeTokens`,
|
|
@@ -7506,60 +7416,8 @@ export class BaseAgent {
|
|
|
7506
7416
|
*/
|
|
7507
7417
|
checkTreeBudgetLimit(params) {
|
|
7508
7418
|
const budget = this.ensureTreeBudget(params);
|
|
7509
|
-
|
|
7510
|
-
|
|
7511
|
-
budget.breachedReason = reason;
|
|
7512
|
-
return {
|
|
7513
|
-
exceeded: true,
|
|
7514
|
-
type: 'iterations',
|
|
7515
|
-
limit: budget.maxTreeSteps,
|
|
7516
|
-
current: budget.totalSteps,
|
|
7517
|
-
reason
|
|
7518
|
-
};
|
|
7519
|
-
}
|
|
7520
|
-
if (budget.maxTreeTokens != null && budget.totalTokens >= budget.maxTreeTokens) {
|
|
7521
|
-
const reason = budget.breachedReason ?? `Agent tree token budget exceeded (${budget.totalTokens}/${budget.maxTreeTokens} total tokens across tree)`;
|
|
7522
|
-
budget.breachedReason = reason;
|
|
7523
|
-
return {
|
|
7524
|
-
exceeded: true,
|
|
7525
|
-
type: 'tokens',
|
|
7526
|
-
limit: budget.maxTreeTokens,
|
|
7527
|
-
current: budget.totalTokens,
|
|
7528
|
-
reason
|
|
7529
|
-
};
|
|
7530
|
-
}
|
|
7531
|
-
if (budget.maxTreeCost != null && budget.totalCost >= budget.maxTreeCost) {
|
|
7532
|
-
const reason = budget.breachedReason ?? `Agent tree cost budget exceeded ($${budget.totalCost.toFixed(4)}/$${budget.maxTreeCost.toFixed(4)} across tree)`;
|
|
7533
|
-
budget.breachedReason = reason;
|
|
7534
|
-
return {
|
|
7535
|
-
exceeded: true,
|
|
7536
|
-
type: 'cost',
|
|
7537
|
-
limit: budget.maxTreeCost,
|
|
7538
|
-
current: budget.totalCost,
|
|
7539
|
-
reason
|
|
7540
|
-
};
|
|
7541
|
-
}
|
|
7542
|
-
if (budget.maxTreeDurationMs != null) {
|
|
7543
|
-
const elapsedMs = Date.now() - budget.startedAtMs;
|
|
7544
|
-
if (elapsedMs >= budget.maxTreeDurationMs) {
|
|
7545
|
-
const reason = budget.breachedReason ?? `Agent tree duration budget exceeded (${elapsedMs}ms/${budget.maxTreeDurationMs}ms across tree)`;
|
|
7546
|
-
budget.breachedReason = reason;
|
|
7547
|
-
return {
|
|
7548
|
-
exceeded: true,
|
|
7549
|
-
type: 'time',
|
|
7550
|
-
limit: budget.maxTreeDurationMs,
|
|
7551
|
-
current: elapsedMs,
|
|
7552
|
-
reason
|
|
7553
|
-
};
|
|
7554
|
-
}
|
|
7555
|
-
}
|
|
7556
|
-
if (budget.breachedReason) {
|
|
7557
|
-
return {
|
|
7558
|
-
exceeded: true,
|
|
7559
|
-
reason: budget.breachedReason
|
|
7560
|
-
};
|
|
7561
|
-
}
|
|
7562
|
-
return { exceeded: false };
|
|
7419
|
+
const result = this._budgetTracker.CheckTreeBudgetLimit(budget);
|
|
7420
|
+
return this._budgetTracker.ToLegacyGuardrailVerdict(result);
|
|
7563
7421
|
}
|
|
7564
7422
|
/**
|
|
7565
7423
|
* Determines if a prompt execution error is fatal and should stop agent execution.
|
|
@@ -9789,7 +9647,17 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
9789
9647
|
// failure surfaces as a 'Failed' step (answering "do pipeline errors show as errors?": yes).
|
|
9790
9648
|
let result;
|
|
9791
9649
|
try {
|
|
9792
|
-
|
|
9650
|
+
// The run's audience (hydrated once per run): a graphExpand stage admits only nodes every reader
|
|
9651
|
+
// may see. An unusable audience refuses the pipeline, as it refuses an action call.
|
|
9652
|
+
const audience = await this.audienceReadersFor(params);
|
|
9653
|
+
if ('Error' in audience) {
|
|
9654
|
+
throw new Error(audience.Error);
|
|
9655
|
+
}
|
|
9656
|
+
result = await new PipelineExecutor(registry, undefined, {
|
|
9657
|
+
contextUser: params.contextUser,
|
|
9658
|
+
provider: this.ProviderToUse,
|
|
9659
|
+
audienceReaders: audience.Readers,
|
|
9660
|
+
}).Execute(pipeline.steps);
|
|
9793
9661
|
}
|
|
9794
9662
|
catch (e) {
|
|
9795
9663
|
result = {
|
|
@@ -10436,11 +10304,10 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10436
10304
|
// and removes any cache-poisoning foot-gun should a future consumer write to it.
|
|
10437
10305
|
agentTypePromptParams = { ...catalog.baseAgentTypePromptParams };
|
|
10438
10306
|
}
|
|
10439
|
-
// A run that withholds task graphs (
|
|
10440
|
-
// them; a copy, so the cached base is never written. executeTasksStep refuses a
|
|
10441
|
-
//
|
|
10442
|
-
|
|
10443
|
-
if (withholding?.TaskGraphs || this.hasBoundActionParams(boundActionParams)) {
|
|
10307
|
+
// A run that withholds task graphs (taskGraphWithholdingReason: a constraint no security envelope will
|
|
10308
|
+
// carry) is not offered them; a copy, so the cached base is never written. executeTasksStep refuses a
|
|
10309
|
+
// graph the model writes anyway, through the same predicate.
|
|
10310
|
+
if (withholding?.TaskGraphs) {
|
|
10444
10311
|
agentTypePromptParams = this.withoutTaskGraphs(agentTypePromptParams);
|
|
10445
10312
|
}
|
|
10446
10313
|
if (withholding?.Handoff) {
|
|
@@ -10570,10 +10437,32 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10570
10437
|
return;
|
|
10571
10438
|
}
|
|
10572
10439
|
try {
|
|
10573
|
-
const
|
|
10440
|
+
const rawCandidates = this.catalogNarrowingCandidates(agent, actions, subAgents, skills);
|
|
10441
|
+
const maxSkillDecisionCandidates = typeof promptParams.maxSkillDecisionCandidates === 'number' && promptParams.maxSkillDecisionCandidates >= 1
|
|
10442
|
+
? Math.floor(promptParams.maxSkillDecisionCandidates)
|
|
10443
|
+
: DEFAULT_MAX_SKILL_DECISION_CANDIDATES;
|
|
10444
|
+
const { FilteredCandidates: candidates, PreHiddenSkillIDs: preHiddenSkillIDs } = PreFilterSkillCandidatesForDecision(rawCandidates, this._openingRequest ?? '', maxSkillDecisionCandidates);
|
|
10574
10445
|
const asked = CatalogNarrowingCandidatesToAsk(candidates, limits);
|
|
10575
10446
|
if (asked.length > 0) {
|
|
10576
|
-
|
|
10447
|
+
const outcome = await this.narrowCatalog(agent, contextUser, promptParams, candidates, asked, limits);
|
|
10448
|
+
if (preHiddenSkillIDs.size > 0) {
|
|
10449
|
+
const mergedSkillHidden = new Set(outcome.Hidden.skill);
|
|
10450
|
+
for (const id of preHiddenSkillIDs) {
|
|
10451
|
+
mergedSkillHidden.add(id);
|
|
10452
|
+
}
|
|
10453
|
+
outcome.Hidden.skill = mergedSkillHidden;
|
|
10454
|
+
}
|
|
10455
|
+
this._catalogNarrowing = outcome;
|
|
10456
|
+
}
|
|
10457
|
+
else if (preHiddenSkillIDs.size > 0) {
|
|
10458
|
+
this._catalogNarrowing = {
|
|
10459
|
+
Hidden: {
|
|
10460
|
+
action: new Set(),
|
|
10461
|
+
agent: new Set(),
|
|
10462
|
+
skill: preHiddenSkillIDs,
|
|
10463
|
+
},
|
|
10464
|
+
Lists: {},
|
|
10465
|
+
};
|
|
10577
10466
|
}
|
|
10578
10467
|
}
|
|
10579
10468
|
catch (error) {
|
|
@@ -10599,17 +10488,22 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10599
10488
|
}
|
|
10600
10489
|
/**
|
|
10601
10490
|
* Every item of the three lists as a narrowing candidate. An action or sub-agent with
|
|
10602
|
-
* `MinExecutionsPerRun` set,
|
|
10491
|
+
* `MinExecutionsPerRun` set, explicitly assigned `MJ: AI Agent Skills` (when the agent also has
|
|
10492
|
+
* unpinned auto-activatable skills), and the Find Candidate tools, are pinned: always shown.
|
|
10603
10493
|
*/
|
|
10604
10494
|
catalogNarrowingCandidates(agent, actions, subAgents, skills) {
|
|
10605
10495
|
const requiredActionIDs = AIEngine.Instance.AgentActions
|
|
10606
10496
|
.filter(aa => UUIDsEqual(aa.AgentID, agent.ID) && aa.Status === 'Active' && (aa.MinExecutionsPerRun ?? 0) > 0)
|
|
10607
10497
|
.map(aa => aa.ActionID);
|
|
10498
|
+
const assignedSkillIDs = new UUIDSet((AIEngine.Instance.AgentSkills ?? [])
|
|
10499
|
+
.filter(as => UUIDsEqual(as.AgentID, agent.ID) && as.Status === 'Active')
|
|
10500
|
+
.map(as => as.SkillID));
|
|
10501
|
+
const hasUnpinnedSkills = skills.some(s => !assignedSkillIDs.Has(s.ID));
|
|
10608
10502
|
const candidate = (kind, item, pinned) => ({ Kind: kind, ID: item.ID, Name: item.Name, Description: item.Description ?? '', Pinned: pinned });
|
|
10609
10503
|
return [
|
|
10610
10504
|
...actions.map(a => candidate('action', a, IsAlwaysShownAction(a.Name) || requiredActionIDs.some(id => UUIDsEqual(id, a.ID)))),
|
|
10611
10505
|
...subAgents.filter(s => !!s).map(s => candidate('agent', s, (s.MinExecutionsPerRun ?? 0) > 0)),
|
|
10612
|
-
...skills.map(s => candidate('skill', s,
|
|
10506
|
+
...skills.map(s => candidate('skill', s, hasUnpinnedSkills && assignedSkillIDs.Has(s.ID))),
|
|
10613
10507
|
];
|
|
10614
10508
|
}
|
|
10615
10509
|
/**
|
|
@@ -10763,7 +10657,10 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10763
10657
|
}
|
|
10764
10658
|
const shownSet = new Set(shown);
|
|
10765
10659
|
const hiddenNames = items.filter(item => !shownSet.has(item)).map(item => item.Name);
|
|
10766
|
-
|
|
10660
|
+
const hasFindCandidateSkills = kind === 'skill' &&
|
|
10661
|
+
this._effectiveActions.some(a => (a.Name ?? '').trim().toLowerCase() === CATALOG_NARROWING_FIND_SKILLS.toLowerCase());
|
|
10662
|
+
const note = CatalogNarrowingNote(kind, hiddenNames, hasFindCandidateSkills ? { hasFindCandidateSkills: true } : undefined);
|
|
10663
|
+
return `${note}\n\n${format(shown)}`;
|
|
10767
10664
|
}
|
|
10768
10665
|
catch (error) {
|
|
10769
10666
|
LogErrorEx({
|
|
@@ -10981,89 +10878,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10981
10878
|
* @since 2.132.0
|
|
10982
10879
|
*/
|
|
10983
10880
|
applyResponseTypeAutoAlignment(params, explicitResponseType) {
|
|
10984
|
-
|
|
10985
|
-
// run's data. Writing into it would turn a key "explicit" for every later merge of that override.
|
|
10986
|
-
if (IsPlainObject(params.includeResponseTypeDefinition)) {
|
|
10987
|
-
params.includeResponseTypeDefinition = { ...params.includeResponseTypeDefinition };
|
|
10988
|
-
}
|
|
10989
|
-
// Ensure includeResponseTypeDefinition is an object
|
|
10990
|
-
else if (!params.includeResponseTypeDefinition || typeof params.includeResponseTypeDefinition !== 'object') {
|
|
10991
|
-
params.includeResponseTypeDefinition = {
|
|
10992
|
-
payload: true,
|
|
10993
|
-
responseForms: true,
|
|
10994
|
-
commands: true,
|
|
10995
|
-
forEach: true,
|
|
10996
|
-
while: true,
|
|
10997
|
-
scratchpad: true,
|
|
10998
|
-
decisions: true,
|
|
10999
|
-
finishIf: true
|
|
11000
|
-
};
|
|
11001
|
-
}
|
|
11002
|
-
const responseType = params.includeResponseTypeDefinition;
|
|
11003
|
-
const decisionsEnabled = this.DecisionsEnabled(params);
|
|
11004
|
-
// finishIf gates are opt-in (`finishIfMode`), and need the master switch. While off, the model is
|
|
11005
|
-
// not taught to write one, whatever includeFinishIfDocs says, so the response field below follows it off too.
|
|
11006
|
-
if (!decisionsEnabled || ResolveFinishIfMode(params.finishIfMode) === 'off') {
|
|
11007
|
-
params.includeFinishIfDocs = false;
|
|
11008
|
-
}
|
|
11009
|
-
// `decisions` is opt-in too (`includeDecisionsDocs: true`), and needs the master switch. Its docs and
|
|
11010
|
-
// types add about 1,200 tokens to every turn, and on the Prompt Eval corpus no model used it
|
|
11011
|
-
// (typed-decision plan, Task 4.7). Unset means off, so the response field below follows it off too.
|
|
11012
|
-
if (!decisionsEnabled || params.includeDecisionsDocs !== true) {
|
|
11013
|
-
params.includeDecisionsDocs = false;
|
|
11014
|
-
}
|
|
11015
|
-
// Auto-alignment mappings: docs flag → response type property
|
|
11016
|
-
const alignmentMappings = [
|
|
11017
|
-
{ docsFlag: 'includePayloadInPrompt', responseTypeKey: 'payload' },
|
|
11018
|
-
{ docsFlag: 'includeResponseFormDocs', responseTypeKey: 'responseForms' },
|
|
11019
|
-
{ docsFlag: 'includeCommandDocs', responseTypeKey: 'commands' },
|
|
11020
|
-
{ docsFlag: 'includeForEachDocs', responseTypeKey: 'forEach' },
|
|
11021
|
-
{ docsFlag: 'includeWhileDocs', responseTypeKey: 'while' },
|
|
11022
|
-
{ docsFlag: 'includeScratchpadDocs', responseTypeKey: 'scratchpad' },
|
|
11023
|
-
{ docsFlag: 'includeArtifactToolsDocs', responseTypeKey: 'artifactToolCalls' },
|
|
11024
|
-
{ docsFlag: 'includeConversationToolsDocs', responseTypeKey: 'conversationToolCalls' },
|
|
11025
|
-
{ docsFlag: 'includePipelineDocs', responseTypeKey: 'pipeline' },
|
|
11026
|
-
{ docsFlag: 'includeMemoryWritesDocs', responseTypeKey: 'memoryWrites' },
|
|
11027
|
-
{ docsFlag: 'includeDecisionsDocs', responseTypeKey: 'decisions' },
|
|
11028
|
-
{ docsFlag: 'includeFinishIfDocs', responseTypeKey: 'finishIf' }
|
|
11029
|
-
];
|
|
11030
|
-
for (const { docsFlag, responseTypeKey } of alignmentMappings) {
|
|
11031
|
-
// Check if the user explicitly set this response type property
|
|
11032
|
-
// (not from schema defaults, which always provide true)
|
|
11033
|
-
const wasExplicitlySet = explicitResponseType &&
|
|
11034
|
-
Object.prototype.hasOwnProperty.call(explicitResponseType, responseTypeKey);
|
|
11035
|
-
// Auto-align: if docs flag is false AND user didn't explicitly set the response type
|
|
11036
|
-
// then auto-align the response type to false
|
|
11037
|
-
if (params[docsFlag] === false && !wasExplicitlySet) {
|
|
11038
|
-
responseType[responseTypeKey] = false;
|
|
11039
|
-
}
|
|
11040
|
-
// If user explicitly set the value, respect it regardless of docs flag
|
|
11041
|
-
// Otherwise default to true if not set
|
|
11042
|
-
else if (responseType[responseTypeKey] === undefined) {
|
|
11043
|
-
responseType[responseTypeKey] = true;
|
|
11044
|
-
}
|
|
11045
|
-
}
|
|
11046
|
-
// With the master switch off, neither decision field is offered, even when set explicitly: the
|
|
11047
|
-
// model must not be invited to ask for something the run would refuse.
|
|
11048
|
-
if (!decisionsEnabled) {
|
|
11049
|
-
responseType.decisions = false;
|
|
11050
|
-
responseType.finishIf = false;
|
|
11051
|
-
}
|
|
11052
|
-
// Capability gates align the OTHER way: default OFF, and the section appears only when the
|
|
11053
|
-
// gate is explicitly on. Running these through the loop above would invert their meaning —
|
|
11054
|
-
// that loop's `else` branch defaults an unset key to true, which is exactly what a gated
|
|
11055
|
-
// capability must never do.
|
|
11056
|
-
const gateMappings = [
|
|
11057
|
-
{ gateFlag: 'enableTaskGraphs', responseTypeKey: 'tasks' },
|
|
11058
|
-
{ gateFlag: 'enableHandoff', responseTypeKey: 'handoff' }
|
|
11059
|
-
];
|
|
11060
|
-
for (const { gateFlag, responseTypeKey } of gateMappings) {
|
|
11061
|
-
const wasExplicitlySet = explicitResponseType &&
|
|
11062
|
-
Object.prototype.hasOwnProperty.call(explicitResponseType, responseTypeKey);
|
|
11063
|
-
if (!wasExplicitlySet) {
|
|
11064
|
-
responseType[responseTypeKey] = params[gateFlag] === true;
|
|
11065
|
-
}
|
|
11066
|
-
}
|
|
10881
|
+
this._contextAssembler.ApplyResponseTypeAutoAlignment(params, explicitResponseType, this.DecisionsEnabled(params));
|
|
11067
10882
|
}
|
|
11068
10883
|
/**
|
|
11069
10884
|
* Extracts default values from a JSON Schema definition.
|
|
@@ -11075,25 +10890,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11075
10890
|
* @since 2.131.0
|
|
11076
10891
|
*/
|
|
11077
10892
|
extractSchemaDefaults(schemaJson) {
|
|
11078
|
-
|
|
11079
|
-
return {};
|
|
11080
|
-
try {
|
|
11081
|
-
const schema = JSON.parse(schemaJson);
|
|
11082
|
-
const defaults = {};
|
|
11083
|
-
if (schema.properties) {
|
|
11084
|
-
for (const [key, prop] of Object.entries(schema.properties)) {
|
|
11085
|
-
const propDef = prop;
|
|
11086
|
-
if (propDef.default !== undefined) {
|
|
11087
|
-
defaults[key] = propDef.default;
|
|
11088
|
-
}
|
|
11089
|
-
}
|
|
11090
|
-
}
|
|
11091
|
-
return defaults;
|
|
11092
|
-
}
|
|
11093
|
-
catch (e) {
|
|
11094
|
-
LogError(`Failed to parse PromptParamsSchema: ${e instanceof Error ? e.message : String(e)}`);
|
|
11095
|
-
return {};
|
|
11096
|
-
}
|
|
10893
|
+
return this._contextAssembler.ExtractSchemaDefaults(schemaJson);
|
|
11097
10894
|
}
|
|
11098
10895
|
/**
|
|
11099
10896
|
* The finishIf settings of the current step, from its merged agent-type prompt params. A gate is
|
|
@@ -11596,10 +11393,20 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11596
11393
|
}
|
|
11597
11394
|
}
|
|
11598
11395
|
// Enforce per-(Agent, User) action policy narrowing rules when a user policy is active
|
|
11599
|
-
const policyBlocked = this.checkUserActionPolicy(params, action, actionEntity, contextUser ?? params.contextUser);
|
|
11396
|
+
const policyBlocked = await this.checkUserActionPolicy(params, action, actionEntity, contextUser ?? params.contextUser);
|
|
11600
11397
|
if (policyBlocked) {
|
|
11601
11398
|
return policyBlocked;
|
|
11602
11399
|
}
|
|
11400
|
+
// A run under a task-graph envelope refuses egress once tainted, whenever the taint arrived. The run
|
|
11401
|
+
// stays tainted and no argument changes the refusal, so the action is locked out for the run, as a
|
|
11402
|
+
// refused binding is: the model is told to stop calling it, not to adjust its arguments and retry.
|
|
11403
|
+
const taintBlocked = this.checkTaintedEgress(params, action, actionEntity, contextUser ?? params.contextUser);
|
|
11404
|
+
if (taintBlocked) {
|
|
11405
|
+
if (!skipBreaker) {
|
|
11406
|
+
this.lockOutAction(action, actionEntity, 'tainted');
|
|
11407
|
+
}
|
|
11408
|
+
return taintBlocked;
|
|
11409
|
+
}
|
|
11603
11410
|
// The run's audience, hydrated once per run — lazily here, since this method is also called outside
|
|
11604
11411
|
// Execute (the pipeline executor, tests). An unusable audience refuses the call: nothing is dispatched.
|
|
11605
11412
|
const audience = await this.audienceReadersFor(params);
|
|
@@ -11608,7 +11415,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11608
11415
|
}
|
|
11609
11416
|
try {
|
|
11610
11417
|
// Execute the action and return the full ActionResult
|
|
11611
|
-
const result = await ActionEngineServer.Instance.RunAction({
|
|
11418
|
+
const result = await AgentUserPolicyEngine.Instance.RunWithExecutingAgentContext(params.agent?.ID ?? '', () => ActionEngineServer.Instance.RunAction({
|
|
11612
11419
|
Action: actionEntity,
|
|
11613
11420
|
Params: this.toActionParams(binding, actionEntity),
|
|
11614
11421
|
ContextUser: contextUser,
|
|
@@ -11616,7 +11423,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11616
11423
|
SkipActionLog: false,
|
|
11617
11424
|
Context: this.stampActionContext(params),
|
|
11618
11425
|
...this.runBoundDispatchParams(params, actionEntity, audience.Readers, contextUser),
|
|
11619
|
-
});
|
|
11426
|
+
}));
|
|
11620
11427
|
this.recordDispatchOutcome(params, action, actionEntity, result, normalizedParams, skipBreaker);
|
|
11621
11428
|
return result;
|
|
11622
11429
|
}
|
|
@@ -11635,16 +11442,60 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11635
11442
|
throw new Error(`Error executing actions: ${error.message}`);
|
|
11636
11443
|
}
|
|
11637
11444
|
}
|
|
11445
|
+
/**
|
|
11446
|
+
* Refuses a `disallowWhenTainted` action (`Action.Config_Object`) in a run that executes under a
|
|
11447
|
+
* task-graph security envelope (`ExecuteAgentParams.SecurityEnvelope`: a graph's agent node, its
|
|
11448
|
+
* continuation turn, or a sub-agent of either) once the run is tainted — checked on every call against
|
|
11449
|
+
* the run's current taint. The node's runner takes those actions away from a run that starts tainted;
|
|
11450
|
+
* this is what stops one that becomes tainted mid-run (it read a web page, then tries to send mail).
|
|
11451
|
+
*/
|
|
11452
|
+
checkTaintedEgress(params, action, actionEntity, contextUser) {
|
|
11453
|
+
if (!params.SecurityEnvelope || !this.IsRunTainted || actionEntity.Config_Object?.disallowWhenTainted !== true) {
|
|
11454
|
+
return null;
|
|
11455
|
+
}
|
|
11456
|
+
return {
|
|
11457
|
+
Success: false,
|
|
11458
|
+
ResultCode: TAINTED_EGRESS_BLOCKED,
|
|
11459
|
+
Message: `Action "${actionEntity.Name}" was not run: this workflow step has read untrusted content, and the action ` +
|
|
11460
|
+
'sends data out or cannot be undone. A person must review the content in a Human step before it can run.',
|
|
11461
|
+
Params: [],
|
|
11462
|
+
RunParams: {
|
|
11463
|
+
Action: actionEntity,
|
|
11464
|
+
Params: this.toActionParams({ Params: action.params ?? {}, Bound: [] }, actionEntity),
|
|
11465
|
+
ContextUser: contextUser,
|
|
11466
|
+
Filters: [],
|
|
11467
|
+
},
|
|
11468
|
+
};
|
|
11469
|
+
}
|
|
11638
11470
|
/**
|
|
11639
11471
|
* Checks per-(Agent, User) action policy narrowing rules (`MJ: AI Agent User Policies`)
|
|
11640
|
-
* before dispatching an action.
|
|
11641
|
-
*
|
|
11472
|
+
* before dispatching an action. Loads the user's policy on cold cache (failing closed on
|
|
11473
|
+
* lookup error) and returns a synthetic ActionResult when the action is denied, deferred
|
|
11474
|
+
* outside a configured time window, or requires explicit user approval.
|
|
11642
11475
|
*/
|
|
11643
|
-
checkUserActionPolicy(params, action, actionEntity, contextUser) {
|
|
11476
|
+
async checkUserActionPolicy(params, action, actionEntity, contextUser) {
|
|
11644
11477
|
if (!contextUser?.ID || !params?.agent?.ID) {
|
|
11645
11478
|
return null;
|
|
11646
11479
|
}
|
|
11647
|
-
|
|
11480
|
+
let policy = AgentUserPolicyEngine.Instance.GetCachedPolicy(params.agent.ID, contextUser.ID, params.provider);
|
|
11481
|
+
if (!policy) {
|
|
11482
|
+
const lookup = await AgentUserPolicyEngine.Instance.ResolvePolicyForAgentAndUser(params.agent.ID, contextUser.ID, contextUser, { provider: params.provider });
|
|
11483
|
+
if (lookup.status === 'error') {
|
|
11484
|
+
return {
|
|
11485
|
+
Success: false,
|
|
11486
|
+
ResultCode: POLICY_DENIED_RESULT_CODE,
|
|
11487
|
+
Message: `Action "${actionEntity.Name || action.name}" blocked (fail-closed): user policy lookup failed (${lookup.errorMessage}).`,
|
|
11488
|
+
Params: [],
|
|
11489
|
+
RunParams: {
|
|
11490
|
+
Action: actionEntity,
|
|
11491
|
+
Params: this.toActionParams({ Params: action.params ?? {}, Bound: [] }, actionEntity),
|
|
11492
|
+
ContextUser: contextUser,
|
|
11493
|
+
Filters: [],
|
|
11494
|
+
},
|
|
11495
|
+
};
|
|
11496
|
+
}
|
|
11497
|
+
policy = lookup.policy;
|
|
11498
|
+
}
|
|
11648
11499
|
if (!policy) {
|
|
11649
11500
|
return null;
|
|
11650
11501
|
}
|
|
@@ -11968,6 +11819,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11968
11819
|
companyId: params.companyId,
|
|
11969
11820
|
SecondaryScopes: params.SecondaryScopes,
|
|
11970
11821
|
SearchScopeIDs: params.SearchScopeIDs, // the host's search scopes bound the sub-agent too
|
|
11822
|
+
...this.subAgentTaint(params), // a tainted parent's sub-agent starts tainted
|
|
11971
11823
|
conversationDetailId: params.conversationDetailId, // propagate conversationDetailId so sub-agent task graphs attach to the chat message
|
|
11972
11824
|
onAgentRunCreated: async (agentRunId) => {
|
|
11973
11825
|
stepEntity.TargetLogID = agentRunId;
|
|
@@ -11976,6 +11828,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11976
11828
|
this.queueStepSave(stepEntity, (s) => { s.TargetLogID = agentRunId; });
|
|
11977
11829
|
}
|
|
11978
11830
|
});
|
|
11831
|
+
// Every sub-agent path (child, related, parallel) comes through here, so the child's taint reaches
|
|
11832
|
+
// the parent whichever path ran it.
|
|
11833
|
+
this.absorbSubAgentTaint(subAgentRequest.name, result, stepEntity?.StepNumber ?? (stepCount + 1));
|
|
11979
11834
|
// Check if execution was successful
|
|
11980
11835
|
if (result.success) {
|
|
11981
11836
|
this.logStatus(`✅ Sub-agent '${subAgentRequest.name}' completed successfully`, true, params);
|
|
@@ -12069,30 +11924,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12069
11924
|
* @private
|
|
12070
11925
|
*/
|
|
12071
11926
|
formatSubAgentDetails(subAgents) {
|
|
12072
|
-
return
|
|
12073
|
-
let line = `- **${sa.Name}** — ${sa.Description}`;
|
|
12074
|
-
if (sa.ExecutionMode !== 'Sequential') {
|
|
12075
|
-
line += ` _(${sa.ExecutionMode}, order: ${sa.ExecutionOrder})_`;
|
|
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
|
-
}
|
|
12094
|
-
return line;
|
|
12095
|
-
}).join('\n');
|
|
11927
|
+
return this._contextAssembler.FormatSubAgentDetails(subAgents);
|
|
12096
11928
|
}
|
|
12097
11929
|
/**
|
|
12098
11930
|
* Formats the skill CATALOG as compact markdown — name + description ONLY. This is
|
|
@@ -12103,7 +11935,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12103
11935
|
* @private
|
|
12104
11936
|
*/
|
|
12105
11937
|
formatSkillsCatalog(skills) {
|
|
12106
|
-
return
|
|
11938
|
+
return this._contextAssembler.FormatSkillsCatalog(skills);
|
|
12107
11939
|
}
|
|
12108
11940
|
/**
|
|
12109
11941
|
* Utility method to get agent prompt parameters for a given agent. This gets the
|
|
@@ -12148,39 +11980,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12148
11980
|
* @private
|
|
12149
11981
|
*/
|
|
12150
11982
|
formatActionDetails(actions, boundActionParams) {
|
|
12151
|
-
return
|
|
12152
|
-
const lines = [];
|
|
12153
|
-
lines.push(`### ${action.Name}`);
|
|
12154
|
-
lines.push(action.Description);
|
|
12155
|
-
const visibleParams = UnboundParams(action.Params.Items, BindingsForAction(boundActionParams, action.ID));
|
|
12156
|
-
const inputParams = visibleParams
|
|
12157
|
-
.filter(p => {
|
|
12158
|
-
const t = p.Type.trim().toLowerCase();
|
|
12159
|
-
return t === 'input' || t === 'both';
|
|
12160
|
-
});
|
|
12161
|
-
const outputParams = visibleParams
|
|
12162
|
-
.filter(p => {
|
|
12163
|
-
const t = p.Type.trim().toLowerCase();
|
|
12164
|
-
return t === 'output' || t === 'both';
|
|
12165
|
-
});
|
|
12166
|
-
if (inputParams.length > 0) {
|
|
12167
|
-
lines.push(`**Input:** ${inputParams.map(p => this.formatActionParameter(p)).join(', ')}`);
|
|
12168
|
-
}
|
|
12169
|
-
if (outputParams.length > 0) {
|
|
12170
|
-
lines.push(`**Output:** ${outputParams.map(p => this.formatActionParameter(p)).join(', ')}`);
|
|
12171
|
-
}
|
|
12172
|
-
if (action.ResultCodes.Items.length > 0) {
|
|
12173
|
-
const rcParts = action.ResultCodes.Items.map(rc => {
|
|
12174
|
-
const marker = rc.IsSuccess ? '✓' : '✗';
|
|
12175
|
-
const desc = rc.Description && rc.Description.toLowerCase() !== rc.ResultCode.toLowerCase()
|
|
12176
|
-
? ` ${rc.Description}`
|
|
12177
|
-
: '';
|
|
12178
|
-
return `${rc.ResultCode} ${marker}${desc}`;
|
|
12179
|
-
});
|
|
12180
|
-
lines.push(`**Results:** ${rcParts.join(' · ')}`);
|
|
12181
|
-
}
|
|
12182
|
-
return lines.join('\n');
|
|
12183
|
-
}).join('\n\n');
|
|
11983
|
+
return this._contextAssembler.FormatActionDetails(actions, boundActionParams);
|
|
12184
11984
|
}
|
|
12185
11985
|
/**
|
|
12186
11986
|
* The client tools in force for a run: the agent's static metadata tools under the session, app
|
|
@@ -12192,24 +11992,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12192
11992
|
* tier, `clientTools` the override tier.
|
|
12193
11993
|
*/
|
|
12194
11994
|
resolveClientToolsForRun(agent, data) {
|
|
12195
|
-
|
|
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 });
|
|
11995
|
+
return this._contextAssembler.ResolveClientToolsForRun(agent, data);
|
|
12213
11996
|
}
|
|
12214
11997
|
/**
|
|
12215
11998
|
* Build the client tool prompt section for system prompt injection.
|
|
@@ -12230,35 +12013,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12230
12013
|
* static metadata tool of the same name. Collisions are rare in practice.
|
|
12231
12014
|
*/
|
|
12232
12015
|
buildClientToolPromptSection(agent, extraData) {
|
|
12233
|
-
|
|
12234
|
-
if (tools.length === 0) {
|
|
12235
|
-
return ''; // No client tools available
|
|
12236
|
-
}
|
|
12237
|
-
const lines = [];
|
|
12238
|
-
lines.push('### Client Tools (execute in the user\'s browser)');
|
|
12239
|
-
lines.push('Client tools run in the user\'s browser and interact with the UI. Use these when you need');
|
|
12240
|
-
lines.push('to navigate the user somewhere, display a specific view, switch dashboard tabs, or show');
|
|
12241
|
-
lines.push('records. When you choose client tools, set nextStep.type to "ClientTools".');
|
|
12242
|
-
lines.push('');
|
|
12243
|
-
lines.push('NOTE: Do NOT use client tools for asking the user questions or collecting input.');
|
|
12244
|
-
lines.push('Use the "Chat" step for that. Client tools read and change the user\'s UI; some return an image.');
|
|
12245
|
-
lines.push('');
|
|
12246
|
-
for (const tool of tools) {
|
|
12247
|
-
const categoryTag = tool.Category ? ` [${tool.Category}]` : '';
|
|
12248
|
-
lines.push(`- **${tool.Name}**${categoryTag}: ${tool.Description}`);
|
|
12249
|
-
// Show input parameters from InputSchema
|
|
12250
|
-
const props = tool.InputSchema?.properties;
|
|
12251
|
-
const required = tool.InputSchema?.required;
|
|
12252
|
-
if (props) {
|
|
12253
|
-
const paramParts = Object.entries(props).map(([name, schema]) => {
|
|
12254
|
-
const req = required?.includes(name) ? '\\*' : '';
|
|
12255
|
-
const desc = schema.description ? ` — ${schema.description}` : '';
|
|
12256
|
-
return `\`${name}\`${req}${desc}`;
|
|
12257
|
-
});
|
|
12258
|
-
lines.push(` Inputs: ${paramParts.join(', ')}`);
|
|
12259
|
-
}
|
|
12260
|
-
}
|
|
12261
|
-
return lines.join('\n');
|
|
12016
|
+
return this._contextAssembler.BuildClientToolPromptSection(agent, extraData);
|
|
12262
12017
|
}
|
|
12263
12018
|
/**
|
|
12264
12019
|
* Build the app context section for system prompt injection.
|
|
@@ -12266,46 +12021,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12266
12021
|
* it as a concise markdown section the LLM can reference.
|
|
12267
12022
|
*/
|
|
12268
12023
|
buildAppContextSection(extraData) {
|
|
12269
|
-
|
|
12270
|
-
if (!ctx)
|
|
12271
|
-
return '';
|
|
12272
|
-
const app = ctx['App'];
|
|
12273
|
-
const activeNav = ctx['ActiveNavItem'];
|
|
12274
|
-
const otherNavs = ctx['OtherNavItems'];
|
|
12275
|
-
const user = ctx['User'];
|
|
12276
|
-
if (!app?.Name)
|
|
12277
|
-
return '';
|
|
12278
|
-
const lines = [];
|
|
12279
|
-
lines.push('### Current Application Context');
|
|
12280
|
-
lines.push(`The user is currently in the **${app.Name}** application${app.Description ? ` — ${app.Description}` : ''}.`);
|
|
12281
|
-
if (activeNav?.Name) {
|
|
12282
|
-
lines.push('');
|
|
12283
|
-
lines.push(`**Active view:** ${activeNav.Name}${activeNav.Description ? ` — ${activeNav.Description}` : ''}${activeNav.ResourceType ? ` (${activeNav.ResourceType})` : ''}`);
|
|
12284
|
-
}
|
|
12285
|
-
if (otherNavs && otherNavs.length > 0) {
|
|
12286
|
-
lines.push('');
|
|
12287
|
-
lines.push('**Other views available in this app:**');
|
|
12288
|
-
for (const nav of otherNavs) {
|
|
12289
|
-
lines.push(`- ${nav.Name}${nav.Description ? ` — ${nav.Description}` : ''}`);
|
|
12290
|
-
}
|
|
12291
|
-
}
|
|
12292
|
-
if (user?.Name) {
|
|
12293
|
-
lines.push('');
|
|
12294
|
-
lines.push(`**User:** ${user.Name}${user.Roles?.length ? ` (Roles: ${user.Roles.join(', ')})` : ''}`);
|
|
12295
|
-
}
|
|
12296
|
-
// Additional context reported by the active view/component
|
|
12297
|
-
const dashboardCtx = ctx['AdditionalContext'];
|
|
12298
|
-
if (dashboardCtx && Object.keys(dashboardCtx).length > 0) {
|
|
12299
|
-
lines.push('');
|
|
12300
|
-
lines.push('**Dashboard state:**');
|
|
12301
|
-
for (const [key, value] of Object.entries(dashboardCtx)) {
|
|
12302
|
-
if (value === null || value === undefined)
|
|
12303
|
-
continue;
|
|
12304
|
-
const displayValue = typeof value === 'object' ? JSON.stringify(value) : String(value);
|
|
12305
|
-
lines.push(`- ${key}: ${displayValue}`);
|
|
12306
|
-
}
|
|
12307
|
-
}
|
|
12308
|
-
return lines.join('\n');
|
|
12024
|
+
return this._contextAssembler.BuildAppContextSection(extraData);
|
|
12309
12025
|
}
|
|
12310
12026
|
/**
|
|
12311
12027
|
* Formats a single action parameter as a compact inline string.
|
|
@@ -12317,28 +12033,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12317
12033
|
* @private
|
|
12318
12034
|
*/
|
|
12319
12035
|
formatActionParameter(param) {
|
|
12320
|
-
|
|
12321
|
-
const parts = [];
|
|
12322
|
-
if (param.IsArray) {
|
|
12323
|
-
parts.push('array');
|
|
12324
|
-
}
|
|
12325
|
-
// A stored ValueSchema is the real type, so it replaces the coarse ValueType label — the
|
|
12326
|
-
// same information the native tool declaration carries.
|
|
12327
|
-
const valueSchema = GetStoredValueSchema(param);
|
|
12328
|
-
const vt = param.ValueType?.trim();
|
|
12329
|
-
if (valueSchema) {
|
|
12330
|
-
parts.push(DescribeValueSchemaInline(valueSchema));
|
|
12331
|
-
}
|
|
12332
|
-
else if (vt && vt !== 'Scalar' && vt !== 'Other') {
|
|
12333
|
-
parts.push(vt);
|
|
12334
|
-
}
|
|
12335
|
-
const suffix = parts.length > 0 ? ` (${parts.join(', ')})` : '';
|
|
12336
|
-
let defaultStr = '';
|
|
12337
|
-
if (param.DefaultValue != null && param.DefaultValue !== '') {
|
|
12338
|
-
defaultStr = ` (default: ${JSON.stringify(param.DefaultValue)})`;
|
|
12339
|
-
}
|
|
12340
|
-
const desc = param.Description ? ` — ${param.Description}` : '';
|
|
12341
|
-
return `\`${param.Name}\`${requiredMarker}${suffix}${desc}${defaultStr}`;
|
|
12036
|
+
return this._contextAssembler.FormatActionParameter(param);
|
|
12342
12037
|
}
|
|
12343
12038
|
/**
|
|
12344
12039
|
* The `user`-role record of what the model asked to run on an Actions turn ("[You invoked ...]").
|
|
@@ -12347,28 +12042,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12347
12042
|
* @protected
|
|
12348
12043
|
*/
|
|
12349
12044
|
buildActionInvocationMessage(actions, params) {
|
|
12350
|
-
|
|
12351
|
-
const aa = actions[0];
|
|
12352
|
-
const shownParams = this.shownActionParamEntries(params, aa);
|
|
12353
|
-
if (shownParams.length === 0) {
|
|
12354
|
-
return `[You invoked the **${aa.name}** action.]`;
|
|
12355
|
-
}
|
|
12356
|
-
const paramsList = shownParams
|
|
12357
|
-
.map(([key, value]) => `• **${key}**: ${this.formatParamValueForMessage(value)}`)
|
|
12358
|
-
.join('\n');
|
|
12359
|
-
return `[You invoked the **${aa.name}** action with parameters:\n${paramsList}\n]`;
|
|
12360
|
-
}
|
|
12361
|
-
return `[You invoked **${actions.length} actions** in parallel:\n\n` + actions.map((aa, index) => {
|
|
12362
|
-
const actionText = `${index + 1}. **${aa.name}**`;
|
|
12363
|
-
const shownParams = this.shownActionParamEntries(params, aa);
|
|
12364
|
-
if (shownParams.length === 0) {
|
|
12365
|
-
return actionText;
|
|
12366
|
-
}
|
|
12367
|
-
const paramsList = shownParams
|
|
12368
|
-
.map(([key, value]) => ` • **${key}**: ${this.formatParamValueForMessage(value)}`)
|
|
12369
|
-
.join('\n');
|
|
12370
|
-
return `${actionText}\n${paramsList}`;
|
|
12371
|
-
}).join('\n\n') + '\n]';
|
|
12045
|
+
return this._stepDispatcher.BuildActionInvocationMessage(actions, (aa) => this.shownActionParamEntries(params, aa));
|
|
12372
12046
|
}
|
|
12373
12047
|
/**
|
|
12374
12048
|
* The action-results message body: a header naming any failures, then each result in the
|
|
@@ -12382,7 +12056,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12382
12056
|
}
|
|
12383
12057
|
/**
|
|
12384
12058
|
* Formats an array of action result summaries as compact markdown instead of
|
|
12385
|
-
* pretty-printed JSON.
|
|
12059
|
+
* pretty-printed JSON. This typically saves 60-70 % of the tokens that the
|
|
12386
12060
|
* old `JSON.stringify(actionSummaries, null, 2)` approach consumed, while
|
|
12387
12061
|
* remaining equally parseable by LLMs.
|
|
12388
12062
|
*
|
|
@@ -12402,53 +12076,11 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12402
12076
|
* @protected
|
|
12403
12077
|
*/
|
|
12404
12078
|
formatActionResultsAsMarkdown(actionSummaries) {
|
|
12405
|
-
return
|
|
12406
|
-
const marker = a.success ? '✓' : '✗';
|
|
12407
|
-
const lines = [];
|
|
12408
|
-
lines.push(`## ${a.actionName} ${marker}`);
|
|
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
|
-
}
|
|
12434
|
-
// Format output params as bullet list. An exempt action's values go out verbatim.
|
|
12435
|
-
if (a.params && a.params.length > 0) {
|
|
12436
|
-
const crush = !this._actionResultCrush?.exemptActions?.has(a.actionName);
|
|
12437
|
-
lines.push('**Output:**');
|
|
12438
|
-
for (const p of a.params) {
|
|
12439
|
-
lines.push(`• \`${p.Name}\`: ${this.formatParamValueForResult(p.Value, 0, crush)}`);
|
|
12440
|
-
}
|
|
12441
|
-
}
|
|
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;
|
|
12447
|
-
}).join('\n\n');
|
|
12079
|
+
return this._stepDispatcher.FormatActionResultsAsMarkdown(actionSummaries, this._actionResultCrush);
|
|
12448
12080
|
}
|
|
12449
12081
|
/**
|
|
12450
12082
|
* Formats an ExecuteAgentResult as compact markdown for inclusion in
|
|
12451
|
-
* conversation messages.
|
|
12083
|
+
* conversation messages. Extracts only the fields that are meaningful
|
|
12452
12084
|
* to the calling agent (success, status, error, and payload) and
|
|
12453
12085
|
* presents them in a concise format.
|
|
12454
12086
|
*
|
|
@@ -12458,90 +12090,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12458
12090
|
* @private
|
|
12459
12091
|
*/
|
|
12460
12092
|
formatSubAgentResultAsMarkdown(subAgentName, result) {
|
|
12461
|
-
|
|
12462
|
-
const lines = [];
|
|
12463
|
-
lines.push(`## Sub-agent: ${subAgentName} ${marker}`);
|
|
12464
|
-
// Status / error from the agent run
|
|
12465
|
-
const status = result.agentRun?.Status || (result.success ? 'Completed' : 'Failed');
|
|
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
|
-
}
|
|
12477
|
-
if (!result.success && result.agentRun?.ErrorMessage) {
|
|
12478
|
-
lines.push(`**Error:** ${result.agentRun.ErrorMessage}`);
|
|
12479
|
-
}
|
|
12480
|
-
if (result.agentRun?.Message?.trim()) {
|
|
12481
|
-
lines.push(`**Message:**\n${result.agentRun.Message.trim()}`);
|
|
12482
|
-
}
|
|
12483
|
-
// Payload — the actual result data the parent agent cares about.
|
|
12484
|
-
// Not truncated by default — the expiration/compaction lifecycle handles
|
|
12485
|
-
// context window management. Truncating here permanently discards data
|
|
12486
|
-
// before the LLM ever sees it.
|
|
12487
|
-
if (result.payload != null) {
|
|
12488
|
-
const payloadStr = typeof result.payload === 'string'
|
|
12489
|
-
? result.payload
|
|
12490
|
-
: JSON.stringify(result.payload);
|
|
12491
|
-
lines.push(`**Payload:**\n${payloadStr}`);
|
|
12492
|
-
}
|
|
12493
|
-
return lines.join('\n');
|
|
12494
|
-
}
|
|
12495
|
-
/**
|
|
12496
|
-
* Formats a single output parameter value for inclusion in action result
|
|
12497
|
-
* markdown. Scalars are shown inline with backtick formatting; objects and
|
|
12498
|
-
* arrays use compact (single-line) JSON to avoid the indentation overhead
|
|
12499
|
-
* of pretty-printed JSON.
|
|
12500
|
-
*
|
|
12501
|
-
* By default, values are **not truncated** — the expiration/compaction lifecycle
|
|
12502
|
-
* handles context window management. Truncating at formatting time permanently
|
|
12503
|
-
* discards data before the LLM ever sees it. Pass an explicit maxLength only
|
|
12504
|
-
* when you have a specific reason to limit output size.
|
|
12505
|
-
*
|
|
12506
|
-
* @param value - The parameter value (any type)
|
|
12507
|
-
* @param maxLength - Maximum character length before truncation (0 = no limit, default 0)
|
|
12508
|
-
* @returns Formatted string
|
|
12509
|
-
* @private
|
|
12510
|
-
*/
|
|
12511
|
-
formatParamValueForResult(value, maxLength = 0, crush = true) {
|
|
12512
|
-
if (value === null || value === undefined) {
|
|
12513
|
-
return '`null`';
|
|
12514
|
-
}
|
|
12515
|
-
if (typeof value === 'boolean' || typeof value === 'number') {
|
|
12516
|
-
return `\`${String(value)}\``;
|
|
12517
|
-
}
|
|
12518
|
-
if (typeof value === 'string') {
|
|
12519
|
-
// A string param may carry JSON (many actions JSON.stringify their payloads),
|
|
12520
|
-
// SQL/TS code, or plain text. Try structural JSON compression first — it is a
|
|
12521
|
-
// safe no-op on non-JSON (crushParamValue's internal JSON.parse failure is
|
|
12522
|
-
// caught and returns null) — then opt-in AST code reduction (SQL/TS), then pass
|
|
12523
|
-
// through (optionally length-capped).
|
|
12524
|
-
const crushedJson = crush ? this.crushParamValue(value) : null;
|
|
12525
|
-
if (crushedJson !== null) {
|
|
12526
|
-
return crushedJson;
|
|
12527
|
-
}
|
|
12528
|
-
const crushedCode = crush ? this.crushCodeValue(value) : null;
|
|
12529
|
-
if (crushedCode !== null) {
|
|
12530
|
-
return crushedCode;
|
|
12531
|
-
}
|
|
12532
|
-
return maxLength > 0 && value.length > maxLength ? `${value.substring(0, maxLength)}…` : value;
|
|
12533
|
-
}
|
|
12534
|
-
// Objects/arrays: compact JSON (no pretty-printing), optionally structurally
|
|
12535
|
-
// compressed via context-crush when crushing is enabled and the value is large.
|
|
12536
|
-
const stringValue = JSON.stringify(value);
|
|
12537
|
-
const crushed = crush ? this.crushParamValue(stringValue) : null;
|
|
12538
|
-
if (crushed !== null) {
|
|
12539
|
-
return crushed;
|
|
12540
|
-
}
|
|
12541
|
-
if (maxLength > 0 && stringValue.length > maxLength) {
|
|
12542
|
-
return `${stringValue.substring(0, maxLength)}…`;
|
|
12543
|
-
}
|
|
12544
|
-
return stringValue;
|
|
12093
|
+
return this._stepDispatcher.FormatSubAgentResultAsMarkdown(subAgentName, result);
|
|
12545
12094
|
}
|
|
12546
12095
|
/**
|
|
12547
12096
|
* Resolve the per-run action-result compression config from the agent-type prompt
|
|
@@ -12550,109 +12099,19 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12550
12099
|
* @private
|
|
12551
12100
|
*/
|
|
12552
12101
|
resolveActionResultCrush(params) {
|
|
12553
|
-
|
|
12554
|
-
if (agentTypePromptParams?.crushActionResults === false) {
|
|
12555
|
-
return undefined;
|
|
12556
|
-
}
|
|
12557
|
-
const requestedLang = agentTypePromptParams?.crushCodeLang;
|
|
12558
|
-
const codeLang = requestedLang === 'sql' || requestedLang === 'typescript' ? requestedLang : undefined;
|
|
12559
|
-
const uncrushed = agentTypePromptParams?.uncrushedActions;
|
|
12560
|
-
const exemptActions = new Set(Array.isArray(uncrushed) ? uncrushed.filter((name) => typeof name === 'string') : []);
|
|
12561
|
-
return { threshold: BaseAgent.ACTION_RESULT_CRUSH_THRESHOLD, maxChars: undefined, codeLang, exemptActions };
|
|
12562
|
-
}
|
|
12563
|
-
/**
|
|
12564
|
-
* AST-reduce a large code-string action-result value when the agent opted into a code
|
|
12565
|
-
* language (via `crushCodeLang` or a subclass override) and the value clears the size
|
|
12566
|
-
* threshold. Returns reduced code plus a one-line legend, or null to keep the string
|
|
12567
|
-
* verbatim (crushing disabled, too small, or no net saving).
|
|
12568
|
-
*
|
|
12569
|
-
* token optimization via @memberjunction/context-crush (CodeCompressor-inspired)
|
|
12570
|
-
* @private
|
|
12571
|
-
*/
|
|
12572
|
-
crushCodeValue(stringValue) {
|
|
12573
|
-
const config = this._actionResultCrush;
|
|
12574
|
-
if (!config || !config.codeLang || stringValue.length < config.threshold) {
|
|
12575
|
-
return null;
|
|
12576
|
-
}
|
|
12577
|
-
// Crushing is a best-effort optimization — it must never break an agent turn. Any
|
|
12578
|
-
// failure falls back to the verbatim value.
|
|
12579
|
-
try {
|
|
12580
|
-
const result = CrushCode(stringValue, config.codeLang);
|
|
12581
|
-
if (result.CrushedChars >= result.OriginalChars) {
|
|
12582
|
-
return null;
|
|
12583
|
-
}
|
|
12584
|
-
const legend = DescribeCrush(result);
|
|
12585
|
-
return legend ? `${result.Text}\n ↳ ${legend}` : result.Text;
|
|
12586
|
-
}
|
|
12587
|
-
catch {
|
|
12588
|
-
return null;
|
|
12589
|
-
}
|
|
12590
|
-
}
|
|
12591
|
-
/**
|
|
12592
|
-
* Structurally compress a JSON action-result value when crushing is enabled for the run
|
|
12593
|
-
* and the value clears the size threshold. Accepts either the `JSON.stringify` of an
|
|
12594
|
-
* object/array param, or a raw string param that itself contains JSON (many actions
|
|
12595
|
-
* stringify their payloads, e.g. `run-adhoc-query`'s `Results`). Returns crushed text
|
|
12596
|
-
* plus a one-line legend, or null when crushing is disabled, the value is too small, the
|
|
12597
|
-
* value isn't valid JSON, or compression wouldn't actually save characters — so callers
|
|
12598
|
-
* fall back to verbatim (and, for strings, to code crushing) behavior.
|
|
12599
|
-
*
|
|
12600
|
-
* token optimization via @memberjunction/context-crush (SmartCrusher-inspired)
|
|
12601
|
-
* @private
|
|
12602
|
-
*/
|
|
12603
|
-
crushParamValue(stringValue) {
|
|
12604
|
-
const config = this._actionResultCrush;
|
|
12605
|
-
if (!config || stringValue.length < config.threshold) {
|
|
12606
|
-
return null;
|
|
12607
|
-
}
|
|
12608
|
-
// Crushing is a best-effort optimization — it must never break an agent turn. Any
|
|
12609
|
-
// failure (non-JSON input, pathologically deep payloads) falls back to verbatim.
|
|
12610
|
-
try {
|
|
12611
|
-
// Parse to a plain JSON value. This is the JSON.stringify of an object/array
|
|
12612
|
-
// param, or a raw string param that contains JSON; non-JSON strings throw here
|
|
12613
|
-
// and are caught below (caller then tries code crushing / verbatim).
|
|
12614
|
-
const json = JSON.parse(stringValue);
|
|
12615
|
-
const result = CrushJSON(json, { MaxChars: config.maxChars });
|
|
12616
|
-
if (result.CrushedChars >= result.OriginalChars) {
|
|
12617
|
-
return null; // no net saving — keep the verbatim JSON
|
|
12618
|
-
}
|
|
12619
|
-
const legend = DescribeCrush(result);
|
|
12620
|
-
return legend ? `${result.Text}\n ↳ ${legend}` : result.Text;
|
|
12621
|
-
}
|
|
12622
|
-
catch {
|
|
12623
|
-
return null;
|
|
12624
|
-
}
|
|
12102
|
+
return this._stepDispatcher.ResolveActionResultCrush(params, this._agentTypePromptParams, BaseAgent.ACTION_RESULT_CRUSH_THRESHOLD);
|
|
12625
12103
|
}
|
|
12626
12104
|
/**
|
|
12627
12105
|
* Formats a parameter value for display in action execution messages.
|
|
12628
12106
|
* Truncates long strings and formats objects/arrays for readability.
|
|
12629
12107
|
*
|
|
12630
|
-
* @param {
|
|
12108
|
+
* @param {unknown} value - The parameter value to format
|
|
12631
12109
|
* @param {number} maxLength - Maximum length before truncation (default: 100)
|
|
12632
12110
|
* @returns {string} Formatted value suitable for message display
|
|
12633
12111
|
* @private
|
|
12634
12112
|
*/
|
|
12635
12113
|
formatParamValueForMessage(value, maxLength = 100) {
|
|
12636
|
-
|
|
12637
|
-
return 'null';
|
|
12638
|
-
}
|
|
12639
|
-
let stringValue;
|
|
12640
|
-
if (typeof value === 'string') {
|
|
12641
|
-
stringValue = value;
|
|
12642
|
-
}
|
|
12643
|
-
else if (typeof value === 'object') {
|
|
12644
|
-
// For objects/arrays, use compact JSON
|
|
12645
|
-
stringValue = JSON.stringify(value);
|
|
12646
|
-
}
|
|
12647
|
-
else {
|
|
12648
|
-
stringValue = String(value);
|
|
12649
|
-
}
|
|
12650
|
-
// Truncate if too long
|
|
12651
|
-
if (stringValue.length > maxLength) {
|
|
12652
|
-
return `\`${stringValue.substring(0, maxLength)}...\``;
|
|
12653
|
-
}
|
|
12654
|
-
// Use inline code formatting for values
|
|
12655
|
-
return `\`${stringValue}\``;
|
|
12114
|
+
return this._stepDispatcher.FormatParamValueForMessage(value, maxLength);
|
|
12656
12115
|
}
|
|
12657
12116
|
/**
|
|
12658
12117
|
* Gets the agent type name for a given type ID.
|
|
@@ -14760,7 +14219,6 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14760
14219
|
// Child sub-agents don't use context messages (they inherit payload directly)
|
|
14761
14220
|
const subAgentResult = await this.ExecuteSubAgent(params, subAgentRequest, subAgentEntity, stepEntity, scopedPayload, undefined, // No context message for child sub-agents
|
|
14762
14221
|
stepCount);
|
|
14763
|
-
this.absorbSubAgentTaint(subAgentRequest.name, subAgentResult, stepEntity?.StepNumber ?? (stepCount + 1));
|
|
14764
14222
|
let mergedPayload = previousDecision.newPayload; // Start with the original payload
|
|
14765
14223
|
let currentStepPayloadChangeResult = undefined;
|
|
14766
14224
|
if (subAgentResult.success) {
|
|
@@ -15172,28 +14630,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15172
14630
|
* @protected
|
|
15173
14631
|
*/
|
|
15174
14632
|
cloneSubAgentPayload(payload) {
|
|
15175
|
-
|
|
15176
|
-
return payload;
|
|
15177
|
-
if (typeof payload !== 'object')
|
|
15178
|
-
return payload;
|
|
15179
|
-
if (typeof globalThis.structuredClone === 'function') {
|
|
15180
|
-
try {
|
|
15181
|
-
return globalThis.structuredClone(payload);
|
|
15182
|
-
}
|
|
15183
|
-
catch {
|
|
15184
|
-
// DataCloneError — typically a Proxy (a live JSONType `<Field>Object` view) or an
|
|
15185
|
-
// object holding functions. Fall through to the JSON clone below; returning the
|
|
15186
|
-
// original here would silently give the sub-agent the caller's LIVE object and lose
|
|
15187
|
-
// payload isolation.
|
|
15188
|
-
}
|
|
15189
|
-
}
|
|
15190
|
-
try {
|
|
15191
|
-
return ToPlainJSON(payload);
|
|
15192
|
-
}
|
|
15193
|
-
catch (error) {
|
|
15194
|
-
LogError(`BaseAgent.cloneSubAgentPayload: payload could not be cloned (${error instanceof Error ? error.message : String(error)}); sub-agent will share the caller's object`);
|
|
15195
|
-
return payload;
|
|
15196
|
-
}
|
|
14633
|
+
return this._stepDispatcher.CloneSubAgentPayload(payload);
|
|
15197
14634
|
}
|
|
15198
14635
|
/**
|
|
15199
14636
|
* Pre-flight for one parallel sub-agent: resolve the entity, push the
|
|
@@ -15961,66 +15398,8 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15961
15398
|
*
|
|
15962
15399
|
* @private
|
|
15963
15400
|
*/
|
|
15964
|
-
applySubAgentOutputMapping(subAgentResult,
|
|
15965
|
-
|
|
15966
|
-
const mapping = JSON.parse(mappingConfig);
|
|
15967
|
-
const updateObj = {};
|
|
15968
|
-
for (const [subAgentPath, parentPath] of Object.entries(mapping)) {
|
|
15969
|
-
let value;
|
|
15970
|
-
if (subAgentPath === '*') {
|
|
15971
|
-
// Wildcard - capture entire sub-agent result
|
|
15972
|
-
value = subAgentResult;
|
|
15973
|
-
}
|
|
15974
|
-
else {
|
|
15975
|
-
// Extract from sub-agent result using dot notation
|
|
15976
|
-
value = this.getValueFromPath(subAgentResult, subAgentPath);
|
|
15977
|
-
}
|
|
15978
|
-
if (value !== undefined) {
|
|
15979
|
-
// Parse the parent path and build nested object
|
|
15980
|
-
const pathParts = parentPath.split('.');
|
|
15981
|
-
let current = updateObj;
|
|
15982
|
-
for (let i = 0; i < pathParts.length - 1; i++) {
|
|
15983
|
-
const part = pathParts[i];
|
|
15984
|
-
// Remove [] suffix for intermediate path parts
|
|
15985
|
-
const cleanPart = part.endsWith('[]') ? part.slice(0, -2) : part;
|
|
15986
|
-
if (!(cleanPart in current)) {
|
|
15987
|
-
current[cleanPart] = {};
|
|
15988
|
-
}
|
|
15989
|
-
current = current[cleanPart];
|
|
15990
|
-
}
|
|
15991
|
-
// Use helper to support array append on final path part
|
|
15992
|
-
this.setMappedValue(current, pathParts[pathParts.length - 1], value);
|
|
15993
|
-
}
|
|
15994
|
-
}
|
|
15995
|
-
if (Object.keys(updateObj).length === 0) {
|
|
15996
|
-
return null;
|
|
15997
|
-
}
|
|
15998
|
-
return {
|
|
15999
|
-
updateElements: updateObj
|
|
16000
|
-
};
|
|
16001
|
-
}
|
|
16002
|
-
catch (error) {
|
|
16003
|
-
LogError(`Failed to parse SubAgentOutputMapping: ${error.message}`);
|
|
16004
|
-
return null;
|
|
16005
|
-
}
|
|
16006
|
-
}
|
|
16007
|
-
/**
|
|
16008
|
-
* Sets a value in a target object, supporting array append operations.
|
|
16009
|
-
* If the key ends with [], the value is appended to an array instead of replacing.
|
|
16010
|
-
*
|
|
16011
|
-
* @param target - Target object to modify
|
|
16012
|
-
* @param key - Property key, optionally ending with [] for array append
|
|
16013
|
-
* @param value - Value to set or append
|
|
16014
|
-
* @private
|
|
16015
|
-
*/
|
|
16016
|
-
/**
|
|
16017
|
-
* Sets a value on a target object, honouring the `[]` array-append suffix.
|
|
16018
|
-
*
|
|
16019
|
-
* Delegates for the same reason as {@link getValueFromPath} — `results[]` must mean append in
|
|
16020
|
-
* both engines, or a workflow accumulates in one and overwrites in the other.
|
|
16021
|
-
*/
|
|
16022
|
-
setMappedValue(target, key, value) {
|
|
16023
|
-
SetMappedValue(target, key, value);
|
|
15401
|
+
applySubAgentOutputMapping(subAgentResult, parentPayload, mappingConfig) {
|
|
15402
|
+
return this._stepDispatcher.ApplySubAgentOutputMapping(subAgentResult, parentPayload, mappingConfig, (obj, path) => this.getValueFromPath(obj, path));
|
|
16024
15403
|
}
|
|
16025
15404
|
/**
|
|
16026
15405
|
* Applies sub-agent input mapping to prepare initial payload for related sub-agent.
|
|
@@ -16033,42 +15412,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16033
15412
|
* @private
|
|
16034
15413
|
*/
|
|
16035
15414
|
applySubAgentInputMapping(parentPayload, mappingConfig) {
|
|
16036
|
-
|
|
16037
|
-
const mapping = JSON.parse(mappingConfig);
|
|
16038
|
-
const subAgentPayload = {};
|
|
16039
|
-
for (const [parentPath, subAgentPath] of Object.entries(mapping)) {
|
|
16040
|
-
let value;
|
|
16041
|
-
if (parentPath === '*') {
|
|
16042
|
-
// Wildcard - send entire parent payload to sub-agent
|
|
16043
|
-
value = parentPayload;
|
|
16044
|
-
}
|
|
16045
|
-
else {
|
|
16046
|
-
// Extract from parent payload using dot notation
|
|
16047
|
-
value = this.getValueFromPath(parentPayload, parentPath);
|
|
16048
|
-
}
|
|
16049
|
-
if (value !== undefined) {
|
|
16050
|
-
// Parse the sub-agent path and build nested object
|
|
16051
|
-
const pathParts = subAgentPath.split('.');
|
|
16052
|
-
let current = subAgentPayload;
|
|
16053
|
-
for (let i = 0; i < pathParts.length - 1; i++) {
|
|
16054
|
-
const part = pathParts[i];
|
|
16055
|
-
if (!(part in current)) {
|
|
16056
|
-
current[part] = {};
|
|
16057
|
-
}
|
|
16058
|
-
current = current[part];
|
|
16059
|
-
}
|
|
16060
|
-
current[pathParts[pathParts.length - 1]] = value;
|
|
16061
|
-
}
|
|
16062
|
-
}
|
|
16063
|
-
if (Object.keys(subAgentPayload).length === 0) {
|
|
16064
|
-
return null;
|
|
16065
|
-
}
|
|
16066
|
-
return subAgentPayload;
|
|
16067
|
-
}
|
|
16068
|
-
catch (error) {
|
|
16069
|
-
LogError(`Failed to parse SubAgentInputMapping: ${error.message}`);
|
|
16070
|
-
return null;
|
|
16071
|
-
}
|
|
15415
|
+
return this._stepDispatcher.ApplySubAgentInputMapping(parentPayload, mappingConfig, (obj, path) => this.getValueFromPath(obj, path));
|
|
16072
15416
|
}
|
|
16073
15417
|
/**
|
|
16074
15418
|
* Prepares a context message containing parent payload data for related sub-agent.
|
|
@@ -16086,46 +15430,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16086
15430
|
* @private
|
|
16087
15431
|
*/
|
|
16088
15432
|
prepareRelatedSubAgentContextMessage(parentPayload, contextPaths, params) {
|
|
16089
|
-
|
|
16090
|
-
return null;
|
|
16091
|
-
}
|
|
16092
|
-
// Check for wildcard - send entire payload
|
|
16093
|
-
if (contextPaths.includes('*')) {
|
|
16094
|
-
return {
|
|
16095
|
-
role: 'user',
|
|
16096
|
-
content: `Parent Agent Context:\n\n${JSON.stringify(parentPayload, null, 2)}`
|
|
16097
|
-
};
|
|
16098
|
-
}
|
|
16099
|
-
// Extract specific paths (supports both payload paths and conversation paths)
|
|
16100
|
-
const contextData = {};
|
|
16101
|
-
for (const path of contextPaths) {
|
|
16102
|
-
let value;
|
|
16103
|
-
// Check if this is a conversation reference
|
|
16104
|
-
if (ConversationMessageResolver.isConversationReference(path) && params?.conversationMessages) {
|
|
16105
|
-
value = ConversationMessageResolver.resolve(path, params.conversationMessages);
|
|
16106
|
-
}
|
|
16107
|
-
else {
|
|
16108
|
-
// Regular payload path
|
|
16109
|
-
value = this.getValueFromPath(parentPayload, path);
|
|
16110
|
-
}
|
|
16111
|
-
if (value !== undefined) {
|
|
16112
|
-
contextData[path] = value;
|
|
16113
|
-
}
|
|
16114
|
-
}
|
|
16115
|
-
if (Object.keys(contextData).length === 0) {
|
|
16116
|
-
return null;
|
|
16117
|
-
}
|
|
16118
|
-
// Format as readable context
|
|
16119
|
-
const contextLines = Object.entries(contextData).map(([key, value]) => {
|
|
16120
|
-
const valueStr = typeof value === 'object'
|
|
16121
|
-
? JSON.stringify(value, null, 2)
|
|
16122
|
-
: String(value);
|
|
16123
|
-
return `${key}:\n${valueStr}`;
|
|
16124
|
-
});
|
|
16125
|
-
return {
|
|
16126
|
-
role: 'user',
|
|
16127
|
-
content: `Parent Agent Context:\n\n${contextLines.join('\n\n')}`
|
|
16128
|
-
};
|
|
15433
|
+
return this._stepDispatcher.PrepareRelatedSubAgentContextMessage(parentPayload, contextPaths, params, (obj, path) => this.getValueFromPath(obj, path));
|
|
16129
15434
|
}
|
|
16130
15435
|
/**
|
|
16131
15436
|
* Helper method to get a value from a nested object path.
|
|
@@ -17221,24 +16526,22 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17221
16526
|
};
|
|
17222
16527
|
}
|
|
17223
16528
|
const spec = this.canonicalizeTaskGraphSpec(rawSpec);
|
|
17224
|
-
// Fail closed
|
|
17225
|
-
|
|
17226
|
-
|
|
17227
|
-
|
|
17228
|
-
|
|
16529
|
+
// Fail closed on anything the graph could not carry (the same predicate the prompt used to hide `tasks`).
|
|
16530
|
+
const withheld = this.taskGraphRefusal(params, previousDecision);
|
|
16531
|
+
if (withheld) {
|
|
16532
|
+
return withheld;
|
|
16533
|
+
}
|
|
16534
|
+
const envelope = this.taskGraphSecurityEnvelope(params);
|
|
16535
|
+
if ('Refusal' in envelope) {
|
|
17229
16536
|
return {
|
|
17230
16537
|
step: 'Failed',
|
|
17231
16538
|
terminate: true,
|
|
17232
|
-
errorMessage:
|
|
16539
|
+
errorMessage: `Task graph not submitted: ${envelope.Refusal}`,
|
|
17233
16540
|
previousPayload: previousDecision.previousPayload,
|
|
17234
16541
|
newPayload: previousDecision.newPayload || previousDecision.previousPayload
|
|
17235
16542
|
};
|
|
17236
16543
|
}
|
|
17237
|
-
|
|
17238
|
-
const withheld = this.taskGraphRefusal(params, previousDecision);
|
|
17239
|
-
if (withheld) {
|
|
17240
|
-
return withheld;
|
|
17241
|
-
}
|
|
16544
|
+
const securityEnvelope = envelope.Envelope;
|
|
17242
16545
|
const stepEntity = await this.createStepEntity({
|
|
17243
16546
|
stepType: 'TaskGraph',
|
|
17244
16547
|
stepName: `Task Graph: ${spec.workflowName}`,
|
|
@@ -17276,7 +16579,8 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17276
16579
|
Invocation: { Data: params.data, Context: params.context },
|
|
17277
16580
|
Debug: params.taskGraphDebug?.paused ? { paused: true } : undefined,
|
|
17278
16581
|
ContextUser: params.contextUser,
|
|
17279
|
-
Provider: this.ProviderToUse
|
|
16582
|
+
Provider: this.ProviderToUse,
|
|
16583
|
+
...(securityEnvelope ? { SecurityEnvelope: securityEnvelope } : {}),
|
|
17280
16584
|
});
|
|
17281
16585
|
await this.finalizeStepEntity(stepEntity, outcome.Success, outcome.ErrorMessage, { spec, submitted: outcome.Success, parentTaskID: outcome.ParentTaskID });
|
|
17282
16586
|
if (!outcome.Success) {
|
|
@@ -17310,6 +16614,44 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17310
16614
|
newPayload: previousDecision.newPayload || previousDecision.previousPayload
|
|
17311
16615
|
};
|
|
17312
16616
|
}
|
|
16617
|
+
/**
|
|
16618
|
+
* How a sub-agent run inherits this run's taint (S2). A sub-agent works from this run's context, so it
|
|
16619
|
+
* starts tainted when this run is tainted now, and carries the taint into its memory writes and any graph
|
|
16620
|
+
* it submits. When this run executes under a task-graph envelope (`params.SecurityEnvelope`), the
|
|
16621
|
+
* sub-agent gets that envelope with `IsRunTainted` set, and so refuses `disallowWhenTainted` actions as
|
|
16622
|
+
* an agent node does. A run outside any graph hands down only the taint (`ParentRunTainted`): its
|
|
16623
|
+
* sub-agent is held to what the run itself is, not to a gate the run is not under.
|
|
16624
|
+
*/
|
|
16625
|
+
subAgentTaint(params) {
|
|
16626
|
+
const tainted = this.IsRunTainted || params.SecurityEnvelope?.IsRunTainted === true;
|
|
16627
|
+
if (params.SecurityEnvelope) {
|
|
16628
|
+
return { SecurityEnvelope: { ...params.SecurityEnvelope, IsRunTainted: tainted } };
|
|
16629
|
+
}
|
|
16630
|
+
return tainted ? { ParentRunTainted: true } : {};
|
|
16631
|
+
}
|
|
16632
|
+
/**
|
|
16633
|
+
* The security envelope a graph this run submits carries: the run's bound parameters, the readers its audience
|
|
16634
|
+
* adds, its validated scope exactly as each action dispatch is handed it ({@link runScopeFor}), the caller's
|
|
16635
|
+
* tenant context and its taint — merged with the envelope this run itself executes under, when it is a
|
|
16636
|
+
* task-graph node (`ExecuteAgentParams.SecurityEnvelope`), keeping the stricter of each part.
|
|
16637
|
+
*/
|
|
16638
|
+
taskGraphSecurityEnvelope(params) {
|
|
16639
|
+
const scope = this.runScopeFor(params);
|
|
16640
|
+
const derived = BuildTaskSecurityEnvelope({
|
|
16641
|
+
BoundActionParams: params.boundActionParams,
|
|
16642
|
+
AudienceReaderUserIDs: AgentAudienceReaderIDs(params.Audience, params.contextUser?.ID),
|
|
16643
|
+
RunScope: {
|
|
16644
|
+
PrimaryScopeEntityName: scope.PrimaryScopeEntityName ?? null,
|
|
16645
|
+
PrimaryScopeRecordID: scope.PrimaryScopeRecordID,
|
|
16646
|
+
SecondaryScopes: scope.SecondaryScopes ?? null,
|
|
16647
|
+
...(scope.SearchScopeIDs ? { SearchScopeIDs: scope.SearchScopeIDs } : {}),
|
|
16648
|
+
},
|
|
16649
|
+
CallerTenantContext: params.contextUser?.TenantContext,
|
|
16650
|
+
IsRunTainted: this.IsRunTainted,
|
|
16651
|
+
});
|
|
16652
|
+
const merged = MergeTaskSecurityEnvelopes(derived, params.SecurityEnvelope);
|
|
16653
|
+
return 'Reason' in merged ? { Refusal: merged.Reason } : { Envelope: merged.Envelope };
|
|
16654
|
+
}
|
|
17313
16655
|
/**
|
|
17314
16656
|
* Executes a `'Handoff'` next step: records the `'Handoff'` step entity with the resolved
|
|
17315
16657
|
* target agent ID, stores {@link _handoffResult} for {@link ExecuteAgentResult.handoff},
|
|
@@ -17460,40 +16802,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17460
16802
|
* @protected
|
|
17461
16803
|
*/
|
|
17462
16804
|
buildPlanApprovalForm(planText) {
|
|
17463
|
-
return
|
|
17464
|
-
title: 'Review Plan',
|
|
17465
|
-
description: 'Review the proposed plan below. Edit it if needed, then approve to proceed — or reject (with a note on what to change) and the agent will re-plan.',
|
|
17466
|
-
submitLabel: 'Submit',
|
|
17467
|
-
questions: [
|
|
17468
|
-
{
|
|
17469
|
-
id: 'plan',
|
|
17470
|
-
label: 'Plan',
|
|
17471
|
-
// markdown: agents author plans in Markdown (see the plan-mode prompt
|
|
17472
|
-
// instructions); the UI renders a formatted preview with an Edit toggle.
|
|
17473
|
-
type: { type: 'textarea', markdown: true },
|
|
17474
|
-
defaultValue: planText,
|
|
17475
|
-
required: true
|
|
17476
|
-
},
|
|
17477
|
-
{
|
|
17478
|
-
id: 'reason',
|
|
17479
|
-
label: 'Feedback',
|
|
17480
|
-
type: { type: 'textarea', placeholder: 'Optional — if rejecting, tell the agent what to change and it will re-plan.' },
|
|
17481
|
-
required: false
|
|
17482
|
-
},
|
|
17483
|
-
{
|
|
17484
|
-
id: 'decision',
|
|
17485
|
-
label: 'Decision',
|
|
17486
|
-
type: {
|
|
17487
|
-
type: 'buttongroup',
|
|
17488
|
-
options: [
|
|
17489
|
-
{ value: 'approve', label: 'Approve' },
|
|
17490
|
-
{ value: 'reject', label: 'Reject' }
|
|
17491
|
-
]
|
|
17492
|
-
},
|
|
17493
|
-
required: true
|
|
17494
|
-
}
|
|
17495
|
-
]
|
|
17496
|
-
};
|
|
16805
|
+
return this._feedbackCoordinator.BuildPlanApprovalForm(planText);
|
|
17497
16806
|
}
|
|
17498
16807
|
async executeChatStep(params, previousDecision) {
|
|
17499
16808
|
// Chat steps are successful immediately — record in a single INSERT instead of INSERT + UPDATE
|
|
@@ -17545,119 +16854,28 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17545
16854
|
await this.createFeedbackRequest(params, stepEntity, decision);
|
|
17546
16855
|
}
|
|
17547
16856
|
/**
|
|
17548
|
-
* Creates a persistent AIAgentRequest row when a Chat step fires.
|
|
17549
|
-
* Resolves the target user via the assignment chain
|
|
17550
|
-
*
|
|
17551
|
-
*
|
|
17552
|
-
*
|
|
17553
|
-
*
|
|
17554
|
-
*
|
|
16857
|
+
* Creates a persistent AIAgentRequest row when a Chat or Plan step fires.
|
|
16858
|
+
* Resolves the target user via the assignment chain (delegating to
|
|
16859
|
+
* {@link AgentFeedbackCoordinator.CreateFeedbackRequest}):
|
|
16860
|
+
* 1. ExecuteAgentParams.assignmentStrategy (per-invocation override)
|
|
16861
|
+
* 2. Agent Type's AssignmentStrategy
|
|
16862
|
+
* 3. Agent's Category AssignmentStrategy (walks up ParentID tree)
|
|
16863
|
+
* 4. Request Type's DefaultAssignmentStrategy
|
|
16864
|
+
* 5. Fallback: contextUser (explicit caller) or null (system-level, visible to admins)
|
|
17555
16865
|
*
|
|
17556
16866
|
* @private
|
|
17557
16867
|
*/
|
|
17558
16868
|
async createFeedbackRequest(params, stepEntity, previousDecision) {
|
|
17559
|
-
|
|
17560
|
-
|
|
17561
|
-
|
|
17562
|
-
|
|
17563
|
-
|
|
17564
|
-
|
|
17565
|
-
|
|
17566
|
-
|
|
17567
|
-
|
|
17568
|
-
request.RequestedAt = new Date();
|
|
17569
|
-
request.RequestForUserID = requestForUserId;
|
|
17570
|
-
request.Status = 'Requested';
|
|
17571
|
-
request.Request = previousDecision.message || 'Agent needs user input';
|
|
17572
|
-
request.RequestTypeID = requestTypeId;
|
|
17573
|
-
request.ResponseSchema = previousDecision.responseForm
|
|
17574
|
-
? JSON.stringify(previousDecision.responseForm)
|
|
17575
|
-
: null;
|
|
17576
|
-
request.Priority = priority;
|
|
17577
|
-
request.OriginatingAgentRunID = this._agentRun?.ID || null;
|
|
17578
|
-
request.OriginatingAgentRunStepID = stepEntity.ID;
|
|
17579
|
-
if (expirationMinutes != null && expirationMinutes > 0) {
|
|
17580
|
-
request.ExpiresAt = new Date(Date.now() + expirationMinutes * 60_000);
|
|
17581
|
-
}
|
|
17582
|
-
const saved = await request.Save();
|
|
17583
|
-
if (saved) {
|
|
17584
|
-
this._feedbackRequestId = request.ID;
|
|
17585
|
-
this.logStatus(`📋 Created feedback request ${request.ID} for user ${requestForUserId || '(system)'}`, true, params);
|
|
17586
|
-
}
|
|
17587
|
-
else {
|
|
17588
|
-
LogError(`Failed to save AIAgentRequest for agent ${params.agent.Name}`);
|
|
17589
|
-
}
|
|
17590
|
-
}
|
|
17591
|
-
catch (error) {
|
|
17592
|
-
// Don't let request creation failure break the agent execution
|
|
17593
|
-
LogError(`Error creating feedback request: ${error.message}`);
|
|
17594
|
-
}
|
|
17595
|
-
}
|
|
17596
|
-
/**
|
|
17597
|
-
* Walks the assignment strategy resolution chain (bottom-up, first-non-null wins):
|
|
17598
|
-
* 1. ExecuteAgentParams.assignmentStrategy (per-invocation)
|
|
17599
|
-
* 2. Agent Type's AssignmentStrategy
|
|
17600
|
-
* 3. Agent's Category AssignmentStrategy (walks up ParentID tree)
|
|
17601
|
-
* 4. Request Type's DefaultAssignmentStrategy
|
|
17602
|
-
* 5. Fallback: null (caller uses contextUser + warning)
|
|
17603
|
-
* @private
|
|
17604
|
-
*/
|
|
17605
|
-
async resolveAssignmentStrategy(params, requestTypeId) {
|
|
17606
|
-
// 1. Per-invocation override (highest precedence)
|
|
17607
|
-
if (params.assignmentStrategy) {
|
|
17608
|
-
return params.assignmentStrategy;
|
|
17609
|
-
}
|
|
17610
|
-
// 2. Agent Type's AssignmentStrategy
|
|
17611
|
-
const agentType = AIEngine.Instance.AgentTypes.find(at => UUIDsEqual(at.ID, params.agent.TypeID));
|
|
17612
|
-
const typeStrategy = parseAssignmentStrategy(agentType?.AssignmentStrategy ?? null);
|
|
17613
|
-
if (typeStrategy) {
|
|
17614
|
-
return typeStrategy;
|
|
17615
|
-
}
|
|
17616
|
-
// 3. Agent's Category AssignmentStrategy (walk up ParentID tree)
|
|
17617
|
-
const categoryStrategy = await this.resolveCategoryAssignmentStrategy(params);
|
|
17618
|
-
if (categoryStrategy) {
|
|
17619
|
-
return categoryStrategy;
|
|
17620
|
-
}
|
|
17621
|
-
// 4. Request Type's DefaultAssignmentStrategy (request types are cached on the AI engine)
|
|
17622
|
-
if (requestTypeId) {
|
|
17623
|
-
const requestType = AIEngine.Instance.AgentRequestTypes.find(t => UUIDsEqual(t.ID, requestTypeId));
|
|
17624
|
-
if (requestType) {
|
|
17625
|
-
const rtStrategy = parseAssignmentStrategy(requestType.DefaultAssignmentStrategy);
|
|
17626
|
-
if (rtStrategy) {
|
|
17627
|
-
return rtStrategy;
|
|
17628
|
-
}
|
|
17629
|
-
}
|
|
16869
|
+
const requestId = await this._feedbackCoordinator.CreateFeedbackRequest({
|
|
16870
|
+
Params: params,
|
|
16871
|
+
StepEntity: stepEntity,
|
|
16872
|
+
Decision: previousDecision,
|
|
16873
|
+
AgentRun: this._agentRun,
|
|
16874
|
+
Provider: params.provider || this._activeProvider,
|
|
16875
|
+
});
|
|
16876
|
+
if (requestId) {
|
|
16877
|
+
this._feedbackRequestId = requestId;
|
|
17630
16878
|
}
|
|
17631
|
-
return null;
|
|
17632
|
-
}
|
|
17633
|
-
/**
|
|
17634
|
-
* Walks up the agent's category hierarchy looking for an AssignmentStrategy.
|
|
17635
|
-
* Uses AIEngine.Instance.AgentCategories (cached during engine Config).
|
|
17636
|
-
*/
|
|
17637
|
-
async resolveCategoryAssignmentStrategy(params) {
|
|
17638
|
-
const categoryId = params.agent.CategoryID;
|
|
17639
|
-
if (!categoryId)
|
|
17640
|
-
return null;
|
|
17641
|
-
try {
|
|
17642
|
-
const categories = AIEngine.Instance.AgentCategories;
|
|
17643
|
-
// Walk up the tree from the agent's category to the root
|
|
17644
|
-
let currentId = categoryId;
|
|
17645
|
-
const visited = new Set(); // prevent infinite loops
|
|
17646
|
-
while (currentId && !visited.has(currentId)) {
|
|
17647
|
-
visited.add(currentId);
|
|
17648
|
-
const cat = categories.find(c => UUIDsEqual(c.ID, currentId));
|
|
17649
|
-
if (!cat)
|
|
17650
|
-
break;
|
|
17651
|
-
const strategy = parseAssignmentStrategy(cat.AssignmentStrategy);
|
|
17652
|
-
if (strategy)
|
|
17653
|
-
return strategy;
|
|
17654
|
-
currentId = cat.ParentID;
|
|
17655
|
-
}
|
|
17656
|
-
}
|
|
17657
|
-
catch (error) {
|
|
17658
|
-
LogError(`Error resolving category assignment strategy: ${error.message}`);
|
|
17659
|
-
}
|
|
17660
|
-
return null;
|
|
17661
16879
|
}
|
|
17662
16880
|
/**
|
|
17663
16881
|
* Resolves the file storage account ID for this agent's file artifacts.
|
|
@@ -17676,94 +16894,6 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17676
16894
|
async getStorageAccountID(params) {
|
|
17677
16895
|
return AIEngine.Instance.ResolveAgentStorageAccountID(params.agent, params.override?.storageAccountId);
|
|
17678
16896
|
}
|
|
17679
|
-
/**
|
|
17680
|
-
* Resolves the target user ID from a resolved assignment strategy.
|
|
17681
|
-
* For simple strategies (RunUser, AgentOwner, SpecificUser), resolves immediately.
|
|
17682
|
-
* For List/SharedInbox strategies, delegates to list-based resolution.
|
|
17683
|
-
* Falls back to contextUser with a warning if no strategy is provided.
|
|
17684
|
-
* @private
|
|
17685
|
-
*/
|
|
17686
|
-
resolveUserFromStrategy(strategy, params) {
|
|
17687
|
-
if (!strategy) {
|
|
17688
|
-
// No strategy resolved anywhere — fall back to contextUser + warning
|
|
17689
|
-
if (params.contextUser?.ID) {
|
|
17690
|
-
LogStatus(`⚠️ No assignment strategy configured for agent ${params.agent.Name}; defaulting to context user`);
|
|
17691
|
-
return params.contextUser.ID;
|
|
17692
|
-
}
|
|
17693
|
-
LogStatus(`⚠️ No assignment strategy and no context user for agent ${params.agent.Name}; request will be unassigned`);
|
|
17694
|
-
return null;
|
|
17695
|
-
}
|
|
17696
|
-
switch (strategy.type) {
|
|
17697
|
-
case 'RunUser':
|
|
17698
|
-
return params.contextUser?.ID
|
|
17699
|
-
?? this._agentRun?.UserID
|
|
17700
|
-
?? null;
|
|
17701
|
-
case 'AgentOwner':
|
|
17702
|
-
return params.agent.OwnerUserID ?? null;
|
|
17703
|
-
case 'SpecificUser':
|
|
17704
|
-
return strategy.userID ?? null;
|
|
17705
|
-
case 'List':
|
|
17706
|
-
// List-based resolution (RoundRobin, LeastBusy, Random) requires async DB lookups.
|
|
17707
|
-
// For now, fall back to contextUser. Full list resolution is a future enhancement
|
|
17708
|
-
// that will query ListDetail records and track assignment state.
|
|
17709
|
-
LogStatus(`ℹ️ List-based assignment strategy configured but not yet implemented; defaulting to context user`);
|
|
17710
|
-
return params.contextUser?.ID ?? null;
|
|
17711
|
-
case 'SharedInbox':
|
|
17712
|
-
// SharedInbox means "unassigned — anyone in the list can claim it"
|
|
17713
|
-
return null;
|
|
17714
|
-
default:
|
|
17715
|
-
return params.contextUser?.ID ?? null;
|
|
17716
|
-
}
|
|
17717
|
-
}
|
|
17718
|
-
/**
|
|
17719
|
-
* Determines the request type ID based on the Chat step's context.
|
|
17720
|
-
* - If the responseForm has only approve/reject-style buttons, uses "Approval"
|
|
17721
|
-
* - If there's a responseForm with fields, uses "Information"
|
|
17722
|
-
* - Otherwise defaults to "Information"
|
|
17723
|
-
*
|
|
17724
|
-
* Request types come from the AI engine's cached `MJ: AI Agent Request Types` rows
|
|
17725
|
-
* (`AIEngineBase.ResolveAgentRequestTypeID`), the same source the agent actions use.
|
|
17726
|
-
* @private
|
|
17727
|
-
*/
|
|
17728
|
-
async resolveRequestTypeId(previousDecision, contextUser) {
|
|
17729
|
-
try {
|
|
17730
|
-
// Determine type name based on responseForm content
|
|
17731
|
-
let typeName = 'Information'; // default
|
|
17732
|
-
if (previousDecision.responseForm) {
|
|
17733
|
-
typeName = this.detectRequestTypeName(previousDecision.responseForm);
|
|
17734
|
-
}
|
|
17735
|
-
return await AIEngine.Instance.ResolveAgentRequestTypeID(typeName, contextUser);
|
|
17736
|
-
}
|
|
17737
|
-
catch (error) {
|
|
17738
|
-
LogError(`Error resolving request type: ${error.message}`);
|
|
17739
|
-
return null;
|
|
17740
|
-
}
|
|
17741
|
-
}
|
|
17742
|
-
/**
|
|
17743
|
-
* Inspects an AgentResponseForm to determine the best request type name.
|
|
17744
|
-
* Returns "Approval" if the form is a simple two-option approve/reject pattern,
|
|
17745
|
-
* otherwise returns "Information".
|
|
17746
|
-
* @private
|
|
17747
|
-
*/
|
|
17748
|
-
detectRequestTypeName(form) {
|
|
17749
|
-
const q = form.questions?.[0];
|
|
17750
|
-
if (!q || form.questions.length !== 1) {
|
|
17751
|
-
return 'Information';
|
|
17752
|
-
}
|
|
17753
|
-
const qType = q.type;
|
|
17754
|
-
if ((qType.type === 'buttongroup' || qType.type === 'radio') && 'options' in qType) {
|
|
17755
|
-
const opts = qType.options;
|
|
17756
|
-
if (opts.length === 2) {
|
|
17757
|
-
const labels = opts.map(o => o.label.toLowerCase());
|
|
17758
|
-
const hasPositive = labels.some(l => l.includes('approv') || l.includes('yes') || l.includes('accept'));
|
|
17759
|
-
const hasNegative = labels.some(l => l.includes('reject') || l.includes('no') || l.includes('deny'));
|
|
17760
|
-
if (hasPositive && hasNegative) {
|
|
17761
|
-
return 'Approval';
|
|
17762
|
-
}
|
|
17763
|
-
}
|
|
17764
|
-
}
|
|
17765
|
-
return 'Information';
|
|
17766
|
-
}
|
|
17767
16897
|
/**
|
|
17768
16898
|
* Executes a ForEach loop with actual for loop
|
|
17769
16899
|
*/
|
|
@@ -17794,22 +16924,10 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17794
16924
|
return this.completeForEachLoop(forEach, loopStepEntity, loopResults, previousDecision, params);
|
|
17795
16925
|
}
|
|
17796
16926
|
validateWhileOperation(whileOp, agentId = this._agentRun?.AgentID ?? '') {
|
|
17797
|
-
|
|
17798
|
-
return 'Condition is required';
|
|
17799
|
-
}
|
|
17800
|
-
if (!whileOp.itemVariable || whileOp.itemVariable.trim() === '') {
|
|
17801
|
-
return 'Item variable is required';
|
|
17802
|
-
}
|
|
17803
|
-
return this.validateLoopBodyOperation('While', whileOp, agentId);
|
|
16927
|
+
return this._stepDispatcher.ValidateWhileOperation(whileOp, (kind, op) => this.validateLoopBodyOperation(kind, op, agentId));
|
|
17804
16928
|
}
|
|
17805
16929
|
validateForEachHeader(forEach) {
|
|
17806
|
-
|
|
17807
|
-
return 'Item variable is required';
|
|
17808
|
-
}
|
|
17809
|
-
if (!forEach.collectionPath || forEach.collectionPath.trim() === '') {
|
|
17810
|
-
return 'Collection path is required';
|
|
17811
|
-
}
|
|
17812
|
-
return null;
|
|
16930
|
+
return this._stepDispatcher.ValidateForEachHeader(forEach);
|
|
17813
16931
|
}
|
|
17814
16932
|
/**
|
|
17815
16933
|
* Validates the loop body arm (`action` | `steps` | `subAgent`) shared by `ForEach` and `While`.
|
|
@@ -17919,24 +17037,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17919
17037
|
* Strips "payload." prefix if present (for LLM convenience)
|
|
17920
17038
|
*/
|
|
17921
17039
|
getCollectionFromPayload(payload, path) {
|
|
17922
|
-
|
|
17923
|
-
// fixed list/range without a prior step having to build the array in the payload first.
|
|
17924
|
-
const trimmed = path.trim();
|
|
17925
|
-
if (trimmed.toLowerCase().startsWith('static:')) {
|
|
17926
|
-
try {
|
|
17927
|
-
const parsed = JSON.parse(trimmed.substring(trimmed.indexOf(':') + 1).trim());
|
|
17928
|
-
return Array.isArray(parsed) ? parsed : null;
|
|
17929
|
-
}
|
|
17930
|
-
catch {
|
|
17931
|
-
return null;
|
|
17932
|
-
}
|
|
17933
|
-
}
|
|
17934
|
-
// Remove "payload." prefix if present
|
|
17935
|
-
const cleanPath = path.toLowerCase().startsWith('payload.')
|
|
17936
|
-
? path.substring(8)
|
|
17937
|
-
: path;
|
|
17938
|
-
const value = this.getValueFromPath(payload, cleanPath);
|
|
17939
|
-
return Array.isArray(value) ? value : null;
|
|
17040
|
+
return this._stepDispatcher.GetCollectionFromPayload(payload, path, (obj, p) => this.getValueFromPath(obj, p));
|
|
17940
17041
|
}
|
|
17941
17042
|
/**
|
|
17942
17043
|
* Helper: Create parent ForEach loop step (not finalized until loop completes)
|
|
@@ -18037,55 +17138,20 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
18037
17138
|
* Each batch contains up to maxConcurrency items with their original indices.
|
|
18038
17139
|
*/
|
|
18039
17140
|
createBatches(items, maxConcurrency) {
|
|
18040
|
-
|
|
18041
|
-
for (let i = 0; i < items.length; i += maxConcurrency) {
|
|
18042
|
-
const batch = items.slice(i, i + maxConcurrency).map((item, batchOffset) => ({
|
|
18043
|
-
item,
|
|
18044
|
-
index: i + batchOffset
|
|
18045
|
-
}));
|
|
18046
|
-
batches.push(batch);
|
|
18047
|
-
}
|
|
18048
|
-
return batches;
|
|
17141
|
+
return this._stepDispatcher.CreateBatches(items, maxConcurrency);
|
|
18049
17142
|
}
|
|
18050
17143
|
/**
|
|
18051
17144
|
* Apply ForEach results sequentially to build final payload.
|
|
18052
17145
|
* This ensures payload changes are applied in order even when iterations ran in parallel.
|
|
18053
17146
|
*/
|
|
18054
17147
|
applyForEachResultsSequentially(sortedResults, initialPayload, continueOnError) {
|
|
18055
|
-
|
|
18056
|
-
const results = [];
|
|
18057
|
-
const errors = [];
|
|
18058
|
-
for (const { result, error, payload, appliedFolds } of sortedResults) {
|
|
18059
|
-
if (error) {
|
|
18060
|
-
errors.push(error);
|
|
18061
|
-
if (!continueOnError) {
|
|
18062
|
-
break;
|
|
18063
|
-
}
|
|
18064
|
-
}
|
|
18065
|
-
else if (result) {
|
|
18066
|
-
results.push(result);
|
|
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
|
-
}
|
|
18076
|
-
}
|
|
18077
|
-
}
|
|
18078
|
-
return { results, errors, finalPayload: currentPayload };
|
|
17148
|
+
return this._stepDispatcher.ApplyForEachResultsSequentially(sortedResults, initialPayload, continueOnError, (p) => this.cloneSubAgentPayload(p));
|
|
18079
17149
|
}
|
|
18080
17150
|
extractActionOutputObject(summaries) {
|
|
18081
|
-
return
|
|
17151
|
+
return this._stepDispatcher.ExtractActionOutputObject(summaries);
|
|
18082
17152
|
}
|
|
18083
17153
|
applyLoopOutputFold(basePayload, output, mapping) {
|
|
18084
|
-
|
|
18085
|
-
? this.cloneSubAgentPayload(basePayload)
|
|
18086
|
-
: {};
|
|
18087
|
-
const mapped = ApplyOutputMapping(output, mapping, target);
|
|
18088
|
-
return mapped.updates;
|
|
17154
|
+
return this._stepDispatcher.ApplyLoopOutputFold(basePayload, output, mapping, (p) => this.cloneSubAgentPayload(p));
|
|
18089
17155
|
}
|
|
18090
17156
|
/**
|
|
18091
17157
|
* Executes an ordered sequence of `LoopBodyActionStep` actions inside a single `ForEach` or `While`
|
|
@@ -18295,24 +17361,16 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
18295
17361
|
}
|
|
18296
17362
|
return this.createFailedStep(errorMessage, previousDecision);
|
|
18297
17363
|
}
|
|
18298
|
-
/**
|
|
18299
|
-
* One loop error as readable text. Joining the error objects directly wrote "[object Object]"
|
|
18300
|
-
* into the step's ErrorMessage. Falls back to JSON when an iteration threw something with no
|
|
18301
|
-
* message (a thrown non-Error).
|
|
18302
|
-
*/
|
|
18303
|
-
describeLoopError(err) {
|
|
18304
|
-
return err.message ? err.message : JSON.stringify(err);
|
|
18305
|
-
}
|
|
18306
17364
|
/** All loop errors as text for a step's ErrorMessage. */
|
|
18307
17365
|
formatLoopErrors(errors) {
|
|
18308
|
-
return
|
|
17366
|
+
return this._stepDispatcher.FormatLoopErrors(errors);
|
|
18309
17367
|
}
|
|
18310
17368
|
/**
|
|
18311
17369
|
* Formats loop iteration results as markdown. Handles two distinct result shapes
|
|
18312
17370
|
* depending on whether the loop body executed actions or sub-agents:
|
|
18313
17371
|
*
|
|
18314
17372
|
* - **Action iterations**: `priorStepResult` is an `ActionResultSummary[]`, set by
|
|
18315
|
-
* `executeActionsStep()
|
|
17373
|
+
* `executeActionsStep()`. These are formatted via `formatActionResultsAsMarkdown()`.
|
|
18316
17374
|
*
|
|
18317
17375
|
* - **Sub-agent iterations**: `priorStepResult` is a **pre-formatted markdown string**,
|
|
18318
17376
|
* set by the loop handlers (`executeSingleForEachIteration` / `executeSingleWhileIteration`)
|
|
@@ -18324,33 +17382,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
18324
17382
|
* markdown style used by non-loop results, ensuring consistency across the codebase.
|
|
18325
17383
|
*/
|
|
18326
17384
|
formatLoopResultsAsMarkdown(results, errors) {
|
|
18327
|
-
|
|
18328
|
-
for (let i = 0; i < results.length; i++) {
|
|
18329
|
-
const iterResult = results[i].priorStepResult;
|
|
18330
|
-
// Action iterations: priorStepResult is ActionResultSummary[] — format via shared helper
|
|
18331
|
-
if (Array.isArray(iterResult)) {
|
|
18332
|
-
lines.push(`### Iteration ${i + 1}`);
|
|
18333
|
-
lines.push(this.formatActionResultsAsMarkdown(iterResult));
|
|
18334
|
-
}
|
|
18335
|
-
else if (iterResult != null) {
|
|
18336
|
-
// Sub-agent iterations: priorStepResult is already a markdown string from
|
|
18337
|
-
// formatSubAgentResultAsMarkdown() called in the loop handler. Non-string
|
|
18338
|
-
// results (edge cases) are JSON-stringified as a fallback.
|
|
18339
|
-
lines.push(`### Iteration ${i + 1}`);
|
|
18340
|
-
const text = typeof iterResult === 'string'
|
|
18341
|
-
? iterResult
|
|
18342
|
-
: JSON.stringify(iterResult);
|
|
18343
|
-
lines.push(text);
|
|
18344
|
-
}
|
|
18345
|
-
// null/undefined priorStepResult: iteration produced no output — skip silently
|
|
18346
|
-
}
|
|
18347
|
-
if (errors.length > 0) {
|
|
18348
|
-
lines.push(`### Errors`);
|
|
18349
|
-
for (const err of errors) {
|
|
18350
|
-
lines.push(`• ✗ ${this.describeLoopError(err)}`);
|
|
18351
|
-
}
|
|
18352
|
-
}
|
|
18353
|
-
return lines.join('\n');
|
|
17385
|
+
return this._stepDispatcher.FormatLoopResultsAsMarkdown(results, errors, this._actionResultCrush, (summaries) => this.formatActionResultsAsMarkdown(summaries));
|
|
18354
17386
|
}
|
|
18355
17387
|
/**
|
|
18356
17388
|
* Resolves expiration/compaction metadata for loop result messages by looking up
|
|
@@ -18448,13 +17480,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
18448
17480
|
* Helper: Create failed step
|
|
18449
17481
|
*/
|
|
18450
17482
|
createFailedStep(errorMessage, previousDecision) {
|
|
18451
|
-
return
|
|
18452
|
-
step: 'Failed',
|
|
18453
|
-
terminate: false,
|
|
18454
|
-
errorMessage,
|
|
18455
|
-
previousPayload: previousDecision.previousPayload,
|
|
18456
|
-
newPayload: previousDecision.newPayload || previousDecision.previousPayload
|
|
18457
|
-
};
|
|
17483
|
+
return this._stepDispatcher.CreateFailedStep(errorMessage, previousDecision);
|
|
18458
17484
|
}
|
|
18459
17485
|
/**
|
|
18460
17486
|
* Executes a While loop with actual while loop
|
|
@@ -18916,38 +17942,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
18916
17942
|
* @private
|
|
18917
17943
|
*/
|
|
18918
17944
|
calculateTokenStats() {
|
|
18919
|
-
|
|
18920
|
-
let promptTokens = 0;
|
|
18921
|
-
let completionTokens = 0;
|
|
18922
|
-
let cacheReadTokens = 0;
|
|
18923
|
-
let cacheWriteTokens = 0;
|
|
18924
|
-
let totalCost = 0;
|
|
18925
|
-
// Iterate through the agent run's steps to sum up tokens
|
|
18926
|
-
if (this._agentRun?.Steps) {
|
|
18927
|
-
for (const step of this._agentRun.Steps) {
|
|
18928
|
-
if ((step.StepType === 'Prompt' || step.StepType === 'Compaction' || step.StepType === 'Decision') && step.PromptRun) {
|
|
18929
|
-
// Add tokens from prompt runs (rollup fields include any nested child prompt runs).
|
|
18930
|
-
// A Decision step carries its own decision call's run — the Finish check, a single-state
|
|
18931
|
-
// request, or one item of a forEachItemIn request — so each call is counted once.
|
|
18932
|
-
totalTokens += step.PromptRun.TokensUsedRollup || 0;
|
|
18933
|
-
promptTokens += step.PromptRun.TokensPromptRollup || 0;
|
|
18934
|
-
completionTokens += step.PromptRun.TokensCompletionRollup || 0;
|
|
18935
|
-
cacheReadTokens += step.PromptRun.TokensCacheReadRollup || 0;
|
|
18936
|
-
cacheWriteTokens += step.PromptRun.TokensCacheWriteRollup || 0;
|
|
18937
|
-
totalCost += step.PromptRun.TotalCost || 0;
|
|
18938
|
-
}
|
|
18939
|
-
else if (step.StepType === 'Sub-Agent' && step.SubAgentRun) {
|
|
18940
|
-
// Add tokens from sub-agent runs (these should already be calculated recursively)
|
|
18941
|
-
totalTokens += step.SubAgentRun.TotalTokensUsed || 0;
|
|
18942
|
-
promptTokens += step.SubAgentRun.TotalPromptTokensUsed || 0;
|
|
18943
|
-
completionTokens += step.SubAgentRun.TotalCompletionTokensUsed || 0;
|
|
18944
|
-
cacheReadTokens += step.SubAgentRun.TotalCacheReadTokensUsed || 0;
|
|
18945
|
-
cacheWriteTokens += step.SubAgentRun.TotalCacheWriteTokensUsed || 0;
|
|
18946
|
-
totalCost += step.SubAgentRun.TotalCost || 0;
|
|
18947
|
-
}
|
|
18948
|
-
}
|
|
18949
|
-
}
|
|
18950
|
-
return { totalTokens, promptTokens, completionTokens, cacheReadTokens, cacheWriteTokens, totalCost };
|
|
17945
|
+
return this._budgetTracker.CalculateRunTokenStats(this._agentRun);
|
|
18951
17946
|
}
|
|
18952
17947
|
/**
|
|
18953
17948
|
* Applies a {@link calculateTokenStats} result to a run entity's six denormalized
|
|
@@ -18957,12 +17952,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
18957
17952
|
* @private
|
|
18958
17953
|
*/
|
|
18959
17954
|
applyTokenStatsToRun(run, tokenStats) {
|
|
18960
|
-
run
|
|
18961
|
-
run.TotalPromptTokensUsed = tokenStats.promptTokens;
|
|
18962
|
-
run.TotalCompletionTokensUsed = tokenStats.completionTokens;
|
|
18963
|
-
run.TotalCacheReadTokensUsed = tokenStats.cacheReadTokens;
|
|
18964
|
-
run.TotalCacheWriteTokensUsed = tokenStats.cacheWriteTokens;
|
|
18965
|
-
run.TotalCost = tokenStats.totalCost;
|
|
17955
|
+
this._budgetTracker.ApplyTokenStatsToRun(run, tokenStats);
|
|
18966
17956
|
}
|
|
18967
17957
|
/**
|
|
18968
17958
|
* Gets the count of how many times a specific action has been executed in this agent run.
|
|
@@ -18995,8 +17985,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
18995
17985
|
* @protected
|
|
18996
17986
|
*/
|
|
18997
17987
|
incrementExecutionCount(itemId) {
|
|
18998
|
-
|
|
18999
|
-
this._executionCounts.set(itemId, currentCount + 1);
|
|
17988
|
+
this._budgetTracker.IncrementExecutionCount(this._executionCounts, itemId);
|
|
19000
17989
|
}
|
|
19001
17990
|
/**
|
|
19002
17991
|
* Gets the execution count for an item (action or sub-agent).
|
|
@@ -19006,7 +17995,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
19006
17995
|
* @protected
|
|
19007
17996
|
*/
|
|
19008
17997
|
getExecutionCount(itemId) {
|
|
19009
|
-
return this.
|
|
17998
|
+
return this._budgetTracker.GetExecutionCount(this._executionCounts, itemId);
|
|
19010
17999
|
}
|
|
19011
18000
|
/**
|
|
19012
18001
|
* Checks if all minimum execution requirements are met for actions and sub-agents.
|
|
@@ -20034,22 +19023,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
20034
19023
|
* Resolves templates like {{item.field}}, {{index}}, etc. in action parameters and sub-agent payloads
|
|
20035
19024
|
*/
|
|
20036
19025
|
resolveTemplates(obj, context, itemVariable) {
|
|
20037
|
-
|
|
20038
|
-
for (const [key, value] of Object.entries(obj)) {
|
|
20039
|
-
if (typeof value === 'string') {
|
|
20040
|
-
result[key] = this.resolveValueFromContext(value, context, itemVariable);
|
|
20041
|
-
}
|
|
20042
|
-
else if (Array.isArray(value)) {
|
|
20043
|
-
result[key] = value.map(v => typeof v === 'string' ? this.resolveValueFromContext(v, context, itemVariable) : v);
|
|
20044
|
-
}
|
|
20045
|
-
else if (typeof value === 'object' && value !== null) {
|
|
20046
|
-
result[key] = this.resolveTemplates(value, context, itemVariable);
|
|
20047
|
-
}
|
|
20048
|
-
else {
|
|
20049
|
-
result[key] = value;
|
|
20050
|
-
}
|
|
20051
|
-
}
|
|
20052
|
-
return result;
|
|
19026
|
+
return this._stepDispatcher.ResolveTemplates(obj, context, itemVariable, (val, ctx, iv) => this.resolveValueFromContext(val, ctx, iv), (nested, ctx, iv) => this.resolveTemplates(nested, ctx, iv));
|
|
20053
19027
|
}
|
|
20054
19028
|
/**
|
|
20055
19029
|
* Resolves a value from context using variable references - extracts from LoopAgentType
|
|
@@ -20070,52 +19044,10 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
20070
19044
|
* Template: "{{user}}" → resolves to entire object {name: "Alice", age: 30}
|
|
20071
19045
|
*/
|
|
20072
19046
|
resolveValueFromContext(value, context, itemVariable) {
|
|
20073
|
-
|
|
20074
|
-
|
|
20075
|
-
|
|
20076
|
-
|
|
20077
|
-
const trimmedValue = value.trim();
|
|
20078
|
-
if (trimmedValue.startsWith('{{') && trimmedValue.endsWith('}}') && !trimmedValue.slice(2, -2).includes('{{')) {
|
|
20079
|
-
// Single-variable case: "{{city.name}}" — strip wrappers, fall through to
|
|
20080
|
-
// single-variable resolution below which can return non-string types (objects, numbers)
|
|
20081
|
-
value = trimmedValue.substring(2, trimmedValue.length - 2).trim();
|
|
20082
|
-
}
|
|
20083
|
-
else if (trimmedValue.includes('{{')) {
|
|
20084
|
-
// Inline template interpolation: "text {{var.prop}} more {{var2.field}}"
|
|
20085
|
-
// The string contains embedded {{}} expressions mixed with literal text.
|
|
20086
|
-
// Each expression is resolved individually and stringified back into the template.
|
|
20087
|
-
return this.resolveInlineTemplateExpressions(trimmedValue, context, itemVariable);
|
|
20088
|
-
}
|
|
20089
|
-
// Check itemVariable reference (the custom loop variable name like "entityName" or "user")
|
|
20090
|
-
// This handles both direct references and path-based property access
|
|
20091
|
-
const ivToLower = itemVariable?.trim().toLowerCase();
|
|
20092
|
-
const valueLower = value?.toLowerCase();
|
|
20093
|
-
// CRITICAL: Check for exact match FIRST (handles scalar arrays and direct object references)
|
|
20094
|
-
// Example: {{entityName}} where context.item = "Users" (scalar)
|
|
20095
|
-
// Example: {{user}} where context.item = {name: "Alice", age: 30} (object)
|
|
20096
|
-
if (valueLower === ivToLower) {
|
|
20097
|
-
return context.item; // Return the current iteration item (scalar or object)
|
|
20098
|
-
}
|
|
20099
|
-
// Check for path notation (handles property access on object arrays)
|
|
20100
|
-
// Example: {{entityName.property}} - won't work for scalars but handles objects
|
|
20101
|
-
// Example: {{user.name}} where context.item = {name: "Alice"} → returns "Alice"
|
|
20102
|
-
if (valueLower?.startsWith(`${ivToLower}.`)) {
|
|
20103
|
-
const path = value.substring(ivToLower.length + 1);
|
|
20104
|
-
return this.getValueFromPath(context.item, path);
|
|
20105
|
-
}
|
|
20106
|
-
// Check for direct context variable references (index, payload, data, etc.)
|
|
20107
|
-
// These are the fixed context properties set up by the loop execution
|
|
20108
|
-
for (const [varName, varValue] of Object.entries(context)) {
|
|
20109
|
-
if (value === varName) {
|
|
20110
|
-
return varValue;
|
|
20111
|
-
}
|
|
20112
|
-
if (value?.trim().toLowerCase().startsWith(`${varName}.`)) {
|
|
20113
|
-
const path = value.substring(varName.length + 1);
|
|
20114
|
-
return this.getValueFromPath(varValue, path);
|
|
20115
|
-
}
|
|
20116
|
-
}
|
|
20117
|
-
// Static value - no variable reference found, return as literal string
|
|
20118
|
-
return value;
|
|
19047
|
+
return this._stepDispatcher.ResolveValueFromContext(value, context, itemVariable, {
|
|
19048
|
+
resolveInline: (tpl, ctx, iv) => this.resolveInlineTemplateExpressions(tpl, ctx, iv),
|
|
19049
|
+
getPath: (obj, path) => this.getValueFromPath(obj, path),
|
|
19050
|
+
});
|
|
20119
19051
|
}
|
|
20120
19052
|
/**
|
|
20121
19053
|
* Resolves multiple {{expression}} placeholders embedded within a literal string.
|
|
@@ -20132,16 +19064,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
20132
19064
|
* // → "largest company in Tokyo Japan"
|
|
20133
19065
|
*/
|
|
20134
19066
|
resolveInlineTemplateExpressions(template, context, itemVariable) {
|
|
20135
|
-
|
|
20136
|
-
return template.replace(expressionPattern, (_match, expr) => {
|
|
20137
|
-
// Resolve each expression using the single-variable path (without {{ }} wrappers)
|
|
20138
|
-
const resolved = this.resolveValueFromContext(expr.trim(), context, itemVariable);
|
|
20139
|
-
// If the expression didn't resolve (returned unchanged), keep original {{ }} for transparency
|
|
20140
|
-
if (resolved === expr.trim()) {
|
|
20141
|
-
return _match;
|
|
20142
|
-
}
|
|
20143
|
-
return String(resolved ?? '');
|
|
20144
|
-
});
|
|
19067
|
+
return this._stepDispatcher.ResolveInlineTemplateExpressions(template, context, itemVariable, (val, ctx, iv) => this.resolveValueFromContext(val, ctx, iv));
|
|
20145
19068
|
}
|
|
20146
19069
|
/**
|
|
20147
19070
|
* Reads a value out of a nested object by dotted path, with `name[0]` array indexing.
|