liminal-cli 0.3.30

The liminal command: serve the network, maintain its stores, or serve its discovery MCP over stdio
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! The ticket's configuration.
//!
//! The ticket's configuration (SDK-017 R1), read from the TOML file named on
//! its command line: the server's address, the channel, the Lys pass from a
//! file of its own (never printed or logged), and the limits. A missing or
//! zero field is refused by its name before any socket or stdin is touched.

use std::fmt;
use std::path::{Path, PathBuf};
use std::time::Duration;

pub use crate::mcp::listen_config::ListenConfig;
use serde::Deserialize;

/// The Lys pass, read from its file. Its Debug prints its length only.
pub struct Token(String);

impl Token {
    /// Borrows the pass only for the authenticated connection boundary.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for Token {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Token({} bytes)", self.0.len())
    }
}

/// The ticket's limits; every one is positive.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Limits {
    /// The longest JSON-RPC line read from stdin, in bytes.
    pub frame_bytes: usize,
    /// The largest topology record accepted from `console.topology`, in bytes.
    pub record_bytes: usize,
    /// How long one routed request may wait for its reply, in milliseconds.
    pub reply_timeout_ms: u64,
    /// The most steps one flow may carry.
    pub flow_steps: usize,
    /// The largest request body sent on a subject, in bytes.
    pub request_bytes: usize,
    /// How long a loopback server or issuer may take to accept a connection
    /// before the seat is refused (AGT-006 R3), in milliseconds; 2000 when
    /// unnamed: a local exchange answers in milliseconds.
    #[serde(default = "default_connect_timeout_ms")]
    pub connect_timeout_ms: u64,
    /// The largest answer `liminal mcp` writes inline on stdout, in bytes; a
    /// larger one is handed over whole as a file (SRV-052 R2). 16 MiB when
    /// unnamed: an MCP host holds a tool result in memory, and 16 MiB is far
    /// past a page while bounded. Never the stdin line bound.
    #[serde(default = "default_answer_bytes")]
    pub answer_bytes: usize,
}

const fn default_connect_timeout_ms() -> u64 {
    2_000
}

const fn default_answer_bytes() -> usize {
    16_777_216
}

fn central_server() -> String {
    crate::seat::CENTRAL_SERVER.to_owned()
}

impl Limits {
    /// The reply timeout as a duration.
    #[must_use]
    pub const fn reply_timeout(&self) -> Duration {
        Duration::from_millis(self.reply_timeout_ms)
    }

    /// The loopback connect bound as a duration.
    #[must_use]
    pub const fn connect_timeout(&self) -> Duration {
        Duration::from_millis(self.connect_timeout_ms)
    }

    const fn validate(self) -> Result<Self, &'static str> {
        if self.frame_bytes == 0 {
            return Err("frame_bytes");
        }
        if self.record_bytes == 0 {
            return Err("record_bytes");
        }
        if self.reply_timeout_ms == 0 {
            return Err("reply_timeout_ms");
        }
        if self.flow_steps == 0 {
            return Err("flow_steps");
        }
        if self.request_bytes == 0 {
            return Err("request_bytes");
        }
        if self.connect_timeout_ms == 0 {
            return Err("connect_timeout_ms");
        }
        if self.answer_bytes == 0 {
            return Err("answer_bytes");
        }
        Ok(self)
    }
}

/// Validated inputs for the ticket.
#[derive(Debug)]
pub struct Config {
    /// The server address every connection dials.
    pub server: String,
    /// The channel routed requests travel on.
    pub channel: String,
    /// Where the pass comes from: a fixed pass, or Lys asked with the agent's key.
    pub credential: Credential,
    /// The limits validated before anything is opened.
    pub limits: Limits,
    /// This seat's validated agent identity, used only for its own inbox.
    pub agent: Option<String>,
    /// Exact subjects and positive bounds for channel input.
    pub listen: ListenConfig,
}

