# 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.

- URL: https://docs.mentoragent.net/configure/run-a-turn-from-code
- Verified with: MentorAgent 1.5.0
- Last updated: 2026-11-27
- Packages: Novior.MentorAgent, Novior.MentorAgent.Server

Use this page to start a [turn](https://docs.mentoragent.net/reference/glossary#turn) of the agent from your application's code, with nobody at the [widget](https://docs.mentoragent.net/reference/glossary#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

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:

```csharp title="CaseDigestJob.cs"
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Components.Authorization;
using Novior.MentorAgent.Abstractions.Interfaces;   // IMentorOrchestrator
```

```csharp title="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()`:

```csharp title="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.

## 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 `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](https://docs.mentoragent.net/concepts/governance#how-mentoragent-finds-the-user).

## Confirmations

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`](https://docs.mentoragent.net/reference/options#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.

## What policies and observers see

Your [action policies](https://docs.mentoragent.net/reference/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`.

## Test the job without a model

The example runs with the fake model of [Test without a model](https://docs.mentoragent.net/configure/test-without-model). Call `RunAsync` yourself, on a host that is built and not started, so that the timer does not wait for the night.

---

- Previous: [Show that the assistant is off](https://docs.mentoragent.net/configure/turn-the-assistant-off.md)
- Next: [Production checklist](https://docs.mentoragent.net/configure/production.md)
