Crestapps core chat interactions

From CrestApps/CrestApps.AgentSkills · View interactive version

Crestapps core chat interactions is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for Chat Interactions and the shared chat hubs and chat UI in CrestApps.Core 2.0. Covers AddChatInteractions with AddEntityCoreStores or AddYesSqlStores, ConfigureVisitorIdentity, ConfigureChatRateLimiting and ConfigureChatHubOptions, subclassing ChatInteractionHubBase and AIChatHubCore with A

How to use this skill

Skill file

CrestApps.Core Chat Interactions

A Chat Interaction is an operator-controlled conversation that needs no AI Profile: the interaction itself stores its deployments, system message, sampling, tools, agents, MCP connections, data source and documents. It is the fastest way to validate a provider and deployment. AI Chat sessions (AIChatSession) are the profile-based equivalent used by end-user chat pages and widgets. Both ship in CrestApps.Core.AI.Chat and share the same chat UI scripts.

Guidelines

Registration

using CrestApps.Core.AI.Chat;
using CrestApps.Core.AI.OpenAI;
using CrestApps.Core.AI.Security;
using CrestApps.Core.Data.EntityCore;
using CrestApps.Core.SignalR;
using MyApp.Hubs;

builder.Services.AddCrestAppsCore(crestApps => crestApps
    .AddAISuite(ai => ai
        .AddEntityCoreStores()
        .AddOpenAI()
        .AddSignalR(addStoreCommitterFilter: true)
        .AddChatInteractions(chatInteractions => chatInteractions
            .AddEntityCoreStores()
            .ConfigureChatHubOptions<ChatInteractionHub>()
            .ConfigureVisitorIdentity(options =>
            {
                options.RemoteAddressMode = AIVisitorRemoteAddressMode.Hashed;
            })
            .ConfigureChatRateLimiting(options =>
            {
                options.AnonymousSessionStartPartitions =
                    ChatRateLimitPartition.Visitor |
                    ChatRateLimitPartition.NetworkAddress;
            })
        )
    )
    .AddEntityCoreSqliteDataStore("Data Source=app.db")
);

// HubOptions<THub> is per concrete hub type; configure every chat hub you map.
builder.Services.ConfigureCrestAppsChatHubOptions<AIChatHub>();

var app = builder.Build();

app.MapHub<ChatInteractionHub>("/hubs/chat-interaction");
app.MapHub<AIChatHub>("/hubs/ai-chat");

Use .AddYesSqlStores() instead of .AddEntityCoreStores() for YesSql; YesSql hosts create the index tables with CreateChatInteractionIndexSchemaAsync and CreateChatInteractionPromptIndexSchemaAsync (see crestapps-core-yessql-stores).

AddCoreAIChatInteractions() (called by AddChatInteractions) registers visitor identity, chat notifications, the session-processing pipeline (AddCoreAIChatSessionProcessing: data extraction, post-session processing, the AIChatSessionCloseBackgroundService that closes inactive sessions every 5 minutes), CitationReferenceCollector, CompositeAIReferenceLinkResolver, ChatInteractionCompletionContextBuilderHandler, the built-in settings handlers (data source, prompt template, persona), and OptionsRealtimeIceServerProvider.

ConfigureChatHubOptions<THub>() uses AddHubOptions<THub> (a plain services.Configure<HubOptions<THub>> is silently ignored by SignalR) and sets a 10-minute client timeout, 15-second keep-alive, 10 MB maximum message size, 8 parallel invocations per client, and a stream buffer of 64.

Host the Hub

ChatInteractionHub and AIChatHub above are host classes. The interaction hub looks like this; the session hub is in chat-interactions-examples.md.

using CrestApps.Core.AI.Chat.Hubs;
using CrestApps.Core.AI.Models;
using Microsoft.AspNetCore.Authorization;

namespace MyApp.Hubs;

[Authorize]
public sealed class ChatInteractionHub : ChatInteractionHubBase
{
    public ChatInteractionHub(
        IServiceProvider services,
        TimeProvider timeProvider,
        ILogger<ChatInteractionHub> logger)
        : base(services, timeProvider, logger)
    {
    }

    protected override Task<bool> AuthorizeAsync(IServiceProvider services, ChatInteraction interaction)
        => Task.FromResult(string.Equals(interaction.OwnerId, Context.UserIdentifier, StringComparison.Ordinal));

    protected override Task<ChatMode> GetChatModeAsync(IServiceProvider services)
        => Task.FromResult(ChatMode.Conversation);
}

Other virtual hooks include GetDeploymentSettingsAsync (returns the DefaultAIDeploymentSettings used for slot defaults), IsTextToSpeechPlaybackEnabledAsync, CollectStreamingReferences (merge citations with CitationReferenceCollector), OnAssistantPromptCreatedAsync, ValidateSettings, and the localizable message methods (GetNotAuthorizedMessage, GetSettingsValidationMessage, GetNoRealtimeDeploymentMessage, GetConversationDeploymentNotRealtimeMessage, and others). AIChatHubCore<TClient> exposes AuthorizeProfileAsync(IServiceProvider, AIProfile) and GetRateLimitedMessage(PromptSecurityResult), which returns a "slow down" message with the retry delay when the message rate limit is hit.

