From 181b2c0638fe7c710c853d195e7faa8faece266d Mon Sep 17 00:00:00 2001 From: lotherk Date: Tue, 24 Nov 2026 07:57:35 +0000 Subject: [PATCH] ask: the model can put a question to the operator, in every front end The `ask` tool asks and the answer -- or "nobody answered" -- becomes the observation. Read class: it changes nothing on the machine, and the authority is the operator, not a gate. Front ends: the chat draws a dialog (options to pick, typed words still count), the protocol carries it as an `ask` event and an `answer` command, MCP returns it from splinter_say and resumes with splinter_answer, the Telegram gateway sends it as a message and takes the next message from an allowed user. What the review of the WIP found, and what this fixes: - -p hung for the full 900 s ask wait: sp_engine_prompt installed engine_ask, but nobody polls events on the synchronous path. cfg.ask now stays NULL there, so the tool answers at once with "nobody can be asked here". Measured: 3 s instead of 900 s (was rc=124 after 20 s). - splinter_say over MCP hung the same way, because tool_say only looked at st.waiting. It now looks at st.asking and returns the question; the client timed out at 15 s before, and the turn was lost. - protocol.c read the question buffer uninitialized when sp_engine_ask returned 0. - turn_ask answered nothing when the window could not be opened, which parked the turn for the full wait. - pick_run computed the list height without the question's rows, so the highlighted row scrolled out of the window (reproduced: after nine Downs no ">" row was on the screen). pick_draw and pick_run now share pick_listtop(). - the Telegram gateway was dead for this tool: it runs its turns on a copy of e->base, where ask was never set, so the model was told "nobody can be asked" while the operator sat in the chat. New tg_ask, verified against a running daemon and covered in test_gateway.sh. - tests/test_ask_ui.sh was untracked and not in make check, so it never ran. A2A keeps no ask channel on purpose: there an approval pauses the task into INPUT_REQUIRED, and the ask signature cannot express a pause -- saying "nobody can be asked" is the honest answer there. Tests: make check green (327 s), including the new test_ask_mcp.sh and test_ask_ui.sh, both wired into make check. test_ask_mcp.sh was verified to fail against the unfixed code (client times out, no result written). make check-asan: 46 binaries clean. make check-tsan: 46 binaries, no races. --- Makefile | 2 + README.md | 42 +++++- docs/FRONTENDS.md | 4 + docs/PROTOCOL.md | 10 +- include/splinter.h | 29 ++++ include/splinter_engine.h | 30 +++++ share/locale/de.msg | 10 ++ share/locale/en.msg | 10 ++ share/locale/pt_BR.msg | 10 ++ src/backend/engine.c | 216 +++++++++++++++++++++++++++++- src/backend/mcpsession.c | 47 ++++++- src/backend/telegram.c | 121 +++++++++++++++++ src/frontend/curses.c | 247 +++++++++++++++++++++++++++++++++-- src/frontend/protocol.c | 36 +++++ src/frontend/ui_backend.h | 8 ++ src/frontend/ui_local.c | 13 ++ src/frontend/ui_remote.c | 54 ++++++++ tests/fake_openai_ask.py | 39 ++++++ tests/fake_telegram.py | 21 +++ tests/sh/port.sh | 87 +++++++++++- tests/test_a2a_context.sh | 19 ++- tests/test_ask_mcp.sh | 113 ++++++++++++++++ tests/test_ask_ui.sh | 95 ++++++++++++++ tests/test_gateway.sh | 44 +++---- tests/test_gateway_openai.sh | 36 +++-- tests/test_interview.sh | 29 ++-- tests/test_junction.sh | 32 ++--- tests/test_mcpsession.sh | 30 ++--- tests/test_pools.sh | 14 +- tests/test_protocol.sh | 20 ++- 30 files changed, 1317 insertions(+), 151 deletions(-) create mode 100644 tests/fake_openai_ask.py create mode 100755 tests/test_ask_mcp.sh create mode 100755 tests/test_ask_ui.sh diff --git a/Makefile b/Makefile index a2a640e..d568013 100644 --- a/Makefile +++ b/Makefile @@ -375,6 +375,7 @@ check: $(LIB) $(BIN) $(CLIENT) $(PLUGIN) $(TESTS) tests/test_junction echo "== tests/test_a2a_input.sh"; sh tests/test_a2a_input.sh; \ echo "== tests/test_swarm_socket.sh"; sh tests/test_swarm_socket.sh; \ echo "== tests/test_ui.sh"; sh tests/test_ui.sh; \ + echo "== tests/test_ask_ui.sh"; sh tests/test_ask_ui.sh; \ echo "== tests/test_protocol.sh"; sh tests/test_protocol.sh; \ echo "== tests/test_attach.sh"; sh tests/test_attach.sh; \ echo "== tests/test_attach_busy.sh"; sh tests/test_attach_busy.sh; \ @@ -384,6 +385,7 @@ check: $(LIB) $(BIN) $(CLIENT) $(PLUGIN) $(TESTS) tests/test_junction echo "== tests/test_reconnect.sh"; sh tests/test_reconnect.sh; \ 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 "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 03c2d00..a52ad47 100644 --- a/README.md +++ b/README.md @@ -606,12 +606,26 @@ or job state; no model turn, no transport. ## A fleet in one directory -`src/swarm.c` is the local variant. The first splinter started in a directory -binds `.splinter-swarm.sock` and becomes the master; later ones join as slaves. +`src/backend/swarm.c` is the local variant, and it is opt-in: `--chat --swarm` +is what binds `.splinter-swarm.sock`. A plain `--chat` never creates the file, +never joins a fleet, and cannot be locked by one — a shared working directory +used to collect a leftover socket from every session, and the next start that +found one sat on `[swarm locked]` because nobody answered on it. + +The first instance to bind becomes the master; later ones join as slaves. `/swarm ` sends a line to the least busy peer, `/swarm ` picks one, `/swarm ls` lists them, and a routed command runs there. It is IPC between processes that share a working directory — not A2A, and not a network protocol. +The file exists exactly as long as the fleet does: it is removed by the last +member to leave, whatever order the members go in. When the master exits first, +a remaining member takes the fleet over (binds the path, or joins whoever was +faster); a master that is killed hard leaves the file without a listener, and +the survivor removes that leftover and binds it, because a refused connect is +proof that nobody answers there. SIGTERM and SIGHUP unlink the file from the +signal handler (`swarm_emergency_unlink`), since those never reach +`sp_engine_close`. + ## First run: the interview splinter --interview @@ -997,12 +1011,16 @@ work with splinter itself: splinter_steer type into the running turn splinter_cancel cancel the running turn splinter_approve answer a pending approval (allow true|false) + splinter_answer answer the question the `ask` tool asked `say` starts a real turn, so the server needs a provider: give it `-m` (or run `--daemon --mcp-server-listen`, where the Telegram daemon and the MCP server share one engine). A turn that parks on an approval is returned as the -question, not as a failure; `splinter_approve` answers it. The first line of -`splinter_say` is the answer, then the step and tool-call counts. +question, not as a failure; `splinter_approve` answers it. A turn that parks +on the `ask` tool comes back the same way ("the model asks: ..."), and +`splinter_answer` delivers the text — both return instead of holding the call +until the client gives up. The first line of `splinter_say` is the answer, then +the step and tool-call counts. ## Tools @@ -1031,6 +1049,14 @@ the prompt. reports progress is not killed for being long. - `webfetch` (mutate): http(s) only, curl started without a shell. Not read: a URL the model picks is a message out of the machine. +- `ask` (read): puts a question to the operator and waits for the answer; the + answer, or "nobody answered", becomes the observation. Read because it + changes nothing on the machine and the operator is the authority, not a gate. + With `options` the chat shows a dialog to pick from; typed words still count. + 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. - `echo` (read), `clock` (read). Mutate and destructive tools ask first, unless `--autonomous` is set. In the @@ -1084,6 +1110,14 @@ ABI in `docs/PLUGINS.md`. ThreadSanitizer, then back) when you touched threads, a widget or a plugin's process globals. It is not part of `make check` because a race is not deterministic and the rebuild is slow. +- A shell test that starts a server takes its port from `tests/sh/port.sh` and + waits with `wait_listen` (HTTP) or `wait_tcp` (anything else) — never a + number, never a `sleep`. A guessed port (`20000 + $$ % 30000`) landed on one + `dtsession` held on 2026-11-21: the fake died, curl answered from the desktop + session, and twenty checks failed pointing at the gateway instead of at + the port. + The wait proves the *started process* owns the listening socket, because a + fake that dies on a taken port still leaves something answering there. ## License diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index fc368cb..0ff5cc0 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -110,6 +110,10 @@ The recommended shape for a GUI: * draw `tool` as a call row and `tool_result` under it (or on the same row when `join` is true); * when `approval` arrives, show the question and send `approve`; +* when `ask` arrives, show `text` and `options` and send `answer` with the + text the operator gave; the turn is parked until it arrives, so a client + that ignores the event leaves the model waiting (the engine's timeout ends + it with "nobody answered", but slowly); * `busy` drives the spinner; `cancel` and `steer` are the two buttons that must remain live during a turn; * nothing in the client has to know a provider, a session file or a tool's diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index fd33d2c..f4bfb93 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -125,6 +125,13 @@ it is sending. Answer the open approval question. `false` denies; the denial becomes the observation the model sees (it is not silent). +### `{"cmd":"answer","text":"..."}` + +Answer the open question from the `ask` tool. The text is the answer; an empty +string counts as "no answer" and the model is told so. A client that answers +nothing leaves the turn parked for the engine's wait, then the tool reports +that nobody answered — it does not hang forever. + ### `{"cmd":"cancel"}` Cancel the running turn. The engine sets its flag; every transport kills the @@ -228,7 +235,7 @@ with 0. | `ev` | fields | meaning | | --- | --- | --- | | `ready` | `protocol`, `version` | the greeting, always first | -| `state` | `session`, `dir`, `model`, `endpoint`, `agent`, `agents[]`, `agent_cur`, `tokens_in`, `tokens_out`, `ctx_used`, `ctx_max`, `cached`, `turn_tokens_out`, `steps`, `calls`, `compactions`, `last_ms`, `last_steps`, `last_calls`, `busy`, `waiting`, `quit` | everything a sidebar or the status bar shows | +| `state` | `session`, `dir`, `model`, `endpoint`, `agent`, `agents[]`, `agent_cur`, `tokens_in`, `tokens_out`, `ctx_used`, `ctx_max`, `cached`, `turn_tokens_out`, `steps`, `calls`, `compactions`, `last_ms`, `last_steps`, `last_calls`, `busy`, `waiting`, `asking`, `quit` | everything a sidebar or the status bar shows | | `submitted` | `text` | the prompt actually run (a command may have rewritten it) | | `busy` | `on` | a turn started or ended | | `stream` | `kind` (`text` or `think`), `text` | a delta of the answer or the reasoning | @@ -238,6 +245,7 @@ with 0. | `entry` | `role`, `text` | a finished transcript entry | | `note` | `text` | a one-line prompt note, e.g. a usage-limit wait; `""` clears it | | `approval` | `name`, `args`, `call`, `auth`, `class` | a tool needs consent; answer with `approve` | +| `ask` | `text`, `options[]` | the `ask` tool's question; answer with `answer` | | `turn` | `ok`, `rc`, `answer`, `error` | one turn ended; `busy:false` ends the work | | `clear` | — | `/new`: drop the transcript pane (the session is new) | | `reply` | `text` | the answer to a command; may be empty | diff --git a/include/splinter.h b/include/splinter.h index f482295..00b8d80 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -359,6 +359,23 @@ int sp_session_remove_if_empty(const char *dir, const char *id); /* ----------------------------------------------------------------- agent */ +/* + * The question a tool may put to the operator (`ask`). The sizes are fixed + * because the pending question lives in the engine struct, which is one per + * process: a model that asks a 4 KiB question should have written it in its + * answer instead. + */ +#define SP_ASK_MAX 1024 /* the question's text */ +#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. + */ +#define SP_ASK_WAIT_S 900 + struct sp_agent_config { size_t max_steps; /* tool rounds per turn */ size_t max_bytes; /* request budget */ @@ -381,6 +398,18 @@ struct sp_agent_config { int (*approve)(void *ctx, const char *name, int auth, const char *args); void *approve_ctx; + /* + * A question the `ask` tool puts to the operator. `opts` holds up to + * `nopts` suggested answers (may be 0) and the callback writes the + * answer into `answer` (cap bytes). Returns 0 on an answer, -1 when + * there is nobody to ask -- the tool then says so in its observation + * instead of hanging. NULL disables the tool's asking and is the one + * difference from an approval, which fails closed. + */ + int (*ask)(void *ctx, const char *text, + const char (*opts)[SP_ASK_OPT_LEN], size_t nopts, + char *answer, size_t cap); + void *ask_ctx; /* * Nonzero: 'approve' is itself the channel (the Telegram gateway asks in * its own chat) and is asked directly. Otherwise the ack mechanism goes diff --git a/include/splinter_engine.h b/include/splinter_engine.h index e7c4e9f..e7902d0 100644 --- a/include/splinter_engine.h +++ b/include/splinter_engine.h @@ -92,6 +92,14 @@ enum sp_ev_kind { SP_EV_NOTE, /* a: the prompt's one line, "" clears it */ SP_EV_ENTRY, /* a: role, b: text */ SP_EV_APPROVAL, /* a: name, b: args, n: authorization class */ + /* + * The model asked the operator a question (the `ask` tool). n: the + * number of options, a: the text. The options are read with + * sp_engine_ask() when the front end draws the dialog; the answer goes + * back through sp_engine_answer(). Not an approval: an approval is a + * yes/no about something that already happened, this is input. + */ + SP_EV_ASK, SP_EV_TURN_END, /* n: rc, a: answer, b: error */ SP_EV_STATE, /* the model, tokens or profile changed */ SP_EV_CLEAR, /* /new: the transcript is the old conversation */ @@ -131,6 +139,13 @@ struct sp_engine_state { int busy; int quit; /* /quit was typed */ int waiting; /* the turn waits for an approval */ + /* + * The turn waits for an answer to the `ask` tool. Separate from + * `waiting` because the answer is text and the way out is different + * (sp_engine_answer, not sp_engine_approve) - a caller that only knew + * "waiting" would send a yes/no to a question that has options. + */ + int asking; int agents_n; int agent_cur; }; @@ -258,6 +273,21 @@ int sp_engine_approval(struct sp_engine *, char *name, size_t namelen, /* Answer it. 0 when nothing was pending. */ int sp_engine_approve(struct sp_engine *, int allow); +/* + * The model asked the operator something (the `ask` tool). Same park/wake as + * the approval above, so cancel and Ctrl-C behave the same, but the answer is + * text: an option the operator picked, or words they typed. + * + * 1 while a question is pending; `text` is what was asked and up to `max` + * options are copied into `opts` (nopts may be NULL). Options are hints for a + * dialog; a front end that has no dialog asks the same question as a line and + * the answer is still valid text. + */ +int sp_engine_ask(struct sp_engine *, char *text, size_t textlen, + char (*opts)[SP_ASK_OPT_LEN], size_t max, size_t *nopts); +/* Answer it with free text or a picked option. 0 when nothing was pending. */ +int sp_engine_answer(struct sp_engine *, const char *text); + /* ------------------------------------------------------------------ input */ /* diff --git a/share/locale/de.msg b/share/locale/de.msg index a540f9d..d08d970 100644 --- a/share/locale/de.msg +++ b/share/locale/de.msg @@ -283,3 +283,13 @@ ui.agent_busy = ein Turn laeuft; wechsle den Agenten, wenn er fertig ist # /learn: mine the sessions of this folder for what stays true learn.empty = (keine frueheren Sitzungen in diesem Ordner - lerne aus diesem Gespraech und sag, was du behalten wuerdest.) + +# der Dialog des `ask`-Tools: das Modell fragt, der Operator antwortet +ui.ask_title = das Modell fragt +ui.ask_empty = (keine Antwortvorschlaege - tippe deine Antwort und Enter) +ui.ask_none = (kein Vorschlag passt - Enter schickt, was du getippt hast) +ui.ask_filter = Antwort: +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. diff --git a/share/locale/en.msg b/share/locale/en.msg index 57dbb0c..c6ddcc6 100644 --- a/share/locale/en.msg +++ b/share/locale/en.msg @@ -282,3 +282,13 @@ ui.agent_busy = a turn is running; switch the agent when it is done # /learn: mine the sessions of this folder for what stays true learn.empty = (no earlier sessions in this folder - learn from this conversation and say what you would keep.) + +# the `ask` tool's dialog: the model asks, the operator answers +ui.ask_title = the model asks +ui.ask_empty = (no suggested answers - type your answer and press Enter) +ui.ask_none = (no suggestion matches - Enter sends what you typed) +ui.ask_filter = answer: +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. diff --git a/share/locale/pt_BR.msg b/share/locale/pt_BR.msg index 3425203..13352eb 100644 --- a/share/locale/pt_BR.msg +++ b/share/locale/pt_BR.msg @@ -286,3 +286,13 @@ ui.agent_busy = um turno esta em andamento; troque de agente quando terminar # /learn: mine the sessions of this folder for what stays true learn.empty = (nenhuma sessao anterior nesta pasta - aprenda com esta conversa e diga o que guardaria.) + +# o dialogo da ferramenta `ask`: o modelo pergunta, o operador responde +ui.ask_title = o modelo pergunta +ui.ask_empty = (sem sugestoes - escreva a resposta e pressione Enter) +ui.ask_none = (nenhuma sugestao corresponde - Enter envia o que voce escreveu) +ui.ask_filter = resposta: +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. diff --git a/src/backend/engine.c b/src/backend/engine.c index d049166..dc0be3b 100644 --- a/src/backend/engine.c +++ b/src/backend/engine.c @@ -153,6 +153,18 @@ struct sp_engine { char approve_name[64]; char approve_args[256]; int approve_auth; + /* + * The question a tool is parked on (ask_operator). Same condition + * variable and the same "the thread parks, the front end answers" + * shape as the approval above, because a second wait mechanism would + * be a second place to get cancel and Ctrl-C wrong. What differs is + * the answer: free text (or a picked option) instead of yes/no. + */ + int ask_pending; + char ask_text[SP_ASK_MAX]; + char ask_answer[SP_ASK_MAX]; + size_t ask_nopts; + char ask_opts[SP_ASK_OPTIONS][SP_ASK_OPT_LEN]; /* the last turn, for the sidebar and /status */ size_t last_ms, last_steps, last_calls; @@ -314,6 +326,7 @@ sp_engine_state(struct sp_engine *e, struct sp_engine_state *st) st->busy = e->running || e->ext_busy; st->quit = e->quit; st->waiting = e->approve_pending; + st->asking = e->ask_pending; st->agents_n = (int)e->agents.n; st->agent_cur = e->agent_cur; pthread_mutex_unlock(&e->lock); @@ -1137,6 +1150,193 @@ sp_engine_approve(struct sp_engine *e, int allow) return pending; } +/* + * The `ask` tool: the model puts a question to the operator. The channel is + * the agent's `ask` callback, not a second event queue -- a tool that reaches + * around the front end would have to know about curses, sockets and the + * gateway, and the timeout would have to be written three times. + * + * The observation is the answer as text. When nobody answers, it says so + * plainly: a model that reads "nobody answered" can proceed or ask again, + * while an empty string reads as "the operator said nothing" and leads it to + * guess what was wanted. + */ +static int +tool_ask(const char *args, struct sp_buf *out, void *ctx) +{ + struct sp_agent *a = ctx; + mcp_json *v = mcp_parse(args); + char text[SP_ASK_MAX]; + char answer[SP_ASK_MAX]; + char opts[SP_ASK_OPTIONS][SP_ASK_OPT_LEN]; + const mcp_json *list; + size_t nopts = 0, i, n; + + answer[0] = '\0'; + text[0] = '\0'; + if (v == NULL) { + sp_buf_puts(out, "error: 'question' is required"); + return 0; + } + { + const char *q = mcp_arg_string(v, "question"); + + if (q == NULL || *q == '\0') + q = mcp_arg_string(v, "text"); + if (q != NULL) + snprintf(text, sizeof(text), "%s", q); + } + list = mcp_arg(v, "options"); + n = mcp_array_len(list); + for (i = 0; i < n && nopts < SP_ASK_OPTIONS; i++) { + const char *o = mcp_json_string(mcp_array_at(list, i)); + + if (o != NULL && *o != '\0') + snprintf(opts[nopts++], sizeof(opts[0]), "%s", o); + } + mcp_json_free(v); + if (text[0] == '\0') { + sp_buf_puts(out, "error: 'question' is required"); + return 0; + } + if (a->cfg->ask == NULL) { + /* + * Not a silent deny: in a run without a front end (--script, a + * gateway that only streams) the model gets told, so it falls + * back to stating the assumption instead of inventing one. + */ + sp_buf_puts(out, "nobody can be asked here: this run has no " + "operator attached. Decide yourself and state the " + "assumption in your answer."); + return 0; + } + if (a->cfg->ask(a->cfg->ask_ctx, text, (const char (*)[SP_ASK_OPT_LEN])opts, + nopts, answer, sizeof(answer)) != 0 || + answer[0] == '\0') { + sp_buf_puts(out, "no answer: the question was not answered " + "(the operator cancelled or did not respond). Proceed with " + "your best judgement and say what you assumed."); + return 0; + } + sp_buf_printf(out, "%s", answer); + return 0; +} +static int +engine_register_ask(struct sp_registry *r, struct sp_agent *a) +{ + struct sp_tool t; + + memset(&t, 0, sizeof(t)); + t.name = "ask"; + t.description = "Ask the operator a question and wait for the answer. " + "Use it when a decision is theirs: two designs that both work, a " + "name, which of several files. Do not use it to confirm what you " + "were already told, and do not use it to report progress. Give " + "'options' when the answer is one of a few (a dialog is shown, " + "typed words still count); leave it out for a free answer."; + t.params = "{\"type\":\"object\",\"properties\":{" + "\"question\":{\"type\":\"string\",\"description\":" + "\"the question, one or two sentences\"}," + "\"options\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}," + "\"description\":\"suggested answers, at most 8\"}}," + "\"required\":[\"question\"]}"; + /* + * Read, not mutate: it changes nothing on the machine, and a question + * that needs an approval first would be answered after the operator + * already read it. The authority is the operator themselves. + */ + t.auth = SP_AUTH_READ; + t.run = tool_ask; + t.ctx = a; + return sp_registry_add(r, &t); +} + +/* + * A tool asks the operator something. Same parking as the approval above: + * the turn thread waits on e->cond, the front end calls sp_engine_answer() + * from its own thread. The difference that matters is the failure mode -- + * a question that nobody can answer must not hang the turn, so the wait ends + * on cancel, on Ctrl-C (the cancel flag) and on a timeout, and each of those + * returns -1 so the tool can say "nobody answered" as its observation. + */ +static int +engine_ask(void *ctx, const char *text, const char (*opts)[SP_ASK_OPT_LEN], + size_t nopts, char *answer, size_t cap) +{ + struct sp_engine *e = ctx; + struct timespec deadline; + size_t i; + int rc; + + if (e == NULL || text == NULL || answer == NULL || cap == 0) + return -1; + pthread_mutex_lock(&e->lock); + snprintf(e->ask_text, sizeof(e->ask_text), "%s", text); + e->ask_nopts = nopts < SP_ASK_OPTIONS ? nopts : SP_ASK_OPTIONS; + /* opts may be NULL with nopts 0 (a question with no choices) */ + for (i = 0; opts != NULL && i < e->ask_nopts; i++) + snprintf(e->ask_opts[i], sizeof(e->ask_opts[i]), "%s", + opts[i]); + e->ask_answer[0] = '\0'; + e->ask_pending = 1; + pthread_mutex_unlock(&e->lock); + /* 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; + pthread_mutex_lock(&e->lock); + while (e->ask_pending && !e->cancel && + pthread_cond_timedwait(&e->cond, &e->lock, &deadline) == 0) + ; + e->ask_pending = 0; + rc = e->ask_answer[0] != '\0' && !e->cancel ? 0 : -1; + if (rc == 0) + snprintf(answer, cap, "%s", e->ask_answer); + pthread_mutex_unlock(&e->lock); + return rc; +} + +int +sp_engine_ask(struct sp_engine *e, char *text, size_t textlen, + char (*opts)[SP_ASK_OPT_LEN], size_t max, size_t *nopts) +{ + size_t i, n; + + if (e == NULL || text == NULL || textlen == 0) + return 0; + pthread_mutex_lock(&e->lock); + n = e->ask_nopts; + if (!e->ask_pending) { + pthread_mutex_unlock(&e->lock); + return 0; + } + snprintf(text, textlen, "%s", e->ask_text); + for (i = 0; opts != NULL && i < n && i < max; i++) + snprintf(opts[i], SP_ASK_OPT_LEN, "%s", e->ask_opts[i]); + if (nopts != NULL) + *nopts = n < max ? n : max; + pthread_mutex_unlock(&e->lock); + return 1; +} + +int +sp_engine_answer(struct sp_engine *e, const char *text) +{ + int pending; + + if (e == NULL) + return 0; + pthread_mutex_lock(&e->lock); + pending = e->ask_pending; + if (pending && text != NULL) { + snprintf(e->ask_answer, sizeof(e->ask_answer), "%s", text); + e->ask_pending = 0; + pthread_cond_broadcast(&e->cond); + } + pthread_mutex_unlock(&e->lock); + return pending; +} + int sp_engine_cancel(struct sp_engine *e) { @@ -1534,6 +1734,8 @@ engine_submit(struct sp_engine *e, const char *text) e->turn_cfg.stream_ctx = e; e->turn_cfg.approve = engine_approve; e->turn_cfg.approve_ctx = e; + e->turn_cfg.ask = engine_ask; + e->turn_cfg.ask_ctx = e; e->turn_cfg.tool_begin = engine_tool_begin; e->turn_cfg.tool_begin_ctx = e; e->turn_cfg.tool_end = engine_tool_end; @@ -1828,6 +2030,17 @@ sp_engine_prompt(struct sp_engine *e, const char *text, sp_stream_cb stream, cfg.stream = stream; cfg.stream_ctx = stream_ctx; } + /* + * 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. + */ + cfg.cancel = &e->cancel; e->ag.cfg = &cfg; rc = sp_agent_run(&e->ag, text, answer, err); e->ag.cfg = &e->base; @@ -3806,7 +4019,8 @@ sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o, if (sp_builtin_register(&e->reg, e->conf != NULL ? e->conf->tools_root : NULL) != 0 || - sp_skills_register(&e->reg, e->conf) != 0) { + sp_skills_register(&e->reg, e->conf) != 0 || + engine_register_ask(&e->reg, &e->ag) != 0) { /* * A tools_root that cannot be resolved is the one failure a * working setup hits here, so it is named: "cannot register" diff --git a/src/backend/mcpsession.c b/src/backend/mcpsession.c index 94bf6d9..ef55e6d 100644 --- a/src/backend/mcpsession.c +++ b/src/backend/mcpsession.c @@ -168,7 +168,12 @@ static const struct { "Answer a pending approval: allow true runs the tool, false denies it " "(the denial becomes the observation the model sees).", "{\"type\":\"object\",\"properties\":{\"allow\":{\"type\":\"boolean\"}}," - "\"required\":[\"allow\"]}" } + "\"required\":[\"allow\"]}" }, + { "splinter_answer", SP_AUTH_MUTATE, + "Answer the question the `ask` tool put to the operator: the text of " + "the answer. Use it when splinter_say returns \"the model asks\".", + "{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"," + "\"description\":\"the answer\"}},\"required\":[\"text\"]}" } }; int @@ -419,6 +424,26 @@ tool_say(const char *args, struct sp_buf *out) auth == SP_AUTH_MUTATE ? "mutate" : "read"); goto done; } + /* + * The model asked the operator something. This is the same + * 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). + */ + if (sp_engine_state(e, &st) == 0 && st.asking) { + char qt[SP_ASK_MAX]; + + if (sp_engine_ask(e, qt, sizeof(qt), NULL, 0, NULL)) + sp_buf_printf(out, "the model asks: %s\n" + "call splinter_answer {\"text\":\"...\"}\n", + qt); + else + sp_buf_puts(out, "the model asks a question " + "(it could not be read)\n" + "call splinter_answer {\"text\":\"...\"}\n"); + goto done; + } if (sp_mcp_stopping()) { /* the server is shutting down: do not hold it up */ (void)sp_engine_cancel(e); @@ -599,6 +624,24 @@ tool_approve(const char *args, struct sp_buf *out) return 0; } +static int +tool_answer(const char *args, struct sp_buf *out) +{ + char text[SP_ASK_MAX]; + + arg_string(args, "text", text, sizeof(text)); + if (text[0] == '\0') { + sp_buf_puts(out, "error: 'text' is required"); + return 0; + } + if (sp_engine_answer(*session_eng, text) == 0) { + sp_buf_puts(out, "error: no question is pending"); + return 0; + } + sp_buf_printf(out, "answered: %s\n", text); + return 0; +} + int sp_mcpsession_call(const char *name, const char *args, struct sp_buf *out) { @@ -630,5 +673,7 @@ sp_mcpsession_call(const char *name, const char *args, struct sp_buf *out) return tool_cancel(out), 1; if (strcmp(name, "splinter_approve") == 0) return tool_approve(args, out), 1; + if (strcmp(name, "splinter_answer") == 0) + return tool_answer(args, out), 1; return 0; } diff --git a/src/backend/telegram.c b/src/backend/telegram.c index 5fb5ead..005104e 100644 --- a/src/backend/telegram.c +++ b/src/backend/telegram.c @@ -69,6 +69,11 @@ static volatile int tg_stop; static int tg_curl(const char *url, const char *post_body, struct sp_buf *out, struct sp_buf *err); +/* defined further down; tg_ask() above them reads the chat while it waits */ +static int tg_callback(const char *token, const char *allow, + const mcp_json *cq, struct sp_agent *ag, struct sp_config *conf, + struct sp_host *host, const char *sess_dir); +static int tg_ack_reply(const char *token, long chat_id, const char *text); /* Telegram shows "typing" for about five seconds; a turn takes longer. */ struct typing { @@ -1066,6 +1071,112 @@ tg_note(void *ctx, const char *text) sp_buf_free(&err); } +/* + * The `ask` tool's question, in the chat the turn came from. + * + * Same shape as tg_approve: the turn is parked, so this function reads the + * chat itself until the operator answers. The difference is the answer -- free + * text, not yes/no -- so the reply is simply the next message from an allowed + * user, and an option is taken by sending its text (a keyboard would be a + * second way to answer one question). + * + * Without this the model was told "nobody can be asked here" while the + * operator sat in the chat: the engine sets the callback on its own turn + * config, and the gateway runs its turns on a copy of the base config. + */ +static int +tg_ask(void *ctx, const char *text, const char (*opts)[SP_ASK_OPT_LEN], + size_t nopts, char *answer, size_t cap) +{ + struct sp_buf msg, url, reply, err; + time_t end; + size_t i; + int got = -1; + + (void)ctx; + if (tg_cur.chat_id == 0 || text == NULL || answer == NULL || cap == 0) + return -1; + if (sp_buf_init(&msg) != 0 || sp_buf_init(&url) != 0 || + sp_buf_init(&reply) != 0 || sp_buf_init(&err) != 0) { + sp_buf_free(&msg); + sp_buf_free(&url); + sp_buf_free(&reply); + sp_buf_free(&err); + return -1; + } + sp_buf_printf(&msg, "%s\n\n%s", text, sp_td("ask.how", + "Answer with a message. /cancel cancels the turn.")); + for (i = 0; i < nopts; i++) { + sp_buf_puts(&msg, i == 0 ? "\n\n" : "\n"); + sp_buf_printf(&msg, "- %s", opts[i]); + } + (void)send_message(tg_cur.token, tg_cur.chat_id, msg.p, NULL); + + end = time(NULL) + SP_ASK_WAIT_S; + while (!tg_stop && time(NULL) < end) { + mcp_json *v; + const mcp_json *result, *update; + size_t k; + + 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 (k = 0; result != NULL && + (update = mcp_array_at(result, k)) != NULL; k++) { + const mcp_json *m, *cq; + long uid = tg_id(update, "update_id"); + const char *t; + long chat, from; + + if (uid < tg_offset) + continue; + tg_offset = uid + 1; + cq = mcp_arg(update, "callback_query"); + if (cq != NULL) { + /* a button from an approval; still not an answer */ + (void)tg_callback(tg_cur.token, tg_cur.allow, cq, + NULL, NULL, NULL, NULL); + continue; + } + m = mcp_arg(update, "message"); + if (m == NULL) + continue; + t = mcp_arg_string(m, "text"); + chat = tg_id(mcp_arg(m, "chat"), "id"); + from = tg_id(mcp_arg(m, "from"), "id"); + if (t == NULL || chat == 0 || !allowed(tg_cur.allow, from)) + continue; + /* + * A reply to some other approval is consumed by that + * one, not taken as this question's answer: "ok 7" is + * not an answer to "which colour?". + */ + if (tg_ack_reply(tg_cur.token, chat, t)) + continue; + snprintf(answer, cap, "%s", t); + got = 0; + break; + } + if (v != NULL) + mcp_json_free(v); + if (got == 0) + break; + } + sp_buf_free(&msg); + sp_buf_free(&url); + sp_buf_free(&reply); + sp_buf_free(&err); + return got; +} + /* * /interview: the model talks to the user, not a questionnaire. The system * prompt is swapped for the interview prompt and the conversation restarted; @@ -2215,6 +2326,16 @@ sp_telegram_run(struct sp_agent *ag, struct sp_host *host, const char *token, gcfg.approve_ctx = &tg_cur; gcfg.approve_is_channel = 1; } + /* + * The operator is in the chat, so `ask` must reach them there. + * Set from the base config, not from the turn config: the + * gateway runs its turns itself (sp_agent_run) and never goes + * through engine_submit(), which is what installs engine_ask. + */ + if (orig->ask == NULL) { + gcfg.ask = tg_ask; + gcfg.ask_ctx = &tg_cur; + } ag->cfg = &gcfg; } diff --git a/src/frontend/curses.c b/src/frontend/curses.c index 227c890..5a0d0d0 100644 --- a/src/frontend/curses.c +++ b/src/frontend/curses.c @@ -161,7 +161,8 @@ enum { PAIR_THINK, /* the model's reasoning */ PAIR_TOOL, /* a tool call */ PAIR_NOTICE, /* status and session notes */ - PAIR_SIDE /* sidebar: the theme's text on the theme's page */ + PAIR_SIDE, /* sidebar: the theme's text on the theme's page */ + PAIR_PICK /* the selected row of a picker */ }; /* the session id and directory the sidebar shows */ @@ -278,6 +279,14 @@ init_colors(const struct sp_theme *t) init_pair(PAIR_ACCENT, accent, t->idx_bg); init_pair(PAIR_DIM, dim, t->idx_bg); init_pair(PAIR_STATUS, t->idx_bg, t->idx_fg); + /* + * The picked row: the page colour on the accent colour, not the + * other way round. fg-on-accent read as "light grey on light + * blue" in the dark theme and the cursor was invisible; a + * terminal has 8 or 16 colours and the accent is the bright one, + * so the dark page colour belongs on top of it. + */ + init_pair(PAIR_PICK, t->idx_bg, t->idx_accent); init_pair(PAIR_INPUT, t->idx_fg, t->idx_bg); init_pair(PAIR_ERROR, errc, t->idx_bg); init_pair(PAIR_AGENT, agent, t->idx_bg); @@ -292,6 +301,7 @@ init_colors(const struct sp_theme *t) init_pair(PAIR_ACCENT, rgb(t->accent, n), rgb(t->bg, n)); init_pair(PAIR_DIM, rgb(t->border, n), rgb(t->bg, n)); init_pair(PAIR_STATUS, rgb(t->status_fg, n), rgb(t->status, n)); + init_pair(PAIR_PICK, rgb(t->bg, n), rgb(t->accent, n)); init_pair(PAIR_INPUT, rgb(t->input_fg, n), rgb(t->input_bg, n)); init_pair(PAIR_ERROR, rgb(t->error, n), rgb(t->bg, n)); init_pair(PAIR_AGENT, rgb(t->agent, n), rgb(t->bg, n)); @@ -2427,10 +2437,18 @@ struct pick_list { struct pick_text { const char *title; /* the window's title line */ + const char *note; /* optional text above the filter (the question) */ const char *empty; /* nothing in the list at all */ const char *none; /* nothing matches the filter */ const char *filter; /* label in front of the filter line */ const char *hint; /* the footer */ + /* + * Enter with nothing matching sends the typed line. True for the `ask` + * dialog, where the rows are suggestions and the answer is text; false + * for /model and /sessions, where a choice outside the list would be + * an instruction the backend cannot carry out. + */ + int free_text; }; static void @@ -2524,16 +2542,123 @@ pick_window(int *wp, int *hp) return win; } +/* + * Wrap `text` into `w` columns and count the rows, at most `maxrows`. The + * count is what the caller needs before drawing: the question above the filter + * pushes the list down, and a list drawn over the last line of the question is + * unreadable. Breaks at spaces, and inside a word that does not fit on a line + * of its own (a tool name, a path), so nothing is dropped. + * + * `out` may be NULL, and then only the row count comes back -- the scroller + * needs the same number the drawer computes, and must not have to keep a copy + * of the text to get it. + */ +static int +pick_wrap(const char *text, int w, int maxrows, char *out, size_t outcap) +{ + int rows = 0, col = 0; + size_t o = 0; + + if (w < 4) + w = 4; + if (out != NULL && outcap > 0) + out[0] = '\0'; + for (; text != NULL && *text != '\0' && rows < maxrows; text++) { + if (*text == '\n' || (col >= w && *text != ' ')) { + if (rows + 1 >= maxrows) { + /* no room left: mark the cut, do not lie */ + if (out != NULL && o + 4 < outcap) { + memcpy(out + o, "...", 3); + out[o += 3] = '\0'; + } + return rows + 1; + } + if (out != NULL) { + if (o + 2 < outcap) + out[o++] = '\n'; + out[o] = '\0'; + } + rows++; + col = 0; + if (*text == '\n') + continue; + } + if (out != NULL && o + 2 < outcap) { + out[o++] = *text; + out[o] = '\0'; + } + col++; + } + return rows + 1; +} + +/* the wrapped question, one row per '\n', starting at window row 1 */ +static void +pick_draw_note(WINDOW *win, const char *note, int w, int rows) +{ + /* + * Sized from the question, not from a round number: pick_wrap() drops + * what does not fit, and a 1024-byte question plus its wrap points is + * more than 1024 bytes. Sized here so the drawer never cuts a line the + * scroller counted. + */ + char wrapped[SP_ASK_MAX * 2]; + char *line, *save = NULL; + int row = 1; + + (void)pick_wrap(note, w, rows, wrapped, sizeof(wrapped)); + line = strtok_r(wrapped, "\n", &save); + wattrset(win, COLOR_PAIR(PAIR_MAIN) | A_BOLD); + for (; line != NULL && row < 1 + rows; line = strtok_r(NULL, "\n", + &save), row++) + mvwaddnstr(win, row, 2, line, w); + wattrset(win, COLOR_PAIR(PAIR_MAIN)); +} + +/* + * Where the rows start, and how many fit. The question above the filter takes + * rows away from the list, and the caller that scrolls has to know the same + * number the caller that draws uses -- when it did not, the highlighted row + * scrolled out of the window and the operator moved a cursor they could not + * see (the `ask` dialog with a three-line question). + */ +static int +pick_listtop(const struct pick_text *t, int w, int h) +{ + int noteh = 0, top; + + if (t->note != NULL && *t->note != '\0') + noteh = pick_wrap(t->note, w - 4, 3, NULL, 0); + top = noteh > 0 ? 2 + noteh : 2; + if (top > h - 1) + top = h - 1; + return top; +} + static void pick_draw(WINDOW *win, const struct pick_list *l, const size_t *match, size_t nmatch, size_t cur, size_t top, const char *filter, const struct pick_text *t) { - int h = getmaxy(win), w = getmaxx(win), listh = h - 4, y; + int h = getmaxy(win), w = getmaxx(win), y, listh; const char *label = t->filter != NULL ? t->filter : ""; int fw = 2 + (int)strlen(label) + 1; + int listtop, noteh, filtrow; char line[1100]; + /* + * A question is longer than one line and it is the part the operator + * has to read: wrap it over as many rows as it needs (at most three) + * and move the filter and the rows down. /model and /sessions pass no + * note and keep their layout. + */ + listtop = pick_listtop(t, w, h); + noteh = listtop - 2; + filtrow = noteh > 0 ? 1 + noteh : 1; + listh = h - 2 - listtop; + if (listh < 1) + listh = 1; + werase(win); /* * No box(): the vendored curses draws ACS corners as letters, so a @@ -2544,24 +2669,29 @@ pick_draw(WINDOW *win, const struct pick_list *l, const size_t *match, mvwhline(win, 0, 0, ' ', w); mvwaddnstr(win, 0, 1, t->title != NULL ? t->title : "", w - 2); wattrset(win, COLOR_PAIR(PAIR_MAIN)); - mvwaddnstr(win, 1, 2, label, w - 4); + if (noteh > 0) + pick_draw_note(win, t->note, w - 4, noteh); + mvwaddnstr(win, filtrow, 2, label, w - 4); if (fw < w - 2) - mvwaddnstr(win, 1, fw, filter, w - 2 - fw); + mvwaddnstr(win, filtrow, fw, filter, w - 2 - fw); if (l->n == 0) - mvwaddnstr(win, 3, 2, t->empty != NULL ? t->empty : "", w - 4); - else if (nmatch == 0) - mvwaddnstr(win, 3, 2, t->none != NULL ? t->none : "", w - 4); + mvwaddnstr(win, listtop, 2, t->empty != NULL ? t->empty : "", + w - 4); + else if (nmatch == 0 && !t->free_text) + mvwaddnstr(win, listtop, 2, t->none != NULL ? t->none : "", + w - 4); for (y = 0; y < listh; y++) { size_t pos = top + (size_t)y, idx; - int row = 2 + y; + int row = listtop + y; if (pos >= nmatch) break; idx = match[pos]; - snprintf(line, sizeof(line), "%s%s", + snprintf(line, sizeof(line), "%s%s%s", + pos == cur ? "> " : " ", l->v[idx].current ? "* " : " ", l->v[idx].label); if (pos == cur) { - wattrset(win, COLOR_PAIR(PAIR_STATUS)); + wattrset(win, COLOR_PAIR(PAIR_PICK) | A_BOLD); mvwhline(win, row, 1, ' ', w - 2); mvwaddnstr(win, row, 1, line, w - 2); wattrset(win, COLOR_PAIR(PAIR_MAIN)); @@ -2573,7 +2703,7 @@ pick_draw(WINDOW *win, const struct pick_list *l, const size_t *match, if (t->hint != NULL) mvwaddnstr(win, h - 2, 1, t->hint, w - 2); wattrset(win, COLOR_PAIR(PAIR_MAIN)); - wmove(win, 1, fw + (int)strlen(filter) < w - 1 ? + wmove(win, filtrow, fw + (int)strlen(filter) < w - 1 ? fw + (int)strlen(filter) : w - 2); wnoutrefresh(win); doupdate(); @@ -2651,7 +2781,10 @@ pick_run(struct pick_view *view, struct pick_list *list, nmatch = pick_match(list, filter, match); for (;;) { int changed = 0; - int listh = h - 4; + int listh = h - 2 - pick_listtop(t, w, h); + + if (listh < 1) + listh = 1; if (nmatch == 0) cur = 0; @@ -2664,14 +2797,28 @@ pick_run(struct pick_view *view, struct pick_list *list, werase(win); pick_draw(win, list, match, nmatch, cur, top, filter, t); c = ui_getkey(win, -1); - if (c == 27 || c == 3 || c == 4) + if (c == 27) break; + /* + * Ctrl-C and Ctrl-D leave the picker too, but as a cancel: the + * caller has to wake whatever parked on the choice (the `ask` + * tool waits for an answer), not leave it waiting. + */ + if (c == 3 || c == 4) { + rc = -2; + break; + } if (c == '\n' || c == '\r' || c == KEY_ENTER) { if (nmatch > 0) { snprintf(sel, cap, "%s", list->v[match[cur]].sel); rc = 0; break; } + if (t->free_text && flen > 0) { + snprintf(sel, cap, "%s", filter); + rc = 0; + break; + } continue; } if (c == KEY_RESIZE) { @@ -3734,6 +3881,65 @@ turn_paint(struct ui_state *s, struct turn_view *v) turn_draw_input(s, v); } +/* + * The `ask` tool put a question to the operator. Same park/wake as the approval + * above, but the answer is text: the options are rows in the picker and a + * typed line is the answer too. A question that arrives while the operator is + * not looking must not hang the turn for its full timeout, so Esc and Ctrl-C + * answer with nothing and the tool reports "no answer". + */ +static void +turn_ask(struct ui_state *s) +{ + char text[SP_ASK_MAX]; + char opts[SP_ASK_OPTIONS][SP_ASK_OPT_LEN]; + char sel[SP_ASK_MAX]; + struct pick_list list; + struct pick_text t; + struct pick_view view; + size_t i, n = 0; + int rc; + + if (s->be->ask == NULL || s->be->answer == NULL) + return; + if (!s->be->ask(s->be->ctx, text, sizeof(text), opts, + SP_ASK_OPTIONS, &n)) + return; + memset(&list, 0, sizeof(list)); + memset(&t, 0, sizeof(t)); + for (i = 0; i < n; i++) + pick_add(&list, opts[i], opts[i], 0); + t.title = sp_t("ui.ask_title"); + t.note = text; + t.empty = sp_t("ui.ask_empty"); + t.none = sp_t("ui.ask_none"); + t.filter = sp_t("ui.ask_filter"); + t.hint = sp_t("ui.ask_hint"); + t.free_text = 1; + memset(&view, 0, sizeof(view)); + if (pick_view_open(&view) != 0) { + /* + * 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 + * one the tool reports as "no answer". + */ + (void)s->be->answer(s->be->ctx, ""); + return; + } + /* + * The answer is whatever Enter took: a row's option, or the typed line + * when nothing matched. -2 is the operator's cancel and is sent as an + * empty answer, which the tool reports as "no answer". + */ + memset(sel, 0, sizeof(sel)); + rc = pick_run(&view, &list, &t, NULL, NULL, NULL, NULL, NULL, sel, + sizeof(sel)); + pick_view_close(&view); + (void)s->be->answer(s->be->ctx, rc == 0 ? sel : ""); + (void)rc; +} + /* * A tool needs permission. The engine parked the turn; the question goes where * the prompt is, and y/N answers it. It names the call the way the transcript @@ -3994,7 +4200,8 @@ ui_turn(struct ui_state *s, const char *text) s->turn_running = 1; s->turn_ms = 0; for (;;) { - int c; + int c; + char probe[SP_ASK_MAX]; drain_events(s, &v); if (!s->be->busy(s->be->ctx)) @@ -4002,6 +4209,18 @@ ui_turn(struct ui_state *s, const char *text) c = ui_getkey(ui_input, 100); if (c == UK_NONE) continue; + /* + * A question is drawn in its own window and edits its own line; + * the key that woke the loop is not an answer to it. Asking + * before the approval keeps both channels apart: a turn that + * parks on `ask` has no approval open. + */ + if (s->be->ask != NULL && s->be->ask(s->be->ctx, probe, + sizeof(probe), NULL, 0, NULL)) { + turn_ask(s); + turn_paint(s, &v); + continue; + } if (turn_approval(s, c)) continue; if (c == ERR) { diff --git a/src/frontend/protocol.c b/src/frontend/protocol.c index bf276ee..d7128ac 100644 --- a/src/frontend/protocol.c +++ b/src/frontend/protocol.c @@ -197,6 +197,7 @@ send_state(struct client *c, struct sp_engine *eng, const char *name) ev_num(&b, "last_calls", (long)st.last_calls); ev_bool(&b, "busy", st.busy); ev_bool(&b, "waiting", st.waiting); + ev_bool(&b, "asking", st.asking); ev_bool(&b, "quit", st.quit); sp_buf_puts(&b, ",\"agents\":["); for (i = 0; i < st.agents_n; i++) { @@ -279,6 +280,38 @@ send_event(struct client *c, struct sp_engine *eng, const struct sp_event *ev) "destructive"); break; } + case SP_EV_ASK: { + char opts[SP_ASK_OPTIONS][SP_ASK_OPT_LEN]; + char q[SP_ASK_MAX]; + size_t i, n = 0; + + /* + * The question and its options in one event: the client draws the + * dialog from it and answers with {"cmd":"answer"}. Sending the + * options as a second event would leave a client that polls + * between them drawing a dialog with no choices. + * + * q starts empty: the engine can already have taken the pending + * question down (a cancel raced the event), and sp_engine_ask() + * then writes nothing. Reading the buffer anyway sent whatever + * was on the stack to the client. + */ + q[0] = '\0'; + (void)sp_engine_ask(eng, q, sizeof(q), opts, SP_ASK_OPTIONS, + &n); + ev_start(&b, "ask"); + ev_str(&b, "text", ev->a != NULL ? ev->a : q); + sp_buf_puts(&b, ",\"options\":["); + for (i = 0; i < n; i++) { + if (i > 0) + sp_buf_puts(&b, ","); + sp_buf_puts(&b, "\""); + (void)sp_json_escape(&b, opts[i]); + sp_buf_puts(&b, "\""); + } + sp_buf_puts(&b, "]"); + break; + } case SP_EV_TURN_END: ev_start(&b, "turn"); ev_bool(&b, "ok", ev->n == 0); @@ -806,6 +839,9 @@ handle_line(struct client *c, struct proto *p, const char *line) } } else if (strcmp(cmd, "approve") == 0) { (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 : ""); } else if (strcmp(cmd, "cancel") == 0) { (void)sp_engine_cancel(eng); } else if (strcmp(cmd, "steer") == 0) { diff --git a/src/frontend/ui_backend.h b/src/frontend/ui_backend.h index cd92ea3..1e82b73 100644 --- a/src/frontend/ui_backend.h +++ b/src/frontend/ui_backend.h @@ -47,6 +47,14 @@ struct ui_backend { int (*approval)(void *ctx, char *name, size_t namelen, int *auth, char *args, size_t argslen); int (*approve)(void *ctx, int allow); + /* + * The question the `ask` tool is parked on: the text and its options, + * and the answer the front end gives back. A backend without a dialog + * asks the same text as a line; the answer is free text either way. + */ + int (*ask)(void *ctx, char *text, size_t textlen, + char (*opts)[SP_ASK_OPT_LEN], size_t max, size_t *nopts); + int (*answer)(void *ctx, const char *text); /* the event queue */ int (*poll)(void *ctx, struct sp_event *out); diff --git a/src/frontend/ui_local.c b/src/frontend/ui_local.c index e7a5b81..95c66b8 100644 --- a/src/frontend/ui_local.c +++ b/src/frontend/ui_local.c @@ -74,6 +74,17 @@ static int loc_approve(void *ctx, int allow) return sp_engine_approve(ENG(ctx), allow); } +static int loc_ask(void *ctx, char *text, size_t textlen, + char (*opts)[SP_ASK_OPT_LEN], size_t max, size_t *nopts) +{ + return sp_engine_ask(ENG(ctx), text, textlen, opts, max, nopts); +} + +static int loc_answer(void *ctx, const char *text) +{ + return sp_engine_answer(ENG(ctx), text); +} + static int loc_poll(void *ctx, struct sp_event *out) { return sp_engine_poll(ENG(ctx), out); @@ -280,6 +291,8 @@ static const struct ui_backend local = { .take_steer = loc_take_steer, .approval = loc_approval, .approve = loc_approve, + .ask = loc_ask, + .answer = loc_answer, .poll = loc_poll, .event_free = loc_event_free, .state = loc_state, diff --git a/src/frontend/ui_remote.c b/src/frontend/ui_remote.c index eb72d69..cc2d677 100644 --- a/src/frontend/ui_remote.c +++ b/src/frontend/ui_remote.c @@ -87,6 +87,11 @@ struct rem { int pending; /* an approval question is open */ char a_name[64], a_args[256]; int a_auth; + /* the `ask` tool's question: text, options, and the answer to send back */ + int asking; + char q_text[SP_ASK_MAX]; + char q_opts[SP_ASK_OPTIONS][SP_ASK_OPT_LEN]; + size_t q_nopts; int presubmitted; /* input started the turn already */ int proto; /* the server's protocol version */ long tag; /* the last request tag this client sent */ @@ -317,6 +322,7 @@ fill_state(struct rem *r, const mcp_json *v) r->st.last_calls = (size_t)mcp_arg_int(v, "last_calls", 0); r->st.busy = mcp_arg_bool(v, "busy", 0); r->st.waiting = mcp_arg_bool(v, "waiting", 0); + r->st.asking = mcp_arg_bool(v, "asking", 0); r->st.quit = mcp_arg_bool(v, "quit", 0); r->st.agent_cur = mcp_arg_int(v, "agent_cur", 0); if ((s = mcp_arg_string(v, "session")) != NULL) @@ -528,6 +534,20 @@ dispatch(struct rem *r, const char *line) mcp_arg_string(v, "args") != NULL ? mcp_arg_string(v, "args") : ""); q_push(r, SP_EV_APPROVAL, r->a_auth, r->a_name, r->a_args); + } else if (strcmp(ev, "ask") == 0) { + const mcp_json *items = mcp_arg(v, "options"); + size_t i, n = items != NULL ? mcp_array_len(items) : 0; + const char *txt = mcp_arg_string(v, "text"); + + r->asking = 1; + snprintf(r->q_text, sizeof(r->q_text), "%s", + txt != NULL ? txt : ""); + r->q_nopts = 0; + for (i = 0; i < n && r->q_nopts < SP_ASK_OPTIONS; i++) + snprintf(r->q_opts[r->q_nopts++], SP_ASK_OPT_LEN, "%s", + mcp_json_string(mcp_array_at(items, i)) != NULL ? + mcp_json_string(mcp_array_at(items, i)) : ""); + q_push(r, SP_EV_ASK, (long)r->q_nopts, r->q_text, NULL); } else if (strcmp(ev, "turn") == 0) { q_push(r, SP_EV_TURN_END, mcp_arg_int(v, "rc", 1), mcp_arg_string(v, "answer"), mcp_arg_string(v, "error")); @@ -679,6 +699,38 @@ rem_approve(void *ctx, int allow) return rc == 0; } +static int +rem_ask(void *ctx, char *text, size_t textlen, char (*opts)[SP_ASK_OPT_LEN], + size_t max, size_t *nopts) +{ + struct rem *r = ctx; + size_t i, n; + + if (!r->asking) + return 0; + if (text != NULL && textlen > 0) + snprintf(text, textlen, "%s", r->q_text); + n = r->q_nopts < max ? r->q_nopts : max; + for (i = 0; opts != NULL && i < n; i++) + snprintf(opts[i], SP_ASK_OPT_LEN, "%s", r->q_opts[i]); + if (nopts != NULL) + *nopts = n; + return 1; +} + +static int +rem_answer(void *ctx, const char *text) +{ + struct rem *r = ctx; + + if (!r->asking) + return 0; + r->asking = 0; + if (r->fd < 0) + return 0; + return send_cmd(r, "answer", "text", text != NULL ? text : "") == 0; +} + static int rem_poll(void *ctx, struct sp_event *out) { @@ -1310,6 +1362,8 @@ sp_ui_backend_remote(const char *socket_path, struct sp_buf *err) be.steer = rem_steer; be.approval = rem_approval; be.approve = rem_approve; + be.ask = rem_ask; + be.answer = rem_answer; be.poll = rem_poll; be.event_free = rem_event_free; be.state = rem_state; diff --git a/tests/fake_openai_ask.py b/tests/fake_openai_ask.py new file mode 100644 index 0000000..79130d0 --- /dev/null +++ b/tests/fake_openai_ask.py @@ -0,0 +1,39 @@ +# fake OpenAI endpoint: the first request of a turn asks the operator a question +# with the `ask` tool, the next one answers with what came back. +# argv: port, options (comma separated, may be empty) +import http.server, json, sys + + +def ev(d): + return ("data: " + json.dumps(d) + "\n\n").encode() + + +OPTS = [o for o in (sys.argv[2].split(",") if len(sys.argv) > 2 else []) if o] + + +class H(http.server.BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + n = int(self.headers.get("Content-Length", 0)) + req = json.loads(self.rfile.read(n)) + last = req["messages"][-1] + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + w = self.wfile.write + if last["role"] == "tool": + w(ev({"choices": [{"delta": {"content": + "answer was: " + str(last.get("content", ""))}}]})) + else: + args = {"question": "Which colour should the login page be?"} + if OPTS: + args["options"] = OPTS + w(ev({"choices": [{"delta": {"tool_calls": [{"index": 0, + "id": "c1", "type": "function", "function": { + "name": "ask", "arguments": json.dumps(args)}}]}}]})) + w(b"data: [DONE]\n\n") + + +http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever() diff --git a/tests/fake_telegram.py b/tests/fake_telegram.py index fcb800e..2077526 100644 --- a/tests/fake_telegram.py +++ b/tests/fake_telegram.py @@ -143,6 +143,11 @@ class H(http.server.BaseHTTPRequestHandler): m = re.match(r"Frage (\d+)/", text) if m: add_update("antwort-%s" % m.group(1)) + # the `ask` tool: the question arrives with its answer hint. Match + # on the question, not on the hint -- the hint is translated and + # this fake runs under SPLINTER_LOCALE=de in the gateway test. + if "Which colour should the login page be?" in text: + add_update(ANSWER) m = re.match(r"Zustimmung (\d+):", text) if m: add_update("was machst du?") # must be told to wait @@ -206,6 +211,22 @@ class H(http.server.BaseHTTPRequestHandler): answer = "".join("Zeile %03d\n" % i for i in range(1, 121)) chunks = [{"choices": [{"delta": {"content": answer}}]}, {"choices": [{"delta": {}, "finish_reason": "stop"}]}] + elif "frag den operator" in last_user: + # the `ask` tool: a question with options on the first request, + # then the answer the tool returned is echoed back as the answer + if has_tool: + last = [m for m in req.get("messages", []) + if m.get("role") == "tool"] + got = last[-1].get("content", "") if last else "" + answer = "antwort war: " + str(got) + chunks = [{"choices": [{"delta": {"content": answer}}]}, + {"choices": [{"delta": {}, "finish_reason": "stop"}]}] + else: + chunks = [{"choices": [{"delta": {"tool_calls": [{ + "index": 0, "id": "c1", "type": "function", + "function": {"name": "ask", "arguments": json.dumps({ + "question": "Which colour should the login page be?", + "options": ["green", "blue"]})}}]}}]}] elif "bild" in last_user: answer = "Hier:\n\n![Ein Bild](https://example.org/b.png)\n\nEnde\n" chunks = [{"choices": [{"delta": {"content": answer}}]}, diff --git a/tests/sh/port.sh b/tests/sh/port.sh index 6ce39b7..325dddd 100644 --- a/tests/sh/port.sh +++ b/tests/sh/port.sh @@ -25,17 +25,100 @@ s = socket.socket(); s.bind(("127.0.0.1", 0)) print(s.getsockname()[1]); s.close()' } +# Several ports at once, for a test that runs more than one server: asking +# twice is not enough, because the kernel hands out the same port again as +# soon as the first socket is closed. One socket per port, all bound before +# any is released, so the numbers are distinct - and then the caller gets them +# space separated, e.g. `set -- $(free_ports 3); P0=$1 P1=$2 P2=$3`. +free_ports() { + python3 -c 'import socket, sys +n = int(sys.argv[1]) +ss = [] +for _ in range(n): + s = socket.socket(); s.bind(("127.0.0.1", 0)); ss.append(s) +print(" ".join(str(s.getsockname()[1]) for s in ss)) +for s in ss: s.close()' "$1" +} + # $1 = port, $2 = pid of the server we started. -# 0 when that process is alive AND accepting connections. +# 0 when that process is alive AND its own socket accepts on that port. +# +# "Curl answered" is not enough on its own: when a fake dies on a port that +# another program already holds (Address already in use), something answers +# there and the test goes on against a server that knows nothing about it. +# Checking the pid catches most of it, but not the window before the fake has +# exited - so the answer has to come from a socket this pid owns. wait_listen() { _p="$1" _pid="$2" _i=0 while [ "$_i" -lt 100 ]; do kill -0 "$_pid" 2>/dev/null || return 1 - curl -s -o /dev/null "http://127.0.0.1:$_p/x" && return 0 + if curl -s -o /dev/null "http://127.0.0.1:$_p/x" && + listener_is "$_p" "$_pid"; then + return 0 + fi sleep 0.2 _i=$((_i + 1)) done return 1 } + +# $1 = port, $2 = pid of the server we started. +# 0 when that process is alive AND holds the LISTEN socket on that port. +# +# The same contract as wait_listen, for a server that is not HTTP: probing it +# with curl would hang or time out on a protocol that never answers an HTTP +# request, so only the socket is tried here. The ownership check is what makes +# this more than "somebody is listening" - a server that died on a taken port +# leaves a stranger on it, and that stranger must not pass for ours. +wait_tcp() { + _p="$1" + _pid="$2" + _i=0 + while [ "$_i" -lt 100 ]; do + kill -0 "$_pid" 2>/dev/null || return 1 + if _tcp_open "$_p" && listener_is "$_p" "$_pid"; then + return 0 + fi + sleep 0.1 + _i=$((_i + 1)) + done + return 1 +} + +_tcp_open() { + python3 - "$1" <<'PY' 2>/dev/null +import socket, sys +s = socket.socket() +s.settimeout(0.2) +try: + s.connect(("127.0.0.1", int(sys.argv[1]))) +except OSError: + sys.exit(1) +finally: + s.close() +PY +} + +# Does process $2 own the LISTEN socket on port $1? Reads /proc, so it is Linux +# only; when it cannot tell (no /proc/net/tcp, an IPv6-only listener) it says +# "yes" and the weaker check stands - a test must not hang on a helper. +listener_is() { + _lport="$1" + _lpid="$2" + _ino=$(awk -v want="$(printf '%04X' "$_lport")" ' + NR > 1 && $4 == "0A" { + split($2, a, ":") + if (a[2] == want) { print $10; exit } + }' /proc/net/tcp 2>/dev/null) + if [ -z "$_ino" ]; then + return 0 + fi + for _fd in /proc/"$_lpid"/fd/*; do + case "$(readlink "$_fd" 2>/dev/null)" in + "socket:[$_ino]") return 0 ;; + esac + done + return 1 +} diff --git a/tests/test_a2a_context.sh b/tests/test_a2a_context.sh index 4a2d419..31bacdf 100755 --- a/tests/test_a2a_context.sh +++ b/tests/test_a2a_context.sh @@ -7,9 +7,13 @@ # that id also reaches 2. set -u cd "$(dirname "$0")/.." || exit 1 +. "$(dirname "$0")/sh/port.sh" D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-a2a-ctx-XXXXXX") || exit 1 -P0=$((20000 + ($$ % 20000))) -P1=$((P0 + 1)) +# Two servers, so two ports out of one call: asking twice returns the same +# number (see free_ports). +set -- $(free_ports 2) +P0=$1 +P1=$2 F0= F1= cleanup() { @@ -22,13 +26,6 @@ mkdir -p "$D/home" fails=0 check() { if "$@"; then :; else echo "FAIL $*"; fails=$((fails + 1)); fi; } -wait_port() { - for i in $(seq 1 50); do - curl -s -o /dev/null "http://127.0.0.1:$1/" && return 0 - sleep 0.2 - done - return 1 -} send() { # send ctx=$1 if [ -n "$ctx" ]; then @@ -48,13 +45,13 @@ context_of() { python3 -I tests/fake_openai_count.py "$P0" & F0=$! -check wait_port "$P0" +check wait_listen "$P0" "$F0" HOME="$D/home" ./splinter --no-config --endpoint \ "http://127.0.0.1:$P0/v1/chat/completions" --model m \ --a2a-server-listen 127.0.0.1 --a2a-listen-port "$P1" \ >"$D/out" 2>"$D/err" & F1=$! -check wait_port "$P1" +check wait_listen "$P1" "$F1" r=$(send "ctx-multi" "eins") check test "$(answer "$r")" = "users=1" diff --git a/tests/test_ask_mcp.sh b/tests/test_ask_mcp.sh new file mode 100755 index 0000000..48c02ae --- /dev/null +++ b/tests/test_ask_mcp.sh @@ -0,0 +1,113 @@ +#!/bin/sh +# The `ask` tool over MCP: the question comes back, the answer resumes the turn. +# +# What it guards: `splinter_say` used to park for the engine's full ask wait +# (900 s) when the model asked a question -- the MCP client timed out at 15 s +# and the answer could never be delivered, so the turn was lost. The check is +# that `say` RETURNS with the question, and that `splinter_answer` then makes +# the turn finish with the answer the operator gave. A test that only checked +# "the tool is listed" would have passed while that hang was in the code. +set -u +cd "$(dirname "$0")/.." || exit 1 +. tests/sh/port.sh +SP=${SPLINTER:-./splinter} +D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-askmcp-XXXXXX") || exit 1 +set -- $(free_ports 2) +P=$1 +M=$2 +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 +HOME=$D/home $SP --no-config --autonomous --model m \ + --endpoint "http://127.0.0.1:$P/v1/chat/completions" \ + --mcp-server-listen 127.0.0.1 --mcp-listen-port "$M" \ + > "$D/srv.out" 2>&1 & +S=$! +if ! wait_tcp "$M" "$S"; then + echo "FAIL the MCP server did not start" + cat "$D/srv.out" + exit 1 +fi + +python3 - "$M" "$D" <<'PY' || fail=$((fail + 1)) +import json, socket, sys, time + +port, d = int(sys.argv[1]), sys.argv[2] +s = socket.create_connection(("127.0.0.1", port), 5) +# the client's own timeout is the point: a park longer than this is the bug +s.settimeout(15) +f = s.makefile("rw", encoding="utf-8") + +def req(i, method, params=None): + o = {"jsonrpc": "2.0", "id": i, "method": method} + if params is not None: + o["params"] = params + f.write(json.dumps(o) + "\n"); f.flush() + return json.loads(f.readline()) + +def call(i, name, args): + r = req(i, "tools/call", {"name": name, "arguments": args}) + if "error" in r: + print("error:", r["error"], file=sys.stderr); sys.exit(1) + return r["result"]["content"][0]["text"] + +def out(line): + with open(d + "/result", "a") as fh: + fh.write(line + "\n") + +req(1, "initialize", {}) +t0 = time.time() +say = call(2, "splinter_say", {"text": "which colour"}) +took = time.time() - t0 +out("ask_returned %s" % ("yes" if "the model asks" in say else "no")) +out("ask_fast %s" % ("yes" if took < 10 else "no")) +out("ask_has_question %s" % ("yes" if "colour" in say else "no")) +out("ask_names_answer_tool %s" % ("yes" if "splinter_answer" in say else "no")) + +ans = call(3, "splinter_answer", {"text": "blue"}) +out("answer_ok %s" % ("yes" if "answered" in ans else "no")) + +# the turn must finish on its own now; poll instead of sleeping a fixed time +done = False +for i in range(4, 40): + time.sleep(0.5) + if "busy: no" in call(i, "splinter_state", {}): + done = True + break +out("turn_finished %s" % ("yes" if done else "no")) + +# a second answer with nothing pending is an error, not a silent accept +stray = call(90, "splinter_answer", {"text": "red"}) +out("stray_refused %s" % ("yes" if "no question is pending" in stray else "no")) +PY + +while read -r key val; do + case $key in + ask_returned) check 'say returns with the question instead of parking' '[ "$val" = yes ]' ;; + ask_fast) check 'say returns in seconds, not at the engine timeout' '[ "$val" = yes ]' ;; + ask_has_question) check 'the question text reaches the client' '[ "$val" = yes ]' ;; + ask_names_answer_tool) check 'the reply names splinter_answer' '[ "$val" = yes ]' ;; + answer_ok) check 'splinter_answer is accepted' '[ "$val" = yes ]' ;; + turn_finished) check 'the turn finishes once it is answered' '[ "$val" = yes ]' ;; + stray_refused) check 'an answer with no question pending is refused' '[ "$val" = yes ]' ;; + esac +done < "$D/result" 2>/dev/null +# the client died before it wrote anything (a park longer than its timeout): +# that is the failure, and it must not be read as "no check failed" +[ -s "$D/result" ] || { echo "FAIL the client got no answer at all"; fail=$((fail + 1)); } + +[ "$fail" -eq 0 ] || { echo "--- server log ---"; cat "$D/srv.out"; exit 1; } +echo "test_ask_mcp: ok" diff --git a/tests/test_ask_ui.sh b/tests/test_ask_ui.sh new file mode 100755 index 0000000..28d731a --- /dev/null +++ b/tests/test_ask_ui.sh @@ -0,0 +1,95 @@ +#!/bin/sh +# splinter -- the `ask` tool's dialog on the screen. +# +# What it guards: the model asks a question and the turn PARKED. The whole +# point of the tool is that the answer is the operator's, so the test checks +# both shapes -- an option taken from the list, and a line typed that matches +# no option -- and that the answer really reaches the model, because a dialog +# that draws and then answers nothing is the bug this test exists for. +# +# The fake endpoint asks once and then echoes what the tool returned. +set -u +cd "$(dirname "$0")/.." || exit 1 +. tests/sh/port.sh +SP=${SPLINTER:-./splinter} +D=$(mktemp -d "${TMPDIR:-/tmp}/uia-XXXXXX") || exit 1 +S=uia-$$ +# Our own tmux server: $TMUX wins over -L and TMUX_TMPDIR, so a run started +# inside the user's tmux would drive the user's server and the kill at the end +# would take every session in it down (see tests/test_ui.sh). +unset TMUX TMUX_PANE +TMUX_TMPDIR="$D" +export TMUX_TMPDIR +trap 'tmux kill-server 2>/dev/null; [ -n "${F:-}" ] && kill $F 2>/dev/null; rm -rf "$D"' EXIT + +P=$(free_port) +python3 tests/fake_openai_ask.py "$P" "green,blue,red" > "$D/fake.out" 2>&1 & +F=$! +wait_listen "$P" "$F" || { echo "FAIL fake did not start"; cat "$D/fake.out"; exit 1; } + +mkdir -p "$D/home" +tmux new-session -d -s $S -x 100 -y 32 "HOME=$D/home SPLINTER_LOCALE=en \ + SPLINTER_SESSION_DIR=$D/home/.splinter $SP --no-config \ + --endpoint http://127.0.0.1:$P/v1/chat/completions --model m --chat" || exit 1 +# the ready entry is drawn before the input line owns the keyboard +for i in $(seq 1 40); do + tmux capture-pane -t $S -p | grep -q 'Enter sends' && break + sleep 0.3 +done + +fail=0 +check() { # $1 = what, then grep patterns + _w=$1; shift + for _p in "$@"; do + if ! tmux capture-pane -t $S -p | grep -qF -- "$_p"; then + echo "FAIL $_w: no '$_p'" + sed -n '1,32p' /dev/null + fail=1 + fi + done +} +check_shows() { check "$1" "$2"; } + +typed() { sleep 0.4; tmux send-keys -t $S -l "$1"; } +key() { tmux send-keys -t $S "$@"; } + +sleep 2 +typed 'farbe'; key Enter +# the question and its options must be on the screen +for i in $(seq 1 30); do + tmux capture-pane -t $S -p | grep -qF 'Which colour' && break + sleep 0.3 +done +check 'dialog shows the question' 'Which colour should the login page be?' +check 'dialog shows an option' 'green' +check 'dialog shows the title' 'the model asks' +check 'dialog shows a hint' 'Enter' + +# pick the second row +key Down; sleep 0.2; key Enter +for i in $(seq 1 40); do + tmux capture-pane -t $S -p | grep -qF 'answer was:' && break + sleep 0.3 +done +check 'the picked option reached the model' 'answer was: blue' + +# the second turn: type an answer that is no option +typed 'nochmal'; key Enter +for i in $(seq 1 30); do + tmux capture-pane -t $S -p | grep -qF 'Which colour' && break + sleep 0.3 +done +typed 'purple' +sleep 0.3 +key Enter +for i in $(seq 1 40); do + tmux capture-pane -t $S -p | grep -qF 'answer was: purple' && break + sleep 0.3 +done +check 'the typed answer reached the model' 'answer was: purple' + +key C-u C-d +sleep 0.5 +[ "$fail" -eq 0 ] && echo "test_ask_ui: ok" +[ -n "${VERBOSE:-}" ] && tmux capture-pane -t $S -p | tail -32 +[ "$fail" -eq 0 ] || { tmux capture-pane -t $S -p | tail -32; exit 1; } diff --git a/tests/test_gateway.sh b/tests/test_gateway.sh index 6b2e7b1..bf65eff 100755 --- a/tests/test_gateway.sh +++ b/tests/test_gateway.sh @@ -8,34 +8,12 @@ # a fake Bot API and a fake model, once with "ok" and once with "no". set -u cd "$(dirname "$0")/.." || exit 1 +. "$(dirname "$0")/sh/port.sh" D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-gw-XXXXXX") || exit 1 SPLINTER_SESSION_DIR="$D/home/.splinter"; export SPLINTER_SESSION_DIR trap 'rm -rf "$D"' EXIT fails=0 -wait_fake() { # $1 = port, $2 = pid; 0 when THAT process accepts a connection - # - # Check the pid first. Without it a port that some other program already - # holds looks like a fake that started: curl answers, the test goes on, - # and the failures show up far from the cause. Seen on 2026-11-21 with - # dtsession (the CDE desktop) holding 36343, a port the old formula - # picked; twenty-odd gateway checks failed for it. - for i in $(seq 1 100); do - kill -0 "$2" 2>/dev/null || return 1 - curl -s -o /dev/null "http://127.0.0.1:$1/x" && return 0 - sleep 0.2 - done - return 1 -} - -# A port this process can really bind. The old formula, 20000 + $$ % 30000, -# is a guess and collided with whatever else the machine runs. -free_port() { - python3 -c 'import socket -s = socket.socket(); s.bind(("127.0.0.1", 0)) -print(s.getsockname()[1]); s.close()' -} - run() { # $1 = answer word; leaves $D/sent.log and maybe $D/out.txt P=$(free_port) rm -rf "$D/home" "$D/out.txt" "$D/sent.log" @@ -47,7 +25,7 @@ run() { # $1 = answer word; leaves $D/sent.log and maybe $D/out.txt python3 -I tests/fake_telegram.py "$P" "$D/out.txt" "$D/sent.log" "$1" \ > "$D/fake.out" 2>&1 & S=$! - if ! wait_fake "$P" "$S"; then + if ! wait_listen "$P" "$S"; then echo "FAIL fake telegram did not start on $P" cat "$D/fake.out" 2>/dev/null fails=$((fails + 1)) @@ -106,7 +84,7 @@ run_text() { # $1 = first message, $2 = line to wait for, $3 = port offset, python3 -I tests/fake_telegram.py "$P" "$D/out.txt" "$D/sent.log" ok "$1" \ > "$D/fake.out" 2>&1 & S=$! - if ! wait_fake "$P" "$S"; then + if ! wait_listen "$P" "$S"; then echo "FAIL fake telegram did not start on $P" cat "$D/fake.out" 2>/dev/null fails=$((fails + 1)) @@ -243,6 +221,20 @@ check "the summary is in USER.txt" grep -q 'mag C99' "$D/home/.splinter/USER.txt check "the marker is not in USER.txt" \ sh -c "! grep -q INTERVIEW_COMPLETE '$D/home/.splinter/USER.txt'" +# the `ask` tool reaches the operator in the chat, and the reply is the +# observation: the gateway runs its turns on a copy of the base config, so a +# callback set only on the engine's turn config never arrived here and the +# model was told "nobody can be asked" while the operator sat in the chat. +run_text "frag den operator" 'antwort war: ok' 105 +check "the question reaches the chat" \ + grep -q 'Which colour should the login page be?' "$D/sent.log" +check "the question carries its options" \ + grep -q -- '- green' "$D/sent.log" +check "the operator's answer reaches the model" \ + grep -q '^antwort war: ok' "$D/sent.log" +check "the model is not told nobody is there" \ + sh -c "! grep -q 'nobody can be asked' '$D/sent.log'" + # The model sends a tool call with arguments that are not JSON. The turn # corrects it and asks again - and the operator must see that in the chat: # the engine's note callback wrote to a screen queue that a gateway never @@ -255,7 +247,7 @@ printf 'endpoint = http://127.0.0.1:%s/v1/chat/completions\nmodel = m\ntelegram_ python3 -I tests/fake_telegram.py "$P" "$D/out.txt" "$D/sent.log" ok "kaputt" \ > "$D/fake.out" 2>&1 & S=$! -if ! wait_fake "$P" "$S"; then +if ! wait_listen "$P" "$S"; then echo "FAIL fake telegram did not start on $P" fails=$((fails + 1)) else diff --git a/tests/test_gateway_openai.sh b/tests/test_gateway_openai.sh index 70db2e1..131752c 100755 --- a/tests/test_gateway_openai.sh +++ b/tests/test_gateway_openai.sh @@ -9,14 +9,17 @@ # can ask for SSE; and beyond loopback the server refuses without a token. set -u cd "$(dirname "$0")/.." || exit 1 +. "$(dirname "$0")/sh/port.sh" D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-gw-XXXXXX") || exit 1 -P0=$((20000 + $$ % 8000)) -PF=$P0 -P1=$((P0 + 70)) -P2=$((P0 + 71)) -P3=$((P0 + 72)) -P4=$((P0 + 73)) -P5=$((P0 + 74)) +# One upstream fake and five gateways: six ports out of one call, all bound +# before any is released, so no two can come back the same (see free_ports). +set -- $(free_ports 6) +PF=$1 +P1=$2 +P2=$3 +P3=$4 +P4=$5 +P5=$6 F= G1= G2= @@ -41,15 +44,6 @@ checkgrep() { # pattern file fails=$((fails + 1)) fi } -wait_port() { # port, tries - i=0 - while [ "$i" -lt "$2" ]; do - curl -s -o /dev/null "http://127.0.0.1:$1/v1/models" && return 0 - i=$((i + 1)) - sleep 0.3 - done - return 1 -} post() { # port, body, out curl -s -X POST "http://127.0.0.1:$1/v1/chat/completions" \ -H 'Content-Type: application/json' -d "$2" > "$3" @@ -60,7 +54,11 @@ printf 'inhalt-von-gw-read\n' > "$D/read.txt" python3 -I tests/fake_gateway.py "$PF" "$D/read.txt" "$D/written.txt" \ > "$D/fake.log" 2>&1 & F=$! -sleep 0.8 +if ! wait_listen "$PF" "$F"; then + echo "FAIL the upstream fake never listened" + cat "$D/fake.log" + exit 1 +fi HOME=$D/h1 SPLINTER_LOCALE=en ./splinter --no-config --autonomous \ --endpoint "http://127.0.0.1:$PF/v1" --model up \ @@ -77,7 +75,7 @@ HOME=$D/h3 SPLINTER_LOCALE=en SPLINTER_GATEWAY_TOKEN=geheim ./splinter \ --openai-listen 127.0.0.1 --openai-listen-port "$P3" \ > "$D/g3.log" 2>&1 & G3=$! -if ! wait_port "$P1" 40 || ! wait_port "$P2" 40; then +if ! wait_listen "$P1" "$G1" || ! wait_listen "$P2" "$G2"; then echo "FAIL a gateway did not start" cat "$D/g1.log" "$D/g2.log" exit 1 @@ -195,7 +193,7 @@ HOME=$D/h5 SPLINTER_LOCALE=en SPLINTER_GATEWAY_READ_TIMEOUT=2 ./splinter \ --openai-listen 127.0.0.1 --openai-listen-port "$P5" \ > "$D/g5.log" 2>&1 & G4=$! -if ! wait_port "$P5" 40; then +if ! wait_listen "$P5" "$G4"; then echo "FAIL the timeout gateway did not start" cat "$D/g5.log" fails=$((fails + 1)) diff --git a/tests/test_interview.sh b/tests/test_interview.sh index 1fa8518..a6317aa 100755 --- a/tests/test_interview.sh +++ b/tests/test_interview.sh @@ -8,7 +8,8 @@ set -u cd "$(dirname "$0")/.." || exit 1 D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-iv-XXXXXX") || exit 1 SPLINTER_SESSION_DIR="$D/home/.splinter"; export SPLINTER_SESSION_DIR -port=18992 +. "$(dirname "$0")/sh/port.sh" +port=$(free_port) srv= cleanup() { [ -n "$srv" ] && kill "$srv" 2>/dev/null; rm -rf "$D"; } trap cleanup EXIT INT TERM @@ -25,9 +26,10 @@ check "the summary is in USER.txt" grep -q 'likes C99' "$D/home/.splinter/USER.t check "the marker is not in USER.txt" sh -c "! grep -q INTERVIEW_COMPLETE '$D/home/.splinter/USER.txt'" # the next run's request must carry USER.txt in the system prompt -python3 - "$D/req.json" <<'PY' & +python3 - "$D/req.json" "$port" <<'PY' & import http.server, sys out = sys.argv[1] +port = int(sys.argv[2]) class H(http.server.BaseHTTPRequestHandler): def log_message(self, *a): pass @@ -40,26 +42,13 @@ class H(http.server.BaseHTTPRequestHandler): self.send_header("Content-Length", str(len(b))) self.end_headers() self.wfile.write(b) -http.server.ThreadingHTTPServer(("127.0.0.1", 18992), H).serve_forever() +http.server.ThreadingHTTPServer(("127.0.0.1", port), H).serve_forever() PY srv=$! -i=0 -while [ $i -lt 50 ]; do - if python3 - "$port" <<'PY' -import socket, sys -s = socket.socket(); s.settimeout(0.2) -try: - s.connect(("127.0.0.1", int(sys.argv[1]))) -except OSError: - sys.exit(1) -finally: - s.close() -PY - then - break - fi - i=$((i + 1)); sleep 0.1 -done +if ! wait_listen "$port" "$srv"; then + echo "FAIL the fake endpoint did not start on $port" + exit 1 +fi HOME="$D/home" ./splinter --no-config --model m \ --endpoint "http://127.0.0.1:$port/v1/chat/completions" \ diff --git a/tests/test_junction.sh b/tests/test_junction.sh index 4a1f196..92e8591 100644 --- a/tests/test_junction.sh +++ b/tests/test_junction.sh @@ -7,31 +7,19 @@ set -e cd "$(dirname "$0")/.." -port=${JUNCTION_TEST_PORT:-18099} +. "$(dirname "$0")/sh/port.sh" + +port=${JUNCTION_TEST_PORT:-$(free_port)} python3 tests/fake_junction.py "$port" & pid=$! trap 'kill $pid 2>/dev/null || true' EXIT INT TERM -# wait for the port, not for a fixed sleep: a loaded machine starts python late -i=0 -while [ $i -lt 50 ]; do - if python3 - "$port" <<'EOF' -import socket, sys -s = socket.socket() -s.settimeout(0.2) -try: - s.connect(("127.0.0.1", int(sys.argv[1]))) - sys.exit(0) -except OSError: - sys.exit(1) -finally: - s.close() -EOF - then - break - fi - i=$((i + 1)) - sleep 0.1 -done +# The helper proves that *our* fake owns the listening socket, not just that +# something answers: a port another program holds used to make this test talk +# to a stranger that knows nothing about junction. +if ! wait_listen "$port" "$pid"; then + echo "test_junction: the fake junction did not start on $port" + exit 1 +fi ./tests/test_junction "$port" diff --git a/tests/test_mcpsession.sh b/tests/test_mcpsession.sh index 76ebe36..28248c5 100755 --- a/tests/test_mcpsession.sh +++ b/tests/test_mcpsession.sh @@ -7,8 +7,10 @@ set -e cd "$(dirname "$0")/.." +. "$(dirname "$0")/sh/port.sh" + D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-mcps-XXXXXX") || exit 1 -port=$((21000 + ($$ % 20000))) +port=$(free_port) pid= cleanup() { [ -n "$pid" ] && kill "$pid" 2>/dev/null; rm -rf "$D"; } trap cleanup EXIT INT TERM @@ -20,23 +22,13 @@ HOME=$D/home ./splinter --no-config --autonomous --model m \ --mcp-listen-port "$port" > "$D/srv.out" 2>&1 & pid=$! -i=0 -while [ $i -lt 50 ]; do - if python3 - "$port" <<'PY' -import socket, sys -s = socket.socket(); s.settimeout(0.2) -try: - s.connect(("127.0.0.1", int(sys.argv[1]))) -except OSError: - sys.exit(1) -finally: - s.close() -PY - then - break - fi - i=$((i + 1)); sleep 0.1 -done +# the helper proves our own server owns the socket, so a port another program +# holds cannot make the checks below talk to a stranger +if ! wait_tcp "$port" "$pid"; then + echo "test_mcpsession: the MCP server did not start on $port" + cat "$D/srv.out" + exit 1 +fi python3 - "$port" <<'PY' import json, socket, sys @@ -64,7 +56,7 @@ assert init["result"]["serverInfo"]["name"] == "splinter", init tools = [t["name"] for t in req(2, "tools/list")["result"]["tools"]] for want in ("splinter_sessions", "splinter_state", "splinter_models", "splinter_history", "splinter_say", "splinter_steer", - "splinter_cancel", "splinter_approve"): + "splinter_cancel", "splinter_approve", "splinter_answer"): assert want in tools, (want, tools) state = call(3, "splinter_state", {}) diff --git a/tests/test_pools.sh b/tests/test_pools.sh index 8a06158..19160eb 100644 --- a/tests/test_pools.sh +++ b/tests/test_pools.sh @@ -6,8 +6,12 @@ # the second answers. The run must end up on the second without waiting. set -u cd "$(dirname "$0")/.." || exit 1 +. "$(dirname "$0")/sh/port.sh" D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-pool-XXXXXX") || exit 1 -PA=$((20000 + $$ % 20000)); PB=$((PA + 1)) +# Two fakes: one call, both bound before either is released (see free_ports). +set -- $(free_ports 2) +PA=$1 +PB=$2 trap 'kill $FA $FB 2>/dev/null; rm -rf "$D"' EXIT fails=0 check() { d=$1; shift; if "$@"; then :; else echo "FAIL $d"; fails=$((fails + 1)); fi; } @@ -18,12 +22,8 @@ FA=$! python3 -I tests/fake_openai_limit.py "$PB" "$D/b.log" & FB=$! # B refuses its first request too: make it answer at once by priming it -for p in $PA $PB; do - for i in $(seq 1 50); do - curl -s -o /dev/null "http://127.0.0.1:$p/x" && break - sleep 0.2 - done -done +if ! wait_listen "$PA" "$FA"; then echo "FAIL the first fake never listened"; exit 1; fi +if ! wait_listen "$PB" "$FB"; then echo "FAIL the second fake never listened"; exit 1; fi curl -s -o /dev/null -X POST -d '{}' "http://127.0.0.1:$PB/prime" cat > "$D/home/splinter.conf" < "$D/fake.out" 2>&1 & F1=$! -sleep 0.8 +if ! wait_listen "$P1" "$F1"; then + echo "FAIL the first fake never listened" + cat "$D/fake.out" + exit 1 +fi HOME=$D/home SPLINTER_LOCALE=en ./splinter --no-config --autonomous \ --endpoint "http://127.0.0.1:$P1/v1/chat/completions" --model m \ --serve --socket "$D/sock" > "$D/serve.out" 2>&1 & @@ -330,7 +338,11 @@ mkdir -p "$D/home2" python3 -I tests/fake_telegram.py "$P2" "$D/denied.txt" "$D/sent2.log" ok \ > "$D/fake2.out" 2>&1 & F2=$! -sleep 0.8 +if ! wait_listen "$P2" "$F2"; then + echo "FAIL the second fake never listened" + cat "$D/fake2.out" + exit 1 +fi HOME=$D/home2 SPLINTER_LOCALE=en ./splinter --no-config \ --endpoint "http://127.0.0.1:$P2/v1/chat/completions" --model m \ --serve --socket "$D/sock2" > "$D/serve2.out" 2>&1 &