aether-agent-cli 0.9.13

CLI and ACP server for the Aether AI coding agent
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
use super::fake_prompt_mcp::FakePromptMcp;
use super::server::{AcpServer, ServerRunError};
use super::session::actor::SessionActorInit;
use super::session::agent_key::AgentKey;
use super::session::agents::SessionAgents;
use super::session::config::SessionConfigState;
use super::session::error::SessionError;
use super::session::hooks::SessionHooks;
use super::session::model::{Modes, ValidatedMode};
use super::session::runtime::{AgentRuntime, RuntimeFactory};
use super::state::{AcpState, AcpStateConfig};
use crate::error::CliError;
use crate::resolve::InitialSessionSelection;
use crate::settings_args::SettingsSourceArgs;
use crate::workspace::WorkspaceManager;
use crate::workspace::testing::StdCopyCloner;
use acp_utils::notifications::{AuthMethodsUpdatedParams, McpNotification};
use acp_utils::testing::{TestPeer, initialize_request};
use aether_auth::OAuthCredentialStorage;
use aether_core::agent_spec::{AgentSpec, AgentSpecExposure};
use aether_core::core::{AgentBuilder, AgentHandle, Prompt};
use aether_core::events::{AgentEvent, Command, MessageEvent, ToolEvent, TurnEvent, TurnOutcome, UserCommand};
use aether_core::mcp::{McpBuilder, McpSession, ServerFactory, mcp};
use aether_project::AgentCatalog;
use aether_sessions::SessionStore;
use aether_sessions::{SessionControlEvent, SessionEvent, SessionMeta, UserEvent, last_agent_from_events};
use agent_client_protocol::schema::v2::{
    AbsolutePath, InitializeResponse, ReplayFrom, ReplayFromStart, ResumeSessionRequest, SessionId, SessionUpdate,
    StateUpdate, StopReason,
};
use agent_client_protocol::{Agent, Channel, Client, ConnectionTo, on_receive_notification};
use futures::FutureExt;
use llm::testing::FakeLlmProvider;
use llm::{ChatMessage, Context, LlmModel, LlmResponse, SessionUsageEvent, StreamingModelProvider};
use llm::{MessageId, ProviderConnectionOverrides, ToolCallRequest, ToolCallResult};
use mcp_utils::client::{InMemoryServerSpec, McpServer, McpTransport, ToolExposure};
use mcp_utils::testing::{FakeMcpServer, FakeTool, FakeToolResponse, completed_task_payload};
use rmcp::RoleServer;
use rmcp::model::{CallToolResult, CreateTaskResult, DetailedTask, Task, TaskPayload, TaskStatus};
use rmcp::service::DynService;
use std::collections::HashMap;
use std::future::Future;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use tokio::sync::{mpsc, oneshot, watch};
use tokio::task::{JoinHandle, JoinSet, LocalSet};
use tokio_util::sync::CancellationToken;

const PLANNER_REPLY: &str = "planner reply";
const CODER_REPLY: &str = "coder reply";

pub struct AcpTestHarness {
    pub client_cx: ConnectionTo<Agent>,
    pub peer: TestPeer,
    pub initialize_response: InitializeResponse,
    connection: Option<HarnessConnectionTasks>,
    pub auth_updates: mpsc::UnboundedReceiver<acp_utils::notifications::AuthMethodsUpdatedParams>,
    resume_agent: FakeAcpAgent,
    runtime_control: Arc<Mutex<FakeRuntimeControl>>,
    pub oauth_store: Arc<aether_auth::FakeOAuthCredentialStore>,
    agent_cx: ConnectionTo<Client>,
    state: Arc<AcpState>,
    session_store: Arc<SessionStore>,
    _tmp: tempfile::TempDir,
}

/// A real loopback listener backed by the harness's existing state and fake runtimes.
pub struct AcpWebSocketTestServer {
    pub address: SocketAddr,
    detached: watch::Receiver<u64>,
    shutdown: Option<oneshot::Sender<()>>,
    task: JoinHandle<Result<(), ServerRunError>>,
}

impl AcpWebSocketTestServer {
    pub fn url(&self) -> String {
        format!("ws://{}", self.address)
    }

    pub fn subscribe(&self) -> watch::Receiver<u64> {
        self.detached.clone()
    }

    /// Join networking cleanup without shutting down the harness-owned host.
    pub async fn shutdown(mut self) {
        let _ = self.shutdown.take().expect("server is running").send(());
        (&mut self.task).await.expect("listener task joins").expect("listener shuts down");
    }

    /// Drop the running server without executing the normal async shutdown path.
    pub async fn abort(mut self) {
        self.task.abort();
        assert!((&mut self.task).await.expect_err("listener task is aborted").is_cancelled());
    }
}

impl Drop for AcpWebSocketTestServer {
    fn drop(&mut self) {
        self.task.abort();
    }
}