/// Where the ticket's pass comes from.
#[derive(Debug)]
pub enum Credential {
    /// A pass read once from `token_file`, whose Debug reveals only its length.
    Token(Token),
    /// `[lys]`: the agent's own pass, asked of Lys with its key and renewed.
    Lys(crate::lys::LysTable),
    /// Neither (ACCESS-010 R3): an open seat on an exchange that gates
    /// nothing; it presents no credential, only the name it declares
    /// (ACCESS-012 R2), when it has one.
    Open {
        /// `[open] name`, recorded by the exchange as `open:<name>`.
        name: Option<String>,
    },
}

impl Credential {
    /// Who this seat is to an exchange, in one phrase: `open:<name>` or
    /// `open:anonymous` for an open seat, the kind alone for the others.
    #[must_use]
    pub fn holder(&self) -> String {
        match self {
            Self::Open { name } => format!("open:{}", name.as_deref().unwrap_or("anonymous")),
            Self::Token(_) => "token file".to_owned(),
            Self::Lys(lys) => format!("lys issuer {}", lys.issuer),
        }
    }

    /// The record an open seat presents at `Connect` (ACCESS-012 R2):
    /// `open:<name>`, or nothing when it declares no name; empty for every
    /// other credential, which present their pass instead.
    #[must_use]
    pub fn open_record(&self) -> Vec<u8> {
        match self {
            Self::Open { name: Some(name) } => format!("open:{name}").into_bytes(),
            _ => Vec::new(),
        }
    }
}

/// Whether `name` is a declared name: 1 to 64 of `a-z`, `0-9`, `.`, `_` or
/// `-`, the same word as the exchange's.
#[must_use]
pub fn is_open_name(name: &str) -> bool {
    (1..=64).contains(&name.len())
        && name.bytes().all(|b| {
            b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-')
        })
}

/// Why a configuration is refused.
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    /// Reading the named configuration failed.
    #[error("the configuration {path} cannot be read: {message}")]
    Unreadable {
        /// The configuration that could not be read.
        path: PathBuf,
        /// The operating-system failure, without file contents.
        message: String,
    },
    /// The named configuration did not satisfy its schema.
    #[error("the configuration {path} is refused: {message}")]
    Invalid {
        /// The refused configuration.
        path: PathBuf,
        /// The schema failure, without file contents.
        message: String,
    },
    /// A limit is zero.
    #[error("the configuration {path} is refused: {field} must be positive")]
    Zero {
        /// The refused configuration.
        path: PathBuf,
        /// The field that is zero.
        field: &'static str,
    },
    /// Reading or validating the pass failed, without revealing its bytes.
    #[error("the token file {path} cannot be read: {message}")]
    Token {
        /// The refused token file.
        path: PathBuf,
        /// The failure, without token contents.
        message: String,
    },
}

/// The file as written; every field but the server (the central exchange
/// when unnamed) is required, and an unknown one is refused.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Written {
    harness: Option<toml::Table>,
    #[serde(default = "central_server")]
    server: String,
    channel: String,
    token_file: Option<PathBuf>,
    lys: Option<crate::lys::LysTable>,
    limits: Limits,
    agent: Option<String>,
    #[serde(default)]
    listen: ListenConfig,
    open: Option<OpenTable>,
}

/// `[open]` (ACCESS-011 R1): how far a seat with no credential reaches. The
/// table is refused beside a credential, so it never reads as a way to
/// loosen a gated seat.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OpenTable {
    /// Loopback without the table; the network when the operator writes it.
    #[serde(default)]
    pub reach: Reach,
    /// The name this seat declares to an open exchange (ACCESS-012 R2):
    /// recorded as `open:<name>` on what it creates; anonymous without one.
    #[serde(default)]
    pub name: Option<String>,
}

/// How far an open seat reaches.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Reach {
    /// This machine only.
    #[default]
    Loopback,
    /// Any exchange address the seat names; the exchange asks it nothing.
    Network,
}

