diff --git a/.gitignore b/.gitignore index b619c6f..75bcd04 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ memoryd *.o +memoryd-http diff --git a/Makefile b/Makefile index 09b37ee..11f9205 100644 --- a/Makefile +++ b/Makefile @@ -2,20 +2,27 @@ CC ?= cc CFLAGS ?= -std=c99 -O2 -Wall -Wextra -Werror LIBDIR ?= vendor/libmcp PREFIX ?= /usr/local +CGIDIR ?= $(PREFIX)/lib/cgi-bin -all: memoryd +all: memoryd memoryd-http memoryd: memoryd.c $(LIBDIR)/mcp.h $(CC) $(CFLAGS) -I$(LIBDIR) -o $@ memoryd.c -lm -test: memoryd - ./tests/run.sh +memoryd-http: memoryd-http.c vendor/cgi/cgi.h $(LIBDIR)/mcp.h + $(CC) $(CFLAGS) -I$(LIBDIR) -Ivendor/cgi -o $@ memoryd-http.c -install: memoryd +test: memoryd memoryd-http + ./tests/run.sh + ./tests/test-http.sh + +install: memoryd memoryd-http mkdir -p $(DESTDIR)$(PREFIX)/bin cp memoryd $(DESTDIR)$(PREFIX)/bin/ + install -d $(DESTDIR)$(CGIDIR) + install -m 0755 memoryd-http $(DESTDIR)$(CGIDIR)/memoryd-http clean: - rm -f memoryd + rm -f memoryd memoryd-http .PHONY: all test install clean diff --git a/README.md b/README.md index 811a7ee..9113711 100644 --- a/README.md +++ b/README.md @@ -103,3 +103,38 @@ sudo make install The suite starts its own embedder stub with deterministic vectors, so it does not depend on a model being loaded on this machine. + +## Web UI (CGI) + +`memoryd-http` is a C99 CGI program: HTML 4.01, no JavaScript, no auth. It never reads +the memory files itself — every list, search, read, add, update and delete is a +`tools/call` against memoryd (`MEMORYD_URL`, default `http://127.0.0.1:8795/mcp`). The +browser and the agents therefore share one store. + +| Address | Effect | +|---|---| +| `/` | memories, filter with `?scope=…&limit=…` | +| `/search?q=…` | semantic search, optional `&scope=…` | +| `/scopes` | scopes with counts | +| `/new` | add a memory | +| `/m/` | one memory with created/source | +| `/m//edit` | edit text, tags, scope | +| `/m//delete` | POST only | + +```sh +make # memoryd and memoryd-http +sudo make install # /usr/local/bin/memoryd, /usr/local/lib/cgi-bin/memoryd-http +``` + +With busybox httpd (the four fleet CGIs share the navigation when installed side by +side): + +```sh +install -d /srv/www/cgi-bin +install -m 0755 memoryd-http /srv/www/cgi-bin/ +MEMORYD_URL=http://127.0.0.1:8795/mcp \ + busybox httpd -f -p 0.0.0.0:8798 -h /srv/www +``` + +`vendor/cgi/cgi.h` is the shared CGI helper (the same file lives in wikid, skilld and +tasksd): environment, HTML shell, Markdown, form parameters and the MCP call. diff --git a/memoryd-http.c b/memoryd-http.c new file mode 100644 index 0000000..39c528a --- /dev/null +++ b/memoryd-http.c @@ -0,0 +1,749 @@ +/* + * memoryd-http — CGI front-end for memoryd. + * + * C99, HTML 4.01, no JavaScript, no auth. Everything goes through memoryd's + * MCP server: list, search, scopes, add, update, delete. The CGI never reads + * the memory files itself, so the web view and the agents share one store. + * + * Routes (mounted at /cgi-bin/memoryd-http under busybox httpd): + * / — memories, optional ?scope=…&limit=… + * /search?q=… — semantic search, optional &scope= + * /scopes — scope overview + * /new — add a memory + * /m/ — one memory, with created/source + * /m//edit — edit text, tags, scope + * /m//delete — POST only + * + * Environment: MEMORYD_URL (default http://127.0.0.1:8795/mcp) + * + * Build: + * cc -std=c99 -O2 -Wall -Wextra -Wpedantic -D_POSIX_C_SOURCE=200809L \ + * -Ivendor/libmcp -Ivendor/cgi -o memoryd-http memoryd-http.c + */ +#define _POSIX_C_SOURCE 200809L +#define MCP_IMPLEMENTATION +#include "mcp.h" +#include "cgi.h" + +#define ENV_URL "MEMORYD_URL" +#define DEF_URL "http://127.0.0.1:8795/mcp" +#define APP "memoryd-http" + +struct mem_item { + char *id; + char *scope; + char *meta; /* model, tags, score — display only */ + mcp_buf text; +}; + +static void mem_items_free(struct mem_item *items, size_t n) +{ + size_t i; + + for (i = 0; i < n; i++) { + free(items[i].id); + free(items[i].scope); + free(items[i].meta); + mcp_buf_free(&items[i].text); + } + free(items); +} + +static int mem_header(const char *p, size_t len) +{ + size_t i = 1; + const char *ob, *cb; + + if (len < 4 || p[0] != 'm' || !isdigit((unsigned char)p[1])) + return 0; + while (i < len && isdigit((unsigned char)p[i])) + i++; + if (i >= len || p[i] != ' ') + return 0; + ob = memchr(p, '[', len); + cb = memchr(p, ']', len); + return ob != NULL && cb != NULL && ob < cb; +} + +/* + * memory_list / memory_search / memory_get all use: + * m00035 [scope] score=… (model) tags=… + * first line of text + * more text, unindented + * created=… source=… (memory_get only) + * Each entry starts with an m header line. + */ +static size_t mem_parse(const char *text, struct mem_item **out) +{ + struct mem_item *items = NULL; + size_t n = 0, cap = 0; + struct mem_item *cur = NULL; + const char *p = text; + + *out = NULL; + if (text == NULL) + return 0; + while (*p != '\0') { + const char *eol = strchr(p, '\n'); + size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p); + + if (len == 0) + goto next; + if (mem_header(p, len)) { + const char *sp = memchr(p, ' ', len); + const char *ob = memchr(p, '[', len); + const char *cb = memchr(p, ']', len); + const char *ms, *me; + + if (n == cap) { + size_t ncap = cap ? cap * 2 : 16; + struct mem_item *grown = realloc(items, + ncap * sizeof(*items)); + + if (grown == NULL) + break; + items = grown; + cap = ncap; + } + cur = &items[n++]; + memset(cur, 0, sizeof(*cur)); + mcp_buf_init(&cur->text); + cur->id = strndup(p, (size_t)(sp - p)); + cur->scope = strndup(ob + 1, (size_t)(cb - ob - 1)); + ms = cb + 1; + me = p + len; + while (ms < me && *ms == ' ') + ms++; + cur->meta = strndup(ms, (size_t)(me - ms)); + goto next; + } + if (cur != NULL) { + if (len >= 4 && strncmp(p, " ", 4) == 0) { + if (strncmp(p + 4, "created=", 8) == 0) + goto next; /* memory_get trailer */ + if (cur->text.len == 0) + mcp_buf_add(&cur->text, p + 4, len - 4); + else { + mcp_buf_puts(&cur->text, "\n"); + mcp_buf_add(&cur->text, p, len); + } + } else if (p[0] == '(' && p[len - 1] == ')') { + /* "(5 of 41, newest first)" footer */ + } else { + if (cur->text.len > 0) + mcp_buf_puts(&cur->text, "\n"); + mcp_buf_add(&cur->text, p, len); + } + } +next: + if (eol == NULL) + break; + p = eol + 1; + } + *out = items; + return n; +} + +static char *mem_field(const char *meta, const char *key) +{ + const char *p = meta != NULL ? strstr(meta, key) : NULL; + size_t len; + + if (p == NULL) + return NULL; + p += strlen(key); + len = strcspn(p, " \n"); + return strndup(p, len); +} + +static void mem_created_source(const char *text, long *created, char **source) +{ + const char *p = text != NULL ? strstr(text, "\n created=") : NULL; + char *end; + + *created = 0; + *source = NULL; + if (p == NULL) + return; + p += strlen("\n created="); + *created = strtol(p, &end, 10); + p = strstr(end, "source="); + if (p != NULL) { + size_t len; + + p += 7; + len = strcspn(p, "\n"); + *source = strndup(p, len); + } +} + +static void render_text_clipped(const char *text, size_t max) +{ + size_t len = strlen(text); + + if (len <= max) { + cg_md(text); + return; + } + { + char *cut = strndup(text, max); + char *last_space; + size_t clen; + + if (cut == NULL) + return; + clen = strlen(cut); + last_space = strrchr(cut, ' '); + if (last_space != NULL && clen > 40) { + *last_space = '\0'; + clen = strlen(cut); + } + cg_md(cut); + fputs(" …", stdout); + free(cut); + (void)clen; + } +} + +static void render_items(struct mem_item *items, size_t n) +{ + size_t i; + + if (n == 0) { + fputs("

