-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.rs
More file actions
1240 lines (1125 loc) · 38.5 KB
/
Copy pathcli.rs
File metadata and controls
1240 lines (1125 loc) · 38.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::fs;
use std::fs::File;
use std::io::{self, IsTerminal, Read, Write};
use std::net::Shutdown;
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use chrono::{Local, TimeZone};
use clap::{Parser, Subcommand};
#[cfg(target_os = "linux")]
use nix::sys::signal::{Signal, kill};
#[cfg(target_os = "linux")]
use nix::unistd::Pid;
use rand::random;
use serde::Serialize;
use vt100::Parser as VtParser;
use crate::broker;
use crate::protocol::{
BROKER_API_VERSION, BrokerRequest, BrokerResponse, Event, SessionState, SessionSummary,
};
use crate::store;
const DEFAULT_RUN_YIELD_TIMEOUT_MS: u64 = 10_000;
const DEFAULT_ATTACH_YIELD_TIMEOUT_MS: u64 = 300_000;
#[derive(Parser, Debug)]
#[command(name = "contd")]
#[command(about = "Stateless wrapper for interactive CLI sessions")]
pub struct Cli {
#[arg(long, global = true, help = "Emit machine-readable JSON responses")]
json: bool,
#[arg(
long,
global = true,
help = "Print extra diagnostics (stdin tty, process state, wait channel)"
)]
verbose: bool,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
#[command(about = "Start a new managed interactive session")]
Run {
#[arg(
long = "yield_timeout",
value_name = "DURATION",
value_parser = parse_yield_timeout_ms,
help = "Hard deadline for this call (default 10s). When reached, return with collected output even if the process is still producing output (supports: ms, s, min/m, h/hr, d; max 1d)"
)]
yield_timeout: Option<u64>,
#[arg(
required = true,
trailing_var_arg = true,
help = "Command and arguments to run under contd session management"
)]
command: Vec<String>,
#[arg(
long,
help = "Render PTY output through a virtual 80-column screen with frame (safe for TUI control sequences)"
)]
raw_pty: bool,
},
#[command(about = "Attach to a session and optionally send input")]
Attach {
#[arg(help = "Session id or unique prefix to attach to")]
session_id: String,
#[arg(
long,
help = "Input payload; supports terminal escapes (e.g. \\n newline, \\r Enter, \\t Tab, \\e ESC, \\x1b byte, \\u{2191} Unicode)"
)]
input: Option<String>,
#[arg(
long = "yield_timeout",
value_name = "DURATION",
value_parser = parse_yield_timeout_ms,
help = "Hard deadline for this call (default 300s). When reached, return with collected output even if the process is still producing output (supports: ms, s, min/m, h/hr, d; max 1d)"
)]
yield_timeout: Option<u64>,
#[arg(
long,
help = "Render PTY output through a virtual 80-column screen with frame (safe for TUI control sequences)"
)]
raw_pty: bool,
},
#[command(about = "Terminate a running session")]
Kill {
#[arg(help = "Session id or unique prefix to terminate")]
session_id: String,
},
#[command(about = "List known sessions (or one matched by id/prefix)")]
List {
#[arg(help = "Optional session id/prefix filter")]
session_id: Option<String>,
},
#[command(about = "Garbage-collect finished sessions")]
Gc,
#[command(about = "Stop brokers and remove all state")]
Clean,
#[command(hide = true)]
Broker {
#[arg(
long = "state-root",
help = "State root directory used by the background broker"
)]
state_root: PathBuf,
},
}
pub fn run() -> i32 {
let cli = Cli::parse();
let json = cli.json;
match run_inner(cli) {
Ok(code) => code,
Err(err) => {
if json {
let event = Event::Error {
code: "runtime_error".into(),
message: err.to_string(),
};
println!("{}", event.to_json_line());
} else {
eprintln!("{}", style("error", COLOR_RED, true));
eprintln!("{}", err);
}
1
}
}
}
fn run_inner(cli: Cli) -> Result<i32> {
let json = cli.json;
let verbose = cli.verbose;
match cli.command {
Commands::Broker { state_root } => {
broker::run_broker(&state_root)?;
Ok(0)
}
Commands::Run {
command,
yield_timeout,
raw_pty,
} => {
let response = send_to_broker(BrokerRequest::Run {
command,
yield_timeout_ms: Some(yield_timeout.unwrap_or(DEFAULT_RUN_YIELD_TIMEOUT_MS)),
})?;
Ok(handle_response(response, json, raw_pty, verbose, None))
}
Commands::Attach {
session_id,
input,
yield_timeout,
raw_pty,
} => {
let payload = match input {
Some(value) => decode_cli_input_escapes(&value)?,
None => read_stdin_if_piped()?,
};
let response = send_to_broker(BrokerRequest::Attach {
session_id,
input: payload,
yield_timeout_ms: Some(yield_timeout.unwrap_or(DEFAULT_ATTACH_YIELD_TIMEOUT_MS)),
})?;
Ok(handle_response(response, json, raw_pty, verbose, None))
}
Commands::Kill { session_id } => {
let response = send_to_broker(BrokerRequest::Kill { session_id })?;
Ok(handle_response(response, json, false, verbose, None))
}
Commands::List { session_id } => {
let highlight = session_id.clone();
let response = send_to_broker(BrokerRequest::List { session_id })?;
Ok(handle_response(
response,
json,
false,
verbose,
highlight.as_deref(),
))
}
Commands::Gc => {
let response = send_to_broker(BrokerRequest::Gc)?;
Ok(handle_response(response, json, false, verbose, None))
}
Commands::Clean => clean_state(json),
}
}
#[derive(Debug, Serialize)]
struct CleanReport {
roots: Vec<String>,
removed_roots: usize,
stopped_brokers: usize,
}
fn clean_state(json: bool) -> Result<i32> {
let roots = clean_roots()?;
let stopped_brokers = stop_brokers_for_roots(&roots)?;
let mut removed_roots = 0usize;
for root in &roots {
if root.exists() {
fs::remove_dir_all(root)
.with_context(|| format!("failed to remove state root {}", root.display()))?;
removed_roots += 1;
}
}
let report = CleanReport {
roots: roots
.iter()
.map(|p| p.to_string_lossy().to_string())
.collect(),
removed_roots,
stopped_brokers,
};
if json {
println!(
"{}",
serde_json::to_string(&report).expect("clean report serialization")
);
} else {
println!("{}", style("cleaned", COLOR_CYAN, true));
println!("stopped brokers: {}", report.stopped_brokers);
println!("removed roots: {}", report.removed_roots);
for root in report.roots {
println!("root: {root}");
}
}
Ok(0)
}
fn clean_roots() -> Result<Vec<PathBuf>> {
let mut roots = Vec::new();
let current = store::state_root()?;
roots.push(current.clone());
let default = default_state_root()?;
if default != current {
roots.push(default);
}
Ok(roots)
}
fn default_state_root() -> Result<PathBuf> {
Ok(PathBuf::from("/tmp").join("contd"))
}
#[cfg(target_os = "linux")]
fn stop_brokers_for_roots(roots: &[PathBuf]) -> Result<usize> {
let mut matched_pids = Vec::new();
for entry in fs::read_dir("/proc").context("failed to read /proc")? {
let entry = entry?;
let name = entry.file_name();
let Some(name) = name.to_str() else {
continue;
};
let Ok(pid_raw) = name.parse::<i32>() else {
continue;
};
let cmdline_path = entry.path().join("cmdline");
let raw = match fs::read(&cmdline_path) {
Ok(raw) => raw,
Err(_) => continue,
};
let args = parse_proc_cmdline(&raw);
if roots.iter().any(|root| is_broker_for_root(&args, root)) {
matched_pids.push(pid_raw);
}
}
for pid_raw in &matched_pids {
let _ = kill(Pid::from_raw(*pid_raw), Signal::SIGTERM);
}
let deadline = Instant::now() + Duration::from_millis(700);
while Instant::now() < deadline {
if matched_pids
.iter()
.all(|pid_raw| !process_is_alive(*pid_raw))
{
break;
}
thread::sleep(Duration::from_millis(20));
}
for pid_raw in &matched_pids {
if process_is_alive(*pid_raw) {
let _ = kill(Pid::from_raw(*pid_raw), Signal::SIGKILL);
}
}
Ok(matched_pids.len())
}
#[cfg(not(target_os = "linux"))]
fn stop_brokers_for_roots(_roots: &[PathBuf]) -> Result<usize> {
Ok(0)
}
#[cfg(target_os = "linux")]
fn process_is_alive(pid_raw: i32) -> bool {
kill(Pid::from_raw(pid_raw), None::<Signal>).is_ok()
}
#[cfg(target_os = "linux")]
fn parse_proc_cmdline(raw: &[u8]) -> Vec<String> {
raw.split(|b| *b == 0)
.filter(|segment| !segment.is_empty())
.map(|segment| String::from_utf8_lossy(segment).to_string())
.collect()
}
#[cfg(target_os = "linux")]
fn is_broker_for_root(args: &[String], root: &Path) -> bool {
if args.len() < 4 {
return false;
}
args[1] == "broker" && args[2] == "--state-root" && args[3] == root.to_string_lossy()
}
fn handle_response(
response: BrokerResponse,
json: bool,
raw_pty: bool,
verbose: bool,
list_highlight_prefix: Option<&str>,
) -> i32 {
if json {
return handle_response_json(response);
}
handle_response_human(response, raw_pty, verbose, list_highlight_prefix)
}
fn handle_response_json(response: BrokerResponse) -> i32 {
match response {
BrokerResponse::Event { event } => {
let code = match &event {
Event::Error { code, .. }
if code == "session_not_found"
|| code == "session_unrecoverable"
|| code == "session_id_ambiguous" =>
{
2
}
Event::Error { .. } => 1,
_ => 0,
};
println!("{}", event.to_json_line());
code
}
other => {
println!(
"{}",
serde_json::to_string(&other).expect("response serialization")
);
0
}
}
}
fn handle_response_human(
response: BrokerResponse,
raw_pty: bool,
verbose: bool,
list_highlight_prefix: Option<&str>,
) -> i32 {
match response {
BrokerResponse::Event { event } => render_event_human(event, raw_pty, verbose),
BrokerResponse::List { sessions } => {
println!("{}", style("sessions", COLOR_CYAN, true));
render_session_tree(&sessions, list_highlight_prefix);
0
}
BrokerResponse::Gc { removed } => {
println!("removed sessions: {removed}");
0
}
BrokerResponse::Pong { version } => {
println!("pong v{version}");
0
}
}
}
fn render_event_human(event: Event, raw_pty: bool, verbose: bool) -> i32 {
match event {
Event::SessionWaitingInput {
session_id,
output,
detector,
} => {
println!("{}", style("ready for input", COLOR_GREEN, true));
println!("id: {session_id}");
print_detector(&detector, verbose);
print_pty_output(&output, raw_pty);
0
}
Event::SessionSteadyInput {
session_id,
output,
detector,
} => {
println!(
"{}",
style("screen stable, may be ready for input", COLOR_GREEN, true)
);
println!("id: {session_id}");
print_detector(&detector, verbose);
print_pty_output(&output, raw_pty);
0
}
Event::SessionYieldTimeout {
session_id,
output,
timeout_ms,
} => {
println!("{}", style("timed out", COLOR_YELLOW, true));
println!("id: {session_id}");
println!("timeout_ms: {timeout_ms}");
print_pty_output(&output, raw_pty);
0
}
Event::SessionExited {
session_id,
output,
exit_code,
signal,
} => {
let failed = exit_code.map(|code| code != 0).unwrap_or(false) || signal.is_some();
if failed {
println!("{}", style("failed", COLOR_RED, true));
println!("reason: process ended with error");
} else {
println!("{}", style("exited", COLOR_MAGENTA, true));
}
println!("id: {session_id}");
println!("exit_code: {}", format_option_i32(exit_code));
println!("signal: {}", format_option_i32(signal));
print_pty_output(&output, raw_pty);
0
}
Event::Error { code, message } => {
println!("{}", style("error", COLOR_RED, true));
println!("code: {code}");
println!("message: {message}");
if code == "session_not_found"
|| code == "session_unrecoverable"
|| code == "session_id_ambiguous"
{
2
} else {
1
}
}
}
}
fn send_to_broker(request: BrokerRequest) -> Result<BrokerResponse> {
let root = store::state_root()?;
// Client commands are stateless; broker keeps the long-lived session state.
ensure_broker_available(&root)?;
request_once(&root, &request)
}
fn ensure_broker_available(root: &Path) -> Result<()> {
store::ensure_state_dirs(root)?;
match ping_broker_status(root)? {
BrokerPingStatus::Compatible => return Ok(()),
BrokerPingStatus::Incompatible => {
// A running but incompatible broker (older/newer wire format) must be removed,
// otherwise a stale process can keep the root lock and prevent bootstrap.
restart_incompatible_broker(root)?;
}
BrokerPingStatus::Unavailable => {}
}
// Lazy bootstrap: spawn hidden broker subcommand from the same binary.
let exe = std::env::current_exe().context("failed to locate current executable")?;
let broker_stderr =
BrokerStderrLog::new().context("failed to allocate broker stderr capture")?;
let broker_stderr_writer = broker_stderr
.writer()
.context("failed to prepare broker stderr capture")?;
let mut child = Command::new(exe)
.arg("broker")
.arg("--state-root")
.arg(root)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(broker_stderr_writer))
.spawn()
.context("failed to start broker process")?;
for _ in 0..60 {
if matches!(ping_broker_status(root)?, BrokerPingStatus::Compatible) {
return Ok(());
}
if let Some(status) = child.try_wait().context("failed to poll broker process")? {
let stderr = read_broker_stderr(&broker_stderr);
if stderr.is_empty() {
anyhow::bail!("broker exited before becoming ready ({status})");
}
anyhow::bail!("broker exited before becoming ready ({status}): {stderr}");
}
thread::sleep(Duration::from_millis(50));
}
let stderr = read_broker_stderr(&broker_stderr);
if stderr.is_empty() {
anyhow::bail!("broker failed to start");
}
anyhow::bail!("broker failed to start: {stderr}")
}
fn read_broker_stderr(stderr_log: &BrokerStderrLog) -> String {
stderr_log.read()
}
struct BrokerStderrLog {
path: PathBuf,
}
impl BrokerStderrLog {
fn new() -> Result<Self> {
let mut path = std::env::temp_dir();
path.push(format!(
"contd-broker-stderr-{}-{}.log",
std::process::id(),
random::<u64>()
));
let _ = File::options()
.create_new(true)
.write(true)
.open(&path)
.with_context(|| format!("failed to create {}", path.display()))?;
Ok(Self { path })
}
fn writer(&self) -> Result<File> {
File::options()
.append(true)
.open(&self.path)
.with_context(|| format!("failed to open {}", self.path.display()))
}
fn read(&self) -> String {
let raw = match fs::read_to_string(&self.path) {
Ok(raw) => raw,
Err(_) => return String::new(),
};
raw.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.collect::<Vec<_>>()
.join(" | ")
}
}
impl Drop for BrokerStderrLog {
fn drop(&mut self) {
let _ = fs::remove_file(&self.path);
}
}
enum BrokerPingStatus {
Compatible,
Incompatible,
Unavailable,
}
fn ping_broker_status(root: &Path) -> Result<BrokerPingStatus> {
match request_once(root, &BrokerRequest::Ping) {
Ok(BrokerResponse::Pong { version }) => {
if version == BROKER_API_VERSION {
Ok(BrokerPingStatus::Compatible)
} else {
Ok(BrokerPingStatus::Incompatible)
}
}
Ok(_) => Ok(BrokerPingStatus::Incompatible),
Err(err) => {
let message = err.to_string();
if message.contains("failed to decode broker response") {
return Ok(BrokerPingStatus::Incompatible);
}
Ok(BrokerPingStatus::Unavailable)
}
}
}
fn restart_incompatible_broker(root: &Path) -> Result<()> {
#[cfg(target_os = "linux")]
{
let _ = stop_brokers_for_roots(&[root.to_path_buf()])?;
}
let socket_path = store::broker_socket(root);
if socket_path.exists() {
let _ = fs::remove_file(&socket_path);
}
Ok(())
}
fn request_once(root: &Path, request: &BrokerRequest) -> Result<BrokerResponse> {
store::ensure_state_dirs(root)?;
let socket_path = store::broker_socket(root);
let mut stream = connect_with_timeout(&socket_path, Duration::from_millis(300))?;
let response_timeout = rpc_timeout_for(request);
stream
.set_read_timeout(Some(response_timeout))
.context("failed to set broker read timeout")?;
stream
.set_write_timeout(Some(Duration::from_secs(2)))
.context("failed to set broker write timeout")?;
let encoded = serde_json::to_vec(request).context("failed to encode request")?;
stream
.write_all(&encoded)
.with_context(|| format!("failed to write request to {}", socket_path.display()))?;
stream
.shutdown(Shutdown::Write)
.with_context(|| format!("failed to shutdown write side of {}", socket_path.display()))?;
let mut raw = Vec::new();
stream
.read_to_end(&mut raw)
.with_context(|| format!("failed to read response from {}", socket_path.display()))?;
let response = serde_json::from_slice::<BrokerResponse>(&raw)
.context("failed to decode broker response")?;
Ok(response)
}
fn connect_with_timeout(socket_path: &Path, timeout: Duration) -> Result<UnixStream> {
let deadline = Instant::now() + timeout;
loop {
match UnixStream::connect(socket_path) {
Ok(stream) => return Ok(stream),
Err(err) => {
if Instant::now() >= deadline {
return Err(err).with_context(|| {
format!(
"timed out connecting to broker socket {}",
socket_path.display()
)
});
}
thread::sleep(Duration::from_millis(20));
}
}
}
}
fn rpc_timeout_for(request: &BrokerRequest) -> Duration {
match request {
// Boundary detection for interactive sessions can legitimately take longer
// (for example, sleep before returning to stdin or natural process exit).
BrokerRequest::Run {
yield_timeout_ms: Some(timeout_ms),
..
}
| BrokerRequest::Attach {
yield_timeout_ms: Some(timeout_ms),
..
} => Duration::from_millis(*timeout_ms).saturating_add(Duration::from_secs(5)),
BrokerRequest::Run { .. } | BrokerRequest::Attach { .. } => Duration::from_secs(300),
BrokerRequest::Kill { .. }
| BrokerRequest::List { .. }
| BrokerRequest::Gc
| BrokerRequest::Ping => Duration::from_secs(8),
}
}
fn read_stdin_if_piped() -> Result<String> {
if io::stdin().is_terminal() {
return Ok(String::new());
}
let mut input = String::new();
io::stdin()
.read_to_string(&mut input)
.context("failed to read stdin")?;
Ok(input)
}
fn decode_cli_input_escapes(value: &str) -> Result<String> {
let mut out = String::with_capacity(value.len());
let mut chars = value.chars();
while let Some(ch) = chars.next() {
if ch != '\\' {
out.push(ch);
continue;
}
let Some(next) = chars.next() else {
anyhow::bail!("invalid --input escape: trailing backslash");
};
match next {
'n' => out.push('\n'), // newline (LF, 0x0A)
'r' => out.push('\r'), // carriage return / Enter (CR, 0x0D)
't' => out.push('\t'), // horizontal tab (HT, 0x09)
'b' => out.push('\u{0008}'), // backspace (BS, 0x08)
'f' => out.push('\u{000c}'), // form feed (FF, 0x0C)
'v' => out.push('\u{000b}'), // vertical tab (VT, 0x0B)
'0' => out.push('\0'), // NUL byte (0x00)
'e' => out.push('\u{001b}'), // escape (ESC, 0x1B)
'\\' => out.push('\\'), // literal backslash
'"' => out.push('"'), // literal double quote
'\'' => out.push('\''), // literal single quote
'x' => {
// \xHH: one raw byte in hex (useful for ESC sequences like \x1b[A).
let h1 = chars.next().ok_or_else(|| {
anyhow::anyhow!("invalid --input escape: \\x expects 2 hex digits")
})?;
let h2 = chars.next().ok_or_else(|| {
anyhow::anyhow!("invalid --input escape: \\x expects 2 hex digits")
})?;
let byte = parse_hex_byte(h1, h2)?;
out.push(byte as char);
}
'u' => {
// \u{...}: Unicode scalar, e.g. \u{2191} for ↑.
let open = chars
.next()
.ok_or_else(|| anyhow::anyhow!("invalid --input escape: \\u expects '{{'"))?;
if open != '{' {
anyhow::bail!("invalid --input escape: \\u expects '{{...}}'");
}
let mut hex = String::new();
loop {
let c = chars.next().ok_or_else(|| {
anyhow::anyhow!("invalid --input escape: missing '}}' for \\u{{...}}")
})?;
if c == '}' {
break;
}
if !c.is_ascii_hexdigit() {
anyhow::bail!("invalid --input escape: \\u{{...}} only accepts hex digits");
}
if hex.len() >= 6 {
anyhow::bail!("invalid --input escape: \\u{{...}} too long");
}
hex.push(c);
}
if hex.is_empty() {
anyhow::bail!("invalid --input escape: \\u{{...}} cannot be empty");
}
let scalar = u32::from_str_radix(&hex, 16).with_context(|| {
format!("invalid --input escape: bad unicode scalar \\u{{{hex}}}")
})?;
let ch = char::from_u32(scalar).ok_or_else(|| {
anyhow::anyhow!("invalid --input escape: bad unicode scalar \\u{{{hex}}}")
})?;
out.push(ch);
}
other => anyhow::bail!(
"invalid --input escape: \\{other} (supported: \\\\, \\n, \\r, \\t, \\b, \\f, \\v, \\e, \\0, \\xHH, \\u{{...}}, \\\", \\\')"
),
}
}
Ok(out)
}
fn parse_hex_byte(h1: char, h2: char) -> Result<u8> {
let hex = [h1, h2].iter().collect::<String>();
u8::from_str_radix(&hex, 16)
.with_context(|| format!("invalid --input escape: bad hex byte \\x{hex}"))
}
fn print_detector(detector: &crate::protocol::DetectorSnapshot, verbose: bool) {
println!("pid: {}", detector.pid);
if !verbose {
return;
}
if let Some(stdin_target) = &detector.stdin_target {
println!("stdin tty: {stdin_target}");
}
if let Some(state) = detector.process_state {
println!("proc state: {state}");
}
if let Some(wchan) = &detector.wchan {
println!("wchan: {wchan}");
}
}
fn print_pty_output(output: &str, raw_pty: bool) {
if output.is_empty() {
return;
}
println!();
println!("{}", style("output:", COLOR_CYAN, false));
// Default mode sanitizes terminal-control sequences that can corrupt shell UI.
// `--raw-pty` renders through a virtual VT screen so control sequences stay scoped.
let rendered = if raw_pty {
render_framed_vt100_output(output)
} else {
sanitize_terminal_output(output)
};
print!("{rendered}");
if !rendered.ends_with('\n') {
println!();
}
let _ = io::stdout().flush();
}
fn sanitize_terminal_output(input: &str) -> String {
let bytes = input.as_bytes();
let mut out = String::with_capacity(input.len());
let mut i = 0usize;
while i < bytes.len() {
let b = bytes[i];
if b == 0x1b {
if let Some((seq_end, final_byte)) = parse_csi_sequence(bytes, i) {
// Keep SGR color/style sequences (CSI ... m), escape screen-control sequences.
if final_byte == b'm' {
out.push_str(&String::from_utf8_lossy(&bytes[i..seq_end]));
} else {
out.push_str(&escape_bytes(&bytes[i..seq_end]));
}
i = seq_end;
continue;
}
out.push_str("\\x1b");
i += 1;
continue;
}
// Keep common layout controls; escape the rest to avoid terminal corruption.
if b == b'\n' || b == b'\r' || b == b'\t' || (0x20..=0x7e).contains(&b) {
out.push(b as char);
} else {
out.push_str(&format!("\\x{b:02x}"));
}
i += 1;
}
out
}
fn render_framed_vt100_output(input: &str) -> String {
const COLS: u16 = 80;
let rows = estimate_vt_rows(input, COLS as usize);
let mut parser = VtParser::new(rows, COLS, 0);
parser.process(input.as_bytes());
let screen = parser.screen();
let lines = trim_trailing_blank_lines(screen.contents());
frame_lines(&lines, COLS as usize)
}
fn estimate_vt_rows(input: &str, cols: usize) -> u16 {
let mut plain_bytes = 0usize;
let mut line_breaks = 1usize;
for b in input.bytes() {
if b == b'\n' {
line_breaks += 1;
} else if (0x20..=0x7e).contains(&b) || b == b'\t' {
plain_bytes += 1;
}
}
let wraps = plain_bytes / cols.max(1);
let estimated = line_breaks.saturating_add(wraps).saturating_add(8);
estimated.clamp(8, u16::MAX as usize) as u16
}
fn trim_trailing_blank_lines(contents: String) -> Vec<String> {
let mut lines: Vec<String> = contents
.lines()
.map(|line| line.trim_end().to_string())
.collect();
while lines.last().is_some_and(|line| line.is_empty()) {
lines.pop();
}
if lines.is_empty() {
lines.push(String::new());
}
lines
}
fn frame_lines(lines: &[String], width: usize) -> String {
let mut out = String::new();
out.push('+');
out.push_str(&"-".repeat(width));
out.push('+');
out.push('\n');
for line in lines {
out.push('|');
out.push_str(&fit_to_width(line, width));
out.push('|');
out.push('\n');
}
out.push('+');
out.push_str(&"-".repeat(width));
out.push('+');
out
}
fn fit_to_width(line: &str, width: usize) -> String {
let mut out = String::new();
for ch in line.chars().take(width) {
out.push(ch);
}
let len = out.chars().count();
if len < width {
out.push_str(&" ".repeat(width - len));
}
out
}
fn parse_csi_sequence(bytes: &[u8], start: usize) -> Option<(usize, u8)> {
if start + 1 >= bytes.len() || bytes[start + 1] != b'[' {
return None;
}
let mut idx = start + 2;
while idx < bytes.len() {
let b = bytes[idx];
// CSI final byte range in ANSI escape grammar.
if (0x40..=0x7e).contains(&b) {
return Some((idx + 1, b));
}
idx += 1;
}
None
}
fn escape_bytes(bytes: &[u8]) -> String {
let mut escaped = String::new();
for b in bytes {
escaped.push_str(&format!("\\x{b:02x}"));
}
escaped
}
fn render_session_tree(sessions: &[SessionSummary], list_highlight_prefix: Option<&str>) {
if sessions.is_empty() {
println!("(none)");
return;
}
for (index, session) in sessions.iter().enumerate() {
let last = index + 1 == sessions.len();
let branch = if last { "└─" } else { "├─" };
let indent = if last { " " } else { "│ " };
let state = state_label(&session.state);
println!(
"{branch} {} {}",
render_session_id(&session.session_id, list_highlight_prefix),
style(state, state_color(&session.state), true)
);
render_summary_block(session, indent);
}
}
fn render_session_id(session_id: &str, list_highlight_prefix: Option<&str>) -> String {
let Some(prefix) = list_highlight_prefix else {
return style(session_id, COLOR_CYAN, true);
};
if prefix.is_empty() {
return style(session_id, COLOR_CYAN, true);
}
if let Some(rest) = session_id.strip_prefix(prefix) {
if !io::stdout().is_terminal() {
return session_id.to_string();
}
let matched = style_underline(prefix, COLOR_RED);
let rest = style(rest, COLOR_CYAN, true);
return format!("{matched}{rest}");
}
style(session_id, COLOR_CYAN, true)
}
fn render_summary_block(session: &SessionSummary, indent: &str) {