@memberjunction/ai-agents 6.2.0-edge.6 → 6.2.0-edge.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -2
- package/dist/AgentRunner.d.ts +96 -3
- package/dist/AgentRunner.d.ts.map +1 -1
- package/dist/AgentRunner.js +438 -34
- package/dist/AgentRunner.js.map +1 -1
- package/dist/AgentWakeTriggerService.d.ts.map +1 -1
- package/dist/AgentWakeTriggerService.js +8 -1
- package/dist/AgentWakeTriggerService.js.map +1 -1
- package/dist/MJAIAgentRequestEntityServer.d.ts +15 -1
- package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
- package/dist/MJAIAgentRequestEntityServer.js +43 -3
- package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
- package/dist/MemoryWriteManager.d.ts +12 -0
- package/dist/MemoryWriteManager.d.ts.map +1 -1
- package/dist/MemoryWriteManager.js +18 -3
- package/dist/MemoryWriteManager.js.map +1 -1
- package/dist/agent-pre-execution-rag.d.ts.map +1 -1
- package/dist/agent-pre-execution-rag.js +1 -0
- package/dist/agent-pre-execution-rag.js.map +1 -1
- package/dist/agent-run-watchdog.d.ts +51 -13
- package/dist/agent-run-watchdog.d.ts.map +1 -1
- package/dist/agent-run-watchdog.js +89 -21
- package/dist/agent-run-watchdog.js.map +1 -1
- package/dist/agent-types/flow-agent-type.d.ts +6 -0
- package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
- package/dist/agent-types/flow-agent-type.js +70 -6
- package/dist/agent-types/flow-agent-type.js.map +1 -1
- package/dist/agent-types/loop-agent-prompt-params.d.ts +46 -3
- package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-prompt-params.js +9 -4
- package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
- package/dist/agent-types/loop-agent-response-type.d.ts +35 -4
- package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-response-type.js +1 -1
- package/dist/agent-types/loop-agent-response-type.js.map +1 -1
- package/dist/agent-types/loop-agent-type.d.ts +27 -4
- package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-type.js +121 -18
- package/dist/agent-types/loop-agent-type.js.map +1 -1
- package/dist/base-agent.d.ts +390 -37
- package/dist/base-agent.d.ts.map +1 -1
- package/dist/base-agent.js +2046 -433
- package/dist/base-agent.js.map +1 -1
- package/dist/catalog-narrowing.d.ts.map +1 -1
- package/dist/catalog-narrowing.js +6 -3
- package/dist/catalog-narrowing.js.map +1 -1
- package/dist/client-tool-results.d.ts +12 -0
- package/dist/client-tool-results.d.ts.map +1 -1
- package/dist/client-tool-results.js +21 -0
- package/dist/client-tool-results.js.map +1 -1
- package/dist/handoff-target.d.ts +80 -0
- package/dist/handoff-target.d.ts.map +1 -0
- package/dist/handoff-target.js +158 -0
- package/dist/handoff-target.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/memory-manager-agent.d.ts.map +1 -1
- package/dist/memory-manager-agent.js +2 -0
- package/dist/memory-manager-agent.js.map +1 -1
- package/dist/native-tools/action-tool-builder.d.ts +6 -0
- package/dist/native-tools/action-tool-builder.d.ts.map +1 -1
- package/dist/native-tools/action-tool-builder.js +21 -5
- package/dist/native-tools/action-tool-builder.js.map +1 -1
- package/dist/native-tools/control-tools.d.ts +15 -4
- package/dist/native-tools/control-tools.d.ts.map +1 -1
- package/dist/native-tools/control-tools.js +31 -14
- package/dist/native-tools/control-tools.js.map +1 -1
- package/dist/pipeline/pipeline-registry.d.ts +5 -12
- package/dist/pipeline/pipeline-registry.d.ts.map +1 -1
- package/dist/pipeline/pipeline-registry.js +28 -2
- package/dist/pipeline/pipeline-registry.js.map +1 -1
- package/dist/pipeline/providers/serialize.d.ts +7 -3
- package/dist/pipeline/providers/serialize.d.ts.map +1 -1
- package/dist/pipeline/providers/serialize.js +9 -5
- package/dist/pipeline/providers/serialize.js.map +1 -1
- package/dist/realtime/bridge-realtime-session-factory.d.ts +3 -3
- package/dist/realtime/bridge-realtime-session-factory.d.ts.map +1 -1
- package/dist/realtime/bridge-realtime-session-factory.js +12 -6
- package/dist/realtime/bridge-realtime-session-factory.js.map +1 -1
- package/dist/realtime/bridge-room-transcript-sink.js +2 -0
- package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
- package/dist/realtime/realtime-client-session-service.d.ts +72 -25
- package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
- package/dist/realtime/realtime-client-session-service.js +154 -54
- package/dist/realtime/realtime-client-session-service.js.map +1 -1
- package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
- package/dist/realtime/realtime-coagent-config.js +2 -28
- package/dist/realtime/realtime-coagent-config.js.map +1 -1
- package/dist/realtime/realtime-platform-credentials.d.ts +65 -0
- package/dist/realtime/realtime-platform-credentials.d.ts.map +1 -0
- package/dist/realtime/realtime-platform-credentials.js +148 -0
- package/dist/realtime/realtime-platform-credentials.js.map +1 -0
- package/dist/realtime/realtime-recording-capture.d.ts +1 -0
- package/dist/realtime/realtime-recording-capture.d.ts.map +1 -1
- package/dist/realtime/realtime-recording-capture.js +17 -3
- package/dist/realtime/realtime-recording-capture.js.map +1 -1
- package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -1
- package/dist/realtime/realtime-recording-opus-assembly.js +9 -4
- package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -1
- package/dist/realtime/realtime-session-runner.d.ts.map +1 -1
- package/dist/realtime/realtime-session-runner.js +5 -7
- package/dist/realtime/realtime-session-runner.js.map +1 -1
- package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
- package/dist/realtime/realtime-turn-moderator.js +1 -0
- package/dist/realtime/realtime-turn-moderator.js.map +1 -1
- package/dist/realtime/realtime-vendor-resolution.d.ts +41 -2
- package/dist/realtime/realtime-vendor-resolution.d.ts.map +1 -1
- package/dist/realtime/realtime-vendor-resolution.js +86 -4
- package/dist/realtime/realtime-vendor-resolution.js.map +1 -1
- package/dist/rubric-evaluation-agent-runner.js +1 -0
- package/dist/rubric-evaluation-agent-runner.js.map +1 -1
- package/dist/runtime-state-fragment.d.ts.map +1 -1
- package/dist/runtime-state-fragment.js +3 -0
- package/dist/runtime-state-fragment.js.map +1 -1
- package/dist/sub-agent-consult.d.ts +75 -0
- package/dist/sub-agent-consult.d.ts.map +1 -0
- package/dist/sub-agent-consult.js +193 -0
- package/dist/sub-agent-consult.js.map +1 -0
- package/dist/volatile-child-prompt.d.ts +7 -0
- package/dist/volatile-child-prompt.d.ts.map +1 -1
- package/dist/volatile-child-prompt.js +8 -0
- package/dist/volatile-child-prompt.js.map +1 -1
- package/package.json +20 -20
package/dist/AgentRunner.js
CHANGED
|
@@ -13,9 +13,12 @@ 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';
|
|
20
23
|
import { ActionEngineServer } from '@memberjunction/actions';
|
|
21
24
|
import { FileStorageEngine } from '@memberjunction/storage';
|
|
@@ -34,6 +37,21 @@ export function SelectPrimaryArtifact(fileArtifacts, payloadArtifact) {
|
|
|
34
37
|
export function selectPrimaryArtifact(fileArtifacts, payloadArtifact) {
|
|
35
38
|
return SelectPrimaryArtifact(fileArtifacts, payloadArtifact);
|
|
36
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
|
+
}
|
|
37
55
|
/**
|
|
38
56
|
* AgentRunner provides a thin wrapper for executing AI agents.
|
|
39
57
|
*
|
|
@@ -98,6 +116,8 @@ export class AgentRunner {
|
|
|
98
116
|
* instead: a truncated title still names the artifact the user is looking at.
|
|
99
117
|
*/
|
|
100
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; }
|
|
101
121
|
constructor(provider) {
|
|
102
122
|
this._provider = provider ?? Metadata.Provider;
|
|
103
123
|
}
|
|
@@ -254,10 +274,12 @@ export class AgentRunner {
|
|
|
254
274
|
}
|
|
255
275
|
const conversationWriter = options.ConversationWriter ?? contextUser;
|
|
256
276
|
let agentResponseDetail;
|
|
277
|
+
let saveGeneratedName;
|
|
257
278
|
try {
|
|
258
279
|
let conversationId;
|
|
259
280
|
let userMessageDetailId;
|
|
260
281
|
let agentResponseDetailId;
|
|
282
|
+
let isNewConversation = false;
|
|
261
283
|
if (options.agentResponseDetail) {
|
|
262
284
|
// The server created the reply row for this run (RunAIAgentFromConversationDetail): write into it.
|
|
263
285
|
agentResponseDetail = options.agentResponseDetail;
|
|
@@ -315,27 +337,16 @@ export class AgentRunner {
|
|
|
315
337
|
// Step 1: Get or create conversation
|
|
316
338
|
conversationId = options.conversationId || '';
|
|
317
339
|
if (!conversationId) {
|
|
340
|
+
isNewConversation = true;
|
|
318
341
|
LogStatus('Creating new conversation');
|
|
319
342
|
const conversation = await md.GetEntityObject('MJ: Conversations', conversationWriter);
|
|
320
|
-
//
|
|
321
|
-
// 1.
|
|
322
|
-
//
|
|
323
|
-
//
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
// Try to generate a name using the "Name Conversation" prompt (same as UI)
|
|
328
|
-
const nameResult = await this.generateConversationName(options.userMessage, contextUser, md, params);
|
|
329
|
-
if (nameResult) {
|
|
330
|
-
conversationName = nameResult.name;
|
|
331
|
-
conversationDescription = nameResult.description;
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
if (!conversationName) {
|
|
335
|
-
conversationName = `Chat with ${params.agent.Name}`;
|
|
336
|
-
}
|
|
337
|
-
conversation.Name = conversationName;
|
|
338
|
-
conversation.Description = conversationDescription || ''; // Set description too (like UI does)
|
|
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 = '';
|
|
339
350
|
conversation.UserID = params.userId || conversationWriter.ID;
|
|
340
351
|
conversation.Status = 'Available';
|
|
341
352
|
conversation.DataContextID = null; // Can be set by caller if needed
|
|
@@ -347,7 +358,10 @@ export class AgentRunner {
|
|
|
347
358
|
throw new Error('Failed to create conversation');
|
|
348
359
|
}
|
|
349
360
|
conversationId = conversation.ID;
|
|
350
|
-
LogStatus(`Created conversation ${conversationId}: ${
|
|
361
|
+
LogStatus(`Created conversation ${conversationId}: ${initialConversationName}`);
|
|
362
|
+
if (!options.conversationName && options.userMessage) {
|
|
363
|
+
saveGeneratedName = this.startConversationNaming(conversation, options.userMessage, contextUser, md, params);
|
|
364
|
+
}
|
|
351
365
|
}
|
|
352
366
|
// Step 2: Create conversation detail for user message
|
|
353
367
|
LogStatus('Creating conversation detail for user message');
|
|
@@ -436,7 +450,10 @@ export class AgentRunner {
|
|
|
436
450
|
// the conversation with the artifact already available." This means ALL artifacts
|
|
437
451
|
// on that path (both agent-produced Output and user-attached Input) should
|
|
438
452
|
// be available to the agent via artifact tools.
|
|
439
|
-
|
|
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);
|
|
440
457
|
const modifiedParams = {
|
|
441
458
|
...params,
|
|
442
459
|
// First-class conversationId gates the cross-turn context features
|
|
@@ -489,12 +506,10 @@ export class AgentRunner {
|
|
|
489
506
|
// then for any other save still in flight on this entity
|
|
490
507
|
await progressSaves;
|
|
491
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.
|
|
492
512
|
LogStatus('Updating agent response detail with final result');
|
|
493
|
-
// Reload to get any updates from agent execution
|
|
494
|
-
const loaded = await agentResponseDetail.Load(agentResponseDetailId);
|
|
495
|
-
if (!loaded) {
|
|
496
|
-
LogError(`Failed to reload agent response detail ${agentResponseDetailId}`);
|
|
497
|
-
}
|
|
498
513
|
const finalState = AgentRunner.ResolveFinalDetailState(agentResult);
|
|
499
514
|
agentResponseDetail.Message = finalState.Message;
|
|
500
515
|
agentResponseDetail.Status = finalState.Status;
|
|
@@ -559,7 +574,7 @@ export class AgentRunner {
|
|
|
559
574
|
const mediaToSave = agentResult.mediaOutputs;
|
|
560
575
|
LogStatus(`Processing ${mediaToSave.length} media output(s)`);
|
|
561
576
|
// Save to AIAgentRunMedia for permanent audit/lineage storage
|
|
562
|
-
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);
|
|
563
578
|
// Create Artifact + ArtifactVersion + ConversationDetailArtifact for each
|
|
564
579
|
// media output so the chat UI renders them as artifact cards. This replaces
|
|
565
580
|
// the old CreateConversationMediaAttachments path which wrote to the deprecated
|
|
@@ -674,6 +689,362 @@ export class AgentRunner {
|
|
|
674
689
|
}
|
|
675
690
|
throw error;
|
|
676
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
|
+
};
|
|
677
1048
|
}
|
|
678
1049
|
/**
|
|
679
1050
|
* Gets the maximum version number for an artifact.
|
|
@@ -699,6 +1070,7 @@ export class AgentRunner {
|
|
|
699
1070
|
ExtraFilter: `ArtifactID='${AgentRunner.filterId(artifactId, 'GetMaxVersionForArtifact artifactId')}'`,
|
|
700
1071
|
OrderBy: 'VersionNumber DESC',
|
|
701
1072
|
MaxRows: 1,
|
|
1073
|
+
SkipTotalRowCount: true,
|
|
702
1074
|
ResultType: 'entity_object'
|
|
703
1075
|
}, contextUser);
|
|
704
1076
|
if (result.Success && result.Results && result.Results.length > 0) {
|
|
@@ -746,6 +1118,7 @@ export class AgentRunner {
|
|
|
746
1118
|
ExtraFilter: `ArtifactID='${AgentRunner.filterId(artifactId, 'CheckForDuplicateVersion artifactId')}' AND VersionNumber=${latestVersion}`,
|
|
747
1119
|
Fields: ['ID', 'ContentHash'],
|
|
748
1120
|
MaxRows: 1,
|
|
1121
|
+
SkipTotalRowCount: true,
|
|
749
1122
|
ResultType: 'simple'
|
|
750
1123
|
}, contextUser);
|
|
751
1124
|
if (result.Success && result.Results.length > 0 && result.Results[0].ContentHash === candidateHash) {
|
|
@@ -824,6 +1197,7 @@ export class AgentRunner {
|
|
|
824
1197
|
`AND ArtifactVersionID='${AgentRunner.filterId(versionId, 'hasOutputLink versionId')}' AND Direction='Output'`,
|
|
825
1198
|
Fields: ['ID'],
|
|
826
1199
|
MaxRows: 1,
|
|
1200
|
+
SkipTotalRowCount: true,
|
|
827
1201
|
ResultType: 'simple'
|
|
828
1202
|
}, contextUser);
|
|
829
1203
|
if (!result.Success) {
|
|
@@ -858,6 +1232,7 @@ export class AgentRunner {
|
|
|
858
1232
|
ExtraFilter: `ConversationDetailID='${AgentRunner.filterId(conversationDetailId, 'FindPreviousArtifactForMessage conversationDetailId')}' AND Direction='Output'`,
|
|
859
1233
|
OrderBy: '__mj_CreatedAt DESC',
|
|
860
1234
|
MaxRows: 1,
|
|
1235
|
+
SkipTotalRowCount: true,
|
|
861
1236
|
ResultType: 'entity_object'
|
|
862
1237
|
}, contextUser);
|
|
863
1238
|
if (!result.Success || !result.Results || result.Results.length === 0) {
|
|
@@ -1302,6 +1677,7 @@ export class AgentRunner {
|
|
|
1302
1677
|
ExtraFilter: `ID='${EscapeSQLString(artifactId)}'`,
|
|
1303
1678
|
Fields: ['ID', 'UserID'],
|
|
1304
1679
|
MaxRows: 1,
|
|
1680
|
+
SkipTotalRowCount: true,
|
|
1305
1681
|
ResultType: 'simple',
|
|
1306
1682
|
},
|
|
1307
1683
|
{
|
|
@@ -1309,6 +1685,7 @@ export class AgentRunner {
|
|
|
1309
1685
|
ExtraFilter: `ArtifactID='${EscapeSQLString(artifactId)}' AND UserID='${EscapeSQLString(contextUser.ID)}' AND CanEdit=1`,
|
|
1310
1686
|
Fields: ['ID'],
|
|
1311
1687
|
MaxRows: 1,
|
|
1688
|
+
SkipTotalRowCount: true,
|
|
1312
1689
|
ResultType: 'simple',
|
|
1313
1690
|
},
|
|
1314
1691
|
], contextUser);
|
|
@@ -1439,6 +1816,8 @@ export class AgentRunner {
|
|
|
1439
1816
|
* @param agentRunId - The ID of the agent run
|
|
1440
1817
|
* @param mediaOutputs - Array of media outputs to save
|
|
1441
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
|
|
1442
1821
|
* @returns Array of saved AIAgentRunMedia IDs
|
|
1443
1822
|
* @since 3.1.0
|
|
1444
1823
|
*
|
|
@@ -1453,7 +1832,7 @@ export class AgentRunner {
|
|
|
1453
1832
|
* console.log(`Saved ${mediaIds.length} media outputs`);
|
|
1454
1833
|
* ```
|
|
1455
1834
|
*/
|
|
1456
|
-
async SaveAgentRunMedia(agentRunId, mediaOutputs, contextUser, provider) {
|
|
1835
|
+
async SaveAgentRunMedia(agentRunId, mediaOutputs, contextUser, provider, resolvedStorageAccountId) {
|
|
1457
1836
|
if (!mediaOutputs || mediaOutputs.length === 0) {
|
|
1458
1837
|
return [];
|
|
1459
1838
|
}
|
|
@@ -1461,6 +1840,12 @@ export class AgentRunner {
|
|
|
1461
1840
|
const savedIds = [];
|
|
1462
1841
|
const md = provider || this._provider;
|
|
1463
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
|
+
}
|
|
1464
1849
|
// Use AIEngine's cached modalities instead of a fresh DB call
|
|
1465
1850
|
const aiEngine = AIEngine.Instance;
|
|
1466
1851
|
for (let i = 0; i < mediaToSave.length; i++) {
|
|
@@ -1482,9 +1867,27 @@ export class AgentRunner {
|
|
|
1482
1867
|
continue;
|
|
1483
1868
|
}
|
|
1484
1869
|
mediaEntity.MimeType = mediaOutput.mimeType;
|
|
1485
|
-
//
|
|
1870
|
+
// Upload to MJStorage when configured (or fall back to InlineData) if NOT from prompt run media
|
|
1486
1871
|
if (!mediaOutput.promptRunMediaId && mediaOutput.data) {
|
|
1487
|
-
|
|
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;
|
|
1488
1891
|
}
|
|
1489
1892
|
// Set dimensions if available
|
|
1490
1893
|
if (mediaOutput.width) {
|
|
@@ -1614,11 +2017,12 @@ export class AgentRunner {
|
|
|
1614
2017
|
const estimatedSizeBytes = media.data
|
|
1615
2018
|
? Math.ceil(media.data.length * 0.75)
|
|
1616
2019
|
: undefined;
|
|
1617
|
-
//
|
|
2020
|
+
// Reuse fileId when SaveAgentRunMedia already uploaded the bytes to MJStorage;
|
|
2021
|
+
// otherwise upload when a storage account is configured, exactly as ProcessFileArtifacts
|
|
1618
2022
|
// does for file outputs.
|
|
1619
|
-
const fileId = media.data
|
|
2023
|
+
const fileId = media.fileId ?? (media.data
|
|
1620
2024
|
? await this.uploadToStorageIfConfigured(media.data, fileName, media.mimeType, contextUser, resolvedStorageAccountId, md, 'CreateMediaArtifacts')
|
|
1621
|
-
: undefined;
|
|
2025
|
+
: undefined);
|
|
1622
2026
|
if (fileId) {
|
|
1623
2027
|
await this.createFileArtifact(fileId, media.mimeType, fileName, estimatedSizeBytes, conversationDetailId, contextUser, md, true, `media ${media.modality}`);
|
|
1624
2028
|
}
|