Repository navigation
Expand file tree
/
Copy pathclient.go
More file actions
4336 lines (3987 loc) · 149 KB
/
Copy pathclient.go
File metadata and controls
4336 lines (3987 loc) · 149 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-5.4",
// })
// if err != nil {
// log.Fatal(err)
// }
//
// session.On(func(event copilot.SessionEvent) {
// if d, ok := event.Data.(*copilot.AssistantMessageData); ok {
// fmt.Println(d.Content)
// }
// })
//
// session.Send(copilot.MessageOptions{Prompt: "Hello!"})
package copilot
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"net/netip"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"unicode/utf8"
"github.com/google/uuid"
"github.com/github/copilot-sdk/go/internal/embeddedcli"
"github.com/github/copilot-sdk/go/internal/jsonrpc2"
"github.com/github/copilot-sdk/go/internal/truncbuffer"
"github.com/github/copilot-sdk/go/rpc"
)
// defaultBearerTokenProviderName is the implicit provider name for the singular,
// whole-session [ProviderConfig]. Named providers are keyed by their own Name.
const defaultBearerTokenProviderName = "default"
type cloudSkillProviderError struct{}
func (cloudSkillProviderError) Error() string {
return "Skill providers are not supported for cloud sessions."
}
type disabledMemoryStoreError struct{}
func (disabledMemoryStoreError) Error() string {
return "StoreMemory requires Memory.Enabled to be true."
}
type cloudMemoryStoreError struct{}
func (cloudMemoryStoreError) Error() string {
return "Memory stores are not supported for cloud sessions."
}
// requestedMemoryStore returns the memory store callback, failing when it is
// set without enabling memory.
func requestedMemoryStore(
memory *MemoryConfiguration,
store func(context.Context, StoredMemory) error,
) (func(context.Context, StoredMemory) error, error) {
if store == nil {
return nil, nil
}
if memory == nil || !memory.Enabled {
return nil, disabledMemoryStoreError{}
}
return store, nil
}
// collectBearerTokenProviders gathers the per-provider [BearerTokenProvider] callbacks
// from the singular provider and any named providers, keyed by provider name. The
// singular provider uses the implicit name "default"; named providers use their
// own Name. Returns nil when no callbacks are configured.
func collectBearerTokenProviders(provider *ProviderConfig, providers []NamedProviderConfig) map[string]BearerTokenProvider {
callbacks := make(map[string]BearerTokenProvider)
if provider != nil && provider.BearerTokenProvider != nil {
callbacks[defaultBearerTokenProviderName] = provider.BearerTokenProvider
}
for i := range providers {
if providers[i].BearerTokenProvider != nil {
callbacks[providers[i].Name] = providers[i].BearerTokenProvider
}
}
if len(callbacks) == 0 {
return nil
}
return callbacks
}
func validateSessionFSConfig(config *SessionFSConfig) error {
if config == nil {
return nil
}
if config.InitialWorkingDirectory == "" {
return errors.New("SessionFS.InitialWorkingDirectory is required")
}
if config.SessionStatePath == "" {
return errors.New("SessionFS.SessionStatePath is required")
}
if config.Conventions != rpc.SessionFSSetProviderConventionsPosix && config.Conventions != rpc.SessionFSSetProviderConventionsWindows {
return errors.New("SessionFS.Conventions must be either 'posix' or 'windows'")
}
return nil
}
// validateEnvironmentOptions enforces the transport-specific rules for
// per-client environment, working directory, and telemetry. It panics (fails
// loud) on a misconfiguration, matching the other SDKs.
//
// In-process hosts share the process environment and working directory.
// Child-process transports accept environment at
// either the client or connection level, not both.
func validateEnvironmentOptions(connection RuntimeConnection, opts *ClientOptions) {
if _, ok := connection.(InProcessConnection); ok {
if opts.Env != nil {
panic("Env is not supported with InProcessConnection: environment variables belong to the shared host process. Use typed client/session options or a child-process transport.")
}
if opts.WorkingDirectory != "" {
panic("WorkingDirectory is not supported with InProcessConnection: the native runtime shares the host process working directory. Set SessionConfig.WorkingDirectory instead.")
}
if opts.Telemetry != nil && !utf8.ValidString(opts.Telemetry.FilePath) {
panic("Telemetry.FilePath must be valid UTF-8 with InProcessConnection")
}
return
}
if cp, ok := connection.(childProcessConnection); ok {
if cp.connEnv() != nil && opts.Env != nil {
panic("Set environment variables via either the client-level Env option or the connection's Env, not both. Prefer the connection-level Env for child-process transports.")
}
}
}
// 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{
// Connection: copilot.URIConnection{URL: "localhost:3000"},
// })
//
// if err := client.Start(); err != nil {
// log.Fatal(err)
// }
// defer client.Stop()
type Client struct {
options ClientOptions
process *exec.Cmd
processStdin io.WriteCloser
client *jsonrpc2.Client
actualPort atomic.Int64 // read by RuntimePort without startStopMux
actualHost string
state connectionState
sessions map[string]*Session
sessionsMux sync.Mutex
sessionsGeneration uint64
autoModeRecoveryCleanups map[*jsonrpc2.Client]map[string]<-chan struct{}
pendingShellAuthenticationRequests map[shellAuthenticationKey][]*shellAuthenticationTicket
pendingShellAuthenticationRequestsMux sync.Mutex
ahp ahpHostState
gitHubTokenProviders map[string]GitHubTokenProvider
gitHubTokenProvidersMux sync.RWMutex
requestAdapter *copilotRequestAdapter
requestAdapterMux sync.Mutex
installationConfirmationAdapter *installationConfirmationAdapter
installationConfirmationAdapterMux sync.Mutex
sessionOperations map[string]*sessionOperation
sessionOperationsMux sync.Mutex
activeSessionCallbacks map[string]int
isExternalServer bool
conn net.Conn // stores net.Conn for external TCP connections
useStdio bool // resolved value from options
useInProcess bool // true for InProcessConnection (FFI transport)
ffiHost inProcessHost
runOnUiThread func(action func() error) error
// resolved process options for the spawned runtime (zero values for URIConnection)
cliPath string
cliArgs []string
port int
tcpConnectionToken string
modelsCache []ModelInfo
modelsCacheMux sync.Mutex
lifecycleHandlers map[uint64]SessionLifecycleHandler
typedLifecycleHandlers map[SessionLifecycleEventType]map[uint64]SessionLifecycleHandler
nextLifecycleHandlerID uint64
lifecycleHandlersMux sync.Mutex
startStopMux sync.RWMutex // protects process and state during start/[force]stop
transportMux sync.Mutex // guards startup and transport visibility outside startStopMux; see ensureConnected
startup *startupAttempt
testHookTransportAcquired func() // tests only: runs after ensureConnected acquires a transport
processDone chan struct{}
processErrorPtr *error
osProcess atomic.Pointer[os.Process]
negotiatedProtocolVersion int
// effectiveConnectionToken is the token sent in `connect`; auto-generated when
// the SDK spawns its own CLI in TCP mode.
effectiveConnectionToken string
onListModels func(ctx context.Context) ([]ModelInfo, error)
// RPC provides typed server-scoped RPC methods.
// This field is nil until the client is connected via Start().
RPC *rpc.ServerRPC
// internalRPC provides SDK-internal RPC methods (handshake helpers etc.).
// Lowercase = not exported; external callers cannot reach it.
internalRPC *rpc.InternalServerRPC
}
type sessionOperation struct {
permit chan struct{}
users int
}
// NewClient creates a new Copilot runtime client with the given options.
//
// If options is nil, default options are used (spawns the bundled runtime over
// stdio). The client is not connected after creation; call [Client.Start] to
// connect, or simply call [Client.CreateSession]/[Client.ResumeSession], which
// auto-start the runtime on first use.
//
// Example:
//
// // Default options: bundled runtime over stdio
// client := copilot.NewClient(nil)
//
// // Custom CLI path over stdio
// client := copilot.NewClient(&copilot.ClientOptions{
// Connection: copilot.StdioConnection{Path: "/usr/local/bin/copilot"},
// LogLevel: "debug",
// })
//
// // Connect to an already-running runtime
// client := copilot.NewClient(&copilot.ClientOptions{
// Connection: copilot.URIConnection{URL: "localhost:8080"},
// })
func NewClient(options *ClientOptions) *Client {
opts := ClientOptions{}
client := &Client{
options: opts,
state: stateDisconnected,
sessions: make(map[string]*Session),
gitHubTokenProviders: make(map[string]GitHubTokenProvider),
actualHost: "localhost",
isExternalServer: false,
useStdio: true,
}
if options != nil {
opts = *options
}
for _, path := range opts.BuiltinPluginDirectories {
if !filepath.IsAbs(path) {
panic(fmt.Sprintf("BuiltinPluginDirectories must contain only absolute paths: %s", path))
}
}
opts.BuiltinPluginDirectories = append([]string(nil), opts.BuiltinPluginDirectories...)
// Resolve the connection. An explicit connection always wins; otherwise
// honor the same process/environment override as the other SDKs.
connection := opts.Connection
if connection == nil {
env := opts.Env
if env == nil {
env = os.Environ()
}
connection = resolveDefaultConnection(env)
}
switch conn := connection.(type) {
case StdioConnection:
client.useStdio = true
client.cliPath = conn.Path
if len(conn.Args) > 0 {
client.cliArgs = append([]string{}, conn.Args...)
}
case TCPConnection:
client.useStdio = false
client.cliPath = conn.Path
if len(conn.Args) > 0 {
client.cliArgs = append([]string{}, conn.Args...)
}
client.port = conn.Port
client.tcpConnectionToken = conn.ConnectionToken
case URIConnection:
if conn.URL == "" {
panic("URIConnection requires a non-empty URL")
}
host, port := parseCLIURL(conn.URL)
client.actualHost = host
client.actualPort.Store(int64(port))
client.isExternalServer = true
client.useStdio = false
client.tcpConnectionToken = conn.ConnectionToken
case InProcessConnection:
client.useStdio = false
client.useInProcess = true
client.runOnUiThread = conn.RunOnUiThread
if opts.Telemetry != nil {
telemetry := *opts.Telemetry
if telemetry.CaptureContent != nil {
telemetry.CaptureContent = Bool(*telemetry.CaptureContent)
}
opts.Telemetry = &telemetry
}
default:
panic(fmt.Sprintf("unknown RuntimeConnection type: %T", connection))
}
// Validate transport-specific option constraints before resolving defaults.
validateEnvironmentOptions(connection, &opts)
// Validate auth options when connecting to an external runtime.
if client.isExternalServer && (opts.GitHubToken != "" || opts.UseLoggedInUser != nil) {
panic("GitHubToken and UseLoggedInUser cannot be used with URIConnection (external runtime manages its own auth)")
}
if client.isExternalServer && opts.InternalTestOptions != nil {
panic("InternalTestOptions requires a runtime owned by this client")
}
// For child-process transports, a connection-level env takes precedence over
// the client-level env (setting both was rejected above). Resolve it before
// defaulting so an explicit empty connection env stays authoritative.
if cp, ok := connection.(childProcessConnection); ok {
if env := cp.connEnv(); env != nil {
opts.Env = env
}
}
// Default Env to current environment if not set
if opts.Env == nil {
opts.Env = os.Environ()
}
opts.Env = append([]string{}, opts.Env...)
// Check the effective environment for a child-process runtime override.
if client.cliPath == "" && !client.useInProcess {
if cliPath := getEnvValue(opts.Env, "COPILOT_CLI_PATH"); cliPath != "" {
client.cliPath = cliPath
}
}
// Resolve the effective connection token: explicit value if set; else if the SDK
// spawns its own runtime in TCP mode, generate a UUID; otherwise empty. The
// in-process transport uses no socket, so it needs no connection token.
if client.tcpConnectionToken != "" {
client.effectiveConnectionToken = client.tcpConnectionToken
} else if !client.useStdio && !client.isExternalServer && !client.useInProcess {
client.effectiveConnectionToken = uuid.NewString()
}
if opts.OnListModels != nil {
client.onListModels = opts.OnListModels
}
if opts.SessionFS != nil {
if err := validateSessionFSConfig(opts.SessionFS); err != nil {
panic(err.Error())
}
}
if opts.Network != nil {
// Copy so later changes by the caller cannot make the registration and
// the installed handlers disagree.
network := *opts.Network
opts.Network = &network
}
client.options = opts
validateNewClientForMode(&client.options)
return client
}
func resolveRuntimeExecutable(explicitPath, bundledRuntimePath string) (string, error) {
if explicitPath != "" {
return explicitPath, nil
}
if bundledRuntimePath == "" {
return "", errors.New(
"managed Copilot runtime unavailable: the embedded bundle does not contain copilot-runtime and adjacent runtime.node; regenerate the bundle, provide an explicit path, or set COPILOT_CLI_PATH",
)
}
return bundledRuntimePath, nil
}
const defaultConnectionEnvVar = "COPILOT_SDK_DEFAULT_CONNECTION"
// resolveDefaultConnection selects the transport when no explicit connection
// was supplied. The override is primarily used by hosts and the E2E transport
// matrix; explicit connection options always take precedence.
func resolveDefaultConnection(env []string) RuntimeConnection {
value := getEnvValue(env, defaultConnectionEnvVar)
switch {
case value == "", strings.EqualFold(value, "stdio"):
return StdioConnection{}
case strings.EqualFold(value, "inprocess"):
return InProcessConnection{}
default:
panic(fmt.Sprintf(
"invalid %s value %q: expected \"inprocess\", \"stdio\", or unset",
defaultConnectionEnvVar,
value,
))
}
}
// getEnvValue looks up a key in an environment slice ([]string of "KEY=VALUE").
// Returns the value if found, or empty string otherwise.
func getEnvValue(env []string, key string) string {
prefix := key + "="
for i := len(env) - 1; i >= 0; i-- {
if strings.HasPrefix(env[i], prefix) {
return env[i][len(prefix):]
}
}
return ""
}
// setEnvValue returns a copy of env with all existing entries for key removed and
// a single trailing KEY=VALUE entry added so SDK-managed values win deterministically.
func setEnvValue(env []string, key string, value string) []string {
prefix := key + "="
filtered := make([]string, 0, len(env)+1)
for _, entry := range env {
if !strings.HasPrefix(entry, prefix) {
filtered = append(filtered, entry)
}
}
return append(filtered, key+"="+value)
}
// parseCLIURL parses a CLI URL into host and port components.
//
// Supports raw TCP addresses: "host:port", "[ipv6]:port", "http://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) {
if strings.HasPrefix(strings.ToLower(url), "https://") {
panic("HTTPS runtime connections are not supported: this transport uses plaintext TCP, not TLS")
}
// Remove protocol if present
cleanURL, _ := strings.CutPrefix(url, "http://")
// Use the standard parser only for the bracketed IPv6 form. Keep the
// existing host:port parsing behavior for all other inputs.
if strings.HasPrefix(cleanURL, "[") {
host, portStr, err := net.SplitHostPort(cleanURL)
if err != nil {
panic(fmt.Sprintf("Invalid port in URIConnection: %s", url))
}
addr, err := netip.ParseAddr(host)
if err != nil || !addr.Is6() {
panic(fmt.Sprintf("Invalid URIConnection format: %s", url))
}
port, err := strconv.Atoi(portStr)
if err != nil || port <= 0 || port > 65535 {
panic(fmt.Sprintf("Invalid port in URIConnection: %s", url))
}
return host, port
}
// 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 {
portStr = cleanURL
}
if host == "" {
host = "localhost"
}
port, err := strconv.Atoi(portStr)
if err != nil || port <= 0 || port > 65535 {
panic(fmt.Sprintf("Invalid port in URIConnection: %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 URIConnection), only establishes the connection.
// Otherwise, spawns the CLI server process and then connects.
//
// CreateSession and ResumeSession call this method automatically when the client is not connected.
// Operations called while Start is in progress wait for it and fail with its
// error if it fails.
//
// Returns an error if the server fails to start or the connection fails.
//
// Example:
//
// client := copilot.NewClient(nil)
// 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) (err error) {
c.startStopMux.Lock()
defer c.startStopMux.Unlock()
if c.state == stateConnected && c.client != nil {
select {
case <-c.client.ConnectionClosed():
// The close callback may still be waiting to publish disconnected state.
case <-c.processDone:
// The runtime exited and requests already fail with its exit error,
// but the reader may still be running a handler and has not reached
// the end of the stream to close the connection.
default:
return nil
}
}
if c.client != nil {
if err := c.killProcessAndWait(); err != nil {
return fmt.Errorf("failed to retire previous runtime: %w", err)
}
// Nothing listens on the retired runtime's port any more.
if !c.isExternalServer {
c.actualPort.Store(0)
}
// Do not join the lost connection's reader: the caller may be a handler
// on it, such as a lifecycle listener that saw a request fail when the
// runtime exited. The reader exits once that handler returns.
c.client.Close()
// Sessions are bound to the lost connection, so the new one cannot
// serve them; retire them as ForceStop does so their waiters fail now.
c.disconnectAhpHosts()
c.retireSessionsLocally()
}
// Publish startup before creating the transport and while holding
// startStopMux, so ensureConnected never observes a partially started
// transport and never waits on startup while Stop holds the lock.
startup := &startupAttempt{done: make(chan struct{})}
c.transportMux.Lock()
c.startup = startup
c.transportMux.Unlock()
defer func() {
c.transportMux.Lock()
c.startup = nil
c.transportMux.Unlock()
startup.finish(err)
}()
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()
if !c.isExternalServer {
c.actualPort.Store(0)
}
c.state = stateError
return errors.Join(err, killErr)
}
if err := c.initializeConnection(ctx); err != nil {
// Fail waiting operations first: one may be a handler on the reader that
// closing the connection joins.
startup.finish(err)
// The runtime keeps registrations made on this connection, such as an
// exclusive runtime-scoped network callback claim, until it closes, so
// close it on any failure.
c.client.Stop()
c.client = nil
c.conn = nil
c.RPC = nil
c.internalRPC = nil
killErr := c.killProcess()
if !c.isExternalServer {
c.actualPort.Store(0)
}
c.state = stateError
return errors.Join(err, killErr)
}
c.state = stateConnected
return nil
}
// initializeConnection verifies the protocol version and registers the
// client's providers on a new connection.
func (c *Client) initializeConnection(ctx context.Context) error {
// Verify protocol version compatibility
if err := c.verifyProtocolVersion(ctx); err != nil {
return err
}
if request := networkSetProviderRequest(c.options.Network); request != nil {
if _, err := c.RPC.Network.SetProvider(ctx, request); err != nil {
return err
}
}
if c.options.ExtensionLaunchProvider != nil {
if _, err := c.RPC.RegisterExtensionLaunchProvider(ctx); err != nil {
return err
}
}
if len(c.options.BuiltinPluginDirectories) > 0 {
if _, err := c.client.Request(ctx, "plugins.builtin.set", map[string]any{
"paths": c.options.BuiltinPluginDirectories,
}); err != nil {
return err
}
}
// If a session filesystem provider was configured, register it.
if c.options.SessionFS != nil {
req := &rpc.SessionFSSetProviderRequest{
InitialCwd: c.options.SessionFS.InitialWorkingDirectory,
SessionStatePath: c.options.SessionFS.SessionStatePath,
Conventions: c.options.SessionFS.Conventions,
}
if c.options.SessionFS.Capabilities != nil {
sqlite := c.options.SessionFS.Capabilities.Sqlite
binary := c.options.SessionFS.Capabilities.Binary
req.Capabilities = &rpc.SessionFSSetProviderCapabilities{
Sqlite: &sqlite,
Binary: &binary,
}
if c.options.SessionFS.Capabilities.ReadFileRange {
readFileRange := true
req.Capabilities.ReadFileRange = &readFileRange
}
}
_, err := c.RPC.SessionFS.SetProvider(ctx, req)
if err != nil {
return err
}
}
// If a request handler was configured, register as the inference provider.
if c.options.RequestHandler != nil {
if _, err := c.RPC.LlmInference.SetProvider(ctx); err != nil {
return err
}
}
return nil
}
// Stop stops the CLI server and closes all active sessions.
//
// This method performs graceful cleanup:
// 1. Closes all active sessions (releases in-memory resources); detach requests
// share one 10 second timeout, so an unresponsive runtime cannot hold the
// remaining steps back
// 2. Requests runtime shutdown for SDK-owned CLI processes
// 3. Closes owned stdio input and waits up to 10 seconds for host cleanup and exit
// 4. Terminates any remaining owned CLI process and closes the JSON-RPC connection
//
// Note: session data on disk is preserved, so sessions can be resumed later.
// To permanently remove session data before stopping, call [Client.DeleteSession]
// for each session first.
//
// 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 {
c.disconnectAhpHosts()
var errs []error
// Failed resumes may restore the resident's callbacks until detach finishes.
c.sessionsMux.Lock()
sessions := make([]*Session, 0, len(c.sessions))
for _, session := range c.sessions {
sessions = append(sessions, session)
}
c.sessionsMux.Unlock()
// A hung runtime never answers session.detach, so every detach shares one
// deadline; past it, Stop moves on to runtime shutdown and termination.
detachCtx, cancelDetach := context.WithTimeout(context.Background(), runtimeShutdownTimeout)
for _, session := range sessions {
if err := session.disconnect(detachCtx); err != nil {
errs = append(errs, fmt.Errorf("failed to disconnect session %s: %w", session.SessionID, err))
}
}
cancelDetach()
c.sessionsMux.Lock()
// Fence later rollback and retire residents restored during graceful detach.
c.sessionsGeneration++
remainingSessions := make([]*Session, 0, len(c.sessions))
for _, session := range c.sessions {
remainingSessions = append(remainingSessions, session)
}
c.sessions = make(map[string]*Session)
c.sessionsMux.Unlock()
for _, session := range remainingSessions {
session.cancelPendingExternalTools()
session.retireEventProcessing(true)
}
c.cancelPendingShellAuthenticationRequests()
c.clearGitHubTokenProviders()
c.closeCopilotRequestAdapter()
c.closeInstallationConfirmationAdapter()
c.startStopMux.Lock()
defer c.startStopMux.Unlock()
if (c.process != nil || c.ffiHost != nil) && !c.isExternalServer && c.RPC != nil {
rpcClient := c.RPC
runtimeShutdownStart := time.Now()
shutdownDone := make(chan error, 1)
go func() {
_, err := rpcClient.Runtime.Shutdown(context.Background())
shutdownDone <- err
}()
select {
case err := <-shutdownDone:
if err != nil {
c.logDebugTiming(runtimeShutdownStart, "CopilotClient.Stop runtime shutdown failed")
errs = append(errs, fmt.Errorf("failed to gracefully shut down runtime: %w", err))
} else {
c.logDebugTiming(runtimeShutdownStart, "CopilotClient.Stop runtime shutdown complete")
}
case <-time.After(runtimeShutdownTimeout):
c.logDebugTiming(runtimeShutdownStart, "CopilotClient.Stop runtime shutdown timed out")
errs = append(errs, fmt.Errorf("timed out gracefully shutting down runtime after %s", runtimeShutdownTimeout))
}
}
// The stdio host finalizes telemetry after EOF, not after runtime.shutdown.
// Keep stdout open while allowing the child to finish that cleanup naturally.
if c.process != nil && !c.isExternalServer && c.processStdin != nil {
processExitStart := time.Now()
if err := c.processStdin.Close(); err != nil && !errors.Is(err, os.ErrClosed) {
errs = append(errs, fmt.Errorf("failed to close CLI stdin: %w", err))
}
c.processStdin = nil
select {
case <-c.processDone:
c.logDebugTiming(processExitStart, "CopilotClient.Stop CLI process exited gracefully")
c.osProcess.Store(nil)
c.process = nil
case <-time.After(processExitTimeout):
c.logDebugTiming(processExitStart, "CopilotClient.Stop CLI process exit timed out; killing process")
}
}
if c.process != nil && !c.isExternalServer {
if err := c.killProcessAndWait(); err != nil {
errs = append(errs, err)
}
}
c.process = nil
// Tear down the in-process FFI host (closes the connection and shuts down the
// native runtime). No child process to reap in this mode.
if c.ffiHost != nil {
c.ffiHost.Dispose()
c.ffiHost = 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.retireTransport()
// Clear models cache
c.modelsCacheMux.Lock()
c.modelsCache = nil
c.modelsCacheMux.Unlock()
c.state = stateDisconnected
if !c.isExternalServer {
c.actualPort.Store(0)
}
return errors.Join(errs...)
}
// retireTransport clears the stopped transport. Callers that passed
// ensureConnected keep their snapshot, whose requests then fail with an error.
func (c *Client) retireTransport() {
c.transportMux.Lock()
defer c.transportMux.Unlock()
c.client = nil
c.RPC = nil
c.internalRPC = nil
}
func (c *Client) logDebugTiming(start time.Time, message string) {
switch strings.ToLower(c.options.LogLevel) {
case "debug", "all":
log.Printf("%s elapsed=%s", message, time.Since(start))
}
}
// 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)
//
// Event processing observes the stop signal before dispatching each remaining
// callback. Callbacks already being dispatched are not awaited and may finish
// after this method returns; an event handler can itself call ForceStop.
// Pending response waits fail when the session is retired, without waiting for
// an idle event or their context deadline.
// Registered session callbacks are released locally, including unadmitted event
// handler entries retained by a dispatch snapshot.
//
// 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() {
c.disconnectAhpHosts()
// 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.retireSessionsLocally()
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
// Dispose the in-process FFI host (if any) without waiting on graceful shutdown.
if c.ffiHost != nil {
c.ffiHost.Dispose()
c.ffiHost = 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.retireTransport()
// Clear models cache
c.modelsCacheMux.Lock()
c.modelsCache = nil
c.modelsCacheMux.Unlock()
c.state = stateDisconnected
if !c.isExternalServer {
c.actualPort.Store(0)
}
}
// retireSessionsLocally removes every session and retires it without
// contacting the runtime: pending waits fail, and registered callbacks and
// connection-scoped handlers are released. It does not wait for event
// callbacks already being dispatched, which may themselves stop the client.
func (c *Client) retireSessionsLocally() {
c.sessionsMux.Lock()
c.sessionsGeneration++
sessions := make([]*Session, 0, len(c.sessions))
for _, session := range c.sessions {
sessions = append(sessions, session)
}
c.sessions = make(map[string]*Session)
c.sessionsMux.Unlock()
c.cancelPendingShellAuthenticationRequests()
for _, session := range sessions {
session.clearSkillProvider()
session.clearMemoryStore()
session.cancelPendingExternalTools()
session.stopEventProcessing()
}
c.clearGitHubTokenProviders()
c.closeCopilotRequestAdapter()
c.closeInstallationConfirmationAdapter()
}
// startupAttempt publishes the outcome of an in-progress Start to the
// operations waiting for it in ensureConnected.
type startupAttempt struct {
done chan struct{} // closed once the outcome is published
err error // the startup failure; written before done is closed
once sync.Once
}
// finish publishes the outcome of the attempt; only the first call has effect.
func (a *startupAttempt) finish(err error) {
a.once.Do(func() {
a.err = err
close(a.done)
})
}
// ensureConnected returns the transport for the caller's requests, waiting for
// an in-progress Start and starting the client when it is disconnected. Callers
// must use the returned client rather than re-reading c.client, which a
// concurrent Stop may retire; a stopped transport fails requests with an error.
//
// transportMux, never held across I/O or while joining the JSON-RPC reader,
// orders this check with transport changes: Start writes the transport while
// startup is set and publishes it by clearing startup, and Stop and ForceStop
// retire it through retireTransport. A failed Start publishes its error before
// closing the transport and keeps startup set until it returns, so callers fail
// with that error instead of restarting the client during its cleanup.
func (c *Client) ensureConnected(ctx context.Context) (*jsonrpc2.Client, error) {
return c.acquireTransport(ctx, true)
}
// connectedTransport is ensureConnected for requests that do not start the
// client: it waits for an in-progress Start, but fails when the client is
// disconnected.
func (c *Client) connectedTransport(ctx context.Context) (*jsonrpc2.Client, error) {
return c.acquireTransport(ctx, false)