nexo-microapp-sdk 0.1.12

Reusable runtime helpers for Phase 11 stdio microapps consuming the nexo-rs daemon (JSON-RPC dispatch loop, BindingContext parsing, typed replies).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! BCP-47 locale subset for agent language configuration.
//!
//! The SDK ships a closed-enum locale model — every recognised
//! language and region is enumerated explicitly in [`LangCode`] and
//! [`RegionCode`]. Adding new locales requires a code change so
//! that the per-locale system addenda + voice picker tables stay
//! in lock-step (an exhaustive `match` over the enums prevents
//! "parse-but-no-addendum" gaps).
//!
//! ## Why a string-backed value type?
//!
//! [`Locale`] stores the canonical BCP-47 string (`es-AR`, not
//! `ES_ar`) so the wire shape stays transparent — call sites that
//! already serialise `Option<String>` (e.g.
//! `nexo_tool_meta::reply_kind::OutboundReplyContext::language`)
//! keep working unchanged. Consumers parse the string back into a
//! [`Locale`] on the receiving side.
//!
//! See `crates/microapp-sdk/src/voice/locale_addenda.rs` for the
//! addendum + voice picker tables that consume this type.

use thiserror::Error;

/// Closed set of language subtags. Adding one == code change.
///
/// Lowercase 2-letter ISO-639-1 codes when serialised. Variants
/// listed alphabetically by code for diff stability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LangCode {
    /// German.
    De,
    /// English.
    En,
    /// Spanish.
    Es,
    /// French.
    Fr,
    /// Italian.
    It,
    /// Japanese.
    Ja,
    /// Portuguese.
    Pt,
    /// Chinese (simplified script assumed; `zh-Hant` rejected v1).
    Zh,
}

impl LangCode {
    /// Lowercase 2-letter ISO-639-1 code (`es`, `en`, `pt`, …).
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::De => "de",
            Self::En => "en",
            Self::Es => "es",
            Self::Fr => "fr",
            Self::It => "it",
            Self::Ja => "ja",
            Self::Pt => "pt",
            Self::Zh => "zh",
        }
    }
}

/// Closed set of region subtags. Per-language coverage is what the
/// voice picker table guarantees a region-matched Edge voice for.
///
/// Uppercase 2-letter ISO-3166-1 alpha-2 codes when serialised.
/// Variants listed alphabetically.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RegionCode {
    /// Argentina.
    Ar,
    /// Australia.
    Au,
    /// Brazil.
    Br,
    /// Canada.
    Ca,
    /// Chile.
    Cl,
    /// China.
    Cn,
    /// Colombia.
    Co,
    /// Germany.
    De,
    /// Spain.
    Es,
    /// France.
    Fr,
    /// United Kingdom.
    Gb,
    /// Italy.
    It,
    /// Japan.
    Jp,
    /// Mexico.
    Mx,
    /// Peru.
    Pe,
    /// Portugal.
    Pt,
    /// United States.
    Us,
}

impl RegionCode {
    /// Uppercase 2-letter ISO-3166-1 alpha-2 code (`AR`, `MX`, …).
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Ar => "AR",
            Self::Au => "AU",
            Self::Br => "BR",
            Self::Ca => "CA",
            Self::Cl => "CL",
            Self::Cn => "CN",
            Self::Co => "CO",
            Self::De => "DE",
            Self::Es => "ES",
            Self::Fr => "FR",
            Self::Gb => "GB",
            Self::It => "IT",
            Self::Jp => "JP",
            Self::Mx => "MX",
            Self::Pe => "PE",
            Self::Pt => "PT",
            Self::Us => "US",
        }
    }
}

/// Parsed BCP-47 locale (subset).
///
/// Cheap to clone — wraps a single canonical [`String`]
/// (`es-AR`, never `ES_ar`). Construct via [`std::str::FromStr`]
/// or [`Locale::new`]; both routes guarantee the closed-enum set.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Locale(String);

impl Locale {
    /// Build a locale from already-typed enum values. The caller
    /// has already proved the language + region pair is valid; the
    /// resulting [`Locale::as_bcp47`] is the canonical
    /// `"<lang>-<REGION>"` (or `"<lang>"` when region is None).
    pub fn new(language: LangCode, region: Option<RegionCode>) -> Self {
        let raw = match region {
            Some(r) => format!("{}-{}", language.as_str(), r.as_str()),
            None => language.as_str().to_string(),
        };
        Self(raw)
    }