pub struct FakeAgentSwitchingSession {
    session_id: SessionId,
    planner: FakeAcpAgent,
    coder: FakeAcpAgent,
}

#[derive(Clone)]
pub struct FakeAcpAgent {
    name: String,
    captured_contexts: Arc<Mutex<Vec<Context>>>,
}

pub struct FakeBackgroundTask {
    server: FakeMcpServer,
}

pub struct PendingRuntime {
    started: oneshot::Receiver<()>,
    release: oneshot::Sender<bool>,
}

impl PendingRuntime {
    pub async fn wait_until_started(&mut self) {
        (&mut self.started).await.expect("runtime startup reached");
    }

    pub fn finish(self, succeed: bool) {
        self.release.send(succeed).expect("runtime startup is waiting");
    }
}

impl AcpTestHarness {
    pub fn pause_next_runtime(&self) -> PendingRuntime {
        let (started, observed) = oneshot::channel();
        let (release, proceed) = oneshot::channel();
        self.runtime_control.lock().unwrap().pending = Some((started, proceed));
        PendingRuntime { started: observed, release }
    }

    pub fn pause_prompt_expansion(&self) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
        let gate = (Arc::new(tokio::sync::Notify::new()), Arc::new(tokio::sync::Notify::new()));
        self.runtime_control.lock().unwrap().prompt_gate = Some(gate.clone());
        gate
    }

    pub fn watch_agent_prompts(&self) -> watch::Receiver<usize> {
        self.runtime_control.lock().unwrap().agent_prompts.subscribe()
    }

    pub fn elicit_during_prompt_expansion(&self) -> mpsc::UnboundedReceiver<rmcp::model::ElicitResult> {
        let (sender, receiver) = mpsc::unbounded_channel();
        self.runtime_control.lock().unwrap().elicitation_results = Some(sender);
        receiver
    }

    pub fn live_runtime_count(&self) -> usize {
        self.runtime_control.lock().unwrap().agents.iter().filter(|sender| !sender.is_closed()).count()
    }

    pub async fn disconnect(&mut self) {
        if let Some(connection) = self.connection.take() {
            connection.shutdown().await;
        }
    }

    pub async fn start_unattached_session(&mut self, prompt: impl Into<String>) -> SessionId {
        self.disconnect().await;
        self.state.start_session(prompt.into()).await.expect("unattached session starts")
    }

    /// Connect a fresh initialized client to the same host and session store.
    pub async fn reconnect(&mut self) {
        assert!(self.connection.is_none(), "disconnect the current client before reconnecting");
        assert!(!self.state.stop_token().is_cancelled(), "host is running");
        let connection = connect_client(self.state.clone()).await;
        self.client_cx = connection.client_cx;
        self.agent_cx = connection.agent_cx;
        self.peer = connection.peer;
        self.initialize_response = connection.initialize_response;
        self.auth_updates = connection.auth_updates;
        self.connection = Some(connection.tasks);
    }

    pub async fn resume(&self, session_id: &SessionId) {
        self.client_cx
            .send_request(ResumeSessionRequest::new(session_id.clone(), AbsolutePath::new("/tmp")))
            .block_task()
            .await
            .expect("session resumes");
    }

    pub async fn resume_with_replay(&self, session_id: &SessionId) {
        self.client_cx
            .send_request(
                ResumeSessionRequest::new(session_id.clone(), AbsolutePath::new("/tmp"))
                    .replay_from(ReplayFrom::Start(ReplayFromStart::new())),
            )
            .block_task()
            .await
            .expect("session resumes with replay");
    }

    /// Move this persistent host from its in-memory connection to a real port-zero listener.
    pub async fn serve_websocket(&mut self) -> AcpWebSocketTestServer {
        self.disconnect().await;
        self.listen_websocket().await
    }

    /// Listen without disconnecting any existing client.
    pub async fn listen_websocket(&self) -> AcpWebSocketTestServer {
        assert!(!self.state.stop_token().is_cancelled(), "host is running");
        let server =
            AcpServer::bind("127.0.0.1:0".parse().unwrap(), self.state.clone()).await.expect("bind test server");
        let address = server.local_addr().expect("listener address");
        let detached = self.state.client_slot().subscribe();
        let (shutdown, stopped) = oneshot::channel();
        let task = tokio::spawn(server.run_until(async move {
            let _ = stopped.await;
            Ok(())
        }));
        AcpWebSocketTestServer { address, detached, shutdown: Some(shutdown), task }
    }

    /// Stop the connection and all host-owned session runtimes.
    pub async fn shutdown(&mut self) {
        self.disconnect().await;
        self.state.shutdown_all().await;
    }

    pub fn stored_events(&self, session_id: &SessionId) -> Vec<SessionEvent> {
        self.session_store.load(session_id.0.as_ref()).expect("stored session loads").1
    }

    /// Runs `body` with a fresh harness on the current-thread `LocalSet` the
    /// host needs for its `spawn_local` tasks; tests must be annotated with
    /// `#[tokio::test(flavor = "current_thread")]`.
    pub async fn run<F, Fut, T>(body: F) -> T
    where
        F: FnOnce(Self) -> Fut,
        Fut: Future<Output = T>,
    {
        LocalSet::new().run_until(Box::pin(async move { body(Self::start().await).await })).await
    }

    pub async fn run_with_hooks<F, Fut>(hooks: SessionHooks, body: F)
    where
        F: FnOnce(Self) -> Fut,
        Fut: Future<Output = ()>,
    {
        LocalSet::new().run_until(Box::pin(async move { body(Self::start_with(hooks).await).await })).await;
    }

    pub async fn start() -> Self {
        Self::start_with(SessionHooks::default()).await
    }

    async fn start_with(hooks: SessionHooks) -> Self {
        let tmp = tempfile::tempdir().expect("tempdir for session store");
        let session_store = Arc::new(SessionStore::from_path(tmp.path().to_path_buf()));
        let workspace_manager = Arc::new(WorkspaceManager::from_registry_path_with_cloner(
            tmp.path().join("workspaces.json"),
            Arc::new(StdCopyCloner),
        ));
        let (resume_def, resume_agent) = fake_agent("Resume", "resume-mcp", "resume", "resumed reply");
        let mut resume_agents = HashMap::new();
        resume_agents.insert(resume_def.spec.name.clone(), resume_def);
        let runtime_control = Arc::new(Mutex::new(FakeRuntimeControl::default()));
        let runtime_factory = Arc::new(FakeRuntimeFactory {
            cwd: PathBuf::from("/tmp"),
            agents: resume_agents,
            control: runtime_control.clone(),
        });
        let oauth_store = Arc::new(aether_auth::FakeOAuthCredentialStore::new());
        let state = Arc::new(AcpState::with_login(
            AcpStateConfig {
                session_store: session_store.clone(),
                workspace_manager,
                oauth_credential_store: oauth_store.clone(),
                initial_selection: InitialSessionSelection::default(),
                settings_source: SettingsSourceArgs::default(),
                provider_connections: ProviderConnectionOverrides::default(),
                telemetry: None,
                runtime_factory: Some(runtime_factory),
                cwd: PathBuf::from("/tmp"),
                hooks,
            },
            Arc::new(FakeProviderLogin),
        ));

        let connection = connect_client(state.clone()).await;
        Self {
            client_cx: connection.client_cx,
            peer: connection.peer,
            initialize_response: connection.initialize_response,
            connection: Some(connection.tasks),
            auth_updates: connection.auth_updates,
            resume_agent,
            runtime_control,
            oauth_store,
            agent_cx: connection.agent_cx,
            state,
            session_store,
            _tmp: tmp,
        }
    }

    pub fn resume_agent(&self) -> &FakeAcpAgent {
        &self.resume_agent
    }

    pub async fn insert_agent_switching_session(&self) -> FakeAgentSwitchingSession {
        self.insert_switching_session(
            SessionId::new("agent-switching-session"),
            Vec::new(),
            Some("Planner".to_string()),
            false,
        )
        .await
    }

    pub async fn insert_agent_switching_session_with_serverless_coder(&self) -> FakeAgentSwitchingSession {
        self.insert_switching_session(
            SessionId::new("agent-switching-serverless-session"),
            Vec::new(),
            Some("Planner".to_string()),
            true,
        )
        .await
    }

    pub async fn insert_loaded_agent_switching_session(&self, session_id: &str) -> FakeAgentSwitchingSession {
        let events = self.session_store.load(session_id).map(|(_, events)| events).unwrap_or_default();
        let selected_mode = last_agent_from_events(Some("Planner".to_string()), &events);
        self.insert_switching_session(SessionId::new(session_id), events, selected_mode, false).await
    }

    pub async fn expect_idle(&mut self, session_id: &SessionId, expected: StopReason) {
        loop {
            let notification = self.peer.next_session_notification().await;
            if notification.session_id == *session_id
                && let SessionUpdate::StateUpdate(StateUpdate::Idle(idle)) = notification.update
            {
                assert_eq!(idle.stop_reason, Some(expected));
                return;
            }
        }
    }

    pub async fn updates_until(
        &mut self,
        session_id: &SessionId,
        last: impl Fn(&SessionUpdate) -> bool,
    ) -> Vec<SessionUpdate> {
        let mut updates = Vec::new();
        loop {
            let notification = self.peer.next_session_notification().await;
            if notification.session_id != *session_id {
                continue;
            }
            let done = last(&notification.update);
            updates.push(notification.update);
            if done {
                return updates;
            }
        }
    }

    pub async fn expect_mcp_server_status(&mut self, expected: &[&str]) {
        assert_server_status(self.peer.next_mcp_notification().await, expected);
    }

    pub async fn expect_mcp_server_status_exact(&mut self, expected: &[&str]) {
        assert_server_status_exact(self.peer.next_mcp_notification().await, expected);
    }

    pub async fn expect_available_commands(&mut self, expected: &[&str], unexpected: &[&str]) {
        loop {
            let update = self.peer.next_session_notification().await.update;
            if matches!(update, SessionUpdate::AvailableCommandsUpdate(_)) {
                assert_available_commands(update, expected, unexpected);
                return;
            }
        }
    }

    pub fn append_agent_switch(&self, session_id: &str, from: Option<&str>, to: Option<&str>) {
        self.append_stored_event(
            session_id,
            &SessionEvent::Control(SessionControlEvent::AgentSwitched {
                from: from.map(str::to_string),
                to: to.map(str::to_string),
            }),
        );
    }

    /// Register a stub session built from a hand-spawned
    /// `(agent_tx, agent_rx, agent_handle)` triple — typically from
    /// `aether_core::core::agent(fake_llm).spawn().await`. Pairs the agent with a
    /// real but empty in-memory MCP (no servers). The session is routable via
    /// `state.route_prompt(id)` / `state.cancel(id)`.
    pub async fn insert_stub_session(
        &self,
        agent_tx: mpsc::Sender<Command>,
        agent_rx: mpsc::Receiver<AgentEvent>,
        agent_handle: AgentHandle,
        id: SessionId,
        model: &str,
    ) {
        let mut mcp = mcp("/tmp").spawn().await.expect("stub MCP spawns");
        mcp.block_until_ready().await.expect("stub MCP is ready");
        self.register_stub_session(StubAgentParts { tx: agent_tx, rx: agent_rx, handle: agent_handle, mcp }, id, model)
            .await;
    }

    pub async fn insert_background_task_session(
        &self,
        provider: FakeLlmProvider,
        task: &FakeBackgroundTask,
        id: SessionId,
    ) {
        let server = task.server.clone();
        let gate = self.runtime_control.lock().unwrap().prompt_gate.clone();
        let mcp = with_in_memory_server(mcp("/tmp"), "tasks", move || server.clone().into_dyn());
        let mcp = with_in_memory_server(mcp, "prompts", move || {
            FakePromptMcp::new("plan").with_gate(gate.clone()).into_dyn()
        });
        let mut mcp = mcp.spawn().await.expect("background task MCP spawns");
        mcp.block_until_ready().await.expect("background task MCP is ready");
        let (tx, rx, handle) = AgentBuilder::new(Arc::new(provider))
            .max_auto_continues(0)
            .tools(mcp.handle().clone(), Vec::new())
            .spawn()
            .await
            .expect("background task agent spawns");
        self.register_stub_session(StubAgentParts { tx, rx, handle, mcp }, id, "fake:fake").await;
    }

    pub fn append_stored_session(&self, session_id: &str, created_at: &str) {
        self.append_stored_session_in(session_id, created_at, std::path::Path::new("/tmp"));
    }

    pub fn append_stored_session_in(&self, session_id: &str, created_at: &str, cwd: &std::path::Path) {
        let meta = SessionMeta {
            session_id: session_id.to_string(),
            cwd: cwd.to_path_buf(),
            model: "anthropic:claude-sonnet-4-5".to_string(),
            selected_mode: None,
            created_at: created_at.to_string(),
        };

        self.session_store.append_meta(session_id, &meta).expect("stored session meta appends");
    }

    pub fn append_stored_prompt(&self, session_id: &str, prompt: &str) {
        self.append_stored_event(
            session_id,
            &SessionEvent::User(UserEvent::Message {
                message_id: llm::MessageId::new(),
                content: vec![llm::ContentBlock::text(prompt)],
                display_content: None,
            }),
        );
    }

    pub fn append_stored_user_blocks(&self, session_id: &str, blocks: Vec<llm::ContentBlock>) {
        self.append_stored_event(
            session_id,
            &SessionEvent::User(UserEvent::Message {
                message_id: llm::MessageId::new(),
                content: blocks,
                display_content: None,
            }),
        );
    }

    pub fn append_stored_agent_turn(&self, session_id: &str, text: &str) {
        self.append_stored_agent_text(session_id, text);
        self.append_stored_event(
            session_id,
            &SessionEvent::Agent(AgentEvent::Turn(TurnEvent::Ended { outcome: TurnOutcome::Completed })),
        );
    }

    pub fn append_stored_agent_text(&self, session_id: &str, text: &str) {
        self.append_stored_event(
            session_id,
            &SessionEvent::Agent(AgentEvent::Message(MessageEvent::Text {
                message_id: MessageId::new(),
                chunk: text.to_string(),
                is_complete: true,
            })),
        );
    }

    pub fn append_stored_tool_call(&self, session_id: &str, id: &str, name: &str, arguments: &str) {
        self.append_stored_event(
            session_id,
            &SessionEvent::Agent(AgentEvent::Tool(ToolEvent::Call {
                request: ToolCallRequest {
                    id: id.to_string(),
                    name: name.to_string(),
                    arguments: arguments.to_string(),
                },
            })),
        );
    }

    pub fn append_stored_tool_result(&self, session_id: &str, id: &str, name: &str, result: &str) {
        self.append_stored_event(
            session_id,
            &SessionEvent::Agent(AgentEvent::Tool(ToolEvent::Result {
                result: ToolCallResult {
                    id: id.to_string(),
                    name: name.to_string(),
                    arguments: "{}".to_string(),
                    result: result.to_string(),
                },
                result_meta: None,
            })),
        );
    }

    async fn insert_switching_session(
        &self,
        acp_session_id: SessionId,
        events: Vec<SessionEvent>,
        selected_mode: Option<String>,
        serverless_coder: bool,
    ) -> FakeAgentSwitchingSession {
        let (planner_def, planner) = fake_agent("Planner", "planner-mcp", "plan", PLANNER_REPLY);
        let (mut coder_def, coder) = fake_agent("Coder", "coder-mcp", "edit", CODER_REPLY);
        if serverless_coder {
            coder_def.mcp = None;
        }

        let mut catalog_specs = Vec::new();
        let mut agents = HashMap::new();
        for def in [planner_def, coder_def] {
            catalog_specs.push(def.spec.clone());
            agents.insert(def.spec.name.clone(), def);
        }
        let specs = SessionAgents::new(AgentCatalog::new(PathBuf::from("/tmp"), catalog_specs, None));

        let factory =
            Arc::new(FakeRuntimeFactory { cwd: PathBuf::from("/tmp"), agents, control: self.runtime_control.clone() });
        let initial_agent = selected_mode.clone().unwrap_or_else(|| "Planner".to_string());

        self.state
            .register_session(SessionActorInit {
                cwd: PathBuf::from("/tmp"),
                mcp_servers: Vec::new(),
                session_id: acp_session_id.clone(),
                connection: Some(self.agent_cx.clone()),
                repository: self.session_store.clone(),
                oauth_credential_store: self.oauth_store.clone(),
                active_agent: AgentKey::Named(initial_agent),
                specs,
                runtime_factory: factory,
                transcript: events,
                replay: false,
                modes: switching_modes(),
                config: SessionConfigState::with_selection(
                    "anthropic:claude-sonnet-4-5".to_string(),
                    selected_mode,
                    None,
                ),
                hooks: SessionHooks::default(),
            })
            .await;
        FakeAgentSwitchingSession { session_id: acp_session_id, planner, coder }
    }

    pub fn append_stored_event(&self, session_id: &str, event: &SessionEvent) {
        self.session_store.append_event(session_id, event).expect("stored session event appends");
    }

    async fn register_stub_session(&self, mut parts: StubAgentParts, id: SessionId, model: &str) {
        let model_spec: llm::catalog::LlmModel = "anthropic:claude-sonnet-4-5".parse().expect("test model parses");
        let mut specs = SessionAgents::new(AgentCatalog::empty(PathBuf::from("/tmp")));
        specs.set_default(AgentSpec::bare(&model_spec, None, Vec::new()));
        let agent_prompts = self.runtime_control.lock().unwrap().agent_prompts.clone();
        self.runtime_control.lock().unwrap().agents.push(parts.tx.clone());
        parts.tx = count_prompts(parts.tx, agent_prompts);
        let factory = Arc::new(StubRuntimeFactory { agent_parts: Mutex::new(Some(parts)) });

        self.state
            .register_session(SessionActorInit {
                cwd: PathBuf::from("/tmp"),
                mcp_servers: Vec::new(),
                session_id: id.clone(),
                connection: Some(self.agent_cx.clone()),
                repository: self.session_store.clone(),
                oauth_credential_store: self.oauth_store.clone(),
                active_agent: AgentKey::Default,
                specs,
                runtime_factory: factory,
                transcript: Vec::new(),
                replay: false,
                modes: Modes::default(),
                config: SessionConfigState::with_selection(model.to_string(), None, None),
                hooks: SessionHooks::default(),
            })
            .await;
    }
}

