rust-expect 0.1.0

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

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

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::Mutex;

#[cfg(unix)]
use crate::backend::{AsyncPty, PtyConfig, PtySpawner};
#[cfg(windows)]
use crate::backend::{PtyConfig, PtySpawner, WindowsAsyncPty};
use crate::config::SessionConfig;
use crate::dialog::{Dialog, DialogExecutor, DialogResult};
use crate::error::{ExpectError, Result};
use crate::expect::{ExpectState, MatchResult, Matcher, Pattern, PatternManager, PatternSet};
use crate::interact::InteractBuilder;
use crate::types::{ControlChar, Dimensions, Match, ProcessExitStatus, SessionId, SessionState};

/// A session handle for interacting with a spawned process.
///
/// The session provides methods to send input, expect patterns in output,
/// and manage the lifecycle of the process.
pub struct Session<T: AsyncReadExt + AsyncWriteExt + Unpin + Send> {
    /// The underlying transport (PTY, SSH channel, etc.).
    transport: Arc<Mutex<T>>,
    /// Session configuration.
    config: SessionConfig,
    /// Pattern matcher.
    matcher: Matcher,
    /// Pattern manager for before/after patterns.
    pattern_manager: PatternManager,
    /// Current session state.
    state: SessionState,
    /// Unique session identifier.
    id: SessionId,
    /// EOF flag.
    eof: bool,
}

impl<T: AsyncReadExt + AsyncWriteExt + Unpin + Send> Session<T> {
    /// Create a new session with the given transport.
    pub fn new(transport: T, config: SessionConfig) -> Self {
        let buffer_size = config.buffer.max_size;
        let mut matcher = Matcher::new(buffer_size);
        matcher.set_default_timeout(config.timeout.default);
        Self {
            transport: Arc::new(Mutex::new(transport)),
            config,
            matcher,
            pattern_manager: PatternManager::new(),
            state: SessionState::Starting,
            id: SessionId::new(),
            eof: false,
        }
    }

    /// Get the session ID.
    #[must_use]
    pub const fn id(&self) -> &SessionId {
        &self.id
    }

    /// Get the current session state.
    #[must_use]
    pub const fn state(&self) -> SessionState {
        self.state
    }

    /// Get the session configuration.
    #[must_use]
    pub const fn config(&self) -> &SessionConfig {
        &self.config
    }

    /// Check if EOF has been detected.
    #[must_use]
    pub const fn is_eof(&self) -> bool {
        self.eof
    }

    /// Get the current buffer contents.
    #[must_use]
    pub fn buffer(&mut self) -> String {
        self.matcher.buffer_str()
    }

    /// Clear the buffer.
    pub fn clear_buffer(&mut self) {
        self.matcher.clear();
    }

    /// Get the pattern manager for before/after patterns.
    #[must_use]
    pub const fn pattern_manager(&self) -> &PatternManager {
        &self.pattern_manager
    }

    /// Get mutable access to the pattern manager.
    pub const fn pattern_manager_mut(&mut self) -> &mut PatternManager {
        &mut self.pattern_manager
    }

    /// Set the session state.
    pub const fn set_state(&mut self, state: SessionState) {
        self.state = state;
    }

    /// Send bytes to the process.
    ///
    /// # Errors
    ///
    /// Returns an error if the write fails.
    #[allow(clippy::significant_drop_tightening)]
    pub async fn send(&mut self, data: &[u8]) -> Result<()> {
        if matches!(self.state, SessionState::Closed | SessionState::Exited(_)) {
            return Err(ExpectError::SessionClosed);
        }

        let mut transport = self.transport.lock().await;
        transport
            .write_all(data)
            .await
            .map_err(|e| ExpectError::io_context("writing to process", e))?;
        transport
            .flush()
            .await
            .map_err(|e| ExpectError::io_context("flushing process output", e))?;
        Ok(())
    }

    /// Send a string to the process.
    ///
    /// # Errors
    ///
    /// Returns an error if the write fails.
    pub async fn send_str(&mut self, s: &str) -> Result<()> {
        self.send(s.as_bytes()).await
    }

