mobius-gateway 0.16.8

Headless authenticated gateway for möbius frontends
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
use clap::{ArgAction, Args, Parser, Subcommand};
use mobius::backend::model::provider::HostedWebSearch;

use super::*;

/// Parsed `mobius-gateway` command line.
#[derive(Debug, Parser)]
#[command(
    name = "mobius-gateway",
    version,
    propagate_version = true,
    about = "Run and configure a möbius gateway"
)]
pub struct GatewayCli {
    /// Directory containing gateway configuration and runtime state.
    #[arg(long, global = true, value_name = "PATH")]
    state_dir: Option<PathBuf>,

    #[command(subcommand)]
    command: Option<GatewaySubcommand>,
}

/// Frontend selected by a parsed gateway command line.
#[derive(Debug)]
pub enum FrontendCommand {
    /// Interactive Cloudflare initialization.
    Init(PathBuf),
    /// Gateway administration dashboard.
    Dashboard(PathBuf),
    /// Interactive provider setup.
    Provider(PathBuf),
}

#[derive(Debug, Subcommand)]
enum GatewaySubcommand {
    /// Open the provider setup interface.
    Provider,
    /// Initialize gateway state.
    Init(InitArgs),
    /// Initialize a direct loopback gateway for machine use.
    Bootstrap,
    /// Restore the default Bot configuration.
    ResetBotDefaults,
    /// Enable or disable the gateway-owned desktop while the gateway is stopped.
    SetDesktop {
        /// Use true to enable the gateway-owned desktop or false to disable it.
        #[arg(long, action = ArgAction::Set, hide_possible_values = true)]
        enabled: bool,
    },
    /// Issue a one-time pairing code as JSON.
    PairingCode {
        /// Emit machine-readable JSON.
        #[arg(long, required = true)]
        json: bool,
    },
    /// Register a model provider non-interactively.
    RegisterProvider(RegisterProviderArgs),
    /// Revoke a stored credential and cancel operations that use it.
    ClearProviderCredential {
        #[arg(long)]
        instance: String,
    },
    /// Connect this installation to a running gateway.
    Connect(ConnectArgs),
    /// Run the gateway server.
    Serve(ServeArgs),
    #[command(name = "__serve", hide = true)]
    ServeChild,
    /// Stop a background gateway.
    Exit,
}

#[derive(Debug, Args)]
struct InitArgs {
    /// Address on which the gateway listens.
    #[arg(long, value_name = "ADDR")]
    listen: Option<SocketAddr>,

    /// PEM certificate for a direct TLS listener.
    #[arg(
        long = "tls-cert",
        value_name = "PATH",
        requires = "private_key",
        conflicts_with_all = ["cloudflare_hostname", "cloudflare_token_file"]
    )]
    certificate: Option<PathBuf>,

    /// PEM private key for a direct TLS listener.
    #[arg(
        long = "tls-key",
        value_name = "PATH",
        requires = "certificate",
        conflicts_with_all = ["cloudflare_hostname", "cloudflare_token_file"]
    )]
    private_key: Option<PathBuf>,

    /// Public hostname served by a named Cloudflare tunnel.
    #[arg(
        long,
        value_name = "HOST",
        requires = "cloudflare_token_file",
        conflicts_with_all = ["certificate", "private_key"]
    )]
    cloudflare_hostname: Option<String>,

    /// Owner-only file containing the named Cloudflare tunnel token.
    #[arg(
        long,
        value_name = "PATH",
        requires = "cloudflare_hostname",
        conflicts_with_all = ["certificate", "private_key"]
    )]
    cloudflare_token_file: Option<PathBuf>,
}

impl InitArgs {
    fn is_interactive(&self) -> bool {
        self.listen.is_none()
            && self.certificate.is_none()
            && self.private_key.is_none()
            && self.cloudflare_hostname.is_none()
            && self.cloudflare_token_file.is_none()
    }
}

#[derive(Debug, Args)]
struct RegisterProviderArgs {
    /// Native Responses processing tier; omitted to use the endpoint default.
    #[arg(long, value_name = "TIER")]
    service_tier: Option<String>,
    /// Provider identifier.
    #[arg(long, value_name = "ID")]
    provider: String,

    /// Stable identifier for this configured provider instance.
    #[arg(long, value_name = "ID")]
    instance: Option<String>,

