-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathSession.cs
More file actions
372 lines (344 loc) · 13.1 KB
/
Session.cs
File metadata and controls
372 lines (344 loc) · 13.1 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
using Microsoft.Extensions.AI;
using StreamJsonRpc;
using System.Text.Json;
using System.Text.Json.Nodes;
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 SessionConfig { Model = "gpt-4" });
///
/// // Subscribe to events
/// using var subscription = session.On(evt =>
/// {
/// if (evt.Type == "assistant.message")
/// {
/// Console.WriteLine($"Assistant: {evt.Data?.Content}");
/// }
/// });
///
/// // Send a message
/// await session.SendAsync(new MessageOptions { Prompt = "Hello, world!" });
/// </code>
/// </example>
public class CopilotSession : IAsyncDisposable
{
private readonly HashSet<SessionEventHandler> _eventHandlers = new();
private readonly Dictionary<string, AIFunction> _toolHandlers = new();
private readonly JsonRpc _rpc;
private PermissionHandler? _permissionHandler;
private readonly SemaphoreSlim _permissionHandlerLock = new(1, 1);
/// <summary>
/// Gets the unique identifier for this session.
/// </summary>
/// <value>A string that uniquely identifies this session.</value>
public string SessionId { 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>
/// <remarks>
/// This constructor is internal. Use <see cref="CopilotClient.CreateSessionAsync"/> to create sessions.
/// </remarks>
internal CopilotSession(string sessionId, JsonRpc rpc)
{
SessionId = sessionId;
_rpc = rpc;
}
/// <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>
/// The message is processed asynchronously. Subscribe to events via <see cref="On"/> to receive
/// streaming responses and other session events.
/// </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 _rpc.InvokeWithCancellationAsync<SendMessageResponse>(
"session.send", [request], cancellationToken);
return response.MessageId;
}
/// <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.Type)
/// {
/// case "assistant.message":
/// Console.WriteLine($"Assistant: {evt.Data?.Content}");
/// break;
/// case "session.error":
/// 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.Add(handler);
return new OnDisposeCall(() => _eventHandlers.Remove(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)
{
foreach (var handler in _eventHandlers.ToArray())
{
// We allow handler exceptions to propagate so they are not lost
handler(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(PermissionHandler handler)
{
_permissionHandlerLock.Wait();
try
{
_permissionHandler = handler;
}
finally
{
_permissionHandlerLock.Release();
}
}
/// <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)
{
await _permissionHandlerLock.WaitAsync();
PermissionHandler? handler;
try
{
handler = _permissionHandler;
}
finally
{
_permissionHandlerLock.Release();
}
if (handler == null)
{
return new PermissionRequestResult
{
Kind = "denied-no-approval-rule-and-could-not-request-from-user"
};
}
var request = JsonSerializer.Deserialize<PermissionRequest>(permissionRequestData.GetRawText())
?? throw new InvalidOperationException("Failed to deserialize permission request");
var invocation = new PermissionInvocation
{
SessionId = SessionId
};
return await handler(request, invocation);
}
/// <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.Type == "assistant.message")
/// {
/// Console.WriteLine($"Assistant: {evt.Data?.Content}");
/// }
/// }
/// </code>
/// </example>
public async Task<IReadOnlyList<SessionEvent>> GetMessagesAsync(CancellationToken cancellationToken = default)
{
var response = await _rpc.InvokeWithCancellationAsync<GetMessagesResponse>(
"session.getMessages", [new { sessionId = SessionId }], cancellationToken);
return response.Events.Select(e => SessionEvent.FromJson(e.ToJsonString())).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 _rpc.InvokeWithCancellationAsync<object>(
"session.abort", [new { sessionId = SessionId }], 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();
///
/// // Or manually dispose
/// var session2 = await client.CreateSessionAsync();
/// // ... use the session ...
/// await session2.DisposeAsync();
/// </code>
/// </example>
public async ValueTask DisposeAsync()
{
await _rpc.InvokeWithCancellationAsync<object>(
"session.destroy", [new { sessionId = SessionId }]);
_eventHandlers.Clear();
_toolHandlers.Clear();
await _permissionHandlerLock.WaitAsync();
try
{
_permissionHandler = null;
}
finally
{
_permissionHandlerLock.Release();
}
}
private class OnDisposeCall(Action callback) : IDisposable
{
public void Dispose() => callback();
}
private 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; }
}
private record SendMessageResponse
{
public string MessageId { get; init; } = string.Empty;
}
private record GetMessagesResponse
{
public List<JsonObject> Events { get; init; } = new();
}
}