// Copyright (c) Microsoft. All rights reserved. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Agents.AI.Workflows.Declarative.Extensions; using Microsoft.Agents.AI.Workflows.Declarative.Kit; using Microsoft.Agents.AI.Workflows.Declarative.PowerFx; using Microsoft.Extensions.AI; namespace Microsoft.Agents.AI.Workflows.Declarative.Interpreter; /// /// The root executor for a declarative workflow. /// internal sealed class DeclarativeWorkflowExecutor( string workflowId, DeclarativeWorkflowOptions options, WorkflowFormulaState state, Func inputTransform) : Executor(workflowId), IResettableExecutor, IModeledAction where TInput : notnull { /// public ValueTask ResetAsync() { return default; } [SendsMessage(typeof(ActionExecutorResult))] public override async ValueTask HandleAsync(TInput message, IWorkflowContext context, CancellationToken cancellationToken = default) { // No state to restore if we're starting from the beginning. state.SetInitialized(); DeclarativeWorkflowContext declarativeContext = new(context, state); ChatMessage input = inputTransform.Invoke(message); string? conversationId = options.ConversationId; if (string.IsNullOrWhiteSpace(conversationId)) { conversationId = await options.AgentProvider.CreateConversationAsync(cancellationToken).ConfigureAwait(false); } await declarativeContext.QueueConversationUpdateAsync(conversationId, isExternal: true, cancellationToken).ConfigureAwait(false); ChatMessage inputMessage = await options.AgentProvider.CreateMessageAsync(conversationId, input, cancellationToken).ConfigureAwait(false); // Use the original input for System.LastMessage to ensure Text is preserved (the // service may strip text on round-trip), but substitute server-side media references // (e.g., HostedFileContent) so subsequent actions don't re-upload large blobs. await declarativeContext.SetLastMessageAsync(input.MergeForLastMessage(inputMessage)).ConfigureAwait(false); await context.SendResultMessageAsync(this.Id, cancellationToken).ConfigureAwait(false); } }