@memberjunction/ai-agents 6.2.0-edge.5 → 6.2.0-edge.7

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 (165) hide show
  1. package/README.md +89 -2
  2. package/dist/AgentDataPreloader.d.ts +4 -2
  3. package/dist/AgentDataPreloader.d.ts.map +1 -1
  4. package/dist/AgentDataPreloader.js +21 -12
  5. package/dist/AgentDataPreloader.js.map +1 -1
  6. package/dist/AgentRunner.d.ts +150 -5
  7. package/dist/AgentRunner.d.ts.map +1 -1
  8. package/dist/AgentRunner.js +588 -64
  9. package/dist/AgentRunner.js.map +1 -1
  10. package/dist/AgentWakeTriggerService.d.ts +183 -0
  11. package/dist/AgentWakeTriggerService.d.ts.map +1 -0
  12. package/dist/AgentWakeTriggerService.js +485 -0
  13. package/dist/AgentWakeTriggerService.js.map +1 -0
  14. package/dist/ArtifactToolManager.d.ts +1 -0
  15. package/dist/ArtifactToolManager.d.ts.map +1 -1
  16. package/dist/ArtifactToolManager.js +5 -0
  17. package/dist/ArtifactToolManager.js.map +1 -1
  18. package/dist/ConversationToolManager.d.ts +1 -1
  19. package/dist/ConversationToolManager.d.ts.map +1 -1
  20. package/dist/ConversationToolManager.js +10 -4
  21. package/dist/ConversationToolManager.js.map +1 -1
  22. package/dist/MJAIAgentRequestEntityServer.d.ts +15 -1
  23. package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
  24. package/dist/MJAIAgentRequestEntityServer.js +63 -3
  25. package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
  26. package/dist/agent-context-injector.d.ts +21 -4
  27. package/dist/agent-context-injector.d.ts.map +1 -1
  28. package/dist/agent-context-injector.js +49 -13
  29. package/dist/agent-context-injector.js.map +1 -1
  30. package/dist/agent-memory-context-builder.js +2 -2
  31. package/dist/agent-memory-context-builder.js.map +1 -1
  32. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  33. package/dist/agent-pre-execution-rag.js +6 -8
  34. package/dist/agent-pre-execution-rag.js.map +1 -1
  35. package/dist/agent-run-watchdog.d.ts +71 -18
  36. package/dist/agent-run-watchdog.d.ts.map +1 -1
  37. package/dist/agent-run-watchdog.js +223 -90
  38. package/dist/agent-run-watchdog.js.map +1 -1
  39. package/dist/agent-types/flow-agent-type.d.ts +13 -0
  40. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  41. package/dist/agent-types/flow-agent-type.js +165 -27
  42. package/dist/agent-types/flow-agent-type.js.map +1 -1
  43. package/dist/agent-types/loop-agent-prompt-params.d.ts +32 -5
  44. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  45. package/dist/agent-types/loop-agent-prompt-params.js +5 -3
  46. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  47. package/dist/agent-types/loop-agent-response-type.d.ts +35 -4
  48. package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
  49. package/dist/agent-types/loop-agent-response-type.js +1 -1
  50. package/dist/agent-types/loop-agent-response-type.js.map +1 -1
  51. package/dist/agent-types/loop-agent-type.d.ts +103 -9
  52. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  53. package/dist/agent-types/loop-agent-type.js +351 -68
  54. package/dist/agent-types/loop-agent-type.js.map +1 -1
  55. package/dist/base-agent.d.ts +551 -44
  56. package/dist/base-agent.d.ts.map +1 -1
  57. package/dist/base-agent.js +2742 -549
  58. package/dist/base-agent.js.map +1 -1
  59. package/dist/bound-action-params.d.ts +57 -0
  60. package/dist/bound-action-params.d.ts.map +1 -0
  61. package/dist/bound-action-params.js +91 -0
  62. package/dist/bound-action-params.js.map +1 -0
  63. package/dist/catalog-narrowing.d.ts.map +1 -1
  64. package/dist/catalog-narrowing.js +6 -3
  65. package/dist/catalog-narrowing.js.map +1 -1
  66. package/dist/handoff-target.d.ts +80 -0
  67. package/dist/handoff-target.d.ts.map +1 -0
  68. package/dist/handoff-target.js +158 -0
  69. package/dist/handoff-target.js.map +1 -0
  70. package/dist/index.d.ts +7 -0
  71. package/dist/index.d.ts.map +1 -1
  72. package/dist/index.js +7 -0
  73. package/dist/index.js.map +1 -1
  74. package/dist/memory-cleanup-agent.d.ts.map +1 -1
  75. package/dist/memory-cleanup-agent.js +3 -0
  76. package/dist/memory-cleanup-agent.js.map +1 -1
  77. package/dist/memory-manager-agent.d.ts.map +1 -1
  78. package/dist/memory-manager-agent.js +8 -1
  79. package/dist/memory-manager-agent.js.map +1 -1
  80. package/dist/native-tools/action-tool-builder.d.ts +6 -0
  81. package/dist/native-tools/action-tool-builder.d.ts.map +1 -1
  82. package/dist/native-tools/action-tool-builder.js +21 -5
  83. package/dist/native-tools/action-tool-builder.js.map +1 -1
  84. package/dist/native-tools/agent-tools.d.ts +64 -0
  85. package/dist/native-tools/agent-tools.d.ts.map +1 -0
  86. package/dist/native-tools/agent-tools.js +23 -0
  87. package/dist/native-tools/agent-tools.js.map +1 -0
  88. package/dist/native-tools/control-tools.d.ts +40 -7
  89. package/dist/native-tools/control-tools.d.ts.map +1 -1
  90. package/dist/native-tools/control-tools.js +139 -50
  91. package/dist/native-tools/control-tools.js.map +1 -1
  92. package/dist/native-tools/framework-tools.d.ts +47 -0
  93. package/dist/native-tools/framework-tools.d.ts.map +1 -0
  94. package/dist/native-tools/framework-tools.js +187 -0
  95. package/dist/native-tools/framework-tools.js.map +1 -0
  96. package/dist/native-tools/native-control-config.d.ts +93 -0
  97. package/dist/native-tools/native-control-config.d.ts.map +1 -0
  98. package/dist/native-tools/native-control-config.js +104 -0
  99. package/dist/native-tools/native-control-config.js.map +1 -0
  100. package/dist/native-tools/tool-result-turns.d.ts +41 -8
  101. package/dist/native-tools/tool-result-turns.d.ts.map +1 -1
  102. package/dist/native-tools/tool-result-turns.js +76 -2
  103. package/dist/native-tools/tool-result-turns.js.map +1 -1
  104. package/dist/native-tools/turn-mode.d.ts +8 -0
  105. package/dist/native-tools/turn-mode.d.ts.map +1 -0
  106. package/dist/native-tools/turn-mode.js +14 -0
  107. package/dist/native-tools/turn-mode.js.map +1 -0
  108. package/dist/pipeline/pipeline-registry.d.ts +5 -12
  109. package/dist/pipeline/pipeline-registry.d.ts.map +1 -1
  110. package/dist/pipeline/pipeline-registry.js +28 -2
  111. package/dist/pipeline/pipeline-registry.js.map +1 -1
  112. package/dist/pipeline/providers/serialize.d.ts +7 -3
  113. package/dist/pipeline/providers/serialize.d.ts.map +1 -1
  114. package/dist/pipeline/providers/serialize.js +9 -5
  115. package/dist/pipeline/providers/serialize.js.map +1 -1
  116. package/dist/query-builder-agent.d.ts +20 -1
  117. package/dist/query-builder-agent.d.ts.map +1 -1
  118. package/dist/query-builder-agent.js +35 -3
  119. package/dist/query-builder-agent.js.map +1 -1
  120. package/dist/realtime/bridge-room-transcript-sink.js +3 -0
  121. package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
  122. package/dist/realtime/bridge-session-transcript-sink.js +1 -0
  123. package/dist/realtime/bridge-session-transcript-sink.js.map +1 -1
  124. package/dist/realtime/realtime-client-session-service.d.ts +22 -2
  125. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  126. package/dist/realtime/realtime-client-session-service.js +70 -10
  127. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  128. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  129. package/dist/realtime/realtime-coagent-config.js +2 -28
  130. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  131. package/dist/realtime/realtime-recording-capture.d.ts +1 -0
  132. package/dist/realtime/realtime-recording-capture.d.ts.map +1 -1
  133. package/dist/realtime/realtime-recording-capture.js +17 -3
  134. package/dist/realtime/realtime-recording-capture.js.map +1 -1
  135. package/dist/realtime/realtime-recording-ledger.d.ts +20 -0
  136. package/dist/realtime/realtime-recording-ledger.d.ts.map +1 -1
  137. package/dist/realtime/realtime-recording-ledger.js +16 -0
  138. package/dist/realtime/realtime-recording-ledger.js.map +1 -1
  139. package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -1
  140. package/dist/realtime/realtime-recording-opus-assembly.js +9 -4
  141. package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -1
  142. package/dist/realtime/realtime-recording-store.d.ts +6 -5
  143. package/dist/realtime/realtime-recording-store.d.ts.map +1 -1
  144. package/dist/realtime/realtime-recording-store.js +47 -21
  145. package/dist/realtime/realtime-recording-store.js.map +1 -1
  146. package/dist/realtime/realtime-session-runner.d.ts.map +1 -1
  147. package/dist/realtime/realtime-session-runner.js +5 -7
  148. package/dist/realtime/realtime-session-runner.js.map +1 -1
  149. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  150. package/dist/realtime/realtime-turn-moderator.js +1 -0
  151. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  152. package/dist/rubric-evaluation-agent-runner.js +1 -0
  153. package/dist/rubric-evaluation-agent-runner.js.map +1 -1
  154. package/dist/runtime-state-fragment.d.ts.map +1 -1
  155. package/dist/runtime-state-fragment.js +3 -0
  156. package/dist/runtime-state-fragment.js.map +1 -1
  157. package/dist/sub-agent-consult.d.ts +75 -0
  158. package/dist/sub-agent-consult.d.ts.map +1 -0
  159. package/dist/sub-agent-consult.js +193 -0
  160. package/dist/sub-agent-consult.js.map +1 -0
  161. package/dist/volatile-child-prompt.d.ts +7 -0
  162. package/dist/volatile-child-prompt.d.ts.map +1 -1
  163. package/dist/volatile-child-prompt.js +8 -0
  164. package/dist/volatile-child-prompt.js.map +1 -1
  165. package/package.json +20 -20
