diff --git a/AGENTS.md b/AGENTS.md index a9c52b89..13c76c49 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -197,6 +197,12 @@ ACP model changes must be traceable to the upstream schema or an intentional SDK Do not infer wire compatibility from similar Kotlin types. Confirm serialized JSON shapes with tests. +A serializer defines its type's wire shape, so it stays next to the model; there is no separate `serialization` package: + +- A type's custom serializer lives in the model's file. +- A serializer base or helper used by several files gets its own file named after it, in the same package, such as `JsonObjectSerializer.kt` or v2 `OpenTaggedUnionSerializer.kt`. +- A file over the length limit splits by model concern, and the serializers move with their types, as in `SubagentSessionUpdateSerializers.kt`. + ## Kotlin Style Follow the official Kotlin style configured in `gradle.properties` and the existing package layout. diff --git a/acp-model/api/acp-model.api b/acp-model/api/acp-model.api index 4a98cff2..6c0cfa97 100644 --- a/acp-model/api/acp-model.api +++ b/acp-model/api/acp-model.api @@ -1069,8 +1069,8 @@ public final class com/agentclientprotocol/model/CancelRequestNotification$Compa public final class com/agentclientprotocol/model/ClientCapabilities : com/agentclientprotocol/model/AcpCapabilities, com/agentclientprotocol/model/AcpWithMeta { public static final field Companion Lcom/agentclientprotocol/model/ClientCapabilities$Companion; public fun ()V - public fun (Lcom/agentclientprotocol/model/FileSystemCapability;ZLcom/agentclientprotocol/model/PlanCapabilities;Lcom/agentclientprotocol/model/AuthCapabilities;Lcom/agentclientprotocol/model/ClientNesCapabilities;Ljava/util/List;Lcom/agentclientprotocol/model/ElicitationCapabilities;Lkotlinx/serialization/json/JsonElement;)V - public synthetic fun (Lcom/agentclientprotocol/model/FileSystemCapability;ZLcom/agentclientprotocol/model/PlanCapabilities;Lcom/agentclientprotocol/model/AuthCapabilities;Lcom/agentclientprotocol/model/ClientNesCapabilities;Ljava/util/List;Lcom/agentclientprotocol/model/ElicitationCapabilities;Lkotlinx/serialization/json/JsonElement;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public fun (Lcom/agentclientprotocol/model/FileSystemCapability;ZLcom/agentclientprotocol/model/PlanCapabilities;Lcom/agentclientprotocol/model/AuthCapabilities;Lcom/agentclientprotocol/model/ClientNesCapabilities;Ljava/util/List;Lcom/agentclientprotocol/model/ElicitationCapabilities;Lkotlinx/serialization/json/JsonElement;Lcom/agentclientprotocol/model/SubagentCapabilities;)V + public synthetic fun (Lcom/agentclientprotocol/model/FileSystemCapability;ZLcom/agentclientprotocol/model/PlanCapabilities;Lcom/agentclientprotocol/model/AuthCapabilities;Lcom/agentclientprotocol/model/ClientNesCapabilities;Ljava/util/List;Lcom/agentclientprotocol/model/ElicitationCapabilities;Lkotlinx/serialization/json/JsonElement;Lcom/agentclientprotocol/model/SubagentCapabilities;ILkotlin/jvm/internal/DefaultConstructorMarker;)V public final fun component1 ()Lcom/agentclientprotocol/model/FileSystemCapability; public final fun component2 ()Z public final fun component3 ()Lcom/agentclientprotocol/model/PlanCapabilities; @@ -1079,8 +1079,9 @@ public final class com/agentclientprotocol/model/ClientCapabilities : com/agentc public final fun component6 ()Ljava/util/List; public final fun component7 ()Lcom/agentclientprotocol/model/ElicitationCapabilities; public final fun component8 ()Lkotlinx/serialization/json/JsonElement; - public final fun copy (Lcom/agentclientprotocol/model/FileSystemCapability;ZLcom/agentclientprotocol/model/PlanCapabilities;Lcom/agentclientprotocol/model/AuthCapabilities;Lcom/agentclientprotocol/model/ClientNesCapabilities;Ljava/util/List;Lcom/agentclientprotocol/model/ElicitationCapabilities;Lkotlinx/serialization/json/JsonElement;)Lcom/agentclientprotocol/model/ClientCapabilities; - public static synthetic fun copy$default (Lcom/agentclientprotocol/model/ClientCapabilities;Lcom/agentclientprotocol/model/FileSystemCapability;ZLcom/agentclientprotocol/model/PlanCapabilities;Lcom/agentclientprotocol/model/AuthCapabilities;Lcom/agentclientprotocol/model/ClientNesCapabilities;Ljava/util/List;Lcom/agentclientprotocol/model/ElicitationCapabilities;Lkotlinx/serialization/json/JsonElement;ILjava/lang/Object;)Lcom/agentclientprotocol/model/ClientCapabilities; + public final fun component9 ()Lcom/agentclientprotocol/model/SubagentCapabilities; + public final fun copy (Lcom/agentclientprotocol/model/FileSystemCapability;ZLcom/agentclientprotocol/model/PlanCapabilities;Lcom/agentclientprotocol/model/AuthCapabilities;Lcom/agentclientprotocol/model/ClientNesCapabilities;Ljava/util/List;Lcom/agentclientprotocol/model/ElicitationCapabilities;Lkotlinx/serialization/json/JsonElement;Lcom/agentclientprotocol/model/SubagentCapabilities;)Lcom/agentclientprotocol/model/ClientCapabilities; + public static synthetic fun copy$default (Lcom/agentclientprotocol/model/ClientCapabilities;Lcom/agentclientprotocol/model/FileSystemCapability;ZLcom/agentclientprotocol/model/PlanCapabilities;Lcom/agentclientprotocol/model/AuthCapabilities;Lcom/agentclientprotocol/model/ClientNesCapabilities;Ljava/util/List;Lcom/agentclientprotocol/model/ElicitationCapabilities;Lkotlinx/serialization/json/JsonElement;Lcom/agentclientprotocol/model/SubagentCapabilities;ILjava/lang/Object;)Lcom/agentclientprotocol/model/ClientCapabilities; public fun equals (Ljava/lang/Object;)Z public final fun getAuth ()Lcom/agentclientprotocol/model/AuthCapabilities; public final fun getElicitation ()Lcom/agentclientprotocol/model/ElicitationCapabilities; @@ -1088,6 +1089,7 @@ public final class com/agentclientprotocol/model/ClientCapabilities : com/agentc public final fun getNes ()Lcom/agentclientprotocol/model/ClientNesCapabilities; public final fun getPlanCapabilities ()Lcom/agentclientprotocol/model/PlanCapabilities; public final fun getPositionEncodings ()Ljava/util/List; + public final fun getSubagents ()Lcom/agentclientprotocol/model/SubagentCapabilities; public final fun getTerminal ()Z public fun get_meta ()Lkotlinx/serialization/json/JsonElement; public fun hashCode ()I @@ -2855,6 +2857,71 @@ public final class com/agentclientprotocol/model/HttpHeader$Companion { public final fun serializer ()Lkotlinx/serialization/KSerializer; } +public abstract class com/agentclientprotocol/model/IdleStopReason { +} + +public final class com/agentclientprotocol/model/IdleStopReason$Cancelled : com/agentclientprotocol/model/IdleStopReason { + public static final field INSTANCE Lcom/agentclientprotocol/model/IdleStopReason$Cancelled; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/IdleStopReason$EndTurn : com/agentclientprotocol/model/IdleStopReason { + public static final field INSTANCE Lcom/agentclientprotocol/model/IdleStopReason$EndTurn; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/IdleStopReason$Error : com/agentclientprotocol/model/IdleStopReason { + public fun ()V + public fun (Lcom/agentclientprotocol/rpc/JsonRpcError;)V + public synthetic fun (Lcom/agentclientprotocol/rpc/JsonRpcError;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lcom/agentclientprotocol/rpc/JsonRpcError; + public final fun copy (Lcom/agentclientprotocol/rpc/JsonRpcError;)Lcom/agentclientprotocol/model/IdleStopReason$Error; + public static synthetic fun copy$default (Lcom/agentclientprotocol/model/IdleStopReason$Error;Lcom/agentclientprotocol/rpc/JsonRpcError;ILjava/lang/Object;)Lcom/agentclientprotocol/model/IdleStopReason$Error; + public fun equals (Ljava/lang/Object;)Z + public final fun getError ()Lcom/agentclientprotocol/rpc/JsonRpcError; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/IdleStopReason$MaxTokens : com/agentclientprotocol/model/IdleStopReason { + public static final field INSTANCE Lcom/agentclientprotocol/model/IdleStopReason$MaxTokens; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/IdleStopReason$MaxTurnRequests : com/agentclientprotocol/model/IdleStopReason { + public static final field INSTANCE Lcom/agentclientprotocol/model/IdleStopReason$MaxTurnRequests; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/IdleStopReason$Other : com/agentclientprotocol/model/IdleStopReason { + public fun (Ljava/lang/String;Lkotlinx/serialization/json/JsonObject;)V + public synthetic fun (Ljava/lang/String;Lkotlinx/serialization/json/JsonObject;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Lkotlinx/serialization/json/JsonObject; + public final fun copy (Ljava/lang/String;Lkotlinx/serialization/json/JsonObject;)Lcom/agentclientprotocol/model/IdleStopReason$Other; + public static synthetic fun copy$default (Lcom/agentclientprotocol/model/IdleStopReason$Other;Ljava/lang/String;Lkotlinx/serialization/json/JsonObject;ILjava/lang/Object;)Lcom/agentclientprotocol/model/IdleStopReason$Other; + public fun equals (Ljava/lang/Object;)Z + public final fun getFields ()Lkotlinx/serialization/json/JsonObject; + public final fun getStopReason ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/IdleStopReason$Refusal : com/agentclientprotocol/model/IdleStopReason { + public static final field INSTANCE Lcom/agentclientprotocol/model/IdleStopReason$Refusal; + public fun equals (Ljava/lang/Object;)Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class com/agentclientprotocol/model/Implementation : com/agentclientprotocol/model/AcpWithMeta { public static final field Companion Lcom/agentclientprotocol/model/Implementation$Companion; public fun (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lkotlinx/serialization/json/JsonElement;)V @@ -5886,6 +5953,24 @@ public final class com/agentclientprotocol/model/SessionAdditionalDirectoriesCap public final fun serializer ()Lkotlinx/serialization/KSerializer; } +public final class com/agentclientprotocol/model/SessionCancelCapabilities : com/agentclientprotocol/model/AcpWithMeta { + public static final field Companion Lcom/agentclientprotocol/model/SessionCancelCapabilities$Companion; + public fun ()V + public fun (Lkotlinx/serialization/json/JsonElement;)V + public synthetic fun (Lkotlinx/serialization/json/JsonElement;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lkotlinx/serialization/json/JsonElement; + public final fun copy (Lkotlinx/serialization/json/JsonElement;)Lcom/agentclientprotocol/model/SessionCancelCapabilities; + public static synthetic fun copy$default (Lcom/agentclientprotocol/model/SessionCancelCapabilities;Lkotlinx/serialization/json/JsonElement;ILjava/lang/Object;)Lcom/agentclientprotocol/model/SessionCancelCapabilities; + public fun equals (Ljava/lang/Object;)Z + public fun get_meta ()Lkotlinx/serialization/json/JsonElement; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/SessionCancelCapabilities$Companion { + public final fun serializer ()Lkotlinx/serialization/KSerializer; +} + public final class com/agentclientprotocol/model/SessionCapabilities : com/agentclientprotocol/model/AcpWithMeta { public static final field Companion Lcom/agentclientprotocol/model/SessionCapabilities$Companion; public fun ()V @@ -6971,6 +7056,87 @@ public final class com/agentclientprotocol/model/SessionUpdate$SessionInfoUpdate public final fun serializer ()Lkotlinx/serialization/KSerializer; } +public final class com/agentclientprotocol/model/SessionUpdate$SessionMessage : com/agentclientprotocol/model/SessionUpdate { + public static final field Companion Lcom/agentclientprotocol/model/SessionUpdate$SessionMessage$Companion; + public synthetic fun (Ljava/lang/String;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public synthetic fun (Ljava/lang/String;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1-Q0JOWoQ ()Ljava/lang/String; + public final fun component2 ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun component3 ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun component4 ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun component5 ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun component6 ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun component7 ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun copy-unNxBgg (Ljava/lang/String;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;)Lcom/agentclientprotocol/model/SessionUpdate$SessionMessage; + public static synthetic fun copy-unNxBgg$default (Lcom/agentclientprotocol/model/SessionUpdate$SessionMessage;Ljava/lang/String;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;ILjava/lang/Object;)Lcom/agentclientprotocol/model/SessionUpdate$SessionMessage; + public fun equals (Ljava/lang/Object;)Z + public final fun getContent ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun getMessageId-Q0JOWoQ ()Ljava/lang/String; + public final fun getRecipientMessageId ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun getRecipientSessionId ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun getSenderMessageId ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun getSenderSessionId ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun get_meta ()Lcom/agentclientprotocol/model/MaybeUndefined; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/SessionUpdate$SessionMessage$Companion { + public final fun serializer ()Lkotlinx/serialization/KSerializer; +} + +public final class com/agentclientprotocol/model/SessionUpdate$SessionMessageChunk : com/agentclientprotocol/model/SessionUpdate, com/agentclientprotocol/model/AcpWithMeta { + public static final field Companion Lcom/agentclientprotocol/model/SessionUpdate$SessionMessageChunk$Companion; + public synthetic fun (Ljava/lang/String;Lcom/agentclientprotocol/model/ContentBlock;Lkotlinx/serialization/json/JsonElement;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public synthetic fun (Ljava/lang/String;Lcom/agentclientprotocol/model/ContentBlock;Lkotlinx/serialization/json/JsonElement;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1-Q0JOWoQ ()Ljava/lang/String; + public final fun component2 ()Lcom/agentclientprotocol/model/ContentBlock; + public final fun component3 ()Lkotlinx/serialization/json/JsonElement; + public final fun copy-jGZKPAM (Ljava/lang/String;Lcom/agentclientprotocol/model/ContentBlock;Lkotlinx/serialization/json/JsonElement;)Lcom/agentclientprotocol/model/SessionUpdate$SessionMessageChunk; + public static synthetic fun copy-jGZKPAM$default (Lcom/agentclientprotocol/model/SessionUpdate$SessionMessageChunk;Ljava/lang/String;Lcom/agentclientprotocol/model/ContentBlock;Lkotlinx/serialization/json/JsonElement;ILjava/lang/Object;)Lcom/agentclientprotocol/model/SessionUpdate$SessionMessageChunk; + public fun equals (Ljava/lang/Object;)Z + public final fun getContent ()Lcom/agentclientprotocol/model/ContentBlock; + public final fun getMessageId-Q0JOWoQ ()Ljava/lang/String; + public fun get_meta ()Lkotlinx/serialization/json/JsonElement; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/SessionUpdate$SessionMessageChunk$Companion { + public final fun serializer ()Lkotlinx/serialization/KSerializer; +} + +public final class com/agentclientprotocol/model/SessionUpdate$SubagentUpdate : com/agentclientprotocol/model/SessionUpdate { + public static final field Companion Lcom/agentclientprotocol/model/SessionUpdate$SubagentUpdate$Companion; + public synthetic fun (Ljava/lang/String;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public synthetic fun (Ljava/lang/String;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1-7EW-EgU ()Ljava/lang/String; + public final fun component2 ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun component3 ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun component4 ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun component5 ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun component6 ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun component7 ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun component8 ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun copy-aXQG-3s (Ljava/lang/String;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;)Lcom/agentclientprotocol/model/SessionUpdate$SubagentUpdate; + public static synthetic fun copy-aXQG-3s$default (Lcom/agentclientprotocol/model/SessionUpdate$SubagentUpdate;Ljava/lang/String;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;Lcom/agentclientprotocol/model/MaybeUndefined;ILjava/lang/Object;)Lcom/agentclientprotocol/model/SessionUpdate$SubagentUpdate; + public fun equals (Ljava/lang/Object;)Z + public final fun getAdditionalDirectories ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun getCapabilities ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun getCwd ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun getDescription ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun getSessionId-7EW-EgU ()Ljava/lang/String; + public final fun getState ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun getTitle ()Lcom/agentclientprotocol/model/MaybeUndefined; + public final fun get_meta ()Lcom/agentclientprotocol/model/MaybeUndefined; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/SessionUpdate$SubagentUpdate$Companion { + public final fun serializer ()Lkotlinx/serialization/KSerializer; +} + public final class com/agentclientprotocol/model/SessionUpdate$ToolCall : com/agentclientprotocol/model/SessionUpdate, com/agentclientprotocol/model/AcpWithMeta { public static final field Companion Lcom/agentclientprotocol/model/SessionUpdate$ToolCall$Companion; public synthetic fun (Ljava/lang/String;Ljava/lang/String;Lcom/agentclientprotocol/model/ToolKind;Lcom/agentclientprotocol/model/ToolCallStatus;Ljava/util/List;Ljava/util/List;Lkotlinx/serialization/json/JsonElement;Lkotlinx/serialization/json/JsonElement;Lkotlinx/serialization/json/JsonElement;ILkotlin/jvm/internal/DefaultConstructorMarker;)V @@ -7462,6 +7628,84 @@ public final class com/agentclientprotocol/model/StartNesResponse$Companion { public final fun serializer ()Lkotlinx/serialization/KSerializer; } +public abstract class com/agentclientprotocol/model/StateUpdate { + public static final field Companion Lcom/agentclientprotocol/model/StateUpdate$Companion; +} + +public final class com/agentclientprotocol/model/StateUpdate$Companion { + public final fun serializer ()Lkotlinx/serialization/KSerializer; +} + +public final class com/agentclientprotocol/model/StateUpdate$Idle : com/agentclientprotocol/model/StateUpdate, com/agentclientprotocol/model/AcpWithMeta { + public fun ()V + public fun (Lcom/agentclientprotocol/model/IdleStopReason;Lcom/agentclientprotocol/model/Usage;Lkotlinx/serialization/json/JsonElement;)V + public synthetic fun (Lcom/agentclientprotocol/model/IdleStopReason;Lcom/agentclientprotocol/model/Usage;Lkotlinx/serialization/json/JsonElement;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lcom/agentclientprotocol/model/IdleStopReason; + public final fun component2 ()Lcom/agentclientprotocol/model/Usage; + public final fun component3 ()Lkotlinx/serialization/json/JsonElement; + public final fun copy (Lcom/agentclientprotocol/model/IdleStopReason;Lcom/agentclientprotocol/model/Usage;Lkotlinx/serialization/json/JsonElement;)Lcom/agentclientprotocol/model/StateUpdate$Idle; + public static synthetic fun copy$default (Lcom/agentclientprotocol/model/StateUpdate$Idle;Lcom/agentclientprotocol/model/IdleStopReason;Lcom/agentclientprotocol/model/Usage;Lkotlinx/serialization/json/JsonElement;ILjava/lang/Object;)Lcom/agentclientprotocol/model/StateUpdate$Idle; + public fun equals (Ljava/lang/Object;)Z + public final fun getStopReason ()Lcom/agentclientprotocol/model/IdleStopReason; + public final fun getUsage ()Lcom/agentclientprotocol/model/Usage; + public fun get_meta ()Lkotlinx/serialization/json/JsonElement; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/StateUpdate$Other : com/agentclientprotocol/model/StateUpdate { + public fun (Ljava/lang/String;Lkotlinx/serialization/json/JsonObject;)V + public synthetic fun (Ljava/lang/String;Lkotlinx/serialization/json/JsonObject;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Ljava/lang/String; + public final fun component2 ()Lkotlinx/serialization/json/JsonObject; + public final fun copy (Ljava/lang/String;Lkotlinx/serialization/json/JsonObject;)Lcom/agentclientprotocol/model/StateUpdate$Other; + public static synthetic fun copy$default (Lcom/agentclientprotocol/model/StateUpdate$Other;Ljava/lang/String;Lkotlinx/serialization/json/JsonObject;ILjava/lang/Object;)Lcom/agentclientprotocol/model/StateUpdate$Other; + public fun equals (Ljava/lang/Object;)Z + public final fun getFields ()Lkotlinx/serialization/json/JsonObject; + public final fun getState ()Ljava/lang/String; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/StateUpdate$RequiresAction : com/agentclientprotocol/model/StateUpdate, com/agentclientprotocol/model/AcpWithMeta { + public fun ()V + public fun (Lkotlinx/serialization/json/JsonElement;)V + public synthetic fun (Lkotlinx/serialization/json/JsonElement;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lkotlinx/serialization/json/JsonElement; + public final fun copy (Lkotlinx/serialization/json/JsonElement;)Lcom/agentclientprotocol/model/StateUpdate$RequiresAction; + public static synthetic fun copy$default (Lcom/agentclientprotocol/model/StateUpdate$RequiresAction;Lkotlinx/serialization/json/JsonElement;ILjava/lang/Object;)Lcom/agentclientprotocol/model/StateUpdate$RequiresAction; + public fun equals (Ljava/lang/Object;)Z + public fun get_meta ()Lkotlinx/serialization/json/JsonElement; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/StateUpdate$Running : com/agentclientprotocol/model/StateUpdate, com/agentclientprotocol/model/AcpWithMeta { + public fun ()V + public fun (Lkotlinx/serialization/json/JsonElement;)V + public synthetic fun (Lkotlinx/serialization/json/JsonElement;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lkotlinx/serialization/json/JsonElement; + public final fun copy (Lkotlinx/serialization/json/JsonElement;)Lcom/agentclientprotocol/model/StateUpdate$Running; + public static synthetic fun copy$default (Lcom/agentclientprotocol/model/StateUpdate$Running;Lkotlinx/serialization/json/JsonElement;ILjava/lang/Object;)Lcom/agentclientprotocol/model/StateUpdate$Running; + public fun equals (Ljava/lang/Object;)Z + public fun get_meta ()Lkotlinx/serialization/json/JsonElement; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/StateUpdate$Unknown : com/agentclientprotocol/model/StateUpdate, com/agentclientprotocol/model/AcpWithMeta { + public fun ()V + public fun (Lkotlinx/serialization/json/JsonElement;)V + public synthetic fun (Lkotlinx/serialization/json/JsonElement;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lkotlinx/serialization/json/JsonElement; + public final fun copy (Lkotlinx/serialization/json/JsonElement;)Lcom/agentclientprotocol/model/StateUpdate$Unknown; + public static synthetic fun copy$default (Lcom/agentclientprotocol/model/StateUpdate$Unknown;Lkotlinx/serialization/json/JsonElement;ILjava/lang/Object;)Lcom/agentclientprotocol/model/StateUpdate$Unknown; + public fun equals (Ljava/lang/Object;)Z + public fun get_meta ()Lkotlinx/serialization/json/JsonElement; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class com/agentclientprotocol/model/StopReason : java/lang/Enum { public static final field CANCELLED Lcom/agentclientprotocol/model/StopReason; public static final field Companion Lcom/agentclientprotocol/model/StopReason$Companion; @@ -7538,6 +7782,44 @@ public final class com/agentclientprotocol/model/StringPropertySchema$Companion public final fun serializer ()Lkotlinx/serialization/KSerializer; } +public final class com/agentclientprotocol/model/SubagentCapabilities : com/agentclientprotocol/model/AcpWithMeta { + public static final field Companion Lcom/agentclientprotocol/model/SubagentCapabilities$Companion; + public fun ()V + public fun (Lkotlinx/serialization/json/JsonElement;)V + public synthetic fun (Lkotlinx/serialization/json/JsonElement;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lkotlinx/serialization/json/JsonElement; + public final fun copy (Lkotlinx/serialization/json/JsonElement;)Lcom/agentclientprotocol/model/SubagentCapabilities; + public static synthetic fun copy$default (Lcom/agentclientprotocol/model/SubagentCapabilities;Lkotlinx/serialization/json/JsonElement;ILjava/lang/Object;)Lcom/agentclientprotocol/model/SubagentCapabilities; + public fun equals (Ljava/lang/Object;)Z + public fun get_meta ()Lkotlinx/serialization/json/JsonElement; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/SubagentCapabilities$Companion { + public final fun serializer ()Lkotlinx/serialization/KSerializer; +} + +public final class com/agentclientprotocol/model/SubagentSessionCapabilities : com/agentclientprotocol/model/AcpWithMeta { + public static final field Companion Lcom/agentclientprotocol/model/SubagentSessionCapabilities$Companion; + public fun ()V + public fun (Lcom/agentclientprotocol/model/SessionCancelCapabilities;Lkotlinx/serialization/json/JsonElement;)V + public synthetic fun (Lcom/agentclientprotocol/model/SessionCancelCapabilities;Lkotlinx/serialization/json/JsonElement;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1 ()Lcom/agentclientprotocol/model/SessionCancelCapabilities; + public final fun component2 ()Lkotlinx/serialization/json/JsonElement; + public final fun copy (Lcom/agentclientprotocol/model/SessionCancelCapabilities;Lkotlinx/serialization/json/JsonElement;)Lcom/agentclientprotocol/model/SubagentSessionCapabilities; + public static synthetic fun copy$default (Lcom/agentclientprotocol/model/SubagentSessionCapabilities;Lcom/agentclientprotocol/model/SessionCancelCapabilities;Lkotlinx/serialization/json/JsonElement;ILjava/lang/Object;)Lcom/agentclientprotocol/model/SubagentSessionCapabilities; + public fun equals (Ljava/lang/Object;)Z + public final fun getCancel ()Lcom/agentclientprotocol/model/SessionCancelCapabilities; + public fun get_meta ()Lkotlinx/serialization/json/JsonElement; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final class com/agentclientprotocol/model/SubagentSessionCapabilities$Companion { + public final fun serializer ()Lkotlinx/serialization/KSerializer; +} + public final class com/agentclientprotocol/model/SuggestNesRequest : com/agentclientprotocol/model/AcpRequest, com/agentclientprotocol/model/AcpWithSessionId { public static final field Companion Lcom/agentclientprotocol/model/SuggestNesRequest$Companion; public synthetic fun (Ljava/lang/String;Ljava/lang/String;JLcom/agentclientprotocol/model/NesPosition;Lcom/agentclientprotocol/model/NesRange;Lcom/agentclientprotocol/model/NesTriggerKind;Lcom/agentclientprotocol/model/NesSuggestContext;Lkotlinx/serialization/json/JsonElement;ILkotlin/jvm/internal/DefaultConstructorMarker;)V @@ -7849,6 +8131,36 @@ public final class com/agentclientprotocol/model/ToolCallContent$Diff$Companion public final fun serializer ()Lkotlinx/serialization/KSerializer; } +public final class com/agentclientprotocol/model/ToolCallContent$Session : com/agentclientprotocol/model/ToolCallContent, com/agentclientprotocol/model/AcpWithMeta { + public static final field Companion Lcom/agentclientprotocol/model/ToolCallContent$Session$Companion; + public synthetic fun (Ljava/lang/String;Lkotlinx/serialization/json/JsonElement;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public synthetic fun (Ljava/lang/String;Lkotlinx/serialization/json/JsonElement;Lkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun component1-7EW-EgU ()Ljava/lang/String; + public final fun component2 ()Lkotlinx/serialization/json/JsonElement; + public final fun copy-HxD9utI (Ljava/lang/String;Lkotlinx/serialization/json/JsonElement;)Lcom/agentclientprotocol/model/ToolCallContent$Session; + public static synthetic fun copy-HxD9utI$default (Lcom/agentclientprotocol/model/ToolCallContent$Session;Ljava/lang/String;Lkotlinx/serialization/json/JsonElement;ILjava/lang/Object;)Lcom/agentclientprotocol/model/ToolCallContent$Session; + public fun equals (Ljava/lang/Object;)Z + public final fun getSessionId-7EW-EgU ()Ljava/lang/String; + public fun get_meta ()Lkotlinx/serialization/json/JsonElement; + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public final synthetic class com/agentclientprotocol/model/ToolCallContent$Session$$serializer : kotlinx/serialization/internal/GeneratedSerializer { + public static final field INSTANCE Lcom/agentclientprotocol/model/ToolCallContent$Session$$serializer; + public final fun childSerializers ()[Lkotlinx/serialization/KSerializer; + public final fun deserialize (Lkotlinx/serialization/encoding/Decoder;)Lcom/agentclientprotocol/model/ToolCallContent$Session; + public synthetic fun deserialize (Lkotlinx/serialization/encoding/Decoder;)Ljava/lang/Object; + public final fun getDescriptor ()Lkotlinx/serialization/descriptors/SerialDescriptor; + public final fun serialize (Lkotlinx/serialization/encoding/Encoder;Lcom/agentclientprotocol/model/ToolCallContent$Session;)V + public synthetic fun serialize (Lkotlinx/serialization/encoding/Encoder;Ljava/lang/Object;)V + public fun typeParametersSerializers ()[Lkotlinx/serialization/KSerializer; +} + +public final class com/agentclientprotocol/model/ToolCallContent$Session$Companion { + public final fun serializer ()Lkotlinx/serialization/KSerializer; +} + public final class com/agentclientprotocol/model/ToolCallContent$Terminal : com/agentclientprotocol/model/ToolCallContent, com/agentclientprotocol/model/AcpWithMeta { public static final field Companion Lcom/agentclientprotocol/model/ToolCallContent$Terminal$Companion; public fun (Ljava/lang/String;Lkotlinx/serialization/json/JsonElement;)V diff --git a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Capabilities.kt b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Capabilities.kt index 1b7d3241..90dfff55 100644 --- a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Capabilities.kt +++ b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Capabilities.kt @@ -94,7 +94,9 @@ public data class ClientCapabilities( val positionEncodings: List? = null, @property:UnstableApi val elicitation: ElicitationCapabilities? = null, - override val _meta: JsonElement? = null + override val _meta: JsonElement? = null, + @Serializable(with = LenientSubagentCapabilitiesSerializer::class) + val subagents: SubagentCapabilities? = null, ) : AcpCapabilities, AcpWithMeta /** @@ -157,15 +159,10 @@ public data class SessionDeleteCapabilities( ) : AcpWithMeta /** - * **UNSTABLE** - * - * This capability is not part of the spec yet, and may be removed or changed at any point. - * * Capabilities for the `session/close` method. * * By supplying `{}` it means that the agent supports closing of sessions. */ -@UnstableApi @Serializable public data class SessionCloseCapabilities( override val _meta: JsonElement? = null @@ -197,7 +194,6 @@ public data class SessionCapabilities( val list: SessionListCapabilities? = null, val resume: SessionResumeCapabilities? = null, val delete: SessionDeleteCapabilities? = null, - @property:UnstableApi val close: SessionCloseCapabilities? = null, @property:UnstableApi val additionalDirectories: SessionAdditionalDirectoriesCapabilities? = null, diff --git a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/JsonObjectSerializer.kt b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/JsonObjectSerializer.kt new file mode 100644 index 00000000..88ebb035 --- /dev/null +++ b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/JsonObjectSerializer.kt @@ -0,0 +1,110 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package com.agentclientprotocol.model + +import kotlinx.serialization.DeserializationStrategy +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerializationException +import kotlinx.serialization.builtins.nullable +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.buildClassSerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonDecoder +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonEncoder +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive + +/** + * Base for hand-written serializers that read and write a model as one JSON object. + * + * A value that is not a JSON object fails with [SerializationException]. Subclasses decide which + * of their fields tolerate malformed input. + */ +internal abstract class JsonObjectSerializer(serialName: String) : KSerializer { + override val descriptor: SerialDescriptor = buildClassSerialDescriptor(serialName) + + abstract fun decode(json: Json, obj: JsonObject): T + + abstract fun encode(json: Json, value: T): JsonObject + + final override fun serialize(encoder: Encoder, value: T) { + val jsonEncoder = encoder as? JsonEncoder + ?: throw SerializationException("${descriptor.serialName} supports only JSON encoding") + jsonEncoder.encodeJsonElement(encode(jsonEncoder.json, value)) + } + + final override fun deserialize(decoder: Decoder): T { + val jsonDecoder = decoder as? JsonDecoder + ?: throw SerializationException("${descriptor.serialName} supports only JSON decoding") + val element = jsonDecoder.decodeJsonElement() + val obj = element as? JsonObject + ?: throw SerializationException("${descriptor.serialName} must be a JSON object") + return decode(jsonDecoder.json, obj) + } +} + +/** + * The `_meta` of this object, or `null` when it is absent, `null` or not a JSON object, as Rust's `DefaultOnError` + * on `Meta` decodes it. + */ +internal fun JsonObject.lenientMeta(): JsonObject? = this["_meta"] as? JsonObject + +/** + * Decodes [key] with [deserializer], or returns `null` when it is absent, `null` or fails to decode, as Rust's + * `DefaultOnError` on an `Option` field does. + */ +internal fun JsonObject.decodeOrNull( + json: Json, + key: String, + deserializer: DeserializationStrategy, +): T? { + val element = this[key] ?: return null + if (element is JsonNull) return null + return json.decodeLenientlyOrNull(deserializer, element) +} + +/** + * Decodes [element] with [deserializer], or returns `null` when it fails to decode, for the lenient decoders. + */ +internal fun Json.decodeLenientlyOrNull(deserializer: DeserializationStrategy, element: JsonElement): T? = + try { + decodeFromJsonElement(deserializer, element) + } catch (_: Exception) { + // Broad: tree decoding reports malformed shapes through several exception types. + null + } + +/** + * The string value of this element, or `null` when it is not a JSON string. + */ +internal fun JsonElement?.stringOrNull(): String? = (this as? JsonPrimitive)?.takeIf { it.isString }?.content + +/** + * Serializer for an optional `_meta` property that decodes a value that is not a JSON object as `null`. + * + * Mirrors Rust's `DefaultOnError` on `Meta` for models whose other fields use generated serializers. + */ +internal object LenientMetaSerializer : KSerializer { + override val descriptor: SerialDescriptor = JsonElement.serializer().nullable.descriptor + + override fun serialize(encoder: Encoder, value: JsonElement?) { + if (value == null) { + encoder.encodeNull() + return + } + val jsonEncoder = encoder as? JsonEncoder + ?: throw SerializationException("_meta supports only JSON encoding") + jsonEncoder.encodeJsonElement(value) + } + + override fun deserialize(decoder: Decoder): JsonElement? { + val jsonDecoder = decoder as? JsonDecoder + ?: throw SerializationException("_meta supports only JSON decoding") + return jsonDecoder.decodeJsonElement() as? JsonObject + } +} diff --git a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/MaybeUndefined.kt b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/MaybeUndefined.kt index c9fa4985..a547b2e1 100644 --- a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/MaybeUndefined.kt +++ b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/MaybeUndefined.kt @@ -2,7 +2,6 @@ package com.agentclientprotocol.model -import com.agentclientprotocol.annotations.UnstableApi import kotlinx.serialization.DeserializationStrategy import kotlinx.serialization.SerializationStrategy import kotlinx.serialization.json.Json @@ -14,19 +13,15 @@ import kotlinx.serialization.json.JsonObjectBuilder /** * A three-state field for upsert payloads: absent, JSON `null`, or a value. * - * v2 upsert payloads (e.g. `ToolCallUpdate`, the message upserts) give optional fields - * patch semantics: an omitted field leaves the existing value unchanged, `null` explicitly - * clears it, and a concrete value replaces it. Kotlin's `T?` collapses the first two states, - * so such fields are modeled with this type instead. + * Upsert payloads (e.g. the v2 `ToolCallUpdate` and message upserts, and the v1 subagent + * session updates) give optional fields patch semantics: an omitted field leaves the existing + * value unchanged, `null` explicitly clears it, and a concrete value replaces it. Kotlin's + * `T?` collapses the first two states, so such fields are modeled with this type instead. * - * This type intentionally has no [kotlinx.serialization.KSerializer]: whether a key is - * present on the wire is decided by the containing object, not the field value, and - * `ACPJson`'s `explicitNulls = false` would strip an explicit `JsonNull` emitted by a field - * serializer. Structs with [MaybeUndefined] fields use hand-written serializers that decode - * by key presence (absent → [Undefined], `null` → [Null]) and encode by skipping [Undefined] - * and emitting `JsonNull` for [Null]. + * This type has no [kotlinx.serialization.KSerializer], because whether a key is present is + * decided by the containing object. A model with [MaybeUndefined] fields needs a hand-written + * serializer that omits [Undefined] and writes an explicit JSON `null` for [Null]. */ -@UnstableApi public sealed class MaybeUndefined { /** * The field is not present; an existing value is left unchanged. @@ -63,10 +58,9 @@ public sealed class MaybeUndefined { /** * This state unless it is [Undefined], in which case [other]. * - * An explicit [Null] is a present state and wins over [other], so folding a patch onto a - * stored state is `newer.orElse(older)`: the patch's [Null] survives as [Null] and callers - * can decide how to render an explicitly cleared value (mirrors Rust's `apply_update` field - * handling). Use [update] instead to collapse the fold to a plain nullable. + * An explicit [Null] wins over [other], so `newer.orElse(older)` folds a patch onto a stored + * state and keeps an explicit clear visible, as Rust's `apply_update` does. Use [update] to + * fold onto a plain nullable instead. */ public fun orElse(other: MaybeUndefined<@UnsafeVariance T>): MaybeUndefined = if (this is Undefined) other else this @@ -76,49 +70,41 @@ public sealed class MaybeUndefined { * Applies this field's patch semantics to a previous value: [MaybeUndefined.Undefined] * keeps [previous], [MaybeUndefined.Null] clears it, and [MaybeUndefined.Value] replaces it. */ -@UnstableApi public fun MaybeUndefined.update(previous: T?): T? = when (this) { is MaybeUndefined.Value -> value MaybeUndefined.Undefined -> previous MaybeUndefined.Null -> null } -// Shared building blocks for the hand-written serializers of structs with [MaybeUndefined] -// fields. Field semantics mirror the Rust schema's serde attributes: -// `#[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]` plus -// `DefaultOnError` (and `VecSkipError` for collections). +/* + * Helpers for the hand-written serializers of models with [MaybeUndefined] fields. They follow the Rust + * schema's `#[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]` with `DefaultOnError`, + * and `VecSkipError` for lists. + */ /** - * Decodes a tri-state field: absent key → [MaybeUndefined.Undefined], JSON `null` → - * [MaybeUndefined.Null], otherwise the decoded value. + * Decodes a tri-state field. A malformed value decodes as [MaybeUndefined.Undefined], as with Rust's + * `DefaultOnError`. * - * A present-but-malformed value degrades to [MaybeUndefined.Undefined] instead of failing, - * mirroring Rust's `DefaultOnError` on every `MaybeUndefined` field of the v2 schema. + * `ACPJson` is lenient and decodes a JSON number or boolean as a string, so a string field that must + * reject them checks the element itself. */ -@OptIn(UnstableApi::class) -internal fun JsonObject.decodeMaybeUndefined( +internal fun JsonObject.decodeMaybeUndefined( json: Json, key: String, deserializer: DeserializationStrategy, ): MaybeUndefined { val element = this[key] ?: return MaybeUndefined.Undefined if (element is JsonNull) return MaybeUndefined.Null - return try { - MaybeUndefined.Value(json.decodeFromJsonElement(deserializer, element)) - } catch (_: Exception) { - // DefaultOnError parity: kotlinx tree decoding reports malformed shapes through a - // variety of RuntimeExceptions, not just SerializationException. - MaybeUndefined.Undefined - } + val value = json.decodeLenientlyOrNull(deserializer, element) ?: return MaybeUndefined.Undefined + return MaybeUndefined.Value(value) } /** - * Decodes a tri-state collection field like [decodeMaybeUndefined], with Rust's `VecSkipError` - * semantics on top: items that fail to decode are skipped instead of failing the field, and a - * present-but-non-array value degrades to [MaybeUndefined.Undefined]. + * Decodes a tri-state list field, skipping items that fail to decode, as Rust's `VecSkipError` does. + * A value that is not an array decodes as [MaybeUndefined.Undefined]. */ -@OptIn(UnstableApi::class) -internal fun JsonObject.decodeMaybeUndefinedList( +internal fun JsonObject.decodeMaybeUndefinedList( json: Json, key: String, itemDeserializer: DeserializationStrategy, @@ -130,27 +116,17 @@ internal fun JsonObject.decodeMaybeUndefinedList( } /** - * Decodes the items of this array with Rust's `VecSkipError` semantics: an item that fails to decode - * is skipped instead of failing the whole list. + * Decodes the items of this array, skipping those that fail to decode, as Rust's `VecSkipError` does. */ -internal fun JsonArray.decodeSkippingInvalid( +internal fun JsonArray.decodeSkippingInvalid( json: Json, itemDeserializer: DeserializationStrategy, -): List = mapNotNull { item -> - try { - json.decodeFromJsonElement(itemDeserializer, item) - } catch (_: Exception) { - // See decodeMaybeUndefined for why the catch is broad. - null - } -} +): List = mapNotNull { item -> json.decodeLenientlyOrNull(itemDeserializer, item) } /** - * Encodes a tri-state field: [MaybeUndefined.Undefined] emits nothing, [MaybeUndefined.Null] - * emits an explicit JSON `null` (building the [JsonObject] directly bypasses `ACPJson`'s - * `explicitNulls = false`), and [MaybeUndefined.Value] emits the encoded value. + * Encodes a tri-state field: [MaybeUndefined.Undefined] writes nothing and [MaybeUndefined.Null] + * writes an explicit JSON `null`. */ -@OptIn(UnstableApi::class) internal fun JsonObjectBuilder.putMaybeUndefined( json: Json, key: String, @@ -159,6 +135,7 @@ internal fun JsonObjectBuilder.putMaybeUndefined( ) { when (value) { MaybeUndefined.Undefined -> {} + // Put into the object directly, so `ACPJson`'s `explicitNulls = false` can't drop it. MaybeUndefined.Null -> put(key, JsonNull) is MaybeUndefined.Value -> put(key, json.encodeToJsonElement(serializer, value.value)) } diff --git a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Methods.kt b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Methods.kt index 906dc8bd..0e9dcdf4 100644 --- a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Methods.kt +++ b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Methods.kt @@ -215,7 +215,6 @@ public open class AcpMethod(public val methodName: MethodName) { SetSessionConfigOptionResponse.serializer() ) - @UnstableApi public object SessionClose : AcpSessionRequestResponseMethod( "session/close", CloseSessionRequest.serializer(), @@ -504,7 +503,6 @@ public open class AcpMethod(public val methodName: MethodName) { ) public val SessionSetConfigOption: AcpSessionRequestResponseMethod get() = V1.SessionSetConfigOption - @UnstableApi @Deprecated( "Method objects are grouped by protocol version now", ReplaceWith("AcpMethod.AgentMethods.V1.SessionClose"), diff --git a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Requests.kt b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Requests.kt index b95ca58b..3b469e88 100644 --- a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Requests.kt +++ b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Requests.kt @@ -905,10 +905,6 @@ public data class DeleteSessionResponse( ) : AcpResponse /** - * **UNSTABLE** - * - * This capability is not part of the spec yet, and may be removed or changed at any point. - * * Request parameters for closing an active session. * * If supported, the agent must cancel any ongoing work related to the session @@ -917,7 +913,6 @@ public data class DeleteSessionResponse( * * Only available if the agent supports the `session.close` capability. */ -@UnstableApi @Serializable public data class CloseSessionRequest( override val sessionId: SessionId, @@ -925,13 +920,8 @@ public data class CloseSessionRequest( ) : AcpRequest, AcpWithSessionId /** - * **UNSTABLE** - * - * This capability is not part of the spec yet, and may be removed or changed at any point. - * * Response from closing a session. */ -@UnstableApi @Serializable public data class CloseSessionResponse( override val _meta: JsonElement? = null diff --git a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/SessionUpdate.kt b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/SessionUpdate.kt index b641a010..103f7918 100644 --- a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/SessionUpdate.kt +++ b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/SessionUpdate.kt @@ -270,6 +270,104 @@ public sealed class SessionUpdate { override val _meta: JsonElement? = null ) : SessionUpdate(), AcpWithMeta + /** + * A patch of a subagent session, sent by the agent as `subagent_update` on the parent's stream. Needs the + * `subagents` client capability. + * + * The first update for a [sessionId] announces the subagent under the session whose stream carries it; later + * updates patch it. + * + * ### Patch semantics + * + * Every field except [sessionId] is a [MaybeUndefined] patch: omitted leaves the stored value unchanged, `null` + * clears it, and a value replaces it. [capabilities] is replaced as a whole, not merged, so `{}` permits nothing, + * like `null`. The SDK does not validate or rewrite patch contents; for example, it does not check that [cwd] is + * absolute. + * + * ### Decoding + * + * Decoding is lenient for [title], [description], [capabilities], [state] and [_meta]: a malformed value decodes + * as [MaybeUndefined.Undefined]. [cwd] and [additionalDirectories] are strict, because the client acts on them: a + * malformed value fails the whole update. + * + * This type does not implement [AcpWithMeta], because [_meta] is a patch field. + * + * @property title the parent's display label for the subagent session + * @property description the parent's description of the subagent session's role + * @property capabilities what the client may send for the subagent session + * @property state the work state of the session; a value that is not a JSON object or has no string `state` + * decodes as [MaybeUndefined.Undefined] + * @property cwd absolute working directory of the session + * @property additionalDirectories absolute additional roots of the session + * @property _meta extension metadata; a value that is not a JSON object decodes as + * [MaybeUndefined.Undefined] + */ + @Serializable(with = SubagentUpdateSerializer::class) + public data class SubagentUpdate( + val sessionId: SessionId, + val title: MaybeUndefined = MaybeUndefined.Undefined, + val description: MaybeUndefined = MaybeUndefined.Undefined, + val capabilities: MaybeUndefined = MaybeUndefined.Undefined, + val state: MaybeUndefined = MaybeUndefined.Undefined, + val cwd: MaybeUndefined = MaybeUndefined.Undefined, + val additionalDirectories: MaybeUndefined> = MaybeUndefined.Undefined, + val _meta: MaybeUndefined = MaybeUndefined.Undefined, + ) : SessionUpdate() + + /** + * A message exchanged between sessions, sent as `session_message`. Needs the `subagents` client + * capability. + * + * Messages are keyed by [messageId] within the session whose stream carries the update: repeated updates with + * the same ID patch the stored message. Every other field is a [MaybeUndefined] patch: omitted leaves the + * stored value unchanged, `null` clears it, and a value replaces it. For [content], `[]` clears it too, but + * stays distinct from `null` on the wire and round-trips as it came in. A [content] value replaces everything + * accumulated for the message so far, including chunks of [SessionMessageChunk]. + * + * Decoding is lenient: a malformed patch field decodes as [MaybeUndefined.Undefined], an unparseable + * content block is skipped, and a content array whose items are all invalid decodes as `[]`. + * + * This type does not implement [AcpWithMeta], because [_meta] is a patch field. + * + * @property messageId identifies the message across updates and chunks + * @property senderSessionId the session that sent the message + * @property recipientSessionId the session the message is addressed to + * @property senderMessageId the message in the sender's session that this one corresponds to + * @property recipientMessageId the message in the recipient's session that this one corresponds to + * @property content complete replacement content of the message + * @property _meta extension metadata; a value that is not a JSON object decodes as + * [MaybeUndefined.Undefined] + */ + @Serializable(with = SessionMessageSerializer::class) + public data class SessionMessage( + val messageId: MessageId, + val senderSessionId: MaybeUndefined = MaybeUndefined.Undefined, + val recipientSessionId: MaybeUndefined = MaybeUndefined.Undefined, + val senderMessageId: MaybeUndefined = MaybeUndefined.Undefined, + val recipientMessageId: MaybeUndefined = MaybeUndefined.Undefined, + val content: MaybeUndefined> = MaybeUndefined.Undefined, + val _meta: MaybeUndefined = MaybeUndefined.Undefined, + ) : SessionUpdate() + + /** + * A chunk of a message exchanged between sessions, sent as `session_message_chunk`. Needs the + * `subagents` client capability. + * + * The chunk appends [content] to the message with the same [messageId]. It carries no participant fields: + * any such field on the wire is ignored. + * + * @property messageId the message the chunk belongs to + * @property content the appended content block + * @property _meta extension metadata; omitted, `null` and values that are not a JSON object all decode + * as `null` + */ + @Serializable(with = SessionMessageChunkSerializer::class) + public data class SessionMessageChunk( + val messageId: MessageId, + val content: ContentBlock, + override val _meta: JsonElement? = null, + ) : SessionUpdate(), AcpWithMeta + /** * Unknown session update for forward compatibility. * @@ -300,97 +398,22 @@ internal object SessionUpdateSerializer : KSerializer { override fun serialize(encoder: Encoder, value: SessionUpdate) { val jsonEncoder = encoder as JsonEncoder val jsonObject = when (value) { - is SessionUpdate.UserMessageChunk -> { - val base = ACPJson.encodeToJsonElement(SessionUpdate.UserMessageChunk.serializer(), value).jsonObject - buildJsonObject { - put(SESSION_UPDATE_DISCRIMINATOR, "user_message_chunk") - base.forEach { (k, v) -> put(k, v) } - } - } - is SessionUpdate.AgentMessageChunk -> { - val base = ACPJson.encodeToJsonElement(SessionUpdate.AgentMessageChunk.serializer(), value).jsonObject - buildJsonObject { - put(SESSION_UPDATE_DISCRIMINATOR, "agent_message_chunk") - base.forEach { (k, v) -> put(k, v) } - } - } - is SessionUpdate.AgentThoughtChunk -> { - val base = ACPJson.encodeToJsonElement(SessionUpdate.AgentThoughtChunk.serializer(), value).jsonObject - buildJsonObject { - put(SESSION_UPDATE_DISCRIMINATOR, "agent_thought_chunk") - base.forEach { (k, v) -> put(k, v) } - } - } - is SessionUpdate.ToolCall -> { - val base = ACPJson.encodeToJsonElement(SessionUpdate.ToolCall.serializer(), value).jsonObject - buildJsonObject { - put(SESSION_UPDATE_DISCRIMINATOR, "tool_call") - base.forEach { (k, v) -> put(k, v) } - } - } - is SessionUpdate.ToolCallUpdate -> { - val base = ACPJson.encodeToJsonElement(SessionUpdate.ToolCallUpdate.serializer(), value).jsonObject - buildJsonObject { - put(SESSION_UPDATE_DISCRIMINATOR, "tool_call_update") - base.forEach { (k, v) -> put(k, v) } - } - } - is SessionUpdate.PlanUpdate -> { - val base = ACPJson.encodeToJsonElement(SessionUpdate.PlanUpdate.serializer(), value).jsonObject - buildJsonObject { - put(SESSION_UPDATE_DISCRIMINATOR, "plan") - base.forEach { (k, v) -> put(k, v) } - } - } - is SessionUpdate.PlanUpdateV2 -> { - val base = ACPJson.encodeToJsonElement(SessionUpdate.PlanUpdateV2.serializer(), value).jsonObject - buildJsonObject { - put(SESSION_UPDATE_DISCRIMINATOR, "plan_update") - base.forEach { (k, v) -> put(k, v) } - } - } - is SessionUpdate.PlanRemoved -> { - val base = ACPJson.encodeToJsonElement(SessionUpdate.PlanRemoved.serializer(), value).jsonObject - buildJsonObject { - put(SESSION_UPDATE_DISCRIMINATOR, "plan_removed") - base.forEach { (k, v) -> put(k, v) } - } - } - is SessionUpdate.AvailableCommandsUpdate -> { - val base = ACPJson.encodeToJsonElement(SessionUpdate.AvailableCommandsUpdate.serializer(), value).jsonObject - buildJsonObject { - put(SESSION_UPDATE_DISCRIMINATOR, "available_commands_update") - base.forEach { (k, v) -> put(k, v) } - } - } - is SessionUpdate.CurrentModeUpdate -> { - val base = ACPJson.encodeToJsonElement(SessionUpdate.CurrentModeUpdate.serializer(), value).jsonObject - buildJsonObject { - put(SESSION_UPDATE_DISCRIMINATOR, "current_mode_update") - base.forEach { (k, v) -> put(k, v) } - } - } - is SessionUpdate.ConfigOptionUpdate -> { - val base = ACPJson.encodeToJsonElement(SessionUpdate.ConfigOptionUpdate.serializer(), value).jsonObject - buildJsonObject { - put(SESSION_UPDATE_DISCRIMINATOR, "config_option_update") - base.forEach { (k, v) -> put(k, v) } - } - } - is SessionUpdate.SessionInfoUpdate -> { - val base = ACPJson.encodeToJsonElement(SessionUpdate.SessionInfoUpdate.serializer(), value).jsonObject - buildJsonObject { - put(SESSION_UPDATE_DISCRIMINATOR, "session_info_update") - base.forEach { (k, v) -> put(k, v) } - } - } - is SessionUpdate.UsageUpdate -> { - val base = ACPJson.encodeToJsonElement(SessionUpdate.UsageUpdate.serializer(), value).jsonObject - buildJsonObject { - put(SESSION_UPDATE_DISCRIMINATOR, "usage_update") - base.forEach { (k, v) -> put(k, v) } - } - } + is SessionUpdate.UserMessageChunk -> tagged("user_message_chunk", SessionUpdate.UserMessageChunk.serializer(), value) + is SessionUpdate.AgentMessageChunk -> tagged("agent_message_chunk", SessionUpdate.AgentMessageChunk.serializer(), value) + is SessionUpdate.AgentThoughtChunk -> tagged("agent_thought_chunk", SessionUpdate.AgentThoughtChunk.serializer(), value) + is SessionUpdate.ToolCall -> tagged("tool_call", SessionUpdate.ToolCall.serializer(), value) + is SessionUpdate.ToolCallUpdate -> tagged("tool_call_update", SessionUpdate.ToolCallUpdate.serializer(), value) + is SessionUpdate.PlanUpdate -> tagged("plan", SessionUpdate.PlanUpdate.serializer(), value) + is SessionUpdate.PlanUpdateV2 -> tagged("plan_update", SessionUpdate.PlanUpdateV2.serializer(), value) + is SessionUpdate.PlanRemoved -> tagged("plan_removed", SessionUpdate.PlanRemoved.serializer(), value) + is SessionUpdate.AvailableCommandsUpdate -> tagged("available_commands_update", SessionUpdate.AvailableCommandsUpdate.serializer(), value) + is SessionUpdate.CurrentModeUpdate -> tagged("current_mode_update", SessionUpdate.CurrentModeUpdate.serializer(), value) + is SessionUpdate.ConfigOptionUpdate -> tagged("config_option_update", SessionUpdate.ConfigOptionUpdate.serializer(), value) + is SessionUpdate.SessionInfoUpdate -> tagged("session_info_update", SessionUpdate.SessionInfoUpdate.serializer(), value) + is SessionUpdate.UsageUpdate -> tagged("usage_update", SessionUpdate.UsageUpdate.serializer(), value) + is SessionUpdate.SubagentUpdate -> tagged("subagent_update", SessionUpdate.SubagentUpdate.serializer(), value) + is SessionUpdate.SessionMessage -> tagged("session_message", SessionUpdate.SessionMessage.serializer(), value) + is SessionUpdate.SessionMessageChunk -> tagged("session_message_chunk", SessionUpdate.SessionMessageChunk.serializer(), value) is SessionUpdate.UnknownSessionUpdate -> { // For unknown, use the stored type and raw JSON buildJsonObject { @@ -404,6 +427,17 @@ internal object SessionUpdateSerializer : KSerializer { jsonEncoder.encodeJsonElement(jsonObject) } + /** + * Encodes a known variant with [serializer] and puts the discriminator [type] first. + */ + private fun tagged(type: String, serializer: KSerializer, value: T): JsonObject { + val base = ACPJson.encodeToJsonElement(serializer, value).jsonObject + return buildJsonObject { + put(SESSION_UPDATE_DISCRIMINATOR, type) + base.forEach { (k, v) -> put(k, v) } + } + } + override fun deserialize(decoder: Decoder): SessionUpdate { val jsonDecoder = decoder as JsonDecoder val jsonObject = jsonDecoder.decodeJsonElement().jsonObject @@ -463,6 +497,18 @@ internal object SessionUpdateSerializer : KSerializer { SessionUpdate.UsageUpdate.serializer(), jsonObject ) + "subagent_update" -> ACPJson.decodeFromJsonElement( + SessionUpdate.SubagentUpdate.serializer(), + jsonObject + ) + "session_message" -> ACPJson.decodeFromJsonElement( + SessionUpdate.SessionMessage.serializer(), + jsonObject + ) + "session_message_chunk" -> ACPJson.decodeFromJsonElement( + SessionUpdate.SessionMessageChunk.serializer(), + jsonObject + ) else -> { // Unknown session update type - capture it for forward compatibility SessionUpdate.UnknownSessionUpdate( diff --git a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/SubagentSessionUpdateSerializers.kt b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/SubagentSessionUpdateSerializers.kt new file mode 100644 index 00000000..c3874fff --- /dev/null +++ b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/SubagentSessionUpdateSerializers.kt @@ -0,0 +1,146 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package com.agentclientprotocol.model + +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.SerializationException +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.builtins.serializer +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject + +/* + * Serializers of the subagent session updates. Field semantics follow the Rust schema's serde attributes: + * `DefaultOnError` fields decode a malformed value as absent, and `cwd` and `additionalDirectories` are + * strict, decoded by the `decodeStrict*` helpers. A required field that is missing or malformed fails the update. + */ + +internal object SubagentUpdateSerializer : JsonObjectSerializer( + "com.agentclientprotocol.model.SessionUpdate.SubagentUpdate", +) { + override fun decode(json: Json, obj: JsonObject): SessionUpdate.SubagentUpdate = SessionUpdate.SubagentUpdate( + sessionId = SessionId(obj.requiredString("sessionId")), + title = obj.decodeMaybeUndefinedString("title") { it }, + description = obj.decodeMaybeUndefinedString("description") { it }, + capabilities = obj.decodeMaybeUndefined(json, "capabilities", SubagentSessionCapabilities.serializer()), + state = obj.decodeMaybeUndefined(json, "state", StateUpdate.serializer()), + cwd = obj.decodeStrictMaybeUndefinedString("cwd"), + additionalDirectories = obj.decodeStrictMaybeUndefinedStringList("additionalDirectories"), + _meta = obj.decodeMaybeUndefinedMeta(), + ) + + override fun encode(json: Json, value: SessionUpdate.SubagentUpdate): JsonObject = buildJsonObject { + put("sessionId", JsonPrimitive(value.sessionId.value)) + putMaybeUndefined(json, "title", value.title, String.serializer()) + putMaybeUndefined(json, "description", value.description, String.serializer()) + putMaybeUndefined(json, "capabilities", value.capabilities, SubagentSessionCapabilities.serializer()) + putMaybeUndefined(json, "state", value.state, StateUpdate.serializer()) + putMaybeUndefined(json, "cwd", value.cwd, String.serializer()) + putMaybeUndefined( + json, + "additionalDirectories", + value.additionalDirectories, + ListSerializer(String.serializer()), + ) + putMaybeUndefined(json, "_meta", value._meta, JsonElement.serializer()) + } +} + +internal object SessionMessageSerializer : JsonObjectSerializer( + "com.agentclientprotocol.model.SessionUpdate.SessionMessage", +) { + override fun decode(json: Json, obj: JsonObject): SessionUpdate.SessionMessage = SessionUpdate.SessionMessage( + messageId = MessageId(obj.requiredString("messageId")), + senderSessionId = obj.decodeMaybeUndefinedString("senderSessionId", ::SessionId), + recipientSessionId = obj.decodeMaybeUndefinedString("recipientSessionId", ::SessionId), + senderMessageId = obj.decodeMaybeUndefinedString("senderMessageId", ::MessageId), + recipientMessageId = obj.decodeMaybeUndefinedString("recipientMessageId", ::MessageId), + content = obj.decodeMaybeUndefinedList(json, "content", ContentBlock.serializer()), + _meta = obj.decodeMaybeUndefinedMeta(), + ) + + override fun encode(json: Json, value: SessionUpdate.SessionMessage): JsonObject = buildJsonObject { + put("messageId", JsonPrimitive(value.messageId.value)) + putMaybeUndefined(json, "senderSessionId", value.senderSessionId, SessionId.serializer()) + putMaybeUndefined(json, "recipientSessionId", value.recipientSessionId, SessionId.serializer()) + putMaybeUndefined(json, "senderMessageId", value.senderMessageId, MessageId.serializer()) + putMaybeUndefined(json, "recipientMessageId", value.recipientMessageId, MessageId.serializer()) + putMaybeUndefined(json, "content", value.content, ListSerializer(ContentBlock.serializer())) + putMaybeUndefined(json, "_meta", value._meta, JsonElement.serializer()) + } +} + +internal object SessionMessageChunkSerializer : JsonObjectSerializer( + "com.agentclientprotocol.model.SessionUpdate.SessionMessageChunk", +) { + override fun decode(json: Json, obj: JsonObject): SessionUpdate.SessionMessageChunk { + val content = obj["content"] as? JsonObject + ?: throw SerializationException("'content' must be a content block object in ${descriptor.serialName}") + return SessionUpdate.SessionMessageChunk( + messageId = MessageId(obj.requiredString("messageId")), + content = json.decodeFromJsonElement(ContentBlock.serializer(), content), + _meta = obj.lenientMeta(), + ) + } + + override fun encode(json: Json, value: SessionUpdate.SessionMessageChunk): JsonObject = buildJsonObject { + put("messageId", JsonPrimitive(value.messageId.value)) + put("content", json.encodeToJsonElement(ContentBlock.serializer(), value.content)) + value._meta?.let { put("_meta", it) } + } +} + +private fun JsonObject.requiredString(key: String): String = + this[key].stringOrNull() ?: throw SerializationException("'$key' must be a string") + +/** + * Decodes a tri-state string field where a value that is not a JSON string decodes as absent. + * + * The check is explicit because `ACPJson` is lenient and would read `false` or `42` as text. + */ +private fun JsonObject.decodeMaybeUndefinedString(key: String, wrap: (String) -> T): MaybeUndefined = + when (val element = this[key]) { + null -> MaybeUndefined.Undefined + is JsonNull -> MaybeUndefined.Null + else -> element.stringOrNull()?.let { MaybeUndefined.Value(wrap(it)) } ?: MaybeUndefined.Undefined + } + +/** + * Decodes a tri-state string field where a value that is not a JSON string fails the update. + */ +private fun JsonObject.decodeStrictMaybeUndefinedString(key: String): MaybeUndefined = + when (val element = this[key]) { + null -> MaybeUndefined.Undefined + is JsonNull -> MaybeUndefined.Null + else -> MaybeUndefined.Value(element.stringOrNull() ?: throw SerializationException("'$key' must be a string")) + } + +/** + * Decodes a tri-state string list field where a non-array value, or any item that is not a JSON string, + * fails the update. + */ +private fun JsonObject.decodeStrictMaybeUndefinedStringList(key: String): MaybeUndefined> = + when (val element = this[key]) { + null -> MaybeUndefined.Undefined + is JsonNull -> MaybeUndefined.Null + is JsonArray -> MaybeUndefined.Value( + element.map { it.stringOrNull() ?: throw SerializationException("'$key' must contain only strings") } + ) + else -> throw SerializationException("'$key' must be an array of strings") + } + +/** + * Decodes a tri-state `_meta` where a value that is not a JSON object decodes as absent. + */ +private fun JsonObject.decodeMaybeUndefinedMeta(): MaybeUndefined = + when (val element = this["_meta"]) { + null -> MaybeUndefined.Undefined + is JsonNull -> MaybeUndefined.Null + is JsonObject -> MaybeUndefined.Value(element) + else -> MaybeUndefined.Undefined + } diff --git a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/SubagentState.kt b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/SubagentState.kt new file mode 100644 index 00000000..89379a0a --- /dev/null +++ b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/SubagentState.kt @@ -0,0 +1,262 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package com.agentclientprotocol.model + +import com.agentclientprotocol.annotations.UnstableApi +import com.agentclientprotocol.rpc.JsonRpcError +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonObjectBuilder +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject + +/** + * The work state of a subagent session, as reported in `subagent_update.state`. + * + * This is an open union discriminated by `state`. Each known state keeps only its own fields, and extra + * fields beside it are dropped. [Unknown] is the real `unknown` state, reported when the agent lost + * observability of the session's work. [Other] holds a state this SDK does not recognize. This differs + * from the v2 `StateUpdate`, whose `Unknown` means unrecognized. + * + * Decoding fails for a value that is not a JSON object and for a missing or non-string `state`, and + * `subagent_update` treats such a state as absent. A known state always decodes as that state: a malformed field + * of it decodes as `null`. + */ +@Serializable(with = StateUpdateSerializer::class) +public sealed class StateUpdate { + /** + * The subagent is doing foreground work. + * + * @property _meta extension metadata; a value that is not a JSON object decodes as `null` + */ + public data class Running( + override val _meta: JsonElement? = null, + ) : StateUpdate(), AcpWithMeta + + /** + * The subagent is not doing foreground work. + * + * @property stopReason why the work stopped; omitted, `null` and non-string values decode as `null`, meaning no + * stop reason is reported + * @property usage token usage of the completed work; omitted, `null` and malformed values decode as `null`; + * unstable: not part of the stable v1 schema + * @property _meta extension metadata; a value that is not a JSON object decodes as `null` + */ + @OptIn(UnstableApi::class) + public data class Idle( + val stopReason: IdleStopReason? = null, + @property:UnstableApi + val usage: Usage? = null, + override val _meta: JsonElement? = null, + ) : StateUpdate(), AcpWithMeta + + /** + * The subagent is waiting on user action before it can continue. + * + * @property _meta extension metadata; a value that is not a JSON object decodes as `null` + */ + public data class RequiresAction( + override val _meta: JsonElement? = null, + ) : StateUpdate(), AcpWithMeta + + /** + * The agent cannot observe the subagent's work, so its state is not known. + * + * @property _meta extension metadata; a value that is not a JSON object decodes as `null` + */ + public data class Unknown( + override val _meta: JsonElement? = null, + ) : StateUpdate(), AcpWithMeta + + /** + * A state this SDK does not recognize. + * + * Clients should preserve it when storing, replaying or forwarding session history. It is encoded back + * as received. Decoding never produces it for a recognized state, so [state] should not be one of + * `running`, `idle`, `requires_action` or `unknown`. + * + * @property state the unrecognized discriminator + * @property fields every other field as received, including `_meta` + */ + public data class Other( + val state: String, + val fields: JsonObject = JsonObject(emptyMap()), + ) : StateUpdate() +} + +/** + * Why a subagent went idle, as reported in [StateUpdate.Idle.stopReason]. + * + * This is an open union discriminated by `stopReason`. It has no wire form of its own: its fields sit + * beside `state`, `usage` and `_meta` in the idle snapshot. The first five values match [StopReason]. A known + * stop reason keeps only its own fields, and extra fields beside it are dropped. + */ +public sealed class IdleStopReason { + /** + * The work finished normally. + */ + public data object EndTurn : IdleStopReason() + + /** + * The work hit the token limit. + */ + public data object MaxTokens : IdleStopReason() + + /** + * The work hit the limit of model requests per turn. + */ + public data object MaxTurnRequests : IdleStopReason() + + /** + * The model refused to continue. + */ + public data object Refusal : IdleStopReason() + + /** + * The work was cancelled. + */ + public data object Cancelled : IdleStopReason() + + /** + * The work failed. + * + * @property error the JSON-RPC error describing the failure, which agents should include; omitted, `null` and + * malformed values decode as `null` + */ + public data class Error( + val error: JsonRpcError? = null, + ) : IdleStopReason() + + /** + * A stop reason this SDK does not recognize. + * + * Clients should preserve it when storing, replaying or forwarding session history. It is encoded back + * as received. Decoding never produces it for a recognized stop reason, so [stopReason] should not be one + * of the known values. + * + * @property stopReason the unrecognized discriminator + * @property fields every other field as received, except `state`, `stopReason`, `usage` and `_meta`, which + * belong to the idle snapshot + */ + public data class Other( + val stopReason: String, + val fields: JsonObject = JsonObject(emptyMap()), + ) : IdleStopReason() +} + +private const val STATE_KEY = "state" +private const val STOP_REASON_KEY = "stopReason" +private const val USAGE_KEY = "usage" +private const val META_KEY = "_meta" +private const val ERROR_KEY = "error" + +/* + * The wire names of the known states and stop reasons, shared by both directions so that they round-trip. + */ +private const val STATE_RUNNING = "running" +private const val STATE_IDLE = "idle" +private const val STATE_REQUIRES_ACTION = "requires_action" +private const val STATE_UNKNOWN = "unknown" +private const val STOP_END_TURN = "end_turn" +private const val STOP_MAX_TOKENS = "max_tokens" +private const val STOP_MAX_TURN_REQUESTS = "max_turn_requests" +private const val STOP_REFUSAL = "refusal" +private const val STOP_CANCELLED = "cancelled" +private const val STOP_ERROR = "error" + +/** + * Fields of an idle snapshot that [IdleStopReason.Other] never holds. + */ +private val IDLE_SNAPSHOT_KEYS = setOf(STATE_KEY, STOP_REASON_KEY, USAGE_KEY, META_KEY) + +@OptIn(UnstableApi::class) +internal object StateUpdateSerializer : JsonObjectSerializer( + "com.agentclientprotocol.model.StateUpdate", +) { + override fun decode(json: Json, obj: JsonObject): StateUpdate { + val state = obj[STATE_KEY].stringOrNull() + ?: throw SerializationException("'$STATE_KEY' discriminator must be a string in StateUpdate") + + return when (state) { + STATE_RUNNING -> StateUpdate.Running(obj.lenientMeta()) + STATE_IDLE -> StateUpdate.Idle( + stopReason = decodeIdleStopReason(json, obj), + usage = obj.decodeOrNull(json, USAGE_KEY, Usage.serializer()), + _meta = obj.lenientMeta(), + ) + + STATE_REQUIRES_ACTION -> StateUpdate.RequiresAction(obj.lenientMeta()) + STATE_UNKNOWN -> StateUpdate.Unknown(obj.lenientMeta()) + else -> StateUpdate.Other(state, JsonObject(obj - STATE_KEY)) + } + } + + override fun encode(json: Json, value: StateUpdate): JsonObject = buildJsonObject { + when (value) { + is StateUpdate.Running -> putState(STATE_RUNNING, value._meta) + is StateUpdate.RequiresAction -> putState(STATE_REQUIRES_ACTION, value._meta) + is StateUpdate.Unknown -> putState(STATE_UNKNOWN, value._meta) + is StateUpdate.Idle -> { + put(STATE_KEY, JsonPrimitive(STATE_IDLE)) + value.stopReason?.let { encodeIdleStopReason(json, it) } + value.usage?.let { put(USAGE_KEY, json.encodeToJsonElement(Usage.serializer(), it)) } + value._meta?.let { put(META_KEY, it) } + } + + is StateUpdate.Other -> { + put(STATE_KEY, JsonPrimitive(value.state)) + value.fields.forEach { (key, element) -> if (key != STATE_KEY) put(key, element) } + } + } + } + + private fun JsonObjectBuilder.putState(state: String, meta: JsonElement?) { + put(STATE_KEY, JsonPrimitive(state)) + meta?.let { put(META_KEY, it) } + } + + /* + * A missing, `null` or non-string `stopReason` means none is reported. Rust gets this by flattening an + * optional field, so any failure to read the tagged union falls back to `None`. + */ + private fun decodeIdleStopReason(json: Json, obj: JsonObject): IdleStopReason? { + val stopReason = obj[STOP_REASON_KEY].stringOrNull() ?: return null + + return when (stopReason) { + STOP_END_TURN -> IdleStopReason.EndTurn + STOP_MAX_TOKENS -> IdleStopReason.MaxTokens + STOP_MAX_TURN_REQUESTS -> IdleStopReason.MaxTurnRequests + STOP_REFUSAL -> IdleStopReason.Refusal + STOP_CANCELLED -> IdleStopReason.Cancelled + STOP_ERROR -> IdleStopReason.Error(obj.decodeOrNull(json, ERROR_KEY, JsonRpcError.serializer())) + else -> IdleStopReason.Other(stopReason, JsonObject(obj - IDLE_SNAPSHOT_KEYS)) + } + } + + private fun JsonObjectBuilder.encodeIdleStopReason(json: Json, stopReason: IdleStopReason) { + val discriminator = when (stopReason) { + IdleStopReason.EndTurn -> STOP_END_TURN + IdleStopReason.MaxTokens -> STOP_MAX_TOKENS + IdleStopReason.MaxTurnRequests -> STOP_MAX_TURN_REQUESTS + IdleStopReason.Refusal -> STOP_REFUSAL + IdleStopReason.Cancelled -> STOP_CANCELLED + is IdleStopReason.Error -> STOP_ERROR + is IdleStopReason.Other -> stopReason.stopReason + } + put(STOP_REASON_KEY, JsonPrimitive(discriminator)) + + when (stopReason) { + is IdleStopReason.Error -> + stopReason.error?.let { put(ERROR_KEY, json.encodeToJsonElement(JsonRpcError.serializer(), it)) } + + is IdleStopReason.Other -> + stopReason.fields.forEach { (key, element) -> if (key !in IDLE_SNAPSHOT_KEYS) put(key, element) } + + else -> {} + } + } +} diff --git a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Subagents.kt b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Subagents.kt new file mode 100644 index 00000000..8d6e3963 --- /dev/null +++ b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Subagents.kt @@ -0,0 +1,115 @@ +@file:OptIn(ExperimentalSerializationApi::class) + +package com.agentclientprotocol.model + +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializable +import kotlinx.serialization.builtins.nullable +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonDecoder +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject + +/** + * Subagent capabilities supported by the client. + * + * By supplying `{}` in `clientCapabilities.subagents` the client opts in to `subagent_update`, + * `session_message` and `session_message_chunk` session updates and to `session` tool call content. Without it the + * agent must not send any of them. An omitted, `null` or malformed value means unsupported. + * + * @property _meta extension metadata; a value that is not a JSON object decodes as `null` + */ +@Serializable(with = SubagentCapabilitiesSerializer::class) +public data class SubagentCapabilities( + override val _meta: JsonElement? = null, +) : AcpWithMeta + +/** + * Controls the client may use on a subagent session, as announced by the agent. + * + * Every field decodes leniently: a malformed value decodes as `null` and the rest of the object + * still decodes. + * + * @property cancel present when the client may send `session/cancel` for the subagent session; + * omitted, `null` and malformed values all mean it may not + * @property _meta extension metadata; a value that is not a JSON object decodes as `null` + */ +@Serializable(with = SubagentSessionCapabilitiesSerializer::class) +public data class SubagentSessionCapabilities( + val cancel: SessionCancelCapabilities? = null, + override val _meta: JsonElement? = null, +) : AcpWithMeta + +/** + * Marker for the `cancel` control: its presence means the client may send `session/cancel` for the + * subagent session. + * + * @property _meta extension metadata; a value that is not a JSON object decodes as `null` + */ +@Serializable(with = SessionCancelCapabilitiesSerializer::class) +public data class SessionCancelCapabilities( + override val _meta: JsonElement? = null, +) : AcpWithMeta + +internal object SubagentCapabilitiesSerializer : JsonObjectSerializer( + "com.agentclientprotocol.model.SubagentCapabilities", +) { + override fun decode(json: Json, obj: JsonObject): SubagentCapabilities = + SubagentCapabilities(_meta = obj.lenientMeta()) + + override fun encode(json: Json, value: SubagentCapabilities): JsonObject = buildJsonObject { + value._meta?.let { put("_meta", it) } + } +} + +internal object SessionCancelCapabilitiesSerializer : JsonObjectSerializer( + "com.agentclientprotocol.model.SessionCancelCapabilities", +) { + override fun decode(json: Json, obj: JsonObject): SessionCancelCapabilities = + SessionCancelCapabilities(_meta = obj.lenientMeta()) + + override fun encode(json: Json, value: SessionCancelCapabilities): JsonObject = buildJsonObject { + value._meta?.let { put("_meta", it) } + } +} + +internal object SubagentSessionCapabilitiesSerializer : JsonObjectSerializer( + "com.agentclientprotocol.model.SubagentSessionCapabilities", +) { + override fun decode(json: Json, obj: JsonObject): SubagentSessionCapabilities = SubagentSessionCapabilities( + cancel = obj.decodeOrNull(json, "cancel", SessionCancelCapabilities.serializer()), + _meta = obj.lenientMeta(), + ) + + override fun encode(json: Json, value: SubagentSessionCapabilities): JsonObject = buildJsonObject { + value.cancel?.let { put("cancel", json.encodeToJsonElement(SessionCancelCapabilities.serializer(), it)) } + value._meta?.let { put("_meta", it) } + } +} + +/** + * Serializer for `ClientCapabilities.subagents`: a malformed value decodes as `null` instead of failing the + * enclosing capabilities, since a client that advertises something unreadable has not opted in. + */ +internal object LenientSubagentCapabilitiesSerializer : KSerializer { + private val delegate: KSerializer = SubagentCapabilities.serializer() + + override val descriptor: SerialDescriptor = delegate.nullable.descriptor + + override fun serialize(encoder: Encoder, value: SubagentCapabilities?) { + if (value == null) encoder.encodeNull() else encoder.encodeSerializableValue(delegate, value) + } + + override fun deserialize(decoder: Decoder): SubagentCapabilities? { + val jsonDecoder = decoder as JsonDecoder + val element = jsonDecoder.decodeJsonElement() + if (element is JsonNull) return null + return jsonDecoder.json.decodeLenientlyOrNull(delegate, element) + } +} diff --git a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/ToolCall.kt b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/ToolCall.kt index 5b2a9c46..2452eadd 100644 --- a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/ToolCall.kt +++ b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/ToolCall.kt @@ -2,6 +2,7 @@ package com.agentclientprotocol.model +import com.agentclientprotocol.annotations.UnstableApi import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonElement @@ -98,4 +99,22 @@ public sealed class ToolCallContent { val terminalId: String, override val _meta: JsonElement? = null ) : ToolCallContent(), AcpWithMeta + + /** + * A display-only reference to a session that this tool call operates on, such as a child session it + * spawned or waits on. + * + * In v1 the agent may send it only when the client advertised the `subagents` client capability. The + * referenced session must already be known to the client, through session setup or an announcement. + * The reference grants no controls and says nothing about the referenced session's work. + * + * @property _meta item metadata; omitted, `null` and values that are not a JSON object all decode as `null` + */ + @Serializable + @SerialName("session") + public data class Session( + val sessionId: SessionId, + @Serializable(with = LenientMetaSerializer::class) + override val _meta: JsonElement? = null + ) : ToolCallContent(), AcpWithMeta } \ No newline at end of file diff --git a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Types.kt b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Types.kt index 5338606b..c04ee95b 100644 --- a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Types.kt +++ b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/Types.kt @@ -133,17 +133,12 @@ public value class SessionConfigGroupId(public val value: String) { } /** - * **UNSTABLE** - * - * This capability is not part of the spec yet, and may be removed or changed at any point. - * * A unique message identifier for [PromptRequest], session update message chunks, and [PromptResponse]. * * If provided by the client, the Agent SHOULD echo this value as `userMessageId` in the * [PromptResponse] to confirm it was recorded. * Both clients and agents MUST use UUID format for message IDs. */ -@UnstableApi @JvmInline @Serializable public value class MessageId(public val value: String) { diff --git a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/v2/conversion/CapabilitiesConversions.kt b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/v2/conversion/CapabilitiesConversions.kt index 286a2c4c..4777de01 100644 --- a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/v2/conversion/CapabilitiesConversions.kt +++ b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/v2/conversion/CapabilitiesConversions.kt @@ -320,8 +320,8 @@ public fun V1AuthCapabilities.toV2(): AuthCapabilities = AuthCapabilities( * Converts these v2 client capabilities to their v1 equivalent. * * The v1-only fields are filled with their "unsupported" values: `fs` is left unset, - * `terminal` is `false` and `plan` is left unset. v2 makes `plan_update` baseline, so a v1 - * agent reading this will fall back to the older `plan` session update type. + * `terminal` is `false`, and `plan` and `subagents` are left unset. v2 makes `plan_update` + * baseline, so a v1 agent reading this will fall back to the older `plan` session update type. * * @throws ProtocolConversionException if a nested capability has no v1 representation */ @@ -340,15 +340,16 @@ public fun ClientCapabilities.toV1(): V1ClientCapabilities = V1ClientCapabilitie /** * Converts these v1 client capabilities to their v2 equivalent. * - * @throws ProtocolConversionException if `fs`, `terminal` or `plan` advertise support — - * the `fs` and `terminal` method families were removed in v2, and `plan_update` became - * baseline, so none of the three has anywhere to go + * @throws ProtocolConversionException if `fs`, `terminal`, `plan` or `subagents` advertise + * support — the `fs` and `terminal` method families were removed in v2, `plan_update` became + * baseline, and v2 does not model subagents yet, so none of the four has anywhere to go */ @UnstableApi public fun V1ClientCapabilities.toV2(): ClientCapabilities { if (fs != null && fs != FileSystemCapability()) throw unrepresentableV1Field("ClientCapabilities", "fs") if (terminal) throw unrepresentableV1Field("ClientCapabilities", "terminal") if (planCapabilities != null) throw unrepresentableV1Field("ClientCapabilities", "plan") + if (subagents != null) throw unrepresentableV1Field("ClientCapabilities", "subagents") return ClientCapabilities( auth = auth?.toV2(), elicitation = elicitation, diff --git a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/v2/conversion/SessionUpdateConversions.kt b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/v2/conversion/SessionUpdateConversions.kt index 2d65f579..09fb9b61 100644 --- a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/v2/conversion/SessionUpdateConversions.kt +++ b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/v2/conversion/SessionUpdateConversions.kt @@ -316,6 +316,7 @@ public fun SessionUpdate.toV1(): List = when (this) { * An unrecognized v1 update crosses unchanged: both versions preserve one as raw JSON. * * @throws ProtocolConversionException if this is a `current_mode_update`, which v2 removed, + * a `subagent_update`, `session_message` or `session_message_chunk`, which v2 does not model yet, * or a message chunk with no `messageId`, which v2 requires */ @UnstableApi @@ -345,6 +346,15 @@ public fun V1SessionUpdate.toV2(): SessionUpdate = when (this) { is V1SessionUpdate.CurrentModeUpdate -> throw removedV1EnumVariant("SessionUpdate", "current_mode_update") + is V1SessionUpdate.SubagentUpdate -> + throw removedV1EnumVariant("SessionUpdate", "subagent_update") + + is V1SessionUpdate.SessionMessage -> + throw removedV1EnumVariant("SessionUpdate", "session_message") + + is V1SessionUpdate.SessionMessageChunk -> + throw removedV1EnumVariant("SessionUpdate", "session_message_chunk") + // Both versions keep unrecognized updates as raw JSON, so this crosses losslessly. is V1SessionUpdate.UnknownSessionUpdate -> SessionUpdate.Unknown(sessionUpdate = sessionUpdateType, rawJson = rawJson) diff --git a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/v2/conversion/ToolCallConversions.kt b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/v2/conversion/ToolCallConversions.kt index a0362369..5b046ed7 100644 --- a/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/v2/conversion/ToolCallConversions.kt +++ b/acp-model/src/commonMain/kotlin/com/agentclientprotocol/model/v2/conversion/ToolCallConversions.kt @@ -117,7 +117,7 @@ private fun ToolCallContent.toV1OrNull(): V1ToolCallContent? = when (this) { private fun V1ToolCallContent.toV2OrNull(): ToolCallContent? = when (this) { is V1ToolCallContent.Content -> ToolCallContent.Content(content = content.toV2()) - is V1ToolCallContent.Diff, is V1ToolCallContent.Terminal -> null + is V1ToolCallContent.Diff, is V1ToolCallContent.Terminal, is V1ToolCallContent.Session -> null } /** diff --git a/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/SubagentCapabilitiesSerializationTest.kt b/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/SubagentCapabilitiesSerializationTest.kt new file mode 100644 index 00000000..c9984090 --- /dev/null +++ b/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/SubagentCapabilitiesSerializationTest.kt @@ -0,0 +1,121 @@ +package com.agentclientprotocol.model + +import com.agentclientprotocol.rpc.ACPJson +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNull + +class SubagentCapabilitiesSerializationTest { + private fun encodedJson(value: ClientCapabilities) = + ACPJson.encodeToJsonElement(ClientCapabilities.serializer(), value) as JsonObject + + private fun decodeClient(payload: String) = ACPJson.decodeFromString(ClientCapabilities.serializer(), payload) + + private fun decodeSession(payload: String) = + ACPJson.decodeFromString(SubagentSessionCapabilities.serializer(), payload) + + private val meta = buildJsonObject { put("k", "v") } + + @Test + fun `client capabilities decode and encode the empty subagents marker`() { + val capabilities = decodeClient("""{"subagents": {}}""") + + assertEquals(SubagentCapabilities(), capabilities.subagents) + assertEquals(JsonObject(emptyMap()), encodedJson(capabilities)["subagents"]) + } + + @Test + fun `client capabilities keep subagents meta and round trip`() { + val original = ClientCapabilities(subagents = SubagentCapabilities(_meta = meta)) + + val encoded = encodedJson(original) + + assertEquals(buildJsonObject { put("_meta", meta) }, encoded["subagents"]) + assertEquals(original, ACPJson.decodeFromJsonElement(ClientCapabilities.serializer(), encoded)) + } + + @Test + fun `client capabilities subagents is absent null and omitted on encode`() { + assertNull(decodeClient("{}").subagents) + assertNull(decodeClient("""{"subagents": null}""").subagents) + assertEquals(false, encodedJson(ClientCapabilities()).containsKey("subagents")) + } + + @Test + fun `malformed subagents decodes as absent without failing the enclosing capabilities`() { + for (malformed in listOf("true", "false", "\"yes\"", "42", "[]")) { + val capabilities = decodeClient("""{"terminal": true, "subagents": $malformed}""") + + assertNull(capabilities.subagents, malformed) + assertEquals(true, capabilities.terminal, malformed) + } + } + + @Test + fun `subagent session capabilities round trip cancel with meta`() { + val payload = """{"cancel": {"_meta": {"k": "v"}}, "_meta": {"k": "v"}}""" + + val decoded = decodeSession(payload) + + assertEquals(SubagentSessionCapabilities(SessionCancelCapabilities(meta), meta), decoded) + assertEquals( + ACPJson.parseToJsonElement(payload), + ACPJson.encodeToJsonElement(SubagentSessionCapabilities.serializer(), decoded), + ) + } + + @Test + fun `subagent session capabilities round trip and omit absent fields`() { + val granted = SubagentSessionCapabilities(cancel = SessionCancelCapabilities()) + + val grantedJson = ACPJson.encodeToJsonElement(SubagentSessionCapabilities.serializer(), granted) + val emptyJson = ACPJson.encodeToJsonElement(SubagentSessionCapabilities.serializer(), SubagentSessionCapabilities()) + + assertEquals(buildJsonObject { put("cancel", JsonObject(emptyMap())) }, grantedJson) + assertEquals(JsonObject(emptyMap()), emptyJson) + assertEquals(granted, ACPJson.decodeFromJsonElement(SubagentSessionCapabilities.serializer(), grantedJson)) + } + + @Test + fun `subagent session capabilities treat omitted and null cancel the same`() { + assertNull(decodeSession("{}").cancel) + assertNull(decodeSession("""{"cancel": null}""").cancel) + } + + @Test + fun `malformed cancel decodes as null and keeps the other fields`() { + for (malformed in listOf("true", "false", "\"yes\"", "1", "[]")) { + val decoded = decodeSession("""{"cancel": $malformed, "_meta": {"k": "v"}}""") + + assertNull(decoded.cancel, malformed) + assertEquals(meta, decoded._meta, malformed) + } + } + + @Test + fun `malformed capability meta decodes as null`() { + assertEquals(SubagentCapabilities(_meta = null), decodeClient("""{"subagents": {"_meta": false}}""").subagents) + assertEquals( + SubagentSessionCapabilities(SessionCancelCapabilities(), null), + decodeSession("""{"cancel": {"_meta": 1}, "_meta": "x"}"""), + ) + } + + @Test + fun `capabilities that are not objects fail to decode`() { + assertFailsWith { decodeSession("true") } + assertFailsWith { decodeSession("[]") } + assertFailsWith { + ACPJson.decodeFromString(SessionCancelCapabilities.serializer(), "\"x\"") + } + assertFailsWith { + ACPJson.decodeFromString(SubagentCapabilities.serializer(), "null") + } + } +} diff --git a/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/SubagentSessionUpdatesSerializationTest.kt b/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/SubagentSessionUpdatesSerializationTest.kt new file mode 100644 index 00000000..21c3f09d --- /dev/null +++ b/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/SubagentSessionUpdatesSerializationTest.kt @@ -0,0 +1,453 @@ +@file:OptIn(UnstableApi::class) + +package com.agentclientprotocol.model + +import com.agentclientprotocol.annotations.UnstableApi +import com.agentclientprotocol.rpc.ACPJson +import com.agentclientprotocol.rpc.JsonRpcError +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.put +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertIs + +class SubagentSessionUpdatesSerializationTest { + private fun decode(payload: String): SessionUpdate = ACPJson.decodeFromString(SessionUpdate.serializer(), payload) + + private fun encode(value: SessionUpdate): JsonElement = ACPJson.encodeToJsonElement(SessionUpdate.serializer(), value) + + private fun json(payload: String): JsonElement = ACPJson.parseToJsonElement(payload) + + private fun assertRoundTrips(payload: String, expected: SessionUpdate) { + val decoded = decode(payload) + + assertEquals(expected, decoded) + assertEquals(json(payload), encode(decoded)) + } + + private fun subagent(fields: String = ""): String = + """{"sessionUpdate":"subagent_update","sessionId":"child"${if (fields.isEmpty()) "" else ",$fields"}}""" + + private fun message(fields: String = ""): String = + """{"sessionUpdate":"session_message","messageId":"m1"${if (fields.isEmpty()) "" else ",$fields"}}""" + + private fun chunk(fields: String = ""): String = + """{"sessionUpdate":"session_message_chunk","messageId":"m1"${if (fields.isEmpty()) "" else ",$fields"}}""" + + private val meta = buildJsonObject { put("k", "v") } + private val text = ContentBlock.Text("hi") + private val textJson = """{"type":"text","text":"hi"}""" + private val child = SessionId("child") + + // SubagentUpdate + + @Test + fun `subagent update with only a session id leaves every patch field undefined`() { + assertRoundTrips(subagent(), SessionUpdate.SubagentUpdate(child)) + } + + @Test + fun `every subagent update patch field distinguishes absent null and value`() { + assertRoundTrips( + subagent( + """"title":null,"description":null,"capabilities":null,"state":null,"cwd":null,""" + + """"additionalDirectories":null,"_meta":null""" + ), + SessionUpdate.SubagentUpdate( + sessionId = child, + title = MaybeUndefined.Null, + description = MaybeUndefined.Null, + capabilities = MaybeUndefined.Null, + state = MaybeUndefined.Null, + cwd = MaybeUndefined.Null, + additionalDirectories = MaybeUndefined.Null, + _meta = MaybeUndefined.Null, + ), + ) + assertRoundTrips( + subagent( + """"title":"T","description":"D","capabilities":{"cancel":{}},"state":{"state":"running"},""" + + """"cwd":"/work","additionalDirectories":["/a","/b"],"_meta":{"k":"v"}""" + ), + SessionUpdate.SubagentUpdate( + sessionId = child, + title = MaybeUndefined.Value("T"), + description = MaybeUndefined.Value("D"), + capabilities = MaybeUndefined.Value(SubagentSessionCapabilities(cancel = SessionCancelCapabilities())), + state = MaybeUndefined.Value(StateUpdate.Running()), + cwd = MaybeUndefined.Value("/work"), + additionalDirectories = MaybeUndefined.Value(listOf("/a", "/b")), + _meta = MaybeUndefined.Value(meta), + ), + ) + } + + @Test + fun `empty additional directories list differs from null`() { + assertRoundTrips( + subagent(""""additionalDirectories":[]"""), + SessionUpdate.SubagentUpdate(child, additionalDirectories = MaybeUndefined.Value(emptyList())), + ) + } + + @Test + fun `empty capabilities and capabilities with a null cancel decode as empty capabilities`() { + for (field in listOf(""""capabilities":{}""", """"capabilities":{"cancel":null}""")) { + val decoded = decode(subagent(field)) + + assertEquals( + SessionUpdate.SubagentUpdate(child, capabilities = MaybeUndefined.Value(SubagentSessionCapabilities())), + decoded, + field, + ) + assertEquals(json(subagent(""""capabilities":{}""")), encode(decoded), field) + } + } + + @Test + fun `malformed lenient subagent update fields decode as absent`() { + val payloads = listOf( + """"title":false""", + """"title":42""", + """"description":false""", + """"description":{"a":1}""", + """"capabilities":false""", + """"capabilities":"x"""", + """"state":"running"""", + """"state":{}""", + """"state":{"state":4}""", + """"state":42""", + """"state":[]""", + """"_meta":false""", + """"_meta":[1]""", + ) + + for (field in payloads) { + val decoded = decode(subagent(field)) + + assertEquals(SessionUpdate.SubagentUpdate(child), decoded, field) + assertEquals(json(subagent()), encode(decoded), field) + } + } + + @Test + fun `malformed lenient fields do not disturb valid siblings`() { + assertEquals( + SessionUpdate.SubagentUpdate(child, description = MaybeUndefined.Value("D")), + decode(subagent(""""title":false,"description":"D"""")), + ) + } + + @Test + fun `malformed cwd and additional directories fail the subagent update`() { + val payloads = listOf( + """"cwd":false""", + """"cwd":42""", + """"cwd":{}""", + """"cwd":["/a"]""", + """"additionalDirectories":"/tmp/wt"""", + """"additionalDirectories":false""", + """"additionalDirectories":["/tmp/wt",false]""", + """"additionalDirectories":[42]""", + """"additionalDirectories":[null]""", + ) + + for (field in payloads) { + assertFailsWith(field) { decode(subagent(field)) } + } + } + + @Test + fun `subagent update without a valid session id fails`() { + assertFailsWith { decode("""{"sessionUpdate":"subagent_update"}""") } + assertFailsWith { decode("""{"sessionUpdate":"subagent_update","sessionId":null}""") } + assertFailsWith { decode("""{"sessionUpdate":"subagent_update","sessionId":42}""") } + } + + @Test + fun `unrecognized and non trivial states decode inside a subagent update`() { + val pausedJson = """{"state":"paused","retryAt":42,"_meta":{"k":"v"}}""" + val otherStopReasonJson = """{"state":"idle","stopReason":"_paused","resumeAfter":30,"_meta":{"k":"v"}}""" + val errorJson = """{"state":"idle","stopReason":"error","error":{"code":-32000,"message":"boom"}}""" + + /* + * Each case is the nested state, the decoded value and its re-encoded form, which drops a malformed `_meta`. + */ + val cases = listOf( + Triple( + pausedJson, + StateUpdate.Other( + "paused", + buildJsonObject { + put("retryAt", 42) + put("_meta", meta) + }, + ), + pausedJson, + ), + Triple( + otherStopReasonJson, + StateUpdate.Idle( + stopReason = IdleStopReason.Other("_paused", buildJsonObject { put("resumeAfter", 30) }), + _meta = meta, + ), + otherStopReasonJson, + ), + Triple( + errorJson, + StateUpdate.Idle(stopReason = IdleStopReason.Error(JsonRpcError(code = -32000, message = "boom"))), + errorJson, + ), + Triple("""{"state":"unknown","_meta":false}""", StateUpdate.Unknown(), """{"state":"unknown"}"""), + ) + + for ((state, expected, encoded) in cases) { + val decoded = decode(subagent(""""state":$state""")) + + assertEquals(SessionUpdate.SubagentUpdate(child, state = MaybeUndefined.Value(expected)), decoded, state) + assertEquals(json(subagent(""""state":$encoded""")), encode(decoded), state) + } + } + + // SessionMessage + + @Test + fun `session message with only a message id leaves every patch field undefined`() { + assertRoundTrips(message(), SessionUpdate.SessionMessage(MessageId("m1"))) + } + + @Test + fun `every session message patch field distinguishes null and value`() { + assertRoundTrips( + message( + """"senderSessionId":null,"recipientSessionId":null,"senderMessageId":null,""" + + """"recipientMessageId":null,"content":null,"_meta":null""" + ), + SessionUpdate.SessionMessage( + messageId = MessageId("m1"), + senderSessionId = MaybeUndefined.Null, + recipientSessionId = MaybeUndefined.Null, + senderMessageId = MaybeUndefined.Null, + recipientMessageId = MaybeUndefined.Null, + content = MaybeUndefined.Null, + _meta = MaybeUndefined.Null, + ), + ) + assertRoundTrips( + message( + """"senderSessionId":"a","recipientSessionId":"b","senderMessageId":"sm","""" + + """recipientMessageId":"rm","content":[$textJson],"_meta":{"k":"v"}""" + ), + SessionUpdate.SessionMessage( + messageId = MessageId("m1"), + senderSessionId = MaybeUndefined.Value(SessionId("a")), + recipientSessionId = MaybeUndefined.Value(SessionId("b")), + senderMessageId = MaybeUndefined.Value(MessageId("sm")), + recipientMessageId = MaybeUndefined.Value(MessageId("rm")), + content = MaybeUndefined.Value(listOf(text)), + _meta = MaybeUndefined.Value(meta), + ), + ) + } + + @Test + fun `session message empty content list differs from null`() { + assertRoundTrips( + message(""""content":[]"""), + SessionUpdate.SessionMessage(MessageId("m1"), content = MaybeUndefined.Value(emptyList())), + ) + } + + @Test + fun `session message skips unparseable content blocks`() { + val cases = listOf( + Triple("""[{"type":"bogus"},$textJson,{"type":"text"},42]""", listOf(text), "[$textJson]"), + Triple("""[{"type":"bogus"},42]""", emptyList(), "[]"), + ) + + for ((content, expected, encoded) in cases) { + val decoded = decode(message(""""content":$content""")) + + assertEquals( + SessionUpdate.SessionMessage(MessageId("m1"), content = MaybeUndefined.Value(expected)), + decoded, + content, + ) + assertEquals(json(message(""""content":$encoded""")), encode(decoded), content) + } + } + + @Test + fun `malformed session message patch fields decode as absent`() { + val payloads = listOf( + """"senderSessionId":42""", + """"senderSessionId":false""", + """"recipientSessionId":{}""", + """"senderMessageId":42""", + """"recipientMessageId":["x"]""", + """"content":false""", + """"content":{}""", + """"_meta":false""", + """"_meta":"x"""", + ) + + for (field in payloads) { + val decoded = decode(message(field)) + + assertEquals(SessionUpdate.SessionMessage(MessageId("m1")), decoded, field) + assertEquals(json(message()), encode(decoded), field) + } + } + + @Test + fun `session message without a valid message id fails`() { + for (id in listOf("", ""","messageId":null""", ""","messageId":42""")) { + assertFailsWith(id) { + decode("""{"sessionUpdate":"session_message"$id}""") + } + } + } + + // SessionMessageChunk + + @Test + fun `session message chunk round trips`() { + assertRoundTrips( + chunk(""""content":$textJson"""), + SessionUpdate.SessionMessageChunk(MessageId("m1"), text), + ) + assertRoundTrips( + chunk(""""content":$textJson,"_meta":{"k":"v"}"""), + SessionUpdate.SessionMessageChunk(MessageId("m1"), text, meta), + ) + } + + @Test + fun `session message chunk null and malformed meta decode as null`() { + for (field in listOf(""""_meta":null""", """"_meta":false""", """"_meta":"x"""", """"_meta":[1]""")) { + val decoded = decode(chunk(""""content":$textJson,$field""")) + + assertEquals(SessionUpdate.SessionMessageChunk(MessageId("m1"), text), decoded, field) + assertEquals(json(chunk(""""content":$textJson""")), encode(decoded), field) + } + } + + @Test + fun `session message chunk ignores participant fields`() { + val decoded = decode(chunk(""""content":$textJson,"senderSessionId":"a","recipientMessageId":"r"""")) + + assertEquals(json(chunk(""""content":$textJson""")), encode(decoded)) + } + + @Test + fun `session message chunk without valid required fields fails`() { + val payloads = listOf( + """{"sessionUpdate":"session_message_chunk","content":$textJson}""", + """{"sessionUpdate":"session_message_chunk","messageId":null,"content":$textJson}""", + """{"sessionUpdate":"session_message_chunk","messageId":42,"content":$textJson}""", + """{"sessionUpdate":"session_message_chunk","messageId":"m1"}""", + """{"sessionUpdate":"session_message_chunk","messageId":"m1","content":null}""", + """{"sessionUpdate":"session_message_chunk","messageId":"m1","content":42}""", + """{"sessionUpdate":"session_message_chunk","messageId":"m1","content":{"type":"bogus"}}""", + ) + + for (payload in payloads) { + assertFailsWith(payload) { decode(payload) } + } + } + + // ToolCallContent.Session + + private val toolCallContentCases = listOf( + """{"type":"session","sessionId":"child"}""" to ToolCallContent.Session(child), + """{"type":"session","sessionId":"child","_meta":{"k":"v"}}""" to ToolCallContent.Session(child, meta), + ) + + @Test + fun `session tool call content round trips on its own`() { + for ((payload, expected) in toolCallContentCases) { + val decoded = ACPJson.decodeFromString(ToolCallContent.serializer(), payload) + + assertEquals(expected, decoded) + assertEquals(json(payload), ACPJson.encodeToJsonElement(ToolCallContent.serializer(), decoded)) + } + } + + @Test + fun `session tool call content round trips inside tool call and tool call update`() { + for ((contentJson, expected) in toolCallContentCases) { + val toolCall = decode("""{"sessionUpdate":"tool_call","toolCallId":"t1","title":"x","content":[$contentJson]}""") + assertEquals(listOf(expected), assertIs(toolCall).content) + assertEquals(json("[$contentJson]"), encode(toolCall).jsonObject["content"]) + + val toolCallUpdate = decode("""{"sessionUpdate":"tool_call_update","toolCallId":"t1","content":[$contentJson]}""") + assertEquals( + listOf(expected), + assertIs(toolCallUpdate).content, + ) + assertEquals(json("[$contentJson]"), encode(toolCallUpdate).jsonObject["content"]) + } + } + + @Test + fun `session tool call content with malformed meta decodes without meta`() { + for (metaJson in listOf("false", "\"x\"", "[1]", "null")) { + val payload = """{"sessionUpdate":"tool_call_update","toolCallId":"t1","content":""" + + """[{"type":"session","sessionId":"child","_meta":$metaJson}]}""" + + val decoded = assertIs(decode(payload)) + + assertEquals(listOf(ToolCallContent.Session(child)), decoded.content, metaJson) + assertEquals( + json("""[{"type":"session","sessionId":"child"}]"""), + encode(decoded).jsonObject["content"], + metaJson, + ) + } + } + + @Test + fun `session tool call content without a string session id fails`() { + for (id in listOf("", ""","sessionId":null""", ""","sessionId":{}""")) { + assertFailsWith(id) { + ACPJson.decodeFromString(ToolCallContent.serializer(), """{"type":"session"$id}""") + } + } + } + + // Full notifications + + @Test + fun `the three discriminators decode inside a full session notification`() { + val cases = listOf( + subagent(""""title":"T"""") to SessionUpdate.SubagentUpdate(child, title = MaybeUndefined.Value("T")), + message(""""content":[$textJson]""") to + SessionUpdate.SessionMessage(MessageId("m1"), content = MaybeUndefined.Value(listOf(text))), + chunk(""""content":$textJson""") to SessionUpdate.SessionMessageChunk(MessageId("m1"), text), + ) + + for ((update, expected) in cases) { + val payload = """{"sessionId":"root","update":$update}""" + + val notification = ACPJson.decodeFromString(SessionNotification.serializer(), payload) + + assertEquals(SessionNotification(SessionId("root"), expected), notification) + assertEquals(json(payload), ACPJson.encodeToJsonElement(SessionNotification.serializer(), notification)) + } + } + + @Test + fun `an invalid known subagent update fails the notification instead of becoming unknown`() { + assertFailsWith { + ACPJson.decodeFromString( + SessionNotification.serializer(), + """{"sessionId":"root","update":${subagent(""""cwd":false""")}}""", + ) + } + } + +} diff --git a/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/SubagentStateSerializationTest.kt b/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/SubagentStateSerializationTest.kt new file mode 100644 index 00000000..144cbf94 --- /dev/null +++ b/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/SubagentStateSerializationTest.kt @@ -0,0 +1,233 @@ +package com.agentclientprotocol.model + +import com.agentclientprotocol.rpc.ACPJson +import com.agentclientprotocol.rpc.JsonRpcError +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertIs +import kotlin.test.assertNull + +class SubagentStateSerializationTest { + private fun decode(payload: String): StateUpdate = ACPJson.decodeFromString(StateUpdate.serializer(), payload) + + private fun encode(value: StateUpdate): JsonElement = ACPJson.encodeToJsonElement(StateUpdate.serializer(), value) + + private fun json(payload: String): JsonElement = ACPJson.parseToJsonElement(payload) + + private fun assertRoundTrips(payload: String, expected: StateUpdate) { + val decoded = decode(payload) + + assertEquals(expected, decoded) + assertEquals(json(payload), encode(decoded)) + } + + private val meta = buildJsonObject { put("k", "v") } + + @Test + fun `known states round trip`() { + assertRoundTrips("""{"state":"running"}""", StateUpdate.Running()) + assertRoundTrips("""{"state":"running","_meta":{"k":"v"}}""", StateUpdate.Running(meta)) + assertRoundTrips("""{"state":"requires_action"}""", StateUpdate.RequiresAction()) + assertRoundTrips("""{"state":"requires_action","_meta":{"k":"v"}}""", StateUpdate.RequiresAction(meta)) + assertRoundTrips("""{"state":"unknown"}""", StateUpdate.Unknown()) + assertRoundTrips("""{"state":"unknown","_meta":{"k":"v"}}""", StateUpdate.Unknown(meta)) + assertRoundTrips("""{"state":"idle"}""", StateUpdate.Idle()) + } + + @Test + fun `every known stop reason round trips on an idle snapshot`() { + val cases = mapOf( + "end_turn" to IdleStopReason.EndTurn, + "max_tokens" to IdleStopReason.MaxTokens, + "max_turn_requests" to IdleStopReason.MaxTurnRequests, + "refusal" to IdleStopReason.Refusal, + "cancelled" to IdleStopReason.Cancelled, + ) + + for ((wire, expected) in cases) { + assertRoundTrips("""{"state":"idle","stopReason":"$wire"}""", StateUpdate.Idle(stopReason = expected)) + } + } + + @Test + fun `unrecognized state round trips unchanged and keeps meta`() { + val payload = """{"state":"paused","retryAt":42,"_meta":{"k":"v"},"nested":{"a":[1,2]}}""" + + val decoded = decode(payload) + + val other = assertIs(decoded) + assertEquals("paused", other.state) + assertEquals(setOf("retryAt", "_meta", "nested"), other.fields.keys) + assertEquals(json(payload), encode(decoded)) + } + + @Test + fun `unrecognized state with a malformed meta is preserved as received`() { + assertRoundTrips( + """{"state":"paused","_meta":false}""", + StateUpdate.Other("paused", buildJsonObject { put("_meta", JsonPrimitive(false)) }), + ) + } + + @Test + fun `extra fields beside a known state are dropped`() { + assertEquals(StateUpdate.Running(), decode("""{"state":"running","foo":1}""")) + assertEquals(json("""{"state":"running"}"""), encode(decode("""{"state":"running","foo":1}"""))) + assertEquals(StateUpdate.Unknown(), decode("""{"state":"unknown","foo":{"a":1}}""")) + } + + @Test + fun `malformed state meta decodes as null`() { + for (state in listOf("running", "requires_action", "unknown", "idle")) { + for (malformed in listOf("false", "1", "\"x\"", "[]", "null")) { + val decoded = decode("""{"state":"$state","_meta":$malformed}""") + + assertNull((decoded as AcpWithMeta)._meta, "$state $malformed") + } + } + } + + @Test + fun `a non object value or a missing or non string state is a decode failure not an unrecognized state`() { + val payloads = listOf( + "\"running\"", + "42", + "true", + "[]", + "null", + "{}", + """{"state":4}""", + """{"state":null}""", + """{"state":["running"]}""", + ) + + for (malformed in payloads) { + assertFailsWith(malformed) { decode(malformed) } + } + } + + @Test + fun `idle with error stop reason round trips`() { + val payload = """{"state":"idle","stopReason":"error","error":{"code":-32603,"message":"boom","data":{"a":1}}}""" + val expected = StateUpdate.Idle( + stopReason = IdleStopReason.Error( + JsonRpcError(code = -32603, message = "boom", data = buildJsonObject { put("a", 1) }), + ), + ) + + assertRoundTrips(payload, expected) + } + + @Test + fun `omitted null and malformed error decode as no error and encode without it`() { + for (error in listOf("", ""","error":null""", ""","error":"failed"""", ""","error":{"code":"x"}""", ""","error":{}""")) { + val decoded = decode("""{"state":"idle","stopReason":"error"$error}""") + + assertEquals(StateUpdate.Idle(stopReason = IdleStopReason.Error()), decoded, error) + assertEquals(json("""{"state":"idle","stopReason":"error"}"""), encode(decoded), error) + } + } + + @Test + fun `error beside a non error stop reason is dropped`() { + val decoded = decode("""{"state":"idle","stopReason":"end_turn","error":{"code":1,"message":"m"}}""") + + assertEquals(StateUpdate.Idle(stopReason = IdleStopReason.EndTurn), decoded) + assertEquals(json("""{"state":"idle","stopReason":"end_turn"}"""), encode(decoded)) + } + + @Test + fun `idle with usage round trips`() { + val payload = """{"state":"idle","stopReason":"end_turn","usage":{"inputTokens":1,"outputTokens":2,"totalTokens":3}}""" + + assertRoundTrips( + payload, + StateUpdate.Idle(IdleStopReason.EndTurn, Usage(inputTokens = 1, outputTokens = 2, totalTokens = 3)), + ) + } + + @Test + fun `omitted null and malformed usage decode as null without failing the snapshot`() { + val malformedUsages = listOf( + "null", + "false", + "\"many\"", + "[]", + """{"inputTokens":1}""", + """{"inputTokens":1,"outputTokens":[],"totalTokens":3}""", + ) + + assertEquals(StateUpdate.Idle(IdleStopReason.EndTurn), decode("""{"state":"idle","stopReason":"end_turn"}""")) + for (usage in malformedUsages) { + val decoded = decode("""{"state":"idle","stopReason":"end_turn","usage":$usage,"_meta":{"k":"v"}}""") + + assertEquals(StateUpdate.Idle(IdleStopReason.EndTurn, usage = null, _meta = meta), decoded, usage) + } + } + + @Test + fun `absent null malformed and non string stop reasons decode as no stop reason and encode without it`() { + val cases = listOf("", ""","stopReason":null""", ""","stopReason":true""", ""","stopReason":false""", + ""","stopReason":4""", ""","stopReason":["end_turn"]""", ""","stopReason":{"a":1}""") + + for (stopReason in cases) { + val decoded = decode("""{"state":"idle","_meta":{"k":"v"}$stopReason}""") + + assertEquals(StateUpdate.Idle(stopReason = null, _meta = meta), decoded, stopReason) + assertEquals(json("""{"state":"idle","_meta":{"k":"v"}}"""), encode(decoded), stopReason) + } + } + + @Test + fun `unrecognized stop reason keeps its fields but not the snapshot fields`() { + val payload = """ + {"state":"idle","stopReason":"_paused","resumeAfter":30,"nested":{"a":1}, + "usage":{"inputTokens":1,"outputTokens":2,"totalTokens":3},"_meta":{"k":"v"}} + """.trimIndent() + + val decoded = decode(payload) + + val idle = assertIs(decoded) + val other = assertIs(idle.stopReason) + assertEquals("_paused", other.stopReason) + assertEquals(setOf("resumeAfter", "nested"), other.fields.keys) + assertEquals(Usage(inputTokens = 1, outputTokens = 2, totalTokens = 3), idle.usage) + assertEquals(meta, idle._meta) + assertEquals(json(payload), encode(decoded)) + } + + @Test + fun `unrecognized stop reason without extra fields round trips`() { + assertRoundTrips( + """{"state":"idle","stopReason":"_paused"}""", + StateUpdate.Idle(stopReason = IdleStopReason.Other("_paused")), + ) + } + + @Test + fun `encoding an unrecognized stop reason never lets its fields override the snapshot`() { + val stopReason = IdleStopReason.Other( + "_paused", + buildJsonObject { + put("state", "running") + put("usage", 1) + put("_meta", 2) + put("stopReason", "end_turn") + put("keep", 3) + }, + ) + + val encoded = encode(StateUpdate.Idle(stopReason, _meta = meta)) + + assertEquals( + json("""{"state":"idle","stopReason":"_paused","keep":3,"_meta":{"k":"v"}}"""), + encoded, + ) + } +} diff --git a/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/v2/CapabilitiesConversionTest.kt b/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/v2/CapabilitiesConversionTest.kt index 3d5d7744..ef239970 100644 --- a/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/v2/CapabilitiesConversionTest.kt +++ b/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/v2/CapabilitiesConversionTest.kt @@ -13,6 +13,7 @@ import com.agentclientprotocol.model.SessionAdditionalDirectoriesCapabilities import com.agentclientprotocol.model.SessionCloseCapabilities import com.agentclientprotocol.model.SessionListCapabilities import com.agentclientprotocol.model.SessionResumeCapabilities +import com.agentclientprotocol.model.SubagentCapabilities import com.agentclientprotocol.model.v2.conversion.ProtocolConversionException import com.agentclientprotocol.model.v2.conversion.fromV1 import com.agentclientprotocol.model.v2.conversion.toV1 @@ -284,6 +285,25 @@ class CapabilitiesConversionTest { ) } + @Test + fun `the v1 client subagents capability does not convert to v2`() { + assertEquals( + "v1 ClientCapabilities.subagents cannot be represented in v2", + assertFailsWith { + V1ClientCapabilities(subagents = SubagentCapabilities()).toV2() + }.message, + ) + assertFailsWith { + V1InitializeRequest( + protocolVersion = 1, + clientCapabilities = V1ClientCapabilities(subagents = SubagentCapabilities()), + clientInfo = Implementation(name = "client", version = "1.0.0"), + ).toV2() + } + + assertEquals(ClientCapabilities(), V1ClientCapabilities(subagents = null).toV2()) + } + @Test fun `an fs object that advertises nothing is treated as absent`() { assertEquals(ClientCapabilities(), V1ClientCapabilities(fs = FileSystemCapability()).toV2()) diff --git a/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/v2/SessionUpdateConversionTest.kt b/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/v2/SessionUpdateConversionTest.kt index 50cdeeb8..f8e0818d 100644 --- a/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/v2/SessionUpdateConversionTest.kt +++ b/acp-model/src/commonTest/kotlin/com/agentclientprotocol/model/v2/SessionUpdateConversionTest.kt @@ -5,6 +5,7 @@ package com.agentclientprotocol.model.v2 import com.agentclientprotocol.annotations.UnstableApi import com.agentclientprotocol.model.MaybeUndefined import com.agentclientprotocol.model.MessageId +import com.agentclientprotocol.model.SessionId import com.agentclientprotocol.model.SessionModeId import com.agentclientprotocol.model.ToolCallId import com.agentclientprotocol.model.ToolCallLocation @@ -162,6 +163,22 @@ class SessionUpdateConversionTest { } } + @Test + fun `v1 subagent updates have no v2 form`() { + assertFailsWith { + V1SessionUpdate.SubagentUpdate(sessionId = SessionId("child_1")).toV2() + } + assertFailsWith { + V1SessionUpdate.SessionMessage(messageId = MessageId("msg_1")).toV2() + } + assertFailsWith { + V1SessionUpdate.SessionMessageChunk( + messageId = MessageId("msg_1"), + content = V1ContentBlock.Text(text = "hi"), + ).toV2() + } + } + // Tool calls: v1's two variants collapse into one v2 upsert @Test @@ -305,6 +322,25 @@ class SessionUpdateConversionTest { ) } + @Test + fun `v1 session tool call content does not cross to v2`() { + val content = listOf( + V1ToolCallContent.Session(sessionId = SessionId("child_1")), + V1ToolCallContent.Content(V1ContentBlock.Text("kept")), + ) + val expected = MaybeUndefined.Value(listOf(ToolCallContent.Content(ContentBlock.Text("kept")))) + + val update: V1SessionUpdate = V1SessionUpdate.ToolCallUpdate(toolCallId = ToolCallId("tc_1"), content = content) + assertEquals(expected, assertIs(update.toV2()).update.content) + + val creation: V1SessionUpdate = V1SessionUpdate.ToolCall( + toolCallId = ToolCallId("tc_1"), + title = "Delegate", + content = content, + ) + assertEquals(expected, assertIs(creation.toV2()).update.content) + } + @Test fun `a cleared tool call meta cannot be represented in v1`() { val update = SessionUpdate.ToolCallUpdate( diff --git a/samples/kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/support/util.kt b/samples/kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/support/util.kt index 836b74b0..6fcc3a3d 100644 --- a/samples/kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/support/util.kt +++ b/samples/kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/support/util.kt @@ -75,6 +75,18 @@ fun SessionUpdate.render() { println("Plan removed: ${this.id}") } + is SessionUpdate.SubagentUpdate -> { + println("Subagent session ${this.sessionId.value} updated") + } + + is SessionUpdate.SessionMessage -> { + println("Session message ${this.messageId.value} updated") + } + + is SessionUpdate.SessionMessageChunk -> { + println("Session message ${this.messageId.value}: ${this.content.render()}") + } + is SessionUpdate.UnknownSessionUpdate -> { println("Unknown session update: ${this.sessionUpdateType}") }