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:
1 parent
489c5da26a
commit
25a616a87f
15 files changed
+641
-88
No files matched your search
@@ -11,3 +11,4 @@ tests/test_agent
|
||||
plugins/*/*.so
|
||||
tests/test_*
|
||||
!tests/test_*.c
|
||||
!tests/test_*.sh
|
||||
@@ -200,6 +200,7 @@ check: $(LIB) $(BIN) $(PLUGIN) $(TESTS)
|
||||
@set -e; python3 tools/check_i18n.py; python3 tools/gen_www.py --check; \
|
||||
export LD_LIBRARY_PATH=.; \
|
||||
for t in $(TESTS); do echo "== $$t"; ./$$t; done; \
|
||||
echo "== tests/test_gateway.sh"; sh tests/test_gateway.sh; \
|
||||
echo "all tests passed"
|
||||
|
||||
# The installed binary finds its own library through an rpath relative to itself
|
||||
|
||||
+33
-1
@@ -3,9 +3,13 @@
|
||||
Splinter reads one file, so that `splinter` alone is enough to start working.
|
||||
|
||||
```
|
||||
$XDG_CONFIG_HOME/splinter/config (or ~/.config/splinter/config)
|
||||
~/.splinter/splinter.conf
|
||||
```
|
||||
|
||||
next to the sessions. If that file does not exist, an older install's
|
||||
`$XDG_CONFIG_HOME/splinter/config` (or `~/.config/splinter/config`) is read
|
||||
instead.
|
||||
|
||||
`SPLINTER_CONFIG=/path` overrides the location, `--config PATH` does the same
|
||||
for one run, `--no-config` ignores the file entirely, and `--init-config`
|
||||
writes a commented example.
|
||||
@@ -43,6 +47,34 @@ lies about what it does.
|
||||
| `max_bytes` | conversation budget in bytes, `0` = no limit |
|
||||
| `session_dir` | where session logs go (default `~/.splinter`) |
|
||||
| `system_prompt` | sent once at the start of a conversation |
|
||||
| `telegram_allow` | user ids the gateway answers, comma-separated; empty means nobody |
|
||||
| `memory_url` | base URL of a mem0 server (`memory_search`, `memory_add`) |
|
||||
| `memory_key_env` | env var with the mem0 key, sent as `Authorization: Token <key>` |
|
||||
| `skills_dir` | a directory of skills, one line each |
|
||||
| `env_delegates` | `1` turns `CLAUDE_CODE_OAUTH_TOKEN(_N)` into delegates (default off) |
|
||||
| `exit` | one way to reach a model for the exit ring, see below |
|
||||
| `delegate` | another model the `delegate` tool can hand work to, see below |
|
||||
|
||||
Secrets never go into the file: every `*key_env` names a variable, and the
|
||||
variable holds the key. Those variables are hidden from the `run` tool's shell.
|
||||
|
||||
## Exits and delegates
|
||||
|
||||
Both are one line each, `|`-separated, every field but the first named:
|
||||
|
||||
```
|
||||
exit = groq | Groq free tier | endpoint=https://api.groq.com/openai/v1/chat/completions | model=llama-3.3-70b | key_env=GROQ_KEY
|
||||
|
||||
delegate = coder | C99, POSIX, kennt den Quellbaum | endpoint=http://kontron:8080/v1/chat/completions | model=qwen | tags=code,review | prio=5 | max_parallel=2
|
||||
delegate = far | the same, on another machine | host=buildbox | endpoint=... | model=...
|
||||
delegate = claude-cli | Claude Code | kind=cli | cmd=claude -p | tags=plan
|
||||
```
|
||||
|
||||
`exit` fields: `endpoint`, `model`, `key_env`; the second field is the label.
|
||||
`delegate` fields: `endpoint`, `model`, `key_env`, `tags`, `prio`,
|
||||
`max_parallel`, `kind` (`openai` or `cli`), `cmd` (for `cli`), and `host` - an
|
||||
ssh target: the child splinter runs there, with that machine's keys. An unnamed
|
||||
field is the description the selection reads.
|
||||
|
||||
## Example: local model
|
||||
|
||||
|
||||
@@ -204,6 +204,13 @@ struct sp_agent_config {
|
||||
int (*approve)(void *ctx, const char *name, int auth,
|
||||
const char *args);
|
||||
void *approve_ctx;
|
||||
/*
|
||||
* Nonzero: 'approve' is itself the channel (the Telegram gateway asks in
|
||||
* its own chat) and is asked directly. Otherwise the ack mechanism goes
|
||||
* first when SPLINTER_ACK_CHANNELS is set - which in the gateway meant
|
||||
* waiting for an answer that only the blocked gateway could read.
|
||||
*/
|
||||
int approve_is_channel;
|
||||
|
||||
/*
|
||||
* Steering: while a turn runs, the operator may type. The UI cannot
|
||||
|
||||
+43
-7
@@ -34,7 +34,6 @@
|
||||
#include "i18n.h"
|
||||
|
||||
#define OUT_CAP (4u << 20)
|
||||
#define BODY_CAP (1u << 20)
|
||||
|
||||
struct cli_cfg {
|
||||
char cmd[512];
|
||||
@@ -71,13 +70,26 @@ render(const struct sp_conv *conv, int full, struct sp_buf *out)
|
||||
}
|
||||
}
|
||||
|
||||
/* 's' as one single-quoted shell word */
|
||||
static int
|
||||
sh_word(struct sp_buf *b, const char *s)
|
||||
{
|
||||
if (sp_buf_puts(b, "'") != 0)
|
||||
return -1;
|
||||
for (; *s != '\0'; s++)
|
||||
if (*s == '\'' ? sp_buf_puts(b, "'\\''") != 0 :
|
||||
sp_buf_add(b, s, 1) != 0)
|
||||
return -1;
|
||||
return sp_buf_puts(b, "'");
|
||||
}
|
||||
|
||||
static int
|
||||
cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
struct cli_cfg *c = ctx;
|
||||
struct sp_buf body, cmd, raw;
|
||||
char path[512];
|
||||
char path[512], errpath[540] = "", errtext[512];
|
||||
const char *tmpdir = getenv("TMPDIR");
|
||||
int fd, status;
|
||||
ssize_t w;
|
||||
@@ -110,8 +122,20 @@ cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
goto fail;
|
||||
}
|
||||
|
||||
/* the program reads the prompt on stdin; timeout guards a hang */
|
||||
sp_buf_printf(&cmd, "timeout %s %s < %s", c->timeout, c->cmd, path);
|
||||
/*
|
||||
* The program reads the prompt on stdin; timeout guards a hang. Its
|
||||
* stderr goes to a file next to the prompt: on the terminal it landed in
|
||||
* the middle of the curses screen, and the error message below promised
|
||||
* "the program's own stderr" while it quoted stdout. The paths are quoted;
|
||||
* TMPDIR is the operator's, but a space in it still broke the command.
|
||||
*/
|
||||
snprintf(errpath, sizeof(errpath), "%s.err", path);
|
||||
sp_buf_printf(&cmd, "timeout %s %s < ", c->timeout, c->cmd);
|
||||
if (sh_word(&cmd, path) != 0 || sp_buf_puts(&cmd, " 2> ") != 0 ||
|
||||
sh_word(&cmd, errpath) != 0) {
|
||||
unlink(path);
|
||||
goto fail;
|
||||
}
|
||||
p = popen(cmd.p, "r");
|
||||
if (p == NULL) {
|
||||
sp_buf_printf(err, "cli: popen: %s", strerror(errno));
|
||||
@@ -138,6 +162,18 @@ cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
}
|
||||
status = pclose(p);
|
||||
unlink(path);
|
||||
errtext[0] = '\0';
|
||||
{
|
||||
FILE *ef = fopen(errpath, "r");
|
||||
size_t en = 0;
|
||||
|
||||
if (ef != NULL) {
|
||||
en = fread(errtext, 1, sizeof(errtext) - 1, ef);
|
||||
fclose(ef);
|
||||
}
|
||||
errtext[en] = '\0';
|
||||
(void)unlink(errpath);
|
||||
}
|
||||
|
||||
if (status < 0) {
|
||||
sp_buf_printf(err, "cli: %s", strerror(errno));
|
||||
@@ -151,7 +187,7 @@ cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
|
||||
sp_buf_printf(err, sp_td("cli.failed", "cli: '%s' failed (exit %d): %.400s"), c->cmd,
|
||||
WIFEXITED(status) ? WEXITSTATUS(status) : -1,
|
||||
raw.p != NULL ? raw.p : "");
|
||||
errtext[0] != '\0' ? errtext : raw.p != NULL ? raw.p : "");
|
||||
goto fail;
|
||||
}
|
||||
if (raw.len == 0) {
|
||||
@@ -162,14 +198,14 @@ cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
out->content = strdup(raw.p);
|
||||
if (out->content == NULL)
|
||||
goto fail;
|
||||
if (body.len > BODY_CAP)
|
||||
(void)0; /* capped above; kept explicit */
|
||||
sp_buf_free(&body);
|
||||
sp_buf_free(&cmd);
|
||||
sp_buf_free(&raw);
|
||||
return 0;
|
||||
|
||||
fail:
|
||||
if (errpath[0] != '\0')
|
||||
(void)unlink(errpath);
|
||||
sp_buf_free(&body);
|
||||
sp_buf_free(&cmd);
|
||||
sp_buf_free(&raw);
|
||||
|
||||
+38
-7
@@ -11,10 +11,15 @@
|
||||
* exit = groq | Groq free tier | endpoint=... | model=... | key_env=GROQ_KEY
|
||||
* exit = local | kontron, lokal | endpoint=... | model=...
|
||||
*
|
||||
* Only a rate limit moves the ring. A syntax error or a bad key stops the turn
|
||||
* Only pressure moves the ring: a rate limit, an exhausted quota, or a provider
|
||||
* that is down (500/502/503/504). A syntax error or a bad key stops the turn
|
||||
* where it is - pretending every failure is "try the next one" would hide real
|
||||
* breakage behind a random provider. Each step is reported, so the log says which
|
||||
* exit served the turn.
|
||||
*
|
||||
* And once an exit has streamed text to the screen, its failure is the turn's
|
||||
* failure: asking the next exit would show the operator a second answer after
|
||||
* half of the first one.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -37,7 +42,7 @@ struct ring {
|
||||
|
||||
static struct ring ring;
|
||||
|
||||
/* A rate limit is the only thing worth another exit. */
|
||||
/* Pressure - a limit or a provider that is down - is worth another exit. */
|
||||
static int
|
||||
is_pressure(int rc, long status, const struct sp_buf *err)
|
||||
{
|
||||
@@ -142,6 +147,24 @@ ring_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* passes the stream through and remembers whether anything was shown */
|
||||
struct seen {
|
||||
sp_stream_cb cb;
|
||||
void *ctx;
|
||||
int shown;
|
||||
};
|
||||
|
||||
static void
|
||||
seen_cb(void *ctx, int kind, const char *text)
|
||||
{
|
||||
struct seen *s = ctx;
|
||||
|
||||
if (text != NULL && *text != '\0')
|
||||
s->shown = 1;
|
||||
if (s->cb != NULL)
|
||||
s->cb(s->ctx, kind, text);
|
||||
}
|
||||
|
||||
static int
|
||||
ring_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
struct sp_buf *err, sp_stream_cb cb, void *cbctx)
|
||||
@@ -149,6 +172,7 @@ ring_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
struct ring *r = ctx;
|
||||
size_t i;
|
||||
char line[128];
|
||||
struct seen seen;
|
||||
|
||||
if (build() != 0)
|
||||
return -1;
|
||||
@@ -160,8 +184,11 @@ ring_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
if (sp_buf_init(&e) != 0)
|
||||
return -1;
|
||||
sp_reply_free(out);
|
||||
rc = r->tr[i].send_stream(r->tr[i].ctx, conv, out, &e, cb,
|
||||
cbctx);
|
||||
seen.cb = cb;
|
||||
seen.ctx = cbctx;
|
||||
seen.shown = 0;
|
||||
rc = r->tr[i].send_stream(r->tr[i].ctx, conv, out, &e, seen_cb,
|
||||
&seen);
|
||||
status = out->status;
|
||||
if (rc == 0) {
|
||||
r->last = (int)i;
|
||||
@@ -172,12 +199,16 @@ ring_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
sp_buf_free(&e);
|
||||
return 0;
|
||||
}
|
||||
if (!is_pressure(rc, status, &e)) {
|
||||
if (err != NULL)
|
||||
if (!is_pressure(rc, status, &e) || seen.shown) {
|
||||
if (err != NULL) {
|
||||
(void)sp_buf_puts(err, e.p != NULL ? e.p :
|
||||
"ring: exit failed");
|
||||
if (seen.shown && is_pressure(rc, status, &e))
|
||||
(void)sp_buf_puts(err, " (after part of "
|
||||
"the answer was shown; not retried)");
|
||||
}
|
||||
sp_buf_free(&e);
|
||||
return rc;
|
||||
return rc != 0 ? rc : -1;
|
||||
}
|
||||
snprintf(line, sizeof(line), "ring: %s busy, next exit",
|
||||
r->cfg->exit[i].label);
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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 */
|
||||
@@ -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
@@ -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
@@ -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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# fake Telegram Bot API + fake OpenAI streaming endpoint for tests/test_gateway.sh.
|
||||
# argv: port, file the model asks to write, log of sent messages, answer word.
|
||||
# The first update asks for work; the model answers with a write tool call;
|
||||
# when the gateway asks for approval, three updates follow: a question (must be
|
||||
# told to wait), an answer from a stranger (must be ignored) and the real one.
|
||||
import http.server, json, re, sys, threading, time
|
||||
LOCK = threading.Lock()
|
||||
updates = [{"update_id": 1, "message": {"text": "schreib die datei",
|
||||
"chat": {"id": 42}, "from": {"id": 7}}}]
|
||||
next_uid = [2]
|
||||
sent = []
|
||||
TARGET = sys.argv[2]
|
||||
ANSWER = sys.argv[4] if len(sys.argv) > 4 else "ok"
|
||||
def add_update(text, frm=7):
|
||||
with LOCK:
|
||||
updates.append({"update_id": next_uid[0], "message": {"text": text,
|
||||
"chat": {"id": 42}, "from": {"id": frm}}})
|
||||
next_uid[0] += 1
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def log_message(self, *a): pass
|
||||
def reply(self, obj, ctype="application/json"):
|
||||
b = obj if isinstance(obj, bytes) else json.dumps(obj).encode()
|
||||
self.send_response(200); self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)
|
||||
def body(self):
|
||||
n = int(self.headers.get("Content-Length", 0)); return self.rfile.read(n)
|
||||
def do_GET(self):
|
||||
if "/getUpdates" in self.path:
|
||||
off = int(re.search(r"offset=(-?\d+)", self.path).group(1))
|
||||
for _ in range(10):
|
||||
with LOCK:
|
||||
got = [u for u in updates if u["update_id"] >= off]
|
||||
if got: break
|
||||
time.sleep(0.2)
|
||||
return self.reply({"ok": True, "result": got})
|
||||
self.reply({"ok": True, "result": []})
|
||||
def do_POST(self):
|
||||
raw = self.body()
|
||||
if "/sendMessage" in self.path:
|
||||
text = json.loads(raw).get("text", "")
|
||||
with open(sys.argv[3], "a") as f: f.write(text.replace("\n", " | ") + "\n")
|
||||
m = re.match(r"Zustimmung (\d+):", text)
|
||||
if m:
|
||||
add_update("was machst du?") # must be told to wait
|
||||
add_update("ok " + m.group(1), frm=99) # stranger: ignored
|
||||
add_update(ANSWER + " " + m.group(1))
|
||||
return self.reply({"ok": True, "result": {}})
|
||||
if "/sendChatAction" in self.path:
|
||||
return self.reply({"ok": True, "result": True})
|
||||
req = json.loads(raw)
|
||||
has_tool = any(m.get("role") == "tool" for m in req.get("messages", []))
|
||||
if has_tool:
|
||||
chunks = [{"choices": [{"delta": {"content": "fertig"}}]},
|
||||
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
|
||||
else:
|
||||
args = json.dumps({"path": TARGET, "content": "vom gateway\n"})
|
||||
chunks = [{"choices": [{"delta": {"tool_calls": [{"index": 0, "id": "c1",
|
||||
"type": "function", "function": {"name": "write", "arguments": args}}]}}]},
|
||||
{"choices": [{"delta": {}, "finish_reason": "tool_calls"}]}]
|
||||
b = "".join("data: " + json.dumps(c) + "\n\n" for c in chunks) + "data: [DONE]\n\n"
|
||||
self.reply(b.encode(), "text/event-stream")
|
||||
http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
@@ -116,6 +117,44 @@ main(void)
|
||||
strcmp(who, "first") == 0, "the first answer wins");
|
||||
}
|
||||
|
||||
/*
|
||||
* ---- the channel message says what is approved, and is only data ----
|
||||
* It used to be "Zustimmung <id>" alone, so a phone said yes to a
|
||||
* number.
|
||||
*/
|
||||
{
|
||||
const char *chan = "/var/tmp/splinter_test_ack/chan.sh";
|
||||
const char *got = "/var/tmp/splinter_test_ack/chan.out";
|
||||
const char *mark = "/var/tmp/splinter_test_ack/pwned";
|
||||
FILE *f = fopen(chan, "w");
|
||||
char msg[1024] = "";
|
||||
|
||||
if (f != NULL) {
|
||||
fprintf(f, "#!/bin/sh\nprintf '%%s' \"$1\" > %s\n", got);
|
||||
fclose(f);
|
||||
}
|
||||
(void)chmod(chan, 0700);
|
||||
(void)setenv("SPLINTER_ACK_CHANNELS", chan, 1);
|
||||
id = sp_ack_request("run",
|
||||
"{\"command\":\"x'; touch /var/tmp/splinter_test_ack/pwned; '\"}",
|
||||
"destructive", 5);
|
||||
CHECK(sp_ack_notify(id, NULL) == 1, "the channel was fired");
|
||||
f = fopen(got, "r");
|
||||
if (f != NULL) {
|
||||
size_t n = fread(msg, 1, sizeof(msg) - 1, f);
|
||||
|
||||
msg[n] = '\0';
|
||||
fclose(f);
|
||||
}
|
||||
CHECK(strstr(msg, "run") != NULL && strstr(msg, "touch") != NULL,
|
||||
"the message names the tool and its arguments");
|
||||
CHECK(access(mark, F_OK) != 0,
|
||||
"a quote in the arguments runs nothing");
|
||||
(void)sp_ack_answer(id, 0, "test");
|
||||
(void)sp_ack_wait(id, 1, who, sizeof(who));
|
||||
(void)unsetenv("SPLINTER_ACK_CHANNELS");
|
||||
}
|
||||
|
||||
/* ---- a directory others may write into is not trusted with a yes ---- */
|
||||
(void)system("rm -rf /var/tmp/splinter_test_ack_open");
|
||||
(void)system("mkdir -p /var/tmp/splinter_test_ack_open && "
|
||||
|
||||
Executable
+61
@@ -0,0 +1,61 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# splinter -- the Telegram gateway asks for approval in its own chat.
|
||||
#
|
||||
# Before: a tool call that needed consent either was denied (no approval
|
||||
# stream in a daemon) or waited for an "ok <id>" that only the blocked gateway
|
||||
# could have read. And a refused sendMessage crashed it (NULL err). Run against
|
||||
# a fake Bot API and a fake model, once with "ok" and once with "no".
|
||||
set -u
|
||||
cd "$(dirname "$0")/.." || exit 1
|
||||
D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-gw-XXXXXX") || exit 1
|
||||
trap 'rm -rf "$D"' EXIT
|
||||
fails=0
|
||||
|
||||
run() { # $1 = answer word; leaves $D/sent.log and maybe $D/out.txt
|
||||
P=$((20000 + ($$ + ${2:-0}) % 30000))
|
||||
rm -rf "$D/home" "$D/out.txt" "$D/sent.log"
|
||||
mkdir -p "$D/home"
|
||||
printf 'endpoint = http://127.0.0.1:%s/v1/chat/completions\nmodel = m\ntelegram_allow = 7\n' \
|
||||
"$P" > "$D/home/splinter.conf"
|
||||
python3 -I tests/fake_telegram.py "$P" "$D/out.txt" "$D/sent.log" "$1" &
|
||||
S=$!
|
||||
for i in $(seq 1 50); do
|
||||
curl -s -o /dev/null "http://127.0.0.1:$P/x" && break
|
||||
sleep 0.2
|
||||
done
|
||||
HOME="$D/home" SPLINTER_TELEGRAM_TOKEN=tok \
|
||||
SPLINTER_TELEGRAM_API="http://127.0.0.1:$P" \
|
||||
SPLINTER_ACK_DIR="$D/home/ack" SPLINTER_ACK_TTL=20 \
|
||||
./splinter --config "$D/home/splinter.conf" --daemon \
|
||||
> "$D/gw.out" 2>&1 &
|
||||
G=$!
|
||||
for i in $(seq 1 40); do
|
||||
grep -q '^fertig' "$D/sent.log" 2>/dev/null && break
|
||||
sleep 0.5
|
||||
done
|
||||
kill "$G" "$S" 2>/dev/null
|
||||
wait "$G" "$S" 2>/dev/null
|
||||
}
|
||||
|
||||
check() { # $1 = description, $2.. = command
|
||||
d=$1; shift
|
||||
if "$@"; then :; else echo "FAIL $d"; fails=$((fails + 1)); fi
|
||||
}
|
||||
|
||||
run ok 0
|
||||
check "approval is asked in the chat, with the tool" \
|
||||
grep -q '^Zustimmung [0-9]*: write ' "$D/sent.log"
|
||||
check "a question meanwhile is told to wait" \
|
||||
grep -q '^Ich warte noch' "$D/sent.log"
|
||||
check "the yes is acknowledged" grep -q '^Zustimmung erteilt' "$D/sent.log"
|
||||
check "the tool ran after the yes" grep -q 'vom gateway' "$D/out.txt"
|
||||
check "the turn ends with the answer" grep -q '^fertig' "$D/sent.log"
|
||||
|
||||
run no 1
|
||||
check "the no is acknowledged" grep -q '^Abgelehnt' "$D/sent.log"
|
||||
check "the tool did not run after the no" test ! -e "$D/out.txt"
|
||||
|
||||
if [ "$fails" -eq 0 ]; then echo "test_gateway: ok"; exit 0; fi
|
||||
cat "$D/gw.out"
|
||||
exit 1
|
||||
@@ -8,7 +8,11 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "config.h"
|
||||
#include "memory.h"
|
||||
|
||||
static int failures;
|
||||
@@ -33,6 +37,74 @@ main(void)
|
||||
CHECK(user != NULL);
|
||||
CHECK(strlen(user) > 0);
|
||||
|
||||
/*
|
||||
* ---- memory_key_env reaches the server, and only through stdin ----
|
||||
* It used to become SPLINTER_MEM_KEY in curl's environment, which curl
|
||||
* never reads: no request carried a key. A fake curl records its argv
|
||||
* and the config it is handed.
|
||||
*/
|
||||
{
|
||||
char dir[] = "/var/tmp/splinter-mem-XXXXXX";
|
||||
char path[600], line[1400], cfgf[620], argf[620];
|
||||
char buf[4096];
|
||||
const char *oldpath = getenv("PATH");
|
||||
static struct sp_config c;
|
||||
struct sp_registry r;
|
||||
struct sp_buf out;
|
||||
const struct sp_tool *t;
|
||||
FILE *f;
|
||||
size_t n;
|
||||
|
||||
CHECK(mkdtemp(dir) != NULL);
|
||||
snprintf(cfgf, sizeof(cfgf), "%s/cfg", dir);
|
||||
snprintf(argf, sizeof(argf), "%s/args", dir);
|
||||
snprintf(path, sizeof(path), "%s/curl", dir);
|
||||
f = fopen(path, "w");
|
||||
CHECK(f != NULL);
|
||||
if (f != NULL) {
|
||||
fprintf(f, "#!/bin/sh\nprintf '%%s\\n' \"$@\" > %s\n"
|
||||
"cat > %s\necho '{\"results\":[]}'\n", argf, cfgf);
|
||||
fclose(f);
|
||||
}
|
||||
(void)chmod(path, 0755);
|
||||
snprintf(line, sizeof(line), "%s:%s", dir,
|
||||
oldpath != NULL ? oldpath : "/usr/bin:/bin");
|
||||
(void)setenv("PATH", line, 1);
|
||||
(void)setenv("MY_MEM0_KEY", "m0-geheim", 1);
|
||||
|
||||
sp_config_init(&c);
|
||||
snprintf(c.memory_url, sizeof(c.memory_url), "http://mem0.example");
|
||||
snprintf(c.memory_key_env, sizeof(c.memory_key_env), "MY_MEM0_KEY");
|
||||
memset(&r, 0, sizeof(r));
|
||||
CHECK(sp_memory_register(&r, &c) == 0);
|
||||
CHECK(sp_buf_init(&out) == 0);
|
||||
t = sp_registry_find(&r, "memory_search");
|
||||
CHECK(t != NULL);
|
||||
if (t != NULL)
|
||||
(void)t->run("{\"query\":\"x\"}", &out, t->ctx);
|
||||
|
||||
buf[0] = '\0';
|
||||
if ((f = fopen(cfgf, "r")) != NULL) {
|
||||
n = fread(buf, 1, sizeof(buf) - 1, f);
|
||||
buf[n] = '\0';
|
||||
fclose(f);
|
||||
}
|
||||
CHECK(strstr(buf, "Authorization: Token m0-geheim") != NULL);
|
||||
buf[0] = '\0';
|
||||
if ((f = fopen(argf, "r")) != NULL) {
|
||||
n = fread(buf, 1, sizeof(buf) - 1, f);
|
||||
buf[n] = '\0';
|
||||
fclose(f);
|
||||
}
|
||||
CHECK(buf[0] != '\0' && strstr(buf, "m0-geheim") == NULL);
|
||||
|
||||
sp_buf_free(&out);
|
||||
sp_registry_free(&r);
|
||||
(void)setenv("PATH", oldpath != NULL ? oldpath : "/usr/bin:/bin", 1);
|
||||
snprintf(line, sizeof(line), "rm -rf '%s'", dir);
|
||||
(void)system(line);
|
||||
}
|
||||
|
||||
if (failures == 0)
|
||||
printf("test_memory: ok\n");
|
||||
return failures == 0 ? 0 : 1;
|
||||
|
||||
Reference in new issue
Block a user