//! Command-line parsing for `leleka`. No framework: a flag table per command, `--flag value` or `--flag=value`. use crate::{config::Ports, layout::Dirs}; use std::{collections::BTreeMap, path::PathBuf}; pub const USAGE: &str = "\ leleka - one-command deployment of the Leleka runtime USAGE leleka up [OPTIONS] preflight, fetch+verify the model, build the KAR archive, install, start, wait for \ ready leleka preflight [OPTIONS] only the host checks (exit 1 when one fails) leleka run --config FILE the foreground supervisor that systemd starts (engine + gateway + API) leleka status [OPTIONS] service state and readiness leleka reconfigure [OPTIONS] change the inference settings of the running engine without reloading the model leleka logs [OPTIONS] read the service's structured logs: --tail N (default 50), --since 15m|2h|1d|UTC \ time, --level warn, --component api|engine|supervisor|runtime-client|gateway|memory, --source \ requests|api|engine|gateway|leleka, --request ID (any 6+ characters of a request id: every line of that request, API \ and engine joined), --follow, --json (the stored JSON lines as they are) leleka report [OPTIONS] a sanitized support bundle in one small JSON file you can attach to feedback: \ versions, commit, Strata pin, profile, expert tier ON/OFF with its digest, hardware, service health, request \ statistics, the last --last N (default 50) request records and recent warnings. No prompts, no model \ output, no API key or token. It shows what it would contain and writes nothing until you add --yes; --out \ FILE|- chooses the place. Nothing is ever sent anywhere by Leleka: no telemetry upload exists leleka down [OPTIONS] stop the systemd service leleka service install|uninstall|status|start|stop [OPTIONS] keep the service running without a terminal: a Task Scheduler task at logon on \ Windows (native route), the user unit in the distribution (+ a task that keeps the VM alive) on the WSL route leleka verify [OPTIONS] hash both shards and the archive in full (in parallel), check the pinned digests, \ renew the verification stamps that let a restart skip the hashing (needs a prepared state); --quick hashes nothing: it reports the health of the installation (stamps, \ service, disk, logs) leleka seal-exec --file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG... copy the archive into a sealed memfd (--sparse-ple: only the byte ranges the serve \ path reads, as rtx5090-32g does) and run COMMAND with the descriptor; {FD} in an argument is its number (Linux; for \ A/B runs outside `leleka run`) leleka profiles [show NAME] list the memory profiles, or print one as JSON leleka version UP / PREFLIGHT OPTIONS --dry-run print the plan and the preflight, change nothing --json machine-readable plan / summary on stdout --profile auto|NAME|FILE memory profile (default auto: chosen from the GPU) --gpu N CUDA device ordinal (default 0) --assets DIR model volume: shards, KAR archive, MTP pack, tokenizer [$LELEKA_ASSETS] --state-dir DIR configs, tokens, logs, status [$LELEKA_STATE] --prefix DIR install prefix (bin/, lib/cublas/) [$LELEKA_PREFIX] --bin-src DIR where to take the six binaries from (default: the directory of this binary) --mode auto|system|user|foreground|none --foreground same as --mode foreground (WSL without systemd, containers, terminals) --api-port N API port (default 8081) --api-bind IP API listen address (default 127.0.0.1; 0.0.0.0 only inside a container whose port is published to 127.0.0.1 or tunnelled; the key is the only protection, no TLS) --engine-port N engine gRPC port (default 18766) --daemon-port N gateway port (default 18080) --preset dedicated|workstation dedicated (default) takes the whole host; workstation leaves cores, RAM and VRAM for Docker, agents and the IDE (env LELEKA_PRESET) --gpu-budget-gib N override the profile's GPU memory budget --context-tokens N override the profile's context ceiling --no-fetch never download or build; require the model files to exist --reverify ignore the verification stamps and hash everything again --trust-archive accept an existing archive of the pinned length + its provenance file without the strict re-derivation (hours-scale); the engine still checks its SHA-256 and every CRC against the pinned digest at each load --mtp-pack PATH import the MTP pack (directory or .tar/.tar.gz of data/mtp-rt) into the assets --expert-profile-file PATH install this copy of the upstream data/expert-profile.bin (the ranked VRAM expert tier; sha256 8f59b4aa...388975baf is checked) instead of the table embedded in this binary. Without it `up` installs the embedded table (works offline), downloads it from its pinned upstream commit only if that fails, and fails closed on any other digest --no-expert-tier run without the ranked VRAM expert tier (much slower decode); status and verify say OFF --cublas-dir DIR use this CUDA 12 cuBLAS directory instead of searching / downloading --no-install-cublas fail instead of downloading cuBLAS 12.9.1.4 --timeout-s N wait this long for readiness (default 3600) --kar-fd N an already sealed KAR memfd inherited from the parent process: not copied again, its RAM is not required (foreground / --mode none only) --service-user NAME system unit only: account the service runs as (default leleka, created if missing) RECONFIGURE OPTIONS (any of them; the call waits for the request in flight, the engine reopens its serve stack in a \ few seconds, the weights stay loaded; a refused change keeps the previous settings; --kv-resident is fixed per process and needs `leleka up`) --context-tokens N tokens of context (1..262144) --prefill-capacity N prefill chunk: 256 512 1024 2048 3072 4096 6144 8192 --kv-resident N only the value in force is accepted (the K/V window is fixed per process; restart to \ change it) --prefix-cache-mib auto|off|N host-RAM budget of the cross-session prefix cache --prefix-cache-tail off|prompt|reply request-end checkpoints --prefix-cache-block N tokens per prefix block (multiple of 256; 0 = the prefill chunk) --prefix-retention-min N minutes an idle cached session is kept (0 = no limit) --cpu-workers N CPU expert workers (1..15) --spec-min-p P draft-probability floor (0..1) --gpu-budget-gib N VRAM budget of the engine (1..1024). Fixed when the CUDA context is created: the \ supervisor restarts the engine process (the model loads again, minutes), the gateway and the API keep their \ ports --preset dedicated|workstation resource preset (same restart); refused when the host cannot hold it --persist keep the change across restarts of the service (writes leleka.json) --assets/--state-dir/--prefix/--api-port/--json as for `up`; `leleka status` prints the settings in force WINDOWS leleka.exe runs the engine in one of two ways (docs/windows.md): --wsl / --native route for up, preflight, verify, status, reconfigure, down: `--wsl` (the default for \ `up`) runs the Linux `leleka` inside WSL2 through wsl.exe and talks to it over loopback HTTP; `--native` \ runs engine, gateway and API as Windows processes (the model volume must already be on a Windows disk) --wsl-distro NAME WSL2 distribution to use (default: the default one that is not Docker's) \ [$LELEKA_WSL_DISTRO] --wsl-bin PATH the Linux `leleka` inside the distribution (default: searched in the usual places) leleka doctor what this Windows machine offers: GPU, RAM, .wslconfig advice, WSL distributions, the \ Linux leleka Paths for the WSL route may be Linux paths (/home/me/leleka), \\\\wsl.localhost\\Ubuntu\\... paths or Windows \ paths (C:\\...; they become /mnt/c/..., which is far too slow for the model, so --assets is refused there). Native defaults live in \ %LOCALAPPDATA%\\leleka. LOGS Every process writes one JSON object per line to STATE/logs/{leleka,engine,gateway,api,requests}.log (timestamp \ in UTC with milliseconds, level, component, event, flat fields); a terminal gets the same event as key=value text. `requests.log` has one \ record per generation request: request id and session tag (a hash of the client's session header), dialect, model, profile, prompt / \ cached / output tokens, queue wait, time to first token, prefill and decode tok/s, finish reason, error class, whether the engine was \ lost meanwhile, the GPU clock, temperature and throttle reasons. The same id is in the `x-leleka-request-id` response header and in the \ engine's own line (tokens per speculative round, expert-tier share served from VRAM / PCIe / CPU). Prompts and answers are never \ logged; the API key and tokens are scrubbed from every line. Files are size-capped and rotated by the supervisor (leleka.json `logs`), \ and a repeating event is sampled (burst, then one line per 10 s with a `suppressed` count). `/metrics?format=prometheus` exposes the \ same figures as counters, histograms and gauges. LELEKA_LOG_LEVEL=debug|info|warn|error, LELEKA_LOG_FORMAT=json|text|legacy, LELEKA_LOG_DEBUG=1 (debug level + the \ length of redacted text) are read by every process. `leleka run` starts its children with JSON; a binary started by hand writes key=value \ text on a terminal and, into a file, the plain lines that the lab scripts (scripts/e2e) parse (also LELEKA_LOG_LEGACY=1). ENVIRONMENT HF_TOKEN optional Hugging Face token for the model download (sent only to huggingface.co) "; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ModeChoice { Auto, System, User, Foreground, None, } #[derive(Clone, Debug)] pub struct UpOptions { pub dry_run: bool, pub json: bool, pub profile: Option, pub gpu: u32, pub dirs: Dirs, pub bin_src: Option, pub mode: ModeChoice, /// Resource preset (`--preset`, `LELEKA_PRESET`): how much of the host the engine may take. pub preset: crate::resources::Preset, pub ports: Ports, pub gpu_budget_gib: Option, pub context_tokens: Option, pub fetch: bool, pub reverify: bool, /// `leleka verify --quick`: report the health of the installation from the stamps and the status file, hash /// nothing. pub quick: bool, /// Accept an existing archive of the pinned length without the strict F32 re-derivation. pub trust_archive: bool, pub mtp_pack: Option, /// `--expert-profile-file`: install this file as the expert profile instead of downloading it. pub expert_profile_file: Option, /// `--no-expert-tier`: the explicit opt-out of the ranked VRAM expert tier. pub no_expert_tier: bool, pub cublas_dir: Option, pub install_cublas: bool, pub timeout_s: u64, /// System unit only: the account the service runs as (created when missing). Default `leleka`. pub service_user: Option, /// An already sealed archive descriptor inherited from the parent (foreground / prepare-only runs). pub kar_fd: Option, } /// What `leleka reconfigure` was asked to change. #[derive(Clone, Debug, Default, PartialEq)] pub struct ReconfigureArgs { /// Runtime settings (the members of `POST /v1/reconfigure`): the engine reopens its serve stack. pub settings: serde_json::Map, /// New VRAM budget: needs a new engine process. pub gpu_budget_gib: Option, /// New resource preset: needs a new engine process. pub preset: Option, /// Keep the change across restarts of the service (`leleka.json`). pub persist: bool, } /// `leleka service ACTION`: keep the service running without a terminal (`service.rs`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ServiceAction { Install, Uninstall, Status, Start, Stop, /// WSL route only: the logon task runs this to start the unit and keep the WSL2 VM alive. Hold, } #[derive(Debug)] pub enum Command { Service(ServiceAction, UpOptions), Up(UpOptions), Preflight(UpOptions), Run { config: PathBuf, kar_fd: Option, }, ExecInherit(Vec), /// `leleka seal-exec --file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG...` (Linux). SealExec(Vec), /// `leleka seal-probe FILE` (not in `--help`): seal FILE into a memfd with the code `leleka run` uses for the /// archive and compare the memfd with the file byte for byte (SHA-256 of both). A measurement and identity tool for /// the cold-load work. SealProbe(PathBuf), Status(UpOptions), Down(UpOptions), /// The options locate the running service; the arguments are what to change. Reconfigure(UpOptions, ReconfigureArgs), Verify(UpOptions), /// `leleka logs`: the options locate the state directory. Logs(UpOptions, crate::logview::LogsArgs), /// `leleka report`. Report(UpOptions, crate::logview::ReportArgs), Profiles(Option), Version, Help, } type Flags = BTreeMap>; const UP_FLAGS: &[(&str, bool)] = &[ ("--dry-run", false), ("--json", false), ("--profile", true), ("--gpu", true), ("--assets", true), ("--state-dir", true), ("--prefix", true), ("--bin-src", true), ("--mode", true), ("--preset", true), ("--foreground", false), ("--api-port", true), ("--api-bind", true), ("--engine-port", true), ("--daemon-port", true), ("--gpu-budget-gib", true), ("--context-tokens", true), ("--no-fetch", false), ("--reverify", false), ("--quick", false), ("--trust-archive", false), ("--mtp-pack", true), ("--expert-profile-file", true), ("--no-expert-tier", false), ("--cublas-dir", true), ("--no-install-cublas", false), ("--timeout-s", true), ("--service-user", true), ("--kar-fd", true), ]; /// Environment access is injected so that parsing is testable. pub struct Environment<'a> { pub root: bool, pub home: Option, pub var: &'a dyn Fn(&str) -> Option, } /// The settings flags of `leleka reconfigure` (member of the settings document, takes a value). const RECONFIGURE_FLAGS: &[(&str, &str)] = &[ ("--context-tokens", "context_tokens"), ("--prefill-capacity", "prefill_capacity"), ("--kv-resident", "kv_resident"), ("--prefix-cache-mib", "prefix_cache_mib"), ("--prefix-cache-tail", "prefix_cache_tail"), ("--prefix-cache-block", "prefix_cache_block"), ("--prefix-retention-min", "prefix_retention_min"), ("--cpu-workers", "cpu_workers"), ("--spec-min-p", "spec_min_p"), ]; #[cfg(test)] mod tests; mod dispatch; mod flag_parsing; mod subcommands; pub use dispatch::parse; use flag_parsing::{number, parse_flags, ranged, text, up_options}; pub use subcommands::split_reconfigure; #[cfg(test)] pub(crate) use subcommands::tests_options; use subcommands::{logs_command, reconfigure_command, report_command};