objectiveai-mcp-laboratory 2.2.12

MCP (Model Context Protocol) filesystem helpers for ObjectiveAI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
const MAX_OUTPUT_CHARS: usize = 30_000;
const MAX_PERSISTED_SIZE: usize = 64 * 1024 * 1024; // 64MB

use std::collections::HashMap;
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
use std::time::Duration;

use dashmap::DashMap;
use tokio::fs;

#[derive(Debug, serde::Serialize)]
pub struct BashOutput {
    pub stdout: String,
    pub stderr: String,
    pub interrupted: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "returnCodeInterpretation")]
    pub return_code_interpretation: Option<String>,
    #[serde(rename = "isImage", skip_serializing_if = "std::ops::Not::not")]
    pub is_image: bool,
    #[serde(skip_serializing_if = "Option::is_none", rename = "persistedOutputPath")]
    pub persisted_output_path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "persistedOutputSize")]
    pub persisted_output_size: Option<u64>,
    #[serde(rename = "noOutputExpected", skip_serializing_if = "std::ops::Not::not")]
    pub no_output_expected: bool,
}

/// Shell state shared by every agent dialing this laboratory MCP. CWD and
/// exported env are kept **per agent-instance-hierarchy (AIH)** so concurrent
/// agents sharing the one container don't trample each other's working
/// directory or environment; the snapshot, tmux socket, and shell path are
/// process-global (the snapshot is the container's static functions/aliases).
#[derive(Debug, Clone)]
pub struct ShellState {
    /// Per-AIH working directory, persisted across that AIH's commands.
    cwds: Arc<DashMap<String, PathBuf>>,
    /// Path to the shell environment snapshot file (functions, aliases, options).
    /// Captured once at session start from the user's shell config.
    snapshot_path: Arc<RwLock<Option<String>>>,
    /// Tmux socket env override. Set once tmux is first used.
    tmux_env: Arc<RwLock<Option<String>>>,
    /// Whether tmux has been used this session.
    tmux_used: Arc<RwLock<bool>>,
    /// The user's shell path (e.g., /bin/bash, /bin/zsh).
    shell_path: String,
    /// Working directory an AIH starts in before it runs anything (env
    /// `OBJECTIVEAI_LABORATORY_CWD`, baked in at `laboratories create`,
    /// defaulting to `/`). Only the first-touch fallback — once an AIH runs a
    /// command its cwd is tracked per-AIH in `cwds`.
    default_cwd: PathBuf,
}

impl ShellState {
    pub fn new(default_cwd: PathBuf) -> Self {
        let shell_path = detect_shell();
        Self {
            cwds: Arc::new(DashMap::new()),
            snapshot_path: Arc::new(RwLock::new(None)),
            tmux_env: Arc::new(RwLock::new(None)),
            tmux_used: Arc::new(RwLock::new(false)),
            shell_path,
            default_cwd,
        }
    }

    /// Initialize the shell snapshot asynchronously.
    /// Should be called once at session start.
    pub async fn init_snapshot(&self) {
        match create_shell_snapshot(&self.shell_path).await {
            Ok(path) => {
                *self.snapshot_path.write().unwrap() = Some(path);
            }
            Err(e) => {
                tracing::warn!("Failed to create shell snapshot: {e}");
            }
        }
    }

    /// This AIH's current working directory, or the laboratory's configured
    /// default the first time the AIH is seen.
    fn get_cwd(&self, aih: &str) -> PathBuf {
        self.cwds
            .get(aih)
            .map(|c| c.clone())
            .unwrap_or_else(|| self.default_cwd.clone())
    }

    fn set_cwd(&self, aih: &str, path: PathBuf) {
        self.cwds.insert(aih.to_string(), path);
    }

    fn get_snapshot_path(&self) -> Option<String> {
        self.snapshot_path.read().unwrap().clone()
    }

    fn mark_tmux_used(&self) {
        *self.tmux_used.write().unwrap() = true;
    }

