lingshu-tools 0.10.0

Tool registry, ToolHandler trait, and 50+ tool implementations
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
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
//! # process — Background process management
//!
//! WHY process management: Long-running commands (dev servers, watchers,
//! builds) must not block the agent loop. This tool lets the agent spawn
//! processes in the background and poll/kill them later.
//!
//! ```text
//!   run_process("cargo watch") ──→ ProcessTable.register() ──→ proc-1
//!//!                                         ├── PID stored for SIGKILL
//!                                         └── tokio::spawn drains stdout/stderr
//!
//!   get_process_output("proc-1") ──→ ProcessTable.get_output_tail() ──→ buffered log
//!   list_processes               ──→ ProcessTable.list_all()         ──→ [...records]
//!   kill_process("proc-1")       ──→ ProcessTable.kill() + SIGKILL   ──→ Killed
//!   wait_for_process("proc-1")   ──→ poll until exited / timeout     ──→ exit code
//! ```
//!
//! Stdout/stderr are drained by a background tokio task into a ring
//! buffer inside the ProcessRecord, keeping memory bounded even for
//! chatty processes.
//!
//! Shell startup noise (job-control warnings from `sh -lic`) is filtered
//! from the first chunk, matching prior terminal cleanup behavior.
//!
//! The ProcessTable lives on the Agent and is shared via `ToolContext.process_table`.
//!
//! ## Backend routing
//!
//! Local backends use a real host subprocess with live stdout/stderr pipes and
//! stdin injection. Non-local backends (Docker / SSH / Modal / Daytona /
//! Singularity) follow the established remote-background model: launch the
//! command under `nohup sh -lc ...`, redirect output to a sandbox log file,
//! then poll that log and exit-code file through the active execution backend.

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

use async_trait::async_trait;
use serde::Deserialize;
use serde_json::json;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command as TokioCommand;
use tokio_util::sync::CancellationToken;

use lingshu_types::{ToolError, ToolSchema};

use crate::process_table::ProcessTable;
use crate::registry::{ToolContext, ToolHandler};
use crate::tools::backend_pool::{get_or_create_backend, resolve_workdir};
use crate::tools::backends::{BackendKind, ExecutionBackend, shell_quote};

/// Shell startup warnings to strip from the first output line.
///
/// These appear when `sh -lic` is used and the shell is not attached to a
/// terminal. Filtering them prevents confusing the agent and matches prior
/// background-process filtering.
const SHELL_NOISE: &[&str] = &[
    "bash: cannot set terminal process group",
    "bash: no job control in this shell",
    "no job control in this shell",
    "cannot set terminal process group",
    "tcsetattr: Inappropriate ioctl for device",
];

/// Return true if `line` is a shell startup warning that should be dropped.
fn is_shell_noise(line: &str) -> bool {
    SHELL_NOISE.iter().any(|noise| line.contains(noise))
}

fn format_process_listing(records: &[crate::process_table::ProcessRecord]) -> String {
    if records.is_empty() {
        return "No background processes running.".into();
    }

    let mut lines = vec![format!("Background processes ({}):", records.len())];
    for rec in records {
        let duration = rec
            .started_at
            .elapsed()
            .map(|d| format!("{}s ago", d.as_secs()))
            .unwrap_or_else(|_| "?".into());
        let pid_str = rec.pid.map(|p| format!(" pid={}", p)).unwrap_or_default();
        lines.push(format!(
            "  {} [{}]{} {} — started {} in {}",
            rec.process_id,
            rec.status.as_str(),
            pid_str,
            rec.command,
            duration,
            rec.cwd
        ));
    }
    lines.join("\n")
}

// ─── run_process ───────────────────────────────────────────────
//
// WHY "sh -c": Spawning via the shell gives the agent access to
// pipelines, redirects, and environment variable expansion — the
// same semantics as the `terminal` tool for one-shot commands.
// The security scanner in lingshu-security runs before spawn.

pub struct RunProcessTool;

#[derive(Deserialize)]
struct RunArgs {
    /// Shell command to execute (passed to `sh -c`)
    command: String,
    /// Optional working directory (defaults to current directory)
    cwd: Option<String>,
    #[serde(default)]
    pty: bool,
    /// Optional substring patterns to watch for in process output.
    /// Notifications are delivered in real-time when matched.
    #[serde(default)]
    watch_patterns: Vec<String>,
}

pub(crate) async fn start_background_process(
    tool_name: &'static str,
    command: &str,
    cwd_override: Option<&str>,
    pty: bool,
    watch_patterns: Vec<String>,
    ctx: &ToolContext,
) -> Result<String, ToolError> {
    // Security: scan for dangerous patterns before spawning.
    // WHY: Background processes persist beyond a single tool call, so
    // we must prevent agents from launching persistent malicious processes.
    if let Some(reasons) = crate::approval_runtime::command_approval_reasons(ctx, command) {
        crate::approval_runtime::request_command_approval(ctx, command, reasons).await?;
    }

    crate::command_interaction::guard_run_process_command(
        command,
        &ctx.config.terminal_backend,
        pty,
    )?;

    let cwd = resolve_workdir(ctx, cwd_override);

    let Some(ref table) = ctx.process_table else {
        return Err(ToolError::Unavailable {
            tool: tool_name.into(),
            reason: "Process table not available in this context.".into(),
        });
    };

    // Enforce the MAX_PROCESSES cap: evict oldest finished entries first.
    table.prune_if_full().await;

    // Use the session_key from context (gateway: "platform:chat_id", CLI: session_id).
    // Enables has_active_for_session() — matches the existing session-scoped process model.
    let session_key = ctx.session_key.clone().unwrap_or_default();

    if pty && ctx.config.terminal_backend != BackendKind::Local {
        return Err(
            ToolError::capability_denied(
                tool_name,
                "pty_backend_unsupported",
                format!(
                    "PTY mode is only available on the local terminal backend. The active backend is {}.",
                    ctx.config.terminal_backend
                ),
            )
            .with_suggested_action(
                "Switch to the local backend for interactive PTY commands, or run a non-PTY background command."
                    .to_string(),
            ),
        );
    }

    let process_id = table.register(command.to_string(), cwd.clone(), session_key);

    if let Some(sink) = ctx.watch_notification_tx.clone() {
        table.set_watch_sink(&process_id, sink).await;
    }

    // Set watch patterns if provided
    if !watch_patterns.is_empty() {
        table.set_watch_patterns(&process_id, watch_patterns).await;
    }

    if ctx.config.terminal_backend == BackendKind::Local {
        spawn_local_process(tool_name, command, &cwd, pty, table, process_id).await
    } else {
        let backend = get_or_create_backend(ctx).await?;
        spawn_remote_process(
            tool_name,
            command,
            &cwd,
            table,
            process_id,
            &ctx.task_id,
            backend,
        )
        .await
    }
}

