Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
320 changes: 316 additions & 4 deletions acp-model/api/acp-model.api

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ public data class ClientCapabilities(
val positionEncodings: List<PositionEncodingKind>? = 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

/**
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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<T : Any>(serialName: String) : KSerializer<T> {
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 <T : Any> JsonObject.decodeOrNull(
json: Json,
key: String,
deserializer: DeserializationStrategy<T>,
): 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 <T : Any> Json.decodeLenientlyOrNull(deserializer: DeserializationStrategy<T>, 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<JsonElement?> {
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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<out T> {
/**
* The field is not present; an existing value is left unchanged.
Expand Down Expand Up @@ -63,10 +58,9 @@ public sealed class MaybeUndefined<out T> {
/**
* 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<T> =
if (this is Undefined) other else this
Expand All @@ -76,49 +70,41 @@ public sealed class MaybeUndefined<out T> {
* 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 <T> MaybeUndefined<T>.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 <T> JsonObject.decodeMaybeUndefined(
internal fun <T : Any> JsonObject.decodeMaybeUndefined(
json: Json,
key: String,
deserializer: DeserializationStrategy<T>,
): MaybeUndefined<T> {
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 <T> JsonObject.decodeMaybeUndefinedList(
internal fun <T : Any> JsonObject.decodeMaybeUndefinedList(
json: Json,
key: String,
itemDeserializer: DeserializationStrategy<T>,
Expand All @@ -130,27 +116,17 @@ internal fun <T> 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 <T> JsonArray.decodeSkippingInvalid(
internal fun <T : Any> JsonArray.decodeSkippingInvalid(
json: Json,
itemDeserializer: DeserializationStrategy<T>,
): List<T> = mapNotNull { item ->
try {
json.decodeFromJsonElement(itemDeserializer, item)
} catch (_: Exception) {
// See decodeMaybeUndefined for why the catch is broad.
null
}
}
): List<T> = 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 <T> JsonObjectBuilder.putMaybeUndefined(
json: Json,
key: String,
Expand All @@ -159,6 +135,7 @@ internal fun <T> 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))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,6 @@ public open class AcpMethod(public val methodName: MethodName) {
SetSessionConfigOptionResponse.serializer()
)

@UnstableApi
public object SessionClose : AcpSessionRequestResponseMethod<CloseSessionRequest, CloseSessionResponse>(
"session/close",
CloseSessionRequest.serializer(),
Expand Down Expand Up @@ -504,7 +503,6 @@ public open class AcpMethod(public val methodName: MethodName) {
)
public val SessionSetConfigOption: AcpSessionRequestResponseMethod<SetSessionConfigOptionRequest, SetSessionConfigOptionResponse> get() = V1.SessionSetConfigOption

@UnstableApi
@Deprecated(
"Method objects are grouped by protocol version now",
ReplaceWith("AcpMethod.AgentMethods.V1.SessionClose"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -917,21 +913,15 @@ public data class DeleteSessionResponse(
*
* Only available if the agent supports the `session.close` capability.
*/
@UnstableApi
@Serializable
public data class CloseSessionRequest(
override val sessionId: SessionId,
override val _meta: JsonElement? = null
) : 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
Expand Down
Loading
Loading