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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 68 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,19 +146,40 @@ 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.
- The response hook of `sendRequestRaw` (and the typed `Protocol.sendRequest`) runs in the read loop for a success response, before the caller resumes and before the next message. It must not suspend, block or throw. If it runs, it has finished before the call returns or throws. It may have run for a call that then ends with `CancellationException`, so the caller's failure path must undo or complete what the hook did: an opening undoes it, a close completes it.
- `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.
Expand Down Expand Up @@ -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.
Expand Down
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)

Expand Down
Loading
Loading