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
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
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

//! IDE-proxied shell executor via ACP `terminal/*` methods.
//!
//! When the IDE advertises `terminal` capability, the agent routes `bash` tool
//! calls through the IDE's integrated terminal instead of spawning a local process.
//! This keeps the terminal visible in the IDE UI and allows live output streaming.
//!
//! # Security
//!
//! All terminal commands require an [`AcpPermissionGate`] to request IDE confirmation.
//! Stdin writes are rate-limited and capped at 64 KiB (REQ-P23-1). Commands that
//! resolve to shell interpreters (`bash`, `sh`, `zsh`, etc.) trigger an explicit
//! warning in the permission prompt.
//!
//! # Terminal lifecycle
//!
//! ACP requires the terminal to remain alive until after the `tool_call_update`
//! notification containing `ToolCallContent::Terminal(terminal_id)` is emitted.
//! Call [`AcpShellExecutor::release_terminal`] only after that notification is sent.

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use agent_client_protocol as acp;
use schemars::JsonSchema;
use serde::Deserialize;
use tokio::sync::{mpsc, oneshot};
use tokio_util::sync::CancellationToken;
use zeph_tools::{
    ToolCall, ToolError, ToolOutput,
    executor::deserialize_params,
    registry::{InvocationHint, ToolDef},
};

use crate::{error::AcpError, permission::AcpPermissionGate};

const KILL_GRACE_TIMEOUT: Duration = Duration::from_secs(5);

/// Maximum stdin payload size (64 KiB). REQ-P23-1.
const MAX_STDIN_BYTES: usize = 65_536;

/// Bounded stdin channel capacity (back-pressure). MED-02.
const STDIN_CHANNEL_CAPACITY: usize = 16;

/// Stdin rate-limit interval — 100 msg/sec. MED-02.
const STDIN_RATE_INTERVAL: Duration = Duration::from_millis(10);

/// Shell interpreters that require explicit warning in permission prompt. REQ-P23-5.
const SHELL_INTERPRETERS: &[&str] = &["bash", "sh", "zsh", "fish", "dash"];

/// Transparent prefixes that wrap another command without changing its semantics.
const TRANSPARENT_PREFIXES: &[&str] = &["env", "command", "exec", "nice", "nohup", "time"];

/// Extract the effective command binary name from a shell command string.
///
/// Iteratively skips transparent prefixes (`env`, `command`, `exec`, etc.) and
/// env-var assignments (`FOO=bar`) to reach the real binary. Falls back to `"bash"`
/// if the command is empty.
fn extract_command_binary(command: &str) -> &str {
    // Split into tokens and skip leading env-var assignments and transparent prefixes.
    let mut tokens = command.split_whitespace().peekable();
    loop {
        match tokens.peek() {
            None => return "bash",
            Some(tok) => {
                // Skip env-var assignments.
                if tok.contains('=') {
                    tokens.next();
                    continue;
                }
                // Skip transparent prefix commands.
                let base = tok.rsplit('/').next().unwrap_or(tok);
                if TRANSPARENT_PREFIXES.contains(&base) {
                    tokens.next();
                    continue;
                }
                // First non-prefix, non-assignment token is the binary.
                let binary = tok.rsplit('/').next().unwrap_or(tok);
                return binary;
            }
        }
    }
}

struct ShellResult {
    output: String,
    exit_code: Option<u32>,
    terminal_id: String,
}

struct TerminalRequest {
    session_id: acp::schema::SessionId,
    command: String,
    args: Vec<String>,
    cwd: Option<PathBuf>,
    timeout: Duration,
    reply: oneshot::Sender<Result<ShellResult, AcpError>>,
    /// When `Some`, intermediate terminal output chunks are sent as `ToolCallUpdate`
    /// notifications on this channel so the IDE can stream output live.
    /// The `tool_call_id` is the ACP tool call ID to update.
    stream_tx: Option<(mpsc::Sender<acp::schema::SessionNotification>, String)>,
}

struct TerminalReleaseRequest {
    session_id: acp::schema::SessionId,
    terminal_id: String,
}

struct StdinWriteRequest {
    session_id: acp::schema::SessionId,
    terminal_id: acp::schema::TerminalId,
    data: Vec<u8>,
    reply: oneshot::Sender<Result<(), AcpError>>,
}

enum TerminalMessage {
    Execute(TerminalRequest),
    Release(TerminalReleaseRequest),
    WriteStdin(StdinWriteRequest),
}

/// IDE-proxied shell executor.
///
/// Routes `bash` tool calls to the IDE terminal via ACP `terminal/*` methods.
/// Only constructed when the IDE advertises `terminal` capability.
#[derive(Clone)]
pub struct AcpShellExecutor {
    session_id: acp::schema::SessionId,
    request_tx: mpsc::UnboundedSender<TerminalMessage>,
    permission_gate: Option<AcpPermissionGate>,
    timeout: Duration,
}

impl AcpShellExecutor {
    /// Create the executor and its background handler future.
    ///
    /// Spawn the returned future with `tokio::spawn`; it drives terminal
    /// create/execute/release requests forwarded from the `bash` and
    /// `bash_stdin` tools.
    pub fn new(
        conn: Arc<acp::ConnectionTo<acp::Client>>,
        session_id: acp::schema::SessionId,
        permission_gate: Option<AcpPermissionGate>,
        timeout_secs: u64,
    ) -> (Self, impl std::future::Future<Output = ()>) {
        Self::with_timeout(
            conn,
            session_id,
            permission_gate,
            Duration::from_secs(timeout_secs),
        )
    }

    /// Create the executor with a configurable command timeout.
    pub fn with_timeout(
        conn: Arc<acp::ConnectionTo<acp::Client>>,
        session_id: acp::schema::SessionId,
        permission_gate: Option<AcpPermissionGate>,
        timeout: Duration,
    ) -> (Self, impl std::future::Future<Output = ()>) {
        let (tx, rx) = mpsc::unbounded_channel::<TerminalMessage>();
        let handler = async move { run_terminal_handler(conn, rx).await };
        (
            Self {
                session_id,
                request_tx: tx,
                permission_gate,
                timeout,
            },
            handler,
        )
    }

    /// Release a terminal by ID after the `tool_call_update` notification has been sent.
    ///
    /// This must be called after the ACP `tool_call_update` containing
    /// `ToolCallContent::Terminal(terminal_id)` is emitted so that the IDE can
    /// still display the terminal output when it processes the notification.
    pub fn release_terminal(&self, terminal_id: String) {
        self.request_tx
            .send(TerminalMessage::Release(TerminalReleaseRequest {
                session_id: self.session_id.clone(),
                terminal_id,
            }))
            .ok();
    }

