Commit Graph
15 Commits
Author SHA1 Message Date
adm a52bec97d4 Sliding window 30+20 + GEN 0 cache pre-warm (pre-warm-on-change)
Window: MAIN_AREA 30 + BUFFER 20 (same 50 cap) halves rotation frequency. context: shared compose_prefix (byte-exact prefix of compose) + notepad_fingerprint (rendered header body, excludes updated_at). inkling: build_prefix_ids renders without finish_prompt. service: prewarm() sends GEN 0 directly (no PerfMeter/DB). sessions: schedule_prewarm at turn end on pending rotation OR notepad-dirty (ws=0 normalized); session_chat loads only the window subset.

examples/prewarm_bench.rs: joint GEN 0 -> RESUME bench, PASS on HIP (cached==L==385). Verified live all-agent: notepad write -> pre-warm 1468 -> next turn cached_tokens==1468. Tests: prefix property, opener-skip, GEN 0 primitive, notepad fingerprint. Suite 162 passed + 3 ignored.
2026-11-26 19:12:59 +01:00
adm 0ce84581a4 Add context management: notepad, sliding window, cache reuse, windowed GUI
Per-session notepad: agent-curated labelled entries via the notepad tool
(set/remove/clear), injected as a pinned <NOTEPAD> section above DIALOG,
char-budgeted with a consolidate ceiling, exposed in a read-only GUI panel.

Sliding DIALOG window (src/window.rs): retains recent messages by count in
two tiers (MAIN_AREA=40 + BUFFER=10), append-only while the buffer fills so
the prompt prefix stays byte-stable for KV reuse, then stepped hysteresis
eviction snapping to user-turn boundaries (never splits a tool exchange).
window_start persisted per session; full history never deleted.

Engine prefix-cache reuse: leave DIALOG open (a moving </DIALOG> closer broke
the engine prompt_ckpt_prefix every user turn, forcing full re-prefill);
surface usage.cached_tokens as a GUI badge; fix the PerfMeter prefill gauge to
gauge over non-cached tokens; add a static sliding-window marker after the
opener so the model knows older turns are omitted.

Stats clarity: distinguish the current inference context (last_prompt_tokens,
new "Contesto attuale" card) from the cumulative lifetime token total
(relabeled "Token cumulativi ... su tutti i turni"); /api/stats carries both.

Windowed browser transcript: GET /api/sessions/{id}/messages returns only the
retained window (SQL-filtered by window_start, never loads the full history)
plus the total count, wrapped as {messages, window_start, total}; the GUI shows
a banner noting older turns are preserved server-side. Full-chat export deferred.

Settings: the session scope re-reads the persisted instance fresh from the store
(like the general scope already did), fixing a stale-cache display that looked
like the session System Prompt was not being kept.

Docs (README) refreshed; 158 tests + 3 ignored green, clippy and fmt clean.
2026-11-26 03:12:23 +01:00
adm 840410a08f Close context sections with </NAME> + blank line so boundaries are explicit
The Inkling template renders message content verbatim with no separator, so closing tags were glued to <|end_message|> and the model did not perceive section boundaries. compose() now emits each static section as <NAME>... </NAME> followed by a blank line, and DIALOG opener/closer on their own lines. Added an #[ignore] ground-truth test rendering the composed context through the REAL chat_template.jinja asserting </SYSTEM_PROMPT>\n\n, </TOOL_USE>\n\n and </DIALOG> survive. Live probe: model now cites </TOOL_USE> + blank line and </DIALOG>. 140 tests green, clippy/fmt clean.
2026-11-25 21:51:12 +01:00
adm 765c197b95 Add a live statistics dashboard over persistent history
Replace the four-row stats modal with a real dashboard — our own angle on
the reference's ephemeral request monitor: because our context lives in
SQLite we can aggregate over ALL history, not just the last N requests.

Backend:
- Usage carries the engine's prompt_ms/decode_ms (from DONE); a token-
  weighted in-memory PerfMeter in ChatService records every served
  request (complete + stream) and exposes decode/prefill tok/s.
- store::Stats grows total_tokens, tool_calls (json_array_length over
  assistant tool_calls_json), a per-session breakdown (busiest first)
  and a per-UTC-day token series; all over existing columns, no schema
  change, still behind the Store trait.