No memories found.

\n", stdout); + return; + } + for (i = 0; i < n; i++) { + fputs("
", stdout); + cg_html(items[i].id); + fputs(" ", stdout); + cg_html(items[i].scope); + fputs("", stdout); + if (items[i].meta != NULL && *items[i].meta != '\0') { + fputs(" ", stdout); + cg_html(items[i].meta); + fputs("", stdout); + } + fputs("
\n
", stdout); + render_text_clipped(items[i].text.p != NULL ? items[i].text.p : "", + 700); + fputs("
\n
\n", stdout); + } +} + +static void form_filter(const char *scope) +{ + fputs("
\n", stdout); +} + +static void search_form(void) +{ + fputs("
" + "
\n", stdout); +} + +static void route_list(const char *query) +{ + char *scope = cg_param(query, "scope"); + char *limstr = cg_param(query, "limit"); + int limit = limstr != NULL ? atoi(limstr) : 50; + mcp_buf args; + int first = 1; + char *text; + struct mem_item *items = NULL; + size_t n; + + if (limit <= 0 || limit > 200) + limit = 50; + mcp_buf_init(&args); + mcp_buf_puts(&args, "{"); + cg_args_add_str(&args, &first, "scope", scope); + cg_args_add_int(&args, &first, "limit", limit); + mcp_buf_puts(&args, "}"); + text = cg_rpc(ENV_URL, DEF_URL, "memory_list", args.p); + mcp_buf_free(&args); + + cg_head(APP, "Memories"); + fputs("

Memories

\n", stdout); + search_form(); + fputs(" ", stdout); + form_filter(scope); + fputs("\n", stdout); + if (text == NULL) { + fputs("
memoryd did not answer.
\n", stdout); + } else { + n = mem_parse(text, &items); + render_items(items, n); + mem_items_free(items, n); + free(text); + } + cg_foot(); + free(scope); + free(limstr); +} + +static void route_search(const char *query) +{ + char *q = cg_param(query, "q"); + char *scope = cg_param(query, "scope"); + mcp_buf args; + int first = 1; + char *text; + struct mem_item *items = NULL; + size_t n; + + cg_head(APP, "Search memories"); + fputs("

Search memories

\n", stdout); + search_form(); + fputs(" ", stdout); + form_filter(scope); + fputs("\n", stdout); + if (q == NULL || *q == '\0') { + fputs("

Give a word or phrase.

