sessions switch locally, gateway keeps caller settings and mixed calls

- sp_engine_switch(): close the old engine and open the chosen session from
  the same options; if the new one fails, reopen the session the engine was
  on. The protocol's open and the in-process /open both use it. The curses
  screen clears the pane and replays the new history, so /open no longer says
  it needs --attach.
- gateway: temperature, top_p and max_tokens (max_completion_tokens) are
  forwarded to the provider instead of dropped; request bodies may be
  Transfer-Encoding: chunked; a mixed reply runs the gw_ calls, returns the
  caller's calls in tool_calls and puts the local observations in content
  (also in the SSE delta), so the caller can echo them back.
- reconnect: when the remembered session is gone, the screen says which one
  and stays on the session the server has instead of silently swapping the
  transcript.
- ring: the exits' transports are disposed on plugin shutdown.
- /status goes through the catalogues like the rest of the UI (the English
  labels and their alignment are unchanged, so existing parsers still work).
- the man page passes mandoc -Tlint and covers the gateway and /open.

Tests: test_ui.sh covers local /sessions and /open (new, back, history),
test_protocol.sh the shared switch, test_reconnect.sh a vanished session,
test_gateway_openai.sh forwarded parameters, a chunked body and the mixed
reply in JSON and SSE. make check green.
This commit is contained in:
lotherk committed 2026-11-16 10:18:41 +00:00
1 parent 5143fcd054
commit a01bfe9df1
28 files changed
+931 -244

No files matched your search

