-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathsession.go
More file actions
1270 lines (1158 loc) · 38.4 KB
/
session.go
File metadata and controls
1270 lines (1158 loc) · 38.4 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.
package copilot
import (
"context"
"encoding/json"
"fmt"
"sync"
"time"
"github.com/github/copilot-sdk/go/internal/jsonrpc2"
"github.com/github/copilot-sdk/go/rpc"
)
type sessionHandler struct {
id uint64
fn SessionEventHandler
}
// Session represents a single conversation session with the Copilot CLI.
//
// A session maintains conversation state, handles events, and manages tool execution.
// Sessions are created via [Client.CreateSession] or resumed via [Client.ResumeSession].
//
// The session provides methods to send messages, subscribe to events, retrieve
// conversation history, and manage the session lifecycle. All methods are safe
// for concurrent use.
//
// Example usage:
//
// session, err := client.CreateSession(copilot.SessionConfig{
// Model: "gpt-4",
// })
// if err != nil {
// log.Fatal(err)
// }
// defer session.Disconnect()
//
// // Subscribe to events
// unsubscribe := session.On(func(event copilot.SessionEvent) {
// if d, ok := event.Data.(*copilot.AssistantMessageData); ok {
// fmt.Println("Assistant:", d.Content)
// }
// })
// defer unsubscribe()
//
// // Send a message
// messageID, err := session.Send(copilot.MessageOptions{
// Prompt: "Hello, world!",
// })
type Session struct {
// SessionID is the unique identifier for this session.
SessionID string
workspacePath string
client *jsonrpc2.Client
clientSessionApis *rpc.ClientSessionApiHandlers
handlers []sessionHandler
nextHandlerID uint64
handlerMutex sync.RWMutex
toolHandlers map[string]ToolHandler
toolHandlersM sync.RWMutex
permissionHandler PermissionHandlerFunc
permissionMux sync.RWMutex
userInputHandler UserInputHandler
userInputMux sync.RWMutex
hooks *SessionHooks
hooksMux sync.RWMutex
transformCallbacks map[string]SectionTransformFn
transformMu sync.Mutex
commandHandlers map[string]CommandHandler
commandHandlersMu sync.RWMutex
elicitationHandler ElicitationHandler
elicitationMu sync.RWMutex
capabilities SessionCapabilities
capabilitiesMu sync.RWMutex
// eventCh serializes user event handler dispatch. dispatchEvent enqueues;
// a single goroutine (processEvents) dequeues and invokes handlers in FIFO order.
eventCh chan SessionEvent
closeOnce sync.Once // guards eventCh close so Disconnect is safe to call more than once
// RPC provides typed session-scoped RPC methods.
RPC *rpc.SessionRpc
}
// WorkspacePath returns the path to the session workspace directory when infinite
// sessions are enabled. Contains checkpoints/, plan.md, and files/ subdirectories.
// Returns empty string if infinite sessions are disabled.
func (s *Session) WorkspacePath() string {
return s.workspacePath
}
// newSession creates a new session wrapper with the given session ID and client.
func newSession(sessionID string, client *jsonrpc2.Client, workspacePath string) *Session {
s := &Session{
SessionID: sessionID,
workspacePath: workspacePath,
client: client,
clientSessionApis: &rpc.ClientSessionApiHandlers{},
handlers: make([]sessionHandler, 0),
toolHandlers: make(map[string]ToolHandler),
commandHandlers: make(map[string]CommandHandler),
eventCh: make(chan SessionEvent, 128),
RPC: rpc.NewSessionRpc(client, sessionID),
}
go s.processEvents()
return s
}
// Send sends a message to this session and waits for the response.
//
// The message is processed asynchronously. Subscribe to events via [Session.On]
// to receive streaming responses and other session events.
//
// Parameters:
// - options: The message options including the prompt and optional attachments.
//
// Returns the message ID of the response, which can be used to correlate events,
// or an error if the session has been disconnected or the connection fails.
//
// Example:
//
// messageID, err := session.Send(context.Background(), copilot.MessageOptions{
// Prompt: "Explain this code",
// Attachments: []copilot.Attachment{
// {Type: "file", Path: "./main.go"},
// },
// })
// if err != nil {
// log.Printf("Failed to send message: %v", err)
// }
func (s *Session) Send(ctx context.Context, options MessageOptions) (string, error) {
traceparent, tracestate := getTraceContext(ctx)
req := sessionSendRequest{
SessionID: s.SessionID,
Prompt: options.Prompt,
Attachments: options.Attachments,
Mode: options.Mode,
Traceparent: traceparent,
Tracestate: tracestate,
}
result, err := s.client.Request("session.send", req)
if err != nil {
return "", fmt.Errorf("failed to send message: %w", err)
}
var response sessionSendResponse
if err := json.Unmarshal(result, &response); err != nil {
return "", fmt.Errorf("failed to unmarshal send response: %w", err)
}
return response.MessageID, nil
}
// SendAndWait sends a message to this session and waits until the session becomes idle.
//
// This is a convenience method that combines [Session.Send] with waiting for
// the session.idle event. Use this when you want to block until the assistant
// has finished processing the message.
//
// Events are still delivered to handlers registered via [Session.On] while waiting.
//
// Parameters:
// - options: The message options including the prompt and optional attachments.
// - timeout: How long to wait for completion. Defaults to 60 seconds if zero.
// Controls how long to wait; does not abort in-flight agent work.
//
// Returns the final assistant message event, or nil if none was received.
// Returns an error if the timeout is reached or the connection fails.
//
// Example:
//
// response, err := session.SendAndWait(context.Background(), copilot.MessageOptions{
// Prompt: "What is 2+2?",
// }) // Use default 60s timeout
// if err != nil {
// log.Printf("Failed: %v", err)
// }
// if response != nil {
// if d, ok := response.Data.(*AssistantMessageData); ok {
// fmt.Println(d.Content)
// }
// }
func (s *Session) SendAndWait(ctx context.Context, options MessageOptions) (*SessionEvent, error) {
if _, ok := ctx.Deadline(); !ok {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, 60*time.Second)
defer cancel()
}
idleCh := make(chan struct{}, 1)
errCh := make(chan error, 1)
var lastAssistantMessage *SessionEvent
var mu sync.Mutex
unsubscribe := s.On(func(event SessionEvent) {
switch d := event.Data.(type) {
case *AssistantMessageData:
mu.Lock()
eventCopy := event
lastAssistantMessage = &eventCopy
mu.Unlock()
case *SessionIdleData:
select {
case idleCh <- struct{}{}:
default:
}
case *SessionErrorData:
select {
case errCh <- fmt.Errorf("session error: %s", d.Message):
default:
}
}
})
defer unsubscribe()
_, err := s.Send(ctx, options)
if err != nil {
return nil, err
}
select {
case <-idleCh:
mu.Lock()
result := lastAssistantMessage
mu.Unlock()
return result, nil
case err := <-errCh:
return nil, err
case <-ctx.Done(): // TODO: remove once session.Send honors the context
return nil, fmt.Errorf("waiting for session.idle: %w", ctx.Err())
}
}
// On subscribes to events from this session.
//
// Events include assistant messages, tool executions, errors, and session state
// changes. Multiple handlers can be registered and will all receive events.
// Handlers are called synchronously in the order they were registered.
//
// The returned function can be called to unsubscribe the handler. It is safe
// to call the unsubscribe function multiple times.
//
// Example:
//
// unsubscribe := session.On(func(event copilot.SessionEvent) {
// switch d := event.Data.(type) {
// case *copilot.AssistantMessageData:
// fmt.Println("Assistant:", d.Content)
// case *copilot.SessionErrorData:
// fmt.Println("Error:", d.Message)
// }
// })
//
// // Later, to stop receiving events:
// unsubscribe()
func (s *Session) On(handler SessionEventHandler) func() {
s.handlerMutex.Lock()
defer s.handlerMutex.Unlock()
id := s.nextHandlerID
s.nextHandlerID++
s.handlers = append(s.handlers, sessionHandler{id: id, fn: handler})
// Return unsubscribe function
return func() {
s.handlerMutex.Lock()
defer s.handlerMutex.Unlock()
for i, h := range s.handlers {
if h.id == id {
s.handlers = append(s.handlers[:i], s.handlers[i+1:]...)
break
}
}
}
}
// registerTools registers tool handlers for this session.
//
// Tools allow the assistant to execute custom functions. When the assistant
// invokes a tool, the corresponding handler is called with the tool arguments.
//
// This method is internal and typically called when creating a session with tools.
func (s *Session) registerTools(tools []Tool) {
s.toolHandlersM.Lock()
defer s.toolHandlersM.Unlock()
s.toolHandlers = make(map[string]ToolHandler)
for _, tool := range tools {
if tool.Name == "" || tool.Handler == nil {
continue
}
s.toolHandlers[tool.Name] = tool.Handler
}
}
// getToolHandler retrieves a registered tool handler by name.
// Returns the handler and true if found, or nil and false if not registered.
func (s *Session) getToolHandler(name string) (ToolHandler, bool) {
s.toolHandlersM.RLock()
handler, ok := s.toolHandlers[name]
s.toolHandlersM.RUnlock()
return handler, ok
}
// registerPermissionHandler registers a permission handler for this session.
//
// When the assistant needs permission to perform certain actions (e.g., file
// operations), this handler is called to approve or deny the request.
//
// This method is internal and typically called when creating a session.
func (s *Session) registerPermissionHandler(handler PermissionHandlerFunc) {
s.permissionMux.Lock()
defer s.permissionMux.Unlock()
s.permissionHandler = handler
}
// getPermissionHandler returns the currently registered permission handler, or nil.
func (s *Session) getPermissionHandler() PermissionHandlerFunc {
s.permissionMux.RLock()
defer s.permissionMux.RUnlock()
return s.permissionHandler
}
// registerUserInputHandler registers a user input handler for this session.
//
// When the assistant needs to ask the user a question (e.g., via ask_user tool),
// this handler is called to get the user's response.
//
// This method is internal and typically called when creating a session.
func (s *Session) registerUserInputHandler(handler UserInputHandler) {
s.userInputMux.Lock()
defer s.userInputMux.Unlock()
s.userInputHandler = handler
}
// getUserInputHandler returns the currently registered user input handler, or nil.
func (s *Session) getUserInputHandler() UserInputHandler {
s.userInputMux.RLock()
defer s.userInputMux.RUnlock()
return s.userInputHandler
}
// handleUserInputRequest handles a user input request from the Copilot CLI.
// This is an internal method called by the SDK when the CLI requests user input.
func (s *Session) handleUserInputRequest(request UserInputRequest) (UserInputResponse, error) {
handler := s.getUserInputHandler()
if handler == nil {
return UserInputResponse{}, fmt.Errorf("no user input handler registered")
}
invocation := UserInputInvocation{
SessionID: s.SessionID,
}
return handler(request, invocation)
}
// registerHooks registers hook handlers for this session.
//
// Hooks are called at various points during session execution to allow
// customization and observation of the session lifecycle.
//
// This method is internal and typically called when creating a session.
func (s *Session) registerHooks(hooks *SessionHooks) {
s.hooksMux.Lock()
defer s.hooksMux.Unlock()
s.hooks = hooks
}
// getHooks returns the currently registered hooks, or nil.
func (s *Session) getHooks() *SessionHooks {
s.hooksMux.RLock()
defer s.hooksMux.RUnlock()
return s.hooks
}
// handleHooksInvoke handles a hook invocation from the Copilot CLI.
// This is an internal method called by the SDK when the CLI invokes a hook.
func (s *Session) handleHooksInvoke(hookType string, rawInput json.RawMessage) (any, error) {
hooks := s.getHooks()
if hooks == nil {
return nil, nil
}
invocation := HookInvocation{
SessionID: s.SessionID,
}
switch hookType {
case "preToolUse":
if hooks.OnPreToolUse == nil {
return nil, nil
}
var input PreToolUseHookInput
if err := json.Unmarshal(rawInput, &input); err != nil {
return nil, fmt.Errorf("invalid hook input: %w", err)
}
return hooks.OnPreToolUse(input, invocation)
case "postToolUse":
if hooks.OnPostToolUse == nil {
return nil, nil
}
var input PostToolUseHookInput
if err := json.Unmarshal(rawInput, &input); err != nil {
return nil, fmt.Errorf("invalid hook input: %w", err)
}
return hooks.OnPostToolUse(input, invocation)
case "userPromptSubmitted":
if hooks.OnUserPromptSubmitted == nil {
return nil, nil
}
var input UserPromptSubmittedHookInput
if err := json.Unmarshal(rawInput, &input); err != nil {
return nil, fmt.Errorf("invalid hook input: %w", err)
}
return hooks.OnUserPromptSubmitted(input, invocation)
case "sessionStart":
if hooks.OnSessionStart == nil {
return nil, nil
}
var input SessionStartHookInput
if err := json.Unmarshal(rawInput, &input); err != nil {
return nil, fmt.Errorf("invalid hook input: %w", err)
}
return hooks.OnSessionStart(input, invocation)
case "sessionEnd":
if hooks.OnSessionEnd == nil {
return nil, nil
}
var input SessionEndHookInput
if err := json.Unmarshal(rawInput, &input); err != nil {
return nil, fmt.Errorf("invalid hook input: %w", err)
}
return hooks.OnSessionEnd(input, invocation)
case "errorOccurred":
if hooks.OnErrorOccurred == nil {
return nil, nil
}
var input ErrorOccurredHookInput
if err := json.Unmarshal(rawInput, &input); err != nil {
return nil, fmt.Errorf("invalid hook input: %w", err)
}
return hooks.OnErrorOccurred(input, invocation)
default:
return nil, nil
}
}
// registerTransformCallbacks registers transform callbacks for this session.
//
// Transform callbacks are invoked when the CLI requests system message section
// transforms. This method is internal and typically called when creating a session.
func (s *Session) registerTransformCallbacks(callbacks map[string]SectionTransformFn) {
s.transformMu.Lock()
defer s.transformMu.Unlock()
s.transformCallbacks = callbacks
}
type systemMessageTransformSection struct {
Content string `json:"content"`
}
type systemMessageTransformRequest struct {
SessionID string `json:"sessionId"`
Sections map[string]systemMessageTransformSection `json:"sections"`
}
type systemMessageTransformResponse struct {
Sections map[string]systemMessageTransformSection `json:"sections"`
}
// handleSystemMessageTransform handles a system message transform request from the Copilot CLI.
// This is an internal method called by the SDK when the CLI requests section transforms.
func (s *Session) handleSystemMessageTransform(sections map[string]systemMessageTransformSection) (systemMessageTransformResponse, error) {
s.transformMu.Lock()
callbacks := s.transformCallbacks
s.transformMu.Unlock()
result := make(map[string]systemMessageTransformSection)
for sectionID, data := range sections {
var callback SectionTransformFn
if callbacks != nil {
callback = callbacks[sectionID]
}
if callback != nil {
transformed, err := callback(data.Content)
if err != nil {
result[sectionID] = systemMessageTransformSection{Content: data.Content}
} else {
result[sectionID] = systemMessageTransformSection{Content: transformed}
}
} else {
result[sectionID] = systemMessageTransformSection{Content: data.Content}
}
}
return systemMessageTransformResponse{Sections: result}, nil
}
// registerCommands registers command handlers for this session.
func (s *Session) registerCommands(commands []CommandDefinition) {
s.commandHandlersMu.Lock()
defer s.commandHandlersMu.Unlock()
s.commandHandlers = make(map[string]CommandHandler)
for _, cmd := range commands {
if cmd.Name == "" || cmd.Handler == nil {
continue
}
s.commandHandlers[cmd.Name] = cmd.Handler
}
}
// getCommandHandler retrieves a registered command handler by name.
func (s *Session) getCommandHandler(name string) (CommandHandler, bool) {
s.commandHandlersMu.RLock()
handler, ok := s.commandHandlers[name]
s.commandHandlersMu.RUnlock()
return handler, ok
}
// executeCommandAndRespond dispatches a command.execute event to the registered handler
// and sends the result (or error) back via the RPC layer.
func (s *Session) executeCommandAndRespond(requestID, commandName, command, args string) {
ctx := context.Background()
handler, ok := s.getCommandHandler(commandName)
if !ok {
errMsg := fmt.Sprintf("Unknown command: %s", commandName)
s.RPC.Commands.HandlePendingCommand(ctx, &rpc.SessionCommandsHandlePendingCommandParams{
RequestID: requestID,
Error: &errMsg,
})
return
}
cmdCtx := CommandContext{
SessionID: s.SessionID,
Command: command,
CommandName: commandName,
Args: args,
}
if err := handler(cmdCtx); err != nil {
errMsg := err.Error()
s.RPC.Commands.HandlePendingCommand(ctx, &rpc.SessionCommandsHandlePendingCommandParams{
RequestID: requestID,
Error: &errMsg,
})
return
}
s.RPC.Commands.HandlePendingCommand(ctx, &rpc.SessionCommandsHandlePendingCommandParams{
RequestID: requestID,
})
}
// registerElicitationHandler registers an elicitation handler for this session.
func (s *Session) registerElicitationHandler(handler ElicitationHandler) {
s.elicitationMu.Lock()
defer s.elicitationMu.Unlock()
s.elicitationHandler = handler
}
// getElicitationHandler returns the currently registered elicitation handler, or nil.
func (s *Session) getElicitationHandler() ElicitationHandler {
s.elicitationMu.RLock()
defer s.elicitationMu.RUnlock()
return s.elicitationHandler
}
// handleElicitationRequest dispatches an elicitation.requested event to the registered handler
// and sends the result back via the RPC layer. Auto-cancels on error.
func (s *Session) handleElicitationRequest(elicitCtx ElicitationContext, requestID string) {
handler := s.getElicitationHandler()
if handler == nil {
return
}
ctx := context.Background()
result, err := handler(elicitCtx)
if err != nil {
// Handler failed — attempt to cancel so the request doesn't hang.
s.RPC.UI.HandlePendingElicitation(ctx, &rpc.SessionUIHandlePendingElicitationParams{
RequestID: requestID,
Result: rpc.SessionUIHandlePendingElicitationParamsResult{
Action: rpc.ActionCancel,
},
})
return
}
rpcContent := make(map[string]*rpc.Content)
for k, v := range result.Content {
rpcContent[k] = toRPCContent(v)
}
s.RPC.UI.HandlePendingElicitation(ctx, &rpc.SessionUIHandlePendingElicitationParams{
RequestID: requestID,
Result: rpc.SessionUIHandlePendingElicitationParamsResult{
Action: rpc.Action(result.Action),
Content: rpcContent,
},
})
}
// toRPCContent converts an arbitrary value to a *rpc.Content for elicitation responses.
func toRPCContent(v any) *rpc.Content {
if v == nil {
return nil
}
c := &rpc.Content{}
switch val := v.(type) {
case bool:
c.Bool = &val
case float64:
c.Double = &val
case int:
f := float64(val)
c.Double = &f
case string:
c.String = &val
case []string:
c.StringArray = val
case []any:
strs := make([]string, 0, len(val))
for _, item := range val {
if s, ok := item.(string); ok {
strs = append(strs, s)
}
}
c.StringArray = strs
default:
s := fmt.Sprintf("%v", val)
c.String = &s
}
return c
}
// Capabilities returns the session capabilities reported by the server.
func (s *Session) Capabilities() SessionCapabilities {
s.capabilitiesMu.RLock()
defer s.capabilitiesMu.RUnlock()
return s.capabilities
}
// setCapabilities updates the session capabilities.
func (s *Session) setCapabilities(caps *SessionCapabilities) {
s.capabilitiesMu.Lock()
defer s.capabilitiesMu.Unlock()
if caps != nil {
s.capabilities = *caps
} else {
s.capabilities = SessionCapabilities{}
}
}
// UI returns the interactive UI API for showing elicitation dialogs.
// Methods on the returned SessionUI will error if the host does not support
// elicitation (check Capabilities().UI.Elicitation first).
func (s *Session) UI() *SessionUI {
return &SessionUI{session: s}
}
// assertElicitation checks that the host supports elicitation and returns an error if not.
func (s *Session) assertElicitation() error {
caps := s.Capabilities()
if caps.UI == nil || !caps.UI.Elicitation {
return fmt.Errorf("elicitation is not supported by the host; check session.Capabilities().UI.Elicitation before calling UI methods")
}
return nil
}
// Elicitation shows a generic elicitation dialog with a custom schema.
func (ui *SessionUI) Elicitation(ctx context.Context, message string, requestedSchema rpc.RequestedSchema) (*ElicitationResult, error) {
if err := ui.session.assertElicitation(); err != nil {
return nil, err
}
rpcResult, err := ui.session.RPC.UI.Elicitation(ctx, &rpc.SessionUIElicitationParams{
Message: message,
RequestedSchema: requestedSchema,
})
if err != nil {
return nil, err
}
return fromRPCElicitationResult(rpcResult), nil
}
// Confirm shows a confirmation dialog and returns the user's boolean answer.
// Returns false if the user declines or cancels.
func (ui *SessionUI) Confirm(ctx context.Context, message string) (bool, error) {
if err := ui.session.assertElicitation(); err != nil {
return false, err
}
defaultTrue := &rpc.Content{Bool: Bool(true)}
rpcResult, err := ui.session.RPC.UI.Elicitation(ctx, &rpc.SessionUIElicitationParams{
Message: message,
RequestedSchema: rpc.RequestedSchema{
Type: rpc.RequestedSchemaTypeObject,
Properties: map[string]rpc.Property{
"confirmed": {
Type: rpc.PropertyTypeBoolean,
Default: defaultTrue,
},
},
Required: []string{"confirmed"},
},
})
if err != nil {
return false, err
}
if rpcResult.Action == rpc.ActionAccept {
if c, ok := rpcResult.Content["confirmed"]; ok && c != nil && c.Bool != nil {
return *c.Bool, nil
}
}
return false, nil
}
// Select shows a selection dialog with the given options.
// Returns the selected string, or empty string and false if the user declines/cancels.
func (ui *SessionUI) Select(ctx context.Context, message string, options []string) (string, bool, error) {
if err := ui.session.assertElicitation(); err != nil {
return "", false, err
}
rpcResult, err := ui.session.RPC.UI.Elicitation(ctx, &rpc.SessionUIElicitationParams{
Message: message,
RequestedSchema: rpc.RequestedSchema{
Type: rpc.RequestedSchemaTypeObject,
Properties: map[string]rpc.Property{
"selection": {
Type: rpc.PropertyTypeString,
Enum: options,
},
},
Required: []string{"selection"},
},
})
if err != nil {
return "", false, err
}
if rpcResult.Action == rpc.ActionAccept {
if c, ok := rpcResult.Content["selection"]; ok && c != nil && c.String != nil {
return *c.String, true, nil
}
}
return "", false, nil
}
// Input shows a text input dialog. Returns the entered text, or empty string and
// false if the user declines/cancels.
func (ui *SessionUI) Input(ctx context.Context, message string, opts *InputOptions) (string, bool, error) {
if err := ui.session.assertElicitation(); err != nil {
return "", false, err
}
prop := rpc.Property{Type: rpc.PropertyTypeString}
if opts != nil {
if opts.Title != "" {
prop.Title = &opts.Title
}
if opts.Description != "" {
prop.Description = &opts.Description
}
if opts.MinLength != nil {
f := float64(*opts.MinLength)
prop.MinLength = &f
}
if opts.MaxLength != nil {
f := float64(*opts.MaxLength)
prop.MaxLength = &f
}
if opts.Format != "" {
format := rpc.Format(opts.Format)
prop.Format = &format
}
if opts.Default != "" {
prop.Default = &rpc.Content{String: &opts.Default}
}
}
rpcResult, err := ui.session.RPC.UI.Elicitation(ctx, &rpc.SessionUIElicitationParams{
Message: message,
RequestedSchema: rpc.RequestedSchema{
Type: rpc.RequestedSchemaTypeObject,
Properties: map[string]rpc.Property{
"value": prop,
},
Required: []string{"value"},
},
})
if err != nil {
return "", false, err
}
if rpcResult.Action == rpc.ActionAccept {
if c, ok := rpcResult.Content["value"]; ok && c != nil && c.String != nil {
return *c.String, true, nil
}
}
return "", false, nil
}
// fromRPCElicitationResult converts the RPC result to the SDK ElicitationResult.
func fromRPCElicitationResult(r *rpc.SessionUIElicitationResult) *ElicitationResult {
if r == nil {
return nil
}
content := make(map[string]any)
for k, v := range r.Content {
if v == nil {
content[k] = nil
continue
}
if v.Bool != nil {
content[k] = *v.Bool
} else if v.Double != nil {
content[k] = *v.Double
} else if v.String != nil {
content[k] = *v.String
} else if v.StringArray != nil {
content[k] = v.StringArray
}
}
return &ElicitationResult{
Action: string(r.Action),
Content: content,
}
}
// dispatchEvent enqueues an event for delivery to user handlers and fires
// broadcast handlers concurrently.
//
// Broadcast work (tool calls, permission requests) is fired in a separate
// goroutine so it does not block the JSON-RPC read loop. User event handlers
// are delivered by a single consumer goroutine (processEvents), guaranteeing
// serial, FIFO dispatch without blocking the read loop.
func (s *Session) dispatchEvent(event SessionEvent) {
go s.handleBroadcastEvent(event)
// Send to the event channel in a closure with a recover guard.
// Disconnect closes eventCh, and in Go sending on a closed channel
// panics — there is no non-panicking send primitive. We only want
// to suppress that specific panic; other panics are not expected here.
func() {
defer func() { recover() }()
s.eventCh <- event
}()
}
// processEvents is the single consumer goroutine for the event channel.
// It invokes user handlers serially, in arrival order. Panics in individual
// handlers are recovered so that one misbehaving handler does not prevent
// others from receiving the event.
func (s *Session) processEvents() {
for event := range s.eventCh {
s.handlerMutex.RLock()
handlers := make([]SessionEventHandler, 0, len(s.handlers))
for _, h := range s.handlers {
handlers = append(handlers, h.fn)
}
s.handlerMutex.RUnlock()
for _, handler := range handlers {
func() {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Error in session event handler: %v\n", r)
}
}()
handler(event)
}()
}
}
}
// handleBroadcastEvent handles broadcast request events by executing local handlers
// and responding via RPC. This implements the protocol v3 broadcast model where tool
// calls and permission requests are broadcast as session events to all clients.
//
// Handlers are executed in their own goroutine (not the JSON-RPC read loop or the
// event consumer loop) so that a stalled handler does not block event delivery or
// cause RPC deadlocks.
func (s *Session) handleBroadcastEvent(event SessionEvent) {
switch d := event.Data.(type) {
case *ExternalToolRequestedData:
handler, ok := s.getToolHandler(d.ToolName)
if !ok {
return
}
var tp, ts string
if d.Traceparent != nil {
tp = *d.Traceparent
}
if d.Tracestate != nil {
ts = *d.Tracestate
}
s.executeToolAndRespond(d.RequestID, d.ToolName, d.ToolCallID, d.Arguments, handler, tp, ts)
case *PermissionRequestedData:
if d.ResolvedByHook != nil && *d.ResolvedByHook {
return // Already resolved by a permissionRequest hook; no client action needed.
}
handler := s.getPermissionHandler()
if handler == nil {
return
}
s.executePermissionAndRespond(d.RequestID, d.PermissionRequest, handler)
case *CommandExecuteData:
s.executeCommandAndRespond(d.RequestID, d.CommandName, d.Command, d.Args)
case *ElicitationRequestedData:
handler := s.getElicitationHandler()
if handler == nil {
return
}
var requestedSchema map[string]any
if d.RequestedSchema != nil {
requestedSchema = map[string]any{
"type": string(d.RequestedSchema.Type),
"properties": d.RequestedSchema.Properties,
}
if len(d.RequestedSchema.Required) > 0 {
requestedSchema["required"] = d.RequestedSchema.Required
}
}
mode := ""
if d.Mode != nil {
mode = string(*d.Mode)
}
elicitationSource := ""
if d.ElicitationSource != nil {
elicitationSource = *d.ElicitationSource
}
url := ""
if d.URL != nil {
url = *d.URL
}
s.handleElicitationRequest(ElicitationContext{
SessionID: s.SessionID,
Message: d.Message,
RequestedSchema: requestedSchema,
Mode: mode,
ElicitationSource: elicitationSource,
URL: url,
}, d.RequestID)
case *CapabilitiesChangedData:
if d.UI != nil && d.UI.Elicitation != nil {
s.setCapabilities(&SessionCapabilities{
UI: &UICapabilities{Elicitation: *d.UI.Elicitation},
})
}
}
}
// executeToolAndRespond executes a tool handler and sends the result back via RPC.
func (s *Session) executeToolAndRespond(requestID, toolName, toolCallID string, arguments any, handler ToolHandler, traceparent, tracestate string) {
ctx := contextWithTraceParent(context.Background(), traceparent, tracestate)
defer func() {
if r := recover(); r != nil {
errMsg := fmt.Sprintf("tool panic: %v", r)
s.RPC.Tools.HandlePendingToolCall(ctx, &rpc.SessionToolsHandlePendingToolCallParams{
RequestID: requestID,
Error: &errMsg,
})
}
}()
invocation := ToolInvocation{
SessionID: s.SessionID,
ToolCallID: toolCallID,
ToolName: toolName,
Arguments: arguments,
TraceContext: ctx,
}
result, err := handler(invocation)
if err != nil {
errMsg := err.Error()
s.RPC.Tools.HandlePendingToolCall(ctx, &rpc.SessionToolsHandlePendingToolCallParams{
RequestID: requestID,
Error: &errMsg,
})
return
}
textResultForLLM := result.TextResultForLLM
if textResultForLLM == "" {
textResultForLLM = fmt.Sprintf("%v", result)
}
// Default ResultType to "success" when unset, or "failure" when there's an error.
effectiveResultType := result.ResultType
if effectiveResultType == "" {