    fn has_tmux_been_used(&self) -> bool {
        *self.tmux_used.read().unwrap()
    }

    fn get_tmux_env(&self) -> Option<String> {
        self.tmux_env.read().unwrap().clone()
    }

    fn set_tmux_env(&self, value: String) {
        *self.tmux_env.write().unwrap() = Some(value);
    }
}

pub async fn execute_bash(
    shell_state: &ShellState,
    aih: &str,
    command: &str,
    timeout_ms: Option<u64>,
) -> Result<BashOutput, String> {
    // Default 30 minutes, no hard max
    let timeout_ms = timeout_ms.unwrap_or(1_800_000);
    let timeout_duration = Duration::from_millis(timeout_ms);

    // Track tmux usage
    if command.contains("tmux") {
        shell_state.mark_tmux_used();
        if shell_state.get_tmux_env().is_none() {
            if let Ok(socket_path) = init_tmux_socket().await {
                shell_state.set_tmux_env(socket_path);
            }
        }
    }

    // Build the full command string with all session state. cwd + the exported
    // env file are per-AIH; the snapshot is process-global.
    let cwd = shell_state.get_cwd(aih);
    let env_path = env_path_for(aih);
    let snapshot_path = shell_state.get_snapshot_path();
    let has_snapshot = snapshot_path.is_some();

    let mut command_parts: Vec<String> = Vec::new();

    // 1. Source the shell snapshot (if available).
    //
    // EVERY file replay below uses the guarded POSIX dot form
    // `[ -r X ] && . X 2>/dev/null || true` — never bare `source` or
    // bare `.`:
    // - `source` doesn't exist in dash (silently loses the replay on
    //   debian-slim images; busybox ash happens to accept it).
    // - a bare `. X` on a MISSING file ABORTS a non-interactive
    //   dash/ash before `|| true` can apply (POSIX dot is a special
    //   built-in; XCU 2.14/2.8.1) — and the per-AIH env file
    //   legitimately doesn't exist on an AIH's first command. bash
    //   merely returns non-zero, which is how `source … || true`
    //   masked all of this.
    // The `[ -r … ]` guard matches POSIX's "no readable file" abort
    // condition, and the chain stays correct inside the ` && ` join
    // (left-associative: the trailing `|| true` never swallows the
    // next part).
    if let Some(ref snap) = snapshot_path {
        command_parts.push(format!(
            "[ -r {p} ] && . {p} 2>/dev/null || true",
            p = shell_quote(snap)
        ));
    }

    // 1b. Replay the exported env persisted after this AIH's previous
    // command. The file won't exist on the first call — the readable
    // guard shrugs that off (see the dot-abort note above).
    command_parts.push(format!(
        "[ -r {p} ] && . {p} 2>/dev/null || true",
        p = shell_quote(&env_path)
    ));

    // 3. Source CLAUDE_ENV_FILE if set (for venv/conda activation, parent process env persistence)
    if let Ok(env_file) = std::env::var("CLAUDE_ENV_FILE") {
        if !env_file.is_empty() && std::path::Path::new(&env_file).exists() {
            command_parts.push(format!(
                "[ -r {p} ] && . {p} 2>/dev/null || true",
                p = shell_quote(&env_file)
            ));
        }
    }

    // 4. Disable extended glob patterns (security hardening)
    if std::env::var("CLAUDE_CODE_SHELL_PREFIX").is_ok() {
        // When using a shell wrapper, disable extglob for both bash and zsh
        command_parts.push("{ shopt -u extglob || setopt NO_EXTENDED_GLOB; } >/dev/null 2>&1 || true".to_string());
    } else if shell_state.shell_path.contains("bash") {
        command_parts.push("shopt -u extglob 2>/dev/null || true".to_string());
    } else if shell_state.shell_path.contains("zsh") {
        command_parts.push("setopt NO_EXTENDED_GLOB 2>/dev/null || true".to_string());
    }

    // 5. The user's command (wrapped in eval for alias expansion)
    command_parts.push(format!("eval {}", shell_quote(command)));

    // 6. After the command, capture BOTH cwd and exported env in one trailing
    // step: cwd → a per-call temp file (read back into ShellState below), env →
    // the persistent per-session file (sourced by the next command at step 1b).
    let cwd_file = cwd_file_path();
    command_parts.push(format!(
        "{{ pwd -P >| {}; export -p >| {}; }}",
        shell_quote(&cwd_file),
        shell_quote(&env_path),
    ));

    let command_string = command_parts.join(" && ");

    // Build spawn args: -c [-l] <command>
    // Use login shell (-l) only when no snapshot is available
    let mut args = vec!["-c".to_string()];
    if !has_snapshot {
        args.push("-l".to_string());
    }
    args.push(command_string);

    // Build environment overrides
    let mut env_overrides: HashMap<String, String> = HashMap::new();

    // Set SHELL to the detected shell path
    env_overrides.insert("SHELL".into(), shell_state.shell_path.clone());

    // Prevent git from opening an interactive editor (would hang)
    env_overrides.entry("GIT_EDITOR".into()).or_insert_with(|| "true".into());

    // Tmux socket isolation
    if let Some(tmux_env) = shell_state.get_tmux_env() {
        env_overrides.insert("TMUX".into(), tmux_env);
    }


    // Create a temp file to capture interleaved stdout+stderr at the OS level
    let output_file_path = tool_results_dir().join(format!(
        "bash-output-{}",
        CWD_COUNTER.fetch_add(1, Ordering::Relaxed)
    ));
    fs::create_dir_all(tool_results_dir())
        .await
        .map_err(|e| format!("Failed to create tool-results dir: {e}"))?;

    let output_file = fs::OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .open(&output_file_path)
        .await
        .map_err(|e| format!("Failed to create output file: {e}"))?
        .into_std()
        .await;

    let stdout_file = output_file
        .try_clone()
        .map_err(|e| format!("Failed to clone output file: {e}"))?;

    let mut cmd = tokio::process::Command::new(&shell_state.shell_path);
    cmd.args(&args)
        .current_dir(&cwd)
        .stdin(Stdio::null())
        .stdout(Stdio::from(stdout_file))
        .stderr(Stdio::from(output_file));
    // Give this exec its OWN process group (pgid == child pid), so
    // every descendant it spawns shares that group — the handle the
    // attribution engine maps back to this AIH. Inherited across fork;
    // unchanged for the child's own signal handling. Linux-only (the
    // laboratory always runs in a Linux container; attribution is
    // Linux-only too).
    #[cfg(target_os = "linux")]
    cmd.process_group(0);

    // Apply session env var overrides
    for (key, value) in &env_overrides {
        cmd.env(key, value);
    }

    let mut child = cmd
        .spawn()
        .map_err(|e| format!("Failed to spawn command: {e}"))?;

    // Register this exec's process group under the caller's AIH for the
    // exec's lifetime, so filesystem writes it (and its descendants)
    // make are attributed to this agent. `child.id()` == the new pgid.
    let pgid = child.id().map(|p| p as i32);
    if let Some(pgid) = pgid {
        crate::attribution::register_session(pgid, aih);
    }

    // Wait for child to exit (output is in the file, not pipes)
    let (exit_code, interrupted) = match tokio::time::timeout(timeout_duration, child.wait()).await
    {
        Ok(Ok(status)) => (status.code(), false),
        Ok(Err(e)) => {
            if let Some(pgid) = pgid {
                crate::attribution::unregister_session(pgid);
            }
            return Err(format!("Command failed: {e}"));
        }
        Err(_) => {
            // Timeout — kill the child, then read whatever output was written
            let _ = child.kill().await;
            (None, true)
        }
    };
    if let Some(pgid) = pgid {
        crate::attribution::unregister_session(pgid);
    }

    // Read the output file
    let full_output = fs::read_to_string(&output_file_path).await.unwrap_or_default();
    let full_output_size = full_output.len();

    let mut persisted_output_path: Option<String> = None;
    let mut persisted_output_size: Option<u64> = None;

    let combined = if full_output_size > MAX_OUTPUT_CHARS {
        persisted_output_size = Some(full_output_size as u64);

        // The file is already on disk — truncate it if it exceeds MAX_PERSISTED_SIZE
        if full_output_size > MAX_PERSISTED_SIZE {
            let _ = fs::write(&output_file_path, &full_output[..MAX_PERSISTED_SIZE]).await;
        }
        persisted_output_path = Some(output_file_path.to_string_lossy().into_owned());

        // Build truncated inline output
        let total_lines = full_output.lines().count();
        let truncated = &full_output[..MAX_OUTPUT_CHARS];
        let kept_lines = truncated.lines().count();
        let dropped = total_lines - kept_lines;
        format!(
            "{}\n\n... [{} lines truncated] ...\nFull output ({} bytes) saved to: {}\nUse the Read tool to access it.",
            truncated,
            dropped,
            full_output_size,
            persisted_output_path.as_ref().unwrap()
        )
    } else {
        // Small output — clean up the temp file
        let _ = fs::remove_file(&output_file_path).await;
        full_output
    };

    // Read the saved CWD from the temp file and persist it for this AIH.
    if let Ok(new_cwd) = fs::read_to_string(&cwd_file).await {
        let new_cwd = new_cwd.trim();
        if !new_cwd.is_empty() {
            shell_state.set_cwd(aih, PathBuf::from(new_cwd));
        }
    }
    // Clean up the CWD file
    let _ = fs::remove_file(&cwd_file).await;

    let return_code_interpretation = interpret_return_code(command, exit_code);
    let no_output_expected = is_silent_command(command);

    let is_image = detect_base64_image(&combined);

    let stderr_msg = if interrupted {
        format!("Command timed out after {timeout_ms}ms")
    } else {
        String::new()
    };

    Ok(BashOutput {
        stdout: combined,
        stderr: stderr_msg,
        interrupted,
        exit_code,
        return_code_interpretation,
        is_image,
        persisted_output_path,
        persisted_output_size,
        no_output_expected,
    })
}

