Skip to main content

agentmux_common/deeplinks/
parse.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! srv's and mcp's parser of deep links (docs/specs/SPEC_DEEP_LINKS_ONE_FRAMEWORK_2026_11_20.md ยง3.2, R6 to R9,
5//! G7, G8). The app has the same parser in TypeScript (`frontend/app/deeplinks/parse.ts`); both are written from
6//! the one grammar and the one registry, and both run `crates/common/deeplinks/conformance.json`. A change here is
7//! a change there.
8//!
9//! The order of the checks is part of the contract, so both sides give the same reason for the same link:
10//! 1. length, then the scheme;
11//! 2. the shape: view, segments, query and anchor, no empty part;
12//! 3. each part, left to right: its characters, its percent-encoding (decoded once), control characters, its one
13//!    written form;
14//! 4. the view (an alias is rewritten first), its build, the place, `host`, the parameters, the anchor.
15
16use std::collections::BTreeMap;
17
18use super::types::{Kind, Place, Registry, Segment, View};
19
20pub const SCHEME: &str = "agentmux://";
21
22/// Why a link is refused. `as_str` is the code the conformance file names.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum LinkError {
25    TooLong,
26    NotAgentmux,
27    BadSyntax,
28    BadEncoding,
29    DoubleEncoded,
30    ControlChar,
31    NotCanonical,
32    UnknownView,
33    UnknownPlace,
34    UnknownParam,
35    UnknownAnchor,
36    DuplicateParam,
37    EmptyParam,
38    BadValue,
39    BadPath,
40    MissingPlace,
41    NotYet,
42}
43
44impl LinkError {
45    pub fn as_str(self) -> &'static str {
46        match self {
47            LinkError::TooLong => "too_long",
48            LinkError::NotAgentmux => "not_agentmux",
49            LinkError::BadSyntax => "bad_syntax",
50            LinkError::BadEncoding => "bad_encoding",
51            LinkError::DoubleEncoded => "double_encoded",
52            LinkError::ControlChar => "control_char",
53            LinkError::NotCanonical => "not_canonical",
54            LinkError::UnknownView => "unknown_view",
55            LinkError::UnknownPlace => "unknown_place",
56            LinkError::UnknownParam => "unknown_param",
57            LinkError::UnknownAnchor => "unknown_anchor",
58            LinkError::DuplicateParam => "duplicate_param",
59            LinkError::EmptyParam => "empty_param",
60            LinkError::BadValue => "bad_value",
61            LinkError::BadPath => "bad_path",
62            LinkError::MissingPlace => "missing_place",
63            LinkError::NotYet => "not_yet",
64        }
65    }
66}
67
68/// A value of a var or a parameter: a number for an `int`, text for every other kind.
69#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
70pub enum Value {
71    Text(String),
72    Int(i64),
73}
74
75impl std::fmt::Display for Value {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        match self {
78            Value::Text(s) => f.write_str(s),
79            Value::Int(n) => write!(f, "{n}"),
80        }
81    }
82}
83
84/// A link read: its view, the place it matched, the values of the place's vars, its parameters and anchor.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct ParsedLink {
87    /// The registry view (`ext` for a widget).
88    pub view: &'static View,
89    /// The place it matched, or None for the view as it is.
90    pub place: Option<&'static Place>,
91    /// Each var of the place by name; for a widget, `package` too.
92    pub values: BTreeMap<String, Value>,
93    pub params: BTreeMap<String, Value>,
94    pub anchor: Option<String>,
95    /// The computer the place is on (`host=machine[/channel]`, build 4d), when the link names one.
96    pub host: Option<String>,
97    /// The link's one written form (R7).
98    pub canonical: String,
99}
100
101type R<T> = Result<T, LinkError>;
102
103fn is_unreserved(b: u8) -> bool {
104    b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~')
105}
106
107/// C0 and C1 controls, DEL, the bidirectional marks, embeddings, overrides and isolates, zero-width characters (G8).
108pub fn is_control(c: char) -> bool {
109    let u = c as u32;
110    u <= 0x1F
111        || (0x7F..=0x9F).contains(&u)
112        || u == 0x061C
113        || (0x200B..=0x200F).contains(&u)
114        || (0x202A..=0x202E).contains(&u)
115        || (0x2060..=0x2069).contains(&u)
116        || u == 0xFEFF
117}
118
119/// The one percent-encoding of `text` (R7): unreserved characters as they are, every other byte as `%HH`, upper case.
120pub fn encode_part(text: &str) -> String {
121    let mut out = String::with_capacity(text.len());
122    for &b in text.as_bytes() {
123        if is_unreserved(b) {
124            out.push(b as char);
125        } else {
126            out.push_str(&format!("%{b:02X}"));
127        }
128    }
129    out
130}
131
132fn has_pct_triplet(text: &str) -> bool {
133    let b = text.as_bytes();
134    b.windows(3).any(|w| w[0] == b'%' && w[1].is_ascii_hexdigit() && w[2].is_ascii_hexdigit())
135}
136
137/// `raw` decoded once, with every check of step 3.
138fn decode_part(raw: &str) -> R<String> {
139    let bytes = raw.as_bytes();
140    let mut out = Vec::with_capacity(bytes.len());
141    let mut i = 0;
142    while i < bytes.len() {
143        let b = bytes[i];
144        if b == b'%' {
145            let hex = bytes.get(i + 1..i + 3).ok_or(LinkError::BadEncoding)?;
146            if !hex.iter().all(u8::is_ascii_hexdigit) {
147                return Err(LinkError::BadEncoding);
148            }
149            let s = std::str::from_utf8(hex).map_err(|_| LinkError::BadEncoding)?;
150            out.push(u8::from_str_radix(s, 16).map_err(|_| LinkError::BadEncoding)?);
151            i += 3;
152        } else if is_unreserved(b) {
153            out.push(b);
154            i += 1;
155        } else {
156            return Err(LinkError::BadSyntax);
157        }
158    }
159    let text = String::from_utf8(out).map_err(|_| LinkError::BadEncoding)?;
160    if has_pct_triplet(&text) {
161        return Err(LinkError::DoubleEncoded);
162    }
163    if text.chars().any(is_control) {
164        return Err(LinkError::ControlChar);
165    }
166    if encode_part(&text) != raw {
167        return Err(LinkError::NotCanonical);
168    }
169    Ok(text)
170}
171
172fn all_chars(s: &str, first: impl Fn(char) -> bool, rest: impl Fn(char) -> bool, max: usize) -> bool {
173    let mut chars = s.chars();
174    match chars.next() {
175        Some(c) if first(c) => {}
176        _ => return false,
177    }
178    s.chars().count() <= max && chars.all(rest)
179}
180
181fn lower_alnum(c: char) -> bool {
182    c.is_ascii_lowercase() || c.is_ascii_digit()
183}
184
185fn is_id(s: &str) -> bool {
186    all_chars(s, lower_alnum, |c| lower_alnum(c) || matches!(c, '.' | '_' | '-'), 128)
187}
188
189fn is_slug(s: &str) -> bool {
190    all_chars(s, lower_alnum, |c| lower_alnum(c) || c == '-', 24)
191}
192
193fn is_param_key(s: &str) -> bool {
194    all_chars(s, |c| c.is_ascii_lowercase(), |c| lower_alnum(c) || c == '_', 32)
195}
196
197fn is_opaque(s: &str) -> bool {
198    s.strip_prefix("e_").is_some_and(|r| (8..=32).contains(&r.len()) && r.chars().all(lower_alnum))
199}
200
201fn is_package(s: &str) -> bool {
202    let part = |p: &str| all_chars(p, lower_alnum, |c| lower_alnum(c) || c == '-', usize::MAX);
203    match s.split_once('.') {
204        Some((a, b)) => part(a) && part(b),
205        None => false,
206    }
207}
208
209/// Windows device names, which open a device whatever folder or extension they are written with.
210fn is_device(base: &str) -> bool {
211    let l = base.to_lowercase();
212    if matches!(l.as_str(), "con" | "prn" | "aux" | "nul" | "conin$" | "conout$") {
213        return true;
214    }
215    let mut chars = l.chars();
216    let head: String = chars.by_ref().take(3).collect();
217    let tail: Vec<char> = chars.collect();
218    (head == "com" || head == "lpt") && tail.len() == 1 && (tail[0].is_ascii_digit() || matches!(tail[0], '\u{b9}' | '\u{b2}' | '\u{b3}'))
219}
220
221/// Why `path` may not be opened by a link, as a structural check both sides make the same way (G7), or None. srv
222/// applies the rest of G7 (what the caller may read, where a symbolic link leads) when the link is opened.
223pub fn path_problem(path: &str) -> Option<LinkError> {
224    if path.contains('\\') {
225        return Some(LinkError::BadPath);
226    }
227    let b = path.as_bytes();
228    let rest = if b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && b[2] == b'/' {
229        &path[3..]
230    } else if path.starts_with('/') && !path.starts_with("//") {
231        &path[1..]
232    } else {
233        // Relative, a drive-relative `C:x`, or a UNC `//server`.
234        return Some(LinkError::BadPath);
235    };
236    if rest.is_empty() {
237        return None;
238    }
239    for seg in rest.split('/') {
240        if seg.is_empty() || seg == "." || seg == ".." || seg.contains(':') || seg.ends_with('.') || seg.ends_with(' ') {
241            return Some(LinkError::BadPath);
242        }
243        if is_device(seg.split('.').next().unwrap_or("")) {
244            return Some(LinkError::BadPath);
245        }
246    }
247    None
248}
249
250fn name_problem(name: &str) -> bool {
251    name.chars().count() > 255
252        || name == "."
253        || name == ".."
254        || name.contains(['/', '\\', ':'])
255        || is_device(name.split('.').next().unwrap_or(""))
256        || name.ends_with(' ')
257        || name.ends_with('.')
258}
259
260struct Typed<'a> {
261    kind: Kind,
262    values: &'a [super::types::EnumValue],
263    min: Option<i64>,
264    max: Option<i64>,
265}
266
267/// `text` read as a value of `spec`'s kind. An enum value that isn't one is the caller's to name.
268fn typed_value(spec: &Typed<'_>, text: &str, enum_miss: LinkError) -> R<Value> {
269    let lower = text.to_lowercase();
270    match spec.kind {
271        Kind::Enum => {
272            if spec.values.iter().any(|v| v.id == text) {
273                Ok(Value::Text(text.to_string()))
274            } else if spec.values.iter().any(|v| v.id == lower) {
275                Err(LinkError::NotCanonical)
276            } else {
277                Err(enum_miss)
278            }
279        }
280        Kind::Id | Kind::Slug => {
281            let check = if spec.kind == Kind::Id { is_id } else { is_slug };
282            if check(text) {
283                Ok(Value::Text(text.to_string()))
284            } else if check(&lower) {
285                Err(LinkError::NotCanonical)
286            } else {
287                Err(LinkError::BadValue)
288            }
289        }
290        Kind::Int => {
291            let digits = !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit());
292            if digits && text.len() > 1 && text.starts_with('0') {
293                return Err(LinkError::NotCanonical);
294            }
295            if !digits || text.len() > 10 {
296                return Err(LinkError::BadValue);
297            }
298            let n: i64 = text.parse().map_err(|_| LinkError::BadValue)?;
299            if n < spec.min.unwrap_or(0) || n > spec.max.unwrap_or(2_147_483_647) {
300                return Err(LinkError::BadValue);
301            }
302            Ok(Value::Int(n))
303        }
304        Kind::Opaque => is_opaque(text).then(|| Value::Text(text.to_string())).ok_or(LinkError::BadValue),
305        Kind::Path => match path_problem(text) {
306            Some(e) => Err(e),
307            None => Ok(Value::Text(text.to_string())),
308        },
309        Kind::Name => (!name_problem(text)).then(|| Value::Text(text.to_string())).ok_or(LinkError::BadValue),
310    }
311}
312
313struct Shape {
314    head: String,
315    segments: Vec<String>,
316    params: Vec<(String, String)>,
317    anchor: Option<String>,
318}
319
320/// Step 2 and 3: the link cut into its parts, each decoded once.
321fn shape_of(link: &str, reg: &Registry) -> R<Shape> {
322    if link.len() > reg.max_bytes {
323        return Err(LinkError::TooLong);
324    }
325    let mut rest = link.strip_prefix(SCHEME).ok_or(LinkError::NotAgentmux)?;
326    let mut anchor_raw = None;
327    if let Some((before, after)) = rest.split_once('#') {
328        if after.is_empty() || after.contains('#') {
329            return Err(LinkError::BadSyntax);
330        }
331        anchor_raw = Some(after);
332        rest = before;
333    }
334    let mut query_raw = None;
335    if let Some((before, after)) = rest.split_once('?') {
336        if after.is_empty() || after.contains('?') {
337            return Err(LinkError::BadSyntax);
338        }
339        query_raw = Some(after);
340        rest = before;
341    }
342    let raw_segments: Vec<&str> = rest.split('/').collect();
343    if raw_segments.iter().any(|s| s.is_empty()) {
344        return Err(LinkError::BadSyntax);
345    }
346    let mut raw_params = Vec::new();
347    if let Some(q) = query_raw {
348        for piece in q.split('&') {
349            let (k, v) = piece.split_once('=').ok_or(LinkError::BadSyntax)?;
350            raw_params.push((k, v));
351        }
352    }
353    let mut decoded = raw_segments.iter().map(|s| decode_part(s)).collect::<R<Vec<_>>>()?;
354    let head = decoded.remove(0);
355    let mut params = Vec::with_capacity(raw_params.len());
356    for (k, v) in raw_params {
357        if !is_param_key(k) {
358            return Err(if is_param_key(&k.to_lowercase()) { LinkError::NotCanonical } else { LinkError::BadSyntax });
359        }
360        if v.is_empty() {
361            return Err(LinkError::EmptyParam);
362        }
363        params.push((k.to_string(), decode_part(v)?));
364    }
365    let anchor = anchor_raw.map(decode_part).transpose()?;
366    Ok(Shape { head, segments: decoded, params, anchor })
367}
368
369/// An alias rewritten to the form it stands for (R7).
370fn unalias(shape: Shape, reg: &Registry) -> Shape {
371    let parts: Vec<&str> = std::iter::once(shape.head.as_str()).chain(shape.segments.iter().map(String::as_str)).collect();
372    for alias in reg.aliases {
373        if alias.from.len() != parts.len() || alias.from[0] != parts[0] {
374            continue;
375        }
376        let mut bound: BTreeMap<&str, &str> = BTreeMap::new();
377        let fits = alias.from.iter().zip(&parts).all(|(f, p)| {
378            if f.starts_with('{') && f.ends_with('}') {
379                bound.insert(*f, *p);
380                true
381            } else {
382                f == p
383            }
384        });
385        if !fits {
386            continue;
387        }
388        let to: Vec<String> = alias.to.iter().map(|t| bound.get(*t).copied().unwrap_or(*t).to_string()).collect();
389        return Shape { head: to[0].clone(), segments: to[1..].to_vec(), params: shape.params, anchor: shape.anchor };
390    }
391    shape
392}
393
394fn find_view(head: &str, reg: &'static Registry) -> R<(&'static View, Option<String>)> {
395    if let Some(v) = reg.views.iter().find(|v| !v.prefix && v.id == head) {
396        return Ok((v, None));
397    }
398    for v in reg.views.iter().filter(|v| v.prefix) {
399        if let Some(pkg) = head.strip_prefix(v.id).and_then(|r| r.strip_prefix('.')) {
400            if is_package(pkg) {
401                return Ok((v, Some(pkg.to_string())));
402            }
403        }
404    }
405    let lower = head.to_lowercase();
406    if head != lower && reg.views.iter().any(|v| v.id == lower) {
407        return Err(LinkError::NotCanonical);
408    }
409    Err(LinkError::UnknownView)
410}
411
412/// The place `segments` names, with its vars' values.
413fn match_place(view: &'static View, segments: &[String]) -> R<(&'static Place, BTreeMap<String, Value>)> {
414    let lit_fits = |p: &Place, exact: bool| {
415        p.segments.len() == segments.len()
416            && p.segments.iter().zip(segments).all(|(s, given)| match s {
417                Segment::Lit(l) => *l == given.as_str() || (!exact && *l == given.to_lowercase()),
418                Segment::Var(_) => true,
419            })
420    };
421    if !view.places.iter().any(|p| lit_fits(p, false)) {
422        return Err(LinkError::UnknownPlace);
423    }
424    let exact: Vec<&'static Place> = view.places.iter().filter(|p| lit_fits(p, true)).collect();
425    if exact.is_empty() {
426        return Err(LinkError::NotCanonical);
427    }
428    let mut first = None;
429    for place in exact {
430        let mut values = BTreeMap::new();
431        let mut failed = None;
432        for (s, given) in place.segments.iter().zip(segments) {
433            if let Segment::Var(v) = s {
434                let spec = Typed { kind: v.kind, values: v.values, min: v.min, max: v.max };
435                match typed_value(&spec, given, LinkError::UnknownPlace) {
436                    Ok(val) => {
437                        values.insert(v.name.to_string(), val);
438                    }
439                    Err(e) => {
440                        failed = Some(e);
441                        break;
442                    }
443                }
444            }
445        }
446        match failed {
447            None => return Ok((place, values)),
448            Some(e) => {
449                first.get_or_insert(e);
450            }
451        }
452    }
453    Err(first.unwrap_or(LinkError::UnknownPlace))
454}
455
456/// The parameter every link may take, last: the computer its place is on, `machine[/channel]`, lower case.
457pub const HOST_PARAM: &str = "host";
458
459/// One part of a `host`: a letter or digit, then up to 62 of letters, digits, `.`, `_` and `-`, lower case.
460fn is_host_part(s: &str) -> bool {
461    let mut chars = s.chars();
462    chars.next().is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
463        && s.len() <= 63
464        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-'))
465}
466
467/// A machine's name, never an address: digits and dots alone are an IPv4 address.
468fn is_host(s: &str) -> bool {
469    let (machine, channel) = s.split_once('/').map_or((s, None), |(m, c)| (m, Some(c)));
470    let address = machine.chars().all(|c| c.is_ascii_digit() || c == '.');
471    is_host_part(machine) && !address && channel.is_none_or(is_host_part)
472}
473
474/// `given` without `host`, and its value: once, last, `machine[/channel]` in lower case.
475fn take_host(given: &[(String, String)]) -> R<(&[(String, String)], Option<String>)> {
476    let Some(at) = given.iter().position(|(k, _)| k == HOST_PARAM) else {
477        return Ok((given, None));
478    };
479    if given.iter().filter(|(k, _)| k == HOST_PARAM).count() > 1 {
480        return Err(LinkError::DuplicateParam);
481    }
482    if at != given.len() - 1 {
483        return Err(LinkError::NotCanonical);
484    }
485    let text = &given[at].1;
486    if !is_host(text) {
487        return Err(if is_host(&text.to_lowercase()) { LinkError::NotCanonical } else { LinkError::BadValue });
488    }
489    Ok((&given[..at], Some(text.clone())))
490}
491
492fn read_params(
493    place: Option<&'static Place>,
494    values: &BTreeMap<String, Value>,
495    given: &[(String, String)],
496) -> R<BTreeMap<String, Value>> {
497    let declared = place.map(|p| p.params).unwrap_or(&[]);
498    let mut out = BTreeMap::new();
499    let mut last: Option<usize> = None;
500    for (key, text) in given {
501        if out.contains_key(key) {
502            return Err(LinkError::DuplicateParam);
503        }
504        let index = declared.iter().position(|p| p.name == key.as_str()).ok_or(LinkError::UnknownParam)?;
505        let spec = &declared[index];
506        if let Some((var, allowed)) = spec.only_with {
507            let holds = values.get(var).map(Value::to_string);
508            if !holds.is_some_and(|h| allowed.contains(&h.as_str())) {
509                return Err(LinkError::UnknownParam);
510            }
511        }
512        if last.is_some_and(|l| index < l) {
513            return Err(LinkError::NotCanonical);
514        }
515        last = Some(index);
516        let typed = Typed { kind: spec.kind, values: spec.values, min: spec.min, max: spec.max };
517        out.insert(key.clone(), typed_value(&typed, text, LinkError::BadValue)?);
518    }
519    Ok(out)
520}
521
522/// The one written form of a destination (R7). `values` holds `package` for a widget.
523pub fn format_link(
524    view: &View,
525    place: Option<&Place>,
526    values: &BTreeMap<String, Value>,
527    params: &BTreeMap<String, Value>,
528    anchor: Option<&str>,
529    host: Option<&str>,
530) -> String {
531    let head = if view.prefix {
532        format!("{}.{}", view.id, values.get("package").map(Value::to_string).unwrap_or_default())
533    } else {
534        view.id.to_string()
535    };
536    let mut parts = vec![head];
537    if let Some(p) = place {
538        for s in p.segments {
539            parts.push(match s {
540                Segment::Lit(l) => l.to_string(),
541                Segment::Var(v) => values.get(v.name).map(Value::to_string).unwrap_or_default(),
542            });
543        }
544    }
545    let mut link = format!("{SCHEME}{}", parts.iter().map(|p| encode_part(p)).collect::<Vec<_>>().join("/"));
546    let mut written: Vec<String> = place
547        .map(|p| p.params)
548        .unwrap_or(&[])
549        .iter()
550        .filter_map(|p| params.get(p.name).map(|v| format!("{}={}", p.name, encode_part(&v.to_string()))))
551        .collect();
552    if let Some(h) = host {
553        written.push(format!("{HOST_PARAM}={}", encode_part(h)));
554    }
555    if !written.is_empty() {
556        link.push('?');
557        link.push_str(&written.join("&"));
558    }
559    if let Some(a) = anchor {
560        link.push('#');
561        link.push_str(&encode_part(a));
562    }
563    link
564}
565
566/// Reads `link` against `reg`: the destination it names, or why it is refused (R8).
567pub fn parse_link_in(link: &str, reg: &'static Registry) -> R<ParsedLink> {
568    let shape = unalias(shape_of(link, reg)?, reg);
569    let (view, pkg) = find_view(&shape.head, reg)?;
570    if view.build > reg.build {
571        return Err(LinkError::NotYet);
572    }
573    let (place, mut values) = if shape.segments.is_empty() {
574        if view.requires_place {
575            return Err(LinkError::MissingPlace);
576        }
577        (None, BTreeMap::new())
578    } else {
579        let (p, v) = match_place(view, &shape.segments)?;
580        (Some(p), v)
581    };
582    if let Some(pkg) = pkg {
583        values.insert("package".to_string(), Value::Text(pkg));
584    }
585    let (given, host) = take_host(&shape.params)?;
586    let params = read_params(place, &values, given)?;
587    if let Some(a) = &shape.anchor {
588        if place.and_then(|p| p.anchor).is_none() {
589            return Err(LinkError::UnknownAnchor);
590        }
591        typed_value(&Typed { kind: Kind::Id, values: &[], min: None, max: None }, a, LinkError::BadValue)?;
592    }
593    let canonical = format_link(view, place, &values, &params, shape.anchor.as_deref(), host.as_deref());
594    Ok(ParsedLink { view, place, values, params, anchor: shape.anchor, host, canonical })
595}
596
597/// Reads `link` against the registry.
598pub fn parse_link(link: &str) -> R<ParsedLink> {
599    parse_link_in(link, &super::registry::REGISTRY)
600}