    /// Recover the [`LangCode`]. Infallible: every constructed
    /// [`Locale`] has been parsed against the closed enum.
    pub fn language(&self) -> LangCode {
        // Safe-by-construction: `Self::new` and `FromStr` both
        // build from a known-good `LangCode`. We re-parse the
        // first segment instead of caching to keep the type
        // small + `Copy`-clone-friendly via the inner String.
        let head = self.0.split('-').next().unwrap_or("");
        parse_language(head).expect("Locale invariant: language always valid")
    }

    /// Recover the [`RegionCode`] when present, `None` for
    /// language-only locales (`"es"`, `"en"`, …).
    pub fn region(&self) -> Option<RegionCode> {
        let mut parts = self.0.split('-');
        let _lang = parts.next();
        let region = parts.next()?;
        // `Self::new` and `FromStr` only produce already-validated
        // region tokens, so this expect can never trip on a value
        // that came through the public surface.
        Some(parse_region(region).expect("Locale invariant: region always valid"))
    }

    /// The canonical BCP-47 string (`"es-AR"` / `"en-US"` /
    /// `"es"`). Identical to [`Locale::to_string`] but without the
    /// allocation when the caller can borrow.
    pub fn as_bcp47(&self) -> &str {
        &self.0
    }

    /// Drop the region subtag, returning the language-only locale.
    /// Useful for fallback logic in voice picker / addendum tables.
    pub fn language_only(&self) -> Locale {
        Self::new(self.language(), None)
    }

    /// `true` when the locale carries no region subtag.
    pub fn is_just_language(&self) -> bool {
        !self.0.contains('-')
    }
}

impl std::str::FromStr for Locale {
    type Err = LocaleParseError;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            return Err(LocaleParseError::Empty);
        }
        // `es_AR` (Java/Microsoft style) accepted; canonical
        // separator is `-`. Lowercase the language head, uppercase
        // the region tail, refuse anything past the first region.
        let normalised = trimmed.replace('_', "-");
        let mut parts = normalised.split('-');
        let lang_raw = parts.next().unwrap_or(""); // safe: non-empty trimmed
        let region_raw = parts.next();
        if parts.next().is_some() {
            return Err(LocaleParseError::TooManySubtags(trimmed.to_string()));
        }

        let lang_lower = lang_raw.to_ascii_lowercase();
        let language = parse_language(&lang_lower)
            .ok_or_else(|| LocaleParseError::UnknownLanguage(lang_raw.to_string()))?;

        let region = match region_raw {
            None => None,
            Some(r) => {
                let upper = r.to_ascii_uppercase();
                let region = parse_region(&upper).ok_or_else(|| {
                    LocaleParseError::UnknownRegion(language.as_str().to_string(), r.to_string())
                })?;
                Some(region)
            }
        };

        Ok(Self::new(language, region))
    }
}

impl std::fmt::Display for Locale {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

// `#[serde(transparent)]` makes the JSON / YAML wire shape a bare
// string (`"es-AR"`), preserving compatibility with the existing
// `OutboundReplyContext.language: Option<String>` field. The
// transparent representation also means `serde_json::to_string`
// of a `Locale` is `"\"es-AR\""` — same as the input.
impl serde::Serialize for Locale {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(&self.0)
    }
}

impl<'de> serde::Deserialize<'de> for Locale {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        use serde::de::Error;
        let raw = String::deserialize(d)?;
        raw.parse().map_err(D::Error::custom)
    }
}

fn parse_language(s: &str) -> Option<LangCode> {
    Some(match s {
        "de" => LangCode::De,
        "en" => LangCode::En,
        "es" => LangCode::Es,
        "fr" => LangCode::Fr,
        "it" => LangCode::It,
        "ja" => LangCode::Ja,
        "pt" => LangCode::Pt,
        "zh" => LangCode::Zh,
        _ => return None,
    })
}