/// Detect the user's shell from environment.
/// Checks CLAUDE_CODE_SHELL first, then SHELL, then tries common paths on Windows.
/// Always returns a full path (or at least a validated executable path).
fn detect_shell() -> String {
    // 1. Check CLAUDE_CODE_SHELL env var first
    if let Ok(shell) = std::env::var("CLAUDE_CODE_SHELL") {
        if shell.contains("bash") || shell.contains("zsh") {
            return shell;
        }
    }

    // 2. Check SHELL env var
    if let Ok(shell) = std::env::var("SHELL") {
        if !shell.is_empty() {
            return shell;
        }
    }

    // 3. On Windows (msys/git-bash — LOCAL DEV ONLY, the shipped
    //    binary is always musl-linux), try the common paths. No
    //    `which` subprocess fallback: this detector is sync (called
    //    from ShellState's constructor) and the repo spawns
    //    subprocesses through tokio only.
    if cfg!(windows) {
        for candidate in &["/usr/bin/bash", "/bin/bash"] {
            if std::path::Path::new(candidate).exists() {
                return candidate.to_string();
            }
        }
    }

    // 4. Probe common shell locations and use the first that exists. A bare
    //    `/bin/bash` fallback fails on images that put bash elsewhere (the
    //    Alpine `bash` image installs it at `/usr/local/bin/bash`, with no
    //    `/bin/bash`) or that ship only a POSIX shell. Prefer bash, then fall
    //    back to `/bin/sh` (always present in a laboratory image — the
    //    container entrypoint itself is `/bin/sh`).
    for candidate in &[
        "/bin/bash",
        "/usr/bin/bash",
        "/usr/local/bin/bash",
        "/bin/sh",
        "/usr/bin/sh",
    ] {
        if std::path::Path::new(candidate).exists() {
            return candidate.to_string();
        }
    }

    "/bin/bash".into()
}

