// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.CommandLine;
using System.CommandLine.Completions;
using System.Diagnostics;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Nodes;
using Aspire.Cli.Agents;
using Aspire.Cli.Agents.AspireSkills;
using Aspire.Cli.Agents.Copilot;
using Aspire.Cli.Agents.Hooks;
using Aspire.Cli.Agents.OpenCode;
using Aspire.Cli.Agents.Playwright;
using Aspire.Cli.Configuration;
using Aspire.Cli.Git;
using Aspire.Cli.Interaction;
using Aspire.Cli.Projects;
using Aspire.Cli.Resources;
using Aspire.Cli.Utils;
using Spectre.Console;
namespace Aspire.Cli.Commands;
/// <summary>
/// Command that initializes configuration and copied skills for selected agents.
/// This is the new command under 'aspire agent init'.
/// </summary>
internal sealed class AgentInitCommand : BaseCommand
{
private readonly IAgentEnvironmentDetector _agentEnvironmentDetector;
private readonly IReadOnlyList<IAgentClient> _clients;
private readonly PlaywrightCliInstaller _playwrightCliInstaller;
private readonly IGitRepository _gitRepository;
private readonly ILanguageDiscovery _languageDiscovery;
private readonly ITelemetryHookConfigurator _telemetryHookConfigurator;
private readonly ICliHostEnvironment _hostEnvironment;
private readonly IConfigurationService _configurationService;
private readonly IProjectLocator _projectLocator;
private static readonly string[] s_skillChoices =
[CommonAgentApplicators.AspireSkillName, SkillDefinition.PlaywrightCli.Name, SkillDefinition.DotnetInspect.Name];
public AgentInitCommand(
IAgentEnvironmentDetector agentEnvironmentDetector,
IEnumerable<IAgentClient> clients,
PlaywrightCliInstaller playwrightCliInstaller,
IGitRepository gitRepository,
ILanguageDiscovery languageDiscovery,
ITelemetryHookConfigurator telemetryHookConfigurator,
IConfigurationService configurationService,
IProjectLocator projectLocator,
CommonCommandServices services)
: base("init", AgentCommandStrings.InitCommand_Description, services)
{
_agentEnvironmentDetector = agentEnvironmentDetector;
_clients = clients.ToArray();
AgentsOption = CreateAgentsOption(_clients);
_playwrightCliInstaller = playwrightCliInstaller;
_gitRepository = gitRepository;
_languageDiscovery = languageDiscovery;
_telemetryHookConfigurator = telemetryHookConfigurator;
_hostEnvironment = services.HostEnvironment;
_configurationService = configurationService;
_projectLocator = projectLocator;
Options.Add(s_workspaceRootOption);
Options.Add(s_mcpOption);
Options.Add(s_removeSkillCopiesOption);
Options.Add(AgentsOption);
Options.Add(s_scopeOption);
Options.Add(s_skillsOption);
}
internal Option<string?> AgentsOption { get; }
internal static readonly Option<AgentConfigurationScope> s_scopeOption = CreateScopeOption();
internal static readonly Option<string?> s_workspaceRootOption = new("--workspace-root")
{
Description = AgentCommandStrings.InitCommand_WorkspaceRootOptionDescription
};
internal static readonly Option<string?> s_skillsOption = CreateSkillsOption();
/// <summary>
/// Confirms whether standalone <c>aspire agent init</c> configures the Aspire MCP server for
/// selected agent environments. This option is only registered on this command — <c>aspire
/// new</c> and <c>aspire init</c> do not add it, so MCP configuration is unavailable from
/// those chained flows by construction. Omitting the option defaults to "no"; passing
/// <c>--mcp</c> opts in, and <c>--mcp=false</c> is an explicit opt-out.
/// </summary>
internal static readonly Option<bool?> s_mcpOption = new("--mcp")
{
Description = AgentCommandStrings.InitCommand_McpOptionDescription,
Recursive = true
};
/// <summary>
/// Authorizes deleting copied Aspire skill folders that the Aspire skills plugin replaces at the
/// selected scope. Those folders can contain user edits, so omitting the option asks interactively
/// (defaulting to "no") and keeps them in non-interactive runs.
/// </summary>
internal static readonly Option<bool?> s_removeSkillCopiesOption = new("--remove-skill-copies")
{
Description = AgentCommandStrings.InitCommand_RemoveSkillCopiesOptionDescription,
Recursive = true
};
private static Option<string?> CreateSkillsOption()
{
var supportedSkills = string.Join(",", s_skillChoices);
var option = new Option<string?>("--skills")
{
HelpName = "skills",
Description = string.Format(CultureInfo.InvariantCulture, AgentCommandStrings.InitCommand_SkillsOptionDescription,
supportedSkills, ConsoleInteractionService.AllChoice, ConsoleInteractionService.NoneChoice),
Recursive = true,
Arity = ArgumentArity.ExactlyOne,
CustomParser = result =>
{
if (result.Tokens.Count != 1)
{
return null;
}
// For example: "aspire,playwright-cli". "all" selects these skills/tools, never MCP.
var value = result.Tokens[0].Value;
var selected = ConsoleInteractionService.MatchChoices(value, s_skillChoices, static name => name);
if (selected is null || selected.Count == 0 &&
!string.Equals(value, ConsoleInteractionService.NoneChoice, StringComparison.OrdinalIgnoreCase))
{
result.AddError(string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_InvalidSkills,
value, supportedSkills, ConsoleInteractionService.AllChoice, ConsoleInteractionService.NoneChoice));
}
return value;
}
};
option.CompletionSources.Clear();
option.CompletionSources.Add([.. s_skillChoices, ConsoleInteractionService.AllChoice, ConsoleInteractionService.NoneChoice]);
return option;
}
private static Option<string?> CreateAgentsOption(IReadOnlyList<IAgentClient> clients)
{
var supportedClients = string.Join(",", clients.Select(static client => client.Id));
var option = new Option<string?>("--agents")
{
HelpName = "agents",
Description = string.Format(CultureInfo.InvariantCulture, AgentCommandStrings.InitCommand_EnvironmentsOptionDescription,
supportedClients, ConsoleInteractionService.AllChoice, ConsoleInteractionService.NoneChoice),
Recursive = true,
Arity = ArgumentArity.ExactlyOne,
CustomParser = result =>
{
if (result.Tokens.Count == 0)
{
return null;
}
var value = result.Tokens[0].Value;
var selected = ConsoleInteractionService.MatchChoices(value, clients, static client => client.Id);
if (selected is null || selected.Count == 0 &&
!string.Equals(value, ConsoleInteractionService.NoneChoice, StringComparison.OrdinalIgnoreCase))
{
result.AddError(string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_InvalidEnvironments,
value, supportedClients, ConsoleInteractionService.AllChoice, ConsoleInteractionService.NoneChoice));
}
return value;
}
};
option.CompletionSources.Clear();
option.CompletionSources.Add(_ =>
[.. clients.Select(static client => new CompletionItem(client.Id)),
new CompletionItem(ConsoleInteractionService.AllChoice), new CompletionItem(ConsoleInteractionService.NoneChoice)]);
return option;
}
private static Option<AgentConfigurationScope> CreateScopeOption()
{
var option = new Option<AgentConfigurationScope>("--scope")
{
HelpName = "project|global",
Description = AgentCommandStrings.InitCommand_ScopeOptionDescription,
Recursive = true,
Arity = ArgumentArity.ExactlyOne
};
// Native enum parsing also accepts numeric and composite values; scope is one named choice.
option.Validators.Add(result =>
{
if (result.Tokens.Count == 1 &&
Enum.TryParse<AgentConfigurationScope>(result.Tokens[0].Value, ignoreCase: true, out _) &&
!Enum.GetNames<AgentConfigurationScope>().Contains(result.Tokens[0].Value, StringComparer.OrdinalIgnoreCase))
{
result.AddError(string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_InvalidScope, result.Tokens[0].Value));
}
});
option.CompletionSources.Clear();
option.CompletionSources.Add(static _ => [new CompletionItem("project"), new CompletionItem("global")]);
return option;
}
/// <summary>
/// Public entry point for executing the init command.
/// This allows McpInitCommand to delegate to this implementation.
/// </summary>
internal Task<CommandResult> ExecuteCommandAsync(ParseResult parseResult, CancellationToken cancellationToken)
{
return ExecuteAsync(parseResult, cancellationToken);
}
/// <summary>
/// Prompts the user to run agent init after a successful command, then chains into agent init if accepted.
/// Used by commands (e.g. <c>aspire init</c>, <c>aspire new</c>) to offer agent init as a follow-up step.
/// Chained flows never register <c>--mcp</c> and never offer MCP server configuration: this
/// method always executes agent init with MCP configuration unavailable, so MCP remains an
/// explicit opt-in reachable only through standalone <c>aspire agent init</c>.
/// The agent, skill, and scope bindings reuse the standalone command's non-interactive selection semantics.
/// </summary>
internal async Task<AgentInitExecutionResult> PromptAndChainAsync(
IInteractionService interactionService,
int previousResultExitCode,
DirectoryInfo workspaceRoot,
DirectoryInfo configurationDirectory,
PromptBinding<bool> agentInitBinding,
PromptBinding<string?> agentsBinding,
PromptBinding<string?> skillsBinding,
PromptBinding<AgentConfigurationScope> scopeBinding,
PromptBinding<bool> removeSkillCopiesBinding,
CancellationToken cancellationToken)
{
if (previousResultExitCode != CliExitCodes.Success)
{
return new(previousResultExitCode, [], []);
}
// Add a separating line between prompt and previous work in aspire new and aspire init.
interactionService.DisplayEmptyLine();
var runAgentInit = await interactionService.PromptConfirmAsync(
SharedCommandStrings.PromptRunAgentInit,
binding: agentInitBinding,
cancellationToken: cancellationToken);
if (runAgentInit)
{
return await ExecuteAgentInitAsync(
workspaceRoot, configurationDirectory, agentsBinding, skillsBinding,
scopeBinding, mcpBinding: null, removeSkillCopiesBinding, cancellationToken);
}
return new(CliExitCodes.Success, [], []);
}
protected override async Task<CommandResult> ExecuteAsync(ParseResult parseResult, CancellationToken cancellationToken)
{
var workspaceRoot = await PromptForWorkspaceRootAsync(parseResult, cancellationToken);
var result = await ExecuteAgentInitAsync(
workspaceRoot,
configurationDirectory: null,
PromptBinding.Create(parseResult, AgentsOption),
PromptBinding.Create(parseResult, s_skillsOption, CommonAgentApplicators.AspireSkillName),
PromptBinding.Create(parseResult, s_scopeOption, AgentConfigurationScope.Project),
PromptBinding.CreateBoolConfirm(parseResult, s_mcpOption, defaultValue: false),
PromptBinding.CreateBoolConfirm(parseResult, s_removeSkillCopiesOption, defaultValue: false),
cancellationToken);
return CommandResult.FromExitCode(result.ExitCode);
}
private async Task<DirectoryInfo> GetConfigurationDirectoryAsync(CancellationToken cancellationToken)
{
// Discover the AppHost without the advisory configuration-source checks performed
// by UseOrFindAppHostProjectFileAsync. Agent setup only consumes saved settings.
var appHost = await _projectLocator.GetAppHostFromSettingsAsync(cancellationToken);
if (appHost is null)
{
var candidates = await _projectLocator.FindAppHostProjectFilesAsync(
ExecutionContext.WorkingDirectory, AppHostDiscoveryScope.DefaultFiltered, cancellationToken, skipValidation: true);
appHost = candidates.Count switch
{
0 => null,
1 => candidates[0],
_ => await InteractionService.PromptForSelectionAsync(
InteractionServiceStrings.SelectAppHostToUse,
candidates,
file => $"{file.Name.EscapeMarkup()} ({Path.GetRelativePath(ExecutionContext.WorkingDirectory.FullName, file.FullName).EscapeMarkup()})",
cancellationToken: cancellationToken)
};
}
return appHost?.Directory ?? ExecutionContext.WorkingDirectory;
}
private async Task<DirectoryInfo> PromptForWorkspaceRootAsync(ParseResult parseResult, CancellationToken cancellationToken)
{
// Try to discover the git repository root to use as the default workspace root
var gitRoot = await _gitRepository.GetRootAsync(cancellationToken);
var defaultWorkspaceRoot = gitRoot ?? ExecutionContext.WorkingDirectory;
// Prompt the user for the workspace root
var workspaceRootPath = await InteractionService.PromptForFilePathAsync(
McpCommandStrings.InitCommand_WorkspaceRootPrompt,
binding: PromptBinding.Create(parseResult, s_workspaceRootOption, defaultWorkspaceRoot.FullName),
validator: path =>
{
if (string.IsNullOrWhiteSpace(path))
{
return ValidationResult.Error(McpCommandStrings.InitCommand_WorkspaceRootRequired);
}
if (!Directory.Exists(path))
{
return ValidationResult.Error(string.Format(CultureInfo.InvariantCulture, McpCommandStrings.InitCommand_WorkspaceRootNotFound, path));
}
return ValidationResult.Success();
},
directory: true,
cancellationToken: cancellationToken);
return new DirectoryInfo(workspaceRootPath);
}
private async Task<AgentInitExecutionResult> ExecuteAgentInitAsync(
DirectoryInfo workspaceRoot,
DirectoryInfo? configurationDirectory,
PromptBinding<string?> agentsBinding,
PromptBinding<string?> skillsBinding,
PromptBinding<AgentConfigurationScope> scopeBinding,
PromptBinding<bool>? mcpBinding,
PromptBinding<bool> removeSkillCopiesBinding,
CancellationToken cancellationToken)
{
var (agentsProvided, requestedAgents) = agentsBinding.Resolve();
IReadOnlyList<IAgentClient> selectedClients;
if (agentsProvided && requestedAgents is not null)
{
var matchedClients = ConsoleInteractionService.MatchChoices(requestedAgents, _clients, static client => client.Id);
if (matchedClients is null)
{
InteractionService.DisplayError(string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_InvalidEnvironments,
requestedAgents, string.Join(",", _clients.Select(static client => client.Id)),
ConsoleInteractionService.AllChoice, ConsoleInteractionService.NoneChoice));
return new(CliExitCodes.InvalidCommand, [], []);
}
selectedClients = matchedClients;
}
else
{
var context = new AgentEnvironmentScanContext
{
WorkingDirectory = ExecutionContext.WorkingDirectory,
RepositoryRoot = workspaceRoot
};
var detectedEnvironments = await InteractionService.ShowStatusAsync(
McpCommandStrings.InitCommand_DetectingAgentEnvironments,
async () => await _agentEnvironmentDetector.DetectAsync(context, cancellationToken),
emoji: KnownEmojis.Robot);
// Shared discovery does not authorize configuring another agent. Defaults
// express detected agent use, independently of assets and their destinations.
var defaultClients = _clients
.Where(client => (client.Environments & detectedEnvironments) != AgentEnvironment.None).ToArray();
if (defaultClients.Length == 0)
{
defaultClients = [_clients.Single(client => string.Equals(client.Id, CopilotAgentClient.ClientId, StringComparisons.AgentClientId))];
}
selectedClients = await InteractionService.PromptForSelectionsAsync(
AgentCommandStrings.InitCommand_SelectAgentsPrompt,
_clients.OrderByDescending(client => defaultClients.Contains(client)),
static client => client.DisplayName.EscapeMarkup(),
preSelected: defaultClients,
optional: true,
binding: agentsBinding.WithDefault(string.Join(",", defaultClients.Select(static client => client.Id))),
echoSelected: false,
cancellationToken: cancellationToken);
}
// Both explicit and interactive opt-outs stop before acquiring the skill catalog.
if (selectedClients.Count == 0)
{
InteractionService.DisplaySubtleMessage(AgentCommandStrings.InitCommand_NoConfigurationSelected);
return new(CliExitCodes.Success, [], []);
}
// Detect the AppHost language to determine which skills to offer.
// When no language is detected (e.g., standalone `aspire agent init`), language-restricted skills are excluded.
var detectedLanguage = await _languageDiscovery.DetectLanguageRecursiveAsync(workspaceRoot, cancellationToken);
var availableSkillChoices = s_skillChoices
.Where(name => name != SkillDefinition.DotnetInspect.Name || SkillDefinition.DotnetInspect.IsApplicableToLanguage(detectedLanguage))
.ToArray();
var (skillsProvided, requestedSkills) = skillsBinding.Resolve();
var showSkillWarnings = (_hostEnvironment.SupportsInteractiveInput && (!skillsProvided || requestedSkills is null)) ||
ConsoleInteractionService.MatchChoices(requestedSkills ?? CommonAgentApplicators.AspireSkillName,
availableSkillChoices, static name => name)?.Contains(CommonAgentApplicators.AspireSkillName) is true;
IReadOnlyList<SkillSource> skillSources = [];
string? skillConfigurationError = null;
if (showSkillWarnings)
{
configurationDirectory ??= await GetConfigurationDirectoryAsync(cancellationToken);
try
{
skillSources = SkillSource.Resolve(configurationDirectory, new FileInfo(_configurationService.GetSettingsFilePath(isGlobal: true)));
var usesPlugins = selectedClients.Any(client => client.Id != OpenCodeAgentClient.ClientId);
var usesOpenCode = selectedClients.Any(client => client.Id == OpenCodeAgentClient.ClientId);
List<IReadOnlyList<(string Label, string Value)>> sourceDetails = [];
foreach (var skillSource in skillSources)
{
var sourceName = skillSource.GetName();
if (sourceName.Equals(SkillSource.DefaultName, StringComparison.OrdinalIgnoreCase))
{
continue;
}
List<(string Label, string Value)> details = [(SharedCommandStrings.SourceName, sourceName)];
if (usesPlugins)
{
details.Add((SharedCommandStrings.SourceGitRepository, skillSource.GetRepositoryUrl()));
if (skillSource.Ref is not null)
{
details.Add((SharedCommandStrings.SourceRef, skillSource.Ref));
}
if (!string.Equals(skillSource.Marketplace, sourceName, StringComparison.OrdinalIgnoreCase))
{
details.Add((SharedCommandStrings.SourceMarketplace, skillSource.Marketplace!));
}
details.Add((SharedCommandStrings.SourcePlugins, string.Join(", ", skillSource.GetPluginNames())));
}
if (usesOpenCode)
{
if (skillSource.OpenCodeV1Catalog is not null)
{
details.Add((SharedCommandStrings.SourceOpenCodeV1Catalog, skillSource.OpenCodeV1Catalog));
}
if (skillSource.OpenCodeV2Catalog is not null)
{
details.Add((SharedCommandStrings.SourceOpenCodeV2Catalog, skillSource.OpenCodeV2Catalog));
}
}
if (details.Count > 1)
{
sourceDetails.Add(details);
}
}
if (sourceDetails.Count > 0)
{
InteractionService.DisplayMessage(KnownEmojis.Information, AgentCommandStrings.InitCommand_SkillSourcesExplanation);
InteractionService.DisplaySourceDetails(sourceDetails);
if (InteractionService.DisplaySourceTrustWarning(ExecutionContext))
{
InteractionService.DisplayEmptyLine();
}
}
}
catch (Exception ex) when (ex is JsonException or InvalidOperationException or IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
skillConfigurationError = ex.Message;
}
}
var selectedSkillNames = await InteractionService.PromptForSelectionsAsync(
AgentCommandStrings.InitCommand_SelectSkills,
availableSkillChoices,
name => $"{name.EscapeMarkup()} — {(name == CommonAgentApplicators.AspireSkillName
? AgentCommandStrings.InitCommand_AspireSkillChoice
: SimplifyDescription(SkillDefinition.CliDefined.Single(skill => skill.HasName(name)).Description)).EscapeMarkup()}",
preSelected: [CommonAgentApplicators.AspireSkillName],
optional: true,
binding: skillsBinding,
echoSelected: false,
cancellationToken: cancellationToken);
var playwright = selectedSkillNames.Contains(SkillDefinition.PlaywrightCli.Name);
var dotnetInspect = selectedSkillNames.Contains(SkillDefinition.DotnetInspect.Name);
var configureAspire = selectedSkillNames.Contains(CommonAgentApplicators.AspireSkillName);
if (configureAspire && skillConfigurationError is not null)
{
InteractionService.DisplayError(skillConfigurationError);
return new(CliExitCodes.InvalidCommand, selectedClients, []);
}
// `mcpBinding` is only supplied by standalone `aspire agent init` (see s_mcpOption).
// Chained flows (`aspire new`, `aspire init`) never construct a binding for it, so MCP
// configuration is unreachable from those flows by construction rather than by a runtime
// visibility flag. The Aspire MCP server is the only server the CLI configures today, so
// this is a plain confirmation rather than a selection; the confirmed choice is applied to
// every selected configuration target.
var configureMcp = false;
if (mcpBinding is not null)
{
configureMcp = await InteractionService.PromptConfirmAsync(
AgentCommandStrings.InitCommand_ConfigureMcpServerPrompt,
binding: mcpBinding,
cancellationToken: cancellationToken);
}
var (scopeProvided, requestedScope) = scopeBinding.Resolve();
var scope = scopeProvided ? requestedScope : scopeBinding.DefaultValue;
if (!configureAspire && !playwright && !dotnetInspect && !configureMcp)
{
// Nothing is installed, so scope is not prompted for. The re-run still refreshes hooks for
// clients whose Aspire setup already exists at the resolved scope.
await ConfigureTelemetryHooksForAspireSetupAsync(selectedClients, [], workspaceRoot, scope, cancellationToken);
DisplayRequestedSkillCopiesKept(selectedClients, workspaceRoot, scope, removeSkillCopiesBinding, cancellationToken);
InteractionService.DisplaySubtleMessage(AgentCommandStrings.InitCommand_NoConfigurationSelected);
return new(CliExitCodes.Success, selectedClients, []);
}
if (!scopeProvided && _hostEnvironment.SupportsInteractiveInput)
{
scope = await InteractionService.PromptForSelectionAsync(
AgentCommandStrings.InitCommand_SelectScopePrompt,
new[] { AgentConfigurationScope.Project, AgentConfigurationScope.Global },
value => value is AgentConfigurationScope.Project
? AgentCommandStrings.InitCommand_ProjectScope
: AgentCommandStrings.InitCommand_GlobalScope,
cancellationToken: cancellationToken);
}
List<SkillDefinition> selectedSkills = [];
var hasErrors = false;
if (playwright)
{
selectedSkills.Add(SkillDefinition.PlaywrightCli);
}
if (dotnetInspect)
{
selectedSkills.Add(SkillDefinition.DotnetInspect);
}
// The selected clients determine destinations; defaults never fabricate detection.
var selectedSkillDirs = new HashSet<string>(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
if (selectedSkills.Count > 0)
{
selectedSkillDirs.UnionWith(selectedClients
.Select(client => client.GetSkillBaseDirectory(scope, workspaceRoot)));
}
IReadOnlyList<AgentTargetResult> registrationResults = [];
if (configureAspire)
{
cancellationToken.ThrowIfCancellationRequested();
registrationResults = await AgentConfiguration.ApplyRemoteAsync(selectedClients, workspaceRoot, scope, skillSources, cancellationToken);
var aspireSkillsReplaceCopies = AspireSkillsReplaceSkillCopies(registrationResults, selectedClients, workspaceRoot, scope);
var skillCopiesToRemove = aspireSkillsReplaceCopies
? FindSkillCopiesAtSelectedScope(selectedClients, workspaceRoot, scope, cancellationToken)
: [];
var deleteSkillCopies = skillCopiesToRemove.Length > 0 &&
await ConfirmSkillCopyDeletionAsync(skillCopiesToRemove, workspaceRoot, removeSkillCopiesBinding, cancellationToken);
var (removedSkillCopies, skillCopyFailures) = RemoveSkillCopies(deleteSkillCopies ? skillCopiesToRemove : [], workspaceRoot);
hasErrors |= DisplayRemoteConfigurationResults(registrationResults, workspaceRoot);
if (removedSkillCopies.Count > 0)
{
InteractionService.DisplayMessage(KnownEmojis.FileFolder, string.Format(CultureInfo.CurrentCulture,
AgentCommandStrings.InitCommand_RemovedSkillCopies, string.Join(", ", removedSkillCopies)));
}
else if (skillCopiesToRemove.Length > 0 && !deleteSkillCopies)
{
DisplaySkillCopiesKept(skillCopiesToRemove, workspaceRoot, explainPluginRequirement: false);
}
foreach (var failure in skillCopyFailures)
{
InteractionService.DisplayError(failure);
hasErrors = true;
}
if (!aspireSkillsReplaceCopies)
{
DisplayRequestedSkillCopiesKept(selectedClients, workspaceRoot, scope, removeSkillCopiesBinding, cancellationToken);
}
}
else
{
DisplayRequestedSkillCopiesKept(selectedClients, workspaceRoot, scope, removeSkillCopiesBinding, cancellationToken);
}
// --- Phase 3: Apply copied skill files at each unique destination ---
// Each skill file write is fast (small markdown files), so sequential execution
// is fine — parallelizing would complicate error handling for no meaningful gain.
var installedSkills = new List<InstalledSkillSummaryItem>();
foreach (var skillDirectory in selectedSkillDirs)
{
foreach (var skill in selectedSkills)
{
// Playwright CLI is installed via PlaywrightCliInstaller, not as a static skill file
if (!skill.HasInstallableFiles)
{
continue;
}
var installResult = await InstallSkillAsync(
skillDirectory,
skill,
cancellationToken);
if (installResult is not null)
{
installedSkills.Add(installResult);
}
else
{
hasErrors = true;
}
}
}
// --- Phase 4: Handle Playwright CLI (installs binary + mirrors skill files to registered directories) ---
if (selectedSkills.Contains(SkillDefinition.PlaywrightCli))
{
try
{
var (status, message, installedSkillDirectories) = await _playwrightCliInstaller.InstallSelectedAsync(selectedSkillDirs, cancellationToken);
switch (status)
{
case PlaywrightInstallStatus.Installed:
InteractionService.DisplayMessage(KnownEmojis.CheckMarkButton, AgentCommandStrings.InitCommand_InstalledPlaywrightCli);
break;
case PlaywrightInstallStatus.InstalledWithWarnings:
InteractionService.DisplayMessage(KnownEmojis.PoliceCarLight, message!);
break;
case PlaywrightInstallStatus.Failed:
InteractionService.DisplayError(message!);
hasErrors = true;
break;
case PlaywrightInstallStatus.Skipped:
// npm is not available — not an error, just informational.
InteractionService.DisplaySubtleMessage(AgentCommandStrings.InitCommand_PlaywrightCliSkipped);
break;
default:
throw new UnreachableException($"Unexpected PlaywrightInstallStatus: {status}");
}
installedSkills.AddRange(installedSkillDirectories.Select(directory =>
new InstalledSkillSummaryItem(SkillDefinition.PlaywrightCli.Name, directory)));
}
catch (InvalidOperationException ex)
{
InteractionService.DisplayError(ex.Message);
hasErrors = true;
}
InteractionService.DisplayEmptyLine();
}
DisplayInstalledSkillsSummary(installedSkills, scope, workspaceRoot);
// --- Phase 5: Apply MCP server configuration if the user confirmed ---
var mcpConfiguredClients = new List<IAgentClient>();
if (configureMcp)
{
var pathComparer = OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
// Aliased paths can use distinct server keys; coalesce file I/O, not client formats.
var targetsByPath = selectedClients.SelectMany(client =>
client.GetMcpConfigPaths(scope, workspaceRoot)
.Select(target => (Client: client, target.Path, target.ConfigureServer)))
.GroupBy(static target => target.Path, pathComparer);
foreach (var targets in targetsByPath)
{
var firstTarget = targets.First();
var description = string.Format(CultureInfo.CurrentCulture,
AgentCommandStrings.InitCommand_McpConfigurationDescription, firstTarget.Client.DisplayName, targets.Key);
try
{
var edit = new AgentConfiguration();
var (config, configFilePath) = await firstTarget.Client.ReadMcpConfigAsync(
targets.Key, workspaceRoot, scope, edit, cancellationToken);
var notifications = new List<(KnownEmoji Emoji, string Message)>();
// Legacy repairs share the same selection, scope, and consent as new configuration.
foreach (var (client, _, configureServer) in targets)
{
var (repaired, added) = client.UpdateMcpConfig(config, configFilePath, configureServer, scope);
if (repaired)
{
notifications.Add((KnownEmojis.Wrench,
string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.DeprecatedConfigUpdate_Description, client.DisplayName)));
}
if (added)
{
notifications.Add((KnownEmojis.CheckMarkButton, string.Format(CultureInfo.CurrentCulture,
AgentCommandStrings.InitCommand_McpConfigurationDescription, client.DisplayName, configFilePath)));
}
}
if (notifications.Count > 0)
{
await edit.PublishAsync(configFilePath, config, cancellationToken);
}
foreach (var (emoji, message) in notifications)
{
InteractionService.DisplayMessage(emoji, message);
}
// Repair-only targets don't add the Aspire server, so they don't count as configured.
mcpConfiguredClients.AddRange(targets
.Where(static target => target.ConfigureServer)
.Select(static target => target.Client));
}
catch (Exception ex) when (ex is InvalidOperationException or IOException or UnauthorizedAccessException)
{
InteractionService.DisplayError(ex.Message);
if (ex.InnerException is JsonException)
{
InteractionService.DisplaySubtleMessage(
string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.SkippedMalformedConfigFile, description));
}
hasErrors = true;
}
}
}
// --- Phase 6: Install agent telemetry hooks (default-on, parity with azure-skills) ---
// Setup at either scope registers one user-level hook per selected client. Hooks are never written
// to project configuration because Copilot runs hooks from every source, including a repository's
// .claude/settings.json, and ignores Claude's `if` filter. A project-level hook would launch the
// CLI on every matching tool call, or twice alongside the user-level hook. Whether telemetry is
// actually transmitted stays gated by the single ASPIRE_CLI_TELEMETRY_OPTOUT opt-out, which both
// the hook scripts and the `aspire agent telemetry` command path re-check at runtime.
// The hooks only report aspire@aspire-skills skills and Aspire MCP tool usage, so a client gets a
// hook only when this run registered that plugin or configured the Aspire MCP server for it at the
// requested scope, or either is already set up there. The latter keeps re-runs that skip both
// choices refreshing the hook. Selecting the aspire skill choice is not enough: skill sources can
// disable the default source or replace its plugins.
await ConfigureTelemetryHooksForAspireSetupAsync(
selectedClients,
GetAspireSkillsRegisteredClients(registrationResults, skillSources).Concat(mcpConfiguredClients).ToHashSet(),
workspaceRoot,
scope,
cancellationToken);
if (hasErrors)
{
InteractionService.DisplayMessage(KnownEmojis.PoliceCarLight, AgentCommandStrings.ConfigurationCompletedWithErrors);
}
else
{
InteractionService.DisplaySuccess(McpCommandStrings.InitCommand_ConfigurationComplete);
}
return new(
hasErrors ? CliExitCodes.InvalidCommand : CliExitCodes.Success,
selectedClients,
selectedSkills)
{
RegistrationResults = registrationResults,
SkillSources = skillSources
};
}
private async Task ConfigureTelemetryHooksForAspireSetupAsync(
IReadOnlyList<IAgentClient> selectedClients,
ICollection<IAgentClient> aspireConfiguredClients,
DirectoryInfo workspaceRoot,
AgentConfigurationScope scope,
CancellationToken cancellationToken)
{
var telemetryHookClients = new List<IAgentClient>();
foreach (var client in selectedClients)
{
// The configurator owns hook eligibility; the guard only avoids reading config it would ignore.
if (aspireConfiguredClients.Contains(client) ||
(client.SupportsTelemetryHooks && await HasExistingAspireSetupAsync(client, workspaceRoot, scope, cancellationToken)))
{
telemetryHookClients.Add(client);
}
}
if (telemetryHookClients.Count > 0)
{
await ConfigureTelemetryHooksAsync(telemetryHookClients, cancellationToken);
}
}
private static IEnumerable<IAgentClient> GetAspireSkillsRegisteredClients(
IReadOnlyList<AgentTargetResult> registrationResults,
IReadOnlyList<SkillSource> skillSources)
{
var registersAspireSkillsPlugin = skillSources.Any(static source =>
source.GetPluginNames().Contains(AspireSkillsRemoteConfiguration.PluginName, StringComparer.Ordinal));
if (!registersAspireSkillsPlugin)
{
return [];
}
return registrationResults
.Where(static result => result.Status is not AgentConfigurationStatus.Failed)
.SelectMany(static result => result.Clients);
}
private static async Task<bool> HasExistingAspireSetupAsync(
IAgentClient client, DirectoryInfo workspaceRoot, AgentConfigurationScope scope, CancellationToken cancellationToken)
{
// Invalid plugin settings report no registration, so a valid MCP registration is still found.
if (HasAspireSkillsRegistration(client, workspaceRoot, scope))
{
return true;
}
try
{
foreach (var (path, configureServer) in client.GetMcpConfigPaths(scope, workspaceRoot).Where(static target => target.ConfigureServer))
{
// Probe a discarded in-memory copy with the client's own update logic, so each client's
// server container and nesting rules apply. Nothing to add means the server already exists.
// This relies on UpdateMcpConfig only mutating the passed JsonObject; files are written
// only when an AgentConfiguration edit is published, and this one never is.
var (config, configFilePath) = await client.ReadMcpConfigAsync(
path, workspaceRoot, scope, new AgentConfiguration(), cancellationToken);
if (!client.UpdateMcpConfig(config, configFilePath, configureServer, scope).Added)
{
return true;
}
}
}
catch (Exception ex) when (IsUnreadableConfig(ex))
{
}
try
{
// Paths are enumerated lazily from directories that can change underneath us, so
// enumeration failures need the same best-effort handling as individual file reads.
foreach (var path in client.GetForwardedMcpConfigPaths(scope))
{
try
{
var config = await McpConfigFileHelper.ReadConfigAsync(
path, ConfigurationHelper.ParseOptions, new AgentConfiguration(), cancellationToken);
if (McpConfigFileHelper.GetServerContainer(config, "servers", path)?["aspire"] is JsonObject)
{
return true;
}
}
catch (Exception ex) when (IsUnreadableConfig(ex))
{
// One unreadable file must not hide a valid registration in another.
}
}
}
catch (Exception ex) when (IsUnreadableConfig(ex))
{
}
return false;
// Unreadable config is not evidence of Aspire setup, and hook installation is best effort.
static bool IsUnreadableConfig(Exception ex) =>
ex is InvalidOperationException or IOException or UnauthorizedAccessException;
}
private async Task ConfigureTelemetryHooksAsync(
IReadOnlyList<IAgentClient> clients,
CancellationToken cancellationToken)
{
IReadOnlyList<TelemetryHookResult> results;
try
{
results = await _telemetryHookConfigurator.ConfigureAsync(clients, cancellationToken);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// Hook installation is best-effort transparency tooling; never fail `agent init` over it.
// This deliberately catches everything except cancellation: besides file IO failures, a
// corrupted CLI build could surface a missing embedded hook script as an
// InvalidOperationException, and that must not abort the whole command either.
InteractionService.DisplaySubtleMessage(ex.Message);
return;
}
var configuredNames = results
.Where(result => result.Status is TelemetryHookStatus.Configured)
.Select(result => result.Client.DisplayName)
.ToList();
if (configuredNames.Count > 0)
{
InteractionService.DisplayMessage(
KnownEmojis.BarChart,
string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_TelemetryHooksInstalled, string.Join(", ", configuredNames)));
}
foreach (var result in results.Where(result => result.Status is not TelemetryHookStatus.Configured))
{
var clientName = result.Client.DisplayName;
var message = result.Status switch
{
TelemetryHookStatus.MalformedConfig => string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_TelemetryHookSkippedMalformedConfig, clientName),
TelemetryHookStatus.UnexpectedConfigShape => string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_TelemetryHookSkippedUnexpectedShape, clientName),
TelemetryHookStatus.WriteFailed => string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_TelemetryHookWriteFailed, clientName),
_ => throw new UnreachableException($"Unexpected telemetry hook status: {result.Status}"),
};
// Skips are surfaced to the user but never treated as command failures: a user-owned
// config we can't safely modify must not break `agent init`.
InteractionService.DisplaySubtleMessage(message);
}
}
/// <summary>
/// Extracts the single short sentence from a skill description so the selection prompt
/// stays readable.
/// </summary>
/// <remarks>
/// Bundle manifest descriptions can include a bold skill-type prefix followed by a
/// short tagline and additional usage guidance, for example:
/// "**WORKFLOW SKILL** - Top-level router for Aspire 13.4 distributed apps. Detects the AppHost. USE FOR: ..."
/// This trims the prefix and returns only the first sentence. Inputs without the prefix
/// or sentence terminator are returned trimmed-but-otherwise-unchanged so CLI-defined
/// short descriptions are preserved as-is.
/// </remarks>
internal static string SimplifyDescription(string description)
{
if (string.IsNullOrWhiteSpace(description))
{
return description;
}
var simplified = description.Trim();
// Strip the leading bold "TYPE SKILL" prefix when present, and only then strip the
// separator characters that typically follow it. Gating the separator strip on the
// prefix match avoids silently mutating descriptions that legitimately start with
// a dash, em-dash, or colon (e.g. "-mode flag explained" or ":memo notes").
var strippedBoldPrefix = false;
if (simplified.StartsWith("**", StringComparison.Ordinal))
{
var endBold = simplified.IndexOf("**", 2, StringComparison.Ordinal);
if (endBold > 0)
{
simplified = simplified[(endBold + 2)..].TrimStart();
strippedBoldPrefix = true;
}
}
if (strippedBoldPrefix)
{
// Separators that typically follow the bold prefix (" - ", " — ", " – ", ": ").
while (simplified.Length > 0 && simplified[0] is '-' or '\u2013' or '\u2014' or ':')
{
simplified = simplified[1..].TrimStart();
}
}
// Return up to and including the first sentence-ending punctuation followed by
// whitespace or end-of-string. This avoids splitting on inline punctuation such
// as "13.4" or "github.com" inside the first sentence.
for (var i = 0; i < simplified.Length; i++)
{
if (simplified[i] is '.' or '!' or '?'
&& (i + 1 >= simplified.Length || char.IsWhiteSpace(simplified[i + 1])))
{
return simplified[..(i + 1)];
}
}
return simplified;
}
/// <summary>
/// Installs the files for a skill at the specified location, creating or updating them as needed.
/// </summary>
private async Task<InstalledSkillSummaryItem?> InstallSkillAsync(
string skillBaseDirectory,
SkillDefinition skill,
CancellationToken cancellationToken)
{
var fullSkillDirectoryPath = Path.Combine(skillBaseDirectory, skill.Name);
try
{
var skillContent = skill.SkillContent ??
throw new InvalidOperationException($"Skill '{skill.Name}' does not define installable files.");
var fullPath = Path.Combine(fullSkillDirectoryPath, "SKILL.md");
var directory = Path.GetDirectoryName(fullPath);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
if (File.Exists(fullPath))
{
var existingContent = await File.ReadAllTextAsync(fullPath, cancellationToken);
if (string.Equals(existingContent.ReplaceLineEndings("\n"), skillContent.ReplaceLineEndings("\n"), StringComparison.Ordinal))
{
return new(skill.Name, skillBaseDirectory);
}
}
await File.WriteAllTextAsync(fullPath, skillContent, cancellationToken);
return new(skill.Name, skillBaseDirectory);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException)
{
InteractionService.DisplayError(
string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_FailedToInstallSkill, skill.Name, fullSkillDirectoryPath, ex.Message));
return null;
}
}
private void DisplayInstalledSkillsSummary(IReadOnlyList<InstalledSkillSummaryItem> installedSkills, AgentConfigurationScope scope, DirectoryInfo workspaceRoot)
{
if (installedSkills.Count == 0)
{
return;
}
var lines = new List<string> { AgentCommandStrings.InitCommand_InstalledSkillsSummary };
lines.Add($" {string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_InstalledSkillsSummarySkills,
string.Join(", ", installedSkills.Select(static skill => skill.SkillName).Distinct(StringComparer.Ordinal)))}");
var locations = new List<string>();
var hasSharedLocation = false;
foreach (var directory in installedSkills.Select(static skill => skill.Directory).Distinct(StringComparers.FileSystemPath))
{
var clients = _clients.Where(client =>
StringComparers.FileSystemPath.Equals(directory, client.GetSkillBaseDirectory(scope, workspaceRoot)))
.ToArray();
hasSharedLocation |= clients.Length > 1;
locations.Add(string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_LocationWithAgents,
AgentPath.GetDisplayPath(directory, scope, workspaceRoot, ExecutionContext),
string.Join(", ", clients.Select(static client => client.DisplayName))));
}
lines.Add($" {string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_InstalledSkillsSummaryLocations,
string.Join(", ", locations))}");
var message = string.Join(Environment.NewLine, lines.Select(static line => line.EscapeMarkup()));
if (hasSharedLocation)
{
message += $"{Environment.NewLine} [dim]{AgentCommandStrings.InitCommand_SharedLocationNotice.EscapeMarkup()}[/]";
}
InteractionService.DisplayMessage(KnownEmojis.Robot, message, allowMarkup: true);
InteractionService.DisplayEmptyLine();
}
private bool DisplayRemoteConfigurationResults(IReadOnlyList<AgentTargetResult> results, DirectoryInfo workspaceRoot)
{
var hasErrors = false;
foreach (var resultGroup in results.GroupBy(result => result.Status switch
{
AgentConfigurationStatus.Configured or AgentConfigurationStatus.Unchanged => false,
AgentConfigurationStatus.Failed => true,
_ => throw new UnreachableException()
}))
{
if (resultGroup.Key)
{
var failedTargets = resultGroup.SelectMany(result => result.Clients, (result, client) =>
{
var target = string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_ConfigurationTarget,
client.DisplayName, AgentPath.GetDisplayPath(result.TargetPath, workspaceRoot, ExecutionContext));
return result.Message is null ? target : $"{target}{Environment.NewLine} {result.Message}";
});
InteractionService.DisplayError(string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_FailedTarget,
string.Join($"{Environment.NewLine} ", failedTargets)));
InteractionService.DisplayEmptyLine();
hasErrors = true;
continue;
}
var targets = resultGroup.Select(result =>
string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_LocationWithAgents,
AgentPath.GetDisplayPath(result.TargetPath, workspaceRoot, ExecutionContext),
string.Join(", ", result.Clients.Select(static client => client.DisplayName))));
var message = string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_ConfiguredTargets,
string.Join(", ", targets));
InteractionService.DisplayMessage(KnownEmojis.Robot, message);
}
return hasErrors;
}
private static bool AspireSkillsReplaceSkillCopies(IReadOnlyList<AgentTargetResult> registrationResults,
IReadOnlyList<IAgentClient> selectedClients, DirectoryInfo workspaceRoot, AgentConfigurationScope scope)
{
// The saved configuration proves the replacement lives at the selected scope, but a local or managed
// settings file can still disable it, so the merged settings must enable it too.
return !registrationResults.Any(static result => result.Status is AgentConfigurationStatus.Failed) &&
selectedClients.All(client => registrationResults.Any(result =>
result.Clients.Contains(client) && result.Configuration is { } configuration &&
ConfigurationContainsAspireSkills(client, configuration)) &&
HasAspireSkillsRegistration(client, workspaceRoot, scope));
}
private string[] FindSkillCopiesAtSelectedScope(IReadOnlyList<IAgentClient> selectedClients, DirectoryInfo workspaceRoot,
AgentConfigurationScope scope, CancellationToken cancellationToken)
=> LocalAspireSkills.Find(ExecutionContext.WorkingDirectory, workspaceRoot, ExecutionContext.HomeDirectory, cancellationToken)
.Where(copy => copy.Scope == scope && selectedClients.Any(client =>
copy.Owners.Contains(client.Id, StringComparers.AgentClientId)))
.Select(copy => copy.Directory)
.ToArray();
// Copies are only removed once the Aspire skills plugin replaces them. When --remove-skill-copies
// was passed but that did not happen, report the kept copies instead of ignoring the request silently.
private void DisplayRequestedSkillCopiesKept(IReadOnlyList<IAgentClient> selectedClients, DirectoryInfo workspaceRoot,
AgentConfigurationScope scope, PromptBinding<bool> removeSkillCopiesBinding, CancellationToken cancellationToken)
{
if (removeSkillCopiesBinding.Resolve() is not (true, true))
{
return;
}
var skillDirectories = FindSkillCopiesAtSelectedScope(selectedClients, workspaceRoot, scope, cancellationToken);
if (skillDirectories.Length > 0)
{
DisplaySkillCopiesKept(skillDirectories, workspaceRoot, explainPluginRequirement: true);
}
}
private void DisplaySkillCopiesKept(IEnumerable<string> skillDirectories, DirectoryInfo workspaceRoot, bool explainPluginRequirement)
{
var kept = string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_KeptSkillCopies,
string.Join(", ", skillDirectories.Select(directory => AgentPath.GetDisplayPath(directory, workspaceRoot, ExecutionContext))));
InteractionService.DisplayMessage(KnownEmojis.FileFolder, string.Join(Environment.NewLine,
[
kept.EscapeMarkup(),
.. explainPluginRequirement
? [$"[dim]{AgentCommandStrings.InitCommand_SkillCopiesRequirePlugin.EscapeMarkup()}[/]"]
: Array.Empty<string>()
]), allowMarkup: true);
}
private IEnumerable<string> FormatSkillCopyFolders(IEnumerable<string> skillDirectories, DirectoryInfo workspaceRoot)
=> skillDirectories.Select(directory =>
$" {AgentPath.GetDisplayPath(directory, workspaceRoot, ExecutionContext).EscapeMarkup()}");
private async Task<bool> ConfirmSkillCopyDeletionAsync(IReadOnlyList<string> skillDirectories, DirectoryInfo workspaceRoot,
PromptBinding<bool> removeSkillCopiesBinding, CancellationToken cancellationToken)
{
var (wasProvided, removeSkillCopies) = removeSkillCopiesBinding.Resolve();
if (wasProvided)
{
return removeSkillCopies;
}
// The copies can contain user edits, so only an explicit option or an interactive answer
// authorizes recursively deleting them.
if (!_hostEnvironment.SupportsInteractiveInput)
{
return false;
}
InteractionService.DisplayMessage(KnownEmojis.PoliceCarLight, string.Join(Environment.NewLine,
[
$"[yellow]{AgentCommandStrings.InitCommand_SkillCopiesFound.EscapeMarkup()}[/]",
.. FormatSkillCopyFolders(skillDirectories, workspaceRoot)
]), allowMarkup: true);
var prompt = skillDirectories.Count == 1
? AgentCommandStrings.InitCommand_DeleteSkillCopyPrompt
: string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_DeleteSkillCopiesPrompt, skillDirectories.Count);
return await InteractionService.PromptConfirmAsync(prompt, removeSkillCopiesBinding, cancellationToken);
}
private (List<string> Removed, List<string> Failures) RemoveSkillCopies(IReadOnlyList<string> skillDirectories, DirectoryInfo workspaceRoot)
{
List<string> removed = [];
List<string> failures = [];
foreach (var skillDirectory in skillDirectories)
{
var displayPath = AgentPath.GetDisplayPath(skillDirectory, workspaceRoot, ExecutionContext);
try
{
if (IsBehindLink(new DirectoryInfo(skillDirectory), workspaceRoot))
{
failures.Add(string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_RemoveSkillCopyFailed,
displayPath, AgentCommandStrings.InitCommand_SkillCopyBehindLink));
continue;
}
Directory.Delete(skillDirectory, recursive: true);
removed.Add(displayPath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
failures.Add(string.Format(CultureInfo.CurrentCulture, AgentCommandStrings.InitCommand_RemoveSkillCopyFailed,
displayPath, ex.Message));
}
}
return (removed, failures);
}
private static bool ConfigurationContainsAspireSkills(IAgentClient client, JsonObject configuration)
{
if (client.Id == OpenCodeAgentClient.ClientId)
{
try
{
return AspireSkillsRemoteConfiguration.HasOpenCodeCatalog(configuration, [SkillSource.BuiltIn]);
}
catch (Exception ex) when (ex is InvalidOperationException or ArgumentException)
{
return false;
}
}
return configuration["enabledPlugins"] is JsonObject plugins &&
plugins[AspireSkillsRemoteConfiguration.PluginName] is JsonValue enabled &&
enabled.TryGetValue<bool>(out var isEnabled) && isEnabled;
}
private static bool HasAspireSkillsRegistration(IAgentClient client, DirectoryInfo workspaceRoot,
AgentConfigurationScope scope)
{
try
{
// Configured sources can enable unrelated plugins that would not replace the copied Aspire skills.
return client.HasIntegrationRegistration(workspaceRoot, scope, [SkillSource.BuiltIn]);
}
catch (Exception ex) when (ex is JsonException or InvalidOperationException or IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
// Unreadable settings cannot prove the agent still has Aspire skills, so keep the copies.
return false;
}
}
// Discovery follows links, so a copy reached through a linked folder (for example
// .agents/skills -> ~/shared-skills) lives outside the workspace or profile, and deleting it
// would remove files other tools share. Only directories below the workspace root or profile
// are checked because those roots themselves are commonly links (for example a mapped drive).
private bool IsBehindLink(DirectoryInfo directory, DirectoryInfo workspaceRoot)
{
for (var current = directory; current is not null; current = current.Parent)
{
if (IsSamePath(current.FullName, workspaceRoot.FullName) ||
IsSamePath(current.FullName, ExecutionContext.HomeDirectory.FullName))
{
return false;
}
if (current.LinkTarget is not null)
{
return true;
}
}
return false;
static bool IsSamePath(string left, string right) =>
StringComparers.FileSystemPath.Equals(Path.TrimEndingDirectorySeparator(left), Path.TrimEndingDirectorySeparator(right));
}
private sealed record InstalledSkillSummaryItem(string SkillName, string Directory);
}
internal readonly record struct AgentInitExecutionResult(
int ExitCode,
IReadOnlyList<IAgentClient> SelectedClients,
IReadOnlyList<SkillDefinition> SelectedSkills)
{
public IReadOnlyList<AgentTargetResult> RegistrationResults { get; init; } = [];
public IReadOnlyList<SkillSource> SkillSources { get; init; } = [];
}