backend/frontend: an engine every front end can talk to

The harness was two halves that could not see each other: main.c built the
agent, ui.c ran it -- with the curses thread model, the approval condition
variable, the slash commands and the provider switching inside the drawing
code. A second front end had to copy all of it.

Now:

  src/backend/   engine.c owns the session, the turn thread, the event queue
                 and every command; agent, transports, tools, session, config,
                 providers, plugins and the protocol servers move here.
  src/frontend/  curses.c draws and reads keys through ui_backend.h;
                 ui_local.c is the engine in this process, ui_remote.c is a
                 served engine behind a socket. protocol.c serves the engine
                 as JSON lines (protocol 2: history, approvals, steering);
                 client.c is splinterctl, the reference client.

splinter --serve / --attach: the same screen runs as a client of a served
engine, so the socket carries everything the front end needs. docs/PROTOCOL.md
and docs/FRONTENDS.md describe the contract; docs/proto-example.py is a
60-line client. tests/test_engine, test_protocol and test_attach cover the
event order, the socket and the attach mode.

Review fixes in the same tree: dynamic line buffers (9 KB prompts and 8 KB
events were truncated), a turn event no longer ends the busy window (steer
leftovers), the screen finalises every turn, /new keeps the profile, reopens
the log and gets unique ids, the profile is remembered in <session>.agent so
--resume comes back in it, agent statistics are a locked snapshot (no data
race), !shell keeps 64 KiB with a marker, the socket probes for a live server,
compares its inode and sets CLOEXEC/SNDTIMEO, exit 2 means configuration,
BSD peer checks use getpeereid, and the i18n checker scans the new
subdirectories again.

Includes the parallel session's SSE fix: the parser reports what a line
produced, so a tool name no longer lands in the answer ("readread").
This commit is contained in:
lotherk committed 2026-11-16 09:06:51 +00:00
1 parent c9f21be89b
commit a9f175c25b
99 files changed
+8927 -4197

No files matched your search