AIChatHubCore<TClient> also exposes AuthorizeSessionAsync(IServiceProvider, AIChatSession) and ValidateOutputAsync(...) (the output security filter, then the profile's guardrails; returns the replacement text for a blocked reply or null).

Session Ownership

Loading, continuing, rating and acting on a session all call AuthorizeSessionAsync first. By default it allows only the signed-in user whose id (ClaimTypes.NameIdentifier, else the name) equals AIChatSession.UserId, or, for a visitor session, the same ClientId from IAIVisitorIdentityResolver. A session with neither is refused. A refused id is answered with GetSessionNotFoundMessage(), and a message sent to it starts a new session for the caller. Let staff open other users' conversations by widening it:

protected override async Task<bool> AuthorizeSessionAsync(IServiceProvider services, AIChatSession chatSession)
{
    if (await base.AuthorizeSessionAsync(services, chatSession))
    {
        return true;
    }

    var authorizationService = services.GetRequiredService<IAuthorizationService>();

    return (await authorizationService.AuthorizeAsync(Context.User, "Admin")).Succeeded;
}

Stop After Streaming

When the user presses Stop after the answer has streamed, the hubs still validate, save and finish the turn: the remaining work ignores the cancelled token, and SendMessage runs in a child scope the hub owns because SignalR disposes the invocation scope on cancel. A host that overrides ExecuteInScopeAsync with its own scope keeps that scope.

Hub methods called by the client (interaction hub; the session hub takes profileId and sessionId instead of itemId):

| Method | Purpose |

|---|---|

| SendMessage(itemId, prompt) | Streams CompletionPartialMessage items through a ChannelReader |

| RunAgent(input) | Session hub only: an AG-UI run that streams AG-UI events (see crestapps-core-ag-ui) |

| LoadInteraction(itemId) / SaveSettings(itemId, settings) / ClearHistory(itemId) | Load, update and reset an interaction |

| StartConversation, SendAudioStream, SynthesizeSpeech | Speech-to-text and text-to-speech conversation mode |

| StartRealtimeConversation, StartRealtimeWebRtc, AddRealtimeIceCandidate, GetRealtimeIceServers, UpdateRealtimeSettings, UpdateRealtimeSpeechSpeed, StopConversation | Realtime voice (see crestapps-core-realtime-voice) |

| HandleNotificationAction(sessionId, notificationType, actionName) | Chat notification buttons |

| SetPageTools(tools) / ClearPageTools() | Session hub only: the WebMCP tools the tab exposes (see crestapps-core-webmcp) |

IChatInteractionHubClient callbacks: ReceiveError, LoadInteraction, SettingsSaved, HistoryCleared, ReceiveTranscript, ReceiveAudioChunk, ReceiveAudioComplete, ReceiveRealtimeAnswer, ReceiveRealtimeIceCandidate, ReceiveRealtimeEvent, ReceiveConversationUserMessage, ReceiveConversationAssistantToken, ReceiveConversationAssistantComplete, ReceiveNotification, UpdateNotification, RemoveNotification.

The Interaction and Its Settings

SaveSettings reads camelCase keys from the settings JSON: title, orchestratorName, connectionName, deploymentName (stored as ChatDeploymentName), utilityDeploymentName, conversationDeploymentName, realtimeVoiceName, systemMessage, temperature, topP, frequencyPenalty, presencePenalty, maxTokens, pastMessagesCount, toolNames, agentNames, mcpConnectionIds, plus whatever the registered IChatInteractionSettingsHandler implementations read (for example filter, personaId).

Security Behavior

Documents

Upload and remove endpoints live in CrestApps.Core.AI.Documents.Endpoints and need document processing (crestapps-core-document-processing):

app.AddUploadChatInteractionDocumentEndpoint();
app.AddRemoveChatInteractionDocumentEndpoint();
app.AddUploadChatSessionDocumentEndpoint();
app.AddRemoveChatSessionDocumentEndpoint();
app.AddDownloadAIDocumentEndpoint();

Each Add*Endpoint() returns the endpoint's RouteHandlerBuilder (add filters or metadata to it), so call them on app one by one; they no longer chain. Authorize them by registering IAuthorizationHandler implementations for AIChatDocumentOperations.ManageDocuments on ChatInteraction and on AIChatSessionDocumentAuthorizationContext.

@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Antiforgery

<meta name="RequestVerificationToken" content="@Antiforgery.GetAndStoreTokens(Context).RequestToken" />

The vendored scripts send the token (through window.CoreAIAntiforgery in chat-markers.js) from the chat config's antiforgeryToken, else that meta tag, else a hidden __RequestVerificationToken field, and only to same-origin URLs.

Chat UI Assets

The browser scripts are published as @crestapps/ai-chat-ui (npm or jsDelivr). Load Vue 3, marked, DOMPurify and a pinned SignalR client first, then the CrestApps scripts:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@crestapps/ai-chat-ui/dist/chat-widget.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@crestapps/ai-chat-ui/dist/chat-image-carousel.min.css" />

<script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@10.0.11/dist/browser/signalr.min.js"
        integrity="sha384-N+pL/4qXZHZcvsa6hVMd5/7cdF3lC59ZMNHeQyRo5q9jmC7yw0hcJILPjUDSU7ZS"
        crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dompurify@3/dist/purify.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@crestapps/ai-chat-ui/dist/chat-markers.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@crestapps/ai-chat-ui/dist/chat-image-carousel.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@crestapps/ai-chat-ui/dist/ai-chat.min.js"></script>

What an Answer May Render

CoreAIImages.sanitize (in chat-markers.js, used by both chat scripts and the MVC chat-interaction view) cleans every answer:

window.coreAIChatManager().initialize({
    // ...
    allowedImageHosts: ['images.example.com', '*.cdn.example.com']
});

Upgrading Within 2.0 Previews

Upgrading from 1.x

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.