\n", stdout); + cg_foot(); + free(q); free(scope); + return; + } + mcp_buf_init(&args); + mcp_buf_puts(&args, "{"); + cg_args_add_str(&args, &first, "query", q); + cg_args_add_str(&args, &first, "scope", scope); + cg_args_add_int(&args, &first, "limit", 20); + mcp_buf_puts(&args, "}"); + text = cg_rpc(ENV_URL, DEF_URL, "memory_search", args.p); + mcp_buf_free(&args); + if (text == NULL) { + fputs("
memoryd did not answer.
\n", stdout); + } else { + n = mem_parse(text, &items); + render_items(items, n); + mem_items_free(items, n); + free(text); + } + cg_foot(); + free(q); + free(scope); +} + +static void route_scopes(void) +{ + char *text = cg_rpc(ENV_URL, DEF_URL, "memory_scopes", "{}"); + + cg_head(APP, "Memory scopes"); + fputs("

Memory scopes

\n", stdout); + if (text == NULL) { + fputs("
memoryd did not answer.
\n", stdout); + cg_foot(); + return; + } + { + const char *p = strchr(text, '\n'); + + if (p == NULL) { + fputs("

", stdout); + cg_html(text); + fputs("

\n", stdout); + } else { + fputs("

", stdout); + cg_html_n(text, (size_t)(p - text)); + fputs("

\n
    \n", stdout); + p++; + while (*p != '\0') { + const char *eol = strchr(p, '\n'); + size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p); + const char *tok = p; + const char *tok_end; + + while (tok < p + len && (*tok == ' ' || *tok == '\t')) + tok++; + tok_end = tok; + while (tok_end < p + len && *tok_end != ' ' && *tok_end != '\t') + tok_end++; + if (tok_end > tok) { + char name[512]; + size_t nl = (size_t)(tok_end - tok); + + if (nl >= sizeof(name)) + nl = sizeof(name) - 1; + memcpy(name, tok, nl); + name[nl] = '\0'; + fputs("
  • ", stdout); + cg_html(name); + fputs("", stdout); + if (tok_end < p + len) { + fputs(" ", stdout); + cg_html_n(tok_end, (size_t)(p + len - tok_end)); + fputs("", stdout); + } + fputs("
  • \n", stdout); + } + if (eol == NULL) + break; + p = eol + 1; + } + fputs("
\n", stdout); + } + } + free(text); + cg_foot(); +} + +static void memory_form(const char *action, const char *id, const char *text, + const char *scope, const char *tags, const char *source) +{ + fputs("
\n", stdout); + if (id != NULL) { + fputs("\n", stdout); + } + fputs("

\n" + "

\n" + "

\n", stdout); + if (source != NULL) { + fputs("

\n", stdout); + } + fputs("

\n
\n", stdout); +} + +static void route_new(const char *query, const char *body) +{ + const char *method = cg_method(); + + if (strcmp(method, "POST") != 0) { + char *scope = cg_param(query, "scope"); + + cg_head(APP, "Add a memory"); + fputs("

Add a memory

\n", stdout); + memory_form("/new", NULL, "", scope, "", ""); + cg_foot(); + free(scope); + return; + } + { + char *text = cg_param(body, "text"); + char *scope = cg_param(body, "scope"); + char *tags = cg_param(body, "tags"); + char *source = cg_param(body, "source"); + mcp_buf args; + int first = 1; + char *result; + + if (text == NULL || *text == '\0') { + cg_head(APP, "Add a memory"); + fputs("

Add a memory

\n" + "
A memory needs text.
\n", stdout); + memory_form("/new", NULL, text, scope, tags, source); + cg_foot(); + goto out; + } + mcp_buf_init(&args); + mcp_buf_puts(&args, "{"); + cg_args_add_str(&args, &first, "text", text); + cg_args_add_str(&args, &first, "scope", scope); + cg_args_add_str(&args, &first, "tags", tags); + cg_args_add_str(&args, &first, "source", source); + mcp_buf_puts(&args, "}"); + result = cg_rpc(ENV_URL, DEF_URL, "memory_add", args.p); + mcp_buf_free(&args); + cg_head(APP, "Add a memory"); + if (result == NULL) { + fputs("
memoryd did not answer.
\n", stdout); + memory_form("/new", NULL, text, scope, tags, source); + } else { + fputs("

Stored

\n
", stdout); + cg_html(result); + fputs("
\n\n", stdout); + free(result); + } + cg_foot(); +out: + free(text); free(scope); free(tags); free(source); + } +} + +static void route_detail(const char *id) +{ + mcp_buf args; + int first = 1; + char *text; + struct mem_item *items = NULL; + size_t n; + long created = 0; + char *source = NULL; + + mcp_buf_init(&args); + mcp_buf_puts(&args, "{"); + cg_args_add_str(&args, &first, "id", id); + mcp_buf_puts(&args, "}"); + text = cg_rpc(ENV_URL, DEF_URL, "memory_get", args.p); + mcp_buf_free(&args); + if (text == NULL) { + cg_error_page(APP, "Memory not found", "memoryd did not answer."); + return; + } + cg_head(APP, id); + n = mem_parse(text, &items); + mem_created_source(text, &created, &source); + fputs("

", stdout); + cg_html(id); + fputs("

\n", stdout); + if (n == 0) { + fputs("
No such memory.
\n", stdout); + } else { + fputs("

scope: ", stdout); + cg_html(items[0].scope); + fputs("", stdout); + if (items[0].meta != NULL && *items[0].meta != '\0') { + fputs(" · ", stdout); + cg_html(items[0].meta); + } + fputs(" · created ", stdout); + cg_time(created); + if (source != NULL && *source != '\0') { + fputs(" · source ", stdout); + cg_html(source); + } + fputs("

