weirdnet-backends 0.4.8

Weirdnet model-node wrapper: llama.cpp server, vLLM and MLX-LM adapters, a local supervisor (swap groups, idle unload, crash backoff, drain), SSE decoding, raw infer/2 serving, and the /weirdnet-backends/node/1 protocol with signed capability records.
Documentation
# weirdnet-backends

The Weirdnet model-node wrapper. A model node runs models and takes requests, like a llama.cpp,
vLLM or MLX-LM server (it can even be one: a stock server it only wraps). This crate starts and stops
the engines and serves them to inference nodes; what to load is always the caller's decision.

- `EngineConfig` / `ModelLaunch`: how `llama-server`, `vllm serve` and MLX-LM's
  `mlx_lm.server` are launched (loopback only, random port, per-process API key in the
  environment, or checked by a proxy for MLX-LM) and probed. Ready means the server on the
  port takes the launch's key and lists its model; a port taken by another process before the
  engine binds it is retried on a new one. `Wrap` attaches to a stock
  OpenAI-compatible server on loopback without owning it.
- `Capabilities`: what each model takes (chat, embeddings, images, audio), in `ModelStatus`
  and so in capability records, so routing keeps image, audio and embedding requests off
  models that can't serve them. `ModelLaunch::capabilities` derives it: embedding models only
  embed; llama.cpp models with a multimodal projector (`--mmproj`) take images and audio;
  vLLM and MLX-LM models are text only.
  `Capabilities::limits` carries the model's media and request limits (a
  [weirdnet-agent]https://crates.io/crates/weirdnet-agent `MediaLimits`: images per request,
  image token cost and edge, audio length and token rate, request bytes), each absent when
  unknown: the operator sets them with `ModelLaunch::with_limits`, `intersect` keeps the
  stricter ones, and `Capabilities::apply_to` / `ModelStatus::apply_to` fill a catalog/1 entry's
  inputs, limits and context window.
- `Supervisor`: load and unload with draining, **swap groups** (loading one model of a group
  unloads the others), **idle unload**, crash restarts with exponential backoff and crash-loop
  detection, `SupervisorEvent`s, per-model logs; chat, completion and embedding forwarding.
  `Supervisor::reserve(holder)` holds the node's GPU for one job (a training run, say): it
  stops every engine and starts none until `release(holder)`.
  `add_model` and `remove_model` change the served models at run time, without a restart.
- `ChunkDecoder` / `ToolCalls`: OpenAI server-sent events decoded into `Chunk`s (text,
  reasoning, tool-call fragments, finish reason and usage).
- `ModelHost`: a [`weirdnet-agent`]https://crates.io/crates/weirdnet-agent 0.5 `InferHost`
  serving **raw infer/2** from the supervisor's models. Cancel aborts the engine request;
  assistant prefixes continue (resume); draining refuses new requests.
- Images and audio: `weirdnet-agent` 0.5 content parts (`image_url` with a `data:` URL,
  `input_audio`) reach llama.cpp unchanged, in the OpenAI shape. `ModelHost` refuses them for a
  model whose `Capabilities` lack them (`Unsupported`, so a pool tries another node) and refuses
  remote image URLs (`BadRequest`). `Capabilities::inputs()` gives the `Modalities` an inference
  node puts in its catalog entry (`CatalogModel::with_inputs`).

```rust
use std::sync::Arc;
use weirdnet_backends::{EngineConfig, EngineKind, ModelHost, ModelLaunch, Supervisor, SupervisorOptions};

let chat = ModelLaunch::new("qwen3-8b", EngineKind::Llamacpp, "/models/qwen3-8b-q4_k_m.gguf");
let sup = Supervisor::new(vec![EngineConfig::llamacpp("llama-server")], vec![chat], SupervisorOptions::default());
sup.load("qwen3-8b").await?;
let host = Arc::new(ModelHost::new(sup.clone(), auth)); // serve with weirdnet_agent::remote::infer::v2::serve
```


## Managing model files (models/1)

