zeph-acp 0.20.0

ACP (Agent Client Protocol) server for IDE embedding
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;

use agent_client_protocol as acp;
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;

use crate::agent::ZephAcpAgent;

// ── Constants ─────────────────────────────────────────────────────────────────

const MAX_IMPORT_EVENTS: usize = 10_000;
const MAX_SESSION_ID_LEN: usize = 128;

// ── Types ─────────────────────────────────────────────────────────────────────

#[derive(Deserialize)]
pub(crate) struct SessionListParams {}

#[derive(Serialize, Deserialize)]
pub(crate) struct SessionListEntry {
    pub session_id: String,
    pub created_at: String,
    pub busy: bool,
}

#[derive(Serialize, Deserialize)]
pub(crate) struct SessionListResponse {
    pub sessions: Vec<SessionListEntry>,
}

#[derive(Deserialize)]
pub(crate) struct SessionGetParams {
    pub session_id: String,
}

#[derive(Serialize, Deserialize)]
pub(crate) struct SessionEventEntry {
    pub event_type: String,
    pub payload: String,
}

#[derive(Serialize, Deserialize)]
pub(crate) struct SessionGetResponse {
    pub session_id: String,
    pub created_at: String,
    pub busy: bool,
    pub events: Vec<SessionEventEntry>,
}

#[derive(Deserialize)]
pub(crate) struct SessionDeleteParams {
    pub session_id: String,
}

#[derive(Serialize, Deserialize)]
pub(crate) struct SessionDeleteResponse {
    pub deleted: bool,
}

#[derive(Deserialize)]
pub(crate) struct SessionExportParams {
    pub session_id: String,
}

#[derive(Serialize, Deserialize)]
pub(crate) struct SessionExportResponse {
    pub session_id: String,
    pub events: Vec<SessionEventEntry>,
    pub exported_at: String,
}

#[derive(Deserialize)]
pub(crate) struct SessionImportParams {
    pub events: Vec<SessionEventEntry>,
}

#[derive(Serialize, Deserialize)]
pub(crate) struct SessionImportResponse {
    pub session_id: String,
}

#[derive(Deserialize)]
pub(crate) struct AgentToolsParams {
    #[expect(
        dead_code,
        reason = "required for JSON deserialization of the ACP ext method params"
    )]
    pub session_id: String,
}

#[derive(Serialize, Deserialize)]
pub(crate) struct ToolInfo {
    pub id: String,
    pub description: String,
}

#[derive(Serialize, Deserialize)]
pub(crate) struct AgentToolsResponse {
    pub tools: Vec<ToolInfo>,
}

#[derive(Deserialize)]
pub(crate) struct WorkingDirUpdateParams {
    pub session_id: String,
    pub path: String,
}

#[derive(Serialize, Deserialize)]
pub(crate) struct WorkingDirUpdateResponse {
    pub updated: bool,
}

// ── Dispatch ──────────────────────────────────────────────────────────────────

/// Dispatch an `ExtRequest` to the appropriate custom method handler.
/// Returns `None` if the method name is not recognized.
pub(crate) fn dispatch<'a>(
    agent: &'a ZephAcpAgent,
    req: &'a acp::schema::ExtRequest,
) -> Option<
    Pin<Box<dyn std::future::Future<Output = acp::Result<acp::schema::ExtResponse>> + Send + 'a>>,
> {
    match req.method.as_ref() {
        "_session/list" => Some(Box::pin(handle_session_list(agent, &req.params))),
        "_session/get" => Some(Box::pin(handle_session_get(agent, &req.params))),
        "_session/delete" => Some(Box::pin(handle_session_delete(agent, &req.params))),
        "_session/export" => Some(Box::pin(handle_session_export(agent, &req.params))),
        "_session/import" => Some(Box::pin(handle_session_import(agent, &req.params))),
        "_agent/tools" => Some(Box::pin(handle_agent_tools(agent, &req.params))),
        "_agent/working_dir/update" => {
            Some(Box::pin(handle_working_dir_update(agent, &req.params)))
        }
        _ => None,
    }
}

// ── Helpers ───────────────────────────────────────────────────────────────────

