@memberjunction/ai-agents 6.2.0-edge.5 → 6.2.0-edge.6
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 +60 -0
- package/dist/AgentDataPreloader.d.ts +4 -2
- package/dist/AgentDataPreloader.d.ts.map +1 -1
- package/dist/AgentDataPreloader.js +21 -12
- package/dist/AgentDataPreloader.js.map +1 -1
- package/dist/AgentRunner.d.ts +55 -3
- package/dist/AgentRunner.d.ts.map +1 -1
- package/dist/AgentRunner.js +150 -30
- package/dist/AgentRunner.js.map +1 -1
- package/dist/AgentWakeTriggerService.d.ts +183 -0
- package/dist/AgentWakeTriggerService.d.ts.map +1 -0
- package/dist/AgentWakeTriggerService.js +478 -0
- package/dist/AgentWakeTriggerService.js.map +1 -0
- package/dist/ArtifactToolManager.d.ts +1 -0
- package/dist/ArtifactToolManager.d.ts.map +1 -1
- package/dist/ArtifactToolManager.js +5 -0
- package/dist/ArtifactToolManager.js.map +1 -1
- package/dist/ConversationToolManager.d.ts +1 -1
- package/dist/ConversationToolManager.d.ts.map +1 -1
- package/dist/ConversationToolManager.js +10 -4
- package/dist/ConversationToolManager.js.map +1 -1
- package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
- package/dist/MJAIAgentRequestEntityServer.js +20 -0
- package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
- package/dist/agent-context-injector.d.ts +21 -4
- package/dist/agent-context-injector.d.ts.map +1 -1
- package/dist/agent-context-injector.js +49 -13
- package/dist/agent-context-injector.js.map +1 -1
- package/dist/agent-memory-context-builder.js +2 -2
- package/dist/agent-memory-context-builder.js.map +1 -1
- package/dist/agent-pre-execution-rag.js +5 -8
- package/dist/agent-pre-execution-rag.js.map +1 -1
- package/dist/agent-run-watchdog.d.ts +23 -8
- package/dist/agent-run-watchdog.d.ts.map +1 -1
- package/dist/agent-run-watchdog.js +141 -76
- package/dist/agent-run-watchdog.js.map +1 -1
- package/dist/agent-types/flow-agent-type.d.ts +7 -0
- package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
- package/dist/agent-types/flow-agent-type.js +95 -21
- package/dist/agent-types/flow-agent-type.js.map +1 -1
- package/dist/agent-types/loop-agent-prompt-params.d.ts +6 -2
- package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
- package/dist/agent-types/loop-agent-type.d.ts +76 -5
- package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-type.js +230 -50
- package/dist/agent-types/loop-agent-type.js.map +1 -1
- package/dist/base-agent.d.ts +244 -10
- package/dist/base-agent.d.ts.map +1 -1
- package/dist/base-agent.js +1019 -193
- package/dist/base-agent.js.map +1 -1
- package/dist/bound-action-params.d.ts +57 -0
- package/dist/bound-action-params.d.ts.map +1 -0
- package/dist/bound-action-params.js +91 -0
- package/dist/bound-action-params.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/memory-cleanup-agent.d.ts.map +1 -1
- package/dist/memory-cleanup-agent.js +3 -0
- package/dist/memory-cleanup-agent.js.map +1 -1
- package/dist/memory-manager-agent.d.ts.map +1 -1
- package/dist/memory-manager-agent.js +6 -1
- package/dist/memory-manager-agent.js.map +1 -1
- package/dist/native-tools/agent-tools.d.ts +64 -0
- package/dist/native-tools/agent-tools.d.ts.map +1 -0
- package/dist/native-tools/agent-tools.js +23 -0
- package/dist/native-tools/agent-tools.js.map +1 -0
- package/dist/native-tools/control-tools.d.ts +26 -4
- package/dist/native-tools/control-tools.d.ts.map +1 -1
- package/dist/native-tools/control-tools.js +114 -42
- package/dist/native-tools/control-tools.js.map +1 -1
- package/dist/native-tools/framework-tools.d.ts +47 -0
- package/dist/native-tools/framework-tools.d.ts.map +1 -0
- package/dist/native-tools/framework-tools.js +187 -0
- package/dist/native-tools/framework-tools.js.map +1 -0
- package/dist/native-tools/native-control-config.d.ts +93 -0
- package/dist/native-tools/native-control-config.d.ts.map +1 -0
- package/dist/native-tools/native-control-config.js +104 -0
- package/dist/native-tools/native-control-config.js.map +1 -0
- package/dist/native-tools/tool-result-turns.d.ts +41 -8
- package/dist/native-tools/tool-result-turns.d.ts.map +1 -1
- package/dist/native-tools/tool-result-turns.js +76 -2
- package/dist/native-tools/tool-result-turns.js.map +1 -1
- package/dist/native-tools/turn-mode.d.ts +8 -0
- package/dist/native-tools/turn-mode.d.ts.map +1 -0
- package/dist/native-tools/turn-mode.js +14 -0
- package/dist/native-tools/turn-mode.js.map +1 -0
- package/dist/query-builder-agent.d.ts +20 -1
- package/dist/query-builder-agent.d.ts.map +1 -1
- package/dist/query-builder-agent.js +35 -3
- package/dist/query-builder-agent.js.map +1 -1
- package/dist/realtime/bridge-room-transcript-sink.js +1 -0
- package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
- package/dist/realtime/bridge-session-transcript-sink.js +1 -0
- package/dist/realtime/bridge-session-transcript-sink.js.map +1 -1
- package/dist/realtime/realtime-recording-ledger.d.ts +20 -0
- package/dist/realtime/realtime-recording-ledger.d.ts.map +1 -1
- package/dist/realtime/realtime-recording-ledger.js +16 -0
- package/dist/realtime/realtime-recording-ledger.js.map +1 -1
- package/dist/realtime/realtime-recording-store.d.ts +6 -5
- package/dist/realtime/realtime-recording-store.d.ts.map +1 -1
- package/dist/realtime/realtime-recording-store.js +47 -21
- package/dist/realtime/realtime-recording-store.js.map +1 -1
- package/package.json +20 -20
package/dist/base-agent.js
CHANGED
|
@@ -13,18 +13,22 @@
|
|
|
13
13
|
import { MJEnvironmentEntityExtended, ConversationEngine } from '@memberjunction/core-entities';
|
|
14
14
|
import { BuildActionToolSet, CoerceActionArguments, FilterDeclarableActions, SanitizeToolName } from './native-tools/action-tool-builder.js';
|
|
15
15
|
import { DescribeValueSchemaInline, GetStoredValueSchema } from './native-tools/action-param-schema.js';
|
|
16
|
+
import { ApplyBoundActionParams, BindingsForAction, IsBoundParamName, UnboundParams } from './bound-action-params.js';
|
|
16
17
|
import { BuildNativeToolSet, COMPLETE_TASK_TOOL, SUB_AGENT_TOOL_PREFIX } from './native-tools/control-tools.js';
|
|
17
|
-
import {
|
|
18
|
+
import { TurnToolCallingMode } from './native-tools/turn-mode.js';
|
|
19
|
+
import { NATIVE_CONTROL_TEMPLATE_DATA, NATIVE_ONLY_TEMPLATE_FLAG, ResolveNativeControlConfig } from './native-tools/native-control-config.js';
|
|
20
|
+
import { BuildFrameworkTools } from './native-tools/framework-tools.js';
|
|
21
|
+
import { BuildAssistantToolCallTurn, BuildToolResultTurn, CompactAnsweredToolCallArguments, CompactToolResultContent, CompactToolResultContentAsync } from './native-tools/tool-result-turns.js';
|
|
18
22
|
import { LooksLikeLoopEnvelope } from './native-tools/dual-channel.js';
|
|
19
23
|
import { MJAIAgentRunEntityExtended, ResolvePromptRunUserID, ResolvePayloadAtEnd } from "@memberjunction/ai-core-plus";
|
|
20
24
|
import { Metadata, RunView, LogStatus, LogStatusEx, LogError, LogErrorEx, IsVerboseLoggingEnabled, DatabaseProviderBase, ToPlainJSON } from '@memberjunction/core';
|
|
21
25
|
import { AgentRunWatchdog } from './agent-run-watchdog.js';
|
|
22
|
-
import { AIPromptRunner, GetToolCallingDecision } from '@memberjunction/ai-prompts';
|
|
23
|
-
import { BaseRealtimeModel, GetAIAPIKey, CredentialScopeAllows, MakeAIAPIKeyResolver, IsPrefixPromptCache } from '@memberjunction/ai';
|
|
26
|
+
import { AIPromptRunner, GetToolCallingDecision, GetSentPrefixFingerprint } from '@memberjunction/ai-prompts';
|
|
27
|
+
import { BaseLLM, BaseRealtimeModel, GetAIAPIKey, CredentialScopeAllows, MakeAIAPIKeyResolver, IsPrefixPromptCache } from '@memberjunction/ai';
|
|
24
28
|
import { BaseAgentType } from './agent-types/base-agent-type.js';
|
|
25
29
|
import { ProviderRubricEngine } from '@memberjunction/rubrics';
|
|
26
30
|
import { ExecuteSelfCheck, PickSelfCheckLink } from './self-check.js';
|
|
27
|
-
import { CopyScalarsAndArrays, JSONValidator, MJGlobal, NormalizeUUID, SafeExpressionEvaluator, UUIDsEqual, EscapeSQLString, IsPlainObject, CleanAndParseJSON, IsValidUUID, IndexByUUID } from '@memberjunction/global';
|
|
31
|
+
import { CopyScalarsAndArrays, JSONValidator, MJGlobal, NormalizeUUID, SafeExpressionEvaluator, UUIDsEqual, UUIDSet, EscapeSQLString, IsPlainObject, CleanAndParseJSON, IsValidUUID, IndexByUUID } from '@memberjunction/global';
|
|
28
32
|
// token optimization via @memberjunction/context-crush (SmartCrusher/CacheAligner-inspired)
|
|
29
33
|
import { CrushJSON, DescribeCrush, PartitionStablePrefix } from '@memberjunction/context-crush';
|
|
30
34
|
// AST-aware code reduction (CodeCompressor-inspired) — opt-in per agent type
|
|
@@ -561,16 +565,6 @@ export class BaseAgent {
|
|
|
561
565
|
*/
|
|
562
566
|
this._selfCheckAttemptsByRun = new Map();
|
|
563
567
|
this._selfCheckLinkByAgent = new Map();
|
|
564
|
-
/**
|
|
565
|
-
* Determines the request type ID based on the Chat step's context.
|
|
566
|
-
* - If the responseForm has only approve/reject-style buttons, uses "Approval"
|
|
567
|
-
* - If there's a responseForm with fields, uses "Information"
|
|
568
|
-
* - Otherwise defaults to "Information"
|
|
569
|
-
*
|
|
570
|
-
* Caches the request type lookup for the duration of this agent execution.
|
|
571
|
-
* @private
|
|
572
|
-
*/
|
|
573
|
-
this._requestTypeCache = null;
|
|
574
568
|
}
|
|
575
569
|
/**
|
|
576
570
|
* Maximum allowed validation retries before forcing failure.
|
|
@@ -832,6 +826,133 @@ export class BaseAgent {
|
|
|
832
826
|
blocked.RunParams.Action = actionEntity;
|
|
833
827
|
return blocked;
|
|
834
828
|
}
|
|
829
|
+
/**
|
|
830
|
+
* Applies the run's bound parameters to one call (`ExecuteAgentParams.boundActionParams`): a bound
|
|
831
|
+
* value replaces whatever the model sent under its name, and the override is logged with the run and
|
|
832
|
+
* step IDs. The rules are {@link ApplyBoundActionParams}'s; this adds only the log line.
|
|
833
|
+
*/
|
|
834
|
+
applyActionBindings(params, action, actionEntity, options) {
|
|
835
|
+
const bindings = BindingsForAction(params.boundActionParams, actionEntity.ID);
|
|
836
|
+
const application = ApplyBoundActionParams(action.params, bindings, actionEntity.Params?.Items ?? [], actionEntity.Name);
|
|
837
|
+
if (application.Overridden.length > 0) {
|
|
838
|
+
const names = application.Overridden.map((n) => `'${n}'`).join(', ');
|
|
839
|
+
this.logStatus(` 🔒 Action '${action.name}': the model supplied ${names}, which this run binds; the model's value is discarded (${this.whereInRun(options)})`, false, params);
|
|
840
|
+
}
|
|
841
|
+
return application;
|
|
842
|
+
}
|
|
843
|
+
/** "run <id>, step <id>" for an audit line. */
|
|
844
|
+
whereInRun(options) {
|
|
845
|
+
return `run ${this._agentRun?.ID ?? 'n/a'}, step ${options?.StepID ?? 'n/a'}`;
|
|
846
|
+
}
|
|
847
|
+
/**
|
|
848
|
+
* The `ActionParam` array for one dispatch. Coerced against each param's declared schema on every
|
|
849
|
+
* path — envelope, native and flow — so `"640"` reaches an integer param as 640 whichever protocol
|
|
850
|
+
* produced it, while bound parameters keep their exact host-supplied value and carry the `Bound`
|
|
851
|
+
* marker into the execution log.
|
|
852
|
+
*/
|
|
853
|
+
toActionParams(application, actionEntity) {
|
|
854
|
+
const coerced = CoerceActionArguments(actionEntity.Params?.Items ?? [], application.Params);
|
|
855
|
+
return Object.entries(coerced).map(([key, value]) => {
|
|
856
|
+
const bound = application.Bound.includes(key);
|
|
857
|
+
const param = { Name: key, Value: bound ? application.Params[key] : value, Type: 'Input' };
|
|
858
|
+
if (bound) {
|
|
859
|
+
param.Bound = true;
|
|
860
|
+
}
|
|
861
|
+
return param;
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
/**
|
|
865
|
+
* A call its bindings refuse. The reason (a required parameter bound to nothing, or a binding that
|
|
866
|
+
* names no input of the action) is logged for the operator with the run and step IDs. The model is
|
|
867
|
+
* told only that the action is unavailable, because naming the parameter would reveal what is being
|
|
868
|
+
* hidden; and the action is locked out for the rest of the run the way a fatal configuration failure
|
|
869
|
+
* is, so the circuit breaker short-circuits every later call instead of the model being told to
|
|
870
|
+
* "adjust its parameters" for a refusal it cannot fix.
|
|
871
|
+
*/
|
|
872
|
+
refuseBoundAction(params, action, actionEntity, reason, options) {
|
|
873
|
+
this.logError(`Bound action parameters refused '${actionEntity.Name}' (${this.whereInRun(options)}): ${reason}`, {
|
|
874
|
+
category: 'ActionExecution',
|
|
875
|
+
agent: params.agent,
|
|
876
|
+
metadata: { actionName: action.name, runId: this._agentRun?.ID, stepId: options?.StepID }
|
|
877
|
+
});
|
|
878
|
+
this._fatalActionFailures.add(action.name);
|
|
879
|
+
if (actionEntity.Name) {
|
|
880
|
+
this._fatalActionFailures.add(actionEntity.Name);
|
|
881
|
+
}
|
|
882
|
+
return this.buildBlockedActionResult(actionEntity, 'fatal', `Action '${action.name}' is not available in this run's configuration. Do not call it again; use another tool or proceed with the data you have.`);
|
|
883
|
+
}
|
|
884
|
+
/** True when the run binds a parameter on at least one of these actions. */
|
|
885
|
+
bindsAnyAction(actions, bound) {
|
|
886
|
+
return bound !== undefined && actions.some((a) => BindingsForAction(bound, a.ID) !== undefined);
|
|
887
|
+
}
|
|
888
|
+
/** True when the run has any bound action parameters at all. */
|
|
889
|
+
hasBoundActionParams(bound) {
|
|
890
|
+
return bound !== undefined && Object.keys(bound).length > 0;
|
|
891
|
+
}
|
|
892
|
+
/**
|
|
893
|
+
* The error that fails a run at its start when `boundActionParams` names an action that does not
|
|
894
|
+
* exist, so a host that keyed by name or mistyped an ID finds out at once rather than having the
|
|
895
|
+
* parameter it meant to hide shown to the model. Root run only: a sub-agent inherits bindings that
|
|
896
|
+
* were already checked. Needs the action engine configured (Phase 1 of {@link Execute}).
|
|
897
|
+
*/
|
|
898
|
+
boundActionParamsError(params) {
|
|
899
|
+
const bound = params.boundActionParams;
|
|
900
|
+
if (this._depth !== 0 || !bound || Object.keys(bound).length === 0) {
|
|
901
|
+
return null;
|
|
902
|
+
}
|
|
903
|
+
const known = new UUIDSet(ActionEngineServer.Instance.Actions.map((a) => a.ID));
|
|
904
|
+
const unknown = Object.keys(bound).filter((id) => !known.Has(id));
|
|
905
|
+
if (unknown.length === 0) {
|
|
906
|
+
return null;
|
|
907
|
+
}
|
|
908
|
+
return `boundActionParams names no known action: ${unknown.map((id) => `'${id}'`).join(', ')}. Keys are Action IDs.`;
|
|
909
|
+
}
|
|
910
|
+
/**
|
|
911
|
+
* Gives a run that continues another (`lastRunId`) the earlier run's stored bindings, when its caller
|
|
912
|
+
* passed none (an empty object counts as none, as everywhere else). Fails closed: a prior run that
|
|
913
|
+
* can't be read, or whose stored bindings don't parse, fails this run rather than starting it unbound.
|
|
914
|
+
*/
|
|
915
|
+
async inheritBoundActionParams(params) {
|
|
916
|
+
if (this.hasBoundActionParams(params.boundActionParams) || !params.lastRunId) {
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
this.assertLastRunIdIsUUID(params.lastRunId);
|
|
920
|
+
const result = await new RunView().RunView({
|
|
921
|
+
EntityName: 'MJ: AI Agent Runs',
|
|
922
|
+
ExtraFilter: `ID='${EscapeSQLString(params.lastRunId)}'`,
|
|
923
|
+
Fields: ['BoundActionParams'],
|
|
924
|
+
ResultType: 'simple',
|
|
925
|
+
BypassCache: true
|
|
926
|
+
}, params.contextUser);
|
|
927
|
+
if (!result.Success) {
|
|
928
|
+
throw new Error(`Could not read the bindings of run ${params.lastRunId}: ${result.ErrorMessage}`);
|
|
929
|
+
}
|
|
930
|
+
if (result.Results.length === 0) {
|
|
931
|
+
throw new Error(`Could not read the bindings of run ${params.lastRunId}: no such run is visible to this user`);
|
|
932
|
+
}
|
|
933
|
+
const stored = result.Results[0].BoundActionParams;
|
|
934
|
+
if (stored) {
|
|
935
|
+
const parsed = JSON.parse(stored);
|
|
936
|
+
if (!IsPlainObject(parsed)) {
|
|
937
|
+
throw new Error(`The stored bindings of run ${params.lastRunId} are not an object of action bindings`);
|
|
938
|
+
}
|
|
939
|
+
params.boundActionParams = parsed;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* The model's parameters for one action as the progress line and the model-facing invocation record
|
|
944
|
+
* show them: minus any name the run binds, since a value the model wrote for a bound parameter was
|
|
945
|
+
* discarded and must not be shown as if it had been used. With no bindings, `Object.entries(aa.params)`.
|
|
946
|
+
*/
|
|
947
|
+
shownActionParamEntries(params, aa) {
|
|
948
|
+
const entries = Object.entries(aa.params ?? {});
|
|
949
|
+
if (!params.boundActionParams) {
|
|
950
|
+
return entries;
|
|
951
|
+
}
|
|
952
|
+
const actionEntity = this.getEffectiveActionsForValidation(params.agent.ID).find((a) => a.Name === aa.name);
|
|
953
|
+
const bindings = BindingsForAction(params.boundActionParams, actionEntity?.ID ?? '');
|
|
954
|
+
return bindings ? entries.filter(([key]) => !IsBoundParamName(key, bindings)) : entries;
|
|
955
|
+
}
|
|
835
956
|
/**
|
|
836
957
|
* Names the rule behind a failed action summary so the directive matches what actually
|
|
837
958
|
* happened. A blocked call reports the rule that blocked it. A dispatched failure is fatal if
|
|
@@ -1630,6 +1751,10 @@ export class BaseAgent {
|
|
|
1630
1751
|
this._runAbortController = timeoutController;
|
|
1631
1752
|
try {
|
|
1632
1753
|
this.logStatus(`🤖 Starting execution of agent '${params.agent.Name}'`, true, params);
|
|
1754
|
+
// A run that continues another keeps that run's bindings unless its caller gives its own.
|
|
1755
|
+
// Without this, resuming a bound run (from a stored request, or a client's lastRunId)
|
|
1756
|
+
// would show the model the parameters its original caller hid.
|
|
1757
|
+
await this.inheritBoundActionParams(params);
|
|
1633
1758
|
// =====================================================================================
|
|
1634
1759
|
// LATENCY OPTIMIZATION (Opt #4): Parallelized initialization sequence.
|
|
1635
1760
|
//
|
|
@@ -1673,6 +1798,8 @@ export class BaseAgent {
|
|
|
1673
1798
|
this._lastModelSelectionInfo = undefined;
|
|
1674
1799
|
this._lastVolatileStateMessage = undefined;
|
|
1675
1800
|
this._resolvedTrailingStateMode = undefined;
|
|
1801
|
+
this._lastSentFingerprints = undefined;
|
|
1802
|
+
this._lastSentPrefix = undefined;
|
|
1676
1803
|
this._turn1InsertionIndex = -1;
|
|
1677
1804
|
this._runScope = undefined; // set again by initializeAgentRun, in Phase 1
|
|
1678
1805
|
this.resetActionCircuitBreaker();
|
|
@@ -1749,6 +1876,18 @@ export class BaseAgent {
|
|
|
1749
1876
|
const errorMessage = `User ${params.contextUser.Email} does not have permission to run agent '${params.agent.Name}' (ID: ${params.agent.ID})`;
|
|
1750
1877
|
await this.failRunAtStart(errorMessage, params);
|
|
1751
1878
|
}
|
|
1879
|
+
// A binding keyed by something other than a known Action ID fails the run here, before any
|
|
1880
|
+
// prompt is built: silently ignoring it would show the model the parameter the host meant to hide.
|
|
1881
|
+
const bindingError = this.boundActionParamsError(params);
|
|
1882
|
+
if (bindingError) {
|
|
1883
|
+
this.logStatus(`🚫 ${bindingError}`, false, params);
|
|
1884
|
+
if (this._agentRun) {
|
|
1885
|
+
this._agentRun.Status = 'Failed';
|
|
1886
|
+
this._agentRun.ErrorMessage = bindingError;
|
|
1887
|
+
await this._agentRun.Save();
|
|
1888
|
+
}
|
|
1889
|
+
throw new Error(bindingError);
|
|
1890
|
+
}
|
|
1752
1891
|
// Reset per-run state (sync, instant — no parallelization needed)
|
|
1753
1892
|
this._audienceReaders = undefined;
|
|
1754
1893
|
this._audienceSource = undefined;
|
|
@@ -1937,6 +2076,9 @@ export class BaseAgent {
|
|
|
1937
2076
|
this.skipHeldDecisions(params, this.runEndForHeldDecisions());
|
|
1938
2077
|
this.releasePerRunDataCache();
|
|
1939
2078
|
await this.finalizeRun(this.deriveRunOutcome());
|
|
2079
|
+
if (this._agentRun?.ID) {
|
|
2080
|
+
AgentRunWatchdog.Instance.Untrack(this._agentRun.ID);
|
|
2081
|
+
}
|
|
1940
2082
|
// The run is over: a later direct ExecuteSingleAction resolves the scope and the audience from its own params.
|
|
1941
2083
|
this.clearRunBoundState();
|
|
1942
2084
|
}
|
|
@@ -2705,6 +2847,7 @@ export class BaseAgent {
|
|
|
2705
2847
|
data: params.data,
|
|
2706
2848
|
TrustReservedRunData: params.TrustReservedRunData, // the session's data, already vetted when it started
|
|
2707
2849
|
verbose: params.verbose,
|
|
2850
|
+
boundActionParams: params.boundActionParams, // the target keeps the run's bindings, as every sub-agent run does
|
|
2708
2851
|
treeBudget: this.ensureTreeBudget(params),
|
|
2709
2852
|
// Progress streams BOTH to the runner's narration consumer (request.OnProgress —
|
|
2710
2853
|
// it paces SendContextNote/RequestSpokenUpdate over the live socket) AND to any
|
|
@@ -2914,6 +3057,7 @@ export class BaseAgent {
|
|
|
2914
3057
|
// the tracked entry below.
|
|
2915
3058
|
const detail = await md.GetEntityObject('MJ: Conversation Details', params.contextUser);
|
|
2916
3059
|
detail.NewRecord();
|
|
3060
|
+
detail.MarkServerAuthoredReply(); // an agent turn is the server's to write; a person's turn is unaffected
|
|
2917
3061
|
detail.ConversationID = conversationID;
|
|
2918
3062
|
detail.Role = mjRole;
|
|
2919
3063
|
detail.Message = transcript.Text;
|
|
@@ -2966,6 +3110,7 @@ export class BaseAgent {
|
|
|
2966
3110
|
}
|
|
2967
3111
|
created = true;
|
|
2968
3112
|
}
|
|
3113
|
+
detail.MarkServerAuthoredReply();
|
|
2969
3114
|
detail.Message = transcript.Text;
|
|
2970
3115
|
detail.Status = 'Complete';
|
|
2971
3116
|
detail.TurnEndedAt = new Date();
|
|
@@ -3100,11 +3245,12 @@ export class BaseAgent {
|
|
|
3100
3245
|
Provider: md,
|
|
3101
3246
|
Peaks: peaks.length > 0 ? peaks : undefined
|
|
3102
3247
|
});
|
|
3103
|
-
if (stored.FileID) {
|
|
3248
|
+
if (stored.FileID && !stored.ErrorMessage) {
|
|
3104
3249
|
this.logStatus(`🎬 Realtime recording stored (${Math.round(encoded.DurationMs / 1000)}s, file ${stored.FileID}).`, true, params);
|
|
3105
3250
|
}
|
|
3106
3251
|
else {
|
|
3107
|
-
// The store never throws, so its reason only reaches an operator if we log it here.
|
|
3252
|
+
// The store never throws, so its reason only reaches an operator if we log it here. A
|
|
3253
|
+
// FileID alongside an ErrorMessage is an uploaded file the session was not stamped with.
|
|
3108
3254
|
this.logError(`Failed to store realtime recording for session ${sessionID}: ${stored.ErrorMessage ?? 'no reason reported'}`, {
|
|
3109
3255
|
agent: params.agent, category: 'RealtimeSession'
|
|
3110
3256
|
});
|
|
@@ -4101,7 +4247,7 @@ export class BaseAgent {
|
|
|
4101
4247
|
*/
|
|
4102
4248
|
recordToolCallingInstrumentation(stepEntity, promptResult) {
|
|
4103
4249
|
try {
|
|
4104
|
-
const mode = promptResult
|
|
4250
|
+
const mode = TurnToolCallingMode(promptResult);
|
|
4105
4251
|
if (mode) {
|
|
4106
4252
|
stepEntity.ToolCallingMode = mode;
|
|
4107
4253
|
}
|
|
@@ -4170,11 +4316,18 @@ export class BaseAgent {
|
|
|
4170
4316
|
* action results as ONE tool turn — a tool_result block per call, paired by id — when the
|
|
4171
4317
|
* turn's results go back natively; otherwise the markdown user message as before. An action that
|
|
4172
4318
|
* cannot be paired with a call id keeps the markdown message for itself.
|
|
4319
|
+
*
|
|
4320
|
+
* A failed action's guidance (from `failureGuidance`) rides inside its own error result, where
|
|
4321
|
+
* the model reads it as part of that call's outcome rather than as a separate instruction.
|
|
4322
|
+
*
|
|
4323
|
+
* @returns The summaries answered as native tool results — the caller still owes the rest any
|
|
4324
|
+
* guidance, as a message
|
|
4173
4325
|
*/
|
|
4174
|
-
appendActionResults(params, summaries, resultsMessage, metadata, previousDecision) {
|
|
4326
|
+
appendActionResults(params, summaries, resultsMessage, metadata, previousDecision, failureGuidance) {
|
|
4327
|
+
const answered = new Set();
|
|
4175
4328
|
if (!previousDecision.nativeTurn?.sendResultsNatively) {
|
|
4176
4329
|
params.conversationMessages.push({ role: 'user', content: resultsMessage, metadata });
|
|
4177
|
-
return;
|
|
4330
|
+
return answered;
|
|
4178
4331
|
}
|
|
4179
4332
|
const unpaired = [...(previousDecision.actions ?? [])];
|
|
4180
4333
|
const results = [...this.payloadToolResult(previousDecision)];
|
|
@@ -4186,19 +4339,22 @@ export class BaseAgent {
|
|
|
4186
4339
|
orphans.push(summary);
|
|
4187
4340
|
continue;
|
|
4188
4341
|
}
|
|
4342
|
+
const guidance = failureGuidance?.get(summary);
|
|
4189
4343
|
results.push({
|
|
4190
4344
|
toolCallId: action.toolCallId,
|
|
4191
4345
|
toolName: SanitizeToolName(summary.actionName),
|
|
4192
|
-
content: this.formatActionResultsAsMarkdown([summary]),
|
|
4346
|
+
content: this.formatActionResultsAsMarkdown([summary]) + (guidance ? `\n\n${guidance}` : ''),
|
|
4193
4347
|
isError: !summary.success
|
|
4194
4348
|
});
|
|
4349
|
+
answered.add(summary);
|
|
4195
4350
|
}
|
|
4196
4351
|
if (results.length > 0) {
|
|
4197
|
-
|
|
4352
|
+
this.PushToolResultTurn(params, BuildToolResultTurn(results, metadata));
|
|
4198
4353
|
}
|
|
4199
4354
|
if (orphans.length > 0) {
|
|
4200
4355
|
params.conversationMessages.push({ role: 'user', content: `Action results:\n${this.formatActionResultsAsMarkdown(orphans)}`, metadata });
|
|
4201
4356
|
}
|
|
4357
|
+
return answered;
|
|
4202
4358
|
}
|
|
4203
4359
|
/**
|
|
4204
4360
|
* Answers any tool call the turn's own result path left dangling, immediately before the
|
|
@@ -4224,19 +4380,54 @@ export class BaseAgent {
|
|
|
4224
4380
|
}
|
|
4225
4381
|
// Only the most recent assistant call turn can still be open — anything earlier was
|
|
4226
4382
|
// answered by its own branch or closed by a previous pass through here.
|
|
4227
|
-
|
|
4383
|
+
const at = BaseAgent.lastToolCallTurnIndex(messages);
|
|
4384
|
+
if (at < 0) {
|
|
4385
|
+
return;
|
|
4386
|
+
}
|
|
4387
|
+
const answered = BaseAgent.toolCallIdsAnsweredAfter(messages, at);
|
|
4388
|
+
// A call with no id cannot be paired by any provider, so it cannot be answered here
|
|
4389
|
+
// either — `extractOpenAICompatibleToolCalls` substitutes '' when a host omits the id.
|
|
4390
|
+
const unanswered = (messages[at].toolCalls ?? [])
|
|
4391
|
+
.filter((call) => !!call.id && !answered.has(call.id));
|
|
4392
|
+
if (unanswered.length === 0) {
|
|
4393
|
+
return;
|
|
4394
|
+
}
|
|
4395
|
+
const synthetic = BuildToolResultTurn(unanswered.map((call) => ({
|
|
4396
|
+
toolCallId: call.id,
|
|
4397
|
+
toolName: call.name,
|
|
4398
|
+
content: 'Not executed — the agent did not run this call on this turn. See the message that follows.',
|
|
4399
|
+
isError: true
|
|
4400
|
+
})), { turnAdded: this._promptTurnCount, messageType: 'action-result' });
|
|
4401
|
+
BaseAgent.insertToolResultsAfterCallTurn(messages, at, synthetic);
|
|
4402
|
+
}
|
|
4403
|
+
/**
|
|
4404
|
+
* Appends a tool turn answering the latest call turn. When that call turn is already followed
|
|
4405
|
+
* by a tool turn — declined calls, or agent-tool results, answered first — the results join it,
|
|
4406
|
+
* because Anthropic takes every result for a call turn from the one message that follows it.
|
|
4407
|
+
*/
|
|
4408
|
+
PushToolResultTurn(params, results) {
|
|
4409
|
+
const messages = params.conversationMessages;
|
|
4410
|
+
const at = BaseAgent.lastToolCallTurnIndex(messages);
|
|
4411
|
+
if (at >= 0 && at === messages.length - 2 && messages[at + 1].role === 'tool') {
|
|
4412
|
+
BaseAgent.insertToolResultsAfterCallTurn(messages, at, results);
|
|
4413
|
+
return;
|
|
4414
|
+
}
|
|
4415
|
+
messages.push(results);
|
|
4416
|
+
}
|
|
4417
|
+
/** The index of the most recent assistant turn that made tool calls, or -1. */
|
|
4418
|
+
static lastToolCallTurnIndex(messages) {
|
|
4228
4419
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
4229
4420
|
const candidate = messages[i];
|
|
4230
4421
|
if (candidate.role === 'assistant' && candidate.toolCalls?.length) {
|
|
4231
|
-
|
|
4232
|
-
break;
|
|
4422
|
+
return i;
|
|
4233
4423
|
}
|
|
4234
4424
|
}
|
|
4235
|
-
|
|
4236
|
-
|
|
4237
|
-
|
|
4425
|
+
return -1;
|
|
4426
|
+
}
|
|
4427
|
+
/** The call ids that already have a `tool_result` in some message after the call turn. */
|
|
4428
|
+
static toolCallIdsAnsweredAfter(messages, callTurnIndex) {
|
|
4238
4429
|
const answered = new Set();
|
|
4239
|
-
for (let i =
|
|
4430
|
+
for (let i = callTurnIndex + 1; i < messages.length; i++) {
|
|
4240
4431
|
const content = messages[i].content;
|
|
4241
4432
|
if (!Array.isArray(content)) {
|
|
4242
4433
|
continue;
|
|
@@ -4247,19 +4438,24 @@ export class BaseAgent {
|
|
|
4247
4438
|
}
|
|
4248
4439
|
}
|
|
4249
4440
|
}
|
|
4250
|
-
|
|
4251
|
-
|
|
4252
|
-
|
|
4253
|
-
|
|
4254
|
-
|
|
4441
|
+
return answered;
|
|
4442
|
+
}
|
|
4443
|
+
/**
|
|
4444
|
+
* Places a tool turn immediately after the assistant turn whose calls it answers.
|
|
4445
|
+
*
|
|
4446
|
+
* Anthropic requires every result for a call turn in the single message that follows it, and
|
|
4447
|
+
* OpenAI requires the call turn to be followed by its tool messages — so a result appended after
|
|
4448
|
+
* a retry message that already sits behind the call is rejected by both. When the message right
|
|
4449
|
+
* after the call turn is already a tool turn, the results merge into it instead of opening a
|
|
4450
|
+
* second one.
|
|
4451
|
+
*/
|
|
4452
|
+
static insertToolResultsAfterCallTurn(messages, callTurnIndex, results) {
|
|
4453
|
+
const adjacent = messages[callTurnIndex + 1];
|
|
4454
|
+
if (adjacent?.role === 'tool' && Array.isArray(adjacent.content) && Array.isArray(results.content)) {
|
|
4455
|
+
messages[callTurnIndex + 1] = { ...adjacent, content: [...adjacent.content, ...results.content] };
|
|
4255
4456
|
return;
|
|
4256
4457
|
}
|
|
4257
|
-
|
|
4258
|
-
toolCallId: call.id,
|
|
4259
|
-
toolName: call.name,
|
|
4260
|
-
content: 'Not executed — the agent did not run this call on this turn. See the message that follows.',
|
|
4261
|
-
isError: true
|
|
4262
|
-
})), { turnAdded: this._promptTurnCount, messageType: 'action-result' }));
|
|
4458
|
+
messages.splice(callTurnIndex + 1, 0, results);
|
|
4263
4459
|
}
|
|
4264
4460
|
/**
|
|
4265
4461
|
* a tool turn can never be REMOVED from history — that orphans the assistant call it
|
|
@@ -4289,19 +4485,37 @@ export class BaseAgent {
|
|
|
4289
4485
|
// envelope step, so a hidden action or sub-agent left undeclared could not be called at all.
|
|
4290
4486
|
const actions = FilterDeclarableActions(this.getEffectiveActionsForValidation(params.agent.ID), AIEngine.Instance.AgentActions.filter((aa) => UUIDsEqual(aa.AgentID, params.agent.ID)));
|
|
4291
4487
|
const subAgents = this.getEffectiveSubAgentsForValidation(params.agent.ID);
|
|
4292
|
-
|
|
4488
|
+
const agentTools = this.GetAgentTools(params);
|
|
4489
|
+
const control = this.GetNativeControlConfig(params);
|
|
4490
|
+
// A native-only agent declares its control and framework tools even with no Actions or
|
|
4491
|
+
// sub-agents: tools are its only way to act.
|
|
4492
|
+
if (actions.length === 0 && subAgents.length === 0 && agentTools.length === 0 && !control.NativeOnly) {
|
|
4293
4493
|
return;
|
|
4294
4494
|
}
|
|
4295
4495
|
try {
|
|
4296
|
-
|
|
4496
|
+
// A bound parameter (ExecuteAgentParams.boundActionParams) is left out of the tool's schema, so
|
|
4497
|
+
// the model is never asked for it. With no bindings each action's full list is used, as before.
|
|
4498
|
+
const paramsByAction = new Map(actions.map((a) => [a.ID, UnboundParams(a.Params.Items, BindingsForAction(params.boundActionParams, a.ID))]));
|
|
4499
|
+
const actionSet = BuildActionToolSet(actions, paramsByAction);
|
|
4297
4500
|
// Under implicit control flow the agent cannot know which model will answer, so it declares the full
|
|
4298
4501
|
// set — Actions plus the control-flow tools (one per sub-agent, payload_change_request,
|
|
4299
4502
|
// ask_user) — and NAMES the control ones. The runner keeps them only when the selected
|
|
4300
4503
|
// model's LLM.NativeControlFlow resolves to 'implicit'; a hybrid model never sees them.
|
|
4301
|
-
const
|
|
4504
|
+
const frameworkTools = control.NativeOnly
|
|
4505
|
+
? BuildFrameworkTools(this.frameworkToolHost(params), this.frameworkToolAvailability(promptParams, params))
|
|
4506
|
+
: [];
|
|
4507
|
+
const toolSet = BuildNativeToolSet(actionSet, subAgents, control, agentTools, frameworkTools);
|
|
4508
|
+
if (control.NativeOnly && promptParams.data) {
|
|
4509
|
+
// The template renders the tools-only prompt when this is set AND the runner resolves implicit control flow.
|
|
4510
|
+
promptParams.data[NATIVE_ONLY_TEMPLATE_FLAG] = true;
|
|
4511
|
+
promptParams.data[NATIVE_CONTROL_TEMPLATE_DATA] = { Terminal: control.Terminal, PayloadChangeTool: control.PayloadChangeTool, AskUser: control.AskUser };
|
|
4512
|
+
}
|
|
4302
4513
|
promptParams.tools = toolSet.tools;
|
|
4303
4514
|
promptParams.controlFlowToolNames = toolSet.controlToolNames;
|
|
4304
4515
|
promptParams.toolChoice = this.resolveToolChoiceForTurn(params);
|
|
4516
|
+
// Parallel calls stay on through each provider's own default (OpenAI, Anthropic and Gemini
|
|
4517
|
+
// allow them when the flag is absent). Sending an explicit flag would reach providers
|
|
4518
|
+
// whose models do not document it, and a rejected flag would strip every tool.
|
|
4305
4519
|
this._nativeToolBindings = toolSet.byToolName;
|
|
4306
4520
|
}
|
|
4307
4521
|
catch (error) {
|
|
@@ -4311,6 +4525,212 @@ export class BaseAgent {
|
|
|
4311
4525
|
LogError(`Agent '${params.agent.Name}': could not declare native tools — ${error instanceof Error ? error.message : String(error)}`);
|
|
4312
4526
|
}
|
|
4313
4527
|
}
|
|
4528
|
+
/**
|
|
4529
|
+
* The agent's own native tools — tools that read and write this agent's state, such as
|
|
4530
|
+
* `write_section` / `edit_section`. None by default; a driver class overrides this.
|
|
4531
|
+
*
|
|
4532
|
+
* Declared beside the agent's Actions whenever the run declares native tools, and dispatched in
|
|
4533
|
+
* every native mode. Each call runs as a `Tool` run step, in the order the model made the calls,
|
|
4534
|
+
* and its {@link AgentToolResult.PayloadChange} is applied before the next call runs. See
|
|
4535
|
+
* {@link AgentToolDefinition} for the contract.
|
|
4536
|
+
*
|
|
4537
|
+
* @param params The run parameters
|
|
4538
|
+
* @returns The tools to declare this turn
|
|
4539
|
+
*/
|
|
4540
|
+
GetAgentTools(params) {
|
|
4541
|
+
return [];
|
|
4542
|
+
}
|
|
4543
|
+
/**
|
|
4544
|
+
* Which framework capabilities a native-only agent gets as tools this turn — the same gates the
|
|
4545
|
+
* hybrid prompt applies to the matching envelope fields and their documentation.
|
|
4546
|
+
*/
|
|
4547
|
+
frameworkToolAvailability(promptParams, params) {
|
|
4548
|
+
const p = promptParams.data?.__agentTypePromptParams;
|
|
4549
|
+
return {
|
|
4550
|
+
// Each gate matches the one that renders the tool's docs, so a tool is never taught but undeclared.
|
|
4551
|
+
Scratchpad: p?.includeScratchpadDocs !== false,
|
|
4552
|
+
MemoryWrites: p?.includeMemoryWritesDocs !== false && this.memoryWriteSkip(params) === null,
|
|
4553
|
+
ArtifactTools: p?.includeArtifactToolsDocs !== false && this._artifactToolManager.HasArtifacts(),
|
|
4554
|
+
ConversationTools: p?.includeConversationToolsDocs !== false && this._conversationToolManager.IsAvailable,
|
|
4555
|
+
Decisions: this.DecisionsEnabled(p) && p?.includeDecisionsDocs !== false
|
|
4556
|
+
};
|
|
4557
|
+
}
|
|
4558
|
+
/** The capabilities behind the framework tools, bound to this run. */
|
|
4559
|
+
frameworkToolHost(params) {
|
|
4560
|
+
return {
|
|
4561
|
+
ApplyScratchpad: (changes) => this.applyScratchpadFromTool(changes),
|
|
4562
|
+
WriteMemory: (note, type, scopeHint) => this.writeMemoryFromTool({ note, type, scopeHint }, params),
|
|
4563
|
+
RunArtifactTool: (artifactId, tool, input) => this.runArtifactToolFromTool({ artifactId, tool, input }),
|
|
4564
|
+
RunConversationTool: (tool, input) => this.runConversationToolFromTool(tool, input),
|
|
4565
|
+
RunDecisions: (requests, payload) => this.runDecisionsFromTool(requests, payload, params)
|
|
4566
|
+
};
|
|
4567
|
+
}
|
|
4568
|
+
applyScratchpadFromTool(changes) {
|
|
4569
|
+
this._scratchpadManager.ApplyScratchpadChanges(changes);
|
|
4570
|
+
this._scratchpadManager.EnforceTaskLimit(50);
|
|
4571
|
+
return `Scratchpad updated. ${this._scratchpadManager.GetTaskSummary()}`.trim();
|
|
4572
|
+
}
|
|
4573
|
+
async writeMemoryFromTool(write, params) {
|
|
4574
|
+
const skip = this.memoryWriteSkip(params);
|
|
4575
|
+
if (skip) {
|
|
4576
|
+
return { Content: `Not saved: ${skip.Told}.`, IsError: true };
|
|
4577
|
+
}
|
|
4578
|
+
const result = await this._memoryWriteManager.ExecuteWrite(write, this.memoryWriteOptions(params));
|
|
4579
|
+
const failed = result.disposition === 'error' || result.disposition === 'rejected-type';
|
|
4580
|
+
return { Content: `${result.disposition}${result.reason ? `: ${result.reason}` : ''}`, IsError: failed };
|
|
4581
|
+
}
|
|
4582
|
+
async runArtifactToolFromTool(call) {
|
|
4583
|
+
const stored = await this._artifactToolManager.ExecuteSingleToolCall(call);
|
|
4584
|
+
return stored.result.success
|
|
4585
|
+
? { Content: this.capStandaloneToolResultText(RenderToolResultData(stored.result.data)), IsError: false }
|
|
4586
|
+
: { Content: stored.result.errorMessage ?? `Artifact tool '${call.tool}' failed.`, IsError: true };
|
|
4587
|
+
}
|
|
4588
|
+
async runConversationToolFromTool(tool, input) {
|
|
4589
|
+
const name = ConversationToolNames.find((n) => n === tool);
|
|
4590
|
+
if (!name) {
|
|
4591
|
+
return { Content: `'${tool}' is not a conversation tool. Use one of: ${ConversationToolNames.join(', ')}.`, IsError: true };
|
|
4592
|
+
}
|
|
4593
|
+
// The same per-turn cap the envelope's conversationToolCalls has; summarizeRange is a model call.
|
|
4594
|
+
if (this._conversationToolTurn?.turn !== this._promptTurnCount) {
|
|
4595
|
+
this._conversationToolTurn = { turn: this._promptTurnCount, count: 0 };
|
|
4596
|
+
}
|
|
4597
|
+
if (++this._conversationToolTurn.count > MAX_CONVERSATION_TOOL_CALLS_PER_TURN) {
|
|
4598
|
+
return { Content: `Skipped — per-turn cap of ${MAX_CONVERSATION_TOOL_CALLS_PER_TURN} conversation tool calls reached. Call it again on your next turn.`, IsError: true };
|
|
4599
|
+
}
|
|
4600
|
+
const ran = await this._conversationToolManager.ExecuteSingleToolCall({ tool: name, input: input });
|
|
4601
|
+
return ran.result.success
|
|
4602
|
+
? { Content: this.capStandaloneToolResultText(RenderToolResultData(ran.result.data)), IsError: false }
|
|
4603
|
+
: { Content: ran.result.errorMessage ?? `Conversation tool '${tool}' failed.`, IsError: true };
|
|
4604
|
+
}
|
|
4605
|
+
async runDecisionsFromTool(requests, payload, params) {
|
|
4606
|
+
const results = await this.executeDecisionRequestsAsSteps(requests, payload, this._agentTypePromptParams, params);
|
|
4607
|
+
// fls-guard: decision outcomes, not entity rows
|
|
4608
|
+
return { Content: JSON.stringify(results), IsError: results.length > 0 && results.every((r) => !r.success) };
|
|
4609
|
+
}
|
|
4610
|
+
/**
|
|
4611
|
+
* Runs the turn's agent-tool calls in order, each as its own `Tool` run step, threading the
|
|
4612
|
+
* payload through them so successive edits compose.
|
|
4613
|
+
*
|
|
4614
|
+
* @param calls The calls, in the order the model made them
|
|
4615
|
+
* @param payload The payload before the first call
|
|
4616
|
+
* @param params The run parameters
|
|
4617
|
+
* @returns The payload after the last call, and one result per call, in call order
|
|
4618
|
+
*/
|
|
4619
|
+
async ExecuteAgentToolCallsAsSteps(calls, payload, params) {
|
|
4620
|
+
let current = payload;
|
|
4621
|
+
const results = [];
|
|
4622
|
+
for (const call of calls) {
|
|
4623
|
+
// A cancelled run stops between calls; the calls it never reached are answered as not run.
|
|
4624
|
+
if (params.cancellationToken?.aborted) {
|
|
4625
|
+
results.push({ toolCallId: call.toolCallId, toolName: call.toolName, content: 'Not executed: the run was cancelled.', isError: true });
|
|
4626
|
+
continue;
|
|
4627
|
+
}
|
|
4628
|
+
const outcome = await this.executeAgentToolCallAsStep(call, current, params);
|
|
4629
|
+
current = outcome.payload;
|
|
4630
|
+
results.push(outcome.result);
|
|
4631
|
+
}
|
|
4632
|
+
return { payload: current, results };
|
|
4633
|
+
}
|
|
4634
|
+
/** One agent-tool call as a `Tool` run step: run it, apply its payload change, record both. */
|
|
4635
|
+
async executeAgentToolCallAsStep(call, payload, params) {
|
|
4636
|
+
const step = await this.createStepEntity({
|
|
4637
|
+
stepType: 'Tool',
|
|
4638
|
+
stepName: `Agent Tool: ${call.toolName}`,
|
|
4639
|
+
contextUser: params.contextUser,
|
|
4640
|
+
inputData: { tool: call.toolName, arguments: call.arguments },
|
|
4641
|
+
payloadAtStart: payload
|
|
4642
|
+
});
|
|
4643
|
+
// Whatever fails below, the step is finalized and the call answered — never left Running.
|
|
4644
|
+
let outcome = { payload, content: '', isError: true };
|
|
4645
|
+
try {
|
|
4646
|
+
const ran = await this.runAgentTool(call, payload, params);
|
|
4647
|
+
// payload_change_request keeps its single-call behaviour: the allowed parts apply.
|
|
4648
|
+
const partial = this._nativeToolBindings?.get(call.toolName)?.kind === 'payloadChange';
|
|
4649
|
+
const applied = !ran.IsError && ran.PayloadChange
|
|
4650
|
+
? this.applyAgentToolPayloadChange(payload, ran.PayloadChange, params, partial)
|
|
4651
|
+
: { payload, error: undefined };
|
|
4652
|
+
outcome = { payload: applied.payload, content: applied.error ?? ran.Content, isError: ran.IsError || applied.error !== undefined };
|
|
4653
|
+
}
|
|
4654
|
+
catch (error) {
|
|
4655
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
4656
|
+
LogError(`Agent '${params.agent?.Name}': applying agent tool '${call.toolName}' failed: ${message}`);
|
|
4657
|
+
outcome = { payload, content: `The tool's change could not be applied: ${message}. Nothing was changed.`, isError: true };
|
|
4658
|
+
}
|
|
4659
|
+
finally {
|
|
4660
|
+
step.PayloadAtEnd = this.serializePayloadAtEnd(outcome.payload);
|
|
4661
|
+
await this.finalizeStepEntity(step, !outcome.isError, outcome.isError ? outcome.content : undefined, { tool: call.toolName, content: outcome.content, isError: outcome.isError });
|
|
4662
|
+
}
|
|
4663
|
+
return { payload: outcome.payload, result: { toolCallId: call.toolCallId, toolName: call.toolName, content: outcome.content, isError: outcome.isError } };
|
|
4664
|
+
}
|
|
4665
|
+
/** Calls the tool's handler; an undeclared tool or a thrown error becomes an error result. */
|
|
4666
|
+
async runAgentTool(call, payload, params) {
|
|
4667
|
+
const binding = this._nativeToolBindings?.get(call.toolName);
|
|
4668
|
+
if (binding?.kind === 'payloadChange') {
|
|
4669
|
+
// One of several payload writes on a turn, run in call order with the agent's own tools.
|
|
4670
|
+
return { Content: 'Payload change applied.', IsError: false, PayloadChange: call.arguments };
|
|
4671
|
+
}
|
|
4672
|
+
if (binding?.kind !== 'agentTool') {
|
|
4673
|
+
return { Content: `'${call.toolName}' is not one of this agent's tools.`, IsError: true };
|
|
4674
|
+
}
|
|
4675
|
+
try {
|
|
4676
|
+
// A copy: the tool changes state through its PayloadChange, which PayloadSelfWritePaths
|
|
4677
|
+
// checks — an edit made in place on the live payload would bypass that check.
|
|
4678
|
+
const context = { CurrentPayload: this.cloneSubAgentPayload(payload), Params: params, ContextUser: params.contextUser };
|
|
4679
|
+
return await binding.definition.Execute(call.arguments, context);
|
|
4680
|
+
}
|
|
4681
|
+
catch (error) {
|
|
4682
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
4683
|
+
LogError(`Agent '${params.agent?.Name}': agent tool '${call.toolName}' threw: ${message}`);
|
|
4684
|
+
return { Content: `The tool failed: ${message}`, IsError: true };
|
|
4685
|
+
}
|
|
4686
|
+
}
|
|
4687
|
+
/**
|
|
4688
|
+
* Applies an agent tool's payload change through PayloadManager, under the agent's
|
|
4689
|
+
* `PayloadSelfWritePaths`. A change that touches a path the agent may not write is rejected
|
|
4690
|
+
* whole — a partial write would leave the payload in a state the tool never described — and
|
|
4691
|
+
* the reason goes back to the model as the call's error result.
|
|
4692
|
+
*
|
|
4693
|
+
* @param partial Apply the allowed parts and report the rest, as a single `payload_change_request`
|
|
4694
|
+
* on a turn always has; the model wrote that change itself, path by path
|
|
4695
|
+
*/
|
|
4696
|
+
applyAgentToolPayloadChange(payload, change, params, partial = false) {
|
|
4697
|
+
const allowedPaths = params.agent.PayloadSelfWritePaths
|
|
4698
|
+
? JSON.parse(params.agent.PayloadSelfWritePaths)
|
|
4699
|
+
: this.getDefaultPayloadSelfWritePaths();
|
|
4700
|
+
const changeResult = this._payloadManager.applyAgentChangeRequest(payload, change, {
|
|
4701
|
+
validateChanges: true,
|
|
4702
|
+
logChanges: true,
|
|
4703
|
+
agentName: params.agent.Name,
|
|
4704
|
+
allowedPaths,
|
|
4705
|
+
verbose: params.verbose === true || IsVerboseLoggingEnabled()
|
|
4706
|
+
});
|
|
4707
|
+
const blocked = changeResult.blockedOperations ?? [];
|
|
4708
|
+
if (blocked.length > 0) {
|
|
4709
|
+
const paths = [...new Set(blocked.map((b) => b.path))].join(', ');
|
|
4710
|
+
return partial
|
|
4711
|
+
? { payload: changeResult.result, error: `Applied, except the paths this agent may not write: ${paths}.` }
|
|
4712
|
+
: { payload, error: `Not applied: this agent may not write ${paths}. Nothing was changed.` };
|
|
4713
|
+
}
|
|
4714
|
+
return { payload: changeResult.result };
|
|
4715
|
+
}
|
|
4716
|
+
/**
|
|
4717
|
+
* Answers the turn's agent-tool calls, directly after the call turn the loop just replayed. When
|
|
4718
|
+
* the turn's results do not go back natively, the results become one user message instead.
|
|
4719
|
+
*/
|
|
4720
|
+
appendAgentToolResults(params, step) {
|
|
4721
|
+
const pending = this._pendingAgentToolResults;
|
|
4722
|
+
this._pendingAgentToolResults = undefined;
|
|
4723
|
+
if (!pending || pending.results.length === 0) {
|
|
4724
|
+
return;
|
|
4725
|
+
}
|
|
4726
|
+
const metadata = { turnAdded: this._promptTurnCount, messageType: 'action-result' };
|
|
4727
|
+
if (step.nativeTurn?.sendResultsNatively && this._lastNativeTurnAppended === step.nativeTurn) {
|
|
4728
|
+
this.PushToolResultTurn(params, BuildToolResultTurn(pending.results, metadata));
|
|
4729
|
+
return;
|
|
4730
|
+
}
|
|
4731
|
+
const lines = pending.results.map((r) => `### ${r.toolName}${r.isError ? ' (failed)' : ''}\n${r.content}`);
|
|
4732
|
+
params.conversationMessages.push({ role: 'user', content: `Tool results:\n\n${lines.join('\n\n')}`, metadata });
|
|
4733
|
+
}
|
|
4314
4734
|
/**
|
|
4315
4735
|
* The `tool_choice` for this turn (§8.3).
|
|
4316
4736
|
*
|
|
@@ -4337,14 +4757,43 @@ export class BaseAgent {
|
|
|
4337
4757
|
* address them. That belongs to the prompt, and is why the native-mode Actions section names
|
|
4338
4758
|
* the cases explicitly.
|
|
4339
4759
|
*
|
|
4760
|
+
* **A text-terminal agent** (`NativeControl.Terminal: 'text'`) declares no `complete_task`: its
|
|
4761
|
+
* answer is the plain-text reply, and its state changes went through its own tools on earlier
|
|
4762
|
+
* turns. Its final turn is `'none'`, which asks for exactly that reply.
|
|
4763
|
+
*
|
|
4340
4764
|
* Subclasses may narrow this further; the base contract is that a forced terminal choice must
|
|
4341
4765
|
* never be relaxed to `'auto'` on a turn the framework has already decided is terminal.
|
|
4342
4766
|
*
|
|
4343
4767
|
* @param params The run parameters, for the per-run iteration override
|
|
4344
|
-
* @returns `{ name: 'complete_task' }
|
|
4768
|
+
* @returns On the final permitted iteration, `{ name: 'complete_task' }`, or `'none'` for a
|
|
4769
|
+
* text-terminal agent; otherwise `'auto'`
|
|
4345
4770
|
*/
|
|
4346
4771
|
resolveToolChoiceForTurn(params) {
|
|
4347
|
-
|
|
4772
|
+
if (!this.isFinalPermittedIteration(params)) {
|
|
4773
|
+
return 'auto';
|
|
4774
|
+
}
|
|
4775
|
+
return this.GetNativeControlConfig(params).Terminal === 'text' ? 'none' : { name: COMPLETE_TASK_TOOL };
|
|
4776
|
+
}
|
|
4777
|
+
/**
|
|
4778
|
+
* The agent's native control configuration — which control tools it declares and how its run
|
|
4779
|
+
* ends — from the `NativeControl` block of its `TypeConfiguration`. Defaults when there is none.
|
|
4780
|
+
*
|
|
4781
|
+
* Parsed once per distinct configuration; anything unusable is logged once and falls back to its
|
|
4782
|
+
* default, so a typo never fails a run.
|
|
4783
|
+
*
|
|
4784
|
+
* @param params The run parameters, for the agent
|
|
4785
|
+
*/
|
|
4786
|
+
GetNativeControlConfig(params) {
|
|
4787
|
+
const source = params.agent?.TypeConfiguration ?? null;
|
|
4788
|
+
if (this._nativeControl && this._nativeControl.source === source) {
|
|
4789
|
+
return this._nativeControl.config;
|
|
4790
|
+
}
|
|
4791
|
+
const { Config, Problems } = ResolveNativeControlConfig(source);
|
|
4792
|
+
for (const problem of Problems) {
|
|
4793
|
+
LogError(`Agent '${params.agent?.Name}': ${problem}`);
|
|
4794
|
+
}
|
|
4795
|
+
this._nativeControl = { source, config: Config };
|
|
4796
|
+
return Config;
|
|
4348
4797
|
}
|
|
4349
4798
|
/**
|
|
4350
4799
|
* Whether the turn currently being prepared is the last one this run will be allowed.
|
|
@@ -4380,7 +4829,7 @@ export class BaseAgent {
|
|
|
4380
4829
|
const systemPrompt = config.systemPrompt;
|
|
4381
4830
|
const childPrompt = config.childPrompt;
|
|
4382
4831
|
// Gather context data (including runtime action changes)
|
|
4383
|
-
const promptTemplateData = await this.gatherPromptTemplateData(params.agent, params.contextUser, params.data, params.actionChanges, params.subAgentChanges, this.promptWithholding(params));
|
|
4832
|
+
const promptTemplateData = await this.gatherPromptTemplateData(params.agent, params.contextUser, params.data, params.actionChanges, params.subAgentChanges, params.boundActionParams, this.promptWithholding(params));
|
|
4384
4833
|
// Set up the hierarchical prompt execution
|
|
4385
4834
|
const promptParams = new AIPromptParams();
|
|
4386
4835
|
// Attribute the resulting AIPromptRun to this agent. Agents share agent-type-level system
|
|
@@ -4405,6 +4854,12 @@ export class BaseAgent {
|
|
|
4405
4854
|
promptParams.contextUser = params.contextUser;
|
|
4406
4855
|
// Last gate before the history goes back to the model: no tool call may be left dangling.
|
|
4407
4856
|
this.reconcileUnansweredToolCalls(params);
|
|
4857
|
+
if (this.GetNativeControlConfig(params).CompactToolArguments) {
|
|
4858
|
+
const compacted = CompactAnsweredToolCallArguments(params.conversationMessages);
|
|
4859
|
+
if (compacted > 0) {
|
|
4860
|
+
this.logStatus(`[NativeTools] Compacted the large arguments of ${compacted} older tool call(s)`, true, params);
|
|
4861
|
+
}
|
|
4862
|
+
}
|
|
4408
4863
|
promptParams.conversationMessages = params.conversationMessages;
|
|
4409
4864
|
promptParams.verbose = params.verbose; // Pass through verbose flag
|
|
4410
4865
|
this.applyNativeTools(promptParams, params);
|
|
@@ -4459,6 +4914,10 @@ export class BaseAgent {
|
|
|
4459
4914
|
promptParams.data['_ARTIFACTS_ENABLED'] = this.isArtifactSupportEnabled(params.agent);
|
|
4460
4915
|
if (artifactToolsEnabled && this._artifactToolManager.HasArtifacts()) {
|
|
4461
4916
|
promptParams.data['_ARTIFACT_MANIFEST'] = this._artifactToolManager.ToManifestString();
|
|
4917
|
+
if (this.GetNativeControlConfig(params).NativeOnly) {
|
|
4918
|
+
// The native-only prompt (picked at render time) names the artifact_tool tool instead of artifactToolCalls.
|
|
4919
|
+
promptParams.data['_ARTIFACT_MANIFEST_NATIVE'] = this._artifactToolManager.ToManifestString({ nativeTools: true });
|
|
4920
|
+
}
|
|
4462
4921
|
promptParams.data['_ARTIFACT_TOOLS'] = this._artifactToolManager.GetToolDocumentation();
|
|
4463
4922
|
promptParams.data['_ARTIFACT_TOOL_SUMMARY'] = this._artifactToolManager.GetSummary();
|
|
4464
4923
|
this.logStatus(`[ArtifactTools] Injected manifest into prompt: ${this._artifactToolManager.GetSummary()}`, true, params);
|
|
@@ -4472,6 +4931,9 @@ export class BaseAgent {
|
|
|
4472
4931
|
const conversationToolsEnabled = agentTypePromptParams?.includeConversationToolsDocs !== false;
|
|
4473
4932
|
if (conversationToolsEnabled && this._conversationToolManager.IsAvailable) {
|
|
4474
4933
|
promptParams.data['_CONVERSATION_TOOLS'] = this._conversationToolManager.GetToolDocumentation();
|
|
4934
|
+
if (this.GetNativeControlConfig(params).NativeOnly) {
|
|
4935
|
+
promptParams.data['_CONVERSATION_TOOLS_NATIVE'] = this._conversationToolManager.GetToolDocumentation(true);
|
|
4936
|
+
}
|
|
4475
4937
|
}
|
|
4476
4938
|
// Enable the memory-writes response field + docs only for agents that opted in
|
|
4477
4939
|
// via AllowMemoryWrite, and never under an audience (memoryWriteSkip). Disabled agents never
|
|
@@ -4592,8 +5054,87 @@ export class BaseAgent {
|
|
|
4592
5054
|
}
|
|
4593
5055
|
this._lastVolatileStateMessage = volatileStateMessage;
|
|
4594
5056
|
}
|
|
5057
|
+
if (promptParams.conversationMessages) {
|
|
5058
|
+
promptParams.conversationMessages = this.dropReasoningBehindChangedHistory(params, promptParams.conversationMessages, promptParams);
|
|
5059
|
+
}
|
|
4595
5060
|
return promptParams;
|
|
4596
5061
|
}
|
|
5062
|
+
/**
|
|
5063
|
+
* Drops replayed reasoning that the history before it no longer matches.
|
|
5064
|
+
*
|
|
5065
|
+
* A driver with `ReplayedReasoningRequiresStablePrefix` accepts a replayed reasoning block
|
|
5066
|
+
* only while every message before it is exactly what was sent when the block was produced.
|
|
5067
|
+
* Expiry, compaction, message expansion and context recovery all rewrite earlier messages,
|
|
5068
|
+
* and each would make the request fail. So the outgoing messages are compared with the
|
|
5069
|
+
* previous request's: from the first message that was changed or removed, every call turn's
|
|
5070
|
+
* reasoning is dropped — in this request and in the history, so later requests stay
|
|
5071
|
+
* consistent. Messages the previous request did not have (the model's reply, new results)
|
|
5072
|
+
* are not a change.
|
|
5073
|
+
*/
|
|
5074
|
+
dropReasoningBehindChangedHistory(params, outgoing, promptParams) {
|
|
5075
|
+
const fingerprints = outgoing.map(BaseAgent.messageFingerprint);
|
|
5076
|
+
const previous = this._lastSentFingerprints;
|
|
5077
|
+
this._lastSentFingerprints = fingerprints;
|
|
5078
|
+
if (!this.replaysPrefixBoundReasoning()) {
|
|
5079
|
+
return outgoing;
|
|
5080
|
+
}
|
|
5081
|
+
// The system prompt and tools are compared by the prompt runner, which renders the one and finalizes the other.
|
|
5082
|
+
promptParams.ReplayedReasoningPrefix = this._lastSentPrefix;
|
|
5083
|
+
if (!previous) {
|
|
5084
|
+
return outgoing;
|
|
5085
|
+
}
|
|
5086
|
+
const changedAt = previous.findIndex((fingerprint, i) => fingerprints[i] !== fingerprint);
|
|
5087
|
+
if (changedAt < 0) {
|
|
5088
|
+
return outgoing;
|
|
5089
|
+
}
|
|
5090
|
+
const stale = new Set(outgoing.slice(changedAt).flatMap((m) => m.reasoning?.length ? (m.toolCalls ?? []).map((c) => c.id) : []));
|
|
5091
|
+
if (stale.size === 0) {
|
|
5092
|
+
return outgoing;
|
|
5093
|
+
}
|
|
5094
|
+
const withoutReasoning = (m) => {
|
|
5095
|
+
const { reasoning: _dropped, ...rest } = m;
|
|
5096
|
+
return rest;
|
|
5097
|
+
};
|
|
5098
|
+
const callsStale = (m) => !!m.reasoning && (m.toolCalls ?? []).some((c) => stale.has(c.id));
|
|
5099
|
+
// In place: the caller holds this array.
|
|
5100
|
+
params.conversationMessages.forEach((m, i) => {
|
|
5101
|
+
if (callsStale(m)) {
|
|
5102
|
+
params.conversationMessages[i] = withoutReasoning(m);
|
|
5103
|
+
}
|
|
5104
|
+
});
|
|
5105
|
+
this.logStatus(`Dropped replayed reasoning from ${stale.size} tool call(s): an earlier message changed since it was produced`, true, params);
|
|
5106
|
+
return outgoing.map((m, i) => (i >= changedAt && callsStale(m) ? withoutReasoning(m) : m));
|
|
5107
|
+
}
|
|
5108
|
+
/** Whether this run replays reasoning to a driver that binds it to an unchanged request prefix. */
|
|
5109
|
+
replaysPrefixBoundReasoning() {
|
|
5110
|
+
const selection = this._lastModelSelectionInfo;
|
|
5111
|
+
return this._nativeToolBindings !== undefined
|
|
5112
|
+
&& this.DriverRequiresStableReasoningPrefix(selection?.ModelSelected, selection?.vendorSelected);
|
|
5113
|
+
}
|
|
5114
|
+
/**
|
|
5115
|
+
* Keeps the system-prompt-and-tools fingerprint of the request just sent, for the next one. When
|
|
5116
|
+
* it changed, the runner sent this request without replayed reasoning; the history drops it too,
|
|
5117
|
+
* so no later request replays a block made under the old prompt or tools.
|
|
5118
|
+
*/
|
|
5119
|
+
trackSentPrefix(params, promptResult) {
|
|
5120
|
+
const sent = GetSentPrefixFingerprint(promptResult.chatResult);
|
|
5121
|
+
const previous = this._lastSentPrefix;
|
|
5122
|
+
this._lastSentPrefix = sent;
|
|
5123
|
+
if (previous === undefined || sent === undefined || sent === previous || !this.replaysPrefixBoundReasoning()) {
|
|
5124
|
+
return;
|
|
5125
|
+
}
|
|
5126
|
+
params.conversationMessages.forEach((m, i) => {
|
|
5127
|
+
const turn = m;
|
|
5128
|
+
if (turn.reasoning) {
|
|
5129
|
+
const { reasoning: _dropped, ...rest } = turn;
|
|
5130
|
+
params.conversationMessages[i] = rest;
|
|
5131
|
+
}
|
|
5132
|
+
});
|
|
5133
|
+
}
|
|
5134
|
+
/** What makes a message the same message to a provider — reasoning aside, which only this check removes. */
|
|
5135
|
+
static messageFingerprint(m) {
|
|
5136
|
+
return JSON.stringify([m.role, m.content, m.toolCalls?.map((c) => [c.id, c.name, c.arguments])]);
|
|
5137
|
+
}
|
|
4597
5138
|
/**
|
|
4598
5139
|
* In append-only mode, restores turn 1's volatile state fragment if mode resolution
|
|
4599
5140
|
* was deferred until after turn 1 (e.g. dynamic model selection).
|
|
@@ -4654,7 +5195,9 @@ export class BaseAgent {
|
|
|
4654
5195
|
* Which providers are which is METADATA, not code: the `PrefixPromptCache` flag in the model
|
|
4655
5196
|
* catalog's `ModelConfiguration` cascade (Model Types < Models < Vendors' `Configuration.ModelDefaults`
|
|
4656
5197
|
* < Model Vendors), read through {@link resolvePrefixPromptCache}. `true` means append-only;
|
|
4657
|
-
* anything else means replace.
|
|
5198
|
+
* anything else means replace. One exception comes from the driver, not the catalog: a run that
|
|
5199
|
+
* declares native tools to a driver whose replayed reasoning needs the history before it
|
|
5200
|
+
* unchanged is append-only too (see {@link ResolveAppendOnlyState}).
|
|
4658
5201
|
*
|
|
4659
5202
|
* Decided ONCE per run. An explicit `trailingStateMode` or a runtime model override answers
|
|
4660
5203
|
* immediately. Otherwise the answer is frozen at the first model selection and reused for every
|
|
@@ -4683,7 +5226,11 @@ export class BaseAgent {
|
|
|
4683
5226
|
if (promptParams.override?.modelId) {
|
|
4684
5227
|
const model = AIEngine.Instance?.ModelsByID?.get(NormalizeUUID(promptParams.override.modelId));
|
|
4685
5228
|
const vendor = promptParams.override.vendorId ? AIEngine.Instance?.VendorsByID?.get(NormalizeUUID(promptParams.override.vendorId)) : undefined;
|
|
4686
|
-
|
|
5229
|
+
// Without a vendor the serving driver is not known yet: a catalog "yes" stands, anything
|
|
5230
|
+
// else waits for the first selection below, which names the vendor.
|
|
5231
|
+
if (vendor || this.resolvePrefixPromptCache(model, undefined)) {
|
|
5232
|
+
return this.ResolveAppendOnlyState(model, vendor);
|
|
5233
|
+
}
|
|
4687
5234
|
}
|
|
4688
5235
|
if (this._resolvedTrailingStateMode !== undefined) {
|
|
4689
5236
|
return this._resolvedTrailingStateMode;
|
|
@@ -4691,12 +5238,39 @@ export class BaseAgent {
|
|
|
4691
5238
|
if (this._lastModelSelectionInfo) {
|
|
4692
5239
|
const model = this._lastModelSelectionInfo.ModelSelected;
|
|
4693
5240
|
const vendor = this._lastModelSelectionInfo.vendorSelected;
|
|
4694
|
-
this._resolvedTrailingStateMode = this.
|
|
5241
|
+
this._resolvedTrailingStateMode = this.ResolveAppendOnlyState(model, vendor);
|
|
4695
5242
|
return this._resolvedTrailingStateMode;
|
|
4696
5243
|
}
|
|
4697
5244
|
// Turn 1, nothing known yet: replace-in-place, resolved for good on turn 2 (see above).
|
|
4698
5245
|
return false;
|
|
4699
5246
|
}
|
|
5247
|
+
/**
|
|
5248
|
+
* Whether this run keeps its runtime-state fragments (append-only): the model sits behind a
|
|
5249
|
+
* byte-prefix prompt cache, or the run declares native tools to a driver whose replayed
|
|
5250
|
+
* reasoning is accepted only while the history before it is unchanged. In replace mode each
|
|
5251
|
+
* request drops the previous fragment, and a thinking block produced after it would be replayed
|
|
5252
|
+
* behind a changed history and rejected.
|
|
5253
|
+
*/
|
|
5254
|
+
ResolveAppendOnlyState(model, vendor) {
|
|
5255
|
+
if (this.resolvePrefixPromptCache(model, vendor)) {
|
|
5256
|
+
return true;
|
|
5257
|
+
}
|
|
5258
|
+
return this._nativeToolBindings !== undefined && this.DriverRequiresStableReasoningPrefix(model, vendor);
|
|
5259
|
+
}
|
|
5260
|
+
/** Whether the driver serving `model` on `vendor` binds replayed reasoning to the unchanged history before it. */
|
|
5261
|
+
DriverRequiresStableReasoningPrefix(model, vendor) {
|
|
5262
|
+
if (!model || !vendor) {
|
|
5263
|
+
return false;
|
|
5264
|
+
}
|
|
5265
|
+
const engine = AIEngine.Instance;
|
|
5266
|
+
const modelVendor = (engine.ModelVendorsByModelID?.get(NormalizeUUID(model.ID)) ?? [])
|
|
5267
|
+
.find(mv => UUIDsEqual(mv.VendorID, vendor.ID) && engine.IsInferenceProvider(mv));
|
|
5268
|
+
if (!modelVendor?.DriverClass) {
|
|
5269
|
+
return false;
|
|
5270
|
+
}
|
|
5271
|
+
const driver = MJGlobal.Instance.ClassFactory.GetRegistration(BaseLLM, modelVendor.DriverClass)?.SubClass;
|
|
5272
|
+
return driver?.ReplayedReasoningRequiresStablePrefix === true;
|
|
5273
|
+
}
|
|
4700
5274
|
/**
|
|
4701
5275
|
* Whether a model, as served by a vendor, sits behind a byte-prefix prompt cache
|
|
4702
5276
|
* (`LLM.PrefixPromptCache`), read from the model catalog's `ModelConfiguration` cascade —
|
|
@@ -5503,10 +6077,12 @@ export class BaseAgent {
|
|
|
5503
6077
|
if (nextStep.step !== 'Retry') {
|
|
5504
6078
|
this._generalValidationRetryCount++;
|
|
5505
6079
|
}
|
|
6080
|
+
// A native complete_task keeps its turn and call id, so the refusal answers that call.
|
|
5506
6081
|
return {
|
|
5507
6082
|
step: 'Retry',
|
|
5508
6083
|
terminate: false,
|
|
5509
|
-
errorMessage: violationMessage
|
|
6084
|
+
errorMessage: violationMessage,
|
|
6085
|
+
...(nextStep.nativeTurn ? { nativeTurn: nextStep.nativeTurn, payloadToolCallId: nextStep.payloadToolCallId } : {})
|
|
5510
6086
|
};
|
|
5511
6087
|
}
|
|
5512
6088
|
// Check if the agent has FinalPayloadValidation configured
|
|
@@ -6952,35 +7528,104 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
6952
7528
|
this.logStatus(`📌 Next step determined: ${guardrailCheckedStep.step}${guardrailCheckedStep.terminate ? ' (terminating)' : ''}`, true, params);
|
|
6953
7529
|
// the model's own call turn goes into history before anything answers it.
|
|
6954
7530
|
this.appendNativeAssistantTurn(params, guardrailCheckedStep);
|
|
7531
|
+
// the agent's own tools already ran in the prompt step; their results answer first.
|
|
7532
|
+
this.appendAgentToolResults(params, guardrailCheckedStep);
|
|
6955
7533
|
// if we need to retry make sure we add the retry message to the conversation messages
|
|
6956
7534
|
if (guardrailCheckedStep.step === 'Retry' && guardrailCheckedStep.payloadToolCallId && guardrailCheckedStep.nativeTurn?.sendResultsNatively) {
|
|
6957
7535
|
// A payload-only turn, or a complete_task that failed Success validation, is answered as a
|
|
6958
7536
|
// tool result for that call — the feedback is what the model reads next.
|
|
6959
|
-
|
|
7537
|
+
// A complete_task that came back as a Retry was refused (Success validation, a self-check
|
|
7538
|
+
// rubric): its feedback, wherever the step carries it, is that call's error result.
|
|
7539
|
+
const toolName = this.nativeToolNameForCall(guardrailCheckedStep, guardrailCheckedStep.payloadToolCallId);
|
|
7540
|
+
const refusedCompletion = toolName === COMPLETE_TASK_TOOL;
|
|
7541
|
+
const feedback = guardrailCheckedStep.retryInstructions
|
|
7542
|
+
|| (refusedCompletion ? guardrailCheckedStep.message || guardrailCheckedStep.errorMessage : undefined);
|
|
7543
|
+
this.PushToolResultTurn(params, BuildToolResultTurn([{
|
|
6960
7544
|
toolCallId: guardrailCheckedStep.payloadToolCallId,
|
|
6961
|
-
toolName
|
|
6962
|
-
content:
|
|
6963
|
-
isError:
|
|
7545
|
+
toolName,
|
|
7546
|
+
content: feedback || (refusedCompletion ? 'The task is not complete yet.' : 'Payload change applied.'),
|
|
7547
|
+
isError: refusedCompletion
|
|
6964
7548
|
}], { turnAdded: this._promptTurnCount, messageType: 'action-result' }));
|
|
6965
7549
|
}
|
|
6966
7550
|
else if (guardrailCheckedStep.step === 'Success' && guardrailCheckedStep.payloadToolCallId && guardrailCheckedStep.nativeTurn?.sendResultsNatively) {
|
|
6967
7551
|
// complete_task ended the run: answer the call so the history never ends on a dangling tool_use.
|
|
6968
|
-
|
|
7552
|
+
this.PushToolResultTurn(params, BuildToolResultTurn([{
|
|
6969
7553
|
toolCallId: guardrailCheckedStep.payloadToolCallId,
|
|
6970
7554
|
toolName: this.nativeToolNameForCall(guardrailCheckedStep, guardrailCheckedStep.payloadToolCallId),
|
|
6971
7555
|
content: 'Task complete.',
|
|
6972
7556
|
isError: false
|
|
6973
7557
|
}], { turnAdded: this._promptTurnCount, messageType: 'action-result' }));
|
|
6974
7558
|
}
|
|
6975
|
-
else if (guardrailCheckedStep.step === 'Retry'
|
|
6976
|
-
|
|
6977
|
-
|
|
6978
|
-
|
|
6979
|
-
|
|
7559
|
+
else if (guardrailCheckedStep.step === 'Retry') {
|
|
7560
|
+
const reason = guardrailCheckedStep.retryInstructions || guardrailCheckedStep.message || guardrailCheckedStep.errorMessage;
|
|
7561
|
+
if (reason && !this.answerNativeRetryTurn(params, guardrailCheckedStep, reason)) {
|
|
7562
|
+
params.conversationMessages.push({
|
|
7563
|
+
role: 'user',
|
|
7564
|
+
content: `Retrying due to: ${reason}`
|
|
7565
|
+
});
|
|
7566
|
+
}
|
|
6980
7567
|
}
|
|
6981
7568
|
// Return the next step directly - execution handling is done in execute NextStep
|
|
6982
7569
|
return guardrailCheckedStep;
|
|
6983
7570
|
}
|
|
7571
|
+
/**
|
|
7572
|
+
* Answers a retried native tool-call turn in the protocol itself: every call gets an `is_error`
|
|
7573
|
+
* result carrying the retry reason, and no user message follows.
|
|
7574
|
+
*
|
|
7575
|
+
* The call turn was just replayed by `appendNativeAssistantTurn`, so the result turn lands
|
|
7576
|
+
* directly behind it — the adjacency Anthropic and OpenAI both require. Calls the turn already
|
|
7577
|
+
* answered (its agent tools ran and reported) keep their results; the rest join that tool turn.
|
|
7578
|
+
* Returns false when the turn's results do not go back natively, or no call is left to answer;
|
|
7579
|
+
* the caller then sends the reason as a user message, and `reconcileUnansweredToolCalls`
|
|
7580
|
+
* closes any call still open.
|
|
7581
|
+
*/
|
|
7582
|
+
answerNativeRetryTurn(params, step, reason) {
|
|
7583
|
+
const turn = step.nativeTurn;
|
|
7584
|
+
const messages = params.conversationMessages;
|
|
7585
|
+
const at = turn?.sendResultsNatively ? BaseAgent.lastToolCallTurnIndex(messages) : -1;
|
|
7586
|
+
if (!turn || at < 0) {
|
|
7587
|
+
return false;
|
|
7588
|
+
}
|
|
7589
|
+
const answered = BaseAgent.toolCallIdsAnsweredAfter(messages, at);
|
|
7590
|
+
const calls = turn.toolCalls.filter((call) => !!call.id && !answered.has(call.id));
|
|
7591
|
+
if (calls.length === 0) {
|
|
7592
|
+
return false;
|
|
7593
|
+
}
|
|
7594
|
+
BaseAgent.insertToolResultsAfterCallTurn(messages, at, BuildToolResultTurn(calls.map((call) => ({
|
|
7595
|
+
toolCallId: call.id,
|
|
7596
|
+
toolName: call.name,
|
|
7597
|
+
content: `Not executed. ${reason}`,
|
|
7598
|
+
isError: true
|
|
7599
|
+
})), { turnAdded: this._promptTurnCount, messageType: 'action-result' }));
|
|
7600
|
+
return true;
|
|
7601
|
+
}
|
|
7602
|
+
/**
|
|
7603
|
+
* A turn that wrote and then asked or completed, where a write failed: the question or
|
|
7604
|
+
* completion is declined, and the turn becomes a plain "go again" Retry. The model made that
|
|
7605
|
+
* call expecting its writes to land, so it reads the failure and decides again.
|
|
7606
|
+
*
|
|
7607
|
+
* @returns The step to process — `step` itself when nothing failed or it is not terminal
|
|
7608
|
+
*/
|
|
7609
|
+
declineTerminalAfterFailedWrite(step, results) {
|
|
7610
|
+
const terminal = (step.step === 'Success' || step.step === 'Chat') && step.nativeTurn;
|
|
7611
|
+
if (!terminal || !results.some((r) => r.isError && step.agentToolCalls?.some((c) => c.toolCallId === r.toolCallId))) {
|
|
7612
|
+
return step;
|
|
7613
|
+
}
|
|
7614
|
+
const call = step.nativeTurn?.toolCalls.find((c) => {
|
|
7615
|
+
const kind = this._nativeToolBindings?.get(c.name)?.kind;
|
|
7616
|
+
return kind === 'complete' || kind === 'askUser';
|
|
7617
|
+
});
|
|
7618
|
+
if (call?.id) {
|
|
7619
|
+
results.push({
|
|
7620
|
+
toolCallId: call.id, toolName: call.name, isError: true,
|
|
7621
|
+
content: `Not executed. A write on this turn failed (see its result). Fix it, then call ${call.name} again.`
|
|
7622
|
+
});
|
|
7623
|
+
}
|
|
7624
|
+
return {
|
|
7625
|
+
...step, step: 'Retry', terminate: false, payloadToolCallId: undefined,
|
|
7626
|
+
message: undefined, responseForm: undefined, retryInstructions: undefined
|
|
7627
|
+
};
|
|
7628
|
+
}
|
|
6984
7629
|
/** The tool name the model used for a call on this turn — `payload_change_request` when it cannot be found. */
|
|
6985
7630
|
nativeToolNameForCall(step, toolCallId) {
|
|
6986
7631
|
return step.nativeTurn?.toolCalls.find((c) => c.id === toolCallId)?.name ?? 'payload_change_request';
|
|
@@ -7278,7 +7923,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
7278
7923
|
}
|
|
7279
7924
|
if (decision.step === 'Actions' && decision.actions?.length) {
|
|
7280
7925
|
if (!native) {
|
|
7281
|
-
tail.push({ role: 'user', content: this.buildActionInvocationMessage(decision.actions) });
|
|
7926
|
+
tail.push({ role: 'user', content: this.buildActionInvocationMessage(decision.actions, params) });
|
|
7282
7927
|
}
|
|
7283
7928
|
const summaries = this.summarizeStoppedRunActions(decision.actions, tailSteps);
|
|
7284
7929
|
this.appendActionResults(scratch, summaries, this.buildActionResultsMessage(summaries), undefined, decision);
|
|
@@ -8000,6 +8645,20 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
8000
8645
|
`Instead: page it with get_rows(start, count), or run a pipeline that filters/aggregates it ` +
|
|
8001
8646
|
`server-side (where / select / groupBy → only the small final result returns to you).]`);
|
|
8002
8647
|
}
|
|
8648
|
+
/** Where and for whom a memory write lands — shared by the envelope field and the native tool. */
|
|
8649
|
+
memoryWriteOptions(params) {
|
|
8650
|
+
return {
|
|
8651
|
+
agentId: params.agent.ID,
|
|
8652
|
+
contextUser: params.contextUser,
|
|
8653
|
+
agentRunId: this._agentRun?.ID,
|
|
8654
|
+
conversationId: this._agentRun?.ConversationID || undefined,
|
|
8655
|
+
conversationDetailId: params.conversationDetailId,
|
|
8656
|
+
userId: params.userId || params.contextUser?.ID,
|
|
8657
|
+
companyId: params.companyId,
|
|
8658
|
+
verbose: params.verbose,
|
|
8659
|
+
provider: this.ProviderToUse,
|
|
8660
|
+
};
|
|
8661
|
+
}
|
|
8003
8662
|
/**
|
|
8004
8663
|
* Executes a batch of in-flight memory writes, recording each as its own
|
|
8005
8664
|
* `Tool` AIAgentRunStep (a sibling of the Prompt step that requested them)
|
|
@@ -8028,17 +8687,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
8028
8687
|
scopeHint: write.scopeHint,
|
|
8029
8688
|
},
|
|
8030
8689
|
});
|
|
8031
|
-
const result = await this._memoryWriteManager.ExecuteWrite(write,
|
|
8032
|
-
agentId: params.agent.ID,
|
|
8033
|
-
contextUser: params.contextUser,
|
|
8034
|
-
agentRunId: this._agentRun?.ID,
|
|
8035
|
-
conversationId: this._agentRun?.ConversationID || undefined,
|
|
8036
|
-
conversationDetailId: params.conversationDetailId,
|
|
8037
|
-
userId: params.userId || params.contextUser?.ID,
|
|
8038
|
-
companyId: params.companyId,
|
|
8039
|
-
verbose: params.verbose,
|
|
8040
|
-
provider: this.ProviderToUse,
|
|
8041
|
-
});
|
|
8690
|
+
const result = await this._memoryWriteManager.ExecuteWrite(write, this.memoryWriteOptions(params));
|
|
8042
8691
|
const failed = result.disposition === 'error' || result.disposition === 'rejected-type';
|
|
8043
8692
|
await this.finalizeStepEntity(writeStep, !failed, failed ? result.reason : undefined, {
|
|
8044
8693
|
disposition: result.disposition,
|
|
@@ -8118,13 +8767,16 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
8118
8767
|
*/
|
|
8119
8768
|
async skipMemoryWrites(requestedWriteCount, skip, params) {
|
|
8120
8769
|
this.logStatus(`[MemoryWrites] LLM emitted ${requestedWriteCount} memory write(s) but ${skip.Reason} — skipping`, true, params);
|
|
8121
|
-
|
|
8770
|
+
await this.createStepEntity({
|
|
8122
8771
|
stepType: 'Tool',
|
|
8123
8772
|
stepName: `Memory Writes: skipped (${skip.Reason})`,
|
|
8124
8773
|
contextUser: params.contextUser,
|
|
8125
8774
|
inputData: { requestedWriteCount },
|
|
8775
|
+
completed: {
|
|
8776
|
+
success: true,
|
|
8777
|
+
outputData: { skipped: true, reason: skip.Reason }
|
|
8778
|
+
}
|
|
8126
8779
|
});
|
|
8127
|
-
await this.finalizeStepEntity(skipStep, true, undefined, { skipped: true, reason: skip.Reason });
|
|
8128
8780
|
params.conversationMessages.push({
|
|
8129
8781
|
role: 'user',
|
|
8130
8782
|
content: `Memory write result: ${skip.Told} — the requested memories were NOT saved. Do not emit memoryWrites again.`,
|
|
@@ -8756,6 +9408,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
8756
9408
|
return;
|
|
8757
9409
|
const message = {
|
|
8758
9410
|
role: 'user',
|
|
9411
|
+
// fls-guard: decision outcomes, not entity rows
|
|
8759
9412
|
content: `Decision results:\n${JSON.stringify(results)}`,
|
|
8760
9413
|
metadata: {
|
|
8761
9414
|
turnAdded: this._promptTurnCount,
|
|
@@ -8803,7 +9456,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
8803
9456
|
*
|
|
8804
9457
|
* @private
|
|
8805
9458
|
*/
|
|
8806
|
-
async gatherPromptTemplateData(agent, _contextUser, extraData, actionChanges, subAgentChanges, withholding) {
|
|
9459
|
+
async gatherPromptTemplateData(agent, _contextUser, extraData, actionChanges, subAgentChanges, boundActionParams, withholding) {
|
|
8807
9460
|
try {
|
|
8808
9461
|
const engine = AIEngine.Instance;
|
|
8809
9462
|
// Build (or reuse) the agent-invariant base catalog. This is process-wide cached on
|
|
@@ -8840,7 +9493,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
8840
9493
|
const result = this.applyActionChanges([...catalog.baseActionsRaw], actionChanges, agent.ID, isRoot);
|
|
8841
9494
|
activeActions = result.actions.filter(a => a.Status === 'Active');
|
|
8842
9495
|
this._dynamicActionLimits = result.dynamicLimits;
|
|
8843
|
-
actionDetails = this.formatActionDetails(activeActions);
|
|
9496
|
+
actionDetails = this.formatActionDetails(activeActions, boundActionParams);
|
|
8844
9497
|
}
|
|
8845
9498
|
else {
|
|
8846
9499
|
// No actionChanges this step → no dynamically-added actions, hence no dynamic limits.
|
|
@@ -8849,6 +9502,12 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
8849
9502
|
// Resetting to {} is correct and required: it prevents a prior step's actionChanges limits
|
|
8850
9503
|
// from leaking into a step that has none. It is NOT relied upon to persist across steps.
|
|
8851
9504
|
this._dynamicActionLimits = {};
|
|
9505
|
+
// A bound parameter (ExecuteAgentParams.boundActionParams) is left out of the catalog the model
|
|
9506
|
+
// reads. The cached markdown describes every parameter, so a run that binds one on an active
|
|
9507
|
+
// action renders the catalog for itself; a run with no bindings keeps the cached text untouched.
|
|
9508
|
+
if (this.bindsAnyAction(activeActions, boundActionParams)) {
|
|
9509
|
+
actionDetails = this.formatActionDetails(activeActions, boundActionParams);
|
|
9510
|
+
}
|
|
8852
9511
|
}
|
|
8853
9512
|
// Store for later validation in executeActionsStep
|
|
8854
9513
|
this._effectiveActions = activeActions;
|
|
@@ -8870,7 +9529,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
8870
9529
|
}
|
|
8871
9530
|
// A run that withholds task graphs (an audience or a tenant: see taskGraphWithholdingReason) is not offered
|
|
8872
9531
|
// them; a copy, so the cached base is never written. executeTasksStep refuses a graph the model writes anyway.
|
|
8873
|
-
|
|
9532
|
+
// A bound run (ExecuteAgentParams.boundActionParams) is not offered them either: a graph's action
|
|
9533
|
+
// nodes are dispatched outside the binding gate (executeTasksStep refuses one of those too).
|
|
9534
|
+
if (withholding?.TaskGraphs || this.hasBoundActionParams(boundActionParams)) {
|
|
8874
9535
|
agentTypePromptParams = this.withoutTaskGraphs(agentTypePromptParams);
|
|
8875
9536
|
}
|
|
8876
9537
|
// Store for the finishIf gate, which runs after this prompt in executeActionsStep / executeNextStep
|
|
@@ -8891,7 +9552,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
8891
9552
|
// decision judges only skills the policy offers, and an override that skips `super` keeps it.
|
|
8892
9553
|
// The counts stay whole: they are what the model can call, and a narrowed list says what it hides.
|
|
8893
9554
|
await this.ensureCatalogNarrowing(agent, _contextUser, agentTypePromptParams, activeActions, uniqueActiveSubAgents, availableSkills);
|
|
8894
|
-
actionDetails = this.narrowedCatalogSection('action', activeActions, actionDetails, shown => this.formatActionDetails(shown));
|
|
9555
|
+
actionDetails = this.narrowedCatalogSection('action', activeActions, actionDetails, shown => this.formatActionDetails(shown, boundActionParams));
|
|
8895
9556
|
subAgentDetails = this.narrowedCatalogSection('agent', uniqueActiveSubAgents, subAgentDetails, shown => this.formatSubAgentDetails(shown));
|
|
8896
9557
|
const skillsCatalog = this.narrowedCatalogSection('skill', availableSkills, this.formatSkillsCatalog(availableSkills), shown => this.formatSkillsCatalog(shown));
|
|
8897
9558
|
// The client tools and the app context (per-run, from extraData) — neither under an audience (callerContextSections).
|
|
@@ -9867,18 +10528,6 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
9867
10528
|
return key || undefined;
|
|
9868
10529
|
};
|
|
9869
10530
|
}
|
|
9870
|
-
/** The model's arguments as the engine's input parameters. */
|
|
9871
|
-
toEngineActionParams(action, actionEntity) {
|
|
9872
|
-
// Coerced against each param's declared schema on every path — envelope, native and flow —
|
|
9873
|
-
// so `"640"` reaches an integer param as 640 whichever protocol produced it. Harness
|
|
9874
|
-
// stand-ins may build an Action literal without the related-record collection.
|
|
9875
|
-
const coerced = CoerceActionArguments(actionEntity.Params?.Items ?? [], action.params);
|
|
9876
|
-
return Object.entries(coerced).map(([key, value]) => ({
|
|
9877
|
-
Name: key,
|
|
9878
|
-
Value: value,
|
|
9879
|
-
Type: 'Input'
|
|
9880
|
-
}));
|
|
9881
|
-
}
|
|
9882
10531
|
/**
|
|
9883
10532
|
* The action context for one dispatch: the agent's own context object, by reference (do NOT spread —
|
|
9884
10533
|
* spreading destroys class instances, losing getters/methods on typed contexts like SkipAgentContext),
|
|
@@ -9893,6 +10542,12 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
9893
10542
|
// named skill the run never activated. Always stamped — an empty array means "inside an
|
|
9894
10543
|
// agent run, with no skill active", which is a different fact from "no agent at all".
|
|
9895
10544
|
actionContext.ActiveSkillIDs = this.activeSkillIDsForRun(params);
|
|
10545
|
+
// The run's bound parameters, for actions that describe other actions (Find Candidate Actions,
|
|
10546
|
+
// Find Best Action) so they hide the same names the catalog hides. Stamped only when the run
|
|
10547
|
+
// has bindings, so an unbound run's context is unchanged.
|
|
10548
|
+
if (params.boundActionParams) {
|
|
10549
|
+
actionContext.BoundActionParams = params.boundActionParams;
|
|
10550
|
+
}
|
|
9896
10551
|
if (this._resolvedStorageAccountId) {
|
|
9897
10552
|
actionContext.__resolvedStorageAccountId = this._resolvedStorageAccountId;
|
|
9898
10553
|
}
|
|
@@ -9977,11 +10632,17 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
9977
10632
|
* The full ActionResult objects are returned, allowing the caller to access result codes, output parameters,
|
|
9978
10633
|
* and other execution details.
|
|
9979
10634
|
*
|
|
10635
|
+
* The run's bound parameters (`ExecuteAgentParams.boundActionParams`) are applied first: a bound value
|
|
10636
|
+
* replaces whatever the model sent under its name, and a call the bindings refuse (a required parameter
|
|
10637
|
+
* bound to nothing, a binding naming no input of the action) returns a blocked `'fatal'` result without
|
|
10638
|
+
* dispatching and locks the action out for the rest of the run.
|
|
10639
|
+
*
|
|
9980
10640
|
* @param {ExecuteAgentParams} params - Parameters from agent execution for context passing
|
|
9981
10641
|
* @param {AgentAction} action - Action to execute
|
|
9982
10642
|
* @param {UserInfo} [contextUser] - Optional user context for permissions
|
|
9983
10643
|
* @param {ExecuteSingleActionOptions} [options] - `skipCircuitBreaker` bypasses the run-scoped
|
|
9984
|
-
* circuit breaker for callers that do their own failure accounting (the pipeline executor)
|
|
10644
|
+
* circuit breaker for callers that do their own failure accounting (the pipeline executor);
|
|
10645
|
+
* `StepID` names the run step in the audit lines a bound parameter writes
|
|
9985
10646
|
*
|
|
9986
10647
|
* @returns {Promise<ActionResult>} ActionResult object from the action execution
|
|
9987
10648
|
*
|
|
@@ -9989,7 +10650,13 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
9989
10650
|
*/
|
|
9990
10651
|
async ExecuteSingleAction(params, action, actionEntity, contextUser, options) {
|
|
9991
10652
|
const skipBreaker = options?.skipCircuitBreaker === true;
|
|
9992
|
-
|
|
10653
|
+
// Bound parameters first: what the model sent under a bound name is discarded here, and a call
|
|
10654
|
+
// the bindings refuse never reaches the engine; it is locked out for the run instead.
|
|
10655
|
+
const binding = this.applyActionBindings(params, action, actionEntity, options);
|
|
10656
|
+
if (binding.Refusal) {
|
|
10657
|
+
return this.refuseBoundAction(params, action, actionEntity, binding.Refusal, options);
|
|
10658
|
+
}
|
|
10659
|
+
const normalizedParams = this.normalizeActionParams(binding.HasBindings ? binding.Params : action.params);
|
|
9993
10660
|
// Run-scoped circuit breaker: each rule short-circuits in 0ms with a result that carries the
|
|
9994
10661
|
// rule that fired, so the failure directive can name it without consulting the history.
|
|
9995
10662
|
if (!skipBreaker) {
|
|
@@ -10013,7 +10680,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10013
10680
|
// Execute the action and return the full ActionResult
|
|
10014
10681
|
const result = await ActionEngineServer.Instance.RunAction({
|
|
10015
10682
|
Action: actionEntity,
|
|
10016
|
-
Params: this.
|
|
10683
|
+
Params: this.toActionParams(binding, actionEntity),
|
|
10017
10684
|
ContextUser: contextUser,
|
|
10018
10685
|
Filters: [],
|
|
10019
10686
|
SkipActionLog: false,
|
|
@@ -10083,7 +10750,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10083
10750
|
Params: [],
|
|
10084
10751
|
RunParams: {
|
|
10085
10752
|
Action: actionEntity,
|
|
10086
|
-
Params: this.
|
|
10753
|
+
Params: this.toActionParams({ Params: action.params ?? {}, Bound: [] }, actionEntity),
|
|
10087
10754
|
ContextUser: contextUser,
|
|
10088
10755
|
Filters: [],
|
|
10089
10756
|
},
|
|
@@ -10133,8 +10800,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10133
10800
|
if (typed.role === 'assistant' && typed.toolCalls?.length) {
|
|
10134
10801
|
const answered = typed.toolCalls.every((call) => call.id && resolved.has(call.id));
|
|
10135
10802
|
if (!answered) {
|
|
10136
|
-
// Demote to prose rather than send a call this window never answers.
|
|
10137
|
-
|
|
10803
|
+
// Demote to prose rather than send a call this window never answers. Its reasoning
|
|
10804
|
+
// goes too: the signatures were minted for the turn with its calls.
|
|
10805
|
+
const { toolCalls: _dropped, reasoning: _reasoning, ...rest } = typed;
|
|
10138
10806
|
kept.push({ ...rest, content: typed.content || '[tool call omitted for context management]' });
|
|
10139
10807
|
continue;
|
|
10140
10808
|
}
|
|
@@ -10323,6 +10991,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10323
10991
|
treeBudget: this.ensureTreeBudget(params), // propagate shared cumulative root-tree budget to sub-agent
|
|
10324
10992
|
actionChanges: subAgentActionChanges, // propagate filtered action changes to sub-agent
|
|
10325
10993
|
subAgentChanges: subAgentSubAgentChanges, // propagate filtered sub-agent changes to sub-agent
|
|
10994
|
+
boundActionParams: params.boundActionParams, // every sub-agent run keeps the caller's bindings, as it keeps actionChanges
|
|
10326
10995
|
PrimaryScopeEntityName: params.PrimaryScopeEntityName, // propagate scope to sub-agent
|
|
10327
10996
|
PrimaryScopeRecordID: params.PrimaryScopeRecordID,
|
|
10328
10997
|
companyId: params.companyId,
|
|
@@ -10440,21 +11109,26 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10440
11109
|
* Produces ~75% fewer tokens than the previous JSON format while preserving
|
|
10441
11110
|
* all information the LLM needs to invoke actions correctly.
|
|
10442
11111
|
*
|
|
11112
|
+
* A parameter the run binds (`ExecuteAgentParams.boundActionParams`) is left out, so the model is
|
|
11113
|
+
* never told it exists. With no bindings the output is the cached catalog's, unchanged.
|
|
11114
|
+
*
|
|
10443
11115
|
* @param {MJActionEntityExtended[]} actions - Array of action entities
|
|
11116
|
+
* @param {BoundActionParams} [boundActionParams] - The run's bindings, when it has any
|
|
10444
11117
|
* @returns {string} Markdown formatted string with action details
|
|
10445
11118
|
* @private
|
|
10446
11119
|
*/
|
|
10447
|
-
formatActionDetails(actions) {
|
|
11120
|
+
formatActionDetails(actions, boundActionParams) {
|
|
10448
11121
|
return actions.map(action => {
|
|
10449
11122
|
const lines = [];
|
|
10450
11123
|
lines.push(`### ${action.Name}`);
|
|
10451
11124
|
lines.push(action.Description);
|
|
10452
|
-
const
|
|
11125
|
+
const visibleParams = UnboundParams(action.Params.Items, BindingsForAction(boundActionParams, action.ID));
|
|
11126
|
+
const inputParams = visibleParams
|
|
10453
11127
|
.filter(p => {
|
|
10454
11128
|
const t = p.Type.trim().toLowerCase();
|
|
10455
11129
|
return t === 'input' || t === 'both';
|
|
10456
11130
|
});
|
|
10457
|
-
const outputParams =
|
|
11131
|
+
const outputParams = visibleParams
|
|
10458
11132
|
.filter(p => {
|
|
10459
11133
|
const t = p.Type.trim().toLowerCase();
|
|
10460
11134
|
return t === 'output' || t === 'both';
|
|
@@ -10631,23 +11305,25 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10631
11305
|
* like one the loop wrote. See the Actions step for why it is a user-role annotation.
|
|
10632
11306
|
* @protected
|
|
10633
11307
|
*/
|
|
10634
|
-
buildActionInvocationMessage(actions) {
|
|
11308
|
+
buildActionInvocationMessage(actions, params) {
|
|
10635
11309
|
if (actions.length === 1) {
|
|
10636
11310
|
const aa = actions[0];
|
|
10637
|
-
|
|
11311
|
+
const shownParams = this.shownActionParamEntries(params, aa);
|
|
11312
|
+
if (shownParams.length === 0) {
|
|
10638
11313
|
return `[You invoked the **${aa.name}** action.]`;
|
|
10639
11314
|
}
|
|
10640
|
-
const paramsList =
|
|
11315
|
+
const paramsList = shownParams
|
|
10641
11316
|
.map(([key, value]) => `• **${key}**: ${this.formatParamValueForMessage(value)}`)
|
|
10642
11317
|
.join('\n');
|
|
10643
11318
|
return `[You invoked the **${aa.name}** action with parameters:\n${paramsList}\n]`;
|
|
10644
11319
|
}
|
|
10645
11320
|
return `[You invoked **${actions.length} actions** in parallel:\n\n` + actions.map((aa, index) => {
|
|
10646
11321
|
const actionText = `${index + 1}. **${aa.name}**`;
|
|
10647
|
-
|
|
11322
|
+
const shownParams = this.shownActionParamEntries(params, aa);
|
|
11323
|
+
if (shownParams.length === 0) {
|
|
10648
11324
|
return actionText;
|
|
10649
11325
|
}
|
|
10650
|
-
const paramsList =
|
|
11326
|
+
const paramsList = shownParams
|
|
10651
11327
|
.map(([key, value]) => ` • **${key}**: ${this.formatParamValueForMessage(value)}`)
|
|
10652
11328
|
.join('\n');
|
|
10653
11329
|
return `${actionText}\n${paramsList}`;
|
|
@@ -10690,11 +11366,12 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10690
11366
|
const lines = [];
|
|
10691
11367
|
lines.push(`## ${a.actionName} ${marker}`);
|
|
10692
11368
|
lines.push(`**Result:** ${a.resultCode} — ${a.message || '(no message)'}`);
|
|
10693
|
-
// Format output params as bullet list
|
|
11369
|
+
// Format output params as bullet list. An exempt action's values go out verbatim.
|
|
10694
11370
|
if (a.params && a.params.length > 0) {
|
|
11371
|
+
const crush = !this._actionResultCrush?.exemptActions?.has(a.actionName);
|
|
10695
11372
|
lines.push('**Output:**');
|
|
10696
11373
|
for (const p of a.params) {
|
|
10697
|
-
lines.push(`• \`${p.Name}\`: ${this.formatParamValueForResult(p.Value)}`);
|
|
11374
|
+
lines.push(`• \`${p.Name}\`: ${this.formatParamValueForResult(p.Value, 0, crush)}`);
|
|
10698
11375
|
}
|
|
10699
11376
|
}
|
|
10700
11377
|
return lines.join('\n');
|
|
@@ -10752,7 +11429,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10752
11429
|
* @returns Formatted string
|
|
10753
11430
|
* @private
|
|
10754
11431
|
*/
|
|
10755
|
-
formatParamValueForResult(value, maxLength = 0) {
|
|
11432
|
+
formatParamValueForResult(value, maxLength = 0, crush = true) {
|
|
10756
11433
|
if (value === null || value === undefined) {
|
|
10757
11434
|
return '`null`';
|
|
10758
11435
|
}
|
|
@@ -10765,11 +11442,11 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10765
11442
|
// safe no-op on non-JSON (crushParamValue's internal JSON.parse failure is
|
|
10766
11443
|
// caught and returns null) — then opt-in AST code reduction (SQL/TS), then pass
|
|
10767
11444
|
// through (optionally length-capped).
|
|
10768
|
-
const crushedJson = this.crushParamValue(value);
|
|
11445
|
+
const crushedJson = crush ? this.crushParamValue(value) : null;
|
|
10769
11446
|
if (crushedJson !== null) {
|
|
10770
11447
|
return crushedJson;
|
|
10771
11448
|
}
|
|
10772
|
-
const crushedCode = this.crushCodeValue(value);
|
|
11449
|
+
const crushedCode = crush ? this.crushCodeValue(value) : null;
|
|
10773
11450
|
if (crushedCode !== null) {
|
|
10774
11451
|
return crushedCode;
|
|
10775
11452
|
}
|
|
@@ -10778,7 +11455,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10778
11455
|
// Objects/arrays: compact JSON (no pretty-printing), optionally structurally
|
|
10779
11456
|
// compressed via context-crush when crushing is enabled and the value is large.
|
|
10780
11457
|
const stringValue = JSON.stringify(value);
|
|
10781
|
-
const crushed = this.crushParamValue(stringValue);
|
|
11458
|
+
const crushed = crush ? this.crushParamValue(stringValue) : null;
|
|
10782
11459
|
if (crushed !== null) {
|
|
10783
11460
|
return crushed;
|
|
10784
11461
|
}
|
|
@@ -10800,7 +11477,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
10800
11477
|
}
|
|
10801
11478
|
const requestedLang = agentTypePromptParams?.crushCodeLang;
|
|
10802
11479
|
const codeLang = requestedLang === 'sql' || requestedLang === 'typescript' ? requestedLang : undefined;
|
|
10803
|
-
|
|
11480
|
+
const uncrushed = agentTypePromptParams?.uncrushedActions;
|
|
11481
|
+
const exemptActions = new Set(Array.isArray(uncrushed) ? uncrushed.filter((name) => typeof name === 'string') : []);
|
|
11482
|
+
return { threshold: BaseAgent.ACTION_RESULT_CRUSH_THRESHOLD, maxChars: undefined, codeLang, exemptActions };
|
|
10804
11483
|
}
|
|
10805
11484
|
/**
|
|
10806
11485
|
* AST-reduce a large code-string action-result value when the agent opted into a code
|
|
@@ -11144,6 +11823,19 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11144
11823
|
// 0. It has to be recorded on the run itself because the run is the only thing that outlives
|
|
11145
11824
|
// the dispatcher that started it, and the next graph this run submits reads it back.
|
|
11146
11825
|
this._agentRun.ContinuationDepth = params.continuationDepth ?? 0;
|
|
11826
|
+
// Stored so a run that continues this one (lastRunId) applies the same bindings.
|
|
11827
|
+
// Plain JSON.stringify on purpose: a binding that can't be stored must fail the run, not be dropped.
|
|
11828
|
+
// Normalize `undefined` parameter values to `null` so JSON.stringify preserves the bound key
|
|
11829
|
+
// (ApplyBoundActionParams treats `null` and `undefined` identically).
|
|
11830
|
+
if (params.boundActionParams) {
|
|
11831
|
+
const serialized = JSON.stringify(params.boundActionParams, (_key, value) => (value === undefined ? null : value));
|
|
11832
|
+
if (typeof this._agentRun.SetServerBoundActionParams === 'function') {
|
|
11833
|
+
this._agentRun.SetServerBoundActionParams(serialized);
|
|
11834
|
+
}
|
|
11835
|
+
else {
|
|
11836
|
+
this._agentRun.BoundActionParams = serialized;
|
|
11837
|
+
}
|
|
11838
|
+
}
|
|
11147
11839
|
// Set LastRunID for run chaining (different from ParentRunID)
|
|
11148
11840
|
if (params.lastRunId) {
|
|
11149
11841
|
// Check for circular references in the run chain (reusing preloadedLastRun when available)
|
|
@@ -11315,15 +12007,27 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
11315
12007
|
// Original validation logic
|
|
11316
12008
|
const validationResult = await this.validateAgent(agent);
|
|
11317
12009
|
if (validationResult) {
|
|
11318
|
-
// Create validation step
|
|
11319
|
-
|
|
11320
|
-
|
|
11321
|
-
|
|
12010
|
+
// Create pre-completed validation step (single INSERT instead of INSERT + UPDATE)
|
|
12011
|
+
await this.createStepEntity({
|
|
12012
|
+
stepType: 'Validation',
|
|
12013
|
+
stepName: 'Agent Validation',
|
|
12014
|
+
contextUser,
|
|
12015
|
+
completed: {
|
|
12016
|
+
success: false,
|
|
12017
|
+
errorMessage: validationResult.agentRun?.ErrorMessage ?? undefined
|
|
12018
|
+
}
|
|
12019
|
+
});
|
|
11322
12020
|
return await this.createFailureResult(validationResult.agentRun?.ErrorMessage || 'Validation failed', contextUser);
|
|
11323
12021
|
}
|
|
11324
|
-
// Validation successful - create success step
|
|
11325
|
-
|
|
11326
|
-
|
|
12022
|
+
// Validation successful - create pre-completed success step (single INSERT instead of INSERT + UPDATE)
|
|
12023
|
+
await this.createStepEntity({
|
|
12024
|
+
stepType: 'Validation',
|
|
12025
|
+
stepName: 'Agent Validation',
|
|
12026
|
+
contextUser,
|
|
12027
|
+
completed: {
|
|
12028
|
+
success: true
|
|
12029
|
+
}
|
|
12030
|
+
});
|
|
11327
12031
|
return null;
|
|
11328
12032
|
}
|
|
11329
12033
|
catch (error) {
|
|
@@ -12315,16 +13019,68 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12315
13019
|
// don't need to save here, the run will be saved later
|
|
12316
13020
|
}
|
|
12317
13021
|
const promptParams = await this.preparePromptParams(promptConfig, downstreamPayload, params);
|
|
12318
|
-
// Pass cancellation token and streaming callbacks to prompt execution
|
|
13022
|
+
// Pass cancellation token and streaming callbacks to prompt execution.
|
|
13023
|
+
// Coalesce rapid token chunks within a ~35ms window while emitting the first chunk immediately
|
|
13024
|
+
// and flushing synchronously on completion so downstream GraphQL/PubSub/WebSocket callbacks
|
|
13025
|
+
// are not flooded on every single token.
|
|
12319
13026
|
promptParams.cancellationToken = params.cancellationToken;
|
|
13027
|
+
let pendingStreamingChunk = null;
|
|
13028
|
+
let streamingCoalesceTimer = null;
|
|
13029
|
+
let lastStreamingEmitTime = 0;
|
|
13030
|
+
const streamingCoalesceWindowMS = 35;
|
|
13031
|
+
const flushPendingStreamingChunk = () => {
|
|
13032
|
+
if (streamingCoalesceTimer !== null) {
|
|
13033
|
+
clearTimeout(streamingCoalesceTimer);
|
|
13034
|
+
streamingCoalesceTimer = null;
|
|
13035
|
+
}
|
|
13036
|
+
if (pendingStreamingChunk !== null && params.onStreaming) {
|
|
13037
|
+
const toEmit = pendingStreamingChunk;
|
|
13038
|
+
pendingStreamingChunk = null;
|
|
13039
|
+
lastStreamingEmitTime = Date.now();
|
|
13040
|
+
params.onStreaming(toEmit);
|
|
13041
|
+
}
|
|
13042
|
+
};
|
|
12320
13043
|
promptParams.onStreaming = params.onStreaming ? (chunk) => {
|
|
12321
|
-
|
|
12322
|
-
// The server resolver should get the agent run from the closure
|
|
12323
|
-
params.onStreaming({
|
|
13044
|
+
const enrichedChunk = {
|
|
12324
13045
|
...chunk,
|
|
12325
13046
|
stepType: 'prompt',
|
|
12326
13047
|
stepEntityId: stepEntity.ID
|
|
12327
|
-
}
|
|
13048
|
+
};
|
|
13049
|
+
if (chunk.isComplete) {
|
|
13050
|
+
if (pendingStreamingChunk !== null) {
|
|
13051
|
+
enrichedChunk.content = pendingStreamingChunk.content + enrichedChunk.content;
|
|
13052
|
+
pendingStreamingChunk = null;
|
|
13053
|
+
}
|
|
13054
|
+
if (streamingCoalesceTimer !== null) {
|
|
13055
|
+
clearTimeout(streamingCoalesceTimer);
|
|
13056
|
+
streamingCoalesceTimer = null;
|
|
13057
|
+
}
|
|
13058
|
+
lastStreamingEmitTime = Date.now();
|
|
13059
|
+
params.onStreaming(enrichedChunk);
|
|
13060
|
+
return;
|
|
13061
|
+
}
|
|
13062
|
+
const now = Date.now();
|
|
13063
|
+
if (lastStreamingEmitTime === 0 || (pendingStreamingChunk === null && now - lastStreamingEmitTime >= streamingCoalesceWindowMS)) {
|
|
13064
|
+
lastStreamingEmitTime = now;
|
|
13065
|
+
params.onStreaming(enrichedChunk);
|
|
13066
|
+
return;
|
|
13067
|
+
}
|
|
13068
|
+
if (pendingStreamingChunk === null) {
|
|
13069
|
+
pendingStreamingChunk = { ...enrichedChunk };
|
|
13070
|
+
}
|
|
13071
|
+
else {
|
|
13072
|
+
pendingStreamingChunk.content += enrichedChunk.content;
|
|
13073
|
+
if (enrichedChunk.modelName) {
|
|
13074
|
+
pendingStreamingChunk.modelName = enrichedChunk.modelName;
|
|
13075
|
+
}
|
|
13076
|
+
}
|
|
13077
|
+
if (streamingCoalesceTimer === null) {
|
|
13078
|
+
const delay = Math.max(1, streamingCoalesceWindowMS - (now - lastStreamingEmitTime));
|
|
13079
|
+
streamingCoalesceTimer = setTimeout(() => {
|
|
13080
|
+
streamingCoalesceTimer = null;
|
|
13081
|
+
flushPendingStreamingChunk();
|
|
13082
|
+
}, delay);
|
|
13083
|
+
}
|
|
12328
13084
|
} : undefined;
|
|
12329
13085
|
promptParams.onPromptRunCreated = async (promptRunId) => {
|
|
12330
13086
|
stepEntity.TargetLogID = promptRunId;
|
|
@@ -12333,7 +13089,13 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12333
13089
|
this.queueStepSave(stepEntity, (s) => { s.TargetLogID = promptRunId; });
|
|
12334
13090
|
};
|
|
12335
13091
|
// Execute the prompt
|
|
12336
|
-
|
|
13092
|
+
let promptResult;
|
|
13093
|
+
try {
|
|
13094
|
+
promptResult = await this.executePrompt(promptParams);
|
|
13095
|
+
}
|
|
13096
|
+
finally {
|
|
13097
|
+
flushPendingStreamingChunk();
|
|
13098
|
+
}
|
|
12337
13099
|
this.recordPromptUsageInTreeBudget(promptResult.promptRun, promptResult, params);
|
|
12338
13100
|
this.recordToolCallingInstrumentation(stepEntity, promptResult);
|
|
12339
13101
|
// Increment prompt-specific turn counter (used for expiration age calculations)
|
|
@@ -12353,6 +13115,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12353
13115
|
if (promptResult.modelSelectionInfo) {
|
|
12354
13116
|
this._lastModelSelectionInfo = promptResult.modelSelectionInfo;
|
|
12355
13117
|
}
|
|
13118
|
+
this.trackSentPrefix(params, promptResult);
|
|
12356
13119
|
// Check for cancellation after prompt execution — before the failure check, because a prompt
|
|
12357
13120
|
// the caller cancelled comes back failed, and that is not a prompt failure. The step does not
|
|
12358
13121
|
// terminate the loop: a terminating step would finalize the run as Failed. The loop's own
|
|
@@ -12411,7 +13174,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12411
13174
|
displayMode: 'both' // Show in both live and historical modes
|
|
12412
13175
|
});
|
|
12413
13176
|
// Determine next step using agent type, this doesn't validate, just gets the LLM response and then we can process payload changes
|
|
12414
|
-
|
|
13177
|
+
let initialNextStep = await this.determineNextStep(params, config.agentType, promptResult, payload);
|
|
12415
13178
|
// Apply payload changes if provided
|
|
12416
13179
|
const isUnmodifiedInheritedPayload = payload === params.payload;
|
|
12417
13180
|
let finalPayload = (initialNextStep.artifactDirective?.behavior === 'create-new'
|
|
@@ -12457,6 +13220,19 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
12457
13220
|
const payloadCheckParams = promptParams.data?.__agentTypePromptParams;
|
|
12458
13221
|
await this.checkPayloadChangesWhenOn(changeResult, initialNextStep, promptResult, payloadCheckParams, params);
|
|
12459
13222
|
}
|
|
13223
|
+
// Run the agent's own tool calls (zero turn cost — processed inline), in order, after any
|
|
13224
|
+
// same-turn payload_change_request. Their results answer the calls once the call turn is
|
|
13225
|
+
// replayed in processNextStep.
|
|
13226
|
+
this._pendingAgentToolResults = undefined;
|
|
13227
|
+
const declined = (initialNextStep.declinedToolCalls ?? [])
|
|
13228
|
+
.map((d) => ({ toolCallId: d.toolCallId, toolName: d.toolName, content: `Not executed. ${d.reason}`, isError: true }));
|
|
13229
|
+
if (initialNextStep.agentToolCalls?.length || declined.length) {
|
|
13230
|
+
const ran = await this.ExecuteAgentToolCallsAsSteps(initialNextStep.agentToolCalls ?? [], finalPayload, params);
|
|
13231
|
+
finalPayload = ran.payload;
|
|
13232
|
+
const results = [...ran.results, ...declined];
|
|
13233
|
+
initialNextStep = this.declineTerminalAfterFailedWrite(initialNextStep, results);
|
|
13234
|
+
this._pendingAgentToolResults = { results };
|
|
13235
|
+
}
|
|
12460
13236
|
// Apply scratchpad changes if provided (zero turn cost — processed inline)
|
|
12461
13237
|
if (initialNextStep.scratchpad) {
|
|
12462
13238
|
this._scratchpadManager.ApplyScratchpadChanges(initialNextStep.scratchpad);
|
|
@@ -13053,7 +13829,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
13053
13829
|
}
|
|
13054
13830
|
if (previousDecision?.nativeTurn?.sendResultsNatively && subAgentRequest.toolCallId) {
|
|
13055
13831
|
// the delegate_to_* call is answered as a tool result.
|
|
13056
|
-
|
|
13832
|
+
this.PushToolResultTurn(params, BuildToolResultTurn([...this.payloadToolResult(previousDecision), {
|
|
13057
13833
|
toolCallId: subAgentRequest.toolCallId,
|
|
13058
13834
|
toolName: `${SUB_AGENT_TOOL_PREFIX}${SanitizeToolName(subAgentRequest.name)}`,
|
|
13059
13835
|
content: resultMessage,
|
|
@@ -13598,7 +14374,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
13598
14374
|
const pairable = nativeResults ? allExecutions.filter((e) => !!e.request.toolCallId) : [];
|
|
13599
14375
|
const unpairable = allExecutions.filter((e) => !pairable.includes(e));
|
|
13600
14376
|
if (pairable.length > 0) {
|
|
13601
|
-
|
|
14377
|
+
this.PushToolResultTurn(params, BuildToolResultTurn([
|
|
13602
14378
|
...this.payloadToolResult(previousDecision),
|
|
13603
14379
|
...pairable.map((e) => ({
|
|
13604
14380
|
toolCallId: e.request.toolCallId,
|
|
@@ -13849,7 +14625,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
13849
14625
|
}
|
|
13850
14626
|
if (previousDecision.nativeTurn?.sendResultsNatively && subAgentRequest.toolCallId) {
|
|
13851
14627
|
// the delegate_to_* call is answered as a tool result (same as the child path).
|
|
13852
|
-
|
|
14628
|
+
this.PushToolResultTurn(params, BuildToolResultTurn([...this.payloadToolResult(previousDecision), {
|
|
13853
14629
|
toolCallId: subAgentRequest.toolCallId,
|
|
13854
14630
|
toolName: `${SUB_AGENT_TOOL_PREFIX}${SanitizeToolName(subAgentRequest.name)}`,
|
|
13855
14631
|
content: relatedResultMessage,
|
|
@@ -14131,8 +14907,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14131
14907
|
const aa = actions[0];
|
|
14132
14908
|
progressMessage = `Executing **${aa.name}** action`;
|
|
14133
14909
|
// Add parameters if they exist
|
|
14134
|
-
|
|
14135
|
-
|
|
14910
|
+
const shownParams = this.shownActionParamEntries(params, aa);
|
|
14911
|
+
if (shownParams.length > 0) {
|
|
14912
|
+
const paramsList = shownParams
|
|
14136
14913
|
.map(([key, value]) => {
|
|
14137
14914
|
const displayValue = this.formatParamValueForMessage(value);
|
|
14138
14915
|
return `• **${key}**: ${displayValue}`;
|
|
@@ -14148,8 +14925,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14148
14925
|
progressMessage = `Executing **${actions.length} actions** in parallel:\n\n` + actions.map((aa, index) => {
|
|
14149
14926
|
let actionText = `${index + 1}. **${aa.name}**`;
|
|
14150
14927
|
// Add parameters if they exist
|
|
14151
|
-
|
|
14152
|
-
|
|
14928
|
+
const shownParams = this.shownActionParamEntries(params, aa);
|
|
14929
|
+
if (shownParams.length > 0) {
|
|
14930
|
+
const paramsList = shownParams
|
|
14153
14931
|
.map(([key, value]) => {
|
|
14154
14932
|
const displayValue = this.formatParamValueForMessage(value);
|
|
14155
14933
|
return ` • **${key}**: ${displayValue}`;
|
|
@@ -14184,7 +14962,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14184
14962
|
// which (pre-guardrail) looped forever. Phrasing it in second person under the `user`
|
|
14185
14963
|
// role keeps the memory while removing the false assistant-prose exemplar. The
|
|
14186
14964
|
// human-facing narration is emitted separately via onProgress above.
|
|
14187
|
-
const actionMessage = this.buildActionInvocationMessage(actions);
|
|
14965
|
+
const actionMessage = this.buildActionInvocationMessage(actions, params);
|
|
14188
14966
|
if (addConversationMessage) {
|
|
14189
14967
|
// Record as a `user`-role environment annotation (no metadata - permanent record).
|
|
14190
14968
|
// See the note above on why this is NOT an `assistant` turn.
|
|
@@ -14207,7 +14985,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14207
14985
|
// Fall back to database-configured actions if _effectiveActions is empty (shouldn't happen in normal flow)
|
|
14208
14986
|
const effectiveActions = this._effectiveActions.length > 0
|
|
14209
14987
|
? this._effectiveActions
|
|
14210
|
-
: actionEngine.Actions.filter(a => agentActions.some(aa => UUIDsEqual(aa.ActionID, a.ID)));
|
|
14988
|
+
: (actionEngine.Actions || []).filter(a => agentActions.some(aa => UUIDsEqual(aa.ActionID, a.ID)));
|
|
14211
14989
|
// Call agent type's pre-processing for actions
|
|
14212
14990
|
try {
|
|
14213
14991
|
const currentPayload = previousDecision?.newPayload || previousDecision?.previousPayload || params.payload;
|
|
@@ -14224,16 +15002,23 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14224
15002
|
// Execute all actions in parallel
|
|
14225
15003
|
let lastStep = undefined;
|
|
14226
15004
|
const actionPromises = actions.map(async (aa) => {
|
|
14227
|
-
// Find action entity from the effective actions (which includes runtime changes)
|
|
14228
|
-
|
|
15005
|
+
// Find action entity from the effective actions (which includes runtime changes),
|
|
15006
|
+
// or from actions referenced directly by this agent's Flow steps (AIAgentStep.ActionID)
|
|
15007
|
+
let actionEntity = effectiveActions.find(a => a.Name === aa.name);
|
|
15008
|
+
if (!actionEntity && Array.isArray(actionEngine?.Actions)) {
|
|
15009
|
+
const agentSteps = AIEngine.Instance.GetAgentSteps?.(params.agent.ID) || [];
|
|
15010
|
+
const stepActionIds = new UUIDSet(agentSteps.map(s => s.ActionID));
|
|
15011
|
+
actionEntity = actionEngine.Actions.find(a => a.Name === aa.name && stepActionIds.Has(a.ID));
|
|
15012
|
+
}
|
|
14229
15013
|
if (!actionEntity) {
|
|
14230
15014
|
throw new Error(`Action "${aa.name}" Not Found for Agent "${params.agent.Name}". Available actions: ${effectiveActions.map(a => a.Name).join(', ')}`);
|
|
14231
15015
|
}
|
|
14232
|
-
// Prepare input data for the action step
|
|
14233
|
-
|
|
14234
|
-
|
|
14235
|
-
|
|
14236
|
-
|
|
15016
|
+
// Prepare input data for the action step. The names this run binds on the action are
|
|
15017
|
+
// recorded with it, so a step audit tells a bound value from a chosen one on its own.
|
|
15018
|
+
const boundNames = Object.keys(BindingsForAction(params.boundActionParams, actionEntity.ID) ?? {});
|
|
15019
|
+
const actionInputData = boundNames.length > 0
|
|
15020
|
+
? { actionName: aa.name, actionParams: aa.params, boundParams: boundNames }
|
|
15021
|
+
: { actionName: aa.name, actionParams: aa.params };
|
|
14237
15022
|
const stepEntity = await this.createStepEntity({ stepType: 'Actions', stepName: `Execute Action: ${aa.name}`, contextUser: params.contextUser, targetId: actionEntity.ID, inputData: actionInputData, payloadAtStart: currentPayload, payloadAtEnd: currentPayload, parentId: parentStepId, skills: this.getSkillAttributionForAction(actionEntity.ID, params.agent) });
|
|
14238
15023
|
lastStep = stepEntity;
|
|
14239
15024
|
// Override step number to ensure unique values for parallel actions
|
|
@@ -14243,7 +15028,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14243
15028
|
let actionResult;
|
|
14244
15029
|
try {
|
|
14245
15030
|
// Execute the action
|
|
14246
|
-
actionResult = await this.ExecuteSingleAction(params, aa, actionEntity, params.contextUser, actionOptions);
|
|
15031
|
+
actionResult = await this.ExecuteSingleAction(params, aa, actionEntity, params.contextUser, { ...actionOptions, StepID: stepEntity.ID });
|
|
14247
15032
|
// Update step entity with ActionExecutionLog ID if available
|
|
14248
15033
|
if (actionResult.LogEntry?.ID) {
|
|
14249
15034
|
const logId = actionResult.LogEntry.ID;
|
|
@@ -14281,8 +15066,10 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14281
15066
|
const actionSummaries = actionResults.map(result => {
|
|
14282
15067
|
const actionResult = result.result;
|
|
14283
15068
|
const isActionSuccess = Boolean(result.success && (actionResult ? actionResult.Success : true));
|
|
14284
|
-
// Filter to output params only
|
|
14285
|
-
|
|
15069
|
+
// Filter to output params only. A bound parameter (ExecuteAgentParams.boundActionParams) is
|
|
15070
|
+
// left out as well: the model was not shown it on the way in, so it is not shown it on the way out.
|
|
15071
|
+
const bindings = BindingsForAction(params.boundActionParams, result.actionEntity?.ID ?? '');
|
|
15072
|
+
const outputParams = actionResult?.Params?.filter(p => (p.Type === 'Both' || p.Type === 'Output') && !IsBoundParamName(p.Name, bindings)) || [];
|
|
14286
15073
|
// Intercept large media content (images, audio, video) and replace with placeholders
|
|
14287
15074
|
// This prevents context overflow from base64 data (~700K tokens per 1024x1024 image)
|
|
14288
15075
|
// Pass actionEntity for generic ValueType=MediaOutput detection from metadata
|
|
@@ -14344,7 +15131,14 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14344
15131
|
}
|
|
14345
15132
|
if (addConversationMessage) {
|
|
14346
15133
|
// Add user message with results and optional metadata
|
|
14347
|
-
|
|
15134
|
+
// Failure guidance, so the model does not repeatedly loop on broken tools. Not when the breaker
|
|
15135
|
+
// is bypassed for this step: there is then no model in the loop to act on it (Flow, ForEach,
|
|
15136
|
+
// While, pipeline), and the directive would only pollute the history.
|
|
15137
|
+
const failureGuidance = failedActions.length > 0 && actionOptions?.skipCircuitBreaker !== true
|
|
15138
|
+
? new Map(failedActions.map((f) => [f, this.formatActionFailureDirective(f)]))
|
|
15139
|
+
: undefined;
|
|
15140
|
+
// results as a tool turn or the markdown user message; a natively answered failure carries its guidance
|
|
15141
|
+
const answeredNatively = this.appendActionResults(params, actionSummaries, resultsMessage, metadata, previousDecision, failureGuidance);
|
|
14348
15142
|
// Surface explicit AI directives from action results as a separate instruction message.
|
|
14349
15143
|
// Actions that need the AI to follow specific instructions (not just acknowledge data)
|
|
14350
15144
|
// populate AIDirectives on their ActionResultSimple return value.
|
|
@@ -14360,11 +15154,10 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14360
15154
|
content: `IMPORTANT — Follow these directives from the action results:\n\n${directiveText}`
|
|
14361
15155
|
});
|
|
14362
15156
|
}
|
|
14363
|
-
//
|
|
14364
|
-
|
|
14365
|
-
|
|
14366
|
-
|
|
14367
|
-
const failureText = failedActions.map(f => this.formatActionFailureDirective(f)).join('\n\n');
|
|
15157
|
+
// Guidance for any failure not answered as a native tool result goes in a message of its own.
|
|
15158
|
+
const unanswered = failureGuidance ? failedActions.filter((f) => !answeredNatively.has(f)) : [];
|
|
15159
|
+
if (failureGuidance && unanswered.length > 0) {
|
|
15160
|
+
const failureText = unanswered.map((f) => failureGuidance.get(f)).join('\n\n');
|
|
14368
15161
|
params.conversationMessages.push({
|
|
14369
15162
|
role: 'user',
|
|
14370
15163
|
content: `IMPORTANT — Action Execution Failure Guidance:\n\n${failureText}`
|
|
@@ -15063,7 +15856,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15063
15856
|
* @protected
|
|
15064
15857
|
*/
|
|
15065
15858
|
async recordSkillActivationStep(skill, currentPayload, params, invocation) {
|
|
15066
|
-
|
|
15859
|
+
await this.createStepEntity({
|
|
15067
15860
|
stepType: 'Skill',
|
|
15068
15861
|
stepName: `Skill: ${skill.Name}`,
|
|
15069
15862
|
targetId: skill.ID,
|
|
@@ -15071,16 +15864,19 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15071
15864
|
contextUser: params.contextUser,
|
|
15072
15865
|
payloadAtStart: currentPayload,
|
|
15073
15866
|
payloadAtEnd: currentPayload,
|
|
15074
|
-
...(invocation ? { skills: [invocation] } : {})
|
|
15075
|
-
|
|
15076
|
-
|
|
15077
|
-
|
|
15078
|
-
|
|
15079
|
-
|
|
15080
|
-
|
|
15081
|
-
|
|
15082
|
-
|
|
15083
|
-
|
|
15867
|
+
...(invocation ? { skills: [invocation] } : {}),
|
|
15868
|
+
completed: {
|
|
15869
|
+
success: true,
|
|
15870
|
+
outputData: {
|
|
15871
|
+
skillId: skill.ID,
|
|
15872
|
+
skillName: skill.Name,
|
|
15873
|
+
...(invocation ? {
|
|
15874
|
+
activationType: invocation.ActivationType,
|
|
15875
|
+
requestedBy: invocation.Provenance.RequestedBy,
|
|
15876
|
+
...(invocation.Reason ? { reason: invocation.Reason } : {})
|
|
15877
|
+
} : {})
|
|
15878
|
+
}
|
|
15879
|
+
}
|
|
15084
15880
|
});
|
|
15085
15881
|
}
|
|
15086
15882
|
/**
|
|
@@ -15135,6 +15931,19 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15135
15931
|
newPayload: previousDecision.newPayload || previousDecision.previousPayload
|
|
15136
15932
|
};
|
|
15137
15933
|
}
|
|
15934
|
+
// Fail closed under bound parameters (ExecuteAgentParams.boundActionParams): a graph's action nodes
|
|
15935
|
+
// are dispatched by the task-graph runner with the inputs the model authored, outside
|
|
15936
|
+
// ExecuteSingleAction, so nothing would hide or apply a binding. The response type already withholds
|
|
15937
|
+
// `tasks` from a bound run; this is the gate for a model that emits one anyway.
|
|
15938
|
+
if (this.hasBoundActionParams(params.boundActionParams)) {
|
|
15939
|
+
return {
|
|
15940
|
+
step: 'Failed',
|
|
15941
|
+
terminate: true,
|
|
15942
|
+
errorMessage: 'Task graphs are not available in a run with bound action parameters: a graph dispatches actions outside the binding gate.',
|
|
15943
|
+
previousPayload: previousDecision.previousPayload,
|
|
15944
|
+
newPayload: previousDecision.newPayload || previousDecision.previousPayload
|
|
15945
|
+
};
|
|
15946
|
+
}
|
|
15138
15947
|
// Fail closed under an audience or a tenant-scoped run (taskGraphRefusal): a graph runs outside the run's gates.
|
|
15139
15948
|
const withheld = this.taskGraphRefusal(params, previousDecision);
|
|
15140
15949
|
if (withheld) {
|
|
@@ -15226,17 +16035,20 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15226
16035
|
const graph = nextStep.taskGraph;
|
|
15227
16036
|
if (!graph?.folded)
|
|
15228
16037
|
return;
|
|
15229
|
-
|
|
16038
|
+
await this.createStepEntity({
|
|
15230
16039
|
stepType: 'TaskGraph',
|
|
15231
16040
|
stepName: `Task Graph (folded): ${graph.spec.workflowName}`,
|
|
15232
16041
|
contextUser: params.contextUser,
|
|
15233
|
-
inputData: { spec: graph.spec, folded: true, foldReason: graph.foldReason }
|
|
15234
|
-
|
|
15235
|
-
|
|
15236
|
-
|
|
15237
|
-
|
|
15238
|
-
|
|
15239
|
-
|
|
16042
|
+
inputData: { spec: graph.spec, folded: true, foldReason: graph.foldReason },
|
|
16043
|
+
completed: {
|
|
16044
|
+
success: true,
|
|
16045
|
+
outputData: {
|
|
16046
|
+
spec: graph.spec,
|
|
16047
|
+
folded: true,
|
|
16048
|
+
foldReason: graph.foldReason,
|
|
16049
|
+
submitted: false
|
|
16050
|
+
}
|
|
16051
|
+
}
|
|
15240
16052
|
});
|
|
15241
16053
|
}
|
|
15242
16054
|
async executePlanStep(params, previousDecision) {
|
|
@@ -15245,9 +16057,12 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15245
16057
|
stepType: 'Plan',
|
|
15246
16058
|
stepName: 'Plan Presented for Approval',
|
|
15247
16059
|
contextUser: params.contextUser,
|
|
15248
|
-
inputData: { plan: planText }
|
|
16060
|
+
inputData: { plan: planText },
|
|
16061
|
+
completed: {
|
|
16062
|
+
success: true,
|
|
16063
|
+
outputData: { plan: planText }
|
|
16064
|
+
}
|
|
15249
16065
|
});
|
|
15250
|
-
await this.finalizeStepEntity(stepEntity, true, undefined, { plan: planText });
|
|
15251
16066
|
const responseForm = this.buildPlanApprovalForm(planText);
|
|
15252
16067
|
const planPresentation = {
|
|
15253
16068
|
step: 'Plan',
|
|
@@ -15323,9 +16138,15 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15323
16138
|
};
|
|
15324
16139
|
}
|
|
15325
16140
|
async executeChatStep(params, previousDecision) {
|
|
15326
|
-
|
|
15327
|
-
|
|
15328
|
-
|
|
16141
|
+
// Chat steps are successful immediately — record in a single INSERT instead of INSERT + UPDATE
|
|
16142
|
+
const stepEntity = await this.createStepEntity({
|
|
16143
|
+
stepType: 'Chat',
|
|
16144
|
+
stepName: 'User Interaction',
|
|
16145
|
+
contextUser: params.contextUser,
|
|
16146
|
+
completed: {
|
|
16147
|
+
success: true
|
|
16148
|
+
}
|
|
16149
|
+
});
|
|
15329
16150
|
// For root agents, create a persistent AIAgentRequest so the request is
|
|
15330
16151
|
// tracked in the dashboard and can be responded to outside a conversation (none under an audience).
|
|
15331
16152
|
await this.raiseFeedbackRequest(params, stepEntity, previousDecision);
|
|
@@ -15439,9 +16260,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15439
16260
|
if (categoryStrategy) {
|
|
15440
16261
|
return categoryStrategy;
|
|
15441
16262
|
}
|
|
15442
|
-
// 4. Request Type's DefaultAssignmentStrategy
|
|
15443
|
-
if (requestTypeId
|
|
15444
|
-
const requestType =
|
|
16263
|
+
// 4. Request Type's DefaultAssignmentStrategy (request types are cached on the AI engine)
|
|
16264
|
+
if (requestTypeId) {
|
|
16265
|
+
const requestType = AIEngine.Instance.AgentRequestTypes.find(t => UUIDsEqual(t.ID, requestTypeId));
|
|
15445
16266
|
if (requestType) {
|
|
15446
16267
|
const rtStrategy = parseAssignmentStrategy(requestType.DefaultAssignmentStrategy);
|
|
15447
16268
|
if (rtStrategy) {
|
|
@@ -15536,24 +16357,24 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
15536
16357
|
return params.contextUser?.ID ?? null;
|
|
15537
16358
|
}
|
|
15538
16359
|
}
|
|
16360
|
+
/**
|
|
16361
|
+
* Determines the request type ID based on the Chat step's context.
|
|
16362
|
+
* - If the responseForm has only approve/reject-style buttons, uses "Approval"
|
|
16363
|
+
* - If there's a responseForm with fields, uses "Information"
|
|
16364
|
+
* - Otherwise defaults to "Information"
|
|
16365
|
+
*
|
|
16366
|
+
* Request types come from the AI engine's cached `MJ: AI Agent Request Types` rows
|
|
16367
|
+
* (`AIEngineBase.ResolveAgentRequestTypeID`), the same source the agent actions use.
|
|
16368
|
+
* @private
|
|
16369
|
+
*/
|
|
15539
16370
|
async resolveRequestTypeId(previousDecision, contextUser) {
|
|
15540
16371
|
try {
|
|
15541
|
-
// Load request types if not cached
|
|
15542
|
-
if (!this._requestTypeCache) {
|
|
15543
|
-
const rv = new RunView();
|
|
15544
|
-
const result = await rv.RunView({
|
|
15545
|
-
EntityName: 'MJ: AI Agent Request Types',
|
|
15546
|
-
ResultType: 'entity_object'
|
|
15547
|
-
}, contextUser);
|
|
15548
|
-
this._requestTypeCache = result.Success ? result.Results : [];
|
|
15549
|
-
}
|
|
15550
16372
|
// Determine type name based on responseForm content
|
|
15551
16373
|
let typeName = 'Information'; // default
|
|
15552
16374
|
if (previousDecision.responseForm) {
|
|
15553
16375
|
typeName = this.detectRequestTypeName(previousDecision.responseForm);
|
|
15554
16376
|
}
|
|
15555
|
-
|
|
15556
|
-
return matchedType?.ID || null;
|
|
16377
|
+
return await AIEngine.Instance.ResolveAgentRequestTypeID(typeName, contextUser);
|
|
15557
16378
|
}
|
|
15558
16379
|
catch (error) {
|
|
15559
16380
|
LogError(`Error resolving request type: ${error.message}`);
|
|
@@ -16292,6 +17113,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16292
17113
|
// Calculate total tokens even for failed runs
|
|
16293
17114
|
this.applyTokenStatsToRun(this._agentRun, this.calculateTokenStats());
|
|
16294
17115
|
await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
|
|
17116
|
+
AgentRunWatchdog.Instance.Untrack(this._agentRun.ID);
|
|
16295
17117
|
}
|
|
16296
17118
|
return {
|
|
16297
17119
|
success: false,
|
|
@@ -16466,6 +17288,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16466
17288
|
// Calculate total tokens from all prompts and sub-agents
|
|
16467
17289
|
this.applyTokenStatsToRun(this._agentRun, this.calculateTokenStats());
|
|
16468
17290
|
const ok = await this._agentRun.Save({ SaveReturnMode: 'datestamps_only' });
|
|
17291
|
+
AgentRunWatchdog.Instance.Untrack(this._agentRun.ID);
|
|
16469
17292
|
if (!ok) {
|
|
16470
17293
|
LogError(`Failed to finalize agent run ${this._agentRun.ID}`);
|
|
16471
17294
|
}
|
|
@@ -16728,8 +17551,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16728
17551
|
});
|
|
16729
17552
|
}
|
|
16730
17553
|
else if (msg.metadata.expirationMode === 'Compact') {
|
|
16731
|
-
//
|
|
16732
|
-
|
|
17554
|
+
// Compacted once is compacted: compacting again would summarize the summary, and
|
|
17555
|
+
// change the message again on every turn. Expansion clears the flag.
|
|
17556
|
+
if (msg.metadata.compactMode && !msg.metadata.wasCompacted) {
|
|
16733
17557
|
messagesToCompact.push({
|
|
16734
17558
|
index: i,
|
|
16735
17559
|
message: msg,
|
|
@@ -16751,9 +17575,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
16751
17575
|
for (const item of messagesToCompact) {
|
|
16752
17576
|
const originalContent = item.message.content;
|
|
16753
17577
|
if (item.message.role === 'tool') {
|
|
16754
|
-
//
|
|
16755
|
-
|
|
16756
|
-
const compactedTurn =
|
|
17578
|
+
// Compact per block, in the action's own mode (first N chars or an AI summary), so
|
|
17579
|
+
// the tool turn keeps answering its call.
|
|
17580
|
+
const compactedTurn = await CompactToolResultContentAsync(item.message, (text) => this.compactMessage({ ...item.message, content: text }, { ...item.metadata, originalLength: text.length }, params));
|
|
16757
17581
|
const saved = this.estimateTokens(originalContent) - this.estimateTokens(compactedTurn.content);
|
|
16758
17582
|
params.conversationMessages[item.index] = {
|
|
16759
17583
|
...compactedTurn,
|
|
@@ -17362,7 +18186,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
17362
18186
|
return originalContent; // Already short enough
|
|
17363
18187
|
}
|
|
17364
18188
|
const truncated = originalContent.substring(0, length);
|
|
17365
|
-
|
|
18189
|
+
// A native-only agent has no message expansion, so its tool results do not offer it.
|
|
18190
|
+
const expandable = !(message.role === 'tool' && this.GetNativeControlConfig(params).NativeOnly);
|
|
18191
|
+
return `${truncated}...\n\n[Compacted: showing first ${length} of ${originalContent.length} characters.${expandable ? ' Agent can request expansion if needed.' : ''}]`;
|
|
17366
18192
|
}
|
|
17367
18193
|
case 'AI Summary': {
|
|
17368
18194
|
try {
|