+2 -1
View File
@@ -1,5 +1,6 @@
*.o
splinter
splinterctl
tests/test_buf
tests/test_tool
tests/test_session
@@ -15,7 +16,7 @@ tests/test_*
# python bytecode from the test helpers
__pycache__/
src/catalogs.c
src/backend/catalogs.c
# Claude Code worktrees and local session state
.claude/
+85 -56
View File
@@ -5,13 +5,16 @@
# make curses builds the vendored NetBSD curses explicitly
# make clean removes generated files only
#
# The layout is deliberate: all logic lives in libsplinter.so. The binary and
# every plugin link against that one library, so there is exactly one copy of
# The layout is deliberate: the backend lives in libsplinter.so (src/backend,
# the engine and everything it owns). The front ends are src/frontend/curses.c
# (the screen), src/frontend/protocol.c (the engine on a socket) and
# src/frontend/client.c (the reference client); src/main.c launches them.
# Every one of them links that single library, so there is exactly one copy of
# each symbol in the process. Two copies would mean two registries.
CC ?= cc
CFLAGS ?= -std=c99 -O2 -Wall -Wextra -Werror -D_POSIX_C_SOURCE=200809L \
-fPIC -Iinclude -Isrc -Ivendor/libmcp -Ivendor/netbsd-curses/libcurses
-fPIC -Iinclude -Isrc/backend -Isrc/frontend -Ivendor/libmcp -Ivendor/netbsd-curses/libcurses
LDFLAGS ?=
LIBS ?= -lpthread
PREFIX ?= /usr/local
@@ -21,12 +24,15 @@ CURSES_A = $(CURSES_DIR)/libcurses/libcurses.a \
$(CURSES_DIR)/libterminfo/libterminfo.a
LIB = libsplinter.so
LIBOBJ = src/buf.o src/tool.o src/session.o src/conv.o src/transport.o \
src/json.o src/sse.o src/openai.o src/transport_openai.o \
src/anthropic.o src/transport_anthropic.o src/builtin.o \
src/agent.o src/theme.o src/palettes.o src/decomp.o src/i18n.o src/delegate.o src/telegram.o src/log.o src/cmdscript.o src/folder.o src/interview.o src/ack.o src/mcpserver.o src/skills.o src/memory.o src/prompt.o src/config.o src/plugin.o src/curl.o src/swarm.o src/provstate.o src/md.o src/tgmd.o src/b64.o src/a2aserver.o src/providers.o src/usage.o src/confblock.o src/agents.o src/catalogs.o
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
BIN = splinter
BINOBJ = src/main.o src/ui.o
BINOBJ = src/main.o src/frontend/curses.o src/frontend/protocol.o \
src/frontend/ui_local.o src/frontend/ui_remote.o
CLIENT = splinterctl
CLIENTOBJ = src/frontend/client.o
PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \
plugins/cli/cli.so plugins/focus/focus.so plugins/mcp/mcp.so \
plugins/ring/ring.so plugins/reminder/reminder.so \
@@ -38,13 +44,13 @@ PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \
plugins/tmux/tmux.so
TESTS = tests/test_buf tests/test_tool tests/test_session tests/test_conv \
tests/test_transport tests/test_agent tests/test_openai \
tests/test_theme tests/test_plugin tests/test_memory tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_anthropic tests/test_cli tests/test_compactor tests/test_secrets tests/test_mcpclient tests/test_kids tests/test_lifecycle tests/test_md tests/test_tgmd tests/test_providers tests/test_b64 tests/test_pause tests/test_swarm tests/test_provstate tests/test_planner tests/test_tmux tests/test_usage tests/test_agents tests/test_confblock tests/test_jobs
tests/test_theme tests/test_plugin tests/test_memory tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_anthropic tests/test_cli tests/test_compactor tests/test_secrets tests/test_mcpclient tests/test_kids tests/test_lifecycle tests/test_md tests/test_tgmd tests/test_providers tests/test_b64 tests/test_pause tests/test_swarm tests/test_provstate tests/test_planner tests/test_tmux tests/test_usage tests/test_agents tests/test_confblock tests/test_jobs tests/test_engine
RPATH = -Wl,-rpath,'$$ORIGIN'
PLUGIN_RPATH = -Wl,-rpath,'$$ORIGIN/../..'
TEST_RPATH = -Wl,-rpath,'$$ORIGIN/..'
all: $(LIB) $(BIN) $(PLUGIN)
all: $(LIB) $(BIN) $(CLIENT) $(PLUGIN)
# The vendored tree ships a GNUmakefile; this is the only place that needs GNU
# make, and it is why the comment above says so out loud.
@@ -54,7 +60,7 @@ $(CURSES_A):
curses: $(CURSES_A)
src/catalogs.c: share/locale/de.msg share/locale/en.msg share/locale/pt_BR.msg tools/embed_catalogs.sh
src/backend/catalogs.c: share/locale/de.msg share/locale/en.msg share/locale/pt_BR.msg tools/embed_catalogs.sh
sh tools/embed_catalogs.sh share/locale/*.msg > $@
$(LIB): $(LIBOBJ) $(CURSES_A)
@@ -62,6 +68,12 @@ $(LIB): $(LIBOBJ) $(CURSES_A)
# curses belongs to the front end, not to the library: a plugin that drew into
# a WINDOW would be a plugin holding the UI thread's state.
# The reference client links the library for the JSON it cannot be bothered to
# write twice, but never the curses code and never the engine's internals.
$(CLIENT): $(CLIENTOBJ) $(LIB)
$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(CLIENTOBJ) -L. -lsplinter $(RPATH) \
$(LIBS)
$(BIN): $(BINOBJ) $(LIB)
$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(BINOBJ) -L. -lsplinter $(RPATH) \
$(CURSES_A) $(LIBS)
@@ -109,55 +121,63 @@ plugins/cps/cps.so: plugins/cps/cps.c $(LIB)
# A cli delegate's child has to find plugins/cli/cli.so. Beside an installed
# binary there is no such file, so the build directory this binary came from is
# compiled in as the last resort (sp_delegate_cli_plugin in src/delegate.c).
src/delegate.o: src/delegate.c
# compiled in as the last resort (sp_delegate_cli_plugin in src/backend/delegate.c).
src/backend/delegate.o: src/backend/delegate.c
$(CC) $(CFLAGS) -DSPLINTER_PLUGIN_DIR='"$(CURDIR)"' -c -o $@ $<
# POSIX make has no automatic dependencies. Rather than a list that is wrong
# the day somebody adds an #include, every object depends on the headers that
# make up the interface: a change there rebuilds everything that could see it.
HDRS = include/splinter.h include/splinter_plugin.h src/config.h src/ack.h \
src/curl.h src/log.h src/i18n.h src/md.h src/b64.h src/a2aserver.h
HDRS = include/splinter.h include/splinter_engine.h include/splinter_plugin.h \
src/backend/config.h src/backend/ack.h \
src/backend/curl.h src/backend/log.h src/backend/i18n.h src/backend/md.h src/backend/b64.h src/backend/a2aserver.h
$(LIBOBJ) $(BINOBJ): $(HDRS)
$(PLUGIN): $(HDRS)
src/agent.o: include/splinter.h
src/buf.o: include/splinter.h
src/tool.o: include/splinter.h
src/session.o: include/splinter.h
src/transport.o: include/splinter.h
src/conv.o: include/splinter.h
src/json.o: vendor/libmcp/mcp.h
src/sse.o: include/splinter.h vendor/libmcp/mcp.h
src/openai.o: include/splinter.h vendor/libmcp/mcp.h
src/transport_openai.o: include/splinter.h src/curl.h src/log.h
src/anthropic.o: include/splinter.h vendor/libmcp/mcp.h
src/transport_anthropic.o: include/splinter.h src/curl.h src/log.h vendor/libmcp/mcp.h
src/curl.o: src/curl.h include/splinter.h
src/builtin.o: include/splinter.h
src/theme.o: src/theme.h src/palettes.h include/splinter.h
src/palettes.o: src/palettes.h
src/decomp.o: src/decomp.h
src/i18n.o: src/i18n.h include/splinter.h
src/delegate.o: src/config.h include/splinter.h
src/telegram.o: include/splinter.h src/curl.h src/ack.h
src/log.o: src/log.h
src/cmdscript.o: src/cmdscript.h include/splinter.h
src/folder.o: src/folder.h include/splinter.h
src/ack.o: src/ack.h include/splinter.h
src/interview.o: src/interview.h include/splinter.h
src/mcpserver.o: src/mcpserver.h include/splinter.h
src/skills.o: src/skills.h src/config.h include/splinter.h
src/prompt.o: src/prompt.h include/splinter.h
src/memory.o: src/memory.h src/config.h include/splinter.h
src/config.o: src/config.h include/splinter.h
src/plugin.o: include/splinter.h include/splinter_plugin.h
src/ui.o: src/ui.h src/theme.h src/decomp.h src/i18n.h include/splinter.h include/splinter_plugin.h src/md.h
src/md.o: src/md.h include/splinter.h
src/b64.o: src/b64.h include/splinter.h
src/a2aserver.o: src/a2aserver.h include/splinter.h vendor/libmcp/mcp.h
src/providers.o: src/providers.h src/config.h include/splinter.h include/splinter_plugin.h
src/main.o: include/splinter.h src/config.h src/i18n.h include/splinter_plugin.h src/ui.h src/theme.h src/a2aserver.h
src/backend/agent.o: include/splinter.h
src/backend/buf.o: include/splinter.h
src/backend/tool.o: include/splinter.h
src/backend/session.o: include/splinter.h
src/backend/transport.o: include/splinter.h
src/backend/conv.o: include/splinter.h
src/backend/json.o: vendor/libmcp/mcp.h
src/backend/sse.o: include/splinter.h vendor/libmcp/mcp.h
src/backend/openai.o: include/splinter.h vendor/libmcp/mcp.h
src/backend/transport_openai.o: include/splinter.h src/backend/curl.h src/backend/log.h
src/backend/anthropic.o: include/splinter.h vendor/libmcp/mcp.h
src/backend/transport_anthropic.o: include/splinter.h src/backend/curl.h src/backend/log.h vendor/libmcp/mcp.h
src/backend/curl.o: src/backend/curl.h include/splinter.h
src/backend/builtin.o: include/splinter.h
src/backend/theme.o: src/backend/theme.h src/backend/palettes.h include/splinter.h
src/backend/palettes.o: src/backend/palettes.h
src/backend/decomp.o: src/backend/decomp.h
src/backend/i18n.o: src/backend/i18n.h include/splinter.h
src/backend/delegate.o: src/backend/config.h include/splinter.h
src/backend/telegram.o: include/splinter.h src/backend/curl.h src/backend/ack.h
src/backend/log.o: src/backend/log.h
src/backend/cmdscript.o: src/backend/cmdscript.h include/splinter.h
src/backend/folder.o: src/backend/folder.h include/splinter.h
src/backend/ack.o: src/backend/ack.h include/splinter.h
src/backend/interview.o: src/backend/interview.h include/splinter.h
src/backend/mcpserver.o: src/backend/mcpserver.h include/splinter.h
src/backend/skills.o: src/backend/skills.h src/backend/config.h include/splinter.h
src/backend/prompt.o: src/backend/prompt.h include/splinter.h
src/backend/memory.o: src/backend/memory.h src/backend/config.h include/splinter.h
src/backend/config.o: src/backend/config.h include/splinter.h
src/backend/plugin.o: include/splinter.h include/splinter_plugin.h
src/frontend/curses.o: src/frontend/ui.h src/frontend/ui_backend.h \
include/splinter_engine.h src/backend/theme.h src/backend/decomp.h src/backend/i18n.h include/splinter.h include/splinter_plugin.h src/backend/md.h
src/backend/md.o: src/backend/md.h include/splinter.h
src/backend/b64.o: src/backend/b64.h include/splinter.h
src/backend/a2aserver.o: src/backend/a2aserver.h include/splinter.h vendor/libmcp/mcp.h
src/frontend/ui_local.o: src/frontend/ui_backend.h include/splinter_engine.h src/frontend/ui.h
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/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 \
src/frontend/ui_backend.h src/backend/config.h src/backend/i18n.h include/splinter_plugin.h src/frontend/ui.h src/backend/theme.h src/backend/a2aserver.h
tests/test_buf: tests/test_buf.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_buf.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
@@ -192,7 +212,7 @@ tests/test_ack: tests/test_ack.c $(LIB)
tests/test_i18n: tests/test_i18n.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_i18n.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_ascii: tests/test_ascii.c $(LIB) $(BINOBJ)
$(CC) $(CFLAGS) -o $@ tests/test_ascii.c src/ui.o -L. -lsplinter \
$(CC) $(CFLAGS) -o $@ tests/test_ascii.c src/frontend/curses.o -L. -lsplinter \
$(TEST_RPATH) $(CURSES_A) $(LIBS)
tests/test_md: tests/test_md.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_md.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
@@ -217,6 +237,8 @@ tests/test_agents: tests/test_agents.c $(LIB)
tests/test_confblock: tests/test_confblock.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_confblock.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_engine: tests/test_engine.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_engine.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_usage: tests/test_usage.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_usage.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_tmux: tests/test_tmux.c $(LIB) $(PLUGIN)
@@ -248,7 +270,7 @@ tests/test_lifecycle: tests/test_lifecycle.c $(LIB) tests/plugin_lifecycle.so
tests/test_plugin: tests/test_plugin.c $(LIB) $(PLUGIN)
$(CC) $(CFLAGS) -o $@ tests/test_plugin.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
check: $(LIB) $(BIN) $(PLUGIN) $(TESTS)
check: $(LIB) $(BIN) $(CLIENT) $(PLUGIN) $(TESTS)
@set -e; python3 tools/check_i18n.py; \
export LD_LIBRARY_PATH=.; \
for t in $(TESTS); do echo "== $$t"; ./$$t; done; \
@@ -265,6 +287,8 @@ check: $(LIB) $(BIN) $(PLUGIN) $(TESTS)
echo "== tests/test_agents_ui.sh"; sh tests/test_agents_ui.sh; \
echo "== tests/test_a2a_input.sh"; sh tests/test_a2a_input.sh; \
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 "all tests passed"
# The installed binary finds its own library through an rpath relative to itself
@@ -283,6 +307,11 @@ install: all
$(CURSES_A) $(LIBS)
mv -f $(DESTDIR)$(PREFIX)/bin/.splinter.new \
$(DESTDIR)$(PREFIX)/bin/splinter
$(CC) $(CFLAGS) $(LDFLAGS) -Wl,-rpath,'$$ORIGIN/../lib' \
-o $(DESTDIR)$(PREFIX)/bin/.$(CLIENT).new $(CLIENTOBJ) -L. -lsplinter \
$(LIBS)
mv -f $(DESTDIR)$(PREFIX)/bin/.$(CLIENT).new \
$(DESTDIR)$(PREFIX)/bin/$(CLIENT)
cp $(LIB) $(DESTDIR)$(PREFIX)/lib/.$(LIB).new
mv -f $(DESTDIR)$(PREFIX)/lib/.$(LIB).new $(DESTDIR)$(PREFIX)/lib/$(LIB)
for p in $(PLUGIN); do \
@@ -293,8 +322,8 @@ install: all
@echo "installed $(DESTDIR)$(PREFIX)/bin/splinter"
clean:
rm -f src/catalogs.c $(BIN) $(LIB) $(LIBOBJ) $(BINOBJ) $(PLUGIN) $(TESTS) \
tests/plugin_lifecycle.so
rm -f src/backend/catalogs.c $(BIN) $(CLIENT) $(LIB) $(LIBOBJ) $(BINOBJ) \
$(CLIENTOBJ) $(PLUGIN) $(TESTS) tests/plugin_lifecycle.so
.PHONY: all check curses install clean
+85 -33
View File
@@ -8,15 +8,18 @@ quarters, a sidebar on the last one that says which agent, provider, model and
allowance you are on and where the tools will act, the prompt below it. The
conversation starts clear at the top and only ever grows.
make # libsplinter.so, the binary, the plugins
make # libsplinter.so, the binaries, the plugins
make check # the tests, no network, no model
make install PREFIX=$HOME/.local # binary, library, plugins
make install PREFIX=$HOME/.local # binaries, library, plugins
splinter --init-config # writes ~/.splinter/splinter.conf
splinter --doctor # does every provider answer?
splinter # the chat; Tab switches build / plan
splinter -m claude # a provider, a pool, provider/model
splinter --model-list # everything -m takes
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
The working day with several subscriptions (who analyses, who implements, what
happens at a limit) is in `docs/WORKFLOW.md`.
@@ -36,7 +39,7 @@ is appended to `~/.splinter/<id>.jsonl` as one JSON object per line.
`--autonomous` was given.
- Skip a denial silently: the denial becomes the observation the model sees.
## Protocol
## Transport protocol
The harness speaks a line protocol with its transport, not a vendor API:
@@ -51,32 +54,73 @@ transport replays replies.
## Layout
libsplinter.so every symbol, once; binary and plugins link to it
include/splinter.h the core interface
The harness is a backend and a set of front ends; `docs/FRONTENDS.md` says
where the line runs and how to add another one.
libsplinter.so every symbol, once; binaries and plugins link to it
include/splinter.h the core interface
include/splinter_engine.h the engine a front end talks to (events, turns)
include/splinter_plugin.h plugin ABI and host API
src/plugin.c dlopen loader, widget registry, worker threads
src/conv.c the conversation (owned messages, no sharing)
src/openai.c request shaping + reply parsing, pure functions
src/transport_openai.c HTTP to /v1/chat/completions via curl(1)
src/json.c libmcp's JSON, instantiated once
src/ui.c curses UI: transcript, sidebar, prompt
src/md.c markdown tables as aligned text
src/theme.c CDE palettes -> terminal colours
src/palettes.c generated from CDE's *.dp files
tools/genpalettes.py the generator
plugins/clock/ example plugin: a sidebar clock + a tool
vendor/netbsd-curses/ NetBSD curses and terminfo, vendored
docs/PLUGINS.md the ABI, the threading rules
src/buf.c growable buffer, JSON escaping
src/tool.c registry
src/session.c append-only JSONL session
src/transport.c deterministic mock transport
src/builtin.c read/write/edit/search/list/run/web tools
src/agent.c the loop
src/main.c CLI
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)
src/backend/engine.c session + agent + turn thread + event queue
src/backend/agent.c the loop
src/backend/conv.c the conversation (owned messages, no sharing)
src/backend/openai.c request shaping + reply parsing, pure functions
src/backend/transport*.c HTTP, the mock, the vendor shapes
src/backend/session.c append-only JSONL session
src/backend/builtin.c read/write/edit/search/list/run/web tools
src/backend/tool.c the registry
src/backend/config.c the config file
src/backend/providers.c -m, /model, pools, failover
src/backend/plugin.c dlopen loader, widget registry, worker threads
src/backend/md.c markdown tables as aligned text
src/backend/telegram.c gateway mode
src/backend/a2aserver.c the A2A server
src/frontend/curses.c transcript, sidebar, prompt
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 socket client (--attach)
src/frontend/protocol.c splinter --serve: JSON lines on a Unix socket
src/frontend/client.c splinterctl, the reference protocol client
src/frontend/ui.h the curses entry point
src/main.c launcher: parse, config, engine, front end
plugins/clock/ example plugin: a sidebar clock + a tool
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
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)
## Front ends
The engine is front-end neutral: `sp_engine_submit()` starts a turn on its own
thread and everything that happens — streamed text, a step's reasoning, a tool
call, its observation, an approval question, the answer — becomes an event the
front end drains. The curses interface is one front end; `splinter --serve`
is another, and it is what a GUI would use.
```sh
splinter --serve # ~/.splinter/splinter.sock
splinter --serve --socket /tmp/s.sock
splinter --attach --socket /tmp/s.sock # the curses UI, as a client
splinterctl --socket /tmp/s.sock --say "list the C files"
python3 docs/proto-example.py /tmp/s.sock "list the C files"
```
The screen itself is a client in `--attach` mode: it speaks the same lines a
GUI would, shows the server's session and its transcript so far, runs every
turn there and switches the server's profiles. That is the proof that the
protocol carries everything the front end needs; if `--attach` works, a GUI
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.
## Plugins and themes
@@ -278,13 +322,19 @@ The turn runs on its own thread, so the keyboard stays live. Every tool call is
one row in the transcript, in the words of the call itself - `>> Run echo a` -
because "it did something" is not information. The reasoning is inserted before
those rows: it came first, and the log should read in the order things
happened. While it runs, the input line leads with the elapsed seconds and the
call in progress (`12s Run du -sh ../xsrc`) and then the steer prompt, which
keeps its room when the row is narrow - a call that pushes `steer>` off the
right edge hides the one hint the row exists for. A steer is picked up at the
happened. While it runs, the input line is only `12s steer> ` and what is
typed: the call belongs in the transcript, and in the prompt it was a second
copy that pushed the steer hint off the right edge. A steer is picked up at the
next step boundary; in a single-step turn it becomes the next message instead of
being dropped. Curses is only ever touched by the UI thread.
A name is not text: `SP_STREAM_TOOL` carries the name of a call that has begun,
and the answer text is built from `SP_STREAM_TEXT` alone. The stream used to be
classified by looking for `tool_calls` in the raw line, which broke as soon as
the provider sent `"content":null` beside the call - the name landed in the
answer and two `read` calls were printed as `<model> readread`. The kind now
comes from the parser (`sp_sse_kind`).
## Compaction
`focus` keeps the session's goal in front of the model every five turns, the
@@ -533,7 +583,9 @@ delegation once.
`--resume` loads the newest session in the session directory back into the
conversation and puts it on screen. It continues that session id rather than
opening a fresh one beside it - the first version did the latter, which looked
like a resume and was none.
like a resume and was none. The agent profile comes back too: the engine keeps
the session's profile in `<session>.agent`, so a session left in plan resumes
in plan.
## MCP
+100
View File
@@ -0,0 +1,100 @@
# Backend and front ends
`splinter` is split in two so that the screen is not the harness.
```
+-----------------------+
a keyboard ---> | front end (curses) | ---\
+-----------------------+ \
\ +----------------+
a socket ---> | front end (protocol) | --------> | the engine |
+-----------------------+ / +----------------+
/ agent, tools,
-p / --daemon --> | direct library use | ---/ transports,
+-----------------------+ session, config,
plugins
```
## The backend
`libsplinter.so` is the whole harness minus the screen:
| file | what it owns |
| --- | --- |
| `src/backend/engine.c` | `struct sp_engine`: session, conversation, registry, plugins, transport, agent, turn thread, event queue, slash commands |
| `src/backend/agent.c` | the loop: request, tool calls, observations, answer |
| `src/backend/transport*.c`, `openai.c`, `anthropic.c`, `sse.c` | a conversation in, a reply out |
| `src/backend/builtin.c`, `tool.c` | the tools and the registry |
| `src/backend/session.c`, `conv.c` | append-only JSONL, owned messages |
| `src/backend/config.c`, `providers.c`, `usage.c` | configuration and providers |
| `src/backend/plugin.c` | `dlopen`, widgets, commands, gates, compactors |
| `src/backend/telegram.c`, `a2aserver.c`, `mcpserver.c` | outbound protocol adapters |
The engine never calls into a front end. A turn runs on a thread of the
engine's making and appends `struct sp_event` records to a queue; the front end
drains it whenever it draws. That is the whole threading rule, and it is why a
slow terminal cannot stall a model, and why a GUI cannot corrupt a turn.
`include/splinter_engine.h` is the C boundary. Its event kinds map one to one
onto the JSON `ev` names in `docs/PROTOCOL.md`.
## The front ends
| file | kind |
| --- | --- |
| `src/frontend/curses.c` | the screen: transcript, sidebar, prompt, keys |
| `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/client.c` | `splinterctl`, the reference protocol client |
| `src/main.c` | the launcher: parse, config, engine, pick a front end |
`curses.c` owns the screen, the themes, the markdown-to-ASCII pass, the input
history and the key bindings. It does not know how a provider is switched, how
a session is created or how an approval is waited for — those are
`/model`, `/new` and the engine's condition variable. It talks to one of two
backends through `ui_backend.h`: the engine linked into the process
(`--chat`), or a served engine over the socket (`--attach`). The screen cannot
tell them apart, which is the test the protocol has to pass.
```
splinter --serve --socket /tmp/s.sock # one process: engine + protocol
splinter --attach --socket /tmp/s.sock # another: the screen as a client
```
## Writing a GUI client
Two ways, and the second one is the interesting one.
1. **Link the library.** Include `splinter_engine.h`, call `sp_engine_open()`,
then `sp_engine_input()` / `sp_engine_submit()` / `sp_engine_poll()` as
`src/frontend/curses.c` does. This only works from C or a C-binding
language.
2. **Speak the socket.** Run `splinter --serve` and connect to the Unix socket
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.
The recommended shape for a GUI:
* one window per connection; the `state` event fills the sidebar (session,
model, agent, tokens);
* on connect, send `history` once and draw the returned items - a GUI that
joins a session should not look like it invented it;
* append `stream` deltas to the open bubble; close it on `step` or `turn`;
* draw `tool` as a call row and `tool_result` under it (or on the same row
when `join` is true);
* when `approval` arrives, show the question and send `approve`;
* `busy` drives the spinner; `cancel` and `steer` are the two buttons that
must remain live during a turn;
* nothing in the client has to know a provider, a session file or a tool's
authorization class — the engine already decided.
There is one conversation and one client at a time; a second connection waits
until the first is gone. An attaching client asks for `history` (the last 100
messages, up to 256 KiB) and shows the session it joins; live events continue
from that point. If a client disconnects, the server cancels a running turn,
because an approval that nobody can answer would park the engine forever.
+229
View File
@@ -0,0 +1,229 @@
# The front-end protocol
`splinter --serve` runs the engine on a Unix socket. Everything a front end
needs — the transcript, the reasoning as it streams, tool calls, approval
questions, slash commands, model and profile switches — arrives as one JSON
object per line. The curses interface uses the same engine in-process through
`include/splinter_engine.h`; this socket is the same boundary for programs that
are not C.
```
splinter --serve [--socket PATH]
```
The default socket is `$SPLINTER_SOCKET`, else `~/.splinter/splinter.sock`.
The file is created mode `0600` and the server refuses a peer whose uid is not
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.
## Framing
* One JSON object per line, UTF-8, `\n` terminated. No arrays, no envelope.
* Server → client objects have `"ev"`; client → server objects have `"cmd"`.
* Unknown fields are ignored. Unknown `cmd` answers with an `error` event.
* `"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
cancels the turn (an approval nobody can answer would otherwise park the
engine forever) and accepts the next client.
## Sequence
```
client server
| connect |
|<-- {"ev":"ready","protocol":2,...} |
| {"cmd":"commands"} / {"cmd":"history"} |
|<-- {"ev":"state",...} |
|<-- {"ev":"commands","names":[...]} |
|<-- {"ev":"history","items":[...]} |
| {"cmd":"input","line":"hallo"} |
|<-- {"ev":"submitted","text":"hallo"}|
|<-- {"ev":"busy","on":true} |
|<-- {"ev":"stream","kind":"think",..}| (only with a reasoning model)
|<-- {"ev":"stream","kind":"text",..} |
|<-- {"ev":"step","think":..,"text":..}
|<-- {"ev":"tool","name":"run",...} |
|<-- {"ev":"approval","name":"run",..}| (a mutating tool)
| {"cmd":"approve","allow":true} |
|<-- {"ev":"tool_result",...} |
|<-- {"ev":"stream","kind":"text",..} |
|<-- {"ev":"turn","ok":true,...} |
|<-- {"ev":"state",...} |
|<-- {"ev":"busy","on":false} |
```
`stream` chunks are deltas: append them. `step` marks the end of one model step
at a tool call; it carries the step's whole reasoning and answer, so a client
that lost a chunk can repair from it. The final answer of the turn is in
`turn.answer` (the last step's text, which is also the last `stream` text).
A `turn` event does not by itself mean the engine is idle. A steer that was
typed too late for a step boundary becomes a second turn in the same busy
period: another `entry` (`you`), more `stream`/`turn` events, and only then
`busy:false`. A client finishes its work when `busy.on` is `false`, not at the
first `turn`; each `turn` is one answer to show.
## Client → server
### `{"cmd":"input","line":"..."}`
The universal entry point: exactly what the operator typed.
* A slash command (`/model`, `/status`, `/agent plan`, …) answers with a
`reply` event and does not start a turn.
* A prompt starts a turn: `submitted`, then the turn events.
* `!command` runs a shell; its output arrives as an `entry` with
`"role":"shell"`.
* A program in `~/.splinter/commands/` replaces the line with its output and
starts a turn with it (`submitted` carries the text).
The server refuses this command with an `error` while a turn is running; the
transcript is the engine's, not a client's scratchpad.
### `{"cmd":"say","text":"..."}`
Start a turn directly, without command interpretation. The client has already
decided this is a prompt (for example from its own input field).
### `{"cmd":"command","line":"/..."}`
Alias of `input`; kept because a client that has a command palette knows what
it is sending.
### `{"cmd":"approve","allow":true}`
Answer the open approval question. `false` denies; the denial becomes the
observation the model sees (it is not silent).
### `{"cmd":"cancel"}`
Cancel the running turn. The engine sets its flag; every transport kills the
child process or the `curl` it started. The turn then ends with
`"ev":"turn","ok":false`.
### `{"cmd":"steer","text":"..."}`
Text typed while the turn runs. The loop picks it up at the next step boundary
and puts it into the conversation; a step that has already ended cannot be
interrupted. If no turn runs, the answer is an `error`.
### `{"cmd":"state"}`
Ask for a `state` event. Useful after a reconnect.
### `{"cmd":"history"}`
Ask for the transcript so far: `"ev":"history"`, `"truncated":bool`,
`"items":[{"role":"user","text":"..."}, {"role":"assistant",...}]`. The last
100 messages and 256 KiB are sent; a client that attaches shows the session it
joins instead of an empty pane. The system prompt and tool observations stay
out — this is what the person and the model said.
### `{"cmd":"commands"}`
Ask what a command palette may offer: `"ev":"commands"`,
`"names":["agent","connect","model",...]` — the same list Tab completes in the
curses front end, plugin commands and `commands/` programs included.
### `{"cmd":"ping"}` / `{"cmd":"quit"}`
`pong`; and a clean shutdown: `quit` event, server closes the socket and exits
with 0.
## Server → client
| `ev` | fields | meaning |
| --- | --- | --- |
| `ready` | `protocol`, `version` | the greeting, always first |
| `state` | `session`, `dir`, `model`, `endpoint`, `agent`, `agents[]`, `agent_cur`, `tokens_in`, `tokens_out`, `steps`, `calls`, `compactions`, `last_ms`, `last_steps`, `last_calls`, `busy`, `waiting`, `quit` | everything a sidebar shows |
| `submitted` | `text` | the prompt actually run (a command may have rewritten it) |
| `busy` | `on` | a turn started or ended |
| `stream` | `kind` (`text` or `think`), `text` | a delta of the answer or the reasoning |
| `step` | `think`, `text` | one model step ended at a tool call |
| `tool` | `name`, `args`, `call` | a tool call; `call` is the readable line (`Run ls -l`) |
| `tool_result` | `name`, `text`, `join` | what the tool returned; `join` true means "append to the call row" |
| `entry` | `role`, `text` | a finished transcript entry |
| `note` | `text` | a one-line prompt note, e.g. a usage-limit wait; `""` clears it |
| `approval` | `name`, `args`, `call`, `auth`, `class` | a tool needs consent; answer with `approve` |
| `turn` | `ok`, `rc`, `answer`, `error` | one turn ended; `busy:false` ends the work |
| `clear` | — | `/new`: drop the transcript pane (the session is new) |
| `reply` | `text` | the answer to a command; may be empty |
| `error` | `text` | the command was refused |
| `commands` | `names[]` | the slash commands, for a palette |
| `history` | `truncated`, `items[]` | the transcript so far (role/text) |
| `pong` | — | answer to `ping` |
| `quit` | — | the engine is shutting down |
`entry.role` is one of `you`, `agent`, `thinking`, `tool`, `observation`,
`splinter`, `shell`, `error`. A client renders them in its own way; the
sidecar values (`state`, `tool.call`, `tool_result.join`) exist so it does not
have to re-implement the harness' own arithmetic.
## A minimal client
```python
import json, socket, sys
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(sys.argv[1])
f = s.makefile("rw", encoding="utf-8")
def send(obj):
f.write(json.dumps(obj) + "\n")
f.flush()
send({"cmd": "input", "line": "list the C files"})
for line in f:
ev = json.loads(line)
if ev["ev"] == "stream" and ev["kind"] == "text":
print(ev["text"], end="", flush=True)
elif ev["ev"] == "tool":
print("\n>>", ev["call"])
elif ev["ev"] == "approval":
send({"cmd": "approve", "allow": True})
elif ev["ev"] == "turn":
print()
break
```
Run it against `splinter --serve --socket /tmp/s.sock` with the socket path as
the argument; `docs/proto-example.py` is the same program with argument
handling.
## The same boundary in C
`include/splinter_engine.h` is what `src/frontend/curses.c` and
`src/frontend/protocol.c` use:
```c
struct sp_engine *eng;
struct sp_engine_opts o = { .conf = &conf, .base = &cfg, .endpoint = url,
.model = name, .key_env = "SPLINTER_API_KEY" };
sp_engine_open(&eng, &o, &err);
sp_engine_input(eng, "/status", &reply); /* or a prompt ... */
sp_engine_submit(eng, prompt); /* ... then a turn */
while (sp_engine_poll(eng, &ev)) /* the same events as above */
handle(ev);
sp_engine_approve(eng, 1);
sp_engine_close(eng);
```
The event kinds map one to one onto the JSON `ev` names (`SP_EV_TOOL` ↔
`tool`, `SP_EV_TURN_END` ↔ `turn`). A front end cannot drift from the socket
protocol without drifting from the curses one, because both read the same
queue.
## Versioning
`"protocol": 2` is the current version. Additive fields keep the number;
removing a field or changing its meaning bumps it, and the curses front end
moves in the same commit. Version 2 added the `history` command, which
`--attach` uses during its greeting: a client that needs it refuses a version
1 server instead of waiting for an answer that never comes.
+22
View File
@@ -12,6 +12,28 @@ Stream.
## Erledigt
- **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
einzeln, Engine-Steer-Rest wird per `sp_engine_take_steer` uebernommen,
Engine-Statistik als Lock-Snapshot (kein Datenrace), Profil wird in
`<session>.agent` gemerkt (--resume startet wieder in plan), `/new` oeffnet
das Log neu und vergibt eindeutige Ids, Shell-Ausgabe 64 KiB mit Marker,
Socket-Probe/Inode/CLOEXEC/SO_SNDTIMEO, Protokoll v2 mit `history` (attach
zeigt das bisherige Transkript), `same_user` auch fuer BSD, Exit 2 fuer
Konfigurationsfehler, `agent_switch` meldet Aktivierungsfehler, i18n-Checker
scannt src/backend+frontend. `tests/test_protocol.sh` und
`tests/test_attach.sh` decken die neuen Pfade ab; `make check` gruen.
- **Backend und Frontends getrennt**: `src/backend/` traegt Engine, Loop,
Tools, Session, Config und Plugins; `src/frontend/curses.c` zeichnet nur
noch und liest Tasten, `src/frontend/protocol.c` gibt dieselben Events als
JSON-Zeilen auf einem Unix-Socket aus, `src/frontend/client.c` ist der
Referenz-Client (`splinterctl`). Die C-Grenze ist
`include/splinter_engine.h`; das Format steht in `docs/PROTOCOL.md`, die
Aufteilung in `docs/FRONTENDS.md`. Ein GUI-Client kann damit in jeder
Sprache gegen `splinter --serve` gebaut werden. Belege:
`tests/test_engine` (Event-Reihenfolge eines Turns) und
`tests/test_protocol.sh` (Socket, Freigabe, Kommandos, quit).
- Werkzeuge: read, write, edit, search, list, run, websearch, webfetch,
folder_history, delegate (plus parallel/list/submit/jobs/result/due/retry),
skill_search/skill_load, memory_search/memory_add, echo, clock
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""A minimal splinter GUI-backend client.
It speaks the line protocol from docs/PROTOCOL.md and prints the transcript as
text -- the same events a Tk/Qt/Electron window would draw. Start a server
first:
splinter --serve --socket /tmp/splinter.sock
python3 docs/proto-example.py /tmp/splinter.sock "list the C files"
Approve is answered with `y` on stdin; everything else is printed as it
arrives.
"""
import json
import socket
import sys
class Splinter:
def __init__(self, path):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(path)
self.f = self.sock.makefile("rw", encoding="utf-8")
def send(self, **obj):
self.f.write(json.dumps(obj) + "\n")
self.f.flush()
def events(self):
for line in self.f:
line = line.strip()
if line:
yield json.loads(line)
def main():
if len(sys.argv) < 3:
print(__doc__)
return 2
cli = Splinter(sys.argv[1])
cli.send(cmd="input", line=" ".join(sys.argv[2:]))
for ev in cli.events():
kind = ev.get("ev")
if kind == "stream" and ev.get("kind") == "text":
print(ev.get("text", ""), end="", flush=True)
elif kind == "stream" and ev.get("kind") == "think":
pass # a GUI would show this dimmed
elif kind == "tool":
print("\n>> " + ev.get("call", "?"))
elif kind == "tool_result" and not ev.get("join"):
print(ev.get("text", ""))
elif kind in ("entry", "reply", "error"):
print("[%s] %s" % (ev.get("role", kind), ev.get("text", "")))
elif kind == "approval":
print("[approval] %s (%s) [y/N] " % (ev.get("call", "?"),
ev.get("class", "?")),
end="", flush=True)
answer = sys.stdin.readline().strip().lower()
cli.send(cmd="approve", allow=answer.startswith("y"))
elif kind == "state" and ev.get("busy"):
print("[%s/%s]" % (ev.get("agent"), ev.get("model")),
file=sys.stderr)
elif kind == "turn":
print()
if not ev.get("ok"):
print("turn failed: " + ev.get("error", ""), file=sys.stderr)
return 1
return 0
return 1
if __name__ == "__main__":
sys.exit(main())
+34 -1
View File
@@ -98,6 +98,28 @@ Beyond 127.x it needs
.Ev SPLINTER_A2A_SERVER_TOKEN .
.It Fl -a2a-listen-port Ar N
A2A port (default 8099).
.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
.Pa docs/PROTOCOL.md .
Any program that can open a Unix socket can be a front end, which is what a
GUI client connects to.
.It Fl -attach
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.
.It Fl -socket Ar PATH
Socket for
.Fl -serve
and
.Fl -attach ,
default
.Ev SPLINTER_SOCKET
or
.Pa ~/.splinter/splinter.sock .
The file is mode 0600 and the server refuses a peer of another uid.
.It Fl -session Ar DIR
Session directory (default
.Pa ~/.splinter ) .
@@ -109,7 +131,18 @@ Print the version and exit.
.El
.Sh PROTOCOL
.Nm
speaks a line protocol with its transport, not a vendor API:
is a backend with front ends.
The curses interface links the engine in process;
.Fl -serve
exposes the same engine as JSON lines on a Unix socket, where
.Pa splinterctl
is the reference client and the place to start a GUI from.
The engine reports a turn as events -- streamed text, a step, a tool call, its
observation, an approval question, the answer -- and never calls into a front
end.
.Pp
Between the harness and its transport the protocol is simpler, and not a
vendor API:
.Bd -literal -offset indent
request user <text>
request observe <tool> <output>
+5
View File
@@ -423,6 +423,11 @@ int sp_sse_finish(struct sp_sse *, struct sp_reply *out, struct sp_buf *err);
int sp_sse_done(const struct sp_sse *);
int sp_sse_usage(const struct sp_sse *, long *in, long *out);
const char *sp_sse_tool_start(const struct sp_sse *, size_t index);
/* What the last line carried: SP_STREAM_THINK, SP_STREAM_TEXT, SP_STREAM_TOOL,
* or -1 for nothing. Transports classify by this, not by sniffing the line:
* OpenAI sends `"content":null` next to `tool_calls`, and a substring test made
* the tool's name part of the answer ("<model> readread"). */
int sp_sse_kind(const struct sp_sse *);
/*
* transport_anthropic.c -- the Anthropic Messages API, via curl(1).
+235
View File
@@ -0,0 +1,235 @@
/*
* splinter -- the engine every front end talks to.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* The engine is the whole harness minus the screen: it owns the session, the
* conversation, the tool registry, the plugins, the transport and the agent,
* runs one turn at a time on its own thread, and reports what happened as a
* queue of events.
*
* Why a queue and not callbacks: a turn runs on a thread of the engine's
* making, and a front end (curses, a socket, a GUI) must not be called from
* it -- it would have to be thread-safe in every drawing routine, and a slow
* front end would stall the model. The engine only appends to a queue under a
* mutex; the front end drains it whenever it is ready. Nothing here ever calls
* into a front end.
*
* The contract, in one paragraph: sp_engine_open() builds the engine from the
* command line and the config; sp_engine_input() turns a typed line into
* either a command reply or a prompt; sp_engine_submit() starts the turn;
* sp_engine_poll() delivers its events; sp_engine_approve(), sp_engine_steer()
* and sp_engine_cancel() are what a front end may do while it runs.
*
* This is the C boundary. The same engine is served over a line-oriented JSON
* socket by `splinter --serve`, so a GUI may be written in any language; see
* docs/PROTOCOL.md. The two front ends use exactly the calls below, which is
* what keeps them from drifting apart.
*/
#ifndef SPLINTER_ENGINE_H
#define SPLINTER_ENGINE_H
#include <stddef.h>
#include "splinter.h"
struct sp_config;
struct sp_host;
struct sp_agent;
struct sp_conv;
struct sp_engine;
struct swarm;
#define SP_ENGINE_PLUGINS 32
/* ---------------------------------------------------------------- options */
/*
* What sp_engine_open() needs. Strings are copied; `conf` and `base` are read
* and not owned (main keeps them alive for the whole run), but the engine does
* change conf the way the old binary did: /model writes a drop-in, /connect
* adds a provider, a pool failover marks one benched.
*/
struct sp_engine_opts {
struct sp_config *conf;
const struct sp_agent_config *base; /* steps, byte budget, prompt */
const char *endpoint;
const char *model;
const char *key_env; /* variable holding the API key */
const char *transport; /* plugin transport ("cli"), or NULL */
const char *kind; /* "anthropic", or NULL */
const char *script; /* mock replies, one per line */
const char *agent; /* profile to start in */
const char *session_dir;
const char *session_id;
const char *plugins[SP_ENGINE_PLUGINS];
size_t nplugins;
int resume; /* load the session's history */
int continue_last; /* -c: newest session in this cwd */
int no_transport; /* tools only (MCP server, delegate) */
int swarm; /* join the local fleet */
};
/* ----------------------------------------------------------------- events */
enum sp_ev_kind {
SP_EV_NONE = 0,
SP_EV_BUSY, /* n: 1 the turn started, 0 it ended */
SP_EV_STREAM, /* n: SP_STREAM_TEXT|SP_STREAM_THINK, a: chunk */
SP_EV_STEP, /* a: the step's reasoning, b: its answer */
SP_EV_TOOL, /* a: name, b: arguments as sent */
SP_EV_TOOL_RESULT, /* a: name, b: observation, n: 1 joins the call */
SP_EV_NOTE, /* a: the prompt's one line, "" clears it */
SP_EV_ENTRY, /* a: role, b: text */
SP_EV_APPROVAL, /* a: name, b: args, n: authorization class */
SP_EV_TURN_END, /* n: rc, a: answer, b: error */
SP_EV_STATE, /* the model, tokens or profile changed */
SP_EV_CLEAR, /* /new: the transcript is the old conversation */
SP_EV_QUIT /* /quit was typed; the front end may close */
};
struct sp_event {
int kind;
long n;
char *a;
char *b;
};
/* 1 when an event was taken, 0 when the queue is empty. Free with
* sp_engine_event_free(). */
int sp_engine_poll(struct sp_engine *, struct sp_event *);
void sp_engine_event_free(struct sp_event *);
/* --------------------------------------------------------------- snapshot */
struct sp_engine_state {
char model[256];
char endpoint[512];
char agent[48];
char session[64];
char dir[512];
char theme[48]; /* set by the front end, for /status */
size_t tokens_in, tokens_out;
size_t steps, calls, compactions; /* the session's counters */
size_t last_ms, last_steps, last_calls; /* the last turn */
int busy;
int quit; /* /quit was typed */
int waiting; /* the turn waits for an approval */
int agents_n;
int agent_cur;
};
int sp_engine_state(struct sp_engine *, struct sp_engine_state *);
/* -------------------------------------------------------------- lifecycle */
int sp_engine_open(struct sp_engine **, const struct sp_engine_opts *,
struct sp_buf *err);
void sp_engine_close(struct sp_engine *);
/* The pieces a front end may look at. The pointers stay valid until close. */
struct sp_agent *sp_engine_agent(struct sp_engine *);
struct sp_host *sp_engine_host(struct sp_engine *);
struct sp_config *sp_engine_config(struct sp_engine *);
struct sp_registry *sp_engine_registry(struct sp_engine *);
struct swarm *sp_engine_swarm(struct sp_engine *);
const struct sp_conv *sp_engine_conv(struct sp_engine *);
void sp_engine_set_theme(struct sp_engine *, const char *);
/* The default stream callback for async turns (the gateway has nobody to
* stream to and installs a sink; -p passes its own to sp_engine_prompt). */
void sp_engine_set_stream(struct sp_engine *, sp_stream_cb, void *ctx);
const char *sp_engine_state_dir(struct sp_engine *);
const char *sp_engine_session_id(struct sp_engine *);
/* ------------------------------------------------------------------ turns */
/*
* Start a turn. Returns 0, or -1 when one is already running: the engine runs
* exactly one turn at a time, because there is one conversation and one model.
*/
int sp_engine_submit(struct sp_engine *, const char *text);
int sp_engine_busy(struct sp_engine *);
int sp_engine_quit(struct sp_engine *);
/* Join the finished turn. Call it once sp_engine_busy() said 0, before the
* next submit; closing does it too. */
int sp_engine_wait(struct sp_engine *);
/* Ask the model once without the queue: what -p and the slash prompt use. */
int sp_engine_prompt(struct sp_engine *, const char *text, sp_stream_cb,
void *stream_ctx, struct sp_buf *answer, struct sp_buf *err);
/* ------------------------------------------------------- during one turn */
int sp_engine_cancel(struct sp_engine *);
/* Text typed while the turn runs: the loop picks it up at a step boundary.
* -1 when no turn is running. */
int sp_engine_steer(struct sp_engine *, const char *text);
/*
* A steer that arrived after the turn's last step boundary: the worker has
* finished, the text is still pending. A front end takes it and runs it as the
* next prompt, so typing into the last second is not lost. 0 while a turn is
* still running (the loop will take it) or when nothing is pending.
*/
int sp_engine_take_steer(struct sp_engine *, struct sp_buf *out);
/* 1 while a tool waits for the operator, with the call in the buffers. */
int sp_engine_approval(struct sp_engine *, char *name, size_t namelen,
int *auth, char *args, size_t argslen);
/* Answer it. 0 when nothing was pending. */
int sp_engine_approve(struct sp_engine *, int allow);
/* ------------------------------------------------------------------ input */
/*
* One line from the operator. Returns
*
* SP_INPUT_PROMPT a prompt for the model; start the turn with it
* SP_INPUT_HANDLED a command; `out` is the reply to show
* SP_INPUT_SUBMIT a command that replaced the line; `out` is the prompt
* to start a turn with (a program in commands/)
*
* The engine owns /model, /agent, /new, /connect, /usage, /status, /widgets,
* /swarm, /resume, /quit, !shell and every command a plugin registered, so a
* GUI gets the same set as the curses front end without re-implementing one.
*
* Call it while the engine is idle. A command changes the conversation, the
* transport and the session; doing that under a running turn is a front-end
* bug. sp_engine_conv() is a read-only view for the same reason: the messages
* are the worker's while a turn runs.
*/
#define SP_INPUT_PROMPT 0
#define SP_INPUT_HANDLED 1
#define SP_INPUT_SUBMIT 2
int sp_engine_input(struct sp_engine *, const char *line, struct sp_buf *out);
/* The names Tab completes, without the slash, sorted. Returns the count. */
int sp_engine_command_names(struct sp_engine *, char (*names)[64], int max);
/* Agent profiles: Tab's three calls. */
int sp_engine_agents(struct sp_engine *);
const char *sp_engine_agent_name(struct sp_engine *, int idx);
int sp_engine_agent_cur(struct sp_engine *);
int sp_engine_agent_switch(struct sp_engine *, int idx);
/* ------------------------------------------------------------- formatting */
/*
* How a tool call and its observation read, shared by every front end:
*
* Run du -sh ../xsrc
* Read src/frontend/curses.c
*
* Arguments are unescaped, the one that matters (command, path, ...) is
* picked, and the rest is left out. SP_OBS_JOIN says the observation is only
* " [exit status 0]" and belongs on the call's row; SP_OBS_NONE says there is
* nothing to show; SP_OBS_SHOWN means `out` is a block for the transcript.
*/
#define SP_OBS_NONE 0
#define SP_OBS_SHOWN 1
#define SP_OBS_JOIN 2
void sp_call_summary(const char *name, const char *args, char *out,
size_t cap);
int sp_obs_short(const char *obs, struct sp_buf *out);
#endif /* SPLINTER_ENGINE_H */
+2
View File
@@ -7,6 +7,7 @@
ui.ready = bereit. Enter sendet, Ctrl-D beendet.
ui.more_lines = ... %zu Zeilen mehr
ui.working = laeuft...
ui.compacted = Kontext kompaktiert: %zu->%zu Nachrichten, %s->%s (%s->%s)
ui.steering_queued = Steuerung eingereiht
sidebar.session = Sitzung
@@ -182,6 +183,7 @@ ui.limit_wait = Nutzungslimit: weiter um %s (Strg-C stoppt, /resume macht weiter
agent.switched = Agent: %s - %s %s
agent.readonly = [nur lesen]
agent.none = kein Agent '%s'
agent.failed = Agent-Profil '%s' laesst sich nicht aktivieren
agent.help = Tab wechselt, /agent NAME waehlt
agent.desc.build = voller Zugriff: lesen, aendern, bauen, testen
agent.desc.plan = nur lesen: analysieren, abwaegen, planen; aendert nichts
+2
View File
@@ -6,6 +6,7 @@
ui.ready = ready. Enter sends, Ctrl-D quits.
ui.more_lines = ... %zu more lines
ui.working = working...
ui.compacted = context compacted: %zu->%zu msgs, %s->%s (%s->%s)
ui.steering_queued = steering queued
sidebar.session = session
@@ -181,6 +182,7 @@ ui.limit_wait = usage limit: continuing at %s (Ctrl-C stops, /resume goes on)
agent.switched = agent: %s - %s %s
agent.readonly = [read-only]
agent.none = no agent '%s'
agent.failed = cannot activate the agent profile '%s'
agent.help = Tab switches, /agent NAME picks
agent.desc.build = full access: reads, changes, builds, tests
agent.desc.plan = read-only: analyse, weigh, plan; changes nothing
+2
View File
@@ -7,6 +7,7 @@
ui.ready = pronto. Enter envia, Ctrl-D sai.
ui.more_lines = ... %zu linhas a mais
ui.working = trabalhando...
ui.compacted = contexto compactado: %zu->%zu msgs, %s->%s (%s->%s)
ui.steering_queued = direcionamento na fila
ui.prompt_mark = >
ui.steer_mark = direcionar>
@@ -185,6 +186,7 @@ ui.limit_wait = limite de uso: continua as %s (Ctrl-C para, /resume continua)
agent.switched = agente: %s - %s %s
agent.readonly = [somente leitura]
agent.none = nenhum agente '%s'
agent.failed = nao foi possivel ativar o perfil de agente '%s'
agent.help = Tab alterna, /agent NOME escolhe
agent.desc.build = acesso total: ler, alterar, compilar, testar
agent.desc.plan = somente leitura: analisar, ponderar, planejar; nao altera nada
File renamed without changes.
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+2268
View File
File diff suppressed because it is too large. Load diff
File renamed without changes.
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
File renamed without changes.
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
File renamed without changes.
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+25
View File
@@ -35,6 +35,7 @@ struct sp_sse {
struct sse_call calls[MAX_CALLS];
size_t ncalls;
int done;
int last; /* what the last line put into out */
long tokens_in;
long tokens_out;
};
@@ -96,6 +97,26 @@ sp_sse_tool_start(const struct sp_sse *s, size_t index)
return s->calls[index].name;
}
/*
* The parser knows what it produced, so nobody has to guess from the raw
* line. A chunk can carry text and a tool name at once; text wins, because
* that is what belongs in the answer - the name is announced separately
* (sp_sse_tool_start).
*/
int
sp_sse_kind(const struct sp_sse *s)
{
if (s == NULL)
return -1;
if (s->last & 2)
return SP_STREAM_THINK;
if (s->last & 1)
return SP_STREAM_TEXT;
if (s->last & 4)
return SP_STREAM_TOOL;
return -1;
}
static struct sse_call *
call_slot(struct sp_sse *s, size_t index)
{
@@ -125,6 +146,7 @@ sp_sse_line(struct sp_sse *s, const char *line, struct sp_buf *out,
if (s == NULL)
return -1;
s->last = 0;
while (*line == ' ' || *line == '\t')
line++;
if (*line == '\0' || *line == ':' || *line == '\n')
@@ -188,6 +210,7 @@ sp_sse_line(struct sp_sse *s, const char *line, struct sp_buf *out,
mcp_json_free(v);
return -1;
}
s->last |= 1;
produced = 1;
}
@@ -201,6 +224,7 @@ sp_sse_line(struct sp_sse *s, const char *line, struct sp_buf *out,
mcp_json_free(v);
return -1;
}
s->last |= 2;
produced = 1;
}
}
@@ -247,6 +271,7 @@ sp_sse_line(struct sp_sse *s, const char *line, struct sp_buf *out,
mcp_json_free(v);
return -1;
}
s->last |= 4;
produced = 1;
}
if (args != NULL && mcp_json_string(args) != NULL &&
View File
File renamed without changes.
View File
File renamed without changes.
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
View File
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -519,12 +519,17 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
goto out;
}
if (produced > 0 && cb != NULL && delta.len > 0) {
kind = SP_STREAM_TEXT;
if (strstr(ln, "\"reasoning_content\"") != NULL)
kind = SP_STREAM_THINK;
else if (strstr(ln, "tool_calls") != NULL &&
strstr(ln, "\"content\"") == NULL)
kind = SP_STREAM_TOOL;
/*
* The parser says what it produced. Sniffing
* the line for "tool_calls" and "content" was
* wrong the moment OpenAI started sending
* `"content":null` beside a call: the chunk
* counted as text and the tool's name went
* into the answer.
*/
kind = sp_sse_kind(sse);
if (kind < 0)
kind = SP_STREAM_TEXT;
cb(cbctx, kind, delta.p);
}
}
@@ -550,8 +555,11 @@ openai_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
sp_buf_puts(&tail, ln);
sp_buf_clear(&delta);
if (sp_sse_line(sse, ln, &delta, err) > 0 && cb != NULL &&
delta.len > 0)
cb(cbctx, SP_STREAM_TEXT, delta.p);
delta.len > 0) {
int k = sp_sse_kind(sse);
cb(cbctx, k < 0 ? SP_STREAM_TEXT : k, delta.p);
}
}
sp_buf_free(&lbuf);
}
View File
File renamed without changes.
View File
File renamed without changes.
+425
View File
@@ -0,0 +1,425 @@
/*
* splinterctl -- the reference client for the splinter protocol.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* A GUI needs the events, not a terminal; this program exists so the protocol
* has a client that is not curses, and so `tests/test_protocol.sh` can drive a
* served engine without a screen. It prints the transcript as text:
*
* splinterctl # a small REPL against the served engine
* splinterctl --say "hallo" # one turn, its answer on stdout
* splinterctl --cmd /status # one command, its reply on stdout
* splinterctl --socket PATH # the socket a --serve instance listens on
*
* It is deliberately not a GUI: a real client reads the same lines and draws
* them its own way. See docs/PROTOCOL.md.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include "splinter.h"
#include "mcp.h"
#include "protocol.h"
struct client {
int fd;
struct sp_buf in;
struct sp_buf line;
int think; /* show the reasoning */
int streamed;
int saw_submitted;
int saw_turn;
int saw_reply;
int quit;
int turn_ok;
int failed;
int said_session;
int busy;
};
/* the same default as the server, without linking the server object */
static void
default_socket(char *buf, size_t cap)
{
const char *env = getenv("SPLINTER_SOCKET");
if (env != NULL && *env != '\0') {
snprintf(buf, cap, "%s", env);
return;
}
snprintf(buf, cap, "%s/.splinter/splinter.sock",
getenv("HOME") != NULL ? getenv("HOME") : ".");
}
static int
connect_to(const char *path)
{
struct sockaddr_un addr;
int fd;
if (strlen(path) >= sizeof(addr.sun_path)) {
fprintf(stderr, "splinterctl: socket path too long\n");
return -1;
}
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
perror("splinterctl: socket");
return -1;
}
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", path);
if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
fprintf(stderr, "splinterctl: %s: %s\n", path, strerror(errno));
close(fd);
return -1;
}
return fd;
}
static int
send_all(int fd, const char *p, size_t n)
{
while (n > 0) {
ssize_t w = send(fd, p, n, MSG_NOSIGNAL);
if (w < 0) {
if (errno == EINTR)
continue;
return -1;
}
p += w;
n -= (size_t)w;
}
return 0;
}
static int
send_cmd(int fd, const char *cmd, const char *key, const char *val)
{
struct sp_buf b;
int rc;
if (sp_buf_init(&b) != 0)
return -1;
sp_buf_printf(&b, "{\"cmd\":\"%s\"", cmd);
if (key != NULL && val != NULL) {
sp_buf_printf(&b, ",\"%s\":\"", key);
(void)sp_json_escape(&b, val);
sp_buf_puts(&b, "\"");
}
sp_buf_puts(&b, "}\n");
rc = send_all(fd, b.p, b.len);
sp_buf_free(&b);
return rc;
}
/* one event; returns 1 when the wait for this command is over */
static int
show_event(struct client *c, const mcp_json *v)
{
const char *ev = mcp_arg_string(v, "ev");
if (ev == NULL)
return 0;
if (strcmp(ev, "ready") == 0) {
int proto = mcp_arg_int(v, "protocol", 0);
fprintf(stderr, "splinterctl: protocol %d\n", proto);
if (proto != SP_PROTO_VERSION) {
fprintf(stderr, "splinterctl: the server speaks protocol "
"%d, this client speaks %d\n", proto,
SP_PROTO_VERSION);
c->failed = 1;
c->saw_reply = 1;
}
} else if (strcmp(ev, "state") == 0) {
const char *sess = mcp_arg_string(v, "session");
const char *dir = mcp_arg_string(v, "dir");
if (!c->said_session && sess != NULL && *sess != '\0') {
fprintf(stderr, "splinterctl: session %s%s%s\n", sess,
dir != NULL && *dir != '\0' ? " in " : "",
dir != NULL ? dir : "");
c->said_session = 1;
}
} else if (strcmp(ev, "stream") == 0) {
const char *kind = mcp_arg_string(v, "kind");
const char *text = mcp_arg_string(v, "text");
if (text == NULL)
return 0;
if (kind != NULL && strcmp(kind, "think") == 0) {
if (c->think)
fputs(text, stdout);
} else {
fwrite(text, 1, strlen(text), stdout);
fflush(stdout);
c->streamed = 1;
}
} else if (strcmp(ev, "tool") == 0) {
const char *call = mcp_arg_string(v, "call");
printf("\n>> %s\n", call != NULL ? call : "?");
fflush(stdout);
} else if (strcmp(ev, "tool_result") == 0) {
const char *text = mcp_arg_string(v, "text");
if (text == NULL || *text == '\0')
return 0;
if (mcp_arg_bool(v, "join", 0))
printf(" %s\n", text);
else
printf("%s\n", text);
fflush(stdout);
} else if (strcmp(ev, "entry") == 0) {
const char *role = mcp_arg_string(v, "role");
const char *text = mcp_arg_string(v, "text");
if (text == NULL || *text == '\0')
return 0;
printf("[%s] %s\n", role != NULL ? role : "?", text);
fflush(stdout);
} else if (strcmp(ev, "reply") == 0) {
const char *text = mcp_arg_string(v, "text");
if (text != NULL && *text != '\0') {
printf("%s\n", text);
fflush(stdout);
}
c->saw_reply = 1;
} else if (strcmp(ev, "approval") == 0) {
const char *call = mcp_arg_string(v, "call");
char answer[32];
fprintf(stderr, "approve? %s [y/N] ",
call != NULL ? call : "?");
fflush(stderr);
if (fgets(answer, sizeof(answer), stdin) != NULL &&
(answer[0] == 'y' || answer[0] == 'Y')) {
struct sp_buf b;
if (sp_buf_init(&b) == 0) {
sp_buf_puts(&b, "{\"cmd\":\"approve\","
"\"allow\":true}\n");
(void)send_all(c->fd, b.p, b.len);
sp_buf_free(&b);
}
} else {
struct sp_buf b;
if (sp_buf_init(&b) == 0) {
sp_buf_puts(&b, "{\"cmd\":\"approve\","
"\"allow\":false}\n");
(void)send_all(c->fd, b.p, b.len);
sp_buf_free(&b);
}
}
} else if (strcmp(ev, "submitted") == 0) {
c->saw_submitted = 1;
} else if (strcmp(ev, "busy") == 0) {
c->busy = mcp_arg_bool(v, "on", 0);
} else if (strcmp(ev, "turn") == 0) {
const char *err = mcp_arg_string(v, "error");
if (c->streamed) {
printf("\n");
c->streamed = 0;
}
c->saw_turn = 1;
c->turn_ok = mcp_arg_bool(v, "ok", 0);
if (!c->turn_ok && err != NULL && *err != '\0')
fprintf(stderr, "splinterctl: %s\n", err);
} else if (strcmp(ev, "error") == 0) {
const char *text = mcp_arg_string(v, "text");
fprintf(stderr, "splinterctl: %s\n",
text != NULL ? text : "protocol error");
c->failed = 1;
c->saw_reply = 1;
} else if (strcmp(ev, "note") == 0) {
const char *text = mcp_arg_string(v, "text");
if (text != NULL && *text != '\0') {
fprintf(stderr, "splinterctl: %s\n", text);
}
} else if (strcmp(ev, "quit") == 0) {
c->quit = 1;
}
/*
* A turn is over when the engine says it is idle, not at the first
* `turn` event: a leftover steer becomes a second turn in the same busy
* period, and a client that left at the first one would miss it (and
* close the socket while the server still works).
*/
return (c->saw_turn && !c->busy) ||
(c->saw_reply && !c->saw_submitted);
}
/*
* Read until the command is answered: a reply for a slash command, a turn for
* a prompt. Returns 0, -1 on a broken connection.
*/
static int
wait_for(struct client *c)
{
char chunk[4096];
c->saw_reply = c->saw_submitted = c->saw_turn = 0;
c->busy = 0;
for (;;) {
ssize_t got;
char *nl;
size_t len, used;
mcp_json *v;
nl = memchr(c->in.p, '\n', c->in.len);
if (nl == NULL) {
got = recv(c->fd, chunk, sizeof(chunk), 0);
if (got < 0) {
if (errno == EINTR)
continue;
return -1;
}
if (got == 0)
return -1;
if (sp_buf_add(&c->in, chunk, (size_t)got) != 0)
return -1;
continue;
}
len = (size_t)(nl - c->in.p);
sp_buf_clear(&c->line);
if (sp_buf_add(&c->line, c->in.p, len) != 0)
return -1;
if (c->line.len > 0 && c->line.p[c->line.len - 1] == '\r')
c->line.p[--c->line.len] = '\0';
used = len + 1;
memmove(c->in.p, c->in.p + used, c->in.len - used);
c->in.len -= used;
c->in.p[c->in.len] = '\0';
v = mcp_parse(c->line.p);
if (v == NULL)
continue;
{
int done = show_event(c, v);
mcp_json_free(v);
if (done)
return 0;
}
if (c->quit)
return 0;
}
}
static void
usage(void)
{
fprintf(stderr,
"usage: splinterctl [options] [--say TEXT | --cmd LINE]\n\n"
" --socket PATH the socket a `splinter --serve` listens on\n"
" --say TEXT run one turn, print it, exit\n"
" --cmd LINE run one slash command, print the reply, exit\n"
" --think show the model's reasoning\n"
" --quit stop the served engine after this command\n"
"without --say/--cmd: a small REPL; Ctrl-D ends it\n");
}
int
main(int argc, char **argv)
{
struct client c;
char path[700];
const char *say = NULL, *cmd = NULL;
int i, rc = 0, quit_server = 0;
memset(&c, 0, sizeof(c));
c.fd = -1;
default_socket(path, sizeof(path));
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "--socket") == 0 && i + 1 < argc)
snprintf(path, sizeof(path), "%s", argv[++i]);
else if (strcmp(argv[i], "--say") == 0 && i + 1 < argc)
say = argv[++i];
else if (strcmp(argv[i], "--cmd") == 0 && i + 1 < argc)
cmd = argv[++i];
else if (strcmp(argv[i], "--think") == 0)
c.think = 1;
else if (strcmp(argv[i], "--quit") == 0)
quit_server = 1;
else if (strcmp(argv[i], "-h") == 0 ||
strcmp(argv[i], "--help") == 0) {
usage();
return 0;
} else {
fprintf(stderr, "splinterctl: unknown option %s\n",
argv[i]);
usage();
return 2;
}
}
if (sp_buf_init(&c.in) != 0 || sp_buf_init(&c.line) != 0)
return 1;
c.fd = connect_to(path);
if (c.fd < 0)
return 1;
/*
* The greeting (ready, state) stays queued: the first wait_for() reads
* it in order and keeps going until the answer it was asked for.
*/
if (cmd != NULL) {
if (send_cmd(c.fd, "command", "line", cmd) != 0)
rc = 1;
else if (wait_for(&c) != 0)
rc = 1;
else if (c.failed)
rc = 1;
} else if (say != NULL) {
if (send_cmd(c.fd, "say", "text", say) != 0)
rc = 1;
else if (wait_for(&c) != 0)
rc = 1;
else if (c.failed || (c.saw_turn && !c.turn_ok))
rc = 1;
} else {
char line[4096];
for (;;) {
printf("> ");
fflush(stdout);
if (fgets(line, sizeof(line), stdin) == NULL)
break;
line[strcspn(line, "\r\n")] = '\0';
if (line[0] == '\0')
continue;
if (send_cmd(c.fd, "command", "line", line) != 0) {
rc = 1;
break;
}
if (wait_for(&c) != 0) {
rc = 1;
break;
}
if (c.quit)
break;
}
}
/*
* Closing the socket is the end of this client, not of the engine: a
* GUI's window closing must not stop the backend a second window (or a
* scheduled turn) still uses. `splinterctl --quit` asks for the other.
*/
if (quit_server)
(void)send_cmd(c.fd, "quit", NULL, NULL);
close(c.fd);
sp_buf_free(&c.in);
sp_buf_free(&c.line);
return rc;
}
File diff suppressed because it is too large. Load diff
+868
View File
@@ -0,0 +1,868 @@
/*
* splinter -- the line protocol front end: the engine on a Unix socket.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* `splinter --serve` runs the same engine the curses front end uses and sends
* its events as JSON, one object per line. A GUI in any language can then be a
* client: connect, send a line, read the events. Nothing in here draws.
*
* The socket is a file in the user's own directory, mode 0600, and the peer is
* checked against getuid() -- a second local user must not be able to type into
* a conversation that may run `run` with the owner's rights.
*/
#define _GNU_SOURCE 1
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
#include "splinter.h"
#include "splinter_engine.h"
#include "mcp.h"
#include "i18n.h"
#include "protocol.h"
struct client {
int fd;
struct sp_buf in; /* bytes not yet cut into lines */
struct sp_buf line; /* the line handed to handle_line */
int quit;
};
/* --------------------------------------------------------------- writing */
static int
write_all(int fd, const char *p, size_t n)
{
while (n > 0) {
ssize_t w = send(fd, p, n, MSG_NOSIGNAL);
if (w < 0) {
if (errno == EINTR)
continue;
return -1;
}
p += w;
n -= (size_t)w;
}
return 0;
}
static int
send_line(struct client *c, struct sp_buf *b)
{
if (sp_buf_puts(b, "\n") != 0)
return -1;
return write_all(c->fd, b->p, b->len);
}
static void
ev_start(struct sp_buf *b, const char *name)
{
sp_buf_clear(b);
sp_buf_printf(b, "{\"ev\":\"%s\"", name);
}
static void
ev_str(struct sp_buf *b, const char *key, const char *val)
{
sp_buf_printf(b, ",\"%s\":\"", key);
(void)sp_json_escape(b, val != NULL ? val : "");
sp_buf_puts(b, "\"");
}
static void
ev_num(struct sp_buf *b, const char *key, long v)
{
sp_buf_printf(b, ",\"%s\":%ld", key, v);
}
static void
ev_bool(struct sp_buf *b, const char *key, int v)
{
sp_buf_printf(b, ",\"%s\":%s", key, v ? "true" : "false");
}
/* the whole engine state, for a client that just attached or asks again */
static int
send_state(struct client *c, struct sp_engine *eng, const char *name)
{
struct sp_engine_state st;
struct sp_buf b;
int i;
if (sp_engine_state(eng, &st) != 0)
return -1;
if (sp_buf_init(&b) != 0)
return -1;
ev_start(&b, name);
ev_str(&b, "session", st.session);
ev_str(&b, "dir", st.dir);
ev_str(&b, "model", st.model);
ev_str(&b, "endpoint", st.endpoint);
ev_str(&b, "agent", st.agent);
ev_num(&b, "tokens_in", (long)st.tokens_in);
ev_num(&b, "tokens_out", (long)st.tokens_out);
ev_num(&b, "steps", (long)st.steps);
ev_num(&b, "calls", (long)st.calls);
ev_num(&b, "compactions", (long)st.compactions);
ev_num(&b, "last_ms", (long)st.last_ms);
ev_num(&b, "last_steps", (long)st.last_steps);
ev_num(&b, "last_calls", (long)st.last_calls);
ev_bool(&b, "busy", st.busy);
ev_bool(&b, "waiting", st.waiting);
ev_bool(&b, "quit", st.quit);
sp_buf_puts(&b, ",\"agents\":[");
for (i = 0; i < st.agents_n; i++) {
if (i > 0)
sp_buf_puts(&b, ",");
sp_buf_puts(&b, "\"");
(void)sp_json_escape(&b, sp_engine_agent_name(eng, i));
sp_buf_puts(&b, "\"");
}
sp_buf_puts(&b, "]");
ev_num(&b, "agent_cur", st.agent_cur);
sp_buf_puts(&b, "}");
{
int rc = send_line(c, &b);
sp_buf_free(&b);
return rc;
}
}
/* one engine event as one JSON line */
static int
send_event(struct client *c, struct sp_engine *eng, const struct sp_event *ev)
{
struct sp_buf b;
int rc = 0;
if (sp_buf_init(&b) != 0)
return -1;
switch (ev->kind) {
case SP_EV_BUSY:
ev_start(&b, "busy");
ev_bool(&b, "on", ev->n != 0);
break;
case SP_EV_STREAM:
ev_start(&b, "stream");
ev_str(&b, "kind", ev->n == SP_STREAM_THINK ? "think" : "text");
ev_str(&b, "text", ev->a);
break;
case SP_EV_STEP:
ev_start(&b, "step");
ev_str(&b, "think", ev->a);
ev_str(&b, "text", ev->b);
break;
case SP_EV_TOOL: {
char call[640];
sp_call_summary(ev->a, ev->b, call, sizeof(call));
ev_start(&b, "tool");
ev_str(&b, "name", ev->a);
ev_str(&b, "args", ev->b);
ev_str(&b, "call", call);
break;
}
case SP_EV_TOOL_RESULT:
ev_start(&b, "tool_result");
ev_str(&b, "name", ev->a);
ev_str(&b, "text", ev->b);
ev_bool(&b, "join", ev->n == 1);
break;
case SP_EV_NOTE:
ev_start(&b, "note");
ev_str(&b, "text", ev->a);
break;
case SP_EV_ENTRY:
ev_start(&b, "entry");
ev_str(&b, "role", ev->a);
ev_str(&b, "text", ev->b);
break;
case SP_EV_APPROVAL: {
char call[640];
sp_call_summary(ev->a, ev->b, call, sizeof(call));
ev_start(&b, "approval");
ev_str(&b, "name", ev->a);
ev_num(&b, "auth", ev->n);
ev_str(&b, "args", ev->b);
ev_str(&b, "call", call);
ev_str(&b, "class", ev->n == SP_AUTH_MUTATE ? "mutate" :
"destructive");
break;
}
case SP_EV_TURN_END:
ev_start(&b, "turn");
ev_bool(&b, "ok", ev->n == 0);
ev_num(&b, "rc", ev->n);
ev_str(&b, "answer", ev->a);
ev_str(&b, "error", ev->b);
break;
case SP_EV_STATE:
sp_buf_free(&b);
return send_state(c, eng, "state");
case SP_EV_CLEAR:
ev_start(&b, "clear");
break;
case SP_EV_QUIT:
ev_start(&b, "quit");
break;
case SP_EV_NONE:
sp_buf_free(&b);
return 0;
}
sp_buf_puts(&b, "}");
rc = send_line(c, &b);
sp_buf_free(&b);
return rc;
}
static int
send_reply(struct client *c, const char *text)
{
struct sp_buf b;
int rc;
if (sp_buf_init(&b) != 0)
return -1;
ev_start(&b, "reply");
ev_str(&b, "text", text);
sp_buf_puts(&b, "}");
rc = send_line(c, &b);
sp_buf_free(&b);
return rc;
}
static int
send_error(struct client *c, const char *text)
{
struct sp_buf b;
int rc;
if (sp_buf_init(&b) != 0)
return -1;
ev_start(&b, "error");
ev_str(&b, "text", text);
sp_buf_puts(&b, "}");
rc = send_line(c, &b);
sp_buf_free(&b);
return rc;
}
/* Every event the engine queued so far, in order. A command that produced
* entries (/new's clear, a shell's output) must have them delivered before its
* reply: otherwise a GUI clears the pane after it printed the reply. */
static int
drain_to_client(struct client *c, struct sp_engine *eng)
{
struct sp_event ev;
while (sp_engine_poll(eng, &ev)) {
int rc = send_event(c, eng, &ev);
sp_engine_event_free(&ev);
if (rc != 0)
return -1;
if (!sp_engine_busy(eng))
(void)sp_engine_wait(eng);
}
return 0;
}
/*
* The transcript so far, as one event. A long session is cut at 100 messages
* and 256 KiB; the flag says so, and a GUI can offer "load older" later. The
* system prompt and tool observations stay out: the transcript shows what the
* person and the model said.
*/
#define HIST_MSGS 100
#define HIST_BYTES (256 * 1024)
static int
send_history(struct client *c, struct sp_engine *eng)
{
const struct sp_conv *conv = sp_engine_conv(eng);
struct sp_buf b, items;
size_t i, start, bytes = 0;
int first = 1, truncated = 0;
if (sp_buf_init(&b) != 0 || sp_buf_init(&items) != 0) {
sp_buf_free(&b);
sp_buf_free(&items);
return -1;
}
start = conv != NULL && conv->n > HIST_MSGS ? conv->n - HIST_MSGS : 0;
if (start > 0)
truncated = 1;
for (i = start; conv != NULL && i < conv->n; i++) {
const struct sp_msg *m = &conv->v[i];
size_t len;
if (m->role == NULL || m->content == NULL ||
m->content[0] == '\0')
continue;
if (strcmp(m->role, "user") != 0 &&
strcmp(m->role, "assistant") != 0)
continue;
len = strlen(m->content);
if (bytes + len > HIST_BYTES) {
truncated = 1;
break;
}
bytes += len;
if (!first)
sp_buf_puts(&items, ",");
first = 0;
sp_buf_puts(&items, "{\"role\":\"");
(void)sp_json_escape(&items, m->role);
sp_buf_puts(&items, "\",\"text\":\"");
(void)sp_json_escape(&items, m->content);
sp_buf_puts(&items, "\"}");
}
ev_start(&b, "history");
ev_bool(&b, "truncated", truncated);
sp_buf_puts(&b, ",\"items\":[");
sp_buf_puts(&b, items.p != NULL ? items.p : "");
sp_buf_puts(&b, "]}");
sp_buf_free(&items);
{
int rc = send_line(c, &b);
sp_buf_free(&b);
return rc;
}
}
/*
* A steer that arrived after the last step boundary belongs before the next
* prompt. It is shown as the operator's entry and prepended to the text; the
* client that typed it sees it in the transcript instead of losing it.
*/
static int
fold_pending_steer(struct client *c, struct sp_engine *eng, struct sp_buf *prompt)
{
struct sp_buf st, joined;
struct sp_event ev;
int took = 0;
if (sp_buf_init(&st) != 0)
return 0;
if (!sp_engine_take_steer(eng, &st)) {
sp_buf_free(&st);
return 0;
}
ev.kind = SP_EV_ENTRY;
ev.n = 0;
ev.a = "you";
ev.b = st.p;
(void)send_event(c, eng, &ev);
if (sp_buf_init(&joined) == 0) {
(void)sp_buf_puts(&joined, st.p != NULL ? st.p : "");
(void)sp_buf_puts(&joined, "\n\n");
(void)sp_buf_puts(&joined, prompt->p != NULL ? prompt->p : "");
sp_buf_clear(prompt);
(void)sp_buf_puts(prompt, joined.p != NULL ? joined.p : "");
sp_buf_free(&joined);
took = 1;
}
sp_buf_free(&st);
return took;
}
/* -------------------------------------------------------------- commands */
/*
* One line from the client. Returns -1 when the connection should end. A
* command that starts a turn sets *started; the caller then keeps the event
* pump running while the engine works.
*/
static int
handle_line(struct client *c, struct sp_engine *eng, const char *line)
{
mcp_json *v;
const char *cmd, *text;
struct sp_buf out;
int handled;
v = mcp_parse(line);
if (v == NULL) {
(void)send_error(c, "not JSON");
return 0;
}
cmd = mcp_arg_string(v, "cmd");
if (cmd == NULL) {
(void)send_error(c, "no cmd");
mcp_json_free(v);
return 0;
}
if (sp_buf_init(&out) != 0) {
mcp_json_free(v);
return -1;
}
if (strcmp(cmd, "say") == 0 || strcmp(cmd, "submit") == 0) {
text = mcp_arg_string(v, "text");
if (text == NULL || *text == '\0') {
(void)send_error(c, "empty prompt");
} else {
struct sp_buf prompt;
int ok;
if (sp_buf_init(&prompt) != 0) {
mcp_json_free(v);
sp_buf_free(&out);
return -1;
}
(void)sp_buf_puts(&prompt, text);
(void)fold_pending_steer(c, eng, &prompt);
ok = sp_engine_submit(eng,
prompt.p != NULL ? prompt.p : text);
if (ok != 0) {
sp_buf_free(&prompt);
(void)send_error(c, "a turn is already running");
goto done;
}
struct sp_buf b;
if (sp_buf_init(&b) == 0) {
ev_start(&b, "submitted");
ev_str(&b, "text",
prompt.p != NULL ? prompt.p : text);
sp_buf_puts(&b, "}");
(void)send_line(c, &b);
sp_buf_free(&b);
}
sp_buf_free(&prompt);
}
} else if (strcmp(cmd, "input") == 0 ||
strcmp(cmd, "command") == 0) {
text = mcp_arg_string(v, "line");
if (text == NULL) {
(void)send_error(c, "no line");
} else if (sp_engine_busy(eng)) {
(void)send_error(c, "a turn is running");
} else {
handled = sp_engine_input(eng, text, &out);
if (handled == SP_INPUT_PROMPT) {
struct sp_buf prompt, b;
if (sp_buf_init(&prompt) != 0)
goto done;
(void)sp_buf_puts(&prompt,
out.len > 0 ? out.p : text);
(void)fold_pending_steer(c, eng, &prompt);
if (sp_buf_init(&b) == 0) {
ev_start(&b, "submitted");
ev_str(&b, "text", prompt.p != NULL ?
prompt.p : text);
sp_buf_puts(&b, "}");
(void)send_line(c, &b);
sp_buf_free(&b);
}
if (sp_engine_submit(eng, prompt.p != NULL ?
prompt.p : text) != 0)
(void)send_error(c,
"a turn is already running");
sp_buf_free(&prompt);
} else if (handled == SP_INPUT_SUBMIT) {
/* a program in commands/ replaced the line: run it */
struct sp_buf b, prompt;
int prc;
if (drain_to_client(c, eng) != 0)
return -1;
if (sp_buf_init(&prompt) != 0)
goto done;
(void)sp_buf_puts(&prompt,
out.p != NULL ? out.p : "");
(void)fold_pending_steer(c, eng, &prompt);
if (sp_buf_init(&b) == 0) {
ev_start(&b, "submitted");
ev_str(&b, "text", prompt.p != NULL ?
prompt.p : "");
sp_buf_puts(&b, "}");
(void)send_line(c, &b);
sp_buf_free(&b);
}
prc = sp_engine_submit(eng,
prompt.p != NULL ? prompt.p : "");
if (prc != 0)
(void)send_error(c,
"a turn is already running");
sp_buf_free(&prompt);
} else {
if (drain_to_client(c, eng) != 0)
return -1;
(void)send_reply(c, out.p != NULL ? out.p : "");
}
}
} else if (strcmp(cmd, "approve") == 0) {
(void)sp_engine_approve(eng, mcp_arg_bool(v, "allow", 0));
} else if (strcmp(cmd, "cancel") == 0) {
(void)sp_engine_cancel(eng);
} else if (strcmp(cmd, "steer") == 0) {
text = mcp_arg_string(v, "text");
if (text != NULL &&
sp_engine_steer(eng, text) != 0)
(void)send_error(c, "no turn is running");
} else if (strcmp(cmd, "state") == 0) {
(void)send_state(c, eng, "state");
} else if (strcmp(cmd, "history") == 0) {
/*
* The conversation belongs to the worker while a turn runs; a
* history read would race its appends and its realloc. The
* attach greeting is idle by construction.
*/
if (sp_engine_busy(eng))
(void)send_error(c, "a turn is running");
else
(void)send_history(c, eng);
} else if (strcmp(cmd, "commands") == 0) {
/* what a command palette may offer, without the leading slash */
char names[64][64];
int n = sp_engine_command_names(eng, names, 64), i;
struct sp_buf b;
if (sp_buf_init(&b) != 0)
return -1;
ev_start(&b, "commands");
sp_buf_puts(&b, ",\"names\":[");
for (i = 0; i < n; i++) {
if (i > 0)
sp_buf_puts(&b, ",");
sp_buf_puts(&b, "\"");
(void)sp_json_escape(&b, names[i]);
sp_buf_puts(&b, "\"");
}
sp_buf_puts(&b, "]}");
(void)send_line(c, &b);
sp_buf_free(&b);
} else if (strcmp(cmd, "ping") == 0) {
struct sp_buf b;
if (sp_buf_init(&b) == 0) {
ev_start(&b, "pong");
sp_buf_puts(&b, "}");
(void)send_line(c, &b);
sp_buf_free(&b);
}
} else if (strcmp(cmd, "quit") == 0) {
sp_buf_clear(&out);
(void)sp_engine_input(eng, "/quit", &out);
(void)send_reply(c, out.p != NULL ? out.p : "");
c->quit = 1;
} else {
(void)send_error(c, "unknown cmd");
}
done:
sp_buf_free(&out);
mcp_json_free(v);
return 0;
}
/*
* A client went away while a turn was running. The engine would park in an
* approval nobody can answer, so cancel it and drain the events nobody will
* read. The conversation keeps the answer the model produced up to there.
*/
static void
abandon_turn(struct sp_engine *eng)
{
struct sp_event ev;
if (!sp_engine_busy(eng))
return;
(void)sp_engine_cancel(eng);
while (sp_engine_busy(eng)) {
while (sp_engine_poll(eng, &ev))
sp_engine_event_free(&ev);
{
struct timespec ts = { 0, 20000000L };
nanosleep(&ts, NULL);
}
}
while (sp_engine_poll(eng, &ev))
sp_engine_event_free(&ev);
(void)sp_engine_wait(eng);
}
/* the whole life of one connected client */
static int
serve_client(struct sp_engine *eng, int fd)
{
struct client c;
struct sp_buf b;
int rc = 0;
memset(&c, 0, sizeof(c));
c.fd = fd;
if (sp_buf_init(&c.in) != 0 || sp_buf_init(&c.line) != 0 ||
sp_buf_init(&b) != 0) {
sp_buf_free(&c.in);
sp_buf_free(&c.line);
return -1;
}
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) {
sp_buf_free(&b);
sp_buf_free(&c.in);
sp_buf_free(&c.line);
return -1;
}
sp_buf_free(&b);
while (!c.quit) {
struct pollfd pfd;
int pr;
char chunk[4096];
ssize_t got;
struct sp_event ev;
pfd.fd = fd;
pfd.events = POLLIN;
pfd.revents = 0;
pr = poll(&pfd, 1, 100);
if (pr > 0 && (pfd.revents & (POLLHUP | POLLERR | POLLNVAL)))
break;
if (pr > 0 && (pfd.revents & POLLIN)) {
got = recv(fd, chunk, sizeof(chunk), 0);
if (got <= 0) {
if (got < 0 && (errno == EINTR ||
errno == EAGAIN))
continue;
break;
}
if (sp_buf_add(&c.in, chunk, (size_t)got) != 0)
break;
}
/* complete lines, in the order they arrived. The line grows with
* the client: a pasted prompt may be larger than any fixed buffer,
* and a truncated JSON line is a command nobody executed. */
for (;;) {
char *nl = memchr(c.in.p, '\n', c.in.len);
size_t len, used;
if (nl == NULL)
break;
len = (size_t)(nl - c.in.p);
sp_buf_clear(&c.line);
if (sp_buf_add(&c.line, c.in.p, len) != 0) {
rc = -1;
goto out;
}
if (c.line.len > 0 &&
c.line.p[c.line.len - 1] == '\r')
c.line.p[--c.line.len] = '\0';
used = len + 1;
memmove(c.in.p, c.in.p + used, c.in.len - used);
c.in.len -= used;
c.in.p[c.in.len] = '\0';
if (c.line.len == 0)
continue;
if (handle_line(&c, eng, c.line.p) != 0) {
rc = -1;
goto out;
}
if (c.quit)
break;
}
/* and every event the engine produced since the last tick */
while (sp_engine_poll(eng, &ev)) {
if (send_event(&c, 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_quit(eng) || c.quit)
break;
}
out:
abandon_turn(eng);
sp_buf_free(&c.in);
sp_buf_free(&c.line);
return rc;
}
/* ---------------------------------------------------------------- socket */
void
sp_proto_default_socket(char *buf, size_t cap)
{
const char *env = getenv("SPLINTER_SOCKET");
const char *home;
if (env != NULL && *env != '\0') {
snprintf(buf, cap, "%s", env);
return;
}
home = getenv("HOME");
snprintf(buf, cap, "%s/.splinter/splinter.sock",
home != NULL ? home : ".");
}
static int
same_user(int fd)
{
#if defined(SO_PEERCRED)
struct ucred cred;
socklen_t len = sizeof(cred);
if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) != 0)
return 0;
return cred.uid == getuid();
#elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) || \
defined(__APPLE__)
uid_t uid;
gid_t gid;
return getpeereid(fd, &uid, &gid) == 0 && uid == getuid();
#else
(void)fd;
return 0; /* no way to check the peer: refuse, never trust */
#endif
}
int
sp_proto_serve(struct sp_engine *eng, const char *path, struct sp_buf *err)
{
char def[700];
const char *where = path;
struct sockaddr_un addr;
struct stat st, mine;
int lfd, one = 1, have_mine = 0;
if (eng == NULL)
return -1;
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);
return -1;
}
if (lstat(where, &st) == 0) {
/*
* A socket left by a dead server is ours to replace. Anything
* else at that path is somebody's file: refuse, never unlink.
* A socket somebody still answers on is a running server, and
* two writers on one conversation is exactly what this protocol
* promises not to do.
*/
int probe;
if (!S_ISSOCK(st.st_mode)) {
sp_buf_printf(err, "%s exists and is not a socket", where);
return -1;
}
probe = socket(AF_UNIX, SOCK_STREAM, 0);
if (probe >= 0) {
struct sockaddr_un pa;
memset(&pa, 0, sizeof(pa));
pa.sun_family = AF_UNIX;
snprintf(pa.sun_path, sizeof(pa.sun_path), "%s", where);
if (connect(probe, (struct sockaddr *)&pa,
sizeof(pa)) == 0) {
close(probe);
sp_buf_printf(err, "%s is already being served",
where);
return -1;
}
close(probe);
}
(void)unlink(where);
}
lfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (lfd >= 0)
(void)fcntl(lfd, F_SETFD, FD_CLOEXEC);
if (lfd < 0) {
sp_buf_printf(err, "socket: %s", strerror(errno));
return -1;
}
(void)setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", where);
if (bind(lfd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
sp_buf_printf(err, "bind %s: %s", where, strerror(errno));
close(lfd);
return -1;
}
(void)chmod(where, 0600);
if (lstat(where, &mine) == 0)
have_mine = 1;
if (listen(lfd, 4) != 0) {
sp_buf_printf(err, "listen: %s", strerror(errno));
close(lfd);
(void)unlink(where);
return -1;
}
fprintf(stderr, "splinter: serving on %s\n", where);
for (;;) {
int fd = accept(lfd, NULL, NULL);
if (fd < 0) {
if (errno == EINTR)
continue;
sp_buf_printf(err, "accept: %s", strerror(errno));
break;
}
/*
* No child may inherit the listening socket or a client: the
* `run` tool forks shells with the server's descriptors, and a
* background command would keep the socket alive after exit.
*/
(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
{
/*
* A client that stops reading must not block the server
* forever: after five seconds without progress the
* write fails and the connection (and its turn) ends.
*/
struct timeval tv = { 5, 0 };
(void)setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv,
sizeof(tv));
}
if (!same_user(fd)) {
fprintf(stderr, "splinter: refused a client of another "
"user\n");
close(fd);
continue;
}
(void)serve_client(eng, fd);
close(fd);
if (sp_engine_quit(eng))
break;
}
close(lfd);
/*
* Only remove the socket this server created: if another server
* replaced the path while we ran, its file must survive our exit.
*/
if (have_mine && lstat(where, &st) == 0 && S_ISSOCK(st.st_mode) &&
st.st_dev == mine.st_dev && st.st_ino == mine.st_ino)
(void)unlink(where);
return sp_engine_quit(eng) ? 0 : -1;
}
+34
View File
@@ -0,0 +1,34 @@
/*
* splinter -- the line protocol every out-of-process front end speaks.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* A GUI has no business linking libsplinter: the engine is C, the boundary is
* a socket, and the wire format is one JSON object per line. This header is
* what main and the reference client need; the format itself is written down
* in docs/PROTOCOL.md.
*/
#ifndef SPLINTER_PROTOCOL_H
#define SPLINTER_PROTOCOL_H
#include <stddef.h>
struct sp_engine;
struct sp_buf;
#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.
* Returns 0 on a clean quit.
*/
int sp_proto_serve(struct sp_engine *eng, const char *path,
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);
#endif /* SPLINTER_PROTOCOL_H */
+6 -10
View File
@@ -3,21 +3,17 @@
#define SPLINTER_UI_H
#include "splinter.h"
#include "splinter_plugin.h"
#include "swarm.h"
#include "splinter_engine.h"
#include "ui_backend.h"
/*
* Run the interactive chat loop until the user quits. `theme_name` is a CDE
* palette name; NULL selects the default. `host` may be NULL (no plugins).
* `sw` enables the local swarm (fleet) when not NULL.
* palette name; NULL selects the default. `be` is the engine in this process
* (--chat) or a served one behind a socket (--attach); the screen cannot tell
* the difference. This file only draws and reads keys.
* Returns 0 on a clean quit.
*/
int sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *model,
const char *theme_name, struct sp_host *host, struct swarm *sw,
struct sp_config *conf);
/* the agent profile the chat starts in (default "build") */
void sp_ui_start_agent(const char *name);
int sp_ui_run(const struct ui_backend *be, const char *theme_name);
/*
* UTF-8 -> ASCII for the screen. The vendored curses writes Latin-1 bytes for
+93
View File
@@ -0,0 +1,93 @@
/*
* splinter -- what the curses front end needs from a backend.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* The screen does not know whether the engine runs in this process or behind
* a socket. It calls these operations, and two implementations fill them in:
*
* sp_ui_backend_engine() the engine linked into this binary (--chat)
* sp_ui_backend_remote() a `splinter --serve` reached over a Unix socket
* (--attach), speaking docs/PROTOCOL.md
*
* The split exists so `--attach` proves the socket protocol is complete: a
* front end that works locally must work remotely, or the protocol is missing
* something.
*/
#ifndef SPLINTER_UI_BACKEND_H
#define SPLINTER_UI_BACKEND_H
#include <stddef.h>
#include "splinter.h"
#include "splinter_engine.h"
struct sp_buf;
struct sp_conv;
struct sp_host;
struct swarm;
struct ui_backend {
void *ctx;
/* the operator's line: SP_INPUT_PROMPT/HANDLED/SUBMIT + the reply */
int (*input)(void *ctx, const char *line, struct sp_buf *out);
/* turns */
int (*submit)(void *ctx, const char *text);
int (*busy)(void *ctx);
int (*wait)(void *ctx);
int (*cancel)(void *ctx);
int (*steer)(void *ctx, const char *text);
/* a steer that arrived after the turn's last step boundary */
int (*take_steer)(void *ctx, struct sp_buf *out);
/* the approval a tool is parked on */
int (*approval)(void *ctx, char *name, size_t namelen, int *auth,
char *args, size_t argslen);
int (*approve)(void *ctx, int allow);
/* the event queue */
int (*poll)(void *ctx, struct sp_event *out);
void (*event_free)(void *ctx, struct sp_event *ev);
/* state and profiles */
int (*state)(void *ctx, struct sp_engine_state *out);
int (*agents)(void *ctx);
const char *(*agent_name)(void *ctx, int idx);
int (*agent_cur)(void *ctx);
int (*agent_switch)(void *ctx, int idx);
int (*command_names)(void *ctx, char (*names)[64], int max);
/* 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),
void *cbctx);
struct sp_host *(*host)(void *ctx);
struct swarm *(*swarm)(void *ctx);
struct sp_config *(*config)(void *ctx);
const char *(*session_id)(void *ctx);
const char *(*state_dir)(void *ctx);
void (*set_theme)(void *ctx, const char *theme);
int (*quit)(void *ctx);
/* 1 when the engine is this process's (history files are local, then) */
int (*local)(void *ctx);
void (*close)(void *ctx);
};
/*
* The in-process backend. `eng` stays owned by the caller; close is a no-op.
*/
const struct ui_backend *sp_ui_backend_engine(struct sp_engine *eng);
/*
* Connect to a served engine and read the greeting. NULL with `err` filled
* when the socket is not there or answers garbage. The caller must call
* sp_ui_run() and that closes the backend.
*/
const struct ui_backend *sp_ui_backend_remote(const char *socket_path,
struct sp_buf *err);
#endif /* SPLINTER_UI_BACKEND_H */
+209
View File
@@ -0,0 +1,209 @@
/*
* splinter -- the in-process backend for the curses front end.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* Every call here is one engine call. The file is deliberately dull: it is
* the control in the experiment. Whatever --attach can do through the socket,
* this must do through the engine, or the protocol has a hole.
*/
#include <stddef.h>
#include <string.h>
#include "splinter.h"
#include "splinter_engine.h"
#include "ui_backend.h"
static int loc_input(void *ctx, const char *line, struct sp_buf *out)
{
return sp_engine_input(ctx, line, out);
}
static int loc_submit(void *ctx, const char *text)
{
return sp_engine_submit(ctx, text);
}
static int loc_busy(void *ctx)
{
return sp_engine_busy(ctx);
}
static int loc_wait(void *ctx)
{
return sp_engine_wait(ctx);
}
static int loc_take_steer(void *ctx, struct sp_buf *out)
{
return sp_engine_take_steer(ctx, out);
}
static int loc_cancel(void *ctx)
{
return sp_engine_cancel(ctx);
}
static int loc_steer(void *ctx, const char *text)
{
return sp_engine_steer(ctx, text);
}
static int loc_approval(void *ctx, char *name, size_t namelen, int *auth,
char *args, size_t argslen)
{
return sp_engine_approval(ctx, name, namelen, auth, args, argslen);
}
static int loc_approve(void *ctx, int allow)
{
return sp_engine_approve(ctx, allow);
}
static int loc_poll(void *ctx, struct sp_event *out)
{
return sp_engine_poll(ctx, out);
}
static void loc_event_free(void *ctx, struct sp_event *ev)
{
(void)ctx;
sp_engine_event_free(ev);
}
static int loc_state(void *ctx, struct sp_engine_state *out)
{
return sp_engine_state(ctx, out);
}
static int loc_agents(void *ctx)
{
return sp_engine_agents(ctx);
}
static const char *loc_agent_name(void *ctx, int idx)
{
return sp_engine_agent_name(ctx, idx);
}
static int loc_agent_cur(void *ctx)
{
return sp_engine_agent_cur(ctx);
}
static int loc_agent_switch(void *ctx, int idx)
{
return sp_engine_agent_switch(ctx, idx);
}
static int loc_command_names(void *ctx, char (*names)[64], int max)
{
return sp_engine_command_names(ctx, names, max);
}
static int
loc_history(void *ctx, void (*cb)(void *, const char *, const char *),
void *cbctx)
{
const struct sp_conv *conv = sp_engine_conv(ctx);
size_t i;
int n = 0;
if (conv == NULL)
return 0;
for (i = 0; i < conv->n; i++) {
const struct sp_msg *m = &conv->v[i];
if (m->role == NULL || m->content == NULL)
continue;
if (strcmp(m->role, "user") != 0 &&
strcmp(m->role, "assistant") != 0)
continue;
cb(cbctx, m->role, m->content);
n++;
}
return n;
}
static struct sp_host *loc_host(void *ctx)
{
return sp_engine_host(ctx);
}
static struct swarm *loc_swarm(void *ctx)
{
return sp_engine_swarm(ctx);
}
static struct sp_config *loc_config(void *ctx)
{
return sp_engine_config(ctx);
}
static const char *loc_session_id(void *ctx)
{
return sp_engine_session_id(ctx);
}
static const char *loc_state_dir(void *ctx)
{
return sp_engine_state_dir(ctx);
}
static void loc_set_theme(void *ctx, const char *theme)
{
sp_engine_set_theme(ctx, theme);
}
static int loc_quit(void *ctx)
{
return sp_engine_quit(ctx);
}
static int loc_local(void *ctx) { (void)ctx; return 1; }
static void loc_close(void *ctx)
{
(void)ctx;
}
static const struct ui_backend local = {
.input = loc_input,
.submit = loc_submit,
.busy = loc_busy,
.wait = loc_wait,
.cancel = loc_cancel,
.steer = loc_steer,
.take_steer = loc_take_steer,
.approval = loc_approval,
.approve = loc_approve,
.poll = loc_poll,
.event_free = loc_event_free,
.state = loc_state,
.agents = loc_agents,
.agent_name = loc_agent_name,
.agent_cur = loc_agent_cur,
.agent_switch = loc_agent_switch,
.command_names = loc_command_names,
.history = loc_history,
.host = loc_host,
.swarm = loc_swarm,
.config = loc_config,
.session_id = loc_session_id,
.state_dir = loc_state_dir,
.set_theme = loc_set_theme,
.quit = loc_quit,
.local = loc_local,
.close = loc_close
};
const struct ui_backend *
sp_ui_backend_engine(struct sp_engine *eng)
{
static struct ui_backend be;
be = local;
be.ctx = eng;
return &be;
}
+811
View File
@@ -0,0 +1,811 @@
/*
* splinter -- the curses front end behind a socket.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* `splinter --attach` runs the same screen as `--chat`, but the engine is a
* `splinter --serve` in another process. This file turns the line protocol of
* docs/PROTOCOL.md into the operations ui_backend.h promises:
*
* - commands are sent as {"cmd":"input"} and answered with reply/submitted
* - a turn is {"cmd":"say"} (or was already started by input)
* - the event stream is decoded into struct sp_event, the same records the
* in-process backend returns, so the screen cannot tell the difference
* - state, agents and the command list are cached from the state/commands
* events
*
* Everything is synchronous on the UI thread: the screen polls, so a reader
* thread would only add a second queue and a shutdown problem. While a turn
* runs the server streams; the UI drains with a 100 ms tick.
*/
#include <errno.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
#include "splinter.h"
#include "splinter_engine.h"
#include "mcp.h"
#include "protocol.h"
#include "ui_backend.h"
#define REM_MAX_AGENTS 32
#define REM_MAX_NAMES 64
struct rem_item {
char *role;
char *text;
};
struct rem {
int fd;
struct sp_buf in; /* bytes not yet cut into lines */
struct sp_buf line; /* the line being handed to dispatch */
struct sp_event *q;
size_t nq, capq;
struct sp_engine_state st;
struct sp_buf last; /* the text of reply/submitted/error */
char agents[REM_MAX_AGENTS][48];
char names[REM_MAX_NAMES][64];
struct rem_item *hist;
size_t nhist;
int got_history;
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 */
};
static int remote_live; /* one attached screen per process */
static void
q_push(struct rem *r, int kind, long n, const char *a, const char *b)
{
struct sp_event *ev;
if (r->nq == r->capq) {
size_t nc = r->capq != 0 ? r->capq * 2 : 32;
struct sp_event *nq = realloc(r->q, nc * sizeof(*nq));
if (nq == NULL)
return;
r->q = nq;
r->capq = nc;
}
ev = &r->q[r->nq++];
ev->kind = kind;
ev->n = n;
ev->a = a != NULL ? strdup(a) : NULL;
ev->b = b != NULL ? strdup(b) : NULL;
}
static int
q_pop(struct rem *r, struct sp_event *out)
{
if (r->nq == 0)
return 0;
*out = r->q[0];
memmove(&r->q[0], &r->q[1], (r->nq - 1) * sizeof(r->q[0]));
r->nq--;
return 1;
}
static int
send_all(int fd, const char *p, size_t n)
{
while (n > 0) {
ssize_t w = send(fd, p, n, MSG_NOSIGNAL);
if (w < 0) {
if (errno == EINTR)
continue;
return -1;
}
p += w;
n -= (size_t)w;
}
return 0;
}
static int
send_cmd(struct rem *r, const char *cmd, const char *key, const char *val)
{
struct sp_buf b;
int rc;
if (sp_buf_init(&b) != 0)
return -1;
sp_buf_printf(&b, "{\"cmd\":\"%s\"", cmd);
if (key != NULL && val != NULL) {
sp_buf_printf(&b, ",\"%s\":\"", key);
(void)sp_json_escape(&b, val);
sp_buf_puts(&b, "\"");
}
sp_buf_puts(&b, "}\n");
rc = send_all(r->fd, b.p, b.len);
sp_buf_free(&b);
return rc;
}
/* one non-blocking read into the line buffer; 1 data, 0 none, -1 gone */
static int
fill(struct rem *r, int timeout_ms)
{
struct pollfd p = { r->fd, POLLIN, 0 };
char chunk[4096];
ssize_t got;
int pr;
pr = poll(&p, 1, timeout_ms);
if (pr < 0)
return errno == EINTR ? 0 : -1;
if (pr == 0)
return 0;
if (p.revents & (POLLERR | POLLNVAL))
return -1;
if (p.revents & POLLIN) {
got = recv(r->fd, chunk, sizeof(chunk), 0);
if (got <= 0)
return -1;
if (sp_buf_add(&r->in, chunk, (size_t)got) != 0)
return -1;
/*
* A peer that sent its last events and closed reports POLLIN
* and POLLHUP together. The bytes just read are the answer;
* returning -1 here dropped them.
*/
if (p.revents & POLLHUP)
return got > 0 ? 1 : -1;
return 1;
}
if (p.revents & POLLHUP)
return -1;
return 0;
}
/*
* 1 a complete line in r->line, 0 none buffered. The line grows with the
* event: a tool observation or a command reply may be larger than any fixed
* buffer, and a truncated JSON line is an event the front end silently loses.
*/
static int
take_line(struct rem *r)
{
char *nl = memchr(r->in.p, '\n', r->in.len);
size_t len, used;
if (nl == NULL)
return 0;
len = (size_t)(nl - r->in.p);
sp_buf_clear(&r->line);
if (sp_buf_add(&r->line, r->in.p, len) != 0)
return 0;
if (r->line.len > 0 && r->line.p[r->line.len - 1] == '\r')
r->line.p[--r->line.len] = '\0';
used = len + 1;
memmove(r->in.p, r->in.p + used, r->in.len - used);
r->in.len -= used;
r->in.p[r->in.len] = '\0';
return 1;
}
static long
now_ms(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
/* wait up to timeout_ms for one line; 1 line, 0 timeout, -1 connection gone */
static int
next_line(struct rem *r, int timeout_ms)
{
long deadline = now_ms() + timeout_ms;
for (;;) {
int left, rc;
if (take_line(r))
return 1;
left = (int)(deadline - now_ms());
if (left < 0)
left = 0;
rc = fill(r, left);
if (rc < 0)
return -1;
if (rc == 0 && now_ms() >= deadline)
return 0;
}
}
/* cache the state event: everything a sidebar or a Tab needs */
static void
fill_state(struct rem *r, const mcp_json *v)
{
const char *s;
const mcp_json *ag;
r->st.tokens_in = (size_t)mcp_arg_int(v, "tokens_in", 0);
r->st.tokens_out = (size_t)mcp_arg_int(v, "tokens_out", 0);
r->st.steps = (size_t)mcp_arg_int(v, "steps", 0);
r->st.calls = (size_t)mcp_arg_int(v, "calls", 0);
r->st.compactions = (size_t)mcp_arg_int(v, "compactions", 0);
r->st.last_ms = (size_t)mcp_arg_int(v, "last_ms", 0);
r->st.busy = mcp_arg_bool(v, "busy", 0);
r->st.waiting = mcp_arg_bool(v, "waiting", 0);
r->st.quit = mcp_arg_bool(v, "quit", 0);
r->st.agent_cur = mcp_arg_int(v, "agent_cur", 0);
if ((s = mcp_arg_string(v, "session")) != NULL)
snprintf(r->st.session, sizeof(r->st.session), "%s", s);
if ((s = mcp_arg_string(v, "dir")) != NULL)
snprintf(r->st.dir, sizeof(r->st.dir), "%s", s);
if ((s = mcp_arg_string(v, "model")) != NULL)
snprintf(r->st.model, sizeof(r->st.model), "%s", s);
if ((s = mcp_arg_string(v, "endpoint")) != NULL)
snprintf(r->st.endpoint, sizeof(r->st.endpoint), "%s", s);
if ((s = mcp_arg_string(v, "agent")) != NULL)
snprintf(r->st.agent, sizeof(r->st.agent), "%s", s);
ag = mcp_arg(v, "agents");
r->nagents = 0;
if (ag != NULL) {
size_t i, n = mcp_array_len(ag);
for (i = 0; i < n && r->nagents < REM_MAX_AGENTS; i++) {
const char *name = mcp_json_string(mcp_array_at(ag, i));
if (name != NULL)
snprintf(r->agents[r->nagents++],
sizeof(r->agents[0]), "%s", name);
}
}
r->st.agents_n = r->nagents;
}
enum { D_EVENT = 0, D_REPLY, D_SUBMITTED, D_ERROR };
static void
copy_last(struct rem *r, const char *s)
{
sp_buf_clear(&r->last);
(void)sp_buf_puts(&r->last, s != NULL ? s : "");
}
/* one protocol line into events and caches; the D_* says what it was */
static int
dispatch(struct rem *r, const char *line)
{
mcp_json *v = mcp_parse(line);
const char *ev, *s;
int rc = D_EVENT;
if (v == NULL)
return D_EVENT;
ev = mcp_arg_string(v, "ev");
if (ev == NULL) {
mcp_json_free(v);
return D_EVENT;
}
if (strcmp(ev, "state") == 0) {
fill_state(r, v);
/* the screen updates its counters when it drains this one */
q_push(r, SP_EV_STATE, 0, NULL, NULL);
} else if (strcmp(ev, "ready") == 0) {
r->proto = mcp_arg_int(v, "protocol", 0);
} else if (strcmp(ev, "history") == 0) {
const mcp_json *items = mcp_arg(v, "items");
size_t i, n = items != NULL ? mcp_array_len(items) : 0;
for (i = 0; i < r->nhist; i++) {
free(r->hist[i].role);
free(r->hist[i].text);
}
free(r->hist);
r->hist = n > 0 ? calloc(n, sizeof(*r->hist)) : NULL;
r->nhist = 0;
if (r->hist != NULL) {
for (i = 0; i < n; i++) {
const mcp_json *it = mcp_array_at(items, i);
const char *role = mcp_arg_string(it, "role");
const char *text = mcp_arg_string(it, "text");
if (role == NULL || text == NULL)
continue;
r->hist[r->nhist].role = strdup(role);
r->hist[r->nhist].text = strdup(text);
if (r->hist[r->nhist].role != NULL &&
r->hist[r->nhist].text != NULL)
r->nhist++;
else {
free(r->hist[r->nhist].role);
free(r->hist[r->nhist].text);
}
}
}
r->got_history = 1;
} else if (strcmp(ev, "commands") == 0) {
const mcp_json *names = mcp_arg(v, "names");
r->got_cmds = 1;
r->ncommands = 0;
if (names != NULL) {
size_t i, n = mcp_array_len(names);
for (i = 0; i < n && r->ncommands < REM_MAX_NAMES; i++) {
const char *nm = mcp_json_string(
mcp_array_at(names, i));
if (nm != NULL)
snprintf(r->names[r->ncommands++],
sizeof(r->names[0]), "%s", nm);
}
}
} else if (strcmp(ev, "busy") == 0) {
r->st.busy = mcp_arg_bool(v, "on", 0);
q_push(r, SP_EV_BUSY, r->st.busy, NULL, NULL);
} else if (strcmp(ev, "stream") == 0) {
int kind = strcmp(mcp_arg_string(v, "kind") != NULL ?
mcp_arg_string(v, "kind") : "text", "think") == 0 ?
SP_STREAM_THINK : SP_STREAM_TEXT;
q_push(r, SP_EV_STREAM, kind, mcp_arg_string(v, "text"), NULL);
} else if (strcmp(ev, "step") == 0) {
q_push(r, SP_EV_STEP, 0, mcp_arg_string(v, "think"),
mcp_arg_string(v, "text"));
} else if (strcmp(ev, "tool") == 0) {
q_push(r, SP_EV_TOOL, 0, mcp_arg_string(v, "name"),
mcp_arg_string(v, "args"));
} else if (strcmp(ev, "tool_result") == 0) {
q_push(r, SP_EV_TOOL_RESULT,
mcp_arg_bool(v, "join", 0) ? 1 : 0,
mcp_arg_string(v, "name"), mcp_arg_string(v, "text"));
} else if (strcmp(ev, "note") == 0) {
q_push(r, SP_EV_NOTE, 0, mcp_arg_string(v, "text"), NULL);
} else if (strcmp(ev, "entry") == 0) {
q_push(r, SP_EV_ENTRY, 0, mcp_arg_string(v, "role"),
mcp_arg_string(v, "text"));
} else if (strcmp(ev, "approval") == 0) {
r->pending = 1;
r->a_auth = mcp_arg_int(v, "auth", SP_AUTH_MUTATE);
snprintf(r->a_name, sizeof(r->a_name), "%s",
mcp_arg_string(v, "name") != NULL ?
mcp_arg_string(v, "name") : "?");
snprintf(r->a_args, sizeof(r->a_args), "%s",
mcp_arg_string(v, "args") != NULL ?
mcp_arg_string(v, "args") : "");
q_push(r, SP_EV_APPROVAL, r->a_auth, r->a_name, r->a_args);
} else if (strcmp(ev, "turn") == 0) {
q_push(r, SP_EV_TURN_END, mcp_arg_int(v, "rc", 1),
mcp_arg_string(v, "answer"), mcp_arg_string(v, "error"));
} else if (strcmp(ev, "clear") == 0) {
q_push(r, SP_EV_CLEAR, 0, NULL, NULL);
} else if (strcmp(ev, "quit") == 0) {
r->st.quit = 1;
q_push(r, SP_EV_QUIT, 0, NULL, NULL);
} else if (strcmp(ev, "reply") == 0) {
copy_last(r, mcp_arg_string(v, "text"));
rc = D_REPLY;
} else if (strcmp(ev, "submitted") == 0) {
copy_last(r, mcp_arg_string(v, "text"));
r->presubmitted = 1;
r->st.busy = 1;
rc = D_SUBMITTED;
} 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");
rc = D_ERROR;
}
mcp_json_free(v);
return rc;
}
/* ------------------------------------------------------------- operations */
static int
rem_input(void *ctx, const char *line, struct sp_buf *out)
{
struct rem *r = ctx;
if (send_cmd(r, "input", "line", line) != 0)
return SP_INPUT_HANDLED;
for (;;) {
int rc = next_line(r, 30000);
if (rc < 0) {
sp_buf_puts(out, "connection to the backend lost");
return SP_INPUT_HANDLED;
}
if (rc == 0) {
sp_buf_puts(out, "the backend did not answer");
return SP_INPUT_HANDLED;
}
rc = dispatch(r, r->line.p);
if (rc == D_REPLY) {
(void)sp_buf_puts(out, r->last.p != NULL ? r->last.p : "");
return SP_INPUT_HANDLED;
}
if (rc == D_ERROR) {
/*
* dispatch queued an error entry; the screen shows it
* when it drains. Returning it here too printed it
* twice.
*/
return SP_INPUT_HANDLED;
}
if (rc == D_SUBMITTED) {
/*
* The server already started this turn. The screen adds
* the line and calls submit; that call is the no-op.
*/
(void)sp_buf_puts(out, r->last.p != NULL ? r->last.p : "");
return SP_INPUT_PROMPT;
}
/* an event (state, entry, ...): queued, keep waiting */
}
}
static int
rem_submit(void *ctx, const char *text)
{
struct rem *r = ctx;
if (r->presubmitted) {
r->presubmitted = 0;
return 0;
}
if (send_cmd(r, "say", "text", text) != 0)
return -1;
r->st.busy = 1;
return 0;
}
static int rem_busy(void *ctx) { return ((struct rem *)ctx)->st.busy; }
static int rem_wait(void *ctx) { (void)ctx; return 0; }
static int
rem_cancel(void *ctx)
{
struct rem *r = ctx;
return send_cmd(r, "cancel", NULL, NULL);
}
static int
rem_steer(void *ctx, const char *text)
{
return send_cmd(ctx, "steer", "text", text);
}
static int
rem_approval(void *ctx, char *name, size_t namelen, int *auth, char *args,
size_t argslen)
{
struct rem *r = ctx;
if (!r->pending)
return 0;
if (name != NULL && namelen > 0)
snprintf(name, namelen, "%s", r->a_name);
if (args != NULL && argslen > 0)
snprintf(args, argslen, "%s", r->a_args);
if (auth != NULL)
*auth = r->a_auth;
return 1;
}
static int
rem_approve(void *ctx, int allow)
{
struct rem *r = ctx;
struct sp_buf b;
int rc;
if (!r->pending)
return 0;
r->pending = 0;
if (sp_buf_init(&b) != 0)
return 0;
sp_buf_printf(&b, "{\"cmd\":\"approve\",\"allow\":%s}\n",
allow ? "true" : "false");
rc = send_all(r->fd, b.p, b.len);
sp_buf_free(&b);
return rc == 0;
}
static int
rem_poll(void *ctx, struct sp_event *out)
{
struct rem *r = ctx;
if (q_pop(r, out))
return 1;
if (r->eof)
return 0;
for (;;) {
int rc = next_line(r, 0);
if (rc < 0) {
/* the backend went away: one quit event, then quiet */
r->eof = 1;
r->st.busy = 0;
r->st.quit = 1;
q_push(r, SP_EV_QUIT, 0, NULL, NULL);
return q_pop(r, out);
}
if (rc == 0)
return 0;
(void)dispatch(r, r->line.p);
if (q_pop(r, out))
return 1;
}
}
static void
rem_event_free(void *ctx, struct sp_event *ev)
{
(void)ctx;
if (ev == NULL)
return;
free(ev->a);
free(ev->b);
ev->a = ev->b = NULL;
}
static int
rem_state(void *ctx, struct sp_engine_state *out)
{
struct rem *r = ctx;
if (out == NULL)
return -1;
*out = r->st;
return 0;
}
static int rem_agents(void *ctx) { return ((struct rem *)ctx)->nagents; }
static const char *
rem_agent_name(void *ctx, int idx)
{
struct rem *r = ctx;
if (idx < 0 || idx >= r->nagents)
return "";
return r->agents[idx];
}
static int rem_agent_cur(void *ctx) { return ((struct rem *)ctx)->st.agent_cur; }
static int
rem_agent_switch(void *ctx, int idx)
{
struct rem *r = ctx;
char line[96];
struct sp_buf out;
if (idx < 0 || idx >= r->nagents)
return -1;
snprintf(line, sizeof(line), "/agent %s", r->agents[idx]);
if (sp_buf_init(&out) != 0)
return -1;
(void)rem_input(r, line, &out);
sp_buf_free(&out);
return 0;
}
static int
rem_command_names(void *ctx, char (*names)[64], int max)
{
struct rem *r = ctx;
int i, n = 0;
for (i = 0; i < r->ncommands && n < max; i++)
snprintf(names[n++], 64, "%s", r->names[i]);
return n;
}
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 */
(void)ctx;
(void)out;
return 0;
}
static int
rem_history(void *ctx, void (*cb)(void *, const char *, const char *),
void *cbctx)
{
struct rem *r = ctx;
size_t i;
for (i = 0; i < r->nhist; i++)
cb(cbctx, r->hist[i].role, r->hist[i].text);
return (int)r->nhist;
}
static struct sp_host *rem_host(void *ctx) { (void)ctx; return NULL; }
static struct swarm *rem_swarm(void *ctx) { (void)ctx; return NULL; }
static struct sp_config *rem_config(void *ctx) { (void)ctx; return NULL; }
static const char *
rem_session_id(void *ctx)
{
return ((struct rem *)ctx)->st.session;
}
static const char *
rem_state_dir(void *ctx)
{
return ((struct rem *)ctx)->st.dir;
}
static void rem_set_theme(void *ctx, const char *theme) { (void)ctx; (void)theme; }
static int rem_quit(void *ctx) { return ((struct rem *)ctx)->st.quit; }
static int rem_local(void *ctx) { (void)ctx; return 0; }
static void
rem_close(void *ctx)
{
struct rem *r = ctx;
struct sp_event ev;
if (r == NULL)
return;
remote_live = 0;
while (q_pop(r, &ev))
rem_event_free(r, &ev);
for (size_t i = 0; i < r->nhist; i++) {
free(r->hist[i].role);
free(r->hist[i].text);
}
free(r->hist);
free(r->q);
sp_buf_free(&r->in);
sp_buf_free(&r->line);
sp_buf_free(&r->last);
if (r->fd >= 0)
close(r->fd);
free(r);
}
static int
connect_to(const char *path)
{
struct sockaddr_un addr;
int fd;
if (strlen(path) >= sizeof(addr.sun_path)) {
errno = ENAMETOOLONG;
return -1;
}
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0)
return -1;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", path);
if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
close(fd);
return -1;
}
return fd;
}
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')
snprintf(path, sizeof(path), "%s", socket_path);
if (remote_live) {
sp_buf_printf(err, "%s: this process is already attached", path);
return NULL;
}
r = calloc(1, sizeof(*r));
if (r == NULL) {
sp_buf_puts(err, "out of memory");
return NULL;
}
r->fd = -1;
if (sp_buf_init(&r->in) != 0 || sp_buf_init(&r->line) != 0 ||
sp_buf_init(&r->last) != 0) {
sp_buf_free(&r->in);
sp_buf_free(&r->line);
free(r);
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));
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;
be.busy = rem_busy;
be.wait = rem_wait;
be.cancel = rem_cancel;
be.steer = rem_steer;
be.approval = rem_approval;
be.approve = rem_approve;
be.poll = rem_poll;
be.event_free = rem_event_free;
be.state = rem_state;
be.agents = rem_agents;
be.agent_name = rem_agent_name;
be.agent_cur = rem_agent_cur;
be.agent_switch = rem_agent_switch;
be.command_names = rem_command_names;
be.take_steer = rem_take_steer;
be.history = rem_history;
be.host = rem_host;
be.swarm = rem_swarm;
be.config = rem_config;
be.session_id = rem_session_id;
be.state_dir = rem_state_dir;
be.set_theme = rem_set_theme;
be.quit = rem_quit;
be.local = rem_local;
be.close = rem_close;
remote_live = 1;
return &be;
fail:
rem_close(r);
r = NULL;
return NULL;
}
+206 -414
View File
@@ -18,6 +18,7 @@
#include <unistd.h>
#include "splinter.h"
#include "splinter_engine.h"
#include "config.h"
#include "i18n.h"
#include "log.h"
@@ -32,10 +33,11 @@
#include "a2aserver.h"
#include "interview.h"
#include "ack.h"
#include "swarm.h"
#include "splinter_plugin.h"
#include "theme.h"
#include "ui.h"
#include "ui_backend.h"
#include "protocol.h"
static void
usage(FILE *f)
@@ -69,6 +71,10 @@ usage(FILE *f)
" --kind NAME vendor shape of --endpoint: openai (default)\n"
" or anthropic\n"
" --chat interactive curses UI instead of one turn\n"
" --serve serve the line protocol on a Unix socket\n"
" --attach run the curses UI as a client of --serve\n"
" --socket PATH socket for --serve/--attach (default\n"
" ~/.splinter/splinter.sock)\n"
" --theme NAME UI theme: Xresources (default) or a CDE\n"
" palette, e.g. Default, Delphinium, MakroSlate\n"
" --list-themes print the palette names and exit\n"
@@ -112,37 +118,6 @@ need_value(int argc, int i, const char *flag)
}
return 1;
}
/*
* A script file is one reply per line, in the mock transport's own protocol
* ("answer ...", "tool <name> <args>"). Loading it up front means the whole
* turn is deterministic and re-runnable, with no network anywhere.
*/
static int
load_script(struct sp_mock *m, const char *path, struct sp_buf *err)
{
FILE *f;
char line[8192];
f = fopen(path, "r");
if (f == NULL) {
sp_buf_printf(err, "%s: %s", path, strerror(errno));
return -1;
}
while (fgets(line, sizeof(line), f) != NULL) {
line[strcspn(line, "\r\n")] = '\0';
if (line[0] == '\0' || line[0] == '#')
continue;
if (sp_mock_push(m, 200, line) != 0) {
fclose(f);
sp_buf_puts(err, sp_t("err.oom"));
return -1;
}
}
fclose(f);
return 0;
}
/* one-shot mode: print the answer as it arrives, no buffering */
/* bytes the transport streamed: if none, the answer still has to be printed */
static size_t streamed_bytes;
@@ -218,6 +193,9 @@ daemon_stream(void *ctx, int kind, const char *text)
(void)text;
}
/* the longest wait for a usage limit in seconds, 0: the default of 12 h */
static long g_max_wait;
/* everything the command line can say */
struct opts {
const char *prompt, *endpoint, *script, *model, *key_env;
@@ -236,6 +214,8 @@ struct opts {
int acklist, ack_id, ack_yes, mcp_port;
const char *a2a_ip;
int a2a_port;
int serve, attach;
const char *socket;
};
/* the yes/no word of --ack; -1 for anything else */
@@ -250,25 +230,6 @@ ack_word(const char *w)
return 0;
return -1;
}
static struct sp_agent *g_ag;
static struct sp_config *g_conf;
/* a provider at its limit: another member of its pool, if one has room */
static int
main_switch(void *ctx)
{
(void)ctx;
return sp_provider_failover(g_ag, g_conf);
}
/* the longest wait for a usage limit in seconds, 0: the default of 12 h */
static long g_max_wait;
/*
* The command line into 'o' and 'cfg'. Returns -1 to go on, or the exit
* status (help and version exit 0, a bad option 2).
*/
static int
parse_args(int argc, char **argv, struct opts *o, struct sp_agent_config *cfg)
{
@@ -335,6 +296,12 @@ parse_args(int argc, char **argv, struct opts *o, struct sp_agent_config *cfg)
o->plugins[o->nplugins++] = argv[++i];
} else if (!strcmp(a, "--chat"))
o->chat = 1;
else if (!strcmp(a, "--serve"))
o->serve = 1;
else if (!strcmp(a, "--attach"))
o->attach = 1;
else if (!strcmp(a, "--socket"))
VALUE(o->socket);
else if (!strcmp(a, "--choose")) {
if (i + 1 >= argc) {
fprintf(stderr, "splinter: --choose needs text\n");
@@ -448,7 +415,8 @@ take_stdin(struct opts *o)
size_t raw = 0;
/* the interview asks its questions on stdin: leave it alone */
if (o->no_stdin || o->chat || o->daemon || o->interview ||
if (o->no_stdin || o->chat || o->attach || o->daemon ||
o->interview ||
isatty(STDIN_FILENO) || sp_buf_init(&intake) != 0)
return;
if (read_stdin_block(&intake, &is_binary, &raw) != 0 || raw == 0) {
@@ -701,9 +669,9 @@ 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->a2a_ip == NULL && !o->serve) {
fprintf(stderr, "splinter: -p/--prompt is required unless you pass "
"--chat, --daemon, --mcp-server-listen or "
"--chat, --serve, --daemon, --mcp-server-listen or "
"--a2a-server-listen\n");
return 2;
}
@@ -711,10 +679,16 @@ check_usage(const struct opts *o)
}
/* the session directory and id, opened; 0 or the exit status */
/*
* For the one-shot modes that need a session directory but no agent
* (--interview, --ack*): the same rules as the engine's, without building it.
*/
static int
open_session(struct opts *o, struct sp_session_info *sess, struct sp_buf *err)
open_session_only(struct opts *o, struct sp_session_info *sess,
struct sp_buf *err)
{
static char sessbuf[512], idbuf[64];
char cwd[512];
if (o->sessdir == NULL) {
const char *home = getenv("HOME");
@@ -723,13 +697,7 @@ open_session(struct opts *o, struct sp_session_info *sess, struct sp_buf *err)
home != NULL ? home : ".");
o->sessdir = sessbuf;
}
/*
* -c means "the last session that happened *here*". The cwd at start is
* the key, so a session in another tree is never silently loaded.
*/
if (o->continue_here && o->sessid == NULL) {
char cwd[512];
if (getcwd(cwd, sizeof(cwd)) == NULL ||
sp_session_last_for(o->sessdir, cwd, idbuf,
sizeof(idbuf)) != 0) {
@@ -740,11 +708,6 @@ open_session(struct opts *o, struct sp_session_info *sess, struct sp_buf *err)
o->sessid = idbuf;
o->resume = 1;
}
/*
* --resume continues the newest session in the directory unless an id was
* named. Opening a fresh id would resume nothing and still look like it
* worked - the first version of this flag did exactly that.
*/
if (o->resume && o->sessid == NULL &&
sp_session_latest(o->sessdir, idbuf, sizeof(idbuf)) == 0)
o->sessid = idbuf;
@@ -758,70 +721,9 @@ open_session(struct opts *o, struct sp_session_info *sess, struct sp_buf *err)
err->len > 0 ? err->p : sp_t("err.session"));
return 3;
}
(void)sp_log_open(sess->dir, sess->id);
/*
* The cli transport keys the program's own session on this, so claude or
* opencode continue one conversation for the whole splinter session. A
* delegate child inherits its parent's key (plus its name), never its own.
*/
(void)setenv("SPLINTER_CLI_SESSION", sess->id, 0);
return 0;
}
/*
* The plugin host and its plugins. A plugin that fails to load is reported and
* skipped: the harness keeps working, the operator sees why. Returns 0 or the
* exit status; *hostp stays NULL without plugins.
*/
static int
load_plugins(const struct opts *o, struct sp_registry *reg, struct sp_agent *ag,
struct sp_session_info *sess, const struct sp_config *conf,
struct sp_host **hostp, struct sp_buf *err)
{
struct sp_host *host;
size_t k;
*hostp = NULL;
if (o->nplugins == 0)
return 0;
host = sp_host_new(reg, ag, sess);
if (host == NULL) {
fprintf(stderr, "splinter: cannot create plugin host\n");
return 3;
}
/*
* The agent compacts through this pointer. It was never set, so every
* compactor - lcm, focus, reminder - was registered, tested in isolation,
* and never called by the real binary.
*/
ag->host = host;
sp_host_set_config(host, conf);
for (k = 0; k < o->nplugins; k++) {
const char *p = o->plugins[k];
char self[512], found[800];
ssize_t sn;
/*
* A bare name ("lcm", from plugin lcm { }) is a shipped plugin:
* the tree next to the binary, then the installed layout.
*/
if (strchr(p, '/') == NULL &&
(strlen(p) < 3 || strcmp(p + strlen(p) - 3, ".so") != 0)) {
sn = readlink("/proc/self/exe", self, sizeof(self) - 1);
self[sn > 0 ? sn : 0] = '\0';
sp_plugin_path(self, p, found, sizeof(found));
p = found;
}
sp_buf_clear(err);
if (sp_plugin_load(host, p, err) != 0)
fprintf(stderr, "splinter: %s\n", err->len > 0 ? err->p :
sp_t("err.plugin_failed"));
}
*hostp = host;
return 0;
}
/* is the first word of 'cmd' a program on PATH? */
static int
program_found(const char *cmd)
{
@@ -1105,122 +1007,6 @@ run_model_list(const struct sp_config *conf, const struct opts *o)
/* the transport the options name; 0 or the exit status */
static int
pick_transport(const struct opts *o, struct sp_agent *ag, struct sp_host *host,
const struct sp_registry *reg, struct sp_mock *mock, int *have_mock,
struct sp_buf *err)
{
/* a built-in vendor shape, not a plugin transport */
const char *transport = o->transport;
if (o->kind != NULL && strcmp(o->kind, "anthropic") == 0) {
const char *hto = getenv("SPLINTER_HTTP_TIMEOUT");
long http_timeout;
if (o->endpoint == NULL || o->model == NULL) {
fprintf(stderr, "splinter: an anthropic provider needs "
"an endpoint and a model\n");
return 2;
}
http_timeout = hto != NULL && *hto != '\0' ?
strtol(hto, NULL, 10) : 0;
if (http_timeout <= 0)
http_timeout = 900;
ag->tr = sp_anthropic_transport(o->endpoint, o->model,
getenv(o->key_env), reg, http_timeout);
sp_provider_identify(&ag->tr, o->endpoint, getenv(o->key_env));
return 0;
}
if (transport != NULL) {
struct sp_transport *tr;
if (host == NULL) {
fprintf(stderr, "splinter: --transport needs a plugin that "
"provides it (--plugin)\n");
return 2;
}
tr = sp_host_transport(host, transport);
if (tr == NULL) {
fprintf(stderr, "splinter: no plugin provides the '%s' "
"transport\n", transport);
return 2;
}
ag->tr = *tr;
} else if (o->script != NULL) {
if (sp_mock_init(mock) != 0) {
fprintf(stderr, "splinter: %s\n", sp_t("err.oom"));
return 3;
}
*have_mock = 1;
if (load_script(mock, o->script, err) != 0) {
fprintf(stderr, "splinter: %s\n",
err->len > 0 ? err->p : "script");
return 3;
}
ag->tr = sp_mock_transport(mock);
} else if (o->mcp_ip == NULL) {
/* in MCP server mode no model is needed: we are the tool provider */
const char *hto;
long http_timeout;
if (o->model == NULL) {
fprintf(stderr, "splinter: --endpoint needs --model\n");
return 2;
}
hto = getenv("SPLINTER_HTTP_TIMEOUT");
http_timeout = hto != NULL && *hto != '\0' ? strtol(hto, NULL, 10) : 0;
if (http_timeout <= 0)
http_timeout = 900;
ag->tr = sp_openai_transport(o->endpoint, o->model,
getenv(o->key_env), reg, http_timeout);
/* provider identity for per-key quota/usage tracking (plugins) */
sp_provider_identify(&ag->tr, o->endpoint, getenv(o->key_env));
}
return 0;
}
/*
* The conversation: the system prompt, expanded - placeholders are facts about
* this machine, and the model should not have to ask for them - and with
* --resume the session's history. Returns 0 or the exit status.
*/
static int
setup_conversation(const struct opts *o, struct sp_agent *ag,
struct sp_agent_config *cfg, struct sp_session_info *sess,
struct sp_buf *err)
{
static struct sp_conv conv;
static char expanded[8192];
size_t loaded = 0;
sp_conv_init(&conv);
sp_prompt_expand(cfg->system_prompt, expanded, sizeof(expanded), o->model);
cfg->system_prompt = expanded;
if (sp_conv_push(&conv, "system", NULL, cfg->system_prompt) != 0) {
fprintf(stderr, "splinter: %s\n", sp_t("err.oom"));
return 3;
}
ag->conv = &conv;
if (!o->resume)
return 0;
sp_buf_clear(err);
if (sp_session_load(sess, &conv, &loaded, err) != 0) {
fprintf(stderr, "splinter: %s\n",
err->len > 0 ? err->p : "cannot load the session");
return 3;
}
if (loaded > 0)
fprintf(stderr, "splinter: resumed %zu messages from %s\n", loaded,
sess->dir);
return 0;
}
/*
* One gateway per session directory. Two pollers race for getUpdates: one of
* them reads the update and the other never sees it, so a message is answered
* by nobody or twice. The lock is the pid file itself and lives as long as
* the process: flock is released by the kernel when it exits, even on a kill.
*/
static int
daemon_lock(const char *dir, struct sp_buf *err)
{
char path[700], other[32];
@@ -1253,16 +1039,19 @@ daemon_lock(const char *dir, struct sp_buf *err)
return fd;
}
/* --daemon: answer on Telegram until SIGINT */
/* --daemon: answer on Telegram until SIGINT */
static int
run_daemon(struct sp_agent *ag, struct sp_agent_config *cfg,
struct sp_host *host, const struct sp_session_info *sess,
struct sp_config *conf, struct sp_buf *err)
run_daemon(struct sp_engine *eng, struct sp_buf *err)
{
char token[256], tpath[700];
int rc, lockfd;
char token[256], tpath[700];
struct sp_config *conf = sp_engine_config(eng);
struct sp_agent *ag = sp_engine_agent(eng);
struct sp_host *host = sp_engine_host(eng);
int rc, lockfd;
snprintf(tpath, sizeof(tpath), "%s/telegram.token", sess->dir);
snprintf(tpath, sizeof(tpath), "%s/telegram.token",
sp_engine_state_dir(eng));
if (sp_telegram_token(token, sizeof(token), tpath) != 0) {
fprintf(stderr, "splinter: no Telegram token: put it in %s (0600) "
"or set SPLINTER_TELEGRAM_TOKEN\n", tpath);
@@ -1273,14 +1062,13 @@ run_daemon(struct sp_agent *ag, struct sp_agent_config *cfg,
"be answered\n");
return 2;
}
lockfd = daemon_lock(sess->dir, err);
lockfd = daemon_lock(sp_engine_state_dir(eng), err);
if (lockfd < 0) {
fprintf(stderr, "splinter: %s\n",
err->len > 0 ? err->p : "gateway already running");
return 2;
}
cfg->stream = daemon_stream;
cfg->stream_ctx = NULL;
sp_engine_set_stream(eng, daemon_stream, NULL);
rc = sp_telegram_run(ag, host, token, conf->telegram_allow, conf,
err);
close(lockfd); /* the flock goes with it */
@@ -1292,63 +1080,101 @@ run_daemon(struct sp_agent *ag, struct sp_agent_config *cfg,
/* a leading slash is a harness command, also without a TUI */
static int
run_slash_prompt(struct sp_host *host, const char *prompt)
run_slash_prompt(struct sp_engine *eng, const char *prompt)
{
char name[64], args[1536];
struct sp_buf out;
const char *sp = strchr(prompt, ' ');
int rc = 0;
struct sp_buf out;
int rc = 0, kind;
if (sp == NULL) {
snprintf(name, sizeof(name), "%.63s", prompt + 1);
args[0] = '\0';
} else {
size_t nlen = (size_t)(sp - (prompt + 1));
if (nlen >= sizeof(name))
nlen = sizeof(name) - 1;
memcpy(name, prompt + 1, nlen);
name[nlen] = '\0';
snprintf(args, sizeof(args), "%s", sp + 1);
}
if (sp_buf_init(&out) != 0)
return 3;
if (sp_host_command(host, name, args, &out) != 0) {
sp_buf_clear(&out);
sp_buf_printf(&out, sp_t("cmd.unknown"), name);
sp_buf_printf(&out, "\n %s ", sp_t("cmd.available"));
(void)sp_host_command_help(host, &out);
rc = 2;
kind = sp_engine_input(eng, prompt, &out);
if (kind == SP_INPUT_PROMPT) {
struct sp_buf err, answer;
int prc;
if (sp_buf_init(&err) != 0 || sp_buf_init(&answer) != 0) {
sp_buf_free(&out);
return 3;
}
prc = sp_engine_prompt(eng,
out.len > 0 ? out.p : prompt, NULL, NULL, &answer, &err);
if (prc == 0)
printf("%s\n", answer.p != NULL ? answer.p : "");
else {
fprintf(stderr, "splinter: %s\n",
err.len > 0 ? err.p : "turn failed");
rc = 1;
}
sp_buf_free(&err);
sp_buf_free(&answer);
} else if (kind == SP_INPUT_SUBMIT) {
/*
* A program in commands/ replaced the line: its output is the
* prompt. The entry the engine queued for it is shown first,
* then the turn runs on the text.
*/
struct sp_event ev;
struct sp_buf answer, err;
int prc;
while (sp_engine_poll(eng, &ev)) {
if (ev.kind == SP_EV_ENTRY && ev.b != NULL)
printf("%s\n", ev.b);
sp_engine_event_free(&ev);
}
if (sp_buf_init(&answer) != 0 || sp_buf_init(&err) != 0) {
sp_buf_free(&out);
return 3;
}
prc = sp_engine_prompt(eng, out.p != NULL ? out.p : "", NULL,
NULL, &answer, &err);
if (prc == 0)
printf("%s\n", answer.p != NULL ? answer.p : "");
else {
fprintf(stderr, "splinter: %s\n",
err.len > 0 ? err.p : "turn failed");
rc = 1;
}
sp_buf_free(&answer);
sp_buf_free(&err);
} else {
struct sp_event ev;
if (out.p != NULL && out.len > 0)
printf("%s\n", out.p);
/* a '!' shell line answers as an entry, not as a reply */
while (sp_engine_poll(eng, &ev)) {
if (ev.kind == SP_EV_ENTRY && ev.b != NULL)
printf("%s\n", ev.b);
sp_engine_event_free(&ev);
}
}
printf("%s\n", out.p != NULL ? out.p : "");
sp_buf_free(&out);
return rc;
}
/* -p: one turn, the answer on stdout */
static int
run_prompt(struct sp_agent *ag, struct sp_agent_config *cfg, const char *prompt,
int no_stream, struct sp_buf *err)
run_prompt(struct sp_engine *eng, const char *prompt, int no_stream,
struct sp_buf *err)
{
struct sp_buf answer;
struct sp_agent *ag = sp_engine_agent(eng);
int rc;
if (sp_buf_init(&answer) != 0)
return 3;
/*
* Only claim streaming when the transport can stream. With a transport
* that cannot (the cli plugin, an MCP-backed one), setting the callback
* made the agent take the non-streaming path while main still assumed the
* text had already been printed - the answer vanished and only a newline
* came out. --no-stream asks for the blocking path on purpose, which is
* also the only way to exercise a transport's plain send from the CLI.
* that cannot (the cli plugin), setting the callback made the agent take
* the non-streaming path while main still assumed the text had already
* been printed - the answer vanished.
*/
cfg->stream = (!no_stream && ag->tr.send_stream != NULL) ?
stdout_stream : NULL;
cfg->stream_ctx = NULL;
rc = sp_agent_run(ag, prompt, &answer, err);
rc = sp_engine_prompt(eng, prompt,
(!no_stream && ag->tr.send_stream != NULL) ? stdout_stream : NULL,
NULL, &answer, err);
if (rc == 0) {
if (cfg->stream == NULL || streamed_bytes == 0)
if (streamed_bytes == 0)
printf("%s\n", answer.p != NULL ? answer.p : "");
else
printf("\n"); /* the stream already printed it */
@@ -1363,21 +1189,15 @@ int
main(int argc, char **argv)
{
struct opts o;
struct sp_registry reg;
struct sp_agent ag;
struct sp_agent_config cfg;
struct sp_session_info sess;
struct sp_config conf;
struct sp_mock mock;
struct sp_host *host = NULL;
struct sp_engine_opts eo;
struct sp_engine *eng = NULL;
struct sp_buf err;
int rc, have_mock = 0;
int rc;
memset(&o, 0, sizeof(o));
memset(&reg, 0, sizeof(reg));
memset(&ag, 0, sizeof(ag));
memset(&cfg, 0, sizeof(cfg));
memset(&sess, 0, sizeof(sess));
o.key_env = "SPLINTER_API_KEY";
o.mcp_port = 8098;
o.a2a_port = 8099;
@@ -1401,7 +1221,7 @@ main(int argc, char **argv)
take_stdin(&o);
if ((rc = load_config(&o, &conf, &cfg, &err)) >= 0)
return rc;
/* providers from the environment: OLLAMA_KEY(_N), CLAUDE_CODE_OAUTH_TOKEN(_N) */
/* providers from the environment: OLLAMA_KEY(_N), ... */
{
size_t auto_added = sp_config_scan_env(&conf);
@@ -1434,29 +1254,43 @@ main(int argc, char **argv)
sp_agents_free(&al);
return 0;
}
/*
* --attach is a front end, not a run: no provider, no session, no
* engine in this process. The backend is another program.
*/
if (o.attach) {
const struct ui_backend *be;
if (o.prompt != NULL || o.serve || o.daemon ||
o.mcp_ip != NULL || o.a2a_ip != NULL ||
o.select != NULL) {
fprintf(stderr, "splinter: --attach is the screen "
"alone; drop -p/-m/--serve/--daemon/the servers\n");
return 2;
}
sp_buf_clear(&err);
be = sp_ui_backend_remote(o.socket, &err);
if (be == NULL) {
fprintf(stderr, "splinter: %s\n",
err.len > 0 ? err.p : "cannot attach");
sp_buf_free(&err);
return 3;
}
rc = sp_ui_run(be, o.theme);
sp_buf_free(&err);
return rc;
}
if ((rc = apply_selection(&o, &conf)) != 0)
return rc;
if (o.choose != NULL)
return run_choose(&conf, o.choose);
/* the catalogue is chosen now: a config file may set the locale */
(void)sp_i18n_init(NULL);
if ((rc = check_usage(&o)) != 0)
return rc;
if (sp_builtin_register(&reg) != 0 ||
sp_memory_register(&reg, &conf) != 0 ||
sp_skills_register(&reg, &conf) != 0) {
fprintf(stderr, "splinter: cannot register the builtin tools\n");
return 3;
}
if ((rc = open_session(&o, &sess, &err)) != 0)
return rc;
ag.sess = &sess;
sp_openai_set_session(sess.id);
/*
* Answering is not running an agent: any process may drop the answer,
* which is the whole point of the file behind it.
* The modes that answer without an agent: a stored approval and the
* first-run interview. Everything else is built by the engine.
*/
if (o.acklist) {
struct sp_buf out;
@@ -1479,133 +1313,91 @@ main(int argc, char **argv)
return 0;
}
if (o.interview) {
struct sp_session_info sess;
memset(&sess, 0, sizeof(sess));
if ((rc = open_session_only(&o, &sess, &err)) != 0)
return rc;
rc = sp_interview_run(sess.dir, &err);
if (rc != 0)
fprintf(stderr, "splinter: %s\n",
err.len > 0 ? err.p : "interview failed");
return rc == 0 ? 0 : 1;
}
sp_logf("session", "started: %s", sess.id);
if ((rc = load_plugins(&o, &reg, &ag, &sess, &conf, &host, &err)) != 0)
return rc;
/*
* Registered here, not with the builtins: folder_history needs the
* session directory, and delegate needs the host for its task-panel
* entries. Before, the first got an uninitialised sess.dir and the second
* always got host == NULL - a delegation never showed up in the panel.
*/
if (sp_folder_register(&reg, sess.dir) != 0 ||
sp_delegate_register(&reg, &conf, host) != 0) {
fprintf(stderr, "splinter: cannot register folder_history or "
"delegate\n");
return 3;
memset(&eo, 0, sizeof(eo));
eo.conf = &conf;
eo.base = &cfg;
eo.endpoint = o.endpoint;
eo.model = o.model;
eo.key_env = o.key_env;
eo.transport = o.transport;
eo.kind = o.kind;
eo.script = o.script;
eo.agent = o.agent;
eo.session_dir = o.sessdir;
eo.session_id = o.sessid;
eo.resume = o.resume;
eo.continue_last = o.continue_here;
eo.no_transport = o.mcp_ip != NULL || o.delegate != NULL;
/* the fleet belongs to the curses chat, not to a served engine */
eo.swarm = o.chat && !o.serve && !o.daemon && o.a2a_ip == NULL &&
o.mcp_ip == NULL && o.delegate == NULL;
{
size_t k;
for (k = 0; k < o.nplugins && k < SP_ENGINE_PLUGINS; k++)
eo.plugins[k] = o.plugins[k];
eo.nplugins = k;
}
if (o.delegate != NULL) {
rc = run_delegate_cli(&reg, o.delegate, o.prompt);
goto cleanup;
}
if ((rc = pick_transport(&o, &ag, host, &reg, &mock, &have_mock,
&err)) != 0)
return rc;
/*
* /model shows the run's providers, and a command line is part of the
* run: --endpoint/--model without a config file still has a provider.
*/
if (conf.endpoint[0] == '\0' && o.endpoint != NULL)
snprintf(conf.endpoint, sizeof(conf.endpoint), "%s", o.endpoint);
if (conf.model[0] == '\0' && o.model != NULL)
snprintf(conf.model, sizeof(conf.model), "%s", o.model);
if ((rc = setup_conversation(&o, &ag, &cfg, &sess, &err)) != 0)
return rc;
cfg.approval_in = stdin;
cfg.approval_out = stderr;
ag.reg = &reg;
ag.cfg = &cfg;
if (o.agent != NULL) {
static struct sp_agents al;
static struct sp_tool_policy pol;
char cwd[700];
int idx;
{
int erc = sp_engine_open(&eng, &eo, &err);
if (getcwd(cwd, sizeof(cwd)) == NULL)
cwd[0] = '\0';
if (sp_agents_load(&al, cwd, getenv("HOME")) != 0 ||
(idx = sp_agents_find(&al, o.agent)) < 0) {
fprintf(stderr, "splinter: no agent '%s' "
"(splinter --agent-list)\n", o.agent);
return 2;
}
if (o.chat)
sp_ui_start_agent(o.agent);
else {
char *base = sp_agents_base(ag.conv);
(void)sp_agents_activate(&ag, &al.v[idx],
base != NULL ? base : "", &pol);
free(base);
if (al.v[idx].autonomous >= 0)
cfg.autonomous = al.v[idx].autonomous;
if (al.v[idx].model[0] != '\0') {
struct sp_choice ch;
if (sp_provider_choose(&conf, al.v[idx].model,
&ch) == 0 && ch.d->endpoint[0] != '\0' &&
strcmp(ch.d->kind, "cli") != 0) {
(void)sp_provider_apply(&ag, ch.d->kind,
ch.d->endpoint,
ch.model[0] != '\0' ? ch.model :
ch.d->model, ch.d->key_env, &err);
sp_usage_set_active(ch.d->id);
}
}
if (erc != 0) {
fprintf(stderr, "splinter: %s\n",
err.len > 0 ? err.p : "cannot start the engine");
sp_buf_free(&err);
return erc == -2 ? 2 : 3;
}
}
g_ag = &ag;
g_conf = &conf;
if (conf.npools > 0) {
cfg.limit_switch = main_switch;
cfg.switch_ctx = NULL;
}
if (o.a2a_ip != NULL) {
rc = sp_a2a_serve(&ag, o.a2a_ip, o.a2a_port, &err);
if (o.delegate != NULL)
rc = run_delegate_cli(sp_engine_registry(eng), o.delegate,
o.prompt);
else if (o.a2a_ip != NULL) {
rc = sp_a2a_serve(sp_engine_agent(eng), o.a2a_ip, o.a2a_port,
&err);
if (rc != 0)
fprintf(stderr, "splinter: %s\n",
err.len > 0 ? err.p : "A2A server failed");
rc = rc == 0 ? 0 : 1;
} else if (o.mcp_ip != NULL) {
rc = sp_mcp_serve(&reg, o.mcp_ip, o.mcp_port, cfg.autonomous == 1,
&err);
rc = sp_mcp_serve(sp_engine_registry(eng), o.mcp_ip,
o.mcp_port, cfg.autonomous == 1, &err);
if (rc != 0)
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(&ag, &cfg, host, &sess, &conf, &err);
else if (o.chat) {
if (!sp_profile_exists(sess.dir))
rc = run_daemon(eng, &err);
else if (o.serve) {
rc = sp_proto_serve(eng, o.socket, &err);
if (rc != 0)
fprintf(stderr, "splinter: %s\n",
err.len > 0 ? err.p : "protocol server failed");
rc = rc == 0 ? 0 : 1;
} 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",
sp_memory_user());
{
struct swarm sw;
char cwd[512];
if (getcwd(cwd, sizeof(cwd)) == NULL) cwd[0] = '\0';
swarm_init(&sw, cwd);
rc = sp_ui_run(&ag, o.endpoint, o.model, o.theme, host, &sw, &conf);
swarm_close(&sw);
}
} else if (o.prompt != NULL && o.prompt[0] == '/' && host != NULL)
rc = run_slash_prompt(host, o.prompt);
rc = sp_ui_run(sp_ui_backend_engine(eng), o.theme);
} else if (o.prompt != NULL &&
(o.prompt[0] == '/' || o.prompt[0] == '!'))
rc = run_slash_prompt(eng, o.prompt);
else
rc = run_prompt(&ag, &cfg, o.prompt, o.no_stream, &err);
rc = run_prompt(eng, o.prompt, o.no_stream, &err);
cleanup:
if (have_mock)
sp_mock_free(&mock);
sp_host_free(host);
sp_engine_close(eng);
sp_buf_free(&err);
sp_registry_free(&reg);
return rc;
}
-3663
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/sh
# splinter -- the A2A streaming transport, driven through the curses UI.
#
# The UI is the only path that turns streaming on (src/ui.c sets cfg.stream),
# The engine turns streaming on for a front end that can take it,
# so this is where SendStreamingMessage is exercised: artifact chunks arrive
# live, the final status note is not appended to them, and a stream whose only
# answer is the final status message still produces text.
+132
View File
@@ -0,0 +1,132 @@
#!/bin/sh
#
# splinter -- the curses front end attached to a served engine.
#
# What it guards: --attach is a protocol client, not a second engine. The
# screen shows the server's session (not one of its own), a prompt runs on the
# server, /status answers with the server's numbers, Tab switches the server's
# agent profile, and Ctrl-D ends the client while the server keeps serving.
set -u
cd "$(dirname "$0")/.." || exit 1
if ! command -v tmux >/dev/null 2>&1; then
echo "test_attach: skipped (no tmux)"
exit 0
fi
D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-attach-XXXXXX") || exit 1
unset TMUX TMUX_PANE
export TMUX_TMPDIR="$D"
own_server() {
if [ -n "${TMUX:-}" ] || [ "${TMUX_TMPDIR:-}" != "$D" ]; then
echo "test_attach: 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-attach-$$
P=$((20000 + ($$ + 7) % 30000))
F=
G=
fails=0
cleanup() {
killserver
[ -n "$F" ] && kill "$F" 2>/dev/null
[ -n "$G" ] && kill "$G" 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() { # the turn is over when the prompt says build>
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 "$@"; }
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=$!
for i in $(seq 1 60); do
curl -s -o /dev/null "http://127.0.0.1:$P/x" && break
sleep 0.2
done
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" > "$D/serve.log" 2>&1 &
G=$!
for i in $(seq 1 60); do
[ -S "$D/sock" ] && break
sleep 0.2
done
if [ ! -S "$D/sock" ]; then
echo "FAIL the server has no socket"
cat "$D/serve.log"
exit 1
fi
# a turn before the attach: the client must see it in the transcript
HOME=$D/server SPLINTER_LOCALE=en ./splinterctl --socket "$D/sock" \
--say "fruehere frage" > "$D/say-before.txt" 2>/dev/null
check grep -q 'fertig' "$D/say-before.txt"
# the server chooses the session; the client must show it, not one of its own
HOME=$D/server SPLINTER_LOCALE=en ./splinterctl --socket "$D/sock" \
--cmd /status > "$D/status.txt" 2>/dev/null
sess=$(sed -n 's/^ session //p' "$D/status.txt" | 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"
check shows 'fruehere frage'
check shows 'fertig'
typed 'single word ok'; key Enter
check idle_prompt
check shows '<m> ok'
check shows "$sess"
typed '/status'; key Enter
check shows 'status ('
check shows "$sess"
# Tab switches the profile in the engine, not in this process
key Tab
check shows 'agent: plan'
# Ctrl-D ends the client; the server must still be there
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 test -S "$D/sock"
check kill -0 "$G" 2>/dev/null
# no server: attach refuses with an error instead of pretending
HOME=$D/client SPLINTER_LOCALE=en ./splinter --no-config --attach \
--socket "$D/nosock" > /dev/null 2> "$D/err.txt"
check test $? -eq 3
check grep -q 'nosock' "$D/err.txt"
# --attach is the screen alone: a prompt or a server mode is a contradiction
HOME=$D/client SPLINTER_LOCALE=en ./splinter --no-config --attach \
--socket "$D/sock" -p hallo > /dev/null 2> "$D/conflict.txt"
check test $? -eq 2
check grep -q 'screen alone' "$D/conflict.txt"
if [ "$fails" -eq 0 ]; then
echo "test_attach: ok"
exit 0
fi
exit 1
+295
View File
@@ -0,0 +1,295 @@
/*
* splinter -- the engine a front end talks to: one scripted turn, no screen.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* What it guards: the event queue carries a whole turn in order (busy, the
* streamed text, the step, the call, its observation, the answer, idle); the
* commands answer through sp_engine_input without touching an agent; a shell
* line becomes an entry; the shared call/observation shaping reads the way the
* transcript does; and closing the engine frees the turn it ran.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "splinter.h"
#include "splinter_engine.h"
#include "config.h"
#include "i18n.h"
static int failures;
#define CHECK(cond) do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \
#cond); \
failures++; \
} \
} while (0)
static int
contains(const char *hay, const char *needle)
{
return hay != NULL && strstr(hay, needle) != NULL;
}
/* the whole turn, by draining the queue until the engine says idle */
static void
run_turn(struct sp_engine *eng)
{
struct sp_event ev;
int saw_busy_on = 0, saw_stream = 0, saw_step = 0;
int saw_tool = 0, saw_result = 0, saw_turn = 0;
int saw_busy_off = 0;
int rc = -1;
char answer[256] = "";
char tool[64] = "";
int guard = 0;
CHECK(sp_engine_submit(eng, "sag hallo") == 0);
while (guard++ < 500) {
while (sp_engine_poll(eng, &ev)) {
switch (ev.kind) {
case SP_EV_BUSY:
if (ev.n != 0)
saw_busy_on = 1;
else
saw_busy_off = 1;
break;
case SP_EV_STREAM:
if (ev.n == SP_STREAM_TEXT)
saw_stream = 1;
break;
case SP_EV_STEP:
saw_step = 1;
break;
case SP_EV_TOOL:
saw_tool = 1;
snprintf(tool, sizeof(tool), "%s",
ev.a != NULL ? ev.a : "");
break;
case SP_EV_TOOL_RESULT:
saw_result = 1;
break;
case SP_EV_TURN_END:
saw_turn = 1;
rc = (int)ev.n;
snprintf(answer, sizeof(answer), "%s",
ev.a != NULL ? ev.a : "");
break;
default:
break;
}
sp_engine_event_free(&ev);
}
if (!sp_engine_busy(eng) && saw_busy_off)
break;
{
struct timespec ts = { 0, 10000000L };
nanosleep(&ts, NULL);
}
}
(void)sp_engine_wait(eng);
CHECK(saw_busy_on);
/* the mock transport cannot stream; it is not the engine's job to fake it */
(void)saw_stream;
CHECK(saw_step);
CHECK(saw_tool);
CHECK(strcmp(tool, "echo") == 0);
CHECK(saw_result);
CHECK(saw_turn);
CHECK(rc == 0);
CHECK(strcmp(answer, "fertig") == 0);
CHECK(saw_busy_off);
}
int
main(void)
{
struct sp_config conf;
struct sp_agent_config base;
struct sp_engine_opts opts;
struct sp_engine *eng = NULL;
struct sp_buf err, out;
char tmpl[512], script[600], path[700], logpath[760];
char *dir;
const char *tmp = getenv("TMPDIR");
FILE *f;
char call[256];
int kind;
if (tmp == NULL || *tmp == '\0')
tmp = "/tmp";
snprintf(tmpl, sizeof(tmpl), "%s/splinter-engine-XXXXXX", tmp);
dir = mkdtemp(tmpl);
if (dir == NULL) {
perror("mkdtemp");
return 1;
}
(void)snprintf(script, sizeof(script), "%s/script.txt", dir);
snprintf(path, sizeof(path), "%s/.splinter", dir);
(void)mkdir(path, 0700);
f = fopen(script, "w");
if (f == NULL) {
perror("script");
return 1;
}
/* one call, then the answer; the mock replays one line per request */
fprintf(f, "tool echo {\"text\":\"hallo-welt\"}\n");
fprintf(f, "answer fertig\n");
fclose(f);
(void)setenv("HOME", dir, 1);
(void)sp_i18n_init("en");
if (sp_buf_init(&err) != 0 || sp_buf_init(&out) != 0)
return 1;
sp_config_init(&conf);
memset(&base, 0, sizeof(base));
base.max_steps = 10;
base.system_prompt = "test";
memset(&opts, 0, sizeof(opts));
opts.conf = &conf;
opts.base = &base;
opts.script = script;
opts.session_dir = path;
opts.session_id = "sess-engine";
opts.no_transport = 0;
if (sp_engine_open(&eng, &opts, &err) != 0) {
fprintf(stderr, "engine: %s\n", err.p != NULL ? err.p : "?");
return 1;
}
run_turn(eng);
kind = sp_engine_input(eng, "/status", &out);
CHECK(kind == SP_INPUT_HANDLED);
CHECK(contains(out.p, "session sess-engine"));
CHECK(contains(out.p, "agent build"));
sp_buf_clear(&out);
kind = sp_engine_input(eng, "/no-such-command", &out);
CHECK(kind == SP_INPUT_HANDLED);
CHECK(contains(out.p, "/no-such-command"));
sp_buf_clear(&out);
/*
* /new drops the conversation, not the way of working: the active
* profile's prompt goes back on top, and the new session gets an id of
* its own even when two /new happen in the same second.
*/
{
int i, n = sp_engine_agents(eng), plan = -1;
char id1[64] = "", id2[64] = "";
for (i = 0; i < n; i++)
if (strcmp(sp_engine_agent_name(eng, i), "plan") == 0)
plan = i;
CHECK(plan >= 0);
CHECK(sp_engine_agent_switch(eng, plan) == 0);
CHECK(sp_engine_input(eng, "/new", &out) == SP_INPUT_HANDLED);
CHECK(contains(out.p, "sess-"));
snprintf(id1, sizeof(id1), "%s", out.p != NULL ? out.p : "");
/* "[agent: plan]" is the profile tag, in every language */
CHECK(sp_engine_conv(eng)->n > 0 &&
contains(sp_engine_conv(eng)->v[0].content,
"[agent: plan]"));
sp_buf_clear(&out);
CHECK(sp_engine_input(eng, "/new", &out) == SP_INPUT_HANDLED);
snprintf(id2, sizeof(id2), "%s", out.p != NULL ? out.p : "");
CHECK(strcmp(id1, id2) != 0);
CHECK(sp_engine_conv(eng)->n > 0 &&
contains(sp_engine_conv(eng)->v[0].content,
"[agent: plan]"));
sp_buf_clear(&out);
}
/* a shell line is an entry event, not a reply */
kind = sp_engine_input(eng, "!echo shell-out", &out);
CHECK(kind == SP_INPUT_HANDLED);
{
int got = 0;
struct sp_event ev;
while (sp_engine_poll(eng, &ev)) {
if (ev.kind == SP_EV_ENTRY && ev.a != NULL &&
strcmp(ev.a, "shell") == 0 &&
contains(ev.b, "shell-out"))
got = 1;
sp_engine_event_free(&ev);
}
CHECK(got);
}
sp_buf_clear(&out);
/* the session log is on disk, one JSON object per line */
snprintf(logpath, sizeof(logpath), "%s/sess-engine.jsonl",
opts.session_dir);
CHECK(access(logpath, R_OK) == 0);
/*
* The session remembers the profile: a new engine on the same session
* starts in plan again, and the profile prompt appears once, not twice.
*/
{
char sess[64], sdir[512];
struct sp_engine *eng2 = NULL;
int plan2 = -1, i, n2, marks = 0;
const char *sys;
snprintf(sess, sizeof(sess), "%s", sp_engine_session_id(eng));
snprintf(sdir, sizeof(sdir), "%s", sp_engine_state_dir(eng));
sp_engine_close(eng);
eng = NULL;
opts.session_id = sess;
opts.session_dir = sdir;
opts.resume = 1;
opts.agent = NULL;
CHECK(sp_engine_open(&eng2, &opts, &err) == 0);
n2 = sp_engine_agents(eng2);
for (i = 0; i < n2; i++)
if (strcmp(sp_engine_agent_name(eng2, i), "plan") == 0)
plan2 = i;
CHECK(plan2 >= 0);
CHECK(sp_engine_agent_cur(eng2) == plan2);
sys = sp_engine_conv(eng2)->n > 0 ?
sp_engine_conv(eng2)->v[0].content : "";
for (i = 0; sys != NULL && (sys = strstr(sys, "[agent: plan]"))
!= NULL; i++, sys++)
marks = i + 1;
CHECK(marks == 1);
CHECK(sp_engine_take_steer(eng2, &out) == 0);
sp_buf_clear(&out);
sp_engine_close(eng2);
eng = eng2;
}
/* the shaping both front ends print */
sp_call_summary("run", "{\"command\":\"ls -l\"}", call, sizeof(call));
CHECK(strcmp(call, "Run ls -l") == 0);
sp_call_summary("read", "{\"path\":\"src/x.c\",\"limit\":10}", call,
sizeof(call));
CHECK(strcmp(call, "Read src/x.c") == 0);
sp_buf_clear(&out);
CHECK(sp_obs_short("[exit status 0]", &out) == SP_OBS_JOIN);
CHECK(strcmp(out.p, "[exit status 0]") == 0);
sp_buf_clear(&out);
CHECK(sp_obs_short("", &out) == SP_OBS_NONE);
sp_buf_free(&out);
sp_buf_free(&err);
(void)unlink(script);
(void)rmdir(path);
(void)rmdir(dir);
if (failures == 0) {
printf("test_engine: ok\n");
return 0;
}
return 1;
}
+13 -3
View File
@@ -75,7 +75,8 @@ check "the no is acknowledged" grep -q '^Abgelehnt' "$D/sent.log"
check "the tool did not run after the no" test ! -e "$D/out.txt"
# a program in commands/ answers in the chat, without a model turn
run_text() { # $1 = first message, $2 = line to wait for
run_text() { # $1 = first message, $2 = line to wait for, $3 = port offset,
# $4 = a line that must appear too before the fake is killed
P=$((20000 + ($$ + ${3:-0}) % 30000))
rm -rf "$D/home" "$D/out.txt" "$D/sent.log"
mkdir -p "$D/home/.splinter/commands"
@@ -98,8 +99,17 @@ run_text() { # $1 = first message, $2 = line to wait for
./splinter --config "$D/home/splinter.conf" --daemon \
> "$D/gw.out" 2>&1 &
G=$!
# The fake is killed once the marker showed up - so a check that reads a
# line sent *after* it has to name that line here, or the kill wins the
# race (/model: the switch is confirmed, then the next turn's error is
# sent; killing at the confirmation dropped it).
for i in $(seq 1 120); do
grep -q "$2" "$D/sent.log" 2>/dev/null && break
if grep -q "$2" "$D/sent.log" 2>/dev/null; then
if [ -z "${4:-}" ] ||
grep -q "$4" "$D/sent.log" 2>/dev/null; then
break
fi
fi
sleep 0.5
done
kill "$G" "$S" 2>/dev/null
@@ -163,7 +173,7 @@ check "the bot says the new session" grep -q '^Neue Konversation: sess-' "$D/sen
check "a session file was opened" sh -c "ls '$D'/home/.splinter/sess-*.jsonl | tail -1 | grep -q sess-"
# /model offers the configured models and switches on the button
run_text "/model" 'Provider far' 60
run_text "/model" 'Provider far' 60 '^openai:'
check "the model menu lists the configured providers" \
grep -q '"callback_data":"model:far"' "$D/sent.log"
check "the model menu shows the models" grep -q 'far other' "$D/sent.log"
+261
View File
@@ -0,0 +1,261 @@
#!/bin/sh
#
# splinter -- the line protocol: a served engine, driven without a screen.
#
# What it guards: the greeting names the protocol version and the session; a
# prompt produces submitted/stream/tool/tool_result/turn; a slash command
# answers with a reply and does not start a turn; an approval is a question the
# client answers (yes runs the tool, no denies it and nothing is written); the
# reference client speaks it; quit closes the server.
set -u
cd "$(dirname "$0")/.." || exit 1
D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-proto-XXXXXX") || exit 1
P1=$((20000 + $$ % 20000))
P2=$((40000 + $$ % 20000))
F1=
F2=
S1=
S2=
fails=0
cleanup() {
[ -n "$S1" ] && kill "$S1" 2>/dev/null
[ -n "$S2" ] && kill "$S2" 2>/dev/null
[ -n "$F1" ] && kill "$F1" 2>/dev/null
[ -n "$F2" ] && kill "$F2" 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" ] && cat "$2"
fails=$((fails + 1))
fi
}
wait_for() { # path, tries
i=0
while [ "$i" -lt "$2" ]; do
[ -e "$1" ] && return 0
i=$((i + 1))
sleep 0.2
done
return 1
}
mkdir -p "$D/home"
python3 -I tests/fake_telegram.py "$P1" "$D/out.txt" "$D/sent.log" ok \
> "$D/fake.out" 2>&1 &
F1=$!
sleep 0.8
HOME=$D/home SPLINTER_LOCALE=en ./splinter --no-config --autonomous \
--endpoint "http://127.0.0.1:$P1/v1/chat/completions" --model m \
--serve --socket "$D/sock" > "$D/serve.out" 2>&1 &
S1=$!
if ! wait_for "$D/sock" 20; then
echo "FAIL the server never created its socket"
cat "$D/serve.out"
exit 1
fi
# a second server on the same socket must refuse to start
HOME=$D/home SPLINTER_LOCALE=en ./splinter --no-config --autonomous \
--endpoint "http://127.0.0.1:$P1/v1/chat/completions" --model m \
--serve --socket "$D/sock" > "$D/second.out" 2>&1
if [ $? -eq 0 ]; then
echo "FAIL a second server on the same socket started"
fails=$((fails + 1))
fi
checkgrep 'already being served' "$D/second.out"
HOME=$D/home SPLINTER_LOCALE=en ./splinterctl --socket "$D/sock" \
--cmd /status > "$D/alive.out" 2>/dev/null
checkgrep 'session' "$D/alive.out"
# ---------------------------------------------- the events, as JSON lines
# The first turn of this conversation: the fake asks for a tool, runs it and
# answers. This is the shape a GUI draws.
python3 - "$D/sock" > "$D/events.out" 2> "$D/events.err" <<'PY'
import json, socket, sys
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(sys.argv[1])
f = s.makefile("rw", encoding="utf-8")
seen = []
while "state" not in seen:
ev = json.loads(f.readline())
seen.append(ev.get("ev"))
if ev.get("ev") == "ready" and ev.get("protocol") != 2:
print("bad protocol", ev, file=sys.stderr)
sys.exit(1)
if ev.get("ev") == "state" and not ev.get("session"):
print("state without a session", ev, file=sys.stderr)
sys.exit(1)
f.write(json.dumps({"cmd": "commands"}) + "\n")
f.flush()
while True:
ev = json.loads(f.readline())
if ev.get("ev") == "commands":
if "model" not in ev.get("names", []) or "status" not in ev.get("names", []):
print("commands incomplete", ev, file=sys.stderr)
sys.exit(1)
seen.append("commands")
break
f.write(json.dumps({"cmd": "say", "text": "hallo"}) + "\n")
f.flush()
while True:
ev = json.loads(f.readline())
seen.append(ev.get("ev"))
if ev.get("ev") == "turn":
if not ev.get("ok"):
print("turn failed", ev, file=sys.stderr)
sys.exit(1)
answer = ev.get("answer", "")
break
print("events " + " ".join(seen))
print("answer " + answer)
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_ok" if "hallo" in texts else "history_missing")
break
# a shell entry bigger than any fixed 8 KiB line buffer: the client must
# receive the whole JSON line, not a truncated one it cannot parse
f.write(json.dumps({"cmd": "input", "line": "!seq 1 3000"}) + "\n")
f.flush()
big = 0
while True:
ev = json.loads(f.readline())
if ev.get("ev") == "entry" and ev.get("role") == "shell":
big = len(ev.get("text", ""))
if ev.get("ev") == "reply":
break
print("shell_bytes %d" % big)
# and a prompt longer than 8 KiB
f.write(json.dumps({"cmd": "say", "text": "x" * 9000}) + "\n")
f.flush()
while True:
ev = json.loads(f.readline())
if ev.get("ev") == "turn":
print("long_prompt_ok" if ev.get("ok") else "long_prompt_failed")
break
PY
checkgrep 'ready' "$D/events.out"
checkgrep 'state' "$D/events.out"
checkgrep 'submitted' "$D/events.out"
checkgrep 'tool ' "$D/events.out"
checkgrep 'tool_result' "$D/events.out"
checkgrep 'turn' "$D/events.out"
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 'answer fertig' "$D/events.out"
check grep -q 'vom gateway' "$D/out.txt"
# --------------------------------------------------- the reference client
HOME=$D/home SPLINTER_LOCALE=en ./splinterctl --socket "$D/sock" \
--say "hallo" > "$D/say.out" 2> "$D/say.err"
check grep -q 'fertig' "$D/say.out"
HOME=$D/home SPLINTER_LOCALE=en ./splinterctl --socket "$D/sock" \
--cmd /status > "$D/status.out" 2>/dev/null
checkgrep 'session' "$D/status.out"
checkgrep 'model m' "$D/status.out"
HOME=$D/home SPLINTER_LOCALE=en ./splinterctl --socket "$D/sock" \
--cmd /model > "$D/model.out" 2>/dev/null
checkgrep 'main m' "$D/model.out"
# ------------------------------------------------- an approval is a question
[ -n "$S1" ] && kill "$S1" 2>/dev/null
S1=
sleep 0.3
rm -f "$D/sock"
mkdir -p "$D/home2"
python3 -I tests/fake_telegram.py "$P2" "$D/denied.txt" "$D/sent2.log" ok \
> "$D/fake2.out" 2>&1 &
F2=$!
sleep 0.8
HOME=$D/home2 SPLINTER_LOCALE=en ./splinter --no-config \
--endpoint "http://127.0.0.1:$P2/v1/chat/completions" --model m \
--serve --socket "$D/sock2" > "$D/serve2.out" 2>&1 &
S2=$!
if ! wait_for "$D/sock2" 20; then
echo "FAIL the second server never created its socket"
cat "$D/serve2.out"
exit 1
fi
python3 - "$D/sock2" > "$D/deny.out" 2> "$D/deny.err" <<'PY'
import json, socket, sys
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(sys.argv[1])
f = s.makefile("rw", encoding="utf-8")
while True:
ev = json.loads(f.readline())
if ev.get("ev") == "state":
break
f.write(json.dumps({"cmd": "say", "text": "schreib"}) + "\n")
f.flush()
asked = False
while True:
ev = json.loads(f.readline())
if ev.get("ev") == "approval":
asked = True
f.write(json.dumps({"cmd": "approve", "allow": False}) + "\n")
f.flush()
if ev.get("ev") == "turn":
print("asked" if asked else "no question")
print("ok" if ev.get("ok") else "failed")
break
PY
checkgrep 'asked' "$D/deny.out"
checkgrep 'ok' "$D/deny.out"
# the denial is the observation: the tool never ran
check test ! -e "$D/denied.txt"
# ------------------------------------------------------------------- quit
python3 - "$D/sock2" <<'PY'
import json, socket, sys
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(sys.argv[1])
f = s.makefile("rw", encoding="utf-8")
while True:
ev = json.loads(f.readline())
if ev.get("ev") == "state":
break
f.write(json.dumps({"cmd": "quit"}) + "\n")
f.flush()
for line in f:
ev = json.loads(line)
if ev.get("ev") == "quit":
sys.exit(0)
sys.exit(1)
PY
if [ $? -ne 0 ]; then
echo "FAIL quit did not answer with a quit event"
fails=$((fails + 1))
fi
i=0
while kill -0 "$S2" 2>/dev/null && [ "$i" -lt 25 ]; do
i=$((i + 1))
sleep 0.2
done
check test ! -S "$D/sock2"
if [ "$fails" -eq 0 ]; then
echo "test_protocol: ok"
exit 0
fi
exit 1
+19 -2
View File
@@ -41,6 +41,7 @@ main(void)
CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"content\":"
"\"Hal\"}}]}\n", &out, &err) == 1);
CHECK(strcmp(out.p, "Hal") == 0);
CHECK(sp_sse_kind(s) == SP_STREAM_TEXT);
sp_buf_clear(&out);
CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"content\":"
"\"lo\"}}]}\n", &out, &err) == 1);
@@ -53,15 +54,31 @@ main(void)
CHECK(r.ncalls == 0);
CHECK(r.calls_json == NULL);
sp_reply_free(&r);
/* ---- reasoning is its own kind, never the answer ---- */
sp_buf_clear(&out);
CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{"
"\"reasoning_content\":\"hmm\"}}]}\n", &out, &err) == 1);
CHECK(strcmp(out.p, "hmm") == 0);
CHECK(sp_sse_kind(s) == SP_STREAM_THINK);
sp_sse_free(s);
/* ---- a tool call in pieces, the way OpenAI sends them ---- */
/*
* ---- a tool call in pieces, the way OpenAI sends them ----
*
* With `"content":null` beside the call, which is the shape the provider
* actually sends. A transport that guessed "text" from the raw line put
* the tool's name into the answer - two read calls showed up as
* "<model> readread" - so the kind comes from the parser now.
*/
s = sp_sse_new();
sp_buf_clear(&out);
CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"tool_calls\":"
CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"content\":null,"
"\"tool_calls\":"
"[{\"index\":0,\"id\":\"call-a\",\"function\":{\"name\":\"echo\","
"\"arguments\":\"\"}}]}}]}\n", &out, &err) == 1);
CHECK(strcmp(out.p, "echo") == 0);
CHECK(sp_sse_kind(s) == SP_STREAM_TOOL);
CHECK(sp_sse_tool_start(s, 0) != NULL);
sp_buf_clear(&out);
CHECK(sp_sse_line(s, "data: {\"choices\":[{\"delta\":{\"tool_calls\":"
+6 -1
View File
@@ -57,7 +57,12 @@ main(void)
sp_usage_get("a", 10, 3600, 0, 0, &u);
CHECK(u.req_used == 4);
CHECK(u.frac > 0.39 && u.frac < 0.41);
CHECK(u.reset_at >= now + 3590 && u.reset_at <= now + 3601);
/*
* `now` was taken before the records. The assertion is "one window
* from now", not a stopwatch: on a loaded machine a few seconds pass
* between the two, and a one-second upper bound failed the suite.
*/
CHECK(u.reset_at >= now + 3590 && u.reset_at <= now + 3660);
sp_usage_get("a", 0, 0, 1000, 3600, &u);
CHECK(u.tok_used == 600);
CHECK(u.frac > 0.59 && u.frac < 0.61);
+5 -3
View File
@@ -14,7 +14,9 @@ KEY = re.compile(r'sp_td?\(\s*"([^"]+)"')
def used_keys():
keys = set()
for path in list(ROOT.glob("src/*.c")) + list(ROOT.glob("plugins/*/*.c")):
sources = list(ROOT.glob("src/**/*.c"))
sources += list(ROOT.glob("plugins/*/*.c"))
for path in sources:
keys.update(KEY.findall(path.read_text(encoding="utf-8", errors="replace")))
return keys
@@ -37,7 +39,7 @@ LITERAL_ARG = re.compile(r',\s*"([^"\\]*(?:\\.[^"\\]*)*)"')
def hardcoded():
bad = []
for path in list(ROOT.glob("src/*.c")):
for path in ROOT.glob("src/**/*.c"):
for no, line in enumerate(path.read_text(encoding="utf-8",
errors="replace").splitlines(), 1):
if not DRAW.search(line) or "sp_t" in line:
@@ -57,7 +59,7 @@ ALLOWED_ROLES = {"you", "agent", "thinking", "tool", "observation", "error",
def unknown_roles():
bad = []
for path in ROOT.glob("src/*.c"):
for path in ROOT.glob("src/**/*.c"):
for no, line in enumerate(path.read_text(encoding="utf-8",
errors="replace").splitlines(), 1):
for role in ROLE_CALL.findall(line):
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/sh
# Writes a C file holding the message catalogues, so a splinter that was copied
# somewhere (make install, a tarball) never shows raw keys like "ui.ready".
# usage: embed_catalogs.sh share/locale/*.msg > src/catalogs.c
# usage: embed_catalogs.sh share/locale/*.msg > src/backend/catalogs.c
echo '/* generated by tools/embed_catalogs.sh from share/locale -- do not edit */'
echo '#include "splinter.h"'; echo '#include "i18n.h"'
echo