#[async_trait]
impl ToolHandler for RunProcessTool {
    fn name(&self) -> &'static str {
        "run_process"
    }

    fn toolset(&self) -> &'static str {
        "terminal"
    }

    fn emoji(&self) -> &'static str {
        "🚀"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "run_process".into(),
            description: "Spawn a background process. Returns immediately with a process_id. \
                          Use list_processes to poll status and kill_process to stop it."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "command": {
                        "type": "string",
                        "description": "Shell command to run in the background"
                    },
                    "cwd": {
                        "type": "string",
                        "description": "Working directory (defaults to current dir)"
                    },
                    "pty": {
                        "type": "boolean",
                        "description": "Allocate a PTY for local interactive CLI sessions. Local backend only. Full-screen terminal UIs remain unsupported."
                    },
                    "watch_patterns": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Substring patterns to watch for in process output. Notifications are delivered in real-time when matched. Rate-limited to prevent floods."
                    }
                },
                "required": ["command"]
            }),
            strict: None,
        }
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: RunArgs = serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
            tool: "run_process".into(),
            message: e.to_string(),
        })?;

        start_background_process(
            "run_process",
            &args.command,
            args.cwd.as_deref(),
            args.pty,
            args.watch_patterns,
            ctx,
        )
        .await
    }
}

fn remote_process_state_base(task_id: &str, process_id: &str) -> String {
    let sanitized_task = task_id
        .chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
                ch
            } else {
                '_'
            }
        })
        .collect::<String>();
    format!("/tmp/lingshu-bg-{sanitized_task}-{process_id}")
}