fn parse_params<T: serde::de::DeserializeOwned>(raw: &Arc<RawValue>) -> acp::Result<T> {
    serde_json::from_str(raw.get()).map_err(|e| acp::Error::invalid_request().data(e.to_string()))
}

fn to_ext_response<T: Serialize>(value: &T) -> acp::Result<acp::schema::ExtResponse> {
    let json = serde_json::to_string(value)
        .map_err(|e| acp::Error::internal_error().data(e.to_string()))?;
    let raw = RawValue::from_string(json)
        .map_err(|e| acp::Error::internal_error().data(e.to_string()))?;
    Ok(acp::schema::ExtResponse::new(Arc::from(raw)))
}

fn session_not_found() -> acp::Error {
    acp::Error::invalid_request().data("session not found")
}

fn now_iso8601() -> String {
    chrono::Utc::now().to_rfc3339()
}

/// Validate `session_id`: reject if too long or contains characters outside `[a-zA-Z0-9_-]`.
fn validate_session_id(id: &str) -> acp::Result<()> {
    if id.len() > MAX_SESSION_ID_LEN {
        return Err(acp::Error::invalid_request().data("session_id too long"));
    }
    if !id
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
    {
        return Err(acp::Error::invalid_request().data("session_id contains invalid characters"));
    }
    Ok(())
}

// ── Handlers ──────────────────────────────────────────────────────────────────

async fn handle_session_list(
    agent: &ZephAcpAgent,
    raw: &Arc<RawValue>,
) -> acp::Result<acp::schema::ExtResponse> {
    // Deprecated: use the native `list_sessions` ACP method instead.
    // This extension method returns a reduced `SessionListEntry` schema and will be removed
    // in a future release.
    tracing::warn!(
        "ext method `_session/list` is deprecated; use the native `list_sessions` ACP method"
    );
    let _: SessionListParams = parse_params(raw)?;

    // Collect in-memory session tuples while holding the borrow, then release it.
    let in_memory: Vec<(String, String, bool)> = {
        let sessions = agent.sessions.lock();
        let mut tuples = Vec::with_capacity(sessions.len());
        for (id, entry) in sessions.iter() {
            let sid = id.to_string();
            let busy = entry.output_rx.lock().is_none();
            let created_at = entry.created_at.format("%Y-%m-%dT%H:%M:%SZ").to_string();
            tuples.push((sid, created_at, busy));
        }
        tuples
    };

    // Pre-size map: persisted count unknown, use in-memory size as initial hint.
    let mut sessions: std::collections::HashMap<String, SessionListEntry> =
        std::collections::HashMap::with_capacity(in_memory.len());

    // Load persisted sessions first (lower priority, overridden by in-memory).
    if let Some(ref store) = agent.store {
        match store.list_acp_sessions(0).await {
            Ok(rows) => {
                sessions.reserve(rows.len());
                for row in rows {
                    sessions.insert(
                        row.id.clone(),
                        SessionListEntry {
                            session_id: row.id,
                            created_at: row.created_at,
                            busy: false,
                        },
                    );
                }
            }
            Err(e) => tracing::warn!(error = %e, "failed to list persisted ACP sessions"),
        }
    }

    // Override with live in-memory sessions.
    for (sid, created_at, busy) in in_memory {
        sessions.insert(
            sid.clone(),
            SessionListEntry {
                session_id: sid,
                created_at,
                busy,
            },
        );
    }

    let resp = SessionListResponse {
        sessions: sessions.into_values().collect(),
    };
    to_ext_response(&resp)
}

