| 1 | 1 | new file mode 100644 |
| index 0000000..960ea27 | ||
| --- /dev/null | ||
| +++ b/.gitignore | ||
| @@ -0,0 +1,13 @@ | ||
| 1 | +plugin_seqthink | |
| 2 | +plugin_seqthink.exe | |
| 3 | +plugin_seqthink.musl | |
| 4 | +plugin_seqthink.arm64 | |
| 5 | +plugin_seqthink.asan | |
| 6 | +plugin_seqthink.fortify | |
| 7 | +plugin_seqthink.macos-arm64 | |
| 8 | +plugin_seqthink.macos-x86_64 | |
| 9 | +bin/ | |
| 10 | +dist/ | |
| 11 | +*.o | |
| 12 | +__pycache__/ | |
| 13 | +*.pyc |
| 1 | 1 | new file mode 100644 |
| index 0000000..edac426 | ||
| --- /dev/null | ||
| +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | |
| 2 | + | |
| 3 | +Copyright (c) 2026 SCORPIOX INC. | |
| 4 | + | |
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 6 | +of this software and associated documentation files (the "Software"), to deal | |
| 7 | +in the Software without restriction, including without limitation the rights | |
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 9 | +copies of the Software, and to permit persons to whom the Software is | |
| 10 | +furnished to do so, subject to the following conditions: | |
| 11 | + | |
| 12 | +The above copyright notice and this permission notice shall be included in all | |
| 13 | +copies or substantial portions of the Software. | |
| 14 | + | |
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 21 | +SOFTWARE. |
| 1 | 1 | new file mode 100644 |
| index 0000000..53cdb2e | ||
| --- /dev/null | ||
| +++ b/Makefile | ||
| @@ -0,0 +1,79 @@ | ||
| 1 | +# plugin_seqthink - SCORPIOX BOT open-source sequential-thinking MCP connector | |
| 2 | +# | |
| 3 | +# Targets: | |
| 4 | +# make native build -> ./plugin_seqthink | |
| 5 | +# make musl static musl x86_64 -> ./plugin_seqthink (fully static) | |
| 6 | +# make arm64 static aarch64 -> ./plugin_seqthink.arm64 | |
| 7 | +# make win64 MinGW-w64 static -> ./plugin_seqthink.exe | |
| 8 | +# make macos Apple clang -> ./plugin_seqthink (run on macOS) | |
| 9 | +# make asan -fsanitize=address build -> ./plugin_seqthink.asan | |
| 10 | +# make fortify -D_FORTIFY_SOURCE=2 build -> ./plugin_seqthink.fortify | |
| 11 | +# make ui regenerate src/ui_html.h from src/ui.html | |
| 12 | +# make test build + run tests/run.sh | |
| 13 | +# make clean | |
| 14 | + | |
| 15 | +CC ?= cc | |
| 16 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings | |
| 17 | +MUSL_CC ?= musl-gcc | |
| 18 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | |
| 19 | +ARM64_CC ?= aarch64-linux-musl-gcc | |
| 20 | +ARM64_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | |
| 21 | +WIN_CC ?= x86_64-w64-mingw32-gcc | |
| 22 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | |
| 23 | +SRC := src/plugin_seqthink.c vendor/yyjson.c | |
| 24 | +HDR := src/bot_theme_plugin.h src/ui_html.h vendor/yyjson.h | |
| 25 | +INC := -I src -I vendor | |
| 26 | +BIN := plugin_seqthink | |
| 27 | +EXE := plugin_seqthink.exe | |
| 28 | + | |
| 29 | +.PHONY: all native musl arm64 win64 macos asan fortify ui test clean help | |
| 30 | + | |
| 31 | +all: native | |
| 32 | + | |
| 33 | +native: $(BIN) | |
| 34 | + | |
| 35 | +$(BIN): $(SRC) $(HDR) | |
| 36 | + @echo "==> native build ($(CC))" | |
| 37 | + $(CC) $(CFLAGS) $(INC) -o $(BIN) $(SRC) | |
| 38 | + | |
| 39 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | |
| 40 | +musl: $(SRC) $(HDR) | |
| 41 | + @echo "==> static musl build ($(MUSL_CC))" | |
| 42 | + $(MUSL_CC) $(MUSL_CFLAGS) $(INC) -o $(BIN) $(SRC) | |
| 43 | + | |
| 44 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | |
| 45 | +arm64: $(SRC) $(HDR) | |
| 46 | + @echo "==> static aarch64 build ($(ARM64_CC))" | |
| 47 | + $(ARM64_CC) $(ARM64_CFLAGS) $(INC) -o $(BIN).arm64 $(SRC) | |
| 48 | + | |
| 49 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | |
| 50 | +win64: $(SRC) $(HDR) | |
| 51 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | |
| 52 | + $(WIN_CC) $(WIN_CFLAGS) $(INC) -o $(EXE) $(SRC) | |
| 53 | + | |
| 54 | +# Apple clang build (run this on macOS) | |
| 55 | +macos: $(SRC) $(HDR) | |
| 56 | + @echo "==> Apple clang build" | |
| 57 | + $(CC) $(CFLAGS) $(INC) -o $(BIN) $(SRC) | |
| 58 | + | |
| 59 | +asan: $(SRC) $(HDR) | |
| 60 | + @echo "==> ASan build" | |
| 61 | + $(CC) -g -O0 -std=c99 -Wall -Wextra -fsanitize=address $(INC) -o $(BIN).asan $(SRC) | |
| 62 | + | |
| 63 | +fortify: $(SRC) $(HDR) | |
| 64 | + @echo "==> fortify build" | |
| 65 | + $(CC) -O2 -std=c99 -Wall -Wextra -D_FORTIFY_SOURCE=2 $(INC) -o $(BIN).fortify $(SRC) | |
| 66 | + | |
| 67 | +ui: | |
| 68 | + python3 tools/gen_ui.py | |
| 69 | + | |
| 70 | +test: native asan fortify | |
| 71 | + @sh tests/run.sh | |
| 72 | + | |
| 73 | +clean: | |
| 74 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).asan $(BIN).fortify | |
| 75 | + rm -f $(BIN).macos-arm64 $(BIN).macos-x86_64 | |
| 76 | + rm -rf bin dist | |
| 77 | + | |
| 78 | +help: | |
| 79 | + @echo "make | make musl | make arm64 | make win64 | make macos | make asan | make fortify | make ui | make test | make clean" |
| 1 | 1 | new file mode 100644 |
| index 0000000..a3dd890 | ||
| --- /dev/null | ||
| +++ b/README.md | ||
| @@ -0,0 +1,166 @@ | ||
| 1 | +# plugin_seqthink — Sequential Thinking (SCORPIOX BOT plugin) | |
| 2 | + | |
| 3 | +`seqthink` is a clean-room, zero-dependency, pure C99 **MCP connector plugin** | |
| 4 | +for [SCORPIOX BOT](https://bot.scorpiox.net). One small static binary serves the | |
| 5 | +`sequentialthinking` tool over **MCP JSON-RPC 2.0 stdio** and ships a | |
| 6 | +bot-themed **thought-chain viewer**, so structured step-by-step reasoning, | |
| 7 | +revisions and branches made by an agent are inspectable on the node. | |
| 8 | + | |
| 9 | +It is a clean-room C port of the behaviour of the reference | |
| 10 | +`modelcontextprotocol/servers` **sequential-thinking** server: the same | |
| 11 | +parameter validation and error strings, the same "raise `totalThoughts` when | |
| 12 | +`thoughtNumber` exceeds it" rule, the same per-connection history with a | |
| 13 | +`MAX_THOUGHT_HISTORY` cap (oldest evicted, its branch shrunk with it, an | |
| 14 | +emptied branch dropped), the same branch semantics (a branch exists only once a | |
| 15 | +thought carries **both** `branchFromThought` and `branchId`), and the same | |
| 16 | +five-field result. | |
| 17 | + | |
| 18 | +| | | | |
| 19 | +|---|---| | |
| 20 | +| Slug | `seqthink` | | |
| 21 | +| Binary | `plugin_seqthink` (`plugin_seqthink.exe` on Windows) | | |
| 22 | +| `--meta` | `{"name":"seqthink","desc":"Thought chains","kind":"mcp","mcp":true,"daemon":false,"menus":false,"verified":"live"}` | | |
| 23 | +| Category | `devtools` | | |
| 24 | +| Dependencies | none — vendored [yyjson](https://github.com/ibireme/yyjson) (MIT) is compiled in | | |
| 25 | +| Network | **zero outbound requests** (no TLS, no sockets, no `popen`) | | |
| 26 | +| State | its own connector directory only (see below) | | |
| 27 | + | |
| 28 | +## The four modes of one binary | |
| 29 | + | |
| 30 | +| Mode | Trigger | Contract | | |
| 31 | +|---|---|---| | |
| 32 | +| Discovery | `--meta` or `SX_PLUGIN_META=1` | one line of JSON, exit 0, **never authenticated** | | |
| 33 | +| MCP server | `--mcp` | JSON-RPC 2.0 over stdio: `initialize`, `notifications/*`, `ping`, `tools/list`, `tools/call` | | |
| 34 | +| Node API | `?action=...` or a POST JSON body | `Content-Type: application/json`, behind `require_node_auth()` | | |
| 35 | +| Viewer UI | `GET` (default) | responsive dark/light HTML (`?embed=1`, `&theme=`, `sx-theme` handoff), zero `<script src=>` | | |
| 36 | + | |
| 37 | +```bash | |
| 38 | +./plugin_seqthink --meta | |
| 39 | +./plugin_seqthink --schema | |
| 40 | +printf '%s\n' \ | |
| 41 | + '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \ | |
| 42 | + '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \ | |
| 43 | + '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"first step","nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":3}}}' \ | |
| 44 | + | ./plugin_seqthink --mcp | |
| 45 | +``` | |
| 46 | + | |
| 47 | +## The `sequentialthinking` tool | |
| 48 | + | |
| 49 | +Input schema (exact parity with the reference server): | |
| 50 | + | |
| 51 | +| Field | Type | Req | Notes | | |
| 52 | +|---|---|---|---| | |
| 53 | +| `thought` | string | yes | the current thinking step (non-empty, ≤ 64 KB) | | |
| 54 | +| `nextThoughtNeeded` | boolean | yes | a `"true"` / `"false"` string is accepted, like upstream | | |
| 55 | +| `thoughtNumber` | integer ≥ 1 | yes | numbers **or** numeric strings (`z.coerce` parity) | | |
| 56 | +| `totalThoughts` | integer ≥ 1 | yes | estimate; raised automatically when exceeded | | |
| 57 | +| `isRevision` | boolean | no | this thought revises earlier thinking | | |
| 58 | +| `revisesThought` | integer ≥ 1 | no | which thought number is reconsidered | | |
| 59 | +| `branchFromThought` | integer ≥ 1 | no | branching point | | |
| 60 | +| `branchId` | string | no | branch identifier (with `branchFromThought`, opens the branch) | | |
| 61 | +| `needsMoreThoughts` | boolean | no | reached the end but more thoughts are needed | | |
| 62 | + | |
| 63 | +Every accepted thought returns exactly: | |
| 64 | + | |
| 65 | +```json | |
| 66 | +{"thoughtNumber":1,"totalThoughts":3,"nextThoughtNeeded":true,"branches":[],"thoughtHistoryLength":1} | |
| 67 | +``` | |
| 68 | + | |
| 69 | +as `result.content[0].text` **and** as `result.structuredContent`. A validation | |
| 70 | +failure returns `{"error":"...","status":"failed"}` with `isError: true`, using | |
| 71 | +the upstream messages (`Invalid thought: must be a string`, | |
| 72 | +`Invalid thoughtNumber: must be a number`, `Invalid nextThoughtNeeded: must be | |
| 73 | +a boolean`, ...). | |
| 74 | + | |
| 75 | +## Persistence (so the viewer can see agent reasoning) | |
| 76 | + | |
| 77 | +One `--mcp` process is one chain (a server lives as long as its client's | |
| 78 | +connection, exactly like upstream). Each accepted thought additionally | |
| 79 | +snapshots the chain to: | |
| 80 | + | |
| 81 | +``` | |
| 82 | +<state_dir>/chains.json | |
| 83 | +``` | |
| 84 | + | |
| 85 | +where `<state_dir>` is, in order: `$SEQTHINK_STATE_DIR`, | |
| 86 | +`/workspace/.scorpiox/connectors/plugin_seqthink` (when `/workspace` exists and | |
| 87 | +is writable — persists across container restarts), | |
| 88 | +`%LOCALAPPDATA%\scorpiox\connectors\plugin_seqthink` on Windows, else | |
| 89 | +`$HOME/.scorpiox/connectors/plugin_seqthink`. | |
| 90 | + | |
| 91 | +The file is merged by chain id (other chains are never clobbered), bounded to | |
| 92 | +50 chains × 1000 thoughts each, and always written `.tmp` → `rename()`, so an | |
| 93 | +interrupted write can never truncate it. A malformed file degrades to a clean | |
| 94 | +start instead of crashing. `DISABLE_THOUGHT_LOGGING=1|true` (upstream parity) | |
| 95 | +silences the stderr line and the persistence. `MAX_THOUGHT_HISTORY` caps the | |
| 96 | +in-memory history (default 1000; a non-positive-integer value is reported on | |
| 97 | +stderr and replaced by the default). | |
| 98 | + | |
| 99 | +## Node API (behind `require_node_auth()`) | |
| 100 | + | |
| 101 | +`X-Bot-Password`, `Authorization: Bearer` or `?pwd=`; a no-op when the node has | |
| 102 | +no `BOT_PASSWORD`. `--meta`, `--mcp` and the HTML page are never gated. | |
| 103 | + | |
| 104 | +| Action | Result | | |
| 105 | +|---|---| | |
| 106 | +| `?action=chains` | every chain: id, started/updated, thought count, branch list, last thought head | | |
| 107 | +| `?action=chain&id=` | one chain's full thought list (id validated: `[A-Za-z0-9_-]{1,64}`) | | |
| 108 | +| `?action=stats` | chains / thoughts / branches / revisions / last activity | | |
| 109 | +| `?action=info` | plugin + tool schema + caps + state dir | | |
| 110 | +| `?action=clear&confirm=1` | delete the store (also accepts a POST JSON body) | | |
| 111 | + | |
| 112 | +## Build | |
| 113 | + | |
| 114 | +```sh | |
| 115 | +make # native -> ./plugin_seqthink | |
| 116 | +make musl # static musl x86_64 (the universal Linux artifact) | |
| 117 | +make arm64 # static aarch64 | |
| 118 | +make win64 # static PE via MinGW-w64 | |
| 119 | +make macos # Apple clang (run on macOS) | |
| 120 | +make asan # -fsanitize=address | |
| 121 | +make fortify # -D_FORTIFY_SOURCE=2 | |
| 122 | +make test # native + asan + fortify, then tests/run.sh | |
| 123 | +make ui # regenerate src/ui_html.h from src/ui.html | |
| 124 | +``` | |
| 125 | + | |
| 126 | +Or through the release CLI (builds all six dist targets + manifest): | |
| 127 | + | |
| 128 | +```sh | |
| 129 | +scorpiox-cli-botplugin build . | |
| 130 | +``` | |
| 131 | + | |
| 132 | +## Tests | |
| 133 | + | |
| 134 | +```sh | |
| 135 | +sh tests/run.sh # 190+ offline assertions: all 4 modes, MCP parity, | |
| 136 | + # validation errors, caps, auth, HTML invariants, | |
| 137 | + # ASan + fortify, clean-room audit | |
| 138 | +python3 tests/e2e.py # Playwright 1440 / 1024 / 390 dark + light (skips | |
| 139 | + # cleanly without Playwright) | |
| 140 | +``` | |
| 141 | + | |
| 142 | +## Install on a node | |
| 143 | + | |
| 144 | +Install it from SCORPIOX BOT: **Settings → Plugins → Marketplace → seqthink** | |
| 145 | +(1-click prebuilt with SHA-256 verification, or compile-from-source), or let | |
| 146 | +your agent clone, audit and compile this repository. Then register it as an MCP | |
| 147 | +server through the SCORPIOX BOT connector router: | |
| 148 | + | |
| 149 | +```json | |
| 150 | +{ "mcpServers": { "seqthink": { "command": "/path/to/plugin_seqthink", | |
| 151 | + "args": ["--mcp"] } } } | |
| 152 | +``` | |
| 153 | + | |
| 154 | +Open the viewer at `Settings → Plugins` → `Open`, or directly at | |
| 155 | +`/plugin_seqthink` on the node. | |
| 156 | + | |
| 157 | +## Security posture | |
| 158 | + | |
| 159 | +* Runs as a normal plugin binary with the node user's permissions — auditable: | |
| 160 | + this whole repository is the source, and `source.tar.gz` next to every | |
| 161 | + published binary is the exact `git archive` of the pinned commit. | |
| 162 | +* Opens **no** sockets and spawns **no** child processes; the only files it | |
| 163 | + writes are inside its own connector directory. | |
| 164 | +* Chain ids are validated before use; every JSON response is built in one | |
| 165 | + buffer and emitted once; thought text and branch ids are length-capped. | |
| 166 | +* MIT licensed. Vendored yyjson is MIT (see `vendor/LICENSE.yyjson.txt`). |
| 1 | 1 | new file mode 100644 |
| index 0000000..9df916b |

| 1 | 1 | new file mode 100644 |
| index 0000000..1d2bf81 |

| 1 | 1 | new file mode 100644 |
| index 0000000..5881784 |

| 1 | 1 | new file mode 100644 |
| index 0000000..2ab6bb1 |

| 1 | 1 | new file mode 100644 |
| index 0000000..6f9af43 |

| 1 | 1 | new file mode 100644 |
| index 0000000..d914da2 |

| 1 | 1 | new file mode 100644 |
| index 0000000..396bc35 | ||
| --- /dev/null | ||
| +++ b/plugin.json | ||
| @@ -0,0 +1,19 @@ | ||
| 1 | +{ | |
| 2 | + "slug": "seqthink", | |
| 3 | + "id": "plugin_seqthink", | |
| 4 | + "title": "Sequential Thinking", | |
| 5 | + "summary": "Zero-dependency sequential-thinking MCP connector for your node. One C99 binary serves the sequentialthinking tool over MCP stdio (initialize / tools/list / tools/call) with the exact parameter validation, revision and branching semantics of the reference server, snapshots every accepted thought chain to its own connector directory, and ships a bot-themed viewer for recent reasoning chains, revisions and branches.", | |
| 6 | + "category": "devtools", | |
| 7 | + "license": "MIT", | |
| 8 | + "kind": "mcp", | |
| 9 | + "mcp": true, | |
| 10 | + "daemon": false, | |
| 11 | + "menus": false, | |
| 12 | + "verified": "live", | |
| 13 | + "capabilities": [ | |
| 14 | + "mcp_stdio_server", | |
| 15 | + "local_state_write", | |
| 16 | + "no_network" | |
| 17 | + ], | |
| 18 | + "trust_notice": "Executes native C code on your node. Serves the sequentialthinking MCP tool over stdio and writes thought-chain snapshots only inside its own connector directory (~/.scorpiox/connectors/plugin_seqthink, /workspace/.scorpiox/connectors/plugin_seqthink, or $SEQTHINK_STATE_DIR). It opens no network connection of any kind and reads nothing outside that directory." | |
| 19 | +} |
| 1 | 1 | new file mode 100755 |
| index 0000000..83b05c0 | ||
| --- /dev/null | ||
| +++ b/release-dist.sh | ||
| @@ -0,0 +1,369 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# release-dist.sh — build, scan and publish plugin_seqthink to the plugin registry. | |
| 3 | +# | |
| 4 | +# Two paths: | |
| 5 | +# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it | |
| 6 | +# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI. | |
| 7 | +# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz -> | |
| 8 | +# manifest.json + SHA256SUMS -> upload -> latest.json / index.json -> plugingit mirror. | |
| 9 | +# | |
| 10 | +# Nothing here contains a host address or a credential. Everything environment-specific | |
| 11 | +# comes from the environment, so this file stays safe to publish: | |
| 12 | +# | |
| 13 | +# DIST_HOST ssh target for the dist server (required for upload) | |
| 14 | +# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key) | |
| 15 | +# DIST_PATH remote web root of the dist server (default /data/dist) | |
| 16 | +# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64) | |
| 17 | +# MAC_USER / MAC_PASS (optional) | |
| 18 | +# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token) | |
| 19 | +# PLUGINGIT_REMOTE public mirror URL to push into | |
| 20 | +# | |
| 21 | +# Usage: | |
| 22 | +# ./release-dist.sh # full release | |
| 23 | +# ./release-dist.sh --dry-run # build + stage in /tmp, no upload | |
| 24 | +# ./release-dist.sh --no-macos # skip the macOS legs | |
| 25 | +# ./release-dist.sh --no-mirror # skip the plugingit mirror | |
| 26 | + | |
| 27 | +set -euo pipefail | |
| 28 | + | |
| 29 | +SLUG="seqthink" | |
| 30 | +ID="plugin_seqthink" | |
| 31 | +VERSION="1.0.0" | |
| 32 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | |
| 33 | + | |
| 34 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | |
| 35 | +cd "$ROOT" | |
| 36 | + | |
| 37 | +DRY_RUN=0 | |
| 38 | +DO_MACOS=1 | |
| 39 | +DO_MIRROR=1 | |
| 40 | +for arg in "$@"; do | |
| 41 | + case "$arg" in | |
| 42 | + --dry-run) DRY_RUN=1 ;; | |
| 43 | + --no-macos) DO_MACOS=0 ;; | |
| 44 | + --no-mirror) DO_MIRROR=0 ;; | |
| 45 | + -h|--help) sed -n '2,30p' "$0"; exit 0 ;; | |
| 46 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | |
| 47 | + esac | |
| 48 | +done | |
| 49 | + | |
| 50 | +DIST_HOST="${DIST_HOST:-}" | |
| 51 | +DIST_PASS="${DIST_PASS:-}" | |
| 52 | +DIST_PATH="${DIST_PATH:-/data/dist}" | |
| 53 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | |
| 54 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | |
| 55 | + | |
| 56 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | |
| 57 | +mkdir -p "$STAGE" | |
| 58 | +trap 'rm -rf "$STAGE"' EXIT | |
| 59 | + | |
| 60 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | |
| 61 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | |
| 62 | + | |
| 63 | +# ---------------------------------------------------------------- 0. preflight | |
| 64 | +say "0/7 preflight" | |
| 65 | + | |
| 66 | +if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | |
| 67 | + say "using scorpiox-cli-botplugin publish" | |
| 68 | + exec scorpiox-cli-botplugin publish "$ROOT" | |
| 69 | +fi | |
| 70 | +echo " scorpiox-cli-botplugin not installed — running standalone pipeline" | |
| 71 | + | |
| 72 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | |
| 73 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | |
| 74 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | |
| 75 | +echo " version $VERSION" | |
| 76 | +echo " commit $COMMIT" | |
| 77 | + | |
| 78 | +# ---------------------------------------------------------------- 1. secret scan | |
| 79 | +say "1/7 secret & LAN scan (full history)" | |
| 80 | + | |
| 81 | +SCAN_TMP="$STAGE/history.txt" | |
| 82 | +# Scan every added/removed line of every commit. Two exclusions, both about the | |
| 83 | +# audit rather than the code: the committer identity line, and any line that is | |
| 84 | +# itself a scan definition — otherwise this file's own detector patterns read as | |
| 85 | +# findings in every historical revision of it. | |
| 86 | +git log -p --all 2>/dev/null \ | |
| 87 | + | grep -v '^Author: ' \ | |
| 88 | + | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \ | |
| 89 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | |
| 90 | +HITS=0 | |
| 91 | +scan() { # scan <label> <regex> | |
| 92 | + local out | |
| 93 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | |
| 94 | + if [ -n "$out" ]; then | |
| 95 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | |
| 96 | + printf '%s\n' "$out" | sed 's/^/ /' | |
| 97 | + HITS=$((HITS + 1)) | |
| 98 | + else | |
| 99 | + printf ' ok %s\n' "$1" | |
| 100 | + fi | |
| 101 | +} | |
| 102 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | |
| 103 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 104 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | |
| 105 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | |
| 106 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | |
| 107 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | |
| 108 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | |
| 109 | +P_ROOT="/codebases" | |
| 110 | +P_PICOBOT="${P_ROOT}/pico""bot" | |
| 111 | +P_WT=".work""trees" | |
| 112 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | |
| 113 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | |
| 114 | +if [ "$HITS" -ne 0 ]; then | |
| 115 | + die "secret scan found $HITS problem(s) — refusing to publish" | |
| 116 | +fi | |
| 117 | +echo " clean: 0 hits" | |
| 118 | + | |
| 119 | +# ---------------------------------------------------------------- 2. build | |
| 120 | +say "2/7 build targets" | |
| 121 | + | |
| 122 | +build_ok() { [ -f "$1" ]; } | |
| 123 | + | |
| 124 | +# linux-x86_64 (glibc, native) | |
| 125 | +if command -v cc >/dev/null 2>&1; then | |
| 126 | + cc -O2 -std=c99 -Wall -Wextra -I src -I vendor -o "$STAGE/$ID" src/$ID.c vendor/yyjson.c || die "native build failed" | |
| 127 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | |
| 128 | +else | |
| 129 | + die "no native cc found" | |
| 130 | +fi | |
| 131 | + | |
| 132 | +# linux-x86_64-musl (fully static — the universal Linux artifact) | |
| 133 | +if command -v musl-gcc >/dev/null 2>&1; then | |
| 134 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -I src -I vendor -o "$STAGE/$ID.musl" src/$ID.c vendor/yyjson.c \ | |
| 135 | + || die "musl build failed" | |
| 136 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | |
| 137 | +else | |
| 138 | + echo " skip linux-x86_64-musl (no musl-gcc)" | |
| 139 | +fi | |
| 140 | + | |
| 141 | +# linux-arm64-musl (static aarch64 — Pi 5 / ARM64 servers) | |
| 142 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | |
| 143 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -I src -I vendor -o "$STAGE/$ID.arm64" src/$ID.c vendor/yyjson.c \ | |
| 144 | + || die "arm64 musl build failed" | |
| 145 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | |
| 146 | +else | |
| 147 | + echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)" | |
| 148 | +fi | |
| 149 | + | |
| 150 | +# windows-x86_64 (static PE) | |
| 151 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | |
| 152 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -I src -I vendor -o "$STAGE/$ID.exe" src/$ID.c vendor/yyjson.c \ | |
| 153 | + || die "MinGW build failed" | |
| 154 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | |
| 155 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | |
| 156 | +else | |
| 157 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | |
| 158 | +fi | |
| 159 | + | |
| 160 | +# macOS legs — Mach-O must be produced by Apple clang on a real Mac. | |
| 161 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | |
| 162 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | |
| 163 | + MAC_USER="${MAC_USER:-$(whoami)}" | |
| 164 | + MAC_DIR="/tmp/${ID}-mac-$$" | |
| 165 | + echo " building macOS legs on $MAC_HOST" | |
| 166 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | |
| 167 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | |
| 168 | + if [ -n "${MAC_PASS:-}" ]; then | |
| 169 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | |
| 170 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | |
| 171 | + fi | |
| 172 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | |
| 173 | + # Ship the whole src/ + vendor/ tree: the plugin includes bot_theme_plugin.h, | |
| 174 | + # ui_html.h and yyjson.h next to the source, and the CLI/macOS leg history | |
| 175 | + # (lesson ag) shows scp of a lone .c silently loses both Mach-O slices. | |
| 176 | + TARMAC="$STAGE/mac-src.tar.gz" | |
| 177 | + tar -czf "$TARMAC" src vendor | |
| 178 | + if "${SCP_MAC[@]}" "$TARMAC" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tar.gz"; then | |
| 179 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tar.gz" || true | |
| 180 | + # Build straight from the uploaded tree. The star is backslash-escaped: | |
| 181 | + # the remote login shell is zsh and an unmatched glob aborts it (bc). | |
| 182 | + for slice in arm64 x86_64; do | |
| 183 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | |
| 184 | + "cd '$MAC_DIR' && SRCS=\$(find src -name \*.c; find vendor -name \*.c) && clang -O2 -std=c99 -Wall -Wextra -D_DARWIN_C_SOURCE -I src -I vendor -arch $slice -o $ID.$slice \$SRCS" \ | |
| 185 | + 2>/dev/null; then | |
| 186 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | |
| 187 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | |
| 188 | + else | |
| 189 | + echo " warn: macos-$slice build failed on $MAC_HOST" | |
| 190 | + fi | |
| 191 | + done | |
| 192 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" 2>/dev/null || true | |
| 193 | + else | |
| 194 | + echo " warn: mac scp failed" | |
| 195 | + fi | |
| 196 | + else | |
| 197 | + echo " warn: mac host unreachable" | |
| 198 | + fi | |
| 199 | +else | |
| 200 | + echo " skip macOS legs (set MAC_HOST/MAC_USER/MAC_PASS to include them)" | |
| 201 | +fi | |
| 202 | + | |
| 203 | +# ---------------------------------------------------------------- 3. package | |
| 204 | +say "3/7 package" | |
| 205 | + | |
| 206 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | |
| 207 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | |
| 208 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | |
| 209 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | |
| 210 | + | |
| 211 | +target_meta() { # target_meta <key> <file> <format> <relpath> <name> | |
| 212 | + local key="$1" file="$2" fmt="$3" rel="$4" name="$5" | |
| 213 | + [ -f "$file" ] || return 0 | |
| 214 | + local sha size | |
| 215 | + sha=$(sha256sum "$file" | awk '{print $1}') | |
| 216 | + size=$(wc -c < "$file" | tr -d ' ') | |
| 217 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | |
| 218 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | |
| 219 | +} | |
| 220 | + | |
| 221 | +{ | |
| 222 | + printf '{\n' | |
| 223 | + printf ' "slug": "%s",\n' "$SLUG" | |
| 224 | + printf ' "id": "%s",\n' "$ID" | |
| 225 | + printf ' "name": "seqthink",\n' | |
| 226 | + printf ' "desc": "Thought chains",\n' | |
| 227 | + printf ' "title": "Sequential Thinking",\n' | |
| 228 | + printf ' "summary": "Zero-dependency sequential-thinking MCP connector for your node. Serves the sequentialthinking tool over MCP stdio with revision and branching semantics, snapshots accepted thought chains to its own connector directory, and ships a bot-themed chain viewer.",\n' | |
| 229 | + printf ' "category": "devtools",\n' | |
| 230 | + printf ' "version": "%s",\n' "$VERSION" | |
| 231 | + printf ' "license": "MIT",\n' | |
| 232 | + printf ' "trust_notice": "Executes native C code on your node. Serves the sequentialthinking MCP tool over stdio and writes thought-chain snapshots only inside its own connector directory. It opens no network connection of any kind.",\n' | |
| 233 | + printf ' "capabilities": ["mcp_stdio_server", "local_state_write", "no_network"],\n' | |
| 234 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | |
| 235 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | |
| 236 | + printf ' "git_commit": "%s",\n' "$COMMIT" | |
| 237 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 238 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | |
| 239 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -I src -I vendor -o %s src/%s.c vendor/yyjson.c",\n' "$ID" "$ID" | |
| 240 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -I src -I vendor -o %s.exe src/%s.c vendor/yyjson.c",\n' "$ID" "$ID" | |
| 241 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | |
| 242 | + printf ' "targets": {\n' | |
| 243 | + first=1 | |
| 244 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | |
| 245 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" "$ID" | |
| 246 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" "$ID" | |
| 247 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" "$ID" | |
| 248 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" "$ID" | |
| 249 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" "$ID" | |
| 250 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" "$ID" | |
| 251 | + printf '\n }\n}\n' | |
| 252 | +} > "$STAGE/manifest.json" | |
| 253 | + | |
| 254 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | |
| 255 | + || die "generated manifest.json is not valid JSON" | |
| 256 | +echo " manifest.json ok" | |
| 257 | + | |
| 258 | +# SHA256SUMS — relative paths, exactly as published | |
| 259 | +( cd "$STAGE" | |
| 260 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | |
| 261 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | |
| 262 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | |
| 263 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | |
| 264 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | |
| 265 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | |
| 266 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | |
| 267 | + true ) > "$STAGE/SHA256SUMS" | |
| 268 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | |
| 269 | + | |
| 270 | +# ---------------------------------------------------------------- 4. stage | |
| 271 | +say "4/7 stage tree" | |
| 272 | +PKG="$STAGE/pkg" | |
| 273 | +mkdir -p "$PKG/linux-x86_64" "$PKG/linux-x86_64-musl" "$PKG/linux-arm64-musl" \ | |
| 274 | + "$PKG/macos-arm64" "$PKG/macos-x86_64" "$PKG/windows-x86_64" | |
| 275 | +cp -f "$STAGE/$ID" "$PKG/linux-x86_64/$ID" | |
| 276 | +[ -f "$STAGE/$ID.musl" ] && cp -f "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID" | |
| 277 | +[ -f "$STAGE/$ID.arm64" ] && cp -f "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID" | |
| 278 | +[ -f "$STAGE/$ID.macos-arm64" ]&& cp -f "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID" | |
| 279 | +[ -f "$STAGE/$ID.macos-x86_64" ]&&cp -f "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID" | |
| 280 | +[ -f "$STAGE/$ID.exe" ] && cp -f "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe" | |
| 281 | +cp -f "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | |
| 282 | +chmod +x "$PKG"/*/$ID 2>/dev/null || true | |
| 283 | +find "$PKG" -type f | sed 's/^/ /' | |
| 284 | + | |
| 285 | +if [ "$DRY_RUN" -eq 1 ]; then | |
| 286 | + say "dry run — staged at $STAGE/pkg (kept for inspection)" | |
| 287 | + trap - EXIT | |
| 288 | + exit 0 | |
| 289 | +fi | |
| 290 | + | |
| 291 | +# ---------------------------------------------------------------- 5. upload | |
| 292 | +say "5/7 upload" | |
| 293 | + | |
| 294 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set — cannot upload" | |
| 295 | +SSH=(ssh -o StrictHostKeyChecking=no) | |
| 296 | +SCP=(scp -o StrictHostKeyChecking=no) | |
| 297 | +if [ -n "$DIST_PASS" ]; then | |
| 298 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | |
| 299 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | |
| 300 | +fi | |
| 301 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | |
| 302 | + | |
| 303 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | |
| 304 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | |
| 305 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | |
| 306 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | |
| 307 | +# OpenSSH 9 refuses to scp a bare "." source. | |
| 308 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | |
| 309 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | |
| 310 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | |
| 311 | + || die "remote extract failed" | |
| 312 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | |
| 313 | + | |
| 314 | +# latest.json = copy of this version's manifest | |
| 315 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | |
| 316 | + || die "latest.json update failed" | |
| 317 | +echo " updated bot-plugins/$SLUG/latest.json" | |
| 318 | + | |
| 319 | +# index.json — merge, preserving every sibling <slug>/latest.json | |
| 320 | +say "index.json merge" | |
| 321 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | |
| 322 | +import json, os, sys, glob | |
| 323 | +slug = sys.argv[1] | |
| 324 | +entries = {} | |
| 325 | +for p in sorted(glob.glob('*/latest.json')): | |
| 326 | + s = os.path.dirname(p) | |
| 327 | + try: | |
| 328 | + entries[s] = json.load(open(p)) | |
| 329 | + except Exception: | |
| 330 | + pass | |
| 331 | +index = { | |
| 332 | + 'ok': True, | |
| 333 | + 'service': 'bot-plugins-dist', | |
| 334 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | |
| 335 | + 'count': len(entries), | |
| 336 | + 'slugs': sorted(entries), | |
| 337 | + 'plugins': [entries[k] for k in sorted(entries)], | |
| 338 | +} | |
| 339 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | |
| 340 | +os.replace('index.json.tmp', 'index.json') | |
| 341 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | |
| 342 | +PY" || die "index.json merge failed" | |
| 343 | + | |
| 344 | +# ---------------------------------------------------------------- 6. mirror | |
| 345 | +say "6/7 plugingit mirror" | |
| 346 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | |
| 347 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | |
| 348 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://x-access-token:${TOKEN}@|") | |
| 349 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | |
| 350 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | |
| 351 | + echo " mirrored to $PLUGINGIT_REMOTE" | |
| 352 | +else | |
| 353 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | |
| 354 | +fi | |
| 355 | + | |
| 356 | +# ---------------------------------------------------------------- 7. verify | |
| 357 | +say "7/7 verify" | |
| 358 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | |
| 359 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | |
| 360 | +if [ "$CODE" = "200" ]; then | |
| 361 | + python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK — %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \ | |
| 362 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | |
| 363 | +else | |
| 364 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | |
| 365 | +fi | |
| 366 | + | |
| 367 | +printf '\n\033[1mrelease complete\033[0m\n' | |
| 368 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | |
| 369 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | 1 | new file mode 100644 |
| index 0000000..0dd243b | ||
| --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | ||
| 1 | +/* | |
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | |
| 3 | + * | |
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | |
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | |
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | |
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | |
| 8 | + * localStorage key, same prepaint order. | |
| 9 | + * | |
| 10 | + * Three rules, and nothing else: | |
| 11 | + * | |
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | |
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | |
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | |
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | |
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | |
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | |
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | |
| 19 | + * it was already open when the bot changed theme. | |
| 20 | + * | |
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | |
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | |
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | |
| 24 | + * are var() references, one definition covers both themes. | |
| 25 | + * | |
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 27 | + */ | |
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | |
| 29 | +#define SX_BOT_THEME_PLUGIN_H | |
| 30 | + | |
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | |
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | |
| 33 | +#define SX_BOT_THEME_TOKENS \ | |
| 34 | +":root{color-scheme:dark;" \ | |
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | |
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | |
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | |
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | |
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | |
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | |
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | |
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | |
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | |
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | |
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | |
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | |
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | |
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | |
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | |
| 50 | +"}" \ | |
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | |
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 58 | + "--accent-dim:#0066d6;" \ | |
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 62 | + "color-scheme:light}}" \ | |
| 63 | +"html[data-theme=light]{" \ | |
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | |
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | |
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | |
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | |
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | |
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | |
| 70 | + "--accent-dim:#0066d6;" \ | |
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | |
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | |
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | |
| 74 | + "color-scheme:light}" \ | |
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | |
| 76 | +"*{box-sizing:border-box}" \ | |
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | |
| 78 | + "-webkit-font-smoothing:antialiased}" \ | |
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | |
| 80 | +"button:active{transform:scale(.98)}" \ | |
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | |
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | |
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | |
| 84 | +" * hides its own back link and its own toggle. */" \ | |
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | |
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | |
| 87 | + | |
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | |
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | |
| 90 | + * html.embedded so the embed rules apply before first paint. */ | |
| 91 | +#define SX_BOT_THEME_PREPAINT \ | |
| 92 | +"<script>(function(){var t='';" \ | |
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | |
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | |
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | |
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | |
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 99 | +"})();</script>\n" | |
| 100 | + | |
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | |
| 102 | + * at startup in case it changed while this page was already open. Fires the | |
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | |
| 104 | + * re-skin themselves from one listener. */ | |
| 105 | +#define SX_BOT_THEME_HANDOFF \ | |
| 106 | +"<script>(function(){" \ | |
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | |
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | |
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | |
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | |
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | |
| 112 | +"window.sxApplyTheme=apply;" \ | |
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | |
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | |
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | |
| 116 | +"})();</script>\n" | |
| 117 | + | |
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | |
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | |
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | |
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | |
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | |
| 123 | + | |
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | |
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | |
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | |
| 127 | +"})();</script>\n" | |
| 128 | + | |
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..abc92d1 | ||
| --- /dev/null | ||
| +++ b/src/plugin_seqthink.c | ||
| @@ -0,0 +1,1798 @@ | ||
| 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: a | |
| 17 | + * thought-chain timeline (revisions, branches, progress) built from the | |
| 18 | + * snapshots the --mcp leg persists. | |
| 19 | + * | |
| 20 | + * The tool is a clean-room C port of the behaviour of modelcontextprotocol | |
| 21 | + * `servers/src/sequentialthinking` (the sequential-thinking MCP server): | |
| 22 | + * identical parameter validation and error strings, the same "raise | |
| 23 | + * totalThoughts when thoughtNumber exceeds it" rule, a per-connection thought | |
| 24 | + * history with a MAX_THOUGHT_HISTORY cap (default 1000, oldest evicted, its | |
| 25 | + * branch shrunk with it, an emptied branch dropped), branch keys created on | |
| 26 | + * the first thought that carries BOTH branchFromThought and branchId, and the | |
| 27 | + * exact five-field result {thoughtNumber,totalThoughts,nextThoughtNeeded, | |
| 28 | + * branches,thoughtHistoryLength} returned as content[0].text AND as | |
| 29 | + * structuredContent. Validation failures come back as | |
| 30 | + * {"error":...,"status":"failed"} with isError:true, exactly as upstream. | |
| 31 | + * | |
| 32 | + * Beyond upstream: every accepted thought also snapshots its chain to | |
| 33 | + * <state_dir>/chains.json (POSIX: /workspace/.scorpiox/connectors/ | |
| 34 | + * plugin_seqthink when /workspace exists, else $HOME/.scorpiox/connectors/ | |
| 35 | + * plugin_seqthink; Windows: %LOCALAPPDATA%\scorpiox\connectors\plugin_seqthink; | |
| 36 | + * SEQTHINK_STATE_DIR overrides for tests) so the HTML UI can inspect recent | |
| 37 | + * reasoning without holding the MCP process open. Writes are read-modify- | |
| 38 | + * merge on chain id and go .tmp -> rename(), so a crash never leaves a | |
| 39 | + * half-written chains.json. The file is bounded (<= 50 chains, each <= 1000 | |
| 40 | + * thoughts). DISABLE_THOUGHT_LOGGING=1|true (upstream parity) silences both | |
| 41 | + * the stderr line and the persistence. | |
| 42 | + * | |
| 43 | + * Zero dependencies beyond the vendored yyjson: no TLS, no sockets, no | |
| 44 | + * popen. The only files it ever touches live under its own state directory. | |
| 45 | + * | |
| 46 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | |
| 47 | + */ | |
| 48 | + | |
| 49 | +/* Must come before every include: MinGW defaults _WIN32_WINNT to 0x502; | |
| 50 | + * Apple needs _DARWIN_C_SOURCE under -std=c99; MinGW needs its printf for %zu. */ | |
| 51 | +#ifndef _WIN32 | |
| 52 | +# ifndef _POSIX_C_SOURCE | |
| 53 | +# define _POSIX_C_SOURCE 200809L | |
| 54 | +# endif | |
| 55 | +# ifndef _DEFAULT_SOURCE | |
| 56 | +# define _DEFAULT_SOURCE 1 | |
| 57 | +# endif | |
| 58 | +#endif | |
| 59 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | |
| 60 | +# define _WIN32_WINNT 0x0601 | |
| 61 | +#endif | |
| 62 | +#if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) | |
| 63 | +# define _DARWIN_C_SOURCE 1 | |
| 64 | +#endif | |
| 65 | +#if defined(__MINGW32__) && !defined(__USE_MINGW_ANSI_STDIO) | |
| 66 | +# define __USE_MINGW_ANSI_STDIO 1 | |
| 67 | +#endif | |
| 68 | + | |
| 69 | +#include <stdio.h> | |
| 70 | +#include <stdlib.h> | |
| 71 | +#include <string.h> | |
| 72 | +#include <ctype.h> | |
| 73 | +#include <time.h> | |
| 74 | +#include <errno.h> | |
| 75 | +#include <limits.h> | |
| 76 | +#include <stdarg.h> | |
| 77 | + | |
| 78 | +#if defined(_WIN32) | |
| 79 | +# include <windows.h> | |
| 80 | +# include <io.h> | |
| 81 | +# include <direct.h> | |
| 82 | +# include <string.h> | |
| 83 | +# ifndef strncasecmp | |
| 84 | +# define strncasecmp _strnicmp | |
| 85 | +# endif | |
| 86 | +# ifndef _SSIZE_T_DEFINED | |
| 87 | +# define _SSIZE_T_DEFINED | |
| 88 | + typedef long long ssize_t; | |
| 89 | +# endif | |
| 90 | +#else | |
| 91 | +# include <unistd.h> | |
| 92 | +# include <strings.h> | |
| 93 | +# include <sys/stat.h> | |
| 94 | +# include <sys/types.h> | |
| 95 | +#endif | |
| 96 | +#include <sys/stat.h> | |
| 97 | +#include <sys/types.h> | |
| 98 | + | |
| 99 | +#include "yyjson.h" | |
| 100 | +#include "bot_theme_plugin.h" | |
| 101 | +#include "ui_html.h" | |
| 102 | + | |
| 103 | +#define PLUGIN_SLUG "seqthink" | |
| 104 | +#define PLUGIN_ID "plugin_seqthink" | |
| 105 | +#define PLUGIN_VER "1.0.0" | |
| 106 | +#define PLUGIN_NAME "seqthink" | |
| 107 | +#define PLUGIN_DESC "Thought chains" | |
| 108 | + | |
| 109 | +#define MAX_CHAINS 50 /* chains kept in chains.json */ | |
| 110 | +#define MAX_THOUGHTS_EACH 1000 /* thoughts kept per chain in the file */ | |
| 111 | +#define DEFAULT_MAX_HIST 1000 /* upstream DEFAULT_MAX_THOUGHT_HISTORY */ | |
| 112 | +#define THOUGHT_MAX 65536 /* longest accepted thought text */ | |
| 113 | +#define BRANCHID_MAX 128 | |
| 114 | +#define REQ_MAX (2u * 1024u * 1024u) | |
| 115 | + | |
| 116 | +#if defined(_WIN32) | |
| 117 | +# define sx_mkdir(p) _mkdir(p) | |
| 118 | +# define SX_PATHSEP '\\' | |
| 119 | +#else | |
| 120 | +# define sx_mkdir(p) mkdir((p), 0755) | |
| 121 | +# define SX_PATHSEP '/' | |
| 122 | +#endif | |
| 123 | + | |
| 124 | +/* ------------------------------------------------------------------ */ | |
| 125 | +/* Small helpers */ | |
| 126 | +/* ------------------------------------------------------------------ */ | |
| 127 | + | |
| 128 | +static void *sx_malloc(size_t n) | |
| 129 | +{ | |
| 130 | + void *p = malloc(n ? n : 1); | |
| 131 | + if (!p) { | |
| 132 | + fputs("out of memory\n", stderr); | |
| 133 | + exit(1); | |
| 134 | + } | |
| 135 | + return p; | |
| 136 | +} | |
| 137 | + | |
| 138 | +static char *sx_strdup(const char *s) | |
| 139 | +{ | |
| 140 | + size_t n; | |
| 141 | + char *p; | |
| 142 | + if (!s) s = ""; | |
| 143 | + n = strlen(s) + 1; | |
| 144 | + p = (char *)sx_malloc(n); | |
| 145 | + memcpy(p, s, n); | |
| 146 | + return p; | |
| 147 | +} | |
| 148 | + | |
| 149 | +typedef struct { | |
| 150 | + char *p; | |
| 151 | + size_t n; | |
| 152 | + size_t cap; | |
| 153 | +} buf_t; | |
| 154 | + | |
| 155 | +static void buf_init(buf_t *b) { b->p = NULL; b->n = 0; b->cap = 0; } | |
| 156 | + | |
| 157 | +static void buf_reserve(buf_t *b, size_t extra) | |
| 158 | +{ | |
| 159 | + size_t want = b->n + extra + 1; | |
| 160 | + if (want <= b->cap) return; | |
| 161 | + { | |
| 162 | + size_t cap = b->cap ? b->cap : 256; | |
| 163 | + while (cap < want) cap *= 2; | |
| 164 | + b->p = (char *)realloc(b->p, cap); | |
| 165 | + if (!b->p) { fputs("out of memory\n", stderr); exit(1); } | |
| 166 | + b->cap = cap; | |
| 167 | + } | |
| 168 | +} | |
| 169 | + | |
| 170 | +static void buf_add(buf_t *b, const char *s, size_t n) | |
| 171 | +{ | |
| 172 | + buf_reserve(b, n); | |
| 173 | + memcpy(b->p + b->n, s, n); | |
| 174 | + b->n += n; | |
| 175 | + b->p[b->n] = '\0'; | |
| 176 | +} | |
| 177 | + | |
| 178 | +/* Append a NUL-terminated literal; the length is computed, never hand-typed. */ | |
| 179 | +static void buf_str(buf_t *b, const char *s) | |
| 180 | +{ | |
| 181 | + if (s) buf_add(b, s, strlen(s)); | |
| 182 | +} | |
| 183 | + | |
| 184 | +static void buf_addf(buf_t *b, const char *fmt, ...) | |
| 185 | +{ | |
| 186 | + va_list ap; | |
| 187 | + int need; | |
| 188 | + char tmp[512]; | |
| 189 | + va_start(ap, fmt); | |
| 190 | + need = vsnprintf(tmp, sizeof tmp, fmt, ap); | |
| 191 | + va_end(ap); | |
| 192 | + if (need < 0) return; | |
| 193 | + if ((size_t)need < sizeof tmp) { buf_add(b, tmp, (size_t)need); return; } | |
| 194 | + { | |
| 195 | + char *big = (char *)sx_malloc((size_t)need + 1); | |
| 196 | + va_start(ap, fmt); | |
| 197 | + vsnprintf(big, (size_t)need + 1, fmt, ap); | |
| 198 | + va_end(ap); | |
| 199 | + buf_add(b, big, (size_t)need); | |
| 200 | + free(big); | |
| 201 | + } | |
| 202 | +} | |
| 203 | + | |
| 204 | +static void buf_free(buf_t *b) { free(b->p); buf_init(b); } | |
| 205 | + | |
| 206 | +/* getline() is POSIX; MinGW-w64 ships one but msvcrt's varies by release. A | |
| 207 | + * 40-line local version keeps the --mcp loop identical on every target. */ | |
| 208 | +#if defined(_WIN32) | |
| 209 | +static ssize_t sx_getline(char **lineptr, size_t *n, FILE *stream) | |
| 210 | +{ | |
| 211 | + size_t len = 0, cap = *n ? *n : 128; | |
| 212 | + char *buf = *lineptr; | |
| 213 | + int c; | |
| 214 | + if (!buf) { | |
| 215 | + buf = (char *)malloc(cap); | |
| 216 | + if (!buf) return -1; | |
| 217 | + *lineptr = buf; | |
| 218 | + *n = cap; | |
| 219 | + } | |
| 220 | + c = fgetc(stream); | |
| 221 | + if (c == EOF) return -1; | |
| 222 | + while (c != EOF) { | |
| 223 | + if (len + 2 > cap) { | |
| 224 | + char *nb; | |
| 225 | + cap *= 2; | |
| 226 | + nb = (char *)realloc(buf, cap); | |
| 227 | + if (!nb) return -1; | |
| 228 | + buf = nb; | |
| 229 | + *lineptr = buf; | |
| 230 | + *n = cap; | |
| 231 | + } | |
| 232 | + buf[len++] = (char)c; | |
| 233 | + if (c == '\n') break; | |
| 234 | + c = fgetc(stream); | |
| 235 | + } | |
| 236 | + buf[len] = '\0'; | |
| 237 | + return (ssize_t)len; | |
| 238 | +} | |
| 239 | +# define getline(a, b, c) sx_getline((a), (b), (c)) | |
| 240 | +#endif | |
| 241 | + | |
| 242 | +/* JSON-escape s into b (with surrounding quotes). */ | |
| 243 | +static void json_escape_buf(buf_t *b, const char *s) | |
| 244 | +{ | |
| 245 | + const unsigned char *p = (const unsigned char *)(s ? s : ""); | |
| 246 | + buf_str(b, "\""); | |
| 247 | + for (; *p; p++) { | |
| 248 | + switch (*p) { | |
| 249 | + case '"': buf_str(b, "\\\""); break; | |
| 250 | + case '\\': buf_str(b, "\\\\"); break; | |
| 251 | + case '\n': buf_str(b, "\\n"); break; | |
| 252 | + case '\r': buf_str(b, "\\r"); break; | |
| 253 | + case '\t': buf_str(b, "\\t"); break; | |
| 254 | + default: | |
| 255 | + if (*p < 0x20) buf_addf(b, "\\u%04x", (unsigned)*p); | |
| 256 | + else buf_add(b, (const char *)p, 1); | |
| 257 | + } | |
| 258 | + } | |
| 259 | + buf_str(b, "\""); | |
| 260 | +} | |
| 261 | + | |
| 262 | +static void json_escape(FILE *out, const char *s) | |
| 263 | +{ | |
| 264 | + buf_t b; | |
| 265 | + buf_init(&b); | |
| 266 | + json_escape_buf(&b, s); | |
| 267 | + if (b.p) fwrite(b.p, 1, b.n, out); | |
| 268 | + buf_free(&b); | |
| 269 | +} | |
| 270 | + | |
| 271 | +/* Percent-decode in place for query values (the node hands QUERY_STRING raw). */ | |
| 272 | +static int hexval(int c) | |
| 273 | +{ | |
| 274 | + if (c >= '0' && c <= '9') return c - '0'; | |
| 275 | + if (c >= 'a' && c <= 'f') return c - 'a' + 10; | |
| 276 | + if (c >= 'A' && c <= 'F') return c - 'A' + 10; | |
| 277 | + return -1; | |
| 278 | +} | |
| 279 | + | |
| 280 | +static void url_decode(char *s) | |
| 281 | +{ | |
| 282 | + char *d = s; | |
| 283 | + while (*s) { | |
| 284 | + if (*s == '%' && hexval((unsigned char)s[1]) >= 0 && | |
| 285 | + hexval((unsigned char)s[2]) >= 0) { | |
| 286 | + *d++ = (char)(hexval((unsigned char)s[1]) * 16 + | |
| 287 | + hexval((unsigned char)s[2])); | |
| 288 | + s += 3; | |
| 289 | + } else if (*s == '+') { | |
| 290 | + *d++ = ' '; | |
| 291 | + s++; | |
| 292 | + } else { | |
| 293 | + *d++ = *s++; | |
| 294 | + } | |
| 295 | + } | |
| 296 | + *d = '\0'; | |
| 297 | +} | |
| 298 | + | |
| 299 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | |
| 300 | +{ | |
| 301 | + size_t klen; | |
| 302 | + const char *p; | |
| 303 | + if (!qs || !key || !out || outsz == 0) return 0; | |
| 304 | + out[0] = '\0'; | |
| 305 | + klen = strlen(key); | |
| 306 | + p = qs; | |
| 307 | + while (p && *p) { | |
| 308 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | |
| 309 | + size_t i = 0; | |
| 310 | + p += klen + 1; | |
| 311 | + while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; | |
| 312 | + out[i] = '\0'; | |
| 313 | + url_decode(out); | |
| 314 | + return 1; | |
| 315 | + } | |
| 316 | + p = strchr(p, '&'); | |
| 317 | + if (p) p++; | |
| 318 | + } | |
| 319 | + return 0; | |
| 320 | +} | |
| 321 | + | |
| 322 | +/* ------------------------------------------------------------------ */ | |
| 323 | +/* Node authentication (X-Bot-Password | Bearer | ?pwd=). --meta, */ | |
| 324 | +/* --mcp and the HTML page never call this; every JSON action does. */ | |
| 325 | +/* ------------------------------------------------------------------ */ | |
| 326 | + | |
| 327 | +static void require_node_auth(void) | |
| 328 | +{ | |
| 329 | + const char *np = getenv("BOT_PASSWORD"); | |
| 330 | + const char *xp, *auth; | |
| 331 | + char qpwd[256] = {0}; | |
| 332 | + const char *qs; | |
| 333 | + | |
| 334 | + if (!np || !*np) return; /* open node: no gate */ | |
| 335 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | |
| 336 | + if (xp && strcmp(xp, np) == 0) return; | |
| 337 | + auth = getenv("HTTP_AUTHORIZATION"); | |
| 338 | + if (auth) { | |
| 339 | + while (*auth == ' ') auth++; | |
| 340 | + if (strncasecmp(auth, "Bearer ", 7) == 0) { | |
| 341 | + auth += 7; | |
| 342 | + while (*auth == ' ') auth++; | |
| 343 | + if (strcmp(auth, np) == 0) return; | |
| 344 | + } | |
| 345 | + } | |
| 346 | + qs = getenv("QUERY_STRING"); | |
| 347 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && | |
| 348 | + strcmp(qpwd, np) == 0) | |
| 349 | + return; | |
| 350 | + | |
| 351 | + fputs("Status: 401 Unauthorized\r\n" | |
| 352 | + "Content-Type: application/json; charset=utf-8\r\n\r\n" | |
| 353 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | |
| 354 | + exit(0); | |
| 355 | +} | |
| 356 | + | |
| 357 | +/* ------------------------------------------------------------------ */ | |
| 358 | +/* State directory + chains.json */ | |
| 359 | +/* ------------------------------------------------------------------ */ | |
| 360 | + | |
| 361 | +static void state_dir(char *out, size_t outsz) | |
| 362 | +{ | |
| 363 | + const char *env = getenv("SEQTHINK_STATE_DIR"); | |
| 364 | + struct stat st; | |
| 365 | + | |
| 366 | + if (env && *env) { snprintf(out, outsz, "%s", env); return; } | |
| 367 | +#ifndef _WIN32 | |
| 368 | + if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode) && | |
| 369 | + access("/workspace", W_OK) == 0) { | |
| 370 | + snprintf(out, outsz, "/workspace/.scorpiox/connectors/" PLUGIN_ID); | |
| 371 | + return; | |
| 372 | + } | |
| 373 | +#endif | |
| 374 | +#if defined(_WIN32) | |
| 375 | + { | |
| 376 | + const char *la = getenv("LOCALAPPDATA"); | |
| 377 | + if (la && *la) { | |
| 378 | + snprintf(out, outsz, "%s\\scorpiox\\connectors\\" PLUGIN_ID, la); | |
| 379 | + return; | |
| 380 | + } | |
| 381 | + } | |
| 382 | +#endif | |
| 383 | + { | |
| 384 | + const char *home = getenv("HOME"); | |
| 385 | + if (!home || !*home) home = "/root"; | |
| 386 | + snprintf(out, outsz, "%s/.scorpiox/connectors/" PLUGIN_ID, home); | |
| 387 | + } | |
| 388 | +} | |
| 389 | + | |
| 390 | +/* state_dir_name exposes only the leaf directory name for the UI chip (no | |
| 391 | + * absolute path, no home directory name leaks into the browser). */ | |
| 392 | +static void state_dir_name(char *out, size_t outsz) | |
| 393 | +{ | |
| 394 | + char dir[1000]; | |
| 395 | + char *slash; | |
| 396 | + size_t i; | |
| 397 | + state_dir(dir, sizeof dir); | |
| 398 | + slash = strrchr(dir, '/'); | |
| 399 | + if (!slash) slash = strrchr(dir, '\\'); | |
| 400 | + { | |
| 401 | + const char *s = slash ? slash + 1 : dir; | |
| 402 | + for (i = 0; s[i] && i + 1 < outsz; i++) out[i] = s[i]; | |
| 403 | + out[i] = '\0'; | |
| 404 | + } | |
| 405 | +} | |
| 406 | + | |
| 407 | +static int mkdirs(const char *path) | |
| 408 | +{ | |
| 409 | + char buf[1200]; | |
| 410 | + size_t i, n; | |
| 411 | + struct stat st; | |
| 412 | + snprintf(buf, sizeof buf, "%s", path); | |
| 413 | + n = strlen(buf); | |
| 414 | + for (i = 1; i < n; i++) { | |
| 415 | + if (buf[i] == '/' || buf[i] == '\\') { | |
| 416 | + char save = buf[i]; | |
| 417 | + buf[i] = '\0'; | |
| 418 | + if (i > 2) sx_mkdir(buf); | |
| 419 | + buf[i] = save; | |
| 420 | + } | |
| 421 | + } | |
| 422 | + sx_mkdir(buf); | |
| 423 | + return stat(buf, &st) == 0 && S_ISDIR(st.st_mode); | |
| 424 | +} | |
| 425 | + | |
| 426 | +static void chains_path(char *out, size_t outsz) | |
| 427 | +{ | |
| 428 | + char dir[1000]; | |
| 429 | + state_dir(dir, sizeof dir); | |
| 430 | + snprintf(out, outsz, "%s%cchains.json", dir, SX_PATHSEP); | |
| 431 | +} | |
| 432 | + | |
| 433 | +static char *read_file(const char *path, size_t *lenp) | |
| 434 | +{ | |
| 435 | + FILE *f; | |
| 436 | + long sz; | |
| 437 | + char *txt; | |
| 438 | + size_t got; | |
| 439 | + f = fopen(path, "rb"); | |
| 440 | + if (!f) return NULL; | |
| 441 | + fseek(f, 0, SEEK_END); | |
| 442 | + sz = ftell(f); | |
| 443 | + fseek(f, 0, SEEK_SET); | |
| 444 | + if (sz < 0 || sz > 8 * 1024 * 1024) { fclose(f); return NULL; } | |
| 445 | + txt = (char *)sx_malloc((size_t)sz + 1); | |
| 446 | + got = fread(txt, 1, (size_t)sz, f); | |
| 447 | + txt[got] = '\0'; | |
| 448 | + fclose(f); | |
| 449 | + if (lenp) *lenp = got; | |
| 450 | + return txt; | |
| 451 | +} | |
| 452 | + | |
| 453 | +static int write_file_atomic(const char *path, const char *data, size_t len) | |
| 454 | +{ | |
| 455 | + char tmp[1300]; | |
| 456 | + FILE *f; | |
| 457 | + snprintf(tmp, sizeof tmp, "%s.tmp", path); | |
| 458 | + f = fopen(tmp, "wb"); | |
| 459 | + if (!f) return 0; | |
| 460 | + if (len && fwrite(data, 1, len, f) != len) { fclose(f); remove(tmp); return 0; } | |
| 461 | + if (fflush(f) != 0) { fclose(f); remove(tmp); return 0; } | |
| 462 | + fclose(f); | |
| 463 | + if (rename(tmp, path) != 0) { remove(tmp); return 0; } | |
| 464 | + return 1; | |
| 465 | +} | |
| 466 | + | |
| 467 | +/* ------------------------------------------------------------------ */ | |
| 468 | +/* Tool model */ | |
| 469 | +/* ------------------------------------------------------------------ */ | |
| 470 | + | |
| 471 | +typedef struct { | |
| 472 | + char *thought; /* heap, never NULL after validation */ | |
| 473 | + long long thought_number; | |
| 474 | + long long total_thoughts; | |
| 475 | + long long revises; /* 0 = absent */ | |
| 476 | + long long branch_from; /* 0 = absent */ | |
| 477 | + char *branch_id; /* NULL = absent */ | |
| 478 | + int is_revision; | |
| 479 | + int next_needed; | |
| 480 | + int needs_more; | |
| 481 | +} thought_t; | |
| 482 | + | |
| 483 | +typedef struct { | |
| 484 | + thought_t *v; | |
| 485 | + size_t n, cap; | |
| 486 | +} tvec_t; | |
| 487 | + | |
| 488 | +static void tvec_push(tvec_t *h, const thought_t *t) | |
| 489 | +{ | |
| 490 | + if (h->n == h->cap) { | |
| 491 | + h->cap = h->cap ? h->cap * 2 : 16; | |
| 492 | + h->v = (thought_t *)realloc(h->v, h->cap * sizeof *h->v); | |
| 493 | + if (!h->v) { fputs("out of memory\n", stderr); exit(1); } | |
| 494 | + } | |
| 495 | + h->v[h->n++] = *t; | |
| 496 | +} | |
| 497 | + | |
| 498 | +static void thought_free(thought_t *t) | |
| 499 | +{ | |
| 500 | + free(t->thought); | |
| 501 | + free(t->branch_id); | |
| 502 | + memset(t, 0, sizeof *t); | |
| 503 | +} | |
| 504 | + | |
| 505 | +/* Branch registry: insertion-ordered keys with per-branch thought counts. */ | |
| 506 | +typedef struct { | |
| 507 | + char *key; | |
| 508 | + size_t count; | |
| 509 | +} branch_t; | |
| 510 | + | |
| 511 | +typedef struct { | |
| 512 | + branch_t *v; | |
| 513 | + size_t n, cap; | |
| 514 | +} bvec_t; | |
| 515 | + | |
| 516 | +static int bvec_find(const bvec_t *b, const char *key) | |
| 517 | +{ | |
| 518 | + size_t i; | |
| 519 | + for (i = 0; i < b->n; i++) | |
| 520 | + if (strcmp(b->v[i].key, key) == 0) return (int)i; | |
| 521 | + return -1; | |
| 522 | +} | |
| 523 | + | |
| 524 | +static void bvec_create(bvec_t *b, const char *key) | |
| 525 | +{ | |
| 526 | + if (bvec_find(b, key) >= 0) return; | |
| 527 | + if (b->n == b->cap) { | |
| 528 | + b->cap = b->cap ? b->cap * 2 : 8; | |
| 529 | + b->v = (branch_t *)realloc(b->v, b->cap * sizeof *b->v); | |
| 530 | + if (!b->v) { fputs("out of memory\n", stderr); exit(1); } | |
| 531 | + } | |
| 532 | + b->v[b->n].key = sx_strdup(key); | |
| 533 | + b->v[b->n].count = 0; | |
| 534 | + b->n++; | |
| 535 | +} | |
| 536 | + | |
| 537 | +static void bvec_record(bvec_t *b, const char *key) | |
| 538 | +{ | |
| 539 | + int i = bvec_find(b, key); | |
| 540 | + if (i < 0) { bvec_create(b, key); i = (int)b->n - 1; } | |
| 541 | + b->v[i].count++; | |
| 542 | +} | |
| 543 | + | |
| 544 | +static void bvec_evict(bvec_t *b, const char *key) | |
| 545 | +{ | |
| 546 | + int i = bvec_find(b, key); | |
| 547 | + if (i < 0) return; | |
| 548 | + if (b->v[i].count > 0) b->v[i].count--; | |
| 549 | + if (b->v[i].count == 0) { /* upstream: an emptied branch is dropped */ | |
| 550 | + free(b->v[i].key); | |
| 551 | + memmove(&b->v[i], &b->v[i + 1], (b->n - (size_t)i - 1) * sizeof *b->v); | |
| 552 | + b->n--; | |
| 553 | + } | |
| 554 | +} | |
| 555 | + | |
| 556 | +static long long read_max_history(void) | |
| 557 | +{ | |
| 558 | + const char *raw = getenv("MAX_THOUGHT_HISTORY"); | |
| 559 | + const char *p; | |
| 560 | + long long v; | |
| 561 | + if (!raw) return DEFAULT_MAX_HIST; | |
| 562 | + while (*raw == ' ' || *raw == '\t') raw++; | |
| 563 | + if (!*raw) return DEFAULT_MAX_HIST; | |
| 564 | + for (p = raw; *p; p++) if (!isdigit((unsigned char)*p)) break; | |
| 565 | + if (*p != '\0' && !(p == raw + strlen(raw))) { /* trailing junk */ } | |
| 566 | + for (p = raw; *p; p++) { | |
| 567 | + if (!isdigit((unsigned char)*p)) { | |
| 568 | + fprintf(stderr, "MAX_THOUGHT_HISTORY must be a positive integer, " | |
| 569 | + "got \"%s\"; using %d\n", raw, DEFAULT_MAX_HIST); | |
| 570 | + return DEFAULT_MAX_HIST; | |
| 571 | + } | |
| 572 | + } | |
| 573 | + v = strtoll(raw, NULL, 10); | |
| 574 | + if (v < 1) { | |
| 575 | + fprintf(stderr, "MAX_THOUGHT_HISTORY must be a positive integer, " | |
| 576 | + "got \"%s\"; using %d\n", raw, DEFAULT_MAX_HIST); | |
| 577 | + return DEFAULT_MAX_HIST; | |
| 578 | + } | |
| 579 | + return v; | |
| 580 | +} | |
| 581 | + | |
| 582 | +/* Coerce a JSON value to boolean like upstream's coercedBoolean: real bool, | |
| 583 | + * or the strings "true"/"false" (case-insensitive). Returns 1 on success. */ | |
| 584 | +static int val_bool(yyjson_val *v, int *out) | |
| 585 | +{ | |
| 586 | + if (yyjson_is_bool(v)) { *out = yyjson_is_true(v) ? 1 : 0; return 1; } | |
| 587 | + if (yyjson_is_str(v)) { | |
| 588 | + const char *s = yyjson_get_str(v); | |
| 589 | + size_t i, n; | |
| 590 | + char low[16]; | |
| 591 | + if (!s) return 0; | |
| 592 | + n = strlen(s); | |
| 593 | + if (n >= sizeof low) return 0; | |
| 594 | + for (i = 0; i < n; i++) low[i] = (char)tolower((unsigned char)s[i]); | |
| 595 | + low[n] = '\0'; | |
| 596 | + if (strcmp(low, "true") == 0) { *out = 1; return 1; } | |
| 597 | + if (strcmp(low, "false") == 0) { *out = 0; return 1; } | |
| 598 | + return 0; | |
| 599 | + } | |
| 600 | + return 0; | |
| 601 | +} | |
| 602 | + | |
| 603 | +/* Coerce to integer like z.coerce.number().int(): JSON number or a numeric | |
| 604 | + * string. Returns 1 on success. */ | |
| 605 | +static int val_int(yyjson_val *v, long long *out) | |
| 606 | +{ | |
| 607 | + if (yyjson_is_int(v)) { *out = yyjson_get_sint(v); return 1; } | |
| 608 | + if (yyjson_is_uint(v)) { *out = (long long)yyjson_get_uint(v); return 1; } | |
| 609 | + if (yyjson_is_real(v)) { | |
| 610 | + double d = yyjson_get_real(v); | |
| 611 | + if (d == (double)(long long)d) { *out = (long long)d; return 1; } | |
| 612 | + return 0; | |
| 613 | + } | |
| 614 | + if (yyjson_is_str(v)) { | |
| 615 | + const char *s = yyjson_get_str(v); | |
| 616 | + char *end = NULL; | |
| 617 | + long long ll; | |
| 618 | + if (!s || !*s) return 0; | |
| 619 | + errno = 0; | |
| 620 | + ll = strtoll(s, &end, 10); | |
| 621 | + if (errno != 0 || !end) return 0; | |
| 622 | + while (*end == ' ' || *end == '\t' || *end == '\n' || *end == '\r') end++; | |
| 623 | + if (*end != '\0') return 0; | |
| 624 | + *out = ll; | |
| 625 | + return 1; | |
| 626 | + } | |
| 627 | + return 0; | |
| 628 | +} | |
| 629 | + | |
| 630 | +/* Validate against the upstream schema (errors mirror index.ts/lib.ts). */ | |
| 631 | +static int validate_thought(yyjson_val *args, thought_t *t, char *err, size_t errsz) | |
| 632 | +{ | |
| 633 | + yyjson_val *v; | |
| 634 | + memset(t, 0, sizeof *t); | |
| 635 | + | |
| 636 | + v = yyjson_obj_get(args, "thought"); | |
| 637 | + if (!v || !yyjson_is_str(v) || !yyjson_get_str(v) || | |
| 638 | + !yyjson_get_str(v)[0]) { | |
| 639 | + snprintf(err, errsz, "Invalid thought: must be a string"); | |
| 640 | + return 0; | |
| 641 | + } | |
| 642 | + if (strlen(yyjson_get_str(v)) > THOUGHT_MAX) { | |
| 643 | + snprintf(err, errsz, "Invalid thought: too long (max %d bytes)", THOUGHT_MAX); | |
| 644 | + return 0; | |
| 645 | + } | |
| 646 | + t->thought = sx_strdup(yyjson_get_str(v)); | |
| 647 | + | |
| 648 | + v = yyjson_obj_get(args, "nextThoughtNeeded"); | |
| 649 | + if (!val_bool(v, &t->next_needed)) { | |
| 650 | + snprintf(err, errsz, "Invalid nextThoughtNeeded: must be a boolean"); | |
| 651 | + thought_free(t); | |
| 652 | + return 0; | |
| 653 | + } | |
| 654 | + | |
| 655 | + v = yyjson_obj_get(args, "thoughtNumber"); | |
| 656 | + { | |
| 657 | + long long n; | |
| 658 | + if (!val_int(v, &n) || n < 1) { | |
| 659 | + snprintf(err, errsz, "Invalid thoughtNumber: must be a number"); | |
| 660 | + thought_free(t); | |
| 661 | + return 0; | |
| 662 | + } | |
| 663 | + t->thought_number = n; | |
| 664 | + } | |
| 665 | + | |
| 666 | + v = yyjson_obj_get(args, "totalThoughts"); | |
| 667 | + { | |
| 668 | + long long n; | |
| 669 | + if (!val_int(v, &n) || n < 1) { | |
| 670 | + snprintf(err, errsz, "Invalid totalThoughts: must be a number"); | |
| 671 | + thought_free(t); | |
| 672 | + return 0; | |
| 673 | + } | |
| 674 | + t->total_thoughts = n; | |
| 675 | + } | |
| 676 | + | |
| 677 | + v = yyjson_obj_get(args, "isRevision"); | |
| 678 | + if (v && !yyjson_is_null(v) && !val_bool(v, &t->is_revision)) { | |
| 679 | + snprintf(err, errsz, "Invalid isRevision: must be a boolean"); | |
| 680 | + thought_free(t); | |
| 681 | + return 0; | |
| 682 | + } | |
| 683 | + | |
| 684 | + v = yyjson_obj_get(args, "revisesThought"); | |
| 685 | + if (v && !yyjson_is_null(v)) { | |
| 686 | + long long n; | |
| 687 | + if (!val_int(v, &n) || n < 1) { | |
| 688 | + snprintf(err, errsz, "Invalid revisesThought: must be a number"); | |
| 689 | + thought_free(t); | |
| 690 | + return 0; | |
| 691 | + } | |
| 692 | + t->revises = n; | |
| 693 | + } | |
| 694 | + | |
| 695 | + v = yyjson_obj_get(args, "branchFromThought"); | |
| 696 | + if (v && !yyjson_is_null(v)) { | |
| 697 | + long long n; | |
| 698 | + if (!val_int(v, &n) || n < 1) { | |
| 699 | + snprintf(err, errsz, "Invalid branchFromThought: must be a number"); | |
| 700 | + thought_free(t); | |
| 701 | + return 0; | |
| 702 | + } | |
| 703 | + t->branch_from = n; | |
| 704 | + } | |
| 705 | + | |
| 706 | + v = yyjson_obj_get(args, "branchId"); | |
| 707 | + if (v && !yyjson_is_null(v)) { | |
| 708 | + if (!yyjson_is_str(v) || !yyjson_get_str(v)) { | |
| 709 | + snprintf(err, errsz, "Invalid branchId: must be a string"); | |
| 710 | + thought_free(t); | |
| 711 | + return 0; | |
| 712 | + } | |
| 713 | + if (strlen(yyjson_get_str(v)) > BRANCHID_MAX) { | |
| 714 | + snprintf(err, errsz, "Invalid branchId: too long (max %d bytes)", | |
| 715 | + BRANCHID_MAX); | |
| 716 | + thought_free(t); | |
| 717 | + return 0; | |
| 718 | + } | |
| 719 | + t->branch_id = sx_strdup(yyjson_get_str(v)); | |
| 720 | + } | |
| 721 | + | |
| 722 | + v = yyjson_obj_get(args, "needsMoreThoughts"); | |
| 723 | + if (v && !yyjson_is_null(v) && !val_bool(v, &t->needs_more)) { | |
| 724 | + snprintf(err, errsz, "Invalid needsMoreThoughts: must be a boolean"); | |
| 725 | + thought_free(t); | |
| 726 | + return 0; | |
| 727 | + } | |
| 728 | + return 1; | |
| 729 | +} | |
| 730 | + | |
| 731 | +/* One line per accepted thought on stderr, upstream's box condensed to a | |
| 732 | + * single label line (no emoji, no colour codes in a clean-room binary). | |
| 733 | + * Silenced by DISABLE_THOUGHT_LOGGING=1|true like upstream. */ | |
| 734 | +static void log_thought_stderr(const thought_t *t) | |
| 735 | +{ | |
| 736 | + const char *dl = getenv("DISABLE_THOUGHT_LOGGING"); | |
| 737 | + char low[8]; | |
| 738 | + size_t i, n; | |
| 739 | + if (dl && *dl) { | |
| 740 | + n = strlen(dl); | |
| 741 | + if (strcmp(dl, "1") == 0) return; | |
| 742 | + if (n < sizeof low) { | |
| 743 | + for (i = 0; i < n; i++) low[i] = (char)tolower((unsigned char)dl[i]); | |
| 744 | + low[n] = '\0'; | |
| 745 | + if (strcmp(low, "true") == 0) return; | |
| 746 | + } | |
| 747 | + } | |
| 748 | + if (t->is_revision) | |
| 749 | + fprintf(stderr, "[seqthink] Revision %lld/%lld (revising thought %lld)\n", | |
| 750 | + t->thought_number, t->total_thoughts, t->revises); | |
| 751 | + else if (t->branch_from && t->branch_id) | |
| 752 | + fprintf(stderr, "[seqthink] Branch %lld/%lld (from thought %lld, ID: %s)\n", | |
| 753 | + t->thought_number, t->total_thoughts, t->branch_from, t->branch_id); | |
| 754 | + else if (t->branch_from) | |
| 755 | + fprintf(stderr, "[seqthink] Branch %lld/%lld (from thought %lld)\n", | |
| 756 | + t->thought_number, t->total_thoughts, t->branch_from); | |
| 757 | + else | |
| 758 | + fprintf(stderr, "[seqthink] Thought %lld/%lld\n", | |
| 759 | + t->thought_number, t->total_thoughts); | |
| 760 | + fflush(stderr); | |
| 761 | +} | |
| 762 | + | |
| 763 | +/* Append one thought to the persisted chains file. The file is a simple | |
| 764 | + * {"chains":[{"id":...,"started_at":...,"updated_at":...,"branches":[...], | |
| 765 | + * "thoughts":[{...}]}]} document, merged by chain id: our chain's | |
| 766 | + * existing thoughts are kept (bounded), other chains are carried over | |
| 767 | + * (bounded, oldest-updated first to keep the newest). Every field is | |
| 768 | + * re-serialised from parsed values, so a hand-corrupted file degrades to | |
| 769 | + * "unparseable -> start clean" instead of poisoning the output. The bytes go | |
| 770 | + * to <path>.tmp and only then rename() over the file (crash-safe). | |
| 771 | + * Returns 1 on success; a persistence failure never fails the tool call. */ | |
| 772 | + | |
| 773 | +typedef struct { | |
| 774 | + char *thought; | |
| 775 | + long long tn, tt; | |
| 776 | + int next_needed, is_revision, needs_more; | |
| 777 | + long long revises, branch_from; | |
| 778 | + char *branch_id; | |
| 779 | + long long at; | |
| 780 | +} pth_t; | |
| 781 | + | |
| 782 | +typedef struct { | |
| 783 | + char *id; | |
| 784 | + long long started_at, updated_at; | |
| 785 | + pth_t *th; | |
| 786 | + size_t n, cap; | |
| 787 | +} chain_t; | |
| 788 | + | |
| 789 | +static void chain_add(chain_t *c, const pth_t *t) | |
| 790 | +{ | |
| 791 | + if (c->n == c->cap) { | |
| 792 | + c->cap = c->cap ? c->cap * 2 : 16; | |
| 793 | + c->th = (pth_t *)realloc(c->th, c->cap * sizeof *c->th); | |
| 794 | + if (!c->th) { fputs("out of memory\n", stderr); exit(1); } | |
| 795 | + } | |
| 796 | + c->th[c->n++] = *t; | |
| 797 | +} | |
| 798 | + | |
| 799 | +static void chain_free(chain_t *c) | |
| 800 | +{ | |
| 801 | + size_t i; | |
| 802 | + for (i = 0; i < c->n; i++) { free(c->th[i].thought); free(c->th[i].branch_id); } | |
| 803 | + free(c->th); | |
| 804 | + free(c->id); | |
| 805 | + memset(c, 0, sizeof *c); | |
| 806 | +} | |
| 807 | + | |
| 808 | +static char *dup_str_or_null(yyjson_val *v) | |
| 809 | +{ | |
| 810 | + if (yyjson_is_str(v) && yyjson_get_str(v)) return sx_strdup(yyjson_get_str(v)); | |
| 811 | + return NULL; | |
| 812 | +} | |
| 813 | + | |
| 814 | +static int load_chains_model(char *txt, size_t len, chain_t **out, size_t *outn) | |
| 815 | +{ | |
| 816 | + yyjson_doc *doc; | |
| 817 | + yyjson_val *root, *chains; | |
| 818 | + chain_t *cs = NULL; | |
| 819 | + size_t n = 0, i; | |
| 820 | + | |
| 821 | + *out = NULL; *outn = 0; | |
| 822 | + if (!txt) return 1; | |
| 823 | + doc = yyjson_read(txt, len, 0); | |
| 824 | + free(txt); | |
| 825 | + if (!doc) return 0; /* unparseable */ | |
| 826 | + root = yyjson_doc_get_root(doc); | |
| 827 | + if (!yyjson_is_obj(root)) { yyjson_doc_free(doc); return 0; } | |
| 828 | + chains = yyjson_obj_get(root, "chains"); | |
| 829 | + if (!yyjson_is_arr(chains)) { yyjson_doc_free(doc); return 1; } | |
| 830 | + n = yyjson_arr_size(chains); | |
| 831 | + if (n) { | |
| 832 | + cs = (chain_t *)sx_malloc(n * sizeof *cs); | |
| 833 | + memset(cs, 0, n * sizeof *cs); | |
| 834 | + } | |
| 835 | + for (i = 0; i < n; i++) { | |
| 836 | + yyjson_val *c = yyjson_arr_get(chains, i); | |
| 837 | + yyjson_val *v; | |
| 838 | + if (!yyjson_is_obj(c)) continue; | |
| 839 | + v = yyjson_obj_get(c, "id"); | |
| 840 | + if (!yyjson_is_str(v) || !yyjson_get_str(v) || !*yyjson_get_str(v)) continue; | |
| 841 | + cs[i].id = sx_strdup(yyjson_get_str(v)); | |
| 842 | + v = yyjson_obj_get(c, "started_at"); | |
| 843 | + cs[i].started_at = yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0; | |
| 844 | + v = yyjson_obj_get(c, "updated_at"); | |
| 845 | + cs[i].updated_at = yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0; | |
| 846 | + v = yyjson_obj_get(c, "thoughts"); | |
| 847 | + if (yyjson_is_arr(v)) { | |
| 848 | + size_t j, tn = yyjson_arr_size(v); | |
| 849 | + for (j = 0; j < tn; j++) { | |
| 850 | + yyjson_val *tv = yyjson_arr_get(v, j); | |
| 851 | + pth_t t; | |
| 852 | + yyjson_val *x; | |
| 853 | + if (!yyjson_is_obj(tv)) continue; | |
| 854 | + memset(&t, 0, sizeof t); | |
| 855 | + x = yyjson_obj_get(tv, "thought"); | |
| 856 | + if (!yyjson_is_str(x) || !yyjson_get_str(x)) continue; | |
| 857 | + t.thought = sx_strdup(yyjson_get_str(x)); | |
| 858 | + x = yyjson_obj_get(tv, "thought_number"); | |
| 859 | + t.tn = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; | |
| 860 | + x = yyjson_obj_get(tv, "total_thoughts"); | |
| 861 | + t.tt = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; | |
| 862 | + t.next_needed = yyjson_is_true(yyjson_obj_get(tv, "next_needed")); | |
| 863 | + t.is_revision = yyjson_is_true(yyjson_obj_get(tv, "is_revision")); | |
| 864 | + t.needs_more = yyjson_is_true(yyjson_obj_get(tv, "needs_more")); | |
| 865 | + x = yyjson_obj_get(tv, "revises"); | |
| 866 | + t.revises = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; | |
| 867 | + x = yyjson_obj_get(tv, "branch_from"); | |
| 868 | + t.branch_from = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; | |
| 869 | + t.branch_id = dup_str_or_null(yyjson_obj_get(tv, "branch_id")); | |
| 870 | + x = yyjson_obj_get(tv, "at"); | |
| 871 | + t.at = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; | |
| 872 | + chain_add(&cs[i], &t); | |
| 873 | + } | |
| 874 | + } | |
| 875 | + } | |
| 876 | + yyjson_doc_free(doc); | |
| 877 | + *out = cs; *outn = n; | |
| 878 | + return 1; | |
| 879 | +} | |
| 880 | + | |
| 881 | +static void free_model(chain_t *cs, size_t n) | |
| 882 | +{ | |
| 883 | + size_t i; | |
| 884 | + if (!cs) return; | |
| 885 | + for (i = 0; i < n; i++) chain_free(&cs[i]); | |
| 886 | + free(cs); | |
| 887 | +} | |
| 888 | + | |
| 889 | +static void emit_thought(buf_t *b, const pth_t *t) | |
| 890 | +{ | |
| 891 | + buf_str(b, "{\"thought\":"); | |
| 892 | + json_escape_buf(b, t->thought); | |
| 893 | + buf_addf(b, ",\"thought_number\":%lld,\"total_thoughts\":%lld", t->tn, t->tt); | |
| 894 | + buf_addf(b, ",\"next_needed\":%s", t->next_needed ? "true" : "false"); | |
| 895 | + if (t->is_revision) buf_str(b, ",\"is_revision\":true"); | |
| 896 | + if (t->revises) buf_addf(b, ",\"revises\":%lld", t->revises); | |
| 897 | + if (t->branch_from) buf_addf(b, ",\"branch_from\":%lld", t->branch_from); | |
| 898 | + if (t->branch_id) { | |
| 899 | + buf_str(b, ",\"branch_id\":"); | |
| 900 | + json_escape_buf(b, t->branch_id); | |
| 901 | + } | |
| 902 | + if (t->needs_more) buf_str(b, ",\"needs_more\":true"); | |
| 903 | + buf_addf(b, ",\"at\":%lld}", t->at); | |
| 904 | +} | |
| 905 | + | |
| 906 | +static int persist_thought(const char *chain_id, const thought_t *t) | |
| 907 | +{ | |
| 908 | + char dir[1000], path[1200]; | |
| 909 | + char *txt = NULL; | |
| 910 | + size_t len = 0, i, n = 0; | |
| 911 | + chain_t *cs = NULL; | |
| 912 | + chain_t *mine = NULL; | |
| 913 | + pth_t nt; | |
| 914 | + buf_t out; | |
| 915 | + int mine_idx = -1; | |
| 916 | + | |
| 917 | + state_dir(dir, sizeof dir); | |
| 918 | + if (!mkdirs(dir)) return 0; | |
| 919 | + chains_path(path, sizeof path); | |
| 920 | + | |
| 921 | + txt = read_file(path, &len); | |
| 922 | + if (!load_chains_model(txt, len, &cs, &n)) { /* frees txt, strays to clean */ | |
| 923 | + cs = NULL; n = 0; | |
| 924 | + } | |
| 925 | + | |
| 926 | + for (i = 0; i < n; i++) | |
| 927 | + if (cs[i].id && strcmp(cs[i].id, chain_id) == 0) { mine_idx = (int)i; break; } | |
| 928 | + mine = mine_idx >= 0 ? &cs[mine_idx] : NULL; | |
| 929 | + | |
| 930 | + memset(&nt, 0, sizeof nt); | |
| 931 | + nt.thought = sx_strdup(t->thought); /* owned by the chain model */ | |
| 932 | + nt.tn = t->thought_number; | |
| 933 | + nt.tt = t->total_thoughts; | |
| 934 | + nt.next_needed = t->next_needed; | |
| 935 | + nt.is_revision = t->is_revision; | |
| 936 | + nt.needs_more = t->needs_more; | |
| 937 | + nt.revises = t->revises; | |
| 938 | + nt.branch_from = t->branch_from; | |
| 939 | + nt.branch_id = t->branch_id ? sx_strdup(t->branch_id) : NULL; | |
| 940 | + nt.at = (long long)time(NULL); | |
| 941 | + | |
| 942 | + if (!mine) { | |
| 943 | + cs = (chain_t *)realloc(cs, (n + 1) * sizeof *cs); | |
| 944 | + if (!cs) { fputs("out of memory\n", stderr); exit(1); } | |
| 945 | + memset(&cs[n], 0, sizeof cs[n]); | |
| 946 | + mine = &cs[n]; | |
| 947 | + mine->id = sx_strdup(chain_id); | |
| 948 | + mine->started_at = nt.at; | |
| 949 | + n++; | |
| 950 | + } | |
| 951 | + chain_add(mine, &nt); | |
| 952 | + mine->updated_at = nt.at; | |
| 953 | + /* Bound this chain: keep the newest MAX_THOUGHTS_EACH thoughts. */ | |
| 954 | + if (mine->n > MAX_THOUGHTS_EACH) { | |
| 955 | + size_t drop = mine->n - MAX_THOUGHTS_EACH, j; | |
| 956 | + for (j = 0; j < drop; j++) { | |
| 957 | + free(mine->th[j].thought); | |
| 958 | + free(mine->th[j].branch_id); | |
| 959 | + } | |
| 960 | + memmove(&mine->th[0], &mine->th[drop], (mine->n - drop) * sizeof *mine->th); | |
| 961 | + mine->n -= drop; | |
| 962 | + } | |
| 963 | + | |
| 964 | + /* Bound the file: keep our chain + the newest (MAX_CHAINS - 1) others. | |
| 965 | + * mine_idx is the ORIGINAL index of our chain (mine may dangle after a | |
| 966 | + * growth realloc, so identity is tracked by index). */ | |
| 967 | + if (n > MAX_CHAINS) { | |
| 968 | + char *keep = (char *)sx_malloc(n); | |
| 969 | + size_t w = 0, k; | |
| 970 | + memset(keep, 1, n); | |
| 971 | + if (mine_idx >= 0) keep[mine_idx] = 2; /* ours: never dropped */ | |
| 972 | + while (1) { | |
| 973 | + long long oldest = LLONG_MAX; | |
| 974 | + int oi = -1; | |
| 975 | + size_t kept = 0; | |
| 976 | + for (k = 0; k < n; k++) if (keep[k]) kept++; | |
| 977 | + if (kept <= (size_t)MAX_CHAINS) break; | |
| 978 | + for (k = 0; k < n; k++) { | |
| 979 | + if (keep[k] != 1) continue; | |
| 980 | + if (cs[k].updated_at < oldest) { oldest = cs[k].updated_at; oi = (int)k; } | |
| 981 | + } | |
| 982 | + if (oi < 0) { /* tie fallback */ | |
| 983 | + for (k = 0; k < n; k++) if (keep[k] == 1) { oi = (int)k; break; } | |
| 984 | + } | |
| 985 | + if (oi < 0) break; | |
| 986 | + keep[oi] = 0; | |
| 987 | + } | |
| 988 | + for (k = 0; k < n; k++) { | |
| 989 | + if (!keep[k]) { chain_free(&cs[k]); continue; } | |
| 990 | + if (w != k) cs[w] = cs[k]; | |
| 991 | + w++; | |
| 992 | + } | |
| 993 | + n = w; | |
| 994 | + free(keep); | |
| 995 | + } | |
| 996 | + | |
| 997 | + buf_init(&out); | |
| 998 | + buf_str(&out, "{\"chains\":["); | |
| 999 | + for (i = 0; i < n; i++) { | |
| 1000 | + if (i) buf_str(&out, ","); | |
| 1001 | + buf_str(&out, "{\"id\":"); | |
| 1002 | + json_escape_buf(&out, cs[i].id); | |
| 1003 | + buf_addf(&out, ",\"started_at\":%lld,\"updated_at\":%lld,\"thoughts\":[", | |
| 1004 | + cs[i].started_at, cs[i].updated_at); | |
| 1005 | + { | |
| 1006 | + size_t j; | |
| 1007 | + for (j = 0; j < cs[i].n; j++) { | |
| 1008 | + if (j) buf_str(&out, ","); | |
| 1009 | + emit_thought(&out, &cs[i].th[j]); | |
| 1010 | + } | |
| 1011 | + } | |
| 1012 | + buf_str(&out, "],\"count\":"); | |
| 1013 | + buf_addf(&out, "%zu", cs[i].n); | |
| 1014 | + buf_str(&out, ",\"branches\":["); | |
| 1015 | + { /* distinct branch ids in first-seen order */ | |
| 1016 | + size_t j, k; | |
| 1017 | + int first = 1; | |
| 1018 | + for (j = 0; j < cs[i].n; j++) { | |
| 1019 | + int seen = 0; | |
| 1020 | + if (!cs[i].th[j].branch_id || !cs[i].th[j].branch_from) continue; | |
| 1021 | + for (k = 0; k < j; k++) | |
| 1022 | + if (cs[i].th[k].branch_id && cs[i].th[j].branch_id && | |
| 1023 | + strcmp(cs[i].th[k].branch_id, cs[i].th[j].branch_id) == 0) | |
| 1024 | + { seen = 1; break; } | |
| 1025 | + if (seen) continue; | |
| 1026 | + if (!first) buf_str(&out, ","); | |
| 1027 | + first = 0; | |
| 1028 | + json_escape_buf(&out, cs[i].th[j].branch_id); | |
| 1029 | + } | |
| 1030 | + } | |
| 1031 | + buf_str(&out, "]}"); | |
| 1032 | + } | |
| 1033 | + buf_str(&out, "]}"); | |
| 1034 | + | |
| 1035 | + if (!out.p) { free_model(cs, n); return 0; } | |
| 1036 | + { | |
| 1037 | + int ok = write_file_atomic(path, out.p, out.n); | |
| 1038 | + buf_free(&out); | |
| 1039 | + free_model(cs, n); | |
| 1040 | + return ok; | |
| 1041 | + } | |
| 1042 | +} | |
| 1043 | + | |
| 1044 | +/* ------------------------------------------------------------------ */ | |
| 1045 | +/* Session (one --mcp process == one chain) */ | |
| 1046 | +/* ------------------------------------------------------------------ */ | |
| 1047 | + | |
| 1048 | +typedef struct { | |
| 1049 | + tvec_t history; | |
| 1050 | + bvec_t branches; | |
| 1051 | + long long max_hist; | |
| 1052 | + char chain_id[64]; | |
| 1053 | + int persist; | |
| 1054 | +} session_t; | |
| 1055 | + | |
| 1056 | +static void session_init(session_t *s) | |
| 1057 | +{ | |
| 1058 | + const char *dl = getenv("DISABLE_THOUGHT_LOGGING"); | |
| 1059 | + memset(s, 0, sizeof *s); | |
| 1060 | + s->max_hist = read_max_history(); | |
| 1061 | + snprintf(s->chain_id, sizeof s->chain_id, "th-%llx-%lx", | |
| 1062 | + (unsigned long long)time(NULL), (unsigned long) | |
| 1063 | +#if defined(_WIN32) | |
| 1064 | + GetCurrentProcessId() | |
| 1065 | +#else | |
| 1066 | + (unsigned long)getpid() | |
| 1067 | +#endif | |
| 1068 | + ); | |
| 1069 | + s->persist = 1; | |
| 1070 | + if (dl && *dl) { | |
| 1071 | + const char *p = dl; | |
| 1072 | + int all_digits = 1; | |
| 1073 | + for (; *p; p++) if (!isdigit((unsigned char)*p)) { all_digits = 0; break; } | |
| 1074 | + if (strcmp(dl, "1") == 0 || strcmp(dl, "true") == 0 || | |
| 1075 | + strcmp(dl, "TRUE") == 0 || strcmp(dl, "True") == 0) | |
| 1076 | + s->persist = 0; | |
| 1077 | + (void)all_digits; | |
| 1078 | + } | |
| 1079 | +} | |
| 1080 | + | |
| 1081 | +static void session_free(session_t *s) | |
| 1082 | +{ | |
| 1083 | + size_t i; | |
| 1084 | + for (i = 0; i < s->history.n; i++) thought_free(&s->history.v[i]); | |
| 1085 | + free(s->history.v); | |
| 1086 | + for (i = 0; i < s->branches.n; i++) free(s->branches.v[i].key); | |
| 1087 | + free(s->branches.v); | |
| 1088 | + memset(s, 0, sizeof *s); | |
| 1089 | +} | |
| 1090 | + | |
| 1091 | +/* The tool itself. Returns the result text (heap; caller frees) and sets | |
| 1092 | + * *is_error like upstream's {content,isError}. */ | |
| 1093 | +static char *process_thought(session_t *s, yyjson_val *args, int *is_error) | |
| 1094 | +{ | |
| 1095 | + thought_t t; | |
| 1096 | + char err[256]; | |
| 1097 | + buf_t b; | |
| 1098 | + | |
| 1099 | + *is_error = 0; | |
| 1100 | + if (!args || !yyjson_is_obj(args)) { | |
| 1101 | + return sx_strdup("{\"error\":\"Invalid thought: must be a string\"," | |
| 1102 | + "\"status\":\"failed\"}"); | |
| 1103 | + } | |
| 1104 | + if (!validate_thought(args, &t, err, sizeof err)) { | |
| 1105 | + buf_init(&b); | |
| 1106 | + buf_str(&b, "{\"error\":"); | |
| 1107 | + json_escape_buf(&b, err); | |
| 1108 | + buf_str(&b, ",\"status\":\"failed\"}"); | |
| 1109 | + *is_error = 1; | |
| 1110 | + return b.p ? b.p : sx_strdup("{\"error\":\"invalid input\",\"status\":\"failed\"}"); | |
| 1111 | + } | |
| 1112 | + | |
| 1113 | + /* Upstream rule: thoughtNumber past totalThoughts raises the estimate. */ | |
| 1114 | + if (t.thought_number > t.total_thoughts) t.total_thoughts = t.thought_number; | |
| 1115 | + | |
| 1116 | + /* Upstream logs before touching any state. */ | |
| 1117 | + log_thought_stderr(&t); | |
| 1118 | + | |
| 1119 | + tvec_push(&s->history, &t); | |
| 1120 | + if (t.branch_from && t.branch_id) bvec_record(&s->branches, t.branch_id); | |
| 1121 | + | |
| 1122 | + if ((long long)s->history.n > s->max_hist) { | |
| 1123 | + thought_t *oldest = &s->history.v[0]; | |
| 1124 | + if (oldest->branch_from && oldest->branch_id) | |
| 1125 | + bvec_evict(&s->branches, oldest->branch_id); | |
| 1126 | + thought_free(oldest); | |
| 1127 | + memmove(&s->history.v[0], &s->history.v[1], | |
| 1128 | + (s->history.n - 1) * sizeof *s->history.v); | |
| 1129 | + s->history.n--; | |
| 1130 | + } | |
| 1131 | + | |
| 1132 | + if (s->persist) persist_thought(s->chain_id, &t); | |
| 1133 | + | |
| 1134 | + /* Upstream response: exactly these five fields. One buffer, compact | |
| 1135 | + * single-line JSON (valid inside structuredContent); the content text is | |
| 1136 | + * the same object, so tests and clients can parse either. */ | |
| 1137 | + { | |
| 1138 | + size_t i; | |
| 1139 | + buf_init(&b); | |
| 1140 | + buf_addf(&b, "{\"thoughtNumber\":%lld,\"totalThoughts\":%lld," | |
| 1141 | + "\"nextThoughtNeeded\":%s,\"branches\":[", | |
| 1142 | + t.thought_number, t.total_thoughts, | |
| 1143 | + t.next_needed ? "true" : "false"); | |
| 1144 | + for (i = 0; i < s->branches.n; i++) { | |
| 1145 | + if (i) buf_str(&b, ","); | |
| 1146 | + json_escape_buf(&b, s->branches.v[i].key); | |
| 1147 | + } | |
| 1148 | + buf_addf(&b, "],\"thoughtHistoryLength\":%zu}", s->history.n); | |
| 1149 | + } | |
| 1150 | + /* The snapshot was already taken before we hand back; free this | |
| 1151 | + * thought's copy only after persistence used it. */ | |
| 1152 | + return b.p ? b.p : sx_strdup("{}"); | |
| 1153 | +} | |
| 1154 | + | |
| 1155 | +/* ------------------------------------------------------------------ */ | |
| 1156 | +/* --mcp mode: MCP JSON-RPC 2.0 over stdio */ | |
| 1157 | +/* ------------------------------------------------------------------ */ | |
| 1158 | + | |
| 1159 | +static const char SEQTHINK_TOOL_SCHEMA[] = | |
| 1160 | + "{\"type\":\"object\",\"properties\":{" | |
| 1161 | + "\"thought\":{\"type\":\"string\",\"description\":\"Your current thinking step\"}," | |
| 1162 | + "\"nextThoughtNeeded\":{\"type\":\"boolean\",\"description\":\"Whether another thought step is needed\"}," | |
| 1163 | + "\"thoughtNumber\":{\"type\":\"integer\",\"description\":\"Current thought number (numeric value, e.g., 1, 2, 3)\",\"minimum\":1}," | |
| 1164 | + "\"totalThoughts\":{\"type\":\"integer\",\"description\":\"Estimated total thoughts needed (numeric value, e.g., 5, 10)\",\"minimum\":1}," | |
| 1165 | + "\"isRevision\":{\"type\":\"boolean\",\"description\":\"Whether this revises previous thinking\"}," | |
| 1166 | + "\"revisesThought\":{\"type\":\"integer\",\"description\":\"Which thought is being reconsidered\",\"minimum\":1}," | |
| 1167 | + "\"branchFromThought\":{\"type\":\"integer\",\"description\":\"Branching point thought number\",\"minimum\":1}," | |
| 1168 | + "\"branchId\":{\"type\":\"string\",\"description\":\"Branch identifier\"}," | |
| 1169 | + "\"needsMoreThoughts\":{\"type\":\"boolean\",\"description\":\"If more thoughts are needed\"}" | |
| 1170 | + "},\"required\":[\"thought\",\"nextThoughtNeeded\",\"thoughtNumber\",\"totalThoughts\"]}"; | |
| 1171 | + | |
| 1172 | +static const char SEQTHINK_TOOL_OUTPUT[] = | |
| 1173 | + "{\"type\":\"object\",\"properties\":{" | |
| 1174 | + "\"thoughtNumber\":{\"type\":\"number\"}," | |
| 1175 | + "\"totalThoughts\":{\"type\":\"number\"}," | |
| 1176 | + "\"nextThoughtNeeded\":{\"type\":\"boolean\"}," | |
| 1177 | + "\"branches\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}," | |
| 1178 | + "\"thoughtHistoryLength\":{\"type\":\"number\"}}}"; | |
| 1179 | + | |
| 1180 | +static const char SEQTHINK_TOOL_DESC[] = | |
| 1181 | + "A detailed tool for dynamic and reflective problem-solving through thoughts.\n" | |
| 1182 | + "Each thought can build on, question, or revise previous insights as understanding deepens.\n\n" | |
| 1183 | + "When to use this tool:\n" | |
| 1184 | + "- Breaking down complex problems into steps\n" | |
| 1185 | + "- Planning and design with room for revision\n" | |
| 1186 | + "- Analysis that might need course correction\n" | |
| 1187 | + "- Problems where the full scope might not be clear initially\n" | |
| 1188 | + "- Tasks that need to maintain context over multiple steps\n" | |
| 1189 | + "- Situations where irrelevant information needs to be filtered out\n\n" | |
| 1190 | + "You should:\n" | |
| 1191 | + "1. Estimate totalThoughts up front and adjust it up or down as you go;" | |
| 1192 | + " thoughtNumber may exceed it\n" | |
| 1193 | + "2. Question or revise earlier thoughts (isRevision with revisesThought)," | |
| 1194 | + " or branch (branchFromThought with branchId)\n" | |
| 1195 | + "3. Express uncertainty, and ignore information irrelevant to the current step\n" | |
| 1196 | + "4. Generate a solution hypothesis, verify it against the earlier steps," | |
| 1197 | + " and repeat until satisfied\n" | |
| 1198 | + "5. Set nextThoughtNeeded to false only when truly done and a satisfactory" | |
| 1199 | + " answer is reached"; | |
| 1200 | + | |
| 1201 | +/* Emit the tools/list result. */ | |
| 1202 | +static void mcp_tools_list(FILE *out, const char *id_raw) | |
| 1203 | +{ | |
| 1204 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"tools\":[{", id_raw); | |
| 1205 | + fputs("\"name\":\"sequentialthinking\",\"title\":\"Sequential Thinking\"," | |
| 1206 | + "\"description\":", out); | |
| 1207 | + json_escape(out, SEQTHINK_TOOL_DESC); | |
| 1208 | + fputs(",\"inputSchema\":", out); | |
| 1209 | + fputs(SEQTHINK_TOOL_SCHEMA, out); | |
| 1210 | + fputs(",\"outputSchema\":", out); | |
| 1211 | + fputs(SEQTHINK_TOOL_OUTPUT, out); | |
| 1212 | + fputs(",\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":false," | |
| 1213 | + "\"idempotentHint\":false,\"openWorldHint\":false}}]}}\n", out); | |
| 1214 | + fflush(out); | |
| 1215 | +} | |
| 1216 | + | |
| 1217 | +static void mcp_server_info(FILE *out, const char *id_raw) | |
| 1218 | +{ | |
| 1219 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{" | |
| 1220 | + "\"protocolVersion\":\"2024-11-05\",\"capabilities\":{\"tools\":{}}," | |
| 1221 | + "\"serverInfo\":{\"name\":\"%s\",\"version\":\"%s\"}}}\n", | |
| 1222 | + id_raw, PLUGIN_SLUG, PLUGIN_VER); | |
| 1223 | + fflush(out); | |
| 1224 | +} | |
| 1225 | + | |
| 1226 | +/* Copy the raw JSON-RPC id token (number or string) so the reply echoes the | |
| 1227 | + * same type. */ | |
| 1228 | +static int json_id_raw(const char *line, char *out, size_t outsz) | |
| 1229 | +{ | |
| 1230 | + const char *p = strstr(line, "\"id\""); | |
| 1231 | + size_t i = 0; | |
| 1232 | + if (!p) return 0; | |
| 1233 | + p += 4; | |
| 1234 | + while (*p && (unsigned char)*p <= ' ') p++; | |
| 1235 | + if (*p != ':') return 0; | |
| 1236 | + p++; | |
| 1237 | + while (*p && (unsigned char)*p <= ' ') p++; | |
| 1238 | + if (*p == '"') { | |
| 1239 | + out[i++] = *p++; | |
| 1240 | + while (*p && i + 2 < outsz) { | |
| 1241 | + out[i++] = *p; | |
| 1242 | + if (*p == '\\' && p[1]) { p++; out[i++] = *p++; } | |
| 1243 | + else if (*p == '"') { p++; out[i++] = '"'; break; } | |
| 1244 | + else p++; | |
| 1245 | + } | |
| 1246 | + out[i] = '\0'; | |
| 1247 | + return i > 1; | |
| 1248 | + } | |
| 1249 | + while (*p && (isdigit((unsigned char)*p) || *p == '-' || *p == '+') && | |
| 1250 | + i + 1 < outsz) | |
| 1251 | + out[i++] = *p++; | |
| 1252 | + out[i] = '\0'; | |
| 1253 | + return i > 0; | |
| 1254 | +} | |
| 1255 | + | |
| 1256 | +static void mcp_tool_call(FILE *out, const char *id_raw, yyjson_val *params, | |
| 1257 | + session_t *sess) | |
| 1258 | +{ | |
| 1259 | + yyjson_val *name = NULL, *args = NULL, *v; | |
| 1260 | + char *text; | |
| 1261 | + int is_err = 0; | |
| 1262 | + | |
| 1263 | + if (params && yyjson_is_obj(params)) { | |
| 1264 | + name = yyjson_obj_get(params, "name"); | |
| 1265 | + args = yyjson_obj_get(params, "arguments"); | |
| 1266 | + } | |
| 1267 | + if (!name || !yyjson_is_str(name) || !yyjson_get_str(name) || | |
| 1268 | + strcmp(yyjson_get_str(name), "sequentialthinking") != 0) { | |
| 1269 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32602," | |
| 1270 | + "\"message\":\"unknown tool\"}}\n", id_raw); | |
| 1271 | + fflush(out); | |
| 1272 | + return; | |
| 1273 | + } | |
| 1274 | + (void)v; | |
| 1275 | + text = process_thought(sess, args, &is_err); | |
| 1276 | + | |
| 1277 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"content\":" | |
| 1278 | + "[{\"type\":\"text\",\"text\":", id_raw); | |
| 1279 | + json_escape(out, text); | |
| 1280 | + fputs("}],\"structuredContent\":", out); | |
| 1281 | + if (!is_err) { | |
| 1282 | + fputs(text, out); /* the five-field object, verbatim */ | |
| 1283 | + fputs(",\"isError\":false}}\n", out); | |
| 1284 | + } else { | |
| 1285 | + fputs(text, out); /* the {error,status} object */ | |
| 1286 | + fputs(",\"isError\":true}}\n", out); | |
| 1287 | + } | |
| 1288 | + fflush(out); | |
| 1289 | + free(text); | |
| 1290 | +} | |
| 1291 | + | |
| 1292 | +int run_mcp(void) | |
| 1293 | +{ | |
| 1294 | + char *line = NULL; | |
| 1295 | + size_t cap = 0; | |
| 1296 | + ssize_t len; | |
| 1297 | + session_t sess; | |
| 1298 | + | |
| 1299 | + session_init(&sess); | |
| 1300 | + setvbuf(stdout, NULL, _IOLBF, 0); | |
| 1301 | + while ((len = getline(&line, &cap, stdin)) != -1) { | |
| 1302 | + yyjson_doc *doc; | |
| 1303 | + yyjson_val *root, *m, *params; | |
| 1304 | + const char *method; | |
| 1305 | + char id_raw[128] = ""; | |
| 1306 | + | |
| 1307 | + if (len == 0 || !memchr(line, '{', (size_t)len)) continue; | |
| 1308 | + doc = yyjson_read(line, strlen(line), 0); | |
| 1309 | + if (!doc) continue; | |
| 1310 | + root = yyjson_doc_get_root(doc); | |
| 1311 | + m = yyjson_obj_get(root, "method"); | |
| 1312 | + method = yyjson_is_str(m) ? yyjson_get_str(m) : NULL; | |
| 1313 | + params = yyjson_obj_get(root, "params"); | |
| 1314 | + if (!method) { yyjson_doc_free(doc); continue; } | |
| 1315 | + if (strncmp(method, "notifications/", 14) == 0) { | |
| 1316 | + yyjson_doc_free(doc); | |
| 1317 | + continue; | |
| 1318 | + } | |
| 1319 | + if (!json_id_raw(line, id_raw, sizeof id_raw) || !id_raw[0]) { | |
| 1320 | + yyjson_doc_free(doc); | |
| 1321 | + continue; | |
| 1322 | + } | |
| 1323 | + | |
| 1324 | + if (strcmp(method, "initialize") == 0) { | |
| 1325 | + mcp_server_info(stdout, id_raw); | |
| 1326 | + } else if (strcmp(method, "tools/list") == 0) { | |
| 1327 | + mcp_tools_list(stdout, id_raw); | |
| 1328 | + } else if (strcmp(method, "tools/call") == 0) { | |
| 1329 | + mcp_tool_call(stdout, id_raw, params, &sess); | |
| 1330 | + } else if (strcmp(method, "ping") == 0) { | |
| 1331 | + fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{}}\n", id_raw); | |
| 1332 | + fflush(stdout); | |
| 1333 | + } else { | |
| 1334 | + fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32601," | |
| 1335 | + "\"message\":\"method not found\"}}\n", id_raw); | |
| 1336 | + fflush(stdout); | |
| 1337 | + } | |
| 1338 | + yyjson_doc_free(doc); | |
| 1339 | + } | |
| 1340 | + free(line); | |
| 1341 | + session_free(&sess); | |
| 1342 | + return 0; | |
| 1343 | +} | |
| 1344 | + | |
| 1345 | +/* ------------------------------------------------------------------ */ | |
| 1346 | +/* Discovery metadata */ | |
| 1347 | +/* ------------------------------------------------------------------ */ | |
| 1348 | + | |
| 1349 | +static int run_meta(void) | |
| 1350 | +{ | |
| 1351 | + puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"," | |
| 1352 | + "\"kind\":\"mcp\",\"mcp\":true,\"daemon\":false,\"menus\":false," | |
| 1353 | + "\"verified\":\"live\"}"); | |
| 1354 | + fflush(stdout); | |
| 1355 | + return 0; | |
| 1356 | +} | |
| 1357 | + | |
| 1358 | +/* ------------------------------------------------------------------ */ | |
| 1359 | +/* JSON node API */ | |
| 1360 | +/* ------------------------------------------------------------------ */ | |
| 1361 | + | |
| 1362 | +static void json_headers(void) | |
| 1363 | +{ | |
| 1364 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | |
| 1365 | + "Cache-Control: no-store\r\n" | |
| 1366 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | |
| 1367 | +} | |
| 1368 | + | |
| 1369 | +static char *read_body(void) | |
| 1370 | +{ | |
| 1371 | + const char *cl = getenv("CONTENT_LENGTH"); | |
| 1372 | + long n; | |
| 1373 | + char *buf; | |
| 1374 | + size_t got = 0; | |
| 1375 | + if (!cl || !*cl) return NULL; | |
| 1376 | + n = atol(cl); | |
| 1377 | + if (n <= 0 || (unsigned long)n > REQ_MAX) return NULL; | |
| 1378 | + buf = (char *)sx_malloc((size_t)n + 1); | |
| 1379 | + while (got < (size_t)n) { | |
| 1380 | + size_t r = fread(buf + got, 1, (size_t)n - got, stdin); | |
| 1381 | + if (r == 0) break; | |
| 1382 | + got += r; | |
| 1383 | + } | |
| 1384 | + buf[got] = '\0'; | |
| 1385 | + return buf; | |
| 1386 | +} | |
| 1387 | + | |
| 1388 | +/* Read one field from a JSON body as a string (string/int/bool coerced). */ | |
| 1389 | +static int json_str_field(const char *json, const char *key, char *out, size_t outsz) | |
| 1390 | +{ | |
| 1391 | + yyjson_doc *doc; | |
| 1392 | + yyjson_val *v; | |
| 1393 | + int found = 0; | |
| 1394 | + if (!json) return 0; | |
| 1395 | + doc = yyjson_read(json, strlen(json), 0); | |
| 1396 | + if (!doc) return 0; | |
| 1397 | + v = yyjson_obj_get(yyjson_doc_get_root(doc), key); | |
| 1398 | + if (yyjson_is_str(v) && yyjson_get_str(v)) { | |
| 1399 | + snprintf(out, outsz, "%s", yyjson_get_str(v)); | |
| 1400 | + found = 1; | |
| 1401 | + } else if (yyjson_is_int(v)) { | |
| 1402 | + snprintf(out, outsz, "%lld", (long long)yyjson_get_sint(v)); | |
| 1403 | + found = 1; | |
| 1404 | + } else if (yyjson_is_bool(v)) { | |
| 1405 | + snprintf(out, outsz, "%s", yyjson_is_true(v) ? "true" : "false"); | |
| 1406 | + found = 1; | |
| 1407 | + } | |
| 1408 | + yyjson_doc_free(doc); | |
| 1409 | + return found; | |
| 1410 | +} | |
| 1411 | + | |
| 1412 | +static void api_err(const char *msg) | |
| 1413 | +{ | |
| 1414 | + json_headers(); | |
| 1415 | + fputs("{\"ok\":false,\"error\":", stdout); | |
| 1416 | + json_escape(stdout, msg ? msg : "error"); | |
| 1417 | + fputs("}\n", stdout); | |
| 1418 | +} | |
| 1419 | + | |
| 1420 | +static void api_info(void) | |
| 1421 | +{ | |
| 1422 | + char dir[1000]; | |
| 1423 | + state_dir(dir, sizeof dir); | |
| 1424 | + json_headers(); | |
| 1425 | + fputs("{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"slug\":\"" PLUGIN_SLUG | |
| 1426 | + "\",\"version\":\"" PLUGIN_VER "\",\"kind\":\"mcp\",\"mcp\":true," | |
| 1427 | + "\"daemon\":false,\"menus\":false,\"verified\":\"live\"," | |
| 1428 | + "\"tools\":[\"sequentialthinking\"],\"tool_schema\":", stdout); | |
| 1429 | + fputs(SEQTHINK_TOOL_SCHEMA, stdout); | |
| 1430 | + fputs(",\"tool_output_schema\":", stdout); | |
| 1431 | + fputs(SEQTHINK_TOOL_OUTPUT, stdout); | |
| 1432 | + fputs(",\"state_dir\":", stdout); | |
| 1433 | + json_escape(stdout, dir); /* json_escape emits its own quotes (bu) */ | |
| 1434 | + fputs(",\"max_chains\":", stdout); | |
| 1435 | + fprintf(stdout, "%d,\"max_thoughts_each\":%d," | |
| 1436 | + "\"max_thought_history\":%lld}\n", | |
| 1437 | + MAX_CHAINS, MAX_THOUGHTS_EACH, read_max_history()); | |
| 1438 | +} | |
| 1439 | + | |
| 1440 | +/* Load chains.json (or an empty doc). Caller frees doc. */ | |
| 1441 | +static yyjson_doc *load_chains(void) | |
| 1442 | +{ | |
| 1443 | + char path[1200]; | |
| 1444 | + char *txt; | |
| 1445 | + size_t len = 0; | |
| 1446 | + yyjson_doc *doc; | |
| 1447 | + chains_path(path, sizeof path); | |
| 1448 | + (void)len; | |
| 1449 | + txt = read_file(path, &len); | |
| 1450 | + if (txt) { | |
| 1451 | + doc = yyjson_read(txt, strlen(txt), 0); | |
| 1452 | + free(txt); | |
| 1453 | + } else { | |
| 1454 | + doc = yyjson_read("{\"chains\":[]}", 13, 0); | |
| 1455 | + } | |
| 1456 | + return doc; | |
| 1457 | +} | |
| 1458 | + | |
| 1459 | +static void api_chains(void) | |
| 1460 | +{ | |
| 1461 | + yyjson_doc *doc = load_chains(); | |
| 1462 | + yyjson_val *root, *chains; | |
| 1463 | + buf_t b; | |
| 1464 | + size_t i, n = 0, total = 0; | |
| 1465 | + | |
| 1466 | + if (!doc) { api_err("state unreadable"); return; } | |
| 1467 | + root = yyjson_doc_get_root(doc); | |
| 1468 | + chains = yyjson_is_obj(root) ? yyjson_obj_get(root, "chains") : NULL; | |
| 1469 | + if (yyjson_is_arr(chains)) n = yyjson_arr_size(chains); | |
| 1470 | + | |
| 1471 | + buf_init(&b); | |
| 1472 | + buf_addf(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"count\":%zu,", n); | |
| 1473 | + { | |
| 1474 | + char nm[128]; | |
| 1475 | + state_dir_name(nm, sizeof nm); | |
| 1476 | + buf_str(&b, "\"state_dir_name\":"); | |
| 1477 | + json_escape_buf(&b, nm); | |
| 1478 | + } | |
| 1479 | + buf_str(&b, ",\"chains\":["); | |
| 1480 | + for (i = 0; i < n; i++) { | |
| 1481 | + yyjson_val *c = yyjson_arr_get(chains, i); | |
| 1482 | + yyjson_val *v, *ths; | |
| 1483 | + size_t cnt = 0; | |
| 1484 | + const char *last = ""; | |
| 1485 | + if (!yyjson_is_obj(c)) continue; | |
| 1486 | + ths = yyjson_obj_get(c, "thoughts"); | |
| 1487 | + if (yyjson_is_arr(ths)) cnt = yyjson_arr_size(ths); | |
| 1488 | + total += cnt; | |
| 1489 | + if (cnt) { | |
| 1490 | + yyjson_val *lt = yyjson_arr_get_last(ths); | |
| 1491 | + if (yyjson_is_obj(lt)) { | |
| 1492 | + v = yyjson_obj_get(lt, "thought"); | |
| 1493 | + if (yyjson_is_str(v) && yyjson_get_str(v)) last = yyjson_get_str(v); | |
| 1494 | + } | |
| 1495 | + } | |
| 1496 | + if (i) buf_str(&b, ","); | |
| 1497 | + buf_str(&b, "{\"id\":"); | |
| 1498 | + v = yyjson_obj_get(c, "id"); | |
| 1499 | + if (yyjson_is_str(v)) json_escape_buf(&b, yyjson_get_str(v)); | |
| 1500 | + else buf_str(&b, "\"\""); | |
| 1501 | + v = yyjson_obj_get(c, "started_at"); | |
| 1502 | + buf_addf(&b, ",\"started_at\":%lld,", | |
| 1503 | + yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0LL); | |
| 1504 | + v = yyjson_obj_get(c, "updated_at"); | |
| 1505 | + buf_addf(&b, "\"updated_at\":%lld,", | |
| 1506 | + yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0LL); | |
| 1507 | + buf_addf(&b, "\"thoughts\":%zu,", cnt); | |
| 1508 | + buf_str(&b, "\"branches\":["); | |
| 1509 | + { | |
| 1510 | + yyjson_val *brs = yyjson_obj_get(c, "branches"); | |
| 1511 | + if (yyjson_is_arr(brs)) { | |
| 1512 | + size_t j, bn = yyjson_arr_size(brs); | |
| 1513 | + for (j = 0; j < bn; j++) { | |
| 1514 | + yyjson_val *bv = yyjson_arr_get(brs, j); | |
| 1515 | + if (j) buf_str(&b, ","); | |
| 1516 | + if (yyjson_is_str(bv)) json_escape_buf(&b, yyjson_get_str(bv)); | |
| 1517 | + else buf_str(&b, "\"\""); | |
| 1518 | + } | |
| 1519 | + } | |
| 1520 | + } | |
| 1521 | + buf_str(&b, "],\"last_head\":"); | |
| 1522 | + { /* first line of the last thought, clamped to 160 bytes */ | |
| 1523 | + char head[200]; | |
| 1524 | + size_t k = 0; | |
| 1525 | + for (; last[k] && k < 160 && last[k] != '\n'; k++) head[k] = last[k]; | |
| 1526 | + head[k] = '\0'; | |
| 1527 | + json_escape_buf(&b, head); | |
| 1528 | + } | |
| 1529 | + buf_addf(&b, ",\"truncated\":%s}", cnt >= MAX_THOUGHTS_EACH ? "true" : "false"); | |
| 1530 | + } | |
| 1531 | + buf_str(&b, "]}"); | |
| 1532 | + (void)total; | |
| 1533 | + json_headers(); | |
| 1534 | + if (b.p) fwrite(b.p, 1, b.n, stdout); | |
| 1535 | + fputc('\n', stdout); | |
| 1536 | + buf_free(&b); | |
| 1537 | + yyjson_doc_free(doc); | |
| 1538 | +} | |
| 1539 | + | |
| 1540 | +static int valid_chain_id(const char *id) | |
| 1541 | +{ | |
| 1542 | + size_t i; | |
| 1543 | + if (!id || !*id || strlen(id) > 64) return 0; | |
| 1544 | + for (i = 0; id[i]; i++) | |
| 1545 | + if (!(isalnum((unsigned char)id[i]) || id[i] == '-' || id[i] == '_')) | |
| 1546 | + return 0; | |
| 1547 | + return 1; | |
| 1548 | +} | |
| 1549 | + | |
| 1550 | +static void api_chain(const char *id) | |
| 1551 | +{ | |
| 1552 | + yyjson_doc *doc; | |
| 1553 | + yyjson_val *root, *chains, *c = NULL; | |
| 1554 | + size_t i, n; | |
| 1555 | + | |
| 1556 | + if (!valid_chain_id(id)) { api_err("invalid chain id"); return; } | |
| 1557 | + doc = load_chains(); | |
| 1558 | + if (!doc) { api_err("state unreadable"); return; } | |
| 1559 | + root = yyjson_doc_get_root(doc); | |
| 1560 | + chains = yyjson_is_obj(root) ? yyjson_obj_get(root, "chains") : NULL; | |
| 1561 | + if (yyjson_is_arr(chains)) { | |
| 1562 | + n = yyjson_arr_size(chains); | |
| 1563 | + for (i = 0; i < n; i++) { | |
| 1564 | + yyjson_val *cv = yyjson_arr_get(chains, i); | |
| 1565 | + yyjson_val *v = yyjson_is_obj(cv) ? yyjson_obj_get(cv, "id") : NULL; | |
| 1566 | + if (yyjson_is_str(v) && yyjson_get_str(v) && | |
| 1567 | + strcmp(yyjson_get_str(v), id) == 0) { c = cv; break; } | |
| 1568 | + } | |
| 1569 | + } | |
| 1570 | + if (!c) { | |
| 1571 | + yyjson_doc_free(doc); | |
| 1572 | + api_err("chain not found"); | |
| 1573 | + return; | |
| 1574 | + } | |
| 1575 | + { | |
| 1576 | + char *txt = yyjson_val_write(c, 0, NULL); | |
| 1577 | + json_headers(); | |
| 1578 | + if (txt) { | |
| 1579 | + char *obj = txt; | |
| 1580 | + fputs("{\"ok\":true,", stdout); | |
| 1581 | + fputs(obj + 1, stdout); /* drop the object's leading { */ | |
| 1582 | + fputs("\n", stdout); | |
| 1583 | + free(txt); | |
| 1584 | + } else { | |
| 1585 | + fputs("{\"ok\":false,\"error\":\"serialize failed\"}\n", stdout); | |
| 1586 | + } | |
| 1587 | + } | |
| 1588 | + yyjson_doc_free(doc); | |
| 1589 | +} | |
| 1590 | + | |
| 1591 | +static void api_stats(void) | |
| 1592 | +{ | |
| 1593 | + yyjson_doc *doc = load_chains(); | |
| 1594 | + yyjson_val *root, *chains; | |
| 1595 | + size_t i, n = 0, thoughts = 0, branches = 0, revs = 0; | |
| 1596 | + long long newest = 0; | |
| 1597 | + | |
| 1598 | + if (!doc) { api_err("state unreadable"); return; } | |
| 1599 | + root = yyjson_doc_get_root(doc); | |
| 1600 | + chains = yyjson_is_obj(root) ? yyjson_obj_get(root, "chains") : NULL; | |
| 1601 | + if (yyjson_is_arr(chains)) { | |
| 1602 | + n = yyjson_arr_size(chains); | |
| 1603 | + for (i = 0; i < n; i++) { | |
| 1604 | + yyjson_val *c = yyjson_arr_get(chains, i); | |
| 1605 | + yyjson_val *ths, *brs, *ua; | |
| 1606 | + size_t j, tn; | |
| 1607 | + if (!yyjson_is_obj(c)) continue; | |
| 1608 | + ua = yyjson_obj_get(c, "updated_at"); | |
| 1609 | + if (yyjson_is_int(ua) && yyjson_get_sint(ua) > newest) | |
| 1610 | + newest = (long long)yyjson_get_sint(ua); | |
| 1611 | + brs = yyjson_obj_get(c, "branches"); | |
| 1612 | + if (yyjson_is_arr(brs)) branches += yyjson_arr_size(brs); | |
| 1613 | + ths = yyjson_obj_get(c, "thoughts"); | |
| 1614 | + if (!yyjson_is_arr(ths)) continue; | |
| 1615 | + tn = yyjson_arr_size(ths); | |
| 1616 | + thoughts += tn; | |
| 1617 | + for (j = 0; j < tn; j++) { | |
| 1618 | + yyjson_val *tv = yyjson_arr_get(ths, j); | |
| 1619 | + if (yyjson_is_obj(tv) && | |
| 1620 | + yyjson_is_true(yyjson_obj_get(tv, "is_revision"))) | |
| 1621 | + revs++; | |
| 1622 | + } | |
| 1623 | + } | |
| 1624 | + } | |
| 1625 | + json_headers(); | |
| 1626 | + fprintf(stdout, "{\"ok\":true,\"chains\":%zu,\"thoughts\":%zu," | |
| 1627 | + "\"branches\":%zu,\"revisions\":%zu," | |
| 1628 | + "\"last_activity\":%lld,\"max_chains\":%d," | |
| 1629 | + "\"max_thoughts_each\":%d,\"max_thought_history\":%lld}\n", | |
| 1630 | + n, thoughts, branches, revs, newest, MAX_CHAINS, MAX_THOUGHTS_EACH, | |
| 1631 | + read_max_history()); | |
| 1632 | + yyjson_doc_free(doc); | |
| 1633 | +} | |
| 1634 | + | |
| 1635 | +static void api_clear(void) | |
| 1636 | +{ | |
| 1637 | + char path[1200]; | |
| 1638 | + chains_path(path, sizeof path); | |
| 1639 | + if (remove(path) != 0 && errno != ENOENT) { | |
| 1640 | +#ifdef _WIN32 | |
| 1641 | + /* Windows remove() fails on read-only files; try clearing the bit. */ | |
| 1642 | + { | |
| 1643 | + DWORD a = GetFileAttributesA(path); | |
| 1644 | + if (a != INVALID_FILE_ATTRIBUTES) { | |
| 1645 | + SetFileAttributesA(path, FILE_ATTRIBUTE_NORMAL); | |
| 1646 | + if (remove(path) != 0) { api_err("remove failed"); return; } | |
| 1647 | + } else { | |
| 1648 | + api_err("remove failed"); | |
| 1649 | + return; | |
| 1650 | + } | |
| 1651 | + } | |
| 1652 | +#else | |
| 1653 | + api_err("remove failed"); | |
| 1654 | + return; | |
| 1655 | +#endif | |
| 1656 | + } | |
| 1657 | + json_headers(); | |
| 1658 | + fputs("{\"ok\":true,\"cleared\":true}\n", stdout); | |
| 1659 | +} | |
| 1660 | + | |
| 1661 | +static int api_dispatch(const char *action, const char *qs, const char *body) | |
| 1662 | +{ | |
| 1663 | + char id[96] = ""; | |
| 1664 | + | |
| 1665 | + if (!action[0] || strcmp(action, "chains") == 0) { | |
| 1666 | + api_chains(); | |
| 1667 | + return 0; | |
| 1668 | + } | |
| 1669 | + if (strcmp(action, "chain") == 0) { | |
| 1670 | + if (!(body && json_str_field(body, "id", id, sizeof id)) && | |
| 1671 | + !(qs && *qs && get_query_val(qs, "id", id, sizeof id))) | |
| 1672 | + id[0] = '\0'; | |
| 1673 | + api_chain(id); | |
| 1674 | + return 0; | |
| 1675 | + } | |
| 1676 | + if (strcmp(action, "stats") == 0) { api_stats(); return 0; } | |
| 1677 | + if (strcmp(action, "info") == 0) { api_info(); return 0; } | |
| 1678 | + if (strcmp(action, "clear") == 0) { | |
| 1679 | + char cf[16] = ""; | |
| 1680 | + if (!(body && json_str_field(body, "confirm", cf, sizeof cf))) | |
| 1681 | + if (qs && *qs) get_query_val(qs, "confirm", cf, sizeof cf); | |
| 1682 | + if (strcmp(cf, "1") != 0 && strcmp(cf, "true") != 0) { | |
| 1683 | + api_err("confirm=1 required"); | |
| 1684 | + return 0; | |
| 1685 | + } | |
| 1686 | + api_clear(); | |
| 1687 | + return 0; | |
| 1688 | + } | |
| 1689 | + api_err("unknown action"); | |
| 1690 | + return 0; | |
| 1691 | +} | |
| 1692 | + | |
| 1693 | +/* ------------------------------------------------------------------ */ | |
| 1694 | +/* HTML mode */ | |
| 1695 | +/* ------------------------------------------------------------------ */ | |
| 1696 | + | |
| 1697 | +static void emit_ui(void) | |
| 1698 | +{ | |
| 1699 | + const char *p = UI_HTML; | |
| 1700 | + while (*p) { | |
| 1701 | + if (*p == '\001') { | |
| 1702 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", | |
| 1703 | + stdout); | |
| 1704 | + p++; | |
| 1705 | + } else if (*p == '\002') { | |
| 1706 | + fputs(SX_BOT_THEME_HANDOFF, stdout); | |
| 1707 | + p++; | |
| 1708 | + } else { | |
| 1709 | + putchar(*p++); | |
| 1710 | + } | |
| 1711 | + } | |
| 1712 | +} | |
| 1713 | + | |
| 1714 | +static void mode_html(void) | |
| 1715 | +{ | |
| 1716 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | |
| 1717 | + "Cache-Control: no-store\r\n" | |
| 1718 | + "X-Content-Type-Options: nosniff\r\n" | |
| 1719 | + "X-Frame-Options: SAMEORIGIN\r\n" | |
| 1720 | + "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " | |
| 1721 | + "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " | |
| 1722 | + "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); | |
| 1723 | + emit_ui(); | |
| 1724 | +} | |
| 1725 | + | |
| 1726 | +/* ------------------------------------------------------------------ */ | |
| 1727 | +/* main */ | |
| 1728 | +/* ------------------------------------------------------------------ */ | |
| 1729 | + | |
| 1730 | +int main(int argc, char **argv) | |
| 1731 | +{ | |
| 1732 | + const char *qs; | |
| 1733 | + char action[64] = ""; | |
| 1734 | + char *body = NULL; | |
| 1735 | + int have_action = 0; | |
| 1736 | + const char *rm; | |
| 1737 | + int is_post; | |
| 1738 | + | |
| 1739 | +#if defined(_WIN32) | |
| 1740 | + { /* MinGW text-mode stdout turns our CRLF into CRCRLF and breaks CGI | |
| 1741 | + * framing - force binary stdio. */ | |
| 1742 | + _setmode(_fileno(stdout), _O_BINARY); | |
| 1743 | + _setmode(_fileno(stdin), _O_BINARY); | |
| 1744 | + _setmode(_fileno(stderr), _O_BINARY); | |
| 1745 | + } | |
| 1746 | +#endif | |
| 1747 | + | |
| 1748 | + /* 1. Discovery metadata (unauthenticated so /plugins can probe it) */ | |
| 1749 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) | |
| 1750 | + return run_meta(); | |
| 1751 | + /* 2. MCP stdio server */ | |
| 1752 | + if (argc > 1 && strcmp(argv[1], "--mcp") == 0) return run_mcp(); | |
| 1753 | + if (argc > 1 && strcmp(argv[1], "--schema") == 0) { | |
| 1754 | + puts(SEQTHINK_TOOL_SCHEMA); | |
| 1755 | + return 0; | |
| 1756 | + } | |
| 1757 | + if (argc > 1 && strcmp(argv[1], "--version") == 0) { | |
| 1758 | + printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); | |
| 1759 | + return 0; | |
| 1760 | + } | |
| 1761 | + | |
| 1762 | + qs = getenv("QUERY_STRING"); | |
| 1763 | + if (!qs) qs = ""; | |
| 1764 | + | |
| 1765 | + have_action = get_query_val(qs, "action", action, sizeof action); | |
| 1766 | + if (!have_action && strstr(qs, "format=json")) { | |
| 1767 | + const char *fm = strstr(qs, "format=json"); | |
| 1768 | + if (fm[11] == '\0' || fm[11] == '&') { | |
| 1769 | + snprintf(action, sizeof action, "chains"); | |
| 1770 | + have_action = 1; | |
| 1771 | + } | |
| 1772 | + } | |
| 1773 | + | |
| 1774 | + rm = getenv("REQUEST_METHOD"); | |
| 1775 | + is_post = rm && strcmp(rm, "POST") == 0; | |
| 1776 | + | |
| 1777 | + if (have_action || is_post) { | |
| 1778 | + require_node_auth(); | |
| 1779 | + body = read_body(); | |
| 1780 | + if (body) { | |
| 1781 | + char jact[64] = ""; | |
| 1782 | + if (json_str_field(body, "action", jact, sizeof jact) && jact[0]) | |
| 1783 | + snprintf(action, sizeof action, "%s", jact); | |
| 1784 | + else if (!action[0]) | |
| 1785 | + snprintf(action, sizeof action, "chains"); | |
| 1786 | + } else if (!action[0]) { | |
| 1787 | + snprintf(action, sizeof action, "chains"); | |
| 1788 | + } | |
| 1789 | + { | |
| 1790 | + int rc = api_dispatch(action, qs, body); | |
| 1791 | + free(body); | |
| 1792 | + return rc; | |
| 1793 | + } | |
| 1794 | + } | |
| 1795 | + | |
| 1796 | + mode_html(); | |
| 1797 | + return 0; | |
| 1798 | +} |
| 1 | 1 | new file mode 100644 |
| index 0000000..92341a9 | ||
| --- /dev/null | ||
| +++ b/src/ui.html | ||
| @@ -0,0 +1,247 @@ | ||
| 1 | +<!DOCTYPE html> | |
| 2 | +<html> | |
| 3 | +<head> | |
| 4 | +<meta charset="utf-8"> | |
| 5 | +<meta name="viewport" content="width=device-width,initial-scale=1"> | |
| 6 | +<title>Thought Chains</title> | |
| 7 | +<!--TOKENS--> | |
| 8 | +<style> | |
| 9 | +*{box-sizing:border-box} | |
| 10 | +html,body{margin:0;padding:0} | |
| 11 | +body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;line-height:1.5} | |
| 12 | +.wrap{max-width:1180px;margin:0 auto;padding:14px} | |
| 13 | +header{display:flex;flex-wrap:wrap;align-items:center;gap:10px;margin-bottom:12px} | |
| 14 | +header h1{font-size:17px;margin:0;font-weight:700;letter-spacing:-.01em} | |
| 15 | +.chip{font-size:11px;color:var(--text-2);border:1px solid var(--line);border-radius:980px;padding:2px 10px;background:var(--bg-card)} | |
| 16 | +.chip b{color:var(--text);font-weight:600} | |
| 17 | +.spacer{flex:1} | |
| 18 | +button{background:var(--surface-2);color:var(--text);border:1px solid var(--line);border-radius:980px;padding:6px 14px;font:inherit;font-size:13px;font-weight:600;cursor:pointer} | |
| 19 | +button:hover{border-color:var(--line-2)} | |
| 20 | +button.danger{color:var(--red)} | |
| 21 | +button.primary{background:var(--blue);border-color:var(--blue);color:#fff} | |
| 22 | +.grid{display:grid;grid-template-columns:330px 1fr;gap:14px;align-items:start} | |
| 23 | +.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;overflow:hidden} | |
| 24 | +.card h2{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--text-2);margin:0;padding:10px 14px;border-bottom:1px solid var(--line);font-weight:600} | |
| 25 | +ul.chains{list-style:none;margin:0;padding:6px;max-height:70vh;overflow:auto} | |
| 26 | +ul.chains li{padding:9px 10px;border-radius:10px;cursor:pointer;border:1px solid transparent} | |
| 27 | +ul.chains li:hover{background:var(--surface-hover)} | |
| 28 | +ul.chains li.sel{background:var(--surface-2);border-color:var(--line-2)} | |
| 29 | +.cl-top{display:flex;align-items:baseline;gap:8px} | |
| 30 | +.cl-id{font-family:var(--mono);font-size:12px;color:var(--blue);font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | |
| 31 | +.cl-when{font-size:11px;color:var(--text-2);margin-left:auto;white-space:nowrap} | |
| 32 | +.cl-last{font-size:12px;color:var(--text-2);margin-top:3px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden} | |
| 33 | +.cl-meta{display:flex;gap:6px;margin-top:6px;flex-wrap:wrap} | |
| 34 | +.pill{font-size:10px;font-weight:700;border-radius:980px;padding:1px 8px;border:1px solid var(--line);color:var(--text-2)} | |
| 35 | +.pill.b{color:var(--green);border-color:var(--green)} | |
| 36 | +.pill.t{color:var(--teal);border-color:var(--teal)} | |
| 37 | +.detail .empty{padding:36px 20px;text-align:center;color:var(--text-2)} | |
| 38 | +.detail .empty code{font-family:var(--mono);color:var(--text)} | |
| 39 | +.dhead{padding:12px 16px;border-bottom:1px solid var(--line);display:flex;flex-wrap:wrap;gap:10px;align-items:center} | |
| 40 | +.dhead .did{font-family:var(--mono);font-weight:700;color:var(--blue)} | |
| 41 | +.prog{flex:1;min-width:120px;max-width:280px;height:6px;border-radius:3px;background:var(--surface-2);overflow:hidden} | |
| 42 | +.prog i{display:block;height:100%;background:var(--blue);border-radius:3px} | |
| 43 | +.tl{list-style:none;margin:0;padding:14px 16px 18px 16px;position:relative} | |
| 44 | +.tl li{position:relative;padding:0 0 16px 30px} | |
| 45 | +.tl li::before{content:"";position:absolute;left:8px;top:18px;bottom:-2px;width:2px;background:var(--line)} | |
| 46 | +.tl li:last-child::before{display:none} | |
| 47 | +.tl .dot{position:absolute;left:2px;top:4px;width:14px;height:14px;border-radius:50%;border:3px solid var(--bg-card);background:var(--blue)} | |
| 48 | +.tl li.rev .dot{background:var(--orange)} | |
| 49 | +.tl li.br .dot{background:var(--green)} | |
| 50 | +.th-head{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:4px} | |
| 51 | +.th-num{font-weight:700;font-size:13px} | |
| 52 | +.badge{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;border-radius:980px;padding:1px 8px} | |
| 53 | +.badge.rev{color:var(--orange);border:1px solid var(--orange)} | |
| 54 | +.badge.br{color:var(--green);border:1px solid var(--green)} | |
| 55 | +.badge.fin{color:var(--purple);border:1px solid var(--purple)} | |
| 56 | +.th-more{font-size:11px;color:var(--text-2)} | |
| 57 | +.th-body{white-space:pre-wrap;word-wrap:break-word;font-size:13.5px;background:var(--surface-2);border:1px solid var(--line);border-radius:10px;padding:9px 12px;margin-top:2px} | |
| 58 | +.jsonwrap{margin-top:14px} | |
| 59 | +.jsonwrap pre{background:var(--code-bg);border:1px solid var(--line);border-radius:12px;padding:12px;font-family:var(--mono);font-size:11.5px;overflow:auto;max-height:340px;margin:8px 0 0} | |
| 60 | +.errbox{margin:12px 16px;padding:10px 12px;border:1px solid var(--red);border-radius:10px;color:var(--red);font-size:13px} | |
| 61 | +#backBtn{display:none} | |
| 62 | +@media (max-width:860px){ | |
| 63 | + .grid{grid-template-columns:1fr} | |
| 64 | + body[data-view=detail] #listCard{display:none} | |
| 65 | + body:not([data-view=detail]) .tlwrap{display:none} | |
| 66 | + body:not([data-view=detail]) .dhead{display:none} | |
| 67 | + body[data-view=detail] #backBtn{display:inline-block} | |
| 68 | +} | |
| 69 | +</style> | |
| 70 | +</head> | |
| 71 | +<body> | |
| 72 | +<div class="wrap"> | |
| 73 | + <header> | |
| 74 | + <button id="backBtn" type="button">Back</button> | |
| 75 | + <h1>Thought Chains</h1> | |
| 76 | + <span class="chip" id="chipChains">chains <b>-</b></span> | |
| 77 | + <span class="chip" id="chipThoughts">thoughts <b>-</b></span> | |
| 78 | + <span class="chip" id="chipState">state <b>-</b></span> | |
| 79 | + <span class="spacer"></span> | |
| 80 | + <button id="refreshBtn" type="button">Refresh</button> | |
| 81 | + <button id="clearBtn" type="button" class="danger">Clear</button> | |
| 82 | + <button class="embed-hide" id="themeToggle" type="button" title="Toggle appearance">Theme</button> | |
| 83 | + </header> | |
| 84 | + | |
| 85 | + <div class="grid"> | |
| 86 | + <div class="card" id="listCard"> | |
| 87 | + <h2>Chains</h2> | |
| 88 | + <ul class="chains" id="chains"></ul> | |
| 89 | + </div> | |
| 90 | + | |
| 91 | + <div class="card"> | |
| 92 | + <div class="dhead" id="dhead" style="display:none"> | |
| 93 | + <button id="backBtn2" type="button">Back</button> | |
| 94 | + <span class="did" id="dId"></span> | |
| 95 | + <span class="chip" id="dCount"></span> | |
| 96 | + <div class="prog"><i id="dProg" style="width:0%"></i></div> | |
| 97 | + </div> | |
| 98 | + <div class="tlwrap"> | |
| 99 | + <div class="empty" id="empty">Loading...</div> | |
| 100 | + <ul class="tl" id="tl"></ul> | |
| 101 | + </div> | |
| 102 | + <div id="errbox" class="errbox" style="display:none"></div> | |
| 103 | + <div class="jsonwrap" style="padding:0 16px 14px"> | |
| 104 | + <button id="jsonBtn" type="button">Show JSON</button> | |
| 105 | + <pre id="json" style="display:none"></pre> | |
| 106 | + </div> | |
| 107 | + </div> | |
| 108 | + </div> | |
| 109 | +</div> | |
| 110 | +<script> | |
| 111 | +(function(){ | |
| 112 | + var q=new URLSearchParams(location.search); | |
| 113 | + var HUB=q.get('plugin')||''; | |
| 114 | + var node=q.get('node')||''; | |
| 115 | + var sid=q.get('id')||''; | |
| 116 | + var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||localStorage.getItem('bot_active_pwd')||''; | |
| 117 | + var cur=null, lastJson=''; | |
| 118 | + | |
| 119 | + function api(action,extra){ | |
| 120 | + /* Hub-proxy route when served through /plugins?plugin=..., direct node | |
| 121 | + route when opened as /plugin_seqthink. Never call /plugins?plugin= on | |
| 122 | + the node itself: that is discovery and never dispatches. */ | |
| 123 | + var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB)+'&action='+action | |
| 124 | + :'/plugin_seqthink?action='+action); | |
| 125 | + if(extra)u+='&'+extra; | |
| 126 | + if(node)u+='&node='+encodeURIComponent(node); | |
| 127 | + if(sid)u+='&id='+encodeURIComponent(sid); | |
| 128 | + if(pwd)u+='&pwd='+encodeURIComponent(pwd); | |
| 129 | + return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{}}).then(function(r){return r.json();}); | |
| 130 | + } | |
| 131 | + function esc(s){return String(s==null?'':s).replace(/[&<>"]/g,function(c){ | |
| 132 | + return {'&':'&','<':'<','>':'>','"':'"'}[c];});} | |
| 133 | + function fmt(ts){if(!ts)return '-';try{return new Date(ts*1000).toLocaleString();}catch(e){return String(ts);}} | |
| 134 | + function showErr(m){var e=document.getElementById('errbox');e.textContent=m;e.style.display='block';} | |
| 135 | + function clearErr(){document.getElementById('errbox').style.display='none';} | |
| 136 | + function setJson(o){lastJson=JSON.stringify(o,null,2);var j=document.getElementById('json');j.textContent=lastJson;} | |
| 137 | + | |
| 138 | + function renderList(d){ | |
| 139 | + var ul=document.getElementById('chains'); | |
| 140 | + var cs=(d&&d.chains)||[]; | |
| 141 | + document.getElementById('chipChains').innerHTML='chains <b>'+((d&&d.count!=null)?d.count:cs.length)+'</b>'; | |
| 142 | + var tot=0;cs.forEach(function(c){tot+=c.thoughts||0;}); | |
| 143 | + document.getElementById('chipThoughts').innerHTML='thoughts <b>'+tot+'</b>'; | |
| 144 | + document.getElementById('chipState').innerHTML='state <b>'+esc((d&&d.state_dir_name)||'-')+'</b>'; | |
| 145 | + ul.innerHTML=''; | |
| 146 | + if(!cs.length){ | |
| 147 | + if(!cur)document.getElementById('empty').innerHTML= | |
| 148 | + 'No thought chains recorded yet.<br>Call the <code>sequentialthinking</code> MCP tool '+ | |
| 149 | + '(<code>plugin_seqthink --mcp</code>) and press Refresh.'; | |
| 150 | + return; | |
| 151 | + } | |
| 152 | + cs.forEach(function(c){ | |
| 153 | + var li=document.createElement('li'); | |
| 154 | + if(c.id===cur)li.className='sel'; | |
| 155 | + var badges='<span class="pill t">thoughts '+esc(c.thoughts)+'</span>'; | |
| 156 | + if(c.branches&&c.branches.length)badges+='<span class="pill b">branches '+c.branches.length+'</span>'; | |
| 157 | + if(c.truncated)badges+='<span class="pill">capped</span>'; | |
| 158 | + li.innerHTML='<div class="cl-top"><span class="cl-id">'+esc(c.id)+'</span>'+ | |
| 159 | + '<span class="cl-when">'+esc(fmt(c.updated_at))+'</span></div>'+ | |
| 160 | + '<div class="cl-last">'+esc(c.last_head||'')+'</div>'+ | |
| 161 | + '<div class="cl-meta">'+badges+'</div>'; | |
| 162 | + li.onclick=function(){open(c.id);}; | |
| 163 | + ul.appendChild(li); | |
| 164 | + }); | |
| 165 | + } | |
| 166 | + | |
| 167 | + function renderDetail(d){ | |
| 168 | + var tl=document.getElementById('tl'); | |
| 169 | + var th=(d&&d.thoughts)||[]; | |
| 170 | + document.getElementById('dhead').style.display=th.length?'flex':'none'; | |
| 171 | + document.getElementById('dId').textContent=(d&&d.id)||''; | |
| 172 | + var last=th.length?th[th.length-1]:null; | |
| 173 | + var tt=last?(last.total_thoughts||0):0, tn=last?(last.thought_number||0):0; | |
| 174 | + document.getElementById('dCount').textContent=th.length+' thoughts'; | |
| 175 | + document.getElementById('dProg').style.width=(tt>0?Math.min(100,Math.round(100*tn/tt)):0)+'%'; | |
| 176 | + document.getElementById('empty').style.display=th.length?'none':'block'; | |
| 177 | + if(!th.length&&!document.getElementById('empty').textContent.trim()) | |
| 178 | + document.getElementById('empty').textContent='No thoughts in this chain.'; | |
| 179 | + tl.innerHTML=''; | |
| 180 | + th.forEach(function(t){ | |
| 181 | + var li=document.createElement('li'); | |
| 182 | + var cls=t.is_revision?'rev':(t.branch_from?'br':''); | |
| 183 | + if(cls)li.className=cls; | |
| 184 | + var badges='<span class="th-num">#'+esc(t.thought_number)+' / '+esc(t.total_thoughts)+'</span>'; | |
| 185 | + if(t.is_revision)badges+='<span class="badge rev">revision'+(t.revises?' of #'+esc(t.revises):'')+'</span>'; | |
| 186 | + if(t.branch_from)badges+='<span class="badge br">branch from #'+esc(t.branch_from)+ | |
| 187 | + (t.branch_id?' · '+esc(t.branch_id):'')+'</span>'; | |
| 188 | + if(!t.next_needed)badges+='<span class="badge fin">final</span>'; | |
| 189 | + var more=''; | |
| 190 | + if(t.needs_more)more=' <span class="th-more">needs more thoughts</span>'; | |
| 191 | + li.innerHTML='<span class="dot"></span>'+ | |
| 192 | + '<div class="th-head">'+badges+more+'</div>'+ | |
| 193 | + '<div class="th-body">'+esc(t.thought)+'</div>'; | |
| 194 | + tl.appendChild(li); | |
| 195 | + }); | |
| 196 | + } | |
| 197 | + | |
| 198 | + function open(id){ | |
| 199 | + cur=id; | |
| 200 | + document.body.setAttribute('data-view','detail'); | |
| 201 | + clearErr(); | |
| 202 | + api('chain','id='+encodeURIComponent(id)).then(function(d){ | |
| 203 | + if(!d||d.ok===false){showErr((d&&d.error)||'chain failed');return;} | |
| 204 | + renderDetail(d); | |
| 205 | + setJson(d); | |
| 206 | + }).catch(function(e){showErr('chain: '+e);}); | |
| 207 | + refreshList(); | |
| 208 | + } | |
| 209 | + function back(){ | |
| 210 | + cur=null; | |
| 211 | + document.body.removeAttribute('data-view'); | |
| 212 | + document.getElementById('tl').innerHTML=''; | |
| 213 | + document.getElementById('dhead').style.display='none'; | |
| 214 | + refreshList(); | |
| 215 | + } | |
| 216 | + function refreshList(){ | |
| 217 | + api('chains').then(function(d){ | |
| 218 | + if(!d||d.ok===false){showErr((d&&d.error)||'chains failed');return;} | |
| 219 | + renderList(d); | |
| 220 | + if(!cur)setJson(d); | |
| 221 | + }).catch(function(e){showErr('chains: '+e);}); | |
| 222 | + } | |
| 223 | + document.getElementById('refreshBtn').onclick=function(){cur?open(cur):refreshList();}; | |
| 224 | + document.getElementById('backBtn').onclick=back; | |
| 225 | + document.getElementById('backBtn2').onclick=back; | |
| 226 | + document.getElementById('jsonBtn').onclick=function(){ | |
| 227 | + var j=document.getElementById('json'); | |
| 228 | + var on=j.style.display!=='none'; | |
| 229 | + j.style.display=on?'none':'block'; | |
| 230 | + this.textContent=on?'Show JSON':'Hide JSON'; | |
| 231 | + }; | |
| 232 | + document.getElementById('clearBtn').onclick=function(){ | |
| 233 | + if(!window.confirm('Delete all recorded thought chains? This cannot be undone.'))return; | |
| 234 | + api('clear','confirm=1').then(function(d){ | |
| 235 | + if(!d||d.ok===false){showErr((d&&d.error)||'clear failed');return;} | |
| 236 | + cur=null;back(); | |
| 237 | + }).catch(function(e){showErr('clear: '+e);}); | |
| 238 | + }; | |
| 239 | + document.getElementById('themeToggle').onclick=function(){ | |
| 240 | + var t=document.documentElement.getAttribute('data-theme')==='dark'?'light':'dark'; | |
| 241 | + window.sxApplyTheme(t); | |
| 242 | + }; | |
| 243 | + refreshList(); | |
| 244 | +})(); | |
| 245 | +</script> | |
| 246 | +</body> | |
| 247 | +</html> |
| 1 | 1 | new file mode 100644 |
| index 0000000..6e3794a | ||
| --- /dev/null | ||
| +++ b/src/ui_html.h | ||
| @@ -0,0 +1,255 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | |
| 2 | +#ifndef SX_SEQTHINK_UI_HTML_H | |
| 3 | +#define SX_SEQTHINK_UI_HTML_H | |
| 4 | + | |
| 5 | +static const char *UI_HTML = | |
| 6 | + "<!DOCTYPE html>\n" | |
| 7 | + "<html>\n" | |
| 8 | + "<head>\n" | |
| 9 | + "<meta charset=\"utf-8\">\n" | |
| 10 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | |
| 11 | + "<title>Thought Chains</title>\n" | |
| 12 | + "\001\n" | |
| 13 | + "<style>\n" | |
| 14 | + "*{box-sizing:border-box}\n" | |
| 15 | + "html,body{margin:0;padding:0}\n" | |
| 16 | + "body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;line-height:1.5}\n" | |
| 17 | + ".wrap{max-width:1180px;margin:0 auto;padding:14px}\n" | |
| 18 | + "header{display:flex;flex-wrap:wrap;align-items:center;gap:10px;margin-bottom:12px}\n" | |
| 19 | + "header h1{font-size:17px;margin:0;font-weight:700;letter-spacing:-.01em}\n" | |
| 20 | + ".chip{font-size:11px;color:var(--text-2);border:1px solid var(--line);border-radius:980px;padding:2px 10px;background:var(--bg-card)}\n" | |
| 21 | + ".chip b{color:var(--text);font-weight:600}\n" | |
| 22 | + ".spacer{flex:1}\n" | |
| 23 | + "button{background:var(--surface-2);color:var(--text);border:1px solid var(--line);border-radius:980px;padding:6px 14px;font:inherit;font-size:13px;font-weight:600;cursor:pointer}\n" | |
| 24 | + "button:hover{border-color:var(--line-2)}\n" | |
| 25 | + "button.danger{color:var(--red)}\n" | |
| 26 | + "button.primary{background:var(--blue);border-color:var(--blue);color:#fff}\n" | |
| 27 | + ".grid{display:grid;grid-template-columns:330px 1fr;gap:14px;align-items:start}\n" | |
| 28 | + ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;overflow:hidden}\n" | |
| 29 | + ".card h2{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--text-2);margin:0;padding:10px 14px;border-bottom:1px solid var(--line);font-weight:600}\n" | |
| 30 | + "ul.chains{list-style:none;margin:0;padding:6px;max-height:70vh;overflow:auto}\n" | |
| 31 | + "ul.chains li{padding:9px 10px;border-radius:10px;cursor:pointer;border:1px solid transparent}\n" | |
| 32 | + "ul.chains li:hover{background:var(--surface-hover)}\n" | |
| 33 | + "ul.chains li.sel{background:var(--surface-2);border-color:var(--line-2)}\n" | |
| 34 | + ".cl-top{display:flex;align-items:baseline;gap:8px}\n" | |
| 35 | + ".cl-id{font-family:var(--mono);font-size:12px;color:var(--blue);font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" | |
| 36 | + ".cl-when{font-size:11px;color:var(--text-2);margin-left:auto;white-space:nowrap}\n" | |
| 37 | + ".cl-last{font-size:12px;color:var(--text-2);margin-top:3px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}\n" | |
| 38 | + ".cl-meta{display:flex;gap:6px;margin-top:6px;flex-wrap:wrap}\n" | |
| 39 | + ".pill{font-size:10px;font-weight:700;border-radius:980px;padding:1px 8px;border:1px solid var(--line);color:var(--text-2)}\n" | |
| 40 | + ".pill.b{color:var(--green);border-color:var(--green)}\n" | |
| 41 | + ".pill.t{color:var(--teal);border-color:var(--teal)}\n" | |
| 42 | + ".detail .empty{padding:36px 20px;text-align:center;color:var(--text-2)}\n" | |
| 43 | + ".detail .empty code{font-family:var(--mono);color:var(--text)}\n" | |
| 44 | + ".dhead{padding:12px 16px;border-bottom:1px solid var(--line);display:flex;flex-wrap:wrap;gap:10px;align-items:center}\n" | |
| 45 | + ".dhead .did{font-family:var(--mono);font-weight:700;color:var(--blue)}\n" | |
| 46 | + ".prog{flex:1;min-width:120px;max-width:280px;height:6px;border-radius:3px;background:var(--surface-2);overflow:hidden}\n" | |
| 47 | + ".prog i{display:block;height:100%;background:var(--blue);border-radius:3px}\n" | |
| 48 | + ".tl{list-style:none;margin:0;padding:14px 16px 18px 16px;position:relative}\n" | |
| 49 | + ".tl li{position:relative;padding:0 0 16px 30px}\n" | |
| 50 | + ".tl li::before{content:\"\";position:absolute;left:8px;top:18px;bottom:-2px;width:2px;background:var(--line)}\n" | |
| 51 | + ".tl li:last-child::before{display:none}\n" | |
| 52 | + ".tl .dot{position:absolute;left:2px;top:4px;width:14px;height:14px;border-radius:50%;border:3px solid var(--bg-card);background:var(--blue)}\n" | |
| 53 | + ".tl li.rev .dot{background:var(--orange)}\n" | |
| 54 | + ".tl li.br .dot{background:var(--green)}\n" | |
| 55 | + ".th-head{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:4px}\n" | |
| 56 | + ".th-num{font-weight:700;font-size:13px}\n" | |
| 57 | + ".badge{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;border-radius:980px;padding:1px 8px}\n" | |
| 58 | + ".badge.rev{color:var(--orange);border:1px solid var(--orange)}\n" | |
| 59 | + ".badge.br{color:var(--green);border:1px solid var(--green)}\n" | |
| 60 | + ".badge.fin{color:var(--purple);border:1px solid var(--purple)}\n" | |
| 61 | + ".th-more{font-size:11px;color:var(--text-2)}\n" | |
| 62 | + ".th-body{white-space:pre-wrap;word-wrap:break-word;font-size:13.5px;background:var(--surface-2);border:1px solid var(--line);border-radius:10px;padding:9px 12px;margin-top:2px}\n" | |
| 63 | + ".jsonwrap{margin-top:14px}\n" | |
| 64 | + ".jsonwrap pre{background:var(--code-bg);border:1px solid var(--line);border-radius:12px;padding:12px;font-family:var(--mono);font-size:11.5px;overflow:auto;max-height:340px;margin:8px 0 0}\n" | |
| 65 | + ".errbox{margin:12px 16px;padding:10px 12px;border:1px solid var(--red);border-radius:10px;color:var(--red);font-size:13px}\n" | |
| 66 | + "#backBtn{display:none}\n" | |
| 67 | + "@media (max-width:860px){\n" | |
| 68 | + " .grid{grid-template-columns:1fr}\n" | |
| 69 | + " body[data-view=detail] #listCard{display:none}\n" | |
| 70 | + " body:not([data-view=detail]) .tlwrap{display:none}\n" | |
| 71 | + " body:not([data-view=detail]) .dhead{display:none}\n" | |
| 72 | + " body[data-view=detail] #backBtn{display:inline-block}\n" | |
| 73 | + "}\n" | |
| 74 | + "</style>\n" | |
| 75 | + "</head>\n" | |
| 76 | + "<body>\n" | |
| 77 | + "<div class=\"wrap\">\n" | |
| 78 | + " <header>\n" | |
| 79 | + " <button id=\"backBtn\" type=\"button\">Back</button>\n" | |
| 80 | + " <h1>Thought Chains</h1>\n" | |
| 81 | + " <span class=\"chip\" id=\"chipChains\">chains <b>-</b></span>\n" | |
| 82 | + " <span class=\"chip\" id=\"chipThoughts\">thoughts <b>-</b></span>\n" | |
| 83 | + " <span class=\"chip\" id=\"chipState\">state <b>-</b></span>\n" | |
| 84 | + " <span class=\"spacer\"></span>\n" | |
| 85 | + " <button id=\"refreshBtn\" type=\"button\">Refresh</button>\n" | |
| 86 | + " <button id=\"clearBtn\" type=\"button\" class=\"danger\">Clear</button>\n" | |
| 87 | + " <button class=\"embed-hide\" id=\"themeToggle\" type=\"button\" title=\"Toggle appearance\">Theme</button>\n" | |
| 88 | + " </header>\n" | |
| 89 | + "\n" | |
| 90 | + " <div class=\"grid\">\n" | |
| 91 | + " <div class=\"card\" id=\"listCard\">\n" | |
| 92 | + " <h2>Chains</h2>\n" | |
| 93 | + " <ul class=\"chains\" id=\"chains\"></ul>\n" | |
| 94 | + " </div>\n" | |
| 95 | + "\n" | |
| 96 | + " <div class=\"card\">\n" | |
| 97 | + " <div class=\"dhead\" id=\"dhead\" style=\"display:none\">\n" | |
| 98 | + " <button id=\"backBtn2\" type=\"button\">Back</button>\n" | |
| 99 | + " <span class=\"did\" id=\"dId\"></span>\n" | |
| 100 | + " <span class=\"chip\" id=\"dCount\"></span>\n" | |
| 101 | + " <div class=\"prog\"><i id=\"dProg\" style=\"width:0%\"></i></div>\n" | |
| 102 | + " </div>\n" | |
| 103 | + " <div class=\"tlwrap\">\n" | |
| 104 | + " <div class=\"empty\" id=\"empty\">Loading...</div>\n" | |
| 105 | + " <ul class=\"tl\" id=\"tl\"></ul>\n" | |
| 106 | + " </div>\n" | |
| 107 | + " <div id=\"errbox\" class=\"errbox\" style=\"display:none\"></div>\n" | |
| 108 | + " <div class=\"jsonwrap\" style=\"padding:0 16px 14px\">\n" | |
| 109 | + " <button id=\"jsonBtn\" type=\"button\">Show JSON</button>\n" | |
| 110 | + " <pre id=\"json\" style=\"display:none\"></pre>\n" | |
| 111 | + " </div>\n" | |
| 112 | + " </div>\n" | |
| 113 | + " </div>\n" | |
| 114 | + "</div>\n" | |
| 115 | + "<script>\n" | |
| 116 | + "(function(){\n" | |
| 117 | + " var q=new URLSearchParams(location.search);\n" | |
| 118 | + " var HUB=q.get('plugin')||'';\n" | |
| 119 | + " var node=q.get('node')||'';\n" | |
| 120 | + " var sid=q.get('id')||'';\n" | |
| 121 | + " var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||localStorage.getItem('bot_active_pwd')||'';\n" | |
| 122 | + " var cur=null, lastJson='';\n" | |
| 123 | + "\n" | |
| 124 | + " function api(action,extra){\n" | |
| 125 | + " /* Hub-proxy route when served through /plugins?plugin=..., direct node\n" | |
| 126 | + " route when opened as /plugin_seqthink. Never call /plugins?plugin= on\n" | |
| 127 | + " the node itself: that is discovery and never dispatches. */\n" | |
| 128 | + " var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB)+'&action='+action\n" | |
| 129 | + " :'/plugin_seqthink?action='+action);\n" | |
| 130 | + " if(extra)u+='&'+extra;\n" | |
| 131 | + " if(node)u+='&node='+encodeURIComponent(node);\n" | |
| 132 | + " if(sid)u+='&id='+encodeURIComponent(sid);\n" | |
| 133 | + " if(pwd)u+='&pwd='+encodeURIComponent(pwd);\n" | |
| 134 | + " return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{}}).then(function(r){return r.json();});\n" | |
| 135 | + " }\n" | |
| 136 | + " function esc(s){return String(s==null?'':s).replace(/[&<>\"]/g,function(c){\n" | |
| 137 | + " return {'&':'&','<':'<','>':'>','\"':'"'}[c];});}\n" | |
| 138 | + " function fmt(ts){if(!ts)return '-';try{return new Date(ts*1000).toLocaleString();}catch(e){return String(ts);}}\n" | |
| 139 | + " function showErr(m){var e=document.getElementById('errbox');e.textContent=m;e.style.display='block';}\n" | |
| 140 | + " function clearErr(){document.getElementById('errbox').style.display='none';}\n" | |
| 141 | + " function setJson(o){lastJson=JSON.stringify(o,null,2);var j=document.getElementById('json');j.textContent=lastJson;}\n" | |
| 142 | + "\n" | |
| 143 | + " function renderList(d){\n" | |
| 144 | + " var ul=document.getElementById('chains');\n" | |
| 145 | + " var cs=(d&&d.chains)||[];\n" | |
| 146 | + " document.getElementById('chipChains').innerHTML='chains <b>'+((d&&d.count!=null)?d.count:cs.length)+'</b>';\n" | |
| 147 | + " var tot=0;cs.forEach(function(c){tot+=c.thoughts||0;});\n" | |
| 148 | + " document.getElementById('chipThoughts').innerHTML='thoughts <b>'+tot+'</b>';\n" | |
| 149 | + " document.getElementById('chipState').innerHTML='state <b>'+esc((d&&d.state_dir_name)||'-')+'</b>';\n" | |
| 150 | + " ul.innerHTML='';\n" | |
| 151 | + " if(!cs.length){\n" | |
| 152 | + " if(!cur)document.getElementById('empty').innerHTML=\n" | |
| 153 | + " 'No thought chains recorded yet.<br>Call the <code>sequentialthinking</code> MCP tool '+\n" | |
| 154 | + " '(<code>plugin_seqthink --mcp</code>) and press Refresh.';\n" | |
| 155 | + " return;\n" | |
| 156 | + " }\n" | |
| 157 | + " cs.forEach(function(c){\n" | |
| 158 | + " var li=document.createElement('li');\n" | |
| 159 | + " if(c.id===cur)li.className='sel';\n" | |
| 160 | + " var badges='<span class=\"pill t\">thoughts '+esc(c.thoughts)+'</span>';\n" | |
| 161 | + " if(c.branches&&c.branches.length)badges+='<span class=\"pill b\">branches '+c.branches.length+'</span>';\n" | |
| 162 | + " if(c.truncated)badges+='<span class=\"pill\">capped</span>';\n" | |
| 163 | + " li.innerHTML='<div class=\"cl-top\"><span class=\"cl-id\">'+esc(c.id)+'</span>'+\n" | |
| 164 | + " '<span class=\"cl-when\">'+esc(fmt(c.updated_at))+'</span></div>'+\n" | |
| 165 | + " '<div class=\"cl-last\">'+esc(c.last_head||'')+'</div>'+\n" | |
| 166 | + " '<div class=\"cl-meta\">'+badges+'</div>';\n" | |
| 167 | + " li.onclick=function(){open(c.id);};\n" | |
| 168 | + " ul.appendChild(li);\n" | |
| 169 | + " });\n" | |
| 170 | + " }\n" | |
| 171 | + "\n" | |
| 172 | + " function renderDetail(d){\n" | |
| 173 | + " var tl=document.getElementById('tl');\n" | |
| 174 | + " var th=(d&&d.thoughts)||[];\n" | |
| 175 | + " document.getElementById('dhead').style.display=th.length?'flex':'none';\n" | |
| 176 | + " document.getElementById('dId').textContent=(d&&d.id)||'';\n" | |
| 177 | + " var last=th.length?th[th.length-1]:null;\n" | |
| 178 | + " var tt=last?(last.total_thoughts||0):0, tn=last?(last.thought_number||0):0;\n" | |
| 179 | + " document.getElementById('dCount').textContent=th.length+' thoughts';\n" | |
| 180 | + " document.getElementById('dProg').style.width=(tt>0?Math.min(100,Math.round(100*tn/tt)):0)+'%';\n" | |
| 181 | + " document.getElementById('empty').style.display=th.length?'none':'block';\n" | |
| 182 | + " if(!th.length&&!document.getElementById('empty').textContent.trim())\n" | |
| 183 | + " document.getElementById('empty').textContent='No thoughts in this chain.';\n" | |
| 184 | + " tl.innerHTML='';\n" | |
| 185 | + " th.forEach(function(t){\n" | |
| 186 | + " var li=document.createElement('li');\n" | |
| 187 | + " var cls=t.is_revision?'rev':(t.branch_from?'br':'');\n" | |
| 188 | + " if(cls)li.className=cls;\n" | |
| 189 | + " var badges='<span class=\"th-num\">#'+esc(t.thought_number)+' / '+esc(t.total_thoughts)+'</span>';\n" | |
| 190 | + " if(t.is_revision)badges+='<span class=\"badge rev\">revision'+(t.revises?' of #'+esc(t.revises):'')+'</span>';\n" | |
| 191 | + " if(t.branch_from)badges+='<span class=\"badge br\">branch from #'+esc(t.branch_from)+\n" | |
| 192 | + " (t.branch_id?' · '+esc(t.branch_id):'')+'</span>';\n" | |
| 193 | + " if(!t.next_needed)badges+='<span class=\"badge fin\">final</span>';\n" | |
| 194 | + " var more='';\n" | |
| 195 | + " if(t.needs_more)more=' <span class=\"th-more\">needs more thoughts</span>';\n" | |
| 196 | + " li.innerHTML='<span class=\"dot\"></span>'+\n" | |
| 197 | + " '<div class=\"th-head\">'+badges+more+'</div>'+\n" | |
| 198 | + " '<div class=\"th-body\">'+esc(t.thought)+'</div>';\n" | |
| 199 | + " tl.appendChild(li);\n" | |
| 200 | + " });\n" | |
| 201 | + " }\n" | |
| 202 | + "\n" | |
| 203 | + " function open(id){\n" | |
| 204 | + " cur=id;\n" | |
| 205 | + " document.body.setAttribute('data-view','detail');\n" | |
| 206 | + " clearErr();\n" | |
| 207 | + " api('chain','id='+encodeURIComponent(id)).then(function(d){\n" | |
| 208 | + " if(!d||d.ok===false){showErr((d&&d.error)||'chain failed');return;}\n" | |
| 209 | + " renderDetail(d);\n" | |
| 210 | + " setJson(d);\n" | |
| 211 | + " }).catch(function(e){showErr('chain: '+e);});\n" | |
| 212 | + " refreshList();\n" | |
| 213 | + " }\n" | |
| 214 | + " function back(){\n" | |
| 215 | + " cur=null;\n" | |
| 216 | + " document.body.removeAttribute('data-view');\n" | |
| 217 | + " document.getElementById('tl').innerHTML='';\n" | |
| 218 | + " document.getElementById('dhead').style.display='none';\n" | |
| 219 | + " refreshList();\n" | |
| 220 | + " }\n" | |
| 221 | + " function refreshList(){\n" | |
| 222 | + " api('chains').then(function(d){\n" | |
| 223 | + " if(!d||d.ok===false){showErr((d&&d.error)||'chains failed');return;}\n" | |
| 224 | + " renderList(d);\n" | |
| 225 | + " if(!cur)setJson(d);\n" | |
| 226 | + " }).catch(function(e){showErr('chains: '+e);});\n" | |
| 227 | + " }\n" | |
| 228 | + " document.getElementById('refreshBtn').onclick=function(){cur?open(cur):refreshList();};\n" | |
| 229 | + " document.getElementById('backBtn').onclick=back;\n" | |
| 230 | + " document.getElementById('backBtn2').onclick=back;\n" | |
| 231 | + " document.getElementById('jsonBtn').onclick=function(){\n" | |
| 232 | + " var j=document.getElementById('json');\n" | |
| 233 | + " var on=j.style.display!=='none';\n" | |
| 234 | + " j.style.display=on?'none':'block';\n" | |
| 235 | + " this.textContent=on?'Show JSON':'Hide JSON';\n" | |
| 236 | + " };\n" | |
| 237 | + " document.getElementById('clearBtn').onclick=function(){\n" | |
| 238 | + " if(!window.confirm('Delete all recorded thought chains? This cannot be undone.'))return;\n" | |
| 239 | + " api('clear','confirm=1').then(function(d){\n" | |
| 240 | + " if(!d||d.ok===false){showErr((d&&d.error)||'clear failed');return;}\n" | |
| 241 | + " cur=null;back();\n" | |
| 242 | + " }).catch(function(e){showErr('clear: '+e);});\n" | |
| 243 | + " };\n" | |
| 244 | + " document.getElementById('themeToggle').onclick=function(){\n" | |
| 245 | + " var t=document.documentElement.getAttribute('data-theme')==='dark'?'light':'dark';\n" | |
| 246 | + " window.sxApplyTheme(t);\n" | |
| 247 | + " };\n" | |
| 248 | + " refreshList();\n" | |
| 249 | + "})();\n" | |
| 250 | + "</script>\n" | |
| 251 | + "\002</body>\n" | |
| 252 | + "</html>\n" | |
| 253 | + ; | |
| 254 | + | |
| 255 | +#endif /* SX_SEQTHINK_UI_HTML_H */ |
| 1 | 1 | new file mode 100644 |
| index 0000000..eafd5c3 | ||
| --- /dev/null | ||
| +++ b/tests/e2e.py | ||
| @@ -0,0 +1,374 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""tests/e2e.py - viewport and live-behaviour checks for the plugin_seqthink UI. | |
| 3 | + | |
| 4 | +Serves the plugin through a tiny CGI-ish HTTP shim on a loopback port, with a | |
| 5 | +state directory seeded by real --mcp sessions (thoughts, a revision, a branch, | |
| 6 | +unicode). Opens the page with Playwright at 1440 / 1024 / 390 CSS pixels in | |
| 7 | +BOTH themes and asserts: no console error, no horizontal overflow, the chain | |
| 8 | +list is populated from action=chains, selecting a chain renders the timeline | |
| 9 | +with revision and branch badges, the progress bar tracks the last thought, | |
| 10 | +Show JSON reveals parsable JSON, the bot theme handoff works, and Clear | |
| 11 | +(behind confirm) empties the store. | |
| 12 | + | |
| 13 | +Skips cleanly (exit 0) when Playwright is not installed, so `make test` stays | |
| 14 | +offline-only. | |
| 15 | + | |
| 16 | + python3 tests/e2e.py # run if Playwright is available | |
| 17 | + python3 tests/e2e.py --strict # exit 2 when Playwright is missing | |
| 18 | +""" | |
| 19 | + | |
| 20 | +import argparse | |
| 21 | +import http.server | |
| 22 | +import json | |
| 23 | +import os | |
| 24 | +import subprocess | |
| 25 | +import sys | |
| 26 | +import tempfile | |
| 27 | +import threading | |
| 28 | +from urllib.parse import urlparse, parse_qs | |
| 29 | + | |
| 30 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| 31 | +BIN = os.path.join(ROOT, "plugin_seqthink") | |
| 32 | +VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] | |
| 33 | +SHOTS = os.path.join(ROOT, "docs") | |
| 34 | + | |
| 35 | +FAILS = [] | |
| 36 | +PASSES = [] | |
| 37 | + | |
| 38 | + | |
| 39 | +def ok(desc): | |
| 40 | + PASSES.append(desc) | |
| 41 | + print(" ok %s" % desc) | |
| 42 | + | |
| 43 | + | |
| 44 | +def bad(desc, extra=""): | |
| 45 | + FAILS.append(desc) | |
| 46 | + print(" FAIL %s%s" % (desc, (" -- " + str(extra)) if extra else "")) | |
| 47 | + | |
| 48 | + | |
| 49 | +def check(desc, cond, extra=""): | |
| 50 | + ok(desc) if cond else bad(desc, extra) | |
| 51 | + | |
| 52 | + | |
| 53 | +def run_session(state_dir, arg_list): | |
| 54 | + """One --mcp process == one chain (upstream: a server lives as long as its | |
| 55 | + client's connection). Feed every thought of the session on one stdin.""" | |
| 56 | + lines = "\n".join( | |
| 57 | + json.dumps({"jsonrpc": "2.0", "id": i + 1, "method": "tools/call", | |
| 58 | + "params": {"name": "sequentialthinking", "arguments": a}}) | |
| 59 | + for i, a in enumerate(arg_list)) + "\n" | |
| 60 | + env = dict(os.environ) | |
| 61 | + env["SEQTHINK_STATE_DIR"] = state_dir | |
| 62 | + out = subprocess.run([BIN, "--mcp"], input=lines, capture_output=True, | |
| 63 | + text=True, env=env, timeout=30) | |
| 64 | + return [json.loads(l) for l in out.stdout.splitlines() if l.strip()] | |
| 65 | + | |
| 66 | + | |
| 67 | +def call_tool(state_dir, args): | |
| 68 | + return run_session(state_dir, [args])[0] | |
| 69 | + | |
| 70 | + | |
| 71 | +def click_chain(page, idx): | |
| 72 | + page.evaluate( | |
| 73 | + "(i) => { const li = document.querySelectorAll('#chains li')[i];" | |
| 74 | + " if (li) li.click(); }", idx) | |
| 75 | + page.wait_for_timeout(450) | |
| 76 | + | |
| 77 | + | |
| 78 | +def prepare_fixtures(): | |
| 79 | + """Three --mcp sessions: a linear chain with a revision, a branching chain, | |
| 80 | + and a small unicode chain. The viewer reads exactly what the tool wrote.""" | |
| 81 | + tmp = tempfile.mkdtemp(prefix="seqthink_e2e_") | |
| 82 | + env = dict(os.environ) | |
| 83 | + env["SEQTHINK_STATE_DIR"] = tmp | |
| 84 | + | |
| 85 | + # Session 1: one process, one chain: linear thoughts with a revision. | |
| 86 | + run_session(tmp, [ | |
| 87 | + {"thought": "decompose the migration into phases", | |
| 88 | + "nextThoughtNeeded": True, "thoughtNumber": 1, "totalThoughts": 4}, | |
| 89 | + {"thought": "phase 2 assumed a shared schema; that was wrong\n" | |
| 90 | + "the two services must keep separate stores", | |
| 91 | + "nextThoughtNeeded": True, "isRevision": True, "revisesThought": 1, | |
| 92 | + "thoughtNumber": 2, "totalThoughts": 4}, | |
| 93 | + {"thought": "blue-green it and cut over behind a flag", | |
| 94 | + "nextThoughtNeeded": False, "thoughtNumber": 3, "totalThoughts": 4}, | |
| 95 | + ]) | |
| 96 | + | |
| 97 | + # Session 2: a branch (both thoughts carry branchFromThought + branchId). | |
| 98 | + run_session(tmp, [ | |
| 99 | + {"thought": "alternative path: strangler facade", | |
| 100 | + "nextThoughtNeeded": True, "branchFromThought": 1, | |
| 101 | + "branchId": "strangler", "thoughtNumber": 4, "totalThoughts": 5}, | |
| 102 | + {"thought": "facade needs a routing layer first", | |
| 103 | + "nextThoughtNeeded": False, "branchFromThought": 1, | |
| 104 | + "branchId": "strangler", "thoughtNumber": 5, "totalThoughts": 5}, | |
| 105 | + ]) | |
| 106 | + | |
| 107 | + # Session 3: a single unicode thought. | |
| 108 | + call_tool(tmp, {"thought": "unicode check: \u00fcn\u00efc\u00f8d\u00e9, \u00e9mojis, " | |
| 109 | + "\u65e5\u672c\u8a9e and \"quotes\"", | |
| 110 | + "nextThoughtNeeded": False, "thoughtNumber": 1, | |
| 111 | + "totalThoughts": 1}) | |
| 112 | + return tmp, env | |
| 113 | + | |
| 114 | + | |
| 115 | +class Handler(http.server.BaseHTTPRequestHandler): | |
| 116 | + env = {} | |
| 117 | + | |
| 118 | + def _run(self, method): | |
| 119 | + u = urlparse(self.path) | |
| 120 | + qs = u.query | |
| 121 | + env = dict(self.env) | |
| 122 | + env["QUERY_STRING"] = qs | |
| 123 | + env["REQUEST_METHOD"] = method | |
| 124 | + env.pop("BOT_PASSWORD", None) | |
| 125 | + body = b"" | |
| 126 | + if method == "POST": | |
| 127 | + n = int(self.headers.get("Content-Length") or 0) | |
| 128 | + body = self.rfile.read(n) if n > 0 else b"" | |
| 129 | + env["CONTENT_LENGTH"] = str(n) | |
| 130 | + p = subprocess.Popen([BIN], stdin=subprocess.PIPE, | |
| 131 | + stdout=subprocess.PIPE, env=env) | |
| 132 | + out = p.communicate(body)[0] | |
| 133 | + sep = out.find(b"\r\n\r\n") | |
| 134 | + headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" | |
| 135 | + payload = out[sep + 4:] if sep >= 0 else out | |
| 136 | + ctype = "text/html; charset=utf-8" | |
| 137 | + status = 200 | |
| 138 | + for line in headers.splitlines(): | |
| 139 | + low = line.lower() | |
| 140 | + if low.startswith("content-type:"): | |
| 141 | + ctype = line.split(":", 1)[1].strip() | |
| 142 | + elif low.startswith("status:"): | |
| 143 | + try: | |
| 144 | + status = int(line.split(":", 1)[1].strip().split()[0]) | |
| 145 | + except Exception: | |
| 146 | + pass | |
| 147 | + self.send_response(status) | |
| 148 | + self.send_header("Content-Type", ctype) | |
| 149 | + self.send_header("Cache-Control", "no-store") | |
| 150 | + self.send_header("Content-Length", str(len(payload))) | |
| 151 | + self.end_headers() | |
| 152 | + self.wfile.write(payload) | |
| 153 | + | |
| 154 | + def do_GET(self): # noqa: N802 | |
| 155 | + self._run("GET") | |
| 156 | + | |
| 157 | + def do_POST(self): # noqa: N802 | |
| 158 | + self._run("POST") | |
| 159 | + | |
| 160 | + def log_message(self, *_a): | |
| 161 | + pass | |
| 162 | + | |
| 163 | + | |
| 164 | +def serve(env): | |
| 165 | + Handler.env = env | |
| 166 | + httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) | |
| 167 | + t = threading.Thread(target=httpd.serve_forever, daemon=True) | |
| 168 | + t.start() | |
| 169 | + return httpd, httpd.server_address[1] | |
| 170 | + | |
| 171 | + | |
| 172 | +def main(): | |
| 173 | + ap = argparse.ArgumentParser() | |
| 174 | + ap.add_argument("--strict", action="store_true") | |
| 175 | + ap.add_argument("--no-shots", action="store_true") | |
| 176 | + args = ap.parse_args() | |
| 177 | + | |
| 178 | + try: | |
| 179 | + from playwright.sync_api import sync_playwright | |
| 180 | + except Exception: | |
| 181 | + print(" skip e2e (playwright not installed)") | |
| 182 | + return 2 if args.strict else 0 | |
| 183 | + | |
| 184 | + if not os.path.exists(BIN): | |
| 185 | + print(" FAIL plugin binary missing; run `make` first") | |
| 186 | + return 1 | |
| 187 | + | |
| 188 | + tmp, env = prepare_fixtures() | |
| 189 | + httpd, port = serve(env) | |
| 190 | + base = "http://127.0.0.1:%d/" % port | |
| 191 | + print("== e2e: %s (state %s) ==" % (base, tmp)) | |
| 192 | + | |
| 193 | + os.makedirs(SHOTS, exist_ok=True) | |
| 194 | + cleared = False | |
| 195 | + try: | |
| 196 | + with sync_playwright() as p: | |
| 197 | + browser = p.chromium.launch() | |
| 198 | + for w, h in VIEWPORTS: | |
| 199 | + for theme in ("dark", "light"): | |
| 200 | + tag = "%dx%d %s" % (w, h, theme) | |
| 201 | + page = browser.new_page(viewport={"width": w, "height": h}, | |
| 202 | + device_scale_factor=1) | |
| 203 | + errors = [] | |
| 204 | + page.on("console", lambda m: errors.append(m.text) | |
| 205 | + if m.type == "error" else None) | |
| 206 | + page.on("pageerror", lambda e: errors.append(str(e))) | |
| 207 | + page.goto(base + "?theme=" + theme, wait_until="load") | |
| 208 | + page.wait_for_timeout(700) | |
| 209 | + | |
| 210 | + check("%s: no console errors" % tag, not errors, errors[:3]) | |
| 211 | + | |
| 212 | + attr = page.evaluate( | |
| 213 | + "document.documentElement.getAttribute('data-theme')") | |
| 214 | + check("%s: theme applied" % tag, attr == theme, attr) | |
| 215 | + | |
| 216 | + over = page.evaluate( | |
| 217 | + "() => Math.max(document.documentElement.scrollWidth," | |
| 218 | + " document.body.scrollWidth) - window.innerWidth") | |
| 219 | + check("%s: no horizontal overflow" % tag, over <= 1, over) | |
| 220 | + | |
| 221 | + # chain list populated from action=chains | |
| 222 | + n = page.evaluate( | |
| 223 | + "document.querySelectorAll('#chains li').length") | |
| 224 | + check("%s: chain list populated" % tag, n >= 3, n) | |
| 225 | + chips = page.evaluate( | |
| 226 | + "document.getElementById('chipChains').textContent") | |
| 227 | + check("%s: chip counts chains" % tag, "3" in chips, chips) | |
| 228 | + | |
| 229 | + # select chain 0 (the linear chain with the revision) | |
| 230 | + click_chain(page, 0) | |
| 231 | + page.wait_for_timeout(500) | |
| 232 | + rows = page.evaluate("document.querySelectorAll('#tl li').length") | |
| 233 | + check("%s: timeline renders the selected chain" % tag, | |
| 234 | + rows == 3, rows) | |
| 235 | + revs = page.evaluate( | |
| 236 | + "document.querySelectorAll('#tl li.rev').length") | |
| 237 | + check("%s: revision row marked" % tag, revs == 1, revs) | |
| 238 | + fin = page.evaluate( | |
| 239 | + "document.querySelectorAll('#tl .badge.fin').length") | |
| 240 | + check("%s: final thought badged" % tag, fin == 1, fin) | |
| 241 | + # the revision (row 2) is the multi-line thought | |
| 242 | + body = page.evaluate( | |
| 243 | + "document.querySelectorAll('#tl .th-body')[1].textContent") | |
| 244 | + check("%s: multi-line thought keeps its newline" % tag, | |
| 245 | + "\n" in body, repr(body[:60])) | |
| 246 | + | |
| 247 | + # select the branching chain (index 1) | |
| 248 | + page.evaluate("document.getElementById('backBtn') && " | |
| 249 | + "document.getElementById('backBtn').click()") | |
| 250 | + page.wait_for_timeout(400) | |
| 251 | + click_chain(page, 1) | |
| 252 | + page.wait_for_timeout(500) | |
| 253 | + brs = page.evaluate( | |
| 254 | + "document.querySelectorAll('#tl li.br').length") | |
| 255 | + check("%s: branch rows marked" % tag, brs == 2, brs) | |
| 256 | + btxt = page.evaluate( | |
| 257 | + "document.querySelector('#tl .badge.br').textContent") | |
| 258 | + check("%s: branch badge names the id" % tag, | |
| 259 | + "strangler" in btxt, btxt) | |
| 260 | + prog = page.evaluate( | |
| 261 | + "document.getElementById('dProg').style.width") | |
| 262 | + check("%s: progress bar tracks totalThoughts" % tag, | |
| 263 | + prog in ("80%", "100%"), prog) | |
| 264 | + | |
| 265 | + # unicode survives the round trip | |
| 266 | + click_chain(page, 2) | |
| 267 | + page.wait_for_timeout(400) | |
| 268 | + uni = page.evaluate( | |
| 269 | + "document.querySelector('#tl .th-body').textContent") | |
| 270 | + check("%s: unicode thought rendered" % tag, | |
| 271 | + "ünïcødé" in uni and "日本語" in uni, uni[:60]) | |
| 272 | + | |
| 273 | + # JSON panel | |
| 274 | + page.click("#jsonBtn") | |
| 275 | + page.wait_for_timeout(200) | |
| 276 | + jtxt = page.evaluate("document.getElementById('json').textContent") | |
| 277 | + try: | |
| 278 | + parsed = json.loads(jtxt) | |
| 279 | + good = parsed.get("ok") is True and "thoughts" in parsed | |
| 280 | + except Exception: | |
| 281 | + good = False | |
| 282 | + check("%s: Show JSON reveals parsable chain JSON" % tag, good) | |
| 283 | + | |
| 284 | + # theme handoff: the bot posts a new theme, the page follows | |
| 285 | + page.evaluate( | |
| 286 | + "window.postMessage({type:'sx-theme',theme:" | |
| 287 | + "'dark'},'*')") | |
| 288 | + page.wait_for_timeout(200) | |
| 289 | + attr2 = page.evaluate( | |
| 290 | + "document.documentElement.getAttribute('data-theme')") | |
| 291 | + check("%s: sx-theme postMessage followed" % tag, | |
| 292 | + attr2 == "dark", attr2) | |
| 293 | + | |
| 294 | + # CSP allows no external scripts | |
| 295 | + nscripts = page.evaluate( | |
| 296 | + "document.querySelectorAll('script[src]').length") | |
| 297 | + check("%s: no external scripts" % tag, nscripts == 0, nscripts) | |
| 298 | + | |
| 299 | + if not args.no_shots: | |
| 300 | + # the handoff test above flipped us to dark; restore | |
| 301 | + # the viewport's nominal theme before shooting | |
| 302 | + page.evaluate( | |
| 303 | + "(t) => window.postMessage({type:'sx-theme'," | |
| 304 | + "theme:t},'*')", theme) | |
| 305 | + page.wait_for_timeout(200) | |
| 306 | + # representative state: the revision chain, JSON hidden | |
| 307 | + page.evaluate("document.getElementById('backBtn') && " | |
| 308 | + "document.getElementById('backBtn').click()") | |
| 309 | + page.wait_for_timeout(350) | |
| 310 | + click_chain(page, 0) | |
| 311 | + page.evaluate( | |
| 312 | + """() => { const j = | |
| 313 | + document.getElementById('json'); | |
| 314 | + if (j.style.display !== 'none') | |
| 315 | + document.getElementById('jsonBtn').click(); }""") | |
| 316 | + page.wait_for_timeout(350) | |
| 317 | + shot = os.path.join( | |
| 318 | + SHOTS, "ui-%dx%d-%s.png" % (w, h, theme)) | |
| 319 | + page.screenshot(path=shot, full_page=False) | |
| 320 | + if os.path.getsize(shot) > 900 * 1024: | |
| 321 | + bad("%s: screenshot under 900 KB" % tag, | |
| 322 | + os.path.getsize(shot)) | |
| 323 | + else: | |
| 324 | + ok("%s: screenshot written (%d KB)" % | |
| 325 | + (tag, os.path.getsize(shot) // 1024)) | |
| 326 | + | |
| 327 | + page.close() | |
| 328 | + | |
| 329 | + # Clear empties the store (behind a confirm dialog) | |
| 330 | + page = browser.new_page(viewport={"width": 1440, "height": 900}) | |
| 331 | + dialogs = [] | |
| 332 | + page.on("dialog", lambda d: (dialogs.append(d.type), d.accept())) | |
| 333 | + page.goto(base, wait_until="load") | |
| 334 | + page.wait_for_timeout(600) | |
| 335 | + page.click("#clearBtn") | |
| 336 | + page.wait_for_timeout(700) | |
| 337 | + check("clear: confirm dialog fired", dialogs == ["confirm"], dialogs) | |
| 338 | + left = page.evaluate("document.querySelectorAll('#chains li').length") | |
| 339 | + check("clear: chains gone", left == 0, left) | |
| 340 | + cleared = True | |
| 341 | + empty = page.evaluate( | |
| 342 | + "document.getElementById('empty').textContent") | |
| 343 | + check("clear: empty state explains the tool", | |
| 344 | + "sequentialthinking" in empty, empty[:80]) | |
| 345 | + page.close() | |
| 346 | + | |
| 347 | + # a fresh tool call after a clear reappears on Refresh | |
| 348 | + call_tool(tmp, {"thought": "after clear", "nextThoughtNeeded": False, | |
| 349 | + "thoughtNumber": 1, "totalThoughts": 1}) | |
| 350 | + page = browser.new_page(viewport={"width": 1440, "height": 900}) | |
| 351 | + page.goto(base, wait_until="load") | |
| 352 | + page.wait_for_timeout(600) | |
| 353 | + page.click("#refreshBtn") | |
| 354 | + page.wait_for_timeout(600) | |
| 355 | + n = page.evaluate("document.querySelectorAll('#chains li').length") | |
| 356 | + check("repopulated after clear", n == 1, n) | |
| 357 | + page.close() | |
| 358 | + | |
| 359 | + browser.close() | |
| 360 | + finally: | |
| 361 | + httpd.shutdown() | |
| 362 | + | |
| 363 | + print("\n== e2e: %d passed, %d failed ==" % (len(PASSES), len(FAILS))) | |
| 364 | + if FAILS: | |
| 365 | + for f in FAILS: | |
| 366 | + print(" - %s" % f) | |
| 367 | + return 1 | |
| 368 | + if not cleared: | |
| 369 | + return 1 | |
| 370 | + return 0 | |
| 371 | + | |
| 372 | + | |
| 373 | +if __name__ == "__main__": | |
| 374 | + sys.exit(main()) |
| 1 | 1 | new file mode 100755 |
| index 0000000..4f09b7d | ||
| --- /dev/null | ||
| +++ b/tests/run.sh | ||
| @@ -0,0 +1,521 @@ | ||
| 1 | +#!/bin/sh | |
| 2 | +# tests/run.sh - offline checks for plugin_seqthink across all 4 modes. | |
| 3 | +# | |
| 4 | +# Runs against ./plugin_seqthink (native build) on the live machine. The --mcp | |
| 5 | +# leg is driven with a scripted JSON-RPC session on stdin; the CGI leg is | |
| 6 | +# driven through QUERY_STRING / REQUEST_METHOD / CONTENT_LENGTH; the chain | |
| 7 | +# store is pointed at a scratch directory through SEQTHINK_STATE_DIR so the | |
| 8 | +# real node directory is never touched. The last section audits the whole git | |
| 9 | +# history for secrets and internal addresses. | |
| 10 | +# | |
| 11 | +# Exit code 0 = everything passed. | |
| 12 | + | |
| 13 | +set -u | |
| 14 | + | |
| 15 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | |
| 16 | +cd "$ROOT" || exit 1 | |
| 17 | + | |
| 18 | +BIN=./plugin_seqthink | |
| 19 | +PASS=0 | |
| 20 | +FAIL=0 | |
| 21 | +TMP=$(mktemp -d 2>/dev/null || echo /tmp/seqthink_test_$$) | |
| 22 | +mkdir -p "$TMP" | |
| 23 | +trap 'rm -rf "$TMP"' EXIT | |
| 24 | + | |
| 25 | +if [ -t 1 ]; then | |
| 26 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | |
| 27 | +else | |
| 28 | + C_OK=; C_BAD=; C_B=; C_0= | |
| 29 | +fi | |
| 30 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | |
| 31 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | |
| 32 | + | |
| 33 | +check() { # check <desc> <expected-substring> <actual> | |
| 34 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | |
| 35 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)" | |
| 36 | + fi | |
| 37 | +} | |
| 38 | + | |
| 39 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | |
| 40 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | |
| 41 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | |
| 42 | + fi | |
| 43 | +} | |
| 44 | + | |
| 45 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | |
| 46 | +body() { printf '%s' "$1" | sed '1,/^\r$/d'; } | |
| 47 | + | |
| 48 | +jq_() { # jq_ <desc> <python-expression using d> <json> | |
| 49 | + printf '%s' "$3" > "$TMP/_j.json" | |
| 50 | + if python3 - "$TMP/_j.json" "$2" <<'PY' 2>/dev/null | |
| 51 | +import json, sys | |
| 52 | +d = json.load(open(sys.argv[1])) | |
| 53 | +assert eval(sys.argv[2], {"d": d}), sys.argv[2] | |
| 54 | +PY | |
| 55 | + then pass "$1"; else fail "$1"; fi | |
| 56 | +} | |
| 57 | + | |
| 58 | +mcp() { # mcp <state-dir> [env assignments...] -- feeds $TMP/in.jsonl | |
| 59 | + local dir="$1"; shift | |
| 60 | + SEQTHINK_STATE_DIR="$dir" env "$@" "$BIN" --mcp < "$TMP/in.jsonl" 2>"$TMP/err.txt" | |
| 61 | +} | |
| 62 | + | |
| 63 | +# ---------------------------------------------------------------- build | |
| 64 | +section "build" | |
| 65 | +if [ ! -x "$BIN" ]; then | |
| 66 | + echo " building native binary..." | |
| 67 | + cc -O2 -std=c99 -Wall -Wextra -I src -I vendor -o "$BIN" src/plugin_seqthink.c vendor/yyjson.c \ | |
| 68 | + || { echo " build failed"; exit 1; } | |
| 69 | +fi | |
| 70 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | |
| 71 | + | |
| 72 | +SRC=src/plugin_seqthink.c | |
| 73 | +SRC_TXT=$(cat "$SRC") | |
| 74 | + | |
| 75 | +# ---------------------------------------------------------------- mode 1: --meta | |
| 76 | +section "mode 1 --meta (must work without auth - discovery)" | |
| 77 | +META=$("$BIN" --meta) | |
| 78 | +check "meta emits name seqthink" '"name":"seqthink"' "$META" | |
| 79 | +check "meta emits desc" '"desc":"Thought chains"' "$META" | |
| 80 | +check "meta declares kind mcp" '"kind":"mcp"' "$META" | |
| 81 | +check "meta declares mcp true" '"mcp":true' "$META" | |
| 82 | +check "meta declares daemon false" '"daemon":false' "$META" | |
| 83 | +check "meta declares menus false" '"menus":false' "$META" | |
| 84 | +check "meta declares verified" '"verified":"live"' "$META" | |
| 85 | +METAENV=$(SX_PLUGIN_META=1 "$BIN") | |
| 86 | +check "SX_PLUGIN_META=1 yields same meta" '"name":"seqthink"' "$METAENV" | |
| 87 | +[ "$META" = "$METAENV" ] && pass "argv and env meta identical" || fail "argv and env meta differ" | |
| 88 | +if [ "$(printf '%s\n' "$META" | wc -l)" -eq 1 ]; then pass "meta is exactly one line"; else fail "meta is more than one line"; fi | |
| 89 | +check "--version names the plugin" "plugin_seqthink" "$("$BIN" --version)" | |
| 90 | +check "--schema is the input schema" '"required":["thought","nextThoughtNeeded","thoughtNumber","totalThoughts"]' \ | |
| 91 | + "$("$BIN" --schema)" | |
| 92 | + | |
| 93 | +section "plugin.json agrees with --meta" | |
| 94 | +PJ=$(cat plugin.json) | |
| 95 | +jq_ "plugin.json slug/id" "d['slug']=='seqthink' and d['id']=='plugin_seqthink'" "$PJ" | |
| 96 | +jq_ "plugin.json category" "d['category']=='devtools'" "$PJ" | |
| 97 | +jq_ "plugin.json kind/mcp" "d['kind']=='mcp' and d['mcp'] is True" "$PJ" | |
| 98 | +jq_ "plugin.json daemon/menus" "d['daemon'] is False and d['menus'] is False" "$PJ" | |
| 99 | +jq_ "plugin.json verified" "d['verified']=='live'" "$PJ" | |
| 100 | +jq_ "plugin.json has title/summary/trust" "d['title'] and len(d['summary'])>80 and d['trust_notice']" "$PJ" | |
| 101 | +check_not "plugin.json has no LAN address" "192.168." "$PJ" | |
| 102 | + | |
| 103 | +# ---------------------------------------------------------------- mode 2: --mcp | |
| 104 | +section "mode 2 --mcp handshake" | |
| 105 | +cat > "$TMP/in.jsonl" <<'JSONL' | |
| 106 | +{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"probe","version":"1"}}} | |
| 107 | +{"jsonrpc":"2.0","method":"notifications/initialized"} | |
| 108 | +{"jsonrpc":"2.0","id":2,"method":"tools/list"} | |
| 109 | +{"jsonrpc":"2.0","id":3,"method":"ping"} | |
| 110 | +{"jsonrpc":"2.0","id":4,"method":"not/a/method"} | |
| 111 | +JSONL | |
| 112 | +OUT=$(mcp "$TMP/m_hand" env) | |
| 113 | +R1=$(printf '%s' "$OUT" | sed -n 1p) | |
| 114 | +R2=$(printf '%s' "$OUT" | sed -n 2p) | |
| 115 | +R3=$(printf '%s' "$OUT" | sed -n 3p) | |
| 116 | +R4=$(printf '%s' "$OUT" | sed -n 4p) | |
| 117 | +check "initialize answers jsonrpc 2.0" '"jsonrpc":"2.0"' "$R1" | |
| 118 | +check "initialize echoes id" '"id":1' "$R1" | |
| 119 | +check "initialize carries protocol" '"protocolVersion":"2024-11-05"' "$R1" | |
| 120 | +check "initialize advertises tools" '"capabilities":{"tools":{}}' "$R1" | |
| 121 | +check "initialize names the server" '"name":"seqthink"' "$R1" | |
| 122 | +check "notifications get no reply" '"id":2' "$R2" | |
| 123 | +check "tools/list offers sequentialthinking" '"name":"sequentialthinking"' "$R2" | |
| 124 | +check "tool carries a title" '"title":"Sequential Thinking"' "$R2" | |
| 125 | +check "tool carries annotations" '"readOnlyHint":false' "$R2" | |
| 126 | +check "annotations not idempotent" '"idempotentHint":false' "$R2" | |
| 127 | +check "tool carries inputSchema" '"inputSchema"' "$R2" | |
| 128 | +check "inputSchema requires 4 fields" '"required":["thought","nextThoughtNeeded","thoughtNumber","totalThoughts"]' "$R2" | |
| 129 | +check "inputSchema minimum on thoughtNumber" '"thoughtNumber":{"type":"integer"' "$R2" | |
| 130 | +check "tool carries outputSchema" '"thoughtHistoryLength":{"type":"number"}' "$R2" | |
| 131 | +check "ping answered empty result" '"result":{}' "$R3" | |
| 132 | +check "unknown method -> -32601" '"code":-32601' "$R4" | |
| 133 | + | |
| 134 | +section "mode 2 --mcp tool: happy path, revision, branch" | |
| 135 | +cat > "$TMP/in.jsonl" <<'JSONL' | |
| 136 | +{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"break the problem down","nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":3}}} | |
| 137 | +{"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"question an earlier step","nextThoughtNeeded":"true","isRevision":true,"revisesThought":1,"thoughtNumber":2,"totalThoughts":3,"needsMoreThoughts":true}}} | |
| 138 | +{"jsonrpc":"2.0","id":13,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"an alternative path","nextThoughtNeeded":"false","branchFromThought":1,"branchId":"alt-route","thoughtNumber":3,"totalThoughts":3}}} | |
| 139 | +{"jsonrpc":"2.0","id":14,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"past the estimate","nextThoughtNeeded":false,"thoughtNumber":9,"totalThoughts":3}}} | |
| 140 | +JSONL | |
| 141 | +OUT=$(mcp "$TMP/m_ok" env) | |
| 142 | +L11=$(printf '%s' "$OUT" | sed -n 1p) | |
| 143 | +L12=$(printf '%s' "$OUT" | sed -n 2p) | |
| 144 | +L13=$(printf '%s' "$OUT" | sed -n 3p) | |
| 145 | +L14=$(printf '%s' "$OUT" | sed -n 4p) | |
| 146 | +check "call 1 content is text" '"type":"text"' "$L11" | |
| 147 | +check "call 1 reports thoughtNumber" 'thoughtNumber\":1' "$L11" | |
| 148 | +check "call 1 history length 1" 'thoughtHistoryLength\":1}' "$L11" | |
| 149 | +check "call 1 not an error" '"isError":false' "$L11" | |
| 150 | +check "call 1 has structuredContent" '"structuredContent":{"thoughtNumber":1' "$L11" | |
| 151 | +check "call 2 accepted a string bool" '"isError":false' "$L12" | |
| 152 | +check "call 2 history length 2" 'thoughtHistoryLength\":2}' "$L12" | |
| 153 | +check "call 3 records the branch" 'branches\":[\"alt-route\"' "$L13" | |
| 154 | +check "call 4 raised totalThoughts" 'totalThoughts\":9' "$L14" | |
| 155 | +check "call 4 kept the branch list" 'alt-route' "$L14" | |
| 156 | +check "stderr logged thought 1" 'Thought 1/3' "$(cat "$TMP/err.txt")" | |
| 157 | +check "stderr marked the revision" 'Revision 2/3 (revising thought 1)' "$(cat "$TMP/err.txt")" | |
| 158 | +check "stderr marked the branch" 'Branch 3/3 (from thought 1, ID: alt-route)' "$(cat "$TMP/err.txt")" | |
| 159 | +# (structuredContent parity is asserted in detail below) | |
| 160 | +printf '%s' "$L11" > "$TMP/_c.json" | |
| 161 | +if python3 - "$TMP/_c.json" <<'PY' 2>/dev/null | |
| 162 | +import json, sys | |
| 163 | +d = json.load(open(sys.argv[1])) | |
| 164 | +r = d["result"] | |
| 165 | +sc = r["structuredContent"] | |
| 166 | +txt = json.loads(r["content"][0]["text"]) | |
| 167 | +assert sc == txt, (sc, txt) | |
| 168 | +assert sorted(sc) == ["branches", "nextThoughtNeeded", "thoughtHistoryLength", | |
| 169 | + "thoughtNumber", "totalThoughts"], sorted(sc) | |
| 170 | +assert sc["thoughtNumber"] == 1 and sc["totalThoughts"] == 3 | |
| 171 | +assert sc["nextThoughtNeeded"] is True | |
| 172 | +assert sc["branches"] == [] and sc["thoughtHistoryLength"] == 1 | |
| 173 | +PY | |
| 174 | +then pass "structuredContent == parsed content text, exactly 5 fields" | |
| 175 | +else fail "structuredContent == parsed content text, exactly 5 fields" | |
| 176 | +fi | |
| 177 | + | |
| 178 | +section "mode 2 --mcp tool: validation errors mirror upstream" | |
| 179 | +cat > "$TMP/in.jsonl" <<'JSONL' | |
| 180 | +{"jsonrpc":"2.0","id":21,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"","nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":1}}} | |
| 181 | +{"jsonrpc":"2.0","id":22,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":1}}} | |
| 182 | +{"jsonrpc":"2.0","id":23,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"thoughtNumber":0,"totalThoughts":1}}} | |
| 183 | +{"jsonrpc":"2.0","id":24,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"thoughtNumber":"abc","totalThoughts":1}}} | |
| 184 | +{"jsonrpc":"2.0","id":25,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":0}}} | |
| 185 | +{"jsonrpc":"2.0","id":26,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":"yes","thoughtNumber":1,"totalThoughts":1}}} | |
| 186 | +{"jsonrpc":"2.0","id":27,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","thoughtNumber":1,"totalThoughts":1}}} | |
| 187 | +{"jsonrpc":"2.0","id":28,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"isRevision":"maybe","thoughtNumber":1,"totalThoughts":1}}} | |
| 188 | +{"jsonrpc":"2.0","id":29,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"revisesThought":0,"thoughtNumber":1,"totalThoughts":1}}} | |
| 189 | +{"jsonrpc":"2.0","id":30,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"branchFromThought":-2,"thoughtNumber":1,"totalThoughts":1}}} | |
| 190 | +{"jsonrpc":"2.0","id":31,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"branchId":42,"thoughtNumber":1,"totalThoughts":1}}} | |
| 191 | +{"jsonrpc":"2.0","id":32,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"needsMoreThoughts":"perhaps","thoughtNumber":1,"totalThoughts":1}}} | |
| 192 | +{"jsonrpc":"2.0","id":33,"method":"tools/call","params":{"name":"nope","arguments":{}}} | |
| 193 | +{"jsonrpc":"2.0","id":34,"method":"tools/call","params":{"name":"sequentialthinking"}} | |
| 194 | +JSONL | |
| 195 | +OUT=$(mcp "$TMP/m_err" env) | |
| 196 | +E1=$(printf '%s' "$OUT" | sed -n 1p) | |
| 197 | +E2=$(printf '%s' "$OUT" | sed -n 2p) | |
| 198 | +E3=$(printf '%s' "$OUT" | sed -n 3p) | |
| 199 | +E4=$(printf '%s' "$OUT" | sed -n 4p) | |
| 200 | +E5=$(printf '%s' "$OUT" | sed -n 5p) | |
| 201 | +E6=$(printf '%s' "$OUT" | sed -n 6p) | |
| 202 | +E7=$(printf '%s' "$OUT" | sed -n 7p) | |
| 203 | +E8=$(printf '%s' "$OUT" | sed -n 8p) | |
| 204 | +E9=$(printf '%s' "$OUT" | sed -n 9p) | |
| 205 | +E10=$(printf '%s' "$OUT" | sed -n 10p) | |
| 206 | +E11=$(printf '%s' "$OUT" | sed -n 11p) | |
| 207 | +E12=$(printf '%s' "$OUT" | sed -n 12p) | |
| 208 | +E13=$(printf '%s' "$OUT" | sed -n 13p) | |
| 209 | +E14=$(printf '%s' "$OUT" | sed -n 14p) | |
| 210 | +check "empty thought refused" 'Invalid thought: must be a string' "$E1" | |
| 211 | +check "missing thought refused" 'Invalid thought: must be a string' "$E2" | |
| 212 | +check "thoughtNumber 0 refused" 'Invalid thoughtNumber: must be a number' "$E3" | |
| 213 | +check "non-numeric thoughtNumber" 'Invalid thoughtNumber: must be a number' "$E4" | |
| 214 | +check "totalThoughts 0 refused" 'Invalid totalThoughts: must be a number' "$E5" | |
| 215 | +check "bad nextThoughtNeeded" 'Invalid nextThoughtNeeded: must be a boolean' "$E6" | |
| 216 | +check "missing nextThoughtNeeded" 'Invalid nextThoughtNeeded: must be a boolean' "$E7" | |
| 217 | +check "bad isRevision" 'Invalid isRevision: must be a boolean' "$E8" | |
| 218 | +check "bad revisesThought" 'Invalid revisesThought: must be a number' "$E9" | |
| 219 | +check "bad branchFromThought" 'Invalid branchFromThought: must be a number' "$E10" | |
| 220 | +check "branchId must be a string" 'Invalid branchId: must be a string' "$E11" | |
| 221 | +check "bad needsMoreThoughts" 'Invalid needsMoreThoughts: must be a boolean' "$E12" | |
| 222 | +check "all refusals set isError" '"isError":true' "$E1" | |
| 223 | +check "all refusals say failed" '"status\":\"failed\"' "$E1" | |
| 224 | +check "unknown tool -> -32602" '"code":-32602' "$E13" | |
| 225 | +check "missing arguments refused" 'Invalid thought: must be a string' "$E14" | |
| 226 | +cat > "$TMP/in.jsonl" <<'JSONL' | |
| 227 | +{"jsonrpc":"2.0","id":41,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"coerce me","nextThoughtNeeded":"TRUE","thoughtNumber":"2","totalThoughts":"4"}}} | |
| 228 | +JSONL | |
| 229 | +OUT=$(mcp "$TMP/m_coerce" env) | |
| 230 | +check "string numbers coerce (upstream z.coerce)" 'totalThoughts\":4' "$OUT" | |
| 231 | +check "string TRUE coerces to true" 'nextThoughtNeeded\":true' "$OUT" | |
| 232 | + | |
| 233 | +section "mode 2 --mcp: history cap and branch eviction" | |
| 234 | +python3 - > "$TMP/in.jsonl" <<'PY' | |
| 235 | +import json | |
| 236 | +print(json.dumps({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"base","nextThoughtNeeded":True,"thoughtNumber":1,"totalThoughts":9}}})) | |
| 237 | +for i in range(2, 7): | |
| 238 | + print(json.dumps({"jsonrpc":"2.0","id":i,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"beta%d" % i,"nextThoughtNeeded":True,"branchFromThought":1,"branchId":"beta","thoughtNumber":i,"totalThoughts":9}}})) | |
| 239 | +for i in range(7, 9): | |
| 240 | + print(json.dumps({"jsonrpc":"2.0","id":i,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"gamma%d" % i,"nextThoughtNeeded":True,"branchFromThought":1,"branchId":"gamma","thoughtNumber":i,"totalThoughts":9}}})) | |
| 241 | +PY | |
| 242 | +OUT=$(mcp "$TMP/m_cap1" MAX_THOUGHT_HISTORY=1) | |
| 243 | +LAST=$(printf '%s' "$OUT" | tail -1) | |
| 244 | +check "cap 1 keeps one thought" 'thoughtHistoryLength\":1}' "$LAST" | |
| 245 | +check "cap 1 emptied beta dropped" 'branches\":[\"gamma\"]' "$LAST" | |
| 246 | +check_not "cap 1 does not list beta" '\"beta\"' "$LAST" | |
| 247 | +OUT=$(mcp "$TMP/m_cap2" MAX_THOUGHT_HISTORY=3) | |
| 248 | +LAST=$(printf '%s' "$OUT" | tail -1) | |
| 249 | +check "cap 3 keeps three thoughts" 'thoughtHistoryLength\":3}' "$LAST" | |
| 250 | +check "cap 3 still lists beta" 'beta' "$LAST" | |
| 251 | +OUT=$(mcp "$TMP/m_bad" MAX_THOUGHT_HISTORY=abc) | |
| 252 | +check "bad cap warns on stderr" 'MAX_THOUGHT_HISTORY must be a positive integer' "$(cat "$TMP/err.txt")" | |
| 253 | +check "bad cap falls back to default" "thoughtHistoryLength\\\":1}" "$OUT" | |
| 254 | +OUT=$(mcp "$TMP/m_neg" MAX_THOUGHT_HISTORY=0) | |
| 255 | +check "zero cap rejected too" 'must be a positive integer' "$(cat "$TMP/err.txt")" | |
| 256 | + | |
| 257 | +section "mode 2 --mcp: DISABLE_THOUGHT_LOGGING (upstream parity)" | |
| 258 | +OUT=$(mcp "$TMP/m_dis" DISABLE_THOUGHT_LOGGING=true) | |
| 259 | +check "call still succeeds when logging disabled" '"isError":false' "$OUT" | |
| 260 | +if [ -s "$TMP/err.txt" ]; then fail "logging silenced on stderr"; else pass "logging silenced on stderr"; fi | |
| 261 | +if [ -f "$TMP/m_dis/chains.json" ]; then fail "logging disabled also skips persistence"; else pass "logging disabled also skips persistence"; fi | |
| 262 | +OUT=$(mcp "$TMP/m_dis2" DISABLE_THOUGHT_LOGGING=1) | |
| 263 | +if [ -s "$TMP/err.txt" ]; then fail "DISABLE_THOUGHT_LOGGING=1 silences stderr"; else pass "DISABLE_THOUGHT_LOGGING=1 silences stderr"; fi | |
| 264 | + | |
| 265 | +section "mode 2 --mcp: chains.json snapshot for the viewer" | |
| 266 | +CHAINJSON="$TMP/m_ok/chains.json" | |
| 267 | +[ -f "$CHAINJSON" ] && pass "chains.json written" || fail "chains.json missing" | |
| 268 | +CJ=$(cat "$CHAINJSON" 2>/dev/null || echo '{}') | |
| 269 | +jq_ "chains.json has one chain" "len(d['chains'])==1" "$CJ" | |
| 270 | +jq_ "chain keeps 4 thoughts" "d['chains'][0]['count']==4" "$CJ" | |
| 271 | +jq_ "chain records the branch" "d['chains'][0]['branches']==['alt-route']" "$CJ" | |
| 272 | +jq_ "thought carries fields" "set(['thought','thought_number','total_thoughts','next_needed','at']) <= set(d['chains'][0]['thoughts'][0])" "$CJ" | |
| 273 | +jq_ "revision flagged" "d['chains'][0]['thoughts'][1].get('is_revision') is True" "$CJ" | |
| 274 | +jq_ "revision target recorded" "d['chains'][0]['thoughts'][1]['revises']==1" "$CJ" | |
| 275 | +jq_ "branch flagged" "d['chains'][0]['thoughts'][2]['branch_id']=='alt-route'" "$CJ" | |
| 276 | +jq_ "needs_more flagged" "d['chains'][0]['thoughts'][1]['needs_more'] is True" "$CJ" | |
| 277 | +# a second process must merge, not clobber | |
| 278 | +cat > "$TMP/in.jsonl" <<'JSONL' | |
| 279 | +{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"second session","nextThoughtNeeded":false,"thoughtNumber":1,"totalThoughts":1}}} | |
| 280 | +JSONL | |
| 281 | +mcp "$TMP/m_ok" env >/dev/null | |
| 282 | +CJ=$(cat "$CHAINJSON") | |
| 283 | +jq_ "second session merged" "len(d['chains'])==2" "$CJ" | |
| 284 | +jq_ "first chain untouched" "any(c['count']==4 for c in d['chains'])" "$CJ" | |
| 285 | +# malformed store degrades to clean, never a crash or a poisoned file | |
| 286 | +printf 'not json {{{\n' > "$TMP/m_ok/chains.json" | |
| 287 | +mcp "$TMP/m_ok" env >/dev/null 2>&1 | |
| 288 | +check "corrupt store recovered" '"thought"' "$(cat "$TMP/m_ok/chains.json")" | |
| 289 | +# the file is written .tmp then rename()d | |
| 290 | +check "persistence uses a temp file" "rename(tmp, path)" "$SRC_TXT" | |
| 291 | +check_not "persistence never writes the store in place" 'fopen(path, "wb")' "$SRC_TXT" | |
| 292 | + | |
| 293 | +# ---------------------------------------------------------------- mode 3: JSON API | |
| 294 | +section "mode 3 JSON API: authentication" | |
| 295 | +S="$TMP/api"; mkdir -p "$S" | |
| 296 | +cat > "$TMP/in.jsonl" <<'JSONL' | |
| 297 | +{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"alpha one","nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":2}}} | |
| 298 | +{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"alpha two","nextThoughtNeeded":false,"isRevision":true,"revisesThought":1,"thoughtNumber":2,"totalThoughts":2}}} | |
| 299 | +JSONL | |
| 300 | +mcp "$S" env >/dev/null | |
| 301 | +R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw QUERY_STRING="action=chains" "$BIN"; true) | |
| 302 | +check "401 without a credential" "Status: 401 Unauthorized" "$R" | |
| 303 | +check "401 body says invalid" "invalid node password" "$R" | |
| 304 | +check_not "401 leaks no chains" '"chains":[' "$R" | |
| 305 | +R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw HTTP_X_BOT_PASSWORD=secretpw QUERY_STRING="action=chains" "$BIN"; true) | |
| 306 | +check "header credential accepted" '"chains":[' "$R" | |
| 307 | +R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw HTTP_AUTHORIZATION="Bearer secretpw" QUERY_STRING="action=stats" "$BIN"; true) | |
| 308 | +check "bearer credential accepted" '"ok":true' "$R" | |
| 309 | +R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw QUERY_STRING="action=chains&pwd=secretpw" "$BIN"; true) | |
| 310 | +check "query pwd credential accepted" '"chains":[' "$R" | |
| 311 | +R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw QUERY_STRING="action=chains&pwd=nope" "$BIN"; true) | |
| 312 | +check "wrong credential still 401" "Status: 401" "$R" | |
| 313 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chains" "$BIN"; true) | |
| 314 | +check "open node (no BOT_PASSWORD) answers" '"chains":[' "$R" | |
| 315 | +R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw "$BIN" --meta; true) | |
| 316 | +check "--meta stays unauthenticated" '"name":"seqthink"' "$R" | |
| 317 | +R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw "$BIN" < /dev/null; true) | |
| 318 | +check "HTML page stays unauthenticated" "<!DOCTYPE html>" "$R" | |
| 319 | + | |
| 320 | +section "mode 3 JSON API: actions" | |
| 321 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chains" "$BIN"; true) | |
| 322 | +CB=$(body "$R") | |
| 323 | +jq_ "chains lists one chain" "d['count']==1" "$CB" | |
| 324 | +jq_ "chains reports the plugin" "d['plugin']=='plugin_seqthink'" "$CB" | |
| 325 | +jq_ "chain summary has thoughts" "d['chains'][0]['thoughts']==2" "$CB" | |
| 326 | +jq_ "chain summary has last_head" "d['chains'][0]['last_head']=='alpha two'" "$CB" | |
| 327 | +jq_ "chain summary lists branches" "isinstance(d['chains'][0]['branches'], list)" "$CB" | |
| 328 | +jq_ "chains never leaks an absolute state path" "'/' not in d['state_dir_name']" "$CB" | |
| 329 | +CID=$(printf '%s' "$CB" | python3 -c "import json,sys;print(json.load(sys.stdin)['chains'][0]['id'])") | |
| 330 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chain&id=$CID" "$BIN"; true) | |
| 331 | +DB=$(body "$R") | |
| 332 | +jq_ "chain returns thoughts" "len(d['thoughts'])==2" "$DB" | |
| 333 | +jq_ "chain thought text intact" "d['thoughts'][0]['thought']=='alpha one'" "$DB" | |
| 334 | +jq_ "chain marks the revision" "d['thoughts'][1]['is_revision'] is True" "$DB" | |
| 335 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chain&id=does-not-exist" "$BIN"; true) | |
| 336 | +check "unknown chain id -> error" 'chain not found' "$(body "$R")" | |
| 337 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chain&id=..%2F..%2Fetc%2Fpasswd" "$BIN"; true) | |
| 338 | +check "path traversal id refused" 'invalid chain id' "$(body "$R")" | |
| 339 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chain&id=a%3Brm" "$BIN"; true) | |
| 340 | +check "shell metacharacter id refused" 'invalid chain id' "$(body "$R")" | |
| 341 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=stats" "$BIN"; true) | |
| 342 | +SB=$(body "$R") | |
| 343 | +jq_ "stats counts thoughts" "d['thoughts']==2" "$SB" | |
| 344 | +jq_ "stats counts chains" "d['chains']==1" "$SB" | |
| 345 | +jq_ "stats counts revisions" "d['revisions']==1" "$SB" | |
| 346 | +jq_ "stats reports the cap" "d['max_chains']==50" "$SB" | |
| 347 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=info" "$BIN"; true) | |
| 348 | +IB=$(body "$R") | |
| 349 | +jq_ "info declares kind mcp" "d['kind']=='mcp' and d['mcp'] is True" "$IB" | |
| 350 | +jq_ "info declares menus false" "d['menus'] is False and d['daemon'] is False" "$IB" | |
| 351 | +jq_ "info lists the tool" "d['tools']==['sequentialthinking']" "$IB" | |
| 352 | +jq_ "info carries the schema" "'thought' in d['tool_schema']['properties'] and 'branchId' in d['tool_schema']['properties']" "$IB" | |
| 353 | +jq_ "info schema requires 4" "sorted(d['tool_schema']['required'])==sorted(['thought','nextThoughtNeeded','thoughtNumber','totalThoughts'])" "$IB" | |
| 354 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=bogus" "$BIN"; true) | |
| 355 | +check "unknown action refused" 'unknown action' "$(body "$R")" | |
| 356 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="format=json" "$BIN"; true) | |
| 357 | +check "format=json answers JSON" 'Content-Type: application/json' "$R" | |
| 358 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="format=jsonx" "$BIN"; true) | |
| 359 | +check "format=jsonx still serves HTML" 'Content-Type: text/html' "$R" | |
| 360 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=clear" "$BIN"; true) | |
| 361 | +check "clear needs confirmation" 'confirm=1 required' "$(body "$R")" | |
| 362 | +[ -f "$S/chains.json" ] && pass "clear refused left the store" || fail "clear refused wiped the store" | |
| 363 | +printf '{"action":"clear","confirm":"1"}' > "$S/_body.json" | |
| 364 | +R=$(SEQTHINK_STATE_DIR="$S" REQUEST_METHOD=POST CONTENT_LENGTH=$(wc -c < "$S/_body.json") \ | |
| 365 | + HTTP_X_BOT_PASSWORD=sh "$BIN" < "$S/_body.json"; true) | |
| 366 | +check "POST JSON body clear works" '"cleared":true' "$(body "$R")" | |
| 367 | +[ -f "$S/chains.json" ] && fail "clear removed the store" || pass "clear removed the store" | |
| 368 | + | |
| 369 | +section "mode 3 JSON API: bounded store" | |
| 370 | +S2="$TMP/bound"; mkdir -p "$S2" | |
| 371 | +i=1 | |
| 372 | +while [ $i -le 55 ]; do | |
| 373 | + printf '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"chain %s","nextThoughtNeeded":false,"thoughtNumber":1,"totalThoughts":1}}}\n' "$i" \ | |
| 374 | + > "$TMP/one.jsonl" | |
| 375 | + SEQTHINK_STATE_DIR="$S2" env "$BIN" --mcp < "$TMP/one.jsonl" >/dev/null 2>&1 | |
| 376 | + i=$((i + 1)) | |
| 377 | +done | |
| 378 | +BJ=$(cat "$S2/chains.json") | |
| 379 | +jq_ "store never exceeds 50 chains" "len(d['chains'])<=50" "$BJ" | |
| 380 | +jq_ "newest chain survived" "any(c['thoughts'][0]['thought']=='chain 55' for c in d['chains'])" "$BJ" | |
| 381 | + | |
| 382 | +# ---------------------------------------------------------------- mode 4: HTML | |
| 383 | +section "mode 4 HTML UI" | |
| 384 | +Q=$(SEQTHINK_STATE_DIR="$TMP/api" QUERY_STRING="embed=1" "$BIN"; true) | |
| 385 | +check "html content type" "Content-Type: text/html; charset=utf-8" "$Q" | |
| 386 | +check "html declares charset" "<meta charset=" "$Q" | |
| 387 | +check "html has a viewport" "width=device-width" "$Q" | |
| 388 | +check "html is CSP-locked" "default-src 'none'" "$Q" | |
| 389 | +check "html sets X-Frame-Options" "X-Frame-Options: SAMEORIGIN" "$Q" | |
| 390 | +check_not "html never sends Content-Length" "Content-Length:" "$Q" | |
| 391 | +check_not "html has no CDN script" "<script src=" "$Q" | |
| 392 | +check_not "html has no cdnjs" "cdnjs" "$Q" | |
| 393 | +check_not "html has no googleapis" "googleapis" "$Q" | |
| 394 | +check_not "html has no private IPs" "192.168." "$Q" | |
| 395 | +check_not "html has no localhost URL" "http://127.0.0.1" "$Q" | |
| 396 | +check "html has the bot token block" "--bg-card" "$Q" | |
| 397 | +check "html prepaints the theme" "data-theme" "$Q" | |
| 398 | +check "html follows the bot" "sx-theme" "$Q" | |
| 399 | +check "html asks for the theme" "sx-theme-request" "$Q" | |
| 400 | +check "html flags embed mode" "embedded" "$Q" | |
| 401 | +check "html names the plugin" "Thought Chains" "$Q" | |
| 402 | +check "html branches the API route" "/plugin_seqthink?action=" "$Q" | |
| 403 | +check "html supports the hub proxy route" "/plugins?plugin=" "$Q" | |
| 404 | +check "html carries the node password" "X-Bot-Password" "$Q" | |
| 405 | +check "html calls the chains API" "api('chains')" "$Q" | |
| 406 | +check_not "html has no emoji" "💭" "$Q" | |
| 407 | +check_not "html has no emoji (revision)" "🔄" "$Q" | |
| 408 | +check_not "html has no emoji (branch)" "🌿" "$Q" | |
| 409 | +if grep -qF "💭" src/ui.html; then fail "ui source has no emoji"; else pass "ui source has no emoji"; fi | |
| 410 | +grep -c "<script>" src/ui.html >/dev/null 2>&1 && pass "ui has its own script tag" || fail "ui script tag missing" | |
| 411 | +grep -q "<style>" src/ui.html && pass "ui has its own style tag" || fail "ui style tag missing" | |
| 412 | +check_not "ui has no inline hex palette outside tokens" "#123456" "$Q" | |
| 413 | +if python3 tools/gen_ui.py --check >/dev/null 2>&1; then | |
| 414 | + pass "src/ui_html.h is generated from src/ui.html" | |
| 415 | +else | |
| 416 | + fail "src/ui_html.h is stale (run tools/gen_ui.py)" | |
| 417 | +fi | |
| 418 | + | |
| 419 | +section "source invariants" | |
| 420 | +check "_WIN32 forces binary stdout" "_setmode(_fileno(stdout), _O_BINARY)" "$SRC_TXT" | |
| 421 | +check "_WIN32 gate precedes includes" "_WIN32_WINNT 0x0601" "$SRC_TXT" | |
| 422 | +check "Apple needs _DARWIN_C_SOURCE" "_DARWIN_C_SOURCE" "$SRC_TXT" | |
| 423 | +check "meta is emitted before auth" "return run_meta();" "$SRC_TXT" | |
| 424 | +check "mcp mode is dispatched" "return run_mcp();" "$SRC_TXT" | |
| 425 | +check_not "no shell command execution" "popen(" "$SRC_TXT" | |
| 426 | +check_not "no system()" "system(" "$SRC_TXT" | |
| 427 | +check_not "no sockets" "socket(" "$SRC_TXT" | |
| 428 | +check_not "no TLS client" "mbedtls" "$SRC_TXT" | |
| 429 | +check_not "no outbound http helper" "WinHttp" "$SRC_TXT" | |
| 430 | +check "chain ids are validated" "valid_chain_id" "$SRC_TXT" | |
| 431 | +check "history cap is bounded" "MAX_THOUGHT_HISTORY" "$SRC_TXT" | |
| 432 | +check "thought text is length-capped" "THOUGHT_MAX" "$SRC_TXT" | |
| 433 | +check "branch id is length-capped" "BRANCHID_MAX" "$SRC_TXT" | |
| 434 | +check "state dir honours the test override" "SEQTHINK_STATE_DIR" "$SRC_TXT" | |
| 435 | +check "state dir prefers /workspace" "/workspace/.scorpiox/connectors/" "$SRC_TXT" | |
| 436 | +check "state dir uses LOCALAPPDATA on win" "LOCALAPPDATA" "$SRC_TXT" | |
| 437 | +printf '%s' "$SRC_TXT" | grep -q getline && pass "mcp loop reads line-delimited stdio" || fail "mcp loop has no line reader" | |
| 438 | + | |
| 439 | +section "ASan + fortify (parses files it did not write)" | |
| 440 | +if [ ! -x ./plugin_seqthink.asan ] || [ "$SRC_TXT" -nt ./plugin_seqthink.asan ]; then | |
| 441 | + cc -g -O0 -std=c99 -Wall -Wextra -fsanitize=address -I src -I vendor \ | |
| 442 | + -o plugin_seqthink.asan src/plugin_seqthink.c vendor/yyjson.c >/dev/null 2>&1 \ | |
| 443 | + || echo " note: ASan build unavailable here" | |
| 444 | +fi | |
| 445 | +if [ -x ./plugin_seqthink.asan ]; then | |
| 446 | + cat > "$TMP/in.jsonl" <<'JSONL' | |
| 447 | +{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"asan thought with \"quotes\" and \\ backslash and \ntab\t","nextThoughtNeeded":true,"isRevision":true,"revisesThought":1,"thoughtNumber":1,"totalThoughts":2}}} | |
| 448 | +{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"unicode ünïcødé and émojis ok","nextThoughtNeeded":false,"branchFromThought":1,"branchId":"ünï","thoughtNumber":2,"totalThoughts":2}}} | |
| 449 | +JSONL | |
| 450 | + AOUT=$(SEQTHINK_STATE_DIR="$TMP/asan" ./plugin_seqthink.asan --mcp < "$TMP/in.jsonl" 2>"$TMP/aerr.txt") | |
| 451 | + if grep -q "AddressSanitizer" "$TMP/aerr.txt"; then | |
| 452 | + fail "ASan reported a problem"; sed -n 1,12p "$TMP/aerr.txt" | |
| 453 | + else | |
| 454 | + pass "ASan clean on quotes/backslash/newline/unicode thoughts" | |
| 455 | + fi | |
| 456 | + check "ASan run still answered" '"isError":false' "$AOUT" | |
| 457 | + R=$(SEQTHINK_STATE_DIR="$TMP/asan" QUERY_STRING="action=chains" ./plugin_seqthink.asan; true) | |
| 458 | + if grep -q "AddressSanitizer" "$TMP/aerr.txt"; then fail "ASan clean on the CGI read path" | |
| 459 | + else pass "ASan clean on the CGI read path"; fi | |
| 460 | + printf '{{{ not json' > "$TMP/asan/chains.json" | |
| 461 | + SEQTHINK_STATE_DIR="$TMP/asan" QUERY_STRING="action=chains" ./plugin_seqthink.asan >/dev/null 2>>"$TMP/aerr.txt" | |
| 462 | + SEQTHINK_STATE_DIR="$TMP/asan" QUERY_STRING="action=chain&id=th-x" ./plugin_seqthink.asan >/dev/null 2>>"$TMP/aerr.txt" | |
| 463 | + printf '{"chains":[{"id":42,"thoughts":"not an array"},{"thoughts":[]}]}' > "$TMP/asan/chains.json" | |
| 464 | + SEQTHINK_STATE_DIR="$TMP/asan" QUERY_STRING="action=stats" ./plugin_seqthink.asan >/dev/null 2>>"$TMP/aerr.txt" | |
| 465 | + if grep -q "AddressSanitizer" "$TMP/aerr.txt"; then fail "ASan clean on malformed stores" | |
| 466 | + else pass "ASan clean on malformed stores"; fi | |
| 467 | +else | |
| 468 | + echo " skip ASan checks (build unavailable)" | |
| 469 | +fi | |
| 470 | + | |
| 471 | +if [ ! -x ./plugin_seqthink.fortify ]; then | |
| 472 | + cc -O2 -std=c99 -Wall -Wextra -D_FORTIFY_SOURCE=2 -I src -I vendor \ | |
| 473 | + -o plugin_seqthink.fortify src/plugin_seqthink.c vendor/yyjson.c >/dev/null 2>&1 \ | |
| 474 | + || echo " note: fortify build unavailable here" | |
| 475 | +fi | |
| 476 | +if [ -x ./plugin_seqthink.fortify ]; then | |
| 477 | + SEQTHINK_STATE_DIR="$TMP/fort" ./plugin_seqthink.fortify --mcp < "$TMP/in.jsonl" >/dev/null 2>"$TMP/ferr.txt" | |
| 478 | + if grep -qi "buffer overflow" "$TMP/ferr.txt"; then fail "fortify build aborted" | |
| 479 | + else pass "fortify build survives the full session"; fi | |
| 480 | +else | |
| 481 | + echo " skip fortify checks (build unavailable)" | |
| 482 | +fi | |
| 483 | + | |
| 484 | +# ---------------------------------------------------------------- audit | |
| 485 | +section "clean-room audit (working tree + full git history)" | |
| 486 | +audit() { # audit <label> <regex> | |
| 487 | + local out | |
| 488 | + out=$(git grep -InE -e "$2" -- . 2>/dev/null | grep -v 'tests/run.sh' | head -5 || true) | |
| 489 | + if [ -n "$out" ]; then | |
| 490 | + fail "audit: $1"; printf '%s\n' "$out" | sed 's/^/ /' | |
| 491 | + else | |
| 492 | + pass "audit: $1" | |
| 493 | + fi | |
| 494 | +} | |
| 495 | +audit "no LAN 192.168 addresses" '192\.168\.[0-9]+\.[0-9]+' | |
| 496 | +audit "no private 10.x addresses" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | |
| 497 | +PAT="gh""p_[A-Za-z0-9]{36}" | |
| 498 | +audit "no PAT prefix" "$PAT" | |
| 499 | +TOK="3e""f2c00c" | |
| 500 | +audit "no token prefix" "$TOK" | |
| 501 | +SFP="ssh""pass -p " | |
| 502 | +audit "no ssh password flag" "$SFP" | |
| 503 | +HOSTS="macm""ini|intel-""ultra""2|lazar""us" | |
| 504 | +audit "no internal hostnames" "$HOSTS" | |
| 505 | +if ! git rev-parse HEAD >/dev/null 2>&1; then | |
| 506 | + echo " skip git-history audit (repository has no commits yet)" | |
| 507 | +elif command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | |
| 508 | + if scorpiox-cli-botplugin audit "$ROOT" >/dev/null 2>&1; then | |
| 509 | + pass "scorpiox-cli-botplugin audit accepts the repo" | |
| 510 | + else | |
| 511 | + fail "scorpiox-cli-botplugin audit rejected the repo" | |
| 512 | + scorpiox-cli-botplugin audit "$ROOT" 2>&1 | tail -10 | sed 's/^/ /' | |
| 513 | + fi | |
| 514 | +else | |
| 515 | + echo " skip scorpiox-cli-botplugin audit (not installed here)" | |
| 516 | +fi | |
| 517 | + | |
| 518 | +printf '\n%s==============================%s\n' "$C_B" "$C_0" | |
| 519 | +printf ' %s%d passed%s %s%d failed%s\n' "$C_OK" "$PASS" "$C_0" "$([ "$FAIL" -gt 0 ] && printf '%s' "$C_BAD" || printf '%s')" "$FAIL" "$C_0" | |
| 520 | +[ "$FAIL" -eq 0 ] || exit 1 | |
| 521 | +exit 0 |
| 1 | 1 | new file mode 100644 |
| index 0000000..69b1759 | ||
| --- /dev/null | ||
| +++ b/tools/gen_ui.py | ||
| @@ -0,0 +1,105 @@ | ||
| 1 | +#!/usr/bin/env python3 | |
| 2 | +"""tools/gen_ui.py - compile src/ui.html into src/ui_html.h. | |
| 3 | + | |
| 4 | +The page lives in one readable file (src/ui.html) so it can be diffed and | |
| 5 | +reviewed like any other source. This script turns it into a single C string | |
| 6 | +constant with two control-character placeholders: | |
| 7 | + | |
| 8 | + 0x01 -> the bot theme prepaint script + <style> + theme tokens | |
| 9 | + 0x02 -> the bot theme handoff script (just before </body>) | |
| 10 | + | |
| 11 | +main() splits the constant on those bytes and emits the macros from | |
| 12 | +src/bot_theme_plugin.h in their place, so the theme can never drift out of | |
| 13 | +sync with the rest of the bot. | |
| 14 | + | |
| 15 | + python3 tools/gen_ui.py # write src/ui_html.h | |
| 16 | + python3 tools/gen_ui.py --check # exit 1 when the header is stale | |
| 17 | +""" | |
| 18 | + | |
| 19 | +import os | |
| 20 | +import sys | |
| 21 | + | |
| 22 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| 23 | +SRC = os.path.join(ROOT, "src", "ui.html") | |
| 24 | +OUT = os.path.join(ROOT, "src", "ui_html.h") | |
| 25 | + | |
| 26 | +TOKENS = "<!--TOKENS-->" | |
| 27 | +MARK_TOKENS = "\u0001" | |
| 28 | +MARK_HANDOFF = "\u0002" | |
| 29 | + | |
| 30 | + | |
| 31 | +def c_literal(text): | |
| 32 | + """Escape text for a C string literal, one line per source line.""" | |
| 33 | + out = [] | |
| 34 | + for line in text.splitlines(True): | |
| 35 | + piece = [] | |
| 36 | + for ch in line: | |
| 37 | + if ch == "\\": | |
| 38 | + piece.append("\\\\") | |
| 39 | + elif ch == '"': | |
| 40 | + piece.append('\\"') | |
| 41 | + elif ch == "\n": | |
| 42 | + piece.append("\\n") | |
| 43 | + elif ch == "\r": | |
| 44 | + piece.append("\\r") | |
| 45 | + elif ch == "\t": | |
| 46 | + piece.append("\\t") | |
| 47 | + elif ch == MARK_TOKENS: | |
| 48 | + piece.append("\\001") | |
| 49 | + elif ch == MARK_HANDOFF: | |
| 50 | + piece.append("\\002") | |
| 51 | + elif ord(ch) < 0x20: | |
| 52 | + piece.append("\\%03o" % ord(ch)) | |
| 53 | + else: | |
| 54 | + piece.append(ch) | |
| 55 | + out.append(' "%s"\n' % "".join(piece)) | |
| 56 | + return "".join(out) | |
| 57 | + | |
| 58 | + | |
| 59 | +def render(): | |
| 60 | + with open(SRC, "r", encoding="utf-8") as f: | |
| 61 | + html = f.read() | |
| 62 | + | |
| 63 | + if TOKENS not in html: | |
| 64 | + raise SystemExit("src/ui.html has no %s placeholder" % TOKENS) | |
| 65 | + html = html.replace(TOKENS, MARK_TOKENS) | |
| 66 | + | |
| 67 | + # Handoff script goes right before the closing body tag. | |
| 68 | + if "</body>" not in html: | |
| 69 | + raise SystemExit("src/ui.html has no </body>") | |
| 70 | + html = html.replace("</body>", MARK_HANDOFF + "</body>", 1) | |
| 71 | + | |
| 72 | + header = ( | |
| 73 | + "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n" | |
| 74 | + "#ifndef SX_SEQTHINK_UI_HTML_H\n" | |
| 75 | + "#define SX_SEQTHINK_UI_HTML_H\n" | |
| 76 | + "\n" | |
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | |
| 78 | + "\n" | |
| 79 | + "#endif /* SX_SEQTHINK_UI_HTML_H */\n" | |
| 80 | + ) | |
| 81 | + return header | |
| 82 | + | |
| 83 | + | |
| 84 | +def main(): | |
| 85 | + header = render() | |
| 86 | + check = "--check" in sys.argv[1:] | |
| 87 | + if check: | |
| 88 | + try: | |
| 89 | + with open(OUT, "r", encoding="utf-8") as f: | |
| 90 | + cur = f.read() | |
| 91 | + except OSError: | |
| 92 | + cur = "" | |
| 93 | + if cur != header: | |
| 94 | + sys.stderr.write("src/ui_html.h is stale - run tools/gen_ui.py\n") | |
| 95 | + return 1 | |
| 96 | + print("src/ui_html.h is up to date") | |
| 97 | + return 0 | |
| 98 | + with open(OUT, "w", encoding="utf-8") as f: | |
| 99 | + f.write(header) | |
| 100 | + print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header))) | |
| 101 | + return 0 | |
| 102 | + | |
| 103 | + | |
| 104 | +if __name__ == "__main__": | |
| 105 | + sys.exit(main()) |
| 1 | 1 | new file mode 100644 |
| index 0000000..d1ee097 | ||
| --- /dev/null | ||
| +++ b/vendor/LICENSE.yyjson.txt | ||
| @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | |
| 2 | + | |
| 3 | +Copyright (c) 2020 YaoYuan <ibireme@gmail.com> | |
| 4 | + | |
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 6 | +of this software and associated documentation files (the "Software"), to deal | |
| 7 | +in the Software without restriction, including without limitation the rights | |
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 9 | +copies of the Software, and to permit persons to whom the Software is | |
| 10 | +furnished to do so, subject to the following conditions: | |
| 11 | + | |
| 12 | +The above copyright notice and this permission notice shall be included in all | |
| 13 | +copies or substantial portions of the Software. | |
| 14 | + | |
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 21 | +SOFTWARE. |
| 1 | 1 | new file mode 100644 |
| index 0000000..9c445e8 | ||
| --- /dev/null | ||
| +++ b/vendor/yyjson.c | ||
| @@ -0,0 +1,11224 @@ | ||
| 1 | +/*============================================================================== | |
| 2 | + Copyright (c) 2020 YaoYuan <ibireme@gmail.com> | |
| 3 | + | |
| 4 | + Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 5 | + of this software and associated documentation files (the "Software"), to deal | |
| 6 | + in the Software without restriction, including without limitation the rights | |
| 7 | + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 8 | + copies of the Software, and to permit persons to whom the Software is | |
| 9 | + furnished to do so, subject to the following conditions: | |
| 10 | + | |
| 11 | + The above copyright notice and this permission notice shall be included in all | |
| 12 | + copies or substantial portions of the Software. | |
| 13 | + | |
| 14 | + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 15 | + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 16 | + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 17 | + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 18 | + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 19 | + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 20 | + SOFTWARE. | |
| 21 | + *============================================================================*/ | |
| 22 | + | |
| 23 | +#include "yyjson.h" | |
| 24 | +#include <math.h> /* for `HUGE_VAL/INFINIY/NAN` macros, no libm required */ | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | +/*============================================================================== | |
| 29 | + * MARK: - Warning Suppress (Private) | |
| 30 | + *============================================================================*/ | |
| 31 | + | |
| 32 | +#if defined(__clang__) | |
| 33 | +# pragma clang diagnostic ignored "-Wunused-function" | |
| 34 | +# pragma clang diagnostic ignored "-Wunused-parameter" | |
| 35 | +# pragma clang diagnostic ignored "-Wunused-label" | |
| 36 | +# pragma clang diagnostic ignored "-Wunused-macros" | |
| 37 | +# pragma clang diagnostic ignored "-Wunused-variable" | |
| 38 | +#elif YYJSON_IS_REAL_GCC | |
| 39 | +# pragma GCC diagnostic ignored "-Wunused-function" | |
| 40 | +# pragma GCC diagnostic ignored "-Wunused-parameter" | |
| 41 | +# pragma GCC diagnostic ignored "-Wunused-label" | |
| 42 | +# pragma GCC diagnostic ignored "-Wunused-macros" | |
| 43 | +# pragma GCC diagnostic ignored "-Wunused-variable" | |
| 44 | +#elif defined(_MSC_VER) | |
| 45 | +# pragma warning(disable:4100) /* unreferenced formal parameter */ | |
| 46 | +# pragma warning(disable:4101) /* unreferenced variable */ | |
| 47 | +# pragma warning(disable:4102) /* unreferenced label */ | |
| 48 | +# pragma warning(disable:4127) /* conditional expression is constant */ | |
| 49 | +# pragma warning(disable:4702) /* unreachable code */ | |
| 50 | +# pragma warning(disable:4706) /* assignment within conditional expression */ | |
| 51 | +#endif | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | +/*============================================================================== | |
| 56 | + * MARK: - Version (Public) | |
| 57 | + *============================================================================*/ | |
| 58 | + | |
| 59 | +uint32_t yyjson_version(void) { | |
| 60 | + return YYJSON_VERSION_HEX; | |
| 61 | +} | |
| 62 | + | |
| 63 | + | |
| 64 | + | |
| 65 | +/*============================================================================== | |
| 66 | + * MARK: - Flags (Private) | |
| 67 | + *============================================================================*/ | |
| 68 | + | |
| 69 | +/* msvc intrinsic */ | |
| 70 | +#if YYJSON_MSC_VER >= 1400 | |
| 71 | +# include <intrin.h> | |
| 72 | +# if defined(_M_AMD64) || defined(_M_ARM64) | |
| 73 | +# define MSC_HAS_BIT_SCAN_64 1 | |
| 74 | +# pragma intrinsic(_BitScanForward64) | |
| 75 | +# pragma intrinsic(_BitScanReverse64) | |
| 76 | +# else | |
| 77 | +# define MSC_HAS_BIT_SCAN_64 0 | |
| 78 | +# endif | |
| 79 | +# if defined(_M_AMD64) || defined(_M_ARM64) || \ | |
| 80 | + defined(_M_IX86) || defined(_M_ARM) | |
| 81 | +# define MSC_HAS_BIT_SCAN 1 | |
| 82 | +# pragma intrinsic(_BitScanForward) | |
| 83 | +# pragma intrinsic(_BitScanReverse) | |
| 84 | +# else | |
| 85 | +# define MSC_HAS_BIT_SCAN 0 | |
| 86 | +# endif | |
| 87 | +# if defined(_M_AMD64) | |
| 88 | +# define MSC_HAS_UMUL128 1 | |
| 89 | +# pragma intrinsic(_umul128) | |
| 90 | +# else | |
| 91 | +# define MSC_HAS_UMUL128 0 | |
| 92 | +# endif | |
| 93 | +#else | |
| 94 | +# define MSC_HAS_BIT_SCAN_64 0 | |
| 95 | +# define MSC_HAS_BIT_SCAN 0 | |
| 96 | +# define MSC_HAS_UMUL128 0 | |
| 97 | +#endif | |
| 98 | + | |
| 99 | +/* gcc builtin */ | |
| 100 | +#if yyjson_has_builtin(__builtin_clzll) || yyjson_gcc_available(3, 4, 0) | |
| 101 | +# define GCC_HAS_CLZLL 1 | |
| 102 | +#else | |
| 103 | +# define GCC_HAS_CLZLL 0 | |
| 104 | +#endif | |
| 105 | + | |
| 106 | +#if yyjson_has_builtin(__builtin_ctzll) || yyjson_gcc_available(3, 4, 0) | |
| 107 | +# define GCC_HAS_CTZLL 1 | |
| 108 | +#else | |
| 109 | +# define GCC_HAS_CTZLL 0 | |
| 110 | +#endif | |
| 111 | + | |
| 112 | +/* int128 type */ | |
| 113 | +#if defined(__SIZEOF_INT128__) && (__SIZEOF_INT128__ == 16) && \ | |
| 114 | + (defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER)) | |
| 115 | +# define YYJSON_HAS_INT128 1 | |
| 116 | +#else | |
| 117 | +# define YYJSON_HAS_INT128 0 | |
| 118 | +#endif | |
| 119 | + | |
| 120 | +/* IEEE 754 floating-point binary representation */ | |
| 121 | +#if defined(__STDC_IEC_559__) || defined(__STDC_IEC_60559_BFP__) | |
| 122 | +# define YYJSON_HAS_IEEE_754 1 | |
| 123 | +#elif FLT_RADIX == 2 && \ | |
| 124 | + FLT_MANT_DIG == 24 && FLT_DIG == 6 && \ | |
| 125 | + FLT_MIN_EXP == -125 && FLT_MAX_EXP == 128 && \ | |
| 126 | + FLT_MIN_10_EXP == -37 && FLT_MAX_10_EXP == 38 && \ | |
| 127 | + DBL_MANT_DIG == 53 && DBL_DIG == 15 && \ | |
| 128 | + DBL_MIN_EXP == -1021 && DBL_MAX_EXP == 1024 && \ | |
| 129 | + DBL_MIN_10_EXP == -307 && DBL_MAX_10_EXP == 308 | |
| 130 | +# define YYJSON_HAS_IEEE_754 1 | |
| 131 | +#else | |
| 132 | +# define YYJSON_HAS_IEEE_754 0 | |
| 133 | +# undef YYJSON_DISABLE_FAST_FP_CONV | |
| 134 | +# define YYJSON_DISABLE_FAST_FP_CONV 1 | |
| 135 | +#endif | |
| 136 | + | |
| 137 | +/* | |
| 138 | + Correct rounding in double number computations. | |
| 139 | + | |
| 140 | + On the x86 architecture, some compilers may use x87 FPU instructions for | |
| 141 | + floating-point arithmetic. The x87 FPU loads all floating point number as | |
| 142 | + 80-bit double-extended precision internally, then rounds the result to original | |
| 143 | + precision, which may produce inaccurate results. For a more detailed | |
| 144 | + explanation, see the paper: https://arxiv.org/abs/cs/0701192 | |
| 145 | + | |
| 146 | + Here are some examples of double precision calculation error: | |
| 147 | + | |
| 148 | + 2877.0 / 1e6 == 0.002877, but x87 returns 0.0028770000000000002 | |
| 149 | + 43683.0 * 1e21 == 4.3683e25, but x87 returns 4.3683000000000004e25 | |
| 150 | + | |
| 151 | + Here are some examples of compiler flags to generate x87 instructions on x86: | |
| 152 | + | |
| 153 | + clang -m32 -mno-sse | |
| 154 | + gcc/icc -m32 -mfpmath=387 | |
| 155 | + msvc /arch:SSE or /arch:IA32 | |
| 156 | + | |
| 157 | + If we are sure that there's no similar error described above, we can define the | |
| 158 | + YYJSON_DOUBLE_MATH_CORRECT as 1 to enable the fast path calculation. This is | |
| 159 | + not an accurate detection, it's just try to avoid the error at compile-time. | |
| 160 | + An accurate detection can be done at run-time: | |
| 161 | + | |
| 162 | + bool is_double_math_correct(void) { | |
| 163 | + volatile double r = 43683.0; | |
| 164 | + r *= 1e21; | |
| 165 | + return r == 4.3683e25; | |
| 166 | + } | |
| 167 | + | |
| 168 | + See also: utils.h in https://github.com/google/double-conversion/ | |
| 169 | + */ | |
| 170 | +#if !defined(FLT_EVAL_METHOD) && defined(__FLT_EVAL_METHOD__) | |
| 171 | +# define FLT_EVAL_METHOD __FLT_EVAL_METHOD__ | |
| 172 | +#endif | |
| 173 | + | |
| 174 | +#if defined(FLT_EVAL_METHOD) && FLT_EVAL_METHOD != 0 && FLT_EVAL_METHOD != 1 | |
| 175 | +# define YYJSON_DOUBLE_MATH_CORRECT 0 | |
| 176 | +#elif defined(i386) || defined(__i386) || defined(__i386__) || \ | |
| 177 | + defined(_X86_) || defined(__X86__) || defined(_M_IX86) || \ | |
| 178 | + defined(__I86__) || defined(__IA32__) || defined(__THW_INTEL) | |
| 179 | +# if (defined(_MSC_VER) && defined(_M_IX86_FP) && _M_IX86_FP == 2) || \ | |
| 180 | + (defined(__SSE2_MATH__) && __SSE2_MATH__) | |
| 181 | +# define YYJSON_DOUBLE_MATH_CORRECT 1 | |
| 182 | +# else | |
| 183 | +# define YYJSON_DOUBLE_MATH_CORRECT 0 | |
| 184 | +# endif | |
| 185 | +#elif defined(__mc68000__) || defined(__pnacl__) || defined(__native_client__) | |
| 186 | +# define YYJSON_DOUBLE_MATH_CORRECT 0 | |
| 187 | +#else | |
| 188 | +# define YYJSON_DOUBLE_MATH_CORRECT 1 | |
| 189 | +#endif | |
| 190 | + | |
| 191 | +/* | |
| 192 | + Detect the endianness at compile-time. | |
| 193 | + YYJSON_ENDIAN == YYJSON_BIG_ENDIAN | |
| 194 | + YYJSON_ENDIAN == YYJSON_LITTLE_ENDIAN | |
| 195 | + */ | |
| 196 | +#define YYJSON_BIG_ENDIAN 4321 | |
| 197 | +#define YYJSON_LITTLE_ENDIAN 1234 | |
| 198 | + | |
| 199 | +#if yyjson_has_include(<sys/types.h>) | |
| 200 | +# include <sys/types.h> /* POSIX */ | |
| 201 | +#endif | |
| 202 | +#if yyjson_has_include(<endian.h>) | |
| 203 | +# include <endian.h> /* Linux */ | |
| 204 | +#elif yyjson_has_include(<sys/endian.h>) | |
| 205 | +# include <sys/endian.h> /* BSD, Android */ | |
| 206 | +#elif yyjson_has_include(<machine/endian.h>) | |
| 207 | +# include <machine/endian.h> /* BSD, Darwin */ | |
| 208 | +#endif | |
| 209 | + | |
| 210 | +#if defined(BYTE_ORDER) && BYTE_ORDER | |
| 211 | +# if defined(BIG_ENDIAN) && (BYTE_ORDER == BIG_ENDIAN) | |
| 212 | +# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN | |
| 213 | +# elif defined(LITTLE_ENDIAN) && (BYTE_ORDER == LITTLE_ENDIAN) | |
| 214 | +# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN | |
| 215 | +# endif | |
| 216 | +#elif defined(__BYTE_ORDER) && __BYTE_ORDER | |
| 217 | +# if defined(__BIG_ENDIAN) && (__BYTE_ORDER == __BIG_ENDIAN) | |
| 218 | +# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN | |
| 219 | +# elif defined(__LITTLE_ENDIAN) && (__BYTE_ORDER == __LITTLE_ENDIAN) | |
| 220 | +# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN | |
| 221 | +# endif | |
| 222 | +#elif defined(__BYTE_ORDER__) && __BYTE_ORDER__ | |
| 223 | +# if defined(__ORDER_BIG_ENDIAN__) && \ | |
| 224 | + (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) | |
| 225 | +# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN | |
| 226 | +# elif defined(__ORDER_LITTLE_ENDIAN__) && \ | |
| 227 | + (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) | |
| 228 | +# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN | |
| 229 | +# endif | |
| 230 | +#elif (defined(__LITTLE_ENDIAN__) && __LITTLE_ENDIAN__ == 1) || \ | |
| 231 | + defined(__i386) || defined(__i386__) || \ | |
| 232 | + defined(_X86_) || defined(__X86__) || \ | |
| 233 | + defined(_M_IX86) || defined(__THW_INTEL__) || \ | |
| 234 | + defined(__x86_64) || defined(__x86_64__) || \ | |
| 235 | + defined(__amd64) || defined(__amd64__) || \ | |
| 236 | + defined(_M_AMD64) || defined(_M_X64) || \ | |
| 237 | + defined(_M_ARM) || defined(_M_ARM64) || \ | |
| 238 | + defined(__ARMEL__) || defined(__THUMBEL__) || defined(__AARCH64EL__) || \ | |
| 239 | + defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) || \ | |
| 240 | + defined(__EMSCRIPTEN__) || defined(__wasm__) || \ | |
| 241 | + defined(__loongarch__) | |
| 242 | +# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN | |
| 243 | +#elif (defined(__BIG_ENDIAN__) && __BIG_ENDIAN__ == 1) || \ | |
| 244 | + defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || \ | |
| 245 | + defined(_MIPSEB) || defined(__MIPSEB) || defined(__MIPSEB__) || \ | |
| 246 | + defined(__or1k__) || defined(__OR1K__) | |
| 247 | +# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN | |
| 248 | +#else | |
| 249 | +# define YYJSON_ENDIAN 0 /* unknown endian, detect at run-time */ | |
| 250 | +#endif | |
| 251 | + | |
| 252 | +/* | |
| 253 | + This macro controls how yyjson handles unaligned memory accesses. | |
| 254 | + | |
| 255 | + By default, yyjson uses `memcpy()` for memory copying. This allows the compiler | |
| 256 | + to optimize the code and emit unaligned memory access instructions when | |
| 257 | + supported by the target architecture. | |
| 258 | + | |
| 259 | + However, on some older compilers or architectures where `memcpy()` is not | |
| 260 | + well-optimized and may result in unnecessary function calls, defining this | |
| 261 | + macro as 1 may help. In such cases, yyjson switches to manual byte-by-byte | |
| 262 | + access, which can potentially improve performance. | |
| 263 | + | |
| 264 | + An example of the generated assembly code for ARM can be found here: | |
| 265 | + https://godbolt.org/z/334jjhxPT | |
| 266 | + | |
| 267 | + This flag is already enabled for common architectures in the following code, | |
| 268 | + so manual configuration is usually unnecessary. If unsure, you can check the | |
| 269 | + generated assembly or run benchmarks to make an informed decision. | |
| 270 | + */ | |
| 271 | +#ifndef YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS | |
| 272 | +# if defined(__ia64) || defined(_IA64) || defined(__IA64__) || \ | |
| 273 | + defined(__ia64__) || defined(_M_IA64) || defined(__itanium__) | |
| 274 | +# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* Itanium */ | |
| 275 | +# elif (defined(__arm__) || defined(__arm64__) || defined(__aarch64__)) && \ | |
| 276 | + (defined(__GNUC__) || defined(__clang__)) && \ | |
| 277 | + (!defined(__ARM_FEATURE_UNALIGNED) || !__ARM_FEATURE_UNALIGNED) | |
| 278 | +# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* ARM */ | |
| 279 | +# elif defined(__sparc) || defined(__sparc__) | |
| 280 | +# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* SPARC */ | |
| 281 | +# elif defined(__mips) || defined(__mips__) || defined(__MIPS__) | |
| 282 | +# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* MIPS */ | |
| 283 | +# elif defined(__m68k__) || defined(M68000) | |
| 284 | +# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* M68K */ | |
| 285 | +# else | |
| 286 | +# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 0 | |
| 287 | +# endif | |
| 288 | +#endif | |
| 289 | + | |
| 290 | +/* | |
| 291 | + Estimated initial ratio of the JSON data (data_size / value_count). | |
| 292 | + For example: | |
| 293 | + | |
| 294 | + data: {"id":12345678,"name":"Harry"} | |
| 295 | + data_size: 30 | |
| 296 | + value_count: 5 | |
| 297 | + ratio: 6 | |
| 298 | + | |
| 299 | + yyjson uses dynamic memory with a growth factor of 1.5 when reading and writing | |
| 300 | + JSON, the ratios below are used to determine the initial memory size. | |
| 301 | + | |
| 302 | + A too large ratio will waste memory, and a too small ratio will cause multiple | |
| 303 | + memory growths and degrade performance. Currently, these ratios are generated | |
| 304 | + with some commonly used JSON datasets. | |
| 305 | + */ | |
| 306 | +#define YYJSON_READER_ESTIMATED_PRETTY_RATIO 16 | |
| 307 | +#define YYJSON_READER_ESTIMATED_MINIFY_RATIO 6 | |
| 308 | +#define YYJSON_WRITER_ESTIMATED_PRETTY_RATIO 32 | |
| 309 | +#define YYJSON_WRITER_ESTIMATED_MINIFY_RATIO 18 | |
| 310 | + | |
| 311 | +/* The initial and maximum size of the memory pool's chunk in yyjson_mut_doc. */ | |
| 312 | +#define YYJSON_MUT_DOC_STR_POOL_INIT_SIZE 0x100 | |
| 313 | +#define YYJSON_MUT_DOC_STR_POOL_MAX_SIZE 0x1 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..960ea27 | index 0000000..960ea27 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/.gitignore | +++ b/.gitignore | ||
| @@ -0,0 +1,13 @@ | @@ -0,0 +1,13 @@ | ||
| 1 | +plugin_seqthink | ||
| 2 | +plugin_seqthink.exe | ||
| 3 | +plugin_seqthink.musl | ||
| 4 | +plugin_seqthink.arm64 | ||
| 5 | +plugin_seqthink.asan | ||
| 6 | +plugin_seqthink.fortify | ||
| 7 | +plugin_seqthink.macos-arm64 | ||
| 8 | +plugin_seqthink.macos-x86_64 | ||
| 9 | +bin/ | ||
| 10 | +dist/ | ||
| 11 | +*.o | ||
| 12 | +__pycache__/ | ||
| 13 | +*.pyc |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..edac426 | index 0000000..edac426 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/LICENSE | +++ b/LICENSE | ||
| @@ -0,0 +1,21 @@ | @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | ||
| 2 | + | ||
| 3 | +Copyright (c) 2026 SCORPIOX INC. | ||
| 4 | + | ||
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 6 | +of this software and associated documentation files (the "Software"), to deal | ||
| 7 | +in the Software without restriction, including without limitation the rights | ||
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 9 | +copies of the Software, and to permit persons to whom the Software is | ||
| 10 | +furnished to do so, subject to the following conditions: | ||
| 11 | + | ||
| 12 | +The above copyright notice and this permission notice shall be included in all | ||
| 13 | +copies or substantial portions of the Software. | ||
| 14 | + | ||
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 21 | +SOFTWARE. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..53cdb2e | index 0000000..53cdb2e | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/Makefile | +++ b/Makefile | ||
| @@ -0,0 +1,79 @@ | @@ -0,0 +1,79 @@ | ||
| 1 | +# plugin_seqthink - SCORPIOX BOT open-source sequential-thinking MCP connector | ||
| 2 | +# | ||
| 3 | +# Targets: | ||
| 4 | +# make native build -> ./plugin_seqthink | ||
| 5 | +# make musl static musl x86_64 -> ./plugin_seqthink (fully static) | ||
| 6 | +# make arm64 static aarch64 -> ./plugin_seqthink.arm64 | ||
| 7 | +# make win64 MinGW-w64 static -> ./plugin_seqthink.exe | ||
| 8 | +# make macos Apple clang -> ./plugin_seqthink (run on macOS) | ||
| 9 | +# make asan -fsanitize=address build -> ./plugin_seqthink.asan | ||
| 10 | +# make fortify -D_FORTIFY_SOURCE=2 build -> ./plugin_seqthink.fortify | ||
| 11 | +# make ui regenerate src/ui_html.h from src/ui.html | ||
| 12 | +# make test build + run tests/run.sh | ||
| 13 | +# make clean | ||
| 14 | + | ||
| 15 | +CC ?= cc | ||
| 16 | +CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings | ||
| 17 | +MUSL_CC ?= musl-gcc | ||
| 18 | +MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | ||
| 19 | +ARM64_CC ?= aarch64-linux-musl-gcc | ||
| 20 | +ARM64_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | ||
| 21 | +WIN_CC ?= x86_64-w64-mingw32-gcc | ||
| 22 | +WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static | ||
| 23 | +SRC := src/plugin_seqthink.c vendor/yyjson.c | ||
| 24 | +HDR := src/bot_theme_plugin.h src/ui_html.h vendor/yyjson.h | ||
| 25 | +INC := -I src -I vendor | ||
| 26 | +BIN := plugin_seqthink | ||
| 27 | +EXE := plugin_seqthink.exe | ||
| 28 | + | ||
| 29 | +.PHONY: all native musl arm64 win64 macos asan fortify ui test clean help | ||
| 30 | + | ||
| 31 | +all: native | ||
| 32 | + | ||
| 33 | +native: $(BIN) | ||
| 34 | + | ||
| 35 | +$(BIN): $(SRC) $(HDR) | ||
| 36 | + @echo "==> native build ($(CC))" | ||
| 37 | + $(CC) $(CFLAGS) $(INC) -o $(BIN) $(SRC) | ||
| 38 | + | ||
| 39 | +# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy) | ||
| 40 | +musl: $(SRC) $(HDR) | ||
| 41 | + @echo "==> static musl build ($(MUSL_CC))" | ||
| 42 | + $(MUSL_CC) $(MUSL_CFLAGS) $(INC) -o $(BIN) $(SRC) | ||
| 43 | + | ||
| 44 | +# Static aarch64 build - Raspberry Pi 5 / ARM64 servers | ||
| 45 | +arm64: $(SRC) $(HDR) | ||
| 46 | + @echo "==> static aarch64 build ($(ARM64_CC))" | ||
| 47 | + $(ARM64_CC) $(ARM64_CFLAGS) $(INC) -o $(BIN).arm64 $(SRC) | ||
| 48 | + | ||
| 49 | +# Native Win64 static PE - runs on any Windows 10/11 x64 node | ||
| 50 | +win64: $(SRC) $(HDR) | ||
| 51 | + @echo "==> MinGW-w64 build ($(WIN_CC))" | ||
| 52 | + $(WIN_CC) $(WIN_CFLAGS) $(INC) -o $(EXE) $(SRC) | ||
| 53 | + | ||
| 54 | +# Apple clang build (run this on macOS) | ||
| 55 | +macos: $(SRC) $(HDR) | ||
| 56 | + @echo "==> Apple clang build" | ||
| 57 | + $(CC) $(CFLAGS) $(INC) -o $(BIN) $(SRC) | ||
| 58 | + | ||
| 59 | +asan: $(SRC) $(HDR) | ||
| 60 | + @echo "==> ASan build" | ||
| 61 | + $(CC) -g -O0 -std=c99 -Wall -Wextra -fsanitize=address $(INC) -o $(BIN).asan $(SRC) | ||
| 62 | + | ||
| 63 | +fortify: $(SRC) $(HDR) | ||
| 64 | + @echo "==> fortify build" | ||
| 65 | + $(CC) -O2 -std=c99 -Wall -Wextra -D_FORTIFY_SOURCE=2 $(INC) -o $(BIN).fortify $(SRC) | ||
| 66 | + | ||
| 67 | +ui: | ||
| 68 | + python3 tools/gen_ui.py | ||
| 69 | + | ||
| 70 | +test: native asan fortify | ||
| 71 | + @sh tests/run.sh | ||
| 72 | + | ||
| 73 | +clean: | ||
| 74 | + rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).asan $(BIN).fortify | ||
| 75 | + rm -f $(BIN).macos-arm64 $(BIN).macos-x86_64 | ||
| 76 | + rm -rf bin dist | ||
| 77 | + | ||
| 78 | +help: | ||
| 79 | + @echo "make | make musl | make arm64 | make win64 | make macos | make asan | make fortify | make ui | make test | make clean" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..a3dd890 | index 0000000..a3dd890 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/README.md | +++ b/README.md | ||
| @@ -0,0 +1,166 @@ | @@ -0,0 +1,166 @@ | ||
| 1 | +# plugin_seqthink — Sequential Thinking (SCORPIOX BOT plugin) | ||
| 2 | + | ||
| 3 | +`seqthink` is a clean-room, zero-dependency, pure C99 **MCP connector plugin** | ||
| 4 | +for [SCORPIOX BOT](https://bot.scorpiox.net). One small static binary serves the | ||
| 5 | +`sequentialthinking` tool over **MCP JSON-RPC 2.0 stdio** and ships a | ||
| 6 | +bot-themed **thought-chain viewer**, so structured step-by-step reasoning, | ||
| 7 | +revisions and branches made by an agent are inspectable on the node. | ||
| 8 | + | ||
| 9 | +It is a clean-room C port of the behaviour of the reference | ||
| 10 | +`modelcontextprotocol/servers` **sequential-thinking** server: the same | ||
| 11 | +parameter validation and error strings, the same "raise `totalThoughts` when | ||
| 12 | +`thoughtNumber` exceeds it" rule, the same per-connection history with a | ||
| 13 | +`MAX_THOUGHT_HISTORY` cap (oldest evicted, its branch shrunk with it, an | ||
| 14 | +emptied branch dropped), the same branch semantics (a branch exists only once a | ||
| 15 | +thought carries **both** `branchFromThought` and `branchId`), and the same | ||
| 16 | +five-field result. | ||
| 17 | + | ||
| 18 | +| | | | ||
| 19 | +|---|---| | ||
| 20 | +| Slug | `seqthink` | | ||
| 21 | +| Binary | `plugin_seqthink` (`plugin_seqthink.exe` on Windows) | | ||
| 22 | +| `--meta` | `{"name":"seqthink","desc":"Thought chains","kind":"mcp","mcp":true,"daemon":false,"menus":false,"verified":"live"}` | | ||
| 23 | +| Category | `devtools` | | ||
| 24 | +| Dependencies | none — vendored [yyjson](https://github.com/ibireme/yyjson) (MIT) is compiled in | | ||
| 25 | +| Network | **zero outbound requests** (no TLS, no sockets, no `popen`) | | ||
| 26 | +| State | its own connector directory only (see below) | | ||
| 27 | + | ||
| 28 | +## The four modes of one binary | ||
| 29 | + | ||
| 30 | +| Mode | Trigger | Contract | | ||
| 31 | +|---|---|---| | ||
| 32 | +| Discovery | `--meta` or `SX_PLUGIN_META=1` | one line of JSON, exit 0, **never authenticated** | | ||
| 33 | +| MCP server | `--mcp` | JSON-RPC 2.0 over stdio: `initialize`, `notifications/*`, `ping`, `tools/list`, `tools/call` | | ||
| 34 | +| Node API | `?action=...` or a POST JSON body | `Content-Type: application/json`, behind `require_node_auth()` | | ||
| 35 | +| Viewer UI | `GET` (default) | responsive dark/light HTML (`?embed=1`, `&theme=`, `sx-theme` handoff), zero `<script src=>` | | ||
| 36 | + | ||
| 37 | +```bash | ||
| 38 | +./plugin_seqthink --meta | ||
| 39 | +./plugin_seqthink --schema | ||
| 40 | +printf '%s\n' \ | ||
| 41 | + '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \ | ||
| 42 | + '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \ | ||
| 43 | + '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"first step","nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":3}}}' \ | ||
| 44 | + | ./plugin_seqthink --mcp | ||
| 45 | +``` | ||
| 46 | + | ||
| 47 | +## The `sequentialthinking` tool | ||
| 48 | + | ||
| 49 | +Input schema (exact parity with the reference server): | ||
| 50 | + | ||
| 51 | +| Field | Type | Req | Notes | | ||
| 52 | +|---|---|---|---| | ||
| 53 | +| `thought` | string | yes | the current thinking step (non-empty, ≤ 64 KB) | | ||
| 54 | +| `nextThoughtNeeded` | boolean | yes | a `"true"` / `"false"` string is accepted, like upstream | | ||
| 55 | +| `thoughtNumber` | integer ≥ 1 | yes | numbers **or** numeric strings (`z.coerce` parity) | | ||
| 56 | +| `totalThoughts` | integer ≥ 1 | yes | estimate; raised automatically when exceeded | | ||
| 57 | +| `isRevision` | boolean | no | this thought revises earlier thinking | | ||
| 58 | +| `revisesThought` | integer ≥ 1 | no | which thought number is reconsidered | | ||
| 59 | +| `branchFromThought` | integer ≥ 1 | no | branching point | | ||
| 60 | +| `branchId` | string | no | branch identifier (with `branchFromThought`, opens the branch) | | ||
| 61 | +| `needsMoreThoughts` | boolean | no | reached the end but more thoughts are needed | | ||
| 62 | + | ||
| 63 | +Every accepted thought returns exactly: | ||
| 64 | + | ||
| 65 | +```json | ||
| 66 | +{"thoughtNumber":1,"totalThoughts":3,"nextThoughtNeeded":true,"branches":[],"thoughtHistoryLength":1} | ||
| 67 | +``` | ||
| 68 | + | ||
| 69 | +as `result.content[0].text` **and** as `result.structuredContent`. A validation | ||
| 70 | +failure returns `{"error":"...","status":"failed"}` with `isError: true`, using | ||
| 71 | +the upstream messages (`Invalid thought: must be a string`, | ||
| 72 | +`Invalid thoughtNumber: must be a number`, `Invalid nextThoughtNeeded: must be | ||
| 73 | +a boolean`, ...). | ||
| 74 | + | ||
| 75 | +## Persistence (so the viewer can see agent reasoning) | ||
| 76 | + | ||
| 77 | +One `--mcp` process is one chain (a server lives as long as its client's | ||
| 78 | +connection, exactly like upstream). Each accepted thought additionally | ||
| 79 | +snapshots the chain to: | ||
| 80 | + | ||
| 81 | +``` | ||
| 82 | +<state_dir>/chains.json | ||
| 83 | +``` | ||
| 84 | + | ||
| 85 | +where `<state_dir>` is, in order: `$SEQTHINK_STATE_DIR`, | ||
| 86 | +`/workspace/.scorpiox/connectors/plugin_seqthink` (when `/workspace` exists and | ||
| 87 | +is writable — persists across container restarts), | ||
| 88 | +`%LOCALAPPDATA%\scorpiox\connectors\plugin_seqthink` on Windows, else | ||
| 89 | +`$HOME/.scorpiox/connectors/plugin_seqthink`. | ||
| 90 | + | ||
| 91 | +The file is merged by chain id (other chains are never clobbered), bounded to | ||
| 92 | +50 chains × 1000 thoughts each, and always written `.tmp` → `rename()`, so an | ||
| 93 | +interrupted write can never truncate it. A malformed file degrades to a clean | ||
| 94 | +start instead of crashing. `DISABLE_THOUGHT_LOGGING=1|true` (upstream parity) | ||
| 95 | +silences the stderr line and the persistence. `MAX_THOUGHT_HISTORY` caps the | ||
| 96 | +in-memory history (default 1000; a non-positive-integer value is reported on | ||
| 97 | +stderr and replaced by the default). | ||
| 98 | + | ||
| 99 | +## Node API (behind `require_node_auth()`) | ||
| 100 | + | ||
| 101 | +`X-Bot-Password`, `Authorization: Bearer` or `?pwd=`; a no-op when the node has | ||
| 102 | +no `BOT_PASSWORD`. `--meta`, `--mcp` and the HTML page are never gated. | ||
| 103 | + | ||
| 104 | +| Action | Result | | ||
| 105 | +|---|---| | ||
| 106 | +| `?action=chains` | every chain: id, started/updated, thought count, branch list, last thought head | | ||
| 107 | +| `?action=chain&id=` | one chain's full thought list (id validated: `[A-Za-z0-9_-]{1,64}`) | | ||
| 108 | +| `?action=stats` | chains / thoughts / branches / revisions / last activity | | ||
| 109 | +| `?action=info` | plugin + tool schema + caps + state dir | | ||
| 110 | +| `?action=clear&confirm=1` | delete the store (also accepts a POST JSON body) | | ||
| 111 | + | ||
| 112 | +## Build | ||
| 113 | + | ||
| 114 | +```sh | ||
| 115 | +make # native -> ./plugin_seqthink | ||
| 116 | +make musl # static musl x86_64 (the universal Linux artifact) | ||
| 117 | +make arm64 # static aarch64 | ||
| 118 | +make win64 # static PE via MinGW-w64 | ||
| 119 | +make macos # Apple clang (run on macOS) | ||
| 120 | +make asan # -fsanitize=address | ||
| 121 | +make fortify # -D_FORTIFY_SOURCE=2 | ||
| 122 | +make test # native + asan + fortify, then tests/run.sh | ||
| 123 | +make ui # regenerate src/ui_html.h from src/ui.html | ||
| 124 | +``` | ||
| 125 | + | ||
| 126 | +Or through the release CLI (builds all six dist targets + manifest): | ||
| 127 | + | ||
| 128 | +```sh | ||
| 129 | +scorpiox-cli-botplugin build . | ||
| 130 | +``` | ||
| 131 | + | ||
| 132 | +## Tests | ||
| 133 | + | ||
| 134 | +```sh | ||
| 135 | +sh tests/run.sh # 190+ offline assertions: all 4 modes, MCP parity, | ||
| 136 | + # validation errors, caps, auth, HTML invariants, | ||
| 137 | + # ASan + fortify, clean-room audit | ||
| 138 | +python3 tests/e2e.py # Playwright 1440 / 1024 / 390 dark + light (skips | ||
| 139 | + # cleanly without Playwright) | ||
| 140 | +``` | ||
| 141 | + | ||
| 142 | +## Install on a node | ||
| 143 | + | ||
| 144 | +Install it from SCORPIOX BOT: **Settings → Plugins → Marketplace → seqthink** | ||
| 145 | +(1-click prebuilt with SHA-256 verification, or compile-from-source), or let | ||
| 146 | +your agent clone, audit and compile this repository. Then register it as an MCP | ||
| 147 | +server through the SCORPIOX BOT connector router: | ||
| 148 | + | ||
| 149 | +```json | ||
| 150 | +{ "mcpServers": { "seqthink": { "command": "/path/to/plugin_seqthink", | ||
| 151 | + "args": ["--mcp"] } } } | ||
| 152 | +``` | ||
| 153 | + | ||
| 154 | +Open the viewer at `Settings → Plugins` → `Open`, or directly at | ||
| 155 | +`/plugin_seqthink` on the node. | ||
| 156 | + | ||
| 157 | +## Security posture | ||
| 158 | + | ||
| 159 | +* Runs as a normal plugin binary with the node user's permissions — auditable: | ||
| 160 | + this whole repository is the source, and `source.tar.gz` next to every | ||
| 161 | + published binary is the exact `git archive` of the pinned commit. | ||
| 162 | +* Opens **no** sockets and spawns **no** child processes; the only files it | ||
| 163 | + writes are inside its own connector directory. | ||
| 164 | +* Chain ids are validated before use; every JSON response is built in one | ||
| 165 | + buffer and emitted once; thought text and branch ids are length-capped. | ||
| 166 | +* MIT licensed. Vendored yyjson is MIT (see `vendor/LICENSE.yyjson.txt`). |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..9df916b | index 0000000..9df916b |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..1d2bf81 | index 0000000..1d2bf81 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..5881784 | index 0000000..5881784 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..2ab6bb1 | index 0000000..2ab6bb1 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..6f9af43 | index 0000000..6f9af43 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..d914da2 | index 0000000..d914da2 |

| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..396bc35 | index 0000000..396bc35 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/plugin.json | +++ b/plugin.json | ||
| @@ -0,0 +1,19 @@ | @@ -0,0 +1,19 @@ | ||
| 1 | +{ | ||
| 2 | + "slug": "seqthink", | ||
| 3 | + "id": "plugin_seqthink", | ||
| 4 | + "title": "Sequential Thinking", | ||
| 5 | + "summary": "Zero-dependency sequential-thinking MCP connector for your node. One C99 binary serves the sequentialthinking tool over MCP stdio (initialize / tools/list / tools/call) with the exact parameter validation, revision and branching semantics of the reference server, snapshots every accepted thought chain to its own connector directory, and ships a bot-themed viewer for recent reasoning chains, revisions and branches.", | ||
| 6 | + "category": "devtools", | ||
| 7 | + "license": "MIT", | ||
| 8 | + "kind": "mcp", | ||
| 9 | + "mcp": true, | ||
| 10 | + "daemon": false, | ||
| 11 | + "menus": false, | ||
| 12 | + "verified": "live", | ||
| 13 | + "capabilities": [ | ||
| 14 | + "mcp_stdio_server", | ||
| 15 | + "local_state_write", | ||
| 16 | + "no_network" | ||
| 17 | + ], | ||
| 18 | + "trust_notice": "Executes native C code on your node. Serves the sequentialthinking MCP tool over stdio and writes thought-chain snapshots only inside its own connector directory (~/.scorpiox/connectors/plugin_seqthink, /workspace/.scorpiox/connectors/plugin_seqthink, or $SEQTHINK_STATE_DIR). It opens no network connection of any kind and reads nothing outside that directory." | ||
| 19 | +} |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..83b05c0 | index 0000000..83b05c0 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/release-dist.sh | +++ b/release-dist.sh | ||
| @@ -0,0 +1,369 @@ | @@ -0,0 +1,369 @@ | ||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# release-dist.sh — build, scan and publish plugin_seqthink to the plugin registry. | ||
| 3 | +# | ||
| 4 | +# Two paths: | ||
| 5 | +# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it | ||
| 6 | +# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI. | ||
| 7 | +# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz -> | ||
| 8 | +# manifest.json + SHA256SUMS -> upload -> latest.json / index.json -> plugingit mirror. | ||
| 9 | +# | ||
| 10 | +# Nothing here contains a host address or a credential. Everything environment-specific | ||
| 11 | +# comes from the environment, so this file stays safe to publish: | ||
| 12 | +# | ||
| 13 | +# DIST_HOST ssh target for the dist server (required for upload) | ||
| 14 | +# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key) | ||
| 15 | +# DIST_PATH remote web root of the dist server (default /data/dist) | ||
| 16 | +# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64) | ||
| 17 | +# MAC_USER / MAC_PASS (optional) | ||
| 18 | +# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token) | ||
| 19 | +# PLUGINGIT_REMOTE public mirror URL to push into | ||
| 20 | +# | ||
| 21 | +# Usage: | ||
| 22 | +# ./release-dist.sh # full release | ||
| 23 | +# ./release-dist.sh --dry-run # build + stage in /tmp, no upload | ||
| 24 | +# ./release-dist.sh --no-macos # skip the macOS legs | ||
| 25 | +# ./release-dist.sh --no-mirror # skip the plugingit mirror | ||
| 26 | + | ||
| 27 | +set -euo pipefail | ||
| 28 | + | ||
| 29 | +SLUG="seqthink" | ||
| 30 | +ID="plugin_seqthink" | ||
| 31 | +VERSION="1.0.0" | ||
| 32 | +DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins" | ||
| 33 | + | ||
| 34 | +ROOT="$(cd "$(dirname "$0")" && pwd)" | ||
| 35 | +cd "$ROOT" | ||
| 36 | + | ||
| 37 | +DRY_RUN=0 | ||
| 38 | +DO_MACOS=1 | ||
| 39 | +DO_MIRROR=1 | ||
| 40 | +for arg in "$@"; do | ||
| 41 | + case "$arg" in | ||
| 42 | + --dry-run) DRY_RUN=1 ;; | ||
| 43 | + --no-macos) DO_MACOS=0 ;; | ||
| 44 | + --no-mirror) DO_MIRROR=0 ;; | ||
| 45 | + -h|--help) sed -n '2,30p' "$0"; exit 0 ;; | ||
| 46 | + *) echo "unknown argument: $arg" >&2; exit 2 ;; | ||
| 47 | + esac | ||
| 48 | +done | ||
| 49 | + | ||
| 50 | +DIST_HOST="${DIST_HOST:-}" | ||
| 51 | +DIST_PASS="${DIST_PASS:-}" | ||
| 52 | +DIST_PATH="${DIST_PATH:-/data/dist}" | ||
| 53 | +PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}" | ||
| 54 | +PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}" | ||
| 55 | + | ||
| 56 | +STAGE="/tmp/${SLUG}-dist-${VERSION}-$$" | ||
| 57 | +mkdir -p "$STAGE" | ||
| 58 | +trap 'rm -rf "$STAGE"' EXIT | ||
| 59 | + | ||
| 60 | +say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; } | ||
| 61 | +die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; } | ||
| 62 | + | ||
| 63 | +# ---------------------------------------------------------------- 0. preflight | ||
| 64 | +say "0/7 preflight" | ||
| 65 | + | ||
| 66 | +if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | ||
| 67 | + say "using scorpiox-cli-botplugin publish" | ||
| 68 | + exec scorpiox-cli-botplugin publish "$ROOT" | ||
| 69 | +fi | ||
| 70 | +echo " scorpiox-cli-botplugin not installed — running standalone pipeline" | ||
| 71 | + | ||
| 72 | +[ -n "$(git status --porcelain 2>/dev/null)" ] && \ | ||
| 73 | + echo " note: working tree is dirty; source.tar.gz comes from the last commit" | ||
| 74 | +COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown") | ||
| 75 | +echo " version $VERSION" | ||
| 76 | +echo " commit $COMMIT" | ||
| 77 | + | ||
| 78 | +# ---------------------------------------------------------------- 1. secret scan | ||
| 79 | +say "1/7 secret & LAN scan (full history)" | ||
| 80 | + | ||
| 81 | +SCAN_TMP="$STAGE/history.txt" | ||
| 82 | +# Scan every added/removed line of every commit. Two exclusions, both about the | ||
| 83 | +# audit rather than the code: the committer identity line, and any line that is | ||
| 84 | +# itself a scan definition — otherwise this file's own detector patterns read as | ||
| 85 | +# findings in every historical revision of it. | ||
| 86 | +git log -p --all 2>/dev/null \ | ||
| 87 | + | grep -v '^Author: ' \ | ||
| 88 | + | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \ | ||
| 89 | + > "$SCAN_TMP" || : > "$SCAN_TMP" | ||
| 90 | +HITS=0 | ||
| 91 | +scan() { # scan <label> <regex> | ||
| 92 | + local out | ||
| 93 | + out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true) | ||
| 94 | + if [ -n "$out" ]; then | ||
| 95 | + printf ' \033[31mHIT\033[0m %s\n' "$1" | ||
| 96 | + printf '%s\n' "$out" | sed 's/^/ /' | ||
| 97 | + HITS=$((HITS + 1)) | ||
| 98 | + else | ||
| 99 | + printf ' ok %s\n' "$1" | ||
| 100 | + fi | ||
| 101 | +} | ||
| 102 | +scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+' | ||
| 103 | +scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 104 | +scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' | ||
| 105 | +scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}' | ||
| 106 | +scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}' | ||
| 107 | +scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}' | ||
| 108 | +scan "hard-coded ssh password" 'sshpass -p [^"$]' | ||
| 109 | +P_ROOT="/codebases" | ||
| 110 | +P_PICOBOT="${P_ROOT}/pico""bot" | ||
| 111 | +P_WT=".work""trees" | ||
| 112 | +scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}" | ||
| 113 | +scan "run-token env assignment" 'RUNNER_'"PASS=" | ||
| 114 | +if [ "$HITS" -ne 0 ]; then | ||
| 115 | + die "secret scan found $HITS problem(s) — refusing to publish" | ||
| 116 | +fi | ||
| 117 | +echo " clean: 0 hits" | ||
| 118 | + | ||
| 119 | +# ---------------------------------------------------------------- 2. build | ||
| 120 | +say "2/7 build targets" | ||
| 121 | + | ||
| 122 | +build_ok() { [ -f "$1" ]; } | ||
| 123 | + | ||
| 124 | +# linux-x86_64 (glibc, native) | ||
| 125 | +if command -v cc >/dev/null 2>&1; then | ||
| 126 | + cc -O2 -std=c99 -Wall -Wextra -I src -I vendor -o "$STAGE/$ID" src/$ID.c vendor/yyjson.c || die "native build failed" | ||
| 127 | + echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes" | ||
| 128 | +else | ||
| 129 | + die "no native cc found" | ||
| 130 | +fi | ||
| 131 | + | ||
| 132 | +# linux-x86_64-musl (fully static — the universal Linux artifact) | ||
| 133 | +if command -v musl-gcc >/dev/null 2>&1; then | ||
| 134 | + musl-gcc -O2 -std=c99 -Wall -Wextra -static -I src -I vendor -o "$STAGE/$ID.musl" src/$ID.c vendor/yyjson.c \ | ||
| 135 | + || die "musl build failed" | ||
| 136 | + echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes" | ||
| 137 | +else | ||
| 138 | + echo " skip linux-x86_64-musl (no musl-gcc)" | ||
| 139 | +fi | ||
| 140 | + | ||
| 141 | +# linux-arm64-musl (static aarch64 — Pi 5 / ARM64 servers) | ||
| 142 | +if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then | ||
| 143 | + aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -I src -I vendor -o "$STAGE/$ID.arm64" src/$ID.c vendor/yyjson.c \ | ||
| 144 | + || die "arm64 musl build failed" | ||
| 145 | + echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes" | ||
| 146 | +else | ||
| 147 | + echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)" | ||
| 148 | +fi | ||
| 149 | + | ||
| 150 | +# windows-x86_64 (static PE) | ||
| 151 | +if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then | ||
| 152 | + x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -I src -I vendor -o "$STAGE/$ID.exe" src/$ID.c vendor/yyjson.c \ | ||
| 153 | + || die "MinGW build failed" | ||
| 154 | + [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE" | ||
| 155 | + echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes" | ||
| 156 | +else | ||
| 157 | + echo " skip windows-x86_64 (no MinGW cross compiler)" | ||
| 158 | +fi | ||
| 159 | + | ||
| 160 | +# macOS legs — Mach-O must be produced by Apple clang on a real Mac. | ||
| 161 | +# Both slices are cross-built from one host: -arch arm64 and -arch x86_64. | ||
| 162 | +if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then | ||
| 163 | + MAC_USER="${MAC_USER:-$(whoami)}" | ||
| 164 | + MAC_DIR="/tmp/${ID}-mac-$$" | ||
| 165 | + echo " building macOS legs on $MAC_HOST" | ||
| 166 | + SSH_MAC=(ssh -o StrictHostKeyChecking=no) | ||
| 167 | + SCP_MAC=(scp -o StrictHostKeyChecking=no) | ||
| 168 | + if [ -n "${MAC_PASS:-}" ]; then | ||
| 169 | + SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}") | ||
| 170 | + SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}") | ||
| 171 | + fi | ||
| 172 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then | ||
| 173 | + # Ship the whole src/ + vendor/ tree: the plugin includes bot_theme_plugin.h, | ||
| 174 | + # ui_html.h and yyjson.h next to the source, and the CLI/macOS leg history | ||
| 175 | + # (lesson ag) shows scp of a lone .c silently loses both Mach-O slices. | ||
| 176 | + TARMAC="$STAGE/mac-src.tar.gz" | ||
| 177 | + tar -czf "$TARMAC" src vendor | ||
| 178 | + if "${SCP_MAC[@]}" "$TARMAC" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tar.gz"; then | ||
| 179 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tar.gz" || true | ||
| 180 | + # Build straight from the uploaded tree. The star is backslash-escaped: | ||
| 181 | + # the remote login shell is zsh and an unmatched glob aborts it (bc). | ||
| 182 | + for slice in arm64 x86_64; do | ||
| 183 | + if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \ | ||
| 184 | + "cd '$MAC_DIR' && SRCS=\$(find src -name \*.c; find vendor -name \*.c) && clang -O2 -std=c99 -Wall -Wextra -D_DARWIN_C_SOURCE -I src -I vendor -arch $slice -o $ID.$slice \$SRCS" \ | ||
| 185 | + 2>/dev/null; then | ||
| 186 | + "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \ | ||
| 187 | + && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)" | ||
| 188 | + else | ||
| 189 | + echo " warn: macos-$slice build failed on $MAC_HOST" | ||
| 190 | + fi | ||
| 191 | + done | ||
| 192 | + "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" 2>/dev/null || true | ||
| 193 | + else | ||
| 194 | + echo " warn: mac scp failed" | ||
| 195 | + fi | ||
| 196 | + else | ||
| 197 | + echo " warn: mac host unreachable" | ||
| 198 | + fi | ||
| 199 | +else | ||
| 200 | + echo " skip macOS legs (set MAC_HOST/MAC_USER/MAC_PASS to include them)" | ||
| 201 | +fi | ||
| 202 | + | ||
| 203 | +# ---------------------------------------------------------------- 3. package | ||
| 204 | +say "3/7 package" | ||
| 205 | + | ||
| 206 | +git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \ | ||
| 207 | + -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \ | ||
| 208 | + || tar -czf "$STAGE/source.tar.gz" --exclude=.git . | ||
| 209 | +echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes" | ||
| 210 | + | ||
| 211 | +target_meta() { # target_meta <key> <file> <format> <relpath> <name> | ||
| 212 | + local key="$1" file="$2" fmt="$3" rel="$4" name="$5" | ||
| 213 | + [ -f "$file" ] || return 0 | ||
| 214 | + local sha size | ||
| 215 | + sha=$(sha256sum "$file" | awk '{print $1}') | ||
| 216 | + size=$(wc -c < "$file" | tr -d ' ') | ||
| 217 | + printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \ | ||
| 218 | + "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt" | ||
| 219 | +} | ||
| 220 | + | ||
| 221 | +{ | ||
| 222 | + printf '{\n' | ||
| 223 | + printf ' "slug": "%s",\n' "$SLUG" | ||
| 224 | + printf ' "id": "%s",\n' "$ID" | ||
| 225 | + printf ' "name": "seqthink",\n' | ||
| 226 | + printf ' "desc": "Thought chains",\n' | ||
| 227 | + printf ' "title": "Sequential Thinking",\n' | ||
| 228 | + printf ' "summary": "Zero-dependency sequential-thinking MCP connector for your node. Serves the sequentialthinking tool over MCP stdio with revision and branching semantics, snapshots accepted thought chains to its own connector directory, and ships a bot-themed chain viewer.",\n' | ||
| 229 | + printf ' "category": "devtools",\n' | ||
| 230 | + printf ' "version": "%s",\n' "$VERSION" | ||
| 231 | + printf ' "license": "MIT",\n' | ||
| 232 | + printf ' "trust_notice": "Executes native C code on your node. Serves the sequentialthinking MCP tool over stdio and writes thought-chain snapshots only inside its own connector directory. It opens no network connection of any kind.",\n' | ||
| 233 | + printf ' "capabilities": ["mcp_stdio_server", "local_state_write", "no_network"],\n' | ||
| 234 | + printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG" | ||
| 235 | + printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG" | ||
| 236 | + printf ' "git_commit": "%s",\n' "$COMMIT" | ||
| 237 | + printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 238 | + printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')" | ||
| 239 | + printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -I src -I vendor -o %s src/%s.c vendor/yyjson.c",\n' "$ID" "$ID" | ||
| 240 | + printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -I src -I vendor -o %s.exe src/%s.c vendor/yyjson.c",\n' "$ID" "$ID" | ||
| 241 | + printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | ||
| 242 | + printf ' "targets": {\n' | ||
| 243 | + first=1 | ||
| 244 | + emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; } | ||
| 245 | + emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID" "$ID" | ||
| 246 | + emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID" "$ID" | ||
| 247 | + emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID" "$ID" | ||
| 248 | + emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID" "$ID" | ||
| 249 | + emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID" "$ID" | ||
| 250 | + emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe" "$ID" | ||
| 251 | + printf '\n }\n}\n' | ||
| 252 | +} > "$STAGE/manifest.json" | ||
| 253 | + | ||
| 254 | +python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \ | ||
| 255 | + || die "generated manifest.json is not valid JSON" | ||
| 256 | +echo " manifest.json ok" | ||
| 257 | + | ||
| 258 | +# SHA256SUMS — relative paths, exactly as published | ||
| 259 | +( cd "$STAGE" | ||
| 260 | + for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done | ||
| 261 | + [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|" | ||
| 262 | + [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|" | ||
| 263 | + [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|" | ||
| 264 | + [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|" | ||
| 265 | + [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|" | ||
| 266 | + [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|" | ||
| 267 | + true ) > "$STAGE/SHA256SUMS" | ||
| 268 | +echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries" | ||
| 269 | + | ||
| 270 | +# ---------------------------------------------------------------- 4. stage | ||
| 271 | +say "4/7 stage tree" | ||
| 272 | +PKG="$STAGE/pkg" | ||
| 273 | +mkdir -p "$PKG/linux-x86_64" "$PKG/linux-x86_64-musl" "$PKG/linux-arm64-musl" \ | ||
| 274 | + "$PKG/macos-arm64" "$PKG/macos-x86_64" "$PKG/windows-x86_64" | ||
| 275 | +cp -f "$STAGE/$ID" "$PKG/linux-x86_64/$ID" | ||
| 276 | +[ -f "$STAGE/$ID.musl" ] && cp -f "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID" | ||
| 277 | +[ -f "$STAGE/$ID.arm64" ] && cp -f "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID" | ||
| 278 | +[ -f "$STAGE/$ID.macos-arm64" ]&& cp -f "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID" | ||
| 279 | +[ -f "$STAGE/$ID.macos-x86_64" ]&&cp -f "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID" | ||
| 280 | +[ -f "$STAGE/$ID.exe" ] && cp -f "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe" | ||
| 281 | +cp -f "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/" | ||
| 282 | +chmod +x "$PKG"/*/$ID 2>/dev/null || true | ||
| 283 | +find "$PKG" -type f | sed 's/^/ /' | ||
| 284 | + | ||
| 285 | +if [ "$DRY_RUN" -eq 1 ]; then | ||
| 286 | + say "dry run — staged at $STAGE/pkg (kept for inspection)" | ||
| 287 | + trap - EXIT | ||
| 288 | + exit 0 | ||
| 289 | +fi | ||
| 290 | + | ||
| 291 | +# ---------------------------------------------------------------- 5. upload | ||
| 292 | +say "5/7 upload" | ||
| 293 | + | ||
| 294 | +[ -n "$DIST_HOST" ] || die "DIST_HOST is not set — cannot upload" | ||
| 295 | +SSH=(ssh -o StrictHostKeyChecking=no) | ||
| 296 | +SCP=(scp -o StrictHostKeyChecking=no) | ||
| 297 | +if [ -n "$DIST_PASS" ]; then | ||
| 298 | + SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}") | ||
| 299 | + SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}") | ||
| 300 | +fi | ||
| 301 | +REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION" | ||
| 302 | + | ||
| 303 | +"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \ | ||
| 304 | + || die "cannot create $REMOTE_DIR on $DIST_HOST" | ||
| 305 | +# Stage to one tarball, transfer it, extract remotely. Streaming tar through | ||
| 306 | +# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and | ||
| 307 | +# OpenSSH 9 refuses to scp a bare "." source. | ||
| 308 | +tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed" | ||
| 309 | +"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed" | ||
| 310 | +"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \ | ||
| 311 | + || die "remote extract failed" | ||
| 312 | +echo " uploaded to $DIST_HOST:$REMOTE_DIR" | ||
| 313 | + | ||
| 314 | +# latest.json = copy of this version's manifest | ||
| 315 | +"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \ | ||
| 316 | + || die "latest.json update failed" | ||
| 317 | +echo " updated bot-plugins/$SLUG/latest.json" | ||
| 318 | + | ||
| 319 | +# index.json — merge, preserving every sibling <slug>/latest.json | ||
| 320 | +say "index.json merge" | ||
| 321 | +"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY' | ||
| 322 | +import json, os, sys, glob | ||
| 323 | +slug = sys.argv[1] | ||
| 324 | +entries = {} | ||
| 325 | +for p in sorted(glob.glob('*/latest.json')): | ||
| 326 | + s = os.path.dirname(p) | ||
| 327 | + try: | ||
| 328 | + entries[s] = json.load(open(p)) | ||
| 329 | + except Exception: | ||
| 330 | + pass | ||
| 331 | +index = { | ||
| 332 | + 'ok': True, | ||
| 333 | + 'service': 'bot-plugins-dist', | ||
| 334 | + 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins', | ||
| 335 | + 'count': len(entries), | ||
| 336 | + 'slugs': sorted(entries), | ||
| 337 | + 'plugins': [entries[k] for k in sorted(entries)], | ||
| 338 | +} | ||
| 339 | +open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10)) | ||
| 340 | +os.replace('index.json.tmp', 'index.json') | ||
| 341 | +print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries)))) | ||
| 342 | +PY" || die "index.json merge failed" | ||
| 343 | + | ||
| 344 | +# ---------------------------------------------------------------- 6. mirror | ||
| 345 | +say "6/7 plugingit mirror" | ||
| 346 | +if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then | ||
| 347 | + TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE") | ||
| 348 | + AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://x-access-token:${TOKEN}@|") | ||
| 349 | + git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed" | ||
| 350 | + git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true | ||
| 351 | + echo " mirrored to $PLUGINGIT_REMOTE" | ||
| 352 | +else | ||
| 353 | + echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)" | ||
| 354 | +fi | ||
| 355 | + | ||
| 356 | +# ---------------------------------------------------------------- 7. verify | ||
| 357 | +say "7/7 verify" | ||
| 358 | +CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \ | ||
| 359 | + "$DIST_BASE_URL/$SLUG/latest.json" || echo 000) | ||
| 360 | +if [ "$CODE" = "200" ]; then | ||
| 361 | + python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK — %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \ | ||
| 362 | + "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON" | ||
| 363 | +else | ||
| 364 | + echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE" | ||
| 365 | +fi | ||
| 366 | + | ||
| 367 | +printf '\n\033[1mrelease complete\033[0m\n' | ||
| 368 | +printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" | ||
| 369 | +printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION" |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..0dd243b | index 0000000..0dd243b | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/bot_theme_plugin.h | +++ b/src/bot_theme_plugin.h | ||
| @@ -0,0 +1,129 @@ | @@ -0,0 +1,129 @@ | ||
| 1 | +/* | ||
| 2 | + * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins. | ||
| 3 | + * | ||
| 4 | + * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of | ||
| 5 | + * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session | ||
| 6 | + * Card modal, Chat floating window) or in its own tab, and in every case it | ||
| 7 | + * must look like part of the bot: same tokens, same dark/light pair, same | ||
| 8 | + * localStorage key, same prepaint order. | ||
| 9 | + * | ||
| 10 | + * Three rules, and nothing else: | ||
| 11 | + * | ||
| 12 | + * 1. Colours come from these tokens only. No plugin-private palette. | ||
| 13 | + * 2. The theme is decided BEFORE first paint, in this order: | ||
| 14 | + * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme | ||
| 15 | + * so a plugin opened from the bot paints in the bot's theme from frame 0. | ||
| 16 | + * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into | ||
| 17 | + * this window; the plugin follows without a reload. The plugin asks once | ||
| 18 | + * with {type:'sx-theme-request'} at startup, which covers the case where | ||
| 19 | + * it was already open when the bot changed theme. | ||
| 20 | + * | ||
| 21 | + * The bottom of :root carries aliases for the names older plugin CSS already | ||
| 22 | + * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn, | ||
| 23 | + * --ok), so adopting the bot palette is a swap, not a redesign. Because they | ||
| 24 | + * are var() references, one definition covers both themes. | ||
| 25 | + * | ||
| 26 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 27 | + */ | ||
| 28 | +#ifndef SX_BOT_THEME_PLUGIN_H | ||
| 29 | +#define SX_BOT_THEME_PLUGIN_H | ||
| 30 | + | ||
| 31 | +/* Dark is the default; light is applied by html[data-theme=light] (chosen by | ||
| 32 | + * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */ | ||
| 33 | +#define SX_BOT_THEME_TOKENS \ | ||
| 34 | +":root{color-scheme:dark;" \ | ||
| 35 | + "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \ | ||
| 36 | + "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \ | ||
| 37 | + "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \ | ||
| 38 | + "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \ | ||
| 39 | + "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \ | ||
| 40 | + "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \ | ||
| 41 | + "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \ | ||
| 42 | + "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \ | ||
| 43 | + "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \ | ||
| 44 | + "--shadow:0 1px 2px rgba(0,0,0,.35);" \ | ||
| 45 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \ | ||
| 46 | + "--ease:cubic-bezier(.16,1,.3,1);" \ | ||
| 47 | + "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \ | ||
| 48 | + "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \ | ||
| 49 | + "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \ | ||
| 50 | +"}" \ | ||
| 51 | +"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \ | ||
| 52 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 53 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 54 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 55 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 56 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 57 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 58 | + "--accent-dim:#0066d6;" \ | ||
| 59 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 60 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 61 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 62 | + "color-scheme:light}}" \ | ||
| 63 | +"html[data-theme=light]{" \ | ||
| 64 | + "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \ | ||
| 65 | + "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \ | ||
| 66 | + "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \ | ||
| 67 | + "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \ | ||
| 68 | + "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \ | ||
| 69 | + "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \ | ||
| 70 | + "--accent-dim:#0066d6;" \ | ||
| 71 | + "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \ | ||
| 72 | + "--shadow:0 2px 10px rgba(0,0,0,.03);" \ | ||
| 73 | + "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \ | ||
| 74 | + "color-scheme:light}" \ | ||
| 75 | +"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \ | ||
| 76 | +"*{box-sizing:border-box}" \ | ||
| 77 | +"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \ | ||
| 78 | + "-webkit-font-smoothing:antialiased}" \ | ||
| 79 | +"button{font-family:inherit;letter-spacing:inherit}" \ | ||
| 80 | +"button:active{transform:scale(.98)}" \ | ||
| 81 | +"select option{background:var(--menu-bg);color:var(--text)}" \ | ||
| 82 | +"a{color:var(--blue);text-decoration:none;font-weight:600}" \ | ||
| 83 | +"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \ | ||
| 84 | +" * hides its own back link and its own toggle. */" \ | ||
| 85 | +"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \ | ||
| 86 | +"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}" | ||
| 87 | + | ||
| 88 | +/* Pre-paint: decide the theme before the first frame. Must be the first thing | ||
| 89 | + * in <head> so there is no flash of the wrong theme. Also flags embed mode as | ||
| 90 | + * html.embedded so the embed rules apply before first paint. */ | ||
| 91 | +#define SX_BOT_THEME_PREPAINT \ | ||
| 92 | +"<script>(function(){var t='';" \ | ||
| 93 | +"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \ | ||
| 94 | +"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \ | ||
| 95 | +"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \ | ||
| 96 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 97 | +"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \ | ||
| 98 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 99 | +"})();</script>\n" | ||
| 100 | + | ||
| 101 | +/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once | ||
| 102 | + * at startup in case it changed while this page was already open. Fires the | ||
| 103 | + * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can | ||
| 104 | + * re-skin themselves from one listener. */ | ||
| 105 | +#define SX_BOT_THEME_HANDOFF \ | ||
| 106 | +"<script>(function(){" \ | ||
| 107 | +"function apply(t){if(t!=='light'&&t!=='dark')return;" \ | ||
| 108 | +"if(document.documentElement.getAttribute('data-theme')===t)return;" \ | ||
| 109 | +"document.documentElement.setAttribute('data-theme',t);" \ | ||
| 110 | +"try{localStorage.setItem('bot_theme',t);}catch(e){}" \ | ||
| 111 | +"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \ | ||
| 112 | +"window.sxApplyTheme=apply;" \ | ||
| 113 | +"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \ | ||
| 114 | +"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \ | ||
| 115 | +"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \ | ||
| 116 | +"})();</script>\n" | ||
| 117 | + | ||
| 118 | +/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when | ||
| 119 | + * the plugin is opened in its own tab; inside the bot the host owns the theme. | ||
| 120 | + * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */ | ||
| 121 | +#define SX_BOT_THEME_TOGGLE_BTN \ | ||
| 122 | +"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>" | ||
| 123 | + | ||
| 124 | +#define SX_BOT_THEME_TOGGLE_JS \ | ||
| 125 | +"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \ | ||
| 126 | +"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \ | ||
| 127 | +"})();</script>\n" | ||
| 128 | + | ||
| 129 | +#endif /* SX_BOT_THEME_PLUGIN_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..abc92d1 | index 0000000..abc92d1 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/plugin_seqthink.c | +++ b/src/plugin_seqthink.c | ||
| @@ -0,0 +1,1798 @@ | @@ -0,0 +1,1798 @@ | ||
| 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: a | ||
| 17 | + * thought-chain timeline (revisions, branches, progress) built from the | ||
| 18 | + * snapshots the --mcp leg persists. | ||
| 19 | + * | ||
| 20 | + * The tool is a clean-room C port of the behaviour of modelcontextprotocol | ||
| 21 | + * `servers/src/sequentialthinking` (the sequential-thinking MCP server): | ||
| 22 | + * identical parameter validation and error strings, the same "raise | ||
| 23 | + * totalThoughts when thoughtNumber exceeds it" rule, a per-connection thought | ||
| 24 | + * history with a MAX_THOUGHT_HISTORY cap (default 1000, oldest evicted, its | ||
| 25 | + * branch shrunk with it, an emptied branch dropped), branch keys created on | ||
| 26 | + * the first thought that carries BOTH branchFromThought and branchId, and the | ||
| 27 | + * exact five-field result {thoughtNumber,totalThoughts,nextThoughtNeeded, | ||
| 28 | + * branches,thoughtHistoryLength} returned as content[0].text AND as | ||
| 29 | + * structuredContent. Validation failures come back as | ||
| 30 | + * {"error":...,"status":"failed"} with isError:true, exactly as upstream. | ||
| 31 | + * | ||
| 32 | + * Beyond upstream: every accepted thought also snapshots its chain to | ||
| 33 | + * <state_dir>/chains.json (POSIX: /workspace/.scorpiox/connectors/ | ||
| 34 | + * plugin_seqthink when /workspace exists, else $HOME/.scorpiox/connectors/ | ||
| 35 | + * plugin_seqthink; Windows: %LOCALAPPDATA%\scorpiox\connectors\plugin_seqthink; | ||
| 36 | + * SEQTHINK_STATE_DIR overrides for tests) so the HTML UI can inspect recent | ||
| 37 | + * reasoning without holding the MCP process open. Writes are read-modify- | ||
| 38 | + * merge on chain id and go .tmp -> rename(), so a crash never leaves a | ||
| 39 | + * half-written chains.json. The file is bounded (<= 50 chains, each <= 1000 | ||
| 40 | + * thoughts). DISABLE_THOUGHT_LOGGING=1|true (upstream parity) silences both | ||
| 41 | + * the stderr line and the persistence. | ||
| 42 | + * | ||
| 43 | + * Zero dependencies beyond the vendored yyjson: no TLS, no sockets, no | ||
| 44 | + * popen. The only files it ever touches live under its own state directory. | ||
| 45 | + * | ||
| 46 | + * MIT License. Copyright (c) 2026 SCORPIOX INC. | ||
| 47 | + */ | ||
| 48 | + | ||
| 49 | +/* Must come before every include: MinGW defaults _WIN32_WINNT to 0x502; | ||
| 50 | + * Apple needs _DARWIN_C_SOURCE under -std=c99; MinGW needs its printf for %zu. */ | ||
| 51 | +#ifndef _WIN32 | ||
| 52 | +# ifndef _POSIX_C_SOURCE | ||
| 53 | +# define _POSIX_C_SOURCE 200809L | ||
| 54 | +# endif | ||
| 55 | +# ifndef _DEFAULT_SOURCE | ||
| 56 | +# define _DEFAULT_SOURCE 1 | ||
| 57 | +# endif | ||
| 58 | +#endif | ||
| 59 | +#if defined(_WIN32) && !defined(_WIN32_WINNT) | ||
| 60 | +# define _WIN32_WINNT 0x0601 | ||
| 61 | +#endif | ||
| 62 | +#if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) | ||
| 63 | +# define _DARWIN_C_SOURCE 1 | ||
| 64 | +#endif | ||
| 65 | +#if defined(__MINGW32__) && !defined(__USE_MINGW_ANSI_STDIO) | ||
| 66 | +# define __USE_MINGW_ANSI_STDIO 1 | ||
| 67 | +#endif | ||
| 68 | + | ||
| 69 | +#include <stdio.h> | ||
| 70 | +#include <stdlib.h> | ||
| 71 | +#include <string.h> | ||
| 72 | +#include <ctype.h> | ||
| 73 | +#include <time.h> | ||
| 74 | +#include <errno.h> | ||
| 75 | +#include <limits.h> | ||
| 76 | +#include <stdarg.h> | ||
| 77 | + | ||
| 78 | +#if defined(_WIN32) | ||
| 79 | +# include <windows.h> | ||
| 80 | +# include <io.h> | ||
| 81 | +# include <direct.h> | ||
| 82 | +# include <string.h> | ||
| 83 | +# ifndef strncasecmp | ||
| 84 | +# define strncasecmp _strnicmp | ||
| 85 | +# endif | ||
| 86 | +# ifndef _SSIZE_T_DEFINED | ||
| 87 | +# define _SSIZE_T_DEFINED | ||
| 88 | + typedef long long ssize_t; | ||
| 89 | +# endif | ||
| 90 | +#else | ||
| 91 | +# include <unistd.h> | ||
| 92 | +# include <strings.h> | ||
| 93 | +# include <sys/stat.h> | ||
| 94 | +# include <sys/types.h> | ||
| 95 | +#endif | ||
| 96 | +#include <sys/stat.h> | ||
| 97 | +#include <sys/types.h> | ||
| 98 | + | ||
| 99 | +#include "yyjson.h" | ||
| 100 | +#include "bot_theme_plugin.h" | ||
| 101 | +#include "ui_html.h" | ||
| 102 | + | ||
| 103 | +#define PLUGIN_SLUG "seqthink" | ||
| 104 | +#define PLUGIN_ID "plugin_seqthink" | ||
| 105 | +#define PLUGIN_VER "1.0.0" | ||
| 106 | +#define PLUGIN_NAME "seqthink" | ||
| 107 | +#define PLUGIN_DESC "Thought chains" | ||
| 108 | + | ||
| 109 | +#define MAX_CHAINS 50 /* chains kept in chains.json */ | ||
| 110 | +#define MAX_THOUGHTS_EACH 1000 /* thoughts kept per chain in the file */ | ||
| 111 | +#define DEFAULT_MAX_HIST 1000 /* upstream DEFAULT_MAX_THOUGHT_HISTORY */ | ||
| 112 | +#define THOUGHT_MAX 65536 /* longest accepted thought text */ | ||
| 113 | +#define BRANCHID_MAX 128 | ||
| 114 | +#define REQ_MAX (2u * 1024u * 1024u) | ||
| 115 | + | ||
| 116 | +#if defined(_WIN32) | ||
| 117 | +# define sx_mkdir(p) _mkdir(p) | ||
| 118 | +# define SX_PATHSEP '\\' | ||
| 119 | +#else | ||
| 120 | +# define sx_mkdir(p) mkdir((p), 0755) | ||
| 121 | +# define SX_PATHSEP '/' | ||
| 122 | +#endif | ||
| 123 | + | ||
| 124 | +/* ------------------------------------------------------------------ */ | ||
| 125 | +/* Small helpers */ | ||
| 126 | +/* ------------------------------------------------------------------ */ | ||
| 127 | + | ||
| 128 | +static void *sx_malloc(size_t n) | ||
| 129 | +{ | ||
| 130 | + void *p = malloc(n ? n : 1); | ||
| 131 | + if (!p) { | ||
| 132 | + fputs("out of memory\n", stderr); | ||
| 133 | + exit(1); | ||
| 134 | + } | ||
| 135 | + return p; | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +static char *sx_strdup(const char *s) | ||
| 139 | +{ | ||
| 140 | + size_t n; | ||
| 141 | + char *p; | ||
| 142 | + if (!s) s = ""; | ||
| 143 | + n = strlen(s) + 1; | ||
| 144 | + p = (char *)sx_malloc(n); | ||
| 145 | + memcpy(p, s, n); | ||
| 146 | + return p; | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +typedef struct { | ||
| 150 | + char *p; | ||
| 151 | + size_t n; | ||
| 152 | + size_t cap; | ||
| 153 | +} buf_t; | ||
| 154 | + | ||
| 155 | +static void buf_init(buf_t *b) { b->p = NULL; b->n = 0; b->cap = 0; } | ||
| 156 | + | ||
| 157 | +static void buf_reserve(buf_t *b, size_t extra) | ||
| 158 | +{ | ||
| 159 | + size_t want = b->n + extra + 1; | ||
| 160 | + if (want <= b->cap) return; | ||
| 161 | + { | ||
| 162 | + size_t cap = b->cap ? b->cap : 256; | ||
| 163 | + while (cap < want) cap *= 2; | ||
| 164 | + b->p = (char *)realloc(b->p, cap); | ||
| 165 | + if (!b->p) { fputs("out of memory\n", stderr); exit(1); } | ||
| 166 | + b->cap = cap; | ||
| 167 | + } | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +static void buf_add(buf_t *b, const char *s, size_t n) | ||
| 171 | +{ | ||
| 172 | + buf_reserve(b, n); | ||
| 173 | + memcpy(b->p + b->n, s, n); | ||
| 174 | + b->n += n; | ||
| 175 | + b->p[b->n] = '\0'; | ||
| 176 | +} | ||
| 177 | + | ||
| 178 | +/* Append a NUL-terminated literal; the length is computed, never hand-typed. */ | ||
| 179 | +static void buf_str(buf_t *b, const char *s) | ||
| 180 | +{ | ||
| 181 | + if (s) buf_add(b, s, strlen(s)); | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +static void buf_addf(buf_t *b, const char *fmt, ...) | ||
| 185 | +{ | ||
| 186 | + va_list ap; | ||
| 187 | + int need; | ||
| 188 | + char tmp[512]; | ||
| 189 | + va_start(ap, fmt); | ||
| 190 | + need = vsnprintf(tmp, sizeof tmp, fmt, ap); | ||
| 191 | + va_end(ap); | ||
| 192 | + if (need < 0) return; | ||
| 193 | + if ((size_t)need < sizeof tmp) { buf_add(b, tmp, (size_t)need); return; } | ||
| 194 | + { | ||
| 195 | + char *big = (char *)sx_malloc((size_t)need + 1); | ||
| 196 | + va_start(ap, fmt); | ||
| 197 | + vsnprintf(big, (size_t)need + 1, fmt, ap); | ||
| 198 | + va_end(ap); | ||
| 199 | + buf_add(b, big, (size_t)need); | ||
| 200 | + free(big); | ||
| 201 | + } | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +static void buf_free(buf_t *b) { free(b->p); buf_init(b); } | ||
| 205 | + | ||
| 206 | +/* getline() is POSIX; MinGW-w64 ships one but msvcrt's varies by release. A | ||
| 207 | + * 40-line local version keeps the --mcp loop identical on every target. */ | ||
| 208 | +#if defined(_WIN32) | ||
| 209 | +static ssize_t sx_getline(char **lineptr, size_t *n, FILE *stream) | ||
| 210 | +{ | ||
| 211 | + size_t len = 0, cap = *n ? *n : 128; | ||
| 212 | + char *buf = *lineptr; | ||
| 213 | + int c; | ||
| 214 | + if (!buf) { | ||
| 215 | + buf = (char *)malloc(cap); | ||
| 216 | + if (!buf) return -1; | ||
| 217 | + *lineptr = buf; | ||
| 218 | + *n = cap; | ||
| 219 | + } | ||
| 220 | + c = fgetc(stream); | ||
| 221 | + if (c == EOF) return -1; | ||
| 222 | + while (c != EOF) { | ||
| 223 | + if (len + 2 > cap) { | ||
| 224 | + char *nb; | ||
| 225 | + cap *= 2; | ||
| 226 | + nb = (char *)realloc(buf, cap); | ||
| 227 | + if (!nb) return -1; | ||
| 228 | + buf = nb; | ||
| 229 | + *lineptr = buf; | ||
| 230 | + *n = cap; | ||
| 231 | + } | ||
| 232 | + buf[len++] = (char)c; | ||
| 233 | + if (c == '\n') break; | ||
| 234 | + c = fgetc(stream); | ||
| 235 | + } | ||
| 236 | + buf[len] = '\0'; | ||
| 237 | + return (ssize_t)len; | ||
| 238 | +} | ||
| 239 | +# define getline(a, b, c) sx_getline((a), (b), (c)) | ||
| 240 | +#endif | ||
| 241 | + | ||
| 242 | +/* JSON-escape s into b (with surrounding quotes). */ | ||
| 243 | +static void json_escape_buf(buf_t *b, const char *s) | ||
| 244 | +{ | ||
| 245 | + const unsigned char *p = (const unsigned char *)(s ? s : ""); | ||
| 246 | + buf_str(b, "\""); | ||
| 247 | + for (; *p; p++) { | ||
| 248 | + switch (*p) { | ||
| 249 | + case '"': buf_str(b, "\\\""); break; | ||
| 250 | + case '\\': buf_str(b, "\\\\"); break; | ||
| 251 | + case '\n': buf_str(b, "\\n"); break; | ||
| 252 | + case '\r': buf_str(b, "\\r"); break; | ||
| 253 | + case '\t': buf_str(b, "\\t"); break; | ||
| 254 | + default: | ||
| 255 | + if (*p < 0x20) buf_addf(b, "\\u%04x", (unsigned)*p); | ||
| 256 | + else buf_add(b, (const char *)p, 1); | ||
| 257 | + } | ||
| 258 | + } | ||
| 259 | + buf_str(b, "\""); | ||
| 260 | +} | ||
| 261 | + | ||
| 262 | +static void json_escape(FILE *out, const char *s) | ||
| 263 | +{ | ||
| 264 | + buf_t b; | ||
| 265 | + buf_init(&b); | ||
| 266 | + json_escape_buf(&b, s); | ||
| 267 | + if (b.p) fwrite(b.p, 1, b.n, out); | ||
| 268 | + buf_free(&b); | ||
| 269 | +} | ||
| 270 | + | ||
| 271 | +/* Percent-decode in place for query values (the node hands QUERY_STRING raw). */ | ||
| 272 | +static int hexval(int c) | ||
| 273 | +{ | ||
| 274 | + if (c >= '0' && c <= '9') return c - '0'; | ||
| 275 | + if (c >= 'a' && c <= 'f') return c - 'a' + 10; | ||
| 276 | + if (c >= 'A' && c <= 'F') return c - 'A' + 10; | ||
| 277 | + return -1; | ||
| 278 | +} | ||
| 279 | + | ||
| 280 | +static void url_decode(char *s) | ||
| 281 | +{ | ||
| 282 | + char *d = s; | ||
| 283 | + while (*s) { | ||
| 284 | + if (*s == '%' && hexval((unsigned char)s[1]) >= 0 && | ||
| 285 | + hexval((unsigned char)s[2]) >= 0) { | ||
| 286 | + *d++ = (char)(hexval((unsigned char)s[1]) * 16 + | ||
| 287 | + hexval((unsigned char)s[2])); | ||
| 288 | + s += 3; | ||
| 289 | + } else if (*s == '+') { | ||
| 290 | + *d++ = ' '; | ||
| 291 | + s++; | ||
| 292 | + } else { | ||
| 293 | + *d++ = *s++; | ||
| 294 | + } | ||
| 295 | + } | ||
| 296 | + *d = '\0'; | ||
| 297 | +} | ||
| 298 | + | ||
| 299 | +static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) | ||
| 300 | +{ | ||
| 301 | + size_t klen; | ||
| 302 | + const char *p; | ||
| 303 | + if (!qs || !key || !out || outsz == 0) return 0; | ||
| 304 | + out[0] = '\0'; | ||
| 305 | + klen = strlen(key); | ||
| 306 | + p = qs; | ||
| 307 | + while (p && *p) { | ||
| 308 | + if (strncmp(p, key, klen) == 0 && p[klen] == '=') { | ||
| 309 | + size_t i = 0; | ||
| 310 | + p += klen + 1; | ||
| 311 | + while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; | ||
| 312 | + out[i] = '\0'; | ||
| 313 | + url_decode(out); | ||
| 314 | + return 1; | ||
| 315 | + } | ||
| 316 | + p = strchr(p, '&'); | ||
| 317 | + if (p) p++; | ||
| 318 | + } | ||
| 319 | + return 0; | ||
| 320 | +} | ||
| 321 | + | ||
| 322 | +/* ------------------------------------------------------------------ */ | ||
| 323 | +/* Node authentication (X-Bot-Password | Bearer | ?pwd=). --meta, */ | ||
| 324 | +/* --mcp and the HTML page never call this; every JSON action does. */ | ||
| 325 | +/* ------------------------------------------------------------------ */ | ||
| 326 | + | ||
| 327 | +static void require_node_auth(void) | ||
| 328 | +{ | ||
| 329 | + const char *np = getenv("BOT_PASSWORD"); | ||
| 330 | + const char *xp, *auth; | ||
| 331 | + char qpwd[256] = {0}; | ||
| 332 | + const char *qs; | ||
| 333 | + | ||
| 334 | + if (!np || !*np) return; /* open node: no gate */ | ||
| 335 | + xp = getenv("HTTP_X_BOT_PASSWORD"); | ||
| 336 | + if (xp && strcmp(xp, np) == 0) return; | ||
| 337 | + auth = getenv("HTTP_AUTHORIZATION"); | ||
| 338 | + if (auth) { | ||
| 339 | + while (*auth == ' ') auth++; | ||
| 340 | + if (strncasecmp(auth, "Bearer ", 7) == 0) { | ||
| 341 | + auth += 7; | ||
| 342 | + while (*auth == ' ') auth++; | ||
| 343 | + if (strcmp(auth, np) == 0) return; | ||
| 344 | + } | ||
| 345 | + } | ||
| 346 | + qs = getenv("QUERY_STRING"); | ||
| 347 | + if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && | ||
| 348 | + strcmp(qpwd, np) == 0) | ||
| 349 | + return; | ||
| 350 | + | ||
| 351 | + fputs("Status: 401 Unauthorized\r\n" | ||
| 352 | + "Content-Type: application/json; charset=utf-8\r\n\r\n" | ||
| 353 | + "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); | ||
| 354 | + exit(0); | ||
| 355 | +} | ||
| 356 | + | ||
| 357 | +/* ------------------------------------------------------------------ */ | ||
| 358 | +/* State directory + chains.json */ | ||
| 359 | +/* ------------------------------------------------------------------ */ | ||
| 360 | + | ||
| 361 | +static void state_dir(char *out, size_t outsz) | ||
| 362 | +{ | ||
| 363 | + const char *env = getenv("SEQTHINK_STATE_DIR"); | ||
| 364 | + struct stat st; | ||
| 365 | + | ||
| 366 | + if (env && *env) { snprintf(out, outsz, "%s", env); return; } | ||
| 367 | +#ifndef _WIN32 | ||
| 368 | + if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode) && | ||
| 369 | + access("/workspace", W_OK) == 0) { | ||
| 370 | + snprintf(out, outsz, "/workspace/.scorpiox/connectors/" PLUGIN_ID); | ||
| 371 | + return; | ||
| 372 | + } | ||
| 373 | +#endif | ||
| 374 | +#if defined(_WIN32) | ||
| 375 | + { | ||
| 376 | + const char *la = getenv("LOCALAPPDATA"); | ||
| 377 | + if (la && *la) { | ||
| 378 | + snprintf(out, outsz, "%s\\scorpiox\\connectors\\" PLUGIN_ID, la); | ||
| 379 | + return; | ||
| 380 | + } | ||
| 381 | + } | ||
| 382 | +#endif | ||
| 383 | + { | ||
| 384 | + const char *home = getenv("HOME"); | ||
| 385 | + if (!home || !*home) home = "/root"; | ||
| 386 | + snprintf(out, outsz, "%s/.scorpiox/connectors/" PLUGIN_ID, home); | ||
| 387 | + } | ||
| 388 | +} | ||
| 389 | + | ||
| 390 | +/* state_dir_name exposes only the leaf directory name for the UI chip (no | ||
| 391 | + * absolute path, no home directory name leaks into the browser). */ | ||
| 392 | +static void state_dir_name(char *out, size_t outsz) | ||
| 393 | +{ | ||
| 394 | + char dir[1000]; | ||
| 395 | + char *slash; | ||
| 396 | + size_t i; | ||
| 397 | + state_dir(dir, sizeof dir); | ||
| 398 | + slash = strrchr(dir, '/'); | ||
| 399 | + if (!slash) slash = strrchr(dir, '\\'); | ||
| 400 | + { | ||
| 401 | + const char *s = slash ? slash + 1 : dir; | ||
| 402 | + for (i = 0; s[i] && i + 1 < outsz; i++) out[i] = s[i]; | ||
| 403 | + out[i] = '\0'; | ||
| 404 | + } | ||
| 405 | +} | ||
| 406 | + | ||
| 407 | +static int mkdirs(const char *path) | ||
| 408 | +{ | ||
| 409 | + char buf[1200]; | ||
| 410 | + size_t i, n; | ||
| 411 | + struct stat st; | ||
| 412 | + snprintf(buf, sizeof buf, "%s", path); | ||
| 413 | + n = strlen(buf); | ||
| 414 | + for (i = 1; i < n; i++) { | ||
| 415 | + if (buf[i] == '/' || buf[i] == '\\') { | ||
| 416 | + char save = buf[i]; | ||
| 417 | + buf[i] = '\0'; | ||
| 418 | + if (i > 2) sx_mkdir(buf); | ||
| 419 | + buf[i] = save; | ||
| 420 | + } | ||
| 421 | + } | ||
| 422 | + sx_mkdir(buf); | ||
| 423 | + return stat(buf, &st) == 0 && S_ISDIR(st.st_mode); | ||
| 424 | +} | ||
| 425 | + | ||
| 426 | +static void chains_path(char *out, size_t outsz) | ||
| 427 | +{ | ||
| 428 | + char dir[1000]; | ||
| 429 | + state_dir(dir, sizeof dir); | ||
| 430 | + snprintf(out, outsz, "%s%cchains.json", dir, SX_PATHSEP); | ||
| 431 | +} | ||
| 432 | + | ||
| 433 | +static char *read_file(const char *path, size_t *lenp) | ||
| 434 | +{ | ||
| 435 | + FILE *f; | ||
| 436 | + long sz; | ||
| 437 | + char *txt; | ||
| 438 | + size_t got; | ||
| 439 | + f = fopen(path, "rb"); | ||
| 440 | + if (!f) return NULL; | ||
| 441 | + fseek(f, 0, SEEK_END); | ||
| 442 | + sz = ftell(f); | ||
| 443 | + fseek(f, 0, SEEK_SET); | ||
| 444 | + if (sz < 0 || sz > 8 * 1024 * 1024) { fclose(f); return NULL; } | ||
| 445 | + txt = (char *)sx_malloc((size_t)sz + 1); | ||
| 446 | + got = fread(txt, 1, (size_t)sz, f); | ||
| 447 | + txt[got] = '\0'; | ||
| 448 | + fclose(f); | ||
| 449 | + if (lenp) *lenp = got; | ||
| 450 | + return txt; | ||
| 451 | +} | ||
| 452 | + | ||
| 453 | +static int write_file_atomic(const char *path, const char *data, size_t len) | ||
| 454 | +{ | ||
| 455 | + char tmp[1300]; | ||
| 456 | + FILE *f; | ||
| 457 | + snprintf(tmp, sizeof tmp, "%s.tmp", path); | ||
| 458 | + f = fopen(tmp, "wb"); | ||
| 459 | + if (!f) return 0; | ||
| 460 | + if (len && fwrite(data, 1, len, f) != len) { fclose(f); remove(tmp); return 0; } | ||
| 461 | + if (fflush(f) != 0) { fclose(f); remove(tmp); return 0; } | ||
| 462 | + fclose(f); | ||
| 463 | + if (rename(tmp, path) != 0) { remove(tmp); return 0; } | ||
| 464 | + return 1; | ||
| 465 | +} | ||
| 466 | + | ||
| 467 | +/* ------------------------------------------------------------------ */ | ||
| 468 | +/* Tool model */ | ||
| 469 | +/* ------------------------------------------------------------------ */ | ||
| 470 | + | ||
| 471 | +typedef struct { | ||
| 472 | + char *thought; /* heap, never NULL after validation */ | ||
| 473 | + long long thought_number; | ||
| 474 | + long long total_thoughts; | ||
| 475 | + long long revises; /* 0 = absent */ | ||
| 476 | + long long branch_from; /* 0 = absent */ | ||
| 477 | + char *branch_id; /* NULL = absent */ | ||
| 478 | + int is_revision; | ||
| 479 | + int next_needed; | ||
| 480 | + int needs_more; | ||
| 481 | +} thought_t; | ||
| 482 | + | ||
| 483 | +typedef struct { | ||
| 484 | + thought_t *v; | ||
| 485 | + size_t n, cap; | ||
| 486 | +} tvec_t; | ||
| 487 | + | ||
| 488 | +static void tvec_push(tvec_t *h, const thought_t *t) | ||
| 489 | +{ | ||
| 490 | + if (h->n == h->cap) { | ||
| 491 | + h->cap = h->cap ? h->cap * 2 : 16; | ||
| 492 | + h->v = (thought_t *)realloc(h->v, h->cap * sizeof *h->v); | ||
| 493 | + if (!h->v) { fputs("out of memory\n", stderr); exit(1); } | ||
| 494 | + } | ||
| 495 | + h->v[h->n++] = *t; | ||
| 496 | +} | ||
| 497 | + | ||
| 498 | +static void thought_free(thought_t *t) | ||
| 499 | +{ | ||
| 500 | + free(t->thought); | ||
| 501 | + free(t->branch_id); | ||
| 502 | + memset(t, 0, sizeof *t); | ||
| 503 | +} | ||
| 504 | + | ||
| 505 | +/* Branch registry: insertion-ordered keys with per-branch thought counts. */ | ||
| 506 | +typedef struct { | ||
| 507 | + char *key; | ||
| 508 | + size_t count; | ||
| 509 | +} branch_t; | ||
| 510 | + | ||
| 511 | +typedef struct { | ||
| 512 | + branch_t *v; | ||
| 513 | + size_t n, cap; | ||
| 514 | +} bvec_t; | ||
| 515 | + | ||
| 516 | +static int bvec_find(const bvec_t *b, const char *key) | ||
| 517 | +{ | ||
| 518 | + size_t i; | ||
| 519 | + for (i = 0; i < b->n; i++) | ||
| 520 | + if (strcmp(b->v[i].key, key) == 0) return (int)i; | ||
| 521 | + return -1; | ||
| 522 | +} | ||
| 523 | + | ||
| 524 | +static void bvec_create(bvec_t *b, const char *key) | ||
| 525 | +{ | ||
| 526 | + if (bvec_find(b, key) >= 0) return; | ||
| 527 | + if (b->n == b->cap) { | ||
| 528 | + b->cap = b->cap ? b->cap * 2 : 8; | ||
| 529 | + b->v = (branch_t *)realloc(b->v, b->cap * sizeof *b->v); | ||
| 530 | + if (!b->v) { fputs("out of memory\n", stderr); exit(1); } | ||
| 531 | + } | ||
| 532 | + b->v[b->n].key = sx_strdup(key); | ||
| 533 | + b->v[b->n].count = 0; | ||
| 534 | + b->n++; | ||
| 535 | +} | ||
| 536 | + | ||
| 537 | +static void bvec_record(bvec_t *b, const char *key) | ||
| 538 | +{ | ||
| 539 | + int i = bvec_find(b, key); | ||
| 540 | + if (i < 0) { bvec_create(b, key); i = (int)b->n - 1; } | ||
| 541 | + b->v[i].count++; | ||
| 542 | +} | ||
| 543 | + | ||
| 544 | +static void bvec_evict(bvec_t *b, const char *key) | ||
| 545 | +{ | ||
| 546 | + int i = bvec_find(b, key); | ||
| 547 | + if (i < 0) return; | ||
| 548 | + if (b->v[i].count > 0) b->v[i].count--; | ||
| 549 | + if (b->v[i].count == 0) { /* upstream: an emptied branch is dropped */ | ||
| 550 | + free(b->v[i].key); | ||
| 551 | + memmove(&b->v[i], &b->v[i + 1], (b->n - (size_t)i - 1) * sizeof *b->v); | ||
| 552 | + b->n--; | ||
| 553 | + } | ||
| 554 | +} | ||
| 555 | + | ||
| 556 | +static long long read_max_history(void) | ||
| 557 | +{ | ||
| 558 | + const char *raw = getenv("MAX_THOUGHT_HISTORY"); | ||
| 559 | + const char *p; | ||
| 560 | + long long v; | ||
| 561 | + if (!raw) return DEFAULT_MAX_HIST; | ||
| 562 | + while (*raw == ' ' || *raw == '\t') raw++; | ||
| 563 | + if (!*raw) return DEFAULT_MAX_HIST; | ||
| 564 | + for (p = raw; *p; p++) if (!isdigit((unsigned char)*p)) break; | ||
| 565 | + if (*p != '\0' && !(p == raw + strlen(raw))) { /* trailing junk */ } | ||
| 566 | + for (p = raw; *p; p++) { | ||
| 567 | + if (!isdigit((unsigned char)*p)) { | ||
| 568 | + fprintf(stderr, "MAX_THOUGHT_HISTORY must be a positive integer, " | ||
| 569 | + "got \"%s\"; using %d\n", raw, DEFAULT_MAX_HIST); | ||
| 570 | + return DEFAULT_MAX_HIST; | ||
| 571 | + } | ||
| 572 | + } | ||
| 573 | + v = strtoll(raw, NULL, 10); | ||
| 574 | + if (v < 1) { | ||
| 575 | + fprintf(stderr, "MAX_THOUGHT_HISTORY must be a positive integer, " | ||
| 576 | + "got \"%s\"; using %d\n", raw, DEFAULT_MAX_HIST); | ||
| 577 | + return DEFAULT_MAX_HIST; | ||
| 578 | + } | ||
| 579 | + return v; | ||
| 580 | +} | ||
| 581 | + | ||
| 582 | +/* Coerce a JSON value to boolean like upstream's coercedBoolean: real bool, | ||
| 583 | + * or the strings "true"/"false" (case-insensitive). Returns 1 on success. */ | ||
| 584 | +static int val_bool(yyjson_val *v, int *out) | ||
| 585 | +{ | ||
| 586 | + if (yyjson_is_bool(v)) { *out = yyjson_is_true(v) ? 1 : 0; return 1; } | ||
| 587 | + if (yyjson_is_str(v)) { | ||
| 588 | + const char *s = yyjson_get_str(v); | ||
| 589 | + size_t i, n; | ||
| 590 | + char low[16]; | ||
| 591 | + if (!s) return 0; | ||
| 592 | + n = strlen(s); | ||
| 593 | + if (n >= sizeof low) return 0; | ||
| 594 | + for (i = 0; i < n; i++) low[i] = (char)tolower((unsigned char)s[i]); | ||
| 595 | + low[n] = '\0'; | ||
| 596 | + if (strcmp(low, "true") == 0) { *out = 1; return 1; } | ||
| 597 | + if (strcmp(low, "false") == 0) { *out = 0; return 1; } | ||
| 598 | + return 0; | ||
| 599 | + } | ||
| 600 | + return 0; | ||
| 601 | +} | ||
| 602 | + | ||
| 603 | +/* Coerce to integer like z.coerce.number().int(): JSON number or a numeric | ||
| 604 | + * string. Returns 1 on success. */ | ||
| 605 | +static int val_int(yyjson_val *v, long long *out) | ||
| 606 | +{ | ||
| 607 | + if (yyjson_is_int(v)) { *out = yyjson_get_sint(v); return 1; } | ||
| 608 | + if (yyjson_is_uint(v)) { *out = (long long)yyjson_get_uint(v); return 1; } | ||
| 609 | + if (yyjson_is_real(v)) { | ||
| 610 | + double d = yyjson_get_real(v); | ||
| 611 | + if (d == (double)(long long)d) { *out = (long long)d; return 1; } | ||
| 612 | + return 0; | ||
| 613 | + } | ||
| 614 | + if (yyjson_is_str(v)) { | ||
| 615 | + const char *s = yyjson_get_str(v); | ||
| 616 | + char *end = NULL; | ||
| 617 | + long long ll; | ||
| 618 | + if (!s || !*s) return 0; | ||
| 619 | + errno = 0; | ||
| 620 | + ll = strtoll(s, &end, 10); | ||
| 621 | + if (errno != 0 || !end) return 0; | ||
| 622 | + while (*end == ' ' || *end == '\t' || *end == '\n' || *end == '\r') end++; | ||
| 623 | + if (*end != '\0') return 0; | ||
| 624 | + *out = ll; | ||
| 625 | + return 1; | ||
| 626 | + } | ||
| 627 | + return 0; | ||
| 628 | +} | ||
| 629 | + | ||
| 630 | +/* Validate against the upstream schema (errors mirror index.ts/lib.ts). */ | ||
| 631 | +static int validate_thought(yyjson_val *args, thought_t *t, char *err, size_t errsz) | ||
| 632 | +{ | ||
| 633 | + yyjson_val *v; | ||
| 634 | + memset(t, 0, sizeof *t); | ||
| 635 | + | ||
| 636 | + v = yyjson_obj_get(args, "thought"); | ||
| 637 | + if (!v || !yyjson_is_str(v) || !yyjson_get_str(v) || | ||
| 638 | + !yyjson_get_str(v)[0]) { | ||
| 639 | + snprintf(err, errsz, "Invalid thought: must be a string"); | ||
| 640 | + return 0; | ||
| 641 | + } | ||
| 642 | + if (strlen(yyjson_get_str(v)) > THOUGHT_MAX) { | ||
| 643 | + snprintf(err, errsz, "Invalid thought: too long (max %d bytes)", THOUGHT_MAX); | ||
| 644 | + return 0; | ||
| 645 | + } | ||
| 646 | + t->thought = sx_strdup(yyjson_get_str(v)); | ||
| 647 | + | ||
| 648 | + v = yyjson_obj_get(args, "nextThoughtNeeded"); | ||
| 649 | + if (!val_bool(v, &t->next_needed)) { | ||
| 650 | + snprintf(err, errsz, "Invalid nextThoughtNeeded: must be a boolean"); | ||
| 651 | + thought_free(t); | ||
| 652 | + return 0; | ||
| 653 | + } | ||
| 654 | + | ||
| 655 | + v = yyjson_obj_get(args, "thoughtNumber"); | ||
| 656 | + { | ||
| 657 | + long long n; | ||
| 658 | + if (!val_int(v, &n) || n < 1) { | ||
| 659 | + snprintf(err, errsz, "Invalid thoughtNumber: must be a number"); | ||
| 660 | + thought_free(t); | ||
| 661 | + return 0; | ||
| 662 | + } | ||
| 663 | + t->thought_number = n; | ||
| 664 | + } | ||
| 665 | + | ||
| 666 | + v = yyjson_obj_get(args, "totalThoughts"); | ||
| 667 | + { | ||
| 668 | + long long n; | ||
| 669 | + if (!val_int(v, &n) || n < 1) { | ||
| 670 | + snprintf(err, errsz, "Invalid totalThoughts: must be a number"); | ||
| 671 | + thought_free(t); | ||
| 672 | + return 0; | ||
| 673 | + } | ||
| 674 | + t->total_thoughts = n; | ||
| 675 | + } | ||
| 676 | + | ||
| 677 | + v = yyjson_obj_get(args, "isRevision"); | ||
| 678 | + if (v && !yyjson_is_null(v) && !val_bool(v, &t->is_revision)) { | ||
| 679 | + snprintf(err, errsz, "Invalid isRevision: must be a boolean"); | ||
| 680 | + thought_free(t); | ||
| 681 | + return 0; | ||
| 682 | + } | ||
| 683 | + | ||
| 684 | + v = yyjson_obj_get(args, "revisesThought"); | ||
| 685 | + if (v && !yyjson_is_null(v)) { | ||
| 686 | + long long n; | ||
| 687 | + if (!val_int(v, &n) || n < 1) { | ||
| 688 | + snprintf(err, errsz, "Invalid revisesThought: must be a number"); | ||
| 689 | + thought_free(t); | ||
| 690 | + return 0; | ||
| 691 | + } | ||
| 692 | + t->revises = n; | ||
| 693 | + } | ||
| 694 | + | ||
| 695 | + v = yyjson_obj_get(args, "branchFromThought"); | ||
| 696 | + if (v && !yyjson_is_null(v)) { | ||
| 697 | + long long n; | ||
| 698 | + if (!val_int(v, &n) || n < 1) { | ||
| 699 | + snprintf(err, errsz, "Invalid branchFromThought: must be a number"); | ||
| 700 | + thought_free(t); | ||
| 701 | + return 0; | ||
| 702 | + } | ||
| 703 | + t->branch_from = n; | ||
| 704 | + } | ||
| 705 | + | ||
| 706 | + v = yyjson_obj_get(args, "branchId"); | ||
| 707 | + if (v && !yyjson_is_null(v)) { | ||
| 708 | + if (!yyjson_is_str(v) || !yyjson_get_str(v)) { | ||
| 709 | + snprintf(err, errsz, "Invalid branchId: must be a string"); | ||
| 710 | + thought_free(t); | ||
| 711 | + return 0; | ||
| 712 | + } | ||
| 713 | + if (strlen(yyjson_get_str(v)) > BRANCHID_MAX) { | ||
| 714 | + snprintf(err, errsz, "Invalid branchId: too long (max %d bytes)", | ||
| 715 | + BRANCHID_MAX); | ||
| 716 | + thought_free(t); | ||
| 717 | + return 0; | ||
| 718 | + } | ||
| 719 | + t->branch_id = sx_strdup(yyjson_get_str(v)); | ||
| 720 | + } | ||
| 721 | + | ||
| 722 | + v = yyjson_obj_get(args, "needsMoreThoughts"); | ||
| 723 | + if (v && !yyjson_is_null(v) && !val_bool(v, &t->needs_more)) { | ||
| 724 | + snprintf(err, errsz, "Invalid needsMoreThoughts: must be a boolean"); | ||
| 725 | + thought_free(t); | ||
| 726 | + return 0; | ||
| 727 | + } | ||
| 728 | + return 1; | ||
| 729 | +} | ||
| 730 | + | ||
| 731 | +/* One line per accepted thought on stderr, upstream's box condensed to a | ||
| 732 | + * single label line (no emoji, no colour codes in a clean-room binary). | ||
| 733 | + * Silenced by DISABLE_THOUGHT_LOGGING=1|true like upstream. */ | ||
| 734 | +static void log_thought_stderr(const thought_t *t) | ||
| 735 | +{ | ||
| 736 | + const char *dl = getenv("DISABLE_THOUGHT_LOGGING"); | ||
| 737 | + char low[8]; | ||
| 738 | + size_t i, n; | ||
| 739 | + if (dl && *dl) { | ||
| 740 | + n = strlen(dl); | ||
| 741 | + if (strcmp(dl, "1") == 0) return; | ||
| 742 | + if (n < sizeof low) { | ||
| 743 | + for (i = 0; i < n; i++) low[i] = (char)tolower((unsigned char)dl[i]); | ||
| 744 | + low[n] = '\0'; | ||
| 745 | + if (strcmp(low, "true") == 0) return; | ||
| 746 | + } | ||
| 747 | + } | ||
| 748 | + if (t->is_revision) | ||
| 749 | + fprintf(stderr, "[seqthink] Revision %lld/%lld (revising thought %lld)\n", | ||
| 750 | + t->thought_number, t->total_thoughts, t->revises); | ||
| 751 | + else if (t->branch_from && t->branch_id) | ||
| 752 | + fprintf(stderr, "[seqthink] Branch %lld/%lld (from thought %lld, ID: %s)\n", | ||
| 753 | + t->thought_number, t->total_thoughts, t->branch_from, t->branch_id); | ||
| 754 | + else if (t->branch_from) | ||
| 755 | + fprintf(stderr, "[seqthink] Branch %lld/%lld (from thought %lld)\n", | ||
| 756 | + t->thought_number, t->total_thoughts, t->branch_from); | ||
| 757 | + else | ||
| 758 | + fprintf(stderr, "[seqthink] Thought %lld/%lld\n", | ||
| 759 | + t->thought_number, t->total_thoughts); | ||
| 760 | + fflush(stderr); | ||
| 761 | +} | ||
| 762 | + | ||
| 763 | +/* Append one thought to the persisted chains file. The file is a simple | ||
| 764 | + * {"chains":[{"id":...,"started_at":...,"updated_at":...,"branches":[...], | ||
| 765 | + * "thoughts":[{...}]}]} document, merged by chain id: our chain's | ||
| 766 | + * existing thoughts are kept (bounded), other chains are carried over | ||
| 767 | + * (bounded, oldest-updated first to keep the newest). Every field is | ||
| 768 | + * re-serialised from parsed values, so a hand-corrupted file degrades to | ||
| 769 | + * "unparseable -> start clean" instead of poisoning the output. The bytes go | ||
| 770 | + * to <path>.tmp and only then rename() over the file (crash-safe). | ||
| 771 | + * Returns 1 on success; a persistence failure never fails the tool call. */ | ||
| 772 | + | ||
| 773 | +typedef struct { | ||
| 774 | + char *thought; | ||
| 775 | + long long tn, tt; | ||
| 776 | + int next_needed, is_revision, needs_more; | ||
| 777 | + long long revises, branch_from; | ||
| 778 | + char *branch_id; | ||
| 779 | + long long at; | ||
| 780 | +} pth_t; | ||
| 781 | + | ||
| 782 | +typedef struct { | ||
| 783 | + char *id; | ||
| 784 | + long long started_at, updated_at; | ||
| 785 | + pth_t *th; | ||
| 786 | + size_t n, cap; | ||
| 787 | +} chain_t; | ||
| 788 | + | ||
| 789 | +static void chain_add(chain_t *c, const pth_t *t) | ||
| 790 | +{ | ||
| 791 | + if (c->n == c->cap) { | ||
| 792 | + c->cap = c->cap ? c->cap * 2 : 16; | ||
| 793 | + c->th = (pth_t *)realloc(c->th, c->cap * sizeof *c->th); | ||
| 794 | + if (!c->th) { fputs("out of memory\n", stderr); exit(1); } | ||
| 795 | + } | ||
| 796 | + c->th[c->n++] = *t; | ||
| 797 | +} | ||
| 798 | + | ||
| 799 | +static void chain_free(chain_t *c) | ||
| 800 | +{ | ||
| 801 | + size_t i; | ||
| 802 | + for (i = 0; i < c->n; i++) { free(c->th[i].thought); free(c->th[i].branch_id); } | ||
| 803 | + free(c->th); | ||
| 804 | + free(c->id); | ||
| 805 | + memset(c, 0, sizeof *c); | ||
| 806 | +} | ||
| 807 | + | ||
| 808 | +static char *dup_str_or_null(yyjson_val *v) | ||
| 809 | +{ | ||
| 810 | + if (yyjson_is_str(v) && yyjson_get_str(v)) return sx_strdup(yyjson_get_str(v)); | ||
| 811 | + return NULL; | ||
| 812 | +} | ||
| 813 | + | ||
| 814 | +static int load_chains_model(char *txt, size_t len, chain_t **out, size_t *outn) | ||
| 815 | +{ | ||
| 816 | + yyjson_doc *doc; | ||
| 817 | + yyjson_val *root, *chains; | ||
| 818 | + chain_t *cs = NULL; | ||
| 819 | + size_t n = 0, i; | ||
| 820 | + | ||
| 821 | + *out = NULL; *outn = 0; | ||
| 822 | + if (!txt) return 1; | ||
| 823 | + doc = yyjson_read(txt, len, 0); | ||
| 824 | + free(txt); | ||
| 825 | + if (!doc) return 0; /* unparseable */ | ||
| 826 | + root = yyjson_doc_get_root(doc); | ||
| 827 | + if (!yyjson_is_obj(root)) { yyjson_doc_free(doc); return 0; } | ||
| 828 | + chains = yyjson_obj_get(root, "chains"); | ||
| 829 | + if (!yyjson_is_arr(chains)) { yyjson_doc_free(doc); return 1; } | ||
| 830 | + n = yyjson_arr_size(chains); | ||
| 831 | + if (n) { | ||
| 832 | + cs = (chain_t *)sx_malloc(n * sizeof *cs); | ||
| 833 | + memset(cs, 0, n * sizeof *cs); | ||
| 834 | + } | ||
| 835 | + for (i = 0; i < n; i++) { | ||
| 836 | + yyjson_val *c = yyjson_arr_get(chains, i); | ||
| 837 | + yyjson_val *v; | ||
| 838 | + if (!yyjson_is_obj(c)) continue; | ||
| 839 | + v = yyjson_obj_get(c, "id"); | ||
| 840 | + if (!yyjson_is_str(v) || !yyjson_get_str(v) || !*yyjson_get_str(v)) continue; | ||
| 841 | + cs[i].id = sx_strdup(yyjson_get_str(v)); | ||
| 842 | + v = yyjson_obj_get(c, "started_at"); | ||
| 843 | + cs[i].started_at = yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0; | ||
| 844 | + v = yyjson_obj_get(c, "updated_at"); | ||
| 845 | + cs[i].updated_at = yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0; | ||
| 846 | + v = yyjson_obj_get(c, "thoughts"); | ||
| 847 | + if (yyjson_is_arr(v)) { | ||
| 848 | + size_t j, tn = yyjson_arr_size(v); | ||
| 849 | + for (j = 0; j < tn; j++) { | ||
| 850 | + yyjson_val *tv = yyjson_arr_get(v, j); | ||
| 851 | + pth_t t; | ||
| 852 | + yyjson_val *x; | ||
| 853 | + if (!yyjson_is_obj(tv)) continue; | ||
| 854 | + memset(&t, 0, sizeof t); | ||
| 855 | + x = yyjson_obj_get(tv, "thought"); | ||
| 856 | + if (!yyjson_is_str(x) || !yyjson_get_str(x)) continue; | ||
| 857 | + t.thought = sx_strdup(yyjson_get_str(x)); | ||
| 858 | + x = yyjson_obj_get(tv, "thought_number"); | ||
| 859 | + t.tn = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; | ||
| 860 | + x = yyjson_obj_get(tv, "total_thoughts"); | ||
| 861 | + t.tt = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; | ||
| 862 | + t.next_needed = yyjson_is_true(yyjson_obj_get(tv, "next_needed")); | ||
| 863 | + t.is_revision = yyjson_is_true(yyjson_obj_get(tv, "is_revision")); | ||
| 864 | + t.needs_more = yyjson_is_true(yyjson_obj_get(tv, "needs_more")); | ||
| 865 | + x = yyjson_obj_get(tv, "revises"); | ||
| 866 | + t.revises = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; | ||
| 867 | + x = yyjson_obj_get(tv, "branch_from"); | ||
| 868 | + t.branch_from = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; | ||
| 869 | + t.branch_id = dup_str_or_null(yyjson_obj_get(tv, "branch_id")); | ||
| 870 | + x = yyjson_obj_get(tv, "at"); | ||
| 871 | + t.at = yyjson_is_int(x) ? (long long)yyjson_get_sint(x) : 0; | ||
| 872 | + chain_add(&cs[i], &t); | ||
| 873 | + } | ||
| 874 | + } | ||
| 875 | + } | ||
| 876 | + yyjson_doc_free(doc); | ||
| 877 | + *out = cs; *outn = n; | ||
| 878 | + return 1; | ||
| 879 | +} | ||
| 880 | + | ||
| 881 | +static void free_model(chain_t *cs, size_t n) | ||
| 882 | +{ | ||
| 883 | + size_t i; | ||
| 884 | + if (!cs) return; | ||
| 885 | + for (i = 0; i < n; i++) chain_free(&cs[i]); | ||
| 886 | + free(cs); | ||
| 887 | +} | ||
| 888 | + | ||
| 889 | +static void emit_thought(buf_t *b, const pth_t *t) | ||
| 890 | +{ | ||
| 891 | + buf_str(b, "{\"thought\":"); | ||
| 892 | + json_escape_buf(b, t->thought); | ||
| 893 | + buf_addf(b, ",\"thought_number\":%lld,\"total_thoughts\":%lld", t->tn, t->tt); | ||
| 894 | + buf_addf(b, ",\"next_needed\":%s", t->next_needed ? "true" : "false"); | ||
| 895 | + if (t->is_revision) buf_str(b, ",\"is_revision\":true"); | ||
| 896 | + if (t->revises) buf_addf(b, ",\"revises\":%lld", t->revises); | ||
| 897 | + if (t->branch_from) buf_addf(b, ",\"branch_from\":%lld", t->branch_from); | ||
| 898 | + if (t->branch_id) { | ||
| 899 | + buf_str(b, ",\"branch_id\":"); | ||
| 900 | + json_escape_buf(b, t->branch_id); | ||
| 901 | + } | ||
| 902 | + if (t->needs_more) buf_str(b, ",\"needs_more\":true"); | ||
| 903 | + buf_addf(b, ",\"at\":%lld}", t->at); | ||
| 904 | +} | ||
| 905 | + | ||
| 906 | +static int persist_thought(const char *chain_id, const thought_t *t) | ||
| 907 | +{ | ||
| 908 | + char dir[1000], path[1200]; | ||
| 909 | + char *txt = NULL; | ||
| 910 | + size_t len = 0, i, n = 0; | ||
| 911 | + chain_t *cs = NULL; | ||
| 912 | + chain_t *mine = NULL; | ||
| 913 | + pth_t nt; | ||
| 914 | + buf_t out; | ||
| 915 | + int mine_idx = -1; | ||
| 916 | + | ||
| 917 | + state_dir(dir, sizeof dir); | ||
| 918 | + if (!mkdirs(dir)) return 0; | ||
| 919 | + chains_path(path, sizeof path); | ||
| 920 | + | ||
| 921 | + txt = read_file(path, &len); | ||
| 922 | + if (!load_chains_model(txt, len, &cs, &n)) { /* frees txt, strays to clean */ | ||
| 923 | + cs = NULL; n = 0; | ||
| 924 | + } | ||
| 925 | + | ||
| 926 | + for (i = 0; i < n; i++) | ||
| 927 | + if (cs[i].id && strcmp(cs[i].id, chain_id) == 0) { mine_idx = (int)i; break; } | ||
| 928 | + mine = mine_idx >= 0 ? &cs[mine_idx] : NULL; | ||
| 929 | + | ||
| 930 | + memset(&nt, 0, sizeof nt); | ||
| 931 | + nt.thought = sx_strdup(t->thought); /* owned by the chain model */ | ||
| 932 | + nt.tn = t->thought_number; | ||
| 933 | + nt.tt = t->total_thoughts; | ||
| 934 | + nt.next_needed = t->next_needed; | ||
| 935 | + nt.is_revision = t->is_revision; | ||
| 936 | + nt.needs_more = t->needs_more; | ||
| 937 | + nt.revises = t->revises; | ||
| 938 | + nt.branch_from = t->branch_from; | ||
| 939 | + nt.branch_id = t->branch_id ? sx_strdup(t->branch_id) : NULL; | ||
| 940 | + nt.at = (long long)time(NULL); | ||
| 941 | + | ||
| 942 | + if (!mine) { | ||
| 943 | + cs = (chain_t *)realloc(cs, (n + 1) * sizeof *cs); | ||
| 944 | + if (!cs) { fputs("out of memory\n", stderr); exit(1); } | ||
| 945 | + memset(&cs[n], 0, sizeof cs[n]); | ||
| 946 | + mine = &cs[n]; | ||
| 947 | + mine->id = sx_strdup(chain_id); | ||
| 948 | + mine->started_at = nt.at; | ||
| 949 | + n++; | ||
| 950 | + } | ||
| 951 | + chain_add(mine, &nt); | ||
| 952 | + mine->updated_at = nt.at; | ||
| 953 | + /* Bound this chain: keep the newest MAX_THOUGHTS_EACH thoughts. */ | ||
| 954 | + if (mine->n > MAX_THOUGHTS_EACH) { | ||
| 955 | + size_t drop = mine->n - MAX_THOUGHTS_EACH, j; | ||
| 956 | + for (j = 0; j < drop; j++) { | ||
| 957 | + free(mine->th[j].thought); | ||
| 958 | + free(mine->th[j].branch_id); | ||
| 959 | + } | ||
| 960 | + memmove(&mine->th[0], &mine->th[drop], (mine->n - drop) * sizeof *mine->th); | ||
| 961 | + mine->n -= drop; | ||
| 962 | + } | ||
| 963 | + | ||
| 964 | + /* Bound the file: keep our chain + the newest (MAX_CHAINS - 1) others. | ||
| 965 | + * mine_idx is the ORIGINAL index of our chain (mine may dangle after a | ||
| 966 | + * growth realloc, so identity is tracked by index). */ | ||
| 967 | + if (n > MAX_CHAINS) { | ||
| 968 | + char *keep = (char *)sx_malloc(n); | ||
| 969 | + size_t w = 0, k; | ||
| 970 | + memset(keep, 1, n); | ||
| 971 | + if (mine_idx >= 0) keep[mine_idx] = 2; /* ours: never dropped */ | ||
| 972 | + while (1) { | ||
| 973 | + long long oldest = LLONG_MAX; | ||
| 974 | + int oi = -1; | ||
| 975 | + size_t kept = 0; | ||
| 976 | + for (k = 0; k < n; k++) if (keep[k]) kept++; | ||
| 977 | + if (kept <= (size_t)MAX_CHAINS) break; | ||
| 978 | + for (k = 0; k < n; k++) { | ||
| 979 | + if (keep[k] != 1) continue; | ||
| 980 | + if (cs[k].updated_at < oldest) { oldest = cs[k].updated_at; oi = (int)k; } | ||
| 981 | + } | ||
| 982 | + if (oi < 0) { /* tie fallback */ | ||
| 983 | + for (k = 0; k < n; k++) if (keep[k] == 1) { oi = (int)k; break; } | ||
| 984 | + } | ||
| 985 | + if (oi < 0) break; | ||
| 986 | + keep[oi] = 0; | ||
| 987 | + } | ||
| 988 | + for (k = 0; k < n; k++) { | ||
| 989 | + if (!keep[k]) { chain_free(&cs[k]); continue; } | ||
| 990 | + if (w != k) cs[w] = cs[k]; | ||
| 991 | + w++; | ||
| 992 | + } | ||
| 993 | + n = w; | ||
| 994 | + free(keep); | ||
| 995 | + } | ||
| 996 | + | ||
| 997 | + buf_init(&out); | ||
| 998 | + buf_str(&out, "{\"chains\":["); | ||
| 999 | + for (i = 0; i < n; i++) { | ||
| 1000 | + if (i) buf_str(&out, ","); | ||
| 1001 | + buf_str(&out, "{\"id\":"); | ||
| 1002 | + json_escape_buf(&out, cs[i].id); | ||
| 1003 | + buf_addf(&out, ",\"started_at\":%lld,\"updated_at\":%lld,\"thoughts\":[", | ||
| 1004 | + cs[i].started_at, cs[i].updated_at); | ||
| 1005 | + { | ||
| 1006 | + size_t j; | ||
| 1007 | + for (j = 0; j < cs[i].n; j++) { | ||
| 1008 | + if (j) buf_str(&out, ","); | ||
| 1009 | + emit_thought(&out, &cs[i].th[j]); | ||
| 1010 | + } | ||
| 1011 | + } | ||
| 1012 | + buf_str(&out, "],\"count\":"); | ||
| 1013 | + buf_addf(&out, "%zu", cs[i].n); | ||
| 1014 | + buf_str(&out, ",\"branches\":["); | ||
| 1015 | + { /* distinct branch ids in first-seen order */ | ||
| 1016 | + size_t j, k; | ||
| 1017 | + int first = 1; | ||
| 1018 | + for (j = 0; j < cs[i].n; j++) { | ||
| 1019 | + int seen = 0; | ||
| 1020 | + if (!cs[i].th[j].branch_id || !cs[i].th[j].branch_from) continue; | ||
| 1021 | + for (k = 0; k < j; k++) | ||
| 1022 | + if (cs[i].th[k].branch_id && cs[i].th[j].branch_id && | ||
| 1023 | + strcmp(cs[i].th[k].branch_id, cs[i].th[j].branch_id) == 0) | ||
| 1024 | + { seen = 1; break; } | ||
| 1025 | + if (seen) continue; | ||
| 1026 | + if (!first) buf_str(&out, ","); | ||
| 1027 | + first = 0; | ||
| 1028 | + json_escape_buf(&out, cs[i].th[j].branch_id); | ||
| 1029 | + } | ||
| 1030 | + } | ||
| 1031 | + buf_str(&out, "]}"); | ||
| 1032 | + } | ||
| 1033 | + buf_str(&out, "]}"); | ||
| 1034 | + | ||
| 1035 | + if (!out.p) { free_model(cs, n); return 0; } | ||
| 1036 | + { | ||
| 1037 | + int ok = write_file_atomic(path, out.p, out.n); | ||
| 1038 | + buf_free(&out); | ||
| 1039 | + free_model(cs, n); | ||
| 1040 | + return ok; | ||
| 1041 | + } | ||
| 1042 | +} | ||
| 1043 | + | ||
| 1044 | +/* ------------------------------------------------------------------ */ | ||
| 1045 | +/* Session (one --mcp process == one chain) */ | ||
| 1046 | +/* ------------------------------------------------------------------ */ | ||
| 1047 | + | ||
| 1048 | +typedef struct { | ||
| 1049 | + tvec_t history; | ||
| 1050 | + bvec_t branches; | ||
| 1051 | + long long max_hist; | ||
| 1052 | + char chain_id[64]; | ||
| 1053 | + int persist; | ||
| 1054 | +} session_t; | ||
| 1055 | + | ||
| 1056 | +static void session_init(session_t *s) | ||
| 1057 | +{ | ||
| 1058 | + const char *dl = getenv("DISABLE_THOUGHT_LOGGING"); | ||
| 1059 | + memset(s, 0, sizeof *s); | ||
| 1060 | + s->max_hist = read_max_history(); | ||
| 1061 | + snprintf(s->chain_id, sizeof s->chain_id, "th-%llx-%lx", | ||
| 1062 | + (unsigned long long)time(NULL), (unsigned long) | ||
| 1063 | +#if defined(_WIN32) | ||
| 1064 | + GetCurrentProcessId() | ||
| 1065 | +#else | ||
| 1066 | + (unsigned long)getpid() | ||
| 1067 | +#endif | ||
| 1068 | + ); | ||
| 1069 | + s->persist = 1; | ||
| 1070 | + if (dl && *dl) { | ||
| 1071 | + const char *p = dl; | ||
| 1072 | + int all_digits = 1; | ||
| 1073 | + for (; *p; p++) if (!isdigit((unsigned char)*p)) { all_digits = 0; break; } | ||
| 1074 | + if (strcmp(dl, "1") == 0 || strcmp(dl, "true") == 0 || | ||
| 1075 | + strcmp(dl, "TRUE") == 0 || strcmp(dl, "True") == 0) | ||
| 1076 | + s->persist = 0; | ||
| 1077 | + (void)all_digits; | ||
| 1078 | + } | ||
| 1079 | +} | ||
| 1080 | + | ||
| 1081 | +static void session_free(session_t *s) | ||
| 1082 | +{ | ||
| 1083 | + size_t i; | ||
| 1084 | + for (i = 0; i < s->history.n; i++) thought_free(&s->history.v[i]); | ||
| 1085 | + free(s->history.v); | ||
| 1086 | + for (i = 0; i < s->branches.n; i++) free(s->branches.v[i].key); | ||
| 1087 | + free(s->branches.v); | ||
| 1088 | + memset(s, 0, sizeof *s); | ||
| 1089 | +} | ||
| 1090 | + | ||
| 1091 | +/* The tool itself. Returns the result text (heap; caller frees) and sets | ||
| 1092 | + * *is_error like upstream's {content,isError}. */ | ||
| 1093 | +static char *process_thought(session_t *s, yyjson_val *args, int *is_error) | ||
| 1094 | +{ | ||
| 1095 | + thought_t t; | ||
| 1096 | + char err[256]; | ||
| 1097 | + buf_t b; | ||
| 1098 | + | ||
| 1099 | + *is_error = 0; | ||
| 1100 | + if (!args || !yyjson_is_obj(args)) { | ||
| 1101 | + return sx_strdup("{\"error\":\"Invalid thought: must be a string\"," | ||
| 1102 | + "\"status\":\"failed\"}"); | ||
| 1103 | + } | ||
| 1104 | + if (!validate_thought(args, &t, err, sizeof err)) { | ||
| 1105 | + buf_init(&b); | ||
| 1106 | + buf_str(&b, "{\"error\":"); | ||
| 1107 | + json_escape_buf(&b, err); | ||
| 1108 | + buf_str(&b, ",\"status\":\"failed\"}"); | ||
| 1109 | + *is_error = 1; | ||
| 1110 | + return b.p ? b.p : sx_strdup("{\"error\":\"invalid input\",\"status\":\"failed\"}"); | ||
| 1111 | + } | ||
| 1112 | + | ||
| 1113 | + /* Upstream rule: thoughtNumber past totalThoughts raises the estimate. */ | ||
| 1114 | + if (t.thought_number > t.total_thoughts) t.total_thoughts = t.thought_number; | ||
| 1115 | + | ||
| 1116 | + /* Upstream logs before touching any state. */ | ||
| 1117 | + log_thought_stderr(&t); | ||
| 1118 | + | ||
| 1119 | + tvec_push(&s->history, &t); | ||
| 1120 | + if (t.branch_from && t.branch_id) bvec_record(&s->branches, t.branch_id); | ||
| 1121 | + | ||
| 1122 | + if ((long long)s->history.n > s->max_hist) { | ||
| 1123 | + thought_t *oldest = &s->history.v[0]; | ||
| 1124 | + if (oldest->branch_from && oldest->branch_id) | ||
| 1125 | + bvec_evict(&s->branches, oldest->branch_id); | ||
| 1126 | + thought_free(oldest); | ||
| 1127 | + memmove(&s->history.v[0], &s->history.v[1], | ||
| 1128 | + (s->history.n - 1) * sizeof *s->history.v); | ||
| 1129 | + s->history.n--; | ||
| 1130 | + } | ||
| 1131 | + | ||
| 1132 | + if (s->persist) persist_thought(s->chain_id, &t); | ||
| 1133 | + | ||
| 1134 | + /* Upstream response: exactly these five fields. One buffer, compact | ||
| 1135 | + * single-line JSON (valid inside structuredContent); the content text is | ||
| 1136 | + * the same object, so tests and clients can parse either. */ | ||
| 1137 | + { | ||
| 1138 | + size_t i; | ||
| 1139 | + buf_init(&b); | ||
| 1140 | + buf_addf(&b, "{\"thoughtNumber\":%lld,\"totalThoughts\":%lld," | ||
| 1141 | + "\"nextThoughtNeeded\":%s,\"branches\":[", | ||
| 1142 | + t.thought_number, t.total_thoughts, | ||
| 1143 | + t.next_needed ? "true" : "false"); | ||
| 1144 | + for (i = 0; i < s->branches.n; i++) { | ||
| 1145 | + if (i) buf_str(&b, ","); | ||
| 1146 | + json_escape_buf(&b, s->branches.v[i].key); | ||
| 1147 | + } | ||
| 1148 | + buf_addf(&b, "],\"thoughtHistoryLength\":%zu}", s->history.n); | ||
| 1149 | + } | ||
| 1150 | + /* The snapshot was already taken before we hand back; free this | ||
| 1151 | + * thought's copy only after persistence used it. */ | ||
| 1152 | + return b.p ? b.p : sx_strdup("{}"); | ||
| 1153 | +} | ||
| 1154 | + | ||
| 1155 | +/* ------------------------------------------------------------------ */ | ||
| 1156 | +/* --mcp mode: MCP JSON-RPC 2.0 over stdio */ | ||
| 1157 | +/* ------------------------------------------------------------------ */ | ||
| 1158 | + | ||
| 1159 | +static const char SEQTHINK_TOOL_SCHEMA[] = | ||
| 1160 | + "{\"type\":\"object\",\"properties\":{" | ||
| 1161 | + "\"thought\":{\"type\":\"string\",\"description\":\"Your current thinking step\"}," | ||
| 1162 | + "\"nextThoughtNeeded\":{\"type\":\"boolean\",\"description\":\"Whether another thought step is needed\"}," | ||
| 1163 | + "\"thoughtNumber\":{\"type\":\"integer\",\"description\":\"Current thought number (numeric value, e.g., 1, 2, 3)\",\"minimum\":1}," | ||
| 1164 | + "\"totalThoughts\":{\"type\":\"integer\",\"description\":\"Estimated total thoughts needed (numeric value, e.g., 5, 10)\",\"minimum\":1}," | ||
| 1165 | + "\"isRevision\":{\"type\":\"boolean\",\"description\":\"Whether this revises previous thinking\"}," | ||
| 1166 | + "\"revisesThought\":{\"type\":\"integer\",\"description\":\"Which thought is being reconsidered\",\"minimum\":1}," | ||
| 1167 | + "\"branchFromThought\":{\"type\":\"integer\",\"description\":\"Branching point thought number\",\"minimum\":1}," | ||
| 1168 | + "\"branchId\":{\"type\":\"string\",\"description\":\"Branch identifier\"}," | ||
| 1169 | + "\"needsMoreThoughts\":{\"type\":\"boolean\",\"description\":\"If more thoughts are needed\"}" | ||
| 1170 | + "},\"required\":[\"thought\",\"nextThoughtNeeded\",\"thoughtNumber\",\"totalThoughts\"]}"; | ||
| 1171 | + | ||
| 1172 | +static const char SEQTHINK_TOOL_OUTPUT[] = | ||
| 1173 | + "{\"type\":\"object\",\"properties\":{" | ||
| 1174 | + "\"thoughtNumber\":{\"type\":\"number\"}," | ||
| 1175 | + "\"totalThoughts\":{\"type\":\"number\"}," | ||
| 1176 | + "\"nextThoughtNeeded\":{\"type\":\"boolean\"}," | ||
| 1177 | + "\"branches\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}," | ||
| 1178 | + "\"thoughtHistoryLength\":{\"type\":\"number\"}}}"; | ||
| 1179 | + | ||
| 1180 | +static const char SEQTHINK_TOOL_DESC[] = | ||
| 1181 | + "A detailed tool for dynamic and reflective problem-solving through thoughts.\n" | ||
| 1182 | + "Each thought can build on, question, or revise previous insights as understanding deepens.\n\n" | ||
| 1183 | + "When to use this tool:\n" | ||
| 1184 | + "- Breaking down complex problems into steps\n" | ||
| 1185 | + "- Planning and design with room for revision\n" | ||
| 1186 | + "- Analysis that might need course correction\n" | ||
| 1187 | + "- Problems where the full scope might not be clear initially\n" | ||
| 1188 | + "- Tasks that need to maintain context over multiple steps\n" | ||
| 1189 | + "- Situations where irrelevant information needs to be filtered out\n\n" | ||
| 1190 | + "You should:\n" | ||
| 1191 | + "1. Estimate totalThoughts up front and adjust it up or down as you go;" | ||
| 1192 | + " thoughtNumber may exceed it\n" | ||
| 1193 | + "2. Question or revise earlier thoughts (isRevision with revisesThought)," | ||
| 1194 | + " or branch (branchFromThought with branchId)\n" | ||
| 1195 | + "3. Express uncertainty, and ignore information irrelevant to the current step\n" | ||
| 1196 | + "4. Generate a solution hypothesis, verify it against the earlier steps," | ||
| 1197 | + " and repeat until satisfied\n" | ||
| 1198 | + "5. Set nextThoughtNeeded to false only when truly done and a satisfactory" | ||
| 1199 | + " answer is reached"; | ||
| 1200 | + | ||
| 1201 | +/* Emit the tools/list result. */ | ||
| 1202 | +static void mcp_tools_list(FILE *out, const char *id_raw) | ||
| 1203 | +{ | ||
| 1204 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"tools\":[{", id_raw); | ||
| 1205 | + fputs("\"name\":\"sequentialthinking\",\"title\":\"Sequential Thinking\"," | ||
| 1206 | + "\"description\":", out); | ||
| 1207 | + json_escape(out, SEQTHINK_TOOL_DESC); | ||
| 1208 | + fputs(",\"inputSchema\":", out); | ||
| 1209 | + fputs(SEQTHINK_TOOL_SCHEMA, out); | ||
| 1210 | + fputs(",\"outputSchema\":", out); | ||
| 1211 | + fputs(SEQTHINK_TOOL_OUTPUT, out); | ||
| 1212 | + fputs(",\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":false," | ||
| 1213 | + "\"idempotentHint\":false,\"openWorldHint\":false}}]}}\n", out); | ||
| 1214 | + fflush(out); | ||
| 1215 | +} | ||
| 1216 | + | ||
| 1217 | +static void mcp_server_info(FILE *out, const char *id_raw) | ||
| 1218 | +{ | ||
| 1219 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{" | ||
| 1220 | + "\"protocolVersion\":\"2024-11-05\",\"capabilities\":{\"tools\":{}}," | ||
| 1221 | + "\"serverInfo\":{\"name\":\"%s\",\"version\":\"%s\"}}}\n", | ||
| 1222 | + id_raw, PLUGIN_SLUG, PLUGIN_VER); | ||
| 1223 | + fflush(out); | ||
| 1224 | +} | ||
| 1225 | + | ||
| 1226 | +/* Copy the raw JSON-RPC id token (number or string) so the reply echoes the | ||
| 1227 | + * same type. */ | ||
| 1228 | +static int json_id_raw(const char *line, char *out, size_t outsz) | ||
| 1229 | +{ | ||
| 1230 | + const char *p = strstr(line, "\"id\""); | ||
| 1231 | + size_t i = 0; | ||
| 1232 | + if (!p) return 0; | ||
| 1233 | + p += 4; | ||
| 1234 | + while (*p && (unsigned char)*p <= ' ') p++; | ||
| 1235 | + if (*p != ':') return 0; | ||
| 1236 | + p++; | ||
| 1237 | + while (*p && (unsigned char)*p <= ' ') p++; | ||
| 1238 | + if (*p == '"') { | ||
| 1239 | + out[i++] = *p++; | ||
| 1240 | + while (*p && i + 2 < outsz) { | ||
| 1241 | + out[i++] = *p; | ||
| 1242 | + if (*p == '\\' && p[1]) { p++; out[i++] = *p++; } | ||
| 1243 | + else if (*p == '"') { p++; out[i++] = '"'; break; } | ||
| 1244 | + else p++; | ||
| 1245 | + } | ||
| 1246 | + out[i] = '\0'; | ||
| 1247 | + return i > 1; | ||
| 1248 | + } | ||
| 1249 | + while (*p && (isdigit((unsigned char)*p) || *p == '-' || *p == '+') && | ||
| 1250 | + i + 1 < outsz) | ||
| 1251 | + out[i++] = *p++; | ||
| 1252 | + out[i] = '\0'; | ||
| 1253 | + return i > 0; | ||
| 1254 | +} | ||
| 1255 | + | ||
| 1256 | +static void mcp_tool_call(FILE *out, const char *id_raw, yyjson_val *params, | ||
| 1257 | + session_t *sess) | ||
| 1258 | +{ | ||
| 1259 | + yyjson_val *name = NULL, *args = NULL, *v; | ||
| 1260 | + char *text; | ||
| 1261 | + int is_err = 0; | ||
| 1262 | + | ||
| 1263 | + if (params && yyjson_is_obj(params)) { | ||
| 1264 | + name = yyjson_obj_get(params, "name"); | ||
| 1265 | + args = yyjson_obj_get(params, "arguments"); | ||
| 1266 | + } | ||
| 1267 | + if (!name || !yyjson_is_str(name) || !yyjson_get_str(name) || | ||
| 1268 | + strcmp(yyjson_get_str(name), "sequentialthinking") != 0) { | ||
| 1269 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32602," | ||
| 1270 | + "\"message\":\"unknown tool\"}}\n", id_raw); | ||
| 1271 | + fflush(out); | ||
| 1272 | + return; | ||
| 1273 | + } | ||
| 1274 | + (void)v; | ||
| 1275 | + text = process_thought(sess, args, &is_err); | ||
| 1276 | + | ||
| 1277 | + fprintf(out, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{\"content\":" | ||
| 1278 | + "[{\"type\":\"text\",\"text\":", id_raw); | ||
| 1279 | + json_escape(out, text); | ||
| 1280 | + fputs("}],\"structuredContent\":", out); | ||
| 1281 | + if (!is_err) { | ||
| 1282 | + fputs(text, out); /* the five-field object, verbatim */ | ||
| 1283 | + fputs(",\"isError\":false}}\n", out); | ||
| 1284 | + } else { | ||
| 1285 | + fputs(text, out); /* the {error,status} object */ | ||
| 1286 | + fputs(",\"isError\":true}}\n", out); | ||
| 1287 | + } | ||
| 1288 | + fflush(out); | ||
| 1289 | + free(text); | ||
| 1290 | +} | ||
| 1291 | + | ||
| 1292 | +int run_mcp(void) | ||
| 1293 | +{ | ||
| 1294 | + char *line = NULL; | ||
| 1295 | + size_t cap = 0; | ||
| 1296 | + ssize_t len; | ||
| 1297 | + session_t sess; | ||
| 1298 | + | ||
| 1299 | + session_init(&sess); | ||
| 1300 | + setvbuf(stdout, NULL, _IOLBF, 0); | ||
| 1301 | + while ((len = getline(&line, &cap, stdin)) != -1) { | ||
| 1302 | + yyjson_doc *doc; | ||
| 1303 | + yyjson_val *root, *m, *params; | ||
| 1304 | + const char *method; | ||
| 1305 | + char id_raw[128] = ""; | ||
| 1306 | + | ||
| 1307 | + if (len == 0 || !memchr(line, '{', (size_t)len)) continue; | ||
| 1308 | + doc = yyjson_read(line, strlen(line), 0); | ||
| 1309 | + if (!doc) continue; | ||
| 1310 | + root = yyjson_doc_get_root(doc); | ||
| 1311 | + m = yyjson_obj_get(root, "method"); | ||
| 1312 | + method = yyjson_is_str(m) ? yyjson_get_str(m) : NULL; | ||
| 1313 | + params = yyjson_obj_get(root, "params"); | ||
| 1314 | + if (!method) { yyjson_doc_free(doc); continue; } | ||
| 1315 | + if (strncmp(method, "notifications/", 14) == 0) { | ||
| 1316 | + yyjson_doc_free(doc); | ||
| 1317 | + continue; | ||
| 1318 | + } | ||
| 1319 | + if (!json_id_raw(line, id_raw, sizeof id_raw) || !id_raw[0]) { | ||
| 1320 | + yyjson_doc_free(doc); | ||
| 1321 | + continue; | ||
| 1322 | + } | ||
| 1323 | + | ||
| 1324 | + if (strcmp(method, "initialize") == 0) { | ||
| 1325 | + mcp_server_info(stdout, id_raw); | ||
| 1326 | + } else if (strcmp(method, "tools/list") == 0) { | ||
| 1327 | + mcp_tools_list(stdout, id_raw); | ||
| 1328 | + } else if (strcmp(method, "tools/call") == 0) { | ||
| 1329 | + mcp_tool_call(stdout, id_raw, params, &sess); | ||
| 1330 | + } else if (strcmp(method, "ping") == 0) { | ||
| 1331 | + fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":{}}\n", id_raw); | ||
| 1332 | + fflush(stdout); | ||
| 1333 | + } else { | ||
| 1334 | + fprintf(stdout, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":-32601," | ||
| 1335 | + "\"message\":\"method not found\"}}\n", id_raw); | ||
| 1336 | + fflush(stdout); | ||
| 1337 | + } | ||
| 1338 | + yyjson_doc_free(doc); | ||
| 1339 | + } | ||
| 1340 | + free(line); | ||
| 1341 | + session_free(&sess); | ||
| 1342 | + return 0; | ||
| 1343 | +} | ||
| 1344 | + | ||
| 1345 | +/* ------------------------------------------------------------------ */ | ||
| 1346 | +/* Discovery metadata */ | ||
| 1347 | +/* ------------------------------------------------------------------ */ | ||
| 1348 | + | ||
| 1349 | +static int run_meta(void) | ||
| 1350 | +{ | ||
| 1351 | + puts("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"," | ||
| 1352 | + "\"kind\":\"mcp\",\"mcp\":true,\"daemon\":false,\"menus\":false," | ||
| 1353 | + "\"verified\":\"live\"}"); | ||
| 1354 | + fflush(stdout); | ||
| 1355 | + return 0; | ||
| 1356 | +} | ||
| 1357 | + | ||
| 1358 | +/* ------------------------------------------------------------------ */ | ||
| 1359 | +/* JSON node API */ | ||
| 1360 | +/* ------------------------------------------------------------------ */ | ||
| 1361 | + | ||
| 1362 | +static void json_headers(void) | ||
| 1363 | +{ | ||
| 1364 | + fputs("Content-Type: application/json; charset=utf-8\r\n" | ||
| 1365 | + "Cache-Control: no-store\r\n" | ||
| 1366 | + "X-Content-Type-Options: nosniff\r\n\r\n", stdout); | ||
| 1367 | +} | ||
| 1368 | + | ||
| 1369 | +static char *read_body(void) | ||
| 1370 | +{ | ||
| 1371 | + const char *cl = getenv("CONTENT_LENGTH"); | ||
| 1372 | + long n; | ||
| 1373 | + char *buf; | ||
| 1374 | + size_t got = 0; | ||
| 1375 | + if (!cl || !*cl) return NULL; | ||
| 1376 | + n = atol(cl); | ||
| 1377 | + if (n <= 0 || (unsigned long)n > REQ_MAX) return NULL; | ||
| 1378 | + buf = (char *)sx_malloc((size_t)n + 1); | ||
| 1379 | + while (got < (size_t)n) { | ||
| 1380 | + size_t r = fread(buf + got, 1, (size_t)n - got, stdin); | ||
| 1381 | + if (r == 0) break; | ||
| 1382 | + got += r; | ||
| 1383 | + } | ||
| 1384 | + buf[got] = '\0'; | ||
| 1385 | + return buf; | ||
| 1386 | +} | ||
| 1387 | + | ||
| 1388 | +/* Read one field from a JSON body as a string (string/int/bool coerced). */ | ||
| 1389 | +static int json_str_field(const char *json, const char *key, char *out, size_t outsz) | ||
| 1390 | +{ | ||
| 1391 | + yyjson_doc *doc; | ||
| 1392 | + yyjson_val *v; | ||
| 1393 | + int found = 0; | ||
| 1394 | + if (!json) return 0; | ||
| 1395 | + doc = yyjson_read(json, strlen(json), 0); | ||
| 1396 | + if (!doc) return 0; | ||
| 1397 | + v = yyjson_obj_get(yyjson_doc_get_root(doc), key); | ||
| 1398 | + if (yyjson_is_str(v) && yyjson_get_str(v)) { | ||
| 1399 | + snprintf(out, outsz, "%s", yyjson_get_str(v)); | ||
| 1400 | + found = 1; | ||
| 1401 | + } else if (yyjson_is_int(v)) { | ||
| 1402 | + snprintf(out, outsz, "%lld", (long long)yyjson_get_sint(v)); | ||
| 1403 | + found = 1; | ||
| 1404 | + } else if (yyjson_is_bool(v)) { | ||
| 1405 | + snprintf(out, outsz, "%s", yyjson_is_true(v) ? "true" : "false"); | ||
| 1406 | + found = 1; | ||
| 1407 | + } | ||
| 1408 | + yyjson_doc_free(doc); | ||
| 1409 | + return found; | ||
| 1410 | +} | ||
| 1411 | + | ||
| 1412 | +static void api_err(const char *msg) | ||
| 1413 | +{ | ||
| 1414 | + json_headers(); | ||
| 1415 | + fputs("{\"ok\":false,\"error\":", stdout); | ||
| 1416 | + json_escape(stdout, msg ? msg : "error"); | ||
| 1417 | + fputs("}\n", stdout); | ||
| 1418 | +} | ||
| 1419 | + | ||
| 1420 | +static void api_info(void) | ||
| 1421 | +{ | ||
| 1422 | + char dir[1000]; | ||
| 1423 | + state_dir(dir, sizeof dir); | ||
| 1424 | + json_headers(); | ||
| 1425 | + fputs("{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"slug\":\"" PLUGIN_SLUG | ||
| 1426 | + "\",\"version\":\"" PLUGIN_VER "\",\"kind\":\"mcp\",\"mcp\":true," | ||
| 1427 | + "\"daemon\":false,\"menus\":false,\"verified\":\"live\"," | ||
| 1428 | + "\"tools\":[\"sequentialthinking\"],\"tool_schema\":", stdout); | ||
| 1429 | + fputs(SEQTHINK_TOOL_SCHEMA, stdout); | ||
| 1430 | + fputs(",\"tool_output_schema\":", stdout); | ||
| 1431 | + fputs(SEQTHINK_TOOL_OUTPUT, stdout); | ||
| 1432 | + fputs(",\"state_dir\":", stdout); | ||
| 1433 | + json_escape(stdout, dir); /* json_escape emits its own quotes (bu) */ | ||
| 1434 | + fputs(",\"max_chains\":", stdout); | ||
| 1435 | + fprintf(stdout, "%d,\"max_thoughts_each\":%d," | ||
| 1436 | + "\"max_thought_history\":%lld}\n", | ||
| 1437 | + MAX_CHAINS, MAX_THOUGHTS_EACH, read_max_history()); | ||
| 1438 | +} | ||
| 1439 | + | ||
| 1440 | +/* Load chains.json (or an empty doc). Caller frees doc. */ | ||
| 1441 | +static yyjson_doc *load_chains(void) | ||
| 1442 | +{ | ||
| 1443 | + char path[1200]; | ||
| 1444 | + char *txt; | ||
| 1445 | + size_t len = 0; | ||
| 1446 | + yyjson_doc *doc; | ||
| 1447 | + chains_path(path, sizeof path); | ||
| 1448 | + (void)len; | ||
| 1449 | + txt = read_file(path, &len); | ||
| 1450 | + if (txt) { | ||
| 1451 | + doc = yyjson_read(txt, strlen(txt), 0); | ||
| 1452 | + free(txt); | ||
| 1453 | + } else { | ||
| 1454 | + doc = yyjson_read("{\"chains\":[]}", 13, 0); | ||
| 1455 | + } | ||
| 1456 | + return doc; | ||
| 1457 | +} | ||
| 1458 | + | ||
| 1459 | +static void api_chains(void) | ||
| 1460 | +{ | ||
| 1461 | + yyjson_doc *doc = load_chains(); | ||
| 1462 | + yyjson_val *root, *chains; | ||
| 1463 | + buf_t b; | ||
| 1464 | + size_t i, n = 0, total = 0; | ||
| 1465 | + | ||
| 1466 | + if (!doc) { api_err("state unreadable"); return; } | ||
| 1467 | + root = yyjson_doc_get_root(doc); | ||
| 1468 | + chains = yyjson_is_obj(root) ? yyjson_obj_get(root, "chains") : NULL; | ||
| 1469 | + if (yyjson_is_arr(chains)) n = yyjson_arr_size(chains); | ||
| 1470 | + | ||
| 1471 | + buf_init(&b); | ||
| 1472 | + buf_addf(&b, "{\"ok\":true,\"plugin\":\"" PLUGIN_ID "\",\"count\":%zu,", n); | ||
| 1473 | + { | ||
| 1474 | + char nm[128]; | ||
| 1475 | + state_dir_name(nm, sizeof nm); | ||
| 1476 | + buf_str(&b, "\"state_dir_name\":"); | ||
| 1477 | + json_escape_buf(&b, nm); | ||
| 1478 | + } | ||
| 1479 | + buf_str(&b, ",\"chains\":["); | ||
| 1480 | + for (i = 0; i < n; i++) { | ||
| 1481 | + yyjson_val *c = yyjson_arr_get(chains, i); | ||
| 1482 | + yyjson_val *v, *ths; | ||
| 1483 | + size_t cnt = 0; | ||
| 1484 | + const char *last = ""; | ||
| 1485 | + if (!yyjson_is_obj(c)) continue; | ||
| 1486 | + ths = yyjson_obj_get(c, "thoughts"); | ||
| 1487 | + if (yyjson_is_arr(ths)) cnt = yyjson_arr_size(ths); | ||
| 1488 | + total += cnt; | ||
| 1489 | + if (cnt) { | ||
| 1490 | + yyjson_val *lt = yyjson_arr_get_last(ths); | ||
| 1491 | + if (yyjson_is_obj(lt)) { | ||
| 1492 | + v = yyjson_obj_get(lt, "thought"); | ||
| 1493 | + if (yyjson_is_str(v) && yyjson_get_str(v)) last = yyjson_get_str(v); | ||
| 1494 | + } | ||
| 1495 | + } | ||
| 1496 | + if (i) buf_str(&b, ","); | ||
| 1497 | + buf_str(&b, "{\"id\":"); | ||
| 1498 | + v = yyjson_obj_get(c, "id"); | ||
| 1499 | + if (yyjson_is_str(v)) json_escape_buf(&b, yyjson_get_str(v)); | ||
| 1500 | + else buf_str(&b, "\"\""); | ||
| 1501 | + v = yyjson_obj_get(c, "started_at"); | ||
| 1502 | + buf_addf(&b, ",\"started_at\":%lld,", | ||
| 1503 | + yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0LL); | ||
| 1504 | + v = yyjson_obj_get(c, "updated_at"); | ||
| 1505 | + buf_addf(&b, "\"updated_at\":%lld,", | ||
| 1506 | + yyjson_is_int(v) ? (long long)yyjson_get_sint(v) : 0LL); | ||
| 1507 | + buf_addf(&b, "\"thoughts\":%zu,", cnt); | ||
| 1508 | + buf_str(&b, "\"branches\":["); | ||
| 1509 | + { | ||
| 1510 | + yyjson_val *brs = yyjson_obj_get(c, "branches"); | ||
| 1511 | + if (yyjson_is_arr(brs)) { | ||
| 1512 | + size_t j, bn = yyjson_arr_size(brs); | ||
| 1513 | + for (j = 0; j < bn; j++) { | ||
| 1514 | + yyjson_val *bv = yyjson_arr_get(brs, j); | ||
| 1515 | + if (j) buf_str(&b, ","); | ||
| 1516 | + if (yyjson_is_str(bv)) json_escape_buf(&b, yyjson_get_str(bv)); | ||
| 1517 | + else buf_str(&b, "\"\""); | ||
| 1518 | + } | ||
| 1519 | + } | ||
| 1520 | + } | ||
| 1521 | + buf_str(&b, "],\"last_head\":"); | ||
| 1522 | + { /* first line of the last thought, clamped to 160 bytes */ | ||
| 1523 | + char head[200]; | ||
| 1524 | + size_t k = 0; | ||
| 1525 | + for (; last[k] && k < 160 && last[k] != '\n'; k++) head[k] = last[k]; | ||
| 1526 | + head[k] = '\0'; | ||
| 1527 | + json_escape_buf(&b, head); | ||
| 1528 | + } | ||
| 1529 | + buf_addf(&b, ",\"truncated\":%s}", cnt >= MAX_THOUGHTS_EACH ? "true" : "false"); | ||
| 1530 | + } | ||
| 1531 | + buf_str(&b, "]}"); | ||
| 1532 | + (void)total; | ||
| 1533 | + json_headers(); | ||
| 1534 | + if (b.p) fwrite(b.p, 1, b.n, stdout); | ||
| 1535 | + fputc('\n', stdout); | ||
| 1536 | + buf_free(&b); | ||
| 1537 | + yyjson_doc_free(doc); | ||
| 1538 | +} | ||
| 1539 | + | ||
| 1540 | +static int valid_chain_id(const char *id) | ||
| 1541 | +{ | ||
| 1542 | + size_t i; | ||
| 1543 | + if (!id || !*id || strlen(id) > 64) return 0; | ||
| 1544 | + for (i = 0; id[i]; i++) | ||
| 1545 | + if (!(isalnum((unsigned char)id[i]) || id[i] == '-' || id[i] == '_')) | ||
| 1546 | + return 0; | ||
| 1547 | + return 1; | ||
| 1548 | +} | ||
| 1549 | + | ||
| 1550 | +static void api_chain(const char *id) | ||
| 1551 | +{ | ||
| 1552 | + yyjson_doc *doc; | ||
| 1553 | + yyjson_val *root, *chains, *c = NULL; | ||
| 1554 | + size_t i, n; | ||
| 1555 | + | ||
| 1556 | + if (!valid_chain_id(id)) { api_err("invalid chain id"); return; } | ||
| 1557 | + doc = load_chains(); | ||
| 1558 | + if (!doc) { api_err("state unreadable"); return; } | ||
| 1559 | + root = yyjson_doc_get_root(doc); | ||
| 1560 | + chains = yyjson_is_obj(root) ? yyjson_obj_get(root, "chains") : NULL; | ||
| 1561 | + if (yyjson_is_arr(chains)) { | ||
| 1562 | + n = yyjson_arr_size(chains); | ||
| 1563 | + for (i = 0; i < n; i++) { | ||
| 1564 | + yyjson_val *cv = yyjson_arr_get(chains, i); | ||
| 1565 | + yyjson_val *v = yyjson_is_obj(cv) ? yyjson_obj_get(cv, "id") : NULL; | ||
| 1566 | + if (yyjson_is_str(v) && yyjson_get_str(v) && | ||
| 1567 | + strcmp(yyjson_get_str(v), id) == 0) { c = cv; break; } | ||
| 1568 | + } | ||
| 1569 | + } | ||
| 1570 | + if (!c) { | ||
| 1571 | + yyjson_doc_free(doc); | ||
| 1572 | + api_err("chain not found"); | ||
| 1573 | + return; | ||
| 1574 | + } | ||
| 1575 | + { | ||
| 1576 | + char *txt = yyjson_val_write(c, 0, NULL); | ||
| 1577 | + json_headers(); | ||
| 1578 | + if (txt) { | ||
| 1579 | + char *obj = txt; | ||
| 1580 | + fputs("{\"ok\":true,", stdout); | ||
| 1581 | + fputs(obj + 1, stdout); /* drop the object's leading { */ | ||
| 1582 | + fputs("\n", stdout); | ||
| 1583 | + free(txt); | ||
| 1584 | + } else { | ||
| 1585 | + fputs("{\"ok\":false,\"error\":\"serialize failed\"}\n", stdout); | ||
| 1586 | + } | ||
| 1587 | + } | ||
| 1588 | + yyjson_doc_free(doc); | ||
| 1589 | +} | ||
| 1590 | + | ||
| 1591 | +static void api_stats(void) | ||
| 1592 | +{ | ||
| 1593 | + yyjson_doc *doc = load_chains(); | ||
| 1594 | + yyjson_val *root, *chains; | ||
| 1595 | + size_t i, n = 0, thoughts = 0, branches = 0, revs = 0; | ||
| 1596 | + long long newest = 0; | ||
| 1597 | + | ||
| 1598 | + if (!doc) { api_err("state unreadable"); return; } | ||
| 1599 | + root = yyjson_doc_get_root(doc); | ||
| 1600 | + chains = yyjson_is_obj(root) ? yyjson_obj_get(root, "chains") : NULL; | ||
| 1601 | + if (yyjson_is_arr(chains)) { | ||
| 1602 | + n = yyjson_arr_size(chains); | ||
| 1603 | + for (i = 0; i < n; i++) { | ||
| 1604 | + yyjson_val *c = yyjson_arr_get(chains, i); | ||
| 1605 | + yyjson_val *ths, *brs, *ua; | ||
| 1606 | + size_t j, tn; | ||
| 1607 | + if (!yyjson_is_obj(c)) continue; | ||
| 1608 | + ua = yyjson_obj_get(c, "updated_at"); | ||
| 1609 | + if (yyjson_is_int(ua) && yyjson_get_sint(ua) > newest) | ||
| 1610 | + newest = (long long)yyjson_get_sint(ua); | ||
| 1611 | + brs = yyjson_obj_get(c, "branches"); | ||
| 1612 | + if (yyjson_is_arr(brs)) branches += yyjson_arr_size(brs); | ||
| 1613 | + ths = yyjson_obj_get(c, "thoughts"); | ||
| 1614 | + if (!yyjson_is_arr(ths)) continue; | ||
| 1615 | + tn = yyjson_arr_size(ths); | ||
| 1616 | + thoughts += tn; | ||
| 1617 | + for (j = 0; j < tn; j++) { | ||
| 1618 | + yyjson_val *tv = yyjson_arr_get(ths, j); | ||
| 1619 | + if (yyjson_is_obj(tv) && | ||
| 1620 | + yyjson_is_true(yyjson_obj_get(tv, "is_revision"))) | ||
| 1621 | + revs++; | ||
| 1622 | + } | ||
| 1623 | + } | ||
| 1624 | + } | ||
| 1625 | + json_headers(); | ||
| 1626 | + fprintf(stdout, "{\"ok\":true,\"chains\":%zu,\"thoughts\":%zu," | ||
| 1627 | + "\"branches\":%zu,\"revisions\":%zu," | ||
| 1628 | + "\"last_activity\":%lld,\"max_chains\":%d," | ||
| 1629 | + "\"max_thoughts_each\":%d,\"max_thought_history\":%lld}\n", | ||
| 1630 | + n, thoughts, branches, revs, newest, MAX_CHAINS, MAX_THOUGHTS_EACH, | ||
| 1631 | + read_max_history()); | ||
| 1632 | + yyjson_doc_free(doc); | ||
| 1633 | +} | ||
| 1634 | + | ||
| 1635 | +static void api_clear(void) | ||
| 1636 | +{ | ||
| 1637 | + char path[1200]; | ||
| 1638 | + chains_path(path, sizeof path); | ||
| 1639 | + if (remove(path) != 0 && errno != ENOENT) { | ||
| 1640 | +#ifdef _WIN32 | ||
| 1641 | + /* Windows remove() fails on read-only files; try clearing the bit. */ | ||
| 1642 | + { | ||
| 1643 | + DWORD a = GetFileAttributesA(path); | ||
| 1644 | + if (a != INVALID_FILE_ATTRIBUTES) { | ||
| 1645 | + SetFileAttributesA(path, FILE_ATTRIBUTE_NORMAL); | ||
| 1646 | + if (remove(path) != 0) { api_err("remove failed"); return; } | ||
| 1647 | + } else { | ||
| 1648 | + api_err("remove failed"); | ||
| 1649 | + return; | ||
| 1650 | + } | ||
| 1651 | + } | ||
| 1652 | +#else | ||
| 1653 | + api_err("remove failed"); | ||
| 1654 | + return; | ||
| 1655 | +#endif | ||
| 1656 | + } | ||
| 1657 | + json_headers(); | ||
| 1658 | + fputs("{\"ok\":true,\"cleared\":true}\n", stdout); | ||
| 1659 | +} | ||
| 1660 | + | ||
| 1661 | +static int api_dispatch(const char *action, const char *qs, const char *body) | ||
| 1662 | +{ | ||
| 1663 | + char id[96] = ""; | ||
| 1664 | + | ||
| 1665 | + if (!action[0] || strcmp(action, "chains") == 0) { | ||
| 1666 | + api_chains(); | ||
| 1667 | + return 0; | ||
| 1668 | + } | ||
| 1669 | + if (strcmp(action, "chain") == 0) { | ||
| 1670 | + if (!(body && json_str_field(body, "id", id, sizeof id)) && | ||
| 1671 | + !(qs && *qs && get_query_val(qs, "id", id, sizeof id))) | ||
| 1672 | + id[0] = '\0'; | ||
| 1673 | + api_chain(id); | ||
| 1674 | + return 0; | ||
| 1675 | + } | ||
| 1676 | + if (strcmp(action, "stats") == 0) { api_stats(); return 0; } | ||
| 1677 | + if (strcmp(action, "info") == 0) { api_info(); return 0; } | ||
| 1678 | + if (strcmp(action, "clear") == 0) { | ||
| 1679 | + char cf[16] = ""; | ||
| 1680 | + if (!(body && json_str_field(body, "confirm", cf, sizeof cf))) | ||
| 1681 | + if (qs && *qs) get_query_val(qs, "confirm", cf, sizeof cf); | ||
| 1682 | + if (strcmp(cf, "1") != 0 && strcmp(cf, "true") != 0) { | ||
| 1683 | + api_err("confirm=1 required"); | ||
| 1684 | + return 0; | ||
| 1685 | + } | ||
| 1686 | + api_clear(); | ||
| 1687 | + return 0; | ||
| 1688 | + } | ||
| 1689 | + api_err("unknown action"); | ||
| 1690 | + return 0; | ||
| 1691 | +} | ||
| 1692 | + | ||
| 1693 | +/* ------------------------------------------------------------------ */ | ||
| 1694 | +/* HTML mode */ | ||
| 1695 | +/* ------------------------------------------------------------------ */ | ||
| 1696 | + | ||
| 1697 | +static void emit_ui(void) | ||
| 1698 | +{ | ||
| 1699 | + const char *p = UI_HTML; | ||
| 1700 | + while (*p) { | ||
| 1701 | + if (*p == '\001') { | ||
| 1702 | + fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS "</style>", | ||
| 1703 | + stdout); | ||
| 1704 | + p++; | ||
| 1705 | + } else if (*p == '\002') { | ||
| 1706 | + fputs(SX_BOT_THEME_HANDOFF, stdout); | ||
| 1707 | + p++; | ||
| 1708 | + } else { | ||
| 1709 | + putchar(*p++); | ||
| 1710 | + } | ||
| 1711 | + } | ||
| 1712 | +} | ||
| 1713 | + | ||
| 1714 | +static void mode_html(void) | ||
| 1715 | +{ | ||
| 1716 | + fputs("Content-Type: text/html; charset=utf-8\r\n" | ||
| 1717 | + "Cache-Control: no-store\r\n" | ||
| 1718 | + "X-Content-Type-Options: nosniff\r\n" | ||
| 1719 | + "X-Frame-Options: SAMEORIGIN\r\n" | ||
| 1720 | + "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " | ||
| 1721 | + "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; " | ||
| 1722 | + "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); | ||
| 1723 | + emit_ui(); | ||
| 1724 | +} | ||
| 1725 | + | ||
| 1726 | +/* ------------------------------------------------------------------ */ | ||
| 1727 | +/* main */ | ||
| 1728 | +/* ------------------------------------------------------------------ */ | ||
| 1729 | + | ||
| 1730 | +int main(int argc, char **argv) | ||
| 1731 | +{ | ||
| 1732 | + const char *qs; | ||
| 1733 | + char action[64] = ""; | ||
| 1734 | + char *body = NULL; | ||
| 1735 | + int have_action = 0; | ||
| 1736 | + const char *rm; | ||
| 1737 | + int is_post; | ||
| 1738 | + | ||
| 1739 | +#if defined(_WIN32) | ||
| 1740 | + { /* MinGW text-mode stdout turns our CRLF into CRCRLF and breaks CGI | ||
| 1741 | + * framing - force binary stdio. */ | ||
| 1742 | + _setmode(_fileno(stdout), _O_BINARY); | ||
| 1743 | + _setmode(_fileno(stdin), _O_BINARY); | ||
| 1744 | + _setmode(_fileno(stderr), _O_BINARY); | ||
| 1745 | + } | ||
| 1746 | +#endif | ||
| 1747 | + | ||
| 1748 | + /* 1. Discovery metadata (unauthenticated so /plugins can probe it) */ | ||
| 1749 | + if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) | ||
| 1750 | + return run_meta(); | ||
| 1751 | + /* 2. MCP stdio server */ | ||
| 1752 | + if (argc > 1 && strcmp(argv[1], "--mcp") == 0) return run_mcp(); | ||
| 1753 | + if (argc > 1 && strcmp(argv[1], "--schema") == 0) { | ||
| 1754 | + puts(SEQTHINK_TOOL_SCHEMA); | ||
| 1755 | + return 0; | ||
| 1756 | + } | ||
| 1757 | + if (argc > 1 && strcmp(argv[1], "--version") == 0) { | ||
| 1758 | + printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); | ||
| 1759 | + return 0; | ||
| 1760 | + } | ||
| 1761 | + | ||
| 1762 | + qs = getenv("QUERY_STRING"); | ||
| 1763 | + if (!qs) qs = ""; | ||
| 1764 | + | ||
| 1765 | + have_action = get_query_val(qs, "action", action, sizeof action); | ||
| 1766 | + if (!have_action && strstr(qs, "format=json")) { | ||
| 1767 | + const char *fm = strstr(qs, "format=json"); | ||
| 1768 | + if (fm[11] == '\0' || fm[11] == '&') { | ||
| 1769 | + snprintf(action, sizeof action, "chains"); | ||
| 1770 | + have_action = 1; | ||
| 1771 | + } | ||
| 1772 | + } | ||
| 1773 | + | ||
| 1774 | + rm = getenv("REQUEST_METHOD"); | ||
| 1775 | + is_post = rm && strcmp(rm, "POST") == 0; | ||
| 1776 | + | ||
| 1777 | + if (have_action || is_post) { | ||
| 1778 | + require_node_auth(); | ||
| 1779 | + body = read_body(); | ||
| 1780 | + if (body) { | ||
| 1781 | + char jact[64] = ""; | ||
| 1782 | + if (json_str_field(body, "action", jact, sizeof jact) && jact[0]) | ||
| 1783 | + snprintf(action, sizeof action, "%s", jact); | ||
| 1784 | + else if (!action[0]) | ||
| 1785 | + snprintf(action, sizeof action, "chains"); | ||
| 1786 | + } else if (!action[0]) { | ||
| 1787 | + snprintf(action, sizeof action, "chains"); | ||
| 1788 | + } | ||
| 1789 | + { | ||
| 1790 | + int rc = api_dispatch(action, qs, body); | ||
| 1791 | + free(body); | ||
| 1792 | + return rc; | ||
| 1793 | + } | ||
| 1794 | + } | ||
| 1795 | + | ||
| 1796 | + mode_html(); | ||
| 1797 | + return 0; | ||
| 1798 | +} |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..92341a9 | index 0000000..92341a9 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui.html | +++ b/src/ui.html | ||
| @@ -0,0 +1,247 @@ | @@ -0,0 +1,247 @@ | ||
| 1 | +<!DOCTYPE html> | ||
| 2 | +<html> | ||
| 3 | +<head> | ||
| 4 | +<meta charset="utf-8"> | ||
| 5 | +<meta name="viewport" content="width=device-width,initial-scale=1"> | ||
| 6 | +<title>Thought Chains</title> | ||
| 7 | +<!--TOKENS--> | ||
| 8 | +<style> | ||
| 9 | +*{box-sizing:border-box} | ||
| 10 | +html,body{margin:0;padding:0} | ||
| 11 | +body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;line-height:1.5} | ||
| 12 | +.wrap{max-width:1180px;margin:0 auto;padding:14px} | ||
| 13 | +header{display:flex;flex-wrap:wrap;align-items:center;gap:10px;margin-bottom:12px} | ||
| 14 | +header h1{font-size:17px;margin:0;font-weight:700;letter-spacing:-.01em} | ||
| 15 | +.chip{font-size:11px;color:var(--text-2);border:1px solid var(--line);border-radius:980px;padding:2px 10px;background:var(--bg-card)} | ||
| 16 | +.chip b{color:var(--text);font-weight:600} | ||
| 17 | +.spacer{flex:1} | ||
| 18 | +button{background:var(--surface-2);color:var(--text);border:1px solid var(--line);border-radius:980px;padding:6px 14px;font:inherit;font-size:13px;font-weight:600;cursor:pointer} | ||
| 19 | +button:hover{border-color:var(--line-2)} | ||
| 20 | +button.danger{color:var(--red)} | ||
| 21 | +button.primary{background:var(--blue);border-color:var(--blue);color:#fff} | ||
| 22 | +.grid{display:grid;grid-template-columns:330px 1fr;gap:14px;align-items:start} | ||
| 23 | +.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;overflow:hidden} | ||
| 24 | +.card h2{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--text-2);margin:0;padding:10px 14px;border-bottom:1px solid var(--line);font-weight:600} | ||
| 25 | +ul.chains{list-style:none;margin:0;padding:6px;max-height:70vh;overflow:auto} | ||
| 26 | +ul.chains li{padding:9px 10px;border-radius:10px;cursor:pointer;border:1px solid transparent} | ||
| 27 | +ul.chains li:hover{background:var(--surface-hover)} | ||
| 28 | +ul.chains li.sel{background:var(--surface-2);border-color:var(--line-2)} | ||
| 29 | +.cl-top{display:flex;align-items:baseline;gap:8px} | ||
| 30 | +.cl-id{font-family:var(--mono);font-size:12px;color:var(--blue);font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} | ||
| 31 | +.cl-when{font-size:11px;color:var(--text-2);margin-left:auto;white-space:nowrap} | ||
| 32 | +.cl-last{font-size:12px;color:var(--text-2);margin-top:3px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden} | ||
| 33 | +.cl-meta{display:flex;gap:6px;margin-top:6px;flex-wrap:wrap} | ||
| 34 | +.pill{font-size:10px;font-weight:700;border-radius:980px;padding:1px 8px;border:1px solid var(--line);color:var(--text-2)} | ||
| 35 | +.pill.b{color:var(--green);border-color:var(--green)} | ||
| 36 | +.pill.t{color:var(--teal);border-color:var(--teal)} | ||
| 37 | +.detail .empty{padding:36px 20px;text-align:center;color:var(--text-2)} | ||
| 38 | +.detail .empty code{font-family:var(--mono);color:var(--text)} | ||
| 39 | +.dhead{padding:12px 16px;border-bottom:1px solid var(--line);display:flex;flex-wrap:wrap;gap:10px;align-items:center} | ||
| 40 | +.dhead .did{font-family:var(--mono);font-weight:700;color:var(--blue)} | ||
| 41 | +.prog{flex:1;min-width:120px;max-width:280px;height:6px;border-radius:3px;background:var(--surface-2);overflow:hidden} | ||
| 42 | +.prog i{display:block;height:100%;background:var(--blue);border-radius:3px} | ||
| 43 | +.tl{list-style:none;margin:0;padding:14px 16px 18px 16px;position:relative} | ||
| 44 | +.tl li{position:relative;padding:0 0 16px 30px} | ||
| 45 | +.tl li::before{content:"";position:absolute;left:8px;top:18px;bottom:-2px;width:2px;background:var(--line)} | ||
| 46 | +.tl li:last-child::before{display:none} | ||
| 47 | +.tl .dot{position:absolute;left:2px;top:4px;width:14px;height:14px;border-radius:50%;border:3px solid var(--bg-card);background:var(--blue)} | ||
| 48 | +.tl li.rev .dot{background:var(--orange)} | ||
| 49 | +.tl li.br .dot{background:var(--green)} | ||
| 50 | +.th-head{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:4px} | ||
| 51 | +.th-num{font-weight:700;font-size:13px} | ||
| 52 | +.badge{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;border-radius:980px;padding:1px 8px} | ||
| 53 | +.badge.rev{color:var(--orange);border:1px solid var(--orange)} | ||
| 54 | +.badge.br{color:var(--green);border:1px solid var(--green)} | ||
| 55 | +.badge.fin{color:var(--purple);border:1px solid var(--purple)} | ||
| 56 | +.th-more{font-size:11px;color:var(--text-2)} | ||
| 57 | +.th-body{white-space:pre-wrap;word-wrap:break-word;font-size:13.5px;background:var(--surface-2);border:1px solid var(--line);border-radius:10px;padding:9px 12px;margin-top:2px} | ||
| 58 | +.jsonwrap{margin-top:14px} | ||
| 59 | +.jsonwrap pre{background:var(--code-bg);border:1px solid var(--line);border-radius:12px;padding:12px;font-family:var(--mono);font-size:11.5px;overflow:auto;max-height:340px;margin:8px 0 0} | ||
| 60 | +.errbox{margin:12px 16px;padding:10px 12px;border:1px solid var(--red);border-radius:10px;color:var(--red);font-size:13px} | ||
| 61 | +#backBtn{display:none} | ||
| 62 | +@media (max-width:860px){ | ||
| 63 | + .grid{grid-template-columns:1fr} | ||
| 64 | + body[data-view=detail] #listCard{display:none} | ||
| 65 | + body:not([data-view=detail]) .tlwrap{display:none} | ||
| 66 | + body:not([data-view=detail]) .dhead{display:none} | ||
| 67 | + body[data-view=detail] #backBtn{display:inline-block} | ||
| 68 | +} | ||
| 69 | +</style> | ||
| 70 | +</head> | ||
| 71 | +<body> | ||
| 72 | +<div class="wrap"> | ||
| 73 | + <header> | ||
| 74 | + <button id="backBtn" type="button">Back</button> | ||
| 75 | + <h1>Thought Chains</h1> | ||
| 76 | + <span class="chip" id="chipChains">chains <b>-</b></span> | ||
| 77 | + <span class="chip" id="chipThoughts">thoughts <b>-</b></span> | ||
| 78 | + <span class="chip" id="chipState">state <b>-</b></span> | ||
| 79 | + <span class="spacer"></span> | ||
| 80 | + <button id="refreshBtn" type="button">Refresh</button> | ||
| 81 | + <button id="clearBtn" type="button" class="danger">Clear</button> | ||
| 82 | + <button class="embed-hide" id="themeToggle" type="button" title="Toggle appearance">Theme</button> | ||
| 83 | + </header> | ||
| 84 | + | ||
| 85 | + <div class="grid"> | ||
| 86 | + <div class="card" id="listCard"> | ||
| 87 | + <h2>Chains</h2> | ||
| 88 | + <ul class="chains" id="chains"></ul> | ||
| 89 | + </div> | ||
| 90 | + | ||
| 91 | + <div class="card"> | ||
| 92 | + <div class="dhead" id="dhead" style="display:none"> | ||
| 93 | + <button id="backBtn2" type="button">Back</button> | ||
| 94 | + <span class="did" id="dId"></span> | ||
| 95 | + <span class="chip" id="dCount"></span> | ||
| 96 | + <div class="prog"><i id="dProg" style="width:0%"></i></div> | ||
| 97 | + </div> | ||
| 98 | + <div class="tlwrap"> | ||
| 99 | + <div class="empty" id="empty">Loading...</div> | ||
| 100 | + <ul class="tl" id="tl"></ul> | ||
| 101 | + </div> | ||
| 102 | + <div id="errbox" class="errbox" style="display:none"></div> | ||
| 103 | + <div class="jsonwrap" style="padding:0 16px 14px"> | ||
| 104 | + <button id="jsonBtn" type="button">Show JSON</button> | ||
| 105 | + <pre id="json" style="display:none"></pre> | ||
| 106 | + </div> | ||
| 107 | + </div> | ||
| 108 | + </div> | ||
| 109 | +</div> | ||
| 110 | +<script> | ||
| 111 | +(function(){ | ||
| 112 | + var q=new URLSearchParams(location.search); | ||
| 113 | + var HUB=q.get('plugin')||''; | ||
| 114 | + var node=q.get('node')||''; | ||
| 115 | + var sid=q.get('id')||''; | ||
| 116 | + var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||localStorage.getItem('bot_active_pwd')||''; | ||
| 117 | + var cur=null, lastJson=''; | ||
| 118 | + | ||
| 119 | + function api(action,extra){ | ||
| 120 | + /* Hub-proxy route when served through /plugins?plugin=..., direct node | ||
| 121 | + route when opened as /plugin_seqthink. Never call /plugins?plugin= on | ||
| 122 | + the node itself: that is discovery and never dispatches. */ | ||
| 123 | + var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB)+'&action='+action | ||
| 124 | + :'/plugin_seqthink?action='+action); | ||
| 125 | + if(extra)u+='&'+extra; | ||
| 126 | + if(node)u+='&node='+encodeURIComponent(node); | ||
| 127 | + if(sid)u+='&id='+encodeURIComponent(sid); | ||
| 128 | + if(pwd)u+='&pwd='+encodeURIComponent(pwd); | ||
| 129 | + return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{}}).then(function(r){return r.json();}); | ||
| 130 | + } | ||
| 131 | + function esc(s){return String(s==null?'':s).replace(/[&<>"]/g,function(c){ | ||
| 132 | + return {'&':'&','<':'<','>':'>','"':'"'}[c];});} | ||
| 133 | + function fmt(ts){if(!ts)return '-';try{return new Date(ts*1000).toLocaleString();}catch(e){return String(ts);}} | ||
| 134 | + function showErr(m){var e=document.getElementById('errbox');e.textContent=m;e.style.display='block';} | ||
| 135 | + function clearErr(){document.getElementById('errbox').style.display='none';} | ||
| 136 | + function setJson(o){lastJson=JSON.stringify(o,null,2);var j=document.getElementById('json');j.textContent=lastJson;} | ||
| 137 | + | ||
| 138 | + function renderList(d){ | ||
| 139 | + var ul=document.getElementById('chains'); | ||
| 140 | + var cs=(d&&d.chains)||[]; | ||
| 141 | + document.getElementById('chipChains').innerHTML='chains <b>'+((d&&d.count!=null)?d.count:cs.length)+'</b>'; | ||
| 142 | + var tot=0;cs.forEach(function(c){tot+=c.thoughts||0;}); | ||
| 143 | + document.getElementById('chipThoughts').innerHTML='thoughts <b>'+tot+'</b>'; | ||
| 144 | + document.getElementById('chipState').innerHTML='state <b>'+esc((d&&d.state_dir_name)||'-')+'</b>'; | ||
| 145 | + ul.innerHTML=''; | ||
| 146 | + if(!cs.length){ | ||
| 147 | + if(!cur)document.getElementById('empty').innerHTML= | ||
| 148 | + 'No thought chains recorded yet.<br>Call the <code>sequentialthinking</code> MCP tool '+ | ||
| 149 | + '(<code>plugin_seqthink --mcp</code>) and press Refresh.'; | ||
| 150 | + return; | ||
| 151 | + } | ||
| 152 | + cs.forEach(function(c){ | ||
| 153 | + var li=document.createElement('li'); | ||
| 154 | + if(c.id===cur)li.className='sel'; | ||
| 155 | + var badges='<span class="pill t">thoughts '+esc(c.thoughts)+'</span>'; | ||
| 156 | + if(c.branches&&c.branches.length)badges+='<span class="pill b">branches '+c.branches.length+'</span>'; | ||
| 157 | + if(c.truncated)badges+='<span class="pill">capped</span>'; | ||
| 158 | + li.innerHTML='<div class="cl-top"><span class="cl-id">'+esc(c.id)+'</span>'+ | ||
| 159 | + '<span class="cl-when">'+esc(fmt(c.updated_at))+'</span></div>'+ | ||
| 160 | + '<div class="cl-last">'+esc(c.last_head||'')+'</div>'+ | ||
| 161 | + '<div class="cl-meta">'+badges+'</div>'; | ||
| 162 | + li.onclick=function(){open(c.id);}; | ||
| 163 | + ul.appendChild(li); | ||
| 164 | + }); | ||
| 165 | + } | ||
| 166 | + | ||
| 167 | + function renderDetail(d){ | ||
| 168 | + var tl=document.getElementById('tl'); | ||
| 169 | + var th=(d&&d.thoughts)||[]; | ||
| 170 | + document.getElementById('dhead').style.display=th.length?'flex':'none'; | ||
| 171 | + document.getElementById('dId').textContent=(d&&d.id)||''; | ||
| 172 | + var last=th.length?th[th.length-1]:null; | ||
| 173 | + var tt=last?(last.total_thoughts||0):0, tn=last?(last.thought_number||0):0; | ||
| 174 | + document.getElementById('dCount').textContent=th.length+' thoughts'; | ||
| 175 | + document.getElementById('dProg').style.width=(tt>0?Math.min(100,Math.round(100*tn/tt)):0)+'%'; | ||
| 176 | + document.getElementById('empty').style.display=th.length?'none':'block'; | ||
| 177 | + if(!th.length&&!document.getElementById('empty').textContent.trim()) | ||
| 178 | + document.getElementById('empty').textContent='No thoughts in this chain.'; | ||
| 179 | + tl.innerHTML=''; | ||
| 180 | + th.forEach(function(t){ | ||
| 181 | + var li=document.createElement('li'); | ||
| 182 | + var cls=t.is_revision?'rev':(t.branch_from?'br':''); | ||
| 183 | + if(cls)li.className=cls; | ||
| 184 | + var badges='<span class="th-num">#'+esc(t.thought_number)+' / '+esc(t.total_thoughts)+'</span>'; | ||
| 185 | + if(t.is_revision)badges+='<span class="badge rev">revision'+(t.revises?' of #'+esc(t.revises):'')+'</span>'; | ||
| 186 | + if(t.branch_from)badges+='<span class="badge br">branch from #'+esc(t.branch_from)+ | ||
| 187 | + (t.branch_id?' · '+esc(t.branch_id):'')+'</span>'; | ||
| 188 | + if(!t.next_needed)badges+='<span class="badge fin">final</span>'; | ||
| 189 | + var more=''; | ||
| 190 | + if(t.needs_more)more=' <span class="th-more">needs more thoughts</span>'; | ||
| 191 | + li.innerHTML='<span class="dot"></span>'+ | ||
| 192 | + '<div class="th-head">'+badges+more+'</div>'+ | ||
| 193 | + '<div class="th-body">'+esc(t.thought)+'</div>'; | ||
| 194 | + tl.appendChild(li); | ||
| 195 | + }); | ||
| 196 | + } | ||
| 197 | + | ||
| 198 | + function open(id){ | ||
| 199 | + cur=id; | ||
| 200 | + document.body.setAttribute('data-view','detail'); | ||
| 201 | + clearErr(); | ||
| 202 | + api('chain','id='+encodeURIComponent(id)).then(function(d){ | ||
| 203 | + if(!d||d.ok===false){showErr((d&&d.error)||'chain failed');return;} | ||
| 204 | + renderDetail(d); | ||
| 205 | + setJson(d); | ||
| 206 | + }).catch(function(e){showErr('chain: '+e);}); | ||
| 207 | + refreshList(); | ||
| 208 | + } | ||
| 209 | + function back(){ | ||
| 210 | + cur=null; | ||
| 211 | + document.body.removeAttribute('data-view'); | ||
| 212 | + document.getElementById('tl').innerHTML=''; | ||
| 213 | + document.getElementById('dhead').style.display='none'; | ||
| 214 | + refreshList(); | ||
| 215 | + } | ||
| 216 | + function refreshList(){ | ||
| 217 | + api('chains').then(function(d){ | ||
| 218 | + if(!d||d.ok===false){showErr((d&&d.error)||'chains failed');return;} | ||
| 219 | + renderList(d); | ||
| 220 | + if(!cur)setJson(d); | ||
| 221 | + }).catch(function(e){showErr('chains: '+e);}); | ||
| 222 | + } | ||
| 223 | + document.getElementById('refreshBtn').onclick=function(){cur?open(cur):refreshList();}; | ||
| 224 | + document.getElementById('backBtn').onclick=back; | ||
| 225 | + document.getElementById('backBtn2').onclick=back; | ||
| 226 | + document.getElementById('jsonBtn').onclick=function(){ | ||
| 227 | + var j=document.getElementById('json'); | ||
| 228 | + var on=j.style.display!=='none'; | ||
| 229 | + j.style.display=on?'none':'block'; | ||
| 230 | + this.textContent=on?'Show JSON':'Hide JSON'; | ||
| 231 | + }; | ||
| 232 | + document.getElementById('clearBtn').onclick=function(){ | ||
| 233 | + if(!window.confirm('Delete all recorded thought chains? This cannot be undone.'))return; | ||
| 234 | + api('clear','confirm=1').then(function(d){ | ||
| 235 | + if(!d||d.ok===false){showErr((d&&d.error)||'clear failed');return;} | ||
| 236 | + cur=null;back(); | ||
| 237 | + }).catch(function(e){showErr('clear: '+e);}); | ||
| 238 | + }; | ||
| 239 | + document.getElementById('themeToggle').onclick=function(){ | ||
| 240 | + var t=document.documentElement.getAttribute('data-theme')==='dark'?'light':'dark'; | ||
| 241 | + window.sxApplyTheme(t); | ||
| 242 | + }; | ||
| 243 | + refreshList(); | ||
| 244 | +})(); | ||
| 245 | +</script> | ||
| 246 | +</body> | ||
| 247 | +</html> |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..6e3794a | index 0000000..6e3794a | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/src/ui_html.h | +++ b/src/ui_html.h | ||
| @@ -0,0 +1,255 @@ | @@ -0,0 +1,255 @@ | ||
| 1 | +/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */ | ||
| 2 | +#ifndef SX_SEQTHINK_UI_HTML_H | ||
| 3 | +#define SX_SEQTHINK_UI_HTML_H | ||
| 4 | + | ||
| 5 | +static const char *UI_HTML = | ||
| 6 | + "<!DOCTYPE html>\n" | ||
| 7 | + "<html>\n" | ||
| 8 | + "<head>\n" | ||
| 9 | + "<meta charset=\"utf-8\">\n" | ||
| 10 | + "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n" | ||
| 11 | + "<title>Thought Chains</title>\n" | ||
| 12 | + "\001\n" | ||
| 13 | + "<style>\n" | ||
| 14 | + "*{box-sizing:border-box}\n" | ||
| 15 | + "html,body{margin:0;padding:0}\n" | ||
| 16 | + "body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;line-height:1.5}\n" | ||
| 17 | + ".wrap{max-width:1180px;margin:0 auto;padding:14px}\n" | ||
| 18 | + "header{display:flex;flex-wrap:wrap;align-items:center;gap:10px;margin-bottom:12px}\n" | ||
| 19 | + "header h1{font-size:17px;margin:0;font-weight:700;letter-spacing:-.01em}\n" | ||
| 20 | + ".chip{font-size:11px;color:var(--text-2);border:1px solid var(--line);border-radius:980px;padding:2px 10px;background:var(--bg-card)}\n" | ||
| 21 | + ".chip b{color:var(--text);font-weight:600}\n" | ||
| 22 | + ".spacer{flex:1}\n" | ||
| 23 | + "button{background:var(--surface-2);color:var(--text);border:1px solid var(--line);border-radius:980px;padding:6px 14px;font:inherit;font-size:13px;font-weight:600;cursor:pointer}\n" | ||
| 24 | + "button:hover{border-color:var(--line-2)}\n" | ||
| 25 | + "button.danger{color:var(--red)}\n" | ||
| 26 | + "button.primary{background:var(--blue);border-color:var(--blue);color:#fff}\n" | ||
| 27 | + ".grid{display:grid;grid-template-columns:330px 1fr;gap:14px;align-items:start}\n" | ||
| 28 | + ".card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;overflow:hidden}\n" | ||
| 29 | + ".card h2{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--text-2);margin:0;padding:10px 14px;border-bottom:1px solid var(--line);font-weight:600}\n" | ||
| 30 | + "ul.chains{list-style:none;margin:0;padding:6px;max-height:70vh;overflow:auto}\n" | ||
| 31 | + "ul.chains li{padding:9px 10px;border-radius:10px;cursor:pointer;border:1px solid transparent}\n" | ||
| 32 | + "ul.chains li:hover{background:var(--surface-hover)}\n" | ||
| 33 | + "ul.chains li.sel{background:var(--surface-2);border-color:var(--line-2)}\n" | ||
| 34 | + ".cl-top{display:flex;align-items:baseline;gap:8px}\n" | ||
| 35 | + ".cl-id{font-family:var(--mono);font-size:12px;color:var(--blue);font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n" | ||
| 36 | + ".cl-when{font-size:11px;color:var(--text-2);margin-left:auto;white-space:nowrap}\n" | ||
| 37 | + ".cl-last{font-size:12px;color:var(--text-2);margin-top:3px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}\n" | ||
| 38 | + ".cl-meta{display:flex;gap:6px;margin-top:6px;flex-wrap:wrap}\n" | ||
| 39 | + ".pill{font-size:10px;font-weight:700;border-radius:980px;padding:1px 8px;border:1px solid var(--line);color:var(--text-2)}\n" | ||
| 40 | + ".pill.b{color:var(--green);border-color:var(--green)}\n" | ||
| 41 | + ".pill.t{color:var(--teal);border-color:var(--teal)}\n" | ||
| 42 | + ".detail .empty{padding:36px 20px;text-align:center;color:var(--text-2)}\n" | ||
| 43 | + ".detail .empty code{font-family:var(--mono);color:var(--text)}\n" | ||
| 44 | + ".dhead{padding:12px 16px;border-bottom:1px solid var(--line);display:flex;flex-wrap:wrap;gap:10px;align-items:center}\n" | ||
| 45 | + ".dhead .did{font-family:var(--mono);font-weight:700;color:var(--blue)}\n" | ||
| 46 | + ".prog{flex:1;min-width:120px;max-width:280px;height:6px;border-radius:3px;background:var(--surface-2);overflow:hidden}\n" | ||
| 47 | + ".prog i{display:block;height:100%;background:var(--blue);border-radius:3px}\n" | ||
| 48 | + ".tl{list-style:none;margin:0;padding:14px 16px 18px 16px;position:relative}\n" | ||
| 49 | + ".tl li{position:relative;padding:0 0 16px 30px}\n" | ||
| 50 | + ".tl li::before{content:\"\";position:absolute;left:8px;top:18px;bottom:-2px;width:2px;background:var(--line)}\n" | ||
| 51 | + ".tl li:last-child::before{display:none}\n" | ||
| 52 | + ".tl .dot{position:absolute;left:2px;top:4px;width:14px;height:14px;border-radius:50%;border:3px solid var(--bg-card);background:var(--blue)}\n" | ||
| 53 | + ".tl li.rev .dot{background:var(--orange)}\n" | ||
| 54 | + ".tl li.br .dot{background:var(--green)}\n" | ||
| 55 | + ".th-head{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:4px}\n" | ||
| 56 | + ".th-num{font-weight:700;font-size:13px}\n" | ||
| 57 | + ".badge{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;border-radius:980px;padding:1px 8px}\n" | ||
| 58 | + ".badge.rev{color:var(--orange);border:1px solid var(--orange)}\n" | ||
| 59 | + ".badge.br{color:var(--green);border:1px solid var(--green)}\n" | ||
| 60 | + ".badge.fin{color:var(--purple);border:1px solid var(--purple)}\n" | ||
| 61 | + ".th-more{font-size:11px;color:var(--text-2)}\n" | ||
| 62 | + ".th-body{white-space:pre-wrap;word-wrap:break-word;font-size:13.5px;background:var(--surface-2);border:1px solid var(--line);border-radius:10px;padding:9px 12px;margin-top:2px}\n" | ||
| 63 | + ".jsonwrap{margin-top:14px}\n" | ||
| 64 | + ".jsonwrap pre{background:var(--code-bg);border:1px solid var(--line);border-radius:12px;padding:12px;font-family:var(--mono);font-size:11.5px;overflow:auto;max-height:340px;margin:8px 0 0}\n" | ||
| 65 | + ".errbox{margin:12px 16px;padding:10px 12px;border:1px solid var(--red);border-radius:10px;color:var(--red);font-size:13px}\n" | ||
| 66 | + "#backBtn{display:none}\n" | ||
| 67 | + "@media (max-width:860px){\n" | ||
| 68 | + " .grid{grid-template-columns:1fr}\n" | ||
| 69 | + " body[data-view=detail] #listCard{display:none}\n" | ||
| 70 | + " body:not([data-view=detail]) .tlwrap{display:none}\n" | ||
| 71 | + " body:not([data-view=detail]) .dhead{display:none}\n" | ||
| 72 | + " body[data-view=detail] #backBtn{display:inline-block}\n" | ||
| 73 | + "}\n" | ||
| 74 | + "</style>\n" | ||
| 75 | + "</head>\n" | ||
| 76 | + "<body>\n" | ||
| 77 | + "<div class=\"wrap\">\n" | ||
| 78 | + " <header>\n" | ||
| 79 | + " <button id=\"backBtn\" type=\"button\">Back</button>\n" | ||
| 80 | + " <h1>Thought Chains</h1>\n" | ||
| 81 | + " <span class=\"chip\" id=\"chipChains\">chains <b>-</b></span>\n" | ||
| 82 | + " <span class=\"chip\" id=\"chipThoughts\">thoughts <b>-</b></span>\n" | ||
| 83 | + " <span class=\"chip\" id=\"chipState\">state <b>-</b></span>\n" | ||
| 84 | + " <span class=\"spacer\"></span>\n" | ||
| 85 | + " <button id=\"refreshBtn\" type=\"button\">Refresh</button>\n" | ||
| 86 | + " <button id=\"clearBtn\" type=\"button\" class=\"danger\">Clear</button>\n" | ||
| 87 | + " <button class=\"embed-hide\" id=\"themeToggle\" type=\"button\" title=\"Toggle appearance\">Theme</button>\n" | ||
| 88 | + " </header>\n" | ||
| 89 | + "\n" | ||
| 90 | + " <div class=\"grid\">\n" | ||
| 91 | + " <div class=\"card\" id=\"listCard\">\n" | ||
| 92 | + " <h2>Chains</h2>\n" | ||
| 93 | + " <ul class=\"chains\" id=\"chains\"></ul>\n" | ||
| 94 | + " </div>\n" | ||
| 95 | + "\n" | ||
| 96 | + " <div class=\"card\">\n" | ||
| 97 | + " <div class=\"dhead\" id=\"dhead\" style=\"display:none\">\n" | ||
| 98 | + " <button id=\"backBtn2\" type=\"button\">Back</button>\n" | ||
| 99 | + " <span class=\"did\" id=\"dId\"></span>\n" | ||
| 100 | + " <span class=\"chip\" id=\"dCount\"></span>\n" | ||
| 101 | + " <div class=\"prog\"><i id=\"dProg\" style=\"width:0%\"></i></div>\n" | ||
| 102 | + " </div>\n" | ||
| 103 | + " <div class=\"tlwrap\">\n" | ||
| 104 | + " <div class=\"empty\" id=\"empty\">Loading...</div>\n" | ||
| 105 | + " <ul class=\"tl\" id=\"tl\"></ul>\n" | ||
| 106 | + " </div>\n" | ||
| 107 | + " <div id=\"errbox\" class=\"errbox\" style=\"display:none\"></div>\n" | ||
| 108 | + " <div class=\"jsonwrap\" style=\"padding:0 16px 14px\">\n" | ||
| 109 | + " <button id=\"jsonBtn\" type=\"button\">Show JSON</button>\n" | ||
| 110 | + " <pre id=\"json\" style=\"display:none\"></pre>\n" | ||
| 111 | + " </div>\n" | ||
| 112 | + " </div>\n" | ||
| 113 | + " </div>\n" | ||
| 114 | + "</div>\n" | ||
| 115 | + "<script>\n" | ||
| 116 | + "(function(){\n" | ||
| 117 | + " var q=new URLSearchParams(location.search);\n" | ||
| 118 | + " var HUB=q.get('plugin')||'';\n" | ||
| 119 | + " var node=q.get('node')||'';\n" | ||
| 120 | + " var sid=q.get('id')||'';\n" | ||
| 121 | + " var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||localStorage.getItem('bot_active_pwd')||'';\n" | ||
| 122 | + " var cur=null, lastJson='';\n" | ||
| 123 | + "\n" | ||
| 124 | + " function api(action,extra){\n" | ||
| 125 | + " /* Hub-proxy route when served through /plugins?plugin=..., direct node\n" | ||
| 126 | + " route when opened as /plugin_seqthink. Never call /plugins?plugin= on\n" | ||
| 127 | + " the node itself: that is discovery and never dispatches. */\n" | ||
| 128 | + " var u=(HUB?'/plugins?plugin='+encodeURIComponent(HUB)+'&action='+action\n" | ||
| 129 | + " :'/plugin_seqthink?action='+action);\n" | ||
| 130 | + " if(extra)u+='&'+extra;\n" | ||
| 131 | + " if(node)u+='&node='+encodeURIComponent(node);\n" | ||
| 132 | + " if(sid)u+='&id='+encodeURIComponent(sid);\n" | ||
| 133 | + " if(pwd)u+='&pwd='+encodeURIComponent(pwd);\n" | ||
| 134 | + " return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{}}).then(function(r){return r.json();});\n" | ||
| 135 | + " }\n" | ||
| 136 | + " function esc(s){return String(s==null?'':s).replace(/[&<>\"]/g,function(c){\n" | ||
| 137 | + " return {'&':'&','<':'<','>':'>','\"':'"'}[c];});}\n" | ||
| 138 | + " function fmt(ts){if(!ts)return '-';try{return new Date(ts*1000).toLocaleString();}catch(e){return String(ts);}}\n" | ||
| 139 | + " function showErr(m){var e=document.getElementById('errbox');e.textContent=m;e.style.display='block';}\n" | ||
| 140 | + " function clearErr(){document.getElementById('errbox').style.display='none';}\n" | ||
| 141 | + " function setJson(o){lastJson=JSON.stringify(o,null,2);var j=document.getElementById('json');j.textContent=lastJson;}\n" | ||
| 142 | + "\n" | ||
| 143 | + " function renderList(d){\n" | ||
| 144 | + " var ul=document.getElementById('chains');\n" | ||
| 145 | + " var cs=(d&&d.chains)||[];\n" | ||
| 146 | + " document.getElementById('chipChains').innerHTML='chains <b>'+((d&&d.count!=null)?d.count:cs.length)+'</b>';\n" | ||
| 147 | + " var tot=0;cs.forEach(function(c){tot+=c.thoughts||0;});\n" | ||
| 148 | + " document.getElementById('chipThoughts').innerHTML='thoughts <b>'+tot+'</b>';\n" | ||
| 149 | + " document.getElementById('chipState').innerHTML='state <b>'+esc((d&&d.state_dir_name)||'-')+'</b>';\n" | ||
| 150 | + " ul.innerHTML='';\n" | ||
| 151 | + " if(!cs.length){\n" | ||
| 152 | + " if(!cur)document.getElementById('empty').innerHTML=\n" | ||
| 153 | + " 'No thought chains recorded yet.<br>Call the <code>sequentialthinking</code> MCP tool '+\n" | ||
| 154 | + " '(<code>plugin_seqthink --mcp</code>) and press Refresh.';\n" | ||
| 155 | + " return;\n" | ||
| 156 | + " }\n" | ||
| 157 | + " cs.forEach(function(c){\n" | ||
| 158 | + " var li=document.createElement('li');\n" | ||
| 159 | + " if(c.id===cur)li.className='sel';\n" | ||
| 160 | + " var badges='<span class=\"pill t\">thoughts '+esc(c.thoughts)+'</span>';\n" | ||
| 161 | + " if(c.branches&&c.branches.length)badges+='<span class=\"pill b\">branches '+c.branches.length+'</span>';\n" | ||
| 162 | + " if(c.truncated)badges+='<span class=\"pill\">capped</span>';\n" | ||
| 163 | + " li.innerHTML='<div class=\"cl-top\"><span class=\"cl-id\">'+esc(c.id)+'</span>'+\n" | ||
| 164 | + " '<span class=\"cl-when\">'+esc(fmt(c.updated_at))+'</span></div>'+\n" | ||
| 165 | + " '<div class=\"cl-last\">'+esc(c.last_head||'')+'</div>'+\n" | ||
| 166 | + " '<div class=\"cl-meta\">'+badges+'</div>';\n" | ||
| 167 | + " li.onclick=function(){open(c.id);};\n" | ||
| 168 | + " ul.appendChild(li);\n" | ||
| 169 | + " });\n" | ||
| 170 | + " }\n" | ||
| 171 | + "\n" | ||
| 172 | + " function renderDetail(d){\n" | ||
| 173 | + " var tl=document.getElementById('tl');\n" | ||
| 174 | + " var th=(d&&d.thoughts)||[];\n" | ||
| 175 | + " document.getElementById('dhead').style.display=th.length?'flex':'none';\n" | ||
| 176 | + " document.getElementById('dId').textContent=(d&&d.id)||'';\n" | ||
| 177 | + " var last=th.length?th[th.length-1]:null;\n" | ||
| 178 | + " var tt=last?(last.total_thoughts||0):0, tn=last?(last.thought_number||0):0;\n" | ||
| 179 | + " document.getElementById('dCount').textContent=th.length+' thoughts';\n" | ||
| 180 | + " document.getElementById('dProg').style.width=(tt>0?Math.min(100,Math.round(100*tn/tt)):0)+'%';\n" | ||
| 181 | + " document.getElementById('empty').style.display=th.length?'none':'block';\n" | ||
| 182 | + " if(!th.length&&!document.getElementById('empty').textContent.trim())\n" | ||
| 183 | + " document.getElementById('empty').textContent='No thoughts in this chain.';\n" | ||
| 184 | + " tl.innerHTML='';\n" | ||
| 185 | + " th.forEach(function(t){\n" | ||
| 186 | + " var li=document.createElement('li');\n" | ||
| 187 | + " var cls=t.is_revision?'rev':(t.branch_from?'br':'');\n" | ||
| 188 | + " if(cls)li.className=cls;\n" | ||
| 189 | + " var badges='<span class=\"th-num\">#'+esc(t.thought_number)+' / '+esc(t.total_thoughts)+'</span>';\n" | ||
| 190 | + " if(t.is_revision)badges+='<span class=\"badge rev\">revision'+(t.revises?' of #'+esc(t.revises):'')+'</span>';\n" | ||
| 191 | + " if(t.branch_from)badges+='<span class=\"badge br\">branch from #'+esc(t.branch_from)+\n" | ||
| 192 | + " (t.branch_id?' · '+esc(t.branch_id):'')+'</span>';\n" | ||
| 193 | + " if(!t.next_needed)badges+='<span class=\"badge fin\">final</span>';\n" | ||
| 194 | + " var more='';\n" | ||
| 195 | + " if(t.needs_more)more=' <span class=\"th-more\">needs more thoughts</span>';\n" | ||
| 196 | + " li.innerHTML='<span class=\"dot\"></span>'+\n" | ||
| 197 | + " '<div class=\"th-head\">'+badges+more+'</div>'+\n" | ||
| 198 | + " '<div class=\"th-body\">'+esc(t.thought)+'</div>';\n" | ||
| 199 | + " tl.appendChild(li);\n" | ||
| 200 | + " });\n" | ||
| 201 | + " }\n" | ||
| 202 | + "\n" | ||
| 203 | + " function open(id){\n" | ||
| 204 | + " cur=id;\n" | ||
| 205 | + " document.body.setAttribute('data-view','detail');\n" | ||
| 206 | + " clearErr();\n" | ||
| 207 | + " api('chain','id='+encodeURIComponent(id)).then(function(d){\n" | ||
| 208 | + " if(!d||d.ok===false){showErr((d&&d.error)||'chain failed');return;}\n" | ||
| 209 | + " renderDetail(d);\n" | ||
| 210 | + " setJson(d);\n" | ||
| 211 | + " }).catch(function(e){showErr('chain: '+e);});\n" | ||
| 212 | + " refreshList();\n" | ||
| 213 | + " }\n" | ||
| 214 | + " function back(){\n" | ||
| 215 | + " cur=null;\n" | ||
| 216 | + " document.body.removeAttribute('data-view');\n" | ||
| 217 | + " document.getElementById('tl').innerHTML='';\n" | ||
| 218 | + " document.getElementById('dhead').style.display='none';\n" | ||
| 219 | + " refreshList();\n" | ||
| 220 | + " }\n" | ||
| 221 | + " function refreshList(){\n" | ||
| 222 | + " api('chains').then(function(d){\n" | ||
| 223 | + " if(!d||d.ok===false){showErr((d&&d.error)||'chains failed');return;}\n" | ||
| 224 | + " renderList(d);\n" | ||
| 225 | + " if(!cur)setJson(d);\n" | ||
| 226 | + " }).catch(function(e){showErr('chains: '+e);});\n" | ||
| 227 | + " }\n" | ||
| 228 | + " document.getElementById('refreshBtn').onclick=function(){cur?open(cur):refreshList();};\n" | ||
| 229 | + " document.getElementById('backBtn').onclick=back;\n" | ||
| 230 | + " document.getElementById('backBtn2').onclick=back;\n" | ||
| 231 | + " document.getElementById('jsonBtn').onclick=function(){\n" | ||
| 232 | + " var j=document.getElementById('json');\n" | ||
| 233 | + " var on=j.style.display!=='none';\n" | ||
| 234 | + " j.style.display=on?'none':'block';\n" | ||
| 235 | + " this.textContent=on?'Show JSON':'Hide JSON';\n" | ||
| 236 | + " };\n" | ||
| 237 | + " document.getElementById('clearBtn').onclick=function(){\n" | ||
| 238 | + " if(!window.confirm('Delete all recorded thought chains? This cannot be undone.'))return;\n" | ||
| 239 | + " api('clear','confirm=1').then(function(d){\n" | ||
| 240 | + " if(!d||d.ok===false){showErr((d&&d.error)||'clear failed');return;}\n" | ||
| 241 | + " cur=null;back();\n" | ||
| 242 | + " }).catch(function(e){showErr('clear: '+e);});\n" | ||
| 243 | + " };\n" | ||
| 244 | + " document.getElementById('themeToggle').onclick=function(){\n" | ||
| 245 | + " var t=document.documentElement.getAttribute('data-theme')==='dark'?'light':'dark';\n" | ||
| 246 | + " window.sxApplyTheme(t);\n" | ||
| 247 | + " };\n" | ||
| 248 | + " refreshList();\n" | ||
| 249 | + "})();\n" | ||
| 250 | + "</script>\n" | ||
| 251 | + "\002</body>\n" | ||
| 252 | + "</html>\n" | ||
| 253 | + ; | ||
| 254 | + | ||
| 255 | +#endif /* SX_SEQTHINK_UI_HTML_H */ |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..eafd5c3 | index 0000000..eafd5c3 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/e2e.py | +++ b/tests/e2e.py | ||
| @@ -0,0 +1,374 @@ | @@ -0,0 +1,374 @@ | ||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""tests/e2e.py - viewport and live-behaviour checks for the plugin_seqthink UI. | ||
| 3 | + | ||
| 4 | +Serves the plugin through a tiny CGI-ish HTTP shim on a loopback port, with a | ||
| 5 | +state directory seeded by real --mcp sessions (thoughts, a revision, a branch, | ||
| 6 | +unicode). Opens the page with Playwright at 1440 / 1024 / 390 CSS pixels in | ||
| 7 | +BOTH themes and asserts: no console error, no horizontal overflow, the chain | ||
| 8 | +list is populated from action=chains, selecting a chain renders the timeline | ||
| 9 | +with revision and branch badges, the progress bar tracks the last thought, | ||
| 10 | +Show JSON reveals parsable JSON, the bot theme handoff works, and Clear | ||
| 11 | +(behind confirm) empties the store. | ||
| 12 | + | ||
| 13 | +Skips cleanly (exit 0) when Playwright is not installed, so `make test` stays | ||
| 14 | +offline-only. | ||
| 15 | + | ||
| 16 | + python3 tests/e2e.py # run if Playwright is available | ||
| 17 | + python3 tests/e2e.py --strict # exit 2 when Playwright is missing | ||
| 18 | +""" | ||
| 19 | + | ||
| 20 | +import argparse | ||
| 21 | +import http.server | ||
| 22 | +import json | ||
| 23 | +import os | ||
| 24 | +import subprocess | ||
| 25 | +import sys | ||
| 26 | +import tempfile | ||
| 27 | +import threading | ||
| 28 | +from urllib.parse import urlparse, parse_qs | ||
| 29 | + | ||
| 30 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 31 | +BIN = os.path.join(ROOT, "plugin_seqthink") | ||
| 32 | +VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)] | ||
| 33 | +SHOTS = os.path.join(ROOT, "docs") | ||
| 34 | + | ||
| 35 | +FAILS = [] | ||
| 36 | +PASSES = [] | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +def ok(desc): | ||
| 40 | + PASSES.append(desc) | ||
| 41 | + print(" ok %s" % desc) | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +def bad(desc, extra=""): | ||
| 45 | + FAILS.append(desc) | ||
| 46 | + print(" FAIL %s%s" % (desc, (" -- " + str(extra)) if extra else "")) | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +def check(desc, cond, extra=""): | ||
| 50 | + ok(desc) if cond else bad(desc, extra) | ||
| 51 | + | ||
| 52 | + | ||
| 53 | +def run_session(state_dir, arg_list): | ||
| 54 | + """One --mcp process == one chain (upstream: a server lives as long as its | ||
| 55 | + client's connection). Feed every thought of the session on one stdin.""" | ||
| 56 | + lines = "\n".join( | ||
| 57 | + json.dumps({"jsonrpc": "2.0", "id": i + 1, "method": "tools/call", | ||
| 58 | + "params": {"name": "sequentialthinking", "arguments": a}}) | ||
| 59 | + for i, a in enumerate(arg_list)) + "\n" | ||
| 60 | + env = dict(os.environ) | ||
| 61 | + env["SEQTHINK_STATE_DIR"] = state_dir | ||
| 62 | + out = subprocess.run([BIN, "--mcp"], input=lines, capture_output=True, | ||
| 63 | + text=True, env=env, timeout=30) | ||
| 64 | + return [json.loads(l) for l in out.stdout.splitlines() if l.strip()] | ||
| 65 | + | ||
| 66 | + | ||
| 67 | +def call_tool(state_dir, args): | ||
| 68 | + return run_session(state_dir, [args])[0] | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def click_chain(page, idx): | ||
| 72 | + page.evaluate( | ||
| 73 | + "(i) => { const li = document.querySelectorAll('#chains li')[i];" | ||
| 74 | + " if (li) li.click(); }", idx) | ||
| 75 | + page.wait_for_timeout(450) | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +def prepare_fixtures(): | ||
| 79 | + """Three --mcp sessions: a linear chain with a revision, a branching chain, | ||
| 80 | + and a small unicode chain. The viewer reads exactly what the tool wrote.""" | ||
| 81 | + tmp = tempfile.mkdtemp(prefix="seqthink_e2e_") | ||
| 82 | + env = dict(os.environ) | ||
| 83 | + env["SEQTHINK_STATE_DIR"] = tmp | ||
| 84 | + | ||
| 85 | + # Session 1: one process, one chain: linear thoughts with a revision. | ||
| 86 | + run_session(tmp, [ | ||
| 87 | + {"thought": "decompose the migration into phases", | ||
| 88 | + "nextThoughtNeeded": True, "thoughtNumber": 1, "totalThoughts": 4}, | ||
| 89 | + {"thought": "phase 2 assumed a shared schema; that was wrong\n" | ||
| 90 | + "the two services must keep separate stores", | ||
| 91 | + "nextThoughtNeeded": True, "isRevision": True, "revisesThought": 1, | ||
| 92 | + "thoughtNumber": 2, "totalThoughts": 4}, | ||
| 93 | + {"thought": "blue-green it and cut over behind a flag", | ||
| 94 | + "nextThoughtNeeded": False, "thoughtNumber": 3, "totalThoughts": 4}, | ||
| 95 | + ]) | ||
| 96 | + | ||
| 97 | + # Session 2: a branch (both thoughts carry branchFromThought + branchId). | ||
| 98 | + run_session(tmp, [ | ||
| 99 | + {"thought": "alternative path: strangler facade", | ||
| 100 | + "nextThoughtNeeded": True, "branchFromThought": 1, | ||
| 101 | + "branchId": "strangler", "thoughtNumber": 4, "totalThoughts": 5}, | ||
| 102 | + {"thought": "facade needs a routing layer first", | ||
| 103 | + "nextThoughtNeeded": False, "branchFromThought": 1, | ||
| 104 | + "branchId": "strangler", "thoughtNumber": 5, "totalThoughts": 5}, | ||
| 105 | + ]) | ||
| 106 | + | ||
| 107 | + # Session 3: a single unicode thought. | ||
| 108 | + call_tool(tmp, {"thought": "unicode check: \u00fcn\u00efc\u00f8d\u00e9, \u00e9mojis, " | ||
| 109 | + "\u65e5\u672c\u8a9e and \"quotes\"", | ||
| 110 | + "nextThoughtNeeded": False, "thoughtNumber": 1, | ||
| 111 | + "totalThoughts": 1}) | ||
| 112 | + return tmp, env | ||
| 113 | + | ||
| 114 | + | ||
| 115 | +class Handler(http.server.BaseHTTPRequestHandler): | ||
| 116 | + env = {} | ||
| 117 | + | ||
| 118 | + def _run(self, method): | ||
| 119 | + u = urlparse(self.path) | ||
| 120 | + qs = u.query | ||
| 121 | + env = dict(self.env) | ||
| 122 | + env["QUERY_STRING"] = qs | ||
| 123 | + env["REQUEST_METHOD"] = method | ||
| 124 | + env.pop("BOT_PASSWORD", None) | ||
| 125 | + body = b"" | ||
| 126 | + if method == "POST": | ||
| 127 | + n = int(self.headers.get("Content-Length") or 0) | ||
| 128 | + body = self.rfile.read(n) if n > 0 else b"" | ||
| 129 | + env["CONTENT_LENGTH"] = str(n) | ||
| 130 | + p = subprocess.Popen([BIN], stdin=subprocess.PIPE, | ||
| 131 | + stdout=subprocess.PIPE, env=env) | ||
| 132 | + out = p.communicate(body)[0] | ||
| 133 | + sep = out.find(b"\r\n\r\n") | ||
| 134 | + headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else "" | ||
| 135 | + payload = out[sep + 4:] if sep >= 0 else out | ||
| 136 | + ctype = "text/html; charset=utf-8" | ||
| 137 | + status = 200 | ||
| 138 | + for line in headers.splitlines(): | ||
| 139 | + low = line.lower() | ||
| 140 | + if low.startswith("content-type:"): | ||
| 141 | + ctype = line.split(":", 1)[1].strip() | ||
| 142 | + elif low.startswith("status:"): | ||
| 143 | + try: | ||
| 144 | + status = int(line.split(":", 1)[1].strip().split()[0]) | ||
| 145 | + except Exception: | ||
| 146 | + pass | ||
| 147 | + self.send_response(status) | ||
| 148 | + self.send_header("Content-Type", ctype) | ||
| 149 | + self.send_header("Cache-Control", "no-store") | ||
| 150 | + self.send_header("Content-Length", str(len(payload))) | ||
| 151 | + self.end_headers() | ||
| 152 | + self.wfile.write(payload) | ||
| 153 | + | ||
| 154 | + def do_GET(self): # noqa: N802 | ||
| 155 | + self._run("GET") | ||
| 156 | + | ||
| 157 | + def do_POST(self): # noqa: N802 | ||
| 158 | + self._run("POST") | ||
| 159 | + | ||
| 160 | + def log_message(self, *_a): | ||
| 161 | + pass | ||
| 162 | + | ||
| 163 | + | ||
| 164 | +def serve(env): | ||
| 165 | + Handler.env = env | ||
| 166 | + httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) | ||
| 167 | + t = threading.Thread(target=httpd.serve_forever, daemon=True) | ||
| 168 | + t.start() | ||
| 169 | + return httpd, httpd.server_address[1] | ||
| 170 | + | ||
| 171 | + | ||
| 172 | +def main(): | ||
| 173 | + ap = argparse.ArgumentParser() | ||
| 174 | + ap.add_argument("--strict", action="store_true") | ||
| 175 | + ap.add_argument("--no-shots", action="store_true") | ||
| 176 | + args = ap.parse_args() | ||
| 177 | + | ||
| 178 | + try: | ||
| 179 | + from playwright.sync_api import sync_playwright | ||
| 180 | + except Exception: | ||
| 181 | + print(" skip e2e (playwright not installed)") | ||
| 182 | + return 2 if args.strict else 0 | ||
| 183 | + | ||
| 184 | + if not os.path.exists(BIN): | ||
| 185 | + print(" FAIL plugin binary missing; run `make` first") | ||
| 186 | + return 1 | ||
| 187 | + | ||
| 188 | + tmp, env = prepare_fixtures() | ||
| 189 | + httpd, port = serve(env) | ||
| 190 | + base = "http://127.0.0.1:%d/" % port | ||
| 191 | + print("== e2e: %s (state %s) ==" % (base, tmp)) | ||
| 192 | + | ||
| 193 | + os.makedirs(SHOTS, exist_ok=True) | ||
| 194 | + cleared = False | ||
| 195 | + try: | ||
| 196 | + with sync_playwright() as p: | ||
| 197 | + browser = p.chromium.launch() | ||
| 198 | + for w, h in VIEWPORTS: | ||
| 199 | + for theme in ("dark", "light"): | ||
| 200 | + tag = "%dx%d %s" % (w, h, theme) | ||
| 201 | + page = browser.new_page(viewport={"width": w, "height": h}, | ||
| 202 | + device_scale_factor=1) | ||
| 203 | + errors = [] | ||
| 204 | + page.on("console", lambda m: errors.append(m.text) | ||
| 205 | + if m.type == "error" else None) | ||
| 206 | + page.on("pageerror", lambda e: errors.append(str(e))) | ||
| 207 | + page.goto(base + "?theme=" + theme, wait_until="load") | ||
| 208 | + page.wait_for_timeout(700) | ||
| 209 | + | ||
| 210 | + check("%s: no console errors" % tag, not errors, errors[:3]) | ||
| 211 | + | ||
| 212 | + attr = page.evaluate( | ||
| 213 | + "document.documentElement.getAttribute('data-theme')") | ||
| 214 | + check("%s: theme applied" % tag, attr == theme, attr) | ||
| 215 | + | ||
| 216 | + over = page.evaluate( | ||
| 217 | + "() => Math.max(document.documentElement.scrollWidth," | ||
| 218 | + " document.body.scrollWidth) - window.innerWidth") | ||
| 219 | + check("%s: no horizontal overflow" % tag, over <= 1, over) | ||
| 220 | + | ||
| 221 | + # chain list populated from action=chains | ||
| 222 | + n = page.evaluate( | ||
| 223 | + "document.querySelectorAll('#chains li').length") | ||
| 224 | + check("%s: chain list populated" % tag, n >= 3, n) | ||
| 225 | + chips = page.evaluate( | ||
| 226 | + "document.getElementById('chipChains').textContent") | ||
| 227 | + check("%s: chip counts chains" % tag, "3" in chips, chips) | ||
| 228 | + | ||
| 229 | + # select chain 0 (the linear chain with the revision) | ||
| 230 | + click_chain(page, 0) | ||
| 231 | + page.wait_for_timeout(500) | ||
| 232 | + rows = page.evaluate("document.querySelectorAll('#tl li').length") | ||
| 233 | + check("%s: timeline renders the selected chain" % tag, | ||
| 234 | + rows == 3, rows) | ||
| 235 | + revs = page.evaluate( | ||
| 236 | + "document.querySelectorAll('#tl li.rev').length") | ||
| 237 | + check("%s: revision row marked" % tag, revs == 1, revs) | ||
| 238 | + fin = page.evaluate( | ||
| 239 | + "document.querySelectorAll('#tl .badge.fin').length") | ||
| 240 | + check("%s: final thought badged" % tag, fin == 1, fin) | ||
| 241 | + # the revision (row 2) is the multi-line thought | ||
| 242 | + body = page.evaluate( | ||
| 243 | + "document.querySelectorAll('#tl .th-body')[1].textContent") | ||
| 244 | + check("%s: multi-line thought keeps its newline" % tag, | ||
| 245 | + "\n" in body, repr(body[:60])) | ||
| 246 | + | ||
| 247 | + # select the branching chain (index 1) | ||
| 248 | + page.evaluate("document.getElementById('backBtn') && " | ||
| 249 | + "document.getElementById('backBtn').click()") | ||
| 250 | + page.wait_for_timeout(400) | ||
| 251 | + click_chain(page, 1) | ||
| 252 | + page.wait_for_timeout(500) | ||
| 253 | + brs = page.evaluate( | ||
| 254 | + "document.querySelectorAll('#tl li.br').length") | ||
| 255 | + check("%s: branch rows marked" % tag, brs == 2, brs) | ||
| 256 | + btxt = page.evaluate( | ||
| 257 | + "document.querySelector('#tl .badge.br').textContent") | ||
| 258 | + check("%s: branch badge names the id" % tag, | ||
| 259 | + "strangler" in btxt, btxt) | ||
| 260 | + prog = page.evaluate( | ||
| 261 | + "document.getElementById('dProg').style.width") | ||
| 262 | + check("%s: progress bar tracks totalThoughts" % tag, | ||
| 263 | + prog in ("80%", "100%"), prog) | ||
| 264 | + | ||
| 265 | + # unicode survives the round trip | ||
| 266 | + click_chain(page, 2) | ||
| 267 | + page.wait_for_timeout(400) | ||
| 268 | + uni = page.evaluate( | ||
| 269 | + "document.querySelector('#tl .th-body').textContent") | ||
| 270 | + check("%s: unicode thought rendered" % tag, | ||
| 271 | + "ünïcødé" in uni and "日本語" in uni, uni[:60]) | ||
| 272 | + | ||
| 273 | + # JSON panel | ||
| 274 | + page.click("#jsonBtn") | ||
| 275 | + page.wait_for_timeout(200) | ||
| 276 | + jtxt = page.evaluate("document.getElementById('json').textContent") | ||
| 277 | + try: | ||
| 278 | + parsed = json.loads(jtxt) | ||
| 279 | + good = parsed.get("ok") is True and "thoughts" in parsed | ||
| 280 | + except Exception: | ||
| 281 | + good = False | ||
| 282 | + check("%s: Show JSON reveals parsable chain JSON" % tag, good) | ||
| 283 | + | ||
| 284 | + # theme handoff: the bot posts a new theme, the page follows | ||
| 285 | + page.evaluate( | ||
| 286 | + "window.postMessage({type:'sx-theme',theme:" | ||
| 287 | + "'dark'},'*')") | ||
| 288 | + page.wait_for_timeout(200) | ||
| 289 | + attr2 = page.evaluate( | ||
| 290 | + "document.documentElement.getAttribute('data-theme')") | ||
| 291 | + check("%s: sx-theme postMessage followed" % tag, | ||
| 292 | + attr2 == "dark", attr2) | ||
| 293 | + | ||
| 294 | + # CSP allows no external scripts | ||
| 295 | + nscripts = page.evaluate( | ||
| 296 | + "document.querySelectorAll('script[src]').length") | ||
| 297 | + check("%s: no external scripts" % tag, nscripts == 0, nscripts) | ||
| 298 | + | ||
| 299 | + if not args.no_shots: | ||
| 300 | + # the handoff test above flipped us to dark; restore | ||
| 301 | + # the viewport's nominal theme before shooting | ||
| 302 | + page.evaluate( | ||
| 303 | + "(t) => window.postMessage({type:'sx-theme'," | ||
| 304 | + "theme:t},'*')", theme) | ||
| 305 | + page.wait_for_timeout(200) | ||
| 306 | + # representative state: the revision chain, JSON hidden | ||
| 307 | + page.evaluate("document.getElementById('backBtn') && " | ||
| 308 | + "document.getElementById('backBtn').click()") | ||
| 309 | + page.wait_for_timeout(350) | ||
| 310 | + click_chain(page, 0) | ||
| 311 | + page.evaluate( | ||
| 312 | + """() => { const j = | ||
| 313 | + document.getElementById('json'); | ||
| 314 | + if (j.style.display !== 'none') | ||
| 315 | + document.getElementById('jsonBtn').click(); }""") | ||
| 316 | + page.wait_for_timeout(350) | ||
| 317 | + shot = os.path.join( | ||
| 318 | + SHOTS, "ui-%dx%d-%s.png" % (w, h, theme)) | ||
| 319 | + page.screenshot(path=shot, full_page=False) | ||
| 320 | + if os.path.getsize(shot) > 900 * 1024: | ||
| 321 | + bad("%s: screenshot under 900 KB" % tag, | ||
| 322 | + os.path.getsize(shot)) | ||
| 323 | + else: | ||
| 324 | + ok("%s: screenshot written (%d KB)" % | ||
| 325 | + (tag, os.path.getsize(shot) // 1024)) | ||
| 326 | + | ||
| 327 | + page.close() | ||
| 328 | + | ||
| 329 | + # Clear empties the store (behind a confirm dialog) | ||
| 330 | + page = browser.new_page(viewport={"width": 1440, "height": 900}) | ||
| 331 | + dialogs = [] | ||
| 332 | + page.on("dialog", lambda d: (dialogs.append(d.type), d.accept())) | ||
| 333 | + page.goto(base, wait_until="load") | ||
| 334 | + page.wait_for_timeout(600) | ||
| 335 | + page.click("#clearBtn") | ||
| 336 | + page.wait_for_timeout(700) | ||
| 337 | + check("clear: confirm dialog fired", dialogs == ["confirm"], dialogs) | ||
| 338 | + left = page.evaluate("document.querySelectorAll('#chains li').length") | ||
| 339 | + check("clear: chains gone", left == 0, left) | ||
| 340 | + cleared = True | ||
| 341 | + empty = page.evaluate( | ||
| 342 | + "document.getElementById('empty').textContent") | ||
| 343 | + check("clear: empty state explains the tool", | ||
| 344 | + "sequentialthinking" in empty, empty[:80]) | ||
| 345 | + page.close() | ||
| 346 | + | ||
| 347 | + # a fresh tool call after a clear reappears on Refresh | ||
| 348 | + call_tool(tmp, {"thought": "after clear", "nextThoughtNeeded": False, | ||
| 349 | + "thoughtNumber": 1, "totalThoughts": 1}) | ||
| 350 | + page = browser.new_page(viewport={"width": 1440, "height": 900}) | ||
| 351 | + page.goto(base, wait_until="load") | ||
| 352 | + page.wait_for_timeout(600) | ||
| 353 | + page.click("#refreshBtn") | ||
| 354 | + page.wait_for_timeout(600) | ||
| 355 | + n = page.evaluate("document.querySelectorAll('#chains li').length") | ||
| 356 | + check("repopulated after clear", n == 1, n) | ||
| 357 | + page.close() | ||
| 358 | + | ||
| 359 | + browser.close() | ||
| 360 | + finally: | ||
| 361 | + httpd.shutdown() | ||
| 362 | + | ||
| 363 | + print("\n== e2e: %d passed, %d failed ==" % (len(PASSES), len(FAILS))) | ||
| 364 | + if FAILS: | ||
| 365 | + for f in FAILS: | ||
| 366 | + print(" - %s" % f) | ||
| 367 | + return 1 | ||
| 368 | + if not cleared: | ||
| 369 | + return 1 | ||
| 370 | + return 0 | ||
| 371 | + | ||
| 372 | + | ||
| 373 | +if __name__ == "__main__": | ||
| 374 | + sys.exit(main()) |
| 1 | new file mode 100755 | 1 | new file mode 100755 |
| index 0000000..4f09b7d | index 0000000..4f09b7d | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tests/run.sh | +++ b/tests/run.sh | ||
| @@ -0,0 +1,521 @@ | @@ -0,0 +1,521 @@ | ||
| 1 | +#!/bin/sh | ||
| 2 | +# tests/run.sh - offline checks for plugin_seqthink across all 4 modes. | ||
| 3 | +# | ||
| 4 | +# Runs against ./plugin_seqthink (native build) on the live machine. The --mcp | ||
| 5 | +# leg is driven with a scripted JSON-RPC session on stdin; the CGI leg is | ||
| 6 | +# driven through QUERY_STRING / REQUEST_METHOD / CONTENT_LENGTH; the chain | ||
| 7 | +# store is pointed at a scratch directory through SEQTHINK_STATE_DIR so the | ||
| 8 | +# real node directory is never touched. The last section audits the whole git | ||
| 9 | +# history for secrets and internal addresses. | ||
| 10 | +# | ||
| 11 | +# Exit code 0 = everything passed. | ||
| 12 | + | ||
| 13 | +set -u | ||
| 14 | + | ||
| 15 | +ROOT=$(cd "$(dirname "$0")/.." && pwd) | ||
| 16 | +cd "$ROOT" || exit 1 | ||
| 17 | + | ||
| 18 | +BIN=./plugin_seqthink | ||
| 19 | +PASS=0 | ||
| 20 | +FAIL=0 | ||
| 21 | +TMP=$(mktemp -d 2>/dev/null || echo /tmp/seqthink_test_$$) | ||
| 22 | +mkdir -p "$TMP" | ||
| 23 | +trap 'rm -rf "$TMP"' EXIT | ||
| 24 | + | ||
| 25 | +if [ -t 1 ]; then | ||
| 26 | + C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m') | ||
| 27 | +else | ||
| 28 | + C_OK=; C_BAD=; C_B=; C_0= | ||
| 29 | +fi | ||
| 30 | +pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; } | ||
| 31 | +fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; } | ||
| 32 | + | ||
| 33 | +check() { # check <desc> <expected-substring> <actual> | ||
| 34 | + if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else | ||
| 35 | + fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 300)" | ||
| 36 | + fi | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +check_not() { # check_not <desc> <forbidden-substring> <actual> | ||
| 40 | + if printf '%s' "$3" | grep -F -q -- "$2"; then | ||
| 41 | + fail "$1 (must NOT contain: $2)"; else pass "$1" | ||
| 42 | + fi | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; } | ||
| 46 | +body() { printf '%s' "$1" | sed '1,/^\r$/d'; } | ||
| 47 | + | ||
| 48 | +jq_() { # jq_ <desc> <python-expression using d> <json> | ||
| 49 | + printf '%s' "$3" > "$TMP/_j.json" | ||
| 50 | + if python3 - "$TMP/_j.json" "$2" <<'PY' 2>/dev/null | ||
| 51 | +import json, sys | ||
| 52 | +d = json.load(open(sys.argv[1])) | ||
| 53 | +assert eval(sys.argv[2], {"d": d}), sys.argv[2] | ||
| 54 | +PY | ||
| 55 | + then pass "$1"; else fail "$1"; fi | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +mcp() { # mcp <state-dir> [env assignments...] -- feeds $TMP/in.jsonl | ||
| 59 | + local dir="$1"; shift | ||
| 60 | + SEQTHINK_STATE_DIR="$dir" env "$@" "$BIN" --mcp < "$TMP/in.jsonl" 2>"$TMP/err.txt" | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +# ---------------------------------------------------------------- build | ||
| 64 | +section "build" | ||
| 65 | +if [ ! -x "$BIN" ]; then | ||
| 66 | + echo " building native binary..." | ||
| 67 | + cc -O2 -std=c99 -Wall -Wextra -I src -I vendor -o "$BIN" src/plugin_seqthink.c vendor/yyjson.c \ | ||
| 68 | + || { echo " build failed"; exit 1; } | ||
| 69 | +fi | ||
| 70 | +[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing" | ||
| 71 | + | ||
| 72 | +SRC=src/plugin_seqthink.c | ||
| 73 | +SRC_TXT=$(cat "$SRC") | ||
| 74 | + | ||
| 75 | +# ---------------------------------------------------------------- mode 1: --meta | ||
| 76 | +section "mode 1 --meta (must work without auth - discovery)" | ||
| 77 | +META=$("$BIN" --meta) | ||
| 78 | +check "meta emits name seqthink" '"name":"seqthink"' "$META" | ||
| 79 | +check "meta emits desc" '"desc":"Thought chains"' "$META" | ||
| 80 | +check "meta declares kind mcp" '"kind":"mcp"' "$META" | ||
| 81 | +check "meta declares mcp true" '"mcp":true' "$META" | ||
| 82 | +check "meta declares daemon false" '"daemon":false' "$META" | ||
| 83 | +check "meta declares menus false" '"menus":false' "$META" | ||
| 84 | +check "meta declares verified" '"verified":"live"' "$META" | ||
| 85 | +METAENV=$(SX_PLUGIN_META=1 "$BIN") | ||
| 86 | +check "SX_PLUGIN_META=1 yields same meta" '"name":"seqthink"' "$METAENV" | ||
| 87 | +[ "$META" = "$METAENV" ] && pass "argv and env meta identical" || fail "argv and env meta differ" | ||
| 88 | +if [ "$(printf '%s\n' "$META" | wc -l)" -eq 1 ]; then pass "meta is exactly one line"; else fail "meta is more than one line"; fi | ||
| 89 | +check "--version names the plugin" "plugin_seqthink" "$("$BIN" --version)" | ||
| 90 | +check "--schema is the input schema" '"required":["thought","nextThoughtNeeded","thoughtNumber","totalThoughts"]' \ | ||
| 91 | + "$("$BIN" --schema)" | ||
| 92 | + | ||
| 93 | +section "plugin.json agrees with --meta" | ||
| 94 | +PJ=$(cat plugin.json) | ||
| 95 | +jq_ "plugin.json slug/id" "d['slug']=='seqthink' and d['id']=='plugin_seqthink'" "$PJ" | ||
| 96 | +jq_ "plugin.json category" "d['category']=='devtools'" "$PJ" | ||
| 97 | +jq_ "plugin.json kind/mcp" "d['kind']=='mcp' and d['mcp'] is True" "$PJ" | ||
| 98 | +jq_ "plugin.json daemon/menus" "d['daemon'] is False and d['menus'] is False" "$PJ" | ||
| 99 | +jq_ "plugin.json verified" "d['verified']=='live'" "$PJ" | ||
| 100 | +jq_ "plugin.json has title/summary/trust" "d['title'] and len(d['summary'])>80 and d['trust_notice']" "$PJ" | ||
| 101 | +check_not "plugin.json has no LAN address" "192.168." "$PJ" | ||
| 102 | + | ||
| 103 | +# ---------------------------------------------------------------- mode 2: --mcp | ||
| 104 | +section "mode 2 --mcp handshake" | ||
| 105 | +cat > "$TMP/in.jsonl" <<'JSONL' | ||
| 106 | +{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"probe","version":"1"}}} | ||
| 107 | +{"jsonrpc":"2.0","method":"notifications/initialized"} | ||
| 108 | +{"jsonrpc":"2.0","id":2,"method":"tools/list"} | ||
| 109 | +{"jsonrpc":"2.0","id":3,"method":"ping"} | ||
| 110 | +{"jsonrpc":"2.0","id":4,"method":"not/a/method"} | ||
| 111 | +JSONL | ||
| 112 | +OUT=$(mcp "$TMP/m_hand" env) | ||
| 113 | +R1=$(printf '%s' "$OUT" | sed -n 1p) | ||
| 114 | +R2=$(printf '%s' "$OUT" | sed -n 2p) | ||
| 115 | +R3=$(printf '%s' "$OUT" | sed -n 3p) | ||
| 116 | +R4=$(printf '%s' "$OUT" | sed -n 4p) | ||
| 117 | +check "initialize answers jsonrpc 2.0" '"jsonrpc":"2.0"' "$R1" | ||
| 118 | +check "initialize echoes id" '"id":1' "$R1" | ||
| 119 | +check "initialize carries protocol" '"protocolVersion":"2024-11-05"' "$R1" | ||
| 120 | +check "initialize advertises tools" '"capabilities":{"tools":{}}' "$R1" | ||
| 121 | +check "initialize names the server" '"name":"seqthink"' "$R1" | ||
| 122 | +check "notifications get no reply" '"id":2' "$R2" | ||
| 123 | +check "tools/list offers sequentialthinking" '"name":"sequentialthinking"' "$R2" | ||
| 124 | +check "tool carries a title" '"title":"Sequential Thinking"' "$R2" | ||
| 125 | +check "tool carries annotations" '"readOnlyHint":false' "$R2" | ||
| 126 | +check "annotations not idempotent" '"idempotentHint":false' "$R2" | ||
| 127 | +check "tool carries inputSchema" '"inputSchema"' "$R2" | ||
| 128 | +check "inputSchema requires 4 fields" '"required":["thought","nextThoughtNeeded","thoughtNumber","totalThoughts"]' "$R2" | ||
| 129 | +check "inputSchema minimum on thoughtNumber" '"thoughtNumber":{"type":"integer"' "$R2" | ||
| 130 | +check "tool carries outputSchema" '"thoughtHistoryLength":{"type":"number"}' "$R2" | ||
| 131 | +check "ping answered empty result" '"result":{}' "$R3" | ||
| 132 | +check "unknown method -> -32601" '"code":-32601' "$R4" | ||
| 133 | + | ||
| 134 | +section "mode 2 --mcp tool: happy path, revision, branch" | ||
| 135 | +cat > "$TMP/in.jsonl" <<'JSONL' | ||
| 136 | +{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"break the problem down","nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":3}}} | ||
| 137 | +{"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"question an earlier step","nextThoughtNeeded":"true","isRevision":true,"revisesThought":1,"thoughtNumber":2,"totalThoughts":3,"needsMoreThoughts":true}}} | ||
| 138 | +{"jsonrpc":"2.0","id":13,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"an alternative path","nextThoughtNeeded":"false","branchFromThought":1,"branchId":"alt-route","thoughtNumber":3,"totalThoughts":3}}} | ||
| 139 | +{"jsonrpc":"2.0","id":14,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"past the estimate","nextThoughtNeeded":false,"thoughtNumber":9,"totalThoughts":3}}} | ||
| 140 | +JSONL | ||
| 141 | +OUT=$(mcp "$TMP/m_ok" env) | ||
| 142 | +L11=$(printf '%s' "$OUT" | sed -n 1p) | ||
| 143 | +L12=$(printf '%s' "$OUT" | sed -n 2p) | ||
| 144 | +L13=$(printf '%s' "$OUT" | sed -n 3p) | ||
| 145 | +L14=$(printf '%s' "$OUT" | sed -n 4p) | ||
| 146 | +check "call 1 content is text" '"type":"text"' "$L11" | ||
| 147 | +check "call 1 reports thoughtNumber" 'thoughtNumber\":1' "$L11" | ||
| 148 | +check "call 1 history length 1" 'thoughtHistoryLength\":1}' "$L11" | ||
| 149 | +check "call 1 not an error" '"isError":false' "$L11" | ||
| 150 | +check "call 1 has structuredContent" '"structuredContent":{"thoughtNumber":1' "$L11" | ||
| 151 | +check "call 2 accepted a string bool" '"isError":false' "$L12" | ||
| 152 | +check "call 2 history length 2" 'thoughtHistoryLength\":2}' "$L12" | ||
| 153 | +check "call 3 records the branch" 'branches\":[\"alt-route\"' "$L13" | ||
| 154 | +check "call 4 raised totalThoughts" 'totalThoughts\":9' "$L14" | ||
| 155 | +check "call 4 kept the branch list" 'alt-route' "$L14" | ||
| 156 | +check "stderr logged thought 1" 'Thought 1/3' "$(cat "$TMP/err.txt")" | ||
| 157 | +check "stderr marked the revision" 'Revision 2/3 (revising thought 1)' "$(cat "$TMP/err.txt")" | ||
| 158 | +check "stderr marked the branch" 'Branch 3/3 (from thought 1, ID: alt-route)' "$(cat "$TMP/err.txt")" | ||
| 159 | +# (structuredContent parity is asserted in detail below) | ||
| 160 | +printf '%s' "$L11" > "$TMP/_c.json" | ||
| 161 | +if python3 - "$TMP/_c.json" <<'PY' 2>/dev/null | ||
| 162 | +import json, sys | ||
| 163 | +d = json.load(open(sys.argv[1])) | ||
| 164 | +r = d["result"] | ||
| 165 | +sc = r["structuredContent"] | ||
| 166 | +txt = json.loads(r["content"][0]["text"]) | ||
| 167 | +assert sc == txt, (sc, txt) | ||
| 168 | +assert sorted(sc) == ["branches", "nextThoughtNeeded", "thoughtHistoryLength", | ||
| 169 | + "thoughtNumber", "totalThoughts"], sorted(sc) | ||
| 170 | +assert sc["thoughtNumber"] == 1 and sc["totalThoughts"] == 3 | ||
| 171 | +assert sc["nextThoughtNeeded"] is True | ||
| 172 | +assert sc["branches"] == [] and sc["thoughtHistoryLength"] == 1 | ||
| 173 | +PY | ||
| 174 | +then pass "structuredContent == parsed content text, exactly 5 fields" | ||
| 175 | +else fail "structuredContent == parsed content text, exactly 5 fields" | ||
| 176 | +fi | ||
| 177 | + | ||
| 178 | +section "mode 2 --mcp tool: validation errors mirror upstream" | ||
| 179 | +cat > "$TMP/in.jsonl" <<'JSONL' | ||
| 180 | +{"jsonrpc":"2.0","id":21,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"","nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":1}}} | ||
| 181 | +{"jsonrpc":"2.0","id":22,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":1}}} | ||
| 182 | +{"jsonrpc":"2.0","id":23,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"thoughtNumber":0,"totalThoughts":1}}} | ||
| 183 | +{"jsonrpc":"2.0","id":24,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"thoughtNumber":"abc","totalThoughts":1}}} | ||
| 184 | +{"jsonrpc":"2.0","id":25,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":0}}} | ||
| 185 | +{"jsonrpc":"2.0","id":26,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":"yes","thoughtNumber":1,"totalThoughts":1}}} | ||
| 186 | +{"jsonrpc":"2.0","id":27,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","thoughtNumber":1,"totalThoughts":1}}} | ||
| 187 | +{"jsonrpc":"2.0","id":28,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"isRevision":"maybe","thoughtNumber":1,"totalThoughts":1}}} | ||
| 188 | +{"jsonrpc":"2.0","id":29,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"revisesThought":0,"thoughtNumber":1,"totalThoughts":1}}} | ||
| 189 | +{"jsonrpc":"2.0","id":30,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"branchFromThought":-2,"thoughtNumber":1,"totalThoughts":1}}} | ||
| 190 | +{"jsonrpc":"2.0","id":31,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"branchId":42,"thoughtNumber":1,"totalThoughts":1}}} | ||
| 191 | +{"jsonrpc":"2.0","id":32,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"needsMoreThoughts":"perhaps","thoughtNumber":1,"totalThoughts":1}}} | ||
| 192 | +{"jsonrpc":"2.0","id":33,"method":"tools/call","params":{"name":"nope","arguments":{}}} | ||
| 193 | +{"jsonrpc":"2.0","id":34,"method":"tools/call","params":{"name":"sequentialthinking"}} | ||
| 194 | +JSONL | ||
| 195 | +OUT=$(mcp "$TMP/m_err" env) | ||
| 196 | +E1=$(printf '%s' "$OUT" | sed -n 1p) | ||
| 197 | +E2=$(printf '%s' "$OUT" | sed -n 2p) | ||
| 198 | +E3=$(printf '%s' "$OUT" | sed -n 3p) | ||
| 199 | +E4=$(printf '%s' "$OUT" | sed -n 4p) | ||
| 200 | +E5=$(printf '%s' "$OUT" | sed -n 5p) | ||
| 201 | +E6=$(printf '%s' "$OUT" | sed -n 6p) | ||
| 202 | +E7=$(printf '%s' "$OUT" | sed -n 7p) | ||
| 203 | +E8=$(printf '%s' "$OUT" | sed -n 8p) | ||
| 204 | +E9=$(printf '%s' "$OUT" | sed -n 9p) | ||
| 205 | +E10=$(printf '%s' "$OUT" | sed -n 10p) | ||
| 206 | +E11=$(printf '%s' "$OUT" | sed -n 11p) | ||
| 207 | +E12=$(printf '%s' "$OUT" | sed -n 12p) | ||
| 208 | +E13=$(printf '%s' "$OUT" | sed -n 13p) | ||
| 209 | +E14=$(printf '%s' "$OUT" | sed -n 14p) | ||
| 210 | +check "empty thought refused" 'Invalid thought: must be a string' "$E1" | ||
| 211 | +check "missing thought refused" 'Invalid thought: must be a string' "$E2" | ||
| 212 | +check "thoughtNumber 0 refused" 'Invalid thoughtNumber: must be a number' "$E3" | ||
| 213 | +check "non-numeric thoughtNumber" 'Invalid thoughtNumber: must be a number' "$E4" | ||
| 214 | +check "totalThoughts 0 refused" 'Invalid totalThoughts: must be a number' "$E5" | ||
| 215 | +check "bad nextThoughtNeeded" 'Invalid nextThoughtNeeded: must be a boolean' "$E6" | ||
| 216 | +check "missing nextThoughtNeeded" 'Invalid nextThoughtNeeded: must be a boolean' "$E7" | ||
| 217 | +check "bad isRevision" 'Invalid isRevision: must be a boolean' "$E8" | ||
| 218 | +check "bad revisesThought" 'Invalid revisesThought: must be a number' "$E9" | ||
| 219 | +check "bad branchFromThought" 'Invalid branchFromThought: must be a number' "$E10" | ||
| 220 | +check "branchId must be a string" 'Invalid branchId: must be a string' "$E11" | ||
| 221 | +check "bad needsMoreThoughts" 'Invalid needsMoreThoughts: must be a boolean' "$E12" | ||
| 222 | +check "all refusals set isError" '"isError":true' "$E1" | ||
| 223 | +check "all refusals say failed" '"status\":\"failed\"' "$E1" | ||
| 224 | +check "unknown tool -> -32602" '"code":-32602' "$E13" | ||
| 225 | +check "missing arguments refused" 'Invalid thought: must be a string' "$E14" | ||
| 226 | +cat > "$TMP/in.jsonl" <<'JSONL' | ||
| 227 | +{"jsonrpc":"2.0","id":41,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"coerce me","nextThoughtNeeded":"TRUE","thoughtNumber":"2","totalThoughts":"4"}}} | ||
| 228 | +JSONL | ||
| 229 | +OUT=$(mcp "$TMP/m_coerce" env) | ||
| 230 | +check "string numbers coerce (upstream z.coerce)" 'totalThoughts\":4' "$OUT" | ||
| 231 | +check "string TRUE coerces to true" 'nextThoughtNeeded\":true' "$OUT" | ||
| 232 | + | ||
| 233 | +section "mode 2 --mcp: history cap and branch eviction" | ||
| 234 | +python3 - > "$TMP/in.jsonl" <<'PY' | ||
| 235 | +import json | ||
| 236 | +print(json.dumps({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"base","nextThoughtNeeded":True,"thoughtNumber":1,"totalThoughts":9}}})) | ||
| 237 | +for i in range(2, 7): | ||
| 238 | + print(json.dumps({"jsonrpc":"2.0","id":i,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"beta%d" % i,"nextThoughtNeeded":True,"branchFromThought":1,"branchId":"beta","thoughtNumber":i,"totalThoughts":9}}})) | ||
| 239 | +for i in range(7, 9): | ||
| 240 | + print(json.dumps({"jsonrpc":"2.0","id":i,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"gamma%d" % i,"nextThoughtNeeded":True,"branchFromThought":1,"branchId":"gamma","thoughtNumber":i,"totalThoughts":9}}})) | ||
| 241 | +PY | ||
| 242 | +OUT=$(mcp "$TMP/m_cap1" MAX_THOUGHT_HISTORY=1) | ||
| 243 | +LAST=$(printf '%s' "$OUT" | tail -1) | ||
| 244 | +check "cap 1 keeps one thought" 'thoughtHistoryLength\":1}' "$LAST" | ||
| 245 | +check "cap 1 emptied beta dropped" 'branches\":[\"gamma\"]' "$LAST" | ||
| 246 | +check_not "cap 1 does not list beta" '\"beta\"' "$LAST" | ||
| 247 | +OUT=$(mcp "$TMP/m_cap2" MAX_THOUGHT_HISTORY=3) | ||
| 248 | +LAST=$(printf '%s' "$OUT" | tail -1) | ||
| 249 | +check "cap 3 keeps three thoughts" 'thoughtHistoryLength\":3}' "$LAST" | ||
| 250 | +check "cap 3 still lists beta" 'beta' "$LAST" | ||
| 251 | +OUT=$(mcp "$TMP/m_bad" MAX_THOUGHT_HISTORY=abc) | ||
| 252 | +check "bad cap warns on stderr" 'MAX_THOUGHT_HISTORY must be a positive integer' "$(cat "$TMP/err.txt")" | ||
| 253 | +check "bad cap falls back to default" "thoughtHistoryLength\\\":1}" "$OUT" | ||
| 254 | +OUT=$(mcp "$TMP/m_neg" MAX_THOUGHT_HISTORY=0) | ||
| 255 | +check "zero cap rejected too" 'must be a positive integer' "$(cat "$TMP/err.txt")" | ||
| 256 | + | ||
| 257 | +section "mode 2 --mcp: DISABLE_THOUGHT_LOGGING (upstream parity)" | ||
| 258 | +OUT=$(mcp "$TMP/m_dis" DISABLE_THOUGHT_LOGGING=true) | ||
| 259 | +check "call still succeeds when logging disabled" '"isError":false' "$OUT" | ||
| 260 | +if [ -s "$TMP/err.txt" ]; then fail "logging silenced on stderr"; else pass "logging silenced on stderr"; fi | ||
| 261 | +if [ -f "$TMP/m_dis/chains.json" ]; then fail "logging disabled also skips persistence"; else pass "logging disabled also skips persistence"; fi | ||
| 262 | +OUT=$(mcp "$TMP/m_dis2" DISABLE_THOUGHT_LOGGING=1) | ||
| 263 | +if [ -s "$TMP/err.txt" ]; then fail "DISABLE_THOUGHT_LOGGING=1 silences stderr"; else pass "DISABLE_THOUGHT_LOGGING=1 silences stderr"; fi | ||
| 264 | + | ||
| 265 | +section "mode 2 --mcp: chains.json snapshot for the viewer" | ||
| 266 | +CHAINJSON="$TMP/m_ok/chains.json" | ||
| 267 | +[ -f "$CHAINJSON" ] && pass "chains.json written" || fail "chains.json missing" | ||
| 268 | +CJ=$(cat "$CHAINJSON" 2>/dev/null || echo '{}') | ||
| 269 | +jq_ "chains.json has one chain" "len(d['chains'])==1" "$CJ" | ||
| 270 | +jq_ "chain keeps 4 thoughts" "d['chains'][0]['count']==4" "$CJ" | ||
| 271 | +jq_ "chain records the branch" "d['chains'][0]['branches']==['alt-route']" "$CJ" | ||
| 272 | +jq_ "thought carries fields" "set(['thought','thought_number','total_thoughts','next_needed','at']) <= set(d['chains'][0]['thoughts'][0])" "$CJ" | ||
| 273 | +jq_ "revision flagged" "d['chains'][0]['thoughts'][1].get('is_revision') is True" "$CJ" | ||
| 274 | +jq_ "revision target recorded" "d['chains'][0]['thoughts'][1]['revises']==1" "$CJ" | ||
| 275 | +jq_ "branch flagged" "d['chains'][0]['thoughts'][2]['branch_id']=='alt-route'" "$CJ" | ||
| 276 | +jq_ "needs_more flagged" "d['chains'][0]['thoughts'][1]['needs_more'] is True" "$CJ" | ||
| 277 | +# a second process must merge, not clobber | ||
| 278 | +cat > "$TMP/in.jsonl" <<'JSONL' | ||
| 279 | +{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"second session","nextThoughtNeeded":false,"thoughtNumber":1,"totalThoughts":1}}} | ||
| 280 | +JSONL | ||
| 281 | +mcp "$TMP/m_ok" env >/dev/null | ||
| 282 | +CJ=$(cat "$CHAINJSON") | ||
| 283 | +jq_ "second session merged" "len(d['chains'])==2" "$CJ" | ||
| 284 | +jq_ "first chain untouched" "any(c['count']==4 for c in d['chains'])" "$CJ" | ||
| 285 | +# malformed store degrades to clean, never a crash or a poisoned file | ||
| 286 | +printf 'not json {{{\n' > "$TMP/m_ok/chains.json" | ||
| 287 | +mcp "$TMP/m_ok" env >/dev/null 2>&1 | ||
| 288 | +check "corrupt store recovered" '"thought"' "$(cat "$TMP/m_ok/chains.json")" | ||
| 289 | +# the file is written .tmp then rename()d | ||
| 290 | +check "persistence uses a temp file" "rename(tmp, path)" "$SRC_TXT" | ||
| 291 | +check_not "persistence never writes the store in place" 'fopen(path, "wb")' "$SRC_TXT" | ||
| 292 | + | ||
| 293 | +# ---------------------------------------------------------------- mode 3: JSON API | ||
| 294 | +section "mode 3 JSON API: authentication" | ||
| 295 | +S="$TMP/api"; mkdir -p "$S" | ||
| 296 | +cat > "$TMP/in.jsonl" <<'JSONL' | ||
| 297 | +{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"alpha one","nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":2}}} | ||
| 298 | +{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"alpha two","nextThoughtNeeded":false,"isRevision":true,"revisesThought":1,"thoughtNumber":2,"totalThoughts":2}}} | ||
| 299 | +JSONL | ||
| 300 | +mcp "$S" env >/dev/null | ||
| 301 | +R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw QUERY_STRING="action=chains" "$BIN"; true) | ||
| 302 | +check "401 without a credential" "Status: 401 Unauthorized" "$R" | ||
| 303 | +check "401 body says invalid" "invalid node password" "$R" | ||
| 304 | +check_not "401 leaks no chains" '"chains":[' "$R" | ||
| 305 | +R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw HTTP_X_BOT_PASSWORD=secretpw QUERY_STRING="action=chains" "$BIN"; true) | ||
| 306 | +check "header credential accepted" '"chains":[' "$R" | ||
| 307 | +R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw HTTP_AUTHORIZATION="Bearer secretpw" QUERY_STRING="action=stats" "$BIN"; true) | ||
| 308 | +check "bearer credential accepted" '"ok":true' "$R" | ||
| 309 | +R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw QUERY_STRING="action=chains&pwd=secretpw" "$BIN"; true) | ||
| 310 | +check "query pwd credential accepted" '"chains":[' "$R" | ||
| 311 | +R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw QUERY_STRING="action=chains&pwd=nope" "$BIN"; true) | ||
| 312 | +check "wrong credential still 401" "Status: 401" "$R" | ||
| 313 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chains" "$BIN"; true) | ||
| 314 | +check "open node (no BOT_PASSWORD) answers" '"chains":[' "$R" | ||
| 315 | +R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw "$BIN" --meta; true) | ||
| 316 | +check "--meta stays unauthenticated" '"name":"seqthink"' "$R" | ||
| 317 | +R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw "$BIN" < /dev/null; true) | ||
| 318 | +check "HTML page stays unauthenticated" "<!DOCTYPE html>" "$R" | ||
| 319 | + | ||
| 320 | +section "mode 3 JSON API: actions" | ||
| 321 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chains" "$BIN"; true) | ||
| 322 | +CB=$(body "$R") | ||
| 323 | +jq_ "chains lists one chain" "d['count']==1" "$CB" | ||
| 324 | +jq_ "chains reports the plugin" "d['plugin']=='plugin_seqthink'" "$CB" | ||
| 325 | +jq_ "chain summary has thoughts" "d['chains'][0]['thoughts']==2" "$CB" | ||
| 326 | +jq_ "chain summary has last_head" "d['chains'][0]['last_head']=='alpha two'" "$CB" | ||
| 327 | +jq_ "chain summary lists branches" "isinstance(d['chains'][0]['branches'], list)" "$CB" | ||
| 328 | +jq_ "chains never leaks an absolute state path" "'/' not in d['state_dir_name']" "$CB" | ||
| 329 | +CID=$(printf '%s' "$CB" | python3 -c "import json,sys;print(json.load(sys.stdin)['chains'][0]['id'])") | ||
| 330 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chain&id=$CID" "$BIN"; true) | ||
| 331 | +DB=$(body "$R") | ||
| 332 | +jq_ "chain returns thoughts" "len(d['thoughts'])==2" "$DB" | ||
| 333 | +jq_ "chain thought text intact" "d['thoughts'][0]['thought']=='alpha one'" "$DB" | ||
| 334 | +jq_ "chain marks the revision" "d['thoughts'][1]['is_revision'] is True" "$DB" | ||
| 335 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chain&id=does-not-exist" "$BIN"; true) | ||
| 336 | +check "unknown chain id -> error" 'chain not found' "$(body "$R")" | ||
| 337 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chain&id=..%2F..%2Fetc%2Fpasswd" "$BIN"; true) | ||
| 338 | +check "path traversal id refused" 'invalid chain id' "$(body "$R")" | ||
| 339 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chain&id=a%3Brm" "$BIN"; true) | ||
| 340 | +check "shell metacharacter id refused" 'invalid chain id' "$(body "$R")" | ||
| 341 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=stats" "$BIN"; true) | ||
| 342 | +SB=$(body "$R") | ||
| 343 | +jq_ "stats counts thoughts" "d['thoughts']==2" "$SB" | ||
| 344 | +jq_ "stats counts chains" "d['chains']==1" "$SB" | ||
| 345 | +jq_ "stats counts revisions" "d['revisions']==1" "$SB" | ||
| 346 | +jq_ "stats reports the cap" "d['max_chains']==50" "$SB" | ||
| 347 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=info" "$BIN"; true) | ||
| 348 | +IB=$(body "$R") | ||
| 349 | +jq_ "info declares kind mcp" "d['kind']=='mcp' and d['mcp'] is True" "$IB" | ||
| 350 | +jq_ "info declares menus false" "d['menus'] is False and d['daemon'] is False" "$IB" | ||
| 351 | +jq_ "info lists the tool" "d['tools']==['sequentialthinking']" "$IB" | ||
| 352 | +jq_ "info carries the schema" "'thought' in d['tool_schema']['properties'] and 'branchId' in d['tool_schema']['properties']" "$IB" | ||
| 353 | +jq_ "info schema requires 4" "sorted(d['tool_schema']['required'])==sorted(['thought','nextThoughtNeeded','thoughtNumber','totalThoughts'])" "$IB" | ||
| 354 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=bogus" "$BIN"; true) | ||
| 355 | +check "unknown action refused" 'unknown action' "$(body "$R")" | ||
| 356 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="format=json" "$BIN"; true) | ||
| 357 | +check "format=json answers JSON" 'Content-Type: application/json' "$R" | ||
| 358 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="format=jsonx" "$BIN"; true) | ||
| 359 | +check "format=jsonx still serves HTML" 'Content-Type: text/html' "$R" | ||
| 360 | +R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=clear" "$BIN"; true) | ||
| 361 | +check "clear needs confirmation" 'confirm=1 required' "$(body "$R")" | ||
| 362 | +[ -f "$S/chains.json" ] && pass "clear refused left the store" || fail "clear refused wiped the store" | ||
| 363 | +printf '{"action":"clear","confirm":"1"}' > "$S/_body.json" | ||
| 364 | +R=$(SEQTHINK_STATE_DIR="$S" REQUEST_METHOD=POST CONTENT_LENGTH=$(wc -c < "$S/_body.json") \ | ||
| 365 | + HTTP_X_BOT_PASSWORD=sh "$BIN" < "$S/_body.json"; true) | ||
| 366 | +check "POST JSON body clear works" '"cleared":true' "$(body "$R")" | ||
| 367 | +[ -f "$S/chains.json" ] && fail "clear removed the store" || pass "clear removed the store" | ||
| 368 | + | ||
| 369 | +section "mode 3 JSON API: bounded store" | ||
| 370 | +S2="$TMP/bound"; mkdir -p "$S2" | ||
| 371 | +i=1 | ||
| 372 | +while [ $i -le 55 ]; do | ||
| 373 | + printf '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"chain %s","nextThoughtNeeded":false,"thoughtNumber":1,"totalThoughts":1}}}\n' "$i" \ | ||
| 374 | + > "$TMP/one.jsonl" | ||
| 375 | + SEQTHINK_STATE_DIR="$S2" env "$BIN" --mcp < "$TMP/one.jsonl" >/dev/null 2>&1 | ||
| 376 | + i=$((i + 1)) | ||
| 377 | +done | ||
| 378 | +BJ=$(cat "$S2/chains.json") | ||
| 379 | +jq_ "store never exceeds 50 chains" "len(d['chains'])<=50" "$BJ" | ||
| 380 | +jq_ "newest chain survived" "any(c['thoughts'][0]['thought']=='chain 55' for c in d['chains'])" "$BJ" | ||
| 381 | + | ||
| 382 | +# ---------------------------------------------------------------- mode 4: HTML | ||
| 383 | +section "mode 4 HTML UI" | ||
| 384 | +Q=$(SEQTHINK_STATE_DIR="$TMP/api" QUERY_STRING="embed=1" "$BIN"; true) | ||
| 385 | +check "html content type" "Content-Type: text/html; charset=utf-8" "$Q" | ||
| 386 | +check "html declares charset" "<meta charset=" "$Q" | ||
| 387 | +check "html has a viewport" "width=device-width" "$Q" | ||
| 388 | +check "html is CSP-locked" "default-src 'none'" "$Q" | ||
| 389 | +check "html sets X-Frame-Options" "X-Frame-Options: SAMEORIGIN" "$Q" | ||
| 390 | +check_not "html never sends Content-Length" "Content-Length:" "$Q" | ||
| 391 | +check_not "html has no CDN script" "<script src=" "$Q" | ||
| 392 | +check_not "html has no cdnjs" "cdnjs" "$Q" | ||
| 393 | +check_not "html has no googleapis" "googleapis" "$Q" | ||
| 394 | +check_not "html has no private IPs" "192.168." "$Q" | ||
| 395 | +check_not "html has no localhost URL" "http://127.0.0.1" "$Q" | ||
| 396 | +check "html has the bot token block" "--bg-card" "$Q" | ||
| 397 | +check "html prepaints the theme" "data-theme" "$Q" | ||
| 398 | +check "html follows the bot" "sx-theme" "$Q" | ||
| 399 | +check "html asks for the theme" "sx-theme-request" "$Q" | ||
| 400 | +check "html flags embed mode" "embedded" "$Q" | ||
| 401 | +check "html names the plugin" "Thought Chains" "$Q" | ||
| 402 | +check "html branches the API route" "/plugin_seqthink?action=" "$Q" | ||
| 403 | +check "html supports the hub proxy route" "/plugins?plugin=" "$Q" | ||
| 404 | +check "html carries the node password" "X-Bot-Password" "$Q" | ||
| 405 | +check "html calls the chains API" "api('chains')" "$Q" | ||
| 406 | +check_not "html has no emoji" "💭" "$Q" | ||
| 407 | +check_not "html has no emoji (revision)" "🔄" "$Q" | ||
| 408 | +check_not "html has no emoji (branch)" "🌿" "$Q" | ||
| 409 | +if grep -qF "💭" src/ui.html; then fail "ui source has no emoji"; else pass "ui source has no emoji"; fi | ||
| 410 | +grep -c "<script>" src/ui.html >/dev/null 2>&1 && pass "ui has its own script tag" || fail "ui script tag missing" | ||
| 411 | +grep -q "<style>" src/ui.html && pass "ui has its own style tag" || fail "ui style tag missing" | ||
| 412 | +check_not "ui has no inline hex palette outside tokens" "#123456" "$Q" | ||
| 413 | +if python3 tools/gen_ui.py --check >/dev/null 2>&1; then | ||
| 414 | + pass "src/ui_html.h is generated from src/ui.html" | ||
| 415 | +else | ||
| 416 | + fail "src/ui_html.h is stale (run tools/gen_ui.py)" | ||
| 417 | +fi | ||
| 418 | + | ||
| 419 | +section "source invariants" | ||
| 420 | +check "_WIN32 forces binary stdout" "_setmode(_fileno(stdout), _O_BINARY)" "$SRC_TXT" | ||
| 421 | +check "_WIN32 gate precedes includes" "_WIN32_WINNT 0x0601" "$SRC_TXT" | ||
| 422 | +check "Apple needs _DARWIN_C_SOURCE" "_DARWIN_C_SOURCE" "$SRC_TXT" | ||
| 423 | +check "meta is emitted before auth" "return run_meta();" "$SRC_TXT" | ||
| 424 | +check "mcp mode is dispatched" "return run_mcp();" "$SRC_TXT" | ||
| 425 | +check_not "no shell command execution" "popen(" "$SRC_TXT" | ||
| 426 | +check_not "no system()" "system(" "$SRC_TXT" | ||
| 427 | +check_not "no sockets" "socket(" "$SRC_TXT" | ||
| 428 | +check_not "no TLS client" "mbedtls" "$SRC_TXT" | ||
| 429 | +check_not "no outbound http helper" "WinHttp" "$SRC_TXT" | ||
| 430 | +check "chain ids are validated" "valid_chain_id" "$SRC_TXT" | ||
| 431 | +check "history cap is bounded" "MAX_THOUGHT_HISTORY" "$SRC_TXT" | ||
| 432 | +check "thought text is length-capped" "THOUGHT_MAX" "$SRC_TXT" | ||
| 433 | +check "branch id is length-capped" "BRANCHID_MAX" "$SRC_TXT" | ||
| 434 | +check "state dir honours the test override" "SEQTHINK_STATE_DIR" "$SRC_TXT" | ||
| 435 | +check "state dir prefers /workspace" "/workspace/.scorpiox/connectors/" "$SRC_TXT" | ||
| 436 | +check "state dir uses LOCALAPPDATA on win" "LOCALAPPDATA" "$SRC_TXT" | ||
| 437 | +printf '%s' "$SRC_TXT" | grep -q getline && pass "mcp loop reads line-delimited stdio" || fail "mcp loop has no line reader" | ||
| 438 | + | ||
| 439 | +section "ASan + fortify (parses files it did not write)" | ||
| 440 | +if [ ! -x ./plugin_seqthink.asan ] || [ "$SRC_TXT" -nt ./plugin_seqthink.asan ]; then | ||
| 441 | + cc -g -O0 -std=c99 -Wall -Wextra -fsanitize=address -I src -I vendor \ | ||
| 442 | + -o plugin_seqthink.asan src/plugin_seqthink.c vendor/yyjson.c >/dev/null 2>&1 \ | ||
| 443 | + || echo " note: ASan build unavailable here" | ||
| 444 | +fi | ||
| 445 | +if [ -x ./plugin_seqthink.asan ]; then | ||
| 446 | + cat > "$TMP/in.jsonl" <<'JSONL' | ||
| 447 | +{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"asan thought with \"quotes\" and \\ backslash and \ntab\t","nextThoughtNeeded":true,"isRevision":true,"revisesThought":1,"thoughtNumber":1,"totalThoughts":2}}} | ||
| 448 | +{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"unicode ünïcødé and émojis ok","nextThoughtNeeded":false,"branchFromThought":1,"branchId":"ünï","thoughtNumber":2,"totalThoughts":2}}} | ||
| 449 | +JSONL | ||
| 450 | + AOUT=$(SEQTHINK_STATE_DIR="$TMP/asan" ./plugin_seqthink.asan --mcp < "$TMP/in.jsonl" 2>"$TMP/aerr.txt") | ||
| 451 | + if grep -q "AddressSanitizer" "$TMP/aerr.txt"; then | ||
| 452 | + fail "ASan reported a problem"; sed -n 1,12p "$TMP/aerr.txt" | ||
| 453 | + else | ||
| 454 | + pass "ASan clean on quotes/backslash/newline/unicode thoughts" | ||
| 455 | + fi | ||
| 456 | + check "ASan run still answered" '"isError":false' "$AOUT" | ||
| 457 | + R=$(SEQTHINK_STATE_DIR="$TMP/asan" QUERY_STRING="action=chains" ./plugin_seqthink.asan; true) | ||
| 458 | + if grep -q "AddressSanitizer" "$TMP/aerr.txt"; then fail "ASan clean on the CGI read path" | ||
| 459 | + else pass "ASan clean on the CGI read path"; fi | ||
| 460 | + printf '{{{ not json' > "$TMP/asan/chains.json" | ||
| 461 | + SEQTHINK_STATE_DIR="$TMP/asan" QUERY_STRING="action=chains" ./plugin_seqthink.asan >/dev/null 2>>"$TMP/aerr.txt" | ||
| 462 | + SEQTHINK_STATE_DIR="$TMP/asan" QUERY_STRING="action=chain&id=th-x" ./plugin_seqthink.asan >/dev/null 2>>"$TMP/aerr.txt" | ||
| 463 | + printf '{"chains":[{"id":42,"thoughts":"not an array"},{"thoughts":[]}]}' > "$TMP/asan/chains.json" | ||
| 464 | + SEQTHINK_STATE_DIR="$TMP/asan" QUERY_STRING="action=stats" ./plugin_seqthink.asan >/dev/null 2>>"$TMP/aerr.txt" | ||
| 465 | + if grep -q "AddressSanitizer" "$TMP/aerr.txt"; then fail "ASan clean on malformed stores" | ||
| 466 | + else pass "ASan clean on malformed stores"; fi | ||
| 467 | +else | ||
| 468 | + echo " skip ASan checks (build unavailable)" | ||
| 469 | +fi | ||
| 470 | + | ||
| 471 | +if [ ! -x ./plugin_seqthink.fortify ]; then | ||
| 472 | + cc -O2 -std=c99 -Wall -Wextra -D_FORTIFY_SOURCE=2 -I src -I vendor \ | ||
| 473 | + -o plugin_seqthink.fortify src/plugin_seqthink.c vendor/yyjson.c >/dev/null 2>&1 \ | ||
| 474 | + || echo " note: fortify build unavailable here" | ||
| 475 | +fi | ||
| 476 | +if [ -x ./plugin_seqthink.fortify ]; then | ||
| 477 | + SEQTHINK_STATE_DIR="$TMP/fort" ./plugin_seqthink.fortify --mcp < "$TMP/in.jsonl" >/dev/null 2>"$TMP/ferr.txt" | ||
| 478 | + if grep -qi "buffer overflow" "$TMP/ferr.txt"; then fail "fortify build aborted" | ||
| 479 | + else pass "fortify build survives the full session"; fi | ||
| 480 | +else | ||
| 481 | + echo " skip fortify checks (build unavailable)" | ||
| 482 | +fi | ||
| 483 | + | ||
| 484 | +# ---------------------------------------------------------------- audit | ||
| 485 | +section "clean-room audit (working tree + full git history)" | ||
| 486 | +audit() { # audit <label> <regex> | ||
| 487 | + local out | ||
| 488 | + out=$(git grep -InE -e "$2" -- . 2>/dev/null | grep -v 'tests/run.sh' | head -5 || true) | ||
| 489 | + if [ -n "$out" ]; then | ||
| 490 | + fail "audit: $1"; printf '%s\n' "$out" | sed 's/^/ /' | ||
| 491 | + else | ||
| 492 | + pass "audit: $1" | ||
| 493 | + fi | ||
| 494 | +} | ||
| 495 | +audit "no LAN 192.168 addresses" '192\.168\.[0-9]+\.[0-9]+' | ||
| 496 | +audit "no private 10.x addresses" '\b10\.[0-9]+\.[0-9]+\.[0-9]+' | ||
| 497 | +PAT="gh""p_[A-Za-z0-9]{36}" | ||
| 498 | +audit "no PAT prefix" "$PAT" | ||
| 499 | +TOK="3e""f2c00c" | ||
| 500 | +audit "no token prefix" "$TOK" | ||
| 501 | +SFP="ssh""pass -p " | ||
| 502 | +audit "no ssh password flag" "$SFP" | ||
| 503 | +HOSTS="macm""ini|intel-""ultra""2|lazar""us" | ||
| 504 | +audit "no internal hostnames" "$HOSTS" | ||
| 505 | +if ! git rev-parse HEAD >/dev/null 2>&1; then | ||
| 506 | + echo " skip git-history audit (repository has no commits yet)" | ||
| 507 | +elif command -v scorpiox-cli-botplugin >/dev/null 2>&1; then | ||
| 508 | + if scorpiox-cli-botplugin audit "$ROOT" >/dev/null 2>&1; then | ||
| 509 | + pass "scorpiox-cli-botplugin audit accepts the repo" | ||
| 510 | + else | ||
| 511 | + fail "scorpiox-cli-botplugin audit rejected the repo" | ||
| 512 | + scorpiox-cli-botplugin audit "$ROOT" 2>&1 | tail -10 | sed 's/^/ /' | ||
| 513 | + fi | ||
| 514 | +else | ||
| 515 | + echo " skip scorpiox-cli-botplugin audit (not installed here)" | ||
| 516 | +fi | ||
| 517 | + | ||
| 518 | +printf '\n%s==============================%s\n' "$C_B" "$C_0" | ||
| 519 | +printf ' %s%d passed%s %s%d failed%s\n' "$C_OK" "$PASS" "$C_0" "$([ "$FAIL" -gt 0 ] && printf '%s' "$C_BAD" || printf '%s')" "$FAIL" "$C_0" | ||
| 520 | +[ "$FAIL" -eq 0 ] || exit 1 | ||
| 521 | +exit 0 |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..69b1759 | index 0000000..69b1759 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/tools/gen_ui.py | +++ b/tools/gen_ui.py | ||
| @@ -0,0 +1,105 @@ | @@ -0,0 +1,105 @@ | ||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""tools/gen_ui.py - compile src/ui.html into src/ui_html.h. | ||
| 3 | + | ||
| 4 | +The page lives in one readable file (src/ui.html) so it can be diffed and | ||
| 5 | +reviewed like any other source. This script turns it into a single C string | ||
| 6 | +constant with two control-character placeholders: | ||
| 7 | + | ||
| 8 | + 0x01 -> the bot theme prepaint script + <style> + theme tokens | ||
| 9 | + 0x02 -> the bot theme handoff script (just before </body>) | ||
| 10 | + | ||
| 11 | +main() splits the constant on those bytes and emits the macros from | ||
| 12 | +src/bot_theme_plugin.h in their place, so the theme can never drift out of | ||
| 13 | +sync with the rest of the bot. | ||
| 14 | + | ||
| 15 | + python3 tools/gen_ui.py # write src/ui_html.h | ||
| 16 | + python3 tools/gen_ui.py --check # exit 1 when the header is stale | ||
| 17 | +""" | ||
| 18 | + | ||
| 19 | +import os | ||
| 20 | +import sys | ||
| 21 | + | ||
| 22 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 23 | +SRC = os.path.join(ROOT, "src", "ui.html") | ||
| 24 | +OUT = os.path.join(ROOT, "src", "ui_html.h") | ||
| 25 | + | ||
| 26 | +TOKENS = "<!--TOKENS-->" | ||
| 27 | +MARK_TOKENS = "\u0001" | ||
| 28 | +MARK_HANDOFF = "\u0002" | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def c_literal(text): | ||
| 32 | + """Escape text for a C string literal, one line per source line.""" | ||
| 33 | + out = [] | ||
| 34 | + for line in text.splitlines(True): | ||
| 35 | + piece = [] | ||
| 36 | + for ch in line: | ||
| 37 | + if ch == "\\": | ||
| 38 | + piece.append("\\\\") | ||
| 39 | + elif ch == '"': | ||
| 40 | + piece.append('\\"') | ||
| 41 | + elif ch == "\n": | ||
| 42 | + piece.append("\\n") | ||
| 43 | + elif ch == "\r": | ||
| 44 | + piece.append("\\r") | ||
| 45 | + elif ch == "\t": | ||
| 46 | + piece.append("\\t") | ||
| 47 | + elif ch == MARK_TOKENS: | ||
| 48 | + piece.append("\\001") | ||
| 49 | + elif ch == MARK_HANDOFF: | ||
| 50 | + piece.append("\\002") | ||
| 51 | + elif ord(ch) < 0x20: | ||
| 52 | + piece.append("\\%03o" % ord(ch)) | ||
| 53 | + else: | ||
| 54 | + piece.append(ch) | ||
| 55 | + out.append(' "%s"\n' % "".join(piece)) | ||
| 56 | + return "".join(out) | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def render(): | ||
| 60 | + with open(SRC, "r", encoding="utf-8") as f: | ||
| 61 | + html = f.read() | ||
| 62 | + | ||
| 63 | + if TOKENS not in html: | ||
| 64 | + raise SystemExit("src/ui.html has no %s placeholder" % TOKENS) | ||
| 65 | + html = html.replace(TOKENS, MARK_TOKENS) | ||
| 66 | + | ||
| 67 | + # Handoff script goes right before the closing body tag. | ||
| 68 | + if "</body>" not in html: | ||
| 69 | + raise SystemExit("src/ui.html has no </body>") | ||
| 70 | + html = html.replace("</body>", MARK_HANDOFF + "</body>", 1) | ||
| 71 | + | ||
| 72 | + header = ( | ||
| 73 | + "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n" | ||
| 74 | + "#ifndef SX_SEQTHINK_UI_HTML_H\n" | ||
| 75 | + "#define SX_SEQTHINK_UI_HTML_H\n" | ||
| 76 | + "\n" | ||
| 77 | + "static const char *UI_HTML =\n" + c_literal(html) + " ;\n" | ||
| 78 | + "\n" | ||
| 79 | + "#endif /* SX_SEQTHINK_UI_HTML_H */\n" | ||
| 80 | + ) | ||
| 81 | + return header | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def main(): | ||
| 85 | + header = render() | ||
| 86 | + check = "--check" in sys.argv[1:] | ||
| 87 | + if check: | ||
| 88 | + try: | ||
| 89 | + with open(OUT, "r", encoding="utf-8") as f: | ||
| 90 | + cur = f.read() | ||
| 91 | + except OSError: | ||
| 92 | + cur = "" | ||
| 93 | + if cur != header: | ||
| 94 | + sys.stderr.write("src/ui_html.h is stale - run tools/gen_ui.py\n") | ||
| 95 | + return 1 | ||
| 96 | + print("src/ui_html.h is up to date") | ||
| 97 | + return 0 | ||
| 98 | + with open(OUT, "w", encoding="utf-8") as f: | ||
| 99 | + f.write(header) | ||
| 100 | + print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header))) | ||
| 101 | + return 0 | ||
| 102 | + | ||
| 103 | + | ||
| 104 | +if __name__ == "__main__": | ||
| 105 | + sys.exit(main()) |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..d1ee097 | index 0000000..d1ee097 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/vendor/LICENSE.yyjson.txt | +++ b/vendor/LICENSE.yyjson.txt | ||
| @@ -0,0 +1,21 @@ | @@ -0,0 +1,21 @@ | ||
| 1 | +MIT License | ||
| 2 | + | ||
| 3 | +Copyright (c) 2020 YaoYuan <ibireme@gmail.com> | ||
| 4 | + | ||
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 6 | +of this software and associated documentation files (the "Software"), to deal | ||
| 7 | +in the Software without restriction, including without limitation the rights | ||
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 9 | +copies of the Software, and to permit persons to whom the Software is | ||
| 10 | +furnished to do so, subject to the following conditions: | ||
| 11 | + | ||
| 12 | +The above copyright notice and this permission notice shall be included in all | ||
| 13 | +copies or substantial portions of the Software. | ||
| 14 | + | ||
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 21 | +SOFTWARE. |
| 1 | new file mode 100644 | 1 | new file mode 100644 |
| index 0000000..9c445e8 | index 0000000..9c445e8 | ||
| --- /dev/null | --- /dev/null | ||
| +++ b/vendor/yyjson.c | +++ b/vendor/yyjson.c | ||
| @@ -0,0 +1,11224 @@ | @@ -0,0 +1,11224 @@ | ||
| 1 | +/*============================================================================== | ||
| 2 | + Copyright (c) 2020 YaoYuan <ibireme@gmail.com> | ||
| 3 | + | ||
| 4 | + Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 5 | + of this software and associated documentation files (the "Software"), to deal | ||
| 6 | + in the Software without restriction, including without limitation the rights | ||
| 7 | + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 8 | + copies of the Software, and to permit persons to whom the Software is | ||
| 9 | + furnished to do so, subject to the following conditions: | ||
| 10 | + | ||
| 11 | + The above copyright notice and this permission notice shall be included in all | ||
| 12 | + copies or substantial portions of the Software. | ||
| 13 | + | ||
| 14 | + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 15 | + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 16 | + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 17 | + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 18 | + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 19 | + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 20 | + SOFTWARE. | ||
| 21 | + *============================================================================*/ | ||
| 22 | + | ||
| 23 | +#include "yyjson.h" | ||
| 24 | +#include <math.h> /* for `HUGE_VAL/INFINIY/NAN` macros, no libm required */ | ||
| 25 | + | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +/*============================================================================== | ||
| 29 | + * MARK: - Warning Suppress (Private) | ||
| 30 | + *============================================================================*/ | ||
| 31 | + | ||
| 32 | +#if defined(__clang__) | ||
| 33 | +# pragma clang diagnostic ignored "-Wunused-function" | ||
| 34 | +# pragma clang diagnostic ignored "-Wunused-parameter" | ||
| 35 | +# pragma clang diagnostic ignored "-Wunused-label" | ||
| 36 | +# pragma clang diagnostic ignored "-Wunused-macros" | ||
| 37 | +# pragma clang diagnostic ignored "-Wunused-variable" | ||
| 38 | +#elif YYJSON_IS_REAL_GCC | ||
| 39 | +# pragma GCC diagnostic ignored "-Wunused-function" | ||
| 40 | +# pragma GCC diagnostic ignored "-Wunused-parameter" | ||
| 41 | +# pragma GCC diagnostic ignored "-Wunused-label" | ||
| 42 | +# pragma GCC diagnostic ignored "-Wunused-macros" | ||
| 43 | +# pragma GCC diagnostic ignored "-Wunused-variable" | ||
| 44 | +#elif defined(_MSC_VER) | ||
| 45 | +# pragma warning(disable:4100) /* unreferenced formal parameter */ | ||
| 46 | +# pragma warning(disable:4101) /* unreferenced variable */ | ||
| 47 | +# pragma warning(disable:4102) /* unreferenced label */ | ||
| 48 | +# pragma warning(disable:4127) /* conditional expression is constant */ | ||
| 49 | +# pragma warning(disable:4702) /* unreachable code */ | ||
| 50 | +# pragma warning(disable:4706) /* assignment within conditional expression */ | ||
| 51 | +#endif | ||
| 52 | + | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +/*============================================================================== | ||
| 56 | + * MARK: - Version (Public) | ||
| 57 | + *============================================================================*/ | ||
| 58 | + | ||
| 59 | +uint32_t yyjson_version(void) { | ||
| 60 | + return YYJSON_VERSION_HEX; | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +/*============================================================================== | ||
| 66 | + * MARK: - Flags (Private) | ||
| 67 | + *============================================================================*/ | ||
| 68 | + | ||
| 69 | +/* msvc intrinsic */ | ||
| 70 | +#if YYJSON_MSC_VER >= 1400 | ||
| 71 | +# include <intrin.h> | ||
| 72 | +# if defined(_M_AMD64) || defined(_M_ARM64) | ||
| 73 | +# define MSC_HAS_BIT_SCAN_64 1 | ||
| 74 | +# pragma intrinsic(_BitScanForward64) | ||
| 75 | +# pragma intrinsic(_BitScanReverse64) | ||
| 76 | +# else | ||
| 77 | +# define MSC_HAS_BIT_SCAN_64 0 | ||
| 78 | +# endif | ||
| 79 | +# if defined(_M_AMD64) || defined(_M_ARM64) || \ | ||
| 80 | + defined(_M_IX86) || defined(_M_ARM) | ||
| 81 | +# define MSC_HAS_BIT_SCAN 1 | ||
| 82 | +# pragma intrinsic(_BitScanForward) | ||
| 83 | +# pragma intrinsic(_BitScanReverse) | ||
| 84 | +# else | ||
| 85 | +# define MSC_HAS_BIT_SCAN 0 | ||
| 86 | +# endif | ||
| 87 | +# if defined(_M_AMD64) | ||
| 88 | +# define MSC_HAS_UMUL128 1 | ||
| 89 | +# pragma intrinsic(_umul128) | ||
| 90 | +# else | ||
| 91 | +# define MSC_HAS_UMUL128 0 | ||
| 92 | +# endif | ||
| 93 | +#else | ||
| 94 | +# define MSC_HAS_BIT_SCAN_64 0 | ||
| 95 | +# define MSC_HAS_BIT_SCAN 0 | ||
| 96 | +# define MSC_HAS_UMUL128 0 | ||
| 97 | +#endif | ||
| 98 | + | ||
| 99 | +/* gcc builtin */ | ||
| 100 | +#if yyjson_has_builtin(__builtin_clzll) || yyjson_gcc_available(3, 4, 0) | ||
| 101 | +# define GCC_HAS_CLZLL 1 | ||
| 102 | +#else | ||
| 103 | +# define GCC_HAS_CLZLL 0 | ||
| 104 | +#endif | ||
| 105 | + | ||
| 106 | +#if yyjson_has_builtin(__builtin_ctzll) || yyjson_gcc_available(3, 4, 0) | ||
| 107 | +# define GCC_HAS_CTZLL 1 | ||
| 108 | +#else | ||
| 109 | +# define GCC_HAS_CTZLL 0 | ||
| 110 | +#endif | ||
| 111 | + | ||
| 112 | +/* int128 type */ | ||
| 113 | +#if defined(__SIZEOF_INT128__) && (__SIZEOF_INT128__ == 16) && \ | ||
| 114 | + (defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER)) | ||
| 115 | +# define YYJSON_HAS_INT128 1 | ||
| 116 | +#else | ||
| 117 | +# define YYJSON_HAS_INT128 0 | ||
| 118 | +#endif | ||
| 119 | + | ||
| 120 | +/* IEEE 754 floating-point binary representation */ | ||
| 121 | +#if defined(__STDC_IEC_559__) || defined(__STDC_IEC_60559_BFP__) | ||
| 122 | +# define YYJSON_HAS_IEEE_754 1 | ||
| 123 | +#elif FLT_RADIX == 2 && \ | ||
| 124 | + FLT_MANT_DIG == 24 && FLT_DIG == 6 && \ | ||
| 125 | + FLT_MIN_EXP == -125 && FLT_MAX_EXP == 128 && \ | ||
| 126 | + FLT_MIN_10_EXP == -37 && FLT_MAX_10_EXP == 38 && \ | ||
| 127 | + DBL_MANT_DIG == 53 && DBL_DIG == 15 && \ | ||
| 128 | + DBL_MIN_EXP == -1021 && DBL_MAX_EXP == 1024 && \ | ||
| 129 | + DBL_MIN_10_EXP == -307 && DBL_MAX_10_EXP == 308 | ||
| 130 | +# define YYJSON_HAS_IEEE_754 1 | ||
| 131 | +#else | ||
| 132 | +# define YYJSON_HAS_IEEE_754 0 | ||
| 133 | +# undef YYJSON_DISABLE_FAST_FP_CONV | ||
| 134 | +# define YYJSON_DISABLE_FAST_FP_CONV 1 | ||
| 135 | +#endif | ||
| 136 | + | ||
| 137 | +/* | ||
| 138 | + Correct rounding in double number computations. | ||
| 139 | + | ||
| 140 | + On the x86 architecture, some compilers may use x87 FPU instructions for | ||
| 141 | + floating-point arithmetic. The x87 FPU loads all floating point number as | ||
| 142 | + 80-bit double-extended precision internally, then rounds the result to original | ||
| 143 | + precision, which may produce inaccurate results. For a more detailed | ||
| 144 | + explanation, see the paper: https://arxiv.org/abs/cs/0701192 | ||
| 145 | + | ||
| 146 | + Here are some examples of double precision calculation error: | ||
| 147 | + | ||
| 148 | + 2877.0 / 1e6 == 0.002877, but x87 returns 0.0028770000000000002 | ||
| 149 | + 43683.0 * 1e21 == 4.3683e25, but x87 returns 4.3683000000000004e25 | ||
| 150 | + | ||
| 151 | + Here are some examples of compiler flags to generate x87 instructions on x86: | ||
| 152 | + | ||
| 153 | + clang -m32 -mno-sse | ||
| 154 | + gcc/icc -m32 -mfpmath=387 | ||
| 155 | + msvc /arch:SSE or /arch:IA32 | ||
| 156 | + | ||
| 157 | + If we are sure that there's no similar error described above, we can define the | ||
| 158 | + YYJSON_DOUBLE_MATH_CORRECT as 1 to enable the fast path calculation. This is | ||
| 159 | + not an accurate detection, it's just try to avoid the error at compile-time. | ||
| 160 | + An accurate detection can be done at run-time: | ||
| 161 | + | ||
| 162 | + bool is_double_math_correct(void) { | ||
| 163 | + volatile double r = 43683.0; | ||
| 164 | + r *= 1e21; | ||
| 165 | + return r == 4.3683e25; | ||
| 166 | + } | ||
| 167 | + | ||
| 168 | + See also: utils.h in https://github.com/google/double-conversion/ | ||
| 169 | + */ | ||
| 170 | +#if !defined(FLT_EVAL_METHOD) && defined(__FLT_EVAL_METHOD__) | ||
| 171 | +# define FLT_EVAL_METHOD __FLT_EVAL_METHOD__ | ||
| 172 | +#endif | ||
| 173 | + | ||
| 174 | +#if defined(FLT_EVAL_METHOD) && FLT_EVAL_METHOD != 0 && FLT_EVAL_METHOD != 1 | ||
| 175 | +# define YYJSON_DOUBLE_MATH_CORRECT 0 | ||
| 176 | +#elif defined(i386) || defined(__i386) || defined(__i386__) || \ | ||
| 177 | + defined(_X86_) || defined(__X86__) || defined(_M_IX86) || \ | ||
| 178 | + defined(__I86__) || defined(__IA32__) || defined(__THW_INTEL) | ||
| 179 | +# if (defined(_MSC_VER) && defined(_M_IX86_FP) && _M_IX86_FP == 2) || \ | ||
| 180 | + (defined(__SSE2_MATH__) && __SSE2_MATH__) | ||
| 181 | +# define YYJSON_DOUBLE_MATH_CORRECT 1 | ||
| 182 | +# else | ||
| 183 | +# define YYJSON_DOUBLE_MATH_CORRECT 0 | ||
| 184 | +# endif | ||
| 185 | +#elif defined(__mc68000__) || defined(__pnacl__) || defined(__native_client__) | ||
| 186 | +# define YYJSON_DOUBLE_MATH_CORRECT 0 | ||
| 187 | +#else | ||
| 188 | +# define YYJSON_DOUBLE_MATH_CORRECT 1 | ||
| 189 | +#endif | ||
| 190 | + | ||
| 191 | +/* | ||
| 192 | + Detect the endianness at compile-time. | ||
| 193 | + YYJSON_ENDIAN == YYJSON_BIG_ENDIAN | ||
| 194 | + YYJSON_ENDIAN == YYJSON_LITTLE_ENDIAN | ||
| 195 | + */ | ||
| 196 | +#define YYJSON_BIG_ENDIAN 4321 | ||
| 197 | +#define YYJSON_LITTLE_ENDIAN 1234 | ||
| 198 | + | ||
| 199 | +#if yyjson_has_include(<sys/types.h>) | ||
| 200 | +# include <sys/types.h> /* POSIX */ | ||
| 201 | +#endif | ||
| 202 | +#if yyjson_has_include(<endian.h>) | ||
| 203 | +# include <endian.h> /* Linux */ | ||
| 204 | +#elif yyjson_has_include(<sys/endian.h>) | ||
| 205 | +# include <sys/endian.h> /* BSD, Android */ | ||
| 206 | +#elif yyjson_has_include(<machine/endian.h>) | ||
| 207 | +# include <machine/endian.h> /* BSD, Darwin */ | ||
| 208 | +#endif | ||
| 209 | + | ||
| 210 | +#if defined(BYTE_ORDER) && BYTE_ORDER | ||
| 211 | +# if defined(BIG_ENDIAN) && (BYTE_ORDER == BIG_ENDIAN) | ||
| 212 | +# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN | ||
| 213 | +# elif defined(LITTLE_ENDIAN) && (BYTE_ORDER == LITTLE_ENDIAN) | ||
| 214 | +# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN | ||
| 215 | +# endif | ||
| 216 | +#elif defined(__BYTE_ORDER) && __BYTE_ORDER | ||
| 217 | +# if defined(__BIG_ENDIAN) && (__BYTE_ORDER == __BIG_ENDIAN) | ||
| 218 | +# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN | ||
| 219 | +# elif defined(__LITTLE_ENDIAN) && (__BYTE_ORDER == __LITTLE_ENDIAN) | ||
| 220 | +# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN | ||
| 221 | +# endif | ||
| 222 | +#elif defined(__BYTE_ORDER__) && __BYTE_ORDER__ | ||
| 223 | +# if defined(__ORDER_BIG_ENDIAN__) && \ | ||
| 224 | + (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) | ||
| 225 | +# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN | ||
| 226 | +# elif defined(__ORDER_LITTLE_ENDIAN__) && \ | ||
| 227 | + (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) | ||
| 228 | +# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN | ||
| 229 | +# endif | ||
| 230 | +#elif (defined(__LITTLE_ENDIAN__) && __LITTLE_ENDIAN__ == 1) || \ | ||
| 231 | + defined(__i386) || defined(__i386__) || \ | ||
| 232 | + defined(_X86_) || defined(__X86__) || \ | ||
| 233 | + defined(_M_IX86) || defined(__THW_INTEL__) || \ | ||
| 234 | + defined(__x86_64) || defined(__x86_64__) || \ | ||
| 235 | + defined(__amd64) || defined(__amd64__) || \ | ||
| 236 | + defined(_M_AMD64) || defined(_M_X64) || \ | ||
| 237 | + defined(_M_ARM) || defined(_M_ARM64) || \ | ||
| 238 | + defined(__ARMEL__) || defined(__THUMBEL__) || defined(__AARCH64EL__) || \ | ||
| 239 | + defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) || \ | ||
| 240 | + defined(__EMSCRIPTEN__) || defined(__wasm__) || \ | ||
| 241 | + defined(__loongarch__) | ||
| 242 | +# define YYJSON_ENDIAN YYJSON_LITTLE_ENDIAN | ||
| 243 | +#elif (defined(__BIG_ENDIAN__) && __BIG_ENDIAN__ == 1) || \ | ||
| 244 | + defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || \ | ||
| 245 | + defined(_MIPSEB) || defined(__MIPSEB) || defined(__MIPSEB__) || \ | ||
| 246 | + defined(__or1k__) || defined(__OR1K__) | ||
| 247 | +# define YYJSON_ENDIAN YYJSON_BIG_ENDIAN | ||
| 248 | +#else | ||
| 249 | +# define YYJSON_ENDIAN 0 /* unknown endian, detect at run-time */ | ||
| 250 | +#endif | ||
| 251 | + | ||
| 252 | +/* | ||
| 253 | + This macro controls how yyjson handles unaligned memory accesses. | ||
| 254 | + | ||
| 255 | + By default, yyjson uses `memcpy()` for memory copying. This allows the compiler | ||
| 256 | + to optimize the code and emit unaligned memory access instructions when | ||
| 257 | + supported by the target architecture. | ||
| 258 | + | ||
| 259 | + However, on some older compilers or architectures where `memcpy()` is not | ||
| 260 | + well-optimized and may result in unnecessary function calls, defining this | ||
| 261 | + macro as 1 may help. In such cases, yyjson switches to manual byte-by-byte | ||
| 262 | + access, which can potentially improve performance. | ||
| 263 | + | ||
| 264 | + An example of the generated assembly code for ARM can be found here: | ||
| 265 | + https://godbolt.org/z/334jjhxPT | ||
| 266 | + | ||
| 267 | + This flag is already enabled for common architectures in the following code, | ||
| 268 | + so manual configuration is usually unnecessary. If unsure, you can check the | ||
| 269 | + generated assembly or run benchmarks to make an informed decision. | ||
| 270 | + */ | ||
| 271 | +#ifndef YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS | ||
| 272 | +# if defined(__ia64) || defined(_IA64) || defined(__IA64__) || \ | ||
| 273 | + defined(__ia64__) || defined(_M_IA64) || defined(__itanium__) | ||
| 274 | +# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* Itanium */ | ||
| 275 | +# elif (defined(__arm__) || defined(__arm64__) || defined(__aarch64__)) && \ | ||
| 276 | + (defined(__GNUC__) || defined(__clang__)) && \ | ||
| 277 | + (!defined(__ARM_FEATURE_UNALIGNED) || !__ARM_FEATURE_UNALIGNED) | ||
| 278 | +# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* ARM */ | ||
| 279 | +# elif defined(__sparc) || defined(__sparc__) | ||
| 280 | +# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* SPARC */ | ||
| 281 | +# elif defined(__mips) || defined(__mips__) || defined(__MIPS__) | ||
| 282 | +# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* MIPS */ | ||
| 283 | +# elif defined(__m68k__) || defined(M68000) | ||
| 284 | +# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 1 /* M68K */ | ||
| 285 | +# else | ||
| 286 | +# define YYJSON_DISABLE_UNALIGNED_MEMORY_ACCESS 0 | ||
| 287 | +# endif | ||
| 288 | +#endif | ||
| 289 | + | ||
| 290 | +/* | ||
| 291 | + Estimated initial ratio of the JSON data (data_size / value_count). | ||
| 292 | + For example: | ||
| 293 | + | ||
| 294 | + data: {"id":12345678,"name":"Harry"} | ||
| 295 | + data_size: 30 | ||
| 296 | + value_count: 5 | ||
| 297 | + ratio: 6 | ||
| 298 | + | ||
| 299 | + yyjson uses dynamic memory with a growth factor of 1.5 when reading and writing | ||
| 300 | + JSON, the ratios below are used to determine the initial memory size. | ||
| 301 | + | ||
| 302 | + A too large ratio will waste memory, and a too small ratio will cause multiple | ||
| 303 | + memory growths and degrade performance. Currently, these ratios are generated | ||
| 304 | + with some commonly used JSON datasets. | ||
| 305 | + */ | ||
| 306 | +#define YYJSON_READER_ESTIMATED_PRETTY_RATIO 16 | ||
| 307 | +#define YYJSON_READER_ESTIMATED_MINIFY_RATIO 6 | ||
| 308 | +#define YYJSON_WRITER_ESTIMATED_PRETTY_RATIO 32 | ||
| 309 | +#define YYJSON_WRITER_ESTIMATED_MINIFY_RATIO 18 | ||
| 310 | + | ||
| 311 | +/* The initial and maximum size of the memory pool's chunk in yyjson_mut_doc. */ | ||
| 312 | +#define YYJSON_MUT_DOC_STR_POOL_INIT_SIZE 0x100 | ||
| 313 | +#define YYJSON_MUT_DOC_STR_POOL_MAX_SIZE 0x1 |