async fn spawn_local_process(
    tool_name: &'static str,
    command: &str,
    cwd: &str,
    pty: bool,
    table: &Arc<ProcessTable>,
    process_id: String,
) -> Result<String, ToolError> {
    if pty {
        return crate::local_pty::spawn_background(tool_name, command, cwd, table, process_id)
            .await;
    }

    let cwd_path = std::path::Path::new(cwd);
    let shell_exe = crate::tools::backends::local::preferred_shell_executable();
    let mut cmd = TokioCommand::new(&shell_exe);
    cmd.arg(crate::tools::backends::local::shell_command_flag(
        &shell_exe, true,
    ))
    .arg(command)
    .current_dir(cwd_path)
    .env_clear()
    .envs(crate::tools::backends::local::safe_env())
    .env("PYTHONUNBUFFERED", "1")
    .env("TERM", "dumb")
    .env("LC_ALL", "C.UTF-8")
    .env("PATH", crate::tools::backends::local::subprocess_path())
    .stdout(std::process::Stdio::piped())
    .stderr(std::process::Stdio::piped())
    .stdin(std::process::Stdio::piped());
    #[cfg(unix)]
    cmd.process_group(0);
    let child_result = cmd.spawn();

    let mut child = match child_result {
        Ok(c) => c,
        Err(e) => {
            table.mark_killed(&process_id).await;
            return Err(ToolError::ExecutionFailed {
                tool: tool_name.into(),
                message: format!("Failed to spawn process: {e}"),
            });
        }
    };

    if let Some(pid) = child.id() {
        table.set_pid(&process_id, pid).await;
    }

    if let Some(child_stdin) = child.stdin.take() {
        use tokio::io::AsyncWriteExt;
        let (stdin_tx, mut stdin_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
        table.set_stdin_tx(&process_id, stdin_tx).await;
        tokio::spawn(async move {
            let mut stdin = child_stdin;
            while let Some(data) = stdin_rx.recv().await {
                if stdin.write_all(data.as_bytes()).await.is_err() {
                    break;
                }
                let _ = stdin.flush().await;
            }
        });
    }

    let table_clone = Arc::clone(table);
    let pid_clone = process_id.clone();
    let stdout = child.stdout.take().map(BufReader::new);
    let stderr = child.stderr.take().map(BufReader::new);

    if let Some(stdout_reader) = stdout {
        let t = Arc::clone(&table_clone);
        let p = pid_clone.clone();
        tokio::spawn(async move {
            drain_reader(stdout_reader, &t, &p).await;
        });
    }

    if let Some(stderr_reader) = stderr {
        let t = Arc::clone(&table_clone);
        let p = pid_clone.clone();
        tokio::spawn(async move {
            drain_reader(stderr_reader, &t, &p).await;
        });
    }

    let table_exit = Arc::clone(table);
    let pid_exit = process_id.clone();
    tokio::spawn(async move {
        match child.wait().await {
            Ok(status) => {
                let code = status.code().unwrap_or(-1);
                table_exit.mark_exited(&pid_exit, code).await;
            }
            Err(_) => {
                table_exit.mark_killed(&pid_exit).await;
            }
        }
    });

    Ok(serde_json::to_string(&json!({
        "ok": true,
        "process_id": process_id,
        "command": command
    }))
    .expect("infallible"))
}

async fn spawn_remote_process(
    tool_name: &'static str,
    command: &str,
    cwd: &str,
    table: &Arc<ProcessTable>,
    process_id: String,
    task_id: &str,
    backend: Arc<dyn ExecutionBackend>,
) -> Result<String, ToolError> {
    let base = remote_process_state_base(task_id, &process_id);
    let log_path = format!("{base}.log");
    let pid_path = format!("{base}.pid");
    let exit_path = format!("{base}.exit");
    let backend_kind = backend.kind();
    let supervisor = format!(
        "nohup sh -lc {command} > {log} 2>&1 < /dev/null & \
         _lingshu_pid=$!; \
         printf '%s\\n' \"$_lingshu_pid\" > {pid}; \
         wait \"$_lingshu_pid\"; \
         _lingshu_status=$?; \
         printf '%s\\n' \"$_lingshu_status\" > {exit}",
        command = shell_quote(command),
        log = shell_quote(&log_path),
        pid = shell_quote(&pid_path),
        exit = shell_quote(&exit_path),
    );

    let launcher = format!(
        "rm -f {log} {pid} {exit}; \
         nohup sh -lc {supervisor} >/dev/null 2>&1 < /dev/null & \
         for _lingshu_i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20; do \
           [ -s {pid} ] && break; \
           sleep 0.1; \
         done; \
         cat {pid} 2>/dev/null || true",
        supervisor = shell_quote(&supervisor),
        log = shell_quote(&log_path),
        pid = shell_quote(&pid_path),
        exit = shell_quote(&exit_path),
    );

    let launch = backend
        .execute(
            &launcher,
            cwd,
            Duration::from_secs(10),
            CancellationToken::new(),
            crate::tool_progress_tail::ExecuteOptions::default(),
        )
        .await?;

    let pid = launch
        .stdout
        .lines()
        .rev()
        .find_map(|line| line.trim().parse::<u32>().ok());

    let Some(pid) = pid else {
        table.mark_killed(&process_id).await;
        return Err(ToolError::ExecutionFailed {
            tool: tool_name.into(),
            message: format!(
                "Failed to start background process in {} backend: {}",
                backend.kind(),
                launch.format(2048, 512)
            ),
        });
    };

    table.set_pid(&process_id, pid).await;

    let (kill_tx, mut kill_rx) = tokio::sync::mpsc::unbounded_channel::<()>();
    table.set_remote_kill(&process_id, kill_tx);

    let table_poll = Arc::clone(table);
    let pid_poll = process_id.clone();
    let backend_poll = Arc::clone(&backend);
    let cwd_poll = cwd.to_string();
    tokio::spawn(async move {
        loop {
            tokio::select! {
                _ = kill_rx.recv() => {
                    let kill_cmd = format!(
                        "if [ -s {pid} ]; then \
                           _lingshu_pid=$(cat {pid} 2>/dev/null); \
                           kill -KILL -- -\"$_lingshu_pid\" 2>/dev/null || true; \
                           kill -KILL \"$_lingshu_pid\" 2>/dev/null || true; \
                           printf '137\\n' > {exit} 2>/dev/null || true; \
                         fi",
                        pid = shell_quote(&pid_path),
                        exit = shell_quote(&exit_path),
                    );
                    let _ = backend_poll
                        .execute(
                            &kill_cmd,
                            &cwd_poll,
                            Duration::from_secs(5),
                            CancellationToken::new(),
                            crate::tool_progress_tail::ExecuteOptions::default(),
                        )
                        .await;
                    table_poll.mark_killed(&pid_poll).await;
                    break;
                }
                _ = tokio::time::sleep(Duration::from_secs(2)) => {
                    if refresh_remote_output(&backend_poll, &cwd_poll, &table_poll, &pid_poll, &log_path).await.is_err() {
                        table_poll.mark_exited(&pid_poll, -1).await;
                        break;
                    }
                    match read_remote_exit_code(&backend_poll, &cwd_poll, &exit_path).await {
                        Ok(Some(code)) => {
                            let _ = refresh_remote_output(&backend_poll, &cwd_poll, &table_poll, &pid_poll, &log_path).await;
                            table_poll.mark_exited(&pid_poll, code).await;
                            break;
                        }
                        Ok(None) => {}
                        Err(_) => {
                            table_poll.mark_exited(&pid_poll, -1).await;
                            break;
                        }
                    }
                }
            }
        }
    });

    Ok(serde_json::to_string(&json!({
        "ok": true,
        "process_id": process_id,
        "command": command,
        "backend": backend_kind.to_string()
    }))
    .expect("infallible"))
}

async fn refresh_remote_output(
    backend: &Arc<dyn ExecutionBackend>,
    cwd: &str,
    table: &ProcessTable,
    process_id: &str,
    log_path: &str,
) -> Result<(), ToolError> {
    let read_cmd = format!("tail -n 500 {} 2>/dev/null || true", shell_quote(log_path));
    let output = backend
        .execute(
            &read_cmd,
            cwd,
            Duration::from_secs(5),
            CancellationToken::new(),
            crate::tool_progress_tail::ExecuteOptions::default(),
        )
        .await?;
    table
        .replace_output(process_id, normalize_output_lines(&output.stdout))
        .await;
    Ok(())
}

async fn read_remote_exit_code(
    backend: &Arc<dyn ExecutionBackend>,
    cwd: &str,
    exit_path: &str,
) -> Result<Option<i32>, ToolError> {
    let read_cmd = format!(
        "test -s {path} && cat {path} || true",
        path = shell_quote(exit_path)
    );
    let output = backend
        .execute(
            &read_cmd,
            cwd,
            Duration::from_secs(5),
            CancellationToken::new(),
            crate::tool_progress_tail::ExecuteOptions::default(),
        )
        .await?;
    Ok(output
        .stdout
        .lines()
        .rev()
        .find_map(|line| line.trim().parse::<i32>().ok()))
}

fn normalize_output_lines(output: &str) -> Vec<String> {
    let mut first_lines = true;
    let mut lines = Vec::new();
    for raw in output.lines() {
        let trimmed = raw.trim_end_matches('\r');
        if first_lines && is_shell_noise(trimmed) {
            continue;
        }
        if !trimmed.is_empty() {
            first_lines = false;
        }
        lines.push(trimmed.to_string());
    }
    lines
}

/// Drain a line-buffered async reader into the process ring buffer.
///
/// WHY line-buffered: Line boundaries give meaningful units for display.
/// Tool output (compiler warnings, log lines) is inherently line-structured.
///
/// Shell noise filtering: The first non-empty lines are checked against
/// `SHELL_NOISE` and silently dropped. This matches the prior
/// `ProcessRegistry._clean_shell_noise()`.
///
/// Watch patterns: If the process has `watch_state` set, each line is
/// checked against the patterns and notifications are sent via the sink.
async fn drain_reader(
    mut reader: BufReader<impl tokio::io::AsyncRead + Unpin>,
    table: &ProcessTable,
    process_id: &str,
) {
    let mut first_lines = true; // still scanning the startup noise prefix
    let mut line = String::new();
    loop {
        line.clear();
        match reader.read_line(&mut line).await {
            Ok(0) => break, // EOF
            Ok(_) => {
                let trimmed = line.trim_end_matches('\n').trim_end_matches('\r');
                // Suppress shell startup noise from the leading output.
                if first_lines && is_shell_noise(trimmed) {
                    continue;
                }
                if !trimmed.is_empty() {
                    first_lines = false;
                }
                table
                    .append_output(process_id, vec![trimmed.to_string()])
                    .await;
            }
            Err(_) => break,
        }
    }
}

inventory::submit!(&RunProcessTool as &dyn ToolHandler);

// ─── list_processes ────────────────────────────────────────────

pub struct ListProcessesTool;

#[async_trait]
impl ToolHandler for ListProcessesTool {
    fn name(&self) -> &'static str {
        "list_processes"
    }

    fn toolset(&self) -> &'static str {
        "terminal"
    }

    fn emoji(&self) -> &'static str {
        "📋"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "list_processes".into(),
            description: "List background processes started in this session.".into(),
            parameters: json!({"type": "object", "properties": {}}),
            strict: None,
        }
    }

    async fn execute(
        &self,
        _args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let Some(ref table) = ctx.process_table else {
            return Ok("No background processes running.".into());
        };

        let records = table.list_all().await;
        Ok(format_process_listing(&records))
    }
}

