nestor-satellite 0.5.0

Rust SDK to write Nestor satellite drivers: pairing, the WebSocket link, text, and WebRTC audio as a feature.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! The values of the satellite protocol `nestor.satellite/1`: a device, what it can do, how it can
//! be paired, and the intents it receives.
//!
//! They mirror the JSON Schemas vendored in `schemas/`, generated by the Nestor server: every
//! constructor checks the same constraints, so a manifest built here is one the core accepts.

use std::collections::BTreeSet;
use std::fmt;

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use thiserror::Error;

/// The protocol this SDK speaks.
pub const PROTOCOL: &str = "nestor.satellite/1";

/// The device sends what a person typed (`input.text`).
pub const TEXT_INPUT: &str = "text.input";
/// The device shows the assistant's words (`intent.text`).
pub const TEXT_DISPLAY: &str = "text.display";
/// The device captures audio (a microphone) and streams it to the core.
pub const AUDIO_CAPTURE: &str = "audio.capture";
/// The device plays the core's voice (a speaker).
pub const AUDIO_PLAYBACK: &str = "audio.playback";
/// The device performs expressions (`intent.expression`).
pub const EXPRESSION: &str = "expression.emotion";
/// The device moves its head with speech (`intent.beat`).
pub const HEAD_MOTION: &str = "motion.head";
/// The device detects people on its own (`observation.person.detected`).
pub const PERSON_DETECTION: &str = "vision.person_detection";
/// The device detects voice activity on its own (`observation.speech.activity`).
pub const SPEECH_ACTIVITY: &str = "audio.speech_activity";
/// The device can make itself noticed (blink, wiggle, chime) when a person asks which one it is
/// (`intent.identify`, and `identify` in a pending pairing's answer). An aid, never a proof.
pub const IDENTIFY: &str = "device.identify";

/// At most this many capabilities in a manifest.
pub const MAX_CAPABILITIES: usize = 32;
const MAX_TEXT: usize = 64;

/// Something that does not follow `nestor.satellite/1`.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("{0}")]
pub struct ProtocolError(pub(crate) String);

impl ProtocolError {
    pub(crate) fn new(message: impl Into<String>) -> Self {
        Self(message.into())
    }
}

/// The assistant's attitude, shown until the next one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Behavior {
    /// At rest.
    Idle,
    /// Someone is talking to the assistant.
    Listening,
    /// The assistant prepares its answer.
    Thinking,
    /// The assistant speaks.
    Speaking,
}

/// An expression, performed as the matching audio is played.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Expression {
    /// A laugh, a smile.
    Joy,
    /// A sigh.
    Sigh,
    /// Pondering.
    Thoughtful,
    /// A whisper.
    Whisper,
    /// Excitement.
    Excited,
    /// Clearing the throat.
    Ahem,
}

impl Behavior {
    /// Every behavior, in the schema's order.
    pub const ALL: [Self; 4] = [Self::Idle, Self::Listening, Self::Thinking, Self::Speaking];

    /// The wire name (`"idle"`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Idle => "idle",
            Self::Listening => "listening",
            Self::Thinking => "thinking",
            Self::Speaking => "speaking",
        }
    }
}

impl Expression {
    /// Every expression, in the schema's order.
    pub const ALL: [Self; 6] = [Self::Joy, Self::Sigh, Self::Thoughtful, Self::Whisper, Self::Excited, Self::Ahem];

    /// The wire name (`"joy"`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Joy => "joy",
            Self::Sigh => "sigh",
            Self::Thoughtful => "thoughtful",
            Self::Whisper => "whisper",
            Self::Excited => "excited",
            Self::Ahem => "ahem",
        }
    }
}

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

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

