Run a turn from your own code
Start a turn of the agent from a BackgroundService or a job, with nobody at the widget: the scope, the user of the turn, roles, confirmations and errors.
On this page
Use this page to start a turn of the agent from your application's code, with nobody at the widget. For example, a BackgroundService asks for a summary of the open cases every night, or a job answers events. The page says what to write, who the user of the turn is, and what happens to roles, confirmations and errors when there is no request.
The job
Section titled “The job”Each turn runs in a dependency injection (DI) scope of its own. In that scope, the job gives the turn its user, listens for the answer, and sends the message:
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Components.Authorization;
using Novior.MentorAgent.Abstractions.Interfaces; // IMentorOrchestrator// Asks the agent for a digest every night, with nobody at the widget
public sealed class CaseDigestJob(
IServiceScopeFactory scopes, ILogger<CaseDigestJob> logger)
: BackgroundService
{
// The job's own identity: authenticated, with the role it needs
public static readonly ClaimsPrincipal ServiceUser = new(
new ClaimsIdentity(
[
new(ClaimTypes.NameIdentifier, "case-digest-job"),
new(ClaimTypes.Name, "case-digest-job"),
new(ClaimTypes.Role, "Agents"),
], authenticationType: "Service"));
protected override async Task ExecuteAsync(CancellationToken ct)
{
using var timer = new PeriodicTimer(TimeSpan.FromHours(24));
while (await timer.WaitForNextTickAsync(ct))
{
var (reply, error) = await RunAsync(
"Summarize the open cases for the morning team", ct);
logger.LogInformation("Digest: {Reply} {Error}", reply, error);
}
}
public async Task<(string Reply, string? Error)> RunAsync(
string message, CancellationToken ct)
{
// One scope for each turn: a conversation of its own
await using var scope = scopes.CreateAsyncScope();
var services = scope.ServiceProvider;
// The user of the turn, for roles, policies and observers
var auth = (IHostEnvironmentAuthenticationStateProvider)
services.GetRequiredService<AuthenticationStateProvider>();
auth.SetAuthenticationState(
Task.FromResult(new AuthenticationState(ServiceUser)));
var state = services.GetRequiredService<IMentorStateService>();
var reply = new StringBuilder();
string? error = null;
state.OnStreamingChunk += text => reply.Append(text);
state.OnError += text => error = text;
// Nobody can confirm here: refuse what asks for a confirmation
state.OnConfirmationRequired += request =>
state.Cancel(request.ActionId);
await services.GetRequiredService<IMentorOrchestrator>()
.SendMessageAsync(message, ct);
return (reply.ToString(), error);
}
}Register it after AddMentorAgent() and AddMentorAgentServer():
// After AddMentorAgent() and AddMentorAgentServer()
services.AddSingleton<CaseDigestJob>();
services.AddHostedService(sp => sp.GetRequiredService<CaseDigestJob>());- One scope, one session.
IMentorOrchestrator, the conversation and the session belong to the scope. A new scope is a new session. Several messages in one scope are turns of the same session. SendMessageAsyncdoes not throw when the model fails. It passes a message written for users toOnError, not the exception.- The events of the turn come from
IMentorStateService, in the same scope.OnStreamingChunkgives the answer in pieces, as in the widget.OnErrorgives an error, andOnConfirmationRequiredgives a confirmation request.
The user of the turn
Section titled “The user of the turn”A job has no request and no circuit, so the turn has no user until you give it one. SetAuthenticationState on the AuthenticationStateProvider of the scope gives it the job's identity, with its roles:
- The identity must be authenticated: create its
ClaimsIdentitywith an authentication type, as"Service"in the example. Roles are itsClaimTypes.Roleclaims. - The order does not matter. You can call
AddRazorComponents()before or afterAddMentorAgentServer(). The one that you call first registers theAuthenticationStateProvider, and either provider takes the identity that you set. - With your own
AuthenticationStateProvider, one that does not implementIHostEnvironmentAuthenticationStateProvider, the cast of the example throwsInvalidCastException. Give the job's user through your provider instead. - Without an identity, the turn is anonymous. An action with
RequiredRolesis not offered, and a call to it is refused. Nothing throws, also when Blazor's provider was registered first and cannot be read outside a circuit. In that case, a call to an action with roles also writes an error to the log. - With no provider at all, when the app calls neither
AddMentorAgentServer()norAddRazorComponents(), the example'sGetRequiredService<AuthenticationStateProvider>()throwsInvalidOperationException. A turn started without the job's identity still runs, as an anonymous turn: an action withRequiredRolesis not offered, a call to it is refused, and the log has a warning that names the action.
How MentorAgent finds the user on the other channels is in Governance.
Confirmations
Section titled “Confirmations”An action that asks for a confirmation waits for an answer, and in a job nobody gives one:
- Answer from the job.
OnConfirmationRequiredcomes with the request.Cancel(actionId)refuses it, as the example does, and the action does not run.ConfirmAsync(actionId)confirms it, and the action runs. Confirm only what the job may do on its own. - Or set a time limit. By default,
ConfirmationTimeoutsets no limit, so the turn waits until the token given toSendMessageAsyncis cancelled. With a limit, a confirmation that nobody answers is refused when the time is up, and the action does not run.
What policies and observers see
Section titled “What policies and observers see”Your action policies and observers see the turn as any other turn:
SurfaceisInProcess, as in a Blazor circuit;Useris the identity that the job set, ornullwithout one;SessionIdis the scope's, andTurnIdis new for each message.
Surface is InProcess in a Blazor circuit too, so a policy tells the job's turns from a person's by User, never by Surface.
Test the job without a model
Section titled “Test the job without a model”The example runs with the fake model of Test without a model. Call RunAsync yourself, on a host that is built and not started, so that the timer does not wait for the night.
See also
Section titled “See also”- Roles, confirmation and governance — Role checks and human-in-the-loop approval for AI agent tools in .NET, enforced in code on every channel and not in the prompt, and what stays in your code.
- Action policies and observers — The types that let your code decide on each action, record every decision of the gate, know who confirmed a call, and list the actions.
- Test without a model — Test your actions, roles and confirmation boxes in automated tests with a fake IChatClient, develop offline with a local model, and catch regressions.
