gateway, sessions, reconnect: splinter serves other harnesses and keeps tabs

- --openai-listen: an OpenAI-compatible /v1/chat/completions and /v1/models.
  The model gets splinter's local tools as gw_* (executed here) and the
  caller's tools under their own names (returned as tool_calls to run there).
  Local calls loop inside one request; a mixed reply runs the local calls and
  asks again. --autonomous gates mutation; beyond loopback a bearer token is
  required; stream:true answers with SSE.
- --serve keeps several sessions: sessions/open over the protocol and
  /sessions, /open in the attach screen. The server owns the engines, closes
  the old one before opening the next (plugins keep globals) and sends
  state/history after every switch. Session ids are unique per process, so two
  engines in the same second no longer share a file.
- --attach reconnects: when the server goes away the screen keeps running,
  retries every second, asks for its session by id and restores the
  transcript; a missing session falls back to the server's current one.
- transports own their context now: provider switches and close dispose it
  (a switch used to leak one per change). The idle screen repaints entries it
  drains, so a reconnect note is not invisible.
- docs/GATEWAY.md; PROTOCOL, FRONTENDS, README and the manual page describe
  the three; tests cover the gateway tools, sessions/open and a server
  restart under --attach.
This commit is contained in:
lotherk committed 2026-11-16 09:33:37 +00:00
1 parent a9f175c25b
commit 5143fcd054
32 files changed
+2642 -111

No files matched your search

