7
Architecture
Jaroslav Beneš edited this page 2026-11-13 09:23:04 +00:00

Architecture

This page describes dev (2.0); where 1.x on main differs in a way that matters, it says so.

One process per front end, one event bus per session. createApp (in src/app.ts) wires configuration, the project, the model and an Engine; the TUI, lembas run, the ACP agent and the tests all start there and subscribe to the same events.

Layout of src/

cli.ts             argv: the TUI, or run | models | sessions | config (check|schema|list|get|set)
                   | login | logout | serve --stdio | service | mcp | voice | kb | trust | update
                   | uninstall
app.ts             wiring shared by every front end: config → project → model → Engine; spawn
                   (subagents, as jobs), wake() (a job's note into the session), the live Settings,
                   freeze() of memory and skills per session
headless.ts        `lembas run "…"`: answer on stdout, tool lines on stderr, or --json lines
settings.ts        a setting's value and source; set for session / global / project
reload.ts          /reload: execv the binary on disk now, back on the same session
doctor.ts          `lembas config check`: machine checks (another `lembas` first on PATH, …)
service.ts         `lembas service`: the link as a systemd *user* unit, one copy at a time
uninstall.ts       `lembas uninstall [--purge]`
harness.ts         the harness spec embedded at build time: version, tool catalogue
version.ts         replaced at compile time

bus/               the typed event bus, and the Asker interface (who answers approvals,
                   questions and plans)
config/            XDG paths (LEMBAS_HOME for tests), YAML loading and layering, {env:}/{file:}
                   substitution, the zod schema, the settings list, JSON Schemas
provider/          index.ts (the login's model by its served id; NOT_LOGGED_IN), types.ts
                   (Message, StreamEvent), common.ts (retry rule, part builder, stream recorder),
                   sse.ts, think.ts (inline <think> splitter), effort.ts, learned.ts, http.ts (TLS,
                   auth), tokens.ts, refs.ts (a model's served id, and the older forms that still
                   resolve); the one client: openai-chat.ts
permission/        wildcard.ts, arity.ts (OpenCode), bash.ts (the small shell reader),
                   hardline.ts (the floor), evaluate.ts (rules, modes, paths)
tool/              tool.ts (the framework), registry.ts, names.ts (former names; `todo` becomes a
                   plan_write, bash_output/bash_list/bash_kill the job tools); read, write, edit,
                   multiedit, apply_patch (+ patch.ts, unidiff.ts, replace.ts), search.ts (list,
                   glob, grep), bash (a command still running at its timeout becomes a job),
                   job_tools.ts (job_list, job_output, job_stop, job_send, report), web, ask_user,
                   plan_write, plan_update, plan_submit, task, memory, skills, library,
                   session_search, settings, view_image, project_tools (tasks, decisions),
                   recall (any stored result again), show (a file in the client's viewer)
jobs/              registry.ts (one JobRegistry per process: commands and subagents as jobs, owned
                   by a session, persisted in the store, woken through the attached front end),
                   note.ts (the marked notes — conformance `jobs`)
plan/              plan.ts: the structured plan (harness/conformance/plan.json) — normalise, apply,
                   fromTodos, render (with ids), summary (the panel's six lines)
pages/             fence.ts (an `html-view` page fence: its title, the note, the text projection),
                   store.ts (a page kept under the state directory, one file each)
session/           engine.ts (the loop), store.ts (SQLite + FTS5), turns.ts (undo/redo),
                   results.ts (context hygiene: result ids, stubs, the cap, recall),
                   title.ts, context.ts (/context), capacity.ts (the capacity rule),
                   commands.ts (slash commands shared by the TUI and ACP)
prompt/            assemble.ts (the system prompt, instructionChain), fill.ts (a spec text's
                   variables; a bullet whose variable is empty disappears), personality.ts
project/           root.ts (.agent, or .lembas), init.ts (first open: trust, git, skeleton),
                   safe.ts (no writes through a committed symlink), attach.ts (@ references),
                   files.ts (the @ index), commands.ts, agents.ts, board.ts, image.ts
git/               run.ts, repo.ts, snapshot.ts (the shadow store), branch.ts, commit.ts,
                   release.ts, worktree.ts
memory/            store.ts (MEMORY.md, USER.md), threats.ts (the injection scanner)
skill/             SKILL.md directories, the skills block of the prompt
library/           store.ts (notes, bases, documents, chunks; FTS5 + vectors), chunks.ts,
                   embed.ts, ingest.ts, cli.ts (`lembas kb`)
mcp/               index.ts (McpManager: stdio and HTTP servers), oauth.ts
search/            webui (a LLeMbas instance's), searxng, firecrawl, ddg; fetch.ts (pages)
voice/             audio.ts (recorders and players), speech.ts, text.ts, index.ts
lembas/            the LLeMbas server: client.ts (discovery, device login, the protocol check),
                   login.ts, webui.ts (the login, expanded into the server's /v1 and its
                   models), personal.ts (personalization, usage)
acp/               agent.ts, rpc.ts, link.ts, hub.ts, share.ts, prompt.ts, turns.ts,
                   pending.ts, shellrc.ts — see below
update/            index.ts, source.ts, sshsig.ts, version.ts — see below
tui/               OpenTUI + Solid — see below

Outside src/: harness/ (the shared spec), schema/ (JSON Schemas for the two YAML files, from bun run schema), scripts/ (build, dist, smoke, drive, ci, licences, harness), install.sh and get.sh, third_party/.

The engine loop (src/session/engine.ts)

  1. Stream a reply from the provider; forward text, reasoning and tool-call deltas to the bus. A tool-call fragment that names no index continues the last call started (harness/quirks.json tool-call-without-index).
  2. No tool calls → done. Otherwise decide every call first (asking is sequential): parse and validate the arguments, build the tool's permission request, evaluate it, ask when needed. The same call three times running is always asked about.
  3. Run what was allowed: consecutive ordinary calls together, up to four; an exclusive tool (such as ask_user) alone; two calls on the same file in order. Errors become tool results, never exceptions.
  4. Append the results — each made into what the model sees as it is inserted (session/results.ts, below) — and go round again.

The numbers — the step backstop, how many calls run together, how often a silent reply is nudged, and the wrap-up message — are harness/loop.json's (LOOP in harness.ts). The plan (plan_write, plan_update) is the engine's: kept in the session store's meta under plan, so it survives a resume, emitted as the plan event, and put into the prompt as {{plan_context}} on every step while it exists.

Around that: messages sent meanwhile wait in the engine's inbox and enter after the step's tool results as one user message marked STEER_MARK (busy_input: queue holds them for the next prompt instead). Stop keeps what streamed, so /continue picks up there. Budgets (harness/loop.json: wall time, tool output bytes, written tokens) and the step ceiling withdraw the tools and ask for an answer from what the model has. Context: before each step, past compaction.auto_at of the window, the history is summarised, the table of reads appended, and the turn's prompt put back verbatim — at most twice a turn. Nothing is pruned in place any more (1.x cut old outputs first; that threw the prompt cache away). Capacity (session/capacity.ts) refuses a subagent on a model its server cannot hold beside the session's own, or beside a running subagent's.

Context hygiene (src/session/results.ts)

Harness spec 3.0.0 (harness/context.md, loop.json context): every measure acts when a result is inserted, and nothing already sent is ever rewritten, so the server's prompt cache holds. ResultContext gives every result an id (# and hex, at least four digits, never reused — [#0001]); a read is headed by its path, lines, length and the first 8 hex digits of the content's SHA-256. A read of an unchanged file inside an earlier full read, or a list/glob/grep repeated with the same result, is a stub naming the earlier id. Output over 400 lines or 40,000 characters keeps its head and tail with an [N lines elided, full output #id] line. edit, multiedit, write and apply_patch answer with their hunks under the new content's hash. Full results live in the session store's results table, so recall (tool/recall.ts) shows any of them, or a range, also after a resume or a compaction. A stub only points at a result still in the conversation (presentIds): after a compaction, an /undo or a rewind the file is read in full. Compaction appends compactionTable() — the reads still in the conversation — to the summary. blocks/context.md tells the model, wherever recall is offered.

Background work: jobs (src/jobs/)

A job is a command in the background (bash with background: true, or a foreground command still running when its timeout passed — it is handed over with its buffer, not killed) or a subagent in the background (task with background: true). One JobRegistry per process; every lookup is scoped by the owning session, ids job1… per session continuing from the store. A job's row lives in the jobs table (its record, the last 64 KB of output, and a note waiting for a session nobody has open); a job found running when a process starts is lost. Each createApp attaches { sessionId(), bus, wake, store }: the registry emits job (start/update/end, ≤ 4 a second per job) and job_note on that bus and calls wake when a job ends — engine.note() while a prompt runs (delivered at the next step boundary, JOB_MARK), otherwise a turn of its own through Turns.prompt with machine: true. The texts are jobs/note.ts (harness/loop.json jobs.marks, conformance/jobs.json). A subagent's own commands stop when it ends; a session's jobs stop with /delete; the TUI asks before quitting or reloading with jobs running; headless waits for the prompt's jobs. On process exit every command's group gets TERM, then KILL, synchronously.

Subagents (src/app.ts spawn, src/tool/task.ts)

spawn() builds a child Engine — its own Bus, the parent's tools minus NOT_FOR_SUBAGENTS plus report, stricterMode, limits.subagent_steps — with a session row of its own (sessions.parent_id; children are left out of /sessions and session_search, and deleted with the parent), and registers it as a subagent job: the registry follows the child's bus (its text and tool lines become the job's transcript for job_output; sub_tool with the jobId and usage{child} go to the parent's bus). A synchronous task awaits the handle and returns the report as the call's output (silent: no note); background: true returns the id and the end note wakes the parent. job_send steers a running child (to_subagent mark) or prompts a finished one again under the same id; report wakes the parent with the message mark. A child's approval request carries source: { jobId, agent, description } so every card can say who asks. The preamble is harness/prompts/blocks/subagent.md, the built-ins' instructions harness/prompts/agents/*.md.

Permission evaluation (src/permission/evaluate.ts)

Every path is judged where it really is (realPath).

  1. Hardline: the raw line, then each simple command in its plain spelling (plainCommands: VAR= prefixes, wrappers such as sudo -u x, env -i, timeout 5, xargs taken off; quotes and program paths removed; sh -c "…" read as the line it runs); protected paths for writes. Deny.
  2. Rules: defaults → global → project (trusted only) → session approvals. Per pattern the last match wins, across patterns the strictest; an approval never beats a written deny, and a deny on the plain spelling is a deny. A bash line is split into simple commands; command substitution, eval, nested shells or a redirect to a file turn an allow into ask. Files a command names follow the read rules and the project boundary.
  3. A path outside the project goes through external_directory.
  4. Mode: auto allows; plan allows reads and writes only under the project's plans/; edit allows file reads and writes inside the project (not .git/, not the project's own config, agents, commands and skills); manual is the rules as they are. A subagent can be stricter than its parent, never looser.

"Always allow" covers the command's arity prefix (git commit -m x → git commit *); a command that runs others is approved exactly, and a line where one runs others offers no "always".

Providers (src/provider/)

There is one: the server the CLI is logged in to, spoken to as OpenAI chat at its /v1 (openai-chat.ts). index.ts resolveModel finds a model by its served id (deepseek/deepseek-flash; refs.ts still resolves the older <login>/<id> forms), else config.yaml's model, else the server's default for the account; without a login it throws NOT_LOGGED_IN, which says lembas login <address>. The context window, efforts, vision and capacity are what /v1/models says — no discovery. The client turns the provider-neutral Message[] into its request and its stream into StreamEvents (text, reasoning, tool_call_delta, usage, progress, notice, finish). common.retrying() owns the retry rule: only while nothing of the reply has been passed on, plus one attempt for a server error. effort.ts and learned.ts remember an effort a server refused. 1.x on main has five dialects (openai-chat, responses, anthropic, gemini, ollama), custom connections, context discovery and a model fallback.

The session store and turns

session/store.ts is ~/.local/share/lembas/sessions.db (bun:sqlite), sessions and messages with an FTS5 index for session_search and /sessions. Each prompt is a turn (session/turns.ts): a snapshot before and after in a shadow git repository (git/snapshot.ts, under ~/.local/share/lembas/snapshot/, borrowing the project's objects, skipping .git, node_modules, the project's local/ and files over 2 MB, off above 20 000 files). /undo restores exactly the paths the turn changed and drops it from the conversation; /redo reverses that; /checkpoint keeps a tree under a name with its objects packed so a git gc in the project cannot orphan it. Titles are set from the first prompt at once and improved by the model after the first reply.

The system prompt (src/prompt/assemble.ts)

Identity → the shared text (system/default.md, its variables filled by prompt/fill.ts: the terminal as the surface, the file tools, background commands, the git section, the current plan) and the family overlay → the instance's instructions, when a LLeMbas client sent them over the link → environment, model roster, git state, task board → the instruction files → MCP server instructions (scanned) → memory guidance and the memory snapshot (the server's lembas://memory when memory is the server's) → the skills block → the library block (when knowledge tools are offered; this machine's bases only) → the context block (where recall is offered) → the mode → the person's custom instructions → the personality (an instance's, when it sent them). The last two use the same headings and order as the LLeMbas web UI. Memory and skills are frozen per session (freeze() at start, /new and resume), so a save during the session does not change the prompt under it and the provider's prompt cache stays valid.

Instruction files stack (instructionChain, harness filesystem.md): the global AGENTS.md, then every directory from the project root down to the working directory, outermost first, each giving its AGENTS.md, else its CLAUDE.md — only a real file inside the project (a link out is passed over) — then the configured instructions. 1.x took only the nearest file.

The TUI (src/tui/)

A subscriber like any other. state.ts turns bus events into a list of items, buffering streamed text and flushing about 30 times a second; the permission asker is a store entry whose resolve a card calls. index.tsx builds the renderer and gives the terminal back before any fatal error; app.tsx is Root (layout, keys, dialogs); components/ holds the prompt, messages, the permission, question and plan cards, the spinner, the status bar, the todo list, the first-run and setup screens; commands.ts the built-in slash commands; palette.ts and theme.ts every colour; clipboard.ts copies by OSC 52 and the system clipboard; paste.ts keeps the prompt box's paste placeholders ([Pasted text 40 lines], [Image 1]: OpenTUI extmarks over the label, the content beside them, sent in full); reportsmenu.ts is /reports (the schedules' reports, from the server); pages/fence.ts reads the html-view page fences of a reply, which a terminal shows as a note and keeps as files (/pages); kitty-clipboard.ts asks a kitty terminal for the image on its clipboard (OSC 5522), which is how one crosses SSH; project/image.ts reads the machine's own clipboard and recognises an image pasted as a data URL; locale.ts writes numbers as the terminal's locale does. Jobs: state.ts keeps the session's jobs from the job events (running first, an unseen flag per job); the status bar counts them; /jobs (commands.ts) is a live picker — Enter opens, k stops; components/jobview.tsx is a command's output following its tail; components/subagent.tsx is an entered subagent: the child's own createView(bus) inside a TuiContext.Provider, read-only, with the prompt box routed to job_send (app.tsx entered). Ctrl+B hands the step's foreground command to the registry (ToolContext.backgroundNow, one AbortController per step's tool group in the engine); quitting or /reload with jobs running asks first.

  • agent.ts — the CLI as an ACP agent: lembas serve --stdio for an editor, and the far end of the LLeMbas link. A session is an ordinary session (createApp): same tools, permissions, prompts and hardline as the TUI. A client that says it is LLeMbas also gets every engine event as _lembas/event. Limits are the device's: the global remote: block's roots, max_mode, trust and approval timeout. Context is the client's: _meta.lembas on session/new and every session/prompt may carry the instance's system prompt, the account's personalization, the chat's knowledge bases (no longer read: the knowledge bases are this machine's) — the 1.1.0 capabilities context, library, plan_state (the plan as a structure on the plan update, on _lembas/plan and in status) and rewind (_lembas/session/rewind: a turn and everything after it leave the conversation as /undo does, files untouched). A session the client opened sends its id as _meta.lembas.scope on every memory call and on the memory read. show (spec 3.0.0): offered only in a session a client opened that said it can show files; the device reads the file (at most 1 MB) and sends it with _lembas/show to the web UI's or Desktop's viewer. A bare terminal never offers it.
  • Link protocol 3 (LEMBAS_PROTOCOL): spoken alone. A server listing only 1 and 2 is refused at login and before every dial, saying to update the server or use LLeMbas CLI 1.x; a newer one is told to update the CLI; a 4400 close stops the link with the same advice. session/new's result says instance, and a session the client opens runs on the chat's model or is refused (-32602 with the reason) — never answered on the device's own model.
  • rpc.ts — JSON-RPC 2.0, one message a line on stdio and one per WebSocket frame on the link; written here so its few rules are what LLeMbas implements in Python too.
  • link.ts — the machine dials out to the instance it is logged in to; one connection per device, re-dialled with backoff. Nothing listens.
  • hub.ts — one session, seen from the terminal and the web alike. The process holding the link (the service, or a terminal sharing with /remote) is the hub, on a Unix socket in the state directory (mode 0600). A web-started session runs in the hub; opening it in a terminal asks the hub to let go.
  • share.ts — a terminal's side of the hub: its session shown in the web UI, the web as a second keyboard; an approval asked on both sides, first answer wins.
  • prompt.ts — a web prompt made into what the TUI would have sent: /name through session/commands.ts, @path through the TUI's expander, images and files stored as attachments (10 MB a block, 25 MB a prompt).
  • jobs.ts — the jobs capability's answers (_lembas/jobs, _lembas/job/output|stop|send|transcript, jobs in status), shared by agent.ts for the sessions it holds and by share.ts for a terminal's (through hub/job).
  • turns.ts — turn ids, the last 200 per session in a file shared by the service and a terminal, so a prompt is never run twice across a handover or a restart; _lembas/session/status reports running, queued and last finished.
  • pending.ts — deletes the instance has not acknowledged, resent.
  • shellrc.ts — shell integration for a terminal opened from the web: OSC 133 and OSC 7 marks for bash, zsh and fish.

The whole protocol, every _lembas/* method and capability, is harness/acp.md. lembas/client.ts finds an instance (/.well-known/lembas.json) and signs in by device code (RFC 8628); lembas/webui.ts reads the account's models from /v1/models at every start.

Updates and signing (src/update/)

source.ts lists releases from GitHub's or Gitea's API or a static directory (default: the public GitHub repository). version.ts compares SemVer; a channel is stable or beta. index.ts installs: fetch SHA256SUMS and SHA256SUMS.sig; sshsig.ts checks the SSH signature itself (PROTOCOL.sshsig, namespace lembas-release, a key from RELEASE_KEYS or update.public_key, ed25519 over the hashed list), with no ssh-keygen needed; the list's first line must name the release's version; the asset must match its checksum; the unpacked binary must report that version. The running binary is hard-linked to .prev and the new one renamed over it; the running process keeps its inode. A build from source is never updated, and nothing older than what runs is installed unless asked for by name. RELEASE_KEYS is a list so the key can be rotated: a release signed by the old key ships the new one.

The service (src/service.ts)

lembas service install writes ~/.config/systemd/user/lembas.service and starts it; status, logs, uninstall, and run (what the unit runs: the link and the hub, in the foreground). It runs as the user, never root, listens on nothing, and says — rather than does — that lingering is needed to keep it running while nobody is logged in.

Library, memory, skills, MCP, voice

  • Memory is the server's when the login's token has the memory scope (library: lembas, the default then): the memory tool is the server's /mcp tool, and the prompt's snapshot is the resource lembas://memory, read as a session starts and kept for it. Otherwise it is two small files (MEMORY.md, USER.md) under the config directory, written by the memory tool and scanned by memory/threats.ts. Skills are SKILL.md directories; only names and first lines enter the prompt, and skill_manage is all-or-nothing across the files it touches.
  • The library is one SQLite file: notes, knowledge bases, documents and chunks (LLeMbas's chunker, shared by conformance), bm25 plus optional vectors, fused by reciprocal rank. It is always this machine's: with library: lembas only memory comes from the server's /mcp (1.x took notes and knowledge from there too).
  • MCP: McpManager connects every server at once without blocking the TUI; a server that connects mid-session is usable from the next prompt. Stdio servers get a minimal environment; HTTP servers try streamable HTTP, then SSE; OAuth is the SDK's flow with tokens in mcp-auth.json (mode 600).
  • HTML pages (harness pages.md): a reply's html-view fence is a page the web UI and Desktop show in a sealed frame. A terminal's model is never offered pages; a reply that has one (a report, a chat seen over the link) is drawn with the note This answer has a page: title, and the page is kept under $XDG_STATE_HOME/lembas/pages/<session>/ (0600, as written); /pages lists them.
  • Voice: every recorder delivers raw 16 kHz mono s16le on stdout, so the level meter and silence detection work the same; the recorder is its own process group and is killed with it.