-
Notifications
You must be signed in to change notification settings - Fork 967
feat: add async context manager support for CopilotClient and Copilot… #475
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Sumanth007
wants to merge
5
commits into
github:main
Choose a base branch
from
Sumanth007:feat/async-context-manager
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+210
−9
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
9f9d54e
feat: add async context manager support for CopilotClient and Copilot…
Sumanth007 7621015
fix: improve cleanup error handling in CopilotClient and CopilotSession
Sumanth007 ee8f235
fix: update model version in README and improve context manager tests…
Sumanth007 542be3f
fix: improve cleanup error handling in CopilotClient and CopilotSessi…
Sumanth007 0aeb747
fix: update async context manager exit methods to return None for exc…
Sumanth007 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -22,7 +22,8 @@ | |||||
| from collections.abc import Callable | ||||||
| from dataclasses import asdict, is_dataclass | ||||||
| from pathlib import Path | ||||||
| from typing import Any, cast | ||||||
| from types import TracebackType | ||||||
| from typing import Any, Optional, cast | ||||||
|
|
||||||
| from .generated.rpc import ServerRpc | ||||||
| from .generated.session_events import session_event_from_dict | ||||||
|
|
@@ -212,6 +213,38 @@ def __init__(self, options: CopilotClientOptions | None = None): | |||||
| self._lifecycle_handlers_lock = threading.Lock() | ||||||
| self._rpc: ServerRpc | None = None | ||||||
|
|
||||||
| async def __aenter__(self) -> "CopilotClient": | ||||||
| """ | ||||||
| Enter the async context manager. | ||||||
|
|
||||||
| Automatically starts the CLI server and establishes a connection if not | ||||||
| already connected. | ||||||
|
|
||||||
| Returns: | ||||||
| The CopilotClient instance. | ||||||
|
|
||||||
| Example: | ||||||
| >>> async with CopilotClient() as client: | ||||||
| ... session = await client.create_session() | ||||||
| ... await session.send({"prompt": "Hello!"}) | ||||||
| """ | ||||||
| await self.start() | ||||||
| return self | ||||||
|
|
||||||
| async def __aexit__( | ||||||
| self, | ||||||
| exc_type: Optional[type[BaseException]], | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please use Python 3.11+ type annotation syntax and set default values, e.g.:
Suggested change
|
||||||
| exc_val: Optional[BaseException], | ||||||
| exc_tb: Optional[TracebackType], | ||||||
| ) -> None: | ||||||
| """ | ||||||
| Exit the async context manager. | ||||||
|
|
||||||
| Performs graceful cleanup by destroying all active sessions and stopping | ||||||
| the CLI server. | ||||||
| """ | ||||||
| await self.stop() | ||||||
|
|
||||||
| @property | ||||||
| def rpc(self) -> ServerRpc: | ||||||
| """Typed server-scoped RPC methods.""" | ||||||
|
|
||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -9,7 +9,8 @@ | |||||
| import inspect | ||||||
| import threading | ||||||
| from collections.abc import Callable | ||||||
| from typing import Any, cast | ||||||
| from types import TracebackType | ||||||
| from typing import Any, Optional, cast | ||||||
|
|
||||||
| from .generated.rpc import SessionModelSwitchToParams, SessionRpc | ||||||
| from .generated.session_events import SessionEvent, SessionEventType, session_event_from_dict | ||||||
|
|
@@ -73,6 +74,7 @@ def __init__(self, session_id: str, client: Any, workspace_path: str | None = No | |||||
| self.session_id = session_id | ||||||
| self._client = client | ||||||
| self._workspace_path = workspace_path | ||||||
| self._destroyed = False | ||||||
| self._event_handlers: set[Callable[[SessionEvent], None]] = set() | ||||||
| self._event_handlers_lock = threading.Lock() | ||||||
| self._tool_handlers: dict[str, ToolHandler] = {} | ||||||
|
|
@@ -85,6 +87,35 @@ def __init__(self, session_id: str, client: Any, workspace_path: str | None = No | |||||
| self._hooks_lock = threading.Lock() | ||||||
| self._rpc: SessionRpc | None = None | ||||||
|
|
||||||
| async def __aenter__(self) -> "CopilotSession": | ||||||
| """ | ||||||
| Enter the async context manager. | ||||||
|
|
||||||
| Returns the session instance, ready for use. The session must already be | ||||||
| created (via CopilotClient.create_session or resume_session). | ||||||
|
|
||||||
| Returns: | ||||||
| The CopilotSession instance. | ||||||
|
|
||||||
| Example: | ||||||
| >>> async with await client.create_session() as session: | ||||||
| ... await session.send({"prompt": "Hello!"}) | ||||||
| """ | ||||||
| return self | ||||||
|
|
||||||
| async def __aexit__( | ||||||
| self, | ||||||
| exc_type: Optional[type[BaseException]], | ||||||
| exc_val: Optional[BaseException], | ||||||
| exc_tb: Optional[TracebackType], | ||||||
| ) -> None: | ||||||
| """ | ||||||
| Exit the async context manager. | ||||||
|
|
||||||
| Automatically destroys the session and releases all associated resources. | ||||||
| """ | ||||||
| await self.destroy() | ||||||
|
|
||||||
| @property | ||||||
| def rpc(self) -> SessionRpc: | ||||||
| """Typed session-scoped RPC methods.""" | ||||||
|
|
@@ -487,20 +518,33 @@ async def disconnect(self) -> None: | |||||
|
|
||||||
| After calling this method, the session object can no longer be used. | ||||||
|
|
||||||
| This method is idempotent—calling it multiple times is safe and will | ||||||
| not raise an error if the session is already destroyed. | ||||||
|
|
||||||
| Raises: | ||||||
| Exception: If the connection fails. | ||||||
| Exception: If the connection fails (on first destroy call). | ||||||
|
|
||||||
| Example: | ||||||
| >>> # Clean up when done — session can still be resumed later | ||||||
| >>> await session.disconnect() | ||||||
| """ | ||||||
| await self._client.request("session.destroy", {"sessionId": self.session_id}) | ||||||
| # Ensure that the check and update of _destroyed are atomic so that | ||||||
| # only the first caller proceeds to send the destroy RPC. | ||||||
| with self._event_handlers_lock: | ||||||
| self._event_handlers.clear() | ||||||
| with self._tool_handlers_lock: | ||||||
| self._tool_handlers.clear() | ||||||
| with self._permission_handler_lock: | ||||||
| self._permission_handler = None | ||||||
| if self._destroyed: | ||||||
| return | ||||||
| self._destroyed = True | ||||||
|
|
||||||
| try: | ||||||
| await self._client.request("session.destroy", {"sessionId": self.session_id}) | ||||||
| finally: | ||||||
| # Clear handlers even if the request fails | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| with self._event_handlers_lock: | ||||||
| self._event_handlers.clear() | ||||||
| with self._tool_handlers_lock: | ||||||
| self._tool_handlers.clear() | ||||||
| with self._permission_handler_lock: | ||||||
| self._permission_handler = None | ||||||
|
|
||||||
| async def destroy(self) -> None: | ||||||
| """ | ||||||
|
|
||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
All examples should be updated to use context managers and the README the call-out should be you can do what the context manager does manually and how to do that.