-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathSession.cs
More file actions
1281 lines (1173 loc) · 50.6 KB
/
Session.cs
File metadata and controls
1281 lines (1173 loc) · 50.6 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
using GitHub.Copilot.SDK.Rpc;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using StreamJsonRpc;
using System.Collections.Immutable;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Threading.Channels;
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>
/// <para>
/// <see cref="CopilotSession"/> implements <see cref="IAsyncDisposable"/>. Use the
/// <c>await using</c> pattern for automatic cleanup, or call <see cref="DisposeAsync"/>
/// explicitly. Disposing a session releases in-memory resources but preserves session data
/// on disk — the conversation can be resumed later via
/// <see cref="CopilotClient.ResumeSessionAsync"/>. To permanently delete session data,
/// use <see cref="CopilotClient.DeleteSessionAsync"/>.
/// </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 sealed partial class CopilotSession : IAsyncDisposable
{
private readonly Dictionary<string, AIFunction> _toolHandlers = [];
private readonly Dictionary<string, CommandHandler> _commandHandlers = [];
private readonly JsonRpc _rpc;
private readonly ILogger _logger;
private volatile PermissionRequestHandler? _permissionHandler;
private volatile UserInputHandler? _userInputHandler;
private volatile ElicitationHandler? _elicitationHandler;
private ImmutableArray<SessionEventHandler> _eventHandlers = ImmutableArray<SessionEventHandler>.Empty;
private SessionHooks? _hooks;
private readonly SemaphoreSlim _hooksLock = new(1, 1);
private Dictionary<string, Func<string, Task<string>>>? _transformCallbacks;
private readonly SemaphoreSlim _transformCallbacksLock = new(1, 1);
private SessionRpc? _sessionRpc;
private int _isDisposed;
/// <summary>
/// Channel that serializes event dispatch. <see cref="DispatchEvent"/> enqueues;
/// a single background consumer (<see cref="ProcessEventsAsync"/>) dequeues and
/// invokes handlers one at a time, preserving arrival order.
/// </summary>
private readonly Channel<SessionEvent> _eventChannel = Channel.CreateUnbounded<SessionEvent>(
new() { SingleReader = true });
/// <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; internal set; }
/// <summary>
/// Gets the capabilities reported by the host for this session.
/// </summary>
/// <value>
/// A <see cref="SessionCapabilities"/> object describing what the host supports.
/// Capabilities are populated from the session create/resume response and updated
/// in real time via <c>capabilities.changed</c> events.
/// </value>
public SessionCapabilities Capabilities { get; private set; } = new();
/// <summary>
/// Gets the UI API for eliciting information from the user during this session.
/// </summary>
/// <value>
/// An <see cref="ISessionUiApi"/> implementation with convenience methods for
/// confirm, select, input, and custom elicitation dialogs.
/// </value>
/// <remarks>
/// All methods on this property throw <see cref="InvalidOperationException"/>
/// if the host does not report elicitation support via <see cref="Capabilities"/>.
/// Check <c>session.Capabilities.Ui?.Elicitation == true</c> before calling.
/// </remarks>
public ISessionUiApi Ui { get; }
internal ClientSessionApiHandlers ClientSessionApis { get; } = new();
/// <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="logger">Logger for diagnostics.</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, ILogger logger, string? workspacePath = null)
{
SessionId = sessionId;
_rpc = rpc;
_logger = logger;
WorkspacePath = workspacePath;
Ui = new SessionUiApiImpl(this);
// Start the asynchronous processing loop.
_ = ProcessEventsAsync();
}
private Task<T> InvokeRpcAsync<T>(string method, object?[]? args, CancellationToken cancellationToken)
{
return 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 (traceparent, tracestate) = TelemetryHelpers.GetTraceContext();
var request = new SendMessageRequest
{
SessionId = SessionId,
Prompt = options.Prompt,
Attachments = options.Attachments,
Mode = options.Mode,
Traceparent = traceparent,
Tracestate = tracestate
};
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?>(TaskCreationOptions.RunContinuationsAsynchronously);
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>
/// Handlers are invoked serially in event-arrival order on a background thread.
/// A handler will never be called concurrently with itself or with other handlers
/// on the same session.
/// </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)
{
ImmutableInterlocked.Update(ref _eventHandlers, array => array.Add(handler));
return new ActionDisposable(() => ImmutableInterlocked.Update(ref _eventHandlers, array => array.Remove(handler)));
}
/// <summary>
/// Enqueues an event for serial dispatch to all registered handlers.
/// </summary>
/// <param name="sessionEvent">The session event to dispatch.</param>
/// <remarks>
/// This method is non-blocking. Broadcast request events (external_tool.requested,
/// permission.requested) are fired concurrently so that a stalled handler does not
/// block event delivery. The event is then placed into an in-memory channel and
/// processed by a single background consumer (<see cref="ProcessEventsAsync"/>),
/// which guarantees user handlers see events one at a time, in order.
/// </remarks>
internal void DispatchEvent(SessionEvent sessionEvent)
{
// Fire broadcast work concurrently (fire-and-forget with error logging).
// This is done outside the channel so broadcast handlers don't block the
// consumer loop — important when a secondary client's handler intentionally
// never completes (multi-client permission scenario).
_ = HandleBroadcastEventAsync(sessionEvent);
// Queue the event for serial processing by user handlers.
_eventChannel.Writer.TryWrite(sessionEvent);
}
/// <summary>
/// Single-reader consumer loop that processes events from the channel.
/// Ensures user event handlers are invoked serially and in FIFO order.
/// </summary>
private async Task ProcessEventsAsync()
{
await foreach (var sessionEvent in _eventChannel.Reader.ReadAllAsync())
{
foreach (var handler in _eventHandlers)
{
try
{
handler(sessionEvent);
}
catch (Exception ex)
{
LogEventHandlerError(ex);
}
}
}
}
/// <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)
{
return _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 = PermissionRequestResultKind.DeniedCouldNotRequestFromUser
};
}
var request = JsonSerializer.Deserialize(permissionRequestData.GetRawText(), SessionEventsJsonContext.Default.PermissionRequest)
?? throw new InvalidOperationException("Failed to deserialize permission request");
var invocation = new PermissionInvocation
{
SessionId = SessionId
};
return await handler(request, invocation);
}
/// <summary>
/// Handles broadcast request events by executing local handlers and responding via RPC.
/// Implements the protocol v3 broadcast model where tool calls and permission requests
/// are broadcast as session events to all clients.
/// </summary>
private async Task HandleBroadcastEventAsync(SessionEvent sessionEvent)
{
try
{
switch (sessionEvent)
{
case ExternalToolRequestedEvent toolEvent:
{
var data = toolEvent.Data;
if (string.IsNullOrEmpty(data.RequestId) || string.IsNullOrEmpty(data.ToolName))
return;
var tool = GetTool(data.ToolName);
if (tool is null)
return; // This client doesn't handle this tool; another client will.
using (TelemetryHelpers.RestoreTraceContext(data.Traceparent, data.Tracestate))
await ExecuteToolAndRespondAsync(data.RequestId, data.ToolName, data.ToolCallId, data.Arguments, tool);
break;
}
case PermissionRequestedEvent permEvent:
{
var data = permEvent.Data;
if (string.IsNullOrEmpty(data.RequestId) || data.PermissionRequest is null)
return;
if (data.ResolvedByHook == true)
return; // Already resolved by a permissionRequest hook; no client action needed.
var handler = _permissionHandler;
if (handler is null)
return; // This client doesn't handle permissions; another client will.
await ExecutePermissionAndRespondAsync(data.RequestId, data.PermissionRequest, handler);
break;
}
case CommandExecuteEvent cmdEvent:
{
var data = cmdEvent.Data;
if (string.IsNullOrEmpty(data.RequestId))
return;
await ExecuteCommandAndRespondAsync(data.RequestId, data.CommandName, data.Command, data.Args);
break;
}
case ElicitationRequestedEvent elicitEvent:
{
var data = elicitEvent.Data;
if (string.IsNullOrEmpty(data.RequestId))
return;
if (_elicitationHandler is not null)
{
var schema = data.RequestedSchema is not null
? new ElicitationSchema
{
Type = data.RequestedSchema.Type,
Properties = data.RequestedSchema.Properties,
Required = data.RequestedSchema.Required?.ToList()
}
: null;
await HandleElicitationRequestAsync(
new ElicitationContext
{
SessionId = SessionId,
Message = data.Message,
RequestedSchema = schema,
Mode = data.Mode,
ElicitationSource = data.ElicitationSource,
Url = data.Url
},
data.RequestId);
}
break;
}
case CapabilitiesChangedEvent capEvent:
{
var data = capEvent.Data;
Capabilities = new SessionCapabilities
{
Ui = data.Ui is not null
? new SessionUiCapabilities { Elicitation = data.Ui.Elicitation }
: Capabilities.Ui
};
break;
}
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogBroadcastHandlerError(ex);
}
}
/// <summary>
/// Executes a tool handler and sends the result back via the HandlePendingToolCall RPC.
/// </summary>
private async Task ExecuteToolAndRespondAsync(string requestId, string toolName, string toolCallId, object? arguments, AIFunction tool)
{
try
{
var invocation = new ToolInvocation
{
SessionId = SessionId,
ToolCallId = toolCallId,
ToolName = toolName,
Arguments = arguments
};
var aiFunctionArgs = new AIFunctionArguments
{
Context = new Dictionary<object, object?>
{
[typeof(ToolInvocation)] = invocation
}
};
if (arguments is not null)
{
if (arguments is not JsonElement incomingJsonArgs)
{
throw new InvalidOperationException($"Incoming arguments must be a {nameof(JsonElement)}; received {arguments.GetType().Name}");
}
foreach (var prop in incomingJsonArgs.EnumerateObject())
{
aiFunctionArgs[prop.Name] = prop.Value;
}
}
var result = await tool.InvokeAsync(aiFunctionArgs);
var toolResultObject = ToolResultObject.ConvertFromInvocationResult(result, tool.JsonSerializerOptions);
await Rpc.Tools.HandlePendingToolCallAsync(requestId, toolResultObject, error: null);
}
catch (Exception ex)
{
try
{
await Rpc.Tools.HandlePendingToolCallAsync(requestId, result: null, error: ex.Message);
}
catch (IOException)
{
// Connection lost or RPC error — nothing we can do
}
catch (ObjectDisposedException)
{
// Connection already disposed — nothing we can do
}
}
}
/// <summary>
/// Executes a permission handler and sends the result back via the HandlePendingPermissionRequest RPC.
/// </summary>
private async Task ExecutePermissionAndRespondAsync(string requestId, PermissionRequest permissionRequest, PermissionRequestHandler handler)
{
try
{
var invocation = new PermissionInvocation
{
SessionId = SessionId
};
var result = await handler(permissionRequest, invocation);
if (result.Kind == new PermissionRequestResultKind("no-result"))
{
return;
}
await Rpc.Permissions.HandlePendingPermissionRequestAsync(requestId, result);
}
catch (Exception)
{
try
{
await Rpc.Permissions.HandlePendingPermissionRequestAsync(requestId, new PermissionRequestResult
{
Kind = PermissionRequestResultKind.DeniedCouldNotRequestFromUser
});
}
catch (IOException)
{
// Connection lost or RPC error — nothing we can do
}
catch (ObjectDisposedException)
{
// Connection already disposed — nothing we can do
}
}
}
/// <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>
/// Registers command handlers for this session.
/// </summary>
/// <param name="commands">The command definitions to register.</param>
internal void RegisterCommands(IEnumerable<CommandDefinition>? commands)
{
_commandHandlers.Clear();
if (commands is null) return;
foreach (var cmd in commands)
{
_commandHandlers[cmd.Name] = cmd.Handler;
}
}
/// <summary>
/// Registers an elicitation handler for this session.
/// </summary>
/// <param name="handler">The handler to invoke when an elicitation request is received.</param>
internal void RegisterElicitationHandler(ElicitationHandler? handler)
{
_elicitationHandler = handler;
}
/// <summary>
/// Sets the capabilities reported by the host for this session.
/// </summary>
/// <param name="capabilities">The capabilities to set.</param>
internal void SetCapabilities(SessionCapabilities? capabilities)
{
Capabilities = capabilities ?? new SessionCapabilities();
}
/// <summary>
/// Dispatches a command.execute event to the registered handler and
/// responds via the commands.handlePendingCommand RPC.
/// </summary>
private async Task ExecuteCommandAndRespondAsync(string requestId, string commandName, string command, string args)
{
if (!_commandHandlers.TryGetValue(commandName, out var handler))
{
try
{
await Rpc.Commands.HandlePendingCommandAsync(requestId, error: $"Unknown command: {commandName}");
}
catch (Exception ex) when (ex is IOException or ObjectDisposedException)
{
// Connection lost — nothing we can do
}
return;
}
try
{
await handler(new CommandContext
{
SessionId = SessionId,
Command = command,
CommandName = commandName,
Args = args
});
await Rpc.Commands.HandlePendingCommandAsync(requestId);
}
catch (Exception error) when (error is not OperationCanceledException)
{
// User handler can throw any exception — report the error back to the server
// so the pending command doesn't hang.
var message = error.Message;
try
{
await Rpc.Commands.HandlePendingCommandAsync(requestId, error: message);
}
catch (Exception ex) when (ex is IOException or ObjectDisposedException)
{
// Connection lost — nothing we can do
}
}
}
/// <summary>
/// Dispatches an elicitation.requested event to the registered handler and
/// responds via the ui.handlePendingElicitation RPC. Auto-cancels on handler errors.
/// </summary>
private async Task HandleElicitationRequestAsync(ElicitationContext context, string requestId)
{
var handler = _elicitationHandler;
if (handler is null) return;
try
{
var result = await handler(context);
await Rpc.Ui.HandlePendingElicitationAsync(requestId, new SessionUiHandlePendingElicitationRequestResult
{
Action = result.Action,
Content = result.Content
});
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// User handler can throw any exception — attempt to cancel so the request doesn't hang.
try
{
await Rpc.Ui.HandlePendingElicitationAsync(requestId, new SessionUiHandlePendingElicitationRequestResult
{
Action = SessionUiElicitationResultAction.Cancel
});
}
catch (Exception innerEx) when (innerEx is IOException or ObjectDisposedException)
{
// Connection lost — nothing we can do
}
}
}
/// <summary>
/// Throws if the host does not support elicitation.
/// </summary>
private void AssertElicitation()
{
if (Capabilities.Ui?.Elicitation != true)
{
throw new InvalidOperationException(
"Elicitation is not supported by the host. " +
"Check session.Capabilities.Ui?.Elicitation before calling UI methods.");
}
}
/// <summary>
/// Implements <see cref="ISessionUiApi"/> backed by the session's RPC connection.
/// </summary>
private sealed class SessionUiApiImpl(CopilotSession session) : ISessionUiApi
{
public async Task<ElicitationResult> ElicitationAsync(ElicitationParams elicitationParams, CancellationToken cancellationToken)
{
session.AssertElicitation();
var schema = new SessionUiElicitationRequestRequestedSchema
{
Type = elicitationParams.RequestedSchema.Type,
Properties = elicitationParams.RequestedSchema.Properties,
Required = elicitationParams.RequestedSchema.Required
};
var result = await session.Rpc.Ui.ElicitationAsync(elicitationParams.Message, schema, cancellationToken);
return new ElicitationResult { Action = result.Action, Content = result.Content };
}
public async Task<bool> ConfirmAsync(string message, CancellationToken cancellationToken)
{
session.AssertElicitation();
var schema = new SessionUiElicitationRequestRequestedSchema
{
Type = "object",
Properties = new Dictionary<string, object>
{
["confirmed"] = new Dictionary<string, object> { ["type"] = "boolean", ["default"] = true }
},
Required = ["confirmed"]
};
var result = await session.Rpc.Ui.ElicitationAsync(message, schema, cancellationToken);
if (result.Action == SessionUiElicitationResultAction.Accept
&& result.Content != null
&& result.Content.TryGetValue("confirmed", out var val))
{
return val switch
{
bool b => b,
JsonElement { ValueKind: JsonValueKind.True } => true,
JsonElement { ValueKind: JsonValueKind.False } => false,
_ => false
};
}
return false;
}
public async Task<string?> SelectAsync(string message, string[] options, CancellationToken cancellationToken)
{
session.AssertElicitation();
var schema = new SessionUiElicitationRequestRequestedSchema
{
Type = "object",
Properties = new Dictionary<string, object>
{
["selection"] = new Dictionary<string, object> { ["type"] = "string", ["enum"] = options }
},
Required = ["selection"]
};
var result = await session.Rpc.Ui.ElicitationAsync(message, schema, cancellationToken);
if (result.Action == SessionUiElicitationResultAction.Accept
&& result.Content != null
&& result.Content.TryGetValue("selection", out var val))
{
return val switch
{
string s => s,
JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(),
_ => val.ToString()
};
}
return null;
}
public async Task<string?> InputAsync(string message, InputOptions? options, CancellationToken cancellationToken)
{
session.AssertElicitation();
var field = new Dictionary<string, object> { ["type"] = "string" };
if (options?.Title != null) field["title"] = options.Title;
if (options?.Description != null) field["description"] = options.Description;
if (options?.MinLength != null) field["minLength"] = options.MinLength;
if (options?.MaxLength != null) field["maxLength"] = options.MaxLength;
if (options?.Format != null) field["format"] = options.Format;
if (options?.Default != null) field["default"] = options.Default;
var schema = new SessionUiElicitationRequestRequestedSchema
{
Type = "object",
Properties = new Dictionary<string, object> { ["value"] = field },
Required = ["value"]
};
var result = await session.Rpc.Ui.ElicitationAsync(message, schema, cancellationToken);
if (result.Action == SessionUiElicitationResultAction.Accept
&& result.Content != null
&& result.Content.TryGetValue("value", out var val))
{
return val switch
{
string s => s,
JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(),
_ => val.ToString()
};
}
return null;
}
}
/// <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 ?? 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,
_ => null
};
}
/// <summary>
/// Registers transform callbacks for system message sections.
/// </summary>
/// <param name="callbacks">The transform callbacks keyed by section identifier.</param>
internal void RegisterTransformCallbacks(Dictionary<string, Func<string, Task<string>>>? callbacks)
{
_transformCallbacksLock.Wait();
try
{
_transformCallbacks = callbacks;
}
finally
{
_transformCallbacksLock.Release();
}
}
/// <summary>
/// Handles a systemMessage.transform RPC call from the Copilot CLI.
/// </summary>
/// <param name="sections">The raw JSON element containing sections to transform.</param>
/// <returns>A task that resolves with the transformed sections.</returns>
internal async Task<SystemMessageTransformRpcResponse> HandleSystemMessageTransformAsync(JsonElement sections)
{
Dictionary<string, Func<string, Task<string>>>? callbacks;
await _transformCallbacksLock.WaitAsync();
try
{
callbacks = _transformCallbacks;
}
finally