/// Generate a unique CWD temp file path for this invocation.
/// Uses an atomic counter combined with PID for uniqueness within a process.
static CWD_COUNTER: AtomicU64 = AtomicU64::new(0);
fn cwd_file_path() -> String {
    let id = CWD_COUNTER.fetch_add(1, Ordering::Relaxed);
    format!(
        "{}/objectiveai-mcp-{}-{}-cwd",
        std::env::temp_dir().to_string_lossy(),
        std::process::id(),
        id,
    )
}

/// Per-AIH exported-env file path. The AIH (which contains `/`) is hashed so
/// the filename is filesystem-safe and collision-free; `export -p` is dumped
/// here after each of this AIH's commands and sourced before the next, giving
/// env the same cross-command persistence as cwd, scoped per agent instance.
fn env_path_for(aih: &str) -> String {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    aih.hash(&mut h);
    format!(
        "{}/objectiveai-mcp-{}-env-{:016x}.sh",
        std::env::temp_dir().to_string_lossy(),
        std::process::id(),
        h.finish(),
    )
}

fn tool_results_dir() -> std::path::PathBuf {
    std::env::temp_dir().join(format!(
        "objectiveai-mcp-{}-tool-results",
        std::process::id()
    ))
}

/// Parsed data URI components.
pub struct ParsedDataUri {
    pub media_type: String,
    pub data: String,
}

