Skip to content

Commit 3ff8495

Browse files
committed
docs(samples): add a subagents sample
- A scripted v1 agent that delegates to subagents and relays a native agent's workers as nested subagents, and a client that shows, cancels and closes them, then loads the session again. - Its `runSubagents` task, logback configuration and README, and a row in `samples/README.md`. - JVM tests that run the sample end to end, so `check` catches an SDK change that breaks it. - AGENTS.md: how samples are laid out and tested.
1 parent 65fb4e6 commit 3ff8495

27 files changed

Lines changed: 2580 additions & 1 deletion

‎AGENTS.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,9 @@ Cross-transport integration and conformance-style tests. Use this module for beh
5959

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

62-
Runnable examples for stable ACP, direct v2 use, negotiation, and external-agent integration. Samples should demonstrate supported public APIs, not internal shortcuts.
62+
Runnable examples for stable ACP, direct v2 use, negotiation, authentication, subagents, and external-agent integration. Samples should demonstrate supported public APIs, not internal shortcuts.
63+
64+
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.
6365

6466
### `e2e`
6567

‎samples/README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ Each sample has its own README in its package, linked from the first column.
1717
| [v2][v2] | A v2 client and a v2 agent talking directly | v2 | `runV2SimpleAgent` | nothing |
1818
| [v2][v2] | `ClientNegotiator` choosing between v1 and v2, then the v2 conversation | negotiated | `runV2Negotiation` | nothing |
1919
| [auth][auth] | The unstable `auth/status` query, without a session | v1 and v2 | `runAuthStatus` | nothing |
20+
| [subagents][subagents] | An agent that delegates to subagents, and a client that shows, cancels and closes them | v1 | `runSubagents` | nothing |
21+
22+
The v2, `auth/status` and subagent APIs are unstable (`@UnstableApi`) and need an explicit opt-in.
2023

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

5055
[simple]: kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/simple/README.md
5156
[gemini]: kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/gemini/README.md
5257
[v2]: kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/v2/README.md
5358
[auth]: kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/auth/README.md
59+
[subagents]: kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/subagents/README.md
5460
[support]: kotlin-acp-client-sample/src/main/kotlin/com/agentclientprotocol/samples/support

‎samples/kotlin-acp-client-sample/build.gradle.kts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,22 @@ dependencies {
1212
implementation(libs.logback.classic)
1313
}
1414

