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
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ Cross-transport integration and conformance-style tests. Use this module for beh

### `:samples:kotlin-acp-client-sample`

Runnable examples for stable ACP, direct v2 use, negotiation, and external-agent integration. Samples should demonstrate supported public APIs, not internal shortcuts.
Runnable examples for stable ACP, direct v2 use, negotiation, authentication, subagents, and external-agent integration. Samples should demonstrate supported public APIs, not internal shortcuts.

Each sample has its own package under `com.agentclientprotocol.samples`, with shared helpers in `support`, and its own Gradle run task registered with `registerSampleTask` in the module's `build.gradle.kts`. `samples/README.md` is the table of contents. A new sample adds a package, a task, its own `README.md` in its package, and a row in `samples/README.md`. The module's JVM tests (`src/test`) run scripted samples through their entry points, so `./gradlew check` catches a sample that an SDK change breaks.

### `e2e`

Expand Down
6 changes: 6 additions & 0 deletions samples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ Each sample has its own README in its package, linked from the first column.
| [v2][v2] | A v2 client and a v2 agent talking directly | v2 | `runV2SimpleAgent` | nothing |
| [v2][v2] | `ClientNegotiator` choosing between v1 and v2, then the v2 conversation | negotiated | `runV2Negotiation` | nothing |
| [auth][auth] | The unstable `auth/status` query, without a session | v1 and v2 | `runAuthStatus` | nothing |
| [subagents][subagents] | An agent that delegates to subagents, and a client that shows, cancels and closes them | v1 | `runSubagents` | nothing |

The v2, `auth/status` and subagent APIs are unstable (`@UnstableApi`) and need an explicit opt-in.

The package [`support`][support] is not a sample. It has the helpers that several samples share: the interactive
terminal client, in-memory transports, the transport to an external process, and console rendering of updates.
Expand Down Expand Up @@ -46,9 +49,12 @@ has no task of its own yet:
2. Register a task for it with `registerSampleTask` in `build.gradle.kts`.
3. Add a `README.md` to the package: what the sample shows, how to run it, and its files.
4. Add a row to the table above, linking to that README.
5. If it runs without input or external tools, add a test under `src/test` that runs its entry point, as
`SubagentsSampleTest` does. `./gradlew check` runs it.

[simple]: kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/simple/README.md
[gemini]: kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/gemini/README.md
[v2]: kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/v2/README.md
[auth]: kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/auth/README.md
[subagents]: kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/subagents/README.md
[support]: kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/support
23 changes: 23 additions & 0 deletions samples/kotlin-acp-client-sample/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,22 @@ dependencies {
implementation(libs.logback.classic)
}

/*
* The tests run scripted samples end to end, so that a change in the SDK that breaks a sample fails `check`.
*/
testing {
suites {
@Suppress("UnstableApiUsage")
named<JvmTestSuite>("test") {
useJUnitJupiter(libs.versions.junit.get())

dependencies {
implementation("org.jetbrains.kotlin:kotlin-test-junit5")
}
}
}
}