inventory::submit!(&ListProcessesTool as &dyn ToolHandler);

// ─── kill_process ──────────────────────────────────────────────

pub struct KillProcessTool;

#[derive(Deserialize)]
struct KillArgs {
    process_id: String,
}

#[async_trait]
impl ToolHandler for KillProcessTool {
    fn name(&self) -> &'static str {
        "kill_process"
    }

    fn toolset(&self) -> &'static str {
        "terminal"
    }

    fn emoji(&self) -> &'static str {
        "🛑"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "kill_process".into(),
            description: "Kill a background process by its ID.".into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "process_id": {
                        "type": "string",
                        "description": "ID of the background process to kill"
                    }
                },
                "required": ["process_id"]
            }),
            strict: None,
        }
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: KillArgs = serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
            tool: "kill_process".into(),
            message: e.to_string(),
        })?;

        let Some(ref table) = ctx.process_table else {
            return Err(ToolError::NotFound(format!(
                "No process with ID '{}' found (process table unavailable).",
                args.process_id
            )));
        };

        let killed = table.kill(&args.process_id).await;
        if killed {
            Ok(format!("Process '{}' has been killed.", args.process_id))
        } else {
            Err(ToolError::NotFound(format!(
                "No process with ID '{}' found.",
                args.process_id
            )))
        }
    }
}

inventory::submit!(&KillProcessTool as &dyn ToolHandler);

// ─── get_process_output ────────────────────────────────────────
//
// Matches the legacy `process(action="poll")` contract.
// Returns the last N lines of buffered output plus status/exit code.

pub struct GetProcessOutputTool;

#[derive(Deserialize)]
struct GetOutputArgs {
    process_id: String,
    /// Max number of output lines to return (default: 100).
    tail: Option<usize>,
    /// Line offset from the start of the buffer (default: 0 = last `tail` lines).
    /// When > 0, skip the first `offset` lines and return up to `tail` lines.
    /// Matches the legacy `process(action="log", offset=K, limit=N)` contract.
    offset: Option<usize>,
}

#[async_trait]
impl ToolHandler for GetProcessOutputTool {
    fn name(&self) -> &'static str {
        "get_process_output"
    }

    fn toolset(&self) -> &'static str {
        "terminal"
    }

    fn emoji(&self) -> &'static str {
        "📄"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "get_process_output".into(),
            description: "Get buffered output (stdout+stderr) from a background process. \
                          Returns the last `tail` lines plus current status. \
                          Use `offset` > 0 to paginate from the start of the buffer. \
                          Call repeatedly to poll a long-running process."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "process_id": {
                        "type": "string",
                        "description": "ID of the background process (from run_process)"
                    },
                    "tail": {
                        "type": "integer",
                        "description": "Max lines to return (default: 100). Used as the limit when offset=0 (last N lines) or as page size when offset > 0."
                    },
                    "offset": {
                        "type": "integer",
                        "description": "Line offset from the start of the buffer. Default: 0 (last `tail` lines). Set to K to skip the first K lines."
                    }
                },
                "required": ["process_id"]
            }),
            strict: None,
        }
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: GetOutputArgs =
            serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
                tool: "get_process_output".into(),
                message: e.to_string(),
            })?;

        let Some(ref table) = ctx.process_table else {
            return Err(ToolError::Unavailable {
                tool: "get_process_output".into(),
                reason: "Process table not available in this context.".into(),
            });
        };

        let tail = args.tail.unwrap_or(100).clamp(1, 500);
        let offset = args.offset.unwrap_or(0);
        match table.get_output_page(&args.process_id, offset, tail).await {
            Some((output, total_lines, status, exit_code)) => {
                let status_str = match (&status, exit_code) {
                    (crate::process_table::ProcessStatus::Exited, Some(code)) => {
                        format!("exited (code {})", code)
                    }
                    (crate::process_table::ProcessStatus::Killed, _) => "killed".into(),
                    _ => "running".into(),
                };
                let showing = output.lines().count();
                if output.is_empty() {
                    Ok(format!(
                        "[{}: {} — no output yet]",
                        args.process_id, status_str
                    ))
                } else {
                    let page_note = format!(" [{} of {} lines]", showing, total_lines);
                    Ok(format!(
                        "[{}: {}{}]\n{}",
                        args.process_id, status_str, page_note, output
                    ))
                }
            }
            None => Err(ToolError::NotFound(format!(
                "No process with ID '{}' found.",
                args.process_id
            ))),
        }
    }
}