async fn handle_session_get(
    agent: &ZephAcpAgent,
    raw: &Arc<RawValue>,
) -> acp::Result<acp::schema::ExtResponse> {
    let params: SessionGetParams = parse_params(raw)?;
    let sid = params.session_id.as_str();
    validate_session_id(sid)?;

    let (in_memory, created_at, busy) = {
        let sessions = agent.sessions.lock();
        if let Some(entry) = sessions.get(&acp::schema::SessionId::new(sid)) {
            let busy = entry.output_rx.lock().is_none();
            let created_at = entry.created_at.format("%Y-%m-%dT%H:%M:%SZ").to_string();
            (true, created_at, busy)
        } else {
            (false, now_iso8601(), false)
        }
    };

    if !in_memory {
        match &agent.store {
            Some(store) => {
                let exists = store
                    .acp_session_exists(sid)
                    .await
                    .map_err(|e| acp::Error::internal_error().data(e.to_string()))?;
                if !exists {
                    return Err(session_not_found());
                }
            }
            None => return Err(session_not_found()),
        }
    }

    let events = if let Some(ref store) = agent.store {
        match store.load_acp_events(sid).await {
            Ok(evs) => evs
                .into_iter()
                .map(|e| SessionEventEntry {
                    event_type: e.event_type,
                    payload: e.payload,
                })
                .collect(),
            Err(e) => {
                tracing::warn!(error = %e, session_id = %sid, "failed to load ACP events");
                vec![]
            }
        }
    } else {
        vec![]
    };

    let resp = SessionGetResponse {
        session_id: sid.to_owned(),
        created_at,
        busy,
        events,
    };
    to_ext_response(&resp)
}

async fn handle_session_delete(
    agent: &ZephAcpAgent,
    raw: &Arc<RawValue>,
) -> acp::Result<acp::schema::ExtResponse> {
    let params: SessionDeleteParams = parse_params(raw)?;
    validate_session_id(&params.session_id)?;

    let acp_id = acp::schema::SessionId::new(params.session_id.as_str());
    let removed_memory = agent.sessions.lock().remove(&acp_id).is_some();
    if removed_memory {
        // cancel_signal already dropped with the entry; nothing extra needed.
        tracing::debug!(session_id = %params.session_id, "removed in-memory ACP session");
    }

    let removed_store = if let Some(ref store) = agent.store {
        match store.delete_acp_session(&params.session_id).await {
            Ok(()) => true,
            Err(e) => {
                tracing::warn!(error = %e, session_id = %params.session_id, "failed to delete ACP session from store");
                false
            }
        }
    } else {
        false
    };

    to_ext_response(&SessionDeleteResponse {
        deleted: removed_memory || removed_store,
    })
}

async fn handle_session_export(
    agent: &ZephAcpAgent,
    raw: &Arc<RawValue>,
) -> acp::Result<acp::schema::ExtResponse> {
    let params: SessionExportParams = parse_params(raw)?;
    validate_session_id(&params.session_id)?;

    let events = match &agent.store {
        Some(store) => store
            .load_acp_events(&params.session_id)
            .await
            .map_err(|e| acp::Error::internal_error().data(e.to_string()))?
            .into_iter()
            .map(|e| SessionEventEntry {
                event_type: e.event_type,
                payload: e.payload,
            })
            .collect(),
        None => vec![],
    };

    to_ext_response(&SessionExportResponse {
        session_id: params.session_id,
        events,
        exported_at: now_iso8601(),
    })
}

async fn handle_session_import(
    agent: &ZephAcpAgent,
    raw: &Arc<RawValue>,
) -> acp::Result<acp::schema::ExtResponse> {
    let params: SessionImportParams = parse_params(raw)?;

    if params.events.len() > MAX_IMPORT_EVENTS {
        return Err(acp::Error::invalid_request()
            .data(format!("too many events: limit is {MAX_IMPORT_EVENTS}")));
    }

    let new_id = uuid::Uuid::new_v4().to_string();

    if let Some(ref store) = agent.store {
        store
            .create_acp_session(&new_id)
            .await
            .map_err(|e| acp::Error::internal_error().data(e.to_string()))?;
        let pairs: Vec<(&str, &str)> = params
            .events
            .iter()
            .map(|e| (e.event_type.as_str(), e.payload.as_str()))
            .collect();
        store
            .import_acp_events(&new_id, &pairs)
            .await
            .map_err(|e| acp::Error::internal_error().data(e.to_string()))?;
    }

    to_ext_response(&SessionImportResponse { session_id: new_id })
}