    async fn handle_bash_stdin(&self, call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
        // REQ-P23-2: blocked if no permission gate
        let gate = self
            .permission_gate
            .as_ref()
            .ok_or_else(|| ToolError::Blocked {
                command: "bash_stdin: permission gate required".into(),
            })?;

        let params: BashStdinParams = deserialize_params(&call.params)?;

        if params.data.len() > MAX_STDIN_BYTES {
            return Err(ToolError::InvalidParams {
                message: AcpError::StdinTooLarge {
                    size: params.data.len(),
                }
                .to_string(),
            });
        }
        let data = params.data.as_bytes().to_vec();

        // REQ-P23-5: warn when writing to a shell interpreter terminal.
        // Terminal IDs are opaque strings, but common practice is to include
        // the command name. We always request permission explicitly for stdin writes.
        let is_shell = SHELL_INTERPRETERS
            .iter()
            .any(|s| params.terminal_id.contains(s));
        let title = if is_shell {
            "bash_stdin [WARNING: stdin to shell interpreter — data will be executed as commands]"
                .to_string()
        } else {
            "bash_stdin".to_owned()
        };
        let fields = acp::schema::ToolCallUpdateFields::new()
            .title(title)
            .raw_input(serde_json::json!({
                "terminal_id": params.terminal_id,
                "data_length": params.data.len(),
            }));
        let tool_call = acp::schema::ToolCallUpdate::new("bash_stdin".to_owned(), fields);
        let allowed = gate
            .check_permission(self.session_id.clone(), tool_call)
            .await
            .map_err(|e| ToolError::InvalidParams {
                message: e.to_string(),
            })?;
        if !allowed {
            return Err(ToolError::Blocked {
                command: "bash_stdin: permission denied".into(),
            });
        }

        let terminal_id: acp::schema::TerminalId = params.terminal_id.clone().into();
        let (reply_tx, reply_rx) = oneshot::channel();
        self.request_tx
            .send(TerminalMessage::WriteStdin(StdinWriteRequest {
                session_id: self.session_id.clone(),
                terminal_id,
                data,
                reply: reply_tx,
            }))
            .map_err(|_| ToolError::InvalidParams {
                message: "terminal handler closed".into(),
            })?;
        reply_rx
            .await
            .map_err(|_| ToolError::InvalidParams {
                message: "terminal handler closed".into(),
            })?
            .map_err(|e| ToolError::InvalidParams {
                message: e.to_string(),
            })?;

        Ok(Some(ToolOutput {
            tool_name: zeph_tools::ToolName::new("bash_stdin"),
            summary: format!(
                "wrote {} bytes to stdin of {}",
                params.data.len(),
                params.terminal_id
            ),
            blocks_executed: 1,
            filter_stats: None,
            diff: None,
            streamed: false,
            terminal_id: Some(params.terminal_id),
            locations: None,
            raw_response: None,
            claim_source: Some(zeph_tools::ClaimSource::Shell),
        }))
    }

    async fn execute_shell(
        &self,
        command: String,
        args: Vec<String>,
        cwd: Option<PathBuf>,
        stream_tx: Option<(mpsc::Sender<acp::schema::SessionNotification>, String)>,
    ) -> Result<ShellResult, AcpError> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.request_tx
            .send(TerminalMessage::Execute(TerminalRequest {
                session_id: self.session_id.clone(),
                command,
                args,
                cwd,
                timeout: self.timeout,
                reply: reply_tx,
                stream_tx,
            }))
            .map_err(|_| AcpError::ChannelClosed)?;
        reply_rx.await.map_err(|_| AcpError::ChannelClosed)?
    }
}

#[derive(Deserialize, JsonSchema)]
struct BashParams {
    command: String,
    #[serde(default)]
    args: Vec<String>,
    #[serde(default)]
    cwd: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
struct BashStdinParams {
    terminal_id: String,
    data: String,
}

impl zeph_tools::ToolExecutor for AcpShellExecutor {
    async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
        Ok(None)
    }

    fn tool_definitions(&self) -> Vec<ToolDef> {
        let mut defs = vec![ToolDef {
            id: "bash".into(),
            description: "Execute a shell command in the IDE terminal.\n\nParameters: command (string, required) - shell command to run\nReturns: stdout/stderr combined with exit code\nErrors: Timeout; permission denied by IDE; command blocked by policy\nExample: {\"command\": \"cargo build\"}".into(),
            schema: schemars::schema_for!(BashParams),
            invocation: InvocationHint::ToolCall,
            output_schema: None,
        }];
        // REQ-P23-2: bash_stdin only available when a permission gate is present.
        if self.permission_gate.is_some() {
            defs.push(ToolDef {
                id: "bash_stdin".into(),
                description: "Write data to stdin of a running terminal process.\n\nParameters: terminal_id (string, required) - terminal to write to; data (string, required) - stdin data\nReturns: confirmation\nErrors: terminal not found; terminal process exited\nExample: {\"terminal_id\": \"term-1\", \"data\": \"yes\\n\"}".into(),
                schema: schemars::schema_for!(BashStdinParams),
                invocation: InvocationHint::ToolCall,
                output_schema: None,
            });
        }
        defs
    }