/*
* The plain `run` task starts the simple agent by default; override it with
* `-PmainClass=<fully qualified main class>`.
Expand Down Expand Up @@ -68,3 +84,10 @@ registerSampleTask(
"Queries the unstable auth/status method over v1 and v2 without a session.",
"com.agentclientprotocol.samples.auth.AuthStatusAppKt"
)
registerSampleTask(
"runSubagents",
"Runs a scripted agent that delegates to subagents, and a client that shows, cancels and closes them (ACP v1).",
"com.agentclientprotocol.samples.subagents.SubagentsAppKt"
).configure {
systemProperty("logback.configurationFile", "logback-subagents.xml")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# subagents

An agent that delegates work to subagents, and a client that shows, cancels and closes them.

- Protocol: ACP v1 (the `subagents` capability).
- Needs: nothing.
- Package: `com.agentclientprotocol.samples.subagents`.

The subagent protocol is stable in v1, but the SDK's Kotlin API for it (`@UnstableApi`) may still change, so the sample
opts in explicitly.

## What it shows

A scripted run with no input. The client opens a session and sends two prompts, then closes the session.

- The agent delegates the first prompt to three subagents. The reviewer completes, the user cancels the cleaner while
its permission request is pending, and the tester fails after it started a grandchild whose feed is lost.
- The agent relays the second prompt to a native agent, whose workers become nested subagents.

Then the client loads the closed session again.

- The agent tells the session's history again from its own record of each turn, subagents included. Each stream gets
its history, then `Opened`, then live updates.
- The replayed subagents start with no confirmed state and no cancel grant. The agent grants cancel again to the
reviewer, which works on a new task, and the user cancels it.
- The client then closes the session again.

The app prints what each side sees.

## How to run

From the repository root:

```bash
./gradlew :samples:kotlin-acp-client-sample:runSubagents
```

The streams of different sessions are delivered concurrently, so lines of different sessions may interleave
differently from run to run. The task logs only warnings, to stderr, through `logback-subagents.xml`.

One warning may appear, depending on timing. When the user cancels the cleaner, the client answers its pending
permission request `cancelled`, and the agent stops the cleaner's work. If the agent's stop cancels the request before
the answer arrives, the agent sends `$/cancel_request` for it, and the client logs that it got a cancel for a request
it has already answered.

## Where to start

Read [`agent/DelegatingAgentSession.kt`](agent/DelegatingAgentSession.kt) first for the agent side and
[`client/SubagentsClient.kt`](client/SubagentsClient.kt) for the client side.
[`SubagentsApp.kt`](SubagentsApp.kt) wires them together in one process, and [`Transcript.kt`](Transcript.kt) holds the
lines both sides write.

## Files

Each file is named after the SDK type it implements or mainly uses.

The agent side, in package `agent`:

- [`DelegatingAgentSupport.kt`](agent/DelegatingAgentSupport.kt): the `AgentSupport`; it opens a
`DelegatingAgentSession`.
- [`DelegatingAgentSession.kt`](agent/DelegatingAgentSession.kt): the root `AgentSession`, which delegates or relays
each prompt and replays the history on `session/load`.
- [`DelegatedSubagentFactory.kt`](agent/DelegatedSubagentFactory.kt): the `AgentSubagentFactory` that sends a delegated
child's announcement.
- [`DelegatedSubagentSession.kt`](agent/DelegatedSubagentSession.kt): the `AgentSubagentSession` of a delegated child;
it runs a `DelegatedTask`.
- [`DelegatedTask.kt`](agent/DelegatedTask.kt): a task, and what its work can do through the child's context.
- [`SampleTasks.kt`](agent/SampleTasks.kt): the reviewer, cleaner and tester tasks, and the reviewer's task after the
load.
- [`SessionRecord.kt`](agent/SessionRecord.kt): what the root, each of its turns and each subagent did, which the root
tells again on `session/load`.
- [`RemoteProbeSubagentSession.kt`](agent/RemoteProbeSubagentSession.kt): the tester's grandchild.
- [`NativeRelayedSubagentSession.kt`](agent/NativeRelayedSubagentSession.kt): the `AgentSubagentSession` of one
relayed worker of a native agent, and the relay loop that builds the tree from the flat event stream.
- [`FakeNativeAgent.kt`](agent/FakeNativeAgent.kt): the simulated native agent and its flat event stream; it uses no SDK
type.
- [`SessionUpdates.kt`](agent/SessionUpdates.kt): small builders for the updates the agent sends, and its
transcript lines.

The client side, in package `client`:

- [`SubagentsClient.kt`](client/SubagentsClient.kt): runs the `Client`: initialize, the two prompts, close, load, close.
- [`TreeClientSessionOperations.kt`](client/TreeClientSessionOperations.kt): the `ClientSessionOperations` and
`SubagentOperations` shared by every session.
- [`RootClientSessionOperations.kt`](client/RootClientSessionOperations.kt) and
[`SubagentClientSessionOperations.kt`](client/SubagentClientSessionOperations.kt): the operations of the root and of a
subagent.
- [`ScriptedUser.kt`](client/ScriptedUser.kt): answers permission requests, or cancels the subagent that asks.
- [`ClientTranscript.kt`](client/ClientTranscript.kt): writes the client's lines and renders sessions and updates.

## Where each scenario lives

The numbers are those of the section comments in each side's files.

| Scenario | Agent | Client |
| --- | --- | --- |
| The `subagents` capability | `DelegatingAgentSession` (1: no capability, work inline) | `SubagentsClient` (1) |
| Announcing a child, and the operations that receive it | `DelegatedSubagentFactory` (2) | `TreeClientSessionOperations` (2) |
| A child's requests, such as a permission request | `DelegatedTask` (3) | `SubagentClientSessionOperations`, `ScriptedUser` (5) |
| Links from the parent: `session_message`, session tool call content | `DelegatingAgentSession` (4) | `TreeClientSessionOperations`, `SubagentsClient` (3) |
| Patches to a child | `DelegatedTask` (5) | `TreeClientSessionOperations` (3) |
| A child's own stream: history, `Opened`, live updates | | `SubagentClientSessionOperations` (4) |
| Cancel | `DelegatedSubagentSession` (6) | `ScriptedUser` (5, 6) |
| Failure, and the SDK's `unknown` | `DelegatedSubagentSession`, `RemoteProbeSubagentSession` (7) | |
| A grandchild | `RemoteProbeSubagentSession` (8) | `TreeClientSessionOperations` (3) |
| Closing the root | `DelegatingAgentSession` (9) | `SubagentsClient` (7) |
| Relay of a native agent, `announce(…, parent = …)` | `NativeRelayedSubagentSession` (10) | |
| `session/load`: the root tells each turn again from its record | `DelegatingAgentSession` (11) | `SubagentsClient` (9), `TreeClientSessionOperations` (8) |
| A replayed child's own history, its children included | `DelegatingAgentSession` (12) | |
| The replayed tree, at each parent's `Opened` | | `TreeClientSessionOperations` (11) |
| A fresh cancel grant after the load | `DelegatingAgentSession` (13) | `SubagentsClient` (10) |
| The current state of a finished child after the load | `DelegatingAgentSession` (14) | |

## Tests

`SubagentsSampleTest` runs the same script, on one thread and on `Dispatchers.Default`, and checks its key events, so
`./gradlew check` fails if the sample breaks. `agent/DelegatedWorkTest` checks how a task's end maps to its `idle` stop
reason. Both are under `src/test`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.agentclientprotocol.samples.subagents

import com.agentclientprotocol.agent.Agent
import com.agentclientprotocol.protocol.Protocol
import com.agentclientprotocol.samples.subagents.agent.DelegatingAgentSupport
import com.agentclientprotocol.samples.subagents.client.SubagentsSessions
import com.agentclientprotocol.samples.subagents.client.runSubagentsClient
import com.agentclientprotocol.samples.support.createInMemoryTransportPair
import kotlinx.coroutines.coroutineScope

/**
* Runs the subagents sample (ACP v1): an agent that delegates work to subagents, and a client that shows them, in one
* process. It prints a transcript of what each side sees.
*
* The client's script:
* 1. initializes the connection with the `subagents` capability and opens a session;
* 2. sends a prompt that the agent delegates to three subagents: the reviewer completes, the user cancels the cleaner
* while its permission request is pending, and the tester fails after it started a grandchild;
* 3. sends a prompt that the agent relays to a native agent, whose workers become nested subagents;
* 4. closes the session, which closes every subagent below it;
* 5. loads the session again: the agent replays its history and its subagents, and grants cancel again to the
* reviewer, which the user then cancels;
* 6. closes the session again.
*
* Each line names the side and the session it belongs to. The streams of different sessions are delivered
* concurrently, so their lines may interleave differently from run to run; the lines of one session keep their order.
*
* Start reading the agent at `agent/DelegatingAgentSession.kt` and the client at `client/SubagentsClient.kt`.
*/
suspend fun main() {
runSubagentsSample(Transcript { line -> println(line.render()) })
}

