Novior.MentorAgent.Abstractions
1.3.0
Prefix Reserved
See the version list below for details.
dotnet add package Novior.MentorAgent.Abstractions --version 1.3.0
NuGet\Install-Package Novior.MentorAgent.Abstractions -Version 1.3.0
<PackageReference Include="Novior.MentorAgent.Abstractions" Version="1.3.0" />
<PackageVersion Include="Novior.MentorAgent.Abstractions" Version="1.3.0" />
<PackageReference Include="Novior.MentorAgent.Abstractions" />
paket add Novior.MentorAgent.Abstractions --version 1.3.0
#r "nuget: Novior.MentorAgent.Abstractions, 1.3.0"
#:package Novior.MentorAgent.Abstractions@1.3.0
#addin nuget:?package=Novior.MentorAgent.Abstractions&version=1.3.0
#tool nuget:?package=Novior.MentorAgent.Abstractions&version=1.3.0
Novior.MentorAgent.Abstractions
New package IDs. From 1.0.0 the packages, their namespaces and their assemblies are
Novior.MentorAgent.*; up to 1.0.0-rc.15 they wereMentorAgent.*. See Migrating from the MentorAgent.* packages in the Novior.MentorAgent README.
You do not need to install this package directly. It is included automatically as a transitive dependency of
Novior.MentorAgentandNovior.MentorAgent.Blazor.
This package is the shared foundation of the MentorAgent family. It contains all the contracts, models, and UI components shared between the server-side and client-side packages — with no AI or ASP.NET Core server dependencies, making it fully compatible with Blazor WebAssembly.
Table of Contents
- Package Family
- What's included
- Component parameter reference
- Static assets — CSS and JS
- When you actually touch this package
- Why a separate package?
- Requirements
- Related Packages
- License
Package Family
| Package | Install when |
|---|---|
| Novior.MentorAgent | Blazor Server app |
| Novior.MentorAgent.Server | Web API / headless backend, or Blazor Auto server-side project |
| Novior.MentorAgent.Blazor | Blazor WASM / Blazor Auto client project |
| Novior.MentorAgent.Abstractions ← you are here | Never directly — it arrives with any of the above |
| Novior.MentorAgent.Declarative | Optional — define Level-2 specialist agents in YAML instead of C# |
What's included
Interfaces
| Interface | Description |
|---|---|
IMentorOrchestrator |
AI orchestrator contract — implemented by MentorOrchestrator (server) and WasmMentorOrchestrator (WASM) |
IMentorStateService |
Thread-safe event bus between the AI layer and the UI layer |
IMentorPageContext |
Page context and UI actions registry |
IMentorAgent |
Marker interface for Level 2 specialized agents |
IMentorTeam |
Marker interface for Level 3 collaborative teams |
IMentorStructured |
Typed generation — GenerateAsync<T>(input, instructions) returns a deserialized T, with the JSON schema derived from your type |
IMentorMetrics |
Read-side of the token/cost counters — GetSnapshot() feeds MentorDashboard |
IMentorTour |
Supplies the onboarding tour steps. The default implementation generates them from the app's own pages and tools; register your own to script the tour by hand |
IMentorMetricsStore |
Optional persistence/aggregation for those metrics. Implement it to survive restarts or to read an external aggregate (Prometheus, Azure Monitor) instead of the in-RAM snapshot |
Models
| Type | Description |
|---|---|
ConfirmationRequest |
HITL confirmation request shown in ConfirmationBanner |
MentorRagResult |
A single RAG search result with content, URL, title, and score, plus optional Metadata the model is shown with it |
MentorWidgetOptions |
UI-only options for ChatWidget (theme, position, language, etc.) |
UIActionRegistration |
Handler registration for a page-level UI action |
PageContextSnapshot |
Serializable page context sent from WASM client to server hub |
UIActionInfo |
UI action descriptor in a PageContextSnapshot |
AgentDisplayInfo |
Remote agent display info for the A2A detail badge |
MentorAttachment |
One image on a user turn — DataBase64 (upload/paste) or Url (remote), mapped to the Agent Framework's DataContent / UriContent |
MentorUserMessage |
A user turn as text + attachments; an image-only turn (empty text) is valid |
MentorTourStep |
One step of the onboarding tour — title, body, the screen it describes and a ready-made question the user can send with one tap |
MentorCard |
A generative-UI card a tool returns instead of prose — kind, title, subtitle, fields, actions, image, accent |
MentorCardField / MentorCardAction |
One label/value row, and one button (SendMessage / Navigate / UIAction) |
MentorMetricsSnapshot |
Point-in-time totals, per-model breakdown, hourly series, top actions and cost — the payload of GET /mentor/admin/metrics |
MentorModelUsage |
One model's slice of that snapshot (tokens, calls, latency, cost) |
ModelPrice |
record ModelPrice(decimal InputPer1M, decimal OutputPer1M) — you supply prices; the library ships no price table, because they change and a stale one lies |
Enums
| Enum | Values |
|---|---|
MentorLanguage |
English, Italian, French, German, Spanish, Portuguese, Dutch, Polish, Japanese, Chinese |
MentorTheme |
Default, Dark, Minimal, Custom, Auto |
ChatPosition |
BottomRight, BottomLeft, TopRight, TopLeft, SideRight, SideLeft |
MentorshipLevel |
Minimal, Standard, Proactive |
MentorHostedTools |
[Flags] — None, WebSearch, CodeInterpreter, FileSearch, ImageGeneration, HostedMcp. The set the model provider may run on its own infrastructure; also what the server publishes on connect so a client badge never drifts from the server |
MentorModelKind |
Cheap, Strong, Embedding, Other — how a model's usage is attributed in the metrics snapshot. Other is any model id that is none of the three configured ones, e.g. a ClassifierChatClient on its own deployment |
MentorCardActionKind |
SendMessage, Navigate, UIAction — what a card button does |
MentorCardAccent |
Default, Success, Warning, Danger, Info — the card's colour accent |
UI Components (Razor)
All MentorAgent UI components live here so they work identically in both Blazor Server and Blazor WASM:
| Component | Description |
|---|---|
ChatWidget |
Main floating chat widget — injects CSS/JS automatically |
MessageBubble |
A chat message: Markdown rendering (links to http/https addresses included), citation chips and any images the message carries. XSS-safe by construction — every piece of model text is HTML-encoded before a tag is emitted, so the model supplies data, never markup |
ChatInput |
Text input with voice recognition and the image composer (upload, paste, drag & drop, remote URL) |
MentorDashboard |
Admin token & cost dashboard — per-model breakdown, temporal SVG charts, cost table. Presentational: hand it a MentorMetricsSnapshot, from DI in Blazor Server or from GET /mentor/admin/metrics in WASM. Never rendered by ChatWidget — keep it off end-user pages |
ConfirmationBanner |
HITL approval dialog |
OnboardingTour |
Guided first-run tour. Presentational — it is handed the steps and raises callbacks, which is what lets the same component serve Blazor Server (steps from DI) and WASM (steps over HTTP) |
MentorCardView |
Built-in renderer for a MentorCard. XSS-safe by construction — every value goes through Razor interpolation and no MarkupString is used, because a card carries data and never markup |
WelcomePanel |
Empty-state welcome screen with suggestion chips |
TypingIndicator |
Animated typing dots while AI processes |
RagSourcePanel |
Citation chips below AI responses |
McpStatusBadge / McpDetailBar |
MCP server connection status |
A2AStatusBadge / A2ADetailBar |
A2A remote agent status |
Core
| Type | Description |
|---|---|
MentorLocalizer |
In-memory i18n for 10 languages — no .resx files, no external dependencies. Registered by AddMentorAgent() / AddMentorAgentBlazor(); inject it as MentorLocalizer and call L.Get("key") if you build UI that must match the widget's language. L.Language is the language it uses: the application's, read on every use |
MentorLanguageExtensions |
MentorLanguage.Italian.ToIsoCode() → "it" (ISO 639-1; an unknown value gives "en"), and ToFullName() → "Italian". ToIsoCode() is what the components hand the JS layer, which expands it to the BCP-47 tag the browser Speech APIs expect ("it" → "it-IT"). A custom voice control that talks to SpeechRecognition / speechSynthesis directly has to do that expansion itself to speak the same language as the widget |
TourProgress |
(internal) Where the onboarding tour resumes. Not API — documented only because its edge cases are user-visible |
Component parameter reference
Every component is presentational in the sense that matters: it takes its data through parameters and raises callbacks out, never calling the AI itself. That is what lets the identical component serve Blazor Server (data from DI) and WebAssembly (data over HTTP), and it is what lets you compose the parts on your own pages instead of taking the whole widget.
ChatWidget is the exception — it is the assembled widget and resolves IMentorOrchestrator,
IMentorStateService and navigation for itself.
They still need DI. Every component except
MentorDashboardandMentorCardViewinjectsIOptions<MentorWidgetOptions>,MentorLocalizeror both, soAddMentorAgent()/AddMentorAgentBlazor()must have run in that host. RenderingMessageBubbleon a page of an app that never registered MentorAgent throws at build-render time, not at first interaction.
Namespaces and injections. The components live in
Novior.MentorAgent.Abstractions.Components, the models and enums inNovior.MentorAgent.Abstractions.Models, the interfaces inNovior.MentorAgent.Abstractions.InterfacesandMentorLocalizerinNovior.MentorAgent.Abstractions.Core.ChatMessage/ChatRolecome fromMicrosoft.Extensions.AI. The examples below assume these in your_Imports.razor, plus the services they call injected on the page:@using Novior.MentorAgent.Abstractions.Components @using Novior.MentorAgent.Abstractions.Models @using Novior.MentorAgent.Abstractions.Interfaces @using Novior.MentorAgent.Abstractions.Core @using Microsoft.Extensions.AI @inject IMentorOrchestrator Orchestrator @inject IMentorStateService State @inject NavigationManager Nav @inject IMentorTour Tour
ChatWidget
| Parameter | Type | Description |
|---|---|---|
CardTemplate |
RenderFragment<MentorCard>? |
Optional custom renderer for generative-UI cards. Not supplied → MentorCardView is used. Match on card.Kind and fall back to the built-in renderer for kinds you do not handle |
Language |
MentorLanguage? |
This widget's language: its texts, voice and onboarding tour, and the language of every turn it sends. Not supplied → the application's Language, through the MentorLocalizer from DI. See A language per page in the MentorAgent README |
@* A MentorCardView inside the template needs no OnAction: ChatWidget cascades its own
dispatcher around the cards, so these buttons send / navigate / run the UI action. *@
<ChatWidget>
<CardTemplate Context="card">
@if (card.Kind == "order") { <OrderCard Card="card" /> }
else { <MentorCardView Card="card" /> }
</CardTemplate>
</ChatWidget>
The template replaces the widget's card rendering for every card, but not its button handling:
a <MentorCardView Card="card" /> rendered inside the template without OnAction uses the widget's
dispatcher, so its SendMessage, Navigate and UIAction buttons work as they do on an untemplated
card. An OnAction you set explicitly still wins. Buttons your template draws itself (inside
OrderCard above) do not get the dispatcher: handle them yourself, or render MentorCardView for
the cards whose buttons should just work.
Everything else about the widget comes from MentorWidgetOptions in DI, not from parameters — see
the option tables in the Novior.MentorAgent or
Novior.MentorAgent.Blazor README, depending on which
host you use.
MentorDashboard
| Parameter | Type | Default | Description |
|---|---|---|---|
Snapshot |
MentorMetricsSnapshot? |
null |
An override, not the only source. Pass it in WASM/headless. In Blazor Server leave it null and the component resolves the data itself |
OnRefresh |
EventCallback |
— | Fired after the Refresh button re-resolves. Handle it in WASM to re-fetch; in Blazor Server you can ignore it |
Currency |
string |
"$" |
Symbol prefixed to every cost figure. The library never converts — supply ModelPricing already in the currency you want shown |
Language |
MentorLanguage? |
null |
null → the MentorLocalizer from DI, which follows the Language option on both hosts (AddMentorAgent() and AddMentorAgentBlazor() both register it). Pass it only to override that language, or in an app that registered neither; there the dashboard falls back to English |
The Refresh button is part of the populated view; OnRefresh only decides whether anything of yours
runs when it is pressed. With no data at all the component renders its empty state rather than
throwing, and that state has no Refresh button. In WASM, a first fetch that failed cannot be
retried from the dashboard: retry it yourself (a button of your own, or a timer) and pass the new
Snapshot.
Its resolution order when Snapshot is null is: an external IMentorMetricsStore.QueryAsync()
first (so a Prometheus/Azure Monitor aggregate wins), then the live in-RAM IMentorMetrics snapshot.
@* Blazor Server — no parameters needed *@
<MentorDashboard />
@* WASM — you own the fetch *@
<MentorDashboard Snapshot="_snapshot"
OnRefresh="Reload"
Currency="€"
Language="MentorLanguage.Italian" />
MentorCardView
| Parameter | Type | Description |
|---|---|---|
Card |
MentorCard |
Required. The card to render |
OnAction |
EventCallback<MentorCardAction> |
Raised when a button is pressed. Left unset inside ChatWidget (including in a CardTemplate), the widget's own dispatcher sends / navigates / runs the UI action; an explicit OnAction wins. Wire it yourself when you render cards outside the widget |
<MentorCardView Card="_card" OnAction="RunCardAction" />
@code {
private readonly MentorCard _card = new("order")
{
Title = "Ordine #1002",
Subtitle = "Laura Bianchi",
Accent = MentorCardAccent.Info,
Fields = [new("Stato", "Shipped"), new("Totale", "1.249,98 €")],
Actions =
[
new("Apri", MentorCardActionKind.Navigate, "/orders/1002"),
new("Dettagli", MentorCardActionKind.SendMessage, "Dammi i dettagli dell'ordine 1002"),
],
};
// @inject IMentorOrchestrator Orchestrator, NavigationManager Nav, IMentorPageContext PageContext
private async Task RunCardAction(MentorCardAction action)
{
switch (action.Kind)
{
case MentorCardActionKind.SendMessage:
await Orchestrator.SendMessageAsync(action.Value);
break;
case MentorCardActionKind.Navigate:
Nav.NavigateTo(action.Value);
break;
// Resolved at click time, as ChatWidget does: the page that registered the action
// may have changed since the card was rendered.
case MentorCardActionKind.UIAction
when PageContext.UIActions.TryGetValue(action.Value, out var reg):
if (reg.HandlerAsync is not null) await reg.HandlerAsync(null);
else reg.Handler(null);
break;
}
}
}
The buttons are written by the tool that produced the card, never by the model's prose — which is why a card can safely carry actions. Inside
ChatWidgetthe buttons are handled for you, in aCardTemplatetoo as long as the card is rendered byMentorCardView; wireOnActionyourself only when you render cards outside the widget.
MessageBubble
| Parameter | Type | Description |
|---|---|---|
Message |
ChatMessage |
Required. The MEAI message. Role decides the side and styling |
IsStreaming |
bool |
Renders the trailing caret while text is still arriving |
SentAt |
DateTime? |
Timestamp under the bubble; omitted when null |
Sources |
IReadOnlyList<MentorRagResult>? |
RAG citation chips below the message, rendered through RagSourcePanel, so only on an assistant message and only when MentorWidgetOptions.ShowRagSources is on |
@foreach (var m in _messages)
{
<MessageBubble Message="m.Message" SentAt="m.At" Sources="m.Sources" />
}
@* the one still arriving — the caret is the only difference *@
@if (_streaming is not null)
{
<MessageBubble Message="_streaming" IsStreaming="true" />
}
Message is MEAI's own ChatMessage, so the role decides the side and the styling. Model text is
HTML-encoded before any Markdown tag is emitted, so a reply containing <script> renders as text.
Only an absolute http or https address becomes a link: javascript:, data: and relative ones stay
text.
ChatInput
| Parameter | Type | Description |
|---|---|---|
OnSend |
EventCallback<MentorUserMessage> |
Required. Raised with text and attachments — an image-only turn (empty text) is valid |
Disabled |
bool |
Blocks input while a turn is in flight |
Placeholder |
string? |
Overrides the localised default. MentorWidgetOptions.InputPlaceholder is not read here: ChatWidget passes it in, so pass it yourself on your own surface |
The rest comes from MentorWidgetOptions. The microphone appears only with EnableVoiceInput (and a
browser that supports speech recognition). The image composer appears only with EnableImageInput,
limited by MaxImageBytes, MaxImagesPerMessage and AllowedImageTypes. MaxMessageLength sets
the textarea's maxlength.
<ChatInput OnSend="Send" Disabled="_busy" Placeholder="Chiedi qualcosa sugli ordini…" />
@code {
private bool _busy;
private async Task Send(MentorUserMessage message)
{
_busy = true;
try
{
// Text AND attachments. An image-only turn — empty Text, one attachment — is valid.
await Orchestrator.SendMessageAsync(message.Text, message.Attachments);
}
finally { _busy = false; }
}
}
OnboardingTour
| Parameter | Type | Description |
|---|---|---|
Steps |
IReadOnlyList<MentorTourStep> |
Required. From IMentorTour in Blazor Server, or GET /mentor/tour in WASM |
StartIndex |
int |
Where to open. Clamped into range, so a stale stored index cannot throw |
OnIndexChanged |
EventCallback<int> |
Fired on every step change — this is what the host persists to resume later |
OnNavigate |
EventCallback<string> |
The step's URL, when the user chooses to go there |
OnAsk |
EventCallback<string> |
The step's ready-made question, when the user taps it |
OnClose |
EventCallback |
Skip or finish |
OnNavigate and OnAsk are engagement, not dismissal: the host is expected to suspend the tour
and resume at the next step, not mark it seen. ChatWidget already does this.
@if (_tourOpen)
{
<OnboardingTour Steps="_steps"
StartIndex="_resumeAt"
OnIndexChanged="Persist"
OnNavigate="GoThere"
OnAsk="AskThat"
OnClose="Finish" />
}
@code {
private IReadOnlyList<MentorTourStep> _steps = [];
private bool _tourOpen;
private int _resumeAt;
protected override async Task OnInitializedAsync()
{
// IMentorTour from DI on both hosts: generated in-process on Blazor Server,
// fetched from GET /mentor/tour by Novior.MentorAgent.Blazor on WebAssembly.
_steps = await Tour.GetStepsAsync();
_resumeAt = await LoadSavedIndex(); // your storage; clamped for you
// At or past the end: the user already acted on the last step, so there is nothing to resume.
_tourOpen = _steps.Count > 0 && _resumeAt < _steps.Count;
}
// Track where the user IS, not where the tour opened: the component moves on its own and
// OnIndexChanged is the only way you learn it.
private Task Persist(int index) { _resumeAt = index; return SaveIndex(index); }
// Engagement, not dismissal: suspend and resume at the NEXT step rather than marking it seen.
private async Task GoThere(string url) { _tourOpen = false; await SaveIndex(_resumeAt + 1); Nav.NavigateTo(url); }
private async Task AskThat(string q) { _tourOpen = false; await SaveIndex(_resumeAt + 1); await Orchestrator.SendMessageAsync(q); }
private Task Finish() { _tourOpen = false; return MarkSeen(); }
}
ConfirmationBanner
| Parameter | Type | Description |
|---|---|---|
Request |
ConfirmationRequest |
Required. What is being approved |
OnConfirm |
EventCallback |
Required. Approve |
OnCancel |
EventCallback |
Required. Reject |
@if (_pending is not null)
{
<ConfirmationBanner Request="_pending" OnConfirm="Approve" OnCancel="Reject" />
}
@code {
private ConfirmationRequest? _pending;
protected override void OnInitialized() =>
State.OnConfirmationRequired += r => { _pending = r; InvokeAsync(StateHasChanged); };
private async Task Approve() { var r = _pending!; _pending = null; await State.ConfirmAsync(r.ActionId); }
private Task Reject() { var r = _pending!; _pending = null; State.Cancel(r.ActionId); return Task.CompletedTask; }
}
On WebAssembly the snippet above already answers over HTTP:
State.ConfirmAsync/State.Cancelpost toPOST /mentor/approve?actionId=…&approved=true|falserather than calling a hub method, because SignalR dispatches one invocation at a time per connection, so a hub call would queue behind the very turn it is meant to release. The request goes to the hub's origin whenMentorAgentBlazorOptions.HubUrlis an absolutehttp(s)URL (relative to the hostHttpClient'sBaseAddresswhen it is relative, i.e. same-origin hosting) and carriesAuthorization: Bearer <token>fromMentorAgentBlazorOptions.AccessTokenProviderwhen one is set, the same credential the hub uses, so a signed-in user's answer is not refused with 401. Stop takes the same route (POST /mentor/cancel). The host must still register anHttpClient, as the WASM template does. Call the endpoints yourself only from a client that has noIMentorStateService(JavaScript, React), and send the same bearer token there.
WelcomePanel
| Parameter | Type | Default | Description |
|---|---|---|---|
BotName |
string |
"Mentor AI" |
Shown in the empty state heading and as the avatar's alt text |
WelcomeMessage |
string? |
null |
null or blank → the localised default. Rendered as HTML, not encoded: pass only text you wrote, never user or model input |
EnableSuggestions |
bool |
true |
Whether to render the three built-in, localised suggestion chips. They also need OnChipClick; with no handler they are not rendered |
OnChipClick |
EventCallback<string> |
— | The chip's text, to be sent as a user turn |
@if (_messages.Count == 0)
{
<WelcomePanel BotName="Assistente ShopFlow"
WelcomeMessage="Ciao! Posso aiutarti con ordini e prodotti."
EnableSuggestions="true"
OnChipClick="Send" />
}
The chip's text arrives as an ordinary user turn — there is nothing special about it, which is why
OnChipClick and the input's OnSend can share one handler.
RagSourcePanel
| Parameter | Type | Description |
|---|---|---|
Sources |
IReadOnlyList<MentorRagResult>? |
Citation chips: the first three, then a "+N more" chip that expands the rest. Renders nothing when null, empty, or when MentorWidgetOptions.ShowRagSources is off, which is the default: set options.ShowRagSources = true on either host |
<RagSourcePanel Sources="_sources" />
@code {
// null or empty renders nothing at all, so there is no need to guard the element.
private IReadOnlyList<MentorRagResult>? _sources;
protected override void OnInitialized() =>
State.OnRagSourcesReady += s => { _sources = s; InvokeAsync(StateHasChanged); };
}
Status badges
| Component | Parameters |
|---|---|
McpStatusBadge |
ServerStatus (IReadOnlyDictionary<string, bool?>? — name → connected/failed/unknown), OnToggle |
McpDetailBar |
Visible (bool), ServerStatus, OnClose |
A2AStatusBadge |
OnToggle — the agent list comes from MentorWidgetOptions.RemoteAgentDisplays |
A2ADetailBar |
Visible (bool), OnClose |
bool? in ServerStatus is three-valued on purpose: true connected, false failed,
null not yet probed. Rendering null as "failed" would show a red badge during startup.
The badges are also gated by MentorWidgetOptions, so on a page of your own they render nothing until
the matching options are set. McpStatusBadge needs ShowMcpStatus and HasMcpServers, plus at
least one entry in ServerStatus. McpDetailBar needs HasMcpServers and a non-empty ServerStatus.
A2AStatusBadge needs ShowA2AStatus and HasRemoteAgents. A2ADetailBar needs a non-empty
RemoteAgentDisplays. On Blazor Server, AddMentorAgent() fills HasMcpServers, HasRemoteAgents,
RemoteAgentDisplays and McpServerNames from your MCP and A2A configuration. On WebAssembly you set
them on MentorAgentBlazorOptions, because the client cannot see the server's configuration.
<McpStatusBadge ServerStatus="_mcp" OnToggle="() => _mcpOpen = !_mcpOpen" />
<McpDetailBar Visible="_mcpOpen" ServerStatus="_mcp" OnClose="() => _mcpOpen = false" />
<A2AStatusBadge OnToggle="() => _a2aOpen = !_a2aOpen" />
<A2ADetailBar Visible="_a2aOpen" OnClose="() => _a2aOpen = false" />
@code {
private bool _mcpOpen, _a2aOpen;
// name → connected. Seed every configured server as null ("connecting") rather than false:
// nothing has been probed yet. An EMPTY dictionary hides the badge until the first status
// event, which with lazily-connected MCP servers is the first message.
// (@inject IOptions<MentorWidgetOptions> Options)
private readonly Dictionary<string, bool?> _mcp = new(StringComparer.OrdinalIgnoreCase);
protected override void OnInitialized()
{
foreach (var name in Options.Value.McpServerNames) _mcp[name] = null;
State.OnMcpServerStatusChanged += (name, ok) =>
{
_mcp[name] = ok;
InvokeAsync(StateHasChanged);
};
}
}
The A2A badge takes no data parameter on purpose — its agent list comes from
MentorWidgetOptions.RemoteAgentDisplays, because a remote agent is configuration rather than
runtime state.
TypingIndicator
No parameters — animated dots. Show it while a turn is in flight and nothing has streamed yet.
@if (_busy && _streaming is null)
{
<TypingIndicator />
}
Show it only while a turn is in flight and nothing has streamed yet — once the first token lands,
MessageBubble with IsStreaming="true" carries the signal instead.
Composing your own chat surface
The reason these components take parameters and raise callbacks instead of calling the AI is so you can build a surface that is not the floating widget — an inline panel, a side rail, a page of your own. Everything below is host-agnostic: in Blazor Server the state service comes from DI, on WebAssembly the same interface is backed by the hub.
Without ChatWidget on the page nothing injects the stylesheet and the script, so add both tags
yourself: see Static assets — CSS and JS.
@inject IMentorOrchestrator Orchestrator
@inject IMentorStateService State
@implements IDisposable
<div class="my-chat">
@if (_messages.Count == 0)
{
<WelcomePanel BotName="Assistente" OnChipClick="Send" />
}
@foreach (var m in _messages)
{
<MessageBubble Message="m" />
}
@if (_streaming is not null) { <MessageBubble Message="_streaming" IsStreaming="true" /> }
@if (_busy && _streaming is null) { <TypingIndicator /> }
<RagSourcePanel Sources="_sources" />
@if (_pending is not null)
{
<ConfirmationBanner Request="_pending" OnConfirm="Approve" OnCancel="Reject" />
}
<ChatInput OnSend="OnSend" Disabled="_busy" />
</div>
@code {
private readonly List<ChatMessage> _messages = [];
private ChatMessage? _streaming;
private IReadOnlyList<MentorRagResult>? _sources;
private ConfirmationRequest? _pending;
private bool _busy;
private readonly System.Text.StringBuilder _buffer = new();
protected override void OnInitialized()
{
State.OnStreamingChunk += Chunk;
State.OnStreamingCompleted += Completed;
State.OnBusyChanged += Busy;
State.OnRagSourcesReady += Rag;
State.OnConfirmationRequired += Confirm;
}
private void Chunk(string c)
{
_buffer.Append(c);
_streaming = new ChatMessage(ChatRole.Assistant, _buffer.ToString());
InvokeAsync(StateHasChanged);
}
private void Completed()
{
if (_buffer.Length > 0) _messages.Add(new ChatMessage(ChatRole.Assistant, _buffer.ToString()));
_buffer.Clear();
_streaming = null;
InvokeAsync(StateHasChanged);
}
private void Busy(bool b) { _busy = b; InvokeAsync(StateHasChanged); }
private void Rag(IReadOnlyList<MentorRagResult> s) { _sources = s; InvokeAsync(StateHasChanged); }
private void Confirm(ConfirmationRequest r) { _pending = r; InvokeAsync(StateHasChanged); }
private async Task Send(string text) => await OnSend(new MentorUserMessage(text));
private async Task OnSend(MentorUserMessage m)
{
_messages.Add(new ChatMessage(ChatRole.User, m.Text));
_sources = null;
await Orchestrator.SendMessageAsync(m.Text, m.Attachments);
}
private async Task Approve() { var r = _pending!; _pending = null; await State.ConfirmAsync(r.ActionId); }
private Task Reject() { var r = _pending!; _pending = null; State.Cancel(r.ActionId); return Task.CompletedTask; }
public void Dispose()
{
State.OnStreamingChunk -= Chunk;
State.OnStreamingCompleted -= Completed;
State.OnBusyChanged -= Busy;
State.OnRagSourcesReady -= Rag;
State.OnConfirmationRequired -= Confirm;
}
}
Unsubscribe. These are plain C# events on a scoped service that outlives your component, so a component that subscribes and never detaches is kept alive by the service and re-rendered after disposal.
ChatWidgetdoes this for you; a hand-built surface has to do it itself.
Subscribe to OnError too. A message the host refuses before the model runs produces no streamed
text and no OnStreamingCompleted: only OnError with the localised reason, then OnBusyChanged(false).
That covers a message that is too long or rate-limited, one blocked by the safety check (or, with
SafetyCheckFailure = MentorSafetyCheckFailure.Block, one whose check could not run), and one refused
as out of scope under RefuseOutOfScope. Provider failures arrive the same way. Without a handler, the
surface above shows the user's bubble and then nothing:
@if (_error is not null) { <div class="my-chat__error">@_error</div> }
@code {
private string? _error;
// OnInitialized: State.OnError += Error; Dispose: State.OnError -= Error;
// OnSend: _error = null; before sending the next message
private void Error(string message) { _error = message; InvokeAsync(StateHasChanged); }
}
Static assets — CSS and JS
The stylesheet and the JavaScript layer ship in this package, not in Novior.MentorAgent:
_content/Novior.MentorAgent.Abstractions/css/MentorAgent.css
_content/Novior.MentorAgent.Abstractions/js/MentorAgent.js
_content/Novior.MentorAgent.Abstractions/IconMA.png ← default avatar
ChatWidget injects the first two itself through <HeadContent>, so a Blazor Server or Blazor Web
App host needs no markup, and it versions them for you: the ?v= it writes is the package version
and the commit the package was built from (?v=<version>+<commit>), so every release changes it.
A standalone WASM host references them manually in index.html instead — and neither file is
fingerprinted, and UseStaticFiles serves them without a Cache-Control, so the ?v= query string
is the cache buster: set it to the version of the package you install and change it on every
upgrade. A stale MentorAgent.js fails silently and looks like
missing features rather than a caching problem.
That injection happens only where ChatWidget is rendered, and it relies on the <HeadOutlet />
that the Blazor Web App template already includes. A page that composes the parts without
ChatWidget (see Composing your own chat surface) gets neither
file: the components render unstyled, and ChatInput's microphone and paste / drag & drop stay off
without an error. Sending a message still works: the call that resets the textarea after a send is
guarded, so a missing script neither throws nor ends a Blazor Server circuit. Reference both files yourself in that case, with the same paths
and the package version as the ?v= (ChatWidget adds the commit; a link you write needs only the
version), in App.razor (Blazor Server / Web App) or index.html:
<link href="_content/Novior.MentorAgent.Abstractions/css/MentorAgent.css?v=1.3.0" rel="stylesheet" />
<script src="_content/Novior.MentorAgent.Abstractions/js/MentorAgent.js?v=1.3.0"></script>
The script can safely load a second time on a page where ChatWidget also renders: the later tag
wins and the voice state carries over.
The JS layer covers text-to-speech (sentence-queued, barge-in, hands-free), speech recognition, the
image composer (upload, paste, drag & drop, client-side downscaling) and localStorage helpers. It
is called through IJSRuntime by the components; there is no supported way to call it directly.
For the complete CSS variable reference — palette, widget size, fonts, the dashboard and chart
colours — see Widget customization → CSS variables
in the Novior.MentorAgent README. The variables are defined here but documented there, next to the
options that set them.
When you actually touch this package
Most of the time you never reference these types by name — Novior.MentorAgent and Novior.MentorAgent.Blazor
wire them for you. Three cases where you do:
1. Rendering the admin dashboard yourself. MentorDashboard is presentational, so the same
component works in-process and over HTTP. In Blazor Server, inject the metrics; in WASM, fetch the
snapshot from the admin endpoint:
@* Blazor Server — in-process. It resolves the metrics itself; no parameters needed. *@
<MentorDashboard />
@* WASM — over HTTP. There is no IMentorMetrics in the browser, so pass the snapshot. Language is optional: it follows AddMentorAgentBlazor's Language unless you override it. *@
@inject HttpClient Http
<MentorDashboard Snapshot="_snapshot" Language="MentorLanguage.Italian" />
@code {
MentorMetricsSnapshot? _snapshot;
protected override async Task OnInitializedAsync() =>
_snapshot = await Http.GetFromJsonAsync<MentorMetricsSnapshot>("/mentor/admin/metrics");
}
Put it behind authorization. The snapshot is operator data — cost, volumes, top actions — and must never appear on an end-user page.
The endpoint is gated on its own as well:
GET /mentor/admin/metricsrequires the role inMentorOptions.DashboardRole("Admin"by default;""leaves it open, for development only). TheHttpClientyou fetch with must therefore send the signed-in admin's credentials (cookie or bearer token). Without them the request is refused (401/403, or a redirect to the login page under cookie authentication) andGetFromJsonAsyncthrows instead of the dashboard rendering its empty state. In a standalone WASM app, itsBaseAddressmust also be the server's origin, not the client's.
2. Persisting or aggregating metrics. Implement IMentorMetricsStore and register it before
AddMentorAgent(), in a headless host too, where AddMentorAgentServer() comes after it. Registered
any later, the store still answers QueryAsync, but LoadForSeedAsync and SaveAsync are never called,
because the persistence service is added only when the store is already there. Without one the snapshot
lives in RAM and resets on restart; with one you get durability, or you can serve an external aggregate
instead:
Every method has a default no-op implementation, because the two scenarios use different halves of the contract — implement only the one you need:
// (A) Local durability — restore totals at startup, persist periodically and on shutdown.
// QueryAsync stays default (null) so the dashboard keeps serving the live in-RAM snapshot.
public sealed class FileMetricsStore : IMentorMetricsStore
{
public Task<MentorMetricsSnapshot?> LoadForSeedAsync(CancellationToken ct = default) => /* read */;
public Task SaveAsync(MentorMetricsSnapshot s, CancellationToken ct = default) => /* write */;
}
// (B) External source — serve the aggregate your OpenTelemetry export already pushed to
// Prometheus / Azure Monitor (multi-instance, historical). Nothing to seed, nothing to save.
public sealed class PrometheusMetricsStore : IMentorMetricsStore
{
public Task<MentorMetricsSnapshot?> QueryAsync(CancellationToken ct = default) => /* query */;
}
builder.Services.AddSingleton<IMentorMetricsStore, FileMetricsStore>(); // BEFORE AddMentorAgent()
3. Building your own composer or transcript. MentorUserMessage + MentorAttachment are the shape
of a user turn, and IMentorOrchestrator.SendMessageAsync(text, attachments) is what consumes it — so
a custom input control can replace ChatInput without touching the orchestration layer.
Working implementations ship in the samples repository, Novior.MentorAgent.Samples: the dashboard
in the AdminDashboard page of MentorAgentSample, MentorAgentNuget, MentorAgentBlazor and
MentorAgentNugetWebAssembly; a FileMetricsStore in six hosts (MAUI included), and
PrometheusMetricsStore and AzureMonitorMetricsStore in MentorAgentServer and
MentorAgentNugetApiServer; and a composer of its own in the React client, mentoragentreact,
which sends the same message and attachments over the SignalR hub.
Why a separate package?
Novior.MentorAgent depends on Microsoft.Agents.AI, ModelContextProtocol and other packages that are not compatible with Blazor WebAssembly. Novior.MentorAgent.Blazor (WASM) cannot reference Novior.MentorAgent directly.
Novior.MentorAgent.Abstractions contains only WebAssembly-safe dependencies:
Microsoft.AspNetCore.Components.WebMicrosoft.AspNetCore.Components.AuthorizationMicrosoft.Extensions.AI
Both Novior.MentorAgent and Novior.MentorAgent.Blazor reference Novior.MentorAgent.Abstractions — sharing interfaces, models, and UI components without cross-contaminating dependencies.
The practical rule: anything that must run in the browser goes here. If you are adding a type
and it needs Microsoft.Agents.AI, an HttpContext, or the file system, it does not belong in this
package — the WASM build will not fail at compile time, it will fail at runtime in the browser.
Requirements
- .NET 10.0 or later
Microsoft.AspNetCore.Components.Web10.0.3Microsoft.AspNetCore.Components.Authorization10.0.3Microsoft.Extensions.AI10.11.0
No AI provider, no server packages, no JavaScript dependencies beyond the browser's own Speech and File APIs.
Related Packages
| Package | Purpose |
|---|---|
| Novior.MentorAgent | Blazor Server — full AI assistant |
| Novior.MentorAgent.Server | Any ASP.NET Core app — headless AI backend |
| Novior.MentorAgent.Blazor | Blazor WASM — SignalR client |
| Novior.MentorAgent.Declarative | Optional — Level-2 specialists defined in YAML |
License
Apache License 2.0 — the full text is in the LICENSE file inside this package, with the copyright notice in NOTICE. Versions up to and including 1.0.0-rc.14 were released under the MIT License, which still applies to them.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.AspNetCore.Components.Authorization (>= 10.0.3)
- Microsoft.AspNetCore.Components.Web (>= 10.0.3)
- Microsoft.Extensions.AI (>= 10.11.0)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on Novior.MentorAgent.Abstractions:
| Package | Downloads |
|---|---|
|
Novior.MentorAgent
Add AI agents to your .NET application, under your rules. C# methods become tools for an agent built on Microsoft Agent Framework; on each one you declare which roles may use it and whether the user must confirm first. Ready-made chat widget for Blazor and MAUI, or any front end over SignalR and SSE; MCP and A2A with Novior.MentorAgent.Server. Cost control, multi-agent teams, RAG and memory. |
|
|
Novior.MentorAgent.Blazor
Blazor WebAssembly client for MentorAgent. Install in your Blazor WASM / Blazor Auto client project. Connects to a Novior.MentorAgent.Server hub via SignalR and provides the same ChatWidget experience as Blazor Server. |
GitHub repositories
This package is not used by any popular GitHub repositories.
1.3.0 - 2026-11-05
### Added
- ACTION-RULES.md lists the rules by which a method becomes an action, how actions are named, and how roles and
confirmations add up. Each rule has a name that does not change and at least one test that fails when the rule does;
a rule that comes in, changes or is retired is named in the release notes of its version. The rules of 1.3.0:
`scan.assemblies-once`, `scan.concrete-classes`, `scan.public-instance-declared`, `scan.marker`,
`scan.mentor-action-wins`, `scan.override-keeps-action`, `kind.one-per-class`, `kind.page-is-separate`,
`kind.agent-owns-methods`, `kind.skill-methods-level1`, `kind.team-needs-members`, `kind.member-tools-leave-level1`,
`kind.member-tools-same-rules`, `name.snake-case`, `name.team-tool`, `name.shared-warned`,
`name.called-method-decides`, `confirm.declared-decides`, `confirm.default-for-writes`,
`confirm.description-only-not-defaulted`, `confirm.predicate-adds`, `confirm.master-switch`,
`confirm.beats-read-only`, `confirm.unconfirmed-writes-warned`, `roles.any-of`, `roles.signed-in`,
`roles.checked-before-confirmation`, `roles.offered-when-allowed`, `surface.coordinator-only`,
`surface.mcp-withholds-gated` and `surface.card-ungated-only`.
- An action can ship off, and the application can turn its actions on and off from outside its code.
`[MentorAction(Enabled = false)]` keeps an action in the catalogue (`MentorActionInfo.EnabledByDefault` is false)
and nowhere else: no agent is offered it, no model reads about it, the MCP server does not list it, the A2A card
does not show it, and a call to it does not run. An `IMentorActionGovernor`, registered with
`AddMentorActionGovernor<T>()`, answers for each action whether it is on, and can turn on one the code ships off:
registering one gives whoever implements it the power to widen what the code allows. It is asked once as a session
builds its tools, on every `tools/list` of the MCP server and before every call, with the session's id; a session
keeps the tools it was built with, and a call to an action turned off meanwhile is refused. There can be one: a
second registration throws. A governor that throws, or does not answer within `ActionPolicyTimeout`, stops the
action. The A2A card follows the code only, so an action turned on from outside is not on it. New reason codes:
`disabled` (`Denied`) and `governor-failed` (`PolicyFailed`). New rules: `enabled.off-by-default`,
`enabled.external-decides` and `surface.governor-session`; `surface.mcp-withholds-gated` and
`surface.card-ungated-only` now also leave out an action that is off.
- The governor can also give an action its roles: `IMentorActionGovernor.GetRequiredRolesAsync` answers in place of
`[MentorAction(RequiredRoles = ...)]`, with `null` for the code's roles and an empty list for none. The answer
decides whom the action is offered to, the check at every call, before a confirmation and again after it, and which
MCP callers see and call it: an action the MCP server withheld only for its roles is published once the governor
requires none. `MentorActionDecision.RolesFromOutside` says when the roles came from the governor. New rule:
`roles.external-replace`; `roles.checked-before-confirmation` now checks the governor's roles when it gives them.
- The governor can also decide whether the user confirms an action: `IMentorActionGovernor.GetConfirmationAsync`
answers `MentorConfirmationChoice.Code` for the code's confirmation, `Required` to ask even if the code does not,
and `None` not to ask even if the code does — declared, by default for writes, or by `RequiresApproval`. A
confirmation added counts from the call, one taken away from the next session, and in Native mode no auto-approval
rule lets a required one through. A policy's `Confirm` still asks, a hosted MCP server's approval still comes from
its provider, and with `RequireConfirmation` off nobody is asked. An action whose confirmation is taken away still
counts as one that changes data. The MCP server publishes an action that asks for confirmation once the governor
takes it away, and withholds one it requires. `MentorActionDecision.ConfirmationFromOutside` says when the governor
changed whether a call is confirmed. New rule: `confirm.external-decides`; `confirm.predicate-adds` and
`surface.mcp-withholds-gated` now say what the governor can take away.
- The governor can also rewrite the description the model reads: `IMentorActionGovernor.GetDescriptionAsync` answers
in place of the code's, with `null` or a blank text for the code's. It is asked as a session builds its tools and
on every `tools/list` of the MCP server, and the answer is what the coordinator, the specialists and the team
members read, what tool filtering ranks, and what `tools/list` shows; the action's name and argument schema never
change, and the code's `ProactiveHint` still follows the description. What the user sees keeps the code's
description: the confirmation banner, the bar of the running action and `MentorActionDecision.DisplayName`. On a
call to the MCP server the policies are asked with the code's description. New rule: `describe.external-replace`.
- An `IMentorAgentSource` says what it loaded and what it left out, and when it is asked is a promise. A source is
asked whenever a coordinator is built: at least once per session — once per Blazor circuit, MAUI app scope or hub
connection, and at every request on `/mentor/chat` and every task over A2A — and `MentorAgentSourceContext.SessionId`
names the session, as `MentorActionRequest.SessionId` does. MentorAgent now calls `IMentorAgentSource.LoadAsync`,
which returns a `MentorAgentSourceResult`: the agents, and a `MentorAgentRejection` (`Name`, `ReasonCode`, `Detail`,
`Tool`) for each definition left out or tool taken away. Its default body returns the agents of `GetAgentsAsync`, so
an existing source works unchanged. An `IMentorAgentSourceObserver`, registered with
`AddMentorAgentSourceObserver<T>()`, receives a `MentorAgentSourceReport` for each source every time a coordinator
is built, also when the source loaded nothing; a source that throws is reported as `source-failed`, with the
exception's type and never its message. The reason codes, in `MentorAgentRejectionReasons`: `invalid-definition`,
`not-an-agent`, `foreign-tools`, `invalid-configuration`, `source-failed`, `tool-not-found` and
`hosted-tool-removed`. **Novior.MentorAgent.Declarative** reports every definition it does not load and every tool
it takes away. New rules: `declarative.functions-match` and `declarative.no-hosted-tools`.
- `MentorRuntimeOptions.Changeable` lists the options that can be changed while the application runs, and from when
a change applies (`MentorOptionReadAt`). From the next turn of every session: `Language`, `RateLimitPerUser`,
`RateLimitWindowSecs`, `ConfirmationMessage`, `ConfirmationTimeout`, `ActionPolicyTimeout`, `EnableActionFeedback`,
`EnableGenerativeCards`, `EnableSafetyCheck` and `CheckAnnouncedActions`. From the sessions that begin after the
change: `MentorshipLevel`,
`ProactiveNextSteps`, `EnableRichResponses`, `RefuseOutOfScope`, `ToolFilterMaxTools` and `MaxSessionMessages`. To
change one, assign it on the `IOptions<MentorOptions>` value, replacing a collection rather than changing it in
place. Every other option is read before the application starts: set it there. Each option listed has a test that
changes it on a running application, and every option declares when it is read, so a new one cannot ship without
the decision.
- After a turn in which the coordinator called no tool, MentorAgent asks a model whether its reply announces an action
("I'm registering the note…") or reports one as done when nothing ran (`MentorOptions.CheckAnnouncedActions`, on by
default). If it does, the coordinator gets one more request in the same turn, with the same tools, told to call the
tool now or to say that it was not done. The question names the tools the model was sent, and the answer names the
one that does the action: the second request then says that this tool is there to call now. The instruction is that
request's last message, read after the reply it is about, and never stored. A call to an action of the application
the agent was not given (one that is off for the session) runs nothing, and the turn is checked as one in which
nothing ran. The call is never required and passes the gate as any other, the reply
already shown is not held back, and the second reply is not checked again. The question goes to
`ClassifierChatClient`, or to `ChatClient` without one: a few hundred tokens after every reply that called no tool,
so a small deployment there is worth configuring. Its verdict is logged at Information for every reply it checks,
with the time and the tokens it took. On Path A with the history kept by MentorAgent; not with
`UseServiceManagedHistory` nor with a pre-built `Agent` (BUG-220).
- A call the model makes to an action of the application that the coordinator was not given in the turn — one that
is off, or another agent's — reaches no gate and runs nothing. `IMentorActionObserver` now receives its one
decision, `Denied` with the new reason code `not-offered`, and the call's span says the same, in Blocking and in
Native mode, with `CheckAnnouncedActions` on or off. A call the coordinator was given keeps the decisions of its
gate, and only those.
- One instance of the application can tell which tenant a request belongs to. `IMentorTenantResolver`, registered with
`services.AddMentorTenantResolver<T>()` (one per application), names it from the caller, the surface and the
request's services; `IMentorTenant.Id` reads it, in an action, a policy or the governor, and
`IMentorTenant.GetIdAsync()` resolves it first in a scope that had no turn yet. It is asked when a turn
starts — in a Blazor circuit, on the hub, on `/mentor/chat`, in an A2A task — and for every `tools/list` and
`tools/call` of the MCP server, where each call reads its own. A request is never served without a tenant: a resolver
that throws, or answers `null`, empty or white space, refuses it before the model or the action, and a turn whose
tenant is not the one its conversation began with is refused too. Without a resolver there is one tenant, as before,
and `IMentorTenant.Id` is `null`.
- With an `IMentorTenantResolver`, two tenants on one instance share no memory, no rate limit and no conversation.
`MentorMemoryService.GetUserIdAsync()` — the key of the memory and of `RateLimitPerUser` — is the tenant's own
(`tenant:<id>/<the user's key>`), the shared anonymous bucket included, and so is the MCP server's per-caller
allowance. A session snapshot names its tenant and is restored for that tenant only: one of another tenant, one that
names none where a resolver is registered, and one that names a tenant where none is, are refused before the
conversation changes (a 400 on `/mentor/session`). The history MentorAgent keeps is a coordinator's own, as before; a
single `ChatHistoryProvider` instance with a resolver registered is reported at start-up, since it serves every tenant
— `ChatHistoryProviderFactory` runs in the conversation's scope, where `IMentorTenant` reads the tenant. Without a
resolver every key and every snapshot is as before.
- With an `IMentorTenantResolver`, every metric names its tenant: the `mentoragent.tenant` tag is on the four counters
(`mentoragent.turns`, `mentoragent.tool_calls`, `mentoragent.errors`, `mentoragent.guardrail_blocks`) and on the
`mentor.turn` span, the MCP server's calls included, so the whole instance is read per tenant from OpenTelemetry. The
token & cost dashboard and `GET /mentor/admin/metrics` show the figures of the reader's tenant only: tokens, cost,
turns, errors, guardrail blocks and top actions. A reader whose tenant the resolver does not name sees none (a 403
on the endpoint). `IMentorMetrics.GetSnapshot(string? tenant)` and `IMentorMetricsStore.QueryAsync(string? tenant,
CancellationToken)` are new, with defaults that keep existing implementations working. A custom `IMentorMetrics`
shows a tenant nothing rather than the instance's figures (a 204 on the endpoint). A store is asked for a tenant only
when it implements the new overload. A tenant's figures are kept in RAM since the process started; the store saves
and seeds the instance's. Without a resolver the series, the dashboard and the endpoint are as before.
- With an `IMentorTenantResolver`, retrieval and the logs know the tenant. `MentorRagRequest.TenantId` gives a RAG
source the turn's tenant; MentorAgent filters nothing, so a source that holds several tenants' documents returns
that tenant's. A source that implements only the `(query, maxResults)` overload never sees it, and a Warning says
so at its first search with a tenant. Every log line of a turn, the application's own code in the turn included,
and of a call to the MCP server is written in a log scope with one pair, `mentoragent.tenant`, the key of the
metrics and the span; a provider that includes scopes shows it. Without a resolver nothing changes.
- `MentorOptions.RagNoResultsNotice` (off by default) tells the model when the knowledge-base search of a turn kept no
document — none returned, or every one below `RagMinScore`: a question the documents would cover is answered "not
found in the documents" rather than from memory, and a message that needs no document, such as a greeting or an
action, is answered as usual. The text is MentorAgent's, in the language of the turn, in that request's
instructions only. It is not given after a search that failed, nor without a source.
- A knowledge-base search that fails can be monitored. With `EnableObservability` it is counted on
`mentoragent.rag_failures`, tagged with the source (`mentoragent.rag.source`, its type's full name) and the
exception's type (`mentoragent.error.type`), never its message, and with `mentoragent.tenant` when a resolver is
registered; a Stop during the search is not counted. Each search has a `mentor.rag.search` span, with the source,
and the status Error when it failed. The Warning names the source: "The search of … failed — RAG context skipped.".
- `IMentorRagSource.OnConversationChangedAsync` tells a source that the session's conversation changed, so one that
keeps state for it clears it: `MentorConversationChange.Reason` is `Reset` (New conversation), `Restored` (a saved
conversation took its place) or `Replaced` (a restored conversation the service no longer knew was replaced,
BUG-110), with the session's id and its tenant. The default does nothing, so an existing source works unchanged. It
is called with `UseRag` on, on the instance the session searches with, bounded by `SafetyCheckTimeout`; a source
that throws or does not answer in time is logged as a warning, and the conversation changes anyway.
- `MentorVectorStoreRagSource<TRecord>`, a knowledge-base source over any collection of
`Microsoft.Extensions.VectorData` (pgvector, Qdrant, Azure AI Search, an in-memory one), registered with
`services.AddMentorVectorStoreRag(sp => collection, new MentorVectorStoreRagOptions<TRecord> { Content = … })`.
The options say what of a record is the document, its title, its link and its metadata, and which records a request
may see (`Filter`, given the `MentorRagRequest` with its tenant and user). Scores are read as similarities whatever
the collection's distance function: with `CosineDistance`, the Postgres default, the source uses 1 − distance, so
`RagMinScore` keeps the nearest documents. The function comes from `DistanceFunction` or from the record's
`[VectorStoreVector]` attribute; when neither names one, or it is a Euclidean, Manhattan or Hamming distance,
registering the source fails. The message is embedded once per turn with `MentorOptions.EmbeddingGenerator` and
shared with routing, tool filtering and memory, or with a generator of the source's own; without either, the
collection embeds the text itself. `DefaultMinScore` is 0.5. With a tenant resolver and no `Filter`, the first
search with a tenant is logged as a warning. `Novior.MentorAgent` now references
`Microsoft.Extensions.VectorData.Abstractions` 10.10.0, which Agent Framework already brought.
- A provider that ignores `tool_choice: "required"` is reported. `RequireLookupForRecordQuestions` and
`RequireActionForChangeRequests` require the first call of the turn with `ChatToolMode.RequireAny`; a provider that
answers such a request without any call — Ollama ignores `tool_choice` — makes them do nothing, and the first time
it does a warning says so, once per provider client: "The provider answered a request that required a tool call
(tool_choice: required) without calling one: …". A call to a tool the request did not offer is still a call, and a
streamed reply is looked at as it goes by, nothing held back. The README has a recipe for llama-server and vLLM.
- `CoordinatorSampling` (`MentorSamplingOptions`): the coordinator's sampling — `Temperature`, `TopP`, `TopK`,
`MaxOutputTokens`, `FrequencyPenalty`, `PresencePenalty`, `Seed` — on every request of its turns, the forced first
call and the follow-ups of the tool loop included. The option unset, and each value left null, is the provider's
own; in configuration, `Mentor:CoordinatorSampling:Temperature` and so on. The classifiers call the provider directly
and keep their own settings: those that ask for temperature 0 still do, the others keep the provider's default, as
before. A negative temperature, a top-p outside (0, 1], or a top-k or output limit below 1 stops the application at
startup. Stop sequences are not offered: one that also occurs in a tool call's arguments would cut the call short.
- `WarmUpChatModel`: with `WarmUpAtStartup`, the warm-up also sends the coordinator's model one minimal request, so
the first turn does not pay for opening the connection, the provider's empty prompt cache or a local model still
loading. Every start costs one request per client — `ChatClient`, and `StrongChatClient` when it is set — with the
coordinator's instructions, tools and sampling, no call allowed (`ChatToolMode.None`), one short user message and at
most 16 output tokens. It goes straight to the provider client: no history, no memory, no turn on the dashboard;
the warm-up's log line gives its time and tokens. A request that fails is a warning, and the application carries
on; without `WarmUpAtStartup` the option has no effect, and a startup warning says so.
- `MentorEvaluator.RunConversationsAsync`: whole conversations (`EvalConversation`, `EvalTurn`) through the mentor
itself — the orchestrator, streaming, with its tools, filters, roles, RAG, memory and the history from one turn to
the next — each in a session of its own. A turn can require tools (`ExpectTools`: "at turn 2 it must call X"),
forbid others (`ForbidTools`), and set a token budget, a limit on the time to the first token and an expectation
for the judge. Its result adds `ToolsCalled`, read from the tool gate, `TimeToFirstToken`, `TurnDuration`,
`Conversation` and `Turn`; its tokens are those of its own session, exact while other sessions talk. **Every
confirmation is answered no by default: an evaluation does not write data on its own.**
`MentorEvalOptions.ApproveConfirmations` answers yes, and `PrepareSession` sets the conversation's user or page
before its first turn. `RunAsync` is unchanged; `SystemInstructions`, `Checks` and `Evaluators` stay its own.
- `EvalTurn.ExpectRefusal`: a conversation turn can expect the mentor to refuse — `EvalRefusal.OutOfScope`
(`RefuseOutOfScope`), `EvalRefusal.Guardrail` (the safety check, the host's `InputGuardrail`, or the model refusing
to answer) or `EvalRefusal.Any`. That refusal, shown to the user as an error, then passes the turn and the
conversation goes on; a turn that was answered, refused the other way or failed, fails, and its notes say which. A
safety check that could not run, a message too long, the rate limit and a missing tenant are not refusals: they stay
errors. Without the expectation a refusal fails the turn as before. `MentorEvalResult.Refusal` reports the refusal a
turn showed, expected or not.
- A `dotnet new` template in the repository, `templates/mentoragent-blazor`: a Blazor Server helpdesk with a
MentorAgent assistant and three actions — `list_open_tickets`, `assign_ticket` with a confirmation, `close_ticket`
with a confirmation and the `Agent` role — the model from the configuration with its key in the user secrets, and a
test sign-in with two users, one without the role. Its test project runs the assistant with a scripted model through
`RunConversationsAsync`: a support agent who confirms closes a ticket, without a yes the ticket stays open, and
without the role the action is not offered. It is installed from a clone of the repository, not from NuGet:
`dotnet new install templates/mentoragent-blazor`, then `dotnet new mentoragent-blazor -n Helpdesk`.
### Changed
- An `IMentorRagSource` that answers with no list (`null`) fails at once, with a message that says a source finding
nothing returns an empty list, instead of a `NullReferenceException` later on. The turn goes on without documents,
as before.
- **Novior.MentorAgent.Declarative:** a `kind: function` entry that names no action of the session — unknown to the
application, or off for the session — is taken away from the agent, with a warning, and the agent loads without it.
The Agent Framework used to give the agent a function of that name with nothing behind it: the model could call it,
nothing ran, and the agent stopped without a word in the log. An action that is off is therefore described to no
model through a definition that names it either.
- Every package is now checked at pack time against the public API of 1.2.0, so 1.3.0 cannot break code built
against 1.2.0 by accident. An intended break is listed in this file as Breaking.
- The family moves onto the Microsoft Agent Framework 1.27.0 line (`Microsoft.Agents.AI` and
`Microsoft.Agents.AI.Workflows` 1.27.0). **Novior.MentorAgent.Declarative:** `Microsoft.Agents.AI.Declarative` moves
to 1.27.0-rc1, on the same line. The two breaking changes of Agent Framework 1.27 are in parts MentorAgent does not
use: `AddFoundryResponses` for hosted Foundry applications, and the redirect callbacks of `DefaultHttpRequestHandler`.
- The packages' description and tags say what MentorAgent is: AI agents in a .NET application under your rules —
roles, confirmations, cost control. The tags of `Novior.MentorAgent`, `.Server` and `.Blazor` now include
`ai-governance`, `governance`, `authorization`, `roles`, `approval` and `human-in-the-loop`; the `mentor` tag, which
found only namesakes, is gone from all five packages.
### Fixed
- When a restored conversation the service no longer knew was replaced by a new one (BUG-110), the knowledge-base
search kept the recent messages of the conversation that was gone: the first search of the new one was given the
message of the turn that had failed. They are now cleared, as on a reset or a restore.
- The turn's vector of the message (`IMentorQueryEmbedding`) was kept on its text alone (BUG-229): a knowledge-base
source that embeds the message with a model of its own was handed the vector of `MentorOptions.EmbeddingGenerator`,
or routing, tool filtering and memory were handed the source's, whichever asked first in the turn. Each generator
now gets the vector it makes, still computed once per turn, compared by reference; at most four generators are
remembered, the oldest dropped first, so one built for every call cannot make the cache grow.
### Security
- **Novior.MentorAgent.Server:** BUG-230 (S1): `GET /mentor/chat` ran a turn for any request the browser sent with the
sign-in cookie, and with cookie authentication (`SameSite=Lax`) that includes a link clicked on another site: one
link ran a turn as the signed-in user, with the link author's question, even with `RequireAuthorization`. Both
`GET` and `POST /mentor/chat` now answer `403` before the turn when the browser's Fetch Metadata says another site
started the request (`Sec-Fetch-Site` `cross-site` or `same-site`, `Sec-Fetch-Mode` not `cors`), and log a warning
`chat.cross-site-refused` without the question. Your own page's calls, clients without Fetch Metadata and `cors`
requests work as before. With a `SameSite=None` cookie, or for browsers that send no Fetch Metadata, add a check
of your own: the Server README says how.
The full history is in CHANGELOG.md, inside this package.