diff --git a/AGENTS.md b/AGENTS.md index 13c76c49..f5e8c176 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -146,12 +146,21 @@ Lifecycle correctness is part of the public behavior. Changes to startup, cancel - Keep normal close, timeout/abort, parent cancellation, and I/O failure paths distinct and testable. - Only updates emitted through the v2 `AgentSession.prompt` flow count toward the turn’s lifecycle. The first user message supplies the prompt receipt, and an emitted idle prevents the SDK from sending another if the turn fails. - The v1 client keeps one `ClientSessionHolder` per session id. With a `ClientOperationsFactory`, the holder buffers the session's updates until the opening call answers. The `loadSession` and `resumeSession` overloads that take `ClientSessionOperations` claim the holder before the request goes out, and one consumer hands its queue to the operations until the answer. Until the switch to the session, every update passes that one queue with its one consumer, so the arrival order holds by construction: do not add a second delivery path, a lock, or a counter there. After the switch, an update goes synchronously to the session. An update that misses the closed queue waits in the `lateDeliveries` chain for the drain and for the update that missed the queue before it, so late updates keep their order too. -- The v1 agent runs one turn at a time per session, an SDK guarantee the protocol does not define. Only the turn frees its slot, when it answers, so a `session/prompt` sent earlier, even while a cancelled turn winds down, is rejected. `session/cancel` targets the turn registered when it arrives, never one registered while `AgentSession.cancel()` runs, and a cancelled turn answers only after every such call returns, so updates sent from it precede the response. A turn's flow failure stays inside the turn's job so it still passes that wait: after a cancel it answers `cancelled` (aborted calls often throw), otherwise it answers with the error. For WebSocket shutdown, preserve the established sequence: reject new work, enter closing state, drain accepted frames within the configured timeout, then perform a normal WebSocket close. Reserve cancellation/abort for timeout, cancellation, or writer failure. For STDIO, preserve newline-delimited frame behavior. Protocol output belongs on stdout; diagnostics and logs belong on stderr. +### Shared state + +- Keep state that several coroutines or threads share in immutable values behind atomics, with one atomic for all the state that one rule connects, as `SessionTable` does. Don't split a rule's state over several atomics and keep the rule true by the order of writes and reads. A plain `var` holds only state that one coroutine owns at a time. +- Decide from one `value` load. If a decision needs two atomics, a rule connects them: fold them. The value may be stale, so a decision that changes state is made in the write itself. +- Write with a pure CAS (`update`, `getAndUpdate`, `compareAndSet`). The lambda can run more than once, so it only computes the new value from the old one: it assigns nothing outside, reads no other atomic, and calls nothing with an effect. It may throw to reject the update. Read results from the snapshot that `getAndUpdate` returns. +- Take a lock (`SynchronizedObject`) only when no one may see the update without an effect that can't lag it, such as a send whose place on the wire matters. Every writer of that atomic then takes the lock and publishes with `value =`, and readers still don't lock. If a failed effect makes the section restore the old value, say so at the site: a reader may have seen the new one. +- Under a lock, call only code that doesn't suspend, block, take another lock, or call back into code that takes this lock. App code, and completing or cancelling a deferred or a job, can do any of that, so do them after the lock. +- Use a `Mutex` only for a section that must suspend. +- An operation may change several components in steps. State that can't be a value, such as a job, a deferred or a channel, follows one deciding CAS: its winner runs the other steps once, after it. Each step must be harmless to observe before the others, and removals compare identity, so a late step changes nothing. + ### Read-loop ordering and hooks - `Protocol` starts incoming notification and request handlers in arrival order, on one thread, and runs each until its first suspension, or its return, before any later handler starts. A notification's first part also runs before the next message, but a response that arrives right after a request may be handled before that request's handler starts. Code that relies on this, such as the client's `session/update` sorting and its permission handler, must keep that first part non-suspending and must not give the handler a dispatcher in its additional context. @@ -159,6 +168,18 @@ For STDIO, preserve newline-delimited frame behavior. Protocol output belongs on - `RequestOutcome.onResponseQueued` runs once the transport has accepted the success response, before `afterResponse`, so what it sends follows the response. It must not suspend, block or throw, and `mapResponse` must keep it. Use `onCompletion` to detect a response that never reached the transport. - Run work that belongs to the connection but outlives a request, such as subagent collections and openings, in `Protocol.newConnectionScope`, not in a handler's coroutine. +### v1 agent + +- One turn runs at a time per session, an SDK guarantee that ACP doesn't define. Only the turn frees its slot, when it answers. A `session/cancel` targets the turn registered when it arrives, and a cancelled turn answers only after every such `AgentSession.cancel()` has returned, so updates sent from it precede the response. Keep a turn's flow failure inside the turn's job so the turn still passes that wait. +- `SessionTable` holds roots and subagents in one atomic snapshot. Check and apply each rule that spans both in one update: a subagent registers only while its root is registered, a root is opened, replaced or removed together with its subagents, and root and subagent ids stay apart. A check in one update and a change in another lets a child commit under a root that is already gone. +- A `SubagentSessionWrapper` is pending until its own `SubagentUpdate` is sent from the factory, and every other operation fails until then. It is dropped (unregistered) if the factory throws or returns without the announcement, and removed by subtree cleanup. Its `events` are collected only after the factory returns, and a replayed child's only when the replay window closes. +- A child's own `SubagentUpdate` goes on its parent's stream, everything else on the child's. A root's `notify` rejects every `SubagentUpdate`, so the SDK sees each announcement and grant, and rejects `session_message`, `session_message_chunk` and `ToolCallContent.Session` without the client's `subagents` capability. Keep these checks in the one place every root path sends through. +- Record a child's cancel grant before sending the `SubagentUpdate` that carries it, and restore it if the send fails, so a `session/cancel` sent right after the grant is routed. +- The SDK never invents a child's outcome. It reports only `unknown`, when the `events` feed ends while the last state it sent is active, or when a factory that throws after the announcement left the state active. A collection that the SDK cancels sends nothing. +- A root's subtree is removed, its scope cancelled and its children's operations made to fail, before the response: on `session/close` after `AgentSession.close` returns, and, when a load or resume replaces an open root, once the app's factory returns and before the replay. No app code runs for the children. The root is removed by identity, so a root that replaced it stays. A later failure of the replacing load doesn't restore the old root. +- During `session/load`, what the subagents send before the replay returns is history: a grant is never in effect and a state doesn't count as active. The replay window stays open until the transport has accepted the response, and it closes from `onResponseQueued`, not `afterResponse`, because the client treats whatever follows the response as live, and so the replayed children's collections start before a slow `postInitialize()`. Before it answers, the load handler waits for the subagents' history sends in flight, their `SubagentUpdate`s and their own-stream updates alike, and such an update sent after that waits for the window to close and is live, so each lands on the side of the response it counts for. A root's own updates aren't counted, so only those that the replay sends before it returns are surely history. A failed load drops the root with every registration made during it. +- A child's lock orders its sends against dropping or removing it. + ## Public API and Compatibility The published modules use strict explicit API mode and Kotlin's binary compatibility validator. @@ -307,6 +328,52 @@ public data class TerminalOutputChunk( Phrase `@property` and `@param` text as a lowercase continuation with no trailing period, matching the existing `@param` and `@throws` style. Not every property needs a tag: document the ones whose contract is not evident from the name and type, and leave the rest to the class prose. +### Structuring long comments + +A long comment must be easy to scan. Never write a wall of text. + +- Keep paragraphs short, with one idea each. +- Put enumerations, alternatives, and case matrices, such as "before X / after X" or a list of failure cases, in bullet lists instead of chained clauses. +- Split a long KDoc, meaning several paragraphs or several distinct topics, into sections with Markdown headings. Use `###` for a section and `####` for a subsection. Level 3 keeps them below the page headings that Dokka generates. +- Put a heading on its own line, followed by a blank KDoc line. +- Keep a short comment, one or two paragraphs, as plain prose without headings. +- A long non-KDoc block comment does not render Markdown. Give it the same structure with separate paragraphs and lists; headings are optional. + +The `AgentSubagents` class KDoc is the example for sections (`### Removal`, `### Replay`), and `AgentSubagents.announce` is the example for bulleted failure cases. + +Use: + +```kotlin +/** + * Closes the session and frees its id. + * + * ### Pending requests + * + * Requests in flight when the call starts are answered before it returns. Requests that arrive later fail with + * [IllegalStateException]. + * + * ### Failure + * + * The call throws when: + * - the session is already closed; + * - the transport rejects the request. + * + * Nothing is removed then, and the session can be closed again. + * + * ### Cancellation + * + * If the caller is cancelled, the request is still sent, and the session counts as closed once the agent answers. + */ +``` + +Avoid: + +```kotlin +/** + * Closes the session and frees its id. Requests in flight when the call starts are answered before it returns, and requests that arrive later fail with [IllegalStateException]. The call throws when the session is already closed or when the transport rejects the request, in which case nothing is removed and the session can be closed again, and if the caller is cancelled, the request is still sent, and the session counts as closed once the agent answers. + */ +``` + ## Testing Strategy Use proportional verification while keeping core changes well covered. diff --git a/README.md b/README.md index efffaf8c..773ad183 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ Create a `Client` with your own `ClientSessionOperations` implementation. This s import com.agentclientprotocol.client.* import com.agentclientprotocol.common.ClientSessionOperations import com.agentclientprotocol.common.Event +import com.agentclientprotocol.common.SessionEvent import com.agentclientprotocol.common.SessionParameters import com.agentclientprotocol.model.* import com.agentclientprotocol.protocol.Protocol @@ -215,9 +216,13 @@ private class TerminalSession( // Grant whichever option was first in the list (swap for real UX). RequestPermissionResponse(RequestPermissionOutcome.Selected(permissions.first().optionId)) - override suspend fun notify(notification: SessionUpdate, _meta: JsonElement?) { - // Surface streaming updates back to the host application. - println("Agent update: $notification") + override suspend fun notify(event: SessionEvent) { + when (event) { + // Surface streaming updates back to the host application. + is SessionEvent.Update -> println("Agent update: ${event.update}") + // Updates before this marker came before the answer that opened the session; later ones are live. + is SessionEvent.Opened -> println("Session opened") + } } override suspend fun fsReadTextFile( diff --git a/acp-integration-test/src/commonTest/kotlin/com/agentclientprotocol/FeaturesTest.kt b/acp-integration-test/src/commonTest/kotlin/com/agentclientprotocol/FeaturesTest.kt index b10b67bb..921a370d 100644 --- a/acp-integration-test/src/commonTest/kotlin/com/agentclientprotocol/FeaturesTest.kt +++ b/acp-integration-test/src/commonTest/kotlin/com/agentclientprotocol/FeaturesTest.kt @@ -30,11 +30,7 @@ open class TestClientSessionOperations(): ClientSessionOperations { TODO() } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { - } + override suspend fun notify(event: SessionEvent) {} } open class TestAgentSession(override val sessionId: SessionId = SessionId("test-session-id")) : AgentSession { @@ -121,7 +117,9 @@ abstract class FeaturesTest(protocolDriver: ProtocolDriver) : ProtocolDriver by assertContentEquals(listOf("Hello", "File content: test", "END_TURN"), result) } + // TODO assert the current_mode_update in notify instead, together with removing the deprecated ClientSession.currentMode. @Test + @Suppress("DEPRECATION") fun `change mode from client`() = testWithProtocols { clientProtocol, agentProtocol -> val client = Client(protocol = clientProtocol) diff --git a/acp-integration-test/src/commonTest/kotlin/com/agentclientprotocol/SimpleAgentTest.kt b/acp-integration-test/src/commonTest/kotlin/com/agentclientprotocol/SimpleAgentTest.kt index 0e0bc082..f42c58d0 100644 --- a/acp-integration-test/src/commonTest/kotlin/com/agentclientprotocol/SimpleAgentTest.kt +++ b/acp-integration-test/src/commonTest/kotlin/com/agentclientprotocol/SimpleAgentTest.kt @@ -10,6 +10,8 @@ import com.agentclientprotocol.client.UnsupportedProtocolVersionException import com.agentclientprotocol.common.ClientSessionOperations import com.agentclientprotocol.common.Event import com.agentclientprotocol.common.SessionCreationParameters +import com.agentclientprotocol.common.SessionEvent +import com.agentclientprotocol.common.notify import com.agentclientprotocol.framework.ProtocolDriver import com.agentclientprotocol.model.* import com.agentclientprotocol.protocol.AcpExpectedError @@ -153,10 +155,8 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver TODO("Not yet implemented") } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return TODO("Not yet implemented") } } @@ -220,10 +220,8 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver TODO("Not yet implemented") } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return TODO("Not yet implemented") } } @@ -301,10 +299,8 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver TODO("Not yet implemented") } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return TODO("Not yet implemented") } } @@ -375,10 +371,8 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver TODO("Not yet implemented") } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return TODO("Not yet implemented") } } @@ -456,10 +450,8 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver ) } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return TODO("Not yet implemented") } } @@ -546,10 +538,8 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver } } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return TODO("Not yet implemented") } } @@ -642,10 +632,8 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver } } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return TODO("Not yet implemented") } } @@ -730,11 +718,7 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver } } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { - } + override suspend fun notify(event: SessionEvent) {} } } @@ -801,10 +785,9 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver TODO() } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return + val notification = event.update notificationDeferred.complete(notification) } } @@ -868,10 +851,9 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return + val notification = event.update notificationDeferred.complete(notification) } } @@ -955,11 +937,7 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { - } + override suspend fun notify(event: SessionEvent) {} } } } @@ -975,10 +953,9 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return + val notification = event.update val text = (notification as? SessionUpdate.AgentMessageChunk)?.content as? ContentBlock.Text ?: return received.add(text.text) } @@ -990,79 +967,6 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver assertContentEquals(listOf(freshReplay), received) } - @Test - fun `unknown session request during init should fail fast with not found`() = testWithProtocols { clientProtocol, agentProtocol -> - val unknownSessionId = SessionId("unknown-request-session-id") - val requestFailure = CompletableDeferred() - - val client = Client(protocol = clientProtocol) - Agent(protocol = agentProtocol, agentSupport = object : AgentSupport { - override suspend fun initialize(clientInfo: ClientInfo): AgentInfo { - return AgentInfo(clientInfo.protocolVersion) - } - - override suspend fun createSession(sessionParameters: SessionCreationParameters): AgentSession { - this@testWithProtocols.launch { - try { - AcpMethod.ClientMethods.V1.FsReadTextFile( - agentProtocol, - ReadTextFileRequest(unknownSessionId, "/test/path", null, null, null) - ) - requestFailure.complete(AssertionError("Unknown session request should fail")) - } catch (t: Throwable) { - requestFailure.complete(t) - } - } - - delay(200.milliseconds) - return object : AgentSession { - override val sessionId: SessionId = SessionId("known-session-id") - - override suspend fun prompt( - content: List, - _meta: JsonElement?, - ): Flow = emptyFlow() - } - } - - override suspend fun loadSession( - sessionId: SessionId, - sessionParameters: SessionCreationParameters, - ): AgentSession { - TODO("Not yet implemented") - } - }) - - client.initialize(ClientInfo(protocolVersion = LATEST_PROTOCOL_VERSION)) - - withTimeout(2000.milliseconds) { - client.newSession(SessionCreationParameters("/test/path", emptyList())) { _, _ -> - object : ClientSessionOperations { - override suspend fun requestPermissions( - toolCall: SessionUpdate.ToolCallUpdate, - permissions: List, - _meta: JsonElement?, - ): RequestPermissionResponse { - return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) - } - - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { - } - } - } - } - - val failure = withTimeout(2000.milliseconds) { requestFailure.await() } - val message = failure.message ?: failure.toString() - assertTrue( - message.contains("Session $unknownSessionId not found"), - "Unexpected failure message: $message" - ) - } - @Test fun `unknown session replay should survive while another session still initializing`() = testWithProtocols { clientProtocol, agentProtocol -> val newSessionId = SessionId("parallel-new-session-id") @@ -1127,10 +1031,9 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return + val notification = event.update val text = (notification as? SessionUpdate.AgentMessageChunk)?.content as? ContentBlock.Text ?: return if (!replayReceived.isCompleted) { replayReceived.complete(text.text) @@ -1153,11 +1056,7 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { - } + override suspend fun notify(event: SessionEvent) {} } } } @@ -1236,10 +1135,9 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return + val notification = event.update notificationDeferred.complete(notification) } } @@ -1318,10 +1216,9 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return + val notification = event.update notificationDeferred.complete(notification) } } @@ -1386,7 +1283,9 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) } - override suspend fun notify(notification: SessionUpdate, _meta: JsonElement?) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return + val notification = event.update val text = (notification as? SessionUpdate.AgentMessageChunk)?.content as? ContentBlock.Text ?: return received.update { it + text.text } } @@ -1453,7 +1352,9 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) } - override suspend fun notify(notification: SessionUpdate, _meta: JsonElement?) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return + val notification = event.update val text = (notification as? SessionUpdate.AgentMessageChunk)?.content as? ContentBlock.Text ?: return received.update { it + text.text } } @@ -1585,10 +1486,9 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return + val notification = event.update val text = (notification as? SessionUpdate.AgentMessageChunk)?.content as? ContentBlock.Text ?: return if (!firstNotification.isCompleted) { firstNotification.complete(text.text) @@ -1680,10 +1580,9 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return + val notification = event.update val text = (notification as? SessionUpdate.AgentMessageChunk)?.content as? ContentBlock.Text ?: return received.add(text.text) } @@ -1750,10 +1649,9 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return + val notification = event.update if (notification !is SessionUpdate.AgentMessageChunk) return val text = (notification.content as ContentBlock.Text).text received.add(text) @@ -1835,10 +1733,9 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return + val notification = event.update delay(2.milliseconds) val text = (notification as? SessionUpdate.AgentMessageChunk)?.content as? ContentBlock.Text ?: return receivedMessages.add(text.text) @@ -1936,10 +1833,9 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return + val notification = event.update delay(clientNotifyDelay) val message = when (notification) { is SessionUpdate.AgentMessageChunk -> "agent:${(notification.content as ContentBlock.Text).text}" @@ -2619,10 +2515,9 @@ abstract class SimpleAgentTest(protocolDriver: ProtocolDriver) : ProtocolDriver return RequestPermissionResponse(RequestPermissionOutcome.Cancelled) } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return + val notification = event.update readyUpdate.complete(notification) } } diff --git a/acp/api/acp.api b/acp/api/acp.api index 192b8322..55920ac6 100644 --- a/acp/api/acp.api +++ b/acp/api/acp.api @@ -86,6 +86,36 @@ public final class com/agentclientprotocol/agent/AgentSessionKt { public static synthetic fun setConfigOption-lh9iGNw$default (Lcom/agentclientprotocol/agent/AgentSession;Ljava/lang/String;Ljava/lang/String;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; } +public final class com/agentclientprotocol/agent/AgentSubagentContext { + public final fun getClient ()Lcom/agentclientprotocol/common/ClientSessionOperations; + public final fun getSessionId-7EW-EgU ()Ljava/lang/String; + public final fun getSubagents ()Lcom/agentclientprotocol/agent/AgentSubagents; +} + +public abstract interface class com/agentclientprotocol/agent/AgentSubagentFactory { + public abstract fun createSubagent (Lcom/agentclientprotocol/agent/AgentSubagentContext;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; +} + +public abstract interface class com/agentclientprotocol/agent/AgentSubagentSession { + public fun cancel (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun cancel$suspendImpl (Lcom/agentclientprotocol/agent/AgentSubagentSession;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public fun getEvents ()Lkotlinx/coroutines/flow/Flow; +} + +public final class com/agentclientprotocol/agent/AgentSubagentSession$DefaultImpls { + public static fun cancel (Lcom/agentclientprotocol/agent/AgentSubagentSession;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static fun getEvents (Lcom/agentclientprotocol/agent/AgentSubagentSession;)Lkotlinx/coroutines/flow/Flow; +} + +public final class com/agentclientprotocol/agent/AgentSubagents { + public final fun announce-LQdhiks (Ljava/lang/String;Lcom/agentclientprotocol/agent/AgentSubagentFactory;Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun announce-LQdhiks$default (Lcom/agentclientprotocol/agent/AgentSubagents;Ljava/lang/String;Lcom/agentclientprotocol/agent/AgentSubagentFactory;Ljava/lang/String;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; +} + +public final class com/agentclientprotocol/agent/AgentSubagentsKt { + public static final fun getSubagents (Lkotlin/coroutines/CoroutineContext;)Lcom/agentclientprotocol/agent/AgentSubagents; +} + public abstract interface class com/agentclientprotocol/agent/AgentSupport { public fun authStatus (Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun authStatus$default (Lcom/agentclientprotocol/agent/AgentSupport;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; @@ -588,8 +618,7 @@ public final class com/agentclientprotocol/client/v2/ElicitationHandler$DefaultI } public abstract interface class com/agentclientprotocol/common/ClientSessionOperations : com/agentclientprotocol/common/ElicitationOperations, com/agentclientprotocol/common/FileSystemOperations, com/agentclientprotocol/common/TerminalOperations { - public abstract fun notify (Lcom/agentclientprotocol/model/SessionUpdate;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; - public static synthetic fun notify$default (Lcom/agentclientprotocol/common/ClientSessionOperations;Lcom/agentclientprotocol/model/SessionUpdate;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; + public abstract fun notify (Lcom/agentclientprotocol/common/SessionEvent;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public abstract fun requestPermissions (Lcom/agentclientprotocol/model/SessionUpdate$ToolCallUpdate;Ljava/util/List;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun requestPermissions$default (Lcom/agentclientprotocol/common/ClientSessionOperations;Lcom/agentclientprotocol/model/SessionUpdate$ToolCallUpdate;Ljava/util/List;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; } @@ -599,7 +628,6 @@ public final class com/agentclientprotocol/common/ClientSessionOperations$Defaul public static fun createElicitation (Lcom/agentclientprotocol/common/ClientSessionOperations;Lcom/agentclientprotocol/model/CreateElicitationRequest;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static fun fsReadTextFile-i6TIkSo (Lcom/agentclientprotocol/common/ClientSessionOperations;Ljava/lang/String;Lkotlin/UInt;Lkotlin/UInt;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static fun fsWriteTextFile (Lcom/agentclientprotocol/common/ClientSessionOperations;Ljava/lang/String;Ljava/lang/String;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; - public static synthetic fun notify$default (Lcom/agentclientprotocol/common/ClientSessionOperations;Lcom/agentclientprotocol/model/SessionUpdate;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public static synthetic fun requestPermissions$default (Lcom/agentclientprotocol/common/ClientSessionOperations;Lcom/agentclientprotocol/model/SessionUpdate$ToolCallUpdate;Ljava/util/List;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; public static fun terminalCreate-HNfBzwE (Lcom/agentclientprotocol/common/ClientSessionOperations;Ljava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/util/List;Lkotlin/ULong;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static fun terminalKill (Lcom/agentclientprotocol/common/ClientSessionOperations;Ljava/lang/String;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; @@ -608,6 +636,11 @@ public final class com/agentclientprotocol/common/ClientSessionOperations$Defaul public static fun terminalWaitForExit (Lcom/agentclientprotocol/common/ClientSessionOperations;Ljava/lang/String;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; } +public final class com/agentclientprotocol/common/ClientSessionOperationsKt { + public static final fun notify (Lcom/agentclientprotocol/common/ClientSessionOperations;Lcom/agentclientprotocol/model/SessionUpdate;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; + public static synthetic fun notify$default (Lcom/agentclientprotocol/common/ClientSessionOperations;Lcom/agentclientprotocol/model/SessionUpdate;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; +} + public abstract interface class com/agentclientprotocol/common/ElicitationOperations { public fun completeElicitation (Lcom/agentclientprotocol/model/CompleteElicitationNotification;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun completeElicitation$suspendImpl (Lcom/agentclientprotocol/common/ElicitationOperations;Lcom/agentclientprotocol/model/CompleteElicitationNotification;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; @@ -660,6 +693,20 @@ public final class com/agentclientprotocol/common/SessionCreationParameters { public final fun get_meta ()Lkotlinx/serialization/json/JsonElement; } +public abstract class com/agentclientprotocol/common/SessionEvent { +} + +public final class com/agentclientprotocol/common/SessionEvent$Opened : com/agentclientprotocol/common/SessionEvent { + public final fun getResponse ()Lcom/agentclientprotocol/model/AcpCreatedSessionResponse; +} + +public final class com/agentclientprotocol/common/SessionEvent$Update : com/agentclientprotocol/common/SessionEvent { + public fun (Lcom/agentclientprotocol/model/SessionUpdate;Lkotlinx/serialization/json/JsonElement;)V + public synthetic fun (Lcom/agentclientprotocol/model/SessionUpdate;Lkotlinx/serialization/json/JsonElement;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun getUpdate ()Lcom/agentclientprotocol/model/SessionUpdate; + public final fun get_meta ()Lkotlinx/serialization/json/JsonElement; +} + public abstract interface class com/agentclientprotocol/common/TerminalOperations { public fun terminalCreate-HNfBzwE (Ljava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/util/List;Lkotlin/ULong;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static synthetic fun terminalCreate-HNfBzwE$default (Lcom/agentclientprotocol/common/TerminalOperations;Ljava/lang/String;Ljava/util/List;Ljava/lang/String;Ljava/util/List;Lkotlin/ULong;Lkotlinx/serialization/json/JsonElement;Lkotlin/coroutines/Continuation;ILjava/lang/Object;)Ljava/lang/Object; diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/Agent.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/Agent.kt index df67bd32..f6bb1982 100644 --- a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/Agent.kt +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/Agent.kt @@ -1,32 +1,27 @@ package com.agentclientprotocol.agent +import com.agentclientprotocol.agent.internal.NesSessionWrapper import com.agentclientprotocol.agent.internal.RemoteClientSessionOperations +import com.agentclientprotocol.agent.internal.RootSessionWrapper +import com.agentclientprotocol.agent.internal.SessionWrapperContextElement +import com.agentclientprotocol.agent.internal.SubagentSessionWrapper +import com.agentclientprotocol.agent.internal.sessionWrapper import com.agentclientprotocol.annotations.UnstableApi import com.agentclientprotocol.client.ClientInfo import com.agentclientprotocol.common.ClientSessionOperations -import com.agentclientprotocol.common.Event import com.agentclientprotocol.common.SessionCreationParameters import com.agentclientprotocol.model.* import com.agentclientprotocol.protocol.* import com.agentclientprotocol.util.SequenceToPaginatedResponseAdapter import io.github.oshai.kotlinlogging.KotlinLogging import kotlinx.atomicfu.atomic +import kotlinx.atomicfu.getAndUpdate import kotlinx.atomicfu.update +import kotlinx.collections.immutable.PersistentMap +import kotlinx.collections.immutable.mutate import kotlinx.collections.immutable.persistentMapOf -import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.Job -import kotlinx.coroutines.coroutineScope -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.getAndUpdate -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import kotlinx.serialization.json.JsonElement -import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.CoroutineContext private val logger = KotlinLogging.logger {} @@ -51,164 +46,26 @@ public class Agent( private val agentSupport: AgentSupport, ) { - internal open class BaseSessionWrapper( - val agent: Agent, - val protocol: Protocol - ) { - internal suspend fun executeWithSession(block: suspend () -> T): T { - return withContext(this.asContextElement()) { - return@withContext block() - } - } - } - - internal class SessionWrapper( - agent: Agent, - val agentSession: AgentSession, - val clientOperations: ClientSessionOperations, - protocol: Protocol - ) : BaseSessionWrapper(agent, protocol) { - private class PromptSession(val promptJob: Job) { - /** - * The number of cancels still running for this turn, or [ANSWERING] once the turn has passed the wait for - * them and is about to answer. - */ - private val runningCancels = MutableStateFlow(0) - - private val _isCancelRequested = atomic(false) - - /** - * Whether a `session/cancel` targeted this turn before it started answering. - */ - val isCancelRequested: Boolean get() = _isCancelRequested.value - - /** - * Registers a cancel for this turn. Returns `false` if the turn is already answering. - */ - fun startCancel(): Boolean { - val started = runningCancels.getAndUpdate { if (it == ANSWERING) it else it + 1 } != ANSWERING - if (started) _isCancelRequested.value = true - return started - } - - fun finishCancel() { - runningCancels.update { it - 1 } - } - - /** - * Suspends until no cancel is running for this turn, then marks the turn as answering. - */ - suspend fun awaitCancels() { - while (!runningCancels.compareAndSet(0, ANSWERING)) { - runningCancels.first { it == 0 } - } - } - - private companion object { - const val ANSWERING = -1 - } - } - - private val _activePrompt = atomic(null) + private val _clientInfo = CompletableDeferred() - @OptIn(UnstableApi::class) - suspend fun prompt(content: List, _meta: JsonElement? = null): PromptResponse { - var response: PromptResponse? = null - var failure: Throwable? = null - return coroutineScope { - val promptJob = launch(start = CoroutineStart.LAZY) { - /* - * Keep a failure inside the turn's job, so a failed turn still waits for running cancels and a - * cancel can still decide its answer. - */ - try { - agentSession.prompt(content, _meta).collect { event -> - when (event) { - is Event.PromptResponseEvent -> { - if (response != null) { - logger.error { "Received repeated prompt response: ${event.response} (previous: $response). The last is used" } - } - response = event.response - } - - is Event.SessionUpdateEvent -> { - clientOperations.notify(event.update, event._meta) - } - } - } - } catch (e: CancellationException) { - throw e - } catch (e: Throwable) { - failure = e - } - } + /** + * The root sessions and subagents of this connection, at every depth, by session id. + * + * One snapshot, so each rule that spans roots and subagents is checked and applied in one update. + */ + private val _sessions = atomic(SessionTable(persistentMapOf(), persistentMapOf())) - val promptSession = PromptSession(promptJob) - if (!_activePrompt.compareAndSet(null, promptSession)) { - error("There is already active prompt execution") - } - try { - promptJob.join() - /* - * A cancelled turn answers only after the session's cancel() returns: the response must follow - * every aborted operation and every update, including those sent from cancel(). - */ - promptSession.awaitCancels() - /* - * The session's cancel() may stop the turn cooperatively, so its flow ends normally before the - * SDK cancels the job. The client still cancelled the turn and must get the `cancelled` reason. - */ - val isCancelled = promptJob.isCancelled || promptSession.isCancelRequested - failure?.let { e -> - if (!isCancelled) throw e - logger.debug(e) { "Prompt turn failed after a cancel; answering as cancelled" } - } - response ?: PromptResponse( - stopReason = if (isCancelled) StopReason.CANCELLED else StopReason.END_TURN - ) - } finally { - // Only the turn frees its slot, so the next prompt can start only after this one has answered. - _activePrompt.value = null - } - } - } + private class SessionTable( + val roots: PersistentMap, + val subagents: PersistentMap, + ) { + fun subagentsOf(root: RootSessionWrapper): List = + subagents.values.filter { it.root === root } - suspend fun cancel() { - /* - * Take the turn to cancel before notifying the session: the session's cancel() may suspend, and a turn - * that has already answered may be followed by the next one meanwhile, which this cancel must not touch. - */ - val promptToCancel = _activePrompt.value?.takeIf { it.startCancel() } - try { - // notify AgentSession about upcoming cancellation, this way implementations can gracefully stop ongoing requests - agentSession.cancel() - - if (promptToCancel != null) { - logger.trace { "Cancelling prompt" } - // we expect that all nested outgoing jobs will be cancelled automatically due to structured concurrency - // -> prompt task - // <- [request] read file - // -> [response] read file - // <- [request] permissions - // |suspended| - // cancelling the whole prompt should cancel all nested outgoing requests. These requests on CE will propagate cancellation to the other side - promptToCancel.promptJob.cancel() - } - } finally { - promptToCancel?.finishCancel() - } - } + fun withoutSubagents(removed: List): PersistentMap = + subagents.mutate { map -> removed.forEach { map.remove(it.sessionId) } } } - internal class NesSessionWrapper @OptIn(UnstableApi::class) constructor( - agent: Agent, - val nesSession: NesAgentSession, - protocol: Protocol - ) : BaseSessionWrapper(agent, protocol) - - private val _clientInfo = CompletableDeferred() - private val _sessions = atomic(persistentMapOf()) - private val _nesSessions = atomic(persistentMapOf()) internal fun getClientInfoOrThrow(): ClientInfo { @@ -308,6 +165,7 @@ public class Agent( } protocol.setRequestHandler(AcpMethod.AgentMethods.V1.SessionDelete) { params: DeleteSessionRequest -> + checkNotSubagent(params.sessionId) return@setRequestHandler agentSupport.deleteSession(params.sessionId, params._meta) } @@ -327,10 +185,11 @@ public class Agent( } protocol.setRequestOutcomeHandler(AcpMethod.AgentMethods.V1.SessionLoad) { params: LoadSessionRequest -> + checkNotSubagent(params.sessionId) val sessionParameters = SessionCreationParameters(params.cwd, params.mcpServers, params.additionalDirectories, params._meta) val created = createSession( sessionParameters, - beforeResponse = { session -> session.replayHistory() }, + replayHistory = { session -> session.replayHistory() }, ) { agentSupport.loadSession(params.sessionId, sessionParameters) } @OptIn(UnstableApi::class) return@setRequestOutcomeHandler created.mapResponse { session -> @@ -344,17 +203,6 @@ public class Agent( } } - protocol.setRequestOutcomeHandler(AcpMethod.AgentMethods.V1.SessionResume) { params: ResumeSessionRequest -> - val sessionParameters = SessionCreationParameters(params.cwd, params.mcpServers, params.additionalDirectories, params._meta) - val created = createSession(sessionParameters) { agentSupport.resumeSession(params.sessionId, sessionParameters) } - return@setRequestOutcomeHandler created.mapResponse { session -> - ResumeSessionResponse( - modes = session.asModeState(), - models = session.asModelState() - ) - } - } - protocol.setRequestHandler(AcpMethod.AgentMethods.V1.SessionSetMode) { params: SetSessionModeRequest -> val session = getSessionOrThrow(params.sessionId) return@setRequestHandler session.executeWithSession { @@ -377,24 +225,38 @@ public class Agent( } protocol.setNotificationHandler(AcpMethod.AgentMethods.V1.SessionCancel) { params: CancelNotification -> + val child = subagentOrNull(params.sessionId) + if (child != null) { + child.cancel() + return@setNotificationHandler + } val session = getSessionOrThrow(params.sessionId) session.executeWithSession { session.cancel() } } - @OptIn(UnstableApi::class) protocol.setRequestHandler(AcpMethod.AgentMethods.V1.SessionClose) { params: CloseSessionRequest -> - val session = getSessionOrThrow(params.sessionId) + /* + * Closing is idempotent: an unknown or closed id gets the empty result without calling the app + * (https://agentclientprotocol.com/protocol/v1/session-setup#closing-active-sessions). A subagent's id is + * still rejected. + */ + val session = _sessions.value.roots[params.sessionId] ?: run { + checkNotSubagent(params.sessionId) + return@setRequestHandler CloseSessionResponse() + } val response = session.executeWithSession { session.agentSession.close(params._meta) } - _sessions.update { it.remove(params.sessionId) } + // Before the response, so no update of a child follows it. + removeRoot(session) return@setRequestHandler response } @OptIn(UnstableApi::class) protocol.setRequestOutcomeHandler(AcpMethod.AgentMethods.V1.SessionFork) { params: ForkSessionRequest -> + checkNotSubagent(params.sessionId) val sessionParameters = SessionCreationParameters(params.cwd, params.mcpServers, params.additionalDirectories, params._meta) val created = createSession(sessionParameters) { agentSupport.forkSession(params.sessionId, sessionParameters) } return@setRequestOutcomeHandler created.mapResponse { session -> @@ -409,6 +271,7 @@ public class Agent( @OptIn(UnstableApi::class) protocol.setRequestOutcomeHandler(AcpMethod.AgentMethods.V1.SessionResume) { params: ResumeSessionRequest -> + checkNotSubagent(params.sessionId) val sessionParameters = SessionCreationParameters(params.cwd, params.mcpServers, params.additionalDirectories, params._meta) val created = createSession(sessionParameters) { agentSupport.resumeSession(params.sessionId, sessionParameters) } return@setRequestOutcomeHandler created.mapResponse { session -> @@ -516,51 +379,143 @@ public class Agent( } } + /** + * Opens a root session. [replayHistory] is given only for `session/load`: it runs before the response, in the + * replay window of the new session. + */ + @OptIn(UnstableApi::class) private suspend fun createSession( sessionParameters: SessionCreationParameters, - beforeResponse: suspend (AgentSession) -> Unit = {}, + replayHistory: (suspend (AgentSession) -> Unit)? = null, sessionFactory: suspend (SessionCreationParameters) -> AgentSession, ): RequestOutcome { val session = sessionFactory(sessionParameters) val clientInfo = getClientInfoOrThrow() - val sessionWrapper = SessionWrapper( + val sessionWrapper = RootSessionWrapper( this, session, RemoteClientSessionOperations(protocol, session.sessionId, clientInfo.capabilities), - protocol + protocol, + subagentsSupported = clientInfo.capabilities.subagents != null, + replaying = replayHistory != null, ) - _sessions.update { - it.put(session.sessionId, sessionWrapper) + /* + * Re-opening an open id, as `session/load` and `session/resume` may, replaces its root. The old subtree is + * cleaned up before the replay, which may announce the same ids again; the old root's turn and AgentSession + * are left alone. + */ + val before = _sessions.getAndUpdate { table -> + check(sessionWrapper.sessionId !in table.subagents) { + "Session ${sessionWrapper.sessionId} is already registered on this connection as a subagent" + } + val removed = table.roots[sessionWrapper.sessionId]?.let { table.subagentsOf(it) }.orEmpty() + SessionTable(table.roots.put(sessionWrapper.sessionId, sessionWrapper), table.withoutSubagents(removed)) } + before.roots[sessionWrapper.sessionId]?.let { cleanUpSubtree(it, before.subagentsOf(it)) } - try { - sessionWrapper.executeWithSession { beforeResponse(session) } - } catch (t: Throwable) { - _sessions.update { sessions -> - if (sessions[session.sessionId] === sessionWrapper) sessions.remove(session.sessionId) else sessions + if (replayHistory != null) { + try { + sessionWrapper.executeWithSession { replayHistory(session) } + // The response may be sent once this returns, so the history sends still in flight must precede it. + sessionWrapper.replayWindow.awaitHistorySends() + } catch (t: Throwable) { + removeRoot(sessionWrapper) + sessionWrapper.replayWindow.close() + throw t } - throw t } return RequestOutcome( response = session, afterResponse = { sessionWrapper.executeWithSession { session.postInitialize() } }, + onCompletion = { + // A window still open here means the load response never reached the transport: the load failed. + if (sessionWrapper.replayWindow.isOpen) { + removeRoot(sessionWrapper) + sessionWrapper.replayWindow.close() + } + }, + /* + * The client treats what follows the load response as live, so the window closes once the transport has + * the response, not when afterResponse starts, and the replayed subagents' collections start before a + * slow postInitialize() could hold them back. + */ + onResponseQueued = if (replayHistory != null) { + { sessionWrapper.replayWindow.close() } + } else { + null + }, ) } - private fun getSessionOrThrow(sessionId: SessionId): SessionWrapper = _sessions.value[sessionId] ?: acpFail("Session $sessionId not found") + private fun getSessionOrThrow(sessionId: SessionId): RootSessionWrapper { + _sessions.value.roots[sessionId]?.let { return it } + checkNotSubagent(sessionId) + acpFail("Session $sessionId not found") + } - private fun getNesSessionOrThrow(sessionId: SessionId): NesSessionWrapper = _nesSessions.value[sessionId] ?: acpFail("NES session $sessionId not found") -} + /** + * Rejects a session method on a subagent's id: the client may only cancel a subagent. + */ + private fun checkNotSubagent(sessionId: SessionId) { + if (sessionId in _sessions.value.subagents) acpFail("Session $sessionId is a subagent") + } + internal fun subagentOrNull(sessionId: SessionId): SubagentSessionWrapper? = _sessions.value.subagents[sessionId] -internal class SessionWrapperContextElement(val sessionWrapper: Agent.BaseSessionWrapper) : AbstractCoroutineContextElement(Key) { - object Key : CoroutineContext.Key -} + /** + * Registers [child] under its own id while its root is registered. + * + * @throws IllegalArgumentException if the id is already registered on this connection, as a root session or a + * subagent + * @throws IllegalStateException if [child]'s root is no longer registered: it was closed, its `session/load` + * failed, or a re-opening of its id replaced it + */ + internal fun registerSubagent(child: SubagentSessionWrapper) { + val root = child.root + _sessions.update { table -> + check(table.roots[root.sessionId] === root) { "Session ${root.sessionId} is closed" } + require(child.sessionId !in table.roots && child.sessionId !in table.subagents) { + "Session ${child.sessionId} is already registered on this connection" + } + SessionTable(table.roots, table.subagents.put(child.sessionId, child)) + } + } + + /** + * Removes [child] if it is still the subagent registered under its id. + */ + internal fun unregisterSubagent(child: SubagentSessionWrapper) { + _sessions.update { table -> + if (table.subagents[child.sessionId] !== child) return@update table + SessionTable(table.roots, table.subagents.remove(child.sessionId)) + } + } -internal fun Agent.BaseSessionWrapper.asContextElement() = SessionWrapperContextElement(this) + /** + * Removes [root] with every subagent below it, and cleans its subtree up. A root that replaced [root] stays. + */ + private fun removeRoot(root: RootSessionWrapper) { + val before = _sessions.getAndUpdate { table -> + val roots = if (table.roots[root.sessionId] === root) table.roots.remove(root.sessionId) else table.roots + SessionTable(roots, table.withoutSubagents(table.subagentsOf(root))) + } + cleanUpSubtree(root, before.subagentsOf(root)) + } + + /** + * Cancels the collections of [root]'s subagents, [removed] from the table already, and makes their operations + * fail, without calling app code. + */ + private fun cleanUpSubtree(root: RootSessionWrapper, removed: List) { + root.cancelSubtreeScope() + removed.forEach { it.remove() } + } + + private fun getNesSessionOrThrow(sessionId: SessionId): NesSessionWrapper = _nesSessions.value[sessionId] ?: acpFail("NES session $sessionId not found") +} public val CoroutineContext.agent: Agent get() = this[SessionWrapperContextElement.Key]?.sessionWrapper?.agent ?: error("No agent data found in context") @@ -573,13 +528,9 @@ public val CoroutineContext.clientInfo: ClientInfo /** * Returns a remote client connected to the counterpart via the current protocol. * Only available for chat sessions. NES sessions do not have access to client operations. + * In a subagent's context, these are the subagent's operations (see [AgentSubagentContext.client]). * * @throws IllegalStateException if called from a NES session context or outside a session context */ public val CoroutineContext.client: ClientSessionOperations - get() { - val wrapper = this[SessionWrapperContextElement.Key]?.sessionWrapper - ?: error("No session found in context") - return (wrapper as? Agent.SessionWrapper)?.clientOperations - ?: error("Client operations are not available for NES sessions. Only chat sessions have access to client operations.") - } + get() = sessionWrapper("Client operations").clientOperations diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/AgentSession.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/AgentSession.kt index b129b527..6ea99ba6 100644 --- a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/AgentSession.kt +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/AgentSession.kt @@ -31,9 +31,47 @@ public interface AgentSession { * currentCoroutineContext().client * ``` * - * If it throws, `session/load` fails with that error and the session is not registered. + * If it throws, `session/load` fails with that error and the session is not registered. A session that was open + * under the same id is not restored. * * See protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/session-setup#loading-sessions) + * + * ### Subagents + * + * Recorded subagents are replayed through the unstable [AgentSubagents] API. The SDK doesn't record history and + * doesn't tell a factory that it replays, so the app: + * - sends each recorded update in its recorded order through the client of the session that sent it live: the + * root's own client, or the child's [AgentSubagentContext.client], which routes as it did live; + * - turns each recorded announcement into an [AgentSubagents.announce] call whose factory sends it and returns; + * - keeps the factory's context, the only way to reach the child afterwards, for example in the returned session. + * + * So no update needs special handling, a patch can't precede its announcement, and only the interleaving of + * different streams may differ from the live one. See [AgentSubagents] for the replay window and the events. + * + * In this example, which assumes that the client advertised the `subagents` capability, `record` is the app's list + * of updates in the order they went out, each with the id of the session whose client sent it and, for an + * announcement, the id of its parent. `ReplayedSubagent` is the app's [AgentSubagentSession] that keeps the + * factory's context and has empty events. + * + * ``` + * override suspend fun replayHistory() { + * val root = currentCoroutineContext() + * val children = mutableMapOf() + * for ((sender, parent, update) in record) { + * val client = if (sender == sessionId) root.client else children[sender]?.client + * if (client != null) { + * client.notify(update) + * } else { + * // A child's first recorded update is its announcement. + * val factory = AgentSubagentFactory { context -> + * context.client.notify(update) + * ReplayedSubagent(context) + * } + * children[sender] = root.subagents!!.announce(sender, factory, parent).context + * } + * } + * } + * ``` */ public suspend fun replayHistory() {} @@ -71,19 +109,18 @@ public interface AgentSession { public suspend fun cancel() {} /** - * **UNSTABLE** - * - * This capability is not part of the spec yet, and may be removed or changed at any point. - * * Closes the session and frees up any resources associated with it. * The agent must cancel any ongoing work (as if `cancel` was called) * and then free up any resources associated with the session. * - * Only called if the agent advertises the `session.close` capability. + * Stop the work of the session's subagents here too: once this returns, the SDK removes them without calling app + * code. If it throws, the session and its subagents stay registered. See [AgentSubagents]. + * + * Only called if the agent advertises the `session.close` capability. A `session/close` for a session id that + * is unknown or already closed doesn't call it: the agent answers it with an empty [CloseSessionResponse]. * * Corresponds to the [AcpMethod.AgentMethods.V1.SessionClose] */ - @UnstableApi public suspend fun close(_meta: JsonElement?): CloseSessionResponse { throw NotImplementedError("close is not implemented. The capability is declared in AgentCapabilities.sessionCapabilities.close") } diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/AgentSubagents.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/AgentSubagents.kt new file mode 100644 index 00000000..6e8cd4a3 --- /dev/null +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/AgentSubagents.kt @@ -0,0 +1,253 @@ +package com.agentclientprotocol.agent + +import com.agentclientprotocol.agent.internal.SessionWrapper +import com.agentclientprotocol.agent.internal.SubagentSessionWrapper +import com.agentclientprotocol.agent.internal.sessionWrapper +import com.agentclientprotocol.annotations.UnstableApi +import com.agentclientprotocol.common.ClientSessionOperations +import com.agentclientprotocol.model.SessionId +import com.agentclientprotocol.model.SessionUpdate +import com.agentclientprotocol.model.StateUpdate +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emptyFlow +import kotlin.coroutines.CoroutineContext + +/** + * **UNSTABLE** + * + * The subagent protocol is stable in v1, but this Kotlin API is unstable and may be removed or changed at any point. + * + * What the SDK gives an [AgentSubagentFactory] that builds a child: the child's own operations, bound to its id. + * + * The context belongs to the child, not to the factory call: it stays valid after the factory returns or throws, so + * work the factory launched can keep using it. + * + * [client] sends requests for the child's session and routes each update by the subagents rule: + * - a [SessionUpdate.SubagentUpdate] for this child goes on the parent's stream; + * - a [SessionUpdate.SubagentUpdate] for any other session is rejected with [IllegalArgumentException]; + * - every other update goes on the child's own stream. + * + * Until the child's announcement, a [SessionUpdate.SubagentUpdate] for this child, has been sent, every other + * operation of [client] fails with [IllegalStateException]. Once the child is dropped, because its factory failed or + * returned before announcing it, or removed (see [AgentSubagents]), every operation fails that way again. + * + * @property sessionId the id of the child being built, as passed to [AgentSubagents.announce] + * @property client the child's client operations + * @property subagents the child's own subagents, for announcing grandchildren + */ +@UnstableApi +public class AgentSubagentContext internal constructor( + public val sessionId: SessionId, + public val client: ClientSessionOperations, + public val subagents: AgentSubagents, +) + +/** + * **UNSTABLE** + * + * The subagent protocol is stable in v1, but this Kotlin API is unstable and may be removed or changed at any point. + * + * A subagent the app exposes to the client. Built by an [AgentSubagentFactory]. + * + * The SDK does not run the child's work. The work may be a coroutine in this process or a subroutine of a native + * agent the app relays: the session only reports what the child does through [events], and receives the client's + * cancellation through [cancel]. + */ +@UnstableApi +public interface AgentSubagentSession { + /** + * The child's live work after its announcement, as the subagents spec defines it. + * + * A [SessionUpdate.SubagentUpdate] for this child goes on the parent's stream, where it patches the child and + * carries its work state. Every other update goes on the child's own stream. The first item isn't special: the + * factory has already sent the announcement. + * + * The SDK collects this once, in the child's session context, so it should be cold (or hot with replay). It + * starts after the factory returns or, for a replayed child, after the root's `session/load` response has been + * accepted by the transport, so everything it sends is live, not history. It may be empty, for example for a child + * that only has history. + * + * The app reports the child's work state itself: `running` and `idle` as it observes work starting and stopping. + * When it knows that the work failed, or that it stopped after [cancel], it emits `idle` with the `error` or + * `cancelled` stop reason before the flow ends, and the SDK then sends nothing more. The SDK never reports an + * outcome on its own: if the flow completes or throws while the last state it emitted is active (`running`, + * `requires_action` or an unrecognized state), it reports [StateUpdate.Unknown], because the client can no longer + * observe the child. + * + * The SDK cancels the collection, and sends nothing for it, when the child is removed (see [AgentSubagents]) or + * the connection ends. A feed that ends doesn't stop the collections of the child's own subagents. + */ + public val events: Flow get() = emptyFlow() + + /** + * Called on `session/cancel` for this child while the current cancel grant is in effect. Report the outcome + * through [events]. The SDK does not stop the collection. + * + * A cancel that arrives with no grant in effect is ignored. One that arrives with a grant in effect while the + * child's [AgentSubagentFactory.createSubagent] still runs is held until the factory returns this session. Each + * held cancel is then delivered, outside the call to [AgentSubagents.announce], if a grant is still in effect and + * the child is still registered. It is dropped if the factory throws. + * + * A grant sent while the root replays is never in effect (see [AgentSubagents]): to enable cancel for a + * replayed child, send a fresh grant, for example through [events]. + * + * An exception this method throws is logged and ignored: `session/cancel` is a notification. + */ + public suspend fun cancel() {} +} + +/** + * **UNSTABLE** + * + * The subagent protocol is stable in v1, but this Kotlin API is unstable and may be removed or changed at any point. + * + * Builds a child for [AgentSubagents.announce]. Mirrors the client-side + * [com.agentclientprotocol.client.ClientOperationsFactory]. + */ +@UnstableApi +public fun interface AgentSubagentFactory { + /** + * Builds the child. The call runs in the child's session context, so `currentCoroutineContext().client` is the + * child's [AgentSubagentContext.client]. The SDK collects the returned session's events afterwards. + * + * The factory must send the child's announcement, a [SessionUpdate.SubagentUpdate] whose session id is + * [AgentSubagentContext.sessionId], through [context] before it returns. Otherwise [AgentSubagents.announce] drops + * the child and throws. The factory may suspend and start the child's work first: an app that needs something from + * the work before announcing waits for it here. The announcement needs only the session id, so a state that isn't + * known yet is left out and sent later as a patch. Everything sent through [context] before this returns goes out + * before [AgentSubagents.announce] returns. + * + * A cancel grant sent from here takes effect at once unless the root replays: a `session/cancel` for the child that + * arrives before this returns is held for the returned session, see [AgentSubagentSession.cancel]. + * + * A replay of a recorded child passes a factory of its own, see [AgentSession.replayHistory]. + */ + public suspend fun createSubagent(context: AgentSubagentContext): S +} + +/** + * **UNSTABLE** + * + * The subagent protocol is stable in v1, but this Kotlin API is unstable and may be removed or changed at any point. + * + * The subagents of one session, a root session or a subagent, for announcing its children to the client. An instance + * is bound to its session and stays valid for that session's lifetime, not only inside the call that obtained it. + * There is no update method: patches to a child are ordinary events of the child. + * + * ### Removal + * + * Every subagent belongs to a root session. The SDK removes every subagent below a root, at every depth, and calls no + * app code for them: + * - on `session/close`, after the root's [AgentSession.close] returns and before the response. Stopping their work + * and freeing their resources belongs to that `close`. If it throws, the root and its subagents stay registered; + * - when `session/load` or `session/resume` re-opens a root that is still open, once [AgentSupport.loadSession] or + * [AgentSupport.resumeSession] returns, before the replay and the response. The old [AgentSession] isn't closed + * and its turn isn't cancelled, so stopping the old subagents' work is up to the app. + * + * After the removal: + * - the subagent's id is free again, and `session/cancel` for it is ignored; + * - its event collection stops, and its client operations and [announce] fail, as each of them documents; [announce] + * of the closed root fails too; + * - none of its updates follows the close response, but a request it already had in flight, or the + * `$/cancel_request` the SDK sends when the removal cancels that call, may still reach the client after it. + * + * When the connection ends, the collections stop the same way. + * + * ### Replay + * + * During the root's `session/load`, every subagent announced below the root replays a recorded one. An update sent + * for them through [AgentSubagentContext.client] counts by when its send starts: + * - before [AgentSession.replayHistory] returns, it is history, as the subagents spec defines it: a cancel grant is + * never in effect, and a state doesn't count as active. The load response follows it; + * - later, until the transport has accepted the load response, `notify` suspends until then. The update follows the + * response and is live: a cancel grant in it takes effect. + * + * So a request batched with the `session/load` that sends such an update after the replay hangs, and the load with + * it: the batch's one response waits for both. + * + * If the load fails, including when its response can't be built or sent, every subagent announced during it is + * removed with the root, and a `notify` still waiting fails. Subagents announced at any other time are live. + * + * The returned session's [AgentSubagentSession.events] are live: their collection starts once the transport has + * accepted the load response, before [AgentSession.postInitialize], and their updates are fresh patches to the + * replayed child. A child that only has history returns empty events. + * + * To replay subagents, see [AgentSession.replayHistory]. + */ +@UnstableApi +public class AgentSubagents internal constructor(private val bound: SessionWrapper) { + /** + * Registers [sessionId] under [parent], calls [factory] with the child's context, then collects the returned + * session's events. Returns the session once [factory] has returned, after the child's announcement. Returning is + * the caller's ordering point: an update the parent sends afterwards, such as a `session_message` naming the + * child, follows the announcement. + * + * [parent] defaults to the session this object is bound to. It may name an announced descendant of that session + * that is still registered, for relays that learn about nested children from a flat event stream. + * + * The announcement is a [SessionUpdate.SubagentUpdate] whose session id is [sessionId]. [factory] must send it + * through [AgentSubagentContext.client] before it returns, and it must be the first thing sent for the child. + * While the root replays, the events are collected later, see [AgentSubagents]. + * + * ### Failure + * + * Before the announcement is sent, the child is unregistered, so its id is free again, and nothing more is sent: + * - if [factory] throws, or returns without having sent the announcement, this call throws + * [IllegalStateException]; + * - if the caller is cancelled, this call rethrows the [CancellationException]. + * + * After it is sent, the child stays registered and its events are never collected: + * - if [factory] throws, the SDK revokes the child's cancel grant and, if the factory left the work state active, + * reports [StateUpdate.Unknown], except while the root is replaying. This call rethrows the exception unchanged, + * except that a [CancellationException] while the caller is active surfaces as [IllegalStateException], so it + * doesn't tear down the caller's scope; + * - if the caller is cancelled, the SDK does the same, and this call rethrows the [CancellationException]. + * + * @throws IllegalArgumentException if [parent] is neither the bound session nor a registered, announced + * descendant of it, or if [sessionId] is already registered on the connection, as a root session or a subagent + * @throws IllegalStateException if the bound session's root is no longer registered (closed, replaced by a + * re-opening, or its load failed), if the bound session is a subagent that isn't announced yet, was dropped, or + * was removed with its root, if the child's announcement could not be sent, or when [factory] fails as described + * above + */ + public suspend fun announce( + sessionId: SessionId, + factory: AgentSubagentFactory, + parent: SessionId? = null, + ): S { + val parentWrapper = resolveParent(parent) + val child = SubagentSessionWrapper(bound.agent, bound.protocol, sessionId, parentWrapper) + bound.agent.registerSubagent(child) + return child.announce(factory) + } + + private fun resolveParent(parent: SessionId?): SessionWrapper { + // An unannounced child's children would put traffic on a stream the client doesn't know. + if (bound is SubagentSessionWrapper) bound.checkAnnounced() + if (parent == null || parent == bound.sessionId) return bound + + val candidate = bound.agent.subagentOrNull(parent) + require(candidate != null && candidate.isAnnounced && candidate.isDescendantOf(bound)) { + "Parent $parent is neither session ${bound.sessionId} nor an announced subagent below it" + } + return candidate + } +} + +/** + * **UNSTABLE** + * + * The subagent protocol is stable in v1, but this Kotlin API is unstable and may be removed or changed at any point. + * + * The subagents of the current session: a root session or a subagent. `null` when the client didn't advertise + * `subagents`: run the child without exposing it. + * + * Without the capability, a root session must not send the updates the subagents spec defines either: its client + * operations reject `session_message`, `session_message_chunk`, and tool calls with session content. + * + * @throws IllegalStateException if called outside a session context or from a NES session context + */ +@UnstableApi +public val CoroutineContext.subagents: AgentSubagents? + get() = sessionWrapper("Subagents").subagents diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/AgentSupport.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/AgentSupport.kt index c03da1b5..1c5bd129 100644 --- a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/AgentSupport.kt +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/AgentSupport.kt @@ -197,6 +197,8 @@ public interface AgentSupport { /** * Loads an existing session with the specified id and parameters. * + * If a session with this id is still open, the returned session replaces it, see [AgentSubagents]. + * * @param sessionId the id of the session to load * @param sessionParameters parameters for loading the session * @return an [AgentSession] instance for the loaded session @@ -212,6 +214,13 @@ public interface AgentSupport { * * Forks an existing session, creating a new session based on the existing session's context. * + * The fork starts with no subagents, and the source session keeps its own. If the fork copies the history of + * subagents, the app must give the copies new ids and remap them in the `senderSessionId` and + * `recipientSessionId` of messages and in `session` tool call content, including references to the source + * session, which become the fork's id: the SDK doesn't rewrite update contents. The copied subagents reach the + * client only when the fork is loaded later, announced from the fork's [AgentSession.replayHistory] through + * [AgentSubagents.announce]. + * * @param sessionId the id of the session to fork * @param sessionParameters parameters for the forked session * @return an [AgentSession] instance for the forked session @@ -228,6 +237,8 @@ public interface AgentSupport { * * Resumes an existing session without replaying message history. * + * If a session with this id is still open, the returned session replaces it, see [AgentSubagents]. + * * @param sessionId the id of the session to resume * @param sessionParameters parameters for resuming the session * @return an [AgentSession] instance for the resumed session diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/BaseSessionWrapper.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/BaseSessionWrapper.kt new file mode 100644 index 00000000..270156c4 --- /dev/null +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/BaseSessionWrapper.kt @@ -0,0 +1,37 @@ +package com.agentclientprotocol.agent.internal + +import com.agentclientprotocol.agent.Agent +import com.agentclientprotocol.protocol.Protocol +import kotlinx.coroutines.withContext +import kotlin.coroutines.AbstractCoroutineContextElement +import kotlin.coroutines.CoroutineContext + +internal open class BaseSessionWrapper( + val agent: Agent, + val protocol: Protocol +) { + internal suspend fun executeWithSession(block: suspend () -> T): T { + return withContext(this.asContextElement()) { + return@withContext block() + } + } +} + +internal class SessionWrapperContextElement(val sessionWrapper: BaseSessionWrapper) : AbstractCoroutineContextElement(Key) { + object Key : CoroutineContext.Key +} + +internal fun BaseSessionWrapper.asContextElement() = SessionWrapperContextElement(this) + +/** + * The root session or subagent of this context. + * + * @param feature what the caller needs from the session, for the error message + * @throws IllegalStateException outside a session context or in a NES session context + */ +internal fun CoroutineContext.sessionWrapper(feature: String): SessionWrapper { + val wrapper = this[SessionWrapperContextElement.Key]?.sessionWrapper + ?: error("No session found in context") + return wrapper as? SessionWrapper + ?: error("$feature are not available for NES sessions. Only chat sessions have access to ${feature.lowercase()}.") +} diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/NesSessionWrapper.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/NesSessionWrapper.kt new file mode 100644 index 00000000..cf5abac7 --- /dev/null +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/NesSessionWrapper.kt @@ -0,0 +1,12 @@ +package com.agentclientprotocol.agent.internal + +import com.agentclientprotocol.agent.Agent +import com.agentclientprotocol.agent.NesAgentSession +import com.agentclientprotocol.annotations.UnstableApi +import com.agentclientprotocol.protocol.Protocol + +internal class NesSessionWrapper @OptIn(UnstableApi::class) constructor( + agent: Agent, + val nesSession: NesAgentSession, + protocol: Protocol +) : BaseSessionWrapper(agent, protocol) diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/RemoteClientSessionOperations.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/RemoteClientSessionOperations.kt index 18a75cfa..7b08f7a9 100644 --- a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/RemoteClientSessionOperations.kt +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/RemoteClientSessionOperations.kt @@ -2,25 +2,60 @@ package com.agentclientprotocol.agent.internal import com.agentclientprotocol.annotations.UnstableApi import com.agentclientprotocol.common.ClientSessionOperations +import com.agentclientprotocol.common.SessionEvent import com.agentclientprotocol.model.* +import com.agentclientprotocol.protocol.Protocol import com.agentclientprotocol.protocol.RpcMethodsOperations import com.agentclientprotocol.protocol.invoke import kotlinx.serialization.json.JsonElement -internal class RemoteClientSessionOperations(private val rpc: RpcMethodsOperations, private val sessionId: SessionId, private val clientCapabilities: ClientCapabilities) : ClientSessionOperations { +/** + * The client operations of one session, sent to the client for [sessionId]. Root sessions use it as is, and + * [SubagentClientOperations] adds a subagent's gating and routing. + */ +internal open class RemoteClientSessionOperations( + protected val rpc: RpcMethodsOperations, + protected val sessionId: SessionId, + private val clientCapabilities: ClientCapabilities, +) : ClientSessionOperations { + /** + * Throws if nothing may be sent for this session yet. Every operation but [notify] calls it. + */ + protected open fun checkCanSend() {} + override suspend fun requestPermissions( toolCall: SessionUpdate.ToolCallUpdate, permissions: List, _meta: JsonElement?, ): RequestPermissionResponse { + checkCanSend() return AcpMethod.ClientMethods.V1.SessionRequestPermission(rpc, RequestPermissionRequest(sessionId, toolCall, permissions, _meta)) } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { - return AcpMethod.ClientMethods.V1.SessionUpdate(rpc, SessionNotification(sessionId, notification, _meta)) + /** + * Sends the update of [event] for this root session. Every root path sends through here, the prompt flow and the + * replay too, so a root's subagents rules are checked once: + * - a [SessionUpdate.SubagentUpdate] is rejected, so the SDK sees every announcement and grant; + * - without the `subagents` client capability, the updates that need it are rejected, as ACP requires + * (https://agentclientprotocol.com/protocol/v1/subagents#checking-support). + * + * @throws IllegalArgumentException for a [SessionUpdate.SubagentUpdate] + * @throws IllegalStateException for an update that needs the missing `subagents` capability, or for + * [SessionEvent.Opened], which only the client runtime delivers + */ + @OptIn(UnstableApi::class) + override suspend fun notify(event: SessionEvent) { + val (notification, _meta) = event.requireUpdate() + if (notification is SessionUpdate.SubagentUpdate) { + throw IllegalArgumentException( + "SubagentUpdate for ${notification.sessionId} cannot be sent through the client operations of " + + "session $sessionId: announce subagents through subagents.announce" + ) + } + if (clientCapabilities.subagents == null && notification.needsSubagentsCapability()) { + error("Client does not support subagents capability") + } + AcpMethod.ClientMethods.V1.SessionUpdate(rpc, SessionNotification(sessionId, notification, _meta)) } override suspend fun fsReadTextFile( @@ -29,6 +64,7 @@ internal class RemoteClientSessionOperations(private val rpc: RpcMethodsOperatio limit: UInt?, _meta: JsonElement?, ): ReadTextFileResponse { + checkCanSend() if (clientCapabilities.fs?.readTextFile != true) error("Client does not support fs.readTextFile capability") return AcpMethod.ClientMethods.V1.FsReadTextFile(rpc, ReadTextFileRequest(sessionId, path, line, limit, _meta)) } @@ -38,6 +74,7 @@ internal class RemoteClientSessionOperations(private val rpc: RpcMethodsOperatio content: String, _meta: JsonElement?, ): WriteTextFileResponse { + checkCanSend() if (clientCapabilities.fs?.writeTextFile != true) error("Client does not support fs.writeTextFile capability") return AcpMethod.ClientMethods.V1.FsWriteTextFile(rpc, WriteTextFileRequest(sessionId, path, content, _meta)) } @@ -50,6 +87,7 @@ internal class RemoteClientSessionOperations(private val rpc: RpcMethodsOperatio outputByteLimit: ULong?, _meta: JsonElement?, ): CreateTerminalResponse { + checkCanSend() if (!clientCapabilities.terminal) error("Client does not support terminal capability") return AcpMethod.ClientMethods.V1.TerminalCreate(rpc, CreateTerminalRequest(sessionId, command, args, cwd, env, outputByteLimit, _meta)) } @@ -58,6 +96,7 @@ internal class RemoteClientSessionOperations(private val rpc: RpcMethodsOperatio terminalId: String, _meta: JsonElement?, ): TerminalOutputResponse { + checkCanSend() if (!clientCapabilities.terminal) error("Client does not support terminal capability") return AcpMethod.ClientMethods.V1.TerminalOutput(rpc, TerminalOutputRequest(sessionId, terminalId, _meta)) } @@ -66,6 +105,7 @@ internal class RemoteClientSessionOperations(private val rpc: RpcMethodsOperatio terminalId: String, _meta: JsonElement?, ): ReleaseTerminalResponse { + checkCanSend() if (!clientCapabilities.terminal) error("Client does not support terminal capability") return AcpMethod.ClientMethods.V1.TerminalRelease(rpc, ReleaseTerminalRequest(sessionId, terminalId, _meta)) } @@ -74,6 +114,7 @@ internal class RemoteClientSessionOperations(private val rpc: RpcMethodsOperatio terminalId: String, _meta: JsonElement?, ): WaitForTerminalExitResponse { + checkCanSend() if (!clientCapabilities.terminal) error("Client does not support terminal capability") return AcpMethod.ClientMethods.V1.TerminalWaitForExit(rpc, WaitForTerminalExitRequest(sessionId, terminalId, _meta)) } @@ -82,6 +123,7 @@ internal class RemoteClientSessionOperations(private val rpc: RpcMethodsOperatio terminalId: String, _meta: JsonElement?, ): KillTerminalCommandResponse { + checkCanSend() if (!clientCapabilities.terminal) error("Client does not support terminal capability") return AcpMethod.ClientMethods.V1.TerminalKill(rpc, KillTerminalCommandRequest(sessionId, terminalId, _meta)) } @@ -90,6 +132,7 @@ internal class RemoteClientSessionOperations(private val rpc: RpcMethodsOperatio override suspend fun createElicitation( request: CreateElicitationRequest ): CreateElicitationResponse { + checkCanSend() val elicitation = clientCapabilities.elicitation ?: error("Client does not support elicitation capability") when (request.mode) { @@ -125,6 +168,7 @@ internal class RemoteClientSessionOperations(private val rpc: RpcMethodsOperatio override suspend fun completeElicitation( notification: CompleteElicitationNotification ) { + checkCanSend() AcpMethod.ClientMethods.V1.ElicitationComplete(rpc, notification) } @@ -138,4 +182,55 @@ internal class RemoteClientSessionOperations(private val rpc: RpcMethodsOperatio ) { completeElicitation(CompleteElicitationNotification(elicitationId, _meta)) } -} \ No newline at end of file +} + +/** + * The client operations of [subagent], allowed only while it is announced and registered, with updates routed by the + * subagents rule. [subagent] does the sending. + */ +@OptIn(UnstableApi::class) +internal class SubagentClientOperations( + protocol: Protocol, + sessionId: SessionId, + clientCapabilities: ClientCapabilities, + private val subagent: SubagentSessionWrapper, +) : RemoteClientSessionOperations(protocol, sessionId, clientCapabilities) { + override fun checkCanSend() = subagent.checkAnnounced() + + override suspend fun notify(event: SessionEvent) { + val (notification, _meta) = event.requireUpdate() + if (notification is SessionUpdate.SubagentUpdate) { + require(notification.sessionId == sessionId) { + "SubagentUpdate for ${notification.sessionId} cannot be sent through the client operations of " + + "subagent $sessionId: announce nested subagents through subagents.announce" + } + subagent.sendSubagentUpdate(notification, _meta) + } else { + subagent.sendSessionUpdate(notification, _meta) + } + } +} + +/** + * Returns the update of an event that agent code sends. [SessionEvent.Opened] has an internal constructor, so only an + * SDK bug could pass one here. + * + * @throws IllegalStateException for [SessionEvent.Opened] + */ +internal fun SessionEvent.requireUpdate(): Pair = when (this) { + is SessionEvent.Update -> update to _meta + is SessionEvent.Opened -> throw IllegalStateException("SessionEvent.Opened is delivered only by the client runtime") +} + +/** + * Whether the v1 subagents pages define this update, so an agent may send it only with the `subagents` client + * capability (`docs/protocol/v1/subagents.mdx`, "Checking support"). That includes tool call content that references a + * session (`docs/protocol/v1/tool-calls.mdx`, "Sessions"). + */ +@OptIn(UnstableApi::class) +private fun SessionUpdate.needsSubagentsCapability(): Boolean = when (this) { + is SessionUpdate.SessionMessage, is SessionUpdate.SessionMessageChunk -> true + is SessionUpdate.ToolCall -> content.any { it is ToolCallContent.Session } + is SessionUpdate.ToolCallUpdate -> content.orEmpty().any { it is ToolCallContent.Session } + else -> false +} diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/ReplayWindow.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/ReplayWindow.kt new file mode 100644 index 00000000..f83e4a00 --- /dev/null +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/ReplayWindow.kt @@ -0,0 +1,95 @@ +package com.agentclientprotocol.agent.internal + +import kotlinx.collections.immutable.PersistentList +import kotlinx.collections.immutable.persistentListOf +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.getAndUpdate +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.flow.updateAndGet + +/** + * The replay window of a root opened by `session/load`: what the root's subtree sends while it is open precedes the + * load response, so it is history. While the load is being answered, a new send waits for the window to close and is + * then live. The window closes once the transport has accepted the response, or when the load fails. + */ +internal class ReplayWindow(open: Boolean) { + /** + * The state of an open window. + * + * @property historySends the sends that count as history and may not have reached the transport yet + * @property closing whether the load is about to be answered, so a new send can no longer count as history + * @property deferredStarts what [runAfterClose] deferred; [close] runs each once + */ + private data class Open( + val historySends: Int = 0, + val closing: Boolean = false, + val deferredStarts: PersistentList<() -> Unit> = persistentListOf(), + ) + + /** + * The open window, or `null` once it is closed. + */ + private val state = MutableStateFlow(if (open) Open() else null) + + /** + * Whether the window is open, or closing. + */ + val isOpen: Boolean get() = state.value != null + + /** + * Runs [start] now, or when the window closes if it is still open, so what [start] sends follows the load response. + */ + fun runAfterClose(start: () -> Unit) { + // A closed window stays null, so `start` runs now; an open one keeps it for close(). + val window = state.updateAndGet { open -> open?.copy(deferredStarts = open.deferredStarts.add(start)) } + if (window == null) start() + } + + /** + * Runs [send], which sends an update of the root's subtree, so that the update reaches the transport on the side of + * the load response it counts for. [send] gets whether the update is live: `false` while the window is open, when + * the response waits for it. + */ + suspend fun send(send: (isLive: Boolean) -> T): T { + val isHistory = startSend() + try { + return send(!isHistory) + } finally { + if (isHistory) state.update { it?.copy(historySends = it.historySends - 1) } + } + } + + /** + * Counts a send in the window, waiting first while it is closing. + * + * @return `true` if the send is history, because the window is open and the send is counted in it; `false` if the + * window is closed, so the send is live + */ + private suspend fun startSend(): Boolean { + while (true) { + val window = state.value ?: return false + if (window.closing) { + state.first { it == null } + } else if (state.compareAndSet(window, window.copy(historySends = window.historySends + 1))) { + return true + } + } + } + + /** + * Marks the load as about to be answered and waits until every history send has reached the transport, so all of + * them precede the response. + */ + suspend fun awaitHistorySends() { + state.update { it?.copy(closing = true) } + state.first { it == null || it.historySends == 0 } + } + + /** + * Closes the window and runs the starts deferred until then. + */ + fun close() { + state.getAndUpdate { null }?.deferredStarts?.forEach { it() } + } +} diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/RootSessionWrapper.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/RootSessionWrapper.kt new file mode 100644 index 00000000..7019d53c --- /dev/null +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/RootSessionWrapper.kt @@ -0,0 +1,188 @@ +package com.agentclientprotocol.agent.internal + +import com.agentclientprotocol.agent.Agent +import com.agentclientprotocol.agent.AgentSession +import com.agentclientprotocol.agent.AgentSubagents +import com.agentclientprotocol.annotations.UnstableApi +import com.agentclientprotocol.common.ClientSessionOperations +import com.agentclientprotocol.common.Event +import com.agentclientprotocol.common.notify +import com.agentclientprotocol.model.* +import com.agentclientprotocol.protocol.Protocol +import io.github.oshai.kotlinlogging.KotlinLogging +import kotlinx.atomicfu.atomic +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancel +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.getAndUpdate +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.serialization.json.JsonElement + +private val logger = KotlinLogging.logger {} + +/** + * A root session: runs its turns one at a time (see [AgentSession.prompt]) and owns the replay window and the subtree + * scope of its subagents. + * + * @param replaying whether the session is being opened by `session/load`, which opens its [replayWindow] + */ +internal class RootSessionWrapper( + agent: Agent, + val agentSession: AgentSession, + override val clientOperations: ClientSessionOperations, + protocol: Protocol, + subagentsSupported: Boolean, + replaying: Boolean = false, +) : SessionWrapper(agent, protocol) { + override val sessionId: SessionId get() = agentSession.sessionId + override val root: RootSessionWrapper get() = this + + @OptIn(UnstableApi::class) + override val subagents: AgentSubagents? = if (subagentsSupported) AgentSubagents(this) else null + + /** + * The scope where the events of this root's subagents are collected. Lazy, so a session without subagents keeps no + * job on the connection. + */ + val subtreeScope: CoroutineScope by lazy { protocol.newConnectionScope("Subagents of session $sessionId") } + + /** + * The replay window of `session/load`, closed at once for a session opened otherwise. + */ + val replayWindow: ReplayWindow = ReplayWindow(open = replaying) + + /** + * Cancels the collections of this root's subtree. The caller removes the subagents themselves. + */ + fun cancelSubtreeScope() { + subtreeScope.cancel() + } + + private val _activePrompt = atomic(null) + + @OptIn(UnstableApi::class) + suspend fun prompt(content: List, _meta: JsonElement? = null): PromptResponse { + var response: PromptResponse? = null + var failure: Throwable? = null + return coroutineScope { + val promptJob = launch(start = CoroutineStart.LAZY) { + /* + * Keep a failure inside the turn's job, so a failed turn still waits for running cancels and a + * cancel can still decide its answer. + */ + try { + agentSession.prompt(content, _meta).collect { event -> + when (event) { + is Event.PromptResponseEvent -> { + if (response != null) { + logger.error { "Received repeated prompt response: ${event.response} (previous: $response). The last is used" } + } + response = event.response + } + + is Event.SessionUpdateEvent -> { + clientOperations.notify(event.update, event._meta) + } + } + } + } catch (e: CancellationException) { + /* + * FIXME: a CancellationException that the app's own flow throws, such as an uncaught + * `withTimeout`, is treated as a client cancel: rethrowing it cancels `promptJob`, so the turn + * answers `cancelled` and the real failure is lost. + * + * See https://github.com/agentclientprotocol/kotlin-sdk/issues/166. + */ + throw e + } catch (e: Throwable) { + failure = e + } + } + + val promptSession = PromptSession(promptJob) + if (!_activePrompt.compareAndSet(null, promptSession)) { + error("There is already active prompt execution") + } + try { + promptJob.join() + /* + * A cancelled turn answers only after the session's cancel() returns: the response must follow + * every aborted operation and every update, including those sent from cancel(). + * + * The session's cancel() may stop the turn cooperatively, so its flow ends normally before the + * SDK cancels the job. The client still cancelled the turn and must get the `cancelled` reason. + * + * The wait goes first, so it runs even for a cancelled job. + */ + val isCancelled = promptSession.awaitCancels() || promptJob.isCancelled + failure?.let { e -> + if (!isCancelled) throw e + logger.debug(e) { "Prompt turn failed after a cancel; answering as cancelled" } + } + response ?: PromptResponse( + stopReason = if (isCancelled) StopReason.CANCELLED else StopReason.END_TURN + ) + } finally { + // Only the turn frees its slot, so the next prompt can start only after this one has answered. + _activePrompt.value = null + } + } + } + + suspend fun cancel() { + /* + * Take the turn to cancel before notifying the session: the session's cancel() may suspend, and a turn + * that has already answered may be followed by the next one meanwhile, which this cancel must not touch. + */ + val promptToCancel = _activePrompt.value?.takeIf { it.startCancel() } + try { + agentSession.cancel() + + if (promptToCancel != null) { + logger.trace { "Cancelling prompt" } + // This cancels the turn's requests in flight too, and each of them sends `$/cancel_request`. + promptToCancel.promptJob.cancel() + } + } finally { + promptToCancel?.finishCancel() + } + } +} + +private class PromptSession(val promptJob: Job) { + /** + * The cancels of this turn: how many still run, whether any started, and whether the turn is answering. + * Once it answers, nothing changes. + */ + private data class Cancels(val running: Int = 0, val requested: Boolean = false, val answering: Boolean = false) + + private val cancels = MutableStateFlow(Cancels()) + + /** + * Registers a cancel for this turn. Returns `false` if the turn is already answering. + */ + fun startCancel(): Boolean = + !cancels.getAndUpdate { if (it.answering) it else it.copy(running = it.running + 1, requested = true) }.answering + + fun finishCancel() { + cancels.update { it.copy(running = it.running - 1) } + } + + /** + * Suspends until no cancel is running for this turn, marks the turn as answering, and returns whether a + * cancel targeted it. + */ + suspend fun awaitCancels(): Boolean { + while (true) { + val current = cancels.first { it.running == 0 } + // Compares by equality, which is enough: equal states are interchangeable. + if (cancels.compareAndSet(current, current.copy(answering = true))) return current.requested + } + } +} diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/SessionWrapper.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/SessionWrapper.kt new file mode 100644 index 00000000..61abd869 --- /dev/null +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/SessionWrapper.kt @@ -0,0 +1,30 @@ +package com.agentclientprotocol.agent.internal + +import com.agentclientprotocol.agent.Agent +import com.agentclientprotocol.agent.AgentSubagents +import com.agentclientprotocol.annotations.UnstableApi +import com.agentclientprotocol.common.ClientSessionOperations +import com.agentclientprotocol.model.* +import com.agentclientprotocol.protocol.Protocol + +/** + * A session with client operations: a root session or a subagent. NES sessions have none. + */ +internal abstract class SessionWrapper( + agent: Agent, + protocol: Protocol +) : BaseSessionWrapper(agent, protocol) { + abstract val sessionId: SessionId + abstract val clientOperations: ClientSessionOperations + + /** + * The root session at the top of this session's tree: itself for a root session. + */ + abstract val root: RootSessionWrapper + + /** + * This session's subagents, or `null` when the client did not advertise `subagents`. + */ + @OptIn(UnstableApi::class) + abstract val subagents: AgentSubagents? +} diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/SubagentSessionWrapper.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/SubagentSessionWrapper.kt new file mode 100644 index 00000000..e838830d --- /dev/null +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/internal/SubagentSessionWrapper.kt @@ -0,0 +1,366 @@ +@file:OptIn(UnstableApi::class) + +package com.agentclientprotocol.agent.internal + +import com.agentclientprotocol.agent.Agent +import com.agentclientprotocol.agent.AgentSubagentContext +import com.agentclientprotocol.agent.AgentSubagentFactory +import com.agentclientprotocol.agent.AgentSubagentSession +import com.agentclientprotocol.agent.AgentSubagents +import com.agentclientprotocol.annotations.UnstableApi +import com.agentclientprotocol.common.notify +import com.agentclientprotocol.model.AcpMethod +import com.agentclientprotocol.model.MaybeUndefined +import com.agentclientprotocol.model.MaybeUndefined.Value +import com.agentclientprotocol.model.SessionId +import com.agentclientprotocol.model.SessionNotification +import com.agentclientprotocol.model.SessionUpdate +import com.agentclientprotocol.model.SessionUpdate.SubagentUpdate +import com.agentclientprotocol.model.StateUpdate +import com.agentclientprotocol.model.StateUpdate.Unknown +import com.agentclientprotocol.model.update +import com.agentclientprotocol.protocol.Protocol +import com.agentclientprotocol.protocol.invoke +import io.github.oshai.kotlinlogging.KotlinLogging +import kotlinx.atomicfu.atomic +import kotlinx.atomicfu.locks.SynchronizedObject +import kotlinx.atomicfu.locks.synchronized +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineName +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.serialization.json.JsonElement + +private val logger = KotlinLogging.logger {} + +/** + * A subagent registered on the connection: its client operations, its own [AgentSubagents], and its announcement + * phase, cancel grant and work state as the SDK tracks them. + * + * @property parent the session whose stream carries this child's [SessionUpdate.SubagentUpdate]s + */ +internal class SubagentSessionWrapper( + agent: Agent, + protocol: Protocol, + override val sessionId: SessionId, + val parent: SessionWrapper, +) : SessionWrapper(agent, protocol) { + /** + * [DROPPED] is a child that was never announced, [REMOVED] an announced one that subtree cleanup removed. + */ + private enum class Phase { PENDING, ANNOUNCED, DROPPED, REMOVED } + + /** + * What the SDK tracks of this child's own [SessionUpdate.SubagentUpdate]s. + * + * @property phase [Phase.ANNOUNCED] only once the announcement was sent, so an operation that sees it can't + * overtake the announcement + * @property cancelGranted whether cancel is granted, from the live updates sent for this child on any path + * @property factoryState the last live `state` sent while the factory ran, for a factory that throws after the + * announcement + */ + private data class State( + val phase: Phase = Phase.PENDING, + val cancelGranted: Boolean = false, + val factoryRunning: Boolean = true, + val factoryState: StateUpdate? = null, + ) + + /** + * Makes each own [SessionUpdate.SubagentUpdate] send atomic with its tracking in [state], and orders every send + * against dropping or removing the child. Every write of [state] holds it, and it is held only around + * non-suspending sends. + */ + private val lock = SynchronizedObject() + + private val state = atomic(State()) + + /** + * The session the factory returned, or `null` if it threw or the child was removed first. Completed after the + * write that ends the factory's run or removes the child. + */ + private val factorySession = CompletableDeferred() + + override val root: RootSessionWrapper = parent.root + + override val clientOperations: SubagentClientOperations = + SubagentClientOperations(protocol, sessionId, agent.getClientInfoOrThrow().capabilities, this) + + override val subagents: AgentSubagents = AgentSubagents(this) + + private val context = AgentSubagentContext(sessionId, clientOperations, subagents) + + val isAnnounced: Boolean get() = state.value.phase == Phase.ANNOUNCED + + /** + * Whether `session/cancel` for this child is currently granted to the client. + */ + val isCancelGranted: Boolean get() = state.value.cancelGranted + + /** + * The session the factory returned, or `null` while the factory runs, after it threw, or if the child was removed + * first. + */ + @OptIn(ExperimentalCoroutinesApi::class) + val session: AgentSubagentSession? + get() = if (factorySession.isCompleted) factorySession.getCompleted() else null + + /** + * Throws [IllegalStateException] unless the announcement has been sent and the child is still registered. + */ + fun checkAnnounced() { + val phase = state.value.phase + if (phase == Phase.PENDING) error("Subagent $sessionId is not announced yet: send its SubagentUpdate first") + checkRegistered(phase) + } + + private fun checkRegistered(phase: Phase) { + when (phase) { + Phase.PENDING, Phase.ANNOUNCED -> {} + Phase.DROPPED -> error("Subagent $sessionId is not registered") + Phase.REMOVED -> error("Subagent $sessionId is not registered: its root session ${root.sessionId} is closed") + } + } + + fun isDescendantOf(ancestor: SessionWrapper): Boolean { + var current: SessionWrapper = parent + while (current !== ancestor) { + current = (current as? SubagentSessionWrapper)?.parent ?: return false + } + return true + } + + /** + * Runs the factory, which must send the announcement, then starts the collection. A replayed child's collection + * waits until the transport has accepted the root's load response. + */ + suspend fun announce(factory: AgentSubagentFactory): S { + val session = try { + executeWithSession { factory.createSubagent(context) } + } catch (e: Throwable) { + // Only the caller's own cancellation passes as is: the app's would tear down the caller's scope. + val callerCancelled = e is CancellationException && !currentCoroutineContext().isActive + // A held cancel has no session to reach. + val announced = !endFactory(null) + if (announced) reportFactoryFailure() + throw when { + callerCancelled -> e + announced && e !is CancellationException -> e + announced -> IllegalStateException("Subagent $sessionId is announced, but its factory failed", e) + else -> IllegalStateException("Subagent $sessionId is not announced: its factory failed", e) + } + } + + if (endFactory(session)) { + throw IllegalStateException( + "Subagent $sessionId is not announced: its factory must send the announcement before returning" + ) + } + + root.replayWindow.runAfterClose { startCollection(session) } + return session + } + + /** + * Ends the factory's run with [session], or `null` if it threw, and unregisters this child unless it was announced, + * so its operations fail. Returns whether it is dropped. + */ + private fun endFactory(session: AgentSubagentSession?): Boolean { + val ended = synchronized(lock) { + val current = state.value + val phase = if (current.phase == Phase.PENDING) Phase.DROPPED else current.phase + current.copy(phase = phase, factoryRunning = false).also { state.value = it } + } + factorySession.complete(session) + + val dropped = ended.phase == Phase.DROPPED + if (dropped) agent.unregisterSubagent(this) + return dropped + } + + /** + * Makes every operation fail from now on, once the child has left the session table. A pending child can no longer + * be announced, so its `announce` fails. + */ + fun remove() { + synchronized(lock) { + val current = state.value + when (current.phase) { + Phase.PENDING -> state.value = current.copy(phase = Phase.DROPPED) + Phase.ANNOUNCED -> state.value = current.copy(phase = Phase.REMOVED) + Phase.DROPPED, Phase.REMOVED -> {} + } + } + // Ends the cancels held for a factory that may never return. + factorySession.complete(null) + } + + /** + * The factory threw after the announcement, so there is no session to cancel or collect: revokes the grant, since + * the client couldn't learn otherwise that its cancel is ignored, and reports `unknown` if the factory left the + * child active. It doesn't suspend, so it runs for a cancelled caller too. + */ + private fun reportFactoryFailure() { + // Grants and states sent in the replay window are history, so there is nothing to correct. + if (root.replayWindow.isOpen) return + runCatching { sendFactoryFailureCorrection() } + .onFailure { logger.debug(it) { "Could not correct subagent $sessionId after its factory failed" } } + } + + private fun startCollection(session: AgentSubagentSession) { + root.subtreeScope.launch(asContextElement() + CoroutineName("Subagent $sessionId events")) { + var eventsState: StateUpdate? = null + val failure = try { + session.events.collect { update -> + clientOperations.notify(update) + if (update is SessionUpdate.SubagentUpdate) eventsState = update.state.update(eventsState) + } + null + } catch (e: CancellationException) { + // A cancellation from the app's flow while this job is active is a feed failure. + if (currentCoroutineContext().isActive) e else throw e + } catch (e: Throwable) { + e + } + onFeedEnd(failure, eventsState) + } + } + + /** + * Reports `unknown` if the events, which completed or failed with [failure], ended while [eventsState], the last + * state they sent, is active, since the client can no longer observe the child. State sent through the client + * operations isn't seen there. The child stays registered. + */ + private suspend fun onFeedEnd(failure: Throwable?, eventsState: StateUpdate?) { + if (failure != null) { + logger.warn(failure) { "Events of subagent $sessionId failed" } + } else { + logger.debug { "Events of subagent $sessionId completed" } + } + + // A collection that the SDK cancelled owes nothing. + if (!currentCoroutineContext().isActive || !eventsState.isActiveState()) return + runCatching { + val update = SubagentUpdate(sessionId, state = Value(Unknown())) + // A collection starts only once the replay window has closed. + synchronized(lock) { sendSubagentUpdateLocked(update, null, isLive = true) } + }.onFailure { logger.debug(it) { "Could not report subagent $sessionId unknown after its events ended" } } + } + + /** + * Serves `session/cancel` for this child: calls [AgentSubagentSession.cancel] while the grant is in effect, waiting + * for the factory's session if the factory still runs, and otherwise ignores it, because a notification can't get + * an error. + */ + suspend fun cancel() { + // Checked on arrival, before anything suspends, so a cancel without a grant is never held. + if (!isCancelGranted) return ignoreCancel("cancel is not granted") + if (!factorySession.isCompleted) { + logger.info { "Holding session/cancel for subagent $sessionId until its factory returns" } + } + + val session = factorySession.await() ?: return ignoreCancel("it has no session") + // A held cancel may find the grant revoked or the child gone. + val current = state.value + if (!current.cancelGranted || current.phase != Phase.ANNOUNCED) { + return ignoreCancel("cancel is no longer granted or it is removed") + } + callCancel(session) + } + + private fun ignoreCancel(reason: String) { + logger.info { "Ignoring session/cancel for subagent $sessionId: $reason" } + } + + private suspend fun callCancel(session: AgentSubagentSession) { + try { + executeWithSession { session.cancel() } + } catch (e: Throwable) { + // Only the caller's own cancellation passes: a notification has no response to fail. + if (e is CancellationException && !currentCoroutineContext().isActive) throw e + logger.warn(e) { "Cancel of subagent $sessionId failed" } + } + } + + /** + * Sends an update of this child's session, such as a message or a tool call, on the child's stream. Its own + * [SessionUpdate.SubagentUpdate] goes through [sendSubagentUpdate] instead. + */ + suspend fun sendSessionUpdate(notification: SessionUpdate, _meta: JsonElement?) { + // The SDK tracks nothing of it, but the client tells history from live by the side of the load response. + root.replayWindow.send { + // Under the lock, so nothing is sent once the child was removed. + synchronized(lock) { + checkAnnounced() + AcpMethod.ClientMethods.V1.SessionUpdate(protocol, SessionNotification(sessionId, notification, _meta)) + } + } + } + + /** + * Sends this child's own [SessionUpdate.SubagentUpdate], on the parent's stream: it announces the child, or updates + * its state and cancel grant. + */ + suspend fun sendSubagentUpdate(update: SessionUpdate.SubagentUpdate, _meta: JsonElement?) { + root.replayWindow.send { isLive -> synchronized(lock) { sendSubagentUpdateLocked(update, _meta, isLive) } } + } + + private fun sendFactoryFailureCorrection() { + synchronized(lock) { + val current = state.value + val revokeGrant = current.cancelGranted + val reportUnknown = current.factoryState.isActiveState() + if (!revokeGrant && !reportUnknown) return + + val correction = SessionUpdate.SubagentUpdate( + sessionId = sessionId, + capabilities = if (revokeGrant) MaybeUndefined.Null else MaybeUndefined.Undefined, + state = if (reportUnknown) MaybeUndefined.Value(StateUpdate.Unknown()) else MaybeUndefined.Undefined, + ) + // Only after the replay window closed, which reportFactoryFailure checked. + sendSubagentUpdateLocked(correction, null, isLive = true) + } + } + + /** + * Sends a [SessionUpdate.SubagentUpdate] for this child on the parent's stream, with [lock] held. Unless [isLive], + * it is history: it neither grants cancel nor counts as the factory's last state. + */ + private fun sendSubagentUpdateLocked(update: SessionUpdate.SubagentUpdate, _meta: JsonElement?, isLive: Boolean) { + val current = state.value + checkRegistered(current.phase) + + val capabilities = if (isLive) update.capabilities else MaybeUndefined.Undefined + val granted = when (capabilities) { + MaybeUndefined.Undefined -> current.cancelGranted + MaybeUndefined.Null -> false + is MaybeUndefined.Value -> capabilities.value.cancel != null + } + /* + * The grant is published before the send, so a `session/cancel` right after it is routed, and restored if the + * send fails. A reader may have seen the new grant meanwhile. + */ + state.value = current.copy(cancelGranted = granted) + try { + AcpMethod.ClientMethods.V1.SessionUpdate(protocol, SessionNotification(parent.sessionId, update, _meta)) + } catch (e: Throwable) { + state.value = current + throw e + } + + val factoryState = + if (isLive && current.factoryRunning) update.state.update(current.factoryState) else current.factoryState + state.value = current.copy(phase = Phase.ANNOUNCED, cancelGranted = granted, factoryState = factoryState) + } +} + +/** + * Whether this last known state shows the child working. An unrecognized state counts as active. + */ +private fun StateUpdate?.isActiveState(): Boolean = when (this) { + is StateUpdate.Running, is StateUpdate.RequiresAction, is StateUpdate.Other -> true + is StateUpdate.Idle, is StateUpdate.Unknown, null -> false +} diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/v2/Agent.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/v2/Agent.kt index 90d460d2..93d6a516 100644 --- a/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/v2/Agent.kt +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/agent/v2/Agent.kt @@ -228,6 +228,40 @@ public class Agent( ends it — and `cancelled` is honest, because the turn really was cancelled, just locally rather than on the client's asking. */ + /* + FIXME: this branch assumes every CancellationException is a local cancellation, but the + app's own flow can throw one too. Example: an uncaught `withTimeout` inside + `AgentSession.prompt()`, with no `session/cancel` from the client. The client then gets + `idle(cancelled)` for a turn nobody cancelled, and the real failure isn't reported. The + same happens before insertion: the `completeExceptionally` path above rethrows the CE, the + prompt handler's `insertedMessageId.await()` throws it, and `Protocol` answers `-32800 + Cancelled` (`toJsonRpcError` in `protocol/Exceptions.kt`) to a prompt the client never + cancelled. #131 fixed only the SDK-made case: a peer's `-32800` response is now + `AcpRequestCancelledException`, handled above. + + Suggested fix: classify a CE by two facts, whether the turn's job is still active and + whether a `session/cancel` arrived during this turn. + - Job cancelled (`close()`, `cancelPendingIncomingRequest(s)`, `turn.cancel()` from the + prompt handler's `afterResponse`/`onCompletion`): keep this branch as it is. + - Job active and a cancel was requested: still `idle(cancelled)`. The app aborted its + work in response to the client's cancel, and aborted calls often throw. + - Job active and no cancel was requested: treat it like the `else` branch below, an + error log and `idle(stopReason = null)`, and don't rethrow. + A job-state check alone is not enough, and it would regress the second case. + `cancel()` here only calls `session.cancel()` and never cancels the turn's job, so after + a real client cancel the job is still active. The turn needs a cancel-requested flag, + like the `requested` flag of v1's `PromptSession` in `agent/internal/RootSessionWrapper.kt`, + set by `cancel()` for the turn registered when the cancel arrives. + + Apply the same split before insertion: answer `-32800` only after a cancel, otherwise + fail the receipt with a non-cancellation exception so it becomes `-32603`. Keep the SDK's + own `CancellationException("Prompt cancelled before user message insertion")` thrown in + `collect` above out of the "app CE" case: it runs in an active job too, so it needs its + own exception type or an explicit branch. + + Cover it with lifecycle tests for each case above, using a client cancel as the control. + The v1 counterpart is the FIXME in `RootSessionWrapper.prompt` in `agent/internal/RootSessionWrapper.kt`. + */ is CancellationException -> { logger.debug(t) { "Reporting a locally cancelled turn for session ${session.sessionId}" } reportIdle(StopReason.Cancelled) diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/client/ClientSessionHolder.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/client/ClientSessionHolder.kt index bdf37f33..5ef9eea6 100644 --- a/acp/src/commonMain/kotlin/com/agentclientprotocol/client/ClientSessionHolder.kt +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/client/ClientSessionHolder.kt @@ -2,6 +2,7 @@ package com.agentclientprotocol.client import com.agentclientprotocol.annotations.UnstableApi import com.agentclientprotocol.common.ClientSessionOperations +import com.agentclientprotocol.common.notify import com.agentclientprotocol.model.SessionUpdate import kotlinx.atomicfu.atomic import kotlinx.coroutines.CompletableDeferred diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/client/ClientSessionImpl.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/client/ClientSessionImpl.kt index d19c184d..67fa2215 100644 --- a/acp/src/commonMain/kotlin/com/agentclientprotocol/client/ClientSessionImpl.kt +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/client/ClientSessionImpl.kt @@ -4,6 +4,7 @@ import com.agentclientprotocol.annotations.UnstableApi import com.agentclientprotocol.common.ClientSessionOperations import com.agentclientprotocol.common.Event import com.agentclientprotocol.common.SessionCreationParameters +import com.agentclientprotocol.common.notify import com.agentclientprotocol.model.* import com.agentclientprotocol.protocol.Protocol import com.agentclientprotocol.protocol.invoke diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/common/ClientSessionOperations.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/common/ClientSessionOperations.kt index 2d4f6633..9d0e0f8a 100644 --- a/acp/src/commonMain/kotlin/com/agentclientprotocol/common/ClientSessionOperations.kt +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/common/ClientSessionOperations.kt @@ -20,9 +20,10 @@ public interface ClientSessionOperations : FileSystemOperations, TerminalOperati /** * Asks the user whether the agent may perform [toolCall], offering [permissions], and returns the outcome. * - * This can simply wait for the user: when the client cancels or closes the session, the SDK answers the - * request with [RequestPermissionOutcome.Cancelled] on its own and cancels this coroutine. Returning - * `Cancelled` here is allowed but unnecessary. + * This can simply wait for the user: when the client cancels or closes the session, and, for a subagent, when the + * agent reports its work cancelled or its root is closed, the SDK answers the request with + * [RequestPermissionOutcome.Cancelled] on its own and cancels this coroutine. Returning `Cancelled` here is + * allowed but unnecessary. * * Respond to cancellation promptly, for example by dismissing the UI in `finally`: the `cancelled` reply goes * out only after this coroutine finishes, so blocking a thread or suspending in `NonCancellable` delays it. @@ -34,7 +35,35 @@ public interface ClientSessionOperations : FileSystemOperations, TerminalOperati ): RequestPermissionResponse /** - * Handles notification from an agent that is not bound to any prompt + * Handles an event of the session's stream that is not bound to any prompt. + * + * On the client, this receives the session's updates as [SessionEvent.Update], and once the [SessionEvent.Opened] + * marker, which separates the updates that came before the answer of the opening call, such as the history that + * `session/load` replays, from the live ones. [SessionEvent.Opened] says when it is and isn't delivered. + * + * Until the opening call returns, the call delivers these events itself: cancelling the caller cancels `notify`, + * and a cancellation of the caller or a failure of `notify` fails the opening. After the call has returned, a + * failure of `notify` is logged, as for any live update. A subagent session has no opening call, see + * [com.agentclientprotocol.client.ClientSubagentSession]. + * + * The client delivers a session's events one at a time, in arrival order: the next one waits until `notify` + * returns, and so do the updates of a running prompt turn. So `notify` must not wait for a later event of its own + * session. For example, calling [com.agentclientprotocol.client.ClientSession.prompt] inside `notify` and + * collecting its flow there never returns. + * + * On the agent, this sends a [SessionEvent.Update] to the client, and throws [IllegalStateException] for + * [SessionEvent.Opened], which only the client runtime delivers. Agent code usually calls the `notify` extension + * that takes a [SessionUpdate]. */ - public suspend fun notify(notification: SessionUpdate, _meta: JsonElement? = null) + public suspend fun notify(event: SessionEvent) +} + +/** + * Sends [notification] as a [SessionEvent.Update] through [ClientSessionOperations.notify]. + * + * This is an extension rather than an overridable member, so a client implementation can't override it instead of + * the member and miss [SessionEvent.Opened]. + */ +public suspend fun ClientSessionOperations.notify(notification: SessionUpdate, _meta: JsonElement? = null) { + notify(SessionEvent.Update(notification, _meta)) } diff --git a/acp/src/commonMain/kotlin/com/agentclientprotocol/common/SessionEvent.kt b/acp/src/commonMain/kotlin/com/agentclientprotocol/common/SessionEvent.kt new file mode 100644 index 00000000..42fd3c8b --- /dev/null +++ b/acp/src/commonMain/kotlin/com/agentclientprotocol/common/SessionEvent.kt @@ -0,0 +1,42 @@ +package com.agentclientprotocol.common + +import com.agentclientprotocol.model.AcpCreatedSessionResponse +import com.agentclientprotocol.model.SessionUpdate +import kotlinx.serialization.json.JsonElement + +/** + * An event of a session's stream, delivered to [ClientSessionOperations.notify]. + * + * The stream carries the session's updates and, once, the [Opened] marker that separates the updates that came + * before the answer of the opening call from the live ones. + */ +public sealed class SessionEvent { + /** + * A `session/update` of the session. + * + * @property _meta the notification's metadata + */ + public class Update(public val update: SessionUpdate, public val _meta: JsonElement? = null) : SessionEvent() + + /** + * Marks the point from which this stream is live: updates before it came before the answer of the call that + * opened the root session, and updates after it are current. + * + * ### Delivery + * + * - A successful opening delivers exactly one [Opened] to its operations, before any live update. + * - An opening call that fails before the agent's answer arrives delivers none. + * - Once the answer has arrived, the call can still fail: if its caller is cancelled, or `notify` throws, while the + * call delivers [Opened] and the updates that arrived before the session took over. [Opened] may already have + * been delivered then, so treat a failed opening call as a failed opening, whatever events the operations got. + * + * At this point the session's [com.agentclientprotocol.client.BaseClientSession.subagents] lists every subagent + * announced before it whose setup succeeded. The subagents' own lists complete at their own `Opened`, see there. + * + * Only the client runtime delivers it; agent code can't create one. + * + * @property response the answer of the call that opened this session, with its state at this point; `null` for a + * subagent, which no call opens: its state starts unconfirmed and comes from later updates + */ + public class Opened internal constructor(public val response: AcpCreatedSessionResponse?) : SessionEvent() +} diff --git a/acp/src/commonTest/kotlin/com/agentclientprotocol/agent/internal/ReplayWindowTest.kt b/acp/src/commonTest/kotlin/com/agentclientprotocol/agent/internal/ReplayWindowTest.kt new file mode 100644 index 00000000..6a1b9a7f --- /dev/null +++ b/acp/src/commonTest/kotlin/com/agentclientprotocol/agent/internal/ReplayWindowTest.kt @@ -0,0 +1,77 @@ +package com.agentclientprotocol.agent.internal + +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.async +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +@OptIn(ExperimentalCoroutinesApi::class) +class ReplayWindowTest { + @Test + fun `a send in an open window is history and the response waits for it`() = runTest { + val window = ReplayWindow(open = true) + + lateinit var waiter: Job + val isLive = window.send { isLive -> + waiter = launch(start = CoroutineStart.UNDISPATCHED) { window.awaitHistorySends() } + assertFalse(waiter.isCompleted, "the wait must not end while a history send runs") + isLive + } + assertFalse(isLive) + + runCurrent() + assertTrue(waiter.isCompleted) + assertTrue(window.isOpen) + } + + @Test + fun `a send started while the window is closing waits for it to close and is live`() = runTest { + val window = ReplayWindow(open = true) + window.awaitHistorySends() + + val sent = async { window.send { isLive -> isLive } } + runCurrent() + assertFalse(sent.isCompleted) + + window.close() + assertTrue(sent.await()) + assertFalse(window.isOpen) + } + + @Test + fun `close runs the deferred starts once and later ones run at once`() = runTest { + val window = ReplayWindow(open = true) + val started = mutableListOf() + + window.runAfterClose { started += "first" } + window.runAfterClose { started += "second" } + assertEquals(emptyList(), started) + + window.close() + window.close() + assertEquals(listOf("first", "second"), started) + + window.runAfterClose { started += "third" } + assertEquals(listOf("first", "second", "third"), started) + } + + @Test + fun `a window closed at construction sends live and runs starts at once`() = runTest { + val window = ReplayWindow(open = false) + assertFalse(window.isOpen) + + assertTrue(window.send { isLive -> isLive }) + window.awaitHistorySends() + + var started = false + window.runAfterClose { started = true } + assertTrue(started) + } +} diff --git a/acp/src/commonTest/kotlin/com/agentclientprotocol/client/ClientSessionHolderTest.kt b/acp/src/commonTest/kotlin/com/agentclientprotocol/client/ClientSessionHolderTest.kt deleted file mode 100644 index eae29f26..00000000 --- a/acp/src/commonTest/kotlin/com/agentclientprotocol/client/ClientSessionHolderTest.kt +++ /dev/null @@ -1,155 +0,0 @@ -package com.agentclientprotocol.client - -import com.agentclientprotocol.annotations.UnstableApi -import com.agentclientprotocol.common.ClientSessionOperations -import com.agentclientprotocol.model.ContentBlock -import com.agentclientprotocol.model.PermissionOption -import com.agentclientprotocol.model.RequestPermissionResponse -import com.agentclientprotocol.model.SessionUpdate -import com.agentclientprotocol.protocol.AcpExpectedError -import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.async -import kotlinx.coroutines.launch -import kotlinx.coroutines.test.runCurrent -import kotlinx.coroutines.test.runTest -import kotlinx.serialization.json.JsonElement -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertTrue - -/** - * When the last session initialization ends, `Client` reaps speculative [ClientSessionHolder] holders that no initialization claimed. - * The `session/update` handler may have looked such a holder up just before the reap and only queue into it afterwards. - * Both steps are non-suspending, so this interleaving needs real parallelism through `Client`; - * these tests put the holder into the same states directly. - * - * The early delivery tests cover the order, the failure and the owner of a holder that `Client.loadSession` with a - * [ClientSessionOperations] argument opens. - */ -@OptIn(ExperimentalCoroutinesApi::class, UnstableApi::class) -class ClientSessionHolderTest { - private val queuedUpdate = SessionUpdate.AgentMessageChunk(ContentBlock.Text("queued")) - private val lateUpdate = SessionUpdate.AgentMessageChunk(ContentBlock.Text("late")) - - @Test - fun `update for a reaped holder is reported as undelivered instead of failing`() = runTest { - val holder = ClientSessionHolder() - holder.failAndDrainQueue(AcpExpectedError("Session session-9 not found")) { _, _ -> } - - assertFalse(holder.handleOrQueue(lateUpdate, null)) - } - - @Test - fun `update arriving during the reap is reported after the queued updates are drained`() = runTest { - val holder = ClientSessionHolder() - assertTrue(holder.handleOrQueue(queuedUpdate, null)) - - val events = mutableListOf() - val releaseDrain = CompletableDeferred() - launch { - holder.failAndDrainQueue(AcpExpectedError("Session session-9 not found")) { update, _ -> - releaseDrain.await() - events += "drained $update" - } - } - // The reap has closed the channel and is suspended while handing the queued update over. - runCurrent() - - val late = async { - holder.handleOrQueue(lateUpdate, null).also { events += "late update delivered: $it" } - } - runCurrent() - assertFalse(late.isCompleted, "the late update must wait until the queued updates are drained") - - releaseDrain.complete(Unit) - assertFalse(late.await()) - assertEquals(listOf("drained $queuedUpdate", "late update delivered: false"), events) - } - - @Test - fun `early delivery hands the queued updates and the arriving updates to the operations in arrival order`() = runTest { - val holder = ClientSessionHolder() - assertTrue(holder.handleOrQueue(queuedUpdate, null)) - assertTrue(holder.claim(ClientSessionHolder.Opener.OPERATIONS)) - - val operations = RecordingOperations() - val delivery = launch { holder.deliverEarly(operations) } - runCurrent() - assertEquals(listOf(queuedUpdate), operations.updates) - - assertTrue(holder.handleOrQueue(lateUpdate, null)) - holder.endEarlyDelivery() - delivery.join() - assertEquals(listOf(queuedUpdate, lateUpdate), operations.updates) - } - - @Test - fun `early delivery hands one update at a time to the operations`() = runTest { - val holder = ClientSessionHolder() - val releaseFirst = CompletableDeferred() - val operations = RecordingOperations(beforeEach = { update -> if (update == queuedUpdate) releaseFirst.await() }) - val delivery = launch { holder.deliverEarly(operations) } - - assertTrue(holder.handleOrQueue(queuedUpdate, null)) - assertTrue(holder.handleOrQueue(lateUpdate, null)) - holder.endEarlyDelivery() - runCurrent() - assertTrue(operations.updates.isEmpty(), "the second update must wait until the operations return from the first") - - releaseFirst.complete(Unit) - delivery.join() - assertEquals(listOf(queuedUpdate, lateUpdate), operations.updates) - } - - @Test - fun `updates left by a failed early delivery go to the unconnected handler and later updates are undelivered`() = runTest { - val holder = ClientSessionHolder() - val failure = IllegalStateException("notify failed") - val delivery = async { runCatching { holder.deliverEarly(RecordingOperations(beforeEach = { throw failure })) } } - assertTrue(holder.handleOrQueue(queuedUpdate, null)) - assertTrue(holder.handleOrQueue(lateUpdate, null)) - assertEquals(failure, delivery.await().exceptionOrNull()) - - val unconnected = mutableListOf() - holder.failAndDrainQueue(IllegalStateException("load failed")) { update, _ -> unconnected += update } - assertEquals(listOf(lateUpdate), unconnected) - assertFalse(holder.handleOrQueue(SessionUpdate.AgentMessageChunk(ContentBlock.Text("after")), null)) - } - - @Test - fun `one kind of opener owns a holder`() = runTest { - val early = ClientSessionHolder() - assertTrue(early.claim(ClientSessionHolder.Opener.OPERATIONS)) - assertFalse(early.claim(ClientSessionHolder.Opener.OPERATIONS), "a second early opening") - assertFalse(early.claim(ClientSessionHolder.Opener.FACTORY), "a factory opening of an early holder") - - val factory = ClientSessionHolder() - assertTrue(factory.claim(ClientSessionHolder.Opener.FACTORY)) - assertTrue(factory.claim(ClientSessionHolder.Opener.FACTORY), "a second factory opening keeps its old behavior") - assertFalse(factory.claim(ClientSessionHolder.Opener.OPERATIONS), "an early opening of a factory holder") - - val failed = ClientSessionHolder() - failed.failAndDrainQueue(IllegalStateException("load failed")) { _, _ -> } - assertTrue(failed.isFailed) - assertFalse(failed.claim(ClientSessionHolder.Opener.OPERATIONS), "an early opening of a failed holder") - } - - private class RecordingOperations( - private val beforeEach: suspend (SessionUpdate) -> Unit = {}, - ) : ClientSessionOperations { - val updates = mutableListOf() - - override suspend fun requestPermissions( - toolCall: SessionUpdate.ToolCallUpdate, - permissions: List, - _meta: JsonElement?, - ): RequestPermissionResponse = error("not expected in this test") - - override suspend fun notify(notification: SessionUpdate, _meta: JsonElement?) { - beforeEach(notification) - updates += notification - } - } -} diff --git a/acp/src/jvmTest/kotlin/com/agentclientprotocol/agent/AgentSubagentsTest.kt b/acp/src/jvmTest/kotlin/com/agentclientprotocol/agent/AgentSubagentsTest.kt new file mode 100644 index 00000000..22f7e306 --- /dev/null +++ b/acp/src/jvmTest/kotlin/com/agentclientprotocol/agent/AgentSubagentsTest.kt @@ -0,0 +1,2607 @@ +@file:OptIn(UnstableApi::class) + +package com.agentclientprotocol.agent + +import com.agentclientprotocol.agent.internal.NesSessionWrapper +import com.agentclientprotocol.agent.internal.RemoteClientSessionOperations +import com.agentclientprotocol.agent.internal.RootSessionWrapper +import com.agentclientprotocol.agent.internal.SessionWrapperContextElement +import com.agentclientprotocol.agent.internal.asContextElement +import com.agentclientprotocol.agent.internal.sessionWrapper +import com.agentclientprotocol.annotations.UnstableApi +import com.agentclientprotocol.client.ClientInfo +import com.agentclientprotocol.common.ClientSessionOperations +import com.agentclientprotocol.common.Event +import com.agentclientprotocol.common.SessionCreationParameters +import com.agentclientprotocol.common.SessionEvent +import com.agentclientprotocol.common.notify +import com.agentclientprotocol.model.AcpMethod +import com.agentclientprotocol.model.AcpRequest +import com.agentclientprotocol.model.CancelNotification +import com.agentclientprotocol.model.CancelRequestNotification +import com.agentclientprotocol.model.ClientCapabilities +import com.agentclientprotocol.model.CloseSessionRequest +import com.agentclientprotocol.model.CloseSessionResponse +import com.agentclientprotocol.model.ContentBlock +import com.agentclientprotocol.model.DeleteSessionRequest +import com.agentclientprotocol.model.ElicitationCapabilities +import com.agentclientprotocol.model.ElicitationId +import com.agentclientprotocol.model.ElicitationMode +import com.agentclientprotocol.model.ElicitationUrlCapabilities +import com.agentclientprotocol.model.FileSystemCapability +import com.agentclientprotocol.model.ForkSessionRequest +import com.agentclientprotocol.model.IdleStopReason +import com.agentclientprotocol.model.InitializeRequest +import com.agentclientprotocol.model.LATEST_PROTOCOL_VERSION +import com.agentclientprotocol.model.LoadSessionRequest +import com.agentclientprotocol.model.LoadSessionResponse +import com.agentclientprotocol.model.MaybeUndefined +import com.agentclientprotocol.model.MessageId +import com.agentclientprotocol.model.ModelId +import com.agentclientprotocol.model.NewSessionRequest +import com.agentclientprotocol.model.PromptRequest +import com.agentclientprotocol.model.ResumeSessionRequest +import com.agentclientprotocol.model.SessionCancelCapabilities +import com.agentclientprotocol.model.SessionConfigId +import com.agentclientprotocol.model.SessionConfigOptionValue +import com.agentclientprotocol.model.SessionId +import com.agentclientprotocol.model.SessionMode +import com.agentclientprotocol.model.SessionModeId +import com.agentclientprotocol.model.SessionNotification +import com.agentclientprotocol.model.SessionUpdate +import com.agentclientprotocol.model.SetSessionConfigOptionRequest +import com.agentclientprotocol.model.SetSessionModeRequest +import com.agentclientprotocol.model.SetSessionModelRequest +import com.agentclientprotocol.model.StateUpdate +import com.agentclientprotocol.model.StopReason +import com.agentclientprotocol.model.SubagentCapabilities +import com.agentclientprotocol.model.SubagentSessionCapabilities +import com.agentclientprotocol.model.SuggestNesRequest +import com.agentclientprotocol.model.SuggestNesResponse +import com.agentclientprotocol.model.ToolCallContent +import com.agentclientprotocol.model.ToolCallId +import com.agentclientprotocol.protocol.Protocol +import com.agentclientprotocol.rpc.ACPJson +import com.agentclientprotocol.rpc.JsonRpcErrorCode +import com.agentclientprotocol.rpc.JsonRpcErrorResponse +import com.agentclientprotocol.rpc.JsonRpcMessage +import com.agentclientprotocol.rpc.JsonRpcNotification +import com.agentclientprotocol.rpc.JsonRpcRequest +import com.agentclientprotocol.rpc.JsonRpcSuccessResponse +import com.agentclientprotocol.rpc.RequestId +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.ConcurrentLinkedQueue +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import kotlin.coroutines.ContinuationInterceptor +import kotlin.coroutines.CoroutineContext +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNotSame +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue +import kotlin.test.fail +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CopyableThrowable +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.cancel +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.consumeAsFlow +import kotlinx.coroutines.flow.emitAll +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.isActive +import kotlinx.coroutines.job +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.coroutines.yield +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +class AgentSubagentsTest { + + private val rootId = SessionId("root") + private val childId = SessionId("child") + private val siblingId = SessionId("sibling") + private val grandchildId = SessionId("grandchild") + + private class RootSession(override val sessionId: SessionId) : AgentSession { + val context = CompletableDeferred() + + @Volatile + var promptHandler: PromptHandler = {} + + @Volatile + var replay: suspend () -> Unit = {} + + /** + * Runs in [postInitialize] after [context] is completed. + */ + @Volatile + var afterInitialize: suspend () -> Unit = {} + + @Volatile + var onClose: suspend () -> Unit = {} + + /** + * Thrown while the SDK builds the response that opens this session. + */ + @Volatile + var responseFailure: Throwable? = null + + /** + * Runs while the SDK builds the response that opens this session, before [responseFailure] is thrown. + */ + @Volatile + var onBuildResponse: () -> Unit = {} + + override val availableModes: List + get() { + onBuildResponse() + return responseFailure?.let { throw it } ?: emptyList() + } + + override suspend fun postInitialize() { + context.complete(checkNotNull(currentCoroutineContext()[SessionWrapperContextElement.Key])) + afterInitialize() + } + + override suspend fun replayHistory() = replay() + + override suspend fun close(_meta: JsonElement?): CloseSessionResponse { + onClose() + return CloseSessionResponse() + } + + override suspend fun prompt(content: List, _meta: JsonElement?): Flow = flow { + promptHandler(content) + } + } + + private class TestSubagent( + override val events: Flow = emptyFlow(), + private val onCancel: suspend () -> Unit = {}, + ) : AgentSubagentSession { + override suspend fun cancel() = onCancel() + } + + /** + * A factory that sends the child's plain announcement and returns a [TestSubagent] with [events]. + */ + private fun announcing( + events: Flow = emptyFlow(), + onCancel: suspend () -> Unit = {}, + ) = AgentSubagentFactory { context -> + context.client.notify(announcement(context.sessionId)) + TestSubagent(events, onCancel) + } + + /** + * An initialized agent with one root session. [rootContext] holds only the root's session element, so + * `withContext(rootContext)` runs a block as the root's code while keeping the caller's job. + */ + private class Fixture( + val transport: TestTransport, + val protocol: Protocol, + val agent: Agent, + val root: RootSession, + val rootContext: CoroutineContext, + val openable: OpenableSessions, + ) { + val rootSubagents: AgentSubagents get() = assertNotNull(rootContext.subagents) + val rootClient get() = rootContext.client + val rootWrapper get() = rootContext.rootWrapper + + /** + * Waits until every collection of [root]'s subtree has ended, including the SDK's feed-end handling. + */ + suspend fun awaitCollectionsEnded(root: RootSessionWrapper = rootWrapper) { + withTimeout(5.seconds) { root.subtreeScope.coroutineContext.job.children.forEach { it.join() } } + } + + /** + * Opens another root session with `session/new` and returns its context, once its postInitialize ran. + */ + suspend fun newRoot(session: RootSession): CoroutineContext { + openable.created.add(session) + transport.testRequest(AcpMethod.AgentMethods.V1.SessionNew, NewSessionRequest(".", emptyList())) + return withTimeout(5.seconds) { session.context.await() } + } + + /** + * Serves `session/load` for [session] and returns everything sent up to and including the response. + */ + suspend fun load(session: RootSession, id: RequestId? = null): List { + openable.byId[session.sessionId] = session + val method = AcpMethod.AgentMethods.V1.SessionLoad + val params = + ACPJson.encodeToJsonElement(method.requestSerializer, LoadSessionRequest(session.sessionId, ".", emptyList())) + return if (id == null) { + transport.fireTestRequest(method.methodName, params) + } else { + transport.fireTestRequest(method.methodName, params, id) + } + } + + suspend fun resume(session: RootSession): JsonRpcMessage? { + openable.byId[session.sessionId] = session + return request(AcpMethod.AgentMethods.V1.SessionResume, ResumeSessionRequest(session.sessionId, ".")) + } + + /** + * Serves `session/close` for [sessionId] and returns everything sent up to and including the response. + */ + suspend fun close(sessionId: SessionId): List = transport.fireTestRequest( + AcpMethod.AgentMethods.V1.SessionClose.methodName, + ACPJson.encodeToJsonElement(AcpMethod.AgentMethods.V1.SessionClose.requestSerializer, CloseSessionRequest(sessionId)), + ) + + fun fireCancel(sessionId: SessionId) { + transport.fireTestNotification( + AcpMethod.AgentMethods.V1.SessionCancel.methodName, + ACPJson.encodeToJsonElement(AcpMethod.AgentMethods.V1.SessionCancel.serializer, CancelNotification(sessionId)), + ) + } + + suspend fun request(method: AcpMethod.AcpRequestResponseMethod, params: T): JsonRpcMessage? = + transport.fireTestRequest(method.methodName, ACPJson.encodeToJsonElement(method.requestSerializer, params)) + .lastOrNull() + + fun fireWithoutReply(method: AcpMethod.AcpRequestResponseMethod, params: T, id: RequestId) { + val encoded = ACPJson.encodeToJsonElement(method.requestSerializer, params) + transport.fireTestRequestWithoutReply(method.methodName, encoded, id) + } + + suspend fun inRoot(block: suspend () -> T): T = withContext(rootContext) { block() } + + suspend fun nextNotification(): SessionNotification { + val message = assertNotNull(transport.receiveTestMessages(1).firstOrNull(), "Expected a notification") + return assertNotNull(message.sessionNotificationOrNull(), "Expected session/update, got $message") + } + + /** + * Asserts that nothing was sent since the last read: a marker the root sends now is the next message. + */ + suspend fun assertNothingMoreSent() { + val marker = text("marker") + rootClient.notify(marker) + assertEquals(SessionNotification(SessionId("root"), marker), nextNotification()) + } + } + + /** + * The sessions the fixture's agent opens: the next `session/new` takes [created]'s head, or the fixture's root, + * and `session/load` and `session/resume` look sessions up in [byId], or throw [failure] if it is set. + */ + private class OpenableSessions { + val created = ConcurrentLinkedQueue() + val byId = ConcurrentHashMap() + + @Volatile + var failure: Throwable? = null + + fun find(sessionId: SessionId): RootSession { + failure?.let { throw it } + return checkNotNull(byId[sessionId]) + } + } + + private fun withSubagents( + subagentsCapability: Boolean = true, + otherCapabilities: ClientCapabilities = ClientCapabilities(), + block: suspend CoroutineScope.(Fixture) -> Unit, + ) = runBlocking { + val transport = TestTransport(5.seconds) + val protocol = Protocol(this, transport) + val root = RootSession(rootId) + val openable = OpenableSessions() + val support = object : AgentSupport { + override suspend fun initialize(clientInfo: ClientInfo): AgentInfo = AgentInfo() + override suspend fun createSession(sessionParameters: SessionCreationParameters): AgentSession = + openable.created.poll() ?: root + + override suspend fun loadSession(sessionId: SessionId, sessionParameters: SessionCreationParameters) = + openable.find(sessionId) + + override suspend fun resumeSession(sessionId: SessionId, sessionParameters: SessionCreationParameters) = + openable.find(sessionId) + } + val agent = Agent(protocol, support) + protocol.start() + try { + val capabilities = otherCapabilities.copy(subagents = if (subagentsCapability) SubagentCapabilities() else null) + transport.testRequest(AcpMethod.AgentMethods.V1.Initialize, InitializeRequest(LATEST_PROTOCOL_VERSION, capabilities)) + transport.testRequest(AcpMethod.AgentMethods.V1.SessionNew, NewSessionRequest(".", emptyList())) + val rootContext = withTimeout(5.seconds) { root.context.await() } + block(Fixture(transport, protocol, agent, root, rootContext, openable)) + } finally { + protocol.close() + } + } + + // Context accessors + + @Test + fun `subagents accessor fails outside a session context`() = runBlocking { + assertFailsWith { currentCoroutineContext().subagents } + Unit + } + + @Test + fun `subagents accessor fails in a NES session context`() = withSubagents { f -> + val nesSession = object : NesAgentSession { + override val nesSessionId = SessionId("nes") + override suspend fun suggest(request: SuggestNesRequest): SuggestNesResponse = error("Not called") + } + val nesContext = NesSessionWrapper(f.agent, nesSession, f.protocol).asContextElement() + + val failure = assertFailsWith { nesContext.subagents } + assertTrue(failure.message!!.contains("NES"), failure.message) + } + + @Test + fun `child context resolves its own client, subagents and agent`() = withSubagents { f -> + assertNotNull(f.rootContext.subagents) + var checked = false + f.rootSubagents.announce(childId, { context -> + val coroutineContext = currentCoroutineContext() + assertEquals(childId, context.sessionId) + assertSame(context.client, coroutineContext.client) + assertSame(context.subagents, coroutineContext.subagents) + assertSame(f.agent, coroutineContext.agent) + context.client.notify(announcement(childId)) + checked = true + TestSubagent() + }) + assertTrue(checked) + } + + // Announcement + + @Test + fun `events follow the factory's announcement, and their first item is not special`() = withSubagents { f -> + val patch = SessionUpdate.SubagentUpdate(childId, state = MaybeUndefined.Value(StateUpdate.Running())) + f.rootSubagents.announce(childId, announcing(flowOf(patch, text("from events")))) + + assertEquals(SessionNotification(rootId, announcement(childId)), f.nextNotification()) + assertEquals(SessionNotification(rootId, patch), f.nextNotification()) + assertEquals(SessionNotification(childId, text("from events")), f.nextNotification()) + } + + @Test + fun `announce returns after the factory and a parent message sent then follows it`() = withSubagents { f -> + val started = CompletableDeferred() + val release = CompletableDeferred() + val announcing = async { + f.rootSubagents.announce(childId, { context -> + started.complete(Unit) + release.await() + context.client.notify(announcement(childId)) + TestSubagent() + }) + } + withTimeout(5.seconds) { started.await() } + assertFalse(announcing.isCompleted) + + release.complete(Unit) + withTimeout(5.seconds) { announcing.await() } + val message = SessionUpdate.SessionMessage(MessageId("m1"), recipientSessionId = MaybeUndefined.Value(childId)) + f.rootClient.notify(message) + + assertEquals(SessionNotification(rootId, announcement(childId)), f.nextNotification()) + assertEquals(SessionNotification(rootId, message), f.nextNotification()) + } + + @Test + fun `operations fail before the announcement`() = withSubagents { f -> + val failures = mutableListOf() + val session = TestSubagent() + val announced = f.rootSubagents.announce(childId, { context -> + val client = context.client + failures += assertFailsWith { client.notify(text("early")) } + failures += assertFailsWith { + client.requestPermissions(SessionUpdate.ToolCallUpdate(ToolCallId("t")), emptyList()) + } + failures += assertFailsWith { client.fsReadTextFile("/a") } + failures += assertFailsWith { client.terminalCreate("ls") } + + client.notify(announcement(childId)) + client.notify(text("after")) + session + }) + + assertSame(session, announced) + assertEquals(4, failures.size) + failures.forEach { assertTrue(it.message!!.contains("not announced"), it.message) } + assertEquals(SessionNotification(rootId, announcement(childId)), f.nextNotification()) + assertEquals(SessionNotification(childId, text("after")), f.nextNotification()) + } + + @Test + fun `an announced child's requests are sent for the child's session`() = withSubagents( + otherCapabilities = ClientCapabilities( + fs = FileSystemCapability(readTextFile = true, writeTextFile = true), + terminal = true, + elicitation = ElicitationCapabilities(url = ElicitationUrlCapabilities()), + ), + ) { f -> + val client = announceChild(f, childId).client + val sent = mutableListOf() + // Captures each request as it is sent and fails the call, so no response is needed. + f.transport.onSend = { message -> + if (message is JsonRpcRequest) { + sent += message + throw UncopiedException("request captured") + } + } + val requests: List Unit>> = listOf( + "requestPermissions" to { client.requestPermissions(SessionUpdate.ToolCallUpdate(ToolCallId("t")), emptyList()) }, + "fsReadTextFile" to { client.fsReadTextFile("/a") }, + "fsWriteTextFile" to { client.fsWriteTextFile("/a", "content") }, + "terminalCreate" to { client.terminalCreate("ls") }, + "terminalOutput" to { client.terminalOutput("term") }, + "terminalRelease" to { client.terminalRelease("term") }, + "terminalWaitForExit" to { client.terminalWaitForExit("term") }, + "terminalKill" to { client.terminalKill("term") }, + "createSessionElicitation" to { + (client as RemoteClientSessionOperations).createSessionElicitation( + ElicitationMode.Url(ElicitationId("e"), "https://example.com"), + "Sign in", + ) + }, + ) + + for ((name, request) in requests) { + assertFailsWith(name) { request() } + val params = assertNotNull(sent.removeLastOrNull()?.params, name).jsonObject + assertEquals(childId.value, params["sessionId"]?.jsonPrimitive?.content, name) + } + } + + @Test + fun `grant is recorded before the update is sent, on every path`() = withSubagents { f -> + val grantsAtSend = mutableListOf() + f.transport.onSend = { message -> + val update = message.sessionNotificationOrNull()?.update + if (update is SessionUpdate.SubagentUpdate && update.sessionId == childId) { + grantsAtSend += f.agent.subagentOrNull(childId)?.isCancelGranted + } + } + val revoke = SessionUpdate.SubagentUpdate(childId, capabilities = MaybeUndefined.Null) + val regrant = SessionUpdate.SubagentUpdate(childId, capabilities = MaybeUndefined.Value(grant())) + val withoutCancel = SessionUpdate.SubagentUpdate( + childId, + capabilities = MaybeUndefined.Value(SubagentSessionCapabilities()) + ) + val events = Channel(Channel.UNLIMITED) + events.send(revoke) + + val context = announce(f.rootSubagents, childId, granted = true, events = events.consumeAsFlow()) + repeat(2) { f.nextNotification() } + context.client.notify(regrant) + f.nextNotification() + events.send(withoutCancel) + f.nextNotification() + + assertEquals(listOf(true, false, true, false), grantsAtSend) + events.close() + } + + // announce errors + + @Test + fun `a parent outside the bound session's subtree or unknown is rejected`() = withSubagents { f -> + val child = announceChild(f, childId) + announceChild(f, siblingId) + var factoryCalled = false + + for (parent in listOf(siblingId, rootId, SessionId("unknown"))) { + assertFailsWith("parent $parent") { + child.subagents.announce(grandchildId, { factoryCalled = true; TestSubagent() }, parent = parent) + } + } + assertFalse(factoryCalled) + assertNull(f.agent.subagentOrNull(grandchildId)) + f.assertNothingMoreSent() + } + + @Test + fun `an unannounced child cannot announce grandchildren`() = withSubagents { f -> + var nested: Throwable? = null + val failure = assertFailsWith { + f.rootSubagents.announce(childId, { context -> + nested = runCatching { context.subagents.announce(grandchildId, { TestSubagent() }) }.exceptionOrNull() + error("factory gives up") + }) + } + + assertIs(nested) + assertTrue(failure.causes().any { it.message == "factory gives up" }, failure.stackTraceToString()) + assertNull(f.agent.subagentOrNull(grandchildId)) + f.assertNothingMoreSent() + } + + @Test + fun `a duplicate id is rejected, including a root session id`() = withSubagents { f -> + announceChild(f, childId) + + assertFailsWith { f.rootSubagents.announce(childId, { TestSubagent() }) } + assertFailsWith { f.rootSubagents.announce(rootId, { TestSubagent() }) } + f.assertNothingMoreSent() + } + + @Test + fun `a session opened with a subagent's id fails and the subagent stays registered`() = withSubagents { f -> + val child = announceChild(f, childId) + val wrapper = assertNotNull(f.agent.subagentOrNull(childId)) + + f.openable.created.add(RootSession(childId)) + assertIs(f.request(AcpMethod.AgentMethods.V1.SessionNew, NewSessionRequest(".", emptyList()))) + + assertSame(wrapper, f.agent.subagentOrNull(childId)) + child.client.notify(text("still registered")) + assertEquals(SessionNotification(childId, text("still registered")), f.nextNotification()) + val prompt = assertIs( + f.request(AcpMethod.AgentMethods.V1.SessionPrompt, PromptRequest(childId, listOf(ContentBlock.Text("go")))) + ) + assertEquals("Session $childId is a subagent", prompt.error.message) + f.assertNothingMoreSent() + } + + @Test + fun `a factory that returns without announcing fails announce, never collects the events and frees the id`() = + withSubagents { f -> + val collected = CompletableDeferred() + lateinit var context: AgentSubagentContext + val failure = assertFailsWith { + f.rootSubagents.announce(childId, { + context = it + assertFailsWith { it.client.notify(announcement(siblingId)) } + // An announcement in the events doesn't count: they are collected only after an announcement. + TestSubagent(flow { + collected.complete(Unit) + emit(announcement(childId)) + }) + }) + } + + assertTrue(failure.message!!.contains("not announced"), failure.message) + assertNull(f.agent.subagentOrNull(childId)) + f.awaitCollectionsEnded() + assertFalse(collected.isCompleted) + assertFailsWith { context.client.notify(announcement(childId)) } + f.assertNothingMoreSent() + + announceChild(f, childId) + } + + /* + * A cancellation that the factory throws while the caller is active is the factory's failure, and announce wraps + * it. A caller that is cancelled itself gets its cancellation as is. + */ + @Test + fun `a factory that throws before announcing fails announce and frees the id`() { + val failures: List Unit>> = listOf( + IllegalArgumentException("bad config") to { failure -> + assertTrue(failure.causes().any { it is IllegalArgumentException }, failure.stackTraceToString()) + }, + CancellationException("app timeout") to { failure -> assertWrapsCancellation(failure) }, + ) + for ((thrown, assertFailure) in failures) { + withSubagents { f -> + val failure = assertFailsWith { f.rootSubagents.announce(childId, { throw thrown }) } + + assertFailure(failure) + assertTrue(currentCoroutineContext().isActive) + assertNull(f.agent.subagentOrNull(childId)) + f.assertNothingMoreSent() + announceChild(f, childId) + } + } + } + + @Test + fun `a factory that throws after announcing an active child revokes the grant and reports unknown`() { + val uncopied = UncopiedException("factory failed late") + val failures: List Unit>> = listOf( + uncopied to { failure -> assertSame(uncopied, failure) }, + CancellationException("app timeout") to { failure -> + assertIs(failure) + assertWrapsCancellation(failure) + }, + ) + for ((thrown, assertFailure) in failures) { + withSubagents { f -> + lateinit var context: AgentSubagentContext + val failure = runCatching { + f.rootSubagents.announce(childId, { + context = it + it.client.notify(announcement(childId, granted = true, state = StateUpdate.Running())) + throw thrown + }) + }.exceptionOrNull() + + assertFailure(assertNotNull(failure)) + assertTrue(currentCoroutineContext().isActive) + assertEquals(SessionNotification(rootId, announcement(childId, granted = true, state = StateUpdate.Running())), f.nextNotification()) + val correction = SessionUpdate.SubagentUpdate( + childId, + capabilities = MaybeUndefined.Null, + state = MaybeUndefined.Value(StateUpdate.Unknown()), + ) + assertEquals(SessionNotification(rootId, correction), f.nextNotification()) + f.assertNothingMoreSent() + + val child = assertNotNull(f.agent.subagentOrNull(childId)) + assertFalse(child.isCancelGranted) + assertNull(child.session) + assertFailsWith { f.rootSubagents.announce(childId, { TestSubagent() }) } + + context.client.notify(text("still valid")) + assertEquals(SessionNotification(childId, text("still valid")), f.nextNotification()) + } + } + } + + @Test + fun `a factory that throws after announcing an idle child without grant sends nothing more`() = + withSubagents { f -> + val idle = StateUpdate.Idle(IdleStopReason.EndTurn) + assertFailsWith { + f.rootSubagents.announce(childId, { + it.client.notify(announcement(childId, state = StateUpdate.Running())) + it.client.notify(SessionUpdate.SubagentUpdate(childId, state = MaybeUndefined.Value(idle))) + throw RuntimeException("factory failed late") + }) + } + + repeat(2) { f.nextNotification() } + f.assertNothingMoreSent() + assertNotNull(f.agent.subagentOrNull(childId)) + } + + @Test + fun `a caller cancelled while the factory runs after announcing still sends the correction`() = + withSubagents { f -> + val announced = CompletableDeferred() + var outcome: Result? = null + val caller = launch { + outcome = runCatching { + f.rootSubagents.announce(childId, { + it.client.notify(announcement(childId, granted = true)) + announced.complete(Unit) + awaitCancellation() + }) + } + } + withTimeout(5.seconds) { announced.await() } + caller.cancelAndJoin() + + assertIs(outcome?.exceptionOrNull()) + assertEquals(SessionNotification(rootId, announcement(childId, granted = true)), f.nextNotification()) + val correction = SessionUpdate.SubagentUpdate(childId, capabilities = MaybeUndefined.Null) + assertEquals(SessionNotification(rootId, correction), f.nextNotification()) + assertNotNull(f.agent.subagentOrNull(childId)) + } + + @Test + fun `a caller cancelled before the announcement unregisters the child`() = withSubagents { f -> + val started = CompletableDeferred() + var outcome: Result? = null + val caller = launch { + outcome = runCatching { + f.rootSubagents.announce(childId, { + started.complete(Unit) + awaitCancellation() + }) + } + } + withTimeout(5.seconds) { started.await() } + caller.cancelAndJoin() + + assertIs(outcome?.exceptionOrNull()) + assertNull(f.agent.subagentOrNull(childId)) + f.assertNothingMoreSent() + announceChild(f, childId) + } + + /* + * The factory doesn't suspend after the announcement, but its call ends with the caller's cancellation anyway. + */ + @Test + fun `a caller cancelled after the announcement keeps the child registered and never collects its events`() = + withSubagents { f -> + lateinit var caller: Job + f.transport.onSend = { message -> + val update = message.sessionNotificationOrNull()?.update + if (update is SessionUpdate.SubagentUpdate && update.sessionId == childId) caller.cancel() + } + val collected = CompletableDeferred() + lateinit var context: AgentSubagentContext + var outcome: Result? = null + caller = launch { + outcome = runCatching { + f.rootSubagents.announce(childId, { + context = it + it.client.notify(announcement(childId)) + TestSubagent(flow { collected.complete(Unit) }) + }) + } + } + caller.join() + f.transport.onSend = {} + + assertIs(outcome?.exceptionOrNull()) + assertEquals(SessionNotification(rootId, announcement(childId)), f.nextNotification()) + assertTrue(assertNotNull(f.agent.subagentOrNull(childId)).isAnnounced) + context.client.notify(text("still valid")) + assertEquals(SessionNotification(childId, text("still valid")), f.nextNotification()) + f.awaitCollectionsEnded() + assertFalse(collected.isCompleted) + } + + // Routing + + @Test + fun `the opening marker can't be sent through the root's or a child's operations`() = withSubagents { f -> + val child = announceChild(f, childId) + + assertFailsWith { f.rootClient.notify(SessionEvent.Opened(LoadSessionResponse())) } + assertFailsWith { child.client.notify(SessionEvent.Opened(null)) } + f.assertNothingMoreSent() + } + + @Test + fun `a SubagentUpdate for another session is rejected by a child's operations`() = withSubagents { f -> + val child = announceChild(f, childId) + + assertFailsWith { child.client.notify(announcement(grandchildId)) } + assertFailsWith { child.client.notify(announcement(rootId)) } + f.assertNothingMoreSent() + } + + @Test + fun `a child's session messages and session references go on the child's stream`() = withSubagents { f -> + val child = announceChild(f, childId) + + for (update in subagentsDefinedUpdates()) { + child.client.notify(update) + assertEquals(SessionNotification(childId, update), f.nextNotification()) + } + } + + @Test + fun `updates sent through the child's coroutine context go on the child's stream`() = withSubagents { f -> + f.rootSubagents.announce(childId, announcing(flow { + currentCoroutineContext().client.notify(text("from context")) + })) + + assertEquals(SessionNotification(rootId, announcement(childId)), f.nextNotification()) + assertEquals(SessionNotification(childId, text("from context")), f.nextNotification()) + } + + @Test + fun `an announcement goes on its parent's stream, including an explicit descendant parent`() = withSubagents { f -> + val child = announceChild(f, childId) + child.subagents.announce(grandchildId, announcing(flowOf(text("grand")))) + assertEquals(SessionNotification(childId, announcement(grandchildId)), f.nextNotification()) + assertEquals(SessionNotification(grandchildId, text("grand")), f.nextNotification()) + + val greatGrandchildId = SessionId("great-grandchild") + f.rootSubagents.announce(greatGrandchildId, announcing(), parent = grandchildId) + f.rootSubagents.announce(siblingId, announcing(), parent = rootId) + + assertEquals(SessionNotification(grandchildId, announcement(greatGrandchildId)), f.nextNotification()) + assertEquals(SessionNotification(rootId, announcement(siblingId)), f.nextNotification()) + } + + // Root session checks + + @Test + fun `a root rejects any SubagentUpdate, with and without the capability, also from a prompt flow`() { + for (capability in listOf(true, false)) { + withSubagents(subagentsCapability = capability) { f -> + val failure = assertFailsWith { f.rootClient.notify(announcement(childId)) } + assertTrue(failure.message!!.contains("subagents.announce"), failure.message) + f.assertNothingMoreSent() + + f.root.promptHandler = { emit(Event.SessionUpdateEvent(announcement(childId))) } + assertPromptFails(f) + } + } + } + + @Test + fun `a root without the capability has no subagents and rejects subagents updates`() = + withSubagents(subagentsCapability = false) { f -> + assertNull(f.rootContext.subagents) + for (update in subagentsDefinedUpdates()) { + val failure = assertFailsWith { f.rootClient.notify(update) } + assertEquals("Client does not support subagents capability", failure.message) + + f.root.promptHandler = { emit(Event.SessionUpdateEvent(update)) } + assertPromptFails(f) + } + f.assertNothingMoreSent() + + val plainToolCall = SessionUpdate.ToolCall( + ToolCallId("plain"), + "Plain", + content = listOf(ToolCallContent.Content(ContentBlock.Text("output"))), + ) + f.rootClient.notify(plainToolCall) + assertEquals(SessionNotification(rootId, plainToolCall), f.nextNotification()) + } + + @Test + fun `a root with the capability sends subagents updates, also from a prompt flow`() = withSubagents { f -> + val updates = subagentsDefinedUpdates() + for (update in updates) { + f.rootClient.notify(update) + assertEquals(SessionNotification(rootId, update), f.nextNotification()) + } + + f.root.promptHandler = { updates.forEach { emit(Event.SessionUpdateEvent(it)) } } + val (response, notifications) = f.transport.testRequest( + AcpMethod.AgentMethods.V1.SessionPrompt, + PromptRequest(rootId, listOf(ContentBlock.Text("go"))), + ) + assertEquals(StopReason.END_TURN, response?.stopReason) + assertEquals(updates.map { SessionNotification(rootId, it) }, notifications.map { it.sessionNotificationOrNull() }) + } + + // session/cancel on a child id + + @Test + fun `session cancel on a granted child calls its cancel in the child's context`() = withSubagents { f -> + val cancelClients = Channel(Channel.UNLIMITED) + val events = Channel(Channel.UNLIMITED) + lateinit var context: AgentSubagentContext + f.rootSubagents.announce(childId, { + context = it + it.client.notify(announcement(childId, granted = true)) + TestSubagent(events.consumeAsFlow(), onCancel = { cancelClients.send(currentCoroutineContext().client) }) + }) + f.nextNotification() + + f.fireCancel(childId) + + assertSame(context.client, withTimeout(5.seconds) { cancelClients.receive() }) + events.send(text("still collected")) + assertEquals(SessionNotification(childId, text("still collected")), f.nextNotification()) + f.assertNothingMoreSent() + events.close() + } + + @Test + fun `session cancel on a child without a grant in effect is ignored`() { + val revokeWithNull = SessionUpdate.SubagentUpdate(childId, capabilities = MaybeUndefined.Null) + val revokeWithoutCancel = + SessionUpdate.SubagentUpdate(childId, capabilities = MaybeUndefined.Value(SubagentSessionCapabilities())) + val setups: List) -> Unit>> = listOf( + "never granted" to { f, cancels -> + announce(f.rootSubagents, childId, cancels = cancels) + f.nextNotification() + }, + "revoked with null capabilities" to { f, cancels -> + val events = flow { emit(revokeWithNull); awaitCancellation() } + announce(f.rootSubagents, childId, granted = true, events = events, cancels = cancels) + repeat(2) { f.nextNotification() } + }, + "revoked with capabilities without cancel" to { f, cancels -> + val events = flow { emit(revokeWithoutCancel); awaitCancellation() } + announce(f.rootSubagents, childId, granted = true, events = events, cancels = cancels) + repeat(2) { f.nextNotification() } + }, + "granted by a factory that then threw" to { f, _ -> + assertFailsWith { + f.rootSubagents.announce(childId, { + it.client.notify(announcement(childId, granted = true)) + throw RuntimeException("factory failed late") + }) + } + repeat(2) { f.nextNotification() } + }, + ) + for ((name, setup) in setups) { + withSubagents { f -> + val cancels = Channel(Channel.UNLIMITED) + setup(f, cancels) + announceProbe(f, cancels) + + assertCancelIgnored(f, childId, cancels) + assertNotNull(f.agent.subagentOrNull(childId), name) + } + } + } + + @Test + fun `session cancel handled while the grant is still being sent is routed`() = withSubagents { f -> + val cancels = Channel(Channel.UNLIMITED) + announceProbe(f, cancels) + val child = announce(f.rootSubagents, childId, cancels = cancels) + f.nextNotification() + // The blocked send below holds the child's lock, which the end of its feed would wait for. + f.awaitCollectionsEnded() + val grantUpdate = SessionUpdate.SubagentUpdate(childId, capabilities = MaybeUndefined.Value(grant())) + var firstCancelled: SessionId? = null + /* + * The grant's send doesn't return until a cancel has been handled, so the child's cancel is routed only if the + * grant was recorded before the send. Otherwise the probe's cancel, handled after it, is the first. + */ + f.transport.onSend = { message -> + if (message.sessionNotificationOrNull()?.update == grantUpdate) { + f.fireCancel(childId) + f.fireCancel(probeId) + firstCancelled = runBlocking { withTimeout(5.seconds) { cancels.receive() } } + } + } + + // Off the thread that reads incoming messages, which the blocked send would otherwise stall. + withContext(Dispatchers.IO) { child.client.notify(grantUpdate) } + + assertEquals(childId, firstCancelled) + assertEquals(probeId, withTimeout(5.seconds) { cancels.receive() }) + } + + @Test + fun `a grant change whose send fails is undone, so session cancel is routed as before it`() { + val changes = listOf( + false to SessionUpdate.SubagentUpdate(childId, capabilities = MaybeUndefined.Value(grant())), + true to SessionUpdate.SubagentUpdate(childId, capabilities = MaybeUndefined.Null), + ) + for ((granted, change) in changes) { + withSubagents { f -> + val cancels = Channel(Channel.UNLIMITED) + announceProbe(f, cancels) + val child = announce(f.rootSubagents, childId, granted = granted, cancels = cancels) + f.nextNotification() + f.transport.onSend = { message -> + if (message.sessionNotificationOrNull()?.update == change) throw UncopiedException("send failed") + } + + assertFailsWith { child.client.notify(change) } + f.transport.onSend = {} + + assertEquals(granted, assertNotNull(f.agent.subagentOrNull(childId)).isCancelGranted, "granted $granted") + if (granted) { + f.fireCancel(childId) + assertEquals(childId, withTimeout(5.seconds) { cancels.receive() }) + } else { + assertCancelIgnored(f, childId, cancels) + } + f.assertNothingMoreSent() + } + } + } + + @Test + fun `a throwing cancel does not break the connection`() = withSubagents { f -> + val cancels = Channel(Channel.UNLIMITED) + f.rootSubagents.announce(childId, { + it.client.notify(announcement(childId, granted = true)) + TestSubagent(onCancel = { + cancels.send(childId) + throw RuntimeException("cancel failed") + }) + }) + f.nextNotification() + announceProbe(f, cancels) + + repeat(2) { + f.fireCancel(childId) + assertEquals(childId, withTimeout(5.seconds) { cancels.receive() }) + } + f.fireCancel(probeId) + assertEquals(probeId, withTimeout(5.seconds) { cancels.receive() }) + val (response, _) = f.transport.testRequest( + AcpMethod.AgentMethods.V1.SessionPrompt, + PromptRequest(rootId, listOf(ContentBlock.Text("go"))), + ) + assertEquals(StopReason.END_TURN, response?.stopReason) + } + + @Test + fun `each session cancel held while a granted factory runs is delivered after it returns`() = withSubagents { f -> + val cancels = Channel(Channel.UNLIMITED) + val cancelClients = Channel(Channel.UNLIMITED) + announceProbe(f, cancels) + val session = TestSubagent(onCancel = { + cancelClients.send(currentCoroutineContext().client) + cancels.send(childId) + }) + + withHeldFactory(f, f.rootSubagents, announcement(childId, granted = true), { session }) { held -> + // Two cancels while the factory runs: the probe's cancel proves both were handled, and held. + repeat(2) { f.fireCancel(childId) } + f.fireCancel(probeId) + assertEquals(probeId, withTimeout(5.seconds) { cancels.receive() }) + assertTrue(cancels.isEmpty) + held.release.complete(Unit) + withTimeout(5.seconds) { held.announcing.await() }.getOrThrow() + + repeat(2) { + assertEquals(childId, withTimeout(5.seconds) { cancels.receive() }) + assertSame(held.context.client, cancelClients.receive()) + } + f.fireCancel(probeId) + assertEquals(probeId, withTimeout(5.seconds) { cancels.receive() }) + assertTrue(cancels.isEmpty) + } + } + + @Test + fun `a held session cancel ends without a call when the factory throws or the root is closed`() { + for (factoryThrows in listOf(true, false)) { + withSubagents { f -> + val cancels = Channel(Channel.UNLIMITED) + announceProbe(f, cancels) + val closingSubagents = assertNotNull(f.newRoot(RootSession(closingId)).subagents) + val afterRelease: suspend (AgentSubagentContext) -> AgentSubagentSession = { + if (factoryThrows) throw RuntimeException("factory failed late") + TestSubagent(onCancel = { cancels.send(childId) }) + } + + withHeldFactory(f, closingSubagents, announcement(childId, granted = true), afterRelease) { held -> + val child = assertNotNull(f.agent.subagentOrNull(childId)) + val heldCancel = async(start = CoroutineStart.UNDISPATCHED) { child.cancel() } + f.fireCancel(childId) + f.fireCancel(probeId) + assertEquals(probeId, withTimeout(5.seconds) { cancels.receive() }) + assertFalse(heldCancel.isCompleted, "the cancel waits for the factory") + + if (factoryThrows) { + held.release.complete(Unit) + assertIs(withTimeout(5.seconds) { held.announcing.await() }.exceptionOrNull()) + withTimeout(5.seconds) { heldCancel.await() } + // The correction that revokes the grant. + f.nextNotification() + } else { + assertIs(f.close(closingId).single()) + // Before the factory returns. + withTimeout(5.seconds) { heldCancel.await() } + held.release.complete(Unit) + withTimeout(5.seconds) { held.announcing.await() }.getOrThrow() + } + assertCancelIgnored(f, childId, cancels) + } + } + } + } + + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `a held session cancel is dropped when the root is closed before it resumes`() = withSubagents { f -> + val cancels = Channel(Channel.UNLIMITED) + val closingSubagents = assertNotNull(f.newRoot(RootSession(closingId)).subagents) + val session = TestSubagent(onCancel = { cancels.send(childId) }) + + withHeldFactory(f, closingSubagents, announcement(childId, granted = true), { session }) { held -> + val child = assertNotNull(f.agent.subagentOrNull(childId)) + // The held cancel resumes only when this dispatcher runs, after the factory returned and the root closed. + val dispatcher = StandardTestDispatcher() + val heldCancel = async(dispatcher) { child.cancel() } + try { + dispatcher.scheduler.runCurrent() + assertFalse(heldCancel.isCompleted, "the cancel waits for the factory") + + held.release.complete(Unit) + withTimeout(5.seconds) { held.announcing.await() }.getOrThrow() + assertIs(f.close(closingId).single()) + dispatcher.scheduler.runCurrent() + + assertTrue(heldCancel.isCompleted) + assertTrue(cancels.isEmpty) + } finally { + heldCancel.cancel() + dispatcher.scheduler.runCurrent() + } + } + } + + /* + * The grant in effect when a cancel arrives decides whether it is held, and the grant in effect when the factory + * returns decides whether a held cancel is delivered. + */ + @Test + fun `session cancel while the factory runs is not delivered without a grant on arrival and on return`() { + val grants = listOf( + // Granted only after the cancel arrived. + announcement(childId) to SessionUpdate.SubagentUpdate(childId, capabilities = MaybeUndefined.Value(grant())), + // Revoked before the held cancel is delivered. + announcement(childId, granted = true) to SessionUpdate.SubagentUpdate(childId, capabilities = MaybeUndefined.Null), + ) + for ((announced, beforeReturn) in grants) { + withSubagents { f -> + val cancels = Channel(Channel.UNLIMITED) + announceProbe(f, cancels) + val afterRelease: suspend (AgentSubagentContext) -> AgentSubagentSession = { context -> + context.client.notify(beforeReturn) + TestSubagent(onCancel = { cancels.send(childId) }) + } + + withHeldFactory(f, f.rootSubagents, announced, afterRelease) { held -> + assertCancelIgnored(f, childId, cancels) + held.release.complete(Unit) + withTimeout(5.seconds) { held.announcing.await() }.getOrThrow() + assertEquals(SessionNotification(rootId, beforeReturn), f.nextNotification()) + + f.awaitCollectionsEnded() + assertTrue(cancels.isEmpty) + } + } + } + } + + @Test + fun `session cancel while a replaying factory runs is not held`() = withSubagents { f -> + val loaded = RootSession(loadedId) + val cancels = Channel(Channel.UNLIMITED) + announceProbe(f, cancels) + loaded.replay = { + currentSubagents().announce(childId, { context -> + context.client.notify(announcement(childId, granted = true)) + // A history grant is never in effect, so this cancel is ignored rather than held. + f.fireCancel(childId) + f.fireCancel(probeId) + assertEquals(probeId, withTimeout(5.seconds) { cancels.receive() }) + TestSubagent(onCancel = { cancels.send(childId) }) + }) + } + + assertIs(f.load(loaded).last()) + + f.awaitCollectionsEnded(loaded.wrapper()) + assertTrue(cancels.isEmpty) + } + + @Test + fun `session cancel is still routed after the feed ended`() = withSubagents { f -> + val cancels = Channel(Channel.UNLIMITED) + val running = stateUpdate(childId, StateUpdate.Running()) + announce(f.rootSubagents, childId, granted = true, events = flowOf(running), cancels = cancels) + repeat(2) { f.nextNotification() } + assertEquals(SessionNotification(rootId, stateUpdate(childId, StateUpdate.Unknown())), f.nextNotification()) + f.awaitCollectionsEnded() + + f.fireCancel(childId) + + assertEquals(childId, withTimeout(5.seconds) { cancels.receive() }) + assertTrue(assertNotNull(f.agent.subagentOrNull(childId)).isCancelGranted) + } + + // Other session methods on a child id + + @Test + fun `session methods on a child id are rejected as a subagent's, and on an unknown id not`() = withSubagents { f -> + announceChild(f, childId) + + for ((name, request) in sessionRequests(f, childId)) { + val response = assertIs(request(), name) + assertEquals(JsonRpcErrorCode.INVALID_PARAMS.code, response.error.code, name) + assertEquals("Session $childId is a subagent", response.error.message, name) + } + assertTrue(assertNotNull(f.agent.subagentOrNull(childId)).isAnnounced) + + val unknownId = SessionId("unknown") + val lookups = setOf("prompt", "set_mode", "set_model", "set_config_option") + // An unknown id's close is answered with an empty result. + for ((name, request) in sessionRequests(f, unknownId).filter { it.first != "close" }) { + val response = assertIs(request(), name) + if (name in lookups) { + assertEquals("Session $unknownId not found", response.error.message, name) + } else { + assertNotEquals("Session $unknownId is a subagent", response.error.message, name) + } + } + f.assertNothingMoreSent() + } + + @Test + fun `a close of an unknown or closed id answers an empty result`() = withSubagents { f -> + val unknownId = SessionId("unknown") + assertEquals(CloseSessionResponse(), closeResult(f.close(unknownId).single())) + + val closing = RootSession(closingId) + f.newRoot(closing) + val closes = AtomicInteger() + closing.onClose = { closes.incrementAndGet() } + repeat(2) { assertEquals(CloseSessionResponse(), closeResult(f.close(closingId).single()), "close ${it + 1}") } + assertEquals(1, closes.get(), "only the first close reaches the app") + f.assertNothingMoreSent() + } + + // Feed end + + @Test + fun `a feed that ends reports unknown only while the child is active`() = withSubagents { f -> + val endings = listOf( + Triple("running", listOf(StateUpdate.Running()), true), + Triple("requires-action", listOf(StateUpdate.RequiresAction()), true), + Triple("other", listOf(StateUpdate.Other("paused")), true), + Triple("idle", listOf(StateUpdate.Running(), StateUpdate.Idle(IdleStopReason.EndTurn)), false), + Triple("unknown", listOf(StateUpdate.Running(), StateUpdate.Unknown()), false), + Triple("none", emptyList(), false), + Triple("cleared", listOf(StateUpdate.Running(), null), false), + ) + for ((name, states, owesUnknown) in endings) { + for (fails in listOf(false, true)) { + val id = SessionId("child-$name-$fails") + val updates = states.map { state -> + SessionUpdate.SubagentUpdate(id, state = state?.let { MaybeUndefined.Value(it) } ?: MaybeUndefined.Null) + } + f.rootSubagents.announce(id, announcing(flow { + updates.forEach { emit(it) } + if (fails) throw RuntimeException("feed down") + })) + + assertEquals(SessionNotification(rootId, announcement(id)), f.nextNotification()) + for (update in updates) assertEquals(SessionNotification(rootId, update), f.nextNotification()) + if (owesUnknown) { + assertEquals(SessionNotification(rootId, stateUpdate(id, StateUpdate.Unknown())), f.nextNotification()) + } + f.awaitCollectionsEnded() + f.assertNothingMoreSent() + assertNotNull(f.agent.subagentOrNull(id)) + } + } + } + + @Test + fun `a cancellation thrown by the app's feed reports unknown and completes the collection`() = withSubagents { f -> + val collectionJob = CompletableDeferred() + f.rootSubagents.announce(childId, announcing(flow { + collectionJob.complete(currentCoroutineContext().job) + emit(stateUpdate(childId, StateUpdate.Running())) + throw CancellationException("app timeout") + })) + + repeat(2) { f.nextNotification() } + assertEquals(SessionNotification(rootId, stateUpdate(childId, StateUpdate.Unknown())), f.nextNotification()) + val collection = withTimeout(5.seconds) { collectionJob.await() } + withTimeout(5.seconds) { collection.join() } + assertFalse(collection.isCancelled) + f.assertNothingMoreSent() + } + + @Test + fun `a collection the SDK cancels sends nothing, however the feed ends`() { + val endings: List Unit> = listOf( + { awaitCancellation() }, + { runCatching { awaitCancellation() } }, + { runCatching { awaitCancellation() }; throw RuntimeException("feed down on cancel") }, + ) + for (ending in endings) { + withSubagents { f -> + val waiting = CompletableDeferred() + f.rootSubagents.announce(childId, announcing(flow { + emit(stateUpdate(childId, StateUpdate.Running())) + waiting.complete(Unit) + ending() + })) + repeat(2) { f.nextNotification() } + withTimeout(5.seconds) { waiting.await() } + + f.rootWrapper.subtreeScope.cancel() + + f.awaitCollectionsEnded() + f.assertNothingMoreSent() + } + } + } + + @Test + fun `state sent through the child's client operations does not make a feed owe unknown`() = withSubagents { f -> + val running = stateUpdate(childId, StateUpdate.Running()) + f.rootSubagents.announce(childId, { + it.client.notify(announcement(childId, state = StateUpdate.Running())) + TestSubagent(flow { currentCoroutineContext().client.notify(running) }) + }) + + assertEquals(SessionNotification(rootId, announcement(childId, state = StateUpdate.Running())), f.nextNotification()) + assertEquals(SessionNotification(rootId, running), f.nextNotification()) + f.awaitCollectionsEnded() + f.assertNothingMoreSent() + } + + @Test + fun `a child whose feed ended keeps its id and can be named as a parent`() = withSubagents { f -> + f.rootSubagents.announce(childId, announcing()) + f.nextNotification() + f.awaitCollectionsEnded() + + assertFailsWith { f.rootSubagents.announce(childId, { TestSubagent() }) } + f.rootSubagents.announce(grandchildId, announcing(), parent = childId) + + assertEquals(SessionNotification(childId, announcement(grandchildId)), f.nextNotification()) + } + + @Test + fun `a feed that ends while active does not affect a sibling's collection`() = withSubagents { f -> + val release = CompletableDeferred() + f.rootSubagents.announce(childId, announcing(flow { + emit(stateUpdate(childId, StateUpdate.Running())) + release.await() + throw RuntimeException("child feed down") + })) + val siblingEvents = Channel(Channel.UNLIMITED) + f.rootSubagents.announce(siblingId, announcing(flow { + emit(stateUpdate(siblingId, StateUpdate.Running())) + emitAll(siblingEvents) + })) + repeat(4) { f.nextNotification() } + + release.complete(Unit) + assertEquals(SessionNotification(rootId, stateUpdate(childId, StateUpdate.Unknown())), f.nextNotification()) + siblingEvents.send(text("sibling alive")) + + assertEquals(SessionNotification(siblingId, text("sibling alive")), f.nextNotification()) + f.assertNothingMoreSent() + siblingEvents.close() + } + + // Subtree cleanup + + @Test + fun `closing a root sends the children's final updates before the response and nothing about them after it`() = + withSubagents { f -> + val closing = RootSession(closingId) + val closingContext = f.newRoot(closing) + val childStopped = CompletableDeferred() + val grandchildStopped = CompletableDeferred() + val child = announceActive(assertNotNull(closingContext.subagents), childId, childStopped) + assertEquals(closingId, f.nextNotification().sessionId) + val grandchild = announceActive(child.subagents, grandchildId, grandchildStopped) + assertEquals(childId, f.nextNotification().sessionId) + + closing.onClose = { + child.client.notify(text("final child")) + grandchild.client.notify(text("final grandchild")) + } + val received = f.close(closingId) + + assertSentBeforeResponse( + listOf(SessionNotification(childId, text("final child")), SessionNotification(grandchildId, text("final grandchild"))), + received, + ) + withTimeout(5.seconds) { + childStopped.await() + grandchildStopped.await() + } + f.awaitCollectionsEnded(closingContext.rootWrapper) + f.assertNothingMoreSent() + } + + @Test + fun `after a root is closed its subagents are gone at every depth`() = withSubagents { f -> + val closingContext = f.newRoot(RootSession(closingId)) + val closingSubagents = assertNotNull(closingContext.subagents) + val cancels = Channel(Channel.UNLIMITED) + val child = announce(closingSubagents, childId, granted = true, cancels = cancels) + val grandchild = announce(child.subagents, grandchildId, granted = true, cancels = cancels) + repeat(2) { f.nextNotification() } + + assertIs(f.close(closingId).single()) + + for ((id, context) in listOf(childId to child, grandchildId to grandchild)) { + assertNull(f.agent.subagentOrNull(id)) + for (operation in childOperations(context)) { + val failure = assertFailsWith { operation() } + assertTrue(failure.message!!.contains("not registered"), failure.message) + } + assertFailsWith { context.subagents.announce(SessionId("late"), { TestSubagent() }) } + assertFailsWith { + f.rootSubagents.announce(SessionId("orphan"), { TestSubagent() }, parent = id) + } + } + assertFailsWith { closingSubagents.announce(SessionId("late"), { TestSubagent() }) } + + announceProbe(f, cancels) + assertCancelIgnored(f, childId, cancels) + assertCancelIgnored(f, grandchildId, cancels) + f.assertNothingMoreSent() + + val reused = announceChild(f, childId) + reused.subagents.announce(grandchildId, announcing()) + assertEquals(SessionNotification(childId, announcement(grandchildId)), f.nextNotification()) + } + + @Test + fun `removing a root while a factory runs before its announcement fails its sends and its announce`() { + val removals: List RootSession>> = listOf( + "close" to { f -> + assertIs(f.close(loadedId).single()) + f.root + }, + "resume" to { f -> RootSession(loadedId).also { assertIs(f.resume(it)) } }, + ) + for ((name, remove) in removals) { + withSubagents { f -> + val removed = RootSession(loadedId) + assertIs(f.resume(removed)) + val removedSubagents = assertNotNull(removed.wrapper().subagents) + var sendFailure: Throwable? = null + val afterRelease: suspend (AgentSubagentContext) -> AgentSubagentSession = { context -> + // A factory that swallows the failure and returns still fails its announce. + sendFailure = runCatching { context.client.notify(announcement(childId)) }.exceptionOrNull() + TestSubagent() + } + + withHeldFactory(f, removedSubagents, announcement = null, afterRelease) { held -> + val live = remove(f) + held.release.complete(Unit) + + val failure = assertIs(held.announcing.await().exceptionOrNull(), name) + assertTrue(failure.message!!.contains("not announced"), failure.message) + assertIs(sendFailure, name) + assertNull(f.agent.subagentOrNull(childId)) + assertFailsWith { removedSubagents.announce(siblingId, announcing()) } + assertNull(f.agent.subagentOrNull(siblingId)) + f.assertNothingMoreSent() + + assertNotNull(live.wrapper().subagents).announce(childId, announcing()) + assertEquals(SessionNotification(live.sessionId, announcement(childId)), f.nextNotification()) + } + } + } + } + + @Test + fun `a close that throws leaves the subagents registered and working`() = withSubagents { f -> + val closing = RootSession(closingId) + val closingSubagents = assertNotNull(f.newRoot(closing).subagents) + val events = Channel(Channel.UNLIMITED) + val child = announce(closingSubagents, childId, events = events.consumeAsFlow()) + f.nextNotification() + closing.onClose = { throw RuntimeException("close failed") } + + assertIs(f.close(closingId).single()) + + assertTrue(assertNotNull(f.agent.subagentOrNull(childId)).isAnnounced) + events.send(text("from events")) + assertEquals(SessionNotification(childId, text("from events")), f.nextNotification()) + child.client.notify(text("from client")) + assertEquals(SessionNotification(childId, text("from client")), f.nextNotification()) + child.subagents.announce(grandchildId, announcing()) + assertEquals(SessionNotification(childId, announcement(grandchildId)), f.nextNotification()) + closingSubagents.announce(siblingId, announcing()) + assertEquals(SessionNotification(closingId, announcement(siblingId)), f.nextNotification()) + events.close() + } + + /* + * Nothing can be sent once the connection has ended, so whether the SDK would report `unknown` for these + * collections can't be observed here. `a collection the SDK cancels sends nothing, however the feed ends` covers + * that rule. + */ + @Test + fun `the connection's end cancels the collections at every depth`() { + val endings: List<(Fixture) -> Unit> = listOf({ it.protocol.close() }, { it.transport.close() }) + for (ending in endings) { + withSubagents { f -> + val childStopped = CompletableDeferred() + val grandchildStopped = CompletableDeferred() + val child = announceActive(f.rootSubagents, childId, childStopped) + f.nextNotification() + announceActive(child.subagents, grandchildId, grandchildStopped) + f.nextNotification() + + ending(f) + + withTimeout(5.seconds) { + childStopped.await() + grandchildStopped.await() + } + } + } + } + + @Test + fun `a feed that ends leaves the collections of the child's subagents running`() = withSubagents { f -> + val release = CompletableDeferred() + val child = announce(f.rootSubagents, childId, events = flow { + emit(stateUpdate(childId, StateUpdate.Running())) + release.await() + }) + repeat(2) { f.nextNotification() } + val grandchildEvents = Channel(Channel.UNLIMITED) + child.subagents.announce(grandchildId, announcing(grandchildEvents.consumeAsFlow())) + f.nextNotification() + + release.complete(Unit) + assertEquals(SessionNotification(rootId, stateUpdate(childId, StateUpdate.Unknown())), f.nextNotification()) + grandchildEvents.send(text("grandchild alive")) + + assertEquals(SessionNotification(grandchildId, text("grandchild alive")), f.nextNotification()) + assertNotNull(f.agent.subagentOrNull(childId)) + grandchildEvents.close() + } + + // Replay during session/load + + @Test + fun `a history grant does not route session cancel, a fresh grant after the response does`() = withSubagents { f -> + val loaded = RootSession(loadedId) + val cancels = Channel(Channel.UNLIMITED) + val events = Channel(Channel.UNLIMITED) + loaded.replay = { + announce(currentSubagents(), childId, granted = true, events = events.consumeAsFlow(), cancels = cancels) + } + assertIs(f.load(loaded).last()) + + assertFalse(assertNotNull(f.agent.subagentOrNull(childId)).isCancelGranted) + announceProbe(f, cancels) + assertCancelIgnored(f, childId, cancels) + + val freshGrant = SessionUpdate.SubagentUpdate(childId, capabilities = MaybeUndefined.Value(grant())) + events.send(freshGrant) + assertEquals(SessionNotification(loadedId, freshGrant), f.nextNotification()) + f.fireCancel(childId) + assertEquals(childId, withTimeout(5.seconds) { cancels.receive() }) + events.close() + } + + @Test + fun `a history running state does not make an ending feed owe unknown`() = withSubagents { f -> + val loaded = RootSession(loadedId) + loaded.replay = { announce(currentSubagents(), childId, state = StateUpdate.Running()) } + + val received = f.load(loaded) + + assertEquals(2, received.size, "$received") + f.awaitCollectionsEnded(loaded.wrapper()) + f.assertNothingMoreSent() + assertNotNull(f.agent.subagentOrNull(childId)) + } + + @Test + fun `a replaying factory that throws after announcing sends no correction`() = withSubagents { f -> + val loaded = RootSession(loadedId) + var failure: Throwable? = null + loaded.replay = { + failure = runCatching { + currentSubagents().announce(childId, { context -> + context.client.notify(announcement(childId, granted = true, state = StateUpdate.Running())) + throw UncopiedException("factory failed late") + }) + }.exceptionOrNull() + } + + val received = f.load(loaded) + + assertIs(failure) + assertSentBeforeResponse( + listOf(SessionNotification(loadedId, announcement(childId, granted = true, state = StateUpdate.Running()))), + received, + ) + f.assertNothingMoreSent() + assertNotNull(f.agent.subagentOrNull(childId)) + } + + @Test + fun `a replaying factory that returns without announcing fails announce and frees the id`() = withSubagents { f -> + val loaded = RootSession(loadedId) + var failure: Throwable? = null + loaded.replay = { + failure = runCatching { + currentSubagents().announce(childId, { TestSubagent(flowOf(announcement(childId))) }) + }.exceptionOrNull() + currentSubagents().announce(childId, announcing()) + } + + val received = f.load(loaded) + + assertIs(failure) + assertSentBeforeResponse(listOf(SessionNotification(loadedId, announcement(childId))), received) + assertNotNull(f.agent.subagentOrNull(childId)) + f.awaitCollectionsEnded(loaded.wrapper()) + f.assertNothingMoreSent() + } + + @Test + fun `a replayed tree's announcements and history precede the load response and its events follow it`() = + withSubagents { f -> + val loaded = RootSession(loadedId) + val session = TestSubagent(flowOf(text("child live"))) + var announced: AgentSubagentSession? = null + var nestedFailure: Throwable? = null + loaded.replay = { + announced = currentSubagents().announce(childId, { context -> + context.client.notify(announcement(childId)) + context.client.notify(text("child history")) + context.subagents.announce(grandchildId, { grandchild -> + grandchild.client.notify(announcement(grandchildId)) + grandchild.client.notify(text("grandchild history")) + TestSubagent(flowOf(text("grandchild live"))) + }) + nestedFailure = runCatching { + context.subagents.announce(siblingId, { TestSubagent() }) + }.exceptionOrNull() + session + }) + } + + val received = f.load(loaded) + + assertSame(session, announced) + assertSentBeforeResponse( + listOf( + SessionNotification(loadedId, announcement(childId)), + SessionNotification(childId, text("child history")), + SessionNotification(childId, announcement(grandchildId)), + SessionNotification(grandchildId, text("grandchild history")), + ), + received, + ) + assertIs(nestedFailure) + assertNull(f.agent.subagentOrNull(siblingId)) + assertEquals( + setOf(SessionNotification(childId, text("child live")), SessionNotification(grandchildId, text("grandchild live"))), + setOf(f.nextNotification(), f.nextNotification()), + ) + } + + @Test + fun `replayed collections start without waiting for postInitialize`() = withSubagents { f -> + val loaded = RootSession(loadedId) + val liveSeen = CompletableDeferred() + val initialized = CompletableDeferred() + loaded.replay = { announce(currentSubagents(), childId, events = flowOf(text("live"))) } + // Blocks until the child's live event has been seen, so a collection that waited for it would never start. + loaded.afterInitialize = { + liveSeen.await() + initialized.complete(Unit) + } + + assertIs(f.load(loaded).last()) + + assertEquals(SessionNotification(childId, text("live")), f.nextNotification()) + assertFalse(initialized.isCompleted) + liveSeen.complete(Unit) + withTimeout(5.seconds) { initialized.await() } + } + + @Test + fun `replayed collections keep running when postInitialize throws`() = withSubagents { f -> + val loaded = RootSession(loadedId) + val events = Channel(Channel.UNLIMITED) + val failed = CompletableDeferred() + loaded.replay = { announce(currentSubagents(), childId, events = events.consumeAsFlow()) } + loaded.afterInitialize = { + try { + throw RuntimeException("postInitialize failed") + } finally { + failed.complete(Unit) + } + } + + assertIs(f.load(loaded).last()) + withTimeout(5.seconds) { failed.await() } + + events.send(text("still collected")) + assertEquals(SessionNotification(childId, text("still collected")), f.nextNotification()) + events.close() + } + + /* + * The load fails either in its replay or after it, while the SDK builds its response. + */ + @Test + fun `a failed load drops its subagents and a retried load can announce the same ids`() { + for (replayFails in listOf(true, false)) { + withSubagents { f -> + val failing = RootSession(loadedId) + lateinit var failingSubagents: AgentSubagents + lateinit var child: AgentSubagentContext + failing.replay = { + failingSubagents = currentSubagents() + child = replayChildWithGrandchild(flowOf(text("must never be collected"))) + if (replayFails) throw RuntimeException("replay failed") + } + if (!replayFails) failing.responseFailure = RuntimeException("modes unavailable") + + val failed = f.load(failing) + + assertEquals(3, failed.size, "$failed") + assertIs(failed.last()) + assertNull(f.agent.subagentOrNull(childId)) + assertNull(f.agent.subagentOrNull(grandchildId)) + assertSendFailsPromptly { child.client.notify(text("late")) } + assertFailsWith { failingSubagents.announce(siblingId, { TestSubagent() }) } + assertIs( + f.request(AcpMethod.AgentMethods.V1.SessionPrompt, PromptRequest(loadedId, listOf(ContentBlock.Text("go")))) + ) + f.assertNothingMoreSent() + + val retried = RootSession(loadedId) + retried.replay = { replayChildWithGrandchild() } + val received = f.load(retried) + + assertSentBeforeResponse( + listOf(SessionNotification(loadedId, announcement(childId)), SessionNotification(childId, announcement(grandchildId))), + received, + ) + f.awaitCollectionsEnded(retried.wrapper()) + f.assertNothingMoreSent() + } + } + } + + @Test + fun `a grant sent once the load response is queued is live, before the after-response work starts`() = + withSubagents { f -> + val loaded = RootSession(loadedId) + val handlerThreadReleased = CountDownLatch(1) + lateinit var child: AgentSubagentContext + loaded.replay = { + child = announce(currentSubagents(), childId) + /* + * Occupy the single handler thread from the moment the load handler suspends to wait for its + * response to be queued: its after-response work can't start until the test releases it. + */ + val handlerDispatcher = checkNotNull(currentCoroutineContext()[ContinuationInterceptor]) + CoroutineScope(handlerDispatcher).launch { handlerThreadReleased.await(5, TimeUnit.SECONDS) } + } + + try { + assertIs(f.load(loaded).last()) + val freshGrant = SessionUpdate.SubagentUpdate(childId, capabilities = MaybeUndefined.Value(grant())) + child.client.notify(freshGrant) + + assertEquals(SessionNotification(loadedId, freshGrant), f.nextNotification()) + assertTrue(assertNotNull(f.agent.subagentOrNull(childId)).isCancelGranted) + } finally { + handlerThreadReleased.countDown() + } + } + + @Test + fun `an update whose send starts in the replay window precedes the load response, however late the transport takes it`() { + val grant = SessionUpdate.SubagentUpdate(childId, capabilities = MaybeUndefined.Value(grant())) + val history = text("history from another thread") + val updates = listOf( + grant to SessionNotification(loadedId, grant), + history to SessionNotification(childId, history), + ) + for ((update, notification) in updates) { + withSubagents { f -> + val cancels = Channel(Channel.UNLIMITED) + + val received = loadWithReplaySendHeld(f, update, cancels) + + assertSentBeforeResponse( + listOf(SessionNotification(loadedId, announcement(childId)), notification), + received, + "an update counted as history must precede the load response", + ) + assertFalse(assertNotNull(f.agent.subagentOrNull(childId)).isCancelGranted) + announceProbe(f, cancels) + assertCancelIgnored(f, childId, cancels) + } + } + } + + @Test + fun `updates whose send starts while the load is being answered follow the response and are live`() = + withSubagents { f -> + val loaded = RootSession(loadedId) + val cancels = Channel(Channel.UNLIMITED) + val responseSent = CompletableDeferred() + lateinit var lateSends: List> + loaded.replay = { + val child = announce(currentSubagents(), childId, cancels = cancels) + // The load handler marked the window closing before it sends the response. + f.transport.onSend = { message -> + if (message is JsonRpcSuccessResponse && responseSent.complete(Unit)) { + lateSends = startLateSends(child) + } + } + } + + val received = f.load(loaded) + + assertSentBeforeResponse( + listOf(SessionNotification(loadedId, announcement(childId))), + received, + "an update that waits for the load response must not precede it", + ) + assertEquals(lateUpdates(), List(2) { f.nextNotification() }.toSet()) + withTimeout(5.seconds) { lateSends.awaitAll() } + assertTrue(assertNotNull(f.agent.subagentOrNull(childId)).isCancelGranted) + f.fireCancel(childId) + assertEquals(childId, withTimeout(5.seconds) { cancels.receive() }) + } + + @Test + fun `sends waiting for the load to be answered fail when its response can't be built`() = withSubagents { f -> + val loaded = RootSession(loadedId) + val building = CompletableDeferred() + lateinit var lateSends: List> + loaded.replay = { + val child = announce(currentSubagents(), childId) + loaded.onBuildResponse = { if (building.complete(Unit)) lateSends = startLateSends(child) } + } + loaded.responseFailure = RuntimeException("modes unavailable") + + val received = f.load(loaded) + + assertIs(received.last()) + assertLateSendsFail(f, lateSends) + } + + @Test + fun `sends waiting for the load to be answered fail when the load is cancelled`() = withSubagents { f -> + val loaded = RootSession(loadedId) + val history = text("history from another thread") + val historyInTransport = CompletableDeferred() + val handlerSuspended = CompletableDeferred() + val historyReleased = CountDownLatch(1) + f.transport.onSend = { message -> + if (message.sessionNotificationOrNull()?.update == history) { + historyInTransport.complete(Unit) + // The load handler waits for this send, so it is still waiting when the cancel arrives. + historyReleased.await(5, TimeUnit.SECONDS) + } + } + lateinit var child: AgentSubagentContext + loaded.replay = { + child = announce(currentSubagents(), childId) + CoroutineScope(Dispatchers.IO).launch { child.client.notify(history) } + historyInTransport.await() + val handlerDispatcher = checkNotNull(currentCoroutineContext()[ContinuationInterceptor]) + CoroutineScope(handlerDispatcher).launch { handlerSuspended.complete(Unit) } + } + + try { + val loadId = RequestId.create("load") + val load = async { f.load(loaded, loadId) } + handlerSuspended.await() + val lateSends = startLateSends(child) + f.transport.fireTestNotification( + AcpMethod.MetaMethods.CancelRequest.methodName, + ACPJson.encodeToJsonElement( + AcpMethod.MetaMethods.CancelRequest.serializer, + CancelRequestNotification(loadId), + ), + ) + /* + * Removing the cancelled load's subagents takes the child's lock, which the held send keeps: release it + * once the removal has started. + */ + withContext(Dispatchers.IO) { + withTimeout(5.seconds) { while (f.agent.subagentOrNull(childId) != null) yield() } + } + historyReleased.countDown() + + assertIs(withTimeout(5.seconds) { load.await() }.last()) + assertLateSendsFail(f, lateSends) + } finally { + historyReleased.countDown() + } + } + + @Test + fun `subagents announced from postInitialize are live, however the session was opened`() = withSubagents { f -> + val openings: List Unit>> = listOf( + "new" to { session -> f.newRoot(session) }, + "resume" to { session -> assertNotNull(f.resume(session)) }, + "load" to { session -> assertIs(f.load(session).single()) }, + ) + val cancels = Channel(Channel.UNLIMITED) + for ((name, open) in openings) { + val session = RootSession(SessionId("root-$name")) + val id = SessionId("child-$name") + val announced = CompletableDeferred() + session.afterInitialize = { + announced.complete(currentSubagents().announce(id, { + it.client.notify(announcement(id, granted = true)) + TestSubagent(onCancel = { cancels.send(id) }) + })) + } + + open(session) + + assertEquals(SessionNotification(session.sessionId, announcement(id, granted = true)), f.nextNotification()) + withTimeout(5.seconds) { announced.await() } + assertTrue(assertNotNull(f.agent.subagentOrNull(id)).isCancelGranted, name) + f.fireCancel(id) + assertEquals(id, withTimeout(5.seconds) { cancels.receive() }, name) + } + } + + // Re-opening a root that is already open + + @Test + fun `reloading an open root replaces its subagents, and its replay can announce the same ids`() = withSubagents { f -> + val first = RootSession(loadedId) + val oldTree = ReplayedTree() + first.replay = { oldTree.replay() } + assertIs(f.load(first).last()) + val oldChild = assertNotNull(f.agent.subagentOrNull(childId)) + + val second = RootSession(loadedId) + second.replay = { replayChildWithGrandchild() } + val received = f.load(second) + + assertSentBeforeResponse( + listOf(SessionNotification(loadedId, announcement(childId)), SessionNotification(childId, announcement(grandchildId))), + received, + ) + oldTree.awaitStopped() + val newChild = assertNotNull(f.agent.subagentOrNull(childId)) + assertNotSame(oldChild, newChild) + assertSame(second.wrapper(), newChild.root) + assertSame(second.wrapper(), assertNotNull(f.agent.subagentOrNull(grandchildId)).root) + for (context in listOf(oldTree.child, oldTree.grandchild)) { + for (operation in childOperations(context)) { + assertFailsWith { operation() } + } + } + assertIs( + f.request(AcpMethod.AgentMethods.V1.SessionPrompt, PromptRequest(loadedId, listOf(ContentBlock.Text("go")))) + ) + f.awaitCollectionsEnded(first.wrapper()) + f.awaitCollectionsEnded(second.wrapper()) + f.assertNothingMoreSent() + } + + @Test + fun `resuming an open root stops its subagents and frees their ids, and closing it leaves nothing behind`() = + withSubagents { f -> + val first = RootSession(loadedId) + assertIs(f.resume(first)) + val firstSubagents = assertNotNull(first.wrapper().subagents) + val cancels = Channel(Channel.UNLIMITED) + val childStopped = CompletableDeferred() + val grandchildStopped = CompletableDeferred() + val child = announceActive(firstSubagents, childId, childStopped, cancels) + assertEquals(loadedId, f.nextNotification().sessionId) + announceActive(child.subagents, grandchildId, grandchildStopped, cancels) + assertEquals(childId, f.nextNotification().sessionId) + + val second = RootSession(loadedId) + assertIs(f.resume(second)) + + withTimeout(5.seconds) { + childStopped.await() + grandchildStopped.await() + } + f.awaitCollectionsEnded(first.wrapper()) + assertNull(f.agent.subagentOrNull(childId)) + assertNull(f.agent.subagentOrNull(grandchildId)) + announceProbe(f, cancels) + assertCancelIgnored(f, childId, cancels) + assertCancelIgnored(f, grandchildId, cancels) + assertFailsWith { firstSubagents.announce(siblingId, { TestSubagent() }) } + assertNull(f.agent.subagentOrNull(siblingId)) + // Nothing for the old children, not even `unknown` for their running state. + f.assertNothingMoreSent() + + val newChildStopped = CompletableDeferred() + announceActive(assertNotNull(second.wrapper().subagents), childId, newChildStopped, cancels) + assertEquals(SessionNotification(loadedId, announcement(childId, granted = true, state = StateUpdate.Running())), f.nextNotification()) + assertIs(f.close(loadedId).single()) + withTimeout(5.seconds) { newChildStopped.await() } + assertNull(f.agent.subagentOrNull(childId)) + f.awaitCollectionsEnded(second.wrapper()) + f.assertNothingMoreSent() + } + + @Test + fun `a factory that throws on re-opening leaves the open root and its subagents working`() = withSubagents { f -> + val first = RootSession(loadedId) + val prompted = Channel(Channel.UNLIMITED) + first.promptHandler = { prompted.send(Unit) } + assertIs(f.resume(first)) + val firstSubagents = assertNotNull(first.wrapper().subagents) + val cancels = Channel(Channel.UNLIMITED) + val events = Channel(Channel.UNLIMITED) + announce(firstSubagents, childId, granted = true, events = events.consumeAsFlow(), cancels = cancels) + f.nextNotification() + val child = assertNotNull(f.agent.subagentOrNull(childId)) + + f.openable.failure = RuntimeException("cannot open") + assertIs(f.load(RootSession(loadedId)).single()) + assertIs(f.resume(RootSession(loadedId))) + f.openable.failure = null + + assertSame(child, f.agent.subagentOrNull(childId)) + events.send(text("still collected")) + assertEquals(SessionNotification(childId, text("still collected")), f.nextNotification()) + f.fireCancel(childId) + assertEquals(childId, withTimeout(5.seconds) { cancels.receive() }) + firstSubagents.announce(siblingId, announcing()) + assertEquals(SessionNotification(loadedId, announcement(siblingId)), f.nextNotification()) + assertIs( + f.request(AcpMethod.AgentMethods.V1.SessionPrompt, PromptRequest(loadedId, listOf(ContentBlock.Text("go")))) + ) + withTimeout(5.seconds) { prompted.receive() } + events.close() + } + + @Test + fun `a failed replay on reloading an open root leaves no subagents behind`() = withSubagents { f -> + val first = RootSession(loadedId) + val oldTree = ReplayedTree() + first.replay = { oldTree.replay() } + assertIs(f.load(first).last()) + + val second = RootSession(loadedId) + lateinit var newChild: AgentSubagentContext + second.replay = { + newChild = announce(currentSubagents(), childId, events = flowOf(text("must never be collected"))) + throw RuntimeException("replay failed") + } + val failed = f.load(second) + + assertSentBeforeResponse(listOf(SessionNotification(loadedId, announcement(childId))), failed, success = false) + assertNull(f.agent.subagentOrNull(childId)) + assertNull(f.agent.subagentOrNull(grandchildId)) + oldTree.awaitStopped() + for (context in listOf(oldTree.child, oldTree.grandchild, newChild)) { + assertSendFailsPromptly { context.client.notify(text("late")) } + } + assertIs( + f.request(AcpMethod.AgentMethods.V1.SessionPrompt, PromptRequest(loadedId, listOf(ContentBlock.Text("go")))) + ) + f.awaitCollectionsEnded(first.wrapper()) + f.assertNothingMoreSent() + } + + @Test + fun `a re-open while the old root's close runs keeps the new root and its subagents`() = withSubagents { f -> + val first = RootSession(loadedId) + assertIs(f.resume(first)) + val closeStarted = CompletableDeferred() + val releaseClose = CompletableDeferred() + first.onClose = { + closeStarted.complete(Unit) + releaseClose.await() + } + val closeId = RequestId.create("close-old") + f.fireWithoutReply(AcpMethod.AgentMethods.V1.SessionClose, CloseSessionRequest(loadedId), closeId) + withTimeout(5.seconds) { closeStarted.await() } + + val second = RootSession(loadedId) + assertIs(f.resume(second)) + val events = Channel(Channel.UNLIMITED) + val cancels = Channel(Channel.UNLIMITED) + val secondSubagents = assertNotNull(second.wrapper().subagents) + announce(secondSubagents, childId, granted = true, events = events.consumeAsFlow(), cancels = cancels) + assertEquals(SessionNotification(loadedId, announcement(childId, granted = true)), f.nextNotification()) + val child = assertNotNull(f.agent.subagentOrNull(childId)) + + releaseClose.complete(Unit) + val closeResponse = assertIs(f.transport.receiveTestMessages(1).single()) + assertEquals(closeId, closeResponse.id) + + assertIs( + f.request(AcpMethod.AgentMethods.V1.SessionPrompt, PromptRequest(loadedId, listOf(ContentBlock.Text("go")))) + ) + assertSame(child, f.agent.subagentOrNull(childId)) + events.send(text("still collected")) + assertEquals(SessionNotification(childId, text("still collected")), f.nextNotification()) + f.fireCancel(childId) + assertEquals(childId, withTimeout(5.seconds) { cancels.receive() }) + secondSubagents.announce(siblingId, announcing()) + assertEquals(SessionNotification(loadedId, announcement(siblingId)), f.nextNotification()) + events.close() + } + + @Test + fun `an id whose subagent's root is being cleaned up is free for another root`() = withSubagents { f -> + val first = RootSession(loadedId) + assertIs(f.resume(first)) + val testScope: CoroutineScope = this + val suspended = CompletableDeferred() + val reannounced = CompletableDeferred>() + lateinit var oldChild: AgentSubagentContext + assertNotNull(first.wrapper().subagents).announce(childId, { context -> + oldChild = context + context.client.notify(announcement(childId)) + TestSubagent(flow { + suspendCancellableCoroutine { continuation -> + /* + * Runs synchronously while the re-opening's cleanup cancels the old root's collections: after the + * old subagents left the table, and before they are marked removed. + */ + continuation.invokeOnCancellation { + testScope.launch(start = CoroutineStart.UNDISPATCHED) { + reannounced.complete(runCatching { f.rootSubagents.announce(childId, announcing()) }) + } + } + suspended.complete(Unit) + } + }) + }) + assertEquals(SessionNotification(loadedId, announcement(childId)), f.nextNotification()) + withTimeout(5.seconds) { suspended.await() } + + assertIs(f.resume(RootSession(loadedId))) + + val announced = withTimeout(5.seconds) { reannounced.await() } + assertTrue(announced.isSuccess, "the id is free once the old subtree is closed: ${announced.exceptionOrNull()}") + assertSame(f.rootWrapper, assertNotNull(f.agent.subagentOrNull(childId)).root) + assertFailsWith { oldChild.client.notify(text("late")) } + f.awaitCollectionsEnded(first.wrapper()) + assertSame(f.rootWrapper, assertNotNull(f.agent.subagentOrNull(childId)).root, "the old root's cleanup keeps the new entry") + } + + /* + * Re-opening a root cleans up only its subagents: the SDK leaves the replaced root's turn and AgentSession as they + * are. + */ + @Test + fun `a turn running on a replaced root keeps running and answers`() = withSubagents { f -> + val first = RootSession(loadedId) + val started = CompletableDeferred() + val release = CompletableDeferred() + first.promptHandler = { + started.complete(Unit) + release.await() + emit(Event.SessionUpdateEvent(text("old turn"))) + } + assertIs(f.resume(first)) + val promptId = RequestId.create("old-turn") + val prompt = PromptRequest(loadedId, listOf(ContentBlock.Text("go"))) + f.fireWithoutReply(AcpMethod.AgentMethods.V1.SessionPrompt, prompt, promptId) + withTimeout(5.seconds) { started.await() } + + assertIs(f.resume(RootSession(loadedId))) + // The new root has a turn slot of its own. + assertIs( + f.request(AcpMethod.AgentMethods.V1.SessionPrompt, PromptRequest(loadedId, listOf(ContentBlock.Text("go")))) + ) + release.complete(Unit) + + val (update, response) = f.transport.receiveTestMessages(2) + assertEquals(SessionNotification(loadedId, text("old turn")), update.sessionNotificationOrNull()) + assertIs(response) + assertEquals(promptId, response.id) + val stopReason = ACPJson.decodeFromJsonElement(AcpMethod.AgentMethods.V1.SessionPrompt.responseSerializer, response.result).stopReason + assertEquals(StopReason.END_TURN, stopReason) + } + + // Helpers + + private val closingId = SessionId("closing") + private val loadedId = SessionId("loaded") + + private suspend fun currentSubagents(): AgentSubagents = assertNotNull(currentCoroutineContext().subagents) + + /** + * This root's wrapper, once its postInitialize ran. + */ + private suspend fun RootSession.wrapper(): RootSessionWrapper = withTimeout(5.seconds) { context.await() }.rootWrapper + + /** + * Announces [sessionId] under [subagents] from a factory that sends its announcement, with [granted] and [state], and + * returns the child's context. The child collects [events], and its cancel sends its id to [cancels]. + */ + private suspend fun announce( + subagents: AgentSubagents, + sessionId: SessionId, + granted: Boolean = false, + state: StateUpdate? = null, + events: Flow = emptyFlow(), + cancels: Channel? = null, + ): AgentSubagentContext { + lateinit var context: AgentSubagentContext + subagents.announce(sessionId, { + context = it + it.client.notify(announcement(sessionId, granted, state)) + TestSubagent(events, onCancel = { cancels?.send(sessionId) }) + }) + return context + } + + /** + * Announces [sessionId] under the root, reads its announcement and returns its context. + */ + private suspend fun announceChild(f: Fixture, sessionId: SessionId): AgentSubagentContext { + val context = announce(f.rootSubagents, sessionId) + assertEquals(SessionNotification(rootId, announcement(sessionId)), f.nextNotification()) + return context + } + + /** + * Announces a child as running, granted if [cancels] is set, with hot events that never complete, and completes + * [stopped] when their collection stops. Returns once the collection has started. + */ + private suspend fun announceActive( + subagents: AgentSubagents, + sessionId: SessionId, + stopped: CompletableDeferred, + cancels: Channel? = null, + ): AgentSubagentContext { + val started = CompletableDeferred() + val context = announce( + subagents, + sessionId, + granted = cancels != null, + state = StateUpdate.Running(), + events = endlessEvents(stopped, started), + cancels = cancels, + ) + withTimeout(5.seconds) { started.await() } + return context + } + + /** + * Hot events that never complete: they complete [started] once collected, and [stopped] when the collection + * stops. + */ + private fun endlessEvents(stopped: CompletableDeferred, started: CompletableDeferred? = null) = + flow { + try { + started?.complete(Unit) + awaitCancellation() + } finally { + stopped.complete(Unit) + } + } + + /** + * Announces [childId] from a replay, with [grandchildId] announced from its factory, both collecting [events], and + * returns the child's context. + */ + private suspend fun replayChildWithGrandchild(events: Flow = emptyFlow()): AgentSubagentContext { + lateinit var child: AgentSubagentContext + currentSubagents().announce(childId, { context -> + child = context + context.client.notify(announcement(childId)) + announce(context.subagents, grandchildId, events = events) + TestSubagent(events) + }) + return child + } + + /** + * A child with a grandchild below it, both announced from a root's replay as running, with events that never + * complete. + */ + private inner class ReplayedTree { + lateinit var child: AgentSubagentContext + lateinit var grandchild: AgentSubagentContext + private val childStopped = CompletableDeferred() + private val grandchildStopped = CompletableDeferred() + + suspend fun replay() { + currentSubagents().announce(childId, { context -> + child = context + context.client.notify(announcement(childId, state = StateUpdate.Running())) + val grandchildEvents = endlessEvents(grandchildStopped) + grandchild = announce(context.subagents, grandchildId, state = StateUpdate.Running(), events = grandchildEvents) + TestSubagent(endlessEvents(childStopped)) + }) + } + + /** + * Waits until both collections have stopped. + */ + suspend fun awaitStopped() { + withTimeout(5.seconds) { + childStopped.await() + grandchildStopped.await() + } + } + } + + /** + * A factory that waits after its announcement, or before it, until [release] completes. [announcing] is the + * outcome of its `announce` call. + */ + private class HeldFactory( + val context: AgentSubagentContext, + val announcing: Deferred>, + val release: CompletableDeferred, + ) + + /** + * Announces [childId] under [subagents] with a factory that sends [announcement], unless it is `null`, then waits + * until released and returns [afterRelease]'s result. Runs [block] once the factory waits, with the announcement + * read, and releases the factory when [block] ends. + */ + private suspend fun CoroutineScope.withHeldFactory( + f: Fixture, + subagents: AgentSubagents, + announcement: SessionUpdate.SubagentUpdate?, + afterRelease: suspend (AgentSubagentContext) -> AgentSubagentSession, + block: suspend (HeldFactory) -> Unit, + ) { + val waiting = CompletableDeferred() + val release = CompletableDeferred() + val announcing = async { + runCatching { + subagents.announce(childId, { context -> + announcement?.let { context.client.notify(it) } + waiting.complete(context) + release.await() + afterRelease(context) + }) + } + } + try { + val context = withTimeout(5.seconds) { waiting.await() } + if (announcement != null) f.nextNotification() + block(HeldFactory(context, announcing, release)) + } finally { + release.complete(Unit) + } + } + + /** + * A sample of a child's client operations, own announcement included. + */ + private fun childOperations(context: AgentSubagentContext): List Unit> = listOf( + { context.client.notify(text("late")) }, + { context.client.notify(SessionUpdate.SubagentUpdate(context.sessionId, state = MaybeUndefined.Value(StateUpdate.Running()))) }, + { context.client.requestPermissions(SessionUpdate.ToolCallUpdate(ToolCallId("t")), emptyList()) }, + { context.client.fsReadTextFile("/a") }, + ) + + /** + * Loads a root whose replay announces [childId], whose cancel sends its id to [cancels], then sends [update] through + * the child's client from another thread. The transport holds [update] on its sender's thread, after the SDK decided how to count it, + * until the load handler suspends after the replay. Returns what was sent up to the load response, once the send + * has returned. + */ + private suspend fun CoroutineScope.loadWithReplaySendHeld( + f: Fixture, + update: SessionUpdate, + cancels: Channel, + ): List { + val loaded = RootSession(loadedId) + val inTransport = CompletableDeferred() + val handlerSuspended = CompletableDeferred() + val released = CountDownLatch(1) + f.transport.onSend = { message -> + if (message.sessionNotificationOrNull()?.update == update) { + inTransport.complete(Unit) + released.await(5, TimeUnit.SECONDS) + } + } + lateinit var sender: Job + loaded.replay = { + val child = announce(currentSubagents(), childId, cancels = cancels) + sender = CoroutineScope(Dispatchers.IO).launch { child.client.notify(update) } + inTransport.await() + /* + * Runs once the load handler suspends after this replay returns. A response it lets through is + * dispatched to the test's event loop before the release below. + */ + val handlerDispatcher = checkNotNull(currentCoroutineContext()[ContinuationInterceptor]) + CoroutineScope(handlerDispatcher).launch { handlerSuspended.complete(Unit) } + } + val releaser = launch { + handlerSuspended.await() + released.countDown() + } + + try { + val received = f.load(loaded) + withTimeout(5.seconds) { sender.join() } + return received + } finally { + released.countDown() + releaser.cancel() + } + } + + private val lateText = text("late") + + /** + * Starts sends of a cancel grant and of an update on the child's own stream through [child]'s client, on other + * threads, and returns once each has suspended or returned. + */ + private fun startLateSends(child: AgentSubagentContext): List> { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + val grant = SessionUpdate.SubagentUpdate(child.sessionId, capabilities = MaybeUndefined.Value(grant())) + return listOf(grant, lateText).map { update -> + scope.async(start = CoroutineStart.UNDISPATCHED) { child.client.notify(update) } + } + } + + /** + * What [startLateSends] sends for [childId], as the client gets it. + */ + private fun lateUpdates(): Set { + val grant = SessionUpdate.SubagentUpdate(childId, capabilities = MaybeUndefined.Value(grant())) + return setOf(SessionNotification(loadedId, grant), SessionNotification(childId, lateText)) + } + + /** + * Asserts that each of [lateSends] failed because its load failed, and that the loaded root and its child are gone. + */ + private suspend fun assertLateSendsFail(f: Fixture, lateSends: List>) { + lateSends.forEach { send -> + val failure = assertFailsWith { withTimeout(5.seconds) { send.await() } } + // A timeout is an IllegalStateException too. + assertFalse(failure is CancellationException, "$failure") + } + assertNull(f.agent.subagentOrNull(childId)) + assertIs( + f.request(AcpMethod.AgentMethods.V1.SessionPrompt, PromptRequest(loadedId, listOf(ContentBlock.Text("go")))) + ) + f.assertNothingMoreSent() + } + + /** + * Asserts that [send] fails with [IllegalStateException] in time. A child's send under a root opened by + * `session/load` passes the root's replay window and may wait for it to close, so a window left open fails the test + * here instead of hanging it. + */ + private suspend fun assertSendFailsPromptly(send: suspend () -> Unit) { + // Outside assertFailsWith, which would accept the timeout: it is an IllegalStateException too. + withTimeoutOrNull(5.seconds) { assertFailsWith { send() } } + ?: fail("The send did not fail within 5 seconds: it is waiting, such as for a replay window to close") + } + + private val probeId = SessionId("probe") + + /** + * Announces a granted child whose cancel sends [probeId] to [cancels], for proving that an earlier + * `session/cancel` was handled: notifications are handled in wire order. + */ + private suspend fun announceProbe(f: Fixture, cancels: Channel) { + announce(f.rootSubagents, probeId, granted = true, cancels = cancels) + f.nextNotification() + } + + /** + * Sends `session/cancel` for [sessionId] and then for the probe, and asserts that only the probe's cancel ran. + */ + private suspend fun assertCancelIgnored(f: Fixture, sessionId: SessionId, cancels: Channel) { + f.fireCancel(sessionId) + f.fireCancel(probeId) + assertEquals(probeId, withTimeout(5.seconds) { cancels.receive() }) + assertTrue(cancels.isEmpty) + } + + /** + * Every session method other than `session/cancel` on [sessionId], by name. + */ + private fun sessionRequests(f: Fixture, sessionId: SessionId): List JsonRpcMessage?>> { + return listOf( + "prompt" to { f.request(AcpMethod.AgentMethods.V1.SessionPrompt, PromptRequest(sessionId, listOf(ContentBlock.Text("go")))) }, + "set_mode" to { f.request(AcpMethod.AgentMethods.V1.SessionSetMode, SetSessionModeRequest(sessionId, SessionModeId("m"))) }, + "set_model" to { f.request(AcpMethod.AgentMethods.V1.SessionSetModel, SetSessionModelRequest(sessionId, ModelId("m"))) }, + "set_config_option" to { + f.request( + AcpMethod.AgentMethods.V1.SessionSetConfigOption, + SetSessionConfigOptionRequest(sessionId, SessionConfigId("c"), SessionConfigOptionValue.of(true)), + ) + }, + "close" to { f.request(AcpMethod.AgentMethods.V1.SessionClose, CloseSessionRequest(sessionId)) }, + "delete" to { f.request(AcpMethod.AgentMethods.V1.SessionDelete, DeleteSessionRequest(sessionId)) }, + "fork" to { f.request(AcpMethod.AgentMethods.V1.SessionFork, ForkSessionRequest(sessionId, ".", emptyList())) }, + "load" to { f.request(AcpMethod.AgentMethods.V1.SessionLoad, LoadSessionRequest(sessionId, ".", emptyList())) }, + "resume" to { f.request(AcpMethod.AgentMethods.V1.SessionResume, ResumeSessionRequest(sessionId, ".")) }, + ) + } + + /** + * Asserts that [received] is the session notifications [expected], followed by a success response, or by an error + * response unless [success]. + */ + private fun assertSentBeforeResponse( + expected: List, + received: List, + message: String? = null, + success: Boolean = true, + ) { + assertEquals(expected, received.dropLast(1).map { it.sessionNotificationOrNull() }, message) + if (success) { + assertIs(received.last(), message) + } else { + assertIs(received.last(), message) + } + } + + private fun closeResult(response: JsonRpcMessage): CloseSessionResponse = ACPJson.decodeFromJsonElement( + AcpMethod.AgentMethods.V1.SessionClose.responseSerializer, + assertIs(response, "an answer, got $response").result, + ) + + private suspend fun assertPromptFails(f: Fixture) { + val received = f.transport.fireTestRequest( + AcpMethod.AgentMethods.V1.SessionPrompt.methodName, + ACPJson.encodeToJsonElement( + AcpMethod.AgentMethods.V1.SessionPrompt.requestSerializer, + PromptRequest(rootId, listOf(ContentBlock.Text("go"))), + ), + ) + assertIs(received.last()) + assertEquals(1, received.size, "Nothing but the error response is sent: $received") + } + + private fun subagentsDefinedUpdates(): List { + val reference = ToolCallContent.Session(childId) + return listOf( + SessionUpdate.SessionMessage(MessageId("m1"), content = MaybeUndefined.Value(listOf(ContentBlock.Text("hi")))), + SessionUpdate.SessionMessageChunk(MessageId("m1"), ContentBlock.Text("chunk")), + SessionUpdate.ToolCall(ToolCallId("spawn"), "Spawn", content = listOf(reference)), + SessionUpdate.ToolCallUpdate( + ToolCallId("spawn"), + content = listOf(ToolCallContent.Content(ContentBlock.Text("output")), reference), + ), + ) + } +} + +private fun grant() = SubagentSessionCapabilities(cancel = SessionCancelCapabilities()) + +/** + * Asserts that [failure] is an ordinary failure caused by a cancellation. On the JVM a [CancellationException] is an + * [IllegalStateException] itself, so `assertFailsWith` alone would accept it unwrapped. + */ +private fun assertWrapsCancellation(failure: Throwable) { + assertFalse(failure is CancellationException, failure.stackTraceToString()) + assertTrue(failure.causes().any { it is CancellationException }, failure.stackTraceToString()) +} + +private val CoroutineContext.rootWrapper: RootSessionWrapper + get() = this[SessionWrapperContextElement.Key]!!.sessionWrapper as RootSessionWrapper + +private fun announcement( + sessionId: SessionId, + granted: Boolean = false, + state: StateUpdate? = null, +) = SessionUpdate.SubagentUpdate( + sessionId = sessionId, + title = MaybeUndefined.Value("Subagent $sessionId"), + capabilities = if (granted) MaybeUndefined.Value(grant()) else MaybeUndefined.Undefined, + state = state?.let { MaybeUndefined.Value(it) } ?: MaybeUndefined.Undefined, +) + +private fun stateUpdate(sessionId: SessionId, state: StateUpdate) = + SessionUpdate.SubagentUpdate(sessionId, state = MaybeUndefined.Value(state)) + +private fun text(value: String) = SessionUpdate.AgentMessageChunk(ContentBlock.Text(value)) + +/** + * The causes of this exception. Coroutine stack trace recovery may wrap an exception that crosses a suspension point + * in a copy whose cause is the original, so tests look for a cause anywhere in the chain. + */ +private fun Throwable.causes(): Sequence = generateSequence(cause) { it.cause } + +/** + * An exception that coroutine stack trace recovery leaves as is, for asserting that the very instance is rethrown. + */ +@OptIn(ExperimentalCoroutinesApi::class) +private class UncopiedException(message: String) : RuntimeException(message), CopyableThrowable { + override fun createCopy(): UncopiedException? = null +} + +private fun JsonRpcMessage.sessionNotificationOrNull(): SessionNotification? { + if (this !is JsonRpcNotification || method != AcpMethod.ClientMethods.V1.SessionUpdate.methodName) return null + return ACPJson.decodeFromJsonElement(AcpMethod.ClientMethods.V1.SessionUpdate.serializer, checkNotNull(params)) +} diff --git a/acp/src/jvmTest/kotlin/com/agentclientprotocol/agent/AgentTest.kt b/acp/src/jvmTest/kotlin/com/agentclientprotocol/agent/AgentTest.kt index 756bb1ec..b2200380 100644 --- a/acp/src/jvmTest/kotlin/com/agentclientprotocol/agent/AgentTest.kt +++ b/acp/src/jvmTest/kotlin/com/agentclientprotocol/agent/AgentTest.kt @@ -3,6 +3,7 @@ package com.agentclientprotocol.agent import com.agentclientprotocol.annotations.UnstableApi import com.agentclientprotocol.common.Event import com.agentclientprotocol.common.SessionCreationParameters +import com.agentclientprotocol.common.notify import com.agentclientprotocol.model.* import com.agentclientprotocol.protocol.Protocol import com.agentclientprotocol.protocol.setNotificationHandler @@ -13,6 +14,7 @@ import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flow import kotlinx.serialization.Serializable import kotlinx.serialization.json.* +import java.util.concurrent.atomic.AtomicInteger import kotlin.test.* import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds @@ -1052,6 +1054,59 @@ class AgentTest { } } + /* + * Two session/cancel notifications for one turn run AgentSession.cancel() concurrently. The turn answers only + * after both have returned, so the updates sent from either precede the response. + */ + @Test + fun `a turn cancelled twice answers only after both of the session's cancels return`() { + val started = CompletableDeferred() + val turnEnded = CompletableDeferred() + val cancelCount = AtomicInteger() + val cancelGates = Channel>(Channel.UNLIMITED) + + val promptHandler: PromptHandler = { + started.complete(Unit) + try { + awaitCancellation() + } finally { + turnEnded.complete(Unit) + } + } + + val cancelHandler: CancelHandler = { + val index = cancelCount.incrementAndGet() + val release = CompletableDeferred() + cancelGates.send(release) + release.await() + currentCoroutineContext().client.notify(SessionUpdate.AgentMessageChunk(ContentBlock.Text("cleanup $index"))) + } + + withTestAgentSession(promptHandler = promptHandler, cancelHandler = cancelHandler) { testAgent, session -> + testAgent.firePrompt(session.sessionId, "first", RequestId.create(361)) + withTimeout(5.seconds) { started.await() } + testAgent.testCancel(CancelNotification(session.sessionId)) + testAgent.testCancel(CancelNotification(session.sessionId)) + val releaseFirst = withTimeout(5.seconds) { cancelGates.receive() } + val releaseSecond = withTimeout(5.seconds) { cancelGates.receive() } + + releaseFirst.complete(Unit) + assertEquals("cleanup 1", testAgent.receiveAgentMessageText()) + withTimeout(5.seconds) { turnEnded.await() } + + /* + * The absence of a reply can only be observed for a while: the first cancel has returned and the turn + * has ended, so a turn that waited for one cancel only would answer right away. + */ + val early = withTimeoutOrNull(300.milliseconds) { testAgent.transport.receiveTestMessages(1) } + assertNull(early, "The cancelled turn answered before the second cancel returned") + + releaseSecond.complete(Unit) + assertEquals("cleanup 2", testAgent.receiveAgentMessageText()) + assertEquals(StopReason.CANCELLED, testAgent.receivePromptResponse(RequestId.create(361)).stopReason) + } + } + /* * The session's cancel() may stop the turn cooperatively, so its flow ends normally before the SDK cancels the * job. The client cancelled the turn, so the agent MUST answer with the `cancelled` stop reason. @@ -1256,6 +1311,18 @@ class AgentTest { assertEquals(id, reply.id) return ACPJson.decodeFromJsonElement(AcpMethod.AgentMethods.V1.SessionPrompt.responseSerializer, reply.result) } + + /** + * Reads the next message from the agent as a `session/update` with an agent message chunk, and returns its text. + */ + private suspend fun TestAgent.receiveAgentMessageText(): String { + val message = assertNotNull(transport.receiveTestMessages(1).singleOrNull(), "No session/update") + val notification = assertIs(message) + val method = AcpMethod.ClientMethods.V1.SessionUpdate + assertEquals(method.methodName, notification.method) + val update = ACPJson.decodeFromJsonElement(method.serializer, assertNotNull(notification.params)).update + return assertIs(assertIs(update).content).text + } } @OptIn(UnstableApi::class) diff --git a/acp/src/jvmTest/kotlin/com/agentclientprotocol/agent/TestTransport.kt b/acp/src/jvmTest/kotlin/com/agentclientprotocol/agent/TestTransport.kt index ba6a7085..dd05a8ac 100644 --- a/acp/src/jvmTest/kotlin/com/agentclientprotocol/agent/TestTransport.kt +++ b/acp/src/jvmTest/kotlin/com/agentclientprotocol/agent/TestTransport.kt @@ -28,8 +28,15 @@ class TestTransport(val timeout: Duration) : BaseTransport() { private fun fireMessage(message: JsonRpcMessage) = fireFrame(TransportFrame.Single(message)) + /** + * Called with each outgoing message before it is queued for the test to read, on the sender's thread. + */ + @Volatile + var onSend: (JsonRpcMessage) -> Unit = {} + override fun send(frame: TransportFrame) { val message = (frame as TransportFrame.Single).message + onSend(message) responses.trySend(message) } diff --git a/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientEarlySessionUpdatesTest.kt b/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientEarlySessionUpdatesTest.kt index 6affec0f..b1ee62df 100644 --- a/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientEarlySessionUpdatesTest.kt +++ b/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientEarlySessionUpdatesTest.kt @@ -5,54 +5,25 @@ package com.agentclientprotocol.client import com.agentclientprotocol.annotations.UnstableApi import com.agentclientprotocol.common.ClientSessionOperations import com.agentclientprotocol.common.SessionCreationParameters -import com.agentclientprotocol.model.AcpCreatedSessionResponse +import com.agentclientprotocol.common.notify import com.agentclientprotocol.model.AcpMethod -import com.agentclientprotocol.model.ContentBlock import com.agentclientprotocol.model.LoadSessionResponse import com.agentclientprotocol.model.NewSessionResponse -import com.agentclientprotocol.model.PermissionOption -import com.agentclientprotocol.model.RequestPermissionResponse import com.agentclientprotocol.model.ResumeSessionResponse import com.agentclientprotocol.model.SessionConfigOption import com.agentclientprotocol.model.SessionId import com.agentclientprotocol.model.SessionMode import com.agentclientprotocol.model.SessionModeId import com.agentclientprotocol.model.SessionModeState -import com.agentclientprotocol.model.SessionNotification import com.agentclientprotocol.model.SessionUpdate -import com.agentclientprotocol.protocol.Protocol -import com.agentclientprotocol.rpc.ACPJson -import com.agentclientprotocol.rpc.JsonRpcError -import com.agentclientprotocol.rpc.JsonRpcErrorCode -import com.agentclientprotocol.rpc.JsonRpcErrorResponse -import com.agentclientprotocol.rpc.JsonRpcNotification -import com.agentclientprotocol.rpc.JsonRpcRequest -import com.agentclientprotocol.rpc.JsonRpcResponse -import com.agentclientprotocol.rpc.JsonRpcSuccessResponse -import com.agentclientprotocol.rpc.MethodName -import com.agentclientprotocol.rpc.RequestId -import com.agentclientprotocol.rpc.TransportFrame -import com.agentclientprotocol.transport.BaseTransport -import com.agentclientprotocol.transport.Transport import kotlinx.atomicfu.atomic import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancel import kotlinx.coroutines.cancelAndJoin -import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import kotlinx.coroutines.withTimeoutOrNull -import kotlinx.serialization.KSerializer -import kotlinx.serialization.json.JsonElement import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -60,7 +31,6 @@ import kotlin.test.assertNull import kotlin.test.assertSame import kotlin.test.assertTrue import kotlin.time.Duration.Companion.milliseconds -import kotlin.time.Duration.Companion.seconds /** * `Client.loadSession` and `Client.resumeSession` with a [ClientSessionOperations] argument deliver each @@ -71,7 +41,7 @@ class ClientEarlySessionUpdatesTest { private val parameters = SessionCreationParameters(cwd = ".", mcpServers = emptyList()) @Test - fun `load delivers replayed updates before the agent answers`() = withClient { client, agent -> + fun `load delivers replayed updates before the agent answers`() = withScriptedClient { (client, agent) -> val sessionId = SessionId("early-load") val operations = RecordingOperations() val load = async { client.loadSession(sessionId, parameters, operations) } @@ -94,7 +64,7 @@ class ClientEarlySessionUpdatesTest { } @Test - fun `resume delivers updates before the agent answers`() = withClient { client, agent -> + fun `resume delivers updates before the agent answers`() = withScriptedClient { (client, agent) -> val sessionId = SessionId("early-resume") val operations = RecordingOperations() val resume = async { client.resumeSession(sessionId, parameters, operations) } @@ -111,8 +81,10 @@ class ClientEarlySessionUpdatesTest { assertEquals(listOf(early), operations.updates.value) } + // TODO remove the currentMode assertion together with the deprecated ClientSession.currentMode. @Test - fun `updates racing the answer keep their order and arrive once`() = withClient { client, agent -> + @Suppress("DEPRECATION") + fun `updates racing the answer keep their order and arrive once`() = withScriptedClient { (client, agent) -> /* * The answer and the updates after it are put on the wire back to back, so the client switches from * early delivery to the session while those updates are handled. Each round can take either side. @@ -136,8 +108,13 @@ class ClientEarlySessionUpdatesTest { } } + /* + * TODO remove the currentMode assertion together with the deprecated ClientSession.currentMode. It pins the + * replayed mode over the newer one from the response, which is the reason for the deprecation. + */ @Test - fun `the answer waits for an early update that the operations still handle`() = withClient { client, agent -> + @Suppress("DEPRECATION") + fun `the answer waits for an early update that the operations still handle`() = withScriptedClient { (client, agent) -> val sessionId = SessionId("slow-early-update") val releaseModeUpdate = CompletableDeferred() val operations = RecordingOperations(beforeEach = { update -> @@ -165,8 +142,14 @@ class ClientEarlySessionUpdatesTest { assertEquals(PLAN, session.currentMode.value, "the session applies the mode of the early update") } + /* + * TODO remove the currentMode and configOptions assertions together with the deprecated ClientSession.currentMode + * and ClientSession.configOptions. They pin the replayed state over the newer state from the response, which is + * the reason for the deprecation. + */ @Test - fun `mode and config options after an early load equal those after a buffered load`() = withClient { client, agent -> + @Suppress("DEPRECATION") + fun `mode and config options after an early load equal those after a buffered load`() = withScriptedClient { (client, agent) -> val replay = listOf( SessionUpdate.CurrentModeUpdate(PLAN), SessionUpdate.ConfigOptionUpdate(listOf(SessionConfigOption.boolean("thinking", "Thinking", currentValue = true))), @@ -201,8 +184,7 @@ class ClientEarlySessionUpdatesTest { @Test fun `failed load releases the session id`() { - val unconnected = RecordingOperations() - withClient(globalSessionUpdateHandler = { _, update, meta -> unconnected.notify(update, meta) }) { client, agent -> + withScriptedClient { (client, agent, unconnected) -> val sessionId = SessionId("failing-load") val failedOperations = RecordingOperations() val failedLoad = async { runCatching { client.loadSession(sessionId, parameters, failedOperations) } } @@ -216,7 +198,7 @@ class ClientEarlySessionUpdatesTest { val afterFailure = text("after-failure") agent.sendUpdate(sessionId, afterFailure) - unconnected.awaitUpdate(afterFailure) + unconnected.await(sessionId, afterFailure) assertEquals(listOf(replay), failedOperations.updates.value) val operations = RecordingOperations() @@ -234,7 +216,7 @@ class ClientEarlySessionUpdatesTest { } @Test - fun `early load takes over updates buffered for its session id`() = withClient { client, agent -> + fun `early load takes over updates buffered for its session id`() = withScriptedClient { (client, agent) -> val sessionId = SessionId("buffered-before-load") val newSession = async { client.newSession(parameters) { _, _ -> RecordingOperations() } } val newRequest = agent.receiveRequest(AcpMethod.AgentMethods.V1.SessionNew.methodName) @@ -261,7 +243,7 @@ class ClientEarlySessionUpdatesTest { } @Test - fun `factory load still buffers updates until the agent answers`() = withClient { client, agent -> + fun `factory load still buffers updates until the agent answers`() = withScriptedClient { (client, agent) -> val sessionId = SessionId("factory-load") val operations = RecordingOperations() val factoryCalls = atomic(0) @@ -288,8 +270,7 @@ class ClientEarlySessionUpdatesTest { @Test fun `a failing notify fails the load and sends the later updates to the unconnected handler`() { - val unconnected = RecordingOperations() - withClient(globalSessionUpdateHandler = { _, update, meta -> unconnected.notify(update, meta) }) { client, agent -> + withScriptedClient { (client, agent, unconnected) -> val sessionId = SessionId("failing-notify") // A pending session/new makes the client buffer the update for the not yet loaded id. val newSession = async { client.newSession(parameters) { _, _ -> RecordingOperations() } } @@ -310,15 +291,14 @@ class ClientEarlySessionUpdatesTest { agent.sendUpdate(sessionId, afterFailure) agent.answer(newRequest, AcpMethod.AgentMethods.V1.SessionNew.responseSerializer, NewSessionResponse(SessionId("new"))) newSession.await() - unconnected.awaitUpdate(afterFailure) + unconnected.await(sessionId, afterFailure) assertTrue(operations.updates.value.isEmpty(), "the operations of the failed load get no update") } } @Test fun `a load cancelled during the early delivery sends the later updates to the unconnected handler`() { - val unconnected = RecordingOperations() - withClient(globalSessionUpdateHandler = { _, update, meta -> unconnected.notify(update, meta) }) { client, agent -> + withScriptedClient { (client, agent, unconnected) -> val sessionId = SessionId("cancelled-load") val newSession = async { client.newSession(parameters) { _, _ -> RecordingOperations() } } val newRequest = agent.receiveRequest(AcpMethod.AgentMethods.V1.SessionNew.methodName) @@ -337,22 +317,21 @@ class ClientEarlySessionUpdatesTest { agent.awaitHandled() load.cancelAndJoin() - unconnected.awaitUpdate(queued) + unconnected.await(sessionId, queued) // While session/new runs, a later update waits for a possible retry, then goes to the handler at the reap. val afterCancel = text("after-cancel") agent.sendUpdate(sessionId, afterCancel) agent.answer(newRequest, AcpMethod.AgentMethods.V1.SessionNew.responseSerializer, NewSessionResponse(SessionId("new"))) newSession.await() - unconnected.awaitUpdate(afterCancel) + unconnected.await(sessionId, afterCancel) assertTrue(operations.updates.value.isEmpty(), "the operations of the cancelled load get no update") } } @Test fun `a notify that times out fails the load and sends the later updates to the unconnected handler`() { - val unconnected = RecordingOperations() - withClient(globalSessionUpdateHandler = { _, update, meta -> unconnected.notify(update, meta) }) { client, agent -> + withScriptedClient { (client, agent, unconnected) -> val sessionId = SessionId("timed-out-notify") val timedOut = CompletableDeferred() // A cancellation that is not the caller's own, as from a timeout inside a UI callback. @@ -374,20 +353,15 @@ class ClientEarlySessionUpdatesTest { assertTrue(load.await().exceptionOrNull() is IllegalStateException, "the load must fail") unconnected.awaitCount(afterTimeout.size) - assertEquals(afterTimeout, unconnected.updates.value) + assertEquals(afterTimeout, unconnected.updates) assertTrue(operations.updates.value.isEmpty(), "the operations of the failed load get no update") } } @Test fun `a throwing unconnected handler neither replaces the load failure nor stops the drain`() { - val unconnected = RecordingOperations() val queued = listOf(text("queued-1"), text("queued-2")) - val handler = GlobalSessionUpdateHandler { _, update, meta -> - unconnected.notify(update, meta) - if (update == queued.first()) error("global boom") - } - withClient(globalSessionUpdateHandler = handler) { client, agent -> + withScriptedClient(onUnconnected = { _, update -> if (update == queued.first()) error("global boom") }) { (client, agent, unconnected) -> val sessionId = SessionId("throwing-global-handler") val entered = CompletableDeferred() val operations = RecordingOperations(beforeEach = { @@ -404,14 +378,13 @@ class ClientEarlySessionUpdatesTest { agent.fail(request) assertEquals("load failed", load.await().exceptionOrNull()?.message) unconnected.awaitCount(queued.size) - assertEquals(queued, unconnected.updates.value) + assertEquals(queued, unconnected.updates) } } @Test fun `a failed factory hands the queued updates to the unconnected handler at once`() { - val unconnected = RecordingOperations() - withClient(globalSessionUpdateHandler = { _, update, meta -> unconnected.notify(update, meta) }) { client, agent -> + withScriptedClient { (client, agent, unconnected) -> val sessionId = SessionId("failing-factory") // A pending session/new delays the reap, so only the failure itself can drain the queue. val newSession = async { client.newSession(parameters) { _, _ -> RecordingOperations() } } @@ -423,7 +396,7 @@ class ClientEarlySessionUpdatesTest { agent.sendUpdate(sessionId, replay) agent.answer(request, AcpMethod.AgentMethods.V1.SessionLoad.responseSerializer, LoadSessionResponse()) assertTrue(load.await().isFailure) - unconnected.awaitUpdate(replay) + unconnected.await(sessionId, replay) agent.answer(newRequest, AcpMethod.AgentMethods.V1.SessionNew.responseSerializer, NewSessionResponse(SessionId("new"))) newSession.await() @@ -431,7 +404,7 @@ class ClientEarlySessionUpdatesTest { } @Test - fun `a second load of an open session fails before its request`() = withClient { client, agent -> + fun `a second load of an open session fails before its request`() = withScriptedClient { (client, agent) -> val sessionId = SessionId("open-twice") val first = RecordingOperations() val load = async { client.loadSession(sessionId, parameters, first) } @@ -452,7 +425,7 @@ class ClientEarlySessionUpdatesTest { } @Test - fun `a load with operations fails before its request while a factory load is in flight`() = withClient { client, agent -> + fun `a load with operations fails before its request while a factory load is in flight`() = withScriptedClient { (client, agent) -> val sessionId = SessionId("factory-and-early") val factoryOperations = RecordingOperations() val factoryLoad = async { client.loadSession(sessionId, parameters) { _, _ -> factoryOperations } } @@ -472,7 +445,7 @@ class ClientEarlySessionUpdatesTest { } @Test - fun `a load with operations after a failed factory load gets only its own updates`() = withClient { client, agent -> + fun `a load with operations after a failed factory load gets only its own updates`() = withScriptedClient { (client, agent) -> val sessionId = SessionId("early-after-failed-factory") // A pending session/new delays the reap of the failed holder. val newSession = async { client.newSession(parameters) { _, _ -> RecordingOperations() } } @@ -499,7 +472,7 @@ class ClientEarlySessionUpdatesTest { } @Test - fun `a retry after a failed load gets the updates while another session initializes`() = withClient { client, agent -> + fun `a retry after a failed load gets the updates while another session initializes`() = withScriptedClient { (client, agent) -> suspend fun retryAfterFailure(sessionId: SessionId, load: suspend (ClientSessionOperations) -> ClientSession) { val newSession = async { client.newSession(parameters) { _, _ -> RecordingOperations() } } val newRequest = agent.receiveRequest(AcpMethod.AgentMethods.V1.SessionNew.methodName) @@ -527,30 +500,6 @@ class ClientEarlySessionUpdatesTest { retryAfterFailure(factory) { operations -> client.loadSession(factory, parameters) { _, _ -> operations } } } - private fun withClient( - globalSessionUpdateHandler: GlobalSessionUpdateHandler? = null, - block: suspend CoroutineScope.(Client, ScriptedAgentTransport) -> Unit, - ) { - val scope = CoroutineScope(Dispatchers.Default + SupervisorJob()) - try { - val transport = ScriptedAgentTransport() - val protocol = Protocol(scope, transport) - protocol.start() - transport.start() - val client = Client(protocol, globalSessionUpdateHandler = globalSessionUpdateHandler) - runBlocking { - // Real parallelism between the protocol read loop and the load call is part of what is tested. - withContext(Dispatchers.Default) { - withTimeout(60.seconds) { block(client, transport) } - } - } - } finally { - scope.cancel() - } - } - - private fun text(value: String) = SessionUpdate.AgentMessageChunk(ContentBlock.Text(value)) - private fun modes() = SessionModeState( currentModeId = SessionModeId("default"), availableModes = listOf(SessionMode(SessionModeId("default"), "Default"), SessionMode(PLAN, "Plan"), SessionMode(REVIEW, "Review")), @@ -562,110 +511,3 @@ class ClientEarlySessionUpdatesTest { private val REVIEW = SessionModeId("review") } } - -private class RecordingOperations( - private val beforeEach: suspend (SessionUpdate) -> Unit = {}, -) : ClientSessionOperations { - val updates = MutableStateFlow>(emptyList()) - - override suspend fun requestPermissions( - toolCall: SessionUpdate.ToolCallUpdate, - permissions: List, - _meta: JsonElement?, - ): RequestPermissionResponse = error("not expected in this test") - - override suspend fun notify(notification: SessionUpdate, _meta: JsonElement?) { - beforeEach(notification) - updates.update { it + notification } - } - - suspend fun awaitCount(count: Int) { - withTimeout(TIMEOUT) { updates.first { it.size >= count } } - } - - suspend fun awaitUpdate(update: SessionUpdate) { - withTimeout(TIMEOUT) { updates.first { update in it } } - } - - private companion object { - private val TIMEOUT = 5.seconds - } -} - -/** - * The agent side of a connection, driven by the test: it records the requests of the client, and sends the updates - * and the answers the test asks for, in exactly that order. - */ -private class ScriptedAgentTransport : BaseTransport() { - private val requests = Channel(capacity = Channel.UNLIMITED) - private val responses = Channel(capacity = Channel.UNLIMITED) - private val barrierIds = atomic(0) - - override fun start() { - _state.value = Transport.State.STARTED - } - - override fun close() { - _state.value = Transport.State.CLOSING - fireClose() - _state.value = Transport.State.CLOSED - } - - override fun send(frame: TransportFrame) { - when (val message = (frame as TransportFrame.Single).message) { - is JsonRpcRequest -> requests.trySend(message) - is JsonRpcResponse -> responses.trySend(message) - else -> {} - } - } - - suspend fun receiveRequest(method: MethodName): JsonRpcRequest { - val request = withTimeout(5.seconds) { requests.receive() } - assertEquals(method, request.method) - return request - } - - fun assertNoRequest() { - assertNull(requests.tryReceive().getOrNull(), "the client must not send a request") - } - - fun sendUpdate(sessionId: SessionId, update: SessionUpdate) { - fireFrame( - TransportFrame.Single( - JsonRpcNotification( - method = AcpMethod.ClientMethods.V1.SessionUpdate.methodName, - params = ACPJson.encodeToJsonElement( - AcpMethod.ClientMethods.V1.SessionUpdate.serializer, - SessionNotification(sessionId, update), - ), - ) - ) - ) - } - - fun answer(request: JsonRpcRequest, serializer: KSerializer, response: T) { - fireFrame(TransportFrame.Single(JsonRpcSuccessResponse(request.id, ACPJson.encodeToJsonElement(serializer, response)))) - } - - fun fail(request: JsonRpcRequest) { - val error = JsonRpcError(JsonRpcErrorCode.INTERNAL_ERROR.code, "load failed") - fireFrame(TransportFrame.Single(JsonRpcErrorResponse(request.id, error))) - } - - /** - * Returns after the client has handled every message sent before this call. - * - * The client reads messages in wire order and lets each notification handler run before it reads on, so its - * answer to a later request proves that the earlier notifications have been handled. - */ - suspend fun awaitHandled() { - val id = RequestId.create("barrier-${barrierIds.incrementAndGet()}") - fireFrame(TransportFrame.Single(JsonRpcRequest(id, MethodName("test/barrier"), null))) - withTimeout(5.seconds) { - while (responses.receive().id != id) { - // An answer to an earlier barrier. - } - } - } -} - diff --git a/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientHangingSessionUpdateDeliveryTest.kt b/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientHangingSessionUpdateDeliveryTest.kt index c80f90f0..943fd43b 100644 --- a/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientHangingSessionUpdateDeliveryTest.kt +++ b/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientHangingSessionUpdateDeliveryTest.kt @@ -5,6 +5,7 @@ package com.agentclientprotocol.client import com.agentclientprotocol.annotations.UnstableApi import com.agentclientprotocol.common.ClientSessionOperations import com.agentclientprotocol.common.SessionCreationParameters +import com.agentclientprotocol.common.SessionEvent import com.agentclientprotocol.model.AcpMethod import com.agentclientprotocol.model.ContentBlock import com.agentclientprotocol.model.NewSessionResponse @@ -74,7 +75,7 @@ class ClientHangingSessionUpdateDeliveryTest { } } - // Wait until `session/new` is actually on the wire: `initializingSessionsCount` is now positive. + // Wait until `session/new` is actually on the wire: an opening call now runs. assertNotNull( withTimeoutOrNull(5.seconds) { transport.sessionNewSent.await() }, "session/new was never sent", @@ -83,7 +84,7 @@ class ClientHangingSessionUpdateDeliveryTest { // An update for a totally unrelated session arrives while our own session/new is still in flight. transport.emitSessionUpdate(unrelatedSessionId, unrelatedUpdate) - // Completing session/new drops `initializingSessionsCount` back to zero, reaping the buffered + // Completing session/new ends the last opening call, reaping the buffered // holder for the unrelated session. transport.completePendingSessionNew() newSessionResult.await() @@ -107,7 +108,8 @@ private object NoOpSessionOperations : ClientSessionOperations { _meta: JsonElement?, ): RequestPermissionResponse = error("not expected in this test") - override suspend fun notify(notification: SessionUpdate, _meta: JsonElement?) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return error("no updates expected for the session being created in this test") } } diff --git a/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientPermissionCancellationTest.kt b/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientPermissionCancellationTest.kt index 448fbd05..15ce8f24 100644 --- a/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientPermissionCancellationTest.kt +++ b/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientPermissionCancellationTest.kt @@ -6,6 +6,7 @@ import com.agentclientprotocol.annotations.UnstableApi import com.agentclientprotocol.common.ClientSessionOperations import com.agentclientprotocol.common.Event import com.agentclientprotocol.common.SessionCreationParameters +import com.agentclientprotocol.common.SessionEvent import com.agentclientprotocol.model.AcpMethod import com.agentclientprotocol.model.CloseSessionResponse import com.agentclientprotocol.model.ContentBlock @@ -149,6 +150,45 @@ class ClientPermissionCancellationTest { assertIs(turn.await().last()) } + @Test + fun `a request still waiting when the next turn starts is answered by a later cancel`() = + withV1Client { client, agent, scope -> + val operations = UserOperations() + val session = client.newSession(agent, operations) + val firstTurn = scope.async { session.prompt(listOf(ContentBlock.Text("first"))).toList() } + val firstPrompt = agent.prompts.receive() + val request = agent.requestPermission(session.sessionId, "kept") + val user = operations.user("kept") + user.started.await() + + // The agent ends the turn while the request is still waiting for the user. + agent.answerPrompt(firstPrompt) + firstTurn.await() + val secondTurn = scope.async { session.prompt(listOf(ContentBlock.Text("second"))).toList() } + val secondPrompt = agent.prompts.receive() + + session.cancel() + + assertEquals(RequestPermissionOutcome.Cancelled, agent.permissionOutcome(request)) + assertTrue(user.cleanedUp.isCompleted, "the handler stopped without the user answering") + assertEquals(emptyList(), agent.responsesTo(request).toListNow(), "the request got exactly one response") + agent.answerPrompt(secondPrompt) + secondTurn.await() + + // Control: a turn started after the cancel lets new requests reach the app. + val thirdTurn = scope.async { session.prompt(listOf(ContentBlock.Text("third"))).toList() } + val thirdPrompt = agent.prompts.receive() + val next = agent.requestPermission(session.sessionId, "next") + operations.user("next").started.await() + operations.user("next").answer.complete(ALLOWED) + + assertEquals(ALLOWED.outcome, agent.permissionOutcome(next)) + assertEquals(listOf("kept", "next"), operations.calls.toListNow()) + + agent.answerPrompt(thirdPrompt) + thirdTurn.await() + } + @Test fun `a prompt rejected for an active turn does not undo a cancel`() = withV1Client { client, agent, scope -> val operations = UserOperations() @@ -326,7 +366,7 @@ private class UserOperations : ClientSessionOperations { return user(toolCall.toolCallId.value).ask() } - override suspend fun notify(notification: SessionUpdate, _meta: JsonElement?) {} + override suspend fun notify(event: SessionEvent) {} } /** diff --git a/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientSessionUpdateDeliveryTest.kt b/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientSessionUpdateDeliveryTest.kt index ebaaeeef..e60d2933 100644 --- a/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientSessionUpdateDeliveryTest.kt +++ b/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientSessionUpdateDeliveryTest.kt @@ -5,6 +5,7 @@ package com.agentclientprotocol.client import com.agentclientprotocol.annotations.UnstableApi import com.agentclientprotocol.common.ClientSessionOperations import com.agentclientprotocol.common.SessionCreationParameters +import com.agentclientprotocol.common.SessionEvent import com.agentclientprotocol.model.AcpMethod import com.agentclientprotocol.model.ContentBlock import com.agentclientprotocol.model.NewSessionResponse @@ -46,7 +47,7 @@ import kotlin.time.Duration.Companion.seconds * * Getting this wrong used to be observable as `AcpExpectedError: Session not found` logged by the * protocol, plus a silently dropped update, whenever the notification was handled while the concurrent - * `newSession` was registering its holder and dropping `initializingSessionsCount` back to zero. + * `newSession` was registering its holder and ending the last opening call. */ class ClientSessionUpdateDeliveryTest { @Test @@ -108,7 +109,8 @@ private class CompletableUpdate : ClientSessionOperations { _meta: JsonElement?, ): RequestPermissionResponse = error("not expected in this test") - override suspend fun notify(notification: SessionUpdate, _meta: JsonElement?) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return notified.complete(Unit) } diff --git a/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientSessionUpdateForUnconnectedSessionTest.kt b/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientSessionUpdateForUnconnectedSessionTest.kt index 681fbfe6..9001193e 100644 --- a/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientSessionUpdateForUnconnectedSessionTest.kt +++ b/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ClientSessionUpdateForUnconnectedSessionTest.kt @@ -5,6 +5,7 @@ package com.agentclientprotocol.client import com.agentclientprotocol.annotations.UnstableApi import com.agentclientprotocol.common.ClientSessionOperations import com.agentclientprotocol.common.SessionCreationParameters +import com.agentclientprotocol.common.SessionEvent import com.agentclientprotocol.model.AcpMethod import com.agentclientprotocol.model.ContentBlock import com.agentclientprotocol.model.NewSessionResponse @@ -97,7 +98,8 @@ private class UpdateRecorder : ClientSessionOperations { _meta: JsonElement?, ): RequestPermissionResponse = error("not expected in this test") - override suspend fun notify(notification: SessionUpdate, _meta: JsonElement?) { + override suspend fun notify(event: SessionEvent) { + if (event !is SessionEvent.Update) return notified.complete(Unit) } diff --git a/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ScriptedAgentTransport.kt b/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ScriptedAgentTransport.kt new file mode 100644 index 00000000..066e64c4 --- /dev/null +++ b/acp/src/jvmTest/kotlin/com/agentclientprotocol/client/ScriptedAgentTransport.kt @@ -0,0 +1,303 @@ +package com.agentclientprotocol.client + +import com.agentclientprotocol.common.ClientSessionOperations +import com.agentclientprotocol.common.SessionEvent +import com.agentclientprotocol.model.AcpCreatedSessionResponse +import com.agentclientprotocol.model.AcpMethod +import com.agentclientprotocol.model.AcpNotification +import com.agentclientprotocol.model.AcpRequest +import com.agentclientprotocol.model.ContentBlock +import com.agentclientprotocol.model.PermissionOption +import com.agentclientprotocol.model.RequestPermissionRequest +import com.agentclientprotocol.model.RequestPermissionResponse +import com.agentclientprotocol.model.SessionId +import com.agentclientprotocol.model.SessionNotification +import com.agentclientprotocol.model.SessionUpdate +import com.agentclientprotocol.model.ToolCallId +import com.agentclientprotocol.protocol.Protocol +import com.agentclientprotocol.protocol.ProtocolOptions +import com.agentclientprotocol.rpc.ACPJson +import com.agentclientprotocol.rpc.JsonRpcError +import com.agentclientprotocol.rpc.JsonRpcErrorCode +import com.agentclientprotocol.rpc.JsonRpcErrorResponse +import com.agentclientprotocol.rpc.JsonRpcNotification +import com.agentclientprotocol.rpc.JsonRpcRequest +import com.agentclientprotocol.rpc.JsonRpcResponse +import com.agentclientprotocol.rpc.JsonRpcSuccessResponse +import com.agentclientprotocol.rpc.MethodName +import com.agentclientprotocol.rpc.RequestId +import com.agentclientprotocol.rpc.TransportFrame +import com.agentclientprotocol.transport.BaseTransport +import com.agentclientprotocol.transport.Transport +import kotlinx.atomicfu.atomic +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.KSerializer +import kotlinx.serialization.json.JsonElement +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.time.Duration.Companion.seconds + +/** + * Client operations that record the session events they get. + * + * @param beforeEach runs before an update is recorded; it may suspend or throw + * @param beforeOpened runs before the marker is recorded; it may suspend or throw + */ +internal class RecordingOperations( + private val beforeEach: suspend (SessionUpdate) -> Unit = {}, + private val beforeOpened: suspend () -> Unit = {}, +) : ClientSessionOperations { + /** + * Every event in delivery order, the marker as [OPENED]. + */ + val events = MutableStateFlow>(emptyList()) + + /** + * The updates in delivery order, without the marker. + */ + val updates = MutableStateFlow>(emptyList()) + + /** + * The responses of the markers in delivery order. + */ + val openedResponses = MutableStateFlow>(emptyList()) + + override suspend fun requestPermissions( + toolCall: SessionUpdate.ToolCallUpdate, + permissions: List, + _meta: JsonElement?, + ): RequestPermissionResponse = error("not expected in this test") + + override suspend fun notify(event: SessionEvent) { + when (event) { + is SessionEvent.Update -> { + beforeEach(event.update) + updates.update { it + event.update } + events.update { it + event.update } + } + is SessionEvent.Opened -> { + beforeOpened() + openedResponses.update { it + event.response } + events.update { it + OPENED } + } + } + } + + suspend fun awaitCount(count: Int) { + withTimeout(TIMEOUT) { updates.first { it.size >= count } } + } + + suspend fun awaitUpdate(update: SessionUpdate) { + withTimeout(TIMEOUT) { updates.first { update in it } } + } + + suspend fun awaitEvents(count: Int) { + withTimeout(TIMEOUT) { events.first { it.size >= count } } + } + + companion object { + /** + * Stands for the marker in [events]. + */ + const val OPENED = "Opened" + + private val TIMEOUT = 5.seconds + } +} + +/** + * The agent side of a connection, driven by the test: it records the requests of the client, and sends the updates + * and the answers the test asks for, in exactly that order. + */ +internal class ScriptedAgentTransport : BaseTransport() { + private val requests = Channel(capacity = Channel.UNLIMITED) + private val responses = MutableStateFlow>(emptyMap()) + private val notifications = Channel(capacity = Channel.UNLIMITED) + private val barrierIds = atomic(0) + + override fun start() { + _state.value = Transport.State.STARTED + } + + override fun close() { + _state.value = Transport.State.CLOSING + fireClose() + _state.value = Transport.State.CLOSED + } + + override fun send(frame: TransportFrame) { + when (val message = (frame as TransportFrame.Single).message) { + is JsonRpcRequest -> requests.trySend(message) + is JsonRpcResponse -> responses.update { it + (message.id to message) } + is JsonRpcNotification -> notifications.trySend(message) + } + } + + suspend fun receiveRequest(method: MethodName): JsonRpcRequest { + val request = withTimeout(5.seconds) { requests.receive() } + assertEquals(method, request.method) + return request + } + + suspend fun receiveNotification(method: MethodName): JsonRpcNotification { + while (true) { + val notification = withTimeout(5.seconds) { notifications.receive() } + if (notification.method == method) return notification + } + } + + fun assertNoRequest() { + assertNull(requests.tryReceive().getOrNull(), "the client must not send a request") + } + + fun sendUpdate(sessionId: SessionId, update: SessionUpdate) { + sendNotification(AcpMethod.ClientMethods.V1.SessionUpdate, SessionNotification(sessionId, update)) + } + + fun