@@ -13,10 +13,14 @@ import { createHash } from 'crypto';
13
13
  import { LogError, LogStatusEx, IsVerboseLoggingEnabled, LogStatus, Metadata, RunView, RunQuery, ProviderType } from '@memberjunction/core';
14
14
  import { MJGlobal, UUIDsEqual, IsValidUUID, EscapeSQLString, IndexByUUID } from '@memberjunction/global';
15
15
  import { AIEngine } from '@memberjunction/aiengine';
16
- import { ResolvePromptRunUserID, WithAgentRunDataTrustApplied } from '@memberjunction/ai-core-plus';
16
+ import { ResolvePromptRunUserID, WithAgentRunDataTrustApplied, MJAIAgentRunEntityExtended } from '@memberjunction/ai-core-plus';
17
+ import { ResolveConversationAgentPreset } from '@memberjunction/ai-engine-base';
17
18
  import { PlanArtifactTarget, IsKnownArtifactBehavior } from './artifact-target-plan.js';
18
19
  import { BaseAgent } from './base-agent.js';
20
+ import { HostAllowedAgentIDs } from './decision-discovery.js';
21
+ import { ResolveHandoffTarget, HandoffRefusalReasonText } from './handoff-target.js';
19
22
  import { MJEnvironmentEntityExtended, ArtifactMetadataEngine, ConversationEngine, ExtractBase64FromDataUrl, DecideInlineStorage } from '@memberjunction/core-entities';
23
+ import { ActionEngineServer } from '@memberjunction/actions';
20
24
  import { FileStorageEngine } from '@memberjunction/storage';
21
25
  /**
22
26
  * Choose the artifact a run should be represented by.
@@ -33,6 +37,21 @@ export function SelectPrimaryArtifact(fileArtifacts, payloadArtifact) {
33
37
  export function selectPrimaryArtifact(fileArtifacts, payloadArtifact) {
34
38
  return SelectPrimaryArtifact(fileArtifacts, payloadArtifact);
35
39
  }
40
+ /**
41
+ * Builds the system message injected at index `0` of the target agent's `conversationMessages`
42
+ * when a conversation is transferred via handoff.
43
+ */
44
+ export function HandoffBriefMessage(sourceName, brief, reason) {
45
+ const trimmedReason = reason?.trim();
46
+ return [
47
+ '<handoff_brief>',
48
+ `${sourceName} transferred the conversation to you with this brief:`,
49
+ brief.trim(),
50
+ ...(trimmedReason ? [`Reason for transfer: ${trimmedReason}`] : []),
51
+ `Fulfill the user's request directly using this brief without re-asking what the brief already covers.`,
52
+ '</handoff_brief>',
53
+ ].join('\n');
54
+ }
36
55
  /**
37
56
  * AgentRunner provides a thin wrapper for executing AI agents.
38
57
  *
@@ -97,6 +116,8 @@ export class AgentRunner {
97
116
  * instead: a truncated title still names the artifact the user is looking at.
98
117
  */
99
118
  static { this.ARTIFACT_NAME_MAX_LENGTH = 255; }
119
+ /** How long the end of a run waits for the generated conversation name before keeping the initial one. */
120
+ static { this.NAMING_WAIT_MS = 5000; }
100
121
  constructor(provider) {
101
122
  this._provider = provider ?? Metadata.Provider;
102
123
  }
@@ -177,6 +198,46 @@ export class AgentRunner {
177
198
  throw error;
178
199
  }
179
200
  }
