review fixes, third round: the gateway asks in its chat, approvals say what

Telegram gateway
- A tool call of the gateway's own turn that needed consent was either denied
  (a daemon has no approval stream) or, with ack channels set, waited for an
  "ok <id>" that only the blocked gateway could have read. It now asks in the
  chat the turn came from, keeps reading while it waits, resolves answers
  (also other processes' and 'splinter --ack'), ignores strangers and tells
  everything else to wait. The update offset is shared, so nothing is handled
  twice. New cfg flag approve_is_channel: such an approve is asked directly.
- send_message wrote its error through err, and half the callers pass NULL: the
  first refused message (too long, bad UTF-8) crashed the gateway. It also
  missed '"ok": true' by substring; the reply is parsed now.
- tests/test_gateway.sh drives the real daemon against a fake Bot API and a
  fake model (tests/fake_telegram.py), with "ok" and with "no". In make check;
  .gitignore no longer hides tests/test_*.sh.

Approvals
- A channel was told "Zustimmung <id>" and nothing else: a phone said yes to a
  number. The message now names the tool and its arguments (cut at 300 bytes)
  and how to answer, and goes to the channel as "$1", never parsed by sh.

Smaller
- ring: an exit that already streamed text is not retried on the next one
  (the operator saw a second answer after half of the first); the header now
  says what moves the ring - limits and providers that are down.
- cli: the program's stderr went over the curses screen and the error quoted
  stdout. stderr goes to a file and into the error; temp paths are quoted;
  the BODY_CAP no-op is gone. (That is the "kaputt" make check used to print.)
- memory: memory_key_env became an env var curl never reads, so no request had
  a key. It is "Authorization: Token <key>" now, on curl's stdin. Tested.
- docs/CONFIG.md: the real default path, and the seven keys it did not know
  (telegram_allow, memory_url, memory_key_env, skills_dir, env_delegates,
  exit, delegate) with the line formats, checked against the parser.
- The no-token message named a config key that does not exist.

Left as it is, on purpose: 'read' stays unrestricted (decision); the fsync per
session line stays (durability over latency).

make check: 26 test binaries and the gateway script, green, also under
ASan/UBSan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
lotherkandClaude Opus 5.5 committed 2026-11-09 06:13:09 +00:00
1 parent 489c5da26a
commit 25a616a87f
15 files changed
+641 -88

No files matched your search

+71 -3
View File
@@ -31,6 +31,7 @@
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <sys/wait.h>
#include "splinter.h"
#include "ack.h"
@@ -130,6 +131,26 @@ request_expires(const char *path)
return exp;
}
/* sh -c '<cmd>' sh '<arg>': the command is parsed, the argument is not */
static int
run_with_arg(const char *cmd, const char *arg)
{
pid_t child;
int status;
child = fork();
if (child < 0)
return -1;
if (child == 0) {
execl("/bin/sh", "sh", "-c", cmd, "sh", arg, (char *)NULL);
_exit(127);
}
while (waitpid(child, &status, 0) < 0)
if (errno != EINTR)
return -1;
return status;
}
/*
* Write the request under a fresh random id. O_EXCL, so two requests never share
* a file, and 0600, because the arguments may be what is being protected.
@@ -184,27 +205,65 @@ sp_ack_request(const char *tool, const char *args, const char *why, int ttl)
* as one argument. A channel that fails is not fatal - another one may reach a
* human - but the failure is named.
*/
/* one "key=" line of a request file, without the newline */
static void
request_field(int id, const char *key, char *buf, size_t len)
{
char path[700], line[1024];
size_t kl = strlen(key);
FILE *f;
buf[0] = '\0';
if (ack_id_path(path, sizeof(path), id, "") != 0 ||
(f = fopen(path, "r")) == NULL)
return;
while (fgets(line, sizeof(line), f) != NULL)
if (strncmp(line, key, kl) == 0 && line[kl] == '=') {
line[strcspn(line, "\r\n")] = '\0';
snprintf(buf, len, "%s", line + kl + 1);
break;
}
fclose(f);
}
int
sp_ack_notify(int id, struct sp_buf *log)
{
const char *chans = getenv("SPLINTER_ACK_CHANNELS");
char list[512], *save = NULL, *tok;
char tool[64], args[400], msg[600];
int fired = 0;
if (chans == NULL || *chans == '\0')
return 0;
/*
* The message says what is being approved. It used to be "Zustimmung
* <id>" alone: a parent on a phone said yes to a number. Arguments are
* cut at 300 bytes - enough to see the command, not a whole file.
*/
request_field(id, "tool", tool, sizeof(tool));
request_field(id, "args", args, sizeof(args));
if (strlen(args) > 300)
memcpy(args + 297, "...", 4);
snprintf(msg, sizeof(msg), "Zustimmung %d: %s %s\n"
"Antwort: ok %d / no %d", id, tool[0] != '\0' ? tool : "?", args,
id, id);
snprintf(list, sizeof(list), "%s", chans);
for (tok = strtok_r(list, ",", &save); tok != NULL;
tok = strtok_r(NULL, ",", &save)) {
char cmd[1400];
char cmd[600];
int rc;
while (*tok == ' ')
tok++;
if (*tok == '\0')
continue;
snprintf(cmd, sizeof(cmd), "%s 'Zustimmung %d'", tok, id);
rc = system(cmd);
/*
* The channel command is the operator's; the message carries the
* model's arguments and therefore goes in as "$1", never parsed.
*/
snprintf(cmd, sizeof(cmd), "%s \"$1\"", tok);
rc = run_with_arg(cmd, msg);
if (rc == 0)
fired++;
else if (log != NULL)
@@ -306,6 +365,15 @@ sp_ack_answer(int id, int yes, const char *who)
return rc == 0 ? 0 : -1;
}
int
sp_ack_answered(int id)
{
char path[700];
return ack_id_path(path, sizeof(path), id, ".answer") == 0 &&
access(path, F_OK) == 0;
}
int
sp_ack_list(struct sp_buf *out)
{
+2
View File
@@ -18,5 +18,7 @@ int sp_ack_notify(int id, struct sp_buf *log);
int sp_ack_wait(int id, int ttl, char *who, size_t who_len);
int sp_ack_answer(int id, int yes, const char *who);
int sp_ack_list(struct sp_buf *out);
/* 1 when an answer for 'id' is waiting, without consuming it */
int sp_ack_answered(int id);
#endif /* SPLINTER_ACK_H */
+3
View File
@@ -149,6 +149,9 @@ ask_operator(struct sp_agent *a, const struct sp_tool *t, const char *args)
char line[64];
int verdict;
if (a->cfg->approve != NULL && a->cfg->approve_is_channel)
return a->cfg->approve(a->cfg->approve_ctx, t->name, (int)t->auth,
args);
verdict = ack_approval(a, t, args);
if (verdict >= 0)
return verdict;
+28 -45
View File
@@ -31,6 +31,7 @@
#include "mcp.h"
#include "config.h"
#include "memory.h"
#include "curl.h"
static const struct sp_config *mem_cfg;
@@ -57,56 +58,38 @@ sp_memory_user(void)
return name;
}
/* One POST, body from a buffer, answer captured. */
/*
* One POST, body from a buffer, answer captured.
*
* memory_key_env used to be put into the child's environment as
* SPLINTER_MEM_KEY, which curl never reads: no request carried a key, and a
* mem0 that wanted one refused every call. It is now a header, on curl's stdin
* (sp_curl_start), in mem0's "Authorization: Token <key>" form.
*/
static int
mem_post(const char *url, const char *body, struct sp_buf *out,
struct sp_buf *err)
{
int fds[2];
pid_t child;
const char *args[] = { "-sS", "-m", "30", "-X", "POST", "-H",
"Content-Type: application/json", "--data-binary",
body, NULL };
const char *hdrs[2] = { NULL, NULL };
char auth[600];
pid_t child;
int fd;
if (pipe(fds) != 0) {
sp_buf_printf(err, "memory: pipe: %s", strerror(errno));
return -1;
}
child = fork();
if (child < 0) {
sp_buf_printf(err, "memory: fork: %s", strerror(errno));
close(fds[0]);
close(fds[1]);
return -1;
}
if (child == 0) {
char *argv[12];
int n = 0;
if (mem_cfg != NULL && mem_cfg->memory_key_env[0] != '\0') {
const char *key = getenv(mem_cfg->memory_key_env);
(void)dup2(fds[1], STDOUT_FILENO);
close(fds[0]);
close(fds[1]);
argv[n++] = "curl";
argv[n++] = "-sS";
argv[n++] = "-m";
argv[n++] = "30";
argv[n++] = "-X";
argv[n++] = "POST";
argv[n++] = "-H";
argv[n++] = "Content-Type: application/json";
argv[n++] = "--data-binary";
argv[n++] = (char *)body;
if (mem_cfg != NULL && mem_cfg->memory_key_env[0] != '\0') {
const char *key = getenv(mem_cfg->memory_key_env);
if (key != NULL) {
/* the key travels in the environment, never argv */
setenv("SPLINTER_MEM_KEY", key, 1);
}
if (key != NULL && *key != '\0') {
snprintf(auth, sizeof(auth), "Authorization: Token %s", key);
hdrs[0] = auth;
}
argv[n++] = (char *)url;
argv[n] = NULL;
execvp("curl", argv);
_exit(127);
}
close(fds[1]);
fd = sp_curl_start(args, url, hdrs, 1, &child, err);
memset(auth, 0, sizeof(auth));
if (fd < 0)
return -1;
{
struct pollfd pfd;
char chunk[4096];
@@ -114,20 +97,20 @@ mem_post(const char *url, const char *body, struct sp_buf *out,
for (;;) {
ssize_t got;
pfd.fd = fds[0];
pfd.fd = fd;
pfd.events = POLLIN;
if (poll(&pfd, 1, 35000) <= 0) {
(void)kill(child, SIGKILL);
break;
}
got = read(fds[0], chunk, sizeof(chunk));
got = read(fd, chunk, sizeof(chunk));
if (got <= 0)
break;
if (sp_buf_add(out, chunk, (size_t)got) != 0)
break;
}
}
close(fds[0]);
close(fd);
{
int st = 0;
+180 -25
View File
@@ -171,17 +171,38 @@ tg_curl(const char *url, const char *post_body, struct sp_buf *out,
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;
}
static int
send_message(const char *token, long chat_id, const char *text,
struct sp_buf *err)
{
struct sp_buf url, body, reply;
struct sp_buf url, body, reply, sink;
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)
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);
do {
size_t take = len - off;
@@ -219,7 +240,7 @@ send_message(const char *token, long chat_id, const char *text,
rc = -1;
break;
}
if (strstr(reply.p != NULL ? reply.p : "", "\"ok\":true") == NULL) {
if (!tg_reply_ok(reply.p)) {
sp_buf_printf(err, "telegram: sendMessage refused: %.200s",
reply.p != NULL ? reply.p : "");
rc = -1;
@@ -229,6 +250,7 @@ send_message(const char *token, long chat_id, const char *text,
} while (off < len);
sp_buf_free(&url);
sp_buf_free(&body);
sp_buf_free(&sink);
sp_buf_free(&reply);
return rc;
}
@@ -268,12 +290,141 @@ allowed(const char *allow, long id)
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;
/*
* "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 ? "Zustimmung erteilt." :
"Abgelehnt.", NULL);
else
(void)send_message(token, chat_id,
"Diese Anfrage gibt es nicht (mehr).", 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;
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)
return 0;
sp_buf_printf(&msg, "Zustimmung %d: %s %s\nAntwort: ok %d / no %d",
id, name, shown, id, id);
(void)send_message(tg_cur.token, tg_cur.chat_id, msg.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 = mcp_arg(update, "message");
long uid = tg_id(update, "update_id");
const char *text;
long chat, from;
if (uid < tg_offset)
continue;
tg_offset = uid + 1;
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, "Ich warte noch auf eine Zustimmung: "
"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);
return yes;
}
int
sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token,
const char *allow, struct sp_buf *err)
{
long offset = 0;
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)
@@ -286,11 +437,24 @@ sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token,
*/
if (token == NULL || *token == '\0') {
fprintf(stderr, "splinter: no telegram token "
"(SPLINTER_TELEGRAM_TOKEN or telegram_token_env) - the gateway "
"(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);
fprintf(stderr, "splinter: gateway listening (allow: %s)\n",
@@ -303,7 +467,7 @@ sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token,
sp_buf_clear(&url);
sp_buf_printf(&url, "%s/bot%s/getUpdates?timeout=%d&offset=%ld",
api_base(), token, TG_POLL_S, offset);
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",
@@ -338,7 +502,10 @@ sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token,
long chat_id, from, update_id;
update_id = tg_id(update, "update_id");
offset = update_id + 1;
/* tg_approve may have read past this batch already */
if (update_id < tg_offset)
continue;
tg_offset = update_id + 1;
msg = mcp_arg(update, "message");
if (msg == NULL)
continue;
@@ -364,24 +531,8 @@ sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token,
* reader of this chat, so it resolves here instead of letting a
* second poller fight it for updates.
*/
if (strncmp(text, "ok ", 3) == 0 || strncmp(text, "no ", 3) == 0 ||
strncmp(text, "ja ", 3) == 0 || strncmp(text, "nein ", 5) == 0) {
const char *num = strchr(text, ' ');
int id = num != NULL ? atoi(num + 1) : 0;
if (id > 0) {
int yes = text[0] == 'o' || text[0] == 'j';
if (sp_ack_answer(id, yes, "telegram") == 0)
(void)send_message(token, chat_id,
yes ? "Zustimmung erteilt." :
"Abgelehnt.", NULL);
else
(void)send_message(token, chat_id,
"Diese Anfrage gibt es nicht (mehr).", NULL);
continue;
}
}
if (tg_ack_reply(token, chat_id, text))
continue;
if (text[0] == '/' && text[1] != '\0') {
char name[32], *rest;
size_t n = strcspn(text + 1, " ");
@@ -435,6 +586,9 @@ sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token,
&ty) == 0)
typing_on = 1;
tg_cur.token = token;
tg_cur.chat_id = chat_id;
tg_cur.allow = allow;
if (sp_agent_run(ag, prompt_used != NULL ?
prompt_used : text, &answer, &aerr) != 0) {
(void)send_message(token, chat_id,
@@ -463,6 +617,7 @@ sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token,
sp_buf_free(&reply);
sp_buf_free(&answer);
sp_buf_free(&aerr);
ag->cfg = orig;
fprintf(stderr, "splinter: gateway stopped\n");
return 0;
}