.NET: Fix some more static analysis diagnostics (#1025)

* S1006

* S2219

* S3236

* S3260

* S1125

* IDE0063

* IDE0062

* IDE0028
This commit is contained in:
Stephen Toub
2025-09-30 18:50:22 -04:00
committed by GitHub
Unverified
parent 77404d165c
commit 2539282d30
45 changed files with 69 additions and 74 deletions
@@ -96,7 +96,7 @@ namespace SampleApp
public string? ThreadDbKey { get; private set; }
public override async Task AddMessagesAsync(IEnumerable<ChatMessage> messages, CancellationToken cancellationToken)
public override async Task AddMessagesAsync(IEnumerable<ChatMessage> messages, CancellationToken cancellationToken = default)
{
this.ThreadDbKey ??= Guid.NewGuid().ToString("N");
@@ -113,7 +113,7 @@ namespace SampleApp
}), cancellationToken);
}
public override async Task<IEnumerable<ChatMessage>> GetMessagesAsync(CancellationToken cancellationToken)
public override async Task<IEnumerable<ChatMessage>> GetMessagesAsync(CancellationToken cancellationToken = default)
{
var collection = this._vectorStore.GetCollection<string, ChatHistoryItem>("ChatHistory");
await collection.EnsureCollectionExistsAsync(cancellationToken);
@@ -219,7 +219,7 @@ internal sealed class Shuffler(string[] reducerIds, string[] mapperIds, string i
{
private readonly string[] _reducerIds = reducerIds;
private readonly string[] _mapperIds = mapperIds;
private readonly List<MapComplete> _mapResults = new();
private readonly List<MapComplete> _mapResults = [];
/// <summary>
/// Aggregate mapper outputs and write one partition file per reducer.
@@ -97,7 +97,7 @@ public sealed class InMemoryChatMessageStore : ChatMessageStore, IList<ChatMessa
}
/// <inheritdoc />
public override async Task AddMessagesAsync(IEnumerable<ChatMessage> messages, CancellationToken cancellationToken)
public override async Task AddMessagesAsync(IEnumerable<ChatMessage> messages, CancellationToken cancellationToken = default)
{
_ = Throw.IfNull(messages);
@@ -110,7 +110,7 @@ public sealed class InMemoryChatMessageStore : ChatMessageStore, IList<ChatMessa
}
/// <inheritdoc />
public override async Task<IEnumerable<ChatMessage>> GetMessagesAsync(CancellationToken cancellationToken)
public override async Task<IEnumerable<ChatMessage>> GetMessagesAsync(CancellationToken cancellationToken = default)
{
if (this.ReducerTriggerEvent is ChatReducerTriggerEvent.BeforeMessagesRetrieval && this.ChatReducer is not null)
{
@@ -26,8 +26,8 @@ public static class AIAgentExtensions
TaskManager? taskManager = null,
ILoggerFactory? loggerFactory = null)
{
ArgumentNullException.ThrowIfNull(agent, nameof(agent));
ArgumentNullException.ThrowIfNull(agent.Name, nameof(agent.Name));
ArgumentNullException.ThrowIfNull(agent);
ArgumentNullException.ThrowIfNull(agent.Name);
taskManager ??= new();
@@ -15,7 +15,7 @@ public sealed class DeclarativeWorkflowOptions(WorkflowAgentProvider agentProvid
/// <summary>
/// Defines the agent provider.
/// </summary>
public WorkflowAgentProvider AgentProvider { get; } = Throw.IfNull(agentProvider, nameof(agentProvider));
public WorkflowAgentProvider AgentProvider { get; } = Throw.IfNull(agentProvider);
/// <summary>
/// Defines the configuration settings for the workflow.
@@ -15,7 +15,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
internal sealed class AddConversationMessageExecutor(AddConversationMessage model, WorkflowAgentProvider agentProvider, WorkflowFormulaState state) :
DeclarativeActionExecutor<AddConversationMessage>(model, state)
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
Throw.IfNull(this.Model.ConversationId, $"{nameof(this.Model)}.{nameof(this.Model.ConversationId)}");
string conversationId = this.Evaluator.GetValue(this.Model.ConversationId).Value;
@@ -13,7 +13,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
internal sealed class ClearAllVariablesExecutor(ClearAllVariables model, WorkflowFormulaState state)
: DeclarativeActionExecutor<ClearAllVariables>(model, state)
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
EvaluationResult<VariablesToClearWrapper> variablesResult = this.Evaluator.GetValue(this.Model.Variables);
@@ -48,7 +48,7 @@ internal sealed class ConditionGroupExecutor : DeclarativeActionExecutor<Conditi
return string.Equals(Steps.Else(this.Model), executorMessage.Result as string, StringComparison.Ordinal);
}
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
for (int index = 0; index < this.Model.Conditions.Length; ++index)
{
@@ -16,7 +16,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
internal sealed class CopyConversationMessagesExecutor(CopyConversationMessages model, WorkflowAgentProvider agentProvider, WorkflowFormulaState state) :
DeclarativeActionExecutor<CopyConversationMessages>(model, state)
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
Throw.IfNull(this.Model.ConversationId, $"{nameof(this.Model)}.{nameof(this.Model.ConversationId)}");
string conversationId = this.Evaluator.GetValue(this.Model.ConversationId).Value;
@@ -12,7 +12,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
internal sealed class CreateConversationExecutor(CreateConversation model, WorkflowAgentProvider agentProvider, WorkflowFormulaState state) :
DeclarativeActionExecutor<CreateConversation>(model, state)
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
string conversationId = await agentProvider.CreateConversationAsync(cancellationToken).ConfigureAwait(false);
await this.AssignAsync(this.Model.ConversationId?.Path, FormulaValue.New(conversationId), context).ConfigureAwait(false);
@@ -11,7 +11,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
internal sealed class DefaultActionExecutor(DialogAction model, WorkflowFormulaState state) :
DeclarativeActionExecutor(model, state)
{
protected override ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
// No action needed - the edge will be followed automatically
return default;
@@ -16,7 +16,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
internal sealed class EditTableExecutor(EditTable model, WorkflowFormulaState state) : DeclarativeActionExecutor<EditTable>(model, state)
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
PropertyPath variablePath = Throw.IfNull(this.Model.ItemsVariable?.Path, $"{nameof(this.Model)}.{nameof(this.Model.ItemsVariable)}");
@@ -16,7 +16,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
internal sealed class EditTableV2Executor(EditTableV2 model, WorkflowFormulaState state) : DeclarativeActionExecutor<EditTableV2>(model, state)
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
PropertyPath variablePath = Throw.IfNull(this.Model.ItemsVariable?.Path, $"{nameof(this.Model)}.{nameof(this.Model.ItemsVariable)}");
@@ -35,7 +35,7 @@ internal sealed class ForeachExecutor : DeclarativeActionExecutor<Foreach>
protected override bool IsDiscreteAction => false;
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
this._index = 0;
@@ -20,7 +20,7 @@ internal sealed class InvokeAzureAgentExecutor(InvokeAzureAgent model, WorkflowA
private AzureAgentInput? AgentInput => this.Model.Input;
private AzureAgentOutput? AgentOutput => this.Model.Output;
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
string? conversationId = this.GetConversationId();
string agentName = this.GetAgentName();
@@ -17,7 +17,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
internal sealed class ParseValueExecutor(ParseValue model, WorkflowFormulaState state) :
DeclarativeActionExecutor<ParseValue>(model, state)
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
PropertyPath variablePath = Throw.IfNull(this.Model.Variable?.Path, $"{nameof(this.Model)}.{nameof(model.Variable)}");
ValueExpression valueExpression = Throw.IfNull(this.Model.Value, $"{nameof(this.Model)}.{nameof(this.Model.Value)}");
@@ -37,7 +37,7 @@ internal sealed class QuestionExecutor(Question model, WorkflowFormulaState stat
return executorMessage.Result is null;
}
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
await this._promptCount.WriteAsync(context, 0).ConfigureAwait(false);
@@ -14,7 +14,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
internal sealed class ResetVariableExecutor(ResetVariable model, WorkflowFormulaState state) :
DeclarativeActionExecutor<ResetVariable>(model, state)
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
Throw.IfNull(this.Model.Variable, $"{nameof(this.Model)}.{nameof(model.Variable)}");
await context.QueueStateResetAsync(this.Model.Variable).ConfigureAwait(false);
@@ -14,7 +14,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
internal sealed class RetrieveConversationMessageExecutor(RetrieveConversationMessage model, WorkflowAgentProvider agentProvider, WorkflowFormulaState state) :
DeclarativeActionExecutor<RetrieveConversationMessage>(model, state)
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
Throw.IfNull(this.Model.ConversationId, $"{nameof(this.Model)}.{nameof(this.Model.ConversationId)}");
string conversationId = this.Evaluator.GetValue(this.Model.ConversationId).Value;
@@ -16,7 +16,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
internal sealed class RetrieveConversationMessagesExecutor(RetrieveConversationMessages model, WorkflowAgentProvider agentProvider, WorkflowFormulaState state) :
DeclarativeActionExecutor<RetrieveConversationMessages>(model, state)
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
Throw.IfNull(this.Model.ConversationId, $"{nameof(this.Model)}.{nameof(this.Model.ConversationId)}");
string conversationId = this.Evaluator.GetValue(this.Model.ConversationId).Value;
@@ -12,7 +12,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
internal sealed class SendActivityExecutor(SendActivity model, WorkflowFormulaState state) :
DeclarativeActionExecutor<SendActivity>(model, state)
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
if (this.Model.Activity is MessageActivityTemplate messageActivity)
{
@@ -14,7 +14,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
internal sealed class SetMultipleVariablesExecutor(SetMultipleVariables model, WorkflowFormulaState state)
: DeclarativeActionExecutor<SetMultipleVariables>(model, state)
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
foreach (VariableAssignment assignment in this.Model.Assignments)
{
@@ -13,7 +13,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
internal sealed class SetTextVariableExecutor(SetTextVariable model, WorkflowFormulaState state)
: DeclarativeActionExecutor<SetTextVariable>(model, state)
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
if (this.Model.Value is null)
{
@@ -15,7 +15,7 @@ namespace Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
internal sealed class SetVariableExecutor(SetVariable model, WorkflowFormulaState state)
: DeclarativeActionExecutor<SetVariable>(model, state)
{
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken)
protected override async ValueTask<object?> ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
{
PropertyPath variablePath = Throw.IfNull(this.Model.Variable?.Path, $"{nameof(this.Model)}.{nameof(model.Variable)}");
@@ -43,7 +43,7 @@ internal sealed class WorkflowExpressionEngine
private EvaluationResult<bool> Evaluate(BoolExpression expression)
{
Throw.IfNull(expression, nameof(expression));
Throw.IfNull(expression);
if (expression.IsLiteral)
{
@@ -67,7 +67,7 @@ internal sealed class WorkflowExpressionEngine
private EvaluationResult<string> Evaluate(StringExpression expression)
{
Throw.IfNull(expression, nameof(expression));
Throw.IfNull(expression);
if (expression.IsLiteral)
{
@@ -96,7 +96,7 @@ internal sealed class WorkflowExpressionEngine
private EvaluationResult<long> Evaluate(IntExpression expression)
{
Throw.IfNull(expression, nameof(expression));
Throw.IfNull(expression);
if (expression.IsLiteral)
{
@@ -120,7 +120,7 @@ internal sealed class WorkflowExpressionEngine
private EvaluationResult<double> Evaluate(NumberExpression expression)
{
Throw.IfNull(expression, nameof(expression));
Throw.IfNull(expression);
if (expression.IsLiteral)
{
@@ -149,7 +149,7 @@ internal sealed class WorkflowExpressionEngine
private EvaluationResult<DataValue> Evaluate(ValueExpression expression)
{
Throw.IfNull(expression, nameof(expression));
Throw.IfNull(expression);
if (expression.IsLiteral)
{
@@ -163,7 +163,7 @@ internal sealed class WorkflowExpressionEngine
private EvaluationResult<TValue> Evaluate<TValue>(EnumExpression<TValue> expression) where TValue : EnumWrapper
{
Throw.IfNull(expression, nameof(expression));
Throw.IfNull(expression);
if (expression.IsLiteral)
{
@@ -184,7 +184,7 @@ internal sealed class WorkflowExpressionEngine
private EvaluationResult<TValue?> Evaluate<TValue>(ObjectExpression<TValue> expression) where TValue : BotElement
{
Throw.IfNull(expression, nameof(expression));
Throw.IfNull(expression);
if (expression.LiteralValue is not null)
{
@@ -215,7 +215,7 @@ internal sealed class WorkflowExpressionEngine
private EvaluationResult<ImmutableArray<TValue>> Evaluate<TValue>(ArrayExpression<TValue> expression)
{
Throw.IfNull(expression, nameof(expression));
Throw.IfNull(expression);
if (expression.IsLiteral)
{
@@ -229,7 +229,7 @@ internal sealed class WorkflowExpressionEngine
private EvaluationResult<ImmutableArray<TValue>> Evaluate<TValue>(ArrayExpressionOnly<TValue> expression)
{
Throw.IfNull(expression, nameof(expression));
Throw.IfNull(expression);
EvaluationResult<FormulaValue> expressionResult = this.EvaluateScope(expression);
@@ -583,7 +583,7 @@ public static partial class AgentWorkflowBuilder
public ValueTask ResetAsync() => default;
}
private record class HandoffState(
private sealed record class HandoffState(
TurnToken TurnToken,
string? InvokedHandoff,
List<ChatMessage> Messages);
@@ -11,7 +11,7 @@ namespace Microsoft.Agents.AI.Workflows.Execution;
internal sealed class EdgeMap
{
private readonly Dictionary<EdgeId, EdgeRunner> _edgeRunners = [];
private readonly Dictionary<EdgeId, IStatefulEdgeRunner> _statefulRunners = new();
private readonly Dictionary<EdgeId, IStatefulEdgeRunner> _statefulRunners = [];
private readonly Dictionary<string, InputEdgeRunner> _portEdgeRunners;
private readonly InputEdgeRunner _inputRunner;
@@ -21,7 +21,7 @@ internal sealed class MessageEnvelope(object message, ExecutorIdentity source, T
internal MessageEnvelope(object message, ExecutorIdentity source, Type declaredType, string? targetId = null)
: this(message, source, new TypeId(declaredType), targetId)
{
if (!declaredType.IsAssignableFrom(message.GetType()))
if (!declaredType.IsInstanceOfType(message))
{
throw new ArgumentException($"The declared type {declaredType} is not compatible with the message instance of type {message.GetType()}");
}
@@ -39,7 +39,7 @@ public record ExternalRequest(InputPortInfo PortInfo, string RequestId, Portable
/// <exception cref="InvalidOperationException">Thrown when the input data object does not match the expected request type.</exception>
public static ExternalRequest Create(InputPort port, [NotNull] object data, string? requestId = null)
{
if (!port.Request.IsAssignableFrom(Throw.IfNull(data).GetType()))
if (!port.Request.IsInstanceOfType(Throw.IfNull(data)))
{
throw new InvalidOperationException(
$"Message type {data.GetType().Name} is not assignable to the request type {port.Request.Name} of input port {port.Id}.");
@@ -158,7 +158,7 @@ public sealed class PortableValue
this._deserializedValueCache ??= delayedDeserialization.Deserialize(targetType);
}
if (this.Value is not null && targetType.IsAssignableFrom(this.Value.GetType()))
if (this.Value is not null && targetType.IsInstanceOfType(this.Value))
{
value = this.Value;
return true;
@@ -86,7 +86,7 @@ internal static class RouteBuilderExtensions
Throw.IfNull(builder);
Type executorType = typeof(TExecutor);
Debug.Assert(executorType.IsAssignableFrom(executor.GetType()),
Debug.Assert(executorType.IsInstanceOfType(executor),
"executorType must be the same type or a base type of the executor instance.");
foreach (MessageHandlerInfo handlerInfo in executorType.GetHandlerInfos())
@@ -11,7 +11,7 @@ namespace Microsoft.Agents.AI.Workflows.Specialized;
internal sealed class RequestInfoExecutor : Executor
{
private readonly Dictionary<string, ExternalRequest> _wrappedRequests = new();
private readonly Dictionary<string, ExternalRequest> _wrappedRequests = [];
private InputPort Port { get; }
private IExternalRequestSink? RequestSink { get; set; }
@@ -57,7 +57,7 @@ internal sealed class RequestInfoExecutor : Executor
object? maybeRequest = message.AsType(this.Port.Request);
if (maybeRequest != null)
{
Debug.Assert(this.Port.Request.IsAssignableFrom(maybeRequest.GetType()));
Debug.Assert(this.Port.Request.IsInstanceOfType(maybeRequest));
ExternalRequest request = ExternalRequest.Create(this.Port, maybeRequest!);
await this.RequestSink!.PostAsync(request).ConfigureAwait(false);
@@ -93,7 +93,7 @@ internal sealed class RequestInfoExecutor : Executor
public async ValueTask<ExternalRequest> HandleAsync(object message, IWorkflowContext context)
{
Throw.IfNull(message);
Debug.Assert(this.Port.Request.IsAssignableFrom(message.GetType()));
Debug.Assert(this.Port.Request.IsInstanceOfType(message));
ExternalRequest request = ExternalRequest.Create(this.Port, message);
await this.RequestSink!.PostAsync(request).ConfigureAwait(false);
@@ -21,7 +21,7 @@ public static class WorkflowVisualizer
/// <returns>A string representation of the workflow in DOT format.</returns>
public static string ToDotString(this Workflow workflow)
{
Throw.IfNull(workflow, nameof(workflow));
Throw.IfNull(workflow);
var lines = new List<string>
{
@@ -249,10 +249,7 @@ public static class WorkflowVisualizer
{
var sortedSources = sources.OrderBy(x => x, StringComparer.Ordinal).ToList();
var input = target + "|" + string.Join("|", sortedSources);
using (var sha256 = SHA256.Create())
{
return ComputeShortHash(input);
}
return ComputeShortHash(input);
}
private static string ComputeShortHash(string input)
@@ -24,7 +24,7 @@ internal sealed class WorkflowHostAgent : AIAgent
public WorkflowHostAgent(Workflow<List<ChatMessage>> workflow, string? id = null, string? name = null)
{
this._workflow = Throw.IfNull(workflow, nameof(workflow));
this._workflow = Throw.IfNull(workflow);
this._id = id;
this.Name = name;
@@ -45,14 +45,14 @@ internal sealed class WorkflowMessageStore : ChatMessageStore
internal void AddMessages(params IEnumerable<ChatMessage> messages) => this._chatMessages.AddRange(messages);
public override Task AddMessagesAsync(IEnumerable<ChatMessage> messages, CancellationToken cancellationToken)
public override Task AddMessagesAsync(IEnumerable<ChatMessage> messages, CancellationToken cancellationToken = default)
{
this._chatMessages.AddRange(messages);
return Task.CompletedTask;
}
public override Task<IEnumerable<ChatMessage>> GetMessagesAsync(CancellationToken cancellationToken) => Task.FromResult<IEnumerable<ChatMessage>>(this._chatMessages.AsReadOnly());
public override Task<IEnumerable<ChatMessage>> GetMessagesAsync(CancellationToken cancellationToken = default) => Task.FromResult<IEnumerable<ChatMessage>>(this._chatMessages.AsReadOnly());
public IEnumerable<ChatMessage> GetFromBookmark()
{
@@ -31,9 +31,7 @@ public sealed class WorkflowOutputEvent : WorkflowEvent
/// </summary>
/// <param name="type">The type to compare with the type of the underlying data.</param>
/// <returns>true if the underlying data is assignable to type T; otherwise, false.</returns>
public bool IsType(Type type) => this.Data == null
? false
: type.IsAssignableFrom(this.Data.GetType());
public bool IsType(Type type) => this.Data is { } data && type.IsInstanceOfType(data);
/// <summary>
/// Attempts to retrieve the underlying data as the specified type.
@@ -12,7 +12,7 @@ internal sealed class WorkflowThread : AgentThread
public WorkflowThread(string workflowId, string? workflowName, string runId)
{
this.MessageStore = new();
this.RunId = Throw.IfNullOrEmpty(runId, nameof(runId));
this.RunId = Throw.IfNullOrEmpty(runId);
}
public WorkflowThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
@@ -171,7 +171,7 @@ public sealed class OpenTelemetryAgent : DelegatingAIAgent, IDisposable
private sealed class ForwardingChatClient(OpenTelemetryAgent parentAgent) : IChatClient
{
public async Task<ChatResponse> GetResponseAsync(
IEnumerable<ChatMessage> messages, ChatOptions? options, CancellationToken cancellationToken)
IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default)
{
ForwardedOptions? fo = options as ForwardedOptions;
@@ -186,7 +186,7 @@ public sealed class OpenTelemetryAgent : DelegatingAIAgent, IDisposable
}
public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
IEnumerable<ChatMessage> messages, ChatOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken)
IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
ForwardedOptions? fo = options as ForwardedOptions;
@@ -320,7 +320,7 @@ public class ChatClientAgentRunOptionsTests
// Arrange
var originalClient = new Mock<IChatClient>();
IChatClient ClientFactory(IChatClient client) => null!;
static IChatClient ClientFactory(IChatClient client) => null!;
var agent = new ChatClientAgent(originalClient.Object);
var messages = new List<ChatMessage> { new(ChatRole.User, "Test message") };
@@ -344,7 +344,7 @@ public sealed class FunctionInvocationDelegatingAgentTests
if (options?.Tools?.FirstOrDefault() is AIFunction function)
{
executionOrder.Add("Direct-Function-Invocation");
await function.InvokeAsync(new AIFunctionArguments(), ct);
await function.InvokeAsync([], ct);
}
return new ChatResponse([new ChatMessage(ChatRole.Assistant, "Response after direct invocation")]);
});
@@ -476,7 +476,7 @@ public sealed class FunctionInvocationDelegatingAgentTests
var messages = new List<ChatMessage> { new(ChatRole.User, "Test message") };
const string ModifiedResult = "Modified by middleware";
async ValueTask<object?> MiddlewareCallbackAsync(AIAgent agent, FunctionInvocationContext context, Func<FunctionInvocationContext, CancellationToken, ValueTask<object?>> next, CancellationToken cancellationToken)
static async ValueTask<object?> MiddlewareCallbackAsync(AIAgent agent, FunctionInvocationContext context, Func<FunctionInvocationContext, CancellationToken, ValueTask<object?>> next, CancellationToken cancellationToken)
{
await next(context, cancellationToken);
return ModifiedResult; // Return the modified result instead of setting context property
@@ -770,7 +770,7 @@ public sealed class FunctionInvocationDelegatingAgentTests
var innerAgent = new ChatClientAgent(mockChatClient.Object);
var messages = new List<ChatMessage> { new(ChatRole.User, "Test message") };
ValueTask<object?> MiddlewareCallbackAsync(AIAgent agent, FunctionInvocationContext context, Func<FunctionInvocationContext, CancellationToken, ValueTask<object?>> next, CancellationToken cancellationToken)
static ValueTask<object?> MiddlewareCallbackAsync(AIAgent agent, FunctionInvocationContext context, Func<FunctionInvocationContext, CancellationToken, ValueTask<object?>> next, CancellationToken cancellationToken)
{
// Don't call next() - this should prevent function execution
// Return the blocked result directly
@@ -21,13 +21,13 @@ public sealed class TestOutputAdapter(ITestOutputHelper output) : TextWriter, IL
public bool IsEnabled(LogLevel logLevel) => true;
public override void WriteLine(object? value = null) => this.SafeWrite($"{value}");
public override void WriteLine(object? value) => this.SafeWrite($"{value}");
public override void WriteLine(string? format, params object?[] arg) => this.SafeWrite(string.Format(format ?? string.Empty, arg));
public override void WriteLine(string? value) => this.SafeWrite(value ?? string.Empty);
public override void Write(object? value = null) => this.SafeWrite($"{value}");
public override void Write(object? value) => this.SafeWrite($"{value}");
public override void Write(char[]? buffer) => this.SafeWrite(new string(buffer));
@@ -21,13 +21,13 @@ public sealed class TestOutputAdapter(ITestOutputHelper output) : TextWriter, IL
public bool IsEnabled(LogLevel logLevel) => true;
public override void WriteLine(object? value = null) => this.SafeWrite($"{value}");
public override void WriteLine(object? value) => this.SafeWrite($"{value}");
public override void WriteLine(string? format, params object?[] arg) => this.SafeWrite(string.Format(format ?? string.Empty, arg));
public override void WriteLine(string? value) => this.SafeWrite(value ?? string.Empty);
public override void Write(object? value = null) => this.SafeWrite($"{value}");
public override void Write(object? value) => this.SafeWrite($"{value}");
public override void Write(char[]? buffer) => this.SafeWrite(new string(buffer));
@@ -103,7 +103,7 @@ public class EdgeRunnerTests
&& (!targetMatch.HasValue || targetMatch.Value);
bool expectForwardFrom3 = !assignerSelectsEmpty.HasValue && !targetMatch.HasValue; // if there is a target, it is never executor3
HashSet<string> expectedReceivers = new();
HashSet<string> expectedReceivers = [];
if (expectForwardFrom2)
{
expectedReceivers.Add("executor2");
@@ -13,7 +13,7 @@ internal static class Step5EntryPoint
{
public static async ValueTask<string> RunAsync(TextWriter writer, Func<string, int> userGuessCallback, bool rehydrateToRestore = false, CheckpointManager? checkpointManager = null)
{
Dictionary<CheckpointInfo, (NumberSignal signal, string? prompt)> checkpointedOutputs = new();
Dictionary<CheckpointInfo, (NumberSignal signal, string? prompt)> checkpointedOutputs = [];
NumberSignal signal = NumberSignal.Init;
string? prompt = Step4EntryPoint.UpdatePrompt(null, signal);
@@ -84,7 +84,7 @@ public class WorkflowVisualizerTests
var end = new MockExecutor("end");
// Condition that is never used during viz, but presence should mark the edge
bool OnlyIfFoo(string? msg) => msg == "foo";
static bool OnlyIfFoo(string? msg) => msg == "foo";
var workflow = new WorkflowBuilder("start")
.AddEdge<string>(start, mid, OnlyIfFoo)
@@ -195,7 +195,7 @@ public class WorkflowVisualizerTests
var c = new MockExecutor("c");
var end = new ListStrTargetExecutor("end");
bool Condition(string? msg) => msg?.Contains("test") ?? false;
static bool Condition(string? msg) => msg?.Contains("test") ?? false;
var workflow = new WorkflowBuilder("start")
.AddEdge<string>(start, a, Condition) // Conditional edge
@@ -241,7 +241,7 @@ public class WorkflowVisualizerTests
// Test visualization of self-loop edge
var executor = new MockExecutor("loop");
bool LoopCondition(string? msg) => (msg?.Length ?? 0) < 10;
static bool LoopCondition(string? msg) => (msg?.Length ?? 0) < 10;
var workflow = new WorkflowBuilder("loop")
.AddEdge<string>(executor, executor, LoopCondition)
@@ -281,7 +281,7 @@ public class WorkflowVisualizerTests
var mid = new MockExecutor("mid");
var end = new MockExecutor("end");
bool OnlyIfFoo(string? msg) => msg == "foo";
static bool OnlyIfFoo(string? msg) => msg == "foo";
var workflow = new WorkflowBuilder("start")
.AddEdge<string>(start, mid, OnlyIfFoo)
@@ -374,7 +374,7 @@ public class WorkflowVisualizerTests
var c = new MockExecutor("c");
var end = new ListStrTargetExecutor("end");
bool Condition(string? msg) => msg?.Contains("test") ?? false;
static bool Condition(string? msg) => msg?.Contains("test") ?? false;
var workflow = new WorkflowBuilder("start")
.AddEdge<string>(start, a, Condition) // Conditional edge