@memberjunction/ai-agents 6.2.0 → 6.3.0-edge.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -1
- package/dist/AgentContextAssembler.d.ts +127 -0
- package/dist/AgentContextAssembler.d.ts.map +1 -0
- package/dist/AgentContextAssembler.js +482 -0
- package/dist/AgentContextAssembler.js.map +1 -0
- package/dist/AgentDataPreloader.d.ts +5 -1
- package/dist/AgentDataPreloader.d.ts.map +1 -1
- package/dist/AgentDataPreloader.js +13 -7
- package/dist/AgentDataPreloader.js.map +1 -1
- package/dist/AgentFeedbackCoordinator.d.ts +169 -0
- package/dist/AgentFeedbackCoordinator.d.ts.map +1 -0
- package/dist/AgentFeedbackCoordinator.js +593 -0
- package/dist/AgentFeedbackCoordinator.js.map +1 -0
- package/dist/AgentStepDispatcher.d.ts +211 -0
- package/dist/AgentStepDispatcher.d.ts.map +1 -0
- package/dist/AgentStepDispatcher.js +729 -0
- package/dist/AgentStepDispatcher.js.map +1 -0
- package/dist/AgentTreeBudgetTracker.d.ts +163 -0
- package/dist/AgentTreeBudgetTracker.d.ts.map +1 -0
- package/dist/AgentTreeBudgetTracker.js +415 -0
- package/dist/AgentTreeBudgetTracker.js.map +1 -0
- package/dist/AgentWakeTriggerService.d.ts +41 -1
- package/dist/AgentWakeTriggerService.d.ts.map +1 -1
- package/dist/AgentWakeTriggerService.js +154 -8
- package/dist/AgentWakeTriggerService.js.map +1 -1
- package/dist/MJAIAgentRequestEntityServer.d.ts +32 -1
- package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
- package/dist/MJAIAgentRequestEntityServer.js +105 -3
- package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
- package/dist/PayloadManager.d.ts.map +1 -1
- package/dist/PayloadManager.js +14 -1
- package/dist/PayloadManager.js.map +1 -1
- package/dist/SkillMarkdownConverter.d.ts +1 -1
- package/dist/SkillMarkdownConverter.d.ts.map +1 -1
- package/dist/SkillMarkdownConverter.js +4 -4
- package/dist/SkillMarkdownConverter.js.map +1 -1
- package/dist/agent-pre-execution-rag.d.ts +5 -0
- package/dist/agent-pre-execution-rag.d.ts.map +1 -1
- package/dist/agent-pre-execution-rag.js +5 -0
- package/dist/agent-pre-execution-rag.js.map +1 -1
- package/dist/agent-types/base-agent-type.d.ts.map +1 -1
- package/dist/agent-types/base-agent-type.js +8 -1
- package/dist/agent-types/base-agent-type.js.map +1 -1
- package/dist/agent-types/loop-agent-prompt-params.d.ts +18 -0
- package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-prompt-params.js +2 -0
- package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
- package/dist/base-agent.d.ts +105 -133
- package/dist/base-agent.d.ts.map +1 -1
- package/dist/base-agent.js +395 -1472
- package/dist/base-agent.js.map +1 -1
- package/dist/catalog-narrowing.d.ts +112 -5
- package/dist/catalog-narrowing.d.ts.map +1 -1
- package/dist/catalog-narrowing.js +181 -6
- package/dist/catalog-narrowing.js.map +1 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/dist/pipeline/operators.d.ts.map +1 -1
- package/dist/pipeline/operators.js +1 -1
- package/dist/pipeline/operators.js.map +1 -1
- package/dist/pipeline/pipeline-executor.d.ts +29 -1
- package/dist/pipeline/pipeline-executor.d.ts.map +1 -1
- package/dist/pipeline/pipeline-executor.js +159 -2
- package/dist/pipeline/pipeline-executor.js.map +1 -1
- package/dist/pipeline/pipeline.types.d.ts +19 -1
- package/dist/pipeline/pipeline.types.d.ts.map +1 -1
- package/dist/pipeline/template.d.ts +11 -0
- package/dist/pipeline/template.d.ts.map +1 -1
- package/dist/pipeline/template.js +56 -6
- package/dist/pipeline/template.js.map +1 -1
- package/dist/realtime/bridge-room-transcript-sink.d.ts.map +1 -1
- package/dist/realtime/bridge-room-transcript-sink.js +28 -1
- package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
- package/dist/realtime/media-channel-server.js +1 -1
- package/dist/realtime/media-channel-server.js.map +1 -1
- package/dist/realtime/realtime-client-session-service.d.ts +122 -2
- package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
- package/dist/realtime/realtime-client-session-service.js +413 -4
- package/dist/realtime/realtime-client-session-service.js.map +1 -1
- package/dist/realtime/realtime-coagent-config.d.ts +4 -2
- package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
- package/dist/realtime/realtime-coagent-config.js +27 -38
- package/dist/realtime/realtime-coagent-config.js.map +1 -1
- package/dist/realtime/realtime-delegation-narrator.js +1 -1
- package/dist/realtime/realtime-delegation-narrator.js.map +1 -1
- package/dist/realtime/realtime-session-runner.d.ts +2 -0
- package/dist/realtime/realtime-session-runner.d.ts.map +1 -1
- package/dist/realtime/realtime-session-runner.js +24 -3
- package/dist/realtime/realtime-session-runner.js.map +1 -1
- package/dist/unsafe-object-keys.d.ts +20 -0
- package/dist/unsafe-object-keys.d.ts.map +1 -0
- package/dist/unsafe-object-keys.js +42 -0
- package/dist/unsafe-object-keys.js.map +1 -0
- package/package.json +20 -20
|
@@ -0,0 +1,729 @@
|
|
|
1
|
+
import { LogError, ToPlainJSON } from '@memberjunction/core';
|
|
2
|
+
import { ApplyOutputMapping, BuildActionOutputObject, GetValueFromPath, SetMappedValue, } from '@memberjunction/ai-core-plus';
|
|
3
|
+
import { IsPlainObject } from '@memberjunction/global';
|
|
4
|
+
import { CrushJSON, DescribeCrush } from '@memberjunction/context-crush';
|
|
5
|
+
import { CrushCode } from '@memberjunction/context-crush/code';
|
|
6
|
+
import { FormatResponseFormSummary } from './sub-agent-consult.js';
|
|
7
|
+
import { WrapUntrustedExternalData } from './client-tool-results.js';
|
|
8
|
+
import { ConversationMessageResolver } from './utils/ConversationMessageResolver.js';
|
|
9
|
+
import { ExtractWholeTemplateExpression, ReplaceEmbeddedTemplateExpressions, } from './pipeline/template.js';
|
|
10
|
+
/**
|
|
11
|
+
* Collaborator extracted from `BaseAgent` (WS-4.5b) responsible for step and loop
|
|
12
|
+
* dispatching utilities: action/sub-agent invocation & result markdown formatting,
|
|
13
|
+
* structural JSON/code context-crush compression, sub-agent payload cloning and
|
|
14
|
+
* input/output path mapping, ForEach/While batching & sequential result folding,
|
|
15
|
+
* and loop template interpolation (`{{item.field}}`).
|
|
16
|
+
*/
|
|
17
|
+
export class AgentStepDispatcher {
|
|
18
|
+
/**
|
|
19
|
+
* Builds the `user`-role record of what the model asked to run on an Actions turn (`[You invoked ...]`).
|
|
20
|
+
*/
|
|
21
|
+
BuildActionInvocationMessage(actions, resolveShownParams) {
|
|
22
|
+
if (actions.length === 1) {
|
|
23
|
+
const aa = actions[0];
|
|
24
|
+
const shownParams = resolveShownParams(aa);
|
|
25
|
+
if (shownParams.length === 0) {
|
|
26
|
+
return `[You invoked the **${aa.name}** action.]`;
|
|
27
|
+
}
|
|
28
|
+
const paramsList = shownParams
|
|
29
|
+
.map(([key, value]) => `• **${key}**: ${this.FormatParamValueForMessage(value)}`)
|
|
30
|
+
.join('\n');
|
|
31
|
+
return `[You invoked the **${aa.name}** action with parameters:\n${paramsList}\n]`;
|
|
32
|
+
}
|
|
33
|
+
return (`[You invoked **${actions.length} actions** in parallel:\n\n` +
|
|
34
|
+
actions
|
|
35
|
+
.map((aa, index) => {
|
|
36
|
+
const actionText = `${index + 1}. **${aa.name}**`;
|
|
37
|
+
const shownParams = resolveShownParams(aa);
|
|
38
|
+
if (shownParams.length === 0) {
|
|
39
|
+
return actionText;
|
|
40
|
+
}
|
|
41
|
+
const paramsList = shownParams
|
|
42
|
+
.map(([key, value]) => ` • **${key}**: ${this.FormatParamValueForMessage(value)}`)
|
|
43
|
+
.join('\n');
|
|
44
|
+
return `${actionText}\n${paramsList}`;
|
|
45
|
+
})
|
|
46
|
+
.join('\n\n') +
|
|
47
|
+
'\n]');
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Formats an array of action result summaries as compact markdown instead of
|
|
51
|
+
* pretty-printed JSON. This typically saves 60-70% of the tokens that the
|
|
52
|
+
* old `JSON.stringify(actionSummaries, null, 2)` approach consumed, while
|
|
53
|
+
* remaining equally parseable by LLMs.
|
|
54
|
+
*
|
|
55
|
+
* Format per action:
|
|
56
|
+
* ```
|
|
57
|
+
* ## ActionName ✓ (or ✗ for failure)
|
|
58
|
+
* **Result:** RESULT_CODE — human message
|
|
59
|
+
* **Output:**
|
|
60
|
+
* • `ParamName`: value
|
|
61
|
+
* ```
|
|
62
|
+
*
|
|
63
|
+
* AI directives are intentionally omitted here because they are surfaced
|
|
64
|
+
* as a separate high-priority message (see the caller).
|
|
65
|
+
*/
|
|
66
|
+
FormatActionResultsAsMarkdown(actionSummaries, crushConfig) {
|
|
67
|
+
return actionSummaries
|
|
68
|
+
.map((a) => {
|
|
69
|
+
const marker = a.success ? '✓' : '✗';
|
|
70
|
+
const lines = [];
|
|
71
|
+
lines.push(`## ${a.actionName} ${marker}`);
|
|
72
|
+
lines.push(`**Result:** ${a.resultCode} — ${a.message || '(no message)'}`);
|
|
73
|
+
if (!a.success && a.errorRecovery) {
|
|
74
|
+
const er = a.errorRecovery;
|
|
75
|
+
if (er.Retryable !== undefined) {
|
|
76
|
+
lines.push(`**Retryable:** ${er.Retryable ? 'Yes (adjust parameters before retrying)' : 'No (do not retry this action with the same goal)'}`);
|
|
77
|
+
}
|
|
78
|
+
if (er.RecoverySuggestion) {
|
|
79
|
+
lines.push(`**How to Recover:** ${er.RecoverySuggestion}`);
|
|
80
|
+
}
|
|
81
|
+
if (er.SuggestedValues && er.SuggestedValues.length > 0) {
|
|
82
|
+
lines.push(`**Did You Mean:** ${er.SuggestedValues.map((v) => `\`${v}\``).join(', ')}`);
|
|
83
|
+
}
|
|
84
|
+
if (er.InvalidParams && er.InvalidParams.length > 0) {
|
|
85
|
+
lines.push('**Invalid Parameters:**');
|
|
86
|
+
for (const ip of er.InvalidParams) {
|
|
87
|
+
lines.push(`• \`${ip.ParamName}\`: ${ip.Reason}`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (er.ValidParameterExample) {
|
|
91
|
+
lines.push(`**Valid Example:** \`${JSON.stringify(er.ValidParameterExample)}\``);
|
|
92
|
+
}
|
|
93
|
+
if (er.SuggestedNextActions && er.SuggestedNextActions.length > 0) {
|
|
94
|
+
lines.push(`**Suggested Next Actions:** ${er.SuggestedNextActions.map((v) => `\`${v}\``).join(', ')}`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
// Format output params as bullet list. An exempt action's values go out verbatim.
|
|
98
|
+
if (a.params && a.params.length > 0) {
|
|
99
|
+
const crush = !crushConfig?.exemptActions?.has(a.actionName);
|
|
100
|
+
lines.push('**Output:**');
|
|
101
|
+
for (const p of a.params) {
|
|
102
|
+
lines.push(`• \`${p.Name}\`: ${this.FormatParamValueForResult(p.Value, 0, crush, crushConfig)}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const formatted = lines.join('\n');
|
|
106
|
+
if (a.trustLevel === 'Untrusted' || a.trustLevel === 'SemiTrusted') {
|
|
107
|
+
return WrapUntrustedExternalData(formatted, `action:${a.actionName}`, a.trustLevel);
|
|
108
|
+
}
|
|
109
|
+
return formatted;
|
|
110
|
+
})
|
|
111
|
+
.join('\n\n');
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Formats an `ExecuteAgentResult` as compact markdown for inclusion in
|
|
115
|
+
* conversation messages. Extracts only the fields that are meaningful
|
|
116
|
+
* to the calling agent (success, status, error, and payload) and
|
|
117
|
+
* presents them in a concise format.
|
|
118
|
+
*/
|
|
119
|
+
FormatSubAgentResultAsMarkdown(subAgentName, result) {
|
|
120
|
+
const marker = result.success ? '✓' : '✗';
|
|
121
|
+
const lines = [];
|
|
122
|
+
lines.push(`## Sub-agent: ${subAgentName} ${marker}`);
|
|
123
|
+
// Status / error from the agent run
|
|
124
|
+
const status = result.agentRun?.Status || (result.success ? 'Completed' : 'Failed');
|
|
125
|
+
lines.push(`**Status:** ${status}`);
|
|
126
|
+
if (result.agentRun?.FinalStep) {
|
|
127
|
+
lines.push(`**Final step:** ${result.agentRun.FinalStep}`);
|
|
128
|
+
}
|
|
129
|
+
if (result.agentRun?.Message) {
|
|
130
|
+
lines.push(`**Message:** ${result.agentRun.Message}`);
|
|
131
|
+
}
|
|
132
|
+
const formSummary = FormatResponseFormSummary(result.responseForm);
|
|
133
|
+
if (formSummary) {
|
|
134
|
+
lines.push(`**Form:**\n${formSummary}`);
|
|
135
|
+
}
|
|
136
|
+
if (!result.success && result.agentRun?.ErrorMessage) {
|
|
137
|
+
lines.push(`**Error:** ${result.agentRun.ErrorMessage}`);
|
|
138
|
+
}
|
|
139
|
+
if (result.agentRun?.Message?.trim()) {
|
|
140
|
+
lines.push(`**Message:**\n${result.agentRun.Message.trim()}`);
|
|
141
|
+
}
|
|
142
|
+
// Payload — the actual result data the parent agent cares about.
|
|
143
|
+
// Not truncated by default — the expiration/compaction lifecycle handles
|
|
144
|
+
// context window management. Truncating here permanently discards data
|
|
145
|
+
// before the LLM ever sees it.
|
|
146
|
+
if (result.payload != null) {
|
|
147
|
+
const payloadStr = typeof result.payload === 'string' ? result.payload : JSON.stringify(result.payload);
|
|
148
|
+
lines.push(`**Payload:**\n${payloadStr}`);
|
|
149
|
+
}
|
|
150
|
+
return lines.join('\n');
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Formats a single output parameter value for inclusion in action result
|
|
154
|
+
* markdown. Scalars are shown inline with backtick formatting; objects and
|
|
155
|
+
* arrays use compact (single-line) JSON to avoid the indentation overhead
|
|
156
|
+
* of pretty-printed JSON.
|
|
157
|
+
*
|
|
158
|
+
* By default, values are **not truncated** — the expiration/compaction lifecycle
|
|
159
|
+
* handles context window management. Truncating at formatting time permanently
|
|
160
|
+
* discards data before the LLM ever sees it. Pass an explicit maxLength only
|
|
161
|
+
* when you have a specific reason to limit output size.
|
|
162
|
+
*/
|
|
163
|
+
FormatParamValueForResult(value, maxLength = 0, crush = true, crushConfig) {
|
|
164
|
+
if (value === null || value === undefined) {
|
|
165
|
+
return '`null`';
|
|
166
|
+
}
|
|
167
|
+
if (typeof value === 'boolean' || typeof value === 'number') {
|
|
168
|
+
return `\`${String(value)}\``;
|
|
169
|
+
}
|
|
170
|
+
if (typeof value === 'string') {
|
|
171
|
+
// A string param may carry JSON (many actions JSON.stringify their payloads),
|
|
172
|
+
// SQL/TS code, or plain text. Try structural JSON compression first — it is a
|
|
173
|
+
// safe no-op on non-JSON (CrushParamValue's internal JSON.parse failure is
|
|
174
|
+
// caught and returns null) — then opt-in AST code reduction (SQL/TS), then pass
|
|
175
|
+
// through (optionally length-capped).
|
|
176
|
+
const crushedJson = crush ? this.CrushParamValue(value, crushConfig) : null;
|
|
177
|
+
if (crushedJson !== null) {
|
|
178
|
+
return crushedJson;
|
|
179
|
+
}
|
|
180
|
+
const crushedCode = crush ? this.CrushCodeValue(value, crushConfig) : null;
|
|
181
|
+
if (crushedCode !== null) {
|
|
182
|
+
return crushedCode;
|
|
183
|
+
}
|
|
184
|
+
return maxLength > 0 && value.length > maxLength ? `${value.substring(0, maxLength)}…` : value;
|
|
185
|
+
}
|
|
186
|
+
// Objects/arrays: compact JSON (no pretty-printing), optionally structurally
|
|
187
|
+
// compressed via context-crush when crushing is enabled and the value is large.
|
|
188
|
+
const stringValue = JSON.stringify(value);
|
|
189
|
+
const crushed = crush ? this.CrushParamValue(stringValue, crushConfig) : null;
|
|
190
|
+
if (crushed !== null) {
|
|
191
|
+
return crushed;
|
|
192
|
+
}
|
|
193
|
+
if (maxLength > 0 && stringValue.length > maxLength) {
|
|
194
|
+
return `${stringValue.substring(0, maxLength)}…`;
|
|
195
|
+
}
|
|
196
|
+
return stringValue;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Resolves the per-run action-result compression config from the agent-type prompt params.
|
|
200
|
+
*/
|
|
201
|
+
ResolveActionResultCrush(params, fallbackPromptParams, defaultThreshold) {
|
|
202
|
+
const agentTypePromptParams = (params.data?.__agentTypePromptParams ?? fallbackPromptParams);
|
|
203
|
+
if (agentTypePromptParams?.crushActionResults === false) {
|
|
204
|
+
return undefined;
|
|
205
|
+
}
|
|
206
|
+
const requestedLang = agentTypePromptParams?.crushCodeLang;
|
|
207
|
+
const codeLang = requestedLang === 'sql' || requestedLang === 'typescript' ? requestedLang : undefined;
|
|
208
|
+
const uncrushed = agentTypePromptParams?.uncrushedActions;
|
|
209
|
+
const exemptActions = new Set(Array.isArray(uncrushed)
|
|
210
|
+
? uncrushed.filter((name) => typeof name === 'string')
|
|
211
|
+
: []);
|
|
212
|
+
return { threshold: defaultThreshold, maxChars: undefined, codeLang, exemptActions };
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* AST-reduce a large code-string action-result value when the agent opted into a code
|
|
216
|
+
* language (via `crushCodeLang` or a subclass override) and the value clears the size
|
|
217
|
+
* threshold. Returns reduced code plus a one-line legend, or null to keep the string
|
|
218
|
+
* verbatim (crushing disabled, too small, or no net saving).
|
|
219
|
+
*
|
|
220
|
+
* token optimization via @memberjunction/context-crush (CodeCompressor-inspired)
|
|
221
|
+
*/
|
|
222
|
+
CrushCodeValue(stringValue, config) {
|
|
223
|
+
if (!config || !config.codeLang || stringValue.length < config.threshold) {
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
// Crushing is a best-effort optimization — it must never break an agent turn. Any
|
|
227
|
+
// failure falls back to the verbatim value.
|
|
228
|
+
try {
|
|
229
|
+
const result = CrushCode(stringValue, config.codeLang);
|
|
230
|
+
if (result.CrushedChars >= result.OriginalChars) {
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
const legend = DescribeCrush(result);
|
|
234
|
+
return legend ? `${result.Text}\n ↳ ${legend}` : result.Text;
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Structurally compress a JSON action-result value when crushing is enabled for the run
|
|
242
|
+
* and the value clears the size threshold. Accepts either the `JSON.stringify` of an
|
|
243
|
+
* object/array param, or a raw string param that itself contains JSON (many actions
|
|
244
|
+
* stringify their payloads, e.g. `run-adhoc-query`'s `Results`). Returns crushed text
|
|
245
|
+
* plus a one-line legend, or null when crushing is disabled, the value is too small, the
|
|
246
|
+
* value isn't valid JSON, or compression wouldn't actually save characters — so callers
|
|
247
|
+
* fall back to verbatim (and, for strings, to code crushing) behavior.
|
|
248
|
+
*
|
|
249
|
+
* token optimization via @memberjunction/context-crush (SmartCrusher-inspired)
|
|
250
|
+
*/
|
|
251
|
+
CrushParamValue(stringValue, config) {
|
|
252
|
+
if (!config || stringValue.length < config.threshold) {
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
// Crushing is a best-effort optimization — it must never break an agent turn. Any
|
|
256
|
+
// failure (non-JSON input, pathologically deep payloads) falls back to verbatim.
|
|
257
|
+
try {
|
|
258
|
+
// Parse to a plain JSON value. This is the JSON.stringify of an object/array
|
|
259
|
+
// param, or a raw string param that contains JSON; non-JSON strings throw here
|
|
260
|
+
// and are caught below (caller then tries code crushing / verbatim).
|
|
261
|
+
const json = JSON.parse(stringValue);
|
|
262
|
+
const result = CrushJSON(json, { MaxChars: config.maxChars });
|
|
263
|
+
if (result.CrushedChars >= result.OriginalChars) {
|
|
264
|
+
return null; // no net saving — keep the verbatim JSON
|
|
265
|
+
}
|
|
266
|
+
const legend = DescribeCrush(result);
|
|
267
|
+
return legend ? `${result.Text}\n ↳ ${legend}` : result.Text;
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Formats a parameter value for display in action execution messages.
|
|
275
|
+
*/
|
|
276
|
+
FormatParamValueForMessage(value, maxLength = 100) {
|
|
277
|
+
if (value === null || value === undefined) {
|
|
278
|
+
return 'null';
|
|
279
|
+
}
|
|
280
|
+
let stringValue;
|
|
281
|
+
if (typeof value === 'string') {
|
|
282
|
+
stringValue = value;
|
|
283
|
+
}
|
|
284
|
+
else if (typeof value === 'object') {
|
|
285
|
+
stringValue = JSON.stringify(value);
|
|
286
|
+
}
|
|
287
|
+
else {
|
|
288
|
+
stringValue = String(value);
|
|
289
|
+
}
|
|
290
|
+
if (stringValue.length > maxLength) {
|
|
291
|
+
return `\`${stringValue.substring(0, maxLength)}...\``;
|
|
292
|
+
}
|
|
293
|
+
return `\`${stringValue}\``;
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Best-effort deep clone for sub-agent payloads using `structuredClone` with `ToPlainJSON` fallback.
|
|
297
|
+
*/
|
|
298
|
+
CloneSubAgentPayload(payload) {
|
|
299
|
+
if (payload === null || payload === undefined)
|
|
300
|
+
return payload;
|
|
301
|
+
if (typeof payload !== 'object')
|
|
302
|
+
return payload;
|
|
303
|
+
if (typeof globalThis.structuredClone === 'function') {
|
|
304
|
+
try {
|
|
305
|
+
return globalThis.structuredClone(payload);
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
// DataCloneError — typically a Proxy (a live JSONType `<Field>Object` view) or an
|
|
309
|
+
// object holding functions. Fall through to the JSON clone below; returning the
|
|
310
|
+
// original here would silently give the sub-agent the caller's LIVE object and lose
|
|
311
|
+
// payload isolation.
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
try {
|
|
315
|
+
return ToPlainJSON(payload);
|
|
316
|
+
}
|
|
317
|
+
catch (error) {
|
|
318
|
+
LogError(`BaseAgent.cloneSubAgentPayload: payload could not be cloned (${error instanceof Error ? error.message : String(error)}); sub-agent will share the caller's object`);
|
|
319
|
+
return payload;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Applies sub-agent output mapping to update the parent payload.
|
|
324
|
+
*/
|
|
325
|
+
ApplySubAgentOutputMapping(subAgentResult, _parentPayload, mappingConfig, getPathFn) {
|
|
326
|
+
const pathGetter = getPathFn ?? GetValueFromPath;
|
|
327
|
+
try {
|
|
328
|
+
const mapping = JSON.parse(mappingConfig);
|
|
329
|
+
const updateObj = {};
|
|
330
|
+
for (const [subAgentPath, parentPath] of Object.entries(mapping)) {
|
|
331
|
+
let value;
|
|
332
|
+
if (subAgentPath === '*') {
|
|
333
|
+
value = subAgentResult;
|
|
334
|
+
}
|
|
335
|
+
else {
|
|
336
|
+
value = pathGetter(subAgentResult, subAgentPath);
|
|
337
|
+
}
|
|
338
|
+
if (value !== undefined) {
|
|
339
|
+
const pathParts = parentPath.split('.');
|
|
340
|
+
const hasBlockedSegment = pathParts.some((p) => {
|
|
341
|
+
const clean = p.endsWith('[]') ? p.slice(0, -2) : p;
|
|
342
|
+
return clean === '__proto__' || clean === 'constructor' || clean === 'prototype';
|
|
343
|
+
});
|
|
344
|
+
if (hasBlockedSegment) {
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
let current = updateObj;
|
|
348
|
+
for (let i = 0; i < pathParts.length - 1; i++) {
|
|
349
|
+
const part = pathParts[i];
|
|
350
|
+
const cleanPart = part.endsWith('[]') ? part.slice(0, -2) : part;
|
|
351
|
+
if (!Object.prototype.hasOwnProperty.call(current, cleanPart)) {
|
|
352
|
+
current[cleanPart] = {};
|
|
353
|
+
}
|
|
354
|
+
current = current[cleanPart];
|
|
355
|
+
}
|
|
356
|
+
const lastPart = pathParts[pathParts.length - 1];
|
|
357
|
+
SetMappedValue(current, lastPart, value);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
if (Object.keys(updateObj).length === 0) {
|
|
361
|
+
return null;
|
|
362
|
+
}
|
|
363
|
+
return {
|
|
364
|
+
updateElements: updateObj,
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
catch (error) {
|
|
368
|
+
LogError(`Failed to parse SubAgentOutputMapping: ${error instanceof Error ? error.message : String(error)}`);
|
|
369
|
+
return null;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Applies sub-agent input mapping to prepare initial payload for a related sub-agent.
|
|
374
|
+
*/
|
|
375
|
+
ApplySubAgentInputMapping(parentPayload, mappingConfig, getPathFn) {
|
|
376
|
+
const pathGetter = getPathFn ?? GetValueFromPath;
|
|
377
|
+
try {
|
|
378
|
+
const mapping = JSON.parse(mappingConfig);
|
|
379
|
+
const subAgentPayload = {};
|
|
380
|
+
for (const [parentPath, subAgentPath] of Object.entries(mapping)) {
|
|
381
|
+
let value;
|
|
382
|
+
if (parentPath === '*') {
|
|
383
|
+
value = parentPayload;
|
|
384
|
+
}
|
|
385
|
+
else {
|
|
386
|
+
value = pathGetter(parentPayload, parentPath);
|
|
387
|
+
}
|
|
388
|
+
if (value !== undefined) {
|
|
389
|
+
const pathParts = subAgentPath.split('.');
|
|
390
|
+
const hasBlockedSegment = pathParts.some((p) => {
|
|
391
|
+
const clean = p.endsWith('[]') ? p.slice(0, -2) : p;
|
|
392
|
+
return clean === '__proto__' || clean === 'constructor' || clean === 'prototype';
|
|
393
|
+
});
|
|
394
|
+
if (hasBlockedSegment) {
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
let current = subAgentPayload;
|
|
398
|
+
for (let i = 0; i < pathParts.length - 1; i++) {
|
|
399
|
+
const part = pathParts[i];
|
|
400
|
+
if (!Object.prototype.hasOwnProperty.call(current, part)) {
|
|
401
|
+
current[part] = {};
|
|
402
|
+
}
|
|
403
|
+
current = current[part];
|
|
404
|
+
}
|
|
405
|
+
const lastPart = pathParts[pathParts.length - 1];
|
|
406
|
+
current[lastPart] = value;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
if (Object.keys(subAgentPayload).length === 0) {
|
|
410
|
+
return null;
|
|
411
|
+
}
|
|
412
|
+
return subAgentPayload;
|
|
413
|
+
}
|
|
414
|
+
catch (error) {
|
|
415
|
+
LogError(`Failed to parse SubAgentInputMapping: ${error instanceof Error ? error.message : String(error)}`);
|
|
416
|
+
return null;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* Prepares a context message containing parent payload data or conversation messages for a related sub-agent.
|
|
421
|
+
*/
|
|
422
|
+
PrepareRelatedSubAgentContextMessage(parentPayload, contextPaths, params, getPathFn) {
|
|
423
|
+
if (!contextPaths || contextPaths.length === 0) {
|
|
424
|
+
return null;
|
|
425
|
+
}
|
|
426
|
+
if (contextPaths.includes('*')) {
|
|
427
|
+
return {
|
|
428
|
+
role: 'user',
|
|
429
|
+
content: `Parent Agent Context:\n\n${JSON.stringify(parentPayload, null, 2)}`,
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
const pathGetter = getPathFn ?? GetValueFromPath;
|
|
433
|
+
const contextData = {};
|
|
434
|
+
for (const path of contextPaths) {
|
|
435
|
+
let value;
|
|
436
|
+
if (ConversationMessageResolver.isConversationReference(path) && params?.conversationMessages) {
|
|
437
|
+
value = ConversationMessageResolver.resolve(path, params.conversationMessages);
|
|
438
|
+
}
|
|
439
|
+
else {
|
|
440
|
+
value = pathGetter(parentPayload, path);
|
|
441
|
+
}
|
|
442
|
+
if (value !== undefined) {
|
|
443
|
+
contextData[path] = value;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
if (Object.keys(contextData).length === 0) {
|
|
447
|
+
return null;
|
|
448
|
+
}
|
|
449
|
+
const contextLines = Object.entries(contextData).map(([key, value]) => {
|
|
450
|
+
const valueStr = typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value);
|
|
451
|
+
return `${key}:\n${valueStr}`;
|
|
452
|
+
});
|
|
453
|
+
return {
|
|
454
|
+
role: 'user',
|
|
455
|
+
content: `Parent Agent Context:\n\n${contextLines.join('\n\n')}`,
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Validates a `WhileOperation` header and delegates body validation.
|
|
460
|
+
*/
|
|
461
|
+
ValidateWhileOperation(whileOp, validateLoopBody) {
|
|
462
|
+
if (!whileOp.condition || whileOp.condition.trim() === '') {
|
|
463
|
+
return 'Condition is required';
|
|
464
|
+
}
|
|
465
|
+
if (!whileOp.itemVariable || whileOp.itemVariable.trim() === '') {
|
|
466
|
+
return 'Item variable is required';
|
|
467
|
+
}
|
|
468
|
+
return validateLoopBody('While', whileOp);
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Validates a `ForEachOperation` header (`itemVariable` and `collectionPath`).
|
|
472
|
+
*/
|
|
473
|
+
ValidateForEachHeader(forEach) {
|
|
474
|
+
if (!forEach.itemVariable || forEach.itemVariable.trim() === '') {
|
|
475
|
+
return 'Item variable is required';
|
|
476
|
+
}
|
|
477
|
+
if (!forEach.collectionPath || forEach.collectionPath.trim() === '') {
|
|
478
|
+
return 'Collection path is required';
|
|
479
|
+
}
|
|
480
|
+
return null;
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Extracts an array collection from a payload path or a `static:[...]` literal.
|
|
484
|
+
* Strips `"payload."` prefix if present (for LLM convenience).
|
|
485
|
+
*/
|
|
486
|
+
GetCollectionFromPayload(payload, path, getPathFn) {
|
|
487
|
+
// Support a literal static collection: "static:[1,2,3,4,5]". This lets a ForEach iterate a
|
|
488
|
+
// fixed list/range without a prior step having to build the array in the payload first.
|
|
489
|
+
const trimmed = path.trim();
|
|
490
|
+
if (trimmed.toLowerCase().startsWith('static:')) {
|
|
491
|
+
try {
|
|
492
|
+
const parsed = JSON.parse(trimmed.substring(trimmed.indexOf(':') + 1).trim());
|
|
493
|
+
return Array.isArray(parsed) ? parsed : null;
|
|
494
|
+
}
|
|
495
|
+
catch {
|
|
496
|
+
return null;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
const pathGetter = getPathFn ?? GetValueFromPath;
|
|
500
|
+
const cleanPath = path.toLowerCase().startsWith('payload.') ? path.substring(8) : path;
|
|
501
|
+
const value = pathGetter(payload, cleanPath);
|
|
502
|
+
return Array.isArray(value) ? value : null;
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Creates batches of items for parallel `ForEach` processing with their original indices.
|
|
506
|
+
*/
|
|
507
|
+
CreateBatches(items, maxConcurrency) {
|
|
508
|
+
const batches = [];
|
|
509
|
+
for (let i = 0; i < items.length; i += maxConcurrency) {
|
|
510
|
+
const batch = items.slice(i, i + maxConcurrency).map((item, batchOffset) => ({
|
|
511
|
+
item,
|
|
512
|
+
index: i + batchOffset,
|
|
513
|
+
}));
|
|
514
|
+
batches.push(batch);
|
|
515
|
+
}
|
|
516
|
+
return batches;
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Applies `ForEach` results sequentially to build the final payload in index order.
|
|
520
|
+
*/
|
|
521
|
+
ApplyForEachResultsSequentially(sortedResults, initialPayload, continueOnError, clonePayloadFn) {
|
|
522
|
+
let currentPayload = initialPayload;
|
|
523
|
+
const results = [];
|
|
524
|
+
const errors = [];
|
|
525
|
+
for (const { result, error, payload, appliedFolds } of sortedResults) {
|
|
526
|
+
if (error) {
|
|
527
|
+
errors.push(error);
|
|
528
|
+
if (!continueOnError) {
|
|
529
|
+
break;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
else if (result) {
|
|
533
|
+
results.push(result);
|
|
534
|
+
if (appliedFolds && appliedFolds.length > 0) {
|
|
535
|
+
for (const fold of appliedFolds) {
|
|
536
|
+
currentPayload = this.ApplyLoopOutputFold(currentPayload, fold.output, fold.mapping, clonePayloadFn);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
else {
|
|
540
|
+
currentPayload = payload || currentPayload;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
return { results, errors, finalPayload: currentPayload };
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* Extracts the output object from the first action result summary for loop output folding.
|
|
548
|
+
*/
|
|
549
|
+
ExtractActionOutputObject(summaries) {
|
|
550
|
+
return BuildActionOutputObject(summaries[0]?.params, summaries[0]?.message);
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Applies an action output mapping fold onto a cloned copy of `basePayload`.
|
|
554
|
+
*/
|
|
555
|
+
ApplyLoopOutputFold(basePayload, output, mapping, clonePayloadFn) {
|
|
556
|
+
const clone = clonePayloadFn ?? ((p) => this.CloneSubAgentPayload(p));
|
|
557
|
+
const target = IsPlainObject(basePayload)
|
|
558
|
+
? clone(basePayload)
|
|
559
|
+
: {};
|
|
560
|
+
const mapped = ApplyOutputMapping(output, mapping, target);
|
|
561
|
+
return mapped.updates;
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Formats a single loop iteration error as a string.
|
|
565
|
+
*/
|
|
566
|
+
DescribeLoopError(err) {
|
|
567
|
+
return err.message ? err.message : JSON.stringify(err);
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* Formats all loop errors as newline-separated text for a step's `ErrorMessage`.
|
|
571
|
+
*/
|
|
572
|
+
FormatLoopErrors(errors) {
|
|
573
|
+
return errors.map((err) => this.DescribeLoopError(err)).join('\n\n');
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* Formats loop iteration results as markdown. Handles two distinct result shapes
|
|
577
|
+
* depending on whether the loop body executed actions or sub-agents:
|
|
578
|
+
*
|
|
579
|
+
* - **Action iterations**: `priorStepResult` is an `ActionResultSummary[]`, set by
|
|
580
|
+
* `executeActionsStep()`. These are formatted via `FormatActionResultsAsMarkdown()`
|
|
581
|
+
* (or `formatActionResultsFn` when supplied by `BaseAgent`).
|
|
582
|
+
*
|
|
583
|
+
* - **Sub-agent iterations**: `priorStepResult` is a **pre-formatted markdown string**,
|
|
584
|
+
* set by the loop handlers (`executeSingleForEachIteration` / `executeSingleWhileIteration`)
|
|
585
|
+
* which call `formatSubAgentResultAsMarkdown()` and assign the result to `priorStepResult`.
|
|
586
|
+
* Since the markdown is already rendered upstream, this method simply includes it as-is.
|
|
587
|
+
*
|
|
588
|
+
* This two-path design means sub-agent formatting happens at assignment time (in the loop
|
|
589
|
+
* handler), while action formatting happens at render time (here). Both produce the same
|
|
590
|
+
* markdown style used by non-loop results, ensuring consistency across the codebase.
|
|
591
|
+
*/
|
|
592
|
+
FormatLoopResultsAsMarkdown(results, errors, crushConfig, formatActionResultsFn) {
|
|
593
|
+
const formatActions = formatActionResultsFn ??
|
|
594
|
+
((summaries) => this.FormatActionResultsAsMarkdown(summaries, crushConfig));
|
|
595
|
+
const lines = [];
|
|
596
|
+
for (let i = 0; i < results.length; i++) {
|
|
597
|
+
const iterResult = results[i].priorStepResult;
|
|
598
|
+
// Action iterations: priorStepResult is ActionResultSummary[] — format via shared helper
|
|
599
|
+
if (Array.isArray(iterResult)) {
|
|
600
|
+
lines.push(`### Iteration ${i + 1}`);
|
|
601
|
+
lines.push(formatActions(iterResult));
|
|
602
|
+
}
|
|
603
|
+
else if (iterResult != null) {
|
|
604
|
+
// Sub-agent iterations: priorStepResult is already a markdown string from
|
|
605
|
+
// formatSubAgentResultAsMarkdown() called in the loop handler. Non-string
|
|
606
|
+
// results (edge cases) are JSON-stringified as a fallback.
|
|
607
|
+
lines.push(`### Iteration ${i + 1}`);
|
|
608
|
+
const text = typeof iterResult === 'string' ? iterResult : JSON.stringify(iterResult);
|
|
609
|
+
lines.push(text);
|
|
610
|
+
}
|
|
611
|
+
// null/undefined priorStepResult: iteration produced no output — skip silently
|
|
612
|
+
}
|
|
613
|
+
if (errors.length > 0) {
|
|
614
|
+
lines.push('### Errors');
|
|
615
|
+
for (const err of errors) {
|
|
616
|
+
lines.push(`• ✗ ${this.DescribeLoopError(err)}`);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
return lines.join('\n');
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Creates a non-terminating `'Failed'` step preserving the previous decision's payload.
|
|
623
|
+
*/
|
|
624
|
+
CreateFailedStep(errorMessage, previousDecision) {
|
|
625
|
+
return {
|
|
626
|
+
step: 'Failed',
|
|
627
|
+
terminate: false,
|
|
628
|
+
errorMessage,
|
|
629
|
+
previousPayload: previousDecision.previousPayload,
|
|
630
|
+
newPayload: previousDecision.newPayload || previousDecision.previousPayload,
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* Resolves `{{variable}}` templates recursively across an object's string and array properties.
|
|
635
|
+
*
|
|
636
|
+
* `resolveValue` resolves each string; `resolveNested` resolves each nested object. `BaseAgent` binds
|
|
637
|
+
* both to its protected `resolveValueFromContext` / `resolveTemplates`, so a subclass override of
|
|
638
|
+
* either still runs at every depth. Without `resolveNested`, nested objects recurse here with the same
|
|
639
|
+
* `resolveValue`.
|
|
640
|
+
*/
|
|
641
|
+
ResolveTemplates(obj, context, itemVariable, resolveValue, resolveNested) {
|
|
642
|
+
const result = {};
|
|
643
|
+
const resolver = resolveValue ??
|
|
644
|
+
((val, ctx, itemVar) => this.ResolveValueFromContext(val, ctx, itemVar));
|
|
645
|
+
const nestedResolver = resolveNested ??
|
|
646
|
+
((nested, ctx, itemVar) => this.ResolveTemplates(nested, ctx, itemVar, resolver));
|
|
647
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
648
|
+
if (typeof value === 'string') {
|
|
649
|
+
result[key] = resolver(value, context, itemVariable);
|
|
650
|
+
}
|
|
651
|
+
else if (Array.isArray(value)) {
|
|
652
|
+
result[key] = value.map((v) => typeof v === 'string' ? resolver(v, context, itemVariable) : v);
|
|
653
|
+
}
|
|
654
|
+
else if (typeof value === 'object' && value !== null) {
|
|
655
|
+
result[key] = nestedResolver(value, context, itemVariable);
|
|
656
|
+
}
|
|
657
|
+
else {
|
|
658
|
+
result[key] = value;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
return result;
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Resolves a single string value or `{{expression}}` reference from a loop iteration context.
|
|
665
|
+
*
|
|
666
|
+
* Handles both scalar and complex object iterations in `ForEach` / `While` loops:
|
|
667
|
+
* - Single-variable `{{expr}}` can return non-string values (objects, numbers, arrays).
|
|
668
|
+
* - Mixed literal strings containing `{{expr}}` delegate to {@link ResolveInlineTemplateExpressions}
|
|
669
|
+
* and return an interpolated string.
|
|
670
|
+
* - Exact `itemVariable` match (`{{user}}` or `{{entityName}}`) returns `context.item` directly.
|
|
671
|
+
*/
|
|
672
|
+
ResolveValueFromContext(value, context, itemVariable, options) {
|
|
673
|
+
const trimmedValue = value.trim();
|
|
674
|
+
const wholeExpr = ExtractWholeTemplateExpression(trimmedValue);
|
|
675
|
+
if (wholeExpr !== null) {
|
|
676
|
+
// Single-variable case: "{{city.name}}" — strip wrappers, fall through to
|
|
677
|
+
// single-variable resolution below which can return non-string types (objects, numbers)
|
|
678
|
+
value = wholeExpr;
|
|
679
|
+
}
|
|
680
|
+
else if (trimmedValue.includes('{{')) {
|
|
681
|
+
// Inline template interpolation: "text {{var.prop}} more {{var2.field}}"
|
|
682
|
+
return options?.resolveInline
|
|
683
|
+
? options.resolveInline(trimmedValue, context, itemVariable)
|
|
684
|
+
: this.ResolveInlineTemplateExpressions(trimmedValue, context, itemVariable);
|
|
685
|
+
}
|
|
686
|
+
const pathGetter = options?.getPath ?? GetValueFromPath;
|
|
687
|
+
const ivToLower = itemVariable?.trim().toLowerCase();
|
|
688
|
+
const valueLower = value?.toLowerCase();
|
|
689
|
+
// CRITICAL: Check for exact match FIRST (handles scalar arrays and direct object references)
|
|
690
|
+
if (valueLower === ivToLower) {
|
|
691
|
+
return context.item;
|
|
692
|
+
}
|
|
693
|
+
// Check for path notation (handles property access on object arrays)
|
|
694
|
+
if (valueLower?.startsWith(`${ivToLower}.`)) {
|
|
695
|
+
const path = value.substring(ivToLower.length + 1);
|
|
696
|
+
return pathGetter(context.item, path);
|
|
697
|
+
}
|
|
698
|
+
// Check for direct context variable references (index, payload, data, etc.)
|
|
699
|
+
for (const [varName, varValue] of Object.entries(context)) {
|
|
700
|
+
if (value === varName) {
|
|
701
|
+
return varValue;
|
|
702
|
+
}
|
|
703
|
+
if (value?.trim().toLowerCase().startsWith(`${varName.toLowerCase()}.`)) {
|
|
704
|
+
const path = value.substring(varName.length + 1);
|
|
705
|
+
return pathGetter(varValue, path);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
return value;
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Resolves multiple `{{expression}}` placeholders embedded within a literal string.
|
|
712
|
+
*
|
|
713
|
+
* Unlike the single-variable path (which can return objects/numbers), this always
|
|
714
|
+
* returns a string because the resolved values are interpolated back into surrounding text.
|
|
715
|
+
*/
|
|
716
|
+
ResolveInlineTemplateExpressions(template, context, itemVariable, resolveValue) {
|
|
717
|
+
const resolver = resolveValue ??
|
|
718
|
+
((val, ctx, itemVar) => this.ResolveValueFromContext(val, ctx, itemVar));
|
|
719
|
+
return ReplaceEmbeddedTemplateExpressions(template, (expr, rawMatch) => {
|
|
720
|
+
const resolved = resolver(expr, context, itemVariable);
|
|
721
|
+
// If the expression didn't resolve (returned unchanged), keep original {{ }} for transparency
|
|
722
|
+
if (resolved === expr) {
|
|
723
|
+
return rawMatch;
|
|
724
|
+
}
|
|
725
|
+
return String(resolved ?? '');
|
|
726
|
+
});
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
//# sourceMappingURL=AgentStepDispatcher.js.map
|