Files
splinter/plugins/focus/focus.c
T
lotherk 36a66ab4f0 self monitor, MCP session tools, junction serving endpoint
- plugins/self: what the session costs the machine - RSS, CPU, threads, fds
  and io of the process itself from /proc/self/*, and the same (count, RSS,
  CPU) for every process whose parent chain reaches it: run calls, MCP
  children, delegates. Widget, /self and the session_usage tool; interval in
  the plugin block (default 2 s).
- MCP server: the session tools. splinter_sessions, splinter_state,
  splinter_models, splinter_agents, splinter_history, splinter_say,
  splinter_open, splinter_model, splinter_agent, splinter_steer,
  splinter_cancel, splinter_approve. Say starts a real turn and returns the
  answer; a turn parked on an approval returns the question instead of
  failing. Mutating tools obey --autonomous. `--daemon --mcp-server-listen`
  runs the MCP server on a thread beside the Telegram daemon.
- the MCP server asks the engine for its registry on every call (a session
  switch replaces it) and copies the tool name out of the parsed JSON before
  freeing it (the first version compared a dangling pointer and answered
  every session call with empty text).
- junction: "serving <endpoint>" - streaming answers carry no
  X-Junction-Endpoint, so the plugin compares the route targets' ok counters
  from /status between samples and names the one that grew, with its
  last_ms. The header is still used when present (non-streaming). The
  X-Junction-Endpoint of the plugin's own /v1/models probe remains a probe
  fact in /junction only.
- transport: X-Junction-Endpoint is parsed from the response headers in both
  the streaming and the non-streaming path and published through
  sp_host_served_by(); sp_reply carries served_by.
- the curl rate guard (--speed-limit/--speed-time) is gone: it cut slow
  router streams with "Less than 1 bytes/sec" even while keepalives arrived.
  The overall -m timeout stays.
- focus: the sidebar shows "recap N, every M turns", and an applied recap
  writes "recap applied (turn N, every M turns)" into the transcript (host
  status messages are now drained during a turn; protocol clients get them
  as entry events too). The initial goal announcement says so as well.
- tests: test_self, test_mcpsession.sh (real socket), test_focus status
  messages, test_junction serving placeholder.

make check: all tests passed.
2026-11-17 19:13:59 +00:00

617 lines
18 KiB
C

/*
* splinter -- focus: keep the goal in front of the model.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* Long conversations drift. Ten turns in, the model is deep in a detail and the
* thing the session was started for is somewhere behind it. This plugin puts a
* short recap back on the table every seven turns - not as a new instruction
* that overrides the user, but as one system message right before the turn, so
* it can be read as a reminder and dismissed if the user has changed direction.
*
* `/goal <text>` sets the goal. The engine starts a turn with it, asking the
* model for a short recap; the plugin remembers the answer and injects that
* recap every seventh turn. There is no separate /recap command: recapping is
* what a goal does.
*
* The goal is also the first thing the prompt carries. A session that starts
* with a goal (config, resume, planner) gets one system message on its first
* request, before the model has answered anything. A goal that is only
* remembered internally is a goal the model never saw.
*
* A goal ends, and the model says so: the instructions ask it to end its final
* answer with the single line GOAL_COMPLETE. The plugin looks for that line at
* the end of the conversation and in the session log, records the state in the
* session meta (sp_session_set_goal_state), and stops reminding. The sidebar
* says [done] and /goal reports it; a new goal opens a new one.
*
* SPLINTER_FOCUS_GOAL text, exported from the config key `goal`
* SPLINTER_FOCUS_EVERY turns between recaps, default 7
*
* A goal longer than 1000 characters is truncated with a marker: a reminder
* that eats the budget it is meant to protect would be self-defeating.
*
* Position matters. The reminder is inserted before the newest user message,
* not appended after it: the model then reads goal -> request and answers the
* request, instead of reading the request and treating the goal as a reply.
*/
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "splinter.h"
#include "splinter_plugin.h"
#include "i18n.h"
#define GOAL_MAX 1000
#define RECAP_MAX 800
#define GOAL_DONE "GOAL_COMPLETE"
#define SESSION_TAIL (16 * 1024)
/*
* goal, recap and reminders are shared by three threads: /goal runs on the UI
* thread, the compactor on the turn thread, the tick on its own. One lock for
* all of them; the tick used to read the goal while /goal was rewriting it.
*/
static pthread_mutex_t focus_lock = PTHREAD_MUTEX_INITIALIZER;
static char goal[GOAL_MAX + 1];
static char recap[RECAP_MAX + 1]; /* the model's short recap of the goal */
static int recap_pending; /* goal set, waiting for that answer */
static char goal_state[16] = "open"; /* open | succeeded */
static unsigned announced; /* the goal is already in a prompt */
static unsigned armed; /* a GOAL_COMPLETE may now be an answer */
static size_t armed_assistants; /* assistant messages when it was armed */
static struct timespec armed_at; /* and when, for the session file */
static unsigned every = 7;
static unsigned last_reminder;
static unsigned reminders;
static char widget_text[192];
static char session_id[64]; /* whose goal the statics belong to */
static char env_goal[GOAL_MAX + 1]; /* SPLINTER_FOCUS_GOAL fallback */
/* One line, bounded: the recap travels in a system message, not a transcript. */
static void
recap_fit(char *s, size_t cap)
{
size_t i = 0, n = 0;
while (s[i] != '\0' && n + 1 < cap) {
unsigned char c = (unsigned char)s[i++];
if (c == '\n' || c == '\r' || c == '\t') {
if (n > 0 && s[n - 1] != ' ')
s[n++] = ' ';
} else if (c == ' ') {
if (n > 0 && s[n - 1] != ' ')
s[n++] = ' ';
} else
s[n++] = (char)c;
}
while (n > 0 && s[n - 1] == ' ')
n--;
s[n] = '\0';
}
/*
* The first answer after /goal is the recap. A tool round may put empty
* assistant messages before it; only text without calls counts.
*/
static void
recap_capture(struct sp_conv *conv)
{
size_t i;
if (!recap_pending || conv == NULL)
return;
for (i = conv->n; i > 0; i--) {
const struct sp_msg *m = &conv->v[i - 1];
if (m->role == NULL || strcmp(m->role, "assistant") != 0)
continue;
if (m->content == NULL || m->content[0] == '\0')
continue;
if (m->calls != NULL && m->calls[0] != '\0')
continue;
snprintf(recap, sizeof(recap), "%s", m->content);
recap_fit(recap, sizeof(recap));
recap_pending = 0;
return;
}
}
/*
* A plugin is not unloaded between sessions: the same focus statics serve the
* next /open. Read the goal and its state from the session meta whenever the
* session id changes, so a resumed session and a switched session see their
* own goal. The caller holds focus_lock.
*/
static void
focus_session_sync(struct sp_host *h)
{
const char *dir = sp_host_session_dir(h);
const char *id = sp_host_session_id(h);
char g[GOAL_MAX + 1], st[16];
if (id == NULL || *id == '\0' || strcmp(session_id, id) == 0)
return;
snprintf(session_id, sizeof(session_id), "%s", id);
goal[0] = '\0';
recap[0] = '\0';
snprintf(goal_state, sizeof(goal_state), "open");
recap_pending = 0;
announced = 0;
armed = 0;
reminders = 0;
last_reminder = 0;
if (dir != NULL && *dir != '\0' &&
sp_session_get_goal(dir, id, g, sizeof(g)) == 0) {
snprintf(goal, sizeof(goal), "%s", g);
if (sp_session_get_goal_state(dir, id, st, sizeof(st)) == 0 &&
strcmp(st, "succeeded") == 0)
snprintf(goal_state, sizeof(goal_state), "%s", st);
} else if (env_goal[0] != '\0')
snprintf(goal, sizeof(goal), "%s", env_goal);
}
/*
* The model declared the goal reached. Persist that in the session (a resumed
* session must know), stop reminding, and say it in the sidebar and the
* transcript once.
*/
static void
focus_publish(struct sp_host *h)
{
char line[sizeof(widget_text) + 160];
char rec[96];
unsigned n;
int done;
pthread_mutex_lock(&focus_lock);
done = strcmp(goal_state, "succeeded") == 0;
n = reminders;
if (goal[0] == '\0')
line[0] = '\0'; /* no goal: the sidebar says nothing */
else {
snprintf(rec, sizeof(rec), sp_td("focus.widget_recap",
"recap %u, every %u turns"), n, every);
snprintf(line, sizeof(line), "%s%.160s%s\n%s",
done ? "[done] " : "", goal,
strlen(goal) > 160 ? "..." : "", rec);
}
pthread_mutex_unlock(&focus_lock);
(void)sp_host_widget_text(h, "focus", line);
}
static void
focus_mark_succeeded(struct sp_host *h)
{
const char *dir = sp_host_session_dir(h);
const char *id = sp_host_session_id(h);
char g[GOAL_MAX + 1];
int changed = 0;
pthread_mutex_lock(&focus_lock);
if (goal[0] != '\0' && strcmp(goal_state, "succeeded") != 0) {
snprintf(goal_state, sizeof(goal_state), "succeeded");
snprintf(g, sizeof(g), "%s", goal);
changed = 1;
}
pthread_mutex_unlock(&focus_lock);
if (!changed)
return;
if (dir != NULL && *dir != '\0' && id != NULL && *id != '\0') {
struct sp_buf serr;
if (sp_buf_init(&serr) == 0) {
(void)sp_session_set_goal_state(dir, id, "succeeded",
&serr);
sp_buf_free(&serr);
}
}
focus_publish(h);
{
char msg[GOAL_MAX + 128];
snprintf(msg, sizeof(msg), sp_td("focus.succeeded",
"goal succeeded: %s"), g);
(void)sp_host_status_msg(h, msg);
}
}
/*
* The newest assistant answer, and only that: a marker in an old turn does not
* close a goal that was set after it. Tool rounds are skipped, they carry no
* final text - and `after` is how many answers existed when the goal went into
* the prompt, so an answer from before that point does not count.
*/
static size_t
count_assistants(const struct sp_conv *conv)
{
size_t i, n = 0;
for (i = 0; conv != NULL && i < conv->n; i++)
if (conv->v[i].role != NULL &&
strcmp(conv->v[i].role, "assistant") == 0 &&
conv->v[i].content != NULL && conv->v[i].content[0] != '\0')
n++;
return n;
}
static int
conv_goal_complete(const struct sp_conv *conv, size_t after)
{
size_t i;
if (conv == NULL || count_assistants(conv) <= after)
return 0;
for (i = conv->n; i > 0; i--) {
const struct sp_msg *m = &conv->v[i - 1];
if (m->role == NULL || strcmp(m->role, "assistant") != 0)
continue;
if (m->content == NULL || m->content[0] == '\0')
continue;
if (m->calls != NULL && m->calls[0] != '\0')
continue;
return strstr(m->content, GOAL_DONE) != NULL;
}
return 0;
}
/*
* The tick has no conversation in hand; it reads the session log. Only the tail
* is read: the answer that closed the goal is the newest thing in the file, and
* a session that has grown to megabytes must not be read every second.
*/
static int
session_goal_complete(struct sp_host *h)
{
const char *dir = sp_host_session_dir(h);
const char *id = sp_host_session_id(h);
char path[800], tail[SESSION_TAIL + 1];
struct stat st;
off_t size, off;
ssize_t n;
int fd;
char *line, *save = NULL, *last = NULL;
if (dir == NULL || *dir == '\0' || id == NULL || *id == '\0')
return 0;
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, id);
/*
* A file that has not been written since the goal was armed holds the
* answer to an older goal, whatever its last line says.
*/
if (stat(path, &st) != 0)
return 0;
if (st.st_mtim.tv_sec < armed_at.tv_sec ||
(st.st_mtim.tv_sec == armed_at.tv_sec &&
st.st_mtim.tv_nsec <= armed_at.tv_nsec))
return 0;
fd = open(path, O_RDONLY);
if (fd < 0)
return 0;
size = lseek(fd, 0, SEEK_END);
if (size <= 0) {
close(fd);
return 0;
}
off = size > (off_t)SESSION_TAIL ? size - (off_t)SESSION_TAIL : 0;
if (lseek(fd, off, SEEK_SET) < 0) {
close(fd);
return 0;
}
n = read(fd, tail, sizeof(tail) - 1);
close(fd);
if (n <= 0)
return 0;
tail[n] = '\0';
/*
* Only the newest final answer counts: an old GOAL_COMPLETE belongs to
* the goal that was open then, and a new goal has been set since.
*/
for (line = strtok_r(tail, "\n", &save); line != NULL;
line = strtok_r(NULL, "\n", &save)) {
if (strstr(line, "\"role\":\"assistant\"") != NULL)
last = line;
}
return last != NULL && strstr(last, GOAL_DONE) != NULL;
}
/* a system message right before the newest user message, never after it */
static int
insert_before_user(struct sp_conv *conv, const char *text)
{
struct sp_msg m;
size_t at;
if (conv == NULL || conv->n == 0)
return -1;
memset(&m, 0, sizeof(m));
m.role = "system";
m.content = (char *)text;
at = conv->n - 1;
while (at > 0 && conv->v[at].role != NULL &&
strcmp(conv->v[at].role, "user") != 0)
at--;
return sp_conv_insert(conv, at, &m);
}
/*
* The goal is in a prompt now. From here on an answer may close it - but only
* one written after this point: the count of answers and the log's mtime are
* the barrier that keeps an older GOAL_COMPLETE out.
*/
static void
focus_arm(const struct sp_conv *conv)
{
armed = 1;
armed_assistants = count_assistants(conv);
(void)clock_gettime(CLOCK_REALTIME, &armed_at);
}
/* /goal's own prompt already carries the goal: do not say it twice */
static int
newest_user_is_goal_prompt(const struct sp_conv *conv)
{
size_t i;
if (conv == NULL)
return 0;
for (i = conv->n; i > 0; i--) {
const struct sp_msg *m = &conv->v[i - 1];
if (m->role != NULL && strcmp(m->role, "user") == 0)
return m->content != NULL &&
strncmp(m->content, "Goal: ", 6) == 0;
}
return 0;
}
static int
focus_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
unsigned turn)
{
char text[GOAL_MAX + 800];
char rem[GOAL_MAX + 768];
char r[GOAL_MAX + 1];
unsigned n;
int complete;
(void)budget;
if (conv == NULL || conv->n == 0)
return 0;
pthread_mutex_lock(&focus_lock);
focus_session_sync(h);
recap_capture(conv);
/*
* Only an answer to a prompt that carried this goal can close it: armed
* is set when the goal goes into the request, so an old GOAL_COMPLETE
* lying in the conversation cannot close a goal that was set after it.
*/
complete = armed && goal[0] != '\0' &&
strcmp(goal_state, "succeeded") != 0 &&
conv_goal_complete(conv, armed_assistants);
if (complete) {
pthread_mutex_unlock(&focus_lock);
focus_mark_succeeded(h);
return 0;
}
if (goal[0] == '\0' || strcmp(goal_state, "succeeded") == 0 ||
turn == 0 || turn == last_reminder) { /* never twice in a turn */
pthread_mutex_unlock(&focus_lock);
return 0;
}
/*
* The first request carries the goal itself. Recap first, goal text
* until a recap exists - the same rule the periodic reminder follows.
*/
if (!announced) {
if (newest_user_is_goal_prompt(conv)) {
/* /goal or /continue already wrote it into the prompt */
announced = 1;
focus_arm(conv);
last_reminder = turn;
pthread_mutex_unlock(&focus_lock);
focus_publish(h);
return 0;
}
snprintf(r, sizeof(r), "%s", recap[0] != '\0' ? recap : goal);
announced = 1;
focus_arm(conv);
last_reminder = turn;
pthread_mutex_unlock(&focus_lock);
snprintf(rem, sizeof(rem), sp_td("focus.goal_prompt",
"Goal: %s. Work toward it. When the goal is fully "
"achieved, end your final answer with the single "
"line GOAL_COMPLETE so splinter can mark it as "
"succeeded."), r);
snprintf(text, sizeof(text), "[focus] %s", rem);
if (insert_before_user(conv, text) != 0)
return -1;
(void)sp_host_status_msg(h,
sp_t("focus.note_goal"));
focus_publish(h);
return 1;
}
if ((turn % every) != 0) {
pthread_mutex_unlock(&focus_lock);
return 0;
}
snprintf(r, sizeof(r), "%s", recap[0] != '\0' ? recap : goal);
pthread_mutex_unlock(&focus_lock);
snprintf(rem, sizeof(rem), sp_td("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."), r);
snprintf(text, sizeof(text), "[focus] %s", rem);
if (insert_before_user(conv, text) != 0)
return -1;
pthread_mutex_lock(&focus_lock);
last_reminder = turn;
reminders++;
n = reminders;
pthread_mutex_unlock(&focus_lock);
{
char note[160];
snprintf(note, sizeof(note), sp_td("focus.note_recap",
"recap applied (turn %u, every %u turns)"), turn, every);
(void)sp_host_status_msg(h, note);
}
(void)n;
focus_publish(h);
return 1;
}
/*
* /goal <text> set the goal; the engine starts the recap turn
* /goal show what it is now
*/
static int
focus_command(struct sp_host *h, const char *args, struct sp_buf *out,
void *ctx)
{
char g[GOAL_MAX + 1], saveerr[256] = "";
unsigned n;
int done;
(void)ctx;
pthread_mutex_lock(&focus_lock);
focus_session_sync(h);
if (args == NULL || *args == '\0') {
snprintf(g, sizeof(g), "%s", goal);
n = reminders;
done = strcmp(goal_state, "succeeded") == 0;
pthread_mutex_unlock(&focus_lock);
if (g[0] == '\0')
return sp_buf_puts(out, sp_td("focus.none", "no goal set (/goal <text>)"));
if (done)
return sp_buf_printf(out, sp_td("focus.status_done",
"goal: %s [succeeded] (%u recaps, every %u turns)"),
g, n, every);
return sp_buf_printf(out, sp_td("focus.status",
"goal: %s (%u recaps, every %u turns)"), g, n, every);
}
snprintf(goal, sizeof(goal), "%.*s", GOAL_MAX, args);
if (strlen(args) > GOAL_MAX)
snprintf(goal + GOAL_MAX - 24, 25, "...[gekuerzt]");
recap[0] = '\0';
recap_pending = 1;
snprintf(goal_state, sizeof(goal_state), "open");
announced = 0;
armed = 0;
reminders = 0;
last_reminder = 0;
snprintf(g, sizeof(g), "%s", goal);
{
const char *dir = sp_host_session_dir(h);
const char *id = sp_host_session_id(h);
if (dir != NULL && *dir != '\0' && id != NULL && *id != '\0') {
struct sp_buf serr;
if (sp_buf_init(&serr) == 0) {
if (sp_session_set_goal(dir, id, goal, &serr) != 0)
snprintf(saveerr, sizeof(saveerr), "%s",
serr.p != NULL ? serr.p :
"not saved");
sp_buf_free(&serr);
}
}
}
pthread_mutex_unlock(&focus_lock);
/* publish now, so the sidebar does not wait for the next tick */
focus_publish(h);
(void)sp_buf_printf(out, sp_td("focus.set", "goal set: %s"), g);
if (saveerr[0] != '\0')
sp_buf_printf(out, " (%s)", saveerr);
return 0;
}
static int
focus_tick(struct sp_host *h, const char *name, void *ctx)
{
char line[sizeof(widget_text)];
int check = 0;
(void)ctx;
pthread_mutex_lock(&focus_lock);
focus_session_sync(h);
check = armed && goal[0] != '\0' &&
strcmp(goal_state, "succeeded") != 0 &&
session_goal_complete(h);
if (!check) {
if (goal[0] == '\0')
line[0] = '\0'; /* no goal: the sidebar says nothing */
else
snprintf(line, sizeof(line), "%s%.160s%s",
strcmp(goal_state, "succeeded") == 0 ?
"[done] " : "", goal,
strlen(goal) > 160 ? "..." : "");
}
pthread_mutex_unlock(&focus_lock);
if (check) {
focus_mark_succeeded(h);
return 0;
}
return sp_host_widget_text(h, name, line);
}
static const struct sp_compactor focus = { "focus", focus_compact };
static int
focus_init(struct sp_host *h)
{
static const struct sp_widget w = { "focus", focus_tick, NULL, NULL, 1000 };
const char *g = getenv("SPLINTER_FOCUS_GOAL");
const char *e = getenv("SPLINTER_FOCUS_EVERY");
memset(goal, 0, sizeof(goal));
memset(recap, 0, sizeof(recap));
memset(env_goal, 0, sizeof(env_goal));
session_id[0] = '\0';
recap_pending = 0;
snprintf(goal_state, sizeof(goal_state), "open");
announced = 0;
armed = 0;
if (g != NULL) {
snprintf(env_goal, sizeof(env_goal), "%.*s", GOAL_MAX, g);
if (strlen(g) > GOAL_MAX)
snprintf(env_goal + GOAL_MAX - 24, 25,
"...[gekuerzt]");
snprintf(goal, sizeof(goal), "%s", env_goal);
}
if (e != NULL && atoi(e) > 0 && atoi(e) < 1000)
every = (unsigned)atoi(e);
if (sp_host_add_compactor(h, &focus) != 0)
return -1;
if (sp_host_add_command(h, "goal", focus_command, NULL) != 0)
return -1;
if (sp_host_add_widget(h, &w) != 0)
return -1;
return 0;
}
static const struct sp_plugin focus_plugin = {
SP_PLUGIN_ABI, "focus", "1.1.0", focus_init, NULL, NULL
};
const struct sp_plugin *
sp_plugin_describe(void)
{
return &focus_plugin;
}