-
Notifications
You must be signed in to change notification settings - Fork 923
Expand file tree
/
Copy pathclient.go
More file actions
1421 lines (1256 loc) · 41.5 KB
/
client.go
File metadata and controls
1421 lines (1256 loc) · 41.5 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
// Package copilot provides a Go SDK for interacting with the GitHub Copilot CLI.
//
// The copilot package enables Go applications to communicate with the Copilot CLI
// server, create and manage conversation sessions, and integrate custom tools.
//
// Basic usage:
//
// client := copilot.NewClient(nil)
// if err := client.Start(); err != nil {
// log.Fatal(err)
// }
// defer client.Stop()
//
// session, err := client.CreateSession(&copilot.SessionConfig{
// OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
// Model: "gpt-4",
// })
// if err != nil {
// log.Fatal(err)
// }
//
// session.On(func(event copilot.SessionEvent) {
// if event.Type == "assistant.message" {
// fmt.Println(event.Data.Content)
// }
// })
//
// session.Send(copilot.MessageOptions{Prompt: "Hello!"})
package copilot
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/github/copilot-sdk/go/internal/embeddedcli"
"github.com/github/copilot-sdk/go/internal/jsonrpc2"
"github.com/github/copilot-sdk/go/rpc"
)
// Client manages the connection to the Copilot CLI server and provides session management.
//
// The Client can either spawn a CLI server process or connect to an existing server.
// It handles JSON-RPC communication, session lifecycle, tool execution, and permission requests.
//
// Example:
//
// // Create a client with default options (spawns CLI server using stdio)
// client := copilot.NewClient(nil)
//
// // Or connect to an existing server
// client := copilot.NewClient(&copilot.ClientOptions{
// CLIUrl: "localhost:3000",
// })
//
// if err := client.Start(); err != nil {
// log.Fatal(err)
// }
// defer client.Stop()
type Client struct {
options ClientOptions
process *exec.Cmd
client *jsonrpc2.Client
actualPort int
actualHost string
state ConnectionState
sessions map[string]*Session
sessionsMux sync.Mutex
isExternalServer bool
conn net.Conn // stores net.Conn for external TCP connections
useStdio bool // resolved value from options
autoStart bool // resolved value from options
autoRestart bool // resolved value from options
modelsCache []ModelInfo
modelsCacheMux sync.Mutex
lifecycleHandlers []SessionLifecycleHandler
typedLifecycleHandlers map[SessionLifecycleEventType][]SessionLifecycleHandler
lifecycleHandlersMux sync.Mutex
startStopMux sync.RWMutex // protects process and state during start/[force]stop
processDone chan struct{}
processErrorPtr *error
osProcess atomic.Pointer[os.Process]
// RPC provides typed server-scoped RPC methods.
// This field is nil until the client is connected via Start().
RPC *rpc.ServerRpc
}
// NewClient creates a new Copilot CLI client with the given options.
//
// If options is nil, default options are used (spawns CLI server using stdio).
// The client is not connected after creation; call [Client.Start] to connect.
//
// Example:
//
// // Default options
// client := copilot.NewClient(nil)
//
// // Custom options
// client := copilot.NewClient(&copilot.ClientOptions{
// CLIPath: "/usr/local/bin/copilot",
// LogLevel: "debug",
// })
func NewClient(options *ClientOptions) *Client {
opts := ClientOptions{
CLIPath: "",
Cwd: "",
Port: 0,
LogLevel: "info",
}
client := &Client{
options: opts,
state: StateDisconnected,
sessions: make(map[string]*Session),
actualHost: "localhost",
isExternalServer: false,
useStdio: true,
autoStart: true, // default
autoRestart: true, // default
}
if options != nil {
// Validate mutually exclusive options
if options.CLIUrl != "" && ((options.UseStdio != nil) || options.CLIPath != "") {
panic("CLIUrl is mutually exclusive with UseStdio and CLIPath")
}
// Validate auth options with external server
if options.CLIUrl != "" && (options.GitHubToken != "" || options.UseLoggedInUser != nil) {
panic("GitHubToken and UseLoggedInUser cannot be used with CLIUrl (external server manages its own auth)")
}
// Parse CLIUrl if provided
if options.CLIUrl != "" {
host, port := parseCliUrl(options.CLIUrl)
client.actualHost = host
client.actualPort = port
client.isExternalServer = true
client.useStdio = false
opts.CLIUrl = options.CLIUrl
}
if options.CLIPath != "" {
opts.CLIPath = options.CLIPath
}
if len(options.CLIArgs) > 0 {
opts.CLIArgs = append([]string{}, options.CLIArgs...)
}
if options.Cwd != "" {
opts.Cwd = options.Cwd
}
if options.Port > 0 {
opts.Port = options.Port
// If port is specified, switch to TCP mode
client.useStdio = false
}
if options.LogLevel != "" {
opts.LogLevel = options.LogLevel
}
if options.Env != nil {
opts.Env = options.Env
}
if options.UseStdio != nil {
client.useStdio = *options.UseStdio
}
if options.AutoStart != nil {
client.autoStart = *options.AutoStart
}
if options.AutoRestart != nil {
client.autoRestart = *options.AutoRestart
}
if options.GitHubToken != "" {
opts.GitHubToken = options.GitHubToken
}
if options.UseLoggedInUser != nil {
opts.UseLoggedInUser = options.UseLoggedInUser
}
}
// Default Env to current environment if not set
if opts.Env == nil {
opts.Env = os.Environ()
}
// Check environment variable for CLI path
if cliPath := os.Getenv("COPILOT_CLI_PATH"); cliPath != "" {
opts.CLIPath = cliPath
}
client.options = opts
return client
}
// parseCliUrl parses a CLI URL into host and port components.
//
// Supports formats: "host:port", "http://host:port", "https://host:port", or just "port".
// Panics if the URL format is invalid or the port is out of range.
func parseCliUrl(url string) (string, int) {
// Remove protocol if present
cleanUrl, _ := strings.CutPrefix(url, "https://")
cleanUrl, _ = strings.CutPrefix(cleanUrl, "http://")
// Parse host:port or port format
var host string
var portStr string
if before, after, found := strings.Cut(cleanUrl, ":"); found {
host = before
portStr = after
} else {
// Only port provided
portStr = before
}
if host == "" {
host = "localhost"
}
// Validate port
port, err := strconv.Atoi(portStr)
if err != nil || port <= 0 || port > 65535 {
panic(fmt.Sprintf("Invalid port in CLIUrl: %s", url))
}
return host, port
}
// Start starts the CLI server (if not using an external server) and establishes
// a connection.
//
// If connecting to an external server (via CLIUrl), only establishes the connection.
// Otherwise, spawns the CLI server process and then connects.
//
// This method is called automatically when creating a session if AutoStart is true (default).
//
// Returns an error if the server fails to start or the connection fails.
//
// Example:
//
// client := copilot.NewClient(&copilot.ClientOptions{AutoStart: boolPtr(false)})
// if err := client.Start(context.Background()); err != nil {
// log.Fatal("Failed to start:", err)
// }
// // Now ready to create sessions
func (c *Client) Start(ctx context.Context) error {
c.startStopMux.Lock()
defer c.startStopMux.Unlock()
if c.state == StateConnected {
return nil
}
c.state = StateConnecting
// Only start CLI server process if not connecting to external server
if !c.isExternalServer {
if err := c.startCLIServer(ctx); err != nil {
c.process = nil
c.state = StateError
return err
}
}
// Connect to the server
if err := c.connectToServer(ctx); err != nil {
killErr := c.killProcess()
c.state = StateError
return errors.Join(err, killErr)
}
// Verify protocol version compatibility
if err := c.verifyProtocolVersion(ctx); err != nil {
killErr := c.killProcess()
c.state = StateError
return errors.Join(err, killErr)
}
c.state = StateConnected
return nil
}
// Stop stops the CLI server and closes 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 an error that aggregates all errors encountered during cleanup.
//
// Example:
//
// if err := client.Stop(); err != nil {
// log.Printf("Cleanup error: %v", err)
// }
func (c *Client) Stop() error {
var errs []error
// Destroy all active sessions
c.sessionsMux.Lock()
sessions := make([]*Session, 0, len(c.sessions))
for _, session := range c.sessions {
sessions = append(sessions, session)
}
c.sessionsMux.Unlock()
for _, session := range sessions {
if err := session.Destroy(); err != nil {
errs = append(errs, fmt.Errorf("failed to destroy session %s: %w", session.SessionID, err))
}
}
c.sessionsMux.Lock()
c.sessions = make(map[string]*Session)
c.sessionsMux.Unlock()
c.startStopMux.Lock()
defer c.startStopMux.Unlock()
// Kill CLI process FIRST (this closes stdout and unblocks readLoop) - only if we spawned it
if c.process != nil && !c.isExternalServer {
if err := c.killProcess(); err != nil {
errs = append(errs, err)
}
}
c.process = nil
// Close external TCP connection if exists
if c.isExternalServer && c.conn != nil {
if err := c.conn.Close(); err != nil {
errs = append(errs, fmt.Errorf("failed to close socket: %w", err))
}
c.conn = nil
}
// Then close JSON-RPC client (readLoop can now exit)
if c.client != nil {
c.client.Stop()
c.client = nil
}
// Clear models cache
c.modelsCacheMux.Lock()
c.modelsCache = nil
c.modelsCacheMux.Unlock()
c.state = StateDisconnected
if !c.isExternalServer {
c.actualPort = 0
}
c.RPC = nil
return errors.Join(errs...)
}
// ForceStop forcefully stops the CLI server without graceful cleanup.
//
// Use this when [Client.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
// done := make(chan struct{})
// go func() {
// client.Stop()
// close(done)
// }()
//
// select {
// case <-done:
// // Stopped successfully
// case <-time.After(5 * time.Second):
// client.ForceStop()
// }
func (c *Client) ForceStop() {
// Kill the process without waiting for startStopMux, which Start may hold.
// This unblocks any I/O Start is doing (connect, version check).
if p := c.osProcess.Swap(nil); p != nil {
p.Kill()
}
// Clear sessions immediately without trying to destroy them
c.sessionsMux.Lock()
c.sessions = make(map[string]*Session)
c.sessionsMux.Unlock()
c.startStopMux.Lock()
defer c.startStopMux.Unlock()
// Kill CLI process (only if we spawned it)
// This is a fallback in case the process wasn't killed above (e.g. if Start hadn't set
// osProcess yet), or if the process was restarted and osProcess now points to a new process.
if c.process != nil && !c.isExternalServer {
_ = c.killProcess() // Ignore errors since we're force stopping
}
c.process = nil
// Close external TCP connection if exists
if c.isExternalServer && c.conn != nil {
_ = c.conn.Close() // Ignore errors
c.conn = nil
}
// Close JSON-RPC client
if c.client != nil {
c.client.Stop()
c.client = nil
}
// Clear models cache
c.modelsCacheMux.Lock()
c.modelsCache = nil
c.modelsCacheMux.Unlock()
c.state = StateDisconnected
if !c.isExternalServer {
c.actualPort = 0
}
c.RPC = nil
}
func (c *Client) ensureConnected() error {
if c.client != nil {
return nil
}
if c.autoStart {
return c.Start(context.Background())
}
return fmt.Errorf("client not connected. Call Start() first")
}
// CreateSession creates 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 AutoStart is enabled, this will automatically
// start the connection.
//
// The config parameter is required and must include an OnPermissionRequest handler.
//
// Returns the created session or an error if session creation fails.
//
// Example:
//
// // Basic session
// session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
// OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
// })
//
// // Session with model and tools
// session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
// OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
// Model: "gpt-4",
// Tools: []copilot.Tool{
// {
// Name: "get_weather",
// Description: "Get weather for a location",
// Handler: weatherHandler,
// },
// },
// })
func (c *Client) CreateSession(ctx context.Context, config *SessionConfig) (*Session, error) {
if config == nil || config.OnPermissionRequest == nil {
return nil, fmt.Errorf("an OnPermissionRequest handler is required when creating a session. For example, to allow all permissions, use &copilot.SessionConfig{OnPermissionRequest: copilot.PermissionHandler.ApproveAll}")
}
if err := c.ensureConnected(); err != nil {
return nil, err
}
req := createSessionRequest{}
req.Model = config.Model
req.SessionID = config.SessionID
req.ClientName = config.ClientName
req.ReasoningEffort = config.ReasoningEffort
req.ConfigDir = config.ConfigDir
req.Tools = config.Tools
req.SystemMessage = config.SystemMessage
req.AvailableTools = config.AvailableTools
req.ExcludedTools = config.ExcludedTools
req.Provider = config.Provider
req.WorkingDirectory = config.WorkingDirectory
req.MCPServers = config.MCPServers
req.EnvValueMode = "direct"
req.CustomAgents = config.CustomAgents
req.SkillDirectories = config.SkillDirectories
req.DisabledSkills = config.DisabledSkills
req.InfiniteSessions = config.InfiniteSessions
if config.Streaming {
req.Streaming = Bool(true)
}
if config.OnUserInputRequest != nil {
req.RequestUserInput = Bool(true)
}
if config.Hooks != nil && (config.Hooks.OnPreToolUse != nil ||
config.Hooks.OnPostToolUse != nil ||
config.Hooks.OnUserPromptSubmitted != nil ||
config.Hooks.OnSessionStart != nil ||
config.Hooks.OnSessionEnd != nil ||
config.Hooks.OnErrorOccurred != nil) {
req.Hooks = Bool(true)
}
req.RequestPermission = Bool(true)
result, err := c.client.Request("session.create", req)
if err != nil {
return nil, fmt.Errorf("failed to create session: %w", err)
}
var response createSessionResponse
if err := json.Unmarshal(result, &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal response: %w", err)
}
session := newSession(response.SessionID, c.client, response.WorkspacePath)
session.registerTools(config.Tools)
session.registerPermissionHandler(config.OnPermissionRequest)
if config.OnUserInputRequest != nil {
session.registerUserInputHandler(config.OnUserInputRequest)
}
if config.Hooks != nil {
session.registerHooks(config.Hooks)
}
c.sessionsMux.Lock()
c.sessions[response.SessionID] = session
c.sessionsMux.Unlock()
return session, nil
}
// ResumeSession resumes an existing conversation session by its ID.
//
// This is a convenience method that calls [Client.ResumeSessionWithOptions].
// The config must include an OnPermissionRequest handler.
//
// Example:
//
// session, err := client.ResumeSession(context.Background(), "session-123", &copilot.ResumeSessionConfig{
// OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
// })
func (c *Client) ResumeSession(ctx context.Context, sessionID string, config *ResumeSessionConfig) (*Session, error) {
return c.ResumeSessionWithOptions(ctx, sessionID, config)
}
// ResumeSessionWithOptions resumes an existing conversation session with additional configuration.
//
// This allows you to continue a previous conversation, maintaining all conversation history.
// The session must have been previously created and not deleted.
//
// Example:
//
// session, err := client.ResumeSessionWithOptions(context.Background(), "session-123", &copilot.ResumeSessionConfig{
// OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
// Tools: []copilot.Tool{myNewTool},
// })
func (c *Client) ResumeSessionWithOptions(ctx context.Context, sessionID string, config *ResumeSessionConfig) (*Session, error) {
if config == nil || config.OnPermissionRequest == nil {
return nil, fmt.Errorf("an OnPermissionRequest handler is required when resuming a session. For example, to allow all permissions, use &copilot.ResumeSessionConfig{OnPermissionRequest: copilot.PermissionHandler.ApproveAll}")
}
if err := c.ensureConnected(); err != nil {
return nil, err
}
var req resumeSessionRequest
req.SessionID = sessionID
req.ClientName = config.ClientName
req.Model = config.Model
req.ReasoningEffort = config.ReasoningEffort
req.SystemMessage = config.SystemMessage
req.Tools = config.Tools
req.Provider = config.Provider
req.AvailableTools = config.AvailableTools
req.ExcludedTools = config.ExcludedTools
if config.Streaming {
req.Streaming = Bool(true)
}
if config.OnUserInputRequest != nil {
req.RequestUserInput = Bool(true)
}
if config.Hooks != nil && (config.Hooks.OnPreToolUse != nil ||
config.Hooks.OnPostToolUse != nil ||
config.Hooks.OnUserPromptSubmitted != nil ||
config.Hooks.OnSessionStart != nil ||
config.Hooks.OnSessionEnd != nil ||
config.Hooks.OnErrorOccurred != nil) {
req.Hooks = Bool(true)
}
req.WorkingDirectory = config.WorkingDirectory
req.ConfigDir = config.ConfigDir
if config.DisableResume {
req.DisableResume = Bool(true)
}
req.MCPServers = config.MCPServers
req.EnvValueMode = "direct"
req.CustomAgents = config.CustomAgents
req.SkillDirectories = config.SkillDirectories
req.DisabledSkills = config.DisabledSkills
req.InfiniteSessions = config.InfiniteSessions
req.RequestPermission = Bool(true)
result, err := c.client.Request("session.resume", req)
if err != nil {
return nil, fmt.Errorf("failed to resume session: %w", err)
}
var response resumeSessionResponse
if err := json.Unmarshal(result, &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal response: %w", err)
}
session := newSession(response.SessionID, c.client, response.WorkspacePath)
session.registerTools(config.Tools)
session.registerPermissionHandler(config.OnPermissionRequest)
if config.OnUserInputRequest != nil {
session.registerUserInputHandler(config.OnUserInputRequest)
}
if config.Hooks != nil {
session.registerHooks(config.Hooks)
}
c.sessionsMux.Lock()
c.sessions[response.SessionID] = session
c.sessionsMux.Unlock()
return session, nil
}
// ListSessions returns metadata about all sessions known to the server.
//
// Returns a list of SessionMetadata for all available sessions, including their IDs,
// timestamps, optional summaries, and context information.
//
// An optional filter can be provided to filter sessions by cwd, git root, repository, or branch.
//
// Example:
//
// sessions, err := client.ListSessions(context.Background(), nil)
// if err != nil {
// log.Fatal(err)
// }
// for _, session := range sessions {
// fmt.Printf("Session: %s\n", session.SessionID)
// }
//
// Example with filter:
//
// sessions, err := client.ListSessions(context.Background(), &SessionListFilter{Repository: "owner/repo"})
func (c *Client) ListSessions(ctx context.Context, filter *SessionListFilter) ([]SessionMetadata, error) {
if err := c.ensureConnected(); err != nil {
return nil, err
}
params := listSessionsRequest{}
if filter != nil {
params.Filter = filter
}
result, err := c.client.Request("session.list", params)
if err != nil {
return nil, err
}
var response listSessionsResponse
if err := json.Unmarshal(result, &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal sessions response: %w", err)
}
return response.Sessions, nil
}
// DeleteSession permanently deletes a session and all its conversation history.
//
// The session cannot be resumed after deletion. If the session is in the local
// sessions map, it will be removed.
//
// Example:
//
// if err := client.DeleteSession(context.Background(), "session-123"); err != nil {
// log.Fatal(err)
// }
func (c *Client) DeleteSession(ctx context.Context, sessionID string) error {
if err := c.ensureConnected(); err != nil {
return err
}
result, err := c.client.Request("session.delete", deleteSessionRequest{SessionID: sessionID})
if err != nil {
return err
}
var response deleteSessionResponse
if err := json.Unmarshal(result, &response); err != nil {
return fmt.Errorf("failed to unmarshal delete response: %w", err)
}
if !response.Success {
errorMsg := "unknown error"
if response.Error != nil {
errorMsg = *response.Error
}
return fmt.Errorf("failed to delete session %s: %s", sessionID, errorMsg)
}
// Remove from local sessions map if present
c.sessionsMux.Lock()
delete(c.sessions, sessionID)
c.sessionsMux.Unlock()
return nil
}
// GetForegroundSessionID returns 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 nil if no foreground session is set.
//
// Example:
//
// sessionID, err := client.GetForegroundSessionID()
// if err != nil {
// log.Fatal(err)
// }
// if sessionID != nil {
// fmt.Printf("TUI is displaying session: %s\n", *sessionID)
// }
func (c *Client) GetForegroundSessionID(ctx context.Context) (*string, error) {
if c.client == nil {
if c.autoStart {
if err := c.Start(ctx); err != nil {
return nil, err
}
} else {
return nil, fmt.Errorf("client not connected. Call Start() first")
}
}
result, err := c.client.Request("session.getForeground", getForegroundSessionRequest{})
if err != nil {
return nil, err
}
var response getForegroundSessionResponse
if err := json.Unmarshal(result, &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal getForeground response: %w", err)
}
return response.SessionID, nil
}
// SetForegroundSessionID requests 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).
//
// Example:
//
// if err := client.SetForegroundSessionID("session-123"); err != nil {
// log.Fatal(err)
// }
func (c *Client) SetForegroundSessionID(ctx context.Context, sessionID string) error {
if c.client == nil {
if c.autoStart {
if err := c.Start(ctx); err != nil {
return err
}
} else {
return fmt.Errorf("client not connected. Call Start() first")
}
}
result, err := c.client.Request("session.setForeground", setForegroundSessionRequest{SessionID: sessionID})
if err != nil {
return err
}
var response setForegroundSessionResponse
if err := json.Unmarshal(result, &response); err != nil {
return fmt.Errorf("failed to unmarshal setForeground response: %w", err)
}
if !response.Success {
errorMsg := "unknown error"
if response.Error != nil {
errorMsg = *response.Error
}
return fmt.Errorf("failed to set foreground session: %s", errorMsg)
}
return nil
}
// On subscribes to all session lifecycle events.
//
// Lifecycle events are emitted when sessions are created, deleted, updated,
// or change foreground/background state (in TUI+server mode).
//
// Returns a function that, when called, unsubscribes the handler.
//
// Example:
//
// unsubscribe := client.On(func(event copilot.SessionLifecycleEvent) {
// fmt.Printf("Session %s: %s\n", event.SessionID, event.Type)
// })
// defer unsubscribe()
func (c *Client) On(handler SessionLifecycleHandler) func() {
c.lifecycleHandlersMux.Lock()
c.lifecycleHandlers = append(c.lifecycleHandlers, handler)
c.lifecycleHandlersMux.Unlock()
return func() {
c.lifecycleHandlersMux.Lock()
defer c.lifecycleHandlersMux.Unlock()
for i, h := range c.lifecycleHandlers {
// Compare function pointers
if &h == &handler {
c.lifecycleHandlers = append(c.lifecycleHandlers[:i], c.lifecycleHandlers[i+1:]...)
break
}
}
}
}
// OnEventType subscribes to a specific session lifecycle event type.
//
// Returns a function that, when called, unsubscribes the handler.
//
// Example:
//
// unsubscribe := client.OnEventType(copilot.SessionLifecycleForeground, func(event copilot.SessionLifecycleEvent) {
// fmt.Printf("Session %s is now in foreground\n", event.SessionID)
// })
// defer unsubscribe()
func (c *Client) OnEventType(eventType SessionLifecycleEventType, handler SessionLifecycleHandler) func() {
c.lifecycleHandlersMux.Lock()
if c.typedLifecycleHandlers == nil {
c.typedLifecycleHandlers = make(map[SessionLifecycleEventType][]SessionLifecycleHandler)
}
c.typedLifecycleHandlers[eventType] = append(c.typedLifecycleHandlers[eventType], handler)
c.lifecycleHandlersMux.Unlock()
return func() {
c.lifecycleHandlersMux.Lock()
defer c.lifecycleHandlersMux.Unlock()
handlers := c.typedLifecycleHandlers[eventType]
for i, h := range handlers {
if &h == &handler {
c.typedLifecycleHandlers[eventType] = append(handlers[:i], handlers[i+1:]...)
break
}
}
}
}
// handleLifecycleEvent dispatches a lifecycle event to all registered handlers
func (c *Client) handleLifecycleEvent(event SessionLifecycleEvent) {
c.lifecycleHandlersMux.Lock()
// Copy handlers to avoid holding lock during callbacks
typedHandlers := make([]SessionLifecycleHandler, 0)
if handlers, ok := c.typedLifecycleHandlers[event.Type]; ok {
typedHandlers = append(typedHandlers, handlers...)
}
wildcardHandlers := make([]SessionLifecycleHandler, len(c.lifecycleHandlers))
copy(wildcardHandlers, c.lifecycleHandlers)
c.lifecycleHandlersMux.Unlock()
// Dispatch to typed handlers
for _, handler := range typedHandlers {
func() {
defer func() { recover() }() // Ignore handler panics
handler(event)
}()
}
// Dispatch to wildcard handlers
for _, handler := range wildcardHandlers {
func() {
defer func() { recover() }() // Ignore handler panics
handler(event)
}()
}
}
// State returns the current connection state of the client.
//
// Possible states: StateDisconnected, StateConnecting, StateConnected, StateError.
//
// Example:
//
// if client.State() == copilot.StateConnected {
// session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
// OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
// })
// }
func (c *Client) State() ConnectionState {
c.startStopMux.RLock()
defer c.startStopMux.RUnlock()
return c.state
}
// Ping sends a ping request to the server to verify connectivity.
//
// The message parameter is optional and will be echoed back in the response.
// Returns a PingResponse containing the message and server timestamp, or an error.
//
// Example:
//
// resp, err := client.Ping(context.Background(), "health check")
// if err != nil {
// log.Printf("Server unreachable: %v", err)
// } else {
// log.Printf("Server responded at %d", resp.Timestamp)
// }
func (c *Client) Ping(ctx context.Context, message string) (*PingResponse, error) {
if c.client == nil {
return nil, fmt.Errorf("client not connected")
}
result, err := c.client.Request("ping", pingRequest{Message: message})
if err != nil {
return nil, err
}
var response PingResponse
if err := json.Unmarshal(result, &response); err != nil {
return nil, err
}
return &response, nil
}
// GetStatus returns CLI status including version and protocol information
func (c *Client) GetStatus(ctx context.Context) (*GetStatusResponse, error) {
if c.client == nil {
return nil, fmt.Errorf("client not connected")
}
result, err := c.client.Request("status.get", getStatusRequest{})
if err != nil {
return nil, err
}
var response GetStatusResponse
if err := json.Unmarshal(result, &response); err != nil {
return nil, err
}
return &response, nil
}
// GetAuthStatus returns current authentication status
func (c *Client) GetAuthStatus(ctx context.Context) (*GetAuthStatusResponse, error) {
if c.client == nil {
return nil, fmt.Errorf("client not connected")
}
result, err := c.client.Request("auth.getStatus", getAuthStatusRequest{})
if err != nil {
return nil, err
}
var response GetAuthStatusResponse
if err := json.Unmarshal(result, &response); err != nil {
return nil, err
}
return &response, nil
}
// ListModels returns 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.
func (c *Client) ListModels(ctx context.Context) ([]ModelInfo, error) {
if c.client == nil {
return nil, fmt.Errorf("client not connected")
}
// Use mutex for locking to prevent race condition with concurrent calls
c.modelsCacheMux.Lock()
defer c.modelsCacheMux.Unlock()
// Check cache (already inside lock)
if c.modelsCache != nil {
// Return a copy to prevent cache mutation
result := make([]ModelInfo, len(c.modelsCache))
copy(result, c.modelsCache)