| 1 | using System.Text.Json; |
| 2 | using System.Text.Json.Serialization; |
| 3 | |
| 4 | namespace AgentClientProtocol; |
| 5 | |
| 6 | [JsonConverter(typeof(RequestPermissionOutcomeJsonConverter))] |
| 7 | public abstract record RequestPermissionOutcome |
| 8 | { |
| 9 | [JsonPropertyName("outcome")] |
| 10 | public abstract string Outcome { get; } |
| 11 | } |
| 12 | |
| 13 | public record CancelledRequestPermissionOutcome : RequestPermissionOutcome |
| 14 | { |
| 15 | [JsonPropertyName("outcome")] |
| 16 | public override string Outcome => "cancelled"; |
| 17 | } |
| 18 | |
| 19 | public record SelectedRequestPermissionOutcome : RequestPermissionOutcome |
| 20 | { |
| 21 | [JsonPropertyName("outcome")] |
| 22 | public override string Outcome => "selected"; |
| 23 | |
| 24 | [JsonPropertyName("optionId")] |
| 25 | public required string OptionId { get; init; } |
| 26 | } |
| 27 | |
| 28 | public class RequestPermissionOutcomeJsonConverter : JsonConverter<RequestPermissionOutcome> |
| 29 | { |
| 30 | public override RequestPermissionOutcome? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| 31 | { |
| 32 | using var doc = JsonDocument.ParseValue(ref reader); |
| 33 | var root = doc.RootElement; |
| 34 | |
| 35 | if (root.ValueKind != JsonValueKind.Object) |
| 36 | { |
| 37 | throw new JsonException("RequestPermissionOutcome must be a JSON object"); |
| 38 | } |
| 39 | |
| 40 | if (root.TryGetProperty("optionId", out _)) |
| 41 | { |
| 42 | return root.Deserialize<SelectedRequestPermissionOutcome>(options); |
| 43 | } |
| 44 | else |
| 45 | { |
| 46 | return root.Deserialize<CancelledRequestPermissionOutcome>(options); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | public override void Write(Utf8JsonWriter writer, RequestPermissionOutcome value, JsonSerializerOptions options) |
| 51 | { |
| 52 | JsonSerializer.Serialize(writer, value, value.GetType(), options); |
| 53 | } |
| 54 | } |