/// How a person can pair a device. A manifest declares those the device can carry out.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum PairingMethod {
    /// The person reads the device code on the device's screen and types it in Nestor.
    #[serde(rename = "device_code.display")]
    DeviceCodeDisplay,
    /// The person hears the device say its code and types it in Nestor.
    #[serde(rename = "device_code.speech")]
    DeviceCodeSpeech,
    /// The person types an enrollment code on the device.
    #[serde(rename = "enrollment.input")]
    EnrollmentInput,
    /// The person sets the pairing URI or the enrollment code in the device's configuration (flag,
    /// environment, file). Every device supports it.
    #[serde(rename = "enrollment.provisioning")]
    EnrollmentProvisioning,
}

impl PairingMethod {
    /// Every method this SDK can declare, in the schema's order. The protocol's `enrollment.qr`
    /// (scanning the pairing URI's QR code) needs a camera, which this SDK does not drive: it is
    /// not one of them.
    pub const ALL: [Self; 4] =
        [Self::DeviceCodeDisplay, Self::DeviceCodeSpeech, Self::EnrollmentInput, Self::EnrollmentProvisioning];

    /// The wire name (`"device_code.display"`).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::DeviceCodeDisplay => "device_code.display",
            Self::DeviceCodeSpeech => "device_code.speech",
            Self::EnrollmentInput => "enrollment.input",
            Self::EnrollmentProvisioning => "enrollment.provisioning",
        }
    }
}

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

/// How the device received an enrollment code: the pairing methods whose proof is an enrollment code
/// that this SDK carries out (not `enrollment.qr`: it drives no camera).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum EnrollmentMethod {
    /// Typed on the device.
    #[serde(rename = "enrollment.input")]
    Input,
    /// Set in its configuration (flag, environment, file).
    #[serde(rename = "enrollment.provisioning")]
    Provisioning,
}

impl From<EnrollmentMethod> for PairingMethod {
    fn from(method: EnrollmentMethod) -> Self {
        match method {
            EnrollmentMethod::Input => Self::EnrollmentInput,
            EnrollmentMethod::Provisioning => Self::EnrollmentProvisioning,
        }
    }
}

impl fmt::Display for EnrollmentMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        PairingMethod::from(*self).fmt(f)
    }
}

/// A device. `id`, `room` and `brand` are lowercase slugs: they end up in addresses (`voice:salon`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Device {
    id: String,
    model: String,
    room: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    brand: Option<String>,
}

impl Device {
    /// A device `id` (`enceinte-salon`) of a `model` (`raspberry-pi-4`) in a `room` (`salon`).
    pub fn new(
        id: impl Into<String>,
        model: impl Into<String>,
        room: impl Into<String>,
    ) -> Result<Self, ProtocolError> {
        let (id, model, room) = (id.into(), model.into(), room.into());
        for (name, value) in [("id", &id), ("room", &room)] {
            if !is_slug(value) {
                return Err(ProtocolError::new(format!(
                    "device {name} {value:?} must be a lowercase slug (a-z, 0-9, - and _)"
                )));
            }
        }
        if model.is_empty() || model.chars().count() > MAX_TEXT {
            return Err(ProtocolError::new("device model must be 1 to 64 characters"));
        }
        Ok(Self { id, model, room, brand: None })
    }

    /// Its maker, as a slug (`pollen-robotics`).
    pub fn with_brand(mut self, brand: impl Into<String>) -> Result<Self, ProtocolError> {
        let brand = brand.into();
        if !is_slug(&brand) {
            return Err(ProtocolError::new(format!(
                "device brand {brand:?} must be a lowercase slug (a-z, 0-9, - and _)"
            )));
        }
        self.brand = Some(brand);
        Ok(self)
    }

    /// The device id, unique in the household.
    pub fn id(&self) -> &str {
        &self.id
    }

    /// The device model.
    pub fn model(&self) -> &str {
        &self.model
    }

    /// The room the device is in.
    pub fn room(&self) -> &str {
        &self.room
    }

    /// The device's maker, when declared.
    pub fn brand(&self) -> Option<&str> {
        self.brand.as_deref()
    }
}