- GET /api/stats returns the store aggregates flattened plus a live
  engine status (model, max_context, busy) and the perf gauge.

Frontend (mobile-first, vanilla, i18n catalog):
- Overview cards: engine state dot + model + context, decode speed
  (run average) + prefill, total/prompt/completion tokens, sessions +
  messages, tool calls, requests served.
- Daily stacked prompt/completion bar chart (continuous zero-filled
  UTC window, last 30 days) and per-session token-share bars.
- Polls every 2s while open, re-renders only on change; closes via
  button, backdrop or Escape.

Tests: new store breakdown test + extended stats integration assertions
(124 passed, 2 ignored). Verified live on the real engine: decode/prefill
gauge populated from DONE timings; dashboard renders on desktop.
2026-11-25 17:52:38 +01:00
adm e79ee0e20e fix(uploads): raise body limit so images/PDFs/exes upload
The /api/uploads route used axum's standard Json extractor, whose default 2 MiB
body limit silently 413-rejected any base64 payload over ~2 MiB — small .txt
files worked but images, PDFs and executables never reached the handler. Apply
DefaultBodyLimit::max(64 MiB) to the upload route (a 32 MiB decoded file is ~43 MiB
of base64), so the handler runs and applies its own decoded-size cap.

Regression test: a ~3 MiB binary upload now returns 200 (kind=binary). Verified
live with a 3.0 MiB PNG, 3.1 MiB PDF and 3.1 MiB exe: all upload, classify
correctly, and binaries are handed to the model as path reminders.
2026-11-25 17:22:45 +01:00
adm 65f8111ba2 feat: file/image upload + separated framework root (sessions/data/uploads)
- POST /api/uploads: base64 -> shared ~/.strata-ctl/uploads store (uuid+ext),
  content-sniffed kind (image/text/binary), text token-counted via the model
  tokenizer; metadata persisted in a new uploads table.
- Chat attachments routed by kind: images -> Vision bridge (multipart image_url),
  small text (<=2000 tokens) inlined, large text/binary -> path + shell_exec
  reminder; binaries never inlined. Attachment context persisted with the turn.
- GUI: attach button + file picker, removable chips, attachments sent with the
  turn and shown on the user bubble; cleared on session switch.
- Framework root ~/.strata-ctl separated by type: sessions/<name>/, data/ (SQLite,
  moved from ~/.config/strata-ctl), uploads/. Legacy DB copied once on first run.
- count_tokens seam on Formatter (real tokenizer override) + ChatService.
- i18n: upload errors + attachment markers (backend) and attach.* (GUI), it+en.
- 121 tests + 2 ignored; clippy/fmt clean; validated live (upload routing, real
  tokenizer count, image->Vision answered "Rosso", new layout).
2026-11-25 16:25:55 +01:00
adm c199953927 Per-session workspace folder + structural identity reminder
- At the first interaction the session name locks and a personal folder is created under the workspace root (default ~/.strata-ctl/<slug>, configurable via workspace_root); slug is filesystem-safe and unique. Stored in sessions.folder (idempotent migration).

- build_request always prepends a structural identity reminder ('Il tuo nome è X. La tua cartella personale è Y.') before the session SP — not an editable setting; gives the agent awareness of its workspace. router_with_store takes the workspace root. 114 tests green; verified live (folder created, name locked).
2026-11-25 15:48:39 +01:00
adm 0568b92e06 Session settings copy-on-create + immutable friendly names
- SessionSettings instance per session (system_prompt, notes, sampling), snapshotted from global defaults at creation (copy-on-create); editing a session affects only it, editing globals affects only future sessions. Global defaults template stored in DB, seeded from config; GET/PUT /api/settings/defaults.

- Framework-assigned evocative names (word list, src/name.rs) replace the auto-title (removed). Name editable only before the first interaction, then locked (name_locked); PATCH rejects post-lock rename. Session notes carry the user-defined purpose.