    /// Send a line to the process (appends newline based on config).
    ///
    /// # Errors
    ///
    /// Returns an error if the write fails.
    pub async fn send_line(&mut self, line: &str) -> Result<()> {
        let line_ending = self.config.line_ending.as_str();
        let data = format!("{line}{line_ending}");
        self.send(data.as_bytes()).await
    }

    /// Send a control character to the process.
    ///
    /// # Errors
    ///
    /// Returns an error if the write fails.
    pub async fn send_control(&mut self, ctrl: ControlChar) -> Result<()> {
        self.send(&[ctrl.as_byte()]).await
    }

    /// Expect a pattern in the output.
    ///
    /// Blocks until the pattern is matched, EOF is detected, or timeout occurs.
    ///
    /// # Errors
    ///
    /// Returns an error on timeout, EOF (if not expected), or I/O error.
    pub async fn expect(&mut self, pattern: impl Into<Pattern>) -> Result<Match> {
        let patterns = PatternSet::from_patterns(vec![pattern.into()]);
        self.expect_any(&patterns).await
    }

    /// Expect any of the given patterns.
    ///
    /// # Errors
    ///
    /// Returns an error on timeout, EOF (if not expected), or I/O error.
    pub async fn expect_any(&mut self, patterns: &PatternSet) -> Result<Match> {
        let timeout = self.matcher.get_timeout(patterns);
        let state = ExpectState::new(patterns.clone(), timeout);

        loop {
            // Check before patterns first
            if let Some((_, action)) = self
                .pattern_manager
                .check_before(&self.matcher.buffer_str())
            {
                match action {
                    crate::expect::HandlerAction::Continue => {}
                    crate::expect::HandlerAction::Return(s) => {
                        return Ok(Match::new(0, s, String::new(), self.matcher.buffer_str()));
                    }
                    crate::expect::HandlerAction::Abort(msg) => {
                        return Err(ExpectError::PatternNotFound {
                            pattern: msg,
                            buffer: self.matcher.buffer_str(),
                        });
                    }
                    crate::expect::HandlerAction::Respond(s) => {
                        self.send_str(&s).await?;
                    }
                }
            }

            // Check for pattern match
            if let Some(result) = self.matcher.try_match_any(patterns) {
                return Ok(self.matcher.consume_match(&result));
            }

            // Check for timeout
            if state.is_timed_out() {
                return Err(ExpectError::Timeout {
                    duration: timeout,
                    pattern: patterns
                        .iter()
                        .next()
                        .map(|p| p.pattern.as_str().to_string())
                        .unwrap_or_default(),
                    buffer: self.matcher.buffer_str(),
                });
            }

            // Check for EOF
            if self.eof {
                if state.expects_eof() {
                    return Ok(Match::new(
                        0,
                        String::new(),
                        self.matcher.buffer_str(),
                        String::new(),
                    ));
                }
                return Err(ExpectError::Eof {
                    buffer: self.matcher.buffer_str(),
                });
            }

            // Read more data
            self.read_with_timeout(state.remaining_time()).await?;
        }
    }

    /// Expect with a specific timeout.
    ///
    /// # Errors
    ///
    /// Returns an error on timeout, EOF, or I/O error.
    pub async fn expect_timeout(
        &mut self,
        pattern: impl Into<Pattern>,
        timeout: Duration,
    ) -> Result<Match> {
        let pattern = pattern.into();
        let mut patterns = PatternSet::new();
        patterns.add(pattern).add(Pattern::timeout(timeout));
        self.expect_any(&patterns).await
    }

    /// Read data from the transport with timeout.
    async fn read_with_timeout(&mut self, timeout: Duration) -> Result<usize> {
        let mut buf = [0u8; 4096];
        let mut transport = self.transport.lock().await;

        match tokio::time::timeout(timeout, transport.read(&mut buf)).await {
            Ok(Ok(0)) => {
                self.eof = true;
                Ok(0)
            }
            Ok(Ok(n)) => {
                self.matcher.append(&buf[..n]);
                Ok(n)
            }
            Ok(Err(e)) => {
                // On Linux, reading from PTY master returns EIO when the slave is closed
                // (i.e., the child process has terminated). Treat this as EOF.
                // See: https://bugs.python.org/issue5380
                if is_pty_eof_error(&e) {
                    self.eof = true;
                    Ok(0)
                } else {
                    Err(ExpectError::io_context("reading from process", e))
                }
            }
            Err(_) => {
                // Timeout, but not an error - caller will handle
                Ok(0)
            }
        }
    }