+8 -5
View File
@@ -127,14 +127,17 @@ has the field list and a sequence diagram; `docs/FRONTENDS.md` has the code
layout and how to start a GUI on top of it. The socket is `0600` and the server
checks the peer's uid.
The served engine keeps more than one session: `sessions` lists the directory,
`open` switches to an id (or `new`/`last`) and sends the state and history of
that session. The screen offers the same as `/sessions` and `/open ID`. One
session is active at a time, and one client at a time.
The engine keeps more than one session: `sessions` lists the directory, `open`
switches to an id (or `new`/`last`) and sends the state and history of that
session. The screen offers the same as `/sessions` and `/open ID`, locally and
over the socket; a local switch closes the engine and reopens it from the same
options, because plugins keep process globals. One session is active at a time;
over the socket, one client at a time.
`--attach` reconnects: if the server dies, the screen says so, keeps running,
and attaches again when a server is back on the socket - asking for the session
it was on by id, so the conversation continues where it stopped.
it was on by id, so the conversation continues where it stopped. If that
session is gone, it says which one and stays on the server's current session.
## Gateway: another harness, splinter's tools
+8 -4
View File
@@ -65,13 +65,17 @@ splinter --attach --socket /tmp/s.sock # another: the screen as a client
The server owns the engine: `sessions` lists the session directory and `open`
switches to another id (or `new`/`last`), sending the state and history of that
session. The curses screen exposes that as `/sessions` and `/open ID`. One
session is active at a time; two clients still take turns.
session. The curses screen exposes that as `/sessions` and `/open ID`, in both
modes: `--serve` switches its engine, and the in-process `--chat` closes its
engine and opens the next one from the same options (plugins keep process
globals, so the old one goes first). One session is active at a time; two
clients still take turns.
`--attach` keeps running when the backend disappears: it says so, retries every
second, and on the next server asks for the session it was on by id. The history
it already had is shown again, and turns continue. A GUI gets the same with
`sessions`, `open` and its own retry loop.
it already had is shown again, and turns continue; if that session is gone, the
screen says which one and stays on the session the server has. A GUI gets the
same with `sessions`, `open` and its own retry loop.
## Writing a GUI client
+15 -2
View File
@@ -42,13 +42,26 @@ The loop, inside one HTTP request:
`chat.completion` with `tool_calls` and `finish_reason: "tool_calls"`. The
harness runs them, sends the results as `tool` messages in the next request,
and the gateway continues.
4. If a reply mixes both, the local calls run first and the model is asked
again; the caller's calls come on a later step.
4. If a reply mixes both, the local calls run here and the caller's calls are
returned in the same `tool_calls` answer. Since the caller cannot answer a
`gw_` call, the local observations travel in the message `content` (under
"local gateway tools ran on the splinter host:"); the caller sends them back
with the assistant message as usual, and the model sees both sides.
Every request is stateless, as the OpenAI protocol says: the conversation
travels with it. The loop is capped at 16 local tool rounds and each
observation at 32 KiB.
## Request shaping
The caller's `temperature`, `top_p` and `max_tokens` (or
`max_completion_tokens`) are forwarded to the provider; absent values stay the
provider's default. The response echoes the request's `model` name, and every
message, including the mixed-reply case, stays within the OpenAI chat shape.
Bodies may arrive with `Content-Length` or `Transfer-Encoding: chunked`; only
one request per connection is read, then the connection closes.
## Examples
A local tool, executed by splinter, from the caller's point of view an ordinary
+7
View File
@@ -12,6 +12,13 @@ Stream.
## Erledigt
- **Nachtrag 2026-11-16**: Session-Wechsel auch im lokalen UI
(`sp_engine_switch`, `/sessions` + `/open` ohne `--attach`), Gateway reicht
`temperature`/`top_p`/`max_tokens` durch, liest chunked Bodies und gibt bei
gemischten Antworten die Caller-Calls zurueck (lokale Beobachtungen im
Content, auch im SSE-Delta); ein beim Reconnect verschwundener Session-Name
wird gemeldet statt still ersetzt; Ring-Transports werden disposed;
`/status` ist uebersetzt; `docs/splinter.1` ist mandoc-sauber.
- **Gateway, Sessions, Reconnect**: `splinter --openai-listen` ist ein
OpenAI-kompatibler Endpunkt; lokale Tools heissen `gw_*` und laufen auf dem
Splinter-Host, die Tools des aufrufenden Harness werden als tool_calls
+19 -15
View File
@@ -101,10 +101,12 @@ A2A port (default 8099).
.It Fl -openai-listen Ar IP
Serve an OpenAI-compatible endpoint
.Pq Pa /v1/chat/completions , /v1/models
for another harness. The model sees splinter's local tools as
for another harness.
The model sees splinter's local tools as
.Pa gw_ Ns Ar name
and runs them here; tools the caller sends are returned to the caller as
ordinary tool calls and run there. Beyond loopback it needs
ordinary tool calls and run there.
Beyond loopback it needs
.Ev SPLINTER_GATEWAY_TOKEN . See
.Pa docs/GATEWAY.md .
.It Fl -openai-listen-port Ar N
@@ -120,12 +122,14 @@ Run the curses interface as a client of a served engine
.Pq Fl -serve .
The screen shows the server's session and its transcript so far (asked for
with the protocol's history command) and runs every turn there; the socket
protocol is the same one a GUI client uses. The commands
protocol is the same one a GUI client uses.
The commands
.Pa /sessions
and
.Pa /open Ar ID
switch the server's session. If the server goes away, the screen keeps running,
reconnects and asks for the session it was on.
switch the server's session.
If the server goes away, the screen keeps running, reconnects and asks for the
session it was on.
.It Fl -socket Ar PATH
Socket for
.Fl -serve
@@ -153,8 +157,8 @@ The curses interface links the engine in process;
exposes the same engine as JSON lines on a Unix socket, where
.Pa splinterctl
is the reference client and the place to start a GUI from.
The engine reports a turn as events -- streamed text, a step, a tool call, its
observation, an approval question, the answer -- and never calls into a front
The engine reports a turn as events \(em streamed text, a step, a tool call, its
observation, an approval question, the answer \(em and never calls into a front
end.
.Pp
Between the harness and its transport the protocol is simpler, and not a
@@ -171,6 +175,12 @@ Messages API (a provider with `kind = anthropic`) or a program's stdout
(`--transport cli`) into this shape and back.
The harness itself never parses vendor JSON, which is why the loop is testable
with no network at all.
.Sh FILES
.Bl -tag -width Ds
.It Pa ~/.splinter/<id>.jsonl
Append-only session log, one JSON object per line.
A crash can only truncate the tail.
.El
.Sh EXIT STATUS
.Bl -tag -width Ds -compact
.It 0
@@ -183,12 +193,6 @@ Usage or configuration error.
.It 3
The environment could not be set up, for example the session directory.
.El
.Sh FILES
.Bl -tag -width Ds
.It Pa ~/.splinter/<id>.jsonl
Append-only session log, one JSON object per line.
A crash can only truncate the tail.
.El
.Sh EXAMPLES
Run a scripted turn with no network:
.Bd -literal -offset indent
@@ -203,10 +207,10 @@ $ splinter -p "list the C files" --endpoint http://127.0.0.1:8080/turn
.Ed
.Sh SEE ALSO
.Xr curl 1
.Sh AUTHORS
.An Konrad Lother
.Sh CAVEATS
The transport is responsible for anything the model says; the harness trusts
only the registry and the authorization classes.
Tool arguments are passed as a single string and are not validated beyond the
tool's own checks.
.Sh AUTHORS
.An Konrad Lother
+27
View File
@@ -150,6 +150,20 @@ enum {
typedef void (*sp_stream_cb)(void *ctx, int kind, const char *text);
/*
* Request shaping a front end may pass through to a provider. The gateway
* forwards what the calling harness asked for instead of dropping it; zero
* flags mean "not given" and leave the provider default.
*/
struct sp_gen_opts {
int have_temperature;
double temperature;
int have_top_p;
double top_p;
int have_max_tokens;
long max_tokens;
};
struct sp_transport {
int (*send)(void *ctx, const struct sp_conv *, struct sp_reply *out,
struct sp_buf *err);
@@ -421,10 +435,17 @@ char *sp_endpoint_url(const char *endpoint, const char *route, char *out,
struct sp_transport sp_openai_transport(const char *url, const char *model,
const char *api_key, const struct sp_registry *, long timeout_s);
/* the same, with request shaping the caller wants forwarded */
struct sp_transport sp_openai_transport_gen(const char *url, const char *model,
const char *api_key, const struct sp_registry *, long timeout_s,
const struct sp_gen_opts *);
/* openai.c -- pure JSON shaping, testable without a network */
int sp_openai_request(const struct sp_conv *, const char *model,
const struct sp_registry *, int streaming, struct sp_buf *out);
int sp_openai_request_opts(const struct sp_conv *, const char *model,
const struct sp_registry *, int streaming,
const struct sp_gen_opts *, struct sp_buf *out);
int sp_openai_reply(const char *json, struct sp_reply *out,
struct sp_buf *err);
@@ -458,11 +479,17 @@ int sp_sse_kind(const struct sp_sse *);
*/
struct sp_transport sp_anthropic_transport(const char *url, const char *model,
const char *api_key, const struct sp_registry *, long timeout_s);
struct sp_transport sp_anthropic_transport_gen(const char *url,
const char *model, const char *api_key, const struct sp_registry *,
long timeout_s, const struct sp_gen_opts *);
/* anthropic.c -- pure JSON shaping, testable without a network */
int sp_anthropic_request(const struct sp_conv *, const char *model,
const struct sp_registry *, int streaming, int oauth,
struct sp_buf *out);
int sp_anthropic_request_opts(const struct sp_conv *, const char *model,
const struct sp_registry *, int streaming, int oauth,
const struct sp_gen_opts *, struct sp_buf *out);
int sp_anthropic_reply(const char *json, struct sp_reply *out,
struct sp_buf *err);
+10
View File
@@ -127,6 +127,16 @@ int sp_engine_state(struct sp_engine *, struct sp_engine_state *);
int sp_engine_open(struct sp_engine **, const struct sp_engine_opts *,
struct sp_buf *err);
void sp_engine_close(struct sp_engine *);
/*
* Move an engine to another session: close the old engine, open the new one
* from the same options, replace *ep. `id` is a session id, "new" for a fresh
* one, or NULL/"last" for the newest. The old engine is closed first because
* plugins keep process globals; a failed open reopens the session the engine
* was on, so the pointer is only NULL when even that fails. Returns 0 or -1
* with `err` set.
*/
int sp_engine_switch(struct sp_engine **ep, const struct sp_engine_opts *,
const char *id, struct sp_buf *err);
/* The pieces a front end may look at. The pointers stay valid until close. */
struct sp_agent *sp_engine_agent(struct sp_engine *);
+14 -1
View File
@@ -293,13 +293,26 @@ ring_init(struct sp_host *h)
return 0;
}
/* the exits own their contexts; the plugin's lifetime is the process's */
static void
ring_shutdown(struct sp_host *h)
{
size_t i;
(void)h;
for (i = 0; i < ring.n; i++)
sp_transport_dispose(&ring.tr[i]);
ring.n = 0;
(void)pthread_mutex_destroy(&ring.lock);
}
static const struct sp_plugin plugin = {
SP_PLUGIN_ABI,
"ring",
"1.0",
ring_init,
NULL,
NULL
ring_shutdown
};
const struct sp_plugin *
+22 -1
View File
@@ -11,7 +11,7 @@ ui.reconnected = wieder verbunden
ui.reconnecting = Verbindung weg - verbinde neu ...
ui.no_sessions = noch keine Sitzungen
ui.session_opened = Sitzung geoeffnet
ui.attach_only = Sitzungswechsel braucht 'splinter --attach'
ui.session_gone = Sitzung %s ist weg - jetzt auf %s
ui.compacted = Kontext kompaktiert: %zu->%zu Nachrichten, %s->%s (%s->%s)
ui.steering_queued = Steuerung eingereiht
@@ -200,3 +200,24 @@ usage.of_tokens = (%lu/%lu Tokens)
plan.widget = %d offen, %d aktiv, %d erledigt
plan.widget_active = #%d aktiv - %d offen, %d aktiv, %d erledigt
ui.thinking = denkt
status.title = Status (%s)
status.session = Sitzung
status.dir = Verzeichnis
status.model = Modell
status.endpoint = Endpunkt
status.theme = Thema
status.agent = Agent
status.last = zuletzt
status.last_value = %ld ms, %zu Schritte, %zu Toolaufrufe
status.tokens = Tokens
status.tokens_value = ein %zu, aus %zu
status.compact = Kompaktierung
status.compact_value = %zu angewandt, %zu fehlgeschlagen, %zu Runden (Agent %zu)
status.limits = Limits
status.limits_value = max_bytes %zu, max_steps %zu%s
status.autonomous = , autonom
status.meter = Messwert
status.meter_value = ctx %zu/%zu, Cache %zu, Tok %zu/%zu
status.bar = Leiste
status.swarm = Schwarm
status.swarm_value = %s (Id %d)
+22 -1
View File
@@ -10,7 +10,7 @@ ui.reconnected = reconnected
ui.reconnecting = connection lost - reconnecting ...
ui.no_sessions = no sessions yet
ui.session_opened = session opened
ui.attach_only = switching sessions needs 'splinter --attach'
ui.session_gone = session %s is gone - now on %s
ui.compacted = context compacted: %zu->%zu msgs, %s->%s (%s->%s)
ui.steering_queued = steering queued
@@ -199,3 +199,24 @@ usage.of_tokens = (%lu/%lu tokens)
plan.widget = todo %d, doing %d, done %d
plan.widget_active = #%d active - todo %d, doing %d, done %d
ui.thinking = thinking
status.title = status (%s)
status.session = session
status.dir = dir
status.model = model
status.endpoint = endpoint
status.theme = theme
status.agent = agent
status.last = last
status.last_value = %ld ms, %zu steps, %zu tool calls
status.tokens = tokens
status.tokens_value = in %zu, out %zu
status.compact = compact
status.compact_value = %zu applied, %zu failed, %zu turns (agent %zu)
status.limits = limits
status.limits_value = max_bytes %zu, max_steps %zu%s
status.autonomous = , autonomous
status.meter = meter
status.meter_value = ctx %zu/%zu, cache %zu, tok %zu/%zu
status.bar = bar
status.swarm = swarm
status.swarm_value = %s (id %d)
+22 -1
View File
@@ -11,7 +11,7 @@ ui.reconnected = reconectado
ui.reconnecting = conexao perdida - reconectando ...
ui.no_sessions = nenhuma sessao ainda
ui.session_opened = sessao aberta
ui.attach_only = trocar de sessao precisa de 'splinter --attach'
ui.session_gone = sessao %s sumiu - agora em %s
ui.compacted = contexto compactado: %zu->%zu msgs, %s->%s (%s->%s)
ui.steering_queued = direcionamento na fila
ui.prompt_mark = >
@@ -203,3 +203,24 @@ usage.of_tokens = (%lu/%lu tokens)
plan.widget = %d a fazer, %d em curso, %d feitas
plan.widget_active = #%d ativa - %d a fazer, %d em curso, %d feitas
ui.thinking = pensando
status.title = status (%s)
status.session = sessao
status.dir = diretorio
status.model = modelo
status.endpoint = endpoint
status.theme = tema
status.agent = agente
status.last = ultimo
status.last_value = %ld ms, %zu passos, %zu chamadas de ferramenta
status.tokens = tokens
status.tokens_value = entrada %zu, saida %zu
status.compact = compactacao
status.compact_value = %zu aplicadas, %zu falharam, %zu turnos (agente %zu)
status.limits = limites
status.limits_value = max_bytes %zu, max_steps %zu%s
status.autonomous = , autonomo
status.meter = medidor
status.meter_value = ctx %zu/%zu, cache %zu, tok %zu/%zu
status.bar = barra
status.swarm = enxame
status.swarm_value = %s (id %d)
+25 -4
View File
@@ -301,13 +301,14 @@ user_blocks(const struct sp_msg *m, struct sp_buf *b, int *first)
}
int
sp_anthropic_request(const struct sp_conv *conv, const char *model,
const struct sp_registry *reg, int streaming, int oauth, struct sp_buf *out)
sp_anthropic_request_opts(const struct sp_conv *conv, const char *model,
const struct sp_registry *reg, int streaming, int oauth,
const struct sp_gen_opts *gen, struct sp_buf *out)
{
struct sp_buf sys, blocks;
const struct sp_tool *tv;
size_t i, ntv, ntv0, k, nmsg = 0;
int prev_assistant = -1, rc = -1;
int prev_assistant = -1, rc = -1, mt;
if (conv == NULL || out == NULL)
return -1;
@@ -327,11 +328,23 @@ sp_anthropic_request(const struct sp_conv *conv, const char *model,
}
}
/* the API requires max_tokens; a caller's value wins inside its range */
mt = max_tokens();
if (gen != NULL && gen->have_max_tokens &&
gen->max_tokens >= 256 && gen->max_tokens <= 128000)
mt = (int)gen->max_tokens;
sp_buf_clear(out);
if (sp_buf_puts(out, "{\"model\":\"") != 0 ||
sp_json_escape(out, model != NULL ? model : "") != 0 ||
sp_buf_printf(out, "\",\"max_tokens\":%d,\"stream\":%s,",
max_tokens(), streaming ? "true" : "false") != 0)
mt, streaming ? "true" : "false") != 0)
goto out;
if (gen != NULL && gen->have_temperature &&
sp_buf_printf(out, "\"temperature\":%.17g,",
gen->temperature) != 0)
goto out;
if (gen != NULL && gen->have_top_p &&
sp_buf_printf(out, "\"top_p\":%.17g,", gen->top_p) != 0)
goto out;
if (oauth || sys.len > 0) {
int first = 1;
@@ -439,6 +452,14 @@ out:
return rc;
}
int
sp_anthropic_request(const struct sp_conv *conv, const char *model,
const struct sp_registry *reg, int streaming, int oauth, struct sp_buf *out)
{
return sp_anthropic_request_opts(conv, model, reg, streaming, oauth,
NULL, out);
}
/* the neutral call array this file stores in the conversation */
static int
calls_json(struct sp_reply *out, const char *const *ids,
+150 -19
View File
@@ -14,6 +14,7 @@
* owns a screen and a keyboard. Nothing in this file knows what a WINDOW is,
* and no front end has to know how a turn is started or cancelled.
*/
#include <ctype.h>
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
@@ -1649,37 +1650,54 @@ cmd_status(struct sp_engine *e, struct sp_buf *out)
strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm);
if (e->host != NULL)
sp_host_compaction_stats(e->host, &comp, &failed, &turns);
sp_buf_printf(out, "status (%s)\n", tbuf);
sp_buf_printf(out, " session %s\n dir %s\n", e->sess.id,
e->sess.dir);
sp_buf_printf(out, " model %s\n endpoint %s\n theme %s\n",
e->cur_model[0] != '\0' ? e->cur_model : "-",
e->cur_endpoint[0] != '\0' ? e->cur_endpoint : "-", e->theme);
sp_buf_printf(out, " agent %s\n", e->agent_name);
sp_buf_printf(out, " last %ld ms, %zu steps, %zu tool calls\n",
e->last_ms, e->last_steps, e->last_calls);
sp_buf_printf(out, " tokens in %zu, out %zu\n",
sp_buf_printf(out, sp_t("status.title"), tbuf);
sp_buf_puts(out, "\n");
sp_buf_printf(out, " %-8s %s\n", sp_t("status.session"), e->sess.id);
sp_buf_printf(out, " %-8s %s\n", sp_t("status.dir"), e->sess.dir);
sp_buf_printf(out, " %-8s %s\n", sp_t("status.model"),
e->cur_model[0] != '\0' ? e->cur_model : "-");
sp_buf_printf(out, " %-8s %s\n", sp_t("status.endpoint"),
e->cur_endpoint[0] != '\0' ? e->cur_endpoint : "-");
sp_buf_printf(out, " %-8s %s\n", sp_t("status.theme"), e->theme);
sp_buf_printf(out, " %-8s %s\n", sp_t("status.agent"), e->agent_name);
sp_buf_printf(out, " %-8s ", sp_t("status.last"));
sp_buf_printf(out, sp_t("status.last_value"), e->last_ms,
e->last_steps, e->last_calls);
sp_buf_puts(out, "\n");
sp_buf_printf(out, " %-8s ", sp_t("status.tokens"));
sp_buf_printf(out, sp_t("status.tokens_value"),
e->snapshot.tokens_in, e->snapshot.tokens_out);
sp_buf_printf(out, " compact %zu applied, %zu failed, %zu turns (agent %zu)\n",
comp, failed, turns, e->snapshot.compactions);
sp_buf_printf(out, " limits max_bytes %zu, max_steps %zu%s\n",
e->base.max_bytes, e->base.max_steps,
e->base.autonomous ? ", autonomous" : "");
sp_buf_puts(out, "\n");
sp_buf_printf(out, " %-8s ", sp_t("status.compact"));
sp_buf_printf(out, sp_t("status.compact_value"), comp, failed, turns,
e->snapshot.compactions);
sp_buf_puts(out, "\n");
sp_buf_printf(out, " %-8s ", sp_t("status.limits"));
sp_buf_printf(out, sp_t("status.limits_value"), e->base.max_bytes,
e->base.max_steps, e->base.autonomous ?
sp_t("status.autonomous") : "");
sp_buf_puts(out, "\n");
if (e->host != NULL) {
struct sp_meter m;
char seg[512];
sp_host_meter_get(e->host, &m);
sp_buf_printf(out, " meter ctx %zu/%zu, cache %zu, tok %zu/%zu\n",
m.ctx_used, m.ctx_max, m.cached, m.tok_in, m.tok_out);
sp_buf_printf(out, " %-8s ", sp_t("status.meter"));
sp_buf_printf(out, sp_t("status.meter_value"), m.ctx_used,
m.ctx_max, m.cached, m.tok_in, m.tok_out);
sp_buf_puts(out, "\n");
if (sp_host_status_text(e->host, seg, sizeof(seg)) > 0)
sp_buf_printf(out, " bar %s\n", seg);
sp_buf_printf(out, " %-8s %s\n", sp_t("status.bar"),
seg);
}
if (e->have_swarm) {
char sws[256], list[1024];
swarm_status(&e->swarm, sws, sizeof(sws));
sp_buf_printf(out, " swarm %s (id %d)\n", sws, e->swarm.id);
sp_buf_printf(out, " %-8s ", sp_t("status.swarm"));
sp_buf_printf(out, sp_t("status.swarm_value"), sws,
e->swarm.id);
sp_buf_puts(out, "\n");
swarm_list(&e->swarm, list, sizeof(list));
sp_buf_printf(out, "%s", list);
}
@@ -2269,3 +2287,116 @@ sp_engine_close(struct sp_engine *e)
pthread_mutex_destroy(&e->lock);
free(e);
}
/* a session id that is one file name, nothing else */
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_info *)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;
}
int
sp_engine_switch(struct sp_engine **ep, const struct sp_engine_opts *tmpl,
const char *id, struct sp_buf *err)
{
struct sp_engine_opts o, back;
struct sp_engine *old, *ne = NULL;
struct sp_buf oerr;
char keep[64], path[800], picked[64];
const char *dir;
int rc;
if (ep == NULL || *ep == NULL || tmpl == NULL) {
if (err != NULL)
sp_buf_puts(err, "no engine to switch");
return -1;
}
old = *ep;
if (sp_engine_busy(old)) {
if (err != NULL)
sp_buf_puts(err, "a turn is running");
return -1;
}
snprintf(keep, sizeof(keep), "%s", sp_engine_session_id(old));
dir = sp_engine_state_dir(old);
o = *tmpl;
if (id == NULL || strcmp(id, "last") == 0) {
o.session_id = NULL;
o.resume = 1;
o.continue_last = 0;
} else if (strcmp(id, "new") == 0) {
o.session_id = NULL;
o.resume = 0;
o.continue_last = 0;
} else {
if (!valid_session_id(id)) {
if (err != NULL)
sp_buf_puts(err, "invalid session id");
return -1;
}
/*
* Copy the id before the old engine is closed: a caller may
* have passed sp_engine_session_id() of that very engine.
*/
snprintf(picked, sizeof(picked), "%s", id);
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, picked);
if (access(path, R_OK) != 0) {
if (err != NULL)
sp_buf_puts(err, "no such session");
return -1;
}
o.session_id = picked;
o.resume = 1;
o.continue_last = 0;
}
/* one plugin instance at a time: close before the next open */
*ep = NULL;
sp_engine_close(old);
sp_buf_init(&oerr);
rc = sp_engine_open(&ne, &o, &oerr);
if (rc == 0) {
*ep = ne;
sp_buf_free(&oerr);
return 0;
}
/*
* The session did not open. Put the engine back on the session it had,
* so the front end still has a working conversation; only if that also
* fails does *ep stay NULL and the caller has to stop.
*/
back = *tmpl;
back.session_id = keep;
back.resume = 1;
back.continue_last = 0;
if (sp_engine_open(&ne, &back, &oerr) == 0) {
*ep = ne;
} else {
struct sp_engine_opts fresh = *tmpl;
fresh.session_id = NULL;
fresh.resume = 0;
fresh.continue_last = 0;
if (sp_engine_open(&ne, &fresh, &oerr) == 0)
*ep = ne;
}
if (err != NULL) {
if (oerr.len > 0 && oerr.p != NULL)
sp_buf_printf(err, "cannot open the session: %s",
oerr.p);
else
sp_buf_puts(err, "cannot open the session");
}
sp_buf_free(&oerr);
return -1;
}
+135
View File
@@ -92,6 +92,114 @@ sp_http_reply(int fd, int code, const char *reason, const char *type,
strlen(body != NULL ? body : ""));
}
/* the bytes already read with the header, then the socket */
struct http_src {
int fd;
const char *pre;
size_t prelen;
size_t pos;
};
static ssize_t
src_read(struct http_src *src, char *buf, size_t cap)
{
size_t n;
if (src->pos < src->prelen) {
n = src->prelen - src->pos;
if (n > cap)
n = cap;
memcpy(buf, src->pre + src->pos, n);
src->pos += n;
return (ssize_t)n;
}
return read(src->fd, buf, cap);
}
/* one CRLF-terminated line, without its terminator; -1 on EOF or overflow */
static int
src_line(struct http_src *src, char *line, size_t cap)
{
size_t n = 0;
for (;;) {
char ch;
ssize_t got = src_read(src, &ch, 1);
if (got <= 0)
return -1;
if (ch == '\n')
break;
if (ch == '\r')
continue;
if (n + 1 >= cap)
return -1;
line[n++] = ch;
}
line[n] = '\0';
return 0;
}
static int
src_exact(struct http_src *src, size_t n, struct sp_buf *body)
{
char chunk[4096];
while (n > 0) {
size_t want = n > sizeof(chunk) ? sizeof(chunk) : n;
ssize_t got = src_read(src, chunk, want);
if (got <= 0)
return -1;
if (sp_buf_add(body, chunk, (size_t)got) != 0)
return -1;
n -= (size_t)got;
}
return 0;
}
static int
read_chunked(struct http_src *src, struct sp_buf *body, size_t body_max)
{
char line[256];
for (;;) {
char *end;
unsigned long long n;
size_t ln;
char tail[2];
if (src_line(src, line, sizeof(line)) != 0)
return -1;
if ((end = strchr(line, ';')) != NULL)
*end = '\0';
ln = strlen(line);
while (ln > 0 && (line[ln - 1] == ' ' ||
line[ln - 1] == '\t'))
line[--ln] = '\0';
errno = 0;
n = strtoull(line, &end, 16);
if (errno != 0 || end == line || *end != '\0')
return -1;
if (n == 0)
break;
if (n > (unsigned long long)(body_max - body->len))
return -1;
if (src_exact(src, (size_t)n, body) != 0)
return -1;
/* the CRLF that closes the chunk */
if (src_read(src, tail, 2) != 2 || tail[1] != '\n')
return -1;
}
/* trailer section: header lines up to the empty one */
for (;;) {
if (src_line(src, line, sizeof(line)) != 0)
return -1;
if (line[0] == '\0')
return 0;
}
}
int
sp_http_read_request(int fd, char *hdr, size_t cap, struct sp_buf *body,
size_t body_max)
@@ -112,6 +220,33 @@ sp_http_read_request(int fd, char *hdr, size_t cap, struct sp_buf *body,
if ((hend = strstr(hdr, "\r\n\r\n")) != NULL)
break;
}
{
const char *te = sp_http_header_value(hdr,
"Transfer-Encoding");
if (te != NULL) {
/*
* Only "chunked" is understood. A client that streams
* its body has no Content-Length to trust.
*/
if (strncasecmp(te, "chunked", 7) != 0 ||
(te[7] != '\r' && te[7] != '\n' &&
te[7] != '\0' && te[7] != ' ' &&
te[7] != '\t' && te[7] != ','))
return -1;
{
struct http_src src;
src.fd = fd;
src.pre = hend + 4;
src.prelen = used - (size_t)(hend + 4 - hdr);
src.pos = 0;
if (src.prelen > body_max)
return -1;
return read_chunked(&src, body, body_max);
}
}
}
{
const char *v = sp_http_header_value(hdr, "Content-Length");
long clen = v != NULL ? strtol(v, NULL, 10) : 0;
+31 -4
View File
@@ -32,9 +32,27 @@ put_field(struct sp_buf *b, const char *key, const char *value)
return 0;
}
static int
gen_fields(struct sp_buf *out, const struct sp_gen_opts *g)
{
if (g == NULL)
return 0;
if (g->have_temperature &&
sp_buf_printf(out, ",\"temperature\":%.17g", g->temperature) != 0)
return -1;
if (g->have_top_p &&
sp_buf_printf(out, ",\"top_p\":%.17g", g->top_p) != 0)
return -1;
if (g->have_max_tokens &&
sp_buf_printf(out, ",\"max_tokens\":%ld", g->max_tokens) != 0)
return -1;
return 0;
}
int
sp_openai_request(const struct sp_conv *conv, const char *model,
const struct sp_registry *reg, int streaming, struct sp_buf *out)
sp_openai_request_opts(const struct sp_conv *conv, const char *model,
const struct sp_registry *reg, int streaming,
const struct sp_gen_opts *gen, struct sp_buf *out)
{
size_t i, ntv;
const struct sp_tool *tv;
@@ -42,8 +60,10 @@ sp_openai_request(const struct sp_conv *conv, const char *model,
sp_buf_clear(out);
if (sp_buf_puts(out, "{\"model\":") != 0 || sp_buf_puts(out, "\"") != 0 ||
sp_json_escape(out, model != NULL ? model : "") != 0 ||
sp_buf_puts(out, streaming ? "\",\"stream\":true,\"messages\":["
: "\",\"stream\":false,\"messages\":[") != 0)
sp_buf_puts(out, streaming ? "\",\"stream\":true"
: "\",\"stream\":false") != 0 ||
gen_fields(out, gen) != 0 ||
sp_buf_puts(out, ",\"messages\":[") != 0)
return -1;
for (i = 0; i < conv->n; i++) {
@@ -107,6 +127,13 @@ sp_openai_request(const struct sp_conv *conv, const char *model,
return sp_buf_puts(out, "]}");
}
int
sp_openai_request(const struct sp_conv *conv, const char *model,
const struct sp_registry *reg, int streaming, struct sp_buf *out)
{
return sp_openai_request_opts(conv, model, reg, streaming, NULL, out);
}
/*
* Extract the raw tool_calls array as text, so a later request can hand the
* provider back exactly what it sent: re-encoding parsed calls would be a
+151 -52
View File
@@ -414,18 +414,26 @@ parse_messages(const mcp_json *req, struct sp_conv *conv, struct sp_buf *err)
return 0;
}
/* a normalized tool_calls array from a reply, for the caller */
/*
* A normalized tool_calls array from a reply. `only_caller` drops the gw_
* calls: those belong to this host and never go back to the harness.
*/
static void
reply_calls_json(const struct sp_reply *r, struct sp_buf *out)
calls_json(const struct sp_reply *r, int only_caller, struct sp_buf *out)
{
size_t i;
int first = 1;
sp_buf_puts(out, "[");
for (i = 0; i < r->ncalls; i++) {
const struct sp_toolcall *c = &r->calls[i];
if (i > 0)
if (only_caller && 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, "{\"index\":");
sp_buf_printf(out, "%zu", i);
sp_buf_puts(out, ",\"id\":\"");
@@ -524,7 +532,8 @@ run_local(const struct sp_gateway_opts *o, const char *gw_name,
}
static struct sp_transport
make_transport(const struct sp_gateway_opts *o, struct gw_tools *t)
make_transport(const struct sp_gateway_opts *o, struct gw_tools *t,
const struct sp_gen_opts *gen)
{
const char *key = (o->key_env != NULL && *o->key_env != '\0') ?
getenv(o->key_env) : NULL;
@@ -535,10 +544,10 @@ make_transport(const struct sp_gateway_opts *o, struct gw_tools *t)
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);
return sp_anthropic_transport_gen(o->endpoint, o->model, key,
&t->reg, timeout, gen);
return sp_openai_transport_gen(o->endpoint, o->model, key, &t->reg,
timeout, gen);
}
static void
@@ -552,7 +561,7 @@ error_json(struct sp_buf *b, const char *msg)
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)
const char *content, const struct sp_reply *rep, const char *calls)
{
char created[32];
@@ -568,17 +577,12 @@ completion_json(struct sp_buf *out, const char *id, const char *model,
"\"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);
if (calls != NULL) {
sp_buf_puts(out, ",\"tool_calls\":");
sp_buf_puts(out, calls.p != NULL ? calls.p : "[]");
sp_buf_free(&calls);
sp_buf_puts(out, calls);
}
sp_buf_puts(out, "},\"finish_reason\":\"");
sp_buf_puts(out, tool_calls ? "tool_calls" : "stop");
sp_buf_puts(out, calls != NULL ? "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,
@@ -596,10 +600,11 @@ sse_event(struct sp_buf *out, const char *payload)
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)
const char *content, const struct sp_reply *rep, const char *calls)
{
char created[32];
(void)rep; /* usage is not part of the SSE chunks */
snprintf(created, sizeof(created), "%ld", (long)time(NULL));
sp_buf_clear(out);
{
@@ -611,18 +616,20 @@ completion_sse(struct sp_buf *out, const char *id, const char *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 {
/*
* A mixed reply carries text (the local observations) and the
* caller's calls in one delta; OpenAI allows both on a chunk.
*/
if (content != NULL && *content != '\0') {
sp_buf_puts(&chunk, ",\"content\":\"");
(void)sp_json_escape(&chunk, content != NULL ? content : "");
(void)sp_json_escape(&chunk, content);
sp_buf_puts(&chunk, "\"");
} else if (calls == NULL) {
sp_buf_puts(&chunk, ",\"content\":\"\"");
}
if (calls != NULL) {
sp_buf_puts(&chunk, ",\"tool_calls\":");
sp_buf_puts(&chunk, calls);
}
sp_buf_puts(&chunk, "},\"finish_reason\":null}]}");
sse_event(out, chunk.p != NULL ? chunk.p : "{}");
@@ -638,7 +645,7 @@ completion_sse(struct sp_buf *out, const char *id, const char *model,
(void)sp_json_escape(&chunk, model != NULL ? model : "");
sp_buf_printf(&chunk, "\",\"choices\":[{\"index\":0,\"delta\":{},"
"\"finish_reason\":\"%s\"}]}",
tool_calls ? "tool_calls" : "stop");
calls != NULL ? "tool_calls" : "stop");
sse_event(out, chunk.p != NULL ? chunk.p : "{}");
sp_buf_free(&chunk);
}
@@ -647,6 +654,44 @@ completion_sse(struct sp_buf *out, const char *id, const char *model,
/* ------------------------------------------------------------ one request */
/* the generation knobs a caller may set; absent ones stay provider default */
static void
parse_gen(const mcp_json *req, struct sp_gen_opts *g)
{
const mcp_json *v;
memset(g, 0, sizeof(*g));
v = mcp_arg(req, "temperature");
if (v != NULL && v->t == MCP_NUM) {
g->have_temperature = 1;
g->temperature = v->n;
}
v = mcp_arg(req, "top_p");
if (v != NULL && v->t == MCP_NUM) {
g->have_top_p = 1;
g->top_p = v->n;
}
v = mcp_arg(req, "max_tokens");
if (v == NULL || v->t != MCP_NUM)
v = mcp_arg(req, "max_completion_tokens");
if (v != NULL && v->t == MCP_NUM && v->n >= 1 && v->n <= 1e9) {
g->have_max_tokens = 1;
g->max_tokens = (long)v->n;
}
}
static void
append_observation_note(struct sp_buf *notes, const char *name,
const char *obs)
{
if (notes->len > 0)
sp_buf_puts(notes, "\n");
sp_buf_puts(notes, "[");
sp_buf_puts(notes, name != NULL ? name : "gw_");
sp_buf_puts(notes, "]\n");
sp_buf_puts(notes, obs != NULL ? obs : "");
}
static void
handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
{
@@ -656,6 +701,7 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
struct sp_conv conv;
struct gw_tools tools;
struct sp_buf err, answer, payload;
struct sp_gen_opts gen;
int stream;
unsigned long seq = ++g_seq;
char id[80];
@@ -692,6 +738,7 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
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);
parse_gen(req, &gen);
snprintf(id, sizeof(id), "chatcmpl-%ld-%lu", (long)getpid(), seq);
{
@@ -699,7 +746,8 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
int step;
for (step = 0; step < (int)max_steps; step++) {
struct sp_transport tr = make_transport(o, &tools);
struct sp_transport tr = make_transport(o, &tools,
&gen);
struct sp_reply rep;
struct sp_buf uerr;
size_t i, nlocal = 0, nclient = 0;
@@ -738,26 +786,33 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
sp_buf_puts(&answer, rep.content);
if (stream)
completion_sse(&payload, id, model,
answer.p, &rep, 0);
answer.p, &rep, NULL);
else
completion_json(&payload, id, model,
answer.p, &rep, 0);
answer.p, &rep, NULL);
sp_reply_free(&rep);
break;
}
if (nlocal > 0) {
struct sp_buf local;
struct sp_buf local, notes;
sp_buf_init(&notes);
/*
* 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.
* Local calls belong to this host. With no
* caller calls they continue the loop and the
* caller only sees the answer; a mixed reply
* cannot be continued here (its caller calls
* still need results), so it goes back with
* the local observations in the content and
* the caller's calls in tool_calls.
*/
sp_buf_init(&local);
local_calls_json(&rep, &local);
append_assistant_turn(&conv, &rep, &local);
sp_buf_free(&local);
if (nclient == 0) {
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;
@@ -776,10 +831,47 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
sp_buf_puts(&obs, "\n[... "
"truncated]");
}
append_tool_result(&conv, &rep.calls[i],
obs.p != NULL ? obs.p : "");
if (nclient == 0)
append_tool_result(&conv,
&rep.calls[i],
obs.p != NULL ? obs.p : "");
else
append_observation_note(
&notes, nm, obs.p);
sp_buf_free(&obs);
}
if (nclient > 0) {
struct sp_buf calls;
sp_buf_init(&calls);
calls_json(&rep, 1, &calls);
sp_buf_clear(&answer);
if (rep.content != NULL)
sp_buf_puts(&answer,
rep.content);
if (notes.len > 0) {
if (answer.len > 0)
sp_buf_puts(&answer,
"\n\n");
sp_buf_puts(&answer,
"local gateway tools ran on "
"the splinter host:\n");
sp_buf_puts(&answer, notes.p);
}
if (stream)
completion_sse(&payload, id,
model, answer.p, &rep,
calls.p);
else
completion_json(&payload, id,
model, answer.p, &rep,
calls.p);
sp_buf_free(&calls);
sp_buf_free(&notes);
sp_reply_free(&rep);
break;
}
sp_buf_free(&notes);
sp_reply_free(&rep);
continue;
}
@@ -787,15 +879,22 @@ handle_chat(int fd, const struct sp_gateway_opts *o, const char *body)
* 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);
{
struct sp_buf calls;
sp_buf_init(&calls);
calls_json(&rep, 0, &calls);
sp_buf_clear(&answer);
if (rep.content != NULL)
sp_buf_puts(&answer, rep.content);
if (stream)
completion_sse(&payload, id, model,
answer.p, &rep, calls.p);
else
completion_json(&payload, id, model,
answer.p, &rep, calls.p);
sp_buf_free(&calls);
}
sp_reply_free(&rep);
break;
}
+21 -6
View File
@@ -47,6 +47,8 @@ struct as_ctx {
char key[512];
const struct sp_registry *reg;
long timeout_s;
struct sp_gen_opts gen;
int have_gen;
};
static int
@@ -306,8 +308,8 @@ as_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
sp_buf_puts(err, "anthropic: out of memory");
return -1;
}
if (sp_anthropic_request(conv, c->model, c->reg, 0,
is_oauth(c->key), &body) != 0) {
if (sp_anthropic_request_opts(conv, c->model, c->reg, 0,
is_oauth(c->key), c->have_gen ? &c->gen : NULL, &body) != 0) {
sp_buf_puts(err, "anthropic: cannot build the request");
goto out;
}
@@ -394,8 +396,8 @@ as_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
sp_buf_free(&delta);
return -1;
}
if (sp_anthropic_request(conv, c->model, c->reg, 1,
is_oauth(c->key), &body) != 0) {
if (sp_anthropic_request_opts(conv, c->model, c->reg, 1,
is_oauth(c->key), c->have_gen ? &c->gen : NULL, &body) != 0) {
sp_buf_puts(err, "anthropic: cannot build the request");
goto out;
}
@@ -539,8 +541,9 @@ anthropic_free(void *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)
sp_anthropic_transport_gen(const char *url, const char *model,
const char *api_key, const struct sp_registry *reg, long timeout_s,
const struct sp_gen_opts *gen)
{
struct as_ctx *ctx;
struct sp_transport t;
@@ -555,9 +558,21 @@ sp_anthropic_transport(const char *url, const char *model, const char *api_key,
snprintf(ctx->key, sizeof(ctx->key), "%s", api_key != NULL ? api_key : "");
ctx->reg = reg;
ctx->timeout_s = timeout_s > 0 ? timeout_s : 900;
if (gen != NULL) {
ctx->gen = *gen;
ctx->have_gen = 1;
}
t.send = as_send;
t.send_stream = as_stream;
t.ctx = ctx;
t.free = anthropic_free;
return t;
}
struct sp_transport
sp_anthropic_transport(const char *url, const char *model, const char *api_key,
const struct sp_registry *reg, long timeout_s)
{
return sp_anthropic_transport_gen(url, model, api_key, reg, timeout_s,
NULL);
}
+21 -4
View File
@@ -35,6 +35,8 @@ struct openai_ctx {
char key[256];
const struct sp_registry *reg;
long timeout_s;
struct sp_gen_opts gen;
int have_gen;
};
/*
@@ -281,7 +283,8 @@ openai_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
sp_buf_puts(err, sp_td("openai.oom", "openai: out of memory"));
return -1;
}
if (sp_openai_request(conv, c->model, c->reg, 0, &body) != 0) {
if (sp_openai_request_opts(conv, c->model, c->reg, 0,
c->have_gen ? &c->gen : NULL, &body) != 0) {
sp_buf_puts(err, sp_td("openai.build_request",
"openai: cannot build the request"));
goto out;
@@ -405,7 +408,8 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
sp_buf_puts(err, sp_td("openai.oom", "openai: out of memory"));
return -1;
}
if (sp_openai_request(conv, c->model, c->reg, 1, &body) != 0) {
if (sp_openai_request_opts(conv, c->model, c->reg, 1,
c->have_gen ? &c->gen : NULL, &body) != 0) {
sp_buf_puts(err, sp_td("openai.build_request",
"openai: cannot build the request"));
goto out;
@@ -610,8 +614,9 @@ openai_free(void *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)
sp_openai_transport_gen(const char *url, const char *model, const char *api_key,
const struct sp_registry *reg, long timeout_s,
const struct sp_gen_opts *gen)
{
struct openai_ctx *ctx;
struct sp_transport t;
@@ -631,9 +636,21 @@ sp_openai_transport(const char *url, const char *model, const char *api_key,
snprintf(ctx->key, sizeof(ctx->key), "%s", api_key != NULL ? api_key : "");
ctx->reg = reg;
ctx->timeout_s = timeout_s > 0 ? timeout_s : 900;
if (gen != NULL) {
ctx->gen = *gen;
ctx->have_gen = 1;
}
t.send = openai_send;
t.send_stream = openai_stream;
t.ctx = ctx;
t.free = openai_free;
return t;
}
struct sp_transport
sp_openai_transport(const char *url, const char *model, const char *api_key,
const struct sp_registry *reg, long timeout_s)
{
return sp_openai_transport_gen(url, model, api_key, reg, timeout_s,
NULL);
}
+17 -1
View File
@@ -2334,14 +2334,30 @@ sp_ui_run(const struct ui_backend *be, const char *theme_name)
if (sp_buf_init(&err) == 0) {
if (be->open_session(be->ctx, input + 6,
&err) == 0) {
/*
* The old transcript belongs to the
* old session. The remote backend
* already queued a clear and the new
* history; drawing the backend's
* history covers the local one too.
*/
drain_idle(&s);
s.n = 0;
s.scroll = 0;
be->history(be->ctx, history_entry, &s);
sync_state(&s);
add_entry(&s, "splinter",
sp_t("ui.session_opened"));
} else
} else {
add_entry(&s, "error",
err.p != NULL ? err.p :
"cannot open the session");
/* the backend could not restore an
* engine: there is nothing to return to */
if (be->session_id(be->ctx) == NULL ||
be->session_id(be->ctx)[0] == '\0')
s.quit = 1;
}
sp_buf_free(&err);
}
continue;
+24 -76
View File
@@ -463,94 +463,35 @@ send_sessions(struct client *c, struct proto *p)
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.
* 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_engine_opts o = *p->tmpl;
struct sp_engine *old = p->eng, *ne = NULL;
char keep[64], path[800];
struct sp_buf err;
int rc;
struct sp_buf err;
int rc;
if (sp_engine_busy(old)) {
if (sp_engine_busy(p->eng)) {
(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);
rc = sp_engine_switch(&p->eng, p->tmpl, is_new ? "new" : id, &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 :
(void)send_error(c, err.p != NULL && err.len > 0 ? 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);
if (p->eng == NULL) {
(void)send_error(c, "the engine is gone");
c->quit = 1;
}
return 0;
}
p->eng = ne;
sp_buf_free(&err);
(void)send_ready(c);
(void)send_state(c, p->eng, "state");
@@ -777,7 +718,7 @@ abandon_turn(struct sp_engine *eng)
{
struct sp_event ev;
if (!sp_engine_busy(eng))
if (eng == NULL || !sp_engine_busy(eng))
return;
(void)sp_engine_cancel(eng);
while (sp_engine_busy(eng)) {
@@ -873,6 +814,13 @@ serve_client(struct proto *p, int fd)
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) {
@@ -1060,7 +1008,7 @@ sp_proto_serve(const struct sp_proto_opts *opts, struct sp_buf *err)
}
(void)serve_client(&p, fd);
close(fd);
if (sp_engine_quit(p.eng))
if (p.eng == NULL || sp_engine_quit(p.eng))
break;
}
close(lfd);
@@ -1071,7 +1019,7 @@ sp_proto_serve(const struct sp_proto_opts *opts, 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);
rc = sp_engine_quit(p.eng) ? 0 : -1;
rc = p.eng != NULL && sp_engine_quit(p.eng) ? 0 : -1;
sp_engine_close(p.eng);
return rc;
}
+7 -3
View File
@@ -63,7 +63,7 @@ struct ui_backend {
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 */
/* switch to another session; the backend replaces its engine */
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,
@@ -84,9 +84,13 @@ struct ui_backend {
};
/*
* The in-process backend. `eng` stays owned by the caller; close is a no-op.
* The in-process backend. `eng` is a pointer to the caller's engine: a session
* switch replaces the engine behind it. `opts` is the template a switched-to
* engine is built from and must outlive the backend. The caller still owns the
* engine and closes it; close is a no-op.
*/
const struct ui_backend *sp_ui_backend_engine(struct sp_engine *eng);
const struct ui_backend *sp_ui_backend_engine(struct sp_engine **eng,
const struct sp_engine_opts *opts);
/*
* Connect to a served engine and read the greeting. NULL with `err` filled
+66 -34
View File
@@ -7,6 +7,11 @@
* Every call here is one engine call. The file is deliberately dull: it is
* the control in the experiment. Whatever --attach can do through the socket,
* this must do through the engine, or the protocol has a hole.
*
* The context is a pointer to the caller's engine pointer, not the engine:
* a session switch closes the engine and opens another one, and the front end
* must not be left holding the old pointer. `opts` is the template the new
* engine is built from.
*/
#include <stddef.h>
#include <string.h>
@@ -14,57 +19,64 @@
#include "splinter.h"
#include "splinter_engine.h"
#include "ui_backend.h"
#include "i18n.h"
struct loc {
struct sp_engine **ep;
const struct sp_engine_opts *opts;
};
#define ENG(ctx) (*((struct loc *)(ctx))->ep)
static int loc_input(void *ctx, const char *line, struct sp_buf *out)
{
return sp_engine_input(ctx, line, out);
return sp_engine_input(ENG(ctx), line, out);
}
static int loc_submit(void *ctx, const char *text)
{
return sp_engine_submit(ctx, text);
return sp_engine_submit(ENG(ctx), text);
}
static int loc_busy(void *ctx)
{
return sp_engine_busy(ctx);
return sp_engine_busy(ENG(ctx));
}
static int loc_wait(void *ctx)
{
return sp_engine_wait(ctx);
return sp_engine_wait(ENG(ctx));
}
static int loc_take_steer(void *ctx, struct sp_buf *out)
{
return sp_engine_take_steer(ctx, out);
return sp_engine_take_steer(ENG(ctx), out);
}
static int loc_cancel(void *ctx)
{
return sp_engine_cancel(ctx);
return sp_engine_cancel(ENG(ctx));
}
static int loc_steer(void *ctx, const char *text)
{
return sp_engine_steer(ctx, text);
return sp_engine_steer(ENG(ctx), text);
}
static int loc_approval(void *ctx, char *name, size_t namelen, int *auth,
char *args, size_t argslen)
{
return sp_engine_approval(ctx, name, namelen, auth, args, argslen);
return sp_engine_approval(ENG(ctx), name, namelen, auth, args,
argslen);
}
static int loc_approve(void *ctx, int allow)
{
return sp_engine_approve(ctx, allow);
return sp_engine_approve(ENG(ctx), allow);
}
static int loc_poll(void *ctx, struct sp_event *out)
{
return sp_engine_poll(ctx, out);
return sp_engine_poll(ENG(ctx), out);
}
static void loc_event_free(void *ctx, struct sp_event *ev)
@@ -75,27 +87,30 @@ static void loc_event_free(void *ctx, struct sp_event *ev)
static int loc_state(void *ctx, struct sp_engine_state *out)
{
return sp_engine_state(ctx, out);
struct loc *c = ctx;
return c->ep != NULL && *c->ep != NULL ?
sp_engine_state(*c->ep, out) : -1;
}
static int loc_agents(void *ctx)
{
return sp_engine_agents(ctx);
return sp_engine_agents(ENG(ctx));
}
static const char *loc_agent_name(void *ctx, int idx)
{
return sp_engine_agent_name(ctx, idx);
return sp_engine_agent_name(ENG(ctx), idx);
}
static int loc_agent_cur(void *ctx)
{
return sp_engine_agent_cur(ctx);
return sp_engine_agent_cur(ENG(ctx));
}
static int loc_agent_switch(void *ctx, int idx)
{
return sp_engine_agent_switch(ctx, idx);
return sp_engine_agent_switch(ENG(ctx), idx);
}
static int
@@ -103,8 +118,8 @@ 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);
const char *dir = sp_engine_state_dir(ENG(ctx));
const char *cur = sp_engine_session_id(ENG(ctx));
int n, i;
n = sp_session_list(dir, v, 100);
@@ -118,22 +133,21 @@ loc_sessions(void *ctx, void (*cb)(void *, const char *, int, long),
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;
struct loc *c = ctx;
return sp_engine_switch(c->ep, c->opts, id, err);
}
static int loc_command_names(void *ctx, char (*names)[64], int max)
{
return sp_engine_command_names(ctx, names, max);
return sp_engine_command_names(ENG(ctx), names, max);
}
static int
loc_history(void *ctx, void (*cb)(void *, const char *, const char *),
void *cbctx)
{
const struct sp_conv *conv = sp_engine_conv(ctx);
const struct sp_conv *conv = sp_engine_conv(ENG(ctx));
size_t i;
int n = 0;
@@ -155,37 +169,52 @@ loc_history(void *ctx, void (*cb)(void *, const char *, const char *),
static struct sp_host *loc_host(void *ctx)
{
return sp_engine_host(ctx);
struct loc *c = ctx;
return c->ep != NULL && *c->ep != NULL ?
sp_engine_host(*c->ep) : NULL;
}
static struct swarm *loc_swarm(void *ctx)
{
return sp_engine_swarm(ctx);
return sp_engine_swarm(ENG(ctx));
}
static struct sp_config *loc_config(void *ctx)
{
return sp_engine_config(ctx);
struct loc *c = ctx;
return c->ep != NULL && *c->ep != NULL ?
sp_engine_config(*c->ep) : NULL;
}
static const char *loc_session_id(void *ctx)
{
return sp_engine_session_id(ctx);
struct loc *c = ctx;
return c->ep != NULL && *c->ep != NULL ?
sp_engine_session_id(*c->ep) : "";
}
static const char *loc_state_dir(void *ctx)
{
return sp_engine_state_dir(ctx);
struct loc *c = ctx;
return c->ep != NULL && *c->ep != NULL ?
sp_engine_state_dir(*c->ep) : "";
}
static void loc_set_theme(void *ctx, const char *theme)
{
sp_engine_set_theme(ctx, theme);
sp_engine_set_theme(ENG(ctx), theme);
}
static int loc_quit(void *ctx)
{
return sp_engine_quit(ctx);
struct loc *c = ctx;
return c->ep != NULL && *c->ep != NULL ?
sp_engine_quit(*c->ep) : 1;
}
static int loc_local(void *ctx) { (void)ctx; return 1; }
@@ -228,11 +257,14 @@ static const struct ui_backend local = {
};
const struct ui_backend *
sp_ui_backend_engine(struct sp_engine *eng)
sp_ui_backend_engine(struct sp_engine **eng, const struct sp_engine_opts *opts)
{
static struct ui_backend be;
static struct ui_backend be;
static struct loc c;
c.ep = eng;
c.opts = opts;
be = local;
be.ctx = eng;
be.ctx = &c;
return &be;
}
+35 -7
View File
@@ -67,6 +67,8 @@ struct rem {
int nsess;
int got_sessions;
int got_opened;
int sess_gone; /* the restored session was not there */
char gone_old[64], gone_new[64];
int nagents, ncommands;
int pending; /* an approval question is open */
char a_name[64], a_args[256];
@@ -587,7 +589,23 @@ rem_poll(void *ctx, struct sp_event *out)
r->next_try = now_ms() + 1000;
return 0;
}
/*
* The clear in emit_history wipes the screen, so a note about a
* session that did not come back has to follow it.
*/
emit_history(r);
if (r->sess_gone) {
struct sp_buf note;
if (sp_buf_init(&note) == 0) {
sp_buf_printf(&note, sp_t("ui.session_gone"),
r->gone_old, r->gone_new);
q_push(r, SP_EV_ENTRY, 0, "splinter",
note.p != NULL ? note.p : "");
sp_buf_free(&note);
}
r->sess_gone = 0;
}
q_push(r, SP_EV_ENTRY, 0, "splinter", sp_t("ui.reconnected"));
return q_pop(r, out);
}
@@ -773,7 +791,7 @@ rem_open_session(void *ctx, const char *id, struct sp_buf *err)
sp_buf_puts(err, "the backend did not confirm the session");
return -1;
}
emit_history(r);
/* the cached history is now the new session's; the screen replays it */
return 0;
}
@@ -913,16 +931,18 @@ rem_greet(struct rem *r, struct sp_buf *err)
return -1;
}
if (restore && strcmp(old, r->st.session) != 0) {
int failed = 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.
* the one this screen was on. If it is gone, stay on what the
* server has and say so - 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;
if (send_cmd(r, "open", "session", old) != 0) {
failed = 1;
} else {
for (guard = 0; guard < 100 && !r->got_opened &&
!failed; guard++) {
mcp_json *v;
@@ -940,8 +960,16 @@ rem_greet(struct rem *r, struct sp_buf *err)
(void)dispatch(r, r->line.p);
mcp_json_free(v);
}
if (!r->got_opened)
failed = 1;
}
r->quiet_error = 0;
if (failed) {
r->sess_gone = 1;
snprintf(r->gone_old, sizeof(r->gone_old), "%s", old);
snprintf(r->gone_new, sizeof(r->gone_new), "%s",
r->st.session);
}
}
return 0;
}
+1 -1
View File
@@ -1454,7 +1454,7 @@ main(int argc, char **argv)
fprintf(stderr, "splinter: kein Profil fuer '%s' - "
"`splinter --interview` legt eins an\n",
sp_memory_user());
rc = sp_ui_run(sp_ui_backend_engine(eng), o.theme);
rc = sp_ui_run(sp_ui_backend_engine(&eng, &eo), o.theme);
} else if (o.prompt != NULL &&
(o.prompt[0] == '/' || o.prompt[0] == '!'))
rc = run_slash_prompt(eng, o.prompt);
+4
View File
@@ -28,6 +28,10 @@ class H(http.server.BaseHTTPRequestHandler):
if m.get("role") == "user":
user = m.get("content") or ""
stream = bool(req.get("stream"))
if "params" in user:
return self.reply(stream, content="PARAMS t=%s p=%s m=%s" % (
req.get("temperature"), req.get("top_p"),
req.get("max_tokens")))
if last.get("role") == "tool":
return self.reply(stream,
content="ERGEBNIS: " +
+28 -2
View File
@@ -105,10 +105,36 @@ post "$P1" '{"model":"x","messages":[{"role":"user","content":"caller bitte"},{"
"$D/caller2.json"
checkgrep 'ERGEBNIS: client-result' "$D/caller2.json"
# a mixed reply runs the local call and asks the model again
# a mixed reply runs the local call and hands the caller's call back, with
# the local observation in the content (the caller cannot answer gw_ calls)
post "$P1" '{"model":"x","messages":[{"role":"user","content":"mixed"}]}' \
"$D/mixed.json"
checkgrep 'ERGEBNIS: mixed-local' "$D/mixed.json"
checkgrep '"name":"caller_tool"' "$D/mixed.json"
checkgrep 'mixed-local' "$D/mixed.json"
checkgrep '"finish_reason":"tool_calls"' "$D/mixed.json"
# ... and the streamed form carries the same observations and calls
curl -sN -X POST "http://127.0.0.1:$P1/v1/chat/completions" \
-H 'Content-Type: application/json' \
-d '{"model":"x","stream":true,"messages":[{"role":"user","content":"mixed"}]}' \
> "$D/mixed-sse.txt"
checkgrep '"tool_calls"' "$D/mixed-sse.txt"
checkgrep 'mixed-local' "$D/mixed-sse.txt"
checkgrep '\[DONE\]' "$D/mixed-sse.txt"
# generation parameters reach the provider instead of being dropped
post "$P1" '{"model":"x","temperature":0.25,"top_p":0.5,"max_tokens":321,"messages":[{"role":"user","content":"params"}]}' \
"$D/params.json"
checkgrep 'PARAMS t=0.25 p=0.5 m=321' "$D/params.json"
# a chunked request body is read like a Content-Length one
printf '%s' '{"model":"x","messages":[{"role":"user","content":"gw-local"}]}' \
> "$D/chunked.body"
curl -s -X POST "http://127.0.0.1:$P1/v1/chat/completions" \
-H 'Content-Type: application/json' \
-H 'Transfer-Encoding: chunked' \
--data-binary "@$D/chunked.body" > "$D/chunked.json"
checkgrep 'ERGEBNIS: hallo-vom-gw' "$D/chunked.json"
# mutating tools need --autonomous
rm -f "$D/written.txt"
+20 -1
View File
@@ -26,12 +26,14 @@ P=$((20000 + ($$ + 11) % 30000))
F=
G1=
G2=
G3=
fails=0
cleanup() {
killserver
[ -n "$F" ] && kill "$F" 2>/dev/null
[ -n "$G1" ] && kill "$G1" 2>/dev/null
[ -n "$G2" ] && kill "$G2" 2>/dev/null
[ -n "$G3" ] && kill "$G3" 2>/dev/null
rm -rf "$D"
}
trap cleanup EXIT
@@ -110,10 +112,27 @@ typed 'single word ok'; key Enter
check idle_prompt
check shows '<m> ok'
# the session is gone on the next server: the screen says which one and
# stays on the session the server does have
kill "$G2" 2>/dev/null
G2=
sleep 2
rm -f "$D/server/.splinter/"*.jsonl "$D/server/.splinter/"*.meta \
"$D/server/.splinter/"*.agent
G3=$(start_server "$D/s3.log")
if ! wait_sock; then
echo "FAIL server 3 has no socket"
cat "$D/s3.log"
exit 1
fi
check shows 'is gone'
check shows 'reconnected'
check tmux has-session -t $S
key C-u C-d
for i in $(seq 1 40); do [ -s "$D/rc" ] && break; sleep 0.5; done
check test "$(cat "$D/rc" 2>/dev/null)" = 0
check kill -0 "$G2" 2>/dev/null
check kill -0 "$G3" 2>/dev/null
if [ "$fails" -eq 0 ]; then
echo "test_reconnect: ok"
+21
View File
@@ -162,5 +162,26 @@ check shows 'cancelled'
check shows '^build>'
check test "$(quit_code)" = 0
# ---- sessions in the local UI ----
# /open used to answer "needs --attach". The engine can switch in process too:
# list the directory, open a fresh session (clear the pane), then go back to the
# first one and get its transcript again.
start 2
typed 'single word ok'; key Enter
check shows '<m> ok'
old=$(basename "$(ls "$D/home/.splinter/"*.jsonl | head -1)" .jsonl)
typed '/sessions'; key Enter
check shows "$old"
typed '/open new'; key Enter
check shows 'session opened'
sleep 1
check not_shows '<m> ok'
typed 'single word ok'; key Enter
check shows '<m> ok'
typed "/open $old"; key Enter
check shows 'session opened'
check shows '<m> ok'
check test "$(quit_code)" = 0
if [ "$fails" -eq 0 ]; then echo "test_ui: ok"; exit 0; fi
exit 1