sendNotification(method: AcpMethod.AcpNotificationMethod

, params: P) { + val encoded = ACPJson.encodeToJsonElement(method.serializer, params) + fireFrame(TransportFrame.Single(JsonRpcNotification(method = method.methodName, params = encoded))) + } + + /** + * Sends a request of the agent to the client, and returns its id for [awaitResponse]. + */ + fun

sendRequest(method: AcpMethod.AcpRequestResponseMethod, params: P): RequestId { + val id = RequestId.create("agent-${barrierIds.incrementAndGet()}") + val encoded = ACPJson.encodeToJsonElement(method.requestSerializer, params) + fireFrame(TransportFrame.Single(JsonRpcRequest(id, method.methodName, encoded))) + return id + } + + /** + * Waits for the client's answer to the agent's request [id]. + */ + suspend fun awaitResponse(id: RequestId): JsonRpcResponse = + withTimeout(5.seconds) { responses.first { id in it }.getValue(id) } + + /** + * Returns the client's answer to the agent's request [id], or `null` if it hasn't answered yet. + */ + fun responseOrNull(id: RequestId): JsonRpcResponse? = responses.value[id] + + fun answer(request: JsonRpcRequest, serializer: KSerializer, response: T) { + answerRaw(request, ACPJson.encodeToJsonElement(serializer, response)) + } + + fun answerRaw(request: JsonRpcRequest, result: JsonElement) { + fireFrame(TransportFrame.Single(JsonRpcSuccessResponse(request.id, result))) + } + + fun fail(request: JsonRpcRequest, code: JsonRpcErrorCode = JsonRpcErrorCode.INTERNAL_ERROR) { + val error = JsonRpcError(code.code, "load failed") + fireFrame(TransportFrame.Single(JsonRpcErrorResponse(request.id, error))) + } + + /** + * Returns after the client has handled every message sent before this call. + * + * The client reads messages in wire order and lets each notification handler run before it reads on, so its + * answer to a later request proves that the earlier notifications have been handled. + */ + suspend fun awaitHandled() { + val id = RequestId.create("barrier-${barrierIds.incrementAndGet()}") + fireFrame(TransportFrame.Single(JsonRpcRequest(id, MethodName("test/barrier"), null))) + awaitResponse(id) + } +} + +/** + * The updates that reached the client's global handler because no session took them, in arrival order. + */ +internal class UnconnectedUpdates { + private val received = MutableStateFlow>>(emptyList()) + + /** + * Every update with its session id. + */ + val value: List> get() = received.value + + /** + * The updates without their session ids. + */ + val updates: List get() = received.value.map { it.second } + + fun record(id: SessionId, update: SessionUpdate) { + received.update { it + (id to update) } + } + + suspend fun await(id: SessionId, update: SessionUpdate) { + withTimeout(5.seconds) { received.first { (id to update) in it } } + } + + suspend fun awaitCount(count: Int) { + withTimeout(5.seconds) { received.first { it.size >= count } } + } +} + +/** + * One connection of a test: the client, the scripted agent, the updates for unconnected sessions and the client's + * protocol. + */ +internal data class ScriptedConnection( + val client: Client, + val agent: ScriptedAgentTransport, + val unconnected: UnconnectedUpdates, + val protocol: Protocol, +) + +/** + * Runs [block] on a new connection, whose client protocol has [options], with a 60-second bound. + * + * [onUnconnected] runs in the global handler after each unconnected update is recorded, so a test can hold a drain + * there or make the handler throw. With [onDefault], [block] runs on [Dispatchers.Default], in parallel with the read + * loop; otherwise it runs on the single thread of `runBlocking`. + */ +internal fun withScriptedClient( + onUnconnected: suspend (SessionId, SessionUpdate) -> Unit = { _, _ -> }, + options: ProtocolOptions = ProtocolOptions(), + onDefault: Boolean = true, + block: suspend CoroutineScope.(ScriptedConnection) -> Unit, +) { + val scope = CoroutineScope(Dispatchers.Default + SupervisorJob()) + try { + val transport = ScriptedAgentTransport() + val protocol = Protocol(scope, transport, options) + protocol.start() + transport.start() + val unconnected = UnconnectedUpdates() + val client = Client(protocol, globalSessionUpdateHandler = { id, update, _ -> + unconnected.record(id, update) + onUnconnected(id, update) + }) + val connection = ScriptedConnection(client, transport, unconnected, protocol) + runBlocking { + if (onDefault) { + withContext(Dispatchers.Default) { withTimeout(60.seconds) { block(connection) } } + } else { + withTimeout(60.seconds) { block(connection) } + } + } + } finally { + scope.cancel() + } +} + +internal fun text(value: String) = SessionUpdate.AgentMessageChunk(ContentBlock.Text(value)) + +internal fun permissionRequest(id: SessionId, toolCall: String) = + RequestPermissionRequest(id, SessionUpdate.ToolCallUpdate(ToolCallId(toolCall)), emptyList()) + +internal fun decode(response: JsonRpcResponse, serializer: KSerializer): T = + ACPJson.decodeFromJsonElement(serializer, assertIs(response, "an answer, got $response").result) diff --git a/e2e/rust-agent/client-v1/src/e2eTest/kotlin/com/agentclientprotocol/e2e/rustagent/v1/RecordingClientOperations.kt b/e2e/rust-agent/client-v1/src/e2eTest/kotlin/com/agentclientprotocol/e2e/rustagent/v1/RecordingClientOperations.kt index 2f99e104..8a15109d 100644 --- a/e2e/rust-agent/client-v1/src/e2eTest/kotlin/com/agentclientprotocol/e2e/rustagent/v1/RecordingClientOperations.kt +++ b/e2e/rust-agent/client-v1/src/e2eTest/kotlin/com/agentclientprotocol/e2e/rustagent/v1/RecordingClientOperations.kt @@ -5,6 +5,7 @@ import com.agentclientprotocol.client.GlobalElicitationHandler import com.agentclientprotocol.common.ClientSessionOperations import com.agentclientprotocol.common.ElicitationOperations import com.agentclientprotocol.common.FileSystemOperations +import com.agentclientprotocol.common.SessionEvent import com.agentclientprotocol.common.TerminalOperations import com.agentclientprotocol.model.CompleteElicitationNotification import com.agentclientprotocol.model.CreateElicitationRequest @@ -83,8 +84,8 @@ class RecordingClientOperations : ClientSessionOperations, FileSystemOperations, return RequestPermissionResponse(RequestPermissionOutcome.Selected(allowOnce.optionId)) } - override suspend fun notify(notification: SessionUpdate, _meta: JsonElement?) { - notifications += notification + override suspend fun notify(event: SessionEvent) { + if (event is SessionEvent.Update) notifications += event.update } override suspend fun fsReadTextFile(path: String, line: UInt?, limit: UInt?, _meta: JsonElement?): ReadTextFileResponse { diff --git a/e2e/tck/agent-v1/src/main/kotlin/com/agentclientprotocol/tck/v1/TckAgentSupport.kt b/e2e/tck/agent-v1/src/main/kotlin/com/agentclientprotocol/tck/v1/TckAgentSupport.kt index 9846d452..0955714b 100644 --- a/e2e/tck/agent-v1/src/main/kotlin/com/agentclientprotocol/tck/v1/TckAgentSupport.kt +++ b/e2e/tck/agent-v1/src/main/kotlin/com/agentclientprotocol/tck/v1/TckAgentSupport.kt @@ -11,6 +11,7 @@ import com.agentclientprotocol.annotations.UnstableApi import com.agentclientprotocol.client.ClientInfo import com.agentclientprotocol.common.Event import com.agentclientprotocol.common.SessionCreationParameters +import com.agentclientprotocol.common.notify import com.agentclientprotocol.model.* import com.agentclientprotocol.protocol.jsonRpcInvalidParams import io.github.oshai.kotlinlogging.KotlinLogging diff --git a/samples/kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/support/TerminalClientSupport.kt b/samples/kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/support/TerminalClientSupport.kt index 378b70e1..8d204600 100644 --- a/samples/kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/support/TerminalClientSupport.kt +++ b/samples/kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/support/TerminalClientSupport.kt @@ -5,6 +5,7 @@ import com.agentclientprotocol.common.ClientSessionOperations import com.agentclientprotocol.common.Event import com.agentclientprotocol.common.FileSystemOperations import com.agentclientprotocol.common.SessionCreationParameters +import com.agentclientprotocol.common.SessionEvent import com.agentclientprotocol.common.TerminalOperations import com.agentclientprotocol.model.* import com.agentclientprotocol.protocol.Protocol @@ -43,12 +44,18 @@ class TerminalClientSessionOperations : ClientSessionOperations, FileSystemOpera } } - override suspend fun notify( - notification: SessionUpdate, - _meta: JsonElement?, - ) { - println("Agent sent notification:") - notification.render() + override suspend fun notify(event: SessionEvent) { + when (event) { + is SessionEvent.Update -> { + println("Agent sent notification:") + event.update.render() + } + /* + * Updates before Opened arrived before the opening call's answer, like the history that session/load + * replays. + */ + is SessionEvent.Opened -> println("Session opened, later updates are live") + } } override suspend fun fsReadTextFile(