fn parse_region(s: &str) -> Option<RegionCode> {
    Some(match s {
        "AR" => RegionCode::Ar,
        "AU" => RegionCode::Au,
        "BR" => RegionCode::Br,
        "CA" => RegionCode::Ca,
        "CL" => RegionCode::Cl,
        "CN" => RegionCode::Cn,
        "CO" => RegionCode::Co,
        "DE" => RegionCode::De,
        "ES" => RegionCode::Es,
        "FR" => RegionCode::Fr,
        "GB" => RegionCode::Gb,
        "IT" => RegionCode::It,
        "JP" => RegionCode::Jp,
        "MX" => RegionCode::Mx,
        "PE" => RegionCode::Pe,
        "PT" => RegionCode::Pt,
        "US" => RegionCode::Us,
        _ => return None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::str::FromStr;

    // ── Parser: valid inputs ────────────────────────────────────

    #[test]
    fn parses_language_only() {
        let l = Locale::from_str("es").unwrap();
        assert_eq!(l.language(), LangCode::Es);
        assert_eq!(l.region(), None);
        assert_eq!(l.as_bcp47(), "es");
    }

    #[test]
    fn parses_full_locale() {
        let l = Locale::from_str("es-AR").unwrap();
        assert_eq!(l.language(), LangCode::Es);
        assert_eq!(l.region(), Some(RegionCode::Ar));
        assert_eq!(l.as_bcp47(), "es-AR");
    }

    #[test]
    fn parses_underscore_separator_canonicalises_to_hyphen() {
        let l = Locale::from_str("es_AR").unwrap();
        assert_eq!(l.as_bcp47(), "es-AR");
    }

    #[test]
    fn parses_mixed_case_canonicalises() {
        let l = Locale::from_str("ES-ar").unwrap();
        assert_eq!(l.as_bcp47(), "es-AR");
    }

    #[test]
    fn parses_with_surrounding_whitespace() {
        let l = Locale::from_str("  es-AR  ").unwrap();
        assert_eq!(l.as_bcp47(), "es-AR");
    }

    #[test]
    fn parses_pt_br() {
        let l = Locale::from_str("pt-BR").unwrap();
        assert_eq!(l.language(), LangCode::Pt);
        assert_eq!(l.region(), Some(RegionCode::Br));
    }

    // ── Parser: invalid inputs ─────────────────────────────────

    #[test]
    fn empty_string_errors_with_empty_variant() {
        assert_eq!(Locale::from_str("").unwrap_err(), LocaleParseError::Empty);
    }

    #[test]
    fn whitespace_only_errors_with_empty_variant() {
        assert_eq!(
            Locale::from_str("   ").unwrap_err(),
            LocaleParseError::Empty
        );
    }

    #[test]
    fn unknown_language_errors() {
        match Locale::from_str("xx").unwrap_err() {
            LocaleParseError::UnknownLanguage(s) => assert_eq!(s, "xx"),
            other => panic!("expected UnknownLanguage, got {other:?}"),
        }
    }

    #[test]
    fn unknown_region_for_known_language_errors() {
        match Locale::from_str("es-XX").unwrap_err() {
            LocaleParseError::UnknownRegion(lang, region) => {
                assert_eq!(lang, "es");
                assert_eq!(region, "XX");
            }
            other => panic!("expected UnknownRegion, got {other:?}"),
        }
    }

    #[test]
    fn extra_subtags_errors_too_many() {
        match Locale::from_str("es-AR-x").unwrap_err() {
            LocaleParseError::TooManySubtags(s) => assert_eq!(s, "es-AR-x"),
            other => panic!("expected TooManySubtags, got {other:?}"),
        }
    }

    #[test]
    fn script_subtag_errors_too_many() {
        // `zh-Hant` carries a script subtag; v1 parser rejects.
        match Locale::from_str("zh-Hant-CN").unwrap_err() {
            LocaleParseError::TooManySubtags(_) => {}
            other => panic!("expected TooManySubtags, got {other:?}"),
        }
    }

    #[test]
    fn variant_subtag_errors_too_many() {
        match Locale::from_str("de-DE-1996").unwrap_err() {
            LocaleParseError::TooManySubtags(_) => {}
            other => panic!("expected TooManySubtags, got {other:?}"),
        }
    }

    #[test]
    fn m49_un_region_code_errors_unknown_region() {
        // `es-419` (UN M.49 for Latin America) — not in v1 enum.
        match Locale::from_str("es-419").unwrap_err() {
            LocaleParseError::UnknownRegion(lang, region) => {
                assert_eq!(lang, "es");
                assert_eq!(region, "419");
            }
            other => panic!("expected UnknownRegion, got {other:?}"),
        }
    }
}

/// Parser-side errors. Wrapped in [`thiserror::Error`] so they
/// surface cleanly through the existing error envelopes
/// (`ToolError::InvalidArguments`, daemon boot logs, admin RPC).
#[derive(Debug, Clone, Error, PartialEq, Eq)]
pub enum LocaleParseError {
    /// Empty input string after trimming whitespace.
    #[error("empty locale string")]
    Empty,
    /// Language subtag not in [`LangCode`]'s closed set.
    #[error("unsupported language subtag `{0}`")]
    UnknownLanguage(String),
    /// Region subtag not in [`RegionCode`]'s closed set OR not
    /// covered by the voice picker for the supplied language.
    #[error("unsupported region subtag `{1}` for language `{0}`")]
    UnknownRegion(String, String),
    /// Locale string carries more than `language[-region]` —
    /// script subtags (`zh-Hant`), variants (`de-DE-1996`), and
    /// extension subtags are deferred to a follow-up.
    #[error("unsupported subtag count: locale `{0}` has more than one region/script subtag")]
    TooManySubtags(String),
}