Acht Werkzeuge (kb_create, kb_list, kb_write, kb_read, kb_search, kb_entries, kb_delete,
kb_drop). Eine Basis ist ein Name mit einem Verzeichnis darunter; darin liegen Seiten wie
Erinnerungen: Titel, Text, Vektor. Der Zweck unterscheidet sie: Erinnerungen sind das, was
ein Agent beiläufig behält — eine Wissensbasis ist das, was ein Mensch aufgeschrieben hat,
damit es nachgelesen wird.
Zwei Entscheidungen, die den Unterschied zu einem Dateiordner ausmachen: derselbe Titel
aktualisiert die Seite, statt sie zu verdoppeln, und die vorherige Fassung wandert in die
Historie (fünf Versionen) — die Antwort sagt beides. Und die Suche sortiert über alle
Basen gemeinsam, sonst gewinnt die beste Seite je Basis statt der besten Seite.
Namen werden zu Verzeichnisnamen ("Olivia Technik" → olivia-technik), angesprochen wird
die Basis aber über den Namen; wer den Slug kennt, darf ihn auch schreiben.
Ein Fehler auf dem Weg, der die Suite zum Absturz brachte: in der Aktualisierung zeigten
zwei Variablen auf dieselbe Kennung (die gefundene Seite und die neue Seite), und am Ende
wurde beide freigegeben — free(): double free. Jetzt gibt es genau einen Besitzer der
Kennung; die alte Fassung wird einmal gelesen und danach in die Historie kopiert.
Tests: 30 Prüfungen (vorher 16). Neu: Slug aus dem Namen, Aktualisierung statt Dublette,
Historie bleibt lesbar, Basis über den Namen ansprechbar, Suche über alle Basen und
innerhalb einer, Liste mit Seitenzahl, Löschen einer Seite, confirm-Pflicht beim Verwerfen
einer ganzen Basis. make test: PASS.
2025 lines
53 KiB
C
2025 lines
53 KiB
C
/* strdup/POSIX: das Makro muss vor dem ersten Header stehen. */
|
|
#define _POSIX_C_SOURCE 200809L
|
|
|
|
/*
|
|
* memoryd - was ein Agent sich gemerkt hat, mit Bedeutungssuche statt Volltext.
|
|
*
|
|
* Zwei Transporte aus einem Programm:
|
|
*
|
|
* memoryd stdio, JSON-RPC je Zeile
|
|
* memoryd --http 8795 Streamable HTTP, damit jeder Host der Flotte denselben
|
|
* Speicher benutzt statt eines eigenen
|
|
*
|
|
* Der Unterschied zu tasksd und skilld ist die Suche: jede Erinnerung wird beim
|
|
* Schreiben in einen Vektor umgerechnet (Embedding), und gesucht wird über die Nähe
|
|
* dieser Vektoren. "Wie war das noch mit dem Frostschutz" findet dann auch die Notiz,
|
|
* die "Kühlmittel bis -25 Grad" sagt und das Wort Frostschutz nie enthält.
|
|
*
|
|
* Ablage sind Dateien, eine je Erinnerung, unter $MEMORYDIR:
|
|
*
|
|
* m0001.json {"id","scope","text","tags","source","created","model","embedding":[..]}
|
|
*
|
|
* Was NICHT hier hineingehört: Geheimnisse, Zugangsdaten, lange Gesprächsprotokolle.
|
|
* Ein Speicher, der alles behält, macht jede Suche schlechter und jede Sicherung
|
|
* größer — der Text ist das Ergebnis, nicht der Rohstoff.
|
|
*
|
|
* Ohne Embedder läuft der Dienst weiter: dann wird ohne Vektor gespeichert und die
|
|
* Suche fällt auf Teilstrings zurück. Das steht in der Antwort, damit niemand glaubt,
|
|
* eine Bedeutungssuche gesehen zu haben, die keine war.
|
|
*/
|
|
#define MCP_IMPLEMENTATION
|
|
#include "../libmcp/mcp.h"
|
|
|
|
#include <ctype.h>
|
|
#include <dirent.h>
|
|
#include <errno.h>
|
|
#include <fcntl.h>
|
|
#include <limits.h>
|
|
#include <math.h>
|
|
#include <stdarg.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <strings.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/types.h>
|
|
#include <time.h>
|
|
#include <unistd.h>
|
|
|
|
#define MAX_TEXT 16384
|
|
#define MAX_DIM 4096
|
|
|
|
/* ------------------------------------------------------------------ small io */
|
|
|
|
static int is_dir(const char *p)
|
|
{
|
|
struct stat st;
|
|
|
|
return stat(p, &st) == 0 && S_ISDIR(st.st_mode);
|
|
}
|
|
|
|
static int mkdir_p(const char *path)
|
|
{
|
|
char tmp[PATH_MAX];
|
|
size_t i, len;
|
|
|
|
if (strlen(path) >= sizeof(tmp))
|
|
return -1;
|
|
strcpy(tmp, path);
|
|
len = strlen(tmp);
|
|
for (i = 1; i < len; i++) {
|
|
if (tmp[i] != '/')
|
|
continue;
|
|
tmp[i] = '\0';
|
|
if (!is_dir(tmp) && mkdir(tmp, 0755) != 0 && errno != EEXIST)
|
|
return -1;
|
|
tmp[i] = '/';
|
|
}
|
|
if (!is_dir(tmp) && mkdir(tmp, 0755) != 0 && errno != EEXIST)
|
|
return -1;
|
|
return 0;
|
|
}
|
|
|
|
static char *mem_root(void)
|
|
{
|
|
const char *env = getenv("MEMORYDIR");
|
|
const char *home;
|
|
mcp_buf b;
|
|
|
|
mcp_buf_init(&b);
|
|
if (env != NULL && *env != '\0') {
|
|
mcp_buf_puts(&b, env);
|
|
return b.p;
|
|
}
|
|
home = getenv("HOME");
|
|
if (home == NULL)
|
|
home = "/tmp";
|
|
mcp_buf_printf(&b, "%s/.hermes/memories", home);
|
|
return b.p;
|
|
}
|
|
|
|
static char *read_file(const char *path)
|
|
{
|
|
FILE *f = fopen(path, "rb");
|
|
mcp_buf b;
|
|
char tmp[4096];
|
|
size_t n;
|
|
|
|
if (f == NULL)
|
|
return NULL;
|
|
mcp_buf_init(&b);
|
|
while ((n = fread(tmp, 1, sizeof(tmp), f)) > 0)
|
|
mcp_buf_add(&b, tmp, n);
|
|
fclose(f);
|
|
if (b.p == NULL)
|
|
mcp_buf_add(&b, "", 0);
|
|
return b.p;
|
|
}
|
|
|
|
static int write_file_atomic(const char *path, const char *data)
|
|
{
|
|
mcp_buf tmp;
|
|
FILE *f;
|
|
int rc = 0;
|
|
size_t len = strlen(data);
|
|
|
|
mcp_buf_init(&tmp);
|
|
mcp_buf_printf(&tmp, "%s.tmp.%d", path, (int)getpid());
|
|
f = fopen(tmp.p, "wb");
|
|
if (f == NULL) {
|
|
mcp_buf_free(&tmp);
|
|
return -1;
|
|
}
|
|
if (len > 0 && fwrite(data, 1, len, f) != len)
|
|
rc = -1;
|
|
if (fclose(f) != 0)
|
|
rc = -1;
|
|
if (rc == 0 && rename(tmp.p, path) != 0)
|
|
rc = -1;
|
|
if (rc != 0)
|
|
unlink(tmp.p);
|
|
mcp_buf_free(&tmp);
|
|
return rc;
|
|
}
|
|
|
|
static int valid_id(const char *s)
|
|
{
|
|
const char *p;
|
|
|
|
if (s == NULL || *s == '\0' || strlen(s) > 40)
|
|
return 0;
|
|
for (p = s; *p; p++)
|
|
if (!isalnum((unsigned char)*p) && *p != '-' && *p != '_')
|
|
return 0;
|
|
return 1;
|
|
}
|
|
|
|
static char *mem_path(const char *id)
|
|
{
|
|
char *root = mem_root();
|
|
mcp_buf b;
|
|
|
|
mcp_buf_init(&b);
|
|
mcp_buf_printf(&b, "%s/%s.json", root, id);
|
|
free(root);
|
|
return b.p;
|
|
}
|
|
|
|
/* Wer die Datei anlegt, besitzt die Nummer — zwei Server vergeben nie dieselbe. */
|
|
static char *claim_id(void)
|
|
{
|
|
char *root = mem_root();
|
|
int n;
|
|
|
|
mkdir_p(root);
|
|
for (n = 1; n < 1000000; n++) {
|
|
mcp_buf path;
|
|
int fd;
|
|
|
|
mcp_buf_init(&path);
|
|
mcp_buf_printf(&path, "%s/m%05d.json", root, n);
|
|
fd = open(path.p, O_CREAT | O_EXCL | O_WRONLY, 0644);
|
|
mcp_buf_free(&path);
|
|
if (fd >= 0) {
|
|
char *out = malloc(16);
|
|
|
|
close(fd);
|
|
if (out != NULL)
|
|
snprintf(out, 16, "m%05d", n);
|
|
free(root);
|
|
return out;
|
|
}
|
|
if (errno != EEXIST) {
|
|
free(root);
|
|
return NULL;
|
|
}
|
|
}
|
|
free(root);
|
|
return NULL;
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ embedder */
|
|
|
|
/* Der Embedder ist ein OpenAI-kompatibler Dienst (/v1/embeddings). Er läuft hier auf
|
|
* demselben Rechner; steht er woanders, sagt es $EMBED_URL. */
|
|
static const char *embed_url(void)
|
|
{
|
|
const char *u = getenv("EMBED_URL");
|
|
|
|
return (u != NULL && *u != '\0') ? u : "http://127.0.0.1:8091/v1/embeddings";
|
|
}
|
|
|
|
static const char *embed_model(void)
|
|
{
|
|
const char *m = getenv("EMBED_MODEL");
|
|
|
|
return (m != NULL && *m != '\0') ? m : "nomic-embed-text";
|
|
}
|
|
|
|
/* Rumpf bauen, an curl geben, Antwort lesen.
|
|
*
|
|
* popen kann nur eine Richtung (POSIX kennt nur "r" und "w", "r+" ist undefiniert) —
|
|
* deshalb geht der Rumpf über eine temporäre Datei an curl statt über eine Pipe. Das
|
|
* ist der Unterschied zwischen "der Embedder antwortet nicht" und einem popen, das
|
|
* seine eigene Schreibseite verschluckt. */
|
|
static int embed_fetch(const char *text, double **out_vec, int *out_dim)
|
|
{
|
|
mcp_buf body, cmd;
|
|
/* Die temporäre Datei liegt im Speicherverzeichnis, nicht in /tmp: die Einheit
|
|
* läuft mit ProtectSystem=strict, dort ist /tmp schreibgeschützt — und ein
|
|
* Embedder, der an mkstemp scheitert, sieht wie ein toter Embedder aus. */
|
|
char tmpname[PATH_MAX];
|
|
char *root = mem_root();
|
|
int fd;
|
|
FILE *f = NULL;
|
|
char chunk[4096];
|
|
size_t got;
|
|
mcp_json *v = NULL, *data, *first, *emb;
|
|
size_t n, i;
|
|
double *vec;
|
|
int dim;
|
|
|
|
*out_vec = NULL;
|
|
*out_dim = 0;
|
|
|
|
mcp_buf_init(&body);
|
|
mcp_buf_puts(&body, "{\"model\":\"");
|
|
mcp_json_escape(&body, embed_model());
|
|
mcp_buf_puts(&body, "\",\"input\":\"");
|
|
mcp_json_escape(&body, text);
|
|
mcp_buf_puts(&body, "\"}");
|
|
|
|
{
|
|
mcp_buf dir;
|
|
|
|
mcp_buf_init(&dir);
|
|
mcp_buf_printf(&dir, "%s/.tmp", root);
|
|
mkdir_p(dir.p);
|
|
mcp_buf_free(&dir);
|
|
snprintf(tmpname, sizeof(tmpname), "%s/.tmp/embed-XXXXXX", root);
|
|
}
|
|
free(root);
|
|
fd = mkstemp(tmpname);
|
|
if (fd < 0) {
|
|
mcp_buf_free(&body);
|
|
return -1;
|
|
}
|
|
if (write(fd, body.p, body.len) != (ssize_t)body.len) {
|
|
close(fd);
|
|
unlink(tmpname);
|
|
mcp_buf_free(&body);
|
|
return -1;
|
|
}
|
|
close(fd);
|
|
mcp_buf_free(&body);
|
|
|
|
mcp_buf_init(&cmd);
|
|
mcp_buf_printf(&cmd, "curl -sS -m 20 -H 'Content-Type: application/json' "
|
|
"--data-binary @%s '%s' 2>/dev/null", tmpname, embed_url());
|
|
f = popen(cmd.p, "r");
|
|
mcp_buf_free(&cmd);
|
|
if (f == NULL) {
|
|
unlink(tmpname);
|
|
return -1;
|
|
}
|
|
mcp_buf_init(&body); /* als Lesepuffer wiederverwendet */
|
|
while ((got = fread(chunk, 1, sizeof(chunk), f)) > 0)
|
|
mcp_buf_add(&body, chunk, got);
|
|
pclose(f);
|
|
unlink(tmpname);
|
|
|
|
if (body.p == NULL) {
|
|
mcp_buf_free(&body);
|
|
return -1;
|
|
}
|
|
v = mcp_parse(body.p);
|
|
mcp_buf_free(&body);
|
|
if (v == NULL)
|
|
return -1;
|
|
|
|
data = (mcp_json *)mcp_arg(v, "data");
|
|
first = (data != NULL) ? (mcp_json *)mcp_array_at(data, 0) : NULL;
|
|
emb = (first != NULL) ? (mcp_json *)mcp_arg(first, "embedding") : NULL;
|
|
n = (emb != NULL) ? mcp_array_len(emb) : 0;
|
|
if (n == 0 || n > MAX_DIM) {
|
|
mcp_json_free(v);
|
|
return -1;
|
|
}
|
|
dim = (int)n;
|
|
vec = malloc(sizeof(double) * (size_t)dim);
|
|
if (vec == NULL) {
|
|
mcp_json_free(v);
|
|
return -1;
|
|
}
|
|
for (i = 0; i < n; i++) {
|
|
const mcp_json *e = mcp_array_at(emb, i);
|
|
|
|
vec[i] = (e != NULL && e->t == MCP_NUM) ? e->n : 0.0;
|
|
}
|
|
mcp_json_free(v);
|
|
*out_vec = vec;
|
|
*out_dim = dim;
|
|
return 0;
|
|
}
|
|
|
|
static double cosine(const double *a, const double *b, int dim)
|
|
{
|
|
double dot = 0.0, na = 0.0, nb = 0.0;
|
|
int i;
|
|
|
|
for (i = 0; i < dim; i++) {
|
|
dot += a[i] * b[i];
|
|
na += a[i] * a[i];
|
|
nb += b[i] * b[i];
|
|
}
|
|
if (na <= 0.0 || nb <= 0.0)
|
|
return 0.0;
|
|
return dot / (sqrt(na) * sqrt(nb));
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ record */
|
|
|
|
struct mem {
|
|
char *id;
|
|
char *scope;
|
|
char *text;
|
|
char *tags;
|
|
char *source;
|
|
char *model;
|
|
long created;
|
|
double *vec;
|
|
int dim;
|
|
};
|
|
|
|
static void free_mem(struct mem *m)
|
|
{
|
|
if (m == NULL)
|
|
return;
|
|
free(m->id);
|
|
free(m->scope);
|
|
free(m->text);
|
|
free(m->tags);
|
|
free(m->source);
|
|
free(m->model);
|
|
free(m->vec);
|
|
memset(m, 0, sizeof(*m));
|
|
}
|
|
|
|
static const char *js(const mcp_json *v, const char *key)
|
|
{
|
|
const char *s = mcp_arg_string(v, key);
|
|
|
|
return s != NULL ? s : "";
|
|
}
|
|
|
|
static int mem_load(const char *id, struct mem *out)
|
|
{
|
|
char *path, *raw;
|
|
mcp_json *v;
|
|
const mcp_json *emb;
|
|
|
|
memset(out, 0, sizeof(*out));
|
|
if (!valid_id(id))
|
|
return -1;
|
|
path = mem_path(id);
|
|
raw = read_file(path);
|
|
free(path);
|
|
if (raw == NULL)
|
|
return -1;
|
|
v = mcp_parse(raw);
|
|
free(raw);
|
|
if (v == NULL)
|
|
return -1;
|
|
|
|
out->id = strdup(id);
|
|
out->scope = strdup(js(v, "scope"));
|
|
out->text = strdup(js(v, "text"));
|
|
out->tags = strdup(js(v, "tags"));
|
|
out->source = strdup(js(v, "source"));
|
|
out->model = strdup(js(v, "model"));
|
|
out->created = (long)mcp_arg_num(v, "created", 0);
|
|
emb = mcp_arg(v, "embedding");
|
|
out->dim = (emb != NULL) ? (int)mcp_array_len(emb) : 0;
|
|
if (out->dim > 0 && out->dim <= MAX_DIM) {
|
|
size_t i;
|
|
|
|
out->vec = malloc(sizeof(double) * (size_t)out->dim);
|
|
if (out->vec == NULL) {
|
|
out->dim = 0;
|
|
} else {
|
|
for (i = 0; i < (size_t)out->dim; i++) {
|
|
const mcp_json *e = mcp_array_at(emb, i);
|
|
|
|
out->vec[i] = (e != NULL && e->t == MCP_NUM) ? e->n : 0.0;
|
|
}
|
|
}
|
|
}
|
|
mcp_json_free(v);
|
|
if (out->id == NULL || out->scope == NULL || out->text == NULL ||
|
|
out->tags == NULL || out->source == NULL || out->model == NULL) {
|
|
free_mem(out);
|
|
return -1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static void put_str(mcp_buf *b, const char *key, const char *val)
|
|
{
|
|
mcp_buf_printf(b, "\"%s\":\"", key);
|
|
mcp_json_escape(b, val != NULL ? val : "");
|
|
mcp_buf_puts(b, "\"");
|
|
}
|
|
|
|
static int mem_save(const struct mem *m)
|
|
{
|
|
mcp_buf b;
|
|
char *path;
|
|
int rc, i;
|
|
|
|
mcp_buf_init(&b);
|
|
mcp_buf_puts(&b, "{\n ");
|
|
put_str(&b, "id", m->id);
|
|
mcp_buf_puts(&b, ",\n ");
|
|
put_str(&b, "scope", m->scope);
|
|
mcp_buf_puts(&b, ",\n ");
|
|
put_str(&b, "text", m->text);
|
|
mcp_buf_puts(&b, ",\n ");
|
|
put_str(&b, "tags", m->tags);
|
|
mcp_buf_puts(&b, ",\n ");
|
|
put_str(&b, "source", m->source);
|
|
mcp_buf_puts(&b, ",\n ");
|
|
put_str(&b, "model", m->model);
|
|
mcp_buf_printf(&b, ",\n \"created\":%ld", m->created);
|
|
mcp_buf_puts(&b, ",\n \"embedding\":[");
|
|
for (i = 0; i < m->dim; i++)
|
|
mcp_buf_printf(&b, "%s%.7f", i ? "," : "", m->vec[i]);
|
|
mcp_buf_puts(&b, "]\n}\n");
|
|
|
|
path = mem_path(m->id);
|
|
rc = write_file_atomic(path, b.p != NULL ? b.p : "{}");
|
|
free(path);
|
|
mcp_buf_free(&b);
|
|
return rc;
|
|
}
|
|
|
|
/* Alle IDs im Speicher, sortiert (die Sortierung ist die Reihenfolge der Namen). */
|
|
static int list_ids(char ***out, size_t *out_n)
|
|
{
|
|
char *root = mem_root();
|
|
DIR *d;
|
|
struct dirent *e;
|
|
char **ids = NULL;
|
|
size_t n = 0, cap = 0;
|
|
|
|
*out = NULL;
|
|
*out_n = 0;
|
|
d = opendir(root);
|
|
if (d == NULL) {
|
|
free(root);
|
|
return -1;
|
|
}
|
|
while ((e = readdir(d)) != NULL) {
|
|
size_t len = strlen(e->d_name);
|
|
char *id;
|
|
|
|
if (len < 6 || strcmp(e->d_name + len - 5, ".json") != 0)
|
|
continue;
|
|
id = strndup(e->d_name, len - 5);
|
|
if (id == NULL)
|
|
continue;
|
|
if (n == cap) {
|
|
size_t ncap = cap ? cap * 2 : 32;
|
|
char **grown = realloc(ids, sizeof(char *) * ncap);
|
|
|
|
if (grown == NULL) {
|
|
free(id);
|
|
continue;
|
|
}
|
|
ids = grown;
|
|
cap = ncap;
|
|
}
|
|
ids[n++] = id;
|
|
}
|
|
closedir(d);
|
|
free(root);
|
|
*out = ids;
|
|
*out_n = n;
|
|
return 0;
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ helper */
|
|
|
|
static const char *scope_arg(const mcp_json *args)
|
|
{
|
|
const char *s = mcp_arg_string(args, "scope");
|
|
|
|
return (s != NULL) ? s : "";
|
|
}
|
|
|
|
static int scope_matches(const char *task_scope, const char *want)
|
|
{
|
|
size_t len;
|
|
|
|
if (want == NULL || *want == '\0')
|
|
return 1; /* kein Filter: alles */
|
|
len = strlen(want);
|
|
if (strncmp(task_scope, want, len) != 0)
|
|
return 0;
|
|
/* "van" trifft "van" und "van/regeln", nicht "vansinnig" */
|
|
return task_scope[len] == '\0' || task_scope[len] == '/';
|
|
}
|
|
|
|
static void say(mcp_conn *c, const char *fmt, ...)
|
|
{
|
|
char line[2048];
|
|
va_list ap;
|
|
|
|
va_start(ap, fmt);
|
|
vsnprintf(line, sizeof(line), fmt, ap);
|
|
va_end(ap);
|
|
mcp_reply_text(c, line);
|
|
}
|
|
|
|
struct hit {
|
|
struct mem m;
|
|
double score;
|
|
};
|
|
|
|
static int cmp_hit(const void *pa, const void *pb)
|
|
{
|
|
const struct hit *a = pa;
|
|
const struct hit *b = pb;
|
|
|
|
if (a->score < b->score)
|
|
return 1;
|
|
if (a->score > b->score)
|
|
return -1;
|
|
return strcmp(a->m.id, b->m.id);
|
|
}
|
|
|
|
/* Teilstringsuche, wenn kein Vektor da ist (kein Embedder oder alter Eintrag ohne
|
|
* Vektor). strcasestr ist GNU, also selbst geschrieben. */
|
|
static int text_has(const char *haystack, const char *needle)
|
|
{
|
|
size_t nlen;
|
|
|
|
if (needle == NULL || *needle == '\0')
|
|
return 1;
|
|
nlen = strlen(needle);
|
|
for (const char *p = haystack; *p != '\0'; p++) {
|
|
size_t i = 0;
|
|
|
|
while (i < nlen && p[i] != '\0' &&
|
|
tolower((unsigned char)p[i]) == tolower((unsigned char)needle[i]))
|
|
i++;
|
|
if (i == nlen)
|
|
return 1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static void fmt_mem(mcp_buf *b, const struct mem *m, double score, int with_score)
|
|
{
|
|
mcp_buf_printf(b, "%s [%s]", m->id, m->scope);
|
|
if (with_score)
|
|
mcp_buf_printf(b, " score=%.3f", score);
|
|
mcp_buf_printf(b, " (%s)", m->model);
|
|
if (m->tags != NULL && *m->tags != '\0')
|
|
mcp_buf_printf(b, " tags=%s", m->tags);
|
|
mcp_buf_puts(b, "\n ");
|
|
mcp_buf_puts(b, m->text);
|
|
mcp_buf_puts(b, "\n");
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ tools */
|
|
|
|
static void t_add(mcp_conn *c, const mcp_json *args, void *user)
|
|
{
|
|
const char *scope = scope_arg(args);
|
|
const char *text = mcp_arg_string(args, "text");
|
|
const char *tags = mcp_arg_string(args, "tags");
|
|
const char *source = mcp_arg_string(args, "source");
|
|
struct mem m;
|
|
double *vec = NULL;
|
|
int dim = 0;
|
|
int embedded;
|
|
char *id;
|
|
|
|
(void)user;
|
|
if (text == NULL || *text == '\0') {
|
|
mcp_reply_error(c, "memory_add needs a text");
|
|
return;
|
|
}
|
|
if (*scope == '\0')
|
|
scope = "general";
|
|
if (strlen(text) > MAX_TEXT) {
|
|
mcp_reply_error(c, "text too long (limit 16384 bytes) - store the conclusion, "
|
|
"not the transcript");
|
|
return;
|
|
}
|
|
id = claim_id();
|
|
if (id == NULL) {
|
|
mcp_reply_error(c, "could not allocate an id under the memory directory");
|
|
return;
|
|
}
|
|
embedded = (embed_fetch(text, &vec, &dim) == 0);
|
|
|
|
memset(&m, 0, sizeof(m));
|
|
m.id = id;
|
|
m.scope = (char *)scope;
|
|
m.text = (char *)text;
|
|
m.tags = (char *)(tags != NULL ? tags : "");
|
|
m.source = (char *)(source != NULL ? source : "");
|
|
m.model = (char *)(embedded ? embed_model() : "none");
|
|
m.created = (long)time(NULL);
|
|
m.vec = vec;
|
|
m.dim = dim;
|
|
|
|
if (mem_save(&m) != 0) {
|
|
free(vec);
|
|
mcp_reply_error(c, "could not write the memory file");
|
|
return;
|
|
}
|
|
if (embedded)
|
|
say(c, "stored %s in %s (embedded, %d dimensions)", id, scope, dim);
|
|
else
|
|
say(c, "stored %s in %s WITHOUT embedding: the embedder at %s did not answer. "
|
|
"Search will fall back to substrings for this entry.", id, scope,
|
|
embed_url());
|
|
free(vec);
|
|
free(id);
|
|
}
|
|
|
|
static void t_search(mcp_conn *c, const mcp_json *args, void *user)
|
|
{
|
|
const char *query = mcp_arg_string(args, "query");
|
|
const char *scope = scope_arg(args);
|
|
int limit = mcp_arg_int(args, "limit", 5);
|
|
char **ids = NULL;
|
|
size_t n = 0, i;
|
|
struct hit *hits = NULL;
|
|
size_t nhits = 0;
|
|
double *qvec = NULL;
|
|
int qdim = 0;
|
|
int semantic;
|
|
mcp_buf b;
|
|
|
|
(void)user;
|
|
if (query == NULL || *query == '\0') {
|
|
mcp_reply_error(c, "memory_search needs a query");
|
|
return;
|
|
}
|
|
if (limit <= 0 || limit > 50)
|
|
limit = 5;
|
|
|
|
semantic = (embed_fetch(query, &qvec, &qdim) == 0);
|
|
if (list_ids(&ids, &n) != 0) {
|
|
say(c, "no memories yet (nothing stored under %s)", mem_root());
|
|
free(qvec);
|
|
return;
|
|
}
|
|
hits = calloc(n ? n : 1, sizeof(*hits));
|
|
if (hits == NULL) {
|
|
mcp_reply_error(c, "out of memory");
|
|
goto out;
|
|
}
|
|
for (i = 0; i < n; i++) {
|
|
struct mem m;
|
|
|
|
if (mem_load(ids[i], &m) != 0)
|
|
continue;
|
|
if (!scope_matches(m.scope, scope)) {
|
|
free_mem(&m);
|
|
continue;
|
|
}
|
|
if (semantic && m.dim == qdim) {
|
|
hits[nhits].m = m;
|
|
hits[nhits].score = cosine(qvec, m.vec, qdim);
|
|
nhits++;
|
|
} else if (!semantic && text_has(m.text, query)) {
|
|
hits[nhits].m = m;
|
|
hits[nhits].score = 0.0; /* kein Maß, nur "kommt vor" */
|
|
nhits++;
|
|
} else {
|
|
free_mem(&m);
|
|
}
|
|
}
|
|
qsort(hits, nhits, sizeof(*hits), cmp_hit);
|
|
|
|
mcp_buf_init(&b);
|
|
if (nhits == 0) {
|
|
mcp_buf_printf(&b, "nothing found for \"%s\"%s%s\n", query,
|
|
*scope ? " in scope " : "", *scope ? scope : "");
|
|
} else {
|
|
size_t show = (size_t)limit < nhits ? (size_t)limit : nhits;
|
|
|
|
mcp_buf_printf(&b, "%zu hit(s) for \"%s\"%s%s%s%s:\n", show, query,
|
|
*scope ? " in " : "", *scope ? scope : "",
|
|
semantic ? "" : " (substring match - the embedder did not answer)",
|
|
"");
|
|
for (i = 0; i < show; i++)
|
|
fmt_mem(&b, &hits[i].m, hits[i].score, semantic);
|
|
}
|
|
mcp_reply_text(c, b.p != NULL ? b.p : "nothing found");
|
|
mcp_buf_free(&b);
|
|
out:
|
|
for (i = 0; i < nhits; i++)
|
|
free_mem(&hits[i].m);
|
|
free(hits);
|
|
for (i = 0; i < n; i++)
|
|
free(ids[i]);
|
|
free(ids);
|
|
free(qvec);
|
|
}
|
|
|
|
static void t_list(mcp_conn *c, const mcp_json *args, void *user)
|
|
{
|
|
const char *scope = scope_arg(args);
|
|
int limit = mcp_arg_int(args, "limit", 20);
|
|
char **ids = NULL;
|
|
size_t n = 0, i, shown = 0;
|
|
mcp_buf b;
|
|
|
|
(void)user;
|
|
if (limit <= 0 || limit > 200)
|
|
limit = 20;
|
|
if (list_ids(&ids, &n) != 0 || n == 0) {
|
|
say(c, "no memories yet (nothing stored under %s)", mem_root());
|
|
goto out;
|
|
}
|
|
mcp_buf_init(&b);
|
|
for (i = n; i > 0 && shown < (size_t)limit; i--) {
|
|
struct mem m;
|
|
|
|
if (mem_load(ids[i - 1], &m) != 0)
|
|
continue;
|
|
if (!scope_matches(m.scope, scope)) {
|
|
free_mem(&m);
|
|
continue;
|
|
}
|
|
fmt_mem(&b, &m, 0.0, 0);
|
|
shown++;
|
|
free_mem(&m);
|
|
}
|
|
if (shown == 0)
|
|
mcp_buf_printf(&b, "nothing in scope \"%s\"\n", *scope ? scope : "*");
|
|
else if (shown == (size_t)limit && n > shown)
|
|
mcp_buf_printf(&b, "(%zu of %zu, newest first)\n", shown, n);
|
|
mcp_reply_text(c, b.p != NULL ? b.p : "");
|
|
mcp_buf_free(&b);
|
|
out:
|
|
for (i = 0; i < n; i++)
|
|
free(ids[i]);
|
|
free(ids);
|
|
}
|
|
|
|
static void t_get(mcp_conn *c, const mcp_json *args, void *user)
|
|
{
|
|
const char *id = mcp_arg_string(args, "id");
|
|
struct mem m;
|
|
mcp_buf b;
|
|
|
|
(void)user;
|
|
if (id == NULL || mem_load(id, &m) != 0) {
|
|
mcp_reply_error(c, "no such memory");
|
|
return;
|
|
}
|
|
mcp_buf_init(&b);
|
|
fmt_mem(&b, &m, 0.0, 0);
|
|
mcp_buf_printf(&b, " created=%ld source=%s\n", m.created, m.source);
|
|
mcp_reply_text(c, b.p != NULL ? b.p : "");
|
|
mcp_buf_free(&b);
|
|
free_mem(&m);
|
|
}
|
|
|
|
static void t_update(mcp_conn *c, const mcp_json *args, void *user)
|
|
{
|
|
const char *id = mcp_arg_string(args, "id");
|
|
const char *text = mcp_arg_string(args, "text");
|
|
const char *tags = mcp_arg_string(args, "tags");
|
|
const char *scope = mcp_arg_string(args, "scope");
|
|
struct mem m;
|
|
int changed = 0;
|
|
|
|
(void)user;
|
|
if (id == NULL || mem_load(id, &m) != 0) {
|
|
mcp_reply_error(c, "no such memory");
|
|
return;
|
|
}
|
|
if (text != NULL && *text != '\0') {
|
|
double *vec = NULL;
|
|
int dim = 0;
|
|
|
|
free(m.text);
|
|
m.text = strdup(text);
|
|
if (embed_fetch(text, &vec, &dim) == 0) {
|
|
free(m.vec);
|
|
m.vec = vec;
|
|
m.dim = dim;
|
|
free(m.model);
|
|
m.model = strdup(embed_model());
|
|
} else {
|
|
free(m.vec);
|
|
m.vec = NULL;
|
|
m.dim = 0;
|
|
free(m.model);
|
|
m.model = strdup("none");
|
|
}
|
|
changed = 1;
|
|
}
|
|
if (tags != NULL) {
|
|
free(m.tags);
|
|
m.tags = strdup(tags);
|
|
changed = 1;
|
|
}
|
|
if (scope != NULL && *scope != '\0') {
|
|
free(m.scope);
|
|
m.scope = strdup(scope);
|
|
changed = 1;
|
|
}
|
|
if (!changed) {
|
|
say(c, "nothing to change: give text, tags or scope");
|
|
free_mem(&m);
|
|
return;
|
|
}
|
|
if (mem_save(&m) != 0) {
|
|
mcp_reply_error(c, "could not write the memory file");
|
|
free_mem(&m);
|
|
return;
|
|
}
|
|
say(c, "updated %s (embedding: %s)", id, m.dim > 0 ? "yes" : "no");
|
|
free_mem(&m);
|
|
}
|
|
|
|
static void t_delete(mcp_conn *c, const mcp_json *args, void *user)
|
|
{
|
|
const char *id = mcp_arg_string(args, "id");
|
|
char *path;
|
|
|
|
(void)user;
|
|
if (id == NULL || !valid_id(id)) {
|
|
mcp_reply_error(c, "no such memory");
|
|
return;
|
|
}
|
|
path = mem_path(id);
|
|
if (unlink(path) != 0) {
|
|
free(path);
|
|
mcp_reply_error(c, "no such memory");
|
|
return;
|
|
}
|
|
free(path);
|
|
say(c, "deleted %s", id);
|
|
}
|
|
|
|
static void t_scopes(mcp_conn *c, const mcp_json *args, void *user)
|
|
{
|
|
char **ids = NULL;
|
|
size_t n = 0, i;
|
|
struct { char scope[128]; int count; } seen[256];
|
|
int nseen = 0;
|
|
mcp_buf b;
|
|
|
|
(void)args;
|
|
(void)user;
|
|
if (list_ids(&ids, &n) != 0 || n == 0) {
|
|
say(c, "no memories yet");
|
|
goto out;
|
|
}
|
|
for (i = 0; i < n; i++) {
|
|
struct mem m;
|
|
int j, found = -1;
|
|
|
|
if (mem_load(ids[i], &m) != 0)
|
|
continue;
|
|
for (j = 0; j < nseen; j++)
|
|
if (strcmp(seen[j].scope, m.scope) == 0) {
|
|
found = j;
|
|
break;
|
|
}
|
|
if (found < 0 && nseen < 256) {
|
|
found = nseen++;
|
|
snprintf(seen[found].scope, sizeof(seen[found].scope), "%s", m.scope);
|
|
seen[found].count = 0;
|
|
}
|
|
if (found >= 0)
|
|
seen[found].count++;
|
|
free_mem(&m);
|
|
}
|
|
mcp_buf_init(&b);
|
|
mcp_buf_printf(&b, "%zu memories in %d scope(s):\n", n, nseen);
|
|
for (i = 0; i < (size_t)nseen; i++)
|
|
mcp_buf_printf(&b, " %-32s %d\n", seen[i].scope, seen[i].count);
|
|
mcp_reply_text(c, b.p != NULL ? b.p : "");
|
|
mcp_buf_free(&b);
|
|
out:
|
|
for (i = 0; i < n; i++)
|
|
free(ids[i]);
|
|
free(ids);
|
|
}
|
|
|
|
|
|
/* ==========================================================================
|
|
* Wissensbasis: benannte Sammlungen, sonst wie Erinnerungen
|
|
*
|
|
* Eine Wissensbasis ist ein Name mit einem Verzeichnis darunter, und darin liegen
|
|
* Seiten wie Erinnerungen: Titel, Text, Vektor. Der Unterschied ist der Zweck —
|
|
* Erinnerungen sind das, was ein Agent beiläufig behält; eine Wissensbasis ist das,
|
|
* was ein Mensch aufgeschrieben hat, damit es nachgelesen wird.
|
|
*
|
|
* $MEMORYDIR/kb/<slug>/kb.json {"name","slug","description","created"}
|
|
* $MEMORYDIR/kb/<slug>/e00001.json {"id","title","text","tags","source",
|
|
* "created","updated","model","embedding",
|
|
* "history":[{"text","updated"}]}
|
|
*
|
|
* Schreiben mit demselben Titel überschreibt die Seite nicht stillschweigend: der alte
|
|
* Text wandert in `history` (fünf Fassungen), und die Antwort sagt, dass es eine
|
|
* Aktualisierung war. Ein Wiki ohne jede Spur der vorherigen Fassung ist keins.
|
|
* ========================================================================== */
|
|
|
|
#define MAX_KB 512
|
|
#define MAX_HISTORY 5
|
|
|
|
struct entry {
|
|
char *id;
|
|
char *title;
|
|
char *text;
|
|
char *tags;
|
|
char *source;
|
|
char *model;
|
|
long created;
|
|
long updated;
|
|
double *vec;
|
|
int dim;
|
|
/* Ältere Fassungen, nur beim Lesen/Schreiben gebraucht. */
|
|
int nhist;
|
|
long hist_at[MAX_HISTORY];
|
|
char *hist_text[MAX_HISTORY];
|
|
};
|
|
|
|
static void free_entry(struct entry *e)
|
|
{
|
|
int i;
|
|
|
|
if (e == NULL)
|
|
return;
|
|
free(e->id);
|
|
free(e->title);
|
|
free(e->text);
|
|
free(e->tags);
|
|
free(e->source);
|
|
free(e->model);
|
|
free(e->vec);
|
|
for (i = 0; i < e->nhist; i++)
|
|
free(e->hist_text[i]);
|
|
memset(e, 0, sizeof(*e));
|
|
}
|
|
|
|
/* Ein Treffer über mehrere Basen: Basis, Seite, Bewertung. Benannt, weil ein
|
|
* anonymer struct-Typ sich nicht zuweisen lässt (und Sortieren ist Zuweisen). */
|
|
struct kbhit {
|
|
char slug[MAX_KB];
|
|
struct entry e;
|
|
double score;
|
|
};
|
|
|
|
/* Name → Verzeichnisname: Kleinbuchstaben, alles Fremde zu "-", keine Doppelpunkte. */
|
|
static void slugify(const char *name, char *out, size_t outlen)
|
|
{
|
|
size_t i = 0;
|
|
int last_dash = 0;
|
|
|
|
for (const char *p = name; *p != '\0' && i + 1 < outlen; p++) {
|
|
unsigned char ch = (unsigned char)*p;
|
|
|
|
if (isalnum(ch)) {
|
|
out[i++] = (char)tolower(ch);
|
|
last_dash = 0;
|
|
} else if (!last_dash) {
|
|
out[i++] = '-';
|
|
last_dash = 1;
|
|
}
|
|
}
|
|
while (i > 0 && out[i - 1] == '-')
|
|
i--;
|
|
out[i] = '\0';
|
|
}
|
|
|
|
static char *kb_root(void)
|
|
{
|
|
char *root = mem_root();
|
|
mcp_buf b;
|
|
|
|
mcp_buf_init(&b);
|
|
mcp_buf_printf(&b, "%s/kb", root);
|
|
free(root);
|
|
return b.p;
|
|
}
|
|
|
|
static char *kb_dir(const char *slug)
|
|
{
|
|
char *root = kb_root();
|
|
mcp_buf b;
|
|
|
|
mcp_buf_init(&b);
|
|
mcp_buf_printf(&b, "%s/%s", root, slug);
|
|
free(root);
|
|
return b.p;
|
|
}
|
|
|
|
static char *kb_file(const char *slug, const char *leaf)
|
|
{
|
|
char *dir = kb_dir(slug);
|
|
mcp_buf b;
|
|
|
|
mcp_buf_init(&b);
|
|
mcp_buf_printf(&b, "%s/%s", dir, leaf);
|
|
free(dir);
|
|
return b.p;
|
|
}
|
|
|
|
/* Existiert die Basis? Name und Beschreibung kommen aus kb.json. */
|
|
static int kb_meta(const char *slug, char *name, size_t namelen, char *desc, size_t desclen)
|
|
{
|
|
char *path = kb_file(slug, "kb.json");
|
|
char *raw = read_file(path);
|
|
mcp_json *v;
|
|
|
|
free(path);
|
|
if (raw == NULL)
|
|
return -1;
|
|
v = mcp_parse(raw);
|
|
free(raw);
|
|
if (v == NULL)
|
|
return -1;
|
|
snprintf(name, namelen, "%s", js(v, "name"));
|
|
if (desc != NULL)
|
|
snprintf(desc, desclen, "%s", js(v, "description"));
|
|
mcp_json_free(v);
|
|
return 0;
|
|
}
|
|
|
|
static int kb_save_meta(const char *slug, const char *name, const char *desc)
|
|
{
|
|
char *path = kb_file(slug, "kb.json");
|
|
mcp_buf b;
|
|
int rc;
|
|
|
|
mcp_buf_init(&b);
|
|
mcp_buf_puts(&b, "{\n ");
|
|
put_str(&b, "name", name);
|
|
mcp_buf_puts(&b, ",\n ");
|
|
put_str(&b, "slug", slug);
|
|
mcp_buf_puts(&b, ",\n ");
|
|
put_str(&b, "description", desc != NULL ? desc : "");
|
|
mcp_buf_printf(&b, ",\n \"created\":%ld\n}\n", (long)time(NULL));
|
|
rc = write_file_atomic(path, b.p != NULL ? b.p : "{}");
|
|
mcp_buf_free(&b);
|
|
free(path);
|
|
return rc;
|
|
}
|
|
|
|
/* Alle Basen: Verzeichnisse unter kb/ mit kb.json. */
|
|
static int kb_list_all(char slugs[][MAX_KB], int max, int *count)
|
|
{
|
|
char *root = kb_root();
|
|
DIR *d;
|
|
struct dirent *de;
|
|
|
|
*count = 0;
|
|
d = opendir(root);
|
|
if (d == NULL) {
|
|
free(root);
|
|
return -1;
|
|
}
|
|
while ((de = readdir(d)) != NULL && *count < max) {
|
|
char *path;
|
|
FILE *f;
|
|
|
|
if (de->d_name[0] == '.')
|
|
continue;
|
|
path = kb_file(de->d_name, "kb.json");
|
|
f = fopen(path, "r");
|
|
free(path);
|
|
if (f == NULL)
|
|
continue; /* kein fertiges Verzeichnis */
|
|
fclose(f);
|
|
snprintf(slugs[*count], MAX_KB, "%s", de->d_name);
|
|
(*count)++;
|
|
}
|
|
closedir(d);
|
|
free(root);
|
|
/* Verzeichnisreihenfolge ist nicht stabil; sortieren, damit die Ausgabe es ist. */
|
|
for (int i = 1; i < *count; i++)
|
|
for (int j = i; j > 0 && strcmp(slugs[j - 1], slugs[j]) > 0; j--) {
|
|
char tmp[MAX_KB];
|
|
|
|
snprintf(tmp, sizeof(tmp), "%s", slugs[j]);
|
|
snprintf(slugs[j], MAX_KB, "%s", slugs[j - 1]);
|
|
snprintf(slugs[j - 1], MAX_KB, "%s", tmp);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static int kb_entry_ids(const char *slug, char ***out, size_t *out_n)
|
|
{
|
|
char *dir = kb_dir(slug);
|
|
DIR *d;
|
|
struct dirent *de;
|
|
char **ids = NULL;
|
|
size_t n = 0, cap = 0;
|
|
|
|
*out = NULL;
|
|
*out_n = 0;
|
|
d = opendir(dir);
|
|
free(dir);
|
|
if (d == NULL)
|
|
return -1;
|
|
while ((de = readdir(d)) != NULL) {
|
|
size_t len = strlen(de->d_name);
|
|
char *id;
|
|
|
|
if (len < 6 || strncmp(de->d_name, "e", 1) != 0 ||
|
|
strcmp(de->d_name + len - 5, ".json") != 0)
|
|
continue;
|
|
id = strndup(de->d_name, len - 5);
|
|
if (id == NULL)
|
|
continue;
|
|
if (n == cap) {
|
|
size_t ncap = cap ? cap * 2 : 32;
|
|
char **grown = realloc(ids, sizeof(char *) * ncap);
|
|
|
|
if (grown == NULL) {
|
|
free(id);
|
|
continue;
|
|
}
|
|
ids = grown;
|
|
cap = ncap;
|
|
}
|
|
ids[n++] = id;
|
|
}
|
|
closedir(d);
|
|
*out = ids;
|
|
*out_n = n;
|
|
return 0;
|
|
}
|
|
|
|
static char *kb_claim_entry_id(const char *slug)
|
|
{
|
|
char *dir = kb_dir(slug);
|
|
int n;
|
|
|
|
mkdir_p(dir);
|
|
for (n = 1; n < 100000; n++) {
|
|
mcp_buf path;
|
|
int fd;
|
|
|
|
mcp_buf_init(&path);
|
|
mcp_buf_printf(&path, "%s/e%05d.json", dir, n);
|
|
fd = open(path.p, O_CREAT | O_EXCL | O_WRONLY, 0644);
|
|
mcp_buf_free(&path);
|
|
if (fd >= 0) {
|
|
char *out = malloc(16);
|
|
|
|
close(fd);
|
|
if (out != NULL)
|
|
snprintf(out, 16, "e%05d", n);
|
|
free(dir);
|
|
return out;
|
|
}
|
|
if (errno != EEXIST) {
|
|
free(dir);
|
|
return NULL;
|
|
}
|
|
}
|
|
free(dir);
|
|
return NULL;
|
|
}
|
|
|
|
static int entry_load(const char *slug, const char *id, struct entry *out)
|
|
{
|
|
char *leaf, *path, *raw;
|
|
mcp_json *v;
|
|
const mcp_json *emb, *hist;
|
|
|
|
memset(out, 0, sizeof(*out));
|
|
if (!valid_id(id))
|
|
return -1;
|
|
leaf = NULL;
|
|
{
|
|
mcp_buf b;
|
|
|
|
mcp_buf_init(&b);
|
|
mcp_buf_printf(&b, "%s.json", id);
|
|
leaf = b.p;
|
|
}
|
|
path = kb_file(slug, leaf);
|
|
free(leaf);
|
|
raw = read_file(path);
|
|
free(path);
|
|
if (raw == NULL)
|
|
return -1;
|
|
v = mcp_parse(raw);
|
|
free(raw);
|
|
if (v == NULL)
|
|
return -1;
|
|
|
|
out->id = strdup(id);
|
|
out->title = strdup(js(v, "title"));
|
|
out->text = strdup(js(v, "text"));
|
|
out->tags = strdup(js(v, "tags"));
|
|
out->source = strdup(js(v, "source"));
|
|
out->model = strdup(js(v, "model"));
|
|
out->created = (long)mcp_arg_num(v, "created", 0);
|
|
out->updated = (long)mcp_arg_num(v, "updated", out->created);
|
|
emb = mcp_arg(v, "embedding");
|
|
out->dim = (emb != NULL) ? (int)mcp_array_len(emb) : 0;
|
|
if (out->dim > 0 && out->dim <= MAX_DIM) {
|
|
size_t i;
|
|
|
|
out->vec = malloc(sizeof(double) * (size_t)out->dim);
|
|
if (out->vec == NULL) {
|
|
out->dim = 0;
|
|
} else {
|
|
for (i = 0; i < (size_t)out->dim; i++) {
|
|
const mcp_json *e = mcp_array_at(emb, i);
|
|
|
|
out->vec[i] = (e != NULL && e->t == MCP_NUM) ? e->n : 0.0;
|
|
}
|
|
}
|
|
}
|
|
hist = mcp_arg(v, "history");
|
|
if (hist != NULL) {
|
|
size_t nh = mcp_array_len(hist);
|
|
|
|
for (size_t i = 0; i < nh && out->nhist < MAX_HISTORY; i++) {
|
|
const mcp_json *h = mcp_array_at(hist, i);
|
|
|
|
if (h == NULL)
|
|
continue;
|
|
out->hist_text[out->nhist] = strdup(js(h, "text"));
|
|
out->hist_at[out->nhist] = (long)mcp_arg_num(h, "updated", 0);
|
|
if (out->hist_text[out->nhist] != NULL)
|
|
out->nhist++;
|
|
}
|
|
}
|
|
mcp_json_free(v);
|
|
if (out->id == NULL || out->title == NULL || out->text == NULL ||
|
|
out->tags == NULL || out->source == NULL || out->model == NULL) {
|
|
free_entry(out);
|
|
return -1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static int entry_save(const char *slug, const struct entry *e)
|
|
{
|
|
char *leaf, *path;
|
|
mcp_buf b;
|
|
int rc, i;
|
|
|
|
mcp_buf_init(&b);
|
|
mcp_buf_puts(&b, "{\n ");
|
|
put_str(&b, "id", e->id);
|
|
mcp_buf_puts(&b, ",\n ");
|
|
put_str(&b, "title", e->title);
|
|
mcp_buf_puts(&b, ",\n ");
|
|
put_str(&b, "text", e->text);
|
|
mcp_buf_puts(&b, ",\n ");
|
|
put_str(&b, "tags", e->tags);
|
|
mcp_buf_puts(&b, ",\n ");
|
|
put_str(&b, "source", e->source);
|
|
mcp_buf_puts(&b, ",\n ");
|
|
put_str(&b, "model", e->model);
|
|
mcp_buf_printf(&b, ",\n \"created\":%ld,\n \"updated\":%ld", e->created, e->updated);
|
|
mcp_buf_puts(&b, ",\n \"embedding\":[");
|
|
for (i = 0; i < e->dim; i++)
|
|
mcp_buf_printf(&b, "%s%.7f", i ? "," : "", e->vec[i]);
|
|
mcp_buf_puts(&b, "],\n \"history\":[");
|
|
for (i = 0; i < e->nhist; i++) {
|
|
mcp_buf_puts(&b, i ? ",{" : "{");
|
|
put_str(&b, "text", e->hist_text[i]);
|
|
mcp_buf_printf(&b, ",\"updated\":%ld}", e->hist_at[i]);
|
|
}
|
|
mcp_buf_puts(&b, "]\n}\n");
|
|
|
|
{
|
|
mcp_buf leaf_buf;
|
|
|
|
mcp_buf_init(&leaf_buf);
|
|
mcp_buf_printf(&leaf_buf, "%s.json", e->id);
|
|
leaf = leaf_buf.p;
|
|
}
|
|
path = kb_file(slug, leaf != NULL ? leaf : "e.json");
|
|
free(leaf);
|
|
rc = write_file_atomic(path, b.p != NULL ? b.p : "{}");
|
|
free(path);
|
|
mcp_buf_free(&b);
|
|
return rc;
|
|
}
|
|
|
|
/* Seite mit diesem Titel (ohne Rücksicht auf Groß/klein) oder NULL. */
|
|
static char *find_by_title(const char *slug, const char *title)
|
|
{
|
|
char **ids = NULL;
|
|
size_t n = 0, i;
|
|
char *found = NULL;
|
|
|
|
if (kb_entry_ids(slug, &ids, &n) != 0)
|
|
return NULL;
|
|
for (i = 0; i < n && found == NULL; i++) {
|
|
struct entry e;
|
|
|
|
if (entry_load(slug, ids[i], &e) != 0)
|
|
continue;
|
|
if (strcasecmp(e.title, title) == 0)
|
|
found = strdup(ids[i]);
|
|
free_entry(&e);
|
|
}
|
|
for (i = 0; i < n; i++)
|
|
free(ids[i]);
|
|
free(ids);
|
|
return found;
|
|
}
|
|
|
|
static void fmt_entry_ref(mcp_buf *b, const char *slug, const struct entry *e, double score)
|
|
{
|
|
mcp_buf_printf(b, "%s/%s [%s]", slug, e->id, e->title);
|
|
if (score >= 0.0)
|
|
mcp_buf_printf(b, " score=%.3f", score);
|
|
if (e->tags != NULL && *e->tags != '\0')
|
|
mcp_buf_printf(b, " tags=%s", e->tags);
|
|
mcp_buf_puts(b, "\n ");
|
|
if (strlen(e->text) > 400)
|
|
mcp_buf_add(b, e->text, 400);
|
|
else
|
|
mcp_buf_puts(b, e->text);
|
|
if (strlen(e->text) > 400)
|
|
mcp_buf_puts(b, " …");
|
|
mcp_buf_puts(b, "\n");
|
|
}
|
|
|
|
static void t_kb_create(mcp_conn *c, const mcp_json *args, void *user)
|
|
{
|
|
const char *name = mcp_arg_string(args, "name");
|
|
const char *desc = mcp_arg_string(args, "description");
|
|
char slug[MAX_KB], existing[MAX_KB];
|
|
|
|
(void)user;
|
|
if (name == NULL || *name == '\0') {
|
|
mcp_reply_error(c, "kb_create needs a name");
|
|
return;
|
|
}
|
|
slugify(name, slug, sizeof(slug));
|
|
if (slug[0] == '\0') {
|
|
mcp_reply_error(c, "that name has no usable characters for a directory");
|
|
return;
|
|
}
|
|
if (kb_meta(slug, existing, sizeof(existing), NULL, 0) == 0) {
|
|
say(c, "knowledge base \"%s\" already exists (%s) - write into it with kb_write",
|
|
existing, slug);
|
|
return;
|
|
}
|
|
{
|
|
char *dir = kb_dir(slug);
|
|
|
|
mkdir_p(dir);
|
|
free(dir);
|
|
}
|
|
if (kb_save_meta(slug, name, desc) != 0) {
|
|
mcp_reply_error(c, "could not create the knowledge base directory");
|
|
return;
|
|
}
|
|
say(c, "created knowledge base \"%s\" (%s)%s%s", name, slug,
|
|
(desc != NULL && *desc) ? ": " : "", (desc != NULL && *desc) ? desc : "");
|
|
}
|
|
|
|
static void t_kb_list(mcp_conn *c, const mcp_json *args, void *user)
|
|
{
|
|
char slugs[64][MAX_KB];
|
|
int n = 0, i;
|
|
mcp_buf b;
|
|
|
|
(void)args;
|
|
(void)user;
|
|
if (kb_list_all(slugs, 64, &n) != 0 || n == 0) {
|
|
say(c, "no knowledge bases yet - create one with kb_create");
|
|
return;
|
|
}
|
|
mcp_buf_init(&b);
|
|
mcp_buf_printf(&b, "%d knowledge base(s):\n", n);
|
|
for (i = 0; i < n; i++) {
|
|
char name[256] = "", desc[256] = "";
|
|
char **ids = NULL;
|
|
size_t ne = 0;
|
|
|
|
(void)kb_meta(slugs[i], name, sizeof(name), desc, sizeof(desc));
|
|
(void)kb_entry_ids(slugs[i], &ids, &ne);
|
|
for (size_t k = 0; k < ne; k++)
|
|
free(ids[k]);
|
|
free(ids);
|
|
mcp_buf_printf(&b, " %-24s %-20s %4zu entries", slugs[i], name, ne);
|
|
if (desc[0] != '\0')
|
|
mcp_buf_printf(&b, " — %s", desc);
|
|
mcp_buf_puts(&b, "\n");
|
|
}
|
|
mcp_reply_text(c, b.p != NULL ? b.p : "");
|
|
mcp_buf_free(&b);
|
|
}
|
|
|
|
static void t_kb_write(mcp_conn *c, const mcp_json *args, void *user)
|
|
{
|
|
const char *kb = mcp_arg_string(args, "kb");
|
|
const char *title = mcp_arg_string(args, "title");
|
|
const char *text = mcp_arg_string(args, "text");
|
|
const char *tags = mcp_arg_string(args, "tags");
|
|
const char *source = mcp_arg_string(args, "source");
|
|
char slug[MAX_KB], name[256];
|
|
char *own_id = NULL;
|
|
struct entry old, e;
|
|
int had_old = 0;
|
|
double *vec = NULL;
|
|
int dim = 0, embedded, i;
|
|
|
|
(void)user;
|
|
if (kb == NULL || *kb == '\0' || title == NULL || *title == '\0' ||
|
|
text == NULL || *text == '\0') {
|
|
mcp_reply_error(c, "kb_write needs kb, title and text");
|
|
return;
|
|
}
|
|
slugify(kb, slug, sizeof(slug));
|
|
if (kb_meta(slug, name, sizeof(name), NULL, 0) != 0) {
|
|
say(c, "no knowledge base \"%s\" - create it first with kb_create", kb);
|
|
return;
|
|
}
|
|
if (strlen(text) > MAX_TEXT) {
|
|
mcp_reply_error(c, "text too long (limit 16384 bytes) - a page, not a transcript");
|
|
return;
|
|
}
|
|
embedded = (embed_fetch(text, &vec, &dim) == 0);
|
|
|
|
/* Eine Seite mit diesem Titel gibt es schon? Dann ist das eine Aktualisierung.
|
|
* Die alte Fassung wird EINMAL gelesen und danach in die Historie übernommen. */
|
|
memset(&old, 0, sizeof(old));
|
|
{
|
|
char *found = find_by_title(slug, title);
|
|
|
|
if (found != NULL) {
|
|
if (entry_load(slug, found, &old) == 0)
|
|
had_old = 1;
|
|
own_id = found;
|
|
} else {
|
|
own_id = kb_claim_entry_id(slug);
|
|
}
|
|
}
|
|
if (own_id == NULL) {
|
|
free(vec);
|
|
mcp_reply_error(c, "could not allocate a page id");
|
|
return;
|
|
}
|
|
|
|
memset(&e, 0, sizeof(e));
|
|
e.id = own_id;
|
|
e.title = (char *)title;
|
|
e.text = (char *)text;
|
|
e.tags = (char *)(tags != NULL ? tags : "");
|
|
e.source = (char *)(source != NULL ? source : "");
|
|
e.model = (char *)(embedded ? embed_model() : "none");
|
|
e.created = had_old && old.created ? old.created : (long)time(NULL);
|
|
e.updated = (long)time(NULL);
|
|
e.vec = vec;
|
|
e.dim = dim;
|
|
|
|
/* Historie: die bisherigen Fassungen übernehmen, die vorherige anhängen, die
|
|
* älteste fallen lassen, wenn fünf voll sind. */
|
|
if (had_old) {
|
|
for (i = 0; i < old.nhist && e.nhist < MAX_HISTORY; i++) {
|
|
e.hist_text[e.nhist] = strdup(old.hist_text[i] != NULL ? old.hist_text[i] : "");
|
|
e.hist_at[e.nhist] = old.hist_at[i];
|
|
if (e.hist_text[e.nhist] != NULL)
|
|
e.nhist++;
|
|
}
|
|
if (old.text != NULL && strcmp(old.text, text) != 0) {
|
|
if (e.nhist == MAX_HISTORY) {
|
|
free(e.hist_text[0]);
|
|
for (i = 1; i < MAX_HISTORY; i++) {
|
|
e.hist_text[i - 1] = e.hist_text[i];
|
|
e.hist_at[i - 1] = e.hist_at[i];
|
|
}
|
|
e.hist_text[MAX_HISTORY - 1] = NULL;
|
|
e.nhist = MAX_HISTORY - 1;
|
|
}
|
|
e.hist_text[e.nhist] = strdup(old.text);
|
|
e.hist_at[e.nhist] = old.updated;
|
|
if (e.hist_text[e.nhist] != NULL)
|
|
e.nhist++;
|
|
}
|
|
}
|
|
|
|
if (entry_save(slug, &e) == 0) {
|
|
say(c, "%s %s/%s \"%s\"%s%s", had_old ? "updated" : "created", slug, own_id, title,
|
|
embedded ? " (embedded)" : " (WITHOUT embedding: the embedder did not answer, "
|
|
"search will fall back to substrings for this page)",
|
|
(had_old && e.nhist > 0) ? " - earlier version kept in history" : "");
|
|
} else {
|
|
say(c, "could not write %s/%s", slug, own_id);
|
|
}
|
|
|
|
for (i = 0; i < e.nhist; i++)
|
|
free(e.hist_text[i]);
|
|
if (had_old)
|
|
free_entry(&old);
|
|
free(vec);
|
|
free(own_id);
|
|
}
|
|
|
|
static void t_kb_entries(mcp_conn *c, const mcp_json *args, void *user)
|
|
{
|
|
const char *kb = mcp_arg_string(args, "kb");
|
|
int limit = mcp_arg_int(args, "limit", 50);
|
|
char slug[MAX_KB], name[256];
|
|
char **ids = NULL;
|
|
size_t n = 0, i, shown = 0;
|
|
mcp_buf b;
|
|
|
|
(void)user;
|
|
if (kb == NULL || *kb == '\0') {
|
|
mcp_reply_error(c, "kb_entries needs kb");
|
|
return;
|
|
}
|
|
slugify(kb, slug, sizeof(slug));
|
|
if (kb_meta(slug, name, sizeof(name), NULL, 0) != 0) {
|
|
say(c, "no knowledge base \"%s\"", kb);
|
|
return;
|
|
}
|
|
if (limit <= 0 || limit > 500)
|
|
limit = 50;
|
|
mcp_buf_init(&b);
|
|
if (kb_entry_ids(slug, &ids, &n) != 0 || n == 0) {
|
|
mcp_buf_printf(&b, "\"%s\" has no entries yet\n", name);
|
|
mcp_reply_text(c, b.p);
|
|
mcp_buf_free(&b);
|
|
return;
|
|
}
|
|
mcp_buf_printf(&b, "%zu entries in \"%s\" (newest first):\n", n, name);
|
|
for (i = n; i > 0 && shown < (size_t)limit; i--) {
|
|
struct entry e;
|
|
|
|
if (entry_load(slug, ids[i - 1], &e) != 0)
|
|
continue;
|
|
mcp_buf_printf(&b, " %s %s", e.id, e.title);
|
|
if (e.tags != NULL && *e.tags != '\0')
|
|
mcp_buf_printf(&b, " tags=%s", e.tags);
|
|
mcp_buf_printf(&b, " (%s, updated %ld)\n", e.dim > 0 ? "embedded" : "no vector",
|
|
e.updated);
|
|
shown++;
|
|
free_entry(&e);
|
|
}
|
|
if (shown < n)
|
|
mcp_buf_printf(&b, "(%zu of %zu)\n", shown, n);
|
|
mcp_reply_text(c, b.p);
|
|
mcp_buf_free(&b);
|
|
for (i = 0; i < n; i++)
|
|
free(ids[i]);
|
|
free(ids);
|
|
}
|
|
|
|
static void t_kb_read(mcp_conn *c, const mcp_json *args, void *user)
|
|
{
|
|
const char *kb = mcp_arg_string(args, "kb");
|
|
const char *title = mcp_arg_string(args, "title");
|
|
const char *id = mcp_arg_string(args, "id");
|
|
int history = mcp_arg_bool(args, "history", 0);
|
|
char slug[MAX_KB], name[256];
|
|
struct entry e;
|
|
mcp_buf b;
|
|
char *found = NULL;
|
|
|
|
(void)user;
|
|
if (kb == NULL || *kb == '\0') {
|
|
mcp_reply_error(c, "kb_read needs kb and title (or id)");
|
|
return;
|
|
}
|
|
if (id == NULL || *id == '\0') {
|
|
if (title == NULL || *title == '\0') {
|
|
mcp_reply_error(c, "kb_read needs kb and title (or id)");
|
|
return;
|
|
}
|
|
}
|
|
slugify(kb, slug, sizeof(slug));
|
|
if (kb_meta(slug, name, sizeof(name), NULL, 0) != 0) {
|
|
say(c, "no knowledge base \"%s\"", kb);
|
|
return;
|
|
}
|
|
found = (id != NULL && *id != '\0') ? strdup(id) : find_by_title(slug, title);
|
|
if (found == NULL || entry_load(slug, found, &e) != 0) {
|
|
say(c, "no page \"%s\" in \"%s\"", title != NULL ? title : id, name);
|
|
free(found);
|
|
return;
|
|
}
|
|
mcp_buf_init(&b);
|
|
mcp_buf_printf(&b, "# %s (%s/%s)\n", e.title, slug, e.id);
|
|
if (e.tags != NULL && *e.tags != '\0')
|
|
mcp_buf_printf(&b, "tags: %s\n", e.tags);
|
|
mcp_buf_printf(&b, "source: %s created: %ld updated: %ld vector: %s\n\n",
|
|
e.source ? e.source : "-", e.created, e.updated,
|
|
e.dim > 0 ? "yes" : "no");
|
|
mcp_buf_puts(&b, e.text != NULL ? e.text : "");
|
|
mcp_buf_puts(&b, "\n");
|
|
if (history && e.nhist > 0) {
|
|
mcp_buf_printf(&b, "\n--- %d earlier version(s) ---\n", e.nhist);
|
|
for (int i = e.nhist - 1; i >= 0; i--)
|
|
mcp_buf_printf(&b, "[%ld]\n%s\n", e.hist_at[i],
|
|
e.hist_text[i] != NULL ? e.hist_text[i] : "");
|
|
}
|
|
mcp_reply_text(c, b.p != NULL ? b.p : "");
|
|
mcp_buf_free(&b);
|
|
free_entry(&e);
|
|
free(found);
|
|
}
|
|
|
|
static void t_kb_search(mcp_conn *c, const mcp_json *args, void *user)
|
|
{
|
|
const char *query = mcp_arg_string(args, "query");
|
|
const char *kb = mcp_arg_string(args, "kb");
|
|
int limit = mcp_arg_int(args, "limit", 5);
|
|
char slugs[64][MAX_KB];
|
|
int nslugs = 0, si;
|
|
double *qvec = NULL;
|
|
int qdim = 0, semantic;
|
|
mcp_buf b;
|
|
int shown = 0;
|
|
|
|
(void)user;
|
|
if (query == NULL || *query == '\0') {
|
|
mcp_reply_error(c, "kb_search needs a query");
|
|
return;
|
|
}
|
|
if (limit <= 0 || limit > 50)
|
|
limit = 5;
|
|
semantic = (embed_fetch(query, &qvec, &qdim) == 0);
|
|
|
|
if (kb != NULL && *kb != '\0') {
|
|
char slug[MAX_KB];
|
|
|
|
slugify(kb, slug, sizeof(slug));
|
|
snprintf(slugs[0], MAX_KB, "%s", slug);
|
|
nslugs = 1;
|
|
} else if (kb_list_all(slugs, 64, &nslugs) != 0) {
|
|
nslugs = 0;
|
|
}
|
|
if (nslugs == 0) {
|
|
say(c, "no knowledge bases yet - create one with kb_create");
|
|
free(qvec);
|
|
return;
|
|
}
|
|
|
|
/* Alle Treffer sammeln und global sortieren: eine Suche über mehrere Basen soll
|
|
* die beste Seite zeigen, nicht die beste Seite je Basis. */
|
|
{
|
|
struct kbhit *hits = NULL;
|
|
size_t nhits = 0, cap = 0;
|
|
|
|
for (si = 0; si < nslugs; si++) {
|
|
char **ids = NULL;
|
|
size_t n = 0, i;
|
|
|
|
if (kb_entry_ids(slugs[si], &ids, &n) != 0)
|
|
continue;
|
|
for (i = 0; i < n; i++) {
|
|
struct entry e;
|
|
double score = -1.0;
|
|
int take = 0;
|
|
|
|
if (entry_load(slugs[si], ids[i], &e) != 0)
|
|
continue;
|
|
if (semantic && e.dim == qdim) {
|
|
score = cosine(qvec, e.vec, qdim);
|
|
take = 1;
|
|
} else if (!semantic && text_has(e.text, query)) {
|
|
score = -1.0;
|
|
take = 1;
|
|
}
|
|
if (!take) {
|
|
free_entry(&e);
|
|
continue;
|
|
}
|
|
if (nhits == cap) {
|
|
size_t ncap = cap ? cap * 2 : 32;
|
|
void *grown = realloc(hits, ncap * sizeof(struct kbhit));
|
|
|
|
if (grown == NULL) {
|
|
free_entry(&e);
|
|
continue;
|
|
}
|
|
hits = grown;
|
|
cap = ncap;
|
|
}
|
|
snprintf(hits[nhits].slug, MAX_KB, "%.*s", MAX_KB - 1, slugs[si]);
|
|
hits[nhits].e = e;
|
|
hits[nhits].score = score;
|
|
nhits++;
|
|
}
|
|
for (i = 0; i < n; i++)
|
|
free(ids[i]);
|
|
free(ids);
|
|
}
|
|
/* Sortieren: bester Score zuerst (bei Substringsuche die Einfügereihenfolge). */
|
|
for (size_t i = 1; i < nhits; i++)
|
|
for (size_t j = i; j > 0 && hits[j].score > hits[j - 1].score; j--) {
|
|
struct kbhit tmp = hits[j];
|
|
|
|
hits[j] = hits[j - 1];
|
|
hits[j - 1] = tmp;
|
|
}
|
|
|
|
mcp_buf_init(&b);
|
|
if (nhits == 0) {
|
|
mcp_buf_printf(&b, "nothing found for \"%s\"%s%s\n", query,
|
|
semantic ? "" : " (substring match - the embedder did not answer)",
|
|
"");
|
|
} else {
|
|
size_t show = (size_t)limit < nhits ? (size_t)limit : nhits;
|
|
|
|
mcp_buf_printf(&b, "%zu hit(s) for \"%s\"%s:\n", show, query,
|
|
semantic ? "" : " (substring match)");
|
|
for (size_t i = 0; i < show; i++) {
|
|
fmt_entry_ref(&b, hits[i].slug, &hits[i].e, semantic ? hits[i].score : -1.0);
|
|
shown++;
|
|
}
|
|
}
|
|
mcp_reply_text(c, b.p != NULL ? b.p : "");
|
|
mcp_buf_free(&b);
|
|
for (size_t i = 0; i < nhits; i++)
|
|
free_entry(&hits[i].e);
|
|
free(hits);
|
|
}
|
|
(void)shown;
|
|
free(qvec);
|
|
}
|
|
|
|
static void t_kb_delete(mcp_conn *c, const mcp_json *args, void *user)
|
|
{
|
|
const char *kb = mcp_arg_string(args, "kb");
|
|
const char *title = mcp_arg_string(args, "title");
|
|
const char *id = mcp_arg_string(args, "id");
|
|
char slug[MAX_KB], name[256];
|
|
char *target = NULL, *path, *leaf;
|
|
|
|
(void)user;
|
|
if (kb == NULL || *kb == '\0') {
|
|
mcp_reply_error(c, "kb_delete needs kb and title (or id)");
|
|
return;
|
|
}
|
|
slugify(kb, slug, sizeof(slug));
|
|
if (kb_meta(slug, name, sizeof(name), NULL, 0) != 0) {
|
|
say(c, "no knowledge base \"%s\"", kb);
|
|
return;
|
|
}
|
|
target = (id != NULL && *id != '\0') ? strdup(id) : find_by_title(slug, title);
|
|
if (target == NULL) {
|
|
say(c, "no page \"%s\" in \"%s\"", title != NULL ? title : "", name);
|
|
return;
|
|
}
|
|
{
|
|
mcp_buf lb;
|
|
|
|
mcp_buf_init(&lb);
|
|
mcp_buf_printf(&lb, "%s.json", target);
|
|
leaf = lb.p;
|
|
}
|
|
path = kb_file(slug, leaf != NULL ? leaf : "e.json");
|
|
free(leaf);
|
|
if (unlink(path) != 0) {
|
|
free(path);
|
|
free(target);
|
|
mcp_reply_error(c, "could not remove the page file");
|
|
return;
|
|
}
|
|
free(path);
|
|
say(c, "deleted %s/%s", slug, target);
|
|
free(target);
|
|
}
|
|
|
|
static void t_kb_drop(mcp_conn *c, const mcp_json *args, void *user)
|
|
{
|
|
const char *kb = mcp_arg_string(args, "kb");
|
|
const char *confirm = mcp_arg_string(args, "confirm");
|
|
char slug[MAX_KB], name[256];
|
|
char **ids = NULL;
|
|
size_t n = 0, i;
|
|
char *dir;
|
|
mcp_buf cmd;
|
|
|
|
(void)user;
|
|
if (kb == NULL || *kb == '\0') {
|
|
mcp_reply_error(c, "kb_drop needs kb and confirm=\"yes\"");
|
|
return;
|
|
}
|
|
slugify(kb, slug, sizeof(slug));
|
|
if (kb_meta(slug, name, sizeof(name), NULL, 0) != 0) {
|
|
say(c, "no knowledge base \"%s\"", kb);
|
|
return;
|
|
}
|
|
/* Löschen einer ganzen Basis ist nicht rückgängig zu machen — deshalb ein
|
|
* ausdrückliches Wort. Ein Tippfehler soll nicht das ganze Wiki entfernen. */
|
|
if (confirm == NULL || strcmp(confirm, "yes") != 0) {
|
|
say(c, "not deleting \"%s\": pass confirm=\"yes\". It holds %s.", name,
|
|
(kb_entry_ids(slug, &ids, &n) == 0) ? "pages" : "unknown pages");
|
|
for (i = 0; i < n; i++)
|
|
free(ids[i]);
|
|
free(ids);
|
|
return;
|
|
}
|
|
if (kb_entry_ids(slug, &ids, &n) == 0) {
|
|
for (i = 0; i < n; i++)
|
|
free(ids[i]);
|
|
free(ids);
|
|
}
|
|
dir = kb_dir(slug);
|
|
mcp_buf_init(&cmd);
|
|
mcp_buf_printf(&cmd, "rm -rf '%s'", dir != NULL ? dir : "");
|
|
if (system(cmd.p) != 0) {
|
|
mcp_buf_free(&cmd);
|
|
free(dir);
|
|
mcp_reply_error(c, "could not remove the knowledge base directory");
|
|
return;
|
|
}
|
|
mcp_buf_free(&cmd);
|
|
free(dir);
|
|
say(c, "dropped knowledge base \"%s\" (%zu pages removed)", name, n);
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ table */
|
|
|
|
static const mcp_tool TOOLS[] = {
|
|
{ "memory_add",
|
|
"Store one fact for later. Use it the moment something lasting is decided: a "
|
|
"preference, a rule, a measurement, an address, a mistake that must not repeat. "
|
|
"Write the CONCLUSION, not the conversation - one paragraph that still makes "
|
|
"sense to an agent who was not there. The text is embedded on write, so it can "
|
|
"be found by meaning later, not only by keyword. Never store secrets, keys or "
|
|
"passwords here.",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"text\":{\"type\":\"string\",\"description\":\"the fact, self-contained, one paragraph\"},"
|
|
"\"scope\":{\"type\":\"string\",\"description\":\"category, e.g. van/regeln or fleet/junction (default general)\"},"
|
|
"\"tags\":{\"type\":\"string\",\"description\":\"extra keywords, comma separated\"},"
|
|
"\"source\":{\"type\":\"string\",\"description\":\"who or what this came from\"}},"
|
|
"\"required\":[\"text\"]}",
|
|
t_add },
|
|
{ "memory_search",
|
|
"Search what was stored, by meaning. This is the tool to call before asking the "
|
|
"user something they may already have told another agent: 'what did we decide "
|
|
"about the inverter', 'which rule applies in Portugal'. It returns the closest "
|
|
"entries with a score, so a weak match is visible as a weak score instead of "
|
|
"being presented as truth.",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"query\":{\"type\":\"string\",\"description\":\"what you are looking for, in your own words\"},"
|
|
"\"scope\":{\"type\":\"string\",\"description\":\"restrict to a scope and its children\"},"
|
|
"\"limit\":{\"type\":\"integer\",\"description\":\"how many hits, default 5\"}},"
|
|
"\"required\":[\"query\"]}",
|
|
t_search },
|
|
{ "memory_list",
|
|
"List stored memories, newest first. Use it to see what exists in a scope before "
|
|
"writing something that may already be there.",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"scope\":{\"type\":\"string\",\"description\":\"scope and its children\"},"
|
|
"\"limit\":{\"type\":\"integer\",\"description\":\"default 20\"}}}",
|
|
t_list },
|
|
{ "memory_get",
|
|
"Read one memory in full by id.",
|
|
"{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"]}",
|
|
t_get },
|
|
{ "memory_update",
|
|
"Correct a memory: new text (re-embedded), new tags or a new scope. Use it instead "
|
|
"of writing a second, contradicting entry - a store with two truths is worse than "
|
|
"none.",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"id\":{\"type\":\"string\"},"
|
|
"\"text\":{\"type\":\"string\"},"
|
|
"\"tags\":{\"type\":\"string\"},"
|
|
"\"scope\":{\"type\":\"string\"}},\"required\":[\"id\"]}",
|
|
t_update },
|
|
{ "memory_delete",
|
|
"Remove a memory that is wrong or obsolete. Deleting is honest; leaving a stale "
|
|
"fact in place is how an agent confidently repeats something that stopped being "
|
|
"true.",
|
|
"{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"}},\"required\":[\"id\"]}",
|
|
t_delete },
|
|
/* ---- Wissensbasis: benannte Sammlungen von Seiten ---- */
|
|
{ "kb_create",
|
|
"Create a named knowledge base - a self-contained wiki: pages with a title and a "
|
|
"body, searchable by meaning. Use one base per subject area (\"olivia-technik\", "
|
|
"\"fleet-junction\"), not one per project. A page with the same title is updated, "
|
|
"not duplicated.",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"name\":{\"type\":\"string\",\"description\":\"human name, e.g. olivia-technik\"},"
|
|
"\"description\":{\"type\":\"string\",\"description\":\"what belongs in here\"}},"
|
|
"\"required\":[\"name\"]}",
|
|
t_kb_create },
|
|
{ "kb_list",
|
|
"Which knowledge bases exist, how many pages each holds and what they are for. Call "
|
|
"it before writing so you put a page into the right base.",
|
|
"{\"type\":\"object\",\"properties\":{}}",
|
|
t_kb_list },
|
|
{ "kb_write",
|
|
"Write a page into a knowledge base. Same title in the same base = update: the old "
|
|
"text is kept in the page history, nothing is lost silently. Write reference "
|
|
"material a human would want to read later - procedures, measurements, decisions "
|
|
"with their reasoning - not chat transcripts.",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"kb\":{\"type\":\"string\",\"description\":\"which knowledge base\"},"
|
|
"\"title\":{\"type\":\"string\",\"description\":\"page title; the same title updates the page\"},"
|
|
"\"text\":{\"type\":\"string\",\"description\":\"the page body\"},"
|
|
"\"tags\":{\"type\":\"string\",\"description\":\"comma separated\"},"
|
|
"\"source\":{\"type\":\"string\",\"description\":\"who or what this came from\"}},"
|
|
"\"required\":[\"kb\",\"title\",\"text\"]}",
|
|
t_kb_write },
|
|
{ "kb_read",
|
|
"Read one page in full by title (or id), optionally with its earlier versions.",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"kb\":{\"type\":\"string\"},"
|
|
"\"title\":{\"type\":\"string\"},"
|
|
"\"id\":{\"type\":\"string\",\"description\":\"instead of title\"},"
|
|
"\"history\":{\"type\":\"boolean\",\"description\":\"include earlier versions\"}},"
|
|
"\"required\":[\"kb\"]}",
|
|
t_kb_read },
|
|
{ "kb_search",
|
|
"Search the knowledge bases by meaning. Without kb it searches all of them and ranks "
|
|
"globally, so the best page wins, not the best page per base. This is how you answer "
|
|
"\"what does our own documentation say about X\".",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"query\":{\"type\":\"string\"},"
|
|
"\"kb\":{\"type\":\"string\",\"description\":\"restrict to one base\"},"
|
|
"\"limit\":{\"type\":\"integer\",\"description\":\"default 5\"}},"
|
|
"\"required\":[\"query\"]}",
|
|
t_kb_search },
|
|
{ "kb_entries",
|
|
"List the pages of one knowledge base - titles, tags, whether a vector exists, when "
|
|
"it was last changed. Use it to see what the wiki already covers.",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"kb\":{\"type\":\"string\"},"
|
|
"\"limit\":{\"type\":\"integer\",\"description\":\"default 50\"}},"
|
|
"\"required\":[\"kb\"]}",
|
|
t_kb_entries },
|
|
{ "kb_delete",
|
|
"Delete one page from a knowledge base (by title or id). Use it for pages that are "
|
|
"wrong or obsolete - a wiki with two contradicting pages is worse than none.",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"kb\":{\"type\":\"string\"},"
|
|
"\"title\":{\"type\":\"string\"},"
|
|
"\"id\":{\"type\":\"string\"}},"
|
|
"\"required\":[\"kb\"]}",
|
|
t_kb_delete },
|
|
{ "kb_drop",
|
|
"Delete a whole knowledge base and every page in it. Needs confirm=\"yes\"; without "
|
|
"it the tool only says what would be lost. This cannot be undone.",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"kb\":{\"type\":\"string\"},"
|
|
"\"confirm\":{\"type\":\"string\",\"description\":\"the word yes, deliberately\"}},"
|
|
"\"required\":[\"kb\"]}",
|
|
t_kb_drop },
|
|
{ "memory_scopes",
|
|
"Overview: which scopes exist and how many memories each holds. Call it when you "
|
|
"do not know where something belongs.",
|
|
"{\"type\":\"object\",\"properties\":{}}",
|
|
t_scopes },
|
|
};
|
|
|
|
int main(int argc, char **argv)
|
|
{
|
|
mcp_server srv;
|
|
|
|
srv.name = "memoryd";
|
|
srv.version = "1.0.0";
|
|
srv.tools = TOOLS;
|
|
srv.ntools = sizeof(TOOLS) / sizeof(TOOLS[0]);
|
|
srv.user = NULL;
|
|
|
|
if (argc >= 3 && strcmp(argv[1], "--http") == 0) {
|
|
/* "--http 127.0.0.1:8795" bindet an 127.0.0.1, "--http 8795" an alle Adressen.
|
|
* Die Adresse aus der Zeile zu übernehmen ist der Unterschied zwischen "nur
|
|
* lokal" und "im ganzen Netz offen" — und eine Einheit, die 127.0.0.1
|
|
* hinschreibt, soll auch 127.0.0.1 bedeuten. */
|
|
char host[64] = "";
|
|
const char *arg = argv[2];
|
|
const char *colon = strrchr(arg, ':');
|
|
int port;
|
|
|
|
if (colon != NULL && colon != arg) {
|
|
size_t hl = (size_t)(colon - arg);
|
|
|
|
if (hl >= sizeof(host))
|
|
return 2;
|
|
memcpy(host, arg, hl);
|
|
host[hl] = '\0';
|
|
port = mcp_parse_port(colon + 1);
|
|
} else {
|
|
port = mcp_parse_port(arg);
|
|
}
|
|
if (port < 0)
|
|
return 2;
|
|
return mcp_serve_http(&srv, host[0] ? host : NULL, port);
|
|
}
|
|
return mcp_serve_stdio(&srv);
|
|
}
|