Skip to main content

vtcode_commons/
program_resume.rs

1//! Program Resume Protocol (OSC 7577) encoding. No terminal I/O.
2//!
3//! A program that knows how to resume itself reports its resume command to the
4//! terminal; the terminal may run it after a restart. Reports are a hint, never
5//! a guarantee. See <https://www.superlogical.com/rex/docs/build/program-resume>.
6
7use anyhow::{Result, bail, ensure};
8use base64::{Engine, engine::general_purpose::STANDARD};
9use sha2::{Digest, Sha256};
10
11/// Environment variable carrying the per-terminal resume token.
12///
13/// Presence of this variable is the whole feature detection: a program that
14/// does not find it has no token to compute a `mac` with, so it sends nothing.
15pub const RESUME_TOKEN_ENV: &str = "OSC7577_TOKEN";
16
17/// OSC number for the Program Resume Protocol.
18pub const OSC_PROGRAM_RESUME: u16 = 7577;
19
20/// Maximum report length we emit; terminals must accept at least this much.
21pub const MAX_REPORT_LEN: usize = 2048;
22
23/// Maximum `argv` elements we emit; terminals must accept at least this many.
24pub const MAX_ARGV_ELEMENTS: usize = 64;
25
26/// Maximum token bytes we hash. The spec fixes 22-64 characters; anything
27/// beyond this bound is non-conformant and is ignored outright so a hostile
28/// environment cannot force unbounded hashing on every flush.
29const MAX_TOKEN_LEN: usize = 1024;
30
31/// Projection commands for the session-owned resume adapter.
32///
33/// Like [`crate::program_status::ProgramStatusUpdate`], these carry no input or
34/// execution authority: they only describe which resume record the terminal
35/// should hold for this session.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum ProgramResumeUpdate {
38    Configure {
39        enabled: bool,
40    },
41    /// Advertise `argv` as the command that resumes this session, in `cwd`.
42    ///
43    /// `cwd` must be absolute when present. The adapter re-reports only when
44    /// the target changes.
45    SetTarget {
46        argv: Vec<String>,
47        cwd: Option<String>,
48    },
49    /// Withdraw any outstanding resume record (user ended the session).
50    Clear,
51}
52
53/// Read the resume token from the process environment.
54///
55/// Returns `None` when the terminal does not support the protocol (variable
56/// absent) or exported an empty or absurdly long token. The token itself must
57/// never be written to the terminal, logs, or child environments; only the
58/// `mac` travels.
59pub fn resume_token() -> Option<String> {
60    std::env::var(RESUME_TOKEN_ENV)
61        .ok()
62        .filter(|token| !token.is_empty() && token.len() <= MAX_TOKEN_LEN)
63}
64
65/// Current process id for the `pid` key.
66pub fn current_pid() -> u32 {
67    std::process::id()
68}
69
70/// Current Unix time in seconds for the `time` key.
71pub fn current_unix_time() -> u64 {
72    std::time::SystemTime::now()
73        .duration_since(std::time::UNIX_EPOCH)
74        .map(|elapsed| elapsed.as_secs())
75        .unwrap_or_default()
76}
77
78/// Compute the report `mac`: hex SHA-256 over `body:token`.
79fn compute_mac(body: &str, token: &str) -> String {
80    let mut hash = Sha256::new();
81    hash.update(body.as_bytes());
82    hash.update(b":");
83    hash.update(token.as_bytes());
84    let digest = hash.finalize();
85    let mut mac = String::with_capacity(digest.len() * 2);
86    for byte in digest {
87        for nibble in [byte >> 4, byte & 0x0f] {
88            mac.push(char::from(if nibble < 10 { b'0' + nibble } else { b'a' + nibble - 10 }));
89        }
90    }
91    mac
92}
93
94fn ensure_reportable_text(text: &str, what: &str) -> Result<()> {
95    ensure!(!text.chars().any(char::is_control), "{what} contains control characters");
96    Ok(())
97}
98
99fn encode_element(text: &str, what: &str) -> Result<String> {
100    ensure_reportable_text(text, what)?;
101    Ok(STANDARD.encode(text.as_bytes()))
102}
103
104fn is_absolute_path(text: &str) -> bool {
105    if text.starts_with('/') || text.starts_with("\\\\") {
106        return true;
107    }
108    let mut chars = text.chars();
109    matches!((chars.next(), chars.next(), chars.next()), (Some(drive), Some(':'), Some(sep))
110        if drive.is_ascii_alphabetic() && matches!(sep, '\\' | '/'))
111}
112
113fn ensure_valid_argv(argv: &[String]) -> Result<()> {
114    ensure!(argv.len() <= MAX_ARGV_ELEMENTS, "resume argv exceeds element limit");
115    let Some(program) = argv.first() else {
116        bail!("resume argv must have at least one element");
117    };
118    ensure!(!program.is_empty(), "resume program must not be empty");
119    ensure_reportable_text(program, "resume program")?;
120    let bare_name = !program.contains('/') && !program.contains('\\');
121    if bare_name {
122        ensure!(!program.starts_with('-'), "resume program must not start with '-'");
123    } else {
124        ensure!(is_absolute_path(program), "resume program must be a bare name or an absolute path");
125    }
126    for arg in argv.iter().skip(1) {
127        ensure_reportable_text(arg, "resume argument")?;
128    }
129    Ok(())
130}
131
132fn ensure_valid_cwd(cwd: &str) -> Result<()> {
133    ensure_reportable_text(cwd, "resume working directory")?;
134    ensure!(is_absolute_path(cwd), "resume working directory must be absolute");
135    Ok(())
136}
137
138fn wrap_report(body: &str) -> Result<String> {
139    let report = format!("\x1b]{};{body}\x1b\\", OSC_PROGRAM_RESUME);
140    ensure!(report.len() <= MAX_REPORT_LEN, "resume report exceeds byte limit");
141    Ok(report)
142}
143
144/// Validate a resume target without encoding it.
145///
146/// Adapters call this at the boundary so an invalid target is rejected once
147/// instead of failing (and warning) on every flush. Encoding still re-checks,
148/// so this is a fast path, not a trust boundary.
149pub fn validate_target(argv: &[String], cwd: Option<&str>) -> Result<()> {
150    ensure_valid_argv(argv)?;
151    if let Some(cwd) = cwd {
152        ensure_valid_cwd(cwd)?;
153    }
154    Ok(())
155}
156
157/// Encode a resume report for `pid` made at `time`.
158///
159/// `argv` is the command the terminal runs to bring the program back; `cwd`
160/// is the absolute directory to run it in. Fails closed on any malformed
161/// input so callers never emit a report the terminal would reject.
162pub fn encode_report(pid: u32, time: u64, argv: &[String], cwd: Option<&str>, token: &str) -> Result<String> {
163    ensure!(pid > 0, "resume pid must be positive");
164    ensure!(time > 0, "resume time must be positive");
165    ensure!(!token.is_empty(), "resume token must not be empty");
166    validate_target(argv, cwd)?;
167
168    let mut elements = Vec::with_capacity(argv.len());
169    for (index, arg) in argv.iter().enumerate() {
170        elements.push(encode_element(
171            arg,
172            if index == 0 {
173                "resume program"
174            } else {
175                "resume argument"
176            },
177        )?);
178    }
179    let mut body = format!("pid={pid}:time={time}:argv={}", elements.join(","));
180    if let Some(cwd) = cwd {
181        body.push_str(":cwd=");
182        body.push_str(&encode_element(cwd, "resume working directory")?);
183    }
184    let mac = compute_mac(&body, token);
185    body.push_str(":mac=");
186    body.push_str(&mac);
187    wrap_report(&body)
188}
189
190/// Encode a record removal for `pid` made at `time`.
191///
192/// A program sends this when the user ends it and it should no longer be
193/// resumed. Never send it on SIGHUP, SIGTERM, or terminal loss: that is when
194/// the record is needed.
195pub fn encode_clear(pid: u32, time: u64, token: &str) -> Result<String> {
196    ensure!(pid > 0, "resume pid must be positive");
197    ensure!(time > 0, "resume time must be positive");
198    ensure!(!token.is_empty(), "resume token must not be empty");
199    let body = format!("pid={pid}:time={time}:clear=1");
200    let mac = compute_mac(&body, token);
201    wrap_report(&format!("{body}:mac={mac}"))
202}
203
204#[cfg(test)]
205mod tests;