inventory::submit!(&GetProcessOutputTool as &dyn ToolHandler);

// ─── wait_for_process ─────────────────────────────────────────
//
// Matches the legacy `process(action="wait")` contract.
// Blocks (with async yield) until the process exits or timeout.

pub struct WaitForProcessTool;

#[derive(Deserialize)]
struct WaitArgs {
    process_id: String,
    /// Timeout in seconds (default: 60, max: 3600).
    timeout_secs: Option<u64>,
}

#[async_trait]
impl ToolHandler for WaitForProcessTool {
    fn name(&self) -> &'static str {
        "wait_for_process"
    }

    fn toolset(&self) -> &'static str {
        "terminal"
    }

    fn emoji(&self) -> &'static str {
        ""
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "wait_for_process".into(),
            description: "Wait for a background process to finish, then return its exit code \
                          and last 50 lines of output. Use timeout_secs to cap the wait."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "process_id": {
                        "type": "string",
                        "description": "ID of the background process (from run_process)"
                    },
                    "timeout_secs": {
                        "type": "integer",
                        "description": "Max seconds to wait (default: 60)"
                    }
                },
                "required": ["process_id"]
            }),
            strict: None,
        }
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: WaitArgs = serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
            tool: "wait_for_process".into(),
            message: e.to_string(),
        })?;

        let Some(ref table) = ctx.process_table else {
            return Err(ToolError::Unavailable {
                tool: "wait_for_process".into(),
                reason: "Process table not available in this context.".into(),
            });
        };

        let timeout_secs = args.timeout_secs.unwrap_or(60).clamp(1, 3600);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
        let mut last_heartbeat = std::time::Instant::now()
            - std::time::Duration::from_secs(crate::tool_progress_tail::HEARTBEAT_INTERVAL_SECS);

        // Poll the table every 500ms until the process is no longer Running.
        //
        // WHY tokio::select! with cancel: matches the prior wait behavior which
        // checks _interrupt_event in its poll loop. Without this, a user Ctrl+C
        // during wait_for_process would not break out until the deadline.
        loop {
            match table.get_output_tail(&args.process_id, 50).await {
                None => {
                    return Err(ToolError::NotFound(format!(
                        "No process with ID '{}' found.",
                        args.process_id
                    )));
                }
                Some((output, status, exit_code)) => {
                    let is_done = status != crate::process_table::ProcessStatus::Running;
                    if is_done {
                        let status_str = match (&status, exit_code) {
                            (crate::process_table::ProcessStatus::Exited, Some(code)) => {
                                format!("exited (code {})", code)
                            }
                            (crate::process_table::ProcessStatus::Killed, _) => "killed".into(),
                            _ => "done".into(),
                        };
                        return Ok(format!("[{}: {}]\n{}", args.process_id, status_str, output));
                    }

                    if std::time::Instant::now() >= deadline {
                        return Ok(format!(
                            "[{}: still running after {}s — use get_process_output to poll]\n{}",
                            args.process_id, timeout_secs, output
                        ));
                    }

                    let now = std::time::Instant::now();
                    if now.duration_since(last_heartbeat)
                        >= std::time::Duration::from_secs(
                            crate::tool_progress_tail::HEARTBEAT_INTERVAL_SECS,
                        )
                    {
                        last_heartbeat = now;
                        ctx.emit_progress(crate::tool_progress_tail::format_wait_heartbeat(
                            &args.process_id,
                            &output,
                        ));
                    }

                    tokio::select! {
                        _ = tokio::time::sleep(std::time::Duration::from_millis(500)) => {},
                        _ = ctx.cancel.cancelled() => {
                            return Ok(format!(
                                "[{}: interrupted — still running — use get_process_output to poll]\n{}",
                                args.process_id, output
                            ));
                        }
                    }
                }
            }
        }
    }
}

inventory::submit!(&WaitForProcessTool as &dyn ToolHandler);

// ─── write_stdin ──────────────────────────────────────────────
//
// Matches the legacy `process_registry.write_stdin(session_id, data)` contract.
// Sends raw bytes to a running process's stdin, enabling interactive control
// (e.g. answering prompts, sending keystrokes to a Python REPL or REPL-based CLI).
//
// WHY `newline` parameter: Most interactive prompts expect input terminated
// with '\n' (like pressing Enter).  Making it explicit avoids silent
// surprises and matches the prior `submit_stdin()` vs `write_stdin()` split.

fn encode_terminal_key(key: &str) -> Option<&'static str> {
    match key.trim().to_ascii_lowercase().as_str() {
        "enter" | "return" => Some("\n"),
        "tab" => Some("\t"),
        "escape" | "esc" => Some("\u{1b}"),
        "backspace" => Some("\u{7f}"),
        "delete" => Some("\u{1b}[3~"),
        "up" | "arrow_up" => Some("\u{1b}[A"),
        "down" | "arrow_down" => Some("\u{1b}[B"),
        "right" | "arrow_right" => Some("\u{1b}[C"),
        "left" | "arrow_left" => Some("\u{1b}[D"),
        "home" => Some("\u{1b}[H"),
        "end" => Some("\u{1b}[F"),
        "page_up" => Some("\u{1b}[5~"),
        "page_down" => Some("\u{1b}[6~"),
        "ctrl_c" => Some("\u{3}"),
        "ctrl_d" => Some("\u{4}"),
        "ctrl_z" => Some("\u{1a}"),
        _ => None,
    }
}