/// The software a device runs, as it names it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Sdk {
    name: String,
    version: String,
}

impl Sdk {
    /// A software name and version, each 1 to 64 characters.
    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Result<Self, ProtocolError> {
        let (name, version) = (name.into(), version.into());
        for (key, value) in [("name", &name), ("version", &version)] {
            if value.is_empty() || value.chars().count() > MAX_TEXT {
                return Err(ProtocolError::new(format!("sdk {key} must be 1 to 64 characters")));
            }
        }
        Ok(Self { name, version })
    }

    /// This SDK: `nestor-satellite-rust` and its version.
    pub fn this() -> Self {
        Self { name: "nestor-satellite-rust".to_owned(), version: env!("CARGO_PKG_VERSION").to_owned() }
    }

    /// The software name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The software version.
    pub fn version(&self) -> &str {
        &self.version
    }
}

/// A capability the device declares (`family.feature`), with its own parameters.
#[derive(Debug, Clone, PartialEq)]
pub struct Capability {
    name: String,
    params: Map<String, Value>,
}

impl Capability {
    /// A capability by name, e.g. [`AUDIO_CAPTURE`].
    pub fn new(name: impl Into<String>) -> Result<Self, ProtocolError> {
        let name = name.into();
        if !is_capability(&name) {
            return Err(ProtocolError::new(format!("invalid capability {name:?}: expected 'family.feature'")));
        }
        Ok(Self { name, params: Map::new() })
    }

    /// Adds a parameter, e.g. `("formats", json!(["opus/48000"]))`; `name` is reserved.
    pub fn with_param(mut self, key: impl Into<String>, value: impl Into<Value>) -> Result<Self, ProtocolError> {
        let key = key.into();
        if key == "name" {
            return Err(ProtocolError::new("a capability parameter cannot be called 'name'"));
        }
        self.params.insert(key, value.into());
        Ok(self)
    }

    /// The capability name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Its parameters.
    pub fn params(&self) -> &Map<String, Value> {
        &self.params
    }
}

impl Serialize for Capability {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut entry = Map::with_capacity(self.params.len() + 1);
        entry.insert("name".to_owned(), Value::String(self.name.clone()));
        entry.extend(self.params.clone());
        entry.serialize(serializer)
    }
}

/// What a device says about itself when it pairs and when it connects.
///
/// It declares [`PairingMethod::EnrollmentProvisioning`] only; a [`Satellite`](crate::Satellite)
/// replaces its pairing methods with those its outputs and inputs carry out.
#[derive(Debug, Clone, PartialEq)]
pub struct Manifest {
    device: Device,
    capabilities: Vec<Capability>,
    sdk: Option<Sdk>,
    pairing_methods: BTreeSet<PairingMethod>,
}

