From 3f7771fdb894e33c6b3a963c3d310f6a42adbfc3 Mon Sep 17 00:00:00 2001 From: TeseySTD Date: Tue, 10 Nov 2026 13:03:38 +0200 Subject: [PATCH 01/26] feat(acp): add MandoCode.Acp project with ACP v1 protocol types Start the ACP client (issue #137) with the protocol layer only; no behavior change for the app yet. - New UI-free project src/MandoCode.Acp (net8.0;net10.0), referenced by MandoCode and shipped inside the tool package. - Hand-written DTOs for the stable ACP v1 methods, modelled on the official schema pinned to v1.16.0 and vendored under tests/MandoCode.Tests/Acp/schema. - System.Text.Json source generation (AcpJsonContext), no reflection. - Custom union converters instead of [JsonPolymorphic]: net8 requires the discriminator to be the first property and throws on unknown values. Unknown or malformed session/update, content-block and tool-call-content variants degrade to Unknown* values. - String "enums" with constant classes so new values never break parsing. - DTO properties use set rather than init: on net8 the source generator routes init-only types through a parameterized-constructor path where fields missing from the JSON overwrite initializers with null. - Tests: wire shape, unknown fields/variants, discriminator order, and a schema-drift test that checks property names, required fields and enum values against the vendored schema. --- MandoCode.sln | 15 + src/MandoCode.Acp/MandoCode.Acp.csproj | 19 + src/MandoCode.Acp/Protocol/AcpConstants.cs | 105 + src/MandoCode.Acp/Protocol/AcpJsonContext.cs | 66 + src/MandoCode.Acp/Protocol/Content.cs | 83 + src/MandoCode.Acp/Protocol/Converters.cs | 222 + src/MandoCode.Acp/Protocol/Messages.cs | 262 + src/MandoCode.Acp/Protocol/Updates.cs | 130 + src/MandoCode.Acp/README.md | 25 + src/MandoCode/MandoCode.csproj | 5 + tests/MandoCode.Tests/Acp/AcpProtocolTests.cs | 458 ++ .../Acp/AcpSchemaDriftTests.cs | 210 + .../MandoCode.Tests/Acp/schema/schema.v1.json | 6241 +++++++++++++++++ tests/MandoCode.Tests/MandoCode.Tests.csproj | 6 + 14 files changed, 7847 insertions(+) create mode 100644 src/MandoCode.Acp/MandoCode.Acp.csproj create mode 100644 src/MandoCode.Acp/Protocol/AcpConstants.cs create mode 100644 src/MandoCode.Acp/Protocol/AcpJsonContext.cs create mode 100644 src/MandoCode.Acp/Protocol/Content.cs create mode 100644 src/MandoCode.Acp/Protocol/Converters.cs create mode 100644 src/MandoCode.Acp/Protocol/Messages.cs create mode 100644 src/MandoCode.Acp/Protocol/Updates.cs create mode 100644 src/MandoCode.Acp/README.md create mode 100644 tests/MandoCode.Tests/Acp/AcpProtocolTests.cs create mode 100644 tests/MandoCode.Tests/Acp/AcpSchemaDriftTests.cs create mode 100644 tests/MandoCode.Tests/Acp/schema/schema.v1.json diff --git a/MandoCode.sln b/MandoCode.sln index 76489c3..ec5085e 100644 --- a/MandoCode.sln +++ b/MandoCode.sln @@ -11,6 +11,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05 EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MandoCode.Tests", "tests\MandoCode.Tests\MandoCode.Tests.csproj", "{D407041F-0C3B-4215-9F92-38C01435E015}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MandoCode.Acp", "src\MandoCode.Acp\MandoCode.Acp.csproj", "{4AD6649A-5B01-4BE5-A335-534B80F80C5C}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -45,6 +47,18 @@ Global {D407041F-0C3B-4215-9F92-38C01435E015}.Release|x64.Build.0 = Release|Any CPU {D407041F-0C3B-4215-9F92-38C01435E015}.Release|x86.ActiveCfg = Release|Any CPU {D407041F-0C3B-4215-9F92-38C01435E015}.Release|x86.Build.0 = Release|Any CPU + {4AD6649A-5B01-4BE5-A335-534B80F80C5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4AD6649A-5B01-4BE5-A335-534B80F80C5C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4AD6649A-5B01-4BE5-A335-534B80F80C5C}.Debug|x64.ActiveCfg = Debug|Any CPU + {4AD6649A-5B01-4BE5-A335-534B80F80C5C}.Debug|x64.Build.0 = Debug|Any CPU + {4AD6649A-5B01-4BE5-A335-534B80F80C5C}.Debug|x86.ActiveCfg = Debug|Any CPU + {4AD6649A-5B01-4BE5-A335-534B80F80C5C}.Debug|x86.Build.0 = Debug|Any CPU + {4AD6649A-5B01-4BE5-A335-534B80F80C5C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4AD6649A-5B01-4BE5-A335-534B80F80C5C}.Release|Any CPU.Build.0 = Release|Any CPU + {4AD6649A-5B01-4BE5-A335-534B80F80C5C}.Release|x64.ActiveCfg = Release|Any CPU + {4AD6649A-5B01-4BE5-A335-534B80F80C5C}.Release|x64.Build.0 = Release|Any CPU + {4AD6649A-5B01-4BE5-A335-534B80F80C5C}.Release|x86.ActiveCfg = Release|Any CPU + {4AD6649A-5B01-4BE5-A335-534B80F80C5C}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -52,6 +66,7 @@ Global GlobalSection(NestedProjects) = preSolution {3C5A3128-B243-5A70-788F-6B3C2B163656} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {D407041F-0C3B-4215-9F92-38C01435E015} = {0AB3BF05-4346-4AA6-1389-037BE0695223} + {4AD6649A-5B01-4BE5-A335-534B80F80C5C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {B33BAE4E-D6AD-429A-971D-8A9E6D5A4F16} diff --git a/src/MandoCode.Acp/MandoCode.Acp.csproj b/src/MandoCode.Acp/MandoCode.Acp.csproj new file mode 100644 index 0000000..841e62d --- /dev/null +++ b/src/MandoCode.Acp/MandoCode.Acp.csproj @@ -0,0 +1,19 @@ + + + + net10.0;net8.0 + enable + enable + true + MandoCode.Acp + false + + true + + + + + + + diff --git a/src/MandoCode.Acp/Protocol/AcpConstants.cs b/src/MandoCode.Acp/Protocol/AcpConstants.cs new file mode 100644 index 0000000..4614201 --- /dev/null +++ b/src/MandoCode.Acp/Protocol/AcpConstants.cs @@ -0,0 +1,105 @@ +namespace MandoCode.Acp.Protocol; + +/// Protocol-wide constants. +public static class AcpProtocol +{ + /// The only protocol version this client speaks. + public const int Version = 1; + + /// Tag of the official schema the DTOs were written against. + public const string SchemaTag = "v1.16.0"; +} + +/// JSON-RPC method names used by ACP v1 (stable methods only). +public static class AcpMethods +{ + // Client -> agent + public const string Initialize = "initialize"; + public const string Authenticate = "authenticate"; + public const string SessionNew = "session/new"; + public const string SessionLoad = "session/load"; + public const string SessionPrompt = "session/prompt"; + public const string SessionCancel = "session/cancel"; + public const string SessionSetMode = "session/set_mode"; + + // Agent -> client + public const string SessionUpdate = "session/update"; + public const string SessionRequestPermission = "session/request_permission"; + public const string FsReadTextFile = "fs/read_text_file"; + public const string FsWriteTextFile = "fs/write_text_file"; +} + +/// JSON-RPC and ACP error codes. +public static class AcpErrorCodes +{ + public const int ParseError = -32700; + public const int InvalidRequest = -32600; + public const int MethodNotFound = -32601; + public const int InvalidParams = -32602; + public const int InternalError = -32603; + public const int RequestCancelled = -32800; + public const int AuthRequired = -32000; + public const int ResourceNotFound = -32002; +} + +// The schema defines the following as string enums. They are modelled as plain strings with +// constant classes so that values added by newer agents never break deserialization. + +public static class StopReasons +{ + public const string EndTurn = "end_turn"; + public const string MaxTokens = "max_tokens"; + public const string MaxTurnRequests = "max_turn_requests"; + public const string Refusal = "refusal"; + public const string Cancelled = "cancelled"; +} + +public static class ToolKinds +{ + public const string Read = "read"; + public const string Edit = "edit"; + public const string Delete = "delete"; + public const string Move = "move"; + public const string Search = "search"; + public const string Execute = "execute"; + public const string Think = "think"; + public const string Fetch = "fetch"; + public const string SwitchMode = "switch_mode"; + public const string Other = "other"; +} + +public static class ToolCallStatuses +{ + public const string Pending = "pending"; + public const string InProgress = "in_progress"; + public const string Completed = "completed"; + public const string Failed = "failed"; +} + +public static class PermissionOptionKinds +{ + public const string AllowOnce = "allow_once"; + public const string AllowAlways = "allow_always"; + public const string RejectOnce = "reject_once"; + public const string RejectAlways = "reject_always"; +} + +public static class PlanEntryPriorities +{ + public const string High = "high"; + public const string Medium = "medium"; + public const string Low = "low"; +} + +public static class PlanEntryStatuses +{ + public const string Pending = "pending"; + public const string InProgress = "in_progress"; + public const string Completed = "completed"; +} + +public static class Roles +{ + public const string Assistant = "assistant"; + public const string User = "user"; +} diff --git a/src/MandoCode.Acp/Protocol/AcpJsonContext.cs b/src/MandoCode.Acp/Protocol/AcpJsonContext.cs new file mode 100644 index 0000000..0ac8945 --- /dev/null +++ b/src/MandoCode.Acp/Protocol/AcpJsonContext.cs @@ -0,0 +1,66 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MandoCode.Acp.Protocol; + +/// +/// Source-generated serialization metadata for every ACP DTO. All protocol (de)serialization goes +/// through this context, so nothing in the protocol layer depends on runtime reflection. +/// Unknown JSON members are ignored (the System.Text.Json default); null members are omitted on write. +/// +[JsonSourceGenerationOptions(DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] +// initialize / authenticate +[JsonSerializable(typeof(InitializeRequest))] +[JsonSerializable(typeof(InitializeResponse))] +[JsonSerializable(typeof(AuthenticateRequest))] +[JsonSerializable(typeof(AuthenticateResponse))] +// sessions +[JsonSerializable(typeof(NewSessionRequest))] +[JsonSerializable(typeof(NewSessionResponse))] +[JsonSerializable(typeof(LoadSessionRequest))] +[JsonSerializable(typeof(LoadSessionResponse))] +[JsonSerializable(typeof(SetSessionModeRequest))] +[JsonSerializable(typeof(SetSessionModeResponse))] +[JsonSerializable(typeof(PromptRequest))] +[JsonSerializable(typeof(PromptResponse))] +[JsonSerializable(typeof(CancelNotification))] +// agent -> client +[JsonSerializable(typeof(SessionNotification))] +[JsonSerializable(typeof(RequestPermissionRequest))] +[JsonSerializable(typeof(RequestPermissionResponse))] +[JsonSerializable(typeof(ReadTextFileRequest))] +[JsonSerializable(typeof(ReadTextFileResponse))] +[JsonSerializable(typeof(WriteTextFileRequest))] +[JsonSerializable(typeof(WriteTextFileResponse))] +// unions (the converters deserialize concrete variants through these) +[JsonSerializable(typeof(ContentBlock))] +[JsonSerializable(typeof(TextContent))] +[JsonSerializable(typeof(ImageContent))] +[JsonSerializable(typeof(AudioContent))] +[JsonSerializable(typeof(ResourceLink))] +[JsonSerializable(typeof(EmbeddedResource))] +[JsonSerializable(typeof(TextResourceContents))] +[JsonSerializable(typeof(BlobResourceContents))] +[JsonSerializable(typeof(SessionUpdate))] +[JsonSerializable(typeof(UserMessageChunk))] +[JsonSerializable(typeof(AgentMessageChunk))] +[JsonSerializable(typeof(AgentThoughtChunk))] +[JsonSerializable(typeof(ToolCall))] +[JsonSerializable(typeof(ToolCallUpdate))] +[JsonSerializable(typeof(Plan))] +[JsonSerializable(typeof(AvailableCommandsUpdate))] +[JsonSerializable(typeof(CurrentModeUpdate))] +[JsonSerializable(typeof(ToolCallContent))] +[JsonSerializable(typeof(ContentToolCallContent))] +[JsonSerializable(typeof(DiffToolCallContent))] +[JsonSerializable(typeof(TerminalToolCallContent))] +[JsonSerializable(typeof(RequestPermissionOutcome))] +[JsonSerializable(typeof(CancelledPermissionOutcome))] +[JsonSerializable(typeof(SelectedPermissionOutcome))] +[JsonSerializable(typeof(McpServer))] +[JsonSerializable(typeof(McpServerStdio))] +[JsonSerializable(typeof(McpServerHttp))] +[JsonSerializable(typeof(McpServerSse))] +public sealed partial class AcpJsonContext : JsonSerializerContext +{ +} diff --git a/src/MandoCode.Acp/Protocol/Content.cs b/src/MandoCode.Acp/Protocol/Content.cs new file mode 100644 index 0000000..5f9f6fb --- /dev/null +++ b/src/MandoCode.Acp/Protocol/Content.cs @@ -0,0 +1,83 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MandoCode.Acp.Protocol; + +public sealed record Annotations : AcpObject +{ + [JsonPropertyName("audience")] public IReadOnlyList? Audience { get; set; } + [JsonPropertyName("lastModified")] public string? LastModified { get; set; } + [JsonPropertyName("priority")] public double? Priority { get; set; } +} + +/// +/// A piece of prompt or message content, discriminated by type. Values with an +/// unrecognised type deserialize to . +/// +[JsonConverter(typeof(ContentBlockConverter))] +public abstract record ContentBlock : AcpObject; + +public sealed record TextContent : ContentBlock +{ + [JsonPropertyName("type")] public string Type => "text"; + [JsonPropertyName("text")] public string Text { get; set; } = ""; + [JsonPropertyName("annotations")] public Annotations? Annotations { get; set; } + + public TextContent() { } + public TextContent(string text) => Text = text; +} + +public sealed record ImageContent : ContentBlock +{ + [JsonPropertyName("type")] public string Type => "image"; + [JsonPropertyName("data")] public string Data { get; set; } = ""; + [JsonPropertyName("mimeType")] public string MimeType { get; set; } = ""; + [JsonPropertyName("uri")] public string? Uri { get; set; } + [JsonPropertyName("annotations")] public Annotations? Annotations { get; set; } +} + +public sealed record AudioContent : ContentBlock +{ + [JsonPropertyName("type")] public string Type => "audio"; + [JsonPropertyName("data")] public string Data { get; set; } = ""; + [JsonPropertyName("mimeType")] public string MimeType { get; set; } = ""; + [JsonPropertyName("annotations")] public Annotations? Annotations { get; set; } +} + +public sealed record ResourceLink : ContentBlock +{ + [JsonPropertyName("type")] public string Type => "resource_link"; + [JsonPropertyName("name")] public string Name { get; set; } = ""; + [JsonPropertyName("uri")] public string Uri { get; set; } = ""; + [JsonPropertyName("mimeType")] public string? MimeType { get; set; } + [JsonPropertyName("size")] public long? Size { get; set; } + [JsonPropertyName("annotations")] public Annotations? Annotations { get; set; } +} + +public sealed record EmbeddedResource : ContentBlock +{ + [JsonPropertyName("type")] public string Type => "resource"; + [JsonPropertyName("resource")] public EmbeddedResourceContents Resource { get; set; } = new TextResourceContents(); + [JsonPropertyName("annotations")] public Annotations? Annotations { get; set; } +} + +/// The payload of an : text or a base64 blob (told apart by which field is present). +[JsonConverter(typeof(EmbeddedResourceContentsConverter))] +public abstract record EmbeddedResourceContents : AcpObject; + +public sealed record TextResourceContents : EmbeddedResourceContents +{ + [JsonPropertyName("uri")] public string Uri { get; set; } = ""; + [JsonPropertyName("text")] public string Text { get; set; } = ""; + [JsonPropertyName("mimeType")] public string? MimeType { get; set; } +} + +public sealed record BlobResourceContents : EmbeddedResourceContents +{ + [JsonPropertyName("uri")] public string Uri { get; set; } = ""; + [JsonPropertyName("blob")] public string Blob { get; set; } = ""; + [JsonPropertyName("mimeType")] public string? MimeType { get; set; } +} + +/// A content block whose type this client does not know. The raw JSON is preserved. +public sealed record UnknownContentBlock(string? Kind, JsonElement Raw) : ContentBlock; diff --git a/src/MandoCode.Acp/Protocol/Converters.cs b/src/MandoCode.Acp/Protocol/Converters.cs new file mode 100644 index 0000000..e76c3d8 --- /dev/null +++ b/src/MandoCode.Acp/Protocol/Converters.cs @@ -0,0 +1,222 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MandoCode.Acp.Protocol; + +// Why hand-written converters instead of [JsonPolymorphic]: +// * on net8 System.Text.Json requires the discriminator to be the FIRST property of the object +// (AllowOutOfOrderMetadataProperties only arrived in net9), but JSON-RPC peers are free to +// order properties however they like; +// * an unknown discriminator value throws, while ACP requires clients to ignore variants they +// do not understand (new session/update kinds are added regularly). +// These converters find the discriminator in any position, deserialize the matching concrete +// type through the source-generated AcpJsonContext (no reflection), and degrade to an +// Unknown* value for unrecognised or malformed variants. + +/// Shared logic for unions discriminated by a string property. +internal abstract class DiscriminatedUnionConverter : JsonConverter where T : AcpObject +{ + protected abstract string DiscriminatorName { get; } + + /// Deserializes the variant for , or returns null when the kind is unknown. + protected abstract T? ReadKnown(string kind, JsonElement root); + + protected abstract T CreateUnknown(string? kind, JsonElement raw); + + public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + using var document = JsonDocument.ParseValue(ref reader); + var root = document.RootElement; + + string? kind = null; + if (root.ValueKind == JsonValueKind.Object + && root.TryGetProperty(DiscriminatorName, out var discriminator) + && discriminator.ValueKind == JsonValueKind.String) + { + kind = discriminator.GetString(); + } + + if (kind is null) + return CreateUnknown(null, root.Clone()); + + try + { + return ReadKnown(kind, root) ?? CreateUnknown(kind, root.Clone()); + } + catch (JsonException) + { + // A known variant with a malformed body must not take the whole stream down. + return CreateUnknown(kind, root.Clone()); + } + } +} + +internal sealed class ContentBlockConverter : DiscriminatedUnionConverter +{ + protected override string DiscriminatorName => "type"; + + protected override ContentBlock? ReadKnown(string kind, JsonElement root) => kind switch + { + "text" => root.Deserialize(AcpJsonContext.Default.TextContent), + "image" => root.Deserialize(AcpJsonContext.Default.ImageContent), + "audio" => root.Deserialize(AcpJsonContext.Default.AudioContent), + "resource_link" => root.Deserialize(AcpJsonContext.Default.ResourceLink), + "resource" => root.Deserialize(AcpJsonContext.Default.EmbeddedResource), + _ => null, + }; + + protected override ContentBlock CreateUnknown(string? kind, JsonElement raw) => new UnknownContentBlock(kind, raw); + + public override void Write(Utf8JsonWriter writer, ContentBlock value, JsonSerializerOptions options) + { + switch (value) + { + case TextContent v: JsonSerializer.Serialize(writer, v, AcpJsonContext.Default.TextContent); break; + case ImageContent v: JsonSerializer.Serialize(writer, v, AcpJsonContext.Default.ImageContent); break; + case AudioContent v: JsonSerializer.Serialize(writer, v, AcpJsonContext.Default.AudioContent); break; + case ResourceLink v: JsonSerializer.Serialize(writer, v, AcpJsonContext.Default.ResourceLink); break; + case EmbeddedResource v: JsonSerializer.Serialize(writer, v, AcpJsonContext.Default.EmbeddedResource); break; + case UnknownContentBlock v: v.Raw.WriteTo(writer); break; + default: throw new NotSupportedException($"Unsupported content block type {value.GetType().Name}."); + } + } +} + +/// Read-only: the client never sends session/update. +internal sealed class SessionUpdateConverter : DiscriminatedUnionConverter +{ + protected override string DiscriminatorName => "sessionUpdate"; + + protected override SessionUpdate? ReadKnown(string kind, JsonElement root) => kind switch + { + "user_message_chunk" => root.Deserialize(AcpJsonContext.Default.UserMessageChunk), + "agent_message_chunk" => root.Deserialize(AcpJsonContext.Default.AgentMessageChunk), + "agent_thought_chunk" => root.Deserialize(AcpJsonContext.Default.AgentThoughtChunk), + "tool_call" => root.Deserialize(AcpJsonContext.Default.ToolCall), + "tool_call_update" => root.Deserialize(AcpJsonContext.Default.ToolCallUpdate), + "plan" => root.Deserialize(AcpJsonContext.Default.Plan), + "available_commands_update" => root.Deserialize(AcpJsonContext.Default.AvailableCommandsUpdate), + "current_mode_update" => root.Deserialize(AcpJsonContext.Default.CurrentModeUpdate), + _ => null, + }; + + protected override SessionUpdate CreateUnknown(string? kind, JsonElement raw) => new UnknownSessionUpdate(kind, raw); + + public override void Write(Utf8JsonWriter writer, SessionUpdate value, JsonSerializerOptions options) => + throw new NotSupportedException("session/update is sent by agents only; this client never serializes it."); +} + +/// Read-only: tool-call content is produced by agents. +internal sealed class ToolCallContentConverter : DiscriminatedUnionConverter +{ + protected override string DiscriminatorName => "type"; + + protected override ToolCallContent? ReadKnown(string kind, JsonElement root) => kind switch + { + "content" => root.Deserialize(AcpJsonContext.Default.ContentToolCallContent), + "diff" => root.Deserialize(AcpJsonContext.Default.DiffToolCallContent), + "terminal" => root.Deserialize(AcpJsonContext.Default.TerminalToolCallContent), + _ => null, + }; + + protected override ToolCallContent CreateUnknown(string? kind, JsonElement raw) => new UnknownToolCallContent(kind, raw); + + public override void Write(Utf8JsonWriter writer, ToolCallContent value, JsonSerializerOptions options) => + throw new NotSupportedException("Tool-call content is sent by agents only; this client never serializes it."); +} + +/// +/// The text/blob distinction carries no discriminator: a payload with a blob field is a +/// , anything else is treated as . +/// +internal sealed class EmbeddedResourceContentsConverter : JsonConverter +{ + public override EmbeddedResourceContents? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + using var document = JsonDocument.ParseValue(ref reader); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) + throw new JsonException("Embedded resource contents must be an object."); + + return root.TryGetProperty("blob", out _) + ? root.Deserialize(AcpJsonContext.Default.BlobResourceContents) + : root.Deserialize(AcpJsonContext.Default.TextResourceContents); + } + + public override void Write(Utf8JsonWriter writer, EmbeddedResourceContents value, JsonSerializerOptions options) + { + switch (value) + { + case TextResourceContents v: JsonSerializer.Serialize(writer, v, AcpJsonContext.Default.TextResourceContents); break; + case BlobResourceContents v: JsonSerializer.Serialize(writer, v, AcpJsonContext.Default.BlobResourceContents); break; + default: throw new NotSupportedException($"Unsupported resource contents type {value.GetType().Name}."); + } + } +} + +/// Reads and writes the cancelled / selected permission outcome (discriminator outcome). +internal sealed class RequestPermissionOutcomeConverter : JsonConverter +{ + public override RequestPermissionOutcome? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + using var document = JsonDocument.ParseValue(ref reader); + var root = document.RootElement; + + string? kind = root.ValueKind == JsonValueKind.Object + && root.TryGetProperty("outcome", out var p) + && p.ValueKind == JsonValueKind.String + ? p.GetString() + : null; + + return kind switch + { + "cancelled" => root.Deserialize(AcpJsonContext.Default.CancelledPermissionOutcome), + "selected" => root.Deserialize(AcpJsonContext.Default.SelectedPermissionOutcome), + _ => throw new JsonException($"Unknown permission outcome '{kind}'."), + }; + } + + public override void Write(Utf8JsonWriter writer, RequestPermissionOutcome value, JsonSerializerOptions options) + { + switch (value) + { + case CancelledPermissionOutcome v: JsonSerializer.Serialize(writer, v, AcpJsonContext.Default.CancelledPermissionOutcome); break; + case SelectedPermissionOutcome v: JsonSerializer.Serialize(writer, v, AcpJsonContext.Default.SelectedPermissionOutcome); break; + default: throw new NotSupportedException($"Unsupported permission outcome {value.GetType().Name}."); + } + } +} + +/// http / sse servers carry a type; stdio servers do not. +internal sealed class McpServerConverter : JsonConverter +{ + public override McpServer? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + using var document = JsonDocument.ParseValue(ref reader); + var root = document.RootElement; + + string? kind = root.ValueKind == JsonValueKind.Object + && root.TryGetProperty("type", out var p) + && p.ValueKind == JsonValueKind.String + ? p.GetString() + : null; + + return kind switch + { + "http" => root.Deserialize(AcpJsonContext.Default.McpServerHttp), + "sse" => root.Deserialize(AcpJsonContext.Default.McpServerSse), + _ => root.Deserialize(AcpJsonContext.Default.McpServerStdio), + }; + } + + public override void Write(Utf8JsonWriter writer, McpServer value, JsonSerializerOptions options) + { + switch (value) + { + case McpServerStdio v: JsonSerializer.Serialize(writer, v, AcpJsonContext.Default.McpServerStdio); break; + case McpServerHttp v: JsonSerializer.Serialize(writer, v, AcpJsonContext.Default.McpServerHttp); break; + case McpServerSse v: JsonSerializer.Serialize(writer, v, AcpJsonContext.Default.McpServerSse); break; + default: throw new NotSupportedException($"Unsupported MCP server type {value.GetType().Name}."); + } + } +} diff --git a/src/MandoCode.Acp/Protocol/Messages.cs b/src/MandoCode.Acp/Protocol/Messages.cs new file mode 100644 index 0000000..6f5b283 --- /dev/null +++ b/src/MandoCode.Acp/Protocol/Messages.cs @@ -0,0 +1,262 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MandoCode.Acp.Protocol; + +/// +/// Base of every protocol object: carries the optional _meta extension bag. +/// Incoming DTOs are deliberately lenient (no required members): a missing field +/// becomes a default value instead of failing the whole message. +/// +/// Properties use { get; set; }, not init, on purpose: on net8 the System.Text.Json +/// source generator routes types with init-only properties through a "parameterized constructor" +/// path in which fields absent from the JSON overwrite property initializers with null +/// (see AcpProtocolTests.MissingFields_KeepInitializerDefaults). +/// +/// +public abstract record AcpObject +{ + [JsonPropertyName("_meta")] + public JsonElement? Meta { get; set; } +} + +// ───────────────────────── initialize ───────────────────────── + +public sealed record Implementation : AcpObject +{ + [JsonPropertyName("name")] public string Name { get; set; } = ""; + [JsonPropertyName("version")] public string Version { get; set; } = ""; +} + +public sealed record FileSystemCapabilities : AcpObject +{ + [JsonPropertyName("readTextFile")] public bool ReadTextFile { get; set; } + [JsonPropertyName("writeTextFile")] public bool WriteTextFile { get; set; } +} + +public sealed record ClientCapabilities : AcpObject +{ + [JsonPropertyName("fs")] public FileSystemCapabilities Fs { get; set; } = new(); + [JsonPropertyName("terminal")] public bool Terminal { get; set; } +} + +public sealed record InitializeRequest : AcpObject +{ + [JsonPropertyName("protocolVersion")] public int ProtocolVersion { get; set; } = AcpProtocol.Version; + [JsonPropertyName("clientCapabilities")] public ClientCapabilities? ClientCapabilities { get; set; } + [JsonPropertyName("clientInfo")] public Implementation? ClientInfo { get; set; } +} + +public sealed record PromptCapabilities : AcpObject +{ + [JsonPropertyName("image")] public bool Image { get; set; } + [JsonPropertyName("audio")] public bool Audio { get; set; } + [JsonPropertyName("embeddedContext")] public bool EmbeddedContext { get; set; } +} + +public sealed record McpCapabilities : AcpObject +{ + [JsonPropertyName("http")] public bool Http { get; set; } + [JsonPropertyName("sse")] public bool Sse { get; set; } +} + +public sealed record AgentCapabilities : AcpObject +{ + [JsonPropertyName("loadSession")] public bool LoadSession { get; set; } + [JsonPropertyName("promptCapabilities")] public PromptCapabilities PromptCapabilities { get; set; } = new(); + [JsonPropertyName("mcpCapabilities")] public McpCapabilities McpCapabilities { get; set; } = new(); +} + +/// +/// An authentication method advertised by the agent. The schema models this as a union +/// (terminal | agent); only the common fields are kept because this client never +/// calls authenticate - the agent's own login flow does the work. +/// +public sealed record AuthMethod : AcpObject +{ + [JsonPropertyName("id")] public string Id { get; set; } = ""; + [JsonPropertyName("name")] public string Name { get; set; } = ""; + [JsonPropertyName("description")] public string? Description { get; set; } + [JsonPropertyName("type")] public string? Type { get; set; } +} + +public sealed record InitializeResponse : AcpObject +{ + [JsonPropertyName("protocolVersion")] public int ProtocolVersion { get; set; } + [JsonPropertyName("agentCapabilities")] public AgentCapabilities AgentCapabilities { get; set; } = new(); + [JsonPropertyName("authMethods")] public IReadOnlyList AuthMethods { get; set; } = []; + [JsonPropertyName("agentInfo")] public Implementation? AgentInfo { get; set; } +} + +public sealed record AuthenticateRequest : AcpObject +{ + [JsonPropertyName("methodId")] public string MethodId { get; set; } = ""; +} + +public sealed record AuthenticateResponse : AcpObject; + +// ───────────────────────── sessions ───────────────────────── + +public sealed record EnvVariable : AcpObject +{ + [JsonPropertyName("name")] public string Name { get; set; } = ""; + [JsonPropertyName("value")] public string Value { get; set; } = ""; +} + +public sealed record HttpHeader : AcpObject +{ + [JsonPropertyName("name")] public string Name { get; set; } = ""; + [JsonPropertyName("value")] public string Value { get; set; } = ""; +} + +/// +/// An MCP server handed to the agent. This client always sends an empty list (MandoCode's own +/// MCP servers are not forwarded); the types exist so the request shape matches the schema. +/// +[JsonConverter(typeof(McpServerConverter))] +public abstract record McpServer : AcpObject; + +public sealed record McpServerStdio : McpServer +{ + [JsonPropertyName("name")] public string Name { get; set; } = ""; + [JsonPropertyName("command")] public string Command { get; set; } = ""; + [JsonPropertyName("args")] public IReadOnlyList Args { get; set; } = []; + [JsonPropertyName("env")] public IReadOnlyList Env { get; set; } = []; +} + +public sealed record McpServerHttp : McpServer +{ + [JsonPropertyName("type")] public string Type => "http"; + [JsonPropertyName("name")] public string Name { get; set; } = ""; + [JsonPropertyName("url")] public string Url { get; set; } = ""; + [JsonPropertyName("headers")] public IReadOnlyList Headers { get; set; } = []; +} + +public sealed record McpServerSse : McpServer +{ + [JsonPropertyName("type")] public string Type => "sse"; + [JsonPropertyName("name")] public string Name { get; set; } = ""; + [JsonPropertyName("url")] public string Url { get; set; } = ""; + [JsonPropertyName("headers")] public IReadOnlyList Headers { get; set; } = []; +} + +public sealed record NewSessionRequest : AcpObject +{ + [JsonPropertyName("cwd")] public string Cwd { get; set; } = ""; + [JsonPropertyName("mcpServers")] public IReadOnlyList McpServers { get; set; } = []; +} + +public sealed record SessionMode : AcpObject +{ + [JsonPropertyName("id")] public string Id { get; set; } = ""; + [JsonPropertyName("name")] public string Name { get; set; } = ""; +} + +public sealed record SessionModeState : AcpObject +{ + [JsonPropertyName("currentModeId")] public string CurrentModeId { get; set; } = ""; + [JsonPropertyName("availableModes")] public IReadOnlyList AvailableModes { get; set; } = []; +} + +public sealed record NewSessionResponse : AcpObject +{ + [JsonPropertyName("sessionId")] public string SessionId { get; set; } = ""; + [JsonPropertyName("modes")] public SessionModeState? Modes { get; set; } +} + +public sealed record LoadSessionRequest : AcpObject +{ + [JsonPropertyName("sessionId")] public string SessionId { get; set; } = ""; + [JsonPropertyName("cwd")] public string Cwd { get; set; } = ""; + [JsonPropertyName("mcpServers")] public IReadOnlyList McpServers { get; set; } = []; +} + +public sealed record LoadSessionResponse : AcpObject +{ + [JsonPropertyName("modes")] public SessionModeState? Modes { get; set; } +} + +public sealed record SetSessionModeRequest : AcpObject +{ + [JsonPropertyName("sessionId")] public string SessionId { get; set; } = ""; + [JsonPropertyName("modeId")] public string ModeId { get; set; } = ""; +} + +public sealed record SetSessionModeResponse : AcpObject; + +public sealed record PromptRequest : AcpObject +{ + [JsonPropertyName("sessionId")] public string SessionId { get; set; } = ""; + [JsonPropertyName("prompt")] public IReadOnlyList Prompt { get; set; } = []; +} + +public sealed record PromptResponse : AcpObject +{ + /// One of ; kept as a string so new values do not break parsing. + [JsonPropertyName("stopReason")] public string StopReason { get; set; } = ""; +} + +/// The session/cancel notification. +public sealed record CancelNotification : AcpObject +{ + [JsonPropertyName("sessionId")] public string SessionId { get; set; } = ""; +} + +// ───────────────────────── client-side requests ───────────────────────── + +public sealed record PermissionOption : AcpObject +{ + [JsonPropertyName("optionId")] public string OptionId { get; set; } = ""; + [JsonPropertyName("name")] public string Name { get; set; } = ""; + /// One of . + [JsonPropertyName("kind")] public string Kind { get; set; } = ""; +} + +public sealed record RequestPermissionRequest : AcpObject +{ + [JsonPropertyName("sessionId")] public string SessionId { get; set; } = ""; + [JsonPropertyName("toolCall")] public ToolCallUpdate ToolCall { get; set; } = new(); + [JsonPropertyName("options")] public IReadOnlyList Options { get; set; } = []; +} + +/// The client's answer to a permission request: the user either picked an option or the turn was cancelled. +[JsonConverter(typeof(RequestPermissionOutcomeConverter))] +public abstract record RequestPermissionOutcome : AcpObject; + +public sealed record CancelledPermissionOutcome : RequestPermissionOutcome +{ + [JsonPropertyName("outcome")] public string Outcome => "cancelled"; +} + +public sealed record SelectedPermissionOutcome : RequestPermissionOutcome +{ + [JsonPropertyName("outcome")] public string Outcome => "selected"; + [JsonPropertyName("optionId")] public string OptionId { get; set; } = ""; +} + +public sealed record RequestPermissionResponse : AcpObject +{ + [JsonPropertyName("outcome")] public RequestPermissionOutcome Outcome { get; set; } = new CancelledPermissionOutcome(); +} + +public sealed record ReadTextFileRequest : AcpObject +{ + [JsonPropertyName("sessionId")] public string SessionId { get; set; } = ""; + [JsonPropertyName("path")] public string Path { get; set; } = ""; + [JsonPropertyName("line")] public int? Line { get; set; } + [JsonPropertyName("limit")] public int? Limit { get; set; } +} + +public sealed record ReadTextFileResponse : AcpObject +{ + [JsonPropertyName("content")] public string Content { get; set; } = ""; +} + +public sealed record WriteTextFileRequest : AcpObject +{ + [JsonPropertyName("sessionId")] public string SessionId { get; set; } = ""; + [JsonPropertyName("path")] public string Path { get; set; } = ""; + [JsonPropertyName("content")] public string Content { get; set; } = ""; +} + +public sealed record WriteTextFileResponse : AcpObject; diff --git a/src/MandoCode.Acp/Protocol/Updates.cs b/src/MandoCode.Acp/Protocol/Updates.cs new file mode 100644 index 0000000..f9ca61d --- /dev/null +++ b/src/MandoCode.Acp/Protocol/Updates.cs @@ -0,0 +1,130 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MandoCode.Acp.Protocol; + +/// The session/update notification. +public sealed record SessionNotification : AcpObject +{ + [JsonPropertyName("sessionId")] public string SessionId { get; set; } = ""; + [JsonPropertyName("update")] public SessionUpdate Update { get; set; } = new UnknownSessionUpdate(null, default); +} + +/// +/// The payload of session/update, discriminated by sessionUpdate. Read-only on the +/// client side: this client never sends one. Variants this client does not know (for example +/// usage_update) deserialize to . +/// +[JsonConverter(typeof(SessionUpdateConverter))] +public abstract record SessionUpdate : AcpObject; + +public abstract record ContentChunkUpdate : SessionUpdate +{ + [JsonPropertyName("content")] public ContentBlock Content { get; set; } = new TextContent(); + [JsonPropertyName("messageId")] public string? MessageId { get; set; } +} + +public sealed record UserMessageChunk : ContentChunkUpdate; +public sealed record AgentMessageChunk : ContentChunkUpdate; +public sealed record AgentThoughtChunk : ContentChunkUpdate; + +public sealed record ToolCallLocation : AcpObject +{ + [JsonPropertyName("path")] public string Path { get; set; } = ""; + [JsonPropertyName("line")] public int? Line { get; set; } +} + +/// Tool-call content, discriminated by type. Unknown types become . +[JsonConverter(typeof(ToolCallContentConverter))] +public abstract record ToolCallContent : AcpObject; + +public sealed record ContentToolCallContent : ToolCallContent +{ + [JsonPropertyName("content")] public ContentBlock Content { get; set; } = new TextContent(); +} + +public sealed record DiffToolCallContent : ToolCallContent +{ + [JsonPropertyName("path")] public string Path { get; set; } = ""; + [JsonPropertyName("oldText")] public string? OldText { get; set; } + [JsonPropertyName("newText")] public string NewText { get; set; } = ""; +} + +public sealed record TerminalToolCallContent : ToolCallContent +{ + [JsonPropertyName("terminalId")] public string TerminalId { get; set; } = ""; +} + +public sealed record UnknownToolCallContent(string? Kind, JsonElement Raw) : ToolCallContent; + +/// +/// Fields shared by tool_call and tool_call_update. Everything except the id is +/// optional in updates, so all of it is nullable here; sets the defaults +/// the schema documents (kind: other, status: pending) via GetEffectiveKind() / +/// GetEffectiveStatus(). +/// +public abstract record ToolCallBase : SessionUpdate +{ + [JsonPropertyName("toolCallId")] public string ToolCallId { get; set; } = ""; + [JsonPropertyName("title")] public string? Title { get; set; } + [JsonPropertyName("name")] public string? Name { get; set; } + /// One of , or a value from a newer agent. + [JsonPropertyName("kind")] public string? Kind { get; set; } + /// One of , or a value from a newer agent. + [JsonPropertyName("status")] public string? Status { get; set; } + [JsonPropertyName("content")] public IReadOnlyList? Content { get; set; } + [JsonPropertyName("locations")] public IReadOnlyList? Locations { get; set; } + [JsonPropertyName("rawInput")] public JsonElement? RawInput { get; set; } + [JsonPropertyName("rawOutput")] public JsonElement? RawOutput { get; set; } + + /// The kind, falling back to the schema default () when the agent omitted it. + public string GetEffectiveKind() => Kind ?? ToolKinds.Other; +} + +public sealed record ToolCall : ToolCallBase +{ + /// The status, falling back to the schema default () when omitted. + public string GetEffectiveStatus() => Status ?? ToolCallStatuses.Pending; +} + +public sealed record ToolCallUpdate : ToolCallBase; + +public sealed record PlanEntry : AcpObject +{ + [JsonPropertyName("content")] public string Content { get; set; } = ""; + /// One of . + [JsonPropertyName("priority")] public string Priority { get; set; } = ""; + /// One of . + [JsonPropertyName("status")] public string Status { get; set; } = ""; +} + +/// A full replacement of the agent's plan (the plan update always carries every entry). +public sealed record Plan : SessionUpdate +{ + [JsonPropertyName("entries")] public IReadOnlyList Entries { get; set; } = []; +} + +public sealed record UnstructuredCommandInput : AcpObject +{ + [JsonPropertyName("hint")] public string Hint { get; set; } = ""; +} + +public sealed record AvailableCommand : AcpObject +{ + [JsonPropertyName("name")] public string Name { get; set; } = ""; + [JsonPropertyName("description")] public string Description { get; set; } = ""; + [JsonPropertyName("input")] public UnstructuredCommandInput? Input { get; set; } +} + +public sealed record AvailableCommandsUpdate : SessionUpdate +{ + [JsonPropertyName("availableCommands")] public IReadOnlyList AvailableCommands { get; set; } = []; +} + +public sealed record CurrentModeUpdate : SessionUpdate +{ + [JsonPropertyName("currentModeId")] public string CurrentModeId { get; set; } = ""; +} + +/// A session/update variant this client does not know. The raw JSON is preserved; consumers ignore it. +public sealed record UnknownSessionUpdate(string? Kind, JsonElement Raw) : SessionUpdate; diff --git a/src/MandoCode.Acp/README.md b/src/MandoCode.Acp/README.md new file mode 100644 index 0000000..cd0c605 --- /dev/null +++ b/src/MandoCode.Acp/README.md @@ -0,0 +1,25 @@ +# MandoCode.Acp + +A thin, UI-free client for the [Agent Client Protocol](https://agentclientprotocol.com) (ACP), v1, +over stdio (newline-delimited JSON-RPC 2.0). + +- No third-party ACP libraries; DTOs are hand-written against the official JSON schema. +- `System.Text.Json` source generation (`AcpJsonContext`), no reflection-based serialization. +- Targets `net8.0` and `net10.0`. + +## Schema + +DTOs follow `schema.json` from `agentclientprotocol/agent-client-protocol`, pinned to tag +**`v1.16.0`** (`schema/v1/schema.json`). The vendored copy lives in +`tests/MandoCode.Tests/Acp/schema/schema.v1.json`; a drift test checks every modelled type +against it. To update: fetch the new tag's `schema/v1/schema.json`, replace the vendored file, +run the tests and update the tag here and in `AcpProtocol.SchemaTag`. + +## Compatibility rules + +- Unknown JSON fields are ignored. +- Unknown `session/update`, content-block and tool-call-content variants are surfaced as + `Unknown*` values instead of failing the message. +- "Enum" values (stop reasons, tool kinds, statuses, ...) are plain strings with constant + classes, so values added by newer agents never break parsing. +- Features are decided from the capabilities the agent returns from `initialize`. diff --git a/src/MandoCode/MandoCode.csproj b/src/MandoCode/MandoCode.csproj index 050948a..9620141 100644 --- a/src/MandoCode/MandoCode.csproj +++ b/src/MandoCode/MandoCode.csproj @@ -64,6 +64,11 @@ + + + + + diff --git a/tests/MandoCode.Tests/Acp/AcpProtocolTests.cs b/tests/MandoCode.Tests/Acp/AcpProtocolTests.cs new file mode 100644 index 0000000..8e0e7b8 --- /dev/null +++ b/tests/MandoCode.Tests/Acp/AcpProtocolTests.cs @@ -0,0 +1,458 @@ +using System.Text.Json; +using MandoCode.Acp.Protocol; +using Xunit; + +namespace MandoCode.Tests.Acp; + +public class AcpProtocolTests +{ + private static T Read(string json, System.Text.Json.Serialization.Metadata.JsonTypeInfo info) => + JsonSerializer.Deserialize(json, info)!; + + private static string Write(T value, System.Text.Json.Serialization.Metadata.JsonTypeInfo info) => + JsonSerializer.Serialize(value, info); + + // ───────────── requests we send ───────────── + + [Fact] + public void InitializeRequest_SerializesExpectedShape() + { + var request = new InitializeRequest + { + ClientCapabilities = new ClientCapabilities + { + Fs = new FileSystemCapabilities { ReadTextFile = true, WriteTextFile = true }, + Terminal = false, + }, + ClientInfo = new Implementation { Name = "MandoCode", Version = "1.2.3" }, + }; + + using var doc = JsonDocument.Parse(Write(request, AcpJsonContext.Default.InitializeRequest)); + var root = doc.RootElement; + + Assert.Equal(1, root.GetProperty("protocolVersion").GetInt32()); + Assert.True(root.GetProperty("clientCapabilities").GetProperty("fs").GetProperty("readTextFile").GetBoolean()); + Assert.True(root.GetProperty("clientCapabilities").GetProperty("fs").GetProperty("writeTextFile").GetBoolean()); + Assert.False(root.GetProperty("clientCapabilities").GetProperty("terminal").GetBoolean()); + Assert.Equal("MandoCode", root.GetProperty("clientInfo").GetProperty("name").GetString()); + Assert.False(root.TryGetProperty("_meta", out _), "null members must be omitted"); + } + + [Fact] + public void NewSessionRequest_SendsEmptyMcpServersArray() + { + var json = Write(new NewSessionRequest { Cwd = @"C:\work\proj" }, AcpJsonContext.Default.NewSessionRequest); + + using var doc = JsonDocument.Parse(json); + Assert.Equal(@"C:\work\proj", doc.RootElement.GetProperty("cwd").GetString()); + Assert.Equal(JsonValueKind.Array, doc.RootElement.GetProperty("mcpServers").ValueKind); + Assert.Equal(0, doc.RootElement.GetProperty("mcpServers").GetArrayLength()); + } + + [Fact] + public void PromptRequest_WritesContentBlocksWithDiscriminator() + { + var request = new PromptRequest + { + SessionId = "sess-1", + Prompt = + [ + new TextContent("hello"), + new ResourceLink { Name = "a.cs", Uri = "file:///C:/p/a.cs", MimeType = "text/plain", Size = 12 }, + new ImageContent { Data = "AAAA", MimeType = "image/png" }, + new EmbeddedResource { Resource = new TextResourceContents { Uri = "file:///C:/p/b.txt", Text = "body" } }, + ], + }; + + using var doc = JsonDocument.Parse(Write(request, AcpJsonContext.Default.PromptRequest)); + var prompt = doc.RootElement.GetProperty("prompt"); + + Assert.Equal("text", prompt[0].GetProperty("type").GetString()); + Assert.Equal("hello", prompt[0].GetProperty("text").GetString()); + Assert.Equal("resource_link", prompt[1].GetProperty("type").GetString()); + Assert.Equal(12, prompt[1].GetProperty("size").GetInt64()); + Assert.Equal("image", prompt[2].GetProperty("type").GetString()); + Assert.Equal("resource", prompt[3].GetProperty("type").GetString()); + Assert.Equal("body", prompt[3].GetProperty("resource").GetProperty("text").GetString()); + } + + [Fact] + public void CancelNotification_SerializesSessionId() + { + var json = Write(new CancelNotification { SessionId = "s" }, AcpJsonContext.Default.CancelNotification); + Assert.Equal("""{"sessionId":"s"}""", json); + } + + [Fact] + public void PermissionOutcomes_SerializeWithOutcomeDiscriminator() + { + var selected = Write( + new RequestPermissionResponse { Outcome = new SelectedPermissionOutcome { OptionId = "allow-1" } }, + AcpJsonContext.Default.RequestPermissionResponse); + var cancelled = Write( + new RequestPermissionResponse { Outcome = new CancelledPermissionOutcome() }, + AcpJsonContext.Default.RequestPermissionResponse); + + Assert.Equal("""{"outcome":{"outcome":"selected","optionId":"allow-1"}}""", selected); + Assert.Equal("""{"outcome":{"outcome":"cancelled"}}""", cancelled); + } + + [Fact] + public void PermissionOutcome_RoundTrips() + { + var response = Read("""{"outcome":{"optionId":"x","outcome":"selected"}}""", AcpJsonContext.Default.RequestPermissionResponse); + + var selected = Assert.IsType(response.Outcome); + Assert.Equal("x", selected.OptionId); + Assert.IsType( + Read("""{"outcome":{"outcome":"cancelled"}}""", AcpJsonContext.Default.RequestPermissionResponse).Outcome); + } + + [Fact] + public void McpServers_RoundTripEachKind() + { + var request = new NewSessionRequest + { + Cwd = "/p", + McpServers = + [ + new McpServerStdio { Name = "a", Command = "node", Args = ["x.js"], Env = [new EnvVariable { Name = "K", Value = "V" }] }, + new McpServerHttp { Name = "b", Url = "https://h", Headers = [new HttpHeader { Name = "H", Value = "1" }] }, + new McpServerSse { Name = "c", Url = "https://s" }, + ], + }; + + var json = Write(request, AcpJsonContext.Default.NewSessionRequest); + var back = Read(json, AcpJsonContext.Default.NewSessionRequest); + + Assert.IsType(back.McpServers[0]); + Assert.IsType(back.McpServers[1]); + Assert.IsType(back.McpServers[2]); + Assert.DoesNotContain("\"type\":\"stdio\"", json); + } + + // ───────────── responses we receive ───────────── + + [Fact] + public void InitializeResponse_ParsesCapabilitiesAndIgnoresUnknownFields() + { + const string json = """ + { + "protocolVersion": 1, + "futureTopLevelField": {"a": [1, 2, 3]}, + "agentInfo": {"name": "claude-agent", "version": "0.9.0", "title": "Claude"}, + "authMethods": [ + {"id": "claude-login", "name": "Claude login", "description": "run claude auth login"}, + {"type": "terminal", "id": "t", "name": "Terminal", "args": ["--login"]} + ], + "agentCapabilities": { + "loadSession": true, + "promptCapabilities": {"image": true, "audio": false, "embeddedContext": true, "somethingNew": true}, + "mcpCapabilities": {"http": true}, + "sessionCapabilities": {"list": {}} + } + } + """; + + var response = Read(json, AcpJsonContext.Default.InitializeResponse); + + Assert.Equal(1, response.ProtocolVersion); + Assert.Equal("claude-agent", response.AgentInfo!.Name); + Assert.True(response.AgentCapabilities.LoadSession); + Assert.True(response.AgentCapabilities.PromptCapabilities.Image); + Assert.False(response.AgentCapabilities.PromptCapabilities.Audio); + Assert.True(response.AgentCapabilities.PromptCapabilities.EmbeddedContext); + Assert.True(response.AgentCapabilities.McpCapabilities.Http); + Assert.False(response.AgentCapabilities.McpCapabilities.Sse); + Assert.Equal(2, response.AuthMethods.Count); + Assert.Equal("terminal", response.AuthMethods[1].Type); + } + + [Fact] + public void InitializeResponse_MissingOptionalSections_UseDefaults() + { + var response = Read("""{"protocolVersion":1}""", AcpJsonContext.Default.InitializeResponse); + + Assert.False(response.AgentCapabilities.PromptCapabilities.Image); + Assert.Empty(response.AuthMethods); + Assert.Null(response.AgentInfo); + } + + [Fact] + public void MissingFields_KeepInitializerDefaults() + { + // Regression: with init-only properties the net8 source generator overwrote initializers + // with null for every field absent from the JSON. + var capabilities = Read("{}", AcpJsonContext.Default.AgentCapabilities); + Assert.NotNull(capabilities.PromptCapabilities); + Assert.NotNull(capabilities.McpCapabilities); + + var request = Read("""{"cwd":"/p"}""", AcpJsonContext.Default.NewSessionRequest); + Assert.NotNull(request.McpServers); + Assert.Empty(request.McpServers); + + var notification = Read("""{"sessionId":"s","update":{"sessionUpdate":"plan"}}""", AcpJsonContext.Default.SessionNotification); + Assert.Empty(Assert.IsType(notification.Update).Entries); + + var chunk = Assert.IsType( + Read("""{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk"}}""", AcpJsonContext.Default.SessionNotification).Update); + Assert.NotNull(chunk.Content); + } + + [Fact] + public void NewSessionResponse_ParsesModes() + { + var response = Read( + """{"sessionId":"abc","modes":{"currentModeId":"default","availableModes":[{"id":"default","name":"Default"},{"id":"plan","name":"Plan","description":"x"}]},"configOptions":[{"anything":1}]}""", + AcpJsonContext.Default.NewSessionResponse); + + Assert.Equal("abc", response.SessionId); + Assert.Equal("default", response.Modes!.CurrentModeId); + Assert.Equal(2, response.Modes.AvailableModes.Count); + } + + [Theory] + [InlineData("end_turn")] + [InlineData("cancelled")] + [InlineData("a_stop_reason_from_the_future")] + public void PromptResponse_StopReasonIsAnOpenString(string reason) + { + var response = Read($$"""{"stopReason":"{{reason}}"}""", AcpJsonContext.Default.PromptResponse); + Assert.Equal(reason, response.StopReason); + } + + // ───────────── session/update ───────────── + + private static SessionNotification Update(string updateJson) => + Read("{\"sessionId\":\"s1\",\"update\":{" + updateJson + "}}", AcpJsonContext.Default.SessionNotification); + + [Fact] + public void AgentMessageChunk_ParsesTextContent() + { + var n = Update(""" + "sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Hel"} + """); + + var chunk = Assert.IsType(n.Update); + Assert.Equal("Hel", Assert.IsType(chunk.Content).Text); + Assert.Equal("s1", n.SessionId); + } + + [Fact] + public void Discriminator_MayAppearAfterOtherProperties() + { + // net8's [JsonPolymorphic] requires the discriminator first; real agents do not guarantee that. + var n = Update(""" + "content":{"text":"late","type":"text"},"messageId":"m1","sessionUpdate":"agent_thought_chunk" + """); + + var chunk = Assert.IsType(n.Update); + Assert.Equal("late", Assert.IsType(chunk.Content).Text); + Assert.Equal("m1", chunk.MessageId); + } + + [Fact] + public void UserMessageChunk_IsRecognised() + { + var n = Update(""" + "sessionUpdate":"user_message_chunk","content":{"type":"text","text":"hi"} + """); + Assert.IsType(n.Update); + } + + [Fact] + public void ToolCall_ParsesFieldsAndContentVariants() + { + var n = Update(""" + "sessionUpdate":"tool_call", + "toolCallId":"call_1","title":"Edit a.cs","kind":"edit","status":"in_progress", + "locations":[{"path":"C:\\p\\a.cs","line":10}], + "rawInput":{"path":"a.cs"}, + "content":[ + {"type":"diff","path":"C:\\p\\a.cs","oldText":"a","newText":"b"}, + {"type":"content","content":{"type":"text","text":"done"}}, + {"type":"terminal","terminalId":"t1"}, + {"type":"hologram","payload":1} + ] + """); + + var call = Assert.IsType(n.Update); + Assert.Equal("call_1", call.ToolCallId); + Assert.Equal("Edit a.cs", call.Title); + Assert.Equal(ToolKinds.Edit, call.GetEffectiveKind()); + Assert.Equal(ToolCallStatuses.InProgress, call.GetEffectiveStatus()); + Assert.Equal(10, call.Locations![0].Line); + Assert.Equal("a.cs", call.RawInput!.Value.GetProperty("path").GetString()); + + Assert.Collection(call.Content!, + c => { var d = Assert.IsType(c); Assert.Equal("a", d.OldText); Assert.Equal("b", d.NewText); }, + c => Assert.Equal("done", Assert.IsType(Assert.IsType(c).Content).Text), + c => Assert.Equal("t1", Assert.IsType(c).TerminalId), + c => Assert.Equal("hologram", Assert.IsType(c).Kind)); + } + + [Fact] + public void ToolCall_Defaults_FollowTheSchema() + { + var call = Assert.IsType(Update(""" + "sessionUpdate":"tool_call","toolCallId":"c","title":"t" + """).Update); + + Assert.Equal(ToolKinds.Other, call.GetEffectiveKind()); + Assert.Equal(ToolCallStatuses.Pending, call.GetEffectiveStatus()); + } + + [Fact] + public void ToolCallUpdate_PartialFieldsStayNull() + { + var update = Assert.IsType(Update(""" + "sessionUpdate":"tool_call_update","toolCallId":"c","status":"completed" + """).Update); + + Assert.Equal("c", update.ToolCallId); + Assert.Equal(ToolCallStatuses.Completed, update.Status); + Assert.Null(update.Title); + Assert.Null(update.Content); + Assert.Null(update.Locations); + } + + [Fact] + public void Plan_ParsesEntries() + { + var plan = Assert.IsType(Update(""" + "sessionUpdate":"plan","entries":[ + {"content":"Read file","priority":"high","status":"completed"}, + {"content":"Edit file","priority":"medium","status":"in_progress"}] + """).Update); + + Assert.Equal(2, plan.Entries.Count); + Assert.Equal(PlanEntryStatuses.InProgress, plan.Entries[1].Status); + } + + [Fact] + public void AvailableCommandsAndModeUpdates_Parse() + { + var commands = Assert.IsType(Update(""" + "sessionUpdate":"available_commands_update","availableCommands":[{"name":"init","description":"Init","input":{"hint":"path"}}] + """).Update); + Assert.Equal("path", commands.AvailableCommands[0].Input!.Hint); + + var mode = Assert.IsType(Update(""" + "sessionUpdate":"current_mode_update","currentModeId":"plan" + """).Update); + Assert.Equal("plan", mode.CurrentModeId); + } + + [Theory] + [InlineData("usage_update")] + [InlineData("session_info_update")] + [InlineData("config_option_update")] + [InlineData("something_invented_next_year")] + public void UnknownSessionUpdate_IsPreservedNotThrown(string kind) + { + var n = Update($$""" + "sessionUpdate":"{{kind}}","used":123,"nested":{"a":[1]} + """); + + var unknown = Assert.IsType(n.Update); + Assert.Equal(kind, unknown.Kind); + Assert.Equal(123, unknown.Raw.GetProperty("used").GetInt32()); + } + + [Fact] + public void SessionUpdate_WithoutDiscriminator_IsUnknown() + { + var n = Update(""" "content":{"type":"text","text":"x"} """); + Assert.Null(Assert.IsType(n.Update).Kind); + } + + [Fact] + public void KnownUpdate_WithMalformedBody_DegradesToUnknown() + { + // toolCallId has the wrong type: the message must not blow up the stream. + var n = Update(""" + "sessionUpdate":"tool_call","toolCallId":{"oops":true},"title":"t" + """); + + var unknown = Assert.IsType(n.Update); + Assert.Equal("tool_call", unknown.Kind); + } + + [Fact] + public void UnknownContentBlock_IsPreserved() + { + var n = Update(""" + "sessionUpdate":"agent_message_chunk","content":{"type":"hologram","depth":3} + """); + + var chunk = Assert.IsType(n.Update); + var unknown = Assert.IsType(chunk.Content); + Assert.Equal("hologram", unknown.Kind); + Assert.Equal(3, unknown.Raw.GetProperty("depth").GetInt32()); + } + + [Fact] + public void EmbeddedResource_DistinguishesTextFromBlob() + { + var text = Read("""{"type":"resource","resource":{"uri":"file:///a","text":"t"}}""", AcpJsonContext.Default.ContentBlock); + var blob = Read("""{"type":"resource","resource":{"uri":"file:///b","blob":"AAAA","mimeType":"image/png"}}""", AcpJsonContext.Default.ContentBlock); + + Assert.IsType(Assert.IsType(text).Resource); + Assert.IsType(Assert.IsType(blob).Resource); + } + + [Fact] + public void RequestPermissionRequest_ParsesToolCallAndOptions() + { + const string json = """ + { + "sessionId": "s", + "toolCall": {"toolCallId": "c1", "title": "Run tests", "kind": "execute", "status": "pending"}, + "options": [ + {"optionId": "a", "name": "Allow once", "kind": "allow_once"}, + {"optionId": "b", "name": "Reject", "kind": "reject_once"}, + {"optionId": "c", "name": "Whatever", "kind": "new_kind"} + ] + } + """; + + var request = Read(json, AcpJsonContext.Default.RequestPermissionRequest); + + Assert.Equal("c1", request.ToolCall.ToolCallId); + Assert.Equal(ToolKinds.Execute, request.ToolCall.Kind); + Assert.Equal(3, request.Options.Count); + Assert.Equal(PermissionOptionKinds.AllowOnce, request.Options[0].Kind); + Assert.Equal("new_kind", request.Options[2].Kind); + } + + [Fact] + public void FileSystemRequests_Parse() + { + var read = Read("""{"sessionId":"s","path":"C:\\p\\a.txt","line":3,"limit":10}""", AcpJsonContext.Default.ReadTextFileRequest); + Assert.Equal(@"C:\p\a.txt", read.Path); + Assert.Equal(3, read.Line); + Assert.Equal(10, read.Limit); + + var write = Read("""{"sessionId":"s","path":"/p/a.txt","content":"x"}""", AcpJsonContext.Default.WriteTextFileRequest); + Assert.Equal("x", write.Content); + + Assert.Null(Read("""{"sessionId":"s","path":"/p"}""", AcpJsonContext.Default.ReadTextFileRequest).Line); + } + + [Fact] + public void Meta_IsPreservedAsRawJson() + { + var response = Read("""{"protocolVersion":1,"_meta":{"vendor/x":{"k":1}}}""", AcpJsonContext.Default.InitializeResponse); + Assert.Equal(1, response.Meta!.Value.GetProperty("vendor/x").GetProperty("k").GetInt32()); + } + + [Fact] + public void ErrorCodes_MatchTheSchema() + { + Assert.Equal(-32601, AcpErrorCodes.MethodNotFound); + Assert.Equal(-32602, AcpErrorCodes.InvalidParams); + Assert.Equal(-32603, AcpErrorCodes.InternalError); + Assert.Equal(-32000, AcpErrorCodes.AuthRequired); + Assert.Equal(-32800, AcpErrorCodes.RequestCancelled); + } +} diff --git a/tests/MandoCode.Tests/Acp/AcpSchemaDriftTests.cs b/tests/MandoCode.Tests/Acp/AcpSchemaDriftTests.cs new file mode 100644 index 0000000..f0917f8 --- /dev/null +++ b/tests/MandoCode.Tests/Acp/AcpSchemaDriftTests.cs @@ -0,0 +1,210 @@ +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; +using MandoCode.Acp.Protocol; +using Xunit; + +namespace MandoCode.Tests.Acp; + +/// +/// Compares the hand-written DTOs with the vendored official schema +/// (Acp/schema/schema.v1.json, tag recorded in ). +/// Catches typos in JSON names, required fields we forgot to model, and drift in the string "enums". +/// +public class AcpSchemaDriftTests +{ + private static readonly JsonElement Defs = LoadDefs(); + + private static JsonElement LoadDefs() + { + var path = Path.Combine(AppContext.BaseDirectory, "Acp", "schema", "schema.v1.json"); + using var doc = JsonDocument.Parse(File.ReadAllText(path)); + return doc.RootElement.GetProperty("$defs").Clone(); + } + + // CLR type -> schema definition it models. + private static readonly (Type Clr, string Def)[] Models = + [ + (typeof(InitializeRequest), "InitializeRequest"), + (typeof(InitializeResponse), "InitializeResponse"), + (typeof(ClientCapabilities), "ClientCapabilities"), + (typeof(FileSystemCapabilities), "FileSystemCapabilities"), + (typeof(AgentCapabilities), "AgentCapabilities"), + (typeof(PromptCapabilities), "PromptCapabilities"), + (typeof(McpCapabilities), "McpCapabilities"), + (typeof(Implementation), "Implementation"), + (typeof(AuthenticateRequest), "AuthenticateRequest"), + (typeof(AuthenticateResponse), "AuthenticateResponse"), + (typeof(NewSessionRequest), "NewSessionRequest"), + (typeof(NewSessionResponse), "NewSessionResponse"), + (typeof(LoadSessionRequest), "LoadSessionRequest"), + (typeof(LoadSessionResponse), "LoadSessionResponse"), + (typeof(SetSessionModeRequest), "SetSessionModeRequest"), + (typeof(SetSessionModeResponse), "SetSessionModeResponse"), + (typeof(SessionMode), "SessionMode"), + (typeof(SessionModeState), "SessionModeState"), + (typeof(PromptRequest), "PromptRequest"), + (typeof(PromptResponse), "PromptResponse"), + (typeof(CancelNotification), "CancelNotification"), + (typeof(SessionNotification), "SessionNotification"), + (typeof(RequestPermissionRequest), "RequestPermissionRequest"), + (typeof(RequestPermissionResponse), "RequestPermissionResponse"), + (typeof(PermissionOption), "PermissionOption"), + (typeof(SelectedPermissionOutcome), "SelectedPermissionOutcome"), + (typeof(ReadTextFileRequest), "ReadTextFileRequest"), + (typeof(ReadTextFileResponse), "ReadTextFileResponse"), + (typeof(WriteTextFileRequest), "WriteTextFileRequest"), + (typeof(WriteTextFileResponse), "WriteTextFileResponse"), + (typeof(EnvVariable), "EnvVariable"), + (typeof(HttpHeader), "HttpHeader"), + (typeof(McpServerStdio), "McpServerStdio"), + (typeof(McpServerHttp), "McpServerHttp"), + (typeof(McpServerSse), "McpServerSse"), + (typeof(Annotations), "Annotations"), + (typeof(TextContent), "TextContent"), + (typeof(ImageContent), "ImageContent"), + (typeof(AudioContent), "AudioContent"), + (typeof(ResourceLink), "ResourceLink"), + (typeof(EmbeddedResource), "EmbeddedResource"), + (typeof(TextResourceContents), "TextResourceContents"), + (typeof(BlobResourceContents), "BlobResourceContents"), + (typeof(UserMessageChunk), "ContentChunk"), + (typeof(AgentMessageChunk), "ContentChunk"), + (typeof(AgentThoughtChunk), "ContentChunk"), + (typeof(ToolCall), "ToolCall"), + (typeof(ToolCallUpdate), "ToolCallUpdate"), + (typeof(ToolCallLocation), "ToolCallLocation"), + (typeof(ContentToolCallContent), "Content"), + (typeof(DiffToolCallContent), "Diff"), + (typeof(TerminalToolCallContent), "Terminal"), + (typeof(Plan), "Plan"), + (typeof(PlanEntry), "PlanEntry"), + (typeof(UnstructuredCommandInput), "UnstructuredCommandInput"), + (typeof(AvailableCommand), "AvailableCommand"), + (typeof(AvailableCommandsUpdate), "AvailableCommandsUpdate"), + (typeof(CurrentModeUpdate), "CurrentModeUpdate"), + ]; + + // Union discriminators live on the wrapping oneOf, not in the variant's own definition. + private static readonly HashSet Discriminators = ["type", "sessionUpdate", "outcome"]; + + public static IEnumerable ModelData() => + Models.Select(m => new object[] { m.Clr.Name, m.Def }); + + private static Type ClrFor(string clrName) => Models.First(m => m.Clr.Name == clrName).Clr; + + private static JsonTypeInfo InfoFor(Type type) => + AcpJsonContext.Default.GetTypeInfo(type) + ?? throw new InvalidOperationException($"{type.Name} is not registered in AcpJsonContext."); + + [Fact] + public void VendoredSchema_IsPresentAndNonTrivial() + { + Assert.True(Defs.EnumerateObject().Count() > 100); + Assert.True(Defs.TryGetProperty("SessionUpdate", out _)); + } + + [Theory] + [MemberData(nameof(ModelData))] + public void ModelledProperties_ExistInSchema(string clrName, string defName) + { + var schemaProps = SchemaProperties(defName); + var clrProps = InfoFor(ClrFor(clrName)).Properties.Select(p => p.Name).ToList(); + + Assert.Contains("_meta", clrProps); + var unknown = clrProps.Where(n => n != "_meta" && !Discriminators.Contains(n) && !schemaProps.Contains(n)).ToList(); + Assert.True(unknown.Count == 0, + $"{clrName} models properties missing from schema def '{defName}': {string.Join(", ", unknown)}"); + } + + [Theory] + [MemberData(nameof(ModelData))] + public void RequiredSchemaProperties_AreModelled(string clrName, string defName) + { + var required = SchemaRequired(defName); + var clrProps = InfoFor(ClrFor(clrName)).Properties.Select(p => p.Name).ToHashSet(); + + var missing = required.Where(r => !clrProps.Contains(r)).ToList(); + Assert.True(missing.Count == 0, + $"{clrName} does not model required properties of '{defName}': {string.Join(", ", missing)}"); + } + + public static IEnumerable EnumData() => + [ + [typeof(StopReasons), "StopReason"], + [typeof(ToolKinds), "ToolKind"], + [typeof(ToolCallStatuses), "ToolCallStatus"], + [typeof(PermissionOptionKinds), "PermissionOptionKind"], + [typeof(PlanEntryPriorities), "PlanEntryPriority"], + [typeof(PlanEntryStatuses), "PlanEntryStatus"], + [typeof(Roles), "Role"], + ]; + + [Theory] + [MemberData(nameof(EnumData))] + public void ConstantClasses_MatchSchemaEnums(Type constants, string defName) + { + var fromClr = constants.GetFields(BindingFlags.Public | BindingFlags.Static) + .Where(f => f.IsLiteral) + .Select(f => (string)f.GetRawConstantValue()!) + .OrderBy(x => x, StringComparer.Ordinal) + .ToList(); + + var fromSchema = Defs.GetProperty(defName).GetProperty("oneOf").EnumerateArray() + .Select(e => e.GetProperty("const").GetString()!) + .OrderBy(x => x, StringComparer.Ordinal) + .ToList(); + + Assert.Equal(fromSchema, fromClr); + } + + [Fact] + public void SessionUpdate_KnownVariantsAreSubsetOfSchemaVariants() + { + var schemaKinds = Defs.GetProperty("SessionUpdate").GetProperty("oneOf").EnumerateArray() + .Select(v => v.GetProperty("properties").GetProperty("sessionUpdate").GetProperty("const").GetString()!) + .ToHashSet(); + + string[] handled = + [ + "user_message_chunk", "agent_message_chunk", "agent_thought_chunk", "tool_call", + "tool_call_update", "plan", "available_commands_update", "current_mode_update", + ]; + + Assert.All(handled, kind => Assert.Contains(kind, schemaKinds)); + } + + [Fact] + public void Methods_AreDeclaredBySchema() + { + var methods = new HashSet(); + foreach (var def in Defs.EnumerateObject()) + if (def.Value.TryGetProperty("x-method", out var m) && m.ValueKind == JsonValueKind.String) + methods.Add(m.GetString()!); + + string[] used = + [ + AcpMethods.Initialize, AcpMethods.Authenticate, AcpMethods.SessionNew, AcpMethods.SessionLoad, + AcpMethods.SessionPrompt, AcpMethods.SessionCancel, AcpMethods.SessionSetMode, AcpMethods.SessionUpdate, + AcpMethods.SessionRequestPermission, AcpMethods.FsReadTextFile, AcpMethods.FsWriteTextFile, + ]; + + Assert.All(used, method => Assert.Contains(method, methods)); + } + + private static HashSet SchemaProperties(string defName) + { + var def = Defs.GetProperty(defName); + return def.TryGetProperty("properties", out var props) + ? props.EnumerateObject().Select(p => p.Name).ToHashSet() + : []; + } + + private static List SchemaRequired(string defName) + { + var def = Defs.GetProperty(defName); + return def.TryGetProperty("required", out var req) + ? req.EnumerateArray().Select(e => e.GetString()!).ToList() + : []; + } +} diff --git a/tests/MandoCode.Tests/Acp/schema/schema.v1.json b/tests/MandoCode.Tests/Acp/schema/schema.v1.json new file mode 100644 index 0000000..b8e9574 --- /dev/null +++ b/tests/MandoCode.Tests/Acp/schema/schema.v1.json @@ -0,0 +1,6241 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Agent Client Protocol", + "anyOf": [ + { + "title": "Agent", + "description": "A message (request, response, or notification) with `\"jsonrpc\": \"2.0\"` specified as\n[required by JSON-RPC 2.0 Specification][1].\n\n[1]: https://www.jsonrpc.org/specification#compatibility", + "type": "object", + "properties": { + "jsonrpc": { + "type": "string", + "enum": ["2.0"] + } + }, + "required": ["jsonrpc"], + "anyOf": [ + { + "title": "Request", + "allOf": [ + { + "$ref": "#/$defs/AgentRequest" + } + ] + }, + { + "title": "Response", + "allOf": [ + { + "$ref": "#/$defs/AgentResponse" + } + ] + }, + { + "title": "Notification", + "allOf": [ + { + "$ref": "#/$defs/AgentNotification" + } + ] + } + ] + }, + { + "title": "Client", + "description": "A message (request, response, or notification) with `\"jsonrpc\": \"2.0\"` specified as\n[required by JSON-RPC 2.0 Specification][1].\n\n[1]: https://www.jsonrpc.org/specification#compatibility", + "type": "object", + "properties": { + "jsonrpc": { + "type": "string", + "enum": ["2.0"] + } + }, + "required": ["jsonrpc"], + "anyOf": [ + { + "title": "Request", + "allOf": [ + { + "$ref": "#/$defs/ClientRequest" + } + ] + }, + { + "title": "Response", + "allOf": [ + { + "$ref": "#/$defs/ClientResponse" + } + ] + }, + { + "title": "Notification", + "allOf": [ + { + "$ref": "#/$defs/ClientNotification" + } + ] + } + ] + }, + { + "title": "ProtocolLevel", + "description": "A message (request, response, or notification) with `\"jsonrpc\": \"2.0\"` specified as\n[required by JSON-RPC 2.0 Specification][1].\n\n[1]: https://www.jsonrpc.org/specification#compatibility", + "type": "object", + "properties": { + "jsonrpc": { + "type": "string", + "enum": ["2.0"] + }, + "method": { + "description": "The notification method name.", + "type": "string" + }, + "params": { + "description": "Method-specific notification parameters.", + "anyOf": [ + { + "description": "General protocol-level notifications that all sides are expected to\nimplement.\n\nNotifications whose methods start with '$/' are messages which\nare protocol implementation dependent and might not be implementable in all\nclients or agents. For example if the implementation uses a single threaded\nsynchronous programming language then there is little it can do to react to\na `$/cancel_request` notification. If an agent or client receives\nnotifications starting with '$/' it is free to ignore the notification.\n\nNotifications do not expect a response.", + "anyOf": [ + { + "title": "CancelRequestNotification", + "description": "Cancels an ongoing request.\n\nThis is a notification sent by the side that sent a request to cancel that request.\n\nUpon receiving this notification, the receiver:\n\n1. MAY cancel the corresponding request activity and all nested activities\n2. MAY send any pending notifications.\n3. MUST send one of these responses for the original request:\n - Valid response with appropriate data (partial results or cancellation marker)\n - Error response with code `-32800` (Cancelled)\n\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v1/cancellation)", + "allOf": [ + { + "$ref": "#/$defs/CancelRequestNotification" + } + ] + } + ] + }, + { + "type": "null" + } + ] + } + }, + "required": ["jsonrpc", "method"], + "x-docs-ignore": true + } + ], + "$defs": { + "AgentRequest": { + "description": "A JSON-RPC request object.", + "type": "object", + "properties": { + "id": { + "description": "The request id used to correlate the matching response.", + "allOf": [ + { + "$ref": "#/$defs/RequestId" + } + ] + }, + "method": { + "description": "The method name to invoke.", + "type": "string" + }, + "params": { + "description": "Method-specific request parameters.", + "anyOf": [ + { + "description": "All possible requests that an agent can send to a client.\n\nThis enum is used internally for routing RPC requests. You typically won't need\nto use this directly.\n\nThis enum encompasses all method calls from agent to client.", + "anyOf": [ + { + "title": "WriteTextFileRequest", + "description": "Writes content to a text file in the client's file system.\n\nOnly available if the client advertises the `fs.writeTextFile` capability.\nAllows the agent to create or modify files within the client's environment.\n\nSee protocol docs: [Client](https://agentclientprotocol.com/protocol/v1/overview#client)", + "allOf": [ + { + "$ref": "#/$defs/WriteTextFileRequest" + } + ] + }, + { + "title": "ReadTextFileRequest", + "description": "Reads content from a text file in the client's file system.\n\nOnly available if the client advertises the `fs.readTextFile` capability.\nAllows the agent to access file contents within the client's environment.\n\nSee protocol docs: [Client](https://agentclientprotocol.com/protocol/v1/overview#client)", + "allOf": [ + { + "$ref": "#/$defs/ReadTextFileRequest" + } + ] + }, + { + "title": "RequestPermissionRequest", + "description": "Requests permission from the user for a tool call operation.\n\nCalled by the agent when it needs user authorization before executing\na potentially sensitive operation. The client should present the options\nto the user and return their decision.\n\nIf the client cancels the prompt turn via `session/cancel`, it MUST\nrespond to this request with the `cancelled` outcome.\n\nSee protocol docs: [Requesting Permission](https://agentclientprotocol.com/protocol/v1/tool-calls#requesting-permission)", + "allOf": [ + { + "$ref": "#/$defs/RequestPermissionRequest" + } + ] + }, + { + "title": "CreateTerminalRequest", + "description": "Executes a command in a new terminal\n\nOnly available if the `terminal` Client capability is set to `true`.\n\nReturns a `TerminalId` that can be used with other terminal methods\nto get the current output, wait for exit, and kill the command.\n\nThe `TerminalId` can also be used to embed the terminal in a tool call\nby using `terminal` tool call content.\n\nThe Agent is responsible for releasing the terminal by using the `terminal/release`\nmethod.\n\nSee protocol docs: [Terminals](https://agentclientprotocol.com/protocol/v1/terminals)", + "allOf": [ + { + "$ref": "#/$defs/CreateTerminalRequest" + } + ] + }, + { + "title": "TerminalOutputRequest", + "description": "Gets the terminal output and exit status\n\nReturns the current content in the terminal without waiting for the command to exit.\nIf the command has already exited, the exit status is included.\n\nSee protocol docs: [Terminals](https://agentclientprotocol.com/protocol/v1/terminals)", + "allOf": [ + { + "$ref": "#/$defs/TerminalOutputRequest" + } + ] + }, + { + "title": "ReleaseTerminalRequest", + "description": "Releases a terminal\n\nThe command is killed if it hasn't exited yet. Use `terminal/wait_for_exit`\nto wait for the command to exit before releasing the terminal.\n\nAfter release, the `TerminalId` can no longer be used with other `terminal/*` methods,\nbut tool calls that already contain it, continue to display its output.\n\nThe `terminal/kill` method can be used to terminate the command without releasing\nthe terminal, allowing the Agent to call `terminal/output` and other methods.\n\nSee protocol docs: [Terminals](https://agentclientprotocol.com/protocol/v1/terminals)", + "allOf": [ + { + "$ref": "#/$defs/ReleaseTerminalRequest" + } + ] + }, + { + "title": "WaitForTerminalExitRequest", + "description": "Waits for the terminal command to exit and return its exit status\n\nSee protocol docs: [Terminals](https://agentclientprotocol.com/protocol/v1/terminals)", + "allOf": [ + { + "$ref": "#/$defs/WaitForTerminalExitRequest" + } + ] + }, + { + "title": "KillTerminalRequest", + "description": "Kills the terminal command without releasing the terminal\n\nWhile `terminal/release` will also kill the command, this method will keep\nthe `TerminalId` valid so it can be used with other methods.\n\nThis method can be helpful when implementing command timeouts which terminate\nthe command as soon as elapsed, and then get the final output so it can be sent\nto the model.\n\nNote: Call `terminal/release` when `TerminalId` is no longer needed.\n\nSee protocol docs: [Terminals](https://agentclientprotocol.com/protocol/v1/terminals)", + "allOf": [ + { + "$ref": "#/$defs/KillTerminalRequest" + } + ] + }, + { + "title": "CreateElicitationRequest", + "description": "Requests structured user input via a form or URL.\n\nSee protocol docs: [Elicitation](https://agentclientprotocol.com/protocol/v1/elicitation)", + "allOf": [ + { + "$ref": "#/$defs/CreateElicitationRequest" + } + ] + }, + { + "title": "ExtMethodRequest", + "description": "Handles extension method requests from the agent.\n\nAllows the Agent to send an arbitrary request that is not part of the ACP spec.\nExtension methods provide a way to add custom functionality while maintaining\nprotocol compatibility.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "allOf": [ + { + "$ref": "#/$defs/ExtRequest" + } + ] + } + ] + }, + { + "type": "null" + } + ] + } + }, + "required": ["id", "method"], + "x-docs-ignore": true + }, + "RequestId": { + "description": "JSON RPC Request Id\n\nAn identifier established by the Client that MUST contain a String, Number, or NULL value if included. If it is not included it is assumed to be a notification. The value SHOULD normally not be Null \\[1\\] and Numbers SHOULD NOT contain fractional parts \\[2\\]\n\nThe Server MUST reply with the same value in the Response object if included. This member is used to correlate the context between the two objects.\n\n\\[1\\] The use of Null as a value for the id member in a Request object is discouraged, because this specification uses a value of Null for Responses with an unknown id. Also, because JSON-RPC 1.0 uses an id value of Null for Notifications this could cause confusion in handling.\n\n\\[2\\] Fractional parts may be problematic, since many decimal fractions cannot be represented exactly as binary fractions.", + "anyOf": [ + { + "title": "Null", + "description": "The JSON-RPC `null` request id.", + "type": "null" + }, + { + "title": "Number", + "description": "A numeric JSON-RPC request id.", + "type": "integer", + "format": "int64" + }, + { + "title": "Str", + "description": "A string JSON-RPC request id.", + "type": "string" + } + ] + }, + "WriteTextFileRequest": { + "description": "Request to write content to a text file.\n\nOnly available if the client supports the `fs.writeTextFile` capability.", + "type": "object", + "properties": { + "sessionId": { + "description": "The session ID for this request.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "path": { + "description": "Absolute path to the file to write.", + "type": "string" + }, + "content": { + "description": "The text content to write to the file.", + "type": "string" + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId", "path", "content"], + "x-side": "client", + "x-method": "fs/write_text_file" + }, + "SessionId": { + "description": "A unique identifier for a conversation session between a client and agent.\n\nEach session has its own context, conversation history, and state, so one\nagent can run several independent sessions.\n\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/v1/session-setup#session-id)", + "type": "string" + }, + "ReadTextFileRequest": { + "description": "Request to read content from a text file.\n\nOnly available if the client supports the `fs.readTextFile` capability.", + "type": "object", + "properties": { + "sessionId": { + "description": "The session ID for this request.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "path": { + "description": "Absolute path to the file to read.", + "type": "string" + }, + "line": { + "description": "Line number to start reading from (1-based).", + "type": ["integer", "null"], + "format": "uint32", + "minimum": 0 + }, + "limit": { + "description": "Maximum number of lines to read.", + "type": ["integer", "null"], + "format": "uint32", + "minimum": 0 + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId", "path"], + "x-side": "client", + "x-method": "fs/read_text_file" + }, + "RequestPermissionRequest": { + "description": "Request for user permission to execute a tool call.\n\nSent when the agent needs authorization before performing a sensitive operation.\n\nSee protocol docs: [Requesting Permission](https://agentclientprotocol.com/protocol/v1/tool-calls#requesting-permission)", + "type": "object", + "properties": { + "sessionId": { + "description": "The session ID for this request.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "toolCall": { + "description": "Details about the tool call requiring permission.", + "allOf": [ + { + "$ref": "#/$defs/ToolCallUpdate" + } + ] + }, + "options": { + "description": "Available permission options for the user to choose from.", + "type": "array", + "items": { + "$ref": "#/$defs/PermissionOption" + } + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId", "toolCall", "options"], + "x-side": "client", + "x-method": "session/request_permission" + }, + "ToolCallUpdate": { + "description": "An update to an existing tool call.\n\nUsed to report progress and results as tools execute. All fields except\nthe tool call ID are optional - only changed fields need to be included.\n\nSee protocol docs: [Updating](https://agentclientprotocol.com/protocol/v1/tool-calls#updating)", + "type": "object", + "properties": { + "toolCallId": { + "description": "The ID of the tool call being updated.", + "allOf": [ + { + "$ref": "#/$defs/ToolCallId" + } + ] + }, + "kind": { + "description": "Update the tool kind.", + "anyOf": [ + { + "$ref": "#/$defs/ToolKind" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "status": { + "description": "Update the execution status.", + "anyOf": [ + { + "$ref": "#/$defs/ToolCallStatus" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "title": { + "description": "Update the human-readable title.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "name": { + "description": "Update the programmatic name of the tool being invoked.\n\nThis field is optional. Omitting it or sending `null` both mean that\nthe existing name is left unchanged.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "content": { + "description": "Replace the content collection.", + "type": ["array", "null"], + "items": { + "$ref": "#/$defs/ToolCallContent" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "locations": { + "description": "Replace the locations collection.", + "type": ["array", "null"], + "items": { + "$ref": "#/$defs/ToolCallLocation" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "rawInput": { + "description": "Update the raw input.", + "x-deserialize-default-on-error": true + }, + "rawOutput": { + "description": "Update the raw output.", + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["toolCallId"] + }, + "ToolCallId": { + "description": "Unique identifier for a tool call within a session.", + "type": "string" + }, + "ToolKind": { + "description": "Categories of tools that can be invoked.\n\nTool kinds help clients choose appropriate icons and optimize how they\ndisplay tool execution progress.\n\nSee protocol docs: [Creating](https://agentclientprotocol.com/protocol/v1/tool-calls#creating)", + "oneOf": [ + { + "description": "Reading files or data.", + "type": "string", + "const": "read" + }, + { + "description": "Modifying files or content.", + "type": "string", + "const": "edit" + }, + { + "description": "Removing files or data.", + "type": "string", + "const": "delete" + }, + { + "description": "Moving or renaming files.", + "type": "string", + "const": "move" + }, + { + "description": "Searching for information.", + "type": "string", + "const": "search" + }, + { + "description": "Running commands or code.", + "type": "string", + "const": "execute" + }, + { + "description": "Internal reasoning or planning.", + "type": "string", + "const": "think" + }, + { + "description": "Retrieving external data.", + "type": "string", + "const": "fetch" + }, + { + "description": "Switching the current session mode.", + "type": "string", + "const": "switch_mode" + }, + { + "description": "Other tool types (default).", + "type": "string", + "const": "other" + } + ] + }, + "ToolCallStatus": { + "description": "Execution status of a tool call.\n\nTool calls progress through different statuses during their lifecycle.\n\nSee protocol docs: [Status](https://agentclientprotocol.com/protocol/v1/tool-calls#status)", + "oneOf": [ + { + "description": "The tool call hasn't started running yet because the input is either\nstreaming or we're awaiting approval.", + "type": "string", + "const": "pending" + }, + { + "description": "The tool call is currently running.", + "type": "string", + "const": "in_progress" + }, + { + "description": "The tool call completed successfully.", + "type": "string", + "const": "completed" + }, + { + "description": "The tool call failed with an error.", + "type": "string", + "const": "failed" + } + ] + }, + "ToolCallContent": { + "description": "Content produced by a tool call.\n\nTool calls can produce different types of content including\nstandard content blocks (text, images) or file diffs.\n\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/v1/tool-calls#content)", + "oneOf": [ + { + "description": "Standard content block (text, images, resources).", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "content" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/Content" + } + ] + }, + { + "description": "File modification shown as a diff.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "diff" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/Diff" + } + ] + }, + { + "description": "Embed a terminal created with `terminal/create` by its id.\n\nThe terminal must be added before calling `terminal/release`.\n\nSee protocol docs: [Terminal](https://agentclientprotocol.com/protocol/v1/terminals)", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "terminal" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/Terminal" + } + ] + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "ContentBlock": { + "description": "Content blocks represent displayable information in the Agent Client Protocol.\n\nContent blocks appear in:\n- User prompts sent via `session/prompt`\n- Language model output streamed through `session/update` notifications\n- Progress updates and results from tool calls\n\nThis structure is compatible with the Model Context Protocol (MCP), so agents can\nforward content from MCP tool outputs without transformation.\n\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/v1/content)", + "oneOf": [ + { + "description": "Text content. May be plain text or formatted with Markdown.\n\nAll agents MUST support text content blocks in prompts.\nClients SHOULD render this text as Markdown.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "text" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/TextContent" + } + ] + }, + { + "description": "Images for visual context or analysis.\n\nRequires the `image` prompt capability when included in prompts.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "image" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/ImageContent" + } + ] + }, + { + "description": "Audio data for transcription or analysis.\n\nRequires the `audio` prompt capability when included in prompts.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "audio" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/AudioContent" + } + ] + }, + { + "description": "References to resources that the agent can access.\n\nAll agents MUST support resource links in prompts.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "resource_link" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/ResourceLink" + } + ] + }, + { + "description": "Complete resource contents embedded directly in the message.\n\nPreferred for including context as it avoids extra round-trips.\n\nRequires the `embeddedContext` prompt capability when included in prompts.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "resource" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/EmbeddedResource" + } + ] + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "Annotations": { + "description": "Optional annotations for the client. The client can use annotations to inform how objects are used or displayed", + "type": "object", + "properties": { + "audience": { + "description": "Intended recipients for this content, such as the user or assistant.", + "type": ["array", "null"], + "items": { + "$ref": "#/$defs/Role" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "lastModified": { + "description": "Timestamp indicating when the underlying resource was last modified.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "priority": { + "description": "Relative importance of this content when clients choose what to surface.", + "type": ["number", "null"], + "format": "double", + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "Role": { + "description": "The sender or recipient of messages and data in a conversation.", + "oneOf": [ + { + "description": "The assistant side of a conversation.", + "type": "string", + "const": "assistant" + }, + { + "description": "The user side of a conversation.", + "type": "string", + "const": "user" + } + ] + }, + "TextContent": { + "description": "Text provided to or from an LLM.", + "type": "object", + "properties": { + "annotations": { + "description": "Optional annotations that help clients decide how to display or route this content.", + "anyOf": [ + { + "$ref": "#/$defs/Annotations" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "text": { + "description": "Text payload carried by this content block.", + "type": "string" + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["text"] + }, + "ImageContent": { + "description": "An image provided to or from an LLM.", + "type": "object", + "properties": { + "annotations": { + "description": "Optional annotations that help clients decide how to display or route this content.", + "anyOf": [ + { + "$ref": "#/$defs/Annotations" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "data": { + "description": "Base64-encoded media payload.", + "type": "string" + }, + "mimeType": { + "description": "MIME type describing the encoded media payload.", + "type": "string" + }, + "uri": { + "description": "URI associated with this resource or media payload.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["data", "mimeType"] + }, + "AudioContent": { + "description": "Audio provided to or from an LLM.", + "type": "object", + "properties": { + "annotations": { + "description": "Optional annotations that help clients decide how to display or route this content.", + "anyOf": [ + { + "$ref": "#/$defs/Annotations" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "data": { + "description": "Base64-encoded media payload.", + "type": "string" + }, + "mimeType": { + "description": "MIME type describing the encoded media payload.", + "type": "string" + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["data", "mimeType"] + }, + "ResourceLink": { + "description": "A resource that the server is capable of reading, included in a prompt or tool call result.", + "type": "object", + "properties": { + "annotations": { + "description": "Optional annotations that help clients decide how to display or route this content.", + "anyOf": [ + { + "$ref": "#/$defs/Annotations" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "description": { + "description": "Optional human-readable details shown with this protocol object.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "mimeType": { + "description": "MIME type describing the encoded media payload.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "name": { + "description": "Human-readable name shown for this protocol object.", + "type": "string" + }, + "size": { + "description": "Optional size of the linked resource in bytes, if known.", + "type": ["integer", "null"], + "format": "int64", + "x-deserialize-default-on-error": true + }, + "title": { + "description": "Optional display title for end-user UI.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "uri": { + "description": "URI associated with this resource or media payload.", + "type": "string" + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["name", "uri"] + }, + "EmbeddedResourceResource": { + "description": "Resource content that can be embedded in a message.", + "anyOf": [ + { + "title": "TextResourceContents", + "description": "Text resource contents embedded directly in the message.", + "allOf": [ + { + "$ref": "#/$defs/TextResourceContents" + } + ] + }, + { + "title": "BlobResourceContents", + "description": "Binary resource contents embedded directly in the message.", + "allOf": [ + { + "$ref": "#/$defs/BlobResourceContents" + } + ] + } + ] + }, + "TextResourceContents": { + "description": "Text-based resource contents.", + "type": "object", + "properties": { + "mimeType": { + "description": "MIME type describing the encoded media payload.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "text": { + "description": "Text payload carried by this content block.", + "type": "string" + }, + "uri": { + "description": "URI associated with this resource or media payload.", + "type": "string" + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["text", "uri"] + }, + "BlobResourceContents": { + "description": "Binary resource contents.", + "type": "object", + "properties": { + "blob": { + "description": "Base64-encoded bytes for a binary resource payload.", + "type": "string" + }, + "mimeType": { + "description": "MIME type describing the encoded media payload.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "uri": { + "description": "URI associated with this resource or media payload.", + "type": "string" + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["blob", "uri"] + }, + "EmbeddedResource": { + "description": "The contents of a resource, embedded into a prompt or tool call result.", + "type": "object", + "properties": { + "annotations": { + "description": "Optional annotations that help clients decide how to display or route this content.", + "anyOf": [ + { + "$ref": "#/$defs/Annotations" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "resource": { + "description": "Embedded resource payload, either text or binary data.", + "allOf": [ + { + "$ref": "#/$defs/EmbeddedResourceResource" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["resource"] + }, + "Content": { + "description": "Standard content block (text, images, resources).", + "type": "object", + "properties": { + "content": { + "description": "The actual content block.", + "allOf": [ + { + "$ref": "#/$defs/ContentBlock" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["content"] + }, + "Diff": { + "description": "A diff representing file modifications.\n\nShows changes to files in a format suitable for display in the client UI.\n\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/v1/tool-calls#content)", + "type": "object", + "properties": { + "path": { + "description": "The absolute file path being modified.", + "type": "string" + }, + "oldText": { + "description": "The original content (omitted or `null` for new files).", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "newText": { + "description": "The new content after modification.", + "type": "string" + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["path", "newText"] + }, + "TerminalId": { + "description": "Typed identifier used for terminal values on the wire.", + "type": "string" + }, + "Terminal": { + "description": "Embed a terminal created with `terminal/create` by its id.\n\nThe terminal must be added before calling `terminal/release`.\n\nSee protocol docs: [Terminal](https://agentclientprotocol.com/protocol/v1/terminals)", + "type": "object", + "properties": { + "terminalId": { + "description": "Identifier of the terminal instance to embed in the content stream.", + "allOf": [ + { + "$ref": "#/$defs/TerminalId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["terminalId"] + }, + "ToolCallLocation": { + "description": "A file location being accessed or modified by a tool.\n\nEnables clients to implement \"follow-along\" features that track\nwhich files the agent is working with in real-time.\n\nSee protocol docs: [Following the Agent](https://agentclientprotocol.com/protocol/v1/tool-calls#following-the-agent)", + "type": "object", + "properties": { + "path": { + "description": "The absolute file path being accessed or modified.", + "type": "string" + }, + "line": { + "description": "Optional 1-based line number within the file.", + "type": ["integer", "null"], + "format": "uint32", + "minimum": 0, + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["path"] + }, + "PermissionOption": { + "description": "An option presented to the user when requesting permission.", + "type": "object", + "properties": { + "optionId": { + "description": "Unique identifier for this permission option.", + "allOf": [ + { + "$ref": "#/$defs/PermissionOptionId" + } + ] + }, + "name": { + "description": "Human-readable label to display to the user.", + "type": "string" + }, + "kind": { + "description": "Hint about the nature of this permission option.", + "allOf": [ + { + "$ref": "#/$defs/PermissionOptionKind" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["optionId", "name", "kind"] + }, + "PermissionOptionId": { + "description": "Unique identifier for a permission option.", + "type": "string" + }, + "PermissionOptionKind": { + "description": "The type of permission option being presented to the user.\n\nHelps clients choose appropriate icons and UI treatment.", + "oneOf": [ + { + "description": "Allow this operation only this time.", + "type": "string", + "const": "allow_once" + }, + { + "description": "Allow this operation and remember the choice.", + "type": "string", + "const": "allow_always" + }, + { + "description": "Reject this operation only this time.", + "type": "string", + "const": "reject_once" + }, + { + "description": "Reject this operation and remember the choice.", + "type": "string", + "const": "reject_always" + } + ] + }, + "CreateTerminalRequest": { + "description": "Request to create a new terminal and execute a command.", + "type": "object", + "properties": { + "sessionId": { + "description": "The session ID for this request.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "command": { + "description": "The command to execute.", + "type": "string" + }, + "args": { + "description": "Array of command arguments.", + "type": "array", + "items": { + "type": "string" + }, + "x-deserialize-default-on-null": true + }, + "env": { + "description": "Environment variables for the command.", + "type": "array", + "items": { + "$ref": "#/$defs/EnvVariable" + }, + "x-deserialize-default-on-null": true + }, + "cwd": { + "description": "Working directory for the command. Must be an absolute path.", + "type": ["string", "null"] + }, + "outputByteLimit": { + "description": "Maximum number of output bytes to retain.\n\nWhen the limit is exceeded, the Client truncates from the beginning of the output\nto stay within the limit.\n\nThe Client MUST ensure truncation happens at a character boundary to maintain valid\nstring output, even if this means the retained output is slightly less than the\nspecified limit.", + "type": ["integer", "null"], + "format": "uint64", + "minimum": 0 + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId", "command"], + "x-side": "client", + "x-method": "terminal/create" + }, + "EnvVariable": { + "description": "An environment variable to set when launching an MCP server.", + "type": "object", + "properties": { + "name": { + "description": "The name of the environment variable.", + "type": "string" + }, + "value": { + "description": "The value to set for the environment variable.", + "type": "string" + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["name", "value"] + }, + "TerminalOutputRequest": { + "description": "Request to get the current output and status of a terminal.", + "type": "object", + "properties": { + "sessionId": { + "description": "The session ID for this request.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "terminalId": { + "description": "The ID of the terminal to get output from.", + "allOf": [ + { + "$ref": "#/$defs/TerminalId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId", "terminalId"], + "x-side": "client", + "x-method": "terminal/output" + }, + "ReleaseTerminalRequest": { + "description": "Request to release a terminal and free its resources.", + "type": "object", + "properties": { + "sessionId": { + "description": "The session ID for this request.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "terminalId": { + "description": "The ID of the terminal to release.", + "allOf": [ + { + "$ref": "#/$defs/TerminalId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId", "terminalId"], + "x-side": "client", + "x-method": "terminal/release" + }, + "WaitForTerminalExitRequest": { + "description": "Request to wait for a terminal command to exit.", + "type": "object", + "properties": { + "sessionId": { + "description": "The session ID for this request.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "terminalId": { + "description": "The ID of the terminal to wait for.", + "allOf": [ + { + "$ref": "#/$defs/TerminalId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId", "terminalId"], + "x-side": "client", + "x-method": "terminal/wait_for_exit" + }, + "KillTerminalRequest": { + "description": "Request to kill a terminal without releasing it.", + "type": "object", + "properties": { + "sessionId": { + "description": "The session ID for this request.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "terminalId": { + "description": "The ID of the terminal to kill.", + "allOf": [ + { + "$ref": "#/$defs/TerminalId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId", "terminalId"], + "x-side": "client", + "x-method": "terminal/kill" + }, + "CreateElicitationRequest": { + "description": "Request from the agent to elicit structured user input.\n\nThe agent sends this to the client to request information from the user,\neither via a form or by directing them to a URL.\nElicitations are tied to a session (optionally a tool call) or a request.", + "type": "object", + "properties": { + "message": { + "description": "A human-readable message describing what input is needed.", + "type": "string" + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "anyOf": [ + { + "description": "Form-based elicitation where the client renders a form from the provided schema.", + "type": "object", + "properties": { + "mode": { + "type": "string", + "const": "form" + } + }, + "required": ["mode"], + "allOf": [ + { + "$ref": "#/$defs/ElicitationFormMode" + } + ] + }, + { + "description": "URL-based elicitation where the client directs the user to a URL.", + "type": "object", + "properties": { + "mode": { + "type": "string", + "const": "url" + } + }, + "required": ["mode"], + "allOf": [ + { + "$ref": "#/$defs/ElicitationUrlMode" + } + ] + }, + { + "title": "other", + "description": "Custom or future elicitation mode.\n\nValues beginning with `_` are reserved for implementation-specific\nextensions. Unknown values that do not begin with `_` are reserved for\nfuture ACP variants.\n\nClients that do not understand this mode should preserve the raw payload\nwhen storing, replaying, proxying, or forwarding elicitation requests.\nThey MUST NOT render it as a known elicitation mode.", + "type": "object", + "properties": { + "mode": { + "description": "Custom or future elicitation mode.\n\nValues beginning with `_` are reserved for implementation-specific\nextensions. Unknown values that do not begin with `_` are reserved for\nfuture ACP variants.", + "type": "string" + } + }, + "required": ["mode"], + "anyOf": [ + { + "title": "Session", + "description": "Tied to a session, optionally to a specific tool call within that session.", + "allOf": [ + { + "$ref": "#/$defs/ElicitationSessionScope" + } + ] + }, + { + "title": "Request", + "description": "Tied to a specific JSON-RPC request outside of a session\n(e.g., during auth/configuration phases before any session is started).", + "allOf": [ + { + "$ref": "#/$defs/ElicitationRequestScope" + } + ] + } + ], + "unevaluatedProperties": true, + "not": { + "anyOf": [ + { + "type": "object", + "properties": { + "mode": { + "type": "string", + "const": "form" + } + }, + "required": ["mode"] + }, + { + "type": "object", + "properties": { + "mode": { + "type": "string", + "const": "url" + } + }, + "required": ["mode"] + } + ] + } + } + ], + "required": ["message"], + "x-side": "client", + "x-method": "elicitation/create" + }, + "ElicitationSessionScope": { + "description": "Session-scoped elicitation, optionally tied to a specific tool call.\n\nWhen `toolCallId` is set, the elicitation is tied to a specific tool call.\nThis is useful when an agent receives an elicitation from an MCP server\nduring a tool call and needs to redirect it to the user.", + "type": "object", + "properties": { + "sessionId": { + "description": "The session this elicitation is tied to.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "toolCallId": { + "description": "Optional tool call within the session.\n\nOptional. Omitted and `null` are equivalent and mean the elicitation is scoped to the\nsession without a specific tool call.", + "anyOf": [ + { + "$ref": "#/$defs/ToolCallId" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + } + }, + "required": ["sessionId"] + }, + "ElicitationRequestScope": { + "description": "Request-scoped elicitation, tied to a specific JSON-RPC request outside of a session\n(e.g., during auth/configuration phases before any session is started).", + "type": "object", + "properties": { + "requestId": { + "description": "The request this elicitation is tied to.", + "allOf": [ + { + "$ref": "#/$defs/RequestId" + } + ] + } + }, + "required": ["requestId"] + }, + "ElicitationSchema": { + "description": "Type-safe elicitation schema for requesting structured user input.\n\nThis represents a JSON Schema object with primitive-typed properties,\nas required by the elicitation specification.", + "type": "object", + "properties": { + "type": { + "description": "Type discriminator. Always `\"object\"`.", + "x-deserialize-default-on-error": true, + "default": "object", + "allOf": [ + { + "$ref": "#/$defs/ElicitationSchemaType" + } + ] + }, + "title": { + "description": "Optional title for the schema.\n\nOptional. Omitted and `null` are equivalent and mean no title is provided.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "properties": { + "description": "Property definitions (must be primitive types).", + "type": "object", + "default": {}, + "additionalProperties": { + "$ref": "#/$defs/ElicitationPropertySchema" + } + }, + "required": { + "description": "List of required property names.\n\nOptional. Omitted and `null` are equivalent and mean no property names are required.", + "type": ["array", "null"], + "items": { + "type": "string" + } + }, + "description": { + "description": "Optional description of what this schema represents.\n\nOptional. Omitted and `null` are equivalent and mean no schema description is provided.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "ElicitationSchemaType": { + "description": "Type discriminator for elicitation schemas.", + "oneOf": [ + { + "description": "Object schema type.", + "type": "string", + "const": "object" + } + ] + }, + "ElicitationPropertySchema": { + "description": "Property schema for elicitation form fields.\n\nEach variant corresponds to a JSON Schema `\"type\"` value.\nSingle-select enums use `type: \"string\"` with `enum` or `oneOf` set.\nMulti-select enums use `type: \"array\"`.", + "anyOf": [ + { + "description": "String property (or single-select enum when `enum`/`oneOf` is set).", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "string" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/StringPropertySchema" + } + ] + }, + { + "description": "Number (floating-point) property.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "number" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/NumberPropertySchema" + } + ] + }, + { + "description": "Integer property.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "integer" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/IntegerPropertySchema" + } + ] + }, + { + "description": "Boolean property.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "boolean" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/BooleanPropertySchema" + } + ] + }, + { + "description": "Multi-select array property.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "array" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/MultiSelectPropertySchema" + } + ] + }, + { + "title": "other", + "description": "Custom or future elicitation property schema.\n\nValues beginning with `_` are reserved for implementation-specific\nextensions. Unknown values that do not begin with `_` are reserved for\nfuture ACP variants.\n\nClients that do not understand this property schema type should preserve\nthe raw schema when storing, replaying, proxying, or forwarding\nelicitation requests. They MUST NOT render it as a known input control.", + "type": "object", + "properties": { + "type": { + "description": "Custom or future elicitation property schema type.\n\nValues beginning with `_` are reserved for implementation-specific\nextensions. Unknown values that do not begin with `_` are reserved for\nfuture ACP variants.", + "type": "string" + } + }, + "required": ["type"], + "not": { + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "string" + } + }, + "required": ["type"] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "number" + } + }, + "required": ["type"] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "integer" + } + }, + "required": ["type"] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "boolean" + } + }, + "required": ["type"] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "array" + } + }, + "required": ["type"] + } + ] + }, + "additionalProperties": true + } + ] + }, + "StringFormat": { + "description": "String format types for string properties in elicitation schemas.", + "oneOf": [ + { + "description": "Email address format.", + "type": "string", + "const": "email" + }, + { + "description": "URI format.", + "type": "string", + "const": "uri" + }, + { + "description": "Date format (YYYY-MM-DD).", + "type": "string", + "const": "date" + }, + { + "description": "Date-time format (ISO 8601).", + "type": "string", + "const": "date-time" + } + ] + }, + "EnumOption": { + "description": "A titled enum option with a const value, human-readable title, and optional description.", + "type": "object", + "properties": { + "const": { + "description": "The constant value for this option.", + "type": "string" + }, + "title": { + "description": "Human-readable title for this option.", + "type": "string" + }, + "description": { + "description": "Human-readable description.\n\nOptional. Omitted and `null` are equivalent and mean no description is provided.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["const", "title"] + }, + "StringPropertySchema": { + "description": "Schema for string properties in an elicitation form.\n\nWhen `enum` or `oneOf` is set, this represents a single-select enum\nwith `\"type\": \"string\"`.", + "type": "object", + "properties": { + "title": { + "description": "Optional title for the property.\n\nOptional. Omitted and `null` are equivalent and mean no title is provided.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "description": { + "description": "Human-readable description.\n\nOptional. Omitted and `null` are equivalent and mean no description is provided.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "minLength": { + "description": "Minimum string length.\n\nOptional. Omitted and `null` are equivalent and mean there is no minimum length constraint.", + "type": ["integer", "null"], + "format": "uint32", + "minimum": 0 + }, + "maxLength": { + "description": "Maximum string length.\n\nOptional. Omitted and `null` are equivalent and mean there is no maximum length constraint.", + "type": ["integer", "null"], + "format": "uint32", + "minimum": 0 + }, + "pattern": { + "description": "Pattern the string must match.\n\nOptional. Omitted and `null` are equivalent and mean there is no pattern constraint.", + "type": ["string", "null"] + }, + "format": { + "description": "String format.\n\nOptional. Omitted and `null` are equivalent and mean there is no format constraint.", + "anyOf": [ + { + "$ref": "#/$defs/StringFormat" + }, + { + "type": "null" + } + ] + }, + "default": { + "description": "Default value.\n\nOptional. Omitted and `null` are equivalent and mean no default value is provided.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "enum": { + "description": "Enum values for untitled single-select enums.\nOptional. Omitted and `null` are equivalent and mean no untitled single-select choices are\ndeclared by `enum`.", + "type": ["array", "null"], + "items": { + "type": "string" + } + }, + "oneOf": { + "description": "Titled enum options for titled single-select enums.\nOptional. Omitted and `null` are equivalent and mean no titled single-select choices are\ndeclared by `oneOf`.", + "type": ["array", "null"], + "items": { + "$ref": "#/$defs/EnumOption" + } + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "NumberPropertySchema": { + "description": "Schema for number (floating-point) properties in an elicitation form.", + "type": "object", + "properties": { + "title": { + "description": "Optional title for the property.\n\nOptional. Omitted and `null` are equivalent and mean no title is provided.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "description": { + "description": "Human-readable description.\n\nOptional. Omitted and `null` are equivalent and mean no description is provided.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "minimum": { + "description": "Minimum value (inclusive).\n\nOptional. Omitted and `null` are equivalent and mean there is no inclusive lower bound.", + "type": ["number", "null"], + "format": "double" + }, + "maximum": { + "description": "Maximum value (inclusive).\n\nOptional. Omitted and `null` are equivalent and mean there is no inclusive upper bound.", + "type": ["number", "null"], + "format": "double" + }, + "default": { + "description": "Default value.\n\nOptional. Omitted and `null` are equivalent and mean no default value is provided.", + "type": ["number", "null"], + "format": "double", + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "IntegerPropertySchema": { + "description": "Schema for integer properties in an elicitation form.", + "type": "object", + "properties": { + "title": { + "description": "Optional title for the property.\n\nOptional. Omitted and `null` are equivalent and mean no title is provided.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "description": { + "description": "Human-readable description.\n\nOptional. Omitted and `null` are equivalent and mean no description is provided.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "minimum": { + "description": "Minimum value (inclusive).\n\nOptional. Omitted and `null` are equivalent and mean there is no inclusive lower bound.", + "type": ["integer", "null"], + "format": "int64" + }, + "maximum": { + "description": "Maximum value (inclusive).\n\nOptional. Omitted and `null` are equivalent and mean there is no inclusive upper bound.", + "type": ["integer", "null"], + "format": "int64" + }, + "default": { + "description": "Default value.\n\nOptional. Omitted and `null` are equivalent and mean no default value is provided.", + "type": ["integer", "null"], + "format": "int64", + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "BooleanPropertySchema": { + "description": "Schema for boolean properties in an elicitation form.", + "type": "object", + "properties": { + "title": { + "description": "Optional title for the property.\n\nOptional. Omitted and `null` are equivalent and mean no title is provided.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "description": { + "description": "Human-readable description.\n\nOptional. Omitted and `null` are equivalent and mean no description is provided.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "default": { + "description": "Default value.\n\nOptional. Omitted and `null` are equivalent and mean no default value is provided.", + "type": ["boolean", "null"], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "MultiSelectItems": { + "description": "Items for a multi-select (array) property schema.", + "anyOf": [ + { + "description": "Multi-select string items with plain string values.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "string" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/StringMultiSelectItems" + } + ] + }, + { + "title": "other", + "description": "Custom or future typed multi-select items.", + "type": "object", + "properties": { + "type": { + "description": "Custom or future multi-select item type.\n\nValues beginning with `_` are reserved for implementation-specific\nextensions. Unknown values that do not begin with `_` are reserved for\nfuture ACP variants.", + "type": "string" + } + }, + "required": ["type"], + "not": { + "anyOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "string" + } + }, + "required": ["type"] + } + ] + }, + "additionalProperties": true + }, + { + "title": "titled", + "description": "Titled multi-select items with human-readable labels.\n\nAs in MCP, titled items omit `type` and are identified by `anyOf`.", + "allOf": [ + { + "$ref": "#/$defs/TitledMultiSelectItems" + } + ] + } + ] + }, + "StringMultiSelectItems": { + "description": "String item schema for multi-select enum properties.", + "type": "object", + "properties": { + "enum": { + "description": "Allowed enum values.", + "type": "array", + "items": { + "type": "string" + } + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["enum"] + }, + "TitledMultiSelectItems": { + "description": "Items definition for titled multi-select enum properties.", + "type": "object", + "properties": { + "anyOf": { + "description": "Titled enum options.", + "type": "array", + "items": { + "$ref": "#/$defs/EnumOption" + } + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["anyOf"] + }, + "MultiSelectPropertySchema": { + "description": "Schema for multi-select (array) properties in an elicitation form.", + "type": "object", + "properties": { + "title": { + "description": "Optional title for the property.\n\nOptional. Omitted and `null` are equivalent and mean no title is provided.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "description": { + "description": "Human-readable description.\n\nOptional. Omitted and `null` are equivalent and mean no description is provided.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "minItems": { + "description": "Minimum number of items to select.\n\nOptional. Omitted and `null` are equivalent and mean there is no minimum selection count.", + "type": ["integer", "null"], + "format": "uint64", + "minimum": 0 + }, + "maxItems": { + "description": "Maximum number of items to select.\n\nOptional. Omitted and `null` are equivalent and mean there is no maximum selection count.", + "type": ["integer", "null"], + "format": "uint64", + "minimum": 0 + }, + "items": { + "description": "The items definition describing allowed values.", + "allOf": [ + { + "$ref": "#/$defs/MultiSelectItems" + } + ] + }, + "default": { + "description": "Default selected values.\n\nOptional. Omitted and `null` are equivalent and mean no default selections are provided.", + "type": ["array", "null"], + "items": { + "type": "string" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["items"] + }, + "ElicitationFormMode": { + "description": "Form-based elicitation mode where the client renders a form from the provided schema.", + "type": "object", + "properties": { + "requestedSchema": { + "description": "A JSON Schema describing the form fields to present to the user.", + "allOf": [ + { + "$ref": "#/$defs/ElicitationSchema" + } + ] + } + }, + "anyOf": [ + { + "title": "Session", + "description": "Tied to a session, optionally to a specific tool call within that session.", + "allOf": [ + { + "$ref": "#/$defs/ElicitationSessionScope" + } + ] + }, + { + "title": "Request", + "description": "Tied to a specific JSON-RPC request outside of a session\n(e.g., during auth/configuration phases before any session is started).", + "allOf": [ + { + "$ref": "#/$defs/ElicitationRequestScope" + } + ] + } + ], + "required": ["requestedSchema"] + }, + "ElicitationId": { + "description": "Unique identifier for an elicitation.", + "type": "string" + }, + "ElicitationUrlMode": { + "description": "URL-based elicitation mode where the client directs the user to a URL.", + "type": "object", + "properties": { + "elicitationId": { + "description": "The unique identifier for this elicitation.", + "allOf": [ + { + "$ref": "#/$defs/ElicitationId" + } + ] + }, + "url": { + "description": "The URL to direct the user to.", + "type": "string", + "format": "uri" + } + }, + "anyOf": [ + { + "title": "Session", + "description": "Tied to a session, optionally to a specific tool call within that session.", + "allOf": [ + { + "$ref": "#/$defs/ElicitationSessionScope" + } + ] + }, + { + "title": "Request", + "description": "Tied to a specific JSON-RPC request outside of a session\n(e.g., during auth/configuration phases before any session is started).", + "allOf": [ + { + "$ref": "#/$defs/ElicitationRequestScope" + } + ] + } + ], + "required": ["elicitationId", "url"] + }, + "ExtRequest": { + "description": "Allows for sending an arbitrary request that is not part of the ACP spec.\nExtension methods provide a way to add custom functionality while maintaining\nprotocol compatibility.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)" + }, + "AgentResponse": { + "description": "A JSON-RPC response object.", + "anyOf": [ + { + "title": "Result", + "description": "A successful JSON-RPC response.", + "type": "object", + "properties": { + "id": { + "description": "The id of the request this response answers.", + "allOf": [ + { + "$ref": "#/$defs/RequestId" + } + ] + }, + "result": { + "description": "Method-specific response data.", + "anyOf": [ + { + "title": "InitializeResponse", + "description": "Successful result returned for a `initialize` request.", + "allOf": [ + { + "$ref": "#/$defs/InitializeResponse" + } + ] + }, + { + "title": "AuthenticateResponse", + "description": "Successful result returned for a `authenticate` request.", + "allOf": [ + { + "$ref": "#/$defs/AuthenticateResponse" + } + ] + }, + { + "title": "LogoutResponse", + "description": "Successful result returned for a `logout` request.", + "allOf": [ + { + "$ref": "#/$defs/LogoutResponse" + } + ] + }, + { + "title": "NewSessionResponse", + "description": "Successful result returned for a `session/new` request.", + "allOf": [ + { + "$ref": "#/$defs/NewSessionResponse" + } + ] + }, + { + "title": "LoadSessionResponse", + "description": "Successful result returned for a `session/load` request.", + "allOf": [ + { + "$ref": "#/$defs/LoadSessionResponse" + } + ] + }, + { + "title": "ListSessionsResponse", + "description": "Successful result returned for a `session/list` request.", + "allOf": [ + { + "$ref": "#/$defs/ListSessionsResponse" + } + ] + }, + { + "title": "DeleteSessionResponse", + "description": "Successful result returned for a `session/delete` request.", + "allOf": [ + { + "$ref": "#/$defs/DeleteSessionResponse" + } + ] + }, + { + "title": "ResumeSessionResponse", + "description": "Successful result returned for a `session/resume` request.", + "allOf": [ + { + "$ref": "#/$defs/ResumeSessionResponse" + } + ] + }, + { + "title": "CloseSessionResponse", + "description": "Successful result returned for a `session/close` request.", + "allOf": [ + { + "$ref": "#/$defs/CloseSessionResponse" + } + ] + }, + { + "title": "SetSessionModeResponse", + "description": "Successful result returned for a `session/set_mode` request.", + "allOf": [ + { + "$ref": "#/$defs/SetSessionModeResponse" + } + ] + }, + { + "title": "SetSessionConfigOptionResponse", + "description": "Successful result returned for a `session/set_config_option` request.", + "allOf": [ + { + "$ref": "#/$defs/SetSessionConfigOptionResponse" + } + ] + }, + { + "title": "PromptResponse", + "description": "Successful result returned for a `session/prompt` request.", + "allOf": [ + { + "$ref": "#/$defs/PromptResponse" + } + ] + }, + { + "title": "ExtMethodResponse", + "description": "Successful result returned by an extension method outside the core ACP method set.", + "allOf": [ + { + "$ref": "#/$defs/ExtResponse" + } + ] + } + ] + } + }, + "required": ["id", "result"] + }, + { + "title": "Error", + "description": "A failed JSON-RPC response.", + "type": "object", + "properties": { + "id": { + "description": "The id of the request this response answers.", + "allOf": [ + { + "$ref": "#/$defs/RequestId" + } + ] + }, + "error": { + "description": "Method-specific error data.", + "allOf": [ + { + "$ref": "#/$defs/Error" + } + ] + } + }, + "required": ["id", "error"] + } + ], + "x-docs-ignore": true + }, + "InitializeResponse": { + "description": "Response to the `initialize` method.\n\nContains the negotiated protocol version and agent capabilities.\n\nSee protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v1/initialization)", + "type": "object", + "properties": { + "protocolVersion": { + "description": "The protocol version the client specified if supported by the agent,\nor the latest protocol version supported by the agent.\n\nThe client should disconnect, if it doesn't support this version.", + "allOf": [ + { + "$ref": "#/$defs/ProtocolVersion" + } + ] + }, + "agentCapabilities": { + "description": "Capabilities supported by the agent.", + "x-deserialize-default-on-error": true, + "default": { + "loadSession": false, + "promptCapabilities": { + "image": false, + "audio": false, + "embeddedContext": false + }, + "mcpCapabilities": { + "http": false, + "sse": false + }, + "sessionCapabilities": {}, + "auth": {} + }, + "allOf": [ + { + "$ref": "#/$defs/AgentCapabilities" + } + ] + }, + "authMethods": { + "description": "Authentication methods supported by the agent.", + "type": "array", + "items": { + "$ref": "#/$defs/AuthMethod" + }, + "default": [], + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "agentInfo": { + "description": "Information about the Agent name and version sent to the Client.\n\nNote: in future versions of the protocol, this will be required.", + "anyOf": [ + { + "$ref": "#/$defs/Implementation" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["protocolVersion"], + "x-side": "agent", + "x-method": "initialize" + }, + "ProtocolVersion": { + "description": "Protocol version identifier.\n\nThis version is only bumped for breaking changes.\nNon-breaking changes should be introduced via capabilities.", + "type": "integer", + "format": "uint16", + "minimum": 0, + "maximum": 65535 + }, + "AgentCapabilities": { + "description": "Capabilities supported by the agent.\n\nAdvertised during initialization to inform the client about\navailable features and content types.\n\nSee protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/v1/initialization#agent-capabilities)", + "type": "object", + "properties": { + "loadSession": { + "description": "Whether the agent supports `session/load`.", + "type": "boolean", + "default": false, + "x-deserialize-default-on-error": true + }, + "promptCapabilities": { + "description": "Prompt capabilities supported by the agent.", + "x-deserialize-default-on-error": true, + "default": { + "image": false, + "audio": false, + "embeddedContext": false + }, + "allOf": [ + { + "$ref": "#/$defs/PromptCapabilities" + } + ] + }, + "mcpCapabilities": { + "description": "MCP capabilities supported by the agent.", + "x-deserialize-default-on-error": true, + "default": { + "http": false, + "sse": false + }, + "allOf": [ + { + "$ref": "#/$defs/McpCapabilities" + } + ] + }, + "sessionCapabilities": { + "description": "Session lifecycle and prompt capabilities advertised by the agent.", + "x-deserialize-default-on-error": true, + "default": {}, + "allOf": [ + { + "$ref": "#/$defs/SessionCapabilities" + } + ] + }, + "auth": { + "description": "Authentication-related capabilities supported by the agent.", + "x-deserialize-default-on-error": true, + "default": {}, + "allOf": [ + { + "$ref": "#/$defs/AgentAuthCapabilities" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "PromptCapabilities": { + "description": "Prompt capabilities supported by the agent in `session/prompt` requests.\n\nBaseline agent functionality requires support for `text`\nand `resource_link` content blocks in prompt requests.\n\nOther variants must be explicitly opted in to.\nCapabilities for different types of content in prompt requests.\n\nIndicates which content types beyond the baseline (text and resource links)\nthe agent can process.\n\nSee protocol docs: [Prompt Capabilities](https://agentclientprotocol.com/protocol/v1/initialization#prompt-capabilities)", + "type": "object", + "properties": { + "image": { + "description": "Agent supports `image` content blocks.", + "type": "boolean", + "default": false, + "x-deserialize-default-on-error": true + }, + "audio": { + "description": "Agent supports `audio` content blocks.", + "type": "boolean", + "default": false, + "x-deserialize-default-on-error": true + }, + "embeddedContext": { + "description": "Agent supports embedded context in `session/prompt` requests.\n\nWhen enabled, the Client is allowed to include `resource` content blocks\nin prompt requests for pieces of context that are referenced in the message.", + "type": "boolean", + "default": false, + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "McpCapabilities": { + "description": "MCP capabilities supported by the agent", + "type": "object", + "properties": { + "http": { + "description": "Agent supports `http` MCP servers.", + "type": "boolean", + "default": false, + "x-deserialize-default-on-error": true + }, + "sse": { + "description": "Agent supports `sse` MCP servers.", + "type": "boolean", + "default": false, + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "SessionCapabilities": { + "description": "Session capabilities supported by the agent.\n\nAs a baseline, all Agents **MUST** support `session/new`, `session/prompt`, `session/cancel`, and `session/update`.\n\nOptionally, they **MAY** support other session methods and notifications by specifying additional capabilities.\n\nNote: `session/load` is still handled by the top-level `loadSession` capability. This will be unified in future versions of the protocol.\n\nSee protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/v1/initialization#session-capabilities)", + "type": "object", + "properties": { + "list": { + "description": "Whether the agent supports `session/list`.\n\nOptional. Omitted or `null` both mean the agent does not advertise support.\nSupplying `{}` means the agent supports listing sessions.", + "anyOf": [ + { + "$ref": "#/$defs/SessionListCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "delete": { + "description": "Whether the agent supports `session/delete`.\n\nOptional. Omitted or `null` both mean the agent does not advertise support.\nSupplying `{}` means the agent supports deleting sessions from `session/list`.", + "anyOf": [ + { + "$ref": "#/$defs/SessionDeleteCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "additionalDirectories": { + "description": "Whether the agent supports `additionalDirectories` on supported session lifecycle requests.\n\nOptional. Omitted or `null` both mean the agent does not advertise support.\nSupplying `{}` means the agent supports `additionalDirectories` on\nsupported session lifecycle requests.\n\nAgents that also support `session/list` may return\n`SessionInfo.additionalDirectories` to report the complete ordered\nadditional-root list associated with a listed session.", + "anyOf": [ + { + "$ref": "#/$defs/SessionAdditionalDirectoriesCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "systemPrompt": { + "description": "Whether the agent supports `systemPrompt` on session lifecycle requests.\n\nOptional. Omitted or `null` both mean the agent does not advertise support.\nSupplying `{}` means the agent supports `systemPrompt` in `append` mode.", + "anyOf": [ + { + "$ref": "#/$defs/SessionSystemPromptCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "resume": { + "description": "Whether the agent supports `session/resume`.\n\nOptional. Omitted or `null` both mean the agent does not advertise support.\nSupplying `{}` means the agent supports resuming sessions.", + "anyOf": [ + { + "$ref": "#/$defs/SessionResumeCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "close": { + "description": "Whether the agent supports `session/close`.\n\nOptional. Omitted or `null` both mean the agent does not advertise support.\nSupplying `{}` means the agent supports closing sessions.", + "anyOf": [ + { + "$ref": "#/$defs/SessionCloseCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "SessionListCapabilities": { + "description": "Capabilities for the `session/list` method.\n\nSupplying `{}` means the agent supports listing sessions.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "SessionDeleteCapabilities": { + "description": "Capabilities for the `session/delete` method.\n\nSupplying `{}` means the agent supports deleting sessions from `session/list`.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "SessionAdditionalDirectoriesCapabilities": { + "description": "Capabilities for additional session directories support.\n\nSupplying `{}` means the agent supports the `additionalDirectories` field on\nsupported session lifecycle requests. Agents that also support\n`session/list` may return `SessionInfo.additionalDirectories` to report the\ncomplete ordered additional-root list associated with a listed session.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "SessionSystemPromptCapabilities": { + "description": "Capabilities for client-provided system prompts.\n\nSupplying `{}` means the agent supports `systemPrompt` on session lifecycle\nrequests in `append` mode.", + "type": "object", + "properties": { + "mode": { + "description": "Delivery modes the agent supports in addition to `append`.\n\nOptional. Omitted or `null` both mean the agent supports only `append`.", + "anyOf": [ + { + "$ref": "#/$defs/SessionSystemPromptModeCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "SessionSystemPromptModeCapabilities": { + "description": "System prompt delivery modes the agent supports in addition to `append`.\n\n`append` has no entry because every agent advertising\n`sessionCapabilities.systemPrompt` supports it.", + "type": "object", + "properties": { + "override": { + "description": "Whether the agent supports `override` mode.\n\nOptional. Omitted or `null` both mean the agent does not advertise support.\nSupplying `{}` means the agent supports replacing its built-in default\ninstructions with the client-provided system prompt.", + "anyOf": [ + { + "$ref": "#/$defs/SessionSystemPromptOverrideCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "SessionSystemPromptOverrideCapabilities": { + "description": "Capabilities for the `override` system prompt mode.\n\nSupplying `{}` means the agent supports replacing its built-in default\ninstructions with the client-provided system prompt.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "SessionResumeCapabilities": { + "description": "Capabilities for the `session/resume` method.\n\nSupplying `{}` means the agent supports resuming sessions.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "SessionCloseCapabilities": { + "description": "Capabilities for the `session/close` method.\n\nSupplying `{}` means the agent supports closing sessions.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "AgentAuthCapabilities": { + "description": "Authentication-related capabilities supported by the agent.", + "type": "object", + "properties": { + "logout": { + "description": "Whether the agent supports the logout method.\n\nOptional. Omitted or `null` both mean the agent does not advertise support.\nSupplying `{}` means the agent supports the logout method.", + "anyOf": [ + { + "$ref": "#/$defs/LogoutCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "LogoutCapabilities": { + "description": "Logout capabilities supported by the agent.\n\nSupplying `{}` means the agent supports the logout method.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "AuthMethod": { + "description": "Describes an available authentication method.\n\nThe `type` field acts as the discriminator in the serialized JSON form.\nWhen no `type` is present, the method is treated as `agent`.", + "anyOf": [ + { + "description": "Client runs the configured agent program as a separate interactive\nprocess, without passing this method to `authenticate`.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "terminal" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/AuthMethodTerminal" + } + ] + }, + { + "title": "agent", + "description": "Agent handles authentication itself through `authenticate`.\n\nThis is the default when no `type` is specified.", + "allOf": [ + { + "$ref": "#/$defs/AuthMethodAgent" + } + ] + } + ] + }, + "AuthMethodId": { + "description": "Typed identifier used for auth method values on the wire.", + "type": "string" + }, + "AuthMethodTerminal": { + "description": "Terminal-based authentication method.\n\nThe client runs the configured agent program as a separate interactive\nprocess for the user to authenticate via a TUI. Agents MUST advertise this\nmethod only when the client enabled its terminal authentication capability.\nA zero exit status signals success. Any other termination signals failure.\nThe client MUST NOT pass this method to `authenticate`.", + "type": "object", + "properties": { + "id": { + "description": "Unique identifier for this authentication method.", + "allOf": [ + { + "$ref": "#/$defs/AuthMethodId" + } + ] + }, + "name": { + "description": "Human-readable name of the authentication method.", + "type": "string" + }, + "description": { + "description": "Optional human-readable description of this authentication method.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "args": { + "description": "Additional arguments to append to the configured agent invocation for terminal auth.", + "type": "array", + "items": { + "type": "string" + }, + "x-deserialize-default-on-null": true + }, + "env": { + "description": "Additional environment variables to set on the configured agent invocation for terminal auth.\nThese values override same-named variables in the base launch configuration.", + "type": "object", + "x-deserialize-default-on-null": true, + "additionalProperties": { + "type": "string" + } + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["id", "name"] + }, + "AuthMethodAgent": { + "description": "Agent handles authentication itself through `authenticate`.\n\nThis is the default authentication method type.", + "type": "object", + "properties": { + "id": { + "description": "Unique identifier for this authentication method.", + "allOf": [ + { + "$ref": "#/$defs/AuthMethodId" + } + ] + }, + "name": { + "description": "Human-readable name of the authentication method.", + "type": "string" + }, + "description": { + "description": "Optional human-readable description of this authentication method.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["id", "name"] + }, + "Implementation": { + "description": "Metadata about the implementation of the client or agent.\nDescribes the name and version of an ACP implementation, with an optional\ntitle for UI representation.", + "type": "object", + "properties": { + "name": { + "description": "Intended for programmatic or logical use, but can be used as a display\nname fallback if title isn't present.", + "type": "string" + }, + "title": { + "description": "Intended for UI and end-user contexts and optimized to be human-readable\nand easily understood.\n\nIf not provided, the name should be used for display.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "version": { + "description": "Version of the implementation. Can be displayed to the user or used\nfor debugging or metrics purposes. (e.g. \"1.0.0\").", + "type": "string" + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["name", "version"] + }, + "AuthenticateResponse": { + "description": "Response to the `authenticate` method.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "x-side": "agent", + "x-method": "authenticate" + }, + "LogoutResponse": { + "description": "Response to the `logout` method.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "x-side": "agent", + "x-method": "logout" + }, + "NewSessionResponse": { + "description": "Response from creating a new session.\n\nSee protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v1/session-setup#creating-a-session)", + "type": "object", + "properties": { + "sessionId": { + "description": "Unique identifier for the created session.\n\nUsed in all subsequent requests for this conversation.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "modes": { + "description": "Initial mode state if supported by the Agent\n\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)", + "anyOf": [ + { + "$ref": "#/$defs/SessionModeState" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "configOptions": { + "description": "Initial session configuration options if supported by the Agent.", + "type": ["array", "null"], + "items": { + "$ref": "#/$defs/SessionConfigOption" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId"], + "x-side": "agent", + "x-method": "session/new" + }, + "SessionModeState": { + "description": "The set of modes and the one currently active.", + "type": "object", + "properties": { + "currentModeId": { + "description": "The current mode the Agent is in.", + "allOf": [ + { + "$ref": "#/$defs/SessionModeId" + } + ] + }, + "availableModes": { + "description": "The set of modes that the Agent can operate in", + "type": "array", + "items": { + "$ref": "#/$defs/SessionMode" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["currentModeId", "availableModes"] + }, + "SessionModeId": { + "description": "Unique identifier for a Session Mode.", + "type": "string" + }, + "SessionMode": { + "description": "A mode the agent can operate in.\n\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)", + "type": "object", + "properties": { + "id": { + "description": "Stable identifier used to refer to this protocol object in later messages.", + "allOf": [ + { + "$ref": "#/$defs/SessionModeId" + } + ] + }, + "name": { + "description": "Human-readable name shown for this protocol object.", + "type": "string" + }, + "description": { + "description": "Optional human-readable details shown with this protocol object.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["id", "name"] + }, + "SessionConfigOption": { + "description": "A session configuration option selector and its current state.", + "type": "object", + "properties": { + "id": { + "description": "Unique identifier for the configuration option.", + "allOf": [ + { + "$ref": "#/$defs/SessionConfigId" + } + ] + }, + "name": { + "description": "Human-readable label for the option.", + "type": "string" + }, + "description": { + "description": "Optional description for the Client to display to the user.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "category": { + "description": "Optional semantic category for this option (UX only).", + "anyOf": [ + { + "$ref": "#/$defs/SessionConfigOptionCategory" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["id", "name"], + "oneOf": [ + { + "description": "Single-value selector (dropdown).", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "select" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/SessionConfigSelect" + } + ] + }, + { + "description": "Boolean on/off toggle.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "boolean" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/SessionConfigBoolean" + } + ] + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "SessionConfigId": { + "description": "Unique identifier for a session configuration option.", + "type": "string" + }, + "SessionConfigOptionCategory": { + "description": "Semantic category for a session configuration option.\n\nThis is intended to help Clients distinguish broadly common selectors (e.g. model selector vs\nsession mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,\nplacement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown\ncategories gracefully.\n\nCategory names beginning with `_` are free for custom use, like other ACP extension methods.\nCategory names that do not begin with `_` are reserved for the ACP spec.", + "anyOf": [ + { + "description": "Session mode selector.", + "type": "string", + "const": "mode" + }, + { + "description": "Model selector.", + "type": "string", + "const": "model" + }, + { + "description": "Model-related configuration parameter.", + "type": "string", + "const": "model_config" + }, + { + "description": "Thought/reasoning level selector.", + "type": "string", + "const": "thought_level" + }, + { + "title": "other", + "description": "Unknown / uncategorized selector.", + "type": "string" + } + ] + }, + "SessionConfigValueId": { + "description": "Unique identifier for a session configuration option value.", + "type": "string" + }, + "SessionConfigSelectOptions": { + "description": "Possible values for a session configuration option.", + "anyOf": [ + { + "title": "Ungrouped", + "description": "A flat list of options with no grouping.", + "type": "array", + "items": { + "$ref": "#/$defs/SessionConfigSelectOption" + } + }, + { + "title": "Grouped", + "description": "A list of options grouped under headers.", + "type": "array", + "items": { + "$ref": "#/$defs/SessionConfigSelectGroup" + } + } + ] + }, + "SessionConfigSelectOption": { + "description": "A possible value for a session configuration option.", + "type": "object", + "properties": { + "value": { + "description": "Unique identifier for this option value.", + "allOf": [ + { + "$ref": "#/$defs/SessionConfigValueId" + } + ] + }, + "name": { + "description": "Human-readable label for this option value.", + "type": "string" + }, + "description": { + "description": "Optional description for this option value.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["value", "name"] + }, + "SessionConfigSelectGroup": { + "description": "A group of possible values for a session configuration option.", + "type": "object", + "properties": { + "group": { + "description": "Unique identifier for this group.", + "allOf": [ + { + "$ref": "#/$defs/SessionConfigGroupId" + } + ] + }, + "name": { + "description": "Human-readable label for this group.", + "type": "string" + }, + "options": { + "description": "The set of option values in this group.", + "type": "array", + "items": { + "$ref": "#/$defs/SessionConfigSelectOption" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["group", "name", "options"] + }, + "SessionConfigGroupId": { + "description": "Unique identifier for a session configuration option value group.", + "type": "string" + }, + "SessionConfigSelect": { + "description": "A single-value selector (dropdown) session configuration option payload.", + "type": "object", + "properties": { + "currentValue": { + "description": "The currently selected value.", + "allOf": [ + { + "$ref": "#/$defs/SessionConfigValueId" + } + ] + }, + "options": { + "description": "The set of selectable options.", + "allOf": [ + { + "$ref": "#/$defs/SessionConfigSelectOptions" + } + ] + } + }, + "required": ["currentValue", "options"] + }, + "SessionConfigBoolean": { + "description": "A boolean on/off toggle session configuration option payload.", + "type": "object", + "properties": { + "currentValue": { + "description": "The current value of the boolean option.", + "type": "boolean" + } + }, + "required": ["currentValue"] + }, + "LoadSessionResponse": { + "description": "Response from loading an existing session.", + "type": "object", + "properties": { + "modes": { + "description": "Initial mode state if supported by the Agent\n\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)", + "anyOf": [ + { + "$ref": "#/$defs/SessionModeState" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "configOptions": { + "description": "Initial session configuration options if supported by the Agent.", + "type": ["array", "null"], + "items": { + "$ref": "#/$defs/SessionConfigOption" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "x-side": "agent", + "x-method": "session/load" + }, + "ListSessionsResponse": { + "description": "Response from listing sessions.", + "type": "object", + "properties": { + "sessions": { + "description": "Array of session information objects", + "type": "array", + "items": { + "$ref": "#/$defs/SessionInfo" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "nextCursor": { + "description": "Opaque cursor token. If present, pass this in the next request's cursor parameter\nto fetch the next page. If absent, there are no more results.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessions"], + "x-side": "agent", + "x-method": "session/list" + }, + "SessionInfo": { + "description": "Information about a session returned by session/list", + "type": "object", + "properties": { + "sessionId": { + "description": "Unique identifier for the session", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "cwd": { + "description": "The working directory for this session. Must be an absolute path.", + "type": "string" + }, + "additionalDirectories": { + "description": "Additional workspace roots reported for this session. Each path must be absolute.\n\nWhen present, this is the complete ordered additional-root list reported\nby the Agent. Omitted and empty values are equivalent: the response\nreports no additional roots.", + "type": "array", + "items": { + "type": "string" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "title": { + "description": "Human-readable title for the session", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "updatedAt": { + "description": "ISO 8601 timestamp of last activity", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId", "cwd"] + }, + "DeleteSessionResponse": { + "description": "Response from deleting a session.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "x-side": "agent", + "x-method": "session/delete" + }, + "ResumeSessionResponse": { + "description": "Response from resuming an existing session.", + "type": "object", + "properties": { + "modes": { + "description": "Initial mode state if supported by the Agent\n\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)", + "anyOf": [ + { + "$ref": "#/$defs/SessionModeState" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "configOptions": { + "description": "Initial session configuration options if supported by the Agent.", + "type": ["array", "null"], + "items": { + "$ref": "#/$defs/SessionConfigOption" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "x-side": "agent", + "x-method": "session/resume" + }, + "CloseSessionResponse": { + "description": "Response from closing a session.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "x-side": "agent", + "x-method": "session/close" + }, + "SetSessionModeResponse": { + "description": "Response to `session/set_mode` method.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "x-side": "agent", + "x-method": "session/set_mode" + }, + "SetSessionConfigOptionResponse": { + "description": "Response to `session/set_config_option` method.", + "type": "object", + "properties": { + "configOptions": { + "description": "The full set of configuration options and their current values.", + "type": "array", + "items": { + "$ref": "#/$defs/SessionConfigOption" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["configOptions"], + "x-side": "agent", + "x-method": "session/set_config_option" + }, + "PromptResponse": { + "description": "Response from processing a user prompt.\n\nSee protocol docs: [Check for Completion](https://agentclientprotocol.com/protocol/v1/prompt-turn#4-check-for-completion)", + "type": "object", + "properties": { + "stopReason": { + "description": "Indicates why the agent stopped processing the turn.", + "allOf": [ + { + "$ref": "#/$defs/StopReason" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["stopReason"], + "x-side": "agent", + "x-method": "session/prompt" + }, + "StopReason": { + "description": "Reasons why an agent stops processing a prompt turn.\n\nSee protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/v1/prompt-turn#stop-reasons)", + "oneOf": [ + { + "description": "The turn ended successfully.", + "type": "string", + "const": "end_turn" + }, + { + "description": "The turn ended because the agent reached the maximum number of tokens.", + "type": "string", + "const": "max_tokens" + }, + { + "description": "The turn ended because the agent reached the maximum number of allowed\nagent requests between user turns.", + "type": "string", + "const": "max_turn_requests" + }, + { + "description": "The turn ended because the agent refused to continue. The user prompt\nand everything that comes after it won't be included in the next\nprompt, so this should be reflected in the UI.", + "type": "string", + "const": "refusal" + }, + { + "description": "The turn was cancelled by the client via `session/cancel`.\n\nThis stop reason MUST be returned when the client sends a `session/cancel`\nnotification, even if the cancellation causes exceptions in underlying operations.\nAgents should catch these exceptions and return this semantically meaningful\nresponse to confirm successful cancellation.", + "type": "string", + "const": "cancelled" + } + ] + }, + "ExtResponse": { + "description": "Allows for sending an arbitrary response to an extension request that is not part of the ACP spec.\nExtension methods provide a way to add custom functionality while maintaining\nprotocol compatibility.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)" + }, + "Error": { + "description": "JSON-RPC error object.\n\nRepresents an error that occurred during method execution, following the\nJSON-RPC 2.0 error object specification with optional additional data.\n\nSee protocol docs: [JSON-RPC Error Object](https://www.jsonrpc.org/specification#error_object)", + "type": "object", + "properties": { + "code": { + "description": "A number indicating the error type that occurred.\nThis must be an integer as defined in the JSON-RPC specification.", + "allOf": [ + { + "$ref": "#/$defs/ErrorCode" + } + ] + }, + "message": { + "description": "A string providing a short description of the error.\nThe message should be limited to a concise single sentence.", + "type": "string" + }, + "data": { + "description": "Optional primitive or structured value that contains additional information about the error.\nThis may include debugging information or context-specific details.", + "x-deserialize-default-on-error": true + } + }, + "required": ["code", "message"] + }, + "ErrorCode": { + "description": "Predefined error codes for common JSON-RPC and ACP-specific errors.\n\nStandard errors use the JSON-RPC 2.0 codes. ACP-specific errors use the JSON-RPC\nserver-error range (-32000 to -32099), and request cancellation uses -32800 from the\nrange LSP reserves (-32899 to -32800).", + "anyOf": [ + { + "title": "Parse error", + "description": "**Parse error**: Invalid JSON was received by the server.\nAn error occurred on the server while parsing the JSON text.", + "type": "integer", + "format": "int32", + "const": -32700 + }, + { + "title": "Invalid request", + "description": "**Invalid request**: The JSON sent is not a valid Request object.", + "type": "integer", + "format": "int32", + "const": -32600 + }, + { + "title": "Method not found", + "description": "**Method not found**: The method does not exist or is not available.", + "type": "integer", + "format": "int32", + "const": -32601 + }, + { + "title": "Invalid params", + "description": "**Invalid params**: Invalid method parameter(s).", + "type": "integer", + "format": "int32", + "const": -32602 + }, + { + "title": "Internal error", + "description": "**Internal error**: Internal JSON-RPC error.", + "type": "integer", + "format": "int32", + "const": -32603 + }, + { + "title": "Request cancelled", + "description": "**Request cancelled**: Execution of the method was aborted either due to a cancellation request from the caller or\nbecause of resource constraints or shutdown.", + "type": "integer", + "format": "int32", + "const": -32800 + }, + { + "title": "Authentication required", + "description": "**Authentication required**: Authentication is required before this operation can be performed.", + "type": "integer", + "format": "int32", + "const": -32000 + }, + { + "title": "Resource not found", + "description": "**Resource not found**: A given resource, such as a session or file, was not found.", + "type": "integer", + "format": "int32", + "const": -32002 + }, + { + "title": "Other", + "description": "Other undefined error code.", + "type": "integer", + "format": "int32" + } + ] + }, + "AgentNotification": { + "description": "A JSON-RPC notification object.", + "type": "object", + "properties": { + "method": { + "description": "The notification method name.", + "type": "string" + }, + "params": { + "description": "Method-specific notification parameters.", + "anyOf": [ + { + "description": "All possible notifications that an agent can send to a client.\n\nThis enum is used internally for routing RPC notifications. You typically won't need\nto use this directly.\n\nNotifications do not expect a response.", + "anyOf": [ + { + "title": "SessionNotification", + "description": "Handles session update notifications from the agent.\n\nThis is a notification endpoint (no response expected) that receives\nreal-time updates about session progress, including message chunks,\ntool calls, and execution plans.\n\nNote: Clients SHOULD continue accepting tool call updates even after\nsending a `session/cancel` notification, as the agent may send final\nupdates before responding with the cancelled stop reason.\n\nSee protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/v1/prompt-turn#3-agent-reports-output)", + "allOf": [ + { + "$ref": "#/$defs/SessionNotification" + } + ] + }, + { + "title": "CompleteElicitationNotification", + "description": "Notification that a URL-based elicitation has completed.\n\nSee protocol docs: [Elicitation](https://agentclientprotocol.com/protocol/v1/elicitation#url-completion)", + "allOf": [ + { + "$ref": "#/$defs/CompleteElicitationNotification" + } + ] + }, + { + "title": "ExtNotification", + "description": "Handles extension notifications from the agent.\n\nAllows the Agent to send an arbitrary notification that is not part of the ACP spec.\nExtension notifications provide a way to send one-way messages for custom functionality\nwhile maintaining protocol compatibility.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "allOf": [ + { + "$ref": "#/$defs/ExtNotification" + } + ] + } + ] + }, + { + "type": "null" + } + ] + } + }, + "required": ["method"], + "x-docs-ignore": true + }, + "SessionNotification": { + "description": "Notification containing a session update from the agent.\n\nUsed to stream real-time progress and results during prompt processing.\n\nSee protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/v1/prompt-turn#3-agent-reports-output)", + "type": "object", + "properties": { + "sessionId": { + "description": "The ID of the session this update pertains to.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "update": { + "description": "The actual update content.", + "allOf": [ + { + "$ref": "#/$defs/SessionUpdate" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId", "update"], + "x-side": "client", + "x-method": "session/update" + }, + "SessionUpdate": { + "description": "Different types of updates that can be sent during session processing.\n\nThese updates provide real-time feedback about the agent's progress.\n\nSee protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/v1/prompt-turn#3-agent-reports-output)", + "oneOf": [ + { + "description": "A chunk of the user's message being streamed.", + "type": "object", + "properties": { + "sessionUpdate": { + "type": "string", + "const": "user_message_chunk" + } + }, + "required": ["sessionUpdate"], + "allOf": [ + { + "$ref": "#/$defs/ContentChunk" + } + ] + }, + { + "description": "A chunk of the agent's response being streamed.", + "type": "object", + "properties": { + "sessionUpdate": { + "type": "string", + "const": "agent_message_chunk" + } + }, + "required": ["sessionUpdate"], + "allOf": [ + { + "$ref": "#/$defs/ContentChunk" + } + ] + }, + { + "description": "A chunk of the agent's internal reasoning being streamed.", + "type": "object", + "properties": { + "sessionUpdate": { + "type": "string", + "const": "agent_thought_chunk" + } + }, + "required": ["sessionUpdate"], + "allOf": [ + { + "$ref": "#/$defs/ContentChunk" + } + ] + }, + { + "description": "Notification that a new tool call has been initiated.", + "type": "object", + "properties": { + "sessionUpdate": { + "type": "string", + "const": "tool_call" + } + }, + "required": ["sessionUpdate"], + "allOf": [ + { + "$ref": "#/$defs/ToolCall" + } + ] + }, + { + "description": "Update on the status or results of a tool call.", + "type": "object", + "properties": { + "sessionUpdate": { + "type": "string", + "const": "tool_call_update" + } + }, + "required": ["sessionUpdate"], + "allOf": [ + { + "$ref": "#/$defs/ToolCallUpdate" + } + ] + }, + { + "description": "The agent's execution plan for complex tasks.\nSee protocol docs: [Agent Plan](https://agentclientprotocol.com/protocol/v1/agent-plan)", + "type": "object", + "properties": { + "sessionUpdate": { + "type": "string", + "const": "plan" + } + }, + "required": ["sessionUpdate"], + "allOf": [ + { + "$ref": "#/$defs/Plan" + } + ] + }, + { + "description": "Available commands are ready or have changed", + "type": "object", + "properties": { + "sessionUpdate": { + "type": "string", + "const": "available_commands_update" + } + }, + "required": ["sessionUpdate"], + "allOf": [ + { + "$ref": "#/$defs/AvailableCommandsUpdate" + } + ] + }, + { + "description": "The current mode of the session has changed\n\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)", + "type": "object", + "properties": { + "sessionUpdate": { + "type": "string", + "const": "current_mode_update" + } + }, + "required": ["sessionUpdate"], + "allOf": [ + { + "$ref": "#/$defs/CurrentModeUpdate" + } + ] + }, + { + "description": "Session configuration options have been updated.", + "type": "object", + "properties": { + "sessionUpdate": { + "type": "string", + "const": "config_option_update" + } + }, + "required": ["sessionUpdate"], + "allOf": [ + { + "$ref": "#/$defs/ConfigOptionUpdate" + } + ] + }, + { + "description": "Session metadata has been updated (title, timestamps, custom metadata)", + "type": "object", + "properties": { + "sessionUpdate": { + "type": "string", + "const": "session_info_update" + } + }, + "required": ["sessionUpdate"], + "allOf": [ + { + "$ref": "#/$defs/SessionInfoUpdate" + } + ] + }, + { + "description": "Context window and cost update for the session.", + "type": "object", + "properties": { + "sessionUpdate": { + "type": "string", + "const": "usage_update" + } + }, + "required": ["sessionUpdate"], + "allOf": [ + { + "$ref": "#/$defs/UsageUpdate" + } + ] + }, + { + "description": "Information for the user that is not part of session history.\n\nAgents MUST only send this update when the Client advertised\nthe `session.notices` Client capability.", + "type": "object", + "properties": { + "sessionUpdate": { + "type": "string", + "const": "notice" + } + }, + "required": ["sessionUpdate"], + "allOf": [ + { + "$ref": "#/$defs/Notice" + } + ] + }, + { + "description": "A context compaction has been created or updated.\n\nAgents MUST only send this update when the Client advertised\nthe `session.compaction` Client capability.", + "type": "object", + "properties": { + "sessionUpdate": { + "type": "string", + "const": "compaction_update" + } + }, + "required": ["sessionUpdate"], + "allOf": [ + { + "$ref": "#/$defs/CompactionUpdate" + } + ] + }, + { + "description": "A content block appended to a context compaction's retained summary.\n\nAgents MUST only send this update when the Client advertised\nthe `session.compaction` Client capability.", + "type": "object", + "properties": { + "sessionUpdate": { + "type": "string", + "const": "compaction_summary_chunk" + } + }, + "required": ["sessionUpdate"], + "allOf": [ + { + "$ref": "#/$defs/CompactionSummaryChunk" + } + ] + } + ], + "discriminator": { + "propertyName": "sessionUpdate" + } + }, + "MessageId": { + "description": "Unique identifier for a message within a session.", + "type": "string" + }, + "ContentChunk": { + "description": "A streamed item of content", + "type": "object", + "properties": { + "content": { + "description": "A single item of content", + "allOf": [ + { + "$ref": "#/$defs/ContentBlock" + } + ] + }, + "messageId": { + "description": "A unique identifier for the message this chunk belongs to.\n\nAll chunks belonging to the same message share the same `messageId`.\nA change in `messageId` indicates a new message has started.", + "anyOf": [ + { + "$ref": "#/$defs/MessageId" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["content"] + }, + "ToolCall": { + "description": "Represents a tool call that the language model has requested.\n\nTool calls are actions that the agent executes on behalf of the language model,\nsuch as reading files, executing code, or fetching data from external sources.\n\nSee protocol docs: [Tool Calls](https://agentclientprotocol.com/protocol/v1/tool-calls)", + "type": "object", + "properties": { + "toolCallId": { + "description": "Unique identifier for this tool call within the session.", + "allOf": [ + { + "$ref": "#/$defs/ToolCallId" + } + ] + }, + "title": { + "description": "Human-readable title describing what the tool is doing.", + "type": "string" + }, + "name": { + "description": "Programmatic name of the tool being invoked.\n\nThis field is optional. Omitting it or sending `null` both mean that no\ntool name is available.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "kind": { + "description": "The category of tool being invoked.\nHelps clients choose appropriate icons and UI treatment.", + "x-deserialize-default-on-error": true, + "allOf": [ + { + "$ref": "#/$defs/ToolKind" + } + ] + }, + "status": { + "description": "Current execution status of the tool call.", + "x-deserialize-default-on-error": true, + "allOf": [ + { + "$ref": "#/$defs/ToolCallStatus" + } + ] + }, + "content": { + "description": "Content produced by the tool call.", + "type": "array", + "items": { + "$ref": "#/$defs/ToolCallContent" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "locations": { + "description": "File locations affected by this tool call.\nEnables \"follow-along\" features in clients.", + "type": "array", + "items": { + "$ref": "#/$defs/ToolCallLocation" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "rawInput": { + "description": "Raw input parameters sent to the tool.", + "x-deserialize-default-on-error": true + }, + "rawOutput": { + "description": "Raw output returned by the tool.", + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["toolCallId", "title"] + }, + "PlanEntry": { + "description": "A single entry in the execution plan.\n\nRepresents a task or goal that the assistant intends to accomplish\nas part of fulfilling the user's request.\nSee protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/v1/agent-plan#plan-entries)", + "type": "object", + "properties": { + "content": { + "description": "Human-readable description of what this task aims to accomplish.", + "type": "string" + }, + "priority": { + "description": "The relative importance of this task.\nUsed to indicate which tasks are most critical to the overall goal.", + "allOf": [ + { + "$ref": "#/$defs/PlanEntryPriority" + } + ] + }, + "status": { + "description": "Current execution status of this task.", + "allOf": [ + { + "$ref": "#/$defs/PlanEntryStatus" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["content", "priority", "status"] + }, + "PlanEntryPriority": { + "description": "Priority levels for plan entries.\n\nUsed to indicate the relative importance or urgency of different\ntasks in the execution plan.\nSee protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/v1/agent-plan#plan-entries)", + "oneOf": [ + { + "description": "High priority task - critical to the overall goal.", + "type": "string", + "const": "high" + }, + { + "description": "Medium priority task - important but not critical.", + "type": "string", + "const": "medium" + }, + { + "description": "Low priority task - nice to have but not essential.", + "type": "string", + "const": "low" + } + ] + }, + "PlanEntryStatus": { + "description": "Status of a plan entry in the execution flow.\n\nTracks the lifecycle of each task from planning through completion.\nSee protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/v1/agent-plan#plan-entries)", + "oneOf": [ + { + "description": "The task has not started yet.", + "type": "string", + "const": "pending" + }, + { + "description": "The task is currently being worked on.", + "type": "string", + "const": "in_progress" + }, + { + "description": "The task has been successfully completed.", + "type": "string", + "const": "completed" + } + ] + }, + "Plan": { + "description": "An execution plan for accomplishing complex tasks.\n\nPlans consist of multiple entries representing individual tasks or goals.\nAgents report plans to clients to provide visibility into their execution strategy.\nPlans can evolve during execution as the agent discovers new requirements or completes tasks.\n\nSee protocol docs: [Agent Plan](https://agentclientprotocol.com/protocol/v1/agent-plan)", + "type": "object", + "properties": { + "entries": { + "description": "The list of tasks to be accomplished.\n\nWhen updating a plan, the agent must send a complete list of all entries\nwith their current status. The client replaces the entire plan with each update.", + "type": "array", + "items": { + "$ref": "#/$defs/PlanEntry" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["entries"] + }, + "AvailableCommand": { + "description": "Information about a command.", + "type": "object", + "properties": { + "name": { + "description": "Command name (e.g., `create_plan`, `research_codebase`).", + "type": "string" + }, + "description": { + "description": "Human-readable description of what the command does.", + "type": "string" + }, + "input": { + "description": "Input for the command if required", + "anyOf": [ + { + "$ref": "#/$defs/AvailableCommandInput" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["name", "description"] + }, + "AvailableCommandInput": { + "description": "The input specification for a command.", + "anyOf": [ + { + "title": "unstructured", + "description": "All text that was typed after the command name is provided as input.", + "allOf": [ + { + "$ref": "#/$defs/UnstructuredCommandInput" + } + ] + } + ] + }, + "UnstructuredCommandInput": { + "description": "All text that was typed after the command name is provided as input.", + "type": "object", + "properties": { + "hint": { + "description": "A hint to display when the input hasn't been provided yet", + "type": "string" + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["hint"] + }, + "AvailableCommandsUpdate": { + "description": "Available commands are ready or have changed", + "type": "object", + "properties": { + "availableCommands": { + "description": "Commands the agent can execute", + "type": "array", + "items": { + "$ref": "#/$defs/AvailableCommand" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["availableCommands"] + }, + "CurrentModeUpdate": { + "description": "The current mode of the session has changed\n\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)", + "type": "object", + "properties": { + "currentModeId": { + "description": "The ID of the current mode", + "allOf": [ + { + "$ref": "#/$defs/SessionModeId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["currentModeId"] + }, + "ConfigOptionUpdate": { + "description": "Session configuration options have been updated.", + "type": "object", + "properties": { + "configOptions": { + "description": "The full set of configuration options and their current values.", + "type": "array", + "items": { + "$ref": "#/$defs/SessionConfigOption" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["configOptions"] + }, + "SessionInfoUpdate": { + "description": "Update to session metadata. All fields are optional to support partial updates.\n\nAgents send this notification to update session information like title or custom metadata.\nClients can use it to keep session titles and state current.", + "type": "object", + "properties": { + "title": { + "description": "Human-readable title for the session. Set to null to clear.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "updatedAt": { + "description": "ISO 8601 timestamp of last activity. Set to null to clear.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "Cost": { + "description": "Cost information for a session.", + "type": "object", + "properties": { + "amount": { + "description": "Total cumulative cost for session.", + "type": "number", + "format": "double" + }, + "currency": { + "description": "Unit of `amount`: an ISO 4217 currency code (e.g., \"USD\", \"EUR\") for money, or another\nunit such as \"credits\".", + "type": "string" + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["amount", "currency"] + }, + "UsageUpdate": { + "description": "Context window and cost update for a session.", + "type": "object", + "properties": { + "used": { + "description": "Tokens currently in context.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "size": { + "description": "Total context window size in tokens.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "cost": { + "description": "Cumulative session cost (optional).", + "anyOf": [ + { + "$ref": "#/$defs/Cost" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["used", "size"] + }, + "NoticeSeverity": { + "description": "Severity hint for a session notice.", + "anyOf": [ + { + "description": "Informational notice.", + "type": "string", + "const": "info" + }, + { + "description": "Warning notice.", + "type": "string", + "const": "warning" + }, + { + "description": "Error notice.", + "type": "string", + "const": "error" + }, + { + "title": "other", + "description": "Custom or future notice severity.\n\nValues beginning with `_` are reserved for implementation-specific\nextensions. Other unknown values are reserved for future ACP severities.", + "type": "string" + } + ] + }, + "Notice": { + "description": "Fire-and-forget information for the user.\n\nNotices are live events rather than session history. Agents must not rely on\na notice being received, displayed, or seen by the user.\nAgents MUST only send notices when the Client advertised\nthe `session.notices` Client capability. Otherwise, Agents may use an agent\nmessage when the information should still be surfaced to the user.\n\nSee RFD: [Session Notices](https://agentclientprotocol.com/rfds/session-notices)", + "type": "object", + "properties": { + "severity": { + "description": "Presentation severity hint.", + "allOf": [ + { + "$ref": "#/$defs/NoticeSeverity" + } + ] + }, + "title": { + "description": "Required non-empty plain-text title that can stand alone.", + "type": "string", + "minLength": 1 + }, + "description": { + "description": "Optional plain-text detail or guidance.\n\nOmitted and `null` are equivalent and mean no description was supplied.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "Metadata scoped to this notice.\n\nOmitted and `null` are equivalent and mean no metadata was supplied.", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["severity", "title"] + }, + "CompactionId": { + "description": "Unique identifier for a context compaction within a session.", + "type": "string" + }, + "CompactionStatus": { + "description": "Lifecycle state of a context compaction.", + "anyOf": [ + { + "description": "Compaction has started and has not finished.", + "type": "string", + "const": "in_progress" + }, + { + "description": "Compaction finished successfully.", + "type": "string", + "const": "completed" + }, + { + "description": "Compaction finished unsuccessfully.", + "type": "string", + "const": "failed" + }, + { + "description": "Compaction was cancelled before it finished.", + "type": "string", + "const": "cancelled" + }, + { + "title": "other", + "description": "Custom or future compaction status.\n\nValues beginning with `_` are reserved for implementation-specific\nextensions. Other unknown values are reserved for future ACP statuses.", + "type": "string" + } + ] + }, + "CompactionUpdate": { + "description": "A context compaction upsert. The first notification fixes the compaction's\ntimeline position. Later updates with the same ID patch that entity in place.\nAgents MUST only send this update when the Client advertised\nthe `session.compaction` Client capability.\n\n`summary`, `error`, and `_meta` have patch semantics: omission leaves the\nstored value unchanged, `null` clears it, and a concrete value replaces it.\n`summary: []` also clears the summary.", + "type": "object", + "properties": { + "compactionId": { + "description": "The Agent-owned ID of this compaction, unique within the session.", + "allOf": [ + { + "$ref": "#/$defs/CompactionId" + } + ] + }, + "status": { + "description": "Current lifecycle status.", + "allOf": [ + { + "$ref": "#/$defs/CompactionStatus" + } + ] + }, + "summary": { + "description": "Complete replacement user-displayable summary content for the compaction.", + "type": ["array", "null"], + "items": { + "$ref": "#/$defs/ContentBlock" + }, + "x-deserialize-default-on-error": true, + "x-deserialize-skip-invalid-items": true + }, + "error": { + "description": "Human-readable error details for the compaction.", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "Extensible metadata patch for this compaction.", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["compactionId", "status"] + }, + "CompactionSummaryChunk": { + "description": "A content block appended to a compaction's summary. A first-seen ID creates\nan in-progress compaction. Chunks append in receive order.\nAgents MUST only send this update when the Client advertised\nthe `session.compaction` Client capability.", + "type": "object", + "properties": { + "compactionId": { + "description": "ID of the compaction whose summary receives this content.", + "allOf": [ + { + "$ref": "#/$defs/CompactionId" + } + ] + }, + "content": { + "description": "One content block to append.", + "allOf": [ + { + "$ref": "#/$defs/ContentBlock" + } + ] + }, + "_meta": { + "description": "Metadata scoped to this chunk. Omission and `null` both mean absent.", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["compactionId", "content"] + }, + "CompleteElicitationNotification": { + "description": "Notification sent by the agent when a URL-based elicitation is complete.", + "type": "object", + "properties": { + "elicitationId": { + "description": "The ID of the elicitation that completed.", + "allOf": [ + { + "$ref": "#/$defs/ElicitationId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["elicitationId"], + "x-side": "client", + "x-method": "elicitation/complete" + }, + "ExtNotification": { + "description": "Allows either side to send an arbitrary notification that is not part of the ACP spec.\nExtension notifications provide a way to send one-way messages for custom functionality\nwhile maintaining protocol compatibility.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)" + }, + "ClientRequest": { + "description": "A JSON-RPC request object.", + "type": "object", + "properties": { + "id": { + "description": "The request id used to correlate the matching response.", + "allOf": [ + { + "$ref": "#/$defs/RequestId" + } + ] + }, + "method": { + "description": "The method name to invoke.", + "type": "string" + }, + "params": { + "description": "Method-specific request parameters.", + "anyOf": [ + { + "description": "All possible requests that a client can send to an agent.\n\nThis enum is used internally for routing RPC requests. You typically won't need\nto use this directly.\n\nThis enum encompasses all method calls from client to agent.", + "anyOf": [ + { + "title": "InitializeRequest", + "description": "Establishes the connection with a client and negotiates protocol capabilities.\n\nThis method is called once at the beginning of the connection to:\n- Negotiate the protocol version to use\n- Exchange capability information between client and agent\n- Determine available authentication methods\n\nThe agent should respond with its supported protocol version and capabilities.\n\nSee protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v1/initialization)", + "allOf": [ + { + "$ref": "#/$defs/InitializeRequest" + } + ] + }, + { + "title": "AuthenticateRequest", + "description": "Authenticates the client using the specified authentication method.\n\nCalled when the agent requires authentication before allowing session creation.\nThe client provides an authentication method ID that was advertised during\ninitialization and whose type defines the `authenticate` flow.\n\nAfter successful authentication, the client can proceed to create sessions with\n`session/new` without receiving an `auth_required` (`-32000`) error.\n\nSee protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v1/initialization)", + "allOf": [ + { + "$ref": "#/$defs/AuthenticateRequest" + } + ] + }, + { + "title": "LogoutRequest", + "description": "Logs out of the current authenticated state.\n\nAfter a successful logout, all new sessions will require authentication.\nThere is no guarantee about the behavior of already running sessions.", + "allOf": [ + { + "$ref": "#/$defs/LogoutRequest" + } + ] + }, + { + "title": "NewSessionRequest", + "description": "Creates a new conversation session with the agent.\n\nSessions represent independent conversation contexts with their own history and state.\n\nThe agent should:\n- Create a new session context\n- Connect to any specified MCP servers\n- Return a unique session ID for future requests\n\nMay return an `auth_required` (`-32000`) error if the agent requires authentication.\n\nSee protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/v1/session-setup)", + "allOf": [ + { + "$ref": "#/$defs/NewSessionRequest" + } + ] + }, + { + "title": "LoadSessionRequest", + "description": "Loads an existing session to resume a previous conversation.\n\nThis method is only available if the agent advertises the `loadSession` capability.\n\nThe agent should:\n- Restore the session context and conversation history\n- Connect to the specified MCP servers\n- Stream the entire conversation history back to the client via notifications\n\nSee protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/v1/session-setup#loading-sessions)", + "allOf": [ + { + "$ref": "#/$defs/LoadSessionRequest" + } + ] + }, + { + "title": "ListSessionsRequest", + "description": "Lists existing sessions known to the agent.\n\nThis method is only available if the agent advertises the `sessionCapabilities.list` capability.\n\nThe agent should return metadata about sessions with optional filtering and pagination support.", + "allOf": [ + { + "$ref": "#/$defs/ListSessionsRequest" + } + ] + }, + { + "title": "DeleteSessionRequest", + "description": "Deletes an existing session from `session/list`.\n\nThis method is only available if the agent advertises the `sessionCapabilities.delete` capability.", + "allOf": [ + { + "$ref": "#/$defs/DeleteSessionRequest" + } + ] + }, + { + "title": "ResumeSessionRequest", + "description": "Resumes an existing session without returning previous messages.\n\nThis method is only available if the agent advertises the `sessionCapabilities.resume` capability.\n\nThe agent should resume the session context, allowing the conversation to continue\nwithout replaying the message history (unlike `session/load`).", + "allOf": [ + { + "$ref": "#/$defs/ResumeSessionRequest" + } + ] + }, + { + "title": "CloseSessionRequest", + "description": "Closes an active session and frees up any resources associated with it.\n\nThis method is only available if the agent advertises the `sessionCapabilities.close` capability.\n\nThe agent must cancel any ongoing work (as if `session/cancel` was called)\nand then free up any resources associated with the session.", + "allOf": [ + { + "$ref": "#/$defs/CloseSessionRequest" + } + ] + }, + { + "title": "SetSessionModeRequest", + "description": "Sets the current mode for a session.\n\nAllows switching between different agent modes (e.g., \"ask\", \"architect\", \"code\")\nthat affect system prompts, tool availability, and permission behaviors.\n\nThe mode must be one of the modes advertised in `availableModes` during session\ncreation or loading. Agents may also change modes autonomously and notify the\nclient via `current_mode_update` notifications.\n\nThis method can be called at any time during a session, whether the Agent is\nidle or actively generating a response.\n\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)", + "allOf": [ + { + "$ref": "#/$defs/SetSessionModeRequest" + } + ] + }, + { + "title": "SetSessionConfigOptionRequest", + "description": "Sets the current value for a session configuration option.", + "allOf": [ + { + "$ref": "#/$defs/SetSessionConfigOptionRequest" + } + ] + }, + { + "title": "PromptRequest", + "description": "Processes a user prompt within a session.\n\nThis method handles the whole lifecycle of a prompt:\n- Receives user messages with optional context (files, images, etc.)\n- Processes the prompt using language models\n- Reports language model content and tool calls to the Clients\n- Requests permission to run tools\n- Executes any requested tool calls\n- Returns when the turn is complete with a stop reason\n\nSee protocol docs: [Prompt Turn](https://agentclientprotocol.com/protocol/v1/prompt-turn)", + "allOf": [ + { + "$ref": "#/$defs/PromptRequest" + } + ] + }, + { + "title": "ExtMethodRequest", + "description": "Handles extension method requests from the client.\n\nExtension methods provide a way to add custom functionality while maintaining\nprotocol compatibility.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "allOf": [ + { + "$ref": "#/$defs/ExtRequest" + } + ] + } + ] + }, + { + "type": "null" + } + ] + } + }, + "required": ["id", "method"], + "x-docs-ignore": true + }, + "InitializeRequest": { + "description": "Request parameters for the initialize method.\n\nSent by the client to establish connection and negotiate capabilities.\n\nSee protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v1/initialization)", + "type": "object", + "properties": { + "protocolVersion": { + "description": "The latest protocol version supported by the client.", + "allOf": [ + { + "$ref": "#/$defs/ProtocolVersion" + } + ] + }, + "clientCapabilities": { + "description": "Capabilities supported by the client.", + "x-deserialize-default-on-error": true, + "default": { + "fs": { + "readTextFile": false, + "writeTextFile": false + }, + "terminal": false, + "auth": { + "terminal": false + } + }, + "allOf": [ + { + "$ref": "#/$defs/ClientCapabilities" + } + ] + }, + "clientInfo": { + "description": "Information about the Client name and version sent to the Agent.\n\nNote: in future versions of the protocol, this will be required.", + "anyOf": [ + { + "$ref": "#/$defs/Implementation" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["protocolVersion"], + "x-side": "agent", + "x-method": "initialize" + }, + "ClientCapabilities": { + "description": "Capabilities supported by the client.\n\nAdvertised during initialization to inform the agent about\navailable features and methods.\n\nSee protocol docs: [Client Capabilities](https://agentclientprotocol.com/protocol/v1/initialization#client-capabilities)", + "type": "object", + "properties": { + "fs": { + "description": "File system capabilities supported by the client.\nDetermines which file operations the agent can request.", + "x-deserialize-default-on-error": true, + "default": { + "readTextFile": false, + "writeTextFile": false + }, + "allOf": [ + { + "$ref": "#/$defs/FileSystemCapabilities" + } + ] + }, + "terminal": { + "description": "Whether the Client support all `terminal/*` methods.", + "type": "boolean", + "default": false, + "x-deserialize-default-on-error": true + }, + "session": { + "description": "Session-related capabilities supported by the client.\n\nOptional. Omitted or `null` both mean the client does not advertise any\nsession-related extensions.", + "anyOf": [ + { + "$ref": "#/$defs/ClientSessionCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "auth": { + "description": "Authentication capabilities supported by the client.\nDetermines which authentication method types the agent may include\nin its `InitializeResponse`.", + "x-deserialize-default-on-error": true, + "default": { + "terminal": false + }, + "allOf": [ + { + "$ref": "#/$defs/AuthCapabilities" + } + ] + }, + "elicitation": { + "description": "Elicitation capabilities supported by the client.\nDetermines which elicitation modes the agent may use.\n\nOptional. Omitted or `null` both mean the client does not advertise\nelicitation support.", + "anyOf": [ + { + "$ref": "#/$defs/ElicitationCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "FileSystemCapabilities": { + "description": "File system capabilities that a client may support.\n\nSee protocol docs: [FileSystem](https://agentclientprotocol.com/protocol/v1/initialization#filesystem)", + "type": "object", + "properties": { + "readTextFile": { + "description": "Whether the Client supports `fs/read_text_file` requests.", + "type": "boolean", + "default": false, + "x-deserialize-default-on-error": true + }, + "writeTextFile": { + "description": "Whether the Client supports `fs/write_text_file` requests.", + "type": "boolean", + "default": false, + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "ClientSessionCapabilities": { + "description": "Session-related capabilities supported by the client.", + "type": "object", + "properties": { + "compaction": { + "description": "Support for ID-addressed context compaction updates. Omitted or `null`\nmeans unsupported. `{}` advertises the complete compaction contract.", + "anyOf": [ + { + "$ref": "#/$defs/CompactionCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "configOptions": { + "description": "Config option capabilities supported by the client.\n\nOmitted or `null` both mean the client does not advertise support for any\nconfig option extensions.", + "anyOf": [ + { + "$ref": "#/$defs/SessionConfigOptionsCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "notices": { + "description": "Support for live user-facing `notice` session updates.\n\nOptional. Omitted or `null` both mean the client does not advertise support.\nSupplying `{}` means the client can present notices to the user.", + "anyOf": [ + { + "$ref": "#/$defs/NoticeCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "CompactionCapabilities": { + "description": "Client support for ID-addressed context compaction updates.", + "type": "object" + }, + "SessionConfigOptionsCapabilities": { + "description": "Session configuration option capabilities supported by the client.", + "type": "object", + "properties": { + "boolean": { + "description": "Whether the client supports boolean session configuration options.\n\nOptional. Omitted or `null` both mean the client does not advertise support.\nSupplying `{}` means agents may include `type: \"boolean\"` entries in\n`configOptions`, and the client may send `session/set_config_option`\nrequests with `type: \"boolean\"` and a boolean `value`.", + "anyOf": [ + { + "$ref": "#/$defs/BooleanConfigOptionCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "BooleanConfigOptionCapabilities": { + "description": "Capabilities for boolean session configuration options.\n\nSupplying `{}` means the client supports boolean session configuration options.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "NoticeCapabilities": { + "description": "Client support for presenting live notices to the user.", + "type": "object" + }, + "AuthCapabilities": { + "description": "Authentication capabilities supported by the client.\n\nAdvertised during initialization to inform the agent which authentication\nmethod types the client can handle. This governs opt-in types that require\nadditional client-side support.", + "type": "object", + "properties": { + "terminal": { + "description": "Whether the client supports `terminal` authentication methods.\n\nThe client should set this to `true` only when it can reproduce the\nconfigured agent invocation in an interactive terminal. When `true`, the\nagent may include `terminal` entries in its authentication methods.", + "type": "boolean", + "default": false, + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "ElicitationCapabilities": { + "description": "Elicitation capabilities supported by the client.", + "type": "object", + "properties": { + "form": { + "description": "Whether the client supports form-based elicitation.\n\nOptional. Omitted and `null` are equivalent and mean form support is not advertised.\nSupplying `{}` explicitly advertises form support.", + "anyOf": [ + { + "$ref": "#/$defs/ElicitationFormCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "url": { + "description": "Whether the client supports URL-based elicitation.\n\nOptional. Omitted or `null` both mean the client does not advertise support.\nSupplying `{}` means the client supports URL-based elicitation.", + "anyOf": [ + { + "$ref": "#/$defs/ElicitationUrlCapabilities" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "ElicitationFormCapabilities": { + "description": "Form-based elicitation capabilities.\n\nSupplying `{}` means the client supports form-based elicitation.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "ElicitationUrlCapabilities": { + "description": "URL-based elicitation capabilities.\n\nSupplying `{}` means the client supports URL-based elicitation.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "AuthenticateRequest": { + "description": "Request parameters for the authenticate method.\n\nSpecifies which authentication method to use.", + "type": "object", + "properties": { + "methodId": { + "description": "The ID of the authentication method to use.\nMust be one of the methods advertised in the initialize response.", + "allOf": [ + { + "$ref": "#/$defs/AuthMethodId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["methodId"], + "x-side": "agent", + "x-method": "authenticate" + }, + "LogoutRequest": { + "description": "Request parameters for the logout method.\n\nTerminates the current authenticated session.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "x-side": "agent", + "x-method": "logout" + }, + "NewSessionRequest": { + "description": "Request parameters for creating a new session.\n\nSee protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v1/session-setup#creating-a-session)", + "type": "object", + "properties": { + "cwd": { + "description": "The working directory for this session. Must be an absolute path.", + "type": "string" + }, + "additionalDirectories": { + "description": "Additional workspace roots for this session. Each path must be absolute.\n\nThese expand the session's filesystem scope without changing `cwd`, which\nremains the base for relative paths. When omitted or empty, no\nadditional roots are activated for the new session.", + "type": "array", + "items": { + "type": "string" + }, + "x-deserialize-default-on-null": true + }, + "mcpServers": { + "description": "List of MCP (Model Context Protocol) servers the agent should connect to.", + "type": "array", + "items": { + "$ref": "#/$defs/McpServer" + }, + "x-deserialize-default-on-null": true + }, + "systemPrompt": { + "description": "System-level instructions for the new session.\n\nOptional. Omitted and `null` are equivalent and mean the Agent uses its\nown default instructions. Clients MUST only send this when the Agent\nadvertises `sessionCapabilities.systemPrompt`.", + "anyOf": [ + { + "$ref": "#/$defs/SystemPrompt" + }, + { + "type": "null" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["cwd", "mcpServers"], + "x-side": "agent", + "x-method": "session/new" + }, + "McpServer": { + "description": "Configuration for connecting to an MCP (Model Context Protocol) server.\n\nMCP servers provide tools and context that the agent can use when\nprocessing prompts.\n\nSee protocol docs: [MCP Servers](https://agentclientprotocol.com/protocol/v1/session-setup#mcp-servers)", + "anyOf": [ + { + "description": "HTTP transport configuration\n\nOnly available when the Agent capabilities indicate `mcp_capabilities.http` is `true`.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "http" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/McpServerHttp" + } + ] + }, + { + "description": "SSE transport configuration\n\nOnly available when the Agent capabilities indicate `mcp_capabilities.sse` is `true`.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "sse" + } + }, + "required": ["type"], + "allOf": [ + { + "$ref": "#/$defs/McpServerSse" + } + ] + }, + { + "title": "stdio", + "description": "Stdio transport configuration\n\nAll Agents MUST support this transport.", + "allOf": [ + { + "$ref": "#/$defs/McpServerStdio" + } + ] + } + ] + }, + "HttpHeader": { + "description": "An HTTP header to set when making requests to the MCP server.", + "type": "object", + "properties": { + "name": { + "description": "The name of the HTTP header.", + "type": "string" + }, + "value": { + "description": "The value to set for the HTTP header.", + "type": "string" + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["name", "value"] + }, + "McpServerHttp": { + "description": "HTTP transport configuration for MCP.", + "type": "object", + "properties": { + "name": { + "description": "Human-readable name identifying this MCP server.", + "type": "string" + }, + "url": { + "description": "URL to the MCP server.", + "type": "string" + }, + "headers": { + "description": "HTTP headers to set when making requests to the MCP server.", + "type": "array", + "items": { + "$ref": "#/$defs/HttpHeader" + }, + "x-deserialize-default-on-null": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["name", "url", "headers"] + }, + "McpServerSse": { + "description": "SSE transport configuration for MCP.", + "type": "object", + "properties": { + "name": { + "description": "Human-readable name identifying this MCP server.", + "type": "string" + }, + "url": { + "description": "URL to the MCP server.", + "type": "string" + }, + "headers": { + "description": "HTTP headers to set when making requests to the MCP server.", + "type": "array", + "items": { + "$ref": "#/$defs/HttpHeader" + }, + "x-deserialize-default-on-null": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["name", "url", "headers"] + }, + "McpServerStdio": { + "description": "Stdio transport configuration for MCP.", + "type": "object", + "properties": { + "name": { + "description": "Human-readable name identifying this MCP server.", + "type": "string" + }, + "command": { + "description": "Absolute path to the MCP server executable.", + "type": "string" + }, + "args": { + "description": "Command-line arguments to pass to the MCP server.", + "type": "array", + "items": { + "type": "string" + }, + "x-deserialize-default-on-null": true + }, + "env": { + "description": "Environment variables to set when launching the MCP server.", + "type": "array", + "items": { + "$ref": "#/$defs/EnvVariable" + }, + "x-deserialize-default-on-null": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["name", "command", "args", "env"] + }, + "SystemPrompt": { + "description": "Client-provided system-level instructions for a session.\n\nClients MUST only send this when the Agent advertises\n`sessionCapabilities.systemPrompt`. Agents that cannot apply it, for example\nbecause of an unadvertised mode or an unsupported content block type, MUST\nreturn an error instead of creating, loading, or resuming the session.", + "type": "object", + "properties": { + "mode": { + "description": "How the Agent combines `content` with its own instructions.\n\nRequired. Agents MUST return an error for a mode they do not support rather than\ntreating it as `append` or `override`.", + "allOf": [ + { + "$ref": "#/$defs/SystemPromptMode" + } + ] + }, + "content": { + "description": "The system prompt content.\n\nAgents advertising the capability MUST accept `text` content blocks.\nClients MUST NOT send other content block types until a future\ncapability allows them, and Agents MUST return an error for content\nblocks they do not support.\n\nClients MUST NOT send an empty array. Agents MAY reject one with\n`-32602` without creating, loading, or resuming the session.", + "type": "array", + "items": { + "$ref": "#/$defs/ContentBlock" + } + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["mode", "content"] + }, + "SystemPromptMode": { + "description": "How the Agent combines a client-provided system prompt with its own instructions.\n\nUnknown modes are preserved so they can be stored,\nproxied, or forwarded. An Agent MUST return an error for a mode it does not\nsupport rather than treating it as `append` or `override`.", + "anyOf": [ + { + "description": "Add the content to the Agent's own instructions rather than replacing them.\n\nEvery Agent that advertises `sessionCapabilities.systemPrompt` supports this mode.\nAgents SHOULD give the content system-level precedence, for example in the\nmodel's system prompt or developer instructions rather than in user-turn\ncontent. Where it is placed and how it is formatted is implementation-defined.", + "type": "string", + "const": "append" + }, + { + "description": "Replace the Agent's built-in default instructions with the content.\n\nThis does not change tool availability, MCP servers, permissions, or session\nconfiguration. Context the Agent supplies from the workspace or environment\nMAY still be included. Clients that use this mode take responsibility for any\ntool guidance or safety instructions the Agent's default instructions\nprovided, and MUST only use it when the Agent advertises\n`sessionCapabilities.systemPrompt.mode.override`.", + "type": "string", + "const": "override" + }, + { + "title": "other", + "description": "Custom or future system prompt mode.\n\nValues beginning with `_` are reserved for implementation-specific\nextensions. Unknown values that do not begin with `_` are reserved for\nfuture ACP variants.", + "type": "string" + } + ] + }, + "LoadSessionRequest": { + "description": "Request parameters for loading an existing session.\n\nOnly available if the Agent supports the `loadSession` capability.\n\nSee protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/v1/session-setup#loading-sessions)", + "type": "object", + "properties": { + "mcpServers": { + "description": "List of MCP servers to connect to for this session.", + "type": "array", + "items": { + "$ref": "#/$defs/McpServer" + }, + "x-deserialize-default-on-null": true + }, + "cwd": { + "description": "The working directory for this session. Must be an absolute path.", + "type": "string" + }, + "additionalDirectories": { + "description": "Additional workspace roots to activate for this session. Each path must be absolute.\n\nWhen omitted or empty, no additional roots are activated. When non-empty,\nthis is the complete resulting additional-root list for the loaded\nsession. It may differ from any previously used or reported list as long as\nthe request `cwd` matches the session's `cwd`.", + "type": "array", + "items": { + "type": "string" + }, + "x-deserialize-default-on-null": true + }, + "sessionId": { + "description": "The ID of the session to load.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "systemPrompt": { + "description": "System-level instructions for the loaded session.\n\nOptional. Omitted and `null` are equivalent. The Agent may then keep a\nsystem prompt it stored with the session or use its default instructions.\nClients MUST only send this when the Agent advertises\n`sessionCapabilities.systemPrompt`, and SHOULD send the same value they used\nwhen the session was created.", + "anyOf": [ + { + "$ref": "#/$defs/SystemPrompt" + }, + { + "type": "null" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["mcpServers", "cwd", "sessionId"], + "x-side": "agent", + "x-method": "session/load" + }, + "ListSessionsRequest": { + "description": "Request parameters for listing existing sessions.\n\nOnly available if the Agent supports the `sessionCapabilities.list` capability.", + "type": "object", + "properties": { + "cwd": { + "description": "Filter sessions by working directory. Must be an absolute path.", + "type": ["string", "null"] + }, + "cursor": { + "description": "Opaque cursor token from a previous response's nextCursor field for cursor-based pagination", + "type": ["string", "null"] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "x-side": "agent", + "x-method": "session/list" + }, + "DeleteSessionRequest": { + "description": "Request parameters for deleting an existing session from `session/list`.\n\nOnly available if the Agent supports the `sessionCapabilities.delete` capability.", + "type": "object", + "properties": { + "sessionId": { + "description": "The ID of the session to delete.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId"], + "x-side": "agent", + "x-method": "session/delete" + }, + "ResumeSessionRequest": { + "description": "Request parameters for resuming an existing session.\n\nResumes an existing session without returning previous messages (unlike `session/load`).\nThis is useful for agents that can resume sessions but don't implement full session loading.\n\nOnly available if the Agent supports the `sessionCapabilities.resume` capability.", + "type": "object", + "properties": { + "sessionId": { + "description": "The ID of the session to resume.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "cwd": { + "description": "The working directory for this session. Must be an absolute path.", + "type": "string" + }, + "additionalDirectories": { + "description": "Additional workspace roots to activate for this session. Each path must be absolute.\n\nWhen omitted or empty, no additional roots are activated. When non-empty,\nthis is the complete resulting additional-root list for the resumed\nsession. It may differ from any previously used or reported list as long as\nthe request `cwd` matches the session's `cwd`.", + "type": "array", + "items": { + "type": "string" + }, + "x-deserialize-default-on-null": true + }, + "mcpServers": { + "description": "List of MCP servers to connect to for this session.", + "type": "array", + "items": { + "$ref": "#/$defs/McpServer" + }, + "x-deserialize-default-on-null": true + }, + "systemPrompt": { + "description": "System-level instructions for the resumed session.\n\nOptional. Omitted and `null` are equivalent. The Agent may then keep a\nsystem prompt it stored with the session or use its default instructions.\nClients MUST only send this when the Agent advertises\n`sessionCapabilities.systemPrompt`, and SHOULD send the same value they used\nwhen the session was created.", + "anyOf": [ + { + "$ref": "#/$defs/SystemPrompt" + }, + { + "type": "null" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId", "cwd"], + "x-side": "agent", + "x-method": "session/resume" + }, + "CloseSessionRequest": { + "description": "Request parameters for closing an active session.\n\nIf supported, the agent **must** cancel any ongoing work related to the session\n(treat it as if `session/cancel` was called) and then free up any resources\nassociated with the session.\n\nOnly available if the Agent supports the `sessionCapabilities.close` capability.", + "type": "object", + "properties": { + "sessionId": { + "description": "The ID of the session to close.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId"], + "x-side": "agent", + "x-method": "session/close" + }, + "SetSessionModeRequest": { + "description": "Request parameters for setting a session mode.", + "type": "object", + "properties": { + "sessionId": { + "description": "The ID of the session to set the mode for.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "modeId": { + "description": "The ID of the mode to set.", + "allOf": [ + { + "$ref": "#/$defs/SessionModeId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId", "modeId"], + "x-side": "agent", + "x-method": "session/set_mode" + }, + "SetSessionConfigOptionRequest": { + "description": "Request parameters for setting a session configuration option.", + "type": "object", + "properties": { + "sessionId": { + "description": "The ID of the session to set the configuration option for.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "configId": { + "description": "The ID of the configuration option to set.", + "allOf": [ + { + "$ref": "#/$defs/SessionConfigId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId", "configId"], + "anyOf": [ + { + "description": "A boolean value (`type: \"boolean\"`).", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "boolean" + }, + "value": { + "description": "The boolean value.", + "type": "boolean" + } + }, + "required": ["type", "value"] + }, + { + "title": "value_id", + "description": "A `SessionConfigValueId` string value.\n\nThis is the default when `type` is absent on the wire. Unknown `type`\nvalues with string payloads also gracefully deserialize into this\nvariant.", + "type": "object", + "properties": { + "value": { + "description": "The value ID.", + "allOf": [ + { + "$ref": "#/$defs/SessionConfigValueId" + } + ] + } + }, + "required": ["value"] + } + ], + "x-side": "agent", + "x-method": "session/set_config_option" + }, + "PromptRequest": { + "description": "Request parameters for sending a user prompt to the agent.\n\nContains the user's message and any additional context.\n\nSee protocol docs: [User Message](https://agentclientprotocol.com/protocol/v1/prompt-turn#1-user-message)", + "type": "object", + "properties": { + "sessionId": { + "description": "The ID of the session to send this user message to", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "prompt": { + "description": "The blocks of content that compose the user's message.\n\nAs a baseline, the Agent MUST support `text` and `resource_link` content blocks,\nwhile other variants are optionally enabled via `PromptCapabilities`.\n\nThe Client MUST adapt its interface according to `PromptCapabilities`.\n\nThe client MAY include referenced pieces of context as either\n`resource` or `resource_link` content blocks.\n\nWhen available, `resource` is preferred\nas it avoids extra round-trips and allows the message to include\npieces of context from sources the agent may not have access to.", + "type": "array", + "items": { + "$ref": "#/$defs/ContentBlock" + } + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId", "prompt"], + "x-side": "agent", + "x-method": "session/prompt" + }, + "ClientResponse": { + "description": "A JSON-RPC response object.", + "anyOf": [ + { + "title": "Result", + "description": "A successful JSON-RPC response.", + "type": "object", + "properties": { + "id": { + "description": "The id of the request this response answers.", + "allOf": [ + { + "$ref": "#/$defs/RequestId" + } + ] + }, + "result": { + "description": "Method-specific response data.", + "anyOf": [ + { + "title": "WriteTextFileResponse", + "description": "Successful result returned for a `fs/write_text_file` request.", + "allOf": [ + { + "$ref": "#/$defs/WriteTextFileResponse" + } + ] + }, + { + "title": "ReadTextFileResponse", + "description": "Successful result returned for a `fs/read_text_file` request.", + "allOf": [ + { + "$ref": "#/$defs/ReadTextFileResponse" + } + ] + }, + { + "title": "RequestPermissionResponse", + "description": "Successful result returned for a `session/request_permission` request.", + "allOf": [ + { + "$ref": "#/$defs/RequestPermissionResponse" + } + ] + }, + { + "title": "CreateTerminalResponse", + "description": "Successful result returned for a `terminal/create` request.", + "allOf": [ + { + "$ref": "#/$defs/CreateTerminalResponse" + } + ] + }, + { + "title": "TerminalOutputResponse", + "description": "Successful result returned for a `terminal/output` request.", + "allOf": [ + { + "$ref": "#/$defs/TerminalOutputResponse" + } + ] + }, + { + "title": "ReleaseTerminalResponse", + "description": "Successful result returned for a `terminal/release` request.", + "allOf": [ + { + "$ref": "#/$defs/ReleaseTerminalResponse" + } + ] + }, + { + "title": "WaitForTerminalExitResponse", + "description": "Successful result returned for a `terminal/wait_for_exit` request.", + "allOf": [ + { + "$ref": "#/$defs/WaitForTerminalExitResponse" + } + ] + }, + { + "title": "KillTerminalResponse", + "description": "Successful result returned for a `terminal/kill` request.", + "allOf": [ + { + "$ref": "#/$defs/KillTerminalResponse" + } + ] + }, + { + "title": "CreateElicitationResponse", + "description": "Successful result returned for a `elicitation/create` request.", + "allOf": [ + { + "$ref": "#/$defs/CreateElicitationResponse" + } + ] + }, + { + "title": "ExtMethodResponse", + "description": "Successful result returned by an extension method outside the core ACP method set.", + "allOf": [ + { + "$ref": "#/$defs/ExtResponse" + } + ] + } + ] + } + }, + "required": ["id", "result"] + }, + { + "title": "Error", + "description": "A failed JSON-RPC response.", + "type": "object", + "properties": { + "id": { + "description": "The id of the request this response answers.", + "allOf": [ + { + "$ref": "#/$defs/RequestId" + } + ] + }, + "error": { + "description": "Method-specific error data.", + "allOf": [ + { + "$ref": "#/$defs/Error" + } + ] + } + }, + "required": ["id", "error"] + } + ], + "x-docs-ignore": true + }, + "WriteTextFileResponse": { + "description": "Response to `fs/write_text_file`", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "x-side": "client", + "x-method": "fs/write_text_file" + }, + "ReadTextFileResponse": { + "description": "Response containing the contents of a text file.", + "type": "object", + "properties": { + "content": { + "description": "Content payload returned by this response.", + "type": "string" + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["content"], + "x-side": "client", + "x-method": "fs/read_text_file" + }, + "RequestPermissionResponse": { + "description": "Response to a permission request.", + "type": "object", + "properties": { + "outcome": { + "description": "The user's decision on the permission request.", + "allOf": [ + { + "$ref": "#/$defs/RequestPermissionOutcome" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["outcome"], + "x-side": "client", + "x-method": "session/request_permission" + }, + "RequestPermissionOutcome": { + "description": "The outcome of a permission request.", + "oneOf": [ + { + "description": "The prompt turn was cancelled before the user responded.\n\nWhen a client sends a `session/cancel` notification to cancel an ongoing\nprompt turn, it MUST respond to all pending `session/request_permission`\nrequests with this `cancelled` outcome.\n\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v1/prompt-turn#cancellation)", + "type": "object", + "properties": { + "outcome": { + "type": "string", + "const": "cancelled" + } + }, + "required": ["outcome"] + }, + { + "description": "The user selected one of the provided options.", + "type": "object", + "properties": { + "outcome": { + "type": "string", + "const": "selected" + } + }, + "required": ["outcome"], + "allOf": [ + { + "$ref": "#/$defs/SelectedPermissionOutcome" + } + ] + } + ], + "discriminator": { + "propertyName": "outcome" + } + }, + "SelectedPermissionOutcome": { + "description": "The user selected one of the provided options.", + "type": "object", + "properties": { + "optionId": { + "description": "The ID of the option the user selected.", + "allOf": [ + { + "$ref": "#/$defs/PermissionOptionId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["optionId"] + }, + "CreateTerminalResponse": { + "description": "Response containing the ID of the created terminal.", + "type": "object", + "properties": { + "terminalId": { + "description": "The unique identifier for the created terminal.", + "allOf": [ + { + "$ref": "#/$defs/TerminalId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["terminalId"], + "x-side": "client", + "x-method": "terminal/create" + }, + "TerminalOutputResponse": { + "description": "Response containing the terminal output and exit status.", + "type": "object", + "properties": { + "output": { + "description": "The terminal output captured so far.", + "type": "string" + }, + "truncated": { + "description": "Whether the output was truncated due to byte limits.", + "type": "boolean" + }, + "exitStatus": { + "description": "Exit status if the command has completed.", + "anyOf": [ + { + "$ref": "#/$defs/TerminalExitStatus" + }, + { + "type": "null" + } + ], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["output", "truncated"], + "x-side": "client", + "x-method": "terminal/output" + }, + "TerminalExitStatus": { + "description": "Exit status of a terminal command.", + "type": "object", + "properties": { + "exitCode": { + "description": "The process exit code (may be null if terminated by signal).", + "type": ["integer", "null"], + "format": "uint32", + "minimum": 0, + "x-deserialize-default-on-error": true + }, + "signal": { + "description": "The signal that terminated the process (may be null if exited normally).", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + } + }, + "ReleaseTerminalResponse": { + "description": "Response to terminal/release method", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "x-side": "client", + "x-method": "terminal/release" + }, + "WaitForTerminalExitResponse": { + "description": "Response containing the exit status of a terminal command.", + "type": "object", + "properties": { + "exitCode": { + "description": "The process exit code (may be null if terminated by signal).", + "type": ["integer", "null"], + "format": "uint32", + "minimum": 0, + "x-deserialize-default-on-error": true + }, + "signal": { + "description": "The signal that terminated the process (may be null if exited normally).", + "type": ["string", "null"], + "x-deserialize-default-on-error": true + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "x-side": "client", + "x-method": "terminal/wait_for_exit" + }, + "KillTerminalResponse": { + "description": "Response to `terminal/kill` method", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "x-side": "client", + "x-method": "terminal/kill" + }, + "CreateElicitationResponse": { + "description": "Response from the client to an elicitation request.", + "type": "object", + "properties": { + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nOptional. Omitted and `null` are equivalent and mean no metadata.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "anyOf": [ + { + "description": "The user accepted and provided content.", + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "accept" + } + }, + "required": ["action"], + "allOf": [ + { + "$ref": "#/$defs/ElicitationAcceptAction" + } + ] + }, + { + "description": "The user declined the elicitation.", + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "decline" + } + }, + "required": ["action"] + }, + { + "description": "The elicitation was cancelled.", + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "cancel" + } + }, + "required": ["action"] + }, + { + "title": "other", + "description": "Custom or future elicitation action.\n\nValues beginning with `_` are reserved for implementation-specific\nextensions. Unknown values that do not begin with `_` are reserved for\nfuture ACP variants.\n\nAgents that do not understand this action should preserve the raw\npayload when storing, replaying, proxying, or forwarding elicitation\nresponses. They MUST NOT treat it as a known elicitation action.", + "type": "object", + "properties": { + "action": { + "description": "Custom or future elicitation action.\n\nValues beginning with `_` are reserved for implementation-specific\nextensions. Unknown values that do not begin with `_` are reserved for\nfuture ACP variants.", + "type": "string" + } + }, + "required": ["action"], + "not": { + "anyOf": [ + { + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "accept" + } + }, + "required": ["action"] + }, + { + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "decline" + } + }, + "required": ["action"] + }, + { + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "cancel" + } + }, + "required": ["action"] + } + ] + }, + "additionalProperties": true + } + ], + "x-side": "client", + "x-method": "elicitation/create" + }, + "ElicitationContentValue": { + "description": "Allowed wire representations for `ElicitationContentValue`.", + "anyOf": [ + { + "title": "String", + "description": "String value accepted in elicitation response content.", + "type": "string" + }, + { + "title": "Integer", + "description": "Integer value accepted in elicitation response content.", + "type": "integer", + "format": "int64" + }, + { + "title": "Number", + "description": "Number value accepted in elicitation response content.", + "type": "number", + "format": "double" + }, + { + "title": "Boolean", + "description": "Boolean value accepted in elicitation response content.", + "type": "boolean" + }, + { + "title": "StringArray", + "description": "String array value accepted in elicitation response content.", + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "ElicitationAcceptAction": { + "description": "The user accepted the elicitation and provided content.", + "type": "object", + "properties": { + "content": { + "description": "The user-provided content, if any, as an object matching the requested schema.", + "type": ["object", "null"], + "additionalProperties": { + "$ref": "#/$defs/ElicitationContentValue" + } + } + } + }, + "ClientNotification": { + "description": "A JSON-RPC notification object.", + "type": "object", + "properties": { + "method": { + "description": "The notification method name.", + "type": "string" + }, + "params": { + "description": "Method-specific notification parameters.", + "anyOf": [ + { + "description": "All possible notifications that a client can send to an agent.\n\nThis enum is used internally for routing RPC notifications. You typically won't need\nto use this directly.\n\nNotifications do not expect a response.", + "anyOf": [ + { + "title": "CancelNotification", + "description": "Cancels ongoing operations for a session.\n\nThis is a notification sent by the client to cancel an ongoing prompt turn.\n\nUpon receiving this notification, the Agent SHOULD:\n- Stop all language model requests as soon as possible\n- Abort all tool call invocations in progress\n- Send any pending `session/update` notifications\n- Respond to the original `session/prompt` request with the `cancelled` stop reason\n\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v1/prompt-turn#cancellation)", + "allOf": [ + { + "$ref": "#/$defs/CancelNotification" + } + ] + }, + { + "title": "ExtNotification", + "description": "Handles extension notifications from the client.\n\nExtension notifications provide a way to send one-way messages for custom functionality\nwhile maintaining protocol compatibility.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "allOf": [ + { + "$ref": "#/$defs/ExtNotification" + } + ] + } + ] + }, + { + "type": "null" + } + ] + } + }, + "required": ["method"], + "x-docs-ignore": true + }, + "CancelNotification": { + "description": "Notification to cancel ongoing operations for a session.\n\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v1/prompt-turn#cancellation)", + "type": "object", + "properties": { + "sessionId": { + "description": "The ID of the session to cancel operations for.", + "allOf": [ + { + "$ref": "#/$defs/SessionId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["sessionId"], + "x-side": "agent", + "x-method": "session/cancel" + }, + "CancelRequestNotification": { + "description": "Notification to cancel an ongoing request.\n\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v1/cancellation)", + "type": "object", + "properties": { + "requestId": { + "description": "The ID of the request to cancel.", + "allOf": [ + { + "$ref": "#/$defs/RequestId" + } + ] + }, + "_meta": { + "description": "The _meta property is reserved by ACP to allow clients and agents to attach additional\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\nthese keys.\n\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)", + "type": ["object", "null"], + "x-deserialize-default-on-error": true, + "additionalProperties": true + } + }, + "required": ["requestId"], + "x-side": "protocol", + "x-method": "$/cancel_request" + } + } +} diff --git a/tests/MandoCode.Tests/MandoCode.Tests.csproj b/tests/MandoCode.Tests/MandoCode.Tests.csproj index 394813d..9e6da65 100644 --- a/tests/MandoCode.Tests/MandoCode.Tests.csproj +++ b/tests/MandoCode.Tests/MandoCode.Tests.csproj @@ -23,6 +23,12 @@ + + + + + + From c4b9336ce824c98f6dfbd3ba38ad53589095865e Mon Sep 17 00:00:00 2001 From: TeseySTD Date: Tue, 10 Nov 2026 13:11:50 +0200 Subject: [PATCH 02/26] feat(acp): add JSON-RPC 2.0 connection over NDJSON streams Transport-agnostic connection used by the ACP client; works on any pair of streams, so it is tested in memory without spawning processes. - Line framing with a small buffered reader (no extra NuGet package): CRLF tolerated, blank lines skipped, 32 MB line cap, and a break after repeated non-JSON lines (agent logging to stdout). - Outgoing requests get numeric ids and are correlated with responses; error responses become JsonRpcException with code and data. - Incoming request ids (number or string) are echoed back unchanged. - The reader never waits on handlers: every incoming request runs on its own task, so a permission prompt can be pending during session/prompt. Unknown methods get -32601, bad params -32602, handler failures -32603. - Notifications are handled by a single consumer to keep session/update order; DrainNotificationsAsync lets callers wait for those that preceded a response. - One writer serializes output, one line per message. - EOF, write failure or dispose fail all pending requests with AcpConnectionClosedException; the transport can attach exit code and stderr tail through DescribeClose. --- src/MandoCode.Acp/AcpExceptions.cs | 49 ++ .../JsonRpc/JsonRpcConnection.cs | 654 ++++++++++++++++++ src/MandoCode.Acp/JsonRpc/JsonRpcId.cs | 68 ++ src/MandoCode.Acp/README.md | 17 +- tests/MandoCode.Tests/Acp/AcpTestKit.cs | 133 ++++ .../Acp/JsonRpcConnectionTests.cs | 576 +++++++++++++++ 6 files changed, 1496 insertions(+), 1 deletion(-) create mode 100644 src/MandoCode.Acp/AcpExceptions.cs create mode 100644 src/MandoCode.Acp/JsonRpc/JsonRpcConnection.cs create mode 100644 src/MandoCode.Acp/JsonRpc/JsonRpcId.cs create mode 100644 tests/MandoCode.Tests/Acp/AcpTestKit.cs create mode 100644 tests/MandoCode.Tests/Acp/JsonRpcConnectionTests.cs diff --git a/src/MandoCode.Acp/AcpExceptions.cs b/src/MandoCode.Acp/AcpExceptions.cs new file mode 100644 index 0000000..fc7091b --- /dev/null +++ b/src/MandoCode.Acp/AcpExceptions.cs @@ -0,0 +1,49 @@ +using System.Text.Json; + +namespace MandoCode.Acp; + +/// An error response (or an error to be sent as a response) in JSON-RPC terms. +public sealed class JsonRpcException : Exception +{ + public int Code { get; } + /// The optional data member of the error object. + public JsonElement? ErrorData { get; } + + public JsonRpcException(int code, string message, JsonElement? data = null) + : base(message) + { + Code = code; + ErrorData = data; + } + + public override string ToString() => $"JSON-RPC error {Code}: {Message}"; +} + +/// +/// The connection to the agent ended (the stream reached EOF, the write side broke, or the +/// connection was disposed) while a request was pending or about to be sent. +/// +public sealed class AcpConnectionClosedException : Exception +{ + /// Exit code of the agent process, when known. + public int? ExitCode { get; } + + /// The last lines the agent wrote to stderr, when known. + public string? StderrTail { get; } + + public AcpConnectionClosedException(string message, int? exitCode = null, string? stderrTail = null, Exception? inner = null) + : base(message, inner) + { + ExitCode = exitCode; + StderrTail = stderrTail; + } +} + +/// +/// The peer broke the wire protocol: a line that is too long, or repeated non-JSON output +/// (typically an agent that logs to stdout instead of stderr). +/// +public sealed class AcpProtocolViolationException : Exception +{ + public AcpProtocolViolationException(string message) : base(message) { } +} diff --git a/src/MandoCode.Acp/JsonRpc/JsonRpcConnection.cs b/src/MandoCode.Acp/JsonRpc/JsonRpcConnection.cs new file mode 100644 index 0000000..1e07d1e --- /dev/null +++ b/src/MandoCode.Acp/JsonRpc/JsonRpcConnection.cs @@ -0,0 +1,654 @@ +using System.Buffers; +using System.Collections.Concurrent; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; +using System.Threading.Channels; + +namespace MandoCode.Acp.JsonRpc; + +public sealed class JsonRpcConnectionOptions +{ + /// Longest accepted line. A longer one means the peer is not speaking NDJSON; the connection is broken. + public int MaxLineBytes { get; init; } = 32 * 1024 * 1024; + + /// Number of consecutive unparseable lines after which the peer is declared to be writing garbage to stdout. + public int MaxConsecutiveParseErrors { get; init; } = 5; + + /// + /// Builds the exception pending requests fail with when the stream ends. The process transport + /// uses it to attach the exit code and stderr tail; the default is a plain message. + /// + public Func? DescribeClose { get; init; } + + /// Diagnostics sink (ignored frames, handler failures). Never write this to the console. + public Action? Diagnostics { get; init; } +} + +/// +/// JSON-RPC 2.0 over newline-delimited JSON on a pair of streams (the agent's stdout and stdin). +/// +/// Outgoing requests get numeric ids and are correlated with their responses. +/// The reader never waits on a handler: every incoming request runs on its own task and +/// answers itself, so a permission prompt can be pending while a prompt request is in flight. +/// Incoming notifications are handled by a single consumer, preserving their order. +/// Writes are serialized through one writer; each message is exactly one line. +/// +/// The connection does not own the streams: the transport that created them closes them. +/// +public sealed class JsonRpcConnection : IAsyncDisposable +{ + private delegate ValueTask> RequestHandler(JsonElement? parameters, CancellationToken cancellationToken); + + private readonly Stream _input; + private readonly Stream _output; + private readonly JsonRpcConnectionOptions _options; + + private readonly Channel _outbound = Channel.CreateUnbounded( + new UnboundedChannelOptions { SingleReader = true }); + + private readonly Channel _notifications = Channel.CreateUnbounded( + new UnboundedChannelOptions { SingleReader = true }); + + private readonly ConcurrentDictionary> _pending = new(); + private readonly ConcurrentDictionary _requestHandlers = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary> _notificationHandlers = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _runningHandlers = new(); + private readonly CancellationTokenSource _lifetime = new(); + private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously); + + private readonly Task _readLoop; + private readonly Task _writeLoop; + private readonly Task _notificationLoop; + + private long _nextRequestId; + private long _nextHandlerId; + private int _terminated; + private Exception? _closeReason; + private int _consecutiveParseErrors; + + private readonly record struct NotificationWork(Func? Handler, JsonElement? Parameters, TaskCompletionSource? Marker); + + public JsonRpcConnection(Stream input, Stream output, JsonRpcConnectionOptions? options = null) + { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(output); + + _options = options ?? new JsonRpcConnectionOptions(); + _input = input; + _output = output; + + _readLoop = Task.Run(ReadLoopAsync); + _writeLoop = Task.Run(WriteLoopAsync); + _notificationLoop = Task.Run(NotificationLoopAsync); + } + + /// + /// Completes when the connection ends: normally for EOF or dispose, faulted when the peer broke + /// the protocol or the transport failed. + /// + public Task Completion => _completion.Task; + + /// Why the connection ended, or null while it is open. + public Exception? CloseReason => Volatile.Read(ref _closeReason); + + // ───────────────────────── handlers ───────────────────────── + + /// Registers the handler for an incoming request (a call the peer expects an answer to). + public void RegisterRequestHandler( + string method, + JsonTypeInfo requestInfo, + JsonTypeInfo responseInfo, + Func> handler) + { + _requestHandlers[method] = async (parameters, cancellationToken) => + { + if (parameters is null) + throw new JsonRpcException(Protocol.AcpErrorCodes.InvalidParams, $"Missing params for '{method}'."); + + TRequest? request; + try + { + request = parameters.Value.Deserialize(requestInfo); + } + catch (JsonException ex) + { + throw new JsonRpcException(Protocol.AcpErrorCodes.InvalidParams, $"Invalid params for '{method}': {ex.Message}"); + } + + if (request is null) + throw new JsonRpcException(Protocol.AcpErrorCodes.InvalidParams, $"Invalid params for '{method}'."); + + var response = await handler(request, cancellationToken).ConfigureAwait(false); + return writer => System.Text.Json.JsonSerializer.Serialize(writer, response, responseInfo); + }; + } + + /// Registers the handler for an incoming notification. Handlers run one at a time, in arrival order. + public void RegisterNotificationHandler( + string method, + JsonTypeInfo notificationInfo, + Func handler) + { + _notificationHandlers[method] = async parameters => + { + TNotification? notification; + try + { + notification = parameters is null ? default : parameters.Value.Deserialize(notificationInfo); + } + catch (JsonException ex) + { + Diagnose($"Ignoring notification '{method}' with invalid params: {ex.Message}"); + return; + } + + if (notification is null) + { + Diagnose($"Ignoring notification '{method}' without usable params."); + return; + } + + await handler(notification).ConfigureAwait(false); + }; + } + + // ───────────────────────── sending ───────────────────────── + + public async Task SendRequestAsync( + string method, + TRequest request, + JsonTypeInfo requestInfo, + JsonTypeInfo responseInfo, + CancellationToken cancellationToken = default) + { + ThrowIfClosed(); + + var id = Interlocked.Increment(ref _nextRequestId); + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _pending[id] = tcs; + + using var registration = cancellationToken.Register(() => + { + if (_pending.TryRemove(id, out var removed)) + removed.TrySetCanceled(cancellationToken); + }); + + try + { + Enqueue(writer => + { + writer.WriteStartObject(); + writer.WriteString("jsonrpc", "2.0"); + writer.WriteNumber("id", id); + writer.WriteString("method", method); + writer.WritePropertyName("params"); + System.Text.Json.JsonSerializer.Serialize(writer, request, requestInfo); + writer.WriteEndObject(); + }); + + // The race between a close and our registration is closed by FailPending, which + // also runs after _terminated is set, so this task cannot be left dangling. + if (Volatile.Read(ref _terminated) != 0) + FailPending(); + + var result = await tcs.Task.ConfigureAwait(false); + + try + { + var response = result.Deserialize(responseInfo); + return response ?? throw new JsonRpcException(Protocol.AcpErrorCodes.InternalError, $"'{method}' returned an empty result."); + } + catch (Exception ex) when (ex is JsonException or InvalidOperationException) + { + throw new JsonRpcException(Protocol.AcpErrorCodes.InternalError, $"'{method}' returned a malformed result: {ex.Message}"); + } + } + finally + { + _pending.TryRemove(id, out _); + } + } + + public Task SendNotificationAsync( + string method, + TNotification notification, + JsonTypeInfo notificationInfo) + { + ThrowIfClosed(); + + Enqueue(writer => + { + writer.WriteStartObject(); + writer.WriteString("jsonrpc", "2.0"); + writer.WriteString("method", method); + writer.WritePropertyName("params"); + System.Text.Json.JsonSerializer.Serialize(writer, notification, notificationInfo); + writer.WriteEndObject(); + }); + + return Task.CompletedTask; + } + + /// + /// Completes once every notification received before this call has been handled. The reader + /// dispatches a response as soon as it arrives, so a caller that must see all session/update + /// notifications that preceded a response awaits this first. + /// + public Task DrainNotificationsAsync() + { + var marker = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + if (!_notifications.Writer.TryWrite(new NotificationWork(null, null, marker))) + marker.TrySetResult(); + return marker.Task; + } + + // ───────────────────────── write path ───────────────────────── + + private void Enqueue(Action write) + { + var buffer = new ArrayBufferWriter(256); + using (var writer = new Utf8JsonWriter(buffer)) + write(writer); + + var line = new byte[buffer.WrittenCount + 1]; + buffer.WrittenSpan.CopyTo(line); + line[^1] = (byte)'\n'; + + if (!_outbound.Writer.TryWrite(line)) + throw ClosedException(); + } + + private async Task WriteLoopAsync() + { + try + { + await foreach (var line in _outbound.Reader.ReadAllAsync().ConfigureAwait(false)) + { + await _output.WriteAsync(line).ConfigureAwait(false); + await _output.FlushAsync().ConfigureAwait(false); + } + } + catch (Exception ex) when (ex is IOException or ObjectDisposedException or InvalidOperationException or NotSupportedException) + { + Terminate(CreateClosedException(ex)); + } + catch (OperationCanceledException) + { + } + } + + // ───────────────────────── read path ───────────────────────── + + private async Task ReadLoopAsync() + { + try + { + var token = _lifetime.Token; + var buffer = new byte[16 * 1024]; + int start = 0, end = 0, scanFrom = 0; + + while (true) + { + var newline = buffer.AsSpan(scanFrom, end - scanFrom).IndexOf((byte)'\n'); + if (newline >= 0) + { + var lineEnd = scanFrom + newline; + HandleLine(buffer.AsMemory(start, lineEnd - start)); + start = scanFrom = lineEnd + 1; + continue; + } + + scanFrom = end; + + if (end - start > _options.MaxLineBytes) + { + throw new AcpProtocolViolationException( + $"The agent sent a line longer than {_options.MaxLineBytes} bytes without a newline; it is not speaking newline-delimited JSON."); + } + + if (start == end) + { + start = end = scanFrom = 0; + } + else if (end == buffer.Length) + { + if (start > 0) + { + // Slide the unfinished line to the front to make room. + Buffer.BlockCopy(buffer, start, buffer, 0, end - start); + end -= start; + scanFrom -= start; + start = 0; + } + else + { + // The line is longer than the buffer but still within the limit checked above. + Array.Resize(ref buffer, (int)Math.Min((long)buffer.Length * 2, (long)_options.MaxLineBytes + 1)); + } + } + + var read = await _input.ReadAsync(buffer.AsMemory(end), token).ConfigureAwait(false); + if (read == 0) + { + // EOF: a final line without a trailing newline still counts. + if (end > start) + HandleLine(buffer.AsMemory(start, end - start)); + break; + } + + end += read; + } + + Terminate(CreateClosedException(null)); + } + catch (OperationCanceledException) + { + Terminate(CreateClosedException(null)); + } + catch (AcpProtocolViolationException ex) + { + Terminate(ex); + } + catch (Exception ex) when (ex is IOException or ObjectDisposedException) + { + Terminate(CreateClosedException(ex)); + } + } + + private void HandleLine(ReadOnlyMemory line) + { + // Tolerate CRLF-terminated peers. + if (line.Length > 0 && line.Span[^1] == 0x0D) + line = line[..^1]; + + if (IsBlank(line.Span)) + return; + + JsonDocument document; + try + { + document = JsonDocument.Parse(line); + } + catch (JsonException) + { + OnUnparseable($"Skipped a line that is not valid JSON ({line.Length} bytes)."); + return; + } + + using (document) + { + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) + { + OnUnparseable("Skipped JSON that is not a JSON-RPC message object."); + return; + } + + _consecutiveParseErrors = 0; + Dispatch(root); + } + } + + private static bool IsBlank(ReadOnlySpan line) + { + foreach (var b in line) + { + if (b is not (0x20 or 0x09 or 0x0D or 0x0A)) + return false; + } + + return true; + } + + private void OnUnparseable(string message) + { + Diagnose(message); + if (++_consecutiveParseErrors >= _options.MaxConsecutiveParseErrors) + { + throw new AcpProtocolViolationException( + "The agent wrote non-protocol output to stdout (it must write only newline-delimited JSON-RPC there; logs belong on stderr)."); + } + } + + private void Dispatch(JsonElement root) + { + var hasId = root.TryGetProperty("id", out var idElement) && JsonRpcId.TryRead(idElement, out _); + var hasMethod = root.TryGetProperty("method", out var methodElement) && methodElement.ValueKind == JsonValueKind.String; + + if (hasMethod) + { + var method = methodElement.GetString()!; + JsonElement? parameters = root.TryGetProperty("params", out var p) ? p.Clone() : null; + + if (hasId) + { + JsonRpcId.TryRead(idElement, out var id); + StartRequestHandler(id, method, parameters); + } + else + { + QueueNotification(method, parameters); + } + + return; + } + + if (hasId && (root.TryGetProperty("result", out _) || root.TryGetProperty("error", out _))) + { + CompleteRequest(idElement, root); + return; + } + + Diagnose("Ignored a message that is neither a request, a notification nor a response."); + } + + private void CompleteRequest(JsonElement idElement, JsonElement root) + { + JsonRpcId.TryRead(idElement, out var id); + if (!id.TryGetInt64(out var numericId) || !_pending.TryRemove(numericId, out var tcs)) + { + Diagnose($"Ignored a response with unknown id {id}."); + return; + } + + if (root.TryGetProperty("error", out var error) && error.ValueKind == JsonValueKind.Object) + { + var code = error.TryGetProperty("code", out var c) && c.TryGetInt32(out var parsedCode) + ? parsedCode + : Protocol.AcpErrorCodes.InternalError; + var message = error.TryGetProperty("message", out var m) && m.ValueKind == JsonValueKind.String + ? m.GetString() ?? "" + : "The agent returned an error without a message."; + JsonElement? data = error.TryGetProperty("data", out var d) ? d.Clone() : null; + + tcs.TrySetException(new JsonRpcException(code, message, data)); + return; + } + + tcs.TrySetResult(root.TryGetProperty("result", out var result) ? result.Clone() : default); + } + + // ───────────────────────── incoming requests / notifications ───────────────────────── + + private void StartRequestHandler(JsonRpcId id, string method, JsonElement? parameters) + { + if (!_requestHandlers.TryGetValue(method, out var handler)) + { + Enqueue(writer => WriteErrorResponse(writer, id, Protocol.AcpErrorCodes.MethodNotFound, $"Method not found: {method}", null)); + return; + } + + var handlerId = Interlocked.Increment(ref _nextHandlerId); + var task = Task.Run(async () => + { + try + { + await RunRequestAsync(id, method, handler, parameters).ConfigureAwait(false); + } + finally + { + _runningHandlers.TryRemove(handlerId, out _); + } + }); + _runningHandlers[handlerId] = task; + } + + private async Task RunRequestAsync(JsonRpcId id, string method, RequestHandler handler, JsonElement? parameters) + { + Action write; + try + { + var writeResult = await handler(parameters, _lifetime.Token).ConfigureAwait(false); + write = writer => + { + writer.WriteStartObject(); + writer.WriteString("jsonrpc", "2.0"); + writer.WritePropertyName("id"); + id.WriteTo(writer); + writer.WritePropertyName("result"); + writeResult(writer); + writer.WriteEndObject(); + }; + } + catch (JsonRpcException ex) + { + write = writer => WriteErrorResponse(writer, id, ex.Code, ex.Message, ex.ErrorData); + } + catch (OperationCanceledException) + { + write = writer => WriteErrorResponse(writer, id, Protocol.AcpErrorCodes.RequestCancelled, "Request cancelled.", null); + } + catch (Exception ex) + { + Diagnose($"Handler for '{method}' failed: {ex.GetType().Name}: {ex.Message}"); + write = writer => WriteErrorResponse(writer, id, Protocol.AcpErrorCodes.InternalError, $"Internal error handling '{method}'.", null); + } + + try + { + Enqueue(write); + } + catch (AcpConnectionClosedException) + { + // The peer is gone; there is nobody to answer. + } + } + + private static void WriteErrorResponse(Utf8JsonWriter writer, JsonRpcId id, int code, string message, JsonElement? data) + { + writer.WriteStartObject(); + writer.WriteString("jsonrpc", "2.0"); + writer.WritePropertyName("id"); + id.WriteTo(writer); + writer.WritePropertyName("error"); + writer.WriteStartObject(); + writer.WriteNumber("code", code); + writer.WriteString("message", message); + if (data is { } value) + { + writer.WritePropertyName("data"); + value.WriteTo(writer); + } + + writer.WriteEndObject(); + writer.WriteEndObject(); + } + + private void QueueNotification(string method, JsonElement? parameters) + { + if (!_notificationHandlers.TryGetValue(method, out var handler)) + { + Diagnose($"Ignored notification '{method}' (no handler)."); + return; + } + + _notifications.Writer.TryWrite(new NotificationWork(handler, parameters, null)); + } + + private async Task NotificationLoopAsync() + { + await foreach (var work in _notifications.Reader.ReadAllAsync().ConfigureAwait(false)) + { + if (work.Marker is not null) + { + work.Marker.TrySetResult(); + continue; + } + + try + { + await work.Handler!(work.Parameters).ConfigureAwait(false); + } + catch (Exception ex) + { + // One misbehaving notification must not stop the ones behind it. + Diagnose($"A notification handler failed: {ex.GetType().Name}: {ex.Message}"); + } + } + } + + // ───────────────────────── shutdown ───────────────────────── + + private void ThrowIfClosed() + { + if (Volatile.Read(ref _terminated) != 0) + throw ClosedException(); + } + + private AcpConnectionClosedException ClosedException() => + Volatile.Read(ref _closeReason) as AcpConnectionClosedException + ?? new AcpConnectionClosedException( + Volatile.Read(ref _closeReason)?.Message ?? "The connection to the agent is closed.", + inner: Volatile.Read(ref _closeReason)); + + private AcpConnectionClosedException CreateClosedException(Exception? inner) + { + var described = _options.DescribeClose?.Invoke(); + if (described is not null) + return described; + + return new AcpConnectionClosedException( + inner is null ? "The agent closed the connection." : $"The connection to the agent failed: {inner.Message}", + inner: inner); + } + + private void Terminate(Exception reason) + { + if (Interlocked.Exchange(ref _terminated, 1) != 0) + return; + + Volatile.Write(ref _closeReason, reason); + _outbound.Writer.TryComplete(); + _notifications.Writer.TryComplete(); + FailPending(); + + try { _lifetime.Cancel(); } catch (ObjectDisposedException) { } + + if (reason is AcpProtocolViolationException) + _completion.TrySetException(reason); + else + _completion.TrySetResult(); + } + + private void FailPending() + { + var reason = ClosedException(); + foreach (var id in _pending.Keys) + { + if (_pending.TryRemove(id, out var tcs)) + tcs.TrySetException(reason); + } + } + + private void Diagnose(string message) => _options.Diagnostics?.Invoke(message); + + public async ValueTask DisposeAsync() + { + Terminate(new AcpConnectionClosedException("The connection was disposed.")); + + var work = Task.WhenAll(_readLoop, _writeLoop, _notificationLoop, Task.WhenAll(_runningHandlers.Values)); + await Task.WhenAny(work, Task.Delay(TimeSpan.FromSeconds(2))).ConfigureAwait(false); + + _lifetime.Dispose(); + } +} diff --git a/src/MandoCode.Acp/JsonRpc/JsonRpcId.cs b/src/MandoCode.Acp/JsonRpc/JsonRpcId.cs new file mode 100644 index 0000000..9b13f7d --- /dev/null +++ b/src/MandoCode.Acp/JsonRpc/JsonRpcId.cs @@ -0,0 +1,68 @@ +using System.Globalization; +using System.Text.Json; + +namespace MandoCode.Acp.JsonRpc; + +/// +/// A JSON-RPC request id: a number or a string. Incoming ids are kept exactly as received so the +/// response echoes them unchanged (a peer may use string ids even though this client sends numbers). +/// +public readonly struct JsonRpcId : IEquatable +{ + private readonly string? _raw; + + private JsonRpcId(string raw, bool isString) + { + _raw = raw; + IsString = isString; + } + + public bool IsString { get; } + + /// The id as text: the string value, or the number's literal text. + public string Text => _raw ?? ""; + + public static JsonRpcId FromNumber(long value) => new(value.ToString(CultureInfo.InvariantCulture), false); + + public static JsonRpcId FromString(string value) => new(value, true); + + /// Reads an id from a message; returns false for a missing, null or non-scalar id. + public static bool TryRead(JsonElement element, out JsonRpcId id) + { + switch (element.ValueKind) + { + case JsonValueKind.Number: + id = new JsonRpcId(element.GetRawText(), false); + return true; + case JsonValueKind.String: + id = new JsonRpcId(element.GetString() ?? "", true); + return true; + default: + id = default; + return false; + } + } + + /// The id as a long, if it is an integral number (the only kind this client sends). + public bool TryGetInt64(out long value) + { + if (!IsString && long.TryParse(_raw, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out value)) + return true; + + value = 0; + return false; + } + + public void WriteTo(Utf8JsonWriter writer) + { + if (IsString) + writer.WriteStringValue(_raw); + else + writer.WriteRawValue(_raw ?? "0"); + } + + public bool Equals(JsonRpcId other) => IsString == other.IsString && string.Equals(_raw, other._raw, StringComparison.Ordinal); + public override bool Equals(object? obj) => obj is JsonRpcId other && Equals(other); + public override int GetHashCode() => HashCode.Combine(IsString, _raw); + public override string ToString() => IsString ? $"\"{_raw}\"" : _raw ?? ""; +} diff --git a/src/MandoCode.Acp/README.md b/src/MandoCode.Acp/README.md index cd0c605..1af173d 100644 --- a/src/MandoCode.Acp/README.md +++ b/src/MandoCode.Acp/README.md @@ -5,7 +5,7 @@ over stdio (newline-delimited JSON-RPC 2.0). - No third-party ACP libraries; DTOs are hand-written against the official JSON schema. - `System.Text.Json` source generation (`AcpJsonContext`), no reflection-based serialization. -- Targets `net8.0` and `net10.0`. +- Targets `net8.0` and `net10.0`; depends only on the BCL (no NuGet packages). ## Schema @@ -23,3 +23,18 @@ run the tests and update the tag here and in `AcpProtocol.SchemaTag`. - "Enum" values (stop reasons, tool kinds, statuses, ...) are plain strings with constant classes, so values added by newer agents never break parsing. - Features are decided from the capabilities the agent returns from `initialize`. + +## JSON-RPC layer + +`JsonRpc/JsonRpcConnection` runs JSON-RPC 2.0 over a pair of streams (the agent's stdout/stdin): + +- one message per line (` +`, a trailing ` ` is dropped, blank lines are skipped); a line over + 32 MB, or several consecutive non-JSON lines, break the connection with an explanation; +- outgoing ids are numbers; incoming ids (number or string) are echoed back unchanged; +- the reader never waits on a handler: each incoming request runs on its own task, so a + permission prompt can be pending while `session/prompt` is still in flight; +- incoming notifications are handled by one consumer, in order. A response is dispatched as soon + as it is read, so callers that must see every `session/update` that preceded it await + `DrainNotificationsAsync()` first; +- unknown methods get `-32601`, bad params `-32602`, handler failures `-32603` (without details). diff --git a/tests/MandoCode.Tests/Acp/AcpTestKit.cs b/tests/MandoCode.Tests/Acp/AcpTestKit.cs new file mode 100644 index 0000000..58273fe --- /dev/null +++ b/tests/MandoCode.Tests/Acp/AcpTestKit.cs @@ -0,0 +1,133 @@ +using System.Text; +using System.Text.Json; +using System.Threading.Channels; +using MandoCode.Acp.JsonRpc; +using Xunit; + +namespace MandoCode.Tests.Acp; + +/// One-directional in-memory byte pipe: what one side writes, the other reads. Completing it is EOF. +internal sealed class BytePipe : Stream +{ + private readonly Channel _chunks = Channel.CreateUnbounded(); + private byte[]? _current; + private int _position; + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public void CompleteWriting() => _chunks.Writer.TryComplete(); + + public override void Write(byte[] buffer, int offset, int count) => + _chunks.Writer.TryWrite(buffer.AsSpan(offset, count).ToArray()); + + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + if (!_chunks.Writer.TryWrite(buffer.ToArray())) + throw new IOException("The pipe is closed."); + return ValueTask.CompletedTask; + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + while (_current is null || _position >= _current.Length) + { + if (!await _chunks.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false)) + return 0; + + if (_chunks.Reader.TryRead(out var next)) + { + _current = next; + _position = 0; + } + } + + var count = Math.Min(buffer.Length, _current.Length - _position); + _current.AsSpan(_position, count).CopyTo(buffer.Span); + _position += count; + return count; + } + + public override int Read(byte[] buffer, int offset, int count) => + ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult(); + + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); +} + +/// +/// The agent's side of an in-memory connection. The client under test reads +/// and writes ; tests drive the agent by hand. +/// +internal sealed class FakeAgentPeer : IDisposable +{ + public BytePipe ToClient { get; } = new(); + public BytePipe FromClient { get; } = new(); + + private readonly StreamReader _reader; + + public FakeAgentPeer() => _reader = new StreamReader(FromClient, new UTF8Encoding(false)); + + public JsonRpcConnection CreateConnection(JsonRpcConnectionOptions? options = null) => + new(ToClient, FromClient, options); + + /// Reads the next line the client wrote, parsed as JSON. + public async Task ReadMessageAsync() + { + var line = await _reader.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(5)); + Assert.NotNull(line); + Assert.DoesNotContain('\n', line); + using var doc = JsonDocument.Parse(line!); + return doc.RootElement.Clone(); + } + + public async Task ReadRawLineAsync() => + await _reader.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(5)); + + public void SendLine(string json) => SendRaw(json + "\n"); + + public void SendRaw(string text) => ToClient.Write(Encoding.UTF8.GetBytes(text), 0, Encoding.UTF8.GetByteCount(text)); + + public void SendRawInChunks(string text, int chunkSize) + { + var bytes = Encoding.UTF8.GetBytes(text); + for (var i = 0; i < bytes.Length; i += chunkSize) + ToClient.Write(bytes, i, Math.Min(chunkSize, bytes.Length - i)); + } + + public void SendResult(JsonElement requestId, string resultJson) => + SendLine("{\"jsonrpc\":\"2.0\",\"id\":" + requestId.GetRawText() + ",\"result\":" + resultJson + "}"); + + public void SendError(JsonElement requestId, int code, string message, string? dataJson = null) => + SendLine("{\"jsonrpc\":\"2.0\",\"id\":" + requestId.GetRawText() + + ",\"error\":{\"code\":" + code + ",\"message\":\"" + message + "\"" + + (dataJson is null ? "" : ",\"data\":" + dataJson) + "}}"); + + /// A session/update notification carrying an agent text chunk. + public static string ChunkNotification(string text) => + "{\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"s\",\"update\":" + + "{\"sessionUpdate\":\"agent_message_chunk\",\"content\":{\"type\":\"text\",\"text\":\"" + text + "\"}}}}"; + + /// Ends the agent's stdout: the client sees EOF. + public void CloseOutput() => ToClient.CompleteWriting(); + + public void Dispose() + { + ToClient.CompleteWriting(); + FromClient.CompleteWriting(); + _reader.Dispose(); + } +} + +internal static class TaskExtensions +{ + public static async Task Within(this Task task, int seconds = 5) => + await task.WaitAsync(TimeSpan.FromSeconds(seconds)); + + public static async Task Within(this Task task, int seconds = 5) => + await task.WaitAsync(TimeSpan.FromSeconds(seconds)); +} diff --git a/tests/MandoCode.Tests/Acp/JsonRpcConnectionTests.cs b/tests/MandoCode.Tests/Acp/JsonRpcConnectionTests.cs new file mode 100644 index 0000000..4e907f4 --- /dev/null +++ b/tests/MandoCode.Tests/Acp/JsonRpcConnectionTests.cs @@ -0,0 +1,576 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using MandoCode.Acp; +using MandoCode.Acp.JsonRpc; +using MandoCode.Acp.Protocol; +using Xunit; + +namespace MandoCode.Tests.Acp; + +public class JsonRpcIdTests +{ + [Fact] + public void NumberAndStringIds_RoundTripUnchanged() + { + using var doc = JsonDocument.Parse("""{"n":7,"s":"abc-7","big":9007199254740993}"""); + Assert.True(JsonRpcId.TryRead(doc.RootElement.GetProperty("n"), out var number)); + Assert.True(JsonRpcId.TryRead(doc.RootElement.GetProperty("s"), out var text)); + Assert.True(JsonRpcId.TryRead(doc.RootElement.GetProperty("big"), out var big)); + + Assert.False(number.IsString); + Assert.True(number.TryGetInt64(out var n)); + Assert.Equal(7, n); + + Assert.True(text.IsString); + Assert.False(text.TryGetInt64(out _)); + + Assert.True(big.TryGetInt64(out var b)); + Assert.Equal(9007199254740993, b); + + Assert.Equal("7", Write(number)); + Assert.Equal("\"abc-7\"", Write(text)); + } + + [Fact] + public void StringId_ThatLooksNumeric_IsNotConfusedWithANumber() + { + Assert.NotEqual(JsonRpcId.FromNumber(1), JsonRpcId.FromString("1")); + Assert.False(JsonRpcId.FromString("1").TryGetInt64(out _)); + } + + [Theory] + [InlineData("null")] + [InlineData("true")] + [InlineData("{}")] + public void NonScalarIds_AreRejected(string json) + { + using var doc = JsonDocument.Parse(json); + Assert.False(JsonRpcId.TryRead(doc.RootElement, out _)); + } + + private static string Write(JsonRpcId id) + { + using var stream = new MemoryStream(); + using (var writer = new Utf8JsonWriter(stream)) + id.WriteTo(writer); + return System.Text.Encoding.UTF8.GetString(stream.ToArray()); + } +} + +public class JsonRpcConnectionTests +{ + private static InitializeRequest Init() => new() { ClientInfo = new Implementation { Name = "t", Version = "1" } }; + + private static Task SendInitialize(JsonRpcConnection c, CancellationToken ct = default) => + c.SendRequestAsync(AcpMethods.Initialize, Init(), AcpJsonContext.Default.InitializeRequest, + AcpJsonContext.Default.InitializeResponse, ct); + + // ───────────── correlation ───────────── + + [Fact] + public async Task Request_IsCorrelatedWithItsResponse() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + var pending = SendInitialize(connection); + var message = await peer.ReadMessageAsync(); + + Assert.Equal("2.0", message.GetProperty("jsonrpc").GetString()); + Assert.Equal("initialize", message.GetProperty("method").GetString()); + Assert.Equal(1, message.GetProperty("params").GetProperty("protocolVersion").GetInt32()); + + peer.SendResult(message.GetProperty("id"), """{"protocolVersion":1,"agentInfo":{"name":"a","version":"2"}}"""); + + var response = await pending.Within(); + Assert.Equal("a", response.AgentInfo!.Name); + } + + [Fact] + public async Task ParallelRequests_GetUniqueIds_AndOutOfOrderResponsesReachTheRightCaller() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + var first = connection.SendRequestAsync(AcpMethods.SessionPrompt, + new PromptRequest { SessionId = "s", Prompt = [new TextContent("one")] }, + AcpJsonContext.Default.PromptRequest, AcpJsonContext.Default.PromptResponse); + var second = connection.SendRequestAsync(AcpMethods.SessionPrompt, + new PromptRequest { SessionId = "s", Prompt = [new TextContent("two")] }, + AcpJsonContext.Default.PromptRequest, AcpJsonContext.Default.PromptResponse); + + var m1 = await peer.ReadMessageAsync(); + var m2 = await peer.ReadMessageAsync(); + Assert.NotEqual(m1.GetProperty("id").GetInt64(), m2.GetProperty("id").GetInt64()); + + // Answer in reverse order of arrival. + peer.SendResult(m2.GetProperty("id"), """{"stopReason":"refusal"}"""); + peer.SendResult(m1.GetProperty("id"), """{"stopReason":"end_turn"}"""); + + var firstText = m1.GetProperty("params").GetProperty("prompt")[0].GetProperty("text").GetString(); + var expectedFirst = firstText == "one" ? "end_turn" : "refusal"; + Assert.Equal(expectedFirst, (await first.Within()).StopReason); + Assert.Equal(expectedFirst == "end_turn" ? "refusal" : "end_turn", (await second.Within()).StopReason); + } + + [Fact] + public async Task ErrorResponse_BecomesJsonRpcException_WithCodeAndData() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + var pending = SendInitialize(connection); + var message = await peer.ReadMessageAsync(); + peer.SendError(message.GetProperty("id"), AcpErrorCodes.AuthRequired, "Authentication required", """{"hint":"login"}"""); + + var ex = await Assert.ThrowsAsync(() => pending.Within()); + Assert.Equal(AcpErrorCodes.AuthRequired, ex.Code); + Assert.Equal("Authentication required", ex.Message); + Assert.Equal("login", ex.ErrorData!.Value.GetProperty("hint").GetString()); + } + + [Fact] + public async Task ResponseWithUnknownId_IsIgnored() + { + using var peer = new FakeAgentPeer(); + var diagnostics = new ConcurrentQueue(); + await using var connection = peer.CreateConnection(new JsonRpcConnectionOptions { Diagnostics = diagnostics.Enqueue }); + + peer.SendLine("""{"jsonrpc":"2.0","id":999,"result":{}}"""); + + var pending = SendInitialize(connection); + var message = await peer.ReadMessageAsync(); + peer.SendResult(message.GetProperty("id"), """{"protocolVersion":1}"""); + + Assert.Equal(1, (await pending.Within()).ProtocolVersion); + Assert.Contains(diagnostics, d => d.Contains("unknown id")); + } + + [Fact] + public async Task CancellingTheToken_CancelsTheRequest_AndALateResponseIsHarmless() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + using var cts = new CancellationTokenSource(); + + var pending = SendInitialize(connection, cts.Token); + var message = await peer.ReadMessageAsync(); + + cts.Cancel(); + await Assert.ThrowsAnyAsync(() => pending.Within()); + + peer.SendResult(message.GetProperty("id"), """{"protocolVersion":1}"""); + + var second = SendInitialize(connection); + var next = await peer.ReadMessageAsync(); + peer.SendResult(next.GetProperty("id"), """{"protocolVersion":1}"""); + Assert.Equal(1, (await second.Within()).ProtocolVersion); + } + + // ───────────── framing ───────────── + + [Fact] + public async Task EachMessage_IsExactlyOneLine_EvenWithNewlinesInText() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + _ = connection.SendRequestAsync(AcpMethods.SessionPrompt, + new PromptRequest { SessionId = "s", Prompt = [new TextContent("line1\nline2\r\nline3")] }, + AcpJsonContext.Default.PromptRequest, AcpJsonContext.Default.PromptResponse); + + var raw = await peer.ReadRawLineAsync(); + Assert.NotNull(raw); + using var doc = JsonDocument.Parse(raw!); + Assert.Equal("line1\nline2\r\nline3", + doc.RootElement.GetProperty("params").GetProperty("prompt")[0].GetProperty("text").GetString()); + } + + [Fact] + public async Task FragmentedCrlfAndBlankLines_AreHandled() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + var pending = SendInitialize(connection); + var message = await peer.ReadMessageAsync(); + var id = message.GetProperty("id").GetRawText(); + + // Blank lines, a CRLF terminator, and a body split into 3-byte reads. + peer.SendRaw("\n\r\n \n"); + peer.SendRawInChunks($$$"""{"jsonrpc":"2.0","id":{{{id}}},"result":{"protocolVersion":1}}""" + "\r\n", 3); + + Assert.Equal(1, (await pending.Within()).ProtocolVersion); + } + + [Fact] + public async Task FinalLineWithoutNewline_IsStillDelivered_BeforeEof() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + var pending = SendInitialize(connection); + var message = await peer.ReadMessageAsync(); + + peer.SendRaw($$$"""{"jsonrpc":"2.0","id":{{{message.GetProperty("id").GetRawText()}}},"result":{"protocolVersion":1}}"""); + peer.CloseOutput(); + + Assert.Equal(1, (await pending.Within()).ProtocolVersion); + } + + [Fact] + public async Task LargeMessages_AreReassembled() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + var pending = SendInitialize(connection); + var message = await peer.ReadMessageAsync(); + + var padding = new string('x', 300_000); + peer.SendResult(message.GetProperty("id"), "{\"protocolVersion\":1,\"agentInfo\":{\"name\":\"" + padding + "\",\"version\":\"1\"}}"); + + Assert.Equal(300_000, (await pending.Within()).AgentInfo!.Name.Length); + } + + [Fact] + public async Task OverlongLine_BreaksTheConnection_WithAProtocolViolation() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(new JsonRpcConnectionOptions { MaxLineBytes = 4096 }); + + var pending = SendInitialize(connection); + await peer.ReadMessageAsync(); + + peer.SendRaw(new string('a', 10_000)); + + await Assert.ThrowsAsync(() => connection.Completion.Within()); + await Assert.ThrowsAsync(() => pending.Within()); + } + + [Fact] + public async Task RepeatedNonJsonOutput_BreaksTheConnection_WithAnExplanation() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(new JsonRpcConnectionOptions { MaxConsecutiveParseErrors = 3 }); + + var pending = SendInitialize(connection); + await peer.ReadMessageAsync(); + + peer.SendLine("[info] starting up"); + peer.SendLine("Listening on stdio"); + peer.SendLine("123"); + + var violation = await Assert.ThrowsAsync(() => connection.Completion.Within()); + Assert.Contains("stdout", violation.Message); + var closed = await Assert.ThrowsAsync(() => pending.Within()); + Assert.IsType(closed.InnerException); + } + + [Fact] + public async Task SingleGarbageLine_IsSkipped_AndTheCounterResets() + { + using var peer = new FakeAgentPeer(); + var diagnostics = new ConcurrentQueue(); + await using var connection = peer.CreateConnection(new JsonRpcConnectionOptions + { + MaxConsecutiveParseErrors = 2, + Diagnostics = diagnostics.Enqueue, + }); + + var pending = SendInitialize(connection); + var message = await peer.ReadMessageAsync(); + var id = message.GetProperty("id").GetRawText(); + + peer.SendLine("some banner"); + peer.SendLine("""{"jsonrpc":"2.0","method":"noise","params":{}}"""); + peer.SendLine("another banner"); + peer.SendLine($$$"""{"jsonrpc":"2.0","id":{{{id}}},"result":{"protocolVersion":1}}"""); + + Assert.Equal(1, (await pending.Within()).ProtocolVersion); + Assert.False(connection.Completion.IsCompleted); + Assert.Equal(2, diagnostics.Count(d => d.Contains("not valid JSON"))); + } + + // ───────────── incoming requests ───────────── + + [Fact] + public async Task IncomingRequest_DoesNotBlockTheReader_WhilePermissionIsPending() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + var userDecision = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var handlerStarted = new TaskCompletionSource(); + connection.RegisterRequestHandler( + AcpMethods.SessionRequestPermission, + AcpJsonContext.Default.RequestPermissionRequest, + AcpJsonContext.Default.RequestPermissionResponse, + async (request, _) => + { + handlerStarted.TrySetResult(); + var optionId = await userDecision.Task; + return new RequestPermissionResponse { Outcome = new SelectedPermissionOutcome { OptionId = optionId } }; + }); + + // session/prompt is in flight... + var prompt = connection.SendRequestAsync(AcpMethods.SessionPrompt, + new PromptRequest { SessionId = "s", Prompt = [new TextContent("go")] }, + AcpJsonContext.Default.PromptRequest, AcpJsonContext.Default.PromptResponse); + var promptMessage = await peer.ReadMessageAsync(); + + // ...and the agent asks for permission (string id on purpose) before answering it. + peer.SendLine(""" + {"jsonrpc":"2.0","id":"perm-1","method":"session/request_permission","params":{"sessionId":"s", + "toolCall":{"toolCallId":"c","title":"Edit"},"options":[{"optionId":"allow","name":"Allow","kind":"allow_once"}]}} + """.ReplaceLineEndings(" ")); + await handlerStarted.Task.Within(); + + // The reader is still live: the prompt response is processed while the handler waits. + peer.SendResult(promptMessage.GetProperty("id"), """{"stopReason":"end_turn"}"""); + Assert.Equal("end_turn", (await prompt.Within()).StopReason); + + userDecision.SetResult("allow"); + var answer = await peer.ReadMessageAsync(); + Assert.Equal(JsonValueKind.String, answer.GetProperty("id").ValueKind); + Assert.Equal("perm-1", answer.GetProperty("id").GetString()); + Assert.Equal("selected", answer.GetProperty("result").GetProperty("outcome").GetProperty("outcome").GetString()); + Assert.Equal("allow", answer.GetProperty("result").GetProperty("outcome").GetProperty("optionId").GetString()); + } + + [Fact] + public async Task UnknownMethod_GetsMethodNotFound() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + peer.SendLine("""{"jsonrpc":"2.0","id":5,"method":"terminal/create","params":{}}"""); + + var reply = await peer.ReadMessageAsync(); + Assert.Equal(5, reply.GetProperty("id").GetInt32()); + Assert.Equal(AcpErrorCodes.MethodNotFound, reply.GetProperty("error").GetProperty("code").GetInt32()); + } + + [Fact] + public async Task InvalidParams_GetInvalidParams() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + connection.RegisterRequestHandler(AcpMethods.FsReadTextFile, + AcpJsonContext.Default.ReadTextFileRequest, AcpJsonContext.Default.ReadTextFileResponse, + (_, _) => ValueTask.FromResult(new ReadTextFileResponse { Content = "x" })); + + peer.SendLine("""{"jsonrpc":"2.0","id":1,"method":"fs/read_text_file","params":{"path":{"not":"a string"}}}"""); + Assert.Equal(AcpErrorCodes.InvalidParams, + (await peer.ReadMessageAsync()).GetProperty("error").GetProperty("code").GetInt32()); + + peer.SendLine("""{"jsonrpc":"2.0","id":2,"method":"fs/read_text_file"}"""); + Assert.Equal(AcpErrorCodes.InvalidParams, + (await peer.ReadMessageAsync()).GetProperty("error").GetProperty("code").GetInt32()); + } + + [Fact] + public async Task HandlerFailures_MapToErrorResponses_WithoutLeakingDetails() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + connection.RegisterRequestHandler(AcpMethods.FsReadTextFile, + AcpJsonContext.Default.ReadTextFileRequest, AcpJsonContext.Default.ReadTextFileResponse, + (request, _) => request.Path switch + { + "missing" => throw new JsonRpcException(AcpErrorCodes.ResourceNotFound, "No such file"), + _ => throw new InvalidOperationException("secret internal detail"), + }); + + peer.SendLine("""{"jsonrpc":"2.0","id":1,"method":"fs/read_text_file","params":{"sessionId":"s","path":"missing"}}"""); + var notFound = (await peer.ReadMessageAsync()).GetProperty("error"); + Assert.Equal(AcpErrorCodes.ResourceNotFound, notFound.GetProperty("code").GetInt32()); + Assert.Equal("No such file", notFound.GetProperty("message").GetString()); + + peer.SendLine("""{"jsonrpc":"2.0","id":2,"method":"fs/read_text_file","params":{"sessionId":"s","path":"boom"}}"""); + var internalError = (await peer.ReadMessageAsync()).GetProperty("error"); + Assert.Equal(AcpErrorCodes.InternalError, internalError.GetProperty("code").GetInt32()); + Assert.DoesNotContain("secret", internalError.GetProperty("message").GetString()); + } + + // ───────────── notifications ───────────── + + [Fact] + public async Task Notifications_AreHandledInOrder_AndDrainWaitsForThem() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + var seen = new List(); + connection.RegisterNotificationHandler(AcpMethods.SessionUpdate, AcpJsonContext.Default.SessionNotification, + async n => + { + await Task.Delay(1); // yield so an unordered consumer would interleave + lock (seen) + seen.Add(((AgentMessageChunk)n.Update).Content is TextContent t ? t.Text : "?"); + }); + + for (var i = 0; i < 40; i++) + { + peer.SendLine(FakeAgentPeer.ChunkNotification(i.ToString())); + } + + var pending = SendInitialize(connection); + var message = await peer.ReadMessageAsync(); + peer.SendResult(message.GetProperty("id"), """{"protocolVersion":1}"""); + await pending.Within(); + + await connection.DrainNotificationsAsync().Within(); + + lock (seen) + Assert.Equal(Enumerable.Range(0, 40).Select(i => i.ToString()), seen); + } + + [Fact] + public async Task FailingNotificationHandler_DoesNotStopLaterNotifications() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + var seen = new ConcurrentQueue(); + connection.RegisterNotificationHandler(AcpMethods.SessionUpdate, AcpJsonContext.Default.SessionNotification, + n => + { + var text = ((TextContent)((AgentMessageChunk)n.Update).Content).Text; + if (text == "bad") + throw new InvalidOperationException("boom"); + seen.Enqueue(text); + return ValueTask.CompletedTask; + }); + + foreach (var text in new[] { "a", "bad", "b" }) + peer.SendLine(FakeAgentPeer.ChunkNotification(text)); + + // A response that follows the notifications proves the reader has dispatched all of them + // (DrainNotificationsAsync only covers notifications that were already received). + var pending = SendInitialize(connection); + var message = await peer.ReadMessageAsync(); + peer.SendResult(message.GetProperty("id"), """{"protocolVersion":1}"""); + await pending.Within(); + + await connection.DrainNotificationsAsync().Within(); + Assert.Equal(["a", "b"], seen.ToArray()); + } + + [Fact] + public async Task NotificationWithoutHandler_IsIgnored() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + peer.SendLine("""{"jsonrpc":"2.0","method":"_vendor/thing","params":{"a":1}}"""); + await connection.DrainNotificationsAsync().Within(); + Assert.False(connection.Completion.IsCompleted); + } + + [Fact] + public async Task OutgoingNotification_HasNoId() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + await connection.SendNotificationAsync(AcpMethods.SessionCancel, + new CancelNotification { SessionId = "s1" }, AcpJsonContext.Default.CancelNotification); + + var message = await peer.ReadMessageAsync(); + Assert.Equal("session/cancel", message.GetProperty("method").GetString()); + Assert.False(message.TryGetProperty("id", out _)); + Assert.Equal("s1", message.GetProperty("params").GetProperty("sessionId").GetString()); + } + + // ───────────── shutdown ───────────── + + [Fact] + public async Task Eof_FailsEveryPendingRequest_AndLaterSendsFailFast() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + var a = SendInitialize(connection); + var b = SendInitialize(connection); + await peer.ReadMessageAsync(); + await peer.ReadMessageAsync(); + + peer.CloseOutput(); + + await Assert.ThrowsAsync(() => a.Within()); + await Assert.ThrowsAsync(() => b.Within()); + await connection.Completion.Within(); + await Assert.ThrowsAsync(() => SendInitialize(connection)); + } + + [Fact] + public async Task Eof_UsesTheTransportsDescription_ForExitCodeAndStderr() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(new JsonRpcConnectionOptions + { + DescribeClose = () => new AcpConnectionClosedException("agent exited", exitCode: 3, stderrTail: "fatal: no login"), + }); + + var pending = SendInitialize(connection); + await peer.ReadMessageAsync(); + peer.CloseOutput(); + + var ex = await Assert.ThrowsAsync(() => pending.Within()); + Assert.Equal(3, ex.ExitCode); + Assert.Equal("fatal: no login", ex.StderrTail); + } + + [Fact] + public async Task WriteFailure_ClosesTheConnection() + { + using var peer = new FakeAgentPeer(); + await using var connection = peer.CreateConnection(); + + peer.FromClient.CompleteWriting(); // the agent's stdin is gone: writes now throw IOException + + var pending = SendInitialize(connection); + await Assert.ThrowsAsync(() => pending.Within()); + } + + [Fact] + public async Task Dispose_FailsPending_AndIsIdempotent() + { + using var peer = new FakeAgentPeer(); + var connection = peer.CreateConnection(); + + var pending = SendInitialize(connection); + await peer.ReadMessageAsync(); + + await connection.DisposeAsync(); + await connection.DisposeAsync(); + + await Assert.ThrowsAsync(() => pending.Within()); + await connection.Completion.Within(); + } + + [Fact] + public async Task Dispose_CancelsRunningHandlers() + { + using var peer = new FakeAgentPeer(); + var connection = peer.CreateConnection(); + + var cancelled = new TaskCompletionSource(); + connection.RegisterRequestHandler(AcpMethods.FsReadTextFile, + AcpJsonContext.Default.ReadTextFileRequest, AcpJsonContext.Default.ReadTextFileResponse, + async (_, ct) => + { + try { await Task.Delay(Timeout.Infinite, ct); } + catch (OperationCanceledException) { cancelled.SetResult(); throw; } + return new ReadTextFileResponse(); + }); + + peer.SendLine("""{"jsonrpc":"2.0","id":1,"method":"fs/read_text_file","params":{"sessionId":"s","path":"/x"}}"""); + await Task.Delay(50); + + await connection.DisposeAsync(); + await cancelled.Task.Within(); + } +} From 4228c6a72ef78d20e8f3be85266a1c7305cd9944 Mon Sep 17 00:00:00 2001 From: TeseySTD Date: Tue, 10 Nov 2026 13:30:12 +0200 Subject: [PATCH 03/26] feat(acp): add process transport, command resolver and mock agent Launch agents as subprocesses without ever involving a shell. - AcpProcessTransport: UseShellExecute=false + ArgumentList, redirected stdio, stdout used for protocol only, stderr drained into StderrLog (ring buffer + optional rotated file, never the console). Shutdown closes stdin, waits a grace period, then kills the process tree; a ProcessExit hook kills leftovers. DescribeCloseAsync attaches the exit code and stderr tail to connection-closed errors. - AcpCommandResolver: the configured command must resolve to a real native executable (.exe with a PE header on Windows, ELF/Mach-O on Unix). .cmd/.bat/.ps1 shims and shebang scripts are rejected with an explanation; npx-style downloaders and shells are forbidden; relative PATH entries are ignored; for node the first argument must be an absolute path to an existing script. The resolved absolute path is what gets executed. - AcpEnvironment: drops ANTHROPIC_API_KEY unless the entry opts in, then applies the entry's env on top. - JsonRpcConnection.DescribeClose is now async because the exit code can lag the stdout EOF. - tests/MandoCode.Acp.MockAgent: scriptable fake agent (echo, env/args reporting, exit-immediately, stderr-flood, stdout-garbage, hang-on-shutdown with a child process). - Tests: resolver rules against a fake machine on any host, environment and log units, and integration tests with a real subprocess covering argument fidelity, env, stderr flood, garbage stdout, polite shutdown and tree kill. --- MandoCode.sln | 15 + src/MandoCode.Acp/AcpExceptions.cs | 31 ++ .../JsonRpc/JsonRpcConnection.cs | 29 +- src/MandoCode.Acp/README.md | 20 + .../Transport/AcpCommandResolver.cs | 316 ++++++++++++++ src/MandoCode.Acp/Transport/AcpEnvironment.cs | 54 +++ src/MandoCode.Acp/Transport/AcpLaunchSpec.cs | 16 + .../Transport/AcpProcessTransport.cs | 258 ++++++++++++ src/MandoCode.Acp/Transport/IAcpTransport.cs | 55 +++ src/MandoCode.Acp/Transport/StderrLog.cs | 102 +++++ .../MandoCode.Acp.MockAgent.csproj | 16 + tests/MandoCode.Acp.MockAgent/Program.cs | 174 ++++++++ .../Acp/AcpProcessTransportTests.cs | 322 ++++++++++++++ .../Acp/AcpTransportUnitTests.cs | 397 ++++++++++++++++++ .../Acp/JsonRpcConnectionTests.cs | 2 +- tests/MandoCode.Tests/MandoCode.Tests.csproj | 2 + 16 files changed, 1798 insertions(+), 11 deletions(-) create mode 100644 src/MandoCode.Acp/Transport/AcpCommandResolver.cs create mode 100644 src/MandoCode.Acp/Transport/AcpEnvironment.cs create mode 100644 src/MandoCode.Acp/Transport/AcpLaunchSpec.cs create mode 100644 src/MandoCode.Acp/Transport/AcpProcessTransport.cs create mode 100644 src/MandoCode.Acp/Transport/IAcpTransport.cs create mode 100644 src/MandoCode.Acp/Transport/StderrLog.cs create mode 100644 tests/MandoCode.Acp.MockAgent/MandoCode.Acp.MockAgent.csproj create mode 100644 tests/MandoCode.Acp.MockAgent/Program.cs create mode 100644 tests/MandoCode.Tests/Acp/AcpProcessTransportTests.cs create mode 100644 tests/MandoCode.Tests/Acp/AcpTransportUnitTests.cs diff --git a/MandoCode.sln b/MandoCode.sln index ec5085e..30be3dd 100644 --- a/MandoCode.sln +++ b/MandoCode.sln @@ -13,6 +13,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MandoCode.Tests", "tests\Ma EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MandoCode.Acp", "src\MandoCode.Acp\MandoCode.Acp.csproj", "{4AD6649A-5B01-4BE5-A335-534B80F80C5C}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MandoCode.Acp.MockAgent", "tests\MandoCode.Acp.MockAgent\MandoCode.Acp.MockAgent.csproj", "{987F2544-BD32-4447-B850-BA91D1AF8FE8}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -59,6 +61,18 @@ Global {4AD6649A-5B01-4BE5-A335-534B80F80C5C}.Release|x64.Build.0 = Release|Any CPU {4AD6649A-5B01-4BE5-A335-534B80F80C5C}.Release|x86.ActiveCfg = Release|Any CPU {4AD6649A-5B01-4BE5-A335-534B80F80C5C}.Release|x86.Build.0 = Release|Any CPU + {987F2544-BD32-4447-B850-BA91D1AF8FE8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {987F2544-BD32-4447-B850-BA91D1AF8FE8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {987F2544-BD32-4447-B850-BA91D1AF8FE8}.Debug|x64.ActiveCfg = Debug|Any CPU + {987F2544-BD32-4447-B850-BA91D1AF8FE8}.Debug|x64.Build.0 = Debug|Any CPU + {987F2544-BD32-4447-B850-BA91D1AF8FE8}.Debug|x86.ActiveCfg = Debug|Any CPU + {987F2544-BD32-4447-B850-BA91D1AF8FE8}.Debug|x86.Build.0 = Debug|Any CPU + {987F2544-BD32-4447-B850-BA91D1AF8FE8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {987F2544-BD32-4447-B850-BA91D1AF8FE8}.Release|Any CPU.Build.0 = Release|Any CPU + {987F2544-BD32-4447-B850-BA91D1AF8FE8}.Release|x64.ActiveCfg = Release|Any CPU + {987F2544-BD32-4447-B850-BA91D1AF8FE8}.Release|x64.Build.0 = Release|Any CPU + {987F2544-BD32-4447-B850-BA91D1AF8FE8}.Release|x86.ActiveCfg = Release|Any CPU + {987F2544-BD32-4447-B850-BA91D1AF8FE8}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -67,6 +81,7 @@ Global {3C5A3128-B243-5A70-788F-6B3C2B163656} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {D407041F-0C3B-4215-9F92-38C01435E015} = {0AB3BF05-4346-4AA6-1389-037BE0695223} {4AD6649A-5B01-4BE5-A335-534B80F80C5C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {987F2544-BD32-4447-B850-BA91D1AF8FE8} = {0AB3BF05-4346-4AA6-1389-037BE0695223} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {B33BAE4E-D6AD-429A-971D-8A9E6D5A4F16} diff --git a/src/MandoCode.Acp/AcpExceptions.cs b/src/MandoCode.Acp/AcpExceptions.cs index fc7091b..f77327c 100644 --- a/src/MandoCode.Acp/AcpExceptions.cs +++ b/src/MandoCode.Acp/AcpExceptions.cs @@ -47,3 +47,34 @@ public sealed class AcpProtocolViolationException : Exception { public AcpProtocolViolationException(string message) : base(message) { } } + +/// Why an agent command could not be launched. +public enum AcpLaunchFailure +{ + /// The command (or script argument) does not exist or is not on PATH. + NotFound, + + /// The command is not a real native executable (a .cmd/.bat shim, a shell script, ...). + NotANativeExecutable, + + /// The command is something MandoCode refuses to run: npx-style downloaders and shells. + Forbidden, + + /// The arguments are not acceptable (for example a relative script path for node). + InvalidArguments, + + /// The operating system refused to start the process. + StartFailed, +} + +/// A launch was refused or failed; is written for the user. +public sealed class AcpLaunchException : Exception +{ + public AcpLaunchFailure Failure { get; } + + public AcpLaunchException(AcpLaunchFailure failure, string message, Exception? inner = null) + : base(message, inner) + { + Failure = failure; + } +} diff --git a/src/MandoCode.Acp/JsonRpc/JsonRpcConnection.cs b/src/MandoCode.Acp/JsonRpc/JsonRpcConnection.cs index 1e07d1e..69600bf 100644 --- a/src/MandoCode.Acp/JsonRpc/JsonRpcConnection.cs +++ b/src/MandoCode.Acp/JsonRpc/JsonRpcConnection.cs @@ -16,9 +16,10 @@ public sealed class JsonRpcConnectionOptions /// /// Builds the exception pending requests fail with when the stream ends. The process transport - /// uses it to attach the exit code and stderr tail; the default is a plain message. + /// uses it to attach the exit code and stderr tail (the exit code can lag EOF slightly, hence + /// async); the default is a plain message. /// - public Func? DescribeClose { get; init; } + public Func>? DescribeClose { get; init; } /// Diagnostics sink (ignored frames, handler failures). Never write this to the console. public Action? Diagnostics { get; init; } @@ -270,7 +271,7 @@ private async Task WriteLoopAsync() } catch (Exception ex) when (ex is IOException or ObjectDisposedException or InvalidOperationException or NotSupportedException) { - Terminate(CreateClosedException(ex)); + Terminate(await CreateClosedExceptionAsync(ex).ConfigureAwait(false)); } catch (OperationCanceledException) { @@ -339,11 +340,11 @@ private async Task ReadLoopAsync() end += read; } - Terminate(CreateClosedException(null)); + Terminate(await CreateClosedExceptionAsync(null).ConfigureAwait(false)); } catch (OperationCanceledException) { - Terminate(CreateClosedException(null)); + Terminate(await CreateClosedExceptionAsync(null).ConfigureAwait(false)); } catch (AcpProtocolViolationException ex) { @@ -351,7 +352,7 @@ private async Task ReadLoopAsync() } catch (Exception ex) when (ex is IOException or ObjectDisposedException) { - Terminate(CreateClosedException(ex)); + Terminate(await CreateClosedExceptionAsync(ex).ConfigureAwait(false)); } } @@ -601,11 +602,19 @@ private AcpConnectionClosedException ClosedException() => Volatile.Read(ref _closeReason)?.Message ?? "The connection to the agent is closed.", inner: Volatile.Read(ref _closeReason)); - private AcpConnectionClosedException CreateClosedException(Exception? inner) + private async Task CreateClosedExceptionAsync(Exception? inner) { - var described = _options.DescribeClose?.Invoke(); - if (described is not null) - return described; + if (_options.DescribeClose is { } describe) + { + try + { + return await describe().ConfigureAwait(false); + } + catch (Exception) + { + // Fall through to the generic description. + } + } return new AcpConnectionClosedException( inner is null ? "The agent closed the connection." : $"The connection to the agent failed: {inner.Message}", diff --git a/src/MandoCode.Acp/README.md b/src/MandoCode.Acp/README.md index 1af173d..35ec1d8 100644 --- a/src/MandoCode.Acp/README.md +++ b/src/MandoCode.Acp/README.md @@ -38,3 +38,23 @@ run the tests and update the tag here and in `AcpProtocol.SchemaTag`. as it is read, so callers that must see every `session/update` that preceded it await `DrainNotificationsAsync()` first; - unknown methods get `-32601`, bad params `-32602`, handler failures `-32603` (without details). + +## Process transport + +`Transport/AcpProcessTransport` runs the agent as a child process. + +- Started with `UseShellExecute = false` and `ArgumentList`. No shell (`cmd.exe`, `powershell`, + `sh -c`) and no `npx` is ever involved. +- `AcpCommandResolver` turns the configured command into a real native executable or refuses: + Windows accepts only an `.exe` (PE header), Unix only ELF/Mach-O binaries. `.cmd`/`.bat`/`.ps1` + shims and `#!` scripts are rejected with an explanation. Package downloaders (`npx`, `pnpm`, + `yarn`, ...) and shells are forbidden. For `node`, the first argument must be the absolute + path of an existing script. The resolved absolute path is what is executed. +- `AcpEnvironment` removes `ANTHROPIC_API_KEY` from the inherited environment unless the agent + entry opts in; the entry's own `env` is applied on top. +- stdout is the protocol channel only. stderr is drained into `StderrLog` (ring buffer plus an + optional rotated file) and never reaches the console. +- Shutdown closes stdin, waits a grace period, then kills the whole process tree. A + `ProcessExit` hook kills any still-running agents if MandoCode itself exits abruptly. + +The integration tests run the real transport against `tests/MandoCode.Acp.MockAgent`. diff --git a/src/MandoCode.Acp/Transport/AcpCommandResolver.cs b/src/MandoCode.Acp/Transport/AcpCommandResolver.cs new file mode 100644 index 0000000..6bea198 --- /dev/null +++ b/src/MandoCode.Acp/Transport/AcpCommandResolver.cs @@ -0,0 +1,316 @@ +namespace MandoCode.Acp.Transport; + +/// The file-system and platform facts the resolver needs; replaceable so rules are testable on any OS. +public interface IAcpResolverEnvironment +{ + bool IsWindows { get; } + + /// The value of the PATH variable. + string? PathVariable { get; } + + bool FileExists(string path); + + /// Reads up to bytes from the start of the file. + byte[] ReadHeader(string path, int count); + + /// Unix only: whether the file has an execute bit. + bool IsExecutable(string path); +} + +/// The real machine. +public sealed class SystemResolverEnvironment : IAcpResolverEnvironment +{ + public static SystemResolverEnvironment Instance { get; } = new(); + + public bool IsWindows => OperatingSystem.IsWindows(); + + public string? PathVariable => Environment.GetEnvironmentVariable("PATH"); + + public bool FileExists(string path) => File.Exists(path); + + public byte[] ReadHeader(string path, int count) + { + try + { + using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + var buffer = new byte[count]; + var read = stream.Read(buffer, 0, count); + return read == count ? buffer : buffer[..read]; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return []; + } + } + + public bool IsExecutable(string path) + { + if (OperatingSystem.IsWindows()) + return true; + + try + { + const UnixFileMode anyExecute = UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute; + return (File.GetUnixFileMode(path) & anyExecute) != 0; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or PlatformNotSupportedException) + { + return false; + } + } +} + +/// The outcome of resolving an agent command: what to execute and with which arguments. +/// Absolute path of the native executable that will be started. +/// The arguments, unchanged. +public sealed record ResolvedCommand(string ExecutablePath, IReadOnlyList Args); + +/// +/// Turns the configured command into a real native executable, or refuses. +/// +/// The rules exist because an agent command is code that runs with the user's permissions: +/// nothing is launched through a shell, nothing is downloaded at launch time, and what runs is +/// the file the user can see (the resolved absolute path is what gets started and what the trust +/// prompt shows, so PATH cannot change it in between). +/// +/// +/// Windows: only a real .exe (PE header). .cmd, .bat, .ps1 are refused. +/// Unix: an executable ELF or Mach-O binary. Shebang scripts are refused. +/// npx-style launchers and shells (cmd, powershell, sh, ...) are refused. +/// For node the first argument must be the absolute path of an existing script. +/// +/// +public static class AcpCommandResolver +{ + public const string ScriptHint = + "Specify the path to an .exe (or a native binary), or run the adapter as `node `."; + + private static readonly string[] ScriptExtensions = [".cmd", ".bat", ".ps1", ".vbs"]; + + private static readonly HashSet Downloaders = new(StringComparer.OrdinalIgnoreCase) + { + "npx", "npm", "pnpm", "pnpx", "yarn", "bunx", "uvx", "pipx", + }; + + private static readonly HashSet Shells = new(StringComparer.OrdinalIgnoreCase) + { + "cmd", "powershell", "pwsh", "sh", "bash", "zsh", "dash", "fish", "ksh", "csh", "tcsh", "ash", + }; + + public static ResolvedCommand Resolve(string command, IReadOnlyList args, IAcpResolverEnvironment? environment = null) + { + environment ??= SystemResolverEnvironment.Instance; + + if (string.IsNullOrWhiteSpace(command)) + throw new AcpLaunchException(AcpLaunchFailure.NotFound, "The agent has no command configured."); + + command = command.Trim(); + var name = NameWithoutExtension(command); + + if (Downloaders.Contains(name)) + { + throw new AcpLaunchException(AcpLaunchFailure.Forbidden, + $"`{name}` downloads and runs packages at launch time, which MandoCode does not allow. " + + "Install the adapter yourself (with a pinned version) and run it as `node `."); + } + + if (Shells.Contains(name)) + { + throw new AcpLaunchException(AcpLaunchFailure.Forbidden, + $"`{name}` is a shell. MandoCode never launches agents through a shell; point `command` at the agent itself. {ScriptHint}"); + } + + var executable = Path.IsPathRooted(command) + ? ResolveAbsolute(command, environment) + : ResolveOnPath(command, environment); + + ValidateArguments(executable, args, environment); + return new ResolvedCommand(executable, args); + } + + private static string ResolveAbsolute(string command, IAcpResolverEnvironment environment) + { + if (!environment.FileExists(command)) + { + throw new AcpLaunchException(AcpLaunchFailure.NotFound, + $"The agent command `{command}` does not exist."); + } + + EnsureNativeExecutable(command, environment); + return Path.GetFullPath(command); + } + + private static string ResolveOnPath(string command, IAcpResolverEnvironment environment) + { + if (command.IndexOfAny(['/', '\\']) >= 0) + { + throw new AcpLaunchException(AcpLaunchFailure.InvalidArguments, + $"The agent command `{command}` is a relative path. Use a bare command name found on PATH, or an absolute path."); + } + + var directories = (environment.PathVariable ?? "") + .Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + // A relative PATH entry would resolve against whatever the current directory happens to be. + .Where(Path.IsPathRooted) + .ToList(); + + return environment.IsWindows + ? ResolveOnWindowsPath(command, directories, environment) + : ResolveOnUnixPath(command, directories, environment); + } + + private static string ResolveOnWindowsPath(string command, List directories, IAcpResolverEnvironment environment) + { + var extension = Path.GetExtension(command); + var isExe = extension.Equals(".exe", StringComparison.OrdinalIgnoreCase); + var isScript = ScriptExtensions.Any(s => s.Equals(extension, StringComparison.OrdinalIgnoreCase)); + + // `claude.cmd` is rejected outright; `claude` is looked up as claude.exe, and only if there + // is no .exe anywhere do we report the .cmd/.bat shim we found, so the user learns why. + var exeName = isExe ? command : command + ".exe"; + string? shim = null; + + foreach (var directory in directories) + { + if (!isScript) + { + var candidate = Path.Combine(directory, exeName); + if (environment.FileExists(candidate)) + { + EnsureNativeExecutable(candidate, environment); + return Path.GetFullPath(candidate); + } + } + + if (shim is null) + { + foreach (var scriptExtension in ScriptExtensions) + { + var candidate = Path.Combine(directory, isScript ? command : command + scriptExtension); + if (environment.FileExists(candidate)) + { + shim = candidate; + break; + } + } + } + } + + if (shim is not null) + { + throw new AcpLaunchException(AcpLaunchFailure.NotANativeExecutable, + $"`{command}` resolves to `{shim}`, which is a script or shim, not a real executable. {ScriptHint}"); + } + + throw NotOnPath(command); + } + + private static string ResolveOnUnixPath(string command, List directories, IAcpResolverEnvironment environment) + { + foreach (var directory in directories) + { + var candidate = Path.Combine(directory, command); + if (environment.FileExists(candidate) && environment.IsExecutable(candidate)) + { + EnsureNativeExecutable(candidate, environment); + return Path.GetFullPath(candidate); + } + } + + throw NotOnPath(command); + } + + private static AcpLaunchException NotOnPath(string command) => + new(AcpLaunchFailure.NotFound, + $"`{command}` was not found in PATH. Install it, or set an absolute path in the agent's `command`."); + + private static void EnsureNativeExecutable(string path, IAcpResolverEnvironment environment) + { + var extension = Path.GetExtension(path); + + if (environment.IsWindows) + { + if (!extension.Equals(".exe", StringComparison.OrdinalIgnoreCase)) + { + throw new AcpLaunchException(AcpLaunchFailure.NotANativeExecutable, + $"`{path}` is not an .exe (it is `{(extension.Length == 0 ? "extensionless" : extension)}`). {ScriptHint}"); + } + + var header = environment.ReadHeader(path, 2); + if (header.Length < 2 || header[0] != (byte)'M' || header[1] != (byte)'Z') + { + throw new AcpLaunchException(AcpLaunchFailure.NotANativeExecutable, + $"`{path}` has an .exe extension but is not a Windows executable. {ScriptHint}"); + } + + return; + } + + if (!environment.IsExecutable(path)) + { + throw new AcpLaunchException(AcpLaunchFailure.NotANativeExecutable, + $"`{path}` is not marked executable."); + } + + var magic = environment.ReadHeader(path, 4); + if (magic.Length >= 2 && magic[0] == (byte)'#' && magic[1] == (byte)'!') + { + throw new AcpLaunchException(AcpLaunchFailure.NotANativeExecutable, + $"`{path}` is a script (it starts with `#!`), which would run an interpreter the configuration does not show. {ScriptHint}"); + } + + if (!IsKnownNativeBinary(magic)) + { + throw new AcpLaunchException(AcpLaunchFailure.NotANativeExecutable, + $"`{path}` is not a native executable (ELF or Mach-O). {ScriptHint}"); + } + } + + private static bool IsKnownNativeBinary(byte[] magic) + { + if (magic.Length < 4) + return false; + + // ELF + if (magic[0] == 0x7F && magic[1] == (byte)'E' && magic[2] == (byte)'L' && magic[3] == (byte)'F') + return true; + + // Mach-O (32/64-bit, both byte orders) and universal ("fat") binaries. + var value = (uint)(magic[0] << 24 | magic[1] << 16 | magic[2] << 8 | magic[3]); + return value is 0xFEEDFACE or 0xFEEDFACF or 0xCEFAEDFE or 0xCFFAEDFE or 0xCAFEBABE or 0xBEBAFECA; + } + + private static void ValidateArguments(string executable, IReadOnlyList args, IAcpResolverEnvironment environment) + { + if (!NameWithoutExtension(executable).Equals("node", StringComparison.OrdinalIgnoreCase)) + return; + + // `node` runs whatever script it is given, so that script is part of the command: it must be + // a specific file the user installed, not something relative to wherever we happen to run. + if (args.Count == 0) + { + throw new AcpLaunchException(AcpLaunchFailure.InvalidArguments, + "`node` needs the absolute path of the adapter script as its first argument."); + } + + var script = args[0]; + if (!Path.IsPathRooted(script)) + { + throw new AcpLaunchException(AcpLaunchFailure.InvalidArguments, + $"The first argument for `node` must be the absolute path of the adapter script (got `{script}`)."); + } + + if (!environment.FileExists(script)) + { + throw new AcpLaunchException(AcpLaunchFailure.NotFound, + $"The adapter script `{script}` does not exist. Install the adapter first (with a pinned version)."); + } + } + + private static string NameWithoutExtension(string path) + { + var name = Path.GetFileName(path); + var dot = name.LastIndexOf('.'); + return dot > 0 ? name[..dot] : name; + } +} diff --git a/src/MandoCode.Acp/Transport/AcpEnvironment.cs b/src/MandoCode.Acp/Transport/AcpEnvironment.cs new file mode 100644 index 0000000..10f91e7 --- /dev/null +++ b/src/MandoCode.Acp/Transport/AcpEnvironment.cs @@ -0,0 +1,54 @@ +using System.Collections; + +namespace MandoCode.Acp.Transport; + +/// +/// Builds the environment an agent process starts with. A pure function so it can be tested +/// without launching anything. +/// +public static class AcpEnvironment +{ + public const string AnthropicApiKey = "ANTHROPIC_API_KEY"; + + /// + /// inherited environment, minus ANTHROPIC_API_KEY unless the agent entry opted in, + /// with the entry's own env applied on top (an explicit value always wins). + /// + /// + /// Keeping the key out by default means the agent authenticates the way the user set it up + /// (for example a Claude subscription login) instead of silently billing an API key that + /// happens to be exported in the shell. + /// + public static Dictionary Build( + IEnumerable> inherited, + AcpLaunchSpec spec, + bool caseInsensitiveNames) + { + var comparer = caseInsensitiveNames ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; + var result = new Dictionary(comparer); + + foreach (var (name, value) in inherited) + result[name] = value; + + if (!spec.PassAnthropicApiKey) + result.Remove(AnthropicApiKey); + + if (spec.Env is not null) + { + foreach (var (name, value) in spec.Env) + result[name] = value; + } + + return result; + } + + /// The current process environment, in a form accepts. + public static IEnumerable> CaptureCurrent() + { + foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables()) + { + if (entry.Key is string name && entry.Value is string value) + yield return new KeyValuePair(name, value); + } + } +} diff --git a/src/MandoCode.Acp/Transport/AcpLaunchSpec.cs b/src/MandoCode.Acp/Transport/AcpLaunchSpec.cs new file mode 100644 index 0000000..d1e0556 --- /dev/null +++ b/src/MandoCode.Acp/Transport/AcpLaunchSpec.cs @@ -0,0 +1,16 @@ +namespace MandoCode.Acp.Transport; + +/// Everything needed to launch an agent. Built from the user's configuration by the application. +/// Display name, used in logs and messages. +/// A bare command name (looked up in PATH) or an absolute path to a native executable. +/// Arguments, passed one by one (never through a shell). +/// Extra environment variables from the agent entry; they win over inherited ones. +/// When false (the default) ANTHROPIC_API_KEY is removed from the inherited environment. +/// The agent's working directory (the project root). +public sealed record AcpLaunchSpec( + string AgentName, + string Command, + IReadOnlyList Args, + IReadOnlyDictionary? Env, + bool PassAnthropicApiKey, + string WorkingDirectory); diff --git a/src/MandoCode.Acp/Transport/AcpProcessTransport.cs b/src/MandoCode.Acp/Transport/AcpProcessTransport.cs new file mode 100644 index 0000000..5d0bf74 --- /dev/null +++ b/src/MandoCode.Acp/Transport/AcpProcessTransport.cs @@ -0,0 +1,258 @@ +using System.Collections.Concurrent; +using System.ComponentModel; +using System.Diagnostics; +using System.Text; + +namespace MandoCode.Acp.Transport; + +public sealed class AcpProcessOptions +{ + /// How long a polite shutdown (closing stdin) may take before the process tree is killed. + public TimeSpan ShutdownGrace { get; init; } = TimeSpan.FromSeconds(2); + + /// How long to wait for the exit code after stdout reached EOF when describing a closed connection. + public TimeSpan ExitCodeWait { get; init; } = TimeSpan.FromMilliseconds(750); + + /// Longest stderr line kept; the rest of a longer line is dropped. + public int MaxStderrLineLength { get; init; } = 8192; +} + +/// +/// Runs an agent as a child process and exposes its stdio as streams. +/// +/// Started with UseShellExecute = false and ArgumentList; no shell is ever involved. +/// stdout carries protocol messages only; stderr goes to a , never to the console. +/// Shutdown closes stdin, waits a grace period, then kills the whole process tree. +/// +/// +public sealed class AcpProcessTransport : IAcpTransport +{ + private static readonly ConcurrentDictionary Live = new(); + private static int _exitHookInstalled; + + private readonly Process _process; + private readonly StderrLog _stderr; + private readonly AcpProcessOptions _options; + private readonly TaskCompletionSource _exited = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly Task _stderrPump; + private int _disposed; + + private AcpProcessTransport(Process process, StderrLog stderr, AcpProcessOptions options) + { + _process = process; + _stderr = stderr; + _options = options; + + Input = process.StandardOutput.BaseStream; + Output = process.StandardInput.BaseStream; + _stderrPump = Task.Run(PumpStderrAsync); + } + + public Stream Input { get; } + public Stream Output { get; } + public Task Exited => _exited.Task; + public string StderrTail => _stderr.Tail(); + public int ProcessId { get; private set; } + + /// + /// Starts the resolved command. must come from : + /// its absolute path is what gets executed. + /// + public static AcpProcessTransport Start( + AcpLaunchSpec spec, + ResolvedCommand command, + StderrLog stderr, + AcpProcessOptions? options = null) + { + options ??= new AcpProcessOptions(); + + var startInfo = new ProcessStartInfo + { + FileName = command.ExecutablePath, + WorkingDirectory = spec.WorkingDirectory, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + StandardInputEncoding = new UTF8Encoding(false), + StandardErrorEncoding = new UTF8Encoding(false), + }; + + foreach (var argument in command.Args) + startInfo.ArgumentList.Add(argument); + + startInfo.Environment.Clear(); + var environment = AcpEnvironment.Build( + AcpEnvironment.CaptureCurrent(), spec, caseInsensitiveNames: OperatingSystem.IsWindows()); + foreach (var (name, value) in environment) + startInfo.Environment[name] = value; + + var process = new Process { StartInfo = startInfo, EnableRaisingEvents = true }; + + AcpProcessTransport? transport = null; + process.Exited += (_, _) => transport?.OnProcessExited(); + + try + { + process.Start(); + } + catch (Exception ex) when (ex is Win32Exception or InvalidOperationException or IOException) + { + process.Dispose(); + throw new AcpLaunchException(AcpLaunchFailure.StartFailed, + $"Could not start `{command.ExecutablePath}`: {ex.Message}", ex); + } + + transport = new AcpProcessTransport(process, stderr, options) { ProcessId = process.Id }; + Live[process.Id] = process; + InstallExitHook(); + + // The process can have exited before the handler above saw `transport`. + if (process.HasExited) + transport.OnProcessExited(); + + return transport; + } + + private void OnProcessExited() + { + int? code = null; + try { code = _process.ExitCode; } catch (InvalidOperationException) { } + _exited.TrySetResult(code); + } + + private async Task PumpStderrAsync() + { + try + { + var reader = _process.StandardError; + var buffer = new char[4096]; + var line = new StringBuilder(); + var truncated = false; + + int read; + while ((read = await reader.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0) + { + for (var i = 0; i < read; i++) + { + var c = buffer[i]; + if (c == '\n') + { + Flush(); + } + else if (c != '\r') + { + if (line.Length < _options.MaxStderrLineLength) + line.Append(c); + else + truncated = true; + } + } + } + + Flush(); + + void Flush() + { + if (line.Length == 0 && !truncated) + return; + + _stderr.Append(truncated ? line + " [truncated]" : line.ToString()); + line.Clear(); + truncated = false; + } + } + catch (Exception ex) when (ex is IOException or ObjectDisposedException or InvalidOperationException) + { + // The process is gone; whatever was read is already in the log. + } + } + + public async Task DescribeCloseAsync() + { + int? exitCode = null; + var finished = await Task.WhenAny(_exited.Task, Task.Delay(_options.ExitCodeWait)).ConfigureAwait(false); + if (finished == _exited.Task) + exitCode = await _exited.Task.ConfigureAwait(false); + + // Give the stderr pump a moment to deliver the final lines (they often explain the exit). + await Task.WhenAny(_stderrPump, Task.Delay(200)).ConfigureAwait(false); + + var message = exitCode is { } code + ? $"The agent process exited with code {code}." + : "The agent closed the connection."; + + return new AcpConnectionClosedException(message, exitCode, _stderr.Tail(20)); + } + + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + return; + + try + { + // Closing stdin is the polite request to stop; agents are expected to exit on EOF. + Output.Dispose(); + } + catch (Exception ex) when (ex is IOException or ObjectDisposedException) + { + } + + if (!HasExited()) + await Task.WhenAny(_exited.Task, Task.Delay(_options.ShutdownGrace)).ConfigureAwait(false); + + if (!HasExited()) + KillTree(); + + await Task.WhenAny(_exited.Task, Task.Delay(TimeSpan.FromSeconds(5))).ConfigureAwait(false); + await Task.WhenAny(_stderrPump, Task.Delay(TimeSpan.FromSeconds(1))).ConfigureAwait(false); + + Live.TryRemove(ProcessId, out _); + _stderr.Close(); + _process.Dispose(); + } + + /// Kills the agent and everything it started, without the grace period. + public void KillTree() + { + try + { + _process.Kill(entireProcessTree: true); + } + catch (Exception ex) when (ex is InvalidOperationException or Win32Exception or NotSupportedException) + { + // Already gone. + } + } + + private bool HasExited() + { + try { return _process.HasExited; } + catch (InvalidOperationException) { return true; } + } + + private static void InstallExitHook() + { + if (Interlocked.Exchange(ref _exitHookInstalled, 1) != 0) + return; + + // Last resort when MandoCode itself exits without disposing its panes (Ctrl+C, crash): + // never leave agent process trees running. + AppDomain.CurrentDomain.ProcessExit += (_, _) => + { + foreach (var process in Live.Values) + { + try + { + if (!process.HasExited) + process.Kill(entireProcessTree: true); + } + catch (Exception) + { + } + } + }; + } +} diff --git a/src/MandoCode.Acp/Transport/IAcpTransport.cs b/src/MandoCode.Acp/Transport/IAcpTransport.cs new file mode 100644 index 0000000..37e9391 --- /dev/null +++ b/src/MandoCode.Acp/Transport/IAcpTransport.cs @@ -0,0 +1,55 @@ +namespace MandoCode.Acp.Transport; + +/// +/// The byte channel to an agent. is what the agent writes (its stdout) and +/// is what it reads (its stdin). Disposing the transport shuts the agent down. +/// +public interface IAcpTransport : IAsyncDisposable +{ + /// The agent's stdout: protocol messages only. + Stream Input { get; } + + /// The agent's stdin. + Stream Output { get; } + + /// Completes with the exit code when the agent process ends (null when there is no process). + Task Exited { get; } + + /// The last lines the agent wrote to stderr. + string StderrTail { get; } + + /// + /// Describes why the connection ended: exit code (if the process is gone) and stderr tail. + /// Waits briefly for the exit code, which can lag the stdout EOF. + /// + Task DescribeCloseAsync(); +} + +/// A transport over two existing streams, for tests and in-process agents. Owns neither. +public sealed class StreamTransport : IAcpTransport +{ + private readonly TaskCompletionSource _exited = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public StreamTransport(Stream input, Stream output) + { + Input = input; + Output = output; + } + + public Stream Input { get; } + public Stream Output { get; } + public Task Exited => _exited.Task; + public string StderrTail => ""; + + /// Simulates the end of the peer. + public void SignalExit(int? exitCode = null) => _exited.TrySetResult(exitCode); + + public Task DescribeCloseAsync() => + Task.FromResult(new AcpConnectionClosedException("The agent closed the connection.")); + + public ValueTask DisposeAsync() + { + _exited.TrySetResult(null); + return ValueTask.CompletedTask; + } +} diff --git a/src/MandoCode.Acp/Transport/StderrLog.cs b/src/MandoCode.Acp/Transport/StderrLog.cs new file mode 100644 index 0000000..88c3ca5 --- /dev/null +++ b/src/MandoCode.Acp/Transport/StderrLog.cs @@ -0,0 +1,102 @@ +using System.Text; + +namespace MandoCode.Acp.Transport; + +/// +/// Collects what an agent writes to stderr: a ring buffer of the last lines (for error messages) and, +/// optionally, a rotated log file. It never writes to the console: stderr of a subprocess must not +/// corrupt the terminal UI. +/// +public sealed class StderrLog +{ + private readonly object _gate = new(); + private readonly Queue _tail = new(); + private readonly int _capacity; + private readonly string? _filePath; + private readonly long _maxFileBytes; + private StreamWriter? _file; + private long _fileBytes; + + /// How many recent lines to keep in memory. + /// Where to persist the log, or null to keep it in memory only. + /// The file is rotated (to .1) once it grows past this size. + public StderrLog(int capacity = 200, string? filePath = null, long maxFileBytes = 1024 * 1024) + { + _capacity = Math.Max(1, capacity); + _filePath = filePath; + _maxFileBytes = Math.Max(1024, maxFileBytes); + } + + /// The log file, when persistence is on. + public string? FilePath => _filePath; + + public void Append(string line) + { + lock (_gate) + { + _tail.Enqueue(line); + while (_tail.Count > _capacity) + _tail.Dequeue(); + + WriteToFile(line); + } + } + + /// The most recent lines, oldest first, optionally limited to the last . + public string Tail(int maxLines = int.MaxValue) + { + lock (_gate) + { + var lines = _tail.AsEnumerable(); + if (maxLines < _tail.Count) + lines = lines.Skip(_tail.Count - maxLines); + return string.Join('\n', lines); + } + } + + public void Close() + { + lock (_gate) + { + _file?.Dispose(); + _file = null; + } + } + + private void WriteToFile(string line) + { + if (_filePath is null) + return; + + try + { + if (_file is null) + { + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(_filePath))!); + var stream = new FileStream(_filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); + _fileBytes = stream.Length; + _file = new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true }; + } + + if (_fileBytes > _maxFileBytes) + { + _file.Dispose(); + _file = null; + var rotated = _filePath + ".1"; + File.Move(_filePath, rotated, overwrite: true); + _fileBytes = 0; + _file = new StreamWriter(new FileStream(_filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), + new UTF8Encoding(false)) { AutoFlush = true }; + } + + _file.WriteLine(line); + _fileBytes += Encoding.UTF8.GetByteCount(line) + 1; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Logging is best effort: a full disk must not take the agent session down. + _file?.Dispose(); + _file = null; + } + } +} diff --git a/tests/MandoCode.Acp.MockAgent/MandoCode.Acp.MockAgent.csproj b/tests/MandoCode.Acp.MockAgent/MandoCode.Acp.MockAgent.csproj new file mode 100644 index 0000000..ac87265 --- /dev/null +++ b/tests/MandoCode.Acp.MockAgent/MandoCode.Acp.MockAgent.csproj @@ -0,0 +1,16 @@ + + + + + Exe + net10.0;net8.0 + enable + enable + true + false + MandoCode.Acp.MockAgent + + + diff --git a/tests/MandoCode.Acp.MockAgent/Program.cs b/tests/MandoCode.Acp.MockAgent/Program.cs new file mode 100644 index 0000000..7511882 --- /dev/null +++ b/tests/MandoCode.Acp.MockAgent/Program.cs @@ -0,0 +1,174 @@ +using System.Diagnostics; +using System.Text; +using System.Text.Json.Nodes; + +// Usage: MandoCode.Acp.MockAgent [extra args echoed back in initialize._meta.args] +var scenario = args.Length > 0 ? args[0] : "echo"; +return await new MockAgent(scenario, args).RunAsync(); + +internal sealed class MockAgent +{ + private readonly string _scenario; + private readonly string[] _args; + private readonly Stream _stdout = Console.OpenStandardOutput(); + private readonly object _writeGate = new(); + + public MockAgent(string scenario, string[] args) + { + _scenario = scenario; + _args = args; + } + + public async Task RunAsync() + { + switch (_scenario) + { + case "exit-immediately": + Console.Error.WriteLine("mock-agent: fatal: cannot start"); + return 7; + + case "sleep": + await Task.Delay(Timeout.Infinite); + return 0; + + case "stdout-garbage": + for (var i = 0; i < 20; i++) + WriteRaw($"[mock] this is a log line, not JSON-RPC ({i})"); + await Task.Delay(Timeout.Infinite); + return 0; + + case "stderr-flood": + // Far more than a pipe buffer: a transport that does not drain stderr would deadlock. + for (var i = 0; i < 20000; i++) + Console.Error.WriteLine($"flood line {i} " + new string('x', 80)); + break; + + case "hang-on-shutdown": + StartChild(); + break; + } + + using var stdin = new StreamReader(Console.OpenStandardInput(), new UTF8Encoding(false)); + while (await stdin.ReadLineAsync() is { } line) + { + if (string.IsNullOrWhiteSpace(line)) + continue; + + JsonNode? message; + try + { + message = JsonNode.Parse(line); + } + catch (System.Text.Json.JsonException) + { + continue; + } + + if (message is not JsonObject request) + continue; + + Handle(request); + } + + // stdin reached EOF: a well-behaved agent exits. This scenario deliberately does not. + if (_scenario == "hang-on-shutdown") + await Task.Delay(Timeout.Infinite); + + return 0; + } + + private void Handle(JsonObject request) + { + var method = request["method"]?.GetValue(); + var id = request["id"]; + + switch (method) + { + case "initialize": + Reply(id, new JsonObject + { + ["protocolVersion"] = 1, + ["agentInfo"] = new JsonObject { ["name"] = "mock-" + _scenario, ["version"] = "0.0.1" }, + ["agentCapabilities"] = new JsonObject + { + ["loadSession"] = false, + ["promptCapabilities"] = new JsonObject { ["image"] = false, ["audio"] = false, ["embeddedContext"] = true }, + }, + ["authMethods"] = new JsonArray(), + // Lets tests observe how the process was launched without a real prompt round trip. + ["_meta"] = new JsonObject + { + ["pid"] = Environment.ProcessId, + ["cwd"] = Directory.GetCurrentDirectory(), + ["args"] = new JsonArray(_args.Skip(1).Select(a => (JsonNode?)a).ToArray()), + ["env"] = new JsonObject + { + ["ANTHROPIC_API_KEY"] = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY"), + ["MOCK_FOO"] = Environment.GetEnvironmentVariable("MOCK_FOO"), + ["MOCK_INHERITED"] = Environment.GetEnvironmentVariable("MOCK_INHERITED"), + }, + }, + }); + break; + + case "session/new": + Reply(id, new JsonObject { ["sessionId"] = "mock-session-1" }); + break; + + case "session/prompt": + var text = request["params"]?["prompt"]?[0]?["text"]?.GetValue() ?? ""; + Notify("session/update", new JsonObject + { + ["sessionId"] = "mock-session-1", + ["update"] = new JsonObject + { + ["sessionUpdate"] = "agent_message_chunk", + ["content"] = new JsonObject { ["type"] = "text", ["text"] = "echo: " + text }, + }, + }); + Reply(id, new JsonObject { ["stopReason"] = "end_turn" }); + break; + + default: + if (id is not null) + Error(id, -32601, "Method not found: " + method); + break; + } + } + + private static void StartChild() + { + var child = Process.Start(new ProcessStartInfo(Environment.ProcessPath!) + { + ArgumentList = { typeof(MockAgent).Assembly.Location, "sleep" }, + UseShellExecute = false, + }); + Console.Error.WriteLine("child-pid: " + child!.Id); + } + + private void Reply(JsonNode? id, JsonNode result) => + Write(new JsonObject { ["jsonrpc"] = "2.0", ["id"] = id?.DeepClone(), ["result"] = result }); + + private void Error(JsonNode? id, int code, string message) => + Write(new JsonObject + { + ["jsonrpc"] = "2.0", + ["id"] = id?.DeepClone(), + ["error"] = new JsonObject { ["code"] = code, ["message"] = message }, + }); + + private void Notify(string method, JsonNode parameters) => + Write(new JsonObject { ["jsonrpc"] = "2.0", ["method"] = method, ["params"] = parameters }); + + private void Write(JsonNode message) => WriteRaw(message.ToJsonString()); + + private void WriteRaw(string line) + { + var bytes = Encoding.UTF8.GetBytes(line + "\n"); + lock (_writeGate) + { + _stdout.Write(bytes, 0, bytes.Length); + _stdout.Flush(); + } + } +} diff --git a/tests/MandoCode.Tests/Acp/AcpProcessTransportTests.cs b/tests/MandoCode.Tests/Acp/AcpProcessTransportTests.cs new file mode 100644 index 0000000..88b96d4 --- /dev/null +++ b/tests/MandoCode.Tests/Acp/AcpProcessTransportTests.cs @@ -0,0 +1,322 @@ +using System.Diagnostics; +using System.Text.Json; +using MandoCode.Acp; +using MandoCode.Acp.JsonRpc; +using MandoCode.Acp.Protocol; +using MandoCode.Acp.Transport; +using Xunit; + +namespace MandoCode.Tests.Acp; + +/// +/// Runs the real against the mock agent (a separate .NET process), +/// so process launching, stdio plumbing, environment and shutdown are exercised for real. +/// +public class AcpProcessTransportTests : IDisposable +{ + private readonly string _workDir = Path.Combine(Path.GetTempPath(), "mandocode-acp-work-" + Guid.NewGuid().ToString("N")); + private readonly List _cleanup = []; + + public AcpProcessTransportTests() => Directory.CreateDirectory(_workDir); + + public void Dispose() + { + foreach (var item in _cleanup) + item.DisposeAsync().AsTask().GetAwaiter().GetResult(); + + try { Directory.Delete(_workDir, recursive: true); } catch (IOException) { } + } + + private static string DotnetHost() => + Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") + ?? AcpCommandResolver.Resolve("dotnet", []).ExecutablePath; + + private static string MockAgentDll() => + Path.Combine(AppContext.BaseDirectory, "MandoCode.Acp.MockAgent.dll"); + + private AcpLaunchSpec Spec( + string scenario, + IReadOnlyList? extraArgs = null, + Dictionary? env = null, + bool passApiKey = false, + string? workingDirectory = null) => + new("mock-" + scenario, DotnetHost(), [MockAgentDll(), scenario, .. extraArgs ?? []], env, passApiKey, workingDirectory ?? _workDir); + + private AcpProcessTransport Start(AcpLaunchSpec spec, StderrLog? log = null, AcpProcessOptions? options = null) + { + var transport = AcpProcessTransport.Start(spec, new ResolvedCommand(spec.Command, spec.Args), log ?? new StderrLog(), options); + _cleanup.Add(transport); + return transport; + } + + private JsonRpcConnection Connect(AcpProcessTransport transport) + { + var connection = new JsonRpcConnection(transport.Input, transport.Output, + new JsonRpcConnectionOptions { DescribeClose = transport.DescribeCloseAsync, MaxConsecutiveParseErrors = 3 }); + _cleanup.Add(connection); + return connection; + } + + private static Task Initialize(JsonRpcConnection connection) => + connection.SendRequestAsync(AcpMethods.Initialize, new InitializeRequest(), + AcpJsonContext.Default.InitializeRequest, AcpJsonContext.Default.InitializeResponse); + + [Fact] + public async Task LaunchesTheAgent_AndTalksJsonRpcOverItsStdio() + { + var transport = Start(Spec("echo")); + var connection = Connect(transport); + + var response = await Initialize(connection).Within(20); + + Assert.Equal("mock-echo", response.AgentInfo!.Name); + Assert.True(response.AgentCapabilities.PromptCapabilities.EmbeddedContext); + } + + [Fact] + public async Task ArgumentsAndWorkingDirectory_ArriveExactly_WithoutAShell() + { + string[] tricky = + [ + "plain", + "with space", + "\"quoted\"", + @"C:\path with space\dir\", + "--flag=va lue", + "semi;colon & ampersand | pipe > redirect", + "$HOME `whoami` %PATH%", + "ünï-ко́д-日本", + ]; + var transport = Start(Spec("echo", tricky)); + var connection = Connect(transport); + + var response = await Initialize(connection).Within(20); + var meta = response.Meta!.Value; + + Assert.Equal(tricky, meta.GetProperty("args").EnumerateArray().Select(a => a.GetString()).ToArray()); + Assert.Equal(Path.GetFullPath(_workDir).TrimEnd(Path.DirectorySeparatorChar), + Path.GetFullPath(meta.GetProperty("cwd").GetString()!).TrimEnd(Path.DirectorySeparatorChar), + ignoreCase: OperatingSystem.IsWindows()); + } + + [Fact] + public async Task ApiKey_IsNotInheritedByDefault_ButOtherVariablesAre() + { + using var scope = new EnvScope(("ANTHROPIC_API_KEY", "sk-from-the-test-process"), ("MOCK_INHERITED", "yes")); + + var transport = Start(Spec("echo", env: new Dictionary { ["MOCK_FOO"] = "bar" })); + var connection = Connect(transport); + + var env = (await Initialize(connection).Within(20)).Meta!.Value.GetProperty("env"); + + Assert.Equal(JsonValueKind.Null, env.GetProperty("ANTHROPIC_API_KEY").ValueKind); + Assert.Equal("yes", env.GetProperty("MOCK_INHERITED").GetString()); + Assert.Equal("bar", env.GetProperty("MOCK_FOO").GetString()); + } + + [Fact] + public async Task ApiKey_IsPassedWhenTheEntryOptsIn() + { + using var scope = new EnvScope(("ANTHROPIC_API_KEY", "sk-from-the-test-process")); + + var transport = Start(Spec("echo", passApiKey: true)); + var connection = Connect(transport); + + var env = (await Initialize(connection).Within(20)).Meta!.Value.GetProperty("env"); + Assert.Equal("sk-from-the-test-process", env.GetProperty("ANTHROPIC_API_KEY").GetString()); + } + + [Fact] + public async Task RealPromptRoundTrip_StreamsAnUpdateBeforeTheResponse() + { + var transport = Start(Spec("echo")); + var connection = Connect(transport); + + var chunks = new List(); + connection.RegisterNotificationHandler(AcpMethods.SessionUpdate, AcpJsonContext.Default.SessionNotification, n => + { + if (n.Update is AgentMessageChunk { Content: TextContent text }) + chunks.Add(text.Text); + return ValueTask.CompletedTask; + }); + + await Initialize(connection).Within(20); + var session = await connection.SendRequestAsync(AcpMethods.SessionNew, new NewSessionRequest { Cwd = _workDir }, + AcpJsonContext.Default.NewSessionRequest, AcpJsonContext.Default.NewSessionResponse).Within(); + var prompt = await connection.SendRequestAsync(AcpMethods.SessionPrompt, + new PromptRequest { SessionId = session.SessionId, Prompt = [new TextContent("hello")] }, + AcpJsonContext.Default.PromptRequest, AcpJsonContext.Default.PromptResponse).Within(); + await connection.DrainNotificationsAsync().Within(); + + Assert.Equal(StopReasons.EndTurn, prompt.StopReason); + Assert.Equal(["echo: hello"], chunks); + } + + [Fact] + public async Task ExitDuringStartup_FailsThePendingRequest_WithExitCodeAndStderrTail() + { + var transport = Start(Spec("exit-immediately")); + var connection = Connect(transport); + + var ex = await Assert.ThrowsAsync(() => Initialize(connection).Within(20)); + + Assert.Equal(7, ex.ExitCode); + Assert.Contains("fatal: cannot start", ex.StderrTail); + Assert.Equal(7, await transport.Exited.Within()); + } + + [Fact] + public async Task StderrFlood_DoesNotDeadlock_AndIsBoundedInMemory() + { + var log = new StderrLog(capacity: 200); + var transport = Start(Spec("stderr-flood"), log); + var connection = Connect(transport); + + // The agent writes ~1.7 MB to stderr before it reads stdin; this only completes if stderr is drained. + await Initialize(connection).Within(30); + + var deadline = DateTime.UtcNow.AddSeconds(15); + while (!log.Tail(1).Contains("flood line 19999") && DateTime.UtcNow < deadline) + await Task.Delay(50); + + var lines = log.Tail().Split('\n'); + Assert.True(lines.Length <= 200, $"expected at most 200 buffered lines, got {lines.Length}"); + Assert.Contains("flood line 19999", lines[^1]); + } + + [Fact] + public async Task Stderr_NeverReachesTheProtocolStream() + { + var log = new StderrLog(); + var transport = Start(Spec("exit-immediately"), log); + var connection = Connect(transport); + + await Assert.ThrowsAsync(() => Initialize(connection).Within(20)); + + Assert.Contains("mock-agent: fatal", log.Tail()); + } + + [Fact] + public async Task GarbageOnStdout_BreaksTheConnection_WithAnExplanation() + { + var transport = Start(Spec("stdout-garbage")); + var connection = Connect(transport); + + var violation = await Assert.ThrowsAsync(() => connection.Completion.Within(20)); + + Assert.Contains("stdout", violation.Message); + } + + [Fact] + public async Task PoliteShutdown_ClosesStdin_AndTheAgentExitsOnItsOwn() + { + var transport = Start(Spec("echo")); + var connection = Connect(transport); + await Initialize(connection).Within(20); + + var stopwatch = Stopwatch.StartNew(); + await connection.DisposeAsync(); + await transport.DisposeAsync(); + + Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(10), $"shutdown took {stopwatch.Elapsed}"); + Assert.Equal(0, await transport.Exited.Within()); + } + + [Fact] + public async Task AgentThatIgnoresStdinEof_IsKilled_TogetherWithItsChildProcess() + { + var log = new StderrLog(); + var transport = Start(Spec("hang-on-shutdown"), log, + new AcpProcessOptions { ShutdownGrace = TimeSpan.FromMilliseconds(300) }); + var connection = Connect(transport); + await Initialize(connection).Within(20); + + var childPid = await WaitForChildPid(log); + var agentPid = transport.ProcessId; + Assert.False(IsGone(childPid), "the child process should be alive before shutdown"); + + await connection.DisposeAsync(); + await transport.DisposeAsync(); + + await WaitUntil(() => IsGone(agentPid) && IsGone(childPid), TimeSpan.FromSeconds(10)); + Assert.True(IsGone(agentPid), "the agent process survived shutdown"); + Assert.True(IsGone(childPid), "the agent's child process survived shutdown (the tree was not killed)"); + } + + [Fact] + public void StartFailure_IsReportedAsALaunchError() + { + var spec = Spec("echo", workingDirectory: Path.Combine(_workDir, "does", "not", "exist")); + + var ex = Assert.Throws(() => + AcpProcessTransport.Start(spec, new ResolvedCommand(spec.Command, spec.Args), new StderrLog())); + + Assert.Equal(AcpLaunchFailure.StartFailed, ex.Failure); + } + + [Fact] + public void TheRealResolver_FindsDotnet_AsANativeExecutable() + { + var resolved = AcpCommandResolver.Resolve("dotnet", [MockAgentDll(), "echo"]); + + Assert.True(Path.IsPathRooted(resolved.ExecutablePath)); + Assert.True(File.Exists(resolved.ExecutablePath)); + if (OperatingSystem.IsWindows()) + Assert.EndsWith(".exe", resolved.ExecutablePath, StringComparison.OrdinalIgnoreCase); + } + + // ───────────── helpers ───────────── + + private static async Task WaitForChildPid(StderrLog log) + { + var deadline = DateTime.UtcNow.AddSeconds(15); + while (DateTime.UtcNow < deadline) + { + var line = log.Tail().Split('\n').FirstOrDefault(l => l.StartsWith("child-pid: ", StringComparison.Ordinal)); + if (line is not null) + return int.Parse(line["child-pid: ".Length..]); + await Task.Delay(50); + } + + throw new TimeoutException("The mock agent never reported its child pid."); + } + + private static bool IsGone(int pid) + { + try + { + using var process = Process.GetProcessById(pid); + return process.HasExited; + } + catch (ArgumentException) + { + return true; + } + } + + private static async Task WaitUntil(Func condition, TimeSpan timeout) + { + var deadline = DateTime.UtcNow + timeout; + while (!condition() && DateTime.UtcNow < deadline) + await Task.Delay(50); + } + + /// Sets environment variables for the test and restores them afterwards. + private sealed class EnvScope : IDisposable + { + private readonly (string Name, string? Old)[] _saved; + + public EnvScope(params (string Name, string Value)[] variables) + { + _saved = variables.Select(v => (v.Name, Environment.GetEnvironmentVariable(v.Name))).ToArray(); + foreach (var (name, value) in variables) + Environment.SetEnvironmentVariable(name, value); + } + + public void Dispose() + { + foreach (var (name, old) in _saved) + Environment.SetEnvironmentVariable(name, old); + } + } +} diff --git a/tests/MandoCode.Tests/Acp/AcpTransportUnitTests.cs b/tests/MandoCode.Tests/Acp/AcpTransportUnitTests.cs new file mode 100644 index 0000000..b3a7c0c --- /dev/null +++ b/tests/MandoCode.Tests/Acp/AcpTransportUnitTests.cs @@ -0,0 +1,397 @@ +using MandoCode.Acp; +using MandoCode.Acp.Transport; +using Xunit; + +namespace MandoCode.Tests.Acp; + +public class AcpEnvironmentTests +{ + private static AcpLaunchSpec Spec(bool pass = false, Dictionary? env = null) => + new("agent", "cmd", [], env, pass, "/work"); + + private static readonly KeyValuePair[] Inherited = + [ + new("PATH", "/usr/bin"), + new("HOME", "/home/u"), + new("ANTHROPIC_API_KEY", "sk-secret"), + ]; + + [Fact] + public void ApiKey_IsNotPassedByDefault() + { + var env = AcpEnvironment.Build(Inherited, Spec(), caseInsensitiveNames: false); + + Assert.False(env.ContainsKey("ANTHROPIC_API_KEY")); + Assert.Equal("/usr/bin", env["PATH"]); + Assert.Equal("/home/u", env["HOME"]); + } + + [Fact] + public void ApiKey_IsPassedOnlyWhenTheEntryOptsIn() + { + var env = AcpEnvironment.Build(Inherited, Spec(pass: true), caseInsensitiveNames: false); + Assert.Equal("sk-secret", env["ANTHROPIC_API_KEY"]); + } + + [Fact] + public void ApiKey_RemovalIsCaseInsensitive_OnWindowsStyleEnvironments() + { + KeyValuePair[] inherited = [new("Anthropic_Api_Key", "sk-secret"), new("Path", "C:\\bin")]; + + var env = AcpEnvironment.Build(inherited, Spec(), caseInsensitiveNames: true); + + Assert.DoesNotContain(env.Keys, k => k.Equals("ANTHROPIC_API_KEY", StringComparison.OrdinalIgnoreCase)); + Assert.Equal("C:\\bin", env["PATH"]); + } + + [Fact] + public void EntryEnv_OverridesInheritedValues_AndAddsNewOnes() + { + var env = AcpEnvironment.Build(Inherited, + Spec(env: new Dictionary { ["HOME"] = "/override", ["EXTRA"] = "1" }), + caseInsensitiveNames: false); + + Assert.Equal("/override", env["HOME"]); + Assert.Equal("1", env["EXTRA"]); + } + + [Fact] + public void ExplicitEnvValue_Wins_EvenForTheApiKey() + { + // The user wrote it into the agent entry on purpose (and the trust prompt shows env names). + var env = AcpEnvironment.Build(Inherited, + Spec(env: new Dictionary { ["ANTHROPIC_API_KEY"] = "sk-explicit" }), + caseInsensitiveNames: false); + + Assert.Equal("sk-explicit", env["ANTHROPIC_API_KEY"]); + } +} + +public class StderrLogTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "mandocode-acp-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + try { Directory.Delete(_directory, recursive: true); } catch (IOException) { } + } + + [Fact] + public void RingBuffer_KeepsOnlyTheLastLines() + { + var log = new StderrLog(capacity: 3); + for (var i = 1; i <= 10; i++) + log.Append("line " + i); + + Assert.Equal("line 8\nline 9\nline 10", log.Tail()); + Assert.Equal("line 10", log.Tail(1)); + } + + [Fact] + public void FileLog_IsWritten_AndRotatedWhenItGrows() + { + var path = Path.Combine(_directory, "logs", "agent.log"); + var log = new StderrLog(capacity: 5, filePath: path, maxFileBytes: 2048); + + for (var i = 0; i < 100; i++) + log.Append(new string('a', 60) + i); + log.Close(); + + Assert.True(File.Exists(path)); + Assert.True(File.Exists(path + ".1"), "the log should have been rotated"); + Assert.True(new FileInfo(path).Length <= 4096); + Assert.Contains("a99", File.ReadAllText(path)); + } + + [Fact] + public void UnwritableLogPath_DoesNotThrow() + { + var blocker = Path.Combine(_directory, "blocker"); + Directory.CreateDirectory(_directory); + File.WriteAllText(blocker, "i am a file, not a directory"); + + var log = new StderrLog(filePath: Path.Combine(blocker, "agent.log")); + log.Append("still works in memory"); + + Assert.Equal("still works in memory", log.Tail()); + } +} + +/// +/// The resolver's rules, exercised against a fake machine so both the Windows and the Unix rules run +/// on any host. Paths are built with the host's separators; only the OS-specific rules are simulated. +/// +public class AcpCommandResolverTests +{ + private static readonly string Bin = Path.Combine(Path.GetTempPath(), "mc-resolver", "bin"); + private static readonly string Other = Path.Combine(Path.GetTempPath(), "mc-resolver", "other"); + + private static readonly byte[] Pe = [(byte)'M', (byte)'Z', 0x90, 0x00]; + private static readonly byte[] Elf = [0x7F, (byte)'E', (byte)'L', (byte)'F']; + private static readonly byte[] MachO = [0xCF, 0xFA, 0xED, 0xFE]; + private static readonly byte[] Shebang = "#!/usr/bin/env node\n"u8.ToArray(); + private static readonly byte[] Text = "hello"u8.ToArray(); + + private sealed class FakeMachine(bool windows) : IAcpResolverEnvironment + { + public Dictionary Files { get; } = new(StringComparer.OrdinalIgnoreCase); + public HashSet Executable { get; } = new(StringComparer.OrdinalIgnoreCase); + public bool IsWindows => windows; + public string? PathVariable { get; set; } + public bool FileExists(string path) => Files.ContainsKey(path); + public byte[] ReadHeader(string path, int count) => Files[path].Take(count).ToArray(); + public bool IsExecutable(string path) => Executable.Contains(path); + + public FakeMachine Add(string path, byte[] content, bool executable = true) + { + Files[path] = content; + if (executable) + Executable.Add(path); + return this; + } + } + + private static FakeMachine Windows(params string[] pathDirs) => + new(windows: true) { PathVariable = string.Join(Path.PathSeparator, pathDirs) }; + + private static FakeMachine Unix(params string[] pathDirs) => + new(windows: false) { PathVariable = string.Join(Path.PathSeparator, pathDirs) }; + + private static AcpLaunchException Refused(string command, IReadOnlyList args, IAcpResolverEnvironment machine) => + Assert.Throws(() => AcpCommandResolver.Resolve(command, args, machine)); + + // ───────────── Windows rules ───────────── + + [Theory] + [InlineData("claude")] + [InlineData("claude.exe")] + public void Windows_ExeOnPath_IsAccepted_AndTheAbsolutePathIsReturned(string command) + { + var exe = Path.Combine(Bin, "claude.exe"); + var machine = Windows(Bin).Add(exe, Pe); + + var resolved = AcpCommandResolver.Resolve(command, ["--flag"], machine); + + Assert.Equal(Path.GetFullPath(exe), resolved.ExecutablePath); + Assert.Equal(["--flag"], resolved.Args); + } + + [Fact] + public void Windows_CmdShimOnly_IsRejected_WithTheExplanation() + { + var machine = Windows(Bin).Add(Path.Combine(Bin, "claude.cmd"), Text); + + var ex = Refused("claude", [], machine); + + Assert.Equal(AcpLaunchFailure.NotANativeExecutable, ex.Failure); + Assert.Contains("an .exe", ex.Message); + Assert.Contains("node ", ex.Message); + } + + [Theory] + [InlineData("claude.cmd")] + [InlineData("claude.bat")] + [InlineData("claude.ps1")] + public void Windows_ExplicitScriptExtensions_AreRejected(string command) + { + var machine = Windows(Bin).Add(Path.Combine(Bin, command), Text); + Assert.Equal(AcpLaunchFailure.NotANativeExecutable, Refused(command, [], machine).Failure); + } + + [Fact] + public void Windows_ExeIsPreferredOverAShimInALaterDirectory() + { + var machine = Windows(Bin, Other) + .Add(Path.Combine(Bin, "claude.cmd"), Text) + .Add(Path.Combine(Other, "claude.exe"), Pe); + + var resolved = AcpCommandResolver.Resolve("claude", [], machine); + + Assert.Equal(Path.GetFullPath(Path.Combine(Other, "claude.exe")), resolved.ExecutablePath); + } + + [Fact] + public void Windows_ExeThatIsNotAPortableExecutable_IsRejected() + { + var machine = Windows(Bin).Add(Path.Combine(Bin, "fake.exe"), Text); + Assert.Equal(AcpLaunchFailure.NotANativeExecutable, Refused("fake", [], machine).Failure); + } + + [Fact] + public void AbsolutePath_ToACmd_IsRejected_AndToAMissingFile_IsNotFound() + { + var cmd = Path.Combine(Bin, "tool.cmd"); + var machine = Windows(Bin).Add(cmd, Text); + + Assert.Equal(AcpLaunchFailure.NotANativeExecutable, Refused(cmd, [], machine).Failure); + Assert.Equal(AcpLaunchFailure.NotFound, Refused(Path.Combine(Bin, "missing.exe"), [], machine).Failure); + } + + [Fact] + public void Windows_AbsoluteExe_IsAccepted() + { + var exe = Path.Combine(Bin, "agent.exe"); + var resolved = AcpCommandResolver.Resolve(exe, [], Windows().Add(exe, Pe)); + Assert.Equal(Path.GetFullPath(exe), resolved.ExecutablePath); + } + + // ───────────── Unix rules ───────────── + + [Theory] + [MemberData(nameof(NativeBinaries))] + public void Unix_ElfAndMachO_AreAccepted(byte[] magic) + { + var path = Path.Combine(Bin, "agent"); + var resolved = AcpCommandResolver.Resolve("agent", [], Unix(Bin).Add(path, magic)); + Assert.Equal(Path.GetFullPath(path), resolved.ExecutablePath); + } + + public static IEnumerable NativeBinaries() => [[Elf], [MachO]]; + + [Fact] + public void Unix_ShebangScript_IsRejected() + { + var machine = Unix(Bin).Add(Path.Combine(Bin, "claude"), Shebang); + + var ex = Refused("claude", [], machine); + + Assert.Equal(AcpLaunchFailure.NotANativeExecutable, ex.Failure); + Assert.Contains("#!", ex.Message); + } + + [Fact] + public void Unix_UnknownBinaryFormat_AndNonExecutableFiles_AreRejected() + { + var unknown = Unix(Bin).Add(Path.Combine(Bin, "blob"), Text); + Assert.Equal(AcpLaunchFailure.NotANativeExecutable, Refused("blob", [], unknown).Failure); + + // Present on PATH but without the execute bit: the shell would skip it, so it is "not found". + var noExec = Unix(Bin).Add(Path.Combine(Bin, "tool"), Elf, executable: false); + Assert.Equal(AcpLaunchFailure.NotFound, Refused("tool", [], noExec).Failure); + } + + [Fact] + public void Unix_FirstExecutableOnPathWins() + { + var machine = Unix(Bin, Other) + .Add(Path.Combine(Bin, "agent"), Elf) + .Add(Path.Combine(Other, "agent"), Elf); + + Assert.Equal(Path.GetFullPath(Path.Combine(Bin, "agent")), AcpCommandResolver.Resolve("agent", [], machine).ExecutablePath); + } + + // ───────────── rules for every OS ───────────── + + [Fact] + public void CommandNotOnPath_IsNotFound() + { + Assert.Equal(AcpLaunchFailure.NotFound, Refused("nothing", [], Windows(Bin)).Failure); + Assert.Equal(AcpLaunchFailure.NotFound, Refused("nothing", [], Unix(Bin)).Failure); + Assert.Equal(AcpLaunchFailure.NotFound, Refused(" ", [], Unix(Bin)).Failure); + } + + [Fact] + public void RelativePathEntries_AreIgnored() + { + // "." or "bin" in PATH would resolve against the current directory, i.e. against the opened repository. + var machine = Unix(".", "bin").Add(Path.Combine(".", "agent"), Elf).Add(Path.Combine("bin", "agent"), Elf); + Assert.Equal(AcpLaunchFailure.NotFound, Refused("agent", [], machine).Failure); + } + + [Theory] + [InlineData("./agent")] + [InlineData(@".\agent.exe")] + [InlineData("tools/agent")] + public void RelativeCommandPaths_AreRefused(string command) + { + Assert.Equal(AcpLaunchFailure.InvalidArguments, Refused(command, [], Unix(Bin)).Failure); + } + + [Theory] + [InlineData("npx")] + [InlineData("npx.cmd")] + [InlineData("NPX.EXE")] + [InlineData("pnpm")] + [InlineData("yarn")] + [InlineData("bunx")] + [InlineData("uvx")] + public void PackageDownloaders_AreForbidden_EvenIfTheyExist(string command) + { + var machine = Windows(Bin).Add(Path.Combine(Bin, "npx.exe"), Pe).Add(Path.Combine(Bin, "pnpm.exe"), Pe); + + var ex = Refused(command, ["-y", "some-adapter"], machine); + + Assert.Equal(AcpLaunchFailure.Forbidden, ex.Failure); + Assert.Contains("node ", ex.Message); + } + + [Theory] + [InlineData("cmd")] + [InlineData("cmd.exe")] + [InlineData("powershell")] + [InlineData("pwsh.exe")] + [InlineData("sh")] + [InlineData("bash")] + [InlineData("/bin/sh")] + public void Shells_AreForbidden(string command) + { + Assert.Equal(AcpLaunchFailure.Forbidden, Refused(command, ["-c", "evil"], Unix(Bin)).Failure); + } + + // ───────────── node adapters ───────────── + + private static readonly string Script = Path.Combine(Path.GetTempPath(), "mc-resolver", "adapter", "dist", "index.js"); + + private static FakeMachine NodeMachine() + { + var machine = Windows(Bin).Add(Path.Combine(Bin, "node.exe"), Pe); + machine.Files[Script] = Text; + return machine; + } + + [Fact] + public void Node_WithAnAbsoluteExistingScript_IsAccepted() + { + var resolved = AcpCommandResolver.Resolve("node", [Script, "--stdio"], NodeMachine()); + + Assert.Equal(Path.GetFullPath(Path.Combine(Bin, "node.exe")), resolved.ExecutablePath); + Assert.Equal([Script, "--stdio"], resolved.Args); + } + + [Theory] + [InlineData("dist/index.js")] + [InlineData(@"..\adapter\index.js")] + [InlineData("index.js")] + public void Node_WithARelativeScript_IsRejected(string script) + { + var ex = Refused("node", [script], NodeMachine()); + Assert.Equal(AcpLaunchFailure.InvalidArguments, ex.Failure); + Assert.Contains("absolute path", ex.Message); + } + + [Theory] + [InlineData("-e")] + [InlineData("--eval")] + public void Node_WithInlineEvalAsFirstArgument_IsRejected(string flag) + { + Assert.Equal(AcpLaunchFailure.InvalidArguments, Refused("node", [flag, "process.exit()"], NodeMachine()).Failure); + } + + [Fact] + public void Node_WithoutArguments_OrWithAMissingScript_IsRejected() + { + Assert.Equal(AcpLaunchFailure.InvalidArguments, Refused("node", [], NodeMachine()).Failure); + + var missing = Path.Combine(Path.GetTempPath(), "mc-resolver", "nowhere", "index.js"); + Assert.Equal(AcpLaunchFailure.NotFound, Refused("node", [missing], NodeMachine()).Failure); + } + + [Fact] + public void Node_ItselfMustBeARealBinary() + { + var machine = Windows(Bin).Add(Path.Combine(Bin, "node.cmd"), Text); + machine.Files[Script] = Text; + + Assert.Equal(AcpLaunchFailure.NotANativeExecutable, Refused("node", [Script], machine).Failure); + } +} diff --git a/tests/MandoCode.Tests/Acp/JsonRpcConnectionTests.cs b/tests/MandoCode.Tests/Acp/JsonRpcConnectionTests.cs index 4e907f4..a2a78f4 100644 --- a/tests/MandoCode.Tests/Acp/JsonRpcConnectionTests.cs +++ b/tests/MandoCode.Tests/Acp/JsonRpcConnectionTests.cs @@ -511,7 +511,7 @@ public async Task Eof_UsesTheTransportsDescription_ForExitCodeAndStderr() using var peer = new FakeAgentPeer(); await using var connection = peer.CreateConnection(new JsonRpcConnectionOptions { - DescribeClose = () => new AcpConnectionClosedException("agent exited", exitCode: 3, stderrTail: "fatal: no login"), + DescribeClose = () => Task.FromResult(new AcpConnectionClosedException("agent exited", exitCode: 3, stderrTail: "fatal: no login")), }); var pending = SendInitialize(connection); diff --git a/tests/MandoCode.Tests/MandoCode.Tests.csproj b/tests/MandoCode.Tests/MandoCode.Tests.csproj index 9e6da65..5fc4160 100644 --- a/tests/MandoCode.Tests/MandoCode.Tests.csproj +++ b/tests/MandoCode.Tests/MandoCode.Tests.csproj @@ -24,6 +24,8 @@ + + From 83f4eea3f8fd7462a0caa2dae3753be64b2393fb Mon Sep 17 00:00:00 2001 From: TeseySTD Date: Tue, 10 Nov 2026 13:42:58 +0200 Subject: [PATCH 04/26] feat(acp): add AcpClient/AcpSession and mandocode --acp-probe AcpClient performs the initialize handshake (v1 only), opens sessions and routes agent requests (permissions, fs/*) to an IAcpClientHandler; terminal/* is not advertised. AcpSession runs one turn at a time, streams updates and implements cancel (pending permissions answered as cancelled, grace period, unresponsive agents reported). Auth-required is surfaced, never answered with authenticate. mandocode --acp-probe launches an agent after showing the full resolved command, runs initialize + session/new and reports the result. Also: DrainNotificationsAsync now waits for queued notifications after the connection closed, so updates sent right before a crash are not lost. --- docs/acp.md | 68 ++ src/MandoCode.Acp/AcpExceptions.cs | 37 ++ src/MandoCode.Acp/Client/AcpClient.cs | 212 +++++++ src/MandoCode.Acp/Client/AcpSession.cs | 216 +++++++ src/MandoCode.Acp/Client/AcpTurn.cs | 51 ++ src/MandoCode.Acp/Client/IAcpClientHandler.cs | 37 ++ .../JsonRpc/JsonRpcConnection.cs | 4 +- src/MandoCode/Program.cs | 10 + .../Services/Acp/AcpConnectionProbe.cs | 177 ++++++ tests/MandoCode.Acp.MockAgent/Program.cs | 202 +++++- .../Acp/AcpClientProcessTests.cs | 195 ++++++ tests/MandoCode.Tests/Acp/AcpClientTests.cs | 584 ++++++++++++++++++ .../Acp/JsonRpcConnectionTests.cs | 2 +- 13 files changed, 1771 insertions(+), 24 deletions(-) create mode 100644 docs/acp.md create mode 100644 src/MandoCode.Acp/Client/AcpClient.cs create mode 100644 src/MandoCode.Acp/Client/AcpSession.cs create mode 100644 src/MandoCode.Acp/Client/AcpTurn.cs create mode 100644 src/MandoCode.Acp/Client/IAcpClientHandler.cs create mode 100644 src/MandoCode/Services/Acp/AcpConnectionProbe.cs create mode 100644 tests/MandoCode.Tests/Acp/AcpClientProcessTests.cs create mode 100644 tests/MandoCode.Tests/Acp/AcpClientTests.cs diff --git a/docs/acp.md b/docs/acp.md new file mode 100644 index 0000000..db799be --- /dev/null +++ b/docs/acp.md @@ -0,0 +1,68 @@ +# ACP agents (Agent Client Protocol) + +MandoCode can run an external coding agent as a child process and talk to it over the +[Agent Client Protocol](https://agentclientprotocol.com) (ACP v1, JSON-RPC 2.0 over stdio, NDJSON). +Authentication is the agent's own business; MandoCode never handles agent tokens. + +The protocol layer lives in `src/MandoCode.Acp` (no UI dependencies, no third-party ACP libraries). +Schema: pinned to tag `v1.16.0`, vendored in `tests/MandoCode.Tests/Acp/schema/schema.v1.json`. + +## Launch rules + +An agent command is code that runs with your permissions, so launching is deliberately strict: + +- No shell: `ProcessStartInfo` with `UseShellExecute = false` and `ArgumentList`. + `cmd.exe`, `powershell`, `sh -c` and friends are refused. +- The command must resolve (through `PATH`, or as an absolute path) to a real executable: + `.exe` on Windows, ELF/Mach-O on Unix. `.cmd`, `.bat`, `.ps1` and `#!` scripts are refused: + *specify the path to an .exe or run the adapter as `node