15+
/*
16+
* The tests run scripted samples end to end, so that a change in the SDK that breaks a sample fails `check`.
17+
*/
18+
testing {
19+
suites {
20+
@Suppress("UnstableApiUsage")
21+
named<JvmTestSuite>("test") {
22+
useJUnitJupiter(libs.versions.junit.get())
23+
24+
dependencies {
25+
implementation("org.jetbrains.kotlin:kotlin-test-junit5")
26+
}
27+
}
28+
}
29+
}
30+
1531
/*
1632
* The plain `run` task starts the simple agent by default; override it with
1733
* `-PmainClass=<fully qualified main class>`.
@@ -68,3 +84,10 @@ registerSampleTask(
6884
"Queries the unstable auth/status method over v1 and v2 without a session.",
6985
"com.agentclientprotocol.samples.auth.AuthStatusAppKt"
7086
)
87+
registerSampleTask(
88+
"runSubagents",
89+
"Runs a scripted agent that delegates to subagents, and a client that shows, cancels and closes them (ACP v1).",
90+
"com.agentclientprotocol.samples.subagents.SubagentsAppKt"
91+
).configure {
92+
systemProperty("logback.configurationFile", "logback-subagents.xml")
93+
}
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
# subagents
2+
3+
An agent that delegates work to subagents, and a client that shows, cancels and closes them.
4+
5+
- Protocol: ACP v1 (the `subagents` capability).
6+
- Needs: nothing.
7+
- Package: `com.agentclientprotocol.samples.subagents`.
8+
9+
The subagent protocol is stable in v1, but the SDK's Kotlin API for it (`@UnstableApi`) may still change, so the sample
10+
opts in explicitly.
11+
12+
## What it shows
13+
14+
A scripted run with no input. The client opens a session and sends two prompts, then closes the session.
15+
16+
- The agent delegates the first prompt to three subagents. The reviewer completes, the user cancels the cleaner while
17+
its permission request is pending, and the tester fails after it started a grandchild whose feed is lost.
18+
- The agent relays the second prompt to a native agent, whose workers become nested subagents.
19+
20+
Then the client loads the closed session again.
21+
22+
- The agent tells the session's history again from its own record of each turn, subagents included. Each stream gets
23+
its history, then `Opened`, then live updates.
24+
- The replayed subagents start with no confirmed state and no cancel grant. The agent grants cancel again to the
25+
reviewer, which works on a new task, and the user cancels it.
26+
- The client then closes the session again.
27+
28+
The app prints what each side sees.
29+
30+
## How to run
31+
32+
From the repository root:
33+
34+
```bash
35+
./gradlew :samples:kotlin-acp-client-sample:runSubagents
36+
```
37+
38+
The streams of different sessions are delivered concurrently, so lines of different sessions may interleave
39+
differently from run to run. The task logs only warnings, to stderr, through `logback-subagents.xml`.
40+
41+
One warning may appear, depending on timing. When the user cancels the cleaner, the client answers its pending
42+
permission request `cancelled`, and the agent stops the cleaner's work. If the agent's stop cancels the request before
43+
the answer arrives, the agent sends `$/cancel_request` for it, and the client logs that it got a cancel for a request
44+
it has already answered.
45+
46+
## Where to start
47+
48+
Read [`agent/DelegatingAgentSession.kt`](agent/DelegatingAgentSession.kt) first for the agent side and
49+
[`client/SubagentsClient.kt`](client/SubagentsClient.kt) for the client side.
50+
[`SubagentsApp.kt`](SubagentsApp.kt) wires them together in one process, and [`Transcript.kt`](Transcript.kt) holds the
51+
lines both sides write.
52+
53+
## Files
54+
55+
Each file is named after the SDK type it implements or mainly uses.
56+
57+
The agent side, in package `agent`:
58+
59+
- [`DelegatingAgentSupport.kt`](agent/DelegatingAgentSupport.kt): the `AgentSupport`; it opens a
60+
`DelegatingAgentSession`.
61+
- [`DelegatingAgentSession.kt`](agent/DelegatingAgentSession.kt): the root `AgentSession`, which delegates or relays
62+
each prompt and replays the history on `session/load`.
63+
- [`DelegatedSubagentFactory.kt`](agent/DelegatedSubagentFactory.kt): the `AgentSubagentFactory` that sends a delegated
64+
child's announcement.
65+
- [`DelegatedSubagentSession.kt`](agent/DelegatedSubagentSession.kt): the `AgentSubagentSession` of a delegated child;
66+
it runs a `DelegatedTask`.
67+
- [`DelegatedTask.kt`](agent/DelegatedTask.kt): a task, and what its work can do through the child's context.
68+
- [`SampleTasks.kt`](agent/SampleTasks.kt): the reviewer, cleaner and tester tasks, and the reviewer's task after the
69+
load.
70+
- [`SessionRecord.kt`](agent/SessionRecord.kt): what the root, each of its turns and each subagent did, which the root
71+
tells again on `session/load`.
72+
- [`RemoteProbeSubagentSession.kt`](agent/RemoteProbeSubagentSession.kt): the tester's grandchild.
73+
- [`NativeRelayedSubagentSession.kt`](agent/NativeRelayedSubagentSession.kt): the `AgentSubagentSession` of one
74+
relayed worker of a native agent, and the relay loop that builds the tree from the flat event stream.
75+
- [`FakeNativeAgent.kt`](agent/FakeNativeAgent.kt): the simulated native agent and its flat event stream; it uses no SDK
76+
type.
77+
- [`SessionUpdates.kt`](agent/SessionUpdates.kt): small builders for the updates the agent sends, and its
78+
transcript lines.
79+
80+
The client side, in package `client`:
81+
82+
- [`SubagentsClient.kt`](client/SubagentsClient.kt): runs the `Client`: initialize, the two prompts, close, load, close.
83+
- [`TreeClientSessionOperations.kt`](client/TreeClientSessionOperations.kt): the `ClientSessionOperations` and
84+
`SubagentOperations` shared by every session.
85+
- [`RootClientSessionOperations.kt`](client/RootClientSessionOperations.kt) and
86+
[`SubagentClientSessionOperations.kt`](client/SubagentClientSessionOperations.kt): the operations of the root and of a
87+
subagent.
88+
- [`ScriptedUser.kt`](client/ScriptedUser.kt): answers permission requests, or cancels the subagent that asks.
89+
- [`ClientTranscript.kt`](client/ClientTranscript.kt): writes the client's lines and renders sessions and updates.
90+
91+
## Where each scenario lives
92+
93+
The numbers are those of the section comments in each side's files.
94+
95+
| Scenario | Agent | Client |
96+
| --- | --- | --- |
97+
| The `subagents` capability | `DelegatingAgentSession` (1: no capability, work inline) | `SubagentsClient` (1) |
98+
| Announcing a child, and the operations that receive it | `DelegatedSubagentFactory` (2) | `TreeClientSessionOperations` (2) |
99+
| A child's requests, such as a permission request | `DelegatedTask` (3) | `SubagentClientSessionOperations`, `ScriptedUser` (5) |
100+
| Links from the parent: `session_message`, session tool call content | `DelegatingAgentSession` (4) | `TreeClientSessionOperations`, `SubagentsClient` (3) |
101+
| Patches to a child | `DelegatedTask` (5) | `TreeClientSessionOperations` (3) |
102+
| A child's own stream: history, `Opened`, live updates | | `SubagentClientSessionOperations` (4) |
103+
| Cancel | `DelegatedSubagentSession` (6) | `ScriptedUser` (5, 6) |
104+
| Failure, and the SDK's `unknown` | `DelegatedSubagentSession`, `RemoteProbeSubagentSession` (7) | |
105+
| A grandchild | `RemoteProbeSubagentSession` (8) | `TreeClientSessionOperations` (3) |
106+
| Closing the root | `DelegatingAgentSession` (9) | `SubagentsClient` (7) |
107+
| Relay of a native agent, `announce(…, parent = …)` | `NativeRelayedSubagentSession` (10) | |
108+
| `session/load`: the root tells each turn again from its record | `DelegatingAgentSession` (11) | `SubagentsClient` (9), `TreeClientSessionOperations` (8) |
109+
| A replayed child's own history, its children included | `DelegatingAgentSession` (12) | |
110+
| The replayed tree, at each parent's `Opened` | | `TreeClientSessionOperations` (11) |
111+
| A fresh cancel grant after the load | `DelegatingAgentSession` (13) | `SubagentsClient` (10) |
112+
| The current state of a finished child after the load | `DelegatingAgentSession` (14) | |
113+
114+
## Tests
115+
116+
`SubagentsSampleTest` runs the same script, on one thread and on `Dispatchers.Default`, and checks its key events, so
117+
`./gradlew check` fails if the sample breaks. `agent/DelegatedWorkTest` checks how a task's end maps to its `idle` stop
118+
reason. Both are under `src/test`.
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.agentclientprotocol.samples.subagents
2+
3+
import com.agentclientprotocol.agent.Agent
4+
import com.agentclientprotocol.protocol.Protocol
5+
import com.agentclientprotocol.samples.subagents.agent.DelegatingAgentSupport
6+
import com.agentclientprotocol.samples.subagents.client.SubagentsSessions
7+
import com.agentclientprotocol.samples.subagents.client.runSubagentsClient
8+
import com.agentclientprotocol.samples.support.createInMemoryTransportPair
9+
import kotlinx.coroutines.coroutineScope
10+
11+
/**
12+
* Runs the subagents sample (ACP v1): an agent that delegates work to subagents, and a client that shows them, in one
13+
* process. It prints a transcript of what each side sees.
14+
*
15+
* The client's script:
16+
* 1. initializes the connection with the `subagents` capability and opens a session;
17+
* 2. sends a prompt that the agent delegates to three subagents: the reviewer completes, the user cancels the cleaner
18+
* while its permission request is pending, and the tester fails after it started a grandchild;
19+
* 3. sends a prompt that the agent relays to a native agent, whose workers become nested subagents;
20+
* 4. closes the session, which closes every subagent below it;
21+
* 5. loads the session again: the agent replays its history and its subagents, and grants cancel again to the
22+
* reviewer, which the user then cancels;
23+
* 6. closes the session again.
24+
*
25+
* Each line names the side and the session it belongs to. The streams of different sessions are delivered
26+
* concurrently, so their lines may interleave differently from run to run; the lines of one session keep their order.
27+
*
28+
* Start reading the agent at `agent/DelegatingAgentSession.kt` and the client at `client/SubagentsClient.kt`.
29+
*/
30+
suspend fun main() {
31+
runSubagentsSample(Transcript { line -> println(line.render()) })
32+
}
33+
34+
/**
35+
* Connects the agent and the client of the sample in this process and runs the client's script.
36+
*
37+
* @param declareSubagents whether the client declares the `subagents` capability
38+
* @return the opened and the loaded root session, both closed
39+
*/
40+
suspend fun runSubagentsSample(
41+
transcript: Transcript,
42+
declareSubagents: Boolean = true,
43+
): SubagentsSessions = coroutineScope {
44+
val transports = createInMemoryTransportPair()
45+
val agentProtocol = Protocol(this, transports.agent)
46+
Agent(agentProtocol, DelegatingAgentSupport(transcript))
47+
agentProtocol.start()
48+
49+
try {
50+
runSubagentsClient(transports.client, transcript, declareSubagents)
51+
} finally {
52+
agentProtocol.close()
53+
}
54+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.agentclientprotocol.samples.subagents
2+
3+
import com.agentclientprotocol.model.IdleStopReason
4+
import com.agentclientprotocol.model.SessionId
5+
import com.agentclientprotocol.model.SessionUpdate
6+
import com.agentclientprotocol.model.StateUpdate
7+
8+
/**
9+
* Where both sides of the sample write what they see.
10+
*
11+
* [add] is called from several coroutines at once, so an implementation must be thread-safe.
12+
*/
13+
fun interface Transcript {
14+
fun add(line: TranscriptLine)
15+
}
16+
17+
/**
18+
* Which side of the connection wrote a [TranscriptLine].
19+
*/
20+
enum class Side { AGENT, CLIENT }
21+
22+
/**
23+
* One line of the transcript.
24+
*
25+
* @property sessionId the session the line is about, `null` for the connection
26+
* @property update the update the client shows on this line, if any
27+
*/
28+
data class TranscriptLine(
29+
val side: Side,
30+
val sessionId: SessionId?,
31+
val text: String,
32+
val update: SessionUpdate? = null,
33+
) {
34+
fun render(): String = "${side.name.lowercase().padEnd(6)} ${(sessionId?.value ?: "-").padEnd(14)} $text"
35+
}
36+
37+
internal fun StateUpdate?.describe(): String = when (this) {
38+
null -> "no confirmed state"
39+
is StateUpdate.Running -> "running"
40+
is StateUpdate.RequiresAction -> "requires action"
41+
is StateUpdate.Idle -> stopReason?.let { "idle (${it.describe()})" } ?: "idle"
42+
is StateUpdate.Unknown -> "unknown"
43+
is StateUpdate.Other -> state
44+
}
45+
46+
internal fun IdleStopReason.describe(): String = when (this) {
47+
IdleStopReason.EndTurn -> "end_turn"
48+
IdleStopReason.MaxTokens -> "max_tokens"
49+
IdleStopReason.MaxTurnRequests -> "max_turn_requests"
50+
IdleStopReason.Refusal -> "refusal"
51+
IdleStopReason.Cancelled -> "cancelled"
52+
is IdleStopReason.Error -> "error: ${error?.message}"
53+
is IdleStopReason.Other -> stopReason
54+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
@file:OptIn(UnstableApi::class)
2+
3+
package com.agentclientprotocol.samples.subagents.agent
4+
5+
import com.agentclientprotocol.agent.AgentSubagentContext
6+
import com.agentclientprotocol.agent.AgentSubagentFactory
7+
import com.agentclientprotocol.annotations.UnstableApi
8+
import com.agentclientprotocol.common.notify
9+
import com.agentclientprotocol.model.MaybeUndefined
10+
import com.agentclientprotocol.model.SessionCancelCapabilities
11+
import com.agentclientprotocol.model.SessionId
12+
import com.agentclientprotocol.model.SessionUpdate
13+
import com.agentclientprotocol.model.StateUpdate
14+
import com.agentclientprotocol.model.SubagentSessionCapabilities
15+
import com.agentclientprotocol.samples.subagents.Transcript
16+
17+
/**
18+
* The `capabilities` that let the client send `session/cancel` for a child.
19+
*/
20+
internal val cancelGrant = SubagentSessionCapabilities(cancel = SessionCancelCapabilities())
21+
22+
/**
23+
* Builds the child that runs [task] for the parent [parentId], for `AgentSubagents.announce`.
24+
*
25+
* Scenario in this file: 2. announcing a child.
26+
*/
27+
internal class DelegatedSubagentFactory(
28+
private val task: DelegatedTask,
29+
private val parentId: SessionId,
30+
private val transcript: Transcript,
31+
) : AgentSubagentFactory<DelegatedSubagentSession> {
32+
/*
33+
* 2. Announcing a child
34+
*
35+
* `announce` registers the id, calls this, then collects the `events` of the session it returns. The announcement,
36+
* a `subagent_update` for the child that the SDK sends on the parent's stream, must be the first thing sent for
37+
* the child. Here it goes through the child's `client`, with:
38+
* - the title and description the client lists the child with;
39+
* - the cancel grant, `capabilities.cancel`, which lets the client send `session/cancel` for the child;
40+
* - the state `running`, because the work starts with the announcement.
41+
*/
42+
override suspend fun createSubagent(context: AgentSubagentContext): DelegatedSubagentSession {
43+
val announcement = SessionUpdate.SubagentUpdate(
44+
task.id,
45+
title = MaybeUndefined.Value(task.title),
46+
description = MaybeUndefined.Value(task.description),
47+
capabilities = MaybeUndefined.Value(cancelGrant),
48+
state = MaybeUndefined.Value(StateUpdate.Running()),
49+
)
50+
context.client.notify(announcement)
51+
val record = SubagentRecord(announcement)
52+
return DelegatedSubagentSession(task, parentId, task.sentMessageId, context, record, transcript)
53+
}
54+
}

0 commit comments

Comments
 (0)