impl FakeAgentSwitchingSession {
    pub fn session_id(&self) -> &SessionId {
        &self.session_id
    }

    pub fn planner(&self) -> &FakeAcpAgent {
        &self.planner
    }

    pub fn coder(&self) -> &FakeAcpAgent {
        &self.coder
    }
}

impl FakeAcpAgent {
    /// Asserts the agent's most recent turn saw a conversation containing each
    /// of `expected` (user or assistant text), in addition to anything else.
    pub fn assert_saw(&self, expected: &[&str]) {
        let seen = self.latest_conversation();
        for text in expected {
            assert!(seen.iter().any(|m| m == text), "{} should have seen {text:?}; saw {seen:?}", self.name);
        }
    }

    /// Asserts the agent's most recent turn saw *exactly* `expected` and nothing
    /// else — used to prove a freshly-activated agent started with no prior
    /// transcript.
    pub fn assert_saw_exactly(&self, expected: &[&str]) {
        let seen = self.latest_conversation();
        let expected: Vec<String> = expected.iter().map(|t| (*t).to_string()).collect();
        assert_eq!(seen, expected, "{} conversation mismatch", self.name);
    }

    pub fn assert_saw_user_content(&self, expected: &[llm::ContentBlock]) {
        let contexts = self.captured_contexts.lock().expect("captured contexts lock is healthy");
        let latest = contexts.last().expect("agent should have run a turn");
        assert!(
            latest
                .messages()
                .iter()
                .any(|message| { matches!(message, ChatMessage::User { content, .. } if content == expected) }),
            "{} should have seen user content {expected:?}",
            self.name
        );
    }