    /// Wait for the process to exit.
    ///
    /// This method blocks until EOF is detected on the session, which typically
    /// happens when the child process terminates.
    ///
    /// # Warning
    ///
    /// This method has no timeout and may block indefinitely if the process
    /// does not exit. Consider using [`wait_timeout`](Self::wait_timeout) or
    /// [`expect_eof_timeout`](Self::expect_eof_timeout) for bounded waits.
    ///
    /// # Errors
    ///
    /// Returns an error if waiting fails due to I/O error.
    pub async fn wait(&mut self) -> Result<ProcessExitStatus> {
        // Read until EOF
        while !self.eof {
            if self.read_with_timeout(Duration::from_millis(100)).await? == 0 && !self.eof {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        }

        // Return unknown status - actual status depends on backend
        self.state = SessionState::Exited(ProcessExitStatus::Unknown);
        Ok(ProcessExitStatus::Unknown)
    }

    /// Wait for the process to exit with a timeout.
    ///
    /// Like [`wait`](Self::wait), but with a maximum duration to wait.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The timeout expires before the process exits
    /// - An I/O error occurs while waiting
    pub async fn wait_timeout(&mut self, timeout: Duration) -> Result<ProcessExitStatus> {
        let deadline = tokio::time::Instant::now() + timeout;

        while !self.eof {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            if remaining.is_zero() {
                return Err(ExpectError::timeout(
                    timeout,
                    "<EOF>",
                    self.matcher.buffer_str(),
                ));
            }

            // Use smaller of remaining time or 100ms for polling
            let poll_timeout = remaining.min(Duration::from_millis(100));
            if self.read_with_timeout(poll_timeout).await? == 0 && !self.eof {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        }

        self.state = SessionState::Exited(ProcessExitStatus::Unknown);
        Ok(ProcessExitStatus::Unknown)
    }

    /// Check if a pattern matches immediately without blocking.
    #[must_use]
    pub fn check(&mut self, pattern: &Pattern) -> Option<MatchResult> {
        self.matcher.try_match(pattern)
    }

    /// Get the underlying transport.
    ///
    /// Use with caution as direct access bypasses session management.
    #[must_use]
    pub const fn transport(&self) -> &Arc<Mutex<T>> {
        &self.transport
    }

    /// Start an interactive session with pattern hooks.
    ///
    /// This returns a builder that allows you to configure pattern-based
    /// callbacks that fire when patterns match in the output or input.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use rust_expect::{Session, InteractAction};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), rust_expect::ExpectError> {
    ///     let mut session = Session::spawn("/bin/bash", &[]).await?;
    ///
    ///     session.interact()
    ///         .on_output("password:", |ctx| {
    ///             ctx.send("my_password\n")
    ///         })
    ///         .on_output("logout", |_| {
    ///             InteractAction::Stop
    ///         })
    ///         .start()
    ///         .await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    #[must_use]
    pub fn interact(&self) -> InteractBuilder<'_, T>
    where
        T: 'static,
    {
        InteractBuilder::new(&self.transport)
    }

    /// Run a dialog on this session.
    ///
    /// A dialog is a predefined sequence of expect/send operations.
    /// This method executes the dialog and returns the result.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use rust_expect::{Session, Dialog, DialogStep};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), rust_expect::ExpectError> {
    ///     let mut session = Session::spawn("/bin/bash", &[]).await?;
    ///
    ///     let dialog = Dialog::named("shell_test")
    ///         .step(DialogStep::new("prompt")
    ///             .with_expect("$")
    ///             .with_send("echo hello\n"))
    ///         .step(DialogStep::new("verify")
    ///             .with_expect("hello"));
    ///
    ///     let result = session.run_dialog(&dialog).await?;
    ///     assert!(result.success);
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if I/O fails. Step-level timeouts are reported
    /// in the `DialogResult` rather than as errors.
    pub async fn run_dialog(&mut self, dialog: &Dialog) -> Result<DialogResult> {
        let executor = DialogExecutor::default();
        executor.execute(self, dialog).await
    }

    /// Run a dialog with a custom executor.
    ///
    /// This allows customizing the executor settings (max steps, default timeout).
    ///
    /// # Errors
    ///
    /// Returns an error if I/O fails.
    pub async fn run_dialog_with(
        &mut self,
        dialog: &Dialog,
        executor: &DialogExecutor,
    ) -> Result<DialogResult> {
        executor.execute(self, dialog).await
    }

    /// Expect end-of-file (process termination).
    ///
    /// This is a convenience method for waiting until the process terminates
    /// and closes its output stream.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use rust_expect::Session;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), rust_expect::ExpectError> {
    ///     let mut session = Session::spawn("echo", &["hello"]).await?;
    ///     session.expect("hello").await?;
    ///     session.expect_eof().await?;
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the session times out before EOF or an I/O error occurs.
    pub async fn expect_eof(&mut self) -> Result<Match> {
        self.expect(Pattern::eof()).await
    }

    /// Expect end-of-file with a specific timeout.
    ///
    /// # Errors
    ///
    /// Returns an error if the session times out before EOF or an I/O error occurs.
    pub async fn expect_eof_timeout(&mut self, timeout: Duration) -> Result<Match> {
        let mut patterns = PatternSet::new();
        patterns.add(Pattern::eof()).add(Pattern::timeout(timeout));
        self.expect_any(&patterns).await
    }

    /// Run a batch of commands, waiting for the prompt after each.
    ///
    /// This is a convenience method for executing multiple shell commands
    /// in sequence. For each command, it sends the command line and waits
    /// for the prompt pattern to appear.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use rust_expect::{Session, Pattern};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), rust_expect::ExpectError> {
    ///     let mut session = Session::spawn("/bin/bash", &[]).await?;
    ///     session.expect(Pattern::shell_prompt()).await?;
    ///
    ///     // Run a batch of commands
    ///     let results = session.run_script(
    ///         &["pwd", "whoami", "date"],
    ///         Pattern::shell_prompt(),
    ///     ).await?;
    ///
    ///     for result in &results {
    ///         println!("Output: {}", result.before.trim());
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if any command times out or I/O fails.
    /// On error, partial results are lost; consider using [`Self::run_script_with_results`]
    /// if you need to capture partial results on failure.
    pub async fn run_script<I, S>(&mut self, commands: I, prompt: Pattern) -> Result<Vec<Match>>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut results = Vec::new();

        for cmd in commands {
            self.send_line(cmd.as_ref()).await?;
            let result = self.expect(prompt.clone()).await?;
            results.push(result);
        }

        Ok(results)
    }

    /// Run a batch of commands with a specific timeout per command.
    ///
    /// Like [`run_script`](Self::run_script), but applies the given timeout
    /// to each command individually.
    ///
    /// # Errors
    ///
    /// Returns an error if any command times out or I/O fails.
    pub async fn run_script_timeout<I, S>(
        &mut self,
        commands: I,
        prompt: Pattern,
        timeout: Duration,
    ) -> Result<Vec<Match>>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut results = Vec::new();

        for cmd in commands {
            self.send_line(cmd.as_ref()).await?;
            let result = self.expect_timeout(prompt.clone(), timeout).await?;
            results.push(result);
        }

        Ok(results)
    }

