diff --git a/Makefile b/Makefile index d568013..ad34e77 100644 --- a/Makefile +++ b/Makefile @@ -386,6 +386,7 @@ check: $(LIB) $(BIN) $(CLIENT) $(PLUGIN) $(TESTS) tests/test_junction echo "== tests/test_junction.sh"; sh tests/test_junction.sh; \ echo "== tests/test_mcpsession.sh"; sh tests/test_mcpsession.sh; \ echo "== tests/test_ask_mcp.sh"; sh tests/test_ask_mcp.sh; \ + echo "== tests/test_ask_timeout.sh"; sh tests/test_ask_timeout.sh; \ echo "all tests passed" # The unit tests under ASAN/UBSAN with leak detection. Rebuilds the tree with diff --git a/README.md b/README.md index a52ad47..49aeec6 100644 --- a/README.md +++ b/README.md @@ -1056,7 +1056,10 @@ the prompt. The chat and the Telegram gateway ask (there the question arrives as a message and the next message from an allowed user is the answer). A run with no operator attached — `-p`, the A2A server, a gateway that only streams — - tells the model so at once instead of parking the turn. + tells the model so at once instead of parking the turn. A front end that + never answers the question (an older client that does not know the `ask` + event) parks the turn until the wait ends: 900 seconds by default, set + `ask_timeout` or `SPLINTER_ASK_TIMEOUT` to make it shorter. - `echo` (read), `clock` (read). Mutate and destructive tools ask first, unless `--autonomous` is set. In the diff --git a/docs/CONFIG.md b/docs/CONFIG.md index a7ebcec..13fe57d 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -256,6 +256,7 @@ The `${NAME}` form inserts an environment variable. | `theme` | `Xresources` (the default: `*foreground`, `*background`, `*color0..15` from `xrdb`), `light`/`dark` (white or black page, black or white text), or a CDE palette name (`splinter --list-themes`) | | `locale` | language code (`de`, `en`); catalogues live in `share/locale` | | `autonomous` | `1` runs mutating/destructive tools without asking | +| `ask_timeout` | seconds an `ask` waits for the operator's answer (default 900); `SPLINTER_ASK_TIMEOUT` overrides it for one run. Shorten it for a run with no operator attached, so a turn does not park for the full wait | | `steps` | tool rounds per turn (default 150) | | `max_bytes` | conversation budget in bytes, `0` = no limit | | `compact_threshold` | context tokens past which the next request is compacted (`0` = off); judged by the prompt size the provider reports, which every streamed turn asks for | diff --git a/include/splinter.h b/include/splinter.h index 00b8d80..2f032df 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -369,12 +369,16 @@ int sp_session_remove_if_empty(const char *dir, const char *id); #define SP_ASK_OPTIONS 8 /* "which one?" alternatives */ #define SP_ASK_OPT_LEN 96 /* - * How long the `ask` tool waits for an answer. Long enough that a person can - * read the question and think, short enough that a turn with no front end - * attached (a script, a gateway that forgot the caller) comes back with "nobody - * answered" instead of hanging until somebody kills it. + * How long the `ask` tool waits for an answer, when nothing else says. Long + * enough that a person can read the question and think, short enough that a + * turn whose front end does not know the question (an old client, a script) + * comes back with "nobody answered" instead of hanging until somebody kills + * it. Overridden by $SPLINTER_ASK_TIMEOUT, then by `ask_timeout` in the + * config; see sp_ask_wait_s(). No upper bound: how long a turn may wait is + * the operator's call, not the program's. */ #define SP_ASK_WAIT_S 900 +int sp_ask_wait_s(void); struct sp_agent_config { size_t max_steps; /* tool rounds per turn */ diff --git a/share/locale/de.msg b/share/locale/de.msg index d08d970..e2720b5 100644 --- a/share/locale/de.msg +++ b/share/locale/de.msg @@ -44,7 +44,6 @@ sidebar.cwd = Verzeichnis sidebar.last_turn = letzter Turn sidebar.tokens = %zu Tok (ein %zu) - role.you = du role.agent = modell role.thinking = denkt @@ -214,7 +213,6 @@ connect.test_failed = Der Test schlug fehl: %s (gespeichert ist er trotzdem) connect.use = Jetzt nutzen connect.later = Spaeter - reply.empty = (leer) # Agent-Profile, Kontingent, Seitenleiste (mit den Profilen dazugekommen) @@ -293,3 +291,6 @@ ui.ask_hint = Enter nimmt die Zeile; Tippen ersetzt sie Esc bricht ab # das `ask`-Tool im Telegram-Gateway: die Frage kommt als Nachricht ask.how = Antworte mit einer Nachricht. + +# /cancel waehrend einer offenen ask-Frage: der Turn endet, die Frage ist weg +ask.cancelled = abgebrochen - die Frage ist erledigt. diff --git a/share/locale/en.msg b/share/locale/en.msg index c6ddcc6..c703138 100644 --- a/share/locale/en.msg +++ b/share/locale/en.msg @@ -292,3 +292,6 @@ ui.ask_hint = Enter takes the row; typing replaces it Esc cancels # the `ask` tool in the Telegram gateway: the question arrives as a message ask.how = Answer with a message. + +# /cancel while an `ask` question is open: the turn ends, the question is gone +ask.cancelled = cancelled - the question is gone. diff --git a/share/locale/pt_BR.msg b/share/locale/pt_BR.msg index 13352eb..ffb8ba0 100644 --- a/share/locale/pt_BR.msg +++ b/share/locale/pt_BR.msg @@ -55,7 +55,6 @@ sidebar.cwd = diretorio sidebar.last_turn = ultimo turno sidebar.tokens = %zu tok (entrada %zu) - role.you = voce role.agent = modelo role.thinking = pensando @@ -217,7 +216,6 @@ connect.test_failed = O teste falhou: %s (mesmo assim esta salvo) connect.use = Usar agora connect.later = Depois - reply.empty = (vazio) # perfis de agente, uso, barra lateral (junto com os perfis) @@ -296,3 +294,6 @@ ui.ask_hint = Enter pega a linha; digitar substitui Esc cancela # a ferramenta `ask` no gateway do Telegram: a pergunta chega como mensagem ask.how = Responda com uma mensagem. + +# /cancel com uma pergunta `ask` aberta: o turno termina, a pergunta some +ask.cancelled = cancelado - a pergunta nao existe mais. diff --git a/src/backend/agent.c b/src/backend/agent.c index de9bbee..60c358e 100644 --- a/src/backend/agent.c +++ b/src/backend/agent.c @@ -66,6 +66,28 @@ static void quota_hint(const char *provider, const char *key_id, long status, lo sp_provstate_update(provider, key_id, quota_set_fn, &c); } +/* + * How long an `ask` waits for its answer. The environment wins, then the + * config, then SP_ASK_WAIT_S -- the same order the other timeouts use, so an + * operator can shorten it for a scripted run without editing a file, and a + * config can make it a lasting choice. A value that does not parse is not a + * reason to fall back silently: 0 and garbage both mean "not set" here, and + * the default stands. + */ +int +sp_ask_wait_s(void) +{ + const char *s = getenv("SPLINTER_ASK_TIMEOUT"); + long v; + + if (s != NULL && *s != '\0') { + v = strtol(s, NULL, 10); + if (v > 0) + return v > 0x7fffffff ? 0x7fffffff : (int)v; + } + return SP_ASK_WAIT_S; +} + static void * ack_stdin_thread(void *arg) { diff --git a/src/backend/config.c b/src/backend/config.c index 24f09e3..e0e072f 100644 --- a/src/backend/config.c +++ b/src/backend/config.c @@ -842,6 +842,8 @@ load_stream(struct sp_config *c, FILE *f, const char *path, c->delegate_timeout = strtol(val, NULL, 10); else if (!strcmp(key, "run_timeout")) c->run_timeout = strtol(val, NULL, 10); + else if (!strcmp(key, "ask_timeout")) + c->ask_timeout = strtol(val, NULL, 10); else if (!strcmp(key, "env_delegates")) c->env_delegates = (!strcmp(val, "1") || !strcmp(val, "true") || !strcmp(val, "yes")) ? 1 : 0; diff --git a/src/backend/config.h b/src/backend/config.h index f49e4b1..86a5832 100644 --- a/src/backend/config.h +++ b/src/backend/config.h @@ -168,6 +168,7 @@ struct sp_config { long cli_timeout; /* seconds for cli transport, 0: default */ long delegate_timeout; /* seconds for delegate children, 0: default */ long run_timeout; /* seconds for the run tool, 0: default */ + long ask_timeout; /* seconds an ask waits for an answer, 0: default */ int autonomous; /* -1 not set, 0 off, 1 on */ int on_limit_fail; /* 1: a usage limit fails the turn instead of waiting */ long max_wait; /* longest wait for a limit, seconds, 0: 12 h */ diff --git a/src/backend/engine.c b/src/backend/engine.c index dc0be3b..56e0b54 100644 --- a/src/backend/engine.c +++ b/src/backend/engine.c @@ -1283,7 +1283,7 @@ engine_ask(void *ctx, const char *text, const char (*opts)[SP_ASK_OPT_LEN], /* the event carries the question; the front end polls for the answer */ ev_push(e, SP_EV_ASK, (long)e->ask_nopts, e->ask_text, NULL); clock_gettime(CLOCK_REALTIME, &deadline); - deadline.tv_sec += SP_ASK_WAIT_S; + deadline.tv_sec += sp_ask_wait_s(); pthread_mutex_lock(&e->lock); while (e->ask_pending && !e->cancel && pthread_cond_timedwait(&e->cond, &e->lock, &deadline) == 0) @@ -2034,11 +2034,12 @@ sp_engine_prompt(struct sp_engine *e, const char *text, sp_stream_cb stream, * No `ask` channel here on purpose. This path runs the turn on the * CALLING thread, and its callers (-p, the slash prompt) have no loop * that polls the event queue -- so an `ask` would park for the full - * SP_ASK_WAIT_S with nobody able to answer it. Measured: -p against a - * model that asks hung for 900 s and had to be killed. With cfg.ask - * left as it came in (NULL from main), the tool answers at once with - * "nobody can be asked here" and the turn goes on. A front end that - * does poll can still set e->base.ask itself. + * ask wait (sp_ask_wait_s(), 900 s by default) with nobody able to + * answer it. Measured: -p against a model that asks hung for 900 s and + * had to be killed. With cfg.ask left as it came in (NULL from main), + * the tool answers at once with "nobody can be asked here" and the + * turn goes on. A front end that does poll can still set e->base.ask + * itself. */ cfg.cancel = &e->cancel; e->ag.cfg = &cfg; diff --git a/src/backend/mcpsession.c b/src/backend/mcpsession.c index ef55e6d..e0e6b7d 100644 --- a/src/backend/mcpsession.c +++ b/src/backend/mcpsession.c @@ -429,7 +429,8 @@ tool_say(const char *args, struct sp_buf *out) * park as an approval and must leave the same way: returned * to the caller as a question, with the tool that answers it * named. Waiting here instead held the MCP call for the full - * SP_ASK_WAIT_S (measured: 900 s, client timed out at 15 s). + * ask wait (sp_ask_wait_s(), 900 s by default; the client timed + * out at 15 s). */ if (sp_engine_state(e, &st) == 0 && st.asking) { char qt[SP_ASK_MAX]; diff --git a/src/frontend/curses.c b/src/frontend/curses.c index 5a0d0d0..7ed8a22 100644 --- a/src/frontend/curses.c +++ b/src/frontend/curses.c @@ -3921,7 +3921,7 @@ turn_ask(struct ui_state *s) /* * No window (a terminal too small to draw one). The question is * already parked in the engine, so leaving without an answer - * would hold the turn for SP_ASK_WAIT_S. An empty answer is the + * would hold the turn for the full ask wait. An empty answer is the * one the tool reports as "no answer". */ (void)s->be->answer(s->be->ctx, ""); diff --git a/src/frontend/protocol.c b/src/frontend/protocol.c index d7128ac..5f888e8 100644 --- a/src/frontend/protocol.c +++ b/src/frontend/protocol.c @@ -841,7 +841,14 @@ handle_line(struct client *c, struct proto *p, const char *line) (void)sp_engine_approve(eng, mcp_arg_bool(v, "allow", 0)); } else if (strcmp(cmd, "answer") == 0) { text = mcp_arg_string(v, "text"); - (void)sp_engine_answer(eng, text != NULL ? text : ""); + /* + * An answer that arrives after the question is gone (the wait + * expired, the turn was cancelled) must not look like it was + * taken: the client would go on believing the operator was + * heard. `steer` reports the same way one branch down. + */ + if (sp_engine_answer(eng, text != NULL ? text : "") == 0) + (void)send_error(c, "no question is pending"); } else if (strcmp(cmd, "cancel") == 0) { (void)sp_engine_cancel(eng); } else if (strcmp(cmd, "steer") == 0) { diff --git a/src/main.c b/src/main.c index 0d0454f..31e999c 100644 --- a/src/main.c +++ b/src/main.c @@ -656,6 +656,10 @@ load_config(struct opts *o, struct sp_config *conf, struct sp_agent_config *cfg, snprintf(tbuf, sizeof(tbuf), "%ld", conf->run_timeout); setenv("SPLINTER_RUN_TIMEOUT", tbuf, 0); } + if (conf->ask_timeout > 0) { + snprintf(tbuf, sizeof(tbuf), "%ld", conf->ask_timeout); + setenv("SPLINTER_ASK_TIMEOUT", tbuf, 0); + } } /* a config means "this is my setup": start the chat */ if (o->prompt == NULL) diff --git a/tests/test_ask_timeout.sh b/tests/test_ask_timeout.sh new file mode 100755 index 0000000..71819e1 --- /dev/null +++ b/tests/test_ask_timeout.sh @@ -0,0 +1,122 @@ +#!/bin/sh +# The `ask` tool when the front end does not answer: the turn must come back, +# not park. +# +# What it guards: a protocol client that ignores the `ask` event -- one written +# before the event existed, which the version number does not exclude because +# additive events keep it -- leaves the question pending. Before ask_timeout +# existed the wait was hard-coded to 900 s, so such a client lost the turn for +# fifteen minutes with no way to shorten it. Here the wait is set to 3 s and the +# check is that the turn RETURNS with the "no answer" observation instead of +# staying parked. +# +# A test that only checked "the ask event arrived" would have passed while that +# park was in the code: the event did arrive, nobody acted on it. +set -u +cd "$(dirname "$0")/.." || exit 1 +. tests/sh/port.sh +SP=${SPLINTER:-./splinter} +D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-askto-XXXXXX") || exit 1 +set -- $(free_ports 1) +P=$1 +F= +S= +cleanup() { [ -n "$F" ] && kill $F 2>/dev/null; [ -n "$S" ] && kill $S 2>/dev/null + rm -rf "$D"; } +trap cleanup EXIT INT TERM +fail=0 +check() { if eval "$2"; then echo "ok $1"; else echo "FAIL $1"; fail=$((fail + 1)); fi; } + +mkdir -p "$D/home" +python3 -I tests/fake_openai_ask.py "$P" "green,blue" > "$D/fake.out" 2>&1 & +F=$! +if ! wait_listen "$P" "$F"; then + echo "FAIL the fake endpoint did not start" + cat "$D/fake.out" + exit 1 +fi + +# the whole point: the wait is the operator's, not a constant in the code +HOME=$D/home SPLINTER_LOCALE=en SPLINTER_ASK_TIMEOUT=3 ./splinter \ + --no-config --autonomous --model m \ + --endpoint "http://127.0.0.1:$P/v1/chat/completions" \ + --serve --socket "$D/sock" > "$D/serve.out" 2>&1 & +S=$! +i=0 +while [ ! -e "$D/sock" ] && [ "$i" -lt 100 ]; do i=$((i + 1)); sleep 0.2; done +if [ ! -e "$D/sock" ]; then + echo "FAIL the server never created its socket" + cat "$D/serve.out" + exit 1 +fi + +python3 - "$D/sock" > "$D/result" 2> "$D/client.err" <<'PY' +import json, socket, sys, time + +s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) +# generous next to the 3 s wait: this bounds the test, it is not the check +s.settimeout(30) +s.connect(sys.argv[1]) +f = s.makefile("rw", encoding="utf-8") +while True: + if json.loads(f.readline()).get("ev") == "state": + break + +f.write(json.dumps({"cmd": "say", "text": "baue eine login seite"}) + "\n") +f.flush() +t0 = time.time() +saw_ask = False +turn = None +while time.time() - t0 < 25: + try: + ev = json.loads(f.readline()) + except (socket.timeout, OSError): + break # the park: no event at all + if ev.get("ev") == "ask": + saw_ask = True + # deliberately no answer: this is the client that cannot answer + continue + if ev.get("ev") == "turn": + turn = ev + break +took = time.time() - t0 +print("ask_event %s" % ("yes" if saw_ask else "no")) +print("turn_returned %s" % ("yes" if turn else "no")) +print("turn_fast %s" % ("yes" if turn and took < 20 else "no")) +print("turn_ok %s" % ("yes" if turn and turn.get("ok") else "no")) +print("no_answer_said %s" % + ("yes" if turn and "no answer" in turn.get("answer", "") else "no")) + +# the question is gone now: a late answer must be refused, not silently taken +late = None +try: + f.write(json.dumps({"cmd": "answer", "text": "blue"}) + "\n") + f.flush() + while True: + ev = json.loads(f.readline()) + if ev.get("ev") == "error": + late = ev.get("text", "") + break + if ev.get("ev") == "turn": + break +except (socket.timeout, OSError): + pass # the turn never came back; reported above +print("late_answer_refused %s" % + ("yes" if late and "no question" in late else "no")) +PY + +while read -r key val; do + case $key in + ask_event) check 'the question reaches the client as an event' '[ "$val" = yes ]' ;; + turn_returned) check 'the turn returns instead of staying parked' '[ "$val" = yes ]' ;; + turn_fast) check 'it returns at the configured wait, not at 900 s' '[ "$val" = yes ]' ;; + turn_ok) check 'the turn is a success, not an error' '[ "$val" = yes ]' ;; + no_answer_said) check 'the model is told nobody answered' '[ "$val" = yes ]' ;; + late_answer_refused) check 'an answer after the wait is refused' '[ "$val" = yes ]' ;; + esac +done < "$D/result" 2>/dev/null +[ -s "$D/result" ] || { echo "FAIL the client produced no result" + cat "$D/client.err"; fail=$((fail + 1)); } + +[ "$fail" -eq 0 ] || { echo "--- server log ---"; cat "$D/serve.out"; exit 1; } +echo "test_ask_timeout: ok"