    /// Asserts the agent never ran a turn (its LLM was never invoked).
    pub fn assert_never_ran(&self) {
        let contexts = self.captured_contexts.lock().expect("captured contexts lock is healthy");
        assert!(contexts.is_empty(), "{} should not have run; captured {} context(s)", self.name, contexts.len());
    }

    fn latest_conversation(&self) -> Vec<String> {
        let contexts = self.captured_contexts.lock().expect("captured contexts lock is healthy");
        let latest = contexts.last().unwrap_or_else(|| panic!("{} should have run a turn", self.name));
        conversation_texts(latest)
    }
}

impl FakeBackgroundTask {
    pub const TOOL: &str = "tasks__start";
    const ID: &str = "background-task";

    pub fn new() -> Self {
        let working = background_task(TaskStatus::Working);
        let server = FakeMcpServer::new()
            .with_tool(FakeTool::new("start").responds(FakeToolResponse::task(CreateTaskResult::new(working.clone()))))
            .with_task(Self::ID, [DetailedTask::new(working, TaskPayload::Working)]);
        Self { server }
    }

    pub fn complete(&self, output: &str) {
        let result = CallToolResult::success(vec![rmcp::model::ContentBlock::text(output)]);
        let completed = DetailedTask::new(background_task(TaskStatus::Completed), completed_task_payload(result));
        self.server.state().script_task(Self::ID, [completed]);
    }
}