    /// Run a batch of commands, collecting results even on failure.
    ///
    /// Unlike [`run_script`](Self::run_script), this method continues
    /// collecting results and returns them along with any error that occurred.
    ///
    /// # Returns
    ///
    /// A tuple of `(results, error)` where:
    /// - `results` contains the matches for successfully completed commands
    /// - `error` is `Some(err)` if an error occurred, `None` if all commands succeeded
    ///
    /// # Example
    ///
    /// ```ignore
    /// use rust_expect::{Session, Pattern};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), rust_expect::ExpectError> {
    ///     let mut session = Session::spawn("/bin/bash", &[]).await?;
    ///     session.expect(Pattern::shell_prompt()).await?;
    ///
    ///     let (results, error) = session.run_script_with_results(
    ///         &["pwd", "bad_command", "date"],
    ///         Pattern::shell_prompt(),
    ///     ).await;
    ///
    ///     println!("Completed {} commands", results.len());
    ///     if let Some(e) = error {
    ///         eprintln!("Script failed at command {}: {}", results.len(), e);
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn run_script_with_results<I, S>(
        &mut self,
        commands: I,
        prompt: Pattern,
    ) -> (Vec<Match>, Option<ExpectError>)
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut results = Vec::new();

        for cmd in commands {
            match self.send_line(cmd.as_ref()).await {
                Ok(()) => {}
                Err(e) => return (results, Some(e)),
            }

            match self.expect(prompt.clone()).await {
                Ok(result) => results.push(result),
                Err(e) => return (results, Some(e)),
            }
        }