#[allow(clippy::unused_async)]
async fn handle_agent_tools(
    _agent: &ZephAcpAgent,
    raw: &Arc<RawValue>,
) -> acp::Result<acp::schema::ExtResponse> {
    let _params: AgentToolsParams = parse_params(raw)?;

    let tools = vec![
        ToolInfo {
            id: "bash".to_owned(),
            description: "Execute shell commands".to_owned(),
        },
        ToolInfo {
            id: "read_file".to_owned(),
            description: "Read file contents".to_owned(),
        },
        ToolInfo {
            id: "write_file".to_owned(),
            description: "Write or update file contents".to_owned(),
        },
        ToolInfo {
            id: "search".to_owned(),
            description: "Search file content with regex".to_owned(),
        },
        ToolInfo {
            id: "web_scrape".to_owned(),
            description: "Fetch and extract content from a URL".to_owned(),
        },
    ];

    to_ext_response(&AgentToolsResponse { tools })
}

#[allow(clippy::unused_async)]
async fn handle_working_dir_update(
    agent: &ZephAcpAgent,
    raw: &Arc<RawValue>,
) -> acp::Result<acp::schema::ExtResponse> {
    let params: WorkingDirUpdateParams = parse_params(raw)?;
    validate_session_id(&params.session_id)?;

    // Reject path traversal: disallow any ParentDir (..) component.
    let p = std::path::Path::new(&params.path);
    if p.components()
        .any(|c| matches!(c, std::path::Component::ParentDir))
    {
        return Err(acp::Error::invalid_request().data("path traversal not allowed"));
    }

    let acp_id = acp::schema::SessionId::new(params.session_id.as_str());
    let updated = {
        let sessions = agent.sessions.lock();
        if let Some(entry) = sessions.get(&acp_id) {
            *entry.working_dir.lock() = Some(PathBuf::from(&params.path));
            true
        } else {
            false
        }
    };

    to_ext_response(&WorkingDirUpdateResponse { updated })
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(any())] // ACP 0.10 tests disabled — rewrite for 0.11 tracked in #3267
mod tests {
    #![allow(clippy::items_after_statements)]

    use std::sync::Arc;

    use acp::Agent as _;
    use agent_client_protocol as acp;
    use serde_json::value::RawValue;
    use tokio::sync::{mpsc, oneshot};

    use crate::agent::ZephAcpAgent;
    use crate::transport::ConnSlot;

    fn make_spawner() -> crate::agent::AgentSpawner {
        Arc::new(|_channel, _ctx, _session_ctx| Box::pin(async {}))
    }

    fn make_agent() -> (
        ZephAcpAgent,
        mpsc::UnboundedReceiver<(acp::schema::SessionNotification, oneshot::Sender<()>)>,
    ) {
        let (tx, rx) = mpsc::unbounded_channel();
        let conn_slot: ConnSlot = std::rc::Rc::new(std::cell::RefCell::new(None));
        (
            ZephAcpAgent::new(make_spawner(), tx, conn_slot, 4, 1800, None),
            rx,
        )
    }

    fn null_params() -> Arc<RawValue> {
        Arc::from(RawValue::from_string("{}".to_owned()).unwrap())
    }

    fn params_json(json: &str) -> Arc<RawValue> {
        Arc::from(RawValue::from_string(json.to_owned()).unwrap())
    }

    #[tokio::test]
    async fn dispatch_returns_none_for_unknown_method() {
        let (agent, _rx) = make_agent();
        let req = acp::schema::ExtRequest::new("unknown/method", null_params());
        assert!(super::dispatch(&agent, &req).is_none());
    }

