Skip to main content

hyprstream_core/cli/commands/
mod.rs

1pub mod chat;
2pub mod config;
3pub mod flight;
4pub mod git;
5pub mod policy;
6pub mod training;
7pub mod trust;
8pub mod user;
9pub mod worker;
10
11pub use flight::FlightArgs;
12pub use git::{GitAction, GitCommand};
13pub use policy::{PolicyCommand, RoleCommand, TokenCommand};
14pub use training::{TrainingAction, TrainingCommand};
15pub use trust::{
16    DelegateRegistrySignerArgs, EnrollServiceKeyArgs, InstallDeploymentTrustArgs,
17    MintAnchorCapsuleArgs, MintDeploymentCaArgs, MintRegistryJwtArgs, RotateAuthorityArgs,
18    TrustCommand, VerifyDeploymentArgs,
19};
20pub use user::{UserCommand, UserKeysCommand, UserKeysImportFormat};
21pub use worker::{ImageCommand, WorkerAction};
22
23use clap::{Subcommand, ValueEnum};
24
25use hyprstream_rpc_std::model_client::KVQuantType;
26
27/// KV cache quantization type for CLI argument parsing.
28///
29/// Thin wrapper for `clap::ValueEnum` (can't derive on foreign types).
30/// Converts to the generated `KVQuantType` via `From`.
31#[derive(
32    Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum, serde::Serialize, serde::Deserialize,
33)]
34#[serde(rename_all = "lowercase")]
35pub enum KVQuantArg {
36    /// No quantization (full precision FP16/BF16)
37    #[default]
38    None,
39    /// 8-bit integer quantization (~50% memory savings)
40    Int8,
41    /// 4-bit NormalFloat quantization (~75% memory savings)
42    Nf4,
43    /// 4-bit FloatingPoint quantization (~75% memory savings)
44    Fp4,
45}
46
47impl From<KVQuantArg> for KVQuantType {
48    fn from(arg: KVQuantArg) -> Self {
49        match arg {
50            KVQuantArg::None => KVQuantType::None,
51            KVQuantArg::Int8 => KVQuantType::Int8,
52            KVQuantArg::Nf4 => KVQuantType::Nf4,
53            KVQuantArg::Fp4 => KVQuantType::Fp4,
54        }
55    }
56}
57
58/// Overall execution mode for the hyprstream CLI and services
59///
60/// This determines how services are spawned and managed:
61/// - **IpcStandalone**: Multiple processes spawned directly, ipc:// ZMQ transport (default)
62/// - **IpcSystemd**: Multiple systemd services with socket activation, ipc:// ZMQ transport
63#[derive(
64    Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum, serde::Serialize, serde::Deserialize,
65)]
66#[serde(rename_all = "kebab-case")]
67pub enum ExecutionMode {
68    /// Standalone mode with forked processes (default for desktop/server/containers)
69    /// Services spawned via ProcessSpawner with StandaloneBackend
70    #[default]
71    IpcStandalone,
72
73    /// Systemd mode with socket-activated services
74    /// Services managed by systemd, started on-demand via socket activation
75    IpcSystemd,
76}
77
78impl ExecutionMode {
79    /// Detect best execution mode based on system capabilities
80    ///
81    /// Returns:
82    /// - `IpcSystemd` if systemd is available
83    /// - `IpcStandalone` otherwise (default for desktop/server/containers)
84    pub fn detect() -> Self {
85        #[cfg(feature = "systemd")]
86        {
87            if hyprstream_rpc::has_systemd() {
88                return ExecutionMode::IpcSystemd;
89            }
90        }
91        // Default to standalone IPC mode (services as separate processes)
92        ExecutionMode::IpcStandalone
93    }
94
95    /// Get the EndpointMode for this execution mode
96    pub fn endpoint_mode(&self) -> hyprstream_rpc::registry::EndpointMode {
97        hyprstream_rpc::registry::EndpointMode::Ipc
98    }
99
100    /// Whether this mode uses IPC sockets
101    pub fn uses_ipc(&self) -> bool {
102        true
103    }
104
105    /// Whether this mode uses systemd
106    pub fn uses_systemd(&self) -> bool {
107        matches!(self, ExecutionMode::IpcSystemd)
108    }
109}
110
111impl std::fmt::Display for ExecutionMode {
112    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113        match self {
114            ExecutionMode::IpcStandalone => write!(f, "ipc-standalone"),
115            ExecutionMode::IpcSystemd => write!(f, "ipc-systemd"),
116        }
117    }
118}
119
120/// TUI display server actions
121#[derive(Subcommand)]
122pub enum TuiAction {
123    /// Attach to an existing session (or create new if none exist)
124    Attach {
125        /// Session ID to attach to (0 = most recent)
126        #[arg(default_value = "0")]
127        session: u32,
128    },
129
130    /// Create a new session
131    New,
132
133    /// List active sessions
134    List,
135
136    /// Detach from current session
137    Detach,
138
139    /// Play an asciicast v2 recording in a TUI pane
140    Play {
141        /// Path to the .cast file
142        cast_file: std::path::PathBuf,
143
144        /// Session ID to play in (0 = most recent)
145        #[arg(long, default_value = "0")]
146        session: u32,
147
148        /// Loop playback continuously instead of exiting when finished
149        #[arg(long, short = 'l')]
150        loop_playback: bool,
151    },
152
153    /// Run hyprstream as an interactive shell client embedded in a TUI pane
154    ///
155    /// Renders the full ShellClient chrome (status bar, window tabs, F-key legend)
156    /// into a TuiService pane. Useful for Playwright/WebTransport testing.
157    Shell {
158        /// Session ID (0 = most recent)
159        #[arg(long, default_value = "0")]
160        session: u32,
161    },
162}
163
164/// Service management actions
165#[derive(Subcommand)]
166pub enum ServiceAction {
167    /// Install, repair, and update hyprstream services
168    ///
169    /// Idempotent setup: bootstraps directories, registry, policy files, and
170    /// signing key; installs command alias and systemd units.
171    /// With --start: also stops and restarts services to pick up changes.
172    /// With --enable: registers units for autostart at boot (systemctl enable).
173    /// With --system: installs to /etc/systemd/system/ (requires root).
174    Install {
175        /// Operate on specific services only (comma-separated)
176        #[arg(long, short = 's', value_delimiter = ',')]
177        services: Option<Vec<String>>,
178
179        /// Stop and start services after installing/updating units
180        #[arg(long)]
181        start: bool,
182
183        /// Register services for autostart at boot (systemctl enable)
184        #[arg(long)]
185        enable: bool,
186
187        /// Install as system service in /etc/systemd/system/ (requires root)
188        #[arg(long)]
189        system: bool,
190
191        /// Install as a session-scoped user service via the D-Bus session bus.
192        ///
193        /// Use only for services tied to an active login session (e.g. TUI
194        /// multiplexer).  Not suitable for long-lived headless daemons.
195        #[arg(long, conflicts_with = "system")]
196        systemd_session: bool,
197
198        /// Show verbose output for repair checks
199        #[arg(long, short = 'v')]
200        verbose: bool,
201    },
202
203    /// Stop and remove systemd units
204    Uninstall {
205        /// Operate on specific services only
206        #[arg(long, short = 's', value_delimiter = ',')]
207        services: Option<Vec<String>>,
208    },
209
210    /// Start services (via systemd or direct spawn)
211    ///
212    /// Without --foreground: Uses systemd if available, else spawns background process.
213    /// With --foreground: Runs service in foreground (used by systemd ExecStart).
214    /// With --daemon: Bypasses systemd and spawns process directly.
215    Start {
216        /// Service name (all services if omitted)
217        name: Option<String>,
218
219        /// Run in foreground instead of background
220        ///
221        /// Used by systemd unit files (ExecStart) to run the service process.
222        /// When running manually, keeps the service attached to the terminal.
223        #[arg(long, short = 'f', visible_alias = "fg")]
224        foreground: bool,
225
226        /// Force daemon mode (bypass systemd, spawn process directly)
227        ///
228        /// Use this to run services as standalone daemons even when systemd is available.
229        #[arg(long, short = 'd')]
230        daemon: bool,
231
232        /// Run all services in a single foreground process
233        ///
234        /// Starts every configured service in-process without systemd.
235        /// Useful for containers, testing, and environments without a
236        /// systemd user session.
237        #[arg(long, conflicts_with_all = ["foreground", "daemon", "services"])]
238        standalone: bool,
239
240        /// Use IPC sockets for distributed mode
241        #[arg(long)]
242        ipc: bool,
243
244        /// Comma-separated list of services to start in multi-service foreground mode
245        ///
246        /// When used with --foreground, starts all listed services in a single process.
247        /// Example: --services registry,policy,model,streams,event
248        #[arg(long, value_delimiter = ',')]
249        services: Option<Vec<String>>,
250
251        /// Bind address for QUIC/WebTransport server (e.g., 127.0.0.1:4433)
252        ///
253        /// Enables WebTransport access to services via HTTP/3. Use port 0 for random port.
254        #[arg(long)]
255        quic_bind: Option<String>,
256
257        /// Print the SHA-256 hash of the QUIC TLS certificate and include it in startup output
258        ///
259        /// The hash is suitable for use in browser's serverCertificateHashes WebTransport option.
260        #[arg(long)]
261        print_cert_hash: bool,
262    },
263
264    /// Stop services
265    Stop {
266        /// Service name (all services if omitted)
267        name: Option<String>,
268    },
269
270    /// Show service status
271    ///
272    /// Displays running services, unit file locations, and execution mode.
273    Status {
274        /// Show verbose output including unit file contents
275        #[arg(long, short = 'v')]
276        verbose: bool,
277    },
278
279    /// Diagnose the hyprstream installation
280    ///
281    /// Runs all setup checks (directories, registry, policy, signing keys,
282    /// TLS, bootstrap-pubkeys hybrid posture) and reports status without
283    /// starting services. Dispatches before the hybrid gate so it works on
284    /// a partially-broken install.
285    Repair {
286        /// Show verbose output for each check
287        #[arg(long, short = 'v')]
288        verbose: bool,
289    },
290
291    /// Generate or load a service's signing key and write its public sidecars
292    ///
293    /// Runs the same key loader the service itself uses (with
294    /// `resolve_service_signing_key` semantics, so `policy` resolves to the
295    /// flat node/CA key), then ensures the public sidecars exist next to the
296    /// seed: `signing-key.pub` (32-byte Ed25519 verifying key, 0644) and
297    /// `service-pubkey.hybrid` (1984-byte hybrid bootstrap entry, 0644).
298    ///
299    /// Idempotent: an existing key is loaded, never rotated, and up-to-date
300    /// sidecars are left untouched. Does not start any services — intended
301    /// for provisioning/keygen units that run before service startup.
302    EnsureKey {
303        /// Service name (e.g. registry, discovery, policy)
304        name: String,
305    },
306
307    /// Validate retained bootstrap identities and reconcile their enrollment and JWTs
308    ///
309    /// Runs offline before service startup. Never generates or rotates keys,
310    /// changes the bootstrap key set, or replaces a disagreeing manifest.
311    ReconcileEnrollment,
312
313    /// Initialize or validate the node CA without provisioning a service roster
314    EnsureNodeAuthority,
315
316    /// Persist built-in policy templates directly into the configured policy store
317    ///
318    /// This offline provisioning command is intended for boot orchestration before
319    /// Policy or Registry starts. It does not contact a service or load credentials.
320    ProvisionPolicyTemplates {
321        /// Built-in template name; repeat for each template to provision
322        #[arg(long, required = true, action = clap::ArgAction::Append)]
323        template: Vec<String>,
324    },
325
326    /// Read back one local canary through the enrolled Registry identity.
327    /// Requires query authorization; never registers or retries. Uses a fresh
328    /// outbound Iroh carrier identity; N0 can publish transient reach for it.
329    ReadbackLocalCanary {
330        /// Existing canonical direct child of the configured Registry base.
331        #[arg(long)]
332        path: std::path::PathBuf,
333        /// Full Git HEAD OID reviewed before readback.
334        #[arg(long)]
335        expected_head: String,
336    },
337
338    /// Register one existing local canary using the enrolled Registry identity.
339    /// Uses a fresh outbound Iroh carrier; never retries an ambiguous write.
340    /// N0 may publish transient reach for that carrier.
341    RegisterLocalCanary {
342        /// Existing canonical direct child of the configured Registry base.
343        #[arg(long)]
344        path: std::path::PathBuf,
345        /// Full Git HEAD OID reviewed before registration.
346        #[arg(long)]
347        expected_head: String,
348    },
349}