    async fn execute_tool_call(&self, call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
        if call.tool_id == "bash_stdin" {
            return self.handle_bash_stdin(call).await;
        }
        if call.tool_id != "bash" {
            return Ok(None);
        }

        let params: BashParams = deserialize_params(&call.params)?;
        let cwd = params.cwd.map(PathBuf::from);

        let blocklist: Vec<String> = zeph_tools::DEFAULT_BLOCKED_COMMANDS
            .iter()
            .map(|s| (*s).to_owned())
            .collect();

        // Blocklist check — reject dangerous commands before hitting the permission gate.
        if let Some(pattern) = zeph_tools::check_blocklist(&params.command, &blocklist) {
            return Err(ToolError::Blocked { command: pattern });
        }
        // Also check args when the command is a shell interpreter (e.g. bash -c "rm -rf /").
        // This prevents args-field bypass: { command: "bash", args: ["-c", "blocked cmd"] }.
        if let Some(script) = zeph_tools::effective_shell_command(&params.command, &params.args)
            && let Some(pattern) = zeph_tools::check_blocklist(script, &blocklist)
        {
            return Err(ToolError::Blocked { command: pattern });
        }

        if self.permission_gate.is_none() {
            tracing::warn!(
                "AcpShellExecutor has no permission gate — only blocklist applies. \
                 Do not use in production without a permission gate."
            );
        }

        if let Some(gate) = &self.permission_gate {
            // Use the command binary as the cache key, not the tool_id ("bash").
            // This makes "Allow always" apply per binary (git, cargo, etc.).
            let cmd_binary = extract_command_binary(&params.command);
            let fields = acp::schema::ToolCallUpdateFields::new()
                .title(cmd_binary.to_owned())
                .raw_input(serde_json::json!({ "command": params.command }));
            let tool_call = acp::schema::ToolCallUpdate::new(cmd_binary.to_owned(), fields);
            let allowed = gate
                .check_permission(self.session_id.clone(), tool_call)
                .await
                .map_err(|e| ToolError::InvalidParams {
                    message: e.to_string(),
                })?;
            if !allowed {
                return Err(ToolError::Blocked {
                    command: params.command,
                });
            }
        }

        let result = self
            .execute_shell(params.command, params.args, cwd, None)
            .await
            .map_err(|e| ToolError::InvalidParams {
                message: e.to_string(),
            })?;

        let is_error = !matches!(result.exit_code, Some(0) | None);
        let summary = if is_error {
            format!(
                "[exit {}]\n{}",
                result.exit_code.unwrap_or(1),
                result.output
            )
        } else {
            result.output.clone()
        };
        let raw_response = Some(serde_json::json!({
            "stdout": result.output,
            "stderr": "",
            "interrupted": false,
            "isImage": false,
            "noOutputExpected": false
        }));

        Ok(Some(ToolOutput {
            tool_name: zeph_tools::ToolName::new("bash"),
            summary,
            blocks_executed: 1,
            filter_stats: None,
            diff: None,
            streamed: false,
            terminal_id: Some(result.terminal_id),
            locations: None,
            raw_response,
            claim_source: Some(zeph_tools::ClaimSource::Shell),
        }))
    }
}

async fn forward_stdin_via_ext(
    conn: &Arc<acp::ConnectionTo<acp::Client>>,
    session_id: &acp::schema::SessionId,
    terminal_id: &acp::schema::TerminalId,
    data: Vec<u8>,
) -> Result<(), AcpError> {
    use base64::Engine as _;
    let encoded = base64::engine::general_purpose::STANDARD.encode(&data);
    let params_json = serde_json::json!({
        "session_id": session_id.to_string(),
        "terminal_id": terminal_id.to_string(),
        "data": encoded,
    });
    let req = acp::UntypedMessage::new("terminal/write_stdin", params_json)
        .map_err(|e| AcpError::ClientError(e.to_string()))?;
    conn.send_request(req)
        .block_task()
        .await
        .map(|_| ())
        .map_err(|e| AcpError::ClientError(e.to_string()))
}

/// Background pump: drains bounded stdin channel at ≤100 msg/sec (MED-02).
///
/// REQ-P23-3: on any error from `ext_method`, cancels the token and exits.
async fn run_stdin_pump(
    conn: Arc<acp::ConnectionTo<acp::Client>>,
    session_id: acp::schema::SessionId,
    terminal_id: acp::schema::TerminalId,
    mut data_rx: mpsc::Receiver<Vec<u8>>,
    cancel: CancellationToken,
) {
    let mut interval = tokio::time::interval(STDIN_RATE_INTERVAL);
    interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
    loop {
        let data = tokio::select! {
            () = cancel.cancelled() => break,
            msg = data_rx.recv() => match msg {
                Some(d) => d,
                None => break,
            },
        };
        // Rate-limit: wait for tick before forwarding. MED-02.
        tokio::select! {
            () = cancel.cancelled() => break,
            _ = interval.tick() => {}
        }
        if let Err(e) = forward_stdin_via_ext(&conn, &session_id, &terminal_id, data).await {
            // REQ-P23-3: no panics, log and cancel.
            tracing::warn!(%terminal_id, error = %e, "stdin pump error — cancelling");
            cancel.cancel();
            break;
        }
    }
}

async fn run_terminal_handler(
    conn: Arc<acp::ConnectionTo<acp::Client>>,
    mut rx: mpsc::UnboundedReceiver<TerminalMessage>,
) {
    // Maps terminal_id -> (bounded stdin sender, CancellationToken). MED-02, REQ-P23-4.
    let mut stdin_pumps: std::collections::HashMap<
        String,
        (mpsc::Sender<Vec<u8>>, CancellationToken),
    > = std::collections::HashMap::new();

    while let Some(msg) = rx.recv().await {
        match msg {
            TerminalMessage::Execute(req) => {
                let result = execute_in_terminal(
                    &conn,
                    req.session_id,
                    req.command,
                    req.args,
                    req.cwd,
                    req.timeout,
                    req.stream_tx,
                )
                .await;
                // Cancel stdin pump when terminal completes. REQ-P23-4.
                if let Ok(ref shell_result) = result
                    && let Some((_, token)) = stdin_pumps.remove(&shell_result.terminal_id)
                {
                    token.cancel();
                }
                req.reply.send(result).ok();
            }
            TerminalMessage::Release(req) => {
                // Cancel stdin pump on release. REQ-P23-4.
                if let Some((_, token)) = stdin_pumps.remove(&req.terminal_id) {
                    token.cancel();
                }
                let tid = req.terminal_id.clone();
                let release_req =
                    acp::schema::ReleaseTerminalRequest::new(req.session_id, req.terminal_id);
                if let Err(e) = conn.send_request(release_req).block_task().await {
                    tracing::warn!(
                        terminal_id = %tid,
                        error = %e,
                        "failed to release terminal"
                    );
                }
            }
            TerminalMessage::WriteStdin(req) => {
                let tid_str = req.terminal_id.to_string();

                // Lazily start a bounded pump task per terminal. MED-02.
                let (data_tx, cancel) = stdin_pumps.entry(tid_str).or_insert_with(|| {
                    let (tx, rx) = mpsc::channel::<Vec<u8>>(STDIN_CHANNEL_CAPACITY);
                    let token = CancellationToken::new();
                    tokio::spawn(run_stdin_pump(
                        conn.clone(),
                        req.session_id.clone(),
                        req.terminal_id.clone(),
                        rx,
                        token.clone(),
                    ));
                    (tx, token)
                });

                let result = if cancel.is_cancelled() {
                    Err(AcpError::BrokenPipe)
                } else {
                    // Bounded send — returns Err if channel is full (back-pressure).
                    data_tx.try_send(req.data).map_err(|_| AcpError::BrokenPipe)
                };

                req.reply.send(result).ok();
            }
        }
    }
}