\n", stdout); + cg_md(items[0].text.p != NULL ? items[0].text.p : ""); + fputs("\n", stdout); + fputs("
\n", + stdout); + } + mem_items_free(items, n); + free(text); + free(source); + cg_foot(); +} + +static void route_edit(const char *id, const char *body) +{ + char action[512]; + + snprintf(action, sizeof(action), "/m/%s/edit", id); + if (strcmp(cg_method(), "POST") == 0) { + char *text = cg_param(body, "text"); + char *scope = cg_param(body, "scope"); + char *tags = cg_param(body, "tags"); + mcp_buf args; + int first = 1; + char *result; + + if (text == NULL || *text == '\0') { + cg_head(APP, "Edit memory"); + fputs("

Edit ", stdout); + cg_html(id); + fputs("

\n
Text must not be empty.
\n", + stdout); + memory_form(action, NULL, text, scope, tags, NULL); + cg_foot(); + free(text); free(scope); free(tags); + return; + } + mcp_buf_init(&args); + mcp_buf_puts(&args, "{"); + cg_args_add_str(&args, &first, "id", id); + cg_args_add_str(&args, &first, "text", text); + cg_args_add_str(&args, &first, "scope", scope); + cg_args_add_str(&args, &first, "tags", tags != NULL ? tags : ""); + mcp_buf_puts(&args, "}"); + result = cg_rpc(ENV_URL, DEF_URL, "memory_update", args.p); + mcp_buf_free(&args); + cg_head(APP, "Edit memory"); + if (result == NULL) { + fputs("
memoryd did not answer.
\n", stdout); + } else { + fputs("

Updated

\n
", stdout); + cg_html(result); + fputs("
\n\n", stdout); + free(result); + } + cg_foot(); + free(text); free(scope); free(tags); + return; + } + { + mcp_buf args; + int first = 1; + char *text; + struct mem_item *items = NULL; + size_t n; + char *tags = NULL; + + mcp_buf_init(&args); + mcp_buf_puts(&args, "{"); + cg_args_add_str(&args, &first, "id", id); + mcp_buf_puts(&args, "}"); + text = cg_rpc(ENV_URL, DEF_URL, "memory_get", args.p); + mcp_buf_free(&args); + cg_head(APP, "Edit memory"); + fputs("

Edit ", stdout); + cg_html(id); + fputs("

\n", stdout); + if (text == NULL) { + fputs("
memoryd did not answer.
\n", stdout); + } else { + n = mem_parse(text, &items); + if (n > 0) { + tags = mem_field(items[0].meta, "tags="); + memory_form(action, NULL, + items[0].text.p != NULL ? items[0].text.p : "", + items[0].scope, tags, NULL); + } else { + fputs("
No such memory.
\n", stdout); + } + mem_items_free(items, n); + free(text); + } + cg_foot(); + free(tags); + } +} + +static void route_delete(const char *id) +{ + mcp_buf args; + int first = 1; + char *result; + + if (strcmp(cg_method(), "POST") != 0) { + cg_error_page(APP, "Delete memory", "Deletion needs a POST."); + return; + } + mcp_buf_init(&args); + mcp_buf_puts(&args, "{"); + cg_args_add_str(&args, &first, "id", id); + mcp_buf_puts(&args, "}"); + result = cg_rpc(ENV_URL, DEF_URL, "memory_delete", args.p); + mcp_buf_free(&args); + cg_head(APP, "Delete memory"); + if (result == NULL) { + fputs("
memoryd did not answer.
\n", stdout); + } else { + fputs("

Deleted