impl Default for FakeBackgroundTask {
    fn default() -> Self {
        Self::new()
    }
}

struct HarnessConnection {
    client_cx: ConnectionTo<Agent>,
    agent_cx: ConnectionTo<Client>,
    peer: TestPeer,
    initialize_response: InitializeResponse,
    auth_updates: mpsc::UnboundedReceiver<acp_utils::notifications::AuthMethodsUpdatedParams>,
    tasks: HarnessConnectionTasks,
}

struct HarnessConnectionTasks {
    stop: CancellationToken,
    tasks: JoinSet<Result<(), agent_client_protocol::Error>>,
}

impl HarnessConnectionTasks {
    async fn shutdown(mut self) {
        self.stop.cancel();
        while let Some(result) = self.tasks.join_next().await {
            result.expect("connection task joins").expect("connection cleanup completes");
        }
    }
}

async fn connect_client(state: Arc<AcpState>) -> HarnessConnection {
    let (peer, client_builder) = TestPeer::new();
    let (auth_tx, auth_updates) = mpsc::unbounded_channel();
    let client_builder = client_builder.on_receive_notification(
        async move |notification: AuthMethodsUpdatedParams, _cx| {
            let _ = auth_tx.send(notification);
            Ok(())
        },
        on_receive_notification!(),
    );
    let (agent_transport, client_transport) = Channel::duplex();
    let (send_agent_connection, agent_ready) = oneshot::channel();
    let (send_client_connection, client_ready) = oneshot::channel();
    let stop = state.stop_token().child_token();
    let mut tasks = JoinSet::new();
    let agent_stop = stop.clone();
    tasks.spawn_local(async move { state.serve_with(agent_transport, agent_stop, send_agent_connection).await });
    tasks.spawn_local(async move {
        client_builder
            .with_runner(acp_utils::testing::CaptureConnection(send_client_connection))
            .connect_to(client_transport)
            .await
    });
    let agent_cx = agent_ready.await.expect("agent connection");
    let client_cx = client_ready.await.expect("client connection");
    let initialize_response =
        client_cx.send_request(initialize_request()).block_task().await.expect("initialize harness");
    HarnessConnection {
        client_cx,
        agent_cx,
        peer,
        initialize_response,
        auth_updates,
        tasks: HarnessConnectionTasks { stop, tasks },
    }
}