/// Polling interval for terminal output streaming.
const STREAM_POLL_INTERVAL: Duration = Duration::from_millis(200);

/// Kill a terminal, then wait up to [`KILL_GRACE_TIMEOUT`] for it to exit.
async fn kill_terminal(
    conn: &Arc<acp::ConnectionTo<acp::Client>>,
    session_id: &acp::schema::SessionId,
    terminal_id: &acp::schema::TerminalId,
) -> Result<(), AcpError> {
    tracing::warn!(%terminal_id, "terminal command timed out — sending kill");
    let kill_req = acp::schema::KillTerminalRequest::new(session_id.clone(), terminal_id.clone());
    conn.send_request(kill_req)
        .block_task()
        .await
        .map_err(|e| AcpError::ClientError(e.to_string()))?;
    let wait_again =
        acp::schema::WaitForTerminalExitRequest::new(session_id.clone(), terminal_id.clone());
    let _ = tokio::time::timeout(
        KILL_GRACE_TIMEOUT,
        conn.send_request(wait_again).block_task(),
    )
    .await;
    Ok(())
}

/// Stream terminal output chunks to `notify_tx` while polling for process exit.
///
/// Returns the exit code once the process terminates or the timeout is reached.
async fn stream_until_exit(
    conn: &Arc<acp::ConnectionTo<acp::Client>>,
    session_id: &acp::schema::SessionId,
    terminal_id: &acp::schema::TerminalId,
    timeout: Duration,
    notify_tx: &mpsc::Sender<acp::schema::SessionNotification>,
    tool_call_id: &str,
) -> Result<Option<u32>, AcpError> {
    let wait_req =
        acp::schema::WaitForTerminalExitRequest::new(session_id.clone(), terminal_id.clone());
    let exit_future = conn.send_request(wait_req).block_task();
    tokio::pin!(exit_future);
    let deadline = tokio::time::Instant::now() + timeout;
    let mut last_output_len = 0usize;

    loop {
        tokio::select! {
            result = &mut exit_future => {
                return match result {
                    Ok(resp) => Ok(resp.exit_status.exit_code),
                    Err(e) => Err(AcpError::ClientError(e.to_string())),
                };
            }
            () = tokio::time::sleep(STREAM_POLL_INTERVAL) => {
                if tokio::time::Instant::now() >= deadline {
                    kill_terminal(conn, session_id, terminal_id).await?;
                    return Ok(Some(124u32));
                }
                let output_req =
                    acp::schema::TerminalOutputRequest::new(session_id.clone(), terminal_id.clone());
                if let Ok(resp) = conn.send_request(output_req).block_task().await {
                    let new_data = resp.output.get(last_output_len..).unwrap_or("");
                    if !new_data.is_empty() {
                        last_output_len = resp.output.len();
                        let mut meta = serde_json::Map::new();
                        meta.insert(
                            "terminal_output".to_owned(),
                            serde_json::json!({
                                "terminal_id": terminal_id.to_string(),
                                "data": new_data,
                            }),
                        );
                        let update = acp::schema::ToolCallUpdate::new(
                            tool_call_id.to_owned(),
                            acp::schema::ToolCallUpdateFields::new(),
                        )
                        .meta(meta);
                        let notif = acp::schema::SessionNotification::new(
                            session_id.clone(),
                            acp::schema::SessionUpdate::ToolCallUpdate(update),
                        );
                        let _ = notify_tx.try_send(notif);
                    }
                }
            }
        }
    }
}

async fn execute_in_terminal(
    conn: &Arc<acp::ConnectionTo<acp::Client>>,
    session_id: acp::schema::SessionId,
    command: String,
    args: Vec<String>,
    cwd: Option<PathBuf>,
    timeout: Duration,
    stream_tx: Option<(mpsc::Sender<acp::schema::SessionNotification>, String)>,
) -> Result<ShellResult, AcpError> {
    // 1. Create terminal.
    let create_req = acp::schema::CreateTerminalRequest::new(session_id.clone(), command)
        .args(args)
        .cwd(cwd);
    let create_resp = conn
        .send_request(create_req)
        .block_task()
        .await
        .map_err(|e| AcpError::ClientError(e.to_string()))?;
    let terminal_id = create_resp.terminal_id;

    // 2. Wait for exit with timeout; kill if exceeded.
    let exit_code = if let Some((ref notify_tx, ref tool_call_id)) = stream_tx {
        stream_until_exit(
            conn,
            &session_id,
            &terminal_id,
            timeout,
            notify_tx,
            tool_call_id,
        )
        .await?
    } else {
        let wait_req =
            acp::schema::WaitForTerminalExitRequest::new(session_id.clone(), terminal_id.clone());
        match tokio::time::timeout(timeout, conn.send_request(wait_req).block_task()).await {
            Ok(Ok(resp)) => resp.exit_status.exit_code,
            Ok(Err(e)) => return Err(AcpError::ClientError(e.to_string())),
            Err(_) => {
                kill_terminal(conn, &session_id, &terminal_id).await?;
                Some(124u32)
            }
        }
    };

    // 3. Get final output. Terminal is NOT released here — the caller releases it
    //    after the ACP `tool_call_update` notification carrying `ToolCallContent::Terminal`
    //    has been sent, so the IDE can still display the terminal output.
    let output_req =
        acp::schema::TerminalOutputRequest::new(session_id.clone(), terminal_id.clone());
    let output_resp = conn
        .send_request(output_req)
        .block_task()
        .await
        .map_err(|e| AcpError::ClientError(e.to_string()))?;

    // 4. Emit terminal_exit notification if streaming is active.
    if let Some((ref notify_tx, ref tool_call_id)) = stream_tx {
        let mut meta = serde_json::Map::new();
        meta.insert(
            "terminal_exit".to_owned(),
            serde_json::json!({ "terminal_id": terminal_id.to_string(), "exit_code": exit_code }),
        );
        let update = acp::schema::ToolCallUpdate::new(
            tool_call_id.clone(),
            acp::schema::ToolCallUpdateFields::new(),
        )
        .meta(meta);
        let notif = acp::schema::SessionNotification::new(
            session_id.clone(),
            acp::schema::SessionUpdate::ToolCallUpdate(update),
        );
        let _ = notify_tx.try_send(notif);
    }

    // Terminal release is handled by AcpShellExecutor::release_terminal via TerminalMessage::Release.
    Ok(ShellResult {
        output: output_resp.output,
        exit_code,
        terminal_id: terminal_id.to_string(),
    })
}