        (results, None)
    }
}

impl<T: AsyncReadExt + AsyncWriteExt + Unpin + Send> std::fmt::Debug for Session<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Session")
            .field("id", &self.id)
            .field("state", &self.state)
            .field("eof", &self.eof)
            .finish_non_exhaustive()
    }
}

// Unix-specific spawn implementation
#[cfg(unix)]
impl Session<AsyncPty> {
    /// Spawn a new process with the given command.
    ///
    /// This creates a new PTY, forks a child process, and returns a Session
    /// connected to the child's terminal.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use rust_expect::Session;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), rust_expect::ExpectError> {
    ///     let mut session = Session::spawn("/bin/bash", &[]).await?;
    ///     session.expect("$").await?;
    ///     session.send_line("echo hello").await?;
    ///     session.expect("hello").await?;
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The command contains null bytes
    /// - PTY allocation fails
    /// - Fork fails
    /// - The command cannot be executed
    pub async fn spawn(command: &str, args: &[&str]) -> Result<Self> {
        Self::spawn_with_config(command, args, SessionConfig::default()).await
    }

    /// Spawn a new process with custom configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if spawning fails.
    pub async fn spawn_with_config(
        command: &str,
        args: &[&str],
        config: SessionConfig,
    ) -> Result<Self> {
        let pty_config = PtyConfig::from(&config);
        let spawner = PtySpawner::with_config(pty_config);

        // Convert &[&str] to Vec<String> for the spawner
        let args_owned: Vec<String> = args.iter().map(|s| (*s).to_string()).collect();

        // Spawn the process
        let handle = spawner.spawn(command, &args_owned).await?;

        // Wrap in AsyncPty for async I/O
        let async_pty = AsyncPty::from_handle(handle)
            .map_err(|e| ExpectError::io_context("creating async PTY wrapper", e))?;

        // Create the session
        let mut session = Self::new(async_pty, config);
        session.state = SessionState::Running;

        Ok(session)
    }

    /// Get the child process ID.
    #[must_use]
    pub fn pid(&self) -> u32 {
        // We need to access the inner transport's pid
        // For now, use the blocking lock since we know it's not contended
        // during a sync call like this
        if let Ok(transport) = self.transport.try_lock() {
            transport.pid()
        } else {
            0
        }
    }

    /// Resize the terminal.
    ///
    /// # Errors
    ///
    /// Returns an error if the resize ioctl fails.
    pub async fn resize_pty(&mut self, cols: u16, rows: u16) -> Result<()> {
        let mut transport = self.transport.lock().await;
        transport.resize(cols, rows)
    }

    /// Send a signal to the child process.
    ///
    /// # Errors
    ///
    /// Returns an error if sending the signal fails.
    pub fn signal(&self, signal: i32) -> Result<()> {
        if let Ok(transport) = self.transport.try_lock() {
            transport.signal(signal)
        } else {
            Err(ExpectError::io_context(
                "sending signal to process",
                std::io::Error::new(std::io::ErrorKind::WouldBlock, "transport is locked"),
            ))
        }
    }

    /// Kill the child process.
    ///
    /// # Errors
    ///
    /// Returns an error if killing the process fails.
    pub fn kill(&self) -> Result<()> {
        if let Ok(transport) = self.transport.try_lock() {
            transport.kill()
        } else {
            Err(ExpectError::io_context(
                "killing process",
                std::io::Error::new(std::io::ErrorKind::WouldBlock, "transport is locked"),
            ))
        }
    }
}

