From a1794fb1015da7245744785c776b3d8b6efc7877 Mon Sep 17 00:00:00 2001 From: lotherk Date: Wed, 18 Nov 2026 21:54:04 +0000 Subject: [PATCH] engine: /self-check, and tool arguments must be one JSON object /self-check (and /selfcheck) takes the last three turns of the conversation, every failed tool result in them and the last turn's error, and starts a turn with them: something went wrong, check yourself instead of asking the operator, name the cause and continue. Messages are capped per message and in total, oldest dropped first; it is refused mid-turn like /compact and is in the completion list. mcp_parse() stops at the closing brace, so a tool-call argument string holding two objects parsed as the first one and the second command disappeared without a word -- measured in sess-1795032073, where "cat a" ran and "cat b" was silently dropped. mcp_parse_exact() requires the whole text to be the one value; the agent's tool-argument validation uses it, so such a reply is retried and then fails with "model sent malformed tool arguments" instead of running half the command. test_engine drives both spellings and the included turn; test_agent drives the joined-argument reply (three requests, zero tool calls). test_engine and test_agent pass; the build is -Wall -Wextra -Werror clean. --- README.md | 6 ++ share/locale/de.msg | 2 + share/locale/en.msg | 2 + share/locale/pt_BR.msg | 2 + src/backend/agent.c | 13 ++-- src/backend/engine.c | 156 ++++++++++++++++++++++++++++++++++++++++- tests/test_agent.c | 62 ++++++++++++++++ tests/test_engine.c | 16 +++++ vendor/libmcp/mcp.h | 29 ++++++++ 9 files changed, 281 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index d89eabe..aee1345 100644 --- a/README.md +++ b/README.md @@ -438,6 +438,12 @@ session's `.meta`, so a resumed session finds it; `/continue` starts the next turn from it. `/goal` alone shows it. There is no separate `/recap`: recapping is what a goal does. Both work in the TUI and with `-p`. +`/self-check` is the one to type when a turn went nowhere: it hands the model +the last three turns it ran, every failed tool result in them and the last +turn's error, with the instruction to find its own mistake and continue. It +takes no arguments and runs as an ordinary turn, so it works in the TUI, with +`-p` and over the socket. + ## Languages UI strings live in `share/locale/.msg`, plain `key = text` files read at diff --git a/share/locale/de.msg b/share/locale/de.msg index 84efcdb..3ef4708 100644 --- a/share/locale/de.msg +++ b/share/locale/de.msg @@ -58,6 +58,8 @@ focus.goal_prompt = Ziel: %s. Arbeite darauf hin. Wenn das Ziel vollstaendig err focus.reminder = Recap zum Merken: %s. Pruefe vor der Antwort, ob der letzte Schritt naeher am Ziel war; wenn nicht, sage das und nenne den naechsten Schritt. Wenn das Ziel vollstaendig erreicht ist, beende deine letzte Antwort mit der einen Zeile GOAL_COMPLETE. focus.recap_prompt = Ziel: %s. Schreibe einen kurzen Recap zum Merken: 3-5 Punkte, was am Ende stimmen muss, die ersten konkreten Schritte und offene Fragen. Wenn das Ziel vollstaendig erreicht ist, beende deine letzte Antwort mit der einen Zeile GOAL_COMPLETE. focus.continue_prompt = Arbeite an diesem Ziel weiter: %s. Mach dort weiter, wo die Sitzung aufgehoert hat: pruefe den Stand, tue den naechsten konkreten Schritt und berichte, was sich geaendert hat. Wenn das Ziel vollstaendig erreicht ist, beende deine letzte Antwort mit der einen Zeile GOAL_COMPLETE. +selfcheck.prompt = In dieser Sitzung ist etwas schiefgelaufen. Pruefe dich selbst, statt den Operator zu fragen: lies den Schluss unseres Gespraechs unten (Werkzeugausgaben sind gekuerzt), finde den Schritt, der fehlgeschlagen ist, nenne die Ursache, was du falsch gemacht hast und was du jetzt anders machst. Arbeite danach die Aufgabe dort weiter, wo sie stehen geblieben ist. Wiederhole keine Arbeit, die noch gueltig ist. +selfcheck.empty = (noch keine Turns - es gibt nichts zu pruefen, also fang die Aufgabe an.) focus.set = Ziel gesetzt: %s focus.none = kein Ziel gesetzt (/goal ) focus.status = Ziel: %s (%u Recaps, alle %u Turns) diff --git a/share/locale/en.msg b/share/locale/en.msg index 2bfd21d..2405f0f 100644 --- a/share/locale/en.msg +++ b/share/locale/en.msg @@ -57,6 +57,8 @@ focus.goal_prompt = Goal: %s. Work toward it. When the goal is fully achieved, e focus.reminder = Recap to remember: %s. Before answering, check whether the last step moved closer to the goal; if not, say so and name the next step. When the goal is fully achieved, end your final answer with the single line GOAL_COMPLETE. focus.recap_prompt = Goal: %s. Write a short recap to remember: 3-5 bullets, what must be true at the end, the first concrete steps, and open questions. When the goal is fully achieved, end your final answer with the single line GOAL_COMPLETE. focus.continue_prompt = Continue working toward this goal: %s. Pick up where the session stopped: check the current state, do the next concrete step, and report what changed. When the goal is fully achieved, end your final answer with the single line GOAL_COMPLETE. +selfcheck.prompt = Something went wrong in this session, so check yourself instead of asking the operator: read the tail of our conversation below (tool output is shortened), find the step that failed, say what the cause was, what you got wrong, and what you will do differently now. Then continue the task from where it stopped. Do not repeat work that is still valid. +selfcheck.empty = (no turns yet - there is nothing to check, so start the task.) focus.set = goal set: %s focus.none = no goal set (/goal ) focus.status = goal: %s (%u recaps, every %u turns) diff --git a/share/locale/pt_BR.msg b/share/locale/pt_BR.msg index 1224dfc..070fc67 100644 --- a/share/locale/pt_BR.msg +++ b/share/locale/pt_BR.msg @@ -73,6 +73,8 @@ focus.goal_prompt = Objetivo: %s. Trabalhe nisso. Quando o objetivo estiver tota focus.reminder = Recap para lembrar: %s. Antes de responder, verifique se o ultimo passo aproximou do objetivo; se nao, diga isso e proponha o proximo passo. Quando o objetivo estiver totalmente alcancado, termine sua resposta final com a linha unica GOAL_COMPLETE. focus.recap_prompt = Objetivo: %s. Escreva um recap curto para lembrar: 3-5 pontos, o que precisa estar certo no final, os primeiros passos concretos e as perguntas abertas. Quando o objetivo estiver totalmente alcancado, termine sua resposta final com a linha unica GOAL_COMPLETE. focus.continue_prompt = Continue trabalhando neste objetivo: %s. Retome de onde a sessao parou: verifique o estado, faca o proximo passo concreto e relate o que mudou. Quando o objetivo estiver totalmente alcancado, termine sua resposta final com a linha unica GOAL_COMPLETE. +selfcheck.prompt = Algo deu errado nesta sessao, entao verifique voce mesmo em vez de perguntar ao operador: leia o final da nossa conversa abaixo (a saida das ferramentas esta encurtada), encontre o passo que falhou, diga qual foi a causa, o que voce errou e o que vai fazer diferente agora. Depois continue a tarefa de onde ela parou. Nao repita trabalho que ainda e valido. +selfcheck.empty = (ainda sem turnos - nao ha nada para verificar, entao comece a tarefa.) focus.set = objetivo definido: %s focus.none = nenhum objetivo definido (/goal ) focus.status = objetivo: %s (%u recaps, a cada %u turnos) diff --git a/src/backend/agent.c b/src/backend/agent.c index b228c60..93ab14f 100644 --- a/src/backend/agent.c +++ b/src/backend/agent.c @@ -613,10 +613,13 @@ agent_request(struct sp_agent *a, struct sp_conv *conv, struct sp_reply *reply, } /* - * Tool arguments that start with an object must be valid JSON. A bare string - * is the mock/script shape and stays allowed. One model step with "{command:" - * reached the endpoint as an assistant tool_call and made every endpoint - * answer 500; validation happens before that message enters the conversation. + * Tool arguments that start with an object must be valid JSON, and the whole + * string must be that one object. A bare string is the mock/script shape and + * stays allowed. One model step with "{command:" reached the endpoint as an + * assistant tool_call and made every endpoint answer 500; another sent two + * objects in one string and mcp_parse() quietly took the first, so half the + * work vanished. Validation happens before that message enters the + * conversation. */ static int tool_args_valid(const struct sp_reply *r, size_t *bad) @@ -629,7 +632,7 @@ tool_args_valid(const struct sp_reply *r, size_t *bad) if (args == NULL || args[0] == '\0' || args[0] != '{') continue; - v = mcp_parse(args); + v = mcp_parse_exact(args); if (v == NULL) { if (bad != NULL) *bad = i; diff --git a/src/backend/engine.c b/src/backend/engine.c index aed6782..19cd053 100644 --- a/src/backend/engine.c +++ b/src/backend/engine.c @@ -1726,7 +1726,7 @@ sp_engine_command_names(struct sp_engine *e, char (*names)[64], int max) { static const char *builtin[] = { "agent", "agents", "compact", "connect", "continue", "cost", "exit", "model", - "new", "q", "quit", "rename", "reset", "resume", "rm", "status", + "new", "q", "quit", "rename", "reset", "resume", "rm", "self-check", "status", "swarm", "usage", "widgets" }; struct sp_buf b; @@ -2354,6 +2354,154 @@ cmd_cost(struct sp_engine *e, struct sp_buf *out) "reported tokens are measurable\n"); } +/* ------------------------------------------------------------ /self-check */ + +/* + * A turn is everything from one user message to the next. The last three are + * the surprising ones: what was asked, what the model did, and the observation + * that came back -- including the failure it then talked around. + */ +#define SELF_CHECK_TURNS 3 +#define SELF_CHECK_MSG_BYTES 1200 /* per message; the log has the rest */ +#define SELF_CHECK_TOTAL 24000 /* the whole dump, so the prompt stays sane */ +#define SELF_CHECK_FAIL_BYTES 400 + +static int +self_check_is(const struct sp_msg *m, const char *role) +{ + return m->role != NULL && strcmp(m->role, role) == 0; +} + +/* a tool result that says it failed: exit status, or an error line */ +static int +self_check_failure(const struct sp_msg *m) +{ + const char *p, *e; + long status; + + if (!self_check_is(m, "tool") || m->content == NULL) + return 0; + p = strstr(m->content, "[exit status "); + if (p != NULL) { + e = p + 13; + status = strtol(e, NULL, 10); + if (status != 0 && (e[0] == '-' || (e[0] >= '0' && e[0] <= '9'))) + return 1; + } + return strncmp(m->content, "error:", 6) == 0 || + strstr(m->content, "\nerror:") != NULL || + strstr(m->content, "\nno answer") != NULL; +} + +/* + * One message as the model will read it here: the role, the tool name, the + * text cut to a size that still shows what happened. System messages (the + * prompt and lcm's summary) are not part of a turn. + */ +static void +self_check_line(struct sp_buf *b, const struct sp_msg *m, size_t cap) +{ + const char *text = m->content != NULL ? m->content : ""; + size_t len = strlen(text); + + if (m->name != NULL && m->name[0] != '\0') + sp_buf_printf(b, "[%s %s] ", + m->role != NULL ? m->role : "?", m->name); + else + sp_buf_printf(b, "[%s] ", m->role != NULL ? m->role : "?"); + if (len > cap) { + sp_buf_printf(b, "%.*s\n... %zu bytes cut ...", + (int)cap, text, len - cap); + } else { + sp_buf_puts(b, text); + } + sp_buf_puts(b, "\n"); +} + +/* the index where the last 'turns' user messages begin (0: fewer than that) */ +static size_t +self_check_from(const struct sp_conv *c, size_t turns) +{ + size_t i, seen = 0, first = c->n; + + for (i = c->n; i > 0; i--) { + if (!self_check_is(&c->v[i - 1], "user")) + continue; + first = i - 1; + if (++seen == turns) + break; + } + return first; +} + +/* + * /self-check: hand the model the tail of its own conversation and the errors + * in it, so it diagnoses itself instead of asking the operator. It runs as a + * real turn, so the model can go and repair the step it got wrong. + */ +static int +cmd_self_check(struct sp_engine *e, struct sp_buf *out) +{ + struct sp_buf body, fail; + size_t from, i, cut; + + sp_buf_clear(out); + if (sp_buf_init(&body) != 0 || sp_buf_init(&fail) != 0) { + sp_buf_free(&body); + sp_buf_free(&fail); + return SP_INPUT_HANDLED; + } + from = self_check_from(&e->conv, SELF_CHECK_TURNS); + for (i = from; i < e->conv.n; i++) { + if (self_check_is(&e->conv.v[i], "system")) + continue; + self_check_line(&body, &e->conv.v[i], SELF_CHECK_MSG_BYTES); + if (self_check_failure(&e->conv.v[i])) + self_check_line(&fail, &e->conv.v[i], + SELF_CHECK_FAIL_BYTES); + } + sp_buf_puts(out, sp_td("selfcheck.prompt", + "Something went wrong in this session, so check yourself instead " + "of asking the operator: read the tail of our conversation below " + "(tool output is shortened), find the step that failed, say what " + "the cause was, what you got wrong, and what you will do " + "differently now. Then continue the task from where it stopped. " + "Do not repeat work that is still valid.")); + sp_buf_puts(out, "\n"); + if (e->err.p != NULL && e->err.len > 0) { + sp_buf_puts(out, "\nlast turn failed with: "); + sp_buf_puts(out, e->err.p); + sp_buf_puts(out, "\n"); + } + if (fail.len > 0) { + sp_buf_puts(out, "\nfailures in those turns:\n"); + sp_buf_puts(out, fail.p); + } + if (body.len == 0) { + sp_buf_puts(out, "\n"); + sp_buf_puts(out, sp_t("selfcheck.empty")); + } else { + sp_buf_puts(out, "\nthe last turns, as they entered the " + "conversation:\n"); + if (body.len > SELF_CHECK_TOTAL) { + /* keep the newest part, starting on a line */ + cut = body.len - SELF_CHECK_TOTAL; + while (cut < body.len && body.p[cut] != '\n') + cut++; + if (cut < body.len) + cut++; + sp_buf_printf(out, "... %zu bytes of older turns cut " + "...\n", cut); + sp_buf_puts(out, body.p + cut); + } else { + sp_buf_puts(out, body.p); + } + } + sp_buf_free(&body); + sp_buf_free(&fail); + return SP_INPUT_PROMPT; +} + int sp_engine_input(struct sp_engine *e, const char *line, struct sp_buf *out) { @@ -2398,7 +2546,9 @@ sp_engine_input(struct sp_engine *e, const char *line, struct sp_buf *out) if (sp_engine_busy(e) && (strcmp(name, "new") == 0 || strcmp(name, "reset") == 0 || strcmp(name, "compact") == 0 || strcmp(name, "agent") == 0 || - strcmp(name, "agents") == 0 || strcmp(name, "connect") == 0)) { + strcmp(name, "agents") == 0 || strcmp(name, "connect") == 0 || + strcmp(name, "self-check") == 0 || + strcmp(name, "selfcheck") == 0)) { sp_buf_puts(out, sp_t("ui.command_busy")); return SP_INPUT_HANDLED; } @@ -2542,6 +2692,8 @@ sp_engine_input(struct sp_engine *e, const char *line, struct sp_buf *out) sp_buf_free(&confirm); } } + if (strcmp(name, "self-check") == 0 || strcmp(name, "selfcheck") == 0) + return cmd_self_check(e, out); if (e->host != NULL && sp_host_command(e->host, name, args, out) == 0) return SP_INPUT_HANDLED; /* diff --git a/tests/test_agent.c b/tests/test_agent.c index 5634321..23d6b6e 100644 --- a/tests/test_agent.c +++ b/tests/test_agent.c @@ -114,6 +114,39 @@ bad_args_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, out->calls[0].args != NULL && out->calls_json != NULL ? 0 : -1; } +/* + * The shape that cost a whole command in a real session: two argument objects + * in one string. mcp_parse() stops at the first closing brace, so the second + * command was silently dropped; the model must be told instead. + */ +static int joined_args_calls; +static int +joined_args_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out, + struct sp_buf *err) +{ + (void)ctx; + (void)conv; + (void)err; + joined_args_calls++; + memset(out, 0, sizeof(*out)); + out->status = 200; + out->content = strdup(""); + out->ncalls = 1; + out->calls = calloc(1, sizeof(*out->calls)); + if (out->content == NULL || out->calls == NULL) + return -1; + out->calls[0].id = strdup("c1"); + out->calls[0].name = strdup("echo"); + out->calls[0].args = strdup( + "{\"command\":\"echo one\"}{\"command\":\"echo two\"}"); + out->calls_json = strdup("[{\"id\":\"c1\",\"type\":\"function\"," + "\"function\":{\"name\":\"echo\",\"arguments\":" + "\"{\\\"command\\\":\\\"echo one\\\"}" + "{\\\"command\\\":\\\"echo two\\\"}\"}}]"); + return out->calls[0].id != NULL && out->calls[0].name != NULL && + out->calls[0].args != NULL && out->calls_json != NULL ? 0 : -1; +} + static char note_text[256]; static int note_seen; @@ -385,6 +418,35 @@ main(void) sp_conv_free(a.conv); } + /* + * Two argument objects in one string are not a tool call either: the + * first would run and the second vanish without a word. Reject the + * reply and let the model send one call at a time. + */ + { + struct sp_agent a; + struct sp_agent_config cfg; + struct sp_transport tr; + + memset(&a, 0, sizeof(a)); + memset(&cfg, 0, sizeof(cfg)); + memset(&tr, 0, sizeof(tr)); + cfg.max_steps = 8; + cfg.autonomous = 1; + tr.send = joined_args_send; + a.reg = &r; + a.cfg = &cfg; + a.tr = tr; + joined_args_calls = 0; + sp_buf_clear(&answer); + sp_buf_clear(&err); + CHECK(sp_agent_run(&a, "joined args", &answer, &err) != 0); + CHECK(strstr(err.p, "malformed tool arguments") != NULL); + CHECK(joined_args_calls == 3); + CHECK(a.stats.tool_calls == 0); + sp_conv_free(a.conv); + } + sp_buf_free(&answer); sp_buf_free(&err); sp_registry_free(&r); diff --git a/tests/test_engine.c b/tests/test_engine.c index 1057c07..3a67aa0 100644 --- a/tests/test_engine.c +++ b/tests/test_engine.c @@ -254,6 +254,22 @@ main(void) CHECK(contains(out.p, "Ship the config file")); sp_buf_clear(&out); + /* + * /self-check hands the model its own tail: the turns it ran and the + * observations that failed, with the framing that tells it to debug + * itself. Both spellings are commands; the hyphen is the real one. + */ + kind = sp_engine_input(eng, "/self-check", &out); + CHECK(kind == SP_INPUT_PROMPT); + CHECK(contains(out.p, "check yourself")); + CHECK(contains(out.p, "sag hallo")); + CHECK(contains(out.p, "the last turns")); + sp_buf_clear(&out); + kind = sp_engine_input(eng, "/selfcheck", &out); + CHECK(kind == SP_INPUT_PROMPT); + CHECK(contains(out.p, "check yourself")); + sp_buf_clear(&out); + /* * /new drops the conversation, not the way of working: the active * profile's prompt goes back on top, and the new session gets an id of diff --git a/vendor/libmcp/mcp.h b/vendor/libmcp/mcp.h index 75dad25..a90c238 100644 --- a/vendor/libmcp/mcp.h +++ b/vendor/libmcp/mcp.h @@ -131,6 +131,9 @@ void mcp_json_escape(mcp_buf *b, const char *s); /* Parse a complete JSON document. Returns NULL on error. Free with * mcp_json_free(). A backend that stores its own state as JSON needs this. */ mcp_json *mcp_parse(const char *text); +/* The whole text must be that one value: trailing bytes are an error. Use it + * where the text comes from a model, not from a document. */ +mcp_json *mcp_parse_exact(const char *text); void mcp_json_free(mcp_json *v); /* Handle one JSON-RPC line and return the reply as a malloc'd string, or NULL @@ -673,6 +676,32 @@ mcp_json *mcp_parse(const char *text) return v; } +/* + * Like mcp_parse, but the whole text must be the one value. mcp_parse stops at + * the closing brace and ignores what follows, so two argument objects in one + * string parse as the first one and the rest disappears: a model that emitted + * '{"command":"a"}{"command":"b"}' ran only a, silently. Callers that read a + * model's tool arguments want this one. + */ +mcp_json *mcp_parse_exact(const char *text) +{ + mcp_json *v = NULL; + const char *end; + + if (text == NULL) + return NULL; + end = jparse(text, &v); + if (end == NULL) { + jfree(v); + return NULL; + } + if (*skip_ws(end) != '\0') { + jfree(v); + return NULL; + } + return v; +} + void mcp_json_free(mcp_json *v) { jfree(v);