/* * sx_connector.h -- the single entry point of the SCORPIOX BOT Connector SDK. * * One #include gives a clean-room `scorpiox-bot-plugin-oss-` repository * everything it needs to be a first-class SCORPIOX BOT plugin that is also a * connector: * * --meta / SX_PLUGIN_META=1 one-line JSON identity * {name,desc,kind,mcp,daemon,menus,verified} * GET (CGI) the setup UI (bot_theme tokens, sx-theme * postMessage handoff, ?embed=1 layout) * ?action= / ?format=json the control JSON API (require_node_auth) * --mcp stdio MCP JSON-RPC 2.0 server * (initialize / notifications/initialized / * ping / tools/list / tools/call) + --schema * --daemon the always-on channel bridge: persistent * connector dir, default-deny sender allowlist, * pairing codes, and the node loopback client * (POST /inbox, GET /hashes_sse, GET * /conversation on 127.0.0.1:8150) * * Everything is pure C99 with zero external runtime dependencies; TLS comes * from the vendored BearSSL in src/bearssl (see sx_http_tls.h). Link * build/libsxconn.a and write ~200-400 lines of connector logic. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #ifndef SX_CONNECTOR_H #define SX_CONNECTOR_H #include #include #include "sx_http_tls.h" #include "yyjson.h" #ifdef __cplusplus extern "C" { #endif /* ===================================================================== * 1. Identity and lifecycle * ===================================================================== */ #define SX_KIND_UI "ui" #define SX_KIND_MCP "mcp" #define SX_KIND_CHANNEL "channel" #define SX_KIND_HYBRID "hybrid" typedef struct { const char *id; /* plugin_ stem, e.g. "telegram" */ const char *name; /* 1-2 words, shown in dropdowns */ const char *desc; /* <= 15 chars */ const char *kind; /* SX_KIND_* */ int mcp; /* implements --mcp */ int daemon; /* implements --daemon */ int menus; /* -1 = derive from kind */ const char *verified; /* "live" | "mock" */ const char *version; /* semver, optional */ } sx_plugin_info; /* Normalise defaults (kind ui, menus derived, verified mock). */ void sx_info_fill(sx_plugin_info *info); /* Emit the --meta line and exit 0. Call when argc has --meta or * SX_PLUGIN_META is set. */ void sx_meta_emit(const sx_plugin_info *info); /* Windows: force stdout/stderr/stdin to binary mode so CGI header \r\n * never becomes \r\r\n. No-op elsewhere. Call first thing in main(). */ void sx_stdio_binary(void); /* Ignore SIGPIPE process-wide (no-op on Windows). sx_main(), sx_mcp_serve() * and sx_daemon_run() all call it; call it yourself if you use the raw * sx_http_tls.h client without going through any of them. Without it, a * write to a socket the peer has already closed raises SIGPIPE instead of * returning an error. */ void sx_ignore_sigpipe(void); /* Dispatch the classic 3 CGI modes plus the two connector modes. * * --meta / SX_PLUGIN_META -> sx_meta_emit() * --mcp -> sx_mcp_serve() * --schema -> sx_mcp_schema() (compat) * --daemon -> the caller's sx_daemon_cfg loop * (see sx_daemon_run) * QUERY_STRING with action= or * format=json, or POST -> json_cb * otherwise -> html_cb * * Returns the exit code for main(). The two callbacks print their own CGI * headers and return the exit code. */ typedef int (*sx_html_cb)(const sx_plugin_info *info, const char *query, int embed, const char *theme); typedef int (*sx_json_cb)(const sx_plugin_info *info, const char *query, const char *action, const char *body); int sx_main(int argc, char **argv, const sx_plugin_info *info, sx_html_cb html_cb, sx_json_cb json_cb); /* ===================================================================== * 2. CGI helpers * ===================================================================== */ /* The node password from BOT_PASSWORD (empty/absent = open node). */ const char *sx_node_password(void); /* 401 + JSON error and exit(0) unless the request carries the node * password in X-Bot-Password, Authorization: Bearer, or ?pwd=. */ void sx_require_node_auth(void); /* Read one value out of QUERY_STRING into buf. Returns 1 found. Values are * percent-decoded; '+' becomes a space. */ int sx_query_get(const char *query, const char *key, char *buf, size_t capsz); /* Emit CGI headers. status is an HTTP code (200 emits no Status line). * ctype is e.g. "text/html; charset=utf-8". */ void sx_cgi_header(long status, const char *ctype); /* Print an application/json body built from a yyjson mutable doc. */ void sx_print_json_doc(yyjson_mut_doc *doc); /* Print {"ok":false,"error":"..."} with the given CGI status (400 etc.). */ void sx_json_error(const char *msg, long status); /* Read the CGI request body (POST_BODY_FILE or stdin + CONTENT_LENGTH, * capped at 8 MiB). Caller frees. Returns NULL when absent. */ char *sx_read_body(void); /* 1 when argv contains `flag` exactly (e.g. "--mcp"). Used to dispatch the * connector modes a plugin's own main() owns before calling sx_main(). */ int sx_has_flag(int argc, char **argv, const char *flag); /* ===================================================================== * 3. Theme + embed * ===================================================================== */ /* Shared bot_theme CSS custom properties (dark default, light via * html[data-theme=light] or prefers-color-scheme). fputs() it, never * printf() -- it contains literal '%'. */ extern const char *const SX_THEME_CSS; /* Pre-paint script: restores localStorage.bot_theme and flags * under ?embed=1. */ extern const char *const SX_THEME_PREPAINT_JS; /* The plugin side of the sx-theme handoff: answers the host's * {type:'sx-theme'} posts, sends one {type:'sx-theme-request'} at startup, * and hides the local toggle when embedded. Splice before . */ extern const char *const SX_THEME_HANDOFF_JS; /* 1 when ?embed=1|true is in the query (host modal owns the chrome). */ int sx_is_embedded(const char *query); /* "dark" | "light" resolved in the locked order * ?theme= -> localStorage is JS-side -> caller default. */ const char *sx_theme_from_query(const char *query, const char *fallback); /* Convenience: emit a complete (doctype through ) with the * theme tokens, title, and the handoff script. */ void sx_html_head(const char *title); /* The handoff script tag (call just before ). */ void sx_html_handoff_script(void); /* ===================================================================== * 4. --mcp : stdio MCP JSON-RPC 2.0 server * ===================================================================== */ /* One tool exposed over MCP. */ typedef struct { const char *name; const char *description; const char *input_schema_json; /* a JSON Schema object literal, or NULL */ /* Execute the call. `args_json` is the raw arguments object (may be * "{}"). Write human-readable text into `out` (it becomes the text * content block). Return 0 on success, non-zero to set isError. */ int (*call)(const char *args_json, char *out, size_t outsz, char *err, size_t errsz); } sx_mcp_tool; /* Serve MCP over stdin/stdout until EOF. Registers the tools, handles * initialize / notifications/initialized / ping / tools/list / tools/call, * and answers unknown methods with a JSON-RPC method-not-found error. * Line-delimited JSON-RPC (one message per line), unbuffered output. */ int sx_mcp_serve(const sx_plugin_info *info, const sx_mcp_tool *tools, size_t ntools); /* Print the tool array as JSON (--schema compatibility) and return. */ int sx_mcp_schema(const sx_plugin_info *info, const sx_mcp_tool *tools, size_t ntools); /* One-shot: handle exactly one JSON-RPC message from `line` and print the * reply (used by the test suite). Returns 1 if a reply was printed. */ int sx_mcp_handle_line(const sx_plugin_info *info, const sx_mcp_tool *tools, size_t ntools, const char *line, int *did_reply); /* ===================================================================== * 5. --daemon : channel bridge helpers * ===================================================================== */ /* Persistent per-connector state directory, created on demand: * $SX_CONNECTOR_DIR * /workspace/.scorpiox/connectors/ (when /workspace exists) * ~/.scorpiox/connectors/ (Windows: %LOCALAPPDATA% * \scorpiox\connectors\) * Returns 0 on success, -1 when nothing could be created. */ int sx_connector_dir(const char *id, char *out, size_t capsz); /* Path helper: /. */ int sx_connector_path(const char *id, const char *name, char *out, size_t capsz); /* Sender identity + decision. `key` is the platform-stable identity * (e.g. "telegram:12345", "discord:guild/channel/user"). */ typedef struct { char key[192]; char label[128]; char code[12]; /* pairing code (uppercase alphanumeric) */ long long created; /* unix seconds */ int approved; /* 1 allowlisted, 0 pending */ } sx_sender; /* Load/save the sender table (config.json + pending.json in the connector * dir). Arrays are heap-allocated; free with sx_senders_free(). */ int sx_senders_load(const char *id, sx_sender **out, size_t *n_out); int sx_senders_save(const char *id, const sx_sender *items, size_t n); void sx_senders_free(sx_sender *items); /* Default-deny gate. 1 = allowed to reach a session, 0 = refused. * Unknown senders are queued as pending with a fresh pairing code * (unless pairing is disabled) and refused. */ int sx_sender_allowed(const char *id, const char *key, const char *label, int pairing_enabled, char *code_out, size_t codesz); /* Approve a pending sender by key (from the setup UI). */ int sx_sender_approve(const char *id, const char *key); int sx_sender_remove(const char *id, const char *key); /* Resolve a pairing code to its key; returns 1 found. */ int sx_pairing_lookup(const char *id, const char *code, char *key_out, size_t capsz); /* Generic JSON object file helpers (config.json and friends). */ int sx_json_file_load(const char *id, const char *name, yyjson_doc **doc); int sx_json_file_save(const char *id, const char *name, yyjson_mut_doc *doc); /* ---- node loopback client ------------------------------------------- */ /* Base URL of the node API: $SX_NODE_API (default * http://127.0.0.1:8150). */ const char *sx_node_api_base(void); /* POST /inbox?id= with {"text":...}. mode may be NULL * ("auto"), "interrupt" or "queue". Returns 0 on 2xx, -1 with err. */ int sx_node_post_inbox(const char *session, const char *text, const char *mode, char *err, size_t errsz); /* GET /conversation?id=[&after=N][&limit=N]. Body returned * malloc'd in *body (caller frees). 0 ok, -1 err. */ int sx_node_conversation(const char *session, long after, long limit, char **body, char *err, size_t errsz); /* One SSE line from GET /hashes_sse, already stripped of "data: ". */ typedef struct { char id[128]; char session_id[128]; char event[32]; long total; long after; char json[4096]; /* the raw data payload */ } sx_sse_event; typedef struct sx_sse { sx_conn c; int open; char last_event[32]; } sx_sse; /* Open /hashes_sse?id=[&after=N] and read events one at a time. * sx_sse_next() returns 1 event read, 0 stream ended, -1 error/timeout. */ int sx_sse_open(sx_sse *s, const char *session, long after, char *err, size_t errsz); int sx_sse_next(sx_sse *s, sx_sse_event *ev, long timeout_ms); void sx_sse_close(sx_sse *s); /* The daemon supervisor contract: the caller supplies the poll loop. * sx_daemon_run wires the standard lifecycle (pidfile, SIGHUP/SIGTERM for * Windows-safe cooperative stop, connector dir, log line) and calls * `tick` every interval_ms until a stop is requested. * * Return non-zero from `tick` to end the loop. */ typedef struct { const char *id; const char *session; /* default target session for inbound text */ unsigned interval_ms; /* tick period, 0 = 1000 */ void *user; } sx_daemon_cfg; typedef int (*sx_daemon_tick)(const sx_daemon_cfg *cfg, void *user); int sx_daemon_run(const sx_daemon_cfg *cfg, sx_daemon_tick tick); /* Ask a running daemon to stop (writes /stop); used by * plugin_manage action=stop and by tests. */ int sx_daemon_request_stop(const char *id); int sx_daemon_stop_requested(const char *id); /* Structured log line: "[] msg" to stderr with a monotonic stamp. */ void sx_log(const char *id, const char *fmt, ...); /* ===================================================================== * 6. Small shared utilities * ===================================================================== */ /* Read a whole file (malloc'd, NUL-terminated). 1 ok, 0 missing, -1 err. */ int sx_read_file(const char *path, char **buf, size_t *len); /* Write a whole file atomically (tmp + rename). Creates parent dirs. */ int sx_write_file(const char *path, const void *buf, size_t len); /* Ensure a directory exists (mkdir -p). */ int sx_mkdir_p(const char *path); /* Monotonic-ish unique id string (time + counter). */ void sx_make_id(char *out, size_t capsz); /* Random uppercase pairing code, `n` chars (6 default via SX_CODE_LEN). */ #define SX_CODE_LEN 6 void sx_make_code(char *out, size_t capsz); /* Case-insensitive compare / copy helpers used by connectors. */ int sx_ieq(const char *a, const char *b); void sx_copy(char *dst, size_t capsz, const char *src); #ifdef __cplusplus } #endif #endif /* SX_CONNECTOR_H */