fn build_stdin_payload(
    tool: &'static str,
    data: Option<&str>,
    key: Option<&str>,
    newline: bool,
) -> Result<String, ToolError> {
    let mut payload = String::new();
    if let Some(data) = data {
        payload.push_str(data);
    }
    if let Some(key) = key {
        let encoded = encode_terminal_key(key).ok_or_else(|| ToolError::InvalidArgs {
            tool: tool.into(),
            message: format!(
                "Unsupported terminal key '{key}'. Supported keys: enter, tab, escape, backspace, delete, up, down, left, right, home, end, page_up, page_down, ctrl_c, ctrl_d, ctrl_z."
            ),
        })?;
        payload.push_str(encoded);
    }
    if newline {
        payload.push('\n');
    }
    if payload.is_empty() {
        return Err(ToolError::InvalidArgs {
            tool: tool.into(),
            message: "At least one of 'data', 'key', or 'newline=true' is required.".into(),
        });
    }
    Ok(payload)
}

async fn send_stdin_payload(
    tool: &'static str,
    table: &ProcessTable,
    process_id: &str,
    payload: String,
) -> Result<String, ToolError> {
    match table.get_stdin_tx(process_id).await {
        None => Err(ToolError::NotFound(format!(
            "No process with ID '{}' found (or stdin is not available).",
            process_id
        ))),
        Some(tx) => {
            let bytes = payload.len();
            tx.send(payload).map_err(|_| ToolError::ExecutionFailed {
                tool: tool.into(),
                message: format!(
                    "Process '{}' stdin channel closed — process may have exited.",
                    process_id
                ),
            })?;
            Ok(format!(
                "Wrote {} bytes to stdin of process '{}'.",
                bytes, process_id
            ))
        }
    }
}

pub struct WriteStdinTool;

#[derive(Deserialize)]
struct WriteStdinArgs {
    process_id: String,
    /// Text to send to the process stdin.
    data: Option<String>,
    /// Optional terminal key encoded as raw bytes.
    ///
    /// This is a deterministic transport helper, not a screen-model feature.
    /// It maps key names onto the exact bytes written to stdin/PTY.
    key: Option<String>,
    /// If true, append a newline (like pressing Enter). Default: true.
    newline: Option<bool>,
}

#[async_trait]
impl ToolHandler for WriteStdinTool {
    fn name(&self) -> &'static str {
        "write_stdin"
    }

    fn toolset(&self) -> &'static str {
        "terminal"
    }

    fn emoji(&self) -> &'static str {
        "⌨️"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "write_stdin".into(),
            description: "Send text to a running background process's stdin. \
                          Useful for interactive tools (REPLs, prompts). \
                          Set newline=true (default) to simulate pressing Enter."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "process_id": {
                        "type": "string",
                        "description": "ID of the running background process (from run_process)"
                    },
                    "data": {
                        "type": "string",
                        "description": "Text to write to stdin"
                    },
                    "key": {
                        "type": "string",
                        "description": "Optional special key to encode as terminal bytes: enter, tab, escape, backspace, delete, up, down, left, right, home, end, page_up, page_down, ctrl_c, ctrl_d, ctrl_z"
                    },
                    "newline": {
                        "type": "boolean",
                        "description": "Append a newline character (like pressing Enter). Defaults to true for plain text writes and false when a special key is supplied."
                    }
                },
                "required": ["process_id"]
            }),
            strict: None,
        }
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: WriteStdinArgs =
            serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
                tool: "write_stdin".into(),
                message: e.to_string(),
            })?;

        let Some(ref table) = ctx.process_table else {
            return Err(ToolError::Unavailable {
                tool: "write_stdin".into(),
                reason: "Process table not available in this context.".into(),
            });
        };

        let append_newline = args.newline.unwrap_or(args.key.is_none());
        let payload = build_stdin_payload(
            "write_stdin",
            args.data.as_deref(),
            args.key.as_deref(),
            append_newline,
        )?;
        send_stdin_payload("write_stdin", table, &args.process_id, payload).await
    }
}

inventory::submit!(&WriteStdinTool as &dyn ToolHandler);

// ─── process (legacy compatibility facade) ───────────────────────────

pub struct ProcessCompatTool;

#[derive(Deserialize)]
struct ProcessCompatArgs {
    action: String,
    #[serde(default)]
    session_id: Option<String>,
    #[serde(default)]
    data: Option<String>,
    #[serde(default)]
    timeout: Option<u64>,
    #[serde(default)]
    offset: Option<usize>,
    #[serde(default)]
    limit: Option<usize>,
}

