agent-client-protocol-conductor 2.0.0

Conductor for orchestrating Agent Client Protocol proxy chains
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
//! Integration tests for `$/cancel_request` propagation through the conductor.
//!
//! Cancellation is hop-by-hop: every hop re-issues `$/cancel_request` with
//! its own connection's request ID, and the raw notification (whose
//! `requestId` is only meaningful on the connection it arrived over) must
//! *not* be tunneled verbatim through the chain.
//!
//! These tests avoid sleeps:
//!
//! - Channels report what each endpoint observed, awaited with a timeout.
//! - "Exactly one cancellation" assertions rely on a barrier round trip
//!   through the whole chain: the conductor's routing loop and each
//!   connection deliver messages in order, so by the time the barrier
//!   response arrives, any erroneously tunneled notification would already
//!   have been observed.

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use agent_client_protocol::DynConnectTo;
use agent_client_protocol::schema::ProtocolVersion;
use agent_client_protocol::schema::v1::{
    CancelRequestNotification, ConnectMcpRequest, ContentBlock, ContentChunk, InitializeRequest,
    InitializeResponse, McpServer as SchemaMcpServer, McpServerAcpId, NewSessionRequest,
    NewSessionResponse, PermissionOption, PermissionOptionKind, PromptRequest, PromptResponse,
    RequestPermissionOutcome, RequestPermissionRequest, RequestPermissionResponse,
    SelectedPermissionOutcome, SessionId, SessionNotification, SessionUpdate, StopReason,
    ToolCallUpdate, ToolCallUpdateFields,
};
use agent_client_protocol::{
    Agent, ByteStreams, Client, Conductor, ConnectTo, ConnectionTo, Error, JsonRpcRequest,
    JsonRpcResponse, NullRun, Proxy, Responder, Role, SentRequest,
    mcp_server::{McpConnectionTo, McpServer, McpServerConnect},
    role,
};
use agent_client_protocol_conductor::{ConductorImpl, ProxiesAndAgent};
use futures::StreamExt as _;
use futures::channel::mpsc;
use serde::{Deserialize, Serialize};
use tokio::io::duplex;
use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};

#[derive(Debug, Clone, Serialize, Deserialize, JsonRpcRequest)]
#[request(method = "test/simple", response = SimpleResponse)]
struct SimpleRequest {
    message: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonRpcResponse)]
struct SimpleResponse {
    result: String,
}

#[derive(Clone)]
struct TrackingMcpServer {
    connect_tx: mpsc::UnboundedSender<McpServerAcpId>,
}

impl<Counterpart: Role> McpServerConnect<Counterpart> for TrackingMcpServer {
    fn name(&self) -> String {
        "tracking-mcp".to_string()
    }

    fn connect(&self, cx: McpConnectionTo<Counterpart>) -> DynConnectTo<role::mcp::Client> {
        self.connect_tx
            .unbounded_send(
                cx.server_id()
                    .expect("cancellation test server is attached through ACP")
                    .clone(),
            )
            .unwrap();
        DynConnectTo::new(EmptyMcpServerComponent)
    }
}

struct EmptyMcpServerComponent;

impl ConnectTo<role::mcp::Client> for EmptyMcpServerComponent {
    async fn connect_to(self, client: impl ConnectTo<role::mcp::Server>) -> Result<(), Error> {
        role::mcp::Server
            .builder()
            .connect_with(client, async |_cx| {
                std::future::pending::<Result<(), Error>>().await
            })
            .await
    }
}

/// Await the next item on `rx`, panicking instead of hanging if it never
/// arrives.
async fn next_with_timeout<T>(rx: &mut mpsc::UnboundedReceiver<T>) -> T {
    tokio::time::timeout(Duration::from_secs(10), rx.next())
        .await
        .expect("timed out waiting for channel event")
        .expect("channel closed before expected event")
}

/// Assert that no item is currently buffered on `rx`.
///
/// Callers must first establish an ordering barrier (such as a round trip
/// through the whole chain) that guarantees any erroneously sent
/// notification would already have been observed.
fn assert_no_event<T: std::fmt::Debug>(rx: &mut mpsc::UnboundedReceiver<T>) {
    if let Ok(event) = rx.try_recv() {
        panic!("unexpected event: {event:?}");
    }
}

fn advertised_mcp_server_id(request: &NewSessionRequest) -> McpServerAcpId {
    match request.mcp_servers.as_slice() {
        [SchemaMcpServer::Acp(acp)] => acp.server_id.clone(),
        servers => panic!("expected exactly one ACP MCP server, got {servers:?}"),
    }
}

/// The real intercepting proxy from the test fixtures, run in-process.
struct InProcessArrowProxy;

impl ConnectTo<Conductor> for InProcessArrowProxy {
    async fn connect_to(self, client: impl ConnectTo<Proxy>) -> Result<(), Error> {
        agent_client_protocol_test::arrow_proxy::run_arrow_proxy(client).await
    }
}

fn prompt_text(request: &PromptRequest) -> String {
    request
        .prompt
        .iter()
        .filter_map(|block| match block {
            ContentBlock::Text(text) => Some(text.text.as_str()),
            _ => None,
        })
        .collect()
}

