From 5143fcd054033e60ea52a21fd0e09fdf4242bb56 Mon Sep 17 00:00:00 2001 From: lotherk Date: Mon, 16 Nov 2026 09:33:37 +0000 Subject: [PATCH] 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. --- Makefile | 6 +- README.md | 36 +- docs/FRONTENDS.md | 19 +- docs/GATEWAY.md | 91 +++ docs/PROTOCOL.md | 26 +- docs/ROADMAP.md | 8 + docs/splinter.1 | 18 +- include/splinter.h | 19 + share/locale/de.msg | 5 + share/locale/en.msg | 5 + share/locale/pt_BR.msg | 5 + src/backend/engine.c | 23 +- src/backend/http.c | 142 +++++ src/backend/http.h | 33 + src/backend/openai_server.c | 979 ++++++++++++++++++++++++++++++ src/backend/openai_server.h | 34 ++ src/backend/providers.c | 7 +- src/backend/session.c | 48 ++ src/backend/transport.c | 10 + src/backend/transport_anthropic.c | 7 + src/backend/transport_openai.c | 7 + src/frontend/curses.c | 59 +- src/frontend/protocol.c | 255 +++++++- src/frontend/protocol.h | 18 +- src/frontend/ui_backend.h | 6 + src/frontend/ui_local.c | 29 + src/frontend/ui_remote.c | 327 ++++++++-- src/main.c | 83 ++- tests/fake_gateway.py | 97 +++ tests/test_gateway_openai.sh | 162 +++++ tests/test_protocol.sh | 67 ++ tests/test_reconnect.sh | 122 ++++ 32 files changed, 2642 insertions(+), 111 deletions(-) create mode 100644 docs/GATEWAY.md create mode 100644 src/backend/http.c create mode 100644 src/backend/http.h create mode 100644 src/backend/openai_server.c create mode 100644 src/backend/openai_server.h create mode 100644 tests/fake_gateway.py create mode 100755 tests/test_gateway_openai.sh create mode 100755 tests/test_reconnect.sh diff --git a/Makefile b/Makefile index 7e17f42..49d3940 100644 --- a/Makefile +++ b/Makefile @@ -27,7 +27,7 @@ LIB = libsplinter.so LIBOBJ = src/backend/buf.o src/backend/tool.o src/backend/session.o src/backend/conv.o src/backend/transport.o \ src/backend/json.o src/backend/sse.o src/backend/openai.o src/backend/transport_openai.o \ src/backend/anthropic.o src/backend/transport_anthropic.o src/backend/builtin.o \ - src/backend/agent.o src/backend/theme.o src/backend/palettes.o src/backend/decomp.o src/backend/i18n.o src/backend/delegate.o src/backend/telegram.o src/backend/log.o src/backend/cmdscript.o src/backend/folder.o src/backend/interview.o src/backend/ack.o src/backend/mcpserver.o src/backend/skills.o src/backend/memory.o src/backend/prompt.o src/backend/config.o src/backend/plugin.o src/backend/curl.o src/backend/swarm.o src/backend/provstate.o src/backend/md.o src/backend/tgmd.o src/backend/b64.o src/backend/a2aserver.o src/backend/providers.o src/backend/usage.o src/backend/confblock.o src/backend/agents.o src/backend/engine.o src/backend/catalogs.o + src/backend/agent.o src/backend/theme.o src/backend/palettes.o src/backend/decomp.o src/backend/i18n.o src/backend/delegate.o src/backend/telegram.o src/backend/log.o src/backend/cmdscript.o src/backend/folder.o src/backend/interview.o src/backend/ack.o src/backend/mcpserver.o src/backend/skills.o src/backend/memory.o src/backend/prompt.o src/backend/config.o src/backend/plugin.o src/backend/curl.o src/backend/swarm.o src/backend/provstate.o src/backend/md.o src/backend/tgmd.o src/backend/b64.o src/backend/a2aserver.o src/backend/providers.o src/backend/usage.o src/backend/confblock.o src/backend/agents.o src/backend/engine.o src/backend/http.o src/backend/openai_server.o src/backend/catalogs.o BIN = splinter BINOBJ = src/main.o src/frontend/curses.o src/frontend/protocol.o \ src/frontend/ui_local.o src/frontend/ui_remote.o @@ -174,6 +174,8 @@ src/frontend/ui_local.o: src/frontend/ui_backend.h include/splinter_engine.h src src/frontend/ui_remote.o: src/frontend/ui_backend.h src/frontend/protocol.h include/splinter_engine.h vendor/libmcp/mcp.h src/frontend/client.o: src/frontend/protocol.h include/splinter.h src/frontend/protocol.o: src/frontend/protocol.h include/splinter_engine.h include/splinter.h src/backend/i18n.h +src/backend/http.o: src/backend/http.h include/splinter.h +src/backend/openai_server.o: src/backend/openai_server.h src/backend/http.h src/backend/config.h include/splinter.h vendor/libmcp/mcp.h src/backend/engine.o: include/splinter_engine.h src/backend/config.h src/backend/providers.h src/backend/agents.h src/backend/swarm.h src/backend/cmdscript.h src/backend/i18n.h include/splinter_plugin.h src/backend/providers.o: src/backend/providers.h src/backend/config.h include/splinter.h include/splinter_plugin.h src/main.o: include/splinter.h include/splinter_engine.h \ @@ -289,6 +291,8 @@ check: $(LIB) $(BIN) $(CLIENT) $(PLUGIN) $(TESTS) echo "== tests/test_ui.sh"; sh tests/test_ui.sh; \ echo "== tests/test_protocol.sh"; sh tests/test_protocol.sh; \ echo "== tests/test_attach.sh"; sh tests/test_attach.sh; \ + echo "== tests/test_gateway_openai.sh"; sh tests/test_gateway_openai.sh; \ + echo "== tests/test_reconnect.sh"; sh tests/test_reconnect.sh; \ echo "all tests passed" # The installed binary finds its own library through an rpath relative to itself diff --git a/README.md b/README.md index 1f3a09f..23ab805 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ conversation starts clear at the top and only ever grows. splinter --serve # the engine on a socket, for a GUI splinter --attach # the same curses UI, as a client of it splinterctl --say "hallo" # the reference client for that socket + splinter --openai-listen 127.0.0.1 # /v1 for another harness, gw_ tools The working day with several subscriptions (who analyses, who implements, what happens at a limit) is in `docs/WORKFLOW.md`. @@ -76,6 +77,8 @@ where the line runs and how to add another one. src/backend/md.c markdown tables as aligned text src/backend/telegram.c gateway mode src/backend/a2aserver.c the A2A server + src/backend/openai_server.c /v1/chat/completions with gw_ tools + src/backend/http.c the HTTP helpers the JSON servers share src/frontend/curses.c transcript, sidebar, prompt src/frontend/ui_backend.h what the screen needs from a backend @@ -90,6 +93,7 @@ where the line runs and how to add another one. vendor/netbsd-curses/ NetBSD curses and terminfo, vendored docs/PLUGINS.md the ABI, the threading rules docs/PROTOCOL.md the line protocol a GUI client speaks + docs/GATEWAY.md the OpenAI endpoint and its two tool sets tests/ the test binaries, run by `make check` docs/splinter.1 manual page src/www/index*.html the site, written by hand (de, en, pt_BR) @@ -118,9 +122,35 @@ has no hidden C dependency. The protocol is one JSON object per line (`ready`, `state`, `stream`, `step`, `tool`, `tool_result`, `approval`, `turn`, ...; `input`, `say`, `approve`, -`cancel`, `steer`, `state`, `quit`). `docs/PROTOCOL.md` 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. +`cancel`, `steer`, `state`, `quit`, `sessions`, `open`). `docs/PROTOCOL.md` +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. + +`--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. + +## Gateway: another harness, splinter's tools + +`splinter --openai-listen 127.0.0.1` serves `/v1/chat/completions` for another +harness. The model sees splinter's local tools as `gw_read`, `gw_write`, +`gw_run`, ... and the caller's own tools under their own names: + +* a `gw_*` call is executed by splinter, on the host where splinter runs, and + the caller only sees the final answer; +* any other tool call is returned to the calling harness, which runs it where + it runs and sends the results back in the next request. + +That is how one conversation can act in both places, without a name collision +between a local `read` and a caller's `read`. Beyond loopback a +`SPLINTER_GATEWAY_TOKEN` is required, and local mutating tools need +`--autonomous`. `docs/GATEWAY.md` has the details and examples. ## Plugins and themes diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index a4e39eb..e77bde8 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -46,7 +46,7 @@ onto the JSON `ev` names in `docs/PROTOCOL.md`. | `src/frontend/ui_backend.h` | what the screen needs from a backend | | `src/frontend/ui_local.c` | that backend as the engine in this process | | `src/frontend/ui_remote.c` | that backend as a protocol client (`--attach`) | -| `src/frontend/protocol.c` | out-of-process, `splinter --serve`, JSON lines | +| `src/frontend/protocol.c` | `splinter --serve`: JSON lines, sessions, open | | `src/frontend/client.c` | `splinterctl`, the reference protocol client | | `src/main.c` | the launcher: parse, config, engine, pick a front end | @@ -63,6 +63,16 @@ splinter --serve --socket /tmp/s.sock # one process: engine + protocol 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. + +`--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. + ## Writing a GUI client Two ways, and the second one is the interesting one. @@ -76,7 +86,12 @@ Two ways, and the second one is the interesting one. from anything that can open one and write JSON: Python/Tk, Qt, GTK, a web front end through a small bridge. `docs/PROTOCOL.md` is the contract; `docs/proto-example.py` is a complete 60-line client, and - `splinter --attach` is the full curses front end running this way. + `splinter --attach` is the full curses front end running this way. Use + `sessions`/`open` for tabs and retry the connect for a server restart. + +3. **Let another harness use splinter as a model.** `splinter --openai-listen` + serves `/v1/chat/completions`: the caller's tools stay with the caller, + splinter's own run locally under `gw_*`. See `docs/GATEWAY.md`. The recommended shape for a GUI: diff --git a/docs/GATEWAY.md b/docs/GATEWAY.md new file mode 100644 index 0000000..2617b2c --- /dev/null +++ b/docs/GATEWAY.md @@ -0,0 +1,91 @@ +# The OpenAI gateway + +`splinter --openai-listen IP [--openai-listen-port N]` is a small +OpenAI-compatible endpoint. Another harness points its OpenAI client at it and +gets an answer from splinter's configured provider, with **tools on both +sides**: splinter executes its own tools where splinter runs, the caller +executes its tools where the caller runs. + +```sh +# the side with the files and the shell +splinter -m myprovider --openai-listen 127.0.0.1 --openai-listen-port 8097 + +# the other harness +export OPENAI_BASE_URL=http://127.0.0.1:8097/v1 +export OPENAI_API_KEY=unused # unless SPLINTER_GATEWAY_TOKEN is set +``` + +`GET /v1/models` answers with the run's model, so a client that probes first is +happy. `POST /v1/chat/completions` accepts the usual `messages`, `tools` and +`stream` fields. + +## Two tool namespaces + +The model sees two kinds of tools in one request: + +| name | who runs it | where | +| --- | --- | --- | +| `gw_read`, `gw_write`, `gw_edit`, `gw_run`, … | splinter | on the host where splinter runs | +| everything in the caller's `tools` array | the calling harness | where the harness runs | + +`gw_` is reserved: a caller tool with that prefix is refused with HTTP 400, +because that is how a local `read` and a caller's `read` stay apart. + +The loop, inside one HTTP request: + +1. splinter asks its provider with the caller's conversation, the caller's + tools **and** its own tools renamed `gw_*`. +2. If the model calls `gw_*`, splinter runs it here (read tools always; + mutating and destructive ones only with `--autonomous`), appends the + observation and asks the provider again. The caller never sees these calls. +3. If the model calls a caller tool, splinter returns a normal + `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. + +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. + +## Examples + +A local tool, executed by splinter, from the caller's point of view an ordinary +completion: + +```sh +curl -s http://127.0.0.1:8097/v1/chat/completions \ + -H 'Content-Type: application/json' \ + -d '{"model":"x","messages":[{"role":"user","content":"read Cargo.toml"}]}' +``` + +A caller tool comes back instead: + +```json +{"choices":[{"index":0,"message":{"role":"assistant","content":"", + "tool_calls":[{"id":"c1","type":"function", + "function":{"name":"browser_open","arguments":"{\"url\":\"...\"}"}}]}, + "finish_reason":"tool_calls"}]} +``` + +## Security + +- Beyond loopback the server refuses to start without + `SPLINTER_GATEWAY_TOKEN`; with a token set, every request needs + `Authorization: Bearer `. +- `--autonomous` is the switch that lets the model use `gw_write`, `gw_edit` + and `gw_run`. Without it those calls are denied with an observation the model + reads, so it can still answer. +- There is no TLS. Expose it through ssh, WireGuard or a TLS proxy when the + network is not yours. +- One request is served at a time; the endpoint is a gateway, not a load + balanced service. + +## Where the tools come from + +`gw_*` is the engine's registry: the builtins (`read`, `write`, `edit`, +`search`, `list`, `run`, `websearch`, `webfetch`), `folder_history`, +`delegate`, and the memory/skills tools. Plugins loaded with `--plugin` add +theirs. The caller's tools are passed through to the provider untouched, except +for the `gw_` reservation. diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 5b918c6..b0d11af 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -18,7 +18,9 @@ the owner's: this conversation may run `run` with the owner's rights. The reference client is `splinterctl`; `docs/proto-example.py` is a 60-line Python client that shows the whole loop. `splinter --attach` is the complete curses front end speaking this protocol, so anything the screen can do is -reachable over the socket by design. +reachable over the socket by design. If its connection drops, `--attach` +reconnects and asks for the session it was on with `open`; a GUI can do the +same. ## Framing @@ -28,8 +30,9 @@ reachable over the socket by design. * `"protocol": 2` in the greeting is the format version. It changes only when a field changes meaning; new fields are added without a bump. -One client at a time. There is one conversation, and a second writer would be -a second history. When a client disconnects in the middle of a turn, the server +One client at a time. The server holds one active engine, so one conversation +runs; `open` switches it, it does not run two. A second writer on the same +engine would be a second history. When a client disconnects in the middle of a turn, the server cancels the turn (an approval nobody can answer would otherwise park the engine forever) and accepts the next client. @@ -126,6 +129,21 @@ Ask for the transcript so far: `"ev":"history"`, `"truncated":bool`, joins instead of an empty pane. The system prompt and tool observations stay out — this is what the person and the model said. +### `{"cmd":"sessions"}` + +List the sessions in the server's session directory, newest first: +`"ev":"sessions"`, `"items":[{"id","mtime","bytes","current"}]`. `current` marks +the session the connection is on. + +### `{"cmd":"open","session":"ID"}` + +Switch this connection to another session. `"new"` starts a fresh one, +`"last"` the newest, an id continues that file. The server sends `ready`, +`state`, `commands`, `history` and finally `"ev":"opened"` with the new +`session` and `dir`; the old engine is closed first, so plugins are not doubled. +While a turn runs the command is refused. An unknown id is an error and the +connection stays on its session. + ### `{"cmd":"commands"}` Ask what a command palette may offer: `"ev":"commands"`, @@ -157,6 +175,8 @@ with 0. | `reply` | `text` | the answer to a command; may be empty | | `error` | `text` | the command was refused | | `commands` | `names[]` | the slash commands, for a palette | +| `sessions` | `items[]` | the sessions, with id/mtime/bytes/current | +| `opened` | `session`, `dir` | the switch is complete | | `history` | `truncated`, `items[]` | the transcript so far (role/text) | | `pong` | — | answer to `ping` | | `quit` | — | the engine is shutting down | diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index b1b8700..73270e2 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -12,6 +12,14 @@ Stream. ## Erledigt +- **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 + zurueckgegeben und dort ausgefuehrt (`docs/GATEWAY.md`, + `tests/test_gateway_openai.sh`). `--serve` haelt mehrere Sessions + (`sessions`/`open`, `/sessions`/`/open` im UI), `--attach` verbindet sich + nach einem Serverausfall selbst neu und holt die alte Session per id + (`tests/test_protocol.sh`, `tests/test_reconnect.sh`). - **Review-Nachlauf 2026-11-16**: 8-KiB-Zeilen in Server/Client/attach durch dynamische Puffer ersetzt (9-KB-Prompt, 8-KB-Shell-Eintrag), `turn` beendet nicht mehr das busy-Fenster (Steer-Rest), Curses finalisiert jeden Turn diff --git a/docs/splinter.1 b/docs/splinter.1 index 2bb7044..f78b1d8 100644 --- a/docs/splinter.1 +++ b/docs/splinter.1 @@ -98,6 +98,17 @@ Beyond 127.x it needs .Ev SPLINTER_A2A_SERVER_TOKEN . .It Fl -a2a-listen-port Ar N 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 +.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 +.Ev SPLINTER_GATEWAY_TOKEN . See +.Pa docs/GATEWAY.md . +.It Fl -openai-listen-port Ar N +Gateway port (default 8097). .It Fl -serve Serve the engine on a Unix socket instead of drawing a screen. Each request and event is one JSON object per line; see @@ -109,7 +120,12 @@ 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. +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. .It Fl -socket Ar PATH Socket for .Fl -serve diff --git a/include/splinter.h b/include/splinter.h index f9a1c91..c7c506d 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -160,9 +160,18 @@ struct sp_transport { /* optional: provider/key identity for quota/usage tracking (plugins) */ const char *provider; /* e.g. "openai-compat", "ollama", "opencode" */ const char *key_id; /* stable key fingerprint/id, never the secret */ + /* + * Optional: free the context a constructor allocated. A transport a + * caller builds per request (the OpenAI gateway) uses this; the agent's + * own transport lives as long as the agent. Zero for plugin transports, + * whose context belongs to the plugin. + */ + void (*free)(void *ctx); }; void sp_reply_free(struct sp_reply *); +/* free a transport's context (if it owns one) and zero the struct */ +void sp_transport_dispose(struct sp_transport *); /* A deterministic in-process transport: replies are queued FIFO. */ struct sp_mock { @@ -202,6 +211,16 @@ int sp_session_folder_history(const char *dir, const char *cwd, int sp_session_load(const struct sp_session_info *, struct sp_conv *conv, size_t *loaded, struct sp_buf *err); +/* one line of a session listing: id, mtime, bytes; newest first */ +struct sp_session_brief { + char id[64]; + long mtime; + size_t bytes; +}; +/* up to max entries from dir; returns the count (0..max), or -1 */ +int sp_session_list(const char *dir, struct sp_session_brief *v, + size_t max); + /* ----------------------------------------------------------------- agent */ struct sp_agent_config { diff --git a/share/locale/de.msg b/share/locale/de.msg index 8a1fe79..4cf5f27 100644 --- a/share/locale/de.msg +++ b/share/locale/de.msg @@ -7,6 +7,11 @@ ui.ready = bereit. Enter sendet, Ctrl-D beendet. ui.more_lines = ... %zu Zeilen mehr ui.working = laeuft... +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.compacted = Kontext kompaktiert: %zu->%zu Nachrichten, %s->%s (%s->%s) ui.steering_queued = Steuerung eingereiht diff --git a/share/locale/en.msg b/share/locale/en.msg index 5da0662..7ba92e5 100644 --- a/share/locale/en.msg +++ b/share/locale/en.msg @@ -6,6 +6,11 @@ ui.ready = ready. Enter sends, Ctrl-D quits. ui.more_lines = ... %zu more lines ui.working = working... +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.compacted = context compacted: %zu->%zu msgs, %s->%s (%s->%s) ui.steering_queued = steering queued diff --git a/share/locale/pt_BR.msg b/share/locale/pt_BR.msg index 8ac24d8..406740d 100644 --- a/share/locale/pt_BR.msg +++ b/share/locale/pt_BR.msg @@ -7,6 +7,11 @@ ui.ready = pronto. Enter envia, Ctrl-D sai. ui.more_lines = ... %zu linhas a mais ui.working = trabalhando... +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.compacted = contexto compactado: %zu->%zu msgs, %s->%s (%s->%s) ui.steering_queued = direcionamento na fila ui.prompt_mark = > diff --git a/src/backend/engine.c b/src/backend/engine.c index dc3175d..5248010 100644 --- a/src/backend/engine.c +++ b/src/backend/engine.c @@ -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); diff --git a/src/backend/http.c b/src/backend/http.c new file mode 100644 index 0000000..41a05b6 --- /dev/null +++ b/src/backend/http.c @@ -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 +#include +#include +#include +#include +#include + +#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; +} diff --git a/src/backend/http.h b/src/backend/http.h new file mode 100644 index 0000000..aefb895 --- /dev/null +++ b/src/backend/http.h @@ -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 + +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 */ diff --git a/src/backend/openai_server.c b/src/backend/openai_server.c new file mode 100644 index 0000000..b4b9ece --- /dev/null +++ b/src/backend/openai_server.c @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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_ */ + 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; +} diff --git a/src/backend/openai_server.h b/src/backend/openai_server.h new file mode 100644 index 0000000..0b549ae --- /dev/null +++ b/src/backend/openai_server.h @@ -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 + +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 */ diff --git a/src/backend/providers.c b/src/backend/providers.c index 6f757a3..b4264e3 100644 --- a/src/backend/providers.c +++ b/src/backend/providers.c @@ -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; } diff --git a/src/backend/session.c b/src/backend/session.c index 1e8b2b6..503879d 100644 --- a/src/backend/session.c +++ b/src/backend/session.c @@ -21,6 +21,7 @@ #include "mcp.h" #include "log.h" #include +#include #include 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) diff --git a/src/backend/transport.c b/src/backend/transport.c index 9302045..e520664 100644 --- a/src/backend/transport.c +++ b/src/backend/transport.c @@ -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) { diff --git a/src/backend/transport_anthropic.c b/src/backend/transport_anthropic.c index 0c17377..e19f532 100644 --- a/src/backend/transport_anthropic.c +++ b/src/backend/transport_anthropic.c @@ -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; } diff --git a/src/backend/transport_openai.c b/src/backend/transport_openai.c index e30a979..1861c2a 100644 --- a/src/backend/transport_openai.c +++ b/src/backend/transport_openai.c @@ -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; } diff --git a/src/frontend/curses.c b/src/frontend/curses.c index bf413db..8fbd243 100644 --- a/src/frontend/curses.c +++ b/src/frontend/curses.c @@ -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) { /* diff --git a/src/frontend/protocol.c b/src/frontend/protocol.c index 0b8f91c..0071396 100644 --- a/src/frontend/protocol.c +++ b/src/frontend/protocol.c @@ -13,6 +13,7 @@ * a conversation that may run `run` with the owner's rights. */ #define _GNU_SOURCE 1 +#include #include #include #include @@ -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; } diff --git a/src/frontend/protocol.h b/src/frontend/protocol.h index f972e52..6425043 100644 --- a/src/frontend/protocol.h +++ b/src/frontend/protocol.h @@ -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); diff --git a/src/frontend/ui_backend.h b/src/frontend/ui_backend.h index 80b4c99..2d7597d 100644 --- a/src/frontend/ui_backend.h +++ b/src/frontend/ui_backend.h @@ -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), diff --git a/src/frontend/ui_local.c b/src/frontend/ui_local.c index d322a63..dfe0cfd 100644 --- a/src/frontend/ui_local.c +++ b/src/frontend/ui_local.c @@ -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, diff --git a/src/frontend/ui_remote.c b/src/frontend/ui_remote.c index 7564794..859cedd 100644 --- a/src/frontend/ui_remote.c +++ b/src/frontend/ui_remote.c @@ -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; diff --git a/src/main.c b/src/main.c index e4c947c..acb11b2 100644 --- a/src/main.c +++ b/src/main.c @@ -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; diff --git a/tests/fake_gateway.py b/tests/fake_gateway.py new file mode 100644 index 0000000..6848451 --- /dev/null +++ b/tests/fake_gateway.py @@ -0,0 +1,97 @@ +# fake upstream for tests/test_gateway_openai.sh +# argv: port, read_path, write_path +# It answers the gateway's upstream requests: a gw_ tool call (executed by the +# gateway), a caller tool call (returned to the test client), or a final text. +import http.server, json, sys + + +def sse(w, obj): + w.write(("data: " + json.dumps(obj) + "\n\n").encode()) + + +class H(http.server.BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_GET(self): + self.send_response(200) + self.end_headers() + self.wfile.write(b"x") + + def do_POST(self): + n = int(self.headers.get("Content-Length", 0)) + req = json.loads(self.rfile.read(n)) + msgs = req.get("messages", []) + last = msgs[-1] if msgs else {} + user = "" + for m in msgs: + if m.get("role") == "user": + user = m.get("content") or "" + stream = bool(req.get("stream")) + if last.get("role") == "tool": + return self.reply(stream, + content="ERGEBNIS: " + + (last.get("content") or "")[:300]) + if "gw-read" in user: + return self.reply(stream, call=("gw_read", + json.dumps({"path": + sys.argv[2]}))) + if "gw-write" in user: + return self.reply(stream, call=("gw_write", json.dumps( + {"path": sys.argv[3], "content": "geschrieben\n"}))) + if "caller" in user: + return self.reply(stream, call=("caller_tool", '{"x": 1}')) + if "mixed" in user: + return self.reply(stream, call=("gw_echo", + '{"text": "mixed-local"}'), + second=("caller_tool", '{"x": 2}')) + if "stream" in user: + return self.reply(stream, content="gestreamt") + return self.reply(stream, call=("gw_echo", + '{"text": "hallo-vom-gw"}')) + + def reply(self, stream, content="", call=None, second=None): + self.send_response(200) + if stream: + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + w = self.wfile.write + if call: + nm, args = call + sse(w, {"choices": [{"delta": {"tool_calls": [{ + "index": 0, "id": "c1", "type": "function", + "function": {"name": nm, "arguments": args}}]}}]}) + if second: + nm, args = second + sse(w, {"choices": [{"delta": {"tool_calls": [{ + "index": 1, "id": "c2", "type": "function", + "function": {"name": nm, "arguments": args}}]}}]}) + else: + sse(w, {"choices": [{"delta": {"content": content}}]}) + sse(w, {"choices": [{"delta": {}, + "finish_reason": "stop"}]}) + w(b"data: [DONE]\n\n") + return + msg = {"role": "assistant", + "content": content if content else None} + if call: + nm, args = call + msg["tool_calls"] = [{"id": "c1", "type": "function", + "function": {"name": nm, + "arguments": args}}] + if second: + nm, args = second + msg["tool_calls"].append( + {"id": "c2", "type": "function", + "function": {"name": nm, "arguments": args}}) + body = json.dumps({"choices": [{"index": 0, "message": msg}], + "usage": {"prompt_tokens": 11, + "completion_tokens": 7}}).encode() + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), + H).serve_forever() diff --git a/tests/test_gateway_openai.sh b/tests/test_gateway_openai.sh new file mode 100755 index 0000000..e6498ee --- /dev/null +++ b/tests/test_gateway_openai.sh @@ -0,0 +1,162 @@ +#!/bin/sh +# +# splinter -- the OpenAI-compatible gateway. +# +# What it guards: a completion with a local gw_ tool is answered after the +# gateway runs it here; a caller tool is returned to the client with its +# arguments; the caller's follow-up reaches the upstream; gw_read reads locally; +# gw_write needs --autonomous; a token is enforced; gw_ is reserved; the client +# can ask for SSE; and beyond loopback the server refuses without a token. +set -u +cd "$(dirname "$0")/.." || exit 1 +D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-gw-XXXXXX") || exit 1 +P0=$((20000 + $$ % 8000)) +PF=$P0 +P1=$((P0 + 70)) +P2=$((P0 + 71)) +P3=$((P0 + 72)) +P4=$((P0 + 73)) +F= +G1= +G2= +G3= +fails=0 +cleanup() { + [ -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 + +check() { if "$@"; then :; else echo "FAIL $*"; fails=$((fails + 1)); fi; } +checkgrep() { # pattern file + if grep -q -- "$1" "$2" 2>/dev/null; then :; else + echo "FAIL missing '$1' in $2" + [ -f "$2" ] && head -3 "$2" + fails=$((fails + 1)) + fi +} +wait_port() { # port, tries + i=0 + while [ "$i" -lt "$2" ]; do + curl -s -o /dev/null "http://127.0.0.1:$1/v1/models" && return 0 + i=$((i + 1)) + sleep 0.3 + done + return 1 +} +post() { # port, body, out + curl -s -X POST "http://127.0.0.1:$1/v1/chat/completions" \ + -H 'Content-Type: application/json' -d "$2" > "$3" +} + +mkdir -p "$D/h1" "$D/h2" "$D/h3" "$D/h4" +printf 'inhalt-von-gw-read\n' > "$D/read.txt" +python3 -I tests/fake_gateway.py "$PF" "$D/read.txt" "$D/written.txt" \ + > "$D/fake.log" 2>&1 & +F=$! +sleep 0.8 + +HOME=$D/h1 SPLINTER_LOCALE=en ./splinter --no-config --autonomous \ + --endpoint "http://127.0.0.1:$PF/v1" --model up \ + --openai-listen 127.0.0.1 --openai-listen-port "$P1" \ + > "$D/g1.log" 2>&1 & +G1=$! +HOME=$D/h2 SPLINTER_LOCALE=en ./splinter --no-config \ + --endpoint "http://127.0.0.1:$PF/v1" --model up \ + --openai-listen 127.0.0.1 --openai-listen-port "$P2" \ + > "$D/g2.log" 2>&1 & +G2=$! +HOME=$D/h3 SPLINTER_LOCALE=en SPLINTER_GATEWAY_TOKEN=geheim ./splinter \ + --no-config --endpoint "http://127.0.0.1:$PF/v1" --model up \ + --openai-listen 127.0.0.1 --openai-listen-port "$P3" \ + > "$D/g3.log" 2>&1 & +G3=$! +if ! wait_port "$P1" 40 || ! wait_port "$P2" 40; then + echo "FAIL a gateway did not start" + cat "$D/g1.log" "$D/g2.log" + exit 1 +fi +sleep 1 + +# the model list names what the run configured +curl -s "http://127.0.0.1:$P1/v1/models" > "$D/models.json" +checkgrep '"id":"up"' "$D/models.json" + +# a local gw_ tool runs here and the model answers with its observation +post "$P1" '{"model":"x","messages":[{"role":"user","content":"gw-local"}]}' \ + "$D/local.json" +checkgrep 'ERGEBNIS: hallo-vom-gw' "$D/local.json" + +# gw_read reads a file on this host +post "$P1" '{"model":"x","messages":[{"role":"user","content":"gw-read"}]}' \ + "$D/read.json" +checkgrep 'inhalt-von-gw-read' "$D/read.json" + +# a caller tool comes back to the client, with the caller's name +post "$P1" '{"model":"x","messages":[{"role":"user","content":"caller bitte"}],"tools":[{"type":"function","function":{"name":"caller_tool","description":"client","parameters":{"type":"object"}}}]}' \ + "$D/caller.json" +checkgrep '"name":"caller_tool"' "$D/caller.json" +checkgrep '"finish_reason":"tool_calls"' "$D/caller.json" +# ... and its result goes back upstream +post "$P1" '{"model":"x","messages":[{"role":"user","content":"caller bitte"},{"role":"assistant","content":"","tool_calls":[{"id":"c1","type":"function","function":{"name":"caller_tool","arguments":"{\"x\":1}"}}]},{"role":"tool","tool_call_id":"c1","content":"client-result"}]}' \ + "$D/caller2.json" +checkgrep 'ERGEBNIS: client-result' "$D/caller2.json" + +# a mixed reply runs the local call and asks the model again +post "$P1" '{"model":"x","messages":[{"role":"user","content":"mixed"}]}' \ + "$D/mixed.json" +checkgrep 'ERGEBNIS: mixed-local' "$D/mixed.json" + +# mutating tools need --autonomous +rm -f "$D/written.txt" +post "$P2" '{"model":"x","messages":[{"role":"user","content":"gw-write"}]}' \ + "$D/write-denied.json" +checkgrep 'denied: the gateway runs mutating' "$D/write-denied.json" +check test ! -e "$D/written.txt" +post "$P1" '{"model":"x","messages":[{"role":"user","content":"gw-write"}]}' \ + "$D/write-ok.json" +check test -s "$D/written.txt" +checkgrep 'geschrieben' "$D/written.txt" + +# the client can ask for SSE +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":"stream bitte"}]}' \ + > "$D/stream.txt" +checkgrep 'gestreamt' "$D/stream.txt" +checkgrep '\[DONE\]' "$D/stream.txt" + +# a token is required when one is configured +check test "$(curl -s -o /dev/null -w '%{http_code}' -X POST \ + "http://127.0.0.1:$P3/v1/chat/completions" -H 'Content-Type: application/json' \ + -d '{"model":"x","messages":[{"role":"user","content":"hi"}]}')" = 401 +check test "$(curl -s -o /dev/null -w '%{http_code}' -X POST \ + "http://127.0.0.1:$P3/v1/chat/completions" -H 'Authorization: Bearer geheim' \ + -H 'Content-Type: application/json' \ + -d '{"model":"x","messages":[{"role":"user","content":"hi"}]}')" = 200 + +# gw_ is the gateway's namespace +check test "$(curl -s -o /dev/null -w '%{http_code}' -X POST \ + "http://127.0.0.1:$P1/v1/chat/completions" -H 'Content-Type: application/json' \ + -d '{"model":"x","messages":[{"role":"user","content":"hi"}],"tools":[{"type":"function","function":{"name":"gw_read","parameters":{"type":"object"}}}]}')" = 400 + +# beyond loopback there is no gateway without a token +HOME=$D/h4 SPLINTER_LOCALE=en timeout 10 ./splinter --no-config \ + --endpoint "http://127.0.0.1:$PF/v1" --model up \ + --openai-listen 0.0.0.0 --openai-listen-port "$P4" \ + > "$D/noloop.out" 2>&1 +rc=$? +if [ "$rc" -eq 124 ]; then + echo "FAIL a gateway on 0.0.0.0 without a token hung" + fails=$((fails + 1)) +fi +checkgrep 'beyond loopback' "$D/noloop.out" + +if [ "$fails" -eq 0 ]; then + echo "test_gateway_openai: ok" + exit 0 +fi +exit 1 diff --git a/tests/test_protocol.sh b/tests/test_protocol.sh index b928146..f7b30e8 100755 --- a/tests/test_protocol.sh +++ b/tests/test_protocol.sh @@ -83,9 +83,12 @@ s.connect(sys.argv[1]) f = s.makefile("rw", encoding="utf-8") seen = [] +sessA = "" while "state" not in seen: ev = json.loads(f.readline()) seen.append(ev.get("ev")) + if ev.get("ev") == "state": + sessA = ev.get("session", "") if ev.get("ev") == "ready" and ev.get("protocol") != 2: print("bad protocol", ev, file=sys.stderr) sys.exit(1) @@ -148,6 +151,63 @@ while True: if ev.get("ev") == "turn": print("long_prompt_ok" if ev.get("ok") else "long_prompt_failed") break + +# ---- sessions: list, create, switch back, a missing id is an error ---- +f.write(json.dumps({"cmd": "sessions"}) + "\n") +f.flush() +while True: + ev = json.loads(f.readline()) + if ev.get("ev") == "sessions": + cur = [i.get("id") for i in ev.get("items", []) if i.get("current")] + print("sessions_ok" if cur == [sessA] else "sessions_bad") + break +f.write(json.dumps({"cmd": "open", "session": "new"}) + "\n") +f.flush() +sessB = "" +while True: + ev = json.loads(f.readline()) + if ev.get("ev") == "opened": + sessB = ev.get("session", "") + break +print("open_new_ok" if sessB and sessB != sessA else "open_new_bad") +f.write(json.dumps({"cmd": "sessions"}) + "\n") +f.flush() +while True: + ev = json.loads(f.readline()) + if ev.get("ev") == "sessions": + ids = [i.get("id") for i in ev.get("items", [])] + cur = [i.get("id") for i in ev.get("items", []) if i.get("current")] + print("sessions_two_ok" if sessA in ids and sessB in ids and + cur == [sessB] else "sessions_two_bad") + break +f.write(json.dumps({"cmd": "open", "session": sessA}) + "\n") +f.flush() +while True: + ev = json.loads(f.readline()) + if ev.get("ev") == "opened": + print("open_back_ok" if ev.get("session") == sessA else + "open_back_bad") + break +f.write(json.dumps({"cmd": "history"}) + "\n") +f.flush() +while True: + ev = json.loads(f.readline()) + if ev.get("ev") == "history": + texts = [it.get("text", "") for it in ev.get("items", [])] + print("history_restored" if "hallo" in texts else + "history_lost") + break +f.write(json.dumps({"cmd": "open", "session": "does-not-exist"}) + "\n") +f.flush() +ev = json.loads(f.readline()) +print("open_missing" if ev.get("ev") == "error" else "open_missing_bad") +f.write(json.dumps({"cmd": "state"}) + "\n") +f.flush() +while True: + ev = json.loads(f.readline()) + if ev.get("ev") == "state": + print("still_a" if ev.get("session") == sessA else "not_a") + break PY checkgrep 'ready' "$D/events.out" checkgrep 'state' "$D/events.out" @@ -159,6 +219,13 @@ checkgrep 'commands' "$D/events.out" checkgrep 'shell_bytes [0-9]\{4,\}' "$D/events.out" checkgrep 'long_prompt_ok' "$D/events.out" checkgrep 'history_ok' "$D/events.out" +checkgrep 'sessions_ok' "$D/events.out" +checkgrep 'open_new_ok' "$D/events.out" +checkgrep 'sessions_two_ok' "$D/events.out" +checkgrep 'open_back_ok' "$D/events.out" +checkgrep 'history_restored' "$D/events.out" +checkgrep 'open_missing$' "$D/events.out" +checkgrep 'still_a' "$D/events.out" checkgrep 'answer fertig' "$D/events.out" check grep -q 'vom gateway' "$D/out.txt" diff --git a/tests/test_reconnect.sh b/tests/test_reconnect.sh new file mode 100755 index 0000000..5c3269b --- /dev/null +++ b/tests/test_reconnect.sh @@ -0,0 +1,122 @@ +#!/bin/sh +# +# splinter -- --attach survives a backend restart. +# +# What it guards: when the served engine dies, the screen keeps running and +# says so; a new server on the same socket is found, the session the screen was +# on is asked for by id, its history comes back and a new turn works. +set -u +cd "$(dirname "$0")/.." || exit 1 +if ! command -v tmux >/dev/null 2>&1; then + echo "test_reconnect: skipped (no tmux)" + exit 0 +fi +D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-reconnect-XXXXXX") || exit 1 +unset TMUX TMUX_PANE +export TMUX_TMPDIR="$D" +own_server() { + if [ -n "${TMUX:-}" ] || [ "${TMUX_TMPDIR:-}" != "$D" ]; then + echo "test_reconnect: refusing to touch a tmux server this test does not own" >&2 + exit 1 + fi +} +killserver() { own_server; tmux kill-server 2>/dev/null; } +S=splinter-reconnect-$$ +P=$((20000 + ($$ + 11) % 30000)) +F= +G1= +G2= +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 + rm -rf "$D" +} +trap cleanup EXIT +check() { if "$@"; then :; else echo "FAIL $*"; fails=$((fails + 1)); fi; } +shows() { + for i in $(seq 1 60); do + tmux capture-pane -t $S -p | grep -q -- "$1" && return 0 + sleep 0.5 + done + return 1 +} +idle_prompt() { + for i in $(seq 1 60); do + tmux capture-pane -t $S -p | grep -q '^build>' && return 0 + sleep 0.5 + done + return 1 +} +typed() { tmux send-keys -t $S -l "$1"; } +key() { tmux send-keys -t $S "$@"; } +start_server() { # log file + HOME=$D/server SPLINTER_LOCALE=en ./splinter --no-config --autonomous \ + --endpoint "http://127.0.0.1:$P/v1/chat/completions" --model m \ + --serve --socket "$D/sock" > "$1" 2>&1 & + echo $! +} +wait_sock() { + for i in $(seq 1 60); do + [ -S "$D/sock" ] && return 0 + sleep 0.2 + done + return 1 +} + +mkdir -p "$D/server" "$D/client" +python3 -I tests/fake_telegram.py "$P" "$D/out.txt" "$D/sent.log" ok \ + > "$D/fake.log" 2>&1 & +F=$! +sleep 0.8 +G1=$(start_server "$D/s1.log") +if ! wait_sock; then + echo "FAIL server 1 has no socket" + cat "$D/s1.log" + exit 1 +fi +HOME=$D/server SPLINTER_LOCALE=en ./splinterctl --socket "$D/sock" \ + --say "single word ok" > /dev/null 2>&1 +sess=$(HOME=$D/server SPLINTER_LOCALE=en ./splinterctl --socket "$D/sock" \ + --cmd /status 2>/dev/null | sed -n 's/^ session //p' | head -1) +check test -n "$sess" + +tmux new-session -d -s $S -x 110 -y 30 \ + "HOME=$D/client SPLINTER_LOCALE=en ./splinter --no-config \ + --attach --socket $D/sock 2>/dev/null; echo \$? > $D/rc" +check shows 'Enter sends' +check shows "$sess" + +# the server goes away; the screen must keep running +kill "$G1" 2>/dev/null +G1= +sleep 2 +check tmux has-session -t $S +check shows 'connection lost' + +# a new server on the same socket: the screen finds it and restores the session +G2=$(start_server "$D/s2.log") +if ! wait_sock; then + echo "FAIL server 2 has no socket" + cat "$D/s2.log" + exit 1 +fi +check shows 'reconnected' +check shows "$sess" + +typed 'single word ok'; key Enter +check idle_prompt +check shows ' ok' + +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 + +if [ "$fails" -eq 0 ]; then + echo "test_reconnect: ok" + exit 0 +fi +exit 1