| 1 | using System.Text.Json; |
| 2 | using System.Text.Json.Serialization; |
| 3 | |
| 4 | namespace AgentClientProtocol; |
| 5 | |
| 6 | [JsonConverter(typeof(ToolCallContentJsonConverter))] |
| 7 | public abstract record ToolCallContent; |
| 8 | |
| 9 | public record ContentToolCallContent : ToolCallContent |
| 10 | { |
| 11 | [JsonPropertyName("content")] |
| 12 | public required ContentBlock Content { get; init; } |
| 13 | } |
| 14 | |
| 15 | public record DiffToolCallContent : ToolCallContent |
| 16 | { |
| 17 | [JsonPropertyName("path")] |
| 18 | public required string Path { get; init; } |
| 19 | |
| 20 | [JsonPropertyName("newText")] |
| 21 | public required string NewText { get; init; } |
| 22 | |
| 23 | [JsonPropertyName("oldText")] |
| 24 | public string? OldText { get; init; } |
| 25 | } |
| 26 | |
| 27 | public record TerminalToolCallContent : ToolCallContent |
| 28 | { |
| 29 | [JsonPropertyName("terminalId")] |
| 30 | public required string TerminalId { get; init; } |
| 31 | } |
| 32 | |
| 33 | public class ToolCallContentJsonConverter : JsonConverter<ToolCallContent> |
| 34 | { |
| 35 | public override ToolCallContent? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| 36 | { |
| 37 | using var doc = JsonDocument.ParseValue(ref reader); |
| 38 | var root = doc.RootElement; |
| 39 | |
| 40 | if (root.ValueKind != JsonValueKind.Object) |
| 41 | { |
| 42 | throw new JsonException("ToolCallContent must be a JSON object"); |
| 43 | } |
| 44 | |
| 45 | if (root.TryGetProperty("content", out _)) |
| 46 | { |
| 47 | return root.Deserialize<ContentToolCallContent>(options); |
| 48 | } |
| 49 | else if (root.TryGetProperty("terminalId", out _)) |
| 50 | { |
| 51 | return root.Deserialize<TerminalToolCallContent>(options); |
| 52 | } |
| 53 | else if (root.TryGetProperty("path", out _) || root.TryGetProperty("newText", out _)) |
| 54 | { |
| 55 | return root.Deserialize<DiffToolCallContent>(options); |
| 56 | } |
| 57 | |
| 58 | throw new JsonException("Unknown ToolCallContent type - missing discriminator properties"); |
| 59 | } |
| 60 | |
| 61 | public override void Write(Utf8JsonWriter writer, ToolCallContent value, JsonSerializerOptions options) |
| 62 | { |
| 63 | JsonSerializer.Serialize(writer, value, value.GetType(), options); |
| 64 | } |
| 65 | } |
| 66 | |