MentorAgent Docs
Menu

Questa pagina non è ancora tradotta in italiano: qui la trovi in inglese.

Guida praticaPacchetti: Novior.MentorAgent, Novior.MentorAgent.Server

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.

In questa pagina

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.

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:

CaseDigestJob.cs
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Components.Authorization;
using Novior.MentorAgent.Abstractions.Interfaces;   // IMentorOrchestrator
CaseDigestJob.cs
// 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():

Program.cs
// 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.
  • SendMessageAsync does not throw when the model fails. It passes a message written for users to OnError, not the exception.
  • The events of the turn come from IMentorStateService, in the same scope. OnStreamingChunk gives the answer in pieces, as in the widget. OnError gives an error, and OnConfirmationRequired gives a confirmation request.

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 ClaimsIdentity with an authentication type, as "Service" in the example. Roles are its ClaimTypes.Role claims.
  • The order does not matter. You can call AddRazorComponents() before or after AddMentorAgentServer(). The one that you call first registers the AuthenticationStateProvider, and either provider takes the identity that you set.
  • With your own AuthenticationStateProvider, one that does not implement IHostEnvironmentAuthenticationStateProvider, the cast of the example throws InvalidCastException. Give the job's user through your provider instead.
  • Without an identity, the turn is anonymous. An action with RequiredRoles is 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() nor AddRazorComponents(), the example's GetRequiredService<AuthenticationStateProvider>() throws InvalidOperationException. A turn started without the job's identity still runs, as an anonymous turn: an action with RequiredRoles is 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.

An action that asks for a confirmation waits for an answer, and in a job nobody gives one:

  • Answer from the job. OnConfirmationRequired comes 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, ConfirmationTimeout sets no limit, so the turn waits until the token given to SendMessageAsync is cancelled. With a limit, a confirmation that nobody answers is refused when the time is up, and the action does not run.

Your action policies and observers see the turn as any other turn:

  • Surface is InProcess, as in a Blazor circuit;
  • User is the identity that the job set, or null without one;
  • SessionId is the scope's, and TurnId is 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.

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.

  • Ruoli, conferma e governance — Ruoli e approvazione human-in-the-loop per i tool di un agente AI in .NET: controlli nel codice, non nel prompt, su ogni canale, e cosa resta a te.
  • 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.