Skip to main content

gate4agent_types/
input.rs

1use crate::spec::{
2    ModifiedEnterEncoding, PtySubmitContract, RuntimePlatform, WindowsPasteNewline,
3};
4use crate::AgentId;
5use serde::{Deserialize, Serialize};
6use thiserror::Error;
7
8pub const TERMINAL_INPUT_CHUNK_MAX_BYTES: usize = 16 * 1024;
9pub const TERMINAL_INPUT_MAX_BYTES: usize = 16 * 1024 * 1024;
10pub const TERMINAL_BYTES_MAX_BYTES: usize = 64;
11pub const TERMINAL_SUBMIT_DELAY_MS: u64 = 500;
12/// Upper bound the PTY writer enforces before sleeping.
13///
14/// A 16 MiB Windows paste ingest is `500 + ceil(TERMINAL_INPUT_MAX_BYTES / 64)`
15/// = 262644. 400_000 leaves room for that ingest plus a few thousand
16/// antigravity line-settle milliseconds. The delay formula itself is not capped.
17pub const TERMINAL_WRITE_DELAY_MAX_MS: u64 = 400_000;
18pub const SEMANTIC_PROMPT_MAX_BYTES: usize = TERMINAL_INPUT_MAX_BYTES;
19pub const BRACKETED_PASTE_START: &[u8] = b"\x1b[200~";
20pub const BRACKETED_PASTE_END: &[u8] = b"\x1b[201~";
21
22#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
23pub enum PromptFraming {
24    BracketedPaste,
25    Literal,
26}
27
28#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
29pub struct PromptPayload {
30    pub text: String,
31    pub framing: PromptFraming,
32}
33
34#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
35pub struct AgentCommand {
36    pub agent_id: AgentId,
37    pub name: String,
38    pub arguments: Vec<String>,
39}
40
41#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
42pub struct ShellCommand {
43    pub text: String,
44}
45
46#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
47pub struct TerminalText {
48    pub text: String,
49}
50
51#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
52pub enum TerminalControl {
53    Interrupt,
54    EndOfFile,
55    ControlA,
56    ControlB,
57    ControlE,
58    ControlF,
59    ControlG,
60    ControlH,
61    ControlI,
62    ControlJ,
63    ControlK,
64    ControlL,
65    ControlM,
66    ControlN,
67    ControlO,
68    ControlP,
69    ControlQ,
70    ControlR,
71    ControlS,
72    ControlT,
73    ControlU,
74    ControlV,
75    ControlW,
76    ControlX,
77    ControlY,
78    ControlZ,
79    Enter,
80    LineFeed,
81    Escape,
82    Backspace,
83    Tab,
84    BackTab,
85    Insert,
86    Delete,
87    Home,
88    End,
89    PageUp,
90    PageDown,
91    ArrowUp,
92    ArrowDown,
93    ArrowRight,
94    ArrowLeft,
95    Function1,
96    Function2,
97    Function3,
98    Function4,
99    Function5,
100    Function6,
101    Function7,
102    Function8,
103    Function9,
104    Function10,
105    Function11,
106    Function12,
107}
108
109impl TerminalControl {
110    pub fn bytes(self) -> &'static [u8] {
111        match self {
112            Self::Interrupt => b"\x03",
113            Self::EndOfFile => b"\x04",
114            Self::ControlA => b"\x01",
115            Self::ControlB => b"\x02",
116            Self::ControlE => b"\x05",
117            Self::ControlF => b"\x06",
118            Self::ControlG => b"\x07",
119            Self::ControlH => b"\x08",
120            Self::ControlI => b"\x09",
121            Self::ControlJ => b"\x0a",
122            Self::ControlK => b"\x0b",
123            Self::ControlL => b"\x0c",
124            Self::ControlM => b"\x0d",
125            Self::ControlN => b"\x0e",
126            Self::ControlO => b"\x0f",
127            Self::ControlP => b"\x10",
128            Self::ControlQ => b"\x11",
129            Self::ControlR => b"\x12",
130            Self::ControlS => b"\x13",
131            Self::ControlT => b"\x14",
132            Self::ControlU => b"\x15",
133            Self::ControlV => b"\x16",
134            Self::ControlW => b"\x17",
135            Self::ControlX => b"\x18",
136            Self::ControlY => b"\x19",
137            Self::ControlZ => b"\x1a",
138            Self::Enter => b"\r",
139            Self::LineFeed => b"\n",
140            Self::Escape => b"\x1b",
141            Self::Backspace => b"\x08",
142            Self::Tab => b"\t",
143            Self::BackTab => b"\x1b[Z",
144            Self::Insert => b"\x1b[2~",
145            Self::Delete => b"\x1b[3~",
146            Self::Home => b"\x1b[H",
147            Self::End => b"\x1b[F",
148            Self::PageUp => b"\x1b[5~",
149            Self::PageDown => b"\x1b[6~",
150            Self::ArrowUp => b"\x1b[A",
151            Self::ArrowDown => b"\x1b[B",
152            Self::ArrowRight => b"\x1b[C",
153            Self::ArrowLeft => b"\x1b[D",
154            Self::Function1 => b"\x1bOP",
155            Self::Function2 => b"\x1bOQ",
156            Self::Function3 => b"\x1bOR",
157            Self::Function4 => b"\x1bOS",
158            Self::Function5 => b"\x1b[15~",
159            Self::Function6 => b"\x1b[17~",
160            Self::Function7 => b"\x1b[18~",
161            Self::Function8 => b"\x1b[19~",
162            Self::Function9 => b"\x1b[20~",
163            Self::Function10 => b"\x1b[21~",
164            Self::Function11 => b"\x1b[23~",
165            Self::Function12 => b"\x1b[24~",
166        }
167    }
168}
169
170#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
171pub enum InputAction {
172    InsertDraft(PromptPayload),
173    SubmitPrompt(PromptPayload),
174    AgentCommand(AgentCommand),
175    ShellCommand(ShellCommand),
176    TerminalText(TerminalText),
177    TerminalBytes(Vec<u8>),
178    TerminalControl(TerminalControl),
179}
180
181#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
182pub enum PreparedWriteKind {
183    Framing,
184    Data,
185    Submit,
186    Control,
187}
188
189#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
190pub struct PreparedWrite {
191    pub kind: PreparedWriteKind,
192    pub bytes: Vec<u8>,
193    /// Delay after the preceding write and before this write.
194    pub delay_before_ms: u64,
195}
196
197#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
198pub struct PreparedInput {
199    kind: PreparedInputKind,
200    writes: Vec<PreparedWrite>,
201}
202
203#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
204pub enum PreparedInputKind {
205    InsertDraft,
206    SubmitPrompt,
207    AgentCommand,
208    ShellCommand,
209    TerminalText,
210    TerminalBytes,
211    TerminalControl,
212}
213
214impl PreparedInput {
215    /// The operation semantic used to validate its readiness permit.
216    pub fn kind(&self) -> PreparedInputKind {
217        self.kind
218    }
219
220    /// Inspect the bounded write sequence without making it mutable or forgeable.
221    pub fn writes(&self) -> &[PreparedWrite] {
222        &self.writes
223    }
224
225    pub fn into_writes(self) -> Vec<PreparedWrite> {
226        self.writes
227    }
228}
229
230/// Converts an input action to bounded writes without touching a PTY.
231///
232/// Agent and shell commands require a dispatcher that can prove the current
233/// foreground target. Prompt paste and submit are emitted as separate writes.
234pub fn prepare_input(action: InputAction) -> Result<PreparedInput, InputPrepareError> {
235    prepare_input_with_limits(
236        action,
237        TERMINAL_INPUT_CHUNK_MAX_BYTES,
238        TERMINAL_INPUT_MAX_BYTES,
239    )
240}
241
242/// Validate and normalize a semantic prompt before it crosses a process or
243/// protocol boundary. Terminal controls are rendered inert consistently with
244/// PTY prompt preparation, but no terminal framing bytes are added.
245pub fn normalize_semantic_prompt(text: &str) -> Result<String, InputPrepareError> {
246    if text.len() > SEMANTIC_PROMPT_MAX_BYTES {
247        return Err(InputPrepareError::InputTooLarge {
248            bytes: text.len(),
249            max: SEMANTIC_PROMPT_MAX_BYTES,
250        });
251    }
252    Ok(sanitize_prompt_text(text))
253}
254
255pub fn prepare_input_with_limits(
256    action: InputAction,
257    max_chunk_bytes: usize,
258    max_total_bytes: usize,
259) -> Result<PreparedInput, InputPrepareError> {
260    if max_chunk_bytes == 0 {
261        return Err(InputPrepareError::ZeroChunkLimit);
262    }
263    match action {
264        InputAction::InsertDraft(payload) => {
265            prepare_prompt(payload, false, max_chunk_bytes, max_total_bytes)
266        }
267        InputAction::SubmitPrompt(payload) => {
268            prepare_prompt(payload, true, max_chunk_bytes, max_total_bytes)
269        }
270        InputAction::TerminalText(text) => {
271            if let Some((index, character)) = text
272                .text
273                .char_indices()
274                .find(|(_, character)| character.is_control())
275            {
276                return Err(InputPrepareError::ControlCharacterInTerminalText {
277                    index,
278                    codepoint: character as u32,
279                });
280            }
281            bounded_chunks(&text.text, max_chunk_bytes, max_total_bytes).map(|chunks| {
282                PreparedInput {
283                    kind: PreparedInputKind::TerminalText,
284                    writes: chunks
285                        .into_iter()
286                        .map(|bytes| PreparedWrite {
287                            kind: PreparedWriteKind::Data,
288                            bytes,
289                            delay_before_ms: 0,
290                        })
291                        .collect(),
292                }
293            })
294        }
295        InputAction::TerminalBytes(bytes) => {
296            if bytes.is_empty() {
297                return Err(InputPrepareError::EmptyTerminalBytes);
298            }
299            let max_bytes = TERMINAL_BYTES_MAX_BYTES
300                .min(max_chunk_bytes)
301                .min(max_total_bytes);
302            if bytes.len() > max_bytes {
303                return Err(InputPrepareError::InputTooLarge {
304                    bytes: bytes.len(),
305                    max: max_bytes,
306                });
307            }
308            Ok(PreparedInput {
309                kind: PreparedInputKind::TerminalBytes,
310                writes: vec![PreparedWrite {
311                    kind: PreparedWriteKind::Control,
312                    bytes,
313                    delay_before_ms: 0,
314                }],
315            })
316        }
317        InputAction::TerminalControl(control) => Ok(PreparedInput {
318            kind: PreparedInputKind::TerminalControl,
319            writes: vec![PreparedWrite {
320                kind: PreparedWriteKind::Control,
321                bytes: control.bytes().to_vec(),
322                delay_before_ms: 0,
323            }],
324        }),
325        InputAction::AgentCommand(_) => Err(InputPrepareError::AgentDispatcherRequired),
326        InputAction::ShellCommand(_) => Err(InputPrepareError::ShellDispatcherRequired),
327    }
328}
329
330/// Prepare a provider-native slash command after a dispatcher has selected the
331/// foreground agent. Arguments are TUI text segments, not shell arguments.
332pub fn prepare_agent_command(
333    command: AgentCommand,
334    target_agent: &AgentId,
335) -> Result<PreparedInput, InputPrepareError> {
336    if &command.agent_id != target_agent {
337        return Err(InputPrepareError::AgentTargetMismatch {
338            command_agent: command.agent_id,
339            target_agent: target_agent.clone(),
340        });
341    }
342    if command.name.is_empty()
343        || command.name.len() > 128
344        || !command.name.chars().all(|character| {
345            character.is_ascii_lowercase()
346                || character.is_ascii_digit()
347                || matches!(character, '-' | '_')
348        })
349    {
350        return Err(InputPrepareError::InvalidAgentCommandName(command.name));
351    }
352
353    let mut text = format!("/{}", command.name);
354    for (argument_index, argument) in command.arguments.iter().enumerate() {
355        if argument.is_empty()
356            || argument
357                .chars()
358                .any(|character| character.is_control() || character == '\u{1b}')
359        {
360            return Err(InputPrepareError::InvalidAgentCommandArgument { argument_index });
361        }
362        text.push(' ');
363        text.push_str(argument);
364    }
365
366    let chunks = bounded_chunks(
367        &text,
368        TERMINAL_INPUT_CHUNK_MAX_BYTES,
369        TERMINAL_INPUT_MAX_BYTES,
370    )?;
371    let mut writes: Vec<_> = chunks
372        .into_iter()
373        .map(|bytes| PreparedWrite {
374            kind: PreparedWriteKind::Data,
375            bytes,
376            delay_before_ms: 0,
377        })
378        .collect();
379    writes.push(PreparedWrite {
380        kind: PreparedWriteKind::Submit,
381        bytes: TerminalControl::Enter.bytes().to_vec(),
382        delay_before_ms: TERMINAL_SUBMIT_DELAY_MS,
383    });
384    Ok(PreparedInput {
385        kind: PreparedInputKind::AgentCommand,
386        writes,
387    })
388}
389
390/// Prepare an intentional command line for a dispatcher that has just
391/// confirmed a shell owns the PTY foreground.
392///
393/// Shell syntax is preserved. Control characters are rejected so one action
394/// cannot smuggle extra terminal writes or framing sequences past the typed
395/// protocol. Submission remains a separate delayed write.
396pub fn prepare_shell_command(command: ShellCommand) -> Result<PreparedInput, InputPrepareError> {
397    if command.text.trim().is_empty() {
398        return Err(InputPrepareError::EmptyShellCommand);
399    }
400    if let Some((index, character)) = command
401        .text
402        .char_indices()
403        .find(|(_, character)| character.is_control())
404    {
405        return Err(InputPrepareError::ControlCharacterInShellCommand {
406            index,
407            codepoint: character as u32,
408        });
409    }
410
411    let chunks = bounded_chunks(
412        &command.text,
413        TERMINAL_INPUT_CHUNK_MAX_BYTES,
414        TERMINAL_INPUT_MAX_BYTES,
415    )?;
416    let mut writes: Vec<_> = chunks
417        .into_iter()
418        .map(|bytes| PreparedWrite {
419            kind: PreparedWriteKind::Data,
420            bytes,
421            delay_before_ms: 0,
422        })
423        .collect();
424    writes.push(PreparedWrite {
425        kind: PreparedWriteKind::Submit,
426        bytes: TerminalControl::Enter.bytes().to_vec(),
427        delay_before_ms: TERMINAL_SUBMIT_DELAY_MS,
428    });
429    Ok(PreparedInput {
430        kind: PreparedInputKind::ShellCommand,
431        writes,
432    })
433}
434
435/// Shift+Enter bytes for a Windows input-record newline.
436///
437/// `AltEnter` is `\x1b\r`. `CsiU` is `\x1b[13;2u`. The prompt writer uses
438/// these as newlines; it does not append an extra Shift+Enter after the body.
439pub fn shift_enter_sequence(encoding: WindowsPasteNewline) -> &'static [u8] {
440    shift_enter_str(encoding).as_bytes()
441}
442
443/// Ctrl+Enter when the contract names CSI-u: `\x1b[13;5u`.
444///
445/// `prepare_agent_prompt` does not send this chord.
446pub fn ctrl_enter_sequence() -> &'static [u8] {
447    b"\x1b[13;5u"
448}
449
450/// Host flags that choose a PTY chord.
451///
452/// `local_windows_conpty` is a local Windows ConPTY. WSL is not that host.
453#[derive(Clone, Copy, Debug, Eq, PartialEq)]
454pub struct PtyHostGates {
455    pub platform: RuntimePlatform,
456    pub kitty_flags: u32,
457    pub modify_other_keys: u32,
458    pub local_windows_conpty: bool,
459}
460
461/// Chords with fixed Orca `sendInput` bytes.
462///
463/// Option IME, kitty CSI-u text, and layout or dead-key bytes are absent.
464/// Cmd+Up and Cmd+Down scroll the viewport and are not PTY bytes.
465#[derive(Clone, Copy, Debug, Eq, PartialEq)]
466pub enum PtyShortcut {
467    ShiftEnter,
468    AltEnter,
469    CtrlEnter,
470    CtrlBackspace,
471    CmdBackspace,
472    CmdDelete,
473    CmdArrowLeft,
474    CmdArrowRight,
475    AltBackspace,
476    AltDelete {
477        numpad: bool,
478        non_agent_fullscreen: bool,
479    },
480    AltArrowLeft,
481    AltArrowRight,
482    CtrlArrowLeft,
483    CtrlArrowRight,
484}
485
486/// Kitty 0, modifyOtherKeys 0, and ConPTY only when `platform` is Windows.
487pub fn local_plain(platform: RuntimePlatform) -> PtyHostGates {
488    PtyHostGates {
489        platform,
490        kitty_flags: 0,
491        modify_other_keys: 0,
492        local_windows_conpty: platform == RuntimePlatform::Windows,
493    }
494}
495
496/// Encode one Orca chord. `None` means the policy sends no bytes.
497pub fn encode_pty_shortcut(
498    shortcut: PtyShortcut,
499    contract: &PtySubmitContract,
500    host: PtyHostGates,
501) -> Option<&'static [u8]> {
502    match shortcut {
503        PtyShortcut::ShiftEnter => Some(encode_shift_enter(contract, host)),
504        PtyShortcut::AltEnter => encode_alt_enter(host),
505        PtyShortcut::CtrlEnter => Some(encode_ctrl_enter(contract, host)),
506        PtyShortcut::CtrlBackspace => Some(b"\x17"),
507        PtyShortcut::CmdBackspace => mac_command(host, b"\x15"),
508        PtyShortcut::CmdDelete => mac_command(host, b"\x0b"),
509        PtyShortcut::CmdArrowLeft => mac_command(host, b"\x01"),
510        PtyShortcut::CmdArrowRight => mac_command(host, b"\x05"),
511        PtyShortcut::AltBackspace => {
512            if host.kitty_flags > 0 {
513                None
514            } else {
515                Some(b"\x1b\x7f")
516            }
517        }
518        PtyShortcut::AltDelete {
519            numpad,
520            non_agent_fullscreen,
521        } => {
522            if host.platform == RuntimePlatform::MacOs
523                && !numpad
524                && !non_agent_fullscreen
525                && host.kitty_flags == 0
526            {
527                Some(b"\x1bd")
528            } else {
529                None
530            }
531        }
532        PtyShortcut::AltArrowLeft => {
533            word_motion(host.kitty_flags > 0 || host.local_windows_conpty, b"\x1bb")
534        }
535        PtyShortcut::AltArrowRight => {
536            word_motion(host.kitty_flags > 0 || host.local_windows_conpty, b"\x1bf")
537        }
538        PtyShortcut::CtrlArrowLeft => word_motion(
539            host.platform == RuntimePlatform::MacOs || host.local_windows_conpty,
540            b"\x1bb",
541        ),
542        PtyShortcut::CtrlArrowRight => word_motion(
543            host.platform == RuntimePlatform::MacOs || host.local_windows_conpty,
544            b"\x1bf",
545        ),
546    }
547}
548
549fn encode_shift_enter(contract: &PtySubmitContract, host: PtyHostGates) -> &'static [u8] {
550    let windows_host = host.platform == RuntimePlatform::Windows;
551    let trusted_windows_csi_u =
552        windows_host && contract.windows_shift_enter == Some(ModifiedEnterEncoding::CsiU);
553    let can_csi_u = trusted_windows_csi_u || host.kitty_flags > 0;
554    if can_csi_u {
555        shift_enter_sequence(WindowsPasteNewline::CsiU)
556    } else if host.modify_other_keys > 0 {
557        b"\x1b[27;2;13~"
558    } else {
559        shift_enter_sequence(WindowsPasteNewline::AltEnter)
560    }
561}
562
563fn encode_alt_enter(host: PtyHostGates) -> Option<&'static [u8]> {
564    if host.kitty_flags > 0 {
565        None
566    } else if host.modify_other_keys > 0 {
567        Some(b"\x1b[27;3;13~")
568    } else {
569        None
570    }
571}
572
573fn encode_ctrl_enter(contract: &PtySubmitContract, host: PtyHostGates) -> &'static [u8] {
574    let can_csi_u = !host.local_windows_conpty
575        || host.kitty_flags > 0
576        || contract.ctrl_enter == Some(ModifiedEnterEncoding::CsiU);
577    if can_csi_u {
578        ctrl_enter_sequence()
579    } else {
580        b"\r"
581    }
582}
583
584fn mac_command(host: PtyHostGates, bytes: &'static [u8]) -> Option<&'static [u8]> {
585    if host.platform == RuntimePlatform::MacOs {
586        Some(bytes)
587    } else {
588        None
589    }
590}
591
592fn word_motion(suppressed: bool, bytes: &'static [u8]) -> Option<&'static [u8]> {
593    if suppressed {
594        None
595    } else {
596        Some(bytes)
597    }
598}
599
600/// One control write when the policy has bytes. `None` stays `None`.
601pub fn prepare_pty_shortcut(
602    shortcut: PtyShortcut,
603    contract: &PtySubmitContract,
604    host: PtyHostGates,
605) -> Option<PreparedInput> {
606    let bytes = encode_pty_shortcut(shortcut, contract, host)?;
607    Some(PreparedInput {
608        kind: PreparedInputKind::TerminalControl,
609        writes: vec![PreparedWrite {
610            kind: PreparedWriteKind::Control,
611            bytes: bytes.to_vec(),
612            delay_before_ms: 0,
613        }],
614    })
615}
616
617fn shift_enter_str(encoding: WindowsPasteNewline) -> &'static str {
618    match encoding {
619        WindowsPasteNewline::AltEnter => "\u{1b}\r",
620        WindowsPasteNewline::CsiU => "\u{1b}[13;2u",
621    }
622}
623
624/// Frame one prompt using the shared submit contract.
625///
626/// On Windows, when `windows_paste_newline` is set, the body is an
627/// input-record paste: CR, LF, and CRLF each become one Alt+Enter or CSI-u
628/// Shift+Enter, ESC becomes U+241B, and the body is not bracketed. A typed
629/// lead, when requested, stays in front of that body and is only space-folded.
630///
631/// Every other platform, and Windows without that newline, keeps the
632/// bracketed `<ESC>` paste. `lead` is typed only when
633/// `paste_needs_typed_request` is set and the folded lead is non-empty. The
634/// host supplies that sentence; this function does not invent one. Enter
635/// joins the paste frame only when `submit_joins_paste_frame` is set (omp).
636/// Every other submit is a later write delayed by `500 + ingest + line_settle`,
637/// uncapped. Ctrl+Enter is never written here.
638pub fn prepare_agent_prompt(
639    text: &str,
640    submit: bool,
641    contract: &PtySubmitContract,
642    platform: RuntimePlatform,
643    lead: Option<&str>,
644) -> Result<PreparedInput, InputPrepareError> {
645    if text.len() > TERMINAL_INPUT_MAX_BYTES {
646        return Err(InputPrepareError::InputTooLarge {
647            bytes: text.len(),
648            max: TERMINAL_INPUT_MAX_BYTES,
649        });
650    }
651    let input_record = (platform == RuntimePlatform::Windows)
652        .then_some(contract.windows_paste_newline)
653        .flatten();
654    let mut framed = String::new();
655    if contract.paste_needs_typed_request {
656        if let Some(lead) = lead {
657            framed.push_str(&fold_typed_request_lead(lead));
658        }
659    }
660    if let Some(newline) = input_record {
661        framed.push_str(&encode_windows_input_record_paste_text(text, newline));
662    } else {
663        let body = sanitize_prompt_text(text);
664        framed.push_str("\u{1b}[200~");
665        framed.push_str(&body);
666        framed.push_str("\u{1b}[201~");
667        debug_assert_eq!("\u{1b}[200~".as_bytes(), BRACKETED_PASTE_START);
668        debug_assert_eq!("\u{1b}[201~".as_bytes(), BRACKETED_PASTE_END);
669    }
670    if framed.len() > TERMINAL_INPUT_MAX_BYTES {
671        return Err(InputPrepareError::InputTooLarge {
672            bytes: framed.len(),
673            max: TERMINAL_INPUT_MAX_BYTES,
674        });
675    }
676    let framed_len = framed.len();
677    let mut chunks = if input_record.is_some() {
678        bounded_chunks_atomic_records(
679            &framed,
680            TERMINAL_INPUT_CHUNK_MAX_BYTES,
681            TERMINAL_INPUT_MAX_BYTES,
682        )?
683    } else {
684        bounded_chunks(
685            &framed,
686            TERMINAL_INPUT_CHUNK_MAX_BYTES,
687            TERMINAL_INPUT_MAX_BYTES,
688        )?
689    };
690    if submit && contract.submit_joins_paste_frame {
691        match chunks.last_mut() {
692            Some(last) => last.extend_from_slice(b"\r"),
693            None => chunks.push(b"\r".to_vec()),
694        }
695    }
696    let mut writes: Vec<_> = chunks
697        .into_iter()
698        .map(|bytes| PreparedWrite {
699            kind: PreparedWriteKind::Data,
700            bytes,
701            delay_before_ms: 0,
702        })
703        .collect();
704    if submit && !contract.submit_joins_paste_frame {
705        writes.push(PreparedWrite {
706            kind: PreparedWriteKind::Submit,
707            bytes: TerminalControl::Enter.bytes().to_vec(),
708            delay_before_ms: separate_submit_delay_ms(text, framed_len, contract, platform),
709        });
710    }
711    Ok(PreparedInput {
712        kind: if submit {
713            PreparedInputKind::SubmitPrompt
714        } else {
715            PreparedInputKind::InsertDraft
716        },
717        writes,
718    })
719}
720
721fn separate_submit_delay_ms(
722    prompt: &str,
723    framed_len: usize,
724    contract: &PtySubmitContract,
725    platform: RuntimePlatform,
726) -> u64 {
727    TERMINAL_SUBMIT_DELAY_MS
728        .saturating_add(paste_ingest_ms(framed_len, platform))
729        .saturating_add(line_settle_ms(prompt, contract.submit_line_settle_ms_per_line))
730}
731
732fn paste_ingest_ms(utf8_len: usize, platform: RuntimePlatform) -> u64 {
733    if utf8_len == 0 {
734        return 0;
735    }
736    let divisor: u64 = if platform == RuntimePlatform::Windows {
737        64
738    } else {
739        4096
740    };
741    (utf8_len as u64).div_ceil(divisor)
742}
743
744fn line_settle_ms(prompt: &str, per_line: u64) -> u64 {
745    if per_line == 0 {
746        return 0;
747    }
748    let line_count = (prompt.matches('\n').count() as u64).saturating_add(1).max(1);
749    line_count.saturating_mul(per_line)
750}
751
752/// Controls become single spaces, the line is folded, and one trailing space
753/// is kept so the paste frame is not glued to the typed request.
754fn fold_typed_request_lead(lead: &str) -> String {
755    let mut out = String::new();
756    let mut last_was_space = false;
757    let mut any_text = false;
758    for character in lead.chars() {
759        if character.is_control() || character == ' ' {
760            if any_text && !last_was_space {
761                out.push(' ');
762                last_was_space = true;
763            }
764        } else {
765            out.push(character);
766            last_was_space = false;
767            any_text = true;
768        }
769    }
770    if !any_text {
771        return String::new();
772    }
773    out.push(' ');
774    out
775}
776
777/// Windows input-record paste. CR, LF, and CRLF are one newline. ESC becomes
778/// U+241B. Other scalars, including tabs and the rest of C0, pass through.
779/// The result is not wrapped in bracketed-paste markers.
780fn encode_windows_input_record_paste_text(text: &str, newline: WindowsPasteNewline) -> String {
781    let sequence = shift_enter_str(newline);
782    let mut encoded = String::with_capacity(text.len());
783    let mut chars = text.chars().peekable();
784    while let Some(character) = chars.next() {
785        match character {
786            '\r' => {
787                encoded.push_str(sequence);
788                if chars.peek() == Some(&'\n') {
789                    chars.next();
790                }
791            }
792            '\n' => encoded.push_str(sequence),
793            '\u{1b}' => encoded.push('\u{241b}'),
794            other => encoded.push(other),
795        }
796    }
797    encoded
798}
799
800fn prepare_prompt(
801    payload: PromptPayload,
802    submit: bool,
803    max_chunk_bytes: usize,
804    max_total_bytes: usize,
805) -> Result<PreparedInput, InputPrepareError> {
806    if payload.text.len() > max_total_bytes {
807        return Err(InputPrepareError::InputTooLarge {
808            bytes: payload.text.len(),
809            max: max_total_bytes,
810        });
811    }
812    let sanitized = sanitize_prompt_text(&payload.text);
813    let chunks = bounded_chunks(&sanitized, max_chunk_bytes, max_total_bytes)?;
814    let mut writes = Vec::with_capacity(chunks.len() + 3);
815
816    if payload.framing == PromptFraming::BracketedPaste {
817        writes.push(PreparedWrite {
818            kind: PreparedWriteKind::Framing,
819            bytes: BRACKETED_PASTE_START.to_vec(),
820            delay_before_ms: 0,
821        });
822    }
823    writes.extend(chunks.into_iter().map(|bytes| PreparedWrite {
824        kind: PreparedWriteKind::Data,
825        bytes,
826        delay_before_ms: 0,
827    }));
828    if payload.framing == PromptFraming::BracketedPaste {
829        writes.push(PreparedWrite {
830            kind: PreparedWriteKind::Framing,
831            bytes: BRACKETED_PASTE_END.to_vec(),
832            delay_before_ms: 0,
833        });
834    }
835    if submit {
836        writes.push(PreparedWrite {
837            kind: PreparedWriteKind::Submit,
838            bytes: TerminalControl::Enter.bytes().to_vec(),
839            delay_before_ms: TERMINAL_SUBMIT_DELAY_MS,
840        });
841    }
842
843    Ok(PreparedInput {
844        kind: if submit {
845            PreparedInputKind::SubmitPrompt
846        } else {
847            PreparedInputKind::InsertDraft
848        },
849        writes,
850    })
851}
852
853/// Neutralizes terminal control sequences while preserving prompt newlines and tabs.
854pub fn sanitize_prompt_text(text: &str) -> String {
855    let mut sanitized = String::with_capacity(text.len());
856    for character in text.chars() {
857        match character {
858            '\n' | '\r' | '\t' => sanitized.push(character),
859            '\u{1b}' => sanitized.push_str("<ESC>"),
860            '\u{009b}' => sanitized.push_str("<CSI>"),
861            '\u{009d}' => sanitized.push_str("<OSC>"),
862            value if value.is_control() => {
863                use std::fmt::Write;
864                let _ = write!(sanitized, "<U+{:04X}>", value as u32);
865            }
866            value => sanitized.push(value),
867        }
868    }
869    sanitized
870}
871
872fn bounded_chunks(
873    text: &str,
874    max_chunk_bytes: usize,
875    max_total_bytes: usize,
876) -> Result<Vec<Vec<u8>>, InputPrepareError> {
877    if text.len() > max_total_bytes {
878        return Err(InputPrepareError::InputTooLarge {
879            bytes: text.len(),
880            max: max_total_bytes,
881        });
882    }
883    if text.is_empty() {
884        return Ok(Vec::new());
885    }
886
887    let mut chunks = Vec::new();
888    let mut start = 0;
889    let mut current_bytes = 0;
890    for (index, character) in text.char_indices() {
891        let character_bytes = character.len_utf8();
892        if character_bytes > max_chunk_bytes {
893            return Err(InputPrepareError::ChunkLimitTooSmall {
894                bytes: character_bytes,
895                max: max_chunk_bytes,
896            });
897        }
898        if current_bytes + character_bytes > max_chunk_bytes {
899            chunks.push(text.as_bytes()[start..index].to_vec());
900            start = index;
901            current_bytes = 0;
902        }
903        current_bytes += character_bytes;
904    }
905    chunks.push(text.as_bytes()[start..].to_vec());
906    Ok(chunks)
907}
908
909/// Like [`bounded_chunks`], but an input-record newline (`ESC CR` or CSI-u)
910/// is one piece and is never split across writes.
911fn bounded_chunks_atomic_records(
912    text: &str,
913    max_chunk_bytes: usize,
914    max_total_bytes: usize,
915) -> Result<Vec<Vec<u8>>, InputPrepareError> {
916    if text.len() > max_total_bytes {
917        return Err(InputPrepareError::InputTooLarge {
918            bytes: text.len(),
919            max: max_total_bytes,
920        });
921    }
922    if text.is_empty() {
923        return Ok(Vec::new());
924    }
925    let mut chunks = Vec::new();
926    let mut current = Vec::new();
927    let mut rest = text;
928    while !rest.is_empty() {
929        let piece = next_atomic_record(rest);
930        let bytes = piece.as_bytes();
931        if bytes.len() > max_chunk_bytes {
932            return Err(InputPrepareError::ChunkLimitTooSmall {
933                bytes: bytes.len(),
934                max: max_chunk_bytes,
935            });
936        }
937        if !current.is_empty() && current.len() + bytes.len() > max_chunk_bytes {
938            chunks.push(std::mem::take(&mut current));
939        }
940        current.extend_from_slice(bytes);
941        rest = &rest[piece.len()..];
942    }
943    if !current.is_empty() {
944        chunks.push(current);
945    }
946    Ok(chunks)
947}
948
949fn next_atomic_record(text: &str) -> &str {
950    let Some(first) = text.chars().next() else {
951        return "";
952    };
953    if first != '\u{1b}' {
954        return &text[..first.len_utf8()];
955    }
956    let bytes = text.as_bytes();
957    if bytes.len() >= 2 && bytes[1] == b'\r' {
958        return &text[..2];
959    }
960    const CSI_U: &str = "\u{1b}[13;2u";
961    if text.starts_with(CSI_U) {
962        return &text[..CSI_U.len()];
963    }
964    &text[..first.len_utf8()]
965}
966
967#[derive(Clone, Debug, Deserialize, Eq, Error, PartialEq, Serialize)]
968pub enum InputPrepareError {
969    #[error("terminal input chunk limit cannot be zero")]
970    ZeroChunkLimit,
971    #[error("input is {bytes} bytes; the configured limit is {max} bytes")]
972    InputTooLarge { bytes: usize, max: usize },
973    #[error("a {bytes}-byte UTF-8 code point does not fit the {max}-byte chunk limit")]
974    ChunkLimitTooSmall { bytes: usize, max: usize },
975    #[error("terminal byte sequence cannot be empty")]
976    EmptyTerminalBytes,
977    #[error(
978        "terminal text contains control U+{codepoint:04X} at byte {index}; use TerminalControl"
979    )]
980    ControlCharacterInTerminalText { index: usize, codepoint: u32 },
981    #[error("agent commands require a provider-specific capability dispatcher")]
982    AgentDispatcherRequired,
983    #[error("agent command targets '{command_agent}', but foreground dispatcher selected '{target_agent}'")]
984    AgentTargetMismatch {
985        command_agent: AgentId,
986        target_agent: AgentId,
987    },
988    #[error("invalid agent command name '{0}'")]
989    InvalidAgentCommandName(String),
990    #[error("agent command argument {argument_index} is empty or contains terminal controls")]
991    InvalidAgentCommandArgument { argument_index: usize },
992    #[error("shell commands require a confirmed foreground shell dispatcher")]
993    ShellDispatcherRequired,
994    #[error("shell command cannot be empty")]
995    EmptyShellCommand,
996    #[error("shell command contains control U+{codepoint:04X} at byte {index}")]
997    ControlCharacterInShellCommand { index: usize, codepoint: u32 },
998}
999
1000#[cfg(test)]
1001mod tests {
1002    use super::*;
1003
1004    fn payload(text: &str) -> PromptPayload {
1005        PromptPayload {
1006            text: text.to_owned(),
1007            framing: PromptFraming::BracketedPaste,
1008        }
1009    }
1010
1011    #[test]
1012    fn draft_and_submit_have_distinct_write_sequences() {
1013        let draft = prepare_input(InputAction::InsertDraft(payload("hello"))).unwrap();
1014        let submit = prepare_input(InputAction::SubmitPrompt(payload("hello"))).unwrap();
1015        assert_eq!(draft.writes.last().unwrap().bytes, BRACKETED_PASTE_END);
1016        assert_eq!(
1017            submit.writes.last().unwrap().kind,
1018            PreparedWriteKind::Submit
1019        );
1020        assert_eq!(submit.writes.last().unwrap().bytes, b"\r");
1021        assert_eq!(
1022            submit.writes.last().unwrap().delay_before_ms,
1023            TERMINAL_SUBMIT_DELAY_MS
1024        );
1025    }
1026
1027    #[test]
1028    fn prompt_controls_are_inert_inside_bracketed_paste() {
1029        let prepared = prepare_input(InputAction::InsertDraft(payload("a\x1b[31m\0b"))).unwrap();
1030        let joined: Vec<u8> = prepared
1031            .writes
1032            .iter()
1033            .flat_map(|write| write.bytes.iter().copied())
1034            .collect();
1035        assert_eq!(
1036            String::from_utf8(joined).unwrap(),
1037            "\x1b[200~a<ESC>[31m<U+0000>b\x1b[201~"
1038        );
1039    }
1040
1041    #[test]
1042    fn chunks_never_split_unicode() {
1043        let prepared = prepare_input_with_limits(
1044            InputAction::TerminalText(TerminalText {
1045                text: "aЖ🙂b".to_owned(),
1046            }),
1047            4,
1048            32,
1049        )
1050        .unwrap();
1051        let decoded: Vec<_> = prepared
1052            .writes
1053            .iter()
1054            .map(|write| std::str::from_utf8(&write.bytes).unwrap())
1055            .collect();
1056        assert_eq!(decoded, ["aЖ", "🙂", "b"]);
1057    }
1058
1059    #[test]
1060    fn raw_controls_require_the_control_variant() {
1061        let error = prepare_input(InputAction::TerminalText(TerminalText {
1062            text: "hello\n".to_owned(),
1063        }))
1064        .unwrap_err();
1065        assert!(matches!(
1066            error,
1067            InputPrepareError::ControlCharacterInTerminalText { .. }
1068        ));
1069    }
1070
1071    #[test]
1072    fn terminal_bytes_preserve_one_bounded_sequence_without_framing() {
1073        let sequence = b"\x1b[1;5D".to_vec();
1074        let prepared = prepare_input(InputAction::TerminalBytes(sequence.clone())).unwrap();
1075        assert_eq!(prepared.kind(), PreparedInputKind::TerminalBytes);
1076        assert_eq!(
1077            prepared.writes(),
1078            &[PreparedWrite {
1079                kind: PreparedWriteKind::Control,
1080                bytes: sequence,
1081                delay_before_ms: 0,
1082            }]
1083        );
1084    }
1085
1086    #[test]
1087    fn terminal_bytes_reject_empty_and_oversized_sequences() {
1088        assert_eq!(
1089            prepare_input(InputAction::TerminalBytes(Vec::new())).unwrap_err(),
1090            InputPrepareError::EmptyTerminalBytes,
1091        );
1092        assert_eq!(
1093            prepare_input(InputAction::TerminalBytes(vec![0; TERMINAL_BYTES_MAX_BYTES + 1]))
1094                .unwrap_err(),
1095            InputPrepareError::InputTooLarge {
1096                bytes: TERMINAL_BYTES_MAX_BYTES + 1,
1097                max: TERMINAL_BYTES_MAX_BYTES,
1098            },
1099        );
1100    }
1101
1102    #[test]
1103    fn arrow_controls_preserve_terminal_escape_sequences() {
1104        assert_eq!(TerminalControl::ArrowUp.bytes(), b"\x1b[A");
1105        assert_eq!(TerminalControl::ArrowDown.bytes(), b"\x1b[B");
1106        assert_eq!(TerminalControl::ArrowRight.bytes(), b"\x1b[C");
1107        assert_eq!(TerminalControl::ArrowLeft.bytes(), b"\x1b[D");
1108    }
1109
1110    #[test]
1111    fn interactive_terminal_controls_preserve_xterm_sequences() {
1112        assert_eq!(TerminalControl::BackTab.bytes(), b"\x1b[Z");
1113        assert_eq!(TerminalControl::Insert.bytes(), b"\x1b[2~");
1114        assert_eq!(TerminalControl::Delete.bytes(), b"\x1b[3~");
1115        assert_eq!(TerminalControl::Home.bytes(), b"\x1b[H");
1116        assert_eq!(TerminalControl::End.bytes(), b"\x1b[F");
1117        assert_eq!(TerminalControl::PageUp.bytes(), b"\x1b[5~");
1118        assert_eq!(TerminalControl::PageDown.bytes(), b"\x1b[6~");
1119        assert_eq!(TerminalControl::Function1.bytes(), b"\x1bOP");
1120        assert_eq!(TerminalControl::Function12.bytes(), b"\x1b[24~");
1121        assert_eq!(TerminalControl::ControlA.bytes(), b"\x01");
1122        assert_eq!(TerminalControl::ControlZ.bytes(), b"\x1a");
1123    }
1124
1125    #[test]
1126    fn agent_command_is_target_bound_and_delays_submit() {
1127        let agent = AgentId::new("codex").unwrap();
1128        let prepared = prepare_agent_command(
1129            AgentCommand {
1130                agent_id: agent.clone(),
1131                name: "review".to_owned(),
1132                arguments: vec!["focus on PTY ordering".to_owned()],
1133            },
1134            &agent,
1135        )
1136        .unwrap();
1137        assert_eq!(prepared.writes[0].bytes, b"/review focus on PTY ordering");
1138        assert_eq!(
1139            prepared.writes.last().unwrap().delay_before_ms,
1140            TERMINAL_SUBMIT_DELAY_MS
1141        );
1142    }
1143
1144    #[test]
1145    fn agent_command_rejects_controls_and_foreign_targets() {
1146        let codex = AgentId::new("codex").unwrap();
1147        let kimi = AgentId::new("kimi").unwrap();
1148        let foreign = prepare_agent_command(
1149            AgentCommand {
1150                agent_id: codex.clone(),
1151                name: "help".to_owned(),
1152                arguments: Vec::new(),
1153            },
1154            &kimi,
1155        )
1156        .unwrap_err();
1157        assert!(matches!(
1158            foreign,
1159            InputPrepareError::AgentTargetMismatch { .. }
1160        ));
1161
1162        let control = prepare_agent_command(
1163            AgentCommand {
1164                agent_id: codex.clone(),
1165                name: "rename".to_owned(),
1166                arguments: vec!["unsafe\rsubmit".to_owned()],
1167            },
1168            &codex,
1169        )
1170        .unwrap_err();
1171        assert!(matches!(
1172            control,
1173            InputPrepareError::InvalidAgentCommandArgument { .. }
1174        ));
1175    }
1176
1177    #[test]
1178    fn shell_command_preserves_syntax_and_submits_separately() {
1179        let prepared = prepare_shell_command(ShellCommand {
1180            text: "printf '%s' \"hello world\" | sed 's/world/shell/'".to_owned(),
1181        })
1182        .unwrap();
1183
1184        assert_eq!(prepared.kind(), PreparedInputKind::ShellCommand);
1185        assert_eq!(
1186            prepared.writes[0].bytes,
1187            b"printf '%s' \"hello world\" | sed 's/world/shell/'"
1188        );
1189        assert_eq!(prepared.writes.last().unwrap().bytes, b"\r");
1190        assert_eq!(
1191            prepared.writes.last().unwrap().delay_before_ms,
1192            TERMINAL_SUBMIT_DELAY_MS
1193        );
1194    }
1195
1196    fn claude_contract() -> PtySubmitContract {
1197        PtySubmitContract {
1198            paste_needs_typed_request: true,
1199            ctrl_enter: Some(crate::ModifiedEnterEncoding::CsiU),
1200            ..PtySubmitContract::default()
1201        }
1202    }
1203
1204    #[test]
1205    fn prepare_agent_prompt_omp_joins_enter_into_the_paste_frame() {
1206        let contract = PtySubmitContract {
1207            submit_joins_paste_frame: true,
1208            ..PtySubmitContract::default()
1209        };
1210        let prepared = prepare_agent_prompt(
1211            "brief",
1212            true,
1213            &contract,
1214            crate::RuntimePlatform::Linux,
1215            None,
1216        )
1217        .unwrap();
1218        assert_eq!(prepared.writes().len(), 1);
1219        assert!(prepared.writes()[0].bytes.ends_with(b"\x1b[201~\r"));
1220        assert!(prepared
1221            .writes()
1222            .iter()
1223            .all(|write| write.kind != PreparedWriteKind::Submit));
1224        let mut expected = BRACKETED_PASTE_START.to_vec();
1225        expected.extend_from_slice(b"brief");
1226        expected.extend_from_slice(BRACKETED_PASTE_END);
1227        expected.extend_from_slice(b"\r");
1228        assert_eq!(prepared.writes()[0].bytes, expected);
1229    }
1230
1231    #[test]
1232    fn prepare_agent_prompt_claude_lead_is_outside_the_frame() {
1233        let lead = "Please\r\nfollow\x03\x1b[201~\x7f";
1234        let prepared = prepare_agent_prompt(
1235            "brief",
1236            true,
1237            &claude_contract(),
1238            crate::RuntimePlatform::Linux,
1239            Some(lead),
1240        )
1241        .unwrap();
1242        let mut frame = b"Please follow [201~  ".to_vec();
1243        frame.extend_from_slice(BRACKETED_PASTE_START);
1244        frame.extend_from_slice(b"brief");
1245        frame.extend_from_slice(BRACKETED_PASTE_END);
1246        assert_eq!(prepared.writes().len(), 2);
1247        assert_eq!(prepared.writes()[0].bytes, frame);
1248        assert_eq!(prepared.writes()[1].kind, PreparedWriteKind::Submit);
1249        assert_eq!(prepared.writes()[1].bytes, b"\r");
1250        let ingest = (frame.len() as u64).div_ceil(4096);
1251        assert_eq!(
1252            prepared.writes()[1].delay_before_ms,
1253            TERMINAL_SUBMIT_DELAY_MS + ingest
1254        );
1255        let empty_lead = prepare_agent_prompt(
1256            "brief",
1257            false,
1258            &claude_contract(),
1259            crate::RuntimePlatform::Linux,
1260            Some(""),
1261        )
1262        .unwrap();
1263        assert_eq!(
1264            empty_lead.writes()[0].bytes,
1265            {
1266                let mut bare = BRACKETED_PASTE_START.to_vec();
1267                bare.extend_from_slice(b"brief");
1268                bare.extend_from_slice(BRACKETED_PASTE_END);
1269                bare
1270            }
1271        );
1272    }
1273
1274    #[test]
1275    fn prepare_agent_prompt_antigravity_line_settle_scales_with_newlines() {
1276        let antigravity = PtySubmitContract {
1277            submit_line_settle_ms_per_line: 45,
1278            ..PtySubmitContract::default()
1279        };
1280        let one = prepare_agent_prompt(
1281            "one",
1282            true,
1283            &antigravity,
1284            crate::RuntimePlatform::Linux,
1285            None,
1286        )
1287        .unwrap();
1288        let many = prepare_agent_prompt(
1289            &"\n".repeat(100),
1290            true,
1291            &antigravity,
1292            crate::RuntimePlatform::MacOs,
1293            None,
1294        )
1295        .unwrap();
1296        let aider = prepare_agent_prompt(
1297            "one",
1298            true,
1299            &PtySubmitContract::default(),
1300            crate::RuntimePlatform::Linux,
1301            None,
1302        )
1303        .unwrap();
1304        let one_delay = one.writes().last().unwrap().delay_before_ms;
1305        let many_delay = many.writes().last().unwrap().delay_before_ms;
1306        let aider_delay = aider.writes().last().unwrap().delay_before_ms;
1307        assert!(many_delay - one_delay >= 4_500);
1308        assert_eq!(aider_delay, one_delay - 45);
1309        assert!(one_delay > TERMINAL_SUBMIT_DELAY_MS);
1310    }
1311
1312    #[test]
1313    fn prepare_input_submit_keeps_separate_enter_delay() {
1314        let prepared = prepare_input(InputAction::SubmitPrompt(payload("brief"))).unwrap();
1315        let submit = prepared
1316            .writes()
1317            .iter()
1318            .find(|write| write.kind == PreparedWriteKind::Submit)
1319            .unwrap();
1320        assert_eq!(submit.bytes, b"\r");
1321        assert_eq!(submit.delay_before_ms, 500);
1322        assert!(prepared.writes().len() > 1);
1323    }
1324
1325    #[test]
1326    fn shell_command_rejects_empty_and_control_bearing_text() {
1327        assert_eq!(
1328            prepare_shell_command(ShellCommand {
1329                text: "   ".to_owned(),
1330            })
1331            .unwrap_err(),
1332            InputPrepareError::EmptyShellCommand
1333        );
1334        assert!(matches!(
1335            prepare_shell_command(ShellCommand {
1336                text: "echo first\necho second".to_owned(),
1337            })
1338            .unwrap_err(),
1339            InputPrepareError::ControlCharacterInShellCommand {
1340                index: 10,
1341                codepoint: 10
1342            }
1343        ));
1344    }
1345
1346    fn windows_newline(encoding: crate::WindowsPasteNewline) -> PtySubmitContract {
1347        PtySubmitContract {
1348            windows_paste_newline: Some(encoding),
1349            ..PtySubmitContract::default()
1350        }
1351    }
1352
1353    #[test]
1354    fn encode_windows_alt_enter_rewrites_a_newline_without_brackets() {
1355        let prepared = prepare_agent_prompt(
1356            "a\nb",
1357            true,
1358            &windows_newline(crate::WindowsPasteNewline::AltEnter),
1359            crate::RuntimePlatform::Windows,
1360            None,
1361        )
1362        .unwrap();
1363        assert_eq!(prepared.writes().len(), 2);
1364        assert_eq!(prepared.writes()[0].bytes, b"a\x1b\rb");
1365        assert!(
1366            !prepared.writes()[0].bytes.windows(6).any(|window| {
1367                window == b"\x1b[200~" || window == b"\x1b[201~"
1368            })
1369        );
1370        assert_eq!(prepared.writes()[1].kind, PreparedWriteKind::Submit);
1371        assert_eq!(prepared.writes()[1].bytes, b"\r");
1372        assert!(!prepared.writes()[0].bytes.windows(7).any(|window| window == b"\x1b[13;5u"));
1373    }
1374
1375    #[test]
1376    fn encode_windows_csi_u_newline_is_shift_enter() {
1377        let prepared = prepare_agent_prompt(
1378            "a\nb",
1379            false,
1380            &windows_newline(crate::WindowsPasteNewline::CsiU),
1381            crate::RuntimePlatform::Windows,
1382            None,
1383        )
1384        .unwrap();
1385        assert_eq!(prepared.writes().len(), 1);
1386        assert_eq!(prepared.writes()[0].bytes, b"a\x1b[13;2ub");
1387    }
1388
1389    #[test]
1390    fn encode_windows_crlf_is_one_alt_enter() {
1391        let contract = windows_newline(crate::WindowsPasteNewline::AltEnter);
1392        let crlf = prepare_agent_prompt(
1393            "a\r\nb",
1394            false,
1395            &contract,
1396            crate::RuntimePlatform::Windows,
1397            None,
1398        )
1399        .unwrap();
1400        let lf = prepare_agent_prompt(
1401            "a\nb",
1402            false,
1403            &contract,
1404            crate::RuntimePlatform::Windows,
1405            None,
1406        )
1407        .unwrap();
1408        let cr = prepare_agent_prompt(
1409            "a\rb",
1410            false,
1411            &contract,
1412            crate::RuntimePlatform::Windows,
1413            None,
1414        )
1415        .unwrap();
1416        assert_eq!(crlf.writes()[0].bytes, b"a\x1b\rb");
1417        assert_eq!(crlf.writes()[0].bytes, lf.writes()[0].bytes);
1418        assert_eq!(cr.writes()[0].bytes, lf.writes()[0].bytes);
1419        let two = prepare_agent_prompt(
1420            "a\r\n\r\nb",
1421            false,
1422            &contract,
1423            crate::RuntimePlatform::Windows,
1424            None,
1425        )
1426        .unwrap();
1427        assert_eq!(two.writes()[0].bytes, b"a\x1b\r\x1b\rb");
1428    }
1429
1430    #[test]
1431    fn encode_windows_esc_becomes_symbol_for_escape() {
1432        let prepared = prepare_agent_prompt(
1433            "a\u{1b}b",
1434            false,
1435            &windows_newline(crate::WindowsPasteNewline::AltEnter),
1436            crate::RuntimePlatform::Windows,
1437            None,
1438        )
1439        .unwrap();
1440        assert_eq!(prepared.writes()[0].bytes, "a\u{241b}b".as_bytes());
1441        assert!(!prepared.writes()[0]
1442            .bytes
1443            .windows(5)
1444            .any(|window| window == b"<ESC>"));
1445    }
1446
1447    #[test]
1448    fn encode_windows_lead_stays_outside_the_newline_encoder() {
1449        let contract = PtySubmitContract {
1450            paste_needs_typed_request: true,
1451            windows_paste_newline: Some(crate::WindowsPasteNewline::AltEnter),
1452            ..PtySubmitContract::default()
1453        };
1454        let prepared = prepare_agent_prompt(
1455            "a\nb",
1456            false,
1457            &contract,
1458            crate::RuntimePlatform::Windows,
1459            Some("Please\r\nfollow\x03\x1b[201~\x7f"),
1460        )
1461        .unwrap();
1462        assert_eq!(prepared.writes()[0].bytes, b"Please follow [201~  a\x1b\rb");
1463        assert!(
1464            !prepared.writes()[0]
1465                .bytes
1466                .windows(6)
1467                .any(|window| window == b"\x1b[200~" || window == b"\x1b[201~")
1468        );
1469    }
1470
1471    #[test]
1472    fn encode_windows_newline_is_not_split_across_chunks() {
1473        let mut body = "a".repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES - 1);
1474        body.push('\n');
1475        body.push('b');
1476        let prepared = prepare_agent_prompt(
1477            &body,
1478            false,
1479            &windows_newline(crate::WindowsPasteNewline::AltEnter),
1480            crate::RuntimePlatform::Windows,
1481            None,
1482        )
1483        .unwrap();
1484        assert_eq!(prepared.writes().len(), 2);
1485        assert_eq!(
1486            prepared.writes()[0].bytes,
1487            vec![b'a'; TERMINAL_INPUT_CHUNK_MAX_BYTES - 1]
1488        );
1489        assert_eq!(prepared.writes()[1].bytes, b"\x1b\rb");
1490    }
1491
1492    #[test]
1493    fn encode_windows_newline_stays_bracketed_off_windows() {
1494        let contract = windows_newline(crate::WindowsPasteNewline::AltEnter);
1495        for platform in [
1496            crate::RuntimePlatform::Linux,
1497            crate::RuntimePlatform::MacOs,
1498            crate::RuntimePlatform::Wsl,
1499        ] {
1500            let prepared = prepare_agent_prompt("a\nb\u{1b}c", false, &contract, platform, None)
1501                .unwrap();
1502            let joined: Vec<u8> = prepared
1503                .writes()
1504                .iter()
1505                .flat_map(|write| write.bytes.iter().copied())
1506                .collect();
1507            assert_eq!(
1508                String::from_utf8(joined).unwrap(),
1509                "\u{1b}[200~a\nb<ESC>c\u{1b}[201~"
1510            );
1511        }
1512    }
1513
1514    #[test]
1515    fn encode_windows_without_newline_contract_stays_bracketed() {
1516        let prepared = prepare_agent_prompt(
1517            "a\nb\u{1b}c",
1518            false,
1519            &PtySubmitContract::default(),
1520            crate::RuntimePlatform::Windows,
1521            None,
1522        )
1523        .unwrap();
1524        let joined: Vec<u8> = prepared
1525            .writes()
1526            .iter()
1527            .flat_map(|write| write.bytes.iter().copied())
1528            .collect();
1529        assert_eq!(
1530            String::from_utf8(joined).unwrap(),
1531            "\u{1b}[200~a\nb<ESC>c\u{1b}[201~"
1532        );
1533    }
1534
1535    #[test]
1536    fn shift_enter_sequence_matches_the_newline_encoder() {
1537        assert_eq!(
1538            shift_enter_sequence(crate::WindowsPasteNewline::AltEnter),
1539            b"\x1b\r"
1540        );
1541        assert_eq!(
1542            shift_enter_sequence(crate::WindowsPasteNewline::CsiU),
1543            b"\x1b[13;2u"
1544        );
1545    }
1546
1547    #[test]
1548    fn ctrl_enter_sequence_is_csi_u_and_is_not_a_paste_newline() {
1549        assert_eq!(ctrl_enter_sequence(), b"\x1b[13;5u");
1550        let prepared = prepare_agent_prompt(
1551            "a\nb",
1552            true,
1553            &windows_newline(crate::WindowsPasteNewline::CsiU),
1554            crate::RuntimePlatform::Windows,
1555            None,
1556        )
1557        .unwrap();
1558        let joined: Vec<u8> = prepared
1559            .writes()
1560            .iter()
1561            .flat_map(|write| write.bytes.iter().copied())
1562            .collect();
1563        assert!(!joined.windows(7).any(|window| window == b"\x1b[13;5u"));
1564        assert_eq!(prepared.writes().last().unwrap().bytes, b"\r");
1565    }
1566
1567    fn csi_u_contract(shift: bool, ctrl: bool) -> PtySubmitContract {
1568        PtySubmitContract {
1569            windows_shift_enter: shift.then_some(crate::ModifiedEnterEncoding::CsiU),
1570            ctrl_enter: ctrl.then_some(crate::ModifiedEnterEncoding::CsiU),
1571            ..PtySubmitContract::default()
1572        }
1573    }
1574
1575    fn gates(platform: RuntimePlatform, kitty: u32, modify: u32, conpty: bool) -> PtyHostGates {
1576        PtyHostGates {
1577            platform,
1578            kitty_flags: kitty,
1579            modify_other_keys: modify,
1580            local_windows_conpty: conpty,
1581        }
1582    }
1583
1584    #[test]
1585    fn local_plain_conpty_is_windows_only() {
1586        assert!(local_plain(RuntimePlatform::Windows).local_windows_conpty);
1587        for platform in [
1588            RuntimePlatform::MacOs,
1589            RuntimePlatform::Linux,
1590            RuntimePlatform::Wsl,
1591        ] {
1592            let host = local_plain(platform);
1593            assert!(!host.local_windows_conpty);
1594            assert_eq!(host.kitty_flags, 0);
1595            assert_eq!(host.modify_other_keys, 0);
1596        }
1597    }
1598
1599    #[test]
1600    fn encode_pty_shortcut_shift_enter_follows_the_csi_u_gate() {
1601        let csi_u = b"\x1b[13;2u".as_slice();
1602        let fallback = b"\x1b\r".as_slice();
1603        let modify = b"\x1b[27;2;13~".as_slice();
1604        assert_eq!(csi_u, shift_enter_sequence(crate::WindowsPasteNewline::CsiU));
1605        assert_eq!(fallback, shift_enter_sequence(crate::WindowsPasteNewline::AltEnter));
1606
1607        assert_eq!(
1608            encode_pty_shortcut(
1609                PtyShortcut::ShiftEnter,
1610                &csi_u_contract(true, false),
1611                local_plain(RuntimePlatform::Windows),
1612            ),
1613            Some(csi_u)
1614        );
1615        assert_eq!(
1616            encode_pty_shortcut(
1617                PtyShortcut::ShiftEnter,
1618                &csi_u_contract(true, false),
1619                local_plain(RuntimePlatform::MacOs),
1620            ),
1621            Some(fallback)
1622        );
1623        assert_eq!(
1624            encode_pty_shortcut(
1625                PtyShortcut::ShiftEnter,
1626                &csi_u_contract(false, false),
1627                gates(RuntimePlatform::Linux, 1, 0, false),
1628            ),
1629            Some(csi_u)
1630        );
1631        assert_eq!(
1632            encode_pty_shortcut(
1633                PtyShortcut::ShiftEnter,
1634                &csi_u_contract(false, false),
1635                gates(RuntimePlatform::Linux, 0, 1, false),
1636            ),
1637            Some(modify)
1638        );
1639        assert_eq!(
1640            encode_pty_shortcut(
1641                PtyShortcut::ShiftEnter,
1642                &csi_u_contract(true, false),
1643                local_plain(RuntimePlatform::Wsl),
1644            ),
1645            Some(fallback)
1646        );
1647        assert_eq!(
1648            encode_pty_shortcut(
1649                PtyShortcut::ShiftEnter,
1650                &csi_u_contract(true, false),
1651                gates(RuntimePlatform::MacOs, 0, 4, false),
1652            ),
1653            Some(modify)
1654        );
1655        assert_eq!(
1656            encode_pty_shortcut(
1657                PtyShortcut::ShiftEnter,
1658                &csi_u_contract(false, false),
1659                gates(RuntimePlatform::Windows, 0, 2, true),
1660            ),
1661            Some(modify)
1662        );
1663        assert_eq!(
1664            encode_pty_shortcut(
1665                PtyShortcut::ShiftEnter,
1666                &PtySubmitContract::default(),
1667                local_plain(RuntimePlatform::Windows),
1668            ),
1669            Some(fallback)
1670        );
1671    }
1672
1673    #[test]
1674    fn encode_pty_shortcut_alt_enter_is_modify_other_keys_or_nothing() {
1675        let modifier_3 = b"\x1b[27;3;13~".as_slice();
1676        assert_eq!(
1677            encode_pty_shortcut(
1678                PtyShortcut::AltEnter,
1679                &PtySubmitContract::default(),
1680                gates(RuntimePlatform::Linux, 1, 9, false),
1681            ),
1682            None
1683        );
1684        assert_eq!(
1685            encode_pty_shortcut(
1686                PtyShortcut::AltEnter,
1687                &PtySubmitContract::default(),
1688                local_plain(RuntimePlatform::MacOs),
1689            ),
1690            None
1691        );
1692        assert_eq!(
1693            encode_pty_shortcut(
1694                PtyShortcut::AltEnter,
1695                &PtySubmitContract::default(),
1696                gates(RuntimePlatform::Windows, 0, 1, true),
1697            ),
1698            Some(modifier_3)
1699        );
1700    }
1701
1702    #[test]
1703    fn encode_pty_shortcut_ctrl_enter_is_cr_only_on_local_conpty() {
1704        let csi_u = ctrl_enter_sequence();
1705        assert_eq!(csi_u, b"\x1b[13;5u");
1706        let conpty = gates(RuntimePlatform::Windows, 0, 0, true);
1707        assert_eq!(
1708            encode_pty_shortcut(PtyShortcut::CtrlEnter, &PtySubmitContract::default(), conpty),
1709            Some(b"\r".as_slice())
1710        );
1711        assert_eq!(
1712            encode_pty_shortcut(
1713                PtyShortcut::CtrlEnter,
1714                &PtySubmitContract::default(),
1715                gates(RuntimePlatform::Windows, 2, 0, true),
1716            ),
1717            Some(csi_u)
1718        );
1719        assert_eq!(
1720            encode_pty_shortcut(
1721                PtyShortcut::CtrlEnter,
1722                &csi_u_contract(false, true),
1723                conpty,
1724            ),
1725            Some(csi_u)
1726        );
1727        for platform in [
1728            RuntimePlatform::MacOs,
1729            RuntimePlatform::Linux,
1730            RuntimePlatform::Wsl,
1731        ] {
1732            assert_eq!(
1733                encode_pty_shortcut(
1734                    PtyShortcut::CtrlEnter,
1735                    &PtySubmitContract::default(),
1736                    local_plain(platform),
1737                ),
1738                Some(csi_u)
1739            );
1740        }
1741        assert_eq!(
1742            encode_pty_shortcut(
1743                PtyShortcut::CtrlEnter,
1744                &PtySubmitContract::default(),
1745                gates(RuntimePlatform::Windows, 0, 0, false),
1746            ),
1747            Some(csi_u)
1748        );
1749    }
1750
1751    #[test]
1752    fn encode_pty_shortcut_editing_and_word_motion() {
1753        let plain = PtySubmitContract::default();
1754        let mac = local_plain(RuntimePlatform::MacOs);
1755        let linux = local_plain(RuntimePlatform::Linux);
1756        assert_eq!(
1757            encode_pty_shortcut(PtyShortcut::CmdBackspace, &plain, mac),
1758            Some(b"\x15".as_slice())
1759        );
1760        assert_eq!(
1761            encode_pty_shortcut(PtyShortcut::CmdDelete, &plain, mac),
1762            Some(b"\x0b".as_slice())
1763        );
1764        assert_eq!(
1765            encode_pty_shortcut(PtyShortcut::CmdArrowLeft, &plain, mac),
1766            Some(b"\x01".as_slice())
1767        );
1768        assert_eq!(
1769            encode_pty_shortcut(PtyShortcut::CmdArrowRight, &plain, mac),
1770            Some(b"\x05".as_slice())
1771        );
1772        for shortcut in [
1773            PtyShortcut::CmdBackspace,
1774            PtyShortcut::CmdDelete,
1775            PtyShortcut::CmdArrowLeft,
1776            PtyShortcut::CmdArrowRight,
1777        ] {
1778            assert_eq!(encode_pty_shortcut(shortcut, &plain, linux), None);
1779            assert_eq!(
1780                encode_pty_shortcut(shortcut, &plain, local_plain(RuntimePlatform::Windows)),
1781                None
1782            );
1783        }
1784
1785        assert_eq!(
1786            encode_pty_shortcut(PtyShortcut::CtrlBackspace, &plain, gates(RuntimePlatform::Windows, 3, 0, true)),
1787            Some(b"\x17".as_slice())
1788        );
1789        assert_eq!(
1790            encode_pty_shortcut(PtyShortcut::AltBackspace, &plain, linux),
1791            Some(b"\x1b\x7f".as_slice())
1792        );
1793        assert_eq!(
1794            encode_pty_shortcut(PtyShortcut::AltBackspace, &plain, gates(RuntimePlatform::Linux, 1, 0, false)),
1795            None
1796        );
1797
1798        let alt_delete = PtyShortcut::AltDelete {
1799            numpad: false,
1800            non_agent_fullscreen: false,
1801        };
1802        assert_eq!(
1803            encode_pty_shortcut(alt_delete, &plain, mac),
1804            Some(b"\x1bd".as_slice())
1805        );
1806        assert_eq!(
1807            encode_pty_shortcut(
1808                PtyShortcut::AltDelete {
1809                    numpad: true,
1810                    non_agent_fullscreen: false,
1811                },
1812                &plain,
1813                mac,
1814            ),
1815            None
1816        );
1817        assert_eq!(
1818            encode_pty_shortcut(
1819                PtyShortcut::AltDelete {
1820                    numpad: false,
1821                    non_agent_fullscreen: true,
1822                },
1823                &plain,
1824                mac,
1825            ),
1826            None
1827        );
1828        assert_eq!(
1829            encode_pty_shortcut(alt_delete, &plain, gates(RuntimePlatform::MacOs, 1, 0, false)),
1830            None
1831        );
1832        assert_eq!(encode_pty_shortcut(alt_delete, &plain, linux), None);
1833
1834        assert_eq!(
1835            encode_pty_shortcut(PtyShortcut::AltArrowLeft, &plain, linux),
1836            Some(b"\x1bb".as_slice())
1837        );
1838        assert_eq!(
1839            encode_pty_shortcut(PtyShortcut::AltArrowRight, &plain, linux),
1840            Some(b"\x1bf".as_slice())
1841        );
1842        assert_eq!(
1843            encode_pty_shortcut(PtyShortcut::AltArrowLeft, &plain, gates(RuntimePlatform::Linux, 1, 0, false)),
1844            None
1845        );
1846        assert_eq!(
1847            encode_pty_shortcut(PtyShortcut::AltArrowRight, &plain, local_plain(RuntimePlatform::Windows)),
1848            None
1849        );
1850        assert_eq!(
1851            encode_pty_shortcut(PtyShortcut::AltArrowLeft, &plain, local_plain(RuntimePlatform::Wsl)),
1852            Some(b"\x1bb".as_slice())
1853        );
1854
1855        assert_eq!(encode_pty_shortcut(PtyShortcut::CtrlArrowLeft, &plain, mac), None);
1856        assert_eq!(
1857            encode_pty_shortcut(PtyShortcut::CtrlArrowRight, &plain, local_plain(RuntimePlatform::Windows)),
1858            None
1859        );
1860        assert_eq!(
1861            encode_pty_shortcut(PtyShortcut::CtrlArrowLeft, &plain, linux),
1862            Some(b"\x1bb".as_slice())
1863        );
1864        assert_eq!(
1865            encode_pty_shortcut(PtyShortcut::CtrlArrowRight, &plain, local_plain(RuntimePlatform::Wsl)),
1866            Some(b"\x1bf".as_slice())
1867        );
1868        assert_eq!(
1869            encode_pty_shortcut(PtyShortcut::CtrlArrowLeft, &plain, gates(RuntimePlatform::Linux, 1, 0, false)),
1870            Some(b"\x1bb".as_slice())
1871        );
1872    }
1873
1874    #[test]
1875    fn prepare_pty_shortcut_wraps_bytes_and_keeps_none() {
1876        let prepared = prepare_pty_shortcut(
1877            PtyShortcut::CtrlBackspace,
1878            &PtySubmitContract::default(),
1879            local_plain(RuntimePlatform::Linux),
1880        )
1881        .expect("ctrl+backspace always has bytes");
1882        assert_eq!(prepared.kind(), PreparedInputKind::TerminalControl);
1883        assert_eq!(prepared.writes().len(), 1);
1884        assert_eq!(prepared.writes()[0].kind, PreparedWriteKind::Control);
1885        assert_eq!(prepared.writes()[0].delay_before_ms, 0);
1886        assert_eq!(prepared.writes()[0].bytes, b"\x17");
1887        assert!(prepare_pty_shortcut(
1888            PtyShortcut::AltEnter,
1889            &PtySubmitContract::default(),
1890            local_plain(RuntimePlatform::Linux),
1891        )
1892        .is_none());
1893    }
1894}