- Idempotent migration adds settings_json/name_locked and backfills old sessions; build_request uses the session's own settings snapshot. 112 tests green, clippy/fmt clean; verified live (migration, name lock, settings isolation).
2026-11-25 15:44:52 +01:00
adm 0123f41d99 Refine chat management: auto-titles, per-chat rename/delete, custom modal
- Auto-title a session from its first user message (chat_title) so chats are distinguishable in the sidebar instead of all 'Nuova chat'.

- Per-chat rename (✏️) and delete (🗑️) buttons with aria-labels; stopPropagation so they don't switch the conversation. deleteSessionById selects a fallback or creates a fresh session.

- Replace native prompt()/confirm() with a styled custom modal (showDialog): mobile-friendly and inspectable by automation (native dialogs hung the browser subagent).

Verified via direct HTTP (auto-title/rename/delete) + 108 tests; browser subagent avoided after repeated hangs.
2026-11-25 02:41:51 +01:00
adm 8979201139 Add GUI agent mode: the model acts via a universal shell_exec tool
- agent:🐚 native shell_exec (bash -lc, cwd, timeout, 64 KiB output cap)
  behind a ShellRunner seam — base/host mode now; an isolated Docker-MCP runner
  plugs in later without touching the loop. OpenAI function declaration included.
- agent::run_loop: bounded model<->tool orchestration, generic over the model
  step so it is unit-testable without the engine. Persists the full trajectory
  (assistant tool-call turns + role:tool results + final answer) and emits
  tool_call / tool_result / final / error progress events.
- api::sessions: POST .../chat with agent:true drives the loop and streams the
  events as SSE; the GUI shows commands + output inline (observability, no gate).
- store: messages gains tool_call_id; an idempotent migration adds the column to
  pre-existing databases (CREATE TABLE IF NOT EXISTS does not alter them).
- web: robot agent toggle, tool-call/output blocks, history rendering of tool
  turns; inline favicon to silence the favicon 404.

Validated LIVE on engine 0.1.67: the model called shell_exec('uname -a'), the
host executed it, and the model reported the output; trajectory persisted; GUI
verified by browser (toggle, tool block, output, final answer). 106 tests +
2 ignored green, clippy/fmt clean. Isolated mode (user-provided Docker container)
is the next step.
2026-11-25 02:06:45 +01:00
adm 1e13caa4ed Add mobile-first web GUI with a server-side session store (SQLite)
- store: a swappable Store trait + bundled-SQLite implementation (WAL,
  sessions/messages with per-turn token usage, cascade delete). The standard
  /v1 API stays stateless; conversation context lives server-side so
  multi-session, statistics and advanced settings can grow on top. DB path
  configurable (db_path, default ~/.config/strata-ctl/sessions.db).
- api::sessions: session-aware GUI API — session CRUD, history, POST .../chat
  (loads stored context, reuses the completion service, persists new turns with
  usage; streaming accumulates the assistant turn and persists before [DONE]),
  and /api/stats.
- api::web + web/: a mobile-first chat GUI (vanilla ES modules, no build step),
  embedded via rust-embed and served at GET / (same-origin, offline, single
  binary). Off-canvas session drawer on phones, persistent sidebar on wide
  screens; live streaming with a collapsible thinking panel; model output is
  inserted via textContent only.
- router_with_store mounts the GUI + session API only when a store is configured;
  router()/router_with_auth() are unchanged (API-only).
- Fix: a global [hidden]{display:none!important} reset so an author display rule
  (the stats modal's display:flex) cannot defeat the hidden attribute.

7 new tests (2 store unit + 4 session HTTP end-to-end + 1 config); 94 green +
2 ignored; clippy/fmt clean. Validated live on engine 0.1.67 (context retention,
streaming, stats) and via a browser check (modal, send/render, stats open/close).
Future: the Store backend is intended to move to ArangoDB (multi-model).
2026-11-24 20:38:24 +01:00
adm 9e6d44fa1a Add Anthropic Messages endpoint (/v1/messages), stream + non-stream
- api::anthropic: AnthropicRequest -> internal ChatRequest (system, text/image/
  thinking/tool_use/tool_result blocks, tools input_schema->parameters,
  tool_choice, sampling, stop_sequences); ChatResponse -> Anthropic message
  (thinking/text/tool_use blocks, stop_reason end_turn/max_tokens/tool_use, usage).
- AnthropicStream translator: message_start / content_block_start/delta/stop /
  message_delta / message_stop, with block-index state.
- Refactor service.stream to yield semantic ChatChunk (+ prompt_len); SSE
  serialization and the terminal [DONE] moved to the OpenAI route. ChatChunk
  carries a #[serde(skip)] usage field for presenters (invisible on the OpenAI
  wire). The same engine-driving (abort/stop/disconnect) feeds both formats.
