Repository navigation
Expand file tree
/
Copy pathterminal.rs
More file actions
4338 lines (3974 loc) · 152 KB
/
Copy pathterminal.rs
File metadata and controls
4338 lines (3974 loc) · 152 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
//! Terminal launching, script creation, and process management.
//!
//!
//! Handles:
//! - Terminal preset resolution (kitty, wezterm, tmux, etc.)
//! - Bash script creation for tool launches
//! - Terminal process spawning (new window, same terminal, background)
//! - Kill/close operations for managed terminals
use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, Instant};
use anyhow::{Context, Result, anyhow, bail};
use crate::paths;
use crate::shared::constants::HCOM_IDENTITY_VARS;
use crate::shared::platform;
use crate::shared::terminal_presets::{ArgvTemplate, TERMINAL_ENV_MAP};
use crate::shared::tool_detection::tool_marker_vars;
/// Result of kill_process().
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KillResult {
Sent,
AlreadyDead,
PermissionDenied,
}
const TERMINAL_CLOSE_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PaneCloseResult {
pub closed: bool,
pub retry_command: Option<String>,
}
fn format_close_command(argv: &[String]) -> String {
argv.iter()
.map(|arg| {
#[cfg(windows)]
{
if !arg.is_empty()
&& arg
.chars()
.all(|c| c.is_ascii_alphanumeric() || "/_-.=:,@\\".contains(c))
{
arg.clone()
} else {
ps_quote(arg)
}
}
#[cfg(not(windows))]
{
crate::tools::args_common::shell_quote(arg)
}
})
.collect::<Vec<_>>()
.join(" ")
}
/// Terminal info resolved for an instance.
#[derive(Debug, Clone, Default)]
pub struct TerminalInfo {
pub preset_name: String,
pub pane_id: String,
pub process_id: String,
pub kitty_listen_on: String,
pub terminal_id: String,
pub zellij_session_name: String,
}
/// Result from launch_terminal.
#[derive(Debug)]
pub enum LaunchResult {
/// Background mode: (log_file_path, pid)
Background(String, u32),
/// Success (run_here or new window)
Success,
/// Failed
Failed(String),
}
/// macOS app bundle fallback commands for cross-platform terminals.
/// Used when CLI binary isn't in PATH but .app bundle is installed.
const MACOS_APP_FALLBACKS: &[(&str, ArgvTemplate)] = &[
(
"kitty-window",
&["open", "-n", "-a", "kitty.app", "--args", "{script}"],
),
(
"wezterm-window",
&[
"open",
"-n",
"-a",
"WezTerm.app",
"--args",
"start",
"--",
"bash",
"{script}",
],
),
(
"alacritty",
&[
"open",
"-n",
"-a",
"Alacritty.app",
"--args",
"-e",
"bash",
"{script}",
],
),
];
/// Terminal context vars stripped from the env before spawning a terminal launcher subprocess.
/// Prevents outer terminal identity from leaking into newly-launched terminal panes.
/// Must stay in sync with every env var read by detect_terminal_from_env().
pub(crate) const TERMINAL_CONTEXT_VARS: &[&str] = &[
// Multiplexers
"CMUX_WORKSPACE_ID",
"CMUX_SURFACE_ID",
"TMUX_PANE",
"ZELLIJ_PANE_ID",
// GPU/rich terminals
"KITTY_WINDOW_ID",
"KITTY_PID",
"KITTY_LISTEN_ON",
"WEZTERM_PANE",
"WAVETERM_BLOCKID",
// Bare terminal emulators
"GHOSTTY_RESOURCES_DIR",
"ITERM_SESSION_ID",
"ALACRITTY_WINDOW_ID",
"PTYXIS_PROFILE",
"PTYXIS_VERSION",
"GNOME_TERMINAL_SCREEN",
"KONSOLE_DBUS_WINDOW",
"TERMINATOR_UUID",
"TILIX_ID",
"WT_SESSION",
// HERDR_* not stripped: the herdr preset's CLI (`herdr tab create` /
// `herdr pane run ...`) resolves its server socket from $HERDR_SOCKET_PATH;
// the delivery loop also reuses it for `pane.rename` / `pane.report_agent`.
// Other presets pass the socket via CLI flag (e.g. `kitty @ --to
// {kitty_listen}`) and don't need their identity vars to survive in the
// launcher env.
// Generic terminal identity
"TERM_PROGRAM",
"TERM_SESSION_ID",
];
/// Terminal color/capability vars should come from the terminal/PTY that hosts
/// the child. Forwarding a parent's `TERM=dumb`, test-harness `NO_COLOR`, or
/// stale truecolor state into a new kitty pane can make otherwise-capable tools
/// render in black and white.
pub(crate) const TERMINAL_COLOR_VARS: &[&str] = &[
"TERM",
"COLORTERM",
"NO_COLOR",
"CLICOLOR",
"CLICOLOR_FORCE",
"FORCE_COLOR",
];
/// Detect terminal preset from inherited environment variables.
/// Used for same-terminal PTY launches (run_here=True) to enable close-on-kill.
/// Checks built-in env map first, then TOML presets with pane_id_env defined.
pub fn detect_terminal_from_env() -> Option<String> {
// Built-in mappings
for &(env_var, preset_name) in TERMINAL_ENV_MAP {
if std::env::var(env_var)
.ok()
.filter(|v| !v.is_empty())
.is_some()
{
return Some(preset_name.to_string());
}
}
// TOML-defined presets with pane_id_env
let toml_path = crate::paths::config_toml_path();
if let Some(presets_val) = crate::config::load_toml_presets(&toml_path)
&& let Some(table) = presets_val.as_table()
{
for (name, val) in table {
if let Some(env_var) = val.get("pane_id_env").and_then(|v| v.as_str())
&& std::env::var(env_var)
.ok()
.filter(|v| !v.is_empty())
.is_some()
{
return Some(name.clone());
}
}
}
// TERM_PROGRAM value-based detection (terminals without a unique env var)
if let Ok(term_prog) = std::env::var("TERM_PROGRAM") {
match term_prog.as_str() {
"ghostty" => return Some("ghostty".to_string()),
"iTerm.app" => return Some("iterm".to_string()),
"Apple_Terminal" => return Some("terminal.app".to_string()),
"WarpTerminal" => return Some("warp".to_string()),
_ => {}
}
}
None
}
/// Find macOS .app bundle in common locations.
fn find_macos_app(name: &str) -> Option<PathBuf> {
let app_name = if name.ends_with(".app") {
name.to_string()
} else {
format!("{}.app", name)
};
let home = std::env::var("HOME").ok()?;
let search_dirs = [
PathBuf::from("/Applications"),
PathBuf::from("/System/Applications"),
PathBuf::from("/System/Applications/Utilities"),
PathBuf::from(home).join("Applications"),
];
for base in &search_dirs {
let app_path = base.join(&app_name);
if app_path.exists() {
return Some(app_path);
}
}
None
}
/// Replace `open -a <app>` app names with absolute `.app` bundle paths, in place
/// on an argv vector.
///
/// This is only safe for app-launch commands where `open` passes argv via
/// `--args`. Plain file-open forms like `open -a Terminal {script}` must keep
/// `-a`, otherwise `open` treats the app bundle and script as regular paths and
/// falls back to file association for the script. No-ops if no `--args` tail is
/// present or no app flag is found.
fn rewrite_open_argv_with_app_path(argv: &mut Vec<String>, app_path: &Path) {
for idx in 0..argv.len().saturating_sub(1) {
let flag = &argv[idx];
let takes_app_arg = flag == "-a"
|| (flag.starts_with('-')
&& !flag.starts_with("--")
&& flag.chars().skip(1).any(|c| c == 'a'));
if takes_app_arg {
let has_args_tail = argv.iter().skip(idx + 2).any(|part| part == "--args");
if !has_args_tail {
return;
}
let app_path_str = app_path.to_string_lossy().to_string();
if flag == "-a" {
argv.remove(idx);
argv[idx] = app_path_str;
} else {
let mut rewritten_flag = String::from("-");
for ch in flag.chars().skip(1) {
if ch != 'a' {
rewritten_flag.push(ch);
}
}
if rewritten_flag == "-" {
argv.remove(idx);
argv[idx] = app_path_str;
} else {
argv[idx] = rewritten_flag;
argv[idx + 1] = app_path_str;
}
}
return;
}
}
}
fn rewrite_macos_open_app_argv(argv: &mut Vec<String>, app_name: &str) {
if !cfg!(target_os = "macos") {
return;
}
if let Some(app_path) = find_macos_app(app_name) {
rewrite_open_argv_with_app_path(argv, &app_path);
}
}
fn should_use_command_extension(background: bool, terminal_mode: &str) -> bool {
!background
&& cfg!(target_os = "macos")
&& (terminal_mode == "default" || terminal_mode == "terminal.app")
}
/// Find kitten binary — PATH first, then macOS app bundle.
fn find_kitten_binary() -> Option<String> {
if let Some(path) = which_bin("kitten") {
return Some(path);
}
if cfg!(target_os = "macos")
&& let Some(app) = find_macos_app("kitty")
{
let full = app.join("Contents/MacOS/kitten");
if full.exists() {
return Some(full.to_string_lossy().to_string());
}
}
None
}
/// Find a reachable kitty remote control socket.
pub fn find_kitty_socket() -> String {
let kitten = match find_kitten_binary() {
Some(k) => k,
None => return String::new(),
};
// Find candidate sockets
let mut candidates: Vec<PathBuf> = Vec::new();
if let Ok(entries) = fs::read_dir("/tmp") {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if name.starts_with("kitty") {
candidates.push(entry.path());
}
}
}
candidates.sort_by(|a, b| b.cmp(a)); // Reverse sort (newest first)
for sock_path in &candidates {
// Skip anything that isn't a Unix-domain socket
if !crate::sys::fs::is_socket(sock_path) {
continue;
}
let socket_uri = format!("unix:{}", sock_path.display());
if let Ok(output) = Command::new(&kitten)
.args(["@", "--to", &socket_uri, "ls"])
.output()
&& output.status.success()
{
return socket_uri;
}
}
String::new()
}
fn resolve_kitty_remote_socket(kitty_socket: &str) -> String {
if !kitty_socket.is_empty() {
return kitty_socket.to_string();
}
std::env::var("KITTY_LISTEN_ON")
.ok()
.filter(|v| !v.is_empty())
.unwrap_or_else(find_kitty_socket)
}
fn normalize_terminal_mode_for_launch(
mut terminal_mode: String,
opens_new_window: bool,
run_here: bool,
) -> (String, String) {
let mut kitty_socket = String::new();
if opens_new_window {
if terminal_mode == "default"
&& let Some(detected) = detect_terminal_from_env()
// Ptyxis is commonly installed as a Flatpak. Such shells export
// PTYXIS_VERSION even when no host-side `ptyxis` launcher exists,
// so environment detection alone is not enough to launch a new
// window. Keep `default` in that case and use the normal Linux
// fallback selection below. A configured `ptyxis.binary` override
// (for example, a wrapper around `flatpak run`) is honored.
&& (detected != "ptyxis"
|| crate::config::get_merged_preset("ptyxis")
.and_then(|preset| preset.binary)
.is_some_and(|binary| which_bin(&binary).is_some()))
{
terminal_mode = detected;
}
if terminal_mode == "kitty" {
if std::env::var("KITTY_WINDOW_ID")
.ok()
.filter(|v| !v.is_empty())
.is_some()
{
// Inside kitty — use split, but still need socket for --to injection
kitty_socket = resolve_kitty_remote_socket(&kitty_socket);
terminal_mode = "kitty-split".to_string();
} else {
kitty_socket = find_kitty_socket();
terminal_mode = if kitty_socket.is_empty() {
"kitty-window".to_string()
} else {
"kitty-tab".to_string()
};
}
} else if terminal_mode == "wezterm" {
if std::env::var("WEZTERM_PANE")
.ok()
.filter(|v| !v.is_empty())
.is_some()
{
terminal_mode = "wezterm-split".to_string();
} else if wezterm_reachable() {
terminal_mode = "wezterm-tab".to_string();
} else {
terminal_mode = "wezterm-window".to_string();
}
}
if terminal_mode == "kitty-tab" || terminal_mode == "kitty-split" {
kitty_socket = resolve_kitty_remote_socket(&kitty_socket);
}
} else if run_here {
if let Some(detected) = detect_terminal_from_env() {
terminal_mode = detected;
} else if terminal_mode == "here" {
terminal_mode = "default".to_string();
}
}
(terminal_mode, kitty_socket)
}
pub fn resolve_terminal_mode_for_tips(
terminal: Option<&str>,
config_terminal: &str,
background: bool,
run_here: bool,
) -> (String, bool) {
let explicit_terminal = terminal.filter(|t| !t.is_empty()).or_else(|| {
(config_terminal != "default" && !config_terminal.is_empty()).then_some(config_terminal)
});
let requested = explicit_terminal.unwrap_or("default").to_string();
let (resolved, _) =
normalize_terminal_mode_for_launch(requested, !background && !run_here, run_here);
(
resolved.clone(),
explicit_terminal.is_none() && resolved != "default",
)
}
/// Check if a wezterm mux server is reachable.
pub fn wezterm_reachable() -> bool {
Command::new("wezterm")
.args(["cli", "list"])
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
/// Candidate file names to probe for `name` in a PATH directory. On Windows an
/// extension-less name is expanded with PATHEXT (`.exe`, `.cmd`, …); elsewhere
/// the name is used verbatim.
pub(crate) fn which_candidates(dir: &Path, name: &str) -> Vec<std::path::PathBuf> {
#[cfg(windows)]
{
if Path::new(name).extension().is_some() {
return vec![dir.join(name)];
}
let exts = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string());
let mut out: Vec<std::path::PathBuf> = exts
.split(';')
.filter(|e| !e.is_empty())
.map(|ext| dir.join(format!("{name}{ext}")))
.collect();
out.push(dir.join(name));
out
}
#[cfg(not(windows))]
{
vec![dir.join(name)]
}
}
/// Per-user bin dirs searched after PATH, in order.
///
/// Tool-specific dirs are where each official installer puts its binary.
/// `~/.local/bin` is the default for Codex, Copilot, Qoder, agy, OMP, Cursor, Pi and
/// Claude's native installer; `~/.bun/bin` is where `bun install -g` links
/// npm-published CLIs (pi, omp, opencode, gemini, ...).
fn fallback_bin_dirs(home: &Path, name: &str) -> Vec<std::path::PathBuf> {
const LOCAL: &[&str] = &[".local", "bin"];
const BUN: &[&str] = &[".bun", "bin"];
let dirs: &[&[&str]] = match name {
// Native installer (~/.local/bin) before the legacy ~/.claude/bin copy.
"claude" => &[&[".claude", "local"], LOCAL, &[".claude", "bin"], BUN],
"opencode" => &[&[".opencode", "bin"], LOCAL, BUN],
"kilo" => &[&[".kilo", "bin"], LOCAL, BUN],
"grok" => &[&[".grok", "bin"], LOCAL, BUN],
"kimi" => &[&[".kimi-code", "bin"], LOCAL, BUN],
"pi" => &[&[".pi", "agent", "bin"], LOCAL, BUN],
_ => &[LOCAL, BUN],
};
dirs.iter()
.map(|parts| {
parts
.iter()
.fold(home.to_path_buf(), |p, part| p.join(part))
})
.collect()
}
fn which_in_fallback_dirs(home: &Path, name: &str) -> Option<String> {
fallback_bin_dirs(home, name)
.iter()
.flat_map(|dir| which_candidates(dir, name))
.find(|candidate| candidate.is_file())
.map(|candidate| candidate.to_string_lossy().to_string())
}
/// Simple `which` implementation — find binary in PATH.
pub fn which_bin(name: &str) -> Option<String> {
// `split_paths` uses the platform separator (`;` on Windows, `:` elsewhere),
// which also avoids splitting Windows drive letters like `C:`. PATH being
// entirely unset (rather than merely lacking `name`) still falls through
// to the well-known-location fallbacks below.
if let Some(path_var) = std::env::var_os("PATH") {
for dir in std::env::split_paths(&path_var) {
for candidate in which_candidates(&dir, name) {
if candidate.is_file() {
return Some(candidate.to_string_lossy().to_string());
}
}
}
}
// Fallback: install locations that are often missing from PATH (GUI or
// hook-spawned shells, or the user never added them).
if let Some(found) = dirs::home_dir().and_then(|home| which_in_fallback_dirs(&home, name)) {
return Some(found);
}
#[cfg(windows)]
if name.eq_ignore_ascii_case("agy")
&& let Some(local_app_data) = std::env::var_os("LOCALAPPDATA")
{
let fallback = Path::new(&local_app_data)
.join("agy")
.join("bin")
.join("agy.exe");
if fallback.is_file() {
return Some(fallback.to_string_lossy().into_owned());
}
}
None
}
/// Build a command for a PATH-resolved executable, including Windows npm
/// `.cmd`/`.bat` shims that CreateProcess cannot execute directly.
pub fn executable_command(name: &str) -> Command {
let resolved = which_bin(name).unwrap_or_else(|| name.to_string());
#[cfg(windows)]
if Path::new(&resolved)
.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat"))
{
let mut command = Command::new("cmd.exe");
command.args(["/d", "/c"]).arg(resolved);
return command;
}
Command::new(resolved)
}
/// Bypass npm's Windows `codex.cmd` shim when launching the interactive tool.
///
/// The shim expands `%*` through cmd.exe, which corrupts quote-bearing config
/// values such as the multiline `developer_instructions` bootstrap. Invoking
/// the package's Node entrypoint directly preserves Rust's argv boundaries.
#[cfg(windows)]
pub fn resolve_windows_tool_launcher(tool: &str, resolved: &str) -> Option<(String, Vec<String>)> {
if tool != "codex"
|| !Path::new(resolved)
.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| ext.eq_ignore_ascii_case("cmd"))
{
return None;
}
let prefix = Path::new(resolved).parent()?;
let entrypoint = prefix.join("node_modules/@openai/codex/bin/codex.js");
if !entrypoint.is_file() {
return None;
}
let node = which_bin("node")?;
Some((node, vec![entrypoint.to_string_lossy().into_owned()]))
}
/// Resolve the `bash` command to run on Unix, preferring a `PATH` match and
/// falling back to `/bin/bash`. Shared by the background and run-here launch
/// paths so they can't drift on which `bash` gets invoked.
fn resolve_bash_command() -> String {
which_bin("bash").unwrap_or_else(|| "/bin/bash".to_string())
}
/// Check if a file has a node shebang (#!/usr/bin/env node or similar).
/// Used on Termux to detect npm-installed tools that need `node <path>` rewrite.
pub fn has_node_shebang(path: &str) -> bool {
use std::io::Read;
let Ok(mut f) = std::fs::File::open(path) else {
return false;
};
let mut buf = [0u8; 64];
let Ok(n) = f.read(&mut buf) else {
return false;
};
let header = String::from_utf8_lossy(&buf[..n]);
header.starts_with("#!") && header.contains("node")
}
const TERMUX_CODEX_WRAPPER_PATH: &str = "/data/data/com.termux/files/usr/bin/codex";
const TERMUX_CODEX_INNER_WRAPPER_PATH: &str =
"/data/data/com.termux/files/usr/lib/node_modules/@mmmbuto/codex-cli-termux/bin/codex";
const TERMUX_SH_PATH: &str = "/data/data/com.termux/files/usr/bin/sh";
const TERMUX_PREFIX: &str = "/data/data/com.termux/files/usr";
/// Whether the host Termux installation is visible from this process.
///
/// This is intentionally broader than `is_native_termux_runtime()`: PRoot
/// exposes host Termux paths and environment variables inside the distro.
fn termux_host_visible() -> bool {
platform::is_termux()
}
fn native_termux_prefix() -> bool {
std::env::var("PREFIX")
.ok()
.is_some_and(|prefix| Path::new(&prefix) == Path::new(TERMUX_PREFIX))
}
fn proc_self_root_is_root() -> bool {
fs::read_link("/proc/self/root").is_ok_and(|root| root == Path::new("/"))
}
fn is_native_termux_runtime_from(
is_android_target: bool,
host_visible: bool,
has_native_prefix: bool,
self_root_is_root: bool,
) -> bool {
is_android_target && host_visible && has_native_prefix && self_root_is_root
}
/// Whether this process can safely dispatch scripts into native Termux.
fn is_native_termux_runtime() -> bool {
is_native_termux_runtime_from(
cfg!(target_os = "android"),
termux_host_visible(),
native_termux_prefix(),
proc_self_root_is_root(),
)
}
fn proot_termux_launch_error() -> &'static str {
"Cannot open a native Termux window from this PRoot runtime:\n\
the generated command uses PRoot paths and Linux/glibc binaries that cannot run\n\
in host Termux.\n\n\
Use one of:\n\
hcom <tool> --headless\n\
hcom <tool> --terminal tmux"
}
fn validate_termux_dispatch_status(status: std::process::ExitStatus) -> Result<()> {
if status.success() {
Ok(())
} else {
bail!("Termux RUN_COMMAND dispatch failed: {status}")
}
}
/// Resolve Termux-only tool launch quirks.
///
/// Most npm-installed tools can run as `node <wrapper.js> ...`, but the
/// third-party `codex-cli-termux` wrapper breaks in stripped `RUN_COMMAND`
/// environments when its JS wrapper tries to spawn the nested shell wrapper
/// directly. Bypass that path by invoking the inner wrapper with `sh`.
pub fn resolve_termux_tool_launcher(
tool_name: &str,
resolved: &str,
) -> Option<(String, Vec<String>)> {
if !is_native_termux_runtime() {
return None;
}
if tool_name == "codex"
&& resolved == TERMUX_CODEX_WRAPPER_PATH
&& Path::new(TERMUX_CODEX_INNER_WRAPPER_PATH).exists()
{
let sh = which_bin("sh").unwrap_or_else(|| TERMUX_SH_PATH.to_string());
return Some((sh, vec![TERMUX_CODEX_INNER_WRAPPER_PATH.to_string()]));
}
if has_node_shebang(resolved) {
let node = which_bin("node").unwrap_or_else(|| platform::TERMUX_NODE_PATH.to_string());
return Some((node, vec![resolved.to_string()]));
}
None
}
/// Resolve binary to full path via macOS app bundle fallback.
fn resolve_binary_path(binary: &str, app_name: Option<&str>, preset_name: &str) -> Option<String> {
if which_bin(binary).is_some() {
return None; // Already on PATH
}
if !cfg!(target_os = "macos") {
return None;
}
let app = find_macos_app(app_name.unwrap_or(preset_name))?;
let full_path = app.join("Contents/MacOS").join(binary);
if full_path.exists() {
Some(full_path.to_string_lossy().to_string())
} else {
None
}
}
/// True if `tok` names a bash-family interpreter — its file stem is `bash`
/// (case-insensitive), covering `bash`, `bash.exe`, `/bin/bash`, and
/// `C:\...\bash.exe`.
#[cfg(any(windows, test))]
fn is_bash_interp(tok: &str) -> bool {
std::path::Path::new(tok)
.file_stem()
.and_then(|s| s.to_str())
.is_some_and(|stem| stem.eq_ignore_ascii_case("bash"))
}
/// Detect an unrunnable non-adjacent bash-family `{script}` custom template: a
/// bash-family interpreter token (`bash`, `bash.exe`, `/bin/bash`, …) with a
/// LATER (non-adjacent) `{script}`, so the generated `.ps1` would be handed to
/// bash and can't be rewritten by a simple splice — e.g. `bash -c {script}`,
/// `bash -x {script}`, `bash.exe -i {script}`. Returns the offending
/// interpreter token. Adjacent `<interp> {script}` is handled by
/// `shellify_bash_script_pair` and is NOT flagged.
#[cfg(any(windows, test))]
fn unsupported_bash_script_interp(argv: &[String]) -> Option<String> {
let interp = argv.iter().position(|a| is_bash_interp(a))?;
let script = argv.iter().position(|a| a.contains("{script}"))?;
if script <= interp + 1 {
return None;
}
Some(argv[interp].clone())
}
/// Rewrite an adjacent bash-family `{script}` executor pair to PowerShell in a
/// custom (non-preset) command argv, so the generated `.ps1` runs on Windows
/// without requiring Git Bash on PATH. Matches an adjacent `<interp>` +
/// `{script}` pair anywhere in the argv — not just at argv[0] — where
/// `<interp>` is any bash-family token (`bash`, `bash.exe`, `/bin/bash`, …).
/// A bash-family token with a NON-adjacent `{script}` (e.g. `bash -c {script}`)
/// can't be rewritten by a simple splice — it is rejected with a clear error
/// instead of silently launching a broken command (see
/// `unsupported_bash_script_interp`).
///
/// Off Windows this is a passthrough (the generated script is a bash script).
#[cfg(not(windows))]
fn windows_shellify_custom_argv(argv: Vec<String>) -> Result<Vec<String>> {
Ok(argv)
}
#[cfg(windows)]
fn windows_shellify_custom_argv(argv: Vec<String>) -> Result<Vec<String>> {
if let Some(interp) = unsupported_bash_script_interp(&argv) {
bail!(
"custom terminal command runs `{interp}` with a non-adjacent `{{script}}` and \
cannot run the generated PowerShell script on Windows; use `{interp} {{script}}` \
(adjacent, no flags) or a native command"
);
}
Ok(shellify_bash_script_pair(argv))
}
/// Replace an adjacent bash-family + `{script}` pair with the PowerShell `.ps1`
/// launcher. Platform-agnostic so it can be unit-tested on any host; the
/// `windows_shellify_custom_argv` wrapper only applies it on Windows.
#[cfg(any(windows, test))]
fn shellify_bash_script_pair(mut argv: Vec<String>) -> Vec<String> {
if let Some(i) = argv
.windows(2)
.position(|w| is_bash_interp(&w[0]) && w[1] == "{script}")
{
argv.splice(
i..i + 1,
[
"powershell".to_string(),
"-ExecutionPolicy".to_string(),
"Bypass".to_string(),
"-NoExit".to_string(),
"-File".to_string(),
],
);
}
argv
}
/// Resolve preset name to an open-command argv template (placeholders intact).
///
/// On macOS, if CLI binary isn't in PATH but .app bundle exists,
/// uses a hardcoded fallback or substitutes the full binary path. The returned
/// argv still contains placeholders like `{script}`; substitute via
/// `substitute_open_argv`.
pub fn resolve_terminal_open_argv(preset_name: &str) -> Option<Vec<String>> {
let merged = crate::config::get_merged_preset(preset_name)?;
let mut open_argv = merged.open_argv(cfg!(windows));
let app_name = merged.app_name.as_deref().unwrap_or(preset_name);
if let Some(ref binary) = merged.binary
&& which_bin(binary).is_none()
&& cfg!(target_os = "macos")
{
// New-window presets have hardcoded fallbacks using `open -a`
for &(name, fallback) in MACOS_APP_FALLBACKS {
if name == preset_name && find_macos_app(app_name).is_some() {
let mut argv: Vec<String> = fallback.iter().map(|s| s.to_string()).collect();
rewrite_macos_open_app_argv(&mut argv, app_name);
return Some(argv);
}
}
// Tab/split presets: substitute leading binary element with full path
if let Some(full_path) = resolve_binary_path(binary, Some(app_name), preset_name)
&& open_argv.first().map(String::as_str) == Some(binary.as_str())
{
open_argv[0] = full_path;
}
}
rewrite_macos_open_app_argv(&mut open_argv, app_name);
Some(open_argv)
}
/// Inject `--to <socket>` (after the `@`) for kitten commands launched outside
/// kitty. Splices as separate argv elements — no shell quoting.
///
/// Matches `argv[0]`'s file_stem (not an exact string) because
/// `resolve_terminal_open_argv` may have already rewritten `argv[0]` to
/// kitten's absolute macOS app-bundle path when `kitten` isn't on PATH — a
/// literal "kitten" check would miss that and silently skip the splice,
/// leaving kitten without a socket to reach (it then falls back to
/// controlling-tty discovery, which fails outright in tty-less contexts).
fn splice_kitten_to_socket(argv: &mut Vec<String>, kitty_socket: &str) {
let is_kitten_cmd = argv
.first()
.and_then(|a| Path::new(a).file_stem())
.is_some_and(|stem| stem.eq_ignore_ascii_case("kitten"));
if !kitty_socket.is_empty()
&& !kitty_socket.starts_with("fd:")
&& is_kitten_cmd
&& argv.get(1).map(String::as_str) == Some("@")
&& !argv.iter().any(|a| a == "--to")
{
argv.splice(2..2, ["--to".to_string(), kitty_socket.to_string()]);
}
}
/// Target the launcher's WezTerm tab and, for splits, choose placement.
///
/// The launcher env strips `$WEZTERM_PANE`, and without it `wezterm cli`
/// falls back to whichever pane is focused, so agents would land in an
/// unrelated tab. Pin `--pane-id` explicitly.
///
/// WezTerm has no layout engine (unlike kitty's `--type=window`), so for
/// `split-pane` split the largest pane in the launcher's tab along its longer
/// axis. Repeated launches then tile into an even grid instead of each new
/// pane halving the same space. User-supplied target/direction flags win.
fn splice_wezterm_target(
argv: &mut Vec<String>,
launcher_pane: &str,
list_panes: impl FnOnce() -> Option<String>,
) {
let is_wezterm = argv
.first()
.and_then(|a| Path::new(a).file_stem())
.is_some_and(|stem| stem.eq_ignore_ascii_case("wezterm"));
if !is_wezterm || argv.get(1).map(String::as_str) != Some("cli") {
return;
}
let sep = argv.iter().position(|a| a == "--").unwrap_or(argv.len());
let has_flag = |flags: &[&str]| argv[..sep].iter().any(|a| flags.contains(&a.as_str()));
match argv.get(2).map(String::as_str) {
Some("spawn") if !has_flag(&["--pane-id", "--window-id", "--new-window"]) => {
argv.splice(3..3, ["--pane-id".to_string(), launcher_pane.to_string()]);
}
Some("split-pane") if !has_flag(&["--pane-id"]) => {
let directed = has_flag(&[
"--top-level",
"--left",
"--right",
"--top",
"--bottom",
"--horizontal",
]);
let (pane, dir) = if directed {
(launcher_pane.to_string(), None)
} else {
list_panes()
.and_then(|json| pick_wezterm_split(&json, launcher_pane))
.map(|(pane, dir)| (pane, Some(dir)))
.unwrap_or_else(|| (launcher_pane.to_string(), Some("--right")))
};
let mut args = vec!["--pane-id".to_string(), pane];
args.extend(dir.map(String::from));
argv.splice(3..3, args);
}
_ => {}
}
}
fn wezterm_list_panes() -> Option<String> {
let out = Command::new("wezterm")
.args(["cli", "list", "--format", "json"])
.output()
.ok()?;
out.status
.success()
.then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}
/// From `wezterm cli list --format json`, pick the largest pane in the
/// launcher's tab and the split direction along its longer side.
fn pick_wezterm_split(json: &str, launcher_pane: &str) -> Option<(String, &'static str)> {
let panes: Vec<serde_json::Value> = serde_json::from_str(json).ok()?;
let pane_id = |p: &serde_json::Value| p["pane_id"].as_u64().map(|id| id.to_string());
let tab = panes
.iter()
.find(|p| pane_id(p).as_deref() == Some(launcher_pane))?["tab_id"]
.as_u64()?;
let dim = |p: &serde_json::Value, k: &str| p["size"][k].as_u64().unwrap_or(0);
let target = panes
.iter()
.filter(|p| p["tab_id"].as_u64() == Some(tab))
.max_by_key(|p| dim(p, "cols") * dim(p, "rows"))?;
let (pw, ph) = (dim(target, "pixel_width"), dim(target, "pixel_height"));
// Cells are roughly twice as tall as wide when pixel size is unknown.
let wide = if pw > 0 && ph > 0 {
pw >= ph
} else {
dim(target, "cols") >= dim(target, "rows") * 2
};
Some((pane_id(target)?, if wide { "--right" } else { "--bottom" }))
}
/// Get terminal presets for current platform with availability status.
pub fn get_available_presets() -> Vec<(String, bool)> {
let mut result = vec![("default".to_string(), true)];
let system = platform::platform_name();
let mut seen = std::collections::HashSet::new();
for (name, preset) in crate::shared::terminal_presets::TERMINAL_PRESETS.iter() {
if !preset.platforms.contains(&system) {
continue;
}
let available = if let Some(binary) = preset.binary {
let in_path = which_bin(binary).is_some();
if !in_path && system == "Darwin" {
resolve_binary_path(binary, preset.app_name, name).is_some()
} else {
in_path
}
} else if system == "Darwin" {
let app_name = preset.app_name.unwrap_or(name);
find_macos_app(app_name).is_some()
} else {
true
};
result.push((name.to_string(), available));
seen.insert(name.to_string());
}
// Add TOML-defined presets not already in built-ins
let toml_path = crate::paths::config_toml_path();
if let Some(presets_val) = crate::config::load_toml_presets(&toml_path)
&& let Some(table) = presets_val.as_table()
{
for (name, preset_val) in table {
if seen.contains(name) {
continue;
}
let available = preset_val
.get("binary")
.and_then(|v| v.as_str())
.map(|b| which_bin(b).is_some())
.unwrap_or(true);
result.push((name.clone(), available));
}
}
result.push(("custom".to_string(), true));