\n
", stdout); + cg_html(result); + fputs("
\n\n", stdout); + free(result); + } + cg_foot(); +} + +/* ------------------------------------------------------------------ router */ + +static void handle(const char *path, const char *query, const char *body) +{ + if (strcmp(path, "/") == 0 || strcmp(path, "") == 0) { + route_list(query); + return; + } + if (strcmp(path, "/search") == 0) { + route_search(query); + return; + } + if (strcmp(path, "/scopes") == 0) { + route_scopes(); + return; + } + if (strcmp(path, "/new") == 0) { + route_new(query, body); + return; + } + if (strncmp(path, "/m/", 3) == 0) { + const char *rest = path + 3; + size_t idlen = strcspn(rest, "/"); + char id[256]; + const char *tail; + + if (idlen == 0 || idlen >= sizeof(id)) { + cg_error_page(APP, "Not found", "No memory id in the path."); + return; + } + memcpy(id, rest, idlen); + id[idlen] = '\0'; + cg_url_decode(id); + tail = rest + idlen; + if (strcmp(tail, "/edit") == 0) { + route_edit(id, body); + return; + } + if (strcmp(tail, "/delete") == 0) { + route_delete(id); + return; + } + if (*tail == '\0') { + route_detail(id); + return; + } + } + cg_error_page(APP, "Not found", "No such page."); +} + +int main(void) +{ + char path[4096], query[4096]; + char *body = NULL; + + cg_route(path, sizeof(path), query, sizeof(query)); + if (strcmp(cg_method(), "POST") == 0) + body = cg_read_body(); + cg_header(); + handle(path, query, body != NULL ? body : ""); + free(body); + return 0; +} diff --git a/tests/run.py b/tests/run.py index 947c317..448450c 100644 --- a/tests/run.py +++ b/tests/run.py @@ -218,6 +218,7 @@ def main(): # Ohne Embedder: speichern geht weiter, die Suche sagt, was sie tut. stub.shutdown() + stub.server_close() t, err = c.tool("memory_add", text="Die Pumpe läuft seit März leise.", scope="van/technik") if not err and "WITHOUT embedding" in t: ok("a dead embedder is reported, not hidden") @@ -260,6 +261,7 @@ def main(): except subprocess.TimeoutExpired: srv.kill() stub.shutdown() + stub.server_close() shutil.rmtree(work, ignore_errors=True) print() diff --git a/tests/test-http.sh b/tests/test-http.sh new file mode 100755 index 0000000..5d731f3 --- /dev/null +++ b/tests/test-http.sh @@ -0,0 +1,90 @@ +#!/bin/sh +# Prüft memoryd-http als CGI gegen einen eigenen memoryd auf freiem Port. +set -eu + +cd "$(dirname "$0")/.." + +PORT=$(python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1]); s.close()') +DIR=$(mktemp -d) +PID= + +cleanup() { + [ -n "$PID" ] && kill "$PID" 2>/dev/null || true + [ -n "$PID" ] && wait "$PID" 2>/dev/null || true + rm -rf "$DIR" +} +trap cleanup EXIT INT TERM + +MEMORYDIR="$DIR/store" ./memoryd --http "127.0.0.1:$PORT" >"$DIR/log" 2>&1 & +PID=$! +for _ in $(seq 1 50); do + curl -s -o /dev/null "http://127.0.0.1:$PORT/mcp" -X POST \ + -H 'Content-Type: application/json' \ + -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' && break + sleep 0.1 +done +export MEMORYD_URL="http://127.0.0.1:$PORT/mcp" + +fail() { echo "FAIL: $*" >&2; exit 1; } + +cgi() { + method=$1 + uri=$2 + qs='' + case "$uri" in + *\?*) qs=${uri#*\?} ;; + esac + if [ "$method" = POST ]; then + body=$3 + printf '%s' "$body" | REQUEST_METHOD=POST REQUEST_URI="$uri" \ + QUERY_STRING="$qs" CONTENT_LENGTH=${#body} ./memoryd-http + else + REQUEST_METHOD=GET REQUEST_URI="$uri" QUERY_STRING="$qs" ./memoryd-http + fi +} + +# 1. leere Ablage +cgi GET / >"$DIR/out" +grep -q 'No memories found' "$DIR/out" || fail "empty list" +grep -q 'Content-Type: text/html' "$DIR/out" || fail "content type" + +# 2. anlegen +cgi POST /new 'text=First+memory+about+chlorine&scope=fleet/test&tags=water&source=test' >"$DIR/out" +grep -q 'stored m00001 in fleet/test' "$DIR/out" || fail "add memory" + +# 3. Liste +cgi GET / >"$DIR/out" +grep -q 'First memory about chlorine' "$DIR/out" || fail "list text" +grep -q 'href="/m/m00001"' "$DIR/out" || fail "list link" + +# 4. Detail +cgi GET /m/m00001 >"$DIR/out" +grep -q 'First memory about chlorine' "$DIR/out" || fail "detail" +grep -q 'fleet/test' "$DIR/out" || fail "detail scope" + +# 5. Bearbeiten (Formular und POST) +cgi GET /m/m00001/edit >"$DIR/out" +grep -q 'name="text"' "$DIR/out" || fail "edit form" +grep -q 'value="water"' "$DIR/out" || fail "edit tags" +cgi POST /m/m00001/edit 'text=Updated+memory+text&scope=fleet/test&tags=water,safety' >"$DIR/out" +grep -q 'updated m00001' "$DIR/out" || fail "update memory" +cgi GET /m/m00001 >"$DIR/out" +grep -q 'Updated memory text' "$DIR/out" || fail "update visible" + +# 6. Suche +cgi GET '/search?q=memory' >"$DIR/out" +grep -q 'm00001' "$DIR/out" || fail "search hit" + +# 7. Scopes +cgi GET /scopes >"$DIR/out" +grep -q 'fleet/test' "$DIR/out" || fail "scopes" + +# 8. Löschen (nur POST) +cgi GET /m/m00001/delete >"$DIR/out" +grep -q 'Deletion needs a POST' "$DIR/out" || fail "delete needs POST" +cgi POST /m/m00001/delete '' >"$DIR/out" +grep -q 'deleted m00001' "$DIR/out" || fail "delete memory" +cgi GET / >"$DIR/out" +grep -q 'No memories found' "$DIR/out" || fail "deleted still listed" + +echo "memoryd-http: ok" diff --git a/vendor/cgi/cgi.h b/vendor/cgi/cgi.h new file mode 100644 index 0000000..c34aaca --- /dev/null +++ b/vendor/cgi/cgi.h @@ -0,0 +1,642 @@ +/* + * cgi.h — shared CGI helpers for the fleet's MCP daemons. + * + * Header-only. Include libmcp's mcp.h first (with MCP_IMPLEMENTATION in + * exactly one translation unit); this file uses mcp_buf and the JSON parser. + * + * What it gives a CGI program: + * - CGI environment: base URL, PATH_INFO/REQUEST_URI routing, POST body + * - HTML 4.01 shell with a common navigation across the fleet UIs + * - escaping, URL decoding, form parameters + * - a minimal Markdown renderer + * - cg_rpc(): one MCP tools/call over HTTP via curl + * + * Every daemon answers with result.content[0].text. Text replies stay text; + * JSON replies are parsed by the caller with cg_rpc_json(). + */ +#ifndef FLEET_CGI_H +#define FLEET_CGI_H + +#include +#include +#include +#include +#include + +#if defined(__GNUC__) +#define CG_UNUSED __attribute__((unused)) +#else +#define CG_UNUSED +#endif + +/* ------------------------------------------------------------------ escaping */ + +static CG_UNUSED void cg_html(const char *s) +{ + for (; s != NULL && *s; s++) { + switch (*s) { + case '&': fputs("&", stdout); break; + case '<': fputs("<", stdout); break; + case '>': fputs(">", stdout); break; + case '"': fputs(""", stdout); break; + default: putchar(*s); break; + } + } +} + +static CG_UNUSED void cg_html_n(const char *s, size_t n) +{ + size_t i; + + for (i = 0; i < n; i++) { + switch (s[i]) { + case '&': fputs("&", stdout); break; + case '<': fputs("<", stdout); break; + case '>': fputs(">", stdout); break; + case '"': fputs(""", stdout); break; + default: putchar(s[i]); break; + } + } +} + +static CG_UNUSED char *cg_url_decode(char *s) +{ + char *r = s, *w = s; + + for (; *r; r++, w++) { + if (*r == '+') { + *w = ' '; + } else if (*r == '%' && isxdigit((unsigned char)r[1]) && + isxdigit((unsigned char)r[2])) { + char hex[3] = { r[1], r[2], 0 }; + + *w = (char)strtol(hex, NULL, 16); + r += 2; + } else { + *w = *r; + } + } + *w = '\0'; + return s; +} + +/* Copy one URL-encoded parameter out of qs. malloc'd; caller frees. */ +static CG_UNUSED char *cg_param(const char *qs, const char *name) +{ + size_t nlen = strlen(name); + + for (const char *p = qs; p != NULL && *p; ) { + if (strncmp(p, name, nlen) == 0 && p[nlen] == '=') { + const char *val = p + nlen + 1; + const char *end = strchr(val, '&'); + size_t vlen = end != NULL ? (size_t)(end - val) : strlen(val); + char *out = malloc(vlen + 1); + + if (out == NULL) + return NULL; + memcpy(out, val, vlen); + out[vlen] = '\0'; + cg_url_decode(out); + return out; + } + p = strchr(p, '&'); + if (p != NULL) + p++; + } + return NULL; +} + +/* ------------------------------------------------------------------- env */ + +static CG_UNUSED const char *cg_method(void) +{ + const char *m = getenv("REQUEST_METHOD"); + + return (m != NULL && *m != '\0') ? m : "GET"; +} + +/* "" at the root, otherwise SCRIPT_NAME ("/cgi-bin/memoryd-http"). */ +static CG_UNUSED const char *cg_base(void) +{ + static char base[256]; + static int done; + + if (!done) { + const char *s = getenv("SCRIPT_NAME"); + + base[0] = '\0'; + if (s != NULL && *s != '\0' && strcmp(s, "/") != 0) + snprintf(base, sizeof(base), "%s", s); + done = 1; + } + return base; +} + +/* Percent-encode a query-string value (letters, digits and -_.~/ stay). */ +static CG_UNUSED void cg_urlenc(const char *s) +{ + for (; s != NULL && *s; s++) { + unsigned char c = (unsigned char)*s; + + if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~' || + c == '/') + putchar(c); + else + printf("%%%02X", c); + } +} + +/* Print an internal link target (base + suffix). */ +static CG_UNUSED void cg_link(const char *suffix) +{ + fputs(cg_base(), stdout); + fputs(suffix, stdout); +} + +/* PATH_INFO when the server provides it, else REQUEST_URI minus base. */ +static CG_UNUSED void cg_route(char *path, size_t pathlen, char *query, size_t querylen) +{ + const char *uri = getenv("REQUEST_URI"); + const char *pi = getenv("PATH_INFO"); + const char *qs = getenv("QUERY_STRING"); + const char *base = cg_base(); + size_t i; + + if (uri == NULL) + uri = "/"; + if (pi != NULL && *pi != '\0') { + uri = pi; + } else if (*base != '\0' && strncmp(uri, base, strlen(base)) == 0) { + uri += strlen(base); + if (*uri == '\0') + uri = "/"; + } + snprintf(path, pathlen, "%s", uri); + for (i = 0; path[i] != '\0' && path[i] != '?'; i++) + ; + if (path[i] == '?') { + if (querylen > 0) + snprintf(query, querylen, "%s", path + i + 1); + path[i] = '\0'; + } else if (querylen > 0) { + query[0] = '\0'; + } + if (querylen > 0 && query[0] == '\0' && qs != NULL && *qs != '\0') + snprintf(query, querylen, "%s", qs); +} + +static CG_UNUSED char *cg_read_body(void) +{ + const char *cl = getenv("CONTENT_LENGTH"); + long len; + char *body; + size_t got = 0; + + if (cl == NULL) + return NULL; + len = strtol(cl, NULL, 10); + if (len <= 0 || len > 1024 * 1024) + return NULL; + body = malloc((size_t)len + 1); + if (body == NULL) + return NULL; + while (got < (size_t)len) { + size_t r = fread(body + got, 1, (size_t)len - got, stdin); + + if (r == 0) + break; + got += r; + } + body[got] = '\0'; + return body; +} + +static CG_UNUSED void cg_header(void) +{ + printf("Content-Type: text/html; charset=utf-8\r\n\r\n"); +} + +/* --------------------------------------------------------------- chrome */ + +struct cg_app { + const char *file; + const char *label; +}; + +static CG_UNUSED const struct cg_app cg_apps[] = { + { "wikid-http", "Wiki" }, + { "memoryd-http", "Memories" }, + { "skilld-http", "Skills" }, + { "tasksd-http", "Tasks" }, +}; + +static CG_UNUSED void cg_nav(const char *active) +{ + char dir[256] = ""; + const char *base = cg_base(); + const char *slash = strrchr(base, '/'); + const char *here = slash != NULL ? slash + 1 : base; + + if (slash != NULL) { + size_t n = (size_t)(slash - base) + 1; + + if (n >= sizeof(dir)) + n = sizeof(dir) - 1; + memcpy(dir, base, n); + dir[n] = '\0'; + } + fputs("
", stdout); + for (size_t i = 0; i < sizeof(cg_apps) / sizeof(cg_apps[0]); i++) { + int on = active != NULL && strcmp(active, cg_apps[i].file) == 0; + + fputs("", stdout); + if (on) + fputs("", stdout); + fputs(cg_apps[i].label, stdout); + if (on) + fputs("", stdout); + fputs(" ", stdout); + } + (void)here; + fputs("
\n", stdout); +} + +static CG_UNUSED const char *cg_css = +"body{font-family:serif;margin:1.5em;max-width:76em;background:#fff;color:#222}\n" +"h1,h2,h3,h4{margin-top:1.1em;margin-bottom:0.35em}\n" +"a{color:#0055aa;text-decoration:none}\n" +"a:hover{text-decoration:underline}\n" +"code{background:#f4f4f4;padding:0.08em 0.25em;font-size:0.92em}\n" +"pre{background:#f7f7f7;border:1px solid #ddd;padding:0.7em;overflow:auto;font-size:0.9em}\n" +"textarea{width:100%;max-width:72em;font-family:monospace;font-size:0.95em}\n" +"input[type=text]{max-width:62em;width:100%;font-family:monospace}\n" +".topnav{border-bottom:2px solid #ccc;padding-bottom:0.45em;margin-bottom:1.2em}\n" +".topnav a{margin-right:1.2em;font-size:1.05em}\n" +".meta{color:#666;font-size:0.86em}\n" +".item{border-bottom:1px solid #e6e6e6;padding:0.65em 0}\n" +".head{font-size:0.95em}\n" +".scope{color:#0055aa}\n" +".actions{margin-top:0.35em;font-size:0.9em}\n" +".actions a,.actions form{display:inline-block;margin-right:0.9em}\n" +".actions input[type=submit]{font-size:0.85em}\n" +"form.inline{display:inline}\n" +"table.list{border-collapse:collapse;width:100%;margin:0.7em 0}\n" +"table.list td,table.list th{border-bottom:1px solid #ddd;padding:0.3em 0.55em;text-align:left;vertical-align:top}\n" +"table.list th{background:#f2f2f2}\n" +".state{display:inline-block;padding:0.02em 0.45em;border:1px solid #999;font-size:0.78em;text-transform:uppercase;letter-spacing:0.03em}\n" +".s-pending{background:#fff;color:#333}\n" +".s-running{background:#e6f2ff;color:#004c99}\n" +".s-paused{background:#fff6d8;color:#7a5c00}\n" +".s-done{background:#e8f8e8;color:#1a661a}\n" +".s-dropped{background:#f0f0f0;color:#777}\n" +".msg{border-left:4px solid #9c9;background:#f4faf4;padding:0.5em 0.8em;margin:0.8em 0}\n" +".err{border-left:4px solid #c66;background:#fdf4f4;padding:0.5em 0.8em;margin:0.8em 0;color:#800}\n"; + +static CG_UNUSED void cg_head(const char *active, const char *title) +{ + fputs("\n" + "\n\n" + "\n" + "", stdout); + cg_html(title); + fputs("\n\n\n\n", stdout); + cg_nav(active); +} + +static CG_UNUSED void cg_foot(void) +{ + fputs("\n\n", stdout); +} + +static CG_UNUSED void cg_error_page(const char *active, const char *title, const char *msg) +{ + cg_head(active, title); + fputs("

", stdout); + cg_html(title); + fputs("

\n
", stdout); + cg_html(msg != NULL ? msg : "unknown error"); + fputs("
\n", stdout); + cg_foot(); +} + +static CG_UNUSED void cg_pre(const char *s) +{ + fputs("
", stdout);
+	cg_html(s != NULL ? s : "");
+	fputs("
\n", stdout); +} + +static CG_UNUSED void cg_time(long t) +{ + time_t tt = (time_t)t; + struct tm tm; + char buf[32]; + + if (t <= 0) { + fputs("-", stdout); + return; + } + if (localtime_r(&tt, &tm) == NULL) { + printf("%ld", t); + return; + } + strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M", &tm); + fputs(buf, stdout); +} + +/* --------------------------------------------------------------- markdown */ + +static CG_UNUSED void cg_put_esc(char c) +{ + switch (c) { + case '&': fputs("&", stdout); break; + case '<': fputs("<", stdout); break; + case '>': fputs(">", stdout); break; + case '"': fputs(""", stdout); break; + default: putchar(c); break; + } +} + +static CG_UNUSED void cg_md_inline(const char **pp) +{ + const char *p = *pp; + + while (*p != '\0' && *p != '\n') { + if (*p == '*' && p[1] == '*') { + fputs("", stdout); + p += 2; + while (*p != '\0' && !(*p == '*' && p[1] == '*') && *p != '\n') + cg_put_esc(*p++); + if (*p == '*') + p++; + fputs("", stdout); + } else if (*p == '*') { + fputs("", stdout); + p++; + while (*p != '\0' && *p != '*' && *p != '\n') + cg_put_esc(*p++); + if (*p == '*') + p++; + fputs("", stdout); + } else if (*p == '`') { + if (p[1] == '`') { + p += 2; /* empty span, emit nothing */ + continue; + } + fputs("", stdout); + p++; + while (*p != '\0' && *p != '`' && *p != '\n') + cg_put_esc(*p++); + if (*p == '`') + p++; + fputs("", stdout); + } else if (*p == '&') { + fputs("&", stdout); + p++; + } else if (*p == '<') { + fputs("<", stdout); + p++; + } else if (*p == '>') { + fputs(">", stdout); + p++; + } else { + putchar(*p++); + } + } + *pp = p; +} + +static CG_UNUSED void cg_md(const char *text) +{ + const char *p = text; + int in_para = 0, in_list = 0; + + if (text == NULL) + return; + while (*p != '\0') { + if (strncmp(p, "```", 3) == 0) { + const char *eol = strchr(p, '\n'); + const char *code, *end, *stop; + + if (eol == NULL) { + p += 3; + continue; + } + code = eol + 1; + stop = strstr(code, "\n```"); + end = stop != NULL ? stop : code + strlen(code); + if (in_para) { fputs("

\n", stdout); in_para = 0; } + if (in_list) { fputs("\n", stdout); in_list = 0; } + fputs("
", stdout);
+			cg_html_n(code, (size_t)(end - code));
+			fputs("
\n", stdout); + if (stop != NULL) { + p = stop + 4; + while (*p == '\n') + p++; + } else { + p = end; + } + continue; + } + if (*p == '#') { + int level = 0; + + while (*p == '#') { + level++; + p++; + } + while (*p == ' ') + p++; + if (in_para) { fputs("

\n", stdout); in_para = 0; } + if (in_list) { fputs("\n", stdout); in_list = 0; } + if (level > 6) + level = 6; + printf("", level); + cg_md_inline(&p); + printf("\n", level); + continue; + } + if (*p == '-' && (p[1] == ' ' || p[1] == '\t')) { + if (in_para) { fputs("

\n", stdout); in_para = 0; } + if (!in_list) { fputs("
    \n", stdout); in_list = 1; } + fputs("
  • ", stdout); + p += 2; + cg_md_inline(&p); + fputs("
  • \n", stdout); + continue; + } + if (strncmp(p, "---", 3) == 0 && (p[3] == '\n' || p[3] == '\0')) { + if (in_para) { fputs("

    \n", stdout); in_para = 0; } + if (in_list) { fputs("
\n", stdout); in_list = 0; } + fputs("
\n", stdout); + p += 3; + while (*p == '\n') + p++; + continue; + } + if (*p == '\n') { + if (in_para) { + fputs("

\n", stdout); + in_para = 0; + } else if (in_list && (p[1] == '\n' || p[1] == '\0')) { + fputs("\n", stdout); + in_list = 0; + } + p++; + continue; + } + if (!in_para) { + if (in_list) { fputs("\n", stdout); in_list = 0; } + fputs("

", stdout); + in_para = 1; + } + cg_md_inline(&p); + if (*p == '\n') { + if (p[1] != '\n' && p[1] != '\0') + fputs("
\n", stdout); + p++; + } + } + if (in_para) + fputs("

\n", stdout); + if (in_list) + fputs("\n", stdout); +} + +/* ------------------------------------------------------------------ JSON args */ + +static CG_UNUSED void cg_args_add_str(mcp_buf *b, int *first, const char *key, + const char *val) +{ + if (val == NULL) + return; + if (!*first) + mcp_buf_puts(b, ","); + *first = 0; + mcp_buf_printf(b, "\"%s\":\"", key); + mcp_json_escape(b, val); + mcp_buf_puts(b, "\""); +} + +static CG_UNUSED void cg_args_add_int(mcp_buf *b, int *first, const char *key, int val) +{ + if (!*first) + mcp_buf_puts(b, ","); + *first = 0; + mcp_buf_printf(b, "\"%s\":%d", key, val); +} + +static CG_UNUSED void cg_args_add_bool(mcp_buf *b, int *first, const char *key, int val) +{ + if (!*first) + mcp_buf_puts(b, ","); + *first = 0; + mcp_buf_printf(b, "\"%s\":%s", key, val ? "true" : "false"); +} + +/* -------------------------------------------------------------------- RPC */ + +static CG_UNUSED void cg_shell_quote(mcp_buf *b, const char *s) +{ + mcp_buf_puts(b, "'"); + for (; s != NULL && *s; s++) { + if (*s == '\'') + mcp_buf_puts(b, "'\\''"); + else + mcp_buf_add(b, s, 1); + } + mcp_buf_puts(b, "'"); +} + +/* One tools/call. Returns the text reply (malloc'd) or NULL. */ +static CG_UNUSED char *cg_rpc(const char *env, const char *dflt, const char *tool, + const char *args) +{ + mcp_buf body, cmd, raw; + const char *url; + FILE *fp; + char chunk[4096]; + size_t got; + mcp_json *v; + const mcp_json *result, *content, *first; + const char *text; + char *out = NULL; + + url = (env != NULL) ? getenv(env) : NULL; + if (url == NULL || *url == '\0') + url = dflt; + + mcp_buf_init(&body); + mcp_buf_puts(&body, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\"," + "\"params\":{\"name\":\""); + mcp_json_escape(&body, tool); + mcp_buf_puts(&body, "\",\"arguments\":"); + mcp_buf_puts(&body, (args != NULL && *args != '\0') ? args : "{}"); + mcp_buf_puts(&body, "}}"); + + mcp_buf_init(&cmd); + mcp_buf_puts(&cmd, "curl -sS -m 120 -X POST " + "-H 'Content-Type: application/json' -d "); + cg_shell_quote(&cmd, body.p != NULL ? body.p : "{}"); + mcp_buf_puts(&cmd, " "); + cg_shell_quote(&cmd, url); + mcp_buf_puts(&cmd, " 2>/dev/null"); + mcp_buf_free(&body); + + fp = popen(cmd.p != NULL ? cmd.p : "true", "r"); + mcp_buf_free(&cmd); + if (fp == NULL) + return NULL; + mcp_buf_init(&raw); + while ((got = fread(chunk, 1, sizeof(chunk), fp)) > 0) { + mcp_buf_add(&raw, chunk, got); + if (raw.p == NULL) + break; + } + pclose(fp); + if (raw.p == NULL) { + mcp_buf_free(&raw); + return NULL; + } + + v = mcp_parse(raw.p); + mcp_buf_free(&raw); + if (v == NULL) + return NULL; + result = mcp_arg(v, "result"); + content = mcp_arg(result, "content"); + first = mcp_array_at(content, 0); + text = mcp_arg_string(first, "text"); + if (text == NULL) { + const mcp_json *err = mcp_arg(v, "error"); + + text = mcp_arg_string(err, "message"); + } + if (text != NULL) + out = strdup(text); + mcp_json_free(v); + return out; +} + +/* tools/call whose text reply is JSON. Caller frees with mcp_json_free(). */ +static CG_UNUSED mcp_json *cg_rpc_json(const char *env, const char *dflt, + const char *tool, const char *args) +{ + char *text = cg_rpc(env, dflt, tool, args); + mcp_json *v; + + if (text == NULL) + return NULL; + v = mcp_parse(text); + free(text); + return v; +} + +#endif /* FLEET_CGI_H */