Gleiche Ursache wie in wikid: 20 Sekunden reichen nicht, seit lange Texte über den Proxy in Stücken eingebettet werden.
1124 lines
28 KiB
C
1124 lines
28 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("MEMORYD_HOME");
|
|
const char *home;
|
|
mcp_buf b;
|
|
|
|
if (env == NULL || *env == '\0')
|
|
env = getenv("MEMORYDIR"); /* 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/memoryd", xdg);
|
|
else
|
|
mcp_buf_printf(&b, "%s/.local/share/memoryd", 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. */
|
|
/* 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 = 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);
|
|
/* 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));
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ 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");
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ git */
|
|
/*
|
|
* Ist git installiert, wird die Ablage beim ersten Schreiben ein Repository und jede
|
|
* Änderung festgeschrieben. Ein Speicher ohne Verlauf lässt sich nicht zurückdrehen —
|
|
* "lösche die Erinnerung, die war falsch" ist keine Antwort, wenn sie schon weg ist.
|
|
* Ist git nicht da, läuft alles weiter; der Dienst sagt es beim Start, damit niemand
|
|
* Verlauf annimmt, den es nicht gibt.
|
|
*
|
|
* Die Meldung besteht nur aus eigenen Kennungen (m00001) — kein Modell- oder
|
|
* Menschentext, also 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 = mem_root();
|
|
mcp_buf cmd;
|
|
|
|
mcp_buf_init(&cmd);
|
|
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, "memoryd: git init in %s failed\n", root);
|
|
} else {
|
|
FILE *ign;
|
|
mcp_buf pb;
|
|
|
|
mcp_buf_init(&pb);
|
|
mcp_buf_printf(&pb, "%s/.gitignore", root);
|
|
ign = fopen(pb.p != NULL ? pb.p : "/dev/null", "w");
|
|
if (ign != NULL) {
|
|
fprintf(ign, "*.tmp.*\n.tmp/\n*.lock\n");
|
|
fclose(ign);
|
|
}
|
|
mcp_buf_free(&pb);
|
|
}
|
|
mcp_buf_free(&cmd);
|
|
free(root);
|
|
}
|
|
}
|
|
|
|
static void git_commit(const char *verb, const char *what)
|
|
{
|
|
char *root;
|
|
mcp_buf cmd;
|
|
|
|
if (!git_available())
|
|
return;
|
|
git_ensure_repo();
|
|
root = mem_root();
|
|
mcp_buf_init(&cmd);
|
|
mcp_buf_printf(&cmd, "git -C '%s' add -A >/dev/null 2>&1 && "
|
|
"git -C '%s' -c user.name=memoryd -c user.email=memoryd@localhost "
|
|
"commit -q -m \"%s %s\" >/dev/null 2>&1", root, root, verb, what);
|
|
if (system(cmd.p) != 0)
|
|
fprintf(stderr, "memoryd: git commit failed (%s %s)\n", verb, what);
|
|
mcp_buf_free(&cmd);
|
|
free(root);
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ 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;
|
|
}
|
|
git_commit("memory_add", id);
|
|
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;
|
|
}
|
|
git_commit("memory_update", id);
|
|
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);
|
|
git_commit("memory_delete", id);
|
|
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);
|
|
}
|
|
|
|
|
|
/* ------------------------------------------------------------------ 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 },
|
|
{ "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);
|
|
}
|