using System.Collections; using GitHub.Copilot.SDK; namespace Kopaya.AgentHost.Services; internal static class CopilotCliPathResolver { private const string CopilotCommandName = "copilot"; private const string DefaultWindowsPathExtensions = ".COM;.EXE;.BAT;.CMD"; private static readonly string[] BlockedCliEnvironmentPrefixes = ["BUN_", "COPILOT_", "ELECTRON_", "NODE_", "NPM_"]; public static CopilotClientOptions CreateClientOptions() { return CreateClientOptions(ResolveCliContext()); } internal static CopilotCliContext ResolveCliContext() { string? cliPath = Resolve( Environment.GetEnvironmentVariable("PATH"), Environment.GetEnvironmentVariable("PATHEXT"), OperatingSystem.IsWindows(), File.Exists); if (string.IsNullOrWhiteSpace(cliPath)) { throw new InvalidOperationException( "Kopaya requires the system-installed 'copilot' command on PATH. Install the GitHub Copilot CLI and ensure it is available in the current environment."); } CopilotCliLaunch launch = ResolveCliLaunch( cliPath, OperatingSystem.IsWindows(), Environment.GetEnvironmentVariable("ComSpec")); return new CopilotCliContext( cliPath, launch.Path, launch.Args, ResolveCliEnvironment(GetCurrentEnvironmentVariables())); } internal static CopilotClientOptions CreateClientOptions(CopilotCliContext context) { ArgumentNullException.ThrowIfNull(context); return new CopilotClientOptions { CliPath = context.LaunchPath, CliArgs = context.LaunchArgs, Environment = context.Environment, }; } internal static string? Resolve( string? pathValue, string? pathExtValue, bool isWindows, Func fileExists) { ArgumentNullException.ThrowIfNull(fileExists); return ResolveCliPath(pathValue, pathExtValue, isWindows, fileExists); } internal static IReadOnlyDictionary ResolveCliEnvironment( IEnumerable> environmentVariables) { ArgumentNullException.ThrowIfNull(environmentVariables); Dictionary sanitizedEnvironment = new(StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair entry in environmentVariables) { if (string.IsNullOrWhiteSpace(entry.Key) || entry.Value is null) { continue; } string normalizedKey = entry.Key.ToUpperInvariant(); if (BlockedCliEnvironmentPrefixes.Any(prefix => normalizedKey.StartsWith(prefix, StringComparison.Ordinal))) { continue; } sanitizedEnvironment[entry.Key] = entry.Value; } return sanitizedEnvironment; } internal static CopilotCliLaunch ResolveCliLaunch(string cliPath, bool isWindows, string? commandProcessorPath) { ArgumentException.ThrowIfNullOrWhiteSpace(cliPath); if (!isWindows) { return new CopilotCliLaunch(cliPath, []); } string launchPath = string.IsNullOrWhiteSpace(commandProcessorPath) ? "cmd.exe" : commandProcessorPath; return new CopilotCliLaunch( launchPath, ["/d", "/s", "/c", CopilotCommandName]); } private static string? ResolveCliPath( string? pathValue, string? pathExtValue, bool isWindows, Func fileExists) { if (string.IsNullOrWhiteSpace(pathValue)) { return null; } StringComparer comparer = isWindows ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; foreach (string directory in pathValue .Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .Select(segment => segment.Trim('"')) .Where(segment => !string.IsNullOrWhiteSpace(segment)) .Distinct(comparer)) { foreach (string candidateName in GetCandidateFileNames(pathExtValue, isWindows)) { string candidatePath = Path.Combine(directory, candidateName); if (fileExists(candidatePath)) { return candidatePath; } } } return null; } private static IEnumerable GetCandidateFileNames(string? pathExtValue, bool isWindows) { yield return CopilotCommandName; if (!isWindows) { yield break; } HashSet yielded = new(StringComparer.OrdinalIgnoreCase) { CopilotCommandName, }; string extensions = string.IsNullOrWhiteSpace(pathExtValue) ? DefaultWindowsPathExtensions : pathExtValue; foreach (string extension in extensions .Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .Where(extension => extension.StartsWith('.'))) { string candidateName = CopilotCommandName + extension; if (yielded.Add(candidateName)) { yield return candidateName; } } } private static IEnumerable> GetCurrentEnvironmentVariables() { return Environment.GetEnvironmentVariables() .Cast() .Select(entry => new KeyValuePair( entry.Key?.ToString() ?? string.Empty, entry.Value?.ToString())); } } internal sealed record CopilotCliContext( string CliPath, string LaunchPath, string[] LaunchArgs, IReadOnlyDictionary Environment); internal sealed record CopilotCliLaunch(string Path, string[] Args);