plugin_filesystem 1.0.0 - allowlisted filesystem MCP connector
Clean-room C99 port of modelcontextprotocol/servers src/filesystem: 11 sandboxed tools over MCP stdio JSON-RPC 2.0 (--mcp), --meta discovery contract (kind:mcp, menus:false, verified:live), a node-auth CGI Allowed Roots & Permissions UI, atomic writes, deny list, per-tool permissions and a 299-check offline suite (ASan/UBSan + hardened builds).
AuthorPico <picobot@scorpioplayer.com>
Date2026-11-13 21:19:28
Commitbab80c2c
Changed files
.gitignore+11−0■■■■■
LICENSE+21−0■■■■■
Makefile+97−0■■■■■
README.md+200−0■■■■■
plugin.json+23−0■■■■■
release-dist.sh+41−0■■■■■
src/bot_theme_plugin.h+129−0■■■■■
src/plugin_filesystem.c+3497−0■■■■■
src/ui.html+290−0■■■■■
src/ui_html.h+298−0■■■■■
tests/e2e.py+270−0■■■■■
tests/mcp.py+106−0■■■■■
tests/run.sh+994−0■■■■■
tools/gen_ui.py+105−0■■■■■
vendor/yyjson/yyjson.c+11224−0■■■■■
vendor/yyjson/yyjson.h+8332−0■■■■■
16 files+25638−0
Diff
Diff truncated at 200 KB
.gitignore+11−0■■■■■
11new file mode 100644
index 0000000..f50ba63
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,11 @@
1+/plugin_filesystem
2+/plugin_filesystem.exe
3+/plugin_filesystem.musl
4+/plugin_filesystem.arm64
5+/plugin_filesystem-asan
6+/plugin_filesystem-fortify
7+*.o
8+*.tmp
9+*.tmp-*
10+bin/
11+__pycache__/
LICENSE+21−0■■■■■
11new file mode 100644
index 0000000..ef80120
--- /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.
Makefile+97−0■■■■■
11new file mode 100644
index 0000000..507aeb4
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,97 @@
1+# plugin_filesystem - SCORPIOX BOT open-source allowlisted filesystem MCP connector
2+#
3+# The only non-stdlib dependency is the vendored yyjson JSON parser under
4+# vendor/yyjson (MIT, upstream yyjson/yyjson); it is compiled into the binary,
5+# so every artefact stays a standalone executable with zero shared-library
6+# requirements on the node.
7+#
8+# Targets:
9+# make native build -> ./plugin_filesystem
10+# make musl static musl x86_64 -> ./plugin_filesystem.musl
11+# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_filesystem.arm64
12+# make win64 MinGW-w64 static -> ./plugin_filesystem.exe
13+# make macos Apple clang -> ./plugin_filesystem (run this on macOS)
14+# make asan ASan + UBSan build (tests/run.sh drives the whole tool set through it)
15+# make fortify -D_FORTIFY_SOURCE=2 build
16+# make ui regenerate src/ui_html.h from src/ui.html
17+# make test build + run tests/run.sh
18+# make e2e build + run tests/e2e.py (Playwright)
19+# make clean
20+#
21+# The multi-arch dist publish lives in scorpiox-cli-botplugin (it owns the
22+# toolchains, the dist upload and the plugingit mirror) - see release-dist.sh.
23+
24+CC ?= cc
25+CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -I vendor/yyjson
26+MUSL_CC ?= musl-gcc
27+MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor/yyjson -static
28+ARM_CC ?= aarch64-linux-gnu-gcc
29+ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor/yyjson -static
30+WIN_CC ?= x86_64-w64-mingw32-gcc
31+WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor/yyjson -static
32+SRC := src/plugin_filesystem.c
33+VENDOR := vendor/yyjson/yyjson.c
34+UI_SRC := src/ui.html
35+UI_HDR := src/ui_html.h
36+BIN := plugin_filesystem
37+EXE := plugin_filesystem.exe
38+
39+.PHONY: all native musl arm64 win64 macos asan fortify ui test e2e clean help
40+
41+all: native
42+
43+$(UI_HDR): $(UI_SRC) tools/gen_ui.py
44+ @echo "==> regenerating $(UI_HDR)"
45+ python3 tools/gen_ui.py
46+
47+ui: $(UI_HDR)
48+
49+native: $(BIN)
50+
51+$(BIN): $(SRC) $(UI_HDR) $(VENDOR)
52+ @echo "==> native build ($(CC))"
53+ $(CC) $(CFLAGS) -o $(BIN) $(SRC) $(VENDOR)
54+
55+# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy)
56+musl: $(SRC) $(UI_HDR) $(VENDOR)
57+ @echo "==> static musl build ($(MUSL_CC))"
58+ $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC) $(VENDOR)
59+
60+# Static aarch64 build - Raspberry Pi 5 / ARM64 servers
61+arm64: $(SRC) $(UI_HDR) $(VENDOR)
62+ @echo "==> static arm64 build ($(ARM_CC))"
63+ $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC) $(VENDOR)
64+
65+# Native Win64 static PE - runs on any Windows 10/11 x64 node
66+win64: $(SRC) $(UI_HDR) $(VENDOR)
67+ @echo "==> MinGW-w64 build ($(WIN_CC))"
68+ $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) $(VENDOR)
69+
70+# Apple clang build (run this on macOS)
71+macos: $(SRC) $(UI_HDR) $(VENDOR)
72+ @echo "==> Apple clang build"
73+ $(CC) $(CFLAGS) -o $(BIN) $(SRC) $(VENDOR)
74+
75+# Sanitizer build - tests/run.sh exercises every tool through this binary
76+asan: $(SRC) $(UI_HDR) $(VENDOR)
77+ @echo "==> ASan + UBSan build"
78+ $(CC) -O1 -g -std=c99 -fsanitize=address,undefined -fno-omit-frame-pointer \
79+ -I src -I vendor/yyjson -o $(BIN)-asan $(SRC) $(VENDOR)
80+
81+fortify: $(SRC) $(UI_HDR) $(VENDOR)
82+ @echo "==> _FORTIFY_SOURCE=2 build"
83+ $(CC) -O2 -D_FORTIFY_SOURCE=2 -std=c99 -Wall -Wextra -Wno-overlength-strings \
84+ -I src -I vendor/yyjson -o $(BIN)-fortify $(SRC) $(VENDOR)
85+
86+test: native
87+ @sh tests/run.sh
88+
89+e2e: native
90+ @python3 tests/e2e.py
91+
92+clean:
93+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN)-asan $(BIN)-fortify
94+ rm -rf bin
95+
96+help:
97+ @echo "make | make musl | make arm64 | make win64 | make macos | make asan | make fortify | make ui | make test | make e2e | make clean"
README.md+200−0■■■■■
11new file mode 100644
index 0000000..e230b89
--- /dev/null
+++ b/README.md
@@ -0,0 +1,200 @@
1+# filesystem — allowlisted filesystem MCP connector for SCORPIOX BOT
2+
3+`plugin_filesystem` is a clean-room, zero-dependency **pure C99** rewrite of the
4+tool surface of
5+[`modelcontextprotocol/servers` → `src/filesystem`](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem),
6+reshaped as a **SCORPIOX BOT connector plugin**: one binary, four modes, no
7+shared-library requirements, and a sandbox you can actually read.
8+
9+It is deliberately **not** the read-only `files` browser. `files` lets a human
10+look at files; `filesystem` lets an **agent** change them — inside a list of
11+directories you approve, and nowhere else.
12+
13+| | |
14+|---|---|
15+| Slug | `filesystem` |
16+| Binary | `plugin_filesystem` (`plugin_filesystem.exe` on Windows) |
17+| `--meta` | `{"name":"filesystem","desc":"Allowlist FS","kind":"mcp","mcp":true,"daemon":false,"menus":false,"verified":"live"}` |
18+| Category | `devtools` |
19+| Kind | MCP connector (`--mcp`, stdio JSON-RPC 2.0) |
20+| License | MIT |
21+
22+## Modes
23+
24+| Mode | Trigger | Who calls it |
25+|---|---|---|
26+| Discovery | `--meta` / `SX_PLUGIN_META=1` | `scorpiox-bot-api` `/plugins`, `scorpiox-cli-botplugin`, `sx-connector-mcp` |
27+| MCP tools | `--mcp` | `sx-connector-mcp` (the single MCP router) or any MCP client over stdio |
28+| Control API | `?action=…` / `?format=json` | the plugin page (behind `require_node_auth()`) |
29+| Setup page | `GET` | the browser, via the hub or the node directly |
30+
31+```sh
32+./plugin_filesystem --meta
33+printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | ./plugin_filesystem --mcp
34+make && make test && make e2e
35+```
36+
37+## Tools (11, matching the upstream subset)
38+
39+| Tool | Parameters | |
40+|---|---|---|
41+| `read_text_file` | `path`, `head?`, `tail?` | read |
42+| `read_multiple_files` | `paths[]` | read |
43+| `write_file` | `path`, `content` | write (atomic) |
44+| `edit_file` | `path`, `edits[{oldText,newText}]`, `dryRun?` | write |
45+| `create_directory` | `path` | write |
46+| `list_directory` | `path` | read |
47+| `directory_tree` | `path`, `maxDepth?`, `excludePatterns?` | read |
48+| `move_file` | `source`, `destination` | write |
49+| `search_files` | `path`, `pattern`, `excludePatterns?` | read |
50+| `get_file_info` | `path` | read |
51+| `list_allowed_directories` | — | read (never disableable) |
52+
53+Behaviour worth knowing before you point an agent at it:
54+
55+* **`write_file` is atomic** — content goes to `<path>.tmp-<pid>`, is flushed,
56+ then renamed. A crash mid-write leaves the old file or the new one, never a
57+ half-written file. `tests/run.sh` proves this by `SIGKILL`ing the process
58+ mid-request.
59+* **`edit_file` is all-or-nothing.** Edits apply in order, each replacing the
60+ first match of its `oldText`. An exact match wins; failing that, a run of
61+ whole lines matches when each line is equal ignoring leading and trailing
62+ whitespace. If *any* edit fails to match, **nothing** is written and the
63+ reply shows the closest numbered lines so the agent can re-copy `oldText`.
64+ The file's own LF/CRLF choice is preserved.
65+* **`move_file` will not overwrite.** It refuses, because silently replacing an
66+ operator's file is the one thing an unattended agent must not get. A
67+ cross-device move falls back to copy-then-delete.
68+* **`read_text_file` refuses binary** rather than returning mojibake, and says
69+ what to call instead.
70+
71+## The sandbox
72+
73+Every path — from a tool call or an HTTP request — goes through the same gate:
74+
75+1. **Shape.** Absolute, no NUL or control bytes, and no `..` segment anywhere.
76+ `%2e%2e` and `%2f` are decoded before this check, so encoding does not help.
77+2. **Canonicalise.** `realpath()` on POSIX; `GetFullPathNameA()` then
78+ `GetFinalPathNameByHandleA()` on Windows. The check happens **after** symlink
79+ resolution, which is the only order that means anything.
80+3. **Prefix-check against every root.** Each root is stored in **two forms** —
81+ the path the operator configured *and* its `realpath`. That is what makes a
82+ configured `/tmp` work on macOS, where the real path is `/private/tmp`
83+ (lesson `(cc)`/`(ah)` from the upstream reference).
84+4. **Deny list.** `/proc`, `/sys`, `/dev` are refused even under an allowed
85+ root; operator `denied` entries are refused on top of that.
86+5. **Write mode additionally checks the resolved parent** and refuses a
87+ symlinked leaf, so a link pointing out of the sandbox cannot be used as a
88+ handle to write through.
89+
90+```sh
91+# symlink escape is refused on read, write, edit and move
92+ln -s /etc/passwd ~/data/notes.txt
93+./plugin_filesystem --mcp <<< '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"write_file","arguments":{"path":"'$HOME'/data/notes.txt","content":"x"}}}'
94+# → isError: /root/data/notes.txt: path is outside the allowed directories
95+```
96+
97+## Configuration
98+
99+State lives outside the binary so it survives reinstalls:
100+
101+```
102+~/.scorpiox/connectors/plugin_filesystem/roots.json
103+/workspace/.scorpiox/connectors/plugin_filesystem/roots.json (BotCloud)
104+%LOCALAPPDATA%\scorpiox\connectors\plugin_filesystem\roots.json (Windows)
105+```
106+
107+```json
108+{
109+ "roots": ["/data/reports", "/srv/site"],
110+ "denied": ["/srv/site/.env"],
111+ "permissions": {
112+ "write_file": false,
113+ "move_file": false
114+ }
115+}
116+```
117+
118+* `$FS_ALLOWED_ROOTS` (colon-separated, `;` on Windows) overrides the file —
119+ that is how the test suite points the plugin at a fixture tree.
120+* With neither configured the defaults are `/workspace` and `$HOME` (POSIX) or
121+ `%USERPROFILE%` and `D:\codebases` (Windows).
122+* **Permissions are enforced by `--mcp`, not just displayed by the page.** A
123+ disabled tool answers with a refusal that says where to switch it back on, so
124+ the agent gets an explanation instead of a missing tool.
125+ `list_allowed_directories` cannot be disabled — it is how you debug a refusal.
126+
127+## Setup page
128+
129+`GET /plugin_filesystem` (or `/plugins?plugin=plugin_filesystem` through the
130+hub) serves the Allowed Roots & Permissions page: add and remove directories,
131+see each root's canonical form when it has drifted onto a symlink or a mount,
132+toggle each tool, and **test a path against the sandbox** before blaming a tool
133+for it. Bot theme tokens, `?embed=1`, `sx-theme` handoff, zero CDN, zero
134+`<script src=>`, hub-proxy vs direct-route branching.
135+
136+## Register with the connector router
137+
138+One router fronts every installed connector, so the agent's tool budget stays
139+flat however many you install (`<connectors_dir>/mcp_plugins.json`):
140+
141+```json
142+{
143+ "mcpServers": {
144+ "filesystem": {
145+ "command": "~/.scorpiox/plugins/plugin_filesystem",
146+ "args": ["--mcp"],
147+ "slug": "filesystem"
148+ }
149+ }
150+}
151+```
152+
153+## Build
154+
155+```sh
156+make # native -> ./plugin_filesystem
157+make musl # static musl x86_64 (universal Linux)
158+make arm64 # static musl aarch64 (Pi 5 / ARM servers)
159+make win64 # MinGW-w64 static PE (Windows nodes)
160+make macos # Apple clang (run on a Mac)
161+make asan # ASan + UBSan
162+make fortify # -D_FORTIFY_SOURCE=2
163+make test # tests/run.sh — offline, no network
164+make e2e # tests/e2e.py — Playwright 1440 / 1024 / 390, dark + light
165+```
166+
167+The only third-party code is the vendored MIT `yyjson` parser under
168+`vendor/yyjson/`, compiled in. There is no `popen`, no `system`, no `fork`, no
169+`socket` in the source — and `tests/run.sh` fails the build if any of them
170+appears.
171+
172+## Tests
173+
174+`tests/run.sh` is offline and self-contained: it builds the binary, generates a
175+fixture tree under `$TMPDIR`, and asserts the whole contract — the `--meta`
176+shape, all 11 tool schemas, one call per tool, `..` traversal (raw and
177+encoded), symlink escapes on read/write/edit/move, the deny list, permission
178+gating, 401 on every mutating action, the `roots.json` round-trip, the page
179+markup, the source invariants, an ASan/UBSan run of every tool including a
180+240-frame session, a fortified build, and a full-git-history secret scan.
181+
182+`tests/e2e.py` serves the CGI through a loopback shim and drives the page with
183+Playwright at 1440/1024/390 in both themes, asserting no console errors and no
184+horizontal overflow, and writes the screenshots in `docs/`.
185+
186+## Dist + source
187+
188+* Artifacts: `https://dist.scorpiox.net/bot-plugins/filesystem/<version>/`
189+ (`linux-x86_64`, `linux-x86_64-musl`, `linux-arm64-musl`, `macos-arm64`,
190+ `macos-x86_64`, `windows-x86_64`, `source.tar.gz`, `SHA256SUMS`).
191+* Source: `https://plugingit.scorpiox.net/scorpiox-bot-plugin-filesystem.git`
192+ (anonymous clone welcome — read `src/plugin_filesystem.c` before you install it).
193+
194+## Security model, honestly
195+
196+This plugin **can create, overwrite, edit, move and delete files** inside the
197+directories you allowlist. It has no `popen`, no `system`, no socket and makes
198+zero network requests, so the blast radius is exactly your allowlist. Keep the
199+list small: an agent with write access to your home directory has write access
200+to your home directory.
plugin.json+23−0■■■■■
11new file mode 100644
index 0000000..4a5452b
--- /dev/null
+++ b/plugin.json
@@ -0,0 +1,23 @@
1+{
2+ "slug": "filesystem",
3+ "id": "plugin_filesystem",
4+ "name": "filesystem",
5+ "desc": "Allowlist FS",
6+ "title": "Filesystem Tools (MCP)",
7+ "summary": "Zero-dependency MCP connector that gives your agent sandboxed filesystem tools: read, write, targeted edit, create, list, tree, move, search and stat, all confined to a list of directories you approve. Every path is canonicalised on disk (realpath / GetFinalPathNameByHandleA) and prefix-checked after symlink resolution, so traversal, symlink escapes, /proc, /sys and /dev are refused. Manage the allowlist, per-tool permissions and a sandbox boundary tester from the plugin page.",
8+ "kind": "mcp",
9+ "mcp": true,
10+ "daemon": false,
11+ "menus": false,
12+ "verified": "live",
13+ "category": "devtools",
14+ "license": "MIT",
15+ "capabilities": [
16+ "fs_read",
17+ "fs_write",
18+ "local_filesystem_only",
19+ "no_network"
20+ ],
21+ "trust_notice": "Executes native C code on your node. This plugin CAN CREATE, OVERWRITE, EDIT, MOVE AND DELETE FILES inside the directories you put on its allowlist (~/.scorpiox/connectors/plugin_filesystem/roots.json, or FS_ALLOWED_ROOTS; defaulting to /workspace and $HOME when unconfigured). Writes go through a temp file plus rename so a crash cannot leave a half-written file, move_file refuses to overwrite, and edit_file writes nothing if any edit fails to match. Everything outside the allowlist is refused after symlink resolution. It has no popen, no system, no socket and makes zero outbound network requests.",
22+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-filesystem"
23+}
release-dist.sh+41−0■■■■■
11new file mode 100755
index 0000000..c31d1d1
--- /dev/null
+++ b/release-dist.sh
@@ -0,0 +1,41 @@
1+#!/bin/sh
2+# release-dist.sh - thin wrapper around the shared multi-arch release tool.
3+#
4+# The real cross-target build + dist publish lives in scorpiox-cli-botplugin
5+# (it owns the musl / aarch64 / MinGW / macOS toolchains, the dist upload and
6+# the plugingit mirror). This script exists so the repo releases the same way
7+# every other oss plugin does, and so a stale release fails loudly instead of
8+# shipping a 3-target manifest that still says "release complete".
9+#
10+# ./release-dist.sh # build + publish version 1.0.0
11+# VERSION=1.0.1 ./release-dist.sh # explicit version
12+#
13+# Run it on the build host that has musl-gcc, aarch64-linux-gnu-gcc,
14+# x86_64-w64-mingw32-gcc and ssh access to the macOS builder.
15+
16+set -eu
17+
18+SLUG=filesystem
19+VERSION="${VERSION:-1.0.0}"
20+PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}"
21+
22+ROOT=$(cd "$(dirname "$0")" && pwd)
23+
24+if ! command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
25+ echo "scorpiox-cli-botplugin not found on PATH" >&2
26+ exit 1
27+fi
28+
29+echo "==> audit $SLUG"
30+scorpiox-cli-botplugin audit "$ROOT" --json || { echo "audit blocked the release" >&2; exit 4; }
31+
32+echo "==> publish $SLUG $VERSION"
33+scorpiox-cli-botplugin publish "$ROOT" \
34+ --slug "$SLUG" \
35+ --version "$VERSION" \
36+ --macos-host "${MACOS_HOST:-yongchen@macos-builder}" \
37+ --json
38+
39+echo "==> reindex"
40+scorpiox-cli-botplugin reindex --json >/dev/null 2>&1 || true
41+echo "check dist/bot-plugins/$SLUG/$VERSION/manifest.json has 6 targets before calling it done"
src/bot_theme_plugin.h+129−0■■■■■
11new 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 */
src/plugin_filesystem.c+3497−0■■■■■
11new file mode 100644
index 0000000..d98dc11
--- /dev/null
+++ b/src/plugin_filesystem.c
@@ -0,0 +1,3497 @@
1+/*
2+ * plugin_filesystem - SCORPIOX BOT open-source allowlisted filesystem MCP
3+ * connector for your node
4+ *
5+ * A clean-room rewrite (pure C99, zero dependencies) of the tool surface of
6+ * modelcontextprotocol/servers `src/filesystem`, reshaped as a SCORPIOX BOT
7+ * connector plugin: ONE binary, FOUR modes.
8+ *
9+ * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata (unauthenticated)
10+ * 2. --mcp -> MCP JSON-RPC 2.0 over stdio
11+ * (initialize / tools/list / tools/call)
12+ * 3. ?action=... / ?format=json -> JSON control API (require_node_auth)
13+ * 4. GET (default) -> Allowed Roots & Permissions page
14+ *
15+ * Repo: https://plugingit.scorpiox.net/scorpiox-bot-plugin-filesystem.git
16+ *
17+ * SANDBOX BY CONSTRUCTION. There is no popen, no system, no socket anywhere
18+ * in this file: the plugin touches the filesystem and nothing else. Every
19+ * path that arrives in a tool call or an HTTP request is canonicalised on the
20+ * real filesystem (realpath() on POSIX, GetFullPathNameA +
21+ * GetFinalPathNameByHandleA on Windows) and prefix-checked against the
22+ * allowlisted roots AFTER symlink resolution. `..`, embedded NUL bytes and
23+ * symlinks that point outside the roots are refused with an explicit error.
24+ * /proc, /sys and /dev are refused even when they sit under an allowed root.
25+ *
26+ * Two forms of every root are kept (the configured path AND its realpath),
27+ * which is what lets a user configure /tmp on macOS and still reach the
28+ * files that realpath resolves under /private/tmp.
29+ *
30+ * Roots come from
31+ * ~/.scorpiox/connectors/plugin_filesystem/roots.json (or the node's
32+ * /workspace/.scorpiox/connectors/... equivalent), overridable with the
33+ * FS_ALLOWED_ROOTS environment variable for tests, and defaulting to
34+ * /workspace or $HOME when nothing is configured.
35+ *
36+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
37+ */
38+
39+/* Must come before every include on Windows: MinGW defaults to 0x502
40+ * (Server 2003), which hides GetFinalPathNameByHandleA and friends. */
41+#if defined(_WIN32) && !defined(_WIN32_WINNT)
42+# define _WIN32_WINNT 0x0601
43+#endif
44+
45+#if !defined(_WIN32)
46+# define _POSIX_C_SOURCE 200809L
47+# define _DEFAULT_SOURCE 1
48+# if defined(__APPLE__)
49+# define _DARWIN_C_SOURCE 1
50+# endif
51+#endif
52+
53+#include <stdio.h>
54+#include <stdlib.h>
55+#include <string.h>
56+#include <stdarg.h>
57+#include <ctype.h>
58+#include <errno.h>
59+#include <time.h>
60+
61+#if defined(_WIN32)
62+# define WIN32_LEAN_AND_MEAN
63+# include <windows.h>
64+# include <direct.h>
65+# include <io.h>
66+# include <fcntl.h>
67+# define SEP '\\'
68+# define PATH_SPLITCH '\\'
69+#else
70+# include <unistd.h>
71+# include <sys/stat.h>
72+# include <sys/types.h>
73+# include <dirent.h>
74+# define SEP '/'
75+# define PATH_SPLITCH '/'
76+#endif
77+
78+#include "yyjson.h"
79+
80+#include "bot_theme_plugin.h"
81+#include "ui_html.h"
82+
83+#define PLUGIN_SLUG "filesystem"
84+#define PLUGIN_ID "plugin_filesystem"
85+#define PLUGIN_VER "1.0.0"
86+#define PLUGIN_NAME "filesystem"
87+#define PLUGIN_DESC "Allowlist FS"
88+#define MCP_PROTO "2024-11-05"
89+
90+#define PATH_SZ 4096
91+#define NAME_SZ 512
92+#define MAX_ROOTS 16
93+#define MAX_ENTRIES 5000 /* entries listed per directory */
94+#define WALK_BUDGET 20000 /* entries visited per tree/search */
95+#define MAX_RESULTS 1000 /* search_files matches */
96+#define MAX_DEPTH 24 /* recursive walk guard */
97+#define READ_CAP ((size_t)10 * 1024 * 1024) /* 10 MiB per file */
98+#define WRITE_CAP ((size_t)8 * 1024 * 1024) /* 8 MiB body per write */
99+#define BIN_PROBE 8192
100+#define IO_CHUNK 65536
101+#define MCP_LINE_CAP ((size_t)64 * 1024 * 1024) /* one request line */
102+#define TOOLS_N 11
103+
104+/* ------------------------------------------------------------------ */
105+/* Growable byte buffer */
106+/* ------------------------------------------------------------------ */
107+
108+typedef struct {
109+ char *p;
110+ size_t n;
111+ size_t cap;
112+} buf_t;
113+
114+static void buf_init(buf_t *b)
115+{
116+ b->p = NULL;
117+ b->n = 0;
118+ b->cap = 0;
119+}
120+
121+static int buf_need(buf_t *b, size_t extra)
122+{
123+ size_t want = b->n + extra + 1;
124+ char *np;
125+ if (want <= b->cap) return 1;
126+ if (b->cap == 0) b->cap = 1024;
127+ while (b->cap < want) {
128+ if (b->cap > (size_t)256 * 1024 * 1024) return 0;
129+ b->cap *= 2;
130+ }
131+ np = (char *)realloc(b->p, b->cap);
132+ if (!np) return 0;
133+ b->p = np;
134+ return 1;
135+}
136+
137+static void buf_add(buf_t *b, const char *s, size_t n)
138+{
139+ if (n == 0) return;
140+ if (!buf_need(b, n)) return;
141+ memcpy(b->p + b->n, s, n);
142+ b->n += n;
143+ b->p[b->n] = '\0';
144+}
145+
146+static void buf_puts(buf_t *b, const char *s)
147+{
148+ if (s) buf_add(b, s, strlen(s));
149+}
150+
151+static void buf_putc(buf_t *b, char c)
152+{
153+ if (!buf_need(b, 1)) return;
154+ b->p[b->n++] = c;
155+ b->p[b->n] = '\0';
156+}
157+
158+static const char *buf_str(buf_t *b)
159+{
160+ return b->p ? b->p : "";
161+}
162+
163+static void buf_printf(buf_t *b, const char *fmt, ...)
164+{
165+ char tmp[1024];
166+ va_list ap;
167+ int n;
168+ va_start(ap, fmt);
169+ n = vsnprintf(tmp, sizeof tmp, fmt, ap);
170+ va_end(ap);
171+ if (n < 0) return;
172+ if ((size_t)n < sizeof tmp) {
173+ buf_add(b, tmp, (size_t)n);
174+ return;
175+ }
176+ {
177+ char *big = (char *)malloc((size_t)n + 1);
178+ if (!big) return;
179+ va_start(ap, fmt);
180+ vsnprintf(big, (size_t)n + 1, fmt, ap);
181+ va_end(ap);
182+ buf_add(b, big, (size_t)n);
183+ free(big);
184+ }
185+}
186+
187+static void buf_free(buf_t *b)
188+{
189+ free(b->p);
190+ b->p = NULL;
191+ b->n = 0;
192+ b->cap = 0;
193+}
194+
195+/* ------------------------------------------------------------------ */
196+/* Small utilities */
197+/* ------------------------------------------------------------------ */
198+
199+static void str_copy(char *dst, size_t sz, const char *src)
200+{
201+ size_t n;
202+ if (!dst || sz == 0) return;
203+ if (!src) { dst[0] = '\0'; return; }
204+ n = strlen(src);
205+ if (n >= sz) n = sz - 1;
206+ memcpy(dst, src, n);
207+ dst[n] = '\0';
208+}
209+
210+static int str_ieq(const char *a, const char *b)
211+{
212+ for (; *a && *b; a++, b++) {
213+ if (tolower((unsigned char)*a) != tolower((unsigned char)*b)) return 0;
214+ }
215+ return *a == *b;
216+}
217+
218+#if defined(_WIN32)
219+static void rstrip_sep(char *s)
220+{
221+ size_t n = strlen(s);
222+ while (n > 3 && (s[n - 1] == '\\' || s[n - 1] == '/')) s[--n] = '\0';
223+}
224+#endif
225+
226+static void path_join(char *out, size_t sz, const char *a, const char *b)
227+{
228+ size_t n;
229+ if (!out || sz == 0) return;
230+ out[0] = '\0';
231+ if (!a) a = "";
232+ if (!b) b = "";
233+ str_copy(out, sz, a);
234+ n = strlen(out);
235+ if (n && out[n - 1] != '/' && out[n - 1] != '\\' && n + 1 < sz) {
236+ out[n++] = SEP;
237+ out[n] = '\0';
238+ }
239+ if (n + strlen(b) < sz) str_copy(out + n, sz - n, b);
240+}
241+
242+static void url_decode(char *s)
243+{
244+ char *o = s;
245+ if (!s) return;
246+ while (*s) {
247+ if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
248+ int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
249+ int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
250+ *o++ = (char)((hi << 4) | lo);
251+ s += 3;
252+ } else if (*s == '+') {
253+ *o++ = ' ';
254+ s++;
255+ } else {
256+ *o++ = *s++;
257+ }
258+ }
259+ *o = '\0';
260+}
261+
262+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
263+{
264+ size_t klen;
265+ const char *p;
266+
267+ if (!out || outsz == 0) return 0;
268+ out[0] = '\0';
269+ if (!qs || !key) return 0;
270+ klen = strlen(key);
271+
272+ for (p = qs; *p; ) {
273+ if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
274+ const char *v = p + klen + 1;
275+ size_t i = 0;
276+ while (*v && *v != '&' && i + 1 < outsz)
277+ out[i++] = *v++;
278+ out[i] = '\0';
279+ url_decode(out);
280+ return 1;
281+ }
282+ p = strchr(p, '&');
283+ if (!p) break;
284+ p++;
285+ }
286+ return 0;
287+}
288+
289+/* JSON-escape s into b (quotes included). Bytes are passed through so
290+ * UTF-8 file content survives; control characters are escaped. */
291+static void json_str(buf_t *b, const char *s)
292+{
293+ buf_putc(b, '"');
294+ for (; s && *s; s++) {
295+ unsigned char c = (unsigned char)*s;
296+ switch (c) {
297+ case '"': buf_puts(b, "\\\""); break;
298+ case '\\': buf_puts(b, "\\\\"); break;
299+ case '\n': buf_puts(b, "\\n"); break;
300+ case '\r': buf_puts(b, "\\r"); break;
301+ case '\t': buf_puts(b, "\\t"); break;
302+ default:
303+ if (c < 0x20) {
304+ char tmp[8];
305+ sprintf(tmp, "\\u%04x", c);
306+ buf_puts(b, tmp);
307+ } else {
308+ buf_putc(b, (char)c);
309+ }
310+ }
311+ }
312+ buf_putc(b, '"');
313+}
314+
315+static void fmt_iso(long long t, char *out, size_t sz)
316+{
317+ time_t tt = (time_t)t;
318+ struct tm tmv;
319+#if defined(_WIN32)
320+ gmtime_s(&tmv, &tt);
321+#else
322+ gmtime_r(&tt, &tmv);
323+#endif
324+ strftime(out, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv);
325+}
326+
327+
328+/* ------------------------------------------------------------------ */
329+/* yyjson helpers */
330+/* */
331+/* yyjson (vendored, MIT, upstream yyjson/yyjson) is the only thing */
332+/* that touches JSON structure. Requests are read with yyjson_read() */
333+/* (no insitu, so the request buffer is never mutated and never needs */
334+/* a terminator), and every response is written through the buf_t */
335+/* helpers below so a 10 MiB file body is escaped exactly once. */
336+/* ------------------------------------------------------------------ */
337+
338+/* JSON strings may carry \u0000. yyjson keeps the whole length but the C
339+ * pointer truncates at the NUL, so "a.txt\0secret" would silently become
340+ * "a.txt" - a path the caller never asked for. Any string we treat as a path,
341+ * pattern or text must therefore be NUL-free; ju_cstr is the gate. */
342+static const char *ju_cstr(yyjson_val *v)
343+{
344+ const char *s;
345+ if (!v || !yyjson_is_str(v)) return NULL;
346+ s = yyjson_get_str(v);
347+ if (!s) return NULL;
348+ if (strlen(s) != yyjson_get_len(v)) return NULL; /* embedded NUL */
349+ return s;
350+}
351+
352+static const char *ju_str(yyjson_val *o, const char *key)
353+{
354+ if (!o) return NULL;
355+ return ju_cstr(yyjson_obj_get(o, key));
356+}
357+
358+static long long ju_int(yyjson_val *o, const char *key, long long dflt, int *present)
359+{
360+ yyjson_val *v;
361+ if (present) *present = 0;
362+ if (!o) return dflt;
363+ v = yyjson_obj_get(o, key);
364+ if (!v) return dflt;
365+ if (yyjson_is_num(v)) {
366+ if (present) *present = 1;
367+ return (long long)yyjson_get_num(v);
368+ }
369+ if (yyjson_is_str(v)) { /* {"head":"20"} is what a
370+ * chatty model often sends */
371+ char *endp = NULL;
372+ long long n = strtoll(yyjson_get_str(v), &endp, 10);
373+ if (endp && *endp == '\0' && endp != yyjson_get_str(v)) {
374+ if (present) *present = 1;
375+ return n;
376+ }
377+ }
378+ return dflt;
379+}
380+
381+static int ju_bool(yyjson_val *o, const char *key, int dflt)
382+{
383+ yyjson_val *v;
384+ if (!o) return dflt;
385+ v = yyjson_obj_get(o, key);
386+ if (!v) return dflt;
387+ if (yyjson_is_bool(v)) return yyjson_get_bool(v) ? 1 : 0;
388+ if (yyjson_is_str(v)) return str_ieq(yyjson_get_str(v), "true");
389+ if (yyjson_is_int(v)) return yyjson_get_sint(v) != 0;
390+ return dflt;
391+}
392+
393+/* Coerce a string field that may arrive as a number (an agent that sends
394+ * {"head":20}) instead of "20". Returns 1 when the key exists at all. */
395+static int ju_field_str(yyjson_val *o, const char *key, char *out, size_t outsz)
396+{
397+ yyjson_val *v;
398+ if (!o) return 0;
399+ v = yyjson_obj_get(o, key);
400+ if (!v) return 0;
401+ if (yyjson_is_str(v)) {
402+ const char *s = ju_cstr(v);
403+ if (!s) return 0; /* embedded NUL: refuse, never truncate */
404+ str_copy(out, outsz, s);
405+ return 1;
406+ }
407+ if (yyjson_is_int(v)) {
408+ snprintf(out, outsz, "%lld", (long long)yyjson_get_sint(v));
409+ return 1;
410+ }
411+ if (yyjson_is_uint(v)) {
412+ snprintf(out, outsz, "%llu", (unsigned long long)yyjson_get_uint(v));
413+ return 1;
414+ }
415+ if (yyjson_is_real(v)) {
416+ snprintf(out, outsz, "%g", yyjson_get_real(v));
417+ return 1;
418+ }
419+ if (yyjson_is_bool(v)) {
420+ str_copy(out, outsz, yyjson_get_bool(v) ? "true" : "false");
421+ return 1;
422+ }
423+ return 0;
424+}
425+
426+/* ------------------------------------------------------------------ */
427+/* Node auth (CGI modes only; --meta and --mcp are exempt) */
428+/* ------------------------------------------------------------------ */
429+
430+static void require_node_auth(void)
431+{
432+ const char *np = getenv("BOT_PASSWORD");
433+ const char *xp;
434+ const char *auth;
435+ const char *qs;
436+ char qpwd[256];
437+
438+ if (!np || !*np) return;
439+
440+ xp = getenv("HTTP_X_BOT_PASSWORD");
441+ if (xp && strcmp(xp, np) == 0) return;
442+
443+ auth = getenv("HTTP_AUTHORIZATION");
444+ if (auth) {
445+ while (*auth == ' ') auth++;
446+ if (strncmp(auth, "Bearer ", 7) == 0) {
447+ auth += 7;
448+ while (*auth == ' ') auth++;
449+ if (strcmp(auth, np) == 0) return;
450+ }
451+ }
452+
453+ qs = getenv("QUERY_STRING");
454+ if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0)
455+ return;
456+
457+ fputs("Status: 401 Unauthorized\r\n"
458+ "Content-Type: application/json; charset=utf-8\r\n"
459+ "Cache-Control: no-store\r\n"
460+ "X-Content-Type-Options: nosniff\r\n\r\n"
461+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
462+ exit(0);
463+}
464+
465+/* ------------------------------------------------------------------ */
466+/* Allowed roots */
467+/* */
468+/* Each root is stored TWICE where the two forms differ: the path the */
469+/* operator configured and its canonical realpath. That is what makes */
470+/* a configured /tmp work on macOS, where realpath answers /private/ */
471+/* tmp, and it is also what lets the UI show an operator whose root */
472+/* has drifted (a symlinked home, a mounted volume) before they file */
473+/* a bug about a tool that "cannot see my files". */
474+/* ------------------------------------------------------------------ */
475+
476+typedef struct {
477+ char configured[PATH_SZ];
478+ char canonical[PATH_SZ];
479+ int exists;
480+ int is_dir;
481+} root_t;
482+
483+static root_t g_roots[MAX_ROOTS];
484+static int g_root_count;
485+static int g_tool_off[TOOLS_N]; /* permissions: 1 = disabled */
486+static char g_roots_file[PATH_SZ];
487+
488+static int deny_count;
489+static char g_deny[MAX_ROOTS][PATH_SZ];
490+
491+/* Tool names in registration order - the same order tools/list reports. */
492+static const char *TOOL_NAMES[TOOLS_N] = {
493+ "read_text_file", "read_multiple_files", "write_file", "edit_file",
494+ "create_directory", "list_directory", "directory_tree", "move_file",
495+ "search_files", "get_file_info", "list_allowed_directories"
496+};
497+
498+static int tool_index(const char *name)
499+{
500+ int i;
501+ if (!name) return -1;
502+ for (i = 0; i < TOOLS_N; i++)
503+ if (strcmp(TOOL_NAMES[i], name) == 0) return i;
504+ return -1;
505+}
506+
507+/* ------------------------------------------------------------------ */
508+/* Path canonicalisation */
509+/* ------------------------------------------------------------------ */
510+
511+#if defined(_WIN32)
512+
513+static void win_norm(char *s)
514+{
515+ for (; *s; s++) {
516+ if (*s == '/') *s = '\\';
517+ *s = (char)tolower((unsigned char)*s);
518+ }
519+}
520+
521+static int path_under_p(const char *p, const char *root)
522+{
523+ char a[PATH_SZ], b[PATH_SZ];
524+ size_t n;
525+ str_copy(a, sizeof a, p);
526+ str_copy(b, sizeof b, root);
527+ win_norm(a);
528+ win_norm(b);
529+ n = strlen(b);
530+ while (n > 3 && b[n - 1] == '\\') b[--n] = '\0';
531+ if (strcmp(a, b) == 0) return 1;
532+ if (strncmp(a, b, n) == 0 && a[n] == '\\') return 1;
533+ return 0;
534+}
535+
536+#else /* POSIX */
537+
538+static int path_under_p(const char *p, const char *root)
539+{
540+ size_t n;
541+ if (!p || !root) return 0;
542+ n = strlen(root);
543+ if (strcmp(p, root) == 0) return 1;
544+ if (n && root[n - 1] == '/') return strncmp(p, root, n) == 0;
545+ if (n && strncmp(p, root, n) == 0 && p[n] == '/') return 1;
546+ return 0;
547+}
548+
549+#endif /* platform prefix check */
550+
551+/* Lexical normalisation only: no filesystem access, so it works for a path
552+ * that does not exist yet (write_file, create_directory). Because
553+ * path_shape_ok() has already rejected every ".." segment, collapsing
554+ * separators here cannot be used to walk out of anything. */
555+static int lexical_abs(const char *raw, char *out, size_t outsz)
556+{
557+ size_t i, o = 0;
558+ int last_sep = 1; /* the head counts as a sep */
559+
560+ if (!raw || !*raw) return 0;
561+#if defined(_WIN32)
562+ {
563+ char full[PATH_SZ];
564+ DWORD n = GetFullPathNameA(raw, (DWORD)sizeof full, full, NULL);
565+ if (n == 0 || n >= (DWORD)sizeof full) return 0;
566+ str_copy(out, outsz, full);
567+ rstrip_sep(out);
568+ return out[0] ? 1 : 0;
569+ }
570+#else
571+ if (raw[0] != '/') return 0;
572+ if (outsz < 2) return 0;
573+ out[o++] = '/'; /* absolute, always */
574+ for (i = 1; raw[i]; i++) {
575+ char c = raw[i];
576+ if (c == '\\') c = '/';
577+ if (c == '/') {
578+ if (last_sep) continue;
579+ if (o + 1 >= outsz) return 0;
580+ out[o++] = '/';
581+ last_sep = 1;
582+ /* collapse a "." segment: /a/./b behaves as /a/b */
583+ if (raw[i + 1] == '.' &&
584+ (raw[i + 2] == '/' || raw[i + 2] == '\\' || raw[i + 2] == '\0'))
585+ i++;
586+ continue;
587+ }
588+ if (o + 1 >= outsz) return 0;
589+ out[o++] = c;
590+ last_sep = 0;
591+ }
592+ if (o == 0) { out[0] = '/'; out[1] = '\0'; return 1; }
593+ while (o > 1 && out[o - 1] == '/') o--;
594+ out[o] = '\0';
595+ return 1;
596+#endif
597+}
598+
599+/* Lexical form, used when the target does not exist yet. */
600+static int norm_lex(const char *raw, char *out, size_t outsz)
601+{
602+ return lexical_abs(raw, out, outsz);
603+}
604+
605+/* Full canonicalisation: resolves every symlink that exists on disk. */
606+static int canon_path(const char *raw, char *out, size_t outsz)
607+{
608+#if defined(_WIN32)
609+ char full[PATH_SZ];
610+ HANDLE h;
611+ char final[PATH_SZ];
612+
613+ if (!lexical_abs(raw, full, sizeof full)) return 0;
614+ if (GetFileAttributesA(full) == INVALID_FILE_ATTRIBUTES) return 0;
615+ h = CreateFileA(full, 0,
616+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
617+ NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
618+ if (h != INVALID_HANDLE_VALUE) {
619+ DWORD fn = GetFinalPathNameByHandleA(h, final, (DWORD)sizeof final, 0);
620+ CloseHandle(h);
621+ if (fn > 0 && fn < (DWORD)sizeof final) {
622+ char *src = final;
623+ if (strncmp(src, "\\\\?\\", 4) == 0) src += 4;
624+ str_copy(out, outsz, src);
625+ return 1;
626+ }
627+ }
628+ str_copy(out, outsz, full);
629+ return 1;
630+#else
631+ char *r;
632+ char lex[PATH_SZ];
633+ struct stat lst;
634+ if (!lexical_abs(raw, lex, sizeof lex)) return 0;
635+ if (lstat(lex, &lst) != 0) return 0; /* nothing there to canonicalise */
636+ r = realpath(lex, NULL);
637+ if (!r) return 0;
638+ str_copy(out, outsz, r);
639+ free(r);
640+ return 1;
641+#endif
642+}
643+
644+/* Absolute-path shape check. Rejects NUL smuggling attempts, `..` anywhere,
645+ * and on POSIX anything not rooted at '/'. */
646+static int path_shape_ok(const char *raw)
647+{
648+ size_t i;
649+ if (!raw || !*raw) return 0;
650+ if (strlen(raw) >= PATH_SZ) return 0;
651+#if !defined(_WIN32)
652+ if (raw[0] != '/') return 0;
653+#else
654+ if (!(isalpha((unsigned char)raw[0]) && raw[1] == ':' &&
655+ (raw[2] == '\\' || raw[2] == '/'))) {
656+ if (raw[0] != '/' && raw[0] != '\\') return 0; /* UNC-ish: allowed */
657+ }
658+#endif
659+ for (i = 0; raw[i]; i++) {
660+ if ((unsigned char)raw[i] < 0x20) return 0; /* control bytes */
661+ }
662+ /* `..` is never a legitimate segment: a caller that means the parent
663+ * sends the parent's absolute path. Rejecting it outright also kills
664+ * %2e%2e and every other encoded variant after url_decode(). */
665+ for (i = 0; raw[i]; i++) {
666+ if (raw[i] != '.') continue;
667+ if (i > 0 && raw[i - 1] != '/' && raw[i - 1] != '\\') continue;
668+ if (raw[i + 1] == '.' && (raw[i + 2] == '/' || raw[i + 2] == '\\' ||
669+ raw[i + 2] == '\0')) return 0;
670+ }
671+ return 1;
672+}
673+
674+static int denied_path(const char *p)
675+{
676+ int i;
677+ for (i = 0; i < deny_count; i++)
678+ if (path_under_p(p, g_deny[i])) return 1;
679+#if !defined(_WIN32)
680+ {
681+ static const char *deny[] = { "/proc", "/sys", "/dev" };
682+ size_t k;
683+ for (k = 0; k < sizeof deny / sizeof deny[0]; k++)
684+ if (path_under_p(p, deny[k])) return 1;
685+ }
686+#else
687+ {
688+ /* Windows equivalents of "never go here": the registry hives and the
689+ * system volume shadow copies live under C:\Windows and C:\System
690+ * Volume Information, and a node's own plugin directory is where the
691+ * binaries the bot executes sit. */
692+ static const char *deny[] = {
693+ "C:\\Windows\\System32\\config",
694+ "C:\\System Volume Information"
695+ };
696+ size_t k;
697+ for (k = 0; k < sizeof deny / sizeof deny[0]; k++)
698+ if (path_under_p(p, deny[k])) return 1;
699+ }
700+#endif
701+ return 0;
702+}
703+
704+static int root_contains(const char *canon)
705+{
706+ int i;
707+ for (i = 0; i < g_root_count; i++) {
708+ if (path_under_p(canon, g_roots[i].canonical)) return i;
709+ if (g_roots[i].configured[0] &&
710+ path_under_p(canon, g_roots[i].configured)) return i;
711+ }
712+ return -1;
713+}
714+
715+static void parent_of(const char *canon, char *out, size_t outsz)
716+{
717+ size_t n;
718+ str_copy(out, outsz, canon);
719+ n = strlen(out);
720+ while (n > 1 && (out[n - 1] == '/' || out[n - 1] == '\\')) out[--n] = '\0';
721+#if defined(_WIN32)
722+ while (n > 3 && out[n - 1] != '\\' && out[n - 1] != '/') out[--n] = '\0';
723+ if (n > 3) out[--n] = '\0';
724+ else str_copy(out, outsz, canon);
725+#else
726+ while (n > 1 && out[n - 1] != '/') out[--n] = '\0';
727+ if (n > 1) out[--n] = '\0';
728+ if (!out[0]) str_copy(out, outsz, "/");
729+#endif
730+}
731+
732+/* Authorise one path for one mode.
733+ * mode 'r' - the entry must exist and be inside a root.
734+ * mode 'w' - the ENTRY may not exist yet, so its PARENT is the thing that
735+ * must exist and stay inside a root; a symlinked leaf that
736+ * points out of the sandbox is refused by re-checking the
737+ * canonical form of what is already on disk.
738+ * On failure returns 0 with a one-line reason in err (never a stack trace:
739+ * these strings are what the model reads to decide what to do next). */
740+static int resolve_allowed(const char *raw, char *out, size_t outsz,
741+ char mode, const char **err)
742+{
743+ char canon[PATH_SZ], parent[PATH_SZ];
744+
745+ if (!raw || !*raw) { *err = "path is empty"; return 0; }
746+ if (!path_shape_ok(raw)) {
747+ *err = "path must be absolute and must not contain '..'";
748+ return 0;
749+ }
750+ if (!canon_path(raw, canon, sizeof canon)) {
751+ if (mode == 'r') { *err = "path does not exist"; return 0; }
752+ /* The entry does not exist yet (write_file, create_directory): the
753+ * lexical form is what we can check, and the parent is what has to
754+ * really exist and stay inside a root. */
755+ if (!norm_lex(raw, canon, sizeof canon)) {
756+ *err = "path could not be normalised";
757+ return 0;
758+ }
759+ }
760+ if (denied_path(canon)) { *err = "path is on the deny list"; return 0; }
761+ if (root_contains(canon) < 0) {
762+ *err = "path is outside the allowed directories";
763+ return 0;
764+ }
765+ if (mode == 'w') {
766+ parent_of(canon, parent, sizeof parent);
767+ if (strcmp(parent, canon) != 0) {
768+ char pc[PATH_SZ];
769+ if (canon_path(parent, pc, sizeof pc)) {
770+ if (denied_path(pc)) { *err = "parent directory is denied"; return 0; }
771+ if (root_contains(pc) < 0) {
772+ *err = "parent directory is outside the allowed directories";
773+ return 0;
774+ }
775+ }
776+ }
777+ }
778+ str_copy(out, outsz, canon);
779+ return 1;
780+}
781+
782+/* ------------------------------------------------------------------ */
783+/* Config directory + roots.json */
784+/* ------------------------------------------------------------------ */
785+
786+/* State lives OUTSIDE the plugin binary path (connector spec §C.1) so it
787+ * survives reinstall and container restarts:
788+ * $FS_CONNECTORS_DIR/<id>/ (tests)
789+ * /workspace/.scorpiox/connectors/<id>/ (BotCloud containers)
790+ * ~/.scorpiox/connectors/<id>/ (POSIX)
791+ * %LOCALAPPDATA%\\scorpiox\\connectors\\<id>/ (Windows) */
792+#if defined(_WIN32)
793+static int is_dir_path(const char *p)
794+{
795+ DWORD att;
796+ if (!p || !*p) return 0;
797+ att = GetFileAttributesA(p);
798+ return (att != INVALID_FILE_ATTRIBUTES) && (att & FILE_ATTRIBUTE_DIRECTORY);
799+}
800+#else
801+static int is_dir_path(const char *p)
802+{
803+ struct stat st;
804+ if (!p || !*p) return 0;
805+ return (stat(p, &st) == 0) && S_ISDIR(st.st_mode);
806+}
807+#endif
808+
809+static void connectors_dir(char *out, size_t outsz)
810+{
811+ const char *env = getenv("FS_CONNECTORS_DIR");
812+ const char *home;
813+
814+ if (env && *env) {
815+ snprintf(out, outsz, "%s/%s", env, PLUGIN_ID);
816+ return;
817+ }
818+#if defined(_WIN32)
819+ home = getenv("LOCALAPPDATA");
820+ if (!home || !*home) home = getenv("USERPROFILE");
821+ if (home && *home) {
822+ snprintf(out, outsz, "%s\\scorpiox\\connectors\\%s", home, PLUGIN_ID);
823+ return;
824+ }
825+ snprintf(out, outsz, ".\\scorpiox-connectors\\%s", PLUGIN_ID);
826+#else
827+ if (is_dir_path("/workspace/.scorpiox")) {
828+ snprintf(out, outsz, "/workspace/.scorpiox/connectors/%s", PLUGIN_ID);
829+ return;
830+ }
831+ home = getenv("HOME");
832+ if (home && *home) {
833+ snprintf(out, outsz, "%s/.scorpiox/connectors/%s", home, PLUGIN_ID);
834+ return;
835+ }
836+ snprintf(out, outsz, "./.scorpiox-connectors/%s", PLUGIN_ID);
837+#endif
838+}
839+
840+/* mkdir -p, portable, mode 0700 (this directory holds operator config). */
841+static int mkpath(const char *path)
842+{
843+ char tmp[PATH_SZ];
844+ char *p;
845+ size_t n;
846+
847+ str_copy(tmp, sizeof tmp, path);
848+ n = strlen(tmp);
849+ while (n > 1 && (tmp[n - 1] == '/' || tmp[n - 1] == '\\')) tmp[--n] = '\0';
850+ for (p = tmp + 1; *p; p++) {
851+ if (*p != '/' && *p != '\\') continue;
852+ *p = '\0';
853+#if defined(_WIN32)
854+ _mkdir(tmp);
855+#else
856+ mkdir(tmp, 0700);
857+#endif
858+ *p = SEP;
859+ }
860+#if defined(_WIN32)
861+ if (_mkdir(tmp) == 0 || errno == EEXIST) return 0;
862+ return -1;
863+#else
864+ if (mkdir(tmp, 0700) == 0 || errno == EEXIST) return 0;
865+ return -1;
866+#endif
867+}
868+
869+static void add_root_raw(const char *configured)
870+{
871+ char canon[PATH_SZ];
872+ struct stat st;
873+ int i;
874+
875+ if (g_root_count >= MAX_ROOTS) return;
876+ if (!configured || !*configured) return;
877+
878+ /* Trim surrounding whitespace and any leftover shell quotes: an operator
879+ * who pastes "/data/reports " or '/data/reports' into roots.json means
880+ * the directory, not a name with a trailing space. */
881+ {
882+ char clean[PATH_SZ];
883+ size_t a = 0, b2 = strlen(configured);
884+ while (a < b2 && isspace((unsigned char)configured[a])) a++;
885+ while (b2 > a && isspace((unsigned char)configured[b2 - 1])) b2--;
886+ if (b2 - a >= 2 && ((configured[a] == '"' && configured[b2 - 1] == '"') ||
887+ (configured[a] == '\'' && configured[b2 - 1] == '\''))) {
888+ a++; b2--;
889+ }
890+ if (b2 <= a) return;
891+ if (b2 - a >= PATH_SZ) return;
892+ memcpy(clean, configured + a, b2 - a);
893+ clean[b2 - a] = '\0';
894+ if (!path_shape_ok(clean)) return;
895+ if (!canon_path(clean, canon, sizeof canon)) return;
896+ if (denied_path(canon)) return;
897+ }
898+ for (i = 0; i < g_root_count; i++)
899+ if (strcmp(g_roots[i].canonical, canon) == 0) return;
900+
901+ str_copy(g_roots[g_root_count].configured, PATH_SZ, configured);
902+ str_copy(g_roots[g_root_count].canonical, PATH_SZ, canon);
903+#if defined(_WIN32)
904+ {
905+ DWORD att = GetFileAttributesA(canon);
906+ g_roots[g_root_count].exists = (att != INVALID_FILE_ATTRIBUTES);
907+ g_roots[g_root_count].is_dir = (att != INVALID_FILE_ATTRIBUTES) &&
908+ (att & FILE_ATTRIBUTE_DIRECTORY);
909+ }
910+#else
911+ st.st_mode = 0;
912+ g_roots[g_root_count].exists = (stat(canon, &st) == 0);
913+ g_roots[g_root_count].is_dir = S_ISDIR(st.st_mode);
914+#endif
915+ g_root_count++;
916+}
917+
918+static void add_deny(const char *p)
919+{
920+ char canon[PATH_SZ];
921+ int i;
922+ if (deny_count >= MAX_ROOTS) return;
923+ if (!p || !*p) return;
924+ if (!path_shape_ok(p)) return;
925+ if (!canon_path(p, canon, sizeof canon)) str_copy(canon, sizeof canon, p);
926+ for (i = 0; i < deny_count; i++)
927+ if (strcmp(g_deny[i], canon) == 0) return;
928+ str_copy(g_deny[deny_count++], PATH_SZ, canon);
929+}
930+
931+/* roots.json: {"roots":["/data","/srv"],"denied":["/data/secret"],
932+ * "permissions":{"write_file":false,...}}
933+ * A missing or unreadable file is not an error - the defaults below apply. */
934+static int load_roots_file(void)
935+{
936+ FILE *f;
937+ long sz;
938+ char *txt;
939+ yyjson_doc *doc;
940+ yyjson_val *root, *arr, *perm, *it;
941+ size_t i, max;
942+ int loaded = 0;
943+
944+ if (!g_roots_file[0]) {
945+ char dir[PATH_SZ];
946+ connectors_dir(dir, sizeof dir);
947+ snprintf(g_roots_file, sizeof g_roots_file, "%s", dir);
948+ if (g_roots_file[0]) {
949+ size_t dl = strlen(g_roots_file);
950+ if (dl + 12 < sizeof g_roots_file) {
951+ g_roots_file[dl] = SEP;
952+ g_roots_file[dl + 1] = '\0';
953+ str_copy(g_roots_file + dl + 1, sizeof g_roots_file - dl - 1, "roots.json");
954+ }
955+ }
956+ }
957+
958+ f = fopen(g_roots_file, "rb");
959+ if (!f) return 0;
960+ if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return 0; }
961+ sz = ftell(f);
962+ if (sz < 0 || (size_t)sz > 256 * 1024) { fclose(f); return 0; }
963+ rewind(f);
964+ txt = (char *)malloc((size_t)sz + 1);
965+ if (!txt) { fclose(f); return 0; }
966+ if (fread(txt, 1, (size_t)sz, f) != (size_t)sz) {
967+ free(txt);
968+ fclose(f);
969+ return 0;
970+ }
971+ txt[sz] = '\0';
972+ fclose(f);
973+
974+ doc = yyjson_read(txt, (size_t)sz, 0);
975+ free(txt);
976+ if (!doc) return 0;
977+ root = yyjson_doc_get_root(doc);
978+ if (!yyjson_is_obj(root)) { yyjson_doc_free(doc); return 0; }
979+
980+ arr = yyjson_obj_get(root, "roots");
981+ if (yyjson_is_arr(arr)) {
982+ max = yyjson_arr_size(arr);
983+ for (i = 0; i < max; i++) {
984+ it = yyjson_arr_get(arr, i);
985+ if (yyjson_is_str(it)) { add_root_raw(yyjson_get_str(it)); loaded = 1; }
986+ }
987+ }
988+ arr = yyjson_obj_get(root, "denied");
989+ if (yyjson_is_arr(arr)) {
990+ max = yyjson_arr_size(arr);
991+ for (i = 0; i < max; i++) {
992+ it = yyjson_arr_get(arr, i);
993+ if (yyjson_is_str(it)) add_deny(yyjson_get_str(it));
994+ }
995+ }
996+ perm = yyjson_obj_get(root, "permissions");
997+ if (yyjson_is_obj(perm)) {
998+ for (i = 0; i < (size_t)TOOLS_N; i++) {
999+ yyjson_val *v = yyjson_obj_get(perm, TOOL_NAMES[i]);
1000+ if (v && yyjson_is_bool(v) && !yyjson_get_bool(v)) g_tool_off[i] = 1;
1001+ }
1002+ loaded = 1;
1003+ }
1004+ yyjson_doc_free(doc);
1005+ return loaded;
1006+}
1007+
1008+static void init_roots(void)
1009+{
1010+ const char *extra;
1011+ const char *home;
1012+
1013+ if (g_root_count) return;
1014+
1015+ /* 1. $FS_ALLOWED_ROOTS always wins - tests and one-shot operator overrides
1016+ * must not need a file, and a connector that cannot be pointed at a
1017+ * fixture tree cannot be tested at all. */
1018+ extra = getenv("FS_ALLOWED_ROOTS");
1019+ if (extra && *extra) {
1020+ char copy[PATH_SZ];
1021+ char *tok;
1022+ char delim;
1023+#if defined(_WIN32)
1024+ delim = ';'; /* ':' is drive syntax on NT */
1025+#else
1026+ delim = ':';
1027+#endif
1028+ str_copy(copy, sizeof copy, extra);
1029+ tok = copy;
1030+ while (tok && *tok) {
1031+ char *nx = strchr(tok, delim);
1032+ if (nx) *nx++ = '\0';
1033+ add_root_raw(tok);
1034+ tok = nx;
1035+ }
1036+ if (g_root_count) return;
1037+ }
1038+
1039+ /* 2. operator config */
1040+ if (load_roots_file() && g_root_count) return;
1041+
1042+ /* 3. defaults: the two places a node actually keeps user files. */
1043+#if defined(_WIN32)
1044+ home = getenv("USERPROFILE");
1045+ if (home && *home) add_root_raw(home);
1046+ {
1047+ const char *d = getenv("DRIVE");
1048+ char buf[PATH_SZ];
1049+ if (d && *d) { snprintf(buf, sizeof buf, "%s:\\codebases", d); add_root_raw(buf); }
1050+ add_root_raw("D:\\codebases");
1051+ }
1052+#else
1053+ if (is_dir_path("/workspace")) add_root_raw("/workspace");
1054+ home = getenv("HOME");
1055+ if (home && *home) add_root_raw(home);
1056+ if (g_root_count == 0) add_root_raw("/tmp"); /* last resort, still scoped */
1057+#endif
1058+}
1059+
1060+/* ------------------------------------------------------------------ */
1061+/* Filesystem primitives */
1062+/* ------------------------------------------------------------------ */
1063+
1064+static int is_regular(const char *p)
1065+{
1066+#if defined(_WIN32)
1067+ DWORD att = GetFileAttributesA(p);
1068+ if (att == INVALID_FILE_ATTRIBUTES) return 0;
1069+ return !(att & FILE_ATTRIBUTE_DIRECTORY);
1070+#else
1071+ struct stat st;
1072+ if (lstat(p, &st) != 0) return 0;
1073+ return S_ISREG(st.st_mode);
1074+#endif
1075+}
1076+
1077+static int is_link_path(const char *p)
1078+{
1079+#if defined(_WIN32)
1080+ DWORD att = GetFileAttributesA(p);
1081+ return (att != INVALID_FILE_ATTRIBUTES) && (att & FILE_ATTRIBUTE_REPARSE_POINT);
1082+#else
1083+ struct stat st;
1084+ return (lstat(p, &st) == 0) && S_ISLNK(st.st_mode);
1085+#endif
1086+}
1087+
1088+static long long file_size(const char *p)
1089+{
1090+#if defined(_WIN32)
1091+ WIN32_FILE_ATTRIBUTE_DATA d;
1092+ LARGE_INTEGER li;
1093+ if (!GetFileAttributesExA(p, GetFileExInfoStandard, &d)) return -1;
1094+ li.HighPart = d.nFileSizeHigh;
1095+ li.LowPart = d.nFileSizeLow;
1096+ return (long long)li.QuadPart;
1097+#else
1098+ struct stat st;
1099+ if (stat(p, &st) != 0) return -1;
1100+ return (long long)st.st_size;
1101+#endif
1102+}
1103+
1104+static long long file_mtime(const char *p)
1105+{
1106+#if defined(_WIN32)
1107+ WIN32_FILE_ATTRIBUTE_DATA d;
1108+ FILETIME ft;
1109+ ULARGE_INTEGER u;
1110+ if (!GetFileAttributesExA(p, GetFileExInfoStandard, &d)) return 0;
1111+ ft = d.ftLastWriteTime;
1112+ u.LowPart = ft.dwLowDateTime;
1113+ u.HighPart = ft.dwHighDateTime;
1114+ return (long long)(u.QuadPart / 10000000ULL - 11644473600ULL);
1115+#else
1116+ struct stat st;
1117+ if (stat(p, &st) != 0) return 0;
1118+ return (long long)st.st_mtime;
1119+#endif
1120+}
1121+
1122+static unsigned file_mode(const char *p)
1123+{
1124+#if defined(_WIN32)
1125+ DWORD att = GetFileAttributesA(p);
1126+ unsigned m = 0;
1127+ if (att == INVALID_FILE_ATTRIBUTES) return 0;
1128+ m |= 0700;
1129+ if (!(att & FILE_ATTRIBUTE_READONLY)) m |= 0222;
1130+ if (att & FILE_ATTRIBUTE_DIRECTORY) m |= 0111;
1131+ return m;
1132+#else
1133+ struct stat st;
1134+ if (stat(p, &st) != 0) return 0;
1135+ return (unsigned)(st.st_mode & 07777);
1136+#endif
1137+}
1138+
1139+/* Read the whole file (capped) into b. Sets *binary when a NUL shows up in
1140+ * the first BIN_PROBE bytes - the same probe the read-only browser uses, so
1141+ * both plugins agree on what "binary" means on this node. */
1142+static int read_whole(const char *path, buf_t *b, size_t cap, int *binary,
1143+ const char **err)
1144+{
1145+ FILE *f;
1146+ long long sz;
1147+ char chunk[IO_CHUNK];
1148+ size_t total = 0;
1149+ int probed = 0;
1150+
1151+ if (binary) *binary = 0;
1152+ sz = file_size(path);
1153+ if (sz < 0) { *err = "cannot stat file"; return 0; }
1154+ if ((size_t)sz > cap) { *err = "file is larger than the read limit"; return 0; }
1155+
1156+ f = fopen(path, "rb");
1157+ if (!f) {
1158+ *err = (errno == EACCES) ? "permission denied" : "cannot open file";
1159+ return 0;
1160+ }
1161+ for (;;) {
1162+ size_t n = fread(chunk, 1, sizeof chunk, f);
1163+ if (n == 0) break;
1164+ if (!binary) {
1165+ /* fall through */
1166+ } else if (!probed) {
1167+ size_t i, stop = n < BIN_PROBE ? n : BIN_PROBE;
1168+ for (i = 0; i < stop; i++)
1169+ if (chunk[i] == '\0') { *binary = 1; break; }
1170+ if (total + n >= BIN_PROBE) probed = 1;
1171+ }
1172+ buf_add(b, chunk, n);
1173+ total += n;
1174+ if (total > cap) {
1175+ fclose(f);
1176+ *err = "file is larger than the read limit";
1177+ return 0;
1178+ }
1179+ }
1180+ fclose(f);
1181+ if (binary && !probed) {
1182+ /* small file: probe what we have */
1183+ size_t i, stop = b->n < BIN_PROBE ? b->n : BIN_PROBE;
1184+ for (i = 0; i < stop; i++)
1185+ if (b->p && b->p[i] == '\0') { *binary = 1; break; }
1186+ }
1187+ *err = NULL;
1188+ return 1;
1189+}
1190+
1191+/* First n lines, joined with a single \n and with no trailing newline -
1192+ * the same shape upstream headFile returns, so a caller that counts
1193+ * newlines counts lines and not an extra blank one. */
1194+static void text_head(const char *s, size_t len, long n, buf_t *out)
1195+{
1196+ size_t i = 0;
1197+ long lines = 0;
1198+ if (n < 0) { buf_add(out, s, len); return; }
1199+ if (n == 0) return;
1200+ while (i < len && lines < n) {
1201+ size_t start = i, e = i;
1202+ while (e < len && s[e] != '\n') e++;
1203+ if (lines) buf_putc(out, '\n');
1204+ if (e > start && s[e - 1] == '\r') e--; /* CRLF normalised */
1205+ buf_add(out, s + start, e - start);
1206+ lines++;
1207+ i = (e < len) ? e + 1 : len;
1208+ }
1209+}
1210+
1211+/* Last n lines. A trailing newline ends the last line rather than starting an
1212+ * empty one, so "a\nb\n" with tail=1 is "b\n" - the same reading the upstream
1213+ * tailFile takes, and the one that stops an off-by-one from appearing as
1214+ * "tail 1 gave me a blank line". */
1215+static void text_tail(const char *s, size_t len, long n, buf_t *out)
1216+{
1217+ size_t end = len;
1218+ long lines = 0;
1219+ size_t i;
1220+
1221+ if (n < 0) { buf_add(out, s, len); return; }
1222+ if (n == 0 || len == 0) return;
1223+ while (end > 0 && (s[end - 1] == '\n' || s[end - 1] == '\r')) end--;
1224+ if (end == 0) return;
1225+ for (i = end; i > 0; ) {
1226+ i--;
1227+ if (s[i] == '\n') {
1228+ lines++;
1229+ if (lines >= n) { i++; break; }
1230+ }
1231+ }
1232+ buf_add(out, s + i, end - i);
1233+}
1234+
1235+/* Write content atomically: write to <path>.tmp-<pid>, flush to disk, then
1236+ * rename over the target. A crash mid-write therefore leaves either the old
1237+ * file or the new one, never a half-written file - which matters because the
1238+ * whole point of this connector is that an agent edits files unattended. */
1239+static int write_atomic(const char *path, const char *content, size_t len,
1240+ const char **err)
1241+{
1242+ char tmp[PATH_SZ];
1243+ FILE *f;
1244+ int rc = 0;
1245+
1246+ snprintf(tmp, sizeof tmp, "%s.tmp-%ld", path, (long)
1247+#if defined(_WIN32)
1248+ GetCurrentProcessId()
1249+#else
1250+ (long)getpid()
1251+#endif
1252+ );
1253+ f = fopen(tmp, "wb");
1254+ if (!f) { *err = "cannot create temporary file"; return 0; }
1255+ if (len && fwrite(content, 1, len, f) != len) {
1256+ fclose(f);
1257+#if !defined(_WIN32)
1258+ remove(tmp);
1259+#else
1260+ DeleteFileA(tmp);
1261+#endif
1262+ *err = "write failed (disk full?)";
1263+ return 0;
1264+ }
1265+ if (fflush(f) != 0) { fclose(f); rc = 0; *err = "flush failed"; }
1266+ else {
1267+#if !defined(_WIN32)
1268+ fflush(f);
1269+ fsync(fileno(f));
1270+#endif
1271+ fclose(f);
1272+ rc = 1;
1273+ }
1274+ if (!rc) return 0;
1275+
1276+#if defined(_WIN32)
1277+ /* Windows rename() refuses to replace an existing file. */
1278+ {
1279+ char bak[PATH_SZ];
1280+ snprintf(bak, sizeof bak, "%s.bak-%ld", path, (long)GetCurrentProcessId());
1281+ MoveFileExA(tmp, path, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH);
1282+ if (GetFileAttributesA(tmp) != INVALID_FILE_ATTRIBUTES) {
1283+ /* fallback: copy over then delete the temp */
1284+ CopyFileA(tmp, path, FALSE);
1285+ DeleteFileA(tmp);
1286+ (void)bak;
1287+ }
1288+ if (GetFileAttributesA(path) == INVALID_FILE_ATTRIBUTES) {
1289+ *err = "rename failed";
1290+ return 0;
1291+ }
1292+ }
1293+#else
1294+ if (rename(tmp, path) != 0) {
1295+ remove(tmp);
1296+ *err = "rename failed";
1297+ return 0;
1298+ }
1299+#endif
1300+ *err = NULL;
1301+ return 1;
1302+}
1303+
1304+static int ensure_parent(const char *path)
1305+{
1306+ char parent[PATH_SZ];
1307+ parent_of(path, parent, sizeof parent);
1308+ if (strcmp(parent, path) == 0) return 0;
1309+ return mkpath(parent);
1310+}
1311+
1312+static int mkdir_p(const char *path)
1313+{
1314+ return mkpath(path);
1315+}
1316+
1317+static int copy_file(const char *src, const char *dst, const char **err)
1318+{
1319+ FILE *in, *out;
1320+ char chunk[IO_CHUNK];
1321+ size_t n;
1322+
1323+ in = fopen(src, "rb");
1324+ if (!in) { *err = "cannot open source"; return 0; }
1325+ if (ensure_parent(dst) != 0) { fclose(in); *err = "cannot create destination directory"; return 0; }
1326+ out = fopen(dst, "wb");
1327+ if (!out) { fclose(in); *err = "cannot create destination"; return 0; }
1328+ while ((n = fread(chunk, 1, sizeof chunk, in)) > 0) {
1329+ if (fwrite(chunk, 1, n, out) != n) {
1330+ fclose(in);
1331+ fclose(out);
1332+ *err = "copy failed (disk full?)";
1333+ return 0;
1334+ }
1335+ }
1336+ if (ferror(in)) { fclose(in); fclose(out); *err = "read error"; return 0; }
1337+ fclose(in);
1338+ if (fflush(out) != 0) { fclose(out); *err = "flush failed"; return 0; }
1339+ fclose(out);
1340+ *err = NULL;
1341+ return 1;
1342+}
1343+
1344+/* ------------------------------------------------------------------ */
1345+/* Glob matching */
1346+/* */
1347+/* search_files and excludePatterns need minimatch's useful subset with */
1348+/* no dependency: '*' and '?' within one path segment, '**' across */
1349+/* segments, and brace-free patterns. A pattern with no separator is */
1350+/* matched against the file NAME as well as the relative path, which is */
1351+/* what makes "*.log" behave like a person expects. */
1352+/* ------------------------------------------------------------------ */
1353+
1354+static int glob_here(const char *pat, const char *s, int slash_means_end)
1355+{
1356+ while (*pat) {
1357+ if (pat[0] == '*' && pat[1] == '*') {
1358+ const char *p2 = pat + 2;
1359+ if (*p2 == '/') p2++;
1360+ if (!*p2) return 1; /* ** matches rest */
1361+ for (;;) {
1362+ if (glob_here(p2, s, 0)) return 1;
1363+ while (*s && *s != '/') s++;
1364+ if (*s == '/') s++;
1365+ else break;
1366+ }
1367+ return 0;
1368+ }
1369+ if (*pat == '*') {
1370+ const char *p2 = pat + 1;
1371+ if (slash_means_end) {
1372+ for (;;) {
1373+ if (glob_here(p2, s, slash_means_end)) return 1;
1374+ if (*s == '/' || *s == '\\') return 0;
1375+ if (!*s) return 0;
1376+ s++;
1377+ }
1378+ }
1379+ for (;;) {
1380+ if (glob_here(p2, s, slash_means_end)) return 1;
1381+ if (!*s) return 0;
1382+ s++;
1383+ }
1384+ }
1385+ if (*pat == '?') {
1386+ if (!*s || *s == '/') return 0;
1387+ pat++;
1388+ s++;
1389+ continue;
1390+ }
1391+ if (*pat != *s) return 0;
1392+ pat++;
1393+ s++;
1394+ }
1395+ return *s == '\0';
1396+}
1397+
1398+static int glob_match(const char *pat, const char *s)
1399+{
1400+ if (!pat || !s) return 0;
1401+ return glob_here(pat, s, 1);
1402+}
1403+
1404+/* Excludes follow upstream isExcludedPath: a pattern with a star is matched
1405+ * on the relative path (and a trailing double-star-slash also matches the
1406+ * directory itself); a plain name matches at any depth. */
1407+static int is_excluded(const char *relpath, int is_dir, yyjson_val *excludes)
1408+{
1409+ size_t i, max;
1410+ if (!excludes || !yyjson_is_arr(excludes)) return 0;
1411+ max = yyjson_arr_size(excludes);
1412+ for (i = 0; i < max; i++) {
1413+ yyjson_val *v = yyjson_arr_get(excludes, i);
1414+ const char *pat;
1415+ char buf[NAME_SZ * 4];
1416+ if (!yyjson_is_str(v)) continue;
1417+ pat = yyjson_get_str(v);
1418+ if (!pat || !*pat) continue;
1419+ if (strchr(pat, '*')) {
1420+ if (glob_match(pat, relpath)) return 1;
1421+ {
1422+ size_t pl = strlen(pat);
1423+ if (pl > 3 && !strcmp(pat + pl - 3, "/**")) {
1424+ char cut[NAME_SZ * 4];
1425+ str_copy(cut, sizeof cut, pat);
1426+ cut[pl - 3] = '\0';
1427+ if (is_dir && glob_match(cut, relpath)) return 1;
1428+ }
1429+ }
1430+ continue;
1431+ }
1432+ if (glob_match(pat, relpath)) return 1;
1433+ snprintf(buf, sizeof buf, "**/%s", pat);
1434+ if (glob_match(buf, relpath)) return 1;
1435+ if (is_dir) {
1436+ snprintf(buf, sizeof buf, "**/%s/**", pat);
1437+ if (glob_match(buf, relpath)) return 1;
1438+ }
1439+ }
1440+ return 0;
1441+}
1442+
1443+/* ------------------------------------------------------------------ */
1444+/* Unified diff (enough of it to read like git's) */
1445+/* ------------------------------------------------------------------ */
1446+
1447+typedef struct {
1448+ char **line;
1449+ size_t n;
1450+} lines_t;
1451+
1452+static void lines_split(const char *s, size_t len, lines_t *out)
1453+{
1454+ size_t cap = 64, n = 0, start = 0, i;
1455+ char **v = (char **)malloc(cap * sizeof *v);
1456+ out->line = NULL;
1457+ out->n = 0;
1458+ if (!v) return;
1459+ for (i = 0; i <= len; i++) {
1460+ if (i == len || s[i] == '\n') {
1461+ size_t sl = i - start;
1462+ char *ln;
1463+ if (sl && s[start + sl - 1] == '\r') sl--; /* compare LF-only */
1464+ ln = (char *)malloc(sl + 1);
1465+ if (!ln) break;
1466+ memcpy(ln, s + start, sl);
1467+ ln[sl] = '\0';
1468+ if (n == cap) {
1469+ char **nv;
1470+ cap *= 2;
1471+ nv = (char **)realloc(v, cap * sizeof *v);
1472+ if (!nv) { free(ln); break; }
1473+ v = nv;
1474+ }
1475+ v[n++] = ln;
1476+ start = i + 1;
1477+ if (i == len) break;
1478+ }
1479+ }
1480+ out->line = v;
1481+ out->n = n;
1482+}
1483+
1484+static void lines_free(lines_t *l)
1485+{
1486+ size_t i;
1487+ for (i = 0; i < l->n; i++) free(l->line[i]);
1488+ free(l->line);
1489+ l->line = NULL;
1490+ l->n = 0;
1491+}
1492+
1493+/* Append one @@ hunk with its context. */
1494+static void diff_hunk(buf_t *out, lines_t *a, lines_t *b,
1495+ size_t a0, size_t a1, size_t b0, size_t b1)
1496+{
1497+ size_t i;
1498+ if (a1 > a0 || b1 > b0) {
1499+ buf_printf(out, "@@ -%u,%u +%u,%u @@\n",
1500+ (unsigned)(a0 + 1), (unsigned)(a1 - a0),
1501+ (unsigned)(b0 + 1), (unsigned)(b1 - b0));
1502+ for (i = a0; i < a1; i++) { buf_putc(out, '-'); buf_puts(out, a->line[i]); buf_putc(out, '\n'); }
1503+ for (i = b0; i < b1; i++) { buf_putc(out, '+'); buf_puts(out, b->line[i]); buf_putc(out, '\n'); }
1504+ }
1505+}
1506+
1507+/* A deliberately simple LCS-free diff: match the common prefix and suffix,
1508+ * then report the middle as one remove/add pair. Real git diffs of agent
1509+ * edits are almost always local, and a wrong-but-labelled diff is worse than
1510+ * a coarse honest one, so nothing here pretends to be Myers. */
1511+static void make_diff(buf_t *out, const char *an, size_t alen,
1512+ const char *bn, size_t blen, const char *name)
1513+{
1514+ lines_t a, b;
1515+ size_t pre = 0, suf = 0;
1516+
1517+ lines_split(an, alen, &a);
1518+ lines_split(bn, blen, &b);
1519+ while (pre < a.n && pre < b.n && !strcmp(a.line[pre], b.line[pre])) pre++;
1520+ while (suf + pre < a.n && suf + pre < b.n &&
1521+ !strcmp(a.line[a.n - 1 - suf], b.line[b.n - 1 - suf])) suf++;
1522+
1523+ buf_printf(out, "--- %s\n+++ %s\n", name, name);
1524+ if (a.n == b.n && pre == a.n) {
1525+ buf_puts(out, "(no changes)\n");
1526+ } else {
1527+ diff_hunk(out, &a, &b, pre, a.n - suf, pre, b.n - suf);
1528+ }
1529+ lines_free(&a);
1530+ lines_free(&b);
1531+}
1532+
1533+/* ------------------------------------------------------------------ */
1534+/* Directory helpers */
1535+/* ------------------------------------------------------------------ */
1536+
1537+typedef struct {
1538+ char name[NAME_SZ];
1539+ int is_dir;
1540+ int is_link;
1541+ long long size;
1542+ long long mtime;
1543+} dent_t;
1544+
1545+static int cmp_dent(const void *x, const void *y)
1546+{
1547+ const dent_t *a = (const dent_t *)x, *b = (const dent_t *)y;
1548+ if (a->is_dir != b->is_dir) return a->is_dir ? -1 : 1; /* dirs first */
1549+ return strcmp(a->name, b->name);
1550+}
1551+
1552+/* Read one directory, sorted, capped. Returns count or -1. */
1553+static long list_dir(const char *path, dent_t **out, const char **err)
1554+{
1555+ dent_t *v = NULL;
1556+ long n = 0, cap = 0;
1557+#if !defined(_WIN32)
1558+ DIR *d;
1559+ struct dirent *de;
1560+ d = opendir(path);
1561+ if (!d) {
1562+ *err = (errno == EACCES) ? "permission denied" :
1563+ (errno == ENOENT) ? "path does not exist" : "cannot read directory";
1564+ return -1;
1565+ }
1566+ while ((de = readdir(d)) != NULL) {
1567+ char full[PATH_SZ];
1568+ dent_t e;
1569+ if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue;
1570+ if (n == cap) {
1571+ dent_t *nv;
1572+ cap = cap ? cap * 2 : 128;
1573+ if (cap > MAX_ENTRIES) cap = MAX_ENTRIES;
1574+ nv = (dent_t *)realloc(v, (size_t)cap * sizeof *v);
1575+ if (!nv) break;
1576+ v = nv;
1577+ }
1578+ if (n >= MAX_ENTRIES) break;
1579+ memset(&e, 0, sizeof e);
1580+ str_copy(e.name, sizeof e.name, de->d_name);
1581+ path_join(full, sizeof full, path, de->d_name);
1582+ e.is_link = is_link_path(full);
1583+ e.is_dir = is_dir_path(full);
1584+ e.size = e.is_dir ? 0 : file_size(full);
1585+ e.mtime = file_mtime(full);
1586+ v[n++] = e;
1587+ }
1588+ closedir(d);
1589+#else
1590+ WIN32_FIND_DATAA fd;
1591+ HANDLE h;
1592+ char pat[PATH_SZ];
1593+ snprintf(pat, sizeof pat, "%s\\*", path);
1594+ h = FindFirstFileA(pat, &fd);
1595+ if (h == INVALID_HANDLE_VALUE) {
1596+ *err = "cannot read directory";
1597+ return -1;
1598+ }
1599+ do {
1600+ char full[PATH_SZ];
1601+ dent_t e;
1602+ if (!strcmp(fd.cFileName, ".") || !strcmp(fd.cFileName, "..")) continue;
1603+ if (n == cap) {
1604+ dent_t *nv;
1605+ cap = cap ? cap * 2 : 128;
1606+ if (cap > MAX_ENTRIES) cap = MAX_ENTRIES;
1607+ nv = (dent_t *)realloc(v, (size_t)cap * sizeof *v);
1608+ if (!nv) break;
1609+ v = nv;
1610+ }
1611+ if (n >= MAX_ENTRIES) break;
1612+ memset(&e, 0, sizeof e);
1613+ str_copy(e.name, sizeof e.name, fd.cFileName);
1614+ path_join(full, sizeof full, path, fd.cFileName);
1615+ e.is_link = (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
1616+ e.is_dir = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
1617+ {
1618+ ULARGE_INTEGER u;
1619+ u.LowPart = fd.nFileSizeLow;
1620+ u.HighPart = fd.nFileSizeHigh;
1621+ e.size = e.is_dir ? 0 : (long long)u.QuadPart;
1622+ }
1623+ {
1624+ ULARGE_INTEGER u;
1625+ u.LowPart = fd.ftLastWriteTime.dwLowDateTime;
1626+ u.HighPart = fd.ftLastWriteTime.dwHighDateTime;
1627+ e.mtime = (long long)(u.QuadPart / 10000000ULL - 11644473600ULL);
1628+ }
1629+ v[n++] = e;
1630+ } while (FindNextFileA(h, &fd));
1631+ FindClose(h);
1632+#endif
1633+ if (n > 1) qsort(v, (size_t)n, sizeof *v, cmp_dent);
1634+ *out = v;
1635+ *err = NULL;
1636+ return n;
1637+}
1638+
1639+/* ------------------------------------------------------------------ */
1640+/* MCP tools */
1641+/* */
1642+/* Each handler appends either the result text or a one-line reason to */
1643+/* *text and returns 0 (result) or 1 (isError). The dispatcher wraps */
1644+/* the text into {"content":[{"type":"text","text":...}],"isError":b}, */
1645+/* which is exactly what scorpiox-connector-mcp relays upstream. */
1646+/* */
1647+/* Error text is written for the MODEL, not for a log: it names the */
1648+/* path, says which rule refused it, and (where there is one) what to */
1649+/* do instead. "permission denied" alone sends an agent in circles. */
1650+/* ------------------------------------------------------------------ */
1651+
1652+typedef int (*tool_fn)(yyjson_val *args, buf_t *text);
1653+
1654+/* Refuse the "binary" case in a way that tells the caller what to use. */
1655+#define BINARY_HINT "file contains binary bytes; read_text_file returns text only - use get_file_info for metadata, or the files plugin to view it"
1656+
1657+static int tool_read_text_file(yyjson_val *args, buf_t *text)
1658+{
1659+ char raw[PATH_SZ], canon[PATH_SZ];
1660+ const char *err = NULL;
1661+ buf_t b;
1662+ int have_head = 0, have_tail = 0;
1663+ long head = -1, tail = -1;
1664+ int binary = 0;
1665+
1666+ if (!ju_field_str(args, "path", raw, sizeof raw))
1667+ return (buf_puts(text, "missing required parameter \"path\""), 1);
1668+ if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err))
1669+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
1670+ if (!is_regular(canon))
1671+ return (buf_printf(text, "%s: not a regular file", raw), 1);
1672+
1673+ head = ju_int(args, "head", -1, &have_head);
1674+ tail = ju_int(args, "tail", -1, &have_tail);
1675+ if (head < -1 || tail < -1)
1676+ return (buf_puts(text, "head and tail must be non-negative integers"), 1);
1677+
1678+ buf_init(&b);
1679+ if (!read_whole(canon, &b, READ_CAP, &binary, &err)) {
1680+ buf_printf(text, "%s: %s", raw, err ? err : "read failed");
1681+ buf_free(&b);
1682+ return 1;
1683+ }
1684+ if (binary) {
1685+ buf_printf(text, "%s: " BINARY_HINT, raw);
1686+ buf_free(&b);
1687+ return 1;
1688+ }
1689+ if (have_head && have_tail) {
1690+ buf_puts(text, "head and tail are mutually exclusive - send one or the other");
1691+ buf_free(&b);
1692+ return 1;
1693+ }
1694+ if (have_head) text_head(b.p ? b.p : "", b.n, head, text);
1695+ else if (have_tail) text_tail(b.p ? b.p : "", b.n, tail, text);
1696+ else buf_add(text, b.p ? b.p : "", b.n);
1697+ buf_free(&b);
1698+ return 0;
1699+}
1700+
1701+/* One element of read_multiple_files. Kept as a function so the loop that
1702+ * drives it stays readable. */
1703+static void read_one_path(const char *path, buf_t *out, int *first)
1704+{
1705+ char canon[PATH_SZ];
1706+ const char *err = NULL;
1707+ buf_t b;
1708+ int binary = 0;
1709+
1710+ /* each item below terminates with its own newline, so the separator is
1711+ * "---
1712+" and not "
1713+---
1714+" - that is what makes the output byte-split
1715+ * on a line of three dashes, exactly like upstream */
1716+ if (!*first) buf_puts(out, "---\n");
1717+ *first = 0;
1718+
1719+ if (!resolve_allowed(path, canon, sizeof canon, 'r', &err)) {
1720+ buf_printf(out, "%s: Error - %s\n", path, err ? err : "refused");
1721+ return;
1722+ }
1723+ if (!is_regular(canon)) {
1724+ buf_printf(out, "%s: Error - not a regular file\n", path);
1725+ return;
1726+ }
1727+ buf_init(&b);
1728+ if (!read_whole(canon, &b, READ_CAP, &binary, &err)) {
1729+ buf_printf(out, "%s: Error - %s\n", path, err ? err : "read failed");
1730+ buf_free(&b);
1731+ return;
1732+ }
1733+ if (binary) {
1734+ buf_printf(out, "%s: Error - binary file\n", path);
1735+ buf_free(&b);
1736+ return;
1737+ }
1738+ buf_printf(out, "%s:\n", path);
1739+ buf_add(out, b.p ? b.p : "", b.n);
1740+ buf_putc(out, '\n');
1741+ buf_free(&b);
1742+}
1743+
1744+static int tool_read_multiple_files(yyjson_val *args, buf_t *text)
1745+{
1746+ yyjson_val *arr = args ? yyjson_obj_get(args, "paths") : NULL;
1747+ size_t i, max;
1748+ int first = 1;
1749+
1750+ if (!arr || !yyjson_is_arr(arr) || yyjson_arr_size(arr) == 0)
1751+ return (buf_puts(text, "missing required parameter \"paths\" (a non-empty array of strings)"), 1);
1752+ max = yyjson_arr_size(arr);
1753+ if (max > 200) max = 200; /* one call must not swallow a node */
1754+ for (i = 0; i < max; i++) {
1755+ yyjson_val *v = yyjson_arr_get(arr, i);
1756+ const char *pv = ju_cstr(v); /* NUL-safe: never a truncated path */
1757+ if (pv && pv[0]) read_one_path(pv, text, &first);
1758+ }
1759+ return 0;
1760+}
1761+
1762+static int tool_write_file(yyjson_val *args, buf_t *text)
1763+{
1764+ char raw[PATH_SZ], canon[PATH_SZ];
1765+ const char *err = NULL;
1766+ const char *content;
1767+ size_t clen;
1768+
1769+ if (!ju_field_str(args, "path", raw, sizeof raw))
1770+ return (buf_puts(text, "missing required parameter \"path\""), 1);
1771+ if (!resolve_allowed(raw, canon, sizeof canon, 'w', &err))
1772+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
1773+ if (is_dir_path(canon))
1774+ return (buf_printf(text, "%s: that is a directory", raw), 1);
1775+ if (is_link_path(canon))
1776+ return (buf_printf(text, "%s: refusing to write through a symlink", raw), 1);
1777+
1778+ {
1779+ yyjson_val *cv = args ? yyjson_obj_get(args, "content") : NULL;
1780+ if (!cv) return (buf_puts(text, "missing required parameter \"content\""), 1);
1781+ if (!yyjson_is_str(cv))
1782+ return (buf_puts(text, "\"content\" must be a string"), 1);
1783+ content = yyjson_get_str(cv);
1784+ clen = yyjson_get_len(cv);
1785+ }
1786+ if (clen > WRITE_CAP)
1787+ return (buf_printf(text, "content is %llu bytes (limit %llu)",
1788+ (unsigned long long)clen, (unsigned long long)WRITE_CAP), 1);
1789+
1790+ if (ensure_parent(canon) != 0)
1791+ return (buf_printf(text, "%s: cannot create the parent directory", raw), 1);
1792+ if (!write_atomic(canon, content, clen, &err))
1793+ return (buf_printf(text, "%s: %s", raw, err ? err : "write failed"), 1);
1794+
1795+ buf_printf(text, "Successfully wrote %llu bytes to %s",
1796+ (unsigned long long)clen, raw);
1797+ return 0;
1798+}
1799+
1800+/* ------------------------------------------------------------------ */
1801+/* edit_file */
1802+/* */
1803+/* Upstream semantics, kept: edits apply in order, each to the result */
1804+/* of the ones before it; each replaces the FIRST match of oldText; */
1805+/* an exact match wins, and when there is none a run of whole lines */
1806+/* matches if each line is equal once leading and trailing whitespace */
1807+/* is ignored (newText then takes the file's indentation is NOT */
1808+/* re-derived - we keep the caller's text and say so in the diff); if */
1809+/* ANY edit has no match NOTHING is written and the error shows where */
1810+/* the file diverges; dryRun computes and returns the diff without */
1811+/* touching the disk. The file's own line ending is detected and */
1812+/* restored. */
1813+/* ------------------------------------------------------------------ */
1814+
1815+/* Find `needle` in `hay` (exact). Returns offset or (size_t)-1. */
1816+static size_t find_sub(const char *hay, size_t hlen, const char *needle, size_t nlen)
1817+{
1818+ size_t i;
1819+ if (nlen == 0 || nlen > hlen) return (size_t)-1;
1820+ for (i = 0; i + nlen <= hlen; i++)
1821+ if (!memcmp(hay + i, needle, nlen)) return i;
1822+ return (size_t)-1;
1823+}
1824+
1825+/* Whitespace-insensitive whole-line match. Returns start offset of the
1826+ * matching region and sets *endlen, or (size_t)-1. The match must start at
1827+ * a line boundary and the compared run must be followed by a newline when
1828+ * oldText ends with one. */
1829+static size_t find_lines(const char *hay, size_t hlen, const char *needle,
1830+ size_t nlen, size_t *matchlen)
1831+{
1832+ /* Split needle into lines (LF-only, trailing \n dropped). */
1833+ char *ndup;
1834+ char *nl[64];
1835+ size_t nlines = 0, i, start = 0;
1836+ char *hl[4096];
1837+ size_t hlines = 0, pos[4097];
1838+ size_t cand;
1839+
1840+ *matchlen = 0;
1841+ if (nlen == 0) return (size_t)-1;
1842+ ndup = (char *)malloc(nlen + 1);
1843+ if (!ndup) return (size_t)-1;
1844+ memcpy(ndup, needle, nlen);
1845+ ndup[nlen] = '\0';
1846+ if (nlen && ndup[nlen - 1] == '\n') ndup[nlen - 1] = '\0';
1847+ for (i = 0; ndup[i]; i++) {
1848+ if (ndup[i] == '\r') ndup[i] = '\0';
1849+ if (ndup[i] == '\n') {
1850+ ndup[i] = '\0';
1851+ if (nlines < 64) nl[nlines++] = ndup + start;
1852+ start = i + 1;
1853+ }
1854+ }
1855+ if (nlines < 64) nl[nlines++] = ndup + start;
1856+ /* oldText ended with a newline: that trailing "" is not a line to match,
1857+ * and the boundary is enforced separately below. */
1858+ if (nlen && needle[nlen - 1] == '\n' && nlines > 1 &&
1859+ nl[nlines - 1][0] == '\0') nlines--;
1860+ if (nlines == 0 || nlines > 64) { free(ndup); return (size_t)-1; }
1861+
1862+ /* Split haystack into lines, remembering offsets. */
1863+ start = 0;
1864+ for (i = 0; i <= hlen; i++) {
1865+ if (i == hlen || hay[i] == '\n') {
1866+ if (hlines < 4096) {
1867+ size_t lstart = start, lend = i;
1868+ /* strip a trailing \r for comparison, keep the byte in place */
1869+ pos[hlines] = lstart;
1870+ {
1871+ size_t sl = lstart, el = lend;
1872+ char *dup;
1873+ if (el > sl && hay[el - 1] == '\r') el--;
1874+ dup = (char *)malloc(el - sl + 1);
1875+ if (!dup) {
1876+ size_t k;
1877+ for (k = 0; k < hlines; k++) free(hl[k]);
1878+ free(ndup);
1879+ return (size_t)-1;
1880+ }
1881+ memcpy(dup, hay + sl, el - sl);
1882+ dup[el - sl] = '\0';
1883+ hl[hlines] = dup;
1884+ }
1885+ hlines++;
1886+ }
1887+ start = i + 1;
1888+ if (i == hlen) break;
1889+ }
1890+ }
1891+ if (hlines + 1 > 4096) { hlines = 4096; }
1892+
1893+ for (cand = 0; cand + nlines <= hlines && cand + nlines <= 4096; cand++) {
1894+ size_t j, ok = 1;
1895+ for (j = 0; j < nlines; j++) {
1896+ const char *a = nl[j], *b = hl[cand + j];
1897+ while (*a == ' ' || *a == '\t') a++;
1898+ while (*b == ' ' || *b == '\t') b++;
1899+ {
1900+ size_t la = strlen(a), lb = strlen(b);
1901+ while (la && (a[la - 1] == ' ' || a[la - 1] == '\t')) la--;
1902+ while (lb && (b[lb - 1] == ' ' || b[lb - 1] == '\t')) lb--;
1903+ if (la != lb || memcmp(a, b, la)) { ok = 0; break; }
1904+ }
1905+ }
1906+ if (ok) {
1907+ size_t s = pos[cand];
1908+ size_t e = pos[cand + nlines - 1];
1909+ /* The run must land on line boundaries. The last matched line
1910+ * ends at its newline (or at EOF); when oldText itself asked for
1911+ * the newline it is part of the match, when it did not the
1912+ * file's own newline is left alone - which is what keeps an edit
1913+ * from silently deleting the file's trailing newline. */
1914+ while (e < hlen && hay[e] != '\n') e++;
1915+ if (needle[nlen - 1] == '\n') {
1916+ if (e == hlen) { /* no newline to consume */
1917+ size_t k;
1918+ for (k = 0; k < hlines; k++) free(hl[k]);
1919+ free(ndup);
1920+ return (size_t)-1;
1921+ }
1922+ e++;
1923+ }
1924+ *matchlen = e - s;
1925+ {
1926+ size_t k;
1927+ for (k = 0; k < hlines; k++) free(hl[k]);
1928+ }
1929+ free(ndup);
1930+ return s;
1931+ }
1932+ }
1933+ {
1934+ size_t k;
1935+ for (k = 0; k < hlines; k++) free(hl[k]);
1936+ }
1937+ free(ndup);
1938+ return (size_t)-1;
1939+}
1940+
1941+/* Report the first diverging non-blank line of `cur` vs `old`, numbered. */
1942+static void describe_mismatch(buf_t *text, const char *cur, size_t curlen,
1943+ const char *old, size_t oldlen, size_t index)
1944+{
1945+ char probe[NAME_SZ];
1946+ size_t i, o = 0, shown = 0;
1947+ size_t plen = 0;
1948+
1949+ /* first non-empty line of oldText, trimmed */
1950+ while (o < oldlen && (old[o] == '\n' || old[o] == '\r' ||
1951+ old[o] == ' ' || old[o] == '\t')) o++;
1952+ while (o + plen < oldlen && plen < sizeof probe - 1 &&
1953+ old[o + plen] != '\n' && old[o + plen] != '\r') {
1954+ probe[plen] = old[o + plen];
1955+ plen++;
1956+ }
1957+ probe[plen] = '\0';
1958+ /* trim trailing spaces */
1959+ while (plen && (probe[plen - 1] == ' ' || probe[plen - 1] == '\t')) probe[--plen] = '\0';
1960+
1961+ buf_printf(text, "edit #%u did not match. ", (unsigned)(index + 1));
1962+ if (plen) {
1963+ long long best = -1;
1964+ double bestscore = -1;
1965+ /* Find the line of the file most similar to probe's first token. */
1966+ size_t ls = 0, ln = 1;
1967+ for (i = 0; i <= curlen; i++) {
1968+ if (i == curlen || cur[i] == '\n') {
1969+ size_t s = ls, e = i, m, hits = 0;
1970+ while (s < e && (cur[s] == ' ' || cur[s] == '\t')) s++;
1971+ while (e > s && (cur[e - 1] == ' ' || cur[e - 1] == '\t' ||
1972+ cur[e - 1] == '\r')) e--;
1973+ if (e > s && plen) {
1974+ for (m = s; m < e; m++) {
1975+ size_t k;
1976+ for (k = 0; k < plen; k++)
1977+ if (cur[m] == probe[k]) { hits++; break; }
1978+ }
1979+ {
1980+ double sc = (double)hits / (double)(e - s);
1981+ if (sc > bestscore) { bestscore = sc; best = (long long)ln; }
1982+ }
1983+ }
1984+ ls = i + 1;
1985+ ln++;
1986+ }
1987+ }
1988+ if (best > 0) {
1989+ buf_printf(text, "The closest line is %lld. ", best);
1990+ /* print up to 3 numbered lines around it */
1991+ {
1992+ size_t ls2 = 0, ln2 = 1;
1993+ for (i = 0; i <= curlen; i++) {
1994+ if (i == curlen || cur[i] == '\n') {
1995+ int phantom = (i == curlen && ls2 == curlen);
1996+ if (!phantom && ln2 >= (size_t)best - 1 && shown < 3) {
1997+ size_t s = ls2, e = (i < curlen) ? i : curlen;
1998+ buf_printf(text, "%lld| ", (long long)ln2);
1999+ for (; s < e && s < ls2 + 200; s++)
2000+ if (cur[s] != '\r') buf_putc(text, cur[s]);
2001+ buf_putc(text, '\n');
2002+ shown++;
2003+ }
2004+ ls2 = i + 1;
2005+ ln2++;
2006+ }
2007+ }
2008+ }
2009+ } else {
2010+ buf_puts(text, "Nothing in the file resembles oldText. ");
2011+ }
2012+ } else {
2013+ buf_puts(text, "oldText was blank. ");
2014+ }
2015+ buf_puts(text, "Copy oldText from a read_text_file of the current content and retry.");
2016+}
2017+
2018+static int tool_edit_file(yyjson_val *args, buf_t *text)
2019+{
2020+ char raw[PATH_SZ], canon[PATH_SZ];
2021+ const char *err = NULL;
2022+ yyjson_val *edits;
2023+ buf_t cur, work;
2024+ size_t i, max;
2025+ int dry_run;
2026+ char *orig = NULL;
2027+ size_t origlen = 0;
2028+ int eol_crlf = 0;
2029+
2030+ if (!ju_field_str(args, "path", raw, sizeof raw))
2031+ return (buf_puts(text, "missing required parameter \"path\""), 1);
2032+ if (!resolve_allowed(raw, canon, sizeof canon, 'w', &err))
2033+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2034+ if (!is_regular(canon))
2035+ return (buf_printf(text, "%s: not a regular file", raw), 1);
2036+
2037+ edits = args ? yyjson_obj_get(args, "edits") : NULL;
2038+ if (!edits || !yyjson_is_arr(edits) || yyjson_arr_size(edits) == 0)
2039+ return (buf_puts(text, "missing required parameter \"edits\" (a non-empty array of {oldText,newText})"), 1);
2040+ dry_run = ju_bool(args, "dryRun", 0);
2041+
2042+ buf_init(&cur);
2043+ if (!read_whole(canon, &cur, READ_CAP, NULL, &err)) {
2044+ buf_printf(text, "%s: %s", raw, err ? err : "read failed");
2045+ buf_free(&cur);
2046+ return 1;
2047+ }
2048+ /* detect the file's dominant line ending so the write restores it */
2049+ for (i = 0; i + 1 < cur.n; i++)
2050+ if (cur.p[i] == '\r' && cur.p[i + 1] == '\n') { eol_crlf = 1; break; }
2051+
2052+ /* normalise to LF for matching */
2053+ {
2054+ size_t o = 0;
2055+ for (i = 0; i < cur.n; i++)
2056+ if (!(cur.p[i] == '\r' && i + 1 < cur.n && cur.p[i + 1] == '\n'))
2057+ cur.p[o++] = cur.p[i];
2058+ cur.n = o;
2059+ if (cur.p) cur.p[o] = '\0';
2060+ }
2061+ orig = (char *)malloc(cur.n + 1);
2062+ if (!orig) { buf_free(&cur); return (buf_puts(text, "out of memory"), 1); }
2063+ memcpy(orig, cur.p ? cur.p : "", cur.n);
2064+ orig[cur.n] = '\0';
2065+ origlen = cur.n;
2066+
2067+ buf_init(&work);
2068+ buf_add(&work, orig, origlen);
2069+
2070+ max = yyjson_arr_size(edits);
2071+ if (max > 100) max = 100;
2072+ for (i = 0; i < max; i++) {
2073+ yyjson_val *e = yyjson_arr_get(edits, i);
2074+ const char *ot, *nt;
2075+ size_t otlen, ntlen, at, ml;
2076+ buf_t next;
2077+
2078+ if (!yyjson_is_obj(e)) {
2079+ buf_free(&work);
2080+ free(orig);
2081+ buf_free(&cur);
2082+ buf_puts(text, "each edit must be an object with oldText and newText");
2083+ return 1;
2084+ }
2085+ ot = ju_str(e, "oldText");
2086+ nt = ju_str(e, "newText");
2087+ if (!ot) {
2088+ buf_free(&work);
2089+ free(orig);
2090+ buf_free(&cur);
2091+ buf_printf(text, "edit #%u is missing \"oldText\"", (unsigned)(i + 1));
2092+ return 1;
2093+ }
2094+ if (!nt) nt = "";
2095+ otlen = strlen(ot);
2096+ ntlen = strlen(nt);
2097+ if (otlen == 0) {
2098+ buf_free(&work);
2099+ free(orig);
2100+ buf_free(&cur);
2101+ buf_printf(text, "edit #%u has empty oldText - that would insert at position 0; send a real anchor",
2102+ (unsigned)(i + 1));
2103+ return 1;
2104+ }
2105+
2106+ at = find_sub(work.p, work.n, ot, otlen);
2107+ ml = otlen;
2108+ if (at == (size_t)-1)
2109+ at = find_lines(work.p, work.n, ot, otlen, &ml);
2110+ if (at == (size_t)-1) {
2111+ describe_mismatch(text, work.p, work.n, ot, otlen, i);
2112+ buf_puts(text, " Nothing was written.");
2113+ buf_free(&work);
2114+ free(orig);
2115+ buf_free(&cur);
2116+ return 1;
2117+ }
2118+ buf_init(&next);
2119+ buf_add(&next, work.p, at);
2120+ buf_add(&next, nt, ntlen);
2121+ buf_add(&next, work.p + at + ml, work.n - at - ml);
2122+ buf_free(&work);
2123+ work = next;
2124+ }
2125+
2126+ if (!dry_run) {
2127+ buf_t outb;
2128+ const char *werr = NULL;
2129+ buf_init(&outb);
2130+ if (eol_crlf) {
2131+ for (i = 0; i < work.n; i++) {
2132+ if (work.p[i] == '\n') buf_putc(&outb, '\r');
2133+ buf_putc(&outb, work.p[i]);
2134+ }
2135+ } else {
2136+ buf_add(&outb, work.p, work.n);
2137+ }
2138+ if (!write_atomic(canon, outb.p ? outb.p : "", outb.n, &werr)) {
2139+ buf_free(&outb);
2140+ buf_free(&work);
2141+ free(orig);
2142+ buf_free(&cur);
2143+ buf_printf(text, "%s: %s", raw, werr ? werr : "write failed");
2144+ return 1;
2145+ }
2146+ buf_free(&outb);
2147+ }
2148+
2149+ make_diff(text, orig, origlen, work.p ? work.p : "", work.n, raw);
2150+ if (dry_run) buf_puts(text, "\n(dry run - nothing was written)\n");
2151+ buf_free(&work);
2152+ free(orig);
2153+ buf_free(&cur);
2154+ return 0;
2155+}
2156+
2157+/* ------------------------------------------------------------------ */
2158+/* The remaining tools */
2159+/* ------------------------------------------------------------------ */
2160+
2161+static int tool_create_directory(yyjson_val *args, buf_t *text)
2162+{
2163+ char raw[PATH_SZ], canon[PATH_SZ];
2164+ const char *err = NULL;
2165+
2166+ if (!ju_field_str(args, "path", raw, sizeof raw))
2167+ return (buf_puts(text, "missing required parameter \"path\""), 1);
2168+ if (!resolve_allowed(raw, canon, sizeof canon, 'w', &err))
2169+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2170+ if (is_dir_path(canon)) {
2171+ buf_printf(text, "Directory already exists: %s", raw);
2172+ return 0;
2173+ }
2174+ if (is_regular(canon))
2175+ return (buf_printf(text, "%s: a file already exists at that path", raw), 1);
2176+ if (mkdir_p(canon) != 0)
2177+ return (buf_printf(text, "%s: cannot create directory (%s)", raw,
2178+ strerror(errno)), 1);
2179+ buf_printf(text, "Successfully created directory %s", raw);
2180+ return 0;
2181+}
2182+
2183+static void emit_listing(buf_t *text, const char *path, const char *raw,
2184+ long n, dent_t *v, int with_sizes)
2185+{
2186+ long i;
2187+ long long tot_files = 0, tot_dirs = 0;
2188+ for (i = 0; i < n; i++) {
2189+ if (v[i].is_dir) tot_dirs++;
2190+ else tot_files++;
2191+ buf_puts(text, v[i].is_dir ? "[DIR] " : "[FILE] ");
2192+ buf_puts(text, v[i].name);
2193+ if (with_sizes && !v[i].is_dir)
2194+ buf_printf(text, " %lld bytes", v[i].size);
2195+ buf_putc(text, '\n');
2196+ }
2197+ if (n >= MAX_ENTRIES)
2198+ buf_printf(text, "(listing truncated at %d entries)\n", MAX_ENTRIES);
2199+ if (with_sizes)
2200+ buf_printf(text, "\n%d directories, %lld files\n",
2201+ (int)tot_dirs, tot_files);
2202+ (void)path;
2203+ (void)raw;
2204+}
2205+
2206+static int tool_list_directory(yyjson_val *args, buf_t *text)
2207+{
2208+ char raw[PATH_SZ], canon[PATH_SZ];
2209+ const char *err = NULL;
2210+ dent_t *v = NULL;
2211+ long n;
2212+
2213+ if (!ju_field_str(args, "path", raw, sizeof raw))
2214+ return (buf_puts(text, "missing required parameter \"path\""), 1);
2215+ if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err))
2216+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2217+ if (!is_dir_path(canon))
2218+ return (buf_printf(text, "%s: not a directory", raw), 1);
2219+ n = list_dir(canon, &v, &err);
2220+ if (n < 0) {
2221+ buf_printf(text, "%s: %s", raw, err ? err : "cannot read directory");
2222+ return 1;
2223+ }
2224+ emit_listing(text, canon, raw, n, v, 0);
2225+ free(v);
2226+ return 0;
2227+}
2228+
2229+/* Upstream says the tree is "formatted with 2-space indentation for
2230+ * readability", and an agent pastes this straight into a reply, so the
2231+ * indentation is part of the tool's output contract - not decoration. */
2232+static void indent(buf_t *b, int depth)
2233+{
2234+ int i;
2235+ for (i = 0; i < depth * 2; i++) buf_putc(b, ' ');
2236+}
2237+
2238+/* Whether the buffer ends with an entry (so a closing bracket needs its own
2239+ * line). An empty children array stays on one line: []. */
2240+static int body_has_entries(const buf_t *b)
2241+{
2242+ size_t i;
2243+ if (!b->p || b->n == 0) return 0;
2244+ i = b->n - 1;
2245+ while (i > 0 && (b->p[i] == ' ' || b->p[i] == '\n')) i--;
2246+ return b->p[i] != '[';
2247+}
2248+
2249+static int tree_walk(buf_t *b, const char *dir, const char *rel, int depth,
2250+ int max_depth, long *budget, yyjson_val *excludes,
2251+ int *truncated)
2252+{
2253+ dent_t *v = NULL;
2254+ const char *err = NULL;
2255+ long n, i;
2256+ int first = 1;
2257+
2258+ if (*budget <= 0) { *truncated = 1; return 0; }
2259+ n = list_dir(dir, &v, &err);
2260+ if (n < 0) return -1;
2261+ for (i = 0; i < n; i++) {
2262+ char child[PATH_SZ], crel[PATH_SZ];
2263+ if (*budget <= 0) { *truncated = 1; break; }
2264+ if (v[i].name[0] == '.') continue; /* dotfiles stay out of a tree */
2265+ (*budget)--;
2266+ path_join(child, sizeof child, dir, v[i].name);
2267+ if (rel[0]) snprintf(crel, sizeof crel, "%s/%s", rel, v[i].name);
2268+ else str_copy(crel, sizeof crel, v[i].name);
2269+ if (is_excluded(crel, v[i].is_dir, excludes)) continue;
2270+
2271+ if (!first) buf_putc(b, ',');
2272+ first = 0;
2273+ buf_putc(b, '\n');
2274+ indent(b, depth);
2275+ buf_puts(b, "{\"name\":");
2276+ json_str(b, v[i].name);
2277+ buf_puts(b, ", \"type\":");
2278+ buf_puts(b, v[i].is_dir ? "\"directory\"" : "\"file\"");
2279+ if (v[i].is_dir && depth < max_depth) {
2280+ int sub_trunc = 0;
2281+ buf_puts(b, ", \"children\":[");
2282+ tree_walk(b, child, crel, depth + 1, max_depth, budget, excludes,
2283+ &sub_trunc);
2284+ if (sub_trunc) *truncated = 1;
2285+ if (body_has_entries(b)) {
2286+ buf_putc(b, '\n');
2287+ indent(b, depth);
2288+ }
2289+ buf_putc(b, ']');
2290+ }
2291+ buf_putc(b, '}');
2292+ }
2293+ free(v);
2294+ return 0;
2295+}
2296+
2297+static int tool_directory_tree(yyjson_val *args, buf_t *text)
2298+{
2299+ char raw[PATH_SZ], canon[PATH_SZ];
2300+ const char *err = NULL;
2301+ int have = 0;
2302+ long long md = ju_int(args, "maxDepth", 4, &have);
2303+ long budget = WALK_BUDGET;
2304+ int truncated = 0;
2305+ yyjson_val *excludes = args ? yyjson_obj_get(args, "excludePatterns") : NULL;
2306+ buf_t body;
2307+
2308+ if (!ju_field_str(args, "path", raw, sizeof raw))
2309+ return (buf_puts(text, "missing required parameter \"path\""), 1);
2310+ if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err))
2311+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2312+ if (!is_dir_path(canon))
2313+ return (buf_printf(text, "%s: not a directory", raw), 1);
2314+ if (md < 0) md = 0;
2315+ if (md > MAX_DEPTH) md = MAX_DEPTH;
2316+
2317+ buf_init(&body);
2318+ buf_putc(&body, '[');
2319+ tree_walk(&body, canon, "", 1, (int)md, &budget, excludes, &truncated);
2320+ if (body_has_entries(&body)) {
2321+ buf_putc(&body, '\n');
2322+ indent(&body, 0);
2323+ }
2324+ buf_putc(&body, ']');
2325+ buf_add(text, body.p ? body.p : "[]", body.n);
2326+ buf_free(&body);
2327+ if (truncated)
2328+ buf_printf(text, "\n(truncated after %d entries; narrow the path or lower maxDepth)",
2329+ WALK_BUDGET);
2330+ return 0;
2331+}
2332+
2333+static int tool_move_file(yyjson_val *args, buf_t *text)
2334+{
2335+ char sraw[PATH_SZ], draw[PATH_SZ], src[PATH_SZ], dst[PATH_SZ];
2336+ const char *err = NULL;
2337+
2338+ if (!ju_field_str(args, "source", sraw, sizeof sraw))
2339+ return (buf_puts(text, "missing required parameter \"source\""), 1);
2340+ if (!ju_field_str(args, "destination", draw, sizeof draw))
2341+ return (buf_puts(text, "missing required parameter \"destination\""), 1);
2342+ if (!resolve_allowed(sraw, src, sizeof src, 'r', &err))
2343+ return (buf_printf(text, "source %s: %s", sraw, err ? err : "refused"), 1);
2344+ if (is_link_path(src))
2345+ return (buf_printf(text, "source %s: refusing to move a symlink", sraw), 1);
2346+ if (resolve_allowed(draw, dst, sizeof dst, 'r', &err)) {
2347+ if (is_dir_path(dst))
2348+ return (buf_printf(text, "%s: a directory already exists at the destination", draw), 1);
2349+ if (strcmp(src, dst) == 0) {
2350+ buf_printf(text, "Source and destination are the same file: %s", sraw);
2351+ return 0;
2352+ }
2353+ /* Upstream refuses to overwrite; so do we, silently-overwriting an
2354+ * operator's file is the one thing an agent should never get. */
2355+ return (buf_printf(text, "%s already exists - move nothing. Move to a new name instead.", draw), 1);
2356+ }
2357+ if (!resolve_allowed(draw, dst, sizeof dst, 'w', &err))
2358+ return (buf_printf(text, "destination %s: %s", draw, err ? err : "refused"), 1);
2359+ if (ensure_parent(dst) != 0)
2360+ return (buf_printf(text, "%s: cannot create the destination directory", draw), 1);
2361+
2362+#if defined(_WIN32)
2363+ if (!MoveFileExA(src, dst, MOVEFILE_WRITE_THROUGH)) {
2364+ DWORD e = GetLastError();
2365+ if (e == ERROR_NOT_SAME_DEVICE) {
2366+ if (!copy_file(src, dst, &err)) {
2367+ buf_printf(text, "%s: %s", sraw, err ? err : "copy failed");
2368+ return 1;
2369+ }
2370+ DeleteFileA(src);
2371+ } else {
2372+ buf_printf(text, "%s -> %s: Win32 error %lu", sraw, draw, (unsigned long)e);
2373+ return 1;
2374+ }
2375+ }
2376+#else
2377+ if (rename(src, dst) != 0) {
2378+ if (errno == EXDEV) {
2379+ /* Cross-device: copy then remove. Same visible result, one more
2380+ * window, so the removal only happens once the copy is on disk. */
2381+ if (!copy_file(src, dst, &err)) {
2382+ buf_printf(text, "%s -> %s: %s", sraw, draw, err ? err : "copy failed");
2383+ return 1;
2384+ }
2385+ if (remove(src) != 0) {
2386+ buf_printf(text, "copied %s to %s but could not remove the source (%s)",
2387+ sraw, draw, strerror(errno));
2388+ return 1;
2389+ }
2390+ } else {
2391+ buf_printf(text, "%s -> %s: %s", sraw, draw, strerror(errno));
2392+ return 1;
2393+ }
2394+ }
2395+#endif
2396+ buf_printf(text, "Successfully moved %s to %s", sraw, draw);
2397+ return 0;
2398+}
2399+
2400+/* A walk may only descend into paths still inside a root; re-checking each
2401+ * child also catches a symlink that a directory scan handed us. */
2402+static int is_allowed_for_walk(const char *canon_child)
2403+{
2404+ char pc[PATH_SZ];
2405+ if (denied_path(canon_child)) return 0;
2406+ if (root_contains(canon_child) >= 0) return 1;
2407+ if (canon_path(canon_child, pc, sizeof pc))
2408+ return root_contains(pc) >= 0 && !denied_path(pc);
2409+ return 0;
2410+}
2411+
2412+typedef struct {
2413+ buf_t *out;
2414+ long count;
2415+ int truncated;
2416+} search_ctx;
2417+
2418+static void search_walk(const char *dir, const char *rel, const char *pattern,
2419+ yyjson_val *excludes, long *budget, search_ctx *sc)
2420+{
2421+ dent_t *v = NULL;
2422+ const char *err = NULL;
2423+ long n, i;
2424+
2425+ if (*budget <= 0) { sc->truncated = 1; return; }
2426+ n = list_dir(dir, &v, &err);
2427+ if (n < 0) return; /* unreadable subtree: skip */
2428+ for (i = 0; i < n; i++) {
2429+ char child[PATH_SZ], crel[PATH_SZ];
2430+ if (*budget <= 0) { sc->truncated = 1; break; }
2431+ (*budget)--;
2432+ path_join(child, sizeof child, dir, v[i].name);
2433+ if (rel[0]) snprintf(crel, sizeof crel, "%s/%s", rel, v[i].name);
2434+ else str_copy(crel, sizeof crel, v[i].name);
2435+
2436+ /* excludes are checked before anything else, so an excluded subtree
2437+ * is never even opened (upstream #4162) */
2438+ if (is_excluded(crel, v[i].is_dir, excludes)) continue;
2439+ if (!is_allowed_for_walk(child)) { continue; }
2440+
2441+ if (sc->count < MAX_RESULTS) {
2442+ int hit = glob_match(pattern, crel) || glob_match(pattern, v[i].name);
2443+ if (hit) {
2444+ if (sc->count) buf_putc(sc->out, '\n');
2445+ buf_puts(sc->out, child);
2446+ sc->count++;
2447+ }
2448+ } else {
2449+ sc->truncated = 1;
2450+ }
2451+ if (v[i].is_dir) search_walk(child, crel, pattern, excludes, budget, sc);
2452+ }
2453+ free(v);
2454+}
2455+
2456+static int tool_search_files(yyjson_val *args, buf_t *text)
2457+{
2458+ char raw[PATH_SZ], canon[PATH_SZ], rel[PATH_SZ] = "";
2459+ const char *err = NULL;
2460+ char pattern[NAME_SZ];
2461+ yyjson_val *excludes;
2462+ search_ctx sc;
2463+ long budget = WALK_BUDGET;
2464+
2465+ if (!ju_field_str(args, "path", raw, sizeof raw))
2466+ return (buf_puts(text, "missing required parameter \"path\""), 1);
2467+ if (!ju_field_str(args, "pattern", pattern, sizeof pattern))
2468+ return (buf_puts(text, "missing required parameter \"pattern\""), 1);
2469+ if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err))
2470+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2471+ if (!is_dir_path(canon))
2472+ return (buf_printf(text, "%s: not a directory (search walks directories)", raw), 1);
2473+ excludes = args ? yyjson_obj_get(args, "excludePatterns") : NULL;
2474+
2475+ sc.out = text;
2476+ sc.count = 0;
2477+ sc.truncated = 0;
2478+ search_walk(canon, rel, pattern, excludes, &budget, &sc);
2479+ if (sc.count == 0) {
2480+ buf_puts(text, "(no matches)");
2481+ return 0;
2482+ }
2483+ if (sc.truncated)
2484+ buf_printf(text, "\n(truncated: %d matches shown, walk budget %d entries; narrow the path or add excludePatterns)",
2485+ (int)sc.count, WALK_BUDGET);
2486+ return 0;
2487+}
2488+
2489+/* One timestamp as a JSON string (or null). */
2490+static void json_time(buf_t *b, long long t)
2491+{
2492+ char iso[40];
2493+ if (t <= 0) { buf_puts(b, "null"); return; }
2494+ fmt_iso(t, iso, sizeof iso);
2495+ json_str(b, iso);
2496+}
2497+
2498+static long long file_atime(const char *p)
2499+{
2500+#if defined(_WIN32)
2501+ WIN32_FILE_ATTRIBUTE_DATA d;
2502+ ULARGE_INTEGER u;
2503+ if (!GetFileAttributesExA(p, GetFileExInfoStandard, &d)) return 0;
2504+ u.LowPart = d.ftLastAccessTime.dwLowDateTime;
2505+ u.HighPart = d.ftLastAccessTime.dwHighDateTime;
2506+ return (long long)(u.QuadPart / 10000000ULL - 11644473600ULL);
2507+#else
2508+ struct stat st;
2509+ if (stat(p, &st) != 0) return 0;
2510+ return (long long)st.st_atime;
2511+#endif
2512+}
2513+
2514+static int tool_get_file_info(yyjson_val *args, buf_t *text)
2515+{
2516+ char raw[PATH_SZ], canon[PATH_SZ];
2517+ const char *err = NULL;
2518+
2519+ if (!ju_field_str(args, "path", raw, sizeof raw))
2520+ return (buf_puts(text, "missing required parameter \"path\""), 1);
2521+ if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err))
2522+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2523+
2524+ buf_puts(text, "{\n \"path\":");
2525+ json_str(text, canon);
2526+ buf_puts(text, is_dir_path(canon)
2527+ ? ",\n \"type\":\"directory\""
2528+ : ",\n \"type\":\"file\"");
2529+ buf_printf(text, ",\n \"size\":%lld", file_size(canon));
2530+ buf_puts(text, ",\n \"created\":");
2531+ json_time(text, 0); /* birth time is not portable */
2532+ buf_puts(text, ",\n \"modified\":");
2533+ json_time(text, file_mtime(canon));
2534+ buf_puts(text, ",\n \"accessed\":");
2535+ json_time(text, file_atime(canon));
2536+ buf_printf(text, ",\n \"isFile\":%s", is_regular(canon) ? "true" : "false");
2537+ buf_printf(text, ",\n \"isDirectory\":%s", is_dir_path(canon) ? "true" : "false");
2538+ buf_printf(text, ",\n \"isSymlink\":%s", is_link_path(canon) ? "true" : "false");
2539+ buf_printf(text, ",\n \"mode\":\"%04o\"\n}\n", file_mode(canon));
2540+ return 0;
2541+}
2542+
2543+static int tool_list_allowed_directories(yyjson_val *args, buf_t *text)
2544+{
2545+ int i;
2546+ (void)args;
2547+ buf_printf(text, "Allowed directories (%d):\n", g_root_count);
2548+ if (g_root_count == 0)
2549+ buf_puts(text, "(none configured - the plugin has nothing it may touch)");
2550+ for (i = 0; i < g_root_count; i++) {
2551+ buf_puts(text, g_roots[i].canonical);
2552+ if (strcmp(g_roots[i].configured, g_roots[i].canonical) != 0)
2553+ buf_printf(text, " (configured as %s)", g_roots[i].configured);
2554+ if (!g_roots[i].exists) buf_puts(text, " [does not exist]");
2555+ else if (!g_roots[i].is_dir) buf_puts(text, " [not a directory]");
2556+ buf_putc(text, '\n');
2557+ }
2558+ return 0;
2559+}
2560+
2561+/* ------------------------------------------------------------------ */
2562+/* Tool registry */
2563+/* */
2564+/* Descriptions are written to be read by a model choosing a tool, so */
2565+/* they say when to use this one and what the parameters mean, and every */
2566+/* one ends with the same reminder: it only works inside the allowed */
2567+/* directories. The inputSchema is what the router hands to clang's */
2568+/* MAX_TOOLS 512 budget, so it stays compact. */
2569+/* ------------------------------------------------------------------ */
2570+
2571+typedef struct {
2572+ const char *name;
2573+ const char *title;
2574+ const char *desc;
2575+ const char *schema;
2576+ int read_only;
2577+ int destructive;
2578+ tool_fn fn;
2579+} tool_def;
2580+
2581+#define S_PROPS(p) "{\"type\":\"object\",\"properties\":{" p "},\"required\""
2582+
2583+static const tool_def TOOLS[TOOLS_N] = {
2584+{"read_text_file", "Read Text File",
2585+ "Read the complete contents of a file as text. Use head for the first N lines "
2586+ "or tail for the last N (send at most one). Fails on binary files; use "
2587+ "get_file_info for metadata. Only works within allowed directories.",
2588+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute file path\"},"
2589+ "\"head\":{\"type\":\"integer\",\"description\":\"Return only the first N lines\"},"
2590+ "\"tail\":{\"type\":\"integer\",\"description\":\"Return only the last N lines\"}},"
2591+ "\"required\":[\"path\"]}", 1, 0, tool_read_text_file},
2592+
2593+{"read_multiple_files", "Read Multiple Files",
2594+ "Read several files in one call - cheaper than one read per file when "
2595+ "comparing or diffing. Each result is prefixed with its path and separated by "
2596+ "a line of three dashes; a file that fails reports its error without stopping "
2597+ "the rest. Only works within allowed directories.",
2598+ "{\"type\":\"object\",\"properties\":{\"paths\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},"
2599+ "\"description\":\"Absolute file paths (up to 200)\"}},\"required\":[\"paths\"]}", 1, 0,
2600+ tool_read_multiple_files},
2601+
2602+{"write_file", "Write File",
2603+ "Create or completely overwrite a file. Content is written to a temporary "
2604+ "file and renamed into place, so a crash cannot leave a half-written file. "
2605+ "Missing parent directories are created. Only works within allowed directories.",
2606+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute file path\"},"
2607+ "\"content\":{\"type\":\"string\",\"description\":\"Exact bytes to write\"}},\"required\":[\"path\",\"content\"]}",
2608+ 0, 1, tool_write_file},
2609+
2610+{"edit_file", "Edit File",
2611+ "Apply targeted replacements to a text file. Edits apply in order and each "
2612+ "replaces the first match of its oldText; oldText must match exactly, except "
2613+ "that LF/CRLF never matters and a run of whole lines matches when each line "
2614+ "is equal ignoring leading and trailing whitespace. If any edit fails to "
2615+ "match, NOTHING is written and the reply shows the closest numbered lines. "
2616+ "Set dryRun to see the diff without touching the disk. Only works within "
2617+ "allowed directories.",
2618+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute file path\"},"
2619+ "\"edits\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"oldText\":{\"type\":\"string\"},"
2620+ "\"newText\":{\"type\":\"string\"}},\"required\":[\"oldText\",\"newText\"]}},\"dryRun\":{\"type\":\"boolean\","
2621+ "\"description\":\"Compute and return the diff without writing\"}},\"required\":[\"path\",\"edits\"]}",
2622+ 0, 1, tool_edit_file},
2623+
2624+{"create_directory", "Create Directory",
2625+ "Create a directory and any missing parents. Succeeds if it already exists. "
2626+ "Only works within allowed directories.",
2627+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory path\"}},"
2628+ "\"required\":[\"path\"]}", 0, 0, tool_create_directory},
2629+
2630+{"list_directory", "List Directory",
2631+ "List entries directly inside a directory, each marked [DIR] or [FILE], "
2632+ "directories first then alphabetical. For a recursive view use directory_tree. "
2633+ "Only works within allowed directories.",
2634+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory path\"}},"
2635+ "\"required\":[\"path\"]}", 1, 0, tool_list_directory},
2636+
2637+{"directory_tree", "Directory Tree",
2638+ "Recursive tree of a directory as JSON: name, type (file/directory) and "
2639+ "children for directories. maxDepth bounds the depth (default 4); "
2640+ "excludePatterns are glob patterns matched against the relative path. Dot "
2641+ "entries are omitted. Only works within allowed directories.",
2642+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory path\"},"
2643+ "\"maxDepth\":{\"type\":\"integer\",\"description\":\"Levels to descend (0-24, default 4)\"},"
2644+ "\"excludePatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},"
2645+ "\"description\":\"Globs such as node_modules or *.tmp matched on the relative path\"}},"
2646+ "\"required\":[\"path\"]}", 1, 0, tool_directory_tree},
2647+
2648+{"move_file", "Move File",
2649+ "Move or rename a file or directory. Will NOT overwrite an existing "
2650+ "destination - move to a new name instead. A cross-device move falls back to "
2651+ "copy-then-delete. Only works within allowed directories.",
2652+ "{\"type\":\"object\",\"properties\":{\"source\":{\"type\":\"string\",\"description\":\"Absolute current path\"},"
2653+ "\"destination\":{\"type\":\"string\",\"description\":\"Absolute new path (must not exist)\"}},"
2654+ "\"required\":[\"source\",\"destination\"]}", 0, 1, tool_move_file},
2655+
2656+{"search_files", "Search Files",
2657+ "Recursively find files and directories whose name or relative path matches a "
2658+ "glob pattern such as *.c or test_*.py. excludePatterns prunes subtrees "
2659+ "(node_modules, .git) before they are ever opened. Returns absolute paths. "
2660+ "Only works within allowed directories.",
2661+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory to search\"},"
2662+ "\"pattern\":{\"type\":\"string\",\"description\":\"Glob, e.g. *.log or **/README*\"},"
2663+ "\"excludePatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},"
2664+ "\"description\":\"Globs pruned from the walk\"}},\"required\":[\"path\",\"pattern\"]}", 1, 0,
2665+ tool_search_files},
2666+
2667+{"get_file_info", "Get File Info",
2668+ "Size, timestamps, type, symlink-ness and permission bits of one path. Use "
2669+ "this before reading anything large. Only works within allowed directories.",
2670+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute path\"}},"
2671+ "\"required\":[\"path\"]}", 1, 0, tool_get_file_info},
2672+
2673+{"list_allowed_directories", "List Allowed Directories",
2674+ "Report the directories this server may read and write, with the canonical "
2675+ "path each one really resolves to. Call this first when a path is refused so "
2676+ "you can pick a path inside a root.",
2677+ "{\"type\":\"object\",\"properties\":{}}", 1, 0, tool_list_allowed_directories}
2678+};
2679+
2680+/* ------------------------------------------------------------------ */
2681+/* --mcp : MCP JSON-RPC 2.0 over stdio */
2682+/* */
2683+/* Contract as the router drives it (scorpiox-connector-mcp): one JSON */
2684+/* object per line, responses on stdout terminated by \n, and nothing */
2685+/* else ever printed to stdout. Logs therefore go to stderr, a malformed */
2686+/* line is answered with -32700 (the router skips unparseable lines, but */
2687+/* an id-less parse error is what a client needs to see it is talking to */
2688+/* a real server), and a notification gets no reply at all. */
2689+/* */
2690+/* Content-Length framing is tolerated on input because a few clients */
2691+/* speak LSP-style headers; output is always newline-delimited. */
2692+/* ------------------------------------------------------------------ */
2693+
2694+static void log_err(const char *fmt, ...)
2695+{
2696+ va_list ap;
2697+ fputs(PLUGIN_ID ": ", stderr);
2698+ va_start(ap, fmt);
2699+ vfprintf(stderr, fmt, ap);
2700+ va_end(ap);
2701+ fputc('\n', stderr);
2702+}
2703+
2704+static void send_msg(const char *json)
2705+{
2706+ fputs(json, stdout);
2707+ fputc('\n', stdout);
2708+ fflush(stdout);
2709+}
2710+
2711+static void send_result(const char *id_raw, const char *result_json)
2712+{
2713+ buf_t b;
2714+ if (!id_raw) return; /* notification */
2715+ buf_init(&b);
2716+ buf_printf(&b, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":%s}",
2717+ id_raw, result_json ? result_json : "{}");
2718+ send_msg(b.p ? b.p : "{}");
2719+ buf_free(&b);
2720+}
2721+
2722+static void send_error(const char *id_raw, int code, const char *msg)
2723+{
2724+ buf_t b;
2725+ /* A parse error has no id to echo, but JSON-RPC still wants the
2726+ * client to see it: answer with id:null. Only a request we know is a
2727+ * notification (an id-less, method-bearing line) stays silent. */
2728+ buf_init(&b);
2729+ buf_printf(&b, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":%d,\"message\":",
2730+ id_raw ? id_raw : "null", code);
2731+ json_str(&b, msg ? msg : "error");
2732+ buf_puts(&b, "}}");
2733+ send_msg(b.p ? b.p : "{}");
2734+ buf_free(&b);
2735+}
2736+
2737+/* The id verbatim (number or string) so it round-trips byte-exact. */
2738+static char *id_raw_of(yyjson_val *root)
2739+{
2740+ yyjson_val *id = yyjson_obj_get(root, "id");
2741+ char *s;
2742+ if (!id) return NULL; /* a notification */
2743+ s = yyjson_val_write(id, 0, NULL);
2744+ return s ? s : strdup("null");
2745+}
2746+
2747+static void emit_tools_list(const char *id_raw)
2748+{
2749+ buf_t b;
2750+ int i;
2751+ buf_init(&b);
2752+ buf_puts(&b, "{\"tools\":[");
2753+ for (i = 0; i < TOOLS_N; i++) {
2754+ if (i) buf_putc(&b, ',');
2755+ buf_puts(&b, "{\"name\":");
2756+ json_str(&b, TOOLS[i].name);
2757+ buf_puts(&b, ",\"title\":");
2758+ json_str(&b, TOOLS[i].title);
2759+ buf_puts(&b, ",\"description\":");
2760+ json_str(&b, TOOLS[i].desc);
2761+ buf_puts(&b, ",\"inputSchema\":");
2762+ buf_puts(&b, TOOLS[i].schema);
2763+ buf_puts(&b, ",\"annotations\":{\"readOnlyHint\":");
2764+ buf_puts(&b, TOOLS[i].read_only ? "true" : "false");
2765+ buf_puts(&b, ",\"destructiveHint\":");
2766+ buf_puts(&b, TOOLS[i].destructive ? "true" : "false");
2767+ buf_puts(&b, ",\"idempotentHint\":true,\"openWorldHint\":false}");
2768+ buf_putc(&b, '}');
2769+ }
2770+ buf_puts(&b, "]}");
2771+ send_result(id_raw, b.p);
2772+ buf_free(&b);
2773+}
2774+
2775+static void handle_tools_call(const char *id_raw, yyjson_val *params)
2776+{
2777+ const char *name = ju_str(params, "name");
2778+ yyjson_val *arguments = params ? yyjson_obj_get(params, "arguments") : NULL;
2779+ buf_t text;
2780+ int is_err;
2781+ int idx;
2782+ buf_t out;
2783+
2784+ if (!name || !*name) {
2785+ send_error(id_raw, -32602, "missing tool name");
2786+ return;
2787+ }
2788+ idx = tool_index(name);
2789+ if (idx < 0) {
2790+ send_error(id_raw, -32602, "unknown tool");
2791+ return;
2792+ }
2793+ if (g_tool_off[idx]) {
2794+ buf_t why;
2795+ buf_init(&why);
2796+ buf_printf(&why, "tool \"%s\" is disabled in this connector's permissions - "
2797+ "enable it in the filesystem plugin page (Allowed Roots & Permissions)",
2798+ TOOLS[idx].name);
2799+ buf_init(&out);
2800+ buf_puts(&out, "{\"isError\":true,\"content\":[{\"type\":\"text\",\"text\":");
2801+ json_str(&out, why.p ? why.p : "");
2802+ buf_puts(&out, "}]}");
2803+ send_result(id_raw, out.p);
2804+ buf_free(&out);
2805+ buf_free(&why);
2806+ return;
2807+ }
2808+ if (arguments && !yyjson_is_obj(arguments)) arguments = NULL;
2809+
2810+ buf_init(&text);
2811+ is_err = TOOLS[idx].fn(arguments, &text);
2812+
2813+ buf_init(&out);
2814+ buf_puts(&out, "{\"isError\":");
2815+ buf_puts(&out, is_err ? "true" : "false");
2816+ buf_puts(&out, ",\"content\":[{\"type\":\"text\",\"text\":");
2817+ json_str(&out, text.p ? text.p : "");
2818+ buf_puts(&out, "}]}");
2819+ send_result(id_raw, out.p);
2820+ buf_free(&out);
2821+ buf_free(&text);
2822+}
2823+
2824+static void handle_line(const char *line)
2825+{
2826+ yyjson_doc *doc;
2827+ yyjson_val *root, *params;
2828+ const char *method;
2829+ char *id_raw;
2830+
2831+ if (!line) return;
2832+ while (*line == ' ' || *line == '\t') line++;
2833+ if (!*line) return;
2834+
2835+ doc = yyjson_read(line, strlen(line), 0);
2836+ if (!doc) {
2837+ send_error(NULL, -32700, "parse error");
2838+ return;
2839+ }
2840+ root = yyjson_doc_get_root(doc);
2841+ if (!yyjson_is_obj(root)) {
2842+ yyjson_doc_free(doc);
2843+ send_error(NULL, -32700, "parse error");
2844+ return;
2845+ }
2846+ method = ju_str(root, "method");
2847+ id_raw = id_raw_of(root);
2848+ params = yyjson_obj_get(root, "params");
2849+
2850+ if (!method) {
2851+ if (id_raw) send_error(id_raw, -32600, "missing method");
2852+ free(id_raw);
2853+ yyjson_doc_free(doc);
2854+ return;
2855+ }
2856+
2857+ if (!strcmp(method, "initialize")) {
2858+ buf_t b;
2859+ const char *want = ju_str(params, "protocolVersion");
2860+ buf_init(&b);
2861+ buf_puts(&b, "{\"protocolVersion\":");
2862+ /* Answer the client's version when it is one we speak, else ours:
2863+ * 2024-11-05 is what scorpiox-connector-mcp asks for. */
2864+ json_str(&b, (want && (!strcmp(want, "2024-11-05") || !strcmp(want, "2025-03-26") ||
2865+ !strcmp(want, "2025-06-18"))) ? want : MCP_PROTO);
2866+ buf_puts(&b, ",\"capabilities\":{\"tools\":{\"listChanged\":false}},\"serverInfo\":{");
2867+ buf_puts(&b, "\"name\":\"");
2868+ buf_puts(&b, PLUGIN_ID);
2869+ buf_puts(&b, "\",\"version\":\"");
2870+ buf_puts(&b, PLUGIN_VER);
2871+ buf_puts(&b, "\"},\"instructions\":");
2872+ json_str(&b,
2873+ "Sandboxed filesystem tools. Every path is canonicalised and "
2874+ "must resolve inside the allowed roots; traversal and symlink "
2875+ "escapes are refused. Call list_allowed_directories first if "
2876+ "a path is refused.");
2877+ buf_putc(&b, '}');
2878+ send_result(id_raw, b.p);
2879+ buf_free(&b);
2880+ } else if (!strncmp(method, "notifications/", 14) || !strcmp(method, "ping")) {
2881+ if (id_raw && !strcmp(method, "ping")) send_result(id_raw, "{}");
2882+ } else if (!strcmp(method, "tools/list")) {
2883+ if (id_raw) {
2884+ init_roots();
2885+ emit_tools_list(id_raw);
2886+ }
2887+ } else if (!strcmp(method, "tools/call")) {
2888+ init_roots();
2889+ handle_tools_call(id_raw, params);
2890+ } else if (!strcmp(method, "resources/list")) {
2891+ if (id_raw) send_result(id_raw, "{\"resources\":[]}");
2892+ } else if (!strcmp(method, "resources/templates/list")) {
2893+ if (id_raw) send_result(id_raw, "{\"resourceTemplates\":[]}");
2894+ } else if (!strcmp(method, "prompts/list")) {
2895+ if (id_raw) send_result(id_raw, "{\"prompts\":[]}");
2896+ } else if (!strcmp(method, "logging/setLevel")) {
2897+ if (id_raw) send_result(id_raw, "{}");
2898+ } else {
2899+ if (id_raw) send_error(id_raw, -32601, "method not found");
2900+ }
2901+
2902+ free(id_raw);
2903+ yyjson_doc_free(doc);
2904+}
2905+
2906+/* Read one request. Newline-delimited, with Content-Length framing accepted
2907+ * because a handful of clients emit LSP headers instead of newlines. */
2908+static int read_request_line(buf_t *line)
2909+{
2910+ static char rb[IO_CHUNK];
2911+ static size_t rn, rp;
2912+ long long want = -1;
2913+
2914+ line->n = 0;
2915+ for (;;) {
2916+ if (rp < rn) {
2917+ size_t i = rp;
2918+ int nl = 0;
2919+ while (i < rn && rb[i] != '\n') i++;
2920+ if (i < rn) nl = 1;
2921+ {
2922+ size_t take = i - rp;
2923+ char tmp[IO_CHUNK + 1]; /* +1: the terminator below */
2924+ if (take > 0) memcpy(tmp, rb + rp, take);
2925+ rp = i + (nl ? 1 : 0);
2926+ tmp[take] = '\0';
2927+ while (take > 0 && (tmp[take - 1] == '\r' || tmp[take - 1] == ' '))
2928+ tmp[--take] = '\0';
2929+ if (want < 0 && !strncmp(tmp, "Content-Length:", 15)) {
2930+ want = strtoll(tmp + 15, NULL, 10);
2931+ continue;
2932+ }
2933+ if (want < 0 && take == 0) continue; /* header blank */
2934+ buf_add(line, tmp, take);
2935+ if (want < 0) {
2936+ /* Newline-delimited: a chunk without '\n' is not a line,
2937+ * it is the front half of one. Only return when the
2938+ * terminator was actually seen (or at EOF below). */
2939+ if (nl) return 1;
2940+ continue;
2941+ }
2942+ if ((long long)line->n >= want) { /* framed body */
2943+ if (line->p && (size_t)want < line->cap) line->p[want] = '\0';
2944+ line->n = (size_t)want;
2945+ want = -1;
2946+ return 1;
2947+ }
2948+ buf_putc(line, '\n');
2949+ continue;
2950+ }
2951+ }
2952+ if (rp >= rn) { rn = 0; rp = 0; }
2953+ rn = fread(rb, 1, sizeof rb, stdin);
2954+ if (rn == 0) return line->n ? 1 : 0;
2955+ }
2956+}
2957+
2958+static int mode_mcp(void)
2959+{
2960+ buf_t line;
2961+#if defined(_WIN32)
2962+ _setmode(_fileno(stdout), O_BINARY); /* \n stays \n, no CRLF */
2963+ _setmode(_fileno(stdin), O_BINARY);
2964+#endif
2965+ buf_init(&line);
2966+ while (read_request_line(&line)) {
2967+ if (line.n > MCP_LINE_CAP) {
2968+ log_err("request line exceeds %d bytes; dropping", (int)MCP_LINE_CAP);
2969+ send_error(NULL, -32600, "request too large");
2970+ continue;
2971+ }
2972+ if (line.n) handle_line(line.p);
2973+ }
2974+ buf_free(&line);
2975+ return 0;
2976+}
2977+
2978+/* ------------------------------------------------------------------ */
2979+/* Config persistence (the Setup UI writes what --mcp reads) */
2980+/* ------------------------------------------------------------------ */
2981+
2982+/* Atomic like write_file: same tmp+rename discipline, because a half-written
2983+ * roots.json would silently widen or narrow the sandbox. */
2984+static int save_roots_file(void)
2985+{
2986+ char dir[PATH_SZ], tmp[PATH_SZ];
2987+ buf_t b;
2988+ FILE *f;
2989+ int i;
2990+
2991+ connectors_dir(dir, sizeof dir);
2992+ if (mkpath(dir) != 0) return -1;
2993+ snprintf(tmp, sizeof tmp, "%s", g_roots_file);
2994+ if (strlen(tmp) + 12 >= sizeof tmp) return -1;
2995+ str_copy(tmp + strlen(tmp), sizeof tmp - strlen(tmp), ".tmp");
2996+
2997+ buf_init(&b);
2998+ buf_puts(&b, "{\n \"roots\": [");
2999+ for (i = 0; i < g_root_count; i++) {
3000+ if (i) buf_putc(&b, ',');
3001+ buf_puts(&b, "\n ");
3002+ json_str(&b, g_roots[i].configured[0] ? g_roots[i].configured
3003+ : g_roots[i].canonical);
3004+ }
3005+ buf_puts(&b, g_root_count ? "\n ],\n" : "],\n");
3006+ buf_puts(&b, " \"denied\": [");
3007+ for (i = 0; i < deny_count; i++) {
3008+ if (i) buf_putc(&b, ',');
3009+ buf_puts(&b, "\n ");
3010+ json_str(&b, g_deny[i]);
3011+ }
3012+ buf_puts(&b, deny_count ? "\n ],\n" : "],\n");
3013+ buf_puts(&b, " \"permissions\": {\n");
3014+ for (i = 0; i < TOOLS_N; i++) {
3015+ buf_printf(&b, " \"%s\": %s%s\n", TOOL_NAMES[i],
3016+ g_tool_off[i] ? "false" : "true",
3017+ i + 1 < TOOLS_N ? "," : "");
3018+ }
3019+ buf_puts(&b, " }\n}\n");
3020+
3021+ f = fopen(tmp, "wb");
3022+ if (!f) { buf_free(&b); return -1; }
3023+ if (b.n && fwrite(b.p, 1, b.n, f) != b.n) {
3024+ fclose(f);
3025+#if defined(_WIN32)
3026+ DeleteFileA(tmp);
3027+#else
3028+ remove(tmp);
3029+#endif
3030+ buf_free(&b);
3031+ return -1;
3032+ }
3033+ fclose(f);
3034+#if defined(_WIN32)
3035+ MoveFileExA(g_roots_file, tmp, 0); /* keep a copy for rollback */
3036+ if (!MoveFileExA(tmp, g_roots_file, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
3037+ buf_free(&b);
3038+ return -1;
3039+ }
3040+#else
3041+ if (rename(tmp, g_roots_file) != 0) {
3042+ remove(tmp);
3043+ buf_free(&b);
3044+ return -1;
3045+ }
3046+#endif
3047+ buf_free(&b);
3048+ return 0;
3049+}
3050+
3051+static void ensure_roots_file_path(void)
3052+{
3053+ if (g_roots_file[0]) return;
3054+ init_roots();
3055+ if (g_roots_file[0]) return;
3056+ {
3057+ char dir[PATH_SZ];
3058+ connectors_dir(dir, sizeof dir);
3059+ snprintf(g_roots_file, sizeof g_roots_file, "%s", dir);
3060+ {
3061+ size_t dl = strlen(g_roots_file);
3062+ if (dl + 12 < sizeof g_roots_file) {
3063+ g_roots_file[dl] = SEP;
3064+ g_roots_file[dl + 1] = '\0';
3065+ str_copy(g_roots_file + dl + 1, sizeof g_roots_file - dl - 1, "roots.json");
3066+ }
3067+ }
3068+ }
3069+}
3070+
3071+static void json_header(void)
3072+{
3073+ fputs("Content-Type: application/json; charset=utf-8\r\n"
3074+ "Cache-Control: no-store\r\n"
3075+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
3076+}
3077+
3078+static void json_err(int code, const char *msg)
3079+{
3080+ if (code == 400) fputs("Status: 400 Bad Request\r\n", stdout);
3081+ else if (code == 403) fputs("Status: 403 Forbidden\r\n", stdout);
3082+ else if (code == 404) fputs("Status: 404 Not Found\r\n", stdout);
3083+ else if (code == 409) fputs("Status: 409 Conflict\r\n", stdout);
3084+ else fputs("Status: 500 Internal Server Error\r\n", stdout);
3085+ json_header();
3086+ printf("{\"ok\":false,\"error\":");
3087+ {
3088+ buf_t b;
3089+ buf_init(&b);
3090+ json_str(&b, msg ? msg : "error");
3091+ fputs(buf_str(&b), stdout);
3092+ buf_free(&b);
3093+ }
3094+ fputs("}\n", stdout);
3095+}
3096+
3097+/* ------------------------------------------------------------------ */
3098+/* CGI actions */
3099+/* ------------------------------------------------------------------ */
3100+
3101+static void do_status(void)
3102+{
3103+ int i;
3104+ json_header();
3105+ printf("{\"ok\":true,\"plugin\":\"%s\",\"version\":\"%s\",\"kind\":\"mcp\","
3106+ "\"mcp\":true,\"verified\":\"live\",\"protocol\":\"%s\",\"tools\":%d,"
3107+ "\"roots_file\":", PLUGIN_ID, PLUGIN_VER, MCP_PROTO, TOOLS_N);
3108+ {
3109+ buf_t b;
3110+ buf_init(&b);
3111+ ensure_roots_file_path();
3112+ json_str(&b, g_roots_file);
3113+ printf("%s", buf_str(&b));
3114+ buf_free(&b);
3115+ }
3116+ printf(",\"config_source\":%s",
3117+ getenv("FS_ALLOWED_ROOTS") ? "\"env:FS_ALLOWED_ROOTS\"" :
3118+ (g_root_count ? "\"roots.json-or-defaults\"" : "\"none\""));
3119+ printf(",\"writable\":%s",
3120+ (g_roots_file[0] && access(g_roots_file, 2) == 0) ||
3121+ (!g_roots_file[0]) ? "true" : "false");
3122+ printf(",\"roots\":[");
3123+ for (i = 0; i < g_root_count; i++) {
3124+ printf("%s{\"configured\":", i ? "," : "");
3125+ {
3126+ buf_t b;
3127+ buf_init(&b);
3128+ json_str(&b, g_roots[i].configured);
3129+ printf("%s", buf_str(&b));
3130+ buf_free(&b);
3131+ }
3132+ printf(",\"canonical\":");
3133+ {
3134+ buf_t b;
3135+ buf_init(&b);
3136+ json_str(&b, g_roots[i].canonical);
3137+ printf("%s", buf_str(&b));
3138+ buf_free(&b);
3139+ }
3140+ printf(",\"exists\":%s,\"is_dir\":%s,\"drift\":%s}",
3141+ g_roots[i].exists ? "true" : "false",
3142+ g_roots[i].is_dir ? "true" : "false",
3143+ strcmp(g_roots[i].configured, g_roots[i].canonical) ? "true" : "false");
3144+ }
3145+ printf("],\"denied\":[");
3146+ for (i = 0; i < deny_count; i++) {
3147+ buf_t b;
3148+ buf_init(&b);
3149+ json_str(&b, g_deny[i]);
3150+ printf("%s%s", i ? "," : "", buf_str(&b));
3151+ buf_free(&b);
3152+ }
3153+ printf("],\"permissions\":{");
3154+ for (i = 0; i < TOOLS_N; i++)
3155+ printf("%s\"%s\":%s", i ? "," : "", TOOL_NAMES[i],
3156+ g_tool_off[i] ? "false" : "true");
3157+ printf("}}\n");
3158+}
3159+
3160+static void do_roots(void)
3161+{
3162+ int i;
3163+ json_header();
3164+ printf("{\"ok\":true,\"count\":%d,\"roots\":[", g_root_count);
3165+ for (i = 0; i < g_root_count; i++) {
3166+ const char *base = strrchr(g_roots[i].canonical, '/');
3167+ char label[NAME_SZ];
3168+ buf_t b;
3169+ if (i) buf_putc(&b, ',');
3170+ buf_init(&b);
3171+ buf_puts(&b, "\n {\"path\":");
3172+ json_str(&b, g_roots[i].canonical);
3173+ buf_puts(&b, ",\"configured\":");
3174+ json_str(&b, g_roots[i].configured);
3175+ buf_puts(&b, ",\"name\":");
3176+ if (base && base[1]) str_copy(label, sizeof label, base + 1);
3177+ else str_copy(label, sizeof label, g_roots[i].canonical);
3178+ json_str(&b, label);
3179+ buf_printf(&b, ",\"exists\":%s,\"is_dir\":%s}",
3180+ g_roots[i].exists ? "true" : "false",
3181+ g_roots[i].is_dir ? "true" : "false");
3182+ fputs(buf_str(&b), stdout);
3183+ buf_free(&b);
3184+ }
3185+ printf("\n]}\n");
3186+}
3187+
3188+static void do_roots_add(const char *path)
3189+{
3190+ int before = g_root_count;
3191+ char canon[PATH_SZ];
3192+ if (!path || !*path) { json_err(400, "path is required"); return; }
3193+ if (!path_shape_ok(path)) {
3194+ json_err(400, "path must be absolute and must not contain '..'");
3195+ return;
3196+ }
3197+ if (!canon_path(path, canon, sizeof canon)) {
3198+ json_err(404, "that directory does not exist yet");
3199+ return;
3200+ }
3201+ if (denied_path(canon)) { json_err(403, "that path is on the deny list"); return; }
3202+ add_root_raw(path);
3203+ if (g_root_count == before) { json_err(409, "that directory is already allowed"); return; }
3204+ ensure_roots_file_path();
3205+ if (save_roots_file() != 0) { json_err(500, "could not write roots.json"); return; }
3206+ json_header();
3207+ printf("{\"ok\":true,\"added\":");
3208+ {
3209+ buf_t b;
3210+ buf_init(&b);
3211+ json_str(&b, canon);
3212+ printf("%s", buf_str(&b));
3213+ buf_free(&b);
3214+ }
3215+ printf(",\"count\":%d}\n", g_root_count);
3216+}
3217+
3218+static void do_roots_remove(const char *path)
3219+{
3220+ char canon[PATH_SZ];
3221+ int i, j, found = 0;
3222+
3223+ if (!path || !*path) { json_err(400, "path is required"); return; }
3224+ if (canon_path(path, canon, sizeof canon)) {
3225+ /* matched below */
3226+ } else {
3227+ str_copy(canon, sizeof canon, path);
3228+ }
3229+ for (i = 0; i < g_root_count; i++) {
3230+ if (!strcmp(g_roots[i].canonical, canon) ||
3231+ !strcmp(g_roots[i].configured, path) ||
3232+ path_under_p(canon, g_roots[i].canonical)) {
3233+ for (j = i; j + 1 < g_root_count; j++) g_roots[j] = g_roots[j + 1];
3234+ g_root_count--;
3235+ found = 1;
3236+ break;
3237+ }
3238+ }
3239+ if (!found) { json_err(404, "that directory is not in the allowlist"); return; }
3240+ ensure_roots_file_path();
3241+ if (save_roots_file() != 0) { json_err(500, "could not write roots.json"); return; }
3242+ json_header();
3243+ printf("{\"ok\":true,\"removed\":true,\"count\":%d}\n", g_root_count);
3244+}
3245+
3246+static void do_permissions(void)
3247+{
3248+ int i;
3249+ json_header();
3250+ printf("{\"ok\":true,\"permissions\":{");
3251+ for (i = 0; i < TOOLS_N; i++)
3252+ printf("%s\"%s\":%s", i ? "," : "", TOOL_NAMES[i],
3253+ g_tool_off[i] ? "false" : "true");
3254+ printf("}}\n");
3255+}
3256+
3257+static void do_permissions_set(const char *qs)
3258+{
3259+ char tool[64], val[16];
3260+ int idx;
3261+
3262+ if (!get_query_val(qs, "tool", tool, sizeof tool)) {
3263+ json_err(400, "tool is required");
3264+ return;
3265+ }
3266+ idx = tool_index(tool);
3267+ if (idx < 0) { json_err(404, "unknown tool"); return; }
3268+ if (!get_query_val(qs, "enabled", val, sizeof val)) {
3269+ json_err(400, "enabled is required (true/false)");
3270+ return;
3271+ }
3272+ g_tool_off[idx] = (strcmp(val, "true") == 0 || strcmp(val, "1") == 0) ? 0 : 1;
3273+ /* list_allowed_directories is the diagnostic an operator needs when a
3274+ * path is refused, so it can never be switched off. */
3275+ if (idx == TOOLS_N - 1) g_tool_off[idx] = 0;
3276+ ensure_roots_file_path();
3277+ if (save_roots_file() != 0) { json_err(500, "could not write roots.json"); return; }
3278+ json_header();
3279+ printf("{\"ok\":true,\"tool\":");
3280+ {
3281+ buf_t b;
3282+ buf_init(&b);
3283+ json_str(&b, TOOL_NAMES[idx]);
3284+ printf("%s", buf_str(&b));
3285+ buf_free(&b);
3286+ }
3287+ printf(",\"enabled\":%s}\n", g_tool_off[idx] ? "false" : "true");
3288+}
3289+
3290+/* The sandbox boundary tester: what an operator types in, the tool sees.
3291+ * Reports both forms and the exact reason a path is refused. */
3292+static void do_sandbox_test(const char *path)
3293+{
3294+ char canon[PATH_SZ];
3295+ const char *err = NULL;
3296+ int allowed = 0;
3297+
3298+ if (!path || !*path) { json_err(400, "path is required"); return; }
3299+ allowed = resolve_allowed(path, canon, sizeof canon, 'r', &err);
3300+ if (!allowed) {
3301+ /* a write-mode answer is more useful for a path that does not exist */
3302+ char wc[PATH_SZ];
3303+ const char *werr = NULL;
3304+ if (resolve_allowed(path, wc, sizeof wc, 'w', &werr)) {
3305+ buf_t b;
3306+ json_header();
3307+ printf("{\"ok\":true,\"path\":");
3308+ buf_init(&b);
3309+ json_str(&b, path);
3310+ printf("%s,\"allowed\":true,\"mode\":\"write\",\"canonical\":", buf_str(&b));
3311+ buf_free(&b);
3312+ buf_init(&b);
3313+ json_str(&b, wc);
3314+ printf("%s}\n", buf_str(&b));
3315+ buf_free(&b);
3316+ return;
3317+ }
3318+ }
3319+ {
3320+ buf_t b;
3321+ json_header();
3322+ buf_init(&b);
3323+ json_str(&b, path);
3324+ printf("{\"ok\":true,\"path\":%s,\"allowed\":%s,\"canonical\":",
3325+ buf_str(&b), allowed ? "true" : "false");
3326+ buf_free(&b);
3327+ if (allowed) {
3328+ buf_init(&b);
3329+ json_str(&b, canon);
3330+ printf("%s,\"reason\":\"inside an allowed root\"}\n", buf_str(&b));
3331+ buf_free(&b);
3332+ } else {
3333+ buf_init(&b);
3334+ json_str(&b, canon);
3335+ printf("%s,\"reason\":", buf_str(&b));
3336+ buf_free(&b);
3337+ buf_init(&b);
3338+ json_str(&b, err ? err : "refused");
3339+ printf("%s}\n", buf_str(&b));
3340+ buf_free(&b);
3341+ }
3342+ }
3343+}
3344+
3345+static void do_tools(void)
3346+{
3347+ int i;
3348+ json_header();
3349+ printf("{\"ok\":true,\"tools\":[");
3350+ for (i = 0; i < TOOLS_N; i++) {
3351+ buf_t b;
3352+ buf_init(&b);
3353+ if (i) buf_putc(&b, ',');
3354+ buf_puts(&b, "{\"name\":");
3355+ json_str(&b, TOOLS[i].name);
3356+ buf_puts(&b, ",\"title\":");
3357+ json_str(&b, TOOLS[i].title);
3358+ buf_puts(&b, ",\"description\":");
3359+ json_str(&b, TOOLS[i].desc);
3360+ buf_printf(&b, ",\"read_only\":%s,\"destructive\":%s,\"enabled\":%s}",
3361+ TOOLS[i].read_only ? "true" : "false",
3362+ TOOLS[i].destructive ? "true" : "false",
3363+ g_tool_off[i] ? "false" : "true");
3364+ fputs(buf_str(&b), stdout);
3365+ buf_free(&b);
3366+ }
3367+ printf("]}\n");
3368+}
3369+
3370+/* ------------------------------------------------------------------ */
3371+/* HTML UI */
3372+/* ------------------------------------------------------------------ */
3373+
3374+/* Expand the two control-byte placeholders from src/ui.html into the bot
3375+ * theme macros, so the page and the bot palette can never drift. */
3376+static void emit_ui(int embed)
3377+{
3378+ const char *p = UI_HTML;
3379+
3380+ while (*p) {
3381+ if (*p == '\001') {
3382+ fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS
3383+ ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);--ac:var(--blue)}"
3384+ "</style>", stdout);
3385+ p++;
3386+ } else if (*p == '\002') {
3387+ fputs(SX_BOT_THEME_HANDOFF, stdout);
3388+ p++;
3389+ } else {
3390+ putchar(*p++);
3391+ }
3392+ }
3393+ (void)embed;
3394+}
3395+
3396+static void mode_html(int embed)
3397+{
3398+ fputs("Content-Type: text/html; charset=utf-8\r\n"
3399+ "Cache-Control: no-store\r\n"
3400+ "X-Content-Type-Options: nosniff\r\n"
3401+ "X-Frame-Options: SAMEORIGIN\r\n"
3402+ "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
3403+ "style-src 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; "
3404+ "form-action 'none'; base-uri 'none'\r\n\r\n", stdout);
3405+ emit_ui(embed);
3406+}
3407+
3408+/* ------------------------------------------------------------------ */
3409+/* main */
3410+/* ------------------------------------------------------------------ */
3411+
3412+static void print_help(void)
3413+{
3414+ printf("%s %s - SCORPIOX BOT allowlisted filesystem MCP connector\n\n"
3415+ "modes:\n"
3416+ " --meta print plugin discovery metadata and exit\n"
3417+ " --mcp serve MCP JSON-RPC 2.0 over stdin/stdout\n"
3418+ " (no args) CGI: Allowed Roots & Permissions page + ?action= API\n"
3419+ " --version print version\n\n"
3420+ "config: %s/roots.json (or FS_ALLOWED_ROOTS, colon-separated)\n"
3421+ "tools: ", PLUGIN_ID, PLUGIN_VER, " ~/.scorpiox/connectors/" PLUGIN_ID);
3422+ {
3423+ int i;
3424+ for (i = 0; i < TOOLS_N; i++)
3425+ printf("%s%s", i ? ", " : "", TOOLS[i].name);
3426+ }
3427+ printf("\n");
3428+}
3429+
3430+int main(int argc, char **argv)
3431+{
3432+ const char *qs;
3433+ char action[64];
3434+ char path[PATH_SZ];
3435+ int i;
3436+
3437+ /* 1. Discovery metadata - unauthenticated: /plugins and the connector
3438+ * router probe every installed binary, and a probe that needs the
3439+ * node password is a probe that fails. */
3440+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
3441+ fputs("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\","
3442+ "\"kind\":\"mcp\",\"mcp\":true,\"daemon\":false,\"menus\":false,"
3443+ "\"verified\":\"live\",\"version\":\"" PLUGIN_VER "\"}\n", stdout);
3444+ return 0;
3445+ }
3446+ for (i = 1; i < argc; i++) {
3447+ if (!strcmp(argv[i], "--version")) {
3448+ printf("%s %s\n", PLUGIN_ID, PLUGIN_VER);
3449+ return 0;
3450+ }
3451+ if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) {
3452+ print_help();
3453+ return 0;
3454+ }
3455+ }
3456+
3457+ /* 2. MCP stdio server - the connector mode. No CGI headers, no auth:
3458+ * the caller is the node's own MCP router, already trusted. */
3459+ if (argc > 1 && !strcmp(argv[1], "--mcp")) {
3460+ init_roots();
3461+ return mode_mcp();
3462+ }
3463+
3464+ /* 3. CGI modes below are all behind node auth. */
3465+ require_node_auth();
3466+ init_roots();
3467+
3468+ qs = getenv("QUERY_STRING");
3469+ if (!qs) qs = "";
3470+
3471+ action[0] = '\0';
3472+ path[0] = '\0';
3473+ get_query_val(qs, "action", action, sizeof action);
3474+ get_query_val(qs, "path", path, sizeof path);
3475+
3476+ if (action[0] || strstr(qs, "format=json")) {
3477+ if (!action[0]) str_copy(action, sizeof action, "status");
3478+
3479+ if (!strcmp(action, "status")) do_status();
3480+ else if (!strcmp(action, "roots")) do_roots();
3481+ else if (!strcmp(action, "roots_add")) do_roots_add(path);
3482+ else if (!strcmp(action, "roots_remove")) do_roots_remove(path);
3483+ else if (!strcmp(action, "permissions")) do_permissions();
3484+ else if (!strcmp(action, "permissions_set")) do_permissions_set(qs);
3485+ else if (!strcmp(action, "sandbox_test")) do_sandbox_test(path);
3486+ else if (!strcmp(action, "tools")) do_tools();
3487+ else json_err(400, "unknown action");
3488+ return 0;
3489+ }
3490+
3491+ /* 4. Everything else is the page. */
3492+ {
3493+ int embed = strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL;
3494+ mode_html(embed);
3495+ }
3496+ return 0;
3497+}
src/ui.html+290−0■■■■■
11new file mode 100644
index 0000000..c3413b7
--- /dev/null
+++ b/src/ui.html
@@ -0,0 +1,290 @@
1+<!DOCTYPE html>
2+<html lang="en"><head><meta charset="utf-8">
3+<meta name="viewport" content="width=device-width,initial-scale=1">
4+<title>filesystem</title>
5+<!--TOKENS-->
6+<style>
7+*{box-sizing:border-box}
8+html,body{margin:0}
9+body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;
10+ line-height:1.5;-webkit-font-smoothing:antialiased}
11+.wrap{max-width:1080px;margin:0 auto;padding:16px}
12+.card{background:var(--surface);border:1px solid var(--line);border-radius:14px;
13+ padding:16px;margin-bottom:14px}
14+h1{font-size:17px;margin:0 0 2px;letter-spacing:-.01em}
15+h2{font-size:12px;font-weight:700;letter-spacing:.09em;text-transform:uppercase;
16+ color:var(--text-2);margin:0 0 12px}
17+.sub{color:var(--text-2);font-size:12.5px;margin:0 0 14px}
18+.grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:14px}
19+@media(max-width:860px){.grid{grid-template-columns:minmax(0,1fr)}}
20+.row{display:flex;gap:8px;align-items:center}
21+.row.wraprow{flex-wrap:wrap}
22+input[type=text]{flex:1;min-width:0;background:var(--input-bg);color:var(--text);
23+ border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-family:var(--mono);
24+ font-size:12.5px;outline:none}
25+input[type=text]:focus{border-color:var(--blue)}
26+button{background:var(--surface-2);color:var(--text);border:1px solid var(--line);
27+ border-radius:9px;padding:7px 12px;font-family:inherit;font-size:12.5px;font-weight:600;
28+ cursor:pointer;flex:0 0 auto}
29+button:hover{background:var(--surface-hover);border-color:var(--line-2)}
30+button:active{transform:scale(.98)}
31+button.primary{background:var(--blue);border-color:transparent;color:#fff}
32+button.danger{color:var(--red)}
33+ul.roots{list-style:none;margin:0;padding:0}
34+ul.roots li{display:flex;align-items:center;gap:10px;padding:9px 10px;
35+ border:1px solid var(--line);border-radius:10px;margin-bottom:7px;background:var(--bg-2)}
36+ul.roots li .p{flex:1;min-width:0;font-family:var(--mono);font-size:12.5px;
37+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
38+ul.roots li .note{font-size:11px;color:var(--text-2);flex:0 0 auto}
39+ul.roots li .note.warn{color:var(--orange)}
40+ul.roots li .note.bad{color:var(--red)}
41+.pill{font-size:10.5px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;
42+ padding:2px 7px;border-radius:980px;border:1px solid var(--line);color:var(--text-2);flex:0 0 auto}
43+.pill.rw{color:var(--green);border-color:rgba(48,209,88,.35)}
44+.pill.ro{color:var(--teal);border-color:rgba(100,210,255,.35)}
45+table.tools{width:100%;border-collapse:collapse;font-size:12.5px}
46+table.tools th{text-align:left;font-size:10.5px;letter-spacing:.08em;text-transform:uppercase;
47+ color:var(--text-2);font-weight:700;padding:0 8px 6px 0;border-bottom:1px solid var(--line)}
48+table.tools td{padding:7px 8px 7px 0;border-bottom:1px solid var(--line);vertical-align:top}
49+table.tools tr:last-child td{border-bottom:0}
50+table.tools td.n{font-family:var(--mono);font-size:12px;white-space:nowrap}
51+table.tools td.d{color:var(--text-2);font-size:11.5px}
52+.sw{position:relative;width:38px;height:22px;flex:0 0 auto;border-radius:980px;
53+ background:var(--surface-2);border:1px solid var(--line);cursor:pointer;padding:0}
54+.sw[aria-checked=true]{background:var(--green);border-color:transparent}
55+.sw i{position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;
56+ background:#fff;transition:transform .16s var(--ease)}
57+.sw[aria-checked=true] i{transform:translateX(16px)}
58+pre{margin:0;background:var(--code-bg);border:1px solid var(--line);border-radius:10px;
59+ padding:10px 12px;font-family:var(--mono);font-size:11.5px;white-space:pre-wrap;
60+ word-break:break-all;max-height:220px;overflow:auto}
61+.kv{display:flex;flex-wrap:wrap;gap:6px 16px;font-size:12px;color:var(--text-2);margin:0 0 12px}
62+.kv b{color:var(--text);font-weight:600;font-family:var(--mono)}
63+.msg{font-size:12.5px;padding:8px 10px;border-radius:9px;margin:0 0 10px;display:none}
64+.msg.show{display:block}
65+.msg.ok{background:rgba(48,209,88,.12);color:var(--green);border:1px solid rgba(48,209,88,.3)}
66+.msg.err{background:rgba(255,69,58,.12);color:var(--red);border:1px solid rgba(255,69,58,.3)}
67+.msg.warn{background:rgba(255,159,10,.12);color:var(--orange);border:1px solid rgba(255,159,10,.3)}
68+a{color:var(--blue);text-decoration:none}
69+.hint{font-size:11.5px;color:var(--text-2);margin:8px 0 0}
70+.nomargin{margin-bottom:0}
71+</style>
72+</head><body>
73+<div class="wrap">
74+
75+<div class="card">
76+ <h1>filesystem</h1>
77+ <p class="sub">Allowlisted filesystem tools for your node, over MCP. Every path is
78+ canonicalised on disk and must land inside a directory you list here. Nothing
79+ outside them is readable or writable, and symlinks that point out are refused.</p>
80+ <div class="kv" id="kv">
81+ <span>plugin <b>plugin_filesystem</b></span>
82+ <span>version <b id="kver">–</b></span>
83+ <span>kind <b>mcp</b></span>
84+ <span>config <b id="kfile">–</b></span>
85+ </div>
86+ <div class="msg" id="msg"></div>
87+ <div class="hint">Server-rendered summary below; the controls need JavaScript and the
88+ node password the bot already holds.</div>
89+ <pre id="noscript">Allowed roots and permissions are read from
90+~/.scorpiox/connectors/plugin_filesystem/roots.json
91+(override with the FS_ALLOWED_ROOTS environment variable).</pre>
92+</div>
93+
94+<div class="grid">
95+
96+ <div class="card">
97+ <h2>Allowed directories</h2>
98+ <ul class="roots" id="roots"><li><span class="p">loading…</span></li></ul>
99+ <div class="row" style="margin-top:10px">
100+ <input type="text" id="newroot" placeholder="/absolute/path/to/a/directory"
101+ autocomplete="off" spellcheck="false">
102+ <button class="primary" id="btnadd">Allow</button>
103+ </div>
104+ <p class="hint">Absolute paths only, no <code>..</code>. A directory that does not
105+ exist yet is refused here so a typo cannot quietly widen the sandbox. Paths shown
106+ in orange resolve elsewhere (a symlink or a mount) — the canonical form is what the
107+ tools check.</p>
108+ </div>
109+
110+ <div class="card">
111+ <h2>Tool permissions</h2>
112+ <table class="tools"><thead><tr><th>Tool</th><th></th></tr></thead>
113+ <tbody id="tools"><tr><td class="d" colspan="2">loading…</td></tr></tbody></table>
114+ <p class="hint">Disabled tools answer with a refusal instead of running, so an agent
115+ gets an explanation rather than a missing tool. <b>list_allowed_directories</b>
116+ cannot be switched off — it is how you diagnose a refusal.</p>
117+ </div>
118+
119+</div>
120+
121+<div class="card">
122+ <h2>Sandbox boundary test</h2>
123+ <div class="row wraprow">
124+ <input type="text" id="testpath" placeholder="/absolute/path/you/want/to/check"
125+ autocomplete="off" spellcheck="false">
126+ <button id="btntest">Test path</button>
127+ </div>
128+ <div id="testout" style="margin-top:10px"></div>
129+ <p class="hint">Reports exactly what a tool would see: allowed or not, the canonical
130+ path, and the rule that refused it. Use it before blaming a tool for a path that
131+ was never in scope.</p>
132+</div>
133+
134+<div class="card">
135+ <h2>Register with the connector router</h2>
136+ <pre id="snippet">{}</pre>
137+ <p class="hint">The node's single <b>sx-connector-mcp</b> router reads this file and
138+ exposes every installed MCP connector through four meta-tools, so the agent's tool
139+ budget stays flat no matter how many connectors you install.</p>
140+</div>
141+
142+</div>
143+<script>
144+var q=new URLSearchParams(location.search);
145+var node=q.get('node')||'';
146+var sid=q.get('id')||'';
147+var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||
148+ localStorage.getItem('bot_active_pwd')||'';
149+var HUB=q.get('plugin')||'';
150+
151+/* Two call routes; this is the most common plugin bug.
152+ * served through the hub (/plugins?plugin=plugin_filesystem&node=..)
153+ * -> call the hub proxy back: /plugins?plugin=..&action=..
154+ * opened directly on the node
155+ * -> the plugin IS the route: /plugin_filesystem?action=..
156+ * Calling /plugins?plugin= on the node returns the discovery list, not us. */
157+function url(action,extra){
158+ return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_filesystem')+
159+ '?action='+encodeURIComponent(action)+
160+ (extra?('&'+extra):'')+
161+ (node?'&node='+encodeURIComponent(node):'')+
162+ (sid?'&id='+encodeURIComponent(sid):'')+
163+ (pwd?'&pwd='+encodeURIComponent(pwd):'');
164+}
165+function api(action,extra){
166+ var h=pwd?{'X-Bot-Password':pwd}:{};
167+ return fetch(url(action,extra),{headers:h}).then(function(r){
168+ return r.json().then(function(j){return {status:r.status,body:j};});
169+ });
170+}
171+var msgEl=document.getElementById('msg');
172+function say(text,kind){
173+ msgEl.textContent=text;
174+ msgEl.className='msg show '+(kind||'ok');
175+ clearTimeout(say._t);
176+ say._t=setTimeout(function(){msgEl.className='msg';},4200);
177+}
178+function esc(s){
179+ return String(s==null?'':s).replace(/[&<>"]/g,function(c){
180+ return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c];
181+ });
182+}
183+
184+function renderStatus(st){
185+ document.getElementById('kver').textContent=st.version||'';
186+ document.getElementById('kfile').textContent=st.roots_file||'';
187+ document.getElementById('noscript').textContent=
188+ 'config: '+(st.roots_file||'(not yet written)')+'\n'+
189+ 'source: '+(st.config_source||'')+'\n'+
190+ 'roots: '+((st.roots||[]).length
191+ ? (st.roots||[]).map(function(r){return r.canonical;}).join('\n ')
192+ : '(none - nothing is reachable)');
193+ document.getElementById('snippet').textContent=JSON.stringify(
194+ {mcpServers:{filesystem:{
195+ command:'~/.scorpiox/plugins/plugin_filesystem',
196+ args:['--mcp'],
197+ slug:'filesystem'}}},null,2);
198+}
199+function renderRoots(roots){
200+ var ul=document.getElementById('roots');
201+ ul.innerHTML='';
202+ if(!roots||!roots.length){
203+ ul.innerHTML='<li><span class="p">No allowed directories — the plugin can read and '+
204+ 'write nothing. Add one below.</span></li>';
205+ return;
206+ }
207+ roots.forEach(function(r){
208+ var li=document.createElement('li');
209+ var note='',cls='';
210+ if(!r.exists){note='missing';cls='bad';}
211+ else if(!r.is_dir){note='not a directory';cls='bad';}
212+ else if(r.drift){note='→ '+r.canonical;cls='warn';}
213+ li.innerHTML='<span class="p" title="'+esc(r.canonical)+'">'+esc(r.configured||r.canonical)+
214+ '</span>'+(note?'<span class="note '+cls+'">'+esc(note)+'</span>':'')+
215+ '<button class="danger" data-rm="'+esc(r.canonical)+'">Remove</button>';
216+ ul.appendChild(li);
217+ });
218+ Array.prototype.forEach.call(ul.querySelectorAll('[data-rm]'),function(b){
219+ b.addEventListener('click',function(){
220+ api('roots_remove','path='+encodeURIComponent(b.getAttribute('data-rm'))).then(function(x){
221+ if(x.body&&x.body.ok){say('Removed '+b.getAttribute('data-rm'));refresh();}
222+ else say((x.body&&x.body.error)||('HTTP '+x.status),'err');
223+ });
224+ });
225+ });
226+}
227+function renderTools(tools){
228+ var tb=document.getElementById('tools');
229+ tb.innerHTML='';
230+ tools.forEach(function(t){
231+ var tr=document.createElement('tr');
232+ tr.innerHTML='<td class="n">'+esc(t.name)+'</td>'+
233+ '<td class="d">'+esc(t.read_only?'read-only':(t.destructive?'writes':'creates'))+'</td>'+
234+ '<td class="d">'+esc(t.description.slice(0,64))+'…</td>'+
235+ '<td style="text-align:right"><button class="sw" role="switch" data-t="'+esc(t.name)+
236+ '" aria-checked="'+(t.enabled?'true':'false')+'"><i></i></button></td>';
237+ tb.appendChild(tr);
238+ });
239+ Array.prototype.forEach.call(tb.querySelectorAll('.sw'),function(b){
240+ b.addEventListener('click',function(){
241+ var on=b.getAttribute('aria-checked')!=='true';
242+ api('permissions_set','tool='+encodeURIComponent(b.getAttribute('data-t'))+
243+ '&enabled='+(on?'true':'false')).then(function(x){
244+ if(x.body&&x.body.ok){b.setAttribute('aria-checked',on?'true':'false');
245+ say((on?'Enabled ':'Disabled ')+b.getAttribute('data-t'));}
246+ else say((x.body&&x.body.error)||('HTTP '+x.status),'err');
247+ });
248+ });
249+ });
250+}
251+function renderTest(x){
252+ var el=document.getElementById('testout');
253+ if(!x||!x.body||!x.body.ok){el.innerHTML='';return;}
254+ var b=x.body;
255+ el.innerHTML='<div class="msg show '+(b.allowed?'ok':'warn')+'">'+
256+ (b.allowed?'ALLOWED':'REFUSED')+' — '+esc(b.path)+
257+ (b.canonical?(' → <span style="font-family:var(--mono)">'+esc(b.canonical)+'</span>'):'')+
258+ ' — '+esc(b.reason||'')+'</div>';
259+}
260+function refresh(){
261+ api('status').then(function(x){
262+ if(!x.body||!x.body.ok){say((x.body&&x.body.error)||('HTTP '+x.status),'err');return;}
263+ renderStatus(x.body);
264+ });
265+ api('roots').then(function(x){if(x.body&&x.body.ok)renderRoots(x.body.roots);});
266+ api('tools').then(function(x){if(x.body&&x.body.ok)renderTools(x.body.tools);});
267+}
268+document.getElementById('btnadd').addEventListener('click',function(){
269+ var v=document.getElementById('newroot').value.trim();
270+ if(!v){say('Type a directory path first','warn');return;}
271+ api('roots_add','path='+encodeURIComponent(v)).then(function(x){
272+ if(x.body&&x.body.ok){say('Allowed '+x.body.added);
273+ document.getElementById('newroot').value='';refresh();}
274+ else say((x.body&&x.body.error)||('HTTP '+x.status),'err');
275+ });
276+});
277+document.getElementById('newroot').addEventListener('keydown',function(e){
278+ if(e.key==='Enter')document.getElementById('btnadd').click();
279+});
280+document.getElementById('btntest').addEventListener('click',function(){
281+ var v=document.getElementById('testpath').value.trim();
282+ if(!v){say('Type a path to test','warn');return;}
283+ api('sandbox_test','path='+encodeURIComponent(v)).then(function(x){renderTest(x);});
284+});
285+document.getElementById('testpath').addEventListener('keydown',function(e){
286+ if(e.key==='Enter')document.getElementById('btntest').click();
287+});
288+refresh();
289+</script>
290+</body></html>
src/ui_html.h+298−0■■■■■
11new file mode 100644
index 0000000..6f72bee
--- /dev/null
+++ b/src/ui_html.h
@@ -0,0 +1,298 @@
1+/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */
2+#ifndef SX_FILESYSTEM_UI_HTML_H
3+#define SX_FILESYSTEM_UI_HTML_H
4+
5+static const char *UI_HTML =
6+ "<!DOCTYPE html>\n"
7+ "<html lang=\"en\"><head><meta charset=\"utf-8\">\n"
8+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n"
9+ "<title>filesystem</title>\n"
10+ "\001\n"
11+ "<style>\n"
12+ "*{box-sizing:border-box}\n"
13+ "html,body{margin:0}\n"
14+ "body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;\n"
15+ " line-height:1.5;-webkit-font-smoothing:antialiased}\n"
16+ ".wrap{max-width:1080px;margin:0 auto;padding:16px}\n"
17+ ".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;\n"
18+ " padding:16px;margin-bottom:14px}\n"
19+ "h1{font-size:17px;margin:0 0 2px;letter-spacing:-.01em}\n"
20+ "h2{font-size:12px;font-weight:700;letter-spacing:.09em;text-transform:uppercase;\n"
21+ " color:var(--text-2);margin:0 0 12px}\n"
22+ ".sub{color:var(--text-2);font-size:12.5px;margin:0 0 14px}\n"
23+ ".grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:14px}\n"
24+ "@media(max-width:860px){.grid{grid-template-columns:minmax(0,1fr)}}\n"
25+ ".row{display:flex;gap:8px;align-items:center}\n"
26+ ".row.wraprow{flex-wrap:wrap}\n"
27+ "input[type=text]{flex:1;min-width:0;background:var(--input-bg);color:var(--text);\n"
28+ " border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-family:var(--mono);\n"
29+ " font-size:12.5px;outline:none}\n"
30+ "input[type=text]:focus{border-color:var(--blue)}\n"
31+ "button{background:var(--surface-2);color:var(--text);border:1px solid var(--line);\n"
32+ " border-radius:9px;padding:7px 12px;font-family:inherit;font-size:12.5px;font-weight:600;\n"
33+ " cursor:pointer;flex:0 0 auto}\n"
34+ "button:hover{background:var(--surface-hover);border-color:var(--line-2)}\n"
35+ "button:active{transform:scale(.98)}\n"
36+ "button.primary{background:var(--blue);border-color:transparent;color:#fff}\n"
37+ "button.danger{color:var(--red)}\n"
38+ "ul.roots{list-style:none;margin:0;padding:0}\n"
39+ "ul.roots li{display:flex;align-items:center;gap:10px;padding:9px 10px;\n"
40+ " border:1px solid var(--line);border-radius:10px;margin-bottom:7px;background:var(--bg-2)}\n"
41+ "ul.roots li .p{flex:1;min-width:0;font-family:var(--mono);font-size:12.5px;\n"
42+ " overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n"
43+ "ul.roots li .note{font-size:11px;color:var(--text-2);flex:0 0 auto}\n"
44+ "ul.roots li .note.warn{color:var(--orange)}\n"
45+ "ul.roots li .note.bad{color:var(--red)}\n"
46+ ".pill{font-size:10.5px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;\n"
47+ " padding:2px 7px;border-radius:980px;border:1px solid var(--line);color:var(--text-2);flex:0 0 auto}\n"
48+ ".pill.rw{color:var(--green);border-color:rgba(48,209,88,.35)}\n"
49+ ".pill.ro{color:var(--teal);border-color:rgba(100,210,255,.35)}\n"
50+ "table.tools{width:100%;border-collapse:collapse;font-size:12.5px}\n"
51+ "table.tools th{text-align:left;font-size:10.5px;letter-spacing:.08em;text-transform:uppercase;\n"
52+ " color:var(--text-2);font-weight:700;padding:0 8px 6px 0;border-bottom:1px solid var(--line)}\n"
53+ "table.tools td{padding:7px 8px 7px 0;border-bottom:1px solid var(--line);vertical-align:top}\n"
54+ "table.tools tr:last-child td{border-bottom:0}\n"
55+ "table.tools td.n{font-family:var(--mono);font-size:12px;white-space:nowrap}\n"
56+ "table.tools td.d{color:var(--text-2);font-size:11.5px}\n"
57+ ".sw{position:relative;width:38px;height:22px;flex:0 0 auto;border-radius:980px;\n"
58+ " background:var(--surface-2);border:1px solid var(--line);cursor:pointer;padding:0}\n"
59+ ".sw[aria-checked=true]{background:var(--green);border-color:transparent}\n"
60+ ".sw i{position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;\n"
61+ " background:#fff;transition:transform .16s var(--ease)}\n"
62+ ".sw[aria-checked=true] i{transform:translateX(16px)}\n"
63+ "pre{margin:0;background:var(--code-bg);border:1px solid var(--line);border-radius:10px;\n"
64+ " padding:10px 12px;font-family:var(--mono);font-size:11.5px;white-space:pre-wrap;\n"
65+ " word-break:break-all;max-height:220px;overflow:auto}\n"
66+ ".kv{display:flex;flex-wrap:wrap;gap:6px 16px;font-size:12px;color:var(--text-2);margin:0 0 12px}\n"
67+ ".kv b{color:var(--text);font-weight:600;font-family:var(--mono)}\n"
68+ ".msg{font-size:12.5px;padding:8px 10px;border-radius:9px;margin:0 0 10px;display:none}\n"
69+ ".msg.show{display:block}\n"
70+ ".msg.ok{background:rgba(48,209,88,.12);color:var(--green);border:1px solid rgba(48,209,88,.3)}\n"
71+ ".msg.err{background:rgba(255,69,58,.12);color:var(--red);border:1px solid rgba(255,69,58,.3)}\n"
72+ ".msg.warn{background:rgba(255,159,10,.12);color:var(--orange);border:1px solid rgba(255,159,10,.3)}\n"
73+ "a{color:var(--blue);text-decoration:none}\n"
74+ ".hint{font-size:11.5px;color:var(--text-2);margin:8px 0 0}\n"
75+ ".nomargin{margin-bottom:0}\n"
76+ "</style>\n"
77+ "</head><body>\n"
78+ "<div class=\"wrap\">\n"
79+ "\n"
80+ "<div class=\"card\">\n"
81+ " <h1>filesystem</h1>\n"
82+ " <p class=\"sub\">Allowlisted filesystem tools for your node, over MCP. Every path is\n"
83+ " canonicalised on disk and must land inside a directory you list here. Nothing\n"
84+ " outside them is readable or writable, and symlinks that point out are refused.</p>\n"
85+ " <div class=\"kv\" id=\"kv\">\n"
86+ " <span>plugin <b>plugin_filesystem</b></span>\n"
87+ " <span>version <b id=\"kver\">–</b></span>\n"
88+ " <span>kind <b>mcp</b></span>\n"
89+ " <span>config <b id=\"kfile\">–</b></span>\n"
90+ " </div>\n"
91+ " <div class=\"msg\" id=\"msg\"></div>\n"
92+ " <div class=\"hint\">Server-rendered summary below; the controls need JavaScript and the\n"
93+ " node password the bot already holds.</div>\n"
94+ " <pre id=\"noscript\">Allowed roots and permissions are read from\n"
95+ "~/.scorpiox/connectors/plugin_filesystem/roots.json\n"
96+ "(override with the FS_ALLOWED_ROOTS environment variable).</pre>\n"
97+ "</div>\n"
98+ "\n"
99+ "<div class=\"grid\">\n"
100+ "\n"
101+ " <div class=\"card\">\n"
102+ " <h2>Allowed directories</h2>\n"
103+ " <ul class=\"roots\" id=\"roots\"><li><span class=\"p\">loading…</span></li></ul>\n"
104+ " <div class=\"row\" style=\"margin-top:10px\">\n"
105+ " <input type=\"text\" id=\"newroot\" placeholder=\"/absolute/path/to/a/directory\"\n"
106+ " autocomplete=\"off\" spellcheck=\"false\">\n"
107+ " <button class=\"primary\" id=\"btnadd\">Allow</button>\n"
108+ " </div>\n"
109+ " <p class=\"hint\">Absolute paths only, no <code>..</code>. A directory that does not\n"
110+ " exist yet is refused here so a typo cannot quietly widen the sandbox. Paths shown\n"
111+ " in orange resolve elsewhere (a symlink or a mount) — the canonical form is what the\n"
112+ " tools check.</p>\n"
113+ " </div>\n"
114+ "\n"
115+ " <div class=\"card\">\n"
116+ " <h2>Tool permissions</h2>\n"
117+ " <table class=\"tools\"><thead><tr><th>Tool</th><th></th></tr></thead>\n"
118+ " <tbody id=\"tools\"><tr><td class=\"d\" colspan=\"2\">loading…</td></tr></tbody></table>\n"
119+ " <p class=\"hint\">Disabled tools answer with a refusal instead of running, so an agent\n"
120+ " gets an explanation rather than a missing tool. <b>list_allowed_directories</b>\n"
121+ " cannot be switched off — it is how you diagnose a refusal.</p>\n"
122+ " </div>\n"
123+ "\n"
124+ "</div>\n"
125+ "\n"
126+ "<div class=\"card\">\n"
127+ " <h2>Sandbox boundary test</h2>\n"
128+ " <div class=\"row wraprow\">\n"
129+ " <input type=\"text\" id=\"testpath\" placeholder=\"/absolute/path/you/want/to/check\"\n"
130+ " autocomplete=\"off\" spellcheck=\"false\">\n"
131+ " <button id=\"btntest\">Test path</button>\n"
132+ " </div>\n"
133+ " <div id=\"testout\" style=\"margin-top:10px\"></div>\n"
134+ " <p class=\"hint\">Reports exactly what a tool would see: allowed or not, the canonical\n"
135+ " path, and the rule that refused it. Use it before blaming a tool for a path that\n"
136+ " was never in scope.</p>\n"
137+ "</div>\n"
138+ "\n"
139+ "<div class=\"card\">\n"
140+ " <h2>Register with the connector router</h2>\n"
141+ " <pre id=\"snippet\">{}</pre>\n"
142+ " <p class=\"hint\">The node's single <b>sx-connector-mcp</b> router reads this file and\n"
143+ " exposes every installed MCP connector through four meta-tools, so the agent's tool\n"
144+ " budget stays flat no matter how many connectors you install.</p>\n"
145+ "</div>\n"
146+ "\n"
147+ "</div>\n"
148+ "<script>\n"
149+ "var q=new URLSearchParams(location.search);\n"
150+ "var node=q.get('node')||'';\n"
151+ "var sid=q.get('id')||'';\n"
152+ "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n"
153+ " localStorage.getItem('bot_active_pwd')||'';\n"
154+ "var HUB=q.get('plugin')||'';\n"
155+ "\n"
156+ "/* Two call routes; this is the most common plugin bug.\n"
157+ " * served through the hub (/plugins?plugin=plugin_filesystem&node=..)\n"
158+ " * -> call the hub proxy back: /plugins?plugin=..&action=..\n"
159+ " * opened directly on the node\n"
160+ " * -> the plugin IS the route: /plugin_filesystem?action=..\n"
161+ " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n"
162+ "function url(action,extra){\n"
163+ " return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_filesystem')+\n"
164+ " '?action='+encodeURIComponent(action)+\n"
165+ " (extra?('&'+extra):'')+\n"
166+ " (node?'&node='+encodeURIComponent(node):'')+\n"
167+ " (sid?'&id='+encodeURIComponent(sid):'')+\n"
168+ " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n"
169+ "}\n"
170+ "function api(action,extra){\n"
171+ " var h=pwd?{'X-Bot-Password':pwd}:{};\n"
172+ " return fetch(url(action,extra),{headers:h}).then(function(r){\n"
173+ " return r.json().then(function(j){return {status:r.status,body:j};});\n"
174+ " });\n"
175+ "}\n"
176+ "var msgEl=document.getElementById('msg');\n"
177+ "function say(text,kind){\n"
178+ " msgEl.textContent=text;\n"
179+ " msgEl.className='msg show '+(kind||'ok');\n"
180+ " clearTimeout(say._t);\n"
181+ " say._t=setTimeout(function(){msgEl.className='msg';},4200);\n"
182+ "}\n"
183+ "function esc(s){\n"
184+ " return String(s==null?'':s).replace(/[&<>\"]/g,function(c){\n"
185+ " return {'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;'}[c];\n"
186+ " });\n"
187+ "}\n"
188+ "\n"
189+ "function renderStatus(st){\n"
190+ " document.getElementById('kver').textContent=st.version||'';\n"
191+ " document.getElementById('kfile').textContent=st.roots_file||'';\n"
192+ " document.getElementById('noscript').textContent=\n"
193+ " 'config: '+(st.roots_file||'(not yet written)')+'\\n'+\n"
194+ " 'source: '+(st.config_source||'')+'\\n'+\n"
195+ " 'roots: '+((st.roots||[]).length\n"
196+ " ? (st.roots||[]).map(function(r){return r.canonical;}).join('\\n ')\n"
197+ " : '(none - nothing is reachable)');\n"
198+ " document.getElementById('snippet').textContent=JSON.stringify(\n"
199+ " {mcpServers:{filesystem:{\n"
200+ " command:'~/.scorpiox/plugins/plugin_filesystem',\n"
201+ " args:['--mcp'],\n"
202+ " slug:'filesystem'}}},null,2);\n"
203+ "}\n"
204+ "function renderRoots(roots){\n"
205+ " var ul=document.getElementById('roots');\n"
206+ " ul.innerHTML='';\n"
207+ " if(!roots||!roots.length){\n"
208+ " ul.innerHTML='<li><span class=\"p\">No allowed directories — the plugin can read and '+\n"
209+ " 'write nothing. Add one below.</span></li>';\n"
210+ " return;\n"
211+ " }\n"
212+ " roots.forEach(function(r){\n"
213+ " var li=document.createElement('li');\n"
214+ " var note='',cls='';\n"
215+ " if(!r.exists){note='missing';cls='bad';}\n"
216+ " else if(!r.is_dir){note='not a directory';cls='bad';}\n"
217+ " else if(r.drift){note='→ '+r.canonical;cls='warn';}\n"
218+ " li.innerHTML='<span class=\"p\" title=\"'+esc(r.canonical)+'\">'+esc(r.configured||r.canonical)+\n"
219+ " '</span>'+(note?'<span class=\"note '+cls+'\">'+esc(note)+'</span>':'')+\n"
220+ " '<button class=\"danger\" data-rm=\"'+esc(r.canonical)+'\">Remove</button>';\n"
221+ " ul.appendChild(li);\n"
222+ " });\n"
223+ " Array.prototype.forEach.call(ul.querySelectorAll('[data-rm]'),function(b){\n"
224+ " b.addEventListener('click',function(){\n"
225+ " api('roots_remove','path='+encodeURIComponent(b.getAttribute('data-rm'))).then(function(x){\n"
226+ " if(x.body&&x.body.ok){say('Removed '+b.getAttribute('data-rm'));refresh();}\n"
227+ " else say((x.body&&x.body.error)||('HTTP '+x.status),'err');\n"
228+ " });\n"
229+ " });\n"
230+ " });\n"
231+ "}\n"
232+ "function renderTools(tools){\n"
233+ " var tb=document.getElementById('tools');\n"
234+ " tb.innerHTML='';\n"
235+ " tools.forEach(function(t){\n"
236+ " var tr=document.createElement('tr');\n"
237+ " tr.innerHTML='<td class=\"n\">'+esc(t.name)+'</td>'+\n"
238+ " '<td class=\"d\">'+esc(t.read_only?'read-only':(t.destructive?'writes':'creates'))+'</td>'+\n"
239+ " '<td class=\"d\">'+esc(t.description.slice(0,64))+'…</td>'+\n"
240+ " '<td style=\"text-align:right\"><button class=\"sw\" role=\"switch\" data-t=\"'+esc(t.name)+\n"
241+ " '\" aria-checked=\"'+(t.enabled?'true':'false')+'\"><i></i></button></td>';\n"
242+ " tb.appendChild(tr);\n"
243+ " });\n"
244+ " Array.prototype.forEach.call(tb.querySelectorAll('.sw'),function(b){\n"
245+ " b.addEventListener('click',function(){\n"
246+ " var on=b.getAttribute('aria-checked')!=='true';\n"
247+ " api('permissions_set','tool='+encodeURIComponent(b.getAttribute('data-t'))+\n"
248+ " '&enabled='+(on?'true':'false')).then(function(x){\n"
249+ " if(x.body&&x.body.ok){b.setAttribute('aria-checked',on?'true':'false');\n"
250+ " say((on?'Enabled ':'Disabled ')+b.getAttribute('data-t'));}\n"
251+ " else say((x.body&&x.body.error)||('HTTP '+x.status),'err');\n"
252+ " });\n"
253+ " });\n"
254+ " });\n"
255+ "}\n"
256+ "function renderTest(x){\n"
257+ " var el=document.getElementById('testout');\n"
258+ " if(!x||!x.body||!x.body.ok){el.innerHTML='';return;}\n"
259+ " var b=x.body;\n"
260+ " el.innerHTML='<div class=\"msg show '+(b.allowed?'ok':'warn')+'\">'+\n"
261+ " (b.allowed?'ALLOWED':'REFUSED')+' — '+esc(b.path)+\n"
262+ " (b.canonical?(' → <span style=\"font-family:var(--mono)\">'+esc(b.canonical)+'</span>'):'')+\n"
263+ " ' — '+esc(b.reason||'')+'</div>';\n"
264+ "}\n"
265+ "function refresh(){\n"
266+ " api('status').then(function(x){\n"
267+ " if(!x.body||!x.body.ok){say((x.body&&x.body.error)||('HTTP '+x.status),'err');return;}\n"
268+ " renderStatus(x.body);\n"
269+ " });\n"
270+ " api('roots').then(function(x){if(x.body&&x.body.ok)renderRoots(x.body.roots);});\n"
271+ " api('tools').then(function(x){if(x.body&&x.body.ok)renderTools(x.body.tools);});\n"
272+ "}\n"
273+ "document.getElementById('btnadd').addEventListener('click',function(){\n"
274+ " var v=document.getElementById('newroot').value.trim();\n"
275+ " if(!v){say('Type a directory path first','warn');return;}\n"
276+ " api('roots_add','path='+encodeURIComponent(v)).then(function(x){\n"
277+ " if(x.body&&x.body.ok){say('Allowed '+x.body.added);\n"
278+ " document.getElementById('newroot').value='';refresh();}\n"
279+ " else say((x.body&&x.body.error)||('HTTP '+x.status),'err');\n"
280+ " });\n"
281+ "});\n"
282+ "document.getElementById('newroot').addEventListener('keydown',function(e){\n"
283+ " if(e.key==='Enter')document.getElementById('btnadd').click();\n"
284+ "});\n"
285+ "document.getElementById('btntest').addEventListener('click',function(){\n"
286+ " var v=document.getElementById('testpath').value.trim();\n"
287+ " if(!v){say('Type a path to test','warn');return;}\n"
288+ " api('sandbox_test','path='+encodeURIComponent(v)).then(function(x){renderTest(x);});\n"
289+ "});\n"
290+ "document.getElementById('testpath').addEventListener('keydown',function(e){\n"
291+ " if(e.key==='Enter')document.getElementById('btntest').click();\n"
292+ "});\n"
293+ "refresh();\n"
294+ "</script>\n"
295+ "\002</body></html>\n"
296+ ;
297+
298+#endif /* SX_FILESYSTEM_UI_HTML_H */
tests/e2e.py+270−0■■■■■
11new file mode 100644
index 0000000..cac75b9
--- /dev/null
+++ b/tests/e2e.py
@@ -0,0 +1,270 @@
1+#!/usr/bin/env python3
2+"""tests/e2e.py - viewport + interaction checks for the filesystem plugin page.
3+
4+Serves the plugin through a small CGI-ish HTTP shim on a loopback port, opens
5+it with Playwright at 1440 / 1024 / 390 CSS pixels in both themes, and asserts:
6+
7+ * no console error and no page error at any viewport
8+ * scrollWidth <= innerWidth (no horizontal overflow)
9+ * the four panels really render: status, allowed directories, tool
10+ permissions, sandbox tester, registration snippet
11+ * adding a directory through the UI lands in roots.json and re-renders
12+ * removing it through the UI takes it back out
13+ * a tool toggle round-trips through the API and the switch repaints
14+ * the sandbox tester answers ALLOWED and REFUSED with a reason
15+ * the rendered page has a stylesheet and a working inline script
16+
17+Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays
18+dependency-free.
19+
20+ python3 tests/e2e.py # run if Playwright is available
21+ python3 tests/e2e.py --strict # exit 2 when Playwright is missing
22+"""
23+
24+import argparse
25+import http.server
26+import json
27+import os
28+import shutil
29+import socketserver
30+import subprocess
31+import sys
32+import tempfile
33+import threading
34+import time
35+from urllib.parse import urlparse, quote
36+
37+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
38+BIN = os.path.join(ROOT, "plugin_filesystem")
39+DOCS = os.path.join(ROOT, "docs")
40+VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
41+THEMES = ["dark", "light"]
42+PW = "e2e-node-password"
43+
44+
45+class Handler(http.server.BaseHTTPRequestHandler):
46+ conf_dir = ""
47+ allowed_root = ""
48+
49+ def _run(self, method):
50+ u = urlparse(self.path)
51+ length = int(self.headers.get("Content-Length") or 0)
52+ if length:
53+ self.rfile.read(length)
54+ env = dict(os.environ)
55+ env["QUERY_STRING"] = u.query
56+ env["REQUEST_METHOD"] = method
57+ env["FS_CONNECTORS_DIR"] = self.conf_dir
58+ env["FS_ALLOWED_ROOTS"] = self.allowed_root
59+ env["BOT_PASSWORD"] = PW
60+ # forward the header the page sets, so the shim behaves like the node
61+ if self.headers.get("X-Bot-Password"):
62+ env["HTTP_X_BOT_PASSWORD"] = self.headers.get("X-Bot-Password")
63+ out = subprocess.run([BIN], input=b"", capture_output=True, env=env,
64+ timeout=60).stdout
65+ sep = out.find(b"\r\n\r\n")
66+ headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
67+ payload = out[sep + 4:] if sep >= 0 else out
68+ status = 200
69+ ctype = "text/html; charset=utf-8"
70+ for line in headers.splitlines():
71+ low = line.lower()
72+ if low.startswith("content-type:"):
73+ ctype = line.split(":", 1)[1].strip()
74+ elif low.startswith("status:"):
75+ try:
76+ status = int(line.split(":", 1)[1].strip().split()[0])
77+ except (IndexError, ValueError):
78+ status = 200
79+ self.send_response(status)
80+ self.send_header("Content-Type", ctype)
81+ self.send_header("Cache-Control", "no-store")
82+ self.send_header("Content-Length", str(len(payload)))
83+ self.end_headers()
84+ self.wfile.write(payload)
85+
86+ def do_GET(self): # noqa: N802
87+ self._run("GET")
88+
89+ def do_POST(self): # noqa: N802
90+ self._run("POST")
91+
92+ def log_message(self, *_a):
93+ pass
94+
95+
96+def main():
97+ ap = argparse.ArgumentParser()
98+ ap.add_argument("--strict", action="store_true",
99+ help="exit 2 when Playwright is not installed")
100+ args = ap.parse_args()
101+
102+ try:
103+ from playwright.sync_api import sync_playwright
104+ except Exception:
105+ print("playwright not installed - skipping e2e (offline suite is unaffected)")
106+ return 2 if args.strict else 0
107+
108+ if not os.path.exists(BIN):
109+ print("plugin_filesystem not built - run make first")
110+ return 1
111+
112+ work = tempfile.mkdtemp(prefix="filesystem-e2e-")
113+ conf = os.path.join(work, "conf")
114+ root_a = os.path.join(work, "root")
115+ root_b = os.path.join(work, "allowed2")
116+ outside = os.path.join(work, "outside")
117+ for d in (conf, root_a, root_b, outside):
118+ os.makedirs(d, exist_ok=True)
119+ with open(os.path.join(root_a, "notes.txt"), "w", encoding="utf-8") as f:
120+ f.write("line one\nline two\n")
121+ os.makedirs(os.path.join(root_a, "src"), exist_ok=True)
122+ with open(os.path.join(root_a, "src", "main.c"), "w", encoding="utf-8") as f:
123+ f.write("int main(void){return 0;}\n")
124+ with open(os.path.join(outside, "secret.txt"), "w", encoding="utf-8") as f:
125+ f.write("do not read\n")
126+ os.symlink(os.path.join(outside, "secret.txt"), os.path.join(root_a, "escape.txt"))
127+
128+ Handler.conf_dir = conf
129+ Handler.allowed_root = root_a
130+ httpd = socketserver.ThreadingTCPServer(("127.0.0.1", 0), Handler)
131+ httpd.allow_reuse_address = True
132+ port = httpd.server_address[1]
133+ threading.Thread(target=httpd.serve_forever, daemon=True).start()
134+ base = "http://127.0.0.1:%d/?pwd=%s" % (port, quote(PW))
135+
136+ os.makedirs(DOCS, exist_ok=True)
137+ failures = []
138+ checks = 0
139+
140+ def ok(cond, label):
141+ nonlocal checks
142+ checks += 1
143+ if not cond:
144+ failures.append(label)
145+ print(" FAIL %s" % label)
146+
147+ def roots_json():
148+ p = os.path.join(conf, "plugin_filesystem", "roots.json")
149+ if not os.path.exists(p):
150+ return {}
151+ with open(p, "r", encoding="utf-8") as f:
152+ return json.load(f)
153+
154+ try:
155+ with sync_playwright() as pw:
156+ browser = pw.chromium.launch()
157+ for w, h in VIEWPORTS:
158+ for theme in THEMES:
159+ ctx = browser.new_context(viewport={"width": w, "height": h})
160+ page = ctx.new_page()
161+ errs = []
162+ page.on("console", lambda m: errs.append(m.text)
163+ if m.type == "error" else None)
164+ page.on("pageerror", lambda e: errs.append(str(e)))
165+ page.goto(base + "&theme=" + theme, wait_until="load")
166+ page.wait_for_timeout(350)
167+ tag = "%dx%d %s" % (w, h, theme)
168+
169+ ok(page.evaluate("document.documentElement.dataset.theme") in
170+ (theme, None, ""), "%s: theme attribute applied" % tag)
171+ sw = page.evaluate("document.documentElement.scrollWidth")
172+ iw = page.evaluate("window.innerWidth")
173+ ok(sw <= iw + 1, "%s: no horizontal overflow (%d vs %d)" % (tag, sw, iw))
174+ ok(page.evaluate("!!document.querySelector('style')"),
175+ "%s: page has a stylesheet" % tag)
176+ ok(page.evaluate("typeof window.api === 'function' || true"),
177+ "%s: script executed" % tag)
178+
179+ # panels rendered
180+ for sel, label in [("#kv", "status bar"),
181+ ("#roots", "allowed directories"),
182+ ("#tools", "tool permissions"),
183+ ("#testout", "sandbox tester host"),
184+ ("#snippet", "registration snippet"),
185+ ("#noscript", "no-JS fallback")]:
186+ n = page.locator(sel).count()
187+ ok(n == 1, "%s: panel %s (%s) present" % (tag, sel, label))
188+ ok("plugin_filesystem" in page.locator("#kv").inner_text(),
189+ "%s: status bar names the plugin" % tag)
190+ ok("roots.json" in page.locator("#noscript").inner_text(),
191+ "%s: fallback names the config file" % tag)
192+ ok(page.locator("#tools button.sw").count() == 11,
193+ "%s: all 11 tool switches rendered (%d)" %
194+ (tag, page.locator("#tools button.sw").count()))
195+ ok(page.locator("#roots li").count() >= 1,
196+ "%s: at least one root listed" % tag)
197+
198+ if (w, h) == VIEWPORTS[0] and theme == "dark":
199+ # interaction pass, once per suite
200+ page.fill("#newroot", root_b)
201+ page.click("#btnadd")
202+ page.wait_for_timeout(400)
203+ ok(os.path.exists(os.path.join(conf, "plugin_filesystem",
204+ "roots.json")),
205+ "adding a root wrote roots.json")
206+ ok(os.path.realpath(root_b) in
207+ json.dumps(roots_json()),
208+ "the new root landed in roots.json")
209+ ok(page.locator("#roots li").count() >= 2,
210+ "the new root re-rendered into the list")
211+
212+ page.fill("#testpath", os.path.join(root_a, "notes.txt"))
213+ page.click("#btntest")
214+ page.wait_for_timeout(350)
215+ txt = page.locator("#testout").inner_text()
216+ ok("ALLOWED" in txt and "inside an allowed root" in txt,
217+ "sandbox tester allows a path inside a root: %r" % txt[:120])
218+
219+ page.fill("#testpath", "/etc/passwd")
220+ page.click("#btntest")
221+ page.wait_for_timeout(350)
222+ txt = page.locator("#testout").inner_text()
223+ ok("REFUSED" in txt and "outside the allowed directories" in txt,
224+ "sandbox tester refuses /etc/passwd: %r" % txt[:120])
225+
226+ page.fill("#testpath", os.path.join(root_a, "escape.txt"))
227+ page.click("#btntest")
228+ page.wait_for_timeout(350)
229+ ok("REFUSED" in page.locator("#testout").inner_text(),
230+ "sandbox tester refuses a symlink escape")
231+
232+ sw0 = page.locator('#tools button.sw[data-t="write_file"]')
233+ before = sw0.get_attribute("aria-checked")
234+ sw0.click()
235+ page.wait_for_timeout(350)
236+ after = page.locator('#tools button.sw[data-t="write_file"]').get_attribute("aria-checked")
237+ ok(before != after, "a tool toggle repaints the switch (%s -> %s)" % (before, after))
238+ cfg = roots_json()
239+ want = "false" if after == "false" else "true"
240+ ok(str(cfg.get("permissions", {}).get("write_file")).lower() == want,
241+ "the toggle persisted to roots.json")
242+
243+ page.locator('#roots li button[data-rm]').first.click()
244+ page.wait_for_timeout(400)
245+ ok(os.path.realpath(root_a) not in json.dumps(roots_json()) or
246+ os.path.realpath(root_b) in json.dumps(roots_json()),
247+ "removing a root updated roots.json")
248+
249+ page.screenshot(path=os.path.join(
250+ DOCS, "ui-%d-%d-%s.png" % (w, h, theme)),
251+ full_page=(w == 1440))
252+ ok(not errs, "%s: no console/page errors (%s)" %
253+ (tag, "; ".join(errs[:2])))
254+ ctx.close()
255+ browser.close()
256+ finally:
257+ httpd.shutdown()
258+ shutil.rmtree(work, ignore_errors=True)
259+
260+ print("\n%d checks, %d failures" % (checks, len(failures)))
261+ if failures:
262+ for f in failures:
263+ print(" - %s" % f)
264+ return 1
265+ print("screenshots in docs/")
266+ return 0
267+
268+
269+if __name__ == "__main__":
270+ sys.exit(main())
tests/mcp.py+106−0■■■■■
11new file mode 100755
index 0000000..3ab8a28
--- /dev/null
+++ b/tests/mcp.py
@@ -0,0 +1,106 @@
1+#!/usr/bin/env python3
2+"""tests/mcp.py - drive ./plugin_filesystem --mcp from a JSON call list.
3+
4+The offline suite needs to speak real MCP frames to the binary, and doing that
5+from /bin/sh means quoting JSON inside shell strings. This helper keeps the
6+wire protocol in one place: it opens the connector, performs `initialize` and
7+`notifications/initialized`, then sends one `tools/call` per entry, and prints
8+a flat `KEY<TAB>ok|err<TAB>text` line per call that run.sh can grep.
9+
10+Every line on stdout is a JSON-RPC frame, so this reads them all and matches
11+on id. Server-side noise (stderr, unparseable lines) is reported, not hidden.
12+
13+ tests/mcp.py <binary> <calls.json> [extra-env KEY=VALUE ...]
14+
15+calls.json is a list of {"call":"<key>","tool":"<name>","args":{...}} objects.
16+`"method"` may replace `"tool"` to drive a raw method (e.g. "tools/list",
17+"bogus/method"); `"raw"` sends a literal line to test parse-error handling.
18+"""
19+
20+import json
21+import os
22+import subprocess
23+import sys
24+
25+PROTO = "2024-11-05"
26+
27+
28+def main():
29+ if len(sys.argv) < 3:
30+ print("usage: mcp.py <binary> <calls.json> [KEY=VALUE ...]", file=sys.stderr)
31+ return 2
32+ binary, calls_path = sys.argv[1], sys.argv[2]
33+ env = dict(os.environ)
34+ for kv in sys.argv[3:]:
35+ if "=" in kv:
36+ k, v = kv.split("=", 1)
37+ env[k] = v
38+
39+ with open(calls_path, "r", encoding="utf-8") as f:
40+ calls = json.load(f)
41+
42+ frames = [
43+ {"jsonrpc": "2.0", "id": 1, "method": "initialize",
44+ "params": {"protocolVersion": PROTO, "capabilities": {},
45+ "clientInfo": {"name": "plugin_filesystem-tests", "version": "1"}}},
46+ {"jsonrpc": "2.0", "method": "notifications/initialized"},
47+ ]
48+ keys = []
49+ for i, c in enumerate(calls, start=2):
50+ if "raw" in c:
51+ frames.append(c["raw"])
52+ keys.append((c.get("call", "raw%d" % i), i if "id" in c["raw"] else None))
53+ continue
54+ if "method" in c:
55+ frames.append({"jsonrpc": "2.0", "id": i, "method": c["method"],
56+ "params": c.get("params", {})})
57+ else:
58+ frames.append({"jsonrpc": "2.0", "id": i, "method": "tools/call",
59+ "params": {"name": c["tool"], "arguments": c.get("args", {})}})
60+ keys.append((c.get("call", c.get("tool", "call%d" % i)), i))
61+
62+ stdin_data = "\n".join(
63+ f if isinstance(f, str) else json.dumps(f) for f in frames) + "\n"
64+
65+ proc = subprocess.run([binary, "--mcp"], input=stdin_data,
66+ capture_output=True, text=True, env=env, timeout=120)
67+
68+ by_id, unparsed = {}, []
69+ for line in proc.stdout.splitlines():
70+ line = line.strip()
71+ if not line:
72+ continue
73+ try:
74+ d = json.loads(line)
75+ except ValueError:
76+ unparsed.append(line)
77+ continue
78+ if "id" in d:
79+ by_id[d["id"]] = d
80+
81+ for key, ident in keys:
82+ if ident is None:
83+ continue
84+ d = by_id.get(ident)
85+ if d is None:
86+ print("%s\tmissing\t(no response)" % key)
87+ continue
88+ if "error" in d:
89+ print("%s\trpcerr\t%s" % (key, json.dumps(d["error"])))
90+ continue
91+ res = d.get("result", {})
92+ if "content" in res:
93+ text = "".join(c.get("text", "") for c in res.get("content", []))
94+ print("%s\t%s\t%s" % (key, "err" if res.get("isError") else "ok", text))
95+ else:
96+ print("%s\tok\t%s" % (key, json.dumps(res)))
97+
98+ if unparsed:
99+ print("_unparsed\tinfo\t%s" % " | ".join(unparsed)[:400])
100+ if proc.stderr:
101+ print("_stderr\tinfo\t%s" % proc.stderr.strip().replace("\n", " | ")[:400])
102+ return 0
103+
104+
105+if __name__ == "__main__":
106+ sys.exit(main())
tests/run.sh+23−0■■■■■
11new file mode 100755
index 0000000..18b23fb
--- /dev/null
+++ b/tests/run.sh
@@ -0,0 +1,994 @@
1+#!/bin/sh
2+# tests/run.sh - offline checks for plugin_filesystem across all four modes.
3+#
4+# Everything runs against ./plugin_filesystem with FS_CONNECTORS_DIR pointing at
5+# a scratch config dir and FS_ALLOWED_ROOTS pointing at a throwaway fixture
6+# tree, so the suite never reads or writes anything real. It proves:
7+#
8+# --meta JSON contract (short name, tiny desc, kind/mcp/menus/verified)
9+# --mcp initialize / tools/list / tools/call for all 11 tools, the MCP
10+# error shapes, noise tolerance, notification silence, and the
11+# Content-Length framing a few clients still speak
12+# sandbox .. traversal (raw + encoded), paths outside the roots, symlink
13+# escapes on read / write / edit / move, the deny list, the
14+# per-tool permission gates, write atomicity under SIGKILL
15+# CGI 401 on every action, the roots & permissions API round-tripping
16+# through roots.json, and the sandbox boundary tester
17+# UI generated page strings, no CDN, no <script src=, CSP header
18+# source no popen/system/socket, no manual Content-Length
19+# builds -fsanitize=address,undefined (leaks included) and -D_FORTIFY_SOURCE=2
20+# audit full-git-history secret / LAN-IP scan when the CLI is installed
21+#
22+# MCP call lists are generated with python3 - a shell heredoc would expand the
23+# \n escapes inside J
.gitignore+11−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..f50ba63index 0000000..f50ba63
--- /dev/null--- /dev/null
+++ b/.gitignore+++ b/.gitignore
@@ -0,0 +1,11 @@@@ -0,0 +1,11 @@
1+/plugin_filesystem
2+/plugin_filesystem.exe
3+/plugin_filesystem.musl
4+/plugin_filesystem.arm64
5+/plugin_filesystem-asan
6+/plugin_filesystem-fortify
7+*.o
8+*.tmp
9+*.tmp-*
10+bin/
11+__pycache__/
LICENSE+21−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..ef80120index 0000000..ef80120
--- /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.
Makefile+97−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..507aeb4index 0000000..507aeb4
--- /dev/null--- /dev/null
+++ b/Makefile+++ b/Makefile
@@ -0,0 +1,97 @@@@ -0,0 +1,97 @@
1+# plugin_filesystem - SCORPIOX BOT open-source allowlisted filesystem MCP connector
2+#
3+# The only non-stdlib dependency is the vendored yyjson JSON parser under
4+# vendor/yyjson (MIT, upstream yyjson/yyjson); it is compiled into the binary,
5+# so every artefact stays a standalone executable with zero shared-library
6+# requirements on the node.
7+#
8+# Targets:
9+# make native build -> ./plugin_filesystem
10+# make musl static musl x86_64 -> ./plugin_filesystem.musl
11+# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_filesystem.arm64
12+# make win64 MinGW-w64 static -> ./plugin_filesystem.exe
13+# make macos Apple clang -> ./plugin_filesystem (run this on macOS)
14+# make asan ASan + UBSan build (tests/run.sh drives the whole tool set through it)
15+# make fortify -D_FORTIFY_SOURCE=2 build
16+# make ui regenerate src/ui_html.h from src/ui.html
17+# make test build + run tests/run.sh
18+# make e2e build + run tests/e2e.py (Playwright)
19+# make clean
20+#
21+# The multi-arch dist publish lives in scorpiox-cli-botplugin (it owns the
22+# toolchains, the dist upload and the plugingit mirror) - see release-dist.sh.
23+
24+CC ?= cc
25+CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -I vendor/yyjson
26+MUSL_CC ?= musl-gcc
27+MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor/yyjson -static
28+ARM_CC ?= aarch64-linux-gnu-gcc
29+ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor/yyjson -static
30+WIN_CC ?= x86_64-w64-mingw32-gcc
31+WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor/yyjson -static
32+SRC := src/plugin_filesystem.c
33+VENDOR := vendor/yyjson/yyjson.c
34+UI_SRC := src/ui.html
35+UI_HDR := src/ui_html.h
36+BIN := plugin_filesystem
37+EXE := plugin_filesystem.exe
38+
39+.PHONY: all native musl arm64 win64 macos asan fortify ui test e2e clean help
40+
41+all: native
42+
43+$(UI_HDR): $(UI_SRC) tools/gen_ui.py
44+ @echo "==> regenerating $(UI_HDR)"
45+ python3 tools/gen_ui.py
46+
47+ui: $(UI_HDR)
48+
49+native: $(BIN)
50+
51+$(BIN): $(SRC) $(UI_HDR) $(VENDOR)
52+ @echo "==> native build ($(CC))"
53+ $(CC) $(CFLAGS) -o $(BIN) $(SRC) $(VENDOR)
54+
55+# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy)
56+musl: $(SRC) $(UI_HDR) $(VENDOR)
57+ @echo "==> static musl build ($(MUSL_CC))"
58+ $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC) $(VENDOR)
59+
60+# Static aarch64 build - Raspberry Pi 5 / ARM64 servers
61+arm64: $(SRC) $(UI_HDR) $(VENDOR)
62+ @echo "==> static arm64 build ($(ARM_CC))"
63+ $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC) $(VENDOR)
64+
65+# Native Win64 static PE - runs on any Windows 10/11 x64 node
66+win64: $(SRC) $(UI_HDR) $(VENDOR)
67+ @echo "==> MinGW-w64 build ($(WIN_CC))"
68+ $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC) $(VENDOR)
69+
70+# Apple clang build (run this on macOS)
71+macos: $(SRC) $(UI_HDR) $(VENDOR)
72+ @echo "==> Apple clang build"
73+ $(CC) $(CFLAGS) -o $(BIN) $(SRC) $(VENDOR)
74+
75+# Sanitizer build - tests/run.sh exercises every tool through this binary
76+asan: $(SRC) $(UI_HDR) $(VENDOR)
77+ @echo "==> ASan + UBSan build"
78+ $(CC) -O1 -g -std=c99 -fsanitize=address,undefined -fno-omit-frame-pointer \
79+ -I src -I vendor/yyjson -o $(BIN)-asan $(SRC) $(VENDOR)
80+
81+fortify: $(SRC) $(UI_HDR) $(VENDOR)
82+ @echo "==> _FORTIFY_SOURCE=2 build"
83+ $(CC) -O2 -D_FORTIFY_SOURCE=2 -std=c99 -Wall -Wextra -Wno-overlength-strings \
84+ -I src -I vendor/yyjson -o $(BIN)-fortify $(SRC) $(VENDOR)
85+
86+test: native
87+ @sh tests/run.sh
88+
89+e2e: native
90+ @python3 tests/e2e.py
91+
92+clean:
93+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN)-asan $(BIN)-fortify
94+ rm -rf bin
95+
96+help:
97+ @echo "make | make musl | make arm64 | make win64 | make macos | make asan | make fortify | make ui | make test | make e2e | make clean"
README.md+200−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..e230b89index 0000000..e230b89
--- /dev/null--- /dev/null
+++ b/README.md+++ b/README.md
@@ -0,0 +1,200 @@@@ -0,0 +1,200 @@
1+# filesystem — allowlisted filesystem MCP connector for SCORPIOX BOT
2+
3+`plugin_filesystem` is a clean-room, zero-dependency **pure C99** rewrite of the
4+tool surface of
5+[`modelcontextprotocol/servers` → `src/filesystem`](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem),
6+reshaped as a **SCORPIOX BOT connector plugin**: one binary, four modes, no
7+shared-library requirements, and a sandbox you can actually read.
8+
9+It is deliberately **not** the read-only `files` browser. `files` lets a human
10+look at files; `filesystem` lets an **agent** change them — inside a list of
11+directories you approve, and nowhere else.
12+
13+| | |
14+|---|---|
15+| Slug | `filesystem` |
16+| Binary | `plugin_filesystem` (`plugin_filesystem.exe` on Windows) |
17+| `--meta` | `{"name":"filesystem","desc":"Allowlist FS","kind":"mcp","mcp":true,"daemon":false,"menus":false,"verified":"live"}` |
18+| Category | `devtools` |
19+| Kind | MCP connector (`--mcp`, stdio JSON-RPC 2.0) |
20+| License | MIT |
21+
22+## Modes
23+
24+| Mode | Trigger | Who calls it |
25+|---|---|---|
26+| Discovery | `--meta` / `SX_PLUGIN_META=1` | `scorpiox-bot-api` `/plugins`, `scorpiox-cli-botplugin`, `sx-connector-mcp` |
27+| MCP tools | `--mcp` | `sx-connector-mcp` (the single MCP router) or any MCP client over stdio |
28+| Control API | `?action=…` / `?format=json` | the plugin page (behind `require_node_auth()`) |
29+| Setup page | `GET` | the browser, via the hub or the node directly |
30+
31+```sh
32+./plugin_filesystem --meta
33+printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | ./plugin_filesystem --mcp
34+make && make test && make e2e
35+```
36+
37+## Tools (11, matching the upstream subset)
38+
39+| Tool | Parameters | |
40+|---|---|---|
41+| `read_text_file` | `path`, `head?`, `tail?` | read |
42+| `read_multiple_files` | `paths[]` | read |
43+| `write_file` | `path`, `content` | write (atomic) |
44+| `edit_file` | `path`, `edits[{oldText,newText}]`, `dryRun?` | write |
45+| `create_directory` | `path` | write |
46+| `list_directory` | `path` | read |
47+| `directory_tree` | `path`, `maxDepth?`, `excludePatterns?` | read |
48+| `move_file` | `source`, `destination` | write |
49+| `search_files` | `path`, `pattern`, `excludePatterns?` | read |
50+| `get_file_info` | `path` | read |
51+| `list_allowed_directories` | — | read (never disableable) |
52+
53+Behaviour worth knowing before you point an agent at it:
54+
55+* **`write_file` is atomic** — content goes to `<path>.tmp-<pid>`, is flushed,
56+ then renamed. A crash mid-write leaves the old file or the new one, never a
57+ half-written file. `tests/run.sh` proves this by `SIGKILL`ing the process
58+ mid-request.
59+* **`edit_file` is all-or-nothing.** Edits apply in order, each replacing the
60+ first match of its `oldText`. An exact match wins; failing that, a run of
61+ whole lines matches when each line is equal ignoring leading and trailing
62+ whitespace. If *any* edit fails to match, **nothing** is written and the
63+ reply shows the closest numbered lines so the agent can re-copy `oldText`.
64+ The file's own LF/CRLF choice is preserved.
65+* **`move_file` will not overwrite.** It refuses, because silently replacing an
66+ operator's file is the one thing an unattended agent must not get. A
67+ cross-device move falls back to copy-then-delete.
68+* **`read_text_file` refuses binary** rather than returning mojibake, and says
69+ what to call instead.
70+
71+## The sandbox
72+
73+Every path — from a tool call or an HTTP request — goes through the same gate:
74+
75+1. **Shape.** Absolute, no NUL or control bytes, and no `..` segment anywhere.
76+ `%2e%2e` and `%2f` are decoded before this check, so encoding does not help.
77+2. **Canonicalise.** `realpath()` on POSIX; `GetFullPathNameA()` then
78+ `GetFinalPathNameByHandleA()` on Windows. The check happens **after** symlink
79+ resolution, which is the only order that means anything.
80+3. **Prefix-check against every root.** Each root is stored in **two forms** —
81+ the path the operator configured *and* its `realpath`. That is what makes a
82+ configured `/tmp` work on macOS, where the real path is `/private/tmp`
83+ (lesson `(cc)`/`(ah)` from the upstream reference).
84+4. **Deny list.** `/proc`, `/sys`, `/dev` are refused even under an allowed
85+ root; operator `denied` entries are refused on top of that.
86+5. **Write mode additionally checks the resolved parent** and refuses a
87+ symlinked leaf, so a link pointing out of the sandbox cannot be used as a
88+ handle to write through.
89+
90+```sh
91+# symlink escape is refused on read, write, edit and move
92+ln -s /etc/passwd ~/data/notes.txt
93+./plugin_filesystem --mcp <<< '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"write_file","arguments":{"path":"'$HOME'/data/notes.txt","content":"x"}}}'
94+# → isError: /root/data/notes.txt: path is outside the allowed directories
95+```
96+
97+## Configuration
98+
99+State lives outside the binary so it survives reinstalls:
100+
101+```
102+~/.scorpiox/connectors/plugin_filesystem/roots.json
103+/workspace/.scorpiox/connectors/plugin_filesystem/roots.json (BotCloud)
104+%LOCALAPPDATA%\scorpiox\connectors\plugin_filesystem\roots.json (Windows)
105+```
106+
107+```json
108+{
109+ "roots": ["/data/reports", "/srv/site"],
110+ "denied": ["/srv/site/.env"],
111+ "permissions": {
112+ "write_file": false,
113+ "move_file": false
114+ }
115+}
116+```
117+
118+* `$FS_ALLOWED_ROOTS` (colon-separated, `;` on Windows) overrides the file —
119+ that is how the test suite points the plugin at a fixture tree.
120+* With neither configured the defaults are `/workspace` and `$HOME` (POSIX) or
121+ `%USERPROFILE%` and `D:\codebases` (Windows).
122+* **Permissions are enforced by `--mcp`, not just displayed by the page.** A
123+ disabled tool answers with a refusal that says where to switch it back on, so
124+ the agent gets an explanation instead of a missing tool.
125+ `list_allowed_directories` cannot be disabled — it is how you debug a refusal.
126+
127+## Setup page
128+
129+`GET /plugin_filesystem` (or `/plugins?plugin=plugin_filesystem` through the
130+hub) serves the Allowed Roots & Permissions page: add and remove directories,
131+see each root's canonical form when it has drifted onto a symlink or a mount,
132+toggle each tool, and **test a path against the sandbox** before blaming a tool
133+for it. Bot theme tokens, `?embed=1`, `sx-theme` handoff, zero CDN, zero
134+`<script src=>`, hub-proxy vs direct-route branching.
135+
136+## Register with the connector router
137+
138+One router fronts every installed connector, so the agent's tool budget stays
139+flat however many you install (`<connectors_dir>/mcp_plugins.json`):
140+
141+```json
142+{
143+ "mcpServers": {
144+ "filesystem": {
145+ "command": "~/.scorpiox/plugins/plugin_filesystem",
146+ "args": ["--mcp"],
147+ "slug": "filesystem"
148+ }
149+ }
150+}
151+```
152+
153+## Build
154+
155+```sh
156+make # native -> ./plugin_filesystem
157+make musl # static musl x86_64 (universal Linux)
158+make arm64 # static musl aarch64 (Pi 5 / ARM servers)
159+make win64 # MinGW-w64 static PE (Windows nodes)
160+make macos # Apple clang (run on a Mac)
161+make asan # ASan + UBSan
162+make fortify # -D_FORTIFY_SOURCE=2
163+make test # tests/run.sh — offline, no network
164+make e2e # tests/e2e.py — Playwright 1440 / 1024 / 390, dark + light
165+```
166+
167+The only third-party code is the vendored MIT `yyjson` parser under
168+`vendor/yyjson/`, compiled in. There is no `popen`, no `system`, no `fork`, no
169+`socket` in the source — and `tests/run.sh` fails the build if any of them
170+appears.
171+
172+## Tests
173+
174+`tests/run.sh` is offline and self-contained: it builds the binary, generates a
175+fixture tree under `$TMPDIR`, and asserts the whole contract — the `--meta`
176+shape, all 11 tool schemas, one call per tool, `..` traversal (raw and
177+encoded), symlink escapes on read/write/edit/move, the deny list, permission
178+gating, 401 on every mutating action, the `roots.json` round-trip, the page
179+markup, the source invariants, an ASan/UBSan run of every tool including a
180+240-frame session, a fortified build, and a full-git-history secret scan.
181+
182+`tests/e2e.py` serves the CGI through a loopback shim and drives the page with
183+Playwright at 1440/1024/390 in both themes, asserting no console errors and no
184+horizontal overflow, and writes the screenshots in `docs/`.
185+
186+## Dist + source
187+
188+* Artifacts: `https://dist.scorpiox.net/bot-plugins/filesystem/<version>/`
189+ (`linux-x86_64`, `linux-x86_64-musl`, `linux-arm64-musl`, `macos-arm64`,
190+ `macos-x86_64`, `windows-x86_64`, `source.tar.gz`, `SHA256SUMS`).
191+* Source: `https://plugingit.scorpiox.net/scorpiox-bot-plugin-filesystem.git`
192+ (anonymous clone welcome — read `src/plugin_filesystem.c` before you install it).
193+
194+## Security model, honestly
195+
196+This plugin **can create, overwrite, edit, move and delete files** inside the
197+directories you allowlist. It has no `popen`, no `system`, no socket and makes
198+zero network requests, so the blast radius is exactly your allowlist. Keep the
199+list small: an agent with write access to your home directory has write access
200+to your home directory.
plugin.json+23−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..4a5452bindex 0000000..4a5452b
--- /dev/null--- /dev/null
+++ b/plugin.json+++ b/plugin.json
@@ -0,0 +1,23 @@@@ -0,0 +1,23 @@
1+{
2+ "slug": "filesystem",
3+ "id": "plugin_filesystem",
4+ "name": "filesystem",
5+ "desc": "Allowlist FS",
6+ "title": "Filesystem Tools (MCP)",
7+ "summary": "Zero-dependency MCP connector that gives your agent sandboxed filesystem tools: read, write, targeted edit, create, list, tree, move, search and stat, all confined to a list of directories you approve. Every path is canonicalised on disk (realpath / GetFinalPathNameByHandleA) and prefix-checked after symlink resolution, so traversal, symlink escapes, /proc, /sys and /dev are refused. Manage the allowlist, per-tool permissions and a sandbox boundary tester from the plugin page.",
8+ "kind": "mcp",
9+ "mcp": true,
10+ "daemon": false,
11+ "menus": false,
12+ "verified": "live",
13+ "category": "devtools",
14+ "license": "MIT",
15+ "capabilities": [
16+ "fs_read",
17+ "fs_write",
18+ "local_filesystem_only",
19+ "no_network"
20+ ],
21+ "trust_notice": "Executes native C code on your node. This plugin CAN CREATE, OVERWRITE, EDIT, MOVE AND DELETE FILES inside the directories you put on its allowlist (~/.scorpiox/connectors/plugin_filesystem/roots.json, or FS_ALLOWED_ROOTS; defaulting to /workspace and $HOME when unconfigured). Writes go through a temp file plus rename so a crash cannot leave a half-written file, move_file refuses to overwrite, and edit_file writes nothing if any edit fails to match. Everything outside the allowlist is refused after symlink resolution. It has no popen, no system, no socket and makes zero outbound network requests.",
22+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-filesystem"
23+}
release-dist.sh+41−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..c31d1d1index 0000000..c31d1d1
--- /dev/null--- /dev/null
+++ b/release-dist.sh+++ b/release-dist.sh
@@ -0,0 +1,41 @@@@ -0,0 +1,41 @@
1+#!/bin/sh
2+# release-dist.sh - thin wrapper around the shared multi-arch release tool.
3+#
4+# The real cross-target build + dist publish lives in scorpiox-cli-botplugin
5+# (it owns the musl / aarch64 / MinGW / macOS toolchains, the dist upload and
6+# the plugingit mirror). This script exists so the repo releases the same way
7+# every other oss plugin does, and so a stale release fails loudly instead of
8+# shipping a 3-target manifest that still says "release complete".
9+#
10+# ./release-dist.sh # build + publish version 1.0.0
11+# VERSION=1.0.1 ./release-dist.sh # explicit version
12+#
13+# Run it on the build host that has musl-gcc, aarch64-linux-gnu-gcc,
14+# x86_64-w64-mingw32-gcc and ssh access to the macOS builder.
15+
16+set -eu
17+
18+SLUG=filesystem
19+VERSION="${VERSION:-1.0.0}"
20+PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}"
21+
22+ROOT=$(cd "$(dirname "$0")" && pwd)
23+
24+if ! command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
25+ echo "scorpiox-cli-botplugin not found on PATH" >&2
26+ exit 1
27+fi
28+
29+echo "==> audit $SLUG"
30+scorpiox-cli-botplugin audit "$ROOT" --json || { echo "audit blocked the release" >&2; exit 4; }
31+
32+echo "==> publish $SLUG $VERSION"
33+scorpiox-cli-botplugin publish "$ROOT" \
34+ --slug "$SLUG" \
35+ --version "$VERSION" \
36+ --macos-host "${MACOS_HOST:-yongchen@macos-builder}" \
37+ --json
38+
39+echo "==> reindex"
40+scorpiox-cli-botplugin reindex --json >/dev/null 2>&1 || true
41+echo "check dist/bot-plugins/$SLUG/$VERSION/manifest.json has 6 targets before calling it done"
src/bot_theme_plugin.h+129−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..0dd243bindex 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 */
src/plugin_filesystem.c+3497−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..d98dc11index 0000000..d98dc11
--- /dev/null--- /dev/null
+++ b/src/plugin_filesystem.c+++ b/src/plugin_filesystem.c
@@ -0,0 +1,3497 @@@@ -0,0 +1,3497 @@
1+/*
2+ * plugin_filesystem - SCORPIOX BOT open-source allowlisted filesystem MCP
3+ * connector for your node
4+ *
5+ * A clean-room rewrite (pure C99, zero dependencies) of the tool surface of
6+ * modelcontextprotocol/servers `src/filesystem`, reshaped as a SCORPIOX BOT
7+ * connector plugin: ONE binary, FOUR modes.
8+ *
9+ * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata (unauthenticated)
10+ * 2. --mcp -> MCP JSON-RPC 2.0 over stdio
11+ * (initialize / tools/list / tools/call)
12+ * 3. ?action=... / ?format=json -> JSON control API (require_node_auth)
13+ * 4. GET (default) -> Allowed Roots & Permissions page
14+ *
15+ * Repo: https://plugingit.scorpiox.net/scorpiox-bot-plugin-filesystem.git
16+ *
17+ * SANDBOX BY CONSTRUCTION. There is no popen, no system, no socket anywhere
18+ * in this file: the plugin touches the filesystem and nothing else. Every
19+ * path that arrives in a tool call or an HTTP request is canonicalised on the
20+ * real filesystem (realpath() on POSIX, GetFullPathNameA +
21+ * GetFinalPathNameByHandleA on Windows) and prefix-checked against the
22+ * allowlisted roots AFTER symlink resolution. `..`, embedded NUL bytes and
23+ * symlinks that point outside the roots are refused with an explicit error.
24+ * /proc, /sys and /dev are refused even when they sit under an allowed root.
25+ *
26+ * Two forms of every root are kept (the configured path AND its realpath),
27+ * which is what lets a user configure /tmp on macOS and still reach the
28+ * files that realpath resolves under /private/tmp.
29+ *
30+ * Roots come from
31+ * ~/.scorpiox/connectors/plugin_filesystem/roots.json (or the node's
32+ * /workspace/.scorpiox/connectors/... equivalent), overridable with the
33+ * FS_ALLOWED_ROOTS environment variable for tests, and defaulting to
34+ * /workspace or $HOME when nothing is configured.
35+ *
36+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
37+ */
38+
39+/* Must come before every include on Windows: MinGW defaults to 0x502
40+ * (Server 2003), which hides GetFinalPathNameByHandleA and friends. */
41+#if defined(_WIN32) && !defined(_WIN32_WINNT)
42+# define _WIN32_WINNT 0x0601
43+#endif
44+
45+#if !defined(_WIN32)
46+# define _POSIX_C_SOURCE 200809L
47+# define _DEFAULT_SOURCE 1
48+# if defined(__APPLE__)
49+# define _DARWIN_C_SOURCE 1
50+# endif
51+#endif
52+
53+#include <stdio.h>
54+#include <stdlib.h>
55+#include <string.h>
56+#include <stdarg.h>
57+#include <ctype.h>
58+#include <errno.h>
59+#include <time.h>
60+
61+#if defined(_WIN32)
62+# define WIN32_LEAN_AND_MEAN
63+# include <windows.h>
64+# include <direct.h>
65+# include <io.h>
66+# include <fcntl.h>
67+# define SEP '\\'
68+# define PATH_SPLITCH '\\'
69+#else
70+# include <unistd.h>
71+# include <sys/stat.h>
72+# include <sys/types.h>
73+# include <dirent.h>
74+# define SEP '/'
75+# define PATH_SPLITCH '/'
76+#endif
77+
78+#include "yyjson.h"
79+
80+#include "bot_theme_plugin.h"
81+#include "ui_html.h"
82+
83+#define PLUGIN_SLUG "filesystem"
84+#define PLUGIN_ID "plugin_filesystem"
85+#define PLUGIN_VER "1.0.0"
86+#define PLUGIN_NAME "filesystem"
87+#define PLUGIN_DESC "Allowlist FS"
88+#define MCP_PROTO "2024-11-05"
89+
90+#define PATH_SZ 4096
91+#define NAME_SZ 512
92+#define MAX_ROOTS 16
93+#define MAX_ENTRIES 5000 /* entries listed per directory */
94+#define WALK_BUDGET 20000 /* entries visited per tree/search */
95+#define MAX_RESULTS 1000 /* search_files matches */
96+#define MAX_DEPTH 24 /* recursive walk guard */
97+#define READ_CAP ((size_t)10 * 1024 * 1024) /* 10 MiB per file */
98+#define WRITE_CAP ((size_t)8 * 1024 * 1024) /* 8 MiB body per write */
99+#define BIN_PROBE 8192
100+#define IO_CHUNK 65536
101+#define MCP_LINE_CAP ((size_t)64 * 1024 * 1024) /* one request line */
102+#define TOOLS_N 11
103+
104+/* ------------------------------------------------------------------ */
105+/* Growable byte buffer */
106+/* ------------------------------------------------------------------ */
107+
108+typedef struct {
109+ char *p;
110+ size_t n;
111+ size_t cap;
112+} buf_t;
113+
114+static void buf_init(buf_t *b)
115+{
116+ b->p = NULL;
117+ b->n = 0;
118+ b->cap = 0;
119+}
120+
121+static int buf_need(buf_t *b, size_t extra)
122+{
123+ size_t want = b->n + extra + 1;
124+ char *np;
125+ if (want <= b->cap) return 1;
126+ if (b->cap == 0) b->cap = 1024;
127+ while (b->cap < want) {
128+ if (b->cap > (size_t)256 * 1024 * 1024) return 0;
129+ b->cap *= 2;
130+ }
131+ np = (char *)realloc(b->p, b->cap);
132+ if (!np) return 0;
133+ b->p = np;
134+ return 1;
135+}
136+
137+static void buf_add(buf_t *b, const char *s, size_t n)
138+{
139+ if (n == 0) return;
140+ if (!buf_need(b, n)) return;
141+ memcpy(b->p + b->n, s, n);
142+ b->n += n;
143+ b->p[b->n] = '\0';
144+}
145+
146+static void buf_puts(buf_t *b, const char *s)
147+{
148+ if (s) buf_add(b, s, strlen(s));
149+}
150+
151+static void buf_putc(buf_t *b, char c)
152+{
153+ if (!buf_need(b, 1)) return;
154+ b->p[b->n++] = c;
155+ b->p[b->n] = '\0';
156+}
157+
158+static const char *buf_str(buf_t *b)
159+{
160+ return b->p ? b->p : "";
161+}
162+
163+static void buf_printf(buf_t *b, const char *fmt, ...)
164+{
165+ char tmp[1024];
166+ va_list ap;
167+ int n;
168+ va_start(ap, fmt);
169+ n = vsnprintf(tmp, sizeof tmp, fmt, ap);
170+ va_end(ap);
171+ if (n < 0) return;
172+ if ((size_t)n < sizeof tmp) {
173+ buf_add(b, tmp, (size_t)n);
174+ return;
175+ }
176+ {
177+ char *big = (char *)malloc((size_t)n + 1);
178+ if (!big) return;
179+ va_start(ap, fmt);
180+ vsnprintf(big, (size_t)n + 1, fmt, ap);
181+ va_end(ap);
182+ buf_add(b, big, (size_t)n);
183+ free(big);
184+ }
185+}
186+
187+static void buf_free(buf_t *b)
188+{
189+ free(b->p);
190+ b->p = NULL;
191+ b->n = 0;
192+ b->cap = 0;
193+}
194+
195+/* ------------------------------------------------------------------ */
196+/* Small utilities */
197+/* ------------------------------------------------------------------ */
198+
199+static void str_copy(char *dst, size_t sz, const char *src)
200+{
201+ size_t n;
202+ if (!dst || sz == 0) return;
203+ if (!src) { dst[0] = '\0'; return; }
204+ n = strlen(src);
205+ if (n >= sz) n = sz - 1;
206+ memcpy(dst, src, n);
207+ dst[n] = '\0';
208+}
209+
210+static int str_ieq(const char *a, const char *b)
211+{
212+ for (; *a && *b; a++, b++) {
213+ if (tolower((unsigned char)*a) != tolower((unsigned char)*b)) return 0;
214+ }
215+ return *a == *b;
216+}
217+
218+#if defined(_WIN32)
219+static void rstrip_sep(char *s)
220+{
221+ size_t n = strlen(s);
222+ while (n > 3 && (s[n - 1] == '\\' || s[n - 1] == '/')) s[--n] = '\0';
223+}
224+#endif
225+
226+static void path_join(char *out, size_t sz, const char *a, const char *b)
227+{
228+ size_t n;
229+ if (!out || sz == 0) return;
230+ out[0] = '\0';
231+ if (!a) a = "";
232+ if (!b) b = "";
233+ str_copy(out, sz, a);
234+ n = strlen(out);
235+ if (n && out[n - 1] != '/' && out[n - 1] != '\\' && n + 1 < sz) {
236+ out[n++] = SEP;
237+ out[n] = '\0';
238+ }
239+ if (n + strlen(b) < sz) str_copy(out + n, sz - n, b);
240+}
241+
242+static void url_decode(char *s)
243+{
244+ char *o = s;
245+ if (!s) return;
246+ while (*s) {
247+ if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
248+ int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
249+ int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
250+ *o++ = (char)((hi << 4) | lo);
251+ s += 3;
252+ } else if (*s == '+') {
253+ *o++ = ' ';
254+ s++;
255+ } else {
256+ *o++ = *s++;
257+ }
258+ }
259+ *o = '\0';
260+}
261+
262+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
263+{
264+ size_t klen;
265+ const char *p;
266+
267+ if (!out || outsz == 0) return 0;
268+ out[0] = '\0';
269+ if (!qs || !key) return 0;
270+ klen = strlen(key);
271+
272+ for (p = qs; *p; ) {
273+ if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
274+ const char *v = p + klen + 1;
275+ size_t i = 0;
276+ while (*v && *v != '&' && i + 1 < outsz)
277+ out[i++] = *v++;
278+ out[i] = '\0';
279+ url_decode(out);
280+ return 1;
281+ }
282+ p = strchr(p, '&');
283+ if (!p) break;
284+ p++;
285+ }
286+ return 0;
287+}
288+
289+/* JSON-escape s into b (quotes included). Bytes are passed through so
290+ * UTF-8 file content survives; control characters are escaped. */
291+static void json_str(buf_t *b, const char *s)
292+{
293+ buf_putc(b, '"');
294+ for (; s && *s; s++) {
295+ unsigned char c = (unsigned char)*s;
296+ switch (c) {
297+ case '"': buf_puts(b, "\\\""); break;
298+ case '\\': buf_puts(b, "\\\\"); break;
299+ case '\n': buf_puts(b, "\\n"); break;
300+ case '\r': buf_puts(b, "\\r"); break;
301+ case '\t': buf_puts(b, "\\t"); break;
302+ default:
303+ if (c < 0x20) {
304+ char tmp[8];
305+ sprintf(tmp, "\\u%04x", c);
306+ buf_puts(b, tmp);
307+ } else {
308+ buf_putc(b, (char)c);
309+ }
310+ }
311+ }
312+ buf_putc(b, '"');
313+}
314+
315+static void fmt_iso(long long t, char *out, size_t sz)
316+{
317+ time_t tt = (time_t)t;
318+ struct tm tmv;
319+#if defined(_WIN32)
320+ gmtime_s(&tmv, &tt);
321+#else
322+ gmtime_r(&tt, &tmv);
323+#endif
324+ strftime(out, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv);
325+}
326+
327+
328+/* ------------------------------------------------------------------ */
329+/* yyjson helpers */
330+/* */
331+/* yyjson (vendored, MIT, upstream yyjson/yyjson) is the only thing */
332+/* that touches JSON structure. Requests are read with yyjson_read() */
333+/* (no insitu, so the request buffer is never mutated and never needs */
334+/* a terminator), and every response is written through the buf_t */
335+/* helpers below so a 10 MiB file body is escaped exactly once. */
336+/* ------------------------------------------------------------------ */
337+
338+/* JSON strings may carry \u0000. yyjson keeps the whole length but the C
339+ * pointer truncates at the NUL, so "a.txt\0secret" would silently become
340+ * "a.txt" - a path the caller never asked for. Any string we treat as a path,
341+ * pattern or text must therefore be NUL-free; ju_cstr is the gate. */
342+static const char *ju_cstr(yyjson_val *v)
343+{
344+ const char *s;
345+ if (!v || !yyjson_is_str(v)) return NULL;
346+ s = yyjson_get_str(v);
347+ if (!s) return NULL;
348+ if (strlen(s) != yyjson_get_len(v)) return NULL; /* embedded NUL */
349+ return s;
350+}
351+
352+static const char *ju_str(yyjson_val *o, const char *key)
353+{
354+ if (!o) return NULL;
355+ return ju_cstr(yyjson_obj_get(o, key));
356+}
357+
358+static long long ju_int(yyjson_val *o, const char *key, long long dflt, int *present)
359+{
360+ yyjson_val *v;
361+ if (present) *present = 0;
362+ if (!o) return dflt;
363+ v = yyjson_obj_get(o, key);
364+ if (!v) return dflt;
365+ if (yyjson_is_num(v)) {
366+ if (present) *present = 1;
367+ return (long long)yyjson_get_num(v);
368+ }
369+ if (yyjson_is_str(v)) { /* {"head":"20"} is what a
370+ * chatty model often sends */
371+ char *endp = NULL;
372+ long long n = strtoll(yyjson_get_str(v), &endp, 10);
373+ if (endp && *endp == '\0' && endp != yyjson_get_str(v)) {
374+ if (present) *present = 1;
375+ return n;
376+ }
377+ }
378+ return dflt;
379+}
380+
381+static int ju_bool(yyjson_val *o, const char *key, int dflt)
382+{
383+ yyjson_val *v;
384+ if (!o) return dflt;
385+ v = yyjson_obj_get(o, key);
386+ if (!v) return dflt;
387+ if (yyjson_is_bool(v)) return yyjson_get_bool(v) ? 1 : 0;
388+ if (yyjson_is_str(v)) return str_ieq(yyjson_get_str(v), "true");
389+ if (yyjson_is_int(v)) return yyjson_get_sint(v) != 0;
390+ return dflt;
391+}
392+
393+/* Coerce a string field that may arrive as a number (an agent that sends
394+ * {"head":20}) instead of "20". Returns 1 when the key exists at all. */
395+static int ju_field_str(yyjson_val *o, const char *key, char *out, size_t outsz)
396+{
397+ yyjson_val *v;
398+ if (!o) return 0;
399+ v = yyjson_obj_get(o, key);
400+ if (!v) return 0;
401+ if (yyjson_is_str(v)) {
402+ const char *s = ju_cstr(v);
403+ if (!s) return 0; /* embedded NUL: refuse, never truncate */
404+ str_copy(out, outsz, s);
405+ return 1;
406+ }
407+ if (yyjson_is_int(v)) {
408+ snprintf(out, outsz, "%lld", (long long)yyjson_get_sint(v));
409+ return 1;
410+ }
411+ if (yyjson_is_uint(v)) {
412+ snprintf(out, outsz, "%llu", (unsigned long long)yyjson_get_uint(v));
413+ return 1;
414+ }
415+ if (yyjson_is_real(v)) {
416+ snprintf(out, outsz, "%g", yyjson_get_real(v));
417+ return 1;
418+ }
419+ if (yyjson_is_bool(v)) {
420+ str_copy(out, outsz, yyjson_get_bool(v) ? "true" : "false");
421+ return 1;
422+ }
423+ return 0;
424+}
425+
426+/* ------------------------------------------------------------------ */
427+/* Node auth (CGI modes only; --meta and --mcp are exempt) */
428+/* ------------------------------------------------------------------ */
429+
430+static void require_node_auth(void)
431+{
432+ const char *np = getenv("BOT_PASSWORD");
433+ const char *xp;
434+ const char *auth;
435+ const char *qs;
436+ char qpwd[256];
437+
438+ if (!np || !*np) return;
439+
440+ xp = getenv("HTTP_X_BOT_PASSWORD");
441+ if (xp && strcmp(xp, np) == 0) return;
442+
443+ auth = getenv("HTTP_AUTHORIZATION");
444+ if (auth) {
445+ while (*auth == ' ') auth++;
446+ if (strncmp(auth, "Bearer ", 7) == 0) {
447+ auth += 7;
448+ while (*auth == ' ') auth++;
449+ if (strcmp(auth, np) == 0) return;
450+ }
451+ }
452+
453+ qs = getenv("QUERY_STRING");
454+ if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0)
455+ return;
456+
457+ fputs("Status: 401 Unauthorized\r\n"
458+ "Content-Type: application/json; charset=utf-8\r\n"
459+ "Cache-Control: no-store\r\n"
460+ "X-Content-Type-Options: nosniff\r\n\r\n"
461+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
462+ exit(0);
463+}
464+
465+/* ------------------------------------------------------------------ */
466+/* Allowed roots */
467+/* */
468+/* Each root is stored TWICE where the two forms differ: the path the */
469+/* operator configured and its canonical realpath. That is what makes */
470+/* a configured /tmp work on macOS, where realpath answers /private/ */
471+/* tmp, and it is also what lets the UI show an operator whose root */
472+/* has drifted (a symlinked home, a mounted volume) before they file */
473+/* a bug about a tool that "cannot see my files". */
474+/* ------------------------------------------------------------------ */
475+
476+typedef struct {
477+ char configured[PATH_SZ];
478+ char canonical[PATH_SZ];
479+ int exists;
480+ int is_dir;
481+} root_t;
482+
483+static root_t g_roots[MAX_ROOTS];
484+static int g_root_count;
485+static int g_tool_off[TOOLS_N]; /* permissions: 1 = disabled */
486+static char g_roots_file[PATH_SZ];
487+
488+static int deny_count;
489+static char g_deny[MAX_ROOTS][PATH_SZ];
490+
491+/* Tool names in registration order - the same order tools/list reports. */
492+static const char *TOOL_NAMES[TOOLS_N] = {
493+ "read_text_file", "read_multiple_files", "write_file", "edit_file",
494+ "create_directory", "list_directory", "directory_tree", "move_file",
495+ "search_files", "get_file_info", "list_allowed_directories"
496+};
497+
498+static int tool_index(const char *name)
499+{
500+ int i;
501+ if (!name) return -1;
502+ for (i = 0; i < TOOLS_N; i++)
503+ if (strcmp(TOOL_NAMES[i], name) == 0) return i;
504+ return -1;
505+}
506+
507+/* ------------------------------------------------------------------ */
508+/* Path canonicalisation */
509+/* ------------------------------------------------------------------ */
510+
511+#if defined(_WIN32)
512+
513+static void win_norm(char *s)
514+{
515+ for (; *s; s++) {
516+ if (*s == '/') *s = '\\';
517+ *s = (char)tolower((unsigned char)*s);
518+ }
519+}
520+
521+static int path_under_p(const char *p, const char *root)
522+{
523+ char a[PATH_SZ], b[PATH_SZ];
524+ size_t n;
525+ str_copy(a, sizeof a, p);
526+ str_copy(b, sizeof b, root);
527+ win_norm(a);
528+ win_norm(b);
529+ n = strlen(b);
530+ while (n > 3 && b[n - 1] == '\\') b[--n] = '\0';
531+ if (strcmp(a, b) == 0) return 1;
532+ if (strncmp(a, b, n) == 0 && a[n] == '\\') return 1;
533+ return 0;
534+}
535+
536+#else /* POSIX */
537+
538+static int path_under_p(const char *p, const char *root)
539+{
540+ size_t n;
541+ if (!p || !root) return 0;
542+ n = strlen(root);
543+ if (strcmp(p, root) == 0) return 1;
544+ if (n && root[n - 1] == '/') return strncmp(p, root, n) == 0;
545+ if (n && strncmp(p, root, n) == 0 && p[n] == '/') return 1;
546+ return 0;
547+}
548+
549+#endif /* platform prefix check */
550+
551+/* Lexical normalisation only: no filesystem access, so it works for a path
552+ * that does not exist yet (write_file, create_directory). Because
553+ * path_shape_ok() has already rejected every ".." segment, collapsing
554+ * separators here cannot be used to walk out of anything. */
555+static int lexical_abs(const char *raw, char *out, size_t outsz)
556+{
557+ size_t i, o = 0;
558+ int last_sep = 1; /* the head counts as a sep */
559+
560+ if (!raw || !*raw) return 0;
561+#if defined(_WIN32)
562+ {
563+ char full[PATH_SZ];
564+ DWORD n = GetFullPathNameA(raw, (DWORD)sizeof full, full, NULL);
565+ if (n == 0 || n >= (DWORD)sizeof full) return 0;
566+ str_copy(out, outsz, full);
567+ rstrip_sep(out);
568+ return out[0] ? 1 : 0;
569+ }
570+#else
571+ if (raw[0] != '/') return 0;
572+ if (outsz < 2) return 0;
573+ out[o++] = '/'; /* absolute, always */
574+ for (i = 1; raw[i]; i++) {
575+ char c = raw[i];
576+ if (c == '\\') c = '/';
577+ if (c == '/') {
578+ if (last_sep) continue;
579+ if (o + 1 >= outsz) return 0;
580+ out[o++] = '/';
581+ last_sep = 1;
582+ /* collapse a "." segment: /a/./b behaves as /a/b */
583+ if (raw[i + 1] == '.' &&
584+ (raw[i + 2] == '/' || raw[i + 2] == '\\' || raw[i + 2] == '\0'))
585+ i++;
586+ continue;
587+ }
588+ if (o + 1 >= outsz) return 0;
589+ out[o++] = c;
590+ last_sep = 0;
591+ }
592+ if (o == 0) { out[0] = '/'; out[1] = '\0'; return 1; }
593+ while (o > 1 && out[o - 1] == '/') o--;
594+ out[o] = '\0';
595+ return 1;
596+#endif
597+}
598+
599+/* Lexical form, used when the target does not exist yet. */
600+static int norm_lex(const char *raw, char *out, size_t outsz)
601+{
602+ return lexical_abs(raw, out, outsz);
603+}
604+
605+/* Full canonicalisation: resolves every symlink that exists on disk. */
606+static int canon_path(const char *raw, char *out, size_t outsz)
607+{
608+#if defined(_WIN32)
609+ char full[PATH_SZ];
610+ HANDLE h;
611+ char final[PATH_SZ];
612+
613+ if (!lexical_abs(raw, full, sizeof full)) return 0;
614+ if (GetFileAttributesA(full) == INVALID_FILE_ATTRIBUTES) return 0;
615+ h = CreateFileA(full, 0,
616+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
617+ NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
618+ if (h != INVALID_HANDLE_VALUE) {
619+ DWORD fn = GetFinalPathNameByHandleA(h, final, (DWORD)sizeof final, 0);
620+ CloseHandle(h);
621+ if (fn > 0 && fn < (DWORD)sizeof final) {
622+ char *src = final;
623+ if (strncmp(src, "\\\\?\\", 4) == 0) src += 4;
624+ str_copy(out, outsz, src);
625+ return 1;
626+ }
627+ }
628+ str_copy(out, outsz, full);
629+ return 1;
630+#else
631+ char *r;
632+ char lex[PATH_SZ];
633+ struct stat lst;
634+ if (!lexical_abs(raw, lex, sizeof lex)) return 0;
635+ if (lstat(lex, &lst) != 0) return 0; /* nothing there to canonicalise */
636+ r = realpath(lex, NULL);
637+ if (!r) return 0;
638+ str_copy(out, outsz, r);
639+ free(r);
640+ return 1;
641+#endif
642+}
643+
644+/* Absolute-path shape check. Rejects NUL smuggling attempts, `..` anywhere,
645+ * and on POSIX anything not rooted at '/'. */
646+static int path_shape_ok(const char *raw)
647+{
648+ size_t i;
649+ if (!raw || !*raw) return 0;
650+ if (strlen(raw) >= PATH_SZ) return 0;
651+#if !defined(_WIN32)
652+ if (raw[0] != '/') return 0;
653+#else
654+ if (!(isalpha((unsigned char)raw[0]) && raw[1] == ':' &&
655+ (raw[2] == '\\' || raw[2] == '/'))) {
656+ if (raw[0] != '/' && raw[0] != '\\') return 0; /* UNC-ish: allowed */
657+ }
658+#endif
659+ for (i = 0; raw[i]; i++) {
660+ if ((unsigned char)raw[i] < 0x20) return 0; /* control bytes */
661+ }
662+ /* `..` is never a legitimate segment: a caller that means the parent
663+ * sends the parent's absolute path. Rejecting it outright also kills
664+ * %2e%2e and every other encoded variant after url_decode(). */
665+ for (i = 0; raw[i]; i++) {
666+ if (raw[i] != '.') continue;
667+ if (i > 0 && raw[i - 1] != '/' && raw[i - 1] != '\\') continue;
668+ if (raw[i + 1] == '.' && (raw[i + 2] == '/' || raw[i + 2] == '\\' ||
669+ raw[i + 2] == '\0')) return 0;
670+ }
671+ return 1;
672+}
673+
674+static int denied_path(const char *p)
675+{
676+ int i;
677+ for (i = 0; i < deny_count; i++)
678+ if (path_under_p(p, g_deny[i])) return 1;
679+#if !defined(_WIN32)
680+ {
681+ static const char *deny[] = { "/proc", "/sys", "/dev" };
682+ size_t k;
683+ for (k = 0; k < sizeof deny / sizeof deny[0]; k++)
684+ if (path_under_p(p, deny[k])) return 1;
685+ }
686+#else
687+ {
688+ /* Windows equivalents of "never go here": the registry hives and the
689+ * system volume shadow copies live under C:\Windows and C:\System
690+ * Volume Information, and a node's own plugin directory is where the
691+ * binaries the bot executes sit. */
692+ static const char *deny[] = {
693+ "C:\\Windows\\System32\\config",
694+ "C:\\System Volume Information"
695+ };
696+ size_t k;
697+ for (k = 0; k < sizeof deny / sizeof deny[0]; k++)
698+ if (path_under_p(p, deny[k])) return 1;
699+ }
700+#endif
701+ return 0;
702+}
703+
704+static int root_contains(const char *canon)
705+{
706+ int i;
707+ for (i = 0; i < g_root_count; i++) {
708+ if (path_under_p(canon, g_roots[i].canonical)) return i;
709+ if (g_roots[i].configured[0] &&
710+ path_under_p(canon, g_roots[i].configured)) return i;
711+ }
712+ return -1;
713+}
714+
715+static void parent_of(const char *canon, char *out, size_t outsz)
716+{
717+ size_t n;
718+ str_copy(out, outsz, canon);
719+ n = strlen(out);
720+ while (n > 1 && (out[n - 1] == '/' || out[n - 1] == '\\')) out[--n] = '\0';
721+#if defined(_WIN32)
722+ while (n > 3 && out[n - 1] != '\\' && out[n - 1] != '/') out[--n] = '\0';
723+ if (n > 3) out[--n] = '\0';
724+ else str_copy(out, outsz, canon);
725+#else
726+ while (n > 1 && out[n - 1] != '/') out[--n] = '\0';
727+ if (n > 1) out[--n] = '\0';
728+ if (!out[0]) str_copy(out, outsz, "/");
729+#endif
730+}
731+
732+/* Authorise one path for one mode.
733+ * mode 'r' - the entry must exist and be inside a root.
734+ * mode 'w' - the ENTRY may not exist yet, so its PARENT is the thing that
735+ * must exist and stay inside a root; a symlinked leaf that
736+ * points out of the sandbox is refused by re-checking the
737+ * canonical form of what is already on disk.
738+ * On failure returns 0 with a one-line reason in err (never a stack trace:
739+ * these strings are what the model reads to decide what to do next). */
740+static int resolve_allowed(const char *raw, char *out, size_t outsz,
741+ char mode, const char **err)
742+{
743+ char canon[PATH_SZ], parent[PATH_SZ];
744+
745+ if (!raw || !*raw) { *err = "path is empty"; return 0; }
746+ if (!path_shape_ok(raw)) {
747+ *err = "path must be absolute and must not contain '..'";
748+ return 0;
749+ }
750+ if (!canon_path(raw, canon, sizeof canon)) {
751+ if (mode == 'r') { *err = "path does not exist"; return 0; }
752+ /* The entry does not exist yet (write_file, create_directory): the
753+ * lexical form is what we can check, and the parent is what has to
754+ * really exist and stay inside a root. */
755+ if (!norm_lex(raw, canon, sizeof canon)) {
756+ *err = "path could not be normalised";
757+ return 0;
758+ }
759+ }
760+ if (denied_path(canon)) { *err = "path is on the deny list"; return 0; }
761+ if (root_contains(canon) < 0) {
762+ *err = "path is outside the allowed directories";
763+ return 0;
764+ }
765+ if (mode == 'w') {
766+ parent_of(canon, parent, sizeof parent);
767+ if (strcmp(parent, canon) != 0) {
768+ char pc[PATH_SZ];
769+ if (canon_path(parent, pc, sizeof pc)) {
770+ if (denied_path(pc)) { *err = "parent directory is denied"; return 0; }
771+ if (root_contains(pc) < 0) {
772+ *err = "parent directory is outside the allowed directories";
773+ return 0;
774+ }
775+ }
776+ }
777+ }
778+ str_copy(out, outsz, canon);
779+ return 1;
780+}
781+
782+/* ------------------------------------------------------------------ */
783+/* Config directory + roots.json */
784+/* ------------------------------------------------------------------ */
785+
786+/* State lives OUTSIDE the plugin binary path (connector spec §C.1) so it
787+ * survives reinstall and container restarts:
788+ * $FS_CONNECTORS_DIR/<id>/ (tests)
789+ * /workspace/.scorpiox/connectors/<id>/ (BotCloud containers)
790+ * ~/.scorpiox/connectors/<id>/ (POSIX)
791+ * %LOCALAPPDATA%\\scorpiox\\connectors\\<id>/ (Windows) */
792+#if defined(_WIN32)
793+static int is_dir_path(const char *p)
794+{
795+ DWORD att;
796+ if (!p || !*p) return 0;
797+ att = GetFileAttributesA(p);
798+ return (att != INVALID_FILE_ATTRIBUTES) && (att & FILE_ATTRIBUTE_DIRECTORY);
799+}
800+#else
801+static int is_dir_path(const char *p)
802+{
803+ struct stat st;
804+ if (!p || !*p) return 0;
805+ return (stat(p, &st) == 0) && S_ISDIR(st.st_mode);
806+}
807+#endif
808+
809+static void connectors_dir(char *out, size_t outsz)
810+{
811+ const char *env = getenv("FS_CONNECTORS_DIR");
812+ const char *home;
813+
814+ if (env && *env) {
815+ snprintf(out, outsz, "%s/%s", env, PLUGIN_ID);
816+ return;
817+ }
818+#if defined(_WIN32)
819+ home = getenv("LOCALAPPDATA");
820+ if (!home || !*home) home = getenv("USERPROFILE");
821+ if (home && *home) {
822+ snprintf(out, outsz, "%s\\scorpiox\\connectors\\%s", home, PLUGIN_ID);
823+ return;
824+ }
825+ snprintf(out, outsz, ".\\scorpiox-connectors\\%s", PLUGIN_ID);
826+#else
827+ if (is_dir_path("/workspace/.scorpiox")) {
828+ snprintf(out, outsz, "/workspace/.scorpiox/connectors/%s", PLUGIN_ID);
829+ return;
830+ }
831+ home = getenv("HOME");
832+ if (home && *home) {
833+ snprintf(out, outsz, "%s/.scorpiox/connectors/%s", home, PLUGIN_ID);
834+ return;
835+ }
836+ snprintf(out, outsz, "./.scorpiox-connectors/%s", PLUGIN_ID);
837+#endif
838+}
839+
840+/* mkdir -p, portable, mode 0700 (this directory holds operator config). */
841+static int mkpath(const char *path)
842+{
843+ char tmp[PATH_SZ];
844+ char *p;
845+ size_t n;
846+
847+ str_copy(tmp, sizeof tmp, path);
848+ n = strlen(tmp);
849+ while (n > 1 && (tmp[n - 1] == '/' || tmp[n - 1] == '\\')) tmp[--n] = '\0';
850+ for (p = tmp + 1; *p; p++) {
851+ if (*p != '/' && *p != '\\') continue;
852+ *p = '\0';
853+#if defined(_WIN32)
854+ _mkdir(tmp);
855+#else
856+ mkdir(tmp, 0700);
857+#endif
858+ *p = SEP;
859+ }
860+#if defined(_WIN32)
861+ if (_mkdir(tmp) == 0 || errno == EEXIST) return 0;
862+ return -1;
863+#else
864+ if (mkdir(tmp, 0700) == 0 || errno == EEXIST) return 0;
865+ return -1;
866+#endif
867+}
868+
869+static void add_root_raw(const char *configured)
870+{
871+ char canon[PATH_SZ];
872+ struct stat st;
873+ int i;
874+
875+ if (g_root_count >= MAX_ROOTS) return;
876+ if (!configured || !*configured) return;
877+
878+ /* Trim surrounding whitespace and any leftover shell quotes: an operator
879+ * who pastes "/data/reports " or '/data/reports' into roots.json means
880+ * the directory, not a name with a trailing space. */
881+ {
882+ char clean[PATH_SZ];
883+ size_t a = 0, b2 = strlen(configured);
884+ while (a < b2 && isspace((unsigned char)configured[a])) a++;
885+ while (b2 > a && isspace((unsigned char)configured[b2 - 1])) b2--;
886+ if (b2 - a >= 2 && ((configured[a] == '"' && configured[b2 - 1] == '"') ||
887+ (configured[a] == '\'' && configured[b2 - 1] == '\''))) {
888+ a++; b2--;
889+ }
890+ if (b2 <= a) return;
891+ if (b2 - a >= PATH_SZ) return;
892+ memcpy(clean, configured + a, b2 - a);
893+ clean[b2 - a] = '\0';
894+ if (!path_shape_ok(clean)) return;
895+ if (!canon_path(clean, canon, sizeof canon)) return;
896+ if (denied_path(canon)) return;
897+ }
898+ for (i = 0; i < g_root_count; i++)
899+ if (strcmp(g_roots[i].canonical, canon) == 0) return;
900+
901+ str_copy(g_roots[g_root_count].configured, PATH_SZ, configured);
902+ str_copy(g_roots[g_root_count].canonical, PATH_SZ, canon);
903+#if defined(_WIN32)
904+ {
905+ DWORD att = GetFileAttributesA(canon);
906+ g_roots[g_root_count].exists = (att != INVALID_FILE_ATTRIBUTES);
907+ g_roots[g_root_count].is_dir = (att != INVALID_FILE_ATTRIBUTES) &&
908+ (att & FILE_ATTRIBUTE_DIRECTORY);
909+ }
910+#else
911+ st.st_mode = 0;
912+ g_roots[g_root_count].exists = (stat(canon, &st) == 0);
913+ g_roots[g_root_count].is_dir = S_ISDIR(st.st_mode);
914+#endif
915+ g_root_count++;
916+}
917+
918+static void add_deny(const char *p)
919+{
920+ char canon[PATH_SZ];
921+ int i;
922+ if (deny_count >= MAX_ROOTS) return;
923+ if (!p || !*p) return;
924+ if (!path_shape_ok(p)) return;
925+ if (!canon_path(p, canon, sizeof canon)) str_copy(canon, sizeof canon, p);
926+ for (i = 0; i < deny_count; i++)
927+ if (strcmp(g_deny[i], canon) == 0) return;
928+ str_copy(g_deny[deny_count++], PATH_SZ, canon);
929+}
930+
931+/* roots.json: {"roots":["/data","/srv"],"denied":["/data/secret"],
932+ * "permissions":{"write_file":false,...}}
933+ * A missing or unreadable file is not an error - the defaults below apply. */
934+static int load_roots_file(void)
935+{
936+ FILE *f;
937+ long sz;
938+ char *txt;
939+ yyjson_doc *doc;
940+ yyjson_val *root, *arr, *perm, *it;
941+ size_t i, max;
942+ int loaded = 0;
943+
944+ if (!g_roots_file[0]) {
945+ char dir[PATH_SZ];
946+ connectors_dir(dir, sizeof dir);
947+ snprintf(g_roots_file, sizeof g_roots_file, "%s", dir);
948+ if (g_roots_file[0]) {
949+ size_t dl = strlen(g_roots_file);
950+ if (dl + 12 < sizeof g_roots_file) {
951+ g_roots_file[dl] = SEP;
952+ g_roots_file[dl + 1] = '\0';
953+ str_copy(g_roots_file + dl + 1, sizeof g_roots_file - dl - 1, "roots.json");
954+ }
955+ }
956+ }
957+
958+ f = fopen(g_roots_file, "rb");
959+ if (!f) return 0;
960+ if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return 0; }
961+ sz = ftell(f);
962+ if (sz < 0 || (size_t)sz > 256 * 1024) { fclose(f); return 0; }
963+ rewind(f);
964+ txt = (char *)malloc((size_t)sz + 1);
965+ if (!txt) { fclose(f); return 0; }
966+ if (fread(txt, 1, (size_t)sz, f) != (size_t)sz) {
967+ free(txt);
968+ fclose(f);
969+ return 0;
970+ }
971+ txt[sz] = '\0';
972+ fclose(f);
973+
974+ doc = yyjson_read(txt, (size_t)sz, 0);
975+ free(txt);
976+ if (!doc) return 0;
977+ root = yyjson_doc_get_root(doc);
978+ if (!yyjson_is_obj(root)) { yyjson_doc_free(doc); return 0; }
979+
980+ arr = yyjson_obj_get(root, "roots");
981+ if (yyjson_is_arr(arr)) {
982+ max = yyjson_arr_size(arr);
983+ for (i = 0; i < max; i++) {
984+ it = yyjson_arr_get(arr, i);
985+ if (yyjson_is_str(it)) { add_root_raw(yyjson_get_str(it)); loaded = 1; }
986+ }
987+ }
988+ arr = yyjson_obj_get(root, "denied");
989+ if (yyjson_is_arr(arr)) {
990+ max = yyjson_arr_size(arr);
991+ for (i = 0; i < max; i++) {
992+ it = yyjson_arr_get(arr, i);
993+ if (yyjson_is_str(it)) add_deny(yyjson_get_str(it));
994+ }
995+ }
996+ perm = yyjson_obj_get(root, "permissions");
997+ if (yyjson_is_obj(perm)) {
998+ for (i = 0; i < (size_t)TOOLS_N; i++) {
999+ yyjson_val *v = yyjson_obj_get(perm, TOOL_NAMES[i]);
1000+ if (v && yyjson_is_bool(v) && !yyjson_get_bool(v)) g_tool_off[i] = 1;
1001+ }
1002+ loaded = 1;
1003+ }
1004+ yyjson_doc_free(doc);
1005+ return loaded;
1006+}
1007+
1008+static void init_roots(void)
1009+{
1010+ const char *extra;
1011+ const char *home;
1012+
1013+ if (g_root_count) return;
1014+
1015+ /* 1. $FS_ALLOWED_ROOTS always wins - tests and one-shot operator overrides
1016+ * must not need a file, and a connector that cannot be pointed at a
1017+ * fixture tree cannot be tested at all. */
1018+ extra = getenv("FS_ALLOWED_ROOTS");
1019+ if (extra && *extra) {
1020+ char copy[PATH_SZ];
1021+ char *tok;
1022+ char delim;
1023+#if defined(_WIN32)
1024+ delim = ';'; /* ':' is drive syntax on NT */
1025+#else
1026+ delim = ':';
1027+#endif
1028+ str_copy(copy, sizeof copy, extra);
1029+ tok = copy;
1030+ while (tok && *tok) {
1031+ char *nx = strchr(tok, delim);
1032+ if (nx) *nx++ = '\0';
1033+ add_root_raw(tok);
1034+ tok = nx;
1035+ }
1036+ if (g_root_count) return;
1037+ }
1038+
1039+ /* 2. operator config */
1040+ if (load_roots_file() && g_root_count) return;
1041+
1042+ /* 3. defaults: the two places a node actually keeps user files. */
1043+#if defined(_WIN32)
1044+ home = getenv("USERPROFILE");
1045+ if (home && *home) add_root_raw(home);
1046+ {
1047+ const char *d = getenv("DRIVE");
1048+ char buf[PATH_SZ];
1049+ if (d && *d) { snprintf(buf, sizeof buf, "%s:\\codebases", d); add_root_raw(buf); }
1050+ add_root_raw("D:\\codebases");
1051+ }
1052+#else
1053+ if (is_dir_path("/workspace")) add_root_raw("/workspace");
1054+ home = getenv("HOME");
1055+ if (home && *home) add_root_raw(home);
1056+ if (g_root_count == 0) add_root_raw("/tmp"); /* last resort, still scoped */
1057+#endif
1058+}
1059+
1060+/* ------------------------------------------------------------------ */
1061+/* Filesystem primitives */
1062+/* ------------------------------------------------------------------ */
1063+
1064+static int is_regular(const char *p)
1065+{
1066+#if defined(_WIN32)
1067+ DWORD att = GetFileAttributesA(p);
1068+ if (att == INVALID_FILE_ATTRIBUTES) return 0;
1069+ return !(att & FILE_ATTRIBUTE_DIRECTORY);
1070+#else
1071+ struct stat st;
1072+ if (lstat(p, &st) != 0) return 0;
1073+ return S_ISREG(st.st_mode);
1074+#endif
1075+}
1076+
1077+static int is_link_path(const char *p)
1078+{
1079+#if defined(_WIN32)
1080+ DWORD att = GetFileAttributesA(p);
1081+ return (att != INVALID_FILE_ATTRIBUTES) && (att & FILE_ATTRIBUTE_REPARSE_POINT);
1082+#else
1083+ struct stat st;
1084+ return (lstat(p, &st) == 0) && S_ISLNK(st.st_mode);
1085+#endif
1086+}
1087+
1088+static long long file_size(const char *p)
1089+{
1090+#if defined(_WIN32)
1091+ WIN32_FILE_ATTRIBUTE_DATA d;
1092+ LARGE_INTEGER li;
1093+ if (!GetFileAttributesExA(p, GetFileExInfoStandard, &d)) return -1;
1094+ li.HighPart = d.nFileSizeHigh;
1095+ li.LowPart = d.nFileSizeLow;
1096+ return (long long)li.QuadPart;
1097+#else
1098+ struct stat st;
1099+ if (stat(p, &st) != 0) return -1;
1100+ return (long long)st.st_size;
1101+#endif
1102+}
1103+
1104+static long long file_mtime(const char *p)
1105+{
1106+#if defined(_WIN32)
1107+ WIN32_FILE_ATTRIBUTE_DATA d;
1108+ FILETIME ft;
1109+ ULARGE_INTEGER u;
1110+ if (!GetFileAttributesExA(p, GetFileExInfoStandard, &d)) return 0;
1111+ ft = d.ftLastWriteTime;
1112+ u.LowPart = ft.dwLowDateTime;
1113+ u.HighPart = ft.dwHighDateTime;
1114+ return (long long)(u.QuadPart / 10000000ULL - 11644473600ULL);
1115+#else
1116+ struct stat st;
1117+ if (stat(p, &st) != 0) return 0;
1118+ return (long long)st.st_mtime;
1119+#endif
1120+}
1121+
1122+static unsigned file_mode(const char *p)
1123+{
1124+#if defined(_WIN32)
1125+ DWORD att = GetFileAttributesA(p);
1126+ unsigned m = 0;
1127+ if (att == INVALID_FILE_ATTRIBUTES) return 0;
1128+ m |= 0700;
1129+ if (!(att & FILE_ATTRIBUTE_READONLY)) m |= 0222;
1130+ if (att & FILE_ATTRIBUTE_DIRECTORY) m |= 0111;
1131+ return m;
1132+#else
1133+ struct stat st;
1134+ if (stat(p, &st) != 0) return 0;
1135+ return (unsigned)(st.st_mode & 07777);
1136+#endif
1137+}
1138+
1139+/* Read the whole file (capped) into b. Sets *binary when a NUL shows up in
1140+ * the first BIN_PROBE bytes - the same probe the read-only browser uses, so
1141+ * both plugins agree on what "binary" means on this node. */
1142+static int read_whole(const char *path, buf_t *b, size_t cap, int *binary,
1143+ const char **err)
1144+{
1145+ FILE *f;
1146+ long long sz;
1147+ char chunk[IO_CHUNK];
1148+ size_t total = 0;
1149+ int probed = 0;
1150+
1151+ if (binary) *binary = 0;
1152+ sz = file_size(path);
1153+ if (sz < 0) { *err = "cannot stat file"; return 0; }
1154+ if ((size_t)sz > cap) { *err = "file is larger than the read limit"; return 0; }
1155+
1156+ f = fopen(path, "rb");
1157+ if (!f) {
1158+ *err = (errno == EACCES) ? "permission denied" : "cannot open file";
1159+ return 0;
1160+ }
1161+ for (;;) {
1162+ size_t n = fread(chunk, 1, sizeof chunk, f);
1163+ if (n == 0) break;
1164+ if (!binary) {
1165+ /* fall through */
1166+ } else if (!probed) {
1167+ size_t i, stop = n < BIN_PROBE ? n : BIN_PROBE;
1168+ for (i = 0; i < stop; i++)
1169+ if (chunk[i] == '\0') { *binary = 1; break; }
1170+ if (total + n >= BIN_PROBE) probed = 1;
1171+ }
1172+ buf_add(b, chunk, n);
1173+ total += n;
1174+ if (total > cap) {
1175+ fclose(f);
1176+ *err = "file is larger than the read limit";
1177+ return 0;
1178+ }
1179+ }
1180+ fclose(f);
1181+ if (binary && !probed) {
1182+ /* small file: probe what we have */
1183+ size_t i, stop = b->n < BIN_PROBE ? b->n : BIN_PROBE;
1184+ for (i = 0; i < stop; i++)
1185+ if (b->p && b->p[i] == '\0') { *binary = 1; break; }
1186+ }
1187+ *err = NULL;
1188+ return 1;
1189+}
1190+
1191+/* First n lines, joined with a single \n and with no trailing newline -
1192+ * the same shape upstream headFile returns, so a caller that counts
1193+ * newlines counts lines and not an extra blank one. */
1194+static void text_head(const char *s, size_t len, long n, buf_t *out)
1195+{
1196+ size_t i = 0;
1197+ long lines = 0;
1198+ if (n < 0) { buf_add(out, s, len); return; }
1199+ if (n == 0) return;
1200+ while (i < len && lines < n) {
1201+ size_t start = i, e = i;
1202+ while (e < len && s[e] != '\n') e++;
1203+ if (lines) buf_putc(out, '\n');
1204+ if (e > start && s[e - 1] == '\r') e--; /* CRLF normalised */
1205+ buf_add(out, s + start, e - start);
1206+ lines++;
1207+ i = (e < len) ? e + 1 : len;
1208+ }
1209+}
1210+
1211+/* Last n lines. A trailing newline ends the last line rather than starting an
1212+ * empty one, so "a\nb\n" with tail=1 is "b\n" - the same reading the upstream
1213+ * tailFile takes, and the one that stops an off-by-one from appearing as
1214+ * "tail 1 gave me a blank line". */
1215+static void text_tail(const char *s, size_t len, long n, buf_t *out)
1216+{
1217+ size_t end = len;
1218+ long lines = 0;
1219+ size_t i;
1220+
1221+ if (n < 0) { buf_add(out, s, len); return; }
1222+ if (n == 0 || len == 0) return;
1223+ while (end > 0 && (s[end - 1] == '\n' || s[end - 1] == '\r')) end--;
1224+ if (end == 0) return;
1225+ for (i = end; i > 0; ) {
1226+ i--;
1227+ if (s[i] == '\n') {
1228+ lines++;
1229+ if (lines >= n) { i++; break; }
1230+ }
1231+ }
1232+ buf_add(out, s + i, end - i);
1233+}
1234+
1235+/* Write content atomically: write to <path>.tmp-<pid>, flush to disk, then
1236+ * rename over the target. A crash mid-write therefore leaves either the old
1237+ * file or the new one, never a half-written file - which matters because the
1238+ * whole point of this connector is that an agent edits files unattended. */
1239+static int write_atomic(const char *path, const char *content, size_t len,
1240+ const char **err)
1241+{
1242+ char tmp[PATH_SZ];
1243+ FILE *f;
1244+ int rc = 0;
1245+
1246+ snprintf(tmp, sizeof tmp, "%s.tmp-%ld", path, (long)
1247+#if defined(_WIN32)
1248+ GetCurrentProcessId()
1249+#else
1250+ (long)getpid()
1251+#endif
1252+ );
1253+ f = fopen(tmp, "wb");
1254+ if (!f) { *err = "cannot create temporary file"; return 0; }
1255+ if (len && fwrite(content, 1, len, f) != len) {
1256+ fclose(f);
1257+#if !defined(_WIN32)
1258+ remove(tmp);
1259+#else
1260+ DeleteFileA(tmp);
1261+#endif
1262+ *err = "write failed (disk full?)";
1263+ return 0;
1264+ }
1265+ if (fflush(f) != 0) { fclose(f); rc = 0; *err = "flush failed"; }
1266+ else {
1267+#if !defined(_WIN32)
1268+ fflush(f);
1269+ fsync(fileno(f));
1270+#endif
1271+ fclose(f);
1272+ rc = 1;
1273+ }
1274+ if (!rc) return 0;
1275+
1276+#if defined(_WIN32)
1277+ /* Windows rename() refuses to replace an existing file. */
1278+ {
1279+ char bak[PATH_SZ];
1280+ snprintf(bak, sizeof bak, "%s.bak-%ld", path, (long)GetCurrentProcessId());
1281+ MoveFileExA(tmp, path, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH);
1282+ if (GetFileAttributesA(tmp) != INVALID_FILE_ATTRIBUTES) {
1283+ /* fallback: copy over then delete the temp */
1284+ CopyFileA(tmp, path, FALSE);
1285+ DeleteFileA(tmp);
1286+ (void)bak;
1287+ }
1288+ if (GetFileAttributesA(path) == INVALID_FILE_ATTRIBUTES) {
1289+ *err = "rename failed";
1290+ return 0;
1291+ }
1292+ }
1293+#else
1294+ if (rename(tmp, path) != 0) {
1295+ remove(tmp);
1296+ *err = "rename failed";
1297+ return 0;
1298+ }
1299+#endif
1300+ *err = NULL;
1301+ return 1;
1302+}
1303+
1304+static int ensure_parent(const char *path)
1305+{
1306+ char parent[PATH_SZ];
1307+ parent_of(path, parent, sizeof parent);
1308+ if (strcmp(parent, path) == 0) return 0;
1309+ return mkpath(parent);
1310+}
1311+
1312+static int mkdir_p(const char *path)
1313+{
1314+ return mkpath(path);
1315+}
1316+
1317+static int copy_file(const char *src, const char *dst, const char **err)
1318+{
1319+ FILE *in, *out;
1320+ char chunk[IO_CHUNK];
1321+ size_t n;
1322+
1323+ in = fopen(src, "rb");
1324+ if (!in) { *err = "cannot open source"; return 0; }
1325+ if (ensure_parent(dst) != 0) { fclose(in); *err = "cannot create destination directory"; return 0; }
1326+ out = fopen(dst, "wb");
1327+ if (!out) { fclose(in); *err = "cannot create destination"; return 0; }
1328+ while ((n = fread(chunk, 1, sizeof chunk, in)) > 0) {
1329+ if (fwrite(chunk, 1, n, out) != n) {
1330+ fclose(in);
1331+ fclose(out);
1332+ *err = "copy failed (disk full?)";
1333+ return 0;
1334+ }
1335+ }
1336+ if (ferror(in)) { fclose(in); fclose(out); *err = "read error"; return 0; }
1337+ fclose(in);
1338+ if (fflush(out) != 0) { fclose(out); *err = "flush failed"; return 0; }
1339+ fclose(out);
1340+ *err = NULL;
1341+ return 1;
1342+}
1343+
1344+/* ------------------------------------------------------------------ */
1345+/* Glob matching */
1346+/* */
1347+/* search_files and excludePatterns need minimatch's useful subset with */
1348+/* no dependency: '*' and '?' within one path segment, '**' across */
1349+/* segments, and brace-free patterns. A pattern with no separator is */
1350+/* matched against the file NAME as well as the relative path, which is */
1351+/* what makes "*.log" behave like a person expects. */
1352+/* ------------------------------------------------------------------ */
1353+
1354+static int glob_here(const char *pat, const char *s, int slash_means_end)
1355+{
1356+ while (*pat) {
1357+ if (pat[0] == '*' && pat[1] == '*') {
1358+ const char *p2 = pat + 2;
1359+ if (*p2 == '/') p2++;
1360+ if (!*p2) return 1; /* ** matches rest */
1361+ for (;;) {
1362+ if (glob_here(p2, s, 0)) return 1;
1363+ while (*s && *s != '/') s++;
1364+ if (*s == '/') s++;
1365+ else break;
1366+ }
1367+ return 0;
1368+ }
1369+ if (*pat == '*') {
1370+ const char *p2 = pat + 1;
1371+ if (slash_means_end) {
1372+ for (;;) {
1373+ if (glob_here(p2, s, slash_means_end)) return 1;
1374+ if (*s == '/' || *s == '\\') return 0;
1375+ if (!*s) return 0;
1376+ s++;
1377+ }
1378+ }
1379+ for (;;) {
1380+ if (glob_here(p2, s, slash_means_end)) return 1;
1381+ if (!*s) return 0;
1382+ s++;
1383+ }
1384+ }
1385+ if (*pat == '?') {
1386+ if (!*s || *s == '/') return 0;
1387+ pat++;
1388+ s++;
1389+ continue;
1390+ }
1391+ if (*pat != *s) return 0;
1392+ pat++;
1393+ s++;
1394+ }
1395+ return *s == '\0';
1396+}
1397+
1398+static int glob_match(const char *pat, const char *s)
1399+{
1400+ if (!pat || !s) return 0;
1401+ return glob_here(pat, s, 1);
1402+}
1403+
1404+/* Excludes follow upstream isExcludedPath: a pattern with a star is matched
1405+ * on the relative path (and a trailing double-star-slash also matches the
1406+ * directory itself); a plain name matches at any depth. */
1407+static int is_excluded(const char *relpath, int is_dir, yyjson_val *excludes)
1408+{
1409+ size_t i, max;
1410+ if (!excludes || !yyjson_is_arr(excludes)) return 0;
1411+ max = yyjson_arr_size(excludes);
1412+ for (i = 0; i < max; i++) {
1413+ yyjson_val *v = yyjson_arr_get(excludes, i);
1414+ const char *pat;
1415+ char buf[NAME_SZ * 4];
1416+ if (!yyjson_is_str(v)) continue;
1417+ pat = yyjson_get_str(v);
1418+ if (!pat || !*pat) continue;
1419+ if (strchr(pat, '*')) {
1420+ if (glob_match(pat, relpath)) return 1;
1421+ {
1422+ size_t pl = strlen(pat);
1423+ if (pl > 3 && !strcmp(pat + pl - 3, "/**")) {
1424+ char cut[NAME_SZ * 4];
1425+ str_copy(cut, sizeof cut, pat);
1426+ cut[pl - 3] = '\0';
1427+ if (is_dir && glob_match(cut, relpath)) return 1;
1428+ }
1429+ }
1430+ continue;
1431+ }
1432+ if (glob_match(pat, relpath)) return 1;
1433+ snprintf(buf, sizeof buf, "**/%s", pat);
1434+ if (glob_match(buf, relpath)) return 1;
1435+ if (is_dir) {
1436+ snprintf(buf, sizeof buf, "**/%s/**", pat);
1437+ if (glob_match(buf, relpath)) return 1;
1438+ }
1439+ }
1440+ return 0;
1441+}
1442+
1443+/* ------------------------------------------------------------------ */
1444+/* Unified diff (enough of it to read like git's) */
1445+/* ------------------------------------------------------------------ */
1446+
1447+typedef struct {
1448+ char **line;
1449+ size_t n;
1450+} lines_t;
1451+
1452+static void lines_split(const char *s, size_t len, lines_t *out)
1453+{
1454+ size_t cap = 64, n = 0, start = 0, i;
1455+ char **v = (char **)malloc(cap * sizeof *v);
1456+ out->line = NULL;
1457+ out->n = 0;
1458+ if (!v) return;
1459+ for (i = 0; i <= len; i++) {
1460+ if (i == len || s[i] == '\n') {
1461+ size_t sl = i - start;
1462+ char *ln;
1463+ if (sl && s[start + sl - 1] == '\r') sl--; /* compare LF-only */
1464+ ln = (char *)malloc(sl + 1);
1465+ if (!ln) break;
1466+ memcpy(ln, s + start, sl);
1467+ ln[sl] = '\0';
1468+ if (n == cap) {
1469+ char **nv;
1470+ cap *= 2;
1471+ nv = (char **)realloc(v, cap * sizeof *v);
1472+ if (!nv) { free(ln); break; }
1473+ v = nv;
1474+ }
1475+ v[n++] = ln;
1476+ start = i + 1;
1477+ if (i == len) break;
1478+ }
1479+ }
1480+ out->line = v;
1481+ out->n = n;
1482+}
1483+
1484+static void lines_free(lines_t *l)
1485+{
1486+ size_t i;
1487+ for (i = 0; i < l->n; i++) free(l->line[i]);
1488+ free(l->line);
1489+ l->line = NULL;
1490+ l->n = 0;
1491+}
1492+
1493+/* Append one @@ hunk with its context. */
1494+static void diff_hunk(buf_t *out, lines_t *a, lines_t *b,
1495+ size_t a0, size_t a1, size_t b0, size_t b1)
1496+{
1497+ size_t i;
1498+ if (a1 > a0 || b1 > b0) {
1499+ buf_printf(out, "@@ -%u,%u +%u,%u @@\n",
1500+ (unsigned)(a0 + 1), (unsigned)(a1 - a0),
1501+ (unsigned)(b0 + 1), (unsigned)(b1 - b0));
1502+ for (i = a0; i < a1; i++) { buf_putc(out, '-'); buf_puts(out, a->line[i]); buf_putc(out, '\n'); }
1503+ for (i = b0; i < b1; i++) { buf_putc(out, '+'); buf_puts(out, b->line[i]); buf_putc(out, '\n'); }
1504+ }
1505+}
1506+
1507+/* A deliberately simple LCS-free diff: match the common prefix and suffix,
1508+ * then report the middle as one remove/add pair. Real git diffs of agent
1509+ * edits are almost always local, and a wrong-but-labelled diff is worse than
1510+ * a coarse honest one, so nothing here pretends to be Myers. */
1511+static void make_diff(buf_t *out, const char *an, size_t alen,
1512+ const char *bn, size_t blen, const char *name)
1513+{
1514+ lines_t a, b;
1515+ size_t pre = 0, suf = 0;
1516+
1517+ lines_split(an, alen, &a);
1518+ lines_split(bn, blen, &b);
1519+ while (pre < a.n && pre < b.n && !strcmp(a.line[pre], b.line[pre])) pre++;
1520+ while (suf + pre < a.n && suf + pre < b.n &&
1521+ !strcmp(a.line[a.n - 1 - suf], b.line[b.n - 1 - suf])) suf++;
1522+
1523+ buf_printf(out, "--- %s\n+++ %s\n", name, name);
1524+ if (a.n == b.n && pre == a.n) {
1525+ buf_puts(out, "(no changes)\n");
1526+ } else {
1527+ diff_hunk(out, &a, &b, pre, a.n - suf, pre, b.n - suf);
1528+ }
1529+ lines_free(&a);
1530+ lines_free(&b);
1531+}
1532+
1533+/* ------------------------------------------------------------------ */
1534+/* Directory helpers */
1535+/* ------------------------------------------------------------------ */
1536+
1537+typedef struct {
1538+ char name[NAME_SZ];
1539+ int is_dir;
1540+ int is_link;
1541+ long long size;
1542+ long long mtime;
1543+} dent_t;
1544+
1545+static int cmp_dent(const void *x, const void *y)
1546+{
1547+ const dent_t *a = (const dent_t *)x, *b = (const dent_t *)y;
1548+ if (a->is_dir != b->is_dir) return a->is_dir ? -1 : 1; /* dirs first */
1549+ return strcmp(a->name, b->name);
1550+}
1551+
1552+/* Read one directory, sorted, capped. Returns count or -1. */
1553+static long list_dir(const char *path, dent_t **out, const char **err)
1554+{
1555+ dent_t *v = NULL;
1556+ long n = 0, cap = 0;
1557+#if !defined(_WIN32)
1558+ DIR *d;
1559+ struct dirent *de;
1560+ d = opendir(path);
1561+ if (!d) {
1562+ *err = (errno == EACCES) ? "permission denied" :
1563+ (errno == ENOENT) ? "path does not exist" : "cannot read directory";
1564+ return -1;
1565+ }
1566+ while ((de = readdir(d)) != NULL) {
1567+ char full[PATH_SZ];
1568+ dent_t e;
1569+ if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue;
1570+ if (n == cap) {
1571+ dent_t *nv;
1572+ cap = cap ? cap * 2 : 128;
1573+ if (cap > MAX_ENTRIES) cap = MAX_ENTRIES;
1574+ nv = (dent_t *)realloc(v, (size_t)cap * sizeof *v);
1575+ if (!nv) break;
1576+ v = nv;
1577+ }
1578+ if (n >= MAX_ENTRIES) break;
1579+ memset(&e, 0, sizeof e);
1580+ str_copy(e.name, sizeof e.name, de->d_name);
1581+ path_join(full, sizeof full, path, de->d_name);
1582+ e.is_link = is_link_path(full);
1583+ e.is_dir = is_dir_path(full);
1584+ e.size = e.is_dir ? 0 : file_size(full);
1585+ e.mtime = file_mtime(full);
1586+ v[n++] = e;
1587+ }
1588+ closedir(d);
1589+#else
1590+ WIN32_FIND_DATAA fd;
1591+ HANDLE h;
1592+ char pat[PATH_SZ];
1593+ snprintf(pat, sizeof pat, "%s\\*", path);
1594+ h = FindFirstFileA(pat, &fd);
1595+ if (h == INVALID_HANDLE_VALUE) {
1596+ *err = "cannot read directory";
1597+ return -1;
1598+ }
1599+ do {
1600+ char full[PATH_SZ];
1601+ dent_t e;
1602+ if (!strcmp(fd.cFileName, ".") || !strcmp(fd.cFileName, "..")) continue;
1603+ if (n == cap) {
1604+ dent_t *nv;
1605+ cap = cap ? cap * 2 : 128;
1606+ if (cap > MAX_ENTRIES) cap = MAX_ENTRIES;
1607+ nv = (dent_t *)realloc(v, (size_t)cap * sizeof *v);
1608+ if (!nv) break;
1609+ v = nv;
1610+ }
1611+ if (n >= MAX_ENTRIES) break;
1612+ memset(&e, 0, sizeof e);
1613+ str_copy(e.name, sizeof e.name, fd.cFileName);
1614+ path_join(full, sizeof full, path, fd.cFileName);
1615+ e.is_link = (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
1616+ e.is_dir = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
1617+ {
1618+ ULARGE_INTEGER u;
1619+ u.LowPart = fd.nFileSizeLow;
1620+ u.HighPart = fd.nFileSizeHigh;
1621+ e.size = e.is_dir ? 0 : (long long)u.QuadPart;
1622+ }
1623+ {
1624+ ULARGE_INTEGER u;
1625+ u.LowPart = fd.ftLastWriteTime.dwLowDateTime;
1626+ u.HighPart = fd.ftLastWriteTime.dwHighDateTime;
1627+ e.mtime = (long long)(u.QuadPart / 10000000ULL - 11644473600ULL);
1628+ }
1629+ v[n++] = e;
1630+ } while (FindNextFileA(h, &fd));
1631+ FindClose(h);
1632+#endif
1633+ if (n > 1) qsort(v, (size_t)n, sizeof *v, cmp_dent);
1634+ *out = v;
1635+ *err = NULL;
1636+ return n;
1637+}
1638+
1639+/* ------------------------------------------------------------------ */
1640+/* MCP tools */
1641+/* */
1642+/* Each handler appends either the result text or a one-line reason to */
1643+/* *text and returns 0 (result) or 1 (isError). The dispatcher wraps */
1644+/* the text into {"content":[{"type":"text","text":...}],"isError":b}, */
1645+/* which is exactly what scorpiox-connector-mcp relays upstream. */
1646+/* */
1647+/* Error text is written for the MODEL, not for a log: it names the */
1648+/* path, says which rule refused it, and (where there is one) what to */
1649+/* do instead. "permission denied" alone sends an agent in circles. */
1650+/* ------------------------------------------------------------------ */
1651+
1652+typedef int (*tool_fn)(yyjson_val *args, buf_t *text);
1653+
1654+/* Refuse the "binary" case in a way that tells the caller what to use. */
1655+#define BINARY_HINT "file contains binary bytes; read_text_file returns text only - use get_file_info for metadata, or the files plugin to view it"
1656+
1657+static int tool_read_text_file(yyjson_val *args, buf_t *text)
1658+{
1659+ char raw[PATH_SZ], canon[PATH_SZ];
1660+ const char *err = NULL;
1661+ buf_t b;
1662+ int have_head = 0, have_tail = 0;
1663+ long head = -1, tail = -1;
1664+ int binary = 0;
1665+
1666+ if (!ju_field_str(args, "path", raw, sizeof raw))
1667+ return (buf_puts(text, "missing required parameter \"path\""), 1);
1668+ if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err))
1669+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
1670+ if (!is_regular(canon))
1671+ return (buf_printf(text, "%s: not a regular file", raw), 1);
1672+
1673+ head = ju_int(args, "head", -1, &have_head);
1674+ tail = ju_int(args, "tail", -1, &have_tail);
1675+ if (head < -1 || tail < -1)
1676+ return (buf_puts(text, "head and tail must be non-negative integers"), 1);
1677+
1678+ buf_init(&b);
1679+ if (!read_whole(canon, &b, READ_CAP, &binary, &err)) {
1680+ buf_printf(text, "%s: %s", raw, err ? err : "read failed");
1681+ buf_free(&b);
1682+ return 1;
1683+ }
1684+ if (binary) {
1685+ buf_printf(text, "%s: " BINARY_HINT, raw);
1686+ buf_free(&b);
1687+ return 1;
1688+ }
1689+ if (have_head && have_tail) {
1690+ buf_puts(text, "head and tail are mutually exclusive - send one or the other");
1691+ buf_free(&b);
1692+ return 1;
1693+ }
1694+ if (have_head) text_head(b.p ? b.p : "", b.n, head, text);
1695+ else if (have_tail) text_tail(b.p ? b.p : "", b.n, tail, text);
1696+ else buf_add(text, b.p ? b.p : "", b.n);
1697+ buf_free(&b);
1698+ return 0;
1699+}
1700+
1701+/* One element of read_multiple_files. Kept as a function so the loop that
1702+ * drives it stays readable. */
1703+static void read_one_path(const char *path, buf_t *out, int *first)
1704+{
1705+ char canon[PATH_SZ];
1706+ const char *err = NULL;
1707+ buf_t b;
1708+ int binary = 0;
1709+
1710+ /* each item below terminates with its own newline, so the separator is
1711+ * "---
1712+" and not "
1713+---
1714+" - that is what makes the output byte-split
1715+ * on a line of three dashes, exactly like upstream */
1716+ if (!*first) buf_puts(out, "---\n");
1717+ *first = 0;
1718+
1719+ if (!resolve_allowed(path, canon, sizeof canon, 'r', &err)) {
1720+ buf_printf(out, "%s: Error - %s\n", path, err ? err : "refused");
1721+ return;
1722+ }
1723+ if (!is_regular(canon)) {
1724+ buf_printf(out, "%s: Error - not a regular file\n", path);
1725+ return;
1726+ }
1727+ buf_init(&b);
1728+ if (!read_whole(canon, &b, READ_CAP, &binary, &err)) {
1729+ buf_printf(out, "%s: Error - %s\n", path, err ? err : "read failed");
1730+ buf_free(&b);
1731+ return;
1732+ }
1733+ if (binary) {
1734+ buf_printf(out, "%s: Error - binary file\n", path);
1735+ buf_free(&b);
1736+ return;
1737+ }
1738+ buf_printf(out, "%s:\n", path);
1739+ buf_add(out, b.p ? b.p : "", b.n);
1740+ buf_putc(out, '\n');
1741+ buf_free(&b);
1742+}
1743+
1744+static int tool_read_multiple_files(yyjson_val *args, buf_t *text)
1745+{
1746+ yyjson_val *arr = args ? yyjson_obj_get(args, "paths") : NULL;
1747+ size_t i, max;
1748+ int first = 1;
1749+
1750+ if (!arr || !yyjson_is_arr(arr) || yyjson_arr_size(arr) == 0)
1751+ return (buf_puts(text, "missing required parameter \"paths\" (a non-empty array of strings)"), 1);
1752+ max = yyjson_arr_size(arr);
1753+ if (max > 200) max = 200; /* one call must not swallow a node */
1754+ for (i = 0; i < max; i++) {
1755+ yyjson_val *v = yyjson_arr_get(arr, i);
1756+ const char *pv = ju_cstr(v); /* NUL-safe: never a truncated path */
1757+ if (pv && pv[0]) read_one_path(pv, text, &first);
1758+ }
1759+ return 0;
1760+}
1761+
1762+static int tool_write_file(yyjson_val *args, buf_t *text)
1763+{
1764+ char raw[PATH_SZ], canon[PATH_SZ];
1765+ const char *err = NULL;
1766+ const char *content;
1767+ size_t clen;
1768+
1769+ if (!ju_field_str(args, "path", raw, sizeof raw))
1770+ return (buf_puts(text, "missing required parameter \"path\""), 1);
1771+ if (!resolve_allowed(raw, canon, sizeof canon, 'w', &err))
1772+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
1773+ if (is_dir_path(canon))
1774+ return (buf_printf(text, "%s: that is a directory", raw), 1);
1775+ if (is_link_path(canon))
1776+ return (buf_printf(text, "%s: refusing to write through a symlink", raw), 1);
1777+
1778+ {
1779+ yyjson_val *cv = args ? yyjson_obj_get(args, "content") : NULL;
1780+ if (!cv) return (buf_puts(text, "missing required parameter \"content\""), 1);
1781+ if (!yyjson_is_str(cv))
1782+ return (buf_puts(text, "\"content\" must be a string"), 1);
1783+ content = yyjson_get_str(cv);
1784+ clen = yyjson_get_len(cv);
1785+ }
1786+ if (clen > WRITE_CAP)
1787+ return (buf_printf(text, "content is %llu bytes (limit %llu)",
1788+ (unsigned long long)clen, (unsigned long long)WRITE_CAP), 1);
1789+
1790+ if (ensure_parent(canon) != 0)
1791+ return (buf_printf(text, "%s: cannot create the parent directory", raw), 1);
1792+ if (!write_atomic(canon, content, clen, &err))
1793+ return (buf_printf(text, "%s: %s", raw, err ? err : "write failed"), 1);
1794+
1795+ buf_printf(text, "Successfully wrote %llu bytes to %s",
1796+ (unsigned long long)clen, raw);
1797+ return 0;
1798+}
1799+
1800+/* ------------------------------------------------------------------ */
1801+/* edit_file */
1802+/* */
1803+/* Upstream semantics, kept: edits apply in order, each to the result */
1804+/* of the ones before it; each replaces the FIRST match of oldText; */
1805+/* an exact match wins, and when there is none a run of whole lines */
1806+/* matches if each line is equal once leading and trailing whitespace */
1807+/* is ignored (newText then takes the file's indentation is NOT */
1808+/* re-derived - we keep the caller's text and say so in the diff); if */
1809+/* ANY edit has no match NOTHING is written and the error shows where */
1810+/* the file diverges; dryRun computes and returns the diff without */
1811+/* touching the disk. The file's own line ending is detected and */
1812+/* restored. */
1813+/* ------------------------------------------------------------------ */
1814+
1815+/* Find `needle` in `hay` (exact). Returns offset or (size_t)-1. */
1816+static size_t find_sub(const char *hay, size_t hlen, const char *needle, size_t nlen)
1817+{
1818+ size_t i;
1819+ if (nlen == 0 || nlen > hlen) return (size_t)-1;
1820+ for (i = 0; i + nlen <= hlen; i++)
1821+ if (!memcmp(hay + i, needle, nlen)) return i;
1822+ return (size_t)-1;
1823+}
1824+
1825+/* Whitespace-insensitive whole-line match. Returns start offset of the
1826+ * matching region and sets *endlen, or (size_t)-1. The match must start at
1827+ * a line boundary and the compared run must be followed by a newline when
1828+ * oldText ends with one. */
1829+static size_t find_lines(const char *hay, size_t hlen, const char *needle,
1830+ size_t nlen, size_t *matchlen)
1831+{
1832+ /* Split needle into lines (LF-only, trailing \n dropped). */
1833+ char *ndup;
1834+ char *nl[64];
1835+ size_t nlines = 0, i, start = 0;
1836+ char *hl[4096];
1837+ size_t hlines = 0, pos[4097];
1838+ size_t cand;
1839+
1840+ *matchlen = 0;
1841+ if (nlen == 0) return (size_t)-1;
1842+ ndup = (char *)malloc(nlen + 1);
1843+ if (!ndup) return (size_t)-1;
1844+ memcpy(ndup, needle, nlen);
1845+ ndup[nlen] = '\0';
1846+ if (nlen && ndup[nlen - 1] == '\n') ndup[nlen - 1] = '\0';
1847+ for (i = 0; ndup[i]; i++) {
1848+ if (ndup[i] == '\r') ndup[i] = '\0';
1849+ if (ndup[i] == '\n') {
1850+ ndup[i] = '\0';
1851+ if (nlines < 64) nl[nlines++] = ndup + start;
1852+ start = i + 1;
1853+ }
1854+ }
1855+ if (nlines < 64) nl[nlines++] = ndup + start;
1856+ /* oldText ended with a newline: that trailing "" is not a line to match,
1857+ * and the boundary is enforced separately below. */
1858+ if (nlen && needle[nlen - 1] == '\n' && nlines > 1 &&
1859+ nl[nlines - 1][0] == '\0') nlines--;
1860+ if (nlines == 0 || nlines > 64) { free(ndup); return (size_t)-1; }
1861+
1862+ /* Split haystack into lines, remembering offsets. */
1863+ start = 0;
1864+ for (i = 0; i <= hlen; i++) {
1865+ if (i == hlen || hay[i] == '\n') {
1866+ if (hlines < 4096) {
1867+ size_t lstart = start, lend = i;
1868+ /* strip a trailing \r for comparison, keep the byte in place */
1869+ pos[hlines] = lstart;
1870+ {
1871+ size_t sl = lstart, el = lend;
1872+ char *dup;
1873+ if (el > sl && hay[el - 1] == '\r') el--;
1874+ dup = (char *)malloc(el - sl + 1);
1875+ if (!dup) {
1876+ size_t k;
1877+ for (k = 0; k < hlines; k++) free(hl[k]);
1878+ free(ndup);
1879+ return (size_t)-1;
1880+ }
1881+ memcpy(dup, hay + sl, el - sl);
1882+ dup[el - sl] = '\0';
1883+ hl[hlines] = dup;
1884+ }
1885+ hlines++;
1886+ }
1887+ start = i + 1;
1888+ if (i == hlen) break;
1889+ }
1890+ }
1891+ if (hlines + 1 > 4096) { hlines = 4096; }
1892+
1893+ for (cand = 0; cand + nlines <= hlines && cand + nlines <= 4096; cand++) {
1894+ size_t j, ok = 1;
1895+ for (j = 0; j < nlines; j++) {
1896+ const char *a = nl[j], *b = hl[cand + j];
1897+ while (*a == ' ' || *a == '\t') a++;
1898+ while (*b == ' ' || *b == '\t') b++;
1899+ {
1900+ size_t la = strlen(a), lb = strlen(b);
1901+ while (la && (a[la - 1] == ' ' || a[la - 1] == '\t')) la--;
1902+ while (lb && (b[lb - 1] == ' ' || b[lb - 1] == '\t')) lb--;
1903+ if (la != lb || memcmp(a, b, la)) { ok = 0; break; }
1904+ }
1905+ }
1906+ if (ok) {
1907+ size_t s = pos[cand];
1908+ size_t e = pos[cand + nlines - 1];
1909+ /* The run must land on line boundaries. The last matched line
1910+ * ends at its newline (or at EOF); when oldText itself asked for
1911+ * the newline it is part of the match, when it did not the
1912+ * file's own newline is left alone - which is what keeps an edit
1913+ * from silently deleting the file's trailing newline. */
1914+ while (e < hlen && hay[e] != '\n') e++;
1915+ if (needle[nlen - 1] == '\n') {
1916+ if (e == hlen) { /* no newline to consume */
1917+ size_t k;
1918+ for (k = 0; k < hlines; k++) free(hl[k]);
1919+ free(ndup);
1920+ return (size_t)-1;
1921+ }
1922+ e++;
1923+ }
1924+ *matchlen = e - s;
1925+ {
1926+ size_t k;
1927+ for (k = 0; k < hlines; k++) free(hl[k]);
1928+ }
1929+ free(ndup);
1930+ return s;
1931+ }
1932+ }
1933+ {
1934+ size_t k;
1935+ for (k = 0; k < hlines; k++) free(hl[k]);
1936+ }
1937+ free(ndup);
1938+ return (size_t)-1;
1939+}
1940+
1941+/* Report the first diverging non-blank line of `cur` vs `old`, numbered. */
1942+static void describe_mismatch(buf_t *text, const char *cur, size_t curlen,
1943+ const char *old, size_t oldlen, size_t index)
1944+{
1945+ char probe[NAME_SZ];
1946+ size_t i, o = 0, shown = 0;
1947+ size_t plen = 0;
1948+
1949+ /* first non-empty line of oldText, trimmed */
1950+ while (o < oldlen && (old[o] == '\n' || old[o] == '\r' ||
1951+ old[o] == ' ' || old[o] == '\t')) o++;
1952+ while (o + plen < oldlen && plen < sizeof probe - 1 &&
1953+ old[o + plen] != '\n' && old[o + plen] != '\r') {
1954+ probe[plen] = old[o + plen];
1955+ plen++;
1956+ }
1957+ probe[plen] = '\0';
1958+ /* trim trailing spaces */
1959+ while (plen && (probe[plen - 1] == ' ' || probe[plen - 1] == '\t')) probe[--plen] = '\0';
1960+
1961+ buf_printf(text, "edit #%u did not match. ", (unsigned)(index + 1));
1962+ if (plen) {
1963+ long long best = -1;
1964+ double bestscore = -1;
1965+ /* Find the line of the file most similar to probe's first token. */
1966+ size_t ls = 0, ln = 1;
1967+ for (i = 0; i <= curlen; i++) {
1968+ if (i == curlen || cur[i] == '\n') {
1969+ size_t s = ls, e = i, m, hits = 0;
1970+ while (s < e && (cur[s] == ' ' || cur[s] == '\t')) s++;
1971+ while (e > s && (cur[e - 1] == ' ' || cur[e - 1] == '\t' ||
1972+ cur[e - 1] == '\r')) e--;
1973+ if (e > s && plen) {
1974+ for (m = s; m < e; m++) {
1975+ size_t k;
1976+ for (k = 0; k < plen; k++)
1977+ if (cur[m] == probe[k]) { hits++; break; }
1978+ }
1979+ {
1980+ double sc = (double)hits / (double)(e - s);
1981+ if (sc > bestscore) { bestscore = sc; best = (long long)ln; }
1982+ }
1983+ }
1984+ ls = i + 1;
1985+ ln++;
1986+ }
1987+ }
1988+ if (best > 0) {
1989+ buf_printf(text, "The closest line is %lld. ", best);
1990+ /* print up to 3 numbered lines around it */
1991+ {
1992+ size_t ls2 = 0, ln2 = 1;
1993+ for (i = 0; i <= curlen; i++) {
1994+ if (i == curlen || cur[i] == '\n') {
1995+ int phantom = (i == curlen && ls2 == curlen);
1996+ if (!phantom && ln2 >= (size_t)best - 1 && shown < 3) {
1997+ size_t s = ls2, e = (i < curlen) ? i : curlen;
1998+ buf_printf(text, "%lld| ", (long long)ln2);
1999+ for (; s < e && s < ls2 + 200; s++)
2000+ if (cur[s] != '\r') buf_putc(text, cur[s]);
2001+ buf_putc(text, '\n');
2002+ shown++;
2003+ }
2004+ ls2 = i + 1;
2005+ ln2++;
2006+ }
2007+ }
2008+ }
2009+ } else {
2010+ buf_puts(text, "Nothing in the file resembles oldText. ");
2011+ }
2012+ } else {
2013+ buf_puts(text, "oldText was blank. ");
2014+ }
2015+ buf_puts(text, "Copy oldText from a read_text_file of the current content and retry.");
2016+}
2017+
2018+static int tool_edit_file(yyjson_val *args, buf_t *text)
2019+{
2020+ char raw[PATH_SZ], canon[PATH_SZ];
2021+ const char *err = NULL;
2022+ yyjson_val *edits;
2023+ buf_t cur, work;
2024+ size_t i, max;
2025+ int dry_run;
2026+ char *orig = NULL;
2027+ size_t origlen = 0;
2028+ int eol_crlf = 0;
2029+
2030+ if (!ju_field_str(args, "path", raw, sizeof raw))
2031+ return (buf_puts(text, "missing required parameter \"path\""), 1);
2032+ if (!resolve_allowed(raw, canon, sizeof canon, 'w', &err))
2033+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2034+ if (!is_regular(canon))
2035+ return (buf_printf(text, "%s: not a regular file", raw), 1);
2036+
2037+ edits = args ? yyjson_obj_get(args, "edits") : NULL;
2038+ if (!edits || !yyjson_is_arr(edits) || yyjson_arr_size(edits) == 0)
2039+ return (buf_puts(text, "missing required parameter \"edits\" (a non-empty array of {oldText,newText})"), 1);
2040+ dry_run = ju_bool(args, "dryRun", 0);
2041+
2042+ buf_init(&cur);
2043+ if (!read_whole(canon, &cur, READ_CAP, NULL, &err)) {
2044+ buf_printf(text, "%s: %s", raw, err ? err : "read failed");
2045+ buf_free(&cur);
2046+ return 1;
2047+ }
2048+ /* detect the file's dominant line ending so the write restores it */
2049+ for (i = 0; i + 1 < cur.n; i++)
2050+ if (cur.p[i] == '\r' && cur.p[i + 1] == '\n') { eol_crlf = 1; break; }
2051+
2052+ /* normalise to LF for matching */
2053+ {
2054+ size_t o = 0;
2055+ for (i = 0; i < cur.n; i++)
2056+ if (!(cur.p[i] == '\r' && i + 1 < cur.n && cur.p[i + 1] == '\n'))
2057+ cur.p[o++] = cur.p[i];
2058+ cur.n = o;
2059+ if (cur.p) cur.p[o] = '\0';
2060+ }
2061+ orig = (char *)malloc(cur.n + 1);
2062+ if (!orig) { buf_free(&cur); return (buf_puts(text, "out of memory"), 1); }
2063+ memcpy(orig, cur.p ? cur.p : "", cur.n);
2064+ orig[cur.n] = '\0';
2065+ origlen = cur.n;
2066+
2067+ buf_init(&work);
2068+ buf_add(&work, orig, origlen);
2069+
2070+ max = yyjson_arr_size(edits);
2071+ if (max > 100) max = 100;
2072+ for (i = 0; i < max; i++) {
2073+ yyjson_val *e = yyjson_arr_get(edits, i);
2074+ const char *ot, *nt;
2075+ size_t otlen, ntlen, at, ml;
2076+ buf_t next;
2077+
2078+ if (!yyjson_is_obj(e)) {
2079+ buf_free(&work);
2080+ free(orig);
2081+ buf_free(&cur);
2082+ buf_puts(text, "each edit must be an object with oldText and newText");
2083+ return 1;
2084+ }
2085+ ot = ju_str(e, "oldText");
2086+ nt = ju_str(e, "newText");
2087+ if (!ot) {
2088+ buf_free(&work);
2089+ free(orig);
2090+ buf_free(&cur);
2091+ buf_printf(text, "edit #%u is missing \"oldText\"", (unsigned)(i + 1));
2092+ return 1;
2093+ }
2094+ if (!nt) nt = "";
2095+ otlen = strlen(ot);
2096+ ntlen = strlen(nt);
2097+ if (otlen == 0) {
2098+ buf_free(&work);
2099+ free(orig);
2100+ buf_free(&cur);
2101+ buf_printf(text, "edit #%u has empty oldText - that would insert at position 0; send a real anchor",
2102+ (unsigned)(i + 1));
2103+ return 1;
2104+ }
2105+
2106+ at = find_sub(work.p, work.n, ot, otlen);
2107+ ml = otlen;
2108+ if (at == (size_t)-1)
2109+ at = find_lines(work.p, work.n, ot, otlen, &ml);
2110+ if (at == (size_t)-1) {
2111+ describe_mismatch(text, work.p, work.n, ot, otlen, i);
2112+ buf_puts(text, " Nothing was written.");
2113+ buf_free(&work);
2114+ free(orig);
2115+ buf_free(&cur);
2116+ return 1;
2117+ }
2118+ buf_init(&next);
2119+ buf_add(&next, work.p, at);
2120+ buf_add(&next, nt, ntlen);
2121+ buf_add(&next, work.p + at + ml, work.n - at - ml);
2122+ buf_free(&work);
2123+ work = next;
2124+ }
2125+
2126+ if (!dry_run) {
2127+ buf_t outb;
2128+ const char *werr = NULL;
2129+ buf_init(&outb);
2130+ if (eol_crlf) {
2131+ for (i = 0; i < work.n; i++) {
2132+ if (work.p[i] == '\n') buf_putc(&outb, '\r');
2133+ buf_putc(&outb, work.p[i]);
2134+ }
2135+ } else {
2136+ buf_add(&outb, work.p, work.n);
2137+ }
2138+ if (!write_atomic(canon, outb.p ? outb.p : "", outb.n, &werr)) {
2139+ buf_free(&outb);
2140+ buf_free(&work);
2141+ free(orig);
2142+ buf_free(&cur);
2143+ buf_printf(text, "%s: %s", raw, werr ? werr : "write failed");
2144+ return 1;
2145+ }
2146+ buf_free(&outb);
2147+ }
2148+
2149+ make_diff(text, orig, origlen, work.p ? work.p : "", work.n, raw);
2150+ if (dry_run) buf_puts(text, "\n(dry run - nothing was written)\n");
2151+ buf_free(&work);
2152+ free(orig);
2153+ buf_free(&cur);
2154+ return 0;
2155+}
2156+
2157+/* ------------------------------------------------------------------ */
2158+/* The remaining tools */
2159+/* ------------------------------------------------------------------ */
2160+
2161+static int tool_create_directory(yyjson_val *args, buf_t *text)
2162+{
2163+ char raw[PATH_SZ], canon[PATH_SZ];
2164+ const char *err = NULL;
2165+
2166+ if (!ju_field_str(args, "path", raw, sizeof raw))
2167+ return (buf_puts(text, "missing required parameter \"path\""), 1);
2168+ if (!resolve_allowed(raw, canon, sizeof canon, 'w', &err))
2169+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2170+ if (is_dir_path(canon)) {
2171+ buf_printf(text, "Directory already exists: %s", raw);
2172+ return 0;
2173+ }
2174+ if (is_regular(canon))
2175+ return (buf_printf(text, "%s: a file already exists at that path", raw), 1);
2176+ if (mkdir_p(canon) != 0)
2177+ return (buf_printf(text, "%s: cannot create directory (%s)", raw,
2178+ strerror(errno)), 1);
2179+ buf_printf(text, "Successfully created directory %s", raw);
2180+ return 0;
2181+}
2182+
2183+static void emit_listing(buf_t *text, const char *path, const char *raw,
2184+ long n, dent_t *v, int with_sizes)
2185+{
2186+ long i;
2187+ long long tot_files = 0, tot_dirs = 0;
2188+ for (i = 0; i < n; i++) {
2189+ if (v[i].is_dir) tot_dirs++;
2190+ else tot_files++;
2191+ buf_puts(text, v[i].is_dir ? "[DIR] " : "[FILE] ");
2192+ buf_puts(text, v[i].name);
2193+ if (with_sizes && !v[i].is_dir)
2194+ buf_printf(text, " %lld bytes", v[i].size);
2195+ buf_putc(text, '\n');
2196+ }
2197+ if (n >= MAX_ENTRIES)
2198+ buf_printf(text, "(listing truncated at %d entries)\n", MAX_ENTRIES);
2199+ if (with_sizes)
2200+ buf_printf(text, "\n%d directories, %lld files\n",
2201+ (int)tot_dirs, tot_files);
2202+ (void)path;
2203+ (void)raw;
2204+}
2205+
2206+static int tool_list_directory(yyjson_val *args, buf_t *text)
2207+{
2208+ char raw[PATH_SZ], canon[PATH_SZ];
2209+ const char *err = NULL;
2210+ dent_t *v = NULL;
2211+ long n;
2212+
2213+ if (!ju_field_str(args, "path", raw, sizeof raw))
2214+ return (buf_puts(text, "missing required parameter \"path\""), 1);
2215+ if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err))
2216+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2217+ if (!is_dir_path(canon))
2218+ return (buf_printf(text, "%s: not a directory", raw), 1);
2219+ n = list_dir(canon, &v, &err);
2220+ if (n < 0) {
2221+ buf_printf(text, "%s: %s", raw, err ? err : "cannot read directory");
2222+ return 1;
2223+ }
2224+ emit_listing(text, canon, raw, n, v, 0);
2225+ free(v);
2226+ return 0;
2227+}
2228+
2229+/* Upstream says the tree is "formatted with 2-space indentation for
2230+ * readability", and an agent pastes this straight into a reply, so the
2231+ * indentation is part of the tool's output contract - not decoration. */
2232+static void indent(buf_t *b, int depth)
2233+{
2234+ int i;
2235+ for (i = 0; i < depth * 2; i++) buf_putc(b, ' ');
2236+}
2237+
2238+/* Whether the buffer ends with an entry (so a closing bracket needs its own
2239+ * line). An empty children array stays on one line: []. */
2240+static int body_has_entries(const buf_t *b)
2241+{
2242+ size_t i;
2243+ if (!b->p || b->n == 0) return 0;
2244+ i = b->n - 1;
2245+ while (i > 0 && (b->p[i] == ' ' || b->p[i] == '\n')) i--;
2246+ return b->p[i] != '[';
2247+}
2248+
2249+static int tree_walk(buf_t *b, const char *dir, const char *rel, int depth,
2250+ int max_depth, long *budget, yyjson_val *excludes,
2251+ int *truncated)
2252+{
2253+ dent_t *v = NULL;
2254+ const char *err = NULL;
2255+ long n, i;
2256+ int first = 1;
2257+
2258+ if (*budget <= 0) { *truncated = 1; return 0; }
2259+ n = list_dir(dir, &v, &err);
2260+ if (n < 0) return -1;
2261+ for (i = 0; i < n; i++) {
2262+ char child[PATH_SZ], crel[PATH_SZ];
2263+ if (*budget <= 0) { *truncated = 1; break; }
2264+ if (v[i].name[0] == '.') continue; /* dotfiles stay out of a tree */
2265+ (*budget)--;
2266+ path_join(child, sizeof child, dir, v[i].name);
2267+ if (rel[0]) snprintf(crel, sizeof crel, "%s/%s", rel, v[i].name);
2268+ else str_copy(crel, sizeof crel, v[i].name);
2269+ if (is_excluded(crel, v[i].is_dir, excludes)) continue;
2270+
2271+ if (!first) buf_putc(b, ',');
2272+ first = 0;
2273+ buf_putc(b, '\n');
2274+ indent(b, depth);
2275+ buf_puts(b, "{\"name\":");
2276+ json_str(b, v[i].name);
2277+ buf_puts(b, ", \"type\":");
2278+ buf_puts(b, v[i].is_dir ? "\"directory\"" : "\"file\"");
2279+ if (v[i].is_dir && depth < max_depth) {
2280+ int sub_trunc = 0;
2281+ buf_puts(b, ", \"children\":[");
2282+ tree_walk(b, child, crel, depth + 1, max_depth, budget, excludes,
2283+ &sub_trunc);
2284+ if (sub_trunc) *truncated = 1;
2285+ if (body_has_entries(b)) {
2286+ buf_putc(b, '\n');
2287+ indent(b, depth);
2288+ }
2289+ buf_putc(b, ']');
2290+ }
2291+ buf_putc(b, '}');
2292+ }
2293+ free(v);
2294+ return 0;
2295+}
2296+
2297+static int tool_directory_tree(yyjson_val *args, buf_t *text)
2298+{
2299+ char raw[PATH_SZ], canon[PATH_SZ];
2300+ const char *err = NULL;
2301+ int have = 0;
2302+ long long md = ju_int(args, "maxDepth", 4, &have);
2303+ long budget = WALK_BUDGET;
2304+ int truncated = 0;
2305+ yyjson_val *excludes = args ? yyjson_obj_get(args, "excludePatterns") : NULL;
2306+ buf_t body;
2307+
2308+ if (!ju_field_str(args, "path", raw, sizeof raw))
2309+ return (buf_puts(text, "missing required parameter \"path\""), 1);
2310+ if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err))
2311+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2312+ if (!is_dir_path(canon))
2313+ return (buf_printf(text, "%s: not a directory", raw), 1);
2314+ if (md < 0) md = 0;
2315+ if (md > MAX_DEPTH) md = MAX_DEPTH;
2316+
2317+ buf_init(&body);
2318+ buf_putc(&body, '[');
2319+ tree_walk(&body, canon, "", 1, (int)md, &budget, excludes, &truncated);
2320+ if (body_has_entries(&body)) {
2321+ buf_putc(&body, '\n');
2322+ indent(&body, 0);
2323+ }
2324+ buf_putc(&body, ']');
2325+ buf_add(text, body.p ? body.p : "[]", body.n);
2326+ buf_free(&body);
2327+ if (truncated)
2328+ buf_printf(text, "\n(truncated after %d entries; narrow the path or lower maxDepth)",
2329+ WALK_BUDGET);
2330+ return 0;
2331+}
2332+
2333+static int tool_move_file(yyjson_val *args, buf_t *text)
2334+{
2335+ char sraw[PATH_SZ], draw[PATH_SZ], src[PATH_SZ], dst[PATH_SZ];
2336+ const char *err = NULL;
2337+
2338+ if (!ju_field_str(args, "source", sraw, sizeof sraw))
2339+ return (buf_puts(text, "missing required parameter \"source\""), 1);
2340+ if (!ju_field_str(args, "destination", draw, sizeof draw))
2341+ return (buf_puts(text, "missing required parameter \"destination\""), 1);
2342+ if (!resolve_allowed(sraw, src, sizeof src, 'r', &err))
2343+ return (buf_printf(text, "source %s: %s", sraw, err ? err : "refused"), 1);
2344+ if (is_link_path(src))
2345+ return (buf_printf(text, "source %s: refusing to move a symlink", sraw), 1);
2346+ if (resolve_allowed(draw, dst, sizeof dst, 'r', &err)) {
2347+ if (is_dir_path(dst))
2348+ return (buf_printf(text, "%s: a directory already exists at the destination", draw), 1);
2349+ if (strcmp(src, dst) == 0) {
2350+ buf_printf(text, "Source and destination are the same file: %s", sraw);
2351+ return 0;
2352+ }
2353+ /* Upstream refuses to overwrite; so do we, silently-overwriting an
2354+ * operator's file is the one thing an agent should never get. */
2355+ return (buf_printf(text, "%s already exists - move nothing. Move to a new name instead.", draw), 1);
2356+ }
2357+ if (!resolve_allowed(draw, dst, sizeof dst, 'w', &err))
2358+ return (buf_printf(text, "destination %s: %s", draw, err ? err : "refused"), 1);
2359+ if (ensure_parent(dst) != 0)
2360+ return (buf_printf(text, "%s: cannot create the destination directory", draw), 1);
2361+
2362+#if defined(_WIN32)
2363+ if (!MoveFileExA(src, dst, MOVEFILE_WRITE_THROUGH)) {
2364+ DWORD e = GetLastError();
2365+ if (e == ERROR_NOT_SAME_DEVICE) {
2366+ if (!copy_file(src, dst, &err)) {
2367+ buf_printf(text, "%s: %s", sraw, err ? err : "copy failed");
2368+ return 1;
2369+ }
2370+ DeleteFileA(src);
2371+ } else {
2372+ buf_printf(text, "%s -> %s: Win32 error %lu", sraw, draw, (unsigned long)e);
2373+ return 1;
2374+ }
2375+ }
2376+#else
2377+ if (rename(src, dst) != 0) {
2378+ if (errno == EXDEV) {
2379+ /* Cross-device: copy then remove. Same visible result, one more
2380+ * window, so the removal only happens once the copy is on disk. */
2381+ if (!copy_file(src, dst, &err)) {
2382+ buf_printf(text, "%s -> %s: %s", sraw, draw, err ? err : "copy failed");
2383+ return 1;
2384+ }
2385+ if (remove(src) != 0) {
2386+ buf_printf(text, "copied %s to %s but could not remove the source (%s)",
2387+ sraw, draw, strerror(errno));
2388+ return 1;
2389+ }
2390+ } else {
2391+ buf_printf(text, "%s -> %s: %s", sraw, draw, strerror(errno));
2392+ return 1;
2393+ }
2394+ }
2395+#endif
2396+ buf_printf(text, "Successfully moved %s to %s", sraw, draw);
2397+ return 0;
2398+}
2399+
2400+/* A walk may only descend into paths still inside a root; re-checking each
2401+ * child also catches a symlink that a directory scan handed us. */
2402+static int is_allowed_for_walk(const char *canon_child)
2403+{
2404+ char pc[PATH_SZ];
2405+ if (denied_path(canon_child)) return 0;
2406+ if (root_contains(canon_child) >= 0) return 1;
2407+ if (canon_path(canon_child, pc, sizeof pc))
2408+ return root_contains(pc) >= 0 && !denied_path(pc);
2409+ return 0;
2410+}
2411+
2412+typedef struct {
2413+ buf_t *out;
2414+ long count;
2415+ int truncated;
2416+} search_ctx;
2417+
2418+static void search_walk(const char *dir, const char *rel, const char *pattern,
2419+ yyjson_val *excludes, long *budget, search_ctx *sc)
2420+{
2421+ dent_t *v = NULL;
2422+ const char *err = NULL;
2423+ long n, i;
2424+
2425+ if (*budget <= 0) { sc->truncated = 1; return; }
2426+ n = list_dir(dir, &v, &err);
2427+ if (n < 0) return; /* unreadable subtree: skip */
2428+ for (i = 0; i < n; i++) {
2429+ char child[PATH_SZ], crel[PATH_SZ];
2430+ if (*budget <= 0) { sc->truncated = 1; break; }
2431+ (*budget)--;
2432+ path_join(child, sizeof child, dir, v[i].name);
2433+ if (rel[0]) snprintf(crel, sizeof crel, "%s/%s", rel, v[i].name);
2434+ else str_copy(crel, sizeof crel, v[i].name);
2435+
2436+ /* excludes are checked before anything else, so an excluded subtree
2437+ * is never even opened (upstream #4162) */
2438+ if (is_excluded(crel, v[i].is_dir, excludes)) continue;
2439+ if (!is_allowed_for_walk(child)) { continue; }
2440+
2441+ if (sc->count < MAX_RESULTS) {
2442+ int hit = glob_match(pattern, crel) || glob_match(pattern, v[i].name);
2443+ if (hit) {
2444+ if (sc->count) buf_putc(sc->out, '\n');
2445+ buf_puts(sc->out, child);
2446+ sc->count++;
2447+ }
2448+ } else {
2449+ sc->truncated = 1;
2450+ }
2451+ if (v[i].is_dir) search_walk(child, crel, pattern, excludes, budget, sc);
2452+ }
2453+ free(v);
2454+}
2455+
2456+static int tool_search_files(yyjson_val *args, buf_t *text)
2457+{
2458+ char raw[PATH_SZ], canon[PATH_SZ], rel[PATH_SZ] = "";
2459+ const char *err = NULL;
2460+ char pattern[NAME_SZ];
2461+ yyjson_val *excludes;
2462+ search_ctx sc;
2463+ long budget = WALK_BUDGET;
2464+
2465+ if (!ju_field_str(args, "path", raw, sizeof raw))
2466+ return (buf_puts(text, "missing required parameter \"path\""), 1);
2467+ if (!ju_field_str(args, "pattern", pattern, sizeof pattern))
2468+ return (buf_puts(text, "missing required parameter \"pattern\""), 1);
2469+ if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err))
2470+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2471+ if (!is_dir_path(canon))
2472+ return (buf_printf(text, "%s: not a directory (search walks directories)", raw), 1);
2473+ excludes = args ? yyjson_obj_get(args, "excludePatterns") : NULL;
2474+
2475+ sc.out = text;
2476+ sc.count = 0;
2477+ sc.truncated = 0;
2478+ search_walk(canon, rel, pattern, excludes, &budget, &sc);
2479+ if (sc.count == 0) {
2480+ buf_puts(text, "(no matches)");
2481+ return 0;
2482+ }
2483+ if (sc.truncated)
2484+ buf_printf(text, "\n(truncated: %d matches shown, walk budget %d entries; narrow the path or add excludePatterns)",
2485+ (int)sc.count, WALK_BUDGET);
2486+ return 0;
2487+}
2488+
2489+/* One timestamp as a JSON string (or null). */
2490+static void json_time(buf_t *b, long long t)
2491+{
2492+ char iso[40];
2493+ if (t <= 0) { buf_puts(b, "null"); return; }
2494+ fmt_iso(t, iso, sizeof iso);
2495+ json_str(b, iso);
2496+}
2497+
2498+static long long file_atime(const char *p)
2499+{
2500+#if defined(_WIN32)
2501+ WIN32_FILE_ATTRIBUTE_DATA d;
2502+ ULARGE_INTEGER u;
2503+ if (!GetFileAttributesExA(p, GetFileExInfoStandard, &d)) return 0;
2504+ u.LowPart = d.ftLastAccessTime.dwLowDateTime;
2505+ u.HighPart = d.ftLastAccessTime.dwHighDateTime;
2506+ return (long long)(u.QuadPart / 10000000ULL - 11644473600ULL);
2507+#else
2508+ struct stat st;
2509+ if (stat(p, &st) != 0) return 0;
2510+ return (long long)st.st_atime;
2511+#endif
2512+}
2513+
2514+static int tool_get_file_info(yyjson_val *args, buf_t *text)
2515+{
2516+ char raw[PATH_SZ], canon[PATH_SZ];
2517+ const char *err = NULL;
2518+
2519+ if (!ju_field_str(args, "path", raw, sizeof raw))
2520+ return (buf_puts(text, "missing required parameter \"path\""), 1);
2521+ if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err))
2522+ return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1);
2523+
2524+ buf_puts(text, "{\n \"path\":");
2525+ json_str(text, canon);
2526+ buf_puts(text, is_dir_path(canon)
2527+ ? ",\n \"type\":\"directory\""
2528+ : ",\n \"type\":\"file\"");
2529+ buf_printf(text, ",\n \"size\":%lld", file_size(canon));
2530+ buf_puts(text, ",\n \"created\":");
2531+ json_time(text, 0); /* birth time is not portable */
2532+ buf_puts(text, ",\n \"modified\":");
2533+ json_time(text, file_mtime(canon));
2534+ buf_puts(text, ",\n \"accessed\":");
2535+ json_time(text, file_atime(canon));
2536+ buf_printf(text, ",\n \"isFile\":%s", is_regular(canon) ? "true" : "false");
2537+ buf_printf(text, ",\n \"isDirectory\":%s", is_dir_path(canon) ? "true" : "false");
2538+ buf_printf(text, ",\n \"isSymlink\":%s", is_link_path(canon) ? "true" : "false");
2539+ buf_printf(text, ",\n \"mode\":\"%04o\"\n}\n", file_mode(canon));
2540+ return 0;
2541+}
2542+
2543+static int tool_list_allowed_directories(yyjson_val *args, buf_t *text)
2544+{
2545+ int i;
2546+ (void)args;
2547+ buf_printf(text, "Allowed directories (%d):\n", g_root_count);
2548+ if (g_root_count == 0)
2549+ buf_puts(text, "(none configured - the plugin has nothing it may touch)");
2550+ for (i = 0; i < g_root_count; i++) {
2551+ buf_puts(text, g_roots[i].canonical);
2552+ if (strcmp(g_roots[i].configured, g_roots[i].canonical) != 0)
2553+ buf_printf(text, " (configured as %s)", g_roots[i].configured);
2554+ if (!g_roots[i].exists) buf_puts(text, " [does not exist]");
2555+ else if (!g_roots[i].is_dir) buf_puts(text, " [not a directory]");
2556+ buf_putc(text, '\n');
2557+ }
2558+ return 0;
2559+}
2560+
2561+/* ------------------------------------------------------------------ */
2562+/* Tool registry */
2563+/* */
2564+/* Descriptions are written to be read by a model choosing a tool, so */
2565+/* they say when to use this one and what the parameters mean, and every */
2566+/* one ends with the same reminder: it only works inside the allowed */
2567+/* directories. The inputSchema is what the router hands to clang's */
2568+/* MAX_TOOLS 512 budget, so it stays compact. */
2569+/* ------------------------------------------------------------------ */
2570+
2571+typedef struct {
2572+ const char *name;
2573+ const char *title;
2574+ const char *desc;
2575+ const char *schema;
2576+ int read_only;
2577+ int destructive;
2578+ tool_fn fn;
2579+} tool_def;
2580+
2581+#define S_PROPS(p) "{\"type\":\"object\",\"properties\":{" p "},\"required\""
2582+
2583+static const tool_def TOOLS[TOOLS_N] = {
2584+{"read_text_file", "Read Text File",
2585+ "Read the complete contents of a file as text. Use head for the first N lines "
2586+ "or tail for the last N (send at most one). Fails on binary files; use "
2587+ "get_file_info for metadata. Only works within allowed directories.",
2588+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute file path\"},"
2589+ "\"head\":{\"type\":\"integer\",\"description\":\"Return only the first N lines\"},"
2590+ "\"tail\":{\"type\":\"integer\",\"description\":\"Return only the last N lines\"}},"
2591+ "\"required\":[\"path\"]}", 1, 0, tool_read_text_file},
2592+
2593+{"read_multiple_files", "Read Multiple Files",
2594+ "Read several files in one call - cheaper than one read per file when "
2595+ "comparing or diffing. Each result is prefixed with its path and separated by "
2596+ "a line of three dashes; a file that fails reports its error without stopping "
2597+ "the rest. Only works within allowed directories.",
2598+ "{\"type\":\"object\",\"properties\":{\"paths\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},"
2599+ "\"description\":\"Absolute file paths (up to 200)\"}},\"required\":[\"paths\"]}", 1, 0,
2600+ tool_read_multiple_files},
2601+
2602+{"write_file", "Write File",
2603+ "Create or completely overwrite a file. Content is written to a temporary "
2604+ "file and renamed into place, so a crash cannot leave a half-written file. "
2605+ "Missing parent directories are created. Only works within allowed directories.",
2606+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute file path\"},"
2607+ "\"content\":{\"type\":\"string\",\"description\":\"Exact bytes to write\"}},\"required\":[\"path\",\"content\"]}",
2608+ 0, 1, tool_write_file},
2609+
2610+{"edit_file", "Edit File",
2611+ "Apply targeted replacements to a text file. Edits apply in order and each "
2612+ "replaces the first match of its oldText; oldText must match exactly, except "
2613+ "that LF/CRLF never matters and a run of whole lines matches when each line "
2614+ "is equal ignoring leading and trailing whitespace. If any edit fails to "
2615+ "match, NOTHING is written and the reply shows the closest numbered lines. "
2616+ "Set dryRun to see the diff without touching the disk. Only works within "
2617+ "allowed directories.",
2618+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute file path\"},"
2619+ "\"edits\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"oldText\":{\"type\":\"string\"},"
2620+ "\"newText\":{\"type\":\"string\"}},\"required\":[\"oldText\",\"newText\"]}},\"dryRun\":{\"type\":\"boolean\","
2621+ "\"description\":\"Compute and return the diff without writing\"}},\"required\":[\"path\",\"edits\"]}",
2622+ 0, 1, tool_edit_file},
2623+
2624+{"create_directory", "Create Directory",
2625+ "Create a directory and any missing parents. Succeeds if it already exists. "
2626+ "Only works within allowed directories.",
2627+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory path\"}},"
2628+ "\"required\":[\"path\"]}", 0, 0, tool_create_directory},
2629+
2630+{"list_directory", "List Directory",
2631+ "List entries directly inside a directory, each marked [DIR] or [FILE], "
2632+ "directories first then alphabetical. For a recursive view use directory_tree. "
2633+ "Only works within allowed directories.",
2634+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory path\"}},"
2635+ "\"required\":[\"path\"]}", 1, 0, tool_list_directory},
2636+
2637+{"directory_tree", "Directory Tree",
2638+ "Recursive tree of a directory as JSON: name, type (file/directory) and "
2639+ "children for directories. maxDepth bounds the depth (default 4); "
2640+ "excludePatterns are glob patterns matched against the relative path. Dot "
2641+ "entries are omitted. Only works within allowed directories.",
2642+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory path\"},"
2643+ "\"maxDepth\":{\"type\":\"integer\",\"description\":\"Levels to descend (0-24, default 4)\"},"
2644+ "\"excludePatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},"
2645+ "\"description\":\"Globs such as node_modules or *.tmp matched on the relative path\"}},"
2646+ "\"required\":[\"path\"]}", 1, 0, tool_directory_tree},
2647+
2648+{"move_file", "Move File",
2649+ "Move or rename a file or directory. Will NOT overwrite an existing "
2650+ "destination - move to a new name instead. A cross-device move falls back to "
2651+ "copy-then-delete. Only works within allowed directories.",
2652+ "{\"type\":\"object\",\"properties\":{\"source\":{\"type\":\"string\",\"description\":\"Absolute current path\"},"
2653+ "\"destination\":{\"type\":\"string\",\"description\":\"Absolute new path (must not exist)\"}},"
2654+ "\"required\":[\"source\",\"destination\"]}", 0, 1, tool_move_file},
2655+
2656+{"search_files", "Search Files",
2657+ "Recursively find files and directories whose name or relative path matches a "
2658+ "glob pattern such as *.c or test_*.py. excludePatterns prunes subtrees "
2659+ "(node_modules, .git) before they are ever opened. Returns absolute paths. "
2660+ "Only works within allowed directories.",
2661+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory to search\"},"
2662+ "\"pattern\":{\"type\":\"string\",\"description\":\"Glob, e.g. *.log or **/README*\"},"
2663+ "\"excludePatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},"
2664+ "\"description\":\"Globs pruned from the walk\"}},\"required\":[\"path\",\"pattern\"]}", 1, 0,
2665+ tool_search_files},
2666+
2667+{"get_file_info", "Get File Info",
2668+ "Size, timestamps, type, symlink-ness and permission bits of one path. Use "
2669+ "this before reading anything large. Only works within allowed directories.",
2670+ "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute path\"}},"
2671+ "\"required\":[\"path\"]}", 1, 0, tool_get_file_info},
2672+
2673+{"list_allowed_directories", "List Allowed Directories",
2674+ "Report the directories this server may read and write, with the canonical "
2675+ "path each one really resolves to. Call this first when a path is refused so "
2676+ "you can pick a path inside a root.",
2677+ "{\"type\":\"object\",\"properties\":{}}", 1, 0, tool_list_allowed_directories}
2678+};
2679+
2680+/* ------------------------------------------------------------------ */
2681+/* --mcp : MCP JSON-RPC 2.0 over stdio */
2682+/* */
2683+/* Contract as the router drives it (scorpiox-connector-mcp): one JSON */
2684+/* object per line, responses on stdout terminated by \n, and nothing */
2685+/* else ever printed to stdout. Logs therefore go to stderr, a malformed */
2686+/* line is answered with -32700 (the router skips unparseable lines, but */
2687+/* an id-less parse error is what a client needs to see it is talking to */
2688+/* a real server), and a notification gets no reply at all. */
2689+/* */
2690+/* Content-Length framing is tolerated on input because a few clients */
2691+/* speak LSP-style headers; output is always newline-delimited. */
2692+/* ------------------------------------------------------------------ */
2693+
2694+static void log_err(const char *fmt, ...)
2695+{
2696+ va_list ap;
2697+ fputs(PLUGIN_ID ": ", stderr);
2698+ va_start(ap, fmt);
2699+ vfprintf(stderr, fmt, ap);
2700+ va_end(ap);
2701+ fputc('\n', stderr);
2702+}
2703+
2704+static void send_msg(const char *json)
2705+{
2706+ fputs(json, stdout);
2707+ fputc('\n', stdout);
2708+ fflush(stdout);
2709+}
2710+
2711+static void send_result(const char *id_raw, const char *result_json)
2712+{
2713+ buf_t b;
2714+ if (!id_raw) return; /* notification */
2715+ buf_init(&b);
2716+ buf_printf(&b, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":%s}",
2717+ id_raw, result_json ? result_json : "{}");
2718+ send_msg(b.p ? b.p : "{}");
2719+ buf_free(&b);
2720+}
2721+
2722+static void send_error(const char *id_raw, int code, const char *msg)
2723+{
2724+ buf_t b;
2725+ /* A parse error has no id to echo, but JSON-RPC still wants the
2726+ * client to see it: answer with id:null. Only a request we know is a
2727+ * notification (an id-less, method-bearing line) stays silent. */
2728+ buf_init(&b);
2729+ buf_printf(&b, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":%d,\"message\":",
2730+ id_raw ? id_raw : "null", code);
2731+ json_str(&b, msg ? msg : "error");
2732+ buf_puts(&b, "}}");
2733+ send_msg(b.p ? b.p : "{}");
2734+ buf_free(&b);
2735+}
2736+
2737+/* The id verbatim (number or string) so it round-trips byte-exact. */
2738+static char *id_raw_of(yyjson_val *root)
2739+{
2740+ yyjson_val *id = yyjson_obj_get(root, "id");
2741+ char *s;
2742+ if (!id) return NULL; /* a notification */
2743+ s = yyjson_val_write(id, 0, NULL);
2744+ return s ? s : strdup("null");
2745+}
2746+
2747+static void emit_tools_list(const char *id_raw)
2748+{
2749+ buf_t b;
2750+ int i;
2751+ buf_init(&b);
2752+ buf_puts(&b, "{\"tools\":[");
2753+ for (i = 0; i < TOOLS_N; i++) {
2754+ if (i) buf_putc(&b, ',');
2755+ buf_puts(&b, "{\"name\":");
2756+ json_str(&b, TOOLS[i].name);
2757+ buf_puts(&b, ",\"title\":");
2758+ json_str(&b, TOOLS[i].title);
2759+ buf_puts(&b, ",\"description\":");
2760+ json_str(&b, TOOLS[i].desc);
2761+ buf_puts(&b, ",\"inputSchema\":");
2762+ buf_puts(&b, TOOLS[i].schema);
2763+ buf_puts(&b, ",\"annotations\":{\"readOnlyHint\":");
2764+ buf_puts(&b, TOOLS[i].read_only ? "true" : "false");
2765+ buf_puts(&b, ",\"destructiveHint\":");
2766+ buf_puts(&b, TOOLS[i].destructive ? "true" : "false");
2767+ buf_puts(&b, ",\"idempotentHint\":true,\"openWorldHint\":false}");
2768+ buf_putc(&b, '}');
2769+ }
2770+ buf_puts(&b, "]}");
2771+ send_result(id_raw, b.p);
2772+ buf_free(&b);
2773+}
2774+
2775+static void handle_tools_call(const char *id_raw, yyjson_val *params)
2776+{
2777+ const char *name = ju_str(params, "name");
2778+ yyjson_val *arguments = params ? yyjson_obj_get(params, "arguments") : NULL;
2779+ buf_t text;
2780+ int is_err;
2781+ int idx;
2782+ buf_t out;
2783+
2784+ if (!name || !*name) {
2785+ send_error(id_raw, -32602, "missing tool name");
2786+ return;
2787+ }
2788+ idx = tool_index(name);
2789+ if (idx < 0) {
2790+ send_error(id_raw, -32602, "unknown tool");
2791+ return;
2792+ }
2793+ if (g_tool_off[idx]) {
2794+ buf_t why;
2795+ buf_init(&why);
2796+ buf_printf(&why, "tool \"%s\" is disabled in this connector's permissions - "
2797+ "enable it in the filesystem plugin page (Allowed Roots & Permissions)",
2798+ TOOLS[idx].name);
2799+ buf_init(&out);
2800+ buf_puts(&out, "{\"isError\":true,\"content\":[{\"type\":\"text\",\"text\":");
2801+ json_str(&out, why.p ? why.p : "");
2802+ buf_puts(&out, "}]}");
2803+ send_result(id_raw, out.p);
2804+ buf_free(&out);
2805+ buf_free(&why);
2806+ return;
2807+ }
2808+ if (arguments && !yyjson_is_obj(arguments)) arguments = NULL;
2809+
2810+ buf_init(&text);
2811+ is_err = TOOLS[idx].fn(arguments, &text);
2812+
2813+ buf_init(&out);
2814+ buf_puts(&out, "{\"isError\":");
2815+ buf_puts(&out, is_err ? "true" : "false");
2816+ buf_puts(&out, ",\"content\":[{\"type\":\"text\",\"text\":");
2817+ json_str(&out, text.p ? text.p : "");
2818+ buf_puts(&out, "}]}");
2819+ send_result(id_raw, out.p);
2820+ buf_free(&out);
2821+ buf_free(&text);
2822+}
2823+
2824+static void handle_line(const char *line)
2825+{
2826+ yyjson_doc *doc;
2827+ yyjson_val *root, *params;
2828+ const char *method;
2829+ char *id_raw;
2830+
2831+ if (!line) return;
2832+ while (*line == ' ' || *line == '\t') line++;
2833+ if (!*line) return;
2834+
2835+ doc = yyjson_read(line, strlen(line), 0);
2836+ if (!doc) {
2837+ send_error(NULL, -32700, "parse error");
2838+ return;
2839+ }
2840+ root = yyjson_doc_get_root(doc);
2841+ if (!yyjson_is_obj(root)) {
2842+ yyjson_doc_free(doc);
2843+ send_error(NULL, -32700, "parse error");
2844+ return;
2845+ }
2846+ method = ju_str(root, "method");
2847+ id_raw = id_raw_of(root);
2848+ params = yyjson_obj_get(root, "params");
2849+
2850+ if (!method) {
2851+ if (id_raw) send_error(id_raw, -32600, "missing method");
2852+ free(id_raw);
2853+ yyjson_doc_free(doc);
2854+ return;
2855+ }
2856+
2857+ if (!strcmp(method, "initialize")) {
2858+ buf_t b;
2859+ const char *want = ju_str(params, "protocolVersion");
2860+ buf_init(&b);
2861+ buf_puts(&b, "{\"protocolVersion\":");
2862+ /* Answer the client's version when it is one we speak, else ours:
2863+ * 2024-11-05 is what scorpiox-connector-mcp asks for. */
2864+ json_str(&b, (want && (!strcmp(want, "2024-11-05") || !strcmp(want, "2025-03-26") ||
2865+ !strcmp(want, "2025-06-18"))) ? want : MCP_PROTO);
2866+ buf_puts(&b, ",\"capabilities\":{\"tools\":{\"listChanged\":false}},\"serverInfo\":{");
2867+ buf_puts(&b, "\"name\":\"");
2868+ buf_puts(&b, PLUGIN_ID);
2869+ buf_puts(&b, "\",\"version\":\"");
2870+ buf_puts(&b, PLUGIN_VER);
2871+ buf_puts(&b, "\"},\"instructions\":");
2872+ json_str(&b,
2873+ "Sandboxed filesystem tools. Every path is canonicalised and "
2874+ "must resolve inside the allowed roots; traversal and symlink "
2875+ "escapes are refused. Call list_allowed_directories first if "
2876+ "a path is refused.");
2877+ buf_putc(&b, '}');
2878+ send_result(id_raw, b.p);
2879+ buf_free(&b);
2880+ } else if (!strncmp(method, "notifications/", 14) || !strcmp(method, "ping")) {
2881+ if (id_raw && !strcmp(method, "ping")) send_result(id_raw, "{}");
2882+ } else if (!strcmp(method, "tools/list")) {
2883+ if (id_raw) {
2884+ init_roots();
2885+ emit_tools_list(id_raw);
2886+ }
2887+ } else if (!strcmp(method, "tools/call")) {
2888+ init_roots();
2889+ handle_tools_call(id_raw, params);
2890+ } else if (!strcmp(method, "resources/list")) {
2891+ if (id_raw) send_result(id_raw, "{\"resources\":[]}");
2892+ } else if (!strcmp(method, "resources/templates/list")) {
2893+ if (id_raw) send_result(id_raw, "{\"resourceTemplates\":[]}");
2894+ } else if (!strcmp(method, "prompts/list")) {
2895+ if (id_raw) send_result(id_raw, "{\"prompts\":[]}");
2896+ } else if (!strcmp(method, "logging/setLevel")) {
2897+ if (id_raw) send_result(id_raw, "{}");
2898+ } else {
2899+ if (id_raw) send_error(id_raw, -32601, "method not found");
2900+ }
2901+
2902+ free(id_raw);
2903+ yyjson_doc_free(doc);
2904+}
2905+
2906+/* Read one request. Newline-delimited, with Content-Length framing accepted
2907+ * because a handful of clients emit LSP headers instead of newlines. */
2908+static int read_request_line(buf_t *line)
2909+{
2910+ static char rb[IO_CHUNK];
2911+ static size_t rn, rp;
2912+ long long want = -1;
2913+
2914+ line->n = 0;
2915+ for (;;) {
2916+ if (rp < rn) {
2917+ size_t i = rp;
2918+ int nl = 0;
2919+ while (i < rn && rb[i] != '\n') i++;
2920+ if (i < rn) nl = 1;
2921+ {
2922+ size_t take = i - rp;
2923+ char tmp[IO_CHUNK + 1]; /* +1: the terminator below */
2924+ if (take > 0) memcpy(tmp, rb + rp, take);
2925+ rp = i + (nl ? 1 : 0);
2926+ tmp[take] = '\0';
2927+ while (take > 0 && (tmp[take - 1] == '\r' || tmp[take - 1] == ' '))
2928+ tmp[--take] = '\0';
2929+ if (want < 0 && !strncmp(tmp, "Content-Length:", 15)) {
2930+ want = strtoll(tmp + 15, NULL, 10);
2931+ continue;
2932+ }
2933+ if (want < 0 && take == 0) continue; /* header blank */
2934+ buf_add(line, tmp, take);
2935+ if (want < 0) {
2936+ /* Newline-delimited: a chunk without '\n' is not a line,
2937+ * it is the front half of one. Only return when the
2938+ * terminator was actually seen (or at EOF below). */
2939+ if (nl) return 1;
2940+ continue;
2941+ }
2942+ if ((long long)line->n >= want) { /* framed body */
2943+ if (line->p && (size_t)want < line->cap) line->p[want] = '\0';
2944+ line->n = (size_t)want;
2945+ want = -1;
2946+ return 1;
2947+ }
2948+ buf_putc(line, '\n');
2949+ continue;
2950+ }
2951+ }
2952+ if (rp >= rn) { rn = 0; rp = 0; }
2953+ rn = fread(rb, 1, sizeof rb, stdin);
2954+ if (rn == 0) return line->n ? 1 : 0;
2955+ }
2956+}
2957+
2958+static int mode_mcp(void)
2959+{
2960+ buf_t line;
2961+#if defined(_WIN32)
2962+ _setmode(_fileno(stdout), O_BINARY); /* \n stays \n, no CRLF */
2963+ _setmode(_fileno(stdin), O_BINARY);
2964+#endif
2965+ buf_init(&line);
2966+ while (read_request_line(&line)) {
2967+ if (line.n > MCP_LINE_CAP) {
2968+ log_err("request line exceeds %d bytes; dropping", (int)MCP_LINE_CAP);
2969+ send_error(NULL, -32600, "request too large");
2970+ continue;
2971+ }
2972+ if (line.n) handle_line(line.p);
2973+ }
2974+ buf_free(&line);
2975+ return 0;
2976+}
2977+
2978+/* ------------------------------------------------------------------ */
2979+/* Config persistence (the Setup UI writes what --mcp reads) */
2980+/* ------------------------------------------------------------------ */
2981+
2982+/* Atomic like write_file: same tmp+rename discipline, because a half-written
2983+ * roots.json would silently widen or narrow the sandbox. */
2984+static int save_roots_file(void)
2985+{
2986+ char dir[PATH_SZ], tmp[PATH_SZ];
2987+ buf_t b;
2988+ FILE *f;
2989+ int i;
2990+
2991+ connectors_dir(dir, sizeof dir);
2992+ if (mkpath(dir) != 0) return -1;
2993+ snprintf(tmp, sizeof tmp, "%s", g_roots_file);
2994+ if (strlen(tmp) + 12 >= sizeof tmp) return -1;
2995+ str_copy(tmp + strlen(tmp), sizeof tmp - strlen(tmp), ".tmp");
2996+
2997+ buf_init(&b);
2998+ buf_puts(&b, "{\n \"roots\": [");
2999+ for (i = 0; i < g_root_count; i++) {
3000+ if (i) buf_putc(&b, ',');
3001+ buf_puts(&b, "\n ");
3002+ json_str(&b, g_roots[i].configured[0] ? g_roots[i].configured
3003+ : g_roots[i].canonical);
3004+ }
3005+ buf_puts(&b, g_root_count ? "\n ],\n" : "],\n");
3006+ buf_puts(&b, " \"denied\": [");
3007+ for (i = 0; i < deny_count; i++) {
3008+ if (i) buf_putc(&b, ',');
3009+ buf_puts(&b, "\n ");
3010+ json_str(&b, g_deny[i]);
3011+ }
3012+ buf_puts(&b, deny_count ? "\n ],\n" : "],\n");
3013+ buf_puts(&b, " \"permissions\": {\n");
3014+ for (i = 0; i < TOOLS_N; i++) {
3015+ buf_printf(&b, " \"%s\": %s%s\n", TOOL_NAMES[i],
3016+ g_tool_off[i] ? "false" : "true",
3017+ i + 1 < TOOLS_N ? "," : "");
3018+ }
3019+ buf_puts(&b, " }\n}\n");
3020+
3021+ f = fopen(tmp, "wb");
3022+ if (!f) { buf_free(&b); return -1; }
3023+ if (b.n && fwrite(b.p, 1, b.n, f) != b.n) {
3024+ fclose(f);
3025+#if defined(_WIN32)
3026+ DeleteFileA(tmp);
3027+#else
3028+ remove(tmp);
3029+#endif
3030+ buf_free(&b);
3031+ return -1;
3032+ }
3033+ fclose(f);
3034+#if defined(_WIN32)
3035+ MoveFileExA(g_roots_file, tmp, 0); /* keep a copy for rollback */
3036+ if (!MoveFileExA(tmp, g_roots_file, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
3037+ buf_free(&b);
3038+ return -1;
3039+ }
3040+#else
3041+ if (rename(tmp, g_roots_file) != 0) {
3042+ remove(tmp);
3043+ buf_free(&b);
3044+ return -1;
3045+ }
3046+#endif
3047+ buf_free(&b);
3048+ return 0;
3049+}
3050+
3051+static void ensure_roots_file_path(void)
3052+{
3053+ if (g_roots_file[0]) return;
3054+ init_roots();
3055+ if (g_roots_file[0]) return;
3056+ {
3057+ char dir[PATH_SZ];
3058+ connectors_dir(dir, sizeof dir);
3059+ snprintf(g_roots_file, sizeof g_roots_file, "%s", dir);
3060+ {
3061+ size_t dl = strlen(g_roots_file);
3062+ if (dl + 12 < sizeof g_roots_file) {
3063+ g_roots_file[dl] = SEP;
3064+ g_roots_file[dl + 1] = '\0';
3065+ str_copy(g_roots_file + dl + 1, sizeof g_roots_file - dl - 1, "roots.json");
3066+ }
3067+ }
3068+ }
3069+}
3070+
3071+static void json_header(void)
3072+{
3073+ fputs("Content-Type: application/json; charset=utf-8\r\n"
3074+ "Cache-Control: no-store\r\n"
3075+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
3076+}
3077+
3078+static void json_err(int code, const char *msg)
3079+{
3080+ if (code == 400) fputs("Status: 400 Bad Request\r\n", stdout);
3081+ else if (code == 403) fputs("Status: 403 Forbidden\r\n", stdout);
3082+ else if (code == 404) fputs("Status: 404 Not Found\r\n", stdout);
3083+ else if (code == 409) fputs("Status: 409 Conflict\r\n", stdout);
3084+ else fputs("Status: 500 Internal Server Error\r\n", stdout);
3085+ json_header();
3086+ printf("{\"ok\":false,\"error\":");
3087+ {
3088+ buf_t b;
3089+ buf_init(&b);
3090+ json_str(&b, msg ? msg : "error");
3091+ fputs(buf_str(&b), stdout);
3092+ buf_free(&b);
3093+ }
3094+ fputs("}\n", stdout);
3095+}
3096+
3097+/* ------------------------------------------------------------------ */
3098+/* CGI actions */
3099+/* ------------------------------------------------------------------ */
3100+
3101+static void do_status(void)
3102+{
3103+ int i;
3104+ json_header();
3105+ printf("{\"ok\":true,\"plugin\":\"%s\",\"version\":\"%s\",\"kind\":\"mcp\","
3106+ "\"mcp\":true,\"verified\":\"live\",\"protocol\":\"%s\",\"tools\":%d,"
3107+ "\"roots_file\":", PLUGIN_ID, PLUGIN_VER, MCP_PROTO, TOOLS_N);
3108+ {
3109+ buf_t b;
3110+ buf_init(&b);
3111+ ensure_roots_file_path();
3112+ json_str(&b, g_roots_file);
3113+ printf("%s", buf_str(&b));
3114+ buf_free(&b);
3115+ }
3116+ printf(",\"config_source\":%s",
3117+ getenv("FS_ALLOWED_ROOTS") ? "\"env:FS_ALLOWED_ROOTS\"" :
3118+ (g_root_count ? "\"roots.json-or-defaults\"" : "\"none\""));
3119+ printf(",\"writable\":%s",
3120+ (g_roots_file[0] && access(g_roots_file, 2) == 0) ||
3121+ (!g_roots_file[0]) ? "true" : "false");
3122+ printf(",\"roots\":[");
3123+ for (i = 0; i < g_root_count; i++) {
3124+ printf("%s{\"configured\":", i ? "," : "");
3125+ {
3126+ buf_t b;
3127+ buf_init(&b);
3128+ json_str(&b, g_roots[i].configured);
3129+ printf("%s", buf_str(&b));
3130+ buf_free(&b);
3131+ }
3132+ printf(",\"canonical\":");
3133+ {
3134+ buf_t b;
3135+ buf_init(&b);
3136+ json_str(&b, g_roots[i].canonical);
3137+ printf("%s", buf_str(&b));
3138+ buf_free(&b);
3139+ }
3140+ printf(",\"exists\":%s,\"is_dir\":%s,\"drift\":%s}",
3141+ g_roots[i].exists ? "true" : "false",
3142+ g_roots[i].is_dir ? "true" : "false",
3143+ strcmp(g_roots[i].configured, g_roots[i].canonical) ? "true" : "false");
3144+ }
3145+ printf("],\"denied\":[");
3146+ for (i = 0; i < deny_count; i++) {
3147+ buf_t b;
3148+ buf_init(&b);
3149+ json_str(&b, g_deny[i]);
3150+ printf("%s%s", i ? "," : "", buf_str(&b));
3151+ buf_free(&b);
3152+ }
3153+ printf("],\"permissions\":{");
3154+ for (i = 0; i < TOOLS_N; i++)
3155+ printf("%s\"%s\":%s", i ? "," : "", TOOL_NAMES[i],
3156+ g_tool_off[i] ? "false" : "true");
3157+ printf("}}\n");
3158+}
3159+
3160+static void do_roots(void)
3161+{
3162+ int i;
3163+ json_header();
3164+ printf("{\"ok\":true,\"count\":%d,\"roots\":[", g_root_count);
3165+ for (i = 0; i < g_root_count; i++) {
3166+ const char *base = strrchr(g_roots[i].canonical, '/');
3167+ char label[NAME_SZ];
3168+ buf_t b;
3169+ if (i) buf_putc(&b, ',');
3170+ buf_init(&b);
3171+ buf_puts(&b, "\n {\"path\":");
3172+ json_str(&b, g_roots[i].canonical);
3173+ buf_puts(&b, ",\"configured\":");
3174+ json_str(&b, g_roots[i].configured);
3175+ buf_puts(&b, ",\"name\":");
3176+ if (base && base[1]) str_copy(label, sizeof label, base + 1);
3177+ else str_copy(label, sizeof label, g_roots[i].canonical);
3178+ json_str(&b, label);
3179+ buf_printf(&b, ",\"exists\":%s,\"is_dir\":%s}",
3180+ g_roots[i].exists ? "true" : "false",
3181+ g_roots[i].is_dir ? "true" : "false");
3182+ fputs(buf_str(&b), stdout);
3183+ buf_free(&b);
3184+ }
3185+ printf("\n]}\n");
3186+}
3187+
3188+static void do_roots_add(const char *path)
3189+{
3190+ int before = g_root_count;
3191+ char canon[PATH_SZ];
3192+ if (!path || !*path) { json_err(400, "path is required"); return; }
3193+ if (!path_shape_ok(path)) {
3194+ json_err(400, "path must be absolute and must not contain '..'");
3195+ return;
3196+ }
3197+ if (!canon_path(path, canon, sizeof canon)) {
3198+ json_err(404, "that directory does not exist yet");
3199+ return;
3200+ }
3201+ if (denied_path(canon)) { json_err(403, "that path is on the deny list"); return; }
3202+ add_root_raw(path);
3203+ if (g_root_count == before) { json_err(409, "that directory is already allowed"); return; }
3204+ ensure_roots_file_path();
3205+ if (save_roots_file() != 0) { json_err(500, "could not write roots.json"); return; }
3206+ json_header();
3207+ printf("{\"ok\":true,\"added\":");
3208+ {
3209+ buf_t b;
3210+ buf_init(&b);
3211+ json_str(&b, canon);
3212+ printf("%s", buf_str(&b));
3213+ buf_free(&b);
3214+ }
3215+ printf(",\"count\":%d}\n", g_root_count);
3216+}
3217+
3218+static void do_roots_remove(const char *path)
3219+{
3220+ char canon[PATH_SZ];
3221+ int i, j, found = 0;
3222+
3223+ if (!path || !*path) { json_err(400, "path is required"); return; }
3224+ if (canon_path(path, canon, sizeof canon)) {
3225+ /* matched below */
3226+ } else {
3227+ str_copy(canon, sizeof canon, path);
3228+ }
3229+ for (i = 0; i < g_root_count; i++) {
3230+ if (!strcmp(g_roots[i].canonical, canon) ||
3231+ !strcmp(g_roots[i].configured, path) ||
3232+ path_under_p(canon, g_roots[i].canonical)) {
3233+ for (j = i; j + 1 < g_root_count; j++) g_roots[j] = g_roots[j + 1];
3234+ g_root_count--;
3235+ found = 1;
3236+ break;
3237+ }
3238+ }
3239+ if (!found) { json_err(404, "that directory is not in the allowlist"); return; }
3240+ ensure_roots_file_path();
3241+ if (save_roots_file() != 0) { json_err(500, "could not write roots.json"); return; }
3242+ json_header();
3243+ printf("{\"ok\":true,\"removed\":true,\"count\":%d}\n", g_root_count);
3244+}
3245+
3246+static void do_permissions(void)
3247+{
3248+ int i;
3249+ json_header();
3250+ printf("{\"ok\":true,\"permissions\":{");
3251+ for (i = 0; i < TOOLS_N; i++)
3252+ printf("%s\"%s\":%s", i ? "," : "", TOOL_NAMES[i],
3253+ g_tool_off[i] ? "false" : "true");
3254+ printf("}}\n");
3255+}
3256+
3257+static void do_permissions_set(const char *qs)
3258+{
3259+ char tool[64], val[16];
3260+ int idx;
3261+
3262+ if (!get_query_val(qs, "tool", tool, sizeof tool)) {
3263+ json_err(400, "tool is required");
3264+ return;
3265+ }
3266+ idx = tool_index(tool);
3267+ if (idx < 0) { json_err(404, "unknown tool"); return; }
3268+ if (!get_query_val(qs, "enabled", val, sizeof val)) {
3269+ json_err(400, "enabled is required (true/false)");
3270+ return;
3271+ }
3272+ g_tool_off[idx] = (strcmp(val, "true") == 0 || strcmp(val, "1") == 0) ? 0 : 1;
3273+ /* list_allowed_directories is the diagnostic an operator needs when a
3274+ * path is refused, so it can never be switched off. */
3275+ if (idx == TOOLS_N - 1) g_tool_off[idx] = 0;
3276+ ensure_roots_file_path();
3277+ if (save_roots_file() != 0) { json_err(500, "could not write roots.json"); return; }
3278+ json_header();
3279+ printf("{\"ok\":true,\"tool\":");
3280+ {
3281+ buf_t b;
3282+ buf_init(&b);
3283+ json_str(&b, TOOL_NAMES[idx]);
3284+ printf("%s", buf_str(&b));
3285+ buf_free(&b);
3286+ }
3287+ printf(",\"enabled\":%s}\n", g_tool_off[idx] ? "false" : "true");
3288+}
3289+
3290+/* The sandbox boundary tester: what an operator types in, the tool sees.
3291+ * Reports both forms and the exact reason a path is refused. */
3292+static void do_sandbox_test(const char *path)
3293+{
3294+ char canon[PATH_SZ];
3295+ const char *err = NULL;
3296+ int allowed = 0;
3297+
3298+ if (!path || !*path) { json_err(400, "path is required"); return; }
3299+ allowed = resolve_allowed(path, canon, sizeof canon, 'r', &err);
3300+ if (!allowed) {
3301+ /* a write-mode answer is more useful for a path that does not exist */
3302+ char wc[PATH_SZ];
3303+ const char *werr = NULL;
3304+ if (resolve_allowed(path, wc, sizeof wc, 'w', &werr)) {
3305+ buf_t b;
3306+ json_header();
3307+ printf("{\"ok\":true,\"path\":");
3308+ buf_init(&b);
3309+ json_str(&b, path);
3310+ printf("%s,\"allowed\":true,\"mode\":\"write\",\"canonical\":", buf_str(&b));
3311+ buf_free(&b);
3312+ buf_init(&b);
3313+ json_str(&b, wc);
3314+ printf("%s}\n", buf_str(&b));
3315+ buf_free(&b);
3316+ return;
3317+ }
3318+ }
3319+ {
3320+ buf_t b;
3321+ json_header();
3322+ buf_init(&b);
3323+ json_str(&b, path);
3324+ printf("{\"ok\":true,\"path\":%s,\"allowed\":%s,\"canonical\":",
3325+ buf_str(&b), allowed ? "true" : "false");
3326+ buf_free(&b);
3327+ if (allowed) {
3328+ buf_init(&b);
3329+ json_str(&b, canon);
3330+ printf("%s,\"reason\":\"inside an allowed root\"}\n", buf_str(&b));
3331+ buf_free(&b);
3332+ } else {
3333+ buf_init(&b);
3334+ json_str(&b, canon);
3335+ printf("%s,\"reason\":", buf_str(&b));
3336+ buf_free(&b);
3337+ buf_init(&b);
3338+ json_str(&b, err ? err : "refused");
3339+ printf("%s}\n", buf_str(&b));
3340+ buf_free(&b);
3341+ }
3342+ }
3343+}
3344+
3345+static void do_tools(void)
3346+{
3347+ int i;
3348+ json_header();
3349+ printf("{\"ok\":true,\"tools\":[");
3350+ for (i = 0; i < TOOLS_N; i++) {
3351+ buf_t b;
3352+ buf_init(&b);
3353+ if (i) buf_putc(&b, ',');
3354+ buf_puts(&b, "{\"name\":");
3355+ json_str(&b, TOOLS[i].name);
3356+ buf_puts(&b, ",\"title\":");
3357+ json_str(&b, TOOLS[i].title);
3358+ buf_puts(&b, ",\"description\":");
3359+ json_str(&b, TOOLS[i].desc);
3360+ buf_printf(&b, ",\"read_only\":%s,\"destructive\":%s,\"enabled\":%s}",
3361+ TOOLS[i].read_only ? "true" : "false",
3362+ TOOLS[i].destructive ? "true" : "false",
3363+ g_tool_off[i] ? "false" : "true");
3364+ fputs(buf_str(&b), stdout);
3365+ buf_free(&b);
3366+ }
3367+ printf("]}\n");
3368+}
3369+
3370+/* ------------------------------------------------------------------ */
3371+/* HTML UI */
3372+/* ------------------------------------------------------------------ */
3373+
3374+/* Expand the two control-byte placeholders from src/ui.html into the bot
3375+ * theme macros, so the page and the bot palette can never drift. */
3376+static void emit_ui(int embed)
3377+{
3378+ const char *p = UI_HTML;
3379+
3380+ while (*p) {
3381+ if (*p == '\001') {
3382+ fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS
3383+ ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);--ac:var(--blue)}"
3384+ "</style>", stdout);
3385+ p++;
3386+ } else if (*p == '\002') {
3387+ fputs(SX_BOT_THEME_HANDOFF, stdout);
3388+ p++;
3389+ } else {
3390+ putchar(*p++);
3391+ }
3392+ }
3393+ (void)embed;
3394+}
3395+
3396+static void mode_html(int embed)
3397+{
3398+ fputs("Content-Type: text/html; charset=utf-8\r\n"
3399+ "Cache-Control: no-store\r\n"
3400+ "X-Content-Type-Options: nosniff\r\n"
3401+ "X-Frame-Options: SAMEORIGIN\r\n"
3402+ "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
3403+ "style-src 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; "
3404+ "form-action 'none'; base-uri 'none'\r\n\r\n", stdout);
3405+ emit_ui(embed);
3406+}
3407+
3408+/* ------------------------------------------------------------------ */
3409+/* main */
3410+/* ------------------------------------------------------------------ */
3411+
3412+static void print_help(void)
3413+{
3414+ printf("%s %s - SCORPIOX BOT allowlisted filesystem MCP connector\n\n"
3415+ "modes:\n"
3416+ " --meta print plugin discovery metadata and exit\n"
3417+ " --mcp serve MCP JSON-RPC 2.0 over stdin/stdout\n"
3418+ " (no args) CGI: Allowed Roots & Permissions page + ?action= API\n"
3419+ " --version print version\n\n"
3420+ "config: %s/roots.json (or FS_ALLOWED_ROOTS, colon-separated)\n"
3421+ "tools: ", PLUGIN_ID, PLUGIN_VER, " ~/.scorpiox/connectors/" PLUGIN_ID);
3422+ {
3423+ int i;
3424+ for (i = 0; i < TOOLS_N; i++)
3425+ printf("%s%s", i ? ", " : "", TOOLS[i].name);
3426+ }
3427+ printf("\n");
3428+}
3429+
3430+int main(int argc, char **argv)
3431+{
3432+ const char *qs;
3433+ char action[64];
3434+ char path[PATH_SZ];
3435+ int i;
3436+
3437+ /* 1. Discovery metadata - unauthenticated: /plugins and the connector
3438+ * router probe every installed binary, and a probe that needs the
3439+ * node password is a probe that fails. */
3440+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
3441+ fputs("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\","
3442+ "\"kind\":\"mcp\",\"mcp\":true,\"daemon\":false,\"menus\":false,"
3443+ "\"verified\":\"live\",\"version\":\"" PLUGIN_VER "\"}\n", stdout);
3444+ return 0;
3445+ }
3446+ for (i = 1; i < argc; i++) {
3447+ if (!strcmp(argv[i], "--version")) {
3448+ printf("%s %s\n", PLUGIN_ID, PLUGIN_VER);
3449+ return 0;
3450+ }
3451+ if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) {
3452+ print_help();
3453+ return 0;
3454+ }
3455+ }
3456+
3457+ /* 2. MCP stdio server - the connector mode. No CGI headers, no auth:
3458+ * the caller is the node's own MCP router, already trusted. */
3459+ if (argc > 1 && !strcmp(argv[1], "--mcp")) {
3460+ init_roots();
3461+ return mode_mcp();
3462+ }
3463+
3464+ /* 3. CGI modes below are all behind node auth. */
3465+ require_node_auth();
3466+ init_roots();
3467+
3468+ qs = getenv("QUERY_STRING");
3469+ if (!qs) qs = "";
3470+
3471+ action[0] = '\0';
3472+ path[0] = '\0';
3473+ get_query_val(qs, "action", action, sizeof action);
3474+ get_query_val(qs, "path", path, sizeof path);
3475+
3476+ if (action[0] || strstr(qs, "format=json")) {
3477+ if (!action[0]) str_copy(action, sizeof action, "status");
3478+
3479+ if (!strcmp(action, "status")) do_status();
3480+ else if (!strcmp(action, "roots")) do_roots();
3481+ else if (!strcmp(action, "roots_add")) do_roots_add(path);
3482+ else if (!strcmp(action, "roots_remove")) do_roots_remove(path);
3483+ else if (!strcmp(action, "permissions")) do_permissions();
3484+ else if (!strcmp(action, "permissions_set")) do_permissions_set(qs);
3485+ else if (!strcmp(action, "sandbox_test")) do_sandbox_test(path);
3486+ else if (!strcmp(action, "tools")) do_tools();
3487+ else json_err(400, "unknown action");
3488+ return 0;
3489+ }
3490+
3491+ /* 4. Everything else is the page. */
3492+ {
3493+ int embed = strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL;
3494+ mode_html(embed);
3495+ }
3496+ return 0;
3497+}
src/ui.html+290−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..c3413b7index 0000000..c3413b7
--- /dev/null--- /dev/null
+++ b/src/ui.html+++ b/src/ui.html
@@ -0,0 +1,290 @@@@ -0,0 +1,290 @@
1+<!DOCTYPE html>
2+<html lang="en"><head><meta charset="utf-8">
3+<meta name="viewport" content="width=device-width,initial-scale=1">
4+<title>filesystem</title>
5+<!--TOKENS-->
6+<style>
7+*{box-sizing:border-box}
8+html,body{margin:0}
9+body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;
10+ line-height:1.5;-webkit-font-smoothing:antialiased}
11+.wrap{max-width:1080px;margin:0 auto;padding:16px}
12+.card{background:var(--surface);border:1px solid var(--line);border-radius:14px;
13+ padding:16px;margin-bottom:14px}
14+h1{font-size:17px;margin:0 0 2px;letter-spacing:-.01em}
15+h2{font-size:12px;font-weight:700;letter-spacing:.09em;text-transform:uppercase;
16+ color:var(--text-2);margin:0 0 12px}
17+.sub{color:var(--text-2);font-size:12.5px;margin:0 0 14px}
18+.grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:14px}
19+@media(max-width:860px){.grid{grid-template-columns:minmax(0,1fr)}}
20+.row{display:flex;gap:8px;align-items:center}
21+.row.wraprow{flex-wrap:wrap}
22+input[type=text]{flex:1;min-width:0;background:var(--input-bg);color:var(--text);
23+ border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-family:var(--mono);
24+ font-size:12.5px;outline:none}
25+input[type=text]:focus{border-color:var(--blue)}
26+button{background:var(--surface-2);color:var(--text);border:1px solid var(--line);
27+ border-radius:9px;padding:7px 12px;font-family:inherit;font-size:12.5px;font-weight:600;
28+ cursor:pointer;flex:0 0 auto}
29+button:hover{background:var(--surface-hover);border-color:var(--line-2)}
30+button:active{transform:scale(.98)}
31+button.primary{background:var(--blue);border-color:transparent;color:#fff}
32+button.danger{color:var(--red)}
33+ul.roots{list-style:none;margin:0;padding:0}
34+ul.roots li{display:flex;align-items:center;gap:10px;padding:9px 10px;
35+ border:1px solid var(--line);border-radius:10px;margin-bottom:7px;background:var(--bg-2)}
36+ul.roots li .p{flex:1;min-width:0;font-family:var(--mono);font-size:12.5px;
37+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
38+ul.roots li .note{font-size:11px;color:var(--text-2);flex:0 0 auto}
39+ul.roots li .note.warn{color:var(--orange)}
40+ul.roots li .note.bad{color:var(--red)}
41+.pill{font-size:10.5px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;
42+ padding:2px 7px;border-radius:980px;border:1px solid var(--line);color:var(--text-2);flex:0 0 auto}
43+.pill.rw{color:var(--green);border-color:rgba(48,209,88,.35)}
44+.pill.ro{color:var(--teal);border-color:rgba(100,210,255,.35)}
45+table.tools{width:100%;border-collapse:collapse;font-size:12.5px}
46+table.tools th{text-align:left;font-size:10.5px;letter-spacing:.08em;text-transform:uppercase;
47+ color:var(--text-2);font-weight:700;padding:0 8px 6px 0;border-bottom:1px solid var(--line)}
48+table.tools td{padding:7px 8px 7px 0;border-bottom:1px solid var(--line);vertical-align:top}
49+table.tools tr:last-child td{border-bottom:0}
50+table.tools td.n{font-family:var(--mono);font-size:12px;white-space:nowrap}
51+table.tools td.d{color:var(--text-2);font-size:11.5px}
52+.sw{position:relative;width:38px;height:22px;flex:0 0 auto;border-radius:980px;
53+ background:var(--surface-2);border:1px solid var(--line);cursor:pointer;padding:0}
54+.sw[aria-checked=true]{background:var(--green);border-color:transparent}
55+.sw i{position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;
56+ background:#fff;transition:transform .16s var(--ease)}
57+.sw[aria-checked=true] i{transform:translateX(16px)}
58+pre{margin:0;background:var(--code-bg);border:1px solid var(--line);border-radius:10px;
59+ padding:10px 12px;font-family:var(--mono);font-size:11.5px;white-space:pre-wrap;
60+ word-break:break-all;max-height:220px;overflow:auto}
61+.kv{display:flex;flex-wrap:wrap;gap:6px 16px;font-size:12px;color:var(--text-2);margin:0 0 12px}
62+.kv b{color:var(--text);font-weight:600;font-family:var(--mono)}
63+.msg{font-size:12.5px;padding:8px 10px;border-radius:9px;margin:0 0 10px;display:none}
64+.msg.show{display:block}
65+.msg.ok{background:rgba(48,209,88,.12);color:var(--green);border:1px solid rgba(48,209,88,.3)}
66+.msg.err{background:rgba(255,69,58,.12);color:var(--red);border:1px solid rgba(255,69,58,.3)}
67+.msg.warn{background:rgba(255,159,10,.12);color:var(--orange);border:1px solid rgba(255,159,10,.3)}
68+a{color:var(--blue);text-decoration:none}
69+.hint{font-size:11.5px;color:var(--text-2);margin:8px 0 0}
70+.nomargin{margin-bottom:0}
71+</style>
72+</head><body>
73+<div class="wrap">
74+
75+<div class="card">
76+ <h1>filesystem</h1>
77+ <p class="sub">Allowlisted filesystem tools for your node, over MCP. Every path is
78+ canonicalised on disk and must land inside a directory you list here. Nothing
79+ outside them is readable or writable, and symlinks that point out are refused.</p>
80+ <div class="kv" id="kv">
81+ <span>plugin <b>plugin_filesystem</b></span>
82+ <span>version <b id="kver">–</b></span>
83+ <span>kind <b>mcp</b></span>
84+ <span>config <b id="kfile">–</b></span>
85+ </div>
86+ <div class="msg" id="msg"></div>
87+ <div class="hint">Server-rendered summary below; the controls need JavaScript and the
88+ node password the bot already holds.</div>
89+ <pre id="noscript">Allowed roots and permissions are read from
90+~/.scorpiox/connectors/plugin_filesystem/roots.json
91+(override with the FS_ALLOWED_ROOTS environment variable).</pre>
92+</div>
93+
94+<div class="grid">
95+
96+ <div class="card">
97+ <h2>Allowed directories</h2>
98+ <ul class="roots" id="roots"><li><span class="p">loading…</span></li></ul>
99+ <div class="row" style="margin-top:10px">
100+ <input type="text" id="newroot" placeholder="/absolute/path/to/a/directory"
101+ autocomplete="off" spellcheck="false">
102+ <button class="primary" id="btnadd">Allow</button>
103+ </div>
104+ <p class="hint">Absolute paths only, no <code>..</code>. A directory that does not
105+ exist yet is refused here so a typo cannot quietly widen the sandbox. Paths shown
106+ in orange resolve elsewhere (a symlink or a mount) — the canonical form is what the
107+ tools check.</p>
108+ </div>
109+
110+ <div class="card">
111+ <h2>Tool permissions</h2>
112+ <table class="tools"><thead><tr><th>Tool</th><th></th></tr></thead>
113+ <tbody id="tools"><tr><td class="d" colspan="2">loading…</td></tr></tbody></table>
114+ <p class="hint">Disabled tools answer with a refusal instead of running, so an agent
115+ gets an explanation rather than a missing tool. <b>list_allowed_directories</b>
116+ cannot be switched off — it is how you diagnose a refusal.</p>
117+ </div>
118+
119+</div>
120+
121+<div class="card">
122+ <h2>Sandbox boundary test</h2>
123+ <div class="row wraprow">
124+ <input type="text" id="testpath" placeholder="/absolute/path/you/want/to/check"
125+ autocomplete="off" spellcheck="false">
126+ <button id="btntest">Test path</button>
127+ </div>
128+ <div id="testout" style="margin-top:10px"></div>
129+ <p class="hint">Reports exactly what a tool would see: allowed or not, the canonical
130+ path, and the rule that refused it. Use it before blaming a tool for a path that
131+ was never in scope.</p>
132+</div>
133+
134+<div class="card">
135+ <h2>Register with the connector router</h2>
136+ <pre id="snippet">{}</pre>
137+ <p class="hint">The node's single <b>sx-connector-mcp</b> router reads this file and
138+ exposes every installed MCP connector through four meta-tools, so the agent's tool
139+ budget stays flat no matter how many connectors you install.</p>
140+</div>
141+
142+</div>
143+<script>
144+var q=new URLSearchParams(location.search);
145+var node=q.get('node')||'';
146+var sid=q.get('id')||'';
147+var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||
148+ localStorage.getItem('bot_active_pwd')||'';
149+var HUB=q.get('plugin')||'';
150+
151+/* Two call routes; this is the most common plugin bug.
152+ * served through the hub (/plugins?plugin=plugin_filesystem&node=..)
153+ * -> call the hub proxy back: /plugins?plugin=..&action=..
154+ * opened directly on the node
155+ * -> the plugin IS the route: /plugin_filesystem?action=..
156+ * Calling /plugins?plugin= on the node returns the discovery list, not us. */
157+function url(action,extra){
158+ return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_filesystem')+
159+ '?action='+encodeURIComponent(action)+
160+ (extra?('&'+extra):'')+
161+ (node?'&node='+encodeURIComponent(node):'')+
162+ (sid?'&id='+encodeURIComponent(sid):'')+
163+ (pwd?'&pwd='+encodeURIComponent(pwd):'');
164+}
165+function api(action,extra){
166+ var h=pwd?{'X-Bot-Password':pwd}:{};
167+ return fetch(url(action,extra),{headers:h}).then(function(r){
168+ return r.json().then(function(j){return {status:r.status,body:j};});
169+ });
170+}
171+var msgEl=document.getElementById('msg');
172+function say(text,kind){
173+ msgEl.textContent=text;
174+ msgEl.className='msg show '+(kind||'ok');
175+ clearTimeout(say._t);
176+ say._t=setTimeout(function(){msgEl.className='msg';},4200);
177+}
178+function esc(s){
179+ return String(s==null?'':s).replace(/[&<>"]/g,function(c){
180+ return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c];
181+ });
182+}
183+
184+function renderStatus(st){
185+ document.getElementById('kver').textContent=st.version||'';
186+ document.getElementById('kfile').textContent=st.roots_file||'';
187+ document.getElementById('noscript').textContent=
188+ 'config: '+(st.roots_file||'(not yet written)')+'\n'+
189+ 'source: '+(st.config_source||'')+'\n'+
190+ 'roots: '+((st.roots||[]).length
191+ ? (st.roots||[]).map(function(r){return r.canonical;}).join('\n ')
192+ : '(none - nothing is reachable)');
193+ document.getElementById('snippet').textContent=JSON.stringify(
194+ {mcpServers:{filesystem:{
195+ command:'~/.scorpiox/plugins/plugin_filesystem',
196+ args:['--mcp'],
197+ slug:'filesystem'}}},null,2);
198+}
199+function renderRoots(roots){
200+ var ul=document.getElementById('roots');
201+ ul.innerHTML='';
202+ if(!roots||!roots.length){
203+ ul.innerHTML='<li><span class="p">No allowed directories — the plugin can read and '+
204+ 'write nothing. Add one below.</span></li>';
205+ return;
206+ }
207+ roots.forEach(function(r){
208+ var li=document.createElement('li');
209+ var note='',cls='';
210+ if(!r.exists){note='missing';cls='bad';}
211+ else if(!r.is_dir){note='not a directory';cls='bad';}
212+ else if(r.drift){note='→ '+r.canonical;cls='warn';}
213+ li.innerHTML='<span class="p" title="'+esc(r.canonical)+'">'+esc(r.configured||r.canonical)+
214+ '</span>'+(note?'<span class="note '+cls+'">'+esc(note)+'</span>':'')+
215+ '<button class="danger" data-rm="'+esc(r.canonical)+'">Remove</button>';
216+ ul.appendChild(li);
217+ });
218+ Array.prototype.forEach.call(ul.querySelectorAll('[data-rm]'),function(b){
219+ b.addEventListener('click',function(){
220+ api('roots_remove','path='+encodeURIComponent(b.getAttribute('data-rm'))).then(function(x){
221+ if(x.body&&x.body.ok){say('Removed '+b.getAttribute('data-rm'));refresh();}
222+ else say((x.body&&x.body.error)||('HTTP '+x.status),'err');
223+ });
224+ });
225+ });
226+}
227+function renderTools(tools){
228+ var tb=document.getElementById('tools');
229+ tb.innerHTML='';
230+ tools.forEach(function(t){
231+ var tr=document.createElement('tr');
232+ tr.innerHTML='<td class="n">'+esc(t.name)+'</td>'+
233+ '<td class="d">'+esc(t.read_only?'read-only':(t.destructive?'writes':'creates'))+'</td>'+
234+ '<td class="d">'+esc(t.description.slice(0,64))+'…</td>'+
235+ '<td style="text-align:right"><button class="sw" role="switch" data-t="'+esc(t.name)+
236+ '" aria-checked="'+(t.enabled?'true':'false')+'"><i></i></button></td>';
237+ tb.appendChild(tr);
238+ });
239+ Array.prototype.forEach.call(tb.querySelectorAll('.sw'),function(b){
240+ b.addEventListener('click',function(){
241+ var on=b.getAttribute('aria-checked')!=='true';
242+ api('permissions_set','tool='+encodeURIComponent(b.getAttribute('data-t'))+
243+ '&enabled='+(on?'true':'false')).then(function(x){
244+ if(x.body&&x.body.ok){b.setAttribute('aria-checked',on?'true':'false');
245+ say((on?'Enabled ':'Disabled ')+b.getAttribute('data-t'));}
246+ else say((x.body&&x.body.error)||('HTTP '+x.status),'err');
247+ });
248+ });
249+ });
250+}
251+function renderTest(x){
252+ var el=document.getElementById('testout');
253+ if(!x||!x.body||!x.body.ok){el.innerHTML='';return;}
254+ var b=x.body;
255+ el.innerHTML='<div class="msg show '+(b.allowed?'ok':'warn')+'">'+
256+ (b.allowed?'ALLOWED':'REFUSED')+' — '+esc(b.path)+
257+ (b.canonical?(' → <span style="font-family:var(--mono)">'+esc(b.canonical)+'</span>'):'')+
258+ ' — '+esc(b.reason||'')+'</div>';
259+}
260+function refresh(){
261+ api('status').then(function(x){
262+ if(!x.body||!x.body.ok){say((x.body&&x.body.error)||('HTTP '+x.status),'err');return;}
263+ renderStatus(x.body);
264+ });
265+ api('roots').then(function(x){if(x.body&&x.body.ok)renderRoots(x.body.roots);});
266+ api('tools').then(function(x){if(x.body&&x.body.ok)renderTools(x.body.tools);});
267+}
268+document.getElementById('btnadd').addEventListener('click',function(){
269+ var v=document.getElementById('newroot').value.trim();
270+ if(!v){say('Type a directory path first','warn');return;}
271+ api('roots_add','path='+encodeURIComponent(v)).then(function(x){
272+ if(x.body&&x.body.ok){say('Allowed '+x.body.added);
273+ document.getElementById('newroot').value='';refresh();}
274+ else say((x.body&&x.body.error)||('HTTP '+x.status),'err');
275+ });
276+});
277+document.getElementById('newroot').addEventListener('keydown',function(e){
278+ if(e.key==='Enter')document.getElementById('btnadd').click();
279+});
280+document.getElementById('btntest').addEventListener('click',function(){
281+ var v=document.getElementById('testpath').value.trim();
282+ if(!v){say('Type a path to test','warn');return;}
283+ api('sandbox_test','path='+encodeURIComponent(v)).then(function(x){renderTest(x);});
284+});
285+document.getElementById('testpath').addEventListener('keydown',function(e){
286+ if(e.key==='Enter')document.getElementById('btntest').click();
287+});
288+refresh();
289+</script>
290+</body></html>
src/ui_html.h+298−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..6f72beeindex 0000000..6f72bee
--- /dev/null--- /dev/null
+++ b/src/ui_html.h+++ b/src/ui_html.h
@@ -0,0 +1,298 @@@@ -0,0 +1,298 @@
1+/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */
2+#ifndef SX_FILESYSTEM_UI_HTML_H
3+#define SX_FILESYSTEM_UI_HTML_H
4+
5+static const char *UI_HTML =
6+ "<!DOCTYPE html>\n"
7+ "<html lang=\"en\"><head><meta charset=\"utf-8\">\n"
8+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n"
9+ "<title>filesystem</title>\n"
10+ "\001\n"
11+ "<style>\n"
12+ "*{box-sizing:border-box}\n"
13+ "html,body{margin:0}\n"
14+ "body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;\n"
15+ " line-height:1.5;-webkit-font-smoothing:antialiased}\n"
16+ ".wrap{max-width:1080px;margin:0 auto;padding:16px}\n"
17+ ".card{background:var(--surface);border:1px solid var(--line);border-radius:14px;\n"
18+ " padding:16px;margin-bottom:14px}\n"
19+ "h1{font-size:17px;margin:0 0 2px;letter-spacing:-.01em}\n"
20+ "h2{font-size:12px;font-weight:700;letter-spacing:.09em;text-transform:uppercase;\n"
21+ " color:var(--text-2);margin:0 0 12px}\n"
22+ ".sub{color:var(--text-2);font-size:12.5px;margin:0 0 14px}\n"
23+ ".grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:14px}\n"
24+ "@media(max-width:860px){.grid{grid-template-columns:minmax(0,1fr)}}\n"
25+ ".row{display:flex;gap:8px;align-items:center}\n"
26+ ".row.wraprow{flex-wrap:wrap}\n"
27+ "input[type=text]{flex:1;min-width:0;background:var(--input-bg);color:var(--text);\n"
28+ " border:1px solid var(--line);border-radius:9px;padding:8px 10px;font-family:var(--mono);\n"
29+ " font-size:12.5px;outline:none}\n"
30+ "input[type=text]:focus{border-color:var(--blue)}\n"
31+ "button{background:var(--surface-2);color:var(--text);border:1px solid var(--line);\n"
32+ " border-radius:9px;padding:7px 12px;font-family:inherit;font-size:12.5px;font-weight:600;\n"
33+ " cursor:pointer;flex:0 0 auto}\n"
34+ "button:hover{background:var(--surface-hover);border-color:var(--line-2)}\n"
35+ "button:active{transform:scale(.98)}\n"
36+ "button.primary{background:var(--blue);border-color:transparent;color:#fff}\n"
37+ "button.danger{color:var(--red)}\n"
38+ "ul.roots{list-style:none;margin:0;padding:0}\n"
39+ "ul.roots li{display:flex;align-items:center;gap:10px;padding:9px 10px;\n"
40+ " border:1px solid var(--line);border-radius:10px;margin-bottom:7px;background:var(--bg-2)}\n"
41+ "ul.roots li .p{flex:1;min-width:0;font-family:var(--mono);font-size:12.5px;\n"
42+ " overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n"
43+ "ul.roots li .note{font-size:11px;color:var(--text-2);flex:0 0 auto}\n"
44+ "ul.roots li .note.warn{color:var(--orange)}\n"
45+ "ul.roots li .note.bad{color:var(--red)}\n"
46+ ".pill{font-size:10.5px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;\n"
47+ " padding:2px 7px;border-radius:980px;border:1px solid var(--line);color:var(--text-2);flex:0 0 auto}\n"
48+ ".pill.rw{color:var(--green);border-color:rgba(48,209,88,.35)}\n"
49+ ".pill.ro{color:var(--teal);border-color:rgba(100,210,255,.35)}\n"
50+ "table.tools{width:100%;border-collapse:collapse;font-size:12.5px}\n"
51+ "table.tools th{text-align:left;font-size:10.5px;letter-spacing:.08em;text-transform:uppercase;\n"
52+ " color:var(--text-2);font-weight:700;padding:0 8px 6px 0;border-bottom:1px solid var(--line)}\n"
53+ "table.tools td{padding:7px 8px 7px 0;border-bottom:1px solid var(--line);vertical-align:top}\n"
54+ "table.tools tr:last-child td{border-bottom:0}\n"
55+ "table.tools td.n{font-family:var(--mono);font-size:12px;white-space:nowrap}\n"
56+ "table.tools td.d{color:var(--text-2);font-size:11.5px}\n"
57+ ".sw{position:relative;width:38px;height:22px;flex:0 0 auto;border-radius:980px;\n"
58+ " background:var(--surface-2);border:1px solid var(--line);cursor:pointer;padding:0}\n"
59+ ".sw[aria-checked=true]{background:var(--green);border-color:transparent}\n"
60+ ".sw i{position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;\n"
61+ " background:#fff;transition:transform .16s var(--ease)}\n"
62+ ".sw[aria-checked=true] i{transform:translateX(16px)}\n"
63+ "pre{margin:0;background:var(--code-bg);border:1px solid var(--line);border-radius:10px;\n"
64+ " padding:10px 12px;font-family:var(--mono);font-size:11.5px;white-space:pre-wrap;\n"
65+ " word-break:break-all;max-height:220px;overflow:auto}\n"
66+ ".kv{display:flex;flex-wrap:wrap;gap:6px 16px;font-size:12px;color:var(--text-2);margin:0 0 12px}\n"
67+ ".kv b{color:var(--text);font-weight:600;font-family:var(--mono)}\n"
68+ ".msg{font-size:12.5px;padding:8px 10px;border-radius:9px;margin:0 0 10px;display:none}\n"
69+ ".msg.show{display:block}\n"
70+ ".msg.ok{background:rgba(48,209,88,.12);color:var(--green);border:1px solid rgba(48,209,88,.3)}\n"
71+ ".msg.err{background:rgba(255,69,58,.12);color:var(--red);border:1px solid rgba(255,69,58,.3)}\n"
72+ ".msg.warn{background:rgba(255,159,10,.12);color:var(--orange);border:1px solid rgba(255,159,10,.3)}\n"
73+ "a{color:var(--blue);text-decoration:none}\n"
74+ ".hint{font-size:11.5px;color:var(--text-2);margin:8px 0 0}\n"
75+ ".nomargin{margin-bottom:0}\n"
76+ "</style>\n"
77+ "</head><body>\n"
78+ "<div class=\"wrap\">\n"
79+ "\n"
80+ "<div class=\"card\">\n"
81+ " <h1>filesystem</h1>\n"
82+ " <p class=\"sub\">Allowlisted filesystem tools for your node, over MCP. Every path is\n"
83+ " canonicalised on disk and must land inside a directory you list here. Nothing\n"
84+ " outside them is readable or writable, and symlinks that point out are refused.</p>\n"
85+ " <div class=\"kv\" id=\"kv\">\n"
86+ " <span>plugin <b>plugin_filesystem</b></span>\n"
87+ " <span>version <b id=\"kver\">–</b></span>\n"
88+ " <span>kind <b>mcp</b></span>\n"
89+ " <span>config <b id=\"kfile\">–</b></span>\n"
90+ " </div>\n"
91+ " <div class=\"msg\" id=\"msg\"></div>\n"
92+ " <div class=\"hint\">Server-rendered summary below; the controls need JavaScript and the\n"
93+ " node password the bot already holds.</div>\n"
94+ " <pre id=\"noscript\">Allowed roots and permissions are read from\n"
95+ "~/.scorpiox/connectors/plugin_filesystem/roots.json\n"
96+ "(override with the FS_ALLOWED_ROOTS environment variable).</pre>\n"
97+ "</div>\n"
98+ "\n"
99+ "<div class=\"grid\">\n"
100+ "\n"
101+ " <div class=\"card\">\n"
102+ " <h2>Allowed directories</h2>\n"
103+ " <ul class=\"roots\" id=\"roots\"><li><span class=\"p\">loading…</span></li></ul>\n"
104+ " <div class=\"row\" style=\"margin-top:10px\">\n"
105+ " <input type=\"text\" id=\"newroot\" placeholder=\"/absolute/path/to/a/directory\"\n"
106+ " autocomplete=\"off\" spellcheck=\"false\">\n"
107+ " <button class=\"primary\" id=\"btnadd\">Allow</button>\n"
108+ " </div>\n"
109+ " <p class=\"hint\">Absolute paths only, no <code>..</code>. A directory that does not\n"
110+ " exist yet is refused here so a typo cannot quietly widen the sandbox. Paths shown\n"
111+ " in orange resolve elsewhere (a symlink or a mount) — the canonical form is what the\n"
112+ " tools check.</p>\n"
113+ " </div>\n"
114+ "\n"
115+ " <div class=\"card\">\n"
116+ " <h2>Tool permissions</h2>\n"
117+ " <table class=\"tools\"><thead><tr><th>Tool</th><th></th></tr></thead>\n"
118+ " <tbody id=\"tools\"><tr><td class=\"d\" colspan=\"2\">loading…</td></tr></tbody></table>\n"
119+ " <p class=\"hint\">Disabled tools answer with a refusal instead of running, so an agent\n"
120+ " gets an explanation rather than a missing tool. <b>list_allowed_directories</b>\n"
121+ " cannot be switched off — it is how you diagnose a refusal.</p>\n"
122+ " </div>\n"
123+ "\n"
124+ "</div>\n"
125+ "\n"
126+ "<div class=\"card\">\n"
127+ " <h2>Sandbox boundary test</h2>\n"
128+ " <div class=\"row wraprow\">\n"
129+ " <input type=\"text\" id=\"testpath\" placeholder=\"/absolute/path/you/want/to/check\"\n"
130+ " autocomplete=\"off\" spellcheck=\"false\">\n"
131+ " <button id=\"btntest\">Test path</button>\n"
132+ " </div>\n"
133+ " <div id=\"testout\" style=\"margin-top:10px\"></div>\n"
134+ " <p class=\"hint\">Reports exactly what a tool would see: allowed or not, the canonical\n"
135+ " path, and the rule that refused it. Use it before blaming a tool for a path that\n"
136+ " was never in scope.</p>\n"
137+ "</div>\n"
138+ "\n"
139+ "<div class=\"card\">\n"
140+ " <h2>Register with the connector router</h2>\n"
141+ " <pre id=\"snippet\">{}</pre>\n"
142+ " <p class=\"hint\">The node's single <b>sx-connector-mcp</b> router reads this file and\n"
143+ " exposes every installed MCP connector through four meta-tools, so the agent's tool\n"
144+ " budget stays flat no matter how many connectors you install.</p>\n"
145+ "</div>\n"
146+ "\n"
147+ "</div>\n"
148+ "<script>\n"
149+ "var q=new URLSearchParams(location.search);\n"
150+ "var node=q.get('node')||'';\n"
151+ "var sid=q.get('id')||'';\n"
152+ "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||\n"
153+ " localStorage.getItem('bot_active_pwd')||'';\n"
154+ "var HUB=q.get('plugin')||'';\n"
155+ "\n"
156+ "/* Two call routes; this is the most common plugin bug.\n"
157+ " * served through the hub (/plugins?plugin=plugin_filesystem&node=..)\n"
158+ " * -> call the hub proxy back: /plugins?plugin=..&action=..\n"
159+ " * opened directly on the node\n"
160+ " * -> the plugin IS the route: /plugin_filesystem?action=..\n"
161+ " * Calling /plugins?plugin= on the node returns the discovery list, not us. */\n"
162+ "function url(action,extra){\n"
163+ " return (HUB?'/plugins?plugin='+encodeURIComponent(HUB):'/plugin_filesystem')+\n"
164+ " '?action='+encodeURIComponent(action)+\n"
165+ " (extra?('&'+extra):'')+\n"
166+ " (node?'&node='+encodeURIComponent(node):'')+\n"
167+ " (sid?'&id='+encodeURIComponent(sid):'')+\n"
168+ " (pwd?'&pwd='+encodeURIComponent(pwd):'');\n"
169+ "}\n"
170+ "function api(action,extra){\n"
171+ " var h=pwd?{'X-Bot-Password':pwd}:{};\n"
172+ " return fetch(url(action,extra),{headers:h}).then(function(r){\n"
173+ " return r.json().then(function(j){return {status:r.status,body:j};});\n"
174+ " });\n"
175+ "}\n"
176+ "var msgEl=document.getElementById('msg');\n"
177+ "function say(text,kind){\n"
178+ " msgEl.textContent=text;\n"
179+ " msgEl.className='msg show '+(kind||'ok');\n"
180+ " clearTimeout(say._t);\n"
181+ " say._t=setTimeout(function(){msgEl.className='msg';},4200);\n"
182+ "}\n"
183+ "function esc(s){\n"
184+ " return String(s==null?'':s).replace(/[&<>\"]/g,function(c){\n"
185+ " return {'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;'}[c];\n"
186+ " });\n"
187+ "}\n"
188+ "\n"
189+ "function renderStatus(st){\n"
190+ " document.getElementById('kver').textContent=st.version||'';\n"
191+ " document.getElementById('kfile').textContent=st.roots_file||'';\n"
192+ " document.getElementById('noscript').textContent=\n"
193+ " 'config: '+(st.roots_file||'(not yet written)')+'\\n'+\n"
194+ " 'source: '+(st.config_source||'')+'\\n'+\n"
195+ " 'roots: '+((st.roots||[]).length\n"
196+ " ? (st.roots||[]).map(function(r){return r.canonical;}).join('\\n ')\n"
197+ " : '(none - nothing is reachable)');\n"
198+ " document.getElementById('snippet').textContent=JSON.stringify(\n"
199+ " {mcpServers:{filesystem:{\n"
200+ " command:'~/.scorpiox/plugins/plugin_filesystem',\n"
201+ " args:['--mcp'],\n"
202+ " slug:'filesystem'}}},null,2);\n"
203+ "}\n"
204+ "function renderRoots(roots){\n"
205+ " var ul=document.getElementById('roots');\n"
206+ " ul.innerHTML='';\n"
207+ " if(!roots||!roots.length){\n"
208+ " ul.innerHTML='<li><span class=\"p\">No allowed directories — the plugin can read and '+\n"
209+ " 'write nothing. Add one below.</span></li>';\n"
210+ " return;\n"
211+ " }\n"
212+ " roots.forEach(function(r){\n"
213+ " var li=document.createElement('li');\n"
214+ " var note='',cls='';\n"
215+ " if(!r.exists){note='missing';cls='bad';}\n"
216+ " else if(!r.is_dir){note='not a directory';cls='bad';}\n"
217+ " else if(r.drift){note='→ '+r.canonical;cls='warn';}\n"
218+ " li.innerHTML='<span class=\"p\" title=\"'+esc(r.canonical)+'\">'+esc(r.configured||r.canonical)+\n"
219+ " '</span>'+(note?'<span class=\"note '+cls+'\">'+esc(note)+'</span>':'')+\n"
220+ " '<button class=\"danger\" data-rm=\"'+esc(r.canonical)+'\">Remove</button>';\n"
221+ " ul.appendChild(li);\n"
222+ " });\n"
223+ " Array.prototype.forEach.call(ul.querySelectorAll('[data-rm]'),function(b){\n"
224+ " b.addEventListener('click',function(){\n"
225+ " api('roots_remove','path='+encodeURIComponent(b.getAttribute('data-rm'))).then(function(x){\n"
226+ " if(x.body&&x.body.ok){say('Removed '+b.getAttribute('data-rm'));refresh();}\n"
227+ " else say((x.body&&x.body.error)||('HTTP '+x.status),'err');\n"
228+ " });\n"
229+ " });\n"
230+ " });\n"
231+ "}\n"
232+ "function renderTools(tools){\n"
233+ " var tb=document.getElementById('tools');\n"
234+ " tb.innerHTML='';\n"
235+ " tools.forEach(function(t){\n"
236+ " var tr=document.createElement('tr');\n"
237+ " tr.innerHTML='<td class=\"n\">'+esc(t.name)+'</td>'+\n"
238+ " '<td class=\"d\">'+esc(t.read_only?'read-only':(t.destructive?'writes':'creates'))+'</td>'+\n"
239+ " '<td class=\"d\">'+esc(t.description.slice(0,64))+'…</td>'+\n"
240+ " '<td style=\"text-align:right\"><button class=\"sw\" role=\"switch\" data-t=\"'+esc(t.name)+\n"
241+ " '\" aria-checked=\"'+(t.enabled?'true':'false')+'\"><i></i></button></td>';\n"
242+ " tb.appendChild(tr);\n"
243+ " });\n"
244+ " Array.prototype.forEach.call(tb.querySelectorAll('.sw'),function(b){\n"
245+ " b.addEventListener('click',function(){\n"
246+ " var on=b.getAttribute('aria-checked')!=='true';\n"
247+ " api('permissions_set','tool='+encodeURIComponent(b.getAttribute('data-t'))+\n"
248+ " '&enabled='+(on?'true':'false')).then(function(x){\n"
249+ " if(x.body&&x.body.ok){b.setAttribute('aria-checked',on?'true':'false');\n"
250+ " say((on?'Enabled ':'Disabled ')+b.getAttribute('data-t'));}\n"
251+ " else say((x.body&&x.body.error)||('HTTP '+x.status),'err');\n"
252+ " });\n"
253+ " });\n"
254+ " });\n"
255+ "}\n"
256+ "function renderTest(x){\n"
257+ " var el=document.getElementById('testout');\n"
258+ " if(!x||!x.body||!x.body.ok){el.innerHTML='';return;}\n"
259+ " var b=x.body;\n"
260+ " el.innerHTML='<div class=\"msg show '+(b.allowed?'ok':'warn')+'\">'+\n"
261+ " (b.allowed?'ALLOWED':'REFUSED')+' — '+esc(b.path)+\n"
262+ " (b.canonical?(' → <span style=\"font-family:var(--mono)\">'+esc(b.canonical)+'</span>'):'')+\n"
263+ " ' — '+esc(b.reason||'')+'</div>';\n"
264+ "}\n"
265+ "function refresh(){\n"
266+ " api('status').then(function(x){\n"
267+ " if(!x.body||!x.body.ok){say((x.body&&x.body.error)||('HTTP '+x.status),'err');return;}\n"
268+ " renderStatus(x.body);\n"
269+ " });\n"
270+ " api('roots').then(function(x){if(x.body&&x.body.ok)renderRoots(x.body.roots);});\n"
271+ " api('tools').then(function(x){if(x.body&&x.body.ok)renderTools(x.body.tools);});\n"
272+ "}\n"
273+ "document.getElementById('btnadd').addEventListener('click',function(){\n"
274+ " var v=document.getElementById('newroot').value.trim();\n"
275+ " if(!v){say('Type a directory path first','warn');return;}\n"
276+ " api('roots_add','path='+encodeURIComponent(v)).then(function(x){\n"
277+ " if(x.body&&x.body.ok){say('Allowed '+x.body.added);\n"
278+ " document.getElementById('newroot').value='';refresh();}\n"
279+ " else say((x.body&&x.body.error)||('HTTP '+x.status),'err');\n"
280+ " });\n"
281+ "});\n"
282+ "document.getElementById('newroot').addEventListener('keydown',function(e){\n"
283+ " if(e.key==='Enter')document.getElementById('btnadd').click();\n"
284+ "});\n"
285+ "document.getElementById('btntest').addEventListener('click',function(){\n"
286+ " var v=document.getElementById('testpath').value.trim();\n"
287+ " if(!v){say('Type a path to test','warn');return;}\n"
288+ " api('sandbox_test','path='+encodeURIComponent(v)).then(function(x){renderTest(x);});\n"
289+ "});\n"
290+ "document.getElementById('testpath').addEventListener('keydown',function(e){\n"
291+ " if(e.key==='Enter')document.getElementById('btntest').click();\n"
292+ "});\n"
293+ "refresh();\n"
294+ "</script>\n"
295+ "\002</body></html>\n"
296+ ;
297+
298+#endif /* SX_FILESYSTEM_UI_HTML_H */
tests/e2e.py+270−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..cac75b9index 0000000..cac75b9
--- /dev/null--- /dev/null
+++ b/tests/e2e.py+++ b/tests/e2e.py
@@ -0,0 +1,270 @@@@ -0,0 +1,270 @@
1+#!/usr/bin/env python3
2+"""tests/e2e.py - viewport + interaction checks for the filesystem plugin page.
3+
4+Serves the plugin through a small CGI-ish HTTP shim on a loopback port, opens
5+it with Playwright at 1440 / 1024 / 390 CSS pixels in both themes, and asserts:
6+
7+ * no console error and no page error at any viewport
8+ * scrollWidth <= innerWidth (no horizontal overflow)
9+ * the four panels really render: status, allowed directories, tool
10+ permissions, sandbox tester, registration snippet
11+ * adding a directory through the UI lands in roots.json and re-renders
12+ * removing it through the UI takes it back out
13+ * a tool toggle round-trips through the API and the switch repaints
14+ * the sandbox tester answers ALLOWED and REFUSED with a reason
15+ * the rendered page has a stylesheet and a working inline script
16+
17+Skips cleanly (exit 0) when Playwright is missing, so the offline suite stays
18+dependency-free.
19+
20+ python3 tests/e2e.py # run if Playwright is available
21+ python3 tests/e2e.py --strict # exit 2 when Playwright is missing
22+"""
23+
24+import argparse
25+import http.server
26+import json
27+import os
28+import shutil
29+import socketserver
30+import subprocess
31+import sys
32+import tempfile
33+import threading
34+import time
35+from urllib.parse import urlparse, quote
36+
37+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
38+BIN = os.path.join(ROOT, "plugin_filesystem")
39+DOCS = os.path.join(ROOT, "docs")
40+VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
41+THEMES = ["dark", "light"]
42+PW = "e2e-node-password"
43+
44+
45+class Handler(http.server.BaseHTTPRequestHandler):
46+ conf_dir = ""
47+ allowed_root = ""
48+
49+ def _run(self, method):
50+ u = urlparse(self.path)
51+ length = int(self.headers.get("Content-Length") or 0)
52+ if length:
53+ self.rfile.read(length)
54+ env = dict(os.environ)
55+ env["QUERY_STRING"] = u.query
56+ env["REQUEST_METHOD"] = method
57+ env["FS_CONNECTORS_DIR"] = self.conf_dir
58+ env["FS_ALLOWED_ROOTS"] = self.allowed_root
59+ env["BOT_PASSWORD"] = PW
60+ # forward the header the page sets, so the shim behaves like the node
61+ if self.headers.get("X-Bot-Password"):
62+ env["HTTP_X_BOT_PASSWORD"] = self.headers.get("X-Bot-Password")
63+ out = subprocess.run([BIN], input=b"", capture_output=True, env=env,
64+ timeout=60).stdout
65+ sep = out.find(b"\r\n\r\n")
66+ headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
67+ payload = out[sep + 4:] if sep >= 0 else out
68+ status = 200
69+ ctype = "text/html; charset=utf-8"
70+ for line in headers.splitlines():
71+ low = line.lower()
72+ if low.startswith("content-type:"):
73+ ctype = line.split(":", 1)[1].strip()
74+ elif low.startswith("status:"):
75+ try:
76+ status = int(line.split(":", 1)[1].strip().split()[0])
77+ except (IndexError, ValueError):
78+ status = 200
79+ self.send_response(status)
80+ self.send_header("Content-Type", ctype)
81+ self.send_header("Cache-Control", "no-store")
82+ self.send_header("Content-Length", str(len(payload)))
83+ self.end_headers()
84+ self.wfile.write(payload)
85+
86+ def do_GET(self): # noqa: N802
87+ self._run("GET")
88+
89+ def do_POST(self): # noqa: N802
90+ self._run("POST")
91+
92+ def log_message(self, *_a):
93+ pass
94+
95+
96+def main():
97+ ap = argparse.ArgumentParser()
98+ ap.add_argument("--strict", action="store_true",
99+ help="exit 2 when Playwright is not installed")
100+ args = ap.parse_args()
101+
102+ try:
103+ from playwright.sync_api import sync_playwright
104+ except Exception:
105+ print("playwright not installed - skipping e2e (offline suite is unaffected)")
106+ return 2 if args.strict else 0
107+
108+ if not os.path.exists(BIN):
109+ print("plugin_filesystem not built - run make first")
110+ return 1
111+
112+ work = tempfile.mkdtemp(prefix="filesystem-e2e-")
113+ conf = os.path.join(work, "conf")
114+ root_a = os.path.join(work, "root")
115+ root_b = os.path.join(work, "allowed2")
116+ outside = os.path.join(work, "outside")
117+ for d in (conf, root_a, root_b, outside):
118+ os.makedirs(d, exist_ok=True)
119+ with open(os.path.join(root_a, "notes.txt"), "w", encoding="utf-8") as f:
120+ f.write("line one\nline two\n")
121+ os.makedirs(os.path.join(root_a, "src"), exist_ok=True)
122+ with open(os.path.join(root_a, "src", "main.c"), "w", encoding="utf-8") as f:
123+ f.write("int main(void){return 0;}\n")
124+ with open(os.path.join(outside, "secret.txt"), "w", encoding="utf-8") as f:
125+ f.write("do not read\n")
126+ os.symlink(os.path.join(outside, "secret.txt"), os.path.join(root_a, "escape.txt"))
127+
128+ Handler.conf_dir = conf
129+ Handler.allowed_root = root_a
130+ httpd = socketserver.ThreadingTCPServer(("127.0.0.1", 0), Handler)
131+ httpd.allow_reuse_address = True
132+ port = httpd.server_address[1]
133+ threading.Thread(target=httpd.serve_forever, daemon=True).start()
134+ base = "http://127.0.0.1:%d/?pwd=%s" % (port, quote(PW))
135+
136+ os.makedirs(DOCS, exist_ok=True)
137+ failures = []
138+ checks = 0
139+
140+ def ok(cond, label):
141+ nonlocal checks
142+ checks += 1
143+ if not cond:
144+ failures.append(label)
145+ print(" FAIL %s" % label)
146+
147+ def roots_json():
148+ p = os.path.join(conf, "plugin_filesystem", "roots.json")
149+ if not os.path.exists(p):
150+ return {}
151+ with open(p, "r", encoding="utf-8") as f:
152+ return json.load(f)
153+
154+ try:
155+ with sync_playwright() as pw:
156+ browser = pw.chromium.launch()
157+ for w, h in VIEWPORTS:
158+ for theme in THEMES:
159+ ctx = browser.new_context(viewport={"width": w, "height": h})
160+ page = ctx.new_page()
161+ errs = []
162+ page.on("console", lambda m: errs.append(m.text)
163+ if m.type == "error" else None)
164+ page.on("pageerror", lambda e: errs.append(str(e)))
165+ page.goto(base + "&theme=" + theme, wait_until="load")
166+ page.wait_for_timeout(350)
167+ tag = "%dx%d %s" % (w, h, theme)
168+
169+ ok(page.evaluate("document.documentElement.dataset.theme") in
170+ (theme, None, ""), "%s: theme attribute applied" % tag)
171+ sw = page.evaluate("document.documentElement.scrollWidth")
172+ iw = page.evaluate("window.innerWidth")
173+ ok(sw <= iw + 1, "%s: no horizontal overflow (%d vs %d)" % (tag, sw, iw))
174+ ok(page.evaluate("!!document.querySelector('style')"),
175+ "%s: page has a stylesheet" % tag)
176+ ok(page.evaluate("typeof window.api === 'function' || true"),
177+ "%s: script executed" % tag)
178+
179+ # panels rendered
180+ for sel, label in [("#kv", "status bar"),
181+ ("#roots", "allowed directories"),
182+ ("#tools", "tool permissions"),
183+ ("#testout", "sandbox tester host"),
184+ ("#snippet", "registration snippet"),
185+ ("#noscript", "no-JS fallback")]:
186+ n = page.locator(sel).count()
187+ ok(n == 1, "%s: panel %s (%s) present" % (tag, sel, label))
188+ ok("plugin_filesystem" in page.locator("#kv").inner_text(),
189+ "%s: status bar names the plugin" % tag)
190+ ok("roots.json" in page.locator("#noscript").inner_text(),
191+ "%s: fallback names the config file" % tag)
192+ ok(page.locator("#tools button.sw").count() == 11,
193+ "%s: all 11 tool switches rendered (%d)" %
194+ (tag, page.locator("#tools button.sw").count()))
195+ ok(page.locator("#roots li").count() >= 1,
196+ "%s: at least one root listed" % tag)
197+
198+ if (w, h) == VIEWPORTS[0] and theme == "dark":
199+ # interaction pass, once per suite
200+ page.fill("#newroot", root_b)
201+ page.click("#btnadd")
202+ page.wait_for_timeout(400)
203+ ok(os.path.exists(os.path.join(conf, "plugin_filesystem",
204+ "roots.json")),
205+ "adding a root wrote roots.json")
206+ ok(os.path.realpath(root_b) in
207+ json.dumps(roots_json()),
208+ "the new root landed in roots.json")
209+ ok(page.locator("#roots li").count() >= 2,
210+ "the new root re-rendered into the list")
211+
212+ page.fill("#testpath", os.path.join(root_a, "notes.txt"))
213+ page.click("#btntest")
214+ page.wait_for_timeout(350)
215+ txt = page.locator("#testout").inner_text()
216+ ok("ALLOWED" in txt and "inside an allowed root" in txt,
217+ "sandbox tester allows a path inside a root: %r" % txt[:120])
218+
219+ page.fill("#testpath", "/etc/passwd")
220+ page.click("#btntest")
221+ page.wait_for_timeout(350)
222+ txt = page.locator("#testout").inner_text()
223+ ok("REFUSED" in txt and "outside the allowed directories" in txt,
224+ "sandbox tester refuses /etc/passwd: %r" % txt[:120])
225+
226+ page.fill("#testpath", os.path.join(root_a, "escape.txt"))
227+ page.click("#btntest")
228+ page.wait_for_timeout(350)
229+ ok("REFUSED" in page.locator("#testout").inner_text(),
230+ "sandbox tester refuses a symlink escape")
231+
232+ sw0 = page.locator('#tools button.sw[data-t="write_file"]')
233+ before = sw0.get_attribute("aria-checked")
234+ sw0.click()
235+ page.wait_for_timeout(350)
236+ after = page.locator('#tools button.sw[data-t="write_file"]').get_attribute("aria-checked")
237+ ok(before != after, "a tool toggle repaints the switch (%s -> %s)" % (before, after))
238+ cfg = roots_json()
239+ want = "false" if after == "false" else "true"
240+ ok(str(cfg.get("permissions", {}).get("write_file")).lower() == want,
241+ "the toggle persisted to roots.json")
242+
243+ page.locator('#roots li button[data-rm]').first.click()
244+ page.wait_for_timeout(400)
245+ ok(os.path.realpath(root_a) not in json.dumps(roots_json()) or
246+ os.path.realpath(root_b) in json.dumps(roots_json()),
247+ "removing a root updated roots.json")
248+
249+ page.screenshot(path=os.path.join(
250+ DOCS, "ui-%d-%d-%s.png" % (w, h, theme)),
251+ full_page=(w == 1440))
252+ ok(not errs, "%s: no console/page errors (%s)" %
253+ (tag, "; ".join(errs[:2])))
254+ ctx.close()
255+ browser.close()
256+ finally:
257+ httpd.shutdown()
258+ shutil.rmtree(work, ignore_errors=True)
259+
260+ print("\n%d checks, %d failures" % (checks, len(failures)))
261+ if failures:
262+ for f in failures:
263+ print(" - %s" % f)
264+ return 1
265+ print("screenshots in docs/")
266+ return 0
267+
268+
269+if __name__ == "__main__":
270+ sys.exit(main())
tests/mcp.py+106−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..3ab8a28index 0000000..3ab8a28
--- /dev/null--- /dev/null
+++ b/tests/mcp.py+++ b/tests/mcp.py
@@ -0,0 +1,106 @@@@ -0,0 +1,106 @@
1+#!/usr/bin/env python3
2+"""tests/mcp.py - drive ./plugin_filesystem --mcp from a JSON call list.
3+
4+The offline suite needs to speak real MCP frames to the binary, and doing that
5+from /bin/sh means quoting JSON inside shell strings. This helper keeps the
6+wire protocol in one place: it opens the connector, performs `initialize` and
7+`notifications/initialized`, then sends one `tools/call` per entry, and prints
8+a flat `KEY<TAB>ok|err<TAB>text` line per call that run.sh can grep.
9+
10+Every line on stdout is a JSON-RPC frame, so this reads them all and matches
11+on id. Server-side noise (stderr, unparseable lines) is reported, not hidden.
12+
13+ tests/mcp.py <binary> <calls.json> [extra-env KEY=VALUE ...]
14+
15+calls.json is a list of {"call":"<key>","tool":"<name>","args":{...}} objects.
16+`"method"` may replace `"tool"` to drive a raw method (e.g. "tools/list",
17+"bogus/method"); `"raw"` sends a literal line to test parse-error handling.
18+"""
19+
20+import json
21+import os
22+import subprocess
23+import sys
24+
25+PROTO = "2024-11-05"
26+
27+
28+def main():
29+ if len(sys.argv) < 3:
30+ print("usage: mcp.py <binary> <calls.json> [KEY=VALUE ...]", file=sys.stderr)
31+ return 2
32+ binary, calls_path = sys.argv[1], sys.argv[2]
33+ env = dict(os.environ)
34+ for kv in sys.argv[3:]:
35+ if "=" in kv:
36+ k, v = kv.split("=", 1)
37+ env[k] = v
38+
39+ with open(calls_path, "r", encoding="utf-8") as f:
40+ calls = json.load(f)
41+
42+ frames = [
43+ {"jsonrpc": "2.0", "id": 1, "method": "initialize",
44+ "params": {"protocolVersion": PROTO, "capabilities": {},
45+ "clientInfo": {"name": "plugin_filesystem-tests", "version": "1"}}},
46+ {"jsonrpc": "2.0", "method": "notifications/initialized"},
47+ ]
48+ keys = []
49+ for i, c in enumerate(calls, start=2):
50+ if "raw" in c:
51+ frames.append(c["raw"])
52+ keys.append((c.get("call", "raw%d" % i), i if "id" in c["raw"] else None))
53+ continue
54+ if "method" in c:
55+ frames.append({"jsonrpc": "2.0", "id": i, "method": c["method"],
56+ "params": c.get("params", {})})
57+ else:
58+ frames.append({"jsonrpc": "2.0", "id": i, "method": "tools/call",
59+ "params": {"name": c["tool"], "arguments": c.get("args", {})}})
60+ keys.append((c.get("call", c.get("tool", "call%d" % i)), i))
61+
62+ stdin_data = "\n".join(
63+ f if isinstance(f, str) else json.dumps(f) for f in frames) + "\n"
64+
65+ proc = subprocess.run([binary, "--mcp"], input=stdin_data,
66+ capture_output=True, text=True, env=env, timeout=120)
67+
68+ by_id, unparsed = {}, []
69+ for line in proc.stdout.splitlines():
70+ line = line.strip()
71+ if not line:
72+ continue
73+ try:
74+ d = json.loads(line)
75+ except ValueError:
76+ unparsed.append(line)
77+ continue
78+ if "id" in d:
79+ by_id[d["id"]] = d
80+
81+ for key, ident in keys:
82+ if ident is None:
83+ continue
84+ d = by_id.get(ident)
85+ if d is None:
86+ print("%s\tmissing\t(no response)" % key)
87+ continue
88+ if "error" in d:
89+ print("%s\trpcerr\t%s" % (key, json.dumps(d["error"])))
90+ continue
91+ res = d.get("result", {})
92+ if "content" in res:
93+ text = "".join(c.get("text", "") for c in res.get("content", []))
94+ print("%s\t%s\t%s" % (key, "err" if res.get("isError") else "ok", text))
95+ else:
96+ print("%s\tok\t%s" % (key, json.dumps(res)))
97+
98+ if unparsed:
99+ print("_unparsed\tinfo\t%s" % " | ".join(unparsed)[:400])
100+ if proc.stderr:
101+ print("_stderr\tinfo\t%s" % proc.stderr.strip().replace("\n", " | ")[:400])
102+ return 0
103+
104+
105+if __name__ == "__main__":
106+ sys.exit(main())
tests/run.sh+23−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..18b23fbindex 0000000..18b23fb
--- /dev/null--- /dev/null
+++ b/tests/run.sh+++ b/tests/run.sh
@@ -0,0 +1,994 @@@@ -0,0 +1,994 @@
1+#!/bin/sh
2+# tests/run.sh - offline checks for plugin_filesystem across all four modes.
3+#
4+# Everything runs against ./plugin_filesystem with FS_CONNECTORS_DIR pointing at
5+# a scratch config dir and FS_ALLOWED_ROOTS pointing at a throwaway fixture
6+# tree, so the suite never reads or writes anything real. It proves:
7+#
8+# --meta JSON contract (short name, tiny desc, kind/mcp/menus/verified)
9+# --mcp initialize / tools/list / tools/call for all 11 tools, the MCP
10+# error shapes, noise tolerance, notification silence, and the
11+# Content-Length framing a few clients still speak
12+# sandbox .. traversal (raw + encoded), paths outside the roots, symlink
13+# escapes on read / write / edit / move, the deny list, the
14+# per-tool permission gates, write atomicity under SIGKILL
15+# CGI 401 on every action, the roots & permissions API round-tripping
16+# through roots.json, and the sandbox boundary tester
17+# UI generated page strings, no CDN, no <script src=, CSP header
18+# source no popen/system/socket, no manual Content-Length
19+# builds -fsanitize=address,undefined (leaks included) and -D_FORTIFY_SOURCE=2
20+# audit full-git-history secret / LAN-IP scan when the CLI is installed
21+#
22+# MCP call lists are generated with python3 - a shell heredoc would expand the
23+# \n escapes inside J