/**
* Connects the agent and the client of the sample in this process and runs the client's script.
*
* @param declareSubagents whether the client declares the `subagents` capability
* @return the opened and the loaded root session, both closed
*/
suspend fun runSubagentsSample(
transcript: Transcript,
declareSubagents: Boolean = true,
): SubagentsSessions = coroutineScope {
val transports = createInMemoryTransportPair()
val agentProtocol = Protocol(this, transports.agent)
Agent(agentProtocol, DelegatingAgentSupport(transcript))
agentProtocol.start()

try {
runSubagentsClient(transports.client, transcript, declareSubagents)
} finally {
agentProtocol.close()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.agentclientprotocol.samples.subagents

import com.agentclientprotocol.model.IdleStopReason
import com.agentclientprotocol.model.SessionId
import com.agentclientprotocol.model.SessionUpdate
import com.agentclientprotocol.model.StateUpdate

/**
* Where both sides of the sample write what they see.
*
* [add] is called from several coroutines at once, so an implementation must be thread-safe.
*/
fun interface Transcript {
fun add(line: TranscriptLine)
}

/**
* Which side of the connection wrote a [TranscriptLine].
*/
enum class Side { AGENT, CLIENT }

/**
* One line of the transcript.
*
* @property sessionId the session the line is about, `null` for the connection
* @property update the update the client shows on this line, if any
*/
data class TranscriptLine(
val side: Side,
val sessionId: SessionId?,
val text: String,
val update: SessionUpdate? = null,
) {
fun render(): String = "${side.name.lowercase().padEnd(6)} ${(sessionId?.value ?: "-").padEnd(14)} $text"
}

internal fun StateUpdate?.describe(): String = when (this) {
null -> "no confirmed state"
is StateUpdate.Running -> "running"
is StateUpdate.RequiresAction -> "requires action"
is StateUpdate.Idle -> stopReason?.let { "idle (${it.describe()})" } ?: "idle"
is StateUpdate.Unknown -> "unknown"
is StateUpdate.Other -> state
}

internal fun IdleStopReason.describe(): String = when (this) {
IdleStopReason.EndTurn -> "end_turn"
IdleStopReason.MaxTokens -> "max_tokens"
IdleStopReason.MaxTurnRequests -> "max_turn_requests"
IdleStopReason.Refusal -> "refusal"
IdleStopReason.Cancelled -> "cancelled"
is IdleStopReason.Error -> "error: ${error?.message}"
is IdleStopReason.Other -> stopReason
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
@file:OptIn(UnstableApi::class)

package com.agentclientprotocol.samples.subagents.agent

import com.agentclientprotocol.agent.AgentSubagentContext
import com.agentclientprotocol.agent.AgentSubagentFactory
import com.agentclientprotocol.annotations.UnstableApi
import com.agentclientprotocol.common.notify
import com.agentclientprotocol.model.MaybeUndefined
import com.agentclientprotocol.model.SessionCancelCapabilities
import com.agentclientprotocol.model.SessionId
import com.agentclientprotocol.model.SessionUpdate
import com.agentclientprotocol.model.StateUpdate
import com.agentclientprotocol.model.SubagentSessionCapabilities
import com.agentclientprotocol.samples.subagents.Transcript

/**
* The `capabilities` that let the client send `session/cancel` for a child.
*/
internal val cancelGrant = SubagentSessionCapabilities(cancel = SessionCancelCapabilities())

/**
* Builds the child that runs [task] for the parent [parentId], for `AgentSubagents.announce`.
*
* Scenario in this file: 2. announcing a child.
*/
internal class DelegatedSubagentFactory(
private val task: DelegatedTask,
private val parentId: SessionId,
private val transcript: Transcript,
) : AgentSubagentFactory<DelegatedSubagentSession> {
/*
* 2. Announcing a child
*
* `announce` registers the id, calls this, then collects the `events` of the session it returns. The announcement,
* a `subagent_update` for the child that the SDK sends on the parent's stream, must be the first thing sent for
* the child. Here it goes through the child's `client`, with:
* - the title and description the client lists the child with;
* - the cancel grant, `capabilities.cancel`, which lets the client send `session/cancel` for the child;
* - the state `running`, because the work starts with the announcement.
*/
override suspend fun createSubagent(context: AgentSubagentContext): DelegatedSubagentSession {
val announcement = SessionUpdate.SubagentUpdate(
task.id,
title = MaybeUndefined.Value(task.title),
description = MaybeUndefined.Value(task.description),
capabilities = MaybeUndefined.Value(cancelGrant),
state = MaybeUndefined.Value(StateUpdate.Running()),
)
context.client.notify(announcement)
val record = SubagentRecord(announcement)
return DelegatedSubagentSession(task, parentId, task.sentMessageId, context, record, transcript)
}
}
Loading
Loading