/* * plugin_seqthink - SCORPIOX BOT open-source sequential-thinking connector * * One clean-room C99 binary with the four contracts a SCORPIOX BOT connector * plugin implements: * * 1. --meta / SX_PLUGIN_META=1 -> one line of JSON discovery metadata * (unauthenticated, so the node can always discover it) * 2. --mcp -> MCP JSON-RPC 2.0 over stdio: * initialize / notifications/initialized / ping / tools/list / tools/call. * One tool: sequentialthinking {thought, nextThoughtNeeded, thoughtNumber, * totalThoughts, isRevision?, revisesThought?, branchFromThought?, * branchId?, needsMoreThoughts?} * 3. ?action=... (+ POST JSON) -> JSON node API behind require_node_auth(): * chains / chain / stats / info / clear * 4. GET (default) -> responsive dark/light HTML page (behind * require_node_auth(), same as the JSON API): a thought-chain timeline * (revisions, branches, progress) built from the snapshots the --mcp leg * persists. * * The tool is a clean-room C port of the behaviour of modelcontextprotocol * `servers/src/sequentialthinking` (the sequential-thinking MCP server): * identical parameter validation and error strings, the same "raise * totalThoughts when thoughtNumber exceeds it" rule, a per-connection thought * history with a MAX_THOUGHT_HISTORY cap (default 1000, oldest evicted, its * branch shrunk with it, an emptied branch dropped), branch keys created on * the first thought that carries BOTH branchFromThought and branchId, and the * exact five-field result {thoughtNumber,totalThoughts,nextThoughtNeeded, * branches,thoughtHistoryLength} returned as content[0].text AND as * structuredContent. Validation failures come back as * {"error":...,"status":"failed"} with isError:true, exactly as upstream. * * Beyond upstream: every accepted thought also snapshots its chain to * /chains.json (POSIX: /workspace/.scorpiox/connectors/ * plugin_seqthink when /workspace exists, else $HOME/.scorpiox/connectors/ * plugin_seqthink; Windows: %LOCALAPPDATA%\scorpiox\connectors\plugin_seqthink; * SEQTHINK_STATE_DIR overrides for tests) so the HTML UI can inspect recent * reasoning without holding the MCP process open. Writes are read-modify- * merge on chain id and go .tmp -> rename(), so a crash never leaves a * half-written chains.json. The file is bounded (<= 50 chains, each <= 1000 * thoughts). DISABLE_THOUGHT_LOGGING=1|true (upstream parity) silences both * the stderr line and the persistence. * * Zero dependencies beyond the vendored yyjson: no TLS, no sockets, no * popen. The only files it ever touches live under its own state directory. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ /* Must come before every include: MinGW defaults _WIN32_WINNT to 0x502; * Apple needs _DARWIN_C_SOURCE under -std=c99; MinGW needs its printf for %zu. */ #ifndef _WIN32 # ifndef _POSIX_C_SOURCE # define _POSIX_C_SOURCE 200809L # endif # ifndef _DEFAULT_SOURCE # define _DEFAULT_SOURCE 1 # endif #endif #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) # define _DARWIN_C_SOURCE 1 #endif #if defined(__MINGW32__) && !defined(__USE_MINGW_ANSI_STDIO) # define __USE_MINGW_ANSI_STDIO 1 #endif #include #include #include #include #include #include #include #include #if defined(_WIN32) # include # include # include /* _O_BINARY, _setmode, _fileno */ # include # include # ifndef strncasecmp # define strncasecmp _strnicmp # endif # ifndef _SSIZE_T_DEFINED # define _SSIZE_T_DEFINED typedef long long ssize_t; # endif #else # include # include # include # include #endif #include #include #include "yyjson.h" #include "bot_theme_plugin.h" #include "ui_html.h" #define PLUGIN_SLUG "seqthink" #define PLUGIN_ID "plugin_seqthink" #define PLUGIN_VER "1.0.1" #define PLUGIN_NAME "seqthink" #define PLUGIN_DESC "Thought chains" #define MAX_CHAINS 50 /* chains kept in chains.json */ #define MAX_THOUGHTS_EACH 1000 /* thoughts kept per chain in the file */ #define DEFAULT_MAX_HIST 1000 /* upstream DEFAULT_MAX_THOUGHT_HISTORY */ #define THOUGHT_MAX 65536 /* longest accepted thought text */ #define BRANCHID_MAX 128 #define REQ_MAX (2u * 1024u * 1024u) #if defined(_WIN32) # define sx_mkdir(p) _mkdir(p) # define SX_PATHSEP '\\' #else # define sx_mkdir(p) mkdir((p), 0755) # define SX_PATHSEP '/' #endif /* ------------------------------------------------------------------ */ /* Small helpers */ /* ------------------------------------------------------------------ */ static void *sx_malloc(size_t n) { void *p = malloc(n ? n : 1); if (!p) { fputs("out of memory\n", stderr); exit(1); } return p; } static char *sx_strdup(const char *s) { size_t n; char *p; if (!s) s = ""; n = strlen(s) + 1; p = (char *)sx_malloc(n); memcpy(p, s, n); return p; } typedef struct { char *p; size_t n; size_t cap; } buf_t; static void buf_init(buf_t *b) { b->p = NULL; b->n = 0; b->cap = 0; } static void buf_reserve(buf_t *b, size_t extra) { size_t want = b->n + extra + 1; if (want <= b->cap) return; { size_t cap = b->cap ? b->cap : 256; while (cap < want) cap *= 2; b->p = (char *)realloc(b->p, cap); if (!b->p) { fputs("out of memory\n", stderr); exit(1); } b->cap = cap; } } static void buf_add(buf_t *b, const char *s, size_t n) { buf_reserve(b, n); memcpy(b->p + b->n, s, n); b->n += n; b->p[b->n] = '\0'; } /* Append a NUL-terminated literal; the length is computed, never hand-typed. */ static void buf_str(buf_t *b, const char *s) { if (s) buf_add(b, s, strlen(s)); } static void buf_addf(buf_t *b, const char *fmt, ...) { va_list ap; int need; char tmp[512]; va_start(ap, fmt); need = vsnprintf(tmp, sizeof tmp, fmt, ap); va_end(ap); if (need < 0) return; if ((size_t)need < sizeof tmp) { buf_add(b, tmp, (size_t)need); return; } { char *big = (char *)sx_malloc((size_t)need + 1); va_start(ap, fmt); vsnprintf(big, (size_t)need + 1, fmt, ap); va_end(ap); buf_add(b, big, (size_t)need); free(big); } } static void buf_free(buf_t *b) { free(b->p); buf_init(b); } /* getline() is POSIX; MinGW-w64 ships one but msvcrt's varies by release. A * 40-line local version keeps the --mcp loop identical on every target. */ #if defined(_WIN32) static ssize_t sx_getline(char **lineptr, size_t *n, FILE *stream) { size_t len = 0, cap = *n ? *n : 128; char *buf = *lineptr; int c; if (!buf) { buf = (char *)malloc(cap); if (!buf) return -1; *lineptr = buf; *n = cap; } c = fgetc(stream); if (c == EOF) return -1; while (c != EOF) { if (len + 2 > cap) { char *nb; cap *= 2; nb = (char *)realloc(buf, cap); if (!nb) return -1; buf = nb; *lineptr = buf; *n = cap; } buf[len++] = (char)c; if (c == '\n') break; c = fgetc(stream); } buf[len] = '\0'; return (ssize_t)len; } # define getline(a, b, c) sx_getline((a), (b), (c)) #endif /* JSON-escape s into b (with surrounding quotes). */ static void json_escape_buf(buf_t *b, const char *s) { const unsigned char *p = (const unsigned char *)(s ? s : ""); buf_str(b, "\""); for (; *p; p++) { switch (*p) { case '"': buf_str(b, "\\\""); break; case '\\': buf_str(b, "\\\\"); break; case '\n': buf_str(b, "\\n"); break; case '\r': buf_str(b, "\\r"); break; case '\t': buf_str(b, "\\t"); break; default: if (*p < 0x20) buf_addf(b, "\\u%04x", (unsigned)*p); else buf_add(b, (const char *)p, 1); } } buf_str(b, "\""); } static void json_escape(FILE *out, const char *s) { buf_t b; buf_init(&b); json_escape_buf(&b, s); if (b.p) fwrite(b.p, 1, b.n, out); buf_free(&b); } /* Percent-decode in place for query values (the node hands QUERY_STRING raw). */ static int hexval(int c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } static void url_decode(char *s) { char *d = s; while (*s) { if (*s == '%' && hexval((unsigned char)s[1]) >= 0 && hexval((unsigned char)s[2]) >= 0) { *d++ = (char)(hexval((unsigned char)s[1]) * 16 + hexval((unsigned char)s[2])); s += 3; } else if (*s == '+') { *d++ = ' '; s++; } else { *d++ = *s++; } } *d = '\0'; } static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen; const char *p; if (!qs || !key || !out || outsz == 0) return 0; out[0] = '\0'; klen = strlen(key); p = qs; while (p && *p) { if (strncmp(p, key, klen) == 0 && p[klen] == '=') { size_t i = 0; p += klen + 1; while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; out[i] = '\0'; url_decode(out); return 1; } p = strchr(p, '&'); if (p) p++; } return 0; } /* ------------------------------------------------------------------ */ /* Node authentication (X-Bot-Password | Bearer | ?pwd=). --meta and --mcp */ /* never call this; the whole CGI surface (HTML page + every JSON action) does.*/ /* ------------------------------------------------------------------ */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp, *auth; char qpwd[256] = {0}; const char *qs; if (!np || !*np) return; /* open node: no gate */ xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (strncasecmp(auth, "Bearer ", 7) == 0) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } qs = getenv("QUERY_STRING"); if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) return; fputs("Status: 401 Unauthorized\r\n" "Content-Type: application/json; charset=utf-8\r\n\r\n" "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); exit(0); } /* ------------------------------------------------------------------ */ /* State directory + chains.json */ /* ------------------------------------------------------------------ */ static void state_dir(char *out, size_t outsz) { const char *env = getenv("SEQTHINK_STATE_DIR"); #ifndef _WIN32 struct stat st; #endif if (env && *env) { snprintf(out, outsz, "%s", env); return; } #ifndef _WIN32 if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode) && access("/workspace", W_OK) == 0) { snprintf(out, outsz, "/workspace/.scorpiox/connectors/" PLUGIN_ID); return; } #endif #if defined(_WIN32) { const char *la = getenv("LOCALAPPDATA"); if (la && *la) { snprintf(out, outsz, "%s\\scorpiox\\connectors\\" PLUGIN_ID, la); return; } } #endif { const char *home = getenv("HOME"); if (!home || !*home) home = "/root"; snprintf(out, outsz, "%s/.scorpiox/connectors/" PLUGIN_ID, home); } } /* state_dir_name exposes only the leaf directory name for the UI chip (no * absolute path, no home directory name leaks into the browser). */ static void state_dir_name(char *out, size_t outsz) { char dir[1000]; char *slash; size_t i; state_dir(dir, sizeof dir); slash = strrchr(dir, '/'); if (!slash) slash = strrchr(dir, '\\'); { const char *s = slash ? slash + 1 : dir; for (i = 0; s[i] && i + 1 < outsz; i++) out[i] = s[i]; out[i] = '\0'; } } static int mkdirs(const char *path) { char buf[1200]; size_t i, n; struct stat st; snprintf(buf, sizeof buf, "%s", path); n = strlen(buf); for (i = 1; i < n; i++) { if (buf[i] == '/' || buf[i] == '\\') { char save = buf[i]; buf[i] = '\0'; if (i > 2) sx_mkdir(buf); buf[i] = save; } } sx_mkdir(buf); return stat(buf, &st) == 0 && S_ISDIR(st.st_mode); } static void chains_path(char *out, size_t outsz) { char dir[1000]; state_dir(dir, sizeof dir); snprintf(out, outsz, "%s%cchains.json", dir, SX_PATHSEP); } static char *read_file(const char *path, size_t *lenp) { FILE *f; long sz; char *txt; size_t got; f = fopen(path, "rb"); if (!f) return NULL; fseek(f, 0, SEEK_END); sz = ftell(f); fseek(f, 0, SEEK_SET); if (sz < 0 || sz > 8 * 1024 * 1024) { fclose(f); return NULL; } txt = (char *)sx_malloc((size_t)sz + 1); got = fread(txt, 1, (size_t)sz, f); txt[got] = '\0'; fclose(f); if (lenp) *lenp = got; return txt; } static int write_file_atomic(const char *path, const char *data, size_t len) { char tmp[1300]; FILE *f; snprintf(tmp, sizeof tmp, "%s.tmp", path); f = fopen(tmp, "wb"); if (!f) return 0; if (len && fwrite(data, 1, len, f) != len) { fclose(f); remove(tmp); return 0; } if (fflush(f) != 0) { fclose(f); remove(tmp); return 0; } fclose(f); if (rename(tmp, path) != 0) { remove(tmp); return 0; } return 1; } /* ------------------------------------------------------------------ */ /* Tool model */ /* ------------------------------------------------------------------ */ typedef struct { char *thought; /* heap, never NULL after validation */ long long thought_number; long long total_thoughts; long long revises; /* 0 = absent */ long long branch_from; /* 0 = absent */ char *branch_id; /* NULL = absent */ int is_revision; int next_needed; int needs_more; } thought_t; typedef struct { thought_t *v; size_t n, cap; } tvec_t; static void tvec_push(tvec_t *h, const thought_t *t) { if (h->n == h->cap) { h->cap = h->cap ? h->cap * 2 : 16; h->v = (thought_t *)realloc(h->v, h->cap * sizeof *h->v); if (!h->v) { fputs("out of memory\n", stderr); exit(1); } } h->v[h->n++] = *t; } static void thought_free(thought_t *t) { free(t->thought); free(t->branch_id); memset(t, 0, sizeof *t); } /* Branch registry: insertion-ordered keys with per-branch thought counts. */ typedef struct { char *key; size_t count; } branch_t; typedef struct { branch_t *v; size_t n, cap; } bvec_t; static int bvec_find(const bvec_t *b, const char *key) { size_t i; for (i = 0; i < b->n; i++) if (strcmp(b->v[i].key, key) == 0) return (int)i; return -1; } static void bvec_create(bvec_t *b, const char *key) { if (bvec_find(b, key) >= 0) return; if (b->n == b->cap) { b->cap = b->cap ? b->cap * 2 : 8; b->v = (branch_t *)realloc(b->v, b->cap * sizeof *b->v); if (!b->v) { fputs("out of memory\n", stderr); exit(1); } } b->v[b->n].key = sx_strdup(key); b->v[b->n].count = 0; b->n++; } static void bvec_record(bvec_t *b, const char *key) { int i = bvec_find(b, key); if (i < 0) { bvec_create(b, key); i = (int)b->n - 1; } b->v[i].count++; } static void bvec_evict(bvec_t *b, const char *key) { int i = bvec_find(b, key); if (i < 0) return; if (b->v[i].count > 0) b->v[i].count--; if (b->v[i].count == 0) { /* upstream: an emptied branch is dropped */ free(b->v[i].key); memmove(&b->v[i], &b->v[i + 1], (b->n - (size_t)i - 1) * sizeof *b->v); b->n--; } } static long long read_max_history(void) { const char *raw = getenv("MAX_THOUGHT_HISTORY"); const char *p; long long v; if (!raw) return DEFAULT_MAX_HIST; while (*raw == ' ' || *raw == '\t') raw++; if (!*raw) return DEFAULT_MAX_HIST; for (p = raw; *p; p++) if (!isdigit((unsigned char)*p)) break; if (*p != '\0' && !(p == raw + strlen(raw))) { /* trailing junk */ } for (p = raw; *p; p++) { if (!isdigit((unsigned char)*p)) { fprintf(stderr, "MAX_THOUGHT_HISTORY must be a positive integer, " "got \"%s\"; using %d\n", raw, DEFAULT_MAX_HIST); return DEFAULT_MAX_HIST; } } v = strtoll(raw, NULL, 10); if (v < 1) { fprintf(stderr, "MAX_THOUGHT_HISTORY must be a positive integer, " "got \"%s\"; using %d\n", raw, DEFAULT_MAX_HIST); return DEFAULT_MAX_HIST; } return v; } /* Coerce a JSON value to boolean like upstream's coercedBoolean: real bool, * or the strings "true"/"false" (case-insensitive). Returns 1 on success. */ static int val_bool(yyjson_val *v, int *out) { if (yyjson_is_bool(v)) { *out = yyjson_is_true(v) ? 1 : 0; return 1; } if (yyjson_is_str(v)) { const char *s = yyjson_get_str(v); size_t i, n; char low[16]; if (!s) return 0; n = strlen(s); if (n >= sizeof low) return 0; for (i = 0; i < n; i++) low[i] = (char)tolower((unsigned char)s[i]); low[n] = '\0'; if (strcmp(low, "true") == 0) { *out = 1; return 1; } if (strcmp(low, "false") == 0) { *out = 0; return 1; } return 0; } return 0; } /* Coerce to integer like z.coerce.number().int(): JSON number or a numeric * string. Returns 1 on success. */ static int val_int(yyjson_val *v, long long *out) { if (yyjson_is_int(v)) { *out = yyjson_get_sint(v); return 1; } if (yyjson_is_uint(v)) { *out = (long long)yyjson_get_uint(v); return 1; } if (yyjson_is_real(v)) { double d = yyjson_get_real(v); if (d == (double)(long long)d) { *out = (long long)d; return 1; } return 0; } if (yyjson_is_str(v)) { const char *s = yyjson_get_str(v); char *end = NULL; long long ll; if (!s || !*s) return 0; errno = 0; ll = strtoll(s, &end, 10); if (errno != 0 || !end) return 0; while (*end == ' ' || *end == '\t' || *end == '\n' || *end == '\r') end++; if (*end != '\0') return 0; *out = ll; return 1; } return 0; } /* Validate against the upstream schema (errors mirror index.ts/lib.ts). */ static int validate_thought(yyjson_val *args, thought_t *t, char *err, size_t errsz) { yyjson_val *v; memset(t, 0, sizeof *t); v = yyjson_obj_get(args, "thought"); if (!v || !yyjson_is_str(v) || !yyjson_get_str(v) || !yyjson_get_str(v)[0]) { snprintf(err, errsz, "Invalid thought: must be a string"); return 0; } if (strlen(yyjson_get_str(v)) > THOUGHT_MAX) { snprintf(err, errsz, "Invalid thought: too long (max %d bytes)", THOUGHT_MAX); return 0; } t->thought = sx_strdup(yyjson_get_str(v)); v = yyjson_obj_get(args, "nextThoughtNeeded"); if (!val_bool(v, &t->next_needed)) { snprintf(err, errsz, "Invalid nextThoughtNeeded: must be a boolean"); thought_free(t); return 0; } v = yyjson_obj_get(args, "thoughtNumber"); { long long n; if (!val_int(v, &n) || n < 1) { snprintf(err, errsz, "Invalid thoughtNumber: must be a number"); thought_free(t); return 0; } t->thought_number = n; } v = yyjson_obj_get(args, "totalThoughts"); { long long n; if (!val_int(v, &n) || n < 1) { snprintf(err, errsz, "Invalid totalThoughts: must be a number"); thought_free(t); return 0; } t->total_thoughts = n; } v = yyjson_obj_get(args, "isRevision"); if (v && !yyjson_is_null(v) && !val_bool(v, &t->is_revision)) { snprintf(err, errsz, "Invalid isRevision: must be a boolean"); thought_free(t); return 0; } v = yyjson_obj_get(args, "revisesThought"); if (v && !yyjson_is_null(v)) { long long n; if (!val_int(v, &n) || n < 1) { snprintf(err, errsz, "Invalid revisesThought: must be a number"); thought_free(t); return 0; } t->revises = n; } v = yyjson_obj_get(args, "branchFromThought"); if (v && !yyjson_is_null(v)) { long long n; if (!val_int(v, &n) || n < 1) { snprintf(err, errsz, "Invalid branchFromThought: must be a number"); thought_free(t); return 0; } t->branch_from = n; } v = yyjson_obj_get(args, "branchId"); if (v && !yyjson_is_null(v)) { if (!yyjson_is_str(v) || !yyjson_get_str(v)) { snprintf(err, errsz, "Invalid branchId: must be a string"); thought_free(t); return 0; } if (strlen(yyjson_get_str(v)) > BRANCHID_MAX) { snprintf(err, errsz, "Invalid branchId: too long (max %d bytes)", BRANCHID_MAX); thought_free(t); return 0; } t->branch_id = sx_strdup(yyjson_get_str(v)); } v = yyjson_obj_get(args, "needsMoreThoughts"); if (v && !yyjson_is_null(v) && !val_bool(v, &t->needs_more)) { snprintf(err, errsz, "Invalid needsMoreThoughts: must be a boolean"); thought_free(t); return 0; } return 1; } /* One line per accepted thought on stderr, upstream's box condensed to a * single label line (no emoji, no colour codes in a clean-room binary). * Silenced by DISABLE_THOUGHT_LOGGING=1|true like upstream. */ static void log_thought_stderr(const thought_t *t) { const char *dl = getenv("DISABLE_THOUGHT_LOGGING"); char low[8]; size_t i, n; if (dl && *dl) { n = strlen(dl); if (strcmp(dl, "1") == 0) return; if (n < sizeof low) { for (i = 0; i < n; i++) low[i] = (char)tolower((unsigned char)dl[i]); low[n] = '\0'; if (strcmp(low, "true") == 0) return; } } if (t->is_revision) fprintf(stderr, "[seqthink] Revision %lld/%lld (revising thought %lld)\n", t->thought_number, t->total_thoughts, t->revises); else if (t->branch_from && t->branch_id) fprintf(stderr, "[seqthink] Branch %lld/%lld (from thought %lld, ID: %s)\n", t->thought_number, t->total_thoughts, t->branch_from, t->branch_id); else if (t->branch_from) fprintf(stderr, "[seqthink] Branch %lld/%lld (from thought %lld)\n", t->thought_number, t->total_thoughts, t->branch_from); else fprintf(stderr, "[seqthink] Thought %lld/%lld\n", t->thought_number, t->total_thoughts); fflush(stderr); } /* Append one thought to the persisted chains file. The file is a simple * {"chains":[{"id":...,"started_at":...,"updated_at":...,"branches":[...], * "thoughts":[{...}]}]} document, merged by chain id: our chain's * existing thoughts are kept (bounded), other chains are carried over * (bounded, oldest-updated first to keep the newest). Every field is * re-serialised from parsed values, so a hand-corrupted file degrades to * "unparseable -> start clean" instead of poisoning the output. The bytes go * to .tmp and only then rename() over the file (crash-safe). * Returns 1 on success; a persistence failure never fails the tool call. */ typedef struct { char *thought; long long tn, tt; int next_needed, is_revision, needs_more; long long revises, branch_from; char *branch_id; long long at; } pth_t; typedef struct { char *id; long long started_at, updated_at; pth_t *th; size_t n, cap; } chain_t; static void chain_add(chain_t *c, const pth_t *t) { if (c->n == c->cap) { c->cap = c->cap ? c->cap * 2 : 16; c->th = (pth_t *)realloc(c->th, c->cap * sizeof *c->th); if (!c->th) { fputs("out of memory\n", stderr); exit(1); } } c->th[c->n++] = *t; } static void chain_free(chain_t *c) { size_t i; for (i = 0; i < c->n; i++) { free(c->th[i].thought); free(c->th[i].branch_id); } free(c->th); free(c->id); memset(c, 0, sizeof *c); } static char *dup_str_or_null(yyjson_val *v) { if (yyjson_is_str(v) && yyjson_get_str(v)) return sx_strdup(yyjson_get_str(v)); return NULL; } static int load_chains_model(char *txt, size_t len, chain_t **out, size_t *outn) { yyjson_doc *doc; yyjson_val *root, *chains; chain_t *cs = NULL; size_t n = 0, i; *out = NULL; *outn = 0; if (!txt) return 1; doc = yyjson_read(txt, len, 0); free(txt); if (!doc) return 0; /* unparseable */ root = yyjson_doc_get_root(doc); if (!yyjson_is_obj(root)) { yyjson_doc_free(doc); return 0; } chains = yyjson_obj_get(root, "chains"); if (!yyjson_is_arr(chains)) { yyjson_doc_free(doc); return 1; } n = yyjson_arr_size(chains); if (n) { cs = (chain_t *)sx_malloc(n * sizeof *cs); memset(cs, 0, n * sizeof *cs); } for (i = 0; i < n; i++) { yyjson_val *c = yyjson_arr_get(chains, i); yyjson_val *v; if (!yyjson_is_obj(c)) continue; v = yyjson_obj_get(c, "id"); if (!yyjson_is_str(v) || !yyjson_get_str(v) || !*yyjson_get_str(v)) continue; cs[i].id = sx_strdup(yyjson_get_str(v)); v = yyjson_obj_get(c, "started_at"); cs[i].started_at = yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0; v = yyjson_obj_get(c, "updated_at"); cs[i].updated_at = yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0; v = yyjson_obj_get(c, "thoughts"); if (yyjson_is_arr(v)) { size_t j, tn = yyjson_arr_size(v); for (j = 0; j < tn; j++) { yyjson_val *tv = yyjson_arr_get(v, j); pth_t t; yyjson_val *x; if (!yyjson_is_obj(tv)) continue; memset(&t, 0, sizeof t); x = yyjson_obj_get(tv, "thought"); if (!yyjson_is_str(x) || !yyjson_get_str(x)) continue; t.thought = sx_strdup(yyjson_get_str(x)); x = yyjson_obj_get(tv, "thought_number"); t.tn = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; x = yyjson_obj_get(tv, "total_thoughts"); t.tt = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; t.next_needed = yyjson_is_true(yyjson_obj_get(tv, "next_needed")); t.is_revision = yyjson_is_true(yyjson_obj_get(tv, "is_revision")); t.needs_more = yyjson_is_true(yyjson_obj_get(tv, "needs_more")); x = yyjson_obj_get(tv, "revises"); t.revises = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; x = yyjson_obj_get(tv, "branch_from"); t.branch_from = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; t.branch_id = dup_str_or_null(yyjson_obj_get(tv, "branch_id")); x = yyjson_obj_get(tv, "at"); t.at = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; chain_add(&cs[i], &t); } } } yyjson_doc_free(doc); *out = cs; *outn = n; return 1; } static void free_model(chain_t *cs, size_t n) { size_t i; if (!cs) return; for (i = 0; i < n; i++) chain_free(&cs[i]); free(cs); } static void emit_thought(buf_t *b, const pth_t *t) { buf_str(b, "{\"thought\":"); json_escape_buf(b, t->thought); buf_addf(b, ",\"thought_number\":%lld,\"total_thoughts\":%lld", t->tn, t->tt); buf_addf(b, ",\"next_needed\":%s", t->next_needed ? "true" : "false"); if (t->is_revision) buf_str(b, ",\"is_revision\":true"); if (t->revises) buf_addf(b, ",\"revises\":%lld", t->revises); if (t->branch_from) buf_addf(b, ",\"branch_from\":%lld", t->branch_from); if (t->branch_id) { buf_str(b, ",\"branch_id\":"); json_escape_buf(b, t->branch_id); } if (t->needs_more) buf_str(b, ",\"needs_more\":true"); buf_addf(b, ",\"at\":%lld}", t->at); } static int persist_thought(const char *chain_id, const thought_t *t) { char dir[1000], path[1200]; char *txt = NULL; size_t len = 0, i, n = 0; chain_t *cs = NULL; chain_t *mine = NULL; pth_t nt; buf_t out; int mine_idx = -1; state_dir(dir, sizeof dir); if (!mkdirs(dir)) return 0; chains_path(path, sizeof path); txt = read_file(path, &len); if (!load_chains_model(txt, len, &cs, &n)) { /* frees txt, strays to clean */ cs = NULL; n = 0; } for (i = 0; i < n; i++) if (cs[i].id && strcmp(cs[i].id, chain_id) == 0) { mine_idx = (int)i; break; } mine = mine_idx >= 0 ? &cs[mine_idx] : NULL; memset(&nt, 0, sizeof nt); nt.thought = sx_strdup(t->thought); /* owned by the chain model */ nt.tn = t->thought_number; nt.tt = t->total_thoughts; nt.next_needed = t->next_needed; nt.is_revision = t->is_revision; nt.needs_more = t->needs_more; nt.revises = t->revises; nt.branch_from = t->branch_from; nt.branch_id = t->branch_id ? sx_strdup(t->branch_id) : NULL; nt.at = (long long)time(NULL); if (!mine) { cs = (chain_t *)realloc(cs, (n + 1) * sizeof *cs); if (!cs) { fputs("out of memory\n", stderr); exit(1); } memset(&cs[n], 0, sizeof cs[n]); mine = &cs[n]; mine->id = sx_strdup(chain_id); mine->started_at = nt.at; n++; } chain_add(mine, &nt); mine->updated_at = nt.at; /* Bound this chain: keep the newest MAX_THOUGHTS_EACH thoughts. */ if (mine->n > MAX_THOUGHTS_EACH) { size_t drop = mine->n - MAX_THOUGHTS_EACH, j; for (j = 0; j < drop; j++) { free(mine->th[j].thought); free(mine->th[j].branch_id); } memmove(&mine->th[0], &mine->th[drop], (mine->n - drop) * sizeof *mine->th); mine->n -= drop; } /* Bound the file: keep our chain + the newest (MAX_CHAINS - 1) others. * mine_idx is the ORIGINAL index of our chain (mine may dangle after a * growth realloc, so identity is tracked by index). */ if (n > MAX_CHAINS) { char *keep = (char *)sx_malloc(n); size_t w = 0, k; memset(keep, 1, n); if (mine_idx >= 0) keep[mine_idx] = 2; /* ours: never dropped */ while (1) { long long oldest = LLONG_MAX; int oi = -1; size_t kept = 0; for (k = 0; k < n; k++) if (keep[k]) kept++; if (kept <= (size_t)MAX_CHAINS) break; for (k = 0; k < n; k++) { if (keep[k] != 1) continue; if (cs[k].updated_at < oldest) { oldest = cs[k].updated_at; oi = (int)k; } } if (oi < 0) { /* tie fallback */ for (k = 0; k < n; k++) if (keep[k] == 1) { oi = (int)k; break; } } if (oi < 0) break; keep[oi] = 0; } for (k = 0; k < n; k++) { if (!keep[k]) { chain_free(&cs[k]); continue; } if (w != k) cs[w] = cs[k]; w++; } n = w; free(keep); } buf_init(&out); buf_str(&out, "{\"chains\":["); for (i = 0; i < n; i++) { if (i) buf_str(&out, ","); buf_str(&out, "{\"id\":"); json_escape_buf(&out, cs[i].id); buf_addf(&out, ",\"started_at\":%lld,\"updated_at\":%lld,\"thoughts\":[", cs[i].started_at, cs[i].updated_at); { size_t j; for (j = 0; j < cs[i].n; j++) { if (j) buf_str(&out, ","); emit_thought(&out, &cs[i].th[j]); } } buf_str(&out, "],\"count\":"); buf_addf(&out, "%zu", cs[i].n); buf_str(&out, ",\"branches\":["); { /* distinct branch ids in first-seen order */ size_t j, k; int first = 1; for (j = 0; j < cs[i].n; j++) { int seen = 0; if (!cs[i].th[j].branch_id || !cs[i].th[j].branch_from) continue; for (k = 0; k < j; k++) if (cs[i].th[k].branch_id && cs[i].th[j].branch_id && strcmp(cs[i].th[k].branch_id, cs[i].th[j].branch_id) == 0) { seen = 1; break; } if (seen) continue; if (!first) buf_str(&out, ","); first = 0; json_escape_buf(&out, cs[i].th[j].branch_id); } } buf_str(&out, "]}"); } buf_str(&out, "]}"); if (!out.p) { free_model(cs, n); return 0; } { int ok = write_file_atomic(path, out.p, out.n); buf_free(&out); free_model(cs, n); return ok; } } /* ------------------------------------------------------------------ */ /* Session (one --mcp process == one chain) */ /* ------------------------------------------------------------------ */ typedef struct { tvec_t history; bvec_t branches; long long max_hist; char chain_id[64]; int persist; } session_t; static void session_init(session_t *s) { const char *dl = getenv("DISABLE_THOUGHT_LOGGING"); memset(s, 0, sizeof *s); s->max_hist = read_max_history(); snprintf(s->chain_id, sizeof s->chain_id, "th-%llx-%lx", (unsigned long long)time(NULL), (unsigned long) #if defined(_WIN32) GetCurrentProcessId() #else (unsigned long)getpid() #endif ); s->persist = 1; if (dl && *dl) { const char *p = dl; int all_digits = 1; for (; *p; p++) if (!isdigit((unsigned char)*p)) { all_digits = 0; break; } if (strcmp(dl, "1") == 0 || strcmp(dl, "true") == 0 || strcmp(dl, "TRUE") == 0 || strcmp(dl, "True") == 0) s->persist = 0; (void)all_digits; } } static void session_free(session_t *s) { size_t i; for (i = 0; i < s->history.n; i++) thought_free(&s->history.v[i]); free(s->history.v); for (i = 0; i < s->branches.n; i++) free(s->branches.v[i].key); free(s->branches.v); memset(s, 0, sizeof *s); } /* The tool itself. Returns the result text (heap; caller frees) and sets * *is_error like upstream's {content,isError}. */ static char *process_thought(session_t *s, yyjson_val *args, int *is_error) { thought_t t; char err[256]; buf_t b; *is_error = 0; if (!args || !yyjson_is_obj(args)) { return sx_strdup("{\"error\":\"Invalid thought: must be a string\"," "\"status\":\"failed\"}"); } if (!validate_thought(args, &t, err, sizeof err)) { buf_init(&b); buf_str(&b, "{\"error\":"); json_escape_buf(&b, err); buf_str(&b, ",\"status\":\"failed\"}"); *is_error = 1; return b.p ? b.p : sx_strdup("{\"error\":\"invalid input\",\"status\":\"failed\"}"); } /* Upstream rule: thoughtNumber past totalThoughts raises the estimate. */ if (t.thought_number > t.total_thoughts) t.total_thoughts = t.thought_number; /* Upstream logs before touching any state. */ log_thought_stderr(&t); tvec_push(&s->history, &t); if (t.branch_from && t.branch_id) bvec_record(&s->branches, t.branch_id); if ((long long)s->history.n > s->max_hist) { thought_t *oldest = &s->history.v[0]; if (oldest->branch_from && oldest->branch_id) bvec_evict(&s->branches, oldest->branch_id); thought_free(oldest); memmove(&s->history.v[0], &s->history.v[1], (s->history.n - 1) * sizeof *s->history.v); s->history.n--; } if (s->persist) persist_thought(s->chain_id, &t); /* Upstream response: exactly these five fields. One buffer, compact * single-line JSON (valid inside structuredContent); the content text is * the same object, so tests and clients can parse either. */ { size_t i; buf_init(&b); buf_addf(&b, "{\"thoughtNumber\":%lld,\"totalThoughts\":%lld," "\"nextThoughtNeeded\":%s,\"branches\":[", t.thought_number, t.total_thoughts, t.next_needed ? "true" : "false"); for (i = 0; i < s->branches.n; i++) { if (i) buf_str(&b, ","); json_escape_buf(&b, s->branches.v[i].key); } buf_addf(&b, "],\"thoughtHistoryLength\":%zu}", s->history.n); } /* The snapshot was already taken before we hand back; free this * thought's copy only after persistence used it. */ return b.p ? b.p : sx_strdup("{}"); } /* ------------------------------------------------------------------ */ /* --mcp mode: MCP JSON-RPC 2.0 over stdio */ /* ------------------------------------------------------------------ */ static const char SEQTHINK_TOOL_SCHEMA[] = "{\"type\":\"object\",\"properties\":{" "\"thought\":{\"type\":\"string\",\"description\":\"Your current thinking step\"}," "\"nextThoughtNeeded\":{\"type\":\"boolean\",\"description\":\"Whether another thought step is needed\"}," "\"thoughtNumber\":{\"type\":\"integer\",\"description\":\"Current thought number (numeric value, e.g., 1, 2, 3)\",\"minimum\":1}," "\"totalThoughts\":{\"type\":\"integer\",\"description\":\"Estimated total thoughts needed (numeric value, e.g., 5, 10)\",\"minimum\":1}," "\"isRevision\":{\"type\":\"boolean\",\"description\":\"Whether this revises previous thinking\"}," "\"revisesThought\":{\"type\":\"integer\",\"description\":\"Which thought is being reconsidered\",\"minimum\":1}," "\"branchFromThought\":{\"type\":\"integer\",\"description\":\"Branching point thought number\",\"minimum\":1}," "\"branchId\":{\"type\":\"string\",\"description\":\"Branch identifier\"}," "\"needsMoreThoughts\":{\"type\":\"boolean\",\"description\":\"If more thoughts are needed\"}" "},\"required\":[\"thought\",\"nextThoughtNeeded\",\"thoughtNumber\",\"totalThoughts\"]}"; static const char SEQTHINK_TOOL_OUTPUT[] = "{\"type\":\"object\",\"properties\":{" "\"thoughtNumber\":{\"type\":\"number\"}," "\"totalThoughts\":{\"type\":\"number\"}," "\"nextThoughtNeeded\":{\"type\":\"boolean\"}," "\"branches\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}," "\"thoughtHistoryLength\":{\"type\":\"number\"}}}"; static const char SEQTHINK_TOOL_DESC[] = "A detailed tool for dynamic and reflective problem-solving through thoughts.\n" "Each thought can build on, question, or revise previous insights as understanding deepens.\n\n" "When to use this tool:\n" "- Breaking down complex problems into steps\n" "- Planning and design with room for revision\n" "- Analysis that might need course correction\n" "- Problems where the full scope might not be clear initially\n" "- Tasks that need to maintain context over multiple steps\n" "- Situations where irrelevant information needs to be filtered out\n\n" "You should:\n" "1. Estimate totalThoughts up front and adjust it up or down as you go;" " thoughtNumber may exceed it\n" "2. Question or revise earlier thoughts (isRevision with revisesThought)," " or branch (branchFromThought with branchId)\n" "3. Express uncertainty, and ignore information irrelevant to the current step\n" "4. Generate a solution hypothesis, verify it against the earlier steps," " and repeat until satisfied\n" "5. Set nextThoughtNeeded to false only when truly done and a satisfactory" " answer is reached"; /* Emit the tools/list result. */ static void mcp_tools_list(FILE *out, const char *id_raw) { fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"tools\":[{", id_raw); fputs("\"name\":\"sequentialthinking\",\"title\":\"Sequential Thinking\"," "\"description\":", out); json_escape(out, SEQTHINK_TOOL_DESC); fputs(",\"inputSchema\":", out); fputs(SEQTHINK_TOOL_SCHEMA, out); fputs(",\"outputSchema\":", out); fputs(SEQTHINK_TOOL_OUTPUT, out); fputs(",\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":false," "\"idempotentHint\":false,\"openWorldHint\":false}}]}}\n", out); fflush(out); } static void mcp_server_info(FILE *out, const char *id_raw) { fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{" "\"protocolVersion\":\"2024-11-05\",\"capabilities\":{\"tools\":{}}," "\"serverInfo\":{\"name\":\"%s\",\"version\":\"%s\"}}}\n", id_raw, PLUGIN_SLUG, PLUGIN_VER); fflush(out); } /* Copy the raw JSON-RPC id token (number or string) so the reply echoes the * same type. */ static int json_id_raw(const char *line, char *out, size_t outsz) { const char *p = strstr(line, "\"id\""); size_t i = 0; if (!p) return 0; p += 4; while (*p && (unsigned char)*p <= ' ') p++; if (*p != ':') return 0; p++; while (*p && (unsigned char)*p <= ' ') p++; if (*p == '"') { out[i++] = *p++; while (*p && i + 2 < outsz) { out[i++] = *p; if (*p == '\\' && p[1]) { p++; out[i++] = *p++; } else if (*p == '"') { p++; out[i++] = '"'; break; } else p++; } out[i] = '\0'; return i > 1; } while (*p && (isdigit((unsigned char)*p) || *p == '-' || *p == '+') && i + 1 < outsz) out[i++] = *p++; out[i] = '\0'; return i > 0; } static void mcp_tool_call(FILE *out, const char *id_raw, yyjson_val *params, session_t *sess) { yyjson_val *name = NULL, *args = NULL, *v; char *text; int is_err = 0; if (params && yyjson_is_obj(params)) { name = yyjson_obj_get(params, "name"); args = yyjson_obj_get(params, "arguments"); } if (!name || !yyjson_is_str(name) || !yyjson_get_str(name) || strcmp(yyjson_get_str(name), "sequentialthinking") != 0) { fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32602," "\"message\":\"unknown tool\"}}\n", id_raw); fflush(out); return; } (void)v; text = process_thought(sess, args, &is_err); fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"content\":" "[{\"type\":\"text\",\"text\":", id_raw); json_escape(out, text); fputs("}],\"structuredContent\":", out); if (!is_err) { fputs(text, out); /* the five-field object, verbatim */ fputs(",\"isError\":false}}\n", out); } else { fputs(text, out); /* the {error,status} object */ fputs(",\"isError\":true}}\n", out); } fflush(out); free(text); } int run_mcp(void) { char *line = NULL; size_t cap = 0; ssize_t len; session_t sess; session_init(&sess); setvbuf(stdout, NULL, _IOLBF, 0); while ((len = getline(&line, &cap, stdin)) != -1) { yyjson_doc *doc; yyjson_val *root, *m, *params; const char *method; char id_raw[128] = ""; if (len == 0 || !memchr(line, '{', (size_t)len)) continue; doc = yyjson_read(line, strlen(line), 0); if (!doc) continue; root = yyjson_doc_get_root(doc); m = yyjson_obj_get(root, "method"); method = yyjson_is_str(m) ? yyjson_get_str(m) : NULL; params = yyjson_obj_get(root, "params"); if (!method) { yyjson_doc_free(doc); continue; } if (strncmp(method, "notifications/", 14) == 0) { yyjson_doc_free(doc); continue; } if (!json_id_raw(line, id_raw, sizeof id_raw) || !id_raw[0]) { yyjson_doc_free(doc); continue; } if (strcmp(method, "initialize") == 0) { mcp_server_info(stdout, id_raw); } else if (strcmp(method, "tools/list") == 0) { mcp_tools_list(stdout, id_raw); } else if (strcmp(method, "tools/call") == 0) { mcp_tool_call(stdout, id_raw, params, &sess); } else if (strcmp(method, "ping") == 0) { fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{}}\n", id_raw); fflush(stdout); } else { fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32601," "\"message\":\"method not found\"}}\n", id_raw); fflush(stdout); } yyjson_doc_free(doc); } free(line); session_free(&sess); return 0; } /* ------------------------------------------------------------------ */ /* Discovery metadata */ /* ------------------------------------------------------------------ */ static int run_meta(void) { puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"," "\"kind\":\"mcp\",\"mcp\":true,\"daemon\":false,\"menus\":false," "\"verified\":\"live\"}"); fflush(stdout); return 0; } /* ------------------------------------------------------------------ */ /* JSON node API */ /* ------------------------------------------------------------------ */ static void json_headers(void) { fputs("Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); } static char *read_body(void) { const char *cl = getenv("CONTENT_LENGTH"); long n; char *buf; size_t got = 0; if (!cl || !*cl) return NULL; n = atol(cl); if (n <= 0 || (unsigned long)n > REQ_MAX) return NULL; buf = (char *)sx_malloc((size_t)n + 1); while (got < (size_t)n) { size_t r = fread(buf + got, 1, (size_t)n - got, stdin); if (r == 0) break; got += r; } buf[got] = '\0'; return buf; } /* Read one field from a JSON body as a string (string/int/bool coerced). */ static int json_str_field(const char *json, const char *key, char *out, size_t outsz) { yyjson_doc *doc; yyjson_val *v; int found = 0; if (!json) return 0; doc = yyjson_read(json, strlen(json), 0); if (!doc) return 0; v = yyjson_obj_get(yyjson_doc_get_root(doc), key); if (yyjson_is_str(v) && yyjson_get_str(v)) { snprintf(out, outsz, "%s", yyjson_get_str(v)); found = 1; } else if (yyjson_is_int(v)) { snprintf(out, outsz, "%lld", (long long)yyjson_get_sint(v)); found = 1; } else if (yyjson_is_bool(v)) { snprintf(out, outsz, "%s", yyjson_is_true(v) ? "true" : "false"); found = 1; } yyjson_doc_free(doc); return found; } static void api_err(const char *msg) { json_headers(); fputs("{\"ok\":false,\"error\":", stdout); json_escape(stdout, msg ? msg : "error"); fputs("}\n", stdout); } static void api_info(void) { char dir[1000]; state_dir(dir, sizeof dir); json_headers(); fputs("{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"slug\":\"" PLUGIN_SLUG "\",\"version\":\"" PLUGIN_VER "\",\"kind\":\"mcp\",\"mcp\":true," "\"daemon\":false,\"menus\":false,\"verified\":\"live\"," "\"tools\":[\"sequentialthinking\"],\"tool_schema\":", stdout); fputs(SEQTHINK_TOOL_SCHEMA, stdout); fputs(",\"tool_output_schema\":", stdout); fputs(SEQTHINK_TOOL_OUTPUT, stdout); fputs(",\"state_dir\":", stdout); json_escape(stdout, dir); /* json_escape emits its own quotes (bu) */ fputs(",\"max_chains\":", stdout); fprintf(stdout, "%d,\"max_thoughts_each\":%d," "\"max_thought_history\":%lld}\n", MAX_CHAINS, MAX_THOUGHTS_EACH, read_max_history()); } /* Load chains.json (or an empty doc). Caller frees doc. */ static yyjson_doc *load_chains(void) { char path[1200]; char *txt; size_t len = 0; yyjson_doc *doc; chains_path(path, sizeof path); (void)len; txt = read_file(path, &len); if (txt) { doc = yyjson_read(txt, strlen(txt), 0); free(txt); } else { doc = yyjson_read("{\"chains\":[]}", 13, 0); } return doc; } static void api_chains(void) { yyjson_doc *doc = load_chains(); yyjson_val *root, *chains; buf_t b; size_t i, n = 0, total = 0; if (!doc) { api_err("state unreadable"); return; } root = yyjson_doc_get_root(doc); chains = yyjson_is_obj(root) ? yyjson_obj_get(root, "chains") : NULL; if (yyjson_is_arr(chains)) n = yyjson_arr_size(chains); buf_init(&b); buf_addf(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"count\":%zu,", n); { char nm[128]; state_dir_name(nm, sizeof nm); buf_str(&b, "\"state_dir_name\":"); json_escape_buf(&b, nm); } buf_str(&b, ",\"chains\":["); for (i = 0; i < n; i++) { yyjson_val *c = yyjson_arr_get(chains, i); yyjson_val *v, *ths; size_t cnt = 0; const char *last = ""; if (!yyjson_is_obj(c)) continue; ths = yyjson_obj_get(c, "thoughts"); if (yyjson_is_arr(ths)) cnt = yyjson_arr_size(ths); total += cnt; if (cnt) { yyjson_val *lt = yyjson_arr_get_last(ths); if (yyjson_is_obj(lt)) { v = yyjson_obj_get(lt, "thought"); if (yyjson_is_str(v) && yyjson_get_str(v)) last = yyjson_get_str(v); } } if (i) buf_str(&b, ","); buf_str(&b, "{\"id\":"); v = yyjson_obj_get(c, "id"); if (yyjson_is_str(v)) json_escape_buf(&b, yyjson_get_str(v)); else buf_str(&b, "\"\""); v = yyjson_obj_get(c, "started_at"); buf_addf(&b, ",\"started_at\":%lld,", yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0LL); v = yyjson_obj_get(c, "updated_at"); buf_addf(&b, "\"updated_at\":%lld,", yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0LL); buf_addf(&b, "\"thoughts\":%zu,", cnt); buf_str(&b, "\"branches\":["); { yyjson_val *brs = yyjson_obj_get(c, "branches"); if (yyjson_is_arr(brs)) { size_t j, bn = yyjson_arr_size(brs); for (j = 0; j < bn; j++) { yyjson_val *bv = yyjson_arr_get(brs, j); if (j) buf_str(&b, ","); if (yyjson_is_str(bv)) json_escape_buf(&b, yyjson_get_str(bv)); else buf_str(&b, "\"\""); } } } buf_str(&b, "],\"last_head\":"); { /* first line of the last thought, clamped to 160 bytes */ char head[200]; size_t k = 0; for (; last[k] && k < 160 && last[k] != '\n'; k++) head[k] = last[k]; head[k] = '\0'; json_escape_buf(&b, head); } buf_addf(&b, ",\"truncated\":%s}", cnt >= MAX_THOUGHTS_EACH ? "true" : "false"); } buf_str(&b, "]}"); (void)total; json_headers(); if (b.p) fwrite(b.p, 1, b.n, stdout); fputc('\n', stdout); buf_free(&b); yyjson_doc_free(doc); } static int valid_chain_id(const char *id) { size_t i; if (!id || !*id || strlen(id) > 64) return 0; for (i = 0; id[i]; i++) if (!(isalnum((unsigned char)id[i]) || id[i] == '-' || id[i] == '_')) return 0; return 1; } static void api_chain(const char *id) { yyjson_doc *doc; yyjson_val *root, *chains, *c = NULL; size_t i, n; if (!valid_chain_id(id)) { api_err("invalid chain id"); return; } doc = load_chains(); if (!doc) { api_err("state unreadable"); return; } root = yyjson_doc_get_root(doc); chains = yyjson_is_obj(root) ? yyjson_obj_get(root, "chains") : NULL; if (yyjson_is_arr(chains)) { n = yyjson_arr_size(chains); for (i = 0; i < n; i++) { yyjson_val *cv = yyjson_arr_get(chains, i); yyjson_val *v = yyjson_is_obj(cv) ? yyjson_obj_get(cv, "id") : NULL; if (yyjson_is_str(v) && yyjson_get_str(v) && strcmp(yyjson_get_str(v), id) == 0) { c = cv; break; } } } if (!c) { yyjson_doc_free(doc); api_err("chain not found"); return; } { char *txt = yyjson_val_write(c, 0, NULL); json_headers(); if (txt) { char *obj = txt; fputs("{\"ok\":true,", stdout); fputs(obj + 1, stdout); /* drop the object's leading { */ fputs("\n", stdout); free(txt); } else { fputs("{\"ok\":false,\"error\":\"serialize failed\"}\n", stdout); } } yyjson_doc_free(doc); } static void api_stats(void) { yyjson_doc *doc = load_chains(); yyjson_val *root, *chains; size_t i, n = 0, thoughts = 0, branches = 0, revs = 0; long long newest = 0; if (!doc) { api_err("state unreadable"); return; } root = yyjson_doc_get_root(doc); chains = yyjson_is_obj(root) ? yyjson_obj_get(root, "chains") : NULL; if (yyjson_is_arr(chains)) { n = yyjson_arr_size(chains); for (i = 0; i < n; i++) { yyjson_val *c = yyjson_arr_get(chains, i); yyjson_val *ths, *brs, *ua; size_t j, tn; if (!yyjson_is_obj(c)) continue; ua = yyjson_obj_get(c, "updated_at"); if (yyjson_is_int(ua) && yyjson_get_sint(ua) > newest) newest = (long long)yyjson_get_sint(ua); brs = yyjson_obj_get(c, "branches"); if (yyjson_is_arr(brs)) branches += yyjson_arr_size(brs); ths = yyjson_obj_get(c, "thoughts"); if (!yyjson_is_arr(ths)) continue; tn = yyjson_arr_size(ths); thoughts += tn; for (j = 0; j < tn; j++) { yyjson_val *tv = yyjson_arr_get(ths, j); if (yyjson_is_obj(tv) && yyjson_is_true(yyjson_obj_get(tv, "is_revision"))) revs++; } } } json_headers(); fprintf(stdout, "{\"ok\":true,\"chains\":%zu,\"thoughts\":%zu," "\"branches\":%zu,\"revisions\":%zu," "\"last_activity\":%lld,\"max_chains\":%d," "\"max_thoughts_each\":%d,\"max_thought_history\":%lld}\n", n, thoughts, branches, revs, newest, MAX_CHAINS, MAX_THOUGHTS_EACH, read_max_history()); yyjson_doc_free(doc); } static void api_clear(void) { char path[1200]; chains_path(path, sizeof path); if (remove(path) != 0 && errno != ENOENT) { #ifdef _WIN32 /* Windows remove() fails on read-only files; try clearing the bit. */ { DWORD a = GetFileAttributesA(path); if (a != INVALID_FILE_ATTRIBUTES) { SetFileAttributesA(path, FILE_ATTRIBUTE_NORMAL); if (remove(path) != 0) { api_err("remove failed"); return; } } else { api_err("remove failed"); return; } } #else api_err("remove failed"); return; #endif } json_headers(); fputs("{\"ok\":true,\"cleared\":true}\n", stdout); } static int api_dispatch(const char *action, const char *qs, const char *body) { char id[96] = ""; if (!action[0] || strcmp(action, "chains") == 0) { api_chains(); return 0; } if (strcmp(action, "chain") == 0) { if (!(body && json_str_field(body, "id", id, sizeof id)) && !(qs && *qs && get_query_val(qs, "id", id, sizeof id))) id[0] = '\0'; api_chain(id); return 0; } if (strcmp(action, "stats") == 0) { api_stats(); return 0; } if (strcmp(action, "info") == 0) { api_info(); return 0; } if (strcmp(action, "clear") == 0) { char cf[16] = ""; if (!(body && json_str_field(body, "confirm", cf, sizeof cf))) if (qs && *qs) get_query_val(qs, "confirm", cf, sizeof cf); if (strcmp(cf, "1") != 0 && strcmp(cf, "true") != 0) { api_err("confirm=1 required"); return 0; } api_clear(); return 0; } api_err("unknown action"); return 0; } /* ------------------------------------------------------------------ */ /* HTML mode */ /* ------------------------------------------------------------------ */ static void emit_ui(void) { const char *p = UI_HTML; while (*p) { if (*p == '\001') { fputs(SX_BOT_THEME_PREPAINT "", stdout); p++; } else if (*p == '\002') { fputs(SX_BOT_THEME_HANDOFF, stdout); p++; } else { putchar(*p++); } } } static void mode_html(void) { fputs("Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n" "X-Frame-Options: SAMEORIGIN\r\n" "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); emit_ui(); } /* ------------------------------------------------------------------ */ /* main */ /* ------------------------------------------------------------------ */ int main(int argc, char **argv) { const char *qs; char action[64] = ""; char *body = NULL; int have_action = 0; const char *rm; int is_post; #if defined(_WIN32) { /* MinGW text-mode stdout turns our CRLF into CRCRLF and breaks CGI * framing - force binary stdio. */ _setmode(_fileno(stdout), _O_BINARY); _setmode(_fileno(stdin), _O_BINARY); _setmode(_fileno(stderr), _O_BINARY); } #endif /* 1. Discovery metadata (unauthenticated so /plugins can probe it) */ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) return run_meta(); /* 2. MCP stdio server */ if (argc > 1 && strcmp(argv[1], "--mcp") == 0) return run_mcp(); if (argc > 1 && strcmp(argv[1], "--schema") == 0) { puts(SEQTHINK_TOOL_SCHEMA); return 0; } if (argc > 1 && strcmp(argv[1], "--version") == 0) { printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); return 0; } /* The CGI surface is one private viewer: gate HTML AND the JSON API. * Discovery (--meta) and the stdio MCP server (--mcp) returned above, so * a node still probes and serves this plugin without a credential, but a * bare unauthenticated GET /plugin_seqthink answers 401, exactly like * plugin_logs / plugin_notes / plugin_sqlite. */ require_node_auth(); qs = getenv("QUERY_STRING"); if (!qs) qs = ""; have_action = get_query_val(qs, "action", action, sizeof action); if (!have_action && strstr(qs, "format=json")) { const char *fm = strstr(qs, "format=json"); if (fm[11] == '\0' || fm[11] == '&') { snprintf(action, sizeof action, "chains"); have_action = 1; } } rm = getenv("REQUEST_METHOD"); is_post = rm && strcmp(rm, "POST") == 0; if (have_action || is_post) { body = read_body(); if (body) { char jact[64] = ""; if (json_str_field(body, "action", jact, sizeof jact) && jact[0]) snprintf(action, sizeof action, "%s", jact); else if (!action[0]) snprintf(action, sizeof action, "chains"); } else if (!action[0]) { snprintf(action, sizeof action, "chains"); } { int rc = api_dispatch(action, qs, body); free(body); return rc; } } mode_html(); return 0; }