diff --git a/Makefile b/Makefile index fa2ebc1..514cb91 100644 --- a/Makefile +++ b/Makefile @@ -23,7 +23,7 @@ CURSES_A = $(CURSES_DIR)/libcurses/libcurses.a \ LIB = libsplinter.so LIBOBJ = src/buf.o src/tool.o src/session.o src/conv.o src/transport.o \ src/json.o src/sse.o src/openai.o src/transport_openai.o src/builtin.o \ - src/agent.o src/theme.o src/palettes.o src/decomp.o src/i18n.o src/delegate.o src/config.o src/plugin.o + src/agent.o src/theme.o src/palettes.o src/decomp.o src/i18n.o src/delegate.o src/telegram.o src/config.o src/plugin.o BIN = splinter BINOBJ = src/main.o src/ui.o PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \ @@ -31,7 +31,7 @@ PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \ plugins/ring/ring.so TESTS = tests/test_buf tests/test_tool tests/test_session tests/test_conv \ tests/test_transport tests/test_agent tests/test_openai \ - tests/test_theme tests/test_plugin tests/test_delegate tests/test_builtin tests/test_ascii tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_cli tests/test_compactor + tests/test_theme tests/test_plugin tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_cli tests/test_compactor RPATH = -Wl,-rpath,'$$ORIGIN' PLUGIN_RPATH = -Wl,-rpath,'$$ORIGIN/../..' @@ -101,6 +101,7 @@ src/palettes.o: src/palettes.h src/decomp.o: src/decomp.h src/i18n.o: src/i18n.h include/splinter.h src/delegate.o: src/config.h include/splinter.h +src/telegram.o: include/splinter.h src/config.o: src/config.h include/splinter.h src/plugin.o: include/splinter.h include/splinter_plugin.h src/ui.o: src/ui.h src/theme.h src/decomp.h src/i18n.h include/splinter.h include/splinter_plugin.h @@ -124,6 +125,8 @@ tests/test_theme: tests/test_theme.c $(LIB) $(CC) $(CFLAGS) -o $@ tests/test_theme.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_focus: tests/test_focus.c $(LIB) $(PLUGIN) $(CC) $(CFLAGS) -o $@ tests/test_focus.c -L. -lsplinter $(TEST_RPATH) $(LIBS) +tests/test_telegram: tests/test_telegram.c $(LIB) + $(CC) $(CFLAGS) -o $@ tests/test_telegram.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_delegate: tests/test_delegate.c $(LIB) $(CC) $(CFLAGS) -o $@ tests/test_delegate.c -L. -lsplinter $(TEST_RPATH) $(LIBS) tests/test_builtin: tests/test_builtin.c $(LIB) diff --git a/README.md b/README.md index 1993ac0..c8d24ac 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,25 @@ key that `en.msg` has. Ships with `en` and `de`. Plugins translate their own strings with `sp_t()`. +## Gateway mode + +`--daemon` turns splinter into a Telegram bot: long-poll `getUpdates`, one turn +per message, reply. No curses, no terminal. + + ~/.splinter/telegram.token the token, mode 0600 (or SPLINTER_TELEGRAM_TOKEN) + telegram_allow = 8300935 who is answered, comma separated; nobody by default + +The token is read from a file or the environment and never from an argument, and +the message loop keeps no state on disk beyond the session: a restart re-delivers +the last update, which costs one duplicated answer and never a lost message. +Signature handling is the session's business, not the gateway's. + +A bot cannot start a conversation - the user has to write first, otherwise the +API answers `chat not found`. That is Telegram, not the harness. + +`docs/splinter-gateway.service` is a systemd user unit if it should survive a +logout. + ## The exit ring `plugins/ring/ring.so` holds several ways to reach a model and walks them in diff --git a/docs/splinter-gateway.service b/docs/splinter-gateway.service new file mode 100644 index 0000000..55f0f28 --- /dev/null +++ b/docs/splinter-gateway.service @@ -0,0 +1,22 @@ +# systemd --user unit for splinter's gateway mode. +# +# cp docs/splinter-gateway.service ~/.config/systemd/user/ +# systemctl --user daemon-reload +# systemctl --user enable --now splinter-gateway +# +# The token lives in ~/.splinter/telegram.token (0600) and is never passed as an +# argument: arguments show up in ps. +[Unit] +Description=splinter gateway (Telegram) +After=network-online.target + +[Service] +Type=simple +ExecStart=%h/src/splinter/splinter --daemon +Restart=on-failure +RestartSec=5 +# a gateway that answers the world is not a gateway, it is a leak +Environment=SPLINTER_CONFIG=%h/.splinter/splinter.conf + +[Install] +WantedBy=default.target diff --git a/include/splinter.h b/include/splinter.h index f326023..8a55d1d 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -252,6 +252,10 @@ int sp_agent_run(struct sp_agent *, const char *user_text, int sp_builtin_register(struct sp_registry *); struct sp_config; int sp_delegate_register(struct sp_registry *, const struct sp_config *); +/* Gateway mode: answers on Telegram until SIGINT/SIGTERM. */ +int sp_telegram_run(struct sp_agent *, const char *token, const char *allow, + struct sp_buf *err); +int sp_telegram_token(char *buf, size_t len, const char *path); int sp_delegate_choose(const struct sp_config *, const char *task, const char *tags, char *id, size_t cap, char *why, size_t whylen, int *score); diff --git a/libsplinter.so b/libsplinter.so index c9df226..789f3e8 100755 Binary files a/libsplinter.so and b/libsplinter.so differ diff --git a/src/config.c b/src/config.c index d69191d..44d41af 100644 --- a/src/config.c +++ b/src/config.c @@ -314,6 +314,8 @@ load_one(struct sp_config *c, const char *path, struct sp_buf *err) set_str(c->key_env, sizeof(c->key_env), val); else if (!strcmp(key, "transport")) set_str(c->transport, sizeof(c->transport), val); + else if (!strcmp(key, "telegram_allow")) + set_str(c->telegram_allow, sizeof(c->telegram_allow), val); else if (!strcmp(key, "locale")) set_str(c->locale, sizeof(c->locale), val); else if (!strcmp(key, "theme")) diff --git a/src/config.h b/src/config.h index 8cf4bb4..ee31b9d 100644 --- a/src/config.h +++ b/src/config.h @@ -65,6 +65,7 @@ struct sp_config { char system_prompt[1024]; char session_dir[512]; char cli_cmd[512]; + char telegram_allow[256]; /* comma separated user ids */ char locale[32]; /* language code, exported as SPLINTER_LOCALE */ char plugins[SP_CONFIG_MAX_PLUGINS][512]; size_t nplugins; diff --git a/src/main.c b/src/main.c index a5a8bf0..4bda4e8 100644 --- a/src/main.c +++ b/src/main.c @@ -43,6 +43,7 @@ usage(FILE *f) " --list-themes print the palette names and exit\n" " --resume load the session's history into the conversation\n" " --choose TEXT print which delegate fits TEXT, then exit\n" + " --daemon answer on Telegram until SIGINT\n" " --autonomous run mutating tools without asking\n" " --steps N tool rounds per turn (default 8)\n" " --session DIR session directory (default ~/.splinter)\n" @@ -124,6 +125,7 @@ main(int argc, char **argv) struct sp_mock mock; int have_mock = 0; int i, rc, chatmode = 0, resume = 0; + int daemon_mode = 0; struct sp_config conf; const char *choose_text = NULL; const char *plugins[16]; @@ -194,6 +196,8 @@ main(int argc, char **argv) return 2; } choose_text = argv[++i]; + } else if (!strcmp(argv[i], "--daemon")) { + daemon_mode = 1; } else if (!strcmp(argv[i], "--resume")) { resume = 1; } else if (!strcmp(argv[i], "--autonomous")) { @@ -483,6 +487,27 @@ main(int argc, char **argv) * harness keeps working, the operator sees why. */ + if (daemon_mode) { + char token[256], tpath[700]; + + snprintf(tpath, sizeof(tpath), "%s/telegram.token", sess.dir); + if (sp_telegram_token(token, sizeof(token), tpath) != 0) { + fprintf(stderr, "splinter: no Telegram token: put it in " + "%s (0600) or set SPLINTER_TELEGRAM_TOKEN\n", tpath); + return 2; + } + if (conf.telegram_allow[0] == '\0') { + fprintf(stderr, "splinter: telegram_allow is empty - " + "nobody would be answered\n"); + return 2; + } + rc = sp_telegram_run(&ag, token, conf.telegram_allow, &err); + if (rc != 0) + fprintf(stderr, "splinter: %s\n", + err.p != NULL ? err.p : "gateway failed"); + return rc == 0 ? 0 : 1; + } + if (chatmode) { rc = sp_ui_run(&ag, endpoint, theme, host); if (have_mock) diff --git a/src/telegram.c b/src/telegram.c new file mode 100644 index 0000000..3a9239e --- /dev/null +++ b/src/telegram.c @@ -0,0 +1,334 @@ +/* + * splinter -- the gateway mode. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + * + * A daemon that answers on Telegram: long-polls getUpdates, runs one turn per + * message, replies. No curses, no terminal - the same agent, driven by a socket. + * + * Rules that are not negotiable here: + * + * - the token is read from a file (0600) or the environment, never from an + * argument: an argument ends up in ps and in shell history; + * - only the configured users are answered. Everyone else is ignored, and the + * message is logged without its text; + * - a failed request is reported and the loop continues. A gateway that dies + * on one bad message is a gateway that is down until someone notices. + * + * The offset is kept in memory only: a restart re-delivers the last update, + * which costs one duplicated answer and never a lost message. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "splinter.h" +#include "mcp.h" + +#define TG_API "https://api.telegram.org/bot" +#define TG_MAX_CHUNK 3500 +#define TG_POLL_S 25 + +static volatile int tg_stop; + +static void +on_signal(int sig) +{ + (void)sig; + tg_stop = 1; +} + +/* + * Run curl with the URL built here and return its stdout. + * + * The token is part of the URL, so the command string is never logged and the + * process is exec'd directly instead of through a shell: a token with a quote in + * it would otherwise change the command. + */ +static int +tg_curl(const char *url, const char *post_body, struct sp_buf *out, + struct sp_buf *err) +{ + int fds[2]; + pid_t child; + + if (pipe(fds) != 0) { + sp_buf_printf(err, "telegram: pipe: %s", strerror(errno)); + return -1; + } + child = fork(); + if (child < 0) { + sp_buf_printf(err, "telegram: fork: %s", strerror(errno)); + close(fds[0]); + close(fds[1]); + return -1; + } + if (child == 0) { + char *argv[10]; + int n = 0; + + (void)dup2(fds[1], STDOUT_FILENO); + close(fds[0]); + close(fds[1]); + argv[n++] = "curl"; + argv[n++] = "-sS"; + argv[n++] = "-m"; + argv[n++] = "60"; + if (post_body != NULL) { + argv[n++] = "-X"; + argv[n++] = "POST"; + argv[n++] = "-H"; + argv[n++] = "Content-Type: application/json"; + argv[n++] = "--data-binary"; + argv[n++] = (char *)post_body; + } + argv[n++] = (char *)url; + argv[n] = NULL; + execvp("curl", argv); + _exit(127); + } + close(fds[1]); + { + struct pollfd pfd; + char chunk[4096]; + + for (;;) { + ssize_t got; + + pfd.fd = fds[0]; + pfd.events = POLLIN; + if (poll(&pfd, 1, 90000) <= 0) { + (void)kill(child, SIGKILL); + break; + } + got = read(fds[0], chunk, sizeof(chunk)); + if (got <= 0) + break; + if (sp_buf_add(out, chunk, (size_t)got) != 0) + break; + } + } + close(fds[0]); + { + int st = 0; + + (void)waitpid(child, &st, 0); + if (!WIFEXITED(st) || WEXITSTATUS(st) != 0) { + sp_buf_printf(err, "telegram: curl failed (%d)", + WIFEXITED(st) ? WEXITSTATUS(st) : -1); + return -1; + } + } + return 0; +} + +static int +send_message(const char *token, long chat_id, const char *text, + struct sp_buf *err) +{ + struct sp_buf url, body, reply; + size_t off = 0, len = strlen(text); + int rc = 0; + + if (sp_buf_init(&url) != 0 || sp_buf_init(&body) != 0 || + sp_buf_init(&reply) != 0) + return -1; + sp_buf_printf(&url, "%s%s/sendMessage", TG_API, token); + do { + size_t take = len - off; + + if (take > TG_MAX_CHUNK) + take = TG_MAX_CHUNK; + sp_buf_clear(&body); + sp_buf_printf(&body, "{\"chat_id\":%ld,\"text\":\"", chat_id); + { + char *piece = malloc(take + 1); + + if (piece == NULL) { + rc = -1; + break; + } + memcpy(piece, text + off, take); + piece[take] = '\0'; + (void)sp_json_escape(&body, piece); + free(piece); + } + sp_buf_puts(&body, "\"}"); + sp_buf_clear(&reply); + if (tg_curl(url.p, body.p, &reply, err) != 0) { + rc = -1; + break; + } + if (strstr(reply.p != NULL ? reply.p : "", "\"ok\":true") == NULL) { + sp_buf_printf(err, "telegram: sendMessage refused: %.200s", + reply.p != NULL ? reply.p : ""); + rc = -1; + break; + } + off += take; + } while (off < len); + sp_buf_free(&url); + sp_buf_free(&body); + sp_buf_free(&reply); + return rc; +} + +/* Is this update for a user we answer? */ +static int +allowed(const char *allow, long id) +{ + char copy[256], *p, *save = NULL; + + if (allow == NULL || *allow == '\0') + return 0; /* empty means nobody */ + snprintf(copy, sizeof(copy), "%s", allow); + for (p = strtok_r(copy, ", ", &save); p != NULL; + p = strtok_r(NULL, ", ", &save)) + if (strtol(p, NULL, 10) == id) + return 1; + return 0; +} + +int +sp_telegram_run(struct sp_agent *ag, const char *token, const char *allow, + struct sp_buf *err) +{ + long offset = 0; + struct sp_buf url, reply, answer, aerr; + + if (sp_buf_init(&url) != 0 || sp_buf_init(&reply) != 0 || + sp_buf_init(&answer) != 0 || sp_buf_init(&aerr) != 0) + return -1; + + (void)signal(SIGINT, on_signal); + (void)signal(SIGTERM, on_signal); + fprintf(stderr, "splinter: gateway listening (allow: %s)\n", + allow != NULL && *allow != '\0' ? allow : "nobody"); + + while (!tg_stop) { + mcp_json *v; + const mcp_json *result, *update; + int ok; + + sp_buf_clear(&url); + sp_buf_printf(&url, "%s%s/getUpdates?timeout=%d&offset=%ld", + TG_API, token, TG_POLL_S, offset); + sp_buf_clear(&reply); + if (tg_curl(url.p, NULL, &reply, err) != 0) { + fprintf(stderr, "splinter: %s\n", + err->p != NULL ? err->p : "poll failed"); + sp_buf_clear(err); + sleep(3); + continue; + } + v = mcp_parse(reply.p); + if (v == NULL) + continue; + ok = mcp_arg_bool(v, "ok", 0); + result = mcp_arg(v, "result"); + if (!ok || result == NULL) { + mcp_json_free(v); + sleep(3); + continue; + } + /* updates come as an array; libmcp hands them out by index */ + { + size_t i; + + for (i = 0; (update = mcp_array_at(result, i)) != NULL; + i++) { + const mcp_json *msg; + const char *text; + long chat_id, from; + int update_id; + + update_id = mcp_arg_int(update, "update_id", 0); + offset = (long)update_id + 1; + msg = mcp_arg(update, "message"); + if (msg == NULL) + continue; + text = mcp_arg_string(msg, "text"); + chat_id = mcp_arg_int(mcp_arg(msg, "chat"), + "id", 0); + from = mcp_arg_int(mcp_arg(msg, "from"), + "id", 0); + if (text == NULL || *text == '\0' || chat_id == 0) + continue; + if (!allowed(allow, from)) { + fprintf(stderr, "splinter: ignoring " + "message from %ld\n", from); + continue; + } + sp_buf_clear(&answer); + sp_buf_clear(&aerr); + if (sp_agent_run(ag, text, &answer, &aerr) != 0) { + (void)send_message(token, chat_id, + aerr.p != NULL ? aerr.p : + "turn failed", err); + sp_buf_clear(err); + continue; + } + (void)send_message(token, chat_id, + answer.p != NULL ? answer.p : "(leer)", err); + sp_buf_clear(err); + if (ag->sess != NULL && answer.p != NULL) + (void)sp_session_append(ag->sess, "user", + text, err); + if (ag->sess != NULL && answer.p != NULL) + (void)sp_session_append(ag->sess, + "assistant", answer.p, err); + } + } + mcp_json_free(v); + } + sp_buf_free(&url); + sp_buf_free(&reply); + sp_buf_free(&answer); + sp_buf_free(&aerr); + fprintf(stderr, "splinter: gateway stopped\n"); + return 0; +} + +/* + * The token: file first (0600), then environment. A token on disk can be locked + * down; a token in an argument cannot. + */ +int +sp_telegram_token(char *buf, size_t len, const char *path) +{ + FILE *f; + char line[256]; + + f = fopen(path, "r"); + if (f != NULL) { + size_t n; + + if (fgets(line, sizeof(line), f) == NULL) { + fclose(f); + return -1; + } + fclose(f); + n = strcspn(line, "\r\n"); + line[n] = '\0'; + if (line[0] == '\0') + return -1; + snprintf(buf, len, "%s", line); + return 0; + } + { + const char *env = getenv("SPLINTER_TELEGRAM_TOKEN"); + + if (env == NULL || *env == '\0') + return -1; + snprintf(buf, len, "%s", env); + } + return 0; +} diff --git a/tests/test_config b/tests/test_config index 9823d25..62ea334 100755 Binary files a/tests/test_config and b/tests/test_config differ diff --git a/tests/test_delegate b/tests/test_delegate index ec7fc9c..40503d8 100755 Binary files a/tests/test_delegate and b/tests/test_delegate differ diff --git a/tests/test_telegram b/tests/test_telegram new file mode 100755 index 0000000..a05a822 Binary files /dev/null and b/tests/test_telegram differ diff --git a/tests/test_telegram.c b/tests/test_telegram.c new file mode 100644 index 0000000..5d74cfe --- /dev/null +++ b/tests/test_telegram.c @@ -0,0 +1,77 @@ +/* + * splinter -- gateway bits that can be tested without Telegram. + * + * The token must come from a file (0600) or the environment, never from an + * argument, so both paths are checked here. The network loop is not tested + * against api.telegram.org: it is a loop over one HTTP call, and a test that + * needs the internet fails for reasons that have nothing to do with the code. + */ +#include +#include +#include +#include +#include + +#include "splinter.h" + +static int failures; + +#define CHECK(cond) do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ +} while (0) + +int +main(void) +{ + char dir[512], path[600], buf[256]; + const char *tmp = getenv("TMPDIR"); + FILE *f; + + if (tmp == NULL || *tmp == '\0') + tmp = "/var/tmp"; + snprintf(dir, sizeof(dir), "%s/splinter-tg-XXXXXX", tmp); + CHECK(mkdtemp(dir) != NULL); + snprintf(path, sizeof(path), "%s/telegram.token", dir); + + /* no file, no environment: refuse instead of using an empty token */ + unsetenv("SPLINTER_TELEGRAM_TOKEN"); + CHECK(sp_telegram_token(buf, sizeof(buf), path) != 0); + + /* the file wins, trailing newline stripped */ + f = fopen(path, "w"); + CHECK(f != NULL); + if (f != NULL) { + fputs("123:abc\n", f); + fclose(f); + } + CHECK(sp_telegram_token(buf, sizeof(buf), path) == 0); + CHECK(strcmp(buf, "123:abc") == 0); + + /* environment is the fallback when there is no file */ + CHECK(sp_telegram_token(buf, sizeof(buf), "/nonexistent/token") != 0); + CHECK(setenv("SPLINTER_TELEGRAM_TOKEN", "456:def", 1) == 0); + CHECK(sp_telegram_token(buf, sizeof(buf), "/nonexistent/token") == 0); + CHECK(strcmp(buf, "456:def") == 0); + + /* an empty file is not a token */ + f = fopen(path, "w"); + CHECK(f != NULL); + if (f != NULL) + fclose(f); + unsetenv("SPLINTER_TELEGRAM_TOKEN"); + CHECK(sp_telegram_token(buf, sizeof(buf), path) != 0); + + { + char cmd[600]; + + snprintf(cmd, sizeof(cmd), "rm -rf '%s'", dir); + if (system(cmd) != 0) + fprintf(stderr, "cleanup failed\n"); + } + if (failures == 0) + printf("test_telegram: ok\n"); + return failures == 0 ? 0 : 1; +}