| 1 | /* |
| 2 | * plugin_seqthink - SCORPIOX BOT open-source sequential-thinking connector |
| 3 | * |
| 4 | * One clean-room C99 binary with the four contracts a SCORPIOX BOT connector |
| 5 | * plugin implements: |
| 6 | * |
| 7 | * 1. --meta / SX_PLUGIN_META=1 -> one line of JSON discovery metadata |
| 8 | * (unauthenticated, so the node can always discover it) |
| 9 | * 2. --mcp -> MCP JSON-RPC 2.0 over stdio: |
| 10 | * initialize / notifications/initialized / ping / tools/list / tools/call. |
| 11 | * One tool: sequentialthinking {thought, nextThoughtNeeded, thoughtNumber, |
| 12 | * totalThoughts, isRevision?, revisesThought?, branchFromThought?, |
| 13 | * branchId?, needsMoreThoughts?} |
| 14 | * 3. ?action=... (+ POST JSON) -> JSON node API behind require_node_auth(): |
| 15 | * chains / chain / stats / info / clear |
| 16 | * 4. GET (default) -> responsive dark/light HTML page (behind |
| 17 | * require_node_auth(), same as the JSON API): a thought-chain timeline |
| 18 | * (revisions, branches, progress) built from the snapshots the --mcp leg |
| 19 | * persists. |
| 20 | * |
| 21 | * The tool is a clean-room C port of the behaviour of modelcontextprotocol |
| 22 | * `servers/src/sequentialthinking` (the sequential-thinking MCP server): |
| 23 | * identical parameter validation and error strings, the same "raise |
| 24 | * totalThoughts when thoughtNumber exceeds it" rule, a per-connection thought |
| 25 | * history with a MAX_THOUGHT_HISTORY cap (default 1000, oldest evicted, its |
| 26 | * branch shrunk with it, an emptied branch dropped), branch keys created on |
| 27 | * the first thought that carries BOTH branchFromThought and branchId, and the |
| 28 | * exact five-field result {thoughtNumber,totalThoughts,nextThoughtNeeded, |
| 29 | * branches,thoughtHistoryLength} returned as content[0].text AND as |
| 30 | * structuredContent. Validation failures come back as |
| 31 | * {"error":...,"status":"failed"} with isError:true, exactly as upstream. |
| 32 | * |
| 33 | * Beyond upstream: every accepted thought also snapshots its chain to |
| 34 | * <state_dir>/chains.json (POSIX: /workspace/.scorpiox/connectors/ |
| 35 | * plugin_seqthink when /workspace exists, else $HOME/.scorpiox/connectors/ |
| 36 | * plugin_seqthink; Windows: %LOCALAPPDATA%\scorpiox\connectors\plugin_seqthink; |
| 37 | * SEQTHINK_STATE_DIR overrides for tests) so the HTML UI can inspect recent |
| 38 | * reasoning without holding the MCP process open. Writes are read-modify- |
| 39 | * merge on chain id and go .tmp -> rename(), so a crash never leaves a |
| 40 | * half-written chains.json. The file is bounded (<= 50 chains, each <= 1000 |
| 41 | * thoughts). DISABLE_THOUGHT_LOGGING=1|true (upstream parity) silences both |
| 42 | * the stderr line and the persistence. |
| 43 | * |
| 44 | * Zero dependencies beyond the vendored yyjson: no TLS, no sockets, no |
| 45 | * popen. The only files it ever touches live under its own state directory. |
| 46 | * |
| 47 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 48 | */ |
| 49 | |
| 50 | /* Must come before every include: MinGW defaults _WIN32_WINNT to 0x502; |
| 51 | * Apple needs _DARWIN_C_SOURCE under -std=c99; MinGW needs its printf for %zu. */ |
| 52 | #ifndef _WIN32 |
| 53 | # ifndef _POSIX_C_SOURCE |
| 54 | # define _POSIX_C_SOURCE 200809L |
| 55 | # endif |
| 56 | # ifndef _DEFAULT_SOURCE |
| 57 | # define _DEFAULT_SOURCE 1 |
| 58 | # endif |
| 59 | #endif |
| 60 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 61 | # define _WIN32_WINNT 0x0601 |
| 62 | #endif |
| 63 | #if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) |
| 64 | # define _DARWIN_C_SOURCE 1 |
| 65 | #endif |
| 66 | #if defined(__MINGW32__) && !defined(__USE_MINGW_ANSI_STDIO) |
| 67 | # define __USE_MINGW_ANSI_STDIO 1 |
| 68 | #endif |
| 69 | |
| 70 | #include <stdio.h> |
| 71 | #include <stdlib.h> |
| 72 | #include <string.h> |
| 73 | #include <ctype.h> |
| 74 | #include <time.h> |
| 75 | #include <errno.h> |
| 76 | #include <limits.h> |
| 77 | #include <stdarg.h> |
| 78 | |
| 79 | #if defined(_WIN32) |
| 80 | # include <windows.h> |
| 81 | # include <io.h> |
| 82 | # include <fcntl.h> /* _O_BINARY, _setmode, _fileno */ |
| 83 | # include <direct.h> |
| 84 | # include <string.h> |
| 85 | # ifndef strncasecmp |
| 86 | # define strncasecmp _strnicmp |
| 87 | # endif |
| 88 | # ifndef _SSIZE_T_DEFINED |
| 89 | # define _SSIZE_T_DEFINED |
| 90 | typedef long long ssize_t; |
| 91 | # endif |
| 92 | #else |
| 93 | # include <unistd.h> |
| 94 | # include <strings.h> |
| 95 | # include <sys/stat.h> |
| 96 | # include <sys/types.h> |
| 97 | #endif |
| 98 | #include <sys/stat.h> |
| 99 | #include <sys/types.h> |
| 100 | |
| 101 | #include "yyjson.h" |
| 102 | #include "bot_theme_plugin.h" |
| 103 | #include "ui_html.h" |
| 104 | |
| 105 | #define PLUGIN_SLUG "seqthink" |
| 106 | #define PLUGIN_ID "plugin_seqthink" |
| 107 | #define PLUGIN_VER "1.0.1" |
| 108 | #define PLUGIN_NAME "seqthink" |
| 109 | #define PLUGIN_DESC "Thought chains" |
| 110 | |
| 111 | #define MAX_CHAINS 50 /* chains kept in chains.json */ |
| 112 | #define MAX_THOUGHTS_EACH 1000 /* thoughts kept per chain in the file */ |
| 113 | #define DEFAULT_MAX_HIST 1000 /* upstream DEFAULT_MAX_THOUGHT_HISTORY */ |
| 114 | #define THOUGHT_MAX 65536 /* longest accepted thought text */ |
| 115 | #define BRANCHID_MAX 128 |
| 116 | #define REQ_MAX (2u * 1024u * 1024u) |
| 117 | |
| 118 | #if defined(_WIN32) |
| 119 | # define sx_mkdir(p) _mkdir(p) |
| 120 | # define SX_PATHSEP '\\' |
| 121 | #else |
| 122 | # define sx_mkdir(p) mkdir((p), 0755) |
| 123 | # define SX_PATHSEP '/' |
| 124 | #endif |
| 125 | |
| 126 | /* ------------------------------------------------------------------ */ |
| 127 | /* Small helpers */ |
| 128 | /* ------------------------------------------------------------------ */ |
| 129 | |
| 130 | static void *sx_malloc(size_t n) |
| 131 | { |
| 132 | void *p = malloc(n ? n : 1); |
| 133 | if (!p) { |
| 134 | fputs("out of memory\n", stderr); |
| 135 | exit(1); |
| 136 | } |
| 137 | return p; |
| 138 | } |
| 139 | |
| 140 | static char *sx_strdup(const char *s) |
| 141 | { |
| 142 | size_t n; |
| 143 | char *p; |
| 144 | if (!s) s = ""; |
| 145 | n = strlen(s) + 1; |
| 146 | p = (char *)sx_malloc(n); |
| 147 | memcpy(p, s, n); |
| 148 | return p; |
| 149 | } |
| 150 | |
| 151 | typedef struct { |
| 152 | char *p; |
| 153 | size_t n; |
| 154 | size_t cap; |
| 155 | } buf_t; |
| 156 | |
| 157 | static void buf_init(buf_t *b) { b->p = NULL; b->n = 0; b->cap = 0; } |
| 158 | |
| 159 | static void buf_reserve(buf_t *b, size_t extra) |
| 160 | { |
| 161 | size_t want = b->n + extra + 1; |
| 162 | if (want <= b->cap) return; |
| 163 | { |
| 164 | size_t cap = b->cap ? b->cap : 256; |
| 165 | while (cap < want) cap *= 2; |
| 166 | b->p = (char *)realloc(b->p, cap); |
| 167 | if (!b->p) { fputs("out of memory\n", stderr); exit(1); } |
| 168 | b->cap = cap; |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | static void buf_add(buf_t *b, const char *s, size_t n) |
| 173 | { |
| 174 | buf_reserve(b, n); |
| 175 | memcpy(b->p + b->n, s, n); |
| 176 | b->n += n; |
| 177 | b->p[b->n] = '\0'; |
| 178 | } |
| 179 | |
| 180 | /* Append a NUL-terminated literal; the length is computed, never hand-typed. */ |
| 181 | static void buf_str(buf_t *b, const char *s) |
| 182 | { |
| 183 | if (s) buf_add(b, s, strlen(s)); |
| 184 | } |
| 185 | |
| 186 | static void buf_addf(buf_t *b, const char *fmt, ...) |
| 187 | { |
| 188 | va_list ap; |
| 189 | int need; |
| 190 | char tmp[512]; |
| 191 | va_start(ap, fmt); |
| 192 | need = vsnprintf(tmp, sizeof tmp, fmt, ap); |
| 193 | va_end(ap); |
| 194 | if (need < 0) return; |
| 195 | if ((size_t)need < sizeof tmp) { buf_add(b, tmp, (size_t)need); return; } |
| 196 | { |
| 197 | char *big = (char *)sx_malloc((size_t)need + 1); |
| 198 | va_start(ap, fmt); |
| 199 | vsnprintf(big, (size_t)need + 1, fmt, ap); |
| 200 | va_end(ap); |
| 201 | buf_add(b, big, (size_t)need); |
| 202 | free(big); |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | static void buf_free(buf_t *b) { free(b->p); buf_init(b); } |
| 207 | |
| 208 | /* getline() is POSIX; MinGW-w64 ships one but msvcrt's varies by release. A |
| 209 | * 40-line local version keeps the --mcp loop identical on every target. */ |
| 210 | #if defined(_WIN32) |
| 211 | static ssize_t sx_getline(char **lineptr, size_t *n, FILE *stream) |
| 212 | { |
| 213 | size_t len = 0, cap = *n ? *n : 128; |
| 214 | char *buf = *lineptr; |
| 215 | int c; |
| 216 | if (!buf) { |
| 217 | buf = (char *)malloc(cap); |
| 218 | if (!buf) return -1; |
| 219 | *lineptr = buf; |
| 220 | *n = cap; |
| 221 | } |
| 222 | c = fgetc(stream); |
| 223 | if (c == EOF) return -1; |
| 224 | while (c != EOF) { |
| 225 | if (len + 2 > cap) { |
| 226 | char *nb; |
| 227 | cap *= 2; |
| 228 | nb = (char *)realloc(buf, cap); |
| 229 | if (!nb) return -1; |
| 230 | buf = nb; |
| 231 | *lineptr = buf; |
| 232 | *n = cap; |
| 233 | } |
| 234 | buf[len++] = (char)c; |
| 235 | if (c == '\n') break; |
| 236 | c = fgetc(stream); |
| 237 | } |
| 238 | buf[len] = '\0'; |
| 239 | return (ssize_t)len; |
| 240 | } |
| 241 | # define getline(a, b, c) sx_getline((a), (b), (c)) |
| 242 | #endif |
| 243 | |
| 244 | /* JSON-escape s into b (with surrounding quotes). */ |
| 245 | static void json_escape_buf(buf_t *b, const char *s) |
| 246 | { |
| 247 | const unsigned char *p = (const unsigned char *)(s ? s : ""); |
| 248 | buf_str(b, "\""); |
| 249 | for (; *p; p++) { |
| 250 | switch (*p) { |
| 251 | case '"': buf_str(b, "\\\""); break; |
| 252 | case '\\': buf_str(b, "\\\\"); break; |
| 253 | case '\n': buf_str(b, "\\n"); break; |
| 254 | case '\r': buf_str(b, "\\r"); break; |
| 255 | case '\t': buf_str(b, "\\t"); break; |
| 256 | default: |
| 257 | if (*p < 0x20) buf_addf(b, "\\u%04x", (unsigned)*p); |
| 258 | else buf_add(b, (const char *)p, 1); |
| 259 | } |
| 260 | } |
| 261 | buf_str(b, "\""); |
| 262 | } |
| 263 | |
| 264 | static void json_escape(FILE *out, const char *s) |
| 265 | { |
| 266 | buf_t b; |
| 267 | buf_init(&b); |
| 268 | json_escape_buf(&b, s); |
| 269 | if (b.p) fwrite(b.p, 1, b.n, out); |
| 270 | buf_free(&b); |
| 271 | } |
| 272 | |
| 273 | /* Percent-decode in place for query values (the node hands QUERY_STRING raw). */ |
| 274 | static int hexval(int c) |
| 275 | { |
| 276 | if (c >= '0' && c <= '9') return c - '0'; |
| 277 | if (c >= 'a' && c <= 'f') return c - 'a' + 10; |
| 278 | if (c >= 'A' && c <= 'F') return c - 'A' + 10; |
| 279 | return -1; |
| 280 | } |
| 281 | |
| 282 | static void url_decode(char *s) |
| 283 | { |
| 284 | char *d = s; |
| 285 | while (*s) { |
| 286 | if (*s == '%' && hexval((unsigned char)s[1]) >= 0 && |
| 287 | hexval((unsigned char)s[2]) >= 0) { |
| 288 | *d++ = (char)(hexval((unsigned char)s[1]) * 16 + |
| 289 | hexval((unsigned char)s[2])); |
| 290 | s += 3; |
| 291 | } else if (*s == '+') { |
| 292 | *d++ = ' '; |
| 293 | s++; |
| 294 | } else { |
| 295 | *d++ = *s++; |
| 296 | } |
| 297 | } |
| 298 | *d = '\0'; |
| 299 | } |
| 300 | |
| 301 | static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) |
| 302 | { |
| 303 | size_t klen; |
| 304 | const char *p; |
| 305 | if (!qs || !key || !out || outsz == 0) return 0; |
| 306 | out[0] = '\0'; |
| 307 | klen = strlen(key); |
| 308 | p = qs; |
| 309 | while (p && *p) { |
| 310 | if (strncmp(p, key, klen) == 0 && p[klen] == '=') { |
| 311 | size_t i = 0; |
| 312 | p += klen + 1; |
| 313 | while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; |
| 314 | out[i] = '\0'; |
| 315 | url_decode(out); |
| 316 | return 1; |
| 317 | } |
| 318 | p = strchr(p, '&'); |
| 319 | if (p) p++; |
| 320 | } |
| 321 | return 0; |
| 322 | } |
| 323 | |
| 324 | /* ------------------------------------------------------------------ */ |
| 325 | /* Node authentication (X-Bot-Password | Bearer | ?pwd=). --meta and --mcp */ |
| 326 | /* never call this; the whole CGI surface (HTML page + every JSON action) does.*/ |
| 327 | /* ------------------------------------------------------------------ */ |
| 328 | |
| 329 | static void require_node_auth(void) |
| 330 | { |
| 331 | const char *np = getenv("BOT_PASSWORD"); |
| 332 | const char *xp, *auth; |
| 333 | char qpwd[256] = {0}; |
| 334 | const char *qs; |
| 335 | |
| 336 | if (!np || !*np) return; /* open node: no gate */ |
| 337 | xp = getenv("HTTP_X_BOT_PASSWORD"); |
| 338 | if (xp && strcmp(xp, np) == 0) return; |
| 339 | auth = getenv("HTTP_AUTHORIZATION"); |
| 340 | if (auth) { |
| 341 | while (*auth == ' ') auth++; |
| 342 | if (strncasecmp(auth, "Bearer ", 7) == 0) { |
| 343 | auth += 7; |
| 344 | while (*auth == ' ') auth++; |
| 345 | if (strcmp(auth, np) == 0) return; |
| 346 | } |
| 347 | } |
| 348 | qs = getenv("QUERY_STRING"); |
| 349 | if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && |
| 350 | strcmp(qpwd, np) == 0) |
| 351 | return; |
| 352 | |
| 353 | fputs("Status: 401 Unauthorized\r\n" |
| 354 | "Content-Type: application/json; charset=utf-8\r\n\r\n" |
| 355 | "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); |
| 356 | exit(0); |
| 357 | } |
| 358 | |
| 359 | /* ------------------------------------------------------------------ */ |
| 360 | /* State directory + chains.json */ |
| 361 | /* ------------------------------------------------------------------ */ |
| 362 | |
| 363 | static void state_dir(char *out, size_t outsz) |
| 364 | { |
| 365 | const char *env = getenv("SEQTHINK_STATE_DIR"); |
| 366 | #ifndef _WIN32 |
| 367 | struct stat st; |
| 368 | #endif |
| 369 | |
| 370 | if (env && *env) { snprintf(out, outsz, "%s", env); return; } |
| 371 | #ifndef _WIN32 |
| 372 | if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode) && |
| 373 | access("/workspace", W_OK) == 0) { |
| 374 | snprintf(out, outsz, "/workspace/.scorpiox/connectors/" PLUGIN_ID); |
| 375 | return; |
| 376 | } |
| 377 | #endif |
| 378 | #if defined(_WIN32) |
| 379 | { |
| 380 | const char *la = getenv("LOCALAPPDATA"); |
| 381 | if (la && *la) { |
| 382 | snprintf(out, outsz, "%s\\scorpiox\\connectors\\" PLUGIN_ID, la); |
| 383 | return; |
| 384 | } |
| 385 | } |
| 386 | #endif |
| 387 | { |
| 388 | const char *home = getenv("HOME"); |
| 389 | if (!home || !*home) home = "/root"; |
| 390 | snprintf(out, outsz, "%s/.scorpiox/connectors/" PLUGIN_ID, home); |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | /* state_dir_name exposes only the leaf directory name for the UI chip (no |
| 395 | * absolute path, no home directory name leaks into the browser). */ |
| 396 | static void state_dir_name(char *out, size_t outsz) |
| 397 | { |
| 398 | char dir[1000]; |
| 399 | char *slash; |
| 400 | size_t i; |
| 401 | state_dir(dir, sizeof dir); |
| 402 | slash = strrchr(dir, '/'); |
| 403 | if (!slash) slash = strrchr(dir, '\\'); |
| 404 | { |
| 405 | const char *s = slash ? slash + 1 : dir; |
| 406 | for (i = 0; s[i] && i + 1 < outsz; i++) out[i] = s[i]; |
| 407 | out[i] = '\0'; |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | static int mkdirs(const char *path) |
| 412 | { |
| 413 | char buf[1200]; |
| 414 | size_t i, n; |
| 415 | struct stat st; |
| 416 | snprintf(buf, sizeof buf, "%s", path); |
| 417 | n = strlen(buf); |
| 418 | for (i = 1; i < n; i++) { |
| 419 | if (buf[i] == '/' || buf[i] == '\\') { |
| 420 | char save = buf[i]; |
| 421 | buf[i] = '\0'; |
| 422 | if (i > 2) sx_mkdir(buf); |
| 423 | buf[i] = save; |
| 424 | } |
| 425 | } |
| 426 | sx_mkdir(buf); |
| 427 | return stat(buf, &st) == 0 && S_ISDIR(st.st_mode); |
| 428 | } |
| 429 | |
| 430 | static void chains_path(char *out, size_t outsz) |
| 431 | { |
| 432 | char dir[1000]; |
| 433 | state_dir(dir, sizeof dir); |
| 434 | snprintf(out, outsz, "%s%cchains.json", dir, SX_PATHSEP); |
| 435 | } |
| 436 | |
| 437 | static char *read_file(const char *path, size_t *lenp) |
| 438 | { |
| 439 | FILE *f; |
| 440 | long sz; |
| 441 | char *txt; |
| 442 | size_t got; |
| 443 | f = fopen(path, "rb"); |
| 444 | if (!f) return NULL; |
| 445 | fseek(f, 0, SEEK_END); |
| 446 | sz = ftell(f); |
| 447 | fseek(f, 0, SEEK_SET); |
| 448 | if (sz < 0 || sz > 8 * 1024 * 1024) { fclose(f); return NULL; } |
| 449 | txt = (char *)sx_malloc((size_t)sz + 1); |
| 450 | got = fread(txt, 1, (size_t)sz, f); |
| 451 | txt[got] = '\0'; |
| 452 | fclose(f); |
| 453 | if (lenp) *lenp = got; |
| 454 | return txt; |
| 455 | } |
| 456 | |
| 457 | static int write_file_atomic(const char *path, const char *data, size_t len) |
| 458 | { |
| 459 | char tmp[1300]; |
| 460 | FILE *f; |
| 461 | snprintf(tmp, sizeof tmp, "%s.tmp", path); |
| 462 | f = fopen(tmp, "wb"); |
| 463 | if (!f) return 0; |
| 464 | if (len && fwrite(data, 1, len, f) != len) { fclose(f); remove(tmp); return 0; } |
| 465 | if (fflush(f) != 0) { fclose(f); remove(tmp); return 0; } |
| 466 | fclose(f); |
| 467 | if (rename(tmp, path) != 0) { remove(tmp); return 0; } |
| 468 | return 1; |
| 469 | } |
| 470 | |
| 471 | /* ------------------------------------------------------------------ */ |
| 472 | /* Tool model */ |
| 473 | /* ------------------------------------------------------------------ */ |
| 474 | |
| 475 | typedef struct { |
| 476 | char *thought; /* heap, never NULL after validation */ |
| 477 | long long thought_number; |
| 478 | long long total_thoughts; |
| 479 | long long revises; /* 0 = absent */ |
| 480 | long long branch_from; /* 0 = absent */ |
| 481 | char *branch_id; /* NULL = absent */ |
| 482 | int is_revision; |
| 483 | int next_needed; |
| 484 | int needs_more; |
| 485 | } thought_t; |
| 486 | |
| 487 | typedef struct { |
| 488 | thought_t *v; |
| 489 | size_t n, cap; |
| 490 | } tvec_t; |
| 491 | |
| 492 | static void tvec_push(tvec_t *h, const thought_t *t) |
| 493 | { |
| 494 | if (h->n == h->cap) { |
| 495 | h->cap = h->cap ? h->cap * 2 : 16; |
| 496 | h->v = (thought_t *)realloc(h->v, h->cap * sizeof *h->v); |
| 497 | if (!h->v) { fputs("out of memory\n", stderr); exit(1); } |
| 498 | } |
| 499 | h->v[h->n++] = *t; |
| 500 | } |
| 501 | |
| 502 | static void thought_free(thought_t *t) |
| 503 | { |
| 504 | free(t->thought); |
| 505 | free(t->branch_id); |
| 506 | memset(t, 0, sizeof *t); |
| 507 | } |
| 508 | |
| 509 | /* Branch registry: insertion-ordered keys with per-branch thought counts. */ |
| 510 | typedef struct { |
| 511 | char *key; |
| 512 | size_t count; |
| 513 | } branch_t; |
| 514 | |
| 515 | typedef struct { |
| 516 | branch_t *v; |
| 517 | size_t n, cap; |
| 518 | } bvec_t; |
| 519 | |
| 520 | static int bvec_find(const bvec_t *b, const char *key) |
| 521 | { |
| 522 | size_t i; |
| 523 | for (i = 0; i < b->n; i++) |
| 524 | if (strcmp(b->v[i].key, key) == 0) return (int)i; |
| 525 | return -1; |
| 526 | } |
| 527 | |
| 528 | static void bvec_create(bvec_t *b, const char *key) |
| 529 | { |
| 530 | if (bvec_find(b, key) >= 0) return; |
| 531 | if (b->n == b->cap) { |
| 532 | b->cap = b->cap ? b->cap * 2 : 8; |
| 533 | b->v = (branch_t *)realloc(b->v, b->cap * sizeof *b->v); |
| 534 | if (!b->v) { fputs("out of memory\n", stderr); exit(1); } |
| 535 | } |
| 536 | b->v[b->n].key = sx_strdup(key); |
| 537 | b->v[b->n].count = 0; |
| 538 | b->n++; |
| 539 | } |
| 540 | |
| 541 | static void bvec_record(bvec_t *b, const char *key) |
| 542 | { |
| 543 | int i = bvec_find(b, key); |
| 544 | if (i < 0) { bvec_create(b, key); i = (int)b->n - 1; } |
| 545 | b->v[i].count++; |
| 546 | } |
| 547 | |
| 548 | static void bvec_evict(bvec_t *b, const char *key) |
| 549 | { |
| 550 | int i = bvec_find(b, key); |
| 551 | if (i < 0) return; |
| 552 | if (b->v[i].count > 0) b->v[i].count--; |
| 553 | if (b->v[i].count == 0) { /* upstream: an emptied branch is dropped */ |
| 554 | free(b->v[i].key); |
| 555 | memmove(&b->v[i], &b->v[i + 1], (b->n - (size_t)i - 1) * sizeof *b->v); |
| 556 | b->n--; |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | static long long read_max_history(void) |
| 561 | { |
| 562 | const char *raw = getenv("MAX_THOUGHT_HISTORY"); |
| 563 | const char *p; |
| 564 | long long v; |
| 565 | if (!raw) return DEFAULT_MAX_HIST; |
| 566 | while (*raw == ' ' || *raw == '\t') raw++; |
| 567 | if (!*raw) return DEFAULT_MAX_HIST; |
| 568 | for (p = raw; *p; p++) if (!isdigit((unsigned char)*p)) break; |
| 569 | if (*p != '\0' && !(p == raw + strlen(raw))) { /* trailing junk */ } |
| 570 | for (p = raw; *p; p++) { |
| 571 | if (!isdigit((unsigned char)*p)) { |
| 572 | fprintf(stderr, "MAX_THOUGHT_HISTORY must be a positive integer, " |
| 573 | "got \"%s\"; using %d\n", raw, DEFAULT_MAX_HIST); |
| 574 | return DEFAULT_MAX_HIST; |
| 575 | } |
| 576 | } |
| 577 | v = strtoll(raw, NULL, 10); |
| 578 | if (v < 1) { |
| 579 | fprintf(stderr, "MAX_THOUGHT_HISTORY must be a positive integer, " |
| 580 | "got \"%s\"; using %d\n", raw, DEFAULT_MAX_HIST); |
| 581 | return DEFAULT_MAX_HIST; |
| 582 | } |
| 583 | return v; |
| 584 | } |
| 585 | |
| 586 | /* Coerce a JSON value to boolean like upstream's coercedBoolean: real bool, |
| 587 | * or the strings "true"/"false" (case-insensitive). Returns 1 on success. */ |
| 588 | static int val_bool(yyjson_val *v, int *out) |
| 589 | { |
| 590 | if (yyjson_is_bool(v)) { *out = yyjson_is_true(v) ? 1 : 0; return 1; } |
| 591 | if (yyjson_is_str(v)) { |
| 592 | const char *s = yyjson_get_str(v); |
| 593 | size_t i, n; |
| 594 | char low[16]; |
| 595 | if (!s) return 0; |
| 596 | n = strlen(s); |
| 597 | if (n >= sizeof low) return 0; |
| 598 | for (i = 0; i < n; i++) low[i] = (char)tolower((unsigned char)s[i]); |
| 599 | low[n] = '\0'; |
| 600 | if (strcmp(low, "true") == 0) { *out = 1; return 1; } |
| 601 | if (strcmp(low, "false") == 0) { *out = 0; return 1; } |
| 602 | return 0; |
| 603 | } |
| 604 | return 0; |
| 605 | } |
| 606 | |
| 607 | /* Coerce to integer like z.coerce.number().int(): JSON number or a numeric |
| 608 | * string. Returns 1 on success. */ |
| 609 | static int val_int(yyjson_val *v, long long *out) |
| 610 | { |
| 611 | if (yyjson_is_int(v)) { *out = yyjson_get_sint(v); return 1; } |
| 612 | if (yyjson_is_uint(v)) { *out = (long long)yyjson_get_uint(v); return 1; } |
| 613 | if (yyjson_is_real(v)) { |
| 614 | double d = yyjson_get_real(v); |
| 615 | if (d == (double)(long long)d) { *out = (long long)d; return 1; } |
| 616 | return 0; |
| 617 | } |
| 618 | if (yyjson_is_str(v)) { |
| 619 | const char *s = yyjson_get_str(v); |
| 620 | char *end = NULL; |
| 621 | long long ll; |
| 622 | if (!s || !*s) return 0; |
| 623 | errno = 0; |
| 624 | ll = strtoll(s, &end, 10); |
| 625 | if (errno != 0 || !end) return 0; |
| 626 | while (*end == ' ' || *end == '\t' || *end == '\n' || *end == '\r') end++; |
| 627 | if (*end != '\0') return 0; |
| 628 | *out = ll; |
| 629 | return 1; |
| 630 | } |
| 631 | return 0; |
| 632 | } |
| 633 | |
| 634 | /* Validate against the upstream schema (errors mirror index.ts/lib.ts). */ |
| 635 | static int validate_thought(yyjson_val *args, thought_t *t, char *err, size_t errsz) |
| 636 | { |
| 637 | yyjson_val *v; |
| 638 | memset(t, 0, sizeof *t); |
| 639 | |
| 640 | v = yyjson_obj_get(args, "thought"); |
| 641 | if (!v || !yyjson_is_str(v) || !yyjson_get_str(v) || |
| 642 | !yyjson_get_str(v)[0]) { |
| 643 | snprintf(err, errsz, "Invalid thought: must be a string"); |
| 644 | return 0; |
| 645 | } |
| 646 | if (strlen(yyjson_get_str(v)) > THOUGHT_MAX) { |
| 647 | snprintf(err, errsz, "Invalid thought: too long (max %d bytes)", THOUGHT_MAX); |
| 648 | return 0; |
| 649 | } |
| 650 | t->thought = sx_strdup(yyjson_get_str(v)); |
| 651 | |
| 652 | v = yyjson_obj_get(args, "nextThoughtNeeded"); |
| 653 | if (!val_bool(v, &t->next_needed)) { |
| 654 | snprintf(err, errsz, "Invalid nextThoughtNeeded: must be a boolean"); |
| 655 | thought_free(t); |
| 656 | return 0; |
| 657 | } |
| 658 | |
| 659 | v = yyjson_obj_get(args, "thoughtNumber"); |
| 660 | { |
| 661 | long long n; |
| 662 | if (!val_int(v, &n) || n < 1) { |
| 663 | snprintf(err, errsz, "Invalid thoughtNumber: must be a number"); |
| 664 | thought_free(t); |
| 665 | return 0; |
| 666 | } |
| 667 | t->thought_number = n; |
| 668 | } |
| 669 | |
| 670 | v = yyjson_obj_get(args, "totalThoughts"); |
| 671 | { |
| 672 | long long n; |
| 673 | if (!val_int(v, &n) || n < 1) { |
| 674 | snprintf(err, errsz, "Invalid totalThoughts: must be a number"); |
| 675 | thought_free(t); |
| 676 | return 0; |
| 677 | } |
| 678 | t->total_thoughts = n; |
| 679 | } |
| 680 | |
| 681 | v = yyjson_obj_get(args, "isRevision"); |
| 682 | if (v && !yyjson_is_null(v) && !val_bool(v, &t->is_revision)) { |
| 683 | snprintf(err, errsz, "Invalid isRevision: must be a boolean"); |
| 684 | thought_free(t); |
| 685 | return 0; |
| 686 | } |
| 687 | |
| 688 | v = yyjson_obj_get(args, "revisesThought"); |
| 689 | if (v && !yyjson_is_null(v)) { |
| 690 | long long n; |
| 691 | if (!val_int(v, &n) || n < 1) { |
| 692 | snprintf(err, errsz, "Invalid revisesThought: must be a number"); |
| 693 | thought_free(t); |
| 694 | return 0; |
| 695 | } |
| 696 | t->revises = n; |
| 697 | } |
| 698 | |
| 699 | v = yyjson_obj_get(args, "branchFromThought"); |
| 700 | if (v && !yyjson_is_null(v)) { |
| 701 | long long n; |
| 702 | if (!val_int(v, &n) || n < 1) { |
| 703 | snprintf(err, errsz, "Invalid branchFromThought: must be a number"); |
| 704 | thought_free(t); |
| 705 | return 0; |
| 706 | } |
| 707 | t->branch_from = n; |
| 708 | } |
| 709 | |
| 710 | v = yyjson_obj_get(args, "branchId"); |
| 711 | if (v && !yyjson_is_null(v)) { |
| 712 | if (!yyjson_is_str(v) || !yyjson_get_str(v)) { |
| 713 | snprintf(err, errsz, "Invalid branchId: must be a string"); |
| 714 | thought_free(t); |
| 715 | return 0; |
| 716 | } |
| 717 | if (strlen(yyjson_get_str(v)) > BRANCHID_MAX) { |
| 718 | snprintf(err, errsz, "Invalid branchId: too long (max %d bytes)", |
| 719 | BRANCHID_MAX); |
| 720 | thought_free(t); |
| 721 | return 0; |
| 722 | } |
| 723 | t->branch_id = sx_strdup(yyjson_get_str(v)); |
| 724 | } |
| 725 | |
| 726 | v = yyjson_obj_get(args, "needsMoreThoughts"); |
| 727 | if (v && !yyjson_is_null(v) && !val_bool(v, &t->needs_more)) { |
| 728 | snprintf(err, errsz, "Invalid needsMoreThoughts: must be a boolean"); |
| 729 | thought_free(t); |
| 730 | return 0; |
| 731 | } |
| 732 | return 1; |
| 733 | } |
| 734 | |
| 735 | /* One line per accepted thought on stderr, upstream's box condensed to a |
| 736 | * single label line (no emoji, no colour codes in a clean-room binary). |
| 737 | * Silenced by DISABLE_THOUGHT_LOGGING=1|true like upstream. */ |
| 738 | static void log_thought_stderr(const thought_t *t) |
| 739 | { |
| 740 | const char *dl = getenv("DISABLE_THOUGHT_LOGGING"); |
| 741 | char low[8]; |
| 742 | size_t i, n; |
| 743 | if (dl && *dl) { |
| 744 | n = strlen(dl); |
| 745 | if (strcmp(dl, "1") == 0) return; |
| 746 | if (n < sizeof low) { |
| 747 | for (i = 0; i < n; i++) low[i] = (char)tolower((unsigned char)dl[i]); |
| 748 | low[n] = '\0'; |
| 749 | if (strcmp(low, "true") == 0) return; |
| 750 | } |
| 751 | } |
| 752 | if (t->is_revision) |
| 753 | fprintf(stderr, "[seqthink] Revision %lld/%lld (revising thought %lld)\n", |
| 754 | t->thought_number, t->total_thoughts, t->revises); |
| 755 | else if (t->branch_from && t->branch_id) |
| 756 | fprintf(stderr, "[seqthink] Branch %lld/%lld (from thought %lld, ID: %s)\n", |
| 757 | t->thought_number, t->total_thoughts, t->branch_from, t->branch_id); |
| 758 | else if (t->branch_from) |
| 759 | fprintf(stderr, "[seqthink] Branch %lld/%lld (from thought %lld)\n", |
| 760 | t->thought_number, t->total_thoughts, t->branch_from); |
| 761 | else |
| 762 | fprintf(stderr, "[seqthink] Thought %lld/%lld\n", |
| 763 | t->thought_number, t->total_thoughts); |
| 764 | fflush(stderr); |
| 765 | } |
| 766 | |
| 767 | /* Append one thought to the persisted chains file. The file is a simple |
| 768 | * {"chains":[{"id":...,"started_at":...,"updated_at":...,"branches":[...], |
| 769 | * "thoughts":[{...}]}]} document, merged by chain id: our chain's |
| 770 | * existing thoughts are kept (bounded), other chains are carried over |
| 771 | * (bounded, oldest-updated first to keep the newest). Every field is |
| 772 | * re-serialised from parsed values, so a hand-corrupted file degrades to |
| 773 | * "unparseable -> start clean" instead of poisoning the output. The bytes go |
| 774 | * to <path>.tmp and only then rename() over the file (crash-safe). |
| 775 | * Returns 1 on success; a persistence failure never fails the tool call. */ |
| 776 | |
| 777 | typedef struct { |
| 778 | char *thought; |
| 779 | long long tn, tt; |
| 780 | int next_needed, is_revision, needs_more; |
| 781 | long long revises, branch_from; |
| 782 | char *branch_id; |
| 783 | long long at; |
| 784 | } pth_t; |
| 785 | |
| 786 | typedef struct { |
| 787 | char *id; |
| 788 | long long started_at, updated_at; |
| 789 | pth_t *th; |
| 790 | size_t n, cap; |
| 791 | } chain_t; |
| 792 | |
| 793 | static void chain_add(chain_t *c, const pth_t *t) |
| 794 | { |
| 795 | if (c->n == c->cap) { |
| 796 | c->cap = c->cap ? c->cap * 2 : 16; |
| 797 | c->th = (pth_t *)realloc(c->th, c->cap * sizeof *c->th); |
| 798 | if (!c->th) { fputs("out of memory\n", stderr); exit(1); } |
| 799 | } |
| 800 | c->th[c->n++] = *t; |
| 801 | } |
| 802 | |
| 803 | static void chain_free(chain_t *c) |
| 804 | { |
| 805 | size_t i; |
| 806 | for (i = 0; i < c->n; i++) { free(c->th[i].thought); free(c->th[i].branch_id); } |
| 807 | free(c->th); |
| 808 | free(c->id); |
| 809 | memset(c, 0, sizeof *c); |
| 810 | } |
| 811 | |
| 812 | static char *dup_str_or_null(yyjson_val *v) |
| 813 | { |
| 814 | if (yyjson_is_str(v) && yyjson_get_str(v)) return sx_strdup(yyjson_get_str(v)); |
| 815 | return NULL; |
| 816 | } |
| 817 | |
| 818 | static int load_chains_model(char *txt, size_t len, chain_t **out, size_t *outn) |
| 819 | { |
| 820 | yyjson_doc *doc; |
| 821 | yyjson_val *root, *chains; |
| 822 | chain_t *cs = NULL; |
| 823 | size_t n = 0, i; |
| 824 | |
| 825 | *out = NULL; *outn = 0; |
| 826 | if (!txt) return 1; |
| 827 | doc = yyjson_read(txt, len, 0); |
| 828 | free(txt); |
| 829 | if (!doc) return 0; /* unparseable */ |
| 830 | root = yyjson_doc_get_root(doc); |
| 831 | if (!yyjson_is_obj(root)) { yyjson_doc_free(doc); return 0; } |
| 832 | chains = yyjson_obj_get(root, "chains"); |
| 833 | if (!yyjson_is_arr(chains)) { yyjson_doc_free(doc); return 1; } |
| 834 | n = yyjson_arr_size(chains); |
| 835 | if (n) { |
| 836 | cs = (chain_t *)sx_malloc(n * sizeof *cs); |
| 837 | memset(cs, 0, n * sizeof *cs); |
| 838 | } |
| 839 | for (i = 0; i < n; i++) { |
| 840 | yyjson_val *c = yyjson_arr_get(chains, i); |
| 841 | yyjson_val *v; |
| 842 | if (!yyjson_is_obj(c)) continue; |
| 843 | v = yyjson_obj_get(c, "id"); |
| 844 | if (!yyjson_is_str(v) || !yyjson_get_str(v) || !*yyjson_get_str(v)) continue; |
| 845 | cs[i].id = sx_strdup(yyjson_get_str(v)); |
| 846 | v = yyjson_obj_get(c, "started_at"); |
| 847 | cs[i].started_at = yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0; |
| 848 | v = yyjson_obj_get(c, "updated_at"); |
| 849 | cs[i].updated_at = yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0; |
| 850 | v = yyjson_obj_get(c, "thoughts"); |
| 851 | if (yyjson_is_arr(v)) { |
| 852 | size_t j, tn = yyjson_arr_size(v); |
| 853 | for (j = 0; j < tn; j++) { |
| 854 | yyjson_val *tv = yyjson_arr_get(v, j); |
| 855 | pth_t t; |
| 856 | yyjson_val *x; |
| 857 | if (!yyjson_is_obj(tv)) continue; |
| 858 | memset(&t, 0, sizeof t); |
| 859 | x = yyjson_obj_get(tv, "thought"); |
| 860 | if (!yyjson_is_str(x) || !yyjson_get_str(x)) continue; |
| 861 | t.thought = sx_strdup(yyjson_get_str(x)); |
| 862 | x = yyjson_obj_get(tv, "thought_number"); |
| 863 | t.tn = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; |
| 864 | x = yyjson_obj_get(tv, "total_thoughts"); |
| 865 | t.tt = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; |
| 866 | t.next_needed = yyjson_is_true(yyjson_obj_get(tv, "next_needed")); |
| 867 | t.is_revision = yyjson_is_true(yyjson_obj_get(tv, "is_revision")); |
| 868 | t.needs_more = yyjson_is_true(yyjson_obj_get(tv, "needs_more")); |
| 869 | x = yyjson_obj_get(tv, "revises"); |
| 870 | t.revises = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; |
| 871 | x = yyjson_obj_get(tv, "branch_from"); |
| 872 | t.branch_from = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; |
| 873 | t.branch_id = dup_str_or_null(yyjson_obj_get(tv, "branch_id")); |
| 874 | x = yyjson_obj_get(tv, "at"); |
| 875 | t.at = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; |
| 876 | chain_add(&cs[i], &t); |
| 877 | } |
| 878 | } |
| 879 | } |
| 880 | yyjson_doc_free(doc); |
| 881 | *out = cs; *outn = n; |
| 882 | return 1; |
| 883 | } |
| 884 | |
| 885 | static void free_model(chain_t *cs, size_t n) |
| 886 | { |
| 887 | size_t i; |
| 888 | if (!cs) return; |
| 889 | for (i = 0; i < n; i++) chain_free(&cs[i]); |
| 890 | free(cs); |
| 891 | } |
| 892 | |
| 893 | static void emit_thought(buf_t *b, const pth_t *t) |
| 894 | { |
| 895 | buf_str(b, "{\"thought\":"); |
| 896 | json_escape_buf(b, t->thought); |
| 897 | buf_addf(b, ",\"thought_number\":%lld,\"total_thoughts\":%lld", t->tn, t->tt); |
| 898 | buf_addf(b, ",\"next_needed\":%s", t->next_needed ? "true" : "false"); |
| 899 | if (t->is_revision) buf_str(b, ",\"is_revision\":true"); |
| 900 | if (t->revises) buf_addf(b, ",\"revises\":%lld", t->revises); |
| 901 | if (t->branch_from) buf_addf(b, ",\"branch_from\":%lld", t->branch_from); |
| 902 | if (t->branch_id) { |
| 903 | buf_str(b, ",\"branch_id\":"); |
| 904 | json_escape_buf(b, t->branch_id); |
| 905 | } |
| 906 | if (t->needs_more) buf_str(b, ",\"needs_more\":true"); |
| 907 | buf_addf(b, ",\"at\":%lld}", t->at); |
| 908 | } |
| 909 | |
| 910 | static int persist_thought(const char *chain_id, const thought_t *t) |
| 911 | { |
| 912 | char dir[1000], path[1200]; |
| 913 | char *txt = NULL; |
| 914 | size_t len = 0, i, n = 0; |
| 915 | chain_t *cs = NULL; |
| 916 | chain_t *mine = NULL; |
| 917 | pth_t nt; |
| 918 | buf_t out; |
| 919 | int mine_idx = -1; |
| 920 | |
| 921 | state_dir(dir, sizeof dir); |
| 922 | if (!mkdirs(dir)) return 0; |
| 923 | chains_path(path, sizeof path); |
| 924 | |
| 925 | txt = read_file(path, &len); |
| 926 | if (!load_chains_model(txt, len, &cs, &n)) { /* frees txt, strays to clean */ |
| 927 | cs = NULL; n = 0; |
| 928 | } |
| 929 | |
| 930 | for (i = 0; i < n; i++) |
| 931 | if (cs[i].id && strcmp(cs[i].id, chain_id) == 0) { mine_idx = (int)i; break; } |
| 932 | mine = mine_idx >= 0 ? &cs[mine_idx] : NULL; |
| 933 | |
| 934 | memset(&nt, 0, sizeof nt); |
| 935 | nt.thought = sx_strdup(t->thought); /* owned by the chain model */ |
| 936 | nt.tn = t->thought_number; |
| 937 | nt.tt = t->total_thoughts; |
| 938 | nt.next_needed = t->next_needed; |
| 939 | nt.is_revision = t->is_revision; |
| 940 | nt.needs_more = t->needs_more; |
| 941 | nt.revises = t->revises; |
| 942 | nt.branch_from = t->branch_from; |
| 943 | nt.branch_id = t->branch_id ? sx_strdup(t->branch_id) : NULL; |
| 944 | nt.at = (long long)time(NULL); |
| 945 | |
| 946 | if (!mine) { |
| 947 | cs = (chain_t *)realloc(cs, (n + 1) * sizeof *cs); |
| 948 | if (!cs) { fputs("out of memory\n", stderr); exit(1); } |
| 949 | memset(&cs[n], 0, sizeof cs[n]); |
| 950 | mine = &cs[n]; |
| 951 | mine->id = sx_strdup(chain_id); |
| 952 | mine->started_at = nt.at; |
| 953 | n++; |
| 954 | } |
| 955 | chain_add(mine, &nt); |
| 956 | mine->updated_at = nt.at; |
| 957 | /* Bound this chain: keep the newest MAX_THOUGHTS_EACH thoughts. */ |
| 958 | if (mine->n > MAX_THOUGHTS_EACH) { |
| 959 | size_t drop = mine->n - MAX_THOUGHTS_EACH, j; |
| 960 | for (j = 0; j < drop; j++) { |
| 961 | free(mine->th[j].thought); |
| 962 | free(mine->th[j].branch_id); |
| 963 | } |
| 964 | memmove(&mine->th[0], &mine->th[drop], (mine->n - drop) * sizeof *mine->th); |
| 965 | mine->n -= drop; |
| 966 | } |
| 967 | |
| 968 | /* Bound the file: keep our chain + the newest (MAX_CHAINS - 1) others. |
| 969 | * mine_idx is the ORIGINAL index of our chain (mine may dangle after a |
| 970 | * growth realloc, so identity is tracked by index). */ |
| 971 | if (n > MAX_CHAINS) { |
| 972 | char *keep = (char *)sx_malloc(n); |
| 973 | size_t w = 0, k; |
| 974 | memset(keep, 1, n); |
| 975 | if (mine_idx >= 0) keep[mine_idx] = 2; /* ours: never dropped */ |
| 976 | while (1) { |
| 977 | long long oldest = LLONG_MAX; |
| 978 | int oi = -1; |
| 979 | size_t kept = 0; |
| 980 | for (k = 0; k < n; k++) if (keep[k]) kept++; |
| 981 | if (kept <= (size_t)MAX_CHAINS) break; |
| 982 | for (k = 0; k < n; k++) { |
| 983 | if (keep[k] != 1) continue; |
| 984 | if (cs[k].updated_at < oldest) { oldest = cs[k].updated_at; oi = (int)k; } |
| 985 | } |
| 986 | if (oi < 0) { /* tie fallback */ |
| 987 | for (k = 0; k < n; k++) if (keep[k] == 1) { oi = (int)k; break; } |
| 988 | } |
| 989 | if (oi < 0) break; |
| 990 | keep[oi] = 0; |
| 991 | } |
| 992 | for (k = 0; k < n; k++) { |
| 993 | if (!keep[k]) { chain_free(&cs[k]); continue; } |
| 994 | if (w != k) cs[w] = cs[k]; |
| 995 | w++; |
| 996 | } |
| 997 | n = w; |
| 998 | free(keep); |
| 999 | } |
| 1000 | |
| 1001 | buf_init(&out); |
| 1002 | buf_str(&out, "{\"chains\":["); |
| 1003 | for (i = 0; i < n; i++) { |
| 1004 | if (i) buf_str(&out, ","); |
| 1005 | buf_str(&out, "{\"id\":"); |
| 1006 | json_escape_buf(&out, cs[i].id); |
| 1007 | buf_addf(&out, ",\"started_at\":%lld,\"updated_at\":%lld,\"thoughts\":[", |
| 1008 | cs[i].started_at, cs[i].updated_at); |
| 1009 | { |
| 1010 | size_t j; |
| 1011 | for (j = 0; j < cs[i].n; j++) { |
| 1012 | if (j) buf_str(&out, ","); |
| 1013 | emit_thought(&out, &cs[i].th[j]); |
| 1014 | } |
| 1015 | } |
| 1016 | buf_str(&out, "],\"count\":"); |
| 1017 | buf_addf(&out, "%zu", cs[i].n); |
| 1018 | buf_str(&out, ",\"branches\":["); |
| 1019 | { /* distinct branch ids in first-seen order */ |
| 1020 | size_t j, k; |
| 1021 | int first = 1; |
| 1022 | for (j = 0; j < cs[i].n; j++) { |
| 1023 | int seen = 0; |
| 1024 | if (!cs[i].th[j].branch_id || !cs[i].th[j].branch_from) continue; |
| 1025 | for (k = 0; k < j; k++) |
| 1026 | if (cs[i].th[k].branch_id && cs[i].th[j].branch_id && |
| 1027 | strcmp(cs[i].th[k].branch_id, cs[i].th[j].branch_id) == 0) |
| 1028 | { seen = 1; break; } |
| 1029 | if (seen) continue; |
| 1030 | if (!first) buf_str(&out, ","); |
| 1031 | first = 0; |
| 1032 | json_escape_buf(&out, cs[i].th[j].branch_id); |
| 1033 | } |
| 1034 | } |
| 1035 | buf_str(&out, "]}"); |
| 1036 | } |
| 1037 | buf_str(&out, "]}"); |
| 1038 | |
| 1039 | if (!out.p) { free_model(cs, n); return 0; } |
| 1040 | { |
| 1041 | int ok = write_file_atomic(path, out.p, out.n); |
| 1042 | buf_free(&out); |
| 1043 | free_model(cs, n); |
| 1044 | return ok; |
| 1045 | } |
| 1046 | } |
| 1047 | |
| 1048 | /* ------------------------------------------------------------------ */ |
| 1049 | /* Session (one --mcp process == one chain) */ |
| 1050 | /* ------------------------------------------------------------------ */ |
| 1051 | |
| 1052 | typedef struct { |
| 1053 | tvec_t history; |
| 1054 | bvec_t branches; |
| 1055 | long long max_hist; |
| 1056 | char chain_id[64]; |
| 1057 | int persist; |
| 1058 | } session_t; |
| 1059 | |
| 1060 | static void session_init(session_t *s) |
| 1061 | { |
| 1062 | const char *dl = getenv("DISABLE_THOUGHT_LOGGING"); |
| 1063 | memset(s, 0, sizeof *s); |
| 1064 | s->max_hist = read_max_history(); |
| 1065 | snprintf(s->chain_id, sizeof s->chain_id, "th-%llx-%lx", |
| 1066 | (unsigned long long)time(NULL), (unsigned long) |
| 1067 | #if defined(_WIN32) |
| 1068 | GetCurrentProcessId() |
| 1069 | #else |
| 1070 | (unsigned long)getpid() |
| 1071 | #endif |
| 1072 | ); |
| 1073 | s->persist = 1; |
| 1074 | if (dl && *dl) { |
| 1075 | const char *p = dl; |
| 1076 | int all_digits = 1; |
| 1077 | for (; *p; p++) if (!isdigit((unsigned char)*p)) { all_digits = 0; break; } |
| 1078 | if (strcmp(dl, "1") == 0 || strcmp(dl, "true") == 0 || |
| 1079 | strcmp(dl, "TRUE") == 0 || strcmp(dl, "True") == 0) |
| 1080 | s->persist = 0; |
| 1081 | (void)all_digits; |
| 1082 | } |
| 1083 | } |
| 1084 | |
| 1085 | static void session_free(session_t *s) |
| 1086 | { |
| 1087 | size_t i; |
| 1088 | for (i = 0; i < s->history.n; i++) thought_free(&s->history.v[i]); |
| 1089 | free(s->history.v); |
| 1090 | for (i = 0; i < s->branches.n; i++) free(s->branches.v[i].key); |
| 1091 | free(s->branches.v); |
| 1092 | memset(s, 0, sizeof *s); |
| 1093 | } |
| 1094 | |
| 1095 | /* The tool itself. Returns the result text (heap; caller frees) and sets |
| 1096 | * *is_error like upstream's {content,isError}. */ |
| 1097 | static char *process_thought(session_t *s, yyjson_val *args, int *is_error) |
| 1098 | { |
| 1099 | thought_t t; |
| 1100 | char err[256]; |
| 1101 | buf_t b; |
| 1102 | |
| 1103 | *is_error = 0; |
| 1104 | if (!args || !yyjson_is_obj(args)) { |
| 1105 | return sx_strdup("{\"error\":\"Invalid thought: must be a string\"," |
| 1106 | "\"status\":\"failed\"}"); |
| 1107 | } |
| 1108 | if (!validate_thought(args, &t, err, sizeof err)) { |
| 1109 | buf_init(&b); |
| 1110 | buf_str(&b, "{\"error\":"); |
| 1111 | json_escape_buf(&b, err); |
| 1112 | buf_str(&b, ",\"status\":\"failed\"}"); |
| 1113 | *is_error = 1; |
| 1114 | return b.p ? b.p : sx_strdup("{\"error\":\"invalid input\",\"status\":\"failed\"}"); |
| 1115 | } |
| 1116 | |
| 1117 | /* Upstream rule: thoughtNumber past totalThoughts raises the estimate. */ |
| 1118 | if (t.thought_number > t.total_thoughts) t.total_thoughts = t.thought_number; |
| 1119 | |
| 1120 | /* Upstream logs before touching any state. */ |
| 1121 | log_thought_stderr(&t); |
| 1122 | |
| 1123 | tvec_push(&s->history, &t); |
| 1124 | if (t.branch_from && t.branch_id) bvec_record(&s->branches, t.branch_id); |
| 1125 | |
| 1126 | if ((long long)s->history.n > s->max_hist) { |
| 1127 | thought_t *oldest = &s->history.v[0]; |
| 1128 | if (oldest->branch_from && oldest->branch_id) |
| 1129 | bvec_evict(&s->branches, oldest->branch_id); |
| 1130 | thought_free(oldest); |
| 1131 | memmove(&s->history.v[0], &s->history.v[1], |
| 1132 | (s->history.n - 1) * sizeof *s->history.v); |
| 1133 | s->history.n--; |
| 1134 | } |
| 1135 | |
| 1136 | if (s->persist) persist_thought(s->chain_id, &t); |
| 1137 | |
| 1138 | /* Upstream response: exactly these five fields. One buffer, compact |
| 1139 | * single-line JSON (valid inside structuredContent); the content text is |
| 1140 | * the same object, so tests and clients can parse either. */ |
| 1141 | { |
| 1142 | size_t i; |
| 1143 | buf_init(&b); |
| 1144 | buf_addf(&b, "{\"thoughtNumber\":%lld,\"totalThoughts\":%lld," |
| 1145 | "\"nextThoughtNeeded\":%s,\"branches\":[", |
| 1146 | t.thought_number, t.total_thoughts, |
| 1147 | t.next_needed ? "true" : "false"); |
| 1148 | for (i = 0; i < s->branches.n; i++) { |
| 1149 | if (i) buf_str(&b, ","); |
| 1150 | json_escape_buf(&b, s->branches.v[i].key); |
| 1151 | } |
| 1152 | buf_addf(&b, "],\"thoughtHistoryLength\":%zu}", s->history.n); |
| 1153 | } |
| 1154 | /* The snapshot was already taken before we hand back; free this |
| 1155 | * thought's copy only after persistence used it. */ |
| 1156 | return b.p ? b.p : sx_strdup("{}"); |
| 1157 | } |
| 1158 | |
| 1159 | /* ------------------------------------------------------------------ */ |
| 1160 | /* --mcp mode: MCP JSON-RPC 2.0 over stdio */ |
| 1161 | /* ------------------------------------------------------------------ */ |
| 1162 | |
| 1163 | static const char SEQTHINK_TOOL_SCHEMA[] = |
| 1164 | "{\"type\":\"object\",\"properties\":{" |
| 1165 | "\"thought\":{\"type\":\"string\",\"description\":\"Your current thinking step\"}," |
| 1166 | "\"nextThoughtNeeded\":{\"type\":\"boolean\",\"description\":\"Whether another thought step is needed\"}," |
| 1167 | "\"thoughtNumber\":{\"type\":\"integer\",\"description\":\"Current thought number (numeric value, e.g., 1, 2, 3)\",\"minimum\":1}," |
| 1168 | "\"totalThoughts\":{\"type\":\"integer\",\"description\":\"Estimated total thoughts needed (numeric value, e.g., 5, 10)\",\"minimum\":1}," |
| 1169 | "\"isRevision\":{\"type\":\"boolean\",\"description\":\"Whether this revises previous thinking\"}," |
| 1170 | "\"revisesThought\":{\"type\":\"integer\",\"description\":\"Which thought is being reconsidered\",\"minimum\":1}," |
| 1171 | "\"branchFromThought\":{\"type\":\"integer\",\"description\":\"Branching point thought number\",\"minimum\":1}," |
| 1172 | "\"branchId\":{\"type\":\"string\",\"description\":\"Branch identifier\"}," |
| 1173 | "\"needsMoreThoughts\":{\"type\":\"boolean\",\"description\":\"If more thoughts are needed\"}" |
| 1174 | "},\"required\":[\"thought\",\"nextThoughtNeeded\",\"thoughtNumber\",\"totalThoughts\"]}"; |
| 1175 | |
| 1176 | static const char SEQTHINK_TOOL_OUTPUT[] = |
| 1177 | "{\"type\":\"object\",\"properties\":{" |
| 1178 | "\"thoughtNumber\":{\"type\":\"number\"}," |
| 1179 | "\"totalThoughts\":{\"type\":\"number\"}," |
| 1180 | "\"nextThoughtNeeded\":{\"type\":\"boolean\"}," |
| 1181 | "\"branches\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}," |
| 1182 | "\"thoughtHistoryLength\":{\"type\":\"number\"}}}"; |
| 1183 | |
| 1184 | static const char SEQTHINK_TOOL_DESC[] = |
| 1185 | "A detailed tool for dynamic and reflective problem-solving through thoughts.\n" |
| 1186 | "Each thought can build on, question, or revise previous insights as understanding deepens.\n\n" |
| 1187 | "When to use this tool:\n" |
| 1188 | "- Breaking down complex problems into steps\n" |
| 1189 | "- Planning and design with room for revision\n" |
| 1190 | "- Analysis that might need course correction\n" |
| 1191 | "- Problems where the full scope might not be clear initially\n" |
| 1192 | "- Tasks that need to maintain context over multiple steps\n" |
| 1193 | "- Situations where irrelevant information needs to be filtered out\n\n" |
| 1194 | "You should:\n" |
| 1195 | "1. Estimate totalThoughts up front and adjust it up or down as you go;" |
| 1196 | " thoughtNumber may exceed it\n" |
| 1197 | "2. Question or revise earlier thoughts (isRevision with revisesThought)," |
| 1198 | " or branch (branchFromThought with branchId)\n" |
| 1199 | "3. Express uncertainty, and ignore information irrelevant to the current step\n" |
| 1200 | "4. Generate a solution hypothesis, verify it against the earlier steps," |
| 1201 | " and repeat until satisfied\n" |
| 1202 | "5. Set nextThoughtNeeded to false only when truly done and a satisfactory" |
| 1203 | " answer is reached"; |
| 1204 | |
| 1205 | /* Emit the tools/list result. */ |
| 1206 | static void mcp_tools_list(FILE *out, const char *id_raw) |
| 1207 | { |
| 1208 | fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"tools\":[{", id_raw); |
| 1209 | fputs("\"name\":\"sequentialthinking\",\"title\":\"Sequential Thinking\"," |
| 1210 | "\"description\":", out); |
| 1211 | json_escape(out, SEQTHINK_TOOL_DESC); |
| 1212 | fputs(",\"inputSchema\":", out); |
| 1213 | fputs(SEQTHINK_TOOL_SCHEMA, out); |
| 1214 | fputs(",\"outputSchema\":", out); |
| 1215 | fputs(SEQTHINK_TOOL_OUTPUT, out); |
| 1216 | fputs(",\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":false," |
| 1217 | "\"idempotentHint\":false,\"openWorldHint\":false}}]}}\n", out); |
| 1218 | fflush(out); |
| 1219 | } |
| 1220 | |
| 1221 | static void mcp_server_info(FILE *out, const char *id_raw) |
| 1222 | { |
| 1223 | fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{" |
| 1224 | "\"protocolVersion\":\"2024-11-05\",\"capabilities\":{\"tools\":{}}," |
| 1225 | "\"serverInfo\":{\"name\":\"%s\",\"version\":\"%s\"}}}\n", |
| 1226 | id_raw, PLUGIN_SLUG, PLUGIN_VER); |
| 1227 | fflush(out); |
| 1228 | } |
| 1229 | |
| 1230 | /* Copy the raw JSON-RPC id token (number or string) so the reply echoes the |
| 1231 | * same type. */ |
| 1232 | static int json_id_raw(const char *line, char *out, size_t outsz) |
| 1233 | { |
| 1234 | const char *p = strstr(line, "\"id\""); |
| 1235 | size_t i = 0; |
| 1236 | if (!p) return 0; |
| 1237 | p += 4; |
| 1238 | while (*p && (unsigned char)*p <= ' ') p++; |
| 1239 | if (*p != ':') return 0; |
| 1240 | p++; |
| 1241 | while (*p && (unsigned char)*p <= ' ') p++; |
| 1242 | if (*p == '"') { |
| 1243 | out[i++] = *p++; |
| 1244 | while (*p && i + 2 < outsz) { |
| 1245 | out[i++] = *p; |
| 1246 | if (*p == '\\' && p[1]) { p++; out[i++] = *p++; } |
| 1247 | else if (*p == '"') { p++; out[i++] = '"'; break; } |
| 1248 | else p++; |
| 1249 | } |
| 1250 | out[i] = '\0'; |
| 1251 | return i > 1; |
| 1252 | } |
| 1253 | while (*p && (isdigit((unsigned char)*p) || *p == '-' || *p == '+') && |
| 1254 | i + 1 < outsz) |
| 1255 | out[i++] = *p++; |
| 1256 | out[i] = '\0'; |
| 1257 | return i > 0; |
| 1258 | } |
| 1259 | |
| 1260 | static void mcp_tool_call(FILE *out, const char *id_raw, yyjson_val *params, |
| 1261 | session_t *sess) |
| 1262 | { |
| 1263 | yyjson_val *name = NULL, *args = NULL, *v; |
| 1264 | char *text; |
| 1265 | int is_err = 0; |
| 1266 | |
| 1267 | if (params && yyjson_is_obj(params)) { |
| 1268 | name = yyjson_obj_get(params, "name"); |
| 1269 | args = yyjson_obj_get(params, "arguments"); |
| 1270 | } |
| 1271 | if (!name || !yyjson_is_str(name) || !yyjson_get_str(name) || |
| 1272 | strcmp(yyjson_get_str(name), "sequentialthinking") != 0) { |
| 1273 | fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32602," |
| 1274 | "\"message\":\"unknown tool\"}}\n", id_raw); |
| 1275 | fflush(out); |
| 1276 | return; |
| 1277 | } |
| 1278 | (void)v; |
| 1279 | text = process_thought(sess, args, &is_err); |
| 1280 | |
| 1281 | fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"content\":" |
| 1282 | "[{\"type\":\"text\",\"text\":", id_raw); |
| 1283 | json_escape(out, text); |
| 1284 | fputs("}],\"structuredContent\":", out); |
| 1285 | if (!is_err) { |
| 1286 | fputs(text, out); /* the five-field object, verbatim */ |
| 1287 | fputs(",\"isError\":false}}\n", out); |
| 1288 | } else { |
| 1289 | fputs(text, out); /* the {error,status} object */ |
| 1290 | fputs(",\"isError\":true}}\n", out); |
| 1291 | } |
| 1292 | fflush(out); |
| 1293 | free(text); |
| 1294 | } |
| 1295 | |
| 1296 | int run_mcp(void) |
| 1297 | { |
| 1298 | char *line = NULL; |
| 1299 | size_t cap = 0; |
| 1300 | ssize_t len; |
| 1301 | session_t sess; |
| 1302 | |
| 1303 | session_init(&sess); |
| 1304 | setvbuf(stdout, NULL, _IOLBF, 0); |
| 1305 | while ((len = getline(&line, &cap, stdin)) != -1) { |
| 1306 | yyjson_doc *doc; |
| 1307 | yyjson_val *root, *m, *params; |
| 1308 | const char *method; |
| 1309 | char id_raw[128] = ""; |
| 1310 | |
| 1311 | if (len == 0 || !memchr(line, '{', (size_t)len)) continue; |
| 1312 | doc = yyjson_read(line, strlen(line), 0); |
| 1313 | if (!doc) continue; |
| 1314 | root = yyjson_doc_get_root(doc); |
| 1315 | m = yyjson_obj_get(root, "method"); |
| 1316 | method = yyjson_is_str(m) ? yyjson_get_str(m) : NULL; |
| 1317 | params = yyjson_obj_get(root, "params"); |
| 1318 | if (!method) { yyjson_doc_free(doc); continue; } |
| 1319 | if (strncmp(method, "notifications/", 14) == 0) { |
| 1320 | yyjson_doc_free(doc); |
| 1321 | continue; |
| 1322 | } |
| 1323 | if (!json_id_raw(line, id_raw, sizeof id_raw) || !id_raw[0]) { |
| 1324 | yyjson_doc_free(doc); |
| 1325 | continue; |
| 1326 | } |
| 1327 | |
| 1328 | if (strcmp(method, "initialize") == 0) { |
| 1329 | mcp_server_info(stdout, id_raw); |
| 1330 | } else if (strcmp(method, "tools/list") == 0) { |
| 1331 | mcp_tools_list(stdout, id_raw); |
| 1332 | } else if (strcmp(method, "tools/call") == 0) { |
| 1333 | mcp_tool_call(stdout, id_raw, params, &sess); |
| 1334 | } else if (strcmp(method, "ping") == 0) { |
| 1335 | fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{}}\n", id_raw); |
| 1336 | fflush(stdout); |
| 1337 | } else { |
| 1338 | fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32601," |
| 1339 | "\"message\":\"method not found\"}}\n", id_raw); |
| 1340 | fflush(stdout); |
| 1341 | } |
| 1342 | yyjson_doc_free(doc); |
| 1343 | } |
| 1344 | free(line); |
| 1345 | session_free(&sess); |
| 1346 | return 0; |
| 1347 | } |
| 1348 | |
| 1349 | /* ------------------------------------------------------------------ */ |
| 1350 | /* Discovery metadata */ |
| 1351 | /* ------------------------------------------------------------------ */ |
| 1352 | |
| 1353 | static int run_meta(void) |
| 1354 | { |
| 1355 | puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"," |
| 1356 | "\"kind\":\"mcp\",\"mcp\":true,\"daemon\":false,\"menus\":false," |
| 1357 | "\"verified\":\"live\"}"); |
| 1358 | fflush(stdout); |
| 1359 | return 0; |
| 1360 | } |
| 1361 | |
| 1362 | /* ------------------------------------------------------------------ */ |
| 1363 | /* JSON node API */ |
| 1364 | /* ------------------------------------------------------------------ */ |
| 1365 | |
| 1366 | static void json_headers(void) |
| 1367 | { |
| 1368 | fputs("Content-Type: application/json; charset=utf-8\r\n" |
| 1369 | "Cache-Control: no-store\r\n" |
| 1370 | "X-Content-Type-Options: nosniff\r\n\r\n", stdout); |
| 1371 | } |
| 1372 | |
| 1373 | static char *read_body(void) |
| 1374 | { |
| 1375 | const char *cl = getenv("CONTENT_LENGTH"); |
| 1376 | long n; |
| 1377 | char *buf; |
| 1378 | size_t got = 0; |
| 1379 | if (!cl || !*cl) return NULL; |
| 1380 | n = atol(cl); |
| 1381 | if (n <= 0 || (unsigned long)n > REQ_MAX) return NULL; |
| 1382 | buf = (char *)sx_malloc((size_t)n + 1); |
| 1383 | while (got < (size_t)n) { |
| 1384 | size_t r = fread(buf + got, 1, (size_t)n - got, stdin); |
| 1385 | if (r == 0) break; |
| 1386 | got += r; |
| 1387 | } |
| 1388 | buf[got] = '\0'; |
| 1389 | return buf; |
| 1390 | } |
| 1391 | |
| 1392 | /* Read one field from a JSON body as a string (string/int/bool coerced). */ |
| 1393 | static int json_str_field(const char *json, const char *key, char *out, size_t outsz) |
| 1394 | { |
| 1395 | yyjson_doc *doc; |
| 1396 | yyjson_val *v; |
| 1397 | int found = 0; |
| 1398 | if (!json) return 0; |
| 1399 | doc = yyjson_read(json, strlen(json), 0); |
| 1400 | if (!doc) return 0; |
| 1401 | v = yyjson_obj_get(yyjson_doc_get_root(doc), key); |
| 1402 | if (yyjson_is_str(v) && yyjson_get_str(v)) { |
| 1403 | snprintf(out, outsz, "%s", yyjson_get_str(v)); |
| 1404 | found = 1; |
| 1405 | } else if (yyjson_is_int(v)) { |
| 1406 | snprintf(out, outsz, "%lld", (long long)yyjson_get_sint(v)); |
| 1407 | found = 1; |
| 1408 | } else if (yyjson_is_bool(v)) { |
| 1409 | snprintf(out, outsz, "%s", yyjson_is_true(v) ? "true" : "false"); |
| 1410 | found = 1; |
| 1411 | } |
| 1412 | yyjson_doc_free(doc); |
| 1413 | return found; |
| 1414 | } |
| 1415 | |
| 1416 | static void api_err(const char *msg) |
| 1417 | { |
| 1418 | json_headers(); |
| 1419 | fputs("{\"ok\":false,\"error\":", stdout); |
| 1420 | json_escape(stdout, msg ? msg : "error"); |
| 1421 | fputs("}\n", stdout); |
| 1422 | } |
| 1423 | |
| 1424 | static void api_info(void) |
| 1425 | { |
| 1426 | char dir[1000]; |
| 1427 | state_dir(dir, sizeof dir); |
| 1428 | json_headers(); |
| 1429 | fputs("{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"slug\":\"" PLUGIN_SLUG |
| 1430 | "\",\"version\":\"" PLUGIN_VER "\",\"kind\":\"mcp\",\"mcp\":true," |
| 1431 | "\"daemon\":false,\"menus\":false,\"verified\":\"live\"," |
| 1432 | "\"tools\":[\"sequentialthinking\"],\"tool_schema\":", stdout); |
| 1433 | fputs(SEQTHINK_TOOL_SCHEMA, stdout); |
| 1434 | fputs(",\"tool_output_schema\":", stdout); |
| 1435 | fputs(SEQTHINK_TOOL_OUTPUT, stdout); |
| 1436 | fputs(",\"state_dir\":", stdout); |
| 1437 | json_escape(stdout, dir); /* json_escape emits its own quotes (bu) */ |
| 1438 | fputs(",\"max_chains\":", stdout); |
| 1439 | fprintf(stdout, "%d,\"max_thoughts_each\":%d," |
| 1440 | "\"max_thought_history\":%lld}\n", |
| 1441 | MAX_CHAINS, MAX_THOUGHTS_EACH, read_max_history()); |
| 1442 | } |
| 1443 | |
| 1444 | /* Load chains.json (or an empty doc). Caller frees doc. */ |
| 1445 | static yyjson_doc *load_chains(void) |
| 1446 | { |
| 1447 | char path[1200]; |
| 1448 | char *txt; |
| 1449 | size_t len = 0; |
| 1450 | yyjson_doc *doc; |
| 1451 | chains_path(path, sizeof path); |
| 1452 | (void)len; |
| 1453 | txt = read_file(path, &len); |
| 1454 | if (txt) { |
| 1455 | doc = yyjson_read(txt, strlen(txt), 0); |
| 1456 | free(txt); |
| 1457 | } else { |
| 1458 | doc = yyjson_read("{\"chains\":[]}", 13, 0); |
| 1459 | } |
| 1460 | return doc; |
| 1461 | } |
| 1462 | |
| 1463 | static void api_chains(void) |
| 1464 | { |
| 1465 | yyjson_doc *doc = load_chains(); |
| 1466 | yyjson_val *root, *chains; |
| 1467 | buf_t b; |
| 1468 | size_t i, n = 0, total = 0; |
| 1469 | |
| 1470 | if (!doc) { api_err("state unreadable"); return; } |
| 1471 | root = yyjson_doc_get_root(doc); |
| 1472 | chains = yyjson_is_obj(root) ? yyjson_obj_get(root, "chains") : NULL; |
| 1473 | if (yyjson_is_arr(chains)) n = yyjson_arr_size(chains); |
| 1474 | |
| 1475 | buf_init(&b); |
| 1476 | buf_addf(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"count\":%zu,", n); |
| 1477 | { |
| 1478 | char nm[128]; |
| 1479 | state_dir_name(nm, sizeof nm); |
| 1480 | buf_str(&b, "\"state_dir_name\":"); |
| 1481 | json_escape_buf(&b, nm); |
| 1482 | } |
| 1483 | buf_str(&b, ",\"chains\":["); |
| 1484 | for (i = 0; i < n; i++) { |
| 1485 | yyjson_val *c = yyjson_arr_get(chains, i); |
| 1486 | yyjson_val *v, *ths; |
| 1487 | size_t cnt = 0; |
| 1488 | const char *last = ""; |
| 1489 | if (!yyjson_is_obj(c)) continue; |
| 1490 | ths = yyjson_obj_get(c, "thoughts"); |
| 1491 | if (yyjson_is_arr(ths)) cnt = yyjson_arr_size(ths); |
| 1492 | total += cnt; |
| 1493 | if (cnt) { |
| 1494 | yyjson_val *lt = yyjson_arr_get_last(ths); |
| 1495 | if (yyjson_is_obj(lt)) { |
| 1496 | v = yyjson_obj_get(lt, "thought"); |
| 1497 | if (yyjson_is_str(v) && yyjson_get_str(v)) last = yyjson_get_str(v); |
| 1498 | } |
| 1499 | } |
| 1500 | if (i) buf_str(&b, ","); |
| 1501 | buf_str(&b, "{\"id\":"); |
| 1502 | v = yyjson_obj_get(c, "id"); |
| 1503 | if (yyjson_is_str(v)) json_escape_buf(&b, yyjson_get_str(v)); |
| 1504 | else buf_str(&b, "\"\""); |
| 1505 | v = yyjson_obj_get(c, "started_at"); |
| 1506 | buf_addf(&b, ",\"started_at\":%lld,", |
| 1507 | yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0LL); |
| 1508 | v = yyjson_obj_get(c, "updated_at"); |
| 1509 | buf_addf(&b, "\"updated_at\":%lld,", |
| 1510 | yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0LL); |
| 1511 | buf_addf(&b, "\"thoughts\":%zu,", cnt); |
| 1512 | buf_str(&b, "\"branches\":["); |
| 1513 | { |
| 1514 | yyjson_val *brs = yyjson_obj_get(c, "branches"); |
| 1515 | if (yyjson_is_arr(brs)) { |
| 1516 | size_t j, bn = yyjson_arr_size(brs); |
| 1517 | for (j = 0; j < bn; j++) { |
| 1518 | yyjson_val *bv = yyjson_arr_get(brs, j); |
| 1519 | if (j) buf_str(&b, ","); |
| 1520 | if (yyjson_is_str(bv)) json_escape_buf(&b, yyjson_get_str(bv)); |
| 1521 | else buf_str(&b, "\"\""); |
| 1522 | } |
| 1523 | } |
| 1524 | } |
| 1525 | buf_str(&b, "],\"last_head\":"); |
| 1526 | { /* first line of the last thought, clamped to 160 bytes */ |
| 1527 | char head[200]; |
| 1528 | size_t k = 0; |
| 1529 | for (; last[k] && k < 160 && last[k] != '\n'; k++) head[k] = last[k]; |
| 1530 | head[k] = '\0'; |
| 1531 | json_escape_buf(&b, head); |
| 1532 | } |
| 1533 | buf_addf(&b, ",\"truncated\":%s}", cnt >= MAX_THOUGHTS_EACH ? "true" : "false"); |
| 1534 | } |
| 1535 | buf_str(&b, "]}"); |
| 1536 | (void)total; |
| 1537 | json_headers(); |
| 1538 | if (b.p) fwrite(b.p, 1, b.n, stdout); |
| 1539 | fputc('\n', stdout); |
| 1540 | buf_free(&b); |
| 1541 | yyjson_doc_free(doc); |
| 1542 | } |
| 1543 | |
| 1544 | static int valid_chain_id(const char *id) |
| 1545 | { |
| 1546 | size_t i; |
| 1547 | if (!id || !*id || strlen(id) > 64) return 0; |
| 1548 | for (i = 0; id[i]; i++) |
| 1549 | if (!(isalnum((unsigned char)id[i]) || id[i] == '-' || id[i] == '_')) |
| 1550 | return 0; |
| 1551 | return 1; |
| 1552 | } |
| 1553 | |
| 1554 | static void api_chain(const char *id) |
| 1555 | { |
| 1556 | yyjson_doc *doc; |
| 1557 | yyjson_val *root, *chains, *c = NULL; |
| 1558 | size_t i, n; |
| 1559 | |
| 1560 | if (!valid_chain_id(id)) { api_err("invalid chain id"); return; } |
| 1561 | doc = load_chains(); |
| 1562 | if (!doc) { api_err("state unreadable"); return; } |
| 1563 | root = yyjson_doc_get_root(doc); |
| 1564 | chains = yyjson_is_obj(root) ? yyjson_obj_get(root, "chains") : NULL; |
| 1565 | if (yyjson_is_arr(chains)) { |
| 1566 | n = yyjson_arr_size(chains); |
| 1567 | for (i = 0; i < n; i++) { |
| 1568 | yyjson_val *cv = yyjson_arr_get(chains, i); |
| 1569 | yyjson_val *v = yyjson_is_obj(cv) ? yyjson_obj_get(cv, "id") : NULL; |
| 1570 | if (yyjson_is_str(v) && yyjson_get_str(v) && |
| 1571 | strcmp(yyjson_get_str(v), id) == 0) { c = cv; break; } |
| 1572 | } |
| 1573 | } |
| 1574 | if (!c) { |
| 1575 | yyjson_doc_free(doc); |
| 1576 | api_err("chain not found"); |
| 1577 | return; |
| 1578 | } |
| 1579 | { |
| 1580 | char *txt = yyjson_val_write(c, 0, NULL); |
| 1581 | json_headers(); |
| 1582 | if (txt) { |
| 1583 | char *obj = txt; |
| 1584 | fputs("{\"ok\":true,", stdout); |
| 1585 | fputs(obj + 1, stdout); /* drop the object's leading { */ |
| 1586 | fputs("\n", stdout); |
| 1587 | free(txt); |
| 1588 | } else { |
| 1589 | fputs("{\"ok\":false,\"error\":\"serialize failed\"}\n", stdout); |
| 1590 | } |
| 1591 | } |
| 1592 | yyjson_doc_free(doc); |
| 1593 | } |
| 1594 | |
| 1595 | static void api_stats(void) |
| 1596 | { |
| 1597 | yyjson_doc *doc = load_chains(); |
| 1598 | yyjson_val *root, *chains; |
| 1599 | size_t i, n = 0, thoughts = 0, branches = 0, revs = 0; |
| 1600 | long long newest = 0; |
| 1601 | |
| 1602 | if (!doc) { api_err("state unreadable"); return; } |
| 1603 | root = yyjson_doc_get_root(doc); |
| 1604 | chains = yyjson_is_obj(root) ? yyjson_obj_get(root, "chains") : NULL; |
| 1605 | if (yyjson_is_arr(chains)) { |
| 1606 | n = yyjson_arr_size(chains); |
| 1607 | for (i = 0; i < n; i++) { |
| 1608 | yyjson_val *c = yyjson_arr_get(chains, i); |
| 1609 | yyjson_val *ths, *brs, *ua; |
| 1610 | size_t j, tn; |
| 1611 | if (!yyjson_is_obj(c)) continue; |
| 1612 | ua = yyjson_obj_get(c, "updated_at"); |
| 1613 | if (yyjson_is_int(ua) && yyjson_get_sint(ua) > newest) |
| 1614 | newest = (long long)yyjson_get_sint(ua); |
| 1615 | brs = yyjson_obj_get(c, "branches"); |
| 1616 | if (yyjson_is_arr(brs)) branches += yyjson_arr_size(brs); |
| 1617 | ths = yyjson_obj_get(c, "thoughts"); |
| 1618 | if (!yyjson_is_arr(ths)) continue; |
| 1619 | tn = yyjson_arr_size(ths); |
| 1620 | thoughts += tn; |
| 1621 | for (j = 0; j < tn; j++) { |
| 1622 | yyjson_val *tv = yyjson_arr_get(ths, j); |
| 1623 | if (yyjson_is_obj(tv) && |
| 1624 | yyjson_is_true(yyjson_obj_get(tv, "is_revision"))) |
| 1625 | revs++; |
| 1626 | } |
| 1627 | } |
| 1628 | } |
| 1629 | json_headers(); |
| 1630 | fprintf(stdout, "{\"ok\":true,\"chains\":%zu,\"thoughts\":%zu," |
| 1631 | "\"branches\":%zu,\"revisions\":%zu," |
| 1632 | "\"last_activity\":%lld,\"max_chains\":%d," |
| 1633 | "\"max_thoughts_each\":%d,\"max_thought_history\":%lld}\n", |
| 1634 | n, thoughts, branches, revs, newest, MAX_CHAINS, MAX_THOUGHTS_EACH, |
| 1635 | read_max_history()); |
| 1636 | yyjson_doc_free(doc); |
| 1637 | } |
| 1638 | |
| 1639 | static void api_clear(void) |
| 1640 | { |
| 1641 | char path[1200]; |
| 1642 | chains_path(path, sizeof path); |
| 1643 | if (remove(path) != 0 && errno != ENOENT) { |
| 1644 | #ifdef _WIN32 |
| 1645 | /* Windows remove() fails on read-only files; try clearing the bit. */ |
| 1646 | { |
| 1647 | DWORD a = GetFileAttributesA(path); |
| 1648 | if (a != INVALID_FILE_ATTRIBUTES) { |
| 1649 | SetFileAttributesA(path, FILE_ATTRIBUTE_NORMAL); |
| 1650 | if (remove(path) != 0) { api_err("remove failed"); return; } |
| 1651 | } else { |
| 1652 | api_err("remove failed"); |
| 1653 | return; |
| 1654 | } |
| 1655 | } |
| 1656 | #else |
| 1657 | api_err("remove failed"); |
| 1658 | return; |
| 1659 | #endif |
| 1660 | } |
| 1661 | json_headers(); |
| 1662 | fputs("{\"ok\":true,\"cleared\":true}\n", stdout); |
| 1663 | } |
| 1664 | |
| 1665 | static int api_dispatch(const char *action, const char *qs, const char *body) |
| 1666 | { |
| 1667 | char id[96] = ""; |
| 1668 | |
| 1669 | if (!action[0] || strcmp(action, "chains") == 0) { |
| 1670 | api_chains(); |
| 1671 | return 0; |
| 1672 | } |
| 1673 | if (strcmp(action, "chain") == 0) { |
| 1674 | if (!(body && json_str_field(body, "id", id, sizeof id)) && |
| 1675 | !(qs && *qs && get_query_val(qs, "id", id, sizeof id))) |
| 1676 | id[0] = '\0'; |
| 1677 | api_chain(id); |
| 1678 | return 0; |
| 1679 | } |
| 1680 | if (strcmp(action, "stats") == 0) { api_stats(); return 0; } |
| 1681 | if (strcmp(action, "info") == 0) { api_info(); return 0; } |
| 1682 | if (strcmp(action, "clear") == 0) { |
| 1683 | char cf[16] = ""; |
| 1684 | if (!(body && json_str_field(body, "confirm", cf, sizeof cf))) |
| 1685 | if (qs && *qs) get_query_val(qs, "confirm", cf, sizeof cf); |
| 1686 | if (strcmp(cf, "1") != 0 && strcmp(cf, "true") != 0) { |
| 1687 | api_err("confirm=1 required"); |
| 1688 | return 0; |
| 1689 | } |
| 1690 | api_clear(); |
| 1691 | return 0; |
| 1692 | } |
| 1693 | api_err("unknown action"); |
| 1694 | return 0; |
| 1695 | } |
| 1696 | |
| 1697 | /* ------------------------------------------------------------------ */ |
| 1698 | /* HTML mode */ |
| 1699 | /* ------------------------------------------------------------------ */ |
| 1700 | |
| 1701 | static void emit_ui(void) |
| 1702 | { |
| 1703 | const char *p = UI_HTML; |
| 1704 | while (*p) { |
| 1705 | if (*p == '\001') { |
| 1706 | fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", |
| 1707 | stdout); |
| 1708 | p++; |
| 1709 | } else if (*p == '\002') { |
| 1710 | fputs(SX_BOT_THEME_HANDOFF, stdout); |
| 1711 | p++; |
| 1712 | } else { |
| 1713 | putchar(*p++); |
| 1714 | } |
| 1715 | } |
| 1716 | } |
| 1717 | |
| 1718 | static void mode_html(void) |
| 1719 | { |
| 1720 | fputs("Content-Type: text/html; charset=utf-8\r\n" |
| 1721 | "Cache-Control: no-store\r\n" |
| 1722 | "X-Content-Type-Options: nosniff\r\n" |
| 1723 | "X-Frame-Options: SAMEORIGIN\r\n" |
| 1724 | "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " |
| 1725 | "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " |
| 1726 | "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); |
| 1727 | emit_ui(); |
| 1728 | } |
| 1729 | |
| 1730 | /* ------------------------------------------------------------------ */ |
| 1731 | /* main */ |
| 1732 | /* ------------------------------------------------------------------ */ |
| 1733 | |
| 1734 | int main(int argc, char **argv) |
| 1735 | { |
| 1736 | const char *qs; |
| 1737 | char action[64] = ""; |
| 1738 | char *body = NULL; |
| 1739 | int have_action = 0; |
| 1740 | const char *rm; |
| 1741 | int is_post; |
| 1742 | |
| 1743 | #if defined(_WIN32) |
| 1744 | { /* MinGW text-mode stdout turns our CRLF into CRCRLF and breaks CGI |
| 1745 | * framing - force binary stdio. */ |
| 1746 | _setmode(_fileno(stdout), _O_BINARY); |
| 1747 | _setmode(_fileno(stdin), _O_BINARY); |
| 1748 | _setmode(_fileno(stderr), _O_BINARY); |
| 1749 | } |
| 1750 | #endif |
| 1751 | |
| 1752 | /* 1. Discovery metadata (unauthenticated so /plugins can probe it) */ |
| 1753 | if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) |
| 1754 | return run_meta(); |
| 1755 | /* 2. MCP stdio server */ |
| 1756 | if (argc > 1 && strcmp(argv[1], "--mcp") == 0) return run_mcp(); |
| 1757 | if (argc > 1 && strcmp(argv[1], "--schema") == 0) { |
| 1758 | puts(SEQTHINK_TOOL_SCHEMA); |
| 1759 | return 0; |
| 1760 | } |
| 1761 | if (argc > 1 && strcmp(argv[1], "--version") == 0) { |
| 1762 | printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); |
| 1763 | return 0; |
| 1764 | } |
| 1765 | |
| 1766 | /* The CGI surface is one private viewer: gate HTML AND the JSON API. |
| 1767 | * Discovery (--meta) and the stdio MCP server (--mcp) returned above, so |
| 1768 | * a node still probes and serves this plugin without a credential, but a |
| 1769 | * bare unauthenticated GET /plugin_seqthink answers 401, exactly like |
| 1770 | * plugin_logs / plugin_notes / plugin_sqlite. */ |
| 1771 | require_node_auth(); |
| 1772 | |
| 1773 | qs = getenv("QUERY_STRING"); |
| 1774 | if (!qs) qs = ""; |
| 1775 | |
| 1776 | have_action = get_query_val(qs, "action", action, sizeof action); |
| 1777 | if (!have_action && strstr(qs, "format=json")) { |
| 1778 | const char *fm = strstr(qs, "format=json"); |
| 1779 | if (fm[11] == '\0' || fm[11] == '&') { |
| 1780 | snprintf(action, sizeof action, "chains"); |
| 1781 | have_action = 1; |
| 1782 | } |
| 1783 | } |
| 1784 | |
| 1785 | rm = getenv("REQUEST_METHOD"); |
| 1786 | is_post = rm && strcmp(rm, "POST") == 0; |
| 1787 | |
| 1788 | if (have_action || is_post) { |
| 1789 | body = read_body(); |
| 1790 | if (body) { |
| 1791 | char jact[64] = ""; |
| 1792 | if (json_str_field(body, "action", jact, sizeof jact) && jact[0]) |
| 1793 | snprintf(action, sizeof action, "%s", jact); |
| 1794 | else if (!action[0]) |
| 1795 | snprintf(action, sizeof action, "chains"); |
| 1796 | } else if (!action[0]) { |
| 1797 | snprintf(action, sizeof action, "chains"); |
| 1798 | } |
| 1799 | { |
| 1800 | int rc = api_dispatch(action, qs, body); |
| 1801 | free(body); |
| 1802 | return rc; |
| 1803 | } |
| 1804 | } |
| 1805 | |
| 1806 | mode_html(); |
| 1807 | return 0; |
| 1808 | } |