/// What `liminal mcp`'s flags say about the seat.
///
/// Tom, 25 Oct: "can we have a generic one and set id at runtime?" Each flag
/// given wins over the seat file's value; with no file, `liminal seat
/// init`'s channel and limits stand under them.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Overrides {
    /// `--server`: the exchange to dial.
    pub server: Option<String>,
    /// `--channel`: the channel routed requests travel on.
    pub channel: Option<String>,
    /// `--as`: the name an open seat declares (`[open] name`).
    pub name: Option<String>,
    /// `--agent`: the Lys agent id (`[lys] agent`), given with `--key-file`.
    pub agent: Option<String>,
    /// `--key-file`: the agent's key (`[lys] key_file`), given with `--agent`.
    pub key_file: Option<PathBuf>,
}

impl Overrides {
    /// Whether no flag was given.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self == &Self::default()
    }

    /// Writes the flags into `table`, the seat file's or the seat-init
    /// defaults, so the one validation below reads them as written fields.
    /// The seat's kind is never overridden: `--as` beside `[lys]` or a
    /// `token_file`, and `--agent` beside `[open]` or a `token_file`, are
    /// refused, as is `--agent` or `--key-file` alone.
    fn apply(&self, table: &mut toml::Table, written: bool) -> Result<(), String> {
        let lys = match (&self.agent, &self.key_file) {
            (Some(agent), Some(key_file)) => Some((agent, key_file)),
            (Some(_), None) => return Err("--agent needs --key-file, the agent's key".to_owned()),
            (None, Some(_)) => {
                return Err("--key-file needs --agent, the agent it is the key of".to_owned());
            }
            (None, None) => None,
        };
        if self.name.is_some() && lys.is_some() {
            return Err(
                "--as names an open seat and --agent a Lys one; give one of them".to_owned(),
            );
        }
        let credential = ["lys", "token_file"]
            .into_iter()
            .find(|key| table.contains_key(*key))
            .map(|key| if key == "lys" { "[lys]" } else { "token_file" });
        if let Some(server) = &self.server {
            table.insert("server".into(), server.clone().into());
        }
        if let Some(channel) = &self.channel {
            table.insert("channel".into(), channel.clone().into());
        }
        if let Some(name) = &self.name {
            if let Some(credential) = credential {
                return Err(format!(
                    "--as names an open seat; this seat has {credential}, whose key is its identity"
                ));
            }
            if !is_open_name(name) {
                return Err("--as must be 1 to 64 of a-z, 0-9, '.', '_' or '-'".to_owned());
            }
            let open = table_of(table, "open")?;
            open.insert("name".into(), name.clone().into());
        }
        if let Some((agent, key_file)) = lys {
            if table.contains_key("open") || table.contains_key("token_file") {
                let kind = if table.contains_key("open") {
                    "[open]"
                } else {
                    "token_file"
                };
                return Err(format!(
                    "--agent names a Lys seat; this seat has {kind}, remove it or give --as"
                ));
            }
            let key_file = std::path::absolute(key_file)
                .map_err(|error| format!("--key-file cannot be made absolute: {error}"))?;
            let key_file = key_file
                .to_str()
                .ok_or("--key-file is not a UTF-8 path")?
                .to_owned();
            if table.contains_key("agent") {
                table.insert("agent".into(), agent.clone().into());
            }
            let lys = table_of(table, "lys")?;
            lys.insert("agent".into(), agent.clone().into());
            lys.insert("key_file".into(), key_file.into());
        }
        // With no file an open seat off loopback reaches the network, as
        // `liminal seat init --open` writes it; a file's own reach stands.
        if !written
            && credential.is_none()
            && !table.contains_key("lys")
            && table
                .get("server")
                .and_then(toml::Value::as_str)
                .is_some_and(|server| !crate::seat::names_loopback(server))
        {
            let open = table_of(table, "open")?;
            open.entry("reach").or_insert_with(|| "network".into());
        }
        Ok(())
    }
}