/// A client cancels a request it sent through the conductor (and a
/// passthrough proxy) to the agent.
///
/// The agent must observe exactly one `$/cancel_request`, carrying the ID of
/// the request on the conductor-to-agent connection — not the client's raw
/// notification with its hop-local request ID.
#[tokio::test]
async fn client_cancellation_propagates_hop_by_hop_to_agent() -> Result<(), Error> {
    let (agent_cancel_tx, mut agent_cancel_rx) = mpsc::unbounded();
    // The JSON-RPC id of the parked request, as seen by the agent.
    let (parked_id_tx, mut parked_id_rx) = mpsc::unbounded();

    let agent = Agent
        .builder()
        .on_receive_request(
            async |initialize: InitializeRequest, responder, _cx: ConnectionTo<Client>| {
                responder.respond(InitializeResponse::new(initialize.protocol_version))
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            async move |request: SimpleRequest,
                        responder: Responder<SimpleResponse>,
                        cx: ConnectionTo<Client>| {
                if request.message == "park" {
                    parked_id_tx.unbounded_send(responder.id().clone()).unwrap();
                    let cancellation = responder.cancellation();
                    cx.spawn(async move {
                        let response = cancellation
                            .run_until_cancelled(std::future::pending::<
                                Result<SimpleResponse, Error>,
                            >())
                            .await;
                        responder.respond_with_result(response)
                    })?;
                    return Ok(());
                }

                responder.respond(SimpleResponse {
                    result: format!("echo: {}", request.message),
                })
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_notification(
            async move |cancel: CancelRequestNotification, _cx: ConnectionTo<Client>| {
                agent_cancel_tx.unbounded_send(cancel.request_id).unwrap();
                Ok(())
            },
            agent_client_protocol::on_receive_notification!(),
        );

    let (editor_write, conductor_read) = duplex(8192);
    let (conductor_write, editor_read) = duplex(8192);

    // One passthrough proxy in the chain, so the cancellation crosses every
    // kind of hop: client→conductor, conductor→proxy, proxy→conductor
    // (successor-wrapped), and conductor→agent.
    let conductor_handle = tokio::spawn(async move {
        ConductorImpl::new_agent(
            "cancellation-conductor".to_string(),
            ProxiesAndAgent::new(agent).proxy(Proxy.builder()),
        )
        .run(ByteStreams::new(
            conductor_write.compat_write(),
            conductor_read.compat(),
        ))
        .await
    });

    let client_request_id = tokio::time::timeout(Duration::from_secs(30), async move {
        Client
            .builder()
            .connect_with(
                ByteStreams::new(editor_write.compat_write(), editor_read.compat()),
                async |cx| {
                    let initialize = cx
                        .send_request(InitializeRequest::new(ProtocolVersion::V1))
                        .block_task()
                        .await?;
                    assert_eq!(initialize.protocol_version, ProtocolVersion::V1);

                    let request: SentRequest<SimpleResponse> = cx.send_request(SimpleRequest {
                        message: "park".into(),
                    });
                    let client_request_id = request.id().clone();
                    request.cancel()?;

                    // The cancellation reaches the agent hop by hop, and the
                    // agent's cancellation error flows back the same way.
                    let error = request
                        .block_task()
                        .await
                        .expect_err("request should be cancelled");
                    assert_eq!(i32::from(error.code), -32800);

                    // Barrier: this round trip traverses the whole chain
                    // after the cancellation, so a tunneled raw
                    // `$/cancel_request` would already have been recorded by
                    // the agent.
                    let barrier = cx
                        .send_request(SimpleRequest {
                            message: "barrier".into(),
                        })
                        .block_task()
                        .await?;
                    assert_eq!(barrier.result, "echo: barrier");

                    Ok(client_request_id)
                },
            )
            .await
    })
    .await
    .expect("test timed out")
    .expect("client failed");

    // The agent saw exactly one `$/cancel_request`, for the request ID on
    // its own connection.
    let parked_id = next_with_timeout(&mut parked_id_rx).await;
    assert_ne!(
        parked_id, client_request_id,
        "each hop must re-issue the request under its own ID"
    );
    let observed = next_with_timeout(&mut agent_cancel_rx).await;
    assert_eq!(observed, parked_id);
    assert_no_event(&mut agent_cancel_rx);

    conductor_handle.abort();
    Ok(())
}

/// The agent cancels a request it sent through the conductor to the client
/// (the right-to-left direction).
///
/// The client must observe exactly one `$/cancel_request`, carrying the ID
/// of the request on the client-to-conductor connection — not the agent's
/// raw notification with its hop-local request ID.
#[tokio::test]
async fn agent_cancellation_propagates_hop_by_hop_to_client() -> Result<(), Error> {
    let (client_cancel_tx, mut client_cancel_rx) = mpsc::unbounded();
    // The JSON-RPC id of the parked request, as seen by the client.
    let (parked_id_tx, mut parked_id_rx) = mpsc::unbounded();

    let agent = Agent
        .builder()
        .on_receive_request(
            async |initialize: InitializeRequest, responder, _cx: ConnectionTo<Client>| {
                responder.respond(InitializeResponse::new(initialize.protocol_version))
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            async |request: SimpleRequest,
                   responder: Responder<SimpleResponse>,
                   cx: ConnectionTo<Client>| {
                if request.message == "trigger reverse cancel" {
                    let connection = cx.clone();
                    cx.spawn(async move {
                        // Send a request to the client, cancel it, and report
                        // how it concluded as the response to the trigger.
                        let upstream: SentRequest<SimpleResponse> =
                            connection.send_request(SimpleRequest {
                                message: "park".into(),
                            });
                        upstream.cancel()?;
                        let error = upstream
                            .block_task()
                            .await
                            .expect_err("request to the client should be cancelled");
                        responder.respond(SimpleResponse {
                            result: format!("client request error: {}", i32::from(error.code)),
                        })
                    })?;
                    return Ok(());
                }

                responder.respond(SimpleResponse {
                    result: format!("echo: {}", request.message),
                })
            },
            agent_client_protocol::on_receive_request!(),
        );

    let (editor_write, conductor_read) = duplex(8192);
    let (conductor_write, editor_read) = duplex(8192);

    let conductor_handle = tokio::spawn(async move {
        ConductorImpl::new_agent(
            "cancellation-conductor".to_string(),
            ProxiesAndAgent::new(agent),
        )
        .run(ByteStreams::new(
            conductor_write.compat_write(),
            conductor_read.compat(),
        ))
        .await
    });

    tokio::time::timeout(Duration::from_secs(30), async move {
        Client
            .builder()
            .on_receive_request(
                async move |request: SimpleRequest,
                            responder: Responder<SimpleResponse>,
                            cx: ConnectionTo<Agent>| {
                    assert_eq!(request.message, "park");
                    parked_id_tx.unbounded_send(responder.id().clone()).unwrap();
                    let cancellation = responder.cancellation();
                    cx.spawn(async move {
                        let response = cancellation
                            .run_until_cancelled(std::future::pending::<
                                Result<SimpleResponse, Error>,
                            >())
                            .await;
                        responder.respond_with_result(response)
                    })?;
                    Ok(())
                },
                agent_client_protocol::on_receive_request!(),
            )
            .on_receive_notification(
                async move |cancel: CancelRequestNotification, _cx: ConnectionTo<Agent>| {
                    client_cancel_tx.unbounded_send(cancel.request_id).unwrap();
                    Ok(())
                },
                agent_client_protocol::on_receive_notification!(),
            )
            .connect_with(
                ByteStreams::new(editor_write.compat_write(), editor_read.compat()),
                async |cx| {
                    let initialize = cx
                        .send_request(InitializeRequest::new(ProtocolVersion::V1))
                        .block_task()
                        .await?;
                    assert_eq!(initialize.protocol_version, ProtocolVersion::V1);

                    // The agent answers the trigger only after its request to
                    // the client was cancelled and answered with the standard
                    // cancellation error.
                    let response = cx
                        .send_request(SimpleRequest {
                            message: "trigger reverse cancel".into(),
                        })
                        .block_task()
                        .await?;
                    assert_eq!(response.result, "client request error: -32800");

                    // Barrier: a tunneled raw `$/cancel_request` was queued
                    // in the conductor's routing loop before this request, so
                    // it would already have been recorded by the client.
                    let barrier = cx
                        .send_request(SimpleRequest {
                            message: "barrier".into(),
                        })
                        .block_task()
                        .await?;
                    assert_eq!(barrier.result, "echo: barrier");

                    Ok(())
                },
            )
            .await
    })
    .await
    .expect("test timed out")
    .expect("client failed");

    // The client saw exactly one `$/cancel_request`, for the request ID on
    // its own connection.
    let parked_id = next_with_timeout(&mut parked_id_rx).await;
    let observed = next_with_timeout(&mut client_cancel_rx).await;
    assert_eq!(observed, parked_id);
    assert_no_event(&mut client_cancel_rx);

    conductor_handle.abort();
    Ok(())
}

/// The canonical real-world cancellation cascade, through a real intercepting
/// proxy (`arrow_proxy`) and a full ACP session:
///
/// 1. The client initializes, creates a session, and sends `session/prompt`.
/// 2. The agent asks the client for permission (`session/request_permission`)
///    and waits.
/// 3. The client cancels the *prompt*; the agent reacts by cancelling its
///    outstanding *permission request*, then answers the prompt with the
///    cancellation error.
///
/// Both cancellations must arrive re-issued with the receiving connection's
/// own request ID — exactly once each — and the chain (including the
/// transforming proxy) must keep working afterwards.
#[tokio::test]
async fn prompt_cancellation_cascades_through_real_proxy_chain() -> Result<(), Error> {
    // What the agent observed: incoming `$/cancel_request`s and the id of the
    // parked prompt.
    let (agent_cancel_tx, mut agent_cancel_rx) = mpsc::unbounded();
    let (prompt_id_tx, mut prompt_id_rx) = mpsc::unbounded();
    // What the client observed: incoming `$/cancel_request`s, the id of the
    // parked permission request, and session updates.
    let (client_cancel_tx, mut client_cancel_rx) = mpsc::unbounded();
    let (permission_id_tx, mut permission_id_rx) = mpsc::unbounded();
    let (session_update_tx, mut session_update_rx) = mpsc::unbounded();

    let agent = Agent
        .builder()
        .on_receive_request(
            async |initialize: InitializeRequest, responder, _cx: ConnectionTo<Client>| {
                responder.respond(InitializeResponse::new(initialize.protocol_version))
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            async |request: NewSessionRequest, responder, _cx: ConnectionTo<Client>| {
                assert!(request.mcp_servers.is_empty());
                responder.respond(NewSessionResponse::new(SessionId::new("test-session")))
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            async move |request: PromptRequest,
                        responder: Responder<PromptResponse>,
                        cx: ConnectionTo<Client>| {
                let text = prompt_text(&request);
                if text != "park" {
                    // Echo prompts complete normally, with a session update
                    // the arrow proxy will transform on its way back.
                    cx.send_notification(SessionNotification::new(
                        request.session_id,
                        SessionUpdate::AgentMessageChunk(ContentChunk::new(text.into())),
                    ))?;
                    return responder.respond(PromptResponse::new(StopReason::EndTurn));
                }

                prompt_id_tx.unbounded_send(responder.id().clone()).unwrap();
                let cancellation = responder.cancellation();
                let connection = cx.clone();
                cx.spawn(async move {
                    // Ask the client for permission through the chain.
                    let permission: SentRequest<RequestPermissionResponse> = connection
                        .send_request(RequestPermissionRequest::new(
                            request.session_id,
                            ToolCallUpdate::new("tool-1", ToolCallUpdateFields::default()),
                            vec![PermissionOption::new(
                                "allow",
                                "Allow",
                                PermissionOptionKind::AllowOnce,
                            )],
                        ));

                    // The client cancels the prompt rather than answering the
                    // permission request.
                    cancellation.cancelled().await;

                    // React like a real agent: withdraw the outstanding
                    // permission request, then report the prompt as
                    // cancelled.
                    permission.cancel()?;
                    let permission_error = permission
                        .block_task()
                        .await
                        .expect_err("permission request should be cancelled");

                    if i32::from(permission_error.code) == -32800 {
                        responder.respond_with_result(Err(Error::request_cancelled()))
                    } else {
                        responder.respond_with_result(Err(
                            agent_client_protocol::util::internal_error(format!(
                                "unexpected permission error: {permission_error:?}"
                            )),
                        ))
                    }
                })?;
                Ok(())
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_notification(
            async move |cancel: CancelRequestNotification, _cx: ConnectionTo<Client>| {
                agent_cancel_tx.unbounded_send(cancel.request_id).unwrap();
                Ok(())
            },
            agent_client_protocol::on_receive_notification!(),
        );

    let (editor_write, conductor_read) = duplex(8192);
    let (conductor_write, editor_read) = duplex(8192);

    let conductor_handle = tokio::spawn(async move {
        ConductorImpl::new_agent(
            "cancellation-conductor".to_string(),
            ProxiesAndAgent::new(agent).proxy(InProcessArrowProxy),
        )
        .run(ByteStreams::new(
            conductor_write.compat_write(),
            conductor_read.compat(),
        ))
        .await
    });

    let client_prompt_id = tokio::time::timeout(Duration::from_secs(30), async move {
        Client
            .builder()
            .on_receive_request(
                async move |_request: RequestPermissionRequest,
                            responder: Responder<RequestPermissionResponse>,
                            cx: ConnectionTo<Agent>| {
                    permission_id_tx
                        .unbounded_send(responder.id().clone())
                        .unwrap();
                    let cancellation = responder.cancellation();
                    cx.spawn(async move {
                        let response = cancellation
                            .run_until_cancelled(std::future::pending::<
                                Result<RequestPermissionResponse, Error>,
                            >())
                            .await;
                        responder.respond_with_result(response)
                    })?;
                    Ok(())
                },
                agent_client_protocol::on_receive_request!(),
            )
            .on_receive_notification(
                async move |notification: SessionNotification, _cx: ConnectionTo<Agent>| {
                    if let SessionUpdate::AgentMessageChunk(ContentChunk {
                        content: ContentBlock::Text(text),
                        ..
                    }) = notification.update
                    {
                        session_update_tx.unbounded_send(text.text).unwrap();
                    }
                    Ok(())
                },
                agent_client_protocol::on_receive_notification!(),
            )
            .on_receive_notification(
                async move |cancel: CancelRequestNotification, _cx: ConnectionTo<Agent>| {
                    client_cancel_tx.unbounded_send(cancel.request_id).unwrap();
                    Ok(())
                },
                agent_client_protocol::on_receive_notification!(),
            )
            .connect_with(
                ByteStreams::new(editor_write.compat_write(), editor_read.compat()),
                async |cx| {
                    let initialize = cx
                        .send_request(InitializeRequest::new(ProtocolVersion::V1))
                        .block_task()
                        .await?;
                    assert_eq!(initialize.protocol_version, ProtocolVersion::V1);

                    let session = cx
                        .send_request(NewSessionRequest::new(
                            std::env::current_dir().map_err(Error::into_internal_error)?,
                        ))
                        .block_task()
                        .await?;

                    let prompt: SentRequest<PromptResponse> = cx.send_request(PromptRequest::new(
                        session.session_id.clone(),
                        vec!["park".into()],
                    ));
                    let client_prompt_id = prompt.id().clone();
                    prompt.cancel()?;

                    let error = prompt
                        .block_task()
                        .await
                        .expect_err("prompt should be cancelled");
                    assert_eq!(i32::from(error.code), -32800);

                    // The chain still works end to end: a normal prompt
                    // completes, and its session update comes back through
                    // the arrow proxy, which prefixes `>` — proving the real
                    // proxy sits in the message path.
                    let barrier: PromptResponse = cx
                        .send_request(PromptRequest::new(
                            session.session_id.clone(),
                            vec!["barrier".into()],
                        ))
                        .block_task()
                        .await?;
                    assert_eq!(barrier.stop_reason, StopReason::EndTurn);

                    Ok(client_prompt_id)
                },
            )
            .await
    })
    .await
    .expect("test timed out")
    .expect("client failed");

    // The agent saw exactly one `$/cancel_request` (for the prompt), with the
    // ID of the prompt on the conductor-to-agent connection.
    let prompt_id = next_with_timeout(&mut prompt_id_rx).await;
    assert_ne!(
        prompt_id, client_prompt_id,
        "each hop must re-issue the request under its own ID"
    );
    let observed = next_with_timeout(&mut agent_cancel_rx).await;
    assert_eq!(observed, prompt_id);
    assert_no_event(&mut agent_cancel_rx);

    // The client saw exactly one `$/cancel_request` (for the permission
    // request), with the ID of that request on the client's own connection.
    let permission_id = next_with_timeout(&mut permission_id_rx).await;
    let observed = next_with_timeout(&mut client_cancel_rx).await;
    assert_eq!(observed, permission_id);
    assert_no_event(&mut client_cancel_rx);

    // The barrier prompt's session update was transformed by the arrow proxy.
    let update = next_with_timeout(&mut session_update_rx).await;
    assert_eq!(update, ">barrier");

    conductor_handle.abort();
    Ok(())
}

/// `session/new` is forwarded by proxies with a result hook (to register the
/// session's dynamic handler), not with `forward_response_to` — cancellation
/// must still propagate hop by hop, exactly like every other request.
#[tokio::test]
async fn session_new_cancellation_propagates_through_proxy() -> Result<(), Error> {
    let (agent_cancel_tx, mut agent_cancel_rx) = mpsc::unbounded();
    let (parked_id_tx, mut parked_id_rx) = mpsc::unbounded();

    let agent = Agent
        .builder()
        .on_receive_request(
            async |initialize: InitializeRequest, responder, _cx: ConnectionTo<Client>| {
                responder.respond(InitializeResponse::new(initialize.protocol_version))
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            async move |request: NewSessionRequest,
                        responder: Responder<NewSessionResponse>,
                        cx: ConnectionTo<Client>| {
                if request.cwd.ends_with("park-session") {
                    parked_id_tx.unbounded_send(responder.id().clone()).unwrap();
                    let cancellation = responder.cancellation();
                    cx.spawn(async move {
                        let response = cancellation
                            .run_until_cancelled(std::future::pending::<
                                Result<NewSessionResponse, Error>,
                            >())
                            .await;
                        responder.respond_with_result(response)
                    })?;
                    return Ok(());
                }

                responder.respond(NewSessionResponse::new(SessionId::new("normal-session")))
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_notification(
            async move |cancel: CancelRequestNotification, _cx: ConnectionTo<Client>| {
                agent_cancel_tx.unbounded_send(cancel.request_id).unwrap();
                Ok(())
            },
            agent_client_protocol::on_receive_notification!(),
        );

    let (editor_write, conductor_read) = duplex(8192);
    let (conductor_write, editor_read) = duplex(8192);

    // The passthrough proxy is what exercises the proxy-side `session/new`
    // forwarding hook.
    let conductor_handle = tokio::spawn(async move {
        ConductorImpl::new_agent(
            "cancellation-conductor".to_string(),
            ProxiesAndAgent::new(agent).proxy(Proxy.builder()),
        )
        .run(ByteStreams::new(
            conductor_write.compat_write(),
            conductor_read.compat(),
        ))
        .await
    });

    let client_request_id = tokio::time::timeout(Duration::from_secs(30), async move {
        Client
            .builder()
            .connect_with(
                ByteStreams::new(editor_write.compat_write(), editor_read.compat()),
                async |cx| {
                    let initialize = cx
                        .send_request(InitializeRequest::new(ProtocolVersion::V1))
                        .block_task()
                        .await?;
                    assert_eq!(initialize.protocol_version, ProtocolVersion::V1);

                    let request: SentRequest<NewSessionResponse> =
                        cx.send_request(NewSessionRequest::new("/park-session"));
                    let client_request_id = request.id().clone();
                    request.cancel()?;

                    let error = request
                        .block_task()
                        .await
                        .expect_err("session/new should be cancelled");
                    assert_eq!(i32::from(error.code), -32800);

                    // Barrier through the whole chain: a fresh session still
                    // works after the cancelled one.
                    let session = cx
                        .send_request(NewSessionRequest::new(
                            std::env::current_dir().map_err(Error::into_internal_error)?,
                        ))
                        .block_task()
                        .await?;
                    assert_eq!(session.session_id, SessionId::new("normal-session"));

                    Ok(client_request_id)
                },
            )
            .await
    })
    .await
    .expect("test timed out")
    .expect("client failed");

    // The agent saw exactly one `$/cancel_request`, for the `session/new` ID
    // on its own connection.
    let parked_id = next_with_timeout(&mut parked_id_rx).await;
    assert_ne!(
        parked_id, client_request_id,
        "each hop must re-issue the request under its own ID"
    );
    let observed = next_with_timeout(&mut agent_cancel_rx).await;
    assert_eq!(observed, parked_id);
    assert_no_event(&mut agent_cancel_rx);

    conductor_handle.abort();
    Ok(())
}

/// The SDK's documented proxy session helper also forwards `session/new` with
/// a result hook, so it must opt into cancellation propagation explicitly.
#[tokio::test]
async fn proxy_session_helper_cancellation_propagates_to_agent() -> Result<(), Error> {
    let (agent_cancel_tx, mut agent_cancel_rx) = mpsc::unbounded();
    let (parked_id_tx, mut parked_id_rx) = mpsc::unbounded();

    let agent = Agent
        .builder()
        .on_receive_request(
            async |initialize: InitializeRequest, responder, _cx: ConnectionTo<Client>| {
                responder.respond(InitializeResponse::new(initialize.protocol_version))
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            async move |request: NewSessionRequest,
                        responder: Responder<NewSessionResponse>,
                        cx: ConnectionTo<Client>| {
                if request.cwd.ends_with("park-session") {
                    parked_id_tx.unbounded_send(responder.id().clone()).unwrap();
                    let cancellation = responder.cancellation();
                    cx.spawn(async move {
                        let response = cancellation
                            .run_until_cancelled(std::future::pending::<
                                Result<NewSessionResponse, Error>,
                            >())
                            .await;
                        responder.respond_with_result(response)
                    })?;
                    return Ok(());
                }

                responder.respond(NewSessionResponse::new(SessionId::new("normal-session")))
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_notification(
            async move |cancel: CancelRequestNotification, _cx: ConnectionTo<Client>| {
                agent_cancel_tx.unbounded_send(cancel.request_id).unwrap();
                Ok(())
            },
            agent_client_protocol::on_receive_notification!(),
        );

    let proxy = Proxy.builder().on_receive_request_from(
        Client,
        async |request: NewSessionRequest,
               responder: Responder<NewSessionResponse>,
               cx: ConnectionTo<Conductor>| {
            cx.build_session_from(request)
                .on_proxy_session_start(responder, async |_session_id| Ok::<(), Error>(()))
        },
        agent_client_protocol::on_receive_request!(),
    );

    let (editor_write, conductor_read) = duplex(8192);
    let (conductor_write, editor_read) = duplex(8192);

    let conductor_handle = tokio::spawn(async move {
        ConductorImpl::new_agent(
            "helper-cancellation-conductor".to_string(),
            ProxiesAndAgent::new(agent).proxy(proxy),
        )
        .run(ByteStreams::new(
            conductor_write.compat_write(),
            conductor_read.compat(),
        ))
        .await
    });

    let client_request_id = tokio::time::timeout(Duration::from_secs(30), async move {
        Client
            .builder()
            .connect_with(
                ByteStreams::new(editor_write.compat_write(), editor_read.compat()),
                async |cx| {
                    let initialize = cx
                        .send_request(InitializeRequest::new(ProtocolVersion::V1))
                        .block_task()
                        .await?;
                    assert_eq!(initialize.protocol_version, ProtocolVersion::V1);

                    let request: SentRequest<NewSessionResponse> =
                        cx.send_request(NewSessionRequest::new("/park-session"));
                    let client_request_id = request.id().clone();
                    request.cancel()?;

                    let error = request
                        .block_task()
                        .await
                        .expect_err("session/new should be cancelled");
                    assert_eq!(i32::from(error.code), -32800);

                    let session = cx
                        .send_request(NewSessionRequest::new(
                            std::env::current_dir().map_err(Error::into_internal_error)?,
                        ))
                        .block_task()
                        .await?;
                    assert_eq!(session.session_id, SessionId::new("normal-session"));

                    Ok(client_request_id)
                },
            )
            .await
    })
    .await
    .expect("test timed out")
    .expect("client failed");

    let parked_id = next_with_timeout(&mut parked_id_rx).await;
    assert_ne!(
        parked_id, client_request_id,
        "each hop must re-issue the request under its own ID"
    );
    let observed = next_with_timeout(&mut agent_cancel_rx).await;
    assert_eq!(observed, parked_id);
    assert_no_event(&mut agent_cancel_rx);

    conductor_handle.abort();
    Ok(())
}

/// If the proxy helper attaches MCP servers for a `session/new` that later
/// fails, the MCP dynamic handler must be removed before the next retry.
#[tokio::test]
async fn proxy_session_helper_cleans_up_mcp_handlers_after_cancelled_session() -> Result<(), Error>
{
    let (agent_cancel_tx, mut agent_cancel_rx) = mpsc::unbounded();
    let (parked_id_tx, mut parked_id_rx) = mpsc::unbounded();
    let (mcp_connect_tx, mut mcp_connect_rx) = mpsc::unbounded();
    let (probe_barrier_tx, mut probe_barrier_rx) = mpsc::unbounded();
    let cancelled_mcp_server_id = Arc::new(Mutex::new(None::<McpServerAcpId>));

    let agent = Agent
        .builder()
        .on_receive_request(
            async |initialize: InitializeRequest, responder, _cx: ConnectionTo<Client>| {
                responder.respond(InitializeResponse::new(initialize.protocol_version))
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            {
                let cancelled_mcp_server_id = cancelled_mcp_server_id.clone();
                let parked_id_tx = parked_id_tx.clone();
                let probe_barrier_tx = probe_barrier_tx.clone();
                async move |request: NewSessionRequest,
                            responder: Responder<NewSessionResponse>,
                            cx: ConnectionTo<Client>| {
                    let cancelled_mcp_server_id = cancelled_mcp_server_id.clone();
                    let parked_id_tx = parked_id_tx.clone();
                    let probe_barrier_tx = probe_barrier_tx.clone();
                    let advertised_mcp_server_id = advertised_mcp_server_id(&request);

                    if request.cwd.ends_with("park-session") {
                        *cancelled_mcp_server_id
                            .lock()
                            .expect("cancelled MCP ID mutex poisoned") =
                            Some(advertised_mcp_server_id);
                        parked_id_tx.unbounded_send(responder.id().clone()).unwrap();
                        let cancellation = responder.cancellation();
                        cx.spawn(async move {
                            let response = cancellation
                                .run_until_cancelled(std::future::pending::<
                                    Result<NewSessionResponse, Error>,
                                >())
                                .await;
                            responder.respond_with_result(response)
                        })?;
                        return Ok(());
                    }

                    responder.respond(NewSessionResponse::new(SessionId::new("normal-session")))?;

                    let stale_server_id = cancelled_mcp_server_id
                        .lock()
                        .expect("cancelled MCP ID mutex poisoned")
                        .clone()
                        .expect("cancelled session should have advertised an MCP server");
                    let connection = cx.clone();
                    cx.spawn(async move {
                        connection
                            .send_request(ConnectMcpRequest::new(stale_server_id))
                            .on_receiving_result(async |_| Ok(()))?;

                        let barrier = connection
                            .send_request(RequestPermissionRequest::new(
                                SessionId::new("normal-session"),
                                ToolCallUpdate::new(
                                    "stale-mcp-probe-barrier",
                                    ToolCallUpdateFields::default(),
                                ),
                                vec![PermissionOption::new(
                                    "allow",
                                    "Allow",
                                    PermissionOptionKind::AllowOnce,
                                )],
                            ))
                            .block_task()
                            .await
                            .map(|_| ())
                            .map_err(|error| i32::from(error.code));

                        probe_barrier_tx.unbounded_send(barrier).unwrap();
                        Ok(())
                    })
                }
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_notification(
            async move |cancel: CancelRequestNotification, _cx: ConnectionTo<Client>| {
                agent_cancel_tx.unbounded_send(cancel.request_id).unwrap();
                Ok(())
            },
            agent_client_protocol::on_receive_notification!(),
        );

    let proxy = Proxy.builder().on_receive_request_from(
        Client,
        async move |request: NewSessionRequest,
                    responder: Responder<NewSessionResponse>,
                    cx: ConnectionTo<Conductor>| {
            let mcp_server = McpServer::new(
                TrackingMcpServer {
                    connect_tx: mcp_connect_tx.clone(),
                },
                NullRun,
            );
            cx.build_session_from(request)
                .with_mcp_server(mcp_server)?
                .on_proxy_session_start(responder, async |_session_id| Ok::<(), Error>(()))
        },
        agent_client_protocol::on_receive_request!(),
    );

    let (editor_write, conductor_read) = duplex(8192);
    let (conductor_write, editor_read) = duplex(8192);

    let conductor_handle = tokio::spawn(async move {
        ConductorImpl::new_agent(
            "helper-cleanup-conductor".to_string(),
            ProxiesAndAgent::new(agent).proxy(proxy),
        )
        .run(ByteStreams::new(
            conductor_write.compat_write(),
            conductor_read.compat(),
        ))
        .await
    });

    let client_result = tokio::time::timeout(Duration::from_secs(30), async move {
        Client
            .builder()
            .on_receive_request(
                async |request: RequestPermissionRequest,
                       responder: Responder<RequestPermissionResponse>,
                       _cx: ConnectionTo<Agent>| {
                    assert_eq!(request.session_id, SessionId::new("normal-session"));
                    responder.respond(RequestPermissionResponse::new(
                        RequestPermissionOutcome::Selected(SelectedPermissionOutcome::new("allow")),
                    ))
                },
                agent_client_protocol::on_receive_request!(),
            )
            .connect_with(
                ByteStreams::new(editor_write.compat_write(), editor_read.compat()),
                async move |cx| {
                    let initialize = cx
                        .send_request(InitializeRequest::new(ProtocolVersion::V1))
                        .block_task()
                        .await?;
                    assert_eq!(initialize.protocol_version, ProtocolVersion::V1);

                    let request: SentRequest<NewSessionResponse> =
                        cx.send_request(NewSessionRequest::new("/park-session"));
                    let client_request_id = request.id().clone();
                    request.cancel()?;

                    let error = request
                        .block_task()
                        .await
                        .expect_err("session/new should be cancelled");
                    assert_eq!(i32::from(error.code), -32800);

                    let session = cx
                        .send_request(NewSessionRequest::new(
                            std::env::current_dir().map_err(Error::into_internal_error)?,
                        ))
                        .block_task()
                        .await?;
                    assert_eq!(session.session_id, SessionId::new("normal-session"));

                    let probe_barrier = next_with_timeout(&mut probe_barrier_rx).await;
                    Ok((client_request_id, probe_barrier))
                },
            )
            .await
    })
    .await
    .expect("test timed out")
    .expect("client failed");
    let (client_request_id, probe_barrier) = client_result;

    let parked_id = next_with_timeout(&mut parked_id_rx).await;
    assert_ne!(
        parked_id, client_request_id,
        "each hop must re-issue the request under its own ID"
    );
    let observed = next_with_timeout(&mut agent_cancel_rx).await;
    assert_eq!(observed, parked_id);
    assert_no_event(&mut agent_cancel_rx);

    assert_eq!(
        probe_barrier,
        Ok(()),
        "agent-to-client barrier should succeed after stale MCP probe"
    );
    assert_no_event(&mut mcp_connect_rx);

    conductor_handle.abort();
    Ok(())
}

/// `initialize` is rewritten to `_proxy/initialize` at the conductor-to-proxy
/// hop and forwarded with a result hook — cancellation must still propagate
/// hop by hop, exactly like every other request.
#[tokio::test]
async fn initialize_cancellation_propagates_through_proxy() -> Result<(), Error> {
    let (agent_cancel_tx, mut agent_cancel_rx) = mpsc::unbounded();
    let (parked_id_tx, mut parked_id_rx) = mpsc::unbounded();
    let parked_first = Arc::new(AtomicBool::new(false));

    let agent = Agent.builder().on_receive_request(
        {
            let parked_first = parked_first.clone();
            async move |initialize: InitializeRequest,
                        responder: Responder<InitializeResponse>,
                        cx: ConnectionTo<Client>| {
                if !parked_first.swap(true, Ordering::SeqCst) {
                    parked_id_tx.unbounded_send(responder.id().clone()).unwrap();
                    let cancellation = responder.cancellation();
                    cx.spawn(async move {
                        let response = cancellation
                            .run_until_cancelled(std::future::pending::<
                                Result<InitializeResponse, Error>,
                            >())
                            .await;
                        responder.respond_with_result(response)
                    })?;
                    return Ok(());
                }

                responder.respond(InitializeResponse::new(initialize.protocol_version))
            }
        },
        agent_client_protocol::on_receive_request!(),
    );

    // The cancel observer must be registered on the same builder; do it
    // separately so the request handler above can keep its captures.
    let agent = agent.on_receive_notification(
        async move |cancel: CancelRequestNotification, _cx: ConnectionTo<Client>| {
            agent_cancel_tx.unbounded_send(cancel.request_id).unwrap();
            Ok(())
        },
        agent_client_protocol::on_receive_notification!(),
    );

    let (editor_write, conductor_read) = duplex(8192);
    let (conductor_write, editor_read) = duplex(8192);

    // The passthrough proxy is what exercises the conductor's
    // `initialize` -> `_proxy/initialize` rewriting hop.
    let conductor_handle = tokio::spawn(async move {
        ConductorImpl::new_agent(
            "cancellation-conductor".to_string(),
            ProxiesAndAgent::new(agent).proxy(Proxy.builder()),
        )
        .run(ByteStreams::new(
            conductor_write.compat_write(),
            conductor_read.compat(),
        ))
        .await
    });

    let client_request_id = tokio::time::timeout(Duration::from_secs(30), async move {
        Client
            .builder()
            .connect_with(
                ByteStreams::new(editor_write.compat_write(), editor_read.compat()),
                async |cx| {
                    let request: SentRequest<InitializeResponse> =
                        cx.send_request(InitializeRequest::new(ProtocolVersion::V1));
                    let client_request_id = request.id().clone();
                    request.cancel()?;

                    let error = request
                        .block_task()
                        .await
                        .expect_err("initialize should be cancelled");
                    assert_eq!(i32::from(error.code), -32800);

                    // Barrier through the whole chain: initializing again
                    // still works after the cancelled attempt.
                    let initialize = cx
                        .send_request(InitializeRequest::new(ProtocolVersion::V1))
                        .block_task()
                        .await?;
                    assert_eq!(initialize.protocol_version, ProtocolVersion::V1);

                    Ok(client_request_id)
                },
            )
            .await
    })
    .await
    .expect("test timed out")
    .expect("client failed");

    // The agent saw exactly one `$/cancel_request`, for the `initialize` ID
    // on its own connection.
    let parked_id = next_with_timeout(&mut parked_id_rx).await;
    assert_ne!(
        parked_id, client_request_id,
        "each hop must re-issue the request under its own ID"
    );
    let observed = next_with_timeout(&mut agent_cancel_rx).await;
    assert_eq!(observed, parked_id);
    assert_no_event(&mut agent_cancel_rx);

    conductor_handle.abort();
    Ok(())
}