-
Notifications
You must be signed in to change notification settings - Fork 923
Expand file tree
/
Copy pathsession.go
More file actions
595 lines (536 loc) · 17.4 KB
/
session.go
File metadata and controls
595 lines (536 loc) · 17.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
// 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.Destroy()
//
// // Subscribe to events
// unsubscribe := session.On(func(event copilot.SessionEvent) {
// if event.Type == "assistant.message" {
// fmt.Println("Assistant:", event.Data.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
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
// 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 {
return &Session{
SessionID: sessionID,
workspacePath: workspacePath,
client: client,
handlers: make([]sessionHandler, 0),
toolHandlers: make(map[string]ToolHandler),
RPC: rpc.NewSessionRpc(client, sessionID),
}
}
// 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 destroyed 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) {
req := sessionSendRequest{
SessionID: s.SessionID,
Prompt: options.Prompt,
Attachments: options.Attachments,
Mode: options.Mode,
}
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 {
// fmt.Println(*response.Data.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 event.Type {
case AssistantMessage:
mu.Lock()
eventCopy := event
lastAssistantMessage = &eventCopy
mu.Unlock()
case SessionIdle:
select {
case idleCh <- struct{}{}:
default:
}
case SessionError:
errMsg := "session error"
if event.Data.Message != nil {
errMsg = *event.Data.Message
}
select {
case errCh <- fmt.Errorf("session error: %s", errMsg):
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 event.Type {
// case "assistant.message":
// fmt.Println("Assistant:", event.Data.Content)
// case "session.error":
// fmt.Println("Error:", event.Data.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
}
// handlePermissionRequest handles a permission request from the Copilot CLI.
// This is an internal method called by the SDK when the CLI requests permission.
func (s *Session) handlePermissionRequest(request PermissionRequest) (PermissionRequestResult, error) {
handler := s.getPermissionHandler()
if handler == nil {
return PermissionRequestResult{
Kind: "denied-no-approval-rule-and-could-not-request-from-user",
}, nil
}
invocation := PermissionInvocation{
SessionID: s.SessionID,
}
return handler(request, invocation)
}
// 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, fmt.Errorf("unknown hook type: %s", hookType)
}
}
// dispatchEvent dispatches an event to all registered handlers.
// This is an internal method; handlers are called synchronously and any panics
// are recovered to prevent crashing the event dispatcher.
func (s *Session) dispatchEvent(event SessionEvent) {
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 {
// Call handler - don't let panics crash the dispatcher
func() {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Error in session event handler: %v\n", r)
}
}()
handler(event)
}()
}
}
// GetMessages retrieves all events and messages from this session's history.
//
// This returns the complete conversation history including user messages,
// assistant responses, tool executions, and other session events in
// chronological order.
//
// Returns an error if the session has been destroyed or the connection fails.
//
// Example:
//
// events, err := session.GetMessages(context.Background())
// if err != nil {
// log.Printf("Failed to get messages: %v", err)
// return
// }
// for _, event := range events {
// if event.Type == "assistant.message" {
// fmt.Println("Assistant:", event.Data.Content)
// }
// }
func (s *Session) GetMessages(ctx context.Context) ([]SessionEvent, error) {
result, err := s.client.Request("session.getMessages", sessionGetMessagesRequest{SessionID: s.SessionID})
if err != nil {
return nil, fmt.Errorf("failed to get messages: %w", err)
}
var response sessionGetMessagesResponse
if err := json.Unmarshal(result, &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal get messages response: %w", err)
}
return response.Events, nil
}
// Destroy destroys this session and releases all associated resources.
//
// After calling this method, the session can no longer be used. All event
// handlers and tool handlers are cleared. To continue the conversation,
// use [Client.ResumeSession] with the session ID.
//
// Returns an error if the connection fails.
//
// Example:
//
// // Clean up when done
// if err := session.Destroy(); err != nil {
// log.Printf("Failed to destroy session: %v", err)
// }
func (s *Session) Destroy() error {
_, err := s.client.Request("session.destroy", sessionDestroyRequest{SessionID: s.SessionID})
if err != nil {
return fmt.Errorf("failed to destroy session: %w", err)
}
// Clear handlers
s.handlerMutex.Lock()
s.handlers = nil
s.handlerMutex.Unlock()
s.toolHandlersM.Lock()
s.toolHandlers = nil
s.toolHandlersM.Unlock()
s.permissionMux.Lock()
s.permissionHandler = nil
s.permissionMux.Unlock()
return nil
}
// Abort aborts the currently processing message in this session.
//
// Use this to cancel a long-running request. The session remains valid
// and can continue to be used for new messages.
//
// Returns an error if the session has been destroyed or the connection fails.
//
// Example:
//
// // Start a long-running request in a goroutine
// go func() {
// session.Send(context.Background(), copilot.MessageOptions{
// Prompt: "Write a very long story...",
// })
// }()
//
// // Abort after 5 seconds
// time.Sleep(5 * time.Second)
// if err := session.Abort(context.Background()); err != nil {
// log.Printf("Failed to abort: %v", err)
// }
func (s *Session) Abort(ctx context.Context) error {
_, err := s.client.Request("session.abort", sessionAbortRequest{SessionID: s.SessionID})
if err != nil {
return fmt.Errorf("failed to abort session: %w", err)
}
return nil
}
// SetModel changes the model for this session.
// The new model takes effect for the next message. Conversation history is preserved.
//
// Example:
//
// if err := session.SetModel(context.Background(), "gpt-4.1"); err != nil {
// log.Printf("Failed to set model: %v", err)
// }
func (s *Session) SetModel(ctx context.Context, model string) error {
_, err := s.RPC.Model.SwitchTo(ctx, &rpc.SessionModelSwitchToParams{ModelID: model})
if err != nil {
return fmt.Errorf("failed to set model: %w", err)
}
return nil
}