#[async_trait]
impl ToolHandler for ProcessCompatTool {
    fn name(&self) -> &'static str {
        "process"
    }

    fn toolset(&self) -> &'static str {
        "terminal"
    }

    fn emoji(&self) -> &'static str {
        "🧰"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "process".into(),
            description: "Manage background processes started with the legacy process contract. \
                          Actions: list, poll, log, wait, kill, write, submit. \
                          This is a compatibility facade over Lingshu's run_process/list_processes/\
                          get_process_output/wait_for_process/kill_process/write_stdin tools."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "action": {
                        "type": "string",
                        "enum": ["list", "poll", "log", "wait", "kill", "write", "submit"],
                        "description": "Action to perform on background processes"
                    },
                    "session_id": {
                        "type": "string",
                        "description": "Process ID from run_process. Required for all actions except list."
                    },
                    "data": {
                        "type": "string",
                        "description": "Text to send to stdin for write/submit actions"
                    },
                    "timeout": {
                        "type": "integer",
                        "description": "Timeout in seconds for wait"
                    },
                    "offset": {
                        "type": "integer",
                        "description": "Offset for log pagination"
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Line limit for poll/log"
                    }
                },
                "required": ["action"]
            }),
            strict: None,
        }
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: ProcessCompatArgs =
            serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
                tool: "process".into(),
                message: e.to_string(),
            })?;

        let Some(ref table) = ctx.process_table else {
            return Err(ToolError::Unavailable {
                tool: "process".into(),
                reason: "Process table not available in this context.".into(),
            });
        };

        if args.action == "list" {
            return Ok(format_process_listing(&table.list_all().await));
        }

        let process_id = args
            .session_id
            .as_deref()
            .ok_or_else(|| ToolError::InvalidArgs {
                tool: "process".into(),
                message: "session_id is required for this action".into(),
            })?;

        match args.action.as_str() {
            "poll" => {
                let tail = args.limit.unwrap_or(100).clamp(1, 500);
                match table.get_output_tail(process_id, tail).await {
                    Some((output, status, exit_code)) => {
                        let status_str = match (&status, exit_code) {
                            (crate::process_table::ProcessStatus::Exited, Some(code)) => {
                                format!("exited (code {})", code)
                            }
                            (crate::process_table::ProcessStatus::Killed, _) => "killed".into(),
                            _ => "running".into(),
                        };
                        Ok(format!("[{}: {}]\n{}", process_id, status_str, output))
                    }
                    None => Err(ToolError::NotFound(format!(
                        "No process with ID '{}' found.",
                        process_id
                    ))),
                }
            }
            "log" => {
                let offset = args.offset.unwrap_or(0);
                let limit = args.limit.unwrap_or(200).clamp(1, 500);
                match table.get_output_page(process_id, offset, limit).await {
                    Some((output, total, _, _)) => Ok(format!(
                        "[{}: showing up to {} lines from offset {} of {}]\n{}",
                        process_id, limit, offset, total, output
                    )),
                    None => Err(ToolError::NotFound(format!(
                        "No process with ID '{}' found.",
                        process_id
                    ))),
                }
            }
            "wait" => {
                let timeout_secs = args.timeout.unwrap_or(60).clamp(1, 3600);
                let deadline =
                    std::time::Instant::now() + std::time::Duration::from_secs(timeout_secs);
                loop {
                    match table.get_output_tail(process_id, 50).await {
                        None => {
                            return Err(ToolError::NotFound(format!(
                                "No process with ID '{}' found.",
                                process_id
                            )));
                        }
                        Some((output, status, exit_code)) => {
                            let is_done = status != crate::process_table::ProcessStatus::Running;
                            if is_done {
                                let status_str = match (&status, exit_code) {
                                    (crate::process_table::ProcessStatus::Exited, Some(code)) => {
                                        format!("exited (code {})", code)
                                    }
                                    (crate::process_table::ProcessStatus::Killed, _) => {
                                        "killed".into()
                                    }
                                    _ => "done".into(),
                                };
                                return Ok(format!("[{}: {}]\n{}", process_id, status_str, output));
                            }

                            if std::time::Instant::now() >= deadline {
                                return Ok(format!(
                                    "[{}: still running after {}s]\n{}",
                                    process_id, timeout_secs, output
                                ));
                            }
                        }
                    }
                    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
                }
            }
            "kill" => {
                if table.kill(process_id).await {
                    Ok(format!("Process '{}' has been killed.", process_id))
                } else {
                    Err(ToolError::NotFound(format!(
                        "No process with ID '{}' found.",
                        process_id
                    )))
                }
            }
            "write" | "submit" => {
                let data = args.data.unwrap_or_default();
                let newline = args.action == "submit";
                let payload = build_stdin_payload("process", Some(&data), None, newline)?;
                send_stdin_payload("process", table, process_id, payload).await
            }
            other => Err(ToolError::InvalidArgs {
                tool: "process".into(),
                message: format!(
                    "Unknown action '{other}'. Use list, poll, log, wait, kill, write, or submit."
                ),
            }),
        }
    }
}