`models::ModelsService` serves `/weirdnet-backends/models/1` to the node's owner only: pass it
an `Authorize` such as `weirdnet_agent::serve::RosterAuth` (the owner's linked devices, narrowed
with `require_roles` if you like). Commands: `Search` (Hugging Face Hub, GGUF repos), `Files`
(a repo's models with each footprint against the node's memory budget), `Pull` (download with
progress, resuming a partial file; split GGUFs too; without a named model, the largest that
fits), with `serve`/`load` to hand it to the supervisor without a restart, `List` and `Remove`.
Closing a pull's stream cancels it. The Hugging Face token is the node's own
([`weirdnet-model`](https://crates.io/crates/weirdnet-model) `HfToken`) and never crosses the
wire. `ModelsServer::start` serves it on a `weirdnet-net` node; `ModelsClient` is the owner's side.

```rust
use weirdnet_backends::models::{ModelsService, ModelsServer, Pull};

let svc = Arc::new(ModelsService::new(weirdnet_model::ModelStore::from_env(), supervisor.clone(), owner_auth).with_budget(budget));
let _server = ModelsServer::start(&node, svc.clone())?;
// From the owner's device:
let fits = client.files(&model_node, "unsloth/Qwen3-8B-GGUF", Some(8192), Some(2)).await?;
let pulled = client.pull(&model_node, Pull::new("unsloth/Qwen3-8B-GGUF").serving(true), |p| println!("{}/{}", p.done, p.total)).await?;
```

## Uploading your own models (models/1)

Model files made elsewhere (a fine-tune, a merge, a quantization) go to a node with
`ModelsCommand::Upload`. The client reads them with
[`weirdnet-model`](https://crates.io/crates/weirdnet-model) `artifact::inspect` (GGUF models,
split models, LoRA adapters and vision projectors; Hugging Face safetensors and MLX model
folders; PEFT adapters), which hashes every file and refuses pickles, code and symlinks. The
node checks names, size, free space, its engine and (for adapters) the base before any bytes
move, checks headers as the first bytes arrive, and checks every SHA-256 at the end before
placing the files with `ModelStore::import`. Uploads go in 48 KiB chunks and resume: a closed
stream leaves the parts staged next to the store (kept 7 days by default), and the next upload of
the same files sends only the rest. Each stored entry keeps a `provenance.json` (origin, license,
base, dataset, trainer, who uploaded it and when), which `List` returns.
`StoredEntry::list(&store)` lists a `ModelStore` the same way without a running service (not
served), and `StoredEntry::from_model`, `from_adapter` and `from_projector` (or `From`), with
`with_served` and `with_base`, build entries without serde.

`serving()` hands a model to the supervisor (GGUF on llama.cpp, safetensors on vLLM, MLX on
MLX-LM, when the node runs that engine), an adapter to its base (`with_adapter_for`, live where
the engine allows) and a projector to its llama.cpp model (`with_projector_for`, which gives it
image input). `Pulled::revision` is the files' content revision for the node's capability record.

Writes (upload, remove, peer copies) follow the service's `WritePolicy`: by default any caller
the service's `Authorize` admits, such as any linked device under `RosterAuth`; `with_auth` adds
a separate check (for example a device role). `with_uploads(false)` refuses uploads alone
(`not-allowed`) while pulls, peer copies and removals keep working. It also sets a largest upload, a total quota for
uploads and how much disk stays free (`KeepFree`, by default the larger of 10% and 20 GiB).
Refusals carry a stable reason (`refusal_reason`: `exists`, `too-big`, `no-space`, `quota`,
`wrong-engine`, `wrong-arch`, `no-base`, `bad-name`, `bad-format`, `not-adapter`, `not-allowed`,
`checksum`, `not-found`). `Disk` reports free space, the limits and what uploads use.

A node copies an upload from another node with `Pull::from_peer(node, upload)` (over
`ModelsCommand::Fetch`, resuming like an upload), given `ModelsService::with_peer_dialer`.
After one upload, `ModelsClient::replicate` has the other nodes pull it from that node.

`ModelsService::on_placed(hook)` hears every entry the service places: uploads, peer copies
and Hub pulls. The hook gets a `Placed` with the stored entry as `List` shows it (provenance
included), the `Pulled` answer with its revision, and how it arrived (`PlacedVia`), so an app
can record the entry without a protocol of its own. `with_node_info(node)` keeps a
`NodeService`'s capability record current (`set_model_info` with the revision and a GGUF
file's quantization, and `set_model_origin` with the provenance's origin and license). Hooks run before the client's answer and should be quick.

```rust
use weirdnet_backends::models::Upload;
use weirdnet_model::{Provenance, artifact::{ORIGIN_UPLOAD, inspect}};

let files = vec![PathBuf::from("support-r3-Q4_K_M.gguf")];
let found = inspect(&files)?;
let upload = Upload::new("support-r3", &found, Provenance::new(ORIGIN_UPLOAD).with_license("apache-2.0")).serving();
let pulled = client.upload(&model_node, upload.clone(), &files, |p| println!("{}/{}", p.done, p.total)).await?;
let copies = client.replicate(&model_node, &other_nodes, &upload, |node, p| println!("{node}: {}", p.done)).await;

// On the node:
let svc = ModelsService::new(store, supervisor.clone(), auth)
    .with_node_info(node_service.clone())
    .on_placed(|p| println!("placed {} ({:?}) at {:?}", p.id(), p.via, p.revision()));
```

## LoRA adapters

A `ModelLaunch` can carry LoRA adapters (`LoraAdapter::new(id, path)`, optionally
`with_scale`), each served under its own id next to the base model. On llama.cpp the adapters
are GGUF LoRA files for the base's architecture, loaded with `--lora` and
`--lora-init-without-apply`; each request names its adapter and scale in the `lora` field, so
the base stays plain. On vLLM they are PEFT LoRA directories (or Hub ids) in one
`--lora-modules` list with `--enable-lora` and `--max-loras`, and a request names the adapter
as its `model`. Embedding models and MLX-LM take no adapters.

`Supervisor::add_adapter` adds one to a served base: `AdapterChange::Live` when the base is not
running, `AdapterChange::NextLoad` when it is (loading the adapter's id restarts the base with
it). `remove_adapter` takes one off; `remove_model` on a base removes its adapters too.
`load(adapter)` loads its base and `unload(adapter)` is refused. `status()` has a row per adapter
with `base` set.

Changes while the base keeps running:

- `add_adapter_live` and `remove_adapter_live` also load and unload the adapter in a running
  vLLM engine (`/v1/load_lora_adapter`, `/v1/unload_lora_adapter`). The supervisor starts vLLM
  with `VLLM_ALLOW_RUNTIME_LORA_UPDATING=True` whenever LoRA is on: the base has adapters, or
  `ModelLaunch::with_lora_slots(n)` turns it on with none (`--max-loras` is at least `n`).
- llama-server loads adapter files only at start. An adapter whose file the running engine
  already has (removed and added back, under any id) is live at once; a new file is
  `AdapterChange::NextLoad`.
- `set_adapter_scale(id, scale)` changes a llama.cpp adapter's scale from the next request, and
  a request can set its own with infer/2 `Request::adapter_scale` (weirdnet-agent 0.5.2;
  `complete_scaled` for raw completions). vLLM applies adapters at full strength and refuses
  both. Scales must be finite and within ±`MAX_ADAPTER_SCALE`.

```rust
use weirdnet_backends::{LoraAdapter, ModelLaunch};

let chat = ModelLaunch::new("qwen3-8b", EngineKind::Llamacpp, "/models/qwen3-8b-q4_k_m.gguf")
    .with_adapters(vec![LoraAdapter::new("qwen3-8b-tune", "/models/adapters/tune/tune-LoRA-F16.gguf").with_scale(0.8)]);
```

With the `node` feature, models/1 pulls an adapter for a served base:
`Pull::new(repo).with_adapter_for("qwen3-8b").serving(true)` downloads it with
[`weirdnet-model`](https://crates.io/crates/weirdnet-model) `download_adapter` and adds it.
Adapters whose architecture or base model does not match the base are refused. `Files` lists a
repo's adapters in `RepoFits::adapters`, and `List` and `Remove` cover adapters.
`ServeAdapter`, `UnserveAdapter` and `AdapterScale` (`ModelsClient::serve_adapter`,
`unserve_adapter`, `set_adapter_scale`) put a stored adapter on a base, take one off while
keeping its files, and change its scale, live where the engine allows.

## MLX-LM (Apple silicon)

`EngineKind::Mlx` runs MLX-format models with `mlx_lm.server` on macOS on Apple silicon:

```rust
use weirdnet_backends::{EngineConfig, EngineKind, ModelLaunch, mlx};

let server = mlx::install(&engines_dir.join("mlx"))?; // pinned mlx-lm in a venv (uv, else python3)
let mut qwen = ModelLaunch::new("qwen3-8b", EngineKind::Mlx, "/models/mlx/Qwen3-8B-4bit");
qwen.context = Some(32768); // becomes --max-tokens
let engines = vec![EngineConfig::mlx(server), EngineConfig::llamacpp("llama-server")];
```

- Launch: `mlx_lm.server --model <dir> --host 127.0.0.1 --port <p> --max-tokens <context>`
  (32768 when no context is set; MLX-LM's own default is 512).
- MLX-LM has no API key, so it runs on a private loopback port and the model's port is a small
  proxy in the node that checks the per-process key as a bearer token, rewrites each request's
  `model` to MLX-LM's `default_model`, lists the pool id in `/v1/models` and streams responses
  through.
- A wrapped stock `mlx_lm.server` (`ModelLaunch::wrap` with `EngineKind::Mlx`) gets the same
  proxy.
- Ready only after a one-token completion succeeds (MLX-LM's `/health` is 200 before the
  weights are loaded).
- Text only: image and audio content parts get 400, and so does `/v1/embeddings`;
  `Supervisor::embed` refuses MLX models, and an MLX model with `embedding` set fails to load.
  Run embedding and vision models on llama.cpp.
- `mlx::install` puts `mlx-lm==0.32.2` (`mlx::MLX_LM_VERSION`) into a venv made by `uv`
  (Python 3.12) when it is on `PATH`, else by `python3 -m venv`; `mlx::install_commands` gives
  the commands for apps that run them themselves.

## The `node` feature: `/weirdnet-backends/node/1`

How inference nodes drive model nodes over [`weirdnet-net`](https://crates.io/crates/weirdnet-net).

- **Capability records**, pushed to every subscriber: hardware and memory budget
  ([`weirdnet-model`]https://crates.io/crates/weirdnet-model `hw`), engines, every
  configured model (state, revision, quantization, context and slot limits, load-time
  estimate, measured prefill/decode speed and time to first token, and, when set with
  `NodeService::set_model_origin`, its origin (`hub`, `upload` or `train`) and license), load (queued, active,
  slots, in flight), warm prefix hashes, swap groups, draining, its reservation, whether the node takes
  group jobs and its private links (`NodeService::set_links`, `link::local_links`: address,
  class, interface, nominal and declared speed; public and CGNAT addresses are never
  advertised). Each is signed by the node key, chained to the user by its `NodeCert`, carries
  an increasing sequence number and expires after 90 s; it is refreshed every 15 s and on
  every change. `Verifier` checks the signature, the signer, the expiry and the user's
  certificate, and with `Verifier::with_roster` that the node is still linked (a revoked
  node's record is refused even with its old certificate); `Subscription` also rejects sequence numbers that go backwards.
- **Commands**: `Load` (with `force` for a crash loop), `Unload`, `Drain` (stop admissions and
  wait for requests under way, or resume), `Reserve`/`Release` (hold the GPU for a holder:
  nothing loads, runs or joins a group there until released; since 0.4.3), `GroupUp`/`GroupDown`, `Health`. Cross-machine swap
  groups (a Ray worker, an `rpc-server` on a private link) are started by the application's
  `GroupWorkers`; without one a node answers `Unsupported` and advertises `group_jobs: false`.
- `NodeServer::start` serves node/1 and raw inference on `/weirdnet-backends/infer/1`
  (`RAW_INFER_PROTOCOL`, the infer/2 framing) and, for 0.1.0 inference nodes, on
  `/weirdnet-agent/infer/2`; `NodeServer::start_with(.., NodeServerOptions::default().with_legacy_infer2(false))`
  leaves infer/2 free for a node that is also an inference node. Inference nodes wrap their
  model-node dialer in `RawInferDialer`, which tries the new id and falls back to infer/2. It
  announces `weirdnet-backends-node` with the protocols served; `NodeService::withdraw` ends subscriptions when the
  node leaves. `NodeClient` is the inference node's side, over any `weirdnet-agent` `Dialer`.
- Who may drive a model node is an `Authorize` hook; `weirdnet_agent::serve::RosterAuth`
  admits the user's linked devices.

## Platforms

| | Linux | macOS | Windows |
|---|---|---|---|
| llama.cpp | yes | yes | yes |
| vLLM | yes | no (vLLM is Linux-only) | no |
| MLX-LM | no | Apple silicon only | no |
| Graceful stop (SIGTERM, then SIGKILL after a grace period) | yes | yes | no: killed outright |
| Engine in its own process group (children stopped too) | yes | yes | no |
| Engine dies with the node process | yes (`PR_SET_PDEATHSIG`) | no | no |
| `node` feature | yes | yes | yes |

The Unix-only pieces are behind `cfg(unix)`; the library builds everywhere.

## Tests

The adapter tests run against a mock engine (the test binary re-executes itself as a fake
`llama-server`/`vllm serve`/`mlx_lm.server`), never a real one. The MLX proxy has unit tests
against a fake MLX-LM server in `src/mlx.rs`; no test runs a real `mlx_lm.server`. `tests/node.rs` runs node/1 and raw infer/2
between in-process `weirdnet-net` nodes on the memory transport.