    /// User-facing provider label.
    #[arg(long, value_name = "TEXT")]
    label: Option<String>,

    /// Provider model identifier.
    #[arg(long, value_name = "ID")]
    model: String,

    /// Comma-separated reasoning effort identifiers.
    #[arg(
        long,
        value_name = "CSV",
        value_delimiter = ',',
        action = ArgAction::Set
    )]
    reasoning_efforts: Vec<String>,

    /// Hosted web-search mode: off, cached, or live.
    #[arg(long, value_name = "MODE", default_value = "off")]
    web_search: HostedWebSearch,

    /// Provider API base URL override.
    #[arg(long, value_name = "URL")]
    base_url: Option<String>,

    /// Configure an endpoint that does not require a credential.
    #[arg(long, conflicts_with = "credential_stdin")]
    credentialless: bool,

    /// Read the provider credential from standard input.
    #[arg(long)]
    credential_stdin: bool,

    /// Expire the piped credential at this Unix timestamp (seconds).
    #[arg(long, value_name = "TIMESTAMP", requires = "credential_stdin")]
    credential_expires_at: Option<u64>,
}

#[derive(Debug, Args)]
struct ConnectArgs {
    /// Public or local gateway endpoint.
    #[arg(long, value_name = "ENDPOINT")]
    endpoint: Option<Endpoint>,
}

#[derive(Debug, Args)]
struct ServeArgs {
    /// Start the gateway as a background process.
    #[arg(long)]
    background: bool,

    /// Hold work and native connections until authenticated lifecycle activation.
    #[arg(long, conflicts_with = "background")]
    start_quiesced: bool,
}

#[derive(Debug)]
pub(super) enum Command {
    Init(InitOptions),
    Bootstrap {
        state_dir: PathBuf,
    },
    ResetBotDefaults {
        state_dir: PathBuf,
    },
    SetDesktop {
        state_dir: PathBuf,
        enabled: bool,
    },
    PairingCode {
        state_dir: PathBuf,
    },
    RegisterProvider(RegisterProviderOptions),
    ClearProviderCredential {
        state_dir: PathBuf,
        instance: String,
    },
    Connect(ConnectOptions),
    Serve {
        state_dir: PathBuf,
        background: bool,
        start_quiesced: bool,
    },
    ServeChild {
        state_dir: PathBuf,
    },
    Exit {
        state_dir: PathBuf,
    },
}

#[derive(Debug)]
pub(super) struct InitOptions {
    pub(super) state_dir: PathBuf,
    pub(super) listen: SocketAddr,
    pub(super) tls: Option<TlsConfig>,
    pub(super) cloudflare: Option<CloudflareInit>,
}

pub(super) enum CloudflareInit {
    Quick,
    Named { hostname: String, token: String },
}

impl std::fmt::Debug for CloudflareInit {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Quick => formatter.write_str("CloudflareInit::Quick"),
            Self::Named { hostname, .. } => formatter
                .debug_struct("CloudflareInit::Named")
                .field("hostname", hostname)
                .field("token", &"[redacted]")
                .finish(),
        }
    }
}

#[derive(Debug)]
pub(super) struct ConnectOptions {
    pub(super) state_dir: PathBuf,
    pub(super) endpoint: Option<Endpoint>,
}

#[derive(Debug)]
pub(super) struct RegisterProviderOptions {
    pub(super) service_tier: Option<String>,
    pub(super) state_dir: PathBuf,
    pub(super) provider: String,
    pub(super) instance: Option<String>,
    pub(super) label: Option<String>,
    pub(super) model: String,
    pub(super) reasoning_efforts: Vec<String>,
    pub(super) web_search: HostedWebSearch,
    pub(super) base_url: Option<String>,
    pub(super) credentialless: bool,
    pub(super) credential_stdin: bool,
    pub(super) credential_expires_at: Option<u64>,
}

impl GatewayCli {
    /// Returns the interactive frontend selected by this command line, if any.
    /// # Errors
    ///
    /// Returns an error if validation or an operation required by this function fails.
    pub fn frontend_command(&self) -> Result<Option<FrontendCommand>> {
        let command = match &self.command {
            None => FrontendCommand::Dashboard(self.resolved_state_dir()?),
            Some(GatewaySubcommand::Provider) => {
                FrontendCommand::Provider(self.resolved_state_dir()?)
            }
            Some(GatewaySubcommand::Init(arguments)) if arguments.is_interactive() => {
                FrontendCommand::Init(self.resolved_state_dir()?)
            }
            _ => return Ok(None),
        };
        Ok(Some(command))
    }