// Tests disabled pending ACP 0.11 test infrastructure update (issue #3267 PR3)
#[cfg(any())] // ACP 0.10 tests disabled — pending PR3 test infrastructure
mod tests {
    use std::rc::Rc;

    use zeph_tools::ToolExecutor as _;

    use super::*;

    struct FakeTerminalClient;

    #[async_trait::async_trait(?Send)]
    impl acp::Client for FakeTerminalClient {
        async fn request_permission(
            &self,
            _args: acp::schema::RequestPermissionRequest,
        ) -> acp::Result<acp::RequestPermissionResponse> {
            Err(acp::Error::method_not_found())
        }

        async fn create_terminal(
            &self,
            _args: acp::schema::CreateTerminalRequest,
        ) -> acp::Result<acp::schema::CreateTerminalResponse> {
            Ok(acp::schema::CreateTerminalResponse::new("term-1"))
        }

        async fn wait_for_terminal_exit(
            &self,
            _args: acp::schema::WaitForTerminalExitRequest,
        ) -> acp::Result<acp::WaitForTerminalExitResponse> {
            Ok(acp::WaitForTerminalExitResponse::new(
                acp::TerminalExitStatus::new().exit_code(0u32),
            ))
        }

        async fn terminal_output(
            &self,
            _args: acp::schema::TerminalOutputRequest,
        ) -> acp::Result<acp::TerminalOutputResponse> {
            Ok(acp::TerminalOutputResponse::new("hello\n", false))
        }

        async fn release_terminal(
            &self,
            _args: acp::schema::ReleaseTerminalRequest,
        ) -> acp::Result<acp::ReleaseTerminalResponse> {
            Ok(acp::ReleaseTerminalResponse::new())
        }

        async fn kill_terminal(
            &self,
            _args: acp::schema::KillTerminalRequest,
        ) -> acp::Result<acp::KillTerminalResponse> {
            Ok(acp::KillTerminalResponse::new())
        }

        async fn session_notification(
            &self,
            _args: acp::schema::SessionNotification,
        ) -> acp::Result<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn bash_tool_call_returns_output() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let conn = Rc::new(FakeTerminalClient);
                let sid = acp::schema::SessionId::new("s1");
                let (exec, handler) = AcpShellExecutor::new(conn, sid, None, 120);
                tokio::task::spawn_local(handler);

                let mut params = serde_json::Map::new();
                params.insert("command".to_owned(), serde_json::json!("echo"));
                params.insert("args".to_owned(), serde_json::json!(["hello"]));
                let call = ToolCall {
                    tool_id: zeph_tools::ToolName::new("bash"),
                    params,
                    caller_id: None,
                };

