| 1 | /* |
| 2 | * api.c - the CGI front end for plugin_memory: the browser page and the JSON |
| 3 | * actions it talks to. |
| 4 | * |
| 5 | * There is deliberately no second implementation of the graph operations here. |
| 6 | * Every action maps onto one of the nine tools in tools.c, so the page and an |
| 7 | * agent going through --mcp see exactly the same thing - the same skips, the |
| 8 | * same not-found messages, the same relation rules. When the two are separate |
| 9 | * they drift, and the drift only ever shows up in production. |
| 10 | * |
| 11 | * Parameters are read from the QUERY_STRING *and* from a JSON body, because |
| 12 | * the UI posts JSON (it must: an observation can be any text) while a person |
| 13 | * debugging with curl expects a query string. `action` and `format` are kept |
| 14 | * in separate buffers on purpose - reading one into the other's variable |
| 15 | * silently degrades an action request to the default action. |
| 16 | * |
| 17 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 18 | */ |
| 19 | |
| 20 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 21 | # define _WIN32_WINNT 0x0601 |
| 22 | #endif |
| 23 | |
| 24 | #if !defined(_WIN32) |
| 25 | # define _POSIX_C_SOURCE 200809L |
| 26 | # define _DEFAULT_SOURCE 1 |
| 27 | # if defined(__APPLE__) |
| 28 | # define _DARWIN_C_SOURCE 1 |
| 29 | # endif |
| 30 | #endif |
| 31 | |
| 32 | #include <stdio.h> |
| 33 | #include <stdlib.h> |
| 34 | #include <string.h> |
| 35 | #include <ctype.h> |
| 36 | #include <time.h> |
| 37 | |
| 38 | #if defined(_WIN32) |
| 39 | # define WIN32_LEAN_AND_MEAN |
| 40 | # include <windows.h> |
| 41 | #else |
| 42 | # include <unistd.h> |
| 43 | #endif |
| 44 | |
| 45 | #include "memory.h" |
| 46 | #include "bot_theme_plugin.h" |
| 47 | #include "ui_html.h" |
| 48 | |
| 49 | /* ------------------------------------------------------------------ */ |
| 50 | /* Query string */ |
| 51 | /* ------------------------------------------------------------------ */ |
| 52 | |
| 53 | static void url_decode(char *s) |
| 54 | { |
| 55 | char *o = s; |
| 56 | if (!s) return; |
| 57 | while (*s) { |
| 58 | if (*s == '%' && isxdigit((unsigned char)s[1]) && |
| 59 | isxdigit((unsigned char)s[2])) { |
| 60 | int hi = (s[1] <= '9') ? s[1] - '0' |
| 61 | : (tolower((unsigned char)s[1]) - 'a' + 10); |
| 62 | int lo = (s[2] <= '9') ? s[2] - '0' |
| 63 | : (tolower((unsigned char)s[2]) - 'a' + 10); |
| 64 | *o++ = (char)((hi << 4) | lo); |
| 65 | s += 3; |
| 66 | } else if (*s == '+') { |
| 67 | *o++ = ' '; |
| 68 | s++; |
| 69 | } else { |
| 70 | *o++ = *s++; |
| 71 | } |
| 72 | } |
| 73 | *o = '\0'; |
| 74 | } |
| 75 | |
| 76 | static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) |
| 77 | { |
| 78 | size_t klen; |
| 79 | const char *p = qs; |
| 80 | |
| 81 | if (out && outsz) out[0] = '\0'; |
| 82 | if (!qs || !*qs || !key || !out || outsz == 0) return 0; |
| 83 | klen = strlen(key); |
| 84 | |
| 85 | while (p && *p) { |
| 86 | const char *eq = strchr(p, '='); |
| 87 | const char *amp = strchr(p, '&'); |
| 88 | if (!eq || (amp && eq > amp)) { |
| 89 | p = amp ? amp + 1 : NULL; |
| 90 | continue; |
| 91 | } |
| 92 | if ((size_t)(eq - p) == klen && strncmp(p, key, klen) == 0) { |
| 93 | const char *vs = eq + 1; |
| 94 | size_t n = amp ? (size_t)(amp - vs) : strlen(vs); |
| 95 | if (n >= outsz) n = outsz - 1; |
| 96 | memcpy(out, vs, n); |
| 97 | out[n] = '\0'; |
| 98 | url_decode(out); |
| 99 | return 1; |
| 100 | } |
| 101 | p = amp ? amp + 1 : NULL; |
| 102 | } |
| 103 | return 0; |
| 104 | } |
| 105 | |
| 106 | /* ------------------------------------------------------------------ */ |
| 107 | /* Request body */ |
| 108 | /* ------------------------------------------------------------------ */ |
| 109 | |
| 110 | static char g_body[REQ_BODY_MAX]; |
| 111 | |
| 112 | /* Read the body only when CONTENT_LENGTH says there is one: a CGI handler |
| 113 | * that reads stdin unconditionally hangs on an inherited empty stdin. */ |
| 114 | static int read_request_body(void) |
| 115 | { |
| 116 | const char *cl = getenv("CONTENT_LENGTH"); |
| 117 | long len; |
| 118 | size_t got; |
| 119 | |
| 120 | g_body[0] = '\0'; |
| 121 | if (!cl || !*cl) return 0; |
| 122 | len = strtol(cl, NULL, 10); |
| 123 | if (len <= 0) return 0; |
| 124 | if ((size_t)len >= sizeof g_body) return -1; |
| 125 | got = fread(g_body, 1, (size_t)len, stdin); |
| 126 | g_body[got] = '\0'; |
| 127 | return (int)got; |
| 128 | } |
| 129 | |
| 130 | static yyjson_doc *g_body_doc = NULL; |
| 131 | |
| 132 | static yyjson_val *body_root(void) |
| 133 | { |
| 134 | return g_body_doc ? yyjson_doc_get_root(g_body_doc) : NULL; |
| 135 | } |
| 136 | |
| 137 | /* One parameter: query string first, then the JSON body. Strings are |
| 138 | * returned in `out`; `has` says whether either source had it. */ |
| 139 | static int param_str(const char *qs, const char *key, char *out, size_t outsz) |
| 140 | { |
| 141 | if (out && outsz) out[0] = '\0'; |
| 142 | if (qs && get_query_val(qs, key, out, outsz) && out[0]) return 1; |
| 143 | { |
| 144 | yyjson_val *root = body_root(); |
| 145 | yyjson_val *v = root ? yyjson_obj_get(root, key) : NULL; |
| 146 | if (v && yyjson_is_str(v)) { |
| 147 | str_copy(out, outsz, yyjson_get_str(v)); |
| 148 | return 1; |
| 149 | } |
| 150 | } |
| 151 | return 0; |
| 152 | } |
| 153 | |
| 154 | /* An array parameter (e.g. names[], observations[]) from either source. A |
| 155 | * query string accepts a JSON array value or a |-separated list. */ |
| 156 | static yyjson_val *body_arr(const char *key) |
| 157 | { |
| 158 | yyjson_val *root = body_root(); |
| 159 | yyjson_val *v = root ? yyjson_obj_get(root, key) : NULL; |
| 160 | return (v && yyjson_is_arr(v)) ? v : NULL; |
| 161 | } |
| 162 | |
| 163 | /* ------------------------------------------------------------------ */ |
| 164 | /* Node authentication */ |
| 165 | /* */ |
| 166 | /* The node's :8150 is LAN-reachable, and this plugin can read and write the |
| 167 | * operator's knowledge graph, so it must not answer a bare curl. Three |
| 168 | * credential forms are accepted because the three callers differ: bot-web |
| 169 | * proxies with a header, the plugin iframe appends ?pwd=, and a script may |
| 170 | * send a bearer token. --meta stays open so /plugins can still discover us. */ |
| 171 | /* ------------------------------------------------------------------ */ |
| 172 | |
| 173 | static void require_node_auth(void) |
| 174 | { |
| 175 | const char *np = getenv("BOT_PASSWORD"); |
| 176 | const char *xp, *auth, *qs; |
| 177 | char qpwd[256]; |
| 178 | |
| 179 | if (!np || !*np) return; /* node has no password set */ |
| 180 | |
| 181 | xp = getenv("HTTP_X_BOT_PASSWORD"); |
| 182 | if (xp && strcmp(xp, np) == 0) return; |
| 183 | |
| 184 | auth = getenv("HTTP_AUTHORIZATION"); |
| 185 | if (auth) { |
| 186 | while (*auth == ' ') auth++; |
| 187 | if (strncmp(auth, "Bearer ", 7) == 0) { |
| 188 | auth += 7; |
| 189 | while (*auth == ' ') auth++; |
| 190 | if (strcmp(auth, np) == 0) return; |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | qs = getenv("QUERY_STRING"); |
| 195 | if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && |
| 196 | strcmp(qpwd, np) == 0) return; |
| 197 | |
| 198 | fputs("Status: 401 Unauthorized\r\n" |
| 199 | "Content-Type: application/json; charset=utf-8\r\n" |
| 200 | "Cache-Control: no-store\r\n" |
| 201 | "X-Content-Type-Options: nosniff\r\n\r\n" |
| 202 | "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); |
| 203 | exit(0); |
| 204 | } |
| 205 | |
| 206 | /* ------------------------------------------------------------------ */ |
| 207 | /* Responses */ |
| 208 | /* ------------------------------------------------------------------ */ |
| 209 | |
| 210 | static void json_header(void) |
| 211 | { |
| 212 | fputs("Content-Type: application/json; charset=utf-8\r\n" |
| 213 | "Cache-Control: no-store\r\n" |
| 214 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 215 | } |
| 216 | |
| 217 | static void json_raw(const char *json) |
| 218 | { |
| 219 | json_header(); |
| 220 | fputs(json ? json : "{\"ok\":true}", stdout); |
| 221 | fputc('\n', stdout); |
| 222 | fflush(stdout); |
| 223 | } |
| 224 | |
| 225 | static void json_err(int code, const char *msg) |
| 226 | { |
| 227 | buf_t b; |
| 228 | const char *status = NULL; |
| 229 | |
| 230 | if (code == 400) status = "Status: 400 Bad Request\r\n"; |
| 231 | else if (code == 404) status = "Status: 404 Not Found\r\n"; |
| 232 | else if (code == 413) status = "Status: 413 Payload Too Large\r\n"; |
| 233 | else status = "Status: 500 Internal Server Error\r\n"; |
| 234 | |
| 235 | buf_init(&b); |
| 236 | buf_puts(&b, status); |
| 237 | buf_puts(&b, "Content-Type: application/json; charset=utf-8\r\n" |
| 238 | "Cache-Control: no-store\r\n" |
| 239 | "X-Content-Type-Options: nosniff\r\n\r\n" |
| 240 | "{\"ok\":false,\"status\":"); |
| 241 | { char t[8]; snprintf(t, sizeof t, "%d", code); buf_puts(&b, t); } |
| 242 | buf_puts(&b, ",\"error\":"); |
| 243 | json_str(&b, msg ? msg : "error"); |
| 244 | buf_puts(&b, "}"); |
| 245 | fputs(buf_str(&b), stdout); |
| 246 | fputc('\n', stdout); |
| 247 | fflush(stdout); |
| 248 | buf_free(&b); |
| 249 | } |
| 250 | |
| 251 | /* Run a tool and answer with its result, mapping the tool's own error to a |
| 252 | * 200 + ok:false so the UI can show the message the reference server gives |
| 253 | * rather than a bare HTTP status. */ |
| 254 | /* Run one tool for an HTTP action. The UI's arguments were assembled into a |
| 255 | * mutable document, so serialize it and re-parse: the tools read the |
| 256 | * immutable yyjson_val API, and a cast between the two types would be a |
| 257 | * silent type-lie that only yyjson's internals could expose. At these sizes |
| 258 | * one round trip costs nothing, and both types stay exactly what they are. */ |
| 259 | static void run_tool(const char *name, yyjson_mut_doc *md, |
| 260 | yyjson_mut_val *root) |
| 261 | { |
| 262 | tool_out_t t; |
| 263 | char *s; |
| 264 | char *packed = NULL; |
| 265 | yyjson_doc *parsed = NULL; |
| 266 | yyjson_val *args = NULL; |
| 267 | |
| 268 | if (md && root) { |
| 269 | packed = yyjson_mut_write(md, 0, NULL); |
| 270 | if (packed) { |
| 271 | parsed = yyjson_read(packed, strlen(packed), 0); |
| 272 | if (parsed) args = yyjson_doc_get_root(parsed); |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | tool_out_init(&t); |
| 277 | if (tool_dispatch(name, args, &t) != 0) { |
| 278 | tool_free(&t); |
| 279 | free(packed); |
| 280 | if (parsed) yyjson_doc_free(parsed); |
| 281 | json_err(400, "unknown action"); |
| 282 | return; |
| 283 | } |
| 284 | s = tool_api_result(&t); |
| 285 | json_raw(s); |
| 286 | free(s); |
| 287 | tool_free(&t); |
| 288 | free(packed); |
| 289 | if (parsed) yyjson_doc_free(parsed); |
| 290 | } |
| 291 | |
| 292 | /* ------------------------------------------------------------------ */ |
| 293 | /* Args assembled from the request */ |
| 294 | /* ------------------------------------------------------------------ */ |
| 295 | |
| 296 | /* Build a mutable doc so we can graft arrays taken from the body together |
| 297 | * with scalars from the query string, and hand the tools one object either |
| 298 | * way. The doc owns the memory the tools read during dispatch. */ |
| 299 | typedef struct { |
| 300 | yyjson_mut_doc *md; |
| 301 | yyjson_mut_val *root; |
| 302 | } args_t; |
| 303 | |
| 304 | static void args_init(args_t *a) |
| 305 | { |
| 306 | memset(a, 0, sizeof *a); |
| 307 | a->md = yyjson_mut_doc_new(NULL); |
| 308 | if (!a->md) return; |
| 309 | a->root = yyjson_mut_obj(a->md); |
| 310 | if (a->root) yyjson_mut_doc_set_root(a->md, a->root); |
| 311 | } |
| 312 | |
| 313 | static void args_free(args_t *a) |
| 314 | { |
| 315 | if (a && a->md) yyjson_mut_doc_free(a->md); |
| 316 | memset(a, 0, sizeof *a); |
| 317 | } |
| 318 | |
| 319 | static void args_add_str(args_t *a, const char *k, const char *v) |
| 320 | { |
| 321 | if (a->root) yyjson_mut_obj_add_str(a->md, a->root, k, v ? v : ""); |
| 322 | } |
| 323 | |
| 324 | static void args_add_int(args_t *a, const char *k, long v) |
| 325 | { |
| 326 | if (a->root) yyjson_mut_obj_add_sint(a->md, a->root, k, (int64_t)v); |
| 327 | } |
| 328 | |
| 329 | /* A string array: from the body when present, else a |-separated query value, |
| 330 | * else a repeated single value. */ |
| 331 | static void args_add_arr(args_t *a, const char *k, const char *qval) |
| 332 | { |
| 333 | yyjson_val *src = body_arr(k); |
| 334 | (void)qval; |
| 335 | yyjson_mut_val *arr = a->root ? yyjson_mut_arr(a->md) : NULL; |
| 336 | if (!arr) return; |
| 337 | |
| 338 | if (src) { |
| 339 | size_t i, n = yyjson_arr_size(src); |
| 340 | for (i = 0; i < n; i++) { |
| 341 | yyjson_val *v = yyjson_arr_get(src, i); |
| 342 | if (v && yyjson_is_str(v)) |
| 343 | yyjson_mut_arr_add_str(a->md, arr, yyjson_get_str(v)); |
| 344 | } |
| 345 | } else if (qval && *qval) { |
| 346 | /* '|' separated, with \%7C available for a literal pipe. */ |
| 347 | const char *p = qval; |
| 348 | while (*p) { |
| 349 | const char *s = strchr(p, '|'); |
| 350 | size_t len = s ? (size_t)(s - p) : strlen(p); |
| 351 | char tmp[OBS_TEXT_MAX]; |
| 352 | if (len >= sizeof tmp) len = sizeof tmp - 1; |
| 353 | memcpy(tmp, p, len); |
| 354 | tmp[len] = '\0'; |
| 355 | yyjson_mut_arr_add_str(a->md, arr, tmp); |
| 356 | if (!s) break; |
| 357 | p = s + 1; |
| 358 | } |
| 359 | } |
| 360 | if (a->root) yyjson_mut_obj_add_val(a->md, a->root, k, arr); |
| 361 | } |
| 362 | |
| 363 | /* ------------------------------------------------------------------ */ |
| 364 | /* Actions */ |
| 365 | /* ------------------------------------------------------------------ */ |
| 366 | |
| 367 | static void do_stats(const char *qs) |
| 368 | { |
| 369 | long long size = 0; |
| 370 | int exists = 0; |
| 371 | size_t i, n_obs = 0, types_seen = 0; |
| 372 | const char **types = NULL; |
| 373 | buf_t b; |
| 374 | |
| 375 | (void)qs; |
| 376 | if (graph_load() != 0) { json_err(500, g_data_err); return; } |
| 377 | graph_path_info(&size, &exists); |
| 378 | for (i = 0; i < G.n_ent; i++) n_obs += G.ent[i].n_obs; |
| 379 | |
| 380 | /* distinct types, for the filter chips */ |
| 381 | types = (const char **)calloc(G.n_ent ? G.n_ent : 1, sizeof *types); |
| 382 | buf_init(&b); |
| 383 | buf_puts(&b, "{\"ok\":true,\"entities\":"); |
| 384 | { char t[32]; snprintf(t, sizeof t, "%zu", G.n_ent); buf_puts(&b, t); } |
| 385 | buf_puts(&b, ",\"relations\":"); |
| 386 | { char t[32]; snprintf(t, sizeof t, "%zu", G.n_rel); buf_puts(&b, t); } |
| 387 | buf_puts(&b, ",\"observations\":"); |
| 388 | { char t[32]; snprintf(t, sizeof t, "%zu", n_obs); buf_puts(&b, t); } |
| 389 | buf_puts(&b, ",\"unreadable_lines\":"); |
| 390 | { char t[32]; snprintf(t, sizeof t, "%zu", G.n_bad); buf_puts(&b, t); } |
| 391 | buf_puts(&b, ",\"file_exists\":"); |
| 392 | buf_puts(&b, exists ? "true" : "false"); |
| 393 | buf_puts(&b, ",\"file_bytes\":"); |
| 394 | { char t[32]; snprintf(t, sizeof t, "%lld", size); buf_puts(&b, t); } |
| 395 | buf_puts(&b, ",\"types\":["); |
| 396 | if (types) { |
| 397 | for (i = 0; i < G.n_ent; i++) { |
| 398 | size_t j; |
| 399 | int seen = 0; |
| 400 | for (j = 0; j < types_seen; j++) |
| 401 | if (strcmp(types[j], G.ent[i].etype) == 0) { seen = 1; break; } |
| 402 | if (seen) continue; |
| 403 | if (types_seen >= 200) break; |
| 404 | types[types_seen++] = G.ent[i].etype; |
| 405 | if (types_seen > 1) buf_putc(&b, ','); |
| 406 | json_str(&b, G.ent[i].etype); |
| 407 | } |
| 408 | } |
| 409 | buf_puts(&b, "]}"); |
| 410 | json_raw(buf_str(&b)); |
| 411 | buf_free(&b); |
| 412 | free((void *)types); |
| 413 | } |
| 414 | |
| 415 | static void do_graph(const char *qs) |
| 416 | { |
| 417 | char types[4096], lim[32]; |
| 418 | args_t a; |
| 419 | |
| 420 | args_init(&a); |
| 421 | if (param_str(qs, "entityTypes", types, sizeof types)) |
| 422 | args_add_arr(&a, "entityTypes", types); |
| 423 | if (param_str(qs, "limit", lim, sizeof lim)) |
| 424 | args_add_int(&a, "limit", strtol(lim, NULL, 10)); |
| 425 | run_tool("read_graph", a.md, a.root); |
| 426 | args_free(&a); |
| 427 | } |
| 428 | |
| 429 | static void do_search(const char *qs) |
| 430 | { |
| 431 | char q[512], lim[32], ol[32]; |
| 432 | args_t a; |
| 433 | |
| 434 | if (!param_str(qs, "q", q, sizeof q) || !q[0]) { |
| 435 | json_err(400, "missing q"); |
| 436 | return; |
| 437 | } |
| 438 | args_init(&a); |
| 439 | args_add_str(&a, "query", q); |
| 440 | if (param_str(qs, "limit", lim, sizeof lim)) |
| 441 | args_add_int(&a, "limit", strtol(lim, NULL, 10)); |
| 442 | if (param_str(qs, "observationLimit", ol, sizeof ol)) |
| 443 | args_add_int(&a, "observationLimit", strtol(ol, NULL, 10)); |
| 444 | run_tool("search_nodes", a.md, a.root); |
| 445 | args_free(&a); |
| 446 | } |
| 447 | |
| 448 | static void do_entity(const char *qs) |
| 449 | { |
| 450 | char name[SX_NAME_MAX * 2]; |
| 451 | args_t a; |
| 452 | |
| 453 | if (!param_str(qs, "name", name, sizeof name) || !name[0]) { |
| 454 | json_err(400, "missing name"); |
| 455 | return; |
| 456 | } |
| 457 | args_init(&a); |
| 458 | { |
| 459 | yyjson_mut_val *arr = yyjson_mut_arr(a.md); |
| 460 | yyjson_mut_arr_add_strcpy(a.md, arr, name); |
| 461 | yyjson_mut_obj_add_val(a.md, a.root, "names", arr); |
| 462 | } |
| 463 | run_tool("open_nodes", a.md, a.root); |
| 464 | args_free(&a); |
| 465 | } |
| 466 | |
| 467 | static void do_add_entity(const char *qs) |
| 468 | { |
| 469 | char name[SX_NAME_MAX * 2], type[SX_TYPE_MAX * 2]; |
| 470 | args_t a; |
| 471 | yyjson_mut_val *ents, *ent; |
| 472 | yyjson_val *bobs; |
| 473 | |
| 474 | if (!param_str(qs, "name", name, sizeof name) || !name[0]) { |
| 475 | json_err(400, "missing name"); return; |
| 476 | } |
| 477 | if (!param_str(qs, "entityType", type, sizeof type) || !type[0]) { |
| 478 | json_err(400, "missing entityType"); return; |
| 479 | } |
| 480 | args_init(&a); |
| 481 | ents = yyjson_mut_arr(a.md); |
| 482 | ent = yyjson_mut_obj(a.md); |
| 483 | yyjson_mut_obj_add_strcpy(a.md, ent, "name", name); |
| 484 | yyjson_mut_obj_add_strcpy(a.md, ent, "entityType", type); |
| 485 | bobs = body_arr("observations"); |
| 486 | if (!bobs) { |
| 487 | char obs[OBS_TEXT_MAX * 4]; |
| 488 | if (param_str(qs, "observations", obs, sizeof obs)) { |
| 489 | const char *p = obs; |
| 490 | yyjson_mut_val *arr = yyjson_mut_arr(a.md); |
| 491 | while (*p) { |
| 492 | const char *s = strchr(p, '|'); |
| 493 | size_t len = s ? (size_t)(s - p) : strlen(p); |
| 494 | char tmp[OBS_TEXT_MAX]; |
| 495 | if (len >= sizeof tmp) len = sizeof tmp - 1; |
| 496 | memcpy(tmp, p, len); |
| 497 | tmp[len] = '\0'; |
| 498 | if (*tmp) yyjson_mut_arr_add_strcpy(a.md, arr, tmp); |
| 499 | if (!s) break; |
| 500 | p = s + 1; |
| 501 | } |
| 502 | yyjson_mut_obj_add_val(a.md, ent, "observations", arr); |
| 503 | } else { |
| 504 | yyjson_mut_obj_add_val(a.md, ent, "observations", |
| 505 | yyjson_mut_arr(a.md)); |
| 506 | } |
| 507 | } else { |
| 508 | yyjson_mut_val *arr = yyjson_mut_arr(a.md); |
| 509 | size_t i, n = yyjson_arr_size(bobs); |
| 510 | for (i = 0; i < n; i++) { |
| 511 | yyjson_val *v = yyjson_arr_get(bobs, i); |
| 512 | if (v && yyjson_is_str(v)) |
| 513 | yyjson_mut_arr_add_strcpy(a.md, arr, yyjson_get_str(v)); |
| 514 | } |
| 515 | yyjson_mut_obj_add_val(a.md, ent, "observations", arr); |
| 516 | } |
| 517 | yyjson_mut_arr_add_val(ents, ent); |
| 518 | yyjson_mut_obj_add_val(a.md, a.root, "entities", ents); |
| 519 | run_tool("create_entities", a.md, a.root); |
| 520 | args_free(&a); |
| 521 | } |
| 522 | |
| 523 | static void do_add_relation(const char *qs) |
| 524 | { |
| 525 | char from[SX_NAME_MAX * 2], to[SX_NAME_MAX * 2], type[SX_TYPE_MAX * 2]; |
| 526 | args_t a; |
| 527 | yyjson_mut_val *rels, *rel; |
| 528 | |
| 529 | if (!param_str(qs, "from", from, sizeof from) || !from[0]) { |
| 530 | json_err(400, "missing from"); return; |
| 531 | } |
| 532 | if (!param_str(qs, "to", to, sizeof to) || !to[0]) { |
| 533 | json_err(400, "missing to"); return; |
| 534 | } |
| 535 | if (!param_str(qs, "relationType", type, sizeof type) || !type[0]) { |
| 536 | json_err(400, "missing relationType"); return; |
| 537 | } |
| 538 | args_init(&a); |
| 539 | rels = yyjson_mut_arr(a.md); |
| 540 | rel = yyjson_mut_obj(a.md); |
| 541 | yyjson_mut_obj_add_strcpy(a.md, rel, "from", from); |
| 542 | yyjson_mut_obj_add_strcpy(a.md, rel, "to", to); |
| 543 | yyjson_mut_obj_add_strcpy(a.md, rel, "relationType", type); |
| 544 | yyjson_mut_arr_add_val(rels, rel); |
| 545 | yyjson_mut_obj_add_val(a.md, a.root, "relations", rels); |
| 546 | run_tool("create_relations", a.md, a.root); |
| 547 | args_free(&a); |
| 548 | } |
| 549 | |
| 550 | static void do_add_obs(const char *qs) |
| 551 | { |
| 552 | char name[SX_NAME_MAX * 2]; |
| 553 | args_t a; |
| 554 | yyjson_mut_val *obs, *one, *arr; |
| 555 | yyjson_val *bcontents; |
| 556 | |
| 557 | if (!param_str(qs, "name", name, sizeof name) || !name[0]) { |
| 558 | json_err(400, "missing name"); return; |
| 559 | } |
| 560 | args_init(&a); |
| 561 | obs = yyjson_mut_arr(a.md); |
| 562 | one = yyjson_mut_obj(a.md); |
| 563 | arr = yyjson_mut_arr(a.md); |
| 564 | yyjson_mut_obj_add_strcpy(a.md, one, "entityName", name); |
| 565 | |
| 566 | bcontents = body_arr("contents"); |
| 567 | if (bcontents) { |
| 568 | size_t i, n = yyjson_arr_size(bcontents); |
| 569 | for (i = 0; i < n; i++) { |
| 570 | yyjson_val *v = yyjson_arr_get(bcontents, i); |
| 571 | if (v && yyjson_is_str(v)) |
| 572 | yyjson_mut_arr_add_strcpy(a.md, arr, yyjson_get_str(v)); |
| 573 | } |
| 574 | } else { |
| 575 | char contents[OBS_TEXT_MAX * 4]; |
| 576 | if (param_str(qs, "contents", contents, sizeof contents)) { |
| 577 | const char *p = contents; |
| 578 | while (*p) { |
| 579 | const char *s = strchr(p, '|'); |
| 580 | size_t len = s ? (size_t)(s - p) : strlen(p); |
| 581 | char tmp[OBS_TEXT_MAX]; |
| 582 | if (len >= sizeof tmp) len = sizeof tmp - 1; |
| 583 | memcpy(tmp, p, len); |
| 584 | tmp[len] = '\0'; |
| 585 | if (*tmp) yyjson_mut_arr_add_strcpy(a.md, arr, tmp); |
| 586 | if (!s) break; |
| 587 | p = s + 1; |
| 588 | } |
| 589 | } |
| 590 | } |
| 591 | yyjson_mut_obj_add_val(a.md, one, "contents", arr); |
| 592 | yyjson_mut_arr_add_val(obs, one); |
| 593 | yyjson_mut_obj_add_val(a.md, a.root, "observations", obs); |
| 594 | run_tool("add_observations", a.md, a.root); |
| 595 | args_free(&a); |
| 596 | } |
| 597 | |
| 598 | static void do_delete_entity(const char *qs) |
| 599 | { |
| 600 | char name[SX_NAME_MAX * 2]; |
| 601 | args_t a; |
| 602 | yyjson_mut_val *arr; |
| 603 | |
| 604 | if (!param_str(qs, "name", name, sizeof name) || !name[0]) { |
| 605 | json_err(400, "missing name"); return; |
| 606 | } |
| 607 | args_init(&a); |
| 608 | arr = yyjson_mut_arr(a.md); |
| 609 | yyjson_mut_arr_add_strcpy(a.md, arr, name); |
| 610 | yyjson_mut_obj_add_val(a.md, a.root, "entityNames", arr); |
| 611 | run_tool("delete_entities", a.md, a.root); |
| 612 | args_free(&a); |
| 613 | } |
| 614 | |
| 615 | static void do_delete_relation(const char *qs) |
| 616 | { |
| 617 | char from[SX_NAME_MAX * 2], to[SX_NAME_MAX * 2], type[SX_TYPE_MAX * 2]; |
| 618 | args_t a; |
| 619 | yyjson_mut_val *rels, *rel; |
| 620 | |
| 621 | if (!param_str(qs, "from", from, sizeof from) || !from[0] || |
| 622 | !param_str(qs, "to", to, sizeof to) || !to[0] || |
| 623 | !param_str(qs, "relationType", type, sizeof type) || !type[0]) { |
| 624 | json_err(400, "from, to and relationType are all required"); |
| 625 | return; |
| 626 | } |
| 627 | args_init(&a); |
| 628 | rels = yyjson_mut_arr(a.md); |
| 629 | rel = yyjson_mut_obj(a.md); |
| 630 | yyjson_mut_obj_add_strcpy(a.md, rel, "from", from); |
| 631 | yyjson_mut_obj_add_strcpy(a.md, rel, "to", to); |
| 632 | yyjson_mut_obj_add_strcpy(a.md, rel, "relationType", type); |
| 633 | yyjson_mut_arr_add_val(rels, rel); |
| 634 | yyjson_mut_obj_add_val(a.md, a.root, "relations", rels); |
| 635 | run_tool("delete_relations", a.md, a.root); |
| 636 | args_free(&a); |
| 637 | } |
| 638 | |
| 639 | static void do_delete_obs(const char *qs) |
| 640 | { |
| 641 | char name[SX_NAME_MAX * 2]; |
| 642 | args_t a; |
| 643 | yyjson_mut_val *deletions, *one, *arr; |
| 644 | yyjson_val *bobs; |
| 645 | |
| 646 | if (!param_str(qs, "name", name, sizeof name) || !name[0]) { |
| 647 | json_err(400, "missing name"); return; |
| 648 | } |
| 649 | args_init(&a); |
| 650 | deletions = yyjson_mut_arr(a.md); |
| 651 | one = yyjson_mut_obj(a.md); |
| 652 | arr = yyjson_mut_arr(a.md); |
| 653 | yyjson_mut_obj_add_strcpy(a.md, one, "entityName", name); |
| 654 | |
| 655 | bobs = body_arr("observations"); |
| 656 | if (bobs) { |
| 657 | size_t i, n = yyjson_arr_size(bobs); |
| 658 | for (i = 0; i < n; i++) { |
| 659 | yyjson_val *v = yyjson_arr_get(bobs, i); |
| 660 | if (v && yyjson_is_str(v)) |
| 661 | yyjson_mut_arr_add_strcpy(a.md, arr, yyjson_get_str(v)); |
| 662 | } |
| 663 | } else { |
| 664 | char obs[OBS_TEXT_MAX * 4]; |
| 665 | if (param_str(qs, "observations", obs, sizeof obs)) { |
| 666 | const char *p = obs; |
| 667 | while (*p) { |
| 668 | const char *s = strchr(p, '|'); |
| 669 | size_t len = s ? (size_t)(s - p) : strlen(p); |
| 670 | char tmp[OBS_TEXT_MAX]; |
| 671 | if (len >= sizeof tmp) len = sizeof tmp - 1; |
| 672 | memcpy(tmp, p, len); |
| 673 | tmp[len] = '\0'; |
| 674 | if (*tmp) yyjson_mut_arr_add_strcpy(a.md, arr, tmp); |
| 675 | if (!s) break; |
| 676 | p = s + 1; |
| 677 | } |
| 678 | } |
| 679 | } |
| 680 | yyjson_mut_obj_add_val(a.md, one, "observations", arr); |
| 681 | yyjson_mut_arr_add_val(deletions, one); |
| 682 | yyjson_mut_obj_add_val(a.md, a.root, "deletions", deletions); |
| 683 | run_tool("delete_observations", a.md, a.root); |
| 684 | args_free(&a); |
| 685 | } |
| 686 | |
| 687 | /* The raw JSONL, for an operator who wants to diff or back up the graph. |
| 688 | * Served as text/plain with a filename so the browser offers a download. */ |
| 689 | static void do_export(void) |
| 690 | { |
| 691 | char *text; |
| 692 | size_t len = 0; |
| 693 | const char *p = graph_path(); |
| 694 | |
| 695 | if (graph_load() != 0) { json_err(500, g_data_err); return; } |
| 696 | { |
| 697 | FILE *f = (p && *p) ? fopen(p, "rb") : NULL; |
| 698 | text = NULL; |
| 699 | if (f) { |
| 700 | long sz; |
| 701 | fseek(f, 0, SEEK_END); |
| 702 | sz = ftell(f); |
| 703 | if (sz < 0) sz = 0; |
| 704 | if ((size_t)sz > (size_t)FILE_MAX) sz = (long)FILE_MAX; |
| 705 | if (sz > 0) fseek(f, 0, SEEK_SET); |
| 706 | text = (char *)malloc((size_t)sz + 1); |
| 707 | if (text) len = fread(text, 1, (size_t)sz, f); |
| 708 | text[len] = '\0'; |
| 709 | fclose(f); |
| 710 | } |
| 711 | } |
| 712 | |
| 713 | fputs("Content-Type: text/plain; charset=utf-8\r\n" |
| 714 | "Cache-Control: no-store\r\n" |
| 715 | "X-Content-Type-Options: nosniff\r\n" |
| 716 | "Content-Disposition: attachment; filename=\"memory.jsonl\"\r\n\r\n", |
| 717 | stdout); |
| 718 | if (text && len) fwrite(text, 1, len, stdout); |
| 719 | free(text); |
| 720 | fflush(stdout); |
| 721 | } |
| 722 | |
| 723 | /* tools/list over HTTP - the same schemas an MCP host gets, so the Setup UI |
| 724 | * and an agent can never disagree about what this connector offers. */ |
| 725 | static void do_tools(void) |
| 726 | { |
| 727 | char *t = tools_list_json(); |
| 728 | buf_t b; |
| 729 | buf_init(&b); |
| 730 | buf_puts(&b, "{\"ok\":true,\"connector\":\"" PLUGIN_ID |
| 731 | "\",\"kind\":\"mcp\",\"protocol\":\"" MCP_PROTOCOL |
| 732 | "\",\"tools\":"); |
| 733 | buf_puts(&b, t ? t : "[]"); |
| 734 | buf_puts(&b, "}"); |
| 735 | json_raw(buf_str(&b)); |
| 736 | buf_free(&b); |
| 737 | free(t); |
| 738 | } |
| 739 | |
| 740 | /* ------------------------------------------------------------------ */ |
| 741 | /* The page */ |
| 742 | /* ------------------------------------------------------------------ */ |
| 743 | |
| 744 | static void emit_ui(void) |
| 745 | { |
| 746 | const char *p = UI_HTML; |
| 747 | |
| 748 | while (*p) { |
| 749 | if (*p == '\001') { |
| 750 | fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS |
| 751 | "</style>", stdout); |
| 752 | p++; |
| 753 | } else if (*p == '\002') { |
| 754 | fputs(SX_BOT_THEME_HANDOFF, stdout); |
| 755 | p++; |
| 756 | } else { |
| 757 | putchar(*p++); |
| 758 | } |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | static void mode_html(void) |
| 763 | { |
| 764 | fputs("Content-Type: text/html; charset=utf-8\r\n" |
| 765 | "Cache-Control: no-store\r\n" |
| 766 | "X-Content-Type-Options: nosniff\r\n" |
| 767 | "X-Frame-Options: SAMEORIGIN\r\n" |
| 768 | "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " |
| 769 | "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " |
| 770 | "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); |
| 771 | emit_ui(); |
| 772 | } |
| 773 | |
| 774 | /* ------------------------------------------------------------------ */ |
| 775 | /* Entry */ |
| 776 | /* ------------------------------------------------------------------ */ |
| 777 | |
| 778 | static const char *method(void) |
| 779 | { |
| 780 | const char *m = getenv("REQUEST_METHOD"); |
| 781 | return (m && *m) ? m : "GET"; |
| 782 | } |
| 783 | |
| 784 | int api_handle(void) |
| 785 | { |
| 786 | const char *qs = getenv("QUERY_STRING"); |
| 787 | char action[64], act[64], fmt[32]; |
| 788 | int got; |
| 789 | |
| 790 | if (!qs) qs = ""; |
| 791 | action[0] = '\0'; |
| 792 | act[0] = '\0'; |
| 793 | fmt[0] = '\0'; |
| 794 | |
| 795 | require_node_auth(); |
| 796 | |
| 797 | got = read_request_body(); |
| 798 | if (got < 0) { json_err(413, "the request body is too large"); return 0; } |
| 799 | if (got > 0) { |
| 800 | g_body_doc = yyjson_read(g_body, strlen(g_body), 0); |
| 801 | if (!g_body_doc) { |
| 802 | json_err(400, "the request body is not valid JSON"); |
| 803 | return 0; |
| 804 | } |
| 805 | } |
| 806 | |
| 807 | /* Two buffers on purpose: parsing `format` into `action` would clobber the |
| 808 | * action we just parsed and silently answer the default one. */ |
| 809 | if (!get_query_val(qs, "action", action, sizeof action)) { |
| 810 | if (param_str(qs, "action", action, sizeof action)) { /* body action */ } |
| 811 | } |
| 812 | if (!action[0]) { |
| 813 | if (get_query_val(qs, "format", fmt, sizeof fmt) && |
| 814 | strcmp(fmt, "json") == 0) |
| 815 | str_copy(action, sizeof action, "graph"); |
| 816 | else if (strcmp(method(), "POST") == 0) { |
| 817 | json_err(400, "missing action"); |
| 818 | return 0; |
| 819 | } |
| 820 | } |
| 821 | str_copy(act, sizeof act, action); |
| 822 | |
| 823 | if (act[0]) { |
| 824 | if (strcmp(act, "stats") == 0) { do_stats(qs); } |
| 825 | else if (strcmp(act, "graph") == 0) { do_graph(qs); } |
| 826 | else if (strcmp(act, "search") == 0) { do_search(qs); } |
| 827 | else if (strcmp(act, "entity") == 0) { do_entity(qs); } |
| 828 | else if (strcmp(act, "add_entity") == 0) { do_add_entity(qs); } |
| 829 | else if (strcmp(act, "add_relation") == 0){ do_add_relation(qs); } |
| 830 | else if (strcmp(act, "add_obs") == 0) { do_add_obs(qs); } |
| 831 | else if (strcmp(act, "delete_entity") == 0) { do_delete_entity(qs); } |
| 832 | else if (strcmp(act, "delete_relation") == 0) { do_delete_relation(qs); } |
| 833 | else if (strcmp(act, "delete_obs") == 0) { do_delete_obs(qs); } |
| 834 | else if (strcmp(act, "tools") == 0) { do_tools(); } |
| 835 | else if (strcmp(act, "export") == 0) { do_export(); } |
| 836 | else json_err(400, "unknown action"); |
| 837 | if (g_body_doc) yyjson_doc_free(g_body_doc); |
| 838 | return 0; |
| 839 | } |
| 840 | |
| 841 | mode_html(); |
| 842 | if (g_body_doc) yyjson_doc_free(g_body_doc); |
| 843 | return 0; |
| 844 | } |