The screen had no room for the numbers that say how a turn is doing, and two older behaviours still hurt: scrolling to the top made PgDn jump back to the top, and a catalogue's steer mark without its trailing space glued the typed text to ">". - draw_statusbar() in curses.c: one row above the prompt with ctx used/max + [|||| ] gauge, cache share and tok/s. The history and sidebar lose one row; the prompt stays the bottom row. The bar is drawn on every idle tick, during a turn and in --attach. - ctx: optional field on a provider (and in core) in tokens; the engine reports it in struct sp_engine_state. SPLINTER_CTX_MAX still overrides it. - cache: sp_reply gained tokens_cached. OpenAI reads prompt_tokens_details.cached_tokens / prompt_cache_hit_tokens, Anthropic reads cache_read_input_tokens and counts cache reads+writes in the prompt total. sp_agent_stats keeps the last request's prompt and cache share; the engine keeps the turn's output tokens for a real tok/s. - scroll: grow scroll by the growth of maxscroll, not by the distance from the first visible line. At the top that distance was 0, so every frame re-added the whole scrollback and PgDn could not leave the top. - steer mark: append the missing space if a catalogue omits it. - protocol state carries ctx_used/ctx_max/cached/turn_tokens_out, so the attached UI shows the same bar. - tests: cache parsing in test_sse/test_openai/test_anthropic, ctx parsing in test_confblock, and test_ui checks the bar, the cache share and the PgUp-to-top/PgDn-down path. make check: all tests passed.
1032 lines
25 KiB
C
1032 lines
25 KiB
C
/*
|
|
* splinter -- the line protocol front end: the engine on a Unix socket.
|
|
*
|
|
* Copyright (c) 2026 Konrad Lother
|
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
*
|
|
* `splinter --serve` runs the same engine the curses front end uses and sends
|
|
* its events as JSON, one object per line. A GUI in any language can then be a
|
|
* client: connect, send a line, read the events. Nothing in here draws.
|
|
*
|
|
* The socket is a file in the user's own directory, mode 0600, and the peer is
|
|
* checked against getuid() -- a second local user must not be able to type into
|
|
* a conversation that may run `run` with the owner's rights.
|
|
*/
|
|
#define _GNU_SOURCE 1
|
|
#include <ctype.h>
|
|
#include <errno.h>
|
|
#include <fcntl.h>
|
|
#include <poll.h>
|
|
#include <pthread.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/time.h>
|
|
#include <sys/un.h>
|
|
#include <time.h>
|
|
#include <unistd.h>
|
|
|
|
#include "splinter.h"
|
|
#include "splinter_engine.h"
|
|
#include "mcp.h"
|
|
#include "i18n.h"
|
|
#include "protocol.h"
|
|
|
|
struct client {
|
|
int fd;
|
|
struct sp_buf in; /* bytes not yet cut into lines */
|
|
struct sp_buf line; /* the line handed to handle_line */
|
|
int quit;
|
|
};
|
|
|
|
/* the server's current engine and the template a new session opens from */
|
|
struct proto {
|
|
const struct sp_engine_opts *tmpl;
|
|
struct sp_engine *eng;
|
|
};
|
|
|
|
/* --------------------------------------------------------------- writing */
|
|
|
|
static int
|
|
write_all(int fd, const char *p, size_t n)
|
|
{
|
|
while (n > 0) {
|
|
ssize_t w = send(fd, p, n, MSG_NOSIGNAL);
|
|
|
|
if (w < 0) {
|
|
if (errno == EINTR)
|
|
continue;
|
|
return -1;
|
|
}
|
|
p += w;
|
|
n -= (size_t)w;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static int
|
|
send_line(struct client *c, struct sp_buf *b)
|
|
{
|
|
if (sp_buf_puts(b, "\n") != 0)
|
|
return -1;
|
|
return write_all(c->fd, b->p, b->len);
|
|
}
|
|
|
|
static void
|
|
ev_start(struct sp_buf *b, const char *name)
|
|
{
|
|
sp_buf_clear(b);
|
|
sp_buf_printf(b, "{\"ev\":\"%s\"", name);
|
|
}
|
|
|
|
static void
|
|
ev_str(struct sp_buf *b, const char *key, const char *val)
|
|
{
|
|
sp_buf_printf(b, ",\"%s\":\"", key);
|
|
(void)sp_json_escape(b, val != NULL ? val : "");
|
|
sp_buf_puts(b, "\"");
|
|
}
|
|
|
|
static void
|
|
ev_num(struct sp_buf *b, const char *key, long v)
|
|
{
|
|
sp_buf_printf(b, ",\"%s\":%ld", key, v);
|
|
}
|
|
|
|
static void
|
|
ev_bool(struct sp_buf *b, const char *key, int v)
|
|
{
|
|
sp_buf_printf(b, ",\"%s\":%s", key, v ? "true" : "false");
|
|
}
|
|
|
|
static int
|
|
send_ready(struct client *c)
|
|
{
|
|
struct sp_buf b;
|
|
int rc;
|
|
|
|
if (sp_buf_init(&b) != 0)
|
|
return -1;
|
|
ev_start(&b, "ready");
|
|
ev_num(&b, "protocol", SP_PROTO_VERSION);
|
|
ev_str(&b, "version", SP_VERSION);
|
|
sp_buf_puts(&b, "}");
|
|
rc = send_line(c, &b);
|
|
sp_buf_free(&b);
|
|
return rc;
|
|
}
|
|
|
|
static int
|
|
send_commands(struct client *c, struct sp_engine *eng)
|
|
{
|
|
char names[64][64];
|
|
int n = sp_engine_command_names(eng, names, 64), i;
|
|
struct sp_buf b;
|
|
int rc;
|
|
|
|
if (sp_buf_init(&b) != 0)
|
|
return -1;
|
|
ev_start(&b, "commands");
|
|
sp_buf_puts(&b, ",\"names\":[");
|
|
for (i = 0; i < n; i++) {
|
|
if (i > 0)
|
|
sp_buf_puts(&b, ",");
|
|
sp_buf_puts(&b, "\"");
|
|
(void)sp_json_escape(&b, names[i]);
|
|
sp_buf_puts(&b, "\"");
|
|
}
|
|
sp_buf_puts(&b, "]}");
|
|
rc = send_line(c, &b);
|
|
sp_buf_free(&b);
|
|
return rc;
|
|
}
|
|
|
|
/* the whole engine state, for a client that just attached or asks again */
|
|
static int
|
|
send_state(struct client *c, struct sp_engine *eng, const char *name)
|
|
{
|
|
struct sp_engine_state st;
|
|
struct sp_buf b;
|
|
int i;
|
|
|
|
if (sp_engine_state(eng, &st) != 0)
|
|
return -1;
|
|
if (sp_buf_init(&b) != 0)
|
|
return -1;
|
|
ev_start(&b, name);
|
|
ev_str(&b, "session", st.session);
|
|
ev_str(&b, "dir", st.dir);
|
|
ev_str(&b, "model", st.model);
|
|
ev_str(&b, "endpoint", st.endpoint);
|
|
ev_str(&b, "agent", st.agent);
|
|
ev_num(&b, "tokens_in", (long)st.tokens_in);
|
|
ev_num(&b, "tokens_out", (long)st.tokens_out);
|
|
ev_num(&b, "ctx_used", (long)st.ctx_used);
|
|
ev_num(&b, "ctx_max", (long)st.ctx_max);
|
|
ev_num(&b, "cached", (long)st.cached);
|
|
ev_num(&b, "turn_tokens_out", (long)st.turn_tokens_out);
|
|
ev_num(&b, "steps", (long)st.steps);
|
|
ev_num(&b, "calls", (long)st.calls);
|
|
ev_num(&b, "compactions", (long)st.compactions);
|
|
ev_num(&b, "last_ms", (long)st.last_ms);
|
|
ev_num(&b, "last_steps", (long)st.last_steps);
|
|
ev_num(&b, "last_calls", (long)st.last_calls);
|
|
ev_bool(&b, "busy", st.busy);
|
|
ev_bool(&b, "waiting", st.waiting);
|
|
ev_bool(&b, "quit", st.quit);
|
|
sp_buf_puts(&b, ",\"agents\":[");
|
|
for (i = 0; i < st.agents_n; i++) {
|
|
if (i > 0)
|
|
sp_buf_puts(&b, ",");
|
|
sp_buf_puts(&b, "\"");
|
|
(void)sp_json_escape(&b, sp_engine_agent_name(eng, i));
|
|
sp_buf_puts(&b, "\"");
|
|
}
|
|
sp_buf_puts(&b, "]");
|
|
ev_num(&b, "agent_cur", st.agent_cur);
|
|
sp_buf_puts(&b, "}");
|
|
{
|
|
int rc = send_line(c, &b);
|
|
|
|
sp_buf_free(&b);
|
|
return rc;
|
|
}
|
|
}
|
|
|
|
/* one engine event as one JSON line */
|
|
static int
|
|
send_event(struct client *c, struct sp_engine *eng, const struct sp_event *ev)
|
|
{
|
|
struct sp_buf b;
|
|
int rc = 0;
|
|
|
|
if (sp_buf_init(&b) != 0)
|
|
return -1;
|
|
switch (ev->kind) {
|
|
case SP_EV_BUSY:
|
|
ev_start(&b, "busy");
|
|
ev_bool(&b, "on", ev->n != 0);
|
|
break;
|
|
case SP_EV_STREAM:
|
|
ev_start(&b, "stream");
|
|
ev_str(&b, "kind", ev->n == SP_STREAM_THINK ? "think" : "text");
|
|
ev_str(&b, "text", ev->a);
|
|
break;
|
|
case SP_EV_STEP:
|
|
ev_start(&b, "step");
|
|
ev_str(&b, "think", ev->a);
|
|
ev_str(&b, "text", ev->b);
|
|
break;
|
|
case SP_EV_TOOL: {
|
|
char call[640];
|
|
|
|
sp_call_summary(ev->a, ev->b, call, sizeof(call));
|
|
ev_start(&b, "tool");
|
|
ev_str(&b, "name", ev->a);
|
|
ev_str(&b, "args", ev->b);
|
|
ev_str(&b, "call", call);
|
|
break;
|
|
}
|
|
case SP_EV_TOOL_RESULT:
|
|
ev_start(&b, "tool_result");
|
|
ev_str(&b, "name", ev->a);
|
|
ev_str(&b, "text", ev->b);
|
|
ev_bool(&b, "join", ev->n == 1);
|
|
break;
|
|
case SP_EV_NOTE:
|
|
ev_start(&b, "note");
|
|
ev_str(&b, "text", ev->a);
|
|
break;
|
|
case SP_EV_ENTRY:
|
|
ev_start(&b, "entry");
|
|
ev_str(&b, "role", ev->a);
|
|
ev_str(&b, "text", ev->b);
|
|
break;
|
|
case SP_EV_APPROVAL: {
|
|
char call[640];
|
|
|
|
sp_call_summary(ev->a, ev->b, call, sizeof(call));
|
|
ev_start(&b, "approval");
|
|
ev_str(&b, "name", ev->a);
|
|
ev_num(&b, "auth", ev->n);
|
|
ev_str(&b, "args", ev->b);
|
|
ev_str(&b, "call", call);
|
|
ev_str(&b, "class", ev->n == SP_AUTH_MUTATE ? "mutate" :
|
|
"destructive");
|
|
break;
|
|
}
|
|
case SP_EV_TURN_END:
|
|
ev_start(&b, "turn");
|
|
ev_bool(&b, "ok", ev->n == 0);
|
|
ev_num(&b, "rc", ev->n);
|
|
ev_str(&b, "answer", ev->a);
|
|
ev_str(&b, "error", ev->b);
|
|
break;
|
|
case SP_EV_STATE:
|
|
sp_buf_free(&b);
|
|
return send_state(c, eng, "state");
|
|
case SP_EV_CLEAR:
|
|
ev_start(&b, "clear");
|
|
break;
|
|
case SP_EV_QUIT:
|
|
ev_start(&b, "quit");
|
|
break;
|
|
case SP_EV_NONE:
|
|
sp_buf_free(&b);
|
|
return 0;
|
|
}
|
|
sp_buf_puts(&b, "}");
|
|
rc = send_line(c, &b);
|
|
sp_buf_free(&b);
|
|
return rc;
|
|
}
|
|
|
|
static int
|
|
send_reply(struct client *c, const char *text)
|
|
{
|
|
struct sp_buf b;
|
|
int rc;
|
|
|
|
if (sp_buf_init(&b) != 0)
|
|
return -1;
|
|
ev_start(&b, "reply");
|
|
ev_str(&b, "text", text);
|
|
sp_buf_puts(&b, "}");
|
|
rc = send_line(c, &b);
|
|
sp_buf_free(&b);
|
|
return rc;
|
|
}
|
|
|
|
static int
|
|
send_error(struct client *c, const char *text)
|
|
{
|
|
struct sp_buf b;
|
|
int rc;
|
|
|
|
if (sp_buf_init(&b) != 0)
|
|
return -1;
|
|
ev_start(&b, "error");
|
|
ev_str(&b, "text", text);
|
|
sp_buf_puts(&b, "}");
|
|
rc = send_line(c, &b);
|
|
sp_buf_free(&b);
|
|
return rc;
|
|
}
|
|
|
|
/* Every event the engine queued so far, in order. A command that produced
|
|
* entries (/new's clear, a shell's output) must have them delivered before its
|
|
* reply: otherwise a GUI clears the pane after it printed the reply. */
|
|
static int
|
|
drain_to_client(struct client *c, struct sp_engine *eng)
|
|
{
|
|
struct sp_event ev;
|
|
|
|
while (sp_engine_poll(eng, &ev)) {
|
|
int rc = send_event(c, eng, &ev);
|
|
|
|
sp_engine_event_free(&ev);
|
|
if (rc != 0)
|
|
return -1;
|
|
if (!sp_engine_busy(eng))
|
|
(void)sp_engine_wait(eng);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/*
|
|
* The transcript so far, as one event. A long session is cut at 100 messages
|
|
* and 256 KiB; the flag says so, and a GUI can offer "load older" later. The
|
|
* system prompt and tool observations stay out: the transcript shows what the
|
|
* person and the model said.
|
|
*/
|
|
#define HIST_MSGS 100
|
|
#define HIST_BYTES (256 * 1024)
|
|
|
|
static int
|
|
send_history(struct client *c, struct sp_engine *eng)
|
|
{
|
|
const struct sp_conv *conv = sp_engine_conv(eng);
|
|
struct sp_buf b, items;
|
|
size_t i, start, bytes = 0;
|
|
int first = 1, truncated = 0;
|
|
|
|
if (sp_buf_init(&b) != 0 || sp_buf_init(&items) != 0) {
|
|
sp_buf_free(&b);
|
|
sp_buf_free(&items);
|
|
return -1;
|
|
}
|
|
start = conv != NULL && conv->n > HIST_MSGS ? conv->n - HIST_MSGS : 0;
|
|
if (start > 0)
|
|
truncated = 1;
|
|
for (i = start; conv != NULL && i < conv->n; i++) {
|
|
const struct sp_msg *m = &conv->v[i];
|
|
size_t len;
|
|
|
|
if (m->role == NULL || m->content == NULL ||
|
|
m->content[0] == '\0')
|
|
continue;
|
|
if (strcmp(m->role, "user") != 0 &&
|
|
strcmp(m->role, "assistant") != 0)
|
|
continue;
|
|
len = strlen(m->content);
|
|
if (bytes + len > HIST_BYTES) {
|
|
truncated = 1;
|
|
break;
|
|
}
|
|
bytes += len;
|
|
if (!first)
|
|
sp_buf_puts(&items, ",");
|
|
first = 0;
|
|
sp_buf_puts(&items, "{\"role\":\"");
|
|
(void)sp_json_escape(&items, m->role);
|
|
sp_buf_puts(&items, "\",\"text\":\"");
|
|
(void)sp_json_escape(&items, m->content);
|
|
sp_buf_puts(&items, "\"}");
|
|
}
|
|
ev_start(&b, "history");
|
|
ev_bool(&b, "truncated", truncated);
|
|
sp_buf_puts(&b, ",\"items\":[");
|
|
sp_buf_puts(&b, items.p != NULL ? items.p : "");
|
|
sp_buf_puts(&b, "]}");
|
|
sp_buf_free(&items);
|
|
{
|
|
int rc = send_line(c, &b);
|
|
|
|
sp_buf_free(&b);
|
|
return rc;
|
|
}
|
|
}
|
|
|
|
/*
|
|
* A steer that arrived after the last step boundary belongs before the next
|
|
* prompt. It is shown as the operator's entry and prepended to the text; the
|
|
* client that typed it sees it in the transcript instead of losing it.
|
|
*/
|
|
static int
|
|
fold_pending_steer(struct client *c, struct sp_engine *eng, struct sp_buf *prompt)
|
|
{
|
|
struct sp_buf st, joined;
|
|
struct sp_event ev;
|
|
int took = 0;
|
|
|
|
if (sp_buf_init(&st) != 0)
|
|
return 0;
|
|
if (!sp_engine_take_steer(eng, &st)) {
|
|
sp_buf_free(&st);
|
|
return 0;
|
|
}
|
|
ev.kind = SP_EV_ENTRY;
|
|
ev.n = 0;
|
|
ev.a = "you";
|
|
ev.b = st.p;
|
|
(void)send_event(c, eng, &ev);
|
|
if (sp_buf_init(&joined) == 0) {
|
|
(void)sp_buf_puts(&joined, st.p != NULL ? st.p : "");
|
|
(void)sp_buf_puts(&joined, "\n\n");
|
|
(void)sp_buf_puts(&joined, prompt->p != NULL ? prompt->p : "");
|
|
sp_buf_clear(prompt);
|
|
(void)sp_buf_puts(prompt, joined.p != NULL ? joined.p : "");
|
|
sp_buf_free(&joined);
|
|
took = 1;
|
|
}
|
|
sp_buf_free(&st);
|
|
return took;
|
|
}
|
|
|
|
/* the sessions in this engine's directory, newest first */
|
|
static int
|
|
send_sessions(struct client *c, struct proto *p)
|
|
{
|
|
struct sp_session_brief v[100];
|
|
const char *cur = sp_engine_session_id(p->eng);
|
|
int n, i;
|
|
struct sp_buf b;
|
|
int rc;
|
|
|
|
n = sp_session_list(sp_engine_state_dir(p->eng), v, 100);
|
|
if (n < 0)
|
|
n = 0;
|
|
if (sp_buf_init(&b) != 0)
|
|
return -1;
|
|
ev_start(&b, "sessions");
|
|
sp_buf_puts(&b, ",\"items\":[");
|
|
for (i = 0; i < n; i++) {
|
|
if (i > 0)
|
|
sp_buf_puts(&b, ",");
|
|
sp_buf_puts(&b, "{\"id\":\"");
|
|
(void)sp_json_escape(&b, v[i].id);
|
|
sp_buf_puts(&b, "\",\"title\":\"");
|
|
(void)sp_json_escape(&b, v[i].title);
|
|
sp_buf_printf(&b, "\",\"mtime\":%ld,\"bytes\":%zu,"
|
|
"\"current\":%s}", v[i].mtime, v[i].bytes,
|
|
strcmp(v[i].id, cur) == 0 ? "true" : "false");
|
|
}
|
|
sp_buf_puts(&b, "]}");
|
|
rc = send_line(c, &b);
|
|
sp_buf_free(&b);
|
|
return rc;
|
|
}
|
|
|
|
/*
|
|
* Switch this connection to another session. sp_engine_switch closes the old
|
|
* engine before it opens the next (plugins keep globals) and puts the engine
|
|
* back on the old session when the new one fails. If even that fails there is
|
|
* no engine left, so the connection ends instead of reporting state it does
|
|
* not have.
|
|
*/
|
|
static int
|
|
proto_open(struct client *c, struct proto *p, const char *id, int is_new)
|
|
{
|
|
struct sp_buf err;
|
|
int rc;
|
|
|
|
if (sp_engine_busy(p->eng)) {
|
|
(void)send_error(c, "a turn is running");
|
|
return 0;
|
|
}
|
|
sp_buf_init(&err);
|
|
rc = sp_engine_switch(&p->eng, p->tmpl, is_new ? "new" : id, &err);
|
|
if (rc != 0) {
|
|
(void)send_error(c, err.p != NULL && err.len > 0 ? err.p :
|
|
"cannot open the session");
|
|
sp_buf_free(&err);
|
|
if (p->eng == NULL) {
|
|
(void)send_error(c, "the engine is gone");
|
|
c->quit = 1;
|
|
}
|
|
return 0;
|
|
}
|
|
sp_buf_free(&err);
|
|
(void)send_ready(c);
|
|
(void)send_state(c, p->eng, "state");
|
|
(void)send_commands(c, p->eng);
|
|
(void)send_history(c, p->eng);
|
|
{
|
|
struct sp_buf b;
|
|
|
|
if (sp_buf_init(&b) == 0) {
|
|
ev_start(&b, "opened");
|
|
ev_str(&b, "session", sp_engine_session_id(p->eng));
|
|
ev_str(&b, "dir", sp_engine_state_dir(p->eng));
|
|
sp_buf_puts(&b, "}");
|
|
(void)send_line(c, &b);
|
|
sp_buf_free(&b);
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* -------------------------------------------------------------- commands */
|
|
|
|
/*
|
|
* One line from the client. Returns -1 when the connection should end. A
|
|
* command that starts a turn sets *started; the caller then keeps the event
|
|
* pump running while the engine works.
|
|
*/
|
|
static int
|
|
handle_line(struct client *c, struct proto *p, const char *line)
|
|
{
|
|
struct sp_engine *eng = p->eng;
|
|
mcp_json *v;
|
|
const char *cmd, *text;
|
|
struct sp_buf out;
|
|
int handled;
|
|
|
|
v = mcp_parse(line);
|
|
if (v == NULL) {
|
|
(void)send_error(c, "not JSON");
|
|
return 0;
|
|
}
|
|
cmd = mcp_arg_string(v, "cmd");
|
|
if (cmd == NULL) {
|
|
(void)send_error(c, "no cmd");
|
|
mcp_json_free(v);
|
|
return 0;
|
|
}
|
|
if (sp_buf_init(&out) != 0) {
|
|
mcp_json_free(v);
|
|
return -1;
|
|
}
|
|
if (strcmp(cmd, "say") == 0 || strcmp(cmd, "submit") == 0) {
|
|
text = mcp_arg_string(v, "text");
|
|
if (text == NULL || *text == '\0') {
|
|
(void)send_error(c, "empty prompt");
|
|
} else {
|
|
struct sp_buf prompt;
|
|
int ok;
|
|
|
|
if (sp_buf_init(&prompt) != 0) {
|
|
mcp_json_free(v);
|
|
sp_buf_free(&out);
|
|
return -1;
|
|
}
|
|
(void)sp_buf_puts(&prompt, text);
|
|
(void)fold_pending_steer(c, eng, &prompt);
|
|
ok = sp_engine_submit(eng,
|
|
prompt.p != NULL ? prompt.p : text);
|
|
if (ok != 0) {
|
|
sp_buf_free(&prompt);
|
|
(void)send_error(c, "a turn is already running");
|
|
goto done;
|
|
}
|
|
struct sp_buf b;
|
|
|
|
if (sp_buf_init(&b) == 0) {
|
|
ev_start(&b, "submitted");
|
|
ev_str(&b, "text",
|
|
prompt.p != NULL ? prompt.p : text);
|
|
sp_buf_puts(&b, "}");
|
|
(void)send_line(c, &b);
|
|
sp_buf_free(&b);
|
|
}
|
|
sp_buf_free(&prompt);
|
|
}
|
|
} else if (strcmp(cmd, "input") == 0 ||
|
|
strcmp(cmd, "command") == 0) {
|
|
text = mcp_arg_string(v, "line");
|
|
if (text == NULL) {
|
|
(void)send_error(c, "no line");
|
|
} else if (sp_engine_busy(eng)) {
|
|
(void)send_error(c, "a turn is running");
|
|
} else {
|
|
handled = sp_engine_input(eng, text, &out);
|
|
if (handled == SP_INPUT_PROMPT) {
|
|
struct sp_buf prompt, b;
|
|
|
|
if (sp_buf_init(&prompt) != 0)
|
|
goto done;
|
|
(void)sp_buf_puts(&prompt,
|
|
out.len > 0 ? out.p : text);
|
|
(void)fold_pending_steer(c, eng, &prompt);
|
|
if (sp_buf_init(&b) == 0) {
|
|
ev_start(&b, "submitted");
|
|
ev_str(&b, "text", prompt.p != NULL ?
|
|
prompt.p : text);
|
|
sp_buf_puts(&b, "}");
|
|
(void)send_line(c, &b);
|
|
sp_buf_free(&b);
|
|
}
|
|
if (sp_engine_submit(eng, prompt.p != NULL ?
|
|
prompt.p : text) != 0)
|
|
(void)send_error(c,
|
|
"a turn is already running");
|
|
sp_buf_free(&prompt);
|
|
} else if (handled == SP_INPUT_SUBMIT) {
|
|
/* a program in commands/ replaced the line: run it */
|
|
struct sp_buf b, prompt;
|
|
int prc;
|
|
|
|
if (drain_to_client(c, eng) != 0)
|
|
return -1;
|
|
if (sp_buf_init(&prompt) != 0)
|
|
goto done;
|
|
(void)sp_buf_puts(&prompt,
|
|
out.p != NULL ? out.p : "");
|
|
(void)fold_pending_steer(c, eng, &prompt);
|
|
if (sp_buf_init(&b) == 0) {
|
|
ev_start(&b, "submitted");
|
|
ev_str(&b, "text", prompt.p != NULL ?
|
|
prompt.p : "");
|
|
sp_buf_puts(&b, "}");
|
|
(void)send_line(c, &b);
|
|
sp_buf_free(&b);
|
|
}
|
|
prc = sp_engine_submit(eng,
|
|
prompt.p != NULL ? prompt.p : "");
|
|
if (prc != 0)
|
|
(void)send_error(c,
|
|
"a turn is already running");
|
|
sp_buf_free(&prompt);
|
|
} else {
|
|
if (drain_to_client(c, eng) != 0)
|
|
return -1;
|
|
(void)send_reply(c, out.p != NULL ? out.p : "");
|
|
}
|
|
}
|
|
} else if (strcmp(cmd, "approve") == 0) {
|
|
(void)sp_engine_approve(eng, mcp_arg_bool(v, "allow", 0));
|
|
} else if (strcmp(cmd, "cancel") == 0) {
|
|
(void)sp_engine_cancel(eng);
|
|
} else if (strcmp(cmd, "steer") == 0) {
|
|
text = mcp_arg_string(v, "text");
|
|
if (text != NULL &&
|
|
sp_engine_steer(eng, text) != 0)
|
|
(void)send_error(c, "no turn is running");
|
|
} else if (strcmp(cmd, "state") == 0) {
|
|
(void)send_state(c, eng, "state");
|
|
} else if (strcmp(cmd, "sessions") == 0) {
|
|
(void)send_sessions(c, p);
|
|
} else if (strcmp(cmd, "open") == 0) {
|
|
(void)proto_open(c, p, mcp_arg_string(v, "session"),
|
|
mcp_arg_bool(v, "new", 0));
|
|
} else if (strcmp(cmd, "history") == 0) {
|
|
/*
|
|
* The conversation belongs to the worker while a turn runs; a
|
|
* history read would race its appends and its realloc. The
|
|
* attach greeting is idle by construction.
|
|
*/
|
|
if (sp_engine_busy(eng))
|
|
(void)send_error(c, "a turn is running");
|
|
else
|
|
(void)send_history(c, eng);
|
|
} else if (strcmp(cmd, "commands") == 0) {
|
|
/* what a command palette may offer, without the leading slash */
|
|
char names[64][64];
|
|
int n = sp_engine_command_names(eng, names, 64), i;
|
|
struct sp_buf b;
|
|
|
|
if (sp_buf_init(&b) != 0)
|
|
return -1;
|
|
ev_start(&b, "commands");
|
|
sp_buf_puts(&b, ",\"names\":[");
|
|
for (i = 0; i < n; i++) {
|
|
if (i > 0)
|
|
sp_buf_puts(&b, ",");
|
|
sp_buf_puts(&b, "\"");
|
|
(void)sp_json_escape(&b, names[i]);
|
|
sp_buf_puts(&b, "\"");
|
|
}
|
|
sp_buf_puts(&b, "]}");
|
|
(void)send_line(c, &b);
|
|
sp_buf_free(&b);
|
|
} else if (strcmp(cmd, "ping") == 0) {
|
|
struct sp_buf b;
|
|
|
|
if (sp_buf_init(&b) == 0) {
|
|
ev_start(&b, "pong");
|
|
sp_buf_puts(&b, "}");
|
|
(void)send_line(c, &b);
|
|
sp_buf_free(&b);
|
|
}
|
|
} else if (strcmp(cmd, "quit") == 0) {
|
|
sp_buf_clear(&out);
|
|
(void)sp_engine_input(eng, "/quit", &out);
|
|
(void)send_reply(c, out.p != NULL ? out.p : "");
|
|
c->quit = 1;
|
|
} else {
|
|
(void)send_error(c, "unknown cmd");
|
|
}
|
|
done:
|
|
sp_buf_free(&out);
|
|
mcp_json_free(v);
|
|
return 0;
|
|
}
|
|
|
|
/*
|
|
* A client went away while a turn was running. The engine would park in an
|
|
* approval nobody can answer, so cancel it and drain the events nobody will
|
|
* read. The conversation keeps the answer the model produced up to there.
|
|
*/
|
|
static void
|
|
abandon_turn(struct sp_engine *eng)
|
|
{
|
|
struct sp_event ev;
|
|
|
|
if (eng == NULL || !sp_engine_busy(eng))
|
|
return;
|
|
(void)sp_engine_cancel(eng);
|
|
while (sp_engine_busy(eng)) {
|
|
while (sp_engine_poll(eng, &ev))
|
|
sp_engine_event_free(&ev);
|
|
{
|
|
struct timespec ts = { 0, 20000000L };
|
|
|
|
nanosleep(&ts, NULL);
|
|
}
|
|
}
|
|
while (sp_engine_poll(eng, &ev))
|
|
sp_engine_event_free(&ev);
|
|
(void)sp_engine_wait(eng);
|
|
}
|
|
|
|
/* the whole life of one connected client */
|
|
static int
|
|
serve_client(struct proto *p, int fd)
|
|
{
|
|
struct client c;
|
|
struct sp_buf b;
|
|
int rc = 0;
|
|
|
|
memset(&c, 0, sizeof(c));
|
|
c.fd = fd;
|
|
if (sp_buf_init(&c.in) != 0 || sp_buf_init(&c.line) != 0 ||
|
|
sp_buf_init(&b) != 0) {
|
|
sp_buf_free(&c.in);
|
|
sp_buf_free(&c.line);
|
|
return -1;
|
|
}
|
|
if (send_ready(&c) != 0 ||
|
|
send_state(&c, p->eng, "state") != 0) {
|
|
sp_buf_free(&b);
|
|
sp_buf_free(&c.in);
|
|
sp_buf_free(&c.line);
|
|
return -1;
|
|
}
|
|
sp_buf_free(&b);
|
|
while (!c.quit) {
|
|
struct pollfd pfd;
|
|
int pr;
|
|
char chunk[4096];
|
|
ssize_t got;
|
|
struct sp_event ev;
|
|
|
|
pfd.fd = fd;
|
|
pfd.events = POLLIN;
|
|
pfd.revents = 0;
|
|
pr = poll(&pfd, 1, 100);
|
|
if (pr > 0 && (pfd.revents & (POLLHUP | POLLERR | POLLNVAL)))
|
|
break;
|
|
if (pr > 0 && (pfd.revents & POLLIN)) {
|
|
got = recv(fd, chunk, sizeof(chunk), 0);
|
|
if (got <= 0) {
|
|
if (got < 0 && (errno == EINTR ||
|
|
errno == EAGAIN))
|
|
continue;
|
|
break;
|
|
}
|
|
if (sp_buf_add(&c.in, chunk, (size_t)got) != 0)
|
|
break;
|
|
}
|
|
/* complete lines, in the order they arrived. The line grows with
|
|
* the client: a pasted prompt may be larger than any fixed buffer,
|
|
* and a truncated JSON line is a command nobody executed. */
|
|
for (;;) {
|
|
char *nl = memchr(c.in.p, '\n', c.in.len);
|
|
size_t len, used;
|
|
|
|
if (nl == NULL)
|
|
break;
|
|
len = (size_t)(nl - c.in.p);
|
|
sp_buf_clear(&c.line);
|
|
if (sp_buf_add(&c.line, c.in.p, len) != 0) {
|
|
rc = -1;
|
|
goto out;
|
|
}
|
|
if (c.line.len > 0 &&
|
|
c.line.p[c.line.len - 1] == '\r')
|
|
c.line.p[--c.line.len] = '\0';
|
|
used = len + 1;
|
|
memmove(c.in.p, c.in.p + used, c.in.len - used);
|
|
c.in.len -= used;
|
|
c.in.p[c.in.len] = '\0';
|
|
if (c.line.len == 0)
|
|
continue;
|
|
if (handle_line(&c, p, c.line.p) != 0) {
|
|
rc = -1;
|
|
goto out;
|
|
}
|
|
if (c.quit)
|
|
break;
|
|
}
|
|
/* a switch that could not reopen any engine */
|
|
if (p->eng == NULL)
|
|
break;
|
|
/*
|
|
* Even after a quit, drain once: the engine's quit event (and
|
|
* the reply it queues) still has to reach the client.
|
|
*/
|
|
/* and every event the engine produced since the last tick */
|
|
while (sp_engine_poll(p->eng, &ev)) {
|
|
if (send_event(&c, p->eng, &ev) != 0) {
|
|
sp_engine_event_free(&ev);
|
|
rc = -1;
|
|
goto out;
|
|
}
|
|
sp_engine_event_free(&ev);
|
|
if (!sp_engine_busy(p->eng))
|
|
(void)sp_engine_wait(p->eng);
|
|
}
|
|
if (sp_engine_quit(p->eng) || c.quit)
|
|
break;
|
|
}
|
|
out:
|
|
abandon_turn(p->eng);
|
|
sp_buf_free(&c.in);
|
|
sp_buf_free(&c.line);
|
|
return rc;
|
|
}
|
|
|
|
/* ---------------------------------------------------------------- socket */
|
|
|
|
void
|
|
sp_proto_default_socket(char *buf, size_t cap)
|
|
{
|
|
const char *env = getenv("SPLINTER_SOCKET");
|
|
const char *home;
|
|
|
|
if (env != NULL && *env != '\0') {
|
|
snprintf(buf, cap, "%s", env);
|
|
return;
|
|
}
|
|
home = getenv("HOME");
|
|
snprintf(buf, cap, "%s/.splinter/splinter.sock",
|
|
home != NULL ? home : ".");
|
|
}
|
|
|
|
static int
|
|
same_user(int fd)
|
|
{
|
|
#if defined(SO_PEERCRED)
|
|
struct ucred cred;
|
|
socklen_t len = sizeof(cred);
|
|
|
|
if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) != 0)
|
|
return 0;
|
|
return cred.uid == getuid();
|
|
#elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) || \
|
|
defined(__APPLE__)
|
|
uid_t uid;
|
|
gid_t gid;
|
|
|
|
return getpeereid(fd, &uid, &gid) == 0 && uid == getuid();
|
|
#else
|
|
(void)fd;
|
|
return 0; /* no way to check the peer: refuse, never trust */
|
|
#endif
|
|
}
|
|
|
|
int
|
|
sp_proto_serve(const struct sp_proto_opts *opts, struct sp_buf *err)
|
|
{
|
|
struct proto p;
|
|
char def[700];
|
|
const char *where;
|
|
struct sockaddr_un addr;
|
|
struct stat st, mine;
|
|
int lfd, one = 1, have_mine = 0, rc = 0;
|
|
|
|
if (opts == NULL || opts->engine == NULL) {
|
|
sp_buf_puts(err, "no engine template");
|
|
return -1;
|
|
}
|
|
memset(&p, 0, sizeof(p));
|
|
p.tmpl = opts->engine;
|
|
if (sp_engine_open(&p.eng, p.tmpl, err) != 0) {
|
|
/* the message already says what is wrong */
|
|
return -1;
|
|
}
|
|
where = opts->socket;
|
|
if (where == NULL) {
|
|
sp_proto_default_socket(def, sizeof(def));
|
|
where = def;
|
|
}
|
|
if (strlen(where) >= sizeof(addr.sun_path)) {
|
|
sp_buf_printf(err, "socket path too long: %s", where);
|
|
sp_engine_close(p.eng);
|
|
return -1;
|
|
}
|
|
if (lstat(where, &st) == 0) {
|
|
/*
|
|
* A socket left by a dead server is ours to replace. Anything
|
|
* else at that path is somebody's file: refuse, never unlink.
|
|
* A socket somebody still answers on is a running server, and
|
|
* two writers on one conversation is exactly what this protocol
|
|
* promises not to do.
|
|
*/
|
|
int probe;
|
|
|
|
if (!S_ISSOCK(st.st_mode)) {
|
|
sp_buf_printf(err, "%s exists and is not a socket", where);
|
|
sp_engine_close(p.eng);
|
|
return -1;
|
|
}
|
|
probe = socket(AF_UNIX, SOCK_STREAM, 0);
|
|
if (probe >= 0) {
|
|
struct sockaddr_un pa;
|
|
|
|
memset(&pa, 0, sizeof(pa));
|
|
pa.sun_family = AF_UNIX;
|
|
snprintf(pa.sun_path, sizeof(pa.sun_path), "%s", where);
|
|
if (connect(probe, (struct sockaddr *)&pa,
|
|
sizeof(pa)) == 0) {
|
|
close(probe);
|
|
sp_buf_printf(err, "%s is already being served",
|
|
where);
|
|
sp_engine_close(p.eng);
|
|
return -1;
|
|
}
|
|
close(probe);
|
|
}
|
|
(void)unlink(where);
|
|
}
|
|
lfd = socket(AF_UNIX, SOCK_STREAM, 0);
|
|
if (lfd >= 0)
|
|
(void)fcntl(lfd, F_SETFD, FD_CLOEXEC);
|
|
if (lfd < 0) {
|
|
sp_buf_printf(err, "socket: %s", strerror(errno));
|
|
sp_engine_close(p.eng);
|
|
return -1;
|
|
}
|
|
(void)setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
|
|
memset(&addr, 0, sizeof(addr));
|
|
addr.sun_family = AF_UNIX;
|
|
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", where);
|
|
if (bind(lfd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
|
|
sp_buf_printf(err, "bind %s: %s", where, strerror(errno));
|
|
close(lfd);
|
|
sp_engine_close(p.eng);
|
|
return -1;
|
|
}
|
|
(void)chmod(where, 0600);
|
|
if (lstat(where, &mine) == 0)
|
|
have_mine = 1;
|
|
if (listen(lfd, 4) != 0) {
|
|
sp_buf_printf(err, "listen: %s", strerror(errno));
|
|
close(lfd);
|
|
(void)unlink(where);
|
|
sp_engine_close(p.eng);
|
|
return -1;
|
|
}
|
|
fprintf(stderr, "splinter: serving on %s\n", where);
|
|
for (;;) {
|
|
int fd = accept(lfd, NULL, NULL);
|
|
|
|
if (fd < 0) {
|
|
if (errno == EINTR)
|
|
continue;
|
|
sp_buf_printf(err, "accept: %s", strerror(errno));
|
|
break;
|
|
}
|
|
/*
|
|
* No child may inherit the listening socket or a client: the
|
|
* `run` tool forks shells with the server's descriptors, and a
|
|
* background command would keep the socket alive after exit.
|
|
*/
|
|
(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
|
|
{
|
|
/*
|
|
* A client that stops reading must not block the server
|
|
* forever: after five seconds without progress the
|
|
* write fails and the connection (and its turn) ends.
|
|
*/
|
|
struct timeval tv = { 5, 0 };
|
|
|
|
(void)setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv,
|
|
sizeof(tv));
|
|
}
|
|
if (!same_user(fd)) {
|
|
fprintf(stderr, "splinter: refused a client of another "
|
|
"user\n");
|
|
close(fd);
|
|
continue;
|
|
}
|
|
(void)serve_client(&p, fd);
|
|
close(fd);
|
|
if (p.eng == NULL || sp_engine_quit(p.eng))
|
|
break;
|
|
}
|
|
close(lfd);
|
|
/*
|
|
* Only remove the socket this server created: if another server
|
|
* replaced the path while we ran, its file must survive our exit.
|
|
*/
|
|
if (have_mine && lstat(where, &st) == 0 && S_ISSOCK(st.st_mode) &&
|
|
st.st_dev == mine.st_dev && st.st_ino == mine.st_ino)
|
|
(void)unlink(where);
|
|
rc = p.eng != NULL && sp_engine_quit(p.eng) ? 0 : -1;
|
|
sp_engine_close(p.eng);
|
|
return rc;
|
|
}
|