-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathSession.cs
More file actions
637 lines (583 loc) · 24.2 KB
/
Session.cs
File metadata and controls
637 lines (583 loc) · 24.2 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
using Microsoft.Extensions.AI;
using StreamJsonRpc;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using GitHub.Copilot.SDK.Rpc;
namespace GitHub.Copilot.SDK;
/// <summary>
/// Represents a single conversation session with the Copilot CLI.
/// </summary>
/// <remarks>
/// <para>
/// A session maintains conversation state, handles events, and manages tool execution.
/// Sessions are created via <see cref="CopilotClient.CreateSessionAsync"/> or resumed via
/// <see cref="CopilotClient.ResumeSessionAsync"/>.
/// </para>
/// <para>
/// The session provides methods to send messages, subscribe to events, retrieve
/// conversation history, and manage the session lifecycle.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// await using var session = await client.CreateSessionAsync(new() { OnPermissionRequest = PermissionHandler.ApproveAll, Model = "gpt-4" });
///
/// // Subscribe to events
/// using var subscription = session.On(evt =>
/// {
/// if (evt is AssistantMessageEvent assistantMessage)
/// {
/// Console.WriteLine($"Assistant: {assistantMessage.Data?.Content}");
/// }
/// });
///
/// // Send a message and wait for completion
/// await session.SendAndWaitAsync(new MessageOptions { Prompt = "Hello, world!" });
/// </code>
/// </example>
public partial class CopilotSession : IAsyncDisposable
{
/// <summary>
/// Multicast delegate used as a thread-safe, insertion-ordered handler list.
/// The compiler-generated add/remove accessors use a lock-free CAS loop over the backing field.
/// Dispatch reads the field once (inherent snapshot, no allocation).
/// Expected handler count is small (typically 1–3), so Delegate.Combine/Remove cost is negligible.
/// </summary>
private event SessionEventHandler? _eventHandlers;
private readonly Dictionary<string, AIFunction> _toolHandlers = new();
private readonly JsonRpc _rpc;
private volatile PermissionRequestHandler? _permissionHandler;
private volatile UserInputHandler? _userInputHandler;
private SessionHooks? _hooks;
private readonly SemaphoreSlim _hooksLock = new(1, 1);
private SessionRpc? _sessionRpc;
private int _isDisposed;
/// <summary>
/// Gets the unique identifier for this session.
/// </summary>
/// <value>A string that uniquely identifies this session.</value>
public string SessionId { get; }
/// <summary>
/// Gets the typed RPC client for session-scoped methods.
/// </summary>
public SessionRpc Rpc => _sessionRpc ??= new SessionRpc(_rpc, SessionId);
/// <summary>
/// Gets the path to the session workspace directory when infinite sessions are enabled.
/// </summary>
/// <value>
/// The path to the workspace containing checkpoints/, plan.md, and files/ subdirectories,
/// or null if infinite sessions are disabled.
/// </value>
public string? WorkspacePath { get; }
/// <summary>
/// Initializes a new instance of the <see cref="CopilotSession"/> class.
/// </summary>
/// <param name="sessionId">The unique identifier for this session.</param>
/// <param name="rpc">The JSON-RPC connection to the Copilot CLI.</param>
/// <param name="workspacePath">The workspace path if infinite sessions are enabled.</param>
/// <remarks>
/// This constructor is internal. Use <see cref="CopilotClient.CreateSessionAsync"/> to create sessions.
/// </remarks>
internal CopilotSession(string sessionId, JsonRpc rpc, string? workspacePath = null)
{
SessionId = sessionId;
_rpc = rpc;
WorkspacePath = workspacePath;
}
private Task<T> InvokeRpcAsync<T>(string method, object?[]? args, CancellationToken cancellationToken) =>
CopilotClient.InvokeRpcAsync<T>(_rpc, method, args, cancellationToken);
/// <summary>
/// Sends a message to the Copilot session and waits for the response.
/// </summary>
/// <param name="options">Options for the message to be sent, including the prompt and optional attachments.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> that can be used to cancel the operation.</param>
/// <returns>A task that resolves with the ID of the response message, which can be used to correlate events.</returns>
/// <exception cref="InvalidOperationException">Thrown if the session has been disposed.</exception>
/// <remarks>
/// <para>
/// This method returns immediately after the message is queued. Use <see cref="SendAndWaitAsync"/>
/// if you need to wait for the assistant to finish processing.
/// </para>
/// <para>
/// Subscribe to events via <see cref="On"/> to receive streaming responses and other session events.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// var messageId = await session.SendAsync(new MessageOptions
/// {
/// Prompt = "Explain this code",
/// Attachments = new List<Attachment>
/// {
/// new() { Type = "file", Path = "./Program.cs" }
/// }
/// });
/// </code>
/// </example>
public async Task<string> SendAsync(MessageOptions options, CancellationToken cancellationToken = default)
{
var request = new SendMessageRequest
{
SessionId = SessionId,
Prompt = options.Prompt,
Attachments = options.Attachments,
Mode = options.Mode
};
var response = await InvokeRpcAsync<SendMessageResponse>(
"session.send", [request], cancellationToken);
return response.MessageId;
}
/// <summary>
/// Sends a message to the Copilot session and waits until the session becomes idle.
/// </summary>
/// <param name="options">Options for the message to be sent, including the prompt and optional attachments.</param>
/// <param name="timeout">Timeout duration (default: 60 seconds). Controls how long to wait; does not abort in-flight agent work.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> that can be used to cancel the operation.</param>
/// <returns>A task that resolves with the final assistant message event, or null if none was received.</returns>
/// <exception cref="TimeoutException">Thrown if the timeout is reached before the session becomes idle.</exception>
/// <exception cref="OperationCanceledException">Thrown if the <paramref name="cancellationToken"/> is cancelled.</exception>
/// <exception cref="InvalidOperationException">Thrown if the session has been disposed.</exception>
/// <remarks>
/// <para>
/// This is a convenience method that combines <see cref="SendAsync"/> with waiting for
/// the <c>session.idle</c> event. Use this when you want to block until the assistant
/// has finished processing the message.
/// </para>
/// <para>
/// Events are still delivered to handlers registered via <see cref="On"/> while waiting.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// // Send and wait for completion with default 60s timeout
/// var response = await session.SendAndWaitAsync(new MessageOptions { Prompt = "What is 2+2?" });
/// Console.WriteLine(response?.Data?.Content); // "4"
/// </code>
/// </example>
public async Task<AssistantMessageEvent?> SendAndWaitAsync(
MessageOptions options,
TimeSpan? timeout = null,
CancellationToken cancellationToken = default)
{
var effectiveTimeout = timeout ?? TimeSpan.FromSeconds(60);
var tcs = new TaskCompletionSource<AssistantMessageEvent?>();
AssistantMessageEvent? lastAssistantMessage = null;
void Handler(SessionEvent evt)
{
switch (evt)
{
case AssistantMessageEvent assistantMessage:
lastAssistantMessage = assistantMessage;
break;
case SessionIdleEvent:
tcs.TrySetResult(lastAssistantMessage);
break;
case SessionErrorEvent errorEvent:
var message = errorEvent.Data?.Message ?? "session error";
tcs.TrySetException(new InvalidOperationException($"Session error: {message}"));
break;
}
}
using var subscription = On(Handler);
await SendAsync(options, cancellationToken);
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(effectiveTimeout);
using var registration = cts.Token.Register(() =>
{
if (cancellationToken.IsCancellationRequested)
tcs.TrySetCanceled(cancellationToken);
else
tcs.TrySetException(new TimeoutException($"SendAndWaitAsync timed out after {effectiveTimeout}"));
});
return await tcs.Task;
}
/// <summary>
/// Registers a callback for session events.
/// </summary>
/// <param name="handler">A callback to be invoked when a session event occurs.</param>
/// <returns>An <see cref="IDisposable"/> that, when disposed, unsubscribes the handler.</returns>
/// <remarks>
/// <para>
/// Events include assistant messages, tool executions, errors, and session state changes.
/// Multiple handlers can be registered and will all receive events.
/// </para>
/// <para>
/// Handler exceptions are allowed to propagate so they are not lost.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// using var subscription = session.On(evt =>
/// {
/// switch (evt)
/// {
/// case AssistantMessageEvent:
/// Console.WriteLine($"Assistant: {evt.Data?.Content}");
/// break;
/// case SessionErrorEvent:
/// Console.WriteLine($"Error: {evt.Data?.Message}");
/// break;
/// }
/// });
///
/// // The handler is automatically unsubscribed when the subscription is disposed.
/// </code>
/// </example>
public IDisposable On(SessionEventHandler handler)
{
_eventHandlers += handler;
return new ActionDisposable(() => _eventHandlers -= handler);
}
/// <summary>
/// Dispatches an event to all registered handlers.
/// </summary>
/// <param name="sessionEvent">The session event to dispatch.</param>
/// <remarks>
/// This method is internal. Handler exceptions are allowed to propagate so they are not lost.
/// </remarks>
internal void DispatchEvent(SessionEvent sessionEvent)
{
// Reading the field once gives us a snapshot; delegates are immutable.
_eventHandlers?.Invoke(sessionEvent);
}
/// <summary>
/// Registers custom tool handlers for this session.
/// </summary>
/// <param name="tools">A collection of AI functions that can be invoked by the assistant.</param>
/// <remarks>
/// Tools allow the assistant to execute custom functions. When the assistant invokes a tool,
/// the corresponding handler is called with the tool arguments.
/// </remarks>
internal void RegisterTools(ICollection<AIFunction> tools)
{
_toolHandlers.Clear();
foreach (var tool in tools)
{
_toolHandlers.Add(tool.Name, tool);
}
}
/// <summary>
/// Retrieves a registered tool by name.
/// </summary>
/// <param name="name">The name of the tool to retrieve.</param>
/// <returns>The tool if found; otherwise, <c>null</c>.</returns>
internal AIFunction? GetTool(string name) =>
_toolHandlers.TryGetValue(name, out var tool) ? tool : null;
/// <summary>
/// Registers a handler for permission requests.
/// </summary>
/// <param name="handler">The permission handler function.</param>
/// <remarks>
/// When the assistant needs permission to perform certain actions (e.g., file operations),
/// this handler is called to approve or deny the request.
/// </remarks>
internal void RegisterPermissionHandler(PermissionRequestHandler handler)
{
_permissionHandler = handler;
}
/// <summary>
/// Handles a permission request from the Copilot CLI.
/// </summary>
/// <param name="permissionRequestData">The permission request data from the CLI.</param>
/// <returns>A task that resolves with the permission decision.</returns>
internal async Task<PermissionRequestResult> HandlePermissionRequestAsync(JsonElement permissionRequestData)
{
var handler = _permissionHandler;
if (handler == null)
{
return new PermissionRequestResult
{
Kind = "denied-no-approval-rule-and-could-not-request-from-user"
};
}
var request = JsonSerializer.Deserialize(permissionRequestData.GetRawText(), SessionJsonContext.Default.PermissionRequest)
?? throw new InvalidOperationException("Failed to deserialize permission request");
var invocation = new PermissionInvocation
{
SessionId = SessionId
};
return await handler(request, invocation);
}
/// <summary>
/// Registers a handler for user input requests from the agent.
/// </summary>
/// <param name="handler">The handler to invoke when user input is requested.</param>
internal void RegisterUserInputHandler(UserInputHandler handler)
{
_userInputHandler = handler;
}
/// <summary>
/// Handles a user input request from the Copilot CLI.
/// </summary>
/// <param name="request">The user input request from the CLI.</param>
/// <returns>A task that resolves with the user's response.</returns>
internal async Task<UserInputResponse> HandleUserInputRequestAsync(UserInputRequest request)
{
var handler = _userInputHandler;
if (handler == null)
{
throw new InvalidOperationException("No user input handler registered");
}
var invocation = new UserInputInvocation
{
SessionId = SessionId
};
return await handler(request, invocation);
}
/// <summary>
/// Registers hook handlers for this session.
/// </summary>
/// <param name="hooks">The hooks configuration.</param>
internal void RegisterHooks(SessionHooks hooks)
{
_hooksLock.Wait();
try
{
_hooks = hooks;
}
finally
{
_hooksLock.Release();
}
}
/// <summary>
/// Handles a hook invocation from the Copilot CLI.
/// </summary>
/// <param name="hookType">The type of hook to invoke.</param>
/// <param name="input">The hook input data.</param>
/// <returns>A task that resolves with the hook output.</returns>
internal async Task<object?> HandleHooksInvokeAsync(string hookType, JsonElement input)
{
await _hooksLock.WaitAsync();
SessionHooks? hooks;
try
{
hooks = _hooks;
}
finally
{
_hooksLock.Release();
}
if (hooks == null)
{
return null;
}
var invocation = new HookInvocation
{
SessionId = SessionId
};
return hookType switch
{
"preToolUse" => hooks.OnPreToolUse != null
? await hooks.OnPreToolUse(
JsonSerializer.Deserialize(input.GetRawText(), SessionJsonContext.Default.PreToolUseHookInput)!,
invocation)
: null,
"postToolUse" => hooks.OnPostToolUse != null
? await hooks.OnPostToolUse(
JsonSerializer.Deserialize(input.GetRawText(), SessionJsonContext.Default.PostToolUseHookInput)!,
invocation)
: null,
"userPromptSubmitted" => hooks.OnUserPromptSubmitted != null
? await hooks.OnUserPromptSubmitted(
JsonSerializer.Deserialize(input.GetRawText(), SessionJsonContext.Default.UserPromptSubmittedHookInput)!,
invocation)
: null,
"sessionStart" => hooks.OnSessionStart != null
? await hooks.OnSessionStart(
JsonSerializer.Deserialize(input.GetRawText(), SessionJsonContext.Default.SessionStartHookInput)!,
invocation)
: null,
"sessionEnd" => hooks.OnSessionEnd != null
? await hooks.OnSessionEnd(
JsonSerializer.Deserialize(input.GetRawText(), SessionJsonContext.Default.SessionEndHookInput)!,
invocation)
: null,
"errorOccurred" => hooks.OnErrorOccurred != null
? await hooks.OnErrorOccurred(
JsonSerializer.Deserialize(input.GetRawText(), SessionJsonContext.Default.ErrorOccurredHookInput)!,
invocation)
: null,
_ => throw new ArgumentException($"Unknown hook type: {hookType}")
};
}
/// <summary>
/// Gets the complete list of messages and events in the session.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> that can be used to cancel the operation.</param>
/// <returns>A task that, when resolved, gives the list of all session events in chronological order.</returns>
/// <exception cref="InvalidOperationException">Thrown if the session has been disposed.</exception>
/// <remarks>
/// This returns the complete conversation history including user messages, assistant responses,
/// tool executions, and other session events.
/// </remarks>
/// <example>
/// <code>
/// var events = await session.GetMessagesAsync();
/// foreach (var evt in events)
/// {
/// if (evt is AssistantMessageEvent)
/// {
/// Console.WriteLine($"Assistant: {evt.Data?.Content}");
/// }
/// }
/// </code>
/// </example>
public async Task<IReadOnlyList<SessionEvent>> GetMessagesAsync(CancellationToken cancellationToken = default)
{
var response = await InvokeRpcAsync<GetMessagesResponse>(
"session.getMessages", [new GetMessagesRequest { SessionId = SessionId }], cancellationToken);
return response.Events
.Select(e => SessionEvent.FromJson(e.ToJsonString()))
.OfType<SessionEvent>()
.ToList();
}
/// <summary>
/// Aborts the currently processing message in this session.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> that can be used to cancel the operation.</param>
/// <returns>A task representing the abort operation.</returns>
/// <exception cref="InvalidOperationException">Thrown if the session has been disposed.</exception>
/// <remarks>
/// Use this to cancel a long-running request. The session remains valid and can continue
/// to be used for new messages.
/// </remarks>
/// <example>
/// <code>
/// // Start a long-running request
/// var messageTask = session.SendAsync(new MessageOptions
/// {
/// Prompt = "Write a very long story..."
/// });
///
/// // Abort after 5 seconds
/// await Task.Delay(TimeSpan.FromSeconds(5));
/// await session.AbortAsync();
/// </code>
/// </example>
public async Task AbortAsync(CancellationToken cancellationToken = default)
{
await InvokeRpcAsync<object>(
"session.abort", [new SessionAbortRequest { SessionId = SessionId }], cancellationToken);
}
/// <summary>
/// Changes the model for this session.
/// The new model takes effect for the next message. Conversation history is preserved.
/// </summary>
/// <param name="model">Model ID to switch to (e.g., "gpt-4.1").</param>
/// <param name="cancellationToken">Optional cancellation token.</param>
/// <example>
/// <code>
/// await session.SetModelAsync("gpt-4.1");
/// </code>
/// </example>
public async Task SetModelAsync(string model, CancellationToken cancellationToken = default)
{
await Rpc.Model.SwitchToAsync(model, cancellationToken);
}
/// <summary>
/// Disposes the <see cref="CopilotSession"/> and releases all associated resources.
/// </summary>
/// <returns>A task representing the dispose operation.</returns>
/// <remarks>
/// <para>
/// After calling this method, the session can no longer be used. All event handlers
/// and tool handlers are cleared.
/// </para>
/// <para>
/// To continue the conversation, use <see cref="CopilotClient.ResumeSessionAsync"/>
/// with the session ID.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// // Using 'await using' for automatic disposal
/// await using var session = await client.CreateSessionAsync(new() { OnPermissionRequest = PermissionHandler.ApproveAll });
///
/// // Or manually dispose
/// var session2 = await client.CreateSessionAsync(new() { OnPermissionRequest = PermissionHandler.ApproveAll });
/// // ... use the session ...
/// await session2.DisposeAsync();
/// </code>
/// </example>
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _isDisposed, 1) == 1)
{
return;
}
try
{
await InvokeRpcAsync<object>(
"session.destroy", [new SessionDestroyRequest() { SessionId = SessionId }], CancellationToken.None);
}
catch (ObjectDisposedException)
{
// Connection was already disposed (e.g., client.StopAsync() was called first)
}
catch (IOException)
{
// Connection is broken or closed
}
_eventHandlers = null;
_toolHandlers.Clear();
_permissionHandler = null;
}
internal record SendMessageRequest
{
public string SessionId { get; init; } = string.Empty;
public string Prompt { get; init; } = string.Empty;
public List<UserMessageDataAttachmentsItem>? Attachments { get; init; }
public string? Mode { get; init; }
}
internal record SendMessageResponse
{
public string MessageId { get; init; } = string.Empty;
}
internal record GetMessagesRequest
{
public string SessionId { get; init; } = string.Empty;
}
internal record GetMessagesResponse
{
public List<JsonObject> Events { get; init; } = new();
}
internal record SessionAbortRequest
{
public string SessionId { get; init; } = string.Empty;
}
internal record SessionDestroyRequest
{
public string SessionId { get; init; } = string.Empty;
}
[JsonSourceGenerationOptions(
JsonSerializerDefaults.Web,
AllowOutOfOrderMetadataProperties = true,
NumberHandling = JsonNumberHandling.AllowReadingFromString,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(GetMessagesRequest))]
[JsonSerializable(typeof(GetMessagesResponse))]
[JsonSerializable(typeof(PermissionRequest))]
[JsonSerializable(typeof(SendMessageRequest))]
[JsonSerializable(typeof(SendMessageResponse))]
[JsonSerializable(typeof(SessionAbortRequest))]
[JsonSerializable(typeof(SessionDestroyRequest))]
[JsonSerializable(typeof(UserMessageDataAttachmentsItem))]
[JsonSerializable(typeof(PreToolUseHookInput))]
[JsonSerializable(typeof(PreToolUseHookOutput))]
[JsonSerializable(typeof(PostToolUseHookInput))]
[JsonSerializable(typeof(PostToolUseHookOutput))]
[JsonSerializable(typeof(UserPromptSubmittedHookInput))]
[JsonSerializable(typeof(UserPromptSubmittedHookOutput))]
[JsonSerializable(typeof(SessionStartHookInput))]
[JsonSerializable(typeof(SessionStartHookOutput))]
[JsonSerializable(typeof(SessionEndHookInput))]
[JsonSerializable(typeof(SessionEndHookOutput))]
[JsonSerializable(typeof(ErrorOccurredHookInput))]
[JsonSerializable(typeof(ErrorOccurredHookOutput))]
internal partial class SessionJsonContext : JsonSerializerContext;
}