-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathclient.go
More file actions
2067 lines (1855 loc) · 64.7 KB
/
Copy pathclient.go
File metadata and controls
2067 lines (1855 loc) · 64.7 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 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"
"net"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"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"
)
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
}
// 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
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
// 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
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
}
// 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),
actualHost: "localhost",
isExternalServer: false,
useStdio: true,
}
if options != nil {
opts = *options
}
// Resolve the connection. nil defaults to an empty StdioConnection.
connection := opts.Connection
if connection == nil {
connection = StdioConnection{}
}
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 = port
client.isExternalServer = true
client.useStdio = false
client.tcpConnectionToken = conn.ConnectionToken
default:
panic(fmt.Sprintf("unknown RuntimeConnection type: %T", connection))
}
// 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)")
}
// Default Env to current environment if not set
if opts.Env == nil {
opts.Env = os.Environ()
}
// Check effective environment for CLI path (only if not explicitly set via options)
if client.cliPath == "" {
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.
if client.tcpConnectionToken != "" {
client.effectiveConnectionToken = client.tcpConnectionToken
} else if !client.useStdio && !client.isExternalServer {
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())
}
}
client.options = opts
validateNewClientForMode(&client.options)
return client
}
// 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 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 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.
//
// 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)
}
// 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
req.Capabilities = &rpc.SessionFSSetProviderCapabilities{
Sqlite: &sqlite,
}
}
_, err := c.RPC.SessionFS.SetProvider(ctx, req)
if 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. Closes all active sessions (releases in-memory resources)
// 2. Closes the JSON-RPC connection
// 3. Terminates the CLI server process (if spawned by this client)
//
// 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 {
var errs []error
// Disconnect 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.Disconnect(); err != nil {
errs = append(errs, fmt.Errorf("failed to disconnect 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
c.internalRPC = 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
c.internalRPC = nil
}
func (c *Client) ensureConnected(ctx context.Context) error {
if c.client != nil {
return nil
}
return c.Start(ctx)
}
// 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, this will automatically start the runtime.
//
// The config parameter is optional. If no OnPermissionRequest handler is provided,
// permission requests are surfaced as events for the caller to resolve manually.
//
// Returns the created session or an error if session creation fails.
//
// Example:
//
// // Basic session
// session, err := client.CreateSession(context.Background(), nil)
//
// // 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,
// },
// },
// })
//
// extractTransformCallbacks separates transform callbacks from a SystemMessageConfig,
// returning a wire-safe config and a map of callbacks (nil if none).
func extractTransformCallbacks(config *SystemMessageConfig) (*SystemMessageConfig, map[string]SectionTransformFn) {
if config == nil || config.Mode != "customize" || len(config.Sections) == 0 {
return config, nil
}
callbacks := make(map[string]SectionTransformFn)
wireSections := make(map[string]SectionOverride)
for id, override := range config.Sections {
if override.Transform != nil {
callbacks[id] = override.Transform
wireSections[id] = SectionOverride{Action: "transform"}
} else {
wireSections[id] = override
}
}
if len(callbacks) == 0 {
return config, nil
}
wireConfig := &SystemMessageConfig{
Mode: config.Mode,
Content: config.Content,
Sections: wireSections,
}
return wireConfig, callbacks
}
func (c *Client) CreateSession(ctx context.Context, config *SessionConfig) (*Session, error) {
if config == nil {
config = &SessionConfig{}
}
if err := c.ensureConnected(ctx); err != nil {
return nil, err
}
c.applyConfigDefaultsForMode(config)
req := createSessionRequest{}
req.Model = config.Model
req.ClientName = config.ClientName
req.ReasoningEffort = config.ReasoningEffort
req.ReasoningSummary = config.ReasoningSummary
req.ContextTier = config.ContextTier
req.ConfigDir = config.ConfigDirectory
req.EnableConfigDiscovery = config.EnableConfigDiscovery
req.SkipEmbeddingRetrieval = config.SkipEmbeddingRetrieval
req.EmbeddingCacheStorage = config.EmbeddingCacheStorage
req.OrganizationCustomInstructions = config.OrganizationCustomInstructions
req.EnableOnDemandInstructionDiscovery = config.EnableOnDemandInstructionDiscovery
req.EnableFileHooks = config.EnableFileHooks
req.EnableHostGitOperations = config.EnableHostGitOperations
req.EnableSessionStore = config.EnableSessionStore
req.EnableSkills = config.EnableSkills
req.Tools = config.Tools
systemMessage := c.systemMessageForMode(config.SystemMessage)
wireSystemMessage, transformCallbacks := extractTransformCallbacks(systemMessage)
req.SystemMessage = wireSystemMessage
availableTools, excludedTools, precedence, ferr := c.resolveToolFilterOptions(config.AvailableTools, config.ExcludedTools)
if ferr != nil {
return nil, ferr
}
req.AvailableTools = availableTools
req.ExcludedTools = excludedTools
req.ToolFilterPrecedence = precedence
req.Provider = config.Provider
req.EnableSessionTelemetry = config.EnableSessionTelemetry
req.IsExperimentalMode = config.IsExperimentalMode
req.SkipCustomInstructions = config.SkipCustomInstructions
req.CustomAgentsLocalOnly = config.CustomAgentsLocalOnly
req.CoauthorEnabled = config.CoauthorEnabled
req.ManageScheduleEnabled = config.ManageScheduleEnabled
req.ModelCapabilities = config.ModelCapabilities
req.WorkingDirectory = config.WorkingDirectory
req.MCPServers = config.MCPServers
req.MCPOAuthTokenStorage = config.MCPOAuthTokenStorage
req.EnvValueMode = "direct"
req.CustomAgents = config.CustomAgents
req.DefaultAgent = config.DefaultAgent
req.Agent = config.Agent
req.SkillDirectories = config.SkillDirectories
req.PluginDirectories = config.PluginDirectories
req.InstructionDirectories = config.InstructionDirectories
req.DisabledSkills = config.DisabledSkills
req.InfiniteSessions = config.InfiniteSessions
req.LargeOutput = config.LargeOutput
req.GitHubToken = config.GitHubToken
req.RemoteSession = config.RemoteSession
req.Cloud = config.Cloud
req.Canvases = config.Canvases
req.RequestCanvasRenderer = config.RequestCanvasRenderer
req.RequestExtensions = config.RequestExtensions
req.ExtensionSDKPath = config.ExtensionSDKPath
if len(config.Commands) > 0 {
cmds := make([]wireCommand, 0, len(config.Commands))
for _, cmd := range config.Commands {
cmds = append(cmds, wireCommand{Name: cmd.Name, Description: cmd.Description})
}
req.Commands = cmds
}
if config.OnElicitationRequest != nil {
req.RequestElicitation = Bool(true)
}
if config.OnExitPlanModeRequest != nil {
req.RequestExitPlanMode = Bool(true)
}
if config.OnAutoModeSwitchRequest != nil {
req.RequestAutoModeSwitch = Bool(true)
}
if config.EnableMCPApps {
req.RequestMCPApps = Bool(true)
}
if config.Streaming != nil {
req.Streaming = config.Streaming
}
if config.IncludeSubAgentStreamingEvents != nil {
req.IncludeSubAgentStreamingEvents = config.IncludeSubAgentStreamingEvents
} else {
req.IncludeSubAgentStreamingEvents = Bool(true)
}
if config.OnUserInputRequest != nil {
req.RequestUserInput = Bool(true)
}
if config.Hooks != nil && (config.Hooks.OnPreToolUse != nil ||
config.Hooks.OnPreMCPToolCall != nil ||
config.Hooks.OnPostToolUse != nil ||
config.Hooks.OnPostToolUseFailure != nil ||
config.Hooks.OnUserPromptSubmitted != nil ||
config.Hooks.OnSessionStart != nil ||
config.Hooks.OnSessionEnd != nil ||
config.Hooks.OnErrorOccurred != nil) {
req.Hooks = Bool(true)
}
if config.OnPermissionRequest != nil {
req.RequestPermission = Bool(true)
}
traceparent, tracestate := getTraceContext(ctx)
req.Traceparent = traceparent
req.Tracestate = tracestate
// For cloud sessions, let the CLI/server assign the session id and
// register the session lazily once the response arrives. For non-cloud
// sessions we generate the id client-side (when the caller didn't
// supply one) so the session can be registered BEFORE the RPC — the
// CLI may issue session-scoped requests (e.g. sessionFs.writeFile for
// workspace metadata) during session.create processing, before it has
// sent the response.
useServerGeneratedID := config.Cloud != nil && config.SessionID == ""
var localSessionID string
if useServerGeneratedID {
localSessionID = ""
} else if config.SessionID != "" {
localSessionID = config.SessionID
} else {
localSessionID = uuid.NewString()
}
req.SessionID = localSessionID
// initializeSession creates the session, wires up handlers, and registers
// it in the sessions map. Invoked from the read loop the instant the
// session.create response arrives (synchronously, before the next
// message is dispatched) so notifications for the new session id are
// routed to a registered session.
initializeSession := func(sessionID string) (*Session, error) {
s := newSession(sessionID, c.client, "")
s.registerTools(config.Tools)
s.registerPermissionHandler(config.OnPermissionRequest)
if config.OnUserInputRequest != nil {
s.registerUserInputHandler(config.OnUserInputRequest)
}
if config.Hooks != nil {
s.registerHooks(config.Hooks)
}
if transformCallbacks != nil {
s.registerTransformCallbacks(transformCallbacks)
}
if config.OnEvent != nil {
s.On(config.OnEvent)
}
if len(config.Commands) > 0 {
s.registerCommands(config.Commands)
}
if config.OnElicitationRequest != nil {
s.registerElicitationHandler(config.OnElicitationRequest)
}
if config.OnExitPlanModeRequest != nil {
s.registerExitPlanModeHandler(config.OnExitPlanModeRequest)
}
if config.OnAutoModeSwitchRequest != nil {
s.registerAutoModeSwitchHandler(config.OnAutoModeSwitchRequest)
}
if config.CanvasHandler != nil {
s.registerCanvasHandler(config.CanvasHandler)
}
c.sessionsMux.Lock()
c.sessions[sessionID] = s
c.sessionsMux.Unlock()
if c.options.SessionFS != nil {
if config.CreateSessionFSProvider == nil {
c.sessionsMux.Lock()
delete(c.sessions, sessionID)
c.sessionsMux.Unlock()
return nil, fmt.Errorf("CreateSessionFSProvider is required in session config when SessionFS is enabled in client options")
}
provider := config.CreateSessionFSProvider(s)
if c.options.SessionFS.Capabilities != nil && c.options.SessionFS.Capabilities.Sqlite {
if _, ok := provider.(SessionFSSqliteProvider); !ok {
c.sessionsMux.Lock()
delete(c.sessions, sessionID)
c.sessionsMux.Unlock()
return nil, fmt.Errorf("SessionFS capabilities declare SQLite support but the provider does not implement SessionFSSqliteProvider")
}
}
s.clientSessionAPIs.SessionFS = newSessionFSAdapter(provider)
}
return s, nil
}
var session *Session
var registeredSessionID string
// Pre-register non-cloud sessions BEFORE issuing the RPC so any
// session-scoped requests the CLI emits during session.create processing
// (e.g. sessionFs.writeFile for workspace metadata) can be routed to the
// correct handlers.
if localSessionID != "" {
s, err := initializeSession(localSessionID)
if err != nil {
return nil, err
}
session = s
registeredSessionID = localSessionID
}
// For the server-assigned (cloud) path, register the session
// synchronously from the read loop the instant the response arrives,
// before the read loop dispatches the next message. Without this hook
// the awaiter goroutine may not run until after the read loop has
// dispatched the first session.event notification, which would be
// silently dropped because the session id isn't yet in the lookup
// table. Non-cloud sessions are already registered above.
var inlineCb func(raw json.RawMessage) error
if session == nil {
inlineCb = func(raw json.RawMessage) error {
var early struct {
SessionID string `json:"sessionId"`
}
if err := json.Unmarshal(raw, &early); err != nil {
return fmt.Errorf("failed to parse sessionId from response: %w", err)
}
if early.SessionID == "" {
return fmt.Errorf("session.create response did not include a sessionId")
}
s, err := initializeSession(early.SessionID)
if err != nil {
return err
}
session = s
registeredSessionID = early.SessionID
return nil
}
}
result, err := c.client.RequestWithInlineResponse("session.create", req, inlineCb)
if err != nil {
if registeredSessionID != "" {
c.sessionsMux.Lock()
delete(c.sessions, registeredSessionID)
c.sessionsMux.Unlock()
}
return nil, fmt.Errorf("failed to create session: %w", err)
}
var response createSessionResponse
if err := json.Unmarshal(result, &response); err != nil {
if registeredSessionID != "" {
c.sessionsMux.Lock()
delete(c.sessions, registeredSessionID)
c.sessionsMux.Unlock()
}
return nil, fmt.Errorf("failed to unmarshal response: %w", err)
}
if session == nil {
return nil, fmt.Errorf("session.create response did not include a sessionId")
}
if localSessionID != "" && response.SessionID != "" && response.SessionID != localSessionID {
c.sessionsMux.Lock()
delete(c.sessions, registeredSessionID)
c.sessionsMux.Unlock()
return nil, fmt.Errorf("session.create returned sessionId %s but the caller requested %s", response.SessionID, localSessionID)
}
session.workspacePath = response.WorkspacePath
session.setCapabilities(response.Capabilities)
if err := c.updateSessionOptionsForMode(ctx, session, optBackInFields{
SkipCustomInstructions: config.SkipCustomInstructions,
CustomAgentsLocalOnly: config.CustomAgentsLocalOnly,
CoauthorEnabled: config.CoauthorEnabled,
ManageScheduleEnabled: config.ManageScheduleEnabled,
}); err != nil {
return nil, err
}
return session, nil
}
// ResumeSession resumes an existing conversation session by its ID.
//
// This is a convenience method that calls [Client.ResumeSessionWithOptions].
// 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 = &ResumeSessionConfig{}
}
if err := c.ensureConnected(ctx); err != nil {
return nil, err
}
c.applyResumeDefaultsForMode(config)
var req resumeSessionRequest
req.SessionID = sessionID
req.ClientName = config.ClientName
req.Model = config.Model
req.ReasoningEffort = config.ReasoningEffort
req.ReasoningSummary = config.ReasoningSummary
req.ContextTier = config.ContextTier
systemMessage := c.systemMessageForMode(config.SystemMessage)
wireSystemMessage, transformCallbacks := extractTransformCallbacks(systemMessage)
req.SystemMessage = wireSystemMessage
req.Tools = config.Tools
req.Provider = config.Provider
req.EnableSessionTelemetry = config.EnableSessionTelemetry
req.IsExperimentalMode = config.IsExperimentalMode
req.SkipCustomInstructions = config.SkipCustomInstructions
req.CustomAgentsLocalOnly = config.CustomAgentsLocalOnly
req.CoauthorEnabled = config.CoauthorEnabled
req.ManageScheduleEnabled = config.ManageScheduleEnabled
req.ModelCapabilities = config.ModelCapabilities
availableTools, excludedTools, precedence, ferr := c.resolveToolFilterOptions(config.AvailableTools, config.ExcludedTools)
if ferr != nil {
return nil, ferr
}
req.AvailableTools = availableTools
req.ExcludedTools = excludedTools
req.ToolFilterPrecedence = precedence
if config.Streaming != nil {
req.Streaming = config.Streaming
}
if config.IncludeSubAgentStreamingEvents != nil {
req.IncludeSubAgentStreamingEvents = config.IncludeSubAgentStreamingEvents
} else {
req.IncludeSubAgentStreamingEvents = Bool(true)
}
if config.OnUserInputRequest != nil {
req.RequestUserInput = Bool(true)
}
if config.Hooks != nil && (config.Hooks.OnPreToolUse != nil ||
config.Hooks.OnPreMCPToolCall != nil ||
config.Hooks.OnPostToolUse != nil ||
config.Hooks.OnPostToolUseFailure != 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.ConfigDirectory
req.EnableConfigDiscovery = config.EnableConfigDiscovery
req.SkipEmbeddingRetrieval = config.SkipEmbeddingRetrieval
req.EmbeddingCacheStorage = config.EmbeddingCacheStorage
req.OrganizationCustomInstructions = config.OrganizationCustomInstructions
req.EnableOnDemandInstructionDiscovery = config.EnableOnDemandInstructionDiscovery
req.EnableFileHooks = config.EnableFileHooks
req.EnableHostGitOperations = config.EnableHostGitOperations
req.EnableSessionStore = config.EnableSessionStore
req.EnableSkills = config.EnableSkills
if config.SuppressResumeEvent {
req.DisableResume = Bool(true)
}
req.ContinuePendingWork = config.ContinuePendingWork
req.MCPServers = config.MCPServers
req.MCPOAuthTokenStorage = config.MCPOAuthTokenStorage
req.EnvValueMode = "direct"
req.CustomAgents = config.CustomAgents
req.DefaultAgent = config.DefaultAgent
req.Agent = config.Agent
req.SkillDirectories = config.SkillDirectories
req.PluginDirectories = config.PluginDirectories
req.InstructionDirectories = config.InstructionDirectories
req.DisabledSkills = config.DisabledSkills
req.InfiniteSessions = config.InfiniteSessions
req.LargeOutput = config.LargeOutput
req.GitHubToken = config.GitHubToken
req.RemoteSession = config.RemoteSession
req.Canvases = config.Canvases
req.OpenCanvases = config.OpenCanvases
req.RequestCanvasRenderer = config.RequestCanvasRenderer
req.RequestExtensions = config.RequestExtensions
req.ExtensionSDKPath = config.ExtensionSDKPath
if config.OnPermissionRequest != nil {
req.RequestPermission = Bool(true)
}
if len(config.Commands) > 0 {
cmds := make([]wireCommand, 0, len(config.Commands))