Skip to content

Commit cf2e520

Browse files
author
Mark Pollack
committed
acp-turn-queue: send each turn as its submitter; end a turn before the next starts
A waiting turn is sent from the thread that delivered the previous answer, so the client's identity capture read that thread: the turn reached the agent as no one (refused -32002 under ownerOnly) or as another user. submit now finds the submitter on the submitting thread (client.currentIdentity()) and the prompt is sent as them, or as no one, inside AcpIdentityContext.runAs. When a turn ends, its response now completes first, then turnFinished, and only then does the session's next turn start; a turn submitted from those callbacks waits behind the ending one. TurnListener.turnFinished takes the response or the error: turnFinished(turn, response, error).
1 parent 78ae471 commit cf2e520

11 files changed

Lines changed: 586 additions & 58 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
3737
(`contextWrite(AcpIdentityContext.with(identity))`) or on the thread (`AcpIdentityContext.callAs(identity, ..)`),
3838
such as an agent handler's, wins. One client connection serves every user of the application, and each message goes
3939
as the user of the request that sent it. A `prompt(request, stop)` cancels as the prompt's user, from any thread.
40+
`AcpAsyncClient.currentIdentity()` and `AcpSyncClient.currentIdentity()` return who a call sent now from this thread
41+
would go as (the thread's identity, else the capture's), so code that sends later from another thread can send as
42+
that user (`AcpIdentityContext.runAs`); `AcpIdentityContext.resolveOnThread(capture)` is the same lookup. A call
43+
decided to be for no one (`AcpIdentityContext.put(context, null)`, `callAs(null, ..)`, `runAs(null, ..)`) goes for no
44+
one: the client asks no capture for it, so the thread that happens to send it cannot lend it a user.
4045
- **On the agent side, a framework adapter puts the user into the framework's security context: `AcpIdentityScope`.**
4146
Set it with `identityScope(scope)` on `AcpAgent.AsyncAgentBuilder`, `AcpAgent.SyncAgentBuilder` or
4247
`AcpAgentSupport.Builder`: a synchronous handler runs inside `scope.open(identity)` on its own thread, closed after,
@@ -171,7 +176,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
171176
`submit(sessionId, caller, () -> request)`, which the queue calls once when the turn starts, outside its lock; a
172177
supplier that throws, returns null or builds a request for another session fails its turn, and the next one starts.
173178
`QueuedTurn.request()` is an `Optional`, empty until such a turn starts; `caller()` is the caller given to `submit`,
174-
for display, while the agent sees the caller the built request carries. At most `maxWaitingTurns` (default 32) wait
179+
for display, while the agent sees the caller the built request carries. Each turn is sent as the user who submitted
180+
it, found at `submit` on the submitting thread as the client would find it (`currentIdentity()`), however long it
181+
waited and whichever thread sends it; a turn submitted for no one is sent for no one, never as the user of the
182+
thread that delivered the previous answer. When a turn ends, its `response()` completes first, then
183+
`TurnListener.turnFinished(turn, response, error)` is called with the answer or the error, and only then does the
184+
session's next turn start, even one submitted from those callbacks. At most `maxWaitingTurns` (default 32) wait
175185
per session; one more is refused with `TurnQueueFullException` before anything is sent. `QueuedTurn.cancel()` removes a waiting turn without sending
176186
anything and stops the running one with `session/cancel`; `cancelAll(sessionId)` and `close()` do the same for a
177187
session and for the whole queue. `waitingTurns`, `turns` and a `TurnListener` (turn started, turn finished) are
@@ -181,6 +191,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
181191

182192
### Changed
183193

