scorpiox-bot-plugin-github
←sx_connector.hc
340 lines · 14 KBHEADBlameDownload
1/*
2 * sx_connector.h -- the single entry point of the SCORPIOX BOT Connector SDK.
3 *
4 * One #include gives a clean-room `scorpiox-bot-plugin-oss-<slug>` repository
5 * everything it needs to be a first-class SCORPIOX BOT plugin that is also a
6 * connector:
7 *
8 * --meta / SX_PLUGIN_META=1 one-line JSON identity
9 * {name,desc,kind,mcp,daemon,menus,verified}
10 * GET (CGI) the setup UI (bot_theme tokens, sx-theme
11 * postMessage handoff, ?embed=1 layout)
12 * ?action= / ?format=json the control JSON API (require_node_auth)
13 * --mcp stdio MCP JSON-RPC 2.0 server
14 * (initialize / notifications/initialized /
15 * ping / tools/list / tools/call) + --schema
16 * --daemon the always-on channel bridge: persistent
17 * connector dir, default-deny sender allowlist,
18 * pairing codes, and the node loopback client
19 * (POST /inbox, GET /hashes_sse, GET
20 * /conversation on 127.0.0.1:8150)
21 *
22 * Everything is pure C99 with zero external runtime dependencies; TLS comes
23 * from the vendored BearSSL in src/bearssl (see sx_http_tls.h). Link
24 * build/libsxconn.a and write ~200-400 lines of connector logic.
25 *
26 * MIT License. Copyright (c) 2026 SCORPIOX INC.
27 */
28#ifndef SX_CONNECTOR_H
29#define SX_CONNECTOR_H
30
31#include <stddef.h>
32#include <stdint.h>
33
34#include "sx_http_tls.h"
35#include "yyjson.h"
36
37#ifdef __cplusplus
38extern "C" {
39#endif
40
41/* =====================================================================
42 * 1. Identity and lifecycle
43 * ===================================================================== */
44
45#define SX_KIND_UI "ui"
46#define SX_KIND_MCP "mcp"
47#define SX_KIND_CHANNEL "channel"
48#define SX_KIND_HYBRID "hybrid"
49
50typedef struct {
51 const char *id; /* plugin_<id> stem, e.g. "telegram" */
52 const char *name; /* 1-2 words, shown in dropdowns */
53 const char *desc; /* <= 15 chars */
54 const char *kind; /* SX_KIND_* */
55 int mcp; /* implements --mcp */
56 int daemon; /* implements --daemon */
57 int menus; /* -1 = derive from kind */
58 const char *verified; /* "live" | "mock" */
59 const char *version; /* semver, optional */
60} sx_plugin_info;
61
62/* Normalise defaults (kind ui, menus derived, verified mock). */
63void sx_info_fill(sx_plugin_info *info);
64
65/* Emit the --meta line and exit 0. Call when argc has --meta or
66 * SX_PLUGIN_META is set. */
67void sx_meta_emit(const sx_plugin_info *info);
68
69/* Windows: force stdout/stderr/stdin to binary mode so CGI header \r\n
70 * never becomes \r\r\n. No-op elsewhere. Call first thing in main(). */
71void sx_stdio_binary(void);
72
73/* Ignore SIGPIPE process-wide (no-op on Windows). sx_main(), sx_mcp_serve()
74 * and sx_daemon_run() all call it; call it yourself if you use the raw
75 * sx_http_tls.h client without going through any of them. Without it, a
76 * write to a socket the peer has already closed raises SIGPIPE instead of
77 * returning an error. */
78void sx_ignore_sigpipe(void);
79
80/* Dispatch the classic 3 CGI modes plus the two connector modes.
81 *
82 * --meta / SX_PLUGIN_META -> sx_meta_emit()
83 * --mcp -> sx_mcp_serve()
84 * --schema -> sx_mcp_schema() (compat)
85 * --daemon -> the caller's sx_daemon_cfg loop
86 * (see sx_daemon_run)
87 * QUERY_STRING with action= or
88 * format=json, or POST -> json_cb
89 * otherwise -> html_cb
90 *
91 * Returns the exit code for main(). The two callbacks print their own CGI
92 * headers and return the exit code. */
93typedef int (*sx_html_cb)(const sx_plugin_info *info, const char *query,
94 int embed, const char *theme);
95typedef int (*sx_json_cb)(const sx_plugin_info *info, const char *query,
96 const char *action, const char *body);
97
98int sx_main(int argc, char **argv, const sx_plugin_info *info,
99 sx_html_cb html_cb, sx_json_cb json_cb);
100
101/* =====================================================================
102 * 2. CGI helpers
103 * ===================================================================== */
104
105/* The node password from BOT_PASSWORD (empty/absent = open node). */
106const char *sx_node_password(void);
107
108/* 401 + JSON error and exit(0) unless the request carries the node
109 * password in X-Bot-Password, Authorization: Bearer, or ?pwd=. */
110void sx_require_node_auth(void);
111
112/* Read one value out of QUERY_STRING into buf. Returns 1 found. Values are
113 * percent-decoded; '+' becomes a space. */
114int sx_query_get(const char *query, const char *key, char *buf, size_t capsz);
115
116/* Emit CGI headers. status is an HTTP code (200 emits no Status line).
117 * ctype is e.g. "text/html; charset=utf-8". */
118void sx_cgi_header(long status, const char *ctype);
119
120/* Print an application/json body built from a yyjson mutable doc. */
121void sx_print_json_doc(yyjson_mut_doc *doc);
122
123/* Print {"ok":false,"error":"..."} with the given CGI status (400 etc.). */
124void sx_json_error(const char *msg, long status);
125
126/* Read the CGI request body (POST_BODY_FILE or stdin + CONTENT_LENGTH,
127 * capped at 8 MiB). Caller frees. Returns NULL when absent. */
128char *sx_read_body(void);
129
130/* 1 when argv contains `flag` exactly (e.g. "--mcp"). Used to dispatch the
131 * connector modes a plugin's own main() owns before calling sx_main(). */
132int sx_has_flag(int argc, char **argv, const char *flag);
133
134/* =====================================================================
135 * 3. Theme + embed
136 * ===================================================================== */
137
138/* Shared bot_theme CSS custom properties (dark default, light via
139 * html[data-theme=light] or prefers-color-scheme). fputs() it, never
140 * printf() -- it contains literal '%'. */
141extern const char *const SX_THEME_CSS;
142
143/* Pre-paint script: restores localStorage.bot_theme and flags
144 * <html class="embedded"> under ?embed=1. */
145extern const char *const SX_THEME_PREPAINT_JS;
146
147/* The plugin side of the sx-theme handoff: answers the host's
148 * {type:'sx-theme'} posts, sends one {type:'sx-theme-request'} at startup,
149 * and hides the local toggle when embedded. Splice before </body>. */
150extern const char *const SX_THEME_HANDOFF_JS;
151
152/* 1 when ?embed=1|true is in the query (host modal owns the chrome). */
153int sx_is_embedded(const char *query);
154
155/* "dark" | "light" resolved in the locked order
156 * ?theme= -> localStorage is JS-side -> caller default. */
157const char *sx_theme_from_query(const char *query, const char *fallback);
158
159/* Convenience: emit a complete <head> (doctype through </head>) with the
160 * theme tokens, title, and the handoff script. */
161void sx_html_head(const char *title);
162
163/* The handoff script tag (call just before </body>). */
164void sx_html_handoff_script(void);
165
166/* =====================================================================
167 * 4. --mcp : stdio MCP JSON-RPC 2.0 server
168 * ===================================================================== */
169
170/* One tool exposed over MCP. */
171typedef struct {
172 const char *name;
173 const char *description;
174 const char *input_schema_json; /* a JSON Schema object literal, or NULL */
175 /* Execute the call. `args_json` is the raw arguments object (may be
176 * "{}"). Write human-readable text into `out` (it becomes the text
177 * content block). Return 0 on success, non-zero to set isError. */
178 int (*call)(const char *args_json, char *out, size_t outsz,
179 char *err, size_t errsz);
180} sx_mcp_tool;
181
182/* Serve MCP over stdin/stdout until EOF. Registers the tools, handles
183 * initialize / notifications/initialized / ping / tools/list / tools/call,
184 * and answers unknown methods with a JSON-RPC method-not-found error.
185 * Line-delimited JSON-RPC (one message per line), unbuffered output. */
186int sx_mcp_serve(const sx_plugin_info *info,
187 const sx_mcp_tool *tools, size_t ntools);
188
189/* Print the tool array as JSON (--schema compatibility) and return. */
190int sx_mcp_schema(const sx_plugin_info *info,
191 const sx_mcp_tool *tools, size_t ntools);
192
193/* One-shot: handle exactly one JSON-RPC message from `line` and print the
194 * reply (used by the test suite). Returns 1 if a reply was printed. */
195int sx_mcp_handle_line(const sx_plugin_info *info,
196 const sx_mcp_tool *tools, size_t ntools,
197 const char *line, int *did_reply);
198
199/* =====================================================================
200 * 5. --daemon : channel bridge helpers
201 * ===================================================================== */
202
203/* Persistent per-connector state directory, created on demand:
204 * $SX_CONNECTOR_DIR
205 * /workspace/.scorpiox/connectors/<id> (when /workspace exists)
206 * ~/.scorpiox/connectors/<id> (Windows: %LOCALAPPDATA%
207 * \scorpiox\connectors\<id>)
208 * Returns 0 on success, -1 when nothing could be created. */
209int sx_connector_dir(const char *id, char *out, size_t capsz);
210
211/* Path helper: <connector dir>/<name>. */
212int sx_connector_path(const char *id, const char *name, char *out, size_t capsz);
213
214/* Sender identity + decision. `key` is the platform-stable identity
215 * (e.g. "telegram:12345", "discord:guild/channel/user"). */
216typedef struct {
217 char key[192];
218 char label[128];
219 char code[12]; /* pairing code (uppercase alphanumeric) */
220 long long created; /* unix seconds */
221 int approved; /* 1 allowlisted, 0 pending */
222} sx_sender;
223
224/* Load/save the sender table (config.json + pending.json in the connector
225 * dir). Arrays are heap-allocated; free with sx_senders_free(). */
226int sx_senders_load(const char *id, sx_sender **out, size_t *n_out);
227int sx_senders_save(const char *id, const sx_sender *items, size_t n);
228void sx_senders_free(sx_sender *items);
229
230/* Default-deny gate. 1 = allowed to reach a session, 0 = refused.
231 * Unknown senders are queued as pending with a fresh pairing code
232 * (unless pairing is disabled) and refused. */
233int sx_sender_allowed(const char *id, const char *key, const char *label,
234 int pairing_enabled, char *code_out, size_t codesz);
235
236/* Approve a pending sender by key (from the setup UI). */
237int sx_sender_approve(const char *id, const char *key);
238int sx_sender_remove(const char *id, const char *key);
239
240/* Resolve a pairing code to its key; returns 1 found. */
241int sx_pairing_lookup(const char *id, const char *code, char *key_out,
242 size_t capsz);
243
244/* Generic JSON object file helpers (config.json and friends). */
245int sx_json_file_load(const char *id, const char *name, yyjson_doc **doc);
246int sx_json_file_save(const char *id, const char *name, yyjson_mut_doc *doc);
247
248/* ---- node loopback client ------------------------------------------- */
249
250/* Base URL of the node API: $SX_NODE_API (default
251 * http://127.0.0.1:8150). */
252const char *sx_node_api_base(void);
253
254/* POST /inbox?id=<session> with {"text":...}. mode may be NULL
255 * ("auto"), "interrupt" or "queue". Returns 0 on 2xx, -1 with err. */
256int sx_node_post_inbox(const char *session, const char *text,
257 const char *mode, char *err, size_t errsz);
258
259/* GET /conversation?id=<session>[&after=N][&limit=N]. Body returned
260 * malloc'd in *body (caller frees). 0 ok, -1 err. */
261int sx_node_conversation(const char *session, long after, long limit,
262 char **body, char *err, size_t errsz);
263
264/* One SSE line from GET /hashes_sse, already stripped of "data: ". */
265typedef struct {
266 char id[128];
267 char session_id[128];
268 char event[32];
269 long total;
270 long after;
271 char json[4096]; /* the raw data payload */
272} sx_sse_event;
273
274typedef struct sx_sse {
275 sx_conn c;
276 int open;
277 char last_event[32];
278} sx_sse;
279
280/* Open /hashes_sse?id=<session>[&after=N] and read events one at a time.
281 * sx_sse_next() returns 1 event read, 0 stream ended, -1 error/timeout. */
282int sx_sse_open(sx_sse *s, const char *session, long after,
283 char *err, size_t errsz);
284int sx_sse_next(sx_sse *s, sx_sse_event *ev, long timeout_ms);
285void sx_sse_close(sx_sse *s);
286
287/* The daemon supervisor contract: the caller supplies the poll loop.
288 * sx_daemon_run wires the standard lifecycle (pidfile, SIGHUP/SIGTERM for
289 * Windows-safe cooperative stop, connector dir, log line) and calls
290 * `tick` every interval_ms until a stop is requested.
291 *
292 * Return non-zero from `tick` to end the loop. */
293typedef struct {
294 const char *id;
295 const char *session; /* default target session for inbound text */
296 unsigned interval_ms; /* tick period, 0 = 1000 */
297 void *user;
298} sx_daemon_cfg;
299
300typedef int (*sx_daemon_tick)(const sx_daemon_cfg *cfg, void *user);
301
302int sx_daemon_run(const sx_daemon_cfg *cfg, sx_daemon_tick tick);
303
304/* Ask a running daemon to stop (writes <dir>/stop); used by
305 * plugin_manage action=stop and by tests. */
306int sx_daemon_request_stop(const char *id);
307int sx_daemon_stop_requested(const char *id);
308
309/* Structured log line: "[<id>] msg" to stderr with a monotonic stamp. */
310void sx_log(const char *id, const char *fmt, ...);
311
312/* =====================================================================
313 * 6. Small shared utilities
314 * ===================================================================== */
315
316/* Read a whole file (malloc'd, NUL-terminated). 1 ok, 0 missing, -1 err. */
317int sx_read_file(const char *path, char **buf, size_t *len);
318
319/* Write a whole file atomically (tmp + rename). Creates parent dirs. */
320int sx_write_file(const char *path, const void *buf, size_t len);
321
322/* Ensure a directory exists (mkdir -p). */
323int sx_mkdir_p(const char *path);
324
325/* Monotonic-ish unique id string (time + counter). */
326void sx_make_id(char *out, size_t capsz);
327
328/* Random uppercase pairing code, `n` chars (6 default via SX_CODE_LEN). */
329#define SX_CODE_LEN 6
330void sx_make_code(char *out, size_t capsz);
331
332/* Case-insensitive compare / copy helpers used by connectors. */
333int sx_ieq(const char *a, const char *b);
334void sx_copy(char *dst, size_t capsz, const char *src);
335
336#ifdef __cplusplus
337}
338#endif
339
340#endif /* SX_CONNECTOR_H */