Knowledge, notes, memory and skills, and a harness to make them used

Four places a model can reach for, differing in who writes a record and how it
gets in front of the model.

**Knowledge** is uploaded by a person and searched by the model. It goes through
`services/files.py:prepare` — the same pipeline as a chat attachment — so the
same PDF produces the same text whichever way it arrived, and `Document` carries
the same content columns as `Attachment` for the same reason.

**Notes** are written by the model and edited by you. Too long to inject, so
they are searched.

**Memory** is short facts, and every one of them goes into every request. That
single decision is where the rest of its design comes from: records are capped
short, the block has a budget, there is no search tool because the model is
already looking at them, and they are not shareable — a record about a person is
not content to hand round.

**Skills** are saved procedures. Only the name and description are injected; the
body is fetched when the model decides one applies, which is what makes a
hundred skills affordable. A model may write and revise its own — the safety
story is not a gate but a record: every revision is kept, attributed and
revertible. A model that has just read a hostile page can save a skill that
outlives the conversation, and the honest mitigation is that it is visible and
undoable rather than that it was prevented.

**The harness** is why any of it gets used. A model handed a tools array
ignores it and answers from recall, because nothing in the request suggests
otherwise. `services/harness.py` assembles a preamble from what this chat
actually has: when to reach for each tool, the memories, the skill index.

This is an exception to "system prompts are precedence, not concatenation", and
a deliberate one. That rule governs the three *authored* layers and is
untouched — exactly one still wins. The harness is a different axis: it
describes the machinery rather than the behaviour, nobody authored it, and there
is nothing for it to disagree with. It is prepended to whichever authored prompt
won, in one system message, since several endpoints reject a second.

Supporting changes:

- **Sharing**, in one helper. `visible_to()` is the only definition of who can
  see a library item and every listing and tool goes through it. Sharing grants
  *reading*; two people editing one note with no history and no merge is worse
  than copying it. **Administrators do not bypass this** — they bypass
  permissions elsewhere because an admin can grant themselves those anyway, but
  reading somebody's private notes is a different act.
- **FTS5**, created by `db/migrations.py:ensure_fts` with the triggers an
  external-content index needs. Idempotent, like the column sync beside it.
  Terms are ANDed and then ORed: the caller is usually a model writing a whole
  question, and requiring every word loses the match on one absent term.
- **The attach button is a menu** — file, image, a web page, or a document from
  the library. Attaching a document copies it, because history must not change
  when a document is edited later.
- **A URL fetcher with an SSRF guard.** This server can reach the router, the
  other services on the box and LLeMbas itself, and the address can come from a
  model. Private ranges are refused *after resolution* and redirects are followed
  by hand so every hop is checked. An admin can open it deliberately.
- **Model capabilities split** into protocol support and a toggle per built-in
  tool. Rows predating the split have no `tool_*` keys, and absent counts as on
  when `tools` is on — otherwise an upgrade silently takes web search away from
  every model already configured for it.

Also fixes the test fixture, which built the schema with `create_all` and so ran
against a database without the FTS tables production has; it now runs
`sync_schema`, the same path startup takes.