/// `table[key]` as a table, made empty when absent.
fn table_of<'a>(table: &'a mut toml::Table, key: &str) -> Result<&'a mut toml::Table, String> {
    table
        .entry(key)
        .or_insert_with(|| toml::Value::Table(toml::Table::new()))
        .as_table_mut()
        .ok_or_else(|| format!("{key} must be a table"))
}

/// Where the errors of a seat given only by flags point.
const COMMAND_LINE: &str = "the command line";

impl Config {
    /// Reads and checks the configuration at `path`. A missing field is named
    /// in the error (serde's own words, "missing field `frame_bytes`"), a zero
    /// limit by its name; the pass's bytes never appear in any error.
    ///
    /// # Errors
    /// Returns a named read, schema, zero-limit or token refusal.
    pub fn load(path: &Path) -> Result<Self, ConfigError> {
        Self::load_with(Some(path), &Overrides::default())
    }

    /// Reads the seat at `path`, or `liminal seat init`'s defaults when there
    /// is none, with `overrides` written over it, then checks it exactly as
    /// [`Self::load`] does.
    ///
    /// # Errors
    /// As [`Self::load`], and a refused flag by its name.
    pub fn load_with(path: Option<&Path>, overrides: &Overrides) -> Result<Self, ConfigError> {
        let mut table = match path {
            Some(path) => {
                let text = std::fs::read_to_string(path).map_err(|e| ConfigError::Unreadable {
                    path: path.to_path_buf(),
                    message: e.to_string(),
                })?;
                toml::from_str::<toml::Table>(&text).map_err(|e| ConfigError::Invalid {
                    path: path.to_path_buf(),
                    message: e.message().to_owned(),
                })?
            }
            None => crate::seat::defaults(),
        };
        let path = path.unwrap_or_else(|| Path::new(COMMAND_LINE));
        overrides
            .apply(&mut table, path != Path::new(COMMAND_LINE))
            .map_err(|message| ConfigError::Invalid {
                path: path.to_path_buf(),
                message,
            })?;
        let file: Written =
            table
                .try_into()
                .map_err(|e: toml::de::Error| ConfigError::Invalid {
                    path: path.to_path_buf(),
                    message: e.message().to_owned(),
                })?;
        crate::agent::config::validate_optional(file.harness.as_ref(), path)?;
        let limits = file.limits.validate().map_err(|field| ConfigError::Zero {
            path: path.to_path_buf(),
            field,
        })?;
        file.listen
            .validate_bounds()
            .map_err(|message| ConfigError::Invalid {
                path: path.to_path_buf(),
                message,
            })?;
        let agent = agent_name(&file).map_err(|message| ConfigError::Invalid {
            path: path.to_path_buf(),
            message,
        })?;
        file.listen
            .validate(agent.as_deref())
            .map_err(|message| ConfigError::Invalid {
                path: path.to_path_buf(),
                message,
            })?;
        if file.server.is_empty() {
            return Err(ConfigError::Zero {
                path: path.to_path_buf(),
                field: "server",
            });
        }
        if file.channel.is_empty() {
            return Err(ConfigError::Zero {
                path: path.to_path_buf(),
                field: "channel",
            });
        }
        let credential = credential(path, &file.server, file.token_file, file.lys, file.open)?;
        Ok(Self {
            server: file.server,
            channel: file.channel,
            credential,
            limits,
            agent,
            listen: file.listen,
        })
    }
}

