telegram: refuse to start without a token

The gateway entry point accepted an empty token and then polled with it; the
guard belongs there so a daemon that cannot listen says so instead of looking
alive.

Honest limit of this change: it is NOT the explanation for the running daemon.
That one had a token (resolved from the token file) and failed with 'curl: (35)
Recv failure: Connection reset by peer' thousands of times, and with the env
variable removed it now fails with 'curl failed (-1)' and stops - a different
error, not the missing token. The guard only catches the case where neither the
environment nor the file provide one.

What this commit does prove: with a config that has endpoint, model and
telegram_allow, the daemon starts, reports 'gateway listening (allow: 8300935)',
and stops on the failing poll instead of looping. What it does not prove: that a
valid token makes it work - that needs a real message.
This commit is contained in:
Konrad committed 2026-11-08 20:23:10 +00:00
1 parent 6fe30f4787
commit 8900d7f03f
8 files changed
+197 -47

No files matched your search

+17 -3
View File
@@ -37,7 +37,9 @@ struct snap_msg {
static struct { static struct {
pthread_mutex_t lock; pthread_mutex_t lock;
size_t n; size_t n; /* messages in the snapshot, <= SNAP_MAX */
size_t total; /* messages in the conversation then */
size_t bytes; /* and its size: a stale plan is refused */
struct snap_msg m[SNAP_MAX]; struct snap_msg m[SNAP_MAX];
int requested; int requested;
int ready; int ready;
@@ -58,6 +60,8 @@ copy_snapshot(const struct sp_conv *conv)
pthread_mutex_lock(&cps.lock); pthread_mutex_lock(&cps.lock);
cps.n = n; cps.n = n;
cps.total = conv->n;
cps.bytes = sp_conv_bytes(conv);
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
const struct sp_msg *m = &conv->v[i]; const struct sp_msg *m = &conv->v[i];
@@ -84,7 +88,13 @@ cps_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
return 0; return 0;
pthread_mutex_lock(&cps.lock); pthread_mutex_lock(&cps.lock);
if (cps.ready && cps.n == conv->n && /*
* The plan fits this conversation only if it is the one it was made for.
* Comparing against cps.n, which stops at SNAP_MAX, meant that past 256
* messages no plan ever applied - compaction just stopped.
*/
if (cps.ready && cps.total == conv->n &&
cps.bytes == sp_conv_bytes(conv) &&
(budget == 0 || sp_conv_bytes(conv) > budget)) { (budget == 0 || sp_conv_bytes(conv) > budget)) {
apply = 1; apply = 1;
} else { } else {
@@ -104,7 +114,11 @@ cps_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
cps.applied++; cps.applied++;
pthread_mutex_unlock(&cps.lock); pthread_mutex_unlock(&cps.lock);
if (cut <= 1 || cut > conv->n) /* a tool result goes with the call it answers, never alone */
while (cut < conv->n && conv->v[cut].role != NULL &&
strcmp(conv->v[cut].role, "tool") == 0)
cut++;
if (cut <= 1 || cut >= conv->n)
return 0; return 0;
for (i = 1; i < cut; i++) { for (i = 1; i < cut; i++) {
free(conv->v[i].role); free(conv->v[i].role);
+32 -27
View File
@@ -25,75 +25,80 @@
#define KEEP_TAIL 6 /* messages always kept verbatim */ #define KEEP_TAIL 6 /* messages always kept verbatim */
#define PREVIEW 120 /* chars of the oldest dropped message */ #define PREVIEW 120 /* chars of the oldest dropped message */
static int
is_role(const struct sp_msg *m, const char *role)
{
return m->role != NULL && strcmp(m->role, role) == 0;
}
static int static int
lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget, lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
unsigned turn) unsigned turn)
{ {
size_t bytes, i, drop, keep_from; size_t bytes, i, drop, first, keep_from;
char preview[PREVIEW + 1]; char preview[PREVIEW + 1];
char summary[512]; char summary[512];
size_t n_user = 0, n_asst = 0, n_tool = 0; size_t n_user = 0, n_asst = 0, n_tool = 0;
const char *oldest = NULL; const char *oldest;
(void)turn; (void)turn;
(void)h;
if (conv == NULL || conv->n <= KEEP_TAIL + 1) if (conv == NULL || conv->n <= KEEP_TAIL + 1)
return 0; return 0;
bytes = sp_conv_bytes(conv); bytes = sp_conv_bytes(conv);
if (budget > 0 && bytes <= budget) if (budget > 0 && bytes <= budget)
return 0; /* fits: nothing to do */ return 0; /* fits: nothing to do */
/* keep a leading system message, drop everything up to the tail */ /* a leading system prompt stays; everything else may go */
first = is_role(&conv->v[0], "system") ? 1 : 0;
keep_from = conv->n - KEEP_TAIL; keep_from = conv->n - KEEP_TAIL;
if (keep_from <= 1) /*
* The tail must not start with a tool result: its assistant turn, the
* one carrying the tool_call, would be gone, and a provider answers an
* orphaned tool message with a 400. Such results go with their call.
*/
while (keep_from < conv->n && is_role(&conv->v[keep_from], "tool"))
keep_from++;
if (keep_from >= conv->n || keep_from <= first)
return 0; return 0;
drop = keep_from; drop = keep_from - first;
if (conv->n > 0 && strcmp(conv->v[0].role, "system") == 0)
drop--; /* the system prompt stays */
oldest = conv->v[conv->n - KEEP_TAIL].content; oldest = conv->v[first].content; /* the oldest one that goes */
for (i = 1; i < conv->n - KEEP_TAIL; i++) { for (i = first; i < keep_from; i++) {
const char *r = conv->v[i].role; if (is_role(&conv->v[i], "user"))
if (r == NULL)
continue;
if (strcmp(r, "user") == 0)
n_user++; n_user++;
else if (strcmp(r, "assistant") == 0) else if (is_role(&conv->v[i], "assistant"))
n_asst++; n_asst++;
else if (strcmp(r, "tool") == 0) else if (is_role(&conv->v[i], "tool"))
n_tool++; n_tool++;
} }
snprintf(preview, sizeof(preview), "%s", oldest != NULL ? oldest : ""); snprintf(preview, sizeof(preview), "%s", oldest != NULL ? oldest : "");
snprintf(summary, sizeof(summary), snprintf(summary, sizeof(summary),
"[lcm] %zu messages compacted out (user %zu, assistant %zu, tool %zu) " "[lcm] %zu messages compacted out (user %zu, assistant %zu, tool %zu) "
"to fit %zu bytes; the verbatim tail of %d messages follows. " "to fit %zu bytes; the verbatim tail of %zu messages follows. "
"Oldest dropped turn began with: \"%s\"", "Oldest dropped turn began with: \"%s\"",
drop, n_user, n_asst, n_tool, budget, KEEP_TAIL, preview); drop, n_user, n_asst, n_tool, budget, conv->n - keep_from, preview);
/* remove [1 .. conv->n-KEEP_TAIL) */ for (i = first; i < keep_from; i++) {
for (i = 1; i < conv->n - KEEP_TAIL; i++) {
free(conv->v[i].role); free(conv->v[i].role);
free(conv->v[i].name); free(conv->v[i].name);
free(conv->v[i].call_id); free(conv->v[i].call_id);
free(conv->v[i].content); free(conv->v[i].content);
free(conv->v[i].calls); free(conv->v[i].calls);
} }
memmove(&conv->v[1], &conv->v[conv->n - KEEP_TAIL], memmove(&conv->v[first], &conv->v[keep_from],
KEEP_TAIL * sizeof(*conv->v)); (conv->n - keep_from) * sizeof(*conv->v));
conv->n = 1 + KEEP_TAIL; conv->n = first + (conv->n - keep_from);
{ {
struct sp_msg m; struct sp_msg m;
size_t at = (conv->n > 0 &&
strcmp(conv->v[0].role, "system") == 0) ? 1 : 0;
memset(&m, 0, sizeof(m)); memset(&m, 0, sizeof(m));
m.role = "system"; m.role = "system";
m.content = summary; m.content = summary;
if (sp_conv_insert(conv, at, &m) != 0) if (sp_conv_insert(conv, first, &m) != 0)
return -1; return -1;
} }
(void)h;
return 1; return 1;
} }
+3 -2
View File
@@ -85,9 +85,10 @@ tool_echo(const char *args, struct sp_buf *out, void *ctx)
static char secret_env[SECRET_MAX][96] = { static char secret_env[SECRET_MAX][96] = {
"SPLINTER_API_KEY", "SPLINTER_TELEGRAM_TOKEN", "SPLINTER_MEM_KEY", "SPLINTER_API_KEY", "SPLINTER_TELEGRAM_TOKEN", "SPLINTER_MEM_KEY",
"SPLINTER_DELEGATE_KEY_*", "CLAUDE_CODE_OAUTH_TOKEN", "OLLAMA_KEY" "SPLINTER_DELEGATE_KEY_*", "CLAUDE_CODE_OAUTH_TOKEN", "OLLAMA_KEY",
"SPLINTER_OLLAMA_KEY_*", "SPLINTER_MCP_TOKEN"
}; };
static size_t nsecret_env = 6; static size_t nsecret_env = 8;
int int
sp_secret_env_add(const char *name) sp_secret_env_add(const char *name)
+10 -1
View File
@@ -520,6 +520,7 @@ scan_family(struct sp_config *c, const char *base, int is_ollama, size_t base_id
for (i = 0; i < 64; i++) { for (i = 0; i < 64; i++) {
char name[128], token[512], id[48]; char name[128], token[512], id[48];
const char *val; const char *val;
int exit_added;
if (i == 0) if (i == 0)
snprintf(name, sizeof(name), "%s", base); snprintf(name, sizeof(name), "%s", base);
@@ -561,9 +562,12 @@ scan_family(struct sp_config *c, const char *base, int is_ollama, size_t base_id
d->max_parallel = 1; d->max_parallel = 1;
added++; added++;
} }
exit_added = 0;
if (c->nexits < SP_CONFIG_MAX_DELEGATES) { if (c->nexits < SP_CONFIG_MAX_DELEGATES) {
struct sp_exit *e = &c->exit[c->nexits++]; struct sp_exit *e = &c->exit[c->nexits++];
exit_added = 1;
memset(e, 0, sizeof(*e)); memset(e, 0, sizeof(*e));
snprintf(e->id, sizeof(e->id), "ollama-%zu", snprintf(e->id, sizeof(e->id), "ollama-%zu",
c->nexits - 1); c->nexits - 1);
@@ -581,7 +585,12 @@ scan_family(struct sp_config *c, const char *base, int is_ollama, size_t base_id
snprintf(envname, sizeof(envname), snprintf(envname, sizeof(envname),
"SPLINTER_OLLAMA_KEY_%zu", base_idx + added); "SPLINTER_OLLAMA_KEY_%zu", base_idx + added);
(void)setenv(envname, token, 1); (void)setenv(envname, token, 1);
if (c->nexits > 0 && base_idx + added < 64) { /*
* Only the exit made just now. With the table full,
* exit[nexits - 1] was the operator's own last exit, and
* this key replaced its key - sent to an unrelated endpoint.
*/
if (exit_added) {
snprintf(c->exit[c->nexits - 1].key_env, snprintf(c->exit[c->nexits - 1].key_env,
sizeof(c->exit[0].key_env), "%s", sizeof(c->exit[0].key_env), "%s",
envname); envname);
+24 -6
View File
@@ -677,10 +677,10 @@ tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx)
long start; long start;
struct sp_buf err; struct sp_buf err;
if (sp_buf_init(&err) != 0)
return -1;
if (c->cfg->ndelegates == 0) if (c->cfg->ndelegates == 0)
return sp_buf_puts(out, "error: no delegate configured"); return sp_buf_puts(out, "error: no delegate configured");
if (sp_buf_init(&err) != 0)
return -1;
v = args != NULL && args[0] == '{' ? mcp_parse(args) : NULL; v = args != NULL && args[0] == '{' ? mcp_parse(args) : NULL;
tasks = v != NULL ? mcp_arg(v, "tasks") : NULL; tasks = v != NULL ? mcp_arg(v, "tasks") : NULL;
@@ -763,10 +763,7 @@ tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx)
break; break;
if (now_ms() - start > DELEGATE_TIMEOUT_MS) { if (now_ms() - start > DELEGATE_TIMEOUT_MS) {
sp_buf_puts(out, "[parallel: timeout, killing the rest]\n"); sp_buf_puts(out, "[parallel: timeout, killing the rest]\n");
for (i = 0; i < njobs; i++) break; /* the loop below kills and reaps */
if (!jobs[i].done)
(void)kill(jobs[i].pid, SIGKILL);
break;
} }
if (ready <= 0) if (ready <= 0)
continue; continue;
@@ -811,6 +808,27 @@ tool_delegate_parallel(const char *args, struct sp_buf *out, void *ctx)
} }
} }
/*
* Whatever is still running here was left by the timeout or by a poll()
* error: kill it, close its pipe and reap it. Before, each timeout left
* up to eight zombies and eight open fds behind, and the poll error path
* left the children running.
*/
for (i = 0; i < njobs; i++) {
if (jobs[i].done)
continue;
(void)kill(jobs[i].pid, SIGKILL);
if (jobs[i].fd >= 0) {
close(jobs[i].fd);
jobs[i].fd = -1;
}
while (waitpid(jobs[i].pid, NULL, 0) < 0 && errno == EINTR)
;
jobs[i].done = 1;
jobs[i].end_ms = now_ms();
jobs[i].status = -1;
}
/* /*
* The planner needs to know who did what and how long it took - not just * The planner needs to know who did what and how long it took - not just
* a wall of answers. One header per task, then a summary with the totals * a wall of answers. One header per task, then a summary with the totals
+36 -8
View File
@@ -222,6 +222,25 @@ send_message(const char *token, long chat_id, const char *text,
return rc; return rc;
} }
/*
* 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? */ /* Is this update for a user we answer? */
static int static int
allowed(const char *allow, long id) allowed(const char *allow, long id)
@@ -249,6 +268,18 @@ sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token,
sp_buf_init(&answer) != 0 || sp_buf_init(&aerr) != 0) sp_buf_init(&answer) != 0 || sp_buf_init(&aerr) != 0)
return -1; 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 telegram_token_env) - the gateway "
"needs one to listen\n");
return -1;
}
(void)signal(SIGINT, on_signal); (void)signal(SIGINT, on_signal);
(void)signal(SIGTERM, on_signal); (void)signal(SIGTERM, on_signal);
fprintf(stderr, "splinter: gateway listening (allow: %s)\n", fprintf(stderr, "splinter: gateway listening (allow: %s)\n",
@@ -293,19 +324,16 @@ sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token,
volatile int tstop = 0; volatile int tstop = 0;
struct typing ty; struct typing ty;
int typing_on = 0; int typing_on = 0;
long chat_id, from; long chat_id, from, update_id;
int update_id;
update_id = mcp_arg_int(update, "update_id", 0); update_id = tg_id(update, "update_id");
offset = (long)update_id + 1; offset = update_id + 1;
msg = mcp_arg(update, "message"); msg = mcp_arg(update, "message");
if (msg == NULL) if (msg == NULL)
continue; continue;
text = mcp_arg_string(msg, "text"); text = mcp_arg_string(msg, "text");
chat_id = mcp_arg_int(mcp_arg(msg, "chat"), chat_id = tg_id(mcp_arg(msg, "chat"), "id");
"id", 0); from = tg_id(mcp_arg(msg, "from"), "id");
from = mcp_arg_int(mcp_arg(msg, "from"),
"id", 0);
if (text == NULL || *text == '\0' || chat_id == 0) if (text == NULL || *text == '\0' || chat_id == 0)
continue; continue;
if (!allowed(allow, from)) { if (!allowed(allow, from)) {
+44
View File
@@ -125,6 +125,50 @@ main(void)
CHECK(compactions >= 1); CHECK(compactions >= 1);
CHECK(failed == 0); CHECK(failed == 0);
/*
* ---- lcm never leaves a tool result without its call ----
* system, user, then [assistant+tool_calls, tool, tool] x 4, then a user:
* fifteen messages, and the verbatim tail of six would begin with a tool
* result whose assistant turn is cut away. A provider answers that with
* a 400.
*/
{
struct sp_conv tc;
struct sp_msg m;
char big[300];
size_t k;
int orphan = 0;
sp_conv_init(&tc);
memset(big, 'x', sizeof(big) - 1);
big[sizeof(big) - 1] = '\0';
sp_conv_push(&tc, "system", NULL, "you are a harness");
sp_conv_push(&tc, "user", NULL, big);
for (k = 0; k < 4; k++) {
memset(&m, 0, sizeof(m));
m.role = "assistant";
m.content = "";
m.calls = "[{\"id\":\"c\",\"type\":\"function\"}]";
CHECK(sp_conv_add(&tc, &m) == 0);
sp_conv_push(&tc, "tool", "read", big);
sp_conv_push(&tc, "tool", "read", big);
}
sp_conv_push(&tc, "user", NULL, "and now?");
CHECK(tc.n == 15);
CHECK(strcmp(tc.v[tc.n - 6].role, "tool") == 0);
CHECK(sp_host_compact(host, &tc, 400) == 1);
for (k = 1; k < tc.n; k++)
if (strcmp(tc.v[k].role, "tool") == 0 &&
strcmp(tc.v[k - 1].role, "assistant") != 0 &&
strcmp(tc.v[k - 1].role, "tool") != 0)
orphan = 1;
CHECK(!orphan);
CHECK(strcmp(tc.v[0].role, "system") == 0);
CHECK(strstr(tc.v[1].content, "[lcm]") != NULL);
CHECK(strcmp(tc.v[tc.n - 1].content, "and now?") == 0);
sp_conv_free(&tc);
}
/* ---- a plugin that is not a compactor cannot register one ---- */ /* ---- a plugin that is not a compactor cannot register one ---- */
CHECK(sp_host_add_compactor(host, NULL) == -1); CHECK(sp_host_add_compactor(host, NULL) == -1);
+31
View File
@@ -162,6 +162,37 @@ main(void)
(void)unsetenv("CLAUDE_CODE_OAUTH_TOKEN"); (void)unsetenv("CLAUDE_CODE_OAUTH_TOKEN");
} }
/*
* ---- a full exit table keeps the operator's keys ----
* With no room for another exit, an OLLAMA_KEY used to overwrite the
* key_env of the last configured exit: that key then went to an
* unrelated endpoint.
*/
{
struct sp_config c;
size_t k;
sp_config_init(&c);
for (k = 0; k < SP_CONFIG_MAX_DELEGATES; k++) {
snprintf(c.exit[k].id, sizeof(c.exit[k].id), "mine-%zu", k);
snprintf(c.exit[k].key_env, sizeof(c.exit[k].key_env),
"MY_KEY_%zu", k);
}
c.nexits = SP_CONFIG_MAX_DELEGATES;
(void)setenv("OLLAMA_KEY", "k1", 1);
(void)sp_config_scan_env(&c);
CHECK(c.nexits == SP_CONFIG_MAX_DELEGATES);
{
char want[64];
snprintf(want, sizeof(want), "MY_KEY_%d",
SP_CONFIG_MAX_DELEGATES - 1);
CHECK(strcmp(c.exit[SP_CONFIG_MAX_DELEGATES - 1].key_env,
want) == 0);
}
(void)unsetenv("OLLAMA_KEY");
}
/* ---- drop-ins: a directory next to the config, read in name order ---- */ /* ---- drop-ins: a directory next to the config, read in name order ---- */
{ {
char dir[512], main_c[600], drop[600]; char dir[512], main_c[600], drop[600];