Skip to content

Commit deecbcb

Browse files
baywetCopilotCopilot
authored
.NET: fix(dotnet): validate declarative control-flow inputs (#9357)
* fix(dotnet): validate declarative control-flow inputs Apply existing input validation to workflow decisions and restored loop inputs. Add regression coverage and clarify expression evaluation usage. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd63c138-6c7d-4cff-b97e-a21fd7206604 * fix(dotnet): validate tool settings before dispatch Retain automatic-send settings across matching responses and checkpoint restoration, and align checked-in loop validation. Co-authored-by: Copilot <[email protected]> Copilot-Session: bd63c138-6c7d-4cff-b97e-a21fd7206604 * fix(dotnet): retain automatic-send settings during reapproval Co-authored-by: Copilot <[email protected]> Copilot-Session: bd63c138-6c7d-4cff-b97e-a21fd7206604 * fix(dotnet): align generated foreach workflow fixtures Co-authored-by: Copilot <[email protected]> Copilot-Session: bd63c138-6c7d-4cff-b97e-a21fd7206604 * fix(dotnet): register function checkpoint settings Co-authored-by: Copilot <[email protected]> Copilot-Session: bd63c138-6c7d-4cff-b97e-a21fd7206604 * fix(dotnet): complete restored function approval denials Co-authored-by: Copilot <[email protected]> Copilot-Session: bd63c138-6c7d-4cff-b97e-a21fd7206604 * fix: Simplify auto-send snapshot retrieval Refactor result handling to simplify auto-send logic. Co-authored-by: Copilot Autofix powered by AI <[email protected]> --------- Co-authored-by: Copilot <[email protected]> Co-authored-by: baywet <[email protected]> Co-authored-by: Copilot Autofix powered by AI <[email protected]> Copilot-Session: bd63c138-6c7d-4cff-b97e-a21fd7206604
1 parent 0ec6e47 commit deecbcb

28 files changed

Lines changed: 1099 additions & 84 deletions

‎dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/DeclarativeWorkflowJsonOptions.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ private static JsonSerializerOptions CreateDefaultOptions()
6363
[JsonSerializable(typeof(ExternalInputResponse))]
6464
[JsonSerializable(typeof(UnassignedValue))]
6565
[JsonSerializable(typeof(List<string>))]
66+
[JsonSerializable(typeof(Dictionary<string, bool>))]
6667
// TypeInfoPropertyName disambiguates the two ApprovalSnapshot records that share a simple name.
6768
[JsonSerializable(typeof(Dictionary<string, InvokeFunctionToolExecutor.ApprovalSnapshot>),
6869
TypeInfoPropertyName = "DictionaryStringFunctionApprovalSnapshot")]

‎dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/Kit/IWorkflowContextExtensions.cs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,11 @@ public static async ValueTask<EvaluationResult<string>> FormatTemplateWithSensit
145145
/// <param name="expression">The expression to evaluate.</param>
146146
/// <param name="cancellationToken">A token that propagates notification when operation should be canceled.</param>
147147
/// <returns>The evaluated expression value and its sensitivity metadata.</returns>
148+
/// <remarks>
149+
/// Callers must preserve the sensitivity metadata when storing the result and reject sensitive
150+
/// values before using them for output or control-flow decisions. Use <see cref="EvaluateValueAsync{TValue}"/>
151+
/// when sensitivity metadata does not need to be propagated.
152+
/// </remarks>
148153
public static async ValueTask<EvaluationResult<TValue?>> EvaluateValueWithSensitivityAsync<TValue>(this IWorkflowContext context, string expression, CancellationToken cancellationToken = default)
149154
{
150155
WorkflowFormulaState state = await context.GetStateAsync(cancellationToken).ConfigureAwait(false);

‎dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/ClearAllVariablesExecutor.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ internal sealed class ClearAllVariablesExecutor(ClearAllVariables model, Workflo
1717
{
1818
EvaluationResult<VariablesToClearWrapper> variablesResult = this.Evaluator.GetValue(this.Model.Variables);
1919

20-
string? scope = variablesResult.Value.Value switch
20+
string? scope = this.GetNonSensitiveValue(variablesResult, "variable scope").Value switch
2121
{
2222
VariablesToClear.AllGlobalVariables => VariableScopeNames.Global,
2323
VariablesToClear.ConversationScopedVariables => WorkflowFormulaState.DefaultScopeName,

‎dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/ConditionGroupExecutor.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ public bool IsElse(object? message)
6060
}
6161

6262
EvaluationResult<bool> expressionResult = this.Evaluator.GetValue(conditionItem.Condition);
63-
if (expressionResult.Value)
63+
if (this.GetNonSensitiveValue(expressionResult, "condition"))
6464
{
6565
return Steps.Item(this.Model, conditionItem);
6666
}

‎dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/ForeachExecutor.cs‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,14 @@ public ForeachExecutor(Foreach model, WorkflowFormulaState state)
4949
this._index = 0;
5050

5151
EvaluationResult<DataValue> expressionResult = this.Evaluator.GetValue(this.Model.Items);
52-
if (expressionResult.Value is TableDataValue tableValue)
52+
DataValue items = this.GetNonSensitiveValue(expressionResult, "loop items");
53+
if (items is TableDataValue tableValue)
5354
{
5455
this._values = [.. tableValue.Values.Select(ToLoopValue)];
5556
}
5657
else
5758
{
58-
this._values = [expressionResult.Value.ToFormula()];
59+
this._values = [items.ToFormula()];
5960
}
6061
this._sensitivity = expressionResult.Sensitivity;
6162

@@ -156,9 +157,12 @@ protected override async ValueTask OnCheckpointRestoredAsync(IWorkflowContext co
156157
return;
157158
}
158159

159-
this._values = [.. savedValues.Select(value => value.ToFormula())];
160+
SensitivityLevel sensitivity =
161+
await context.ReadStateAsync<SensitivityLevel>(SensitivityStateKey, cancellationToken: cancellationToken).ConfigureAwait(false);
162+
this._values = [.. this.GetNonSensitiveValue(new EvaluationResult<PortableValue[]>(savedValues, sensitivity), "loop items")
163+
.Select(value => value.ToFormula())];
160164
this._index = await context.ReadStateAsync<int>(IndexStateKey, cancellationToken: cancellationToken).ConfigureAwait(false);
161165
this.HasValue = await context.ReadStateAsync<bool>(HasValueStateKey, cancellationToken: cancellationToken).ConfigureAwait(false);
162-
this._sensitivity = await context.ReadStateAsync<SensitivityLevel>(SensitivityStateKey, cancellationToken: cancellationToken).ConfigureAwait(false);
166+
this._sensitivity = sensitivity;
163167
}
164168
}

‎dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/HttpRequestExecutor.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,7 @@ private string GetUrl()
270270
return null;
271271
}
272272

273-
long value = this.Evaluator.GetValue(this.Model.RequestTimeoutInMilliseconds).Value;
273+
long value = this.GetRequestValue(this.Evaluator.GetValue(this.Model.RequestTimeoutInMilliseconds), "timeout");
274274
return value > 0 ? TimeSpan.FromMilliseconds(value) : null;
275275
}
276276

