Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Copyright (c) Microsoft. All rights reserved.

using System;
using System.Globalization;
using System.Text.RegularExpressions;

namespace Microsoft.Agents.AI.GitHub.Copilot;

/// <summary>
/// Checks that the GitHub Copilot CLI in use meets the minimum supported version.
/// </summary>
internal static partial class CopilotCliVersionGuard
{
/// <summary>The minimum supported GitHub Copilot CLI version.</summary>
internal static readonly Version MinimumVersion = new(1, 0, 85);

// Only the leading major.minor.patch is compared; any suffix is ignored,
// so prerelease builds such as "1.0.85-3" count as 1.0.85.
[GeneratedRegex(@"^\s*v?(\d+)\.(\d+)\.(\d+)", RegexOptions.CultureInvariant)]
private static partial Regex VersionPrefixRegex();

/// <summary>
/// Reads the leading <c>major.minor.patch</c> from a version string.
/// </summary>
/// <param name="version">The version string reported by the CLI.</param>
/// <returns>The parsed version, or <see langword="null"/> if it could not be read.</returns>
internal static Version? Parse(string? version)
{
if (version is null)
{
return null;
}

Match match = VersionPrefixRegex().Match(version);
if (!match.Success
|| !int.TryParse(match.Groups[1].Value, NumberStyles.None, CultureInfo.InvariantCulture, out int major)
|| !int.TryParse(match.Groups[2].Value, NumberStyles.None, CultureInfo.InvariantCulture, out int minor)
|| !int.TryParse(match.Groups[3].Value, NumberStyles.None, CultureInfo.InvariantCulture, out int patch))
{
return null;
}

return new Version(major, minor, patch);
}

/// <summary>
/// Throws if the given CLI version is older than <see cref="MinimumVersion"/> or could not be read.
/// </summary>
/// <param name="version">The version string reported by the CLI.</param>
/// <exception cref="InvalidOperationException">The version is unsupported or could not be read.</exception>
internal static void EnsureSupported(string? version)
{
Version? parsed = Parse(version);
if (parsed is null || parsed < MinimumVersion)
{
throw new InvalidOperationException(
$"GitHub Copilot CLI version {MinimumVersion} or higher is required, but version '{version}' was detected.");
}
}

/// <summary>
/// Creates the error used when the CLI version could not be determined.
/// </summary>
/// <param name="innerException">The error raised while reading the version.</param>
/// <returns>The exception to throw.</returns>
internal static InvalidOperationException CreateUndeterminedVersionException(Exception innerException) =>
new($"GitHub Copilot CLI version {MinimumVersion} or higher is required, but the version could not be determined.", innerException);
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ public sealed class GitHubCopilotAgent : AIAgent, IAsyncDisposable
private readonly bool _ownsClient;
private readonly JsonSerializerOptions _jsonSerializerOptions;
private readonly ILogger _logger;
private readonly SemaphoreSlim _startLock = new(1, 1);
private volatile bool _cliVersionChecked;

/// <summary>
/// Initializes a new instance of the <see cref="GitHubCopilotAgent"/> class.
Expand All @@ -58,6 +60,10 @@ public sealed class GitHubCopilotAgent : AIAgent, IAsyncDisposable
/// <c>SessionConfig.OnPermissionRequest</c>) and defers all other tools. If the caller supplies their own
/// <c>OnPreToolUse</c> hook, it takes precedence and the caller is fully responsible for approval handling; in that
/// case a warning is logged for any approval-required tool that will not be automatically gated.
/// <para>
/// GitHub Copilot CLI version 1.0.85 or higher is required. The version is checked the first time the agent runs,
/// and an <see cref="InvalidOperationException"/> is thrown if it is older or cannot be determined.
/// </para>
/// </remarks>
public GitHubCopilotAgent(
CopilotClient copilotClient,
Expand Down Expand Up @@ -97,6 +103,10 @@ public GitHubCopilotAgent(
/// When a tool wrapped in <see cref="ApprovalRequiredAIFunction"/> is registered, the agent installs a default
/// <c>Hooks.OnPreToolUse</c> handler that returns <c>"ask"</c> for those tools (routing the decision to
/// <c>SessionConfig.OnPermissionRequest</c>) and defers all other tools.
/// <para>
/// GitHub Copilot CLI version 1.0.85 or higher is required. The version is checked the first time the agent runs,
/// and an <see cref="InvalidOperationException"/> is thrown if it is older or cannot be determined.
/// </para>
/// </remarks>
public GitHubCopilotAgent(
CopilotClient copilotClient,
Expand Down Expand Up @@ -303,11 +313,71 @@ public async ValueTask DisposeAsync()
{
await this._copilotClient.DisposeAsync().ConfigureAwait(false);
}

this._startLock.Dispose();
}

private async Task EnsureClientStartedAsync(CancellationToken cancellationToken)
{
await this._copilotClient.StartAsync(cancellationToken).ConfigureAwait(false);
if (this._cliVersionChecked)
{
await this._copilotClient.StartAsync(cancellationToken).ConfigureAwait(false);
return;
}

// Only one start and version check may run at a time, so a failed check can't stop a client
// that another concurrent run has already accepted.
await this._startLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
await this._copilotClient.StartAsync(cancellationToken).ConfigureAwait(false);

if (this._cliVersionChecked)
{
return;
}

try
{
string? version;
try
{
GetStatusResponse status = await this._copilotClient.GetStatusAsync(cancellationToken).ConfigureAwait(false);
version = status?.Version;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
throw CopilotCliVersionGuard.CreateUndeterminedVersionException(ex);
}

CopilotCliVersionGuard.EnsureSupported(version);
}
catch (InvalidOperationException) when (this._ownsClient)
{
await this.StopOwnedClientAfterFailedCheckAsync().ConfigureAwait(false);
throw;
}

// Only a successful check is remembered, so a failed check is repeated on the next run.
this._cliVersionChecked = true;
}
finally
{
this._startLock.Release();
}
}

private async Task StopOwnedClientAfterFailedCheckAsync()
{
try
{
await this._copilotClient.StopAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
// Keep the original version check error; a failure to stop is only logged.
this._logger.LogFailedToStopClientAfterVersionCheck(ex);
}
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Copyright (c) Microsoft. All rights reserved.

using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Logging;

Expand Down Expand Up @@ -28,4 +29,14 @@ public static partial void LogApprovalGatingSkippedDueToCustomHook(
this ILogger logger,
int count,
string tools);

/// <summary>
/// Logs when stopping an owned Copilot client fails after the Copilot CLI version check failed.
/// </summary>
[LoggerMessage(
Level = LogLevel.Debug,
Message = "Failed to stop the GitHub Copilot client after the Copilot CLI version check failed.")]
public static partial void LogFailedToStopClientAfterVersionCheck(
this ILogger logger,
Exception exception);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright (c) Microsoft. All rights reserved.

using System;

namespace Microsoft.Agents.AI.GitHub.Copilot.UnitTests;

/// <summary>
/// Unit tests for the <see cref="CopilotCliVersionGuard"/> class.
/// </summary>
public sealed class CopilotCliVersionGuardTests
{
[Theory]
[InlineData("1.0.85")]
[InlineData("1.0.85-3")]
[InlineData("1.0.90-0.unstable.abc")]
[InlineData("v1.0.106")]
[InlineData("2.0.0")]
public void EnsureSupported_WithSupportedVersion_DoesNotThrow(string version)
{
// Act & Assert
CopilotCliVersionGuard.EnsureSupported(version);
}

[Theory]
[InlineData("1.0.64")]
[InlineData("1.0.84")]
[InlineData("0.9.999")]
[InlineData("dev")]
[InlineData("")]
[InlineData(null)]
public void EnsureSupported_WithUnsupportedOrUnreadableVersion_Throws(string? version)
{
// Act
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(
() => CopilotCliVersionGuard.EnsureSupported(version));

// Assert
Assert.Contains("1.0.85 or higher is required", exception.Message);
Assert.Contains($"'{version}'", exception.Message);
}

[Fact]
public void CreateUndeterminedVersionException_KeepsInnerException()
{
// Arrange
Exception inner = new InvalidOperationException("not connected");

// Act
InvalidOperationException exception = CopilotCliVersionGuard.CreateUndeterminedVersionException(inner);

// Assert
Assert.Contains("version could not be determined", exception.Message);
Assert.Same(inner, exception.InnerException);
}
}
4 changes: 4 additions & 0 deletions python/packages/github_copilot/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ pip install agent-framework-github-copilot

The GitHub Copilot agent enables integration with GitHub Copilot, allowing you to interact with Copilot's agentic capabilities through the Agent Framework.

The agent requires GitHub Copilot CLI version 1.0.85 or higher. When the agent starts, it checks the CLI version
and raises an error if the version is older or cannot be determined. This applies to the CLI bundled with the
`github-copilot-sdk` package as well as one selected with `cli_path`, `GITHUB_COPILOT_CLI_PATH`, or `COPILOT_CLI_PATH`.

## Context providers and function middleware

Context providers can contribute messages, instructions, and tools to a run.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import inspect
import json
import logging
import re
import sys
import warnings
import weakref
Expand Down Expand Up @@ -188,6 +189,36 @@ async def _resolve_function_approval(

logger = logging.getLogger("agent_framework.github_copilot")

# Minimum supported Copilot CLI runtime version.
_MIN_COPILOT_CLI_VERSION = (1, 0, 85)
_VERSION_PREFIX = re.compile(r"^\s*v?(\d+)\.(\d+)\.(\d+)")


def _parse_cli_version(version: object) -> tuple[int, int, int] | None:
"""Parse the leading ``major.minor.patch`` of a CLI version, ignoring any suffix."""
if not isinstance(version, str):
return None
match = _VERSION_PREFIX.match(version)
if match is None:
return None
return int(match.group(1)), int(match.group(2)), int(match.group(3))


async def _ensure_supported_cli_version(client: CopilotClient) -> None:
"""Raise ``AgentException`` unless the connected Copilot CLI meets the minimum version."""
minimum = ".".join(str(part) for part in _MIN_COPILOT_CLI_VERSION)
try:
version: object = (await client.get_status()).version
except Exception as ex:
raise AgentException(
f"GitHub Copilot CLI version {minimum} or higher is required, but the version could not be determined."
) from ex
parsed = _parse_cli_version(version)
if parsed is None or parsed < _MIN_COPILOT_CLI_VERSION:
raise AgentException(
f"GitHub Copilot CLI version {minimum} or higher is required, but version '{version}' was detected."
)


def _provider_service_session_state_keys(agent: object, client: object | None) -> frozenset[str]:
"""Return provider-owned session-state keys declared by the Copilot agent or client."""
Expand Down Expand Up @@ -713,6 +744,7 @@ def __init__(
# are forwarded verbatim to the Copilot SDK by _build_session_kwargs.
self._default_options = opts
self._started = False
self._start_lock = asyncio.Lock()
self._file_hooks_warning_emitted = False

async def __aenter__(self) -> Self:
Expand All @@ -732,35 +764,51 @@ async def start(self) -> None:
agent as an async context manager.

Raises:
AgentException: If the client fails to start.
AgentException: If the client fails to start or the Copilot CLI is older than the
minimum supported version.
"""
if self._started:
return

if self._client is None:
cli_path = self._settings.get("cli_path") or None
log_level = self._settings.get("log_level") or None
base_directory = self._settings.get("base_directory") or None
telemetry = self._settings.get("telemetry") or None
if isinstance(telemetry, str):
telemetry = _parse_telemetry_config(telemetry)

client_kwargs: dict[str, Any] = {}
if cli_path:
client_kwargs["connection"] = RuntimeConnection.for_stdio(path=cli_path)
if log_level:
client_kwargs["log_level"] = log_level
if base_directory:
client_kwargs["base_directory"] = base_directory
if telemetry:
client_kwargs["telemetry"] = telemetry
self._client = CopilotClient(**client_kwargs)
# Only one start may run at a time, so a failed check can't stop a client that another
# concurrent start has already accepted.
async with self._start_lock:
if self._started:
return

if self._client is None:
cli_path = self._settings.get("cli_path") or None
log_level = self._settings.get("log_level") or None
base_directory = self._settings.get("base_directory") or None
telemetry = self._settings.get("telemetry") or None
if isinstance(telemetry, str):
telemetry = _parse_telemetry_config(telemetry)

client_kwargs: dict[str, Any] = {}
if cli_path:
client_kwargs["connection"] = RuntimeConnection.for_stdio(path=cli_path)
if log_level:
client_kwargs["log_level"] = log_level
if base_directory:
client_kwargs["base_directory"] = base_directory
if telemetry:
client_kwargs["telemetry"] = telemetry
self._client = CopilotClient(**client_kwargs)

try:
await self._client.start()
except Exception as ex:
raise AgentException(f"Failed to start GitHub Copilot client: {ex}") from ex

try:
await _ensure_supported_cli_version(self._client)
except BaseException:
if self._owns_client:
with contextlib.suppress(Exception):
await self._client.stop()
raise

try:
await self._client.start()
self._started = True
except Exception as ex:
raise AgentException(f"Failed to start GitHub Copilot client: {ex}") from ex

async def stop(self) -> None:
"""Stop the Copilot client and clean up resources.
Expand Down
Loading
Loading