/// Parse a data URI string into its media type and base64 payload.
pub fn parse_data_uri(s: &str) -> Option<ParsedDataUri> {
    let trimmed = s.trim();
    let rest = trimmed.strip_prefix("data:")?;
    let (media_type, after) = rest.split_once(';')?;
    let data = after.strip_prefix("base64,")?;
    if media_type.is_empty() || data.is_empty() {
        return None;
    }
    Some(ParsedDataUri {
        media_type: media_type.to_string(),
        data: data.to_string(),
    })
}

/// Check if content starts with a base64-encoded image data URI.
/// Matches the official regex: /^data:image\/[a-z0-9.+_-]+;base64,/i
fn detect_base64_image(output: &str) -> bool {
    let s = output.as_bytes();
    // Case-insensitive prefix check: "data:image/"
    if s.len() < 11 {
        return false;
    }
    if !s[..11].eq_ignore_ascii_case(b"data:image/") {
        return false;
    }
    // Media subtype: [a-z0-9.+_-]+ then ";base64,"
    let rest = &s[11..];
    let mut i = 0;
    while i < rest.len() {
        let b = rest[i];
        if b.is_ascii_alphanumeric() || b == b'.' || b == b'+' || b == b'_' || b == b'-' {
            i += 1;
        } else {
            break;
        }
    }
    if i == 0 {
        return false;
    }
    rest[i..].starts_with(b";base64,")
}

/// Command-specific return code interpretation matching Claude Code's commandSemantics.
fn interpret_return_code(command: &str, exit_code: Option<i32>) -> Option<String> {
    let code = exit_code?;
    if code == 0 {
        return None;
    }

    // Extract the base command (first word, ignoring env vars and prefixes)
    let base_cmd = command
        .split(&['|', '&', ';'][..])
        .next()
        .unwrap_or("")
        .split_whitespace()
        .find(|w| !w.contains('=')) // skip env var assignments like FOO=bar
        .unwrap_or("");

    match base_cmd {
        // grep/rg: 0=matches, 1=no matches, 2+=error
        "grep" | "rg" | "egrep" | "fgrep" => {
            if code == 1 {
                Some("No matches found".into())
            } else {
                Some(format!("exit_code:{code}"))
            }
        }
        // diff: 0=identical, 1=differences found, 2+=error
        "diff" => {
            if code == 1 {
                Some("Files differ".into())
            } else {
                Some(format!("exit_code:{code}"))
            }
        }
        // find: 0=success, 1=some dirs inaccessible, 2+=error
        "find" => {
            if code == 1 {
                Some("Some directories were inaccessible".into())
            } else {
                Some(format!("exit_code:{code}"))
            }
        }
        // test/[: 0=true, 1=false, 2+=error
        "test" | "[" => {
            if code == 1 {
                Some("Condition is false".into())
            } else {
                Some(format!("exit_code:{code}"))
            }
        }
        _ => Some(format!("exit_code:{code}")),
    }
}

