.NET Workflows - Code Generation for Declarative Workflow (#655)

* Notes

* Readme typo

* Update readme

* Checkpoint

* Namespace fix

* Fix ID and namespace

* Checkpoint

* Verified

* Comments

* Isolate "Kit"

* Address note: static

* Checkpoint

* Checkpoint "Executor<>"

* Prefix and internal executors

* Test passing

* Cleanup

* Rename "session" concept

* Revert workflow debug

* Fix template base / pragma

* Tune system scope

* Update dotnet/src/Microsoft.Agents.Workflows.Declarative/CodeGen/ResetVariableTemplate.tt

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Fix empty template

* Add validation for codegen ut

* Fix test

* Codegen baselines

* Constant

* Prep

* Mark TODO

* Fix

* Namespace

* One more

* Update baselines

* Checkpoint

* Checkpoint

* Checkpoint

* fme

* Checkpoint

* Another step

* Fixed up

* Roslyn

* Fix

* More cleaning

* Async

* Fix

* Enum checkpoint

* Refine enum

* Checkpoint

* Sync templates

* Checkpoint

* Streamline

* Pre-merge analyzer updates

* Foreach

* Placeholders

* Checkpoint

* Clean-up

* Sample path resolution

* Checkpoint

* Checkpoint - Workflow Code Building

* Validation

* Test cleanup

* Update test basline

* Update test baseline

* Fix DefaultTemplate usage

* Validation checkpoint

* Fix break/continue edges

* Verify generated code builds

* Fix merge

* Fix build validation

* Update template handling of literal string values.

* Test for metadata case

* Update baselines

* Fix merge

* Checkpoint

* Checkpoint: Conditions

* Invoke Agent Checkpoint

* Namespace

* Address code-analysis issues

* Cross platform test support

* Invoke agent checkpoint

* Clean sample

* Checkpoint: Agent Invoke Input Messages

* Checkpoint - Passing

* Checkpoint

* Regenerate all template + port conversation fix

* Checkpoint: Tests good

* Fix test for unbuntu

* Fix build command

* Checkpoint - E2E

* Test fix

* Update integration tests

* Fix merge

* Update

* Checkpoint !!!

* Baby steps

* Checkpoint

* Checkpoint E2E !!!

* So close...

* Integrate test validation

* Fix merge

* Rebase tests

* Namespace

* Namespace

* Test cleanup

* Sample comment cleanup

* Checkpoint: List conversion

* Include these

* CheckPoint: ParseValue

* Namespace

* Fix sampel

* More namspace

* Comments

* Test updates

* Test fix

* Better build

* Shared code

* Sort solution

* Fix build

* Prune solution

* One more

* Conversion matrix

* Final table conversion

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Chris
2025-09-30 21:56:14 +00:00
committed by GitHub
co-authored by Copilot
parent 40f5b6d8fe
commit 77404d165c
181 changed files with 56682 additions and 230 deletions
@@ -0,0 +1,86 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.Interpreter;
namespace Microsoft.Agents.AI.Workflows.Declarative.Kit;
/// <summary>
/// Base class for action executors that do not consume the input message (most).
/// </summary>
/// <param name="id">The executor id</param>
/// <param name="session">Session to support formula expressions.</param>
public abstract class ActionExecutor(string id, FormulaSession session) : ActionExecutor<ActionExecutorResult>(id, session)
{
/// <inheritdoc/>
protected override ValueTask<object?> ExecuteAsync(IWorkflowContext context, ActionExecutorResult message, CancellationToken cancellationToken = default) =>
this.ExecuteAsync(context, cancellationToken);
/// <summary>
/// Executes the core logic of the action.
/// </summary>
/// <param name="context">The workflow execution context providing messaging and state services.</param>
/// <param name="cancellationToken">A token that can be used to observe cancellation.</param>
/// <returns>A <see cref="ValueTask"/> representing the asynchronous execution operation.</returns>
protected abstract ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default);
/// <summary>
/// Test wether the provided value matches the value returned by the prior executor.
/// </summary>
/// <param name="value">The value to test against the message result.</param>
/// <param name="message">The message containing the prior executor result.</param>
/// <returns>True if the value matches the message result</returns>
public static bool IsMatch<TValue>(TValue value, object? message) where TValue : class
{
ActionExecutorResult executorMessage = ActionExecutorResult.ThrowIfNot(message);
object? result = executorMessage.Result;
if (result is TValue resultValue)
{
return value.Equals(resultValue);
}
return false;
}
}
/// <summary>
/// Base class for an action executor that receives the initial trigger message.
/// </summary>
/// <typeparam name="TMessage">The type of message being handled</typeparam>
public abstract class ActionExecutor<TMessage> : Executor<TMessage> where TMessage : notnull
{
private readonly FormulaSession _session;
/// <summary>
/// Initializes a new instance of the <see cref="ActionExecutor{TMessage}"/> class.
/// </summary>
/// <param name="id">The executor id</param>
/// <param name="session">Session to support formula expressions.</param>
protected ActionExecutor(string id, FormulaSession session)
: base(id)
{
this._session = session;
}
/// <inheritdoc/>
public override async ValueTask HandleAsync(TMessage message, IWorkflowContext context)
{
object? result = await this.ExecuteAsync(new DeclarativeWorkflowContext(context, this._session.State), message, cancellationToken: default).ConfigureAwait(false);
Debug.WriteLine($"RESULT #{this.Id} - {result ?? "(null)"}");
await context.SendResultMessageAsync(this.Id, result).ConfigureAwait(false);
}
/// <summary>
/// Executes the core logic of the action.
/// </summary>
/// <param name="context">The workflow execution context providing messaging and state services.</param>
/// <param name="message">The the message handled by this executor.</param>
/// <param name="cancellationToken">A token that can be used to observe cancellation.</param>
/// <returns>A <see cref="ValueTask"/> representing the asynchronous execution operation.</returns>
protected abstract ValueTask<object?> ExecuteAsync(IWorkflowContext context, TMessage message, CancellationToken cancellationToken = default);
}
@@ -0,0 +1,35 @@
// Copyright (c) Microsoft. All rights reserved.
namespace Microsoft.Agents.AI.Workflows.Declarative.Kit;
/// <summary>
/// Message sent to initiate a transition to another <see cref="Executor"/>.
/// </summary>
public sealed record class ActionExecutorResult
{
/// <summary>
/// The identifier of the <see cref="Executor"/> that produced this message.
/// </summary>
public string ExecutorId { get; }
/// <summary>
/// The result of the action, if any provided.
/// </summary>
public object? Result { get; }
internal ActionExecutorResult(string executorId, object? result = null)
{
this.ExecutorId = executorId;
this.Result = result;
}
internal static ActionExecutorResult ThrowIfNot(object? message)
{
if (message is not ActionExecutorResult executorMessage)
{
throw new DeclarativeActionException($"Unexpected message type: {message?.GetType().Name ?? "(null)"} (Expected: {nameof(ActionExecutorResult)})");
}
return executorMessage;
}
}
@@ -0,0 +1,39 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Extensions.AI;
namespace Microsoft.Agents.AI.Workflows.Declarative.Kit;
/// <summary>
/// Base class for agent invokcation.
/// </summary>
/// <param name="id">The executor id</param>
/// <param name="session">Session to support formula expressions.</param>
/// <param name="agentProvider">Provider for accessing and manipulating agents and conversations.</param>
public abstract class AgentExecutor(string id, FormulaSession session, WorkflowAgentProvider agentProvider) : ActionExecutor(id, session)
{
/// <summary>
/// Invokes an agent using the provided <see cref="WorkflowAgentProvider"/>.
/// </summary>
/// <param name="context">The workflow execution context providing messaging and state services.</param>
/// <param name="agentName">The name or identifier of the agent.</param>
/// <param name="conversationId">The identifier of the conversation.</param>
/// <param name="autoSend">Send the agent's response as workflow output. (default: true).</param>
/// <param name="additionalInstructions">Optional additional instructions to the agent.</param>
/// <param name="inputMessages">Optional messages to add to the conversation prior to invocation.</param>
/// <param name="cancellationToken">A token that can be used to observe cancellation.</param>
/// <returns></returns>
protected ValueTask<AgentRunResponse> InvokeAgentAsync(
IWorkflowContext context,
string agentName,
string? conversationId,
bool autoSend,
string? additionalInstructions = null,
IEnumerable<ChatMessage>? inputMessages = null,
CancellationToken cancellationToken = default)
=> agentProvider.InvokeAgentAsync(this.Id, context, agentName, conversationId, autoSend, additionalInstructions, inputMessages, cancellationToken);
}
@@ -0,0 +1,54 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Agents.AI.Workflows.Declarative.Kit;
/// <summary>
/// Signature for a delegate that can be used with <see cref="DelegateExecutor{TMessages}"/>.
/// </summary>
/// <typeparam name="TMessage">The type of message being handled</typeparam>
/// <param name="context">The workflow execution context providing messaging and state services.</param>
/// <param name="message">The the message handled by this executor.</param>
/// <param name="cancellationToken">A token that can be used to observe cancellation.</param>
/// <returns>A <see cref="ValueTask"/> representing the asynchronous execution operation.</returns>
public delegate ValueTask DelegateAction<TMessage>(IWorkflowContext context, TMessage message, CancellationToken cancellationToken) where TMessage : notnull;
/// <summary>
/// Base class for an action executor that receives the initial trigger message.
/// </summary>
public sealed class DelegateExecutor(string id, FormulaSession session, DelegateAction<ActionExecutorResult>? action = null)
: DelegateExecutor<ActionExecutorResult>(id, session, action);
/// <summary>
/// Base class for an action executor that receives the initial trigger message.
/// </summary>
/// <typeparam name="TMessage">The type of message being handled</typeparam>
public class DelegateExecutor<TMessage> : ActionExecutor<TMessage> where TMessage : notnull
{
private readonly DelegateAction<TMessage>? _action;
/// <summary>
/// Initializes a new instance of the <see cref="ActionExecutor"/> class.
/// </summary>
/// <param name="id">The executor id</param>
/// <param name="session">Session to support formula expressions.</param>
/// <param name="action">An optional delegate to execute.</param>
public DelegateExecutor(string id, FormulaSession session, DelegateAction<TMessage>? action = null)
: base(id, session)
{
this._action = action;
}
/// <inheritdoc/>
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, TMessage message, CancellationToken cancellationToken = default)
{
if (this._action is not null)
{
await this._action.Invoke(context, message, cancellationToken).ConfigureAwait(false);
}
return default;
}
}
@@ -0,0 +1,13 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.Agents.AI.Workflows.Declarative.PowerFx;
namespace Microsoft.Agents.AI.Workflows.Declarative.Kit;
/// <summary>
/// Represents a session for supporting formula expressions within a workflow.
/// </summary>
public abstract class FormulaSession
{
internal abstract WorkflowFormulaState State { get; }
}
@@ -0,0 +1,166 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Agents.AI.Workflows.Declarative.Interpreter;
using Microsoft.Agents.AI.Workflows.Declarative.PowerFx;
using Microsoft.Bot.ObjectModel;
using Microsoft.Bot.ObjectModel.Abstractions;
namespace Microsoft.Agents.AI.Workflows.Declarative.Kit;
/// <summary>
/// Extension methods for <see cref="IWorkflowContext"/> that assist with
/// Power Fx expression evaluation.
/// </summary>
public static class IWorkflowContextExtensions
{
/// <summary>
/// Formats a template lines using the workflow's declarative state
/// and evaluating any embedded expressions (e.g., Power Fx) contained within each line.
/// </summary>
/// <param name="context">The workflow execution context used to restore persisted state prior to formatting.</param>
/// <param name="line">The template line to format.</param>
/// <param name="cancellationToken">A token that propagates notification when operation should be canceled.</param>
/// <returns>
/// A single string containing the formatted results of all lines separated by newline characters.
/// A trailing newline will be present if at least one line was processed.
/// </returns>
/// <example>
/// Example:
/// var text = await context.FormatAsync("Hello @{User.Name}", "Count: @{Metrics.Count}");
/// </example>
public static ValueTask<string> FormatTemplateAsync(this IWorkflowContext context, string line, CancellationToken cancellationToken = default) =>
context.FormatTemplateAsync([line], cancellationToken);
/// <summary>
/// Formats a template lines using the workflow's declarative state
/// and evaluating any embedded expressions (e.g., Power Fx) contained within each line.
/// </summary>
/// <param name="context">The workflow execution context used to restore persisted state prior to formatting.</param>
/// <param name="lines">The template lines to format.</param>
/// <param name="cancellationToken">A token that propagates notification when operation should be canceled.</param>
/// <returns>
/// A single string containing the formatted results of all lines separated by newline characters.
/// A trailing newline will be present if at least one line was processed.
/// </returns>
/// <example>
/// Example:
/// var text = await context.FormatAsync("Hello @{User.Name}", "Count: @{Metrics.Count}");
/// </example>
public static async ValueTask<string> FormatTemplateAsync(this IWorkflowContext context, IEnumerable<string> lines, CancellationToken cancellationToken = default)
{
WorkflowFormulaState state = await context.GetStateAsync(cancellationToken: default).ConfigureAwait(false);
StringBuilder builder = new();
foreach (string line in lines)
{
builder.AppendLine(state.Engine.Format(TemplateLine.Parse(line)));
}
return builder.ToString();
}
/// <summary>
/// Evaluate an expression using the workflow's declarative state.
/// </summary>
/// <param name="context">The workflow execution context used to restore persisted state prior to formatting.</param>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="cancellationToken">A token that propagates notification when operation should be canceled.</param>
/// <returns>The evaluated expression value</returns>
public static ValueTask<object?> EvaluateValueAsync(this IWorkflowContext context, string expression, CancellationToken cancellationToken = default) =>
context.EvaluateValueAsync<object>(expression, cancellationToken);
/// <summary>
/// Evaluate an expression using the workflow's declarative state.
/// </summary>
/// <param name="context">The workflow execution context used to restore persisted state prior to formatting.</param>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="cancellationToken">A token that propagates notification when operation should be canceled.</param>
/// <returns>The evaluated expression value</returns>
public static async ValueTask<TValue?> EvaluateValueAsync<TValue>(this IWorkflowContext context, string expression, CancellationToken cancellationToken = default)
{
WorkflowFormulaState state = await context.GetStateAsync(cancellationToken).ConfigureAwait(false);
EvaluationResult<DataValue> result = state.Evaluator.GetValue(ValueExpression.Expression(expression));
return (TValue?)result.Value.ToObject();
}
/// <summary>
/// Evaluate an expression using the workflow's declarative state.
/// </summary>
/// <typeparam name="TElement">The type of the list element.</typeparam>
/// <param name="context">The workflow execution context used to restore persisted state prior to formatting.</param>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="cancellationToken">A token that propagates notification when operation should be canceled.</param>
/// <returns>The evaluated list expression</returns>
public static async ValueTask<IList<TElement>?> EvaluateListAsync<TElement>(this IWorkflowContext context, string expression, CancellationToken cancellationToken = default)
{
WorkflowFormulaState state = await context.GetStateAsync(cancellationToken).ConfigureAwait(false);
EvaluationResult<DataValue> result = state.Evaluator.GetValue(ValueExpression.Expression(expression));
return result.Value.AsList<TElement>();
}
/// <summary>
/// Convert the result of an expression to the specified target type.
/// </summary>
/// <param name="context">The workflow execution context used to restore persisted state prior to formatting.</param>
/// <param name="targetType">Describes the target type for the value conversion.</param>
/// <param name="expression">The expression to evaluate.</param>
/// <param name="cancellationToken">A token that propagates notification when operation should be canceled.</param>
/// <returns>The converted expression value</returns>
public static async ValueTask<object?> ConvertValueAsync(this IWorkflowContext context, VariableType targetType, string expression, CancellationToken cancellationToken = default)
{
object? sourceValue = await context.EvaluateValueAsync(expression, cancellationToken).ConfigureAwait(false);
return sourceValue.ConvertType(targetType);
}
/// <summary>
/// Convert the variable value to the specified target type.
/// </summary>
/// <param name="context">The workflow execution context used to restore persisted state prior to formatting.</param>
/// <param name="targetType">Describes the target type for the value conversion.</param>
/// <param name="key">The key of the state value.</param>
/// <param name = "scopeName" > An optional name that specifies the scope to read.If null, the default scope is used.</param>
/// <param name="cancellationToken">A token that propagates notification when operation should be canceled.</param>
/// <returns>The converted value</returns>
public static async ValueTask<object?> ConvertValueAsync(this IWorkflowContext context, VariableType targetType, string key, string? scopeName = null, CancellationToken cancellationToken = default)
{
object? sourceValue = await context.ReadStateAsync<object>(key, scopeName).ConfigureAwait(false);
return sourceValue.ConvertType(targetType);
}
/// <summary>
/// Evaluate an expression using the workflow's declarative state.
/// </summary>
/// <typeparam name="TElement">The type of the list element.</typeparam>
/// <param name="context">The workflow execution context used to restore persisted state prior to formatting.</param>
/// <param name="key">The key of the state value.</param>
/// <param name = "scopeName" > An optional name that specifies the scope to read.If null, the default scope is used.</param>
/// <returns>The evaluated list expression</returns>
public static async ValueTask<IList<TElement>?> ReadListAsync<TElement>(this IWorkflowContext context, string key, string? scopeName = null)
{
object? value = await context.ReadStateAsync<object>(key, scopeName).ConfigureAwait(false);
return value.AsList<TElement>();
}
private static async Task<WorkflowFormulaState> GetStateAsync(this IWorkflowContext context, CancellationToken cancellationToken)
{
if (context is DeclarativeWorkflowContext declarativeContext)
{
return declarativeContext.State;
}
WorkflowFormulaState state = new(RecalcEngineFactory.Create());
await state.RestoreAsync(context, cancellationToken).ConfigureAwait(false);
return state;
}
}
@@ -0,0 +1,121 @@
// 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.Interpreter;
using Microsoft.Agents.AI.Workflows.Declarative.PowerFx;
using Microsoft.Bot.ObjectModel;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Configuration;
namespace Microsoft.Agents.AI.Workflows.Declarative.Kit;
/// <summary>
/// Base class for an entry-point workflow executor that receives the initial trigger message.
/// </summary>
/// <typeparam name="TInput">The type of the initial message that starts the workflow.</typeparam>
public abstract class RootExecutor<TInput> : Executor<TInput> where TInput : notnull
{
private readonly IConfiguration? _configuration;
private readonly WorkflowAgentProvider _agentProvider;
private readonly WorkflowFormulaState _state;
private readonly Func<TInput, ChatMessage>? _inputTransform;
/// <summary>
/// Get the shared formula session to provide to workflow <see cref="ActionExecutor"/> instances.
/// </summary>
public FormulaSession Session { get; }
/// <summary>
/// Initializes a new instance of the <see cref="RootExecutor{TInput}"/> class.
/// </summary>
/// <param name="id">An optional identifier. If omitted, an identifier is generated by the base class.</param>
/// <param name="options">Configuration options for workflow execution.</param>
/// <param name="inputTransform">An optional function to transform the input message into a <see cref="ChatMessage"/>.</param>
protected RootExecutor(string id, DeclarativeWorkflowOptions options, Func<TInput, ChatMessage>? inputTransform)
: base(id)
{
this._configuration = options.Configuration;
this._agentProvider = options.AgentProvider;
this._inputTransform = inputTransform;
this._state = new WorkflowFormulaState(options.CreateRecalcEngine());
this._state.InitializeSystem();
this.Session = new RootFormulaSession(this._state);
}
/// <inheritdoc/>
public override async ValueTask HandleAsync(TInput message, IWorkflowContext context)
{
DeclarativeWorkflowContext declarativeContext = new(context, this._state);
await this.ExecuteAsync(message, declarativeContext, cancellationToken: default).ConfigureAwait(false);
ChatMessage input = (this._inputTransform ?? DefaultInputTransform).Invoke(message);
string conversationId = await this._agentProvider.CreateConversationAsync(cancellationToken: default).ConfigureAwait(false);
await declarativeContext.QueueConversationUpdateAsync(conversationId).ConfigureAwait(false);
await this._agentProvider.CreateMessageAsync(conversationId, input, cancellationToken: default).ConfigureAwait(false);
await declarativeContext.SetLastMessageAsync(input).ConfigureAwait(false);
await declarativeContext.SendMessageAsync(new ActionExecutorResult(this.Id)).ConfigureAwait(false);
}
/// <summary>
/// Executes the core logic of the root workflow for the provided initial message.
/// </summary>
/// <param name="message">The initial input message that triggered workflow execution.</param>
/// <param name="context">The workflow execution context providing messaging and state services.</param>
/// <param name="cancellationToken">A token that propagates notification when operation should be canceled.</param>
/// <returns>A <see cref="ValueTask"/> representing the asynchronous execution operation.</returns>
protected abstract ValueTask ExecuteAsync(TInput message, IWorkflowContext context, CancellationToken cancellationToken = default);
/// <summary>
/// Initializes the specified variables from <see cref="IConfiguration"/> if available;
/// otherwise falls back to the process environment variables.
/// </summary>
/// <param name="context">The workflow execution context providing messaging and state services.</param>
/// <param name="variableNames">The set of variable names to initialize.</param>
/// <returns>A <see cref="ValueTask"/> representing the asynchronous execution operation.</returns>
protected async ValueTask InitializeEnvironmentAsync(IWorkflowContext context, params string[] variableNames)
{
foreach (string variableName in variableNames)
{
await context.QueueStateUpdateAsync(variableName, GetEnvironmentVariable(variableName), VariableScopeNames.Environment).ConfigureAwait(false);
}
string GetEnvironmentVariable(string name)
{
if (this._configuration is not null)
{
return this._configuration[name] ?? string.Empty;
}
return Environment.GetEnvironmentVariable(name) ?? string.Empty;
}
}
/// <summary>
/// Transforms the input message into a <see cref="ChatMessage"/>.
/// </summary>
/// <param name="message">The original input object.</param>
/// <returns>A <see cref="ChatMessage"/> derived from the input.</returns>
protected internal static ChatMessage DefaultInputTransform(TInput message) =>
message switch
{
ChatMessage chatMessage => chatMessage,
string stringMessage => new ChatMessage(ChatRole.User, stringMessage),
_ => new(ChatRole.User, $"{message}")
};
private sealed class RootFormulaSession : FormulaSession
{
internal RootFormulaSession(WorkflowFormulaState state)
{
this.State = state;
}
internal override WorkflowFormulaState State { get; }
}
}
@@ -0,0 +1,14 @@
// Copyright (c) Microsoft. All rights reserved.
namespace Microsoft.Agents.AI.Workflows.Declarative.Kit;
/// <summary>
/// Represents the absence of an assigned value for a variable used in an expression.
/// </summary>
public sealed record class UnassignedValue
{
/// <summary>
/// A singleton instance of <see cref="UnassignedValue"/>.
/// </summary>
public static UnassignedValue Instance { get; } = new();
}
@@ -0,0 +1,131 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections;
using System.Collections.Frozen;
using System.Collections.Generic;
using Microsoft.Agents.AI.Workflows.Declarative.Extensions;
using Microsoft.Bot.ObjectModel;
namespace Microsoft.Agents.AI.Workflows.Declarative.Kit;
/// <summary>
/// Describes an allowed declarative variable/type used in workflow configuration (primitives, lists, or record-like objects).
/// A record is modeled as IDictionary&lt;string, VariableType?&gt; along with an immutable schema for its fields.
/// </summary>
public sealed class VariableType
{
// Canonical CLR type used to mark a "record" (object with named fields and per-field types).
internal static readonly Type RecordType = typeof(IDictionary<string, object?>);
// Any list of primitive values or records.
internal static readonly Type ListType = typeof(IEnumerable);
// All supported root CLR types (only these may appear directly as VariableType.Type).
private static readonly FrozenSet<Type> s_supportedTypes =
[
typeof(bool),
typeof(int),
typeof(long),
typeof(float),
typeof(decimal),
typeof(double),
typeof(string),
typeof(DateTime),
typeof(TimeSpan),
RecordType,
ListType,
];
/// <summary>
/// Implicitly wraps a CLR <paramref name="type"/> as a <see cref="VariableType"/> (no validation is performed here).
/// Use <see cref="IsValid()"/> or <see cref="IsValid(Type)"/> to confirm support.
/// </summary>
public static implicit operator VariableType(Type type) => new(type);
/// <summary>
/// Returns true if <typeparamref name="TValue"/> is a supported variable type.
/// </summary>
public static bool IsValid<TValue>() => IsValid(typeof(TValue));
/// <summary>
/// Returns true if the provided CLR <paramref name="type"/> is one of the supported root types.
/// </summary>
public static bool IsValid(Type type) => s_supportedTypes.Contains(type);
/// <summary>
/// Creates a record (object) variable type with the supplied <paramref name="fields"/> schema.
/// Each tuple's Key is the field name; Type is the declared VariableType (nullable to allow "unknown"/late binding).
/// </summary>
public static VariableType Record(params IEnumerable<(string Key, VariableType? Type)> fields) =>
new(typeof(IDictionary<string, object?>))
{
Schema = fields.ToFrozenDictionary(kv => kv.Key, kv => kv.Type),
};
/// <summary>
/// Initializes a new instance wrapping the given CLR <paramref name="type"/> (which should be one of the supported types).
/// </summary>
internal VariableType(DataType type)
{
this.Type = type.ToClrType();
if (type is RecordDataType recordType)
{
this.Schema = CreateSchema(recordType.Properties);
}
else if (type is TableDataType tableDataType)
{
this.Schema = CreateSchema(tableDataType.Properties);
}
static FrozenDictionary<string, VariableType?> CreateSchema(IEnumerable<KeyValuePair<string, PropertyInfo>> properties)
{
Dictionary<string, VariableType?> schema = [];
foreach (KeyValuePair<string, PropertyInfo> field in properties)
{
if (field.Value.Type is null)
{
continue;
}
schema[field.Key] = new VariableType(field.Value.Type);
}
return schema.ToFrozenDictionary();
}
}
/// <summary>
/// Initializes a new instance wrapping the given CLR <paramref name="type"/> (which should be one of the supported types).
/// </summary>
public VariableType(Type type)
{
this.Type = type;
}
/// <summary>
/// The underlying CLR type that categorizes this variable (primitive, list, or record sentinel type).
/// </summary>
public Type Type { get; }
/// <summary>
/// Schema for record types: immutable mapping of field name to field VariableType (null means unspecified).
/// Null for non-record VariableTypes.
/// </summary>
public FrozenDictionary<string, VariableType?>? Schema { get; init; }
/// <summary>
/// True if this instance represents a record/object with a field schema.
/// </summary>
public bool IsList => ListType.IsAssignableFrom(this.Type);
/// <summary>
/// True if this instance represents a record/object with a field schema.
/// </summary>
public bool IsRecord => RecordType.IsAssignableFrom(this.Type);
/// <summary>
/// Instance convenience wrapper for <see cref="IsValid(Type)"/> on this VariableType's underlying CLR type.
/// </summary>
public bool IsValid() => IsValid(this.Type);
}