/// The seat's credential from its `token_file` and `[lys]` fields: exactly one
/// of them, or neither for an open seat (ACCESS-010 R3), which reaches a
/// loopback exchange only unless `[open] reach = "network"` says otherwise
/// (ACCESS-011 R1); the loopback refusal happens here, before any dial.
fn credential(
    path: &Path,
    server: &str,
    token_file: Option<PathBuf>,
    lys: Option<crate::lys::LysTable>,
    open: Option<OpenTable>,
) -> Result<Credential, ConfigError> {
    let invalid = |message: String| ConfigError::Invalid {
        path: path.to_path_buf(),
        message,
    };
    if open.is_some() && (token_file.is_some() || lys.is_some()) {
        return Err(invalid(
            "[open] names a seat with no credential; this seat has token_file or [lys], remove one"
                .to_owned(),
        ));
    }
    let reach = open.as_ref().map_or(Reach::Loopback, |open| open.reach);
    let name = open.and_then(|open| open.name);
    if let Some(name) = name.as_deref()
        && !is_open_name(name)
    {
        return Err(invalid(
            "[open] name must be 1 to 64 of a-z, 0-9, '.', '_' or '-'".to_owned(),
        ));
    }
    let token_file = match (token_file, lys) {
        (None, Some(lys)) => return Ok(Credential::Lys(lys)),
        (None, None) if reach == Reach::Network || crate::seat::names_loopback(server) => {
            return Ok(Credential::Open { name });
        }
        (None, None) => {
            return Err(invalid(format!(
                "an open seat (no token_file, no [lys]) reaches a loopback exchange only: \
                 server {server}"
            )));
        }
        (Some(token_file), None) if token_file.is_absolute() => token_file,
        (Some(token_file), None) => path
            .parent()
            .map_or_else(|| token_file.clone(), |base| base.join(&token_file)),
        _ => {
            return Err(invalid(
                "give exactly one of token_file and [lys]".to_owned(),
            ));
        }
    };
    let token = std::fs::read_to_string(&token_file).map_err(|e| ConfigError::Token {
        path: token_file.clone(),
        message: e.to_string(),
    })?;
    let token = token.trim_end_matches(['\r', '\n']);
    if token.is_empty() {
        return Err(ConfigError::Token {
            path: token_file,
            message: "token file is empty".to_owned(),
        });
    }
    Ok(Credential::Token(Token(token.to_owned())))
}

fn agent_name(file: &Written) -> Result<Option<String>, String> {
    let named = file.agent.as_deref().or_else(|| {
        file.lys
            .as_ref()
            .map(|lys| lys.agent.as_str())
            .filter(|name| !name.is_empty())
    });
    let environment = match if named.is_some() || file.lys.is_some() {
        std::env::var("LYS_AGENT")
    } else {
        Err(std::env::VarError::NotPresent)
    } {
        Ok(value) => Some(value),
        Err(std::env::VarError::NotPresent) => None,
        Err(std::env::VarError::NotUnicode(_)) => return Err("LYS_AGENT is not Unicode".to_owned()),
    };
    for candidate in [
        file.agent.as_deref(),
        file.lys
            .as_ref()
            .map(|lys| lys.agent.as_str())
            .filter(|name| !name.is_empty()),
        environment.as_deref(),
    ]
    .into_iter()
    .flatten()
    {
        if candidate.is_empty()
            || candidate.len() > file.listen.agent_bytes
            || candidate.split('.').any(str::is_empty)
            || !candidate
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
        {
            return Err(format!(
                "agent must be a plain identity of at most {} bytes",
                file.listen.agent_bytes
            ));
        }
    }
    if let (Some(named), Some(environment)) = (named, environment.as_deref())
        && named != environment
    {
        return Err(format!(
            "seat agent {named} differs from LYS_AGENT {environment}"
        ));
    }
    if let (Some(root), Some(lys)) = (file.agent.as_deref(), file.lys.as_ref())
        && !lys.agent.is_empty()
        && root != lys.agent
    {
        return Err(format!(
            "seat agent {root} differs from lys.agent {}",
            lys.agent
        ));
    }
    let name = named.map(str::to_owned).or_else(|| {
        if file.lys.is_some() {
            environment
        } else {
            None
        }
    });
    // ACCESS-013 R2: an open seat that declares a name has that station.
    // A name the open check refuses is left to it, so its words are the answer.
    Ok(name.or_else(|| {
        file.open
            .as_ref()
            .and_then(|open| open.name.clone())
            .filter(|name| is_open_name(name))
    }))
}

#[cfg(test)]
#[path = "config_tests.rs"]
mod tests;