/// Detect if a command is expected to produce no output (silent commands).
fn is_silent_command(command: &str) -> bool {
    const SILENT_COMMANDS: &[&str] = &[
        "mv", "cp", "rm", "mkdir", "rmdir", "chmod", "chown", "chgrp",
        "touch", "ln", "cd", "export", "unset", "wait",
    ];
    const NEUTRAL_COMMANDS: &[&str] = &["echo", "printf", "true", "false", ":"];

    // Split on shell operators and check each command segment
    let mut has_non_fallback = false;
    let mut last_was_or = false;

    for segment in command.split(&['|', '&', ';'][..]) {
        let segment = segment.trim();
        if segment.is_empty() {
            continue;
        }
        let base_cmd = segment.split_whitespace().next().unwrap_or("");

        // After || operator, neutral commands don't count
        if last_was_or && NEUTRAL_COMMANDS.contains(&base_cmd) {
            last_was_or = false;
            continue;
        }
        last_was_or = segment.ends_with('|'); // rough heuristic for ||

        has_non_fallback = true;
        if !SILENT_COMMANDS.contains(&base_cmd) {
            return false;
        }
    }
    has_non_fallback
}

/// Simple shell quoting for a single argument.
fn shell_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', "'\\''"))
}

/// Create a shell snapshot by sourcing the user's shell config and capturing
/// functions, aliases, and options. Returns the path to the snapshot file.
async fn create_shell_snapshot(shell_path: &str) -> Result<String, String> {
    let shell_type = if shell_path.contains("zsh") {
        "zsh"
    } else if shell_path.contains("bash") {
        "bash"
    } else {
        "sh"
    };

    let config_file = get_config_file(shell_path);

    // Config file is optional — snapshot still captures Claude Code defaults
    let has_config = std::path::Path::new(&config_file).exists();

    let snapshot_path = format!(
        "{}/objectiveai-mcp-snapshot-{}-{}.sh",
        std::env::temp_dir().to_string_lossy(),
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis(),
    );

    // Guarded POSIX dot — same rule as the per-command preamble: bare
    // `.` on a missing/unreadable file ABORTS non-interactive
    // dash/ash, and `source` doesn't exist in dash.
    let source_line = if has_config {
        format!(
            "[ -r {p} ] && . {p} 2>/dev/null || true",
            p = shell_quote(&config_file)
        )
    } else {
        "true".into()
    };

    let is_windows = cfg!(windows);

    let snapshot_script = if shell_type == "zsh" {
        format!(
            r#"
SNAPSHOT_FILE={snapshot}
{source}
{{
  echo '# Shell snapshot (zsh)'
  typeset -f 2>/dev/null
  alias | sed 's/^alias //g' | sed 's/^/alias -- /'
  setopt 2>/dev/null | while IFS= read -r opt; do echo "setopt $opt"; done
}} > "$SNAPSHOT_FILE" 2>/dev/null
"#,
            snapshot = shell_quote(&snapshot_path),
            source = source_line,
        )
    } else if shell_type == "bash" {
        // On Windows (msys/git-bash), filter out winpty aliases
        let alias_cmd = if is_windows {
            r#"alias | grep -v "='winpty " | sed 's/^alias //g' | sed 's/^/alias -- /'"#
        } else {
            r#"alias | sed 's/^alias //g' | sed 's/^/alias -- /'"#
        };

        format!(
            r#"
SNAPSHOT_FILE={snapshot}
unalias -a 2>/dev/null || true
{source}
{{
  echo '# Shell snapshot (bash)'
  declare -f 2>/dev/null
  {alias_cmd}
  shopt -p 2>/dev/null
  set -o | grep "on" | awk '{{print "set -o " $1}}'
  echo "shopt -s expand_aliases"
}} > "$SNAPSHOT_FILE" 2>/dev/null
"#,
            snapshot = shell_quote(&snapshot_path),
            source = source_line,
            alias_cmd = alias_cmd,
        )
    } else {
        // Plain POSIX sh (busybox ash on alpine, dash on debian-slim):
        // capture ALIASES ONLY.
        // - No functions: POSIX sh has no `declare -f`/`typeset -f` —
        //   there is no way to dump them.
        // - No `shopt`/`expand_aliases`: bash-only, and a failing
        //   special built-in INSIDE a dot-file ABORTS non-interactive
        //   dash — a bash line in the snapshot would kill every later
        //   command, silently.
        // - No `set -o` replay: dash's `set -o` output is a header +
        //   `name on/off` table, so the bash arm's pipeline would emit
        //   `set -o Current` — the abort trap above. ash/dash expand
        //   aliases non-interactively, so nothing more is needed.
        // The sed pair normalizes both alias output formats (POSIX
        // `name='v'` and bash-style `alias name='v'`) into re-`.`-able
        // `alias name='v'` lines — NO `alias --`: dash treats `--` as
        // an alias NAME to look up.
        format!(
            r#"
SNAPSHOT_FILE={snapshot}
unalias -a 2>/dev/null || true
{source}
{{
  echo '# Shell snapshot (sh)'
  alias | sed -e 's/^alias //' -e 's/^/alias /'
}} > "$SNAPSHOT_FILE" 2>/dev/null
"#,
            snapshot = shell_quote(&snapshot_path),
            source = source_line,
        )
    };

    let result = tokio::time::timeout(
        Duration::from_secs(10),
        tokio::process::Command::new(shell_path)
            .args(["-c", &snapshot_script])
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output(),
    )
    .await
    .map_err(|_| "Shell snapshot creation timed out".to_string())?
    .map_err(|e| format!("Failed to create snapshot: {e}"))?;

    if !std::path::Path::new(&snapshot_path).exists() {
        let stderr = String::from_utf8_lossy(&result.stderr);
        return Err(format!("Snapshot file was not created: {stderr}"));
    }

    tracing::info!("Shell snapshot created at {snapshot_path}");
    Ok(snapshot_path)
}

