/model writes its choice to <config>.d/90-model.conf, so the next start uses
it; picking main deletes the file and the configuration speaks again. With a
plugin transport nothing is written, because that program picks the model.
/model probe asks every endpoint /v1/models and offers what it really serves
as buttons; the callback carries an index, because a GGUF path does not fit
in Telegram's 64 bytes. The TUI gets the same command: the list, or
/model <id|name>, with the same persistence.
/connect runs one tiny turn against the provider it just saved (30 s) and
says whether endpoint, model and key answer. The message with the buttons
goes out before the wait starts, so the save is visible immediately.
A2A no longer refuses binary parts: file{bytes} and raw with a non-text media
type are written to the session's inbox (0600, 8 MiB cap) and the prompt says
[file <name> at <path> (mime, n bytes)], so a text model can hand the file to
a tool. The client saves what a remote agent sends the same way
(SPLINTER_A2A_INBOX). SubscribeToTask stays refused: the task store has no
live events, and a one-shot replay would pretend to be a subscription.
Markdown gains <https://...> autolinks and images (as links, since Telegram
has no inline image without sendPhoto).
1932 lines
52 KiB
C
1932 lines
52 KiB
C
/*
|
|
* 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 <errno.h>
|
|
#include <poll.h>
|
|
#include <pthread.h>
|
|
#include <signal.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <strings.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/types.h>
|
|
#include <sys/wait.h>
|
|
#include <unistd.h>
|
|
|
|
#include "ack.h"
|
|
#include "curl.h"
|
|
#include "splinter.h"
|
|
#include "i18n.h"
|
|
#include "mcp.h"
|
|
#include "log.h"
|
|
#include "cmdscript.h"
|
|
#include "interview.h"
|
|
#include "tgmd.h"
|
|
#include "config.h"
|
|
#include "providers.h"
|
|
#include "splinter_plugin.h"
|
|
|
|
/*
|
|
* Where the API lives. Overridable, because a gateway you cannot test without
|
|
* Telegram is a gateway you only test in production.
|
|
*/
|
|
static const char *
|
|
api_base(void)
|
|
{
|
|
const char *env = getenv("SPLINTER_TELEGRAM_API");
|
|
|
|
return env != NULL && *env != '\0' ? env : "https://api.telegram.org";
|
|
}
|
|
|
|
|
|
#define TG_MAX_CHUNK 3500
|
|
/* a piece of rendered HTML, tag overhead included; Telegram's cap is 4096 */
|
|
#define TG_MAX_HTML 3200
|
|
#define TG_POLL_S 25
|
|
|
|
static volatile int tg_stop;
|
|
|
|
static int tg_curl(const char *url, const char *post_body, struct sp_buf *out,
|
|
struct sp_buf *err);
|
|
|
|
/* Telegram shows "typing" for about five seconds; a turn takes longer. */
|
|
struct typing {
|
|
char token[256];
|
|
long chat_id;
|
|
volatile int *stop;
|
|
};
|
|
|
|
static void *
|
|
typing_thread(void *arg)
|
|
{
|
|
struct typing *t = arg;
|
|
struct sp_buf url, reply, err;
|
|
int i;
|
|
|
|
if (sp_buf_init(&url) != 0 || sp_buf_init(&reply) != 0 ||
|
|
sp_buf_init(&err) != 0)
|
|
return NULL;
|
|
sp_buf_printf(&url, "%s/bot%s/sendChatAction", api_base(), t->token);
|
|
{
|
|
struct sp_buf body;
|
|
|
|
if (sp_buf_init(&body) != 0)
|
|
return NULL;
|
|
sp_buf_printf(&body, "{\"chat_id\":%ld,\"action\":\"typing\"}",
|
|
t->chat_id);
|
|
for (i = 0; i < 300 && *t->stop == 0; i++) {
|
|
sp_buf_clear(&reply);
|
|
(void)tg_curl(url.p, body.p, &reply, &err);
|
|
sp_buf_clear(&err);
|
|
sleep(4);
|
|
}
|
|
sp_buf_free(&body);
|
|
}
|
|
sp_buf_free(&url);
|
|
sp_buf_free(&reply);
|
|
sp_buf_free(&err);
|
|
return NULL;
|
|
}
|
|
|
|
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, and an argument is readable by every user of
|
|
* the machine. So the URL goes to curl on stdin (sp_curl_start), and argv holds
|
|
* nothing that would let anybody else drive the bot.
|
|
*/
|
|
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;
|
|
const char *args[12];
|
|
int n = 0;
|
|
|
|
args[n++] = "-sS";
|
|
args[n++] = "-m";
|
|
args[n++] = "60";
|
|
if (post_body != NULL) {
|
|
args[n++] = "-X";
|
|
args[n++] = "POST";
|
|
args[n++] = "-H";
|
|
args[n++] = "Content-Type: application/json";
|
|
args[n++] = "--data-binary";
|
|
args[n++] = post_body;
|
|
}
|
|
args[n] = NULL;
|
|
fds[0] = sp_curl_start(args, url, NULL, 0, &child, err);
|
|
if (fds[0] < 0)
|
|
return -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;
|
|
}
|
|
|
|
/* {"ok":true,...} - parsed, because a substring misses "ok": true */
|
|
static int
|
|
tg_reply_ok(const char *reply)
|
|
{
|
|
mcp_json *v = reply != NULL ? mcp_parse(reply) : NULL;
|
|
int ok;
|
|
|
|
if (v == NULL)
|
|
return 0;
|
|
ok = mcp_arg_bool(v, "ok", 0);
|
|
mcp_json_free(v);
|
|
return ok;
|
|
}
|
|
|
|
/*
|
|
* One sendMessage call. 'parse_mode' is NULL for plain text and "HTML" for a
|
|
* rendered markdown answer; 'markup' is a ready JSON keyboard, or NULL.
|
|
*/
|
|
static int
|
|
post_message(const char *token, long chat_id, const char *text,
|
|
const char *markup, const char *parse_mode, struct sp_buf *err)
|
|
{
|
|
struct sp_buf url, body, reply, sink;
|
|
int rc = 0;
|
|
|
|
if (sp_buf_init(&url) != 0 || sp_buf_init(&body) != 0 ||
|
|
sp_buf_init(&reply) != 0 || sp_buf_init(&sink) != 0)
|
|
return -1;
|
|
/*
|
|
* Half the callers pass NULL for err ("best effort"). The first refused
|
|
* message - too long, invalid UTF-8, a blocked bot - then wrote its error
|
|
* through a NULL pointer and took the gateway down.
|
|
*/
|
|
if (err == NULL)
|
|
err = &sink;
|
|
sp_buf_printf(&url, "%s/bot%s/sendMessage", api_base(), token);
|
|
if (sp_buf_printf(&body, "{\"chat_id\":%ld,\"text\":\"", chat_id) != 0 ||
|
|
sp_json_escape(&body, text) != 0 ||
|
|
sp_buf_puts(&body, "\"") != 0)
|
|
rc = -1;
|
|
if (rc == 0 && parse_mode != NULL && *parse_mode != '\0' &&
|
|
sp_buf_printf(&body, ",\"parse_mode\":\"%s\"", parse_mode) != 0)
|
|
rc = -1;
|
|
if (rc == 0 && markup != NULL && *markup != '\0' &&
|
|
sp_buf_printf(&body, ",\"reply_markup\":%s", markup) != 0)
|
|
rc = -1;
|
|
if (rc == 0 && sp_buf_puts(&body, "}") != 0)
|
|
rc = -1;
|
|
if (rc == 0 && tg_curl(url.p, body.p, &reply, err) != 0)
|
|
rc = -1;
|
|
if (rc == 0 && !tg_reply_ok(reply.p)) {
|
|
sp_buf_printf(err, "telegram: sendMessage refused: %.200s",
|
|
reply.p != NULL ? reply.p : "");
|
|
rc = -1;
|
|
}
|
|
sp_buf_free(&url);
|
|
sp_buf_free(&body);
|
|
sp_buf_free(&sink);
|
|
sp_buf_free(&reply);
|
|
return rc;
|
|
}
|
|
|
|
/* Markdown on by default; SPLINTER_TG_MARKDOWN=0 sends the text as it came. */
|
|
static int
|
|
tg_markdown_enabled(void)
|
|
{
|
|
const char *env = getenv("SPLINTER_TG_MARKDOWN");
|
|
|
|
if (env == NULL || *env == '\0')
|
|
return 1;
|
|
return strcmp(env, "0") != 0 && strcmp(env, "false") != 0 &&
|
|
strcmp(env, "off") != 0 && strcmp(env, "no") != 0;
|
|
}
|
|
|
|
static int
|
|
send_message_markup(const char *token, long chat_id, const char *text,
|
|
const char *markup, struct sp_buf *err)
|
|
{
|
|
size_t off = 0, len = strlen(text);
|
|
|
|
do {
|
|
size_t take = len - off;
|
|
char *piece;
|
|
|
|
if (take > TG_MAX_CHUNK) {
|
|
take = TG_MAX_CHUNK;
|
|
/*
|
|
* Never inside a UTF-8 character: a cut umlaut is invalid
|
|
* UTF-8, Telegram refuses the chunk, and the rest of the
|
|
* answer was lost with it. Back up to a lead byte.
|
|
*/
|
|
while (take > 0 &&
|
|
((unsigned char)text[off + take] & 0xc0) == 0x80)
|
|
take--;
|
|
if (take == 0)
|
|
take = TG_MAX_CHUNK; /* not UTF-8 at all */
|
|
}
|
|
piece = malloc(take + 1);
|
|
if (piece == NULL)
|
|
return -1;
|
|
memcpy(piece, text + off, take);
|
|
piece[take] = '\0';
|
|
if (post_message(token, chat_id, piece,
|
|
off + take >= len ? markup : NULL, NULL, err) != 0) {
|
|
free(piece);
|
|
return -1;
|
|
}
|
|
free(piece);
|
|
off += take;
|
|
} while (off < len);
|
|
return 0;
|
|
}
|
|
|
|
/*
|
|
* The HTML Telegram refused (a broken entity, a tag it does not know): send
|
|
* the same piece as text. Losing the shape of an answer is bad; losing the
|
|
* answer is worse.
|
|
*/
|
|
static int
|
|
send_html_stripped(const char *token, long chat_id, const char *html,
|
|
const char *markup, struct sp_buf *err)
|
|
{
|
|
struct sp_buf plain, text;
|
|
size_t i, start = 0;
|
|
int rc;
|
|
|
|
if (sp_buf_init(&plain) != 0 || sp_buf_init(&text) != 0) {
|
|
sp_buf_free(&plain);
|
|
sp_buf_free(&text);
|
|
return -1;
|
|
}
|
|
for (i = 0; html[i] != '\0'; i++) {
|
|
if (html[i] == '<') {
|
|
const char *gt = strchr(html + i, '>');
|
|
|
|
if (gt != NULL) {
|
|
if (i > start &&
|
|
sp_buf_add(&plain, html + start, i - start) != 0)
|
|
goto fail;
|
|
i = (size_t)(gt - html);
|
|
start = i + 1;
|
|
}
|
|
}
|
|
}
|
|
if (sp_buf_add(&plain, html + start, i - start) != 0)
|
|
goto fail;
|
|
/* unescape what the renderer escaped */
|
|
for (i = 0; plain.p != NULL && plain.p[i] != '\0'; i++) {
|
|
const char *rep = NULL;
|
|
size_t skip = 1;
|
|
|
|
if (strncmp(plain.p + i, "&", 5) == 0) {
|
|
rep = "&";
|
|
skip = 5;
|
|
} else if (strncmp(plain.p + i, "<", 4) == 0) {
|
|
rep = "<";
|
|
skip = 4;
|
|
} else if (strncmp(plain.p + i, ">", 4) == 0) {
|
|
rep = ">";
|
|
skip = 4;
|
|
} else if (strncmp(plain.p + i, """, 6) == 0) {
|
|
rep = "\"";
|
|
skip = 6;
|
|
}
|
|
if (rep != NULL) {
|
|
if (sp_buf_puts(&text, rep) != 0)
|
|
goto fail;
|
|
i += skip - 1;
|
|
continue;
|
|
}
|
|
if (sp_buf_add(&text, plain.p + i, 1) != 0)
|
|
goto fail;
|
|
}
|
|
rc = post_message(token, chat_id,
|
|
text.p != NULL ? text.p : "", markup, NULL, err);
|
|
sp_buf_free(&plain);
|
|
sp_buf_free(&text);
|
|
return rc;
|
|
fail:
|
|
sp_buf_free(&plain);
|
|
sp_buf_free(&text);
|
|
return -1;
|
|
}
|
|
|
|
/*
|
|
* The model writes markdown; Telegram draws HTML. Render it, then hand it over
|
|
* in pieces that carry their own open and closed tags, so a long answer is not
|
|
* one refused message and a chunk boundary is never inside "<code>".
|
|
*/
|
|
static int
|
|
send_markdown(const char *token, long chat_id, const char *text,
|
|
const char *markup, struct sp_buf *err)
|
|
{
|
|
struct sp_buf html, piece;
|
|
struct sp_tgmd_cursor cur;
|
|
int rc = 0, n;
|
|
|
|
if (text == NULL || *text == '\0' || !tg_markdown_enabled())
|
|
return send_message_markup(token, chat_id, text, markup, err);
|
|
if (sp_buf_init(&html) != 0 || sp_buf_init(&piece) != 0) {
|
|
sp_buf_free(&html);
|
|
sp_buf_free(&piece);
|
|
return send_message_markup(token, chat_id, text, markup, err);
|
|
}
|
|
if (sp_tgmd_render(text, &html) != 0 || html.len == 0) {
|
|
sp_buf_free(&html);
|
|
sp_buf_free(&piece);
|
|
return send_message_markup(token, chat_id, text, markup, err);
|
|
}
|
|
sp_tgmd_cursor_init(&cur, html.p);
|
|
while ((n = sp_tgmd_next(&cur, TG_MAX_HTML, &piece)) > 0) {
|
|
/*
|
|
* Only the last piece carries the keyboard: two "reply" buttons
|
|
* would be two chances to answer the same request.
|
|
*/
|
|
const char *mk = cur.pos >= cur.len && cur.nopen == 0 ?
|
|
markup : NULL;
|
|
|
|
if (post_message(token, chat_id, piece.p, mk, "HTML", err) != 0) {
|
|
sp_buf_clear(err);
|
|
if (send_html_stripped(token, chat_id, piece.p, mk,
|
|
err) != 0) {
|
|
rc = -1;
|
|
break;
|
|
}
|
|
sp_buf_clear(err);
|
|
}
|
|
}
|
|
if (n < 0)
|
|
rc = -1;
|
|
sp_tgmd_cursor_free(&cur);
|
|
sp_buf_free(&html);
|
|
sp_buf_free(&piece);
|
|
return rc;
|
|
}
|
|
|
|
static int
|
|
send_message(const char *token, long chat_id, const char *text,
|
|
struct sp_buf *err)
|
|
{
|
|
return send_message_markup(token, chat_id, text, NULL, err);
|
|
}
|
|
|
|
/* one best-effort Bot API call whose answer nobody reads (menus, callbacks) */
|
|
static void
|
|
tg_api_ok(const char *token, const char *method, const char *body)
|
|
{
|
|
struct sp_buf url, reply, err;
|
|
|
|
if (sp_buf_init(&url) != 0 || sp_buf_init(&reply) != 0 ||
|
|
sp_buf_init(&err) != 0)
|
|
return;
|
|
sp_buf_printf(&url, "%s/bot%s/%s", api_base(), token, method);
|
|
(void)tg_curl(url.p, body, &reply, &err);
|
|
sp_buf_free(&url);
|
|
sp_buf_free(&reply);
|
|
sp_buf_free(&err);
|
|
}
|
|
|
|
static void
|
|
tg_answer_callback(const char *token, const char *cqid, const char *text)
|
|
{
|
|
struct sp_buf b;
|
|
|
|
if (sp_buf_init(&b) != 0)
|
|
return;
|
|
sp_buf_puts(&b, "{\"callback_query_id\":\"");
|
|
sp_json_escape(&b, cqid);
|
|
sp_buf_puts(&b, "\",\"text\":\"");
|
|
sp_json_escape(&b, text);
|
|
sp_buf_puts(&b, "\"}");
|
|
tg_api_ok(token, "answerCallbackQuery", b.p);
|
|
sp_buf_free(&b);
|
|
}
|
|
|
|
static void
|
|
tg_clear_buttons(const char *token, long chat, long mid)
|
|
{
|
|
char body[256];
|
|
|
|
snprintf(body, sizeof(body), "{\"chat_id\":%ld,\"message_id\":%ld,"
|
|
"\"reply_markup\":{\"inline_keyboard\":[]}}", chat, mid);
|
|
tg_api_ok(token, "editMessageReplyMarkup", body);
|
|
}
|
|
|
|
/*
|
|
* The command menu Telegram shows behind the menu button. Global per bot; the
|
|
* descriptions come from the catalogue, so a German gateway says German. The
|
|
* menu is best effort: a bot that cannot set it still answers messages.
|
|
*/
|
|
struct tg_cmd {
|
|
char name[40];
|
|
char desc[200];
|
|
};
|
|
|
|
#define TG_MAX_CMDS 100
|
|
|
|
static const char *
|
|
tg_known_desc(const char *name)
|
|
{
|
|
if (strcmp(name, "start") == 0)
|
|
return sp_t("tg.cmd.start");
|
|
if (strcmp(name, "help") == 0)
|
|
return sp_t("tg.cmd.help");
|
|
if (strcmp(name, "goal") == 0)
|
|
return sp_t("tg.cmd.goal");
|
|
if (strcmp(name, "recap") == 0)
|
|
return sp_t("tg.cmd.recap");
|
|
if (strcmp(name, "tasks") == 0)
|
|
return sp_t("tg.cmd.tasks");
|
|
return NULL;
|
|
}
|
|
|
|
/*
|
|
* Telegram command names are lower-case a-z, digits and underscore, at most 32
|
|
* characters. A program called "deploy.sh" stays usable as /deploy.sh in the
|
|
* chat but cannot appear in the menu; the help text still lists it.
|
|
*/
|
|
static void
|
|
tg_add_cmd(struct tg_cmd *cmds, int *n, const char *name, const char *desc)
|
|
{
|
|
size_t i;
|
|
const char *p;
|
|
|
|
if (name == NULL || *name == '\0' || *n >= TG_MAX_CMDS)
|
|
return;
|
|
for (i = 0; name[i] != '\0'; i++) {
|
|
if (i >= 32)
|
|
return;
|
|
if (!((name[i] >= 'a' && name[i] <= 'z') ||
|
|
(name[i] >= '0' && name[i] <= '9') || name[i] == '_'))
|
|
return;
|
|
}
|
|
for (i = 0; i < (size_t)*n; i++)
|
|
if (strcmp(cmds[i].name, name) == 0)
|
|
return;
|
|
snprintf(cmds[*n].name, sizeof(cmds[*n].name), "%s", name);
|
|
p = desc != NULL && *desc != '\0' ? desc : name;
|
|
snprintf(cmds[*n].desc, sizeof(cmds[*n].desc), "%s", p);
|
|
(*n)++;
|
|
}
|
|
|
|
/* host commands from plugins, then the programs in commands/ */
|
|
static void
|
|
tg_collect(struct sp_host *host, const char *sess_dir, struct tg_cmd *cmds,
|
|
int *n)
|
|
{
|
|
struct sp_buf list;
|
|
char dir[700], generic[200];
|
|
char *tok, *save;
|
|
|
|
tg_add_cmd(cmds, n, "start", tg_known_desc("start"));
|
|
tg_add_cmd(cmds, n, "help", tg_known_desc("help"));
|
|
tg_add_cmd(cmds, n, "interview", sp_t("tg.cmd.interview"));
|
|
tg_add_cmd(cmds, n, "model", sp_t("tg.cmd.model"));
|
|
tg_add_cmd(cmds, n, "connect", sp_t("tg.cmd.connect"));
|
|
if (sp_buf_init(&list) != 0)
|
|
return;
|
|
if (host != NULL) {
|
|
(void)sp_host_command_help(host, &list);
|
|
for (tok = list.len > 0 ? strtok_r(list.p, " /", &save) : NULL;
|
|
tok != NULL; tok = strtok_r(NULL, " /", &save)) {
|
|
const char *d = tg_known_desc(tok);
|
|
|
|
if (d == NULL) {
|
|
snprintf(generic, sizeof(generic),
|
|
sp_t("tg.cmd.run"), tok);
|
|
d = generic;
|
|
}
|
|
tg_add_cmd(cmds, n, tok, d);
|
|
}
|
|
}
|
|
if (sp_cmdscript_dir(sess_dir, dir, sizeof(dir)) == 0) {
|
|
sp_buf_clear(&list);
|
|
(void)sp_cmdscript_list(dir, &list);
|
|
for (tok = list.len > 0 ? strtok_r(list.p, " /", &save) : NULL;
|
|
tok != NULL; tok = strtok_r(NULL, " /", &save)) {
|
|
snprintf(generic, sizeof(generic), sp_t("tg.cmd.run"),
|
|
tok);
|
|
tg_add_cmd(cmds, n, tok, generic);
|
|
}
|
|
}
|
|
sp_buf_free(&list);
|
|
}
|
|
|
|
static void
|
|
tg_set_commands(const char *token, struct sp_host *host, const char *sess_dir)
|
|
{
|
|
struct tg_cmd cmds[TG_MAX_CMDS];
|
|
struct sp_buf body;
|
|
int n = 0, i;
|
|
|
|
tg_collect(host, sess_dir, cmds, &n);
|
|
if (sp_buf_init(&body) != 0)
|
|
return;
|
|
sp_buf_puts(&body, "{\"commands\":[");
|
|
for (i = 0; i < n; i++) {
|
|
if (i > 0)
|
|
sp_buf_puts(&body, ",");
|
|
sp_buf_puts(&body, "{\"command\":\"");
|
|
sp_json_escape(&body, cmds[i].name);
|
|
sp_buf_puts(&body, "\",\"description\":\"");
|
|
sp_json_escape(&body, cmds[i].desc);
|
|
sp_buf_puts(&body, "\"}");
|
|
}
|
|
sp_buf_puts(&body, "]}");
|
|
tg_api_ok(token, "setMyCommands", body.p);
|
|
sp_buf_free(&body);
|
|
}
|
|
|
|
/* /start and /help: the short text plus every command that exists right now */
|
|
static void
|
|
tg_help_text(struct sp_host *host, const char *sess_dir, struct sp_buf *out)
|
|
{
|
|
struct sp_buf list;
|
|
char dir[700];
|
|
|
|
sp_buf_puts(out, sp_t("tg.help"));
|
|
sp_buf_puts(out, "\n\n/start /help /interview /model /connect ");
|
|
if (host != NULL)
|
|
(void)sp_host_command_help(host, out);
|
|
if (sp_cmdscript_dir(sess_dir, dir, sizeof(dir)) == 0 &&
|
|
sp_buf_init(&list) == 0) {
|
|
(void)sp_cmdscript_list(dir, &list);
|
|
if (list.len > 0)
|
|
sp_buf_puts(out, list.p);
|
|
sp_buf_free(&list);
|
|
}
|
|
}
|
|
|
|
/*
|
|
* A Telegram id as a long. mcp_arg_int truncated to int: user ids above 2^31
|
|
* (most accounts made in recent years) became garbage and were never
|
|
* allowed(), and supergroup chats (-100...) got replies sent nowhere. Telegram
|
|
* promises ids fit in 52 bits, so the double the parser holds is exact.
|
|
*/
|
|
static long
|
|
tg_id(const mcp_json *obj, const char *key)
|
|
{
|
|
double d;
|
|
|
|
if (obj == NULL)
|
|
return 0;
|
|
d = mcp_arg_num(obj, key, 0);
|
|
if (!(d > -4503599627370496.0 && d < 4503599627370496.0))
|
|
return 0; /* NaN or beyond 2^52: not an id */
|
|
return (long)d;
|
|
}
|
|
|
|
/* 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;
|
|
}
|
|
|
|
/*
|
|
* The update offset is shared by the poll loop and tg_approve: an approval
|
|
* that waits keeps reading the chat, and the loop must not handle again what
|
|
* the approval already consumed.
|
|
*/
|
|
static long tg_offset;
|
|
|
|
/* the chat the current turn came from, for tg_approve */
|
|
static struct {
|
|
const char *token;
|
|
long chat_id;
|
|
const char *allow;
|
|
} tg_cur;
|
|
|
|
/*
|
|
* /interview in the chat: the same questions as `splinter --interview`, one
|
|
* message per answer. The state is per gateway process; a restart abandons a
|
|
* half-finished interview, as a closed terminal does.
|
|
*/
|
|
struct tg_interview {
|
|
int active;
|
|
long chat_id;
|
|
size_t step;
|
|
char answers[16][4096];
|
|
};
|
|
|
|
static struct tg_interview tg_iv;
|
|
|
|
static int
|
|
tg_interview_ask(const char *token, long chat_id, struct sp_buf *err)
|
|
{
|
|
const char *q = sp_interview_prompt(tg_iv.step);
|
|
const char *h = sp_interview_hint(tg_iv.step);
|
|
struct sp_buf msg;
|
|
|
|
if (q == NULL)
|
|
return -1;
|
|
if (sp_buf_init(&msg) != 0)
|
|
return -1;
|
|
sp_buf_printf(&msg, sp_t("tg.interview.question"), tg_iv.step + 1,
|
|
sp_interview_count(), q);
|
|
if (h != NULL && *h != '\0')
|
|
sp_buf_printf(&msg, "\n (%s)", h);
|
|
sp_buf_puts(&msg, "\n");
|
|
sp_buf_puts(&msg, sp_t("tg.interview.how"));
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
return 0;
|
|
}
|
|
|
|
static void
|
|
tg_interview_begin(const char *token, long chat_id, struct sp_buf *err)
|
|
{
|
|
struct sp_buf msg;
|
|
|
|
memset(&tg_iv, 0, sizeof(tg_iv));
|
|
tg_iv.active = 1;
|
|
tg_iv.chat_id = chat_id;
|
|
tg_iv.step = 0;
|
|
if (sp_buf_init(&msg) != 0)
|
|
return;
|
|
sp_buf_printf(&msg, sp_t("tg.interview.start"), sp_memory_user(),
|
|
sp_interview_count());
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
(void)tg_interview_ask(token, chat_id, err);
|
|
}
|
|
|
|
static void
|
|
tg_interview_end(const char *token, long chat_id, const char *session_dir,
|
|
struct sp_buf *err)
|
|
{
|
|
const char *ptrs[16];
|
|
char dir[600], path[700];
|
|
struct sp_buf msg;
|
|
size_t i, n = tg_iv.step;
|
|
|
|
if (n > 16)
|
|
n = 16;
|
|
for (i = 0; i < n; i++)
|
|
ptrs[i] = tg_iv.answers[i];
|
|
if (sp_interview_save(session_dir, ptrs, n, err) == 0) {
|
|
path[0] = '\0';
|
|
if (sp_profile_path(session_dir, dir, sizeof(dir)) != NULL)
|
|
snprintf(path, sizeof(path), "%s/%s.md", dir,
|
|
sp_memory_user());
|
|
if (sp_buf_init(&msg) == 0) {
|
|
sp_buf_printf(&msg, sp_t("tg.interview.saved"), path);
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
}
|
|
} else {
|
|
(void)send_message(token, chat_id,
|
|
err->p != NULL ? err->p : sp_t("err.turn_failed"), err);
|
|
}
|
|
memset(&tg_iv, 0, sizeof(tg_iv));
|
|
}
|
|
|
|
static void
|
|
tg_interview_answer(const char *token, long chat_id, const char *text,
|
|
const char *session_dir, struct sp_buf *err)
|
|
{
|
|
struct sp_buf msg;
|
|
|
|
if (strcmp(text, "/cancel") == 0) {
|
|
memset(&tg_iv, 0, sizeof(tg_iv));
|
|
if (sp_buf_init(&msg) == 0) {
|
|
sp_buf_puts(&msg, sp_t("tg.interview.cancel"));
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
}
|
|
return;
|
|
}
|
|
if (text[0] == '/' && strcmp(text, "/skip") != 0) {
|
|
if (sp_buf_init(&msg) == 0) {
|
|
sp_buf_puts(&msg, sp_t("tg.interview.busy"));
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
}
|
|
return;
|
|
}
|
|
if (tg_iv.step < 16)
|
|
snprintf(tg_iv.answers[tg_iv.step], sizeof(tg_iv.answers[0]),
|
|
"%s", strcmp(text, "/skip") == 0 ? "" : text);
|
|
tg_iv.step++;
|
|
if (tg_iv.step < sp_interview_count())
|
|
(void)tg_interview_ask(token, chat_id, err);
|
|
else
|
|
tg_interview_end(token, chat_id, session_dir, err);
|
|
}
|
|
|
|
/*
|
|
* /model: the models this run was configured with, as buttons. Nothing is
|
|
* probed and nothing is written: the choice is one field of the transport, and
|
|
* a restart goes back to the config. /model <name> keeps the endpoint and
|
|
* takes another model from it.
|
|
*/
|
|
#define TG_MAX_MODELS 24
|
|
|
|
static char tg_model_id[64] = "main";
|
|
static char tg_model_name[256];
|
|
|
|
static void
|
|
tg_model_menu(const char *token, long chat_id, struct sp_config *conf,
|
|
struct sp_buf *err)
|
|
{
|
|
struct sp_buf msg, mark;
|
|
struct sp_provider p;
|
|
size_t i, n;
|
|
|
|
n = sp_provider_count(conf);
|
|
if (n == 0) {
|
|
(void)send_message(token, chat_id, sp_t("model.none"), err);
|
|
return;
|
|
}
|
|
if (sp_buf_init(&msg) != 0 || sp_buf_init(&mark) != 0) {
|
|
sp_buf_free(&msg);
|
|
sp_buf_free(&mark);
|
|
return;
|
|
}
|
|
sp_buf_puts(&msg, sp_t("model.choose"));
|
|
if (tg_model_name[0] != '\0')
|
|
sp_buf_printf(&msg, "\n%s", tg_model_name);
|
|
sp_buf_puts(&mark, "{\"inline_keyboard\":[\n");
|
|
for (i = 0; i < n && i < TG_MAX_MODELS; i++) {
|
|
if (sp_provider_at(conf, i, &p) != 0)
|
|
continue;
|
|
sp_buf_printf(&msg, "\n%s %s%s", p.id, p.model,
|
|
strcmp(p.id, tg_model_id) == 0 ? " *" : "");
|
|
if (p.key_env[0] != '\0' && getenv(p.key_env) == NULL)
|
|
sp_buf_printf(&msg, sp_t("model.no_key"), p.key_env);
|
|
if (i > 0)
|
|
sp_buf_puts(&mark, ",");
|
|
sp_buf_puts(&mark, "[{\"text\":\"");
|
|
(void)sp_json_escape(&mark, p.id);
|
|
sp_buf_puts(&mark, "\",\"callback_data\":\"model:");
|
|
(void)sp_json_escape(&mark, p.id);
|
|
sp_buf_puts(&mark, "\"}]");
|
|
}
|
|
sp_buf_puts(&mark, ",[{\"text\":\"");
|
|
(void)sp_json_escape(&mark, sp_t("model.probe"));
|
|
sp_buf_puts(&mark, "\",\"callback_data\":\"mprobe\"}]]}");
|
|
(void)send_message_markup(token, chat_id, msg.p, mark.p, err);
|
|
sp_buf_free(&msg);
|
|
sp_buf_free(&mark);
|
|
}
|
|
|
|
static void
|
|
tg_model_use(const char *token, long chat_id, struct sp_agent *ag,
|
|
struct sp_config *conf, const char *id, struct sp_buf *err)
|
|
{
|
|
struct sp_buf msg, perr;
|
|
struct sp_provider p;
|
|
size_t idx;
|
|
|
|
if (conf == NULL || ag == NULL ||
|
|
!sp_provider_find(conf, id, &idx)) {
|
|
if (sp_buf_init(&msg) == 0) {
|
|
sp_buf_printf(&msg, sp_t("model.unknown"), id);
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
}
|
|
return;
|
|
}
|
|
if (sp_buf_init(&perr) != 0)
|
|
return;
|
|
if (sp_provider_use(ag, conf, idx, &perr) != 0 ||
|
|
sp_provider_at(conf, idx, &p) != 0) {
|
|
if (sp_buf_init(&msg) == 0) {
|
|
sp_buf_printf(&msg, sp_t("model.failed"),
|
|
perr.p != NULL && perr.len > 0 ? perr.p :
|
|
sp_t("model.unknown"));
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
}
|
|
sp_buf_free(&perr);
|
|
return;
|
|
}
|
|
snprintf(tg_model_id, sizeof(tg_model_id), "%s", p.id);
|
|
snprintf(tg_model_name, sizeof(tg_model_name), "%s", p.model);
|
|
{
|
|
struct sp_buf serr;
|
|
int saved;
|
|
|
|
sp_buf_init(&serr);
|
|
saved = sp_provider_save_choice(conf, &p, &serr);
|
|
if (sp_buf_init(&msg) == 0) {
|
|
if (saved == 0)
|
|
sp_buf_printf(&msg, sp_t("model.saved"),
|
|
p.model, p.id);
|
|
else if (saved < 0)
|
|
sp_buf_printf(&msg, sp_t("model.save_failed"),
|
|
p.model, p.id, serr.p != NULL ?
|
|
serr.p : "?");
|
|
else
|
|
sp_buf_printf(&msg, sp_t("model.switched"),
|
|
p.model, p.id);
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
}
|
|
sp_buf_free(&serr);
|
|
}
|
|
sp_buf_free(&perr);
|
|
}
|
|
|
|
/* /model <name>: the same provider, another model it serves */
|
|
static void
|
|
tg_model_named(const char *token, long chat_id, struct sp_agent *ag,
|
|
struct sp_config *conf, const char *name, struct sp_buf *err)
|
|
{
|
|
struct sp_provider p;
|
|
struct sp_buf msg, perr;
|
|
size_t idx = 0;
|
|
|
|
if (conf == NULL || ag == NULL)
|
|
return;
|
|
/* the running provider, unless it vanished from the config */
|
|
if (!sp_provider_find(conf, tg_model_id, &idx) ||
|
|
sp_provider_at(conf, idx, &p) != 0) {
|
|
if (sp_provider_at(conf, 0, &p) != 0) {
|
|
(void)send_message(token, chat_id, sp_t("model.none"),
|
|
err);
|
|
return;
|
|
}
|
|
}
|
|
if (sp_buf_init(&perr) != 0)
|
|
return;
|
|
if (sp_provider_apply(ag, p.endpoint, name, p.key_env, &perr) != 0) {
|
|
if (sp_buf_init(&msg) == 0) {
|
|
sp_buf_printf(&msg, sp_t("model.failed"),
|
|
perr.p != NULL && perr.len > 0 ? perr.p :
|
|
sp_t("model.unknown"));
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
}
|
|
sp_buf_free(&perr);
|
|
return;
|
|
}
|
|
snprintf(tg_model_name, sizeof(tg_model_name), "%s", name);
|
|
{
|
|
struct sp_provider chosen;
|
|
struct sp_buf serr;
|
|
int saved;
|
|
|
|
memset(&chosen, 0, sizeof(chosen));
|
|
snprintf(chosen.id, sizeof(chosen.id), "%s", p.id);
|
|
snprintf(chosen.endpoint, sizeof(chosen.endpoint), "%s",
|
|
p.endpoint);
|
|
snprintf(chosen.model, sizeof(chosen.model), "%s", name);
|
|
snprintf(chosen.key_env, sizeof(chosen.key_env), "%s",
|
|
p.key_env);
|
|
sp_buf_init(&serr);
|
|
saved = sp_provider_save_choice(conf, &chosen, &serr);
|
|
if (sp_buf_init(&msg) == 0) {
|
|
if (saved == 0)
|
|
sp_buf_printf(&msg, sp_t("model.saved"), name,
|
|
p.id);
|
|
else if (saved < 0)
|
|
sp_buf_printf(&msg, sp_t("model.save_failed"),
|
|
name, p.id, serr.p != NULL ? serr.p : "?");
|
|
else
|
|
sp_buf_printf(&msg, sp_t("model.switched"), name,
|
|
p.id);
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
}
|
|
sp_buf_free(&serr);
|
|
}
|
|
sp_buf_free(&perr);
|
|
}
|
|
|
|
/*
|
|
* /model probe: ask every endpoint what it serves (/v1/models) and offer the
|
|
* answer as buttons. The buttons carry an index into this table, not a model
|
|
* name: a GGUF path does not fit in Telegram's 64 bytes of callback data, and
|
|
* the table dies with the process like the buttons do.
|
|
*/
|
|
#define TG_MAX_PICKS 64
|
|
|
|
struct tg_pick {
|
|
char provider[64];
|
|
char endpoint[512];
|
|
char model[256];
|
|
char key_env[64];
|
|
};
|
|
|
|
static struct tg_pick tg_picks[TG_MAX_PICKS];
|
|
static size_t tg_npicks;
|
|
|
|
static void
|
|
tg_model_pick_menu(const char *token, long chat_id, struct sp_config *conf,
|
|
struct sp_buf *err)
|
|
{
|
|
struct sp_buf msg, mark, ids, perr;
|
|
struct sp_provider p;
|
|
size_t i, n, total = 0;
|
|
|
|
tg_npicks = 0;
|
|
n = sp_provider_count(conf);
|
|
if (n == 0) {
|
|
(void)send_message(token, chat_id, sp_t("model.none"), err);
|
|
return;
|
|
}
|
|
if (sp_buf_init(&msg) == 0)
|
|
sp_buf_printf(&msg, sp_t("model.probe_start"), n);
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
if (sp_buf_init(&msg) != 0)
|
|
return;
|
|
if (sp_buf_init(&mark) != 0) {
|
|
sp_buf_free(&msg);
|
|
return;
|
|
}
|
|
if (sp_buf_init(&ids) != 0 || sp_buf_init(&perr) != 0) {
|
|
sp_buf_free(&msg);
|
|
sp_buf_free(&mark);
|
|
return;
|
|
}
|
|
sp_buf_puts(&mark, "{\"inline_keyboard\":[\n");
|
|
for (i = 0; i < n; i++) {
|
|
const char *line;
|
|
|
|
if (sp_provider_at(conf, i, &p) != 0)
|
|
continue;
|
|
sp_buf_clear(&ids);
|
|
sp_buf_clear(&perr);
|
|
if (sp_provider_served(&p, &ids, &perr) != 0) {
|
|
sp_buf_printf(&msg, "\n%s: %.120s", p.id,
|
|
perr.p != NULL ? perr.p : "?");
|
|
continue;
|
|
}
|
|
sp_buf_printf(&msg, "\n%s:", p.id);
|
|
for (line = strtok(ids.p, "\n"); line != NULL;
|
|
line = strtok(NULL, "\n")) {
|
|
char label[64];
|
|
|
|
if (tg_npicks >= TG_MAX_PICKS)
|
|
break;
|
|
snprintf(tg_picks[tg_npicks].provider, sizeof(
|
|
tg_picks[0].provider), "%s", p.id);
|
|
snprintf(tg_picks[tg_npicks].endpoint, sizeof(
|
|
tg_picks[0].endpoint), "%s", p.endpoint);
|
|
snprintf(tg_picks[tg_npicks].model, sizeof(
|
|
tg_picks[0].model), "%s", line);
|
|
snprintf(tg_picks[tg_npicks].key_env, sizeof(
|
|
tg_picks[0].key_env), "%s", p.key_env);
|
|
sp_buf_printf(&msg, " %s", line);
|
|
/* Telegram caps button text at 64 characters */
|
|
snprintf(label, sizeof(label), "%.20s: %.40s", p.id,
|
|
line);
|
|
if (total > 0)
|
|
sp_buf_puts(&mark, ",");
|
|
sp_buf_puts(&mark, "[{\"text\":\"");
|
|
(void)sp_json_escape(&mark, label);
|
|
sp_buf_printf(&mark, "\",\"callback_data\":\"mm:%zu\""
|
|
"}]", tg_npicks);
|
|
tg_npicks++;
|
|
total++;
|
|
}
|
|
}
|
|
sp_buf_puts(&mark, "]}");
|
|
sp_buf_free(&ids);
|
|
sp_buf_free(&perr);
|
|
if (total == 0)
|
|
sp_buf_puts(&msg, "\n");
|
|
if (total == 0)
|
|
sp_buf_puts(&msg, sp_t("model.probe_none"));
|
|
(void)send_message_markup(token, chat_id, msg.p, mark.p, err);
|
|
sp_buf_free(&mark);
|
|
sp_buf_free(&msg);
|
|
}
|
|
|
|
static void
|
|
tg_model_pick_use(const char *token, long chat_id, struct sp_agent *ag,
|
|
struct sp_config *conf, size_t idx, struct sp_buf *err)
|
|
{
|
|
struct sp_provider p;
|
|
struct sp_buf msg, perr, serr;
|
|
int saved;
|
|
|
|
if (idx >= tg_npicks || ag == NULL) {
|
|
(void)send_message(token, chat_id, sp_t("model.probe_stale"),
|
|
err);
|
|
return;
|
|
}
|
|
memset(&p, 0, sizeof(p));
|
|
snprintf(p.id, sizeof(p.id), "%s", tg_picks[idx].provider);
|
|
snprintf(p.endpoint, sizeof(p.endpoint), "%s",
|
|
tg_picks[idx].endpoint);
|
|
snprintf(p.model, sizeof(p.model), "%s", tg_picks[idx].model);
|
|
snprintf(p.key_env, sizeof(p.key_env), "%s", tg_picks[idx].key_env);
|
|
sp_buf_init(&perr);
|
|
if (sp_provider_apply(ag, p.endpoint, p.model, p.key_env, &perr) != 0) {
|
|
if (sp_buf_init(&msg) == 0) {
|
|
sp_buf_printf(&msg, sp_t("model.failed"),
|
|
perr.p != NULL ? perr.p : "?");
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
}
|
|
sp_buf_free(&perr);
|
|
return;
|
|
}
|
|
sp_buf_free(&perr);
|
|
snprintf(tg_model_id, sizeof(tg_model_id), "%s", p.id);
|
|
snprintf(tg_model_name, sizeof(tg_model_name), "%s", p.model);
|
|
sp_buf_init(&serr);
|
|
saved = sp_provider_save_choice(conf, &p, &serr);
|
|
if (sp_buf_init(&msg) == 0) {
|
|
if (saved == 0)
|
|
sp_buf_printf(&msg, sp_t("model.saved"), p.model, p.id);
|
|
else if (saved < 0)
|
|
sp_buf_printf(&msg, sp_t("model.save_failed"), p.model,
|
|
p.id, serr.p != NULL ? serr.p : "?");
|
|
else
|
|
sp_buf_printf(&msg, sp_t("model.switched"), p.model,
|
|
p.id);
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
}
|
|
sp_buf_free(&serr);
|
|
}
|
|
|
|
/*
|
|
* /connect: one provider per conversation, one question per message. The line
|
|
* is written to <config>.d/20-connect.conf before it is used, so a provider
|
|
* that could not be saved is not advertised as one this run has.
|
|
*/
|
|
enum tg_cc_step {
|
|
TG_CC_NAME = 0,
|
|
TG_CC_ENDPOINT,
|
|
TG_CC_MODEL,
|
|
TG_CC_KEY,
|
|
TG_CC_DONE
|
|
};
|
|
|
|
struct tg_connect {
|
|
int active;
|
|
long chat_id;
|
|
int step;
|
|
char id[64];
|
|
char endpoint[520];
|
|
char model[260];
|
|
char key_env[80];
|
|
};
|
|
|
|
static struct tg_connect tg_cc;
|
|
|
|
static void
|
|
tg_connect_ask(const char *token, long chat_id, struct sp_buf *err)
|
|
{
|
|
struct sp_buf msg;
|
|
|
|
if (sp_buf_init(&msg) != 0)
|
|
return;
|
|
switch (tg_cc.step) {
|
|
case TG_CC_ENDPOINT:
|
|
sp_buf_puts(&msg, sp_t("connect.endpoint"));
|
|
break;
|
|
case TG_CC_MODEL:
|
|
sp_buf_puts(&msg, sp_t("connect.model"));
|
|
break;
|
|
case TG_CC_KEY:
|
|
if (tg_cc.key_env[0] != '\0')
|
|
sp_buf_printf(&msg, sp_t("connect.key_named"),
|
|
tg_cc.key_env);
|
|
else
|
|
sp_buf_puts(&msg, sp_t("connect.key"));
|
|
break;
|
|
default:
|
|
sp_buf_puts(&msg, sp_t("connect.name"));
|
|
break;
|
|
}
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
}
|
|
|
|
static void
|
|
tg_connect_begin(const char *token, long chat_id, struct sp_buf *err)
|
|
{
|
|
if (sp_config_loaded_path() == NULL) {
|
|
/* --no-config: there is no file to write the provider to */
|
|
(void)send_message(token, chat_id, sp_t("connect.nodir"), err);
|
|
return;
|
|
}
|
|
memset(&tg_cc, 0, sizeof(tg_cc));
|
|
tg_cc.active = 1;
|
|
tg_cc.chat_id = chat_id;
|
|
tg_cc.step = TG_CC_NAME;
|
|
(void)send_message(token, chat_id, sp_t("connect.start"), err);
|
|
(void)tg_connect_ask(token, chat_id, err);
|
|
}
|
|
|
|
static void
|
|
tg_connect_end(const char *token, long chat_id, struct sp_agent *ag,
|
|
struct sp_config *conf, struct sp_buf *err)
|
|
{
|
|
char dir[720], line[1400];
|
|
struct sp_buf msg, cerr, mark;
|
|
int rc;
|
|
|
|
mark.p = NULL;
|
|
if (sp_provider_dir(dir, sizeof(dir)) != 0) {
|
|
(void)send_message(token, chat_id, sp_t("connect.nodir"), err);
|
|
memset(&tg_cc, 0, sizeof(tg_cc));
|
|
return;
|
|
}
|
|
if (sp_buf_init(&cerr) != 0)
|
|
return;
|
|
rc = sp_provider_add(conf, dir, tg_cc.id, tg_cc.endpoint, tg_cc.model,
|
|
tg_cc.key_env, &cerr);
|
|
if (rc != 0) {
|
|
if (sp_buf_init(&msg) == 0) {
|
|
sp_buf_printf(&msg, sp_t("connect.failed"),
|
|
cerr.p != NULL && cerr.len > 0 ? cerr.p :
|
|
sp_t("err.turn_failed"));
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
}
|
|
sp_buf_free(&cerr);
|
|
memset(&tg_cc, 0, sizeof(tg_cc));
|
|
return;
|
|
}
|
|
sp_buf_free(&cerr);
|
|
if (sp_buf_init(&msg) != 0)
|
|
goto out;
|
|
if (sp_provider_line(line, sizeof(line), tg_cc.id, tg_cc.endpoint,
|
|
tg_cc.model, tg_cc.key_env) != 0) {
|
|
sp_buf_free(&msg);
|
|
(void)send_message(token, chat_id, sp_t("connect.line_too_long"),
|
|
err);
|
|
memset(&tg_cc, 0, sizeof(tg_cc));
|
|
return;
|
|
}
|
|
sp_buf_printf(&msg, sp_t("connect.saved"), tg_cc.id, tg_cc.model,
|
|
tg_cc.endpoint);
|
|
if (sp_buf_init(&mark) != 0) {
|
|
sp_buf_free(&msg);
|
|
goto out;
|
|
}
|
|
sp_buf_puts(&mark, "{\"inline_keyboard\":[[{\"text\":\"");
|
|
(void)sp_json_escape(&mark, sp_t("connect.use"));
|
|
sp_buf_puts(&mark, "\",\"callback_data\":\"model:");
|
|
(void)sp_json_escape(&mark, tg_cc.id);
|
|
sp_buf_puts(&mark, "\"},{\"text\":\"");
|
|
(void)sp_json_escape(&mark, sp_t("connect.later"));
|
|
sp_buf_puts(&mark, "\",\"callback_data\":\"mlater\"}]]}");
|
|
(void)send_message_markup(token, chat_id, msg.p, mark.p, err);
|
|
sp_buf_free(&mark);
|
|
sp_buf_free(&msg);
|
|
/*
|
|
* The test turn can take half a minute on a slow endpoint. The save is
|
|
* already in the chat by then, so the operator sees what happened
|
|
* before the wait starts.
|
|
*/
|
|
{
|
|
struct sp_provider p;
|
|
struct sp_buf ans, terr;
|
|
|
|
memset(&p, 0, sizeof(p));
|
|
snprintf(p.id, sizeof(p.id), "%.63s", tg_cc.id);
|
|
snprintf(p.endpoint, sizeof(p.endpoint), "%.511s",
|
|
tg_cc.endpoint);
|
|
snprintf(p.model, sizeof(p.model), "%.255s", tg_cc.model);
|
|
snprintf(p.key_env, sizeof(p.key_env), "%.63s", tg_cc.key_env);
|
|
sp_buf_init(&ans);
|
|
sp_buf_init(&terr);
|
|
if (sp_buf_init(&msg) == 0) {
|
|
if (sp_provider_test(&p, &ans, &terr) == 0) {
|
|
char want[160];
|
|
char *nl;
|
|
|
|
snprintf(want, sizeof(want), "%.150s",
|
|
ans.p != NULL ? ans.p : "");
|
|
nl = strchr(want, '\n');
|
|
if (nl != NULL)
|
|
*nl = '\0';
|
|
sp_buf_printf(&msg, sp_t("connect.tested"),
|
|
want);
|
|
} else {
|
|
sp_buf_printf(&msg, sp_t("connect.test_failed"),
|
|
terr.p != NULL && terr.len > 0 ?
|
|
terr.p : "?");
|
|
}
|
|
(void)send_message(token, chat_id, msg.p, err);
|
|
sp_buf_free(&msg);
|
|
}
|
|
sp_buf_free(&ans);
|
|
sp_buf_free(&terr);
|
|
}
|
|
out:
|
|
(void)ag;
|
|
memset(&tg_cc, 0, sizeof(tg_cc));
|
|
}
|
|
|
|
static void
|
|
tg_connect_answer(const char *token, long chat_id, const char *text,
|
|
struct sp_agent *ag, struct sp_config *conf, struct sp_buf *err)
|
|
{
|
|
if (strcmp(text, "/cancel") == 0 || strcasecmp(text, "cancel") == 0) {
|
|
memset(&tg_cc, 0, sizeof(tg_cc));
|
|
(void)send_message(token, chat_id, sp_t("connect.cancel"), err);
|
|
return;
|
|
}
|
|
switch (tg_cc.step) {
|
|
case TG_CC_NAME:
|
|
if (!sp_provider_id_ok(text)) {
|
|
(void)send_message(token, chat_id,
|
|
sp_t("connect.name_bad"), err);
|
|
return;
|
|
}
|
|
snprintf(tg_cc.id, sizeof(tg_cc.id), "%s", text);
|
|
break;
|
|
case TG_CC_ENDPOINT:
|
|
if (strcmp(text, "ollama") == 0) {
|
|
snprintf(tg_cc.endpoint, sizeof(tg_cc.endpoint),
|
|
"http://127.0.0.1:11434/v1/chat/completions");
|
|
} else if (strcmp(text, "opencode") == 0) {
|
|
snprintf(tg_cc.endpoint, sizeof(tg_cc.endpoint),
|
|
"https://opencode.ai/zen/go/v1/chat/completions");
|
|
snprintf(tg_cc.key_env, sizeof(tg_cc.key_env),
|
|
"OPENCODE_GO_API_KEY");
|
|
} else if (!sp_provider_endpoint_ok(text)) {
|
|
(void)send_message(token, chat_id,
|
|
sp_t("connect.endpoint_bad"), err);
|
|
return;
|
|
} else {
|
|
snprintf(tg_cc.endpoint, sizeof(tg_cc.endpoint), "%s",
|
|
text);
|
|
}
|
|
break;
|
|
case TG_CC_MODEL:
|
|
if (!sp_provider_model_ok(text)) {
|
|
(void)send_message(token, chat_id,
|
|
sp_t("connect.model_bad"), err);
|
|
return;
|
|
}
|
|
snprintf(tg_cc.model, sizeof(tg_cc.model), "%s", text);
|
|
break;
|
|
case TG_CC_KEY:
|
|
if (strcmp(text, "-") == 0) {
|
|
tg_cc.key_env[0] = '\0';
|
|
} else if (strcmp(text, "/skip") == 0) {
|
|
/* keep the preset's variable, or none */
|
|
} else if (!sp_provider_key_ok(text)) {
|
|
(void)send_message(token, chat_id,
|
|
sp_t("connect.key_bad"), err);
|
|
return;
|
|
} else {
|
|
snprintf(tg_cc.key_env, sizeof(tg_cc.key_env), "%s",
|
|
text);
|
|
}
|
|
tg_cc.step = TG_CC_DONE;
|
|
tg_connect_end(token, chat_id, ag, conf, err);
|
|
return;
|
|
default:
|
|
break;
|
|
}
|
|
tg_cc.step++;
|
|
if (tg_cc.step >= TG_CC_DONE)
|
|
return;
|
|
(void)tg_connect_ask(token, chat_id, err);
|
|
}
|
|
|
|
/*
|
|
* An inline keyboard answer: ack:<id>:yes|no for an approval, model:<id> for a
|
|
* model, mlater for "not now". The button travels as a callback_query, not a
|
|
* message; the same allow list applies. The buttons are removed after the
|
|
* answer so the chat does not keep a stale choice.
|
|
*/
|
|
static int
|
|
tg_callback(const char *token, const char *allow, const mcp_json *cq,
|
|
struct sp_agent *ag, struct sp_config *conf)
|
|
{
|
|
const mcp_json *from, *msg;
|
|
const char *data, *cqid, *sep;
|
|
long from_id, chat = 0, mid = 0;
|
|
struct sp_buf sink;
|
|
int id, yes;
|
|
|
|
if (cq == NULL)
|
|
return 0;
|
|
data = mcp_arg_string(cq, "data");
|
|
cqid = mcp_arg_string(cq, "id");
|
|
from = mcp_arg(cq, "from");
|
|
msg = mcp_arg(cq, "message");
|
|
from_id = tg_id(from, "id");
|
|
if (msg != NULL) {
|
|
chat = tg_id(mcp_arg(msg, "chat"), "id");
|
|
mid = tg_id(msg, "message_id");
|
|
}
|
|
if (data == NULL || cqid == NULL || !allowed(allow, from_id))
|
|
return 0;
|
|
if (strncmp(data, "model:", 6) == 0) {
|
|
tg_answer_callback(token, cqid, sp_t("model.toast"));
|
|
if (mid != 0)
|
|
tg_clear_buttons(token, chat, mid);
|
|
/* during an approval only this process's poller runs: no agent */
|
|
if (ag != NULL && conf != NULL && chat != 0) {
|
|
if (sp_buf_init(&sink) == 0) {
|
|
tg_model_use(token, chat, ag, conf, data + 6,
|
|
&sink);
|
|
sp_buf_free(&sink);
|
|
}
|
|
}
|
|
return 1;
|
|
}
|
|
if (strcmp(data, "mprobe") == 0) {
|
|
tg_answer_callback(token, cqid, sp_t("model.toast"));
|
|
if (mid != 0)
|
|
tg_clear_buttons(token, chat, mid);
|
|
if (conf != NULL && chat != 0) {
|
|
struct sp_buf sink;
|
|
|
|
if (sp_buf_init(&sink) == 0) {
|
|
tg_model_pick_menu(token, chat, conf, &sink);
|
|
sp_buf_free(&sink);
|
|
}
|
|
}
|
|
return 1;
|
|
}
|
|
if (strncmp(data, "mm:", 3) == 0) {
|
|
tg_answer_callback(token, cqid, sp_t("model.toast"));
|
|
if (mid != 0)
|
|
tg_clear_buttons(token, chat, mid);
|
|
if (ag != NULL && conf != NULL && chat != 0) {
|
|
struct sp_buf sink;
|
|
|
|
if (sp_buf_init(&sink) == 0) {
|
|
tg_model_pick_use(token, chat, ag, conf,
|
|
(size_t)strtoul(data + 3, NULL, 10), &sink);
|
|
sp_buf_free(&sink);
|
|
}
|
|
}
|
|
return 1;
|
|
}
|
|
if (strcmp(data, "mlater") == 0) {
|
|
tg_answer_callback(token, cqid, sp_t("connect.later"));
|
|
if (mid != 0)
|
|
tg_clear_buttons(token, chat, mid);
|
|
return 1;
|
|
}
|
|
if (strncmp(data, "ack:", 4) != 0)
|
|
return 0;
|
|
sep = strrchr(data, ':');
|
|
if (sep == NULL)
|
|
return 0;
|
|
id = atoi(data + 4);
|
|
yes = strcmp(sep + 1, "yes") == 0;
|
|
if (id <= 0)
|
|
return 0;
|
|
if (sp_ack_answer(id, yes, "telegram") == 0) {
|
|
tg_answer_callback(token, cqid, yes ?
|
|
sp_td("ack.granted", "Approved.") :
|
|
sp_td("ack.refused", "Refused."));
|
|
if (chat != 0) {
|
|
if (mid != 0)
|
|
tg_clear_buttons(token, chat, mid);
|
|
(void)send_message(token, chat, yes ?
|
|
sp_td("ack.granted", "Approved.") :
|
|
sp_td("ack.refused", "Refused."), NULL);
|
|
}
|
|
} else {
|
|
tg_answer_callback(token, cqid,
|
|
sp_td("ack.gone", "There is no such request (any more)."));
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
/*
|
|
* "ok <id>", "ja <id>", "no <id>", "nein <id>": an answer to a pending
|
|
* approval - this process's or another one's. Returns 1 when the text was one.
|
|
*/
|
|
static int
|
|
tg_ack_reply(const char *token, long chat_id, const char *text)
|
|
{
|
|
const char *num;
|
|
int id, yes;
|
|
|
|
if (strncmp(text, "ok ", 3) != 0 && strncmp(text, "no ", 3) != 0 &&
|
|
strncmp(text, "ja ", 3) != 0 && strncmp(text, "nein ", 5) != 0)
|
|
return 0;
|
|
num = strchr(text, ' ');
|
|
id = num != NULL ? atoi(num + 1) : 0;
|
|
if (id <= 0)
|
|
return 0;
|
|
yes = text[0] == 'o' || text[0] == 'j';
|
|
if (sp_ack_answer(id, yes, "telegram") == 0)
|
|
(void)send_message(token, chat_id, yes ?
|
|
sp_td("ack.granted", "Approved.") :
|
|
sp_td("ack.refused", "Refused."), NULL);
|
|
else
|
|
(void)send_message(token, chat_id,
|
|
sp_td("ack.gone", "There is no such request (any more)."),
|
|
NULL);
|
|
return 1;
|
|
}
|
|
|
|
/*
|
|
* Approval for a tool call of the gateway's own turn, asked in the chat that
|
|
* started the turn. The gateway is the only reader of that chat, so while it
|
|
* waits it keeps reading: an answer resolves the request (also one from
|
|
* 'splinter --ack' on the machine), anything else is told to wait. A timeout
|
|
* is a no.
|
|
*/
|
|
static int
|
|
tg_approve(void *ctx, const char *name, int auth, const char *args)
|
|
{
|
|
const char *ttl_s = getenv("SPLINTER_ACK_TTL");
|
|
int ttl = ttl_s != NULL && *ttl_s != '\0' ? atoi(ttl_s) : 120;
|
|
char shown[320], who[64] = "";
|
|
struct sp_buf msg, url, reply, err, mark;
|
|
time_t end;
|
|
int id, yes;
|
|
|
|
(void)ctx;
|
|
if (ttl <= 0)
|
|
ttl = 120;
|
|
id = sp_ack_request(name, args, auth == SP_AUTH_MUTATE ? "mutate" :
|
|
"destructive", ttl);
|
|
if (id < 0)
|
|
return 0;
|
|
snprintf(shown, sizeof(shown), "%s", args != NULL ? args : "");
|
|
if (strlen(shown) >= 300)
|
|
memcpy(shown + 296, "...", 4);
|
|
if (sp_buf_init(&msg) != 0 || sp_buf_init(&url) != 0 ||
|
|
sp_buf_init(&reply) != 0 || sp_buf_init(&err) != 0 ||
|
|
sp_buf_init(&mark) != 0)
|
|
return 0;
|
|
sp_buf_printf(&msg, sp_td("ack.request", "Approval %d: %s %s"), id,
|
|
name, shown);
|
|
sp_buf_puts(&msg, "\n");
|
|
sp_buf_printf(&msg, sp_td("ack.how", "Answer: ok %d / no %d"), id, id);
|
|
sp_buf_puts(&mark, "{\"inline_keyboard\":[[{\"text\":\"");
|
|
sp_json_escape(&mark, sp_t("ack.yes"));
|
|
sp_buf_printf(&mark, "\",\"callback_data\":\"ack:%d:yes\"},"
|
|
"{\"text\":\"", id);
|
|
sp_json_escape(&mark, sp_t("ack.no"));
|
|
sp_buf_printf(&mark, "\",\"callback_data\":\"ack:%d:no\"}]]}", id);
|
|
(void)send_message_markup(tg_cur.token, tg_cur.chat_id, msg.p, mark.p,
|
|
NULL);
|
|
|
|
end = time(NULL) + ttl;
|
|
while (!tg_stop && time(NULL) < end && !sp_ack_answered(id)) {
|
|
mcp_json *v;
|
|
const mcp_json *result, *update;
|
|
size_t i;
|
|
|
|
sp_buf_clear(&url);
|
|
sp_buf_printf(&url, "%s/bot%s/getUpdates?timeout=5&offset=%ld",
|
|
api_base(), tg_cur.token, tg_offset);
|
|
sp_buf_clear(&reply);
|
|
sp_buf_clear(&err);
|
|
if (tg_curl(url.p, NULL, &reply, &err) != 0) {
|
|
sleep(1);
|
|
continue;
|
|
}
|
|
v = mcp_parse(reply.p);
|
|
result = v != NULL ? mcp_arg(v, "result") : NULL;
|
|
for (i = 0; result != NULL &&
|
|
(update = mcp_array_at(result, i)) != NULL; i++) {
|
|
const mcp_json *m, *cq;
|
|
long uid = tg_id(update, "update_id");
|
|
const char *text;
|
|
long chat, from;
|
|
|
|
if (uid < tg_offset)
|
|
continue;
|
|
tg_offset = uid + 1;
|
|
cq = mcp_arg(update, "callback_query");
|
|
if (cq != NULL) {
|
|
(void)tg_callback(tg_cur.token, tg_cur.allow, cq, NULL, NULL);
|
|
continue;
|
|
}
|
|
m = mcp_arg(update, "message");
|
|
if (m == NULL)
|
|
continue;
|
|
text = mcp_arg_string(m, "text");
|
|
chat = tg_id(mcp_arg(m, "chat"), "id");
|
|
from = tg_id(mcp_arg(m, "from"), "id");
|
|
if (text == NULL || chat == 0 || !allowed(tg_cur.allow, from))
|
|
continue;
|
|
if (tg_ack_reply(tg_cur.token, chat, text))
|
|
continue;
|
|
sp_buf_clear(&msg);
|
|
sp_buf_printf(&msg, sp_td("ack.waiting",
|
|
"Still waiting for an approval: ok %d / no %d"), id, id);
|
|
(void)send_message(tg_cur.token, chat, msg.p, NULL);
|
|
}
|
|
if (v != NULL)
|
|
mcp_json_free(v);
|
|
}
|
|
/* reads the answer if there is one, and closes the request either way */
|
|
yes = sp_ack_wait(id, 1, who, sizeof(who));
|
|
sp_buf_free(&msg);
|
|
sp_buf_free(&url);
|
|
sp_buf_free(&reply);
|
|
sp_buf_free(&err);
|
|
sp_buf_free(&mark);
|
|
return yes;
|
|
}
|
|
|
|
int
|
|
sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token,
|
|
const char *allow, struct sp_config *conf, struct sp_buf *err)
|
|
{
|
|
struct sp_buf url, reply, answer, aerr;
|
|
struct sp_agent_config gcfg;
|
|
const struct sp_agent_config *orig = ag->cfg;
|
|
|
|
if (sp_buf_init(&url) != 0 || sp_buf_init(&reply) != 0 ||
|
|
sp_buf_init(&answer) != 0 || sp_buf_init(&aerr) != 0)
|
|
return -1;
|
|
|
|
/*
|
|
* Without a token every poll is a connection reset: a daemon that loops on
|
|
* that fills a log and burns a core while doing nothing. Refuse to start and
|
|
* say why, instead of pretending to listen.
|
|
*/
|
|
if (token == NULL || *token == '\0') {
|
|
fprintf(stderr, "splinter: no telegram token "
|
|
"(SPLINTER_TELEGRAM_TOKEN or ~/.splinter/telegram.token) - the gateway "
|
|
"needs one to listen\n");
|
|
return -1;
|
|
}
|
|
|
|
/*
|
|
* Approval in the chat the request came from. Without this the gateway
|
|
* either denied every mutating call (no approval stream) or, with ack
|
|
* channels, waited for an answer that only it could have read.
|
|
*/
|
|
if (orig != NULL && !orig->autonomous && orig->approve == NULL) {
|
|
gcfg = *orig;
|
|
gcfg.approve = tg_approve;
|
|
gcfg.approve_ctx = &tg_cur;
|
|
gcfg.approve_is_channel = 1;
|
|
ag->cfg = &gcfg;
|
|
}
|
|
|
|
(void)signal(SIGINT, on_signal);
|
|
(void)signal(SIGTERM, on_signal);
|
|
tg_set_commands(token, host,
|
|
ag->sess != NULL ? ag->sess->dir : NULL);
|
|
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/bot%s/getUpdates?timeout=%d&offset=%ld",
|
|
api_base(), token, TG_POLL_S, tg_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, *cq;
|
|
const char *text;
|
|
pthread_t tty;
|
|
volatile int tstop = 0;
|
|
struct typing ty;
|
|
int typing_on = 0;
|
|
long chat_id, from, update_id;
|
|
|
|
update_id = tg_id(update, "update_id");
|
|
/* tg_approve may have read past this batch already */
|
|
if (update_id < tg_offset)
|
|
continue;
|
|
tg_offset = update_id + 1;
|
|
cq = mcp_arg(update, "callback_query");
|
|
if (cq != NULL) {
|
|
(void)tg_callback(token, allow, cq, ag, conf);
|
|
continue;
|
|
}
|
|
msg = mcp_arg(update, "message");
|
|
if (msg == NULL)
|
|
continue;
|
|
text = mcp_arg_string(msg, "text");
|
|
chat_id = tg_id(mcp_arg(msg, "chat"), "id");
|
|
from = tg_id(mcp_arg(msg, "from"), "id");
|
|
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);
|
|
/*
|
|
* A slash command is the harness talking, not the
|
|
* model: /goal and /recap come from plugins and
|
|
* answer without a request.
|
|
*/
|
|
/*
|
|
* An answer to a pending approval. The gateway is the one
|
|
* reader of this chat, so it resolves here instead of letting a
|
|
* second poller fight it for updates.
|
|
*/
|
|
if (tg_iv.active && tg_iv.chat_id == chat_id) {
|
|
tg_interview_answer(token, chat_id, text,
|
|
ag->sess != NULL ? ag->sess->dir : NULL,
|
|
err);
|
|
sp_buf_clear(err);
|
|
continue;
|
|
}
|
|
if (tg_cc.active && tg_cc.chat_id == chat_id) {
|
|
tg_connect_answer(token, chat_id, text, ag,
|
|
conf, err);
|
|
sp_buf_clear(err);
|
|
continue;
|
|
}
|
|
if (tg_ack_reply(token, chat_id, text))
|
|
continue;
|
|
if (strcmp(text, "/interview") == 0) {
|
|
tg_interview_begin(token, chat_id, err);
|
|
sp_buf_clear(err);
|
|
continue;
|
|
}
|
|
if (strcmp(text, "/connect") == 0) {
|
|
tg_connect_begin(token, chat_id, err);
|
|
sp_buf_clear(err);
|
|
continue;
|
|
}
|
|
if (strcmp(text, "/model") == 0) {
|
|
tg_model_menu(token, chat_id, conf, err);
|
|
sp_buf_clear(err);
|
|
continue;
|
|
}
|
|
if (strncmp(text, "/model ", 7) == 0) {
|
|
const char *arg = text + 7;
|
|
size_t idx;
|
|
|
|
while (*arg == ' ')
|
|
arg++;
|
|
if (strcmp(arg, "probe") == 0) {
|
|
tg_model_pick_menu(token, chat_id,
|
|
conf, err);
|
|
sp_buf_clear(err);
|
|
continue;
|
|
}
|
|
if (*arg != '\0' &&
|
|
sp_provider_find(conf, arg, &idx))
|
|
tg_model_use(token, chat_id, ag,
|
|
conf, arg, err);
|
|
else if (*arg != '\0')
|
|
tg_model_named(token, chat_id, ag,
|
|
conf, arg, err);
|
|
sp_buf_clear(err);
|
|
continue;
|
|
}
|
|
if (strcmp(text, "/start") == 0 ||
|
|
strcmp(text, "/help") == 0) {
|
|
struct sp_buf help;
|
|
|
|
if (sp_buf_init(&help) == 0) {
|
|
tg_help_text(host, ag->sess != NULL ?
|
|
ag->sess->dir : NULL, &help);
|
|
(void)send_message(token, chat_id,
|
|
help.p != NULL ? help.p :
|
|
sp_t("tg.help"), err);
|
|
sp_buf_free(&help);
|
|
}
|
|
sp_buf_clear(err);
|
|
continue;
|
|
}
|
|
if (text[0] == '/' && text[1] != '\0') {
|
|
char name[32], *rest;
|
|
size_t n = strcspn(text + 1, " ");
|
|
int crc;
|
|
|
|
snprintf(name, sizeof(name), "%.*s",
|
|
(int)n, text + 1);
|
|
rest = (char *)text + 1 + n;
|
|
while (*rest == ' ')
|
|
rest++;
|
|
crc = host != NULL ?
|
|
sp_host_command(host, name, rest,
|
|
&answer) : -1;
|
|
if (crc == 0) {
|
|
(void)send_markdown(token, chat_id,
|
|
answer.p != NULL ? answer.p :
|
|
sp_t("reply.empty"), NULL, err);
|
|
sp_buf_clear(err);
|
|
continue;
|
|
}
|
|
/*
|
|
* Not a plugin command: a program in
|
|
* commands/ gets the rest of the line. In the
|
|
* Telegram chat its output is the reply; in the
|
|
* TUI it becomes the model's context.
|
|
*/
|
|
{
|
|
char cdir[700];
|
|
struct sp_buf cerr;
|
|
|
|
sp_buf_init(&cerr);
|
|
if (sp_cmdscript_dir(ag->sess != NULL ?
|
|
ag->sess->dir : NULL, cdir,
|
|
sizeof(cdir)) == 0 &&
|
|
sp_cmdscript_exists(cdir, name)) {
|
|
if (sp_slash_script(cdir, name,
|
|
rest, &answer, &cerr) == 0) {
|
|
(void)send_markdown(token,
|
|
chat_id,
|
|
answer.p != NULL ?
|
|
answer.p : sp_t("reply.empty"),
|
|
NULL, err);
|
|
} else {
|
|
(void)send_message(token,
|
|
chat_id,
|
|
cerr.p != NULL ?
|
|
cerr.p : sp_t("err.turn_failed"),
|
|
err);
|
|
}
|
|
sp_buf_clear(err);
|
|
sp_buf_free(&cerr);
|
|
continue;
|
|
}
|
|
sp_buf_free(&cerr);
|
|
}
|
|
/*
|
|
* Neither a plugin command nor a program:
|
|
* do not hand a typo to the model. Say what
|
|
* exists, as the TUI does.
|
|
*/
|
|
{
|
|
struct sp_buf u;
|
|
|
|
if (sp_buf_init(&u) == 0) {
|
|
sp_buf_printf(&u,
|
|
sp_t("cmd.unknown"), name);
|
|
sp_buf_puts(&u, "\n ");
|
|
tg_help_text(host,
|
|
ag->sess != NULL ?
|
|
ag->sess->dir : NULL, &u);
|
|
(void)send_message(token, chat_id,
|
|
u.p != NULL ? u.p : sp_t("reply.empty"), err);
|
|
sp_buf_clear(err);
|
|
sp_buf_free(&u);
|
|
}
|
|
}
|
|
continue;
|
|
}
|
|
/* "typing" while the model thinks, not while a
|
|
* plugin answers a slash command */
|
|
snprintf(ty.token, sizeof(ty.token), "%s", token);
|
|
ty.chat_id = chat_id;
|
|
ty.stop = &tstop;
|
|
if (pthread_create(&tty, NULL, typing_thread,
|
|
&ty) == 0)
|
|
typing_on = 1;
|
|
|
|
tg_cur.token = token;
|
|
tg_cur.chat_id = chat_id;
|
|
tg_cur.allow = allow;
|
|
if (sp_agent_run(ag, text, &answer, &aerr) != 0) {
|
|
(void)send_message(token, chat_id,
|
|
aerr.p != NULL ? aerr.p :
|
|
"turn failed", err);
|
|
if (typing_on) {
|
|
tstop = 1;
|
|
(void)pthread_join(tty, NULL);
|
|
}
|
|
sp_buf_clear(err);
|
|
continue;
|
|
}
|
|
if (typing_on) {
|
|
tstop = 1;
|
|
(void)pthread_join(tty, NULL);
|
|
}
|
|
(void)send_markdown(token, chat_id,
|
|
answer.p != NULL ? answer.p : sp_t("reply.empty"),
|
|
NULL, err);
|
|
sp_buf_clear(err);
|
|
/* the agent already recorded both sides */
|
|
}
|
|
}
|
|
mcp_json_free(v);
|
|
}
|
|
sp_buf_free(&url);
|
|
sp_buf_free(&reply);
|
|
sp_buf_free(&answer);
|
|
sp_buf_free(&aerr);
|
|
ag->cfg = orig;
|
|
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;
|
|
}
|