1010import java .util .List ;
1111import java .util .Map ;
1212import java .util .concurrent .CancellationException ;
13- import java .util .concurrent .CompletableFuture ;
1413import java .util .function .Consumer ;
1514import java .util .function .Function ;
1615import java .util .function .Supplier ;
1716
1817import com .agentclientprotocol .sdk .client .AcpAsyncClient ;
1918import com .agentclientprotocol .sdk .client .AcpSyncClient ;
2019import com .agentclientprotocol .sdk .client .CancellationSignal ;
20+ import com .agentclientprotocol .sdk .identity .AcpIdentity ;
21+ import com .agentclientprotocol .sdk .identity .AcpIdentityContext ;
2122import com .agentclientprotocol .sdk .spec .AcpCaller ;
2223import com .agentclientprotocol .sdk .spec .AcpSchema .PromptRequest ;
2324import com .agentclientprotocol .sdk .spec .AcpSchema .PromptResponse ;
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