    fn resolved_state_dir(&self) -> Result<PathBuf> {
        self.state_dir.clone().map_or_else(state_dir, Ok)
    }

    pub(super) fn into_command(self) -> Result<Command> {
        let state_dir = self.state_dir.map_or_else(state_dir, Ok)?;
        match self.command {
            Some(GatewaySubcommand::Init(arguments)) => {
                parse_init(state_dir, arguments).map(Command::Init)
            }
            Some(GatewaySubcommand::Bootstrap) => Ok(Command::Bootstrap { state_dir }),
            Some(GatewaySubcommand::ResetBotDefaults) => {
                Ok(Command::ResetBotDefaults { state_dir })
            }
            Some(GatewaySubcommand::SetDesktop { enabled }) => {
                Ok(Command::SetDesktop { state_dir, enabled })
            }
            Some(GatewaySubcommand::PairingCode { json: _ }) => {
                Ok(Command::PairingCode { state_dir })
            }
            Some(GatewaySubcommand::ClearProviderCredential { instance }) => {
                Ok(Command::ClearProviderCredential {
                    state_dir,
                    instance,
                })
            }
            Some(GatewaySubcommand::RegisterProvider(arguments)) => {
                Ok(Command::RegisterProvider(RegisterProviderOptions {
                    service_tier: arguments.service_tier,
                    state_dir,
                    provider: arguments.provider,
                    instance: arguments.instance,
                    label: arguments.label,
                    model: arguments.model,
                    reasoning_efforts: arguments.reasoning_efforts,
                    web_search: arguments.web_search,
                    base_url: arguments.base_url,
                    credentialless: arguments.credentialless,
                    credential_stdin: arguments.credential_stdin,
                    credential_expires_at: arguments.credential_expires_at,
                }))
            }
            Some(GatewaySubcommand::Connect(arguments)) => Ok(Command::Connect(ConnectOptions {
                state_dir,
                endpoint: arguments.endpoint,
            })),
            Some(GatewaySubcommand::Serve(arguments)) => Ok(Command::Serve {
                state_dir,
                background: arguments.background,
                start_quiesced: arguments.start_quiesced,
            }),
            Some(GatewaySubcommand::ServeChild) => Ok(Command::ServeChild { state_dir }),
            Some(GatewaySubcommand::Exit) => Ok(Command::Exit { state_dir }),
            None | Some(GatewaySubcommand::Provider) => Err(Error::Config(
                "an executable gateway command is required".into(),
            )),
        }
    }
}

pub(super) fn parse_cli(arguments: Vec<OsString>) -> std::result::Result<GatewayCli, clap::Error> {
    GatewayCli::try_parse_from(std::iter::once(OsString::from("mobius-gateway")).chain(arguments))
}

#[cfg(test)]
pub(super) fn parse(arguments: Vec<OsString>) -> Result<Command> {
    parse_cli(arguments)
        .map_err(|error| Error::Config(error.to_string()))?
        .into_command()
}

fn parse_init(state_dir: PathBuf, arguments: InitArgs) -> Result<InitOptions> {
    let tls = match (arguments.certificate, arguments.private_key) {
        (Some(certificate), Some(private_key)) => Some(TlsConfig {
            certificate: std::fs::canonicalize(certificate)?,
            private_key: std::fs::canonicalize(private_key)?,
        }),
        (None, None) => None,
        _ => {
            return Err(Error::Config(
                "--tls-cert and --tls-key must be supplied together".into(),
            ));
        }
    };
    let cloudflare = match (
        arguments.cloudflare_hostname,
        arguments.cloudflare_token_file,
    ) {
        (Some(hostname), Some(path)) => Some(CloudflareInit::Named {
            hostname,
            token: load_cloudflare_token(&path)?,
        }),
        (None, None) => None,
        _ => {
            return Err(Error::Config(
                "--cloudflare-hostname and --cloudflare-token-file must be supplied together"
                    .into(),
            ));
        }
    };
    Ok(InitOptions {
        state_dir,
        listen: arguments.listen.unwrap_or(DEFAULT_LISTEN),
        tls,
        cloudflare,
    })
}