-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathTypes.cs
More file actions
2641 lines (2315 loc) · 90.6 KB
/
Types.cs
File metadata and controls
2641 lines (2315 loc) · 90.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 System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Text.Json.Serialization;
using GitHub.Copilot.SDK.Rpc;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
namespace GitHub.Copilot.SDK;
/// <summary>
/// Represents the connection state of the Copilot client.
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter<ConnectionState>))]
public enum ConnectionState
{
/// <summary>The client is not connected to the server.</summary>
[JsonStringEnumMemberName("disconnected")]
Disconnected,
/// <summary>The client is establishing a connection to the server.</summary>
[JsonStringEnumMemberName("connecting")]
Connecting,
/// <summary>The client is connected and ready to communicate.</summary>
[JsonStringEnumMemberName("connected")]
Connected,
/// <summary>The connection is in an error state.</summary>
[JsonStringEnumMemberName("error")]
Error
}
/// <summary>
/// Configuration options for creating a <see cref="CopilotClient"/> instance.
/// </summary>
public class CopilotClientOptions
{
/// <summary>
/// Initializes a new instance of the <see cref="CopilotClientOptions"/> class.
/// </summary>
public CopilotClientOptions() { }
/// <summary>
/// Initializes a new instance of the <see cref="CopilotClientOptions"/> class
/// by copying the properties of the specified instance.
/// </summary>
protected CopilotClientOptions(CopilotClientOptions? other)
{
if (other is null) return;
AutoStart = other.AutoStart;
#pragma warning disable CS0618 // Obsolete member
AutoRestart = other.AutoRestart;
#pragma warning restore CS0618
CliArgs = (string[]?)other.CliArgs?.Clone();
CliPath = other.CliPath;
CliUrl = other.CliUrl;
Cwd = other.Cwd;
Environment = other.Environment;
GitHubToken = other.GitHubToken;
Logger = other.Logger;
LogLevel = other.LogLevel;
Port = other.Port;
Telemetry = other.Telemetry;
UseLoggedInUser = other.UseLoggedInUser;
UseStdio = other.UseStdio;
OnListModels = other.OnListModels;
SessionFs = other.SessionFs;
}
/// <summary>
/// Path to the Copilot CLI executable. If not specified, uses the bundled CLI from the SDK.
/// </summary>
public string? CliPath { get; set; }
/// <summary>
/// Additional command-line arguments to pass to the CLI process.
/// </summary>
public string[]? CliArgs { get; set; }
/// <summary>
/// Working directory for the CLI process.
/// </summary>
public string? Cwd { get; set; }
/// <summary>
/// Port number for the CLI server when not using stdio transport.
/// </summary>
public int Port { get; set; }
/// <summary>
/// Whether to use stdio transport for communication with the CLI server.
/// </summary>
public bool UseStdio { get; set; } = true;
/// <summary>
/// URL of an existing CLI server to connect to instead of starting a new one.
/// </summary>
public string? CliUrl { get; set; }
/// <summary>
/// Log level for the CLI server (e.g., "info", "debug", "warn", "error").
/// </summary>
public string LogLevel { get; set; } = "info";
/// <summary>
/// Whether to automatically start the CLI server if it is not already running.
/// </summary>
public bool AutoStart { get; set; } = true;
/// <summary>
/// Obsolete. This option has no effect.
/// </summary>
[Obsolete("AutoRestart has no effect and will be removed in a future release.")]
public bool AutoRestart { get; set; }
/// <summary>
/// Environment variables to pass to the CLI process.
/// </summary>
public IReadOnlyDictionary<string, string>? Environment { get; set; }
/// <summary>
/// Logger instance for SDK diagnostic output.
/// </summary>
public ILogger? Logger { get; set; }
/// <summary>
/// GitHub token to use for authentication.
/// When provided, the token is passed to the CLI server via environment variable.
/// This takes priority over other authentication methods.
/// </summary>
public string? GitHubToken { get; set; }
/// <summary>
/// Obsolete. Use <see cref="GitHubToken"/> instead.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use GitHubToken instead.", error: false)]
public string? GithubToken
{
get => GitHubToken;
set => GitHubToken = value;
}
/// <summary>
/// Whether to use the logged-in user for authentication.
/// When true, the CLI server will attempt to use stored OAuth tokens or gh CLI auth.
/// When false, only explicit tokens (GitHubToken or environment variables) are used.
/// Default: true (but defaults to false when GitHubToken is provided).
/// </summary>
public bool? UseLoggedInUser { get; set; }
/// <summary>
/// Custom handler for listing available models.
/// When provided, <c>ListModelsAsync()</c> calls this handler instead of
/// querying the CLI server. Useful in BYOK mode to return models
/// available from your custom provider.
/// </summary>
public Func<CancellationToken, Task<List<ModelInfo>>>? OnListModels { get; set; }
/// <summary>
/// Custom session filesystem provider configuration.
/// When set, the client registers as the session filesystem provider on connect,
/// routing session-scoped file I/O through per-session handlers created via
/// <see cref="SessionConfig.CreateSessionFsHandler"/> or <see cref="ResumeSessionConfig.CreateSessionFsHandler"/>.
/// </summary>
public SessionFsConfig? SessionFs { get; set; }
/// <summary>
/// OpenTelemetry configuration for the CLI server.
/// When set to a non-<see langword="null"/> instance, the CLI server is started with OpenTelemetry instrumentation enabled.
/// </summary>
public TelemetryConfig? Telemetry { get; set; }
/// <summary>
/// Creates a shallow clone of this <see cref="CopilotClientOptions"/> instance.
/// </summary>
/// <remarks>
/// Mutable collection properties are copied into new collection instances so that modifications
/// to those collections on the clone do not affect the original.
/// Other reference-type properties (for example delegates and the logger) are not
/// deep-cloned; the original and the clone will share those objects.
/// </remarks>
public virtual CopilotClientOptions Clone()
{
return new(this);
}
}
/// <summary>
/// OpenTelemetry configuration for the Copilot CLI server.
/// </summary>
public sealed class TelemetryConfig
{
/// <summary>
/// OTLP exporter endpoint URL.
/// </summary>
/// <remarks>
/// Maps to the <c>OTEL_EXPORTER_OTLP_ENDPOINT</c> environment variable.
/// </remarks>
public string? OtlpEndpoint { get; set; }
/// <summary>
/// File path for the file exporter.
/// </summary>
/// <remarks>
/// Maps to the <c>COPILOT_OTEL_FILE_EXPORTER_PATH</c> environment variable.
/// </remarks>
public string? FilePath { get; set; }
/// <summary>
/// Exporter type (<c>"otlp-http"</c> or <c>"file"</c>).
/// </summary>
/// <remarks>
/// Maps to the <c>COPILOT_OTEL_EXPORTER_TYPE</c> environment variable.
/// </remarks>
public string? ExporterType { get; set; }
/// <summary>
/// Source name for telemetry spans.
/// </summary>
/// <remarks>
/// Maps to the <c>COPILOT_OTEL_SOURCE_NAME</c> environment variable.
/// </remarks>
public string? SourceName { get; set; }
/// <summary>
/// Whether to capture message content as part of telemetry.
/// </summary>
/// <remarks>
/// Maps to the <c>OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT</c> environment variable.
/// </remarks>
public bool? CaptureContent { get; set; }
}
/// <summary>
/// Configuration for a custom session filesystem provider.
/// </summary>
public sealed class SessionFsConfig
{
/// <summary>
/// Initial working directory for sessions (user's project directory).
/// </summary>
public required string InitialCwd { get; init; }
/// <summary>
/// Path within each session's SessionFs where the runtime stores
/// session-scoped files (events, workspace, checkpoints, and temp files).
/// </summary>
public required string SessionStatePath { get; init; }
/// <summary>
/// Path conventions used by this filesystem provider.
/// </summary>
public required SessionFsSetProviderRequestConventions Conventions { get; init; }
}
/// <summary>
/// Represents a binary result returned by a tool invocation.
/// </summary>
public class ToolBinaryResult
{
/// <summary>
/// Base64-encoded binary data.
/// </summary>
[JsonPropertyName("data")]
public string Data { get; set; } = string.Empty;
/// <summary>
/// MIME type of the binary data (e.g., "image/png").
/// </summary>
[JsonPropertyName("mimeType")]
public string MimeType { get; set; } = string.Empty;
/// <summary>
/// Type identifier for the binary result.
/// </summary>
[JsonPropertyName("type")]
public string Type { get; set; } = string.Empty;
/// <summary>
/// Optional human-readable description of the binary result.
/// </summary>
[JsonPropertyName("description")]
public string? Description { get; set; }
}
/// <summary>
/// Represents the structured result of a tool execution.
/// </summary>
public class ToolResultObject
{
/// <summary>
/// Text result to be consumed by the language model.
/// </summary>
[JsonPropertyName("textResultForLlm")]
public string TextResultForLlm { get; set; } = string.Empty;
/// <summary>
/// Binary results (e.g., images) to be consumed by the language model.
/// </summary>
[JsonPropertyName("binaryResultsForLlm")]
public List<ToolBinaryResult>? BinaryResultsForLlm { get; set; }
/// <summary>
/// Result type indicator.
/// <list type="bullet">
/// <item><description><c>"success"</c> — the tool executed successfully.</description></item>
/// <item><description><c>"failure"</c> — the tool encountered an error.</description></item>
/// <item><description><c>"rejected"</c> — the tool invocation was rejected.</description></item>
/// <item><description><c>"denied"</c> — the tool invocation was denied by a permission check.</description></item>
/// </list>
/// </summary>
[JsonPropertyName("resultType")]
public string ResultType { get; set; } = "success";
/// <summary>
/// Error message if the tool execution failed.
/// </summary>
[JsonPropertyName("error")]
public string? Error { get; set; }
/// <summary>
/// Log entry for the session history.
/// </summary>
[JsonPropertyName("sessionLog")]
public string? SessionLog { get; set; }
/// <summary>
/// Custom telemetry data associated with the tool execution.
/// </summary>
[JsonPropertyName("toolTelemetry")]
public Dictionary<string, object>? ToolTelemetry { get; set; }
/// <summary>
/// Converts the result of an <see cref="AIFunction"/> invocation into a
/// <see cref="ToolResultObject"/>. Handles <see cref="ToolResultAIContent"/>,
/// <see cref="AIContent"/>, and falls back to JSON serialization.
/// </summary>
internal static ToolResultObject ConvertFromInvocationResult(object? result, JsonSerializerOptions jsonOptions)
{
if (result is ToolResultAIContent trac)
{
return trac.Result;
}
if (TryConvertFromAIContent(result) is { } aiConverted)
{
return aiConverted;
}
return new ToolResultObject
{
ResultType = "success",
TextResultForLlm = result is JsonElement { ValueKind: JsonValueKind.String } je
? je.GetString()!
: JsonSerializer.Serialize(result, jsonOptions.GetTypeInfo(typeof(object))),
};
}
/// <summary>
/// Attempts to convert a result from an <see cref="AIFunction"/> invocation into a
/// <see cref="ToolResultObject"/>. Handles <see cref="TextContent"/>,
/// <see cref="DataContent"/>, and collections of <see cref="AIContent"/>.
/// Returns <see langword="null"/> if the value is not a recognized <see cref="AIContent"/> type.
/// </summary>
internal static ToolResultObject? TryConvertFromAIContent(object? result)
{
if (result is AIContent singleContent)
{
return ConvertAIContents([singleContent]);
}
if (result is IEnumerable<AIContent> contentList)
{
return ConvertAIContents(contentList);
}
return null;
}
private static ToolResultObject ConvertAIContents(IEnumerable<AIContent> contents)
{
List<string>? textParts = null;
List<ToolBinaryResult>? binaryResults = null;
foreach (var content in contents)
{
switch (content)
{
case TextContent textContent:
if (textContent.Text is { } text)
{
(textParts ??= []).Add(text);
}
break;
case DataContent dataContent:
(binaryResults ??= []).Add(new ToolBinaryResult
{
Data = dataContent.Base64Data.ToString(),
MimeType = dataContent.MediaType ?? "application/octet-stream",
Type = dataContent.HasTopLevelMediaType("image") ? "image" : "resource",
});
break;
default:
(textParts ??= []).Add(SerializeAIContent(content));
break;
}
}
return new ToolResultObject
{
TextResultForLlm = textParts is not null ? string.Join("\n", textParts) : "",
ResultType = "success",
BinaryResultsForLlm = binaryResults,
};
}
private static string SerializeAIContent(AIContent content) =>
JsonSerializer.Serialize(content, AIJsonUtilities.DefaultOptions.GetTypeInfo(typeof(AIContent)));
}
/// <summary>
/// Contains context for a tool invocation callback.
/// </summary>
public class ToolInvocation
{
/// <summary>
/// Identifier of the session that triggered the tool call.
/// </summary>
public string SessionId { get; set; } = string.Empty;
/// <summary>
/// Unique identifier of this specific tool call.
/// </summary>
public string ToolCallId { get; set; } = string.Empty;
/// <summary>
/// Name of the tool being invoked.
/// </summary>
public string ToolName { get; set; } = string.Empty;
/// <summary>
/// Arguments passed to the tool by the language model.
/// </summary>
public object? Arguments { get; set; }
}
/// <summary>
/// Delegate for handling tool invocations and returning a result.
/// </summary>
public delegate Task<object?> ToolHandler(ToolInvocation invocation);
/// <summary>Describes the kind of a permission request result.</summary>
[JsonConverter(typeof(PermissionRequestResultKind.Converter))]
[DebuggerDisplay("{Value,nq}")]
public readonly struct PermissionRequestResultKind : IEquatable<PermissionRequestResultKind>
{
/// <summary>Gets the kind indicating the permission was approved.</summary>
public static PermissionRequestResultKind Approved { get; } = new("approved");
/// <summary>Gets the kind indicating the permission was denied by rules.</summary>
public static PermissionRequestResultKind DeniedByRules { get; } = new("denied-by-rules");
/// <summary>Gets the kind indicating the permission was denied because no approval rule was found and the user could not be prompted.</summary>
public static PermissionRequestResultKind DeniedCouldNotRequestFromUser { get; } = new("denied-no-approval-rule-and-could-not-request-from-user");
/// <summary>Gets the kind indicating the permission was denied interactively by the user.</summary>
public static PermissionRequestResultKind DeniedInteractivelyByUser { get; } = new("denied-interactively-by-user");
/// <summary>Gets the kind indicating the permission was denied interactively by the user.</summary>
public static PermissionRequestResultKind NoResult { get; } = new("no-result");
/// <summary>Gets the underlying string value of this <see cref="PermissionRequestResultKind"/>.</summary>
public string Value => _value ?? string.Empty;
private readonly string? _value;
/// <summary>Initializes a new instance of the <see cref="PermissionRequestResultKind"/> struct.</summary>
/// <param name="value">The string value for this kind.</param>
[JsonConstructor]
public PermissionRequestResultKind(string value) => _value = value;
/// <inheritdoc/>
public static bool operator ==(PermissionRequestResultKind left, PermissionRequestResultKind right) => left.Equals(right);
/// <inheritdoc/>
public static bool operator !=(PermissionRequestResultKind left, PermissionRequestResultKind right) => !left.Equals(right);
/// <inheritdoc/>
public override bool Equals([NotNullWhen(true)] object? obj) => obj is PermissionRequestResultKind other && Equals(other);
/// <inheritdoc/>
public bool Equals(PermissionRequestResultKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase);
/// <inheritdoc/>
public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value);
/// <inheritdoc/>
public override string ToString() => Value;
/// <summary>Provides a <see cref="JsonConverter{PermissionRequestResultKind}"/> for serializing <see cref="PermissionRequestResultKind"/> instances.</summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed class Converter : JsonConverter<PermissionRequestResultKind>
{
/// <inheritdoc/>
public override PermissionRequestResultKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.String)
{
throw new JsonException("Expected string for PermissionRequestResultKind.");
}
var value = reader.GetString();
if (value is null)
{
throw new JsonException("PermissionRequestResultKind value cannot be null.");
}
return new PermissionRequestResultKind(value);
}
/// <inheritdoc/>
public override void Write(Utf8JsonWriter writer, PermissionRequestResultKind value, JsonSerializerOptions options) =>
writer.WriteStringValue(value.Value);
}
}
/// <summary>
/// Result of a permission request evaluation.
/// </summary>
public class PermissionRequestResult
{
/// <summary>
/// Permission decision kind.
/// <list type="bullet">
/// <item><description><c>"approved"</c> — the operation is allowed.</description></item>
/// <item><description><c>"denied-by-rules"</c> — denied by configured permission rules.</description></item>
/// <item><description><c>"denied-interactively-by-user"</c> — the user explicitly denied the request.</description></item>
/// <item><description><c>"denied-no-approval-rule-and-could-not-request-from-user"</c> — no rule matched and user approval was unavailable.</description></item>
/// <item><description><c>"no-result"</c> — leave the pending permission request unanswered.</description></item>
/// </list>
/// </summary>
[JsonPropertyName("kind")]
public PermissionRequestResultKind Kind { get; set; }
/// <summary>
/// Permission rules to apply for the decision.
/// </summary>
[JsonPropertyName("rules")]
public List<object>? Rules { get; set; }
}
/// <summary>
/// Contains context for a permission request callback.
/// </summary>
public class PermissionInvocation
{
/// <summary>
/// Identifier of the session that triggered the permission request.
/// </summary>
public string SessionId { get; set; } = string.Empty;
}
/// <summary>
/// Delegate for handling permission requests and returning a decision.
/// </summary>
public delegate Task<PermissionRequestResult> PermissionRequestHandler(PermissionRequest request, PermissionInvocation invocation);
// ============================================================================
// User Input Handler Types
// ============================================================================
/// <summary>
/// Request for user input from the agent.
/// </summary>
public class UserInputRequest
{
/// <summary>
/// The question to ask the user.
/// </summary>
[JsonPropertyName("question")]
public string Question { get; set; } = string.Empty;
/// <summary>
/// Optional choices for multiple choice questions.
/// </summary>
[JsonPropertyName("choices")]
public List<string>? Choices { get; set; }
/// <summary>
/// Whether freeform text input is allowed.
/// </summary>
[JsonPropertyName("allowFreeform")]
public bool? AllowFreeform { get; set; }
}
/// <summary>
/// Response to a user input request.
/// </summary>
public class UserInputResponse
{
/// <summary>
/// The user's answer.
/// </summary>
[JsonPropertyName("answer")]
public string Answer { get; set; } = string.Empty;
/// <summary>
/// Whether the answer was freeform (not from the provided choices).
/// </summary>
[JsonPropertyName("wasFreeform")]
public bool WasFreeform { get; set; }
}
/// <summary>
/// Context for a user input request invocation.
/// </summary>
public class UserInputInvocation
{
/// <summary>
/// Identifier of the session that triggered the user input request.
/// </summary>
public string SessionId { get; set; } = string.Empty;
}
/// <summary>
/// Handler for user input requests from the agent.
/// </summary>
public delegate Task<UserInputResponse> UserInputHandler(UserInputRequest request, UserInputInvocation invocation);
// ============================================================================
// Command Handler Types
// ============================================================================
/// <summary>
/// Defines a slash-command that users can invoke from the CLI TUI.
/// </summary>
public class CommandDefinition
{
/// <summary>
/// Command name (without leading <c>/</c>). For example, <c>"deploy"</c>.
/// </summary>
public required string Name { get; set; }
/// <summary>
/// Human-readable description shown in the command completion UI.
/// </summary>
public string? Description { get; set; }
/// <summary>
/// Handler invoked when the command is executed.
/// </summary>
public required CommandHandler Handler { get; set; }
}
/// <summary>
/// Context passed to a <see cref="CommandHandler"/> when a command is executed.
/// </summary>
public class CommandContext
{
/// <summary>
/// Session ID where the command was invoked.
/// </summary>
public string SessionId { get; set; } = string.Empty;
/// <summary>
/// The full command text (e.g., <c>/deploy production</c>).
/// </summary>
public string Command { get; set; } = string.Empty;
/// <summary>
/// Command name without leading <c>/</c>.
/// </summary>
public string CommandName { get; set; } = string.Empty;
/// <summary>
/// Raw argument string after the command name.
/// </summary>
public string Args { get; set; } = string.Empty;
}
/// <summary>
/// Delegate for handling slash-command executions.
/// </summary>
public delegate Task CommandHandler(CommandContext context);
// ============================================================================
// Elicitation Types (UI — client → server)
// ============================================================================
/// <summary>
/// JSON Schema describing the form fields to present for an elicitation dialog.
/// </summary>
public class ElicitationSchema
{
/// <summary>
/// Schema type indicator (always <c>"object"</c>).
/// </summary>
[JsonPropertyName("type")]
public string Type { get; set; } = "object";
/// <summary>
/// Form field definitions, keyed by field name.
/// </summary>
[JsonPropertyName("properties")]
public Dictionary<string, object> Properties { get; set; } = [];
/// <summary>
/// List of required field names.
/// </summary>
[JsonPropertyName("required")]
public List<string>? Required { get; set; }
}
/// <summary>
/// Parameters for an elicitation request sent from the SDK to the server.
/// </summary>
public class ElicitationParams
{
/// <summary>
/// Message describing what information is needed from the user.
/// </summary>
public required string Message { get; set; }
/// <summary>
/// JSON Schema describing the form fields to present.
/// </summary>
public required ElicitationSchema RequestedSchema { get; set; }
}
/// <summary>
/// Result returned from an elicitation dialog.
/// </summary>
public class ElicitationResult
{
/// <summary>
/// User action: <c>"accept"</c> (submitted), <c>"decline"</c> (rejected), or <c>"cancel"</c> (dismissed).
/// </summary>
public SessionUiElicitationResultAction Action { get; set; }
/// <summary>
/// Form values submitted by the user (present when <see cref="Action"/> is <c>Accept</c>).
/// </summary>
public Dictionary<string, object>? Content { get; set; }
}
/// <summary>
/// Options for the <see cref="ISessionUiApi.InputAsync"/> convenience method.
/// </summary>
public class InputOptions
{
/// <summary>Title label for the input field.</summary>
public string? Title { get; set; }
/// <summary>Descriptive text shown below the field.</summary>
public string? Description { get; set; }
/// <summary>Minimum character length.</summary>
public int? MinLength { get; set; }
/// <summary>Maximum character length.</summary>
public int? MaxLength { get; set; }
/// <summary>Semantic format hint (e.g., <c>"email"</c>, <c>"uri"</c>, <c>"date"</c>, <c>"date-time"</c>).</summary>
public string? Format { get; set; }
/// <summary>Default value pre-populated in the field.</summary>
public string? Default { get; set; }
}
/// <summary>
/// Provides UI methods for eliciting information from the user during a session.
/// </summary>
public interface ISessionUiApi
{
/// <summary>
/// Shows a generic elicitation dialog with a custom schema.
/// </summary>
/// <param name="elicitationParams">The elicitation parameters including message and schema.</param>
/// <param name="cancellationToken">Optional cancellation token.</param>
/// <returns>The <see cref="ElicitationResult"/> with the user's response.</returns>
/// <exception cref="InvalidOperationException">Thrown if the host does not support elicitation.</exception>
Task<ElicitationResult> ElicitationAsync(ElicitationParams elicitationParams, CancellationToken cancellationToken = default);
/// <summary>
/// Shows a confirmation dialog and returns the user's boolean answer.
/// Returns <c>false</c> if the user declines or cancels.
/// </summary>
/// <param name="message">The message to display.</param>
/// <param name="cancellationToken">Optional cancellation token.</param>
/// <returns><c>true</c> if the user confirmed; otherwise <c>false</c>.</returns>
/// <exception cref="InvalidOperationException">Thrown if the host does not support elicitation.</exception>
Task<bool> ConfirmAsync(string message, CancellationToken cancellationToken = default);
/// <summary>
/// Shows a selection dialog with the given options.
/// Returns the selected value, or <c>null</c> if the user declines/cancels.
/// </summary>
/// <param name="message">The message to display.</param>
/// <param name="options">The options to present.</param>
/// <param name="cancellationToken">Optional cancellation token.</param>
/// <returns>The selected string, or <c>null</c> if the user declined/cancelled.</returns>
/// <exception cref="InvalidOperationException">Thrown if the host does not support elicitation.</exception>
Task<string?> SelectAsync(string message, string[] options, CancellationToken cancellationToken = default);
/// <summary>
/// Shows a text input dialog.
/// Returns the entered text, or <c>null</c> if the user declines/cancels.
/// </summary>
/// <param name="message">The message to display.</param>
/// <param name="options">Optional input field options.</param>
/// <param name="cancellationToken">Optional cancellation token.</param>
/// <returns>The entered string, or <c>null</c> if the user declined/cancelled.</returns>
/// <exception cref="InvalidOperationException">Thrown if the host does not support elicitation.</exception>
Task<string?> InputAsync(string message, InputOptions? options = null, CancellationToken cancellationToken = default);
}
// ============================================================================
// Elicitation Types (server → client callback)
// ============================================================================
/// <summary>
/// Context for an elicitation handler invocation, combining the request data
/// with session context. Mirrors the single-argument pattern of <see cref="CommandContext"/>.
/// </summary>
public class ElicitationContext
{
/// <summary>Identifier of the session that triggered the elicitation request.</summary>
public string SessionId { get; set; } = string.Empty;
/// <summary>Message describing what information is needed from the user.</summary>
public string Message { get; set; } = string.Empty;
/// <summary>JSON Schema describing the form fields to present.</summary>
public ElicitationSchema? RequestedSchema { get; set; }
/// <summary>Elicitation mode: <c>"form"</c> for structured input, <c>"url"</c> for browser redirect.</summary>
public ElicitationRequestedDataMode? Mode { get; set; }
/// <summary>The source that initiated the request (e.g., MCP server name).</summary>
public string? ElicitationSource { get; set; }
/// <summary>URL to open in the user's browser (url mode only).</summary>
public string? Url { get; set; }
}
/// <summary>
/// Delegate for handling elicitation requests from the server.
/// </summary>
public delegate Task<ElicitationResult> ElicitationHandler(ElicitationContext context);
// ============================================================================
// Session Capabilities
// ============================================================================
/// <summary>
/// Represents the capabilities reported by the host for a session.
/// </summary>
public class SessionCapabilities
{
/// <summary>
/// UI-related capabilities.
/// </summary>
public SessionUiCapabilities? Ui { get; set; }
}
/// <summary>
/// UI-specific capability flags for a session.
/// </summary>
public class SessionUiCapabilities
{
/// <summary>
/// Whether the host supports interactive elicitation dialogs.
/// </summary>
public bool? Elicitation { get; set; }
}
// ============================================================================
// Hook Handler Types
// ============================================================================
/// <summary>
/// Context for a hook invocation.
/// </summary>
public class HookInvocation
{
/// <summary>
/// Identifier of the session that triggered the hook.
/// </summary>
public string SessionId { get; set; } = string.Empty;
}
/// <summary>
/// Input for a pre-tool-use hook.
/// </summary>
public class PreToolUseHookInput
{
/// <summary>
/// Unix timestamp in milliseconds when the tool use was initiated.
/// </summary>
[JsonPropertyName("timestamp")]
public long Timestamp { get; set; }
/// <summary>
/// Current working directory of the session.
/// </summary>
[JsonPropertyName("cwd")]
public string Cwd { get; set; } = string.Empty;
/// <summary>
/// Name of the tool about to be executed.
/// </summary>
[JsonPropertyName("toolName")]
public string ToolName { get; set; } = string.Empty;
/// <summary>
/// Arguments that will be passed to the tool.
/// </summary>
[JsonPropertyName("toolArgs")]
public object? ToolArgs { get; set; }
}
/// <summary>
/// Output for a pre-tool-use hook.
/// </summary>
public class PreToolUseHookOutput
{
/// <summary>
/// Permission decision for the pending tool call.
/// <list type="bullet">
/// <item><description><c>"allow"</c> — permit the tool to execute.</description></item>
/// <item><description><c>"deny"</c> — block the tool from executing.</description></item>
/// <item><description><c>"ask"</c> — fall through to the normal permission prompt.</description></item>
/// </list>
/// </summary>
[JsonPropertyName("permissionDecision")]
public string? PermissionDecision { get; set; }
/// <summary>
/// Human-readable reason for the permission decision.
/// </summary>
[JsonPropertyName("permissionDecisionReason")]
public string? PermissionDecisionReason { get; set; }
/// <summary>
/// Modified arguments to pass to the tool instead of the original ones.
/// </summary>
[JsonPropertyName("modifiedArgs")]
public object? ModifiedArgs { get; set; }
/// <summary>
/// Additional context to inject into the conversation for the language model.
/// </summary>
[JsonPropertyName("additionalContext")]
public string? AdditionalContext { get; set; }
/// <summary>
/// Whether to suppress the tool's output from the conversation.
/// </summary>
[JsonPropertyName("suppressOutput")]
public bool? SuppressOutput { get; set; }
}
/// <summary>
/// Delegate invoked before a tool is executed, allowing modification or denial of the call.
/// </summary>
public delegate Task<PreToolUseHookOutput?> PreToolUseHandler(PreToolUseHookInput input, HookInvocation invocation);
/// <summary>
/// Input for a post-tool-use hook.
/// </summary>
public class PostToolUseHookInput
{
/// <summary>
/// Unix timestamp in milliseconds when the tool execution completed.
/// </summary>
[JsonPropertyName("timestamp")]
public long Timestamp { get; set; }
/// <summary>
/// Current working directory of the session.
/// </summary>
[JsonPropertyName("cwd")]
public string Cwd { get; set; } = string.Empty;
/// <summary>
/// Name of the tool that was executed.
/// </summary>
[JsonPropertyName("toolName")]
public string ToolName { get; set; } = string.Empty;
/// <summary>
/// Arguments that were passed to the tool.
/// </summary>
[JsonPropertyName("toolArgs")]
public object? ToolArgs { get; set; }
/// <summary>
/// Result returned by the tool execution.
/// </summary>
[JsonPropertyName("toolResult")]
public object? ToolResult { get; set; }
}
/// <summary>
/// Output for a post-tool-use hook.
/// </summary>