/// Spawns each agent's runtime through the real [`AgentRuntime`] wiring, but
/// backed by a [`FakeLlmProvider`] and an in-memory MCP server instead of a
/// network LLM and external MCP processes.
struct FakeRuntimeFactory {
    cwd: PathBuf,
    agents: HashMap<String, FakeAgentDef>,
    control: Arc<Mutex<FakeRuntimeControl>>,
}

#[derive(Default)]
struct FakeRuntimeControl {
    agents: Vec<mpsc::Sender<Command>>,
    pending: Option<(oneshot::Sender<()>, oneshot::Receiver<bool>)>,
    prompt_gate: Option<(Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>)>,
    elicitation_results: Option<mpsc::UnboundedSender<rmcp::model::ElicitResult>>,
    agent_prompts: watch::Sender<usize>,
}

struct FakeAgentDef {
    spec: AgentSpec,
    provider: Arc<dyn StreamingModelProvider>,
    mcp: Option<(String, String)>,
}

#[async_trait::async_trait]
impl RuntimeFactory for FakeRuntimeFactory {
    async fn spawn(
        &self,
        _agent: AgentKey,
        spec: &AgentSpec,
        initial_messages: Vec<ChatMessage>,
        usage_seed: Option<SessionUsageEvent>,
    ) -> Result<AgentRuntime, SessionError> {
        let pending = self.control.lock().unwrap().pending.take();
        if let Some((started, proceed)) = pending {
            let _ = started.send(());
            if !proceed.await.unwrap_or(false) {
                return Err(SessionError::AgentNotFound("injected startup failure".to_string()));
            }
        }
        let def = self
            .agents
            .get(&spec.name)
            .or_else(|| self.agents.values().next())
            .ok_or_else(|| SessionError::AgentNotFound(spec.name.clone()))?;
        let provider = def.provider.clone();

        let mut mcp_builder = mcp(&self.cwd).with_tool_filter(spec.tools.clone());
        if let Some((server_name, prompt_name)) = &def.mcp {
            let prompt_name = prompt_name.clone();
            let gate = self.control.lock().unwrap().prompt_gate.clone();
            let elicitation_results = self.control.lock().unwrap().elicitation_results.clone();
            mcp_builder = with_in_memory_server(mcp_builder, server_name, move || {
                FakePromptMcp::new(&prompt_name)
                    .with_gate(gate.clone())
                    .with_elicitation(elicitation_results.clone())
                    .into_dyn()
            });
        }
        let mut spawn =
            mcp_builder.spawn().await.map_err(|e| SessionError::Build(CliError::McpError(e.to_string())))?;
        spawn.block_until_ready().await.ok_or(SessionError::McpStartupStopped)?;
        let mcp_handle = spawn.handle().clone();
        let mut builder = AgentBuilder::new(provider).max_auto_continues(0);
        if let Some(last) = &usage_seed {
            builder = builder.resume_usage(last);
        }
        for prompt in &spec.prompts {
            builder = builder.system_prompt(prompt.clone());
        }
        let (agent_tx, agent_rx, agent_handle) = builder
            .tools(mcp_handle, Vec::new())
            .messages(initial_messages)
            .spawn()
            .await
            .map_err(|e| SessionError::Build(CliError::AgentError(e.to_string())))?;
        self.control.lock().unwrap().agents.push(agent_tx.clone());
        let (mcp_runtime, event_rx) = spawn.connect_agent(agent_tx.clone()).await.split();

        Ok(AgentRuntime::new(agent_tx, agent_rx, Some(agent_handle), event_rx, mcp_runtime))
    }
}