    #[tokio::test]
    async fn dispatch_session_list_returns_empty() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let req = acp::schema::ExtRequest::new("_session/list", null_params());
                let fut = super::dispatch(&agent, &req).unwrap();
                let resp = fut.await.unwrap();
                let parsed: super::SessionListResponse =
                    serde_json::from_str(resp.0.get()).unwrap();
                assert!(parsed.sessions.is_empty());
            })
            .await;
    }

    #[tokio::test]
    async fn dispatch_session_list_includes_in_memory_session() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let resp = agent
                    .new_session(acp::NewSessionRequest::new(std::path::PathBuf::from(".")))
                    .await
                    .unwrap();
                let sid = resp.session_id.to_string();

                let req = acp::schema::ExtRequest::new("_session/list", null_params());
                let fut = super::dispatch(&agent, &req).unwrap();
                let list_resp: super::SessionListResponse =
                    serde_json::from_str(fut.await.unwrap().0.get()).unwrap();
                assert!(list_resp.sessions.iter().any(|s| s.session_id == sid));
            })
            .await;
    }

    #[tokio::test]
    async fn dispatch_session_delete_removes_session() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let resp = agent
                    .new_session(acp::NewSessionRequest::new(std::path::PathBuf::from(".")))
                    .await
                    .unwrap();
                let sid = resp.session_id.to_string();

                let json = format!(r#"{{"session_id":"{sid}"}}"#);
                let req = acp::schema::ExtRequest::new("_session/delete", params_json(&json));
                let fut = super::dispatch(&agent, &req).unwrap();
                let del_resp: super::SessionDeleteResponse =
                    serde_json::from_str(fut.await.unwrap().0.get()).unwrap();
                assert!(del_resp.deleted);
                assert!(
                    !agent
                        .sessions
                        .borrow()
                        .contains_key(&acp::schema::SessionId::new(sid.as_str()))
                );
            })
            .await;
    }

    #[tokio::test]
    async fn dispatch_session_delete_returns_false_for_unknown() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let json = r#"{"session_id":"no-such-session"}"#;
                let req = acp::schema::ExtRequest::new("_session/delete", params_json(json));
                let fut = super::dispatch(&agent, &req).unwrap();
                let del_resp: super::SessionDeleteResponse =
                    serde_json::from_str(fut.await.unwrap().0.get()).unwrap();
                assert!(!del_resp.deleted);
            })
            .await;
    }

    #[tokio::test]
    async fn dispatch_agent_tools_returns_list() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let json = r#"{"session_id":"any-session"}"#;
                let req = acp::schema::ExtRequest::new("_agent/tools", params_json(json));
                let fut = super::dispatch(&agent, &req).unwrap();
                let tools_resp: super::AgentToolsResponse =
                    serde_json::from_str(fut.await.unwrap().0.get()).unwrap();
                assert!(!tools_resp.tools.is_empty());
            })
            .await;
    }

    #[tokio::test]
    async fn dispatch_working_dir_update_returns_false_for_unknown() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let json = r#"{"session_id":"no-such-session","path":"/tmp"}"#;
                let req =
                    acp::schema::ExtRequest::new("_agent/working_dir/update", params_json(json));
                let fut = super::dispatch(&agent, &req).unwrap();
                let wd_resp: super::WorkingDirUpdateResponse =
                    serde_json::from_str(fut.await.unwrap().0.get()).unwrap();
                assert!(!wd_resp.updated);
            })
            .await;
    }

    #[tokio::test]
    async fn dispatch_working_dir_update_stores_path() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let resp = agent
                    .new_session(acp::NewSessionRequest::new(std::path::PathBuf::from(".")))
                    .await
                    .unwrap();
                let sid = resp.session_id.to_string();

                let json = format!(r#"{{"session_id":"{sid}","path":"/workspace"}}"#);
                let req =
                    acp::schema::ExtRequest::new("_agent/working_dir/update", params_json(&json));
                let fut = super::dispatch(&agent, &req).unwrap();
                let wd_resp: super::WorkingDirUpdateResponse =
                    serde_json::from_str(fut.await.unwrap().0.get()).unwrap();
                assert!(wd_resp.updated);

                let sessions = agent.sessions.lock();
                let entry = sessions
                    .get(&acp::schema::SessionId::new(sid.as_str()))
                    .unwrap();
                assert_eq!(
                    entry.working_dir.lock().as_deref(),
                    Some(std::path::Path::new("/workspace"))
                );
            })
            .await;
    }

    #[tokio::test]
    async fn working_dir_update_rejects_path_traversal() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let resp = agent
                    .new_session(acp::NewSessionRequest::new(std::path::PathBuf::from(".")))
                    .await
                    .unwrap();
                let sid = resp.session_id.to_string();

                let json = format!(r#"{{"session_id":"{sid}","path":"../../etc/passwd"}}"#);
                let req =
                    acp::schema::ExtRequest::new("_agent/working_dir/update", params_json(&json));
                let fut = super::dispatch(&agent, &req).unwrap();
                assert!(fut.await.is_err());
            })
            .await;
    }

    #[tokio::test]
    async fn session_import_rejects_oversized() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                // Build a payload with MAX_IMPORT_EVENTS + 1 events.
                let events: Vec<_> = (0..=super::MAX_IMPORT_EVENTS)
                    .map(|i| {
                        serde_json::json!({"event_type": "user_message", "payload": i.to_string()})
                    })
                    .collect();
                let json = serde_json::to_string(&serde_json::json!({ "events": events })).unwrap();
                let req = acp::schema::ExtRequest::new("_session/import", params_json(&json));
                let fut = super::dispatch(&agent, &req).unwrap();
                assert!(fut.await.is_err());
            })
            .await;
    }

    #[tokio::test]
    async fn session_import_no_store_returns_new_id() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let json = r#"{"events":[]}"#;
                let req = acp::schema::ExtRequest::new("_session/import", params_json(json));
                let fut = super::dispatch(&agent, &req).unwrap();
                let import_resp: super::SessionImportResponse =
                    serde_json::from_str(fut.await.unwrap().0.get()).unwrap();
                assert!(!import_resp.session_id.is_empty());
            })
            .await;
    }

    #[tokio::test]
    async fn session_export_no_store_returns_empty_events() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let json = r#"{"session_id":"any-session-id"}"#;
                let req = acp::schema::ExtRequest::new("_session/export", params_json(json));
                let fut = super::dispatch(&agent, &req).unwrap();
                let export_resp: super::SessionExportResponse =
                    serde_json::from_str(fut.await.unwrap().0.get()).unwrap();
                assert!(export_resp.events.is_empty());
            })
            .await;
    }

    #[tokio::test]
    async fn session_get_returns_error_for_unknown_no_store() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let json = r#"{"session_id":"no-such-session"}"#;
                let req = acp::schema::ExtRequest::new("_session/get", params_json(json));
                let fut = super::dispatch(&agent, &req).unwrap();
                assert!(fut.await.is_err());
            })
            .await;
    }

    #[tokio::test]
    async fn session_get_returns_data_for_in_memory_session() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let resp = agent
                    .new_session(acp::NewSessionRequest::new(std::path::PathBuf::from(".")))
                    .await
                    .unwrap();
                let sid = resp.session_id.to_string();

                let json = format!(r#"{{"session_id":"{sid}"}}"#);
                let req = acp::schema::ExtRequest::new("_session/get", params_json(&json));
                let fut = super::dispatch(&agent, &req).unwrap();
                let get_resp: super::SessionGetResponse =
                    serde_json::from_str(fut.await.unwrap().0.get()).unwrap();
                assert_eq!(get_resp.session_id, sid);
                assert!(!get_resp.busy);
            })
            .await;
    }

    #[tokio::test]
    async fn validate_session_id_rejects_long() {
        let id = "a".repeat(super::MAX_SESSION_ID_LEN + 1);
        assert!(super::validate_session_id(&id).is_err());
    }

    #[tokio::test]
    async fn validate_session_id_rejects_control_chars() {
        assert!(super::validate_session_id("abc\x00def").is_err());
        assert!(super::validate_session_id("abc def").is_err());
        assert!(super::validate_session_id("abc/def").is_err());
    }

    #[tokio::test]
    async fn validate_session_id_accepts_valid() {
        assert!(super::validate_session_id("abc-123_XYZ").is_ok());
        assert!(super::validate_session_id("550e8400-e29b-41d4-a716-446655440000").is_ok());
    }

    // ── Error path: malformed params ──────────────────────────────────────────

    #[tokio::test]
    async fn dispatch_session_get_rejects_malformed_params() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                // Missing required `session_id` field.
                let req = acp::schema::ExtRequest::new("_session/get", null_params());
                let fut = super::dispatch(&agent, &req).unwrap();
                assert!(fut.await.is_err());
            })
            .await;
    }

    #[tokio::test]
    async fn dispatch_session_delete_rejects_malformed_params() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let req = acp::schema::ExtRequest::new("_session/delete", null_params());
                let fut = super::dispatch(&agent, &req).unwrap();
                assert!(fut.await.is_err());
            })
            .await;
    }

    #[tokio::test]
    async fn dispatch_session_export_rejects_malformed_params() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let req = acp::schema::ExtRequest::new("_session/export", null_params());
                let fut = super::dispatch(&agent, &req).unwrap();
                assert!(fut.await.is_err());
            })
            .await;
    }

    #[tokio::test]
    async fn dispatch_working_dir_update_rejects_malformed_params() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let req = acp::schema::ExtRequest::new("_agent/working_dir/update", null_params());
                let fut = super::dispatch(&agent, &req).unwrap();
                assert!(fut.await.is_err());
            })
            .await;
    }

    // ── Error path: invalid session_id in handlers ────────────────────────────

    #[tokio::test]
    async fn session_get_rejects_invalid_session_id() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                // session_id with slash — invalid character.
                let json = r#"{"session_id":"invalid/id"}"#;
                let req = acp::schema::ExtRequest::new("_session/get", params_json(json));
                let fut = super::dispatch(&agent, &req).unwrap();
                assert!(fut.await.is_err());
            })
            .await;
    }

    #[tokio::test]
    async fn session_export_rejects_invalid_session_id() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let json = r#"{"session_id":"bad id with space"}"#;
                let req = acp::schema::ExtRequest::new("_session/export", params_json(json));
                let fut = super::dispatch(&agent, &req).unwrap();
                assert!(fut.await.is_err());
            })
            .await;
    }

    #[tokio::test]
    async fn session_delete_rejects_invalid_session_id() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                // session_id with slash — not in allowed charset.
                let json = r#"{"session_id":"bad/session/id"}"#;
                let req = acp::schema::ExtRequest::new("_session/delete", params_json(json));
                let fut = super::dispatch(&agent, &req).unwrap();
                assert!(fut.await.is_err());
            })
            .await;
    }

    // ── Edge case: import with zero events ────────────────────────────────────

    #[tokio::test]
    async fn session_import_zero_events_returns_new_id() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let json = r#"{"events":[]}"#;
                let req = acp::schema::ExtRequest::new("_session/import", params_json(json));
                let fut = super::dispatch(&agent, &req).unwrap();
                let resp: super::SessionImportResponse =
                    serde_json::from_str(fut.await.unwrap().0.get()).unwrap();
                // New UUID must be non-empty and a valid UUID.
                assert_eq!(resp.session_id.len(), 36);
                assert!(resp.session_id.contains('-'));
            })
            .await;
    }

    // ── Integration: ext_method through Agent trait ───────────────────────────

    #[tokio::test]
    async fn ext_method_unknown_returns_null_response() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let req = acp::schema::ExtRequest::new("unknown/custom/method", null_params());
                let resp = agent.ext_method(req).await.unwrap();
                // Default response for unknown method is JSON null.
                assert_eq!(resp.0.get(), "null");
            })
            .await;
    }

    #[tokio::test]
    async fn ext_method_session_list_via_agent_trait() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                // Create a session first.
                let new_resp = agent
                    .new_session(acp::NewSessionRequest::new(std::path::PathBuf::from(".")))
                    .await
                    .unwrap();
                let sid = new_resp.session_id.to_string();

                // Call _session/list through the Agent trait (not dispatch directly).
                let req = acp::schema::ExtRequest::new("_session/list", null_params());
                let ext_resp = agent.ext_method(req).await.unwrap();
                let list: super::SessionListResponse =
                    serde_json::from_str(ext_resp.0.get()).unwrap();
                assert!(list.sessions.iter().any(|s| s.session_id == sid));
            })
            .await;
    }

    #[tokio::test]
    async fn ext_method_working_dir_path_traversal_via_agent_trait() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (agent, _rx) = make_agent();
                let resp = agent
                    .new_session(acp::NewSessionRequest::new(std::path::PathBuf::from(".")))
                    .await
                    .unwrap();
                let sid = resp.session_id.to_string();

                let json = format!(r#"{{"session_id":"{sid}","path":"../../../etc"}}"#);
                let req =
                    acp::schema::ExtRequest::new("_agent/working_dir/update", params_json(&json));
                // Must return an error through the full Agent trait path.
                assert!(agent.ext_method(req).await.is_err());
            })
            .await;
    }
}