impl Manifest {
    /// A manifest declaring capabilities by name; it names this SDK ([`Sdk::this`]).
    pub fn new<I, S>(device: Device, capabilities: I) -> Result<Self, ProtocolError>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let capabilities = capabilities.into_iter().map(Capability::new).collect::<Result<Vec<_>, _>>()?;
        Self::with_capabilities(device, capabilities)
    }

    /// A manifest declaring capabilities with parameters; it names this SDK ([`Sdk::this`]).
    pub fn with_capabilities(device: Device, capabilities: Vec<Capability>) -> Result<Self, ProtocolError> {
        if capabilities.len() > MAX_CAPABILITIES {
            return Err(ProtocolError::new(format!("at most {MAX_CAPABILITIES} capabilities")));
        }
        let names: BTreeSet<&str> = capabilities.iter().map(Capability::name).collect();
        if names.len() != capabilities.len() {
            return Err(ProtocolError::new("a capability is declared twice"));
        }
        Ok(Self {
            device,
            capabilities,
            sdk: Some(Sdk::this()),
            pairing_methods: BTreeSet::from([PairingMethod::EnrollmentProvisioning]),
        })
    }

    /// Declares the pairing methods the device carries out: at least one.
    pub fn with_pairing_methods(
        mut self,
        methods: impl IntoIterator<Item = PairingMethod>,
    ) -> Result<Self, ProtocolError> {
        let methods: BTreeSet<PairingMethod> = methods.into_iter().collect();
        if methods.is_empty() {
            return Err(ProtocolError::new("a manifest declares at least one pairing method"));
        }
        self.pairing_methods = methods;
        Ok(self)
    }

    /// The manifest with these capabilities declared too (those already declared are kept as they are).
    pub(crate) fn declaring<'a>(mut self, names: impl IntoIterator<Item = &'a str>) -> Result<Self, ProtocolError> {
        for name in names {
            if !self.declares(name) {
                self.capabilities.push(Capability::new(name)?);
            }
        }
        if self.capabilities.len() > MAX_CAPABILITIES {
            return Err(ProtocolError::new(format!("at most {MAX_CAPABILITIES} capabilities")));
        }
        Ok(self)
    }

    /// Names another software than this SDK (a driver framework built on it), or none.
    pub fn with_sdk(mut self, sdk: Option<Sdk>) -> Self {
        self.sdk = sdk;
        self
    }

    /// The device.
    pub fn device(&self) -> &Device {
        &self.device
    }

    /// The declared capabilities.
    pub fn capabilities(&self) -> &[Capability] {
        &self.capabilities
    }

    /// The software named in the manifest.
    pub fn sdk(&self) -> Option<&Sdk> {
        self.sdk.as_ref()
    }

    /// The declared pairing methods, in the schema's order.
    pub fn pairing_methods(&self) -> impl Iterator<Item = PairingMethod> + '_ {
        self.pairing_methods.iter().copied()
    }

    /// Whether the pairing method is declared.
    pub fn supports(&self, method: PairingMethod) -> bool {
        self.pairing_methods.contains(&method)
    }

    /// Whether the capability `name` is declared.
    pub fn declares(&self, name: &str) -> bool {
        self.capabilities.iter().any(|c| c.name == name)
    }

    /// The manifest as the core reads it (`manifest.json`).
    pub fn to_json(&self) -> Value {
        let mut data = Map::new();
        data.insert("protocol".to_owned(), Value::String(PROTOCOL.to_owned()));
        data.insert("device".to_owned(), to_value(&self.device));
        data.insert("capabilities".to_owned(), Value::Array(self.capabilities.iter().map(to_value).collect()));
        if let Some(sdk) = &self.sdk {
            data.insert("sdk".to_owned(), to_value(sdk));
        }
        let methods = self.pairing_methods.iter().map(|m| Value::String(m.as_str().to_owned())).collect();
        data.insert("pairing_methods".to_owned(), Value::Array(methods));
        Value::Object(data)
    }
}

fn to_value(value: &impl Serialize) -> Value {
    // Only maps of strings and JSON values are serialized here: this cannot fail.
    serde_json::to_value(value).unwrap_or(Value::Null)
}

/// `^[a-z0-9][a-z0-9_-]{0,63}$`
pub(crate) fn is_slug(value: &str) -> bool {
    let mut chars = value.chars();
    let first_ok = chars.next().is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit());
    first_ok
        && value.len() <= MAX_TEXT
        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
}