struct StubRuntimeFactory {
    agent_parts: Mutex<Option<StubAgentParts>>,
}

struct StubAgentParts {
    tx: mpsc::Sender<Command>,
    rx: mpsc::Receiver<AgentEvent>,
    handle: AgentHandle,
    mcp: McpSession,
}

#[async_trait::async_trait]
impl RuntimeFactory for StubRuntimeFactory {
    async fn spawn(
        &self,
        _agent: AgentKey,
        _spec: &AgentSpec,
        _initial_messages: Vec<ChatMessage>,
        _usage_seed: Option<SessionUsageEvent>,
    ) -> Result<AgentRuntime, SessionError> {
        let parts = self
            .agent_parts
            .lock()
            .expect("stub agent parts lock is healthy")
            .take()
            .expect("stub runtime spawned more than once");
        let (mcp_runtime, event_rx) = parts.mcp.connect_agent(parts.tx.clone()).await.split();

        Ok(AgentRuntime::new(parts.tx, parts.rx, Some(parts.handle), event_rx, mcp_runtime))
    }
}

fn with_in_memory_server(
    builder: McpBuilder,
    name: &str,
    server: impl Fn() -> Box<dyn DynService<RoleServer>> + Send + Sync + 'static,
) -> McpBuilder {
    let factory: ServerFactory = Box::new(move |_spec, _services| std::future::ready(server()).boxed());
    let transport = McpTransport::InMemory {
        spec: InMemoryServerSpec { factory: name.to_string(), args: Vec::new(), input: None },
    };
    builder.register_in_memory_server(name, factory).with_servers(vec![McpServer::new(
        name,
        transport,
        ToolExposure::ModelVisible,
    )])
}

