@memberjunction/ai-agents 3.4.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/AgentDataPreloader.d.ts +117 -1
- package/dist/AgentDataPreloader.d.ts.map +1 -1
- package/dist/AgentDataPreloader.js +156 -58
- package/dist/AgentDataPreloader.js.map +1 -1
- package/dist/AgentRunner.d.ts +212 -0
- package/dist/AgentRunner.d.ts.map +1 -1
- package/dist/AgentRunner.js +354 -103
- package/dist/AgentRunner.js.map +1 -1
- package/dist/PayloadChangeAnalyzer.d.ts +68 -0
- package/dist/PayloadChangeAnalyzer.d.ts.map +1 -1
- package/dist/PayloadChangeAnalyzer.js +68 -32
- package/dist/PayloadChangeAnalyzer.js.map +1 -1
- package/dist/PayloadFeedbackManager.d.ts +57 -1
- package/dist/PayloadFeedbackManager.d.ts.map +1 -1
- package/dist/PayloadFeedbackManager.js +66 -21
- package/dist/PayloadFeedbackManager.js.map +1 -1
- package/dist/PayloadManager.d.ts +286 -1
- package/dist/PayloadManager.d.ts.map +1 -1
- package/dist/PayloadManager.js +423 -50
- package/dist/PayloadManager.js.map +1 -1
- package/dist/__tests__/action-changes.test.d.ts +13 -0
- package/dist/__tests__/action-changes.test.d.ts.map +1 -1
- package/dist/__tests__/action-changes.test.js +57 -4
- package/dist/__tests__/action-changes.test.js.map +1 -1
- package/dist/__tests__/agent-memory-features.test.d.ts +52 -0
- package/dist/__tests__/agent-memory-features.test.d.ts.map +1 -1
- package/dist/__tests__/agent-memory-features.test.js +96 -13
- package/dist/__tests__/agent-memory-features.test.js.map +1 -1
- package/dist/__tests__/agent-type-prompt-params.test.d.ts +12 -0
- package/dist/__tests__/agent-type-prompt-params.test.d.ts.map +1 -1
- package/dist/__tests__/agent-type-prompt-params.test.js +112 -20
- package/dist/__tests__/agent-type-prompt-params.test.js.map +1 -1
- package/dist/__tests__/chat-handling-option.test.d.ts +26 -0
- package/dist/__tests__/chat-handling-option.test.d.ts.map +1 -1
- package/dist/__tests__/chat-handling-option.test.js +41 -2
- package/dist/__tests__/chat-handling-option.test.js.map +1 -1
- package/dist/agent-context-injector.d.ts +114 -0
- package/dist/agent-context-injector.d.ts.map +1 -1
- package/dist/agent-context-injector.js +138 -19
- package/dist/agent-context-injector.js.map +1 -1
- package/dist/agent-types/base-agent-type.d.ts +354 -0
- package/dist/agent-types/base-agent-type.d.ts.map +1 -1
- package/dist/agent-types/base-agent-type.js +288 -17
- package/dist/agent-types/base-agent-type.js.map +1 -1
- package/dist/agent-types/flow-agent-type.d.ts +328 -2
- package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
- package/dist/agent-types/flow-agent-type.js +503 -63
- package/dist/agent-types/flow-agent-type.js.map +1 -1
- package/dist/agent-types/index.d.ts +14 -3
- package/dist/agent-types/index.d.ts.map +1 -1
- package/dist/agent-types/index.js +14 -23
- package/dist/agent-types/index.js.map +1 -1
- package/dist/agent-types/loop-agent-prompt-params.d.ts +190 -0
- package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-prompt-params.js +23 -6
- package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
- package/dist/agent-types/loop-agent-response-type.d.ts +62 -0
- package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-response-type.js +3 -2
- package/dist/agent-types/loop-agent-response-type.js.map +1 -1
- package/dist/agent-types/loop-agent-type.d.ts +139 -2
- package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-type.js +207 -35
- package/dist/agent-types/loop-agent-type.js.map +1 -1
- package/dist/base-agent.d.ts +1344 -1
- package/dist/base-agent.d.ts.map +1 -1
- package/dist/base-agent.js +2282 -211
- package/dist/base-agent.js.map +1 -1
- package/dist/index.d.ts +24 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +25 -35
- package/dist/index.js.map +1 -1
- package/dist/memory-cleanup-agent.d.ts +53 -1
- package/dist/memory-cleanup-agent.d.ts.map +1 -1
- package/dist/memory-cleanup-agent.js +89 -21
- package/dist/memory-cleanup-agent.js.map +1 -1
- package/dist/memory-manager-agent.d.ts +61 -1
- package/dist/memory-manager-agent.d.ts.map +1 -1
- package/dist/memory-manager-agent.js +260 -116
- package/dist/memory-manager-agent.js.map +1 -1
- package/dist/services/AgentEmbeddingService.d.ts +16 -0
- package/dist/services/AgentEmbeddingService.d.ts.map +1 -0
- package/dist/services/AgentEmbeddingService.js +158 -0
- package/dist/services/AgentEmbeddingService.js.map +1 -0
- package/dist/types/AgentMatchResult.d.ts +18 -0
- package/dist/types/AgentMatchResult.d.ts.map +1 -0
- package/dist/types/AgentMatchResult.js +3 -0
- package/dist/types/AgentMatchResult.js.map +1 -0
- package/dist/types/payload-operations.d.ts +51 -0
- package/dist/types/payload-operations.d.ts.map +1 -1
- package/dist/types/payload-operations.js +54 -15
- package/dist/types/payload-operations.js.map +1 -1
- package/dist/utils/ConversationMessageResolver.d.ts +79 -1
- package/dist/utils/ConversationMessageResolver.d.ts.map +1 -1
- package/dist/utils/ConversationMessageResolver.js +99 -9
- package/dist/utils/ConversationMessageResolver.js.map +1 -1
- package/package.json +20 -19
package/dist/base-agent.d.ts
CHANGED
|
@@ -1,48 +1,345 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Base implementation of the MemberJunction AI Agent framework.
|
|
3
|
+
*
|
|
4
|
+
* This module provides the core BaseAgent class that handles agent execution
|
|
5
|
+
* using a hierarchical prompt system. Agents use their type's system prompt
|
|
6
|
+
* as a parent prompt and their own configured prompts as child prompts,
|
|
7
|
+
* enabling sophisticated agent behaviors through prompt composition.
|
|
8
|
+
*
|
|
9
|
+
* @module @memberjunction/ai-agents
|
|
10
|
+
* @author MemberJunction.com
|
|
11
|
+
* @since 2.49.0
|
|
12
|
+
*/
|
|
1
13
|
import { AIAgentTypeEntity, TemplateParamEntity, AIAgentNoteEntity, AIAgentExampleEntity } from '@memberjunction/core-entities';
|
|
2
14
|
import { AIAgentRunEntityExtended, AIAgentRunStepEntityExtended, AIPromptEntityExtended, AIAgentEntityExtended } from "@memberjunction/ai-core-plus";
|
|
3
15
|
import { UserInfo } from '@memberjunction/core';
|
|
4
16
|
import { ChatMessage, ChatMessageContent } from '@memberjunction/ai';
|
|
5
|
-
import { BaseAgentType } from './agent-types/base-agent-type';
|
|
17
|
+
import { BaseAgentType } from './agent-types/base-agent-type.js';
|
|
6
18
|
import { AIPromptParams, AIPromptRunResult, ExecuteAgentParams, AgentConfiguration, ExecuteAgentResult, AgentAction, AgentSubAgentRequest, BaseAgentNextStep, MessageLifecycleEvent, AgentChatMessage, AIModelSelectionInfo, ActionChange, ActionChangeScope, MediaOutput } from '@memberjunction/ai-core-plus';
|
|
7
19
|
import { ActionEntityExtended, ActionResult } from '@memberjunction/actions-base';
|
|
20
|
+
/**
|
|
21
|
+
* Base implementation for AI Agents in the MemberJunction framework.
|
|
22
|
+
*
|
|
23
|
+
* The BaseAgent class provides the core execution logic for AI agents using
|
|
24
|
+
* a hierarchical prompt system. It implements the following workflow:
|
|
25
|
+
*
|
|
26
|
+
* 1. Loads the agent's type to get the system prompt configuration
|
|
27
|
+
* 2. Validates that the agent type has a properly configured placeholder
|
|
28
|
+
* 3. Loads the agent's first active prompt (ordered by ExecutionOrder)
|
|
29
|
+
* 4. Gathers context data including sub-agents and available actions
|
|
30
|
+
* 5. Executes the prompts hierarchically (system prompt as parent, agent prompt as child)
|
|
31
|
+
* 6. Uses the agent type to determine the next step based on execution results
|
|
32
|
+
*
|
|
33
|
+
* @class BaseAgent
|
|
34
|
+
* @example
|
|
35
|
+
* ```typescript
|
|
36
|
+
* // Using with default context type (any)
|
|
37
|
+
* const agent = new BaseAgent();
|
|
38
|
+
* const result = await agent.Execute({
|
|
39
|
+
* agent: myAgentEntity,
|
|
40
|
+
* conversationMessages: messages,
|
|
41
|
+
* contextUser: currentUser
|
|
42
|
+
* });
|
|
43
|
+
*
|
|
44
|
+
* // Using with typed context through ExecuteAgentParams
|
|
45
|
+
* interface MyContext {
|
|
46
|
+
* apiKey: string;
|
|
47
|
+
* environment: 'dev' | 'prod';
|
|
48
|
+
* }
|
|
49
|
+
*
|
|
50
|
+
* const agent = new BaseAgent();
|
|
51
|
+
* const params: ExecuteAgentParams<MyContext> = {
|
|
52
|
+
* agent: myAgentEntity,
|
|
53
|
+
* conversationMessages: messages,
|
|
54
|
+
* contextUser: currentUser,
|
|
55
|
+
* context: {
|
|
56
|
+
* apiKey: 'abc123',
|
|
57
|
+
* environment: 'prod'
|
|
58
|
+
* }
|
|
59
|
+
* };
|
|
60
|
+
* const result = await agent.Execute(params);
|
|
61
|
+
* ```
|
|
62
|
+
*/
|
|
8
63
|
export declare class BaseAgent {
|
|
64
|
+
/**
|
|
65
|
+
* Maximum allowed validation retries before forcing failure.
|
|
66
|
+
* @private
|
|
67
|
+
*/
|
|
9
68
|
private static readonly MAX_VALIDATION_RETRIES;
|
|
69
|
+
/**
|
|
70
|
+
* Instance of AIPromptRunner used for executing hierarchical prompts.
|
|
71
|
+
* @private
|
|
72
|
+
*/
|
|
10
73
|
private _promptRunner;
|
|
74
|
+
/**
|
|
75
|
+
* Metadata instance for creating entity objects.
|
|
76
|
+
* @private
|
|
77
|
+
*/
|
|
11
78
|
private _metadata;
|
|
79
|
+
/**
|
|
80
|
+
* This is state information that is specific to the agent type. BaseAgent doesn't know what
|
|
81
|
+
* this contains or care, it is just responsible for keeping this, giving the Agent Type the
|
|
82
|
+
* opportunity to initialize its state when a run starts, and passing the object along each
|
|
83
|
+
* time the Agent Type is called to do something such as DetermineNextStep()
|
|
84
|
+
*/
|
|
12
85
|
private _agentTypeState;
|
|
86
|
+
/**
|
|
87
|
+
* Overridable accessor for the current agent instance's agent-type state
|
|
88
|
+
*/
|
|
13
89
|
protected get AgentTypeState(): any;
|
|
14
90
|
private _agentTypeInstance;
|
|
91
|
+
/**
|
|
92
|
+
* Accessor for the agent's type instance
|
|
93
|
+
*/
|
|
15
94
|
get AgentTypeInstance(): BaseAgentType;
|
|
95
|
+
/**
|
|
96
|
+
* Map to track execution counts for actions and sub-agents.
|
|
97
|
+
* Key is the item ID (action ID or sub-agent ID), value is the count.
|
|
98
|
+
* @private
|
|
99
|
+
*/
|
|
16
100
|
private _executionCounts;
|
|
101
|
+
/**
|
|
102
|
+
* Callback for message lifecycle events (expiration, compaction, removal, expansion).
|
|
103
|
+
* @private
|
|
104
|
+
*/
|
|
17
105
|
private _messageLifecycleCallback;
|
|
106
|
+
/**
|
|
107
|
+
* Counter for validation-induced retries (when validation changes a step to Retry).
|
|
108
|
+
* This is separate from FinalPayloadValidation retries.
|
|
109
|
+
* @private
|
|
110
|
+
*/
|
|
18
111
|
private _generalValidationRetryCount;
|
|
112
|
+
/**
|
|
113
|
+
* Current agent run entity.
|
|
114
|
+
* @private
|
|
115
|
+
*/
|
|
19
116
|
private _agentRun;
|
|
117
|
+
/**
|
|
118
|
+
* Access the current run for the agent
|
|
119
|
+
*/
|
|
20
120
|
get AgentRun(): AIAgentRunEntityExtended | null;
|
|
121
|
+
/**
|
|
122
|
+
* Gets the available configuration presets for an agent.
|
|
123
|
+
* Returns semantic presets like "Fast", "Balanced", "High Quality" that users can choose from.
|
|
124
|
+
* These are actual presets stored in the database with specific AIConfiguration references.
|
|
125
|
+
*
|
|
126
|
+
* @param agentId - The ID of the agent to get presets for
|
|
127
|
+
* @returns Array of configuration presets sorted by Priority, or empty array if none configured
|
|
128
|
+
*
|
|
129
|
+
* @example
|
|
130
|
+
* ```typescript
|
|
131
|
+
* const agent = new ResearchAgent();
|
|
132
|
+
* const presets = agent.GetConfigurationPresets('agent-uuid-here');
|
|
133
|
+
* // Returns presets defined in database: [
|
|
134
|
+
* // { Name: 'Fast', DisplayName: 'Quick Draft', AIConfigurationID: 'fast-config-uuid', IsDefault: true },
|
|
135
|
+
* // { Name: 'HighQuality', DisplayName: 'Maximum Detail', AIConfigurationID: 'frontier-uuid', IsDefault: false }
|
|
136
|
+
* // ]
|
|
137
|
+
* // Note: If no presets configured, returns empty array - agent will use default behavior
|
|
138
|
+
* ```
|
|
139
|
+
*/
|
|
21
140
|
GetConfigurationPresets(agentId: string): import("@memberjunction/core-entities").AIAgentConfigurationEntity[];
|
|
141
|
+
/**
|
|
142
|
+
* Gets the default configuration preset for an agent.
|
|
143
|
+
*
|
|
144
|
+
* @param agentId - The ID of the agent to get the default preset for
|
|
145
|
+
* @returns The default preset, or undefined if none configured
|
|
146
|
+
*/
|
|
22
147
|
GetDefaultConfigurationPreset(agentId: string): import("@memberjunction/core-entities").AIAgentConfigurationEntity;
|
|
148
|
+
/**
|
|
149
|
+
* Promotes media outputs to the agent's final outputs.
|
|
150
|
+
* Call this method to add generated images, audio, or video to the agent's outputs.
|
|
151
|
+
* These will be saved to AIAgentRunMedia and flow to ConversationDetailAttachment.
|
|
152
|
+
*
|
|
153
|
+
* @param mediaOutputs - Array of media outputs to promote
|
|
154
|
+
* @since 3.1.0
|
|
155
|
+
*
|
|
156
|
+
* @example
|
|
157
|
+
* ```typescript
|
|
158
|
+
* // Promote images from action result
|
|
159
|
+
* this.promoteMediaOutputs([{
|
|
160
|
+
* modality: 'Image',
|
|
161
|
+
* mimeType: 'image/png',
|
|
162
|
+
* data: base64Data,
|
|
163
|
+
* label: 'Generated Product Image'
|
|
164
|
+
* }]);
|
|
165
|
+
*
|
|
166
|
+
* // Promote from prompt run media reference
|
|
167
|
+
* this.promoteMediaOutputs([{
|
|
168
|
+
* promptRunMediaId: 'prompt-run-media-uuid',
|
|
169
|
+
* modality: 'Image',
|
|
170
|
+
* mimeType: 'image/png',
|
|
171
|
+
* label: 'AI Generated Visualization'
|
|
172
|
+
* }]);
|
|
173
|
+
* ```
|
|
174
|
+
*/
|
|
23
175
|
promoteMediaOutputs(mediaOutputs: MediaOutput[]): void;
|
|
176
|
+
/**
|
|
177
|
+
* Gets the currently accumulated media outputs for this agent run.
|
|
178
|
+
* @returns Array of promoted media outputs
|
|
179
|
+
* @since 3.1.0
|
|
180
|
+
*/
|
|
24
181
|
get MediaOutputs(): MediaOutput[];
|
|
182
|
+
/**
|
|
183
|
+
* Minimum size in characters for binary content to be extracted as a media reference.
|
|
184
|
+
* Content smaller than this threshold is kept inline in action results.
|
|
185
|
+
* Default: 10000 (~7.5KB when decoded from base64)
|
|
186
|
+
* @private
|
|
187
|
+
*/
|
|
25
188
|
private static readonly LARGE_BINARY_THRESHOLD;
|
|
189
|
+
/**
|
|
190
|
+
* Intercepts large media content in action results and replaces with placeholder references.
|
|
191
|
+
* This prevents context overflow when action results contain large base64 data (images, audio, video).
|
|
192
|
+
*
|
|
193
|
+
* Uses generic ValueType=MediaOutput detection from action metadata to identify media output params.
|
|
194
|
+
* Intercepted media is stored in _mediaOutputs with refId and persist=false (not saved unless used).
|
|
195
|
+
*
|
|
196
|
+
* @param actionParams - The output parameters from an action result
|
|
197
|
+
* @param actionEntity - Optional action entity metadata for ValueType checking
|
|
198
|
+
* @returns Sanitized parameters with large media content replaced by ${media:ref-id} placeholders
|
|
199
|
+
* @private
|
|
200
|
+
* @since 3.1.0
|
|
201
|
+
*/
|
|
26
202
|
private interceptLargeBinaryContent;
|
|
203
|
+
/**
|
|
204
|
+
* Resolves media placeholders in a string.
|
|
205
|
+
* Replaces ${media:ref-id} with actual data URIs (data:mime;base64,...).
|
|
206
|
+
* Sets persist=true on resolved media so it will be saved to AIAgentRunMedia.
|
|
207
|
+
*
|
|
208
|
+
* @param text - The string that may contain media placeholders
|
|
209
|
+
* @returns String with placeholders resolved to actual data URIs
|
|
210
|
+
* @private
|
|
211
|
+
* @since 3.1.0
|
|
212
|
+
*/
|
|
27
213
|
private resolveMediaPlaceholdersInString;
|
|
214
|
+
/**
|
|
215
|
+
* Resolves media placeholders in a payload of any type.
|
|
216
|
+
* - For strings: resolves placeholders directly
|
|
217
|
+
* - For objects: recursively processes all string properties
|
|
218
|
+
* - For arrays: recursively processes all elements
|
|
219
|
+
*
|
|
220
|
+
* @param payload - The payload that may contain media placeholders in string values
|
|
221
|
+
* @returns Payload with all placeholders resolved to actual data URIs
|
|
222
|
+
* @private
|
|
223
|
+
* @since 3.1.0
|
|
224
|
+
*/
|
|
28
225
|
private resolveMediaPlaceholdersInPayload;
|
|
226
|
+
/**
|
|
227
|
+
* Recursively resolves media placeholders in any value.
|
|
228
|
+
* @private
|
|
229
|
+
*/
|
|
29
230
|
private resolveMediaPlaceholdersRecursive;
|
|
231
|
+
/**
|
|
232
|
+
* Processes media placeholders in agent messages for conversational agents.
|
|
233
|
+
*
|
|
234
|
+
* Unlike artifact-based agents (which embed images in HTML payload), conversational agents
|
|
235
|
+
* should display images via ConversationDetailAttachment. This method:
|
|
236
|
+
* 1. Detects ${media:xxx} placeholders in the message
|
|
237
|
+
* 2. Sets persist=true on referenced media (triggers save to AIAgentRunMedia)
|
|
238
|
+
* 3. Strips media HTML tags from the message (images display via attachment instead)
|
|
239
|
+
*
|
|
240
|
+
* @param message - The message that may contain media placeholders
|
|
241
|
+
* @returns Cleaned message with media tags stripped
|
|
242
|
+
* @private
|
|
243
|
+
* @since 3.1.0
|
|
244
|
+
*/
|
|
30
245
|
private processMessageMediaPlaceholders;
|
|
246
|
+
/**
|
|
247
|
+
* Agent hierarchy for display purposes (e.g., ["Marketing Agent", "Copywriter Agent"]).
|
|
248
|
+
* Tracked separately as it's display-only and doesn't need persistence.
|
|
249
|
+
* @private
|
|
250
|
+
*/
|
|
31
251
|
private _agentHierarchy;
|
|
252
|
+
/**
|
|
253
|
+
* Current iteration context for ForEach/While loops.
|
|
254
|
+
* Only one active loop per BaseAgent instance (nested loops handled by sub-agent instances).
|
|
255
|
+
* @private
|
|
256
|
+
*/
|
|
32
257
|
private _iterationContext;
|
|
258
|
+
/**
|
|
259
|
+
* Current depth in the agent hierarchy (0 = root agent, 1 = first sub-agent, etc.).
|
|
260
|
+
* @private
|
|
261
|
+
*/
|
|
33
262
|
private _depth;
|
|
263
|
+
/**
|
|
264
|
+
* Parent step counts from root to immediate parent.
|
|
265
|
+
* Example: [2, 1] means root agent is at step 2, parent agent is at step 1.
|
|
266
|
+
* Used to build hierarchical step display (e.g., "2.1.3" for nested agents).
|
|
267
|
+
* @private
|
|
268
|
+
*/
|
|
34
269
|
private _parentStepCounts;
|
|
270
|
+
/**
|
|
271
|
+
* All progress steps including intermediate ones for complete execution tracking.
|
|
272
|
+
* @private
|
|
273
|
+
*/
|
|
35
274
|
private _allProgressSteps;
|
|
275
|
+
/**
|
|
276
|
+
* Sub-agent execution results.
|
|
277
|
+
* @private
|
|
278
|
+
*/
|
|
36
279
|
private _subAgentRuns;
|
|
280
|
+
/**
|
|
281
|
+
* Accumulated media outputs that agents have explicitly promoted.
|
|
282
|
+
* These are collected during agent execution and returned in ExecuteAgentResult.mediaOutputs.
|
|
283
|
+
* Stored to AIAgentRunMedia when the agent completes.
|
|
284
|
+
* @private
|
|
285
|
+
* @since 3.1.0
|
|
286
|
+
*/
|
|
37
287
|
private _mediaOutputs;
|
|
288
|
+
/**
|
|
289
|
+
* Payload manager for handling payload access control.
|
|
290
|
+
* @private
|
|
291
|
+
*/
|
|
38
292
|
private _payloadManager;
|
|
293
|
+
/**
|
|
294
|
+
* Effective actions available to this agent after applying actionChanges.
|
|
295
|
+
* Populated during gatherPromptTemplateData() and used for validation in executeActionsStep().
|
|
296
|
+
* @private
|
|
297
|
+
* @since 2.123.0
|
|
298
|
+
*/
|
|
39
299
|
private _effectiveActions;
|
|
300
|
+
/**
|
|
301
|
+
* Execution limits for dynamically added actions.
|
|
302
|
+
* Maps action IDs to their MaxExecutionsPerRun limit.
|
|
303
|
+
* Populated during gatherPromptTemplateData() when actionChanges include actionLimits.
|
|
304
|
+
* @private
|
|
305
|
+
* @since 2.124.0
|
|
306
|
+
*/
|
|
40
307
|
private _dynamicActionLimits;
|
|
308
|
+
/**
|
|
309
|
+
* Counter for tracking validation retry attempts during FinalPayloadValidation.
|
|
310
|
+
* Reset at the start of each agent run.
|
|
311
|
+
* @private
|
|
312
|
+
*/
|
|
41
313
|
private _validationRetryCount;
|
|
314
|
+
/**
|
|
315
|
+
* Counter tracking the number of context recovery attempts made in this run.
|
|
316
|
+
* Context recovery removes/compacts old messages when context length is exceeded.
|
|
317
|
+
* Reset at the start of each agent run.
|
|
318
|
+
* @private
|
|
319
|
+
*/
|
|
42
320
|
private _contextRecoveryAttempts;
|
|
321
|
+
/**
|
|
322
|
+
* Maximum number of context recovery attempts allowed per agent run.
|
|
323
|
+
* @private
|
|
324
|
+
*/
|
|
43
325
|
private readonly MAX_RECOVERY_ATTEMPTS;
|
|
326
|
+
/**
|
|
327
|
+
* Gets the current validation retry count for the agent run.
|
|
328
|
+
* This count tracks how many times the agent has retried validation
|
|
329
|
+
* during the FinalPayloadValidation step.
|
|
330
|
+
* @readonly
|
|
331
|
+
*/
|
|
44
332
|
get ValidationRetryCount(): number;
|
|
333
|
+
/**
|
|
334
|
+
* Helper method for status logging with verbose control
|
|
335
|
+
* @param message The message to log
|
|
336
|
+
* @param verboseOnly Whether this is a verbose-only message
|
|
337
|
+
* @param params Optional agent execution parameters for custom verbose check
|
|
338
|
+
*/
|
|
45
339
|
protected logStatus(message: string, verboseOnly?: boolean, params?: ExecuteAgentParams): void;
|
|
340
|
+
/**
|
|
341
|
+
* Helper method for enhanced error logging with metadata
|
|
342
|
+
*/
|
|
46
343
|
protected logError(error: Error | string, options?: {
|
|
47
344
|
category?: string;
|
|
48
345
|
metadata?: Record<string, any>;
|
|
@@ -50,41 +347,316 @@ export declare class BaseAgent {
|
|
|
50
347
|
agentType?: AIAgentTypeEntity;
|
|
51
348
|
severity?: 'warning' | 'error' | 'critical';
|
|
52
349
|
}): void;
|
|
350
|
+
/**
|
|
351
|
+
* Wrapper for progress callbacks that captures all progress events.
|
|
352
|
+
* @private
|
|
353
|
+
*/
|
|
53
354
|
private wrapProgressCallback;
|
|
355
|
+
/**
|
|
356
|
+
* This overridable method is responsible for setting up any necessary one-time initalization of the
|
|
357
|
+
* agent type. The base class sets up the AgentTypeInstance and also lets that agent type initialize
|
|
358
|
+
* its state.
|
|
359
|
+
* @param params
|
|
360
|
+
*/
|
|
54
361
|
protected initializeAgentType(params: ExecuteAgentParams, config: AgentConfiguration): Promise<void>;
|
|
362
|
+
/**
|
|
363
|
+
* Preloads data sources configured for the agent.
|
|
364
|
+
*
|
|
365
|
+
* This method loads data from RunView or RunQuery sources as configured in
|
|
366
|
+
* AIAgentDataSource metadata and merges it with caller-provided data, context, and payload.
|
|
367
|
+
* Data sources can target three destinations:
|
|
368
|
+
* - Data: For Nunjucks templates in prompts (visible to LLMs)
|
|
369
|
+
* - Context: For actions only (NOT visible to LLMs)
|
|
370
|
+
* - Payload: For agent state initialization
|
|
371
|
+
*
|
|
372
|
+
* Caller-provided values always take precedence over preloaded values.
|
|
373
|
+
*
|
|
374
|
+
* @param params - The execution parameters
|
|
375
|
+
* @private
|
|
376
|
+
*/
|
|
55
377
|
private preloadAgentData;
|
|
378
|
+
/**
|
|
379
|
+
* Executes an AI agent using hierarchical prompt composition.
|
|
380
|
+
*
|
|
381
|
+
* This method orchestrates the entire agent execution process, from loading
|
|
382
|
+
* configuration to executing prompts and determining next steps. It ensures
|
|
383
|
+
* all required metadata is present and handles errors gracefully.
|
|
384
|
+
*
|
|
385
|
+
* @param {ExecuteAgentParams} params - Parameters for agent execution
|
|
386
|
+
* @param {AIAgentEntityExtended} params.agent - The agent entity to execute
|
|
387
|
+
* @param {ChatMessage[]} params.conversationMessages - Conversation history
|
|
388
|
+
* @param {UserInfo} [params.contextUser] - Optional user context
|
|
389
|
+
* @param {any} [params.context] - Optional context object passed to sub-agents and actions
|
|
390
|
+
* @template C - The type of the agent's context as provided in the ExecuteAgentParams
|
|
391
|
+
* @template R - The type of the agent's result as returned in ExecuteAgentResult
|
|
392
|
+
*
|
|
393
|
+
* @returns {Promise<ExecuteAgentResult>} Result containing next step and any output
|
|
394
|
+
*
|
|
395
|
+
* @throws {Error} Throws if there are issues loading required entities
|
|
396
|
+
*
|
|
397
|
+
* @example
|
|
398
|
+
* ```typescript
|
|
399
|
+
* const result = await agent.Execute({
|
|
400
|
+
* agent: salesAgent,
|
|
401
|
+
* conversationMessages: [{role: 'user', content: 'Help me find products'}],
|
|
402
|
+
* contextUser: currentUser
|
|
403
|
+
* });
|
|
404
|
+
* ```
|
|
405
|
+
*/
|
|
56
406
|
Execute<C = any, R = any>(params: ExecuteAgentParams<C>): Promise<ExecuteAgentResult<R>>;
|
|
407
|
+
/**
|
|
408
|
+
* Sub-classes can override this method to perform any specialized initialization
|
|
409
|
+
* @param params
|
|
410
|
+
*/
|
|
57
411
|
protected initializeStartingPayload<P = any>(params: ExecuteAgentParams<any, P>): Promise<void>;
|
|
412
|
+
/**
|
|
413
|
+
* Executes the agent's internal logic.
|
|
414
|
+
*
|
|
415
|
+
* This method contains the core execution logic that drives agent behavior. By default,
|
|
416
|
+
* it implements a sequential execution loop, but subclasses can override this to
|
|
417
|
+
* implement different execution patterns such as:
|
|
418
|
+
* - Parallel execution of multiple steps
|
|
419
|
+
* - Event-driven or reactive execution
|
|
420
|
+
* - State machine implementations
|
|
421
|
+
* - Custom termination conditions
|
|
422
|
+
* - Alternative flow control mechanisms
|
|
423
|
+
*
|
|
424
|
+
* @template P - The type of the return value from agent execution
|
|
425
|
+
* @param {ExecuteAgentParams} params - The execution parameters with wrapped callbacks (includes wrapped onProgress and onStreaming)
|
|
426
|
+
* @param {AgentConfiguration} config - The loaded agent configuration
|
|
427
|
+
* @returns {Promise<{finalPayload: P, stepCount: number}>} The execution result with typed final payload and step count
|
|
428
|
+
* @protected
|
|
429
|
+
*/
|
|
58
430
|
protected executeAgentInternal<P = any>(params: ExecuteAgentParams, config: AgentConfiguration): Promise<{
|
|
59
431
|
finalStep: BaseAgentNextStep<P>;
|
|
60
432
|
stepCount: number;
|
|
61
433
|
}>;
|
|
434
|
+
/**
|
|
435
|
+
* Initializes the AI and Action engines. Subclasses can override this to add any
|
|
436
|
+
* additional engine/metadata loading initialization they want to do and this method
|
|
437
|
+
* will be called at the right time in the agent execution process.
|
|
438
|
+
*
|
|
439
|
+
* @param {UserInfo} [contextUser] - Optional user context
|
|
440
|
+
* @protected
|
|
441
|
+
*/
|
|
62
442
|
protected initializeEngines(contextUser?: UserInfo): Promise<void>;
|
|
443
|
+
/**
|
|
444
|
+
* Storage for injected memory context to prepend to prompts
|
|
445
|
+
*/
|
|
63
446
|
private _memoryContext;
|
|
447
|
+
/**
|
|
448
|
+
* Storage for injected notes and examples to include in result
|
|
449
|
+
*/
|
|
64
450
|
private _injectedMemory;
|
|
451
|
+
/**
|
|
452
|
+
* Inject notes and examples into agent context memory.
|
|
453
|
+
* Called automatically before agent execution if injection is enabled on the agent.
|
|
454
|
+
* Injects memory context directly into conversation messages array.
|
|
455
|
+
*
|
|
456
|
+
* @param input - The user input text for semantic search
|
|
457
|
+
* @param agent - The agent configuration entity
|
|
458
|
+
* @param userId - Optional user ID for scoping
|
|
459
|
+
* @param companyId - Optional company ID for scoping
|
|
460
|
+
* @param contextUser - User context
|
|
461
|
+
* @param conversationMessages - The conversation messages array to inject into
|
|
462
|
+
* @returns Object containing injected notes and examples
|
|
463
|
+
*/
|
|
65
464
|
protected InjectContextMemory(input: string, agent: AIAgentEntityExtended, userId?: string, companyId?: string, contextUser?: UserInfo, conversationMessages?: ChatMessage[]): Promise<{
|
|
66
465
|
notes: AIAgentNoteEntity[];
|
|
67
466
|
examples: AIAgentExampleEntity[];
|
|
68
467
|
}>;
|
|
468
|
+
/**
|
|
469
|
+
* Converts UI markup (@{...} syntax) in user messages to plain text.
|
|
470
|
+
* This prevents agents from being confused by UI-specific JSON syntax and reduces token usage.
|
|
471
|
+
*
|
|
472
|
+
* Modifies the messages in-place, converting:
|
|
473
|
+
* - Mentions: @{_mode:"mention",...} → "@Agent Name" or "@User Name"
|
|
474
|
+
* - Form responses: @{_mode:"form",...} → "Field1: Value1, Field2: Value2"
|
|
475
|
+
*
|
|
476
|
+
* @param messages - The conversation messages array to convert (modified in-place)
|
|
477
|
+
*/
|
|
69
478
|
protected convertUIMarkupInMessages(messages: ChatMessage[]): void;
|
|
479
|
+
/**
|
|
480
|
+
* Validates that there are no circular references in the run chain.
|
|
481
|
+
* Follows the LastRunID chain to ensure it doesn't loop back to the current run.
|
|
482
|
+
*
|
|
483
|
+
* @param {string} lastRunId - The ID of the last run to check
|
|
484
|
+
* @param {UserInfo} [contextUser] - Optional user context
|
|
485
|
+
* @private
|
|
486
|
+
*/
|
|
70
487
|
private validateRunChain;
|
|
488
|
+
/**
|
|
489
|
+
* Validates that the agent is active and ready for execution.
|
|
490
|
+
*
|
|
491
|
+
* @param {AIAgentEntityExtended} agent - The agent to validate
|
|
492
|
+
* @returns {ExecuteAgentResult | null} Error result if validation fails, null if valid
|
|
493
|
+
* @protected
|
|
494
|
+
*/
|
|
71
495
|
protected validateAgent(agent: AIAgentEntityExtended): Promise<ExecuteAgentResult | null>;
|
|
496
|
+
/**
|
|
497
|
+
* Handles validation of the starting payload if configured.
|
|
498
|
+
*
|
|
499
|
+
* This method validates the input payload against the agent's StartingPayloadValidation
|
|
500
|
+
* schema before execution begins. It respects the agent's PayloadScope if configured.
|
|
501
|
+
*
|
|
502
|
+
* @param {ExecuteAgentParams} params - The execution parameters
|
|
503
|
+
* @returns {Promise<ExecuteAgentResult | null>} Error result if validation fails and mode is 'Fail', null otherwise
|
|
504
|
+
* @protected
|
|
505
|
+
*/
|
|
72
506
|
protected handleStartingPayloadValidation<P = any>(params: ExecuteAgentParams<any, P>): Promise<ExecuteAgentResult | null>;
|
|
507
|
+
/**
|
|
508
|
+
* Handles starting payload validation failures based on the configured mode.
|
|
509
|
+
*
|
|
510
|
+
* @param {ExecuteAgentParams} params - The execution parameters
|
|
511
|
+
* @param {string[]} errorMessages - The validation error messages
|
|
512
|
+
* @returns {ExecuteAgentResult | null} Error result if mode is 'Fail', null if mode is 'Warn'
|
|
513
|
+
* @private
|
|
514
|
+
*/
|
|
73
515
|
private handleStartingValidationFailure;
|
|
516
|
+
/**
|
|
517
|
+
* Loads all required configuration for agent execution.
|
|
518
|
+
*
|
|
519
|
+
* @param {AIAgentEntityExtended} agent - The agent to load configuration for
|
|
520
|
+
* @returns {Promise<AgentConfiguration>} Configuration object with loaded entities
|
|
521
|
+
* @protected
|
|
522
|
+
*/
|
|
74
523
|
protected loadAgentConfiguration(agent: AIAgentEntityExtended): Promise<AgentConfiguration>;
|
|
524
|
+
/**
|
|
525
|
+
* Prepares prompt parameters for hierarchical execution.
|
|
526
|
+
*
|
|
527
|
+
* @param {AIAgentTypeEntity} agentType - The agent type
|
|
528
|
+
* @param {AIPromptEntityExtended} systemPrompt - The system prompt
|
|
529
|
+
* @param {AIPromptEntityExtended} childPrompt - The child prompt
|
|
530
|
+
* @param {ExecuteAgentParams} params - Original execution parameters
|
|
531
|
+
* @returns {Promise<AIPromptParams>} Configured prompt parameters
|
|
532
|
+
* @protected
|
|
533
|
+
*/
|
|
75
534
|
protected preparePromptParams<P>(config: AgentConfiguration, payload: P, params: ExecuteAgentParams): Promise<AIPromptParams>;
|
|
535
|
+
/**
|
|
536
|
+
* Executes the configured prompt. Always uses the attemptJSONRepair option to try to fix LLM
|
|
537
|
+
* JSON syntax issues if they arise.
|
|
538
|
+
*
|
|
539
|
+
* @param {AIPromptParams} promptParams - The prompt parameters
|
|
540
|
+
* @returns {Promise<AIPromptRunResult>} The prompt execution result
|
|
541
|
+
* @protected
|
|
542
|
+
*/
|
|
76
543
|
protected executePrompt(promptParams: AIPromptParams): Promise<AIPromptRunResult>;
|
|
544
|
+
/**
|
|
545
|
+
* Base class method that determines the next step by contacting the agent type class for the specified agent type and delegating
|
|
546
|
+
* that decision. Sub-classes can override this method to implement custom next step logic if needed.
|
|
547
|
+
* @param params
|
|
548
|
+
* @param agentType
|
|
549
|
+
* @param promptResult
|
|
550
|
+
* @returns
|
|
551
|
+
*/
|
|
77
552
|
protected determineNextStep<P>(params: ExecuteAgentParams, agentType: AIAgentTypeEntity, promptResult: AIPromptRunResult, currentPayload: P): Promise<BaseAgentNextStep<P>>;
|
|
553
|
+
/**
|
|
554
|
+
* Validates if the next step is valid, or not. If the next step is invalid, it returns a retry step with an error message
|
|
555
|
+
* that can be processed by the agent via a retry prompt to attempt to correct the issue. Alternatively, subclasses can
|
|
556
|
+
* handle this scenario differently as desired.
|
|
557
|
+
*
|
|
558
|
+
* The BaseAgent class implements checking for sub-agents and actions to ensure that the next step is valid in the
|
|
559
|
+
* context of the current agent. If the next step is a sub-agent, it checks if the sub-agent is active and available for execution.
|
|
560
|
+
* If the next step is actions, it checks if the actions are valid and available for execution.
|
|
561
|
+
* @param params
|
|
562
|
+
* @param nextStep
|
|
563
|
+
* @returns
|
|
564
|
+
*/
|
|
78
565
|
protected validateNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: AIAgentRunEntityExtended, currentStep: AIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
|
|
566
|
+
/**
|
|
567
|
+
* Validates that the sub-agent next step is valid and can be executed by the current agent. Subclasses can override
|
|
568
|
+
* this method to implement custom validation logic if needed.
|
|
569
|
+
* @param params
|
|
570
|
+
* @param nextStep
|
|
571
|
+
* @returns
|
|
572
|
+
*/
|
|
79
573
|
protected validateSubAgentNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: AIAgentRunEntityExtended, currentStep: AIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
|
|
574
|
+
/**
|
|
575
|
+
* Validates that the actions next step is valid and can be executed by the current agent. Subclasses can override
|
|
576
|
+
* this method to implement custom validation logic if needed.
|
|
577
|
+
* @param params
|
|
578
|
+
* @param nextStep
|
|
579
|
+
* @returns
|
|
580
|
+
*/
|
|
80
581
|
protected validateActionsNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: AIAgentRunEntityExtended, currentStep: AIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
|
|
582
|
+
/**
|
|
583
|
+
* Gets the effective actions for validation, using runtime changes if available.
|
|
584
|
+
* Falls back to database-configured actions if _effectiveActions is empty.
|
|
585
|
+
*
|
|
586
|
+
* @param agentId - The ID of the agent to get actions for
|
|
587
|
+
* @returns Array of effective actions available to the agent
|
|
588
|
+
* @protected
|
|
589
|
+
* @since 2.123.0
|
|
590
|
+
*/
|
|
81
591
|
protected getEffectiveActionsForValidation(agentId: string): ActionEntityExtended[];
|
|
592
|
+
/**
|
|
593
|
+
* Validates that the Success next step is valid and can be executed by the current agent. Subclasses can override
|
|
594
|
+
* this method to implement custom validation logic if needed.
|
|
595
|
+
* @param params
|
|
596
|
+
* @param nextStep
|
|
597
|
+
* @returns
|
|
598
|
+
*/
|
|
82
599
|
protected validateSuccessNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: AIAgentRunEntityExtended, currentStep: AIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
|
|
600
|
+
/**
|
|
601
|
+
* Handles final payload validation failures based on the configured mode.
|
|
602
|
+
*
|
|
603
|
+
* @param params - Execution parameters
|
|
604
|
+
* @param nextStep - The original success next step
|
|
605
|
+
* @param currentPayload - The current payload
|
|
606
|
+
* @param mode - The validation mode (Retry, Fail, Warn)
|
|
607
|
+
* @param errorMessages - The validation error messages
|
|
608
|
+
* @returns Modified next step based on validation mode
|
|
609
|
+
*/
|
|
83
610
|
protected handleFinalPayloadValidationFailure<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, mode: string, errorMessages: string[], agentRun: AIAgentRunEntityExtended, currentStep: AIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
|
|
611
|
+
/**
|
|
612
|
+
* Validates that the Failed next step is valid and can be executed by the current agent. Subclasses can override
|
|
613
|
+
* this method to implement custom validation logic if needed.
|
|
614
|
+
* @param params
|
|
615
|
+
* @param nextStep
|
|
616
|
+
* @returns
|
|
617
|
+
*/
|
|
84
618
|
protected validateFailedNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: AIAgentRunEntityExtended, currentStep: AIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
|
|
619
|
+
/**
|
|
620
|
+
* Validates that the Retry next step is valid and can be executed by the current agent. Subclasses can override
|
|
621
|
+
* this method to implement custom validation logic if needed. The retry step is typically used to
|
|
622
|
+
* handle cases where the agent needs to re-attempt a step due to an error or invalid state.
|
|
623
|
+
* @param params
|
|
624
|
+
* @param nextStep
|
|
625
|
+
* @returns
|
|
626
|
+
*/
|
|
85
627
|
protected validateRetryNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: AIAgentRunEntityExtended, currentStep: AIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
|
|
628
|
+
/**
|
|
629
|
+
* Validates that the Chat next step is valid and can be executed by the current agent.
|
|
630
|
+
* Implements ChatHandlingOption remapping logic - if the agent has ChatHandlingOption set,
|
|
631
|
+
* the Chat step is remapped to the specified value (Success, Fail, or Retry).
|
|
632
|
+
* Subclasses can override this method to implement custom validation logic if needed.
|
|
633
|
+
* @param params
|
|
634
|
+
* @param nextStep
|
|
635
|
+
* @returns
|
|
636
|
+
*/
|
|
86
637
|
protected validateChatNextStep<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: AIAgentRunEntityExtended, currentStep: AIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
|
|
638
|
+
/**
|
|
639
|
+
* Checks execution guardrails and modifies next step if limits are exceeded.
|
|
640
|
+
* This method is called after validation but before execution of non-terminal steps.
|
|
641
|
+
*
|
|
642
|
+
* @param params - Execution parameters
|
|
643
|
+
* @param nextStep - The validated next step
|
|
644
|
+
* @param currentPayload - Current payload
|
|
645
|
+
* @param agentRun - Current agent run
|
|
646
|
+
* @param currentStep - Current execution step
|
|
647
|
+
* @returns Modified next step if guardrails exceeded, or original next step
|
|
648
|
+
* @protected
|
|
649
|
+
*/
|
|
87
650
|
protected checkExecutionGuardrails<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: AIAgentRunEntityExtended, currentStep: AIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
|
|
651
|
+
/**
|
|
652
|
+
* Checks if any agent run guardrails have been exceeded.
|
|
653
|
+
* Override this method to implement custom guardrail logic.
|
|
654
|
+
*
|
|
655
|
+
* @param params - Execution parameters
|
|
656
|
+
* @param agentRun - Current agent run
|
|
657
|
+
* @returns Object indicating if guardrails exceeded and details
|
|
658
|
+
* @protected
|
|
659
|
+
*/
|
|
88
660
|
protected hasExceededAgentRunGuardrails(params: ExecuteAgentParams, agentRun: AIAgentRunEntityExtended): Promise<{
|
|
89
661
|
exceeded: boolean;
|
|
90
662
|
type?: 'cost' | 'tokens' | 'iterations' | 'time';
|
|
@@ -92,135 +664,906 @@ export declare class BaseAgent {
|
|
|
92
664
|
current?: number;
|
|
93
665
|
reason?: string;
|
|
94
666
|
}>;
|
|
667
|
+
/**
|
|
668
|
+
* Determines if a prompt execution error is fatal and should stop agent execution.
|
|
669
|
+
* Fatal errors are those that won't be resolved by retrying, such as context length
|
|
670
|
+
* exceeded (when no larger model is available), authentication failures, or invalid
|
|
671
|
+
* request format.
|
|
672
|
+
*
|
|
673
|
+
* @param promptResult - The result from prompt execution
|
|
674
|
+
* @returns true if the error is fatal and agent should terminate, false otherwise
|
|
675
|
+
* @protected
|
|
676
|
+
*/
|
|
95
677
|
protected isFatalPromptError(promptResult: AIPromptRunResult): boolean;
|
|
678
|
+
/**
|
|
679
|
+
* Determines if an error is a configuration error that cannot be resolved by retrying.
|
|
680
|
+
* Configuration errors indicate issues with agent setup that need manual intervention.
|
|
681
|
+
*
|
|
682
|
+
* This method provides detailed diagnostic information to help identify what configuration
|
|
683
|
+
* is missing or incorrect.
|
|
684
|
+
*
|
|
685
|
+
* @param {any} error - The error object or Error instance
|
|
686
|
+
* @param {string} errorMessage - The error message string
|
|
687
|
+
* @param {AgentConfiguration} [config] - Optional agent configuration to check for missing pieces
|
|
688
|
+
* @returns {{isConfigError: boolean, detailedMessage: string}} Object with determination and detailed diagnostic message
|
|
689
|
+
* @protected
|
|
690
|
+
*/
|
|
96
691
|
protected isConfigurationError(errorMessage: string, config?: AgentConfiguration): {
|
|
97
692
|
isConfigError: boolean;
|
|
98
693
|
detailedMessage: string;
|
|
99
694
|
};
|
|
695
|
+
/**
|
|
696
|
+
* Converts ChatMessageContent to a string representation.
|
|
697
|
+
* Handles both simple strings and content block arrays.
|
|
698
|
+
*
|
|
699
|
+
* @param content - The message content to convert
|
|
700
|
+
* @returns String representation of the content
|
|
701
|
+
* @protected
|
|
702
|
+
*/
|
|
100
703
|
protected contentToString(content: ChatMessageContent): string;
|
|
704
|
+
/**
|
|
705
|
+
* Smart trimming of message content based on detected format.
|
|
706
|
+
* Attempts to preserve structure while reducing size.
|
|
707
|
+
*
|
|
708
|
+
* @param content - The message content to trim (must be string)
|
|
709
|
+
* @param maxLength - Maximum length for the trimmed content
|
|
710
|
+
* @returns Object with trimmed content and strategy used
|
|
711
|
+
* @protected
|
|
712
|
+
*/
|
|
101
713
|
protected smartTrimContent(content: string, maxLength?: number): {
|
|
102
714
|
trimmed: string;
|
|
103
715
|
strategy: string;
|
|
104
716
|
originalLength: number;
|
|
105
717
|
};
|
|
718
|
+
/**
|
|
719
|
+
* Serializes payload for logging to PayloadAtStart
|
|
720
|
+
* Override in subclasses to customize logging behavior (e.g., summarize large payloads)
|
|
721
|
+
*
|
|
722
|
+
* @param payload - The payload to serialize
|
|
723
|
+
* @returns Serialized string or null to skip logging
|
|
724
|
+
* @protected
|
|
725
|
+
*/
|
|
106
726
|
protected serializePayloadAtStart(payload: any): string | null;
|
|
727
|
+
/**
|
|
728
|
+
* Serializes payload for logging to PayloadAtEnd
|
|
729
|
+
* Override in subclasses to customize logging behavior (e.g., summarize large payloads)
|
|
730
|
+
*
|
|
731
|
+
* @param payload - The payload to serialize
|
|
732
|
+
* @returns Serialized string or null to skip logging
|
|
733
|
+
* @protected
|
|
734
|
+
*/
|
|
107
735
|
protected serializePayloadAtEnd(payload: any): string | null;
|
|
736
|
+
/**
|
|
737
|
+
* Recovery Strategy 1: Remove oldest action-result messages.
|
|
738
|
+
* Targets messages older than minAge turns for removal.
|
|
739
|
+
*
|
|
740
|
+
* @param params - Agent execution parameters
|
|
741
|
+
* @param tokensToSave - Target number of tokens to free
|
|
742
|
+
* @param currentStepCount - Current turn/step number
|
|
743
|
+
* @param minAge - Minimum age in turns for removal (default: 5)
|
|
744
|
+
* @returns Result with tokens saved and strategy description
|
|
745
|
+
* @protected
|
|
746
|
+
*/
|
|
108
747
|
protected recoveryStrategy_RemoveOldestActionResults(params: ExecuteAgentParams, tokensToSave: number, currentStepCount: number, minAge?: number): {
|
|
109
748
|
tokensSaved: number;
|
|
110
749
|
strategyName: string;
|
|
111
750
|
};
|
|
751
|
+
/**
|
|
752
|
+
* Recovery Strategy 2: Compact old action-result messages.
|
|
753
|
+
* Uses smart trimming to reduce size while preserving some content.
|
|
754
|
+
*
|
|
755
|
+
* @param params - Agent execution parameters
|
|
756
|
+
* @param tokensToSave - Target number of tokens to free
|
|
757
|
+
* @param currentStepCount - Current turn/step number
|
|
758
|
+
* @param minAge - Minimum age in turns for compaction (default: 3)
|
|
759
|
+
* @returns Result with tokens saved and strategy description
|
|
760
|
+
* @protected
|
|
761
|
+
*/
|
|
112
762
|
protected recoveryStrategy_CompactOldActionResults(params: ExecuteAgentParams, tokensToSave: number, currentStepCount: number, minAge?: number): Promise<{
|
|
113
763
|
tokensSaved: number;
|
|
114
764
|
strategyName: string;
|
|
115
765
|
}>;
|
|
766
|
+
/**
|
|
767
|
+
* Recovery Strategy 3: Aggressively compact ALL action-result messages.
|
|
768
|
+
* Used when gentler strategies haven't freed enough space.
|
|
769
|
+
*
|
|
770
|
+
* @param params - Agent execution parameters
|
|
771
|
+
* @param tokensToSave - Target number of tokens to free
|
|
772
|
+
* @returns Result with tokens saved and strategy description
|
|
773
|
+
* @protected
|
|
774
|
+
*/
|
|
116
775
|
protected recoveryStrategy_CompactAllActionResults(params: ExecuteAgentParams, tokensToSave: number): Promise<{
|
|
117
776
|
tokensSaved: number;
|
|
118
777
|
strategyName: string;
|
|
119
778
|
}>;
|
|
779
|
+
/**
|
|
780
|
+
* Recovery Strategy 4: Preserve beginning of last user message (fallback).
|
|
781
|
+
* Keeps the first 200-300 tokens of the user's request (which usually contains the core ask)
|
|
782
|
+
* and adds a clear marker that content was trimmed due to context limits.
|
|
783
|
+
*
|
|
784
|
+
* @param params - Agent execution parameters
|
|
785
|
+
* @param tokensToSave - Target number of tokens to free
|
|
786
|
+
* @returns Result with tokens saved and strategy description
|
|
787
|
+
* @protected
|
|
788
|
+
*/
|
|
120
789
|
protected recoveryStrategy_TrimLastUserMessage(params: ExecuteAgentParams, tokensToSave: number): {
|
|
121
790
|
tokensSaved: number;
|
|
122
791
|
strategyName: string;
|
|
123
792
|
};
|
|
793
|
+
/**
|
|
794
|
+
* Attempts to recover from a context length exceeded error using multiple strategies.
|
|
795
|
+
* Uses escalating strategies: remove old results → compact old results → compact all → trim user message.
|
|
796
|
+
* This approach preserves the user's original request while removing stale action results.
|
|
797
|
+
*
|
|
798
|
+
* @param params - Agent execution parameters (conversationMessages will be modified)
|
|
799
|
+
* @param payload - Current payload to carry forward
|
|
800
|
+
* @param errorMessage - The original error message from the failed prompt
|
|
801
|
+
* @param modelSelectionInfo - Model selection information containing the model and vendor used
|
|
802
|
+
* @returns A Retry step with reduced context or Failed if recovery unsuccessful
|
|
803
|
+
* @protected
|
|
804
|
+
*/
|
|
124
805
|
protected attemptContextRecovery<P>(params: ExecuteAgentParams, payload: P, errorMessage: string, modelSelectionInfo?: AIModelSelectionInfo): Promise<BaseAgentNextStep<P>>;
|
|
806
|
+
/**
|
|
807
|
+
* Processes the next step based on agent type determination.
|
|
808
|
+
*
|
|
809
|
+
* @param {ExecuteAgentParams} params - Original execution parameters
|
|
810
|
+
* @param {AIAgentTypeEntity} agentType - The agent type
|
|
811
|
+
* @param {AIPromptRunResult} promptResult - The prompt execution result
|
|
812
|
+
* @returns {Promise<ExecuteAgentResult>} The execution result
|
|
813
|
+
* @protected
|
|
814
|
+
*/
|
|
125
815
|
protected processNextStep<P>(nextStep: BaseAgentNextStep<P>, params: ExecuteAgentParams, agentType: AIAgentTypeEntity, promptResult: AIPromptRunResult, currentPayload: P, currentStep: AIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
|
|
816
|
+
/**
|
|
817
|
+
* Creates a chat message containing action execution results.
|
|
818
|
+
*
|
|
819
|
+
* @param {AgentAction[]} actions - The actions that were executed
|
|
820
|
+
* @param {any[]} results - The results from action execution
|
|
821
|
+
* @returns {ChatMessage} A formatted message with action results
|
|
822
|
+
* @protected
|
|
823
|
+
*/
|
|
126
824
|
protected createActionResultMessage(actions: AgentAction[], results: ActionResult[]): ChatMessage;
|
|
825
|
+
/**
|
|
826
|
+
* Creates a chat message containing sub-agent execution results.
|
|
827
|
+
*
|
|
828
|
+
* @param {AgentSubAgentRequest} subAgent - The sub-agent that was executed
|
|
829
|
+
* @param {any} result - The result from sub-agent execution
|
|
830
|
+
* @returns {ChatMessage} A formatted message with sub-agent results
|
|
831
|
+
* @protected
|
|
832
|
+
*/
|
|
127
833
|
protected createSubAgentResultMessage(subAgent: AgentSubAgentRequest, result: ExecuteAgentResult): ChatMessage;
|
|
834
|
+
/**
|
|
835
|
+
* Gathers context data about the agent for use in prompt templates.
|
|
836
|
+
*
|
|
837
|
+
* This method collects information about the agent's sub-agents and available
|
|
838
|
+
* actions, formatting them for injection into prompt templates. The data is
|
|
839
|
+
* structured to provide the LLM with comprehensive context about the agent's
|
|
840
|
+
* capabilities and hierarchical relationships.
|
|
841
|
+
*
|
|
842
|
+
* @param {AIAgentEntityExtended} agent - The agent to gather context for
|
|
843
|
+
* @param {UserInfo} [_contextUser] - Optional user context (reserved for future use)
|
|
844
|
+
* @param {any} [extraData] - Optional extra data to include in the context, if provided and keys conflict within the agent context data, the extraData will override the agent context data.
|
|
845
|
+
* @param {ActionChange[]} [actionChanges] - Optional runtime action modifications
|
|
846
|
+
*
|
|
847
|
+
* @returns {Promise<AgentContextData>} Structured context data for prompts
|
|
848
|
+
*
|
|
849
|
+
* @throws {Error} If there's an error accessing agent data
|
|
850
|
+
*
|
|
851
|
+
* @private
|
|
852
|
+
*/
|
|
128
853
|
private gatherPromptTemplateData;
|
|
854
|
+
/**
|
|
855
|
+
* Builds merged agent type prompt params from schema defaults,
|
|
856
|
+
* agent config, and runtime overrides.
|
|
857
|
+
*
|
|
858
|
+
* Merge precedence (lowest to highest):
|
|
859
|
+
* 1. Schema defaults (from AgentType.PromptParamsSchema)
|
|
860
|
+
* 2. Agent config (from AIAgent.AgentTypePromptParams)
|
|
861
|
+
* 3. Runtime overrides (from ExecuteAgentParams.data.__agentTypePromptParams)
|
|
862
|
+
*
|
|
863
|
+
* @param agentType - The agent type entity with schema definition
|
|
864
|
+
* @param agent - The agent entity with configured values
|
|
865
|
+
* @param runtimeOverrides - Optional runtime overrides from ExecuteAgentParams.data
|
|
866
|
+
* @returns Merged prompt params object
|
|
867
|
+
*
|
|
868
|
+
* @protected
|
|
869
|
+
* @since 2.131.0
|
|
870
|
+
*/
|
|
129
871
|
protected buildAgentTypePromptParams(agentType: AIAgentTypeEntity | undefined, agent: AIAgentEntityExtended, runtimeOverrides?: Record<string, unknown>): Record<string, unknown>;
|
|
872
|
+
/**
|
|
873
|
+
* Applies auto-alignment rules to includeResponseTypeDefinition based on other flags.
|
|
874
|
+
*
|
|
875
|
+
* When a documentation flag (e.g., includeForEachDocs) is explicitly set to false,
|
|
876
|
+
* the corresponding response type section (e.g., forEach) should also be excluded
|
|
877
|
+
* unless explicitly set otherwise.
|
|
878
|
+
*
|
|
879
|
+
* Auto-alignment mappings:
|
|
880
|
+
* - includePayloadInPrompt → includeResponseTypeDefinition.payload
|
|
881
|
+
* - includeResponseFormDocs → includeResponseTypeDefinition.responseForms
|
|
882
|
+
* - includeCommandDocs → includeResponseTypeDefinition.commands
|
|
883
|
+
* - includeForEachDocs → includeResponseTypeDefinition.forEach
|
|
884
|
+
* - includeWhileDocs → includeResponseTypeDefinition.while
|
|
885
|
+
*
|
|
886
|
+
* @param params - The merged params object to modify in place
|
|
887
|
+
* @param explicitResponseType - The explicitly set response type config from agent/runtime (not schema defaults)
|
|
888
|
+
* @protected
|
|
889
|
+
* @since 2.132.0
|
|
890
|
+
*/
|
|
130
891
|
protected applyResponseTypeAutoAlignment(params: Record<string, unknown>, explicitResponseType?: Record<string, unknown>): void;
|
|
892
|
+
/**
|
|
893
|
+
* Extracts default values from a JSON Schema definition.
|
|
894
|
+
*
|
|
895
|
+
* @param schemaJson - JSON string containing the schema
|
|
896
|
+
* @returns Object with property names and their default values
|
|
897
|
+
*
|
|
898
|
+
* @protected
|
|
899
|
+
* @since 2.131.0
|
|
900
|
+
*/
|
|
131
901
|
protected extractSchemaDefaults(schemaJson: string | null | undefined): Record<string, unknown>;
|
|
902
|
+
/**
|
|
903
|
+
* This method executes one action using the MemberJunction Actions framework.
|
|
904
|
+
* The full ActionResult objects are returned, allowing the caller to access result codes, output parameters,
|
|
905
|
+
* and other execution details.
|
|
906
|
+
*
|
|
907
|
+
* @param {ExecuteAgentParams} params - Parameters from agent execution for context passing
|
|
908
|
+
* @param {AgentAction} action - Action to execute
|
|
909
|
+
* @param {UserInfo} [contextUser] - Optional user context for permissions
|
|
910
|
+
*
|
|
911
|
+
* @returns {Promise<ActionResult>} ActionResult object from the action execution
|
|
912
|
+
*
|
|
913
|
+
* @throws {Error} If the action fails to execute
|
|
914
|
+
*/
|
|
132
915
|
ExecuteSingleAction(params: ExecuteAgentParams, action: AgentAction, actionEntity: ActionEntityExtended, contextUser?: UserInfo): Promise<ActionResult>;
|
|
916
|
+
/**
|
|
917
|
+
* Prepares conversation messages for sub-agent execution based on database-configured message mode.
|
|
918
|
+
*
|
|
919
|
+
* Message passing is controlled by MessageMode and MaxMessages fields stored in either:
|
|
920
|
+
* - AIAgentRelationship table (for related sub-agents via AgentRelationships)
|
|
921
|
+
* - AIAgent table (for child sub-agents via ParentID)
|
|
922
|
+
*
|
|
923
|
+
* **Message Modes:**
|
|
924
|
+
* - `'None'`: Fresh start - only context message and task message (default)
|
|
925
|
+
* - `'All'`: Pass complete parent conversation history
|
|
926
|
+
* - `'Latest'`: Pass most recent N messages (where N = MaxMessages)
|
|
927
|
+
* - `'Bookend'`: Pass first 2 messages + indicator + most recent (N-2) messages
|
|
928
|
+
*
|
|
929
|
+
* **Priority:** AIAgentRelationship.MessageMode takes precedence over AIAgent.MessageMode
|
|
930
|
+
* to allow different parent agents to pass messages differently to the same sub-agent.
|
|
931
|
+
*
|
|
932
|
+
* Subclasses can override this method to implement custom message preparation logic
|
|
933
|
+
* specific to their domain (e.g., Skip agents adding special context).
|
|
934
|
+
*
|
|
935
|
+
* @param {ExecuteAgentParams} params - Execution parameters with conversation history
|
|
936
|
+
* @param {AgentSubAgentRequest} subAgentRequest - Sub-agent request details
|
|
937
|
+
* @param {AIAgentEntityExtended} subAgent - The sub-agent entity
|
|
938
|
+
* @param {ChatMessage | undefined} contextMessage - Optional context from SubAgentContextPaths
|
|
939
|
+
* @returns {ChatMessage[]} Prepared message array for sub-agent execution
|
|
940
|
+
*
|
|
941
|
+
* @protected
|
|
942
|
+
*/
|
|
133
943
|
protected prepareSubAgentMessages(params: ExecuteAgentParams, subAgentRequest: AgentSubAgentRequest, subAgent: AIAgentEntityExtended, contextMessage?: ChatMessage): ChatMessage[];
|
|
944
|
+
/**
|
|
945
|
+
* Executes a sub-agent synchronously.
|
|
946
|
+
*
|
|
947
|
+
* This method creates a new instance of AgentRunner to execute a sub-agent.
|
|
948
|
+
* The sub-agent receives the provided message/context and runs to completion.
|
|
949
|
+
* If terminateAfter is true, the parent agent will not continue after the
|
|
950
|
+
* sub-agent completes.
|
|
951
|
+
*
|
|
952
|
+
* @param {AgentSubAgentRequest} subAgentRequest - Sub-agent execution details
|
|
953
|
+
* @param {ChatMessage[]} conversationMessages - Current conversation history
|
|
954
|
+
* @param {UserInfo} [contextUser] - Optional user context
|
|
955
|
+
*
|
|
956
|
+
* @returns {Promise<ExecuteAgentResult>} Result from the sub-agent execution
|
|
957
|
+
*
|
|
958
|
+
* @throws {Error} If sub-agent cannot be found or execution fails
|
|
959
|
+
*
|
|
960
|
+
* @example
|
|
961
|
+
* ```typescript
|
|
962
|
+
* const result = await this.ExecuteSubAgent({
|
|
963
|
+
* id: 'agent123',
|
|
964
|
+
* name: 'DataAnalysisAgent',
|
|
965
|
+
* message: 'Analyze sales data for Q4',
|
|
966
|
+
* terminateAfter: false
|
|
967
|
+
* }, messages);
|
|
968
|
+
* ```
|
|
969
|
+
*/
|
|
134
970
|
protected ExecuteSubAgent<SC = any, SR = any>(params: ExecuteAgentParams<SC>, subAgentRequest: AgentSubAgentRequest<SC>, subAgent: AIAgentEntityExtended, stepEntity: AIAgentRunStepEntityExtended, payload?: SR, contextMessage?: ChatMessage, stepCount?: number): Promise<ExecuteAgentResult<SR>>;
|
|
971
|
+
/**
|
|
972
|
+
* Formats sub-agent details for inclusion in prompt context.
|
|
973
|
+
*
|
|
974
|
+
* @param {AIAgentEntityExtended[]} subAgents - Array of sub-agent entities
|
|
975
|
+
* @returns {string} JSON formatted string with sub-agent details
|
|
976
|
+
* @private
|
|
977
|
+
*/
|
|
135
978
|
private formatSubAgentDetails;
|
|
979
|
+
/**
|
|
980
|
+
* Utility method to get agent prompt parameters for a given agent. This gets the
|
|
981
|
+
* highest priority prompt for the agent, and then gets the parameters for that
|
|
982
|
+
* prompt.
|
|
983
|
+
* @param agent
|
|
984
|
+
*/
|
|
136
985
|
protected getAgentPromptParameters(agent: AIAgentEntityExtended): Array<TemplateParamEntity>;
|
|
137
986
|
protected getAgentPromptParametersJSON(agent: AIAgentEntityExtended): string;
|
|
987
|
+
/**
|
|
988
|
+
* Formats action details for inclusion in prompt context.
|
|
989
|
+
*
|
|
990
|
+
* @param {ActionEntityExtended[]} actions - Array of action entities
|
|
991
|
+
* @returns {string} JSON formatted string with comprehensive action details
|
|
992
|
+
* @private
|
|
993
|
+
*/
|
|
138
994
|
private formatActionDetails;
|
|
995
|
+
/**
|
|
996
|
+
* Formats a single action parameter for display.
|
|
997
|
+
*
|
|
998
|
+
* @param {any} param - The action parameter to format
|
|
999
|
+
* @returns {object} Formatted parameter object
|
|
1000
|
+
* @private
|
|
1001
|
+
*/
|
|
139
1002
|
private formatActionParameter;
|
|
1003
|
+
/**
|
|
1004
|
+
* Formats a parameter value for display in action execution messages.
|
|
1005
|
+
* Truncates long strings and formats objects/arrays for readability.
|
|
1006
|
+
*
|
|
1007
|
+
* @param {any} value - The parameter value to format
|
|
1008
|
+
* @param {number} maxLength - Maximum length before truncation (default: 100)
|
|
1009
|
+
* @returns {string} Formatted value suitable for message display
|
|
1010
|
+
* @private
|
|
1011
|
+
*/
|
|
140
1012
|
private formatParamValueForMessage;
|
|
1013
|
+
/**
|
|
1014
|
+
* Gets the agent type name for a given type ID.
|
|
1015
|
+
*
|
|
1016
|
+
* @param {string} typeID - The agent type ID
|
|
1017
|
+
* @returns {string} The agent type name or 'Unknown'
|
|
1018
|
+
* @private
|
|
1019
|
+
*/
|
|
141
1020
|
private getAgentTypeName;
|
|
1021
|
+
/**
|
|
1022
|
+
* Determines if an action change scope applies to the current agent.
|
|
1023
|
+
*
|
|
1024
|
+
* @param {ActionChangeScope} scope - The scope of the action change
|
|
1025
|
+
* @param {string} agentId - The ID of the current agent
|
|
1026
|
+
* @param {boolean} isRoot - Whether this is the root agent
|
|
1027
|
+
* @param {string[]} [agentIds] - Array of specific agent IDs (for 'specific' scope)
|
|
1028
|
+
* @returns {boolean} True if the change applies to this agent
|
|
1029
|
+
* @protected
|
|
1030
|
+
* @since 2.123.0
|
|
1031
|
+
*/
|
|
142
1032
|
protected doesChangeScopeApply(scope: ActionChangeScope, agentId: string, isRoot: boolean, agentIds?: string[]): boolean;
|
|
1033
|
+
/**
|
|
1034
|
+
* Result type for applyActionChanges method.
|
|
1035
|
+
* Contains both the modified actions and any dynamic execution limits.
|
|
1036
|
+
* @since 2.123.0
|
|
1037
|
+
*/
|
|
143
1038
|
protected applyActionChanges(baseActions: ActionEntityExtended[], actionChanges: ActionChange[], agentId: string, isRoot: boolean): {
|
|
144
1039
|
actions: ActionEntityExtended[];
|
|
145
1040
|
dynamicLimits: Record<string, number>;
|
|
146
1041
|
};
|
|
1042
|
+
/**
|
|
1043
|
+
* Filters and transforms action changes for propagation to a sub-agent.
|
|
1044
|
+
*
|
|
1045
|
+
* This method applies the following propagation rules:
|
|
1046
|
+
* - 'global': Propagated as-is to all sub-agents
|
|
1047
|
+
* - 'root': Not propagated (only applies to root agent)
|
|
1048
|
+
* - 'all-subagents': Propagated as 'global' (since sub-agent is now in scope)
|
|
1049
|
+
* - 'specific': Propagated as-is (sub-agent checks if it's in agentIds)
|
|
1050
|
+
*
|
|
1051
|
+
* @param {ActionChange[] | undefined} actionChanges - The action changes to filter
|
|
1052
|
+
* @returns {ActionChange[] | undefined} Filtered action changes for sub-agent, or undefined if empty
|
|
1053
|
+
* @protected
|
|
1054
|
+
* @since 2.123.0
|
|
1055
|
+
*/
|
|
147
1056
|
protected filterActionChangesForSubAgent(actionChanges: ActionChange[] | undefined): ActionChange[] | undefined;
|
|
1057
|
+
/**
|
|
1058
|
+
* Gets value list items for a parameter.
|
|
1059
|
+
*
|
|
1060
|
+
* @param {string} valueListID - The value list ID
|
|
1061
|
+
* @returns {string[] | null} Array of allowed values or null
|
|
1062
|
+
* @private
|
|
1063
|
+
*/
|
|
148
1064
|
private getValueListItems;
|
|
1065
|
+
/**
|
|
1066
|
+
* Gets the action category name for a given category ID.
|
|
1067
|
+
*
|
|
1068
|
+
* @param {string} categoryID - The action category ID
|
|
1069
|
+
* @returns {string} The category name or 'Uncategorized'
|
|
1070
|
+
* @private
|
|
1071
|
+
*/
|
|
149
1072
|
private getActionCategoryName;
|
|
1073
|
+
/**
|
|
1074
|
+
* Initializes the agent run tracking by creating AIAgentRunEntityExtended and setting up context.
|
|
1075
|
+
*
|
|
1076
|
+
* @private
|
|
1077
|
+
* @param {ExecuteAgentParams} params - The execution parameters
|
|
1078
|
+
*/
|
|
150
1079
|
private initializeAgentRun;
|
|
1080
|
+
/**
|
|
1081
|
+
* Validates the agent with tracking.
|
|
1082
|
+
*
|
|
1083
|
+
* @private
|
|
1084
|
+
* @param {AIAgentEntityExtended} agent - The agent to validate
|
|
1085
|
+
* @returns {Promise<ExecuteAgentResult | null>} - Failure result if validation fails, null if successful
|
|
1086
|
+
*/
|
|
151
1087
|
private validateAgentWithTracking;
|
|
1088
|
+
/**
|
|
1089
|
+
* Creates a step entity for tracking.
|
|
1090
|
+
*
|
|
1091
|
+
* @private
|
|
1092
|
+
* @param params - Step creation parameters
|
|
1093
|
+
* @returns {Promise<AIAgentRunStepEntityExtended>} - The created step entity
|
|
1094
|
+
*/
|
|
152
1095
|
private createStepEntity;
|
|
1096
|
+
/**
|
|
1097
|
+
* Finalizes a step entity with completion status.
|
|
1098
|
+
*
|
|
1099
|
+
* @private
|
|
1100
|
+
* @param {AIAgentRunStepEntityExtended} stepEntity - The step entity to finalize
|
|
1101
|
+
* @param {boolean} success - Whether the step was successful
|
|
1102
|
+
* @param {string} [errorMessage] - Optional error message
|
|
1103
|
+
* @param {any} [outputData] - Optional output data to capture for this step
|
|
1104
|
+
*/
|
|
1105
|
+
/**
|
|
1106
|
+
* Builds a summary of payload change results for storage
|
|
1107
|
+
* @param changeResult The result from PayloadManager operations
|
|
1108
|
+
* @returns A serializable summary object
|
|
1109
|
+
*/
|
|
153
1110
|
private buildPayloadChangeResultSummary;
|
|
154
1111
|
private finalizeStepEntity;
|
|
1112
|
+
/**
|
|
1113
|
+
* Default parameter resolution for loop body parameters (used by Flow agents)
|
|
1114
|
+
* Resolves item.field, payload.field, item, index, or static values
|
|
1115
|
+
* @private
|
|
1116
|
+
*/
|
|
155
1117
|
private resolveLoopParams;
|
|
1118
|
+
/**
|
|
1119
|
+
* Formats a message with agent hierarchy for streaming/progress updates.
|
|
1120
|
+
*
|
|
1121
|
+
* @private
|
|
1122
|
+
* @param {string} baseMessage - The base message to format
|
|
1123
|
+
* @returns {string} - The formatted message with hierarchy breadcrumb
|
|
1124
|
+
*/
|
|
156
1125
|
private formatHierarchicalMessage;
|
|
1126
|
+
/**
|
|
1127
|
+
* Builds hierarchical step string from parent and current step counts.
|
|
1128
|
+
*
|
|
1129
|
+
* Examples:
|
|
1130
|
+
* - Root agent step 2: buildHierarchicalStep(2, []) => "2"
|
|
1131
|
+
* - Sub-agent step 1 under root step 2: buildHierarchicalStep(1, [2]) => "2.1"
|
|
1132
|
+
* - Nested sub-agent step 3: buildHierarchicalStep(3, [2, 1]) => "2.1.3"
|
|
1133
|
+
* - Deep nesting: buildHierarchicalStep(5, [1, 2, 3, 4]) => "1.2.3.4.5"
|
|
1134
|
+
*
|
|
1135
|
+
* @param currentStep - Current agent's step number (1-based)
|
|
1136
|
+
* @param parentSteps - Array of parent step counts from root to immediate parent
|
|
1137
|
+
* @returns Formatted hierarchical step string, or undefined if currentStep is undefined/null
|
|
1138
|
+
* @private
|
|
1139
|
+
*/
|
|
157
1140
|
private buildHierarchicalStep;
|
|
1141
|
+
/**
|
|
1142
|
+
* Gets human-readable reasoning for the next step decision.
|
|
1143
|
+
*
|
|
1144
|
+
* @private
|
|
1145
|
+
* @param {BaseAgentNextStep} nextStep - The next step decision
|
|
1146
|
+
* @returns {string} Human-readable reasoning
|
|
1147
|
+
*/
|
|
158
1148
|
private getNextStepReasoning;
|
|
1149
|
+
/**
|
|
1150
|
+
* Executes the next step based on the current state.
|
|
1151
|
+
*
|
|
1152
|
+
* This method can be overridden by subclasses to customize step execution behavior.
|
|
1153
|
+
* It handles the execution of different step types (prompt, actions, sub-agent, chat)
|
|
1154
|
+
* based on the previous decision.
|
|
1155
|
+
*
|
|
1156
|
+
* @protected
|
|
1157
|
+
* @param {ExecuteAgentParams} params - Original execution parameters
|
|
1158
|
+
* @param {AgentConfiguration} config - Agent configuration
|
|
1159
|
+
* @param {BaseAgentNextStep | null} previousDecision - Previous step decision
|
|
1160
|
+
* @returns {Promise<BaseAgentNextStep<P>>}
|
|
1161
|
+
*/
|
|
159
1162
|
protected executeNextStep<P = any>(params: ExecuteAgentParams, config: AgentConfiguration, previousDecision: BaseAgentNextStep<P> | null, stepCount?: number): Promise<BaseAgentNextStep<P>>;
|
|
1163
|
+
/**
|
|
1164
|
+
* Returns the default payload self write paths for the agent. If not specified, it will return undefined
|
|
1165
|
+
|
|
1166
|
+
*/
|
|
160
1167
|
private getDefaultPayloadSelfWritePaths;
|
|
1168
|
+
/**
|
|
1169
|
+
* Executes a prompt step and tracks it.
|
|
1170
|
+
*
|
|
1171
|
+
* @private
|
|
1172
|
+
*/
|
|
161
1173
|
private executePromptStep;
|
|
1174
|
+
/**
|
|
1175
|
+
* Computes the upstream and downstream paths for a sub-agent based on the agent's payload paths.
|
|
1176
|
+
* @param params
|
|
1177
|
+
* @param subAgentEntity
|
|
1178
|
+
* @param subAgentRequest
|
|
1179
|
+
* @returns
|
|
1180
|
+
*/
|
|
162
1181
|
private computeUpstreamDownstreamPaths;
|
|
1182
|
+
/**
|
|
1183
|
+
* Computes the payload for a child sub-agent based on the agent's payload paths.
|
|
1184
|
+
* @param params
|
|
1185
|
+
* @param subAgentEntity
|
|
1186
|
+
* @param downstreamPaths
|
|
1187
|
+
* @param subAgentRequest
|
|
1188
|
+
* @param previousDecision
|
|
1189
|
+
* @returns
|
|
1190
|
+
*/
|
|
163
1191
|
private computeChildSubAgentPayload;
|
|
1192
|
+
/**
|
|
1193
|
+
* Executes a child sub-agent step (ParentID relationship) and tracks it.
|
|
1194
|
+
* Child agents use direct payload inheritance with downstream/upstream paths.
|
|
1195
|
+
*
|
|
1196
|
+
* @private
|
|
1197
|
+
* @param parentStepId - Optional ID of parent step (e.g., ForEach/While loop step) for proper UI hierarchy
|
|
1198
|
+
* @param subAgentPayloadOverride - Optional payload override for sub-agent execution, if provided the normal payload computation is skipped
|
|
1199
|
+
*/
|
|
164
1200
|
private executeChildSubAgentStep;
|
|
1201
|
+
/**
|
|
1202
|
+
* Routes sub-agent execution to the appropriate handler based on relationship type.
|
|
1203
|
+
* Child agents (ParentID) use direct payload coupling.
|
|
1204
|
+
* Related agents (AgentRelationships) use message-based coupling with optional output mapping.
|
|
1205
|
+
*
|
|
1206
|
+
* @private
|
|
1207
|
+
* @param parentStepId - Optional ID of parent step (e.g., ForEach/While loop step) for proper UI hierarchy
|
|
1208
|
+
* @param subAgentPayloadOverride - Optional payload override for sub-agent execution, if provided the normal payload computation is skipped
|
|
1209
|
+
*/
|
|
165
1210
|
private processSubAgentStep;
|
|
1211
|
+
/**
|
|
1212
|
+
* Executes a related sub-agent step (AgentRelationships) and tracks it.
|
|
1213
|
+
* Related agents use message-based communication with independent payloads.
|
|
1214
|
+
* Optional output mapping can merge sub-agent results back to parent payload.
|
|
1215
|
+
*
|
|
1216
|
+
* @private
|
|
1217
|
+
* @param parentStepId - Optional ID of parent step (e.g., ForEach/While loop step) for proper UI hierarchy
|
|
1218
|
+
*/
|
|
166
1219
|
private executeRelatedSubAgentStep;
|
|
1220
|
+
/**
|
|
1221
|
+
* Applies sub-agent output mapping to update the parent payload.
|
|
1222
|
+
* Maps sub-agent result payload paths to parent payload paths.
|
|
1223
|
+
* Mirrors the action output mapping pattern used by Flow agents.
|
|
1224
|
+
*
|
|
1225
|
+
* @private
|
|
1226
|
+
*/
|
|
167
1227
|
private applySubAgentOutputMapping;
|
|
1228
|
+
/**
|
|
1229
|
+
* Sets a value in a target object, supporting array append operations.
|
|
1230
|
+
* If the key ends with [], the value is appended to an array instead of replacing.
|
|
1231
|
+
*
|
|
1232
|
+
* @param target - Target object to modify
|
|
1233
|
+
* @param key - Property key, optionally ending with [] for array append
|
|
1234
|
+
* @param value - Value to set or append
|
|
1235
|
+
* @private
|
|
1236
|
+
*/
|
|
168
1237
|
private setMappedValue;
|
|
1238
|
+
/**
|
|
1239
|
+
* Applies sub-agent input mapping to prepare initial payload for related sub-agent.
|
|
1240
|
+
* Maps parent payload paths to sub-agent initial payload paths.
|
|
1241
|
+
* Enables structural data transfer from parent to related sub-agent.
|
|
1242
|
+
*
|
|
1243
|
+
* @param parentPayload - Parent agent's current payload
|
|
1244
|
+
* @param mappingConfig - JSON mapping configuration string
|
|
1245
|
+
* @returns Mapped payload object for sub-agent initialization, or null if mapping fails or produces empty result
|
|
1246
|
+
* @private
|
|
1247
|
+
*/
|
|
169
1248
|
private applySubAgentInputMapping;
|
|
1249
|
+
/**
|
|
1250
|
+
* Prepares a context message containing parent payload data for related sub-agent.
|
|
1251
|
+
* Extracts specified paths from parent payload or conversation messages and formats
|
|
1252
|
+
* them as a user message to provide LLM context to the sub-agent.
|
|
1253
|
+
*
|
|
1254
|
+
* Supports both payload paths and conversation message paths:
|
|
1255
|
+
* - Payload paths: "fieldName", "nested.field", etc.
|
|
1256
|
+
* - Conversation paths: "conversation.all", "conversation.user.last", "conversation.all.last[5]", etc.
|
|
1257
|
+
*
|
|
1258
|
+
* @param parentPayload - Parent agent's current payload
|
|
1259
|
+
* @param contextPaths - Array of paths to extract, or ["*"] for entire payload
|
|
1260
|
+
* @param params - Execution parameters with conversation messages
|
|
1261
|
+
* @returns ChatMessage with formatted context, or null if no paths specified or no data found
|
|
1262
|
+
* @private
|
|
1263
|
+
*/
|
|
170
1264
|
private prepareRelatedSubAgentContextMessage;
|
|
1265
|
+
/**
|
|
1266
|
+
* Helper method to get a value from a nested object path.
|
|
1267
|
+
* Supports both dot notation (obj.prop) and array indexing (arr[0]).
|
|
1268
|
+
*
|
|
1269
|
+
|
|
1270
|
+
/**
|
|
1271
|
+
* Executes actions step and tracks it.
|
|
1272
|
+
*
|
|
1273
|
+
* @private
|
|
1274
|
+
*/
|
|
171
1275
|
private executeActionsStep;
|
|
1276
|
+
/**
|
|
1277
|
+
* Executes a chat step - these should bubble up to the user for interaction.
|
|
1278
|
+
* Chat steps are terminal and indicate the agent needs user input.
|
|
1279
|
+
*
|
|
1280
|
+
* @private
|
|
1281
|
+
*/
|
|
172
1282
|
private executeChatStep;
|
|
1283
|
+
/**
|
|
1284
|
+
* Executes a ForEach loop with actual for loop
|
|
1285
|
+
* @private
|
|
1286
|
+
*/
|
|
173
1287
|
private executeForEachLoop;
|
|
174
1288
|
private validateWhileOperation;
|
|
175
1289
|
private validateForEachOperation;
|
|
176
1290
|
protected validateActionInAgent(actionName: string): string | null;
|
|
177
1291
|
protected validateSubAgentInAgent(subAgentName: string): string | null;
|
|
1292
|
+
/**
|
|
1293
|
+
* Helper: Validate and extract collection from payload
|
|
1294
|
+
* Strips "payload." prefix if present (for LLM convenience)
|
|
1295
|
+
*/
|
|
178
1296
|
private getCollectionFromPayload;
|
|
1297
|
+
/**
|
|
1298
|
+
* Helper: Create parent ForEach loop step (not finalized until loop completes)
|
|
1299
|
+
*/
|
|
179
1300
|
private createForEachLoopStep;
|
|
1301
|
+
/**
|
|
1302
|
+
* Helper: Execute all iterations with actual for loop
|
|
1303
|
+
*/
|
|
180
1304
|
private executeForEachIterations;
|
|
1305
|
+
/**
|
|
1306
|
+
* Execute ForEach iterations sequentially (one at a time).
|
|
1307
|
+
* This is the original implementation - safe for state accumulation and maintaining order.
|
|
1308
|
+
*/
|
|
181
1309
|
private executeForEachIterationsSequential;
|
|
1310
|
+
/**
|
|
1311
|
+
* Execute ForEach iterations in parallel batches.
|
|
1312
|
+
* Processes multiple iterations concurrently for better performance when iterations are independent.
|
|
1313
|
+
* Results are collected in parallel but applied to payload sequentially to maintain order.
|
|
1314
|
+
*/
|
|
182
1315
|
private executeForEachIterationsParallel;
|
|
1316
|
+
/**
|
|
1317
|
+
* Create batches of items for parallel processing.
|
|
1318
|
+
* Each batch contains up to maxConcurrency items with their original indices.
|
|
1319
|
+
*/
|
|
183
1320
|
private createBatches;
|
|
1321
|
+
/**
|
|
1322
|
+
* Apply ForEach results sequentially to build final payload.
|
|
1323
|
+
* This ensures payload changes are applied in order even when iterations ran in parallel.
|
|
1324
|
+
*/
|
|
184
1325
|
private applyForEachResultsSequentially;
|
|
1326
|
+
/**
|
|
1327
|
+
* Helper: Execute single ForEach iteration
|
|
1328
|
+
*/
|
|
185
1329
|
private executeSingleForEachIteration;
|
|
1330
|
+
/**
|
|
1331
|
+
* Helper: Complete ForEach and return result
|
|
1332
|
+
*/
|
|
186
1333
|
private completeForEachLoop;
|
|
1334
|
+
/**
|
|
1335
|
+
* Helper: Inject loop results as temporary message
|
|
1336
|
+
*/
|
|
187
1337
|
private injectLoopResultsMessage;
|
|
1338
|
+
/**
|
|
1339
|
+
* Helper: Find action with fuzzy matching for loops.
|
|
1340
|
+
* Uses effective actions which includes both database-configured and dynamically added actions.
|
|
1341
|
+
* Returns an object with the resolved action name for use in loop execution.
|
|
1342
|
+
*
|
|
1343
|
+
* @since 2.123.0 - Updated to use _effectiveActions for dynamic action support
|
|
1344
|
+
*/
|
|
188
1345
|
private findAgentActionForLoop;
|
|
1346
|
+
/**
|
|
1347
|
+
* Helper: Create failed step
|
|
1348
|
+
*/
|
|
189
1349
|
private createFailedStep;
|
|
1350
|
+
/**
|
|
1351
|
+
* Executes a While loop with actual while loop
|
|
1352
|
+
* @private
|
|
1353
|
+
*/
|
|
190
1354
|
private executeWhileLoop;
|
|
1355
|
+
/**
|
|
1356
|
+
* Helper: Create parent While loop step
|
|
1357
|
+
*/
|
|
191
1358
|
private createWhileLoopStep;
|
|
1359
|
+
/**
|
|
1360
|
+
* Helper: Execute While iterations with actual while loop
|
|
1361
|
+
*/
|
|
192
1362
|
private executeWhileIterations;
|
|
1363
|
+
/**
|
|
1364
|
+
* Helper: Execute single While iteration
|
|
1365
|
+
*/
|
|
193
1366
|
private executeSingleWhileIteration;
|
|
1367
|
+
/**
|
|
1368
|
+
* Helper: Complete While and return result
|
|
1369
|
+
*/
|
|
194
1370
|
private completeWhileLoop;
|
|
1371
|
+
/**
|
|
1372
|
+
* Creates a failure result with proper tracking.
|
|
1373
|
+
*
|
|
1374
|
+
* @private
|
|
1375
|
+
*/
|
|
195
1376
|
private createFailureResult;
|
|
1377
|
+
/**
|
|
1378
|
+
* Creates a cancelled result.
|
|
1379
|
+
*
|
|
1380
|
+
* @private
|
|
1381
|
+
* @param {string} message - The cancellation message
|
|
1382
|
+
* @returns {Promise<ExecuteAgentResult>} The cancelled result
|
|
1383
|
+
*/
|
|
196
1384
|
private createCancelledResult;
|
|
1385
|
+
/**
|
|
1386
|
+
* Finalizes the agent run with success.
|
|
1387
|
+
*
|
|
1388
|
+
* @private
|
|
1389
|
+
*/
|
|
197
1390
|
private finalizeAgentRun;
|
|
1391
|
+
/**
|
|
1392
|
+
* Calculate total token statistics from the agent run's persisted steps.
|
|
1393
|
+
*
|
|
1394
|
+
* @returns Token statistics including totals and costs
|
|
1395
|
+
* @private
|
|
1396
|
+
*/
|
|
198
1397
|
private calculateTokenStats;
|
|
1398
|
+
/**
|
|
1399
|
+
* Gets the count of how many times a specific action has been executed in this agent run.
|
|
1400
|
+
*
|
|
1401
|
+
* @param agentRunId - The agent run ID (not used anymore, kept for signature compatibility)
|
|
1402
|
+
* @param actionId - The action ID to count
|
|
1403
|
+
* @returns The number of times the action has been executed
|
|
1404
|
+
*/
|
|
199
1405
|
protected getActionExecutionCount(agentRunId: string, actionId: string): Promise<number>;
|
|
1406
|
+
/**
|
|
1407
|
+
* Gets the count of how many times a specific sub-agent has been executed in this agent run.
|
|
1408
|
+
*
|
|
1409
|
+
* @param agentRunId - The agent run ID (not used anymore, kept for signature compatibility)
|
|
1410
|
+
* @param subAgentId - The sub-agent ID to count
|
|
1411
|
+
* @returns The number of times the sub-agent has been executed
|
|
1412
|
+
*/
|
|
200
1413
|
protected getSubAgentExecutionCount(agentRunId: string, subAgentId: string): Promise<number>;
|
|
1414
|
+
/**
|
|
1415
|
+
* Increments the execution count for an item (action or sub-agent).
|
|
1416
|
+
*
|
|
1417
|
+
* @param itemId - The item ID to increment (action ID or sub-agent ID)
|
|
1418
|
+
* @private
|
|
1419
|
+
*/
|
|
201
1420
|
private incrementExecutionCount;
|
|
1421
|
+
/**
|
|
1422
|
+
* Gets the execution count for an item (action or sub-agent).
|
|
1423
|
+
*
|
|
1424
|
+
* @param itemId - The item ID to get count for
|
|
1425
|
+
* @returns The execution count (0 if never executed)
|
|
1426
|
+
* @private
|
|
1427
|
+
*/
|
|
202
1428
|
private getExecutionCount;
|
|
1429
|
+
/**
|
|
1430
|
+
* Checks if all minimum execution requirements are met for actions and sub-agents.
|
|
1431
|
+
*
|
|
1432
|
+
* NOTE: This method intentionally uses only database-configured AgentActions, not _effectiveActions.
|
|
1433
|
+
* MinExecutionsPerRun is a database-only concept - dynamically added actions via actionChanges
|
|
1434
|
+
* do not have minimum execution requirements. If minimum requirements for dynamic actions are
|
|
1435
|
+
* needed in the future, consider adding a `minActionLimits` property to the ActionChange interface.
|
|
1436
|
+
*
|
|
1437
|
+
* @param agent - The agent to check
|
|
1438
|
+
* @param agentRun - The current agent run
|
|
1439
|
+
* @returns Array of violation messages (empty if all requirements are met)
|
|
1440
|
+
*/
|
|
203
1441
|
protected checkMinimumExecutionRequirements(agent: AIAgentEntityExtended, agentRun: AIAgentRunEntityExtended): Promise<string[]>;
|
|
1442
|
+
/**
|
|
1443
|
+
* Prunes and compacts expired messages in the conversation based on configured expiration rules.
|
|
1444
|
+
* Processes messages in three phases: identification, compaction, and removal.
|
|
1445
|
+
*
|
|
1446
|
+
* @param params - Agent execution parameters containing conversation messages
|
|
1447
|
+
* @param currentTurn - Current turn number in the agent execution
|
|
1448
|
+
* @protected
|
|
1449
|
+
*/
|
|
204
1450
|
protected pruneAndCompactExpiredMessages(params: ExecuteAgentParams, currentTurn: number): Promise<void>;
|
|
1451
|
+
/**
|
|
1452
|
+
* Creates an AIAgentRunStep for message compaction operations.
|
|
1453
|
+
* Records the compaction attempt with context about the message being compacted.
|
|
1454
|
+
*
|
|
1455
|
+
* @param prompt - The AI prompt used for compaction
|
|
1456
|
+
* @param message - The message being compacted
|
|
1457
|
+
* @param params - Agent execution parameters
|
|
1458
|
+
* @returns The created run step entity
|
|
1459
|
+
* @protected
|
|
1460
|
+
*/
|
|
205
1461
|
protected createCompactionStep(prompt: AIPromptEntityExtended, message: AgentChatMessage, params: ExecuteAgentParams): Promise<AIAgentRunStepEntityExtended>;
|
|
1462
|
+
/**
|
|
1463
|
+
* Updates the compaction step with execution results and token usage.
|
|
1464
|
+
*
|
|
1465
|
+
* @param step - The run step to update
|
|
1466
|
+
* @param result - The prompt execution result
|
|
1467
|
+
* @param message - The message that was compacted
|
|
1468
|
+
* @param params - Agent execution parameters
|
|
1469
|
+
* @protected
|
|
1470
|
+
*/
|
|
206
1471
|
protected updateCompactionStep(step: AIAgentRunStepEntityExtended, result: AIPromptRunResult<{
|
|
207
1472
|
summary: string;
|
|
208
1473
|
}>, message: AgentChatMessage, params: ExecuteAgentParams): Promise<void>;
|
|
1474
|
+
/**
|
|
1475
|
+
* Compacts a message using configured compaction mode.
|
|
1476
|
+
*
|
|
1477
|
+
* @param message - The message to compact
|
|
1478
|
+
* @param metadata - Compaction configuration
|
|
1479
|
+
* @param params - Agent execution parameters for context
|
|
1480
|
+
* @returns Compacted content string
|
|
1481
|
+
* @protected
|
|
1482
|
+
*/
|
|
209
1483
|
protected compactMessage(message: AgentChatMessage, metadata: {
|
|
210
1484
|
compactMode: 'First N Chars' | 'AI Summary';
|
|
211
1485
|
compactLength: number;
|
|
212
1486
|
compactPromptId: string;
|
|
213
1487
|
originalLength: number;
|
|
214
1488
|
}, params: ExecuteAgentParams): Promise<string>;
|
|
1489
|
+
/**
|
|
1490
|
+
* Returns the system default prompt ID for message compaction.
|
|
1491
|
+
* Looks up the "Compact Agent Message" prompt by name.
|
|
1492
|
+
* @protected
|
|
1493
|
+
*/
|
|
215
1494
|
protected getSystemDefaultCompactPromptId(): string;
|
|
1495
|
+
/**
|
|
1496
|
+
* Estimates token count from content.
|
|
1497
|
+
* Uses js-tiktoken for accurate counting when available and model info is provided,
|
|
1498
|
+
* falls back to improved heuristic otherwise.
|
|
1499
|
+
* @param content - The message content to estimate tokens for
|
|
1500
|
+
* @param modelName - Optional model name for accurate tokenization
|
|
1501
|
+
* @protected
|
|
1502
|
+
*/
|
|
216
1503
|
protected estimateTokens(content: ChatMessage['content'], modelName?: string): number;
|
|
1504
|
+
/**
|
|
1505
|
+
* Provides an improved heuristic token count when tokenizer is unavailable.
|
|
1506
|
+
* @param text - The text to estimate tokens for
|
|
1507
|
+
* @returns Estimated token count
|
|
1508
|
+
* @private
|
|
1509
|
+
*/
|
|
217
1510
|
private heuristicTokenCount;
|
|
1511
|
+
/**
|
|
1512
|
+
* Gets the context limit for the current model.
|
|
1513
|
+
* Uses model selection info from the prompt result to determine the actual model's MaxInputTokens.
|
|
1514
|
+
* @param modelSelectionInfo - Model selection information from the prompt execution
|
|
1515
|
+
* @returns The maximum input tokens for the model
|
|
1516
|
+
* @protected
|
|
1517
|
+
*/
|
|
218
1518
|
protected getModelContextLimit(modelSelectionInfo?: AIModelSelectionInfo): number;
|
|
1519
|
+
/**
|
|
1520
|
+
* Estimates total token count across all conversation messages.
|
|
1521
|
+
* @param messages - Message array to estimate
|
|
1522
|
+
* @returns Total estimated tokens
|
|
1523
|
+
* @protected
|
|
1524
|
+
*/
|
|
219
1525
|
protected estimateConversationTokens(messages: ChatMessage[]): number;
|
|
1526
|
+
/**
|
|
1527
|
+
* Emits message lifecycle event if callback is registered.
|
|
1528
|
+
* @protected
|
|
1529
|
+
*/
|
|
220
1530
|
protected emitMessageLifecycleEvent(event: MessageLifecycleEvent): void;
|
|
1531
|
+
/**
|
|
1532
|
+
* Expands a previously compacted message to its original content.
|
|
1533
|
+
*
|
|
1534
|
+
* @param request - The expand message request
|
|
1535
|
+
* @param params - Agent execution parameters
|
|
1536
|
+
* @param currentTurn - Current turn number
|
|
1537
|
+
* @protected
|
|
1538
|
+
*/
|
|
221
1539
|
protected executeExpandMessageStep(request: BaseAgentNextStep, params: ExecuteAgentParams, currentTurn: number): void;
|
|
1540
|
+
/**
|
|
1541
|
+
* Generic template resolver for loop iterations - extracts from LoopAgentType to make available to all agent types
|
|
1542
|
+
* Resolves templates like {{item.field}}, {{index}}, etc. in action parameters and sub-agent payloads
|
|
1543
|
+
*/
|
|
222
1544
|
protected resolveTemplates(obj: Record<string, unknown>, context: Record<string, any>, itemVariable: string): Record<string, unknown>;
|
|
1545
|
+
/**
|
|
1546
|
+
* Resolves a value from context using variable references - extracts from LoopAgentType
|
|
1547
|
+
*
|
|
1548
|
+
* This method handles both scalar and complex object iterations in ForEach/While loops.
|
|
1549
|
+
*
|
|
1550
|
+
* Examples:
|
|
1551
|
+
*
|
|
1552
|
+
* Scalar array iteration:
|
|
1553
|
+
* candidateEntities = ["Users", "Companies", "Invoices"]
|
|
1554
|
+
* itemVariable = "entityName"
|
|
1555
|
+
* Template: "{{entityName}}" → resolves to "Users", then "Companies", then "Invoices"
|
|
1556
|
+
*
|
|
1557
|
+
* Object array iteration:
|
|
1558
|
+
* users = [{name: "Alice", age: 30}, {name: "Bob", age: 25}]
|
|
1559
|
+
* itemVariable = "user"
|
|
1560
|
+
* Template: "{{user.name}}" → resolves to "Alice", then "Bob"
|
|
1561
|
+
* Template: "{{user}}" → resolves to entire object {name: "Alice", age: 30}
|
|
1562
|
+
*/
|
|
223
1563
|
protected resolveValueFromContext(value: string, context: Record<string, any>, itemVariable: string): any;
|
|
1564
|
+
/**
|
|
1565
|
+
* Helper to get value from nested object path - extracts from LoopAgentType
|
|
1566
|
+
*/
|
|
224
1567
|
protected getValueFromPath(obj: any, path: string): unknown;
|
|
225
1568
|
}
|
|
226
1569
|
//# sourceMappingURL=base-agent.d.ts.map
|