@memberjunction/ai-agents 6.2.2 → 6.3.0-edge.1

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.
Files changed (250) hide show
  1. package/README.md +29 -6
  2. package/dist/AgentContextAssembler.d.ts +127 -0
  3. package/dist/AgentContextAssembler.d.ts.map +1 -0
  4. package/dist/AgentContextAssembler.js +482 -0
  5. package/dist/AgentContextAssembler.js.map +1 -0
  6. package/dist/AgentDataPreloader.d.ts +14 -3
  7. package/dist/AgentDataPreloader.d.ts.map +1 -1
  8. package/dist/AgentDataPreloader.js +147 -22
  9. package/dist/AgentDataPreloader.js.map +1 -1
  10. package/dist/AgentDecisionService.d.ts +10 -1
  11. package/dist/AgentDecisionService.d.ts.map +1 -1
  12. package/dist/AgentDecisionService.js +28 -13
  13. package/dist/AgentDecisionService.js.map +1 -1
  14. package/dist/AgentFeedbackCoordinator.d.ts +169 -0
  15. package/dist/AgentFeedbackCoordinator.d.ts.map +1 -0
  16. package/dist/AgentFeedbackCoordinator.js +593 -0
  17. package/dist/AgentFeedbackCoordinator.js.map +1 -0
  18. package/dist/AgentRunner.d.ts +57 -15
  19. package/dist/AgentRunner.d.ts.map +1 -1
  20. package/dist/AgentRunner.js +692 -101
  21. package/dist/AgentRunner.js.map +1 -1
  22. package/dist/AgentStepDispatcher.d.ts +211 -0
  23. package/dist/AgentStepDispatcher.d.ts.map +1 -0
  24. package/dist/AgentStepDispatcher.js +729 -0
  25. package/dist/AgentStepDispatcher.js.map +1 -0
  26. package/dist/AgentTreeBudgetTracker.d.ts +163 -0
  27. package/dist/AgentTreeBudgetTracker.d.ts.map +1 -0
  28. package/dist/AgentTreeBudgetTracker.js +415 -0
  29. package/dist/AgentTreeBudgetTracker.js.map +1 -0
  30. package/dist/AgentWakeTriggerService.d.ts +41 -1
  31. package/dist/AgentWakeTriggerService.d.ts.map +1 -1
  32. package/dist/AgentWakeTriggerService.js +154 -8
  33. package/dist/AgentWakeTriggerService.js.map +1 -1
  34. package/dist/ArtifactToolManager.d.ts +134 -39
  35. package/dist/ArtifactToolManager.d.ts.map +1 -1
  36. package/dist/ArtifactToolManager.js +2761 -321
  37. package/dist/ArtifactToolManager.js.map +1 -1
  38. package/dist/GovernedArtifactService.d.ts +367 -0
  39. package/dist/GovernedArtifactService.d.ts.map +1 -0
  40. package/dist/GovernedArtifactService.js +2569 -0
  41. package/dist/GovernedArtifactService.js.map +1 -0
  42. package/dist/MJAIAgentRequestEntityServer.d.ts +32 -1
  43. package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
  44. package/dist/MJAIAgentRequestEntityServer.js +105 -3
  45. package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
  46. package/dist/SkillMarkdownConverter.d.ts +1 -1
  47. package/dist/SkillMarkdownConverter.d.ts.map +1 -1
  48. package/dist/SkillMarkdownConverter.js +8 -6
  49. package/dist/SkillMarkdownConverter.js.map +1 -1
  50. package/dist/agent-context-injector.d.ts +2 -25
  51. package/dist/agent-context-injector.d.ts.map +1 -1
  52. package/dist/agent-context-injector.js +38 -153
  53. package/dist/agent-context-injector.js.map +1 -1
  54. package/dist/agent-instance.d.ts +28 -0
  55. package/dist/agent-instance.d.ts.map +1 -0
  56. package/dist/agent-instance.js +39 -0
  57. package/dist/agent-instance.js.map +1 -0
  58. package/dist/agent-memory-context-builder.d.ts.map +1 -1
  59. package/dist/agent-memory-context-builder.js +46 -42
  60. package/dist/agent-memory-context-builder.js.map +1 -1
  61. package/dist/agent-pre-execution-rag.d.ts +5 -0
  62. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  63. package/dist/agent-pre-execution-rag.js +10 -0
  64. package/dist/agent-pre-execution-rag.js.map +1 -1
  65. package/dist/agent-run-watchdog.d.ts +38 -6
  66. package/dist/agent-run-watchdog.d.ts.map +1 -1
  67. package/dist/agent-run-watchdog.js +75 -13
  68. package/dist/agent-run-watchdog.js.map +1 -1
  69. package/dist/agent-types/flow-agent-type.d.ts +6 -1
  70. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  71. package/dist/agent-types/flow-agent-type.js +30 -7
  72. package/dist/agent-types/flow-agent-type.js.map +1 -1
  73. package/dist/agent-types/loop-agent-prompt-params.d.ts +18 -0
  74. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  75. package/dist/agent-types/loop-agent-prompt-params.js +2 -0
  76. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  77. package/dist/agent-types/loop-agent-type.d.ts +4 -0
  78. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  79. package/dist/agent-types/loop-agent-type.js +29 -0
  80. package/dist/agent-types/loop-agent-type.js.map +1 -1
  81. package/dist/artifact-presence-locator.d.ts +132 -0
  82. package/dist/artifact-presence-locator.d.ts.map +1 -0
  83. package/dist/artifact-presence-locator.js +472 -0
  84. package/dist/artifact-presence-locator.js.map +1 -0
  85. package/dist/artifact-tools/CSVToolLibrary.d.ts +2 -2
  86. package/dist/artifact-tools/CSVToolLibrary.d.ts.map +1 -1
  87. package/dist/artifact-tools/CSVToolLibrary.js +41 -14
  88. package/dist/artifact-tools/CSVToolLibrary.js.map +1 -1
  89. package/dist/artifact-tools/DataSnapshotToolLibrary.d.ts +2 -2
  90. package/dist/artifact-tools/DataSnapshotToolLibrary.d.ts.map +1 -1
  91. package/dist/artifact-tools/DataSnapshotToolLibrary.js +53 -21
  92. package/dist/artifact-tools/DataSnapshotToolLibrary.js.map +1 -1
  93. package/dist/artifact-tools/DocumentToolLibrary.d.ts +101 -0
  94. package/dist/artifact-tools/DocumentToolLibrary.d.ts.map +1 -0
  95. package/dist/artifact-tools/DocumentToolLibrary.js +1846 -0
  96. package/dist/artifact-tools/DocumentToolLibrary.js.map +1 -0
  97. package/dist/artifact-tools/DocxToolLibrary.d.ts +2 -4
  98. package/dist/artifact-tools/DocxToolLibrary.d.ts.map +1 -1
  99. package/dist/artifact-tools/DocxToolLibrary.js +42 -30
  100. package/dist/artifact-tools/DocxToolLibrary.js.map +1 -1
  101. package/dist/artifact-tools/ExcelToolLibrary.d.ts +2 -3
  102. package/dist/artifact-tools/ExcelToolLibrary.d.ts.map +1 -1
  103. package/dist/artifact-tools/ExcelToolLibrary.js +105 -49
  104. package/dist/artifact-tools/ExcelToolLibrary.js.map +1 -1
  105. package/dist/artifact-tools/GenericBinaryToolLibrary.d.ts +2 -2
  106. package/dist/artifact-tools/GenericBinaryToolLibrary.d.ts.map +1 -1
  107. package/dist/artifact-tools/GenericBinaryToolLibrary.js +3 -2
  108. package/dist/artifact-tools/GenericBinaryToolLibrary.js.map +1 -1
  109. package/dist/artifact-tools/JSONToolLibrary.d.ts +4 -4
  110. package/dist/artifact-tools/JSONToolLibrary.d.ts.map +1 -1
  111. package/dist/artifact-tools/JSONToolLibrary.js +32 -11
  112. package/dist/artifact-tools/JSONToolLibrary.js.map +1 -1
  113. package/dist/artifact-tools/PDFToolLibrary.d.ts +27 -3
  114. package/dist/artifact-tools/PDFToolLibrary.d.ts.map +1 -1
  115. package/dist/artifact-tools/PDFToolLibrary.js +36 -21
  116. package/dist/artifact-tools/PDFToolLibrary.js.map +1 -1
  117. package/dist/artifact-tools/SearchResultSetToolLibrary.d.ts +2 -2
  118. package/dist/artifact-tools/SearchResultSetToolLibrary.d.ts.map +1 -1
  119. package/dist/artifact-tools/SearchResultSetToolLibrary.js +83 -24
  120. package/dist/artifact-tools/SearchResultSetToolLibrary.js.map +1 -1
  121. package/dist/artifact-tools/SlideDeckToolLibrary.d.ts +50 -0
  122. package/dist/artifact-tools/SlideDeckToolLibrary.d.ts.map +1 -0
  123. package/dist/artifact-tools/SlideDeckToolLibrary.js +1617 -0
  124. package/dist/artifact-tools/SlideDeckToolLibrary.js.map +1 -0
  125. package/dist/artifact-tools/SpreadsheetToolLibrary.d.ts +87 -0
  126. package/dist/artifact-tools/SpreadsheetToolLibrary.d.ts.map +1 -0
  127. package/dist/artifact-tools/SpreadsheetToolLibrary.js +3351 -0
  128. package/dist/artifact-tools/SpreadsheetToolLibrary.js.map +1 -0
  129. package/dist/artifact-tools/TextToolLibrary.d.ts +3 -3
  130. package/dist/artifact-tools/TextToolLibrary.d.ts.map +1 -1
  131. package/dist/artifact-tools/TextToolLibrary.js +34 -24
  132. package/dist/artifact-tools/TextToolLibrary.js.map +1 -1
  133. package/dist/artifact-tools/WhiteboardToolLibrary.d.ts +69 -0
  134. package/dist/artifact-tools/WhiteboardToolLibrary.d.ts.map +1 -0
  135. package/dist/artifact-tools/WhiteboardToolLibrary.js +555 -0
  136. package/dist/artifact-tools/WhiteboardToolLibrary.js.map +1 -0
  137. package/dist/artifact-tools/artifact-comment-suggestion-helper.d.ts +98 -0
  138. package/dist/artifact-tools/artifact-comment-suggestion-helper.d.ts.map +1 -0
  139. package/dist/artifact-tools/artifact-comment-suggestion-helper.js +851 -0
  140. package/dist/artifact-tools/artifact-comment-suggestion-helper.js.map +1 -0
  141. package/dist/artifact-tools/artifact-tool-helpers.d.ts +21 -0
  142. package/dist/artifact-tools/artifact-tool-helpers.d.ts.map +1 -0
  143. package/dist/artifact-tools/artifact-tool-helpers.js +74 -0
  144. package/dist/artifact-tools/artifact-tool-helpers.js.map +1 -0
  145. package/dist/artifact-tools/grepHelper.d.ts +27 -0
  146. package/dist/artifact-tools/grepHelper.d.ts.map +1 -0
  147. package/dist/artifact-tools/grepHelper.js +229 -0
  148. package/dist/artifact-tools/grepHelper.js.map +1 -0
  149. package/dist/artifact-tools/node-vm-safe-regex.d.ts +10 -0
  150. package/dist/artifact-tools/node-vm-safe-regex.d.ts.map +1 -0
  151. package/dist/artifact-tools/node-vm-safe-regex.js +148 -0
  152. package/dist/artifact-tools/node-vm-safe-regex.js.map +1 -0
  153. package/dist/base-agent.d.ts +151 -137
  154. package/dist/base-agent.d.ts.map +1 -1
  155. package/dist/base-agent.js +727 -1550
  156. package/dist/base-agent.js.map +1 -1
  157. package/dist/catalog-narrowing.d.ts +112 -5
  158. package/dist/catalog-narrowing.d.ts.map +1 -1
  159. package/dist/catalog-narrowing.js +181 -6
  160. package/dist/catalog-narrowing.js.map +1 -1
  161. package/dist/decision-discovery.d.ts +42 -15
  162. package/dist/decision-discovery.d.ts.map +1 -1
  163. package/dist/decision-discovery.js +90 -20
  164. package/dist/decision-discovery.js.map +1 -1
  165. package/dist/index.d.ts +17 -2
  166. package/dist/index.d.ts.map +1 -1
  167. package/dist/index.js +17 -3
  168. package/dist/index.js.map +1 -1
  169. package/dist/memory-decision-uses.d.ts +206 -0
  170. package/dist/memory-decision-uses.d.ts.map +1 -0
  171. package/dist/memory-decision-uses.js +259 -0
  172. package/dist/memory-decision-uses.js.map +1 -0
  173. package/dist/memory-manager-agent.d.ts +66 -6
  174. package/dist/memory-manager-agent.d.ts.map +1 -1
  175. package/dist/memory-manager-agent.js +184 -31
  176. package/dist/memory-manager-agent.js.map +1 -1
  177. package/dist/memory-note-gate.d.ts +12 -9
  178. package/dist/memory-note-gate.d.ts.map +1 -1
  179. package/dist/memory-note-gate.js +16 -11
  180. package/dist/memory-note-gate.js.map +1 -1
  181. package/dist/native-tools/control-tools.d.ts +8 -1
  182. package/dist/native-tools/control-tools.d.ts.map +1 -1
  183. package/dist/native-tools/control-tools.js +38 -5
  184. package/dist/native-tools/control-tools.js.map +1 -1
  185. package/dist/native-tools/framework-tools.d.ts +3 -3
  186. package/dist/native-tools/framework-tools.d.ts.map +1 -1
  187. package/dist/native-tools/framework-tools.js +20 -8
  188. package/dist/native-tools/framework-tools.js.map +1 -1
  189. package/dist/pipeline/operators.d.ts.map +1 -1
  190. package/dist/pipeline/operators.js +1 -1
  191. package/dist/pipeline/operators.js.map +1 -1
  192. package/dist/pipeline/pipeline-executor.d.ts +29 -1
  193. package/dist/pipeline/pipeline-executor.d.ts.map +1 -1
  194. package/dist/pipeline/pipeline-executor.js +159 -2
  195. package/dist/pipeline/pipeline-executor.js.map +1 -1
  196. package/dist/pipeline/pipeline.types.d.ts +19 -1
  197. package/dist/pipeline/pipeline.types.d.ts.map +1 -1
  198. package/dist/pipeline/template.d.ts +16 -0
  199. package/dist/pipeline/template.d.ts.map +1 -1
  200. package/dist/pipeline/template.js +55 -6
  201. package/dist/pipeline/template.js.map +1 -1
  202. package/dist/realtime/artifact-workspace-channel-server.d.ts +27 -0
  203. package/dist/realtime/artifact-workspace-channel-server.d.ts.map +1 -0
  204. package/dist/realtime/artifact-workspace-channel-server.js +43 -0
  205. package/dist/realtime/artifact-workspace-channel-server.js.map +1 -0
  206. package/dist/realtime/bridge-realtime-session-factory.d.ts +2 -2
  207. package/dist/realtime/bridge-realtime-session-factory.d.ts.map +1 -1
  208. package/dist/realtime/bridge-realtime-session-factory.js +7 -56
  209. package/dist/realtime/bridge-realtime-session-factory.js.map +1 -1
  210. package/dist/realtime/bridge-room-transcript-sink.d.ts.map +1 -1
  211. package/dist/realtime/bridge-room-transcript-sink.js +28 -1
  212. package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
  213. package/dist/realtime/media-channel-server.js +1 -1
  214. package/dist/realtime/media-channel-server.js.map +1 -1
  215. package/dist/realtime/realtime-artifact-helpers.d.ts +37 -0
  216. package/dist/realtime/realtime-artifact-helpers.d.ts.map +1 -0
  217. package/dist/realtime/realtime-artifact-helpers.js +150 -0
  218. package/dist/realtime/realtime-artifact-helpers.js.map +1 -0
  219. package/dist/realtime/realtime-client-session-service.d.ts +209 -19
  220. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  221. package/dist/realtime/realtime-client-session-service.js +670 -41
  222. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  223. package/dist/realtime/realtime-coagent-config.d.ts +26 -9
  224. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  225. package/dist/realtime/realtime-coagent-config.js +47 -60
  226. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  227. package/dist/realtime/realtime-delegation-narrator.js +1 -1
  228. package/dist/realtime/realtime-delegation-narrator.js.map +1 -1
  229. package/dist/realtime/realtime-moderator-decision.d.ts +86 -0
  230. package/dist/realtime/realtime-moderator-decision.d.ts.map +1 -0
  231. package/dist/realtime/realtime-moderator-decision.js +131 -0
  232. package/dist/realtime/realtime-moderator-decision.js.map +1 -0
  233. package/dist/realtime/realtime-session-runner.d.ts +2 -0
  234. package/dist/realtime/realtime-session-runner.d.ts.map +1 -1
  235. package/dist/realtime/realtime-session-runner.js +24 -3
  236. package/dist/realtime/realtime-session-runner.js.map +1 -1
  237. package/dist/realtime/realtime-tool-broker.d.ts +6 -0
  238. package/dist/realtime/realtime-tool-broker.d.ts.map +1 -1
  239. package/dist/realtime/realtime-tool-broker.js +4 -2
  240. package/dist/realtime/realtime-tool-broker.js.map +1 -1
  241. package/dist/realtime/realtime-turn-moderator.d.ts +20 -0
  242. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  243. package/dist/realtime/realtime-turn-moderator.js +63 -8
  244. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  245. package/dist/repeated-failing-step.d.ts +50 -0
  246. package/dist/repeated-failing-step.d.ts.map +1 -0
  247. package/dist/repeated-failing-step.js +130 -0
  248. package/dist/repeated-failing-step.js.map +1 -0
  249. package/dist/tsconfig.tsbuildinfo +1 -0
  250. 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