+13 -10
View File
@@ -42,6 +42,16 @@
#include "usage.h"
/* /connect: the questions, one answer per line */
/* one id per engine opened in this process, even within the same second */
static unsigned g_session_seq;
static void
new_session_id(char *buf, size_t cap)
{
snprintf(buf, cap, "sess-%ld-%d-%u", (long)time(NULL), (int)getpid(),
++g_session_seq);
}
struct engine_cc {
int active;
int step;
@@ -78,7 +88,6 @@ struct sp_engine {
/* /connect */
struct engine_cc cc;
unsigned new_seq; /* /new count, for a unique id */
int quit;
/* the fleet, when asked for */
@@ -1596,13 +1605,7 @@ cmd_new(struct sp_engine *e, struct sp_buf *out)
const char *base;
memset(&e->sess, 0, sizeof(e->sess));
e->new_seq++;
if (e->new_seq == 1)
snprintf(id, sizeof(id), "sess-%ld-%d", (long)time(NULL),
(int)getpid());
else
snprintf(id, sizeof(id), "sess-%ld-%d-%u", (long)time(NULL),
(int)getpid(), e->new_seq);
new_session_id(id, sizeof(id));
base = e->base_prompt != NULL ? e->base_prompt :
e->base.system_prompt;
sp_buf_init(&serr);
@@ -1920,8 +1923,7 @@ open_session(struct sp_engine *e, const struct sp_engine_opts *o,
sp_session_latest(dir, idbuf, sizeof(idbuf)) == 0)
id = idbuf;
if (id == NULL) {
snprintf(idbuf, sizeof(idbuf), "sess-%ld-%d", (long)time(NULL),
(int)getpid());
new_session_id(idbuf, sizeof(idbuf));
id = idbuf;
}
if (sp_session_open(&e->sess, dir, id, err) != 0)
@@ -2243,6 +2245,7 @@ sp_engine_close(struct sp_engine *e)
engine_join(e);
if (e->have_swarm)
swarm_close(&e->swarm);
sp_transport_dispose(&e->ag.tr);
sp_buf_free(&e->answer);
sp_buf_free(&e->err);
sp_buf_free(&e->live);
+142
View File
@@ -0,0 +1,142 @@
/*
* splinter -- shared HTTP/1.1 request and reply helpers.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include "splinter.h"
#include "http.h"
int
sp_http_write_all(int fd, const char *buf, size_t len)
{
while (len > 0) {
ssize_t n = write(fd, buf, len);
if (n <= 0) {
if (errno == EINTR)
continue;
return -1;
}
buf += n;
len -= (size_t)n;
}
return 0;
}
const char *
sp_http_header_value(const char *hdr, const char *name)
{
const char *p;
size_t n;
if (hdr == NULL || name == NULL)
return NULL;
p = strstr(hdr, "\r\n");
n = strlen(name);
if (p == NULL)
return NULL;
while ((p = strstr(p, "\r\n")) != NULL) {
p += 2;
if (*p == '\0')
break;
if (strncasecmp(p, name, n) == 0 && p[n] == ':') {
const char *v = p + n + 1;
while (*v == ' ' || *v == '\t')
v++;
return v;
}
}
return NULL;
}
int
sp_http_bearer_is(const char *auth, const char *token)
{
size_t n;
if (auth == NULL || token == NULL)
return 0;
if (strncasecmp(auth, "Bearer ", 7) != 0)
return 0;
n = strlen(token);
if (strncmp(auth + 7, token, n) != 0)
return 0;
return auth[7 + n] == '\r' || auth[7 + n] == '\n' ||
auth[7 + n] == '\0';
}
void
sp_http_reply(int fd, int code, const char *reason, const char *type,
const char *body)
{
char hdr[512];
int n;
n = snprintf(hdr, sizeof(hdr),
"HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %zu\r\n"
"Connection: close\r\n\r\n", code, reason,
type != NULL ? type : "application/json",
strlen(body != NULL ? body : ""));
if (n > 0)
(void)sp_http_write_all(fd, hdr, (size_t)n);
(void)sp_http_write_all(fd, body != NULL ? body : "",
strlen(body != NULL ? body : ""));
}
int
sp_http_read_request(int fd, char *hdr, size_t cap, struct sp_buf *body,
size_t body_max)
{
size_t used = 0;
char *hend;
for (;;) {
ssize_t n;
if (used >= cap - 1)
return -1;
n = read(fd, hdr + used, cap - 1 - used);
if (n <= 0)
return -1;
used += (size_t)n;
hdr[used] = '\0';
if ((hend = strstr(hdr, "\r\n\r\n")) != NULL)
break;
}
{
const char *v = sp_http_header_value(hdr, "Content-Length");
long clen = v != NULL ? strtol(v, NULL, 10) : 0;
size_t have;
if (clen < 0 || (size_t)clen > body_max)
return -1;
have = used - (size_t)(hend + 4 - hdr);
if (have > (size_t)clen)
have = (size_t)clen;
if (have > 0 && sp_buf_add(body, hend + 4, have) != 0)
return -1;
while (body->len < (size_t)clen) {
char chunk[4096];
size_t want = (size_t)clen - body->len;
ssize_t n;
if (want > sizeof(chunk))
want = sizeof(chunk);
n = read(fd, chunk, want);
if (n <= 0)
return -1;
if (sp_buf_add(body, chunk, (size_t)n) != 0)
return -1;
}
}
return 0;
}
+33
View File
@@ -0,0 +1,33 @@
/*
* splinter -- the little HTTP/1.1 pieces the JSON servers share.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* Not a web framework: one request per connection, Content-Length only, one
* reply, close. That is what a local tool endpoint needs, and it keeps the
* parsing auditable. The A2A and MCP servers carry their own older copies;
* new services use this one.
*/
#ifndef SPLINTER_HTTP_H
#define SPLINTER_HTTP_H
#include <stddef.h>
struct sp_buf;
#define SP_HTTP_HDR_MAX 16384
#define SP_HTTP_BODY_MAX (4 * 1024 * 1024)
int sp_http_write_all(int fd, const char *buf, size_t len);
/* the value of a header, terminated by the CRLF of the next line */
const char *sp_http_header_value(const char *hdr, const char *name);
int sp_http_bearer_is(const char *auth, const char *token);
/* one complete reply; type is the Content-Type, body is NUL-terminated */
void sp_http_reply(int fd, int code, const char *reason, const char *type,
const char *body);
/* headers into hdr, exactly Content-Length bytes into body; 0 or -1 */
int sp_http_read_request(int fd, char *hdr, size_t cap,
struct sp_buf *body, size_t body_max);
#endif /* SPLINTER_HTTP_H */
+979
View File
@@ -0,0 +1,979 @@
/*
* splinter -- an OpenAI-compatible endpoint with tools on both sides.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* POST /v1/chat/completions a chat completion, for another harness
* GET /v1/models what this endpoint answers as
*
* Why: splinter runs where the files and the shell are. Another harness (on
* another machine) can point its OpenAI client at this endpoint and get an
* answer, without implementing the tools itself.
*
* Two kinds of tools are offered to the model in one request:
*
* gw_read, gw_write, gw_run, ... splinter's own registry. The gateway
* executes them here, on this host, and
* loops until the model has an answer.
* the caller's tools (any other returned to the caller as ordinary
* name, provided in "tools") tool_calls; the harness executes them
* where it runs and sends the results in
* the next request.
*
* The gw_ prefix is the namespace: a caller may use read/write/edit itself,
* and it cannot collide with the local ones. A caller tool that starts with
* gw_ is refused, because that name is ours.
*
* Splinter is a stateless gateway here: the conversation travels in every
* request, exactly as the OpenAI protocol says. Local gw_ calls are executed
* inside one request; a model reply that mixes local and caller calls runs
* the local ones and asks again (the caller calls come on a later step).
*
* Security: binding beyond loopback requires SPLINTER_GATEWAY_TOKEN, and the
* token is checked on every request. Mutating and destructive local tools run
* only with --autonomous; otherwise the model is told they are denied. There
* is no TLS: put it behind ssh or a tunnel when the network is not yours.
*/
#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include "splinter.h"
#include "mcp.h"
#include "config.h"
#include "http.h"
#include "log.h"
#include "openai_server.h"
#define GW_STEPS 16
#define GW_OBS_MAX (32 * 1024)
#define GW_NAME_MAX 96
#define GW_PREFIX "gw_"
static volatile sig_atomic_t g_stop;
static unsigned long g_seq;
static void
on_signal(int sig)
{
(void)sig;
g_stop = 1;
}
/* ------------------------------------------------------------- JSON out */
static void
json_dump(const mcp_json *v, struct sp_buf *out)
{
size_t i;
if (v == NULL) {
sp_buf_puts(out, "null");
return;
}
switch (v->t) {
case MCP_NULL:
sp_buf_puts(out, "null");
break;
case MCP_BOOL:
sp_buf_puts(out, v->b ? "true" : "false");
break;
case MCP_NUM:
sp_buf_printf(out, "%.17g", v->n);
break;
case MCP_STR:
sp_buf_puts(out, "\"");
(void)sp_json_escape(out, v->s != NULL ? v->s : "");
sp_buf_puts(out, "\"");
break;
case MCP_ARR:
sp_buf_puts(out, "[");
for (i = 0; i < v->count; i++) {
if (i > 0)
sp_buf_puts(out, ",");
json_dump(v->items[i], out);
}
sp_buf_puts(out, "]");
break;
case MCP_OBJ:
sp_buf_puts(out, "{");
for (i = 0; i < v->count; i++) {
if (i > 0)
sp_buf_puts(out, ",");
sp_buf_puts(out, "\"");
(void)sp_json_escape(out, v->keys[i]);
sp_buf_puts(out, "\":");
json_dump(v->items[i], out);
}
sp_buf_puts(out, "}");
break;
}
}
/* the text of a content value: a string, or the text parts of an array */
static void
content_text(const mcp_json *v, struct sp_buf *out)
{
if (v == NULL) {
sp_buf_puts(out, "");
return;
}
if (v->t == MCP_STR) {
sp_buf_puts(out, v->s != NULL ? v->s : "");
return;
}
if (v->t == MCP_ARR) {
size_t i;
for (i = 0; i < v->count; i++) {
const mcp_json *part = v->items[i];
const char *type = mcp_arg_string(part, "type");
const char *text;
if (type != NULL && strcmp(type, "text") != 0)
continue; /* an image is not text */
text = mcp_arg_string(part, "text");
if (text == NULL && part->t == MCP_STR)
text = part->s;
if (text != NULL)
sp_buf_puts(out, text);
}
}
}
/* ------------------------------------------------------------- gateway */
struct gw_local {
char *name; /* gw_<tool> */
const struct sp_tool *tool; /* the real one */
};
/* the temporary registry the upstream transport shapes its request from */
struct gw_tools {
struct sp_registry reg;
char **owned;
size_t nown, capown;
struct gw_local **locals;
size_t nlocals, caplocals;
};
static char *
own(struct gw_tools *t, const char *s)
{
char *copy = strdup(s != NULL ? s : "");
if (copy == NULL)
return NULL;
if (t->nown == t->capown) {
size_t nc = t->capown != 0 ? t->capown * 2 : 32;
char **nv = realloc(t->owned, nc * sizeof(*nv));
if (nv == NULL) {
free(copy);
return NULL;
}
t->owned = nv;
t->capown = nc;
}
t->owned[t->nown++] = copy;
return copy;
}
static void
tools_free(struct gw_tools *t)
{
size_t i;
for (i = 0; i < t->nlocals; i++) {
free(t->locals[i]->name);
free(t->locals[i]);
}
free(t->locals);
for (i = 0; i < t->nown; i++)
free(t->owned[i]);
free(t->owned);
sp_registry_free(&t->reg);
memset(t, 0, sizeof(*t));
}
static int
local_run(const char *args, struct sp_buf *out, void *ctx)
{
struct gw_local *l = ctx;
if (l == NULL || l->tool == NULL || l->tool->run == NULL) {
sp_buf_puts(out, "gateway: the local tool has no runner");
return -1;
}
return l->tool->run(args, out, l->tool->ctx);
}
/* a caller tool is never executed here; it is returned to its owner */
static int
client_run(const char *args, struct sp_buf *out, void *ctx)
{
(void)args;
(void)ctx;
sp_buf_puts(out, "gateway: this tool belongs to the caller");
return -1;
}
static int
add_caller_tools(struct gw_tools *t, const mcp_json *tools, struct sp_buf *err)
{
const mcp_json *item;
size_t i, j;
size_t n = tools != NULL ? tools->count : 0;
for (i = 0; i < n; i++) {
const mcp_json *fn, *params;
const char *name, *desc;
struct sp_buf pbuf;
struct sp_tool tool;
char *p = NULL;
item = tools->items[i];
fn = mcp_arg(item, "function");
if (fn == NULL)
fn = item; /* tolerate a flat tool object */
name = mcp_arg_string(fn, "name");
desc = mcp_arg_string(fn, "description");
if (name == NULL || *name == '\0' ||
strlen(name) >= GW_NAME_MAX) {
sp_buf_printf(err, "tool %zu has no usable name", i);
return -1;
}
if (strncmp(name, GW_PREFIX, strlen(GW_PREFIX)) == 0) {
sp_buf_printf(err, "tool name '%s' is reserved: the "
"gateway's local tools live under %s", name,
GW_PREFIX);
return -1;
}
for (j = 0; j < t->reg.len; j++) {
if (t->reg.tools[j].name != NULL &&
strcmp(t->reg.tools[j].name, name) == 0) {
sp_buf_printf(err, "tool '%s' appears twice",
name);
return -1;
}
}
params = mcp_arg(fn, "parameters");
if (params != NULL) {
sp_buf_init(&pbuf);
json_dump(params, &pbuf);
p = own(t, pbuf.p != NULL ? pbuf.p : "{}");
sp_buf_free(&pbuf);
}
memset(&tool, 0, sizeof(tool));
tool.name = own(t, name);
tool.description = own(t, desc != NULL ? desc :
"a tool of the calling harness");
tool.params = p;
tool.auth = SP_AUTH_READ; /* never runs here */
tool.run = client_run;
tool.ctx = NULL;
if (tool.name == NULL || tool.description == NULL ||
sp_registry_add(&t->reg, &tool) != 0) {
sp_buf_puts(err, "cannot register the caller's tools");
return -1;
}
}
return 0;
}
static int
add_local_tools(struct gw_tools *t, const struct sp_registry *real,
struct sp_buf *err)
{
const struct sp_tool *tv;
size_t i, n;
tv = sp_registry_tools(real, &n);
for (i = 0; i < n; i++) {
const struct sp_tool *r = &tv[i];
struct gw_local *l;
struct sp_tool tool;
char name[GW_NAME_MAX], desc[512];
if (r->name == NULL || *r->name == '\0')
continue;
snprintf(name, sizeof(name), "%s%s", GW_PREFIX, r->name);
snprintf(desc, sizeof(desc), "Runs %s on the splinter host: %s",
r->name, r->description != NULL ? r->description : "");
l = calloc(1, sizeof(*l));
if (l == NULL) {
sp_buf_puts(err, "out of memory");
return -1;
}
l->name = strdup(name);
if (l->name == NULL) {
free(l);
sp_buf_puts(err, "out of memory");
return -1;
}
l->tool = r;
if (t->nlocals == t->caplocals) {
size_t nc = t->caplocals != 0 ?
t->caplocals * 2 : 32;
struct gw_local **nv = realloc(t->locals,
nc * sizeof(*nv));
if (nv == NULL) {
free(l->name);
free(l);
sp_buf_puts(err, "out of memory");
return -1;
}
t->locals = nv;
t->caplocals = nc;
}
t->locals[t->nlocals++] = l;
memset(&tool, 0, sizeof(tool));
tool.name = l->name;
tool.description = own(t, desc);
tool.params = r->params != NULL ? own(t, r->params) : NULL;
tool.auth = SP_AUTH_READ; /* the gateway checks the class */
tool.run = local_run;
tool.ctx = l;
if (tool.description == NULL ||
sp_registry_add(&t->reg, &tool) != 0) {
sp_buf_puts(err, "cannot register the gateway tools");
return -1;
}
}
return 0;
}
/* messages: OpenAI's view -> splinter's conversation */
static int
parse_messages(const mcp_json *req, struct sp_conv *conv, struct sp_buf *err)
{
const mcp_json *msgs = mcp_arg(req, "messages");
size_t i;
if (msgs == NULL || msgs->t != MCP_ARR || msgs->count == 0) {
sp_buf_puts(err, "messages is required");
return -1;
}
for (i = 0; i < msgs->count; i++) {
const mcp_json *m = msgs->items[i];
const char *role = mcp_arg_string(m, "role");
const mcp_json *calls = mcp_arg(m, "tool_calls");
struct sp_msg msg;
struct sp_buf content, calls_json;
if (role == NULL) {
sp_buf_printf(err, "message %zu has no role", i);
return -1;
}
if (strcmp(role, "developer") == 0)
role = "system";
if (strcmp(role, "system") != 0 && strcmp(role, "user") != 0 &&
strcmp(role, "assistant") != 0 &&
strcmp(role, "tool") != 0) {
sp_buf_printf(err, "message %zu has role '%s'", i, role);
return -1;
}
if (sp_buf_init(&content) != 0)
return -1;
content_text(mcp_arg(m, "content"), &content);
memset(&msg, 0, sizeof(msg));
msg.role = (char *)role;
msg.content = content.p != NULL ? content.p : "";
msg.call_id = (char *)mcp_arg_string(m, "tool_call_id");
msg.name = (char *)mcp_arg_string(m, "name");
if (calls != NULL) {
sp_buf_init(&calls_json);
json_dump(calls, &calls_json);
msg.calls = calls_json.p;
}
if (sp_conv_add(conv, &msg) != 0) {
sp_buf_free(&content);
if (calls != NULL)
sp_buf_free(&calls_json);
sp_buf_puts(err, "out of memory");
return -1;
}
if (calls != NULL)
sp_buf_free(&calls_json);
sp_buf_free(&content);
}
return 0;
}
/* a normalized tool_calls array from a reply, for the caller */
static void
reply_calls_json(const struct sp_reply *r, struct sp_buf *out)
{
size_t i;
sp_buf_puts(out, "[");
for (i = 0; i < r->ncalls; i++) {
const struct sp_toolcall *c = &r->calls[i];
if (i > 0)
sp_buf_puts(out, ",");
sp_buf_puts(out, "{\"index\":");
sp_buf_printf(out, "%zu", i);
sp_buf_puts(out, ",\"id\":\"");
(void)sp_json_escape(out, c->id != NULL ? c->id : "call");
sp_buf_puts(out, "\",\"type\":\"function\",\"function\":{\"name\":\"");
(void)sp_json_escape(out, c->name != NULL ? c->name : "");
sp_buf_puts(out, "\",\"arguments\":\"");
(void)sp_json_escape(out, c->args != NULL ? c->args : "");
sp_buf_puts(out, "\"}}");
}
sp_buf_puts(out, "]");
}
/* the assistant turn with only the local calls; every one gets its result */
static void
append_assistant_turn(struct sp_conv *conv, const struct sp_reply *rep,
struct sp_buf *local_calls)
{
struct sp_msg m;
memset(&m, 0, sizeof(m));
m.role = "assistant";
m.content = rep->content != NULL ? rep->content : "";
m.calls = local_calls->p;
(void)sp_conv_add(conv, &m);
}
static void
append_tool_result(struct sp_conv *conv, const struct sp_toolcall *c,
const char *obs)
{
struct sp_msg m;
memset(&m, 0, sizeof(m));
m.role = "tool";
m.call_id = c->id;
m.name = c->name;
m.content = (char *)(obs != NULL ? obs : "");
(void)sp_conv_add(conv, &m);
}
/* the local calls only, so the assistant turn needs results for every call */
static void
local_calls_json(const struct sp_reply *rep, struct sp_buf *out)
{
size_t i;
int first = 1;
sp_buf_puts(out, "[");
for (i = 0; i < rep->ncalls; i++) {
const struct sp_toolcall *c = &rep->calls[i];
if (c->name == NULL ||
strncmp(c->name, GW_PREFIX, strlen(GW_PREFIX)) != 0)
continue;
if (!first)
sp_buf_puts(out, ",");
first = 0;
sp_buf_puts(out, "{\"id\":\"");
(void)sp_json_escape(out, c->id != NULL ? c->id : "call");
sp_buf_puts(out, "\",\"type\":\"function\",\"function\":"
"{\"name\":\"");
(void)sp_json_escape(out, c->name);
sp_buf_puts(out, "\",\"arguments\":\"");
(void)sp_json_escape(out, c->args != NULL ? c->args : "{}");
sp_buf_puts(out, "\"}}");
}
sp_buf_puts(out, "]");
}
/* one local tool; returns 0 with the observation in out */
static int
run_local(const struct sp_gateway_opts *o, const char *gw_name,
const char *args, struct sp_buf *out)
{
const struct sp_tool *t;
const char *name = gw_name + strlen(GW_PREFIX);
t = sp_registry_find(o->reg, name);
if (t == NULL) {
sp_buf_printf(out, "gateway: no local tool '%s'", name);
return -1;
}
if (t->auth != SP_AUTH_READ && !o->autonomous) {
sp_buf_puts(out, "denied: the gateway runs mutating and "
"destructive tools only with --autonomous");
return 0;
}
if (t->run == NULL) {
sp_buf_printf(out, "gateway: '%s' has no runner", name);
return -1;
}
if (sp_log_active())
sp_logf("gateway", "local tool %s", name);
return t->run(args, out, t->ctx);
}
static struct sp_transport
make_transport(const struct sp_gateway_opts *o, struct gw_tools *t)
{
const char *key = (o->key_env != NULL && *o->key_env != '\0') ?
getenv(o->key_env) : NULL;
const char *hto = getenv("SPLINTER_HTTP_TIMEOUT");
long timeout = hto != NULL && *hto != '\0' ?
strtol(hto, NULL, 10) : 0;
if (timeout <= 0)
timeout = 900;
if (o->kind != NULL && strcmp(o->kind, "anthropic") == 0)
return sp_anthropic_transport(o->endpoint, o->model, key,
&t->reg, timeout);
return sp_openai_transport(o->endpoint, o->model, key, &t->reg,
timeout);
}
static void
error_json(struct sp_buf *b, const char *msg)
{
sp_buf_clear(b);
sp_buf_puts(b, "{\"error\":{\"message\":\"");
(void)sp_json_escape(b, msg != NULL ? msg : "error");
sp_buf_puts(b, "\",\"type\":\"invalid_request_error\"}}");
}
static void
completion_json(struct sp_buf *out, const char *id, const char *model,
const char *content, const struct sp_reply *rep, int tool_calls)
{
char created[32];
snprintf(created, sizeof(created), "%ld", (long)time(NULL));
sp_buf_clear(out);
sp_buf_puts(out, "{\"id\":\"");
(void)sp_json_escape(out, id);
sp_buf_puts(out, "\",\"object\":\"chat.completion\",\"created\":");
sp_buf_puts(out, created);
sp_buf_puts(out, ",\"model\":\"");
(void)sp_json_escape(out, model != NULL ? model : "");
sp_buf_puts(out, "\",\"choices\":[{\"index\":0,\"message\":{\"role\":"
"\"assistant\",\"content\":\"");
(void)sp_json_escape(out, content != NULL ? content : "");
sp_buf_puts(out, "\"");
if (tool_calls) {
struct sp_buf calls;
sp_buf_init(&calls);
reply_calls_json(rep, &calls);
sp_buf_puts(out, ",\"tool_calls\":");
sp_buf_puts(out, calls.p != NULL ? calls.p : "[]");
sp_buf_free(&calls);
}
sp_buf_puts(out, "},\"finish_reason\":\"");
sp_buf_puts(out, tool_calls ? "tool_calls" : "stop");
sp_buf_puts(out, "\"}],\"usage\":{\"prompt_tokens\":");
sp_buf_printf(out, "%ld,\"completion_tokens\":%ld,\"total_tokens\":%ld}}",
rep != NULL ? rep->tokens_in : 0,
rep != NULL ? rep->tokens_out : 0,
rep != NULL ? rep->tokens_in + rep->tokens_out : 0);
}
static void
sse_event(struct sp_buf *out, const char *payload)
{
sp_buf_puts(out, "data: ");
sp_buf_puts(out, payload);
sp_buf_puts(out, "\n\n");
}
static void
completion_sse(struct sp_buf *out, const char *id, const char *model,
const char *content, const struct sp_reply *rep, int tool_calls)
{
char created[32];
snprintf(created, sizeof(created), "%ld", (long)time(NULL));
sp_buf_clear(out);
{
struct sp_buf chunk;
sp_buf_init(&chunk);
sp_buf_printf(&chunk, "{\"id\":\"%s\",\"object\":"
"\"chat.completion.chunk\",\"created\":%s,\"model\":\"",
id, created);
(void)sp_json_escape(&chunk, model != NULL ? model : "");
sp_buf_puts(&chunk, "\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\"");
if (tool_calls) {
struct sp_buf calls;
sp_buf_init(&calls);
reply_calls_json(rep, &calls);
sp_buf_puts(&chunk, ",\"tool_calls\":");
sp_buf_puts(&chunk, calls.p != NULL ? calls.p : "[]");
sp_buf_free(&calls);
} else {
sp_buf_puts(&chunk, ",\"content\":\"");
(void)sp_json_escape(&chunk, content != NULL ? content : "");
sp_buf_puts(&chunk, "\"");
}
sp_buf_puts(&chunk, "},\"finish_reason\":null}]}");
sse_event(out, chunk.p != NULL ? chunk.p : "{}");
sp_buf_free(&chunk);
}
{
struct sp_buf chunk;
sp_buf_init(&chunk);
sp_buf_printf(&chunk, "{\"id\":\"%s\",\"object\":"
"\"chat.completion.chunk\",\"created\":%s,\"model\":\"",
id, created);
(void)sp_json_escape(&chunk, model != NULL ? model : "");
sp_buf_printf(&chunk, "\",\"choices\":[{\"index\":0,\"delta\":{},"
"\"finish_reason\":\"%s\"}]}",
tool_calls ? "tool_calls" : "stop");
sse_event(out, chunk.p != NULL ? chunk.p : "{}");
sp_buf_free(&chunk);
}
sse_event(out, "[DONE]");
}
/* ------------------------------------------------------------ one request */
static void
handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
{
mcp_json *req;
const mcp_json *msgtools;
const char *req_model;
struct sp_conv conv;
struct gw_tools tools;
struct sp_buf err, answer, payload;
int stream;
unsigned long seq = ++g_seq;
char id[80];
const char *model;
req = mcp_parse(body);
if (req == NULL) {
sp_buf_init(&payload);
error_json(&payload, "the request is not JSON");
sp_http_reply(fd, 400, "Bad Request", "application/json",
payload.p);
sp_buf_free(&payload);
return;
}
memset(&conv, 0, sizeof(conv));
memset(&tools, 0, sizeof(tools));
sp_conv_init(&conv);
if (sp_buf_init(&err) != 0 || sp_buf_init(&answer) != 0 ||
sp_buf_init(&payload) != 0) {
mcp_json_free(req);
return;
}
if (parse_messages(req, &conv, &err) != 0)
goto bad;
msgtools = mcp_arg(req, "tools");
if (msgtools != NULL && msgtools->t != MCP_ARR) {
sp_buf_puts(&err, "tools must be an array");
goto bad;
}
if (add_caller_tools(&tools, msgtools, &err) != 0)
goto bad;
if (add_local_tools(&tools, o->reg, &err) != 0)
goto bad;
req_model = mcp_arg_string(req, "model");
model = req_model != NULL && *req_model != '\0' ? req_model : o->model;
stream = mcp_arg_bool(req, "stream", 0);
snprintf(id, sizeof(id), "chatcmpl-%ld-%lu", (long)getpid(), seq);
{
size_t max_steps = o->max_steps > 0 ? o->max_steps : GW_STEPS;
int step;
for (step = 0; step < (int)max_steps; step++) {
struct sp_transport tr = make_transport(o, &tools);
struct sp_reply rep;
struct sp_buf uerr;
size_t i, nlocal = 0, nclient = 0;
int rc;
if (tr.send == NULL) {
sp_buf_puts(&err, "cannot build the upstream "
"transport");
goto upstream_bad;
}
memset(&rep, 0, sizeof(rep));
sp_buf_init(&uerr);
rc = tr.send(tr.ctx, &conv, &rep, &uerr);
sp_transport_dispose(&tr);
if (rc != 0) {
sp_buf_printf(&err, "upstream: %s",
uerr.p != NULL && uerr.len > 0 ? uerr.p :
"no answer");
sp_buf_free(&uerr);
sp_reply_free(&rep);
goto upstream_bad;
}
sp_buf_free(&uerr);
for (i = 0; i < rep.ncalls; i++) {
if (rep.calls[i].name != NULL &&
strncmp(rep.calls[i].name, GW_PREFIX,
strlen(GW_PREFIX)) == 0)
nlocal++;
else
nclient++;
}
if (nlocal == 0 && nclient == 0) {
/* the answer */
sp_buf_clear(&answer);
if (rep.content != NULL)
sp_buf_puts(&answer, rep.content);
if (stream)
completion_sse(&payload, id, model,
answer.p, &rep, 0);
else
completion_json(&payload, id, model,
answer.p, &rep, 0);
sp_reply_free(&rep);
break;
}
if (nlocal > 0) {
struct sp_buf local;
/*
* The local tools run here. A reply that also
* asks for caller tools is asked again after
* the local results; the caller sees its own
* calls on a later step.
*/
sp_buf_init(&local);
local_calls_json(&rep, &local);
append_assistant_turn(&conv, &rep, &local);
sp_buf_free(&local);
for (i = 0; i < rep.ncalls; i++) {
struct sp_buf obs;
const char *nm = rep.calls[i].name;
if (nm == NULL ||
strncmp(nm, GW_PREFIX,
strlen(GW_PREFIX)) != 0)
continue;
sp_buf_init(&obs);
(void)run_local(o, nm,
rep.calls[i].args != NULL ?
rep.calls[i].args : "{}", &obs);
if (obs.len > GW_OBS_MAX) {
obs.p[GW_OBS_MAX] = '\0';
obs.len = GW_OBS_MAX;
sp_buf_puts(&obs, "\n[... "
"truncated]");
}
append_tool_result(&conv, &rep.calls[i],
obs.p != NULL ? obs.p : "");
sp_buf_free(&obs);
}
sp_reply_free(&rep);
continue;
}
/*
* Only the caller's tools: return them. It runs them
* where it lives and sends the results next time.
*/
sp_buf_clear(&answer);
if (rep.content != NULL)
sp_buf_puts(&answer, rep.content);
if (stream)
completion_sse(&payload, id, model, answer.p,
&rep, 1);
else
completion_json(&payload, id, model, answer.p,
&rep, 1);
sp_reply_free(&rep);
break;
}
if (step == (int)max_steps) {
sp_buf_printf(&err, "more than %zu gateway tool rounds",
max_steps);
goto upstream_bad;
}
}
sp_http_reply(fd, 200, "OK", stream ? "text/event-stream" :
"application/json", payload.p != NULL ? payload.p : "{}");
goto out;
bad:
error_json(&payload, err.p != NULL ? err.p : "bad request");
sp_http_reply(fd, 400, "Bad Request", "application/json", payload.p);
goto out;
upstream_bad:
error_json(&payload, err.p != NULL ? err.p : "upstream failed");
sp_http_reply(fd, 502, "Bad Gateway", "application/json", payload.p);
out:
sp_buf_free(&payload);
sp_buf_free(&answer);
sp_buf_free(&err);
tools_free(&tools);
sp_conv_free(&conv);
mcp_json_free(req);
}
static void
handle_models(int fd, const struct sp_gateway_opts *o)
{
struct sp_buf b;
sp_buf_init(&b);
sp_buf_puts(&b, "{\"object\":\"list\",\"data\":[{\"id\":\"");
(void)sp_json_escape(&b, o->model != NULL ? o->model : "splinter");
sp_buf_puts(&b, "\",\"object\":\"model\",\"created\":0,"
"\"owned_by\":\"splinter\"}]}");
sp_http_reply(fd, 200, "OK", "application/json", b.p);
sp_buf_free(&b);
}
/* ------------------------------------------------------------- the server */
static void
serve_one(int fd, const struct sp_gateway_opts *o, const char *token)
{
char hdr[SP_HTTP_HDR_MAX], method[16], path[256];
struct sp_buf body, payload;
const char *p;
size_t n;
if (sp_buf_init(&body) != 0)
return;
if (sp_http_read_request(fd, hdr, sizeof(hdr), &body,
SP_HTTP_BODY_MAX) != 0) {
sp_buf_init(&payload);
error_json(&payload, "cannot read the request");
sp_http_reply(fd, 400, "Bad Request", "application/json",
payload.p);
sp_buf_free(&payload);
sp_buf_free(&body);
return;
}
if (token != NULL) {
const char *auth = sp_http_header_value(hdr, "Authorization");
if (!sp_http_bearer_is(auth, token)) {
sp_buf_init(&payload);
error_json(&payload, "missing or wrong bearer token");
sp_http_reply(fd, 401, "Unauthorized", "application/json",
payload.p);
sp_buf_free(&payload);
sp_buf_free(&body);
return;
}
}
method[0] = path[0] = '\0';
p = hdr;
n = 0;
while (*p != '\0' && *p != ' ' && n + 1 < sizeof(method))
method[n++] = *p++;
method[n] = '\0';
while (*p == ' ')
p++;
n = 0;
while (*p != '\0' && *p != ' ' && n + 1 < sizeof(path))
path[n++] = *p++;
path[n] = '\0';
if (strcmp(method, "GET") == 0 &&
(strcmp(path, "/v1/models") == 0 ||
strcmp(path, "/models") == 0)) {
handle_models(fd, o);
} else if (strcmp(method, "POST") == 0 &&
(strcmp(path, "/v1/chat/completions") == 0 ||
strcmp(path, "/chat/completions") == 0)) {
handle_chat(fd, o, body.p != NULL ? body.p : "");
} else {
sp_buf_init(&payload);
error_json(&payload, "no such route");
sp_http_reply(fd, 404, "Not Found", "application/json",
payload.p);
sp_buf_free(&payload);
}
sp_buf_free(&body);
}
int
sp_openai_serve(const struct sp_gateway_opts *o, struct sp_buf *err)
{
struct sockaddr_in addr;
int s, one = 1;
struct sigaction sa;
const char *token;
if (o == NULL || o->reg == NULL || o->endpoint == NULL ||
o->model == NULL) {
sp_buf_puts(err, "gateway: no registry, endpoint or model");
return -1;
}
token = o->token != NULL && *o->token != '\0' ? o->token : NULL;
if (token == NULL && strncmp(o->ip != NULL ? o->ip : "127.",
"127.", 4) != 0) {
sp_buf_puts(err, "gateway: beyond loopback it needs "
"SPLINTER_GATEWAY_TOKEN: gw_run would give the network the "
"shell of this user");
return -1;
}
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0) {
sp_buf_printf(err, "gateway: socket: %s", strerror(errno));
return -1;
}
(void)setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons((unsigned short)o->port);
if (inet_pton(AF_INET, o->ip != NULL ? o->ip : "127.0.0.1",
&addr.sin_addr) != 1) {
sp_buf_printf(err, "gateway: '%s' is not an address", o->ip);
close(s);
return -1;
}
if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
sp_buf_printf(err, "gateway: bind %s:%d: %s",
o->ip != NULL ? o->ip : "127.0.0.1", o->port,
strerror(errno));
close(s);
return -1;
}
if (listen(s, 8) != 0) {
sp_buf_printf(err, "gateway: listen: %s", strerror(errno));
close(s);
return -1;
}
memset(&sa, 0, sizeof(sa));
sa.sa_handler = on_signal;
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
fprintf(stderr, "splinter: OpenAI gateway on http://%s:%d/v1 "
"(model %s)\n", o->ip != NULL ? o->ip : "127.0.0.1", o->port,
o->model);
while (!g_stop) {
int fd = accept(s, NULL, NULL);
if (fd < 0) {
if (errno == EINTR)
continue;
sp_buf_printf(err, "gateway: accept: %s",
strerror(errno));
break;
}
(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
serve_one(fd, o, token);
close(fd);
}
close(s);
return 0;
}
+34
View File
@@ -0,0 +1,34 @@
/*
* splinter -- the OpenAI-compatible endpoint for another harness.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* The server lives in openai_server.c; this is what main starts it with.
*/
#ifndef SPLINTER_OPENAI_SERVER_H
#define SPLINTER_OPENAI_SERVER_H
#include <stddef.h>
struct sp_registry;
struct sp_config;
struct sp_buf;
struct sp_gateway_opts {
const char *ip;
int port;
const char *token; /* SPLINTER_GATEWAY_TOKEN, may be NULL */
int autonomous; /* local mutate/destructive tools */
size_t max_steps; /* gateway tool rounds, 0: 16 */
struct sp_registry *reg; /* splinter's own tools */
struct sp_config *conf;
const char *endpoint; /* upstream */
const char *model;
const char *key_env;
const char *kind; /* "anthropic", or NULL */
};
int sp_openai_serve(const struct sp_gateway_opts *, struct sp_buf *err);
#endif /* SPLINTER_OPENAI_SERVER_H */
+5 -2
View File
@@ -210,12 +210,15 @@ sp_provider_apply(struct sp_agent *ag, const char *kind, const char *endpoint,
}
if (key_env != NULL && *key_env != '\0')
key = getenv(key_env);
if (kind != NULL && strcmp(kind, "anthropic") == 0)
if (kind != NULL && strcmp(kind, "anthropic") == 0) {
sp_transport_dispose(&ag->tr);
ag->tr = sp_anthropic_transport(endpoint, model, key, ag->reg,
PROVIDER_TIMEOUT_S);
else
} else {
sp_transport_dispose(&ag->tr);
ag->tr = sp_openai_transport(endpoint, model, key, ag->reg,
PROVIDER_TIMEOUT_S);
}
sp_provider_identify(&ag->tr, endpoint, key);
return 0;
}
+48
View File
@@ -21,6 +21,7 @@
#include "mcp.h"
#include "log.h"
#include <dirent.h>
#include <stdlib.h>
#include <sys/stat.h>
static int
@@ -121,6 +122,53 @@ write_all(int fd, const char *p, size_t n)
return 0;
}
static int
brief_cmp(const void *a, const void *b)
{
const struct sp_session_brief *x = a, *y = b;
if (x->mtime != y->mtime)
return x->mtime < y->mtime ? 1 : -1;
return strcmp(x->id, y->id);
}
int
sp_session_list(const char *dir, struct sp_session_brief *v, size_t max)
{
DIR *d;
struct dirent *e;
size_t n = 0;
if (dir == NULL || v == NULL || max == 0)
return 0;
d = opendir(dir);
if (d == NULL)
return -1;
while ((e = readdir(d)) != NULL && n < max) {
char path[800], id[64];
size_t len;
struct stat st;
len = strlen(e->d_name);
if (len <= 6 || strcmp(e->d_name + len - 6, ".jsonl") != 0)
continue;
if (len - 6 >= sizeof(id))
continue;
memcpy(id, e->d_name, len - 6);
id[len - 6] = '\0';
snprintf(path, sizeof(path), "%s/%s", dir, e->d_name);
if (stat(path, &st) != 0)
continue;
snprintf(v[n].id, sizeof(v[n].id), "%s", id);
v[n].mtime = (long)st.st_mtime;
v[n].bytes = (size_t)st.st_size;
n++;
}
closedir(d);
qsort(v, n, sizeof(*v), brief_cmp);
return (int)n;
}
int
sp_session_append(const struct sp_session_info *info, const char *role,
const char *text, struct sp_buf *err)
+10
View File
@@ -56,6 +56,16 @@ sp_endpoint_url(const char *endpoint, const char *route, char *out,
return out;
}
void
sp_transport_dispose(struct sp_transport *t)
{
if (t == NULL)
return;
if (t->free != NULL)
t->free(t->ctx);
memset(t, 0, sizeof(*t));
}
int
sp_mock_init(struct sp_mock *m)
{
+7
View File
@@ -532,6 +532,12 @@ out:
return rc;
}
static void
anthropic_free(void *ctx)
{
free(ctx);
}
struct sp_transport
sp_anthropic_transport(const char *url, const char *model, const char *api_key,
const struct sp_registry *reg, long timeout_s)
@@ -552,5 +558,6 @@ sp_anthropic_transport(const char *url, const char *model, const char *api_key,
t.send = as_send;
t.send_stream = as_stream;
t.ctx = ctx;
t.free = anthropic_free;
return t;
}
+7
View File
@@ -603,6 +603,12 @@ out:
return rc;
}
static void
openai_free(void *ctx)
{
free(ctx);
}
struct sp_transport
sp_openai_transport(const char *url, const char *model, const char *api_key,
const struct sp_registry *reg, long timeout_s)
@@ -628,5 +634,6 @@ sp_openai_transport(const char *url, const char *model, const char *api_key,
t.send = openai_send;
t.send_stream = openai_stream;
t.ctx = ctx;
t.free = openai_free;
return t;
}
+57 -2
View File
@@ -1529,8 +1529,13 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input,
add_entry(s, "splinter", msg);
got = 1;
}
if (got)
draw_history(s);
/*
* A note from the engine (reconnecting) is an
* entry like any other; redraw after draining,
* not only when a widget had something to say.
*/
(void)got;
draw_history(s);
}
draw_sidebar(s, SESS_ID(be), SESS_DIR(be), host);
if (locked) {
@@ -1677,6 +1682,11 @@ ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input,
char matches[32][64];
int nm = be->command_names(be->ctx, matches,
32);
if (nm < 32)
snprintf(matches[nm++], 64, "sessions");
if (nm < 32)
snprintf(matches[nm++], 64, "open");
const char *prefix = input + 1;
size_t plen = strlen(prefix);
char *m[32];
@@ -2191,6 +2201,19 @@ ui_turn(struct ui_state *s, const char *text)
return rc;
}
static void
session_line(void *cbctx, const char *id, int current, long mtime)
{
struct sp_buf *b = cbctx;
struct tm tm;
char when[32] = "";
time_t t = (time_t)mtime;
if (localtime_r(&t, &tm) != NULL)
strftime(when, sizeof(when), "%Y-%m-%d %H:%M", &tm);
sp_buf_printf(b, "%c %-32s %s\n", current ? '*' : ' ', id, when);
}
static void
history_entry(void *cbctx, const char *role, const char *text)
{
@@ -2291,6 +2314,38 @@ sp_ui_run(const struct ui_backend *be, const char *theme_name)
continue;
if (sp_buf_init(&reply) != 0)
break;
if (strcmp(input, "/sessions") == 0) {
struct sp_buf list;
if (sp_buf_init(&list) == 0) {
if (be->sessions(be->ctx, session_line,
&list) == 0)
sp_buf_puts(&list,
sp_t("ui.no_sessions"));
add_entry(&s, "splinter",
list.p != NULL ? list.p : "");
sp_buf_free(&list);
}
continue;
}
if (strncmp(input, "/open ", 6) == 0 && input[6] != '\0') {
struct sp_buf err;
if (sp_buf_init(&err) == 0) {
if (be->open_session(be->ctx, input + 6,
&err) == 0) {
drain_idle(&s);
sync_state(&s);
add_entry(&s, "splinter",
sp_t("ui.session_opened"));
} else
add_entry(&s, "error",
err.p != NULL ? err.p :
"cannot open the session");
sp_buf_free(&err);
}
continue;
}
kind = be->input(be->ctx, input, &reply);
if (kind == SP_INPUT_HANDLED) {
/*
+232 -23
View File
@@ -13,6 +13,7 @@
* 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>
@@ -40,6 +41,12 @@ struct client {
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
@@ -94,6 +101,48 @@ 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)
@@ -382,6 +431,146 @@ fold_pending_steer(struct client *c, struct sp_engine *eng, struct sp_buf *promp
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_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;
}
static int
valid_session_id(const char *id)
{
size_t i, n;
if (id == NULL || *id == '\0')
return 0;
n = strlen(id);
if (n >= sizeof(((struct sp_session_brief *)0)->id))
return 0;
for (i = 0; i < n; i++)
if (!isalnum((unsigned char)id[i]) && id[i] != '-' &&
id[i] != '_' && id[i] != '.')
return 0;
return strstr(id, "..") == NULL;
}
/*
* Switch this connection to another session. The old engine is closed before
* the new one opens: plugins keep globals, and one plugin instance at a time is
* the only rule that holds. If the new open fails, the old session is opened
* again so the client is not left without one.
*/
static int
proto_open(struct client *c, struct proto *p, const char *id, int is_new)
{
struct sp_engine_opts o = *p->tmpl;
struct sp_engine *old = p->eng, *ne = NULL;
char keep[64], path[800];
struct sp_buf err;
int rc;
if (sp_engine_busy(old)) {
(void)send_error(c, "a turn is running");
return 0;
}
snprintf(keep, sizeof(keep), "%s", sp_engine_session_id(old));
if (!is_new && id != NULL && strcmp(id, "last") != 0 &&
strcmp(id, "new") != 0) {
if (!valid_session_id(id)) {
(void)send_error(c, "invalid session id");
return 0;
}
snprintf(path, sizeof(path), "%s/%s.jsonl",
sp_engine_state_dir(old), id);
if (access(path, R_OK) != 0) {
(void)send_error(c, "no such session");
return 0;
}
}
if (is_new || (id != NULL && strcmp(id, "new") == 0)) {
o.session_id = NULL;
o.resume = 0;
o.continue_last = 0;
} else if (id == NULL || strcmp(id, "last") == 0) {
o.session_id = NULL;
o.resume = 1;
o.continue_last = 0;
} else {
o.session_id = id;
o.resume = 1;
o.continue_last = 0;
}
p->eng = NULL;
sp_engine_close(old);
sp_buf_init(&err);
rc = sp_engine_open(&ne, &o, &err);
if (rc != 0) {
struct sp_engine_opts back = *p->tmpl;
struct sp_buf berr;
int brc;
sp_buf_init(&berr);
back.session_id = keep;
back.resume = 1;
back.continue_last = 0;
brc = sp_engine_open(&ne, &back, &berr);
p->eng = ne;
(void)send_error(c, err.p != NULL ? err.p :
"cannot open the session");
if (brc != 0)
(void)send_error(c, berr.p != NULL ? berr.p :
"and the previous session is gone too");
sp_buf_free(&berr);
sp_buf_free(&err);
return 0;
}
p->eng = ne;
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 */
/*
@@ -390,8 +579,9 @@ fold_pending_steer(struct client *c, struct sp_engine *eng, struct sp_buf *promp
* pump running while the engine works.
*/
static int
handle_line(struct client *c, struct sp_engine *eng, const char *line)
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;
@@ -519,6 +709,11 @@ handle_line(struct client *c, struct sp_engine *eng, const char *line)
(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
@@ -601,7 +796,7 @@ abandon_turn(struct sp_engine *eng)
/* the whole life of one connected client */
static int
serve_client(struct sp_engine *eng, int fd)
serve_client(struct proto *p, int fd)
{
struct client c;
struct sp_buf b;
@@ -615,12 +810,8 @@ serve_client(struct sp_engine *eng, int fd)
sp_buf_free(&c.line);
return -1;
}
ev_start(&b, "ready");
ev_num(&b, "protocol", SP_PROTO_VERSION);
ev_str(&b, "version", SP_VERSION);
sp_buf_puts(&b, "}");
if (send_line(&c, &b) != 0 ||
send_state(&c, eng, "state") != 0) {
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);
@@ -675,7 +866,7 @@ serve_client(struct sp_engine *eng, int fd)
c.in.p[c.in.len] = '\0';
if (c.line.len == 0)
continue;
if (handle_line(&c, eng, c.line.p) != 0) {
if (handle_line(&c, p, c.line.p) != 0) {
rc = -1;
goto out;
}
@@ -683,21 +874,21 @@ serve_client(struct sp_engine *eng, int fd)
break;
}
/* and every event the engine produced since the last tick */
while (sp_engine_poll(eng, &ev)) {
if (send_event(&c, eng, &ev) != 0) {
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(eng))
(void)sp_engine_wait(eng);
if (!sp_engine_busy(p->eng))
(void)sp_engine_wait(p->eng);
}
if (sp_engine_quit(eng) || c.quit)
if (sp_engine_quit(p->eng) || c.quit)
break;
}
out:
abandon_turn(eng);
abandon_turn(p->eng);
sp_buf_free(&c.in);
sp_buf_free(&c.line);
return rc;
@@ -743,22 +934,33 @@ same_user(int fd)
}
int
sp_proto_serve(struct sp_engine *eng, const char *path, struct sp_buf *err)
sp_proto_serve(const struct sp_proto_opts *opts, struct sp_buf *err)
{
char def[700];
const char *where = path;
struct proto p;
char def[700];
const char *where;
struct sockaddr_un addr;
struct stat st, mine;
int lfd, one = 1, have_mine = 0;
int lfd, one = 1, have_mine = 0, rc = 0;
if (eng == NULL)
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) {
@@ -773,6 +975,7 @@ sp_proto_serve(struct sp_engine *eng, const char *path, struct sp_buf *err)
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);
@@ -787,6 +990,7 @@ sp_proto_serve(struct sp_engine *eng, const char *path, struct sp_buf *err)
close(probe);
sp_buf_printf(err, "%s is already being served",
where);
sp_engine_close(p.eng);
return -1;
}
close(probe);
@@ -798,6 +1002,7 @@ sp_proto_serve(struct sp_engine *eng, const char *path, struct sp_buf *err)
(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));
@@ -807,6 +1012,7 @@ sp_proto_serve(struct sp_engine *eng, const char *path, struct sp_buf *err)
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);
@@ -816,6 +1022,7 @@ sp_proto_serve(struct sp_engine *eng, const char *path, struct sp_buf *err)
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);
@@ -851,9 +1058,9 @@ sp_proto_serve(struct sp_engine *eng, const char *path, struct sp_buf *err)
close(fd);
continue;
}
(void)serve_client(eng, fd);
(void)serve_client(&p, fd);
close(fd);
if (sp_engine_quit(eng))
if (sp_engine_quit(p.eng))
break;
}
close(lfd);
@@ -864,5 +1071,7 @@ sp_proto_serve(struct sp_engine *eng, const char *path, struct sp_buf *err)
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);
return sp_engine_quit(eng) ? 0 : -1;
rc = sp_engine_quit(p.eng) ? 0 : -1;
sp_engine_close(p.eng);
return rc;
}
+13 -5
View File
@@ -16,17 +16,25 @@
struct sp_engine;
struct sp_buf;
struct sp_engine_opts;
#define SP_PROTO_VERSION 2
/*
* Serve `eng` on a Unix socket until the engine quits. `path` NULL means
* $SPLINTER_SOCKET or ~/.splinter/splinter.sock. One client at a time: there is
* one conversation, and a second writer would be a second history.
* What the server is started with: the engine template (config, session dir,
* plugins, transport) and the socket. The server opens the first engine itself
* so it can reopen another one when a client asks for a session. `socket` NULL
* means $SPLINTER_SOCKET or ~/.splinter/splinter.sock. One client at a time:
* there is one active conversation, and a second writer would be a second
* history.
* Returns 0 on a clean quit.
*/
int sp_proto_serve(struct sp_engine *eng, const char *path,
struct sp_buf *err);
struct sp_proto_opts {
const struct sp_engine_opts *engine;
const char *socket;
};
int sp_proto_serve(const struct sp_proto_opts *, struct sp_buf *err);
/* The socket path the server would use, for error messages and --help. */
void sp_proto_default_socket(char *buf, size_t cap);
+6
View File
@@ -59,6 +59,12 @@ struct ui_backend {
int (*agent_cur)(void *ctx);
int (*agent_switch)(void *ctx, int idx);
int (*command_names)(void *ctx, char (*names)[64], int max);
/* the sessions in this backend's directory; cb per entry */
int (*sessions)(void *ctx,
void (*cb)(void *cbctx, const char *id, int current,
long mtime), void *cbctx);
/* switch to another session; only a served engine can do that */
int (*open_session)(void *ctx, const char *id, struct sp_buf *err);
/* the transcript so far, one callback per message (no system prompt) */
int (*history)(void *ctx,
void (*cb)(void *cbctx, const char *role, const char *text),
+29
View File
@@ -14,6 +14,7 @@
#include "splinter.h"
#include "splinter_engine.h"
#include "ui_backend.h"
#include "i18n.h"
static int loc_input(void *ctx, const char *line, struct sp_buf *out)
{
@@ -97,6 +98,32 @@ static int loc_agent_switch(void *ctx, int idx)
return sp_engine_agent_switch(ctx, idx);
}
static int
loc_sessions(void *ctx, void (*cb)(void *, const char *, int, long),
void *cbctx)
{
struct sp_session_brief v[100];
const char *dir = sp_engine_state_dir(ctx);
const char *cur = sp_engine_session_id(ctx);
int n, i;
n = sp_session_list(dir, v, 100);
if (n < 0)
return 0;
for (i = 0; i < n; i++)
cb(cbctx, v[i].id, strcmp(v[i].id, cur) == 0, v[i].mtime);
return n;
}
static int
loc_open_session(void *ctx, const char *id, struct sp_buf *err)
{
(void)ctx;
(void)id;
sp_buf_puts(err, sp_t("ui.attach_only"));
return -1;
}
static int loc_command_names(void *ctx, char (*names)[64], int max)
{
return sp_engine_command_names(ctx, names, max);
@@ -186,6 +213,8 @@ static const struct ui_backend local = {
.agent_cur = loc_agent_cur,
.agent_switch = loc_agent_switch,
.command_names = loc_command_names,
.sessions = loc_sessions,
.open_session = loc_open_session,
.history = loc_history,
.host = loc_host,
.swarm = loc_swarm,
+277 -50
View File
@@ -33,6 +33,7 @@
#include "splinter_engine.h"
#include "mcp.h"
#include "protocol.h"
#include "i18n.h"
#include "ui_backend.h"
#define REM_MAX_AGENTS 32
@@ -43,6 +44,12 @@ struct rem_item {
char *text;
};
struct rem_sess {
char id[64];
long mtime;
int current;
};
struct rem {
int fd;
struct sp_buf in; /* bytes not yet cut into lines */
@@ -56,17 +63,25 @@ struct rem {
struct rem_item *hist;
size_t nhist;
int got_history;
struct rem_sess sess[100];
int nsess;
int got_sessions;
int got_opened;
int nagents, ncommands;
int pending; /* an approval question is open */
char a_name[64], a_args[256];
int a_auth;
int presubmitted; /* input started the turn already */
int eof; /* a quit was synthesized */
int proto; /* the server's protocol version */
int got_cmds; /* the commands event arrived */
char path[700]; /* the socket, for a reconnect */
long next_try; /* epoch ms of the next reconnect attempt */
int quiet_error; /* an expected error, no entry */
};
static int remote_live; /* one attached screen per process */
static int rem_connect(struct rem *r, struct sp_buf *err);
static void emit_history(struct rem *r);
static void
q_push(struct rem *r, int kind, long n, const char *a, const char *b)
@@ -334,6 +349,27 @@ dispatch(struct rem *r, const char *line)
}
}
r->got_history = 1;
} else if (strcmp(ev, "sessions") == 0) {
const mcp_json *items = mcp_arg(v, "items");
size_t i, n = items != NULL ? mcp_array_len(items) : 0;
r->nsess = 0;
for (i = 0; i < n && r->nsess < 100; i++) {
const mcp_json *it = mcp_array_at(items, i);
const char *id = mcp_arg_string(it, "id");
if (id == NULL)
continue;
snprintf(r->sess[r->nsess].id,
sizeof(r->sess[0].id), "%s", id);
r->sess[r->nsess].mtime = mcp_arg_int(it, "mtime", 0);
r->sess[r->nsess].current =
mcp_arg_bool(it, "current", 0);
r->nsess++;
}
r->got_sessions = 1;
} else if (strcmp(ev, "opened") == 0) {
r->got_opened = 1;
} else if (strcmp(ev, "commands") == 0) {
const mcp_json *names = mcp_arg(v, "names");
@@ -404,8 +440,9 @@ dispatch(struct rem *r, const char *line)
} else if (strcmp(ev, "error") == 0) {
s = mcp_arg_string(v, "text");
copy_last(r, s != NULL ? s : "protocol error");
q_push(r, SP_EV_ENTRY, 0, "error",
s != NULL ? s : "protocol error");
if (!r->quiet_error)
q_push(r, SP_EV_ENTRY, 0, "error",
s != NULL ? s : "protocol error");
rc = D_ERROR;
}
mcp_json_free(v);
@@ -419,8 +456,10 @@ rem_input(void *ctx, const char *line, struct sp_buf *out)
{
struct rem *r = ctx;
if (send_cmd(r, "input", "line", line) != 0)
if (r->fd < 0 || send_cmd(r, "input", "line", line) != 0) {
sp_buf_puts(out, "not connected to the backend");
return SP_INPUT_HANDLED;
}
for (;;) {
int rc = next_line(r, 30000);
@@ -466,6 +505,8 @@ rem_submit(void *ctx, const char *text)
r->presubmitted = 0;
return 0;
}
if (r->fd < 0)
return -1;
if (send_cmd(r, "say", "text", text) != 0)
return -1;
r->st.busy = 1;
@@ -480,13 +521,19 @@ rem_cancel(void *ctx)
{
struct rem *r = ctx;
if (r->fd < 0)
return -1;
return send_cmd(r, "cancel", NULL, NULL);
}
static int
rem_steer(void *ctx, const char *text)
{
return send_cmd(ctx, "steer", "text", text);
struct rem *r = ctx;
if (r->fd < 0)
return -1;
return send_cmd(r, "steer", "text", text);
}
static int
@@ -516,7 +563,7 @@ rem_approve(void *ctx, int allow)
if (!r->pending)
return 0;
r->pending = 0;
if (sp_buf_init(&b) != 0)
if (r->fd < 0 || sp_buf_init(&b) != 0)
return 0;
sp_buf_printf(&b, "{\"cmd\":\"approve\",\"allow\":%s}\n",
allow ? "true" : "false");
@@ -532,17 +579,36 @@ rem_poll(void *ctx, struct sp_event *out)
if (q_pop(r, out))
return 1;
if (r->eof)
return 0;
if (r->fd < 0) {
/* disconnected: retry once a second, keep the screen alive */
if (now_ms() < r->next_try)
return 0;
if (rem_connect(r, NULL) != 0) {
r->next_try = now_ms() + 1000;
return 0;
}
emit_history(r);
q_push(r, SP_EV_ENTRY, 0, "splinter", sp_t("ui.reconnected"));
return q_pop(r, out);
}
for (;;) {
int rc = next_line(r, 0);
if (rc < 0) {
/* the backend went away: one quit event, then quiet */
r->eof = 1;
/*
* The backend went away. Not a quit: the client keeps
* running and tries to attach again, with the session
* it had. The in-flight turn is gone with the server.
*/
int was = r->fd;
close(was);
r->fd = -1;
r->st.busy = 0;
r->st.quit = 1;
q_push(r, SP_EV_QUIT, 0, NULL, NULL);
r->pending = 0;
r->next_try = now_ms() + 1000;
q_push(r, SP_EV_ENTRY, 0, "splinter",
sp_t("ui.reconnecting"));
return q_pop(r, out);
}
if (rc == 0)
@@ -617,6 +683,18 @@ rem_command_names(void *ctx, char (*names)[64], int max)
return n;
}
static void
emit_history(struct rem *r)
{
size_t i;
q_push(r, SP_EV_CLEAR, 0, NULL, NULL);
for (i = 0; i < r->nhist; i++)
q_push(r, SP_EV_ENTRY, 0,
strcmp(r->hist[i].role, "user") == 0 ? "you" : "agent",
r->hist[i].text);
}
static int rem_take_steer(void *ctx, struct sp_buf *out)
{
/* the server owns the turn and folds a late steer into the next prompt */
@@ -625,6 +703,80 @@ static int rem_take_steer(void *ctx, struct sp_buf *out)
return 0;
}
static int
rem_sessions(void *ctx, void (*cb)(void *, const char *, int, long),
void *cbctx)
{
struct rem *r = ctx;
long deadline;
int i;
if (r->fd < 0 || send_cmd(r, "sessions", NULL, NULL) != 0)
return 0;
r->got_sessions = 0;
deadline = now_ms() + 5000;
while (!r->got_sessions && now_ms() < deadline) {
int rc = next_line(r, 5000);
if (rc <= 0)
break;
(void)dispatch(r, r->line.p);
}
for (i = 0; i < r->nsess; i++)
cb(cbctx, r->sess[i].id, r->sess[i].current,
r->sess[i].mtime);
return r->nsess;
}
static int
rem_open_session(void *ctx, const char *id, struct sp_buf *err)
{
struct rem *r = ctx;
long deadline;
char why[512] = "";
if (r->fd < 0) {
sp_buf_puts(err, "not connected to the backend");
return -1;
}
if (send_cmd(r, "open", "session", id != NULL ? id : "last") != 0) {
sp_buf_puts(err, "cannot send open");
return -1;
}
r->got_opened = 0;
deadline = now_ms() + 30000;
while (!r->got_opened && now_ms() < deadline) {
mcp_json *v;
const char *ev;
int rc = next_line(r, 30000);
if (rc <= 0)
break;
v = mcp_parse(r->line.p);
ev = v != NULL ? mcp_arg_string(v, "ev") : NULL;
if (ev != NULL && strcmp(ev, "error") == 0) {
const char *t = mcp_arg_string(v, "text");
snprintf(why, sizeof(why), "%s", t != NULL ? t :
"cannot open the session");
}
(void)dispatch(r, r->line.p);
mcp_json_free(v);
if (why[0] != '\0')
break;
}
if (why[0] != '\0') {
sp_buf_puts(err, why);
return -1;
}
if (!r->got_opened) {
sp_buf_puts(err, "the backend did not confirm the session");
return -1;
}
emit_history(r);
return 0;
}
static int
rem_history(void *ctx, void (*cb)(void *, const char *, const char *),
void *cbctx)
@@ -707,14 +859,121 @@ connect_to(const char *path)
return fd;
}
/*
* Read the greeting and, when reconnecting, ask for the session we had. The
* commands and history requests are sent first; an open replaces them with the
* restored session's state and history.
*/
static int
rem_greet(struct rem *r, struct sp_buf *err)
{
char old[64] = "";
int got_state = 0, got_cmds = 0, got_history = 0, guard = 0;
int restore;
snprintf(old, sizeof(old), "%s", r->st.session);
restore = old[0] != '\0';
r->proto = 0;
r->got_cmds = 0;
r->got_history = 0;
r->got_opened = 0;
r->got_sessions = 0;
if (send_cmd(r, "commands", NULL, NULL) != 0 ||
send_cmd(r, "history", NULL, NULL) != 0) {
if (err != NULL)
sp_buf_puts(err, "cannot ask for the greeting");
return -1;
}
while ((!got_state || !got_cmds || !got_history) && guard++ < 100) {
int rc = next_line(r, 3000);
if (rc <= 0) {
if (err != NULL)
sp_buf_puts(err, "no greeting from the backend");
return -1;
}
(void)dispatch(r, r->line.p);
if (r->st.session[0] != '\0')
got_state = 1;
if (r->got_cmds)
got_cmds = 1;
if (r->got_history)
got_history = 1;
}
if (!got_state) {
if (err != NULL)
sp_buf_puts(err, "the backend did not say which session "
"it serves");
return -1;
}
if (r->proto != SP_PROTO_VERSION) {
if (err != NULL)
sp_buf_printf(err, "speaks protocol %d, this client "
"speaks %d", r->proto, SP_PROTO_VERSION);
return -1;
}
if (restore && strcmp(old, r->st.session) != 0) {
/*
* The server came back with another (or a new) session. Ask for
* the one this screen was on; if it is gone, stay on what the
* server has and say nothing - the history on screen is stale
* either way, and the user can pick another with /sessions.
*/
r->quiet_error = 1;
if (send_cmd(r, "open", "session", old) == 0) {
int failed = 0;
for (guard = 0; guard < 100 && !r->got_opened &&
!failed; guard++) {
mcp_json *v;
const char *ev;
int rc = next_line(r, 3000);
if (rc <= 0)
break;
v = mcp_parse(r->line.p);
ev = v != NULL ?
mcp_arg_string(v, "ev") : NULL;
if (ev != NULL &&
strcmp(ev, "error") == 0)
failed = 1;
(void)dispatch(r, r->line.p);
mcp_json_free(v);
}
}
r->quiet_error = 0;
}
return 0;
}
static int
rem_connect(struct rem *r, struct sp_buf *err)
{
if (r->fd >= 0)
close(r->fd);
r->fd = -1;
sp_buf_clear(&r->in);
sp_buf_clear(&r->line);
r->fd = connect_to(r->path);
if (r->fd < 0) {
if (err != NULL)
sp_buf_printf(err, "%s: %s", r->path, strerror(errno));
return -1;
}
if (rem_greet(r, err) != 0) {
close(r->fd);
r->fd = -1;
return -1;
}
return 0;
}
const struct ui_backend *
sp_ui_backend_remote(const char *socket_path, struct sp_buf *err)
{
static struct ui_backend be;
static struct rem *r;
char path[700];
int got_state = 0, got_cmds = 0;
int got_history = 0, guard = 0;
sp_proto_default_socket(path, sizeof(path));
if (socket_path != NULL && *socket_path != '\0')
@@ -737,43 +996,9 @@ sp_ui_backend_remote(const char *socket_path, struct sp_buf *err)
sp_buf_puts(err, "out of memory");
return NULL;
}
r->fd = connect_to(path);
if (r->fd < 0) {
sp_buf_printf(err, "%s: %s", path, strerror(errno));
snprintf(r->path, sizeof(r->path), "%s", path);
if (rem_connect(r, err) != 0)
goto fail;
}
/* the greeting, the state and the command list, in whatever order */
if (send_cmd(r, "commands", NULL, NULL) != 0 ||
send_cmd(r, "history", NULL, NULL) != 0) {
sp_buf_printf(err, "%s: cannot ask for the greeting", path);
goto fail;
}
while ((!got_state || !got_cmds || !got_history) && guard++ < 100) {
int rc = next_line(r, 5000);
if (rc <= 0) {
sp_buf_printf(err, "%s: no greeting from the backend",
path);
goto fail;
}
(void)dispatch(r, r->line.p);
if (r->st.session[0] != '\0')
got_state = 1;
if (r->got_cmds)
got_cmds = 1;
if (r->got_history)
got_history = 1;
}
if (!got_state) {
sp_buf_printf(err, "%s: the backend did not say which session "
"it serves", path);
goto fail;
}
if (r->proto != SP_PROTO_VERSION) {
sp_buf_printf(err, "%s: speaks protocol %d, this client speaks "
"%d", path, r->proto, SP_PROTO_VERSION);
goto fail;
}
be.ctx = r;
be.input = rem_input;
be.submit = rem_submit;
@@ -791,6 +1016,8 @@ sp_ui_backend_remote(const char *socket_path, struct sp_buf *err)
be.agent_cur = rem_agent_cur;
be.agent_switch = rem_agent_switch;
be.command_names = rem_command_names;
be.sessions = rem_sessions;
be.open_session = rem_open_session;
be.take_steer = rem_take_steer;
be.history = rem_history;
be.host = rem_host;
+74 -9
View File
@@ -31,6 +31,7 @@
#include "folder.h"
#include "mcpserver.h"
#include "a2aserver.h"
#include "openai_server.h"
#include "interview.h"
#include "ack.h"
#include "splinter_plugin.h"
@@ -98,6 +99,10 @@ usage(FILE *f)
" beyond 127.x it needs "
"SPLINTER_A2A_SERVER_TOKEN\n"
" --a2a-listen-port N A2A port, default 8099\n"
" --openai-listen IP serve an OpenAI-compatible\n"
" /v1/chat/completions with local gw_\n"
" tools and caller tools passed through\n"
" --openai-listen-port N gateway port, default 8097\n"
" --autonomous run mutating tools without asking\n"
" --steps N tool rounds per turn (default 150)\n"
" --session DIR session directory (default ~/.splinter)\n"
@@ -214,6 +219,8 @@ struct opts {
int acklist, ack_id, ack_yes, mcp_port;
const char *a2a_ip;
int a2a_port;
const char *openai_ip;
int openai_port;
int serve, attach;
const char *socket;
};
@@ -355,6 +362,20 @@ parse_args(int argc, char **argv, struct opts *o, struct sp_agent_config *cfg)
return 2;
}
o->a2a_ip = argv[++i];
} else if (!strcmp(a, "--openai-listen")) {
if (i + 1 >= argc) {
fprintf(stderr, "splinter: --openai-listen needs "
"an address\n");
return 2;
}
o->openai_ip = argv[++i];
} else if (!strcmp(a, "--openai-listen-port")) {
if (i + 1 >= argc) {
fprintf(stderr, "splinter: --openai-listen-port "
"needs a number\n");
return 2;
}
o->openai_port = atoi(argv[++i]);
} else if (!strcmp(a, "--a2a-listen-port")) {
if (i + 1 >= argc) {
fprintf(stderr, "splinter: --a2a-listen-port needs "
@@ -669,10 +690,10 @@ check_usage(const struct opts *o)
return 2;
}
if (o->prompt == NULL && !o->chat && !o->daemon && o->mcp_ip == NULL &&
o->a2a_ip == NULL && !o->serve) {
o->a2a_ip == NULL && o->openai_ip == NULL && !o->serve) {
fprintf(stderr, "splinter: -p/--prompt is required unless you pass "
"--chat, --serve, --daemon, --mcp-server-listen or "
"--a2a-server-listen\n");
"--chat, --serve, --daemon, --mcp-server-listen, "
"--a2a-server-listen or --openai-listen\n");
return 2;
}
return 0;
@@ -1201,6 +1222,7 @@ main(int argc, char **argv)
o.key_env = "SPLINTER_API_KEY";
o.mcp_port = 8098;
o.a2a_port = 8099;
o.openai_port = 8097;
cfg.max_steps = 150;
cfg.limit_wait = sp_limit_wait_default;
cfg.limit_ctx = &g_max_wait;
@@ -1350,6 +1372,26 @@ main(int argc, char **argv)
eo.plugins[k] = o.plugins[k];
eo.nplugins = k;
}
/*
* --serve owns its engines: it opens the first one itself and reopens
* another when a client asks for a session, so main must not hold a
* second engine.
*/
if (o.serve) {
struct sp_proto_opts po;
po.engine = &eo;
po.socket = o.socket;
rc = sp_proto_serve(&po, &err);
if (rc != 0) {
fprintf(stderr, "splinter: %s\n",
err.len > 0 ? err.p : "protocol server failed");
sp_buf_free(&err);
return 3;
}
sp_buf_free(&err);
return 0;
}
{
int erc = sp_engine_open(&eng, &eo, &err);
@@ -1377,15 +1419,37 @@ main(int argc, char **argv)
fprintf(stderr, "splinter: %s\n",
err.len > 0 ? err.p : "MCP server failed");
rc = rc == 0 ? 0 : 1;
} else if (o.daemon)
rc = run_daemon(eng, &err);
else if (o.serve) {
rc = sp_proto_serve(eng, o.socket, &err);
} else if (o.openai_ip != NULL) {
struct sp_gateway_opts go;
if (o.transport != NULL || o.endpoint == NULL) {
fprintf(stderr, "splinter: --openai-listen needs an "
"OpenAI-compatible or Anthropic provider "
"(--endpoint/--model or -m), not a plugin "
"transport\n");
rc = 2;
goto done;
}
memset(&go, 0, sizeof(go));
go.ip = o.openai_ip;
go.port = o.openai_port;
go.token = getenv("SPLINTER_GATEWAY_TOKEN");
go.autonomous = cfg.autonomous == 1;
go.max_steps = 16;
go.reg = sp_engine_registry(eng);
go.conf = &conf;
go.endpoint = o.endpoint;
go.model = o.model;
go.key_env = o.key_env;
go.kind = o.kind;
rc = sp_openai_serve(&go, &err);
if (rc != 0)
fprintf(stderr, "splinter: %s\n",
err.len > 0 ? err.p : "protocol server failed");
err.len > 0 ? err.p : "gateway failed");
rc = rc == 0 ? 0 : 1;
} else if (o.chat) {
} else if (o.daemon)
rc = run_daemon(eng, &err);
else if (o.chat) {
if (!sp_profile_exists(sp_engine_state_dir(eng)))
fprintf(stderr, "splinter: kein Profil fuer '%s' - "
"`splinter --interview` legt eins an\n",
@@ -1397,6 +1461,7 @@ main(int argc, char **argv)
else
rc = run_prompt(eng, o.prompt, o.no_stream, &err);
done:
sp_engine_close(eng);
sp_buf_free(&err);
return rc;