                let result = exec.execute_tool_call(&call).await.unwrap().unwrap();
                assert_eq!(result.summary, "hello\n");
                assert_eq!(result.tool_name, "bash");
            })
            .await;
    }

    #[tokio::test]
    async fn unknown_tool_returns_none() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let conn = Rc::new(FakeTerminalClient);
                let sid = acp::schema::SessionId::new("s1");
                let (exec, handler) = AcpShellExecutor::new(conn, sid, None, 120);
                tokio::task::spawn_local(handler);

                let call = ToolCall {
                    tool_id: zeph_tools::ToolName::new("unknown"),
                    params: serde_json::Map::new(),
                    caller_id: None,
                };
                let result = exec.execute_tool_call(&call).await.unwrap();
                assert!(result.is_none());
            })
            .await;
    }

    #[test]
    fn tool_definitions_registers_bash() {
        let (tx, _rx) = mpsc::unbounded_channel::<TerminalMessage>();
        let exec = AcpShellExecutor {
            session_id: acp::schema::SessionId::new("s"),
            request_tx: tx,
            permission_gate: None,
            timeout: Duration::from_mins(2),
        };
        let defs = exec.tool_definitions();
        assert_eq!(defs.len(), 1);
        assert_eq!(defs[0].id, "bash");
    }

    struct NonZeroExitClient;

    #[async_trait::async_trait(?Send)]
    impl acp::Client for NonZeroExitClient {
        async fn request_permission(
            &self,
            _args: acp::schema::RequestPermissionRequest,
        ) -> acp::Result<acp::RequestPermissionResponse> {
            Err(acp::Error::method_not_found())
        }

        async fn create_terminal(
            &self,
            _args: acp::schema::CreateTerminalRequest,
        ) -> acp::Result<acp::schema::CreateTerminalResponse> {
            Ok(acp::schema::CreateTerminalResponse::new("term-fail"))
        }

        async fn wait_for_terminal_exit(
            &self,
            _args: acp::schema::WaitForTerminalExitRequest,
        ) -> acp::Result<acp::WaitForTerminalExitResponse> {
            Ok(acp::WaitForTerminalExitResponse::new(
                acp::TerminalExitStatus::new().exit_code(1u32),
            ))
        }

        async fn terminal_output(
            &self,
            _args: acp::schema::TerminalOutputRequest,
        ) -> acp::Result<acp::TerminalOutputResponse> {
            Ok(acp::TerminalOutputResponse::new("error output\n", false))
        }

        async fn release_terminal(
            &self,
            _args: acp::schema::ReleaseTerminalRequest,
        ) -> acp::Result<acp::ReleaseTerminalResponse> {
            Ok(acp::ReleaseTerminalResponse::new())
        }

        async fn kill_terminal(
            &self,
            _args: acp::schema::KillTerminalRequest,
        ) -> acp::Result<acp::KillTerminalResponse> {
            Ok(acp::KillTerminalResponse::new())
        }

        async fn session_notification(
            &self,
            _args: acp::schema::SessionNotification,
        ) -> acp::Result<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn nonzero_exit_code_prefixes_output() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let conn = Rc::new(NonZeroExitClient);
                let sid = acp::schema::SessionId::new("s1");
                let (exec, handler) = AcpShellExecutor::new(conn, sid, None, 120);
                tokio::task::spawn_local(handler);

                let mut params = serde_json::Map::new();
                params.insert("command".to_owned(), serde_json::json!("false"));
                let call = ToolCall {
                    tool_id: zeph_tools::ToolName::new("bash"),
                    params,
                    caller_id: None,
                };

                let result = exec.execute_tool_call(&call).await.unwrap().unwrap();
                assert!(
                    result.summary.starts_with("[exit 1]"),
                    "got: {}",
                    result.summary
                );
                assert!(result.summary.contains("error output\n"));
            })
            .await;
    }

    struct RejectPermissionClient;

    #[async_trait::async_trait(?Send)]
    impl acp::Client for RejectPermissionClient {
        async fn request_permission(
            &self,
            _args: acp::schema::RequestPermissionRequest,
        ) -> acp::Result<acp::RequestPermissionResponse> {
            Ok(acp::RequestPermissionResponse::new(
                acp::schema::RequestPermissionOutcome::Selected(
                    acp::SelectedPermissionOutcome::new("reject_once"),
                ),
            ))
        }

        async fn create_terminal(
            &self,
            _args: acp::schema::CreateTerminalRequest,
        ) -> acp::Result<acp::schema::CreateTerminalResponse> {
            panic!("should not be called when permission denied")
        }

        async fn wait_for_terminal_exit(
            &self,
            _args: acp::schema::WaitForTerminalExitRequest,
        ) -> acp::Result<acp::WaitForTerminalExitResponse> {
            panic!("should not be called when permission denied")
        }

        async fn terminal_output(
            &self,
            _args: acp::schema::TerminalOutputRequest,
        ) -> acp::Result<acp::TerminalOutputResponse> {
            panic!("should not be called when permission denied")
        }

        async fn release_terminal(
            &self,
            _args: acp::schema::ReleaseTerminalRequest,
        ) -> acp::Result<acp::ReleaseTerminalResponse> {
            panic!("should not be called when permission denied")
        }

        async fn kill_terminal(
            &self,
            _args: acp::schema::KillTerminalRequest,
        ) -> acp::Result<acp::KillTerminalResponse> {
            panic!("should not be called when permission denied")
        }

        async fn session_notification(
            &self,
            _args: acp::schema::SessionNotification,
        ) -> acp::Result<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn permission_denied_returns_blocked_error() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let perm_conn = Rc::new(RejectPermissionClient);
                let sid = acp::schema::SessionId::new("s1");
                let tmp_dir = tempfile::tempdir().unwrap();
                let perm_file = tmp_dir.path().join("perms.toml");
                let (gate, perm_handler) = AcpPermissionGate::new(perm_conn, Some(perm_file));
                tokio::task::spawn_local(perm_handler);

                let term_conn = Rc::new(FakeTerminalClient);
                let (exec, term_handler) = AcpShellExecutor::new(term_conn, sid, Some(gate), 120);
                tokio::task::spawn_local(term_handler);

                let mut params = serde_json::Map::new();
                params.insert("command".to_owned(), serde_json::json!("rm"));
                params.insert("args".to_owned(), serde_json::json!(["-rf", "/important"]));
                let call = ToolCall {
                    tool_id: zeph_tools::ToolName::new("bash"),
                    params,
                    caller_id: None,
                };

                let err = exec.execute_tool_call(&call).await.unwrap_err();
                assert!(matches!(err, ToolError::Blocked { .. }));
            })
            .await;
    }

    #[tokio::test]
    async fn streaming_mode_emits_terminal_exit_notification() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let conn = Rc::new(FakeTerminalClient);
                let sid = acp::schema::SessionId::new("s1");
                let (tx, rx) = mpsc::unbounded_channel::<TerminalMessage>();
                let handler = async move { run_terminal_handler(conn, rx).await };
                tokio::task::spawn_local(handler);

                let (stream_tx, mut stream_rx) = mpsc::channel(8);
                let (reply_tx, reply_rx) = oneshot::channel();
                tx.send(TerminalMessage::Execute(TerminalRequest {
                    session_id: sid,
                    command: "echo".to_owned(),
                    args: vec!["hi".to_owned()],
                    cwd: None,
                    timeout: Duration::from_secs(5),
                    reply: reply_tx,
                    stream_tx: Some((stream_tx, "tool-1".to_owned())),
                }))
                .unwrap();

                let result = reply_rx.await.unwrap().unwrap();
                assert_eq!(result.output, "hello\n");

                // At least a terminal_exit notification must arrive.
                let mut got_exit = false;
                while let Ok(notif) = stream_rx.try_recv() {
                    if let acp::schema::SessionUpdate::ToolCallUpdate(update) = notif.update
                        && let Some(meta) = update.meta
                        && meta.contains_key("terminal_exit")
                    {
                        got_exit = true;
                    }
                }
                assert!(got_exit, "expected terminal_exit notification");
            })
            .await;
    }

    #[test]
    fn extract_command_binary_bare() {
        assert_eq!(extract_command_binary("git status"), "git");
        assert_eq!(extract_command_binary("cargo build --release"), "cargo");
        assert_eq!(extract_command_binary("  cat file.txt  "), "cat");
    }

    #[test]
    fn extract_command_binary_env_prefix() {
        assert_eq!(extract_command_binary("env FOO=bar git status"), "git");
        assert_eq!(extract_command_binary("command git push"), "git");
        assert_eq!(extract_command_binary("exec cargo test"), "cargo");
    }

    #[test]
    fn extract_command_binary_env_var_assignments() {
        assert_eq!(extract_command_binary("FOO=bar BAZ=qux git log"), "git");
    }

    #[test]
    fn extract_command_binary_path() {
        assert_eq!(extract_command_binary("/usr/bin/git status"), "git");
        assert_eq!(
            extract_command_binary("/usr/local/bin/cargo build"),
            "cargo"
        );
    }

    #[test]
    fn extract_command_binary_empty_fallback() {
        assert_eq!(extract_command_binary(""), "bash");
        assert_eq!(extract_command_binary("   "), "bash");
    }

    #[tokio::test]
    async fn blocklist_blocked_before_permission_gate() {
        // rm -rf / must be blocked before the permission gate is consulted.
        // FakeTerminalClient panics if create_terminal is called — so if
        // we reach the terminal, the test fails.
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let conn = Rc::new(FakeTerminalClient);
                let sid = acp::schema::SessionId::new("s1");
                // No permission gate — blocklist runs independently.
                let (exec, handler) = AcpShellExecutor::new(conn, sid, None, 120);
                tokio::task::spawn_local(handler);

                let mut params = serde_json::Map::new();
                params.insert("command".to_owned(), serde_json::json!("rm -rf /"));
                let call = ToolCall {
                    tool_id: zeph_tools::ToolName::new("bash"),
                    params,
                    caller_id: None,
                };

                let err = exec.execute_tool_call(&call).await.unwrap_err();
                assert!(matches!(err, ToolError::Blocked { .. }));
            })
            .await;
    }

    #[tokio::test]
    async fn blocklist_sudo_blocked() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let conn = Rc::new(FakeTerminalClient);
                let sid = acp::schema::SessionId::new("s1");
                let (exec, handler) = AcpShellExecutor::new(conn, sid, None, 120);
                tokio::task::spawn_local(handler);

                let mut params = serde_json::Map::new();
                params.insert(
                    "command".to_owned(),
                    serde_json::json!("sudo apt install vim"),
                );
                let call = ToolCall {
                    tool_id: zeph_tools::ToolName::new("bash"),
                    params,
                    caller_id: None,
                };

                let err = exec.execute_tool_call(&call).await.unwrap_err();
                assert!(matches!(err, ToolError::Blocked { .. }));
            })
            .await;
    }

    #[tokio::test]
    async fn args_field_bypass_blocked_for_shell_interpreter() {
        // SEC-ACP-C2: { command: "bash", args: ["-c", "rm -rf /"] } must be blocked.
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let conn = Rc::new(FakeTerminalClient);
                let sid = acp::schema::SessionId::new("s1");
                let (exec, handler) = AcpShellExecutor::new(conn, sid, None, 120);
                tokio::task::spawn_local(handler);

                let mut params = serde_json::Map::new();
                params.insert("command".to_owned(), serde_json::json!("bash"));
                params.insert(
                    "args".to_owned(),
                    serde_json::json!(["-c", "sudo rm -rf /"]),
                );
                let call = ToolCall {
                    tool_id: zeph_tools::ToolName::new("bash"),
                    params,
                    caller_id: None,
                };

                let err = exec.execute_tool_call(&call).await.unwrap_err();
                assert!(matches!(err, ToolError::Blocked { .. }));
            })
            .await;
    }

    #[tokio::test]
    async fn args_field_bypass_sh_minus_c_blocked() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let conn = Rc::new(FakeTerminalClient);
                let sid = acp::schema::SessionId::new("s1");
                let (exec, handler) = AcpShellExecutor::new(conn, sid, None, 120);
                tokio::task::spawn_local(handler);

                let mut params = serde_json::Map::new();
                params.insert("command".to_owned(), serde_json::json!("sh"));
                params.insert(
                    "args".to_owned(),
                    serde_json::json!(["-c", "shutdown -h now"]),
                );
                let call = ToolCall {
                    tool_id: zeph_tools::ToolName::new("bash"),
                    params,
                    caller_id: None,
                };

                let err = exec.execute_tool_call(&call).await.unwrap_err();
                assert!(matches!(err, ToolError::Blocked { .. }));
            })
            .await;
    }

    #[test]
    fn extract_command_binary_chained_transparent_prefixes() {
        // SEC-ACP-I1: "env command exec sudo rm" -> "sudo", not "command"
        assert_eq!(
            extract_command_binary("env command exec sudo rm -rf /"),
            "sudo"
        );
        assert_eq!(extract_command_binary("nice nohup time git status"), "git");
    }

    #[test]
    fn extract_command_binary_env_var_then_prefix_then_binary() {
        assert_eq!(extract_command_binary("FOO=bar env BAZ=qux git log"), "git");
    }

    #[tokio::test]
    async fn bash_stdin_blocked_without_permission_gate() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let conn = Rc::new(FakeTerminalClient);
                let sid = acp::schema::SessionId::new("s1");
                let (exec, handler) = AcpShellExecutor::new(conn, sid, None, 120);
                tokio::task::spawn_local(handler);

                let mut params = serde_json::Map::new();
                params.insert("terminal_id".to_owned(), serde_json::json!("term-1"));
                params.insert("data".to_owned(), serde_json::json!("hello\n"));
                let call = ToolCall {
                    tool_id: zeph_tools::ToolName::new("bash_stdin"),
                    params,
                    caller_id: None,
                };
                let err = exec.execute_tool_call(&call).await.unwrap_err();
                assert!(matches!(err, ToolError::Blocked { .. }));
            })
            .await;
    }

    #[test]
    fn bash_stdin_not_in_tool_definitions_without_gate() {
        let (tx, _rx) = mpsc::unbounded_channel::<TerminalMessage>();
        let exec = AcpShellExecutor {
            session_id: acp::schema::SessionId::new("s"),
            request_tx: tx,
            permission_gate: None,
            timeout: Duration::from_mins(2),
        };
        let defs = exec.tool_definitions();
        assert!(!defs.iter().any(|d| d.id == "bash_stdin"));
    }

    #[tokio::test]
    async fn bash_stdin_size_limit_rejected() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let perm_conn = Rc::new(RejectPermissionClient);
                let sid = acp::schema::SessionId::new("s1");
                let tmp_dir = tempfile::tempdir().unwrap();
                let perm_file = tmp_dir.path().join("perms.toml");
                let (gate, perm_handler) = AcpPermissionGate::new(perm_conn, Some(perm_file));
                tokio::task::spawn_local(perm_handler);

                let term_conn = Rc::new(FakeTerminalClient);
                let (exec, term_handler) = AcpShellExecutor::new(term_conn, sid, Some(gate), 120);
                tokio::task::spawn_local(term_handler);

                let oversized = "x".repeat(MAX_STDIN_BYTES + 1);
                let mut params = serde_json::Map::new();
                params.insert("terminal_id".to_owned(), serde_json::json!("term-1"));
                params.insert("data".to_owned(), serde_json::json!(oversized));
                let call = ToolCall {
                    tool_id: zeph_tools::ToolName::new("bash_stdin"),
                    params,
                    caller_id: None,
                };
                let err = exec.execute_tool_call(&call).await.unwrap_err();
                assert!(matches!(err, ToolError::InvalidParams { .. }));
            })
            .await;
    }

    struct AllowPermissionClient;

    #[async_trait::async_trait(?Send)]
    impl acp::Client for AllowPermissionClient {
        async fn request_permission(
            &self,
            _args: acp::schema::RequestPermissionRequest,
        ) -> acp::Result<acp::RequestPermissionResponse> {
            Ok(acp::RequestPermissionResponse::new(
                acp::schema::RequestPermissionOutcome::Selected(
                    acp::SelectedPermissionOutcome::new("allow_once"),
                ),
            ))
        }

        async fn session_notification(
            &self,
            _args: acp::schema::SessionNotification,
        ) -> acp::Result<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn bash_stdin_with_permission_gate_succeeds() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let perm_conn = Rc::new(AllowPermissionClient);
                let sid = acp::schema::SessionId::new("s1");
                let tmp_dir = tempfile::tempdir().unwrap();
                let perm_file = tmp_dir.path().join("perms.toml");
                let (gate, perm_handler) = AcpPermissionGate::new(perm_conn, Some(perm_file));
                tokio::task::spawn_local(perm_handler);

                let term_conn = Rc::new(FakeTerminalClient);
                let (exec, term_handler) = AcpShellExecutor::new(term_conn, sid, Some(gate), 120);
                tokio::task::spawn_local(term_handler);

                let mut params = serde_json::Map::new();
                params.insert("terminal_id".to_owned(), serde_json::json!("term-1"));
                params.insert("data".to_owned(), serde_json::json!("echo hello\n"));
                let call = ToolCall {
                    tool_id: zeph_tools::ToolName::new("bash_stdin"),
                    params,
                    caller_id: None,
                };
                let result = exec.execute_tool_call(&call).await.unwrap().unwrap();
                assert_eq!(result.tool_name, "bash_stdin");
                assert!(result.summary.contains("term-1"));
            })
            .await;
    }

    #[test]
    fn bash_stdin_in_tool_definitions_with_gate() {
        let (tx, _rx) = mpsc::unbounded_channel::<TerminalMessage>();
        let tmp_dir = tempfile::tempdir().unwrap();
        let perm_file = tmp_dir.path().join("perms.toml");
        let perm_conn = Rc::new(AllowPermissionClient);
        let (gate, _handler) = AcpPermissionGate::new(perm_conn, Some(perm_file));
        let exec = AcpShellExecutor {
            session_id: acp::schema::SessionId::new("s"),
            request_tx: tx,
            permission_gate: Some(gate),
            timeout: Duration::from_mins(2),
        };
        let defs = exec.tool_definitions();
        assert!(defs.iter().any(|d| d.id == "bash_stdin"));
        assert!(defs.iter().any(|d| d.id == "bash"));
    }

    #[tokio::test]
    async fn bash_stdin_exactly_64kib_boundary_accepted() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let perm_conn = Rc::new(AllowPermissionClient);
                let sid = acp::schema::SessionId::new("s1");
                let tmp_dir = tempfile::tempdir().unwrap();
                let perm_file = tmp_dir.path().join("perms.toml");
                let (gate, perm_handler) = AcpPermissionGate::new(perm_conn, Some(perm_file));
                tokio::task::spawn_local(perm_handler);

                let term_conn = Rc::new(FakeTerminalClient);
                let (exec, term_handler) = AcpShellExecutor::new(term_conn, sid, Some(gate), 120);
                tokio::task::spawn_local(term_handler);

                // Exactly at the limit must succeed.
                let at_limit = "x".repeat(MAX_STDIN_BYTES);
                let mut params = serde_json::Map::new();
                params.insert("terminal_id".to_owned(), serde_json::json!("term-1"));
                params.insert("data".to_owned(), serde_json::json!(at_limit));
                let call = ToolCall {
                    tool_id: zeph_tools::ToolName::new("bash_stdin"),
                    params,
                    caller_id: None,
                };
                let result = exec.execute_tool_call(&call).await.unwrap().unwrap();
                assert_eq!(result.tool_name, "bash_stdin");
            })
            .await;
    }

    #[tokio::test]
    async fn bash_stdin_broken_pipe_fast_fail() {
        // After the CancellationToken is cancelled, WriteStdin must return BrokenPipe immediately.
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (tx, rx) = mpsc::unbounded_channel::<TerminalMessage>();
                let conn = Rc::new(FakeTerminalClient);
                let handler = async move { run_terminal_handler(conn, rx).await };
                tokio::task::spawn_local(handler);

                let sid = acp::schema::SessionId::new("s1");
                let tid: acp::schema::TerminalId = "term-bp".to_owned().into();

                // First WriteStdin: establishes the pump and cancels via a pre-cancelled token.
                // We simulate a broken pump by sending two WriteStdin messages to the same
                // terminal: the first establishes the pump, then we fill the channel beyond
                // capacity so the next try_send returns Err (BrokenPipe).
                let mut replies = Vec::new();
                for _ in 0..=STDIN_CHANNEL_CAPACITY {
                    let (reply_tx, reply_rx) = oneshot::channel();
                    tx.send(TerminalMessage::WriteStdin(StdinWriteRequest {
                        session_id: sid.clone(),
                        terminal_id: tid.clone(),
                        data: b"x".to_vec(),
                        reply: reply_tx,
                    }))
                    .unwrap();
                    replies.push(reply_rx);
                }
                // Collect results: at least one must be BrokenPipe (channel overflow).
                let mut got_broken_pipe = false;
                for reply_rx in replies {
                    if let Ok(Err(AcpError::BrokenPipe)) = reply_rx.await {
                        got_broken_pipe = true;
                    }
                }
                assert!(
                    got_broken_pipe,
                    "expected at least one BrokenPipe from overflow"
                );
            })
            .await;
    }

    #[tokio::test]
    async fn bash_stdin_pump_cancelled_on_release() {
        // After Release, the pump's CancellationToken must be cancelled.
        // Subsequent WriteStdin to the same terminal_id starts a fresh pump (no persistent state).
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (tx, rx) = mpsc::unbounded_channel::<TerminalMessage>();
                let conn = Rc::new(FakeTerminalClient);
                let handler = async move { run_terminal_handler(conn, rx).await };
                tokio::task::spawn_local(handler);

                let sid = acp::schema::SessionId::new("s1");
                let tid: acp::schema::TerminalId = "term-rel".to_owned().into();

                // Establish a pump by writing stdin.
                let (reply_tx, reply_rx) = oneshot::channel();
                tx.send(TerminalMessage::WriteStdin(StdinWriteRequest {
                    session_id: sid.clone(),
                    terminal_id: tid.clone(),
                    data: b"hello\n".to_vec(),
                    reply: reply_tx,
                }))
                .unwrap();
                reply_rx.await.unwrap().unwrap(); // pump established, write queued

                // Release the terminal — must cancel the pump.
                tx.send(TerminalMessage::Release(TerminalReleaseRequest {
                    session_id: sid.clone(),
                    terminal_id: tid.to_string(),
                }))
                .unwrap();

                // Allow the handler to process the Release.
                tokio::task::yield_now().await;

                // Writing again after release starts a fresh pump — should succeed.
                let (fresh_reply, write_result) = oneshot::channel();
                tx.send(TerminalMessage::WriteStdin(StdinWriteRequest {
                    session_id: sid.clone(),
                    terminal_id: tid.clone(),
                    data: b"after release\n".to_vec(),
                    reply: fresh_reply,
                }))
                .unwrap();
                // Fresh pump: send must succeed (Ok).
                write_result.await.unwrap().unwrap();
            })
            .await;
    }
}