Seit lange Seiten über den Proxy in Stücken eingebettet werden, dauert das Einbetten einer 9.000-Zeichen-Seite 25 bis 30 Sekunden. Das feste 'curl -m 20' brach ab, und die Seite wurde ohne Vektor gespeichert — im Erfolgstext nur als 'WITHOUT embedding' vermerkt, in der Wirkung ein dauerhafter Rückfall der Bedeutungssuche auf Zeichenketten.
1512 lines
41 KiB
C
1512 lines
41 KiB
C
/* strdup/POSIX: das Makro muss vor dem ersten Header stehen. */
|
|
#define _POSIX_C_SOURCE 200809L
|
|
|
|
/*
|
|
* wikid - ein Wiki für die Flotte: benannte Wissensbasen mit Seiten.
|
|
*
|
|
* Zwei Transporte aus einem Programm:
|
|
*
|
|
* wikid stdio, JSON-RPC je Zeile
|
|
* wikid --http 8796 Streamable HTTP, damit jeder Host dasselbe Wiki liest
|
|
*
|
|
* Was ein Agent sich beiläufig merkt, gehört nach memoryd; was ein Mensch aufgeschrieben
|
|
* hat, damit es nachgelesen wird, gehört hierher. Technisch ist beides gleich — Titel,
|
|
* Text, Vektor —, aber der Zweck entscheidet über die Form: hier gibt es Basen (ein
|
|
* Thema je Basis) und Seiten mit Titel, und derselbe Titel aktualisiert die Seite, statt
|
|
* sie zu verdoppeln. Die vorherige Fassung bleibt in der Historie.
|
|
*
|
|
* Ablage unter $WIKIDIR:
|
|
*
|
|
* <slug>/kb.json {"name","slug","description","created"}
|
|
* <slug>/e00001.json {"id","title","text","tags","source","created","updated",
|
|
* "model","embedding","history":[{"text","updated"}]}
|
|
*
|
|
* Und weil ein Wiki ohne Verlauf kein Wiki ist: ist git installiert, wird das Verzeichnis
|
|
* beim ersten Schreiben ein Repository, und jede Änderung wird festgeschrieben. Dann ist
|
|
* "wie stand das vor drei Wochen da" eine Frage an git, nicht an die Erinnerung.
|
|
*/
|
|
#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 *wiki_root(void)
|
|
{
|
|
const char *env = getenv("WIKID_HOME");
|
|
const char *home;
|
|
mcp_buf b;
|
|
|
|
if (env == NULL || *env == '\0')
|
|
env = getenv("WIKIDIR"); /* alter Name, bleibt gueltig */
|
|
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";
|
|
{
|
|
const char *xdg = getenv("XDG_DATA_HOME");
|
|
|
|
if (xdg != NULL && *xdg != '\0')
|
|
mcp_buf_printf(&b, "%s/wikid", xdg);
|
|
else
|
|
mcp_buf_printf(&b, "%s/.local/share/wikid", 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 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);
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ git */
|
|
/*
|
|
* Ist git installiert, wird die Ablage beim ersten Schreiben ein Repository und jede
|
|
* Änderung festgeschrieben — dann ist "wie stand das vor drei Wochen da" eine Frage an
|
|
* git statt an die Erinnerung. Ist git nicht da, läuft alles weiter; der Dienst sagt es
|
|
* beim Start und in wiki_list, damit niemand Verlauf annimmt, den es nicht gibt.
|
|
*
|
|
* Zwei Regeln, die den Aufruf billig und harmlos machen:
|
|
* - festgeschrieben wird nur, wenn sich wirklich etwas geändert hat (git commit sagt
|
|
* sonst "nothing to commit" und das ist kein Fehler);
|
|
* - der Text der Meldung kommt ausschließlich aus eigenen Kennungen (e00001, slug),
|
|
* nie aus Modell- oder Menschentext. Damit gibt es nichts zu quoten und nichts zu
|
|
* injizieren.
|
|
*/
|
|
static int g_git = -1; /* -1 ungeprüft, 0 kein git, 1 git vorhanden */
|
|
|
|
static int git_available(void)
|
|
{
|
|
if (g_git >= 0)
|
|
return g_git;
|
|
g_git = (system("git --version >/dev/null 2>&1") == 0) ? 1 : 0;
|
|
return g_git;
|
|
}
|
|
|
|
static void git_ensure_repo(void)
|
|
{
|
|
static int done;
|
|
|
|
if (done || !git_available())
|
|
return;
|
|
done = 1;
|
|
{
|
|
char *root = wiki_root();
|
|
mcp_buf cmd;
|
|
|
|
mcp_buf_init(&cmd);
|
|
/* rev-parse entscheidet, ob schon ein Repository (auch ein übergeordnetes). */
|
|
mcp_buf_printf(&cmd, "git -C '%s' rev-parse --git-dir >/dev/null 2>&1 || "
|
|
"git -C '%s' init -q", root, root);
|
|
if (system(cmd.p) != 0) {
|
|
fprintf(stderr, "wikid: git init in %s failed\n", root);
|
|
} else {
|
|
FILE *ign = NULL;
|
|
char *path = NULL;
|
|
|
|
{
|
|
mcp_buf pb;
|
|
|
|
mcp_buf_init(&pb);
|
|
mcp_buf_printf(&pb, "%s/.gitignore", root);
|
|
path = pb.p;
|
|
}
|
|
ign = fopen(path != NULL ? path : "/dev/null", "w");
|
|
if (ign != NULL) {
|
|
fprintf(ign, "*.tmp.*\n.tmp/\n");
|
|
fclose(ign);
|
|
}
|
|
free(path);
|
|
}
|
|
mcp_buf_free(&cmd);
|
|
free(root);
|
|
}
|
|
}
|
|
|
|
/* Schreibt eine Änderung fest. Verb und Kennung stammen von uns, nicht vom Aufrufer. */
|
|
static void git_commit(const char *verb, const char *what)
|
|
{
|
|
char *root;
|
|
mcp_buf cmd;
|
|
|
|
if (!git_available())
|
|
return;
|
|
git_ensure_repo();
|
|
root = wiki_root();
|
|
mcp_buf_init(&cmd);
|
|
/* Die Kennung ist geprüft (valid_id) beziehungsweise ein Slug aus [a-z0-9-]; der
|
|
* Verb ist ein Literal aus unserem Code. Kein Anführungszeichen weit und breit. */
|
|
mcp_buf_printf(&cmd, "git -C '%s' add -A >/dev/null 2>&1 && "
|
|
"git -C '%s' -c user.name=wikid -c user.email=wikid@localhost "
|
|
"commit -q -m \"%s %s\" >/dev/null 2>&1", root, root, verb, what);
|
|
if (system(cmd.p) != 0)
|
|
fprintf(stderr, "wikid: git commit failed (%s %s)\n", verb, what);
|
|
mcp_buf_free(&cmd);
|
|
free(root);
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ helper */
|
|
|
|
|
|
|
|
static const char *js(const mcp_json *v, const char *key)
|
|
{
|
|
const char *s = mcp_arg_string(v, key);
|
|
|
|
return s != NULL ? s : "";
|
|
}
|
|
|
|
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, "\"");
|
|
}
|
|
|
|
/* Teilstringsuche, wenn kein Vektor da ist (kein Embedder oder alte Seite 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;
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ 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. */
|
|
/* Zeitlimit in Sekunden, ueberschreibbar mit $EMBED_TIMEOUT_S. */
|
|
static int embed_timeout_s(void)
|
|
{
|
|
const char *t = getenv("EMBED_TIMEOUT_S");
|
|
int v = (t != NULL && *t != '\0') ? atoi(t) : 0;
|
|
|
|
return (v > 0) ? v : 180;
|
|
}
|
|
|
|
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 = wiki_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);
|
|
/* Zeitlimit fuer die Einbettung. 20 Sekunden waren zu knapp, seit lange
|
|
* Seiten ueber den Proxy in Stuecken eingebettet werden: eine Seite mit
|
|
* 9.000 Zeichen braucht 25 bis 30 Sekunden, und der Aufruf scheiterte dann
|
|
* still ("WITHOUT embedding"). Der Standard ist grosszuegig, weil ein
|
|
* fehlender Vektor die Bedeutungssuche fuer immer auf Zeichenketten
|
|
* zurueckwirft; $EMBED_TIMEOUT_S ueberschreibt ihn. */
|
|
mcp_buf_printf(&cmd, "curl -sS -m %d -H 'Content-Type: application/json' "
|
|
"--data-binary @%s '%s' 2>/dev/null",
|
|
embed_timeout_s(), 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));
|
|
}
|
|
|
|
/* ==========================================================================
|
|
* 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';
|
|
}
|
|
|
|
/* Die Wurzel IST die Ablage: $WIKIDIR/<slug>/, kein Zwischenverzeichnis. */
|
|
static char *kb_root(void)
|
|
{
|
|
return wiki_root();
|
|
}
|
|
|
|
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;
|
|
}
|
|
git_commit("wiki_create", slug);
|
|
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;
|
|
}
|
|
{
|
|
char *root = wiki_root();
|
|
|
|
mcp_buf_init(&b);
|
|
mcp_buf_printf(&b, "%d knowledge base(s) in %s (history: %s)\n", n, root,
|
|
git_available() ? "git, every change committed"
|
|
: "none - git is not installed");
|
|
free(root);
|
|
}
|
|
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;
|
|
/* Schreibt jemand denselben Titel in anderer Schreibweise, bleibt die Seite unter
|
|
* ihrem bisherigen Namen stehen — sonst macht ein flüchtig klein getippter Update
|
|
* aus "Frostschutz" ein "frostschutz". Ein echter anderer Titel benennt sie um. */
|
|
e.title = (had_old && old.title != NULL && strcasecmp(old.title, title) == 0)
|
|
? old.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) {
|
|
git_commit(had_old ? "page_update" : "page_write", own_id);
|
|
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);
|
|
git_commit("page_delete", target);
|
|
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);
|
|
git_commit("wiki_drop", slug);
|
|
say(c, "dropped knowledge base \"%s\" (%zu pages removed)", name, n);
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ table */
|
|
|
|
static const mcp_tool TOOLS[] = {
|
|
{ "wiki_create",
|
|
"Create a named knowledge base - one wiki per subject area (\"olivia-technik\", "
|
|
"\"fleet-junction\"), not one per project. Pages inside are written with page_write "
|
|
"and found again with wiki_search, by meaning rather than by keyword.",
|
|
"{\"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 },
|
|
{ "wiki_list",
|
|
"Which wikis exist, how many pages each holds and what they are for. Call it before "
|
|
"writing so a page lands in the right wiki.",
|
|
"{\"type\":\"object\",\"properties\":{}}",
|
|
t_kb_list },
|
|
{ "page_write",
|
|
"Write a page: title plus body. The SAME title in the same wiki updates the page "
|
|
"instead of duplicating it, and the previous text stays in the page history - so a "
|
|
"correction never loses what was there before. Write what a human would want to read "
|
|
"later: procedures, measurements, decisions with their reasoning. Not transcripts.",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"kb\":{\"type\":\"string\",\"description\":\"which wiki\"},"
|
|
"\"title\":{\"type\":\"string\",\"description\":\"page title; the same title updates it\"},"
|
|
"\"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 },
|
|
{ "page_read",
|
|
"Read one page in full by title (or id), optionally with its earlier versions - that "
|
|
"is how you answer \"what did we decide back then\".",
|
|
"{\"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 },
|
|
{ "wiki_search",
|
|
"Search the wikis by meaning. Without kb it searches all of them and ranks globally, "
|
|
"so the best page wins rather than the best page per wiki. This is how you answer "
|
|
"\"what does our own documentation say about X\" before asking the human again.",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"query\":{\"type\":\"string\"},"
|
|
"\"kb\":{\"type\":\"string\",\"description\":\"restrict to one wiki\"},"
|
|
"\"limit\":{\"type\":\"integer\",\"description\":\"default 5\"}},"
|
|
"\"required\":[\"query\"]}",
|
|
t_kb_search },
|
|
{ "page_list",
|
|
"List the pages of one wiki - titles, tags, whether a vector exists, when it last "
|
|
"changed. Use it to see what the wiki already covers before writing something new.",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"kb\":{\"type\":\"string\"},"
|
|
"\"limit\":{\"type\":\"integer\",\"description\":\"default 50\"}},"
|
|
"\"required\":[\"kb\"]}",
|
|
t_kb_entries },
|
|
{ "page_delete",
|
|
"Delete one page (by title or id). Use it for pages that are wrong or obsolete - two "
|
|
"contradicting pages are worse than none. The deletion is committed too, so it can be "
|
|
"recovered with git.",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"kb\":{\"type\":\"string\"},"
|
|
"\"title\":{\"type\":\"string\"},"
|
|
"\"id\":{\"type\":\"string\"}},"
|
|
"\"required\":[\"kb\"]}",
|
|
t_kb_delete },
|
|
{ "wiki_drop",
|
|
"Delete a whole wiki and every page in it. Needs confirm=\"yes\"; without it the tool "
|
|
"only says what would be lost. Undone from git if the wiki directory is a repository.",
|
|
"{\"type\":\"object\",\"properties\":{"
|
|
"\"kb\":{\"type\":\"string\"},"
|
|
"\"confirm\":{\"type\":\"string\",\"description\":\"the word yes, deliberately\"}},"
|
|
"\"required\":[\"kb\"]}",
|
|
t_kb_drop },
|
|
};
|
|
|
|
int main(int argc, char **argv)
|
|
{
|
|
mcp_server srv;
|
|
|
|
srv.name = "wikid";
|
|
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);
|
|
}
|