diff --git a/.gitignore b/.gitignore index d60d237..a37f0e9 100644 --- a/.gitignore +++ b/.gitignore @@ -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/ diff --git a/Makefile b/Makefile index e868e22..7e17f42 100644 --- a/Makefile +++ b/Makefile @@ -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 diff --git a/README.md b/README.md index 1e93076..1f3a09f 100644 --- a/README.md +++ b/README.md @@ -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/.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 ` 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 `.agent`, so a session left in plan resumes +in plan. ## MCP diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md new file mode 100644 index 0000000..a4e39eb --- /dev/null +++ b/docs/FRONTENDS.md @@ -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. diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md new file mode 100644 index 0000000..5b918c6 --- /dev/null +++ b/docs/PROTOCOL.md @@ -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. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 2b30c08..b1b8700 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -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 + `.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 diff --git a/docs/proto-example.py b/docs/proto-example.py new file mode 100755 index 0000000..7cf270b --- /dev/null +++ b/docs/proto-example.py @@ -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()) diff --git a/docs/splinter.1 b/docs/splinter.1 index d55352c..2bb7044 100644 --- a/docs/splinter.1 +++ b/docs/splinter.1 @@ -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 request observe diff --git a/include/splinter.h b/include/splinter.h index ee1312c..f9a1c91 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -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 (" readread"). */ +int sp_sse_kind(const struct sp_sse *); /* * transport_anthropic.c -- the Anthropic Messages API, via curl(1). diff --git a/include/splinter_engine.h b/include/splinter_engine.h new file mode 100644 index 0000000..80edfa5 --- /dev/null +++ b/include/splinter_engine.h @@ -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 + +#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 */ diff --git a/share/locale/de.msg b/share/locale/de.msg index 6f67c37..8a1fe79 100644 --- a/share/locale/de.msg +++ b/share/locale/de.msg @@ -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 diff --git a/share/locale/en.msg b/share/locale/en.msg index 43e956e..5da0662 100644 --- a/share/locale/en.msg +++ b/share/locale/en.msg @@ -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 diff --git a/share/locale/pt_BR.msg b/share/locale/pt_BR.msg index 586a219..8ac24d8 100644 --- a/share/locale/pt_BR.msg +++ b/share/locale/pt_BR.msg @@ -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 diff --git a/src/a2aserver.c b/src/backend/a2aserver.c similarity index 100% rename from src/a2aserver.c rename to src/backend/a2aserver.c diff --git a/src/a2aserver.h b/src/backend/a2aserver.h similarity index 100% rename from src/a2aserver.h rename to src/backend/a2aserver.h diff --git a/src/ack.c b/src/backend/ack.c similarity index 100% rename from src/ack.c rename to src/backend/ack.c diff --git a/src/ack.h b/src/backend/ack.h similarity index 100% rename from src/ack.h rename to src/backend/ack.h diff --git a/src/agent.c b/src/backend/agent.c similarity index 100% rename from src/agent.c rename to src/backend/agent.c diff --git a/src/agents.c b/src/backend/agents.c similarity index 100% rename from src/agents.c rename to src/backend/agents.c diff --git a/src/agents.h b/src/backend/agents.h similarity index 100% rename from src/agents.h rename to src/backend/agents.h diff --git a/src/anthropic.c b/src/backend/anthropic.c similarity index 100% rename from src/anthropic.c rename to src/backend/anthropic.c diff --git a/src/b64.c b/src/backend/b64.c similarity index 100% rename from src/b64.c rename to src/backend/b64.c diff --git a/src/b64.h b/src/backend/b64.h similarity index 100% rename from src/b64.h rename to src/backend/b64.h diff --git a/src/buf.c b/src/backend/buf.c similarity index 100% rename from src/buf.c rename to src/backend/buf.c diff --git a/src/builtin.c b/src/backend/builtin.c similarity index 100% rename from src/builtin.c rename to src/backend/builtin.c diff --git a/src/cmdscript.c b/src/backend/cmdscript.c similarity index 100% rename from src/cmdscript.c rename to src/backend/cmdscript.c diff --git a/src/cmdscript.h b/src/backend/cmdscript.h similarity index 100% rename from src/cmdscript.h rename to src/backend/cmdscript.h diff --git a/src/confblock.c b/src/backend/confblock.c similarity index 100% rename from src/confblock.c rename to src/backend/confblock.c diff --git a/src/confblock.h b/src/backend/confblock.h similarity index 100% rename from src/confblock.h rename to src/backend/confblock.h diff --git a/src/config.c b/src/backend/config.c similarity index 100% rename from src/config.c rename to src/backend/config.c diff --git a/src/config.h b/src/backend/config.h similarity index 100% rename from src/config.h rename to src/backend/config.h diff --git a/src/conv.c b/src/backend/conv.c similarity index 100% rename from src/conv.c rename to src/backend/conv.c diff --git a/src/curl.c b/src/backend/curl.c similarity index 100% rename from src/curl.c rename to src/backend/curl.c diff --git a/src/curl.h b/src/backend/curl.h similarity index 100% rename from src/curl.h rename to src/backend/curl.h diff --git a/src/decomp.c b/src/backend/decomp.c similarity index 100% rename from src/decomp.c rename to src/backend/decomp.c diff --git a/src/decomp.h b/src/backend/decomp.h similarity index 100% rename from src/decomp.h rename to src/backend/decomp.h diff --git a/src/delegate.c b/src/backend/delegate.c similarity index 100% rename from src/delegate.c rename to src/backend/delegate.c diff --git a/src/backend/engine.c b/src/backend/engine.c new file mode 100644 index 0000000..dc3175d --- /dev/null +++ b/src/backend/engine.c @@ -0,0 +1,2268 @@ +/* + * splinter -- the engine every front end talks to. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + * + * The code in here used to live in two places that could not see each other: + * main.c built the agent, and src/ui.c ran it -- with the curses thread model, + * the approval condition variable, the slash commands and the provider + * switching all inside the drawing code. A second front end had to copy all of + * it, and the gateway had already started to. + * + * Now the engine owns the moving parts and publishes events; the front end + * owns a screen and a keyboard. Nothing in this file knows what a WINDOW is, + * and no front end has to know how a turn is started or cancelled. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "splinter.h" +#include "splinter_engine.h" +#include "splinter_plugin.h" +#include "agents.h" +#include "cmdscript.h" +#include "config.h" +#include "folder.h" +#include "i18n.h" +#include "log.h" +#include "mcp.h" +#include "memory.h" +#include "prompt.h" +#include "providers.h" +#include "skills.h" +#include "swarm.h" +#include "usage.h" + +/* /connect: the questions, one answer per line */ +struct engine_cc { + int active; + int step; + char id[64]; + char endpoint[520]; + char model[260]; + char key_env[80]; +}; + +struct sp_engine { + /* what main handed over; conf is shared, not owned */ + struct sp_config *conf; + struct sp_agent_config base; + struct sp_agent ag; + struct sp_registry reg; + struct sp_session_info sess; + struct sp_conv conv; + struct sp_host *host; + struct sp_mock mock; + int have_mock; + + char prompt_expanded[8192]; + char cur_model[256]; + char cur_endpoint[512]; + char theme[48]; + char agent_name[48]; + char home_id[64]; /* provider before a profile moved it */ + + /* agent profiles: Tab switches through them */ + struct sp_agents agents; + int agent_cur; + struct sp_tool_policy policy; + char *base_prompt; + + /* /connect */ + struct engine_cc cc; + unsigned new_seq; /* /new count, for a unique id */ + int quit; + + /* the fleet, when asked for */ + struct swarm swarm; + int have_swarm; + + /* ------------------------------------------------------------- turn */ + pthread_mutex_t lock; + pthread_cond_t cond; + pthread_t th; + int have_thread; /* a thread exists and is joinable */ + int running; /* it has not finished yet */ + volatile int cancel; + char *turn_text; /* owned; the worker frees it */ + struct sp_agent_config turn_cfg; /* lives as long as the thread */ + struct sp_buf answer, err; + struct sp_buf live, think; /* the step being streamed */ + struct sp_buf steer; /* text typed during the turn */ + int have_steer; + size_t steers; + long max_wait; /* seconds, 0: 12 h */ + + /* the approval a tool is parked on */ + int approve_pending; + int approve_result; + char approve_name[64]; + char approve_args[256]; + int approve_auth; + + /* the last turn, for the sidebar and /status */ + size_t last_ms, last_steps, last_calls; + struct timespec turn_t0; + /* + * The agent's counters, copied on the thread that owns them (the turn + * worker or the synchronous caller) and read under e->lock. Reading + * ag.stats directly from a front-end thread was a data race. + */ + struct sp_agent_stats snapshot; + + /* events, in the order the turn produced them */ + struct sp_event *q; + size_t nq, capq; +}; + +/* --------------------------------------------------------------- events */ + +/* the caller holds e->lock */ +static void +ev_push_locked(struct sp_engine *e, int kind, long n, const char *a, + const char *b) +{ + struct sp_event *ev; + + if (e->nq == e->capq) { + size_t nc = e->capq != 0 ? e->capq * 2 : 64; + struct sp_event *nq = realloc(e->q, nc * sizeof(*nq)); + + if (nq == NULL) + return; + e->q = nq; + e->capq = nc; + } + ev = &e->q[e->nq++]; + ev->kind = kind; + ev->n = n; + ev->a = a != NULL ? strdup(a) : NULL; + ev->b = b != NULL ? strdup(b) : NULL; + if ((a != NULL && ev->a == NULL) || (b != NULL && ev->b == NULL)) { + free(ev->a); + free(ev->b); + e->nq--; + } +} + +static void +ev_push(struct sp_engine *e, int kind, long n, const char *a, const char *b) +{ + pthread_mutex_lock(&e->lock); + ev_push_locked(e, kind, n, a, b); + pthread_mutex_unlock(&e->lock); +} + +int +sp_engine_poll(struct sp_engine *e, struct sp_event *out) +{ + if (e == NULL || out == NULL) + return 0; + pthread_mutex_lock(&e->lock); + if (e->nq == 0) { + pthread_mutex_unlock(&e->lock); + return 0; + } + *out = e->q[0]; + memmove(&e->q[0], &e->q[1], (e->nq - 1) * sizeof(e->q[0])); + e->nq--; + pthread_mutex_unlock(&e->lock); + return 1; +} + +void +sp_engine_event_free(struct sp_event *ev) +{ + if (ev == NULL) + return; + free(ev->a); + free(ev->b); + ev->a = ev->b = NULL; + ev->kind = SP_EV_NONE; +} + +static void snapshot_stats(struct sp_engine *); + +/* ------------------------------------------------------------- snapshot */ + +int +sp_engine_state(struct sp_engine *e, struct sp_engine_state *st) +{ + if (e == NULL || st == NULL) + return -1; + memset(st, 0, sizeof(*st)); + snprintf(st->model, sizeof(st->model), "%s", e->cur_model); + snprintf(st->endpoint, sizeof(st->endpoint), "%s", e->cur_endpoint); + snprintf(st->agent, sizeof(st->agent), "%s", e->agent_name); + snprintf(st->session, sizeof(st->session), "%s", e->sess.id); + snprintf(st->dir, sizeof(st->dir), "%s", e->sess.dir); + snprintf(st->theme, sizeof(st->theme), "%s", e->theme); + pthread_mutex_lock(&e->lock); + st->tokens_in = e->snapshot.tokens_in; + st->tokens_out = e->snapshot.tokens_out; + st->steps = e->snapshot.steps; + st->calls = e->snapshot.tool_calls; + st->compactions = e->snapshot.compactions; + st->last_ms = e->last_ms; + st->last_steps = e->last_steps; + st->last_calls = e->last_calls; + st->busy = e->running; + st->quit = e->quit; + st->waiting = e->approve_pending; + st->agents_n = (int)e->agents.n; + st->agent_cur = e->agent_cur; + pthread_mutex_unlock(&e->lock); + return 0; +} + +/* ------------------------------------------------------------- accessors */ + +struct sp_agent *sp_engine_agent(struct sp_engine *e) { return &e->ag; } +struct sp_host *sp_engine_host(struct sp_engine *e) { return e->host; } +struct sp_config *sp_engine_config(struct sp_engine *e) { return e->conf; } +struct sp_registry *sp_engine_registry(struct sp_engine *e) { return &e->reg; } +struct swarm *sp_engine_swarm(struct sp_engine *e) { return e->have_swarm ? &e->swarm : NULL; } +const struct sp_conv *sp_engine_conv(struct sp_engine *e) { return &e->conv; } + +void +sp_engine_set_theme(struct sp_engine *e, const char *name) +{ + if (e == NULL) + return; + snprintf(e->theme, sizeof(e->theme), "%s", name != NULL ? name : ""); +} + +void +sp_engine_set_stream(struct sp_engine *e, sp_stream_cb cb, void *ctx) +{ + if (e == NULL) + return; + e->base.stream = cb; + e->base.stream_ctx = ctx; +} + +const char * +sp_engine_state_dir(struct sp_engine *e) { return e->sess.dir; } + +/* /.agent: the profile a session was left in */ +static void +profile_path(struct sp_engine *e, char *buf, size_t cap) +{ + snprintf(buf, cap, "%s/%s.agent", e->sess.dir, e->sess.id); +} + +static void +profile_save(struct sp_engine *e) +{ + char path[700]; + FILE *f; + + if (e->agent_name[0] == '\0') + return; + profile_path(e, path, sizeof(path)); + f = fopen(path, "w"); + if (f == NULL) + return; + fprintf(f, "%s\n", e->agent_name); + fclose(f); + (void)chmod(path, 0600); +} + +static int +profile_load(struct sp_engine *e, char *buf, size_t cap) +{ + char path[700], line[64]; + FILE *f; + + profile_path(e, path, sizeof(path)); + f = fopen(path, "r"); + if (f == NULL) + return 0; + if (fgets(line, sizeof(line), f) == NULL) { + fclose(f); + return 0; + } + fclose(f); + line[strcspn(line, "\r\n")] = '\0'; + if (line[0] == '\0') + return 0; + snprintf(buf, cap, "%.47s", line); + return 1; +} + +const char * +sp_engine_session_id(struct sp_engine *e) { return e->sess.id; } + +int +sp_engine_agents(struct sp_engine *e) { return (int)e->agents.n; } + +int +sp_engine_agent_cur(struct sp_engine *e) { return e->agent_cur; } + +const char * +sp_engine_agent_name(struct sp_engine *e, int idx) +{ + if (e == NULL || idx < 0 || (size_t)idx >= e->agents.n) + return ""; + return e->agents.v[idx].name; +} + +/* ------------------------------------------------------------ formatting */ + +/* + * A tool call as a person reads it. The model sends {"command":"ls 2\u003e\u00261"}; + * what belongs on the screen is command: ls 2>&1 . Strings are unescaped, + * numbers and booleans kept, anything nested is left as it came. + * + * Kept in the engine, not in a front end: the transcript row, the approval + * question and a GUI's call list must all name the same call the same way. + */ +static void +pretty_args(const char *json, char *out, size_t cap) +{ + const char *p = json; + size_t n = 0; + int first = 1; + + out[0] = '\0'; + while (*p == ' ') + p++; + if (*p != '{') { + snprintf(out, cap, "%s", json); + return; + } + p++; + while (*p != '\0' && *p != '}' && n + 8 < cap) { + char key[48]; + size_t k = 0; + + while (*p == ' ' || *p == ',') + p++; + if (*p != '"') + break; + p++; + while (*p != '\0' && *p != '"' && k + 1 < sizeof(key)) + key[k++] = *p++; + key[k] = '\0'; + if (*p == '"') + p++; + while (*p == ' ' || *p == ':') + p++; + if (!first) + n += (size_t)snprintf(out + n, cap - n, " "); + first = 0; + n += (size_t)snprintf(out + n, cap - n, "%s: ", key); + if (*p == '"') { + p++; + while (*p != '\0' && *p != '"' && n + 4 < cap) { + if (*p == '\\' && p[1] != '\0') { + p++; + if (*p == 'n') { + out[n++] = ' '; + } else if (*p == 't') { + out[n++] = ' '; + } else if (*p == 'u' && strlen(p) >= 5) { + unsigned cp = 0; + int i; + + for (i = 1; i <= 4; i++) { + char c = p[i]; + + cp = cp * 16 + (unsigned)(c >= 'a' ? + c - 'a' + 10 : c >= 'A' ? + c - 'A' + 10 : c - '0'); + } + p += 4; + if (cp < 0x80) + out[n++] = (char)cp; + else if (cp < 0x800) { + out[n++] = (char)(0xc0 | (cp >> 6)); + out[n++] = (char)(0x80 | (cp & 0x3f)); + } else { + out[n++] = (char)(0xe0 | (cp >> 12)); + out[n++] = (char)(0x80 | ((cp >> 6) & 0x3f)); + out[n++] = (char)(0x80 | (cp & 0x3f)); + } + } else + out[n++] = *p; + p++; + continue; + } + out[n++] = *p++; + } + if (*p == '"') + p++; + } else { + /* a number, a boolean, an object: as it is, up to the next key */ + int depth = 0; + + while (*p != '\0' && n + 4 < cap) { + if (*p == '{' || *p == '[') + depth++; + else if (*p == '}' || *p == ']') { + if (depth == 0) + break; + depth--; + } else if (*p == ',' && depth == 0) + break; + out[n++] = *p++; + } + } + out[n] = '\0'; + } + out[n < cap ? n : cap - 1] = '\0'; +} + +/* + * The argument that says what a call is about, per tool: a shell call is its + * command, a read is its path. Once the verb has said "Run", the key in front + * of the value ("command: du -sh") only repeats the harness to itself. + */ +static const char * +primary_key(const char *name) +{ + static const struct { + const char *tool, *key; + } keys[] = { + { "run", "command" }, + { "read", "path" }, + { "write", "path" }, + { "edit", "path" }, + { "list", "path" }, + { "search", "pattern" }, + { "websearch", "query" }, + { "webfetch", "url" }, + { "echo", "text" }, + { "delegate", "task" }, + }; + size_t i; + + for (i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) + if (strcmp(name, keys[i].tool) == 0) + return keys[i].key; + return NULL; +} + +void +sp_call_summary(const char *name, const char *args, char *out, size_t cap) +{ + char detail[512] = ""; + const char *key; + size_t n; + + if (name == NULL) + name = "?"; + /* + * The value of the primary key, read out of the object instead of off + * the front of the pretty text: the model may order its arguments as it + * likes, and a "write" carries the whole file content next to the path. + * Everything else in the call is noise on one row. + */ + key = primary_key(name); + if (key != NULL && args != NULL && args[0] == '{') { + mcp_json *v = mcp_parse(args); + + if (v != NULL) { + const char *val = mcp_arg_string(v, key); + + if (val != NULL) + snprintf(detail, sizeof(detail), "%s", val); + mcp_json_free(v); + } + } + if (detail[0] == '\0') + pretty_args(args != NULL ? args : "", detail, sizeof(detail)); + snprintf(out, cap, "%s", name); + if (out[0] >= 'a' && out[0] <= 'z') + out[0] = (char)(out[0] - 'a' + 'A'); + n = strlen(out); + if (*detail != '\0' && n + 2 < cap) + snprintf(out + n, cap - n, " %s", detail); +} + +/* + * What the tool returned, shortened for a transcript. A full `run` can carry + * a 300 KB JSON dump; two limits, both about the screen: sixteen rows and + * four kilobytes. The whole observation is in the session log either way. + */ +#define OBS_ROWS 16 +#define OBS_BYTES 4096 + +int +sp_obs_short(const char *obs, struct sp_buf *out) +{ + size_t len, keep, rows, i, rest = 0; + + if (obs == NULL) + return SP_OBS_NONE; + while (*obs == '\n' || *obs == '\r') + obs++; + len = strlen(obs); + if (len == 0) + return SP_OBS_NONE; + while (len > 0 && (obs[len - 1] == '\n' || obs[len - 1] == '\r')) + len--; + /* + * A call that said nothing but how it ended belongs on the call row - + * + * >> Run mkdir -p build [exit status 0] + * + * instead of two rows for every quiet command. + */ + if (len >= 14 && len <= 32 && strncmp(obs, "[exit status ", 13) == 0 && + obs[len - 1] == ']' && memchr(obs, '\n', len) == NULL) { + sp_buf_clear(out); + if (sp_buf_add(out, obs, len) != 0) + return SP_OBS_NONE; + return SP_OBS_JOIN; + } + keep = len; + for (rows = 0, i = 0; i < len; i++) { + if (i >= OBS_BYTES || rows >= OBS_ROWS) { + keep = i; + break; + } + if (obs[i] == '\n') + rows++; + } + if (keep < len) { + /* a cut in the middle of a line is the byte limit talking */ + if (obs[keep] != '\n') { + size_t cut = keep; + + while (cut > 0 && obs[cut - 1] != '\n') + cut--; + if (cut > 0) + keep = cut; + } + for (i = keep; i < len; i++) + if (obs[i] == '\n') + rest++; + if (obs[len - 1] != '\n') + rest++; + } + sp_buf_clear(out); + if (sp_buf_add(out, obs, keep) != 0) + return SP_OBS_NONE; + if (keep < len && rest > 0) { + char mark[80]; + + snprintf(mark, sizeof(mark), sp_t("ui.more_lines"), rest); + if (sp_buf_printf(out, "\n%s", mark) != 0) + return SP_OBS_NONE; + } + return SP_OBS_SHOWN; +} + +/* the caller owns ag.stats; this is how it becomes readable elsewhere */ +static void +snapshot_stats(struct sp_engine *e) +{ + pthread_mutex_lock(&e->lock); + e->snapshot = e->ag.stats; + pthread_mutex_unlock(&e->lock); +} + +/* -------------------------------------------------------------- callbacks */ + +static void +engine_stream_cb(void *ctx, int kind, const char *text) +{ + struct sp_engine *e = ctx; + + if (text == NULL || *text == '\0') + return; + pthread_mutex_lock(&e->lock); + /* + * SP_STREAM_TOOL carries the name of a call that has begun, not text: + * showing it in the answer glued two calls' names together. The call row + * comes from tool_begin. + */ + if (kind == SP_STREAM_TEXT) + (void)sp_buf_puts(&e->live, text); + else if (kind == SP_STREAM_THINK) + (void)sp_buf_puts(&e->think, text); + pthread_mutex_unlock(&e->lock); + ev_push(e, SP_EV_STREAM, kind, text, NULL); +} + +static void +engine_tool_begin(void *ctx, const char *name, const char *args) +{ + struct sp_engine *e = ctx; + char *think = NULL, *live = NULL; + + if (name == NULL) + return; + /* + * The step is over as far as the screen is concerned: its reasoning and + * its answer go into the queue in that order, then the call itself, and + * the buffers start empty for the next step. + */ + /* + * The agent has counted this step by now; make it visible to the + * sidebar without touching ag.stats from a reader. + */ + snapshot_stats(e); + pthread_mutex_lock(&e->lock); + if (e->think.p != NULL && e->think.len > 0) + think = strdup(e->think.p); + if (e->live.p != NULL && e->live.len > 0) + live = strdup(e->live.p); + sp_buf_clear(&e->think); + sp_buf_clear(&e->live); + pthread_mutex_unlock(&e->lock); + /* + * One step event per call, even when the transport cannot stream: a + * client's step bookkeeping then has a single rule, and the UI's + * segment update with an empty text is a no-op anyway. + */ + ev_push(e, SP_EV_STEP, 0, think != NULL ? think : "", + live != NULL ? live : ""); + ev_push(e, SP_EV_TOOL, 0, name, args); + free(think); + free(live); +} + +static void +engine_tool_end(void *ctx, const char *name, const char *obs) +{ + struct sp_engine *e = ctx; + struct sp_buf short_obs; + int kind; + + if (sp_buf_init(&short_obs) != 0) + return; + kind = sp_obs_short(obs, &short_obs); + if (kind != SP_OBS_NONE) + ev_push(e, SP_EV_TOOL_RESULT, kind == SP_OBS_JOIN ? 1 : 0, + name, short_obs.p != NULL ? short_obs.p : ""); + sp_buf_free(&short_obs); +} + +/* + * A tool needs permission. The turn thread parks on the engine's condition + * variable; the front end asks the operator and calls sp_engine_approve(). + * Ctrl-C must work here too: the wait ends on cancel and the call is denied. + */ +static int +engine_approve(void *ctx, const char *name, int auth, const char *args) +{ + struct sp_engine *e = ctx; + int answer; + + pthread_mutex_lock(&e->lock); + snprintf(e->approve_name, sizeof(e->approve_name), "%s", + name != NULL ? name : "?"); + snprintf(e->approve_args, sizeof(e->approve_args), "%.200s", + args != NULL ? args : ""); + e->approve_auth = auth; + e->approve_result = 0; + e->approve_pending = 1; + pthread_mutex_unlock(&e->lock); + ev_push(e, SP_EV_APPROVAL, auth, e->approve_name, e->approve_args); + pthread_mutex_lock(&e->lock); + while (e->approve_pending && !e->cancel) + pthread_cond_wait(&e->cond, &e->lock); + answer = e->cancel ? 0 : e->approve_result; + e->approve_pending = 0; + pthread_mutex_unlock(&e->lock); + return answer; +} + +int +sp_engine_approval(struct sp_engine *e, char *name, size_t namelen, + int *auth, char *args, size_t argslen) +{ + int pending; + + if (e == NULL) + return 0; + pthread_mutex_lock(&e->lock); + pending = e->approve_pending; + if (pending) { + if (name != NULL && namelen > 0) + snprintf(name, namelen, "%s", e->approve_name); + if (args != NULL && argslen > 0) + snprintf(args, argslen, "%s", e->approve_args); + if (auth != NULL) + *auth = e->approve_auth; + } + pthread_mutex_unlock(&e->lock); + return pending; +} + +int +sp_engine_approve(struct sp_engine *e, int allow) +{ + int pending; + + if (e == NULL) + return 0; + pthread_mutex_lock(&e->lock); + pending = e->approve_pending; + if (pending) { + e->approve_pending = 0; + e->approve_result = allow != 0; + pthread_cond_broadcast(&e->cond); + } + pthread_mutex_unlock(&e->lock); + return pending; +} + +int +sp_engine_cancel(struct sp_engine *e) +{ + if (e == NULL) + return -1; + pthread_mutex_lock(&e->lock); + e->cancel = 1; + pthread_cond_broadcast(&e->cond); + pthread_mutex_unlock(&e->lock); + return 0; +} + +int +sp_engine_steer(struct sp_engine *e, const char *text) +{ + if (e == NULL || text == NULL || *text == '\0') + return -1; + pthread_mutex_lock(&e->lock); + if (!e->running) { + pthread_mutex_unlock(&e->lock); + return -1; + } + if (sp_buf_puts(&e->steer, text) != 0 || + sp_buf_puts(&e->steer, " ") != 0) { + pthread_mutex_unlock(&e->lock); + return -1; + } + e->have_steer = 1; + pthread_mutex_unlock(&e->lock); + return 0; +} + +int +sp_engine_take_steer(struct sp_engine *e, struct sp_buf *out) +{ + int took = 0; + + if (e == NULL || out == NULL) + return 0; + pthread_mutex_lock(&e->lock); + if (!e->running && e->have_steer) { + const char *p = e->steer.p; + size_t n = p != NULL ? strlen(p) : 0; + + while (n > 0 && (p[n - 1] == ' ' || p[n - 1] == '\t')) + n--; + if (n > 0 && sp_buf_add(out, p, n) == 0) + took = 1; + e->have_steer = 0; + sp_buf_clear(&e->steer); + } + pthread_mutex_unlock(&e->lock); + return took; +} + +static int +engine_steer_cb(void *ctx, struct sp_buf *out) +{ + struct sp_engine *e = ctx; + int took = 0; + + pthread_mutex_lock(&e->lock); + if (e->have_steer) { + e->have_steer = 0; + e->steers++; + took = sp_buf_puts(out, e->steer.p != NULL ? e->steer.p : "") == 0 ? + 1 : -1; + sp_buf_clear(&e->steer); + } + pthread_mutex_unlock(&e->lock); + return took; +} + +/* + * The turn hit a usage limit: say so in the prompt and wait for the reset on + * the turn thread. The screen stays alive (another thread); Ctrl-C ends it. + */ +static int +engine_limit_wait(void *ctx, long until, const char *why) +{ + struct sp_engine *e = ctx; + char when[32], line[300]; + struct tm tm; + time_t tt = (time_t)until; + long wait = e->max_wait > 0 ? e->max_wait : 12 * 3600; + + (void)why; + if (until - (long)time(NULL) > wait) + return 0; + strftime(when, sizeof(when), "%a %H:%M", localtime_r(&tt, &tm)); + snprintf(line, sizeof(line), sp_t("ui.limit_wait"), when); + ev_push(e, SP_EV_NOTE, 0, line, NULL); + while ((long)time(NULL) < until && !e->cancel) { + struct timespec ts = { 0, 250000000L }; + + nanosleep(&ts, NULL); + } + ev_push(e, SP_EV_NOTE, 0, "", NULL); + return !e->cancel; +} + +/* a provider at its limit: another member of its pool, if one has room */ +static int +engine_switch(void *ctx) +{ + struct sp_engine *e = ctx; + + return sp_provider_failover(&e->ag, e->conf); +} + +static void +engine_compact(void *ctx, size_t before, size_t after, size_t mb, size_t ma) +{ + struct sp_engine *e = ctx; + char b1[32], b2[32], t1[32], t2[32]; + size_t tb = before / 4, ta = after / 4; + char msg[256]; + + if (before >= 1024) + snprintf(b1, sizeof(b1), "%.1fKiB", before / 1024.0); + else + snprintf(b1, sizeof(b1), "%zuB", before); + if (after >= 1024) + snprintf(b2, sizeof(b2), "%.1fKiB", after / 1024.0); + else + snprintf(b2, sizeof(b2), "%zuB", after); + if (tb >= 1000) + snprintf(t1, sizeof(t1), "~%.1fk tok", tb / 1000.0); + else + snprintf(t1, sizeof(t1), "~%zu tok", tb); + if (ta >= 1000) + snprintf(t2, sizeof(t2), "~%.1fk tok", ta / 1000.0); + else + snprintf(t2, sizeof(t2), "~%zu tok", ta); + snprintf(msg, sizeof(msg), sp_t("ui.compacted"), mb, ma, t1, t2, b1, + b2); + ev_push(e, SP_EV_ENTRY, 0, "splinter", msg); +} + +/* ----------------------------------------------------------------- turns */ + +static void * +turn_thread(void *arg) +{ + struct sp_engine *e = arg; + char *text = e->turn_text; + + for (;;) { + int rc; + char *next = NULL; + + e->ag.cfg = &e->turn_cfg; + sp_openai_set_cancel(&e->cancel); + if (e->have_swarm) + swarm_report_busy(&e->swarm, 1); + /* + * A leftover steer starts a second turn in this same worker. + * The step buffers belong to one turn and must not carry the + * previous answer into the next step event. + */ + pthread_mutex_lock(&e->lock); + sp_buf_clear(&e->live); + sp_buf_clear(&e->think); + pthread_mutex_unlock(&e->lock); + sp_buf_clear(&e->answer); + sp_buf_clear(&e->err); + rc = sp_agent_run(&e->ag, text, &e->answer, &e->err); + if (e->have_swarm) + swarm_report_busy(&e->swarm, 0); + sp_openai_set_cancel(NULL); + /* + * The reasoning is on screen already (it streamed); the log keeps + * the whole of it, the final step's included. + */ + pthread_mutex_lock(&e->lock); + if (e->think.p != NULL && e->think.len > 0) + sp_logf("thinking", "%s", e->think.p); + /* + * A steer the turn took at a step boundary is already in the + * conversation. Only one it never reached becomes the next message. + */ + if (e->cancel) { + /* cancelled: the text typed for this turn is not a prompt */ + e->have_steer = 0; + sp_buf_clear(&e->steer); + } else if (rc == 0 && e->have_steer) { + e->have_steer = 0; + e->steers++; + next = strdup(e->steer.p != NULL ? e->steer.p : ""); + sp_buf_clear(&e->steer); + } + pthread_mutex_unlock(&e->lock); + ev_push(e, SP_EV_TURN_END, rc, + e->answer.p != NULL ? e->answer.p : "", + e->err.p != NULL ? e->err.p : ""); + /* + * e->turn_text is the first text and belongs to the engine; a + * steer's text is the worker's own copy. Clearing the pointer + * with the free keeps sp_engine_close() from freeing it twice. + */ + pthread_mutex_lock(&e->lock); + if (e->turn_text == text) + e->turn_text = NULL; + pthread_mutex_unlock(&e->lock); + free(text); + text = NULL; + snapshot_stats(e); + if (next != NULL && *next != '\0') { + /* + * A single-step turn ends with the answer, so a steer + * typed during it had no step boundary to land on. It + * becomes the next message, run like any other turn. + */ + text = next; + ev_push(e, SP_EV_ENTRY, 0, "you", text); + ev_push(e, SP_EV_STATE, 0, NULL, NULL); + continue; + } + free(next); + break; + } + free(text); + /* + * The old screen said how many steers the turn took; the count moved + * here with the loop, and a front end that has no prompt line to put it + * in still gets it as a transcript entry. + */ + pthread_mutex_lock(&e->lock); + if (e->steers > 0) { + char note[64]; + + snprintf(note, sizeof(note), "(%zu steering%s applied)", + e->steers, e->steers == 1 ? "" : "s"); + ev_push_locked(e, SP_EV_ENTRY, 0, "splinter", note); + } + pthread_mutex_unlock(&e->lock); + /* + * The turn's numbers are part of the first state event, not of the + * join: a remote front end has no join of its own, and the sidebar + * must not show the previous turn until the next event arrives. + */ + { + struct timespec now; + long ms; + + clock_gettime(CLOCK_MONOTONIC, &now); + ms = (long)((now.tv_sec - e->turn_t0.tv_sec) * 1000 + + (now.tv_nsec - e->turn_t0.tv_nsec) / 1000000); + pthread_mutex_lock(&e->lock); + e->last_ms = ms; + e->last_steps = e->ag.stats.steps; + e->last_calls = e->ag.stats.tool_calls; + pthread_mutex_unlock(&e->lock); + } + /* + * The events go into the queue before the turn is marked idle: a front + * end that sees "not busy" must be able to drain everything that + * produced it. + */ + ev_push(e, SP_EV_STATE, 0, NULL, NULL); + ev_push(e, SP_EV_BUSY, 0, NULL, NULL); + pthread_mutex_lock(&e->lock); + e->running = 0; + pthread_cond_broadcast(&e->cond); + pthread_mutex_unlock(&e->lock); + return NULL; +} + +int +sp_engine_submit(struct sp_engine *e, const char *text) +{ + if (e == NULL || text == NULL || *text == '\0') + return -1; + pthread_mutex_lock(&e->lock); + if (e->running) { + pthread_mutex_unlock(&e->lock); + return -1; + } + /* a previous turn is joinable; collect it before starting the next */ + if (e->have_thread) { + pthread_mutex_unlock(&e->lock); + (void)sp_engine_wait(e); + pthread_mutex_lock(&e->lock); + } + e->turn_text = strdup(text); + if (e->turn_text == NULL) { + pthread_mutex_unlock(&e->lock); + return -1; + } + e->turn_cfg = e->base; + e->turn_cfg.cancel = &e->cancel; + e->turn_cfg.steer = engine_steer_cb; + e->turn_cfg.steer_ctx = e; + e->turn_cfg.stream = engine_stream_cb; + e->turn_cfg.stream_ctx = e; + e->turn_cfg.approve = engine_approve; + e->turn_cfg.approve_ctx = e; + e->turn_cfg.tool_begin = engine_tool_begin; + e->turn_cfg.tool_begin_ctx = e; + e->turn_cfg.tool_end = engine_tool_end; + e->turn_cfg.tool_end_ctx = e; + e->turn_cfg.on_compact = engine_compact; + e->turn_cfg.on_compact_ctx = e; + if (e->base.limit_wait != NULL) { + e->turn_cfg.limit_wait = engine_limit_wait; + e->turn_cfg.limit_ctx = e; + } + if (e->conf != NULL && e->conf->npools > 0) { + e->turn_cfg.limit_switch = engine_switch; + e->turn_cfg.switch_ctx = e; + } + /* the profile's own consent rule wins over the configured one */ + if (e->agents.n > 0 && e->agent_cur >= 0 && + (size_t)e->agent_cur < e->agents.n && + e->agents.v[e->agent_cur].autonomous >= 0) + e->turn_cfg.autonomous = + e->agents.v[e->agent_cur].autonomous; + e->cancel = 0; + e->steers = 0; + e->approve_pending = 0; + sp_buf_clear(&e->think); + sp_buf_clear(&e->live); + clock_gettime(CLOCK_MONOTONIC, &e->turn_t0); + e->running = 1; + /* + * The handle is claimed before the thread exists and "busy" is queued + * while the lock is still held: a worker that starts and finishes at + * once must not get its events in front of the busy event, and a front + * end that saw "not busy" must find a thread to join. + */ + e->have_thread = 1; + ev_push_locked(e, SP_EV_BUSY, 1, NULL, NULL); + if (pthread_create(&e->th, NULL, turn_thread, e) != 0) { + e->running = 0; + e->have_thread = 0; + free(e->turn_text); + e->turn_text = NULL; + ev_push_locked(e, SP_EV_BUSY, 0, NULL, NULL); + pthread_mutex_unlock(&e->lock); + return -1; + } + pthread_mutex_unlock(&e->lock); + return 0; +} + +int +sp_engine_quit(struct sp_engine *e) +{ + int quit; + + if (e == NULL) + return 0; + pthread_mutex_lock(&e->lock); + quit = e->quit; + pthread_mutex_unlock(&e->lock); + return quit; +} + +int +sp_engine_busy(struct sp_engine *e) +{ + int busy; + + if (e == NULL) + return 0; + pthread_mutex_lock(&e->lock); + busy = e->running; + pthread_mutex_unlock(&e->lock); + return busy; +} + +int +sp_engine_wait(struct sp_engine *e) +{ + pthread_t th; + int have, running; + + if (e == NULL) + return -1; + pthread_mutex_lock(&e->lock); + have = e->have_thread; + running = e->running; + th = e->th; + if (have && !running) + e->have_thread = 0; + pthread_mutex_unlock(&e->lock); + if (!have) + return 0; + if (running) + return -1; /* a front end waits for SP_EV_BUSY, not for us */ + pthread_join(th, NULL); + return 0; +} + +/* + * Join the turn from close: unlike sp_engine_wait() this one blocks, because + * the engine is about to go away and the worker must not find freed memory. + * A cancel was set first, so the wait is bounded by whatever the transport + * needs to kill its child. + */ +static void +engine_join(struct sp_engine *e) +{ + pthread_t th; + int have; + + pthread_mutex_lock(&e->lock); + while (e->running) + pthread_cond_wait(&e->cond, &e->lock); + have = e->have_thread; + th = e->th; + e->have_thread = 0; + pthread_mutex_unlock(&e->lock); + if (have) + pthread_join(th, NULL); +} + +/* + * One synchronous request: what -p, the slash prompt and a test want. No + * queue, no thread; the caller's stream callback sees the text as it arrives. + */ +int +sp_engine_prompt(struct sp_engine *e, const char *text, sp_stream_cb stream, + void *stream_ctx, struct sp_buf *answer, struct sp_buf *err) +{ + struct sp_agent_config cfg; + int rc; + + if (e == NULL || text == NULL) + return -1; + if (sp_engine_busy(e)) + return -1; + pthread_mutex_lock(&e->lock); + e->cancel = 0; + e->have_steer = 0; + sp_buf_clear(&e->steer); + pthread_mutex_unlock(&e->lock); + cfg = e->base; + if (stream != NULL) { + cfg.stream = stream; + cfg.stream_ctx = stream_ctx; + } + e->ag.cfg = &cfg; + rc = sp_agent_run(&e->ag, text, answer, err); + e->ag.cfg = &e->base; + snapshot_stats(e); + return rc; +} + +/* -------------------------------------------------------------- profiles */ + +/* a built-in profile's description in the user's language */ +static const char * +agent_desc(const struct sp_agent_def *d) +{ + if (strcmp(d->source, "(built in)") == 0) { + if (strcmp(d->name, "build") == 0) + return sp_t("agent.desc.build"); + if (strcmp(d->name, "plan") == 0) + return sp_t("agent.desc.plan"); + } + return d->description; +} + +/* + * Switch the agent profile: its tool policy and prompt take effect on the next + * turn, and its model (if it names one) answers it. The provider the chat was + * on is remembered the first time a profile moves it and comes back with the + * next profile that names no model. + */ +static int +agent_switch(struct sp_engine *e, int idx, int announce) +{ + const struct sp_agent_def *d; + char msg[400]; + + if (e->agents.n == 0 || idx < 0 || (size_t)idx >= e->agents.n) + return -1; + d = &e->agents.v[idx]; + if (sp_agents_activate(&e->ag, d, e->base_prompt != NULL ? + e->base_prompt : "", &e->policy) != 0) { + char msg[200]; + + snprintf(msg, sizeof(msg), sp_t("agent.failed"), d->name); + ev_push(e, SP_EV_ENTRY, 0, "error", msg); + return -1; + } + e->agent_cur = idx; + snprintf(e->agent_name, sizeof(e->agent_name), "%.24s", d->name); + profile_save(e); + if (e->conf != NULL) { + struct sp_choice ch; + const char *want = d->model[0] != '\0' ? d->model : + (e->home_id[0] != '\0' ? e->home_id : NULL); + + if (want != NULL && sp_provider_choose(e->conf, want, &ch) == 0 && + strcmp(ch.d->kind, "cli") != 0 && ch.d->endpoint[0] != '\0') { + struct sp_buf perr; + + if (d->model[0] != '\0' && e->home_id[0] == '\0') + snprintf(e->home_id, sizeof(e->home_id), "%s", + sp_usage_active()); + if (sp_buf_init(&perr) == 0) { + if (sp_provider_apply(&e->ag, ch.d->kind, + ch.d->endpoint, + ch.model[0] != '\0' ? ch.model : ch.d->model, + ch.d->key_env, &perr) == 0) { + sp_usage_set_active(ch.d->id); + snprintf(e->cur_model, sizeof(e->cur_model), + "%s", ch.model[0] != '\0' ? ch.model : + ch.d->model); + snprintf(e->cur_endpoint, + sizeof(e->cur_endpoint), "%s", + ch.d->endpoint); + } + sp_buf_free(&perr); + } + if (d->model[0] == '\0') + e->home_id[0] = '\0'; + } + } + if (announce) { + snprintf(msg, sizeof(msg), sp_t("agent.switched"), d->name, + agent_desc(d), d->max_auth == 0 ? sp_t("agent.readonly") : ""); + ev_push(e, SP_EV_ENTRY, 0, "splinter", msg); + /* at open there is no front end yet; a client gets state directly */ + ev_push(e, SP_EV_STATE, 0, NULL, NULL); + } + return 0; +} + +int +sp_engine_agent_switch(struct sp_engine *e, int idx) +{ + if (e == NULL) + return -1; + return agent_switch(e, idx, 1); +} + +/* --------------------------------------------------------------- commands */ + +/* the shell a '!' line runs in; its output becomes a transcript entry */ +#define SHELL_MAX (64 * 1024) + +static void +engine_shell(struct sp_engine *e, const char *cmd) +{ + struct sp_buf out; + FILE *fp; + char chunk[4096]; + size_t n, total = 0; + + fp = popen(cmd, "r"); + if (fp == NULL) { + ev_push(e, SP_EV_ENTRY, 0, "error", "cannot run the shell"); + return; + } + if (sp_buf_init(&out) != 0) { + pclose(fp); + return; + } + while ((n = fread(chunk, 1, sizeof(chunk), fp)) > 0) { + total += n; + if (out.len < SHELL_MAX) { + size_t take = n; + + if (out.len + take > SHELL_MAX) + take = SHELL_MAX - out.len; + (void)sp_buf_add(&out, chunk, take); + } + } + pclose(fp); + if (total > out.len) + (void)sp_buf_printf(&out, "\n[... %zu bytes not shown]", + total - out.len); + ev_push(e, SP_EV_ENTRY, 0, "shell", + out.p != NULL && out.len > 0 ? out.p : "(no output)"); + sp_buf_free(&out); +} + +/* /connect in the terminal: the same questions the gateway asks, per line */ +static void +connect_ask(struct engine_cc *cc, struct sp_buf *out) +{ + switch (cc->step) { + case 1: + sp_buf_puts(out, sp_t("connect.endpoint")); + break; + case 2: + sp_buf_puts(out, sp_t("connect.model")); + break; + case 3: + if (cc->key_env[0] != '\0') + sp_buf_printf(out, sp_t("connect.key_named"), + cc->key_env); + else + sp_buf_puts(out, sp_t("connect.key")); + break; + default: + sp_buf_puts(out, sp_t("connect.name")); + break; + } +} + +/* returns 1: the line was an answer (handled), 0: nothing is running */ +static int +connect_answer(struct sp_engine *e, const char *line, struct sp_buf *out) +{ + struct engine_cc *cc = &e->cc; + + if (!cc->active) + return 0; + if (strcmp(line, "/cancel") == 0 || strcasecmp(line, "cancel") == 0) { + memset(cc, 0, sizeof(*cc)); + sp_buf_puts(out, sp_t("connect.cancel")); + return 1; + } + switch (cc->step) { + case 0: + if (!sp_provider_id_ok(line)) { + sp_buf_puts(out, sp_t("connect.name_bad")); + return 1; + } + snprintf(cc->id, sizeof(cc->id), "%s", line); + break; + case 1: + if (strcmp(line, "ollama") == 0) { + snprintf(cc->endpoint, sizeof(cc->endpoint), + "http://127.0.0.1:11434/v1"); + } else if (strcmp(line, "opencode") == 0) { + snprintf(cc->endpoint, sizeof(cc->endpoint), + "https://opencode.ai/zen/go/v1"); + snprintf(cc->key_env, sizeof(cc->key_env), + "OPENCODE_GO_API_KEY"); + } else if (!sp_provider_endpoint_ok(line)) { + sp_buf_puts(out, sp_t("connect.endpoint_bad")); + return 1; + } else { + snprintf(cc->endpoint, sizeof(cc->endpoint), "%s", line); + } + break; + case 2: + if (!sp_provider_model_ok(line)) { + sp_buf_puts(out, sp_t("connect.model_bad")); + return 1; + } + snprintf(cc->model, sizeof(cc->model), "%s", line); + break; + default: + if (strcmp(line, "-") == 0) + cc->key_env[0] = '\0'; + else if (strcmp(line, "/skip") != 0) { + if (!sp_provider_key_ok(line)) { + sp_buf_puts(out, sp_t("connect.key_bad")); + return 1; + } + snprintf(cc->key_env, sizeof(cc->key_env), "%s", line); + } + { + char dir[720]; + struct sp_buf cerr; + + sp_buf_init(&cerr); + if (e->conf == NULL || + sp_provider_dir(dir, sizeof(dir)) != 0) { + sp_buf_puts(out, sp_t("connect.nodir")); + } else if (sp_provider_add(e->conf, dir, cc->id, + cc->endpoint, cc->model, cc->key_env, + &cerr) != 0) { + sp_buf_printf(out, sp_t("connect.failed"), + cerr.p != NULL ? cerr.p : "?"); + } else { + sp_buf_printf(out, sp_t("connect.saved"), + cc->id, cc->model, cc->endpoint); + } + sp_buf_free(&cerr); + } + memset(cc, 0, sizeof(*cc)); + return 1; + } + cc->step++; + sp_buf_puts(out, "\n"); + connect_ask(cc, out); + return 1; +} + +static int +name_cmp(const void *a, const void *b) +{ + return strcmp((const char *)a, (const char *)b); +} + +static int +slash_add(char (*names)[64], int *n, int max, const char *name) +{ + int i; + + if (name == NULL || *name == '\0' || *n >= max) + return 0; + for (i = 0; i < *n; i++) + if (strcmp(names[i], name) == 0) + return 0; + snprintf(names[(*n)++], 64, "%s", name); + return 1; +} + +int +sp_engine_command_names(struct sp_engine *e, char (*names)[64], int max) +{ + static const char *builtin[] = { + "agent", "agents", "connect", "exit", "model", "new", "q", + "quit", "reset", "resume", "status", "swarm", "usage", + "widgets" + }; + struct sp_buf b; + char cdir[700], *p, *tok, *save; + size_t i; + int n = 0; + + if (e == NULL || names == NULL || max <= 0) + return 0; + for (i = 0; i < sizeof(builtin) / sizeof(builtin[0]); i++) + slash_add(names, &n, max, builtin[i]); + if (e->host != NULL && sp_buf_init(&b) == 0) { + if (sp_host_command_help(e->host, &b) > 0 && b.p != NULL) { + for (tok = strtok_r(b.p, " \t\r\n", &save); tok != NULL; + tok = strtok_r(NULL, " \t\r\n", &save)) { + p = tok; + if (*p == '/') + p++; + if (*p != '\0') + slash_add(names, &n, max, p); + } + } + sp_buf_free(&b); + } + if (sp_buf_init(&b) == 0) { + if (sp_cmdscript_dir(e->sess.dir, cdir, sizeof(cdir)) == 0 && + sp_cmdscript_list(cdir, &b) > 0 && b.p != NULL) { + for (tok = strtok_r(b.p, " \t\r\n", &save); tok != NULL; + tok = strtok_r(NULL, " \t\r\n", &save)) + if (*tok != '\0') + slash_add(names, &n, max, tok); + } + sp_buf_free(&b); + } + /* stable order for the popup; qsort because the shift loop tripped the + * analyzer's overlap check for no reason */ + qsort(names, (size_t)n, sizeof(names[0]), name_cmp); + return n; +} + +/* /model: list, switch provider, pool or model; remember the choice */ +static void +cmd_model(struct sp_engine *e, const char *args, struct sp_buf *out) +{ + struct sp_provider p; + struct sp_buf perr, serr; + size_t idx = 0, i, n; + char poolname[40]; + int is_pool = 0; + + snprintf(poolname, sizeof(poolname), "%s", args); + is_pool = sp_pool_find(e->conf, args) != NULL; + if (!is_pool) { + const char *sl = strchr(args, '/'); + + if (sl != NULL && (size_t)(sl - args) < sizeof(poolname)) { + memcpy(poolname, args, (size_t)(sl - args)); + poolname[sl - args] = '\0'; + is_pool = sp_pool_find(e->conf, poolname) != NULL; + } + } + if (e->conf == NULL) { + sp_buf_puts(out, sp_t("model.none")); + } else if (args[0] == '\0') { + sp_buf_puts(out, sp_t("model.choose")); + n = sp_provider_count(e->conf); + for (i = 0; i < n; i++) + if (sp_provider_at(e->conf, i, &p) == 0) + sp_buf_printf(out, "\n %s %s%s", + p.id, p.model, + strcmp(p.model, e->cur_model) == 0 ? + " *" : ""); + if (e->conf->npools > 0) + sp_buf_printf(out, "\n%s", sp_t("model.pools")); + for (i = 0; i < e->conf->npools; i++) { + size_t j; + + sp_buf_printf(out, "\n %s pool (%s):", + e->conf->pool[i].id, e->conf->pool[i].strategy); + for (j = 0; j < e->conf->pool[i].nmembers; j++) + sp_buf_printf(out, " %s", + e->conf->pool[i].member[j]); + } + } else if (is_pool) { + struct sp_choice ch; + + if (sp_provider_choose(e->conf, args, &ch) != 0) { + sp_buf_printf(out, sp_t("model.unknown"), args); + } else { + sp_buf_init(&perr); + if (sp_provider_apply(&e->ag, ch.d->kind, ch.d->endpoint, + ch.model[0] != '\0' ? ch.model : ch.d->model, + ch.d->key_env, &perr) != 0) { + sp_buf_printf(out, sp_t("model.failed"), + perr.p != NULL ? perr.p : "?"); + } else { + sp_usage_set_active(ch.d->id); + snprintf(e->cur_endpoint, sizeof(e->cur_endpoint), + "%s", ch.d->endpoint); + snprintf(e->cur_model, sizeof(e->cur_model), "%s", + ch.model[0] != '\0' ? ch.model : ch.d->model); + sp_buf_printf(out, sp_t("model.pool"), poolname, + e->cur_model, ch.d->id); + } + sp_buf_free(&perr); + } + } else if (sp_provider_find(e->conf, args, &idx)) { + sp_buf_init(&perr); + if (sp_provider_use(&e->ag, e->conf, idx, &perr) != 0) { + sp_buf_printf(out, sp_t("model.failed"), + perr.p != NULL ? perr.p : "?"); + } else if (sp_provider_at(e->conf, idx, &p) == 0) { + snprintf(e->cur_endpoint, sizeof(e->cur_endpoint), "%s", + p.endpoint); + snprintf(e->cur_model, sizeof(e->cur_model), "%s", + p.model); + sp_buf_init(&serr); + sp_buf_printf(out, sp_provider_save_choice(e->conf, &p, + &serr) == 0 ? sp_t("model.saved") : + sp_t("model.switched"), p.model, p.id); + sp_buf_free(&serr); + } + sp_buf_free(&perr); + } else { + struct sp_provider chosen; + int ok; + + memset(&p, 0, sizeof(p)); + if (!sp_provider_find(e->conf, e->cur_model, &idx) || + sp_provider_at(e->conf, idx, &p) != 0) + (void)sp_provider_at(e->conf, 0, &p); + sp_buf_init(&perr); + ok = sp_provider_apply(&e->ag, p.kind, p.endpoint, args, + p.key_env, &perr) == 0; + if (ok) { + memset(&chosen, 0, sizeof(chosen)); + snprintf(chosen.id, sizeof(chosen.id), "%s", p.id); + snprintf(chosen.endpoint, sizeof(chosen.endpoint), "%s", + p.endpoint); + snprintf(chosen.model, sizeof(chosen.model), "%s", args); + snprintf(chosen.key_env, sizeof(chosen.key_env), "%s", + p.key_env); + snprintf(e->cur_model, sizeof(e->cur_model), "%s", args); + sp_buf_init(&serr); + sp_buf_printf(out, sp_provider_save_choice(e->conf, + &chosen, &serr) == 0 ? sp_t("model.saved") : + sp_t("model.switched"), args, p.id); + sp_buf_free(&serr); + } else { + sp_buf_printf(out, sp_t("model.failed"), + perr.p != NULL ? perr.p : "?"); + } + sp_buf_free(&perr); + } + ev_push(e, SP_EV_STATE, 0, NULL, NULL); +} + +static void +cmd_new(struct sp_engine *e, struct sp_buf *out) +{ + struct sp_session_info old = e->sess; + char id[64]; + struct sp_buf serr; + const char *base; + + memset(&e->sess, 0, sizeof(e->sess)); + e->new_seq++; + if (e->new_seq == 1) + snprintf(id, sizeof(id), "sess-%ld-%d", (long)time(NULL), + (int)getpid()); + else + snprintf(id, sizeof(id), "sess-%ld-%d-%u", (long)time(NULL), + (int)getpid(), e->new_seq); + base = e->base_prompt != NULL ? e->base_prompt : + e->base.system_prompt; + sp_buf_init(&serr); + if (sp_session_open(&e->sess, old.dir, id, &serr) != 0 || + sp_conv_reset(&e->conv, base) != 0) { + sp_buf_printf(out, sp_t("session.failed"), + serr.p != NULL ? serr.p : "?"); + e->sess = old; + } else { + e->ag.sess = &e->sess; + sp_openai_set_session(e->sess.id); + /* + * /new drops the conversation, not the way of working: the + * profile's prompt goes back on top of the bare base, exactly + * as it was at startup. Without this the sidebar still said + * "plan" while the instructions were build's. + */ + if (e->agents.n > 0 && e->agent_cur >= 0 && + (size_t)e->agent_cur < e->agents.n) + (void)sp_agents_activate(&e->ag, + &e->agents.v[e->agent_cur], base, &e->policy); + (void)sp_log_open(e->sess.dir, e->sess.id); + sp_logf("session", "started: %s", e->sess.id); + profile_save(e); + ev_push(e, SP_EV_CLEAR, 0, NULL, NULL); + sp_buf_printf(out, sp_t("session.new"), e->sess.id); + } + sp_buf_free(&serr); +} + +static void +cmd_status(struct sp_engine *e, struct sp_buf *out) +{ + size_t comp = 0, failed = 0; + unsigned turns = 0; + time_t now = time(NULL); + char tbuf[64]; + struct tm tm; + + (void)localtime_r(&now, &tm); + strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm); + if (e->host != NULL) + sp_host_compaction_stats(e->host, &comp, &failed, &turns); + sp_buf_printf(out, "status (%s)\n", tbuf); + sp_buf_printf(out, " session %s\n dir %s\n", e->sess.id, + e->sess.dir); + sp_buf_printf(out, " model %s\n endpoint %s\n theme %s\n", + e->cur_model[0] != '\0' ? e->cur_model : "-", + e->cur_endpoint[0] != '\0' ? e->cur_endpoint : "-", e->theme); + sp_buf_printf(out, " agent %s\n", e->agent_name); + sp_buf_printf(out, " last %ld ms, %zu steps, %zu tool calls\n", + e->last_ms, e->last_steps, e->last_calls); + sp_buf_printf(out, " tokens in %zu, out %zu\n", + e->snapshot.tokens_in, e->snapshot.tokens_out); + sp_buf_printf(out, " compact %zu applied, %zu failed, %zu turns (agent %zu)\n", + comp, failed, turns, e->snapshot.compactions); + sp_buf_printf(out, " limits max_bytes %zu, max_steps %zu%s\n", + e->base.max_bytes, e->base.max_steps, + e->base.autonomous ? ", autonomous" : ""); + if (e->host != NULL) { + struct sp_meter m; + char seg[512]; + + sp_host_meter_get(e->host, &m); + sp_buf_printf(out, " meter ctx %zu/%zu, cache %zu, tok %zu/%zu\n", + m.ctx_used, m.ctx_max, m.cached, m.tok_in, m.tok_out); + if (sp_host_status_text(e->host, seg, sizeof(seg)) > 0) + sp_buf_printf(out, " bar %s\n", seg); + } + if (e->have_swarm) { + char sws[256], list[1024]; + + swarm_status(&e->swarm, sws, sizeof(sws)); + sp_buf_printf(out, " swarm %s (id %d)\n", sws, e->swarm.id); + swarm_list(&e->swarm, list, sizeof(list)); + sp_buf_printf(out, "%s", list); + } +} + +static void +cmd_widgets(struct sp_engine *e, struct sp_buf *out) +{ + char buf[4096]; + + if (e->host == NULL || sp_host_widget_count(e->host) == 0) + sp_buf_puts(out, sp_t("widgets.none")); + else if (sp_host_widget_snapshot(e->host, buf, sizeof(buf)) > 0) + sp_buf_printf(out, "%s", buf); +} + +static void +cmd_swarm(struct sp_engine *e, const char *args, struct sp_buf *out) +{ + if (!e->have_swarm || e->swarm.role == SWARM_NONE) { + sp_buf_printf(out, "swarm: standalone (no fleet in %s)", + SWARM_PATH); + return; + } + if (args[0] == '\0' || strcmp(args, "ls") == 0 || + strcmp(args, "list") == 0) { + char list[1024]; + + swarm_list(&e->swarm, list, sizeof(list)); + sp_buf_printf(out, "%s", list); + return; + } + { + const char *p = args; + char *end; + long id = -1; + int target; + + while (*p == ' ') + p++; + if (*p >= '0' && *p <= '9') { + id = strtol(p, &end, 10); + p = end; + while (*p == ' ') + p++; + } + if (*p == '\0') { + sp_buf_printf(out, "usage: /swarm [N] " + "(0=master, no N=least busy)\n /swarm ls"); + return; + } + if (e->swarm.role != SWARM_MASTER && id != 0) { + sp_buf_printf(out, + "swarm: only master (0) can route commands"); + return; + } + target = swarm_route(&e->swarm, (int)id, p); + if (target < 0) + sp_buf_printf(out, "swarm: route failed (id %ld)", id); + else + sp_buf_printf(out, "swarm: routed to %d", target); + } +} + +static void +cmd_agents(struct sp_engine *e, struct sp_buf *out) +{ + size_t i; + + for (i = 0; i < e->agents.n; i++) { + const struct sp_agent_def *d = &e->agents.v[i]; + + sp_buf_printf(out, "%c %-12s %s %s\n", + (int)i == e->agent_cur ? '*' : ' ', d->name, + agent_desc(d), d->max_auth == 0 ? + sp_t("agent.readonly") : ""); + if (strcmp(d->source, "(built in)") != 0) + sp_buf_printf(out, " %s\n", d->source); + } + sp_buf_puts(out, sp_t("agent.help")); +} + +int +sp_engine_input(struct sp_engine *e, const char *line, struct sp_buf *out) +{ + char name[64], args[1536], cdir[700]; + const char *sp; + + if (e == NULL || line == NULL || out == NULL) + return SP_INPUT_HANDLED; + if (e->cc.active) + return connect_answer(e, line, out) ? + SP_INPUT_HANDLED : SP_INPUT_PROMPT; + if (line[0] == '!' && line[1] != '\0') { + engine_shell(e, line + 1); + return SP_INPUT_HANDLED; + } + if (line[0] != '/' || line[1] == '\0') + return SP_INPUT_PROMPT; + /* the harness' own continuation prompt, kept for the old muscle memory */ + if (strcmp(line, "/resume") == 0) { + sp_buf_puts(out, "Continue with the task you were working on. " + "Do not repeat work that is already done."); + return SP_INPUT_PROMPT; + } + sp = strchr(line, ' '); + if (sp == NULL) { + snprintf(name, sizeof(name), "%.63s", line + 1); + args[0] = '\0'; + } else { + size_t nlen = (size_t)(sp - (line + 1)); + + if (nlen >= sizeof(name)) + nlen = sizeof(name) - 1; + memcpy(name, line + 1, nlen); + name[nlen] = '\0'; + snprintf(args, sizeof(args), "%s", sp + 1); + } + if (strcmp(name, "agent") == 0 || strcmp(name, "agents") == 0) { + if (args[0] != '\0') { + int idx = sp_agents_find(&e->agents, args); + + if (idx < 0) { + sp_buf_printf(out, sp_t("agent.none"), args); + sp_buf_puts(out, "\n"); + } else + (void)agent_switch(e, idx, 1); + } else + cmd_agents(e, out); + return SP_INPUT_HANDLED; + } + if (strcmp(name, "quit") == 0 || strcmp(name, "exit") == 0 || + strcmp(name, "q") == 0) { + e->quit = 1; + ev_push(e, SP_EV_QUIT, 0, NULL, NULL); + return SP_INPUT_HANDLED; + } + if (strcmp(name, "widgets") == 0 || strcmp(name, "widget") == 0) { + cmd_widgets(e, out); + return SP_INPUT_HANDLED; + } + if (strcmp(name, "usage") == 0) { + sp_usage_report(e->conf, out); + return SP_INPUT_HANDLED; + } + if (strcmp(name, "status") == 0) { + cmd_status(e, out); + return SP_INPUT_HANDLED; + } + if (strcmp(name, "swarm") == 0) { + cmd_swarm(e, args, out); + return SP_INPUT_HANDLED; + } + if (strcmp(name, "model") == 0) { + cmd_model(e, args, out); + return SP_INPUT_HANDLED; + } + if (strcmp(name, "new") == 0 || strcmp(name, "reset") == 0) { + cmd_new(e, out); + return SP_INPUT_HANDLED; + } + if (strcmp(name, "connect") == 0) { + if (sp_config_loaded_path() == NULL) { + sp_buf_puts(out, sp_t("connect.nodir")); + return SP_INPUT_HANDLED; + } + memset(&e->cc, 0, sizeof(e->cc)); + e->cc.active = 1; + e->cc.step = 0; + sp_buf_puts(out, sp_t("connect.start")); + sp_buf_puts(out, "\n"); + connect_ask(&e->cc, out); + return SP_INPUT_HANDLED; + } + if (e->host != NULL && sp_host_command(e->host, name, args, out) == 0) + return SP_INPUT_HANDLED; + /* + * Not a plugin command. A program in commands/ wins over 'unknown': its + * output is not a reply for the operator, it is context for the model, + * so the turn runs after this. + */ + { + struct sp_buf cerr; + + sp_buf_clear(out); + if (sp_buf_init(&cerr) != 0) + return SP_INPUT_HANDLED; + if (sp_cmdscript_dir(e->sess.dir, cdir, sizeof(cdir)) == 0 && + sp_cmdscript_exists(cdir, name) && + sp_slash_script(cdir, name, args, out, &cerr) == 0 && + out->p != NULL) { + ev_push(e, SP_EV_ENTRY, 0, "shell", out->p); + sp_buf_free(&cerr); + return SP_INPUT_SUBMIT; + } + sp_buf_free(&cerr); + } + sp_buf_clear(out); + sp_buf_printf(out, sp_t("cmd.unknown"), name); + sp_buf_printf(out, "\n %s ", sp_t("cmd.available")); + if (e->host != NULL) + (void)sp_host_command_help(e->host, out); + return SP_INPUT_HANDLED; +} + +/* ---------------------------------------------------------------- opening */ + +/* the session directory and id, opened */ +static int +open_session(struct sp_engine *e, const struct sp_engine_opts *o, + struct sp_buf *err, int *code) +{ + static char sessbuf[512], idbuf[64]; + const char *dir = o->session_dir; + const char *id = o->session_id; + + if (dir == NULL) { + const char *home = getenv("HOME"); + + snprintf(sessbuf, sizeof(sessbuf), "%s/.splinter", + home != NULL ? home : "."); + dir = 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_last && id == NULL) { + char cwd[512]; + + if (getcwd(cwd, sizeof(cwd)) == NULL || + sp_session_last_for(dir, cwd, idbuf, sizeof(idbuf)) != 0) { + sp_buf_printf(err, "no session in %s yet", + getcwd(cwd, sizeof(cwd)) != NULL ? cwd : "."); + *code = -2; + return -1; + } + id = idbuf; + } + if ((o->resume || o->continue_last) && id == NULL && + sp_session_latest(dir, idbuf, sizeof(idbuf)) == 0) + id = idbuf; + if (id == NULL) { + snprintf(idbuf, sizeof(idbuf), "sess-%ld-%d", (long)time(NULL), + (int)getpid()); + id = idbuf; + } + if (sp_session_open(&e->sess, dir, id, err) != 0) + return -1; + (void)sp_log_open(e->sess.dir, e->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. + */ + (void)setenv("SPLINTER_CLI_SESSION", e->sess.id, 0); + sp_openai_set_session(e->sess.id); + return 0; +} + +/* the plugin host and its plugins; a failed plugin is reported and skipped */ +static int +load_plugins(struct sp_engine *e, const struct sp_engine_opts *o, + struct sp_buf *err) +{ + struct sp_host *host; + size_t k; + + if (o->nplugins == 0) + return 0; + host = sp_host_new(&e->reg, &e->ag, &e->sess); + if (host == NULL) { + sp_buf_puts(err, "cannot create plugin host"); + return -1; + } + e->ag.host = host; + e->host = host; + sp_host_set_config(host, e->conf); + for (k = 0; k < o->nplugins && k < SP_ENGINE_PLUGINS; 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")); + } + return 0; +} + +/* a script file is one reply per line, in the mock transport's own protocol */ +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; +} + +/* the transport the options name */ +static int +pick_transport(struct sp_engine *e, const struct sp_engine_opts *o, + struct sp_buf *err) +{ + const char *hto; + long http_timeout; + + if (o->no_transport) + return 0; + if (o->kind != NULL && strcmp(o->kind, "anthropic") == 0) { + if (o->endpoint == NULL || o->model == NULL) { + sp_buf_puts(err, "an anthropic provider needs an " + "endpoint and a model"); + return -1; + } + hto = getenv("SPLINTER_HTTP_TIMEOUT"); + http_timeout = hto != NULL && *hto != '\0' ? + strtol(hto, NULL, 10) : 0; + if (http_timeout <= 0) + http_timeout = 900; + e->ag.tr = sp_anthropic_transport(o->endpoint, o->model, + getenv(o->key_env), &e->reg, http_timeout); + sp_provider_identify(&e->ag.tr, o->endpoint, + getenv(o->key_env)); + return 0; + } + if (o->transport != NULL) { + struct sp_transport *tr; + + if (e->host == NULL) { + sp_buf_puts(err, "--transport needs a plugin that " + "provides it"); + return -1; + } + tr = sp_host_transport(e->host, o->transport); + if (tr == NULL) { + sp_buf_printf(err, "no plugin provides the '%s' " + "transport", o->transport); + return -1; + } + e->ag.tr = *tr; + return 0; + } + if (o->script != NULL) { + if (sp_mock_init(&e->mock) != 0) { + sp_buf_puts(err, sp_t("err.oom")); + return -1; + } + e->have_mock = 1; + if (load_script(&e->mock, o->script, err) != 0) + return -1; + e->ag.tr = sp_mock_transport(&e->mock); + return 0; + } + if (o->endpoint == NULL) { + sp_buf_puts(err, "no endpoint"); + return -1; + } + if (o->model == NULL) { + sp_buf_puts(err, "--endpoint needs --model"); + return -1; + } + hto = getenv("SPLINTER_HTTP_TIMEOUT"); + http_timeout = hto != NULL && *hto != '\0' ? strtol(hto, NULL, 10) : 0; + if (http_timeout <= 0) + http_timeout = 900; + e->ag.tr = sp_openai_transport(o->endpoint, o->model, + getenv(o->key_env), &e->reg, http_timeout); + sp_provider_identify(&e->ag.tr, o->endpoint, getenv(o->key_env)); + return 0; +} + +/* + * The conversation: the system prompt, expanded (placeholders are facts about + * this machine), and with --resume the session's history. + */ +static int +setup_conversation(struct sp_engine *e, const struct sp_engine_opts *o, + struct sp_buf *err) +{ + size_t loaded = 0; + + sp_conv_init(&e->conv); + sp_prompt_expand(e->base.system_prompt, e->prompt_expanded, + sizeof(e->prompt_expanded), o->model); + e->base.system_prompt = e->prompt_expanded; + if (e->base.system_prompt != NULL && + e->base.system_prompt[0] != '\0' && + sp_conv_push(&e->conv, "system", NULL, + e->base.system_prompt) != 0) { + sp_buf_puts(err, sp_t("err.oom")); + return -1; + } + e->ag.conv = &e->conv; + if (!o->resume && !o->continue_last) + return 0; + sp_buf_clear(err); + if (sp_session_load(&e->sess, &e->conv, &loaded, err) != 0) + return -1; + return 0; +} + +int +sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o, + struct sp_buf *err) +{ + struct sp_engine *e; + char cwd[700]; + int start = -1, code = -1; + + if (out == NULL || o == NULL || o->conf == NULL || o->base == NULL) + return -1; + *out = NULL; + e = calloc(1, sizeof(*e)); + if (e == NULL) { + sp_buf_puts(err, sp_t("err.oom")); + return -1; + } + pthread_mutex_init(&e->lock, NULL); + pthread_cond_init(&e->cond, NULL); + sp_buf_init(&e->answer); + sp_buf_init(&e->err); + sp_buf_init(&e->live); + sp_buf_init(&e->think); + sp_buf_init(&e->steer); + e->conf = o->conf; + e->base = *o->base; + e->max_wait = o->conf->max_wait > 0 ? o->conf->max_wait : 12 * 3600; + /* + * A pool must be able to move the run to another member at a limit -- + * also on the synchronous path (-p), which does not build the async + * turn's config. This is where the old binary did it, for every mode. + */ + if (e->conf->npools > 0) { + e->base.limit_switch = engine_switch; + e->base.switch_ctx = e; + } + snprintf(e->cur_endpoint, sizeof(e->cur_endpoint), "%s", + o->endpoint != NULL ? o->endpoint : ""); + snprintf(e->cur_model, sizeof(e->cur_model), "%s", + o->model != NULL ? o->model : ""); + if (o->endpoint == NULL && o->conf->endpoint[0] != '\0') + snprintf(e->cur_endpoint, sizeof(e->cur_endpoint), "%s", + o->conf->endpoint); + if (o->model == NULL && o->conf->model[0] != '\0') + snprintf(e->cur_model, sizeof(e->cur_model), "%s", + o->conf->model); + + if (sp_builtin_register(&e->reg) != 0 || + sp_memory_register(&e->reg, e->conf) != 0 || + sp_skills_register(&e->reg, e->conf) != 0) { + sp_buf_puts(err, "cannot register the builtin tools"); + goto fail; + } + if (open_session(e, o, err, &code) != 0) + goto fail; + e->ag.sess = &e->sess; + sp_logf("session", "started: %s", e->sess.id); + if (load_plugins(e, o, err) != 0) + goto fail; + /* + * Registered here, not with the builtins: folder_history needs the + * session directory, and delegate needs the host for its task-panel + * entries. + */ + if (sp_folder_register(&e->reg, e->sess.dir) != 0 || + sp_delegate_register(&e->reg, e->conf, e->host) != 0) { + sp_buf_puts(err, "cannot register folder_history or delegate"); + goto fail; + } + if (pick_transport(e, o, err) != 0) { + code = -2; /* a configuration the user can fix */ + goto fail; + } + /* + * /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 (e->conf->endpoint[0] == '\0' && o->endpoint != NULL) + snprintf(e->conf->endpoint, sizeof(e->conf->endpoint), "%s", + o->endpoint); + if (e->conf->model[0] == '\0' && o->model != NULL) + snprintf(e->conf->model, sizeof(e->conf->model), "%s", o->model); + if (setup_conversation(e, o, err) != 0) + goto fail; + e->ag.reg = &e->reg; + e->ag.cfg = &e->base; + if (getcwd(cwd, sizeof(cwd)) == NULL) + cwd[0] = '\0'; + if (sp_agents_load(&e->agents, cwd, getenv("HOME")) != 0) { + sp_buf_puts(err, "cannot load the agent profiles"); + goto fail; + } + e->base_prompt = sp_agents_base(&e->conv); + if (e->agents.n > 0) { + char saved[48]; + + if (o->agent != NULL && *o->agent != '\0') { + start = sp_agents_find(&e->agents, o->agent); + if (start < 0) { + sp_buf_printf(err, "no agent '%s' " + "(splinter --agent-list)", o->agent); + code = -2; + goto fail; + } + } else if (profile_load(e, saved, sizeof(saved))) + start = sp_agents_find(&e->agents, saved); + if (start < 0) + start = sp_agents_find(&e->agents, "build"); + if (start < 0) + start = 0; + if (agent_switch(e, start, 0) != 0) { + sp_buf_puts(err, "cannot activate the agent profile"); + code = -2; + goto fail; + } + } + if (o->swarm) { + swarm_init(&e->swarm, cwd); + e->have_swarm = 1; + } + *out = e; + return 0; +fail: + sp_engine_close(e); + return code; +} + +void +sp_engine_close(struct sp_engine *e) +{ + if (e == NULL) + return; + if (sp_engine_busy(e)) + (void)sp_engine_cancel(e); + engine_join(e); + if (e->have_swarm) + swarm_close(&e->swarm); + sp_buf_free(&e->answer); + sp_buf_free(&e->err); + sp_buf_free(&e->live); + sp_buf_free(&e->think); + sp_buf_free(&e->steer); + free(e->base_prompt); + free(e->turn_text); + sp_agents_free(&e->agents); + sp_conv_free(&e->conv); + sp_host_free(e->host); + sp_registry_free(&e->reg); + if (e->have_mock) + sp_mock_free(&e->mock); + while (e->nq > 0) { + sp_engine_event_free(&e->q[0]); + memmove(&e->q[0], &e->q[1], (e->nq - 1) * sizeof(e->q[0])); + e->nq--; + } + free(e->q); + pthread_cond_destroy(&e->cond); + pthread_mutex_destroy(&e->lock); + free(e); +} diff --git a/src/folder.c b/src/backend/folder.c similarity index 100% rename from src/folder.c rename to src/backend/folder.c diff --git a/src/folder.h b/src/backend/folder.h similarity index 100% rename from src/folder.h rename to src/backend/folder.h diff --git a/src/i18n.c b/src/backend/i18n.c similarity index 100% rename from src/i18n.c rename to src/backend/i18n.c diff --git a/src/i18n.h b/src/backend/i18n.h similarity index 100% rename from src/i18n.h rename to src/backend/i18n.h diff --git a/src/interview.c b/src/backend/interview.c similarity index 100% rename from src/interview.c rename to src/backend/interview.c diff --git a/src/interview.h b/src/backend/interview.h similarity index 100% rename from src/interview.h rename to src/backend/interview.h diff --git a/src/json.c b/src/backend/json.c similarity index 100% rename from src/json.c rename to src/backend/json.c diff --git a/src/log.c b/src/backend/log.c similarity index 100% rename from src/log.c rename to src/backend/log.c diff --git a/src/log.h b/src/backend/log.h similarity index 100% rename from src/log.h rename to src/backend/log.h diff --git a/src/mcpserver.c b/src/backend/mcpserver.c similarity index 100% rename from src/mcpserver.c rename to src/backend/mcpserver.c diff --git a/src/mcpserver.h b/src/backend/mcpserver.h similarity index 100% rename from src/mcpserver.h rename to src/backend/mcpserver.h diff --git a/src/md.c b/src/backend/md.c similarity index 100% rename from src/md.c rename to src/backend/md.c diff --git a/src/md.h b/src/backend/md.h similarity index 100% rename from src/md.h rename to src/backend/md.h diff --git a/src/memory.c b/src/backend/memory.c similarity index 100% rename from src/memory.c rename to src/backend/memory.c diff --git a/src/memory.h b/src/backend/memory.h similarity index 100% rename from src/memory.h rename to src/backend/memory.h diff --git a/src/openai.c b/src/backend/openai.c similarity index 100% rename from src/openai.c rename to src/backend/openai.c diff --git a/src/palettes.c b/src/backend/palettes.c similarity index 100% rename from src/palettes.c rename to src/backend/palettes.c diff --git a/src/palettes.h b/src/backend/palettes.h similarity index 100% rename from src/palettes.h rename to src/backend/palettes.h diff --git a/src/plugin.c b/src/backend/plugin.c similarity index 100% rename from src/plugin.c rename to src/backend/plugin.c diff --git a/src/prompt.c b/src/backend/prompt.c similarity index 100% rename from src/prompt.c rename to src/backend/prompt.c diff --git a/src/prompt.h b/src/backend/prompt.h similarity index 100% rename from src/prompt.h rename to src/backend/prompt.h diff --git a/src/providers.c b/src/backend/providers.c similarity index 100% rename from src/providers.c rename to src/backend/providers.c diff --git a/src/providers.h b/src/backend/providers.h similarity index 100% rename from src/providers.h rename to src/backend/providers.h diff --git a/src/provstate.c b/src/backend/provstate.c similarity index 100% rename from src/provstate.c rename to src/backend/provstate.c diff --git a/src/provstate.h b/src/backend/provstate.h similarity index 100% rename from src/provstate.h rename to src/backend/provstate.h diff --git a/src/session.c b/src/backend/session.c similarity index 100% rename from src/session.c rename to src/backend/session.c diff --git a/src/skills.c b/src/backend/skills.c similarity index 100% rename from src/skills.c rename to src/backend/skills.c diff --git a/src/skills.h b/src/backend/skills.h similarity index 100% rename from src/skills.h rename to src/backend/skills.h diff --git a/src/sse.c b/src/backend/sse.c similarity index 93% rename from src/sse.c rename to src/backend/sse.c index f358fea..cf73b5f 100644 --- a/src/sse.c +++ b/src/backend/sse.c @@ -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 && diff --git a/src/swarm.c b/src/backend/swarm.c similarity index 100% rename from src/swarm.c rename to src/backend/swarm.c diff --git a/src/swarm.h b/src/backend/swarm.h similarity index 100% rename from src/swarm.h rename to src/backend/swarm.h diff --git a/src/telegram.c b/src/backend/telegram.c similarity index 100% rename from src/telegram.c rename to src/backend/telegram.c diff --git a/src/tgmd.c b/src/backend/tgmd.c similarity index 100% rename from src/tgmd.c rename to src/backend/tgmd.c diff --git a/src/tgmd.h b/src/backend/tgmd.h similarity index 100% rename from src/tgmd.h rename to src/backend/tgmd.h diff --git a/src/theme.c b/src/backend/theme.c similarity index 100% rename from src/theme.c rename to src/backend/theme.c diff --git a/src/theme.h b/src/backend/theme.h similarity index 100% rename from src/theme.h rename to src/backend/theme.h diff --git a/src/tool.c b/src/backend/tool.c similarity index 100% rename from src/tool.c rename to src/backend/tool.c diff --git a/src/transport.c b/src/backend/transport.c similarity index 100% rename from src/transport.c rename to src/backend/transport.c diff --git a/src/transport_anthropic.c b/src/backend/transport_anthropic.c similarity index 100% rename from src/transport_anthropic.c rename to src/backend/transport_anthropic.c diff --git a/src/transport_openai.c b/src/backend/transport_openai.c similarity index 97% rename from src/transport_openai.c rename to src/backend/transport_openai.c index 5cc0c6e..e30a979 100644 --- a/src/transport_openai.c +++ b/src/backend/transport_openai.c @@ -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); } diff --git a/src/usage.c b/src/backend/usage.c similarity index 100% rename from src/usage.c rename to src/backend/usage.c diff --git a/src/usage.h b/src/backend/usage.h similarity index 100% rename from src/usage.h rename to src/backend/usage.h diff --git a/src/frontend/client.c b/src/frontend/client.c new file mode 100644 index 0000000..90a8680 --- /dev/null +++ b/src/frontend/client.c @@ -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 +#include +#include +#include +#include +#include +#include + +#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; +} diff --git a/src/frontend/curses.c b/src/frontend/curses.c new file mode 100644 index 0000000..bf413db --- /dev/null +++ b/src/frontend/curses.c @@ -0,0 +1,2357 @@ +/* + * splinter -- curses front end. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + * + * This file draws and reads keys. It does not run turns, switch providers or + * keep a session: the engine (include/splinter_engine.h) does all of that and + * reports events, which are drained into the transcript here. + * + * Layout, fixed and deliberate: + * + * +---------------------------------+------------+ + * | history | sidebar | + * | three quarters | one quarter| + * | starts clear, only ever grows | model | + * | | usage | + * | | widgets | + * | | session | + * | | directory | + * +---------------------------------+------------+ + * | build> prompt, or "12s tool steer>" | + * +----------------------------------------------+ + * + * Only the UI thread ever calls into curses. The engine runs a turn on a + * thread of its own and only appends to an event queue; this file drains it. + * Anything that wants to appear in the sidebar hands over finished text and + * never touches a WINDOW. + * + * Redraws happen when something changed -- after a turn, after a key -- so an + * idle splinter burns no CPU. + * + * Keys: Enter sends, Ctrl-L redraws, Ctrl-C drops the input line, Ctrl-D quits. + */ +#include +#include +#include +#include "decomp.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "splinter.h" +#include "splinter_engine.h" +#include "mcp.h" +#include "i18n.h" +#include "log.h" +#include "splinter_plugin.h" +#include "config.h" +#include "providers.h" +#include "md.h" +#include "theme.h" +#include "ui.h" +#include "ui_backend.h" +#include "usage.h" +#include "swarm.h" + +/* + * Who is speaking. Not the role - the name: the person from $USER, the model + * from the engine. + */ +static char g_who[128] = "you"; +static char g_model[128] = "model"; + +#define MAX_ENTRIES 512 + +struct elayout; /* the wrapped lines of one entry, below */ + +/* one growing text of a turn: the reasoning, the answer */ +struct seg { + size_t id; /* entry showing the open part, 0 = none */ + size_t off; /* bytes before the open entry */ + size_t shown; /* bytes the open entry shows */ +}; + +struct entry { + char *role; + char *text; + time_t ts; /* when it arrived, for the IRC-style prefix */ + size_t id; /* stable across eviction; see add_entry */ + /* + * The wrapped lines, kept between frames. Wrapping a long transcript + * from scratch on every keystroke and every 100 ms tick was the reason + * the window felt slow: one frame cost as much as the whole log. + * Rebuilt only when the text or the width changed. + */ + struct elayout *cache; + int cache_cols; +}; + +/* + * What the screen knows. The engine owns the session, the model, the agent + * profile and the counters; sync_state() copies them here after every event + * that changed one, so drawing never asks the engine a question it may answer + * with a half-finished turn. + */ +struct ui_state { + const struct ui_backend *be; + struct entry entries[MAX_ENTRIES]; + size_t n; + size_t next_id; /* ids start at 1 */ + size_t scroll; /* lines scrolled back from the bottom */ + size_t scroll_max; /* maxscroll of the last frame */ + size_t scroll_base; /* maxscroll when the reader scrolled */ + long last_ms; + size_t tokens_in; + size_t tokens_out; + size_t last_steps; + size_t last_calls; + char hist[128][1024]; /* what was typed before */ + size_t nhist; + int hist_pos; /* -1: editing a fresh line */ + int last_day; /* for the "--- 2026-11-13 ---" line */ + char agent_name[48]; + struct sp_theme theme; + struct sp_config *conf; /* the engine's, for the sidebar */ + int quit; +}; + +static WINDOW *ui_hist; +static WINDOW *ui_side; +static WINDOW *ui_input; +/* + * The agent whose profile is active. The sidebar does not show it; with one + * text field the prompt carries the name, so "build> " says what Tab did. + */ +static char ui_agent[32]; + +enum { + PAIR_MAIN = 1, /* fg on bg */ + PAIR_ACCENT, /* accent */ + PAIR_DIM, /* border */ + PAIR_STATUS, /* hints and questions */ + PAIR_INPUT, /* the input line */ + PAIR_ERROR /* errors */ +}; + +/* the session id and directory the sidebar shows */ +#define SESS_ID(b) ((b)->session_id((b)->ctx)) +#define SESS_DIR(b) ((b)->state_dir((b)->ctx)) + +static void draw_history(struct ui_state *); +static void draw_sidebar(struct ui_state *, const char *, const char *, + struct sp_host *); +static size_t add_entry(struct ui_state *, const char *, const char *); +static void drain_idle(struct ui_state *); + +/* + * Cut a line for the screen and mark the cut. On a character boundary: the + * text is UTF-8, and half a sequence draws as garbage. + */ +static void +cut_line(char *s, size_t want) +{ + size_t n = strlen(s), cut = want; + + if (n <= want) + return; + while (cut > 0 && ((unsigned char)s[cut] & 0xc0) == 0x80) + cut--; + s[cut] = '\0'; + if (cut >= 3) + memcpy(s + cut - 3, "...", 3); +} + +/* the counters, the model and the profile, from the engine */ +static void +sync_state(struct ui_state *s) +{ + struct sp_engine_state st; + const char *slash; + size_t n; + + if (s->be->state(s->be->ctx, &st) != 0) + return; + s->tokens_in = st.tokens_in; + s->tokens_out = st.tokens_out; + s->last_ms = st.last_ms; + s->last_steps = st.last_steps; + s->last_calls = st.last_calls; + s->conf = s->be->config(s->be->ctx); + snprintf(ui_agent, sizeof(ui_agent), "%.24s", st.agent); + snprintf(s->agent_name, sizeof(s->agent_name), "%s", st.agent); + /* + * A path like /models/x/y.gguf: the name is the last part. A transport + * without a model (a plugin that answers itself) keeps the last name + * instead of showing an empty pair of angle brackets. + */ + slash = strrchr(st.model, '/'); + if (st.model[0] != '\0') + snprintf(g_model, sizeof(g_model), "%.120s", slash != NULL ? + slash + 1 : st.model); + n = strlen(g_model); + if (n > 4 && strcmp(g_model + n - 4, ".gguf") == 0) + g_model[n - 4] = '\0'; +} + +/* the prompt mark, always followed by one space */ +static const char * +prompt_mark(void) +{ + static char buf[64]; + const char *m = sp_t("ui.prompt_mark"); + size_t n = strlen(m); + + snprintf(buf, sizeof(buf), "%s%s%s", ui_agent, m, + n > 0 && m[n - 1] == ' ' ? "" : " "); + return buf; +} + +static short +rgb(const unsigned char c[3], short n) +{ + return sp_color_rgb(c[0], c[1], c[2], n); +} + +static void +init_colors(const struct sp_theme *t) +{ + short n; + + if (!has_colors()) + return; + /* COLORS is only valid after start_color() */ + start_color(); + n = (short)(COLORS > 0 ? COLORS : 8); + if (t->indexed) { + short accent = n >= 16 ? t->idx_accent : COLOR_BLUE; + short dim = n >= 16 ? t->idx_border : COLOR_WHITE; + short errc = n >= 16 ? t->idx_error : COLOR_RED; + + init_pair(PAIR_MAIN, t->idx_fg, t->idx_bg); + init_pair(PAIR_ACCENT, accent, t->idx_bg); + init_pair(PAIR_DIM, dim, t->idx_bg); + init_pair(PAIR_STATUS, t->idx_bg, t->idx_fg); + init_pair(PAIR_INPUT, t->idx_fg, t->idx_bg); + init_pair(PAIR_ERROR, errc, t->idx_bg); + return; + } + init_pair(PAIR_MAIN, rgb(t->fg, n), rgb(t->bg, n)); + init_pair(PAIR_ACCENT, rgb(t->accent, n), rgb(t->bg, n)); + init_pair(PAIR_DIM, rgb(t->border, n), rgb(t->bg, n)); + init_pair(PAIR_STATUS, rgb(t->status_fg, n), rgb(t->status, n)); + init_pair(PAIR_INPUT, rgb(t->input_fg, n), rgb(t->input_bg, n)); + init_pair(PAIR_ERROR, rgb(t->error, n), rgb(t->bg, n)); +} + +/* + * Text goes to curses as ASCII. + * + * Measured, not assumed: the vendored NetBSD curses emits Latin-1 bytes for + * wide characters (ü -> 0xFC) instead of re-encoding to the locale charset, so + * UTF-8 would reach the terminal as mojibake. ncurses passes the bytes through; + * this port does not. Until that is fixed in the library, the UI transliterates + * and the data keeps its exact UTF-8. + * + * iconv(3) does the work, with //TRANSLIT: a hand-written table turned German + * typography into question marks (— “ ” … all became '?'), which is how a + * readable answer turns into noise. Characters that cannot be transliterated + * become '?' - one per character, never silently dropped. + */ +static const struct sp_decomp * +decomp_find(unsigned int cp) +{ + size_t lo = 0, hi = sp_decomp_count; + + while (lo < hi) { + size_t mid = (lo + hi) / 2; + + if (sp_decomp_table[mid].cp == cp) + return &sp_decomp_table[mid]; + if (sp_decomp_table[mid].cp < cp) + lo = mid + 1; + else + hi = mid; + } + return NULL; +} + +/* Decode one UTF-8 sequence; returns bytes consumed, or 0 on a broken byte. */ +static size_t +utf8_next(const unsigned char *s, size_t left, unsigned int *cp) +{ + if (left == 0) + return 0; + if (s[0] < 0x80) { + *cp = s[0]; + return 1; + } + if ((s[0] & 0xe0) == 0xc0 && left >= 2) { + *cp = ((unsigned int)(s[0] & 0x1f) << 6) | (s[1] & 0x3f); + return 2; + } + if ((s[0] & 0xf0) == 0xe0 && left >= 3) { + *cp = ((unsigned int)(s[0] & 0x0f) << 12) | + ((unsigned int)(s[1] & 0x3f) << 6) | (s[2] & 0x3f); + return 3; + } + if ((s[0] & 0xf8) == 0xf0 && left >= 4) { + *cp = ((unsigned int)(s[0] & 0x07) << 18) | + ((unsigned int)(s[1] & 0x3f) << 12) | + ((unsigned int)(s[2] & 0x3f) << 6) | (s[3] & 0x3f); + return 4; + } + return 0; +} + +/* + * UTF-8 -> ASCII for the screen. + * + * Two mechanisms, and the split is the point: letters come from a table + * generated out of Unicode's decompositions (glibc's iconv transliterates "ß" + * but turns "ü" into "?"), punctuation goes through iconv (— becomes --, … + * becomes ...). A character neither can express becomes one '?' — visible, not + * silently dropped. + * + * The conversation and the session log keep the exact UTF-8; only the screen + * is ASCII, because this curses port writes Latin-1 bytes for wide characters. + */ +int +sp_ui_ascii(const char *in, char *out, size_t cap) +{ + iconv_t cd; + const unsigned char *s; + size_t left, used = 0; + int rc = 0; + + if (in == NULL || out == NULL || cap == 0) + return -1; + cd = iconv_open("ASCII//TRANSLIT", "UTF-8"); + s = (const unsigned char *)in; + left = strlen(in); + + while (left > 0) { + unsigned int cp = 0; + size_t n = utf8_next(s, left, &cp); + const char *rep = NULL; + char tmp[16]; + + if (n == 0) { /* broken byte: one '?' and move on */ + if (used + 2 > cap) { + rc = -1; + break; + } + out[used++] = '?'; + s++; + left--; + continue; + } + if (cp < 0x80) { + tmp[0] = (char)cp; + tmp[1] = '\0'; + rep = tmp; + } else { + const struct sp_decomp *d = decomp_find(cp); + + if (d != NULL) { + rep = d->ascii; + } else if (cd != (iconv_t)-1) { + char *ip = (char *)s, *op = tmp; + size_t il = n, ol = sizeof(tmp) - 1; + + if (iconv(cd, &ip, &il, &op, &ol) != (size_t)-1) { + *op = '\0'; + rep = tmp; + } + } + if (rep == NULL) + rep = "?"; + } + { + size_t rl = strlen(rep); + + if (used + rl + 1 > cap) { + rc = -1; + break; + } + memcpy(out + used, rep, rl); + used += rl; + } + s += n; + left -= n; + } + out[used] = '\0'; + if (cd != (iconv_t)-1) + iconv_close(cd); + return rc; +} + +static void +ui_add_text(WINDOW *w, const char *s, int maxcols) +{ + char out[1024]; + + if (s == NULL) + return; + if (sp_ui_ascii(s, out, sizeof(out)) != 0) + snprintf(out, sizeof(out), "%.900s", s); + waddnstr(w, out, maxcols); +} + + + +/* A role is stored as its English key and displayed in the chosen language. */ +static const char * +role_label(const char *role) +{ + char key[48]; + const char *t; + + if (role == NULL) + return ""; + snprintf(key, sizeof(key), "role.%s", role); + t = sp_t(key); + if (t == NULL || strcmp(t, key) == 0) + return role; + return t; +} + +/* + * Row accounting for text that contains newlines. + * + * The first version counted rows as strlen()/cols, which is only true for one + * long line. A model's reasoning is full of newlines, so the real height was + * much larger than the estimate and the text painted over the answer below it - + * "it just goes anywhere on the screen". Every row is therefore computed from + * the actual line structure: split on '\n', then wrap each line. + */ +size_t sp_ui_ascii_char(const char *s, char *out, size_t cap); + +/* + * Rows an entry really occupies: the role prefix shortens the first row, so the + * height is computed from exactly the string that gets drawn ("role: text"), + * not from the text plus an estimate. Getting this wrong lost the last + * character of an entry - a truncated ``` closing a code block. + */ +/* + * IRC shape, as asked for: a timestamp, then who is speaking. + * + * [15:20:13] der text + * [15:20:14] * agent is thinking ... + * [15:20:31] die antwort + * + * A timestamp is cheap and makes a transcript readable hours later; without one + * every old line looks like it happened just now. + */ +static void +entry_prefix(const struct entry *e, char *buf, size_t len) +{ + struct tm tm; + char clock[16], who[64]; + + (void)localtime_r(&e->ts, &tm); + strftime(clock, sizeof(clock), "%H:%M:%S", &tm); + if (strcmp(e->role, "thinking") == 0) { + /* no '*': the markdown pass would eat it as emphasis */ + snprintf(buf, len, "[%s] ~ %s: ", clock, sp_t("ui.thinking")); + } else if (strcmp(e->role, "you") == 0) { + snprintf(who, sizeof(who), "%.40s", g_who); + snprintf(buf, len, "[%s] <%s> ", clock, who); + } else if (strcmp(e->role, "agent") == 0) { + snprintf(who, sizeof(who), "%.40s", g_model); + { + char *dot = strstr(who, ".gguf"); + + if (dot != NULL) + *dot = '\0'; + } + snprintf(buf, len, "[%s] <%s> ", clock, who); + } else if (strcmp(e->role, "tool") == 0) { + snprintf(buf, len, "[%s] >> ", clock); + } else if (strcmp(e->role, "observation") == 0) { + snprintf(buf, len, "[%s] | ", clock); + } else if (strcmp(e->role, "splinter") == 0) { + snprintf(buf, len, "[%s] --- ", clock); + } else { + snprintf(who, sizeof(who), "%.40s", role_label(e->role)); + snprintf(buf, len, "[%s] <%s> ", clock, who); + } +} + + +/* + * Markdown, the little of it a chat actually contains. + * + * **bold** *italic* `code` # heading ``` fence + * + * The markers are removed before anything is measured, because a line measured + * with its asterisks wraps in a different place than the one that is drawn. Each + * kept character carries an attribute, so a bold word stays bold across a wrap. + * + * Fence blocks are drawn dim and their marker lines disappear: an answer full of + * C code should look like code, not like three backticks around code. + */ +#define MD_BOLD 0x01 +#define MD_ITALIC 0x02 +#define MD_CODE 0x04 + +/* + * Is the '*' run at p (len 1 or 2) emphasis, or just an asterisk? The rules of + * CommonMark, short: an opener is followed by text and preceded by a space or + * punctuation, a closer is preceded by text, and an opener needs its closer on + * the same line. Without this "void *ctx, const char *name" in a code answer + * lost its pointers and came out italic. + */ +static int +emph_ok(const char *start, const char *p, int len, int open_now, int in_code) +{ + char prev = p > start ? p[-1] : ' '; + char next = p[len]; + int prev_space = prev == ' ' || prev == '\t' || prev == '\n'; + int next_space = next == '\0' || next == ' ' || next == '\t' || + next == '\n'; + const char *q; + + if (in_code) + return 0; + if (open_now) /* a closer: it must follow text */ + return !prev_space; + if (next_space) /* an opener: it must precede text */ + return 0; + if (!(prev_space || strchr("([{\"'-,.;:/", prev) != NULL)) + return 0; + /* + * ... and a closer must follow on this line before another opener does: + * the nearest opener takes the closer, the earlier ones stay asterisks. + */ + for (q = p + len; *q != '\0' && *q != '\n'; q++) { + int rl = 0; + + if (*q != '*') + continue; + while (q[rl] == '*') + rl++; + if (rl == len) { + char pq = q[-1], nq = q[rl]; + + if (pq != ' ' && pq != '\t') + return 1; /* a closer */ + if (nq != '\0' && nq != ' ' && nq != '\t' && nq != '\n') + return 0; /* a nearer opener */ + } + q += rl - 1; + } + return 0; +} + +static size_t +md_strip_n(const char *in, char *out, unsigned char *attr) +{ + size_t o = 0; + int bold = 0, italic = 0, code = 0, fence = 0; + const char *p = in != NULL ? in : ""; + + while (*p != '\0') { + /* a fence line is a mode switch, not text */ + if ((p[0] == '`' && p[1] == '`' && p[2] == '`') && + (p == in || p[-1] == '\n')) { + fence = !fence; + while (*p != '\0' && *p != '\n') + p++; + continue; + } + if (*p == '\n') { + out[o] = '\n'; + attr[o++] = fence ? MD_CODE : 0; + p++; + bold = italic = code = 0; + continue; + } + if (p[0] == '#' && (p == in || p[-1] == '\n')) { + while (*p == '#') + p++; + while (*p == ' ') + p++; + bold = 1; + continue; + } + if (!fence && p[0] == '*' && p[1] == '*' && + emph_ok(in, p, 2, bold, code)) { + bold = !bold; + p += 2; + continue; + } + if (!fence && *p == '`') { + code = !code; + p++; + continue; + } + /* + * Only the asterisk marks italics. An underscore is part of names: + * Qwen3.6-35B-A3B-UD-Q8_K_XL came out as Qwen3.6-35B-A3B-UD-Q8KX, + * which is a different model as far as a reader is concerned. + */ + if (!fence && *p == '*' && emph_ok(in, p, 1, italic, code)) { + italic = !italic; + p++; + continue; + } + out[o] = *p; + attr[o] = (unsigned char)((fence ? MD_CODE : 0) | + (bold ? MD_BOLD : 0) | (italic ? MD_ITALIC : 0) | + (code ? MD_CODE : 0)); + o++; + p++; + } + out[o] = '\0'; + attr[o] = 0; + return o; +} + +static int +md_prepare(const char *in, char **plain_out, unsigned char **attr_out) +{ + struct sp_buf tb; + const char *src; + size_t n; + + *plain_out = NULL; + *attr_out = NULL; + if (sp_buf_init(&tb) != 0) + return -1; + if (sp_md_table_format(in, &tb) < 0) { + sp_buf_free(&tb); + return -1; + } + src = tb.len > 0 ? tb.p : (in != NULL ? in : ""); + n = strlen(src); + *plain_out = malloc(n + 1); + *attr_out = malloc(n + 1); + if (*plain_out == NULL || *attr_out == NULL) { + free(*plain_out); + free(*attr_out); + *plain_out = NULL; + *attr_out = NULL; + sp_buf_free(&tb); + return -1; + } + md_strip_n(src, *plain_out, *attr_out); + sp_buf_free(&tb); + return 0; +} + +/* + * One character of 's', UTF-8 or not, as ASCII in 'out'; returns how many bytes + * of 's' it took (at least 1 unless *s is NUL). + * + * A UTF-8 character is one unit. Handing sp_ui_ascii a single byte of a two-byte + * sequence produced '??hler' where 'Zaehler' belonged - the transliteration + * needs the whole character. The copy of that character used to live in a + * char[2] on md_draw's stack, and a three- or four-byte character ('...', an + * emoji) wrote past it on every redraw. + */ +size_t +sp_ui_ascii_char(const char *s, char *out, size_t cap) +{ + char one[5]; /* four UTF-8 bytes and the NUL */ + size_t len = 1, k; + unsigned char c = (unsigned char)s[0]; + + if (cap == 0) + return c != 0 ? 1 : 0; + out[0] = '\0'; + if (c == 0) + return 0; + if (c < 0x80) { + if (cap > 1) { + out[0] = (char)c; + out[1] = '\0'; + } + return 1; + } + if ((c & 0xe0) == 0xc0) + len = 2; + else if ((c & 0xf0) == 0xe0) + len = 3; + else if ((c & 0xf8) == 0xf0) + len = 4; + for (k = 0; k < len && s[k] != '\0'; k++) + one[k] = s[k]; + one[k] = '\0'; + if (sp_ui_ascii(one, out, cap) != 0 && cap > 1) { + out[0] = '?'; + out[1] = '\0'; + } + return k; +} + + +/* + * The history pane, laid out once and drawn from that layout. + * + * The earlier version counted rows in one function and drew in another, and + * the two disagreed (the scroll offset was a byte count, the wrap a column + * count), which is why text landed in "zones" and scrolling jumped. Here an + * entry is turned into visual lines exactly once -- word wrapped, with the + * continuation lines hanging under the text -- and both the height and the + * drawing read that same list. + */ +struct vline { + size_t beg, end; /* bytes of the plain text */ + int indent; /* columns left of the text */ +}; + +struct elayout { + char *plain; + unsigned char *attr; + struct vline *v; + size_t n, cap; + int blank; /* a gap before this entry */ +}; + +static int +vl_add(struct elayout *l, size_t beg, size_t end, int indent) +{ + if (l->n == l->cap) { + size_t nc = l->cap != 0 ? l->cap * 2 : 16; + struct vline *nv = realloc(l->v, nc * sizeof(*nv)); + + if (nv == NULL) + return -1; + l->v = nv; + l->cap = nc; + } + l->v[l->n].beg = beg; + l->v[l->n].end = end; + l->v[l->n].indent = indent; + l->n++; + return 0; +} + +/* Word wrap 'p' into 'l'; every line but the first hangs under 'ind'. */ +static void +wrap_text(struct elayout *l, const char *p, int cols, int ind) +{ + size_t i = 0; + int first = 1; + + for (;;) { + int indent = first ? 0 : ind; + size_t avail = (size_t)(cols - indent > 0 ? cols - indent : 1); + size_t beg = i, end, w = 0, brk = 0; + int haveb = 0, wrapped = 0; + + for (;;) { + char o[8]; + size_t n, cw; + + if (p[i] == '\0' || p[i] == '\n') { + end = i; + break; + } + n = sp_ui_ascii_char(p + i, o, sizeof(o)); + if (n == 0) + n = 1; + cw = strlen(o); + if (w + cw > avail && i > beg) { + wrapped = 1; + if (haveb && brk > beg) { + end = brk; + i = brk; + } else + end = i; + break; + } + if (p[i] == ' ' && !(i > beg && p[i - 1] == ' ')) { + brk = i; + haveb = 1; + } + w += cw; + i += n; + } + if (vl_add(l, beg, end, indent) != 0) + return; + first = 0; + if (wrapped) { + while (p[i] == ' ') + i++; + if (p[i] == '\n') + i++; + if (p[i] == '\0') + break; + continue; + } + if (p[i] == '\0') + break; + i++; /* the newline */ + } +} + +static void +elayout_free(struct elayout *l) +{ + free(l->plain); + free(l->attr); + free(l->v); + memset(l, 0, sizeof(*l)); +} + +/* the visual lines of one entry, prefix included; cached in the entry */ +static struct elayout * +entry_layout(struct entry *e, int cols) +{ + char prefix[256]; + char *render; + size_t len; + int ind; + const char *brk; + struct elayout *l; + + if (e->cache != NULL && e->cache_cols == cols) + return e->cache; + if (e->cache == NULL) { + e->cache = calloc(1, sizeof(*e->cache)); + if (e->cache == NULL) + return NULL; + } else + elayout_free(e->cache); + l = e->cache; + e->cache_cols = cols; + entry_prefix(e, prefix, sizeof(prefix)); + /* a table that starts the answer must not start behind the prefix */ + brk = sp_md_table_starts(e->text) ? "\n" : ""; + len = strlen(prefix) + strlen(brk) + strlen(e->text) + 1; + render = malloc(len); + if (render == NULL) + return l; + snprintf(render, len, "%s%s%s", prefix, brk, e->text); + if (md_prepare(render, &l->plain, &l->attr) != 0) { + free(l->plain); + free(l->attr); + l->plain = render; + l->attr = NULL; + } else + free(render); + /* + * Chat lines hang under their text. Command output, shell output and + * diffs are columns the author laid out: shifting them would break them. + */ + if (strcmp(e->role, "splinter") == 0 || strcmp(e->role, "shell") == 0) + ind = 0; + else { + ind = (int)strlen(prefix); + if (ind > 24) + ind = 24; + if (ind > cols / 3) + ind = cols / 3; + } + wrap_text(l, l->plain, cols, ind); + /* blank lines at the end are not content */ + while (l->n > 1 && l->v[l->n - 1].beg == l->v[l->n - 1].end) + l->n--; + return l; +} + +static void +draw_vline(int y, const struct elayout *l, const struct vline *vl) +{ + attr_t base; + short pair; + size_t i; + int x = 1 + vl->indent; + + (void)wattr_get(ui_hist, &base, &pair, NULL); + base &= ~A_COLOR; + for (i = vl->beg; i < vl->end;) { + char o[8]; + unsigned a = l->attr != NULL ? l->attr[i] : 0; + attr_t at = base; + size_t n = sp_ui_ascii_char(l->plain + i, o, sizeof(o)); + + if (n == 0) + n = 1; + if (a & MD_BOLD) + at |= A_BOLD; + if (a & MD_ITALIC) + at |= A_UNDERLINE; + (void)wattr_set(ui_hist, at, (a & MD_CODE) ? PAIR_DIM : pair, NULL); + mvwaddstr(ui_hist, y, x, o); + x += (int)strlen(o); + i += n; + } + (void)wattr_set(ui_hist, base, pair, NULL); +} + +static void +draw_history(struct ui_state *s) +{ + int rows, cols, y = 0; + size_t idx, total = 0, first, line = 0, maxscroll; + struct elayout *l; + unsigned char *blank; + + getmaxyx(ui_hist, rows, cols); + cols -= 2; /* padding left and right */ + werase(ui_hist); + wbkgd(ui_hist, COLOR_PAIR(PAIR_MAIN)); + if (s->n == 0 || cols < 2 || rows < 1) { + wnoutrefresh(ui_hist); + return; + } + blank = calloc(s->n, 1); + if (blank == NULL) { + wnoutrefresh(ui_hist); + return; + } + for (idx = 0; idx < s->n; idx++) { + l = entry_layout(&s->entries[idx], cols); + if (l == NULL) + continue; + /* a new question starts a new exchange: one line of air */ + blank[idx] = idx > 0 && strcmp(s->entries[idx].role, "you") == 0; + total += l->n + (size_t)blank[idx]; + } + maxscroll = total > (size_t)rows ? total - (size_t)rows : 0; + /* scrolled up and text arrived below: keep the reader where he is */ + if (s->scroll > 0 && s->scroll <= s->scroll_max && + maxscroll > s->scroll_base) + s->scroll += maxscroll - s->scroll_base; + if (s->scroll > maxscroll) + s->scroll = maxscroll; + s->scroll_max = maxscroll; + s->scroll_base = maxscroll - s->scroll; + first = maxscroll - s->scroll; /* index of the top visible line */ + + for (idx = 0; idx < s->n && y < rows; idx++) { + const struct entry *e = &s->entries[idx]; + size_t k; + + if (strcmp(e->role, "you") == 0) + wattrset(ui_hist, COLOR_PAIR(PAIR_ACCENT) | A_BOLD); + else if (strcmp(e->role, "agent") == 0) + wattrset(ui_hist, COLOR_PAIR(PAIR_MAIN)); + else if (strcmp(e->role, "error") == 0) + wattrset(ui_hist, COLOR_PAIR(PAIR_ERROR) | A_BOLD); + /* + * A call is the interesting line of a tool step: what the tool + * returned is reference material under it. Painted with it, the + * transcript read as one grey wall of "Run". + */ + else if (strcmp(e->role, "tool") == 0) + wattrset(ui_hist, COLOR_PAIR(PAIR_ACCENT)); + else + wattrset(ui_hist, COLOR_PAIR(PAIR_DIM)); + if (blank[idx]) { + if (line >= first && y < rows) + y++; + line++; + } + l = s->entries[idx].cache; + if (l == NULL) + continue; + for (k = 0; k < l->n && y < rows; k++, line++) { + if (line < first) + continue; + draw_vline(y, l, &l->v[k]); + y++; + } + wattrset(ui_hist, A_NORMAL); + } + free(blank); + wnoutrefresh(ui_hist); +} + +/* + * The streaming turn is drawn as the last thing in the history pane: the tail + * of what has arrived so far. It is not an entry yet - entries are what was + * completed, and mixing the two would make the log look like it changed. + */ +/* + * While a turn runs, the left pane shows what the harness is doing, in the same + * place the conversation lives: the model's reasoning dimmed above, the answer + * as it arrives below. The sidebar keeps the counters - numbers are not text. + */ +static void +sidebar_heading(int *y, int cols, const char *text) +{ + wattron(ui_side, COLOR_PAIR(PAIR_DIM) | A_BOLD); + mvwaddnstr(ui_side, *y, 0, text, cols - 1); + wattroff(ui_side, A_BOLD); + (*y)++; + wattron(ui_side, COLOR_PAIR(PAIR_MAIN)); +} + +/* wrap 'text' into the sidebar from row *y, at most 'maxrows' rows */ +static void +side_text(int *y, int cols, const char *text, int maxrows) +{ + int rows = 0; + + while (*text != '\0' && rows < maxrows && *y < getmaxy(ui_side)) { + size_t n = strlen(text), take = n; + + if (take > (size_t)cols - 1) { + take = (size_t)cols - 1; + while (take > 0 && text[take] != ' ') + take--; + if (take == 0) + take = (size_t)cols - 1; + } + mvwaddnstr(ui_side, (*y)++, 0, text, (int)take); + rows++; + text += take; + while (*text == ' ') + text++; + } +} + +/* + * A path, wrapped at its slashes: "/home/k/src/splinter/plugins" cuts after a + * "/", never in the middle of a name. A path is what the operator checks first + * when a tool wrote somewhere it should not have. + */ +static void +side_path(int *y, int cols, const char *path, int maxrows) +{ + int rows = 0; + size_t len = strlen(path), off = 0; + size_t width = (size_t)cols - 1; + + if (width < 4) + width = 4; + while (off < len && rows < maxrows && *y < getmaxy(ui_side)) { + size_t take = len - off, cut; + + if (take > width) { + take = width; + cut = take; + while (cut > 0 && path[off + cut] != '/') + cut--; + if (cut == 0) + take = width; /* no slash in reach: hard cut */ + else + take = cut + 1; /* keep the slash on this line */ + } + mvwaddnstr(ui_side, (*y)++, 0, path + off, (int)take); + off += take; + rows++; + } +} + +static void +draw_sidebar(struct ui_state *s, const char *id, const char *dir, + struct sp_host *host) +{ + int cols, y = 0; + char key[64]; + const char *act = sp_usage_active(); + + if (ui_side == NULL) + return; /* one text field: no sidebar */ + + (void)dir; + cols = getmaxx(ui_side); + werase(ui_side); + + /* who is answering: the profile, the provider, the model */ + sidebar_heading(&y, cols, sp_t("sidebar.model")); + if (s->agent_name[0] != '\0') { + wattron(ui_side, A_BOLD); + { + char tag[64]; + + snprintf(tag, sizeof(tag), "[%s]", s->agent_name); + mvwaddnstr(ui_side, y++, 0, tag, cols - 1); + } + wattroff(ui_side, A_BOLD); + } + { + char line[300]; + + /* + * The provider belongs to the run's config. In --attach mode there + * is none in this process, and "main / m" would name a provider + * the server may not be using. + */ + if (s->conf != NULL && act != NULL && *act != '\0') + snprintf(line, sizeof(line), "%s / %.120s", act, g_model); + else + snprintf(line, sizeof(line), "%.200s", g_model); + side_text(&y, cols, line, 2); + } + y++; + + /* + * How much of each allowance is used. A remote backend has no config + * here (the counters live in the server's process), and printing the + * client's own zeroes would be a lie: show nothing then. + */ + if (s->conf != NULL) { + const struct sp_config *cfg = s->conf; + struct sp_usage u; + size_t i; + int printed = 0; + char brief[96], line[200]; + + for (i = 0; i <= (cfg != NULL ? cfg->ndelegates : 0); i++) { + const char *pid = i == 0 ? act : cfg->delegate[i - 1].id; + + if (i > 0 && strcmp(pid, act) == 0) + continue; + sp_usage_for(cfg, pid, &u); + if (i > 0 && u.frac < 0 && u.benched_until == 0) + continue; + if (!printed) { + sidebar_heading(&y, cols, sp_t("sidebar.usage")); + printed = 1; + } + sp_usage_brief(&u, brief, sizeof(brief)); + snprintf(line, sizeof(line), "%-9.9s %s", pid, brief); + if (u.frac >= 0.9 || u.benched_until > 0) + wattron(ui_side, COLOR_PAIR(PAIR_ACCENT) | A_BOLD); + if (y < getmaxy(ui_side)) + mvwaddnstr(ui_side, y++, 0, line, cols - 1); + wattrset(ui_side, COLOR_PAIR(PAIR_MAIN)); + } + if (printed) + y++; + } + + /* what the plugins want to show: the goal, the plan, tasks ... */ + if (host != NULL && sp_host_widget_count(host) > 0) { + char snap[1024], *line, *save = NULL; + + sp_host_widget_snapshot(host, snap, sizeof(snap)); + for (line = strtok_r(snap, "\n", &save); line != NULL; + line = strtok_r(NULL, "\n", &save)) { + char name[48], *colon = strchr(line, ':'); + char *text; + size_t nl; + + if (colon == NULL) + continue; + nl = (size_t)(colon - line); + if (nl >= sizeof(name)) + continue; + memcpy(name, line, nl); + name[nl] = '\0'; + text = colon + 1; + while (*text == ' ') + text++; + /* a text that repeats its own name ("plan: 0 tasks") */ + if (strncmp(text, name, nl) == 0 && text[nl] == ':') { + text += nl + 1; + while (*text == ' ') + text++; + } + if (*text == '\0' || y >= getmaxy(ui_side) - 2) + continue; + snprintf(key, sizeof(key), "widget.%s", name); + sidebar_heading(&y, cols, sp_td(key, name)); + side_text(&y, cols, text, 4); + y++; + } + } + + /* the last turn, in one line - two where the column is narrow */ + if (s->last_ms > 0 && y < getmaxy(ui_side) - 2) { + char line[160]; + + sidebar_heading(&y, cols, sp_t("sidebar.last_turn")); + snprintf(line, sizeof(line), sp_t("sidebar.turn_line"), + (double)s->last_ms / 1000.0, s->last_steps, s->last_calls); + side_text(&y, cols, line, 2); + if (s->tokens_out > 0) { + snprintf(line, sizeof(line), sp_t("sidebar.tokens"), + s->tokens_out, s->tokens_in); + side_text(&y, cols, line, 1); + } + y++; + } + + if (id != NULL && y < getmaxy(ui_side) - 2) { + sidebar_heading(&y, cols, sp_t("sidebar.session")); + wattron(ui_side, COLOR_PAIR(PAIR_DIM)); + side_text(&y, cols, id, 1); + } + /* + * Where this splinter runs. Every tool acts relative to it, so it has to + * be on screen: a delegate that wrote into the wrong tree was the one + * question nobody could answer from the screen. $HOME is shown as ~. + */ + { + char cwd[700], shown[760]; + const char *home = getenv("HOME"); + + if (getcwd(cwd, sizeof(cwd)) != NULL) { + if (home != NULL && *home != '\0' && + strncmp(cwd, home, strlen(home)) == 0 && + (cwd[strlen(home)] == '/' || cwd[strlen(home)] == '\0')) + snprintf(shown, sizeof(shown), "~%s", cwd + strlen(home)); + else + snprintf(shown, sizeof(shown), "%s", cwd); + sidebar_heading(&y, cols, sp_t("sidebar.cwd")); + wattron(ui_side, COLOR_PAIR(PAIR_DIM)); + side_path(&y, cols, shown, 4); + } + } + wattrset(ui_side, A_NORMAL); + + wnoutrefresh(ui_side); +} + +/* + * Feed the meter the status plugins read. The harness counts; a plugin must not + * count for itself or the two numbers drift apart. + */ +/* the UI's fields of the meter; the tasks plugin owns others */ +static void +set_ui_fields(struct sp_meter *m, void *ctx) +{ + const struct ui_state *s = ctx; + const char *ctxmax = getenv("SPLINTER_CTX_MAX"); + + m->ctx_used = s->tokens_in; + if (ctxmax != NULL && *ctxmax != '\0') + m->ctx_max = (size_t)strtoul(ctxmax, NULL, 10); + m->tok_in = s->tokens_in; + m->tok_out = s->tokens_out; + if (s->last_ms > 0 && s->tokens_out > 0) + m->tps = (long)((double)s->tokens_out * 1000.0 / + (double)s->last_ms); +} + +static void +update_meter(struct ui_state *s, struct sp_host *host) +{ + if (host != NULL) + sp_host_meter_update(host, set_ui_fields, s); +} + + +static void +hist_load(struct ui_state *s, const char *dir) +{ + char path[600]; + FILE *f; + + if (dir == NULL) + return; + snprintf(path, sizeof(path), "%s/history", dir); + f = fopen(path, "r"); + if (f == NULL) + return; + while (s->nhist < 128 && fgets(s->hist[s->nhist], 1024, f) != NULL) { + s->hist[s->nhist][strcspn(s->hist[s->nhist], "\r\n")] = '\0'; + if (s->hist[s->nhist][0] != '\0') + s->nhist++; + } + fclose(f); + s->hist_pos = -1; +} + +static void +hist_push(struct ui_state *s, const char *dir, const char *line) +{ + char path[600]; + FILE *f; + + if (line == NULL || line[0] == '\0') + return; + /* typing the same thing twice in a row is not two history entries */ + if (s->nhist > 0 && strcmp(s->hist[s->nhist - 1], line) == 0) + return; + if (s->nhist == 128) { + memmove(&s->hist[0], &s->hist[1], sizeof(s->hist[0]) * 127); + s->nhist--; + } + snprintf(s->hist[s->nhist], 1024, "%s", line); + s->nhist++; + s->hist_pos = -1; + + if (dir == NULL) + return; + snprintf(path, sizeof(path), "%s/history", dir); + f = fopen(path, "a"); + if (f == NULL) + return; + fprintf(f, "%s\n", line); + fclose(f); +} + +/* Replace an entry's text in place: a streaming turn keeps one entry per role + * and rewrites it, so the transcript grows where the reader is looking. */ +static void +entry_set_text(struct ui_state *s, size_t id, const char *text) +{ + char *copy; + size_t i; + + for (i = s->n; i > 0; i--) /* the live entry is near the end */ + if (s->entries[i - 1].id == id) + break; + if (i == 0) + return; /* evicted meanwhile: nothing to do */ + copy = strdup(text != NULL ? text : ""); + if (copy == NULL) + return; + free(s->entries[i - 1].text); + s->entries[i - 1].text = copy; + /* the wrapped lines belong to the old text */ + if (s->entries[i - 1].cache != NULL) { + elayout_free(s->entries[i - 1].cache); + free(s->entries[i - 1].cache); + s->entries[i - 1].cache = NULL; + } +} + +/* + * Append an entry and return its id. Callers that update an entry later (the + * live answer, the reasoning) keep the id, not the index: at MAX_ENTRIES the + * oldest entry is evicted and every index moves by one - the streamed answer + * then went into the wrong entry, or into none. + */ +static size_t +add_entry(struct ui_state *s, const char *role, const char *text) +{ + struct entry *e; + size_t id; + + if (s->n == MAX_ENTRIES) { + free(s->entries[0].role); + free(s->entries[0].text); + if (s->entries[0].cache != NULL) { + elayout_free(s->entries[0].cache); + free(s->entries[0].cache); + } + memmove(&s->entries[0], &s->entries[1], + sizeof(s->entries[0]) * (MAX_ENTRIES - 1)); + s->n--; + } + e = &s->entries[s->n++]; + e->role = strdup(role != NULL ? role : "?"); + e->text = strdup(text != NULL ? text : ""); + if (e->role == NULL || e->text == NULL) { + /* out of memory: an entry with no text is better than a NULL */ + free(e->role); + free(e->text); + s->n--; + return 0; + } + e->ts = time(NULL); + e->id = id = ++s->next_id; + e->cache = NULL; + e->cache_cols = 0; + { + struct tm tm; + int day; + + (void)localtime_r(&e->ts, &tm); + day = tm.tm_yday + tm.tm_year * 400; + if (s->last_day != 0 && day != s->last_day) { + char stamp[64]; + struct entry *d; + + /* + * The day changed while splinter was running. Say it once, in + * the chat, so a transcript that spans midnight still reads in + * order - and never again until it changes again. + */ + strftime(stamp, sizeof(stamp), "--- %Y-%m-%d ---", &tm); + if (s->n < MAX_ENTRIES) { + d = &s->entries[s->n]; + d->role = strdup("splinter"); + d->text = strdup(stamp); + if (d->role != NULL && d->text != NULL) { + d->ts = e->ts; + d->id = ++s->next_id; + d->cache = NULL; + d->cache_cols = 0; + s->n++; + } else { + free(d->role); + free(d->text); + } + } + } + s->last_day = day; + } + return id; +} + +static void +layout(void) +{ + int rows, cols; + + getmaxyx(stdscr, rows, cols); + /* + * The conversation on three quarters, the sidebar on the last one, the + * input below both. The conversation starts at the top and grows + * downward; what was written stays where it is. + */ + { + int side_w = cols / 4; + int chat_w = cols - side_w - 1; + + if (side_w < 18) + side_w = cols > 50 ? 18 : 0; + if (side_w == 0) + chat_w = cols; + ui_hist = newwin(rows - 1, chat_w, 0, 0); + ui_side = side_w > 0 ? + newwin(rows - 1, side_w, 0, chat_w + 1) : NULL; + } + wbkgd(ui_hist, COLOR_PAIR(PAIR_MAIN)); + ui_input = newwin(1, cols, rows - 1, 0); + wbkgd(ui_input, COLOR_PAIR(PAIR_INPUT)); + keypad(ui_input, TRUE); + /* a one-line window that may scroll is a screen that jumps */ + scrollok(ui_input, FALSE); +} + +/* + * The terminal changed size: the windows were cut for the old one. layout() + * used to run once, so after a resize the four windows kept their old + * geometry and drew over each other. + */ +static void +relayout(int input_timeout_ms) +{ + if (ui_hist != NULL) + delwin(ui_hist); + if (ui_side != NULL) + delwin(ui_side); + if (ui_input != NULL) + delwin(ui_input); + ui_hist = ui_side = ui_input = NULL; + layout(); + wtimeout(ui_input, input_timeout_ms); + clearok(curscr, TRUE); +} + +/* history, sidebar and status line, then one doupdate() */ +static void +redraw(struct ui_state *s, const struct ui_backend *be) +{ + draw_history(s); + draw_sidebar(s, SESS_ID(be), SESS_DIR(be), be->host(be->ctx)); + doupdate(); +} + +/* the prompt line with what has been typed so far */ +static void +draw_prompt(const char *input) +{ + const char *mark = prompt_mark(); + char *ascii; + size_t n, avail, cap; + int w = getmaxx(ui_input); + + werase(ui_input); + mvwaddstr(ui_input, 0, 0, mark); + /* + * The line is one row and never wraps: when the text is longer than the + * room, the end of it stays visible and the start scrolls out to the + * left. The last column stays empty -- writing into the bottom-right + * cell of a window that cannot scroll is an error in curses, and in + * this port a crash. + */ + avail = (size_t)(w - (int)strlen(mark) - 2); + if (input == NULL || w < 8 || avail < 1) + return; + cap = strlen(input) * 4 + 16; + ascii = malloc(cap); + if (ascii == NULL) + return; + if (sp_ui_ascii(input, ascii, cap) != 0) + snprintf(ascii, cap, "%s", input); + n = strlen(ascii); + if (n > avail) + waddnstr(ui_input, ascii + (n - avail), (int)avail); + else + waddnstr(ui_input, ascii, (int)n); + free(ascii); +} + +/* + * Read one line at the prompt. Enter ends it; Ctrl-D sets s->quit. While no + * key comes, the read times out every 500 ms and repaints sidebar and status + * line: a widget that ticks is useless if the screen only refreshes on a key. + */ +static void +ui_read_line(struct ui_state *s, const struct ui_backend *be, char *input, + size_t cap) +{ + struct sp_host *host = be->host(be->ctx); + struct swarm *sw = be->swarm(be->ctx); + size_t len = 0; + int ch; + int locked = (sw != NULL && sw->role == SWARM_SLAVE && sw->locked); + + input[0] = '\0'; + if (locked) { + werase(ui_input); + mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); + wnoutrefresh(ui_input); + } else + draw_prompt(input); + wnoutrefresh(ui_input); + doupdate(); + wtimeout(ui_input, 500); + if (sw != NULL) + swarm_report_busy(sw, 0); + for (;;) { + /* poll fleet: accept/read, update lock/inbox */ + if (sw != NULL) { + swarm_poll(sw); + locked = (sw->role == SWARM_SLAVE && sw->locked); + if (swarm_take_inbox(sw, input, cap)) { + wtimeout(ui_input, -1); + return; + } + } + ch = wgetch(ui_input); + if (ch == ERR) { + { + char msg[200]; + int got = 0; + + drain_idle(s); + while (sp_host_status_take(host, msg, sizeof(msg))) { + add_entry(s, "splinter", msg); + got = 1; + } + if (got) + draw_history(s); + } + draw_sidebar(s, SESS_ID(be), SESS_DIR(be), host); + if (locked) { + werase(ui_input); + mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); + wnoutrefresh(ui_input); + } else { + draw_prompt(input); + wnoutrefresh(ui_input); + } + doupdate(); + continue; + } + if (ch == '\n' || ch == '\r' || ch == KEY_ENTER) { + if (locked) continue; + break; + } + if (ch == 4) { + s->quit = 1; + break; + } + /* + * Ctrl-L repaints, KEY_RESIZE re-cuts the windows. + */ + if (ch == 12 || ch == KEY_RESIZE) { + if (ch == KEY_RESIZE) + relayout(500); + else + clearok(curscr, TRUE); + draw_history(s); + draw_sidebar(s, SESS_ID(be), SESS_DIR(be), host); + if (locked) { + werase(ui_input); + mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); + } else + draw_prompt(input); + wnoutrefresh(ui_input); + doupdate(); + continue; + } + if (ch == 3) { + if (locked) continue; + len = 0; + input[0] = '\0'; + draw_prompt(input); + wrefresh(ui_input); + continue; + } + if (ch == KEY_UP || ch == KEY_DOWN) { + if (locked || s->nhist == 0) + continue; + if (s->hist_pos < 0) + s->hist_pos = (int)s->nhist; + if (ch == KEY_UP && s->hist_pos > 0) + s->hist_pos--; + else if (ch == KEY_DOWN && s->hist_pos < (int)s->nhist - 1) + s->hist_pos++; + else if (ch == KEY_DOWN) + s->hist_pos = (int)s->nhist; + if (s->hist_pos >= (int)s->nhist || s->hist_pos < 0) + len = 0; + else { + snprintf(input, cap, "%s", s->hist[s->hist_pos]); + len = strlen(input); + } + input[len] = '\0'; + draw_prompt(input); + wrefresh(ui_input); + continue; + } + /* + * PgUp/PgDn and Shift+arrows scroll the chat pane. + */ + if (ch == KEY_PPAGE || ch == KEY_SR) { + s->scroll += (ch == KEY_SR ? 1 : 10); + draw_history(s); + draw_sidebar(s, SESS_ID(be), SESS_DIR(be), host); + if (locked) { + werase(ui_input); + mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); + } else + draw_prompt(input); + wnoutrefresh(ui_input); + doupdate(); + continue; + } + if (ch == KEY_NPAGE || ch == KEY_SF) { + size_t step = (ch == KEY_SF ? 1 : 10); + + s->scroll = s->scroll > step ? s->scroll - step : 0; + draw_history(s); + draw_sidebar(s, SESS_ID(be), SESS_DIR(be), host); + if (locked) { + werase(ui_input); + mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); + } else + draw_prompt(input); + wnoutrefresh(ui_input); + doupdate(); + continue; + } + if (ch == KEY_BACKSPACE || ch == 127 || ch == 8) { + if (locked) continue; + if (len > 0) { + /* drop a whole UTF-8 sequence, not half of one */ + do + len--; + while (len > 0 && ((unsigned char)input[len] & 0xc0) == 0x80); + input[len] = '\0'; + draw_prompt(input); + wrefresh(ui_input); + } + continue; + } + /* + * Tab (Shift-Tab back) switches the agent profile, unless a /command + * is being completed. + */ + if ((ch == '\t' || ch == KEY_BTAB) && + !(input[0] == '/' && strchr(input, ' ') == NULL)) { + int n = be->agents(be->ctx); + int cur = be->agent_cur(be->ctx); + + if (locked || n < 2) + continue; + (void)be->agent_switch(be->ctx, ch == '\t' ? + (cur + 1) % n : (cur + n - 1) % n); + sync_state(s); + drain_idle(s); + draw_history(s); + draw_history(s); + draw_sidebar(s, SESS_ID(be), SESS_DIR(be), host); + draw_prompt(input); + wnoutrefresh(ui_input); + doupdate(); + continue; + } + /* + * Slash completion: Tab shows available /commands. + */ + if (ch == '\t' && input[0] == '/' && strchr(input, ' ') == NULL) { + if (locked) continue; + { + char matches[32][64]; + int nm = be->command_names(be->ctx, matches, + 32); + const char *prefix = input + 1; + size_t plen = strlen(prefix); + char *m[32]; + int k = 0, i2; + + for (i2 = 0; i2 < nm; i2++) + if (strncmp(matches[i2], prefix, plen) == 0) + m[k++] = matches[i2]; + if (k == 1) { + snprintf(input, cap, "/%s ", m[0]); + len = strlen(input); + } else if (k > 1) { + size_t c = strlen(m[0]); + for (i2 = 1; i2 < k; i2++) { + size_t j = 0; + while (j < c && m[0][j] == m[i2][j]) j++; + c = j; + } + if (c > plen) { + snprintf(input, cap, "/%.*s", (int)c, m[0]); + len = strlen(input); + } + { + char hint[512]; size_t off = 0; + off += snprintf(hint + off, sizeof(hint) - off, " "); + for (i2 = 0; i2 < k && off + 2 < sizeof(hint); i2++) + off += snprintf(hint + off, sizeof(hint) - off, "/%s ", m[i2]); + { + /* no status bar: the last row */ + int hy = getmaxy(ui_hist) - 1; + + wattron(ui_hist, COLOR_PAIR(PAIR_STATUS)); + mvwhline(ui_hist, hy, 0, ' ', getmaxx(ui_hist)); + mvwaddnstr(ui_hist, hy, 0, hint, getmaxx(ui_hist) - 1); + wattroff(ui_hist, COLOR_PAIR(PAIR_STATUS)); + wnoutrefresh(ui_hist); + } + } + } + draw_prompt(input); + wnoutrefresh(ui_input); + doupdate(); + } + continue; + } + if (locked) + continue; + if (ch >= 32 && ch < 256 && len + 1 < cap) { + input[len++] = (char)ch; + input[len] = '\0'; + draw_prompt(input); + wrefresh(ui_input); + } + } + wtimeout(ui_input, -1); +} + + +static void +seg_show(struct ui_state *s, struct seg *g, const char *role, const char *text) +{ + size_t len = text != NULL ? strlen(text) : 0; + const char *p; + + if (g->off > len) { /* the buffer started over */ + g->off = 0; + g->shown = 0; + g->id = 0; + } + /* + * While the open entry is the last one it may keep growing. Once + * something was appended below it (a tool call, the answer), what is on + * screen stays as it is: the bytes it shows move into off and the rest + * continues in a new entry. That is the whole append-only rule. + */ + if (g->id != 0 && !(s->n > 0 && s->entries[s->n - 1].id == g->id)) { + g->off += g->shown; + g->shown = 0; + g->id = 0; + } + if (len <= g->off) + return; + p = text + g->off; + while (*p == '\n') + p++; + if (*p == '\0') + return; + if (g->id == 0) + g->id = add_entry(s, role, ""); + entry_set_text(s, g->id, p); + g->shown = len - g->off; +} + +/* what the screen keeps of a running turn between two ticks */ +struct turn_view { + struct timespec t0; + struct seg think, ans; /* the reasoning, the answer */ + struct sp_buf thinkbuf; /* the step's reasoning so far */ + struct sp_buf live; /* the step's answer so far */ + char line[1024]; /* steering text being typed */ + size_t llen; + char note[600]; /* a usage-limit wait, or "" */ + int rc; + int got_end; +}; + +/* a one-line result ("[exit status 0]") joins the call row it belongs to */ +static void +join_previous(struct ui_state *s, const char *text) +{ + struct entry *e; + size_t need; + char *joined; + + if (s->n == 0 || text == NULL) + return; + e = &s->entries[s->n - 1]; + need = strlen(e->text) + strlen(text) + 3; + joined = malloc(need); + if (joined == NULL) + return; + snprintf(joined, need, "%s %s", e->text, text); + entry_set_text(s, e->id, joined); + free(joined); +} + +/* + * Entries the engine produced outside a turn: a shell command's output, the + * announcement of a profile switch, /new clearing the pane. While no turn is + * running nothing else arrives, so a turn-specific event is ignored here. + */ +static void +drain_idle(struct ui_state *s) +{ + struct sp_event ev; + + while (s->be->poll(s->be->ctx, &ev)) { + switch (ev.kind) { + case SP_EV_ENTRY: + add_entry(s, ev.a, ev.b); + break; + case SP_EV_CLEAR: + s->n = 0; + s->scroll = 0; + break; + case SP_EV_STATE: + sync_state(s); + break; + case SP_EV_QUIT: + s->quit = 1; + break; + default: + break; + } + s->be->event_free(s->be->ctx, &ev); + } +} + +/* + * One turn ended. The answer the engine returns is the last step's text; what + * streamed before it already has an entry. Called per turn, not once per + * submit: a steer that had no step boundary becomes a second turn in the same + * worker, and its answer belongs in the transcript too. + */ +static void +finalize_turn(struct ui_state *s, struct turn_view *v, int rc, const char *answer, + const char *err) +{ + if (rc == 0) { + const char *ap = answer != NULL ? answer : ""; + size_t la = strlen(ap), lv = v->live.len; + + if (lv > 0) { + seg_show(s, &v->ans, "agent", v->live.p); + if (la > lv) + add_entry(s, "agent", ap); + } else if (*ap != '\0') + add_entry(s, "agent", ap); + } else + add_entry(s, "error", err != NULL && *err != '\0' ? err : + sp_t("err.turn_failed")); + /* the next turn starts on a clean page */ + v->think.id = v->think.off = v->think.shown = 0; + v->ans.id = v->ans.off = v->ans.shown = 0; + sp_buf_clear(&v->thinkbuf); + sp_buf_clear(&v->live); + v->note[0] = '\0'; +} + +/* + * Everything the turn produced since the last tick, in the order it happened. + * The engine queued it; this is the only place that turns events into entries. + */ +static void +drain_events(struct ui_state *s, struct turn_view *v) +{ + struct sp_event ev; + + while (s->be->poll(s->be->ctx, &ev)) { + switch (ev.kind) { + case SP_EV_STREAM: + if (ev.a == NULL) + break; + if (ev.n == SP_STREAM_TEXT) { + (void)sp_buf_puts(&v->live, ev.a); + seg_show(s, &v->ans, "agent", v->live.p); + } else if (ev.n == SP_STREAM_THINK) { + (void)sp_buf_puts(&v->thinkbuf, ev.a); + seg_show(s, &v->think, "thinking", + v->thinkbuf.p); + } + break; + case SP_EV_STEP: + /* + * The step is over: its reasoning and its answer stay on + * screen as they are, and the next step starts fresh + * below them. + */ + if (ev.a != NULL) + seg_show(s, &v->think, "thinking", ev.a); + if (ev.b != NULL) + seg_show(s, &v->ans, "agent", ev.b); + v->think.id = v->think.off = v->think.shown = 0; + v->ans.id = v->ans.off = v->ans.shown = 0; + sp_buf_clear(&v->thinkbuf); + sp_buf_clear(&v->live); + break; + case SP_EV_TOOL: { + char call[512]; + + sp_call_summary(ev.a, ev.b, call, sizeof(call)); + /* a call row is one row: two hundred columns is plenty */ + cut_line(call, 200); + add_entry(s, "tool", call); + break; + } + case SP_EV_TOOL_RESULT: + if (ev.n == 1) + join_previous(s, ev.b); + else + add_entry(s, "observation", ev.b); + break; + case SP_EV_NOTE: + snprintf(v->note, sizeof(v->note), "%s", + ev.a != NULL ? ev.a : ""); + break; + case SP_EV_ENTRY: + add_entry(s, ev.a, ev.b); + break; + case SP_EV_APPROVAL: + /* turn_approval() polls the engine for this */ + break; + case SP_EV_TURN_END: + v->rc = (int)ev.n; + v->got_end = 1; + finalize_turn(s, v, (int)ev.n, ev.a, ev.b); + break; + case SP_EV_STATE: + sync_state(s); + break; + case SP_EV_CLEAR: + s->n = 0; + s->scroll = 0; + break; + case SP_EV_QUIT: + s->quit = 1; + break; + case SP_EV_BUSY: + case SP_EV_NONE: + break; + } + s->be->event_free(s->be->ctx, &ev); + } +} + +/* + * One tick without a key: the turn so far, on screen. The turn is not drawn + * into a box of its own: it is two entries that grow in place, the reasoning + * first, the answer after the tool calls. Nothing moves when the turn ends. + */ +static void +turn_paint(struct ui_state *s, struct turn_view *v) +{ + struct timespec now; + long ms; + int w, used; + struct swarm *sw = s->be->swarm(s->be->ctx); + + draw_history(s); + draw_sidebar(s, SESS_ID(s->be), SESS_DIR(s->be), + s->be->host(s->be->ctx)); + if (sw != NULL) + swarm_poll(sw); + + /* + * The prompt becomes the steering line: elapsed seconds, the tool that + * is running, then what is typed. One row, never wrapped. + */ + clock_gettime(CLOCK_MONOTONIC, &now); + ms = (long)((now.tv_sec - v->t0.tv_sec) * 1000 + + (now.tv_nsec - v->t0.tv_nsec) / 1000000); + s->last_ms = ms; + update_meter(s, s->be->host(s->be->ctx)); + werase(ui_input); + w = getmaxx(ui_input) - 1; + { + /* + * No status bar: the input line leads with how long the turn + * has been running and the steer prompt. The note is the one + * exception - a usage-limit wait says when it goes on there. + */ + char note[600], mark[700], steer[32]; + + snprintf(steer, sizeof(steer), "%s", + sp_td("ui.steer_mark", "steer> ")); + snprintf(note, sizeof(note), "%lds%s%.500s", ms / 1000, + v->note[0] != '\0' ? " " : "", v->note); + cut_line(note, w > (int)strlen(steer) + 2 ? + (size_t)w - strlen(steer) - 2 : 0); + snprintf(mark, sizeof(mark), "%s %s", note, steer); + mvwaddnstr(ui_input, 0, 0, mark, w); + used = (int)strlen(mark); + } + if (used < w) + ui_add_text(ui_input, v->line, w - used - 1); + wclrtoeol(ui_input); + wnoutrefresh(ui_input); + doupdate(); +} + +/* + * A tool needs permission. The engine parked the turn; the question goes where + * the prompt is, and y/N answers it. It names the call the way the transcript + * does - "Run touch /tmp/x" - and then how far it reaches. + */ +static int +turn_approval(struct ui_state *s, int c) +{ + int auth = SP_AUTH_READ; + char nm[64], ar[256]; + + if (!s->be->approval(s->be->ctx, nm, sizeof(nm), &auth, ar, sizeof(ar))) + return 0; + /* + * Ctrl-C and Ctrl-D are not answers: they go on to turn_key, which + * cancels and wakes the engine. Swallowing them here left the operator + * no way out of a question but y or n. + */ + if (c == 3 || c == 4) + return 0; + { + char call[640], label[64], line[768]; + size_t over, n; + int w = getmaxx(ui_input) - 1; + + sp_call_summary(nm, ar, call, sizeof(call)); + snprintf(label, sizeof(label), "%s", + auth == SP_AUTH_MUTATE ? sp_t("auth.mutate") : + sp_t("auth.destructive")); + snprintf(line, sizeof(line), sp_t("ui.approve"), call, label); + if ((int)strlen(line) > w) { + /* the call gives way; the class and "y/N" never do */ + over = strlen(line) - (size_t)w; + n = strlen(call); + cut_line(call, n > over + 4 ? n - over - 4 : 0); + snprintf(line, sizeof(line), sp_t("ui.approve"), call, + label); + } + werase(ui_input); + mvwaddnstr(ui_input, 0, 0, line, w); + wrefresh(ui_input); + } + if (c == 'y' || c == 'Y' || c == 'n' || c == 'N' || c == 27) + (void)s->be->approve(s->be->ctx, c == 'y' || c == 'Y'); + return 1; +} + +/* + * The keys of a running turn: type to steer (Enter queues the text for the + * next step), PgUp/PgDn scroll, Ctrl-C cancels, Ctrl-D cancels and quits. + * Returns 1 when the turn was cancelled. + */ +static int +turn_key(struct ui_state *s, struct turn_view *v, int c) +{ + if (c == KEY_PPAGE || c == KEY_SR) { + s->scroll += (c == KEY_SR ? 1 : 10); + redraw(s, s->be); + return 0; + } + if (c == KEY_NPAGE || c == KEY_SF) { + size_t step = (c == KEY_SF ? 1 : 10); + + s->scroll = s->scroll > step ? s->scroll - step : 0; + redraw(s, s->be); + return 0; + } + if (c == KEY_RESIZE) { + relayout(100); + redraw(s, s->be); + return 0; + } + /* + * Cancel at the engine: it wakes a turn that is asleep in an approval + * and the transports kill their child or curl when the flag is set. + */ + if (c == 3 || c == 4) { + (void)s->be->cancel(s->be->ctx); + if (c == 4) + s->quit = 1; + return 1; + } + if (c == '\n' || c == '\r' || c == KEY_ENTER) { + if (v->llen > 0) { + (void)s->be->steer(s->be->ctx, v->line); + v->llen = 0; + v->line[0] = '\0'; + mvwaddstr(ui_input, 0, 0, sp_t("ui.steering_queued")); + wclrtoeol(ui_input); + wrefresh(ui_input); + } + return 0; + } + if ((c == KEY_BACKSPACE || c == 127 || c == 8) && v->llen > 0) { + v->line[--v->llen] = '\0'; + return 0; + } + if (c >= 32 && c < 256 && c != 127 && v->llen < sizeof(v->line) - 2) { + v->line[v->llen++] = (char)c; + v->line[v->llen] = '\0'; + } + return 0; +} + +/* + * One turn: start it in the engine, then keep the screen alive until the + * engine says it is done. The answer the engine returns is the last step's + * text; what streamed before it stays in the transcript. + */ +static int +ui_turn(struct ui_state *s, const char *text) +{ + struct turn_view v; + int rc, cancelled = 0; + + memset(&v, 0, sizeof(v)); + clock_gettime(CLOCK_MONOTONIC, &v.t0); + sp_buf_init(&v.thinkbuf); + sp_buf_init(&v.live); + if (s->be->submit(s->be->ctx, text) != 0) { + add_entry(s, "error", sp_t("err.thread")); + sp_buf_free(&v.thinkbuf); + sp_buf_free(&v.live); + return -1; + } + wtimeout(ui_input, 100); + for (;;) { + int c; + + drain_events(s, &v); + if (!s->be->busy(s->be->ctx)) + break; + c = wgetch(ui_input); + if (turn_approval(s, c)) + continue; + if (c == ERR) { + turn_paint(s, &v); + continue; + } + if (turn_key(s, &v, c)) { + cancelled = 1; + break; + } + } + /* + * A cancelled turn: wait for the engine with the screen alive. Every + * transport kills its own child or curl when the flag is set. A second + * Ctrl-C leaves at once instead of holding the terminal hostage. + */ + if (cancelled) { + wtimeout(ui_input, 100); + while (s->be->busy(s->be->ctx)) { + int c2; + + drain_events(s, &v); + werase(ui_input); + mvwaddstr(ui_input, 0, 0, sp_t("ui.cancelling")); + wclrtoeol(ui_input); + wrefresh(ui_input); + c2 = wgetch(ui_input); + if (c2 == 3 || c2 == 4) { + endwin(); + _exit(1); + } + if (c2 == ERR) + turn_paint(s, &v); + } + } + drain_events(s, &v); + (void)s->be->wait(s->be->ctx); + wtimeout(ui_input, -1); + sync_state(s); + /* + * The answers were added when their turn events arrived. What is left + * is the result: -1 when the connection ended without one. + */ + rc = v.got_end ? v.rc : -1; + if (!v.got_end) + add_entry(s, "error", sp_t("err.turn_failed")); + sp_buf_free(&v.thinkbuf); + sp_buf_free(&v.live); + return rc; +} + +static void +history_entry(void *cbctx, const char *role, const char *text) +{ + struct ui_state *s = cbctx; + + if (text == NULL || *text == '\0') + return; + add_entry(s, strcmp(role, "user") == 0 ? "you" : "agent", text); +} + +/* curses up, colours, windows, and the conversation so far on screen */ +static int +ui_start(struct ui_state *s, const struct ui_backend *be, + const char *theme_name) +{ + struct sp_buf err; + const char *user = getenv("USER"); + + memset(s, 0, sizeof(*s)); + s->be = be; + s->conf = be->config(be->ctx); + if (user != NULL && *user != '\0') + snprintf(g_who, sizeof(g_who), "%s", user); + if (sp_buf_init(&err) != 0) + return -1; + if (sp_theme_load(theme_name, &s->theme, &err) != 0) { + fprintf(stderr, "splinter: %s\n", + err.len > 0 ? err.p : sp_t("err.theme")); + sp_buf_free(&err); + return -1; + } + be->set_theme(be->ctx, s->theme.name); + sp_buf_free(&err); + sync_state(s); + + /* + * Without this, curses treats every byte above 0x7f as garbage: German + * umlauts and every UTF-8 answer would arrive as replacement characters. + */ + setlocale(LC_ALL, ""); + initscr(); + /* + * raw(), not cbreak(): cbreak leaves ISIG on, so the terminal driver turns + * Ctrl-C into SIGINT and kills the harness before wgetch() can report the + * key - "Ctrl-C cancels the turn" was a claim, and pressing it proved the + * opposite. raw() hands every byte to us and we decide. + */ + raw(); + noecho(); + keypad(stdscr, TRUE); + curs_set(1); + init_colors(&s->theme); + layout(); + + /* + * Input history is the client's own file. A remote session's directory + * is a path on the server, so --attach keeps the history in memory. + */ + if (be->local(be->ctx)) + hist_load(s, SESS_DIR(be)); + /* + * A resumed session starts with its history on screen: the conversation + * is the same object the model will be given, so showing it is not a + * summary, it is the thing. + */ + be->history(be->ctx, history_entry, s); + add_entry(s, "splinter", sp_t("ui.ready")); + return 0; +} + +int +sp_ui_run(const struct ui_backend *be, const char *theme_name) +{ + struct ui_state s; + char input[1024]; + + if (ui_start(&s, be, theme_name) != 0) { + be->close(be->ctx); + return 1; + } + for (;;) { + struct sp_buf reply; + int kind; + + sync_state(&s); + draw_history(&s); + draw_sidebar(&s, SESS_ID(be), SESS_DIR(be), + be->host(be->ctx)); + werase(ui_input); + mvwaddstr(ui_input, 0, 0, prompt_mark()); + wnoutrefresh(ui_input); + doupdate(); + + ui_read_line(&s, be, input, sizeof(input)); + if (s.quit) + break; + if (input[0] == '\0') + continue; + if (sp_buf_init(&reply) != 0) + break; + kind = be->input(be->ctx, input, &reply); + if (kind == SP_INPUT_HANDLED) { + /* + * The engine queued what the command did (a shell's + * output, /new clearing the pane, a profile switch) + * before it returned its reply: drain first, so /new's + * reply survives the clear it caused. + */ + drain_idle(&s); + if (reply.p != NULL && reply.len > 0) + add_entry(&s, "splinter", reply.p); + sp_buf_free(&reply); + if (s.quit) + break; + continue; + } + { + const char *prompt = input; + + if (reply.p != NULL && reply.len > 0) + prompt = reply.p; + hist_push(&s, be->local(be->ctx) ? SESS_DIR(be) : NULL, + prompt); + s.scroll = 0; + add_entry(&s, "you", prompt); + draw_history(&s); + draw_sidebar(&s, SESS_ID(be), SESS_DIR(be), + be->host(be->ctx)); + werase(ui_input); + mvwaddstr(ui_input, 0, 0, sp_t("ui.working")); + wrefresh(ui_input); + doupdate(); + (void)ui_turn(&s, prompt); + /* + * A steer that arrived after the turn's last step + * boundary is still pending; run it as the next prompt + * instead of dropping it. + */ + { + struct sp_buf st; + + if (sp_buf_init(&st) == 0) { + while (!s.quit && + be->take_steer(be->ctx, &st)) { + hist_push(&s, be->local(be->ctx) ? + SESS_DIR(be) : NULL, st.p); + s.scroll = 0; + add_entry(&s, "you", st.p); + redraw(&s, be); + (void)ui_turn(&s, st.p); + sp_buf_clear(&st); + } + sp_buf_free(&st); + } + } + } + sp_buf_free(&reply); + if (s.quit) + break; + } + endwin(); + be->close(be->ctx); + return 0; +} diff --git a/src/frontend/protocol.c b/src/frontend/protocol.c new file mode 100644 index 0000000..0b8f91c --- /dev/null +++ b/src/frontend/protocol.c @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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; +} diff --git a/src/frontend/protocol.h b/src/frontend/protocol.h new file mode 100644 index 0000000..f972e52 --- /dev/null +++ b/src/frontend/protocol.h @@ -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 + +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 */ diff --git a/src/ui.h b/src/frontend/ui.h similarity index 63% rename from src/ui.h rename to src/frontend/ui.h index 6020515..de961f1 100644 --- a/src/ui.h +++ b/src/frontend/ui.h @@ -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 diff --git a/src/frontend/ui_backend.h b/src/frontend/ui_backend.h new file mode 100644 index 0000000..80b4c99 --- /dev/null +++ b/src/frontend/ui_backend.h @@ -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 + +#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 */ diff --git a/src/frontend/ui_local.c b/src/frontend/ui_local.c new file mode 100644 index 0000000..d322a63 --- /dev/null +++ b/src/frontend/ui_local.c @@ -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 +#include + +#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; +} diff --git a/src/frontend/ui_remote.c b/src/frontend/ui_remote.c new file mode 100644 index 0000000..7564794 --- /dev/null +++ b/src/frontend/ui_remote.c @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include + +#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; +} diff --git a/src/main.c b/src/main.c index 000cb0f..e4c947c 100644 --- a/src/main.c +++ b/src/main.c @@ -18,6 +18,7 @@ #include #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 "). 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(®, 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(®) != 0 || - sp_memory_register(®, &conf) != 0 || - sp_skills_register(®, &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, ®, &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(®, sess.dir) != 0 || - sp_delegate_register(®, &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(®, o.delegate, o.prompt); - goto cleanup; - } - if ((rc = pick_transport(&o, &ag, host, ®, &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 = ® - 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(®, 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(®); return rc; } diff --git a/src/ui.c b/src/ui.c deleted file mode 100644 index bc526f8..0000000 --- a/src/ui.c +++ /dev/null @@ -1,3663 +0,0 @@ -/* - * splinter -- curses chat interface. - * - * Copyright (c) 2026 Konrad Lother - * SPDX-License-Identifier: BSD-3-Clause - * - * Layout, fixed and deliberate: - * - * +---------------------------------+------------+ - * | history | sidebar | - * | three quarters | one quarter| - * | starts clear, only ever grows | model | - * | | usage | - * | | widgets | - * | | session | - * | | directory | - * +---------------------------------+------------+ - * | build> prompt, or "12s tool steer>" | - * +----------------------------------------------+ - * - * No status bar: the running time and the tool lead the prompt, and /usage, - * /status and /widgets put the same numbers into the transcript on demand. - * - * Only the UI thread ever calls into curses. Anything that wants to appear in - * the sidebar hands over finished text and never touches a WINDOW. - * - * Redraws happen when something changed -- after a turn, after a key -- so an - * idle splinter burns no CPU. - * - * Keys: Enter sends, Ctrl-L redraws, Ctrl-C drops the input line, Ctrl-D quits. - */ -#include -#include -#include -#include "decomp.h" -#include -#include -#include -#include -#include -#include -#include - -#include "splinter.h" -#include "mcp.h" -#include "i18n.h" -#include "log.h" -#include "cmdscript.h" -#include "splinter_plugin.h" -#include "config.h" -#include "providers.h" -#include -#include -#include "md.h" -#include "theme.h" -#include "ui.h" -#include "usage.h" -#include "agents.h" -#include "providers.h" - -/* set while a turn runs: widgets hold still instead of ticking under the answer */ -static volatile int g_turn_busy; - -/* - * Who is speaking. Not the role - the name: the person from $USER, the model from - * the configuration. 'thinking is thinking' was a label talking about itself. - */ -static char g_who[128] = "you"; -static char g_model[128] = "model"; - -#define MAX_ENTRIES 512 - -struct elayout; /* the wrapped lines of one entry, below */ - -struct entry { - char *role; - char *text; - time_t ts; /* when it arrived, for the IRC-style prefix */ - size_t id; /* stable across eviction; see add_entry */ - /* - * The wrapped lines, kept between frames. Wrapping a long transcript - * from scratch on every keystroke and every 100 ms tick was the reason - * the window felt slow: one frame cost as much as the whole log. - * Rebuilt only when the text or the width changed. - */ - struct elayout *cache; - int cache_cols; -}; - -struct ui_state { - struct entry entries[MAX_ENTRIES]; - size_t n; - size_t next_id; /* ids start at 1 */ - size_t scroll; /* lines scrolled back from the bottom */ - size_t scroll_max; /* maxscroll of the last frame */ - size_t scroll_base; /* maxscroll when the reader scrolled */ - long last_ms; - size_t tokens_in; - size_t tokens_out; - size_t out_chars; /* characters streamed in this/last turn */ - size_t total_out_chars; /* cumulative assistant output chars */ - char hist[128][1024]; /* what was typed before */ - size_t nhist; - int hist_pos; /* -1: editing a fresh line */ - int last_day; /* for the "--- 2026-11-13 ---" line */ - struct sp_buf last_think; /* the previous turn's reasoning */ - size_t last_steps; - size_t last_calls; - const char *endpoint; - const char *model; - char cur_endpoint[512]; /* owned: /model moves them */ - char cur_model[256]; - struct sp_config *conf; /* for /model, may be NULL */ - struct ui_connect { /* /connect, one answer per line */ - int active; - int step; - char id[64]; - char endpoint[520]; - char model[260]; - char key_env[80]; - } cc; - int quit; - struct sp_theme theme; - struct swarm *sw; /* local fleet, may be NULL/SWARM_NONE */ - /* agent profiles: Tab switches through them */ - struct sp_agents agents; - int agent_cur; - struct sp_tool_policy policy; - char *base_prompt; /* the system prompt without a profile */ - char home_id[64]; /* provider before a profile moved it */ -}; - -static char g_start_agent[48] = "build"; - -void -sp_ui_start_agent(const char *name) -{ - snprintf(g_start_agent, sizeof(g_start_agent), "%s", - name != NULL && *name != '\0' ? name : "build"); -} - -static WINDOW *ui_hist; -static WINDOW *ui_side; -static WINDOW *ui_input; -/* - * The agent whose profile is active. The sidebar used to show it; with one - * text field the prompt carries the name, so "build> " says what Tab did. - */ -static char ui_agent[32]; - - -enum { - PAIR_MAIN = 1, /* fg on bg */ - PAIR_ACCENT, /* accent on bg */ - PAIR_DIM, /* border on bg */ - PAIR_STATUS, /* hints and questions */ - PAIR_INPUT, /* the input line */ - PAIR_ERROR /* errors */ -}; - - -/* - * A turn runs on its own thread so the operator can keep typing. Curses stays - * with the UI thread: the worker only touches this struct, under a mutex. - * Steering is picked up at the next step boundary by the loop itself. - */ -struct turn { - struct sp_agent *ag; - const char *text; - struct sp_buf answer; - struct sp_buf err; - int rc; - volatile int done; - volatile int cancel; - char steer[1024]; - int have_steer; - int steers; - struct sp_buf live; /* the current step's text, streamed */ - struct sp_buf think; /* the current step's reasoning */ - /* - * What the turn produced, in the order it happened: a finished step's - * reasoning, its text, the call it made, a note. The turn thread cannot - * touch the entry list, so it queues here and the UI drains this. Before, - * tool calls were pasted into the reasoning text and the answer text of - * all steps ran together in one buffer - two problems that only existed - * because there was no queue. - */ - struct tun_ev { - int kind; /* 't' reasoning, 'a' answer, 'x' tool, 'n' note */ - char *text; - } *ev; - int nev, capev; - char tool[64]; /* last tool the model called */ - char tool_line[512]; /* name + args, for the live area */ - int tool_tick; - int compacted; /* compaction events to show in chat */ - size_t c_bytes_before; - size_t c_bytes_after; - size_t c_msgs_before; - size_t c_msgs_after; - /* a mutate/destructive tool is waiting for the operator */ - int approve_pending; - int approve_result; - char approve_name[64]; - char approve_args[256]; - int approve_auth; - pthread_cond_t cond; - pthread_mutex_t lock; -}; - -static int ev_push(struct turn *, int, const char *); - -/* - * Called from the turn thread right before a tool runs. The UI drains the list - * on its next tick and writes the calls into the transcript in order - so the - * operator sees which tool ran with which arguments, not just that something - * happened. - */ -/* - * Approval, asked on the screen. - * - * The turn runs on its own thread and must block here until a human answers; - * the UI thread keeps reading keys meanwhile. That is the whole reason this is - * a condition variable and not a prompt on stdout - a curses program cannot - * read stdin behind its own back without eating the keystrokes it needs. - */ -static int -approve_cb(void *ctx, const char *name, int auth, const char *args) -{ - struct turn *t = ctx; - int answer; - - pthread_mutex_lock(&t->lock); - snprintf(t->approve_name, sizeof(t->approve_name), "%s", - name != NULL ? name : "?"); - snprintf(t->approve_args, sizeof(t->approve_args), "%.200s", - args != NULL ? args : ""); - t->approve_auth = auth; - t->approve_result = 0; - t->approve_pending = 1; - pthread_cond_broadcast(&t->cond); - while (t->approve_pending && !t->cancel) - pthread_cond_wait(&t->cond, &t->lock); - answer = t->cancel ? 0 : t->approve_result; - t->approve_pending = 0; - pthread_mutex_unlock(&t->lock); - return answer; -} - -/* - * What the tool returned, into the transcript. A full `run` can carry a - * 300 KB JSON dump, and printing that would bury the conversation, so the - * entry keeps the head of it and says how much is left. Two limits, both - * about the screen: sixteen rows and four kilobytes - a row limit alone lets - * one enormous line through, a byte limit alone lets fifty short lines cover - * the whole screen. The whole text is in the session log either way: the log - * gets what the harness saw, not what fits on screen. - */ -#define OBS_ROWS 16 /* rows of an observation the transcript keeps */ -#define OBS_BYTES 4096 /* and its bytes */ - -static void -tool_end_cb(void *ctx, const char *name, const char *obs) -{ - struct turn *t = ctx; - char *shown; - size_t len, keep, rows, i, rest = 0; - - (void)name; - if (obs == NULL || *obs == '\0') - return; - while (*obs == '\n' || *obs == '\r') - obs++; - len = strlen(obs); - if (len == 0) - return; - while (len > 0 && (obs[len - 1] == '\n' || obs[len - 1] == '\r')) - len--; - /* - * A call that said nothing but how it ended belongs on the call row - - * - * >> Run mkdir -p build [exit status 0] - * - * instead of two rows for every quiet command. Output that has - * something to say keeps its own block underneath. - */ - if (len >= 14 && len <= 32 && strncmp(obs, "[exit status ", 13) == 0 && - obs[len - 1] == ']' && memchr(obs, '\n', len) == NULL) { - char line[64]; - - snprintf(line, sizeof(line), "%.*s", (int)len, obs); - pthread_mutex_lock(&t->lock); - (void)ev_push(t, 's', line); - pthread_mutex_unlock(&t->lock); - return; - } - /* cut at the row that ends the visible block, not in the middle of one */ - keep = len; - for (rows = 0, i = 0; i < len; i++) { - if (i >= OBS_BYTES || rows >= OBS_ROWS) { - keep = i; - break; - } - if (obs[i] == '\n') - rows++; - } - if (keep >= len) { - shown = strdup(obs); - if (shown == NULL) - return; - } else { - /* a cut in the middle of a line is the byte limit talking */ - if (obs[keep] != '\n') { - size_t cut = keep; - - while (cut > 0 && obs[cut - 1] != '\n') - cut--; - if (cut > 0) - keep = cut; - } - for (i = keep; i < len; i++) - if (obs[i] == '\n') - rest++; - if (obs[len - 1] != '\n') - rest++; - shown = malloc(keep + 128); - if (shown == NULL) - return; - memcpy(shown, obs, keep); - shown[keep] = '\0'; - if (rest > 0) { - char mark[80]; - - snprintf(mark, sizeof(mark), sp_t("ui.more_lines"), rest); - snprintf(shown + keep, 128, "\n%s", mark); - } - } - pthread_mutex_lock(&t->lock); - (void)ev_push(t, 'o', shown); - pthread_mutex_unlock(&t->lock); - free(shown); -} - -/* - * A tool call as a person reads it. The model sends {"command":"ls 2\u003e\u00261"}; - * what belongs on the screen is command: ls 2>&1 . Strings are unescaped, - * numbers and booleans kept, anything nested is left as it came. - */ -static void -pretty_args(const char *json, char *out, size_t cap) -{ - const char *p = json; - size_t n = 0; - int first = 1; - - out[0] = '\0'; - while (*p == ' ') - p++; - if (*p != '{') { - snprintf(out, cap, "%s", json); - return; - } - p++; - while (*p != '\0' && *p != '}' && n + 8 < cap) { - char key[48]; - size_t k = 0; - - while (*p == ' ' || *p == ',') - p++; - if (*p != '"') - break; - p++; - while (*p != '\0' && *p != '"' && k + 1 < sizeof(key)) - key[k++] = *p++; - key[k] = '\0'; - if (*p == '"') - p++; - while (*p == ' ' || *p == ':') - p++; - if (!first) - n += (size_t)snprintf(out + n, cap - n, " "); - first = 0; - n += (size_t)snprintf(out + n, cap - n, "%s: ", key); - if (*p == '"') { - p++; - while (*p != '\0' && *p != '"' && n + 4 < cap) { - if (*p == '\\' && p[1] != '\0') { - p++; - if (*p == 'n') { - out[n++] = ' '; - } else if (*p == 't') { - out[n++] = ' '; - } else if (*p == 'u' && strlen(p) >= 5) { - unsigned cp = 0; - int i; - - for (i = 1; i <= 4; i++) { - char c = p[i]; - - cp = cp * 16 + (unsigned)(c >= 'a' ? - c - 'a' + 10 : c >= 'A' ? - c - 'A' + 10 : c - '0'); - } - p += 4; - if (cp < 0x80) - out[n++] = (char)cp; - else if (cp < 0x800) { - out[n++] = (char)(0xc0 | (cp >> 6)); - out[n++] = (char)(0x80 | (cp & 0x3f)); - } else { - out[n++] = (char)(0xe0 | (cp >> 12)); - out[n++] = (char)(0x80 | ((cp >> 6) & 0x3f)); - out[n++] = (char)(0x80 | (cp & 0x3f)); - } - } else - out[n++] = *p; - p++; - continue; - } - out[n++] = *p++; - } - if (*p == '"') - p++; - } else { - /* a number, a boolean, an object: as it is, up to the next key */ - int depth = 0; - - while (*p != '\0' && n + 4 < cap) { - if (*p == '{' || *p == '[') - depth++; - else if (*p == '}' || *p == ']') { - if (depth == 0) - break; - depth--; - } else if (*p == ',' && depth == 0) - break; - out[n++] = *p++; - } - } - out[n] = '\0'; - } - out[n < cap ? n : cap - 1] = '\0'; -} - -/* - * The argument that says what a call is about, per tool: a shell call is its - * command, a read is its path. Once the verb has said "Run", the key in front - * of the value ("command: du -sh") only repeats the harness to itself. - */ -static const char * -primary_key(const char *name) -{ - static const struct { - const char *tool, *key; - } keys[] = { - { "run", "command" }, - { "read", "path" }, - { "write", "path" }, - { "edit", "path" }, - { "list", "path" }, - { "search", "pattern" }, - { "websearch", "query" }, - { "webfetch", "url" }, - { "echo", "text" }, - { "delegate", "task" }, - }; - size_t i; - - for (i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) - if (strcmp(name, keys[i].tool) == 0) - return keys[i].key; - return NULL; -} - -/* - * A tool call as a person reads it: - * - * Run du -sh ../xsrc - * Read src/ui.c - * Search sp_agent_run - * - * The verb is the tool, capitalized; behind it the one argument that matters. - * No JSON and no key names - the model's encoding is not the reader's - * business. The same line goes to the transcript, the prompt and the question - * that asks permission, so all three name the call in the same words. - */ -static void -call_summary(const char *name, const char *args, char *out, size_t cap) -{ - char detail[512] = ""; - const char *key; - size_t n; - - /* - * The value of the primary key, read out of the object instead of off - * the front of the pretty text: the model may order its arguments as it - * likes, and a "write" carries the whole file content next to the path. - * Everything else in the call is noise on one row. - */ - key = primary_key(name); - if (key != NULL && args != NULL && args[0] == '{') { - mcp_json *v = mcp_parse(args); - - if (v != NULL) { - const char *val = mcp_arg_string(v, key); - - if (val != NULL) - snprintf(detail, sizeof(detail), "%s", val); - mcp_json_free(v); - } - } - if (detail[0] == '\0') - pretty_args(args != NULL ? args : "", detail, sizeof(detail)); - snprintf(out, cap, "%s", name); - if (out[0] >= 'a' && out[0] <= 'z') - out[0] = (char)(out[0] - 'a' + 'A'); - n = strlen(out); - if (*detail != '\0' && n + 2 < cap) - snprintf(out + n, cap - n, " %s", detail); -} - -/* - * Cut a line for the screen and mark the cut. On a character boundary: the - * text is UTF-8, and half a sequence draws as garbage. - */ -static void -cut_line(char *s, size_t want) -{ - size_t n = strlen(s), cut = want; - - if (n <= want) - return; - while (cut > 0 && ((unsigned char)s[cut] & 0xc0) == 0x80) - cut--; - s[cut] = '\0'; - if (cut >= 3) - memcpy(s + cut - 3, "...", 3); -} - -/* queue one event for the UI; the caller holds t->lock */ -static int -ev_push(struct turn *t, int kind, const char *text) -{ - struct tun_ev *nv; - - if (text == NULL || *text == '\0') - return 0; - if (t->nev == t->capev) { - int nc = t->capev != 0 ? t->capev * 2 : 16; - - nv = realloc(t->ev, (size_t)nc * sizeof(*nv)); - if (nv == NULL) - return -1; - t->ev = nv; - t->capev = nc; - } - t->ev[t->nev].text = strdup(text); - if (t->ev[t->nev].text == NULL) - return -1; - t->ev[t->nev].kind = kind; - t->nev++; - return 0; -} - -/* - * A tool call is its own line in the transcript, queued here (the turn runs on - * another thread and must not touch the entry list) and drained by the UI. - * It used to be faked into the reasoning text as "› name args", which made it - * uncountable, uncollapsible and a second copy of the same text. - */ -static void -tool_begin_cb(void *ctx, const char *name, const char *args) -{ - struct turn *t = ctx; - char call[sizeof(t->tool_line)]; - - if (name == NULL) - return; - call_summary(name, args, call, sizeof(call)); - pthread_mutex_lock(&t->lock); - /* - * The prompt leads with the same words. It used to be "name {json}" - - * the model's own encoding, cut at forty bytes in the middle of an - * escape, which is what made the line unreadable. - */ - snprintf(t->tool_line, sizeof(t->tool_line), "%s", call); - /* - * The step is over as far as the screen is concerned: its reasoning and - * its text go into the queue in that order, then the call itself, and - * the buffers start empty for the next step. - */ - (void)ev_push(t, 't', t->think.p); - (void)ev_push(t, 'a', t->live.p); - sp_buf_clear(&t->think); - sp_buf_clear(&t->live); - /* a call row is one row: two hundred columns is already more than fits */ - cut_line(call, 200); - (void)ev_push(t, 'x', call); - pthread_mutex_unlock(&t->lock); -} - -static void -stream_cb(void *ctx, int kind, const char *text) -{ - struct turn *t = ctx; - - if (text == NULL) - return; - pthread_mutex_lock(&t->lock); - if (kind == SP_STREAM_TEXT) { - (void)sp_buf_puts(&t->live, text); - } else if (kind == SP_STREAM_THINK) { - (void)sp_buf_puts(&t->think, text); - } else if (kind == SP_STREAM_TOOL) { - snprintf(t->tool, sizeof(t->tool), "%s", text); - t->tool_tick++; - } - pthread_mutex_unlock(&t->lock); -} - -/* - * The turn hit a usage limit: say so in the status line and in the reasoning, - * and wait for the reset on the turn thread. The screen stays alive (it is - * another thread), Ctrl-C ends the wait, and /resume goes on later. - */ -static long g_max_wait = 12 * 3600; - -static int -ui_limit_wait(void *ctx, long until, const char *why) -{ - struct turn *t = ctx; - char when[32], line[300]; - struct tm tm; - time_t tt = (time_t)until; - - if (until - (long)time(NULL) > g_max_wait) - return 0; - strftime(when, sizeof(when), "%a %H:%M", localtime_r(&tt, &tm)); - (void)why; - snprintf(line, sizeof(line), sp_t("ui.limit_wait"), when); - pthread_mutex_lock(&t->lock); - snprintf(t->tool_line, sizeof(t->tool_line), "%s", line); - (void)ev_push(t, 'n', line); - pthread_mutex_unlock(&t->lock); - while ((long)time(NULL) < until && !t->cancel) { - struct timespec ts = { 0, 250000000L }; - - nanosleep(&ts, NULL); - } - pthread_mutex_lock(&t->lock); - t->tool_line[0] = '\0'; - pthread_mutex_unlock(&t->lock); - return !t->cancel; -} - -static int -steer_cb(void *ctx, struct sp_buf *out) -{ - struct turn *t = ctx; - int took = 0; - - pthread_mutex_lock(&t->lock); - if (t->have_steer) { - t->have_steer = 0; - t->steers++; - took = sp_buf_puts(out, t->steer) == 0 ? 1 : -1; - } - pthread_mutex_unlock(&t->lock); - return took; -} - -static void * -turn_thread(void *arg) -{ - struct turn *t = arg; - - g_turn_busy = 1; - t->rc = sp_agent_run(t->ag, t->text, &t->answer, &t->err); - t->done = 1; - g_turn_busy = 0; - return NULL; -} - -/* - * Colour assignment: the theme paints (theme.h says which role comes from - * where). This curses port does not honour -1 in init_pair(), so every pair - * gets real indices; an X resource theme without RGB uses the terminal's own - * indices 0..15, which is the same palette. - */ -static short -rgb(const unsigned char c[3], short n) -{ - return sp_color_rgb(c[0], c[1], c[2], n); -} - -static void -init_colors(const struct sp_theme *t) -{ - short n; - - if (!has_colors()) - return; - /* COLORS is only valid after start_color() */ - start_color(); - n = (short)(COLORS > 0 ? COLORS : 8); - if (t->indexed) { - short accent = n >= 16 ? t->idx_accent : COLOR_BLUE; - short dim = n >= 16 ? t->idx_border : COLOR_WHITE; - short errc = n >= 16 ? t->idx_error : COLOR_RED; - - init_pair(PAIR_MAIN, t->idx_fg, t->idx_bg); - init_pair(PAIR_ACCENT, accent, t->idx_bg); - init_pair(PAIR_DIM, dim, t->idx_bg); - init_pair(PAIR_STATUS, t->idx_bg, t->idx_fg); - init_pair(PAIR_INPUT, t->idx_fg, t->idx_bg); - init_pair(PAIR_ERROR, errc, t->idx_bg); - return; - } - init_pair(PAIR_MAIN, rgb(t->fg, n), rgb(t->bg, n)); - init_pair(PAIR_ACCENT, rgb(t->accent, n), rgb(t->bg, n)); - init_pair(PAIR_DIM, rgb(t->border, n), rgb(t->bg, n)); - init_pair(PAIR_STATUS, rgb(t->status_fg, n), rgb(t->status, n)); - init_pair(PAIR_INPUT, rgb(t->input_fg, n), rgb(t->input_bg, n)); - init_pair(PAIR_ERROR, rgb(t->error, n), rgb(t->bg, n)); -} - -/* - * Text goes to curses as ASCII. - * - * Measured, not assumed: the vendored NetBSD curses emits Latin-1 bytes for - * wide characters (ü -> 0xFC) instead of re-encoding to the locale charset, so - * UTF-8 would reach the terminal as mojibake. ncurses passes the bytes through; - * this port does not. Until that is fixed in the library, the UI transliterates - * and the data keeps its exact UTF-8. - * - * iconv(3) does the work, with //TRANSLIT: a hand-written table turned German - * typography into question marks (— “ ” … all became '?'), which is how a - * readable answer turns into noise. Characters that cannot be transliterated - * become '?' - one per character, never silently dropped. - */ -static const struct sp_decomp * -decomp_find(unsigned int cp) -{ - size_t lo = 0, hi = sp_decomp_count; - - while (lo < hi) { - size_t mid = (lo + hi) / 2; - - if (sp_decomp_table[mid].cp == cp) - return &sp_decomp_table[mid]; - if (sp_decomp_table[mid].cp < cp) - lo = mid + 1; - else - hi = mid; - } - return NULL; -} - -/* Decode one UTF-8 sequence; returns bytes consumed, or 0 on a broken byte. */ -static size_t -utf8_next(const unsigned char *s, size_t left, unsigned int *cp) -{ - if (left == 0) - return 0; - if (s[0] < 0x80) { - *cp = s[0]; - return 1; - } - if ((s[0] & 0xe0) == 0xc0 && left >= 2) { - *cp = ((unsigned int)(s[0] & 0x1f) << 6) | (s[1] & 0x3f); - return 2; - } - if ((s[0] & 0xf0) == 0xe0 && left >= 3) { - *cp = ((unsigned int)(s[0] & 0x0f) << 12) | - ((unsigned int)(s[1] & 0x3f) << 6) | (s[2] & 0x3f); - return 3; - } - if ((s[0] & 0xf8) == 0xf0 && left >= 4) { - *cp = ((unsigned int)(s[0] & 0x07) << 18) | - ((unsigned int)(s[1] & 0x3f) << 12) | - ((unsigned int)(s[2] & 0x3f) << 6) | (s[3] & 0x3f); - return 4; - } - return 0; -} - -/* - * UTF-8 -> ASCII for the screen. - * - * Two mechanisms, and the split is the point: letters come from a table - * generated out of Unicode's decompositions (glibc's iconv transliterates "ß" - * but turns "ü" into "?"), punctuation goes through iconv (— becomes --, … - * becomes ...). A character neither can express becomes one '?' — visible, not - * silently dropped. - * - * The conversation and the session log keep the exact UTF-8; only the screen - * is ASCII, because this curses port writes Latin-1 bytes for wide characters. - */ -int -sp_ui_ascii(const char *in, char *out, size_t cap) -{ - iconv_t cd; - const unsigned char *s; - size_t left, used = 0; - int rc = 0; - - if (in == NULL || out == NULL || cap == 0) - return -1; - cd = iconv_open("ASCII//TRANSLIT", "UTF-8"); - s = (const unsigned char *)in; - left = strlen(in); - - while (left > 0) { - unsigned int cp = 0; - size_t n = utf8_next(s, left, &cp); - const char *rep = NULL; - char tmp[16]; - - if (n == 0) { /* broken byte: one '?' and move on */ - if (used + 2 > cap) { - rc = -1; - break; - } - out[used++] = '?'; - s++; - left--; - continue; - } - if (cp < 0x80) { - tmp[0] = (char)cp; - tmp[1] = '\0'; - rep = tmp; - } else { - const struct sp_decomp *d = decomp_find(cp); - - if (d != NULL) { - rep = d->ascii; - } else if (cd != (iconv_t)-1) { - char *ip = (char *)s, *op = tmp; - size_t il = n, ol = sizeof(tmp) - 1; - - if (iconv(cd, &ip, &il, &op, &ol) != (size_t)-1) { - *op = '\0'; - rep = tmp; - } - } - if (rep == NULL) - rep = "?"; - } - { - size_t rl = strlen(rep); - - if (used + rl + 1 > cap) { - rc = -1; - break; - } - memcpy(out + used, rep, rl); - used += rl; - } - s += n; - left -= n; - } - out[used] = '\0'; - if (cd != (iconv_t)-1) - iconv_close(cd); - return rc; -} - -static void -ui_add_text(WINDOW *w, const char *s, int maxcols) -{ - char out[1024]; - - if (s == NULL) - return; - if (sp_ui_ascii(s, out, sizeof(out)) != 0) - snprintf(out, sizeof(out), "%.900s", s); - waddnstr(w, out, maxcols); -} - - - -/* A role is stored as its English key and displayed in the chosen language. */ -static const char * -role_label(const char *role) -{ - char key[48]; - const char *t; - - if (role == NULL) - return ""; - snprintf(key, sizeof(key), "role.%s", role); - t = sp_t(key); - if (t == NULL || strcmp(t, key) == 0) - return role; - return t; -} - -/* - * Row accounting for text that contains newlines. - * - * The first version counted rows as strlen()/cols, which is only true for one - * long line. A model's reasoning is full of newlines, so the real height was - * much larger than the estimate and the text painted over the answer below it - - * "it just goes anywhere on the screen". Every row is therefore computed from - * the actual line structure: split on '\n', then wrap each line. - */ -size_t sp_ui_ascii_char(const char *s, char *out, size_t cap); - -/* - * Rows an entry really occupies: the role prefix shortens the first row, so the - * height is computed from exactly the string that gets drawn ("role: text"), - * not from the text plus an estimate. Getting this wrong lost the last - * character of an entry - a truncated ``` closing a code block. - */ -/* - * IRC shape, as asked for: a timestamp, then who is speaking. - * - * [15:20:13] der text - * [15:20:14] * agent is thinking ... - * [15:20:31] die antwort - * - * A timestamp is cheap and makes a transcript readable hours later; without one - * every old line looks like it happened just now. - */ -static void -entry_prefix(const struct entry *e, char *buf, size_t len) -{ - struct tm tm; - char clock[16], who[64]; - - (void)localtime_r(&e->ts, &tm); - strftime(clock, sizeof(clock), "%H:%M:%S", &tm); - if (strcmp(e->role, "thinking") == 0) { - /* no '*': the markdown pass would eat it as emphasis */ - snprintf(buf, len, "[%s] ~ %s: ", clock, sp_t("ui.thinking")); - } else if (strcmp(e->role, "you") == 0) { - snprintf(who, sizeof(who), "%.40s", g_who); - snprintf(buf, len, "[%s] <%s> ", clock, who); - } else if (strcmp(e->role, "agent") == 0) { - snprintf(who, sizeof(who), "%.40s", g_model); - { - char *dot = strstr(who, ".gguf"); - - if (dot != NULL) - *dot = '\0'; - } - snprintf(buf, len, "[%s] <%s> ", clock, who); - } else if (strcmp(e->role, "tool") == 0) { - snprintf(buf, len, "[%s] >> ", clock); - } else if (strcmp(e->role, "observation") == 0) { - snprintf(buf, len, "[%s] | ", clock); - } else if (strcmp(e->role, "splinter") == 0) { - snprintf(buf, len, "[%s] --- ", clock); - } else { - snprintf(who, sizeof(who), "%.40s", role_label(e->role)); - snprintf(buf, len, "[%s] <%s> ", clock, who); - } -} - - -/* - * Markdown, the little of it a chat actually contains. - * - * **bold** *italic* `code` # heading ``` fence - * - * The markers are removed before anything is measured, because a line measured - * with its asterisks wraps in a different place than the one that is drawn. Each - * kept character carries an attribute, so a bold word stays bold across a wrap. - * - * Fence blocks are drawn dim and their marker lines disappear: an answer full of - * C code should look like code, not like three backticks around code. - */ -#define MD_BOLD 0x01 -#define MD_ITALIC 0x02 -#define MD_CODE 0x04 - -/* - * Is the '*' run at p (len 1 or 2) emphasis, or just an asterisk? The rules of - * CommonMark, short: an opener is followed by text and preceded by a space or - * punctuation, a closer is preceded by text, and an opener needs its closer on - * the same line. Without this "void *ctx, const char *name" in a code answer - * lost its pointers and came out italic. - */ -static int -emph_ok(const char *start, const char *p, int len, int open_now, int in_code) -{ - char prev = p > start ? p[-1] : ' '; - char next = p[len]; - int prev_space = prev == ' ' || prev == '\t' || prev == '\n'; - int next_space = next == '\0' || next == ' ' || next == '\t' || - next == '\n'; - const char *q; - - if (in_code) - return 0; - if (open_now) /* a closer: it must follow text */ - return !prev_space; - if (next_space) /* an opener: it must precede text */ - return 0; - if (!(prev_space || strchr("([{\"'-,.;:/", prev) != NULL)) - return 0; - /* - * ... and a closer must follow on this line before another opener does: - * the nearest opener takes the closer, the earlier ones stay asterisks. - */ - for (q = p + len; *q != '\0' && *q != '\n'; q++) { - int rl = 0; - - if (*q != '*') - continue; - while (q[rl] == '*') - rl++; - if (rl == len) { - char pq = q[-1], nq = q[rl]; - - if (pq != ' ' && pq != '\t') - return 1; /* a closer */ - if (nq != '\0' && nq != ' ' && nq != '\t' && nq != '\n') - return 0; /* a nearer opener */ - } - q += rl - 1; - } - return 0; -} - -static size_t -md_strip_n(const char *in, char *out, unsigned char *attr) -{ - size_t o = 0; - int bold = 0, italic = 0, code = 0, fence = 0; - const char *p = in != NULL ? in : ""; - - while (*p != '\0') { - /* a fence line is a mode switch, not text */ - if ((p[0] == '`' && p[1] == '`' && p[2] == '`') && - (p == in || p[-1] == '\n')) { - fence = !fence; - while (*p != '\0' && *p != '\n') - p++; - continue; - } - if (*p == '\n') { - out[o] = '\n'; - attr[o++] = fence ? MD_CODE : 0; - p++; - bold = italic = code = 0; - continue; - } - if (p[0] == '#' && (p == in || p[-1] == '\n')) { - while (*p == '#') - p++; - while (*p == ' ') - p++; - bold = 1; - continue; - } - if (!fence && p[0] == '*' && p[1] == '*' && - emph_ok(in, p, 2, bold, code)) { - bold = !bold; - p += 2; - continue; - } - if (!fence && *p == '`') { - code = !code; - p++; - continue; - } - /* - * Only the asterisk marks italics. An underscore is part of names: - * Qwen3.6-35B-A3B-UD-Q8_K_XL came out as Qwen3.6-35B-A3B-UD-Q8KX, - * which is a different model as far as a reader is concerned. - */ - if (!fence && *p == '*' && emph_ok(in, p, 1, italic, code)) { - italic = !italic; - p++; - continue; - } - out[o] = *p; - attr[o] = (unsigned char)((fence ? MD_CODE : 0) | - (bold ? MD_BOLD : 0) | (italic ? MD_ITALIC : 0) | - (code ? MD_CODE : 0)); - o++; - p++; - } - out[o] = '\0'; - attr[o] = 0; - return o; -} - -static int -md_prepare(const char *in, char **plain_out, unsigned char **attr_out) -{ - struct sp_buf tb; - const char *src; - size_t n; - - *plain_out = NULL; - *attr_out = NULL; - if (sp_buf_init(&tb) != 0) - return -1; - if (sp_md_table_format(in, &tb) < 0) { - sp_buf_free(&tb); - return -1; - } - src = tb.len > 0 ? tb.p : (in != NULL ? in : ""); - n = strlen(src); - *plain_out = malloc(n + 1); - *attr_out = malloc(n + 1); - if (*plain_out == NULL || *attr_out == NULL) { - free(*plain_out); - free(*attr_out); - *plain_out = NULL; - *attr_out = NULL; - sp_buf_free(&tb); - return -1; - } - md_strip_n(src, *plain_out, *attr_out); - sp_buf_free(&tb); - return 0; -} - -/* - * One character of 's', UTF-8 or not, as ASCII in 'out'; returns how many bytes - * of 's' it took (at least 1 unless *s is NUL). - * - * A UTF-8 character is one unit. Handing sp_ui_ascii a single byte of a two-byte - * sequence produced '??hler' where 'Zaehler' belonged - the transliteration - * needs the whole character. The copy of that character used to live in a - * char[2] on md_draw's stack, and a three- or four-byte character ('...', an - * emoji) wrote past it on every redraw. - */ -size_t -sp_ui_ascii_char(const char *s, char *out, size_t cap) -{ - char one[5]; /* four UTF-8 bytes and the NUL */ - size_t len = 1, k; - unsigned char c = (unsigned char)s[0]; - - if (cap == 0) - return c != 0 ? 1 : 0; - out[0] = '\0'; - if (c == 0) - return 0; - if (c < 0x80) { - if (cap > 1) { - out[0] = (char)c; - out[1] = '\0'; - } - return 1; - } - if ((c & 0xe0) == 0xc0) - len = 2; - else if ((c & 0xf0) == 0xe0) - len = 3; - else if ((c & 0xf8) == 0xf0) - len = 4; - for (k = 0; k < len && s[k] != '\0'; k++) - one[k] = s[k]; - one[k] = '\0'; - if (sp_ui_ascii(one, out, cap) != 0 && cap > 1) { - out[0] = '?'; - out[1] = '\0'; - } - return k; -} - - -/* - * The history pane, laid out once and drawn from that layout. - * - * The earlier version counted rows in one function and drew in another, and - * the two disagreed (the scroll offset was a byte count, the wrap a column - * count), which is why text landed in "zones" and scrolling jumped. Here an - * entry is turned into visual lines exactly once -- word wrapped, with the - * continuation lines hanging under the text -- and both the height and the - * drawing read that same list. - */ -struct vline { - size_t beg, end; /* bytes of the plain text */ - int indent; /* columns left of the text */ -}; - -struct elayout { - char *plain; - unsigned char *attr; - struct vline *v; - size_t n, cap; - int blank; /* a gap before this entry */ -}; - -static int -vl_add(struct elayout *l, size_t beg, size_t end, int indent) -{ - if (l->n == l->cap) { - size_t nc = l->cap != 0 ? l->cap * 2 : 16; - struct vline *nv = realloc(l->v, nc * sizeof(*nv)); - - if (nv == NULL) - return -1; - l->v = nv; - l->cap = nc; - } - l->v[l->n].beg = beg; - l->v[l->n].end = end; - l->v[l->n].indent = indent; - l->n++; - return 0; -} - -/* Word wrap 'p' into 'l'; every line but the first hangs under 'ind'. */ -static void -wrap_text(struct elayout *l, const char *p, int cols, int ind) -{ - size_t i = 0; - int first = 1; - - for (;;) { - int indent = first ? 0 : ind; - size_t avail = (size_t)(cols - indent > 0 ? cols - indent : 1); - size_t beg = i, end, w = 0, brk = 0; - int haveb = 0, wrapped = 0; - - for (;;) { - char o[8]; - size_t n, cw; - - if (p[i] == '\0' || p[i] == '\n') { - end = i; - break; - } - n = sp_ui_ascii_char(p + i, o, sizeof(o)); - if (n == 0) - n = 1; - cw = strlen(o); - if (w + cw > avail && i > beg) { - wrapped = 1; - if (haveb && brk > beg) { - end = brk; - i = brk; - } else - end = i; - break; - } - if (p[i] == ' ' && !(i > beg && p[i - 1] == ' ')) { - brk = i; - haveb = 1; - } - w += cw; - i += n; - } - if (vl_add(l, beg, end, indent) != 0) - return; - first = 0; - if (wrapped) { - while (p[i] == ' ') - i++; - if (p[i] == '\n') - i++; - if (p[i] == '\0') - break; - continue; - } - if (p[i] == '\0') - break; - i++; /* the newline */ - } -} - -static void -elayout_free(struct elayout *l) -{ - free(l->plain); - free(l->attr); - free(l->v); - memset(l, 0, sizeof(*l)); -} - -/* the visual lines of one entry, prefix included; cached in the entry */ -static struct elayout * -entry_layout(struct entry *e, int cols) -{ - char prefix[256]; - char *render; - size_t len; - int ind; - const char *brk; - struct elayout *l; - - if (e->cache != NULL && e->cache_cols == cols) - return e->cache; - if (e->cache == NULL) { - e->cache = calloc(1, sizeof(*e->cache)); - if (e->cache == NULL) - return NULL; - } else - elayout_free(e->cache); - l = e->cache; - e->cache_cols = cols; - entry_prefix(e, prefix, sizeof(prefix)); - /* a table that starts the answer must not start behind the prefix */ - brk = sp_md_table_starts(e->text) ? "\n" : ""; - len = strlen(prefix) + strlen(brk) + strlen(e->text) + 1; - render = malloc(len); - if (render == NULL) - return l; - snprintf(render, len, "%s%s%s", prefix, brk, e->text); - if (md_prepare(render, &l->plain, &l->attr) != 0) { - free(l->plain); - free(l->attr); - l->plain = render; - l->attr = NULL; - } else - free(render); - /* - * Chat lines hang under their text. Command output, shell output and - * diffs are columns the author laid out: shifting them would break them. - */ - if (strcmp(e->role, "splinter") == 0 || strcmp(e->role, "shell") == 0) - ind = 0; - else { - ind = (int)strlen(prefix); - if (ind > 24) - ind = 24; - if (ind > cols / 3) - ind = cols / 3; - } - wrap_text(l, l->plain, cols, ind); - /* blank lines at the end are not content */ - while (l->n > 1 && l->v[l->n - 1].beg == l->v[l->n - 1].end) - l->n--; - return l; -} - -static void -draw_vline(int y, const struct elayout *l, const struct vline *vl) -{ - attr_t base; - short pair; - size_t i; - int x = 1 + vl->indent; - - (void)wattr_get(ui_hist, &base, &pair, NULL); - base &= ~A_COLOR; - for (i = vl->beg; i < vl->end;) { - char o[8]; - unsigned a = l->attr != NULL ? l->attr[i] : 0; - attr_t at = base; - size_t n = sp_ui_ascii_char(l->plain + i, o, sizeof(o)); - - if (n == 0) - n = 1; - if (a & MD_BOLD) - at |= A_BOLD; - if (a & MD_ITALIC) - at |= A_UNDERLINE; - (void)wattr_set(ui_hist, at, (a & MD_CODE) ? PAIR_DIM : pair, NULL); - mvwaddstr(ui_hist, y, x, o); - x += (int)strlen(o); - i += n; - } - (void)wattr_set(ui_hist, base, pair, NULL); -} - -static void -draw_history(struct ui_state *s) -{ - int rows, cols, y = 0; - size_t idx, total = 0, first, line = 0, maxscroll; - struct elayout *l; - unsigned char *blank; - - getmaxyx(ui_hist, rows, cols); - cols -= 2; /* padding left and right */ - werase(ui_hist); - wbkgd(ui_hist, COLOR_PAIR(PAIR_MAIN)); - if (s->n == 0 || cols < 2 || rows < 1) { - wnoutrefresh(ui_hist); - return; - } - blank = calloc(s->n, 1); - if (blank == NULL) { - wnoutrefresh(ui_hist); - return; - } - for (idx = 0; idx < s->n; idx++) { - l = entry_layout(&s->entries[idx], cols); - if (l == NULL) - continue; - /* a new question starts a new exchange: one line of air */ - blank[idx] = idx > 0 && strcmp(s->entries[idx].role, "you") == 0; - total += l->n + (size_t)blank[idx]; - } - maxscroll = total > (size_t)rows ? total - (size_t)rows : 0; - /* scrolled up and text arrived below: keep the reader where he is */ - if (s->scroll > 0 && s->scroll <= s->scroll_max && - maxscroll > s->scroll_base) - s->scroll += maxscroll - s->scroll_base; - if (s->scroll > maxscroll) - s->scroll = maxscroll; - s->scroll_max = maxscroll; - s->scroll_base = maxscroll - s->scroll; - first = maxscroll - s->scroll; /* index of the top visible line */ - - for (idx = 0; idx < s->n && y < rows; idx++) { - const struct entry *e = &s->entries[idx]; - size_t k; - - if (strcmp(e->role, "you") == 0) - wattrset(ui_hist, COLOR_PAIR(PAIR_ACCENT) | A_BOLD); - else if (strcmp(e->role, "agent") == 0) - wattrset(ui_hist, COLOR_PAIR(PAIR_MAIN)); - else if (strcmp(e->role, "error") == 0) - wattrset(ui_hist, COLOR_PAIR(PAIR_ERROR) | A_BOLD); - /* - * A call is the interesting line of a tool step: what the tool - * returned is reference material under it. Painted with it, the - * transcript read as one grey wall of "Run". - */ - else if (strcmp(e->role, "tool") == 0) - wattrset(ui_hist, COLOR_PAIR(PAIR_ACCENT)); - else - wattrset(ui_hist, COLOR_PAIR(PAIR_DIM)); - if (blank[idx]) { - if (line >= first && y < rows) - y++; - line++; - } - l = s->entries[idx].cache; - if (l == NULL) - continue; - for (k = 0; k < l->n && y < rows; k++, line++) { - if (line < first) - continue; - draw_vline(y, l, &l->v[k]); - y++; - } - wattrset(ui_hist, A_NORMAL); - } - free(blank); - wnoutrefresh(ui_hist); -} - -/* - * The streaming turn is drawn as the last thing in the history pane: the tail - * of what has arrived so far. It is not an entry yet - entries are what was - * completed, and mixing the two would make the log look like it changed. - */ -/* - * While a turn runs, the left pane shows what the harness is doing, in the same - * place the conversation lives: the model's reasoning dimmed above, the answer - * as it arrives below. The sidebar keeps the counters - numbers are not text. - */ -static void -sidebar_heading(int *y, int cols, const char *text) -{ - wattron(ui_side, COLOR_PAIR(PAIR_DIM) | A_BOLD); - mvwaddnstr(ui_side, *y, 0, text, cols - 1); - wattroff(ui_side, A_BOLD); - (*y)++; - wattron(ui_side, COLOR_PAIR(PAIR_MAIN)); -} - -/* wrap 'text' into the sidebar from row *y, at most 'maxrows' rows */ -static void -side_text(int *y, int cols, const char *text, int maxrows) -{ - int rows = 0; - - while (*text != '\0' && rows < maxrows && *y < getmaxy(ui_side)) { - size_t n = strlen(text), take = n; - - if (take > (size_t)cols - 1) { - take = (size_t)cols - 1; - while (take > 0 && text[take] != ' ') - take--; - if (take == 0) - take = (size_t)cols - 1; - } - mvwaddnstr(ui_side, (*y)++, 0, text, (int)take); - rows++; - text += take; - while (*text == ' ') - text++; - } -} - -/* - * A path, wrapped at its slashes: "/home/k/src/splinter/plugins" cuts after a - * "/", never in the middle of a name. A path is what the operator checks first - * when a tool wrote somewhere it should not have. - */ -static void -side_path(int *y, int cols, const char *path, int maxrows) -{ - int rows = 0; - size_t len = strlen(path), off = 0; - size_t width = (size_t)cols - 1; - - if (width < 4) - width = 4; - while (off < len && rows < maxrows && *y < getmaxy(ui_side)) { - size_t take = len - off, cut; - - if (take > width) { - take = width; - cut = take; - while (cut > 0 && path[off + cut] != '/') - cut--; - if (cut == 0) - take = width; /* no slash in reach: hard cut */ - else - take = cut + 1; /* keep the slash on this line */ - } - mvwaddnstr(ui_side, (*y)++, 0, path + off, (int)take); - off += take; - rows++; - } -} - -static void -draw_sidebar(struct ui_state *s, const char *id, const char *dir, - struct sp_host *host) -{ - int cols, y = 0; - char key[64]; - const char *act = sp_usage_active(); - - if (ui_side == NULL) - return; /* one text field: no sidebar */ - - (void)dir; - cols = getmaxx(ui_side); - werase(ui_side); - - /* who is answering: the profile, the provider, the model */ - sidebar_heading(&y, cols, sp_t("sidebar.model")); - if (s->agents.n > 0) { - wattron(ui_side, A_BOLD); - { - char tag[64]; - - snprintf(tag, sizeof(tag), "[%s]", - s->agents.v[s->agent_cur].name); - mvwaddnstr(ui_side, y++, 0, tag, cols - 1); - } - wattroff(ui_side, A_BOLD); - } - { - char line[300]; - - snprintf(line, sizeof(line), "%s%s%s", act, - g_model[0] != '\0' ? " / " : "", g_model); - side_text(&y, cols, line, 2); - } - y++; - - /* how much of each allowance is used: the provider in use, and any that - * has a limit or is benched */ - { - const struct sp_config *cfg = s->conf; - struct sp_usage u; - size_t i; - int printed = 0; - char brief[96], line[200]; - - for (i = 0; i <= (cfg != NULL ? cfg->ndelegates : 0); i++) { - const char *pid = i == 0 ? act : cfg->delegate[i - 1].id; - - if (i > 0 && strcmp(pid, act) == 0) - continue; - sp_usage_for(cfg, pid, &u); - if (i > 0 && u.frac < 0 && u.benched_until == 0) - continue; - if (!printed) { - sidebar_heading(&y, cols, sp_t("sidebar.usage")); - printed = 1; - } - sp_usage_brief(&u, brief, sizeof(brief)); - snprintf(line, sizeof(line), "%-9.9s %s", pid, brief); - if (u.frac >= 0.9 || u.benched_until > 0) - wattron(ui_side, COLOR_PAIR(PAIR_ACCENT) | A_BOLD); - if (y < getmaxy(ui_side)) - mvwaddnstr(ui_side, y++, 0, line, cols - 1); - wattrset(ui_side, COLOR_PAIR(PAIR_MAIN)); - } - if (printed) - y++; - } - - /* what the plugins want to show: the goal, the plan, tasks ... */ - if (host != NULL && sp_host_widget_count(host) > 0) { - char snap[1024], *line, *save = NULL; - - sp_host_widget_snapshot(host, snap, sizeof(snap)); - for (line = strtok_r(snap, "\n", &save); line != NULL; - line = strtok_r(NULL, "\n", &save)) { - char name[48], *colon = strchr(line, ':'); - char *text; - size_t nl; - - if (colon == NULL) - continue; - nl = (size_t)(colon - line); - if (nl >= sizeof(name)) - continue; - memcpy(name, line, nl); - name[nl] = '\0'; - text = colon + 1; - while (*text == ' ') - text++; - /* a text that repeats its own name ("plan: 0 tasks") */ - if (strncmp(text, name, nl) == 0 && text[nl] == ':') { - text += nl + 1; - while (*text == ' ') - text++; - } - if (*text == '\0' || y >= getmaxy(ui_side) - 2) - continue; - snprintf(key, sizeof(key), "widget.%s", name); - sidebar_heading(&y, cols, sp_td(key, name)); - side_text(&y, cols, text, 4); - y++; - } - } - - /* the last turn, in one line - two where the column is narrow */ - if (s->last_ms > 0 && y < getmaxy(ui_side) - 2) { - char line[160]; - - sidebar_heading(&y, cols, sp_t("sidebar.last_turn")); - snprintf(line, sizeof(line), sp_t("sidebar.turn_line"), - (double)s->last_ms / 1000.0, s->last_steps, s->last_calls); - side_text(&y, cols, line, 2); - if (s->tokens_out > 0) { - snprintf(line, sizeof(line), sp_t("sidebar.tokens"), - s->tokens_out, s->tokens_in); - side_text(&y, cols, line, 1); - } - y++; - } - - if (id != NULL && y < getmaxy(ui_side) - 2) { - sidebar_heading(&y, cols, sp_t("sidebar.session")); - wattron(ui_side, COLOR_PAIR(PAIR_DIM)); - side_text(&y, cols, id, 1); - } - /* - * Where this splinter runs. Every tool acts relative to it, so it has to - * be on screen: a delegate that wrote into the wrong tree was the one - * question nobody could answer from the screen. $HOME is shown as ~. - */ - { - char cwd[700], shown[760]; - const char *home = getenv("HOME"); - - if (getcwd(cwd, sizeof(cwd)) != NULL) { - if (home != NULL && *home != '\0' && - strncmp(cwd, home, strlen(home)) == 0 && - (cwd[strlen(home)] == '/' || cwd[strlen(home)] == '\0')) - snprintf(shown, sizeof(shown), "~%s", cwd + strlen(home)); - else - snprintf(shown, sizeof(shown), "%s", cwd); - sidebar_heading(&y, cols, sp_t("sidebar.cwd")); - wattron(ui_side, COLOR_PAIR(PAIR_DIM)); - side_path(&y, cols, shown, 4); - } - } - wattrset(ui_side, A_NORMAL); - - wnoutrefresh(ui_side); -} - -/* - * Feed the meter the status plugins read. The harness counts; a plugin must not - * count for itself or the two numbers drift apart. - */ -static struct sp_host *g_status_host; - -/* the UI's fields of the meter; the tasks plugin owns others */ -static void -set_ui_fields(struct sp_meter *m, void *ctx) -{ - const struct ui_state *s = ctx; - const char *ctxmax = getenv("SPLINTER_CTX_MAX"); - - m->ctx_used = s->tokens_in; - if (ctxmax != NULL && *ctxmax != '\0') - m->ctx_max = (size_t)strtoul(ctxmax, NULL, 10); - m->tok_in = s->tokens_in; - m->tok_out = s->tokens_out; - if (s->last_ms > 0 && s->tokens_out > 0) - m->tps = (long)((double)s->tokens_out * 1000.0 / - (double)s->last_ms); -} - -static void -update_meter(struct ui_state *s, struct sp_host *host) -{ - if (host != NULL) - sp_host_meter_update(host, set_ui_fields, s); -} - - -static void -hist_load(struct ui_state *s, const char *dir) -{ - char path[600]; - FILE *f; - - if (dir == NULL) - return; - snprintf(path, sizeof(path), "%s/history", dir); - f = fopen(path, "r"); - if (f == NULL) - return; - while (s->nhist < 128 && fgets(s->hist[s->nhist], 1024, f) != NULL) { - s->hist[s->nhist][strcspn(s->hist[s->nhist], "\r\n")] = '\0'; - if (s->hist[s->nhist][0] != '\0') - s->nhist++; - } - fclose(f); - s->hist_pos = -1; -} - -static void -hist_push(struct ui_state *s, const char *dir, const char *line) -{ - char path[600]; - FILE *f; - - if (line == NULL || line[0] == '\0') - return; - /* typing the same thing twice in a row is not two history entries */ - if (s->nhist > 0 && strcmp(s->hist[s->nhist - 1], line) == 0) - return; - if (s->nhist == 128) { - memmove(&s->hist[0], &s->hist[1], sizeof(s->hist[0]) * 127); - s->nhist--; - } - snprintf(s->hist[s->nhist], 1024, "%s", line); - s->nhist++; - s->hist_pos = -1; - - if (dir == NULL) - return; - snprintf(path, sizeof(path), "%s/history", dir); - f = fopen(path, "a"); - if (f == NULL) - return; - fprintf(f, "%s\n", line); - fclose(f); -} - -/* Replace an entry's text in place: a streaming turn keeps one entry per role - * and rewrites it, so the transcript grows where the reader is looking. */ -static void -entry_set_text(struct ui_state *s, size_t id, const char *text) -{ - char *copy; - size_t i; - - for (i = s->n; i > 0; i--) /* the live entry is near the end */ - if (s->entries[i - 1].id == id) - break; - if (i == 0) - return; /* evicted meanwhile: nothing to do */ - copy = strdup(text != NULL ? text : ""); - if (copy == NULL) - return; - free(s->entries[i - 1].text); - s->entries[i - 1].text = copy; - /* the wrapped lines belong to the old text */ - if (s->entries[i - 1].cache != NULL) { - elayout_free(s->entries[i - 1].cache); - free(s->entries[i - 1].cache); - s->entries[i - 1].cache = NULL; - } -} - -/* - * Append an entry and return its id. Callers that update an entry later (the - * live answer, the reasoning) keep the id, not the index: at MAX_ENTRIES the - * oldest entry is evicted and every index moves by one - the streamed answer - * then went into the wrong entry, or into none. - */ -static size_t -add_entry(struct ui_state *s, const char *role, const char *text) -{ - struct entry *e; - size_t id; - - if (s->n == MAX_ENTRIES) { - free(s->entries[0].role); - free(s->entries[0].text); - if (s->entries[0].cache != NULL) { - elayout_free(s->entries[0].cache); - free(s->entries[0].cache); - } - memmove(&s->entries[0], &s->entries[1], - sizeof(s->entries[0]) * (MAX_ENTRIES - 1)); - s->n--; - } - e = &s->entries[s->n++]; - e->role = strdup(role != NULL ? role : "?"); - e->text = strdup(text != NULL ? text : ""); - if (e->role == NULL || e->text == NULL) { - /* out of memory: an entry with no text is better than a NULL */ - free(e->role); - free(e->text); - s->n--; - return 0; - } - e->ts = time(NULL); - e->id = id = ++s->next_id; - e->cache = NULL; - e->cache_cols = 0; - { - struct tm tm; - int day; - - (void)localtime_r(&e->ts, &tm); - day = tm.tm_yday + tm.tm_year * 400; - if (s->last_day != 0 && day != s->last_day) { - char stamp[64]; - struct entry *d; - - /* - * The day changed while splinter was running. Say it once, in - * the chat, so a transcript that spans midnight still reads in - * order - and never again until it changes again. - */ - strftime(stamp, sizeof(stamp), "--- %Y-%m-%d ---", &tm); - if (s->n < MAX_ENTRIES) { - d = &s->entries[s->n]; - d->role = strdup("splinter"); - d->text = strdup(stamp); - if (d->role != NULL && d->text != NULL) { - d->ts = e->ts; - d->id = ++s->next_id; - d->cache = NULL; - d->cache_cols = 0; - s->n++; - } else { - free(d->role); - free(d->text); - } - } - } - s->last_day = day; - } - return id; -} - -/* - * Switch the agent profile: its tool policy and prompt take effect on the next - * turn, and its model (if it names one) answers it. The provider the chat was - * on is remembered the first time a profile moves it and comes back with the - * next profile that names no model. - */ -/* a built-in profile's description in the user's language */ -static const char * -agent_desc(const struct sp_agent_def *d) -{ - if (strcmp(d->source, "(built in)") == 0) { - if (strcmp(d->name, "build") == 0) - return sp_t("agent.desc.build"); - if (strcmp(d->name, "plan") == 0) - return sp_t("agent.desc.plan"); - } - return d->description; -} - -static void -agent_switch(struct ui_state *s, struct sp_agent *ag, int idx, int announce) -{ - const struct sp_agent_def *d; - char msg[400]; - - if (s->agents.n == 0 || idx < 0 || (size_t)idx >= s->agents.n) - return; - d = &s->agents.v[idx]; - s->agent_cur = idx; - snprintf(ui_agent, sizeof(ui_agent), "%.24s", d->name); - (void)sp_agents_activate(ag, d, s->base_prompt != NULL ? - s->base_prompt : "", &s->policy); - if (s->conf != NULL) { - struct sp_choice ch; - const char *want = d->model[0] != '\0' ? d->model : - (s->home_id[0] != '\0' ? s->home_id : NULL); - - if (want != NULL && sp_provider_choose(s->conf, want, &ch) == 0 && - strcmp(ch.d->kind, "cli") != 0 && ch.d->endpoint[0] != '\0') { - struct sp_buf perr; - - if (d->model[0] != '\0' && s->home_id[0] == '\0') - snprintf(s->home_id, sizeof(s->home_id), "%s", - sp_usage_active()); - if (sp_buf_init(&perr) == 0) { - if (sp_provider_apply(ag, ch.d->kind, - ch.d->endpoint, - ch.model[0] != '\0' ? ch.model : ch.d->model, - ch.d->key_env, &perr) == 0) { - sp_usage_set_active(ch.d->id); - snprintf(s->cur_model, sizeof(s->cur_model), - "%s", ch.model[0] != '\0' ? ch.model : - ch.d->model); - snprintf(s->cur_endpoint, - sizeof(s->cur_endpoint), "%s", - ch.d->endpoint); - } - sp_buf_free(&perr); - } - if (d->model[0] == '\0') - s->home_id[0] = '\0'; - } - } - if (announce) { - snprintf(msg, sizeof(msg), sp_t("agent.switched"), d->name, - agent_desc(d), d->max_auth == 0 ? sp_t("agent.readonly") : ""); - add_entry(s, "splinter", msg); - } -} - -static void -layout(void) -{ - int rows, cols; - - getmaxyx(stdscr, rows, cols); - /* - * The conversation on three quarters, the sidebar on the last one, the - * input below both. The conversation starts at the top and grows - * downward; what was written stays where it is. - */ - { - int side_w = cols / 4; - int chat_w = cols - side_w - 1; - - if (side_w < 18) - side_w = cols > 50 ? 18 : 0; - if (side_w == 0) - chat_w = cols; - ui_hist = newwin(rows - 1, chat_w, 0, 0); - ui_side = side_w > 0 ? - newwin(rows - 1, side_w, 0, chat_w + 1) : NULL; - } - wbkgd(ui_hist, COLOR_PAIR(PAIR_MAIN)); - ui_input = newwin(1, cols, rows - 1, 0); - wbkgd(ui_input, COLOR_PAIR(PAIR_INPUT)); - keypad(ui_input, TRUE); - /* a one-line window that may scroll is a screen that jumps */ - scrollok(ui_input, FALSE); -} - -/* - * The terminal changed size: the windows were cut for the old one. layout() - * used to run once, so after a resize the four windows kept their old - * geometry and drew over each other. - */ -static void -relayout(int input_timeout_ms) -{ - if (ui_hist != NULL) - delwin(ui_hist); - if (ui_side != NULL) - delwin(ui_side); - if (ui_input != NULL) - delwin(ui_input); - ui_hist = ui_side = ui_input = NULL; - layout(); - wtimeout(ui_input, input_timeout_ms); - clearok(curscr, TRUE); -} - -/* the session id and directory the sidebar shows, NULL-safe */ -#define SESS_ID(ag) ((ag)->sess != NULL ? (ag)->sess->id : NULL) -#define SESS_DIR(ag) ((ag)->sess != NULL ? (ag)->sess->dir : NULL) - -/* history, sidebar and status line, then one doupdate() */ -static void -redraw(struct ui_state *s, struct sp_agent *ag, struct sp_host *host) -{ - draw_history(s); - draw_sidebar(s, SESS_ID(ag), SESS_DIR(ag), host); - doupdate(); -} - -/* - * The prompt mark, always followed by one space: the catalogue reader trims - * trailing blanks, so "> " in the .msg file arrives as ">". - */ -static const char * -prompt_mark(void) -{ - static char buf[64]; - const char *m = sp_t("ui.prompt_mark"); - size_t n = strlen(m); - - snprintf(buf, sizeof(buf), "%s%s%s", ui_agent, m, - n > 0 && m[n - 1] == ' ' ? "" : " "); - return buf; -} - -/* the prompt line with what has been typed so far */ -static void -draw_prompt(const char *input) -{ - const char *mark = prompt_mark(); - char *ascii; - size_t n, avail, cap; - int w = getmaxx(ui_input); - - werase(ui_input); - mvwaddstr(ui_input, 0, 0, mark); - /* - * The line is one row and never wraps: when the text is longer than the - * room, the end of it stays visible and the start scrolls out to the - * left. The last column stays empty -- writing into the bottom-right - * cell of a window that cannot scroll is an error in curses, and in - * this port a crash. - */ - avail = (size_t)(w - (int)strlen(mark) - 2); - if (input == NULL || w < 8 || avail < 1) - return; - cap = strlen(input) * 4 + 16; - ascii = malloc(cap); - if (ascii == NULL) - return; - if (sp_ui_ascii(input, ascii, cap) != 0) - snprintf(ascii, cap, "%s", input); - n = strlen(ascii); - if (n > avail) - waddnstr(ui_input, ascii + (n - avail), (int)avail); - else - waddnstr(ui_input, ascii, (int)n); - free(ascii); -} - -/* - * Read one line at the prompt. Enter ends it; Ctrl-D sets s->quit. While no - * key comes, the read times out every 500 ms and repaints sidebar and status - * line: a widget that ticks is useless if the screen only refreshes on a key. - */ -static int -slash_add_match(char matches[][64], int *n, int max, const char *name) -{ - int i; - if (name == NULL || *name == '\0' || *n >= max) - return 0; - for (i = 0; i < *n; i++) - if (strcmp(matches[i], name) == 0) - return 0; - snprintf(matches[(*n)++], 64, "%s", name); - return 1; -} - -static int -slash_collect(struct sp_agent *ag, struct sp_host *host, - char matches[][64], int max) -{ - int n = 0; - struct sp_buf b; - char cdir[700], *p, *tok, *save; - - slash_add_match(matches, &n, max, "status"); - slash_add_match(matches, &n, max, "usage"); - slash_add_match(matches, &n, max, "widgets"); - slash_add_match(matches, &n, max, "agent"); - slash_add_match(matches, &n, max, "resume"); - slash_add_match(matches, &n, max, "swarm"); - if (host != NULL && sp_buf_init(&b) == 0) { - if (sp_host_command_help(host, &b) > 0 && b.p != NULL) { - for (tok = strtok_r(b.p, " \t\r\n", &save); tok != NULL; - tok = strtok_r(NULL, " \t\r\n", &save)) { - p = tok; - if (*p == '/') - p++; - if (*p != '\0') - slash_add_match(matches, &n, max, p); - } - } - sp_buf_free(&b); - } - if (sp_buf_init(&b) == 0) { - if (sp_cmdscript_dir(ag && ag->sess ? ag->sess->dir : NULL, - cdir, sizeof(cdir)) == 0 && - sp_cmdscript_list(cdir, &b) > 0 && b.p != NULL) { - for (tok = strtok_r(b.p, " \t\r\n", &save); tok != NULL; - tok = strtok_r(NULL, " \t\r\n", &save)) - if (*tok != '\0') - slash_add_match(matches, &n, max, tok); - } - sp_buf_free(&b); - } - /* simple sort for stable popup */ - for (int i = 1; i < n; i++) { - char tmp[64]; int j = i; - snprintf(tmp, sizeof(tmp), "%s", matches[i]); - while (j > 0 && strcmp(matches[j-1], tmp) > 0) { - snprintf(matches[j], 64, "%s", matches[j-1]); - j--; - } - snprintf(matches[j], 64, "%s", tmp); - } - return n; -} - -static void -ui_read_line(struct ui_state *s, struct sp_agent *ag, struct sp_host *host, - char *input, size_t cap) -{ - size_t len = 0; - int ch; - int locked = (s->sw != NULL && s->sw->role == SWARM_SLAVE && s->sw->locked); - - input[0] = '\0'; - if (locked) { - werase(ui_input); - mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); - wnoutrefresh(ui_input); - } else - draw_prompt(input); - wnoutrefresh(ui_input); - doupdate(); - wtimeout(ui_input, 500); - if (s->sw != NULL) - swarm_report_busy(s->sw, 0); - for (;;) { - /* poll fleet: accept/read, update lock/inbox */ - if (s->sw != NULL) { - swarm_poll(s->sw); - locked = (s->sw->role == SWARM_SLAVE && s->sw->locked); - if (swarm_take_inbox(s->sw, input, cap)) { - wtimeout(ui_input, -1); - return; - } - } - ch = wgetch(ui_input); - if (ch == ERR) { - { - char msg[200]; - int got = 0; - - while (sp_host_status_take(host, msg, sizeof(msg))) { - add_entry(s, "splinter", msg); - got = 1; - } - if (got) - draw_history(s); - } - draw_sidebar(s, SESS_ID(ag), SESS_DIR(ag), host); - if (locked) { - werase(ui_input); - mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); - wnoutrefresh(ui_input); - } else { - draw_prompt(input); - wnoutrefresh(ui_input); - } - doupdate(); - continue; - } - if (ch == '\n' || ch == '\r' || ch == KEY_ENTER) { - if (locked) continue; - break; - } - if (ch == 4) { - s->quit = 1; - break; - } - /* - * Ctrl-L repaints, KEY_RESIZE re-cuts the windows. - */ - if (ch == 12 || ch == KEY_RESIZE) { - if (ch == KEY_RESIZE) - relayout(500); - else - clearok(curscr, TRUE); - draw_history(s); - draw_sidebar(s, SESS_ID(ag), SESS_DIR(ag), host); - if (locked) { - werase(ui_input); - mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); - } else - draw_prompt(input); - wnoutrefresh(ui_input); - doupdate(); - continue; - } - if (ch == 3) { - if (locked) continue; - len = 0; - input[0] = '\0'; - draw_prompt(input); - wrefresh(ui_input); - continue; - } - if (ch == KEY_UP || ch == KEY_DOWN) { - if (locked || s->nhist == 0) - continue; - if (s->hist_pos < 0) - s->hist_pos = (int)s->nhist; - if (ch == KEY_UP && s->hist_pos > 0) - s->hist_pos--; - else if (ch == KEY_DOWN && s->hist_pos < (int)s->nhist - 1) - s->hist_pos++; - else if (ch == KEY_DOWN) - s->hist_pos = (int)s->nhist; - if (s->hist_pos >= (int)s->nhist || s->hist_pos < 0) - len = 0; - else { - snprintf(input, cap, "%s", s->hist[s->hist_pos]); - len = strlen(input); - } - input[len] = '\0'; - draw_prompt(input); - wrefresh(ui_input); - continue; - } - /* - * PgUp/PgDn and Shift+arrows scroll the chat pane. - */ - if (ch == KEY_PPAGE || ch == KEY_SR) { - s->scroll += (ch == KEY_SR ? 1 : 10); - draw_history(s); - draw_sidebar(s, SESS_ID(ag), SESS_DIR(ag), host); - if (locked) { - werase(ui_input); - mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); - } else - draw_prompt(input); - wnoutrefresh(ui_input); - doupdate(); - continue; - } - if (ch == KEY_NPAGE || ch == KEY_SF) { - size_t step = (ch == KEY_SF ? 1 : 10); - - s->scroll = s->scroll > step ? s->scroll - step : 0; - draw_history(s); - draw_sidebar(s, SESS_ID(ag), SESS_DIR(ag), host); - if (locked) { - werase(ui_input); - mvwaddstr(ui_input, 0, 0, sp_td("ui.swarm_locked", "[swarm locked] ")); - } else - draw_prompt(input); - wnoutrefresh(ui_input); - doupdate(); - continue; - } - if (ch == KEY_BACKSPACE || ch == 127 || ch == 8) { - if (locked) continue; - if (len > 0) { - /* drop a whole UTF-8 sequence, not half of one */ - do - len--; - while (len > 0 && ((unsigned char)input[len] & 0xc0) == 0x80); - input[len] = '\0'; - draw_prompt(input); - wrefresh(ui_input); - } - continue; - } - /* - * Tab (Shift-Tab back) switches the agent profile, unless a /command - * is being completed. - */ - if ((ch == '\t' || ch == KEY_BTAB) && - !(input[0] == '/' && strchr(input, ' ') == NULL)) { - if (locked || s->agents.n < 2) - continue; - agent_switch(s, ag, ch == '\t' ? - (s->agent_cur + 1) % (int)s->agents.n : - (s->agent_cur + (int)s->agents.n - 1) % (int)s->agents.n, - 1); - draw_history(s); - draw_sidebar(s, SESS_ID(ag), SESS_DIR(ag), host); - draw_prompt(input); - wnoutrefresh(ui_input); - doupdate(); - continue; - } - /* - * Slash completion: Tab shows available /commands. - */ - if (ch == '\t' && input[0] == '/' && strchr(input, ' ') == NULL) { - if (locked) continue; - { - char matches[32][64]; - int nm = slash_collect(ag, host, matches, 32); - const char *prefix = input + 1; - size_t plen = strlen(prefix); - char *m[32]; - int k = 0, i2; - - for (i2 = 0; i2 < nm; i2++) - if (strncmp(matches[i2], prefix, plen) == 0) - m[k++] = matches[i2]; - if (k == 1) { - snprintf(input, cap, "/%s ", m[0]); - len = strlen(input); - } else if (k > 1) { - size_t c = strlen(m[0]); - for (i2 = 1; i2 < k; i2++) { - size_t j = 0; - while (j < c && m[0][j] == m[i2][j]) j++; - c = j; - } - if (c > plen) { - snprintf(input, cap, "/%.*s", (int)c, m[0]); - len = strlen(input); - } - { - char hint[512]; size_t off = 0; - off += snprintf(hint + off, sizeof(hint) - off, " "); - for (i2 = 0; i2 < k && off + 2 < sizeof(hint); i2++) - off += snprintf(hint + off, sizeof(hint) - off, "/%s ", m[i2]); - { - /* no status bar: the last row */ - int hy = getmaxy(ui_hist) - 1; - - wattron(ui_hist, COLOR_PAIR(PAIR_STATUS)); - mvwhline(ui_hist, hy, 0, ' ', getmaxx(ui_hist)); - mvwaddnstr(ui_hist, hy, 0, hint, getmaxx(ui_hist) - 1); - wattroff(ui_hist, COLOR_PAIR(PAIR_STATUS)); - wnoutrefresh(ui_hist); - } - } - } - draw_prompt(input); - wnoutrefresh(ui_input); - doupdate(); - } - continue; - } - if (locked) - continue; - if (ch >= 32 && ch < 256 && len + 1 < cap) { - input[len++] = (char)ch; - input[len] = '\0'; - draw_prompt(input); - wrefresh(ui_input); - } - } - wtimeout(ui_input, -1); -} - - -static void -ui_shell(struct ui_state *s, struct sp_agent *ag, const char *cmd) -{ - FILE *fp; - char buf[8192]; - size_t n = 0; - char shcmd[4096]; - int c; - (void)ag; - snprintf(shcmd, sizeof(shcmd), "sh -c '%.*s' 2>&1", - (int)(sizeof(shcmd) - 20), cmd); - /* simple: avoid single quotes breaking; MVP */ - fp = popen(cmd, "r"); - if (fp == NULL) { - add_entry(s, "shell", "popen failed"); - return; - } - while (n + 1 < sizeof(buf) && (c = fgetc(fp)) != EOF) - buf[n++] = (char)c; - buf[n] = '\0'; - pclose(fp); - add_entry(s, "shell", n > 0 ? buf : "(no output)"); -} - -/* - * A leading slash is a command for the harness, not a prompt: it never reaches - * the model, and its reply is shown as the harness speaking. Unknown commands - * list what exists. Returns 1 when the line was handled; 0 when a program in - * commands/ replaced it with text for the model, so a turn runs with 'input'. - */ -/* /connect in the terminal: the same questions the gateway asks, per line */ -static void -ui_connect_ask(struct ui_state *s, struct sp_buf *out) -{ - switch (s->cc.step) { - case 1: - sp_buf_puts(out, sp_t("connect.endpoint")); - break; - case 2: - sp_buf_puts(out, sp_t("connect.model")); - break; - case 3: - if (s->cc.key_env[0] != '\0') - sp_buf_printf(out, sp_t("connect.key_named"), - s->cc.key_env); - else - sp_buf_puts(out, sp_t("connect.key")); - break; - default: - sp_buf_puts(out, sp_t("connect.name")); - break; - } -} - -/* returns 1: the line was an answer (handled), 0: nothing is running */ -static int -ui_connect_answer(struct ui_state *s, struct sp_agent *ag, const char *line, - struct sp_buf *out) -{ - (void)ag; - if (!s->cc.active) - return 0; - if (strcmp(line, "/cancel") == 0 || strcasecmp(line, "cancel") == 0) { - memset(&s->cc, 0, sizeof(s->cc)); - sp_buf_puts(out, sp_t("connect.cancel")); - return 1; - } - switch (s->cc.step) { - case 0: - if (!sp_provider_id_ok(line)) { - sp_buf_puts(out, sp_t("connect.name_bad")); - return 1; - } - snprintf(s->cc.id, sizeof(s->cc.id), "%s", line); - break; - case 1: - if (strcmp(line, "ollama") == 0) { - snprintf(s->cc.endpoint, sizeof(s->cc.endpoint), - "http://127.0.0.1:11434/v1"); - } else if (strcmp(line, "opencode") == 0) { - snprintf(s->cc.endpoint, sizeof(s->cc.endpoint), - "https://opencode.ai/zen/go/v1"); - snprintf(s->cc.key_env, sizeof(s->cc.key_env), - "OPENCODE_GO_API_KEY"); - } else if (!sp_provider_endpoint_ok(line)) { - sp_buf_puts(out, sp_t("connect.endpoint_bad")); - return 1; - } else { - snprintf(s->cc.endpoint, sizeof(s->cc.endpoint), "%s", - line); - } - break; - case 2: - if (!sp_provider_model_ok(line)) { - sp_buf_puts(out, sp_t("connect.model_bad")); - return 1; - } - snprintf(s->cc.model, sizeof(s->cc.model), "%s", line); - break; - default: - if (strcmp(line, "-") == 0) - s->cc.key_env[0] = '\0'; - else if (strcmp(line, "/skip") != 0) { - if (!sp_provider_key_ok(line)) { - sp_buf_puts(out, sp_t("connect.key_bad")); - return 1; - } - snprintf(s->cc.key_env, sizeof(s->cc.key_env), "%s", - line); - } - { - char dir[720]; - struct sp_buf cerr; - - sp_buf_init(&cerr); - if (s->conf == NULL || - sp_provider_dir(dir, sizeof(dir)) != 0) { - sp_buf_puts(out, sp_t("connect.nodir")); - } else if (sp_provider_add(s->conf, dir, s->cc.id, - s->cc.endpoint, s->cc.model, s->cc.key_env, - &cerr) != 0) { - sp_buf_printf(out, sp_t("connect.failed"), - cerr.p != NULL ? cerr.p : "?"); - } else { - sp_buf_printf(out, sp_t("connect.saved"), - s->cc.id, s->cc.model, s->cc.endpoint); - } - sp_buf_free(&cerr); - } - memset(&s->cc, 0, sizeof(s->cc)); - return 1; - } - s->cc.step++; - sp_buf_puts(out, "\n"); - ui_connect_ask(s, out); - return 1; -} - -static int -ui_slash(struct ui_state *s, struct sp_agent *ag, struct sp_host *host, - char *input, size_t cap) -{ - char name[64], args[1536], outbuf[2048], cdir[700]; - struct sp_buf out, cerr; - const char *sp; - - sp = strchr(input, ' '); - if (sp == NULL) { - snprintf(name, sizeof(name), "%.63s", input + 1); - args[0] = '\0'; - } else { - size_t nlen = (size_t)(sp - (input + 1)); - - if (nlen >= sizeof(name)) - nlen = sizeof(name) - 1; - memcpy(name, input + 1, nlen); - name[nlen] = '\0'; - snprintf(args, sizeof(args), "%s", sp + 1); - } - if (sp_buf_init(&out) != 0) - return 1; - if (strcmp(name, "agent") == 0 || strcmp(name, "agents") == 0) { - size_t i; - - if (args[0] != '\0') { - int idx = sp_agents_find(&s->agents, args); - - if (idx < 0) - { - sp_buf_printf(&out, sp_t("agent.none"), args); - sp_buf_puts(&out, "\n"); - } - else { - agent_switch(s, ag, idx, 1); - snprintf(outbuf, sizeof(outbuf), "%s", ""); - sp_buf_free(&out); - return 1; - } - } - { - for (i = 0; i < s->agents.n; i++) { - const struct sp_agent_def *d = &s->agents.v[i]; - - sp_buf_printf(&out, "%c %-12s %s %s\n", - (int)i == s->agent_cur ? '*' : ' ', d->name, - agent_desc(d), d->max_auth == 0 ? - sp_t("agent.readonly") : ""); - if (strcmp(d->source, "(built in)") != 0) - sp_buf_printf(&out, " %s\n", d->source); - } - } - sp_buf_puts(&out, sp_t("agent.help")); - snprintf(outbuf, sizeof(outbuf), "%s", out.p ? out.p : ""); - sp_buf_free(&out); - add_entry(s, "splinter", outbuf); - return 1; - } - if (strcmp(name, "quit") == 0 || strcmp(name, "exit") == 0 || - strcmp(name, "q") == 0) { - s->quit = 1; - sp_buf_free(&out); - return 1; - } - /* - * /widgets: what a plugin published. The sidebar used to show these lines - * all the time; one text field shows them when asked, as text. - */ - if (strcmp(name, "widgets") == 0 || strcmp(name, "widget") == 0) { - char buf[4096]; - - if (host == NULL || sp_host_widget_count(host) == 0) - sp_buf_puts(&out, sp_t("widgets.none")); - else if (sp_host_widget_snapshot(host, buf, sizeof(buf)) > 0) - sp_buf_printf(&out, "%s", buf); - snprintf(outbuf, sizeof(outbuf), "%s", out.p != NULL ? out.p : ""); - sp_buf_free(&out); - add_entry(s, "splinter", outbuf); - return 1; - } - if (strcmp(name, "usage") == 0) { - sp_usage_report(s->conf, &out); - snprintf(outbuf, sizeof(outbuf), "%s", out.p ? out.p : ""); - sp_buf_free(&out); - add_entry(s, "splinter", outbuf); - return 1; - } - if (strcmp(name, "status") == 0) { - size_t comp = 0, failed = 0; unsigned turns = 0; - time_t now = time(NULL); - char tbuf[64]; - struct tm tm; - - (void)localtime_r(&now, &tm); - strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tm); - sp_host_compaction_stats(host, &comp, &failed, &turns); - sp_buf_printf(&out, "status (%s)\n", tbuf); - sp_buf_printf(&out, " session %s\n dir %s\n", - ag->sess ? ag->sess->id : "-", ag->sess ? ag->sess->dir : "-"); - sp_buf_printf(&out, " model %s\n endpoint %s\n theme %s\n", - s->model ? s->model : "-", s->endpoint ? s->endpoint : "-", - s->theme.name); - sp_buf_printf(&out, " last %ld ms, %zu steps, %zu tool calls\n", - s->last_ms, s->last_steps, s->last_calls); - sp_buf_printf(&out, " tokens in %zu, out %zu (session stats in %zu out %zu)\n", - s->tokens_in, s->tokens_out, - ag->stats.tokens_in, ag->stats.tokens_out); - sp_buf_printf(&out, " output %zu chars this turn, %zu total\n", - s->out_chars, s->total_out_chars); - sp_buf_printf(&out, " compact %zu applied, %zu failed, %zu turns (agent %zu)\n", - comp, failed, turns, ag->stats.compactions); - if (ag->cfg != NULL) - sp_buf_printf(&out, " limits max_bytes %zu, max_steps %zu%s\n", - ag->cfg->max_bytes, ag->cfg->max_steps, - ag->cfg->autonomous ? ", autonomous" : ""); - if (host != NULL) { - struct sp_meter m; - char seg[512]; - - sp_host_meter_get(host, &m); - sp_buf_printf(&out, " meter ctx %zu/%zu, cache %zu, tok %zu/%zu\n", - m.ctx_used, m.ctx_max, m.cached, m.tok_in, m.tok_out); - update_meter(s, host); - if (sp_host_status_text(host, seg, sizeof(seg)) > 0) - sp_buf_printf(&out, " bar %s\n", seg); - } - if (s->sw != NULL && s->sw->role != SWARM_NONE) { - char sws[256], list[1024]; - swarm_status(s->sw, sws, sizeof(sws)); - sp_buf_printf(&out, " swarm %s (id %d)\n", sws, s->sw->id); - swarm_list(s->sw, list, sizeof(list)); - sp_buf_printf(&out, "%s", list); - } - snprintf(outbuf, sizeof(outbuf), "%s", out.p ? out.p : ""); - sp_buf_free(&out); - add_entry(s, "splinter", outbuf); - return 1; - } - if (strcmp(name, "swarm") == 0) { - char list[1024]; - if (s->sw == NULL || s->sw->role == SWARM_NONE) { - sp_buf_printf(&out, "swarm: standalone (no fleet in %s)", SWARM_PATH); - } else if (args[0] == '\0' || strcmp(args, "ls") == 0 || strcmp(args, "list") == 0) { - swarm_list(s->sw, list, sizeof(list)); - sp_buf_printf(&out, "%s", list); - } else { - const char *p = args; - char *end; - long id = -1; - int target; - while (*p == ' ') p++; - if (*p >= '0' && *p <= '9') { - id = strtol(p, &end, 10); - p = end; - while (*p == ' ') p++; - } - if (*p == '\0') { - sp_buf_printf(&out, "usage: /swarm [N] (0=master, no N=least busy)\n /swarm ls"); - } else { - if (s->sw->role != SWARM_MASTER && id != 0) { - /* slave: forward request to master? MVP: only master routes */ - sp_buf_printf(&out, "swarm: only master (0) can route commands"); - } else { - target = swarm_route(s->sw, (int)id, p); - if (target < 0) - sp_buf_printf(&out, "swarm: route failed (id %ld)", id); - else - sp_buf_printf(&out, "swarm: routed to %d", target); - } - } - } - snprintf(outbuf, sizeof(outbuf), "%s", out.p ? out.p : ""); - sp_buf_free(&out); - add_entry(s, "splinter", outbuf); - return 1; - } - /* - * /model: the same list the gateway offers, without buttons. No argument - * lists them, an id switches provider, any other word is a model on the - * current endpoint. The choice is written for the next start, like the - * gateway's. - */ - if (strcmp(name, "model") == 0) { - struct sp_provider p; - struct sp_buf perr, serr; - size_t idx = 0, i, n; - char poolname[40]; - int is_pool = 0; - - /* - * A pool is a selector too, and so is "pool/model": the run starts - * on the member with the most room and moves at a limit, exactly - * what naming the pool in -m does. - */ - snprintf(poolname, sizeof(poolname), "%s", args); - is_pool = sp_pool_find(s->conf, args) != NULL; - if (!is_pool) { - const char *sl = strchr(args, '/'); - - if (sl != NULL && (size_t)(sl - args) < sizeof(poolname)) { - memcpy(poolname, args, (size_t)(sl - args)); - poolname[sl - args] = '\0'; - is_pool = sp_pool_find(s->conf, poolname) != NULL; - } - } - - if (s->conf == NULL) { - sp_buf_puts(&out, sp_t("model.none")); - } else if (args[0] == '\0') { - sp_buf_puts(&out, sp_t("model.choose")); - n = sp_provider_count(s->conf); - for (i = 0; i < n; i++) - if (sp_provider_at(s->conf, i, &p) == 0) - sp_buf_printf(&out, "\n %s %s%s", - p.id, p.model, - strcmp(p.model, s->model) == 0 ? - " *" : ""); - /* a pool is a selector too: it starts on the member with - * the most room and moves at a limit */ - if (s->conf->npools > 0) - sp_buf_printf(&out, "\n%s", sp_t("model.pools")); - for (i = 0; i < s->conf->npools; i++) { - size_t j; - - sp_buf_printf(&out, "\n %s pool (%s):", - s->conf->pool[i].id, - s->conf->pool[i].strategy); - for (j = 0; j < s->conf->pool[i].nmembers; j++) - sp_buf_printf(&out, " %s", - s->conf->pool[i].member[j]); - } - } else if (is_pool) { - struct sp_choice ch; - - if (sp_provider_choose(s->conf, args, &ch) != 0) { - sp_buf_printf(&out, sp_t("model.unknown"), - args); - } else { - sp_buf_init(&perr); - if (sp_provider_apply(ag, ch.d->kind, - ch.d->endpoint, - ch.model[0] != '\0' ? ch.model : ch.d->model, - ch.d->key_env, &perr) != 0) { - sp_buf_printf(&out, sp_t("model.failed"), - perr.p != NULL ? perr.p : "?"); - } else { - sp_usage_set_active(ch.d->id); - snprintf(s->cur_endpoint, - sizeof(s->cur_endpoint), "%s", - ch.d->endpoint); - snprintf(s->cur_model, sizeof(s->cur_model), - "%s", ch.model[0] != '\0' ? - ch.model : ch.d->model); - sp_buf_printf(&out, sp_t("model.pool"), - poolname, s->cur_model, ch.d->id); - } - sp_buf_free(&perr); - } - } else if (sp_provider_find(s->conf, args, &idx)) { - sp_buf_init(&perr); - if (sp_provider_use(ag, s->conf, idx, &perr) != 0) { - sp_buf_printf(&out, sp_t("model.failed"), - perr.p != NULL ? perr.p : "?"); - } else if (sp_provider_at(s->conf, idx, &p) == 0) { - snprintf(s->cur_endpoint, - sizeof(s->cur_endpoint), "%s", p.endpoint); - snprintf(s->cur_model, sizeof(s->cur_model), - "%s", p.model); - sp_buf_init(&serr); - sp_buf_printf(&out, sp_provider_save_choice( - s->conf, &p, &serr) == 0 ? - sp_t("model.saved") : sp_t("model.switched"), - p.model, p.id); - sp_buf_free(&serr); - } - sp_buf_free(&perr); - } else { - struct sp_provider chosen; - int ok; - - memset(&p, 0, sizeof(p)); - if (!sp_provider_find(s->conf, s->model, &idx) || - sp_provider_at(s->conf, idx, &p) != 0) - (void)sp_provider_at(s->conf, 0, &p); - sp_buf_init(&perr); - ok = sp_provider_apply(ag, p.kind, p.endpoint, args, - p.key_env, &perr) == 0; - if (ok) { - memset(&chosen, 0, sizeof(chosen)); - snprintf(chosen.id, sizeof(chosen.id), "%s", - p.id); - snprintf(chosen.endpoint, - sizeof(chosen.endpoint), "%s", p.endpoint); - snprintf(chosen.model, sizeof(chosen.model), - "%s", args); - snprintf(chosen.key_env, sizeof(chosen.key_env), - "%s", p.key_env); - snprintf(s->cur_model, sizeof(s->cur_model), - "%s", args); - sp_buf_init(&serr); - sp_buf_printf(&out, sp_provider_save_choice( - s->conf, &chosen, &serr) == 0 ? - sp_t("model.saved") : sp_t("model.switched"), - args, p.id); - sp_buf_free(&serr); - } else { - sp_buf_printf(&out, sp_t("model.failed"), - perr.p != NULL ? perr.p : "?"); - } - sp_buf_free(&perr); - } - snprintf(outbuf, sizeof(outbuf), "%s", out.p ? out.p : ""); - sp_buf_free(&out); - add_entry(s, "splinter", outbuf); - return 1; - } - if (strcmp(name, "new") == 0 || strcmp(name, "reset") == 0) { - static struct sp_session_info fresh; - char id[64], dir[512]; - struct sp_buf serr; - - /* 'fresh' may be the current session: read the directory first */ - snprintf(dir, sizeof(dir), "%s", - ag->sess != NULL ? ag->sess->dir : ""); - memset(&fresh, 0, sizeof(fresh)); - snprintf(id, sizeof(id), "sess-%ld-%d", (long)time(NULL), - (int)getpid()); - sp_buf_init(&serr); - if (ag->sess == NULL || - sp_session_open(&fresh, dir, id, &serr) != 0 || - sp_conv_reset(ag->conv, ag->cfg != NULL ? - ag->cfg->system_prompt : NULL) != 0) { - sp_buf_printf(&out, sp_t("session.failed"), - serr.p != NULL ? serr.p : "?"); - } else { - ag->sess = &fresh; - s->n = 0; /* the pane is the old conversation */ - s->scroll = 0; - sp_buf_printf(&out, sp_t("session.new"), fresh.id); - } - sp_buf_free(&serr); - snprintf(outbuf, sizeof(outbuf), "%s", out.p ? out.p : ""); - sp_buf_free(&out); - add_entry(s, "splinter", outbuf); - return 1; - } - if (strcmp(name, "connect") == 0) { - if (sp_config_loaded_path() == NULL) { - /* --no-config: there is no file to write the line to */ - sp_buf_puts(&out, sp_t("connect.nodir")); - snprintf(outbuf, sizeof(outbuf), "%s", - out.p != NULL ? out.p : ""); - sp_buf_free(&out); - add_entry(s, "splinter", outbuf); - return 1; - } - memset(&s->cc, 0, sizeof(s->cc)); - s->cc.active = 1; - s->cc.step = 0; - sp_buf_puts(&out, sp_t("connect.start")); - sp_buf_puts(&out, "\n"); - ui_connect_ask(s, &out); - snprintf(outbuf, sizeof(outbuf), "%s", out.p ? out.p : ""); - sp_buf_free(&out); - add_entry(s, "splinter", outbuf); - return 1; - } - if (host != NULL && sp_host_command(host, name, args, &out) == 0) { - snprintf(outbuf, sizeof(outbuf), "%s", out.p != NULL ? out.p : ""); - sp_buf_free(&out); - add_entry(s, "splinter", outbuf); - return 1; - } - /* - * Not a plugin command. A program in commands/ wins over 'unknown': its - * output is not a reply for the operator, it is context for the model, - * so the turn runs after this. - */ - sp_buf_clear(&out); - if (sp_buf_init(&cerr) != 0) { - sp_buf_free(&out); - return 1; - } - if (sp_cmdscript_dir(SESS_DIR(ag), cdir, sizeof(cdir)) == 0 && - sp_cmdscript_exists(cdir, name) && - sp_slash_script(cdir, name, args, &out, &cerr) == 0 && - out.p != NULL) { - add_entry(s, "shell", out.p); - snprintf(input, cap, "%s", out.p); - sp_buf_free(&out); - sp_buf_free(&cerr); - return 0; - } - sp_buf_free(&cerr); - 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); - snprintf(outbuf, sizeof(outbuf), "%s", out.p != NULL ? out.p : ""); - sp_buf_free(&out); - add_entry(s, "splinter", outbuf); - return 1; -} - -/* what the screen keeps of a running turn between two ticks */ -struct turn_view { - struct timespec t0; - int drained; /* events already in the transcript */ - struct seg { - size_t id; /* entry showing the open part, 0 = none */ - size_t off; /* bytes before the open entry */ - size_t shown; /* bytes the open entry shows */ - } think, ans; /* the reasoning, the answer */ - char line[1024]; /* steering text being typed */ - size_t llen; -}; - -/* - * One growing text of the turn -- the reasoning, the answer -- shown append - * only. It grows in its entry while that entry is the last one. Once anything - * was appended below it (a tool line, the answer), that entry is left as it - * is and the rest of the text continues in a new entry at the bottom. Nothing - * that is on screen moves; the transcript only gets longer. - */ -static void -seg_show(struct ui_state *s, struct seg *g, const char *role, const char *text) -{ - size_t len = text != NULL ? strlen(text) : 0; - const char *p; - - if (g->off > len) { /* the buffer started over */ - g->off = 0; - g->shown = 0; - g->id = 0; - } - /* - * While the open entry is the last one it may keep growing. Once - * something was appended below it (a tool call, the answer), what is on - * screen stays as it is: the bytes it shows move into off and the rest - * continues in a new entry. That is the whole append-only rule. - */ - if (g->id != 0 && !(s->n > 0 && s->entries[s->n - 1].id == g->id)) { - g->off += g->shown; - g->shown = 0; - g->id = 0; - } - if (len <= g->off) - return; - p = text + g->off; - while (*p == '\n') - p++; - if (*p == '\0') - return; - if (g->id == 0) - g->id = add_entry(s, role, ""); - entry_set_text(s, g->id, p); - g->shown = len - g->off; -} - -/* a turn's side effects into the transcript: diffs, calls, compaction */ -static void -compact_cb(void *ctx, size_t before, size_t after, size_t mb, size_t ma) -{ - struct turn *t = ctx; - - pthread_mutex_lock(&t->lock); - if (t->compacted == 0) { - t->c_bytes_before = before; - t->c_msgs_before = mb; - } - t->c_bytes_after = after; - t->c_msgs_after = ma; - t->compacted++; - pthread_mutex_unlock(&t->lock); -} - -static void -turn_drain(struct ui_state *s, struct turn *tu, struct turn_view *v) -{ - int k, compacted = 0; - size_t cb = 0, ca = 0, cm = 0, cn = 0; - struct tun_ev ev[24]; - int nev = 0; - - pthread_mutex_lock(&tu->lock); - /* - * Take the events that arrived since the last tick, in order. The - * strings change hands here: the turn drops its pointer, the UI adds - * the entry and frees it. - */ - while (v->drained < tu->nev && nev < (int)(sizeof(ev) / sizeof(ev[0]))) { - ev[nev].kind = tu->ev[v->drained].kind; - ev[nev].text = tu->ev[v->drained].text; - tu->ev[v->drained].text = NULL; - nev++; - v->drained++; - } - compacted = tu->compacted; - cb = tu->c_bytes_before; ca = tu->c_bytes_after; - cm = tu->c_msgs_before; cn = tu->c_msgs_after; - tu->compacted = 0; - tu->c_bytes_before = tu->c_bytes_after = 0; - tu->c_msgs_before = tu->c_msgs_after = 0; - pthread_mutex_unlock(&tu->lock); - for (k = 0; k < nev; k++) { - const char *role; - - /* - * A one-line result ("[exit status 0]") joins the call row it - * belongs to; the call row is the entry just before it, because - * the queue keeps the order the turn produced. - */ - if (ev[k].kind == 's') { - if (s->n > 0) { - struct entry *e = &s->entries[s->n - 1]; - size_t need = strlen(e->text) + - strlen(ev[k].text) + 3; - char *joined = malloc(need); - - if (joined != NULL) { - snprintf(joined, need, "%s %s", e->text, - ev[k].text); - entry_set_text(s, e->id, joined); - free(joined); - } - } - free(ev[k].text); - continue; - } - role = ev[k].kind == 'x' ? "tool" : - ev[k].kind == 'o' ? "observation" : - ev[k].kind == 'n' ? "splinter" : - ev[k].kind == 't' ? "thinking" : "agent"; - /* the log gets what the screen gets, in the same order */ - if (ev[k].kind == 't') - sp_logf("thinking", "%s", ev[k].text); - add_entry(s, role, ev[k].text); - free(ev[k].text); - } - if (compacted > 0) { - char msg[256]; - size_t tb = cb / 4, ta = ca / 4; - - { - char b1[32], b2[32], t1[32], t2[32]; - - if (cb >= 1024) snprintf(b1, sizeof(b1), "%.1fKiB", cb/1024.0); else snprintf(b1, sizeof(b1), "%zuB", cb); - if (ca >= 1024) snprintf(b2, sizeof(b2), "%.1fKiB", ca/1024.0); else snprintf(b2, sizeof(b2), "%zuB", ca); - if (tb >= 1000) snprintf(t1, sizeof(t1), "~%.1fk tok", tb/1000.0); else snprintf(t1, sizeof(t1), "~%zu tok", tb); - if (ta >= 1000) snprintf(t2, sizeof(t2), "~%.1fk tok", ta/1000.0); else snprintf(t2, sizeof(t2), "~%zu tok", ta); - if (compacted == 1) - snprintf(msg, sizeof(msg), - "context compacted: %zu→%zu msgs, %s→%s (%s→%s)", - cm, cn, t1, t2, b1, b2); - else - snprintf(msg, sizeof(msg), - "context compacted %dx: %zu→%zu msgs, %s→%s (%s→%s)", - compacted, cm, cn, t1, t2, b1, b2); - } - add_entry(s, "splinter", msg); - } -} - -/* - * A tool needs permission. The question goes where the prompt is, and y/N - * answers it; the turn thread is parked on a condition variable until it - * does. Returns 1 while a question is open (the key is consumed). - */ -static int -turn_approval(struct turn *tu, int c) -{ - int pending, auth = SP_AUTH_READ; - char nm[64], ar[256]; - - pthread_mutex_lock(&tu->lock); - pending = tu->approve_pending; - if (pending) { - snprintf(nm, sizeof(nm), "%s", tu->approve_name); - snprintf(ar, sizeof(ar), "%s", tu->approve_args); - auth = tu->approve_auth; - } - pthread_mutex_unlock(&tu->lock); - /* - * Ctrl-C and Ctrl-D are not answers: they go on to turn_key, which - * cancels and wakes approve_cb. Swallowing them here left the operator - * no way out of a question but y or n. - */ - if (!pending || c == 3 || c == 4) - return 0; - /* - * The question names the call the way the transcript does - "Run touch - * /tmp/x" - and then how far it reaches. It used to read "run run - * (destructive) {"command": "..."}", with the verb twice and the raw - * arguments in it, which is not a question anybody can answer at a - * glance. - */ - { - char call[640], label[64], line[768]; - size_t over, n; - int w = getmaxx(ui_input) - 1; - - call_summary(nm, ar, call, sizeof(call)); - snprintf(label, sizeof(label), "%s", - auth == SP_AUTH_MUTATE ? sp_t("auth.mutate") : - sp_t("auth.destructive")); - snprintf(line, sizeof(line), sp_t("ui.approve"), call, label); - if ((int)strlen(line) > w) { - /* the call gives way; the class and "y/N" never do */ - over = strlen(line) - (size_t)w; - n = strlen(call); - cut_line(call, n > over + 4 ? n - over - 4 : 0); - snprintf(line, sizeof(line), sp_t("ui.approve"), call, - label); - } - werase(ui_input); - mvwaddnstr(ui_input, 0, 0, line, w); - wrefresh(ui_input); - } - if (c == 'y' || c == 'Y' || c == 'n' || c == 'N' || c == 27) { - pthread_mutex_lock(&tu->lock); - tu->approve_result = (c == 'y' || c == 'Y'); - tu->approve_pending = 0; - pthread_cond_broadcast(&tu->cond); - pthread_mutex_unlock(&tu->lock); - } - return 1; -} - -/* - * One tick without a key: the turn so far, on screen. The turn is not drawn - * into a box of its own: it is two entries that grow in place, the reasoning - * first, the answer after the tool calls. Nothing moves when the turn ends - - * which is what a jumping block feels like. - */ -static void -turn_paint(struct ui_state *s, struct sp_agent *ag, struct sp_host *host, - struct turn *tu, struct turn_view *v) -{ - char *think = NULL, *live = NULL; - struct timespec now; - long ms; - int w, used; - - pthread_mutex_lock(&tu->lock); - if (tu->think.len > 0 && tu->think.p != NULL) - think = strdup(tu->think.p); - if (tu->live.len > 0 && tu->live.p != NULL) - live = strdup(tu->live.p); - pthread_mutex_unlock(&tu->lock); - - turn_drain(s, tu, v); - if (think != NULL) - seg_show(s, &v->think, "thinking", think); - if (live != NULL) { - seg_show(s, &v->ans, "agent", live); - s->out_chars = strlen(live); - } - free(think); - free(live); - draw_history(s); - draw_sidebar(s, SESS_ID(ag), SESS_DIR(ag), host); - /* a fleet moves on while a turn runs; nothing draws it any more */ - if (s->sw != NULL) - swarm_poll(s->sw); - - /* - * The prompt becomes the steering line: elapsed seconds, the tool that - * is running, then what is typed. One row, never wrapped - wrapped input - * scrolls the screen. - */ - clock_gettime(CLOCK_MONOTONIC, &now); - ms = (long)((now.tv_sec - v->t0.tv_sec) * 1000 + - (now.tv_nsec - v->t0.tv_nsec) / 1000000); - s->last_ms = ms; - update_meter(s, host); - werase(ui_input); - w = getmaxx(ui_input) - 1; - { - /* - * No status bar: the running time and the call lead the input. - * The steer prompt keeps its room and the call gives way - a tool - * line that pushes "steer>" off the right edge hides the one hint - * the row exists for. - */ - char lead[600], mark[700], steer[32]; - size_t room; - - snprintf(steer, sizeof(steer), "%s", - sp_td("ui.steer_mark", "steer> ")); - pthread_mutex_lock(&tu->lock); - snprintf(lead, sizeof(lead), "%lds%s%s", ms / 1000, - tu->tool_line[0] != '\0' ? " " : "", tu->tool_line); - pthread_mutex_unlock(&tu->lock); - room = w > (int)strlen(steer) + 2 ? - (size_t)w - strlen(steer) - 2 : 0; - cut_line(lead, room); - snprintf(mark, sizeof(mark), "%s %s", lead, steer); - mvwaddnstr(ui_input, 0, 0, mark, w); - used = (int)strlen(mark); - } - if (used < w) - ui_add_text(ui_input, v->line, w - used - 1); - wclrtoeol(ui_input); - wnoutrefresh(ui_input); - doupdate(); -} - -/* - * The keys of a running turn: type to steer (Enter queues the text for the - * next step), PgUp/PgDn and Shift+Up/Down scroll, Ctrl-C cancels, Ctrl-D - * cancels and quits. Returns 1 when the turn was cancelled. - */ -static int -turn_key(struct ui_state *s, struct sp_agent *ag, struct sp_host *host, - struct turn *tu, struct turn_view *v, int c, char *pending_steer, - size_t ps_cap) -{ - if (c == KEY_PPAGE || c == KEY_SR) { - s->scroll += (c == KEY_SR ? 1 : 10); - redraw(s, ag, host); - return 0; - } - if (c == KEY_NPAGE || c == KEY_SF) { - size_t step = (c == KEY_SF ? 1 : 10); - - s->scroll = s->scroll > step ? s->scroll - step : 0; - redraw(s, ag, host); - return 0; - } - if (c == KEY_RESIZE) { - relayout(100); - redraw(s, ag, host); - return 0; - } - /* - * Cancel under the lock and wake the turn: it may be asleep in - * approve_cb. Setting the flag alone left a turn that was waiting for a - * yes waiting forever, and Ctrl-D did not cancel at all before the join. - */ - if (c == 3 || c == 4) { - pthread_mutex_lock(&tu->lock); - tu->cancel = 1; - pthread_cond_broadcast(&tu->cond); - pthread_mutex_unlock(&tu->lock); - if (c == 4) - s->quit = 1; - return 1; - } - if (c == '\n' || c == '\r' || c == KEY_ENTER) { - if (v->llen > 0) { - pthread_mutex_lock(&tu->lock); - snprintf(tu->steer, sizeof(tu->steer), "%s", v->line); - snprintf(pending_steer, ps_cap, "%s", v->line); - tu->have_steer = 1; - pthread_mutex_unlock(&tu->lock); - v->llen = 0; - v->line[0] = '\0'; - mvwaddstr(ui_input, 0, 0, sp_t("ui.steering_queued")); - wclrtoeol(ui_input); - wrefresh(ui_input); - } - return 0; - } - if ((c == KEY_BACKSPACE || c == 127 || c == 8) && v->llen > 0) { - v->line[--v->llen] = '\0'; - return 0; - } - if (c >= 32 && c < 256 && c != 127 && v->llen < sizeof(v->line) - 2) { - v->line[v->llen++] = (char)c; - v->line[v->llen] = '\0'; - } - return 0; -} - -/* - * One turn on its own thread while this one keeps the screen alive, then its - * result in the transcript. A steer typed too late for a step boundary comes - * back in 'pending_steer'. Returns the turn's rc. - */ -static int -ui_turn(struct ui_state *s, struct sp_agent *ag, struct sp_host *host, - const char *text, char *pending_steer, size_t ps_cap) -{ - struct turn tu; - struct turn_view v; - const struct sp_agent_config *orig = ag->cfg; - struct sp_agent_config cfg = *orig; - if (s->agents.n > 0 && s->agents.v[s->agent_cur].autonomous >= 0) - cfg.autonomous = s->agents.v[s->agent_cur].autonomous; - struct sp_buf answer, err; - struct timespec t1; - pthread_t th; - int rc, cancelled = 0; - - pending_steer[0] = '\0'; - memset(&v, 0, sizeof(v)); - clock_gettime(CLOCK_MONOTONIC, &v.t0); - if (sp_buf_init(&answer) != 0 || sp_buf_init(&err) != 0) - return -1; - - memset(&tu, 0, sizeof(tu)); - tu.ag = ag; - tu.text = text; - sp_buf_init(&tu.answer); - sp_buf_init(&tu.err); - sp_buf_init(&tu.live); - sp_buf_init(&tu.think); - pthread_mutex_init(&tu.lock, NULL); - pthread_cond_init(&tu.cond, NULL); - cfg.cancel = &tu.cancel; - cfg.steer = steer_cb; - cfg.steer_ctx = &tu; - cfg.stream = stream_cb; - cfg.stream_ctx = &tu; - cfg.approve = approve_cb; - cfg.approve_ctx = &tu; - cfg.tool_end = tool_end_cb; - cfg.tool_end_ctx = &tu; - cfg.tool_begin = tool_begin_cb; - cfg.tool_begin_ctx = &tu; - cfg.on_compact = compact_cb; - cfg.on_compact_ctx = &tu; - if (orig->limit_wait != NULL) { - cfg.limit_wait = ui_limit_wait; - cfg.limit_ctx = &tu; - } - sp_openai_set_cancel(&tu.cancel); - ag->cfg = &cfg; - - if (s->sw) swarm_report_busy(s->sw, 1); - if (pthread_create(&th, NULL, turn_thread, &tu) != 0) { - sp_buf_puts(&err, sp_t("err.thread")); - rc = -1; - } else { - wtimeout(ui_input, 100); - for (;;) { - int c, done; - - pthread_mutex_lock(&tu.lock); - done = tu.done; - pthread_mutex_unlock(&tu.lock); - if (done) - break; - c = wgetch(ui_input); - if (turn_approval(&tu, c)) - continue; - if (c == ERR) { - turn_paint(s, ag, host, &tu, &v); - continue; - } - if (turn_key(s, ag, host, &tu, &v, c, pending_steer, - ps_cap)) { - cancelled = 1; - break; - } - } - wtimeout(ui_input, -1); - /* - * A cancelled turn: wait for the worker with the screen alive. - * Every transport kills its own child or curl when the flag is - * set; the cli transport did not, and this join froze the whole - * screen until `claude -p` decided to finish. Now the hint is on - * screen, the repaint continues, and a second Ctrl-C leaves at - * once instead of holding the terminal hostage. - */ - if (cancelled) { - wtimeout(ui_input, 100); - for (;;) { - int c2, done2; - - pthread_mutex_lock(&tu.lock); - done2 = tu.done; - pthread_mutex_unlock(&tu.lock); - if (done2) - break; - werase(ui_input); - mvwaddstr(ui_input, 0, 0, - sp_t("ui.cancelling")); - wclrtoeol(ui_input); - wrefresh(ui_input); - c2 = wgetch(ui_input); - if (c2 == 3 || c2 == 4) { - endwin(); - _exit(1); - } - if (c2 == ERR) - turn_paint(s, ag, host, &tu, &v); - } - wtimeout(ui_input, -1); - } - pthread_join(th, NULL); - if (s->sw) swarm_report_busy(s->sw, 0); - rc = tu.rc; - if (tu.answer.p != NULL) - sp_buf_puts(&answer, tu.answer.p); - if (tu.err.p != NULL) - sp_buf_puts(&err, tu.err.p); - if (tu.steers > 0 && answer.len > 0) { - char note[64]; - - snprintf(note, sizeof(note), " (%d steering%s applied)", - tu.steers, tu.steers == 1 ? "" : "s"); - sp_buf_puts(&answer, note); - } - turn_drain(s, &tu, &v); - /* - * The reasoning is on screen already (it streamed); the log keeps - * the whole of it, tool calls included as their own entries. - */ - if (tu.think.len > 0 && tu.think.p != NULL) - sp_logf("thinking", "%s", tu.think.p); - } - /* - * Restore the caller's config: the patched copy lives on this stack and - * must not outlive the turn. Leaving it set handed the follow-up turn a - * dangling steer callback, which then consumed the same text twice. - */ - sp_openai_set_cancel(NULL); - ag->cfg = orig; - /* - * A steer the turn took at a step boundary is already in the - * conversation. Only one it never reached becomes the next message - - * before, every steer was sent twice. - */ - if (tu.have_steer == 0 || cancelled) - pending_steer[0] = '\0'; - - clock_gettime(CLOCK_MONOTONIC, &t1); - s->last_ms = (long)((t1.tv_sec - v.t0.tv_sec) * 1000 + - (t1.tv_nsec - v.t0.tv_nsec) / 1000000); - s->last_steps = ag->stats.steps; - s->last_calls = ag->stats.tool_calls; - s->tokens_in = ag->stats.tokens_in; - s->tokens_out = ag->stats.tokens_out; - if (rc == 0) { - const char *ap = answer.p != NULL ? answer.p : ""; - - /* - * The answer the agent returns is the last step's text. What the - * model said before its tool calls ("I'll read the file") streamed - * into the entry too; replacing the entry with the final text - * would take it away. Keep the streamed text when it ends in the - * final answer. - */ - { - size_t lv = tu.live.len, la = strlen(ap); - - if (lv > 0 && tu.live.p != NULL) { - /* streamed: show what is left of it, then stop */ - seg_show(s, &v.ans, "agent", tu.live.p); - /* a final answer longer than what streamed was - * not streamed: it gets its own entry */ - if (la > lv) - add_entry(s, "agent", ap); - } else - add_entry(s, "agent", ap); - } - s->total_out_chars += strlen(ap); - s->out_chars = strlen(ap); - } else - add_entry(s, "error", err.len > 0 ? err.p : - sp_t("err.turn_failed")); - - sp_buf_free(&tu.answer); - sp_buf_free(&tu.err); - sp_buf_free(&tu.live); - sp_buf_free(&tu.think); - { - int k; - - for (k = 0; k < tu.nev; k++) - free(tu.ev[k].text); - free(tu.ev); - } - pthread_cond_destroy(&tu.cond); - pthread_mutex_destroy(&tu.lock); - sp_buf_free(&answer); - sp_buf_free(&err); - return rc; -} - -/* curses up, colours, windows, and the conversation so far on screen */ -static int -ui_start(struct ui_state *s, struct sp_agent *ag, struct sp_host *host, - const char *endpoint, const char *model, const char *theme_name, - struct swarm *sw, struct sp_config *conf) -{ - struct sp_buf err; - const char *user = getenv("USER"); - - memset(s, 0, sizeof(*s)); - sp_buf_init(&s->last_think); - snprintf(s->cur_endpoint, sizeof(s->cur_endpoint), "%s", - endpoint != NULL ? endpoint : ""); - snprintf(s->cur_model, sizeof(s->cur_model), "%s", - model != NULL ? model : ""); - s->endpoint = s->cur_endpoint; - s->conf = conf; - if (conf != NULL && conf->max_wait > 0) - g_max_wait = conf->max_wait; - s->sw = sw; - s->model = s->cur_model; - if (user != NULL && *user != '\0') - snprintf(g_who, sizeof(g_who), "%s", user); - if (model != NULL && *model != '\0') { - /* a path like /models/x/y.gguf: the name is the last part */ - const char *slash = strrchr(model, '/'); - size_t n; - - snprintf(g_model, sizeof(g_model), "%s", - slash != NULL ? slash + 1 : model); - n = strlen(g_model); - if (n > 4 && strcmp(g_model + n - 4, ".gguf") == 0) - g_model[n - 4] = '\0'; - } - g_status_host = host; /* the status line is drawn per tick */ - if (sp_buf_init(&err) != 0) - return -1; - if (sp_theme_load(theme_name, &s->theme, &err) != 0) { - fprintf(stderr, "splinter: %s\n", - err.len > 0 ? err.p : sp_t("err.theme")); - sp_buf_free(&err); - return -1; - } - sp_buf_free(&err); - - /* - * Without this, curses treats every byte above 0x7f as garbage: German - * umlauts and every UTF-8 answer would arrive as replacement characters. - */ - setlocale(LC_ALL, ""); - initscr(); - /* - * raw(), not cbreak(): cbreak leaves ISIG on, so the terminal driver turns - * Ctrl-C into SIGINT and kills the harness before wgetch() can report the - * key - "Ctrl-C cancels the turn" was a claim, and pressing it proved the - * opposite. raw() hands every byte to us and we decide. - */ - raw(); - noecho(); - keypad(stdscr, TRUE); - curs_set(1); - init_colors(&s->theme); - layout(); - - hist_load(s, SESS_DIR(ag)); - { - char cwd[700]; - - if (getcwd(cwd, sizeof(cwd)) == NULL) - cwd[0] = '\0'; - if (sp_agents_load(&s->agents, cwd, getenv("HOME")) == 0 && - s->agents.n > 0) { - int idx = sp_agents_find(&s->agents, g_start_agent); - - s->base_prompt = sp_agents_base(ag->conv); - agent_switch(s, ag, idx < 0 ? 0 : idx, idx > 0); - } - } - /* - * A resumed session starts with its history on screen: the conversation is - * the same object the model will be given, so showing it is not a summary, - * it is the thing. - */ - if (ag->conv != NULL) { - size_t i; - - for (i = 0; i < ag->conv->n; i++) { - const struct sp_msg *m = &ag->conv->v[i]; - - if (m->role == NULL || m->content == NULL) - continue; - if (strcmp(m->role, "user") == 0) - add_entry(s, "you", m->content); - else if (strcmp(m->role, "assistant") == 0) { - add_entry(s, "agent", m->content); - s->total_out_chars += strlen(m->content); - } - } - } - s->out_chars = 0; - add_entry(s, "splinter", sp_t("ui.ready")); - return 0; -} - -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) -{ - struct ui_state s; - char input[1024], pending[1024]; - - if (ui_start(&s, ag, host, endpoint, model, theme_name, sw, conf) != 0) - return 1; - for (;;) { - draw_history(&s); - draw_sidebar(&s, SESS_ID(ag), SESS_DIR(ag), host); - werase(ui_input); - mvwaddstr(ui_input, 0, 0, prompt_mark()); - wnoutrefresh(ui_input); - doupdate(); - - ui_read_line(&s, ag, host, input, sizeof(input)); - if (s.quit) - break; - if (input[0] == '\0') - continue; - if (input[0] == '!' && input[1] != '\0') { - ui_shell(&s, ag, input + 1); - continue; - } - /* after a stopped wait (or any stopped turn): go on */ - if (strcmp(input, "/resume") == 0) - snprintf(input, sizeof(input), "Continue with the task " - "you were working on. Do not repeat work that is " - "already done."); - if (input[0] == '/' && input[1] != '\0' && - ui_slash(&s, ag, host, input, sizeof(input))) { - if (s.quit) - break; - continue; - } - if (s.cc.active) { - struct sp_buf o; - - if (sp_buf_init(&o) == 0) { - (void)ui_connect_answer(&s, ag, input, &o); - add_entry(&s, "splinter", o.p != NULL ? o.p : ""); - sp_buf_free(&o); - } - continue; - } - - hist_push(&s, SESS_DIR(ag), input); - s.scroll = 0; - add_entry(&s, "you", input); - draw_history(&s); - draw_sidebar(&s, SESS_ID(ag), SESS_DIR(ag), host); - werase(ui_input); - mvwaddstr(ui_input, 0, 0, sp_t("ui.working")); - wrefresh(ui_input); - doupdate(); - /* - * A failed turn is shown, not returned: the process ends when the - * operator quits, and that is a clean quit (ui.h). Passing the last - * turn's rc out made a cancelled turn exit 255. - */ - (void)ui_turn(&s, ag, host, input, pending, sizeof(pending)); - /* - * A single-step turn ends with the answer, so a steer typed during - * it had no step boundary to land on. Rather than dropping it, it - * becomes the next message, run like any other turn - streamed, - * cancellable, asking for approval on the screen. It used to run - * here on the UI thread with none of that, the screen frozen. - */ - while (pending[0] != '\0' && !s.quit) { - snprintf(input, sizeof(input), "%s", pending); - s.scroll = 0; - add_entry(&s, "you", input); - redraw(&s, ag, host); - (void)ui_turn(&s, ag, host, input, pending, - sizeof(pending)); - } - if (s.quit) - break; - } - - endwin(); - sp_buf_free(&s.last_think); - sp_agents_free(&s.agents); - free(s.base_prompt); - ag->policy = NULL; - return 0; -} diff --git a/tests/test_a2a_ui.sh b/tests/test_a2a_ui.sh index f4e3199..0d806f8 100755 --- a/tests/test_a2a_ui.sh +++ b/tests/test_a2a_ui.sh @@ -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. diff --git a/tests/test_attach.sh b/tests/test_attach.sh new file mode 100755 index 0000000..aa20e08 --- /dev/null +++ b/tests/test_attach.sh @@ -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 ' 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 diff --git a/tests/test_engine.c b/tests/test_engine.c new file mode 100644 index 0000000..06f8511 --- /dev/null +++ b/tests/test_engine.c @@ -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 +#include +#include +#include +#include +#include + +#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; +} diff --git a/tests/test_gateway.sh b/tests/test_gateway.sh index 050bdc1..a0de4bc 100755 --- a/tests/test_gateway.sh +++ b/tests/test_gateway.sh @@ -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" diff --git a/tests/test_protocol.sh b/tests/test_protocol.sh new file mode 100755 index 0000000..b928146 --- /dev/null +++ b/tests/test_protocol.sh @@ -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 diff --git a/tests/test_sse.c b/tests/test_sse.c index 278a642..d392f8e 100644 --- a/tests/test_sse.c +++ b/tests/test_sse.c @@ -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 + * " 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\":" diff --git a/tests/test_usage.c b/tests/test_usage.c index b3d8b82..3e811ae 100644 --- a/tests/test_usage.c +++ b/tests/test_usage.c @@ -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); diff --git a/tools/check_i18n.py b/tools/check_i18n.py index d946362..68d0517 100755 --- a/tools/check_i18n.py +++ b/tools/check_i18n.py @@ -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): diff --git a/tools/embed_catalogs.sh b/tools/embed_catalogs.sh index a9aa99a..48a89ae 100755 --- a/tools/embed_catalogs.sh +++ b/tools/embed_catalogs.sh @@ -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