‎dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/InvokeAzureAgentExecutor.cs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,8 @@ private async ValueTask InvokeAgentAsync(IWorkflowContext context, IEnumerable<C
127127
bool requestInput;
128128
try
129129
{
130-
requestInput = this.Evaluator.GetValue(this.Model.Input.ExternalLoop.When).Value;
130+
requestInput = this.GetNonSensitiveValue(
131+
this.Evaluator.GetValue(this.Model.Input.ExternalLoop.When), "external loop condition");
131132
}
132133
catch (Exception exception) when (
133134
responseObjectWasBlanked &&
@@ -290,7 +291,7 @@ private bool GetAutoSendValue()
290291
// autoSend or have no output block at all).
291292
if (this.AgentOutput is { AutoSendIsDefaultValue: false } output)
292293
{
293-
return this.Evaluator.GetValue(output.AutoSend).Value;
294+
return this.GetNonSensitiveValue(this.Evaluator.GetValue(output.AutoSend), "auto send");
294295
}
295296

296297
return true;

‎dotnet/src/Microsoft.Agents.AI.Workflows.Declarative/ObjectModel/InvokeFunctionToolExecutor.cs‎

Lines changed: 57 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ internal sealed class InvokeFunctionToolExecutor(
3232
private const string ApprovalSnapshotStateKey = nameof(_approvalSnapshots);
3333
private const string HasApprovalRequiredInvocationStateKey = nameof(_hasApprovalRequiredInvocation);
3434
private const string PendingCallIdsStateKey = nameof(_pendingNonApprovalCallIds);
35+
private const string AutoSendSnapshotsStateKey = nameof(_autoSendSnapshots);
3536
private const string LegacyApprovalSnapshotStateKey = "_approvalSnapshot";
3637

3738
/// <summary>
@@ -40,6 +41,7 @@ internal sealed class InvokeFunctionToolExecutor(
4041
/// response is captured.
4142
/// </summary>
4243
private readonly ConcurrentDictionary<string, ApprovalSnapshot> _approvalSnapshots = new(StringComparer.Ordinal);
44+
private readonly ConcurrentDictionary<string, bool> _autoSendSnapshots = new(StringComparer.Ordinal);
4345

4446
private bool _hasApprovalRequiredInvocation;
4547

@@ -78,10 +80,12 @@ public static class Steps
7880
{
7981
string functionName = this.GetFunctionName();
8082
bool requireApproval = this.GetRequireApproval(functionName);
83+
bool autoSend = this.GetAutoSendValue();
8184
Dictionary<string, object?>? arguments = this.GetArguments();
8285

8386
// Per-invocation request id stamped on the outbound content.
8487
string requestId = Guid.NewGuid().ToString("N");
88+
this._autoSendSnapshots[requestId] = autoSend;
8589

8690
// Create the function call content to send to the caller
8791
FunctionCallContent functionCall = new(
@@ -128,7 +132,6 @@ public async ValueTask CaptureResponseAsync(
128132
ExternalInputResponse response,
129133
CancellationToken cancellationToken)
130134
{
131-
bool autoSend = this.GetAutoSendValue();
132135
string? conversationId = this.GetConversationId();
133136
string? responseRequestId = response.RequestId;
134137

@@ -155,6 +158,8 @@ public async ValueTask CaptureResponseAsync(
155158
&& IsCorrelatedResponse(r.CallId, responseRequestId));
156159
}
157160

161+
bool autoSend = matchingResult is not null && this.GetResponseAutoSendValue(response);
162+
158163
// When the caller approved an approval-required function call but didn't execute it
159164
// locally (the hosted Foundry scenario, where mcp_approval_response is converted to a
160165
// ToolApprovalResponseContent only), invoke the registered AIFunction here so that the
@@ -183,16 +188,21 @@ public async ValueTask CaptureResponseAsync(
183188
else if (!approval.Approved)
184189
{
185190
this._approvalSnapshots.TryRemove(approval.RequestId, out _);
191+
this._autoSendSnapshots.TryRemove(approval.RequestId, out _);
186192
await this.AssignErrorAsync(context, "Function invocation was not approved by user.").ConfigureAwait(false);
187193
}
188-
else if (this._approvalSnapshots.TryRemove(approval.RequestId, out ApprovalSnapshot? snapshot))
189-
{
190-
matchingResult = await this.InvokeRegisteredFunctionAsync(approval.RequestId, snapshot, cancellationToken).ConfigureAwait(false);
191-
approvedFunctionResult = matchingResult;
192-
}
193194
else
194195
{
195-
await this.AssignErrorAsync(context, "No pending approval matched the response.").ConfigureAwait(false);
196+
autoSend = this.GetResponseAutoSendValue(response);
197+
if (this._approvalSnapshots.TryRemove(approval.RequestId, out ApprovalSnapshot? snapshot))
198+
{
199+
matchingResult = await this.InvokeRegisteredFunctionAsync(approval.RequestId, snapshot, cancellationToken).ConfigureAwait(false);
200+
approvedFunctionResult = matchingResult;
201+
}
202+
else
203+
{
204+
await this.AssignErrorAsync(context, "No pending approval matched the response.").ConfigureAwait(false);
205+
}
196206
}
197207
}
198208
else if (!this._approvalSnapshots.IsEmpty)
@@ -246,6 +256,7 @@ await this.AssignAsync(
246256
// Drop the per-invocation entry now that the response side effects have been processed.
247257
this._pendingNonApprovalCallIds.TryRemove(matchingResult.CallId, out _);
248258
this._approvalSnapshots.TryRemove(matchingResult.CallId, out _);
259+
this._autoSendSnapshots.TryRemove(matchingResult.CallId, out _);
249260
}
250261

251262
// Completes the action after processing the function result.
@@ -266,6 +277,7 @@ private IEnumerable<ChatMessage> GetSideEffectMessages(ExternalInputResponse res
266277
public override ValueTask ResetAsync()
267278
{
268279
this._approvalSnapshots.Clear();
280+
this._autoSendSnapshots.Clear();
269281
this._hasApprovalRequiredInvocation = false;
270282
this._pendingNonApprovalCallIds.Clear();
271283
return default;
@@ -285,6 +297,8 @@ protected override async ValueTask OnCheckpointingAsync(IWorkflowContext context
285297

286298
List<string> pendingCopy = [.. this._pendingNonApprovalCallIds.Keys];
287299
await context.QueueStateUpdateAsync(PendingCallIdsStateKey, pendingCopy, null, cancellationToken).ConfigureAwait(false);
300+
Dictionary<string, bool> autoSendCopy = this._autoSendSnapshots.ToDictionary(kvp => kvp.Key, kvp => kvp.Value, StringComparer.Ordinal);
301+
await context.QueueStateUpdateAsync(AutoSendSnapshotsStateKey, autoSendCopy, null, cancellationToken).ConfigureAwait(false);
288302

289303
await base.OnCheckpointingAsync(context, cancellationToken).ConfigureAwait(false);
290304
}
@@ -297,6 +311,16 @@ protected override async ValueTask OnCheckpointingAsync(IWorkflowContext context
297311
protected override async ValueTask OnCheckpointRestoredAsync(IWorkflowContext context, CancellationToken cancellationToken = default)
298312
{
299313
await base.OnCheckpointRestoredAsync(context, cancellationToken).ConfigureAwait(false);
314+
this._autoSendSnapshots.Clear();
315+
Dictionary<string, bool>? autoSendSnapshots = await context.ReadStateAsync<Dictionary<string, bool>>(
316+
AutoSendSnapshotsStateKey, null, cancellationToken).ConfigureAwait(false);
317+
if (autoSendSnapshots is not null)
318+
{
319+
foreach (KeyValuePair<string, bool> entry in autoSendSnapshots)
320+
{
321+
this._autoSendSnapshots[entry.Key] = entry.Value;
322+
}
323+
}
300324
this._approvalSnapshots.Clear();
301325
Dictionary<string, ApprovalSnapshot>? snapshots = await context.ReadStateAsync<Dictionary<string, ApprovalSnapshot>>(
302326
ApprovalSnapshotStateKey, null, cancellationToken).ConfigureAwait(false);
@@ -525,14 +549,38 @@ private string GetFunctionName() =>
525549
private bool GetRequireApproval(string functionName)
526550
{
527551
bool requireApproval = this.Model.RequireApproval is not null
528-
&& this.Evaluator.GetValue(this.Model.RequireApproval).Value;
552+
&& this.GetNonSensitiveValue(this.Evaluator.GetValue(this.Model.RequireApproval), "require approval");
529553

530554
return requireApproval
531555
|| agentProvider.Functions?.FirstOrDefault(
532556
f => string.Equals(f.Name, functionName, StringComparison.Ordinal))
533557
?.GetService<ApprovalRequiredAIFunction>() is not null;
534558
}
535559

560+
private bool GetResponseAutoSendValue(ExternalInputResponse response)
561+
{
562+
AIContent[] contents = [.. response.Messages.SelectMany(message => message.Contents)];
563+
FunctionResultContent? result = contents.OfType<FunctionResultContent>()
564+
.FirstOrDefault(r => this.IsCorrelatedPendingNonApprovalResult(r, response.RequestId));
565+
if (result is not null)
566+
{
567+
return this._autoSendSnapshots.TryGetValue(result.CallId, out bool resultAutoSend)
568+
? resultAutoSend
569+
: this.GetAutoSendValue();
570+
}
571+
572+
ToolApprovalResponseContent? approval = contents.OfType<ToolApprovalResponseContent>()
573+
.FirstOrDefault(r => this._approvalSnapshots.ContainsKey(r.RequestId) &&
574+
IsCorrelatedResponse(r.RequestId, response.RequestId));
575+
if (approval is not null && this._autoSendSnapshots.TryGetValue(approval.RequestId, out bool approvalAutoSend))
576+
{
577+
return approvalAutoSend;
578+
}
579+
580+
// Older checkpoints and legacy responses have no captured setting.
581+
return this.GetAutoSendValue();
582+
}
583+
536584
private bool GetAutoSendValue()
537585
{
538586
// InvokeToolOutput.AutoSend is never null — it returns a literal-false default
@@ -541,7 +589,7 @@ private bool GetAutoSendValue()
541589
// default as autoSend = true (the historical behavior).
542590
if (this.Model.Output is { AutoSendIsDefaultValue: false } output)
543591
{
544-
return this.Evaluator.GetValue(output.AutoSend).Value;
592+
return this.GetNonSensitiveValue(this.Evaluator.GetValue(output.AutoSend), "auto send");
545593
}
546594

547595
return true;

0 commit comments

Comments
 (0)