/// Get the shell config file path based on shell type: `.zshrc` /
/// `.bashrc` for the shells that read those, `~/.profile` for plain
/// POSIX sh (the sh-conventional file; `$ENV` is interactive-only and
/// our snapshot shell is neither interactive nor login). The `"~"`
/// HOME-unset fallback is safe — the literal path never exists, so
/// the snapshot simply skips sourcing.
fn get_config_file(shell_path: &str) -> String {
    let home = std::env::var("HOME").unwrap_or_else(|_| "~".into());
    if shell_path.contains("zsh") {
        format!("{home}/.zshrc")
    } else if shell_path.contains("bash") {
        format!("{home}/.bashrc")
    } else {
        format!("{home}/.profile")
    }
}

/// Initialize an isolated tmux socket for this session.
async fn init_tmux_socket() -> Result<String, String> {
    let socket_path = format!(
        "{}/objectiveai-mcp-tmux-{}.sock",
        std::env::temp_dir().to_string_lossy(),
        std::process::id(),
    );

    let output = tokio::process::Command::new("tmux")
        .args(["-S", &socket_path, "new-session", "-d", "-s", "objectiveai"])
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .await
        .map_err(|e| format!("Failed to initialize tmux socket: {e}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("tmux initialization failed: {stderr}"));
    }

    tracing::info!("Tmux socket initialized at {socket_path}");
    Ok(socket_path)
}