Web Server¶
basemode-loom includes a FastAPI server for headless use or building custom frontends.
Starting the server¶
The default development mode enables docs, accepts missing WebSocket origins,
and automatically permits common loopback browser origins. It still binds only
to 127.0.0.1. A non-loopback bind requires both --host and the explicit
--public acknowledgement.
For deployment, configure [server] in TOML or BASEMODE_LOOM_* environment
variables and use:
Production startup fails when allowed_origins is empty. Production also
requires an allowed Origin on WebSocket handshakes and disables /docs,
/redoc, and /openapi.json; --enable-docs explicitly overrides the latter.
HTTP clients without an Origin remain supported. Origin enforcement is a
browser boundary, not authentication.
Or from Python:
import uvicorn
from basemode_loom import GenerationStore
from basemode_loom.api import create_app
store = GenerationStore()
app = create_app(store)
uvicorn.run(app, host="127.0.0.1", port=8000)
Embedding with a private store per user¶
The standalone CLI server loads one SQLite database at startup. An embedding
application can instead pass store_resolver to create_app. It receives
the trusted ASGI scope for each HTTP request and WebSocket connection and
returns the GenerationStore that connection may access:
Store connections use SQLite WAL mode and wait up to 30 seconds for a busy database, allowing concurrent browser sessions to read while short writes are being committed and to tolerate brief write contention.
from starlette.types import Scope
from basemode_loom import GenerationStore
from basemode_loom.api import StoreResolver, create_app
default_store = GenerationStore("/var/lib/grove/default.sqlite")
def resolve_store(scope: Scope) -> GenerationStore:
# Authentication middleware owned by the host application sets this.
store_key = scope["state"]["grove_store_key"]
return stores_by_key[store_key]
resolver: StoreResolver = resolve_store
app = create_app(default_store, store_resolver=resolver)
Use an authenticated application to derive the store key; never accept a
database path or store key from the browser. The supplied default_store
continues to be used when no resolver is passed, including by
basemode-loom serve --db ... for local frontend development.
REST API¶
In development, FastAPI publishes the API contract automatically:
/openapi.jsoncontains the machine-readable OpenAPI 3 schema./docsprovides an interactive Swagger UI./redocprovides a reference-oriented ReDoc view.
The schema includes query constraints and response models, so a frontend can
generate a typed client with tools such as openapi-typescript, Orval, or
OpenAPI Generator. Regenerate that client when /openapi.json changes.
Search and filter trees¶
GET /api/trees?q=learning&category=research&source=codex&sort=recent&direction=desc&archived=active&limit=50
Returns picker-ready tree summaries, the total match count, available facet values and counts, and the database's search capabilities. Supported query parameters are:
q: ID, indexed keyword/semantic query, or metadata substring query when no retrieval index is availablecategory,domain,source,model: repeatable facet valuesarchived:active(the default),archived, orbothsort:auto,relevance,recent,created,oldest,nodes,breadth,branching, ornamedirection:ascordesc; when omitted,nameand legacyoldestare ascending and all other sorts are descendingoffset,limit: pagination;limitis capped at 200
Values repeated within one facet are combined with OR. Different facets are
combined with AND. auto selects relevance ordering for indexed results and
recent ordering otherwise.
recent orders by the tree's updated_at; created orders by created_at.
The legacy oldest value is retained as an ascending created-time sort.
Each item has the following schema (nullable fields are marked ?):
| Field | Type | Meaning |
|---|---|---|
id |
string | Root node ID |
tree_id |
string | Tree ID |
name |
string? | Tree name |
created_at, updated_at |
string | Persisted ISO timestamps |
archived |
boolean | Tree archive state |
node_count |
integer | Text/root nodes including the root; context nodes excluded |
breadth |
integer | Maximum number of nodes at any single depth (root depth is zero) |
avg_branching_factor |
number | Child edges divided by internal-node count; zero with no internal nodes |
branchiness |
number | (leaf_count - 1) / (descendant_count - 1), or zero with at most one descendant |
root_preview, leaf_preview |
string | Flattened root and checked-out-node previews |
category, domain |
string | Classification values, or empty strings |
sources, models |
string[] | Distinct provenance and model names |
score |
number? | Search score for ranked searches |
best_node_id |
string? | Best matching node for ranked searches |
sort=branching uses avg_branching_factor, matching Grove's Branching
display. branchiness remains available as the size-normalized topology
measure used by the subtree statistics endpoint.
The response also contains total (matches before pagination), offset,
limit, facet counts, and search capabilities. The catalogue query paginates
before calculating shapes and page previews for recent, created, name, and
node-count ordering. Breadth and branching ordering necessarily calculate
shape metrics for all matches before pagination.
Manage embeddings¶
Reports whether the active database has a semantic index, including its model, vector dimension, and indexed vector count.
POST /api/embeddings
Content-Type: application/json
{
"model": "mlx",
"min_chars": 1,
"batch_size": 64,
"incremental": true
}
Builds or incrementally updates the semantic index in the server's configured
database. model accepts hash, mlx, or an MLX/Hugging Face model ID. The
optional dim field controls the hash embedder dimension and defaults to 256.
The server must be installed with basemode-loom[embed] for hash indexes or
basemode-loom[embed-mlx] for MLX indexes. Index builds can take time and the
request remains open until the operation completes. The bundled nginx template
allows API requests to run for 15 minutes; configure any other reverse proxy
and client timeout accordingly.
Get config¶
Returns the UI-safe merged user/project config currently loaded by the server. Server security settings are deliberately omitted.
List trees¶
Returns a list of all root nodes as JSON objects.
Create a root¶
Optional fields:
namemodelmax_tokenstemperaturen_branchescontext
Delete a tree¶
Get full tree¶
Returns {"nodes": [...]} with all nodes in the tree.
Get tree stats¶
Returns the same stats as basemode-loom stats.
Export a tree¶
Returns a JSON export payload with version and nodes.
Get one node¶
Returns the serialized node plus reconstructed full_text.
List available models¶
Returns the currently available basemode model catalog for picker UIs.
Import a tree¶
Imports node records directly and returns the inserted count.
Provider API keys¶
Keys are stored in basemode's own key file (~/.config/basemode/auth.json,
mode 0600) through basemode.keys, so a key set here is the same key the
basemode CLI and the loom TUI use. A stored key takes effect immediately —
no restart — because the server also exports it into its own environment.
Keys are write-only. No endpoint returns a stored key. The only read surface is the masked listing below.
{
"providers": [
{
"provider": "openai",
"env_var": "OPENAI_API_KEY",
"configured": true,
"masked": "sk-p...6789",
"source": "stored"
}
],
"writable": true
}
source is "stored" for a key in the key file and "environment" for one
exported into the server's environment, so a UI can explain why generation
already works without anything stored. writable reports whether this server
accepts writes.
Returns the same masked status object. The key travels in the body, not the
path or a query string, to keep it out of access logs and browser history.
provider must be one of basemode's known providers (openai, anthropic,
openrouter, groq, gemini, together, moonshot, xai, zai);
anything else is a 404 unknown_provider, which also stops a caller from
naming an arbitrary environment variable. A blank value is 422 empty_key
and a value over 8 KiB is 413 key_too_large.
There is currently no delete endpoint: basemode.keys exposes no removal
function, and reimplementing its file format here would risk the two drifting
apart. Overwrite a key with PUT, or edit the auth file directly.
Who is allowed to write keys¶
The key file is machine-wide, so a key written through this API becomes the
key every caller of this server generates with. That is what a local
single-user tool wants and is wrong for a shared deployment, so writes are
disabled by default whenever production is on — PUT returns
403 credential_writes_disabled and GET reports "writable": false.
Origin enforcement is a browser boundary, not authentication, so a production server should keep writes off unless it is genuinely single-user and network-isolated. Override in either direction with:
or BASEMODE_LOOM_ALLOW_CREDENTIAL_WRITES=true.
Model ratings¶
A user can rate a model up or down. Ratings are stored in basemode's own
config file (~/.config/basemode/auth.json) beside keys and pinned
strategies, not in the corpus database — a thumb belongs to the user, so it
survives a --db swap, is never exported with a tree, and is shared with the
basemode CLI and the loom TUI.
A rating only reorders listings: GET /api/models sorts thumbs-up models
first and thumbs-down models last, and every entry it returns carries a
rating field (1, -1, or null). Nothing is hidden, and generation is
unaffected.
rating is 1, -1, or null to clear; anything else is 422
invalid_rating, and a blank model is 422 empty_model. The model ID travels
in the body because model IDs contain slashes (anthropic/claude-opus-5),
which a path parameter would force every caller to encode. The response
reports the resolved ID the thumb was stored under (gpt-4o-mini →
openai/gpt-4o-mini), normalized exactly as generation normalizes it, so the
same model rated by either name is one thumb.
Ratings are preferences rather than secrets, but they are still the
operator's preferences in a machine-wide file, so writes follow the same
default as key writes: disabled whenever production is on, with PUT
returning 403 rating_writes_disabled and GET reporting
"writable": false. Override with:
or BASEMODE_LOOM_ALLOW_RATING_WRITES=true.
Flagged generations¶
A user can mark one generation as bad: flag_node over the websocket sets
flagged on the node, exactly like a bookmark, and toggles it off again.
An in-place boundary correction raises the same signal, so it also appears in
this corpus, including corrections recorded before automatic flagging.
The node and its parent carry everything needed to work out what went wrong: the text on both sides of the seam, the model, strategy, parameters, and any recorded boundary correction. The signal only marks which generations are worth reading.
{
"flags": [
{
"node_id": "...",
"tree_id": "...",
"parent_id": "...",
"model": "deepseek/deepseek-v4-flash",
"strategy": "system",
"max_tokens": 200,
"temperature": 0.9,
"created_at": "2026-08-23T18:41:02Z",
"prefix": "...the ship rounded the headland and",
"prefix_truncated": true,
"text": "the sea opened out.",
"boundary": {"raw": " wield both. The sculptor does", "streamed": "wield both. The sculptor does"}
}
],
"by_model": {
"deepseek/deepseek-v4-flash": {"generated": 40, "flagged": 12}
}
}
Each entry pairs what the model was given with what it produced, so the join
between them reads directly — which is where a botched first word shows up.
prefix is the tail of the real generation prefix (the whole lineage, not
just the parent node's own text), trimmed to prefix_chars. by_model
counts flags against generated nodes for the same model, because three flags
out of three is a different signal from three out of three hundred.
boundary records the opening of the generation before it was healed, and is
present only when healing rewrote it — which is rare, so its presence is
itself a signal. raw is what the provider's stream opened with and
streamed is what survived basemode's stream repair; the node's own text is
the third point. Together they say whether a botched seam came from the model
or from the repair, which cannot be reconstructed afterwards from the stored
text alone. Nothing is stored for the overwhelming majority of generations,
where all three agree.
Every successful generated node also carries metadata.timing: monotonic
ttft_ms (provider request start to its first streamed chunk), elapsed_ms,
streaming_ms, completion_tokens, and, when the request duration is measurable,
completion_tokens_per_second. This is end-to-end throughput: completion
tokens divided by the whole provider-request elapsed time, including TTFT.
The count is the same provider-reported or estimated completion count recorded
in metadata.usage, so consumers can check usage.is_estimate when comparing
models.
Unlike ratings and health, flags live in the corpus database rather than in basemode's config, because the evidence does: a flag is worth nothing without the node it points at, and it should travel with the tree when it is exported or shared.
Observed model health¶
A rating is an opinion; health is the record. Basemode records every generated
branch as a logical operation and each physical provider request as an attempt
in its content-free observations.sqlite ledger. Basemode, rather than Loom,
owns success semantics and failure classification.
{
"health": {
"openai/openai/gpt-4o-mini": {
"operational_status": "healthy",
"rules_version": 1,
"operations": 84,
"successful_operations": 75,
"logical_success_rate": 0.8929,
"initial_attempts": 84,
"successful_initial_attempts": 74,
"recovered_operations": 1,
"attempts": 84,
"failures": {"rate_limit": 2},
"account_failures": 0,
"source_counts": {"loom": 84},
"window_start": "2026-08-27T13:41:02.517841+00:00",
"window_end": "2026-09-03T13:41:02.517841+00:00"
}
}
}
Keys are basemode's canonical provider/creator/model — the identity that
groups an endpoint for reporting, derived from the wire ID and never sent to a
provider. model is still supplied as the wire ID, normalized the way
generation normalizes it, and answered under the canonical one, so the two
forms of this endpoint agree. A model that has never been generated with is
simply absent rather than a 404; a blank model is 422 empty_model.
Supplying days windows the whole projection.
Entries from GET /api/models carry a compact projection in a health field
(null for a model never used); pass health_days= there to window it. The
failure categories match the category on a generation_error WebSocket
message, so a UI can label a live failure and the history with one vocabulary.
Recording is read-only from the API's point of view — there is no endpoint
that writes it, and it happens as a side effect of generating. Set
BASEMODE_NO_HEALTH=1 in the server's environment to turn it off.
WebSocket API¶
For live interactive sessions, connect to the WebSocket endpoint:
The WebSocket handler manages a full LoomSession. On connection, send an init message to specify which tree to open:
The server then streams state updates and generation events back to the client as JSON.
Generation jobs are rejected rather than queued when global capacity is full;
the server sends a typed generation_busy message. It similarly sends
generation_limit_exceeded before contacting a provider when the complete
enabled model plan exceeds the branch or output-token limit. Message/field
limits, assembled-prompt limits, and a whole-job timeout provide additional
guards. Provider exception details are not returned to clients.
Client messages¶
{"type": "navigate", "direction": "child"}
{"type": "navigate", "direction": "parent"}
{"type": "navigate", "direction": "next_sibling"}
{"type": "navigate", "direction": "prev_sibling"}
{"type": "generate"}
{"type": "cancel"}
{"type": "edit", "original": "...", "edited": "..."}
{"type": "edit_node", "node_id": "...", "text": "..."}
{"type": "remove_leading_space", "node_id": "..."}
{"type": "add_leading_space", "node_id": "..."}
{"type": "add_node", "parent_id": "...", "text": "..."}
{"type": "delete_node", "node_id": "..."}
{"type": "bookmark_node", "node_id": "..."}
{"type": "flag_node", "node_id": "..."}
{"type": "bookmark_toggle"}
{"type": "bookmark_next"}
{"type": "view_toggle"}
{"type": "hoist_toggle"}
{"type": "model_names_toggle"}
edit rewrites the whole current lineage and forks wherever the text changed.
edit_node targets one node instead: it forks that node alone (rewriting the
root in place, since a root has nothing to fork from) and checks the result
out. add_node hangs a hand-written child off parent_id, tagged
manual/manual rather than a model, and checks it out. Both take their
text straight from a person, so both restore a missing space between the new
segment and the text before it — except where the segment opens with closing
punctuation or a contraction, which attach to the previous word. Both reply
with a state message.
remove_leading_space is the intentionally narrow exception to forked
editing: it removes exactly one opening ASCII space from an existing node,
without changing its identity, descendants, or sibling position. It records
the correction's before/after text in metadata.in_place_edits and flags the
node as a bad generation, so it appears in GET /api/flags with explicit
flags. add_leading_space does the same.
delete_node removes a node and its whole subtree, landing the cursor on the
parent; it refuses a root, which would take the tree with it. bookmark_node
toggles the bookmark on any node, where bookmark_toggle only reaches the
current one. flag_node toggles flagged on a node — see
Flagged generations.
Config updates use set_params:
{
"type": "set_params",
"model": "gpt-4o-mini",
"max_tokens": 200,
"temperature": 0.9,
"n_branches": 3,
"global_max_tokens": 200,
"global_n_branches": 3,
"context": "",
"rewind_split_tokens": true,
"show_model_names": true,
"model_plan": [
{
"model": "gpt-4o-mini",
"n_branches": 2,
"max_tokens": 200,
"temperature": 0.9,
"enabled": true,
"pinned_settings": true
}
],
"persist": true
}
Validation constraints:
max_tokens:50-8000temperature:0.0-2.0n_branches:1-64global_max_tokens:10-8000global_n_branches:1-64rewind_split_tokens: booleanmodel_plan: non-empty list
Server messages¶
state: full serializedSessionStatetoken: streamed token withmodel_idx,branch_idx, andslot_idxgeneration_complete: includesnew_nodesgeneration_error: one per failed provider branch when a batch partially fails; includes the model, model/branch/slot indices, diagnostic category, and any finish reason or provider statusgeneration_cancelledtree_named: emitted when a root gets auto-namederror: protocol or validation error
The WebSocket exposes interactive navigation and generation. Tree discovery, search, filtering, and deletion use the REST endpoints above.