201
+ /**
202
+ * Creates the reply row for an agent's turn on the server: `Role` `AI`, In-Progress, '⏳ Starting...', marked with
203
+ * `MarkServerAuthoredReply()` so the conversation detail gate accepts it. Only the server writes replies, so this is
204
+ * the one place a reply row starts; pass the returned instance to {@link RunAgentInConversation} as
205
+ * `agentResponseDetail` and the run writes its progress and result into it.
206
+ *
207
+ * @param args.conversationId The conversation the reply belongs to.
208
+ * @param args.branchId The fork it sits on, the same as the message it answers; null or omitted is Main.
209
+ * @param args.agentId The agent the reply is from; null for a status line no agent wrote (a workflow's).
210
+ * @param args.contextUser Whom the row is written as: the person the reply is for. They must own the conversation
211
+ * or hold an `Edit` grant on it.
212
+ * @param args.parentId The message the reply answers, when known.
213
+ * @param args.testRunId A test run to link the row to.
214
+ * @param args.provider The provider to write through; defaults to this runner's.
215
+ * @param args.message The row's text, for a server-composed status line; defaults to '⏳ Starting...'.
216
+ * @param args.status The row's status; defaults to In-Progress (a reply a run will fill).
217
+ * @returns The saved row. Throws with the gate's reason when the save is refused.
218
+ */
219
+ async CreateAgentReplyDetail(args) {
220
+ const md = args.provider || this._provider;
221
+ const reply = await md.GetEntityObject('MJ: Conversation Details', args.contextUser);
222
+ reply.MarkServerAuthoredReply();
223
+ reply.ConversationID = args.conversationId;
224
+ reply.BranchID = args.branchId ?? null;
225
+ reply.Message = args.message ?? '⏳ Starting...';
226
+ reply.Role = 'AI';
227
+ reply.Status = args.status ?? 'In-Progress';
228
+ reply.HiddenToUser = false;
229
+ reply.AgentID = args.agentId;
230
+ if (args.parentId) {
231
+ reply.ParentID = args.parentId;
232
+ }
233
+ if (args.testRunId) {
234
+ reply.TestRunID = args.testRunId; // test execution traceability
235
+ }
236
+ if (!(await reply.Save())) {
237
+ throw new Error(`Failed to create agent response conversation detail: ${AgentRunner.saveFailureReason(reply)}`);
238
+ }
239
+ return reply;
240
+ }
180
241
  /**
181
242
  * Runs an AI agent within a conversation context, handling conversation and artifact management.
182
243
  *
@@ -211,13 +272,28 @@ export class AgentRunner {
211
272
  if (!contextUser) {
212
273
  throw new Error('contextUser is required for RunAgentInConversation');
213
274
  }
275
+ const conversationWriter = options.ConversationWriter ?? contextUser;
214
276
  let agentResponseDetail;
277
+ let saveGeneratedName;
215
278
  try {
216
279
  let conversationId;
217
280
  let userMessageDetailId;
218
281
  let agentResponseDetailId;
219
- // If conversationDetailId is provided, use it (UI-created agent response detail)
220
- if (options.conversationDetailId) {
282
+ let isNewConversation = false;
283
+ if (options.agentResponseDetail) {
284
+ // The server created the reply row for this run (RunAIAgentFromConversationDetail): write into it.
285
+ agentResponseDetail = options.agentResponseDetail;
286
+ agentResponseDetailId = agentResponseDetail.ID;
287
+ conversationId = options.conversationId || agentResponseDetail.ConversationID;
288
+ userMessageDetailId = agentResponseDetail.ParentID || agentResponseDetailId;
289
+ }
290
+ else if (options.conversationDetailId) {
291
+ // A caller-supplied detail ID (the legacy RunAIAgent(conversationDetailId=...) shape). The row was not
292
+ // created for this run, so it is loaded unmarked (no MarkServerAuthoredReply), and the conversation
293
+ // detail gate's reply rule refuses the final save (step 5 changes Message and Status) for every user,
294
+ // the system user included. So a caller-supplied detail ID cannot receive the final reply: the run
295
+ // fails at step 5. Only the server-created reply path (options.agentResponseDetail, or the branch
296
+ // below that creates the reply via CreateAgentReplyDetail) completes.
221
297
  agentResponseDetailId = options.conversationDetailId;
222
298
  // LATENCY OPTIMIZATION (Opt #2): When conversationId is pre-resolved by the caller
223
299
  // (e.g., the resolver already loaded the ConversationDetail to build history), we
@@ -236,7 +312,7 @@ export class AgentRunner {
236
312
  else {
237
313
  // Fallback for callers that don't provide conversationId (backward compatibility).
238
314
  // This path still works but incurs the extra DB round-trip to extract conversationId.
239
- const tempDetail = await md.GetEntityObject('MJ: Conversation Details', contextUser);
315
+ const tempDetail = await md.GetEntityObject('MJ: Conversation Details', conversationWriter);
240
316
  if (await tempDetail.Load(agentResponseDetailId)) {
241
317
  conversationId = tempDetail.ConversationID;
242
318
  LogStatus(`Using existing conversation ${conversationId} and agent response detail ${agentResponseDetailId}`);
@@ -247,7 +323,7 @@ export class AgentRunner {
247
323
  }
248
324
  // Load the entity object for progress updates and final status Save at step 5.
249
325
  // This is needed regardless of whether conversationId was pre-resolved.
250
- agentResponseDetail = await md.GetEntityObject('MJ: Conversation Details', contextUser);
326
+ agentResponseDetail = await md.GetEntityObject('MJ: Conversation Details', conversationWriter);
251
327
  if (!await agentResponseDetail.Load(agentResponseDetailId)) {
252
328
  throw new Error(`Failed to load conversation detail entity for status updates: ${agentResponseDetailId}`);
253
329
  }
@@ -261,28 +337,17 @@ export class AgentRunner {
261
337
  // Step 1: Get or create conversation
262
338
  conversationId = options.conversationId || '';
263
339
  if (!conversationId) {
340
+ isNewConversation = true;
264
341
  LogStatus('Creating new conversation');
265
- const conversation = await md.GetEntityObject('MJ: Conversations', contextUser);
266
- // Smart conversation naming:
267
- // 1. Use provided name if given
268
- // 2. Otherwise, use AI prompt to generate a good name from user message
269
- // 3. Fallback to "Chat with [AgentName]"
270
- let conversationName = options.conversationName;
271
- let conversationDescription = null;
272
- if (!conversationName && options.userMessage) {
273
- // Try to generate a name using the "Name Conversation" prompt (same as UI)
274
- const nameResult = await this.generateConversationName(options.userMessage, contextUser, md, params);
275
- if (nameResult) {
276
- conversationName = nameResult.name;
277
- conversationDescription = nameResult.description;
278
- }
279
- }
280
- if (!conversationName) {
281
- conversationName = `Chat with ${params.agent.Name}`;
282
- }
283
- conversation.Name = conversationName;
284
- conversation.Description = conversationDescription || ''; // Set description too (like UI does)
285
- conversation.UserID = params.userId || contextUser.ID;
342
+ const conversation = await md.GetEntityObject('MJ: Conversations', conversationWriter);
343
+ // Save immediately with provided name or fallback so agent execution does not block
344
+ // on the ~1,000ms "Name Conversation" LLM call. When no name was provided, fire
345
+ // generateConversationName in parallel with RunAgent and save the generated name
346
+ // after the run's own writes (in the finally below), before returning.
347
+ const initialConversationName = options.conversationName || `Chat with ${params.agent.Name}`;
348
+ conversation.Name = initialConversationName;
349
+ conversation.Description = '';
350
+ conversation.UserID = params.userId || conversationWriter.ID;
286
351
  conversation.Status = 'Available';
287
352
  conversation.DataContextID = null; // Can be set by caller if needed
288
353
  // Link to test run if provided (for test execution traceability)
@@ -293,15 +358,18 @@ export class AgentRunner {
293
358
  throw new Error('Failed to create conversation');
294
359
  }
295
360
  conversationId = conversation.ID;
296
- LogStatus(`Created conversation ${conversationId}: ${conversationName}`);
361
+ LogStatus(`Created conversation ${conversationId}: ${initialConversationName}`);
362
+ if (!options.conversationName && options.userMessage) {
363
+ saveGeneratedName = this.startConversationNaming(conversation, options.userMessage, contextUser, md, params);
364
+ }
297
365
  }
298
366
  // Step 2: Create conversation detail for user message
299
367
  LogStatus('Creating conversation detail for user message');
300
- const userMessageDetail = await md.GetEntityObject('MJ: Conversation Details', contextUser);
368
+ const userMessageDetail = await md.GetEntityObject('MJ: Conversation Details', conversationWriter);
301
369
  userMessageDetail.ConversationID = conversationId;
302
370
  userMessageDetail.Message = options.userMessage;
303
371
  userMessageDetail.Role = 'User';
304
- userMessageDetail.UserID = contextUser.ID;
372
+ userMessageDetail.UserID = conversationWriter.ID;
305
373
  userMessageDetail.HiddenToUser = false;
306
374
  userMessageDetail.BranchID = params.ConversationBranchID ?? null;
307
375
  // Link to test run if provided (for test execution traceability)
@@ -313,23 +381,16 @@ export class AgentRunner {
313
381
  }
314
382
  userMessageDetailId = userMessageDetail.ID;
315
383
  LogStatus(`Created user message detail ${userMessageDetailId}`);
316
- // Step 3: Create conversation detail for agent response (like UI does)
384
+ // Step 3: Create conversation detail for agent response
317
385
  LogStatus('Creating conversation detail for agent response');
318
- agentResponseDetail = await md.GetEntityObject('MJ: Conversation Details', contextUser);
319
- agentResponseDetail.ConversationID = conversationId;
320
- agentResponseDetail.Message = '⏳ Starting...';
321
- agentResponseDetail.Role = 'AI';
322
- agentResponseDetail.Status = 'In-Progress';
323
- agentResponseDetail.HiddenToUser = false;
324
- agentResponseDetail.AgentID = params.agent.ID;
325
- agentResponseDetail.BranchID = params.ConversationBranchID ?? null;
326
- // Link to test run if provided (for test execution traceability)
327
- if (options.testRunId) {
328
- agentResponseDetail.TestRunID = options.testRunId;
329
- }
330
- if (!(await agentResponseDetail.Save())) {
331
- throw new Error(`Failed to create agent response conversation detail: ${AgentRunner.saveFailureReason(agentResponseDetail)}`);
332
- }
386
+ agentResponseDetail = await this.CreateAgentReplyDetail({
387
+ conversationId,
388
+ branchId: params.ConversationBranchID ?? null,
389
+ agentId: params.agent.ID,
390
+ contextUser: conversationWriter,
391
+ testRunId: options.testRunId,
392
+ provider: md
393
+ });
333
394
  agentResponseDetailId = agentResponseDetail.ID;
334
395
  LogStatus(`Created agent response detail ${agentResponseDetailId}`);
335
396
  }
@@ -389,7 +450,10 @@ export class AgentRunner {
389
450
  // the conversation with the artifact already available." This means ALL artifacts
390
451
  // on that path (both agent-produced Output and user-attached Input) should
391
452
  // be available to the agent via artifact tools.
392
- const inputArtifacts = await this.gatherConversationArtifacts(conversationId, contextUser, params.ConversationHistoryFrom, runBranchId);
453
+ // Brand-new conversations created right above have zero prior artifacts, so skip the 3 DB queries.
454
+ const inputArtifacts = isNewConversation
455
+ ? []
456
+ : await this.gatherConversationArtifacts(conversationId, contextUser, params.ConversationHistoryFrom, runBranchId);
393
457
  const modifiedParams = {
394
458
  ...params,
395
459
  // First-class conversationId gates the cross-turn context features
@@ -442,12 +506,10 @@ export class AgentRunner {
442
506
  // then for any other save still in flight on this entity
443
507
  await progressSaves;
444
508
  await agentResponseDetail.EnsureSaveComplete();
509
+ // No reload first, for latency. Save sends every loaded column, so a pin (SavePinState) or
510
+ // rating written to this row between the last progress save and this one is overwritten.
511
+ // The progress saves already have that window; the reload only rescued a late pin.
445
512
  LogStatus('Updating agent response detail with final result');
446
- // Reload to get any updates from agent execution
447
- const loaded = await agentResponseDetail.Load(agentResponseDetailId);
448
- if (!loaded) {
449
- LogError(`Failed to reload agent response detail ${agentResponseDetailId}`);
450
- }
451
513
  const finalState = AgentRunner.ResolveFinalDetailState(agentResult);
452
514
  agentResponseDetail.Message = finalState.Message;
453
515
  agentResponseDetail.Status = finalState.Status;
@@ -463,7 +525,11 @@ export class AgentRunner {
463
525
  }
464
526
  const saved = await agentResponseDetail.Save();
465
527
  if (!saved) {
466
- LogError(`Failed to save agent response detail ${agentResponseDetailId} with final status: ${AgentRunner.saveFailureReason(agentResponseDetail)}`);
528
+ const reason = AgentRunner.saveFailureReason(agentResponseDetail);
529
+ LogError(`Failed to save agent response detail ${agentResponseDetailId} with final status: ${reason}`);
530
+ // The reply never reached the conversation, so the caller must not report success: a chat
531
+ // client waiting for this row to complete would otherwise wait forever.
532
+ throw new Error(`The agent's reply could not be saved: ${reason}`);
467
533
  }
468
534
  LogStatus(`Updated agent response detail ${agentResponseDetailId} with final status: ${agentResponseDetail.Status}`);
469
535
  }
@@ -508,7 +574,7 @@ export class AgentRunner {
508
574
  const mediaToSave = agentResult.mediaOutputs;
509
575
  LogStatus(`Processing ${mediaToSave.length} media output(s)`);
510
576
  // Save to AIAgentRunMedia for permanent audit/lineage storage
511
- const ids = await this.SaveAgentRunMedia(agentResult.agentRun.ID, mediaToSave, contextUser, md);
577
+ const ids = await this.SaveAgentRunMedia(agentResult.agentRun.ID, mediaToSave, contextUser, md, agentResult.resolvedStorageAccountId);
512
578
  // Create Artifact + ArtifactVersion + ConversationDetailArtifact for each
513
579
  // media output so the chat UI renders them as artifact cards. This replaces
514
580
  // the old CreateConversationMediaAttachments path which wrote to the deprecated
@@ -548,7 +614,46 @@ export class AgentRunner {
548
614
  // no report." Sequential execution removes the interleave; all writes still complete
549
615
  // before we return, so the resolver's 'complete' event still guarantees the client sees
550
616
  // every write.
551
- await updateDetail();
617
+ //
618
+ // A failed reply save (step 5) into the reply row created for this run does NOT skip steps 6-7. AgentRunner is the only writer of
619
+ // AIAgentRunMedia and nothing retries, so skipping them would leave the run Completed with no
620
+ // artifact linked and its media bytes lost. Instead the step-5 error is held, steps 6, 6b and 7
621
+ // each run (one's rejection must not skip the next, and ProcessAgentArtifacts can reject outside
622
+ // its own try/catch), and the step-5 error is thrown last, so the run still fails with its reason.
623
+ let replySaveError;
624
+ try {
625
+ await updateDetail();
626
+ }
627
+ catch (error) {
628
+ replySaveError = error instanceof Error ? error : new Error(String(error));
629
+ }
630
+ if (replySaveError) {
631
+ const runDespiteFailedReply = async (stepName, step) => {
632
+ try {
633
+ await step();
634
+ }
635
+ catch (stepError) {
636
+ const stepMessage = stepError instanceof Error ? stepError.message : String(stepError);
637
+ LogError(`${stepName} failed for agent run ${agentResult.agentRun?.ID} (reply detail ${agentResponseDetailId}) after its reply could not be saved: ${stepMessage}`, undefined, stepError);
638
+ }
639
+ };
640
+ if (options.conversationDetailId && !options.agentResponseDetail) {
641
+ // A caller-supplied row (not created for this run) that the gate refused: link nothing to it, since
642
+ // that would write into a conversation the gate kept this run out of, as the run user. The media
643
+ // bytes belong to the run (AIAgentRunMedia), so only those are kept.
644
+ await runDespiteFailedReply('Step 7 (media audit)', async () => {
645
+ if (agentResult.mediaOutputs?.length) {
646
+ await this.SaveAgentRunMedia(agentResult.agentRun.ID, agentResult.mediaOutputs, contextUser, md);
647
+ }
648
+ });
649
+ }
650
+ else {
651
+ await runDespiteFailedReply('Step 6 (payload artifacts)', processArtifacts);
652
+ await runDespiteFailedReply('Step 6b (file artifacts)', processFileArtifacts);
653
+ await runDespiteFailedReply('Step 7 (media)', saveMedia);
654
+ }
655
+ throw replySaveError;
656
+ }
552
657
  const payloadArtifact = await processArtifacts();
553
658
  const fileArtifacts = await processFileArtifacts();
554
659
  await saveMedia();
@@ -584,6 +689,362 @@ export class AgentRunner {
584
689
  }
585
690
  throw error;
586
691
  }
692
+ finally {
693
+ // After the run's own writes, success or failure: the name call was already paid for.
694
+ await saveGeneratedName?.();
695
+ }
696
+ }
697
+ /**
698
+ * Executes server-side handoff hops sequentially in the same turn while the active run's
699
+ * result carries a resolved `handoff`.
700
+ */
701
+ async FollowHandoffs(input) {
702
+ const outcomes = [];
703
+ const onHopStart = input.hooks?.OnHopStart;
704
+ const onHopEnd = input.hooks?.OnHopEnd;
705
+ const baseHistory = [...(input.params.conversationMessages ?? [])];
706
+ let currentParams = input.params;
707
+ let currentResult = input.sourceResult;
708
+ let currentRowId = input.sourceConversationDetailId;
709
+ let hopIndex = 0;
710
+ while (currentResult?.handoff) {
711
+ const handoff = currentResult.handoff;
712
+ const md = currentParams.provider ?? this._provider;
713
+ const contextUser = currentParams.contextUser;
714
+ const conversationWriter = input.ConversationWriter ?? contextUser;
715
+ // Load the source ConversationDetail row so we can read its BranchID (and update it on refusal)
716
+ let sourceRow;
717
+ let sourceRowLoaded = false;
718
+ try {
719
+ sourceRow = await md.GetEntityObject('MJ: Conversation Details', conversationWriter);
720
+ sourceRow?.MarkServerAuthoredReply?.();
721
+ sourceRowLoaded = Boolean(sourceRow && await sourceRow.Load(currentRowId));
722
+ }
723
+ catch (err) {
724
+ LogError(`FollowHandoffs: failed to load source conversation detail ${currentRowId}: ${err}`);
725
+ }
726
+ const sourceBranchId = sourceRowLoaded
727
+ ? (sourceRow?.BranchID ?? currentParams.ConversationBranchID ?? null)
728
+ : (currentParams.ConversationBranchID ?? null);
729
+ // 1. Re-resolve target agent
730
+ const trustedData = WithAgentRunDataTrustApplied(currentParams).Params.data;
731
+ const resolution = await ResolveHandoffTarget({
732
+ AgentName: handoff.targetAgentName,
733
+ SourceAgentID: currentParams.agent.ID,
734
+ HandoffChain: currentParams.handoffChain ?? [],
735
+ HostAllowedIDs: HostAllowedAgentIDs(trustedData),
736
+ ContextUser: contextUser,
737
+ Agents: AIEngine.Instance.Agents,
738
+ });
739
+ if (resolution.Refusal) {
740
+ const targetLabel = handoff.targetAgentName || handoff.targetAgentId;
741
+ await this.recordRefusedHandoffOnSource(currentResult, sourceRowLoaded ? sourceRow : undefined, targetLabel, HandoffRefusalReasonText(resolution.Refusal.Reason, targetLabel));
742
+ break;
743
+ }
744
+ const resolvedTarget = resolution.Target;
745
+ // 2. Resolve configuration preset for the target agent
746
+ const presetResult = await ResolveConversationAgentPreset({
747
+ ConversationID: input.conversationId,
748
+ AgentID: resolvedTarget.ID,
749
+ BranchID: sourceBranchId,
750
+ ContextUser: contextUser,
751
+ Provider: md,
752
+ });
753
+ // 3. Create target MJ: Conversation Details row via CreateAgentReplyDetail
754
+ // so the instance carries MarkServerAuthoredReply() and the conversation writer user (A19).
755
+ let targetRow;
756
+ try {
757
+ targetRow = await this.CreateAgentReplyDetail({
758
+ conversationId: input.conversationId,
759
+ branchId: sourceBranchId,
760
+ agentId: resolvedTarget.ID,
761
+ contextUser: conversationWriter,
762
+ parentId: currentRowId,
763
+ provider: md,
764
+ });
765
+ }
766
+ catch (createErr) {
767
+ const saveReason = createErr instanceof Error
768
+ ? createErr.message.replace(/^Failed to create agent response conversation detail:\s*/, '')
769
+ : String(createErr);
770
+ LogError(`Failed to create handoff target conversation detail: ${saveReason}`);
771
+ await this.recordRefusedHandoffOnSource(currentResult, sourceRowLoaded ? sourceRow : undefined, resolvedTarget.Name || handoff.targetAgentName || handoff.targetAgentId, saveReason);
772
+ break;
773
+ }
774
+ // 4. Update source run's Handoff step OutputData with TargetConversationDetailID and preset details
775
+ await this.updateSourceHandoffStepOutput(currentResult, targetRow.ID, presetResult);
776
+ // 5. Notify OnHopStart hook
777
+ const hopInfo = {
778
+ hopIndex,
779
+ sourceAgent: currentParams.agent,
780
+ sourceConversationDetailId: currentRowId,
781
+ targetAgent: resolvedTarget,
782
+ targetConversationDetailId: targetRow.ID,
783
+ preset: presetResult.Preset,
784
+ presetSource: presetResult.Source,
785
+ handoff,
786
+ };
787
+ const hopCallbacksResult = await onHopStart?.(hopInfo, {
788
+ agentResult: currentResult,
789
+ conversationDetailId: currentRowId,
790
+ });
791
+ const hopCallbacks = hopCallbacksResult || undefined;
792
+ // 6. Build target ExecuteAgentParams (never copying payload, lastRunId, configurationId, override, or parentRun from source)
793
+ const priorRunId = await this.lookupTargetPriorRunId(input.conversationId, resolvedTarget.ID, sourceBranchId, contextUser, md);
794
+ const targetParams = this.buildHandoffTargetParams(currentParams, baseHistory, resolvedTarget, handoff, sourceBranchId, presetResult.Preset, priorRunId, hopCallbacks);
795
+ // 7. Execute target agent in conversation
796
+ let outcome;
797
+ let hopSucceeded = false;
798
+ try {
799
+ const hopRun = await this.RunAgentInConversation(targetParams, {
800
+ conversationId: input.conversationId,
801
+ agentResponseDetail: targetRow,
802
+ createArtifacts: input.createArtifacts,
803
+ ...(input.ConversationWriter ? { ConversationWriter: input.ConversationWriter } : {}),
804
+ });
805
+ outcome = {
806
+ hopIndex,
807
+ targetAgent: resolvedTarget,
808
+ targetConversationDetailId: targetRow.ID,
809
+ preset: presetResult.Preset,
810
+ presetSource: presetResult.Source,
811
+ agentResult: hopRun.agentResult,
812
+ artifactInfo: hopRun.artifactInfo,
813
+ };
814
+ hopSucceeded = true;
815
+ }
816
+ catch (error) {
817
+ const errorMessage = error instanceof Error ? error.message : String(error);
818
+ LogError(`FollowHandoffs hop ${hopIndex} failed: ${errorMessage}`, undefined, error);
819
+ try {
820
+ targetRow.MarkServerAuthoredReply?.();
821
+ await targetRow.Load(targetRow.ID);
822
+ if (targetRow.Status === 'In-Progress') {
823
+ targetRow.Status = 'Error';
824
+ targetRow.Message = errorMessage;
825
+ targetRow.Error = errorMessage;
826
+ if (!(await targetRow.Save())) {
827
+ LogError(`FollowHandoffs: failed to persist Error on target detail ${targetRow.ID}: ${AgentRunner.saveFailureReason(targetRow)}`);
828
+ }
829
+ }
830
+ }
831
+ catch (persistError) {
832
+ LogError(`FollowHandoffs: failed to persist Error on target detail ${targetRow.ID}: ${persistError}`);
833
+ }
834
+ outcome = {
835
+ hopIndex,
836
+ targetAgent: resolvedTarget,
837
+ targetConversationDetailId: targetRow.ID,
838
+ preset: presetResult.Preset,
839
+ presetSource: presetResult.Source,
840
+ error: errorMessage,
841
+ };
842
+ }
843
+ try {
844
+ await onHopEnd?.(hopInfo, outcome);
845
+ }
846
+ catch (hookError) {
847
+ LogError(`FollowHandoffs OnHopEnd hook failed on hop ${hopIndex}: ${hookError}`, undefined, hookError);
848
+ }
849
+ outcomes.push(outcome);
850
+ if (!hopSucceeded || !outcome.agentResult?.handoff) {
851
+ break;
852
+ }
853
+ currentParams = targetParams;
854
+ currentResult = outcome.agentResult;
855
+ currentRowId = targetRow.ID;
856
+ hopIndex++;
857
+ }
858
+ return outcomes;
859
+ }
860
+ findLatestHandoffStep(result) {
861
+ const steps = result.agentRun?.Steps;
862
+ const runStepId = result.handoff?.runStepId;
863
+ if (!Array.isArray(steps) || !runStepId) {
864
+ return undefined;
865
+ }
866
+ return steps.find(s => s?.ID && UUIDsEqual(s.ID, runStepId));
867
+ }
868
+ async recordRefusedHandoffOnSource(sourceResult, sourceRow, targetLabel, refusalReason) {
869
+ let end = refusalReason.length;
870
+ while (end > 0 && refusalReason.charCodeAt(end - 1) === 46) {
871
+ end--;
872
+ }
873
+ const cleanReason = refusalReason.slice(0, end);
874
+ const handoffStep = this.findLatestHandoffStep(sourceResult);
875
+ if (handoffStep) {
876
+ try {
877
+ handoffStep.Status = 'Failed';
878
+ handoffStep.ErrorMessage = refusalReason;
879
+ handoffStep.CompletedAt = new Date();
880
+ if (!(await handoffStep.Save())) {
881
+ LogError(`FollowHandoffs: failed to save Failed status on Handoff step ${handoffStep.ID}: ${AgentRunner.saveFailureReason(handoffStep)}`);
882
+ }
883
+ }
884
+ catch (err) {
885
+ LogError(`FollowHandoffs: failed to save Failed status on Handoff step: ${err}`);
886
+ }
887
+ }
888
+ const notice = `I couldn't transfer you to ${targetLabel}: ${cleanReason}.`;
889
+ if (sourceResult.agentRun) {
890
+ const existingRunMessage = sourceResult.agentRun.Message ?? sourceRow?.Message;
891
+ sourceResult.agentRun.Message = existingRunMessage
892
+ ? `${existingRunMessage}\n\n${notice}`
893
+ : notice;
894
+ }
895
+ if (sourceRow) {
896
+ try {
897
+ sourceRow.MarkServerAuthoredReply?.();
898
+ sourceRow.Message = sourceRow.Message
899
+ ? `${sourceRow.Message}\n\n${notice}`
900
+ : notice;
901
+ if (!(await sourceRow.Save())) {
902
+ LogError(`FollowHandoffs: failed to append refusal notice to source detail ${sourceRow.ID}: ${AgentRunner.saveFailureReason(sourceRow)}`);
903
+ }
904
+ }
905
+ catch (err) {
906
+ LogError(`FollowHandoffs: failed to append refusal notice to source detail ${sourceRow.ID}: ${err}`);
907
+ }
908
+ }
909
+ }
910
+ async updateSourceHandoffStepOutput(sourceResult, targetConversationDetailId, presetResult) {
911
+ const handoffStep = this.findLatestHandoffStep(sourceResult);
912
+ if (!handoffStep) {
913
+ return;
914
+ }
915
+ try {
916
+ let parsedOutput = {};
917
+ if (handoffStep.OutputData) {
918
+ try {
919
+ const parsed = JSON.parse(handoffStep.OutputData);
920
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
921
+ parsedOutput = parsed;
922
+ }
923
+ }
924
+ catch {
925
+ // keep empty object if prior OutputData was not valid JSON
926
+ }
927
+ }
928
+ const presetName = presetResult.Preset
929
+ ? presetResult.Preset.DisplayName || presetResult.Preset.Name
930
+ : null;
931
+ handoffStep.OutputData = JSON.stringify({
932
+ ...parsedOutput,
933
+ TargetConversationDetailID: targetConversationDetailId,
934
+ PresetID: presetResult.Preset?.ID ?? null,
935
+ PresetName: presetName,
936
+ PresetSource: presetResult.Source,
937
+ });
938
+ if (!(await handoffStep.Save())) {
939
+ LogError(`FollowHandoffs: failed to update Handoff step OutputData on ${handoffStep.ID}: ${AgentRunner.saveFailureReason(handoffStep)}`);
940
+ }
941
+ }
942
+ catch (err) {
943
+ LogError(`FollowHandoffs: failed to update Handoff step OutputData: ${err}`);
944
+ }
945
+ }
946
+ async lookupTargetPriorRunId(conversationId, targetAgentId, branchId, contextUser, provider) {
947
+ if (!contextUser) {
948
+ return undefined;
949
+ }
950
+ try {
951
+ const safeConvId = AgentRunner.filterId(conversationId, 'FollowHandoffs conversationId');
952
+ const safeAgentId = AgentRunner.filterId(targetAgentId, 'FollowHandoffs targetAgentId');
953
+ const safeBranchId = branchId ? AgentRunner.filterId(branchId, 'FollowHandoffs branchId') : null;
954
+ const branches = safeBranchId
955
+ ? await ConversationEngine.LoadBranchesFresh(safeConvId, contextUser, provider)
956
+ : [];
957
+ const settled = MJAIAgentRunEntityExtended.SettledStatuses.map(s => `'${s}'`).join(', ');
958
+ const replyFilter = MJAIAgentRunEntityExtended.BuildReplyOnBranchPathFilter(safeConvId, safeBranchId, branches);
959
+ const rv = RunView.FromMetadataProvider(provider);
960
+ const result = await rv.RunView({
961
+ EntityName: 'MJ: AI Agent Runs',
962
+ ExtraFilter: `ConversationID='${safeConvId}' AND Status IN (${settled}) ` +
963
+ `AND ParentRunID IS NULL AND AgentID='${safeAgentId}' AND ${replyFilter}`,
964
+ OrderBy: '__mj_CreatedAt DESC',
965
+ MaxRows: 1,
966
+ Fields: ['ID'],
967
+ ResultType: 'simple',
968
+ }, contextUser);
969
+ if (result.Success && result.Results && result.Results.length > 0 && result.Results[0].ID) {
970
+ return result.Results[0].ID;
971
+ }
972
+ }
973
+ catch (err) {
974
+ LogError(`FollowHandoffs: failed to look up prior run for agent ${targetAgentId}: ${err}`);
975
+ }
976
+ return undefined;
977
+ }
978
+ buildHandoffTargetParams(sourceParams, baseHistory, targetAgent, handoff, branchId, preset, priorRunId, callbacks) {
979
+ const sourceName = sourceParams.agent.Name || 'Agent';
980
+ const briefMsg = HandoffBriefMessage(sourceName, handoff.brief, handoff.reason);
981
+ const effectiveBranchId = branchId ?? sourceParams.ConversationBranchID;
982
+ const targetParams = {
983
+ agent: targetAgent,
984
+ conversationMessages: [
985
+ { role: 'system', content: briefMsg },
986
+ ...baseHistory,
987
+ ],
988
+ contextUser: sourceParams.contextUser,
989
+ userId: sourceParams.userId,
990
+ companyId: sourceParams.companyId,
991
+ PrimaryScopeEntityName: sourceParams.PrimaryScopeEntityName,
992
+ PrimaryScopeRecordID: sourceParams.PrimaryScopeRecordID,
993
+ SecondaryScopes: sourceParams.SecondaryScopes,
994
+ CredentialScope: sourceParams.CredentialScope,
995
+ apiKeys: sourceParams.apiKeys,
996
+ Audience: sourceParams.Audience,
997
+ data: sourceParams.data,
998
+ TrustReservedRunData: sourceParams.TrustReservedRunData,
999
+ inputArtifacts: sourceParams.inputArtifacts,
1000
+ planMode: sourceParams.planMode,
1001
+ requestedSkillIDs: sourceParams.requestedSkillIDs,
1002
+ ConversationHistoryFrom: sourceParams.ConversationHistoryFrom,
1003
+ ...(effectiveBranchId !== undefined ? { ConversationBranchID: effectiveBranchId } : {}),
1004
+ sessionID: sourceParams.sessionID,
1005
+ cancellationToken: sourceParams.cancellationToken,
1006
+ provider: sourceParams.provider,
1007
+ context: sourceParams.context,
1008
+ handoffChain: [...(sourceParams.handoffChain ?? []), sourceParams.agent.ID],
1009
+ ...(preset?.AIConfigurationID ? { configurationId: preset.AIConfigurationID } : {}),
1010
+ ...(priorRunId ? { lastRunId: priorRunId, autoPopulateLastRunPayload: true } : {}),
1011
+ ...(callbacks?.onProgress ? { onProgress: callbacks.onProgress } : {}),
1012
+ ...(callbacks?.onStreaming ? { onStreaming: callbacks.onStreaming } : {}),
1013
+ };
1014
+ return targetParams;
1015
+ }
1016
+ /**
1017
+ * Starts the "Name Conversation" prompt for a new conversation so it runs alongside the agent, and
1018
+ * returns the step that saves the generated name. That step runs after the run's own writes, which
1019
+ * share the request's connection. A failed generation or save keeps the initial name.
1020
+ */
1021
+ startConversationNaming(conversation, userMessage, contextUser, md, credentials) {
1022
+ const initialName = conversation.Name;
1023
+ const naming = this.generateConversationName(userMessage, contextUser, md, credentials);
1024
+ return async () => {
1025
+ // Bounded: a run that failed or was cancelled early must not wait out the whole naming call.
1026
+ let timer;
1027
+ const gaveUp = new Promise(resolve => { timer = setTimeout(() => resolve(null), AgentRunner.NAMING_WAIT_MS); });
1028
+ const nameResult = await Promise.race([naming, gaveUp]).finally(() => clearTimeout(timer));
1029
+ if (!nameResult?.name) {
1030
+ return;
1031
+ }
1032
+ // Re-read first: Save writes every column, so a stale instance would undo a rename or an
1033
+ // archive made during the run. A name someone already changed is kept. This runs in the run's
1034
+ // finally, so a reload that throws must not replace the run's result.
1035
+ if (!(await conversation.Load(conversation.ID).catch(() => false))) {
1036
+ LogError(`Failed to reload conversation ${conversation.ID} before saving its generated name`);
1037
+ return;
1038
+ }
1039
+ if (conversation.Name !== initialName) {
1040
+ return;
1041
+ }
1042
+ conversation.Name = nameResult.name;
1043
+ conversation.Description = nameResult.description || '';
1044
+ if (!(await conversation.Save())) {
1045
+ LogError(`Failed to save the generated name of conversation ${conversation.ID}: ${AgentRunner.saveFailureReason(conversation)}`);
1046
+ }
1047
+ };
587
1048
  }