// Windows-specific spawn implementation
#[cfg(windows)]
impl Session<WindowsAsyncPty> {
    /// Spawn a new process with the given command.
    ///
    /// This creates a new PTY using Windows ConPTY, spawns a child process,
    /// and returns a Session connected to the child's terminal.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use rust_expect::Session;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), rust_expect::ExpectError> {
    ///     let mut session = Session::spawn("cmd.exe", &[]).await?;
    ///     session.expect(">").await?;
    ///     session.send_line("echo hello").await?;
    ///     session.expect("hello").await?;
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - ConPTY is not available (Windows version too old)
    /// - PTY allocation fails
    /// - The command cannot be executed
    pub async fn spawn(command: &str, args: &[&str]) -> Result<Self> {
        Self::spawn_with_config(command, args, SessionConfig::default()).await
    }

    /// Spawn a new process with custom configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if spawning fails.
    pub async fn spawn_with_config(
        command: &str,
        args: &[&str],
        config: SessionConfig,
    ) -> Result<Self> {
        let pty_config = PtyConfig::from(&config);
        let spawner = PtySpawner::with_config(pty_config);

        // Convert &[&str] to Vec<String> for the spawner
        let args_owned: Vec<String> = args.iter().map(|s| s.to_string()).collect();

        // Spawn the process
        let handle = spawner.spawn(command, &args_owned).await?;

        // Wrap in WindowsAsyncPty for async I/O
        let async_pty = WindowsAsyncPty::from_handle(handle);

        // Create the session
        let mut session = Session::new(async_pty, config);
        session.state = SessionState::Running;

        Ok(session)
    }

    /// Get the child process ID.
    #[must_use]
    pub fn pid(&self) -> u32 {
        if let Ok(transport) = self.transport.try_lock() {
            transport.pid()
        } else {
            0
        }
    }

    /// Resize the terminal.
    ///
    /// # Errors
    ///
    /// Returns an error if the resize operation fails.
    pub async fn resize_pty(&mut self, cols: u16, rows: u16) -> Result<()> {
        let mut transport = self.transport.lock().await;
        transport.resize(cols, rows)
    }

    /// Check if the child process is still running.
    #[must_use]
    pub fn is_running(&self) -> bool {
        if let Ok(transport) = self.transport.try_lock() {
            transport.is_running()
        } else {
            true // Assume running if we can't check
        }
    }

    /// Kill the child process.
    ///
    /// # Errors
    ///
    /// Returns an error if killing the process fails.
    pub fn kill(&self) -> Result<()> {
        if let Ok(mut transport) = self.transport.try_lock() {
            transport.kill()
        } else {
            Err(ExpectError::io_context(
                "killing process",
                std::io::Error::new(std::io::ErrorKind::WouldBlock, "transport is locked"),
            ))
        }
    }
}

/// Extension trait for session operations.
pub trait SessionExt {
    /// Send and expect in one call.
    fn send_expect(
        &mut self,
        send: &str,
        expect: impl Into<Pattern>,
    ) -> impl std::future::Future<Output = Result<Match>> + Send;

    /// Resize the terminal.
    fn resize(
        &mut self,
        dimensions: Dimensions,
    ) -> impl std::future::Future<Output = Result<()>> + Send;
}

/// Check if an I/O error indicates PTY EOF.
///
/// On Linux, reading from the PTY master returns EIO when the slave side
/// has been closed (i.e., the child process has terminated). This is different
/// from the standard EOF behavior where `read()` returns 0 bytes.
///
/// This function returns true for errors that should be treated as EOF:
/// - EIO (errno 5) on Unix systems
/// - `BrokenPipe` on any platform
fn is_pty_eof_error(e: &std::io::Error) -> bool {
    use std::io::ErrorKind;

    // BrokenPipe indicates the other end has closed
    if e.kind() == ErrorKind::BrokenPipe {
        return true;
    }

    // On Unix, check for EIO which indicates slave PTY closed
    #[cfg(unix)]
    {
        if let Some(errno) = e.raw_os_error() {
            // EIO is 5 on Linux/macOS/BSD
            if errno == libc::EIO {
                return true;
            }
        }
    }

    false
}