inventory::submit!(&ProcessCompatTool as &dyn ToolHandler);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::process_table::ProcessTable;
    use std::sync::Arc;

    fn ctx_with_table() -> (ToolContext, Arc<ProcessTable>) {
        let table = Arc::new(ProcessTable::new());
        let mut ctx = ToolContext::test_context();
        ctx.process_table = Some(table.clone());
        (ctx, table)
    }

    #[tokio::test]
    async fn list_processes_empty() {
        let ctx = ToolContext::test_context();
        let result = ListProcessesTool
            .execute(json!({}), &ctx)
            .await
            .expect("no error");
        assert!(result.contains("No background processes"));
    }

    #[tokio::test]
    async fn list_processes_shows_entries() {
        let (ctx, table) = ctx_with_table();
        table.register("cargo build", "/tmp", "");
        let result = ListProcessesTool
            .execute(json!({}), &ctx)
            .await
            .expect("no error");
        assert!(result.contains("proc-1"));
        assert!(result.contains("cargo build"));
    }

    #[tokio::test]
    async fn process_compat_list_shows_entries() {
        let (ctx, table) = ctx_with_table();
        table.register("cargo test", "/tmp", "");
        let result = ProcessCompatTool
            .execute(json!({"action": "list"}), &ctx)
            .await
            .expect("no error");
        assert!(result.contains("cargo test"));
        assert!(result.contains("proc-1"));
    }

    #[tokio::test]
    async fn process_compat_submit_appends_newline() {
        let (ctx, table) = ctx_with_table();
        let id = table.register("python", "/tmp", "");
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>();
        table.set_stdin_tx(&id, tx).await;

        ProcessCompatTool
            .execute(
                json!({"action": "submit", "session_id": id, "data": "print(1)"}),
                &ctx,
            )
            .await
            .expect("submit");

        assert_eq!(rx.recv().await.expect("stdin payload"), "print(1)\n");
    }

    #[test]
    fn write_stdin_key_encoding_is_deterministic() {
        assert_eq!(encode_terminal_key("ctrl_c"), Some("\u{3}"));
        assert_eq!(encode_terminal_key("up"), Some("\u{1b}[A"));
        assert_eq!(encode_terminal_key("escape"), Some("\u{1b}"));
        assert_eq!(encode_terminal_key("unknown"), None);
    }

    #[tokio::test]
    async fn write_stdin_supports_special_keys() {
        let (ctx, table) = ctx_with_table();
        let id = table.register("python", "/tmp", "");
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>();
        table.set_stdin_tx(&id, tx).await;

        WriteStdinTool
            .execute(json!({"process_id": id, "key": "ctrl_c"}), &ctx)
            .await
            .expect("special key write");

        assert_eq!(rx.recv().await.expect("stdin payload"), "\u{3}");
    }

    #[tokio::test]
    async fn write_stdin_rejects_unknown_special_key() {
        let (ctx, _table) = ctx_with_table();
        let err = WriteStdinTool
            .execute(json!({"process_id": "proc-1", "key": "hyper"}), &ctx)
            .await
            .expect_err("unknown key should fail");
        let ToolError::InvalidArgs { message, .. } = err else {
            panic!("expected invalid args");
        };
        assert!(message.contains("Unsupported terminal key"));
    }

    #[tokio::test]
    async fn kill_process_success() {
        let (ctx, table) = ctx_with_table();
        table.register("long_running", "/tmp", "");
        let result = KillProcessTool
            .execute(json!({"process_id": "proc-1"}), &ctx)
            .await
            .expect("no error");
        assert!(result.contains("killed"));
    }

    #[tokio::test]
    async fn kill_process_not_found() {
        let (ctx, _table) = ctx_with_table();
        let result = KillProcessTool
            .execute(json!({"process_id": "proc-9999"}), &ctx)
            .await;
        assert!(result.is_err());
    }

    #[test]
    fn remote_process_state_base_namespaces_by_task_id_and_normalizes_pathish_chars() {
        let first = remote_process_state_base("task/one", "proc-1");
        let second = remote_process_state_base("task:two", "proc-1");
        let windowsish = remote_process_state_base(r"C:\Users\runner\task", "proc-1");

        assert_eq!(first, "/tmp/lingshu-bg-task_one-proc-1");
        assert_eq!(second, "/tmp/lingshu-bg-task_two-proc-1");
        assert_eq!(windowsish, "/tmp/lingshu-bg-C__Users_runner_task-proc-1");
        assert_ne!(first, second);
        assert_ne!(second, windowsish);
    }

    #[tokio::test]
    async fn run_process_rejects_tty_ui_commands() {
        let (ctx, _table) = ctx_with_table();
        let err = RunProcessTool
            .execute(json!({"command": "top"}), &ctx)
            .await
            .expect_err("tty ui should be rejected");
        let ToolError::CapabilityDenied { message, code, .. } = err else {
            panic!("expected capability denied");
        };
        assert_eq!(code, "background_interactive_terminal_unsupported");
        assert!(message.contains("interactive terminal UI"));
    }

    #[tokio::test]
    #[ignore = "PTY stdin write round-trip is not reliable in headless CI environments — run locally with --include-ignored"]
    async fn run_process_pty_round_trips_stdin() {
        let (ctx, table) = ctx_with_table();
        let result = RunProcessTool
            .execute(
                json!({
                    "command": "[ -t 0 ] && printf 'tty\\n'; IFS= read -r line; printf 'got:%s\\n' \"$line\"",
                    "pty": true
                }),
                &ctx,
            )
            .await
            .expect("pty process");
        assert!(result.contains("id=proc-1"), "got: {result}");

        tokio::time::sleep(Duration::from_millis(200)).await;
        let initial = table
            .get_output_tail("proc-1", 10)
            .await
            .expect("process output");
        assert!(initial.0.contains("tty"), "got: {}", initial.0);

        WriteStdinTool
            .execute(json!({"process_id": "proc-1", "data": "hello"}), &ctx)
            .await
            .expect("stdin write");

        let waited = WaitForProcessTool
            .execute(json!({"process_id": "proc-1", "timeout_secs": 5}), &ctx)
            .await
            .expect("wait");
        assert!(waited.contains("got:hello"), "got: {waited}");
    }

    #[tokio::test]
    async fn run_process_pty_rejects_remote_backend() {
        let (mut ctx, _table) = ctx_with_table();
        ctx.config.terminal_backend = BackendKind::Modal;

        let err = RunProcessTool
            .execute(json!({"command": "printf ok", "pty": true}), &ctx)
            .await
            .expect_err("remote PTY should fail");
        let ToolError::CapabilityDenied { code, message, .. } = err else {
            panic!("expected capability denied");
        };
        assert_eq!(code, "pty_backend_unsupported");
        assert!(message.contains("local terminal backend"));
    }

    #[tokio::test]
    async fn run_process_pty_still_blocks_fullscreen_ui() {
        let (ctx, _table) = ctx_with_table();
        let err = RunProcessTool
            .execute(json!({"command": "top", "pty": true}), &ctx)
            .await
            .expect_err("fullscreen UI should fail");
        let ToolError::CapabilityDenied { code, .. } = err else {
            panic!("expected capability denied");
        };
        assert_eq!(code, "background_terminal_observation_unsupported");
    }

    #[tokio::test]
    async fn run_process_rejects_macos_prompt_commands_in_background() {
        if !cfg!(target_os = "macos") {
            return;
        }

        let (ctx, _table) = ctx_with_table();
        let err = RunProcessTool
            .execute(json!({"command": "memo notes -s \"Title\""}), &ctx)
            .await
            .expect_err("macos automation should be rejected");
        let ToolError::CapabilityDenied { message, code, .. } = err else {
            panic!("expected capability denied");
        };
        assert_eq!(code, "background_macos_consent_unsupported");
        assert!(message.contains("macOS permission dialog"));
    }
}