588
1049
  /**
589
1050
  * Gets the maximum version number for an artifact.
@@ -609,6 +1070,7 @@ export class AgentRunner {
609
1070
  ExtraFilter: `ArtifactID='${AgentRunner.filterId(artifactId, 'GetMaxVersionForArtifact artifactId')}'`,
610
1071
  OrderBy: 'VersionNumber DESC',
611
1072
  MaxRows: 1,
1073
+ SkipTotalRowCount: true,
612
1074
  ResultType: 'entity_object'
613
1075
  }, contextUser);
614
1076
  if (result.Success && result.Results && result.Results.length > 0) {
@@ -656,6 +1118,7 @@ export class AgentRunner {
656
1118
  ExtraFilter: `ArtifactID='${AgentRunner.filterId(artifactId, 'CheckForDuplicateVersion artifactId')}' AND VersionNumber=${latestVersion}`,
657
1119
  Fields: ['ID', 'ContentHash'],
658
1120
  MaxRows: 1,
1121
+ SkipTotalRowCount: true,
659
1122
  ResultType: 'simple'
660
1123
  }, contextUser);
661
1124
  if (result.Success && result.Results.length > 0 && result.Results[0].ContentHash === candidateHash) {
@@ -734,6 +1197,7 @@ export class AgentRunner {
734
1197
  `AND ArtifactVersionID='${AgentRunner.filterId(versionId, 'hasOutputLink versionId')}' AND Direction='Output'`,
735
1198
  Fields: ['ID'],
736
1199
  MaxRows: 1,
1200
+ SkipTotalRowCount: true,
737
1201
  ResultType: 'simple'
738
1202
  }, contextUser);
739
1203
  if (!result.Success) {
@@ -768,6 +1232,7 @@ export class AgentRunner {
768
1232
  ExtraFilter: `ConversationDetailID='${AgentRunner.filterId(conversationDetailId, 'FindPreviousArtifactForMessage conversationDetailId')}' AND Direction='Output'`,
769
1233
  OrderBy: '__mj_CreatedAt DESC',
770
1234
  MaxRows: 1,
1235
+ SkipTotalRowCount: true,
771
1236
  ResultType: 'entity_object'
772
1237
  }, contextUser);
773
1238
  if (!result.Success || !result.Results || result.Results.length === 0) {
@@ -1212,6 +1677,7 @@ export class AgentRunner {
1212
1677
  ExtraFilter: `ID='${EscapeSQLString(artifactId)}'`,
1213
1678
  Fields: ['ID', 'UserID'],
1214
1679
  MaxRows: 1,
1680
+ SkipTotalRowCount: true,
1215
1681
  ResultType: 'simple',
1216
1682
  },
1217
1683
  {
@@ -1219,6 +1685,7 @@ export class AgentRunner {
1219
1685
  ExtraFilter: `ArtifactID='${EscapeSQLString(artifactId)}' AND UserID='${EscapeSQLString(contextUser.ID)}' AND CanEdit=1`,
1220
1686
  Fields: ['ID'],
1221
1687
  MaxRows: 1,
1688
+ SkipTotalRowCount: true,
1222
1689
  ResultType: 'simple',
1223
1690
  },
1224
1691
  ], contextUser);
@@ -1349,6 +1816,8 @@ export class AgentRunner {
1349
1816
  * @param agentRunId - The ID of the agent run
1350
1817
  * @param mediaOutputs - Array of media outputs to save
1351
1818
  * @param contextUser - User context for the operation
1819
+ * @param provider - Optional metadata provider for multi-provider support
1820
+ * @param resolvedStorageAccountId - Optional pre-resolved storage account ID from the agent's resolution chain
1352
1821
  * @returns Array of saved AIAgentRunMedia IDs
1353
1822
  * @since 3.1.0
1354
1823
  *
@@ -1363,7 +1832,7 @@ export class AgentRunner {
1363
1832
  * console.log(`Saved ${mediaIds.length} media outputs`);
1364
1833
  * ```
1365
1834
  */
