CrestApps.Core Copilot Orchestrator
CrestApps.Core.AI.Copilot adds CopilotOrchestrator, an IOrchestrator named "copilot" (title Copilot), which runs a turn through the GitHub Copilot SDK and its CLI instead of the default pipeline.
Guidelines
- Choose GitHub OAuth when each user brings a Copilot subscription. Choose
ApiKey(BYOK) for one shared OpenAI-compatible, Azure or Anthropic endpoint. - Treat
NotConfiguredas intentionally disabled; editors should show a warning instead of Copilot fields while it is selected. - Bind
CopilotOptionsyourself; the package reads no configuration section. - GitHub OAuth needs an
ICopilotCredentialStore. BYOK does not. - Copilot does not use AI connections, deployments, deployment capabilities or deployment model parameters, and its SDK-managed requests are not recorded by usage metering.
Registration
using CrestApps.Core.AI.Copilot;
using CrestApps.Core.AI.Copilot.Models;
builder.Services.AddCrestAppsCore(crestApps => crestApps
.AddAISuite(ai => ai
.AddCopilotOrchestrator()
)
);
builder.Services.Configure<CopilotOptions>(builder.Configuration.GetSection("Copilot"));
Raw form: builder.Services.AddCoreAICopilotOrchestrator(); after AddCoreAIServices() and AddCoreAIOrchestration(). It registers a named HttpClient with the standard resilience handler, the orchestrator, GitHubOAuthService, CopilotChatInteractionSettingsHandler, CopilotOrchestrationContextHandler and CopilotOptionsValidator.
Referencing the package downloads the Copilot CLI during build into runtimes/<rid>/native/. It caches the CLI machine-wide under the NuGet packages folder and resolves the npm registry from NPM_CONFIG_REGISTRY or npm config get registry. Override only when needed with the MSBuild properties CopilotUseSharedCliCache, CopilotCliCacheDir, CopilotResolveNpmRegistry and CopilotNpmRegistryUrl; the SDK's CopilotCliBinaryPath and CopilotSkipCliDownload still win.
Authentication Modes
| CopilotAuthenticationType | Required for the orchestrator to run |
|---|---|
| NotConfigured | Never runs |
| GitHubOAuth | ClientId, ClientSecret (Scopes default user:email, read:org) and a signed-in user with a stored credential |
| ApiKey | ProviderType, BaseUrl, DefaultModel; for azure also ApiKey and AzureApiVersion |
CopilotOptionsValidator fails when ClientId or ClientSecret is missing in OAuth mode, or ApiKey is missing in BYOK mode. When the runtime check fails, a turn answers "Copilot is not configured and cannot be used until it has been configured."
{
"Copilot": {
"AuthenticationType": "ApiKey",
"ProviderType": "openai",
"BaseUrl": "https://api.openai.com/v1",
"ApiKey": "sk-...",
"DefaultModel": "gpt-4o",
"WireApi": "completions"
}
}
{
"Copilot": {
"AuthenticationType": "GitHubOAuth",
"ClientId": "Iv1.abc123",
"ClientSecret": "your-client-secret",
"Scopes": [ "user:email", "read:org" ]
}
}
Credential Store
public interface ICopilotCredentialStore
{
Task<CopilotProtectedCredential> GetProtectedCredentialAsync(string userId, CancellationToken cancellationToken = default);
Task SaveProtectedCredentialAsync(string userId, CopilotProtectedCredential credential, CancellationToken cancellationToken = default);
Task ClearCredentialAsync(string userId, CancellationToken cancellationToken = default);
}
CopilotProtectedCredential carries GitHubUsername, ProtectedAccessToken, ProtectedRefreshToken, ExpiresAt and UpdatedUtc; the tokens arrive already protected. Scope storage by user (and tenant). For development, the shipped JsonFileCopilotCredentialStore writes one file per user under App_Data/CopilotCredentials:
builder.Services.AddScoped<ICopilotCredentialStore, JsonFileCopilotCredentialStore>();
Use a database-backed store in production.
OAuth Flow
using System.Security.Claims;
using CrestApps.Core.AI.Copilot.Services;
using Microsoft.AspNetCore.Mvc;
[Route("copilot")]
public sealed class CopilotAuthController : Controller
{
private readonly GitHubOAuthService _oauthService;
public CopilotAuthController(GitHubOAuthService oauthService)
{
_oauthService = oauthService;
}
[HttpGet("connect")]
public IActionResult Connect(string returnUrl = "/")
{
var callbackUrl = Url.Action(nameof(Callback), null, null, Request.Scheme);
return Redirect(_oauthService.GetAuthorizationUrl(callbackUrl, returnUrl));
}
[HttpGet("callback")]
public async Task<IActionResult> Callback(string code, string state, CancellationToken cancellationToken)
{
if (!_oauthService.TryValidateCallbackState(state, out var returnUrl))
{
return BadRequest();
}
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
await _oauthService.ExchangeCodeForTokenAsync(code, userId, cancellationToken);
return LocalRedirect(returnUrl);
}
}
GetAuthorizationUrl writes a protected, ten-minute state cookie (named __Host-crestapps-gh-oauth-state over HTTPS, so a sibling subdomain cannot plant it) and sends a RandomNumberGenerator nonce as state. The state records the signed-in user, and TryValidateCallbackState succeeds only for that same user, deletes the cookie after it validates (one round trip cannot be replayed), and returns only a local return URL (or __popup__). Both need an HttpContext: GetAuthorizationUrl throws InvalidOperationException without one, and validation fails. Other members: GetCredentialAsync, GetProtectedCredentialsAsync, GetValidAccessTokenAsync (refreshes when expired), IsAuthenticatedAsync, ListModelsAsync and DisconnectAsync, all keyed by user id.
Session Metadata
CopilotSessionMetadata on a profile or chat interaction overrides CopilotModel, IsAllowAll (approve all SDK permission requests, default true), and ReasoningEffort (CopilotReasoningEffort.None, Low, Medium, High), and records GitHubUsername plus protected tokens in OAuth mode.
profile.OrchestratorName = "copilot";
profile.Put(new CopilotSessionMetadata { CopilotModel = "gpt-4o", ReasoningEffort = CopilotReasoningEffort.Low });
How a Turn Runs
- Tools come from
IToolRegistry(system, profile, agent and tool instance tools); MCP tools are excluded from it. - Each tool is wrapped so dependency injection works when the SDK invokes it.
- A session config is built with streaming, the model (
CopilotModelorDefaultModel), the tools and the system message. - BYOK sets the provider type, base URL, key,
WireApiand Azure API version; OAuth usesGitHubOAuthService.GetValidAccessTokenAsync. - MCP connections in the context are only described in the system message under
[Available MCP Servers]. The current SDKSessionConfighas no MCP server support, and MCP tools are excluded from the tool list, so the model cannot call MCP tools through this orchestrator. Use the default orchestrator for profiles that depend on MCP tools.
Tool access follows the profile's configuration, the same boundary as the default orchestrator. The Copilot orchestrator creates tools straight from the registry entries rather than through IToolMaterializer, so a tool registered with RequireApproval() is not filtered out here the way the default and Claude orchestrators filter it; do not attach approval-required tools to a Copilot profile.
Troubleshooting
- "Copilot is not configured...": the mode's required values are missing (see the table), usually because nothing bound
CopilotOptions. - Build fails downloading the CLI behind a proxy: set
CopilotNpmRegistryUrlorNPM_CONFIG_REGISTRY, or pointCopilotCliCacheDirat a pre-seeded cache. - OAuth callback rejected: the state cookie expired, was already used, the callback ran on a different host than the connect request, or a different user (or a signed-out browser) completed the flow.
Upgrading Within 2.0 Previews
GitHubOAuthServicebinds the OAuth state to the user who started the flow, deletes the state cookie once it validates, and throws fromGetAuthorizationUrlwithout anHttpContext.
Upgrading from 1.x
- Match the current
ICopilotCredentialStoresignatures, which take aCancellationToken; stores written against older samples without it no longer compile. - Validate the OAuth
statewithTryValidateCallbackState; it is a nonce backed by a protected cookie, not the return URL that older samples redirected to. - The removed deployment purpose and the new deployment capabilities do not affect Copilot.