430 tests, ruff clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jaroslav Beneš
2026-07-21 19:43:57 +02:00
parent a8b7b5fc14
commit 21001f2eb8
51 changed files with 5135 additions and 157 deletions
+4
View File
@@ -69,6 +69,10 @@
transition: color var(--transition-fast), border-color var(--transition-fast);
}
.tabs__tab:hover { color: var(--ink); }
/* The library's tabs are links between pages rather than radios, so the active
one is marked server-side. Same bar, same look. */
.tabs__tab.is-active { color: var(--ink); border-bottom-color: var(--accent); }
a.tabs__tab { text-decoration: none; }
.tabs__panel { display: none; }
+28
View File
@@ -733,6 +733,34 @@ button, input, textarea, select {
box-shadow: var(--shadow-lg);
overflow: hidden;
}
/* The composer's attach menu opens upwards: it sits at the bottom of the
window, so a menu dropping down would be off screen. */
.picker--up .picker__menu {
top: auto;
bottom: calc(100% + var(--sp-1));
left: 0;
right: auto;
}
.picker__menu--compact { width: min(18rem, calc(100vw - var(--sp-8))); padding: var(--sp-1); }
.picker__option-note {
font-size: var(--text-xs);
color: var(--ink-faint);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* A dialog that holds a searchable list rather than a question. */
.dialog--wide { width: min(34rem, calc(100vw - var(--sp-6))); }
.dialog__results {
max-height: min(24rem, 50vh);
overflow-y: auto;
scrollbar-width: thin;
border: 1px solid var(--border);
border-radius: var(--radius);
}
.dialog__results .picker__list { max-height: none; }
.picker__search { padding: var(--sp-2); border-bottom: 1px solid var(--border); }
.input--sm { height: var(--control-h-sm); font-size: var(--text-xs); }
.picker__list { max-height: 22rem; overflow-y: auto; scrollbar-width: thin; padding: var(--sp-1); }
+120
View File
@@ -148,6 +148,126 @@
});
}
/* --- Attaching something that is not a file ----------------------------
The composer's menu offers four things; two of them are the file picker
with a different filter, and two need a round trip. Both of those post a
form and get a chip back, exactly like an upload, so the composer does not
have to know where a chip came from. */
function chipTarget() {
return document.getElementById("attachments");
}
function chatId() {
var input = document.getElementById("file-input");
var url = (input && input.dataset.uploadUrl) || "";
var match = url.match(/chat_id=([^&]+)/);
return match ? decodeURIComponent(match[1]) : "";
}
function postForChip(url, body) {
var target = chipTarget();
if (!target) return Promise.resolve();
return fetch(url, { method: "POST", body: body, credentials: "same-origin" })
.then(function (response) { return response.text(); })
.then(function (html) {
target.insertAdjacentHTML("beforeend", html);
if (window.htmx) window.htmx.process(target.lastElementChild);
});
}
function attachLink() {
if (!window.lembas || !window.lembas.prompt) return;
window.lembas.prompt({
title: "Attach a web page",
message: "The page is fetched now and its text attached, so it will not " +
"change between writing this and sending it.",
placeholder: "https://example.com/article",
confirmLabel: "Fetch",
}).then(function (url) {
if (!url || !url.trim()) return;
var body = new FormData();
body.append("url", url.trim());
body.append("chat_id", chatId());
return postForChip("/api/files/link", body);
});
}
/* The knowledge dialog re-queries the server as you type rather than
filtering in the browser: the library is searched with FTS, which is what
makes it work at five hundred documents instead of five. */
function attachKnowledge() {
var dialog = document.createElement("dialog");
dialog.className = "dialog dialog--wide";
dialog.innerHTML =
'<div class="dialog__form">' +
'<h2 class="dialog__title">Attach from your library</h2>' +
'<input class="input" type="search" placeholder="Search your documents…" ' +
'aria-label="Search your documents">' +
'<div class="dialog__results"></div>' +
'<div class="dialog__actions"><button class="btn" type="button">Close</button></div>' +
"</div>";
document.body.appendChild(dialog);
var search = dialog.querySelector("input");
var results = dialog.querySelector(".dialog__results");
var close = dialog.querySelector("button");
function load(query) {
fetch("/api/files/knowledge-picker?q=" + encodeURIComponent(query || ""), {
credentials: "same-origin",
})
.then(function (response) { return response.text(); })
.then(function (html) { results.innerHTML = html; })
.catch(function () { results.textContent = "Could not load your library."; });
}
var pending = null;
search.addEventListener("input", function () {
clearTimeout(pending);
pending = setTimeout(function () { load(search.value); }, 200);
});
results.addEventListener("click", function (event) {
var option = event.target.closest("[data-attach-knowledge]");
if (!option) return;
var body = new FormData();
body.append("document_id", option.dataset.attachKnowledge);
body.append("chat_id", chatId());
postForChip("/api/files/from-knowledge", body);
finish();
});
function finish() {
dialog.close();
setTimeout(function () { dialog.remove(); }, 200);
}
close.addEventListener("click", finish);
dialog.addEventListener("cancel", function (event) {
event.preventDefault();
finish();
});
dialog.addEventListener("click", function (event) {
if (event.target === dialog) finish();
});
dialog.showModal();
load("");
search.focus();
}
document.addEventListener("click", function (event) {
var choice = event.target.closest("[data-attach]");
if (!choice) return;
event.preventDefault();
var kind = choice.dataset.attach;
if (kind === "file") document.getElementById("file-input").click();
else if (kind === "image") document.getElementById("image-input").click();
else if (kind === "link") attachLink();
else if (kind === "knowledge") attachKnowledge();
});
function setupDropzone() {
var zone = document.querySelector("[data-dropzone]");
if (!zone) return;