-
Notifications
You must be signed in to change notification settings - Fork 923
Expand file tree
/
Copy pathclient.py
More file actions
1610 lines (1322 loc) · 57.3 KB
/
client.py
File metadata and controls
1610 lines (1322 loc) · 57.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Copilot CLI SDK Client - Main entry point for the Copilot SDK.
This module provides the :class:`CopilotClient` class, which manages the connection
to the Copilot CLI server and provides session management capabilities.
Example:
>>> from copilot import CopilotClient
>>>
>>> async with CopilotClient() as client:
... session = await client.create_session()
... await session.send({"prompt": "Hello!"})
"""
import asyncio
import inspect
import os
import re
import subprocess
import sys
import threading
from dataclasses import asdict, is_dataclass
from pathlib import Path
from typing import Any, Callable, Optional, cast
from .generated.rpc import ServerRpc
from .generated.session_events import session_event_from_dict
from .jsonrpc import JsonRpcClient, ProcessExitedError
from .sdk_protocol_version import get_sdk_protocol_version
from .session import CopilotSession
from .types import (
ConnectionState,
CopilotClientOptions,
CustomAgentConfig,
GetAuthStatusResponse,
GetStatusResponse,
ModelInfo,
PingResponse,
ProviderConfig,
ResumeSessionConfig,
SessionConfig,
SessionLifecycleEvent,
SessionLifecycleEventType,
SessionLifecycleHandler,
SessionListFilter,
SessionMetadata,
StopError,
ToolHandler,
ToolInvocation,
ToolResult,
)
def _get_bundled_cli_path() -> Optional[str]:
"""Get the path to the bundled CLI binary, if available."""
# The binary is bundled in copilot/bin/ within the package
bin_dir = Path(__file__).parent / "bin"
if not bin_dir.exists():
return None
# Determine binary name based on platform
if sys.platform == "win32":
binary_name = "copilot.exe"
else:
binary_name = "copilot"
binary_path = bin_dir / binary_name
if binary_path.exists():
return str(binary_path)
return None
class CopilotClient:
"""
Main client for interacting with the Copilot CLI.
The CopilotClient manages the connection to the Copilot CLI server and provides
methods to create and manage conversation sessions. It can either spawn a CLI
server process or connect to an existing server.
The client supports both stdio (default) and TCP transport modes for
communication with the CLI server.
Attributes:
options: The configuration options for the client.
Example:
>>> # Create a client with default options (spawns CLI server)
>>> client = CopilotClient()
>>> await client.start()
>>>
>>> # Create a session and send a message
>>> session = await client.create_session({"model": "gpt-4"})
>>> session.on(lambda event: print(event.type))
>>> await session.send({"prompt": "Hello!"})
>>>
>>> # Clean up
>>> await session.destroy()
>>> await client.stop()
>>> # Or connect to an existing server
>>> client = CopilotClient({"cli_url": "localhost:3000"})
"""
def __init__(self, options: Optional[CopilotClientOptions] = None):
"""
Initialize a new CopilotClient.
Args:
options: Optional configuration options for the client. If not provided,
default options are used (spawns CLI server using stdio).
Raises:
ValueError: If mutually exclusive options are provided (e.g., cli_url
with use_stdio or cli_path).
Example:
>>> # Default options - spawns CLI server using stdio
>>> client = CopilotClient()
>>>
>>> # Connect to an existing server
>>> client = CopilotClient({"cli_url": "localhost:3000"})
>>>
>>> # Custom CLI path with specific log level
>>> client = CopilotClient({
... "cli_path": "/usr/local/bin/copilot",
... "log_level": "debug"
... })
"""
opts = options or {}
# Validate mutually exclusive options
if opts.get("cli_url") and (opts.get("use_stdio") or opts.get("cli_path")):
raise ValueError("cli_url is mutually exclusive with use_stdio and cli_path")
# Validate auth options with external server
if opts.get("cli_url") and (
opts.get("github_token") or opts.get("use_logged_in_user") is not None
):
raise ValueError(
"github_token and use_logged_in_user cannot be used with cli_url "
"(external server manages its own auth)"
)
# Parse cli_url if provided
self._actual_host: str = "localhost"
self._is_external_server: bool = False
if opts.get("cli_url"):
self._actual_host, actual_port = self._parse_cli_url(opts["cli_url"])
self._actual_port: Optional[int] = actual_port
self._is_external_server = True
else:
self._actual_port = None
# Determine CLI path: explicit option > bundled binary
# Not needed when connecting to external server via cli_url
if opts.get("cli_url"):
default_cli_path = "" # Not used for external server
elif opts.get("cli_path"):
default_cli_path = opts["cli_path"]
else:
bundled_path = _get_bundled_cli_path()
if bundled_path:
default_cli_path = bundled_path
else:
raise RuntimeError(
"Copilot CLI not found. The bundled CLI binary is not available. "
"Ensure you installed a platform-specific wheel, or provide cli_path."
)
# Default use_logged_in_user to False when github_token is provided
github_token = opts.get("github_token")
use_logged_in_user = opts.get("use_logged_in_user")
if use_logged_in_user is None:
use_logged_in_user = False if github_token else True
self.options: CopilotClientOptions = {
"cli_path": default_cli_path,
"cwd": opts.get("cwd", os.getcwd()),
"port": opts.get("port", 0),
"use_stdio": False if opts.get("cli_url") else opts.get("use_stdio", True),
"log_level": opts.get("log_level", "info"),
"auto_start": opts.get("auto_start", True),
"auto_restart": opts.get("auto_restart", True),
"use_logged_in_user": use_logged_in_user,
}
if opts.get("cli_args"):
self.options["cli_args"] = opts["cli_args"]
if opts.get("cli_url"):
self.options["cli_url"] = opts["cli_url"]
if opts.get("env"):
self.options["env"] = opts["env"]
if github_token:
self.options["github_token"] = github_token
self._process: Optional[subprocess.Popen] = None
self._client: Optional[JsonRpcClient] = None
self._state: ConnectionState = "disconnected"
self._sessions: dict[str, CopilotSession] = {}
self._sessions_lock = threading.Lock()
self._models_cache: Optional[list[ModelInfo]] = None
self._models_cache_lock = asyncio.Lock()
self._lifecycle_handlers: list[SessionLifecycleHandler] = []
self._typed_lifecycle_handlers: dict[
SessionLifecycleEventType, list[SessionLifecycleHandler]
] = {}
self._lifecycle_handlers_lock = threading.Lock()
self._rpc: Optional[ServerRpc] = None
@property
def rpc(self) -> ServerRpc:
"""Typed server-scoped RPC methods."""
if self._rpc is None:
raise RuntimeError("Client is not connected. Call start() first.")
return self._rpc
def _parse_cli_url(self, url: str) -> tuple[str, int]:
"""
Parse CLI URL into host and port.
Supports formats: "host:port", "http://host:port", "https://host:port",
or just "port".
Args:
url: The CLI URL to parse.
Returns:
A tuple of (host, port).
Raises:
ValueError: If the URL format is invalid or the port is out of range.
"""
import re
# Remove protocol if present
clean_url = re.sub(r"^https?://", "", url)
# Check if it's just a port number
if clean_url.isdigit():
port = int(clean_url)
if port <= 0 or port > 65535:
raise ValueError(f"Invalid port in cli_url: {url}")
return ("localhost", port)
# Parse host:port format
parts = clean_url.split(":")
if len(parts) != 2:
raise ValueError(f"Invalid cli_url format: {url}")
host = parts[0] if parts[0] else "localhost"
try:
port = int(parts[1])
except ValueError as e:
raise ValueError(f"Invalid port in cli_url: {url}") from e
if port <= 0 or port > 65535:
raise ValueError(f"Invalid port in cli_url: {url}")
return (host, port)
async def start(self) -> None:
"""
Start the CLI server and establish a connection.
If connecting to an external server (via cli_url), only establishes the
connection. Otherwise, spawns the CLI server process and then connects.
This method is called automatically when creating a session if ``auto_start``
is True (default).
Raises:
RuntimeError: If the server fails to start or the connection fails.
Example:
>>> client = CopilotClient({"auto_start": False})
>>> await client.start()
>>> # Now ready to create sessions
"""
if self._state == "connected":
return
self._state = "connecting"
try:
# Only start CLI server process if not connecting to external server
if not self._is_external_server:
await self._start_cli_server()
# Connect to the server
await self._connect_to_server()
# Verify protocol version compatibility
await self._verify_protocol_version()
self._state = "connected"
except ProcessExitedError as e:
# Process exited with error - reraise as RuntimeError with stderr
self._state = "error"
raise RuntimeError(str(e)) from None
except Exception as e:
self._state = "error"
# Check if process exited and capture any remaining stderr
if self._process and hasattr(self._process, "poll"):
return_code = self._process.poll()
if return_code is not None and self._client:
stderr_output = self._client.get_stderr_output()
if stderr_output:
raise RuntimeError(
f"CLI process exited with code {return_code}\nstderr: {stderr_output}"
) from e
raise
async def stop(self) -> list["StopError"]:
"""
Stop the CLI server and close all active sessions.
This method performs graceful cleanup:
1. Destroys all active sessions
2. Closes the JSON-RPC connection
3. Terminates the CLI server process (if spawned by this client)
Returns:
A list of StopError objects containing error messages that occurred
during cleanup. An empty list indicates all cleanup succeeded.
Example:
>>> errors = await client.stop()
>>> if errors:
... for error in errors:
... print(f"Cleanup error: {error.message}")
"""
errors: list[StopError] = []
# Atomically take ownership of all sessions and clear the dict
# so no other thread can access them
with self._sessions_lock:
sessions_to_destroy = list(self._sessions.values())
self._sessions.clear()
for session in sessions_to_destroy:
try:
await session.destroy()
except Exception as e:
errors.append(
StopError(message=f"Failed to destroy session {session.session_id}: {e}")
)
# Close client
if self._client:
await self._client.stop()
self._client = None
self._rpc = None
# Clear models cache
async with self._models_cache_lock:
self._models_cache = None
# Kill CLI process
# Kill CLI process (only if we spawned it)
if self._process and not self._is_external_server:
self._process.terminate()
try:
self._process.wait(timeout=5)
except subprocess.TimeoutExpired:
self._process.kill()
self._process = None
self._state = "disconnected"
if not self._is_external_server:
self._actual_port = None
return errors
async def force_stop(self) -> None:
"""
Forcefully stop the CLI server without graceful cleanup.
Use this when :meth:`stop` fails or takes too long. This method:
- Clears all sessions immediately without destroying them
- Force closes the connection
- Kills the CLI process (if spawned by this client)
Example:
>>> # If normal stop hangs, force stop
>>> try:
... await asyncio.wait_for(client.stop(), timeout=5.0)
... except asyncio.TimeoutError:
... await client.force_stop()
"""
# Clear sessions immediately without trying to destroy them
with self._sessions_lock:
self._sessions.clear()
# Force close connection
if self._client:
try:
await self._client.stop()
except Exception:
pass # Ignore errors during force stop
self._client = None
self._rpc = None
# Clear models cache
async with self._models_cache_lock:
self._models_cache = None
# Kill CLI process immediately
if self._process and not self._is_external_server:
self._process.kill()
self._process = None
self._state = "disconnected"
if not self._is_external_server:
self._actual_port = None
async def create_session(self, config: Optional[SessionConfig] = None) -> CopilotSession:
"""
Create a new conversation session with the Copilot CLI.
Sessions maintain conversation state, handle events, and manage tool execution.
If the client is not connected and ``auto_start`` is enabled, this will
automatically start the connection.
Args:
config: Optional configuration for the session, including model selection,
custom tools, system messages, and more.
Returns:
A :class:`CopilotSession` instance for the new session.
Raises:
RuntimeError: If the client is not connected and auto_start is disabled.
Example:
>>> # Basic session
>>> session = await client.create_session()
>>>
>>> # Session with model and streaming
>>> session = await client.create_session({
... "model": "gpt-4",
... "streaming": True
... })
"""
if not self._client:
if self.options["auto_start"]:
await self.start()
else:
raise RuntimeError("Client not connected. Call start() first.")
cfg = config or {}
tool_defs = []
tools = cfg.get("tools")
if tools:
for tool in tools:
definition = {
"name": tool.name,
"description": tool.description,
}
if tool.parameters:
definition["parameters"] = tool.parameters
tool_defs.append(definition)
payload: dict[str, Any] = {}
if cfg.get("model"):
payload["model"] = cfg["model"]
if cfg.get("session_id"):
payload["sessionId"] = cfg["session_id"]
if cfg.get("client_name"):
payload["clientName"] = cfg["client_name"]
if cfg.get("reasoning_effort"):
payload["reasoningEffort"] = cfg["reasoning_effort"]
if tool_defs:
payload["tools"] = tool_defs
# Add system message configuration if provided
system_message = cfg.get("system_message")
if system_message:
payload["systemMessage"] = system_message
# Add tool filtering options
available_tools = cfg.get("available_tools")
if available_tools:
payload["availableTools"] = available_tools
excluded_tools = cfg.get("excluded_tools")
if excluded_tools:
payload["excludedTools"] = excluded_tools
# Enable permission request callback if handler provided
on_permission_request = cfg.get("on_permission_request")
if on_permission_request:
payload["requestPermission"] = True
# Enable user input request callback if handler provided
on_user_input_request = cfg.get("on_user_input_request")
if on_user_input_request:
payload["requestUserInput"] = True
# Enable hooks callback if any hook handler provided
hooks = cfg.get("hooks")
if hooks and any(hooks.values()):
payload["hooks"] = True
# Add working directory if provided
working_directory = cfg.get("working_directory")
if working_directory:
payload["workingDirectory"] = working_directory
# Add streaming option if provided
streaming = cfg.get("streaming")
if streaming is not None:
payload["streaming"] = streaming
# Add provider configuration if provided
provider = cfg.get("provider")
if provider:
payload["provider"] = self._convert_provider_to_wire_format(provider)
# Add MCP servers configuration if provided
mcp_servers = cfg.get("mcp_servers")
if mcp_servers:
payload["mcpServers"] = mcp_servers
payload["envValueMode"] = "direct"
# Add custom agents configuration if provided
custom_agents = cfg.get("custom_agents")
if custom_agents:
payload["customAgents"] = [
self._convert_custom_agent_to_wire_format(agent) for agent in custom_agents
]
# Add config directory override if provided
config_dir = cfg.get("config_dir")
if config_dir:
payload["configDir"] = config_dir
# Add skill directories configuration if provided
skill_directories = cfg.get("skill_directories")
if skill_directories:
payload["skillDirectories"] = skill_directories
# Add disabled skills configuration if provided
disabled_skills = cfg.get("disabled_skills")
if disabled_skills:
payload["disabledSkills"] = disabled_skills
# Add infinite sessions configuration if provided
infinite_sessions = cfg.get("infinite_sessions")
if infinite_sessions:
wire_config: dict[str, Any] = {}
if "enabled" in infinite_sessions:
wire_config["enabled"] = infinite_sessions["enabled"]
if "background_compaction_threshold" in infinite_sessions:
wire_config["backgroundCompactionThreshold"] = infinite_sessions[
"background_compaction_threshold"
]
if "buffer_exhaustion_threshold" in infinite_sessions:
wire_config["bufferExhaustionThreshold"] = infinite_sessions[
"buffer_exhaustion_threshold"
]
payload["infiniteSessions"] = wire_config
if not self._client:
raise RuntimeError("Client not connected")
response = await self._client.request("session.create", payload)
session_id = response["sessionId"]
workspace_path = response.get("workspacePath")
session = CopilotSession(session_id, self._client, workspace_path)
session._register_tools(tools)
if on_permission_request:
session._register_permission_handler(on_permission_request)
if on_user_input_request:
session._register_user_input_handler(on_user_input_request)
if hooks:
session._register_hooks(hooks)
with self._sessions_lock:
self._sessions[session_id] = session
return session
async def resume_session(
self, session_id: str, config: Optional[ResumeSessionConfig] = None
) -> CopilotSession:
"""
Resume an existing conversation session by its ID.
This allows you to continue a previous conversation, maintaining all
conversation history. The session must have been previously created
and not deleted.
Args:
session_id: The ID of the session to resume.
config: Optional configuration for the resumed session.
Returns:
A :class:`CopilotSession` instance for the resumed session.
Raises:
RuntimeError: If the session does not exist or the client is not connected.
Example:
>>> # Resume a previous session
>>> session = await client.resume_session("session-123")
>>>
>>> # Resume with new tools
>>> session = await client.resume_session("session-123", {
... "tools": [my_new_tool]
... })
"""
if not self._client:
if self.options["auto_start"]:
await self.start()
else:
raise RuntimeError("Client not connected. Call start() first.")
cfg = config or {}
tool_defs = []
tools = cfg.get("tools")
if tools:
for tool in tools:
definition = {
"name": tool.name,
"description": tool.description,
}
if tool.parameters:
definition["parameters"] = tool.parameters
tool_defs.append(definition)
payload: dict[str, Any] = {"sessionId": session_id}
# Add client name if provided
client_name = cfg.get("client_name")
if client_name:
payload["clientName"] = client_name
# Add model if provided
model = cfg.get("model")
if model:
payload["model"] = model
if cfg.get("reasoning_effort"):
payload["reasoningEffort"] = cfg["reasoning_effort"]
if tool_defs:
payload["tools"] = tool_defs
# Add system message configuration if provided
system_message = cfg.get("system_message")
if system_message:
payload["systemMessage"] = system_message
# Add available/excluded tools if provided
available_tools = cfg.get("available_tools")
if available_tools:
payload["availableTools"] = available_tools
excluded_tools = cfg.get("excluded_tools")
if excluded_tools:
payload["excludedTools"] = excluded_tools
provider = cfg.get("provider")
if provider:
payload["provider"] = self._convert_provider_to_wire_format(provider)
# Add streaming option if provided
streaming = cfg.get("streaming")
if streaming is not None:
payload["streaming"] = streaming
# Enable permission request callback if handler provided
on_permission_request = cfg.get("on_permission_request")
if on_permission_request:
payload["requestPermission"] = True
# Enable user input request callback if handler provided
on_user_input_request = cfg.get("on_user_input_request")
if on_user_input_request:
payload["requestUserInput"] = True
# Enable hooks callback if any hook handler provided
hooks = cfg.get("hooks")
if hooks and any(hooks.values()):
payload["hooks"] = True
# Add working directory if provided
working_directory = cfg.get("working_directory")
if working_directory:
payload["workingDirectory"] = working_directory
# Add config directory if provided
config_dir = cfg.get("config_dir")
if config_dir:
payload["configDir"] = config_dir
# Add disable resume flag if provided
disable_resume = cfg.get("disable_resume")
if disable_resume:
payload["disableResume"] = True
# Add MCP servers configuration if provided
mcp_servers = cfg.get("mcp_servers")
if mcp_servers:
payload["mcpServers"] = mcp_servers
payload["envValueMode"] = "direct"
# Add custom agents configuration if provided
custom_agents = cfg.get("custom_agents")
if custom_agents:
payload["customAgents"] = [
self._convert_custom_agent_to_wire_format(agent) for agent in custom_agents
]
# Add skill directories configuration if provided
skill_directories = cfg.get("skill_directories")
if skill_directories:
payload["skillDirectories"] = skill_directories
# Add disabled skills configuration if provided
disabled_skills = cfg.get("disabled_skills")
if disabled_skills:
payload["disabledSkills"] = disabled_skills
# Add infinite sessions configuration if provided
infinite_sessions = cfg.get("infinite_sessions")
if infinite_sessions:
wire_config: dict[str, Any] = {}
if "enabled" in infinite_sessions:
wire_config["enabled"] = infinite_sessions["enabled"]
if "background_compaction_threshold" in infinite_sessions:
wire_config["backgroundCompactionThreshold"] = infinite_sessions[
"background_compaction_threshold"
]
if "buffer_exhaustion_threshold" in infinite_sessions:
wire_config["bufferExhaustionThreshold"] = infinite_sessions[
"buffer_exhaustion_threshold"
]
payload["infiniteSessions"] = wire_config
if not self._client:
raise RuntimeError("Client not connected")
response = await self._client.request("session.resume", payload)
resumed_session_id = response["sessionId"]
workspace_path = response.get("workspacePath")
session = CopilotSession(resumed_session_id, self._client, workspace_path)
session._register_tools(cfg.get("tools"))
if on_permission_request:
session._register_permission_handler(on_permission_request)
if on_user_input_request:
session._register_user_input_handler(on_user_input_request)
if hooks:
session._register_hooks(hooks)
with self._sessions_lock:
self._sessions[resumed_session_id] = session
return session
def get_state(self) -> ConnectionState:
"""
Get the current connection state of the client.
Returns:
The current connection state: "disconnected", "connecting",
"connected", or "error".
Example:
>>> if client.get_state() == "connected":
... session = await client.create_session()
"""
return self._state
async def ping(self, message: Optional[str] = None) -> "PingResponse":
"""
Send a ping request to the server to verify connectivity.
Args:
message: Optional message to include in the ping.
Returns:
A PingResponse object containing the ping response.
Raises:
RuntimeError: If the client is not connected.
Example:
>>> response = await client.ping("health check")
>>> print(f"Server responded at {response.timestamp}")
"""
if not self._client:
raise RuntimeError("Client not connected")
result = await self._client.request("ping", {"message": message})
return PingResponse.from_dict(result)
async def get_status(self) -> "GetStatusResponse":
"""
Get CLI status including version and protocol information.
Returns:
A GetStatusResponse object containing version and protocolVersion.
Raises:
RuntimeError: If the client is not connected.
Example:
>>> status = await client.get_status()
>>> print(f"CLI version: {status.version}")
"""
if not self._client:
raise RuntimeError("Client not connected")
result = await self._client.request("status.get", {})
return GetStatusResponse.from_dict(result)
async def get_auth_status(self) -> "GetAuthStatusResponse":
"""
Get current authentication status.
Returns:
A GetAuthStatusResponse object containing authentication state.
Raises:
RuntimeError: If the client is not connected.
Example:
>>> auth = await client.get_auth_status()
>>> if auth.isAuthenticated:
... print(f"Logged in as {auth.login}")
"""
if not self._client:
raise RuntimeError("Client not connected")
result = await self._client.request("auth.getStatus", {})
return GetAuthStatusResponse.from_dict(result)
async def list_models(self) -> list["ModelInfo"]:
"""
List available models with their metadata.
Results are cached after the first successful call to avoid rate limiting.
The cache is cleared when the client disconnects.
Returns:
A list of ModelInfo objects with model details.
Raises:
RuntimeError: If the client is not connected.
Exception: If not authenticated.
Example:
>>> models = await client.list_models()
>>> for model in models:
... print(f"{model.id}: {model.name}")
"""
if not self._client:
raise RuntimeError("Client not connected")
# Use asyncio lock to prevent race condition with concurrent calls
async with self._models_cache_lock:
# Check cache (already inside lock)
if self._models_cache is not None:
return list(self._models_cache) # Return a copy to prevent cache mutation
# Cache miss - fetch from backend while holding lock
response = await self._client.request("models.list", {})
models_data = response.get("models", [])
models = [ModelInfo.from_dict(model) for model in models_data]
# Update cache before releasing lock
self._models_cache = models
return list(models) # Return a copy to prevent cache mutation
async def list_sessions(
self, filter: "SessionListFilter | None" = None
) -> list["SessionMetadata"]:
"""
List all available sessions known to the server.
Returns metadata about each session including ID, timestamps, and summary.
Args:
filter: Optional filter to narrow down the list of sessions by cwd, git root,
repository, or branch.
Returns:
A list of SessionMetadata objects.
Raises:
RuntimeError: If the client is not connected.
Example:
>>> sessions = await client.list_sessions()
>>> for session in sessions:
... print(f"Session: {session.sessionId}")
>>> # Filter sessions by repository
>>> from copilot import SessionListFilter
>>> filtered = await client.list_sessions(SessionListFilter(repository="owner/repo"))
"""
if not self._client:
raise RuntimeError("Client not connected")
payload: dict = {}
if filter is not None:
payload["filter"] = filter.to_dict()
response = await self._client.request("session.list", payload)
sessions_data = response.get("sessions", [])
return [SessionMetadata.from_dict(session) for session in sessions_data]
async def delete_session(self, session_id: str) -> None:
"""
Delete a session permanently.
This permanently removes the session and all its conversation history.
The session cannot be resumed after deletion.
Args:
session_id: The ID of the session to delete.
Raises:
RuntimeError: If the client is not connected or deletion fails.
Example:
>>> await client.delete_session("session-123")
"""
if not self._client:
raise RuntimeError("Client not connected")
response = await self._client.request("session.delete", {"sessionId": session_id})
success = response.get("success", False)
if not success:
error = response.get("error", "Unknown error")
raise RuntimeError(f"Failed to delete session {session_id}: {error}")
# Remove from local sessions map if present
with self._sessions_lock:
if session_id in self._sessions:
del self._sessions[session_id]
async def get_foreground_session_id(self) -> Optional[str]:
"""
Get the ID of the session currently displayed in the TUI.
This is only available when connecting to a server running in TUI+server mode
(--ui-server).
Returns:
The session ID, or None if no foreground session is set.
Raises:
RuntimeError: If the client is not connected.
Example:
>>> session_id = await client.get_foreground_session_id()
>>> if session_id:
... print(f"TUI is displaying session: {session_id}")
"""
if not self._client:
raise RuntimeError("Client not connected")
response = await self._client.request("session.getForeground", {})
return response.get("sessionId")
async def set_foreground_session_id(self, session_id: str) -> None:
"""
Request the TUI to switch to displaying the specified session.
This is only available when connecting to a server running in TUI+server mode
(--ui-server).
Args:
session_id: The ID of the session to display in the TUI.
Raises:
RuntimeError: If the client is not connected or the operation fails.
Example:
>>> await client.set_foreground_session_id("session-123")
"""
if not self._client:
raise RuntimeError("Client not connected")
response = await self._client.request("session.setForeground", {"sessionId": session_id})
success = response.get("success", False)
if not success:
error = response.get("error", "Unknown error")
raise RuntimeError(f"Failed to set foreground session: {error}")
def on(
self,
event_type_or_handler: SessionLifecycleEventType | SessionLifecycleHandler,
handler: Optional[SessionLifecycleHandler] = None,
) -> Callable[[], None]:
"""
Subscribe to session lifecycle events.