Files
aryx/sidecar/src/Kopaya.AgentHost/Services/CopilotCliPathResolver.cs
T

166 lines
5.4 KiB
C#

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()
{
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 CopilotClientOptions
{
CliPath = launch.Path,
CliArgs = launch.Args,
Environment = ResolveCliEnvironment(GetCurrentEnvironmentVariables()),
};
}
internal static string? Resolve(
string? pathValue,
string? pathExtValue,
bool isWindows,
Func<string, bool> fileExists)
{
ArgumentNullException.ThrowIfNull(fileExists);
return ResolveCliPath(pathValue, pathExtValue, isWindows, fileExists);
}
internal static IReadOnlyDictionary<string, string> ResolveCliEnvironment(
IEnumerable<KeyValuePair<string, string?>> environmentVariables)
{
ArgumentNullException.ThrowIfNull(environmentVariables);
Dictionary<string, string> sanitizedEnvironment = new(StringComparer.OrdinalIgnoreCase);
foreach (KeyValuePair<string, string?> 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<string, bool> 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<string> GetCandidateFileNames(string? pathExtValue, bool isWindows)
{
yield return CopilotCommandName;
if (!isWindows)
{
yield break;
}
HashSet<string> 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<KeyValuePair<string, string?>> GetCurrentEnvironmentVariables()
{
return Environment.GetEnvironmentVariables()
.Cast<DictionaryEntry>()
.Select(entry => new KeyValuePair<string, string?>(
entry.Key?.ToString() ?? string.Empty,
entry.Value?.ToString()));
}
}
internal sealed record CopilotCliLaunch(string Path, string[] Args);