fn count_prompts(agent_tx: mpsc::Sender<Command>, prompts: watch::Sender<usize>) -> mpsc::Sender<Command> {
    let (tx, mut rx) = mpsc::channel(32);
    tokio::spawn(async move {
        while let Some(command) = rx.recv().await {
            let is_prompt = matches!(command, Command::UserCommand(UserCommand::Text { .. }));
            if agent_tx.send(command).await.is_err() {
                return;
            }
            if is_prompt {
                prompts.send_modify(|count| *count += 1);
            }
        }
    });
    tx
}

fn background_task(status: TaskStatus) -> Task {
    const CREATED_AT: &str = "2026-01-01T00:00:00Z";
    Task::new(FakeBackgroundTask::ID, status, CREATED_AT.to_string(), CREATED_AT.to_string()).with_poll_interval_ms(10)
}

fn fake_agent(name: &str, server_name: &str, prompt_name: &str, reply: &str) -> (FakeAgentDef, FakeAcpAgent) {
    const TURNS_BEFORE_AND_AFTER_REATTACH: usize = 2;
    let provider = FakeLlmProvider::new(vec![
        vec![LlmResponse::Start, LlmResponse::text(reply), LlmResponse::done()];
        TURNS_BEFORE_AND_AFTER_REATTACH
    ])
    .with_display_name(name);
    let captured_contexts = provider.captured_contexts();
    let def = FakeAgentDef {
        spec: fake_agent_spec(name),
        provider: Arc::new(provider),
        mcp: Some((server_name.to_string(), prompt_name.to_string())),
    };
    let observer = FakeAcpAgent { name: name.to_string(), captured_contexts };
    (def, observer)
}

struct FakeProviderLogin;

#[async_trait::async_trait]
impl super::state::ProviderLogin for FakeProviderLogin {
    async fn login(&self, store: &dyn OAuthCredentialStorage) -> Result<(), llm::LlmError> {
        store
            .save("codex", serde_json::json!({"access_token": "fake-access", "refresh_token": "fake-refresh"}))
            .await?;
        Ok(())
    }
}

fn switching_modes() -> Modes {
    Modes::new(vec![
        ValidatedMode {
            name: "Planner".to_string(),
            model: "anthropic:claude-sonnet-4-5".to_string(),
            reasoning_effort: None,
        },
        ValidatedMode { name: "Coder".to_string(), model: text_only_model(), reasoning_effort: None },
    ])
}

fn text_only_model() -> String {
    LlmModel::all()
        .iter()
        .find(|model| !model.supports_image())
        .expect("catalog contains a text-only model")
        .to_string()
}

fn fake_agent_spec(name: &str) -> AgentSpec {
    let model: llm::catalog::LlmModel = "anthropic:claude-sonnet-4-5".parse().expect("test model parses");
    let mut spec = AgentSpec::bare(&model, None, vec![Prompt::text(&format!("{name} system prompt"))]);
    spec.name = name.to_string();
    spec.description = format!("{name} test agent");
    spec.exposure = AgentSpecExposure::user_only();
    spec
}

fn assert_available_commands(update: SessionUpdate, expected: &[&str], unexpected: &[&str]) {
    let SessionUpdate::AvailableCommandsUpdate(commands) = update else {
        panic!("expected available commands update");
    };
    let names = commands.available_commands.iter().map(|command| command.name.as_str()).collect::<Vec<_>>();
    for name in expected {
        assert!(names.contains(name), "expected command /{name} in {names:?}");
    }
    for name in unexpected {
        assert!(!names.contains(name), "did not expect command /{name} in {names:?}");
    }
}

fn assert_server_status(notification: McpNotification, expected: &[&str]) {
    let McpNotification::ServerStatus { servers } = notification;
    let names = servers.iter().map(|server| server.name.as_str()).collect::<Vec<_>>();
    for server_name in expected {
        assert!(names.contains(server_name), "expected server {server_name} in {names:?}");
    }
}

fn assert_server_status_exact(notification: McpNotification, expected: &[&str]) {
    let McpNotification::ServerStatus { servers } = notification;
    let names = servers.iter().map(|server| server.name.as_str()).collect::<Vec<_>>();
    assert_eq!(names, expected);
}

fn conversation_texts(context: &Context) -> Vec<String> {
    context
        .messages()
        .iter()
        .filter_map(|message| match message {
            ChatMessage::User { content, .. } => llm::ContentBlock::first_text(content).map(str::to_string),
            ChatMessage::Assistant { content, .. } if !content.is_empty() => Some(content.clone()),
            _ => None,
        })
        .collect()
}