1366
- async SaveAgentRunMedia(agentRunId, mediaOutputs, contextUser, provider) {
1835
+ async SaveAgentRunMedia(agentRunId, mediaOutputs, contextUser, provider, resolvedStorageAccountId) {
1367
1836
  if (!mediaOutputs || mediaOutputs.length === 0) {
1368
1837
  return [];
1369
1838
  }
@@ -1371,6 +1840,12 @@ export class AgentRunner {
1371
1840
  const savedIds = [];
1372
1841
  const md = provider || this._provider;
1373
1842
  try {
1843
+ try {
1844
+ await FileStorageEngine.Instance.Config(false, contextUser);
1845
+ }
1846
+ catch (configError) {
1847
+ LogError(`SaveAgentRunMedia: failed to configure FileStorageEngine, falling back to inline: ${configError.message}`);
1848
+ }
1374
1849
  // Use AIEngine's cached modalities instead of a fresh DB call
1375
1850
  const aiEngine = AIEngine.Instance;
1376
1851
  for (let i = 0; i < mediaToSave.length; i++) {
@@ -1392,9 +1867,27 @@ export class AgentRunner {
1392
1867
  continue;
1393
1868
  }
1394
1869
  mediaEntity.MimeType = mediaOutput.mimeType;
1395
- // Only store inline data if NOT from prompt run media
1870
+ // Upload to MJStorage when configured (or fall back to InlineData) if NOT from prompt run media
1396
1871
  if (!mediaOutput.promptRunMediaId && mediaOutput.data) {
1397
- mediaEntity.InlineData = mediaOutput.data;
1872
+ const extension = this.getMimeTypeExtension(mediaOutput.mimeType);
1873
+ const fileName = mediaOutput.label || `${mediaOutput.modality.toLowerCase()}_${i + 1}.${extension}`;
1874
+ const estimatedSizeBytes = Math.ceil(mediaOutput.data.length * 0.75);
1875
+ const fileId = mediaOutput.fileId ?? await this.uploadToStorageIfConfigured(mediaOutput.data, fileName, mediaOutput.mimeType, contextUser, resolvedStorageAccountId, md, 'SaveAgentRunMedia');
1876
+ if (fileId) {
1877
+ mediaEntity.FileID = fileId;
1878
+ mediaEntity.FileName = fileName;
1879
+ mediaEntity.FileSizeBytes = estimatedSizeBytes;
1880
+ mediaOutput.fileId = fileId;
1881
+ }
1882
+ else {
1883
+ mediaEntity.InlineData = mediaOutput.data;
1884
+ }
1885
+ }
1886
+ else if (!mediaOutput.promptRunMediaId && mediaOutput.fileId) {
1887
+ const extension = this.getMimeTypeExtension(mediaOutput.mimeType);
1888
+ const fileName = mediaOutput.label || `${mediaOutput.modality.toLowerCase()}_${i + 1}.${extension}`;
1889
+ mediaEntity.FileID = mediaOutput.fileId;
1890
+ mediaEntity.FileName = fileName;
1398
1891
  }
1399
1892
  // Set dimensions if available
1400
1893
  if (mediaOutput.width) {
@@ -1524,11 +2017,12 @@ export class AgentRunner {
1524
2017
  const estimatedSizeBytes = media.data
1525
2018
  ? Math.ceil(media.data.length * 0.75)
1526
2019
  : undefined;
1527
- // Storage-backed when an account is configured, exactly as ProcessFileArtifacts
2020
+ // Reuse fileId when SaveAgentRunMedia already uploaded the bytes to MJStorage;
2021
+ // otherwise upload when a storage account is configured, exactly as ProcessFileArtifacts
1528
2022
  // does for file outputs.
1529
- const fileId = media.data
2023
+ const fileId = media.fileId ?? (media.data
1530
2024
  ? await this.uploadToStorageIfConfigured(media.data, fileName, media.mimeType, contextUser, resolvedStorageAccountId, md, 'CreateMediaArtifacts')
1531
- : undefined;
2025
+ : undefined);
1532
2026
  if (fileId) {
1533
2027
  await this.createFileArtifact(fileId, media.mimeType, fileName, estimatedSizeBytes, conversationDetailId, contextUser, md, true, `media ${media.modality}`);
1534
2028
  }
@@ -2026,9 +2520,10 @@ export class AgentRunner {
2026
2520
  * `ArtifactToolManager`. No-op for binary content, non-JSON content, or
2027
2521
  * content that already has rows populated.
2028
2522
  *
2029
- * Security: `RunQuery` uses the same read-only, `SQLExpressionValidator`-
2030
- * checked execution path that `data-artifact-viewer` already uses at
2031
- * render time — identical security posture to the existing view path.
2523
+ * Security: the stored SQL runs as ad-hoc SQL for `contextUser`, so the provider
2524
+ * allows only a single read statement over entity views that user may read in
2525
+ * full (no row-level filter, no denied field). It runs on the host's read-only
2526
+ * database login when one is configured, and on the default provider otherwise.
2032
2527
  */
2033
2528
  async hydrateSqlBackedContent(content, contextUser) {
2034
2529
  let parsed;
@@ -2038,8 +2533,11 @@ export class AgentRunner {
2038
2533
  catch {
2039
2534
  return content;
2040
2535
  }
2536
+ if (!this.hasUnhydratedSql(parsed)) {
2537
+ return content;
2538
+ }
2041
2539
  let changed = false;
2042
- const rq = new RunQuery();
2540
+ const rq = await this.adhocSqlRunner();
2043
2541
  const rootMeta = parsed?.metadata;
2044
2542
  const rootRows = parsed?.rows;
2045
2543
  if (rootMeta?.sql && (!rootRows || rootRows.length === 0)) {
@@ -2076,6 +2574,32 @@ export class AgentRunner {
2076
2574
  }
2077
2575
  return changed ? JSON.stringify(parsed) : content;
2078
2576
  }
2577
+ /** True when the parsed artifact carries stored SQL whose rows are missing. */
2578
+ hasUnhydratedSql(parsed) {
2579
+ const rootMeta = parsed?.metadata;
2580
+ const rootRows = parsed?.rows;
2581
+ if (rootMeta?.sql && (!rootRows || rootRows.length === 0)) {
2582
+ return true;
2583
+ }
2584
+ const tables = parsed?.tables;
2585
+ return Array.isArray(tables) && tables.some(t => !!t?.metadata?.sql && (!t.rows || t.rows.length === 0));
2586
+ }
2587
+ /**
2588
+ * A RunQuery on the host's read-only database login when one is registered with the action
2589
+ * engine, otherwise on the default provider.
2590
+ */
2591
+ async adhocSqlRunner() {
2592
+ try {
2593
+ const readOnly = await ActionEngineServer.Instance.GetReadOnlyProvider();
2594
+ if (readOnly) {
2595
+ return new RunQuery(readOnly);
2596
+ }
2597
+ }
2598
+ catch (error) {
2599
+ LogError(`[AgentRunner] Could not open the read-only provider; using the default provider: ${error instanceof Error ? error.message : String(error)}`);
2600
+ }
2601
+ return new RunQuery();
2602
+ }
2079
2603
  /**
2080
2604
  * Infer an artifact type name from a MIME type so ArtifactToolManager
2081
2605
  * can resolve the correct tool library.