/// `^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$`
fn is_capability(value: &str) -> bool {
    let parts: Vec<&str> = value.split('.').collect();
    parts.len() >= 2
        && parts.iter().all(|part| {
            let mut chars = part.chars();
            chars.next().is_some_and(|c| c.is_ascii_lowercase())
                && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn device() -> Device {
        Device::new("enceinte-salon", "raspberry-pi-4", "salon").unwrap()
    }

    #[test]
    fn a_device_id_and_room_must_be_lowercase_slugs() {
        assert!(Device::new("Salon", "m", "salon").is_err());
        assert!(Device::new("ok", "m", "sa lon").is_err());
        assert!(Device::new("-x", "m", "salon").is_err());
        assert!(Device::new("x".repeat(65), "m", "salon").is_err());
        assert!(Device::new("x".repeat(64), "m", "salon").is_ok());
        assert!(device().with_brand("Pollen").is_err());
    }

    #[test]
    fn a_device_model_has_one_to_64_characters() {
        assert!(Device::new("a", "", "salon").is_err());
        assert!(Device::new("a", "é".repeat(64), "salon").is_ok());
        assert!(Device::new("a", "m".repeat(65), "salon").is_err());
    }

    #[test]
    fn a_capability_is_a_dotted_family_and_feature() {
        assert!(Capability::new("audio.capture").is_ok());
        assert!(Capability::new("vision.person_detection").is_ok());
        for wrong in ["audio", "Audio.capture", "audio.", ".capture", "audio.1x", "a..b"] {
            assert!(Capability::new(wrong).is_err(), "{wrong}");
        }
        assert!(Capability::new("audio.capture").unwrap().with_param("name", 1).is_err());
    }

    #[test]
    fn a_manifest_refuses_duplicates_and_too_many_capabilities() {
        assert!(Manifest::new(device(), [AUDIO_CAPTURE, AUDIO_CAPTURE]).is_err());
        let many: Vec<String> = (0..33).map(|i| format!("custom.f{i}")).collect();
        assert!(Manifest::new(device(), many).is_err());
    }

    #[test]
    fn a_manifest_serializes_as_the_core_reads_it() {
        let capture = Capability::new(AUDIO_CAPTURE).unwrap().with_param("formats", json!(["opus/48000"])).unwrap();
        let manifest = Manifest::with_capabilities(device().with_brand("raspberry").unwrap(), vec![capture]).unwrap();
        assert_eq!(
            manifest.to_json(),
            json!({
                "protocol": "nestor.satellite/1",
                "device": {"id": "enceinte-salon", "model": "raspberry-pi-4", "room": "salon", "brand": "raspberry"},
                "capabilities": [{"name": "audio.capture", "formats": ["opus/48000"]}],
                "sdk": {"name": "nestor-satellite-rust", "version": env!("CARGO_PKG_VERSION")},
                "pairing_methods": ["enrollment.provisioning"],
            })
        );
        assert!(manifest.declares(AUDIO_CAPTURE) && !manifest.declares(AUDIO_PLAYBACK));
        let bare = Manifest::new(device(), [AUDIO_PLAYBACK]).unwrap().with_sdk(None);
        assert!(bare.to_json().get("sdk").is_none());
        assert!(bare.to_json()["device"].get("brand").is_none());
    }

    #[test]
    fn pairing_methods_are_declared_once_each_in_the_schema_s_order() {
        use PairingMethod::*;
        let manifest = Manifest::new(device(), [IDENTIFY]).unwrap();
        assert!(manifest.with_pairing_methods([]).is_err(), "at least one");
        let manifest = Manifest::new(device(), [IDENTIFY])
            .unwrap()
            .with_pairing_methods([EnrollmentProvisioning, DeviceCodeSpeech, DeviceCodeDisplay, DeviceCodeSpeech])
            .unwrap();
        assert_eq!(
            manifest.to_json()["pairing_methods"],
            json!(["device_code.display", "device_code.speech", "enrollment.provisioning"])
        );
        assert!(manifest.supports(DeviceCodeSpeech) && !manifest.supports(EnrollmentInput));
        let names: Vec<&str> = PairingMethod::ALL.iter().map(|m| m.as_str()).collect();
        assert_eq!(serde_json::to_value(PairingMethod::ALL).unwrap(), json!(names));
        assert_eq!(PairingMethod::from(EnrollmentMethod::Input), EnrollmentInput);
    }
}