- Route POST /v1/messages; the OpenAI wire is unchanged.

7 new tests (5 conversion unit + 2 HTTP end-to-end); 87 green + 2 ignored;
clippy clean; cargo fmt applied. README updated.
Core cases faithful; deferred: defer_loading/tool_addition/tool_reference,
thinking budget_tokens, prompt-cache token accounting.
2026-11-24 19:58:29 +01:00
adm b6619d30de Add optional API key auth and allowed_hosts enforcement
- AuthConfig (api_key, allowed_hosts) read from the shared config; router_with_auth
  applies an axum middleware before any handler.
- Host not in allowlist -> 403 host_not_allowed; missing/wrong key -> 401
  invalid_api_key (accepts Authorization: Bearer <key> or x-api-key); /health open.
- router() stays the open default: backward compatible (no key, wildcard hosts).
- The non-loopback bind warning now fires only when no api_key is configured.
- README updated (auth is a feature, no longer a gap).

4 new tests; 80 green + 2 real-file ignored; clippy clean; cargo fmt applied.
2026-11-24 18:48:05 +01:00
adm 5bafd000c8 Respond to code review: sampling defaults, abort race, hardening + README
Bug fixes (from review/README.md):
- Apply config sampling defaults field-by-field, so an absent temperature no
  longer means greedy; expose top_k/min_p/repetition_penalty on ChatRequest;
  top_k=0 is "disabled" (-> 64), not greedy.
- Fix cross-request abort race: Engine::request_stop() sets the cancel flag only;
  the owning generate loop does STOP+drain itself, instead of a spawned abort()
  that could hit a later request holding the lock.
- Initialize tracing-subscriber (RUST_LOG, default info); events were dropped.
- TempFilesGuard removes materialized images on every exit path (error/panic/drop);
  build_prompt runs in spawn_blocking off the async worker; ureq image fetch gets a
  15s timeout, a 32MB cap and a basic SSRF guard (literal loopback/private hosts).
- Non-blocking shutdown (STOP+QUIT without taking the request lock first) and a
  bounded drain_to_done that marks the engine dead on timeout.

Operational hardening:
- Graceful shutdown on SIGTERM as well as SIGINT.
- Warn when binding a non-loopback address (no auth, allowed_hosts not enforced).
- Configurable startup/silence timeouts (optional config keys, default 600s).

Docs:
- Add README.md (English): what strata-ctl is, why Rust for stable server use,
  architecture, usage, honest status, and credits to Strata / Niko1221.

76 tests green + 2 real-file ignored; clippy clean; cargo fmt applied.
Deferred (heavy): automatic engine restart after a crash.
2026-11-24 18:42:56 +01:00
adm 597ac432e1 strata-ctl: Rust control layer for the Strata engine (OpenAI-compatible API)
From-scratch rewrite of the Python serve (Python kept as behavioral spec).

- engine: line-protocol supervisor (GEN/T/DONE/STOP/QUIT), silence watchdog,
  abort, is_idle probe.
- config: tolerant shared-JSON loader; foreign keys ignored so one file drives
  strata-ctl and uostream; CLI --config/--host/--port/--serve.
- inkling: o200k tokenizer wrapper + incremental UTF-8-safe detok; chat template
  via minijinja; channel-token dialect (reasoning streamed live); image bridge
  (in-process Vision, image=<path>); formatter assembling the API seam.
- api: /v1/chat/completions (stream SSE + non-stream), /v1/models, /health;
  reasoning_content; structured tool_calls (llama.cpp --jinja style, client-side
  execution); stop sequences with hold-back; abort on client disconnect.

69 tests green + 2 real-file ignored; clippy clean. Text, images and tools
validated live against the real Inkling engine.
2026-11-24 05:28:56 +01:00