194+
- **Breaking against earlier 0.83.0 snapshots, acp-turn-queue and identity:** `TurnListener.turnFinished(QueuedTurn)`
195+
is now `turnFinished(QueuedTurn, PromptResponse, Throwable)`, called after the turn's `response()` has completed
196+
(before, it was called first, and the next turn started before the response completed); a listener overriding the
197+
one-argument method must move to the new one. A queued turn is sent as the user who submitted it, where before it
198+
was sent as whoever the client's capture found on the thread that delivered the previous answer (often no one,
199+
which `AcpSessionAccess.ownerOnly()` refused with `-32002`, or another user). `AcpIdentityContext.put(context,
200+
null)` and `callAs(null, ..)` now mean "for no one" and stop the client asking its capture; before, `put` removed
201+
the identity and `callAs(null, ..)` let the capture fill it in.
184202
- **Breaking: an HTTP connection is bound to the user who opened it.** The Streamable HTTP endpoint binds a connection
185203
to the identity of its `initialize` POST, and a WebSocket connection to that of its handshake. A later POST, GET or
186204
DELETE on the connection whose identity differs (by issuer and subject; an unauthenticated request and an

‎acp-turn-queue/README.md‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,18 @@ PromptResponse answer = alices.response().join(); // sent once the agent has a
3535

3636
- **Order.** A session's turns run one at a time, in the order they were submitted; the next is sent
3737
when the agent has answered the one before. Different sessions do not wait for each other. The
38-
queue starts no thread of its own.
38+
queue starts no thread of its own. When a turn ends, its `response()` completes first, then the
39+
listener's `turnFinished`, and only then does the next turn start, so turn N's end is always seen
40+
before turn N+1's start.
41+
- **Each turn is sent as the user who submitted it.** `submit` finds the user on the submitting
42+
thread, as the client would for a call sent there and then (`client.currentIdentity()`: the
43+
identity the thread runs for, else what the client's `AcpIdentityCapture` reads, such as Spring's
44+
`SecurityContextHolder`). The prompt is sent as that user however long it waited, though a waiting
45+
turn is sent from the thread that delivered the previous answer, whose security context is someone
46+
else's or no one's. A turn submitted for no one is sent for no one. So with the default
47+
`AcpSessionAccess.ownerOnly()`, an owner's queued turn is accepted and nobody else's passes as the
48+
owner. Without a capture, submit as a user with
49+
`AcpIdentityContext.runAs(identity, () -> turns.submit(request))`.
3950
- **Each turn keeps its caller.** A turn is sent as the very `PromptRequest` that was submitted (or
4051
that its supplier built), `_meta` included, so the agent reads each turn's own `AcpCaller` however
4152
long it waited.
@@ -64,7 +75,9 @@ PromptResponse answer = alices.response().join(); // sent once the agent has a
6475
`CancellationException` before the call returns.
6576
- **For a UI.** `waitingTurns(sessionId)`, `turns(sessionId)` (the running turn, then the waiting
6677
ones, each with its `caller()` and `state()`), and a `TurnListener` told when a turn starts and
67-
when it finishes:
78+
when it finishes, with the agent's answer or the error. The calls come in order, so a chat can
79+
show each turn's message when it starts and its end when it finishes, without ordering them
80+
itself:
6881

6982
```java
7083
AcpTurnQueue turns = AcpTurnQueue.builder(client)
@@ -74,6 +87,16 @@ AcpTurnQueue turns = AcpTurnQueue.builder(client)
7487
public void turnStarted(QueuedTurn turn) {
7588
ui.showRunning(turn.sessionId(), turn.caller(), turns.waitingTurns(turn.sessionId()));
7689
}
90+
91+
@Override
92+
public void turnFinished(QueuedTurn turn, PromptResponse response, Throwable error) {
93+
if (response != null) {
94+
ui.showDone(turn.sessionId(), response.stopReason());
95+
}
96+
else if (turn.request().isPresent()) { // it was sent, and failed
97+
ui.showFailed(turn.sessionId(), error.getMessage());
98+
}
99+
}
77100
})
78101
.build();
79102
```

‎acp-turn-queue/src/main/java/com/agentclientprotocol/sdk/client/queue/AcpTurnQueue.java‎

Lines changed: 95 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,15 @@
1010
import java.util.List;
1111
import java.util.Map;
1212
import java.util.concurrent.CancellationException;
13-
import java.util.concurrent.CompletableFuture;
1413
import java.util.function.Consumer;
1514
import java.util.function.Function;
1615
import java.util.function.Supplier;
1716

1817
import com.agentclientprotocol.sdk.client.AcpAsyncClient;
1918
import com.agentclientprotocol.sdk.client.AcpSyncClient;
2019
import com.agentclientprotocol.sdk.client.CancellationSignal;
20+
import com.agentclientprotocol.sdk.identity.AcpIdentity;
21+
import com.agentclientprotocol.sdk.identity.AcpIdentityContext;
2122
import com.agentclientprotocol.sdk.spec.AcpCaller;
2223
import com.agentclientprotocol.sdk.spec.AcpSchema.PromptRequest;
2324
import com.agentclientprotocol.sdk.spec.AcpSchema.PromptResponse;
@@ -46,11 +47,26 @@
4647
* the next one is sent when the agent has answered the one before, which is when ACP lets the
4748
* client send it. Turns of different sessions do not wait for each other. The queue starts no
4849
* thread: it sends each prompt through {@link AcpAsyncClient#prompt(PromptRequest,
49-
* CancellationSignal)} and starts the next turn from the thread that delivers the answer.
50+
* CancellationSignal)} and starts the next turn from the thread that delivers the answer. When a
51+
* turn ends, its {@link QueuedTurn#response()} completes first, then
52+
* {@link TurnListener#turnFinished} is called, and only then does the session's next turn start;
53+
* so whatever a response's callbacks or the listener do for turn N happens before turn N+1
54+
* starts, even for a turn they submit themselves.
55+
*
56+
* <p><b>Who a turn is sent as.</b> A turn is sent as the user who submitted it, however long it
57+
* waited and whichever thread finally sends it. {@code submit} finds that user on the submitting
58+
* thread, as the client would for a call sent there and then ({@link
59+
* AcpAsyncClient#currentIdentity()}: the identity the thread runs for, else what the client's
60+
* {@link com.agentclientprotocol.sdk.identity.AcpIdentityCapture} reads from the thread, such as
61+
* Spring's {@code SecurityContextHolder}), and the prompt is sent as that user
62+
* ({@link AcpIdentityContext#runAs}). A turn submitted for no one is sent for no one: the client
63+
* then reads no capture on the thread that sends it, so a turn never borrows the user of the
64+
* thread that delivered the previous answer. An application without a capture submits as a user
65+
* with {@code AcpIdentityContext.runAs(identity, () -> queue.submit(request))}.
5066
*
5167
* <p><b>Requests.</b> Each turn is sent as the very {@code PromptRequest} that was submitted. Its
5268
* {@code _meta}, and with it the turn's {@link AcpCaller}, reaches the agent unchanged, so every
53-
* turn keeps its own sender however long it waited. A prompt that should reflect what happened
69+
* turn keeps its own declared caller however long it waited. A prompt that should reflect what happened
5470
* while it waited is submitted as a supplier instead, {@link #submit(String, AcpCaller, Supplier)},
5571
* and built when its turn starts; the request it builds is sent just as unchanged.
5672
*
@@ -151,14 +167,32 @@ public static Builder builder(AcpSyncClient client) {
151167
}
152168

153169
private static TurnSender clientSender(AcpAsyncClient client) {
154-
return (request, stop, done) -> client.prompt(request, stop)
155-
.switchIfEmpty(Mono.error(() -> new IllegalStateException("The prompt completed without an answer")))
156-
.subscribe(done::answered, done::failed);
170+
return new TurnSender() {
171+
172+
@Override
173+
public void send(PromptRequest request, @Nullable AcpIdentity identity, CancellationSignal stop,
174+
TurnCallback done) {
175+
// The client finds a prompt's sender when the prompt is subscribed, on the
176+
// subscribing thread: subscribed here as the submitter (or as no one), the prompt,
177+
// and a session/cancel its stop sends later, go as them and not as whoever this
178+
// thread's security context holds.
179+
AcpIdentityContext.runAs(identity, () -> client.prompt(request, stop)
180+
.switchIfEmpty(Mono.error(() -> new IllegalStateException("The prompt completed without an answer")))
181+
.subscribe(done::answered, done::failed));
182+
}
183+
184+
@Override
185+
public @Nullable AcpIdentity currentIdentity() {
186+
return client.currentIdentity();
187+
}
188+
189+
};
157190
}
158191

159192
/**
160193
* Submits a prompt turn. It starts at once if its session has no turn running, and otherwise
161-
* waits for the session's earlier turns. The request is sent as it is, {@code _meta} included.
194+
* waits for the session's earlier turns. The request is sent as it is, {@code _meta} included,
195+
* and as the user who submits it, found on this thread now (see the class description).
162196
* @param request the prompt, for any session the client knows
163197
* @return the turn, to follow and to cancel
164198
* @throws TurnQueueFullException if the session already has the most waiting turns allowed
@@ -168,7 +202,8 @@ private static TurnSender clientSender(AcpAsyncClient client) {
168202
public QueuedTurn submit(PromptRequest request) {
169203
Assert.notNull(request, "The prompt request must not be null");
170204
Assert.hasText(request.sessionId(), "The prompt request must name a session");
171-
return enqueue(request.sessionId(), lane -> QueuedTurn.of(this, lane, request));
205+
AcpIdentity submitter = this.sender.currentIdentity();
206+
return enqueue(request.sessionId(), lane -> QueuedTurn.of(this, lane, request, submitter));
172207
}
173208

174209
/**
@@ -200,6 +235,11 @@ public QueuedTurn submit(String sessionId, Supplier<PromptRequest> requestAtStar
200235
* ({@link QueuedTurn.State#FAILED}, its response completing with that exception or an
201236
* {@link IllegalStateException}), nothing is sent, and the session's next turn starts.
202237
*
238+
* <p>The turn is sent as the user who submits it, found on this thread now, as
239+
* {@link #submit(PromptRequest)} does; the supplier, which runs on another thread when the turn
240+
* waited, need not find that user again. The supplier does not run as that user: code in it
241+
* that reads a security context reads the starting thread's.
242+
*
203243
* <p>{@code caller} is for display only: it is {@link QueuedTurn#caller()} from submit on, so a
204244
* UI can show whose turn waits. The caller the agent sees is the one the built request carries
205245
* in its {@code _meta} (normally {@code caller.addToMeta(...)}); the queue never adds, changes
@@ -216,7 +256,8 @@ public QueuedTurn submit(String sessionId, Supplier<PromptRequest> requestAtStar
216256
public QueuedTurn submit(String sessionId, @Nullable AcpCaller caller, Supplier<PromptRequest> requestAtStart) {
217257
Assert.hasText(sessionId, "The session id must not be blank");
218258
Assert.notNull(requestAtStart, "The request supplier must not be null");
219-
return enqueue(sessionId, lane -> QueuedTurn.later(this, lane, sessionId, caller, requestAtStart));
259+
AcpIdentity submitter = this.sender.currentIdentity();
260+
return enqueue(sessionId, lane -> QueuedTurn.later(this, lane, sessionId, caller, requestAtStart, submitter));
220261
}
221262

222263
private QueuedTurn enqueue(String sessionId, Function<Lane, QueuedTurn> newTurn) {
@@ -259,7 +300,9 @@ public int waitingTurns(String sessionId) {
259300

260301
/**
261302
* The turns of a session the queue holds: the running one first, then the waiting ones in the
262-
* order they will run. A chat UI can show each one's {@link QueuedTurn#caller()}.
303+
* order they will run. A chat UI can show each one's {@link QueuedTurn#caller()}. While a turn
304+
* is ending (its response's callbacks and {@link TurnListener#turnFinished} running), it is
305+
* still the first, in its end state, and the next turn has not started.
263306
* @param sessionId the session
264307
* @return a new, unmodifiable list, empty when the session has no turn running
265308
*/
@@ -339,7 +382,7 @@ private void drainLane(Lane lane, List<QueuedTurn> removed, List<QueuedTurn> sto
339382
}
340383
lane.waiting.clear();
341384
QueuedTurn running = lane.runningTurn();
342-
if (running.claimStop()) {
385+
if (running.state() == QueuedTurn.State.RUNNING && running.claimStop()) {
343386
stopped.add(running);
344387
}
345388
}
@@ -367,8 +410,9 @@ else if (turn.state() != QueuedTurn.State.RUNNING || !turn.claimStop()) {
367410

368411
private void finishCancelled(List<QueuedTurn> turns, String reason) {
369412
for (QueuedTurn turn : turns) {
370-
notify(this.listener::turnFinished, turn);
371-
turn.future().completeExceptionally(new CancellationException(reason));
413+
CancellationException cancelled = new CancellationException(reason);
414+
turn.future().completeExceptionally(cancelled);
415+
notifyFinished(turn, null, cancelled);
372416
}
373417
}
374418

@@ -407,15 +451,15 @@ private void send(QueuedTurn turn) {
407451
}
408452
catch (RuntimeException ex) {
409453
notify(this.listener::turnStarted, turn);
410-
finish(turn, false, future -> future.completeExceptionally(ex));
454+
finish(turn, null, ex);
411455
return;
412456
}
413457
notify(this.listener::turnStarted, turn);
414458
try {
415-
this.sender.send(request, turn.stop(), callback(turn));
459+
this.sender.send(request, turn.submitter(), turn.stop(), callback(turn));
416460
}
417461
catch (RuntimeException ex) {
418-
finish(turn, false, future -> future.completeExceptionally(ex));
462+
finish(turn, null, ex);
419463
}
420464
}
421465

@@ -424,29 +468,39 @@ private TurnCallback callback(QueuedTurn turn) {
424468

425469
@Override
426470
public void answered(PromptResponse response) {
427-
finish(turn, true, future -> future.complete(response));
471+
finish(turn, response, null);
428472
}
429473

430474
@Override
431475
public void failed(Throwable error) {
432-
finish(turn, false, future -> future.completeExceptionally(error));
476+
finish(turn, null, error);
433477
}
434478

435479
};
436480
}
437481

438482
/**
439-
* Ends a running turn, answered or failed, starts the next, and then completes the turn's
440-
* response with {@code outcome}.
483+
* Ends a running turn with the agent's answer, or with {@code error}: completes its response,
484+
* tells the listener, and only then starts the session's next turn. The turn stays its lane's
485+
* running turn until then, so a turn submitted meanwhile, from a response callback or the
486+
* listener, waits behind it instead of starting first.
441487
*/
442-
private void finish(QueuedTurn turn, boolean answered,
443-
Consumer<CompletableFuture<PromptResponse>> outcome) {
444-
QueuedTurn next;
488+
private void finish(QueuedTurn turn, @Nullable PromptResponse response, @Nullable Throwable error) {
445489
synchronized (this.lock) {
446490
if (turn.state() != QueuedTurn.State.RUNNING) {
447491
return;
448492
}
449-
turn.state(answered ? QueuedTurn.State.COMPLETED : QueuedTurn.State.FAILED);
493+
turn.state((error == null) ? QueuedTurn.State.COMPLETED : QueuedTurn.State.FAILED);
494+
}
495+
if (error == null) {
496+
turn.future().complete(response);
497+
}
498+
else {
499+
turn.future().completeExceptionally(error);
500+
}
501+
notifyFinished(turn, response, error);
502+
QueuedTurn next;
503+
synchronized (this.lock) {
450504
Lane lane = turn.lane();
451505
next = lane.waiting.poll();
452506
lane.running = next;
@@ -457,11 +511,9 @@ private void finish(QueuedTurn turn, boolean answered,
457511
this.lanes.remove(lane.sessionId, lane);
458512
}
459513
}
460-
notify(this.listener::turnFinished, turn);
461514
if (next != null) {
462515
start(next);
463516
}
464-
outcome.accept(turn.future());
465517
}
466518

467519
private static void notify(Consumer<QueuedTurn> event, QueuedTurn turn) {
@@ -473,9 +525,18 @@ private static void notify(Consumer<QueuedTurn> event, QueuedTurn turn) {
473525
}
474526
}
475527

528+
private void notifyFinished(QueuedTurn turn, @Nullable PromptResponse response, @Nullable Throwable error) {
529+
try {
530+
this.listener.turnFinished(turn, response, error);
531+
}
532+
catch (RuntimeException ex) {
533+
logger.warn("Turn listener failed for {}: {}", turn, ex.toString(), ex);
534+
}
535+
}
536+
476537
/**
477538
* One session's turns: the running one and those waiting behind it, guarded by the queue's
478-
* lock. A lane exists exactly while its session has a running turn.
539+
* lock. A lane exists exactly while its session has a running turn, or one that is ending.
479540
*/
480541
static final class Lane {
481542

@@ -503,7 +564,13 @@ QueuedTurn runningTurn() {
503564
@FunctionalInterface
504565
interface TurnSender {
505566

506-
void send(PromptRequest request, CancellationSignal stop, TurnCallback done);
567+
/** Sends {@code request} as {@code identity}, the turn's submitter, or as no one for null. */
568+
void send(PromptRequest request, @Nullable AcpIdentity identity, CancellationSignal stop, TurnCallback done);
569+
570+
/** Who a turn submitted now on this thread is for; called by {@code submit}. */
571+
default @Nullable AcpIdentity currentIdentity() {
572+
return null;
573+
}
507574

508575
}
509576

0 commit comments

Comments
 (0)