# strata-ctl A Rust control layer for the [Strata](https://github.com/Niko1221/Strata) inference engine: an OpenAI-compatible HTTP API that drives the engine over its native line protocol. `strata-ctl` is a from-scratch **Rust rewrite of Strata's control framework** (the Python "serve" layer that sits between HTTP clients and the C++ inference engine). It is not a fork of the engine itself: the engine stays the upstream C++ binary (`strata-inkling`); this project replaces the layer that supervises it and exposes it to the network. ## Why Rust? We believe Rust is a much better fit than Python for a process meant to run **stably, unattended, on a server** for long periods: - **Memory safety without a garbage collector** — no GC pauses, no reference-count cycles leaking over weeks of uptime, no interpreter runtime to babysit. - **Predictable latency and throughput** — compiled, no GIL, async I/O on `tokio` with explicit control over blocking work. - **Fearless concurrency** — the compiler enforces the ownership rules that keep a shared, long-lived engine supervisor honest under concurrent requests. - **A single self-contained binary** — trivial to deploy, supervise (systemd) and reproduce; no virtualenv, no dependency drift at runtime. The original Python layer remains the **behavioral specification**: this rewrite aims to match what it does on the wire, while being a more dependable thing to leave running on a server. ## Relationship to Strata - **Strata** — "Run powerful AI on your own computer. Chat, code and work with images, locally." Free, open source (MIT), by **Niko1221** and the Strata contributors: . - This project targets Strata's **Inkling** engine (`strata-inkling`, the `inkling2_loop` architecture) and its in-process Vision. The API layer is built behind a model-agnostic `Formatter` seam, so other dialects can be added later. - All credit for the engine, the model format and the original control-layer behavior goes to the Strata project and its author. `strata-ctl` is an independent reimplementation of the control layer only. ## Features OpenAI-compatible endpoints: - `POST /v1/chat/completions` — streaming (SSE) and non-streaming. - `GET /v1/models`, `GET /health`. Anthropic-compatible endpoint: - `POST /v1/messages` — the Anthropic Messages API (streaming + non-streaming), translated onto the same engine: `system`, text/image/thinking/tool_use/ tool_result content blocks, tools (`input_schema`), `tool_choice`, sampling and `stop_sequences`. Responses use Anthropic content blocks and `stop_reason` (`end_turn` / `max_tokens` / `tool_use`); streaming emits the `message_start` / `content_block_*` / `message_delta` / `message_stop` sequence. Behavior implemented and validated against the real Inkling engine: - **Chain-of-thought separation** — thinking is streamed live as `reasoning_content`, distinct from the answer `content`. - **Images** — OpenAI / Responses / Anthropic image parts (base64 data URLs, http(s) URLs, local paths) are materialized and handed to the engine's in-process Vision; unsupported formats are normalized to PNG. - **Tool calling** — structured OpenAI `tool_calls` in the llama.cpp `--jinja` style: the server renders tool declarations and parses the model's calls; **execution is client-side** (the server never runs tools). - **Stop sequences** — incremental matching with hold-back, so a stop string split across streaming deltas is still caught. - **Abort on client disconnect** — generation is stopped when the SSE client goes away, freeing the engine for the next request. - **Sampling** — per-request knobs override config defaults field-by-field (`temperature`, `top_p`, `top_k`, `min_p`, penalties, `seed`); `top_k = 0` is treated as "disabled", not greedy. Operational hardening: - Graceful shutdown on **SIGINT and SIGTERM**; the engine is signalled without blocking on an in-flight request. - Configurable startup and silence-watchdog timeouts. - Optional **API key** auth (`Authorization: Bearer ` or `x-api-key`) and a **Host allowlist** (`allowed_hosts`, DNS-rebinding protection); `/health` stays open. A warning is logged when binding a non-loopback address with no key set. - Blocking image I/O runs off the async event loop; temp files are cleaned on every exit path; image fetches have a timeout, a size cap and a basic SSRF guard. ## Web GUI A minimal, **mobile-first** chat GUI is served by the same binary at `GET /` (assets under `/assets/...`, embedded via `rust-embed` — no Node, no build step, works offline, same-origin so no CORS). It is a thin client over a **session-aware API**: - `GET /` — the chat shell (responsive: an off-canvas session drawer on phones, a persistent sidebar on wide screens with a **drag-resizable separator** between the session list and the chat — width clamped and persisted; streaming answers with a collapsible "thinking" panel; touch-friendly targets and safe-area insets). - `POST /api/sessions`, `GET /api/sessions`, `GET/PATCH/DELETE /api/sessions/{id}`, `GET /api/sessions/{id}/messages` — session CRUD and history. - `POST /api/sessions/{id}/chat` — append a turn; the server loads the stored context, runs inference (streaming SSE or not) and persists the new turns with their token usage. - `GET /api/stats` — the stats dashboard payload: persistent totals (sessions, messages, prompt/completion/total tokens, tool calls), per-session and per-day breakdowns, plus live engine status and a since-startup decode/prefill speed gauge. - `GET/PUT /api/settings/defaults` — the global default settings template. - `POST /api/uploads` — store an uploaded file (base64) in the shared upload dir; returns metadata (kind, token count, path). Attach the returned id to a chat turn. - `PATCH /api/sessions/{id}` — rename (only before the first interaction) and/or replace the session's own settings instance. **Settings & identity.** Each session owns a *settings instance* (system prompt, notes, sampling) snapshotted from the global defaults at creation (**copy-on-create**): editing a session affects only it, editing the defaults affects only *future* sessions — no retroactive surprises. The user jots the chat's purpose in **notes**. The framework assigns an evocative name (a curated word list); it is editable only before the first interaction, then **immutable**. At that first interaction a personal workspace folder is created (`~/.strata-ctl/sessions//`, under the configurable `workspace_root`) and a structural identity reminder ("your name is …, your personal folder is …") is prepended to the model's context — not an editable setting. The GUI exposes all of this in a ⚙️ settings panel (per-session or general). **Uploads.** The 📎 button attaches files and images. Bytes land in a single **shared** store (`~/.strata-ctl/uploads/`, filename converted to a uuid keeping the extension); nothing is bulk-injected into context. Content is classified by *sniffing* (not extension) and routed: **images** go through the Vision bridge (pixels, not a path); **small text** (≤ ~2000 tokens, measured with the model's own tokenizer) is inlined; **large text and binaries** are handed to the agent as a path with a reminder to inspect them selectively via `shell_exec` — binaries never enter the context directly. The `shell_exec` output cap is a second safety net. **Statistics.** The "Statistiche" button opens a live dashboard over the *persistent* history — our angle on the reference's ephemeral request monitor: overview cards (engine model / context window / idle-busy, token-weighted **decode speed** and prefill speed since startup, total/prompt/completion tokens, sessions, messages, tool calls), a **daily token chart** (stacked prompt/completion per UTC day) and a **per-session breakdown** with relative token-share bars. `GET /api/stats` returns the store aggregates plus a live engine status and an in-memory performance gauge (token-weighted over the requests served since startup, from the engine's `DONE` timings); the view polls every 2s while open. History totals survive restarts; the speed gauge resets with the process. The standard `/v1` API stays **stateless**; conversation context lives server-side in an embedded **SQLite** database (default `~/.strata-ctl/data/sessions.db`, override with `db_path`). Storage sits behind a `Store` trait so it can be swapped (the planned direction is **ArangoDB**, multi-model: KV / documents / graphs / vector indexes) or complemented by another DBMS for advanced analytics later, without touching the API or the GUI. This is the foundation for multi-session, statistics and advanced settings to grow on top. **Framework root.** All persistent state lives under `~/.strata-ctl/` (the Linux user's home; override with `workspace_root`), separated by content type: `sessions//` (agent workspace folders), `data/` (the SQLite database), `uploads/` (uploaded files). A legacy DB at `~/.config/strata-ctl/sessions.db` is copied into `data/` once on first run (the original is left in place). ## Agent mode The GUI model can **act**, not just chat. Tools are **on by default** (the 🤖 button toggles them): the framework is meant to act, not just chat. The agent has a single universal tool, **`shell_exec`** (a shell is universal: file ops, programs, system inspection, web via curl, git, …). A bounded server-side loop drives `model → shell_exec → result → model → … → final answer`, persisting the whole trajectory and streaming progress events — `delta` (the model's thinking and final answer, token by token), `tool_call` / `tool_result` (every command and its output inline) and `final` — so the wait is always visible progress, **observability without a confirmation gate**. Safety is an **environment boundary, not a per-tool sandbox**: `shell_exec` always runs via `bash -lc` on whatever machine the framework runs on, starting in the session's **personal folder** by default (override with `cwd`), with a timeout and an output cap. There is deliberately **no host-vs-container tool split** — if you want stronger protection, run *strata-ctl itself* inside a container, a VM or an isolated machine; the agent then only ever sees that environment. Execution sits behind a `ShellRunner` trait (useful for tests and alternate runners), with no per-call confirmation gate and no separate "isolated" tool backend. ## Architecture ``` shared JSON config ──► InklingFormatter ──► Engine supervisor ──► axum HTTP API (tolerant) tokenizer + chat line protocol /v1/... template + dialect (GEN/T/DONE/STOP) ``` - `config` — tolerant loader for the shared `strata-inkling.json`: it reads what it understands and ignores every other key, so one file can drive several tools. - `inkling` — the model dialect: HF `tokenizers` (o200k BPE) wrapper, MiniJinja chat template, the channel-token state machine, and the image bridge. - `engine` — a pure protocol parser plus a supervisor that owns the child process, serializes requests on its single control stream, and handles STOP/drain/QUIT. - `api` — request/response types, the `Formatter`/`Decoder` seam, the completion service (stream + non-stream), the axum router, the session-aware GUI API and the embedded web assets. - `store` — the persistent session/context store: a `Store` trait with a bundled SQLite implementation (WAL), used by the GUI API. ## Building and running Requires a Rust toolchain and a built Strata engine binary (`strata-inkling`). ```sh cargo build --release # Print the launch plan resolved from the config (default): ./target/release/strata-ctl --config /path/to/strata-inkling.json # Start the engine and serve the API: ./target/release/strata-ctl --serve --config /path/to/strata-inkling.json # overrides: --host 127.0.0.1 --port 8095 ``` The default config path is `~/.config/strata-inkling/strata-inkling.json`. Logging uses `tracing`; set `RUST_LOG` to control verbosity (default `info`). ### Configuration The config is the same JSON the other Strata tools use. Keys acted on here include `exe`, `args`, `cwd`, `tokenizer`, `model_name`, `host`, `port`, `reasoning_effort`, `sampling`, `api_key`, `allowed_hosts`, `db_path` (GUI session database), `workspace_root` (framework root), `system_prompt` (general default), `language` (UI/prompt catalog, default `it`), and the optional `startup_timeout_secs` / `silence_timeout_secs`. Everything else (`arch`, `mcp_servers`, `cors_origins`, …) is preserved untouched and reported as ignored — unknown keys never break startup. ### Localization (i18n) User-facing strings are externalized into embedded per-language catalogs and looked up by key with `{placeholder}` interpolation: - **Backend** (`src/i18n.rs`): `locales/.json`, `t(key, params)`, language from the `language` config key (default `it`), English fallback then the key. - **Frontend** (`web/assets/locales/.json`): `t(key, params)` for dynamic strings and `data-i18n` attributes for static HTML; language follows the browser. Convention: new code routes user-facing strings (and model-facing prompts such as the identity reminder) through the catalog. Wire-protocol fields, JSON keys and identifiers are **never** translated. Existing hardcoded strings are migrated in a later adaptation round. ## Status Working and tested (124 tests, plus 2 real-file tests run on demand). Text, images, the full client-side tool loop, the Anthropic endpoint, the web GUI (session context, streaming, stats, **file/image upload**) and **agent mode** (the model using `shell_exec` on the host) have been validated live against the real Inkling engine. Not yet implemented (honest gaps): forced `tool_choice` (`required` / named function returns a clear 400), multi-slot batching, logprobs / structured output, automatic engine restart after a crash, a full SSRF guard against DNS rebinding, and the OpenAI Responses native endpoint. The Anthropic adapter covers the core cases but not yet the `defer_loading` / `tool_addition` / `tool_reference` tool machinery, the thinking `budget_tokens` mapping, or prompt-cache token accounting. Base/host agent mode, per-session settings (copy-on-create), session notes, immutable names, personal workspace folders and file/image upload (shared store, token-based routing, images via Vision) work. Per-tool host/container sandboxing was **deliberately dropped**: protection comes from where you run the framework (container / VM / isolated host), not from a second tool backend. ## Roadmap **Next headline feature — semantic vector memory (scheduled, not built).** A Qoder-style vector database giving the agent long-term, cross-session semantic recall, useful well beyond coding: embed and index conversation chunks, session notes, uploaded documents and learned facts, then retrieve by similarity to inject the relevant context into a turn, plus explicit *remember* / *semantic search* tools. Recommended shape, preserving the single-binary property: an embedded vector index inside the existing SQLite store (**sqlite-vec**) behind the `Store` trait, fed by the team's `vetta-embedder` (BGE-M3 + reranker) over HTTP. The planned ArangoDB backend already offers vector indexes, so the same seam carries over when the store is swapped. Agreed architecture (design ratified, implementation deferred): - **Embedder = the team's `vetta-embedder` (BGE-M3 + BGE-Reranker-v2-m3).** Already deployed on every Linux host (default `127.0.0.1:8091`, repo `vetta-semantics`): multilingual, dense + learned-sparse + ColBERT + a cross-encoder reranker in one C++/ggml process (Vulkan with CPU fallback, no Python/ONNX). strata-ctl reaches it over HTTP exactly like it reaches the engine (config host/port), so no new model is bundled. Verified live: `/embed` (1024-d) and `/rerank` discriminate correctly. - **Store = sqlite-vec inside the existing SQLite, behind `Store`.** Dense KNN + metadata columns; retrieval pipeline = dense recall → `/rerank` cross-encoder precision → inject. Learned-sparse (`/sparse`) is available later for exact-term boost. Keeps memory co-located and transactional with sessions (single binary); the team's Qdrant (used by Iris) and the planned ArangoDB remain alternate backends behind the same seam, not the default. - **Per-session, one-way opt-in.** Vector memory is off by default (casual chat needs none); enabling it for a session is **irreversible** (a latch like `name_locked`), because indexed memories must not be silently orphaned by a later disable. Enabling requires the embedder to be reachable. - **Layered directives.** An always-on **common core** (knowledge lifecycle: recall when relevant, record durable lessons, verify against current evidence, one topic per memory, prune duplicates) plus **enable-able domain guideline packs** (coding, research/docs, radio/logs, planning, …) that the user — or the agent itself, observably — switches on per need. A pack is not just prose: it carries structured config (categories/tags, chunking strategy, retrieval filters/boosts, exposed tools) so the same general engine serves specialized retrieval. Packs integrate with the per-session settings (copy-on-create) and never override the core (core > pack). ## License and credits MIT, like Strata itself. - **Strata** engine and original control layer: Niko1221 and the Strata contributors — . - **strata-ctl** (this Rust control layer): Federico (`iz0eyj`).