Compare commits
150
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74df75d438 | ||
|
|
4af38ef91b | ||
|
|
df6bfa9cfb | ||
|
|
6debe213c3 | ||
|
|
181b2c0638 | ||
|
|
00bedb4e32 | ||
|
|
719c436f5c | ||
|
|
4fc7614cc5 | ||
|
|
6166acfdea | ||
|
|
1a17d25659 | ||
|
|
1c4fdf0a55 | ||
|
|
8f030af8c2 | ||
|
|
85556ce889 | ||
|
|
9b2fee66a2 | ||
|
|
35d4e1bc53 | ||
|
|
f7158d34d2 | ||
|
|
3b0de63e06 | ||
|
|
7fecc7d153 | ||
|
|
4ff2844955 | ||
|
|
0fc81398dc | ||
|
|
d0a3c484ef | ||
|
|
f7c374bcbb | ||
|
|
91f0136e9d | ||
|
|
44f457b68d | ||
|
|
15fc06c8bf | ||
|
|
030f1be0bb | ||
|
|
4f7255548d | ||
|
|
407f073ae3 | ||
|
|
4b4d822188 | ||
|
|
1b5b4fab27 | ||
|
|
a5665a4dcc | ||
|
|
d9bdb2a62f | ||
|
|
9b83b10804 | ||
|
|
68e5b14d10 | ||
|
|
467739ec2b | ||
|
|
80f055711d | ||
|
|
e177475648 | ||
|
|
b61172a4a5 | ||
|
|
4cdaf2680b | ||
|
|
b1acf1629b | ||
|
|
d7a61a1bd5 | ||
|
|
0b643ca6d9 | ||
|
|
e7e47b7f1d | ||
|
|
d7ce939966 | ||
|
|
98dce53200 | ||
|
|
4783705e6b | ||
|
|
6240f3f72a | ||
|
|
ea772e1851 | ||
|
|
30e202eca0 | ||
|
|
4507a3c57c | ||
|
|
cfe0af2688 | ||
|
|
7634c57872 | ||
|
|
f5d63f6199 | ||
|
|
f6211362cb | ||
|
|
2175263236 | ||
|
|
f568f558d0 | ||
|
|
bc0b9f22f9 | ||
|
|
082223af96 | ||
|
|
d714efb16e | ||
|
|
1781cdd478 | ||
|
|
f19fbf6ac1 | ||
|
|
15d6eb1885 | ||
|
|
139f5ae072 | ||
|
|
de1131cdf5 | ||
|
|
a00534cf6c | ||
|
|
a48a2deec5 | ||
|
|
5ad5768e6a | ||
|
|
ca81d297c2 | ||
|
|
6358fcf42a | ||
|
|
9e2a2e6156 | ||
|
|
678e2814e6 | ||
|
|
fa16bfd0a9 | ||
|
|
87f5987a46 | ||
|
|
f7120882fa | ||
|
|
226fff3461 | ||
|
|
602c8fbf6c | ||
|
|
fb877e263f | ||
|
|
9a6b282388 | ||
|
|
6b51f48335 | ||
|
|
5fd8f76870 | ||
|
|
37d038f716 | ||
|
|
fb3cacbb4c | ||
|
|
eba6f71a2d | ||
|
|
2581885e67 | ||
|
|
e0825c04b7 | ||
|
|
47d45bfd15 | ||
|
|
11d119be04 | ||
|
|
f07128cf9b | ||
|
|
0372981725 | ||
|
|
0841fabe87 | ||
|
|
c11a6c7989 | ||
|
|
e07d59c22e | ||
|
|
21287b88a9 | ||
|
|
4cbd57d829 | ||
|
|
a1794fb101 | ||
|
|
9e13c3eb64 | ||
|
|
6b560e63a0 | ||
|
|
7f8493c949 | ||
|
|
a0f47762f0 | ||
|
|
80154055f1 | ||
|
|
86e0233c16 | ||
|
|
d63da16c65 | ||
|
|
6813fff1b5 | ||
|
|
056b8c4277 | ||
|
|
00aba079c5 | ||
|
|
4be6e26f78 | ||
|
|
ddf0ec5462 | ||
|
|
0f8c5c7e96 | ||
|
|
af2001bfee | ||
|
|
dc9a1c62ec | ||
|
|
82bda09ed1 | ||
|
|
7e74e2a32a | ||
|
|
63b6742447 | ||
|
|
8aee12e9d4 | ||
|
|
1e15c91e4e | ||
|
|
8aad48b928 | ||
|
|
36a66ab4f0 | ||
|
|
55ca5c71f8 | ||
|
|
7e8fe5b825 | ||
|
|
b0c1da65a2 | ||
|
|
0f46c22a58 | ||
|
|
614988aa68 | ||
|
|
be3d0ee415 | ||
|
|
67b4d5d070 | ||
|
|
006198425c | ||
|
|
bff47eede8 | ||
|
|
1726bc1967 | ||
|
|
76c9007c02 | ||
|
|
573ef61afc | ||
|
|
42c11f95c7 | ||
|
|
9af7695064 | ||
|
|
dd135f3b33 | ||
|
|
a01bfe9df1 | ||
|
|
5143fcd054 | ||
|
|
a9f175c25b | ||
|
|
c9f21be89b | ||
|
|
b05bb34cc7 | ||
|
|
41f42cbf95 | ||
|
|
cb73c4a0bb | ||
|
|
32a214aee3 | ||
|
|
5054393e17 | ||
|
|
be2ab165f7 | ||
|
|
fdf8b2888d | ||
|
|
c215fd8101 | ||
|
|
a32c591572 | ||
|
|
74e20547ed | ||
|
|
23bc0d13d4 | ||
|
|
a77641b699 | ||
|
|
f3b832ae64 | ||
|
|
bddba6423b |
No files matched your search
+7
-1
@@ -1,5 +1,6 @@
|
||||
*.o
|
||||
splinter
|
||||
splinterctl
|
||||
tests/test_buf
|
||||
tests/test_tool
|
||||
tests/test_session
|
||||
@@ -15,4 +16,9 @@ tests/test_*
|
||||
|
||||
# python bytecode from the test helpers
|
||||
__pycache__/
|
||||
src/catalogs.c
|
||||
src/backend/catalogs.c
|
||||
src/backend/buildinfo.c
|
||||
|
||||
# Claude Code worktrees and local session state
|
||||
.claude/
|
||||
.splinter-swarm.sock
|
||||
@@ -0,0 +1,8 @@
|
||||
# IMPORT -- where splinter comes from (root AGENTS.md, "What belongs where": ext/)
|
||||
|
||||
upstream splinter, the project's own repository
|
||||
https://git.kropa.tech/hiddenbox/splinter
|
||||
version 0.1 (no release tag yet; see README.md)
|
||||
archive git archive of the submodule's commit (tools/ext-dist.sh), no tarball upstream
|
||||
licence BSD-3-Clause (README.md, "License")
|
||||
pkgsrc recipe in pkgsrc/ of this tree; it becomes misc/splinter (tools/ext-sync.sh)
|
||||
@@ -5,103 +5,167 @@
|
||||
# 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
|
||||
|
||||
# Curses: the vendored NetBSD tree by default. A package build sets
|
||||
# CURSES_LIB and CURSES_DEP instead and gets the base system's curses: the
|
||||
# vendored tree needs host tools (nbperf, host_tic) that a cross build cannot
|
||||
# run, and on NetBSD the base already has libcurses and libterminfo
|
||||
# (ext/src/splinter/pkgsrc/Makefile). CURSES_LIB is what to link, CURSES_DEP
|
||||
# the file that has to exist first -- empty means "nothing to build".
|
||||
CURSES_DIR = vendor/netbsd-curses
|
||||
CURSES_A = $(CURSES_DIR)/libcurses/libcurses.a \
|
||||
$(CURSES_DIR)/libterminfo/libterminfo.a
|
||||
CURSES_LIB ?= $(CURSES_DIR)/libcurses/libcurses.a \
|
||||
$(CURSES_DIR)/libterminfo/libterminfo.a
|
||||
CURSES_DEP ?= $(CURSES_LIB)
|
||||
|
||||
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
|
||||
# Links name the library by file, never through a search path. A search path
|
||||
# loses: a package build passes -L=/usr/pkg/lib ahead of anything this Makefile
|
||||
# can append, so `-lsplinter` found the copy installed by the previous release
|
||||
# instead of the one built a second ago (measured 2026-11-23:
|
||||
# /usr/pkg/lib/libsplinter.so from 22.11. 22:26 made `splinter` fail with
|
||||
# "undefined reference to sp_engine_sources", a function added to engine.c the
|
||||
# same day). Naming the file is order-independent, and the SONAME the library
|
||||
# carries (see the $(LIB) rule) is what the binary records as its dependency,
|
||||
# so the installed program still looks for "libsplinter.so" and not for a
|
||||
# build path.
|
||||
SPLLIB = $(LIB)
|
||||
LIBOBJ = src/backend/buf.o src/backend/tool.o src/backend/session.o src/backend/conv.o src/backend/compact.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/mcpsession.o src/backend/skills.o src/backend/user.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/embed.o src/backend/agents.o src/backend/foreignopen.o src/backend/engine.o src/backend/http.o src/backend/openai_server.o src/backend/catalogs.o
|
||||
# buildinfo.o is separate: buildinfo.c is generated from the objects below.
|
||||
LIBOBJ_ALL = $(LIBOBJ) src/backend/buildinfo.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 \
|
||||
plugins/kids/kids.so plugins/status/status.so plugins/tasks/tasks.so \
|
||||
plugins/ring/ring.so plugins/reminder/reminder.so plugins/recap/recap.so \
|
||||
plugins/kids/kids.so plugins/status/status.so plugins/processes/processes.so \
|
||||
plugins/provider/provider.so \
|
||||
plugins/scheduler/scheduler.so \
|
||||
plugins/planner/planner.so \
|
||||
plugins/a2a/a2a.so \
|
||||
plugins/tmux/tmux.so
|
||||
plugins/junction/junction.so \
|
||||
plugins/self/self.so \
|
||||
plugins/cache/cache.so \
|
||||
plugins/session/session.so \
|
||||
plugins/foreign/foreign.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_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_recap tests/test_sse tests/test_anthropic tests/test_cli tests/test_compactor tests/test_corecompact 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_usage tests/test_agents tests/test_confblock tests/test_jobs tests/test_engine tests/test_self tests/test_fuzz \
|
||||
tests/test_sessiontools tests/test_embed tests/test_foreign \
|
||||
tests/test_foreignopen tests/test_remote_list
|
||||
|
||||
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.
|
||||
$(CURSES_A):
|
||||
# Only when the vendored tree is what is wanted: CURSES_DEP names a file
|
||||
# that already exists when the base system's curses is linked.
|
||||
$(CURSES_LIB):
|
||||
cd $(CURSES_DIR) && $(MAKE) -f GNUmakefile libcurses/libcurses.a \
|
||||
libterminfo/libterminfo.a
|
||||
|
||||
curses: $(CURSES_A)
|
||||
curses: $(CURSES_LIB)
|
||||
|
||||
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)
|
||||
$(CC) -shared -o $@ $(LIBOBJ) $(CURSES_A) $(LIBS)
|
||||
# The build stamp --version prints. It is regenerated only when one of the
|
||||
# objects it describes is newer, so a no-op make keeps the old stamp: the
|
||||
# stamp says when this binary was actually built, not when make last ran.
|
||||
# The revision is included because 0.1.0 does not tell two builds apart.
|
||||
src/backend/buildinfo.c: $(LIBOBJ) $(BINOBJ)
|
||||
@{ \
|
||||
rev=`git rev-parse --short HEAD 2>/dev/null` || rev=unknown; \
|
||||
if [ -n "`git status --porcelain --untracked-files=no 2>/dev/null | head -n 1`" ]; then \
|
||||
rev="$$rev-dirty"; \
|
||||
fi; \
|
||||
printf '/* generated by make: the build stamp of this binary */\nconst char *sp_build_time = "%s";\nconst char *sp_build_rev = "%s";\n' \
|
||||
"`date '+%Y-%m-%d %H:%M:%S %Z'`" "$$rev"; \
|
||||
} > $@
|
||||
|
||||
$(LIB): $(LIBOBJ_ALL) $(CURSES_DEP)
|
||||
$(CC) -shared -Wl,-soname,$(LIB) -o $@ $(LIBOBJ_ALL) $(CURSES_LIB) $(LIBS)
|
||||
|
||||
# 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.
|
||||
$(BIN): $(BINOBJ) $(LIB)
|
||||
$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(BINOBJ) -L. -lsplinter $(RPATH) \
|
||||
$(CURSES_A) $(LIBS)
|
||||
# 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) -o $@ $(CLIENTOBJ) $(SPLLIB) $(LDFLAGS) $(RPATH) \
|
||||
$(LIBS)
|
||||
|
||||
$(BIN): $(BINOBJ) $(LIB) $(CURSES_DEP)
|
||||
$(CC) $(CFLAGS) -o $@ $(BINOBJ) $(SPLLIB) $(LDFLAGS) $(RPATH) \
|
||||
$(CURSES_LIB) $(LIBS)
|
||||
|
||||
plugins/clock/clock.so: plugins/clock/clock.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/clock/clock.c -L. -lsplinter \
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/clock/clock.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/lcm/lcm.so: plugins/lcm/lcm.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/lcm/lcm.c -L. -lsplinter \
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/lcm/lcm.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/session/session.so: plugins/session/session.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/session/session.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/foreign/foreign.so: plugins/foreign/foreign.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/foreign/foreign.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/cli/cli.so: plugins/cli/cli.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/cli/cli.c -L. -lsplinter \
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/cli/cli.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/ring/ring.so: plugins/ring/ring.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/ring/ring.c -L. -lsplinter \
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/ring/ring.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/kids/kids.so: plugins/kids/kids.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/kids/kids.c -L. -lsplinter \
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/kids/kids.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/tasks/tasks.so: plugins/tasks/tasks.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/tasks/tasks.c -L. -lsplinter \
|
||||
plugins/processes/processes.so: plugins/processes/processes.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/processes/processes.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/status/status.so: plugins/status/status.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/status/status.c -L. -lsplinter \
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/status/status.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/reminder/reminder.so: plugins/reminder/reminder.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/reminder/reminder.c -L. -lsplinter \
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/reminder/reminder.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/recap/recap.so: plugins/recap/recap.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/recap/recap.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/mcp/mcp.so: plugins/mcp/mcp.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/mcp/mcp.c -L. -lsplinter \
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/mcp/mcp.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/focus/focus.so: plugins/focus/focus.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/focus/focus.c -L. -lsplinter \
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/focus/focus.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/cps/cps.so: plugins/cps/cps.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/cps/cps.c -L. -lsplinter \
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/cps/cps.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
.c.o:
|
||||
@@ -109,150 +173,200 @@ 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)
|
||||
#
|
||||
# The tests too: a test that allocates a struct sp_reply by value and
|
||||
# links a freshly built library is one header change away from reading
|
||||
# the fields of a different layout. That failure looks like a broken
|
||||
# test, not like a stale object, so it costs an hour every time.
|
||||
$(TESTS): $(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/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/http.o: src/backend/http.h include/splinter.h
|
||||
src/backend/openai_server.o: src/backend/openai_server.h src/backend/http.h src/backend/config.h include/splinter.h vendor/libmcp/mcp.h
|
||||
src/backend/engine.o: include/splinter_engine.h src/backend/config.h src/backend/providers.h src/backend/agents.h src/backend/swarm.h src/backend/cmdscript.h src/backend/i18n.h include/splinter_plugin.h
|
||||
src/backend/providers.o: src/backend/providers.h src/backend/config.h include/splinter.h include/splinter_plugin.h
|
||||
src/main.o: include/splinter.h include/splinter_engine.h \
|
||||
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)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_buf.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_tool: tests/test_tool.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_tool.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_tool.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_session: tests/test_session.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_session.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_session.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_transport: tests/test_transport.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_transport.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_transport.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_agent: tests/test_agent.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_agent.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_agent.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_conv: tests/test_conv.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_conv.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_conv.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_openai: tests/test_openai.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_openai.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_openai.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_theme: tests/test_theme.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_theme.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_theme.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_recap: tests/test_recap.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_recap.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_focus: tests/test_focus.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_focus.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_memory: tests/test_memory.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_memory.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_focus.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_skills: tests/test_skills.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_skills.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_skills.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_telegram: tests/test_telegram.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_telegram.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_telegram.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_delegate: tests/test_delegate.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_delegate.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_delegate.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_builtin: tests/test_builtin.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_builtin.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_builtin.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_ack: tests/test_ack.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_ack.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_ack.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
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 \
|
||||
$(TEST_RPATH) $(CURSES_A) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_i18n.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_ascii: tests/test_ascii.c $(LIB) $(BINOBJ) $(CURSES_DEP)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_ascii.c src/frontend/curses.o $(SPLLIB) \
|
||||
$(TEST_RPATH) $(CURSES_LIB) $(LIBS)
|
||||
tests/test_md: tests/test_md.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_md.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_md.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_tgmd: tests/test_tgmd.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_tgmd.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_tgmd.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_providers: tests/test_providers.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_providers.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_providers.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_b64: tests/test_b64.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_b64.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_b64.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_pause: tests/test_pause.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_pause.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_pause.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_swarm: tests/test_swarm.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_swarm.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_swarm.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_provstate: tests/test_provstate.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_provstate.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
tests/test_planner: tests/test_planner.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_planner.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_provstate.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
|
||||
tests/test_agents: tests/test_agents.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_agents.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_agents.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
|
||||
tests/test_confblock: tests/test_confblock.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_confblock.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_confblock.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
|
||||
tests/test_engine: tests/test_engine.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_engine.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_junction: tests/test_junction.c $(LIB) plugins/junction/junction.so
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_junction.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_self: tests/test_self.c $(LIB) plugins/self/self.so
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_self.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
|
||||
tests/test_fuzz: tests/test_fuzz.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_fuzz.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
|
||||
tests/test_sessiontools: tests/test_sessiontools.c $(LIB) plugins/session/session.so plugins/foreign/foreign.so
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_sessiontools.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_foreign: tests/test_foreign.c $(LIB) plugins/foreign/foreign.so
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_foreign.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_foreignopen: tests/test_foreignopen.c $(LIB) plugins/foreign/foreign.so
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_foreignopen.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
|
||||
# ui_remote.o is linked next to the library: the backend under test is front-end
|
||||
# code (it speaks the protocol over a socket) and libsplinter has no ui_* in it.
|
||||
tests/test_remote_list: tests/test_remote_list.c $(LIB) src/frontend/ui_remote.o \
|
||||
src/frontend/protocol.o
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_remote_list.c src/frontend/ui_remote.o \
|
||||
src/frontend/protocol.o $(SPLLIB) $(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)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_tmux.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_usage.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_jobs: tests/test_jobs.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_jobs.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_jobs.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_config: tests/test_config.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_config.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_config.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_anthropic: tests/test_anthropic.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_anthropic.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_anthropic.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_sse: tests/test_sse.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_sse.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_sse.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_cli: tests/test_cli.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_cli.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_cli.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
|
||||
tests/test_compactor: tests/test_compactor.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_compactor.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_compactor.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
|
||||
tests/test_corecompact: tests/test_corecompact.c $(LIB)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_corecompact.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_secrets: tests/test_secrets.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_secrets.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_secrets.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_mcpclient: tests/test_mcpclient.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_mcpclient.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_mcpclient.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_kids: tests/test_kids.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_kids.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_kids.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_embed: tests/test_embed.c $(LIB) $(HDRS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_embed.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/plugin_lifecycle.so: tests/plugin_lifecycle.c $(LIB) $(HDRS)
|
||||
$(CC) $(CFLAGS) -shared -o $@ tests/plugin_lifecycle.c -L. -lsplinter \
|
||||
$(CC) $(CFLAGS) -shared -o $@ tests/plugin_lifecycle.c $(SPLLIB) \
|
||||
$(TEST_RPATH) $(LIBS)
|
||||
tests/test_lifecycle: tests/test_lifecycle.c $(LIB) tests/plugin_lifecycle.so
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_lifecycle.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_lifecycle.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
tests/test_plugin: tests/test_plugin.c $(LIB) $(PLUGIN)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_plugin.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
|
||||
$(CC) $(CFLAGS) -o $@ tests/test_plugin.c $(SPLLIB) $(TEST_RPATH) $(LIBS)
|
||||
|
||||
check: $(LIB) $(BIN) $(PLUGIN) $(TESTS)
|
||||
# Every test runs under a 64 MB address-space limit: splinter is meant to
|
||||
# be small, and a test that runs away (a retry loop appending to a buffer
|
||||
# took 17 GB, 2026-11-18) must die at once instead of swapping the host.
|
||||
TEST_MEM_KB ?= 65536
|
||||
|
||||
check: $(LIB) $(BIN) $(CLIENT) $(PLUGIN) $(TESTS) tests/test_junction
|
||||
@set -e; python3 tools/check_i18n.py; \
|
||||
ulimit -v $(TEST_MEM_KB); \
|
||||
export LD_LIBRARY_PATH=.; \
|
||||
SPLINTER_SESSION_DIR=$$(mktemp -d "$${TMPDIR:-/tmp}/splinter-check-XXXXXX"); \
|
||||
export SPLINTER_SESSION_DIR; \
|
||||
trap 'rm -rf "$$SPLINTER_SESSION_DIR"' EXIT; \
|
||||
for t in $(TESTS); do echo "== $$t"; ./$$t; done; \
|
||||
echo "== tests/test_delegate_cli.sh"; sh tests/test_delegate_cli.sh; \
|
||||
echo "== tests/test_args.sh"; sh tests/test_args.sh; \
|
||||
echo "== tests/test_interview.sh"; sh tests/test_interview.sh; \
|
||||
echo "== tests/test_gateway.sh"; sh tests/test_gateway.sh; \
|
||||
echo "== tests/test_a2a.sh"; sh tests/test_a2a.sh; \
|
||||
@@ -264,42 +378,93 @@ check: $(LIB) $(BIN) $(PLUGIN) $(TESTS)
|
||||
echo "== tests/test_anthropic.sh"; sh tests/test_anthropic.sh; \
|
||||
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_swarm_socket.sh"; sh tests/test_swarm_socket.sh; \
|
||||
echo "== tests/test_ui.sh"; sh tests/test_ui.sh; \
|
||||
echo "== tests/test_ask_ui.sh"; sh tests/test_ask_ui.sh; \
|
||||
echo "== tests/test_protocol.sh"; sh tests/test_protocol.sh; \
|
||||
echo "== tests/test_attach.sh"; sh tests/test_attach.sh; \
|
||||
echo "== tests/test_attach_busy.sh"; sh tests/test_attach_busy.sh; \
|
||||
echo "== tests/test_gateway_openai.sh"; sh tests/test_gateway_openai.sh; \
|
||||
echo "== tests/test_usage_request.sh"; sh tests/test_usage_request.sh; \
|
||||
echo "== tests/test_compact_resume.sh"; sh tests/test_compact_resume.sh; \
|
||||
echo "== tests/test_reconnect.sh"; sh tests/test_reconnect.sh; \
|
||||
echo "== tests/test_junction.sh"; sh tests/test_junction.sh; \
|
||||
echo "== tests/test_mcpsession.sh"; sh tests/test_mcpsession.sh; \
|
||||
echo "== tests/test_ask_mcp.sh"; sh tests/test_ask_mcp.sh; \
|
||||
echo "== tests/test_ask_timeout.sh"; sh tests/test_ask_timeout.sh; \
|
||||
echo "all tests passed"
|
||||
|
||||
# The unit tests under ASAN/UBSAN with leak detection. Rebuilds the tree with
|
||||
# sanitizers and back; run it when nothing else builds in this tree.
|
||||
check-asan:
|
||||
@sh tests/check_asan.sh
|
||||
|
||||
# The unit tests under ThreadSanitizer: the engine has a turn thread, a UI
|
||||
# thread, widget threads and one thread per MCP server. Rebuilds the tree with
|
||||
# -fsanitize=thread and back; run it when nothing else builds in this tree.
|
||||
check-tsan:
|
||||
@sh tests/check_tsan.sh
|
||||
|
||||
# the test binaries as a list, for check_asan.sh
|
||||
print-tests:
|
||||
@echo $(TESTS)
|
||||
|
||||
# The installed binary finds its own library through an rpath relative to itself
|
||||
# ($ORIGIN), so 'make install PREFIX=$HOME/.local' produces a program that runs
|
||||
# without a wrapper, without LD_LIBRARY_PATH and without an environment file.
|
||||
install: all
|
||||
# Install by rename, never in place. A running splinter has these files
|
||||
# mapped: cp truncates the old inode and writes into pages the process is
|
||||
# executing, which killed a gateway that was up while make install ran
|
||||
# (SIGSEGV at a nonsense address). A rename swaps the directory entry and
|
||||
# leaves the mapped inode alone.
|
||||
install: all $(CURSES_DEP)
|
||||
mkdir -p $(DESTDIR)$(PREFIX)/bin $(DESTDIR)$(PREFIX)/lib \
|
||||
$(DESTDIR)$(PREFIX)/lib/splinter/plugins
|
||||
$(CC) $(CFLAGS) $(LDFLAGS) -Wl,-rpath,'$$ORIGIN/../lib' \
|
||||
-o $(DESTDIR)$(PREFIX)/bin/splinter $(BINOBJ) -L. -lsplinter \
|
||||
$(CURSES_A) $(LIBS)
|
||||
cp $(LIB) $(DESTDIR)$(PREFIX)/lib/
|
||||
cp $(PLUGIN) $(DESTDIR)$(PREFIX)/lib/splinter/plugins/
|
||||
-o $(DESTDIR)$(PREFIX)/bin/.splinter.new $(BINOBJ) $(SPLLIB) \
|
||||
$(CURSES_LIB) $(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) $(SPLLIB) \
|
||||
$(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 \
|
||||
cp "$$p" "$(DESTDIR)$(PREFIX)/lib/splinter/plugins/.new.$$$$" && \
|
||||
mv -f "$(DESTDIR)$(PREFIX)/lib/splinter/plugins/.new.$$$$" \
|
||||
"$(DESTDIR)$(PREFIX)/lib/splinter/plugins/$${p##*/}" || exit 1; \
|
||||
done
|
||||
@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 src/backend/buildinfo.c $(BIN) $(CLIENT) $(LIB) $(LIBOBJ_ALL) $(BINOBJ) \
|
||||
$(CLIENTOBJ) $(PLUGIN) $(TESTS) tests/plugin_lifecycle.so \
|
||||
tests/test_junction
|
||||
|
||||
.PHONY: all check curses install clean
|
||||
|
||||
plugins/provider/provider.so: plugins/provider/provider.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/provider/provider.c -L. -lsplinter \
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/provider/provider.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/scheduler/scheduler.so: plugins/scheduler/scheduler.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/scheduler/scheduler.c -L. -lsplinter \
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/scheduler/scheduler.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/planner/planner.so: plugins/planner/planner.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/planner/planner.c -L. -lsplinter \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
plugins/tmux/tmux.so: plugins/tmux/tmux.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/tmux/tmux.c -L. -lsplinter \
|
||||
plugins/a2a/a2a.so: plugins/a2a/a2a.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/a2a/a2a.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/a2a/a2a.so: plugins/a2a/a2a.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/a2a/a2a.c -L. -lsplinter \
|
||||
plugins/junction/junction.so: plugins/junction/junction.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/junction/junction.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
|
||||
plugins/cache/cache.so: plugins/cache/cache.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/cache/cache.c $(SPLLIB) \
|
||||
$(PLUGIN_LDFLAGS)
|
||||
|
||||
plugins/self/self.so: plugins/self/self.c $(LIB)
|
||||
$(CC) $(CFLAGS) -shared -o $@ plugins/self/self.c $(SPLLIB) \
|
||||
$(PLUGIN_RPATH) $(LIBS)
|
||||
@@ -3,23 +3,81 @@
|
||||
Named after Master Splinter: the one who knows which tools exist, who may use
|
||||
them, and what happened — and trains the ones that do the fighting.
|
||||
|
||||
A C99/POSIX agent harness with a curses interface: chat on three quarters of
|
||||
the screen, a sidebar on one quarter, plugins that can put tools and widgets
|
||||
into both.
|
||||
A C99/POSIX agent harness with a curses interface: the conversation on three
|
||||
quarters, a sidebar on the last one that says which agent, provider, model and
|
||||
allowance you are on and where the tools will act, a status line above the
|
||||
prompt with the context gauge (`ctx used/max`, cache share, tok/s), and the
|
||||
prompt below it. The conversation starts clear at the top and only ever grows.
|
||||
|
||||
make # libsplinter.so, the binary, the plugins
|
||||
Code: https://git.kropa.tech/hiddenbox/splinter
|
||||
|
||||
make # libsplinter.so, the binaries, the plugins
|
||||
make check # the tests, no network, no model
|
||||
make install PREFIX=$HOME/.local # binary, library, plugins
|
||||
make check-asan # the same under ASan/UBSan, leaks included
|
||||
make check-tsan # the same under TSan: data races
|
||||
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
|
||||
splinter --openai-listen 127.0.0.1 # /v1 for another harness, gw_ tools
|
||||
|
||||
The working day with several subscriptions (who analyses, who implements, what
|
||||
happens at a limit) is in `docs/WORKFLOW.md`.
|
||||
|
||||
## Command line
|
||||
|
||||
`splinter --help` prints this list; `docs/splinter.1` is the manual page. Exactly
|
||||
one transport is required (`--endpoint`, `--script` or `--transport`); with none,
|
||||
splinter refuses to start rather than pretend it can talk to a model.
|
||||
|
||||
| option | what it does |
|
||||
|---|---|
|
||||
| `-p, --prompt TEXT` | run one turn with TEXT and exit |
|
||||
| `--endpoint URL` | transport: an OpenAI-compatible chat endpoint (`--model` is then required) |
|
||||
| `--model NAME` | model name for `--endpoint` |
|
||||
| `-m, --select SEL` | a provider or pool of the config: `ID`, `ID/MODEL`, `POOL`, or a model name it serves |
|
||||
| `--agent NAME` | start as that agent profile (`build`, `plan`, or a file in `~/.splinter/agents`, `.agents/`); Tab switches in the chat |
|
||||
| `--agent-list` | list the agent profiles and exit |
|
||||
| `--doctor` | check every provider — key and reachability through its model list, never spending tokens |
|
||||
| `--model-list` | list what `-m` accepts (`--no-probe` skips asking each endpoint) |
|
||||
| `--api-key-env VAR` | read the API key from VAR (default `SPLINTER_API_KEY`; missing means no auth) |
|
||||
| `--script FILE` | transport: replay replies from FILE, one per line (no network) |
|
||||
| `--transport NAME` | use a transport a plugin provides (`cli`) |
|
||||
| `--kind NAME` | vendor shape of `--endpoint`: `openai` (default) or `anthropic` |
|
||||
| `--config PATH`, `--no-config` | this config file, or ignore the config entirely |
|
||||
| `--init-config` | write a commented example config and exit |
|
||||
| `--plugin PATH` | load a plugin (`.so`) before the first turn |
|
||||
| `--chat` | the interactive curses UI instead of one turn |
|
||||
| `--serve`, `--attach`, `--socket PATH` | serve the line protocol on a Unix socket, or be a client of it (default `~/.splinter/splinter.sock`) |
|
||||
| `--theme NAME`, `--list-themes` | UI theme (`Xresources` or a CDE palette such as `Default`, `Delphinium`, `MakroSlate`), and the names |
|
||||
| `--resume`, `-c, --continue` | load the session's history; continue the last session started in this directory |
|
||||
| `--claude`, `--opencode`, `--hermes`, `--from=NAME` | continue the newest session that tool ran in this directory (imports it on the first start) |
|
||||
| `--session DIR`, `--session-id ID` | session directory (default `~/.splinter`) and id (default `sess-<time>-<pid>`) |
|
||||
| `--steps N` | tool rounds per turn (default 150) |
|
||||
| `--max-bytes N` | request budget in bytes, 0 = no limit |
|
||||
| `--autonomous` | accepted for compatibility; splinter does not gate its own tools, so it changes nothing |
|
||||
| `--no-stream` | wait for the whole reply instead of printing it as it arrives |
|
||||
| `--no-stdin` | ignore data on standard input |
|
||||
| `--choose TEXT`, `--delegate ID` | print which delegate fits TEXT; run that delegate with `-p TEXT` and print its observation |
|
||||
| `--daemon` | answer on Telegram until SIGINT |
|
||||
| `--interview` | let the model interview you; writes `USER.txt` |
|
||||
| `--mcp-server-listen IP`, `--mcp-listen-port N` | serve MCP with this registry's tools (port 8098; beyond loopback it needs `SPLINTER_MCP_TOKEN`) |
|
||||
| `--a2a-server-listen IP`, `--a2a-listen-port N` | serve A2A (JSON-RPC, agent card; port 8099; beyond loopback it needs `SPLINTER_A2A_SERVER_TOKEN`) |
|
||||
| `--openai-listen IP`, `--openai-listen-port N` | serve `/v1/chat/completions` with the local `gw_` tools (port 8097) |
|
||||
| `--ack ID yes|no`, `--ack-list` | the ack files under `~/.splinter/ack` — a plugin API (the `kids` plugin asks its parent through it); splinter's own tools do not use it |
|
||||
| `-V, --version`, `-h, --help` | version and this text |
|
||||
|
||||
`--ack`, `--ack-list` and `--live` are read by the parser but missing from the
|
||||
`--help` text (src/main.c:283, :338-352); `--live` is also never used after it is
|
||||
set — the command line of this table, `--help` and the manual page are the
|
||||
reference.
|
||||
|
||||
## What it does
|
||||
|
||||
`splinter -p "list the C files" --endpoint http://127.0.0.1:8080/turn` sends a
|
||||
@@ -31,11 +89,11 @@ is appended to `~/.splinter/<id>.jsonl` as one JSON object per line.
|
||||
- Send a request that exceeds the configured byte budget (nothing is sent; the
|
||||
turn fails instead of letting an endpoint truncate silently).
|
||||
- Run a tool that is not in the registry (the model is told, not guessed at).
|
||||
- Run a mutating or destructive tool without operator consent, unless
|
||||
`--autonomous` was given.
|
||||
- Skip a denial silently: the denial becomes the observation the model sees.
|
||||
- Run a tool the agent's policy does not allow: the denial is the observation
|
||||
the model sees, and it names the policy.
|
||||
- Skip a denial silently.
|
||||
|
||||
## Protocol
|
||||
## Transport protocol
|
||||
|
||||
The harness speaks a line protocol with its transport, not a vendor API:
|
||||
|
||||
@@ -50,45 +108,147 @@ 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: chat 3/4, sidebar 1/4, status bar
|
||||
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: 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/backend/openai_server.c /v1/chat/completions with gw_ tools
|
||||
src/backend/http.c the HTTP helpers the JSON servers share
|
||||
|
||||
src/frontend/curses.c transcript, sidebar, prompt
|
||||
src/frontend/ui_backend.h what the screen needs from a backend
|
||||
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
|
||||
docs/GATEWAY.md the OpenAI endpoint and its two tool sets
|
||||
docs/TOOL-ROOT.md the tools_root fence: what it holds and what not
|
||||
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, the model's question through `ask`, 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`, `ask`, `turn`, ...; `input`, `say`, `answer`,
|
||||
`cancel`, `steer`, `state`, `quit`, `sessions`, `open`). `docs/PROTOCOL.md`
|
||||
has the field list and a sequence diagram; `docs/FRONTENDS.md` has the code
|
||||
layout and how to start a GUI on top of it. The socket is `0600` and the server
|
||||
checks the peer's uid.
|
||||
|
||||
The engine keeps more than one session: `sessions` lists the directory, `open`
|
||||
switches to an id (or `new`/`last`) and sends the state and history of that
|
||||
session. The screen offers the same as `/sessions` and `/open ID`, locally and
|
||||
over the socket; a local switch closes the engine and reopens it from the same
|
||||
options, because plugins keep process globals. `/sessions` without an argument
|
||||
is a picker in two steps: the sources first (`splinter` and every foreign store
|
||||
that has sessions), then the sessions of the chosen one. A foreign row carries
|
||||
its source in the id (`claude:<id>`), and choosing it imports that session and
|
||||
continues it here. A session shows a title - the first user line until
|
||||
`/rename [ID] TITLE` says otherwise - and `/rm ID` removes a session that is not
|
||||
open. One session is active at a time; over the socket, one client at a time.
|
||||
|
||||
`--attach` reconnects: if the server dies, the screen says so, keeps running,
|
||||
and attaches again when a server is back on the socket - asking for the session
|
||||
it was on by id, so the conversation continues where it stopped. If that
|
||||
session is gone, it says which one and stays on the server's current session.
|
||||
|
||||
## Gateway: another harness, splinter's tools
|
||||
|
||||
`splinter --openai-listen 127.0.0.1` serves `/v1/chat/completions` for another
|
||||
harness. The model sees splinter's local tools as `gw_read`, `gw_write`,
|
||||
`gw_run`, ... and the caller's own tools under their own names:
|
||||
|
||||
* a `gw_*` call is executed by splinter, on the host where splinter runs, and
|
||||
the caller only sees the final answer;
|
||||
* any other tool call is returned to the calling harness, which runs it where
|
||||
it runs and sends the results back in the next request.
|
||||
|
||||
That is how one conversation can act in both places, without a name collision
|
||||
between a local `read` and a caller's `read`. Beyond loopback a
|
||||
`SPLINTER_GATEWAY_TOKEN` is required. The endpoint does not approve anything:
|
||||
a caller who can reach it can run the tools the registry offers, and the
|
||||
operator decides what that is by what they register. `docs/GATEWAY.md` has the
|
||||
details and examples.
|
||||
|
||||
The gateway answers one request at a time, so a client that connects and sends
|
||||
half a request used to hold it for everyone; an unanswered read now ends after
|
||||
60 seconds (`SPLINTER_GATEWAY_READ_TIMEOUT`).
|
||||
|
||||
## Plugins and themes
|
||||
|
||||
A plugin is a `.so` against `libsplinter.so`, exporting
|
||||
`sp_plugin_describe()`. It can register tools (with authorization classes the
|
||||
loop enforces) and widgets (rendered in the sidebar). A widget's `tick()` runs
|
||||
on its own thread and publishes text; only the UI thread draws. See
|
||||
`docs/PLUGINS.md`.
|
||||
loop enforces) and widgets. A widget's `tick()` runs on its own thread and
|
||||
publishes a line of text, which the sidebar shows; `/widgets` prints the same
|
||||
lines into the transcript. See `docs/PLUGINS.md`.
|
||||
|
||||
Themes are CDE palettes: 42 of them, generated from the desktop's own `.dp`
|
||||
files. Roles are derived from the eight colour sets — darkest is the
|
||||
background, lightest the foreground, the most saturated the accent. Default is
|
||||
Delphinium. `--list-themes` prints the names, `--theme NAME` picks one.
|
||||
The default theme is `Xresources`: it takes `*foreground`, `*background` and
|
||||
`*color0`..`*color15` from `xrdb -query` (or `~/.Xresources` without X) and
|
||||
paints the UI with them, so the harness looks like the terminal it runs in.
|
||||
Without any of those resources it keeps the terminal's own colour indices.
|
||||
|
||||
Two flat themes are the readable ones: `light` is a white page with black text,
|
||||
`dark` the same inverted. The chat, the sidebar and the input line share the
|
||||
page colour; only the status line above the prompt is a separate surface (light
|
||||
grey on `light`, dark grey on `dark`). That is the shape to reach for when a
|
||||
palette leaves the conversation unreadable: `theme = light` in the config or
|
||||
`--theme light`.
|
||||
|
||||
Every CDE palette from the desktop's `.dp` files is a theme as well, 42 of them
|
||||
including `Default` and `MakroSlate`. A palette is used the way the desktop
|
||||
uses it: set 5 is the chat background, set 4 the input area, set 1 the user's
|
||||
lines, set 7 the model's answer, set 3 its reasoning, set 6 tool calls, set 8
|
||||
status and session notes, and set 2 observations, with black or white text by
|
||||
CDE's own rule. Role colours keep their hue and are moved away from the
|
||||
background only when they would disappear into it. `--list-themes` prints the
|
||||
names, `--theme NAME` picks one, and `theme = NAME` in the config makes it the
|
||||
default.
|
||||
|
||||
## Talking to a model
|
||||
|
||||
@@ -192,6 +352,10 @@ parts are fetched from loopback or a host in `SPLINTER_A2A_URL_ALLOW`.
|
||||
server answers one request at a time, so there is no progress to watch. Beyond loopback the bearer token is required;
|
||||
there is no TLS, so put it behind ssh or a tunnel.
|
||||
|
||||
One request at a time means a client that opens a socket and sends nothing
|
||||
holds everyone else: the server gives up on an unanswered read after 120
|
||||
seconds (`SPLINTER_A2A_READ_TIMEOUT`).
|
||||
|
||||
## Configuration
|
||||
|
||||
`splinter` alone starts the chat: endpoint, model, plugins, theme and session
|
||||
@@ -205,22 +369,71 @@ window, pools that balance or fail over) and agent profiles are in
|
||||
## Streaming
|
||||
|
||||
Answers arrive as they are produced, not as one block: the adapter reads SSE,
|
||||
turns text deltas into the chat pane and tool-call starts into the sidebar, and
|
||||
a reasoning model's own `reasoning_content` is shown dimmed one line above the
|
||||
answer instead of being hidden. In one-shot mode the text goes straight to
|
||||
appends text deltas to the transcript as they arrive and a tool call as its own
|
||||
line, and a reasoning model's own `reasoning_content` is shown dimmed, in
|
||||
sequence, instead of being hidden. In one-shot mode the text goes straight to
|
||||
stdout as it comes.
|
||||
|
||||
Both directions are covered by `test_sse`, which feeds recorded lines: plain
|
||||
text, a tool call split across three chunks, two calls in one turn, a broken
|
||||
data line, and the keepalive lines that carry nothing.
|
||||
A data object split across SSE events, a blank line between its lines and a
|
||||
truncated trailing fragment are all tolerated: the parser buffers until the
|
||||
object is complete and drops a fragment that never is, instead of failing a
|
||||
turn that already has its answer. An error object in the stream
|
||||
(`data: {"error":{"message":...,"code":...}}`) is not ignored: the message is
|
||||
reported and the code becomes the reply's status, so a judge's 400 does not
|
||||
turn into "stream ended with no answer" and is not retried as if it were a
|
||||
broken connection. `test_sse` feeds recorded lines: plain text, a tool call
|
||||
split across three chunks, two calls in one turn, a pretty-printed object
|
||||
across events, a truncated tail, an in-stream 400, and the keepalive lines that
|
||||
carry nothing.
|
||||
|
||||
A request that fails before anything was streamed is tried again three times,
|
||||
five seconds apart; a broken connection, a missing status, a 5xx and a stream
|
||||
that carried no answer qualify, a 401 or 404 does not. After the first streamed
|
||||
chunk the retry stops, because printing the same answer twice is worse than
|
||||
reporting the provider's error. The wait is visible where the failure happened:
|
||||
a status row `retrying in 5 s: ...` joins the transcript below the call, so a
|
||||
pause does not look like a hang and nothing is printed into the input line.
|
||||
Ctrl-C during a wait ends it at once.
|
||||
|
||||
A tool call whose arguments are not JSON is a different failure with a
|
||||
different answer. Sending the identical prompt asks for the identical broken
|
||||
call, so the request is not repeated: the turn appends a user message that
|
||||
quotes what came back and says what was wrong with it - a call cut off by the
|
||||
output limit is told to be smaller, everything else to be one complete JSON
|
||||
object. Five such corrections are allowed, five seconds apart, and each one is
|
||||
announced (`broken tool call, trying again in 5 s (2/5)`), so a gateway that
|
||||
shows no screen still tells the operator why it is quiet. When the fifth
|
||||
correction is spent the turn stops asking for a call at all and asks for words:
|
||||
the operator gets what the model wanted to do, step by step, instead of a turn
|
||||
that died on "model sent malformed tool arguments".
|
||||
|
||||
A stream is never cut for being slow: a router may wait minutes for an upstream
|
||||
without sending anything but keepalive lines, and a byte-per-second guard cut
|
||||
exactly those with "Less than 1 bytes/sec". The overall HTTP timeout is the
|
||||
only limit.
|
||||
|
||||
## Inside tmux
|
||||
|
||||
When the chat starts under tmux, it names the window and the pane after the
|
||||
directory it was started in, with `S: ` in front - `S: kidstube` in one window,
|
||||
`S: splinter` in the next. tmux is asked directly (not through a shell, and the
|
||||
directory is one argument), and `automatic-rename` is turned off for that
|
||||
window so the foreground process does not replace the name. On exit the names
|
||||
tmux had before are put back: normal quit, a signal (SIGTERM/SIGHUP/SIGQUIT) and
|
||||
the double-Ctrl-C exit all restore them, so the shell prompt does not inherit
|
||||
`S:`. Outside tmux nothing is emitted into the terminal.
|
||||
|
||||
## Colour, measured
|
||||
|
||||
A CDE palette is eight mid-tones; painted literally, the accent sat 8% away
|
||||
from the background and nothing was readable. Two fixes, both in `init_colors`:
|
||||
the background is darkened until it is a terminal background, and every role is
|
||||
pushed away from it until it is legible. Delphinium ends up with a white-on-slate
|
||||
text contrast of 14:1, accents at 7.7:1 and labels at 4.7:1 instead of ~1.1:1.
|
||||
A CDE palette is eight mid-tones; painted literally, a role can sit a few
|
||||
percent away from the background, and nothing is readable. Two safeguards live
|
||||
in `theme.c`: text on a surface follows CDE's rule (black on light, white on
|
||||
dark), and a role that is too close to the background is pushed away from it
|
||||
until it is legible. The push keeps the hue, and each role gets a slightly
|
||||
different minimum, so even a monochrome palette yields distinguishable steps.
|
||||
The 256-colour path picks the nearest cube or grey-ramp entry instead of
|
||||
rounding channels down, which used to turn a dark orange into grey 240.
|
||||
`Xresources` themes follow the same rules with colour0..15.
|
||||
|
||||
The other half was a real bug: `COLORS` was read before `start_color()`, so it
|
||||
was 0, the code took the eight-basic-colour path, and the whole palette
|
||||
@@ -234,31 +447,125 @@ The vendored NetBSD curses emits Latin-1 bytes for wide characters (`ü` becomes
|
||||
That is a defect in the ported library, recorded here instead of being papered
|
||||
over with a claim that it works.
|
||||
|
||||
## Input history
|
||||
## What you see, and what is on disk
|
||||
|
||||
The chat draws a transcript: `[time] <you>`, `[time] ~ denkt:` for the model's
|
||||
reasoning, `[time] >> Run du -sh ../xsrc` for a tool call, `[time] | output`
|
||||
for what the tool returned, `[time] <model>` for the answer. A turn that calls
|
||||
tools therefore reads in order: reasoning, text before the call, the call, the
|
||||
output, text after it.
|
||||
|
||||
A call is one row and it says what happened in the words a person would use:
|
||||
the tool as a capitalized verb, then its one interesting argument - the command
|
||||
of a `run`, the path of a `read`, the pattern of a `search`. No JSON, no
|
||||
`command:` in front of the value, and no second copy of the arguments in the
|
||||
prompt: the model's encoding is not the reader's business. Call rows are painted
|
||||
in the accent colour, their output dim underneath, so a run of shell calls is a
|
||||
list of calls and not a grey column of the same word.
|
||||
|
||||
The same records go to `<session_dir>/logs/<session-id>/session.log`, in the
|
||||
order they happened: the user's words, the model's answer, its reasoning, every
|
||||
call with its arguments, every observation, failures and token counts.
|
||||
`wire.jsonl` next to it keeps the request bodies and replies, raw. The log is
|
||||
the complete record - the screen keeps sixteen rows and 4 KiB of a long
|
||||
observation, whichever comes first, and says how many lines are left out, so an
|
||||
`ls -la` or a 300 KB JSON dump does not bury the conversation; the log has all
|
||||
of it.
|
||||
|
||||
## The input line
|
||||
|
||||
Up and Down walk through what was typed before, like a shell. The list is kept
|
||||
in `<session_dir>/history`, so the next session starts with it.
|
||||
|
||||
The prompt is a line editor, not an append buffer: Ctrl-A and Home go to the
|
||||
start, Ctrl-E and End to the end, Left/Right and Ctrl-B/Ctrl-F move by a
|
||||
character (a whole UTF-8 sequence, never a byte), Backspace and Delete remove
|
||||
before and at the caret, Ctrl-K cuts to the end, Ctrl-U clears the line and
|
||||
Ctrl-W removes the word before the caret. Ctrl-L repaints, Ctrl-C clears the
|
||||
line, Ctrl-D quits, Tab completes a `/command` or switches the agent, and
|
||||
Shift+Enter inserts a line break. The `steer>` line of a running turn takes the
|
||||
same keys and scrolls with its caret, so a long sentence stays readable while
|
||||
you type into it. Both prompts used to append every key, which made fixing the
|
||||
first word of a sentence mean retyping it.
|
||||
|
||||
## Steering while a turn runs
|
||||
|
||||
The turn runs on its own thread, so the keyboard stays live. Every tool call is
|
||||
written into the transcript with its name and arguments - `werkzeug: run
|
||||
{"command":"echo a"}` - because "it did something" is not information. The
|
||||
reasoning is inserted before those lines: it came first, and the log should read
|
||||
in the order things happened. The live area has
|
||||
a fixed height (reasoning 8 rows, answer 5, tool line 1): a region that grows
|
||||
with the text moves everything else around it, and text that jumps around the
|
||||
screen is unreadable. While it runs, the
|
||||
input line shows `running Ns | Enter steers, Ctrl-C cancels`. 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.
|
||||
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 is only `steer> ` and what is typed,
|
||||
and the status line above it carries the elapsed seconds as its first meter:
|
||||
the call belongs in the transcript, and in the prompt it was a second copy that
|
||||
pushed the steer hint off the right edge. Nothing else is written into the
|
||||
input line or the status bar; an error is a transcript row below the row that
|
||||
caused it, and a backend request that failed before any answer is retried (the
|
||||
status row says so). A steer is picked up at the
|
||||
next step boundary; in a single-step turn it becomes the next message instead of
|
||||
being dropped. A line that starts with `/` or `!` is a command, not a steer:
|
||||
`/model` opens the picker at once (the switch is applied between requests, so
|
||||
the transport under the running request is never freed), `/status`, `/cost`,
|
||||
`/usage`, `/sessions` and `!` answer immediately. `/compact` typed mid-turn is
|
||||
remembered and applied when the turn ends - the moment you want it is the moment
|
||||
a big conversation has a turn running - and `/new`, `/agent` and `/connect`
|
||||
say "not while a turn runs" instead of being sent to the model. Curses is only
|
||||
ever touched by the UI thread.
|
||||
|
||||
A name is not text: `SP_STREAM_TOOL` carries the name of a call that has begun,
|
||||
and the answer text is built from `SP_STREAM_TEXT` alone. The stream used to be
|
||||
classified by looking for `tool_calls` in the raw line, which broke as soon as
|
||||
the provider sent `"content":null` beside the call - the name landed in the
|
||||
answer and two `read` calls were printed as `<model> readread`. The kind now
|
||||
comes from the parser (`sp_sse_kind`).
|
||||
|
||||
## Compaction
|
||||
|
||||
`focus` keeps the session's goal in front of the model every five turns, the
|
||||
way Claude Code's recap does — one inserted system message, never twice in a
|
||||
turn, nothing until a goal is set. `/goal <text>` sets it, `/recap` forces a
|
||||
reminder, both in the TUI and with `-p`.
|
||||
When the conversation outgrows the window, the core compactor replaces the older
|
||||
part with a digest: each operator message keeps its opening, each assistant turn
|
||||
what it claimed to be doing, each tool result enough to recognise it — in order,
|
||||
because the thread is the point. The newest messages stay verbatim, and the last
|
||||
real user message is pinned so a long tool loop cannot push the task out. A
|
||||
plugin that compacts too runs first; the core one is the backstop.
|
||||
|
||||
What it drops is not gone. The digest opens with a line saying where it went,
|
||||
and the model has `history_search`, which searches the whole session by meaning
|
||||
— not just what is quoted in the digest. The index is built by a background
|
||||
thread, never inside the turn, so the turn does not pay for it (28 ms on a
|
||||
937 KB session). `core { embed = local }` is the default: a built-in CPU
|
||||
encoder, no model, no key. `embed = openai` points it at a real embedding model
|
||||
instead, `off` takes the tool away. See `docs/CONFIG.md`.
|
||||
|
||||
`focus` keeps a short recap of the session's goal in front of the model every
|
||||
seven turns — one inserted system message, never twice in a turn, nothing until
|
||||
a goal is set. `/goal <text>` sets the goal and starts that recap turn; the
|
||||
model's answer is remembered and injected later. The goal is stored in the
|
||||
session's `.meta`, so a resumed session finds it; `/continue` starts the next
|
||||
turn from it. `/goal` alone shows it. There is no separate `/recap`: recapping
|
||||
is what a goal does. Both work in the TUI and with `-p`.
|
||||
|
||||
`/self-check` is the one to type when a turn went nowhere: it hands the model
|
||||
the last three turns it ran, every failed tool result in them and the last
|
||||
turn's error, with the instruction to find its own mistake and continue. It
|
||||
takes no arguments and runs as an ordinary turn, so it works in the TUI, with
|
||||
`-p` and over the socket.
|
||||
|
||||
`/learn` is the one to type when the work is done and nothing was written down.
|
||||
It sends a turn that reads the sessions of this folder — splinter's own with
|
||||
`session_list` and `session_search`, the other harnesses' with `foreign_list`,
|
||||
`foreign_search` and `foreign_read` — and asks for what stays true after today
|
||||
to be kept where it can be found again: a skill for a procedure that worked, a
|
||||
memory for a decision or a measurement, a wiki page for an explanation, a task
|
||||
for work still open. Without an argument it covers every session of the folder
|
||||
and the prompt lists them, newest first; with one (`/learn the gateway retry`)
|
||||
it covers that topic and nothing else. It runs as an ordinary turn, so the same
|
||||
command works in the TUI, with `-p` and over the socket. Which session tools
|
||||
the prompt names depends on what the engine actually loaded; for storing, the
|
||||
prompt names the write tools the registry has (`mcp_junction_skilld__skill_create`
|
||||
and its siblings), and when there are none yet — an MCP server connects in the
|
||||
background — it names their shape and says to read the tool list first. Both
|
||||
came out of live runs: without the names the model greps the filesystem for a
|
||||
server binary, and a prompt that says "you have no write tool" while skilld is
|
||||
still dialling is a lie the model then acts on.
|
||||
|
||||
## Languages
|
||||
|
||||
@@ -301,22 +608,44 @@ or job state; no model turn, no transport.
|
||||
|
||||
## A fleet in one directory
|
||||
|
||||
`src/swarm.c` is the local variant. The first splinter started in a directory
|
||||
binds `.splinter-swarm.sock` and becomes the master; later ones join as slaves.
|
||||
`src/backend/swarm.c` is the local variant, and it is opt-in: `--chat --swarm`
|
||||
is what binds `.splinter-swarm.sock`. A plain `--chat` never creates the file,
|
||||
never joins a fleet, and cannot be locked by one — a shared working directory
|
||||
used to collect a leftover socket from every session, and the next start that
|
||||
found one sat on `[swarm locked]` because nobody answered on it.
|
||||
|
||||
The first instance to bind becomes the master; later ones join as slaves.
|
||||
`/swarm <text>` sends a line to the least busy peer, `/swarm <id> <text>` picks
|
||||
one, `/swarm ls` lists them, and a routed command runs there. It is IPC between
|
||||
processes that share a working directory — not A2A, and not a network protocol.
|
||||
|
||||
The file exists exactly as long as the fleet does: it is removed by the last
|
||||
member to leave, whatever order the members go in. When the master exits first,
|
||||
a remaining member takes the fleet over (binds the path, or joins whoever was
|
||||
faster); a master that is killed hard leaves the file without a listener, and
|
||||
the survivor removes that leftover and binds it, because a refused connect is
|
||||
proof that nobody answers there. SIGTERM and SIGHUP unlink the file from the
|
||||
signal handler (`swarm_emergency_unlink`), since those never reach
|
||||
`sp_engine_close`.
|
||||
|
||||
## First run: the interview
|
||||
|
||||
splinter --interview
|
||||
|
||||
Six questions - language, who you are, stack, answering style, what never to
|
||||
do, which paths are sacred - written to `~/.splinter/profile/<user>.md`. The
|
||||
questions come from the catalogue: the default is English, `locale = de` (or
|
||||
`SPLINTER_LOCALE`) makes them German. Enter
|
||||
skips a question and the skip is recorded as such: an empty line would be a lie.
|
||||
Starting the chat without a profile prints a hint, once.
|
||||
No questionnaire: the model talks to you. Its system prompt says to get to know
|
||||
you - what you work on, the tools you reach for, how you want to be spoken to,
|
||||
what you never want - one question at a time, and to end with a compact summary
|
||||
followed by the single line `INTERVIEW_COMPLETE`.
|
||||
|
||||
That summary is written to `~/.splinter/USER.txt` (0600) and put into the system
|
||||
prompt of every later session, so the harness starts out knowing who it is
|
||||
working with. The marker itself never reaches the file or the transcript. The
|
||||
interview needs a provider like any chat; Telegram has the same `/interview`,
|
||||
with the conversation in the chat.
|
||||
|
||||
An installation from before `USER.txt` still has `~/.splinter/profile/<user>.md`;
|
||||
it is read as the fallback until the first new interview. Starting the chat
|
||||
without either prints a hint, once.
|
||||
|
||||
## Piped input
|
||||
|
||||
@@ -352,12 +681,12 @@ API answers `chat not found`. That is Telegram, not the harness.
|
||||
The bot registers the commands that actually exist with `setMyCommands`:
|
||||
`/start`, `/help`, `/interview`, `/new`, `/model`, `/connect`, every command a
|
||||
loaded plugin registers
|
||||
(`/goal`, `/recap`, `/tasks`, `/quota`, `/tmux`, ...) and every program in
|
||||
(`/goal`, `/quota`, ...) and every program in
|
||||
`~/.splinter/commands/` whose name is a valid Telegram command (lower-case,
|
||||
digits, underscore, at most 32). `/start` and `/help` answer with the short
|
||||
text plus that live list. An approval arrives as a message with **Yes/No
|
||||
buttons**; the callback answers the button, removes the buttons and writes the
|
||||
ack file. The text form `ok <id>` / `no <id>` still works.
|
||||
text plus that live list. The model's `ask` question arrives as a message with
|
||||
the suggested answers as **buttons**; the callback answers it, removes the
|
||||
buttons and hands the text back to the waiting turn.
|
||||
|
||||
The model's markdown is rendered as Telegram HTML: bold, italic, strike,
|
||||
inline code, fenced blocks, links (also `<https://…>`) and quotes become tags,
|
||||
@@ -372,16 +701,62 @@ is split at tag boundaries, with the open tags closed and reopened per
|
||||
message, and a piece Telegram refuses to parse is sent as plain text instead.
|
||||
`SPLINTER_TG_MARKDOWN=0` turns the rendering off.
|
||||
|
||||
`/compact [tokens]` runs the compactors now (default target: `compact_target`,
|
||||
else 8000 tokens) and reports messages/bytes before and after. Typing it while
|
||||
a turn runs does not lose it: the request is queued and applied when that turn
|
||||
ends, which is exactly the moment a large context makes you reach for it. The
|
||||
`lcm` widget in the sidebar keeps the running numbers (context, compactions,
|
||||
messages cut, last cut in messages and bytes, trimmed tool outputs), and the
|
||||
status line carries a `compact N` segment. With
|
||||
`compact_threshold` set, the harness compacts automatically once the last
|
||||
request was larger than that: the conversation is cut to `compact_target`
|
||||
before the next turn, so the context never grows without bound. The size it
|
||||
judges is the `prompt_tokens` the provider reports, so every streamed turn
|
||||
sends `stream_options.include_usage` - a provider that follows the OpenAI
|
||||
contract returns no `usage` otherwise and the threshold would never fire.
|
||||
Compaction rewrites the prompt prefix, which invalidates the provider's prompt
|
||||
cache - the threshold is the knob that trades cache hits for a smaller context.
|
||||
What was dropped stays in the session log, and the `recall` tool searches it:
|
||||
the model can look an earlier turn up instead of guessing.
|
||||
|
||||
The `session` plugin reaches further back: `session_search` finds text in the
|
||||
logs of earlier sessions that ran in this working directory (with date, session
|
||||
id, title and a snippet) and `session_list` shows them. Sessions from other
|
||||
folders are left out. When the working directory has history,
|
||||
the system prompt says so and tells the model to look there before asking the
|
||||
user something that was already answered.
|
||||
|
||||
`/cost` reports what the session has cost: provider-reported dollars (if the
|
||||
provider puts `cost` in its usage object), tokens, and the cache share of the
|
||||
last request. It splits turns into `judged` and `plain`, because a judged model
|
||||
is an upstream alias that runs a judge first: the provider's usage object
|
||||
carries only the final answer, so the judge's own tokens and dollars are not in
|
||||
these numbers. What is measurable is the difference in latency and reported
|
||||
tokens per turn. The sidebar's cost segment prefers the reported dollars over
|
||||
list-price arithmetic.
|
||||
|
||||
`/new` (or `/reset`) starts a fresh conversation and a fresh session file; the
|
||||
old one stays on disk, and the system prompt is put back.
|
||||
|
||||
`/model` lists the models the config names (the main endpoint, every delegate
|
||||
`/model` lists the models the config names (the core endpoint, every delegate
|
||||
with a model, every exit) as buttons and points the running transport at the
|
||||
one you press. The choice is written to `<config>.d/90-model.conf`, so the next
|
||||
start uses it too; picking `main` deletes that file. `/model <name>` keeps the
|
||||
endpoint and takes another model from it. `/model probe` asks every endpoint
|
||||
`/v1/models` and offers what it really serves. The TUI has the same `/model`
|
||||
(list, or `/model <id|name>`), without buttons.
|
||||
one you press. The choice is written to the session's sidecar
|
||||
(`<session>.model`) and comes back when that session is opened again, so one
|
||||
conversation can sit on a different model without changing what a new one
|
||||
starts on. `/model <name>` keeps the endpoint and takes another model from it.
|
||||
`/model probe` asks the configured endpoints `/v1/models` and lists what they
|
||||
really serve.
|
||||
|
||||
In the curses chat, `/model` alone opens a picker: Up/Down move, typing filters
|
||||
by provider or model, Enter takes the highlighted selector, Esc cancels. The
|
||||
rows are the full selector (`junction/qwen3.6-35b-judged`);
|
||||
`-m provider/model` does not invent a second row for the same endpoint. After
|
||||
the configured list appears, the picker asks the endpoint this session is on
|
||||
what it serves and adds those models, so a router's whole menu is selectable
|
||||
and not only the one alias in the config. It is the same list the clients get
|
||||
from the `models` protocol command (with `probe`), so `--attach`
|
||||
has it too, and the actual switch is still the ordinary `/model <selector>`
|
||||
command.
|
||||
|
||||
`/connect` works the same in the TUI, one answer per line. It adds a provider
|
||||
in four answers — name, endpoint, model, key
|
||||
@@ -390,8 +765,8 @@ endpoint. It writes the line to `<config>.d/20-connect.conf`, so the next start
|
||||
has the provider too, runs one tiny turn against it to prove endpoint, model
|
||||
and key work, and offers to use it right away.
|
||||
|
||||
`/interview` asks the same six questions as `splinter --interview`, one
|
||||
message per answer; `/skip` skips one and `/cancel` stops. A program in
|
||||
`/interview` starts the same model-driven interview as `splinter --interview`
|
||||
in the chat; `/new` leaves it. A program in
|
||||
`commands/` answers in the chat: its output is the reply. In the
|
||||
TUI the same program's output becomes context for the model instead. A typo
|
||||
such as `/nosuch` is answered with the command list, not sent to the model.
|
||||
@@ -450,7 +825,7 @@ own model, up to eight run at once, and the answers come back labelled:
|
||||
- slow: 1 task(s), 12018 ms total
|
||||
- fast: 1 task(s), 16 ms total
|
||||
|
||||
The planner gets who did what, how long it took and whether it worked - not a wall
|
||||
The summary gets who did what, how long it took and whether it worked - not a wall
|
||||
of answers. A delegate that is slow or failing is visible in the header before
|
||||
anybody reads its prose.
|
||||
|
||||
@@ -493,15 +868,90 @@ pick is visible instead of mysterious:
|
||||
|
||||
`--choose "text"` prints that decision without running anything:
|
||||
`coder 7 task mentions 'code'`. The child is splinter in one-shot mode with its
|
||||
own context; the tool is classed destructive, so the operator approves the
|
||||
delegation once.
|
||||
own context. The tool is classed destructive; the registry decides whether
|
||||
the agent has it at all.
|
||||
|
||||
## Resuming
|
||||
|
||||
`--resume` loads the newest session in the session directory back into the
|
||||
conversation and puts it on screen. It continues that session id rather than
|
||||
opening a fresh one beside it - the first version did the latter, which looked
|
||||
like a resume and was none.
|
||||
like a resume and was none. The agent profile comes back too: the engine keeps
|
||||
the session's profile in `<session>.agent`, so a session left in plan resumes
|
||||
in plan; the model it was left on is in `<session>.model` and comes back too.
|
||||
|
||||
## Foreign sessions: claude, hermes, opencode
|
||||
|
||||
`splinter --plugin plugins/foreign/foreign.so` reads the three session stores
|
||||
that already exist on the machine and can adopt one of their conversations:
|
||||
|
||||
| source | what it reads |
|
||||
|------------|--------------------------------------------------------|
|
||||
| `claude` | `~/.claude/projects/<slug>/<id>.jsonl` (Claude Code) |
|
||||
| `hermes` | `<root>/state.db` and `<root>/profiles/*/state.db` |
|
||||
| `opencode` | `~/.local/share/opencode/opencode.db` (`session_v2`) |
|
||||
|
||||
The roots are `SPLINTER_FOREIGN_CLAUDE`, `SPLINTER_FOREIGN_HERMES` (a comma
|
||||
list, one root per store) and `SPLINTER_FOREIGN_OPENCODE` (the database file
|
||||
itself), or the plugin's own block in the config, which also loads it:
|
||||
|
||||
plugin foreign {
|
||||
claude = ~/.claude/projects
|
||||
hermes = ~/.hermes, ~/.hermes-work
|
||||
opencode = ~/.local/share/opencode/opencode.db
|
||||
}
|
||||
|
||||
Four tools — `foreign_list`, `foreign_search`, `foreign_read`, `foreign_import`
|
||||
— and the `/foreign` command:
|
||||
|
||||
/foreign list what is there, per store
|
||||
/foreign search TEXT full text, with role and session id
|
||||
/foreign read SOURCE ID one transcript, tool calls in place
|
||||
/foreign import SOURCE ID adopt it as a splinter session
|
||||
|
||||
### Continuing another tool's session from the shell
|
||||
|
||||
The case this was built for: a Claude session hit its limit mid-thought and the
|
||||
conversation has to go on *here*.
|
||||
|
||||
splinter -c --claude
|
||||
|
||||
`--claude` (likewise `--opencode`, `--hermes`, `--from=NAME`) finds the newest
|
||||
session that tool ran in **this** directory, imports it and continues it —
|
||||
the import happens before the history is loaded, so the first turn already
|
||||
carries it. `-c` is not needed for that: `--claude` resumes by itself. What
|
||||
`-c` adds is the fallback — with it, a directory that has neither a foreign
|
||||
nor a splinter session is still an error that says so, instead of an empty
|
||||
start.
|
||||
|
||||
A second start does not import again: the imported session carries
|
||||
`foreign=<source>:<id>` in its sidecar, and that is what the next `-c --claude`
|
||||
finds and continues. Importing again would replace the file and throw away
|
||||
everything the conversation did in splinter since. The empty placeholder a run
|
||||
opens before it knows what it continues is removed; a session that already had
|
||||
content never is.
|
||||
|
||||
The plugin has to be loaded — either `plugin foreign` in the config, or
|
||||
`--plugin plugins/foreign/foreign.so`. Without it the option says so by name
|
||||
instead of silently starting a fresh session.
|
||||
|
||||
`import` writes a real splinter session and says so: the conversation as a
|
||||
replayable `.jsonl`, and a `.meta` with the source's title, its start time and
|
||||
**its** working directory, not the one you imported from. So `/open <new id>`
|
||||
continues it in the chat and `--session-id <new id> --resume` in a shell; `-c`
|
||||
finds it in the directory the conversation actually ran in. The new id carries the origin (`fcl-`, `fhm-`,
|
||||
`foc-`), and the sidecar keeps `foreign=<source>:<id>` — a key the core does not
|
||||
own, so it is carried through every later reopen.
|
||||
|
||||
Three limits worth knowing. The stores are read with `sqlite3 -readonly`, so
|
||||
splinter never writes into them — an import copies, it does not move. Reasoning
|
||||
blocks are dropped on the way in: a provider does not accept another model's
|
||||
thinking as evidence. And the tool calls arrive with their results in place,
|
||||
which is what makes the imported session worth resuming instead of retyping:
|
||||
every `tool_calls` the source recorded is kept with the call id, and every
|
||||
result is kept with the same id, so the pairing a provider insists on survives
|
||||
the import (an imported claude session of 3436 messages reaches the model with
|
||||
its 1630 calls and 1630 results).
|
||||
|
||||
## MCP
|
||||
|
||||
@@ -529,13 +979,17 @@ harness does not pretend to know better. With one server the tools are
|
||||
test server (the model called `mcp_add(17, 25)` and answered 42) and a socket
|
||||
server that speaks HTTP and SSE.
|
||||
|
||||
The sidebar names every server and says whether it is connected
|
||||
(`junction connected`, `files disconnected`), rather than only counting the
|
||||
tools they offered.
|
||||
|
||||
The one-server form from before still works:
|
||||
|
||||
SPLINTER_MCP_CMD="npx -y @modelcontextprotocol/server-filesystem /home" \
|
||||
splinter --plugin plugins/mcp/mcp.so
|
||||
|
||||
The other direction, splinter as the server, is `--mcp-server-listen IP`:
|
||||
newline-delimited JSON-RPC over TCP, read tools only unless `--autonomous`.
|
||||
newline-delimited JSON-RPC over TCP, with the tools the registry offers.
|
||||
On 127.x it needs nothing; on any other address it refuses to start without
|
||||
`SPLINTER_MCP_TOKEN`, and every connection must begin with the line
|
||||
`AUTH <token>`. There is no TLS: across a network you do not own, tunnel it.
|
||||
@@ -544,6 +998,30 @@ On 127.x it needs nothing; on any other address it refuses to start without
|
||||
splinter --mcp-server-listen 0.0.0.0
|
||||
(echo "AUTH $(cat ~/.splinter/mcp.token)"; cat requests.jsonl) | nc host 8098
|
||||
|
||||
Beside the file tools the server offers the session tools, so another agent can
|
||||
work with splinter itself:
|
||||
|
||||
splinter_sessions list the sessions (current marked)
|
||||
splinter_state model, endpoint, profile, session, busy, tokens
|
||||
splinter_models the selectors /model takes
|
||||
splinter_agents the profiles
|
||||
splinter_history the open session's user and assistant messages
|
||||
splinter_say send a prompt, wait, return the answer
|
||||
splinter_open switch to a session (id, new, last)
|
||||
splinter_model switch the model (any /model selector)
|
||||
splinter_agent switch the profile by name
|
||||
splinter_steer type into the running turn
|
||||
splinter_cancel cancel the running turn
|
||||
splinter_answer answer the question the `ask` tool asked
|
||||
|
||||
`say` starts a real turn, so the server needs a provider: give it `-m` (or run
|
||||
`--daemon --mcp-server-listen`, where the Telegram daemon and the MCP server
|
||||
share one engine). A turn that parks on the `ask` tool comes back as the
|
||||
question, not as a failure ("the model asks: ..."), and `splinter_answer`
|
||||
delivers the text — it returns instead of holding the call until the client
|
||||
gives up. The first line of `splinter_say` is the answer, then
|
||||
the step and tool-call counts.
|
||||
|
||||
## Tools
|
||||
|
||||
Every tool declares its class, and the loop enforces it - never the model, never
|
||||
@@ -553,23 +1031,42 @@ the prompt.
|
||||
where it stopped.
|
||||
- `search` (read): literal string over a directory tree, capped at 100 hits.
|
||||
- `list` (read): a directory.
|
||||
- `write` (mutate): writes a file, up to 4 MiB.
|
||||
- `write` (mutate): writes a file, up to 4 MiB. The new text goes to a sibling
|
||||
`.tmp`, is flushed and renamed over the target, so a full disk or a crash can
|
||||
never leave the old file truncated. A symlink is followed and stays a link;
|
||||
the mode of an existing file is kept, and a file the operator made read-only
|
||||
is still refused (`Permission denied`) instead of being replaced.
|
||||
- `edit` (mutate): replaces exactly one occurrence; a non-unique `old` is an
|
||||
error, because an ambiguous edit is a wrong edit waiting to happen.
|
||||
error, because an ambiguous edit is a wrong edit waiting to happen. Written
|
||||
the same way as `write`, atomically. A read error is reported instead of
|
||||
being taken for the end of the file.
|
||||
- `run` (destructive): a shell command; the exit status is an observation.
|
||||
Its own process group, stdin `/dev/null`, killed after `SPLINTER_RUN_TIMEOUT`
|
||||
seconds (default 600) or `run_timeout` in the config, and an environment without
|
||||
splinter's API keys and tokens, so `run env` cannot hand them to the model.
|
||||
Its own process group, stdin `/dev/null`, an environment without splinter's
|
||||
API keys and tokens, so `run env` cannot hand them to the model. It is killed
|
||||
after `SPLINTER_RUN_TIMEOUT` seconds (default 600, or `run_timeout` in the
|
||||
config) **without output**: every line on stdout or stderr resets the window,
|
||||
and the process itself is checked before it is extended, so a long build that
|
||||
reports progress is not killed for being long.
|
||||
- `webfetch` (mutate): http(s) only, curl started without a shell. Not read:
|
||||
a URL the model picks is a message out of the machine.
|
||||
- `ask` (read): puts a question to the operator and waits for the answer; the
|
||||
answer, or "nobody answered", becomes the observation. Read because it
|
||||
changes nothing on the machine and the operator is the authority, not a gate.
|
||||
With `options` the chat shows a dialog to pick from; typed words still count.
|
||||
The chat and the Telegram gateway ask (there the question arrives as a
|
||||
message and the next message from an allowed user is the answer). A run with
|
||||
no operator attached — `-p`, the A2A server, a gateway that only streams —
|
||||
tells the model so at once instead of parking the turn. A front end that
|
||||
never answers the question (an older client that does not know the `ask`
|
||||
event) parks the turn until the wait ends: 900 seconds by default, set
|
||||
`ask_timeout` or `SPLINTER_ASK_TIMEOUT` to make it shorter.
|
||||
- `echo` (read), `clock` (read).
|
||||
|
||||
Mutate and destructive tools ask first, unless `--autonomous` is set. In the
|
||||
chat the question sits where the prompt is - `run (destructive) touch x? y/N` -
|
||||
and the turn waits on it; `n` or Esc denies, and the model is told
|
||||
`error: denied by operator`. This used to be dead code in the TUI: the prompt
|
||||
read stdin behind curses' back, so with `--autonomous` off every such tool was
|
||||
silently denied.
|
||||
A tool the registry offers runs. splinter does not put its own question in
|
||||
front of a tool call - it is the operator's program, and what the agent may
|
||||
reach is what the operator registered (the agent's profile, a plugin's gate,
|
||||
the file tools' root). The one question splinter asks is the model's own,
|
||||
through `ask`.
|
||||
|
||||
## Shell escape
|
||||
|
||||
@@ -580,7 +1077,7 @@ budget in one keystroke.
|
||||
## Slash commands
|
||||
|
||||
A leading `/` never reaches the model: the UI asks the host, the host asks the
|
||||
plugins. A plugin registers what it handles (`/goal`, `/recap` today); an
|
||||
plugins. A plugin registers what it handles (`/goal` today); an
|
||||
unknown command lists what exists instead of being sent as a prompt.
|
||||
|
||||
Compaction is a plugin, not a switch in the loop. Two ship here: `lcm`
|
||||
@@ -592,7 +1089,15 @@ ABI in `docs/PLUGINS.md`.
|
||||
## Limits, stated
|
||||
|
||||
- Tool arguments reach the tool as one string; each tool validates its own.
|
||||
- MCP tools are all `mutate`, so they ask before they run.
|
||||
- The file tools (`read`, `write`, `edit`, `search`, `list`) are only fenced in
|
||||
when `tools_root` is set; empty is the default and means no boundary, so a
|
||||
model that can mutate can also write `~/.ssh/authorized_keys`. With a root set,
|
||||
every path is resolved before it is used (`..`, symlinks, and the entries a
|
||||
recursive `search` walks), so a link inside the root cannot lead out of it.
|
||||
`run` cannot be fenced at all — a shell opens any path — it only starts in the
|
||||
root.
|
||||
- MCP tools are all classed `mutate`: the class is metadata (a plugin gate and
|
||||
a profile's `tools:` read it), not a question in front of every call.
|
||||
- The ring only retries on rate limits; a 500 from a broken endpoint also counts
|
||||
as pressure, so a provider that fails hard gets skipped rather than fixed.
|
||||
- No retrieval tiers over old sessions. Compaction is a plugin (lcm); it cuts the
|
||||
@@ -602,6 +1107,19 @@ ABI in `docs/PLUGINS.md`.
|
||||
- Plugins are not sandboxed. They run in the process with full rights; the
|
||||
authorization classes protect the harness from the *model*, not from code you
|
||||
chose to load.
|
||||
- `make check` is single-threaded in what it asserts. The races that bit are
|
||||
listed in `tests/check_tsan.sh`; run `make check-tsan` (a full rebuild under
|
||||
ThreadSanitizer, then back) when you touched threads, a widget or a plugin's
|
||||
process globals. It is not part of `make check` because a race is not
|
||||
deterministic and the rebuild is slow.
|
||||
- A shell test that starts a server takes its port from `tests/sh/port.sh` and
|
||||
waits with `wait_listen` (HTTP) or `wait_tcp` (anything else) — never a
|
||||
number, never a `sleep`. A guessed port (`20000 + $$ % 30000`) landed on one
|
||||
`dtsession` held on 2026-11-21: the fake died, curl answered from the desktop
|
||||
session, and twenty checks failed pointing at the gateway instead of at
|
||||
the port.
|
||||
The wait proves the *started process* owns the listening socket, because a
|
||||
fake that dies on a taken port still leaves something answering there.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -55,9 +55,9 @@ beobachten).
|
||||
`a2a_get_task`/`a2a_cancel_task` als Client-Werkzeuge und die Agent Card mit
|
||||
Bearer-Token; die Karte meldet `streaming:true` und
|
||||
`pushNotifications:true`. `GetTask` liefert das Task-Objekt, nicht
|
||||
`{"task":...}`. Ein mutierendes Werkzeug pausiert als
|
||||
`INPUT_REQUIRED`; `SendMessage` mit `taskId` und `yes`/`no` setzt fort,
|
||||
`CancelTask` bricht ab (`test_pause`, `test_a2a_input.sh`). `tests/test_a2a.sh` prueft Task, Message, Token, Fehler,
|
||||
`{"task":...}`. Werkzeuge laufen ohne Rueckfrage; es gibt kein
|
||||
`INPUT_REQUIRED` (an einem A2A-Aufrufer sitzt kein Operator, den man fragen
|
||||
koennte), `CancelTask` bricht ab (`test_pause`, `test_a2a_input.sh`). `tests/test_a2a.sh` prueft Task, Message, Token, Fehler,
|
||||
Streaming und Discovery, `tests/test_a2a_ui.sh` den Streaming-Pfad,
|
||||
`tests/test_a2a_server.sh` den Server und den Client gegen den Server
|
||||
(Discovery, blockierend und streamend), `tests/test_a2a_context.sh` die
|
||||
@@ -88,7 +88,7 @@ beobachten).
|
||||
in denselben Puffer; `json_str` haengt an, also wurde aus `job-1` mit
|
||||
`force=1` die Id `job-11` (`src/delegate.c`, `tool_delegate_retry`).
|
||||
- **Skills und Memory**: `src/skills.c`, `src/memory.c`, registriert in
|
||||
`src/main.c:908-909`, `test_skills` und `test_memory` laufen gruen.
|
||||
`src/main.c:908-909` und `test_skills` laufen gruen.
|
||||
- **Kompression verdrahtet**: `ag->host` wird gesetzt (`src/main.c:635`).
|
||||
- **Turn-Loop-Schrittlimit**: `8` war der alte Default, kein Zaehlfehler;
|
||||
`75d8bee` setzt 150 (`src/main.c:873`, `src/config.c:573`).
|
||||
|
||||
+184
-50
@@ -23,15 +23,17 @@ harness will not start. An error names the line you wrote.
|
||||
|
||||
```
|
||||
core {
|
||||
default = main # a provider or a pool, below
|
||||
theme = Delphinium
|
||||
autonomous = true
|
||||
default = provider/model # a provider, provider/model, or a pool
|
||||
theme = Xresources
|
||||
steps = 60
|
||||
on_limit = wait # a usage limit is waited out (or: fail)
|
||||
max_wait = 2d
|
||||
plugins = [plugins/lcm/lcm.so, plugins/cli/cli.so]
|
||||
}
|
||||
|
||||
plugin lcm { } # one block per plugin, see "Plugins"
|
||||
plugin recap { every = 5 } # /recap <text>, repeated every 5 turns
|
||||
plugin cli { }
|
||||
|
||||
telegram { allow = [123456789] }
|
||||
|
||||
provider ocgo {
|
||||
@@ -118,13 +120,17 @@ splinter -m ocgo/other-model # a provider with another of its models
|
||||
splinter -m some-model-name # a model that one provider has
|
||||
```
|
||||
|
||||
Without `-m`, `default` in `core` decides.
|
||||
Without `-m`, `default` in `core` decides. The order is: `-m` on the command
|
||||
line, then the last `default` from the config and its drop-ins (a `/model`
|
||||
choice writes one), then the `endpoint`/`model` of the `core` block (the main
|
||||
endpoint). An explicit `default` is never shadowed by a core endpoint.
|
||||
|
||||
## Agent profiles: build, plan and your own
|
||||
|
||||
Tab in the chat (Shift-Tab back) switches the agent profile, like opencode.
|
||||
The status line shows it (`[plan]`), `/agent` lists them, `/agent NAME` picks
|
||||
one, `splinter --agent NAME` starts in one and `--agent-list` prints them.
|
||||
The prompt carries the name (`plan> `), the transcript notes the switch,
|
||||
`/agent` lists them, `/agent NAME` picks one, `splinter --agent NAME` starts in
|
||||
one and `--agent-list` prints them.
|
||||
|
||||
- `build` is the default: every tool.
|
||||
- `plan` reads, searches and analyses, changes nothing (tools of the class
|
||||
@@ -139,7 +145,7 @@ model: analyst # what -m takes: provider, pool, provider/model
|
||||
tools: read # all (default) | mutate | read
|
||||
allow: [delegate*] # names (or prefix*) allowed beyond that
|
||||
deny: [run] # never allowed, wins over everything
|
||||
autonomous: false # run mutating tools without asking, or not
|
||||
autonomous: false # kept for compatibility; changes nothing now
|
||||
---
|
||||
The prompt. It is added to the system prompt while this profile is active.
|
||||
```
|
||||
@@ -210,8 +216,20 @@ repeats the request: `on_limit = wait`, the default. `max_wait` bounds it
|
||||
## Not in the file: the goal
|
||||
|
||||
The session goal is set at runtime with `/goal <text>` — in the TUI, or in a
|
||||
one-shot run (`splinter -p "/goal ship the config"`). It belongs to the
|
||||
conversation in front of you, not to a file that outlives it.
|
||||
one-shot run (`splinter -p "/goal ship the config"`). It sets the goal and
|
||||
starts a turn that writes a short recap; the recap is injected every seventh
|
||||
turn. The goal itself is stored in the session's `.meta`, so `/continue` and a
|
||||
resumed session find it. It belongs to the conversation in front of you.
|
||||
|
||||
## The `.meta` sidecar is shared
|
||||
|
||||
`<session dir>/<id>.meta` is one `key=value` per line. The core owns `cwd`,
|
||||
`created`, `opened`, `title`, `goal` and `goal_state` and rewrites the file on
|
||||
every open, rename and `/goal`. Any other key is kept verbatim, so a plugin can
|
||||
mark a session in the same file — `plugins/foreign` records `foreign=hermes:h-1`
|
||||
there to say where an imported conversation came from, and the marker survives
|
||||
the reopen that `-c` or `/open` causes. Unknown keys are carried through
|
||||
unchanged, up to eight of them; a `key=value` longer than 159 bytes is cut.
|
||||
|
||||
## Precedence
|
||||
|
||||
@@ -221,32 +239,46 @@ lies about what it does.
|
||||
|
||||
## Keys
|
||||
|
||||
A setting that names a path (`session_dir`, `state_dir`, `tools_root`,
|
||||
`skills_dir`) takes a leading `~` as the home directory, exactly as the shipped
|
||||
template writes it: `~/src` is `$HOME/src`. Any other path is used verbatim.
|
||||
The `${NAME}` form inserts an environment variable.
|
||||
|
||||
| key | meaning |
|
||||
|-----|---------|
|
||||
| `endpoint` | the API base, e.g. `http://127.0.0.1:8080/v1`; splinter appends `/chat/completions` (or `/messages` for `kind = anthropic`), `/models`, and the usage routes. A full route still works: it is cut back to the base |
|
||||
| `model` | model name the endpoint expects |
|
||||
| `ctx` | context window in tokens, optional; the curses status bar uses it for the `ctx used/max` gauge. `SPLINTER_CTX_MAX` overrides it for one run |
|
||||
| `api_key_env` | name of the env var holding the key (default `SPLINTER_API_KEY`) |
|
||||
| `transport` | a transport a plugin provides, e.g. `cli` |
|
||||
| `cli_cmd` | command for the `cli` transport, e.g. `claude -p` |
|
||||
| `plugin` | a plugin to load, one line each; absolute paths survive a `cd` |
|
||||
| `theme` | CDE palette name (`splinter --list-themes`) |
|
||||
| `plugin` | a plugin to load, one line each: a shipped plugin's name (`lcm`) or a path; in the block form `plugin NAME { }`, see "Plugins" |
|
||||
| `theme` | `Xresources` (the default: `*foreground`, `*background`, `*color0..15` from `xrdb`), `light`/`dark` (white or black page, black or white text), or a CDE palette name (`splinter --list-themes`) |
|
||||
| `locale` | language code (`de`, `en`); catalogues live in `share/locale` |
|
||||
| `autonomous` | `1` runs mutating/destructive tools without asking |
|
||||
| `autonomous` | kept so an existing file still parses; splinter does not gate its own tools, so the value changes nothing |
|
||||
| `ask_timeout` | seconds an `ask` waits for the operator's answer (default 900); `SPLINTER_ASK_TIMEOUT` overrides it for one run. Shorten it for a run with no operator attached, so a turn does not park for the full wait |
|
||||
| `steps` | tool rounds per turn (default 150) |
|
||||
| `max_bytes` | conversation budget in bytes, `0` = no limit |
|
||||
| `session_dir` | where session logs go (default `~/.splinter`) |
|
||||
| `compact_threshold` | context tokens past which the next request is compacted (`0` = off); judged by the prompt size the provider reports, which every streamed turn asks for |
|
||||
| `compact_target` | the size compaction aims for, in tokens; `/compact [tokens]` forces it now |
|
||||
| `embed` | the session's search index: `local` (default, built-in CPU encoder, no model and no key), `openai` (posts to `embed_endpoint`), `off` |
|
||||
| `embed_dims` | vector size, 8..4096, default 256; only meaningful for `local`, and `openai` must match what the model returns |
|
||||
| `embed_model` | model name for `embed = openai`, e.g. `nomic-embed-text` |
|
||||
| `embed_endpoint` | base URL for `embed = openai`, e.g. `http://127.0.0.1:11434/v1` |
|
||||
| `embed_key_env` | env var holding the key for `embed_endpoint` |
|
||||
| `embed_timeout` | seconds one embedding request may take |
|
||||
| `session_dir` | where session logs go (default `~/.splinter`); `SPLINTER_SESSION_DIR` overrides it, which is how `make check` keeps its test sessions out of yours |
|
||||
| `tools_root` | the only directory the file tools (`read`, `write`, `edit`, `search`, `list`) may touch. Empty — the default — means no boundary, so an existing setup keeps working. `run` is not fenced by it (a shell can open any path); it starts there. Resolved once at startup with `realpath`, so `..` and symlinks are checked against the file that is actually reached, and a root that does not exist is refused at startup instead of matching nothing |
|
||||
| `system_prompt` | sent once at the start of a conversation |
|
||||
| `telegram_allow` | user ids the gateway answers, comma-separated; empty means nobody |
|
||||
| `memory_url` | base URL of a mem0 server (`memory_search`, `memory_add`) |
|
||||
| `memory_key_env` | env var with the mem0 key, sent as `Authorization: Token <key>` |
|
||||
| `skills_dir` | a directory of skills, one line each |
|
||||
| `env_delegates` | `1` turns `CLAUDE_CODE_OAUTH_TOKEN(_N)` into delegates (default off) |
|
||||
| `on_limit` | `wait` (default) or `fail`: what a usage limit does |
|
||||
| `max_wait` | longest wait for a limit, e.g. `6h`, `2d` (default 12h) |
|
||||
| `kind` | of the main provider: `openai` (default) or `anthropic` |
|
||||
| `kind` | of the core endpoint: `openai` (default) or `anthropic` |
|
||||
| `default` | the provider or pool the conversation starts on |
|
||||
| `pool` | `pool = id \| strategy=failover\|balance \| members=a,b` |
|
||||
| `limit`, `tokens` | allowance of the main provider, see Usage limits |
|
||||
| `limit`, `tokens` | allowance of the core endpoint, see Usage limits |
|
||||
| `exit` | one way to reach a model for the exit ring, see below |
|
||||
| `delegate` | another model the `delegate` tool can hand work to, see below |
|
||||
| `mcp` | an MCP server whose tools become splinter's tools, see below |
|
||||
@@ -281,7 +313,7 @@ calls: one line per call in `~/.splinter/usage/<id>.log`, shared by every
|
||||
splinter on the machine. You declare the allowance:
|
||||
|
||||
```
|
||||
limit = 45/5h # the main provider: 45 calls per 5 hours
|
||||
limit = 45/5h # the core endpoint: 45 calls per 5 hours
|
||||
tokens = 2000000/7d # and/or tokens per window (5m, 5h, 7d, 2w)
|
||||
delegate = claude-a | Claude Pro A | kind=cli | cmd=claude -p | tags=plan | limit=45/5h
|
||||
delegate = claude-b | Claude Pro B | kind=cli | cmd=claude -p | tags=plan | limit=45/5h | env=CLAUDE_CODE_OAUTH_TOKEN=...
|
||||
@@ -290,8 +322,8 @@ delegate = cloud | ollama.com | endpoint=... | model=... | tags=code | toke
|
||||
|
||||
What it does with that:
|
||||
|
||||
- the status line shows how full each allowance is (`claude-a 5h 62%`), a
|
||||
benched one shows when it is back; `/usage` lists all with bars;
|
||||
- `/usage` shows how full each allowance is (`claude-a 5h 62%`), a benched
|
||||
one shows when it is back;
|
||||
- delegation skips a provider whose allowance is used up, and among providers
|
||||
that fit the task equally well (same tags: a pool of accounts) it takes the
|
||||
one with the most left;
|
||||
@@ -320,29 +352,88 @@ task moves to the next delegate in its own slot while the others keep running,
|
||||
unless that one is already at its `max_parallel`. Only when nothing else fits
|
||||
does the job wait (`waiting_quota`) for the reset.
|
||||
|
||||
## Plugins
|
||||
|
||||
Every plugin has its own block. The block loads it, and everything in it
|
||||
apart from `path` and `enabled` is that plugin's own configuration:
|
||||
|
||||
```
|
||||
plugin lcm {
|
||||
keep = 6 # messages kept verbatim
|
||||
tool_trim = 8192 # older tool outputs are cut to this
|
||||
}
|
||||
plugin junction { } # url/header from the mcp junction server
|
||||
plugin session { } # old sessions: session_search/session_list
|
||||
plugin mine {
|
||||
path = ~/my/plugin.so # not shipped: say where it is
|
||||
foo = bar
|
||||
}
|
||||
plugin status { enabled = false } # kept in the file, not loaded
|
||||
```
|
||||
|
||||
| field | meaning |
|
||||
|-------|---------|
|
||||
| `path` | the `.so` to load; without it the shipped plugin of that name |
|
||||
| `enabled` | `false` keeps the block but does not load the plugin (default on) |
|
||||
| anything else | the plugin's own setting, read with `sp_host_plugin_config()` |
|
||||
|
||||
Without `path`, `plugin NAME { }` finds the shipped plugin next to the
|
||||
binary: `plugins/NAME/NAME.so` in the build tree, then the installed
|
||||
`$(PREFIX)/lib/splinter/plugins/NAME.so`, then the build directory the binary
|
||||
was compiled in. A nested block gives dotted names: `server a { url = x }`
|
||||
inside `plugin foo` is `server.a.url`; a list `[a, b]` arrives as `a,b`.
|
||||
`docs/PLUGINS.md` has the API.
|
||||
|
||||
The old forms still load, so an existing file keeps working:
|
||||
`plugins = [plugins/lcm/lcm.so, ...]` in `core` (one path each) and the flat
|
||||
`plugin = /path/to/x.so`. They carry no plugin settings.
|
||||
|
||||
`plugin junction { }` reads the address and the key from the `mcp junction`
|
||||
server it already uses; its own block may override them:
|
||||
|
||||
```
|
||||
plugin junction {
|
||||
url = http://127.0.0.1:8090/mcp
|
||||
header = "Authorization: Bearer ${JUNCTION_TOKEN}"
|
||||
interval = 5000 # ms between /mcp and status checks
|
||||
models_interval = 60000 # ms between /v1/models probes
|
||||
status_path = /status # first alias; /v1/status, /queue, /v1/queue follow
|
||||
}
|
||||
```
|
||||
|
||||
It evaluates the `X-Junction-Mcp` response header (that is how junction
|
||||
identifies itself; a 200 without it is reported as "not junction") and reads
|
||||
uptime, MCP-server health, queue and request counts from `/status`. The sidebar
|
||||
widget, the `junction` status segment, `junction_status` and `/junction` all
|
||||
show that snapshot. Without either block, `SPLINTER_JUNCTION_URL` and
|
||||
`SPLINTER_JUNCTION_TOKEN` are read.
|
||||
|
||||
## MCP servers
|
||||
|
||||
An MCP server contributes tools. One line each, or a block, and it needs the
|
||||
`plugins/mcp/mcp.so` plugin:
|
||||
An MCP server contributes tools. The servers are the configuration of the
|
||||
`mcp` plugin, one `server` block each:
|
||||
|
||||
```
|
||||
plugin = /home/lotherk/src/splinter/plugins/mcp/mcp.so
|
||||
plugin mcp {
|
||||
# streamable HTTP: one POST per message
|
||||
server junction {
|
||||
url = http://172.25.206.16:8090/mcp
|
||||
header = "Authorization: Bearer ${JUNCTION_TOKEN}"
|
||||
}
|
||||
|
||||
# streamable HTTP: one POST per message
|
||||
mcp junction {
|
||||
url = http://172.25.206.16:8090/mcp
|
||||
header = "Authorization: Bearer ${JUNCTION_TOKEN}"
|
||||
# or a program that speaks MCP on its stdin/stdout
|
||||
server files {
|
||||
cmd = "npx -y @modelcontextprotocol/server-filesystem /home"
|
||||
}
|
||||
|
||||
# a server that exists but should not be asked
|
||||
server old { url = http://127.0.0.1:9000/mcp enabled = false }
|
||||
}
|
||||
|
||||
# or a program that speaks MCP on its stdin/stdout
|
||||
mcp files {
|
||||
cmd = "npx -y @modelcontextprotocol/server-filesystem /home"
|
||||
}
|
||||
|
||||
# a server that exists but should not be asked
|
||||
mcp old { url = http://127.0.0.1:9000/mcp enabled = false }
|
||||
```
|
||||
|
||||
The top-level `mcp NAME { ... }` block and the flat `mcp = ...` line from
|
||||
before still work (they need the plugin loaded as well).
|
||||
|
||||
| field | meaning |
|
||||
|-------|---------|
|
||||
| `url` | the endpoint, streamable-HTTP transport (`.../mcp`) |
|
||||
@@ -371,12 +462,12 @@ single-server environment variable from before still works:
|
||||
```
|
||||
endpoint = http://127.0.0.1:8080/v1
|
||||
model = /models/unsloth/Qwen3.6-35B-A3B-MTP-GGUF/Qwen3.6-35B-A3B-UD-Q8_K_XL.gguf
|
||||
theme = Delphinium
|
||||
autonomous = 1
|
||||
plugin = /home/lotherk/src/splinter/plugins/lcm/lcm.so
|
||||
plugin = /home/lotherk/src/splinter/plugins/cps/cps.so
|
||||
plugin = /home/lotherk/src/splinter/plugins/clock/clock.so
|
||||
theme = Xresources
|
||||
plugin = lcm
|
||||
plugin = cps
|
||||
plugin = clock
|
||||
session_dir = /home/lotherk/.splinter
|
||||
tools_root = /home/lotherk/src # the file tools stay here; omit for none
|
||||
```
|
||||
|
||||
## Example: Claude Code as the model
|
||||
@@ -384,9 +475,9 @@ session_dir = /home/lotherk/.splinter
|
||||
```
|
||||
transport = cli
|
||||
cli_cmd = claude -p
|
||||
cli_timeout = 1800
|
||||
plugin = /home/lotherk/src/splinter/plugins/cli/cli.so
|
||||
theme = Delphinium
|
||||
cli_timeout = 1800 # seconds of silence, not a wall clock
|
||||
plugin = cli
|
||||
theme = Xresources
|
||||
```
|
||||
|
||||
`cli_env = NAME=VALUE` (repeatable, up to 8) sets a variable for the cli
|
||||
@@ -432,6 +523,47 @@ or pass the prompt via a flag your CLI supports.
|
||||
With both `endpoint` and `transport` set, `transport` wins — it is the more
|
||||
specific instruction.
|
||||
|
||||
## Searching the session: `embed`
|
||||
|
||||
Compaction drops messages from the conversation to fit the window. They stay in
|
||||
the session file, and the model gets a `history_search` tool to find them again
|
||||
by meaning. The digest that replaces them names the tool — but only when it is
|
||||
really registered, since a prompt pointing at a missing tool teaches the model
|
||||
to call nothing.
|
||||
|
||||
```
|
||||
core {
|
||||
embed = local # default
|
||||
embed_dims = 256
|
||||
}
|
||||
```
|
||||
|
||||
`embed = local` is the built-in encoder: no model, no key, no network. It hashes
|
||||
words, four-character prefixes and bigrams into a signed vector on the CPU. It
|
||||
is weaker than a real embedding model (measured: paraphrase 0.92, unrelated
|
||||
0.01) and it is enough to tell "the deploy machine" from "the frontend build".
|
||||
|
||||
`embed = openai` sends the text to `<embed_endpoint>/embeddings` with
|
||||
`embed_model`; `embed_dims` must match what the model returns. The **question**
|
||||
goes to the same endpoint: an index built by a model can only be searched by
|
||||
that model, so a query is never hashed locally when the index was not. `embed =
|
||||
off` keeps the tool out entirely.
|
||||
|
||||
Two things it does **not** do: it never runs inside the turn, and it never
|
||||
delays an answer. The indexer is its own thread; a 937 KB session costs the turn
|
||||
28 ms. The index lives in `<session_dir>/emb/<session-id>.emb`, next to the
|
||||
session log, and grows with it — a resumed session becomes searchable in the
|
||||
background without anything having been compacted.
|
||||
|
||||
`/status` shows what the indexer is doing (`status.embed`).
|
||||
|
||||
The tool says what it found, or why it found nothing: `the index is still
|
||||
filling; ask again in a moment` while the thread catches up on a session that
|
||||
just grew, `the index is empty: nothing in this session has been indexed yet`
|
||||
when there is nothing to search, `the query has no searchable words` when the
|
||||
question was all stopwords (local encoder), and `the embedding endpoint refused
|
||||
the query` when the remote one did. All of them are answers, not errors.
|
||||
|
||||
## Adding a provider from the chat
|
||||
|
||||
`/connect` — in the Telegram gateway and in the TUI (one answer per line) —
|
||||
@@ -446,12 +578,14 @@ and stand for `http://127.0.0.1:11434/v1` and
|
||||
`OPENCODE_GO_API_KEY`).
|
||||
|
||||
`/model` offers the models the config names and switches the transport; the
|
||||
choice is written to `<config>.d/90-model.conf` (`endpoint`, `model`,
|
||||
`api_key_env`), so the next start has it. Picking `main` deletes that file and
|
||||
the configuration speaks again. `/model probe` asks each endpoint `/v1/models`
|
||||
and lists what it really serves; `/model <name>` takes another model from the
|
||||
current endpoint. With a plugin `transport` nothing is written — that program
|
||||
picks the model.
|
||||
choice is written to the session's sidecar (`<session>.model`) as a selector,
|
||||
so reopening that session brings the model back without changing what a new
|
||||
session starts on. The provider block supplies kind, endpoint and key variable;
|
||||
the sidecar only names the choice. `/model probe` asks each endpoint
|
||||
`/v1/models` and lists what it really serves; the picker in the curses chat
|
||||
also asks the endpoint the session is on and adds those models to its list.
|
||||
`/model <name>` takes another model from the current endpoint. With a plugin
|
||||
`transport` nothing is written — that program picks the model.
|
||||
|
||||
## Drop-ins
|
||||
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
# 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` | `splinter --serve`: JSON lines, sessions, open |
|
||||
| `src/frontend/client.c` | `splinterctl`, the reference protocol client |
|
||||
| `src/main.c` | the launcher: parse, config, engine, pick a front end |
|
||||
|
||||
`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 `ask` question 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
|
||||
```
|
||||
|
||||
The server owns the engine: `sessions` lists the session directory and `open`
|
||||
switches to another id (or `new`/`last`), sending the state and history of that
|
||||
session. The curses screen exposes that as `/sessions` and `/open ID`, in both
|
||||
modes: `--serve` switches its engine, and the in-process `--chat` closes its
|
||||
engine and opens the next one from the same options (plugins keep process
|
||||
globals, so the old one goes first). `/sessions` without an argument is a
|
||||
two-step picker over the same ops (`sources`, then `source_sessions`): the
|
||||
foreign stores appear next to this folder's sessions, and picking one of their
|
||||
rows runs the same `/open <source>:<id>` that imports and continues it. One
|
||||
session is active at a time; two clients still take turns.
|
||||
|
||||
`--attach` keeps running when the backend disappears: it says so, retries every
|
||||
second, and on the next server asks for the session it was on by id. The history
|
||||
it already had is shown again, and turns continue; if that session is gone, the
|
||||
screen says which one and stays on the session the server has. A GUI gets the
|
||||
same with `sessions`, `open` and its own retry loop.
|
||||
|
||||
## Writing a GUI client
|
||||
|
||||
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. Use
|
||||
`sessions`/`open` for tabs and retry the connect for a server restart.
|
||||
|
||||
3. **Let another harness use splinter as a model.** `splinter --openai-listen`
|
||||
serves `/v1/chat/completions`: the caller's tools stay with the caller,
|
||||
splinter's own run locally under `gw_*`. See `docs/GATEWAY.md`.
|
||||
|
||||
The recommended shape for a GUI:
|
||||
|
||||
* 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 `ask` arrives, show `text` and `options` and send `answer` with the
|
||||
text the operator gave; the turn is parked until it arrives, so a client
|
||||
that ignores the event leaves the model waiting (the engine's timeout ends
|
||||
it with "nobody answered", but slowly);
|
||||
* `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 `ask` question that nobody can answer would park the engine forever.
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
# The OpenAI gateway
|
||||
|
||||
`splinter --openai-listen IP [--openai-listen-port N]` is a small
|
||||
OpenAI-compatible endpoint. Another harness points its OpenAI client at it and
|
||||
gets an answer from splinter's configured provider, with **tools on both
|
||||
sides**: splinter executes its own tools where splinter runs, the caller
|
||||
executes its tools where the caller runs.
|
||||
|
||||
```sh
|
||||
# the side with the files and the shell
|
||||
splinter -m myprovider --openai-listen 127.0.0.1 --openai-listen-port 8097
|
||||
|
||||
# the other harness
|
||||
export OPENAI_BASE_URL=http://127.0.0.1:8097/v1
|
||||
export OPENAI_API_KEY=unused # unless SPLINTER_GATEWAY_TOKEN is set
|
||||
```
|
||||
|
||||
`GET /v1/models` answers with the run's model, so a client that probes first is
|
||||
happy. `POST /v1/chat/completions` accepts the usual `messages`, `tools` and
|
||||
`stream` fields.
|
||||
|
||||
## Two tool namespaces
|
||||
|
||||
The model sees two kinds of tools in one request:
|
||||
|
||||
| name | who runs it | where |
|
||||
| --- | --- | --- |
|
||||
| `gw_read`, `gw_write`, `gw_edit`, `gw_run`, … | splinter | on the host where splinter runs |
|
||||
| everything in the caller's `tools` array | the calling harness | where the harness runs |
|
||||
|
||||
`gw_` is reserved: a caller tool with that prefix is refused with HTTP 400,
|
||||
because that is how a local `read` and a caller's `read` stay apart.
|
||||
|
||||
The loop, inside one HTTP request:
|
||||
|
||||
1. splinter asks its provider with the caller's conversation, the caller's
|
||||
tools **and** its own tools renamed `gw_*`.
|
||||
2. If the model calls `gw_*`, splinter runs it here (read tools always;
|
||||
mutating and destructive ones as the registry offers them), appends the
|
||||
observation and asks the provider again. The caller never sees these calls.
|
||||
3. If the model calls a caller tool, splinter returns a normal
|
||||
`chat.completion` with `tool_calls` and `finish_reason: "tool_calls"`. The
|
||||
harness runs them, sends the results as `tool` messages in the next request,
|
||||
and the gateway continues.
|
||||
4. If a reply mixes both, the local calls run here and the caller's calls are
|
||||
returned in the same `tool_calls` answer. Since the caller cannot answer a
|
||||
`gw_` call, the local observations travel in the message `content` (under
|
||||
"local gateway tools ran on the splinter host:"); the caller sends them back
|
||||
with the assistant message as usual, and the model sees both sides.
|
||||
|
||||
Every request is stateless, as the OpenAI protocol says: the conversation
|
||||
travels with it. The loop is capped at 16 local tool rounds and each
|
||||
observation at 32 KiB.
|
||||
|
||||
## Request shaping
|
||||
|
||||
The caller's `temperature`, `top_p` and `max_tokens` (or
|
||||
`max_completion_tokens`) are forwarded to the provider; absent values stay the
|
||||
provider's default. The response echoes the request's `model` name, and every
|
||||
message, including the mixed-reply case, stays within the OpenAI chat shape.
|
||||
|
||||
Bodies may arrive with `Content-Length` or `Transfer-Encoding: chunked`; only
|
||||
one request per connection is read, then the connection closes.
|
||||
|
||||
## Streaming
|
||||
|
||||
With `"stream": true` the gateway uses the provider's streaming transport and
|
||||
forwards each text delta as a `chat.completion.chunk` event while it arrives -
|
||||
the caller sees the answer grow instead of waiting for the last token. The
|
||||
caller's tool calls are sent as one `tool_calls` delta at the end of the step,
|
||||
because a name is only complete when the provider has finished it; local
|
||||
`gw_*` calls stay invisible. `"stream_options":{"include_usage":true}` adds a
|
||||
final usage chunk before `[DONE]`, with the token counts summed over every
|
||||
upstream round of the request.
|
||||
|
||||
If the provider fails after the stream has started, the stream carries an
|
||||
`{"error":...}` object and `[DONE]`; a request that was invalid before the
|
||||
first byte is still an ordinary HTTP 400. The gateway ignores SIGPIPE, so a
|
||||
caller that closes its stream early cannot kill the server.
|
||||
|
||||
## Examples
|
||||
|
||||
A local tool, executed by splinter, from the caller's point of view an ordinary
|
||||
completion:
|
||||
|
||||
```sh
|
||||
curl -s http://127.0.0.1:8097/v1/chat/completions \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"model":"x","messages":[{"role":"user","content":"read Cargo.toml"}]}'
|
||||
```
|
||||
|
||||
A caller tool comes back instead:
|
||||
|
||||
```json
|
||||
{"choices":[{"index":0,"message":{"role":"assistant","content":"",
|
||||
"tool_calls":[{"id":"c1","type":"function",
|
||||
"function":{"name":"browser_open","arguments":"{\"url\":\"...\"}"}}]},
|
||||
"finish_reason":"tool_calls"}]}
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
- Beyond loopback the server refuses to start without
|
||||
`SPLINTER_GATEWAY_TOKEN`; with a token set, every request needs
|
||||
`Authorization: Bearer <token>`.
|
||||
- the endpoint has no approval step: whatever `gw_*` tool the registry offers
|
||||
is callable (`gw_write`, `gw_run`, ...). `--autonomous` is accepted and
|
||||
changes nothing. Who may reach the endpoint is decided by the token and by
|
||||
what the operator registers, not by a question the gateway could not put to
|
||||
anyone.
|
||||
- There is no TLS. Expose it through ssh, WireGuard or a TLS proxy when the
|
||||
network is not yours.
|
||||
- One request is served at a time; the endpoint is a gateway, not a load
|
||||
balanced service. That makes a silent client everyone's problem: an
|
||||
unanswered read ends after 60 seconds
|
||||
(`SPLINTER_GATEWAY_READ_TIMEOUT`), and the next connection is then served.
|
||||
|
||||
## Where the tools come from
|
||||
|
||||
`gw_*` is the engine's registry: the builtins (`read`, `write`, `edit`,
|
||||
`search`, `list`, `run`, `websearch`, `webfetch`), `folder_history`,
|
||||
`delegate`, and the skills tools. Plugins loaded with `--plugin` add
|
||||
theirs. The caller's tools are passed through to the provider untouched, except
|
||||
for the `gw_` reservation.
|
||||
+250
-60
@@ -24,6 +24,46 @@ cc -std=c99 -shared -fPIC -o myplugin.so myplugin.c -L. -lsplinter \
|
||||
plugin that fails to load is reported on stderr and skipped; the harness keeps
|
||||
working.
|
||||
|
||||
## Configuration
|
||||
|
||||
In the config file every plugin has its own block (`docs/CONFIG.md`,
|
||||
"Plugins"):
|
||||
|
||||
```
|
||||
plugin mine {
|
||||
path = ~/my/myplugin.so # omitted: the shipped plugin "mine"
|
||||
depth = 3
|
||||
hosts = [a, b]
|
||||
server a { url = http://a/mcp }
|
||||
}
|
||||
```
|
||||
|
||||
Everything but `path` and `enabled` is the plugin's own, and it reads it
|
||||
through the host by the block's name:
|
||||
|
||||
```c
|
||||
const char *d = sp_host_plugin_config(host, "mine", "depth"); /* "3" */
|
||||
const char *h = sp_host_plugin_config(host, "mine", "hosts"); /* "a,b" */
|
||||
const char *u = sp_host_plugin_config(host, "mine", "server.a.url");
|
||||
```
|
||||
|
||||
A missing key is NULL; the value is a string, parsing is the plugin's job.
|
||||
To see every setting (the servers it was given, say), walk them in file order:
|
||||
|
||||
```c
|
||||
const char *key, *val;
|
||||
size_t i;
|
||||
|
||||
for (i = 0; (val = sp_host_plugin_config_at(host, "mine", i, &key)) != NULL; i++)
|
||||
/* key = "depth", "hosts", "server.a.url", ... */;
|
||||
```
|
||||
|
||||
Both work from `init()` on. The config is read once at start; a value does
|
||||
not change while the plugin runs. The `mcp` plugin is the one exception to
|
||||
the dotted names: its `server NAME { }` blocks become the MCP server list it
|
||||
always read (`sp_host_config()`), so `plugin mcp { server ... }` and the old
|
||||
`mcp NAME { }` block mean the same.
|
||||
|
||||
## What a plugin may do
|
||||
|
||||
| hook | thread | may block | may touch curses |
|
||||
@@ -40,7 +80,7 @@ falls back to the one-shot call.
|
||||
`tick()` runs on a thread the host creates and can stop. It may read files,
|
||||
wait on sockets, sleep. It must not assume it is the only thread.
|
||||
|
||||
Anything that should appear in the sidebar is published:
|
||||
What the plugin wants to say is published as a widget line:
|
||||
|
||||
```c
|
||||
sp_host_widget_text(host, "mywidget", "42 items");
|
||||
@@ -62,9 +102,10 @@ static const struct sp_widget w = {
|
||||
sp_host_add_widget(host, &w);
|
||||
```
|
||||
|
||||
The sidebar lists one line per widget, `name: text`. `draw()` exists for
|
||||
widgets that need more than one line; it runs on the UI thread and must be
|
||||
fast, because it holds up every other pane while it runs.
|
||||
The sidebar lists one line per widget, `name: text`; `/widgets` prints the same
|
||||
lines into the transcript. `draw()` exists for widgets that need more than one
|
||||
line; it runs on the UI thread and must be fast, because it holds up the rest of
|
||||
the screen while it runs.
|
||||
|
||||
## Threads, honestly
|
||||
|
||||
@@ -86,14 +127,23 @@ A plugin registers tools with the same authorization classes the builtins use:
|
||||
struct sp_tool t = { 0 };
|
||||
t.name = "clock";
|
||||
t.description = "Report the local date and time.";
|
||||
/*
|
||||
* parameters is a JSON schema, and its root must say "type":"object".
|
||||
* A bare {} is rejected by judges that validate the tool list (Claude did,
|
||||
* and the whole request failed), even when the model itself would accept it.
|
||||
*/
|
||||
t.params = "{\"type\":\"object\",\"properties\":{}}";
|
||||
t.auth = SP_AUTH_READ;
|
||||
t.run = clock_tool;
|
||||
sp_host_add_tool(host, &t);
|
||||
```
|
||||
|
||||
`SP_AUTH_READ` runs. `SP_AUTH_MUTATE` and `SP_AUTH_DESTRUCTIVE` ask the
|
||||
operator unless the harness was started with `--autonomous`. The loop decides
|
||||
this, not the plugin.
|
||||
`SP_AUTH_READ`, `SP_AUTH_MUTATE` and `SP_AUTH_DESTRUCTIVE` all run: splinter
|
||||
does not put its own question in front of a tool call. What an agent may reach
|
||||
is what the operator registered - the profile's allow/deny list, a plugin's
|
||||
own gate (`sp_host_add_gate`), the file tools' root. A plugin that wants a
|
||||
decision can ask for one through the ack files (`ack.h`, as `plugins/kids`
|
||||
does); that is the plugin's business, not the loop's.
|
||||
|
||||
## Compaction
|
||||
|
||||
@@ -115,16 +165,35 @@ not take the conversation with it.
|
||||
Two come with the tree.
|
||||
|
||||
**lcm** — deterministic, lossy, honest. If the conversation does not fit the
|
||||
budget, it keeps the leading system message and the last six messages, and puts
|
||||
one system message in between that says how many messages went, of which roles,
|
||||
and quotes the head of the oldest dropped turn. No second model is called, so a
|
||||
run stays reproducible and costs nothing extra.
|
||||
budget, it first cuts **old tool outputs** to a head and a tail with a marker
|
||||
in between (their middle stays in the session log, where the `recall` tool
|
||||
finds it); only when that is not enough does it keep the leading system message
|
||||
and the last six messages and put one system message in between that says how
|
||||
many messages went, of which roles, and quotes the head of the oldest dropped
|
||||
turn. No second model is called, so a run stays reproducible and costs nothing
|
||||
extra. `plugin lcm { keep = 6; tool_trim = 8192 }` sets the verbatim tail and
|
||||
the byte cap per old observation; `tool_trim = 0` turns the trim off.
|
||||
|
||||
What it did is visible while it runs - the counters are the compactor's own, not
|
||||
a second estimate:
|
||||
|
||||
```
|
||||
lcm: ctx 12.3k/32k
|
||||
compacted 3 cut 41 msgs
|
||||
last 60->22 msgs 180.2k->44.1k B
|
||||
tools trimmed 7
|
||||
```
|
||||
|
||||
The first line is the context the last request carried against the window; then
|
||||
the number of compactions and how many messages they removed in total; how the
|
||||
last cut looked in messages and bytes; and how many old tool outputs were
|
||||
trimmed. `/status` gets one segment, `compact 3`, next to the other meters.
|
||||
|
||||
**cps** — continuous parallel compression. The expensive part (deciding what
|
||||
would go) is computed on the widget's worker thread from an *index* of the
|
||||
conversation — role, size, and 64 bytes of head per message, copied under a
|
||||
mutex. The worker never touches the conversation itself. When the budget is
|
||||
hit, the main thread splices an already-prepared plan in one pass. Its sidebar
|
||||
hit, the main thread splices an already-prepared plan in one pass. Its widget
|
||||
line shows `idle (applied N, prepared M)` or `plan ready: cut X/Y, A -> B B`,
|
||||
so "continuous" is visible rather than claimed.
|
||||
|
||||
@@ -156,7 +225,9 @@ SPLINTER_CLI_CMD="opencode run" ./splinter -p "hi" --plugin plugins/cli/cli.so
|
||||
- `SPLINTER_CLI_CMD` — the program, default `claude -p`
|
||||
- `SPLINTER_CLI_FULL=1` — send the whole transcript instead of the last user
|
||||
message (for programs that keep no history of their own)
|
||||
- `SPLINTER_CLI_TIMEOUT` — seconds, default 1800 (or `cli_timeout` in the config)
|
||||
- `SPLINTER_CLI_TIMEOUT` — seconds of silence before the program is killed,
|
||||
default 1800 (or `cli_timeout` in the config); output on stdout or stderr
|
||||
resets the window, so a long answer that keeps printing is not cut off
|
||||
- `SPLINTER_CLI_CMD` may include `{file}` (prompt file path) or `{prompt}` (shell-quoted prompt); without a placeholder the prompt is passed on stdin
|
||||
|
||||
The command comes from the operator's environment and runs through `/bin/sh -c`;
|
||||
@@ -174,26 +245,150 @@ the table.
|
||||
/goal splinter zu einem agent-harness machen, das hermes ersetzt
|
||||
```
|
||||
|
||||
`/goal <text>` sets it, `/goal` shows it, `/recap` forces a reminder into the
|
||||
next turn. That works in the TUI and in a one-shot run
|
||||
(`splinter -p "/goal ..."`); it is deliberately not a config key, because a goal
|
||||
belongs to the conversation in front of you and not to a file that outlives it.
|
||||
`SPLINTER_FOCUS_EVERY` sets the interval (default 5 turns).
|
||||
`/goal <text>` sets it and starts a turn: the prompt asks the model for a short
|
||||
recap (3-5 bullets, what must be true at the end, the first steps, open
|
||||
questions). The plugin remembers that answer and injects it every seventh turn
|
||||
— never twice in one turn, nothing at all when no goal is set. `/goal` alone
|
||||
shows the goal. There is no `/recap`: recapping is what a goal does. The goal is
|
||||
stored in the session's `.meta`, so a resume, `/open` or `/continue` finds it
|
||||
again. `/continue` starts a turn that picks the goal up where the session
|
||||
stopped. That works in the TUI and in a one-shot run
|
||||
(`splinter -p "/goal ..."`); it is not a config key, because a goal belongs to
|
||||
the conversation in front of you. `SPLINTER_FOCUS_EVERY` sets the interval
|
||||
(default 7 turns).
|
||||
|
||||
It registers as a compactor and, on every fifth turn, inserts one system
|
||||
message — *before* the newest user message, so the model reads goal then request
|
||||
and answers the request. Never twice in one turn, and nothing at all when no
|
||||
goal is set. The sidebar shows the goal and how many reminders went out.
|
||||
The goal is in the prompt from the first request, not from the seventh turn:
|
||||
when a goal exists and has not been announced in this session yet (config,
|
||||
resume, planner), the compactor inserts it once, before the newest user
|
||||
message.
|
||||
|
||||
A goal ends. Every text that carries the goal — the first announcement, the
|
||||
recap prompt, `/continue`, the periodic reminder — tells the model to end its
|
||||
final answer with the single line `GOAL_COMPLETE` when the goal is fully
|
||||
achieved. The plugin then records `goal_state=succeeded` beside the goal in the
|
||||
session `.meta` (it also watches the session log from its tick, so the state
|
||||
changes without waiting for the next turn), stops reminding, writes one
|
||||
`goal succeeded: …` note into the transcript, and shows `[done]` in the sidebar.
|
||||
Only an answer written after the goal went into a prompt can close it, so an
|
||||
old `GOAL_COMPLETE` cannot mark a goal that was set later. `/goal` reports the
|
||||
state; a new goal opens a new one.
|
||||
|
||||
It registers as a compactor and inserts one system message — *before* the newest
|
||||
user message, so the model reads recap then request and answers the request. If
|
||||
the model has not answered the recap prompt yet, the goal text stands in. Its
|
||||
widget line shows the goal, `[done]` when it is reached, and the warning is
|
||||
never printed twice in one turn.
|
||||
|
||||
It is a reminder, not an instruction: the user can change direction at any
|
||||
time, and the message says so on its face.
|
||||
|
||||
## recap
|
||||
|
||||
`/recap <text>` sets a note that the plugin puts back into the conversation:
|
||||
on the next request, then every N turns (default 5), as a real system message
|
||||
right before the newest user message. It stays in the history, so a long
|
||||
session keeps meeting it.
|
||||
|
||||
```
|
||||
/recap <text> set it (up to 1500 bytes)
|
||||
/recap show it, the interval and how often it was sent
|
||||
/recap every N change the interval; 0 = only once, no repeats
|
||||
/recap off forget it
|
||||
```
|
||||
|
||||
The interval is `plugin recap { every = 5 }`, `SPLINTER_RECAP_EVERY`, or
|
||||
`/recap every N` for the running process. The text is stored per session in
|
||||
`<session dir>/<id>.recap` and comes back on resume. It is not `/goal`: a goal
|
||||
asks the model for its own recap and can end; a recap is the operator's words,
|
||||
verbatim, until `off`.
|
||||
|
||||
## junction
|
||||
|
||||
The fleet router, evaluated from the outside. junction answers `/mcp` with
|
||||
|
||||
```
|
||||
X-Junction-Mcp: 1
|
||||
```
|
||||
|
||||
and that header is the identity: a 200 with the header is junction, a 200
|
||||
without it is "not junction, or a proxy in front of it" — a health check that
|
||||
trusts any answer is wrong exactly when it matters.
|
||||
|
||||
The widget is only what belongs to the model this run is on: its name (from
|
||||
the engine, not from the provider's configured default — `/model` can switch
|
||||
the model without touching the config) and the targets the matching
|
||||
`/status` rule sends it to. Nothing else: a `!` marks a target whose own
|
||||
health probe is failing.
|
||||
|
||||
```
|
||||
junction
|
||||
deepseek-v4.1-flash
|
||||
serving opencode-go1
|
||||
route opencode-go0
|
||||
opencode-go1
|
||||
opencode-go2
|
||||
ollama0-splinter
|
||||
4/4 up
|
||||
```
|
||||
|
||||
`serving` is the `X-Junction-Endpoint` of the **last real answer** - the
|
||||
provider says which upstream actually served it, and the transport publishes
|
||||
it (`sp_host_served_by`). That is not the route: junction may pick another
|
||||
target per request, and a fallback can differ from every rule. `(no request
|
||||
yet)` until the first answer. The route below is what the matching rule would
|
||||
use; the rule is chosen by exact model match, then glob (`*`, `?`), then
|
||||
catch-all, and rules with a `path` describe another route (`/v1/models`). A
|
||||
target whose probe is down gets the `!`.
|
||||
|
||||
Everything else is `/junction`, not the sidebar: uptime, MCP servers, queue,
|
||||
requests, endpoints with p95 and exhausted counts, the model count from
|
||||
`/v1/models`, and **every response header** of every probe grouped by source.
|
||||
That includes `X-Junction-Ms`/`X-Junction-Cache` and the probe's own
|
||||
`X-Junction-Endpoint` (which is `/v1/models` -> `opencode-go`, not the
|
||||
conversation's route). junction accepts `/status`, `/v1/status`, `/queue` and
|
||||
`/v1/queue` as the same route; the plugin remembers which one answered and
|
||||
only tries the whole list when it stops. It does not count a second time.
|
||||
|
||||
That is a widget, a status segment (`junction 20m up`), the tool
|
||||
`junction_status` and `/junction`. The address and the key come from the
|
||||
plugin's own block, else from the `mcp junction` server, else from
|
||||
`SPLINTER_JUNCTION_URL` / `SPLINTER_JUNCTION_TOKEN`. The header is never
|
||||
printed: it carries the key. `interval` (milliseconds, default 5000) sets how
|
||||
often the tick asks; `models_interval` (default 60000) how often the model
|
||||
route is probed, because that one goes upstream and the other two do not.
|
||||
|
||||
## self
|
||||
|
||||
What the session costs the machine, and what its children cost:
|
||||
|
||||
```
|
||||
self
|
||||
84M rss 3.2% cpu
|
||||
18 thr 41 fd
|
||||
kids 3 120M 1.4% cpu
|
||||
io 12M r 300k w
|
||||
```
|
||||
|
||||
The process itself from `/proc/self/status` (VmRSS, Threads), `/proc/self/fd`
|
||||
(count) and `/proc/self/io` (bytes); the children from one pass over
|
||||
`/proc/<pid>/stat`, following the parent chain: `run` calls, MCP server
|
||||
children, delegates, a CLI transport. CPU is the delta between two samples
|
||||
(2 s by default, `interval` in ms), so it says what is happening now; IO is
|
||||
cumulative for the session. `/self` and the `session_usage` tool print the
|
||||
same numbers with the pid and the child count.
|
||||
|
||||
## Zustimmung (ack)
|
||||
|
||||
Ein Werkzeug, das etwas aendert, braucht ein Ja von einem Menschen. Der Mensch
|
||||
kann am Terminal sitzen, am Telefon, oder hinter einem Skript - es koennen
|
||||
Ein Mechanismus, mit dem ein **Plugin** ein Ja von einem Menschen einholt. Der
|
||||
Mensch kann am Terminal sitzen, am Telefon, oder hinter einem Skript - es koennen
|
||||
mehrere Kanaele sein, und die erste Antwort gewinnt.
|
||||
|
||||
splinter selbst fragt nicht: seine eigenen Werkzeuge laufen, sobald die Registry
|
||||
sie anbietet (siehe `docs/TOOL-ROOT.md`). Wer eine Rueckfrage will, baut sie in
|
||||
sein Plugin - `plugins/kids` tut das und fragt sein Elternprogramm ueber diesen
|
||||
Weg. `--ack` und `--ack-list` sind entsprechend Plugin-Werkzeuge, keine
|
||||
Freigabe fuer splinters Tools.
|
||||
|
||||
Der Mechanismus ist zwei Dateien, damit nicht zwei Prozesse um dieselben
|
||||
Telegram-Updates streiten:
|
||||
|
||||
@@ -219,13 +414,15 @@ Antworten, aus jedem Prozess:
|
||||
splinter --ack 482915307 no # no, n, nein - jedes andere Wort ist ein Fehler
|
||||
splinter --ack-list
|
||||
|
||||
Ein Timeout ist ein Nein. Stille ist keine Zustimmung.
|
||||
Fuer ein Plugin, das diesen Weg nutzt, gilt: ein Timeout ist ein Nein, Stille
|
||||
ist keine Zustimmung. splinter erzwingt das nicht - es ist die Regel des
|
||||
Plugins, das fragt.
|
||||
|
||||
Das Telegram-Gateway registriert seine Befehle beim Start: die der geladenen
|
||||
Plugins, die Programme in `~/.splinter/commands/` mit gueltigem Telegram-Namen
|
||||
und `/start`, `/help`, `/interview`; `/help` listet sie im Chat. `/interview`
|
||||
stellt dieselben sechs Fragen wie `splinter --interview` im Chat, `/skip`
|
||||
ueberspringt eine, `/cancel` bricht ab. Die Anfrage selbst legt es als
|
||||
startet dasselbe modellgetriebene Interview wie `splinter --interview` im Chat;
|
||||
die Zusammenfassung landet in `~/.splinter/USER.txt`, `/new` beendet es. Die Anfrage selbst legt es als
|
||||
Nachricht mit **Ja/Nein-Knoepfen** vor.
|
||||
Der Knopf ist ein `callback_query`, kein Text: das Gateway prueft denselben
|
||||
Allow-List-Eintrag, antwortet dem Knopf, entfernt die Knoepfe und legt die
|
||||
@@ -245,16 +442,6 @@ Regeln, die der Code durchsetzt:
|
||||
selben Konto vom Zustimmen abhalten will, braucht eine eigene uid fuer splinter
|
||||
(oder einen Kanal, dessen Antwort der lokale Benutzer nicht schreiben kann).
|
||||
|
||||
## planner
|
||||
|
||||
A plan for the session, not a background job. The list lives in
|
||||
`<session>/plan_tasks.json`; the model can add and update tasks, and `/tasks`
|
||||
shows them, picks the active one and moves it between `todo`, `doing`, `done`,
|
||||
`blocked` and `waiting_quota` (any other state is refused). The file is read and
|
||||
written under one lock on every operation and replaced atomically. The focus plugin's `/goal` is the short reminder;
|
||||
planner is the list behind it. It is a different store from the `tasks` plugin,
|
||||
which owns shell commands with a process and a clock.
|
||||
|
||||
## provider
|
||||
|
||||
Per-`(provider, key)` quota and usage, shared by every splinter that uses the
|
||||
@@ -273,23 +460,6 @@ delegation job that is due (`waiting_quota`, `waiting_poll` or `queued` with
|
||||
delegate job tools, "quota is back in three days" becomes a scheduled retry
|
||||
instead of a lost task.
|
||||
|
||||
## tmux
|
||||
|
||||
Drives a program that wants a terminal (a REPL, an installer, another agent's
|
||||
TUI) in a detached tmux session. Tools: `tmux_start` (destructive: it runs a
|
||||
shell command), `tmux_send` (text and/or key names such as `C-c`), `tmux_ask`
|
||||
(send a line, wait until the pane has new output and has been quiet for
|
||||
`quiet_ms`, return the new lines), `tmux_read`, `tmux_capture` and
|
||||
`tmux_status`. `/tmux` has the same operations plus `attach` and `stop`.
|
||||
|
||||
"New" is a diff of two `capture-pane` snapshots kept in memory: it finds the old
|
||||
capture inside the new one and returns what follows. There is no helper process,
|
||||
no pid file and nothing left behind when splinter exits; the target name is the
|
||||
only thing written, to `<session>/tmux_target`, so a resumed session finds its
|
||||
terminal again. Session names and key names are checked so that neither can be
|
||||
read by tmux as an option. The plugin refuses to load when `tmux` is not
|
||||
installed. `tests/test_tmux.c` runs against a real tmux and skips without one.
|
||||
|
||||
## a2a
|
||||
|
||||
Another agent as the backend, over the Agent2Agent protocol. The transport is
|
||||
@@ -368,12 +538,10 @@ written to the session's `inbox/` (0600, 8 MiB cap) and the prompt says
|
||||
`[file <name> at <path> (mime, n bytes)]`, because a text model cannot read a
|
||||
PNG but the agent around it can. The same is true for a binary `url` part.
|
||||
|
||||
A mutating tool that needs approval pauses the task in
|
||||
`TASK_STATE_INPUT_REQUIRED`; the assistant call is already in the context, the
|
||||
tool has not run. Another `SendMessage` with the same `taskId` and a
|
||||
`yes`/`no` answer resumes it (`sp_agent_resume`); `CancelTask` cancels it.
|
||||
`SendStreamingMessage` has nowhere to resume, so it denies mutating tools
|
||||
instead of pausing.
|
||||
A turn runs to its end, tools included: there is no approval pause and no
|
||||
`TASK_STATE_INPUT_REQUIRED`. An A2A caller is not sitting in front of a
|
||||
prompt, so a question would only park a task nobody answers. `CancelTask`
|
||||
still cancels a task that is running.
|
||||
|
||||
`SubscribeToTask` sends the state the task has now (status update with its
|
||||
message) and ends the stream: one request at a time means a task cannot make
|
||||
@@ -381,3 +549,25 @@ progress while a subscription is open, so a live feed would be a promise the
|
||||
server cannot keep. Beyond loopback
|
||||
`SPLINTER_A2A_SERVER_TOKEN` is required and checked as
|
||||
`Authorization: Bearer ...`; there is no TLS.
|
||||
|
||||
## session
|
||||
|
||||
`session_search` and `session_list` read the logs of earlier sessions that
|
||||
**ran in this working directory**. The cwd recorded in each session's meta
|
||||
sidecar decides that: a session from another folder is left out (a search that
|
||||
wanders answers a question nobody asked), and a session without that record is
|
||||
skipped. Both are read-only; the running session is left out too (it is
|
||||
already in the prompt), unless a call names it with `session=` -- and even
|
||||
then it must belong to this folder.
|
||||
|
||||
`session_search { query, limit?, days?, session? }` walks the sessions newest
|
||||
first, one `getline` per JSONL record, and answers one line per hit:
|
||||
`2026-11-18 20:01 sess-... "title" user: ...text around the match...`.
|
||||
`limit` defaults to 10 (max 50), `days` keeps only recently changed sessions,
|
||||
and the whole answer stops at 12 KB; a hidden remainder says so. `session_list`
|
||||
shows date, id, size and title for the same set, with `(current)` on the open
|
||||
one.
|
||||
|
||||
The engine appends a paragraph to the system prompt when the working directory
|
||||
has earlier sessions: how many, the newest, and that `session_search` /
|
||||
`session_list` read them. No history, no paragraph.
|
||||
@@ -0,0 +1,319 @@
|
||||
# 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, the model's
|
||||
`ask` question, 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. If its connection drops, `--attach`
|
||||
reconnects and asks for the session it was on with `open`; a GUI can do the
|
||||
same.
|
||||
|
||||
## 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.
|
||||
|
||||
### Why this stays one JSON object per line
|
||||
|
||||
It was considered for replacement and kept. The two failures that made the
|
||||
framing look guilty were not on this socket: a model sent two tool-argument
|
||||
objects in one string and `mcp_parse()` silently took the first (fixed with
|
||||
`mcp_parse_exact()`), and a gateway put HTTP chunk framing inside an SSE body
|
||||
(fixed at the gateway). A second, non-JSON protocol would have hidden neither.
|
||||
The line format is also what lets `splinterctl`, `docs/proto-example.py` and a
|
||||
GUI be a client in a few dozen lines.
|
||||
|
||||
One client at a time. The server holds one active engine, so one conversation
|
||||
runs; `open` switches it, it does not run two. A second writer on the same
|
||||
engine would be a second history. When a client disconnects in the middle of a turn, the server
|
||||
cancels the turn (an `ask` question nobody can answer would otherwise park
|
||||
the engine forever) and accepts the next client.
|
||||
|
||||
A client that arrives while another is attached is told so at once: it is
|
||||
accepted only to be sent
|
||||
`{"ev":"error","reason":"attached","text":"another client is attached: ..."}`
|
||||
and then closed, and `splinterctl` exits non-zero. The server answers the door
|
||||
even in the middle of a turn, so a second `splinterctl --cmd /status` gets that
|
||||
error instead of hanging in the listen backlog with no output at all - which
|
||||
reads as a broken engine. A client that hears no greeting at all (an older
|
||||
server) gives up after five seconds with a message rather than waiting for an
|
||||
outer `timeout`.
|
||||
|
||||
## 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":"ask","text":"which?",...}| (only when the model asks)
|
||||
| {"cmd":"answer","text":"blue"} |
|
||||
|<-- {"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":"answer","text":"..."}`
|
||||
|
||||
Answer the open question from the `ask` tool. The text is the answer; an empty
|
||||
string counts as "no answer" and the model is told so. A client that answers
|
||||
nothing leaves the turn parked for the engine's wait, then the tool reports
|
||||
that nobody answered — it does not hang forever.
|
||||
|
||||
### `{"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.
|
||||
|
||||
### `"tag"`: which answer belongs to which request
|
||||
|
||||
A request may carry `"tag":N` (any positive number). The server echoes it in
|
||||
the event that answers it — `sessions`, `sources`, `models` — and
|
||||
the client drops an event whose tag is not the one it is waiting for. Without
|
||||
it a listing was matched by kind alone, so a server slower than the client's
|
||||
5 s timeout left its answer in the socket and the next request of that kind
|
||||
read it as its own. A request without a tag gets an answer without one, as
|
||||
before.
|
||||
|
||||
### `{"cmd":"sessions"}`
|
||||
|
||||
List the sessions in the server's session directory, newest first:
|
||||
`"ev":"sessions"`, `"items":[{"id","title","mtime","bytes","current"}]`.
|
||||
`title` is the first user line or what `/rename` set (empty when there is no
|
||||
message yet), `current` marks the session the connection is on.
|
||||
|
||||
### `{"cmd":"sources"}`
|
||||
|
||||
What the `/sessions` picker offers as a first step: `"ev":"sources"`,
|
||||
`"items":[{"name","count"}]` — `splinter` first (this session directory), then
|
||||
every foreign store that has sessions. A store the plugin cannot read is left
|
||||
out instead of shown empty.
|
||||
|
||||
### `{"cmd":"sessions","source":"NAME"}`
|
||||
|
||||
The second step: the sessions of one source, same `"ev":"sessions"` shape as
|
||||
above. For `splinter` the rows are plain session ids. For `claude`, `hermes`
|
||||
and `opencode` a row's `id` is `"<source>:<id>"`, which is exactly what
|
||||
`{"cmd":"open","session":"claude:<id>"}` takes to import that session and
|
||||
continue it here.
|
||||
|
||||
### `{"cmd":"open","session":"ID"}`
|
||||
|
||||
Switch this connection to another session. `"new"` starts a fresh one,
|
||||
`"last"` the newest, an id continues that file. The server sends `ready`,
|
||||
`state`, `commands`, `history` and finally `"ev":"opened"` with the new
|
||||
`session` and `dir`; the old engine is closed first, so plugins are not doubled.
|
||||
While a turn runs the command is refused. An unknown id is an error and the
|
||||
connection stays on its session.
|
||||
|
||||
`{"cmd":"input","line":"/rename [ID] TITLE"}` names the current session (or the
|
||||
one named by ID), and `{"cmd":"input","line":"/rm ID"}` removes a session that is
|
||||
not the open one: its JSONL, sidecars and `<dir>/logs/<id>` directory. Both
|
||||
answer with a `reply` event.
|
||||
|
||||
### `{"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":"models"}`
|
||||
|
||||
The list `/model` takes, for a picker: `"ev":"models"` with
|
||||
`"items":[{"sel":"junction/qwen3.6-35b","label":"junction/qwen3.6-35b","current":true},...]`.
|
||||
`sel` is what goes after `/model `, `label` is what the picker shows, and
|
||||
`current` marks the model the run is on. Without an argument it is the
|
||||
configuration (providers, then pools), so it answers at once. With
|
||||
`{"cmd":"models","probe":"true"}` the endpoint this session is on is also asked
|
||||
`/v1/models` and its models are appended, as `provider/model` selectors; that
|
||||
is a network call and may take a few seconds. `/model <selector>` through
|
||||
`input` does the switch and stores the choice in the session.
|
||||
|
||||
The answer carries the request's `tag` like the other listings, so a probe that
|
||||
took longer than the client's timeout cannot be read as the answer to the next
|
||||
`models` request: `/model` would then draw the endpoint's models where the
|
||||
configuration was asked for.
|
||||
|
||||
### `{"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`, `ctx_used`, `ctx_max`, `cached`, `turn_tokens_out`, `steps`, `calls`, `compactions`, `last_ms`, `last_steps`, `last_calls`, `busy`, `waiting`, `asking`, `quit` | everything a sidebar or the status bar 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 |
|
||||
| `ask` | `text`, `options[]` | the `ask` tool's question; answer with `answer` |
|
||||
| `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 |
|
||||
| `sessions` | `items[]` | the sessions, with id/title/mtime/bytes/current |
|
||||
| `opened` | `session`, `dir` | the switch is complete |
|
||||
| `history` | `truncated`, `items[]` | the transcript so far (role/text) |
|
||||
| `pong` | — | answer to `ping` |
|
||||
| `quit` | — | the engine is shutting down |
|
||||
|
||||
`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"] == "ask":
|
||||
send({"cmd": "answer", "text": "blue"})
|
||||
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_answer(eng, "blue"); /* answer an `ask` question */
|
||||
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.
|
||||
+56
-9
@@ -12,9 +12,58 @@ Stream.
|
||||
|
||||
## Erledigt
|
||||
|
||||
- **Echtes Gateway-Streaming 2026-11-16**: `stream:true` nutzt den
|
||||
Streaming-Transport des Providers und schickt Text-Deltas sofort als
|
||||
`chat.completion.chunk`; Caller-Tool-Calls kommen als ein Delta am Ende des
|
||||
Schritts, `stream_options.include_usage` liefert die summierten Token-Zahlen
|
||||
vor `[DONE]`. Fehler nach dem ersten Byte kommen als SSE-`error`; SIGPIPE ist
|
||||
ignoriert. Test: `tests/stream_probe.py` prueft, dass die Chunks waehrend des
|
||||
Upstream-Streams ankommen (nicht als ein Block am Ende).
|
||||
- **Session-Titel 2026-11-16**: `.meta` traegt `title` (erste User-Zeile,
|
||||
ueberschreibbar per `/rename [ID] TITEL`); `sessions` liefert ihn als
|
||||
`title`, `/sessions` zeigt ihn. `/rm ID` entfernt JSONL, Sidecars und
|
||||
`logs/<id>` und verweigert die offene Session. Tests: `test_session`,
|
||||
`test_protocol.sh`, `test_ui.sh`.
|
||||
- **Nachtrag 2026-11-16**: Session-Wechsel auch im lokalen UI
|
||||
(`sp_engine_switch`, `/sessions` + `/open` ohne `--attach`), Gateway reicht
|
||||
`temperature`/`top_p`/`max_tokens` durch, liest chunked Bodies und gibt bei
|
||||
gemischten Antworten die Caller-Calls zurueck (lokale Beobachtungen im
|
||||
Content, auch im SSE-Delta); ein beim Reconnect verschwundener Session-Name
|
||||
wird gemeldet statt still ersetzt; Ring-Transports werden disposed;
|
||||
`/status` ist uebersetzt; `docs/splinter.1` ist mandoc-sauber.
|
||||
- **Gateway, Sessions, Reconnect**: `splinter --openai-listen` ist ein
|
||||
OpenAI-kompatibler Endpunkt; lokale Tools heissen `gw_*` und laufen auf dem
|
||||
Splinter-Host, die Tools des aufrufenden Harness werden als tool_calls
|
||||
zurueckgegeben und dort ausgefuehrt (`docs/GATEWAY.md`,
|
||||
`tests/test_gateway_openai.sh`). `--serve` haelt mehrere Sessions
|
||||
(`sessions`/`open`, `/sessions`/`/open` im UI), `--attach` verbindet sich
|
||||
nach einem Serverausfall selbst neu und holt die alte Session per id
|
||||
(`tests/test_protocol.sh`, `tests/test_reconnect.sh`).
|
||||
- **Review-Nachlauf 2026-11-16**: 8-KiB-Zeilen in Server/Client/attach durch
|
||||
dynamische Puffer ersetzt (9-KB-Prompt, 8-KB-Shell-Eintrag), `turn` beendet
|
||||
nicht mehr das busy-Fenster (Steer-Rest), Curses finalisiert jeden Turn
|
||||
einzeln, Engine-Steer-Rest wird per `sp_engine_take_steer` uebernommen,
|
||||
Engine-Statistik als Lock-Snapshot (kein Datenrace), Profil wird in
|
||||
`<session>.agent` gemerkt (--resume startet wieder in plan), `/new` oeffnet
|
||||
das Log neu und vergibt eindeutige Ids, Shell-Ausgabe 64 KiB mit Marker,
|
||||
Socket-Probe/Inode/CLOEXEC/SO_SNDTIMEO, Protokoll v2 mit `history` (attach
|
||||
zeigt das bisherige Transkript), `same_user` auch fuer BSD, Exit 2 fuer
|
||||
Konfigurationsfehler, `agent_switch` meldet Aktivierungsfehler, i18n-Checker
|
||||
scannt src/backend+frontend. `tests/test_protocol.sh` und
|
||||
`tests/test_attach.sh` decken die neuen Pfade ab; `make check` gruen.
|
||||
- **Backend und Frontends getrennt**: `src/backend/` traegt Engine, Loop,
|
||||
Tools, Session, Config und Plugins; `src/frontend/curses.c` zeichnet nur
|
||||
noch und liest Tasten, `src/frontend/protocol.c` gibt dieselben Events als
|
||||
JSON-Zeilen auf einem Unix-Socket aus, `src/frontend/client.c` ist der
|
||||
Referenz-Client (`splinterctl`). Die C-Grenze ist
|
||||
`include/splinter_engine.h`; das Format steht in `docs/PROTOCOL.md`, die
|
||||
Aufteilung in `docs/FRONTENDS.md`. Ein GUI-Client kann damit in jeder
|
||||
Sprache gegen `splinter --serve` gebaut werden. Belege:
|
||||
`tests/test_engine` (Event-Reihenfolge eines Turns) und
|
||||
`tests/test_protocol.sh` (Socket, Freigabe, Kommandos, quit).
|
||||
- Werkzeuge: read, write, edit, search, list, run, websearch, webfetch,
|
||||
folder_history, delegate (plus parallel/list/submit/jobs/result/due/retry),
|
||||
skill_search/skill_load, memory_search/memory_add, echo, clock
|
||||
skill_search/skill_load, echo, clock
|
||||
- Freigabe im TUI (Condition Variable), Diff-Anzeige, Ctrl-C killt curl
|
||||
- Session-Resume, MCP-Client und -Server, Exit-Ring, Delegation mit Modellwahl
|
||||
- Gateway (Telegram) mit Typing-Indicator und Slash-Commands
|
||||
@@ -22,8 +71,6 @@ Stream.
|
||||
- Slash-Programme: `~/.splinter/commands/<name>`, Ausgabe geht ans Modell
|
||||
- **Skills**: `~/.splinter/skills/` + `skills_dir`, `skill_search`/`skill_load`,
|
||||
kein Vorladen (`test_skills`)
|
||||
- **Memory**: mem0-REST, `user_id` aus dem laufenden Prozess, pro User getrennt
|
||||
(`test_memory`)
|
||||
- **Streaming im Gateway**: eigener Callback, damit auch SSE-only-Provider gehen
|
||||
- **Remote/Jumphost**: `host=` schickt den ganzen Aufruf über ssh; belegt in
|
||||
`README.md` (olivia, Provider nur über WireGuard erreichbar)
|
||||
@@ -36,8 +83,9 @@ Stream.
|
||||
(`test_gateway.sh`, `test_ui.sh`); `/connect` auch im TUI
|
||||
- **Modelle wechseln und Provider anlegen**: `/model` liest die konfigurierten
|
||||
Modelle (Haupt-Endpoint, Delegates, Exits), haengt den Transport um, merkt
|
||||
die Wahl in `90-model.conf` und fragt per `/model probe` die Endpoints nach
|
||||
`/v1/models`; das TUI kann dasselbe. `/connect` schreibt eine validierte
|
||||
die Wahl in `<session>.model` und fragt per `/model probe` die Endpoints nach
|
||||
`/v1/models`; das TUI zeigt im Picker auch die Modelle des Endpoints, auf dem
|
||||
die Sitzung gerade laeuft. `/connect` schreibt eine validierte
|
||||
`delegate`-Zeile in den Drop-in neben der benutzten Konfiguration, prueft sie
|
||||
mit einem Test-Turn und registriert sie im laufenden Prozess
|
||||
(`test_providers`, `test_gateway.sh`, `test_ui.sh`)
|
||||
@@ -56,7 +104,6 @@ Stream.
|
||||
ohne Generator; Zahlen darin sind Stand 2026-11-11
|
||||
- **Letzter Delegate-Fehler**: die letzten 400 Bytes des Kindes stehen im Fehler,
|
||||
ein Limit bencht den Delegate und der nächste übernimmt (`test_delegate`)
|
||||
- **A2A INPUT_REQUIRED**: ein mutierendes Werkzeug pausiert (`sp_agent_run`
|
||||
liefert 2), `SendMessage` mit `taskId` und `yes`/`no` setzt per
|
||||
`sp_agent_resume` fort; `CancelTask` bricht ab (`test_pause`,
|
||||
`test_a2a_input.sh`)
|
||||
- **A2A ohne Rueckfrage**: Werkzeuge laufen, `CancelTask` bricht ab; den
|
||||
frueheren `INPUT_REQUIRED`-Pause-Pfad gibt es nicht mehr, `test_pause` und
|
||||
`test_a2a_input.sh` halten das neue Verhalten fest
|
||||
@@ -0,0 +1,40 @@
|
||||
# The tool root: what it is and what it is not
|
||||
|
||||
The file tools (`read`, `write`, `edit`, `search`, `list`) act with the rights of
|
||||
the splinter process. Without a boundary, a model with mutate rights - or a
|
||||
prompt-injected one - can write `~/.ssh/authorized_keys`, `~/.splinter/splinter.conf`
|
||||
(which names the plugins the harness loads), `~/.bashrc`. The authorization
|
||||
classes say *whether* a tool may run, never *where*.
|
||||
|
||||
`tools_root` in `core { }` closes that:
|
||||
|
||||
```
|
||||
core {
|
||||
tools_root = ~/src # empty (the default) = no boundary
|
||||
}
|
||||
```
|
||||
|
||||
Rules that make it hold:
|
||||
|
||||
- **Resolve before deciding, then use the resolved path.** A check on one string
|
||||
and a write to another is the whole class of bug this exists to prevent.
|
||||
`realpath()` for existing paths; `resolve_target()` for a path that does not
|
||||
exist yet, so a *dangling* symlink inside the root cannot be followed out of it
|
||||
by the write that creates the target.
|
||||
- **Recursion needs the same check as the argument.** `search` walks
|
||||
directories; `stat()` follows a directory symlink. Every entry is resolved
|
||||
before it is opened, otherwise a link inside the root is a door.
|
||||
- **The root is resolved once at startup.** A symlinked root would make a later
|
||||
comparison lie, and a root that does not exist is refused at startup with the
|
||||
path in the message instead of silently matching nothing.
|
||||
- **`run` is not fenced and cannot be.** A shell opens any path it likes. It
|
||||
starts in the root (convenience), and when that `chdir` fails the failure goes
|
||||
into the tool's observation - after the redirection, so the model reads it as
|
||||
part of what happened, not on the operator's terminal.
|
||||
- **Empty means off.** Anything else would be a change to a working setup
|
||||
disguised as a fix.
|
||||
|
||||
Tests that guard it live in `tests/test_builtin.c` (absolute path outside,
|
||||
`../..` walk, symlink inside pointing out, dangling symlink, directory symlink
|
||||
through `search`, and the same tree still readable inside the root). Each was
|
||||
verified by removing the check and watching the test go red.
|
||||
+7
-4
@@ -39,15 +39,18 @@ cd ~/src/projekt
|
||||
splinter # Chat auf "work"
|
||||
```
|
||||
|
||||
1. **Ziel setzen**: `/goal <was am Ende stimmen muss>`. Das Plugin `focus`
|
||||
hält splinter dabei, auch nach Kontext-Verdichtung.
|
||||
1. **Ziel setzen**: `/goal <was am Ende stimmen muss>`. Das setzt das Ziel und
|
||||
startet einen Turn, der einen kurzen Recap schreibt; `focus` injiziert ihn
|
||||
alle sieben Turns, auch nach Kontext-Verdichtung.
|
||||
2. **Projektregeln mitgeben**: splinter liest `AGENTS.md`/`GOAL.md` nicht von
|
||||
allein. Erste Nachricht: "Lies GOAL.md und AGENTS.md, halte dich daran."
|
||||
3. **Arbeiten**: normal beschreiben, was getan werden soll. Umsetzung macht
|
||||
der Pool `work`; Aufgaben mit Wörtern wie *analysiere, entscheide, bewerte,
|
||||
review, Architektur, Ursache* gehen an `claudeapi`.
|
||||
4. **Plan führen**: `/tasks` zeigt den Plan der Sitzung, `/tasks work next`
|
||||
nimmt den nächsten Punkt.
|
||||
4. **Hintergrundarbeit**: `process_start` startet lange Kommandos,
|
||||
`process_list`/`process_result` holen Stand und Ausgabe; `delegate` gibt
|
||||
eine Aufgabe an ein anderes Modell, der `scheduler` wiederholt wartende
|
||||
Jobs nach Quota/`run_after`.
|
||||
5. **Verbrauch sehen**: Statusleiste und `/usage` (Balken je Provider).
|
||||
6. **Beenden/Fortsetzen**: Ctrl-D beendet, `splinter -c` setzt die letzte
|
||||
Sitzung in diesem Verzeichnis fort.
|
||||
|
||||
Executable
+73
@@ -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())
|
||||
+125
-18
@@ -32,14 +32,14 @@ the request fits the configured byte budget; otherwise nothing is sent;
|
||||
.It
|
||||
the tool exists in the registry; otherwise the model is told it does not;
|
||||
.It
|
||||
the tool's authorization class allows the call; a mutating or destructive
|
||||
tool asks the operator unless
|
||||
.Fl -autonomous
|
||||
was given.
|
||||
the tool's authorization class allows the call; the class is metadata (a
|
||||
plugin gate and a profile's
|
||||
.Cm tools:
|
||||
read it), splinter asks nothing in front of a call.
|
||||
.El
|
||||
.Pp
|
||||
A denied tool is not skipped silently: the denial is the observation the model
|
||||
receives.
|
||||
A tool the agent's profile does not allow is not skipped silently: the denial
|
||||
is the observation the model receives.
|
||||
.Sh OPTIONS
|
||||
.Bl -tag -width Ds
|
||||
.It Fl p , -prompt Ar TEXT
|
||||
@@ -85,8 +85,8 @@ One-shot mode: wait for the whole reply instead of printing it as it arrives.
|
||||
A transport that can stream uses its streaming method by default; this asks for
|
||||
its plain send method.
|
||||
.It Fl -autonomous
|
||||
Run mutating tools without asking.
|
||||
Read-only tools never ask.
|
||||
Accepted for compatibility; splinter does not gate its own tools, so it
|
||||
changes nothing.
|
||||
.It Fl -steps Ar N
|
||||
Maximum tool rounds per turn (default 150).
|
||||
.It Fl -max-bytes Ar N
|
||||
@@ -98,18 +98,106 @@ Beyond 127.x it needs
|
||||
.Ev SPLINTER_A2A_SERVER_TOKEN .
|
||||
.It Fl -a2a-listen-port Ar N
|
||||
A2A port (default 8099).
|
||||
A port that is not a number between 1 and 65535 is refused before anything
|
||||
binds.
|
||||
.It Fl -openai-listen Ar IP
|
||||
Serve an OpenAI-compatible endpoint
|
||||
.Pq Pa /v1/chat/completions , /v1/models
|
||||
for another harness.
|
||||
The model sees splinter's local tools as
|
||||
.Pa gw_ Ns Ar name
|
||||
and runs them here; tools the caller sends are returned to the caller as
|
||||
ordinary tool calls and run there.
|
||||
Beyond loopback it needs
|
||||
.Ev SPLINTER_GATEWAY_TOKEN . See
|
||||
.Pa docs/GATEWAY.md .
|
||||
.It Fl -openai-listen-port Ar N
|
||||
Gateway port (default 8097).
|
||||
A port that is not a number between 1 and 65535 is refused before anything
|
||||
binds.
|
||||
.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.
|
||||
The commands
|
||||
.Pa /sessions
|
||||
and
|
||||
.Pa /open Ar ID
|
||||
switch the session.
|
||||
.Pa /sessions
|
||||
shows each session with its title: the first user line, or what
|
||||
.Pa /rename
|
||||
.Pq Op Ar ID
|
||||
.Ar TITLE
|
||||
set.
|
||||
.Pa /rm Ar ID
|
||||
removes a session that is not open.
|
||||
If the server goes away, the screen keeps running, reconnects and asks for the
|
||||
session it was on.
|
||||
.It Fl -socket Ar PATH
|
||||
Socket for
|
||||
.Fl -serve
|
||||
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 ) .
|
||||
.It Fl -session-id Ar ID
|
||||
Session id (default
|
||||
.Pa sess-<time>-<pid> ) .
|
||||
.It Fl -claude , Fl -opencode , Fl -hermes , Fl -from Ns = Ns Ar NAME
|
||||
Continue the newest session that tool ran in this directory, importing it
|
||||
into
|
||||
.Nm
|
||||
on the first start.
|
||||
The session this creates carries its origin in the sidecar
|
||||
.Pq Ql foreign=source:id ,
|
||||
so a later
|
||||
.Fl -claude
|
||||
continues that same session instead of importing the conversation again \(em
|
||||
a second import would replace the file and lose everything done here since.
|
||||
Works without
|
||||
.Fl c ,
|
||||
which only adds the rule that the run may also fall back to a
|
||||
.Nm
|
||||
session; a directory with no session of that source is an error either way.
|
||||
Requires the foreign plugin
|
||||
.Pq Ql plugin foreign
|
||||
or
|
||||
.Fl -plugin .
|
||||
.It Fl V , -version
|
||||
Print the version and exit.
|
||||
Print the version, the build time and the git revision, then exit.
|
||||
The release number stays
|
||||
.Ql 0.1.0 ;
|
||||
the build stamp is what tells two builds apart.
|
||||
.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 \(em streamed text, a step, a tool call, its
|
||||
observation, the model's question and its answer \(em and never calls into a
|
||||
front end.
|
||||
.Pp
|
||||
Between the harness and its transport the protocol is simpler, and not a
|
||||
vendor API:
|
||||
.Bd -literal -offset indent
|
||||
request user <text>
|
||||
request observe <tool> <output>
|
||||
@@ -122,6 +210,31 @@ Messages API (a provider with `kind = anthropic`) or a program's stdout
|
||||
(`--transport cli`) into this shape and back.
|
||||
The harness itself never parses vendor JSON, which is why the loop is testable
|
||||
with no network at all.
|
||||
.Sh FILES
|
||||
.Bl -tag -width Ds
|
||||
.It Pa ~/.splinter/<id>.jsonl
|
||||
Append-only session log, one JSON object per line.
|
||||
A crash can only truncate the tail.
|
||||
.It Pa ~/.splinter/emb/<id>.emb
|
||||
The session's search index, one record per line.
|
||||
It is written by a background thread, so it lags the session log by a moment
|
||||
and is rebuilt by reading the log again if it is missing.
|
||||
.It Pa ~/.splinter/<id>.meta
|
||||
The session's sidecar, one
|
||||
.Sq key=value
|
||||
per line: cwd, created, opened, title, goal, goal_state.
|
||||
A key the core does not own is carried through unchanged, so a plugin can mark
|
||||
a session in the same file
|
||||
.Pq Pa plugins/foreign No writes Sy foreign Ns = Ns Ar source : Ns Ar id .
|
||||
.It Pa ~/.splinter/splinter.conf
|
||||
The configuration.
|
||||
.Fl -init-config
|
||||
writes it as
|
||||
.Pa splinter.conf.example
|
||||
when one is already there, so it never overwrites a file in use.
|
||||
See
|
||||
.Pa docs/CONFIG.md .
|
||||
.El
|
||||
.Sh EXIT STATUS
|
||||
.Bl -tag -width Ds -compact
|
||||
.It 0
|
||||
@@ -134,12 +247,6 @@ Usage or configuration error.
|
||||
.It 3
|
||||
The environment could not be set up, for example the session directory.
|
||||
.El
|
||||
.Sh FILES
|
||||
.Bl -tag -width Ds
|
||||
.It Pa ~/.splinter/<id>.jsonl
|
||||
Append-only session log, one JSON object per line.
|
||||
A crash can only truncate the tail.
|
||||
.El
|
||||
.Sh EXAMPLES
|
||||
Run a scripted turn with no network:
|
||||
.Bd -literal -offset indent
|
||||
@@ -154,10 +261,10 @@ $ splinter -p "list the C files" --endpoint http://127.0.0.1:8080/turn
|
||||
.Ed
|
||||
.Sh SEE ALSO
|
||||
.Xr curl 1
|
||||
.Sh AUTHORS
|
||||
.An Konrad Lother
|
||||
.Sh CAVEATS
|
||||
The transport is responsible for anything the model says; the harness trusts
|
||||
only the registry and the authorization classes.
|
||||
Tool arguments are passed as a single string and are not validated beyond the
|
||||
tool's own checks.
|
||||
.Sh AUTHORS
|
||||
.An Konrad Lother
|
||||
+246
-30
@@ -20,6 +20,14 @@
|
||||
|
||||
#define SP_VERSION "0.1.0"
|
||||
|
||||
/*
|
||||
* The build stamp of the binary. Generated by make into
|
||||
* src/backend/buildinfo.c, so --version says which build is running even
|
||||
* though the release number stays the same.
|
||||
*/
|
||||
extern const char *sp_build_time;
|
||||
extern const char *sp_build_rev;
|
||||
|
||||
/* ------------------------------------------------------------------ buffer */
|
||||
|
||||
struct sp_buf {
|
||||
@@ -51,6 +59,18 @@ enum sp_auth {
|
||||
|
||||
struct sp_tool;
|
||||
|
||||
/*
|
||||
* One choice /model takes, for a picker: the selector to type after /model,
|
||||
* a label to show, and whether it is the current one. SP_MODEL_CHOICES is the
|
||||
* most a caller's array has to hold (main + delegates + exits + pools).
|
||||
*/
|
||||
#define SP_MODEL_CHOICES 96
|
||||
struct sp_model_choice {
|
||||
char sel[320];
|
||||
char label[512];
|
||||
int current;
|
||||
};
|
||||
|
||||
/* Return 0 on success. The observation is written into out. */
|
||||
typedef int (*sp_tool_run)(const char *args_json, struct sp_buf *out,
|
||||
void *ctx);
|
||||
@@ -62,6 +82,12 @@ struct sp_tool {
|
||||
enum sp_auth auth;
|
||||
sp_tool_run run;
|
||||
void *ctx;
|
||||
/*
|
||||
* Called once when the registry is freed. A tool whose name,
|
||||
* description, params or ctx were allocated (an MCP server's tools) sets
|
||||
* it; builtins point at static strings and leave it NULL.
|
||||
*/
|
||||
void (*dispose)(struct sp_tool *);
|
||||
};
|
||||
|
||||
struct sp_registry {
|
||||
@@ -111,7 +137,6 @@ int sp_conv_push(struct sp_conv *, const char *role, const char *name,
|
||||
*/
|
||||
int sp_conv_reset(struct sp_conv *, const char *system_prompt);
|
||||
size_t sp_conv_bytes(const struct sp_conv *);
|
||||
int sp_conv_trim(struct sp_conv *, size_t keep_last);
|
||||
|
||||
/* ------------------------------------------------------------- transport */
|
||||
|
||||
@@ -125,7 +150,35 @@ struct sp_reply {
|
||||
long status;
|
||||
long tokens_in; /* provider-reported, 0 when unknown */
|
||||
long tokens_out;
|
||||
long tokens_cached; /* prompt tokens the provider served
|
||||
* from its cache, 0 unknown */
|
||||
long retry_after_s; /* parsed Retry-After header, 0 unknown */
|
||||
double cost; /* provider-reported cost, USD; 0 unknown */
|
||||
/*
|
||||
* A router may say which upstream answered (junction sends
|
||||
* X-Junction-Endpoint): the model a run is on is not always the
|
||||
* endpoint that serves it. "" when the provider does not say.
|
||||
*/
|
||||
char served_by[128];
|
||||
/*
|
||||
* X-Junction-Judge-Next-*: when and where the next judge step runs.
|
||||
* valid is 0 when the provider sent none (not a judged rule).
|
||||
*/
|
||||
int judge_valid;
|
||||
int judge_next, judge_in, judge_step, judge_every;
|
||||
char judge_target[64];
|
||||
char judge_model[128];
|
||||
char judge_cache[8];
|
||||
char cache_mode[8]; /* X-Junction-Cache: off/5m/1h */
|
||||
|
||||
/*
|
||||
* What the provider says ended the message: "stop", "length",
|
||||
* "tool_calls", "max_tokens", "" when it did not say. A tool call
|
||||
* cut off by the token limit is not the same as a broken one, and
|
||||
* only this field tells them apart.
|
||||
*/
|
||||
char finish[24];
|
||||
|
||||
char *content; /* assistant text, may be "" */
|
||||
struct sp_toolcall *calls;
|
||||
char *calls_json; /* the provider's own tool_calls array */
|
||||
@@ -150,6 +203,22 @@ enum {
|
||||
|
||||
typedef void (*sp_stream_cb)(void *ctx, int kind, const char *text);
|
||||
|
||||
/*
|
||||
* Request shaping a front end may pass through to a provider. The gateway
|
||||
* forwards what the calling harness asked for instead of dropping it; zero
|
||||
* flags mean "not given" and leave the provider default.
|
||||
*/
|
||||
struct sp_gen_opts {
|
||||
int have_temperature;
|
||||
double temperature;
|
||||
int have_top_p;
|
||||
double top_p;
|
||||
int have_max_tokens;
|
||||
long max_tokens;
|
||||
/* streaming: ask the provider for a final usage chunk */
|
||||
int include_usage;
|
||||
};
|
||||
|
||||
struct sp_transport {
|
||||
int (*send)(void *ctx, const struct sp_conv *, struct sp_reply *out,
|
||||
struct sp_buf *err);
|
||||
@@ -160,9 +229,18 @@ struct sp_transport {
|
||||
/* optional: provider/key identity for quota/usage tracking (plugins) */
|
||||
const char *provider; /* e.g. "openai-compat", "ollama", "opencode" */
|
||||
const char *key_id; /* stable key fingerprint/id, never the secret */
|
||||
/*
|
||||
* Optional: free the context a constructor allocated. A transport a
|
||||
* caller builds per request (the OpenAI gateway) uses this; the agent's
|
||||
* own transport lives as long as the agent. Zero for plugin transports,
|
||||
* whose context belongs to the plugin.
|
||||
*/
|
||||
void (*free)(void *ctx);
|
||||
};
|
||||
|
||||
void sp_reply_free(struct sp_reply *);
|
||||
/* free a transport's context (if it owns one) and zero the struct */
|
||||
void sp_transport_dispose(struct sp_transport *);
|
||||
|
||||
/* A deterministic in-process transport: replies are queued FIFO. */
|
||||
struct sp_mock {
|
||||
@@ -190,6 +268,24 @@ int sp_session_open(struct sp_session_info *, const char *dir,
|
||||
const char *id, struct sp_buf *err);
|
||||
int sp_session_append(const struct sp_session_info *, const char *role,
|
||||
const char *text, struct sp_buf *err);
|
||||
/*
|
||||
* A full record. The short form above writes a role and a text; that was enough
|
||||
* to read a session back as a chat log and not enough to resume one: a tool
|
||||
* result without the name of its tool, and an assistant turn without its
|
||||
* tool_calls, cannot be sent to a provider at all. An empty text writes
|
||||
* nothing - a record with no content is not a message, it is noise in the file
|
||||
* that made every resumed session carry blank user turns.
|
||||
*/
|
||||
struct sp_sess_rec {
|
||||
const char *role;
|
||||
const char *text;
|
||||
const char *name; /* tool name, when role is "tool" */
|
||||
const char *call_id; /* tool_call id */
|
||||
const char *calls; /* raw tool_calls JSON of an assistant turn */
|
||||
};
|
||||
|
||||
int sp_session_append_rec(const struct sp_session_info *,
|
||||
const struct sp_sess_rec *, struct sp_buf *err);
|
||||
int sp_session_count(const struct sp_session_info *, size_t *n,
|
||||
struct sp_buf *err);
|
||||
int sp_session_latest(const char *dir, char *id, size_t cap);
|
||||
@@ -199,33 +295,121 @@ int sp_session_last_for(const char *dir, const char *cwd, char *id,
|
||||
/* What happened in a directory: sessions, turns, last question. */
|
||||
int sp_session_folder_history(const char *dir, const char *cwd,
|
||||
unsigned limit, struct sp_buf *out);
|
||||
/*
|
||||
* A paragraph for the system prompt when this working directory has earlier
|
||||
* sessions: how many, the newest, and the tools that read them. Empty output
|
||||
* when there are none.
|
||||
*/
|
||||
int sp_session_folder_note(const char *dir, const char *skip_id,
|
||||
struct sp_buf *out);
|
||||
/* a paragraph naming the working directory as the default task scope */
|
||||
int sp_task_scope_note(struct sp_buf *out);
|
||||
/* the working directory a session was started in (meta sidecar) */
|
||||
int sp_session_cwd(const char *dir, const char *id, char *buf, size_t cap);
|
||||
int sp_session_load(const struct sp_session_info *, struct sp_conv *conv,
|
||||
size_t *loaded, struct sp_buf *err);
|
||||
|
||||
/* one line of a session listing: id, title, mtime, bytes; newest first */
|
||||
struct sp_session_brief {
|
||||
char id[64];
|
||||
char title[96]; /* set title, or the first user line */
|
||||
long mtime;
|
||||
size_t bytes;
|
||||
};
|
||||
/* up to max entries from dir; returns the count (0..max), or -1 */
|
||||
int sp_session_list(const char *dir, struct sp_session_brief *v,
|
||||
size_t max);
|
||||
/* give a session a title (one line, at most 95 bytes) */
|
||||
int sp_session_set_title(const char *dir, const char *id,
|
||||
const char *title, struct sp_buf *err);
|
||||
/* the session's /goal, stored in its meta sidecar so a resume finds it */
|
||||
int sp_session_set_goal(const char *dir, const char *id,
|
||||
const char *goal, struct sp_buf *err);
|
||||
int sp_session_get_goal(const char *dir, const char *id,
|
||||
char *buf, size_t cap);
|
||||
/*
|
||||
* "open" or "succeeded". A model that reached the goal answers GOAL_COMPLETE;
|
||||
* the state is what the sidebar and the status line show afterwards. Setting a
|
||||
* new goal resets it to open.
|
||||
*/
|
||||
int sp_session_set_goal_state(const char *dir, const char *id,
|
||||
const char *state, struct sp_buf *err);
|
||||
int sp_session_get_goal_state(const char *dir, const char *id,
|
||||
char *buf, size_t cap);
|
||||
/*
|
||||
* Remove a session: its log, meta, saved profile and the logs/<id> directory.
|
||||
* The caller must not delete the session its engine has open.
|
||||
*/
|
||||
int sp_session_delete(const char *dir, const char *id, struct sp_buf *err);
|
||||
/*
|
||||
* Where a session came from, when a plugin imported it ("claude:<uuid>" as
|
||||
* written by the foreign plugin). Returns 0 and fills buf, or -1 when the
|
||||
* session is splinter's own. The engine reads this to continue the same
|
||||
* imported session on a later start instead of importing it again.
|
||||
*/
|
||||
int sp_session_foreign(const char *dir, const char *id, char *buf,
|
||||
size_t cap);
|
||||
/*
|
||||
* Remove a session that never got a message: the empty placeholder a run
|
||||
* creates before it knows which session it will continue. A session with even
|
||||
* one record is kept. Returns 0 when it was removed, -1 when it has content or
|
||||
* does not exist.
|
||||
*/
|
||||
int sp_session_remove_if_empty(const char *dir, const char *id);
|
||||
|
||||
/* ----------------------------------------------------------------- agent */
|
||||
|
||||
/*
|
||||
* The question a tool may put to the operator (`ask`). The sizes are fixed
|
||||
* because the pending question lives in the engine struct, which is one per
|
||||
* process: a model that asks a 4 KiB question should have written it in its
|
||||
* answer instead.
|
||||
*/
|
||||
#define SP_ASK_MAX 1024 /* the question's text */
|
||||
#define SP_ASK_OPTIONS 8 /* "which one?" alternatives */
|
||||
#define SP_ASK_OPT_LEN 96
|
||||
/*
|
||||
* How long the `ask` tool waits for an answer, when nothing else says. Long
|
||||
* enough that a person can read the question and think, short enough that a
|
||||
* turn whose front end does not know the question (an old client, a script)
|
||||
* comes back with "nobody answered" instead of hanging until somebody kills
|
||||
* it. Overridden by $SPLINTER_ASK_TIMEOUT, then by `ask_timeout` in the
|
||||
* config; see sp_ask_wait_s(). No upper bound: how long a turn may wait is
|
||||
* the operator's call, not the program's.
|
||||
*/
|
||||
#define SP_ASK_WAIT_S 900
|
||||
int sp_ask_wait_s(void);
|
||||
|
||||
struct sp_agent_config {
|
||||
size_t max_steps; /* tool rounds per turn */
|
||||
size_t max_bytes; /* request budget */
|
||||
/*
|
||||
* Compaction by tokens: past `compact_threshold` the next request is
|
||||
* compacted to `compact_target` (both in tokens, 0 = off). The byte
|
||||
* budget stays the hard ceiling.
|
||||
*/
|
||||
size_t compact_threshold;
|
||||
size_t compact_target;
|
||||
const char *system_prompt;
|
||||
int autonomous; /* 1: run mutate tools without asking */
|
||||
FILE *approval_in; /* NULL with !autonomous means deny */
|
||||
FILE *approval_out;
|
||||
/*
|
||||
* UI path for approval: when set, it is asked instead of the streams, so a
|
||||
* curses program can put the question on the screen instead of reading
|
||||
* stdin behind its own back. Returns 1 to allow, 0 to deny.
|
||||
* Kept so an existing config or profile still parses; splinter does not
|
||||
* gate its own tools, so the value changes nothing. A tool the registry
|
||||
* offers runs.
|
||||
*/
|
||||
int (*approve)(void *ctx, const char *name, int auth,
|
||||
const char *args);
|
||||
void *approve_ctx;
|
||||
int autonomous;
|
||||
/*
|
||||
* Nonzero: 'approve' is itself the channel (the Telegram gateway asks in
|
||||
* its own chat) and is asked directly. Otherwise the ack mechanism goes
|
||||
* first when SPLINTER_ACK_CHANNELS is set - which in the gateway meant
|
||||
* waiting for an answer that only the blocked gateway could read.
|
||||
* A question the `ask` tool puts to the operator. `opts` holds up to
|
||||
* `nopts` suggested answers (may be 0) and the callback writes the
|
||||
* answer into `answer` (cap bytes). Returns 0 on an answer, -1 when
|
||||
* there is nobody to ask -- the tool then says so in its observation
|
||||
* instead of hanging. NULL disables the tool's asking; splinter does
|
||||
* not ask anything on its own, so a front end that cannot reach a
|
||||
* person simply leaves this unset.
|
||||
*/
|
||||
int approve_is_channel;
|
||||
int (*ask)(void *ctx, const char *text,
|
||||
const char (*opts)[SP_ASK_OPT_LEN], size_t nopts,
|
||||
char *answer, size_t cap);
|
||||
void *ask_ctx;
|
||||
|
||||
/*
|
||||
* Steering: while a turn runs, the operator may type. The UI cannot
|
||||
@@ -246,6 +430,14 @@ struct sp_agent_config {
|
||||
const char *observation);
|
||||
void *tool_end_ctx;
|
||||
|
||||
/*
|
||||
* A status line the operator should see while a request waits or is
|
||||
* retried; "" clears it. The engine turns it into SP_EV_NOTE, so the
|
||||
* screen can say "retrying in 5 s" instead of looking hung.
|
||||
*/
|
||||
void (*note)(void *ctx, const char *text);
|
||||
void *note_ctx;
|
||||
|
||||
/* Called when the conversation was compacted to fit the budget. */
|
||||
void (*on_compact)(void *ctx, size_t before, size_t after,
|
||||
size_t msgs_before, size_t msgs_after);
|
||||
@@ -271,6 +463,10 @@ struct sp_agent_stats {
|
||||
size_t steps;
|
||||
size_t tokens_in;
|
||||
size_t tokens_out;
|
||||
size_t tokens_cached; /* prompt tokens served from cache, session */
|
||||
double cost; /* provider-reported, USD */
|
||||
size_t last_in; /* the last request's prompt, for the meter */
|
||||
size_t last_cached; /* of which the provider had cached */
|
||||
size_t compactions;
|
||||
size_t tool_calls;
|
||||
size_t denied;
|
||||
@@ -303,26 +499,13 @@ struct sp_agent {
|
||||
struct sp_session_info *sess;
|
||||
struct sp_conv *conv; /* optional: history lives here */
|
||||
struct sp_agent_stats stats;
|
||||
/*
|
||||
* A turn that stopped before a tool ran because a person has to decide.
|
||||
* The assistant message with the calls is already in the conversation;
|
||||
* the calls from pending_from on are still unobserved.
|
||||
*/
|
||||
struct sp_reply pending;
|
||||
size_t pending_from;
|
||||
int has_pending;
|
||||
};
|
||||
|
||||
#define SP_AGENT_INPUT_REQUIRED 2
|
||||
|
||||
int sp_agent_run(struct sp_agent *, const char *user_text,
|
||||
struct sp_buf *answer, struct sp_buf *err);
|
||||
/* Resume a paused turn: decision 1 allows the pending calls, 0 denies. */
|
||||
int sp_agent_resume(struct sp_agent *, int decision, struct sp_buf *answer,
|
||||
struct sp_buf *err);
|
||||
|
||||
/* builtin.c */
|
||||
int sp_builtin_register(struct sp_registry *);
|
||||
int sp_builtin_register(struct sp_registry *, const char *root);
|
||||
/*
|
||||
* Environment names the 'run' tool's shell does not inherit (API keys,
|
||||
* tokens). A trailing '*' makes a prefix. sp_secret_env_is takes "NAME=value".
|
||||
@@ -336,9 +519,11 @@ int sp_delegate_register(struct sp_registry *, const struct sp_config *,
|
||||
struct sp_host;
|
||||
int sp_telegram_run(struct sp_agent *, struct sp_host *host,
|
||||
const char *token, const char *allow, struct sp_config *conf,
|
||||
const char *base_dir, struct sp_buf *err);
|
||||
int sp_telegram_notify(const struct sp_config *conf, const char *text,
|
||||
struct sp_buf *err);
|
||||
int sp_telegram_token(char *buf, size_t len, const char *path);
|
||||
const char *sp_memory_user(void);
|
||||
const char *sp_user_name(void);
|
||||
/*
|
||||
* Slash commands that are programs: <session dir>/commands/<name>. The program
|
||||
* gets the rest of the line, and its output becomes context for the model.
|
||||
@@ -355,6 +540,14 @@ int sp_delegate_prio(const struct sp_config *, const char *id);
|
||||
*/
|
||||
void sp_delegate_cli_plugin(const char *self, char *out, size_t len);
|
||||
|
||||
/*
|
||||
* A shipped plugin by name ("lcm", "mcp"): the build tree next to the binary
|
||||
* at 'self', the installed layout ($(PREFIX)/lib/splinter/plugins), then the
|
||||
* build directory compiled in. None found: the first candidate.
|
||||
*/
|
||||
void sp_plugin_path(const char *self, const char *name, char *out,
|
||||
size_t len);
|
||||
|
||||
/*
|
||||
* Limits. sp_limit_parse: is this error text a rate/usage limit (429, "weekly
|
||||
* limit", "quota", ...) and until when - the reset it names, else an hour.
|
||||
@@ -383,6 +576,9 @@ const volatile int *sp_cancel_flag(void);
|
||||
*/
|
||||
void sp_openai_set_session(const char *id);
|
||||
size_t sp_openai_session_header(const char *url, char *buf, size_t cap);
|
||||
/* /effort: review depth for the next requests; -1 lets the router decide */
|
||||
void sp_openai_set_review_depth(int depth);
|
||||
int sp_openai_review_depth(void);
|
||||
|
||||
/*
|
||||
* One route of an endpoint: the config names the API base (https://host/v1),
|
||||
@@ -394,10 +590,17 @@ char *sp_endpoint_url(const char *endpoint, const char *route, char *out,
|
||||
|
||||
struct sp_transport sp_openai_transport(const char *url, const char *model,
|
||||
const char *api_key, const struct sp_registry *, long timeout_s);
|
||||
/* the same, with request shaping the caller wants forwarded */
|
||||
struct sp_transport sp_openai_transport_gen(const char *url, const char *model,
|
||||
const char *api_key, const struct sp_registry *, long timeout_s,
|
||||
const struct sp_gen_opts *);
|
||||
|
||||
/* openai.c -- pure JSON shaping, testable without a network */
|
||||
int sp_openai_request(const struct sp_conv *, const char *model,
|
||||
const struct sp_registry *, int streaming, struct sp_buf *out);
|
||||
int sp_openai_request_opts(const struct sp_conv *, const char *model,
|
||||
const struct sp_registry *, int streaming,
|
||||
const struct sp_gen_opts *, struct sp_buf *out);
|
||||
int sp_openai_reply(const char *json, struct sp_reply *out,
|
||||
struct sp_buf *err);
|
||||
|
||||
@@ -413,8 +616,15 @@ int sp_sse_line(struct sp_sse *, const char *line, struct sp_buf *out,
|
||||
/* Turn the accumulated state into a reply. Returns 0 or -1. */
|
||||
int sp_sse_finish(struct sp_sse *, struct sp_reply *out, struct sp_buf *err);
|
||||
int sp_sse_done(const struct sp_sse *);
|
||||
/* the code an in-stream error event carried, 0 if none */
|
||||
int sp_sse_error_code(const struct sp_sse *);
|
||||
int sp_sse_usage(const struct sp_sse *, long *in, long *out);
|
||||
const char *sp_sse_tool_start(const struct sp_sse *, size_t index);
|
||||
/* What the last line carried: SP_STREAM_THINK, SP_STREAM_TEXT, SP_STREAM_TOOL,
|
||||
* or -1 for nothing. Transports classify by this, not by sniffing the line:
|
||||
* OpenAI sends `"content":null` next to `tool_calls`, and a substring test made
|
||||
* the tool's name part of the answer ("<model> readread"). */
|
||||
int sp_sse_kind(const struct sp_sse *);
|
||||
|
||||
/*
|
||||
* transport_anthropic.c -- the Anthropic Messages API, via curl(1).
|
||||
@@ -426,11 +636,17 @@ const char *sp_sse_tool_start(const struct sp_sse *, size_t index);
|
||||
*/
|
||||
struct sp_transport sp_anthropic_transport(const char *url, const char *model,
|
||||
const char *api_key, const struct sp_registry *, long timeout_s);
|
||||
struct sp_transport sp_anthropic_transport_gen(const char *url,
|
||||
const char *model, const char *api_key, const struct sp_registry *,
|
||||
long timeout_s, const struct sp_gen_opts *);
|
||||
|
||||
/* anthropic.c -- pure JSON shaping, testable without a network */
|
||||
int sp_anthropic_request(const struct sp_conv *, const char *model,
|
||||
const struct sp_registry *, int streaming, int oauth,
|
||||
struct sp_buf *out);
|
||||
int sp_anthropic_request_opts(const struct sp_conv *, const char *model,
|
||||
const struct sp_registry *, int streaming, int oauth,
|
||||
const struct sp_gen_opts *, struct sp_buf *out);
|
||||
int sp_anthropic_reply(const char *json, struct sp_reply *out,
|
||||
struct sp_buf *err);
|
||||
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
/*
|
||||
* 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_answer(), sp_engine_steer()
|
||||
* and sp_engine_cancel() are what a front end may do while it runs.
|
||||
*
|
||||
* This is the C boundary. The same engine is served over a line-oriented JSON
|
||||
* socket by `splinter --serve`, so a GUI may be written in any language; see
|
||||
* docs/PROTOCOL.md. The two front ends use exactly the calls below, which is
|
||||
* what keeps them from drifting apart.
|
||||
*/
|
||||
#ifndef SPLINTER_ENGINE_H
|
||||
#define SPLINTER_ENGINE_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
struct sp_config;
|
||||
struct sp_host;
|
||||
struct sp_agent;
|
||||
struct sp_conv;
|
||||
struct sp_engine;
|
||||
struct swarm;
|
||||
|
||||
#define SP_ENGINE_PLUGINS 32
|
||||
|
||||
/* ---------------------------------------------------------------- options */
|
||||
|
||||
/*
|
||||
* What sp_engine_open() needs. Strings are copied; `conf` and `base` are read
|
||||
* and not owned (main keeps them alive for the whole run), but the engine does
|
||||
* change conf the way the old binary did: /model writes a drop-in, /connect
|
||||
* adds a provider, a pool failover marks one benched.
|
||||
*/
|
||||
struct sp_engine_opts {
|
||||
struct sp_config *conf;
|
||||
const struct sp_agent_config *base; /* steps, byte budget, prompt */
|
||||
const char *endpoint;
|
||||
const char *model;
|
||||
const char *key_env; /* variable holding the API key */
|
||||
const char *transport; /* plugin transport ("cli"), or NULL */
|
||||
const char *kind; /* "anthropic", or NULL */
|
||||
const char *script; /* mock replies, one per line */
|
||||
const char *agent; /* profile to start in */
|
||||
const char *session_dir;
|
||||
const char *session_id;
|
||||
const char *plugins[SP_ENGINE_PLUGINS];
|
||||
size_t nplugins;
|
||||
int resume; /* load the session's history */
|
||||
int continue_last; /* -c: newest session in this cwd */
|
||||
/*
|
||||
* --claude/--opencode/--hermes: import the newest session that tool
|
||||
* ran in this directory and continue that instead of a splinter one.
|
||||
* from_foreign_id names one session instead of "the newest" - that is
|
||||
* how the /sessions picker continues what the operator pointed at.
|
||||
*/
|
||||
const char *from_foreign;
|
||||
const char *from_foreign_id;
|
||||
int no_transport; /* tools only (MCP server, delegate) */
|
||||
int interview; /* the model interviews the user */
|
||||
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 */
|
||||
/*
|
||||
* The model asked the operator a question (the `ask` tool). n: the
|
||||
* number of options, a: the text. The options are read with
|
||||
* sp_engine_ask() when the front end draws the dialog; the answer goes
|
||||
* back through sp_engine_answer().
|
||||
*/
|
||||
SP_EV_ASK,
|
||||
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;
|
||||
double cost; /* provider-reported, USD */
|
||||
size_t ctx_used; /* prompt tokens of the last request */
|
||||
size_t ctx_max; /* context window, 0 = unknown */
|
||||
size_t cached; /* of ctx_used, served from the provider cache */
|
||||
size_t cached_total; /* of tokens_in, the whole session */
|
||||
size_t turn_tokens_out; /* output tokens of this/last turn */
|
||||
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 */
|
||||
/* the turn waits for an answer to the `ask` tool */
|
||||
int asking;
|
||||
int agents_n;
|
||||
int agent_cur;
|
||||
};
|
||||
|
||||
int sp_engine_state(struct sp_engine *, struct sp_engine_state *);
|
||||
|
||||
/*
|
||||
* The choices /model takes - every provider, then every pool - with the model
|
||||
* as the label and the current one marked. Configuration, not a network probe:
|
||||
* a picker must open at once. Returns how many were written.
|
||||
*/
|
||||
size_t sp_engine_models(struct sp_engine *, struct sp_model_choice *,
|
||||
size_t max);
|
||||
/*
|
||||
* The models the endpoint this session is on reports at /v1/models, as
|
||||
* selectors /model accepts. This talks to the network; the picker asks for it
|
||||
* after the configured list is already on screen.
|
||||
*/
|
||||
size_t sp_engine_served_models(struct sp_engine *, struct sp_model_choice *,
|
||||
size_t max);
|
||||
|
||||
/* -------------------------------------------------------------- lifecycle */
|
||||
|
||||
int sp_engine_open(struct sp_engine **, const struct sp_engine_opts *,
|
||||
struct sp_buf *err);
|
||||
void sp_engine_close(struct sp_engine *);
|
||||
/*
|
||||
* Move an engine to another session: close the old engine, open the new one
|
||||
* from the same options, replace *ep. `id` is a session id, "new" for a fresh
|
||||
* one, or NULL/"last" for the newest. The old engine is closed first because
|
||||
* plugins keep process globals; a failed open reopens the session the engine
|
||||
* was on, so the pointer is only NULL when even that fails. Returns 0 or -1
|
||||
* with `err` set.
|
||||
*/
|
||||
int sp_engine_switch(struct sp_engine **ep, const struct sp_engine_opts *,
|
||||
const char *id, struct sp_buf *err);
|
||||
|
||||
/* The pieces a front end may look at. The pointers stay valid until close. */
|
||||
struct sp_agent *sp_engine_agent(struct sp_engine *);
|
||||
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 *);
|
||||
|
||||
/*
|
||||
* What the /sessions picker offers: the sources that have sessions at all,
|
||||
* its own first. "splinter" is always there (this folder's session directory
|
||||
* is what the run is); the other three only when their store answers with at
|
||||
* least one session, so the picker never offers an empty source.
|
||||
*/
|
||||
struct sp_session_source {
|
||||
char name[16]; /* "splinter", "claude", "hermes", "opencode" */
|
||||
int count; /* 0 when the source could not be listed */
|
||||
};
|
||||
int sp_engine_sources(struct sp_engine *,
|
||||
struct sp_session_source *v, size_t max);
|
||||
|
||||
/*
|
||||
* The sessions of one source. For "splinter" that is the session directory;
|
||||
* for the others the foreign plugin's list, and a row's `id` is then
|
||||
* "claude:<id>" - what sp_engine_switch() takes to import and continue it.
|
||||
* `title` is a label for the screen, not something to parse.
|
||||
*/
|
||||
int sp_engine_source_sessions(struct sp_engine *, const char *source,
|
||||
void (*cb)(void *cbctx, const char *id, const char *title,
|
||||
int current, long mtime), void *cbctx);
|
||||
|
||||
/* ------------------------------------------------------------------ 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 *);
|
||||
|
||||
/*
|
||||
* Work on the engine's agent outside its turn thread. A daemon's Telegram
|
||||
* turn runs sp_agent_run() on its own thread with the engine's agent:
|
||||
* sp_engine_turn_begin() before it, sp_engine_turn_end() after; -1 means
|
||||
* busy (a turn or a session tool owns the agent) and nothing was taken.
|
||||
* While held, sp_engine_busy() says 1. The _agent_ forms find the engine
|
||||
* that owns the agent (0 and a no-op for an agent no engine owns).
|
||||
* sp_engine_hold()/release() is the short form for one tool call: exclusive
|
||||
* like a turn, refused while one runs, not reported as busy.
|
||||
*/
|
||||
int sp_engine_turn_begin(struct sp_engine *);
|
||||
void sp_engine_turn_end(struct sp_engine *);
|
||||
int sp_engine_agent_turn_begin(struct sp_agent *);
|
||||
void sp_engine_agent_turn_end(struct sp_agent *);
|
||||
int sp_engine_hold(struct sp_engine *);
|
||||
void sp_engine_release(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);
|
||||
/*
|
||||
* The model asked the operator something (the `ask` tool). The turn thread
|
||||
* parks on the engine's condition variable and the front end wakes it, so
|
||||
* cancel and Ctrl-C behave the same; the answer is text: an option the
|
||||
* operator picked, or words they typed.
|
||||
*
|
||||
* 1 while a question is pending; `text` is what was asked and up to `max`
|
||||
* options are copied into `opts` (nopts may be NULL). Options are hints for a
|
||||
* dialog; a front end that has no dialog asks the same question as a line and
|
||||
* the answer is still valid text.
|
||||
*/
|
||||
int sp_engine_ask(struct sp_engine *, char *text, size_t textlen,
|
||||
char (*opts)[SP_ASK_OPT_LEN], size_t max, size_t *nopts);
|
||||
/* Answer it with free text or a picked option. 0 when nothing was pending. */
|
||||
int sp_engine_answer(struct sp_engine *, const char *text);
|
||||
|
||||
/* ------------------------------------------------------------------ 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 */
|
||||
@@ -101,6 +101,7 @@ struct sp_meter {
|
||||
size_t tok_in; /* this session */
|
||||
size_t tok_out;
|
||||
size_t cached; /* tokens the provider served from cache */
|
||||
size_t cached_total; /* the same for the whole session */
|
||||
long tps; /* output tokens per second, last turn */
|
||||
double cost; /* session cost, filled from the price config */
|
||||
unsigned tasks_running;
|
||||
@@ -149,9 +150,64 @@ int sp_host_note(struct sp_host *, const char *text);
|
||||
int sp_host_status_msg(struct sp_host *, const char *text);
|
||||
int sp_host_status_take(struct sp_host *, char *buf, size_t len);
|
||||
int sp_host_add_compactor(struct sp_host *, const struct sp_compactor *);
|
||||
/*
|
||||
* The compactor the core registers itself, before any plugin. It is what
|
||||
* compact_threshold and compact_target drive; a plugin that compacts too runs
|
||||
* after it.
|
||||
*/
|
||||
const struct sp_compactor *sp_core_compactor(void);
|
||||
/*
|
||||
* "Leave this conversation alone for this round."
|
||||
*
|
||||
* A compactor that works asynchronously - it copies the conversation, hands it
|
||||
* to a worker and applies the plan on its next call - cannot survive the core
|
||||
* cutting the conversation between the snapshot and the apply: the plan is
|
||||
* made for a conversation that no longer exists, the size check fails, and the
|
||||
* work is thrown away every round while the conversation keeps growing.
|
||||
*
|
||||
* So a plugin in that state calls this before returning 0. The host then keeps
|
||||
* the core compactor out of this one call and asks again next time, which is
|
||||
* when the plan lands. The flag lasts one call and is not remembered.
|
||||
*/
|
||||
void sp_host_compactor_hold(struct sp_host *);
|
||||
int sp_host_add_gate(struct sp_host *, const struct sp_gate *);
|
||||
int sp_host_add_status(struct sp_host *, const struct sp_status *);
|
||||
const struct sp_meter *sp_host_meter(struct sp_host *);
|
||||
/*
|
||||
* The model the engine is on right now. The config says what a provider was
|
||||
* configured with; /model can change the model without touching it, and a
|
||||
* plugin that shows routing must not guess (it did, and named the wrong
|
||||
* route). Empty until the engine sets it.
|
||||
*/
|
||||
const char *sp_host_model(struct sp_host *h);
|
||||
void sp_host_set_model(struct sp_host *h, const char *model);
|
||||
/*
|
||||
* The upstream that served the last model request, when the provider says
|
||||
* (junction: X-Junction-Endpoint). The model is what was asked for; this is
|
||||
* who answered, and a router may pick a different one per request.
|
||||
*/
|
||||
const char *sp_host_served_by(struct sp_host *h);
|
||||
void sp_host_set_served_by(struct sp_host *h, const char *endpoint);
|
||||
/*
|
||||
* The judge schedule of the last judged response (X-Junction-Judge-Next,
|
||||
* -In, -Next-Step/Every/Target/Model/Cache). A plugin can say when the next
|
||||
* escalation happens without calling the model itself.
|
||||
*/
|
||||
struct sp_judge_next {
|
||||
int valid;
|
||||
int next; /* counter value */
|
||||
int in; /* calls remaining */
|
||||
int step, every; /* the next judge's position in the chain */
|
||||
char target[64];
|
||||
char model[128];
|
||||
char cache[8];
|
||||
};
|
||||
void sp_host_set_judge_next(struct sp_host *,
|
||||
const struct sp_judge_next *);
|
||||
int sp_host_judge_next(struct sp_host *, struct sp_judge_next *);
|
||||
/* X-Junction-Cache of the last response: off, 5m or 1h; "" when unknown */
|
||||
const char *sp_host_cache_mode(struct sp_host *);
|
||||
void sp_host_set_cache_mode(struct sp_host *, const char *mode);
|
||||
void sp_host_set_meter(struct sp_host *, const struct sp_meter *);
|
||||
/*
|
||||
* Thread-safe: a copy under the host lock, and a change of only the caller's
|
||||
@@ -224,6 +280,26 @@ void sp_host_turn(struct sp_host *);
|
||||
/* The loaded configuration, so plugins (the exit ring) can read it. */
|
||||
const void *sp_host_config(struct sp_host *);
|
||||
void sp_host_set_config(struct sp_host *, const void *);
|
||||
|
||||
/*
|
||||
* A plugin's own configuration, from its block in the config file:
|
||||
*
|
||||
* plugin lcm {
|
||||
* keep = 40
|
||||
* server junction { url = http://... }
|
||||
* }
|
||||
*
|
||||
* sp_host_plugin_config(h, "lcm", "keep") is "40", a nested block gives
|
||||
* dotted keys ("server.junction.url"), a list "a,b,c". NULL when the key is
|
||||
* not set (or no config is loaded). 'plugin' is the block's name.
|
||||
*
|
||||
* sp_host_plugin_config_at() walks every setting of 'plugin' in file order:
|
||||
* index 0, 1, ... until it returns NULL; *key gets the setting's name.
|
||||
*/
|
||||
const char *sp_host_plugin_config(struct sp_host *, const char *plugin,
|
||||
const char *key);
|
||||
const char *sp_host_plugin_config_at(struct sp_host *, const char *plugin,
|
||||
size_t i, const char **key);
|
||||
struct sp_registry *sp_host_registry(struct sp_host *);
|
||||
|
||||
/* ---- host side, implemented by splinter, called by the harness ---- */
|
||||
@@ -232,6 +308,7 @@ struct sp_host *sp_host_new(struct sp_registry *, struct sp_agent *,
|
||||
struct sp_session_info *);
|
||||
void sp_host_free(struct sp_host *);
|
||||
const char *sp_host_session_dir(struct sp_host *);
|
||||
const char *sp_host_session_id(struct sp_host *);
|
||||
/* Retry a durable delegation job (scheduler/worker). 0 on handled (see out). */
|
||||
int sp_delegate_retry_job(const char *id, int force, struct sp_buf *out);
|
||||
/* Scheduler tick: retry one due waiting_quota/waiting_poll job if any. */
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
splinter is a C99/POSIX agent harness with a curses interface: the
|
||||
conversation on three quarters of the screen, a sidebar with the agent,
|
||||
provider, model and allowance in use, a status line with the context gauge,
|
||||
and the prompt below it.
|
||||
|
||||
It speaks to providers over their HTTP APIs, runs the tools it is asked to
|
||||
run (only those in its registry, and a mutating one only with consent), keeps
|
||||
every turn as JSON Lines under ~/.splinter, and can put its engine on a
|
||||
socket (splinter --serve) for another front end, or present an OpenAI-
|
||||
compatible endpoint of its own (splinter --openai-listen).
|
||||
|
||||
The library (libsplinter.so) is the backend; splinter and splinterctl are the
|
||||
front ends; the plugins under lib/splinter/plugins are the tools (a clock,
|
||||
the MCP client, provider pools, process control and others).
|
||||
@@ -0,0 +1,79 @@
|
||||
# $Makronix$
|
||||
#
|
||||
# splinter -- the project's own C99/POSIX agent harness.
|
||||
#
|
||||
# The source is not a tarball: it is ext/src/splinter in this repository, the
|
||||
# tree that git tracks and a person edits. pkgsrc builds it from there the way
|
||||
# net/fetch and pkgtools/pkg_install build from their files/ directory -- no
|
||||
# DISTFILES, no distinfo, no archive to regenerate after a commit, and
|
||||
# `do-extract' puts the tree into WRKSRC. Build output stays in the work
|
||||
# directory (tools/pkgsrc-cross.mk.conf: WRKOBJDIR), never in the source.
|
||||
#
|
||||
# The mirror in pkgsrc/misc/splinter is made by tools/ext-sync.sh: symlinks to
|
||||
# this file, so this is the only copy of the recipe.
|
||||
|
||||
DISTNAME= splinter-0.1
|
||||
CATEGORIES= misc
|
||||
MASTER_SITES= # empty
|
||||
DISTFILES= # empty
|
||||
|
||||
MAINTAINER= lotherk@lother.io
|
||||
COMMENT= C99/POSIX agent harness with a curses interface
|
||||
LICENSE= modified-bsd
|
||||
|
||||
# The tree this recipe belongs to: three levels above the directory pkgsrc
|
||||
# builds in, which is /home/lotherk/src/makronix here, /mnt inside the build
|
||||
# chroot and /usr/src on an installed system -- the same relative position in
|
||||
# all three, so nothing has to be passed in. `pwd -P': pkgsrc refuses a WRKDIR
|
||||
# path that is not canonical ("must be canonical"), and the mirror in pkgsrc/ is
|
||||
# reached through a symlink.
|
||||
_MAKRONIX_TOP!= cd ${.CURDIR}/../../.. && pwd -P
|
||||
SPLSRC= ${_MAKRONIX_TOP}/ext/src/splinter
|
||||
|
||||
# The top Makefile is POSIX make; it runs the vendored NetBSD curses through
|
||||
# $(MAKE) -f GNUmakefile, which is GNU make. The build host's GNU make is
|
||||
# what USE_TOOLS brings; the target compiler comes from pkgsrc's wrappers.
|
||||
USE_TOOLS+= gmake
|
||||
MAKE_PROGRAM= ${GMAKE}
|
||||
|
||||
NO_CONFIGURE= yes
|
||||
NO_BUILDLINK= yes
|
||||
BUILD_TARGET= all
|
||||
INSTALL_TARGET= install
|
||||
|
||||
MAKE_FLAGS+= PREFIX=${PREFIX}
|
||||
MAKE_FLAGS+= DESTDIR=${DESTDIR}
|
||||
|
||||
# splinter's Makefile has its own CFLAGS default: the dialect, the include
|
||||
# paths of the source tree and -fPIC. A CFLAGS on the command line replaces
|
||||
# that default, so the package's flags are appended here. No -Werror: a
|
||||
# warning in the distribution is not a reason to stop the build. One line
|
||||
# and escaped spaces: a continuation ate the space before -fPIC (measured
|
||||
# 2026-11-17: "make: PIC -Iinclude ... No such file or directory").
|
||||
SPL_CFLAGS= -std=c99\ -D_POSIX_C_SOURCE=200809L\ -D_XOPEN_SOURCE=700\ -D_NETBSD_SOURCE\ -fPIC\ -Iinclude\ -Isrc/backend\ -Isrc/frontend\ -Ivendor/libmcp\ -Ivendor/netbsd-curses/libcurses
|
||||
MAKE_FLAGS+= CFLAGS=${CFLAGS:Q}\ ${SPL_CFLAGS}
|
||||
|
||||
# libsplinter.so is what the binaries and the plugins link against
|
||||
LDFLAGS+= ${COMPILER_RPATH_FLAG}${PREFIX}/lib
|
||||
MAKE_FLAGS+= LDFLAGS=${LDFLAGS:Q}
|
||||
MAKE_FLAGS+= LIBS=-lpthread
|
||||
|
||||
# NetBSD's own curses, not the vendored copy: the base system has libcurses
|
||||
# and libterminfo, and linking them keeps the package small and the build
|
||||
# free of tools that must run while it builds (the vendored tree's nbperf is
|
||||
# a target binary in a cross build). The project's Linux build keeps the
|
||||
# vendored default (Konrad, 2026-11-17: "nur auf linux eigenes curses").
|
||||
MAKE_FLAGS+= CURSES_LIB=-lcurses\ -lterminfo
|
||||
# Empty: nothing in the source tree has to be built before linking. The
|
||||
# Makefile defaults it to $(CURSES_LIB) for the vendored tree.
|
||||
MAKE_FLAGS+= CURSES_DEP=""
|
||||
|
||||
# The source tree as it is, without the history: a .git in WRKSRC would be a
|
||||
# copy of the submodule's repository inside a package build.
|
||||
# The copy is made by a script, not by ${CP} -R: pkgsrc extracts once, and
|
||||
# a commit after that never reached the work directory (tools/ext-extract.sh).
|
||||
do-extract:
|
||||
${RUN}${SH} ${_MAKRONIX_TOP}/tools/ext-extract.sh ${SPLSRC} ${WRKSRC}
|
||||
|
||||
.include "../../mk/pthread.buildlink3.mk"
|
||||
.include "../../mk/bsd.pkg.mk"
|
||||
@@ -0,0 +1,23 @@
|
||||
bin/splinter
|
||||
bin/splinterctl
|
||||
lib/libsplinter.so
|
||||
lib/splinter/plugins/a2a.so
|
||||
lib/splinter/plugins/cache.so
|
||||
lib/splinter/plugins/cli.so
|
||||
lib/splinter/plugins/clock.so
|
||||
lib/splinter/plugins/cps.so
|
||||
lib/splinter/plugins/focus.so
|
||||
lib/splinter/plugins/foreign.so
|
||||
lib/splinter/plugins/junction.so
|
||||
lib/splinter/plugins/kids.so
|
||||
lib/splinter/plugins/lcm.so
|
||||
lib/splinter/plugins/mcp.so
|
||||
lib/splinter/plugins/processes.so
|
||||
lib/splinter/plugins/provider.so
|
||||
lib/splinter/plugins/reminder.so
|
||||
lib/splinter/plugins/recap.so
|
||||
lib/splinter/plugins/ring.so
|
||||
lib/splinter/plugins/scheduler.so
|
||||
lib/splinter/plugins/self.so
|
||||
lib/splinter/plugins/session.so
|
||||
lib/splinter/plugins/status.so
|
||||
+83
-17
@@ -115,11 +115,16 @@ build_request(struct a2a_cfg *c, const char *method, const char *text,
|
||||
"\"params\":{\"message\":{\"messageId\":\"%s\","
|
||||
"\"role\":\"ROLE_USER\",", rid, method, mid) != 0)
|
||||
return -1;
|
||||
/* both ids came from the server: escaped, never pasted */
|
||||
if (c->task_id[0] != '\0' &&
|
||||
sp_buf_printf(out, "\"taskId\":\"%s\",", c->task_id) != 0)
|
||||
(sp_buf_puts(out, "\"taskId\":\"") != 0 ||
|
||||
sp_json_escape(out, c->task_id) != 0 ||
|
||||
sp_buf_puts(out, "\",") != 0))
|
||||
return -1;
|
||||
if (c->context_id[0] != '\0' &&
|
||||
sp_buf_printf(out, "\"contextId\":\"%s\",", c->context_id) != 0)
|
||||
(sp_buf_puts(out, "\"contextId\":\"") != 0 ||
|
||||
sp_json_escape(out, c->context_id) != 0 ||
|
||||
sp_buf_puts(out, "\",") != 0))
|
||||
return -1;
|
||||
if (sp_buf_puts(out, "\"parts\":[{\"text\":\"") != 0 ||
|
||||
sp_json_escape(out, text) != 0 ||
|
||||
@@ -202,7 +207,24 @@ save_part(const char *name, const char *mime, const char *data, size_t n,
|
||||
path, mime != NULL && *mime != '\0' ? mime : "binary", n);
|
||||
}
|
||||
|
||||
/* base64 bytes: text becomes text, anything else a file the agent can open */
|
||||
/* a media type whose bytes are words: text, JSON and the +json family */
|
||||
static int
|
||||
mime_is_text(const char *mime)
|
||||
{
|
||||
if (mime == NULL || *mime == '\0')
|
||||
return 0;
|
||||
if (strncasecmp(mime, "text/", 5) == 0)
|
||||
return 1;
|
||||
return strncasecmp(mime, "application/json", 16) == 0 ||
|
||||
strstr(mime, "+json") != NULL;
|
||||
}
|
||||
|
||||
/*
|
||||
* base64 bytes: text becomes text, anything else a file the agent can open.
|
||||
* A part without a media type is not assumed to be text: its bytes could be
|
||||
* anything, and pasted into the conversation they are noise (or cut at the
|
||||
* first NUL). Should the file not be written, a placeholder says what came.
|
||||
*/
|
||||
static int
|
||||
part_bytes(const char *b64, const char *name, const char *mime,
|
||||
struct sp_buf *out)
|
||||
@@ -216,10 +238,15 @@ part_bytes(const char *b64, const char *name, const char *mime,
|
||||
sp_buf_free(&dec);
|
||||
return -1;
|
||||
}
|
||||
if (mime != NULL && *mime != '\0' && strncmp(mime, "text/", 5) != 0) {
|
||||
ok = save_part(name, mime, dec.p, dec.len, out) == 0;
|
||||
} else {
|
||||
if (mime_is_text(mime)) {
|
||||
ok = append_piece(out, dec.p) == 0;
|
||||
} else {
|
||||
ok = save_part(name, mime, dec.p, dec.len, out) == 0;
|
||||
if (!ok)
|
||||
ok = sp_buf_printf(out, "%s[binary part %s, %zu bytes, "
|
||||
"not saved]", out->len > 0 ? "\n" : "",
|
||||
mime != NULL && *mime != '\0' ? mime : "without type",
|
||||
dec.len) == 0;
|
||||
}
|
||||
sp_buf_free(&dec);
|
||||
return ok ? 0 : -1;
|
||||
@@ -864,11 +891,16 @@ out:
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* one line of the SSE stream: data, or the numeric HTTP status at the end */
|
||||
/*
|
||||
* One line of the SSE stream: data, or the numeric HTTP status at the end.
|
||||
* A server that does not stream answers with a plain JSON body instead - a
|
||||
* JSON-RPC error, typically. Those lines are kept in 'plain' and read once the
|
||||
* stream is over, so the server's own message is what the user sees.
|
||||
*/
|
||||
static int
|
||||
stream_line(struct a2a_cfg *c, char *line, size_t len, struct sp_buf *text,
|
||||
int *saw_text, int *finished, int *http, sp_stream_cb cb, void *cbctx,
|
||||
struct sp_buf *err)
|
||||
struct sp_buf *plain, struct sp_buf *err)
|
||||
{
|
||||
char *p;
|
||||
|
||||
@@ -892,7 +924,15 @@ stream_line(struct a2a_cfg *c, char *line, size_t len, struct sp_buf *text,
|
||||
if (*end == '\0')
|
||||
return 0;
|
||||
}
|
||||
return 0; /* event:, id:, comments, status */
|
||||
if (strncmp(line, "event:", 6) == 0 || strncmp(line, "id:", 3) == 0 ||
|
||||
strncmp(line, "retry:", 6) == 0 || line[0] == ':')
|
||||
return 0; /* event:, id:, comments */
|
||||
if (plain->len < 65536 && (sp_buf_puts(plain, line) != 0 ||
|
||||
sp_buf_puts(plain, "\n") != 0)) {
|
||||
sp_buf_puts(err, "a2a: out of memory");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
@@ -900,8 +940,8 @@ a2a_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
struct sp_buf *err, sp_stream_cb cb, void *cbctx)
|
||||
{
|
||||
struct a2a_cfg *c = ctx;
|
||||
struct sp_buf body, text, lbuf;
|
||||
char templ[600], chunk[4096], *nl, *line;
|
||||
struct sp_buf body, text, lbuf, plain;
|
||||
char templ[600] = "", chunk[4096], *nl, *line;
|
||||
pid_t pid = -1;
|
||||
size_t start, len;
|
||||
ssize_t got;
|
||||
@@ -922,11 +962,13 @@ a2a_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
memset(&body, 0, sizeof(body));
|
||||
memset(&text, 0, sizeof(text));
|
||||
memset(&lbuf, 0, sizeof(lbuf));
|
||||
memset(&plain, 0, sizeof(plain));
|
||||
if (sp_buf_init(&body) != 0 || sp_buf_init(&text) != 0 ||
|
||||
sp_buf_init(&lbuf) != 0) {
|
||||
sp_buf_init(&lbuf) != 0 || sp_buf_init(&plain) != 0) {
|
||||
sp_buf_free(&body);
|
||||
sp_buf_free(&text);
|
||||
sp_buf_free(&lbuf);
|
||||
sp_buf_free(&plain);
|
||||
return -1;
|
||||
}
|
||||
if (render(conv, c->full, &text) != 0) {
|
||||
@@ -944,8 +986,10 @@ a2a_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
sp_buf_clear(&text);
|
||||
dump_request(body.p, body.len);
|
||||
fd = start_post(c, body.p, 1, &pid, templ, sizeof(templ), err);
|
||||
if (fd < 0)
|
||||
if (fd < 0) {
|
||||
templ[0] = '\0'; /* start_post removed it */
|
||||
goto out;
|
||||
}
|
||||
while ((got = read(fd, chunk, sizeof(chunk))) > 0) {
|
||||
if (sp_buf_add(&lbuf, chunk, (size_t)got) != 0) {
|
||||
sp_buf_puts(err, "a2a: out of memory");
|
||||
@@ -958,7 +1002,7 @@ a2a_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
line = lbuf.p + start;
|
||||
len = (size_t)(nl - line);
|
||||
if (stream_line(c, line, len, &text, &saw_text,
|
||||
&finished, &http, cb, cbctx, err) != 0)
|
||||
&finished, &http, cb, cbctx, &plain, err) != 0)
|
||||
goto fail;
|
||||
start = (size_t)(nl - lbuf.p) + 1;
|
||||
}
|
||||
@@ -979,7 +1023,7 @@ a2a_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
/* the last line may not end in a newline */
|
||||
if (lbuf.len > 0) {
|
||||
if (stream_line(c, lbuf.p, lbuf.len, &text, &saw_text,
|
||||
&finished, &http, cb, cbctx, err) != 0)
|
||||
&finished, &http, cb, cbctx, &plain, err) != 0)
|
||||
goto fail;
|
||||
}
|
||||
close(fd);
|
||||
@@ -989,7 +1033,26 @@ a2a_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
sp_buf_printf(err, "a2a: transfer failed for %s", c->url);
|
||||
goto out;
|
||||
}
|
||||
unlink(templ);
|
||||
/*
|
||||
* Not a stream but one JSON body: a JSON-RPC error (or a plain
|
||||
* result) the server sent instead. Read it like an event; an error
|
||||
* member becomes the error.
|
||||
*/
|
||||
if (!finished && plain.len > 0 && plain.p[0] == '{') {
|
||||
struct sp_buf perr;
|
||||
|
||||
if (sp_buf_init(&perr) == 0) {
|
||||
if (stream_event(c, plain.p, &text, &saw_text,
|
||||
&finished, cb, cbctx, &perr) != 0 && perr.len > 0) {
|
||||
sp_buf_puts(err, perr.p);
|
||||
if (http < 200 || http > 299)
|
||||
sp_buf_printf(err, " (HTTP %d)", http);
|
||||
sp_buf_free(&perr);
|
||||
goto out;
|
||||
}
|
||||
sp_buf_free(&perr);
|
||||
}
|
||||
}
|
||||
if (http < 200 || http > 299) {
|
||||
sp_buf_printf(err, "a2a: HTTP %d", http);
|
||||
goto out;
|
||||
@@ -1015,11 +1078,14 @@ fail:
|
||||
close(fd);
|
||||
(void)kill(pid, SIGKILL);
|
||||
(void)waitpid(pid, NULL, 0);
|
||||
unlink(templ);
|
||||
out:
|
||||
/* the request is the whole conversation: never left behind */
|
||||
if (templ[0] != '\0')
|
||||
(void)unlink(templ);
|
||||
sp_buf_free(&body);
|
||||
sp_buf_free(&text);
|
||||
sp_buf_free(&lbuf);
|
||||
sp_buf_free(&plain);
|
||||
return rc;
|
||||
}
|
||||
|
||||
|
||||
Vendored
+390
@@ -0,0 +1,390 @@
|
||||
/*
|
||||
* splinter -- cache: what the prompt cache is doing, in the sidebar.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Three caches meet in one turn:
|
||||
*
|
||||
* provider the prompt tokens the model server served from its own cache
|
||||
* (usage.prompt_tokens_details.cached_tokens), last call and the
|
||||
* whole session;
|
||||
* junction the router's cache mode from X-Junction-Cache (off/5m/1h) and,
|
||||
* when its /status answers, entries/hits/misses/bytes;
|
||||
* local the same provider number seen from this machine - there is no
|
||||
* second cache between splinter and the endpoint, so it is shown
|
||||
* once, not invented twice.
|
||||
*
|
||||
* The widget says the last hit rate and the session hit rate, not a single
|
||||
* number that hides which one it is.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "config.h"
|
||||
#include "curl.h"
|
||||
#include "mcp.h"
|
||||
|
||||
#define CACHE_MS 3000
|
||||
#define CACHE_PROBE_MS 15000
|
||||
#define CACHE_BACKOFF_S 60 /* the longest wait after failed probes */
|
||||
|
||||
struct jcache {
|
||||
int valid;
|
||||
long ttl_s, entries, bytes, hits, misses, joined;
|
||||
time_t at;
|
||||
char url[600];
|
||||
};
|
||||
|
||||
static struct {
|
||||
struct sp_host *host;
|
||||
pthread_mutex_t lock;
|
||||
struct jcache j;
|
||||
char widget[1024];
|
||||
char dbg[256]; /* why the last probe failed; under lock */
|
||||
int down; /* the last probe failed */
|
||||
unsigned fails; /* failed probes in a row */
|
||||
time_t next_probe; /* not before this */
|
||||
} c = { NULL, PTHREAD_MUTEX_INITIALIZER, { 0 }, "", "", 0, 0, 0 };
|
||||
|
||||
/*
|
||||
* A probe that failed: say why, mark the numbers as stale (they are kept, with
|
||||
* their age, but no longer shown as current) and wait longer before the next
|
||||
* try - 3, 6, 12 ... up to 60 s. Every probe blocks the widget thread for up
|
||||
* to 4 s; a junction that is down must not cost that on every tick.
|
||||
*/
|
||||
static void
|
||||
probe_failed(const char *fmt, const char *what)
|
||||
{
|
||||
unsigned delay = CACHE_MS / 1000;
|
||||
unsigned k;
|
||||
|
||||
pthread_mutex_lock(&c.lock);
|
||||
snprintf(c.dbg, sizeof(c.dbg), fmt, what);
|
||||
c.down = 1;
|
||||
if (c.fails < 16)
|
||||
c.fails++;
|
||||
for (k = 1; k < c.fails && delay < CACHE_BACKOFF_S; k++)
|
||||
delay *= 2;
|
||||
if (delay > CACHE_BACKOFF_S)
|
||||
delay = CACHE_BACKOFF_S;
|
||||
c.next_probe = time(NULL) + (time_t)delay;
|
||||
pthread_mutex_unlock(&c.lock);
|
||||
}
|
||||
|
||||
/* "12.3k" for token counts; a cache line should fit one sidebar row */
|
||||
static void
|
||||
human(size_t n, char *buf, size_t cap)
|
||||
{
|
||||
if (n >= 1000000)
|
||||
snprintf(buf, cap, "%.1fM", (double)n / 1e6);
|
||||
else if (n >= 1000)
|
||||
snprintf(buf, cap, "%.1fk", (double)n / 1e3);
|
||||
else
|
||||
snprintf(buf, cap, "%zu", n);
|
||||
}
|
||||
|
||||
static void
|
||||
human_bytes(long n, char *buf, size_t cap)
|
||||
{
|
||||
if (n >= 1024L * 1024L * 1024L)
|
||||
snprintf(buf, cap, "%.1f GB", (double)n / (1024.0 * 1024.0 * 1024.0));
|
||||
else if (n >= 1024L * 1024L)
|
||||
snprintf(buf, cap, "%.1f MB", (double)n / (1024.0 * 1024.0));
|
||||
else if (n >= 1024L)
|
||||
snprintf(buf, cap, "%.0f kB", (double)n / 1024.0);
|
||||
else
|
||||
snprintf(buf, cap, "%ld B", n);
|
||||
}
|
||||
|
||||
/* the junction status URL and header from the mcp server the config names */
|
||||
static void
|
||||
resolve_junction(const struct sp_config *cfg, char *url, size_t urlcap,
|
||||
char *hdr, size_t hdrcap)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
url[0] = '\0';
|
||||
hdr[0] = '\0';
|
||||
if (cfg == NULL)
|
||||
return;
|
||||
for (i = 0; i < cfg->nmcp; i++) {
|
||||
const struct sp_mcpserver *m = &cfg->mcp[i];
|
||||
|
||||
if (strcmp(m->id, "junction") != 0)
|
||||
continue;
|
||||
if (m->url[0] == '\0')
|
||||
return;
|
||||
snprintf(url, urlcap, "%s", m->url);
|
||||
snprintf(hdr, hdrcap, "%s", m->header);
|
||||
break;
|
||||
}
|
||||
if (url[0] == '\0')
|
||||
return;
|
||||
{
|
||||
size_t n = strlen(url);
|
||||
|
||||
if (n >= 4 && strcmp(url + n - 4, "/mcp") == 0) {
|
||||
n -= 4;
|
||||
url[n] = '\0';
|
||||
}
|
||||
while (n > 0 && url[n - 1] == '/')
|
||||
url[--n] = '\0';
|
||||
snprintf(url + n, urlcap - n, "/status");
|
||||
}
|
||||
}
|
||||
|
||||
/* one GET, body only; the widget thread may block for the 4 s timeout */
|
||||
static char *
|
||||
get_body(const char *url, const char *header)
|
||||
{
|
||||
static const char *const args[] = { "-s", "-m", "4", NULL };
|
||||
const char *hdrs[2];
|
||||
char chunk[4096];
|
||||
struct sp_buf err, body;
|
||||
pid_t pid;
|
||||
int fd, st = 0;
|
||||
ssize_t got;
|
||||
|
||||
hdrs[0] = header != NULL && *header != '\0' ? header : NULL;
|
||||
hdrs[1] = NULL;
|
||||
if (sp_buf_init(&err) != 0)
|
||||
return NULL;
|
||||
fd = sp_curl_start(args, url, hdrs, 1, &pid, &err);
|
||||
if (fd < 0) {
|
||||
sp_buf_free(&err);
|
||||
return NULL;
|
||||
}
|
||||
if (sp_buf_init(&body) != 0) {
|
||||
close(fd);
|
||||
(void)waitpid(pid, &st, 0);
|
||||
sp_buf_free(&err);
|
||||
return NULL;
|
||||
}
|
||||
while ((got = read(fd, chunk, sizeof(chunk))) > 0)
|
||||
if (sp_buf_add(&body, chunk, (size_t)got) != 0)
|
||||
break;
|
||||
close(fd);
|
||||
while (waitpid(pid, &st, 0) < 0 && errno == EINTR)
|
||||
;
|
||||
sp_buf_free(&err);
|
||||
return body.p;
|
||||
}
|
||||
|
||||
static void
|
||||
probe_junction(void)
|
||||
{
|
||||
const struct sp_config *cfg;
|
||||
char url[600], hdr[600], *body;
|
||||
mcp_json *v;
|
||||
const mcp_json *cache;
|
||||
struct jcache j;
|
||||
|
||||
cfg = sp_host_config(c.host);
|
||||
resolve_junction(cfg, url, sizeof(url), hdr, sizeof(hdr));
|
||||
if (url[0] == '\0')
|
||||
return;
|
||||
body = get_body(url, hdr);
|
||||
if (body == NULL || body[0] == '\0') {
|
||||
free(body);
|
||||
probe_failed("no body from %s", url);
|
||||
return;
|
||||
}
|
||||
v = mcp_parse(body);
|
||||
if (v == NULL) {
|
||||
probe_failed("unparseable: %.120s", body);
|
||||
free(body);
|
||||
return;
|
||||
}
|
||||
cache = mcp_arg(v, "cache");
|
||||
if (cache == NULL) {
|
||||
probe_failed("no cache object: %.100s", body);
|
||||
free(body);
|
||||
mcp_json_free(v);
|
||||
return;
|
||||
}
|
||||
free(body);
|
||||
memset(&j, 0, sizeof(j));
|
||||
j.valid = 1;
|
||||
j.ttl_s = (long)mcp_arg_int(cache, "ttl_s", 0);
|
||||
j.entries = (long)mcp_arg_int(cache, "entries", 0);
|
||||
j.bytes = (long)mcp_arg_int(cache, "bytes", 0);
|
||||
j.hits = (long)mcp_arg_int(cache, "hits", 0);
|
||||
j.misses = (long)mcp_arg_int(cache, "misses", 0);
|
||||
j.joined = (long)mcp_arg_int(cache, "joined", 0);
|
||||
j.at = time(NULL);
|
||||
snprintf(j.url, sizeof(j.url), "%s", url);
|
||||
pthread_mutex_lock(&c.lock);
|
||||
c.j = j;
|
||||
c.down = 0;
|
||||
c.fails = 0;
|
||||
c.dbg[0] = '\0';
|
||||
c.next_probe = j.at + CACHE_PROBE_MS / 1000;
|
||||
pthread_mutex_unlock(&c.lock);
|
||||
mcp_json_free(v);
|
||||
}
|
||||
|
||||
static int
|
||||
cache_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
{
|
||||
struct sp_meter m;
|
||||
struct jcache j;
|
||||
char text[1024], last[24], ses[24], l[24], s[24];
|
||||
int lpct = 0, spct = 0;
|
||||
time_t now = time(NULL);
|
||||
int probe = 0, down;
|
||||
|
||||
(void)ctx;
|
||||
c.host = h;
|
||||
sp_host_meter_get(h, &m);
|
||||
pthread_mutex_lock(&c.lock);
|
||||
if (now >= c.next_probe)
|
||||
probe = 1;
|
||||
pthread_mutex_unlock(&c.lock);
|
||||
if (probe)
|
||||
probe_junction();
|
||||
pthread_mutex_lock(&c.lock);
|
||||
j = c.j;
|
||||
down = c.down;
|
||||
pthread_mutex_unlock(&c.lock);
|
||||
|
||||
human(m.ctx_used, last, sizeof(last));
|
||||
human(m.tok_in, ses, sizeof(ses));
|
||||
if (m.ctx_used > 0)
|
||||
lpct = (int)((m.cached * 100 + m.ctx_used / 2) / m.ctx_used);
|
||||
if (m.tok_in > 0)
|
||||
spct = (int)((m.cached_total * 100 + m.tok_in / 2) / m.tok_in);
|
||||
snprintf(l, sizeof(l), "%zu", m.cached);
|
||||
snprintf(s, sizeof(s), "%zu", m.cached_total);
|
||||
|
||||
if (m.ctx_used == 0 && m.tok_in == 0)
|
||||
snprintf(text, sizeof(text),
|
||||
"prompt no request yet\n"
|
||||
"junction %s", sp_host_cache_mode(h)[0] != '\0' ?
|
||||
sp_host_cache_mode(h) : "unknown");
|
||||
else
|
||||
snprintf(text, sizeof(text),
|
||||
"prompt %d%% last | %d%% session\n"
|
||||
"cached %s of %s last\n"
|
||||
"session %s of %s tokens",
|
||||
lpct, spct, l, last, s, ses);
|
||||
if (j.valid && down) {
|
||||
size_t off = strlen(text);
|
||||
|
||||
/* the old numbers are not the cache now: say how old they are */
|
||||
snprintf(text + off, sizeof(text) - off,
|
||||
"\njunction %s | stats down\n"
|
||||
"junction last stats %lds ago",
|
||||
sp_host_cache_mode(h)[0] != '\0' ?
|
||||
sp_host_cache_mode(h) : "unknown", (long)(now - j.at));
|
||||
} else if (j.valid) {
|
||||
size_t off = strlen(text);
|
||||
char b[24];
|
||||
|
||||
human_bytes(j.bytes, b, sizeof(b));
|
||||
snprintf(text + off, sizeof(text) - off,
|
||||
"\njunction %s | %ld entries\n"
|
||||
"junction %ld hits | %ld misses | %s",
|
||||
sp_host_cache_mode(h)[0] != '\0' ?
|
||||
sp_host_cache_mode(h) : "unknown",
|
||||
j.entries, j.hits, j.misses, b);
|
||||
} else {
|
||||
size_t off = strlen(text);
|
||||
|
||||
snprintf(text + off, sizeof(text) - off,
|
||||
"\njunction %s | no stats",
|
||||
sp_host_cache_mode(h)[0] != '\0' ?
|
||||
sp_host_cache_mode(h) : "unknown");
|
||||
}
|
||||
(void)sp_host_widget_text(h, name, text);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
cache_command(struct sp_host *h, const char *args, struct sp_buf *out,
|
||||
void *ctx)
|
||||
{
|
||||
struct sp_meter m;
|
||||
struct jcache j;
|
||||
char l[24], s[24], b[24];
|
||||
char curl[600], chdr[600];
|
||||
const struct sp_config *cfg;
|
||||
char dbg[sizeof(c.dbg)];
|
||||
int lpct = 0, spct = 0, down;
|
||||
|
||||
(void)args;
|
||||
(void)ctx;
|
||||
c.host = h;
|
||||
cfg = sp_host_config(h);
|
||||
resolve_junction(cfg, curl, sizeof(curl), chdr, sizeof(chdr));
|
||||
sp_host_meter_get(h, &m);
|
||||
pthread_mutex_lock(&c.lock);
|
||||
j = c.j;
|
||||
down = c.down;
|
||||
snprintf(dbg, sizeof(dbg), "%s", c.dbg);
|
||||
pthread_mutex_unlock(&c.lock);
|
||||
if (m.ctx_used > 0)
|
||||
lpct = (int)((m.cached * 100 + m.ctx_used / 2) / m.ctx_used);
|
||||
if (m.tok_in > 0)
|
||||
spct = (int)((m.cached_total * 100 + m.tok_in / 2) / m.tok_in);
|
||||
human(m.ctx_used, l, sizeof(l));
|
||||
human(m.tok_in, s, sizeof(s));
|
||||
sp_buf_printf(out, "cache:\n");
|
||||
sp_buf_printf(out, " provider last: %zu of %s tokens (%d%%)\n",
|
||||
m.cached, l, lpct);
|
||||
sp_buf_printf(out, " provider session: %zu of %s tokens (%d%%)\n",
|
||||
m.cached_total, s, spct);
|
||||
sp_buf_printf(out, " junction mode: %s\n",
|
||||
sp_host_cache_mode(h)[0] != '\0' ? sp_host_cache_mode(h) : "?");
|
||||
sp_buf_printf(out, " junction url: %s (mcp %zu)\n",
|
||||
curl[0] != '\0' ? curl : "(not configured)",
|
||||
cfg != NULL ? cfg->nmcp : 0);
|
||||
if (j.valid) {
|
||||
human_bytes(j.bytes, b, sizeof(b));
|
||||
sp_buf_printf(out, " junction: %ld entries, %ld hits, "
|
||||
"%ld misses, %s, ttl %ld s, %ld joined\n", j.entries,
|
||||
j.hits, j.misses, b, j.ttl_s, j.joined);
|
||||
sp_buf_printf(out, " junction status: %s\n", j.url);
|
||||
if (down)
|
||||
sp_buf_printf(out, " junction: stale, from %ld s ago; "
|
||||
"the last probe failed\n",
|
||||
(long)(time(NULL) - j.at));
|
||||
} else
|
||||
sp_buf_puts(out, " junction: no /status cache stats\n");
|
||||
if (dbg[0] != '\0')
|
||||
sp_buf_printf(out, " probe: %s\n", dbg);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_widget w = {
|
||||
"cache", cache_tick, NULL, NULL, CACHE_MS
|
||||
};
|
||||
|
||||
static int
|
||||
cache_init(struct sp_host *h)
|
||||
{
|
||||
c.host = h;
|
||||
if (sp_host_add_widget(h, &w) != 0)
|
||||
return -1;
|
||||
if (sp_host_add_command(h, "cache", cache_command, NULL) != 0)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin cache_plugin = {
|
||||
SP_PLUGIN_ABI, "cache", "1.0.0", cache_init, NULL, NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &cache_plugin;
|
||||
}
|
||||
+74
-18
@@ -254,9 +254,23 @@ ci_contains(const char *hay, const char *needle)
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* the idle window in seconds; 0 or less means no limit */
|
||||
static long
|
||||
cli_timeout_s(const struct cli_cfg *c)
|
||||
{
|
||||
char *end = NULL;
|
||||
long n;
|
||||
|
||||
if (c == NULL || c->timeout[0] == '\0')
|
||||
return 0;
|
||||
n = strtol(c->timeout, &end, 10);
|
||||
return n > 0 ? n : 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Build the shell line: timeout, the command with placeholders expanded, the
|
||||
* session arguments, stdin and stderr redirection.
|
||||
* Build the shell line: the command with placeholders expanded, the session
|
||||
* arguments, stdin and stderr redirection. The timeout is not a `timeout`
|
||||
* wrapper here: the read loop owns it so output can move the deadline.
|
||||
*/
|
||||
static int
|
||||
build_cmd(const struct cli_cfg *c, const char *path, const char *prompt,
|
||||
@@ -273,8 +287,6 @@ build_cmd(const struct cli_cfg *c, const char *path, const char *prompt,
|
||||
(sp_buf_puts(cmd, ". ") != 0 || sh_word(cmd, envfile) != 0 ||
|
||||
sp_buf_puts(cmd, " && ") != 0))
|
||||
return -1;
|
||||
if (sp_buf_printf(cmd, "timeout %s ", c->timeout) != 0)
|
||||
return -1;
|
||||
while (*p != '\0') {
|
||||
if (strncmp(p, "{file}", 6) == 0) {
|
||||
if (sh_word(cmd, path) != 0)
|
||||
@@ -315,22 +327,30 @@ build_cmd(const struct cli_cfg *c, const char *path, const char *prompt,
|
||||
* turn could only end when the program decided to. `claude -p` under its
|
||||
* 30-minute timeout therefore held Ctrl-C hostage: the UI set the flag, joined
|
||||
* the worker, and the worker was still blocked reading a pipe. The child gets
|
||||
* its own process group (the shell, `timeout`, and the program under it), and
|
||||
* the read loop polls it, so a cancellation kills the whole tree.
|
||||
* its own process group (the shell and the program under it), and the read
|
||||
* loop polls it, so a cancellation kills the whole tree.
|
||||
*
|
||||
* The timeout is an idle window, not a wall clock: every byte on stdout or
|
||||
* stderr moves it forward, and the process itself is asked whether it is still
|
||||
* there. A long answer that keeps typing is work, not a hang.
|
||||
*/
|
||||
static int
|
||||
run_cmd(const char *line, const char *errpath, struct sp_buf *raw,
|
||||
char *errtext, size_t errcap, int *status, struct sp_buf *err)
|
||||
run_cmd(const char *line, const char *errpath, long timeout_s,
|
||||
struct sp_buf *raw, char *errtext, size_t errcap, int *status,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
const volatile int *cancel = sp_cancel_flag();
|
||||
char chunk[4096];
|
||||
FILE *ef;
|
||||
int fds[2], st = 0, rc = 0;
|
||||
int fds[2], st = 0, rc = 0, timed_out = 0, reaped = 0;
|
||||
pid_t child;
|
||||
size_t en = 0;
|
||||
time_t last_out;
|
||||
long errseen = 0;
|
||||
|
||||
sp_buf_clear(raw);
|
||||
*status = 0;
|
||||
last_out = time(NULL);
|
||||
if (pipe(fds) != 0) {
|
||||
sp_buf_printf(err, "cli: pipe: %s", strerror(errno));
|
||||
return -1;
|
||||
@@ -359,7 +379,9 @@ run_cmd(const char *line, const char *errpath, struct sp_buf *raw,
|
||||
close(fds[1]);
|
||||
for (;;) {
|
||||
struct pollfd pfd;
|
||||
struct stat es;
|
||||
ssize_t got;
|
||||
time_t now;
|
||||
int pr;
|
||||
|
||||
if (cancel != NULL && *cancel) {
|
||||
@@ -368,6 +390,18 @@ run_cmd(const char *line, const char *errpath, struct sp_buf *raw,
|
||||
rc = -1;
|
||||
break;
|
||||
}
|
||||
now = time(NULL);
|
||||
/* stderr goes to a file: its growth is output too */
|
||||
if (errpath[0] != '\0' && stat(errpath, &es) == 0 &&
|
||||
(long)es.st_size > errseen) {
|
||||
errseen = (long)es.st_size;
|
||||
last_out = now;
|
||||
}
|
||||
if (timeout_s > 0 && now - last_out >= timeout_s) {
|
||||
(void)kill(-child, SIGKILL);
|
||||
timed_out = 1;
|
||||
break;
|
||||
}
|
||||
pfd.fd = fds[0];
|
||||
pfd.events = POLLIN;
|
||||
pfd.revents = 0;
|
||||
@@ -402,10 +436,28 @@ run_cmd(const char *line, const char *errpath, struct sp_buf *raw,
|
||||
rc = -1;
|
||||
break;
|
||||
}
|
||||
/*
|
||||
* Output keeps the program alive only if the program is still
|
||||
* there: a closed child can leave bytes in the pipe.
|
||||
*/
|
||||
if (!reaped) {
|
||||
pid_t r;
|
||||
|
||||
do {
|
||||
r = waitpid(child, &st, WNOHANG);
|
||||
} while (r < 0 && errno == EINTR);
|
||||
if (r == child)
|
||||
reaped = 1;
|
||||
}
|
||||
if (!reaped)
|
||||
last_out = time(NULL);
|
||||
}
|
||||
close(fds[0]);
|
||||
(void)waitpid(child, &st, 0);
|
||||
*status = st;
|
||||
if (!reaped)
|
||||
while (waitpid(child, &st, 0) < 0 && errno == EINTR)
|
||||
;
|
||||
/* the caller reports 124 as the cli's own timeout */
|
||||
*status = timed_out ? (124 << 8) : st;
|
||||
ef = fopen(errpath, "r");
|
||||
if (ef != NULL) {
|
||||
en = fread(errtext, 1, errcap - 1, ef);
|
||||
@@ -532,8 +584,8 @@ cli_send_one(struct cli_cfg *c, const struct sp_conv *conv,
|
||||
}
|
||||
if (build_cmd(c, path, body.p != NULL ? body.p : "", key, uuid, extra,
|
||||
errpath, envfile, &cmd) != 0 ||
|
||||
run_cmd(cmd.p, errpath, &raw, errtext, sizeof(errtext), &status,
|
||||
err) != 0) {
|
||||
run_cmd(cmd.p, errpath, cli_timeout_s(c), &raw, errtext,
|
||||
sizeof(errtext), &status, err) != 0) {
|
||||
unlink(path);
|
||||
goto fail;
|
||||
}
|
||||
@@ -550,8 +602,8 @@ cli_send_one(struct cli_cfg *c, const struct sp_conv *conv,
|
||||
resume ? "--resume" : "--session-id", uuid);
|
||||
if (build_cmd(c, path, body.p != NULL ? body.p : "", key, uuid,
|
||||
extra, errpath, envfile, &cmd) != 0 ||
|
||||
run_cmd(cmd.p, errpath, &raw, errtext, sizeof(errtext),
|
||||
&status, err) != 0) {
|
||||
run_cmd(cmd.p, errpath, cli_timeout_s(c), &raw,
|
||||
errtext, sizeof(errtext), &status, err) != 0) {
|
||||
unlink(path);
|
||||
goto fail;
|
||||
}
|
||||
@@ -680,9 +732,13 @@ cli_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
|
||||
time_t tt = (time_t)soonest;
|
||||
struct tm tm;
|
||||
|
||||
if (soonest > 0)
|
||||
strftime(when, sizeof(when), "%Y-%m-%d %H:%M",
|
||||
localtime_r(&tt, &tm));
|
||||
if (soonest > 0) {
|
||||
/* an unrepresentable time must not become a wrong
|
||||
* one: the operator reads this as "come back at" */
|
||||
if (localtime_r(&tt, &tm) != NULL)
|
||||
strftime(when, sizeof(when),
|
||||
"%Y-%m-%d %H:%M", &tm);
|
||||
}
|
||||
if (tried == 0)
|
||||
sp_buf_clear(err);
|
||||
sp_buf_printf(err, "%scli: every account at its usage limit, "
|
||||
|
||||
+84
-20
@@ -25,7 +25,6 @@
|
||||
#include "splinter_plugin.h"
|
||||
#include "i18n.h"
|
||||
|
||||
#define SNAP_MAX 256
|
||||
#define KEEP_TAIL 6
|
||||
#define SUMMARY_MAX 512
|
||||
|
||||
@@ -37,10 +36,12 @@ struct snap_msg {
|
||||
|
||||
static struct {
|
||||
pthread_mutex_t lock;
|
||||
size_t n; /* messages in the snapshot, <= SNAP_MAX */
|
||||
size_t n; /* messages in the snapshot: all of them */
|
||||
size_t cap; /* allocated entries in m */
|
||||
size_t total; /* messages in the conversation then */
|
||||
size_t bytes; /* and its size: a stale plan is refused */
|
||||
struct snap_msg m[SNAP_MAX];
|
||||
size_t budget; /* the budget the plan is made for */
|
||||
struct snap_msg *m;
|
||||
int requested;
|
||||
int ready;
|
||||
size_t cut; /* drop [1, cut) */
|
||||
@@ -53,21 +54,53 @@ static struct {
|
||||
char widget[256];
|
||||
} cps;
|
||||
|
||||
static void
|
||||
copy_snapshot(const struct sp_conv *conv)
|
||||
/* one message as sp_conv_bytes() counts it */
|
||||
static size_t
|
||||
msg_bytes(const struct sp_msg *m)
|
||||
{
|
||||
size_t i, n = conv->n > SNAP_MAX ? SNAP_MAX : conv->n;
|
||||
return (m->role != NULL ? strlen(m->role) : 0) +
|
||||
(m->name != NULL ? strlen(m->name) : 0) +
|
||||
(m->content != NULL ? strlen(m->content) : 0) +
|
||||
(m->calls != NULL ? strlen(m->calls) : 0) + 16;
|
||||
}
|
||||
|
||||
/*
|
||||
* The index covers the whole conversation: a plan made from the first few
|
||||
* hundred messages cut against a conversation of thousands.
|
||||
*/
|
||||
static void
|
||||
copy_snapshot(const struct sp_conv *conv, size_t budget)
|
||||
{
|
||||
size_t i, n = conv->n;
|
||||
|
||||
pthread_mutex_lock(&cps.lock);
|
||||
if (n > cps.cap) {
|
||||
struct snap_msg *nm;
|
||||
size_t ncap = cps.cap ? cps.cap : 64;
|
||||
|
||||
while (ncap < n)
|
||||
ncap *= 2;
|
||||
nm = realloc(cps.m, ncap * sizeof(*nm));
|
||||
if (nm == NULL) {
|
||||
/* no index, no plan: lcm or the host trim still work */
|
||||
cps.requested = 0;
|
||||
cps.ready = 0;
|
||||
pthread_mutex_unlock(&cps.lock);
|
||||
return;
|
||||
}
|
||||
cps.m = nm;
|
||||
cps.cap = ncap;
|
||||
}
|
||||
cps.n = n;
|
||||
cps.total = conv->n;
|
||||
cps.bytes = sp_conv_bytes(conv);
|
||||
cps.budget = budget;
|
||||
for (i = 0; i < n; i++) {
|
||||
const struct sp_msg *m = &conv->v[i];
|
||||
|
||||
snprintf(cps.m[i].role, sizeof(cps.m[i].role), "%s",
|
||||
m->role != NULL ? m->role : "?");
|
||||
cps.m[i].len = m->content != NULL ? strlen(m->content) : 0;
|
||||
cps.m[i].len = msg_bytes(m);
|
||||
snprintf(cps.m[i].head, sizeof(cps.m[i].head), "%s",
|
||||
m->content != NULL ? m->content : "");
|
||||
}
|
||||
@@ -89,21 +122,28 @@ cps_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
|
||||
pthread_mutex_lock(&cps.lock);
|
||||
/*
|
||||
* The plan fits this conversation only if it is the one it was made for.
|
||||
* Comparing against cps.n, which stops at SNAP_MAX, meant that past 256
|
||||
* messages no plan ever applied - compaction just stopped.
|
||||
* The plan fits this conversation only if it is the one it was made for:
|
||||
* same length, same size, same budget.
|
||||
*/
|
||||
if (budget == 0) {
|
||||
pthread_mutex_unlock(&cps.lock);
|
||||
return 0; /* no byte budget: nothing to do */
|
||||
}
|
||||
if (cps.ready && cps.total == conv->n &&
|
||||
if (cps.ready && cps.total == conv->n && cps.budget == budget &&
|
||||
cps.bytes == sp_conv_bytes(conv) &&
|
||||
sp_conv_bytes(conv) > budget) {
|
||||
apply = 1;
|
||||
} else {
|
||||
pthread_mutex_unlock(&cps.lock);
|
||||
copy_snapshot(conv);
|
||||
if (sp_conv_bytes(conv) <= budget)
|
||||
return 0; /* fits: no plan needed */
|
||||
copy_snapshot(conv, budget);
|
||||
/*
|
||||
* The worker is making a plan for exactly this conversation. The
|
||||
* core compactor must not cut it in the meantime, or the plan is
|
||||
* invalid before it lands and every round throws it away.
|
||||
*/
|
||||
sp_host_compactor_hold(h);
|
||||
return 0; /* plan is being prepared */
|
||||
}
|
||||
|
||||
@@ -171,20 +211,44 @@ cps_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
cps.requested = 0;
|
||||
|
||||
for (i = 0; i < cps.n; i++)
|
||||
total += cps.m[i].len + 16;
|
||||
total += cps.m[i].len;
|
||||
tail_from = cps.n > KEEP_TAIL ? cps.n - KEEP_TAIL : 1;
|
||||
cut = tail_from;
|
||||
if (cut <= 1)
|
||||
cut = 1;
|
||||
if (tail_from < 1)
|
||||
tail_from = 1;
|
||||
/*
|
||||
* Cut from the front only as far as the budget needs (room left for the
|
||||
* summary), never into the verbatim tail, and never so that the first
|
||||
* kept message is a tool result without its call.
|
||||
*/
|
||||
cut = 1;
|
||||
{
|
||||
size_t left = total;
|
||||
|
||||
while (cut < tail_from && left + SUMMARY_MAX > cps.budget) {
|
||||
left -= cps.m[cut].len;
|
||||
cut++;
|
||||
}
|
||||
}
|
||||
while (cut < cps.n && strcmp(cps.m[cut].role, "tool") == 0)
|
||||
cut++;
|
||||
snprintf(cps.summary, sizeof(cps.summary),
|
||||
"[cps] %zu messages cut from the front to stay under budget; "
|
||||
"[cps] %zu messages cut from the front to fit %zu bytes; "
|
||||
"verbatim tail of %zu messages follows. Oldest cut turn began with: "
|
||||
"\"%.60s\"", cut - 1, cps.n - cut,
|
||||
"\"%.60s\"", cut - 1, cps.budget, cps.n - cut,
|
||||
cps.n > 1 ? cps.m[1].head : "");
|
||||
cps.before = total;
|
||||
cps.after = 0;
|
||||
cps.after = cps.n > 0 ? cps.m[0].len : 0;
|
||||
for (i = cut; i < cps.n; i++)
|
||||
cps.after += cps.m[i].len + 16;
|
||||
cps.after += cps.m[i].len;
|
||||
if (cut <= 1 || cut >= cps.n) {
|
||||
/* nothing to cut that would leave a valid tail */
|
||||
cps.ready = 0;
|
||||
snprintf(line, sizeof(line), sp_td("cps.idle",
|
||||
"idle (applied %lu, prepared %lu)"), cps.applied,
|
||||
cps.prepared);
|
||||
pthread_mutex_unlock(&cps.lock);
|
||||
return sp_host_widget_text(h, name, line);
|
||||
}
|
||||
cps.cut = cut;
|
||||
cps.ready = 1;
|
||||
cps.prepared++;
|
||||
|
||||
+482
-83
@@ -5,15 +5,29 @@
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Long conversations drift. Ten turns in, the model is deep in a detail and the
|
||||
* thing the session was started for is somewhere behind it. This plugin puts
|
||||
* the goal back on the table every five turns - not as a new instruction that
|
||||
* overrides the user, but as one system message right before the turn, so it
|
||||
* can be read as a reminder and dismissed if the user has changed direction.
|
||||
* thing the session was started for is somewhere behind it. This plugin puts a
|
||||
* short recap back on the table every seven turns - not as a new instruction
|
||||
* that overrides the user, but as one system message right before the turn, so
|
||||
* it can be read as a reminder and dismissed if the user has changed direction.
|
||||
*
|
||||
* The goal comes from the operator, never from the model:
|
||||
* `/goal <text>` sets the goal. The engine starts a turn with it, asking the
|
||||
* model for a short recap; the plugin remembers the answer and injects that
|
||||
* recap every seventh turn. /recap (plugins/recap) is separate: it repeats the
|
||||
* operator's own text, not the model's recap of a goal.
|
||||
*
|
||||
* The goal is also the first thing the prompt carries. A session that starts
|
||||
* with a goal (config, resume, planner) gets one system message on its first
|
||||
* request, before the model has answered anything. A goal that is only
|
||||
* remembered internally is a goal the model never saw.
|
||||
*
|
||||
* A goal ends, and the model says so: the instructions ask it to end its final
|
||||
* answer with the single line GOAL_COMPLETE. The plugin looks for that line at
|
||||
* the end of the conversation and in the session log, records the state in the
|
||||
* session meta (sp_session_set_goal_state), and stops reminding. The sidebar
|
||||
* says [done] and /goal reports it; a new goal opens a new one.
|
||||
*
|
||||
* SPLINTER_FOCUS_GOAL text, exported from the config key `goal`
|
||||
* SPLINTER_FOCUS_EVERY turns between reminders, default 5
|
||||
* SPLINTER_FOCUS_EVERY turns between recaps, default 7
|
||||
*
|
||||
* A goal longer than 1000 characters is truncated with a marker: a reminder
|
||||
* that eats the budget it is meant to protect would be self-defeating.
|
||||
@@ -22,158 +36,536 @@
|
||||
* not appended after it: the model then reads goal -> request and answers the
|
||||
* request, instead of reading the request and treating the goal as a reply.
|
||||
*/
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "i18n.h"
|
||||
|
||||
#define GOAL_MAX 1000
|
||||
#define RECAP_MAX 800
|
||||
#define GOAL_DONE "GOAL_COMPLETE"
|
||||
#define SESSION_TAIL (16 * 1024)
|
||||
|
||||
/*
|
||||
* goal, force and reminders are shared by three threads: /goal and /recap run
|
||||
* on the UI thread, the compactor on the turn thread, the tick on its own.
|
||||
* One lock for all of them; the tick used to read the goal while /goal was
|
||||
* rewriting it.
|
||||
* goal, recap and reminders are shared by three threads: /goal runs on the UI
|
||||
* thread, the compactor on the turn thread, the tick on its own. One lock for
|
||||
* all of them; the tick used to read the goal while /goal was rewriting it.
|
||||
*/
|
||||
static pthread_mutex_t focus_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static char goal[GOAL_MAX + 1];
|
||||
static unsigned every = 5;
|
||||
static char recap[RECAP_MAX + 1]; /* the model's short recap of the goal */
|
||||
static int recap_pending; /* goal set, waiting for that answer */
|
||||
static char goal_state[16] = "open"; /* open | succeeded */
|
||||
static unsigned announced; /* the goal is already in a prompt */
|
||||
static unsigned armed; /* a GOAL_COMPLETE may now be an answer */
|
||||
static size_t armed_assistants; /* assistant messages when it was armed */
|
||||
static struct timespec armed_at; /* and when, for the session file */
|
||||
static unsigned every = 7;
|
||||
static unsigned last_reminder;
|
||||
static int force; /* /recap: remind on the next turn */
|
||||
static unsigned reminders;
|
||||
static char widget_text[128];
|
||||
static char widget_text[192];
|
||||
static char session_id[64]; /* whose goal the statics belong to */
|
||||
static char env_goal[GOAL_MAX + 1]; /* SPLINTER_FOCUS_GOAL fallback */
|
||||
|
||||
/* One line, bounded: the recap travels in a system message, not a transcript. */
|
||||
static void
|
||||
recap_fit(char *s, size_t cap)
|
||||
{
|
||||
size_t i = 0, n = 0;
|
||||
|
||||
while (s[i] != '\0' && n + 1 < cap) {
|
||||
unsigned char c = (unsigned char)s[i++];
|
||||
|
||||
if (c == '\n' || c == '\r' || c == '\t') {
|
||||
if (n > 0 && s[n - 1] != ' ')
|
||||
s[n++] = ' ';
|
||||
} else if (c == ' ') {
|
||||
if (n > 0 && s[n - 1] != ' ')
|
||||
s[n++] = ' ';
|
||||
} else
|
||||
s[n++] = (char)c;
|
||||
}
|
||||
while (n > 0 && s[n - 1] == ' ')
|
||||
n--;
|
||||
s[n] = '\0';
|
||||
}
|
||||
|
||||
/*
|
||||
* The first answer after /goal is the recap. A tool round may put empty
|
||||
* assistant messages before it; only text without calls counts.
|
||||
*/
|
||||
static void
|
||||
recap_capture(struct sp_conv *conv)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (!recap_pending || conv == NULL)
|
||||
return;
|
||||
for (i = conv->n; i > 0; i--) {
|
||||
const struct sp_msg *m = &conv->v[i - 1];
|
||||
|
||||
if (m->role == NULL || strcmp(m->role, "assistant") != 0)
|
||||
continue;
|
||||
if (m->content == NULL || m->content[0] == '\0')
|
||||
continue;
|
||||
if (m->calls != NULL && m->calls[0] != '\0')
|
||||
continue;
|
||||
snprintf(recap, sizeof(recap), "%s", m->content);
|
||||
recap_fit(recap, sizeof(recap));
|
||||
recap_pending = 0;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* A plugin is not unloaded between sessions: the same focus statics serve the
|
||||
* next /open. Read the goal and its state from the session meta whenever the
|
||||
* session id changes, so a resumed session and a switched session see their
|
||||
* own goal. The caller holds focus_lock.
|
||||
*/
|
||||
static void
|
||||
focus_session_sync(struct sp_host *h)
|
||||
{
|
||||
const char *dir = sp_host_session_dir(h);
|
||||
const char *id = sp_host_session_id(h);
|
||||
char g[GOAL_MAX + 1], st[16];
|
||||
|
||||
if (id == NULL || *id == '\0' || strcmp(session_id, id) == 0)
|
||||
return;
|
||||
snprintf(session_id, sizeof(session_id), "%s", id);
|
||||
goal[0] = '\0';
|
||||
recap[0] = '\0';
|
||||
snprintf(goal_state, sizeof(goal_state), "open");
|
||||
recap_pending = 0;
|
||||
announced = 0;
|
||||
armed = 0;
|
||||
reminders = 0;
|
||||
last_reminder = 0;
|
||||
if (dir != NULL && *dir != '\0' &&
|
||||
sp_session_get_goal(dir, id, g, sizeof(g)) == 0) {
|
||||
snprintf(goal, sizeof(goal), "%s", g);
|
||||
if (sp_session_get_goal_state(dir, id, st, sizeof(st)) == 0 &&
|
||||
strcmp(st, "succeeded") == 0)
|
||||
snprintf(goal_state, sizeof(goal_state), "%s", st);
|
||||
} else if (env_goal[0] != '\0')
|
||||
snprintf(goal, sizeof(goal), "%s", env_goal);
|
||||
}
|
||||
|
||||
/*
|
||||
* The model declared the goal reached. Persist that in the session (a resumed
|
||||
* session must know), stop reminding, and say it in the sidebar and the
|
||||
* transcript once.
|
||||
*/
|
||||
static void
|
||||
focus_publish(struct sp_host *h)
|
||||
{
|
||||
char line[sizeof(widget_text) + 160];
|
||||
char rec[96];
|
||||
unsigned n;
|
||||
int done;
|
||||
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
done = strcmp(goal_state, "succeeded") == 0;
|
||||
n = reminders;
|
||||
if (goal[0] == '\0')
|
||||
line[0] = '\0'; /* no goal: the sidebar says nothing */
|
||||
else {
|
||||
snprintf(rec, sizeof(rec), sp_td("focus.widget_recap",
|
||||
"recap %u, every %u turns"), n, every);
|
||||
snprintf(line, sizeof(line), "%s%.160s%s\n%s",
|
||||
done ? "[done] " : "", goal,
|
||||
strlen(goal) > 160 ? "..." : "", rec);
|
||||
}
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
(void)sp_host_widget_text(h, "focus", line);
|
||||
}
|
||||
|
||||
static void
|
||||
focus_mark_succeeded(struct sp_host *h)
|
||||
{
|
||||
const char *dir = sp_host_session_dir(h);
|
||||
const char *id = sp_host_session_id(h);
|
||||
char g[GOAL_MAX + 1];
|
||||
int changed = 0;
|
||||
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
if (goal[0] != '\0' && strcmp(goal_state, "succeeded") != 0) {
|
||||
snprintf(goal_state, sizeof(goal_state), "succeeded");
|
||||
snprintf(g, sizeof(g), "%s", goal);
|
||||
changed = 1;
|
||||
}
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
if (!changed)
|
||||
return;
|
||||
if (dir != NULL && *dir != '\0' && id != NULL && *id != '\0') {
|
||||
struct sp_buf serr;
|
||||
|
||||
if (sp_buf_init(&serr) == 0) {
|
||||
(void)sp_session_set_goal_state(dir, id, "succeeded",
|
||||
&serr);
|
||||
sp_buf_free(&serr);
|
||||
}
|
||||
}
|
||||
focus_publish(h);
|
||||
{
|
||||
char msg[GOAL_MAX + 128];
|
||||
|
||||
snprintf(msg, sizeof(msg), sp_td("focus.succeeded",
|
||||
"goal succeeded: %s"), g);
|
||||
(void)sp_host_status_msg(h, msg);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* The newest assistant answer, and only that: a marker in an old turn does not
|
||||
* close a goal that was set after it. Tool rounds are skipped, they carry no
|
||||
* final text - and `after` is how many answers existed when the goal went into
|
||||
* the prompt, so an answer from before that point does not count.
|
||||
*/
|
||||
static size_t
|
||||
count_assistants(const struct sp_conv *conv)
|
||||
{
|
||||
size_t i, n = 0;
|
||||
|
||||
for (i = 0; conv != NULL && i < conv->n; i++)
|
||||
if (conv->v[i].role != NULL &&
|
||||
strcmp(conv->v[i].role, "assistant") == 0 &&
|
||||
conv->v[i].content != NULL && conv->v[i].content[0] != '\0')
|
||||
n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
static int
|
||||
conv_goal_complete(const struct sp_conv *conv, size_t after)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (conv == NULL || count_assistants(conv) <= after)
|
||||
return 0;
|
||||
for (i = conv->n; i > 0; i--) {
|
||||
const struct sp_msg *m = &conv->v[i - 1];
|
||||
|
||||
if (m->role == NULL || strcmp(m->role, "assistant") != 0)
|
||||
continue;
|
||||
if (m->content == NULL || m->content[0] == '\0')
|
||||
continue;
|
||||
if (m->calls != NULL && m->calls[0] != '\0')
|
||||
continue;
|
||||
return strstr(m->content, GOAL_DONE) != NULL;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The tick has no conversation in hand; it reads the session log. Only the tail
|
||||
* is read: the answer that closed the goal is the newest thing in the file, and
|
||||
* a session that has grown to megabytes must not be read every second.
|
||||
*/
|
||||
static int
|
||||
session_goal_complete(struct sp_host *h)
|
||||
{
|
||||
const char *dir = sp_host_session_dir(h);
|
||||
const char *id = sp_host_session_id(h);
|
||||
char path[800], tail[SESSION_TAIL + 1];
|
||||
struct stat st;
|
||||
off_t size, off;
|
||||
ssize_t n;
|
||||
int fd;
|
||||
char *line, *save = NULL, *last = NULL;
|
||||
|
||||
if (dir == NULL || *dir == '\0' || id == NULL || *id == '\0')
|
||||
return 0;
|
||||
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, id);
|
||||
/*
|
||||
* A file that has not been written since the goal was armed holds the
|
||||
* answer to an older goal, whatever its last line says.
|
||||
*/
|
||||
if (stat(path, &st) != 0)
|
||||
return 0;
|
||||
if (st.st_mtim.tv_sec < armed_at.tv_sec ||
|
||||
(st.st_mtim.tv_sec == armed_at.tv_sec &&
|
||||
st.st_mtim.tv_nsec <= armed_at.tv_nsec))
|
||||
return 0;
|
||||
fd = open(path, O_RDONLY);
|
||||
if (fd < 0)
|
||||
return 0;
|
||||
size = lseek(fd, 0, SEEK_END);
|
||||
if (size <= 0) {
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
off = size > (off_t)SESSION_TAIL ? size - (off_t)SESSION_TAIL : 0;
|
||||
if (lseek(fd, off, SEEK_SET) < 0) {
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
n = read(fd, tail, sizeof(tail) - 1);
|
||||
close(fd);
|
||||
if (n <= 0)
|
||||
return 0;
|
||||
tail[n] = '\0';
|
||||
/*
|
||||
* Only the newest final answer counts: an old GOAL_COMPLETE belongs to
|
||||
* the goal that was open then, and a new goal has been set since.
|
||||
*/
|
||||
for (line = strtok_r(tail, "\n", &save); line != NULL;
|
||||
line = strtok_r(NULL, "\n", &save)) {
|
||||
if (strstr(line, "\"role\":\"assistant\"") != NULL)
|
||||
last = line;
|
||||
}
|
||||
return last != NULL && strstr(last, GOAL_DONE) != NULL;
|
||||
}
|
||||
|
||||
/* a system message right before the newest user message, never after it */
|
||||
static int
|
||||
insert_before_user(struct sp_conv *conv, const char *text)
|
||||
{
|
||||
struct sp_msg m;
|
||||
size_t at;
|
||||
|
||||
if (conv == NULL || conv->n == 0)
|
||||
return -1;
|
||||
memset(&m, 0, sizeof(m));
|
||||
m.role = "system";
|
||||
m.content = (char *)text;
|
||||
at = conv->n - 1;
|
||||
while (at > 0 && conv->v[at].role != NULL &&
|
||||
strcmp(conv->v[at].role, "user") != 0)
|
||||
at--;
|
||||
return sp_conv_insert(conv, at, &m);
|
||||
}
|
||||
|
||||
/*
|
||||
* The goal is in a prompt now. From here on an answer may close it - but only
|
||||
* one written after this point: the count of answers and the log's mtime are
|
||||
* the barrier that keeps an older GOAL_COMPLETE out.
|
||||
*/
|
||||
static void
|
||||
focus_arm(const struct sp_conv *conv)
|
||||
{
|
||||
armed = 1;
|
||||
armed_assistants = count_assistants(conv);
|
||||
(void)clock_gettime(CLOCK_REALTIME, &armed_at);
|
||||
}
|
||||
|
||||
/* /goal's own prompt already carries the goal: do not say it twice */
|
||||
static int
|
||||
newest_user_is_goal_prompt(const struct sp_conv *conv)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (conv == NULL)
|
||||
return 0;
|
||||
for (i = conv->n; i > 0; i--) {
|
||||
const struct sp_msg *m = &conv->v[i - 1];
|
||||
|
||||
if (m->role != NULL && strcmp(m->role, "user") == 0)
|
||||
return m->content != NULL &&
|
||||
strncmp(m->content, "Goal: ", 6) == 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
focus_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
unsigned turn)
|
||||
{
|
||||
char text[GOAL_MAX + 512];
|
||||
struct sp_msg m;
|
||||
size_t at;
|
||||
|
||||
char g[GOAL_MAX + 1];
|
||||
char text[GOAL_MAX + 800];
|
||||
char rem[GOAL_MAX + 768];
|
||||
char r[GOAL_MAX + 1];
|
||||
unsigned n;
|
||||
int complete;
|
||||
|
||||
(void)budget;
|
||||
(void)h;
|
||||
if (conv == NULL || conv->n == 0)
|
||||
return 0;
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
if (goal[0] == '\0' || (!force && (turn == 0 || (turn % every) != 0)) ||
|
||||
turn == last_reminder) { /* one reminder per turn, always */
|
||||
focus_session_sync(h);
|
||||
recap_capture(conv);
|
||||
/*
|
||||
* Only an answer to a prompt that carried this goal can close it: armed
|
||||
* is set when the goal goes into the request, so an old GOAL_COMPLETE
|
||||
* lying in the conversation cannot close a goal that was set after it.
|
||||
*/
|
||||
complete = armed && goal[0] != '\0' &&
|
||||
strcmp(goal_state, "succeeded") != 0 &&
|
||||
conv_goal_complete(conv, armed_assistants);
|
||||
if (complete) {
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
focus_mark_succeeded(h);
|
||||
return 0;
|
||||
}
|
||||
if (goal[0] == '\0' || strcmp(goal_state, "succeeded") == 0 ||
|
||||
turn == 0 || turn == last_reminder) { /* never twice in a turn */
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
return 0;
|
||||
}
|
||||
snprintf(g, sizeof(g), "%s", goal);
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
|
||||
{
|
||||
char rem[1024];
|
||||
|
||||
snprintf(rem, sizeof(rem), sp_td("focus.reminder",
|
||||
"Before answering, check whether the last step moved closer "
|
||||
"to the goal. If not, say so and name the next step. Goal: %s"), g);
|
||||
/*
|
||||
* The first request carries the goal itself. Recap first, goal text
|
||||
* until a recap exists - the same rule the periodic reminder follows.
|
||||
*/
|
||||
if (!announced) {
|
||||
if (newest_user_is_goal_prompt(conv)) {
|
||||
/* /goal or /continue already wrote it into the prompt */
|
||||
announced = 1;
|
||||
focus_arm(conv);
|
||||
last_reminder = turn;
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
focus_publish(h);
|
||||
return 0;
|
||||
}
|
||||
snprintf(r, sizeof(r), "%s", recap[0] != '\0' ? recap : goal);
|
||||
announced = 1;
|
||||
focus_arm(conv);
|
||||
last_reminder = turn;
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
snprintf(rem, sizeof(rem), sp_td("focus.goal_prompt",
|
||||
"Goal: %s. Work toward it. When the goal is fully "
|
||||
"achieved, end your final answer with the single "
|
||||
"line GOAL_COMPLETE so splinter can mark it as "
|
||||
"succeeded."), r);
|
||||
snprintf(text, sizeof(text), "[focus] %s", rem);
|
||||
if (insert_before_user(conv, text) != 0)
|
||||
return -1;
|
||||
(void)sp_host_status_msg(h,
|
||||
sp_t("focus.note_goal"));
|
||||
focus_publish(h);
|
||||
return 1;
|
||||
}
|
||||
|
||||
memset(&m, 0, sizeof(m));
|
||||
m.role = "system";
|
||||
m.content = text;
|
||||
if ((turn % every) != 0) {
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
return 0;
|
||||
}
|
||||
snprintf(r, sizeof(r), "%s", recap[0] != '\0' ? recap : goal);
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
|
||||
/* before the newest message, so the goal is read first */
|
||||
at = conv->n - 1;
|
||||
while (at > 0 && conv->v[at].role != NULL &&
|
||||
strcmp(conv->v[at].role, "user") != 0)
|
||||
at--;
|
||||
if (sp_conv_insert(conv, at, &m) != 0)
|
||||
snprintf(rem, sizeof(rem), sp_td("focus.reminder",
|
||||
"Recap to remember: %s. Before answering, check whether "
|
||||
"the last step moved closer to the goal; if not, say so "
|
||||
"and name the next step. When the goal is fully achieved, "
|
||||
"end your final answer with the single line "
|
||||
"GOAL_COMPLETE."), r);
|
||||
snprintf(text, sizeof(text), "[focus] %s", rem);
|
||||
if (insert_before_user(conv, text) != 0)
|
||||
return -1;
|
||||
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
last_reminder = turn;
|
||||
force = 0;
|
||||
reminders++;
|
||||
snprintf(widget_text, sizeof(widget_text), "%u reminders, every %u turns",
|
||||
reminders, every);
|
||||
n = reminders;
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
{
|
||||
char note[160];
|
||||
|
||||
snprintf(note, sizeof(note), sp_td("focus.note_recap",
|
||||
"recap applied (turn %u, every %u turns)"), turn, every);
|
||||
(void)sp_host_status_msg(h, note);
|
||||
}
|
||||
(void)n;
|
||||
focus_publish(h);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* /goal <text> set the goal at runtime, effective from the next request
|
||||
* /goal <text> set the goal; the engine starts the recap turn
|
||||
* /goal show what it is now
|
||||
* /recap force the reminder into the next turn
|
||||
*/
|
||||
static int
|
||||
focus_command(struct sp_host *h, const char *args, struct sp_buf *out,
|
||||
void *ctx)
|
||||
{
|
||||
char g[GOAL_MAX + 1];
|
||||
char g[GOAL_MAX + 1], saveerr[256] = "";
|
||||
unsigned n;
|
||||
int done;
|
||||
|
||||
(void)ctx;
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
focus_session_sync(h);
|
||||
if (args == NULL || *args == '\0') {
|
||||
snprintf(g, sizeof(g), "%s", goal);
|
||||
n = reminders;
|
||||
done = strcmp(goal_state, "succeeded") == 0;
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
if (g[0] == '\0')
|
||||
return sp_buf_puts(out, sp_td("focus.none", "no goal set (/goal <text>)"));
|
||||
if (done)
|
||||
return sp_buf_printf(out, sp_td("focus.status_done",
|
||||
"goal: %s [succeeded] (%u recaps, every %u turns)"),
|
||||
g, n, every);
|
||||
return sp_buf_printf(out, sp_td("focus.status",
|
||||
"goal: %s (%u reminders, every %u turns)"), g, n, every);
|
||||
"goal: %s (%u recaps, every %u turns)"), g, n, every);
|
||||
}
|
||||
snprintf(goal, sizeof(goal), "%.*s", GOAL_MAX, args);
|
||||
if (strlen(args) > GOAL_MAX)
|
||||
snprintf(goal + GOAL_MAX - 24, 25, "...[gekuerzt]");
|
||||
recap[0] = '\0';
|
||||
recap_pending = 1;
|
||||
snprintf(goal_state, sizeof(goal_state), "open");
|
||||
announced = 0;
|
||||
armed = 0;
|
||||
reminders = 0;
|
||||
last_reminder = 0;
|
||||
force = 0;
|
||||
snprintf(g, sizeof(g), "%s", goal);
|
||||
{
|
||||
const char *dir = sp_host_session_dir(h);
|
||||
const char *id = sp_host_session_id(h);
|
||||
|
||||
if (dir != NULL && *dir != '\0' && id != NULL && *id != '\0') {
|
||||
struct sp_buf serr;
|
||||
|
||||
if (sp_buf_init(&serr) == 0) {
|
||||
if (sp_session_set_goal(dir, id, goal, &serr) != 0)
|
||||
snprintf(saveerr, sizeof(saveerr), "%s",
|
||||
serr.p != NULL ? serr.p :
|
||||
"not saved");
|
||||
sp_buf_free(&serr);
|
||||
}
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
/* publish now, so the sidebar does not wait for the next tick */
|
||||
{
|
||||
char line[192];
|
||||
|
||||
snprintf(line, sizeof(line), "%.160s%s", g,
|
||||
strlen(g) > 160 ? "..." : "");
|
||||
(void)sp_host_widget_text(h, "focus", line);
|
||||
}
|
||||
return sp_buf_printf(out, sp_td("focus.set", "goal set: %s"), g);
|
||||
}
|
||||
|
||||
static int
|
||||
recap_command(struct sp_host *h, const char *args, struct sp_buf *out,
|
||||
void *ctx)
|
||||
{
|
||||
(void)h;
|
||||
(void)args;
|
||||
(void)ctx;
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
if (goal[0] == '\0') {
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
return sp_buf_puts(out, sp_td("focus.none", "no goal set (/goal <text>)"));
|
||||
}
|
||||
force = 1; /* the next turn gets a reminder */
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
return sp_buf_puts(out, sp_td("focus.recap",
|
||||
"reminder scheduled for the next turn"));
|
||||
focus_publish(h);
|
||||
(void)sp_buf_printf(out, sp_td("focus.set", "goal set: %s"), g);
|
||||
if (saveerr[0] != '\0')
|
||||
sp_buf_printf(out, " (%s)", saveerr);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
focus_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
{
|
||||
char line[192];
|
||||
char line[sizeof(widget_text)];
|
||||
int check = 0;
|
||||
|
||||
(void)ctx;
|
||||
pthread_mutex_lock(&focus_lock);
|
||||
if (goal[0] == '\0')
|
||||
line[0] = '\0'; /* no goal: the sidebar says nothing */
|
||||
else
|
||||
snprintf(line, sizeof(line), "%.160s%s",
|
||||
goal, strlen(goal) > 160 ? "..." : "");
|
||||
focus_session_sync(h);
|
||||
check = armed && goal[0] != '\0' &&
|
||||
strcmp(goal_state, "succeeded") != 0 &&
|
||||
session_goal_complete(h);
|
||||
if (!check) {
|
||||
if (goal[0] == '\0')
|
||||
line[0] = '\0'; /* no goal: the sidebar says nothing */
|
||||
else
|
||||
snprintf(line, sizeof(line), "%s%.160s%s",
|
||||
strcmp(goal_state, "succeeded") == 0 ?
|
||||
"[done] " : "", goal,
|
||||
strlen(goal) > 160 ? "..." : "");
|
||||
}
|
||||
pthread_mutex_unlock(&focus_lock);
|
||||
if (check) {
|
||||
focus_mark_succeeded(h);
|
||||
return 0;
|
||||
}
|
||||
return sp_host_widget_text(h, name, line);
|
||||
}
|
||||
|
||||
@@ -187,10 +579,19 @@ focus_init(struct sp_host *h)
|
||||
const char *e = getenv("SPLINTER_FOCUS_EVERY");
|
||||
|
||||
memset(goal, 0, sizeof(goal));
|
||||
memset(recap, 0, sizeof(recap));
|
||||
memset(env_goal, 0, sizeof(env_goal));
|
||||
session_id[0] = '\0';
|
||||
recap_pending = 0;
|
||||
snprintf(goal_state, sizeof(goal_state), "open");
|
||||
announced = 0;
|
||||
armed = 0;
|
||||
if (g != NULL) {
|
||||
snprintf(goal, sizeof(goal), "%.*s", GOAL_MAX, g);
|
||||
snprintf(env_goal, sizeof(env_goal), "%.*s", GOAL_MAX, g);
|
||||
if (strlen(g) > GOAL_MAX)
|
||||
snprintf(goal + GOAL_MAX - 24, 25, "...[gekuerzt]");
|
||||
snprintf(env_goal + GOAL_MAX - 24, 25,
|
||||
"...[gekuerzt]");
|
||||
snprintf(goal, sizeof(goal), "%s", env_goal);
|
||||
}
|
||||
if (e != NULL && atoi(e) > 0 && atoi(e) < 1000)
|
||||
every = (unsigned)atoi(e);
|
||||
@@ -199,15 +600,13 @@ focus_init(struct sp_host *h)
|
||||
return -1;
|
||||
if (sp_host_add_command(h, "goal", focus_command, NULL) != 0)
|
||||
return -1;
|
||||
if (sp_host_add_command(h, "recap", recap_command, NULL) != 0)
|
||||
return -1;
|
||||
if (sp_host_add_widget(h, &w) != 0)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin focus_plugin = {
|
||||
SP_PLUGIN_ABI, "focus", "1.0.0", focus_init, NULL, NULL
|
||||
SP_PLUGIN_ABI, "focus", "1.1.0", focus_init, NULL, NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+45
-17
@@ -20,6 +20,7 @@
|
||||
* - the whitelist matches the tool and its arguments, never the mood.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -260,25 +261,48 @@ whitelisted(const char *tool, const char *args)
|
||||
|
||||
/*
|
||||
* sh -c '<cmd>' sh '<arg>': the command string is parsed, the argument is not.
|
||||
* Returns the wait status, like system(3).
|
||||
* Returns the wait status, like system(3). After 'secs' seconds the command and
|
||||
* everything it started (its own process group) are killed and *timed_out is
|
||||
* set: a parent who is not looking does not approve anything, and the child is
|
||||
* not kept waiting forever either.
|
||||
*/
|
||||
static int
|
||||
run_with_arg(const char *cmd, const char *arg)
|
||||
run_with_arg(const char *cmd, const char *arg, unsigned secs, int *timed_out)
|
||||
{
|
||||
pid_t child;
|
||||
int status;
|
||||
pid_t child, r;
|
||||
int status;
|
||||
struct timespec start, now, nap = { 0, 50000000L };
|
||||
|
||||
*timed_out = 0;
|
||||
child = fork();
|
||||
if (child < 0)
|
||||
return -1;
|
||||
if (child == 0) {
|
||||
(void)setpgid(0, 0);
|
||||
execl("/bin/sh", "sh", "-c", cmd, "sh", arg, (char *)NULL);
|
||||
_exit(127);
|
||||
}
|
||||
while (waitpid(child, &status, 0) < 0)
|
||||
if (errno != EINTR)
|
||||
(void)setpgid(child, child);
|
||||
(void)clock_gettime(CLOCK_MONOTONIC, &start);
|
||||
for (;;) {
|
||||
r = waitpid(child, &status, WNOHANG);
|
||||
if (r == child)
|
||||
return status;
|
||||
if (r < 0 && errno != EINTR)
|
||||
return -1;
|
||||
return status;
|
||||
(void)clock_gettime(CLOCK_MONOTONIC, &now);
|
||||
if ((now.tv_sec - start.tv_sec) * 1000L +
|
||||
(now.tv_nsec - start.tv_nsec) / 1000000L >=
|
||||
(long)secs * 1000L) {
|
||||
*timed_out = 1;
|
||||
(void)kill(-child, SIGKILL);
|
||||
(void)kill(child, SIGKILL);
|
||||
while (waitpid(child, &status, 0) < 0 && errno == EINTR)
|
||||
;
|
||||
return -1;
|
||||
}
|
||||
(void)nanosleep(&nap, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -289,7 +313,7 @@ static int
|
||||
ask_parent(const char *tool, const char *args, char *reason, size_t reason_len)
|
||||
{
|
||||
char cmd[1024], request[1024];
|
||||
int rc;
|
||||
int rc, timed_out;
|
||||
|
||||
/*
|
||||
* The general ack mechanism first: a request file plus whichever channels are
|
||||
@@ -327,12 +351,12 @@ ask_parent(const char *tool, const char *args, char *reason, size_t reason_len)
|
||||
snprintf(cmd, sizeof(cmd), "%s \"$1\"", approve_cmd);
|
||||
snprintf(request, sizeof(request), "Anfrage: %s %s", tool,
|
||||
args != NULL ? args : "");
|
||||
rc = run_with_arg(cmd, request);
|
||||
if (rc == 0)
|
||||
rc = run_with_arg(cmd, request, timeout_s, &timed_out);
|
||||
if (rc == 0 && !timed_out)
|
||||
return 1;
|
||||
snprintf(reason, reason_len, "ein Erwachsener hat nicht zugestimmt (%s)",
|
||||
WIFEXITED(rc) && WEXITSTATUS(rc) == 124 ? "Zeit abgelaufen" :
|
||||
"abgelehnt");
|
||||
timed_out || (rc != -1 && WIFEXITED(rc) && WEXITSTATUS(rc) == 124) ?
|
||||
"Zeit abgelaufen" : "abgelehnt");
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -423,6 +447,15 @@ kids_gate(struct sp_host *h, const char *tool, int auth, const char *args,
|
||||
char *reason, size_t reason_len)
|
||||
{
|
||||
(void)h;
|
||||
/*
|
||||
* The budget comes first: when the day is over every tool is refused,
|
||||
* reading and the parent's own domain list included.
|
||||
*/
|
||||
if (quota_left() == 0) {
|
||||
snprintf(reason, reason_len, "fuer heute ist Schluss (%ld von %u "
|
||||
"Minuten)", used_seconds / 60, daily_minutes);
|
||||
return 0;
|
||||
}
|
||||
if (strcmp(tool, "websearch") == 0 || strcmp(tool, "webfetch") == 0) {
|
||||
/*
|
||||
* The curated list is the safe ground and works in every mode: a
|
||||
@@ -447,11 +480,6 @@ kids_gate(struct sp_host *h, const char *tool, int auth, const char *args,
|
||||
} else if (auth == SP_AUTH_READ)
|
||||
return 1;
|
||||
|
||||
if (quota_left() == 0) {
|
||||
snprintf(reason, reason_len, "fuer heute ist Schluss (%ld von %u "
|
||||
"Minuten)", used_seconds / 60, daily_minutes);
|
||||
return 0;
|
||||
}
|
||||
load_rules();
|
||||
if (whitelisted(tool, args))
|
||||
return 1;
|
||||
|
||||
+445
-9
@@ -15,15 +15,33 @@
|
||||
* call, nothing that makes a run unreproducible. The harder variant (an LLM
|
||||
* writes the summary) is a different plugin, not a flag on this one.
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "mcp.h"
|
||||
|
||||
#define KEEP_TAIL 6 /* messages always kept verbatim */
|
||||
#define KEEP_TAIL 6 /* default: messages always kept verbatim */
|
||||
#define PREVIEW 120 /* chars of the oldest dropped message */
|
||||
#define TOOL_TRIM 8192 /* default: older tool outputs are cut to this */
|
||||
#define RECALL_HIT 1600 /* bytes shown of one matching line */
|
||||
#define RECALL_TOTAL 12000 /* bytes of matches, so recall stays cheap */
|
||||
|
||||
static size_t keep_tail = KEEP_TAIL;
|
||||
static size_t tool_trim = TOOL_TRIM;
|
||||
|
||||
/* what the widget and the status segment show; written by the compactor */
|
||||
static pthread_mutex_t lcm_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static unsigned compactions;
|
||||
static size_t dropped_total;
|
||||
static unsigned trimmed_total;
|
||||
static size_t last_msgs_from, last_msgs_to;
|
||||
static size_t last_bytes_from, last_bytes_to;
|
||||
|
||||
static int
|
||||
is_role(const struct sp_msg *m, const char *role)
|
||||
@@ -31,42 +49,205 @@ is_role(const struct sp_msg *m, const char *role)
|
||||
return m->role != NULL && strcmp(m->role, role) == 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The engine's own continuation prompts. They arrive as user messages, but they
|
||||
* are not the question: after /resume the newest user message is "Continue with
|
||||
* the task ...", and pinning that keeps the keystroke while the task it was
|
||||
* meant to continue is cut away. Measured: a session resumed after a rate limit
|
||||
* woke up with the prompt, one tool call and its error, and no task at all.
|
||||
*/
|
||||
static int
|
||||
is_continuation_prompt(const struct sp_msg *m)
|
||||
{
|
||||
static const char *const pfx[] = {
|
||||
"Continue with the task you were working on",
|
||||
"Continue working toward this goal",
|
||||
};
|
||||
size_t i;
|
||||
|
||||
if (m->content == NULL)
|
||||
return 0;
|
||||
for (i = 0; i < sizeof(pfx) / sizeof(pfx[0]); i++)
|
||||
if (strncmp(m->content, pfx[i], strlen(pfx[i])) == 0)
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* the first line of a text, at most n bytes, for the marker */
|
||||
static void
|
||||
first_line(const char *s, char *out, size_t cap, size_t n)
|
||||
{
|
||||
size_t i = 0;
|
||||
|
||||
while (s[i] != '\0' && i < n && s[i] != '\n' && i + 1 < cap) {
|
||||
unsigned char c = (unsigned char)s[i];
|
||||
|
||||
out[i] = (c >= 32 && c != 127) ? (char)c : ' ';
|
||||
i++;
|
||||
}
|
||||
out[i] = '\0';
|
||||
}
|
||||
|
||||
/*
|
||||
* Tool outputs are the bulk of a long conversation. Before messages are
|
||||
* dropped, every old observation is cut to a head and a tail with a marker in
|
||||
* between; the middle is still in the session log, where the recall tool finds
|
||||
* it. The recent tail (the messages we keep verbatim) is never touched, so the
|
||||
* model always has the output it just asked for.
|
||||
*/
|
||||
static int
|
||||
trim_tools(struct sp_conv *conv, size_t first, size_t end, size_t cap)
|
||||
{
|
||||
size_t i;
|
||||
int n = 0;
|
||||
|
||||
if (cap == 0)
|
||||
return 0;
|
||||
for (i = first; i < end; i++) {
|
||||
struct sp_msg *m = &conv->v[i];
|
||||
size_t len, head, tail, off, room;
|
||||
char *hint = "", *nb;
|
||||
|
||||
if (!is_role(m, "tool") || m->content == NULL)
|
||||
continue;
|
||||
len = strlen(m->content);
|
||||
if (len <= cap)
|
||||
continue;
|
||||
head = cap / 2;
|
||||
tail = cap / 4;
|
||||
if (head + tail >= len)
|
||||
continue;
|
||||
{
|
||||
static char hbuf[72];
|
||||
|
||||
first_line(m->content, hbuf, sizeof(hbuf), 60);
|
||||
hint = hbuf;
|
||||
}
|
||||
nb = malloc(head + tail + 512);
|
||||
if (nb == NULL)
|
||||
continue;
|
||||
memcpy(nb, m->content, head);
|
||||
off = head;
|
||||
room = head + tail + 512 - off;
|
||||
off += (size_t)snprintf(nb + off, room,
|
||||
"\n[lcm] %zu bytes of tool output cut; recall \"%s\"\n",
|
||||
len - head - tail, hint);
|
||||
memcpy(nb + off, m->content + len - tail, tail);
|
||||
off += tail;
|
||||
nb[off] = '\0';
|
||||
free(m->content);
|
||||
m->content = nb;
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/* one message as sp_conv_bytes() counts it */
|
||||
static size_t
|
||||
msg_bytes(const struct sp_msg *m)
|
||||
{
|
||||
return (m->role != NULL ? strlen(m->role) : 0) +
|
||||
(m->name != NULL ? strlen(m->name) : 0) +
|
||||
(m->content != NULL ? strlen(m->content) : 0) +
|
||||
(m->calls != NULL ? strlen(m->calls) : 0) + 16;
|
||||
}
|
||||
|
||||
static int
|
||||
lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
unsigned turn)
|
||||
{
|
||||
size_t bytes, i, drop, first, keep_from;
|
||||
size_t msgs_before, bytes_before;
|
||||
char preview[PREVIEW + 1];
|
||||
char summary[512];
|
||||
size_t n_user = 0, n_asst = 0, n_tool = 0;
|
||||
size_t drop_bytes = 0, add_bytes;
|
||||
long pin_at = -1;
|
||||
char *pin_content = NULL, *pin_name = NULL;
|
||||
int trimmed, pinned = 0;
|
||||
const char *oldest;
|
||||
|
||||
(void)turn;
|
||||
(void)h;
|
||||
if (conv == NULL || conv->n <= KEEP_TAIL + 1)
|
||||
if (conv == NULL || conv->n <= keep_tail + 1)
|
||||
return 0;
|
||||
if (budget == 0)
|
||||
return 0; /* no byte budget: nothing to do */
|
||||
bytes = sp_conv_bytes(conv);
|
||||
msgs_before = conv->n;
|
||||
bytes_before = bytes;
|
||||
if (bytes <= budget)
|
||||
return 0; /* fits: nothing to do */
|
||||
|
||||
/* a leading system prompt stays; everything else may go */
|
||||
first = is_role(&conv->v[0], "system") ? 1 : 0;
|
||||
keep_from = conv->n - KEEP_TAIL;
|
||||
keep_from = conv->n - keep_tail;
|
||||
/*
|
||||
* The tail must not start with a tool result: its assistant turn, the
|
||||
* one carrying the tool_call, would be gone, and a provider answers an
|
||||
* orphaned tool message with a 400. Such results go with their call.
|
||||
*
|
||||
* Walk BACK to that assistant, not forward past the results. Forward
|
||||
* was the first try and it silently shrank the tail: a turn with two
|
||||
* results at the boundary kept four messages where keep_tail says six.
|
||||
* Measured 2026-11-21 on system + user + [assistant, tool, tool] x4 +
|
||||
* user: fifteen messages, tail of six, result was a tail of four.
|
||||
*/
|
||||
while (keep_from < conv->n && is_role(&conv->v[keep_from], "tool"))
|
||||
keep_from++;
|
||||
while (keep_from < conv->n && keep_from > first &&
|
||||
is_role(&conv->v[keep_from], "tool"))
|
||||
keep_from--;
|
||||
if (keep_from >= conv->n || keep_from <= first)
|
||||
return 0;
|
||||
/*
|
||||
* First the cheap cut: old tool outputs. If that is enough the messages
|
||||
* stay, and only the observations shrink.
|
||||
*/
|
||||
trimmed = trim_tools(conv, first, keep_from, tool_trim);
|
||||
if (trimmed > 0) {
|
||||
pthread_mutex_lock(&lcm_lock);
|
||||
trimmed_total += (unsigned)trimmed;
|
||||
pthread_mutex_unlock(&lcm_lock);
|
||||
bytes = sp_conv_bytes(conv);
|
||||
if (bytes <= budget) {
|
||||
pthread_mutex_lock(&lcm_lock);
|
||||
compactions++;
|
||||
dropped_total += 0;
|
||||
last_msgs_from = last_msgs_to = conv->n;
|
||||
last_bytes_from = bytes_before;
|
||||
last_bytes_to = bytes;
|
||||
pthread_mutex_unlock(&lcm_lock);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* The newest user message is the task being answered. A long tool loop
|
||||
* can push it out of the verbatim tail; dropping it made the model ask
|
||||
* "what was the question?" and dig it out with recall. Pin it and put
|
||||
* it back right after the summary. Only a user message is pinned: with
|
||||
* none in the cut range nothing is (pin_at stays -1), never the system
|
||||
* prompt or an assistant turn under the wrong role. A continuation prompt
|
||||
* is skipped: it is the harness talking, not the task.
|
||||
*/
|
||||
for (i = conv->n; i > first; i--) {
|
||||
if (!is_role(&conv->v[i - 1], "user"))
|
||||
continue;
|
||||
if (is_continuation_prompt(&conv->v[i - 1]))
|
||||
continue;
|
||||
pin_at = (long)(i - 1);
|
||||
break;
|
||||
}
|
||||
if (pin_at >= 0 && (size_t)pin_at < keep_from) {
|
||||
pin_content = strdup(conv->v[pin_at].content != NULL ?
|
||||
conv->v[pin_at].content : "");
|
||||
if (conv->v[pin_at].name != NULL)
|
||||
pin_name = strdup(conv->v[pin_at].name);
|
||||
pinned = pin_content != NULL;
|
||||
}
|
||||
drop = keep_from - first;
|
||||
|
||||
oldest = conv->v[first].content; /* the oldest one that goes */
|
||||
for (i = first; i < keep_from; i++) {
|
||||
drop_bytes += msg_bytes(&conv->v[i]);
|
||||
if (is_role(&conv->v[i], "user"))
|
||||
n_user++;
|
||||
else if (is_role(&conv->v[i], "assistant"))
|
||||
@@ -74,12 +255,45 @@ lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
else if (is_role(&conv->v[i], "tool"))
|
||||
n_tool++;
|
||||
}
|
||||
if (pinned && n_user > 0)
|
||||
n_user--; /* the pinned one is kept */
|
||||
snprintf(preview, sizeof(preview), "%s", oldest != NULL ? oldest : "");
|
||||
snprintf(summary, sizeof(summary),
|
||||
"[lcm] %zu messages compacted out (user %zu, assistant %zu, tool %zu) "
|
||||
"to fit %zu bytes; the verbatim tail of %zu messages follows. "
|
||||
"to fit %zu bytes; the verbatim tail of %zu messages follows.%s "
|
||||
"Oldest dropped turn began with: \"%s\"",
|
||||
drop, n_user, n_asst, n_tool, budget, conv->n - keep_from, preview);
|
||||
drop - (pinned ? 1 : 0), n_user, n_asst, n_tool,
|
||||
budget, conv->n - keep_from,
|
||||
pinned ? " The current question was kept." :
|
||||
(trimmed > 0 ? " Older tool output was cut too (recall still has it)." :
|
||||
""),
|
||||
preview);
|
||||
add_bytes = strlen("system") + strlen(summary) + 16;
|
||||
if (pinned)
|
||||
add_bytes += strlen("user") + strlen(pin_content) +
|
||||
(pin_name != NULL ? strlen(pin_name) : 0) + 16;
|
||||
/*
|
||||
* A summary and the pinned question are messages too. If the cut would
|
||||
* remove no more bytes than it adds, the conversation grows (N -> N+1
|
||||
* was the /resume loop) and the context never shrinks. Keep the output
|
||||
* trim, skip the message rewrite. Bytes, not messages: the budget is in
|
||||
* bytes, and one huge message is worth cutting even if it is the only
|
||||
* one that goes.
|
||||
*/
|
||||
if (drop_bytes <= add_bytes) {
|
||||
free(pin_content);
|
||||
free(pin_name);
|
||||
if (trimmed > 0) {
|
||||
pthread_mutex_lock(&lcm_lock);
|
||||
compactions++;
|
||||
last_msgs_from = last_msgs_to = conv->n;
|
||||
last_bytes_from = bytes_before;
|
||||
last_bytes_to = sp_conv_bytes(conv);
|
||||
pthread_mutex_unlock(&lcm_lock);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (i = first; i < keep_from; i++) {
|
||||
free(conv->v[i].role);
|
||||
@@ -99,17 +313,239 @@ lcm_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
m.role = "system";
|
||||
m.content = summary;
|
||||
if (sp_conv_insert(conv, first, &m) != 0)
|
||||
return -1;
|
||||
goto fail;
|
||||
}
|
||||
if (pinned) {
|
||||
struct sp_msg m;
|
||||
|
||||
memset(&m, 0, sizeof(m));
|
||||
m.role = "user";
|
||||
m.name = pin_name;
|
||||
m.content = pin_content;
|
||||
if (sp_conv_insert(conv, first + 1, &m) != 0)
|
||||
goto fail;
|
||||
}
|
||||
{
|
||||
pthread_mutex_lock(&lcm_lock);
|
||||
compactions++;
|
||||
dropped_total += drop;
|
||||
last_msgs_from = msgs_before;
|
||||
last_msgs_to = conv->n;
|
||||
last_bytes_from = bytes_before;
|
||||
last_bytes_to = sp_conv_bytes(conv);
|
||||
pthread_mutex_unlock(&lcm_lock);
|
||||
}
|
||||
free(pin_content);
|
||||
free(pin_name);
|
||||
return 1;
|
||||
|
||||
fail:
|
||||
free(pin_content);
|
||||
free(pin_name);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* case-blind substring for the recall tool */
|
||||
static int
|
||||
has_ci(const char *hay, const char *needle)
|
||||
{
|
||||
size_t n = strlen(needle), i;
|
||||
const char *p;
|
||||
|
||||
for (p = hay; *p != '\0'; p++) {
|
||||
for (i = 0; i < n && p[i] != '\0'; i++)
|
||||
if (tolower((unsigned char)p[i]) !=
|
||||
tolower((unsigned char)needle[i]))
|
||||
break;
|
||||
if (i == n)
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* What compaction dropped is still in the session log. This reads it: the
|
||||
* model can go back to an earlier turn instead of guessing, and the operator
|
||||
* can prove what was said.
|
||||
*/
|
||||
static int
|
||||
lcm_recall(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char query[256] = "", path[800];
|
||||
char *line = NULL;
|
||||
size_t linecap = 0;
|
||||
ssize_t len;
|
||||
struct sp_host *h = ctx;
|
||||
const char *dir = sp_host_session_dir(h);
|
||||
const char *id = sp_host_session_id(h);
|
||||
mcp_json *v;
|
||||
const char *q;
|
||||
FILE *f;
|
||||
int limit = 10, n = 0;
|
||||
|
||||
if (args != NULL && args[0] == '{') {
|
||||
v = mcp_parse(args);
|
||||
if (v != NULL) {
|
||||
q = mcp_arg_string(v, "query");
|
||||
if (q != NULL)
|
||||
snprintf(query, sizeof(query), "%s", q);
|
||||
limit = mcp_arg_int(v, "limit", 10);
|
||||
mcp_json_free(v);
|
||||
}
|
||||
}
|
||||
if (query[0] == '\0')
|
||||
return sp_buf_puts(out, "error: 'query' is required");
|
||||
if (limit < 1 || limit > 50)
|
||||
limit = 10;
|
||||
if (dir == NULL || *dir == '\0' || id == NULL || *id == '\0')
|
||||
return sp_buf_puts(out, "error: no session log");
|
||||
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, id);
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL)
|
||||
return sp_buf_puts(out, "error: cannot read the session log");
|
||||
/*
|
||||
* getline, not fgets: one session line is one JSON object, and an
|
||||
* observation can be tens of KiB. An 8 KiB buffer cut such a line into
|
||||
* pieces, so a match in the middle came back without its context and a
|
||||
* long hit was printed in full. A hit now shows head and tail and says
|
||||
* how much was cut; the whole answer is bounded.
|
||||
*/
|
||||
while (n < limit && (len = getline(&line, &linecap, f)) != -1) {
|
||||
if (!has_ci(line, query))
|
||||
continue;
|
||||
n++;
|
||||
if ((size_t)len > RECALL_HIT) {
|
||||
size_t head = RECALL_HIT - 400, tail = 400;
|
||||
|
||||
sp_buf_printf(out, "%.*s\n[lcm] %zd bytes cut (recall)\n",
|
||||
(int)head, line,
|
||||
len - (ssize_t)(head + tail));
|
||||
sp_buf_puts(out, line + len - (ssize_t)tail);
|
||||
if (line[len - 1] != '\n')
|
||||
sp_buf_puts(out, "\n");
|
||||
} else {
|
||||
sp_buf_puts(out, line);
|
||||
}
|
||||
if (out->len >= RECALL_TOTAL) {
|
||||
sp_buf_puts(out, "... more matches not shown (recall "
|
||||
"limit)\n");
|
||||
break;
|
||||
}
|
||||
}
|
||||
free(line);
|
||||
fclose(f);
|
||||
if (n == 0)
|
||||
sp_buf_printf(out, "no line in the session log contains '%s'",
|
||||
query);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_tool recall_tool = {
|
||||
"recall",
|
||||
"Search the session log for text that is no longer in the context "
|
||||
"(compaction drops it from the prompt, not from the log). Use it "
|
||||
"before guessing about something that happened earlier.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"query\":{\"type\":\"string\",\"description\":\"text to find\"},"
|
||||
"\"limit\":{\"type\":\"integer\",\"description\":\"max matching lines, "
|
||||
"default 10\"}},\"required\":[\"query\"]}",
|
||||
SP_AUTH_READ,
|
||||
lcm_recall,
|
||||
NULL,
|
||||
NULL
|
||||
};
|
||||
|
||||
static const struct sp_compactor lcm = { "lcm", lcm_compact };
|
||||
|
||||
/* "12.3k" for a token count, "842" below a thousand */
|
||||
static void
|
||||
human(size_t n, char *buf, size_t cap)
|
||||
{
|
||||
if (n >= 1000000)
|
||||
snprintf(buf, cap, "%.1fM", (double)n / 1e6);
|
||||
else if (n >= 1000)
|
||||
snprintf(buf, cap, "%.1fk", (double)n / 1e3);
|
||||
else
|
||||
snprintf(buf, cap, "%zu", n);
|
||||
}
|
||||
|
||||
/*
|
||||
* What compaction did, in the sidebar: the context the last request carried,
|
||||
* how often lcm cut, and how the last cut looked. The counters are the
|
||||
* compactor's own, not a second estimate.
|
||||
*/
|
||||
static int
|
||||
lcm_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
{
|
||||
struct sp_meter m;
|
||||
char used[24], max[24], text[512];
|
||||
unsigned c;
|
||||
size_t dropped, from, to;
|
||||
unsigned trimmed;
|
||||
size_t bf, bt;
|
||||
|
||||
(void)ctx;
|
||||
sp_host_meter_get(h, &m);
|
||||
pthread_mutex_lock(&lcm_lock);
|
||||
c = compactions;
|
||||
dropped = dropped_total;
|
||||
trimmed = trimmed_total;
|
||||
from = last_msgs_from;
|
||||
to = last_msgs_to;
|
||||
bf = last_bytes_from;
|
||||
bt = last_bytes_to;
|
||||
pthread_mutex_unlock(&lcm_lock);
|
||||
human(m.ctx_used, used, sizeof(used));
|
||||
if (m.ctx_max > 0)
|
||||
human(m.ctx_max, max, sizeof(max));
|
||||
else
|
||||
snprintf(max, sizeof(max), "?");
|
||||
snprintf(text, sizeof(text),
|
||||
"ctx %s/%s\n"
|
||||
"compacted %u cut %zu msgs\n"
|
||||
"last %zu->%zu msgs %zu->%zu B\n"
|
||||
"tools trimmed %u",
|
||||
used, max, c, dropped, from, to, bf, bt, trimmed);
|
||||
return sp_host_widget_text(h, name, text);
|
||||
}
|
||||
|
||||
static void
|
||||
lcm_status(struct sp_host *h, char *buf, size_t len)
|
||||
{
|
||||
unsigned c;
|
||||
|
||||
(void)h;
|
||||
pthread_mutex_lock(&lcm_lock);
|
||||
c = compactions;
|
||||
pthread_mutex_unlock(&lcm_lock);
|
||||
snprintf(buf, len, "compact %u", c);
|
||||
}
|
||||
|
||||
static int
|
||||
lcm_init(struct sp_host *h)
|
||||
{
|
||||
return sp_host_add_compactor(h, &lcm);
|
||||
static struct sp_tool rt = recall_tool;
|
||||
const char *v;
|
||||
|
||||
v = sp_host_plugin_config(h, "lcm", "keep");
|
||||
if (v != NULL && atoi(v) > 0 && atoi(v) < 1000)
|
||||
keep_tail = (size_t)atoi(v);
|
||||
v = sp_host_plugin_config(h, "lcm", "tool_trim");
|
||||
if (v != NULL && atoi(v) >= 0)
|
||||
tool_trim = (size_t)atoi(v);
|
||||
static const struct sp_widget w = {
|
||||
"lcm", lcm_tick, NULL, NULL, 2000
|
||||
};
|
||||
static const struct sp_status seg = { "compact", lcm_status };
|
||||
|
||||
rt.ctx = h;
|
||||
if (sp_host_add_compactor(h, &lcm) != 0)
|
||||
return -1;
|
||||
if (sp_host_add_widget(h, &w) != 0)
|
||||
return -1;
|
||||
if (sp_host_add_status(h, &seg) != 0)
|
||||
return -1;
|
||||
return sp_host_add_tool(h, &rt);
|
||||
}
|
||||
|
||||
static const struct sp_plugin lcm_plugin = {
|
||||
|
||||
+369
-106
@@ -63,24 +63,58 @@ struct server {
|
||||
char cmd[SP_CONFIG_MCP_CMD];
|
||||
char session[160]; /* Mcp-Session-Id, echoed back */
|
||||
pid_t pid;
|
||||
volatile pid_t http_pid; /* the curl of a round trip in flight */
|
||||
FILE *to; /* stdio: our writes become the server's stdin */
|
||||
int from; /* stdio: its stdout, read without stdio */
|
||||
struct sp_buf in; /* bytes read but not yet a whole line */
|
||||
int next_id;
|
||||
int dead;
|
||||
int ntools;
|
||||
int up; /* handshake done and answering */
|
||||
volatile int up; /* handshake done and answering */
|
||||
int registered; /* its tools are in the registry (once) */
|
||||
pthread_mutex_t lock; /* one round trip at a time */
|
||||
pthread_t th; /* the reconnect thread, joined on shutdown */
|
||||
int th_started;
|
||||
int th_done; /* set under done_mu right before it returns */
|
||||
};
|
||||
|
||||
#define RETRY_S 10
|
||||
static volatile int stopping;
|
||||
/*
|
||||
* Written by the main thread in mcp_shutdown, read by every server thread in
|
||||
* its loop. `volatile` was not enough: it stops the compiler from caching the
|
||||
* value but gives no ordering, so a server thread could read 0 after the
|
||||
* shutdown had already killed its child and keep using buffers that teardown
|
||||
* frees. TSan reported the race as a write in mcp_shutdown against a read in
|
||||
* server_thread_body; the accessors below make it visible and ordered.
|
||||
*/
|
||||
static int stopping;
|
||||
|
||||
static int
|
||||
is_stopping(void)
|
||||
{
|
||||
return __atomic_load_n(&stopping, __ATOMIC_ACQUIRE);
|
||||
}
|
||||
|
||||
static void
|
||||
set_stopping(int v)
|
||||
{
|
||||
__atomic_store_n(&stopping, v, __ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
static struct server sv[MAX_SERVERS];
|
||||
static size_t nsv;
|
||||
static struct sp_host *host;
|
||||
|
||||
/*
|
||||
* The server threads are joinable. Shutdown has to know they are gone before
|
||||
* it frees the buffers they read into and before the host they register tools
|
||||
* in disappears; without the join a thread could call sp_host_add_tool() into
|
||||
* a freed host. Bounded, because a thread stuck in connect() must not hang the
|
||||
* shutdown forever.
|
||||
*/
|
||||
static pthread_mutex_t done_mu = PTHREAD_MUTEX_INITIALIZER;
|
||||
static pthread_cond_t done_cv = PTHREAD_COND_INITIALIZER;
|
||||
|
||||
/* A registered tool knows which server it belongs to and what it is called there. */
|
||||
struct toolref {
|
||||
size_t srv;
|
||||
@@ -88,44 +122,81 @@ struct toolref {
|
||||
};
|
||||
|
||||
/*
|
||||
* Slice the JSON object that follows "inputSchema" out of the raw line.
|
||||
* Print a parsed JSON value back as text.
|
||||
*
|
||||
* libmcp parses but does not print, and a tool schema has to be handed back to
|
||||
* the model exactly as the server wrote it. Brace matching that respects
|
||||
* strings and escapes is small and has no dependency.
|
||||
* libmcp parses but does not print. A tool's schema has to be handed to the
|
||||
* model; it is taken from the tool's own entry in the parsed tools array, so a
|
||||
* tool without one (or a description that mentions "inputSchema") can never
|
||||
* hand its neighbour's schema over. Key order is kept; numbers are printed as
|
||||
* integers when they are integral.
|
||||
*/
|
||||
static const char *
|
||||
slice_object(const char *at, size_t *lenp)
|
||||
static int
|
||||
json_print(struct sp_buf *b, const mcp_json *v)
|
||||
{
|
||||
const char *p = strchr(at, '{');
|
||||
const char *start;
|
||||
int depth = 0, instr = 0, escape = 0;
|
||||
size_t i;
|
||||
|
||||
if (p == NULL)
|
||||
return NULL;
|
||||
start = p;
|
||||
for (; *p != '\0'; p++) {
|
||||
if (escape) {
|
||||
escape = 0;
|
||||
continue;
|
||||
}
|
||||
if (instr) {
|
||||
if (*p == '\\')
|
||||
escape = 1;
|
||||
else if (*p == '"')
|
||||
instr = 0;
|
||||
continue;
|
||||
}
|
||||
if (*p == '"')
|
||||
instr = 1;
|
||||
else if (*p == '{')
|
||||
depth++;
|
||||
else if (*p == '}' && --depth == 0) {
|
||||
*lenp = (size_t)(p - start + 1);
|
||||
return start;
|
||||
switch (v->t) {
|
||||
case MCP_NULL:
|
||||
return sp_buf_puts(b, "null");
|
||||
case MCP_BOOL:
|
||||
return sp_buf_puts(b, v->b ? "true" : "false");
|
||||
case MCP_NUM:
|
||||
if (v->n == (double)(long long)v->n &&
|
||||
v->n > -9007199254740992.0 && v->n < 9007199254740992.0)
|
||||
return sp_buf_printf(b, "%lld", (long long)v->n);
|
||||
return sp_buf_printf(b, "%.17g", v->n);
|
||||
case MCP_STR: {
|
||||
const unsigned char *p = (const unsigned char *)
|
||||
(v->s != NULL ? v->s : "");
|
||||
|
||||
if (sp_buf_puts(b, "\"") != 0)
|
||||
return -1;
|
||||
for (; *p != '\0'; p++) {
|
||||
int rc;
|
||||
|
||||
if (*p == '"' || *p == '\\')
|
||||
rc = sp_buf_printf(b, "\\%c", *p);
|
||||
else if (*p == '\n')
|
||||
rc = sp_buf_puts(b, "\\n");
|
||||
else if (*p == '\r')
|
||||
rc = sp_buf_puts(b, "\\r");
|
||||
else if (*p == '\t')
|
||||
rc = sp_buf_puts(b, "\\t");
|
||||
else if (*p < 0x20)
|
||||
rc = sp_buf_printf(b, "\\u%04x", *p);
|
||||
else
|
||||
rc = sp_buf_add(b, (const char *)p, 1);
|
||||
if (rc != 0)
|
||||
return -1;
|
||||
}
|
||||
return sp_buf_puts(b, "\"");
|
||||
}
|
||||
return NULL;
|
||||
case MCP_ARR:
|
||||
if (sp_buf_puts(b, "[") != 0)
|
||||
return -1;
|
||||
for (i = 0; i < v->count; i++)
|
||||
if ((i > 0 && sp_buf_puts(b, ",") != 0) ||
|
||||
json_print(b, v->items[i]) != 0)
|
||||
return -1;
|
||||
return sp_buf_puts(b, "]");
|
||||
case MCP_OBJ:
|
||||
if (sp_buf_puts(b, "{") != 0)
|
||||
return -1;
|
||||
for (i = 0; i < v->count; i++) {
|
||||
mcp_json key;
|
||||
|
||||
memset(&key, 0, sizeof(key));
|
||||
key.t = MCP_STR;
|
||||
key.s = v->keys[i];
|
||||
if ((i > 0 && sp_buf_puts(b, ",") != 0) ||
|
||||
json_print(b, &key) != 0 ||
|
||||
sp_buf_puts(b, ":") != 0 ||
|
||||
json_print(b, v->items[i]) != 0)
|
||||
return -1;
|
||||
}
|
||||
return sp_buf_puts(b, "}");
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* ---- stdio transport ---- */
|
||||
@@ -349,6 +420,8 @@ http_rpc(struct server *s, const char *method, const char *params,
|
||||
|
||||
snprintf(data, sizeof(data), "@%s", body);
|
||||
args[n++] = "-sS";
|
||||
args[n++] = "--connect-timeout";
|
||||
args[n++] = "5";
|
||||
args[n++] = "-m";
|
||||
args[n++] = tmo;
|
||||
args[n++] = "-X";
|
||||
@@ -375,6 +448,14 @@ http_rpc(struct server *s, const char *method, const char *params,
|
||||
}
|
||||
hdrs[n] = NULL;
|
||||
|
||||
if (is_stopping()) {
|
||||
sp_buf_puts(err, "mcp: shutting down");
|
||||
(void)unlink(body);
|
||||
(void)unlink(hdr);
|
||||
sp_buf_free(&req);
|
||||
sp_buf_free(&out);
|
||||
return NULL;
|
||||
}
|
||||
fd = sp_curl_start(args, s->url, hdrs, 1, &pid, err);
|
||||
if (fd < 0) {
|
||||
(void)unlink(body);
|
||||
@@ -383,6 +464,8 @@ http_rpc(struct server *s, const char *method, const char *params,
|
||||
sp_buf_free(&out);
|
||||
return NULL;
|
||||
}
|
||||
/* shutdown kills it: a server that is down must not hold the exit */
|
||||
s->http_pid = pid;
|
||||
{
|
||||
char chunk[8192];
|
||||
ssize_t got;
|
||||
@@ -394,6 +477,7 @@ http_rpc(struct server *s, const char *method, const char *params,
|
||||
}
|
||||
close(fd);
|
||||
(void)waitpid(pid, &rc, 0);
|
||||
s->http_pid = 0;
|
||||
take_session(s, hdrp);
|
||||
(void)unlink(body);
|
||||
(void)unlink(hdr);
|
||||
@@ -485,7 +569,7 @@ rpc_locked(size_t which, const char *method, const char *params,
|
||||
struct sp_buf line;
|
||||
char *raw;
|
||||
|
||||
if (s->dead) {
|
||||
if (s->dead || (!s->http && (s->to == NULL || s->from <= 0))) {
|
||||
sp_buf_puts(err, "mcp: server not connected (reconnecting)");
|
||||
return NULL;
|
||||
}
|
||||
@@ -546,7 +630,8 @@ notify(struct server *s, const char *method)
|
||||
if (s->http) {
|
||||
struct sp_buf err;
|
||||
char body[600], hdr[600], data[640];
|
||||
const char *args[20], *hdrs[3];
|
||||
const char *args[24], *hdrs[3];
|
||||
char sess[200];
|
||||
struct sp_buf req;
|
||||
pid_t pid;
|
||||
int fd, n = 0;
|
||||
@@ -566,10 +651,17 @@ notify(struct server *s, const char *method)
|
||||
close(fd);
|
||||
snprintf(data, sizeof(data), "@%s", body);
|
||||
args[n++] = "-sS";
|
||||
args[n++] = "--connect-timeout";
|
||||
args[n++] = "5";
|
||||
args[n++] = "-m";
|
||||
args[n++] = HTTP_TIMEOUT_S;
|
||||
args[n++] = "-X";
|
||||
args[n++] = "POST";
|
||||
args[n++] = "-H";
|
||||
args[n++] = "Content-Type: application/json";
|
||||
args[n++] = "-H";
|
||||
args[n++] = "Accept: application/json, "
|
||||
"text/event-stream";
|
||||
args[n++] = "--data-binary";
|
||||
args[n++] = data;
|
||||
args[n++] = "-D";
|
||||
@@ -578,11 +670,21 @@ notify(struct server *s, const char *method)
|
||||
n = 0;
|
||||
if (s->header[0] != '\0')
|
||||
hdrs[n++] = s->header;
|
||||
/* the session initialize handed out */
|
||||
if (s->session[0] != '\0') {
|
||||
snprintf(sess, sizeof(sess),
|
||||
"Mcp-Session-Id: %s",
|
||||
s->session);
|
||||
hdrs[n++] = sess;
|
||||
}
|
||||
hdrs[n] = NULL;
|
||||
fd = sp_curl_start(args, s->url, hdrs,
|
||||
fd = is_stopping() ? -1 :
|
||||
sp_curl_start(args, s->url, hdrs,
|
||||
1, &pid, &err);
|
||||
if (fd >= 0) {
|
||||
s->http_pid = pid;
|
||||
(void)waitpid(pid, NULL, 0);
|
||||
s->http_pid = 0;
|
||||
close(fd);
|
||||
take_session(s, hdr);
|
||||
}
|
||||
@@ -595,6 +697,8 @@ notify(struct server *s, const char *method)
|
||||
sp_buf_free(&err);
|
||||
return;
|
||||
}
|
||||
if (s->to == NULL)
|
||||
return;
|
||||
fprintf(s->to, "{\"jsonrpc\":\"2.0\",\"method\":\"%s\"}\n", method);
|
||||
fflush(s->to);
|
||||
}
|
||||
@@ -612,13 +716,23 @@ spawn(struct server *s, struct sp_buf *err)
|
||||
sp_buf_puts(err, "mcp: a stdio server needs a cmd");
|
||||
return -1;
|
||||
}
|
||||
if (pipe(to) != 0 || pipe(from) != 0) {
|
||||
if (pipe(to) != 0) {
|
||||
sp_buf_printf(err, "mcp: pipe: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
if (pipe(from) != 0) {
|
||||
sp_buf_printf(err, "mcp: pipe: %s", strerror(errno));
|
||||
close(to[0]);
|
||||
close(to[1]);
|
||||
return -1;
|
||||
}
|
||||
child = fork();
|
||||
if (child < 0) {
|
||||
sp_buf_printf(err, "mcp: fork: %s", strerror(errno));
|
||||
close(to[0]);
|
||||
close(to[1]);
|
||||
close(from[0]);
|
||||
close(from[1]);
|
||||
return -1;
|
||||
}
|
||||
if (child == 0) {
|
||||
@@ -636,6 +750,8 @@ spawn(struct server *s, struct sp_buf *err)
|
||||
s->pid = child;
|
||||
s->to = fdopen(to[1], "w");
|
||||
s->from = from[0];
|
||||
if (s->to == NULL)
|
||||
close(to[1]); /* teardown() closes the rest */
|
||||
if (s->to == NULL || sp_buf_init(&s->in) != 0) {
|
||||
sp_buf_puts(err, "mcp: fdopen failed");
|
||||
return -1;
|
||||
@@ -655,8 +771,18 @@ call_tool(const char *args, struct sp_buf *out, void *ctx)
|
||||
|
||||
if (sp_buf_init(¶ms) != 0 || sp_buf_init(&err) != 0)
|
||||
return -1;
|
||||
sp_buf_printf(¶ms, "{\"name\":\"%s\",\"arguments\":%s}", tool->name,
|
||||
args != NULL && args[0] == '{' ? args : "{}");
|
||||
{
|
||||
mcp_json nm;
|
||||
|
||||
/* the name came from the server: printed back escaped */
|
||||
memset(&nm, 0, sizeof(nm));
|
||||
nm.t = MCP_STR;
|
||||
nm.s = (char *)tool->name;
|
||||
sp_buf_puts(¶ms, "{\"name\":");
|
||||
(void)json_print(¶ms, &nm);
|
||||
sp_buf_printf(¶ms, ",\"arguments\":%s}",
|
||||
args != NULL && args[0] == '{' ? args : "{}");
|
||||
}
|
||||
reply = rpc(tool->srv, "tools/call", params.p, &err);
|
||||
sp_buf_free(¶ms);
|
||||
if (reply == NULL) {
|
||||
@@ -676,15 +802,30 @@ call_tool(const char *args, struct sp_buf *out, void *ctx)
|
||||
return 0;
|
||||
}
|
||||
{
|
||||
const mcp_json *res = mcp_arg(v, "result");
|
||||
const mcp_json *content = res != NULL ? mcp_arg(res, "content") : NULL;
|
||||
const mcp_json *first = content != NULL ? mcp_array_at(content, 0) : NULL;
|
||||
const char *text = first != NULL ?
|
||||
mcp_arg_string(first, "text") : NULL;
|
||||
const mcp_json *res = mcp_arg(v, "result");
|
||||
const mcp_json *content = res != NULL ?
|
||||
mcp_arg(res, "content") : NULL;
|
||||
size_t i, ntext = 0;
|
||||
int is_error = res != NULL &&
|
||||
mcp_arg_bool(res, "isError", 0);
|
||||
|
||||
if (text != NULL)
|
||||
sp_buf_printf(out, "%s", text);
|
||||
else
|
||||
/*
|
||||
* Every text part, not only the first; a tool that failed says
|
||||
* so in isError, and the observation has to say it too.
|
||||
*/
|
||||
if (is_error)
|
||||
sp_buf_puts(out, "error: ");
|
||||
for (i = 0; content != NULL && i < mcp_array_len(content); i++) {
|
||||
const mcp_json *part = mcp_array_at(content, i);
|
||||
const char *text = part != NULL ?
|
||||
mcp_arg_string(part, "text") : NULL;
|
||||
|
||||
if (text == NULL)
|
||||
continue;
|
||||
sp_buf_printf(out, "%s%s", ntext > 0 ? "\n" : "", text);
|
||||
ntext++;
|
||||
}
|
||||
if (ntext == 0)
|
||||
sp_buf_printf(out, "%s", reply);
|
||||
}
|
||||
mcp_json_free(v);
|
||||
@@ -694,11 +835,27 @@ call_tool(const char *args, struct sp_buf *out, void *ctx)
|
||||
|
||||
/* ---- registration ---- */
|
||||
|
||||
/*
|
||||
* The registry copies the tool struct, not the strings. Everything that was
|
||||
* allocated for this tool goes with it: the prefixed name, the description,
|
||||
* the printed schema and the toolref the call needs. Without this the tools of
|
||||
* an MCP server leaked when the registry was freed (ASAN found 40 KB across a
|
||||
* single test).
|
||||
*/
|
||||
static void
|
||||
mcp_tool_dispose(struct sp_tool *t)
|
||||
{
|
||||
free((char *)t->name);
|
||||
free((char *)t->description);
|
||||
free((char *)t->params);
|
||||
free(t->ctx);
|
||||
memset(t, 0, sizeof(*t));
|
||||
}
|
||||
|
||||
static int
|
||||
register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err)
|
||||
{
|
||||
char *reply;
|
||||
const char *schema_at;
|
||||
mcp_json*v;
|
||||
const mcp_json *result, *tools;
|
||||
size_t i;
|
||||
@@ -720,13 +877,10 @@ register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err)
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* the schemas, in array order, from the raw text */
|
||||
schema_at = reply;
|
||||
for (i = 0; ; i++) {
|
||||
const mcp_json *t = mcp_array_at(tools, i);
|
||||
const mcp_json *schema;
|
||||
const char *name, *desc;
|
||||
const char *slice;
|
||||
size_t len = 0;
|
||||
struct toolref *ref;
|
||||
struct sp_tool tool;
|
||||
size_t nlen;
|
||||
@@ -737,11 +891,10 @@ register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err)
|
||||
desc = mcp_arg_string(t, "description");
|
||||
if (name == NULL)
|
||||
continue;
|
||||
slice = strstr(schema_at, "inputSchema");
|
||||
if (slice != NULL)
|
||||
slice = slice_object(slice, &len);
|
||||
if (slice != NULL)
|
||||
schema_at = slice;
|
||||
/* this tool's own schema, from its own entry */
|
||||
schema = mcp_arg(t, "inputSchema");
|
||||
if (schema != NULL && schema->t != MCP_OBJ)
|
||||
schema = NULL;
|
||||
|
||||
/* the tool's own name, plus "mcp_" and, with several servers, its id */
|
||||
nlen = strlen(name) + 8 + (prefix ? strlen(s->id) + 1 : 0);
|
||||
@@ -749,10 +902,8 @@ register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err)
|
||||
if (ref == NULL)
|
||||
continue;
|
||||
ref->srv = which;
|
||||
if (prefix)
|
||||
snprintf(ref->name, nlen, "%s_%s", s->id, name);
|
||||
else
|
||||
snprintf(ref->name, nlen, "%s", name);
|
||||
/* the server knows the tool by its own name, never the prefix */
|
||||
snprintf(ref->name, nlen, "%s", name);
|
||||
|
||||
memset(&tool, 0, sizeof(tool));
|
||||
{
|
||||
@@ -762,7 +913,11 @@ register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err)
|
||||
free(ref);
|
||||
continue;
|
||||
}
|
||||
snprintf(toolname, nlen + 4, "mcp_%s", ref->name);
|
||||
if (prefix)
|
||||
snprintf(toolname, nlen + 4, "mcp_%s_%s", s->id,
|
||||
name);
|
||||
else
|
||||
snprintf(toolname, nlen + 4, "mcp_%s", name);
|
||||
tool.name = toolname;
|
||||
}
|
||||
/*
|
||||
@@ -777,23 +932,34 @@ register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err)
|
||||
free(ref);
|
||||
continue;
|
||||
}
|
||||
if (slice != NULL) {
|
||||
char *copy = malloc(len + 1);
|
||||
if (schema != NULL) {
|
||||
struct sp_buf sb;
|
||||
|
||||
if (copy != NULL) {
|
||||
memcpy(copy, slice, len);
|
||||
copy[len] = '\0';
|
||||
tool.params = copy;
|
||||
if (sp_buf_init(&sb) == 0) {
|
||||
if (json_print(&sb, schema) == 0 && sb.p != NULL)
|
||||
tool.params = sb.p; /* kept, like the copy */
|
||||
else
|
||||
sp_buf_free(&sb);
|
||||
}
|
||||
}
|
||||
if (tool.params == NULL)
|
||||
tool.params = "{\"type\":\"object\",\"properties\":{}}";
|
||||
tool.params = strdup(
|
||||
"{\"type\":\"object\",\"properties\":{}}");
|
||||
if (tool.params == NULL) {
|
||||
free((char *)tool.name);
|
||||
free((char *)tool.description);
|
||||
free(ref);
|
||||
continue;
|
||||
}
|
||||
/* an MCP server can do anything; the class is the honest default */
|
||||
tool.auth = SP_AUTH_MUTATE;
|
||||
tool.run = call_tool;
|
||||
tool.ctx = ref;
|
||||
tool.dispose = mcp_tool_dispose;
|
||||
if (sp_host_add_tool(host, &tool) == 0)
|
||||
added++;
|
||||
else
|
||||
mcp_tool_dispose(&tool);
|
||||
}
|
||||
mcp_json_free(v);
|
||||
free(reply);
|
||||
@@ -802,24 +968,33 @@ register_tools(struct server *s, size_t which, int prefix, struct sp_buf *err)
|
||||
|
||||
/* ---- plugin entry points ---- */
|
||||
|
||||
/* The sidebar says how many tools the servers offered and whether they are gone. */
|
||||
/*
|
||||
* The sidebar names every MCP server and whether it is connected, the way the
|
||||
* editor does: "junction connected", "local disconnected". The old line
|
||||
* counted tools, which said nothing about which server was gone.
|
||||
*/
|
||||
static int
|
||||
mcp_widget_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
{
|
||||
char line[96];
|
||||
size_t i;
|
||||
int alive = 0, total = 0;
|
||||
char line[1024];
|
||||
size_t i, off = 0;
|
||||
|
||||
(void)ctx;
|
||||
for (i = 0; i < nsv; i++) {
|
||||
total += sv[i].up ? sv[i].ntools : 0;
|
||||
if (sv[i].up)
|
||||
alive++;
|
||||
if (nsv == 0) {
|
||||
(void)sp_host_widget_text(h, name,
|
||||
"no server configured");
|
||||
return 0;
|
||||
}
|
||||
for (i = 0; i < nsv && off < sizeof(line); i++) {
|
||||
int n;
|
||||
|
||||
n = snprintf(line + off, sizeof(line) - off, "%s%s %s",
|
||||
i > 0 ? "\n" : "", sv[i].id,
|
||||
sv[i].up ? "connected" : "disconnected");
|
||||
if (n < 0)
|
||||
break;
|
||||
off += (size_t)n;
|
||||
}
|
||||
if (nsv > 0 && alive == 0)
|
||||
snprintf(line, sizeof(line), "%d tools, offline", total);
|
||||
else
|
||||
snprintf(line, sizeof(line), "%d tools", total);
|
||||
(void)sp_host_widget_text(h, name, line);
|
||||
return 0;
|
||||
}
|
||||
@@ -850,7 +1025,10 @@ handshake(size_t which, struct sp_buf *err)
|
||||
return -1;
|
||||
free(reply);
|
||||
/* the handshake is not finished until the server is told so */
|
||||
notify(&sv[which], "notifications/initialized");
|
||||
pthread_mutex_lock(&sv[which].lock);
|
||||
if (!sv[which].dead)
|
||||
notify(&sv[which], "notifications/initialized");
|
||||
pthread_mutex_unlock(&sv[which].lock);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -858,21 +1036,29 @@ handshake(size_t which, struct sp_buf *err)
|
||||
static void
|
||||
teardown(struct server *s)
|
||||
{
|
||||
if (!s->http && s->pid > 0) {
|
||||
(void)kill(s->pid, SIGTERM);
|
||||
(void)waitpid(s->pid, NULL, 0);
|
||||
s->pid = 0;
|
||||
if (s->to != NULL)
|
||||
if (!s->http) {
|
||||
if (s->pid > 0) {
|
||||
(void)kill(s->pid, SIGTERM);
|
||||
(void)waitpid(s->pid, NULL, 0);
|
||||
s->pid = 0;
|
||||
}
|
||||
if (s->to != NULL) {
|
||||
fclose(s->to);
|
||||
s->to = NULL;
|
||||
if (s->from > 0)
|
||||
s->to = NULL;
|
||||
}
|
||||
if (s->from > 0) {
|
||||
close(s->from);
|
||||
s->from = 0;
|
||||
if (s->in.p != NULL)
|
||||
sp_buf_free(&s->in);
|
||||
s->from = 0;
|
||||
}
|
||||
}
|
||||
/* The HTTP transport fills the same line buffer while reading its SSE
|
||||
* answer; it leaked because this was freed only for stdio. */
|
||||
if (s->in.p != NULL)
|
||||
sp_buf_free(&s->in);
|
||||
s->session[0] = '\0';
|
||||
s->up = 0;
|
||||
/* until connect_server() has new pipes, a call fails cleanly */
|
||||
s->dead = 1;
|
||||
}
|
||||
|
||||
/* Everything one connect attempt needs: start, handshake, tools (once). */
|
||||
@@ -881,9 +1067,14 @@ connect_server(size_t i, struct sp_buf *err)
|
||||
{
|
||||
struct server *s = &sv[i];
|
||||
|
||||
s->dead = 0;
|
||||
if (!s->http && spawn(s, err) != 0)
|
||||
/* a tool call may be in rpc() now: the pipes change under the lock */
|
||||
pthread_mutex_lock(&s->lock);
|
||||
if (!s->http && spawn(s, err) != 0) {
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
return -1;
|
||||
}
|
||||
s->dead = 0;
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
if (handshake(i, err) != 0)
|
||||
return -1;
|
||||
if (!s->registered) {
|
||||
@@ -906,7 +1097,7 @@ nap(void)
|
||||
{
|
||||
int k;
|
||||
|
||||
for (k = 0; k < RETRY_S * 10 && !stopping; k++) {
|
||||
for (k = 0; k < RETRY_S * 10 && !is_stopping(); k++) {
|
||||
struct timespec ts = { 0, 100000000L };
|
||||
|
||||
nanosleep(&ts, NULL);
|
||||
@@ -936,13 +1127,13 @@ alive_after(const char *err)
|
||||
* reconnect when the link is gone.
|
||||
*/
|
||||
static void *
|
||||
server_thread(void *arg)
|
||||
server_thread_body(void *arg)
|
||||
{
|
||||
size_t i = (size_t)(uintptr_t)arg;
|
||||
struct server *s = &sv[i];
|
||||
int failed_said = 0, ever_up = 0;
|
||||
|
||||
while (!stopping) {
|
||||
while (!is_stopping()) {
|
||||
struct sp_buf err;
|
||||
|
||||
if (sp_buf_init(&err) != 0)
|
||||
@@ -962,6 +1153,7 @@ server_thread(void *arg)
|
||||
ever_up = 1;
|
||||
failed_said = 0;
|
||||
} else {
|
||||
pthread_mutex_lock(&s->lock);
|
||||
teardown(s);
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
if (!failed_said) {
|
||||
@@ -981,7 +1173,7 @@ server_thread(void *arg)
|
||||
char *r;
|
||||
|
||||
nap();
|
||||
if (stopping) {
|
||||
if (is_stopping()) {
|
||||
sp_buf_free(&err);
|
||||
break;
|
||||
}
|
||||
@@ -1001,6 +1193,23 @@ server_thread(void *arg)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/*
|
||||
* Every return of the body goes through here, so shutdown can tell when the
|
||||
* thread is finished instead of guessing with a sleep.
|
||||
*/
|
||||
static void *
|
||||
server_thread(void *arg)
|
||||
{
|
||||
size_t i = (size_t)(uintptr_t)arg;
|
||||
void *rc = server_thread_body(arg);
|
||||
|
||||
pthread_mutex_lock(&done_mu);
|
||||
sv[i].th_done = 1;
|
||||
pthread_cond_broadcast(&done_cv);
|
||||
pthread_mutex_unlock(&done_mu);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int
|
||||
mcp_init(struct sp_host *h)
|
||||
{
|
||||
@@ -1009,7 +1218,7 @@ mcp_init(struct sp_host *h)
|
||||
|
||||
host = h;
|
||||
nsv = 0;
|
||||
stopping = 0;
|
||||
set_stopping(0);
|
||||
conf = sp_host_config(h);
|
||||
|
||||
if (conf != NULL) {
|
||||
@@ -1045,26 +1254,54 @@ mcp_init(struct sp_host *h)
|
||||
}
|
||||
(void)sp_host_add_widget(h, &widget);
|
||||
for (i = 0; i < nsv; i++) {
|
||||
pthread_t t;
|
||||
|
||||
pthread_mutex_init(&sv[i].lock, NULL);
|
||||
sv[i].th_done = 0;
|
||||
say(sv[i].id, "connecting in the background", NULL);
|
||||
if (pthread_create(&t, NULL, server_thread,
|
||||
if (pthread_create(&sv[i].th, NULL, server_thread,
|
||||
(void *)(uintptr_t)i) == 0)
|
||||
pthread_detach(t);
|
||||
sv[i].th_started = 1;
|
||||
else
|
||||
sv[i].dead = 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Wait (bounded) until every server thread has returned. A thread stuck in a
|
||||
* connect must not hang the shutdown; such a thread is left running and its
|
||||
* state is not freed.
|
||||
*/
|
||||
static void
|
||||
stop_threads(void)
|
||||
{
|
||||
struct timespec deadline;
|
||||
size_t i;
|
||||
int pending;
|
||||
|
||||
clock_gettime(CLOCK_REALTIME, &deadline);
|
||||
deadline.tv_sec += 5;
|
||||
pthread_mutex_lock(&done_mu);
|
||||
for (;;) {
|
||||
pending = 0;
|
||||
for (i = 0; i < nsv; i++)
|
||||
if (sv[i].th_started && !sv[i].th_done)
|
||||
pending++;
|
||||
if (pending == 0)
|
||||
break;
|
||||
if (pthread_cond_timedwait(&done_cv, &done_mu, &deadline) != 0)
|
||||
break;
|
||||
}
|
||||
pthread_mutex_unlock(&done_mu);
|
||||
}
|
||||
|
||||
static void
|
||||
mcp_shutdown(struct sp_host *h)
|
||||
{
|
||||
size_t i;
|
||||
size_t i;
|
||||
int done;
|
||||
|
||||
(void)h;
|
||||
stopping = 1;
|
||||
set_stopping(1);
|
||||
for (i = 0; i < nsv; i++) {
|
||||
/* a child is stopped without taking the lock a stuck call may hold */
|
||||
if (!sv[i].http && sv[i].pid > 0) {
|
||||
@@ -1072,8 +1309,34 @@ mcp_shutdown(struct sp_host *h)
|
||||
(void)waitpid(sv[i].pid, NULL, 0);
|
||||
sv[i].pid = 0;
|
||||
}
|
||||
/* an HTTP round trip in flight: its curl goes, the thread sees EOF */
|
||||
if (sv[i].http && sv[i].http_pid > 0)
|
||||
(void)kill(sv[i].http_pid, SIGKILL);
|
||||
sv[i].dead = 1;
|
||||
}
|
||||
/*
|
||||
* Only a thread that has returned may have its buffers freed: the HTTP
|
||||
* line buffer (up to RPC_MAX_LINE) and the tools it registers live there.
|
||||
* Before the join, a late register_tools() could also write into a host
|
||||
* that is being freed.
|
||||
*/
|
||||
stop_threads();
|
||||
for (i = 0; i < nsv; i++) {
|
||||
if (!sv[i].th_started)
|
||||
continue;
|
||||
pthread_mutex_lock(&done_mu);
|
||||
done = sv[i].th_done;
|
||||
pthread_mutex_unlock(&done_mu);
|
||||
if (!done) {
|
||||
fprintf(stderr, "mcp: %s did not stop within 5 s; its "
|
||||
"buffers stay\n", sv[i].id);
|
||||
continue;
|
||||
}
|
||||
(void)pthread_join(sv[i].th, NULL);
|
||||
sv[i].th_started = 0;
|
||||
teardown(&sv[i]);
|
||||
pthread_mutex_destroy(&sv[i].lock);
|
||||
}
|
||||
}
|
||||
|
||||
static const struct sp_plugin plugin = {
|
||||
|
||||
@@ -1,633 +0,0 @@
|
||||
/*
|
||||
* splinter -- the plan of a session (/tasks).
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* A list of things the session means to do, kept in <session>/plan_tasks.json.
|
||||
* It is not a process table: a shell command with a pid and a clock belongs to
|
||||
* the tasks plugin (task_start). Here a task is a sentence and a state:
|
||||
*
|
||||
* todo -> doing -> done blocked waiting_quota
|
||||
*
|
||||
* The file is the contract. Every operation reads it, changes it and writes it
|
||||
* back under one lock, so the tools, the /tasks command, the sidebar tick and a
|
||||
* second splinter looking at the same session all see the same list. Making a
|
||||
* task "doing" sets /goal to its text (the focus plugin), which is what keeps a
|
||||
* long session from drifting.
|
||||
*
|
||||
* Other code reaches this through the command, not through this file:
|
||||
* the delegate parks a task with "/tasks wait <id> <when> <note>" when its
|
||||
* provider is out of quota, and the tick below puts it back to todo when the
|
||||
* time has come.
|
||||
*/
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "mcp.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "i18n.h"
|
||||
|
||||
#define MAX_TASKS 128
|
||||
#define DESC_LEN 1024
|
||||
#define NOTE_LEN 256
|
||||
#define WHEN_LEN 64
|
||||
#define STATUS_LEN 24
|
||||
#define FILE_MAX (256 * 1024)
|
||||
|
||||
struct task {
|
||||
int id;
|
||||
char status[STATUS_LEN];
|
||||
char desc[DESC_LEN];
|
||||
char run_after[WHEN_LEN]; /* unix time, or empty */
|
||||
char note[NOTE_LEN];
|
||||
long created;
|
||||
long updated;
|
||||
};
|
||||
|
||||
static const char *const states[] = {
|
||||
"todo", "doing", "done", "blocked", "waiting_quota", NULL
|
||||
};
|
||||
|
||||
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static struct sp_host *host_ref;
|
||||
static struct task tasks[MAX_TASKS];
|
||||
static size_t ntasks;
|
||||
static int next_id = 1;
|
||||
static int current_id = -1; /* the task in "doing" */
|
||||
|
||||
/* ------------------------------------------------------------- the file */
|
||||
|
||||
static int
|
||||
store_path(char *path, size_t len)
|
||||
{
|
||||
const char *dir = sp_host_session_dir(host_ref);
|
||||
|
||||
if (dir == NULL || dir[0] == '\0')
|
||||
return -1;
|
||||
snprintf(path, len, "%s/plan_tasks.json", dir);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
copy_str(char *dst, size_t len, const char *src)
|
||||
{
|
||||
snprintf(dst, len, "%s", src != NULL ? src : "");
|
||||
}
|
||||
|
||||
static void
|
||||
load(void)
|
||||
{
|
||||
char path[600];
|
||||
char *text;
|
||||
FILE *f;
|
||||
size_t n, i;
|
||||
mcp_json *root;
|
||||
|
||||
ntasks = 0;
|
||||
next_id = 1;
|
||||
current_id = -1;
|
||||
if (store_path(path, sizeof(path)) != 0 || (f = fopen(path, "r")) == NULL)
|
||||
return;
|
||||
if ((text = malloc(FILE_MAX + 1)) == NULL) {
|
||||
fclose(f);
|
||||
return;
|
||||
}
|
||||
n = fread(text, 1, FILE_MAX, f);
|
||||
fclose(f);
|
||||
text[n] = '\0';
|
||||
root = mcp_parse(text);
|
||||
free(text);
|
||||
if (root == NULL)
|
||||
return;
|
||||
for (i = 0; i < mcp_array_len(root) && ntasks < MAX_TASKS; i++) {
|
||||
const mcp_json *o = mcp_array_at(root, i);
|
||||
struct task *t = &tasks[ntasks];
|
||||
|
||||
memset(t, 0, sizeof(*t));
|
||||
t->id = mcp_arg_int(o, "id", 0);
|
||||
if (t->id <= 0)
|
||||
t->id = next_id;
|
||||
copy_str(t->status, sizeof(t->status),
|
||||
mcp_arg_string(o, "status"));
|
||||
if (t->status[0] == '\0')
|
||||
copy_str(t->status, sizeof(t->status), "todo");
|
||||
copy_str(t->desc, sizeof(t->desc), mcp_arg_string(o, "desc"));
|
||||
copy_str(t->run_after, sizeof(t->run_after),
|
||||
mcp_arg_string(o, "run_after"));
|
||||
copy_str(t->note, sizeof(t->note), mcp_arg_string(o, "note"));
|
||||
t->created = (long)mcp_arg_num(o, "created", 0);
|
||||
t->updated = (long)mcp_arg_num(o, "updated", 0);
|
||||
if (t->id >= next_id)
|
||||
next_id = t->id + 1;
|
||||
if (strcmp(t->status, "doing") == 0)
|
||||
current_id = t->id;
|
||||
ntasks++;
|
||||
}
|
||||
mcp_json_free(root);
|
||||
}
|
||||
|
||||
static void
|
||||
put_field(struct sp_buf *b, const char *key, const char *val)
|
||||
{
|
||||
sp_buf_printf(b, "\"%s\":\"", key);
|
||||
sp_json_escape(b, val);
|
||||
sp_buf_puts(b, "\"");
|
||||
}
|
||||
|
||||
/* Write to a temporary name and rename: a reader never sees half a file. */
|
||||
static void
|
||||
save(void)
|
||||
{
|
||||
char path[600], tmp[620];
|
||||
struct sp_buf b;
|
||||
size_t i;
|
||||
FILE *f;
|
||||
|
||||
if (store_path(path, sizeof(path)) != 0 || sp_buf_init(&b) != 0)
|
||||
return;
|
||||
sp_buf_puts(&b, "[\n");
|
||||
for (i = 0; i < ntasks; i++) {
|
||||
const struct task *t = &tasks[i];
|
||||
|
||||
sp_buf_printf(&b, " {\"id\":%d,", t->id);
|
||||
put_field(&b, "status", t->status);
|
||||
sp_buf_puts(&b, ",");
|
||||
put_field(&b, "desc", t->desc);
|
||||
sp_buf_puts(&b, ",");
|
||||
put_field(&b, "run_after", t->run_after);
|
||||
sp_buf_puts(&b, ",");
|
||||
put_field(&b, "note", t->note);
|
||||
sp_buf_printf(&b, ",\"created\":%ld,\"updated\":%ld}%s\n",
|
||||
t->created, t->updated, i + 1 < ntasks ? "," : "");
|
||||
}
|
||||
sp_buf_puts(&b, "]\n");
|
||||
snprintf(tmp, sizeof(tmp), "%s.tmp", path);
|
||||
if ((f = fopen(tmp, "w")) != NULL) {
|
||||
int ok = fwrite(b.p, 1, b.len, f) == b.len;
|
||||
|
||||
if (fclose(f) != 0)
|
||||
ok = 0;
|
||||
if (!ok || rename(tmp, path) != 0)
|
||||
unlink(tmp);
|
||||
}
|
||||
sp_buf_free(&b);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- state */
|
||||
|
||||
static struct task *
|
||||
find(int id)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < ntasks; i++)
|
||||
if (tasks[i].id == id)
|
||||
return &tasks[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static struct task *
|
||||
first_todo(void)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < ntasks; i++)
|
||||
if (strcmp(tasks[i].status, "todo") == 0)
|
||||
return &tasks[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int
|
||||
valid_state(const char *s)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; states[i] != NULL; i++)
|
||||
if (strcmp(states[i], s) == 0)
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* "+90" is ninety seconds from now; anything else is taken as written. */
|
||||
static void
|
||||
when(const char *in, char *out, size_t len)
|
||||
{
|
||||
out[0] = '\0';
|
||||
if (in == NULL || in[0] == '\0')
|
||||
return;
|
||||
if (in[0] == '+') {
|
||||
long d = strtol(in + 1, NULL, 10);
|
||||
|
||||
if (d <= 0)
|
||||
d = 3600;
|
||||
snprintf(out, len, "%ld", (long)time(NULL) + d);
|
||||
return;
|
||||
}
|
||||
snprintf(out, len, "%s", in);
|
||||
}
|
||||
|
||||
static void
|
||||
widget(void)
|
||||
{
|
||||
char b[256];
|
||||
size_t i;
|
||||
int todo = 0, doing = 0, done = 0;
|
||||
|
||||
for (i = 0; i < ntasks; i++) {
|
||||
if (strcmp(tasks[i].status, "todo") == 0)
|
||||
todo++;
|
||||
else if (strcmp(tasks[i].status, "doing") == 0)
|
||||
doing++;
|
||||
else if (strcmp(tasks[i].status, "done") == 0)
|
||||
done++;
|
||||
}
|
||||
if (ntasks == 0)
|
||||
b[0] = '\0'; /* no plan: nothing on the sidebar */
|
||||
else if (current_id > 0)
|
||||
snprintf(b, sizeof(b), sp_td("plan.widget_active",
|
||||
"#%d active - todo %d, doing %d, done %d"), current_id,
|
||||
todo, doing, done);
|
||||
else
|
||||
snprintf(b, sizeof(b), sp_td("plan.widget",
|
||||
"todo %d, doing %d, done %d"), todo, doing, done);
|
||||
sp_host_widget_text(host_ref, "plan", b);
|
||||
}
|
||||
|
||||
/* One task is "doing" at a time; its text becomes the session goal. */
|
||||
static void
|
||||
start(struct task *t)
|
||||
{
|
||||
size_t i;
|
||||
struct sp_buf ignored;
|
||||
|
||||
for (i = 0; i < ntasks; i++)
|
||||
if (strcmp(tasks[i].status, "doing") == 0)
|
||||
copy_str(tasks[i].status, STATUS_LEN, "todo");
|
||||
copy_str(t->status, STATUS_LEN, "doing");
|
||||
t->updated = (long)time(NULL);
|
||||
current_id = t->id;
|
||||
if (sp_buf_init(&ignored) == 0) {
|
||||
(void)sp_host_command(host_ref, "goal", t->desc, &ignored);
|
||||
sp_buf_free(&ignored);
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
changed(void)
|
||||
{
|
||||
save();
|
||||
widget();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ operations */
|
||||
|
||||
static int
|
||||
op_add(const char *desc, const char *run_after, struct sp_buf *out)
|
||||
{
|
||||
struct task *t;
|
||||
|
||||
if (desc == NULL || desc[0] == '\0')
|
||||
return sp_buf_puts(out, "error: description required\n");
|
||||
if (ntasks >= MAX_TASKS)
|
||||
return sp_buf_printf(out, "error: the plan holds %d tasks\n",
|
||||
MAX_TASKS);
|
||||
t = &tasks[ntasks++];
|
||||
memset(t, 0, sizeof(*t));
|
||||
t->id = next_id++;
|
||||
copy_str(t->status, sizeof(t->status), "todo");
|
||||
copy_str(t->desc, sizeof(t->desc), desc);
|
||||
when(run_after, t->run_after, sizeof(t->run_after));
|
||||
t->created = t->updated = (long)time(NULL);
|
||||
changed();
|
||||
return sp_buf_printf(out, "added plan task #%d: %s\n", t->id, t->desc);
|
||||
}
|
||||
|
||||
static int
|
||||
op_list(struct sp_buf *out)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (ntasks == 0)
|
||||
return sp_buf_puts(out, "(no plan tasks) use plan_task_add\n");
|
||||
sp_buf_puts(out, "plan tasks:\n");
|
||||
for (i = 0; i < ntasks; i++) {
|
||||
const struct task *t = &tasks[i];
|
||||
|
||||
sp_buf_printf(out, " #%d [%s]%s %s", t->id, t->status,
|
||||
t->id == current_id ? " *" : "", t->desc);
|
||||
if (t->run_after[0] != '\0')
|
||||
sp_buf_printf(out, " (run_after=%s)", t->run_after);
|
||||
if (t->note[0] != '\0')
|
||||
sp_buf_printf(out, " # %s", t->note);
|
||||
sp_buf_puts(out, "\n");
|
||||
}
|
||||
return sp_buf_puts(out, "use /tasks work <id> | work all | next\n");
|
||||
}
|
||||
|
||||
static int
|
||||
op_done(int id, struct sp_buf *out)
|
||||
{
|
||||
struct task *t = find(id);
|
||||
|
||||
if (t == NULL)
|
||||
return sp_buf_puts(out, "no current task to mark done\n");
|
||||
copy_str(t->status, sizeof(t->status), "done");
|
||||
t->updated = (long)time(NULL);
|
||||
if (current_id == id)
|
||||
current_id = -1;
|
||||
changed();
|
||||
return sp_buf_printf(out, "task #%d done\n", id);
|
||||
}
|
||||
|
||||
/* Park a task until a time: the delegate does this when a quota runs out. */
|
||||
static int
|
||||
op_wait(int id, const char *at, const char *note, struct sp_buf *out)
|
||||
{
|
||||
struct task *t = find(id);
|
||||
|
||||
if (t == NULL)
|
||||
return sp_buf_printf(out, "no task #%d\n", id);
|
||||
if (at != NULL && at[0] != '\0')
|
||||
when(at, t->run_after, sizeof(t->run_after));
|
||||
else
|
||||
when("+3600", t->run_after, sizeof(t->run_after));
|
||||
copy_str(t->status, sizeof(t->status), "waiting_quota");
|
||||
copy_str(t->note, sizeof(t->note),
|
||||
note != NULL && note[0] != '\0' ? note : "quota wait");
|
||||
t->updated = (long)time(NULL);
|
||||
if (current_id == id)
|
||||
current_id = -1;
|
||||
changed();
|
||||
return sp_buf_printf(out, "task #%d waiting_quota run_after=%s\n", id,
|
||||
t->run_after);
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- tools */
|
||||
|
||||
static int
|
||||
arg_id(const mcp_json *a, const char *key)
|
||||
{
|
||||
const char *s = mcp_arg_string(a, key);
|
||||
|
||||
return s != NULL ? atoi(s) : mcp_arg_int(a, key, 0);
|
||||
}
|
||||
|
||||
static int
|
||||
tool_add(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
mcp_json *a;
|
||||
const char *desc;
|
||||
int rc;
|
||||
|
||||
(void)ctx;
|
||||
if ((a = mcp_parse(args != NULL ? args : "{}")) == NULL)
|
||||
return sp_buf_puts(out, "error: arguments are not JSON\n");
|
||||
desc = mcp_arg_string(a, "description");
|
||||
pthread_mutex_lock(&lock);
|
||||
load();
|
||||
rc = op_add(desc, mcp_arg_string(a, "run_after"), out);
|
||||
pthread_mutex_unlock(&lock);
|
||||
mcp_json_free(a);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_list(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
int rc;
|
||||
|
||||
(void)args;
|
||||
(void)ctx;
|
||||
pthread_mutex_lock(&lock);
|
||||
load();
|
||||
rc = op_list(out);
|
||||
pthread_mutex_unlock(&lock);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_update(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
mcp_json *a;
|
||||
struct task *t;
|
||||
const char *s;
|
||||
int id;
|
||||
|
||||
(void)ctx;
|
||||
if ((a = mcp_parse(args != NULL ? args : "{}")) == NULL)
|
||||
return sp_buf_puts(out, "error: arguments are not JSON\n");
|
||||
id = arg_id(a, "id");
|
||||
pthread_mutex_lock(&lock);
|
||||
load();
|
||||
if (id <= 0 || (t = find(id)) == NULL) {
|
||||
sp_buf_printf(out, id <= 0 ? "error: id required\n" :
|
||||
"error: no task #%d\n", id);
|
||||
goto out;
|
||||
}
|
||||
if ((s = mcp_arg_string(a, "status")) != NULL && s[0] != '\0') {
|
||||
if (!valid_state(s)) {
|
||||
sp_buf_printf(out, "error: status is one of todo, "
|
||||
"doing, done, blocked, waiting_quota, not '%s'\n", s);
|
||||
goto out;
|
||||
}
|
||||
if (strcmp(s, "doing") == 0)
|
||||
start(t);
|
||||
else {
|
||||
copy_str(t->status, sizeof(t->status), s);
|
||||
if (current_id == t->id)
|
||||
current_id = -1;
|
||||
}
|
||||
}
|
||||
if ((s = mcp_arg_string(a, "description")) != NULL && s[0] != '\0')
|
||||
copy_str(t->desc, sizeof(t->desc), s);
|
||||
if (mcp_arg(a, "run_after") != NULL) /* present but empty: clear it */
|
||||
when(mcp_arg_string(a, "run_after"), t->run_after,
|
||||
sizeof(t->run_after));
|
||||
if ((s = mcp_arg_string(a, "note")) != NULL && s[0] != '\0')
|
||||
copy_str(t->note, sizeof(t->note), s);
|
||||
t->updated = (long)time(NULL);
|
||||
changed();
|
||||
sp_buf_printf(out, "task #%d -> [%s] %s\n", t->id, t->status, t->desc);
|
||||
out:
|
||||
pthread_mutex_unlock(&lock);
|
||||
mcp_json_free(a);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- command */
|
||||
|
||||
static const char *
|
||||
skip(const char *s)
|
||||
{
|
||||
while (*s == ' ')
|
||||
s++;
|
||||
return s;
|
||||
}
|
||||
|
||||
static int
|
||||
command_locked(const char *args, struct sp_buf *out)
|
||||
{
|
||||
const char *p;
|
||||
struct task *t;
|
||||
|
||||
if (args == NULL || args[0] == '\0' || strcmp(args, "ls") == 0 ||
|
||||
strcmp(args, "list") == 0)
|
||||
return op_list(out);
|
||||
if (strncmp(args, "add ", 4) == 0)
|
||||
return op_add(skip(args + 4), NULL, out);
|
||||
if (strncmp(args, "work", 4) == 0) {
|
||||
p = skip(args + 4);
|
||||
if (strcmp(p, "all") == 0) {
|
||||
if ((t = first_todo()) == NULL)
|
||||
return sp_buf_puts(out, "no todo tasks left\n");
|
||||
} else if (*p != '\0') {
|
||||
if ((t = find(atoi(p))) == NULL)
|
||||
return sp_buf_printf(out, "no task #%d\n",
|
||||
atoi(p));
|
||||
} else
|
||||
return sp_buf_puts(out, "usage: /tasks work <id>|all\n");
|
||||
start(t);
|
||||
changed();
|
||||
return sp_buf_printf(out, "working on #%d: %s\n", t->id,
|
||||
t->desc);
|
||||
}
|
||||
if (strcmp(args, "choose") == 0 || strcmp(args, "next") == 0) {
|
||||
if ((t = first_todo()) == NULL)
|
||||
return sp_buf_puts(out, "no todo tasks\n");
|
||||
start(t);
|
||||
changed();
|
||||
return sp_buf_printf(out, "chose #%d: %s\n", t->id, t->desc);
|
||||
}
|
||||
if (strncmp(args, "done", 4) == 0) {
|
||||
p = skip(args + 4);
|
||||
return op_done(*p != '\0' ? atoi(p) : current_id, out);
|
||||
}
|
||||
if (strncmp(args, "wait", 4) == 0) {
|
||||
char at[WHEN_LEN];
|
||||
int id;
|
||||
size_t n = 0;
|
||||
|
||||
p = skip(args + 4);
|
||||
id = atoi(p);
|
||||
while (*p != '\0' && *p != ' ')
|
||||
p++;
|
||||
p = skip(p);
|
||||
while (*p != '\0' && *p != ' ' && n + 1 < sizeof(at))
|
||||
at[n++] = *p++;
|
||||
at[n] = '\0';
|
||||
return op_wait(id, at, skip(p), out);
|
||||
}
|
||||
return sp_buf_puts(out, "usage: /tasks [ls|add <text>|work <id>|work all"
|
||||
"|next|done [id]|wait <id> <+secs|epoch> [note]]\n");
|
||||
}
|
||||
|
||||
static int
|
||||
command(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
int rc;
|
||||
|
||||
(void)ctx;
|
||||
host_ref = h;
|
||||
pthread_mutex_lock(&lock);
|
||||
load();
|
||||
rc = command_locked(args, out);
|
||||
pthread_mutex_unlock(&lock);
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* The clock: a parked task whose time has come is todo again. */
|
||||
static int
|
||||
tick(struct sp_host *h, const char *name, void *ctx)
|
||||
{
|
||||
long now = (long)time(NULL);
|
||||
size_t i;
|
||||
int moved = 0;
|
||||
|
||||
(void)name;
|
||||
(void)ctx;
|
||||
host_ref = h;
|
||||
pthread_mutex_lock(&lock);
|
||||
load();
|
||||
for (i = 0; i < ntasks; i++) {
|
||||
struct task *t = &tasks[i];
|
||||
long at = strtol(t->run_after, NULL, 10);
|
||||
|
||||
if (strcmp(t->status, "waiting_quota") != 0 || at <= 0 ||
|
||||
now < at)
|
||||
continue;
|
||||
copy_str(t->status, sizeof(t->status), "todo");
|
||||
copy_str(t->note, sizeof(t->note), "quota is back");
|
||||
t->run_after[0] = '\0';
|
||||
t->updated = now;
|
||||
moved = 1;
|
||||
}
|
||||
if (moved)
|
||||
save();
|
||||
widget();
|
||||
pthread_mutex_unlock(&lock);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_tool t_add = {
|
||||
"plan_task_add",
|
||||
"Add a task to the session's plan: a sentence to do, not a process "
|
||||
"(use task_start for shell commands). Optional run_after is a unix "
|
||||
"time, or +seconds from now.",
|
||||
"{\"type\":\"object\",\"properties\":{\"description\":{\"type\":"
|
||||
"\"string\"},\"run_after\":{\"type\":\"string\"}},\"required\":"
|
||||
"[\"description\"]}",
|
||||
SP_AUTH_MUTATE, tool_add, NULL
|
||||
};
|
||||
|
||||
static const struct sp_tool t_list = {
|
||||
"plan_task_list",
|
||||
"List the session's plan with state; the one marked * is active.",
|
||||
"{\"type\":\"object\",\"properties\":{}}",
|
||||
SP_AUTH_READ, tool_list, NULL
|
||||
};
|
||||
|
||||
static const struct sp_tool t_update = {
|
||||
"plan_task_update",
|
||||
"Change a plan task. status is todo, doing, done, blocked or "
|
||||
"waiting_quota; doing makes it the session goal. An empty run_after "
|
||||
"clears the wait.",
|
||||
"{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\"},"
|
||||
"\"status\":{\"type\":\"string\"},\"description\":{\"type\":\"string\"},"
|
||||
"\"run_after\":{\"type\":\"string\"},\"note\":{\"type\":\"string\"}},"
|
||||
"\"required\":[\"id\"]}",
|
||||
SP_AUTH_MUTATE, tool_update, NULL
|
||||
};
|
||||
|
||||
static const struct sp_widget plan_widget = { "plan", tick, NULL, NULL, 5000 };
|
||||
|
||||
static int
|
||||
init(struct sp_host *h)
|
||||
{
|
||||
host_ref = h;
|
||||
pthread_mutex_lock(&lock);
|
||||
load();
|
||||
widget();
|
||||
pthread_mutex_unlock(&lock);
|
||||
sp_host_add_tool(h, &t_add);
|
||||
sp_host_add_tool(h, &t_list);
|
||||
sp_host_add_tool(h, &t_update);
|
||||
sp_host_add_command(h, "tasks", command, NULL);
|
||||
sp_host_add_widget(h, &plan_widget);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin plugin = {
|
||||
SP_PLUGIN_ABI, "planner", "0.2", init, NULL, NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &plugin;
|
||||
}
|
||||
@@ -14,13 +14,14 @@
|
||||
*
|
||||
* The tools:
|
||||
*
|
||||
* task_start command, label? -> id, starts at once
|
||||
* task_list -> id, state, seconds, bytes, label
|
||||
* task_result id -> output, exit status; fails while running
|
||||
* task_kill id -> stop it
|
||||
* process_start command, label? -> id, starts at once
|
||||
* process_list -> id, state, seconds, bytes, label
|
||||
* process_result id -> output, exit status; fails while running
|
||||
* process_kill id -> stop it
|
||||
*
|
||||
* Tasks are shell commands, so starting one is destructive in the same sense that
|
||||
* `run` is: the gate and the approval path see it like any other change.
|
||||
* Tasks are shell commands, so starting one is destructive in the same sense
|
||||
* that `run` is: the authorization class says as much, and splinter runs it
|
||||
* like any other tool the registry offers.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
@@ -73,7 +74,7 @@ running_count(void)
|
||||
}
|
||||
|
||||
static void
|
||||
set_task_fields(struct sp_meter *m, void *ctx)
|
||||
set_process_fields(struct sp_meter *m, void *ctx)
|
||||
{
|
||||
const unsigned *run = ctx;
|
||||
|
||||
@@ -91,7 +92,7 @@ publish_meter(struct sp_host *h)
|
||||
{
|
||||
unsigned run = (unsigned)running_count();
|
||||
|
||||
sp_host_meter_update(h, set_task_fields, &run);
|
||||
sp_host_meter_update(h, set_process_fields, &run);
|
||||
}
|
||||
|
||||
static void
|
||||
@@ -106,35 +107,37 @@ refresh_widget(struct sp_host *h)
|
||||
struct task *t = &tasks[i];
|
||||
int n;
|
||||
|
||||
if (t->running)
|
||||
n = snprintf(text + used, sizeof(text) - used,
|
||||
"#%d %s %lds\n", t->id, t->label,
|
||||
(long)(time(NULL) - t->started));
|
||||
else
|
||||
n = snprintf(text + used, sizeof(text) - used,
|
||||
"#%d %s exit %d %.2fs\n", t->id, t->label,
|
||||
t->status, difftime(t->ended, t->started));
|
||||
/*
|
||||
* The sidebar is for what is happening now. A finished task
|
||||
* stays in process_list/process_result (its output is still there),
|
||||
* but it does not take a row of the sidebar forever.
|
||||
*/
|
||||
if (!t->running)
|
||||
continue;
|
||||
n = snprintf(text + used, sizeof(text) - used,
|
||||
"#%d %s %lds\n", t->id, t->label,
|
||||
(long)(time(NULL) - t->started));
|
||||
if (n < 0 || (size_t)n >= sizeof(text) - used)
|
||||
break;
|
||||
used += (size_t)n;
|
||||
}
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
if (used == 0)
|
||||
(void)sp_host_widget_text(h, "tasks", "");
|
||||
(void)sp_host_widget_text(h, "processes", "");
|
||||
else
|
||||
(void)sp_host_widget_text(h, "tasks", text);
|
||||
(void)sp_host_widget_text(h, "processes", text);
|
||||
}
|
||||
|
||||
extern char **environ;
|
||||
|
||||
/*
|
||||
* The end of a task, under tasks_lock: that is the lock task_list, the widget
|
||||
* The end of a task, under tasks_lock: that is the lock process_list, the widget
|
||||
* and running_count read 'running', 'status' and 'ended' under. They used to
|
||||
* be written under the task's own lock only - two locks guarding one field
|
||||
* guard nothing.
|
||||
*/
|
||||
static void
|
||||
task_finish(struct task *t, int status)
|
||||
process_finish(struct task *t, int status)
|
||||
{
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
t->status = status;
|
||||
@@ -144,14 +147,14 @@ task_finish(struct task *t, int status)
|
||||
}
|
||||
|
||||
/*
|
||||
* Run the task in its own process group, so task_kill can stop the shell and
|
||||
* Run the task in its own process group, so process_kill can stop the shell and
|
||||
* everything it started. popen() gave no pid: t->pid stayed 0, and
|
||||
* kill(-0, SIGTERM) is "every process in my group" - task_kill killed
|
||||
* kill(-0, SIGTERM) is "every process in my group" - process_kill killed
|
||||
* splinter itself. stdin is /dev/null (a task must not read the terminal), and
|
||||
* the environment loses splinter's keys, as for the 'run' tool.
|
||||
*/
|
||||
static void *
|
||||
task_run(void *arg)
|
||||
process_run(void *arg)
|
||||
{
|
||||
struct task *t = arg;
|
||||
char chunk[2048];
|
||||
@@ -169,7 +172,7 @@ task_run(void *arg)
|
||||
pthread_mutex_lock(&t->lock);
|
||||
sp_buf_printf(&t->out, "error: %s", strerror(errno));
|
||||
pthread_mutex_unlock(&t->lock);
|
||||
task_finish(t, 127);
|
||||
process_finish(t, 127);
|
||||
return NULL;
|
||||
}
|
||||
for (i = 0, j = 0; i < n; i++)
|
||||
@@ -200,7 +203,7 @@ task_run(void *arg)
|
||||
pthread_mutex_lock(&t->lock);
|
||||
sp_buf_printf(&t->out, "error: fork: %s", strerror(errno));
|
||||
pthread_mutex_unlock(&t->lock);
|
||||
task_finish(t, 127);
|
||||
process_finish(t, 127);
|
||||
return NULL;
|
||||
}
|
||||
(void)setpgid(child, child);
|
||||
@@ -224,7 +227,7 @@ task_run(void *arg)
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
t->pid = 0; /* reaped: the id may be reused */
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
task_finish(t, st);
|
||||
process_finish(t, st);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -233,6 +236,8 @@ find(int id)
|
||||
{
|
||||
int i;
|
||||
|
||||
if (id <= 0)
|
||||
return NULL; /* 0 marks a released slot */
|
||||
for (i = 0; i < ntasks; i++)
|
||||
if (tasks[i].id == id)
|
||||
return &tasks[i];
|
||||
@@ -242,7 +247,7 @@ find(int id)
|
||||
/*
|
||||
* The value of an argument, with the parser the rest of splinter uses. The old
|
||||
* strstr() only matched "key":"..." - the schema declares 'id' an integer, so
|
||||
* {"id":3} came out empty and every task_kill said "no such task".
|
||||
* {"id":3} came out empty and every process_kill said "no such task".
|
||||
*/
|
||||
static void
|
||||
arg_str(const char *args, const char *key, char *buf, size_t len)
|
||||
@@ -267,6 +272,44 @@ arg_str(const char *args, const char *key, char *buf, size_t len)
|
||||
|
||||
static struct sp_host *host_ref;
|
||||
|
||||
/*
|
||||
* A slot for a new task, under tasks_lock. The table is small, but a session
|
||||
* starts more than sixteen tasks: once it is full, the finished task that ended
|
||||
* first gives its slot (and its output) up. Finished tasks stay listed until
|
||||
* then. NULL only when every slot is still running.
|
||||
*/
|
||||
static struct task *
|
||||
slot_alloc(void)
|
||||
{
|
||||
struct task *t = NULL;
|
||||
int i;
|
||||
|
||||
if (ntasks < TASKS_MAX)
|
||||
return &tasks[ntasks++];
|
||||
for (i = 0; i < ntasks; i++) {
|
||||
if (tasks[i].running)
|
||||
continue;
|
||||
if (t == NULL || tasks[i].ended < t->ended ||
|
||||
(tasks[i].ended == t->ended && tasks[i].id < t->id))
|
||||
t = &tasks[i];
|
||||
}
|
||||
if (t == NULL)
|
||||
return NULL;
|
||||
/* its thread is gone: process_finish() was its last touch */
|
||||
sp_buf_free(&t->out);
|
||||
(void)pthread_mutex_destroy(&t->lock);
|
||||
return t;
|
||||
}
|
||||
|
||||
/* a slot that never became a task: invisible, and the first to be reused */
|
||||
static void
|
||||
slot_release(struct task *t)
|
||||
{
|
||||
t->id = 0;
|
||||
t->running = 0;
|
||||
t->ended = 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Tasks someone else owns - a delegate on another host. They get an entry and a
|
||||
* clock, but no thread here: the harness closes them when the call returns.
|
||||
@@ -279,11 +322,10 @@ ops_begin(struct sp_host *h, const char *label, const char *detail)
|
||||
|
||||
(void)detail;
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
if (ntasks == TASKS_MAX) {
|
||||
if ((t = slot_alloc()) == NULL) {
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return -1;
|
||||
}
|
||||
t = &tasks[ntasks++];
|
||||
memset(t, 0, sizeof(*t));
|
||||
(void)pthread_mutex_init(&t->lock, NULL);
|
||||
t->id = next_id++;
|
||||
@@ -325,7 +367,7 @@ ops_end(struct sp_host *h, int id, int status, size_t tokens)
|
||||
static const struct sp_task_ops task_ops = { ops_begin, ops_end };
|
||||
|
||||
static int
|
||||
tool_task_start(const char *args, struct sp_buf *out, void *ctx)
|
||||
tool_process_start(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char cmd[600], label[80];
|
||||
struct task *t;
|
||||
@@ -344,11 +386,10 @@ tool_task_start(const char *args, struct sp_buf *out, void *ctx)
|
||||
max_parallel);
|
||||
|
||||
pthread_mutex_lock(&tasks_lock);
|
||||
if (ntasks == TASKS_MAX) {
|
||||
if ((t = slot_alloc()) == NULL) {
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return sp_buf_puts(out, "error: task table full");
|
||||
}
|
||||
t = &tasks[ntasks++];
|
||||
memset(t, 0, sizeof(*t));
|
||||
t->id = next_id++;
|
||||
(void)pthread_mutex_init(&t->lock, NULL);
|
||||
@@ -357,14 +398,14 @@ tool_task_start(const char *args, struct sp_buf *out, void *ctx)
|
||||
t->started = time(NULL);
|
||||
t->running = 1;
|
||||
if (sp_buf_init(&t->out) != 0) {
|
||||
ntasks--;
|
||||
slot_release(t);
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return sp_buf_puts(out, "error: no memory");
|
||||
}
|
||||
id = t->id;
|
||||
if (pthread_create(&t->th, NULL, task_run, t) != 0) {
|
||||
t->running = 0;
|
||||
ntasks--;
|
||||
if (pthread_create(&t->th, NULL, process_run, t) != 0) {
|
||||
sp_buf_free(&t->out);
|
||||
slot_release(t);
|
||||
pthread_mutex_unlock(&tasks_lock);
|
||||
return sp_buf_puts(out, "error: cannot start thread");
|
||||
}
|
||||
@@ -380,7 +421,7 @@ tool_task_start(const char *args, struct sp_buf *out, void *ctx)
|
||||
}
|
||||
|
||||
static int
|
||||
tool_task_list(const char *args, struct sp_buf *out, void *ctx)
|
||||
tool_process_list(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
int i, any = 0;
|
||||
|
||||
@@ -390,6 +431,8 @@ tool_task_list(const char *args, struct sp_buf *out, void *ctx)
|
||||
for (i = 0; i < ntasks; i++) {
|
||||
struct task *t = &tasks[i];
|
||||
|
||||
if (t->id == 0)
|
||||
continue; /* released slot */
|
||||
any = 1;
|
||||
if (t->running)
|
||||
sp_buf_printf(out, "#%d running %lds %zu B %s\n", t->id,
|
||||
@@ -407,7 +450,7 @@ tool_task_list(const char *args, struct sp_buf *out, void *ctx)
|
||||
}
|
||||
|
||||
static int
|
||||
tool_task_result(const char *args, struct sp_buf *out, void *ctx)
|
||||
tool_process_result(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char num[32];
|
||||
struct task *t;
|
||||
@@ -440,7 +483,7 @@ tool_task_result(const char *args, struct sp_buf *out, void *ctx)
|
||||
}
|
||||
|
||||
static int
|
||||
tool_task_kill(const char *args, struct sp_buf *out, void *ctx)
|
||||
tool_process_kill(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char num[32];
|
||||
struct task *t;
|
||||
@@ -475,31 +518,35 @@ tool_task_kill(const char *args, struct sp_buf *out, void *ctx)
|
||||
}
|
||||
|
||||
static const struct sp_tool t_start = {
|
||||
"task_start",
|
||||
"process_start",
|
||||
"Start a shell command in the background and return its id. Use it for "
|
||||
"builds, tests or long runs instead of blocking the conversation.",
|
||||
"{\"type\":\"object\",\"properties\":{\"command\":{\"type\":\"string\"},"
|
||||
"\"label\":{\"type\":\"string\",\"description\":\"short name\"}},"
|
||||
"\"required\":[\"command\"]}",
|
||||
SP_AUTH_DESTRUCTIVE, tool_task_start, NULL
|
||||
SP_AUTH_DESTRUCTIVE, tool_process_start, NULL,
|
||||
NULL
|
||||
};
|
||||
|
||||
static const struct sp_tool t_list = {
|
||||
"task_list", "List background tasks: id, state, time, size, label.",
|
||||
"{\"type\":\"object\",\"properties\":{}}", SP_AUTH_READ, tool_task_list,
|
||||
"process_list", "List background tasks: id, state, time, size, label.",
|
||||
"{\"type\":\"object\",\"properties\":{}}", SP_AUTH_READ, tool_process_list,
|
||||
NULL,
|
||||
NULL
|
||||
};
|
||||
|
||||
static const struct sp_tool t_result = {
|
||||
"task_result", "Output and exit status of a finished task.",
|
||||
"process_result", "Output and exit status of a finished task.",
|
||||
"{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\"}},"
|
||||
"\"required\":[\"id\"]}", SP_AUTH_READ, tool_task_result, NULL
|
||||
"\"required\":[\"id\"]}", SP_AUTH_READ, tool_process_result, NULL,
|
||||
NULL
|
||||
};
|
||||
|
||||
static const struct sp_tool t_kill = {
|
||||
"task_kill", "Stop a running task.",
|
||||
"process_kill", "Stop a running task.",
|
||||
"{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\"}},"
|
||||
"\"required\":[\"id\"]}", SP_AUTH_DESTRUCTIVE, tool_task_kill, NULL
|
||||
"\"required\":[\"id\"]}", SP_AUTH_DESTRUCTIVE, tool_process_kill, NULL,
|
||||
NULL
|
||||
};
|
||||
|
||||
static int
|
||||
@@ -513,7 +560,7 @@ tasks_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
}
|
||||
|
||||
static const struct sp_widget widget = {
|
||||
"tasks", /* name */
|
||||
"processes", /* name */
|
||||
tasks_tick, /* tick */
|
||||
NULL, /* draw */
|
||||
NULL, /* ctx */
|
||||
@@ -537,7 +584,7 @@ tasks_init(struct sp_host *h)
|
||||
(void)sp_host_add_tool(h, &t_result);
|
||||
(void)sp_host_add_tool(h, &t_kill);
|
||||
(void)sp_host_add_widget(h, &widget);
|
||||
(void)sp_host_widget_text(h, "tasks", "");
|
||||
(void)sp_host_widget_text(h, "processes", "");
|
||||
sp_host_set_task_ops(h, &task_ops);
|
||||
publish_meter(h);
|
||||
return 0;
|
||||
@@ -0,0 +1,228 @@
|
||||
/*
|
||||
* splinter -- the recap.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* /recap <text> set the recap; it goes into the conversation on the
|
||||
* next request and then every N turns
|
||||
* /recap show it
|
||||
* /recap every N change the interval (0 = never repeat)
|
||||
* /recap off forget it
|
||||
*
|
||||
* The recap is the operator's own text, put into the conversation as a system
|
||||
* message right before the newest user message. It is a real message: it stays
|
||||
* in the history, so a long session keeps meeting it and not only the
|
||||
* system prompt that sank under the conversation.
|
||||
*
|
||||
* Interval: plugin recap { every = 5 }, SPLINTER_RECAP_EVERY, or /recap every.
|
||||
* Default 5. The recap is kept per session in <session dir>/<id>.recap and
|
||||
* comes back on resume.
|
||||
*/
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
#define RECAP_MAX 1500
|
||||
#define EVERY_MAX 1000
|
||||
|
||||
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static char text[RECAP_MAX + 1];
|
||||
static unsigned every = 5;
|
||||
static unsigned last_turn = (unsigned)-1;
|
||||
static int fresh; /* set, and not yet in the conversation */
|
||||
static unsigned sent;
|
||||
static char session_id[64];
|
||||
|
||||
static int
|
||||
recap_path(struct sp_host *h, char *path, size_t n)
|
||||
{
|
||||
const char *dir = sp_host_session_dir(h);
|
||||
const char *id = sp_host_session_id(h);
|
||||
|
||||
if (dir == NULL || id == NULL || *id == '\0' || strchr(id, '/') != NULL)
|
||||
return -1;
|
||||
return snprintf(path, n, "%s/%s.recap", dir, id) < (int)n ? 0 : -1;
|
||||
}
|
||||
|
||||
static void
|
||||
recap_save(struct sp_host *h)
|
||||
{
|
||||
char path[1024];
|
||||
FILE *f;
|
||||
|
||||
if (recap_path(h, path, sizeof(path)) != 0)
|
||||
return;
|
||||
if (text[0] == '\0') {
|
||||
(void)remove(path);
|
||||
return;
|
||||
}
|
||||
if ((f = fopen(path, "w")) == NULL)
|
||||
return;
|
||||
(void)fputs(text, f);
|
||||
(void)fclose(f);
|
||||
}
|
||||
|
||||
/* The statics serve every session; reload when the session changes. */
|
||||
static void
|
||||
recap_sync(struct sp_host *h)
|
||||
{
|
||||
const char *id = sp_host_session_id(h);
|
||||
char path[1024];
|
||||
FILE *f;
|
||||
size_t n;
|
||||
|
||||
if (id == NULL || *id == '\0' || strcmp(session_id, id) == 0)
|
||||
return;
|
||||
snprintf(session_id, sizeof(session_id), "%s", id);
|
||||
text[0] = '\0';
|
||||
fresh = 0;
|
||||
last_turn = (unsigned)-1;
|
||||
if (recap_path(h, path, sizeof(path)) != 0 ||
|
||||
(f = fopen(path, "r")) == NULL)
|
||||
return;
|
||||
n = fread(text, 1, RECAP_MAX, f);
|
||||
text[n] = '\0';
|
||||
(void)fclose(f);
|
||||
}
|
||||
|
||||
static int
|
||||
recap_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
unsigned turn)
|
||||
{
|
||||
char msg[RECAP_MAX + 64];
|
||||
struct sp_msg m;
|
||||
size_t at, i;
|
||||
int due;
|
||||
|
||||
(void)budget;
|
||||
pthread_mutex_lock(&lock);
|
||||
recap_sync(h);
|
||||
if (conv == NULL || conv->n == 0 || text[0] == '\0') {
|
||||
pthread_mutex_unlock(&lock);
|
||||
return 0;
|
||||
}
|
||||
due = fresh || (every != 0 && turn != 0 && turn % every == 0);
|
||||
if (!due || turn == last_turn) {
|
||||
pthread_mutex_unlock(&lock);
|
||||
return 0;
|
||||
}
|
||||
last_turn = turn;
|
||||
fresh = 0;
|
||||
snprintf(msg, sizeof(msg), "[recap]\n%s\n", text);
|
||||
pthread_mutex_unlock(&lock);
|
||||
|
||||
at = conv->n;
|
||||
for (i = conv->n; i > 0; i--) {
|
||||
if (conv->v[i - 1].role != NULL &&
|
||||
strcmp(conv->v[i - 1].role, "user") == 0) {
|
||||
at = i - 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
memset(&m, 0, sizeof(m));
|
||||
m.role = "system";
|
||||
m.content = msg;
|
||||
if (sp_conv_add(conv, &m) != 0) {
|
||||
(void)sp_host_note(h, "recap: cannot add the message");
|
||||
return -1;
|
||||
}
|
||||
if (at < conv->n - 1) {
|
||||
struct sp_msg moved = conv->v[conv->n - 1];
|
||||
|
||||
memmove(&conv->v[at + 1], &conv->v[at],
|
||||
sizeof(conv->v[0]) * (conv->n - 1 - at));
|
||||
conv->v[at] = moved;
|
||||
}
|
||||
pthread_mutex_lock(&lock);
|
||||
sent++;
|
||||
pthread_mutex_unlock(&lock);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int
|
||||
recap_command(struct sp_host *h, const char *args, struct sp_buf *out,
|
||||
void *ctx)
|
||||
{
|
||||
int rc;
|
||||
|
||||
(void)ctx;
|
||||
pthread_mutex_lock(&lock);
|
||||
recap_sync(h);
|
||||
while (args != NULL && (*args == ' ' || *args == '\t'))
|
||||
args++;
|
||||
if (args == NULL || *args == '\0') {
|
||||
if (text[0] == '\0')
|
||||
rc = sp_buf_puts(out, "no recap set (/recap <text>)");
|
||||
else
|
||||
rc = sp_buf_printf(out,
|
||||
"recap: %s (every %u turns, %u sent)", text, every,
|
||||
sent);
|
||||
} else if (strcmp(args, "off") == 0) {
|
||||
text[0] = '\0';
|
||||
fresh = 0;
|
||||
recap_save(h);
|
||||
rc = sp_buf_puts(out, "recap removed");
|
||||
} else if (strncmp(args, "every ", 6) == 0) {
|
||||
char *end;
|
||||
unsigned long v = strtoul(args + 6, &end, 10);
|
||||
|
||||
while (*end == ' ')
|
||||
end++;
|
||||
if (end == args + 6 || *end != '\0' || v > EVERY_MAX)
|
||||
rc = sp_buf_printf(out, "every: 0..%d", EVERY_MAX);
|
||||
else {
|
||||
every = (unsigned)v;
|
||||
rc = sp_buf_printf(out, "recap every %u turns", every);
|
||||
}
|
||||
} else {
|
||||
snprintf(text, sizeof(text), "%.*s", RECAP_MAX, args);
|
||||
fresh = 1;
|
||||
sent = 0;
|
||||
recap_save(h);
|
||||
rc = sp_buf_printf(out, "recap set (every %u turns)", every);
|
||||
}
|
||||
pthread_mutex_unlock(&lock);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static const struct sp_compactor compactor = { "recap", recap_compact };
|
||||
|
||||
static int
|
||||
recap_init(struct sp_host *h)
|
||||
{
|
||||
const char *v = sp_host_plugin_config(h, "recap", "every");
|
||||
const char *env = getenv("SPLINTER_RECAP_EVERY");
|
||||
|
||||
if ((v == NULL || *v == '\0') && env != NULL)
|
||||
v = env;
|
||||
text[0] = '\0';
|
||||
session_id[0] = '\0';
|
||||
every = 5;
|
||||
if (v != NULL && *v != '\0') {
|
||||
unsigned long n = strtoul(v, NULL, 10);
|
||||
|
||||
if (n <= EVERY_MAX)
|
||||
every = (unsigned)n;
|
||||
}
|
||||
if (sp_host_add_compactor(h, &compactor) != 0 ||
|
||||
sp_host_add_command(h, "recap", recap_command, NULL) != 0) {
|
||||
(void)sp_host_note(h, "recap: cannot register");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin plugin = {
|
||||
SP_PLUGIN_ABI, "recap", "1.0", recap_init, NULL, NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &plugin;
|
||||
}
|
||||
+14
-1
@@ -293,13 +293,26 @@ ring_init(struct sp_host *h)
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* the exits own their contexts; the plugin's lifetime is the process's */
|
||||
static void
|
||||
ring_shutdown(struct sp_host *h)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
(void)h;
|
||||
for (i = 0; i < ring.n; i++)
|
||||
sp_transport_dispose(&ring.tr[i]);
|
||||
ring.n = 0;
|
||||
(void)pthread_mutex_destroy(&ring.lock);
|
||||
}
|
||||
|
||||
static const struct sp_plugin plugin = {
|
||||
SP_PLUGIN_ABI,
|
||||
"ring",
|
||||
"1.0",
|
||||
ring_init,
|
||||
NULL,
|
||||
NULL
|
||||
ring_shutdown
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
/*
|
||||
* splinter -- self: what this session costs the machine.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Every other widget talks about the world. This one talks about the process
|
||||
* the operator is looking at: how much memory, CPU, threads and file
|
||||
* descriptors splinter itself holds just by running, and how much its children
|
||||
* (a run tool, an MCP server child, a delegate, a CLI transport) hold under it.
|
||||
*
|
||||
* self
|
||||
* 84M rss 3.2% cpu
|
||||
* 18 thr 41 fd
|
||||
* kids 3 120M 1.4% cpu
|
||||
* io 12M r 300k w
|
||||
*
|
||||
* The numbers come from /proc: /proc/self/status (VmRSS, Threads), /proc/self/fd
|
||||
* (count), /proc/self/io (bytes), /proc/<pid>/stat (utime/stime, rss, PPid).
|
||||
* A child is any process whose parent chain reaches this pid; the walk is one
|
||||
* pass over /proc per tick, which is cheap next to what a model request costs.
|
||||
*
|
||||
* CPU is the delta between two ticks, not a lifetime average, so the widget
|
||||
* says "right now". IO is cumulative for the session; that is what "used"
|
||||
* means here.
|
||||
*
|
||||
* plugin self { interval = 2000 } # ms between samples
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <dirent.h>
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
#define SELF_KIDS_MAX 256
|
||||
#define SELF_LIST_MAX 12
|
||||
#define SELF_DEFAULT_MS 2000
|
||||
|
||||
struct kid {
|
||||
int pid;
|
||||
int ppid;
|
||||
unsigned long rss_pages;
|
||||
unsigned long long ticks;
|
||||
};
|
||||
|
||||
struct sample {
|
||||
unsigned long rss_kb;
|
||||
int threads;
|
||||
int fds;
|
||||
double cpu_pct;
|
||||
unsigned long io_read;
|
||||
unsigned long io_write;
|
||||
unsigned long long self_ticks;
|
||||
double kids_cpu_pct;
|
||||
unsigned long kids_rss_kb;
|
||||
int kids;
|
||||
};
|
||||
|
||||
static pthread_mutex_t self_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static struct sample now_s;
|
||||
static char widget[512];
|
||||
static char detail[4096];
|
||||
|
||||
static long hz;
|
||||
static unsigned long long prev_self_ticks;
|
||||
static double prev_time;
|
||||
static struct { int pid; unsigned long long ticks; } prev_kids[SELF_KIDS_MAX];
|
||||
static size_t prev_nkids;
|
||||
|
||||
static double
|
||||
mono_now(void)
|
||||
{
|
||||
struct timespec ts;
|
||||
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9;
|
||||
}
|
||||
|
||||
/* one /proc/<pid>/stat: ppid, resident pages and utime+stime in clock ticks */
|
||||
static int
|
||||
read_stat(int pid, struct kid *out)
|
||||
{
|
||||
char path[64], buf[2048], *p, *end;
|
||||
FILE *f;
|
||||
char state;
|
||||
long ppid;
|
||||
unsigned long pre[9]; /* pgrp .. cmajflt */
|
||||
unsigned long long utime, stime;
|
||||
unsigned long post[9]; /* cutime .. rss */
|
||||
|
||||
snprintf(path, sizeof(path), "/proc/%d/stat", pid);
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL)
|
||||
return -1;
|
||||
if (fgets(buf, sizeof(buf), f) == NULL) {
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
fclose(f);
|
||||
end = strrchr(buf, ')');
|
||||
if (end == NULL)
|
||||
return -1;
|
||||
p = end + 2; /* after "comm)": state ppid ... */
|
||||
if (sscanf(p, "%c %ld %lu %lu %lu %lu %lu %lu %lu %lu %lu "
|
||||
"%llu %llu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
|
||||
&state, &ppid,
|
||||
&pre[0], &pre[1], &pre[2], &pre[3], &pre[4], &pre[5], &pre[6],
|
||||
&pre[7], &pre[8],
|
||||
&utime, &stime,
|
||||
&post[0], &post[1], &post[2], &post[3], &post[4], &post[5],
|
||||
&post[6], &post[7], &post[8]) != 22)
|
||||
return -1;
|
||||
(void)state;
|
||||
out->pid = pid;
|
||||
out->ppid = (int)ppid;
|
||||
out->rss_pages = post[8]; /* the field named rss, in pages */
|
||||
out->ticks = utime + stime;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
read_self(struct sample *s)
|
||||
{
|
||||
FILE *f;
|
||||
char line[512];
|
||||
|
||||
s->rss_kb = 0;
|
||||
s->threads = 0;
|
||||
f = fopen("/proc/self/status", "r");
|
||||
if (f != NULL) {
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
unsigned long v;
|
||||
|
||||
if (sscanf(line, "VmRSS: %lu kB", &v) == 1)
|
||||
s->rss_kb = v;
|
||||
else if (sscanf(line, "Threads: %lu", &v) == 1)
|
||||
s->threads = (int)v;
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
{
|
||||
DIR *d = opendir("/proc/self/fd");
|
||||
int n = 0;
|
||||
|
||||
if (d != NULL) {
|
||||
struct dirent *e;
|
||||
|
||||
while ((e = readdir(d)) != NULL)
|
||||
if (e->d_name[0] != '.')
|
||||
n++;
|
||||
closedir(d);
|
||||
}
|
||||
s->fds = n;
|
||||
}
|
||||
f = fopen("/proc/self/io", "r");
|
||||
if (f != NULL) {
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
unsigned long v;
|
||||
|
||||
if (sscanf(line, "read_bytes: %lu", &v) == 1)
|
||||
s->io_read = v;
|
||||
else if (sscanf(line, "write_bytes: %lu", &v) == 1)
|
||||
s->io_write = v;
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
human(unsigned long kb, char *buf, size_t cap)
|
||||
{
|
||||
if (kb >= 1024 * 1024)
|
||||
snprintf(buf, cap, "%.1f GB",
|
||||
(double)kb / (1024.0 * 1024.0));
|
||||
else if (kb >= 1024)
|
||||
snprintf(buf, cap, "%.0f MB", (double)kb / 1024.0);
|
||||
else
|
||||
snprintf(buf, cap, "%lu kB", kb);
|
||||
}
|
||||
|
||||
static void
|
||||
human_bytes(unsigned long b, char *buf, size_t cap)
|
||||
{
|
||||
if (b >= 1024UL * 1024UL * 1024UL)
|
||||
snprintf(buf, cap, "%.1f GB",
|
||||
(double)b / (1024.0 * 1024.0 * 1024.0));
|
||||
else if (b >= 1024UL * 1024UL)
|
||||
snprintf(buf, cap, "%.1f MB", (double)b / (1024.0 * 1024.0));
|
||||
else if (b >= 1024)
|
||||
snprintf(buf, cap, "%.0f kB", (double)b / 1024.0);
|
||||
else
|
||||
snprintf(buf, cap, "%lu B", b);
|
||||
}
|
||||
|
||||
static int
|
||||
kid_cmp(const void *a, const void *b)
|
||||
{
|
||||
const struct kid *x = a, *y = b;
|
||||
|
||||
return (x->pid > y->pid) - (x->pid < y->pid);
|
||||
}
|
||||
|
||||
/*
|
||||
* Who is under this process: one read of every /proc/<pid>/stat - all of them,
|
||||
* a busy machine has thousands and stopping at a fixed count missed our own
|
||||
* pid - then include anything whose parent is already included until nothing
|
||||
* changes. Sorted by pid, a parent is a binary search away.
|
||||
*/
|
||||
static void
|
||||
scan_kids(struct sample *s)
|
||||
{
|
||||
DIR *d;
|
||||
struct kid *v = NULL;
|
||||
unsigned char *in = NULL;
|
||||
size_t *parent = NULL;
|
||||
size_t n = 0, cap = 0, i;
|
||||
int self = (int)getpid();
|
||||
|
||||
d = opendir("/proc");
|
||||
if (d != NULL) {
|
||||
struct dirent *e;
|
||||
|
||||
while ((e = readdir(d)) != NULL) {
|
||||
char *end;
|
||||
long pid = strtol(e->d_name, &end, 10);
|
||||
|
||||
if (*end != '\0' || pid <= 0)
|
||||
continue;
|
||||
if (n == cap) {
|
||||
size_t ncap = cap ? cap * 2 : 512;
|
||||
struct kid *nv = realloc(v, ncap * sizeof(*nv));
|
||||
|
||||
if (nv == NULL)
|
||||
break;
|
||||
v = nv;
|
||||
cap = ncap;
|
||||
}
|
||||
memset(&v[n], 0, sizeof(v[n]));
|
||||
if (read_stat((int)pid, &v[n]) != 0)
|
||||
continue;
|
||||
n++;
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
if (n > 0) {
|
||||
in = calloc(n, sizeof(*in));
|
||||
parent = calloc(n, sizeof(*parent));
|
||||
if (in == NULL || parent == NULL)
|
||||
n = 0;
|
||||
}
|
||||
if (n > 0) {
|
||||
qsort(v, n, sizeof(*v), kid_cmp);
|
||||
for (i = 0; i < n; i++) {
|
||||
struct kid key, *pp;
|
||||
|
||||
key.pid = v[i].ppid;
|
||||
pp = bsearch(&key, v, n, sizeof(*v), kid_cmp);
|
||||
parent[i] = pp != NULL ? (size_t)(pp - v) : n;
|
||||
in[i] = v[i].pid == self;
|
||||
}
|
||||
}
|
||||
/* each pass adds at least one more generation, so this ends */
|
||||
for (;;) {
|
||||
int changed = 0;
|
||||
|
||||
for (i = 0; i < n; i++)
|
||||
if (!in[i] && parent[i] < n && in[parent[i]]) {
|
||||
in[i] = 1;
|
||||
changed = 1;
|
||||
}
|
||||
if (!changed)
|
||||
break;
|
||||
}
|
||||
s->kids = 0;
|
||||
s->kids_rss_kb = 0;
|
||||
s->kids_cpu_pct = 0;
|
||||
{
|
||||
double dt = prev_time > 0 ? mono_now() - prev_time : 0;
|
||||
unsigned long long sum = 0;
|
||||
|
||||
for (i = 0; i < n; i++) {
|
||||
size_t pi2;
|
||||
|
||||
if (!in[i] || v[i].pid == self)
|
||||
continue;
|
||||
s->kids++;
|
||||
s->kids_rss_kb += v[i].rss_pages *
|
||||
(unsigned long)(sysconf(_SC_PAGESIZE) / 1024);
|
||||
for (pi2 = 0; pi2 < prev_nkids; pi2++)
|
||||
if (prev_kids[pi2].pid == v[i].pid) {
|
||||
sum += v[i].ticks -
|
||||
prev_kids[pi2].ticks;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (dt > 0 && hz > 0)
|
||||
s->kids_cpu_pct = (double)sum / (double)hz / dt * 100.0;
|
||||
}
|
||||
prev_nkids = 0;
|
||||
for (i = 0; i < n && prev_nkids < SELF_KIDS_MAX; i++)
|
||||
if (in[i] && v[i].pid != self) {
|
||||
prev_kids[prev_nkids].pid = v[i].pid;
|
||||
prev_kids[prev_nkids].ticks = v[i].ticks;
|
||||
prev_nkids++;
|
||||
}
|
||||
free(v);
|
||||
free(in);
|
||||
free(parent);
|
||||
}
|
||||
|
||||
static void
|
||||
sample(struct sample *s)
|
||||
{
|
||||
struct kid self;
|
||||
double now = mono_now();
|
||||
double dt = prev_time > 0 ? now - prev_time : 0;
|
||||
|
||||
memset(s, 0, sizeof(*s));
|
||||
read_self(s);
|
||||
if (read_stat((int)getpid(), &self) == 0) {
|
||||
s->self_ticks = self.ticks;
|
||||
if (dt > 0 && hz > 0 && prev_self_ticks > 0)
|
||||
s->cpu_pct = (double)(self.ticks - prev_self_ticks) /
|
||||
(double)hz / dt * 100.0;
|
||||
prev_self_ticks = self.ticks;
|
||||
}
|
||||
scan_kids(s);
|
||||
prev_time = now;
|
||||
}
|
||||
|
||||
static void
|
||||
compose(struct sample *s)
|
||||
{
|
||||
char rss[24], kids[24], r[24], w[24];
|
||||
|
||||
human(s->rss_kb, rss, sizeof(rss));
|
||||
human(s->kids_rss_kb, kids, sizeof(kids));
|
||||
human_bytes(s->io_read, r, sizeof(r));
|
||||
human_bytes(s->io_write, w, sizeof(w));
|
||||
if (s->kids == 0)
|
||||
snprintf(widget, sizeof(widget),
|
||||
"%s memory | %.1f%% cpu\n"
|
||||
"%d threads | %d open files\n"
|
||||
"no children\n"
|
||||
"io %s read | %s written",
|
||||
rss, s->cpu_pct, s->threads, s->fds, r, w);
|
||||
else
|
||||
snprintf(widget, sizeof(widget),
|
||||
"%s memory | %.1f%% cpu\n"
|
||||
"%d threads | %d open files\n"
|
||||
"children %d | %s | %.1f%% cpu\n"
|
||||
"io %s read | %s written",
|
||||
rss, s->cpu_pct, s->threads, s->fds, s->kids, kids,
|
||||
s->kids_cpu_pct, r, w);
|
||||
|
||||
snprintf(detail, sizeof(detail),
|
||||
"self: pid %d\n"
|
||||
" memory (RSS): %s (%lu kB)\n"
|
||||
" threads: %d\n"
|
||||
" open files: %d\n"
|
||||
" cpu: %.1f%%\n"
|
||||
" io: %s read, %s written\n"
|
||||
"children: %d process(es), %s rss, %.1f%% cpu\n",
|
||||
(int)getpid(), rss, s->rss_kb, s->threads, s->fds, s->cpu_pct,
|
||||
r, w, s->kids, kids, s->kids_cpu_pct);
|
||||
}
|
||||
|
||||
static int
|
||||
self_tick(struct sp_host *h, const char *name, void *ctx)
|
||||
{
|
||||
struct sample s;
|
||||
|
||||
(void)ctx;
|
||||
if (hz <= 0)
|
||||
hz = sysconf(_SC_CLK_TCK);
|
||||
sample(&s);
|
||||
pthread_mutex_lock(&self_lock);
|
||||
now_s = s;
|
||||
compose(&s);
|
||||
pthread_mutex_unlock(&self_lock);
|
||||
return sp_host_widget_text(h, name, widget);
|
||||
}
|
||||
|
||||
static void
|
||||
copy_detail(char *out, size_t cap)
|
||||
{
|
||||
pthread_mutex_lock(&self_lock);
|
||||
snprintf(out, cap, "%s", detail);
|
||||
pthread_mutex_unlock(&self_lock);
|
||||
}
|
||||
|
||||
static int
|
||||
self_tool(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char buf[sizeof(detail)];
|
||||
|
||||
(void)args;
|
||||
(void)ctx;
|
||||
copy_detail(buf, sizeof(buf));
|
||||
sp_buf_puts(out, buf);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
self_command(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
char buf[sizeof(detail)];
|
||||
|
||||
(void)h;
|
||||
(void)ctx;
|
||||
if (args != NULL && *args != '\0')
|
||||
return sp_buf_puts(out, "usage: /self");
|
||||
copy_detail(buf, sizeof(buf));
|
||||
sp_buf_puts(out, buf);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
self_init(struct sp_host *h)
|
||||
{
|
||||
struct sp_widget w;
|
||||
static const struct sp_status seg = { "self", NULL };
|
||||
static const struct sp_tool t = {
|
||||
"session_usage",
|
||||
"What this splinter process costs the machine: RSS, CPU, threads "
|
||||
"and file descriptors of the session itself, and the same for "
|
||||
"every child process under it.",
|
||||
"{\"type\":\"object\",\"properties\":{}}",
|
||||
SP_AUTH_READ,
|
||||
self_tool,
|
||||
NULL,
|
||||
NULL
|
||||
};
|
||||
const char *iv;
|
||||
|
||||
hz = sysconf(_SC_CLK_TCK);
|
||||
memset(&w, 0, sizeof(w));
|
||||
w.name = "self";
|
||||
w.tick = self_tick;
|
||||
iv = sp_host_plugin_config(h, "self", "interval");
|
||||
w.interval_ms = iv != NULL && atoi(iv) > 0 ?
|
||||
(unsigned)atoi(iv) : SELF_DEFAULT_MS;
|
||||
if (sp_host_add_widget(h, &w) != 0)
|
||||
return -1;
|
||||
if (sp_host_add_tool(h, &t) != 0)
|
||||
return -1;
|
||||
if (sp_host_add_command(h, "self", self_command, NULL) != 0)
|
||||
return -1;
|
||||
(void)seg;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin self_plugin = {
|
||||
SP_PLUGIN_ABI, "self", "1.0.0", self_init, NULL, NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &self_plugin;
|
||||
}
|
||||
@@ -0,0 +1,462 @@
|
||||
/*
|
||||
* splinter -- the session plugin: what earlier conversations in this folder said.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* The conversation that is running is the context; this is the rest of the
|
||||
* folder's history. Two tools:
|
||||
*
|
||||
* session_search text in the logs of earlier sessions, with date, id and
|
||||
* title, so the model can quote where it found something
|
||||
* session_list the earlier sessions themselves (date, size, title)
|
||||
*
|
||||
* Both read the same .jsonl files the engine writes; nothing else is kept. The
|
||||
* running session is left out on purpose -- it is already in the prompt, and
|
||||
* the lcm plugin's recall covers what compaction dropped from it.
|
||||
*
|
||||
* "This folder's history" is not only splinter's. Claude Code, Hermes and
|
||||
* opencode keep their own sessions, and the same question -- what did we do
|
||||
* here? -- is answered wrongly when they are left out. This plugin does not
|
||||
* learn their three storage formats: the foreign plugin already knows them and
|
||||
* says so for the same working directory, so its tools are called through the
|
||||
* registry. When it is not loaded, the splinter logs are the whole answer and
|
||||
* the note at the end says so instead of pretending the machine is empty.
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "mcp.h"
|
||||
|
||||
#define MAX_SCAN 400 /* sessions looked at, newest first */
|
||||
#define HIT_BYTES 240 /* text shown around a match */
|
||||
#define TOTAL_BYTES 12000 /* the whole answer, so it stays cheap */
|
||||
#define SCAN_BYTES (64 * 1024 * 1024)
|
||||
|
||||
/* case-blind substring, like the lcm plugin's recall */
|
||||
static int
|
||||
has_ci(const char *hay, const char *needle)
|
||||
{
|
||||
size_t n = strlen(needle), i;
|
||||
const char *p;
|
||||
|
||||
for (p = hay; *p != '\0'; p++) {
|
||||
for (i = 0; i < n && p[i] != '\0'; i++)
|
||||
if (tolower((unsigned char)p[i]) !=
|
||||
tolower((unsigned char)needle[i]))
|
||||
break;
|
||||
if (i == n)
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* where the needle is, case-blind, or -1 */
|
||||
static long
|
||||
find_ci(const char *hay, const char *needle)
|
||||
{
|
||||
size_t n = strlen(needle), i;
|
||||
const char *p;
|
||||
|
||||
for (p = hay; *p != '\0'; p++) {
|
||||
for (i = 0; i < n && p[i] != '\0'; i++)
|
||||
if (tolower((unsigned char)p[i]) !=
|
||||
tolower((unsigned char)needle[i]))
|
||||
break;
|
||||
if (i == n)
|
||||
return (long)(p - hay);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* the readable part around a match: control characters become spaces */
|
||||
static void
|
||||
snippet(struct sp_buf *b, const char *text, const char *query)
|
||||
{
|
||||
long at = find_ci(text, query);
|
||||
size_t len = strlen(text), from = 0, n, i;
|
||||
|
||||
if (at > 60)
|
||||
from = (size_t)at - 60;
|
||||
n = len - from;
|
||||
if (n > HIT_BYTES)
|
||||
n = HIT_BYTES;
|
||||
if (from > 0)
|
||||
sp_buf_puts(b, "...");
|
||||
for (i = 0; i < n; i++) {
|
||||
char c = text[from + i];
|
||||
|
||||
if ((unsigned char)c < 0x20 || (unsigned char)c == 0x7f)
|
||||
c = ' ';
|
||||
(void)sp_buf_add(b, &c, 1);
|
||||
}
|
||||
if (from + n < len)
|
||||
sp_buf_puts(b, "...");
|
||||
}
|
||||
|
||||
static void
|
||||
stamp_of(long mtime, char *buf, size_t cap)
|
||||
{
|
||||
struct tm tm;
|
||||
|
||||
if (localtime_r(&(time_t){ mtime }, &tm) == NULL) {
|
||||
snprintf(buf, cap, "?");
|
||||
return;
|
||||
}
|
||||
strftime(buf, cap, "%Y-%m-%d %H:%M", &tm);
|
||||
}
|
||||
|
||||
/*
|
||||
* The other harnesses, through the foreign plugin's own tools.
|
||||
*
|
||||
* Why not read Claude's jsonl and the two sqlite stores here: the foreign
|
||||
* plugin already does, including the schemas, the sidechain filter and which
|
||||
* Hermes profile has a state.db. A second copy would be a second thing to keep
|
||||
* right, and the first store that changed shape would make the two disagree
|
||||
* about the same folder.
|
||||
*
|
||||
* The call is by tool name through the registry, so this works whenever the
|
||||
* foreign plugin is loaded and does nothing when it is not. `args` is the
|
||||
* foreign tool's own arguments; the answer is appended as-is, because it is
|
||||
* written in the same shape this plugin writes (date, source, id, role,
|
||||
* snippet).
|
||||
*/
|
||||
static int
|
||||
ask_foreign(struct sp_host *h, const char *tool, const char *args,
|
||||
struct sp_buf *out)
|
||||
{
|
||||
struct sp_registry *reg = sp_host_registry(h);
|
||||
const struct sp_tool *t;
|
||||
struct sp_buf tmp;
|
||||
int rc;
|
||||
|
||||
if (reg == NULL || out == NULL)
|
||||
return 0;
|
||||
t = sp_registry_find(reg, tool);
|
||||
if (t == NULL || t->run == NULL)
|
||||
return 0; /* plugin not loaded: nothing to ask */
|
||||
if (sp_buf_init(&tmp) != 0)
|
||||
return 0;
|
||||
rc = t->run(args, &tmp, t->ctx);
|
||||
if (rc == 0 && tmp.len > 0 && tmp.p != NULL) {
|
||||
size_t before = out->len;
|
||||
|
||||
(void)sp_buf_add(out, tmp.p, tmp.len);
|
||||
if (out->len > before && out->p[out->len - 1] != '\n')
|
||||
(void)sp_buf_puts(out, "\n");
|
||||
}
|
||||
sp_buf_free(&tmp);
|
||||
return rc == 0 ? 1 : 0;
|
||||
}
|
||||
|
||||
/* JSON string literal for one argument, escaped */
|
||||
static void
|
||||
arg_str(struct sp_buf *b, const char *key, const char *val)
|
||||
{
|
||||
(void)sp_buf_puts(b, ",\"");
|
||||
(void)sp_buf_puts(b, key);
|
||||
(void)sp_buf_puts(b, "\":\"");
|
||||
(void)sp_json_escape(b, val);
|
||||
(void)sp_buf_puts(b, "\"");
|
||||
}
|
||||
|
||||
/* the same for an integer argument; 0 means "not given" for both callers */
|
||||
static void
|
||||
arg_int(struct sp_buf *b, const char *key, int val)
|
||||
{
|
||||
char num[32];
|
||||
|
||||
if (val <= 0)
|
||||
return;
|
||||
snprintf(num, sizeof(num), ",\"%s\":%d", key, val);
|
||||
(void)sp_buf_puts(b, num);
|
||||
}
|
||||
|
||||
static int
|
||||
session_search(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
struct sp_host *h = ctx;
|
||||
const char *dir = sp_host_session_dir(h);
|
||||
const char *cur = sp_host_session_id(h);
|
||||
struct sp_session_brief *v;
|
||||
char query[200] = "", only[64] = "", cwd[512];
|
||||
int limit = 10, days = 0, nv, i, hits = 0, scanned = 0;
|
||||
int fhits = 0;
|
||||
long now = (long)time(NULL), budget = SCAN_BYTES;
|
||||
mcp_json *a;
|
||||
|
||||
if (dir == NULL || *dir == '\0')
|
||||
return sp_buf_puts(out, "error: no session directory");
|
||||
/* Only sessions that ran in this working directory: "what did we do
|
||||
* last?" is about this folder, not about every conversation ever. */
|
||||
if (getcwd(cwd, sizeof(cwd)) == NULL)
|
||||
return sp_buf_puts(out, "error: cannot determine the working "
|
||||
"directory");
|
||||
if (args != NULL && args[0] == '{' && (a = mcp_parse(args)) != NULL) {
|
||||
const char *q = mcp_arg_string(a, "query");
|
||||
const char *s = mcp_arg_string(a, "session");
|
||||
|
||||
if (q != NULL)
|
||||
snprintf(query, sizeof(query), "%s", q);
|
||||
if (s != NULL)
|
||||
snprintf(only, sizeof(only), "%s", s);
|
||||
limit = mcp_arg_int(a, "limit", 10);
|
||||
days = mcp_arg_int(a, "days", 0);
|
||||
mcp_json_free(a);
|
||||
}
|
||||
if (query[0] == '\0')
|
||||
return sp_buf_puts(out, "error: 'query' is required");
|
||||
if (limit < 1 || limit > 50)
|
||||
limit = 10;
|
||||
v = calloc(MAX_SCAN, sizeof(*v));
|
||||
if (v == NULL)
|
||||
return sp_buf_puts(out, "error: out of memory");
|
||||
nv = sp_session_list(dir, v, MAX_SCAN);
|
||||
if (nv < 0) {
|
||||
free(v);
|
||||
return sp_buf_puts(out, "error: cannot read the session directory");
|
||||
}
|
||||
for (i = 0; i < nv && hits < limit; i++) {
|
||||
char path[800], *line = NULL;
|
||||
size_t cap = 0;
|
||||
ssize_t len;
|
||||
FILE *f;
|
||||
|
||||
if (only[0] == '\0' && cur != NULL && strcmp(v[i].id, cur) == 0)
|
||||
continue; /* running session: context, not history */
|
||||
if (only[0] != '\0' && strcmp(v[i].id, only) != 0)
|
||||
continue;
|
||||
{
|
||||
char scwd[512];
|
||||
|
||||
if (sp_session_cwd(dir, v[i].id, scwd,
|
||||
sizeof(scwd)) != 0 || strcmp(scwd, cwd) != 0)
|
||||
continue;
|
||||
}
|
||||
if (days > 0 && v[i].mtime < now - (long)days * 86400)
|
||||
continue;
|
||||
if (budget <= 0)
|
||||
break;
|
||||
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, v[i].id);
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL)
|
||||
continue;
|
||||
scanned++;
|
||||
while (hits < limit && (len = getline(&line, &cap, f)) != -1) {
|
||||
mcp_json *m;
|
||||
const char *role, *text;
|
||||
char stamp[32], title[96];
|
||||
|
||||
budget -= (long)len;
|
||||
if (!has_ci(line, query))
|
||||
continue;
|
||||
m = mcp_parse(line);
|
||||
if (m == NULL)
|
||||
continue;
|
||||
role = mcp_arg_string(m, "role");
|
||||
text = mcp_arg_string(m, "text");
|
||||
if (text == NULL || !has_ci(text, query)) {
|
||||
mcp_json_free(m);
|
||||
continue;
|
||||
}
|
||||
stamp_of(v[i].mtime, stamp, sizeof(stamp));
|
||||
snprintf(title, sizeof(title), "%s",
|
||||
v[i].title[0] != '\0' ? v[i].title : "(untitled)");
|
||||
sp_buf_printf(out, "%s %s \"%s\" %s: ", stamp,
|
||||
v[i].id, title, role != NULL ? role : "?");
|
||||
snippet(out, text, query);
|
||||
sp_buf_puts(out, "\n");
|
||||
hits++;
|
||||
mcp_json_free(m);
|
||||
if (out->len >= TOTAL_BYTES)
|
||||
break;
|
||||
}
|
||||
free(line);
|
||||
fclose(f);
|
||||
}
|
||||
free(v);
|
||||
/*
|
||||
* The rest of this folder's history: the same three stores the foreign
|
||||
* plugin reads. Only when the answer still has room -- a search that
|
||||
* already filled its limit has nothing to add, and the caller asked for
|
||||
* `limit` rows, not for a report about every harness.
|
||||
*
|
||||
* `session` is not passed on: it names a splinter session id, which the
|
||||
* other harnesses cannot have. A search restricted to one id stays a
|
||||
* pure splinter search instead of listing foreign hits under it.
|
||||
*/
|
||||
if (only[0] == '\0' && hits < limit && out->len < TOTAL_BYTES) {
|
||||
struct sp_buf fa;
|
||||
char num[64];
|
||||
|
||||
if (sp_buf_init(&fa) == 0) {
|
||||
(void)sp_buf_puts(&fa, "{\"query\":\"");
|
||||
(void)sp_json_escape(&fa, query);
|
||||
(void)sp_buf_puts(&fa, "\"");
|
||||
snprintf(num, sizeof(num), ",\"limit\":%d", limit - hits);
|
||||
(void)sp_buf_puts(&fa, num);
|
||||
arg_int(&fa, "days", days);
|
||||
(void)sp_buf_puts(&fa, "}");
|
||||
fhits = ask_foreign(h, "foreign_search", fa.p, out) ?
|
||||
1 : 0;
|
||||
sp_buf_free(&fa);
|
||||
}
|
||||
}
|
||||
if (hits == 0 && fhits == 0)
|
||||
sp_buf_printf(out, "no message in %d earlier session%s contains "
|
||||
"'%s'", scanned, scanned == 1 ? "" : "s", query);
|
||||
else if (hits >= limit || out->len >= TOTAL_BYTES)
|
||||
sp_buf_puts(out, "... (limit reached; narrow the query or raise "
|
||||
"limit)\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
session_list_tool(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
struct sp_host *h = ctx;
|
||||
const char *dir = sp_host_session_dir(h);
|
||||
const char *cur = sp_host_session_id(h);
|
||||
struct sp_session_brief *v;
|
||||
char cwd[512], num[32];
|
||||
int limit = 15, days = 0, nv, i, shown = 0;
|
||||
long now = (long)time(NULL);
|
||||
mcp_json *a;
|
||||
|
||||
if (dir == NULL || *dir == '\0')
|
||||
return sp_buf_puts(out, "error: no session directory");
|
||||
if (getcwd(cwd, sizeof(cwd)) == NULL)
|
||||
return sp_buf_puts(out, "error: cannot determine the working "
|
||||
"directory");
|
||||
if (args != NULL && args[0] == '{' && (a = mcp_parse(args)) != NULL) {
|
||||
limit = mcp_arg_int(a, "limit", 15);
|
||||
days = mcp_arg_int(a, "days", 0);
|
||||
mcp_json_free(a);
|
||||
}
|
||||
if (limit < 1 || limit > 100)
|
||||
limit = 15;
|
||||
v = calloc(MAX_SCAN, sizeof(*v));
|
||||
if (v == NULL)
|
||||
return sp_buf_puts(out, "error: out of memory");
|
||||
nv = sp_session_list(dir, v, MAX_SCAN);
|
||||
if (nv < 0) {
|
||||
free(v);
|
||||
return sp_buf_puts(out, "error: cannot read the session directory");
|
||||
}
|
||||
for (i = 0; i < nv && shown < limit; i++) {
|
||||
char stamp[32], scwd[512];
|
||||
|
||||
if (sp_session_cwd(dir, v[i].id, scwd, sizeof(scwd)) != 0 ||
|
||||
strcmp(scwd, cwd) != 0)
|
||||
continue;
|
||||
if (days > 0 && v[i].mtime < now - (long)days * 86400)
|
||||
continue;
|
||||
stamp_of(v[i].mtime, stamp, sizeof(stamp));
|
||||
sp_buf_printf(out, "%s %s %6.1f KiB %s%s\n", stamp,
|
||||
v[i].id, (double)v[i].bytes / 1024.0,
|
||||
v[i].title[0] != '\0' ? v[i].title : "(untitled)",
|
||||
(cur != NULL && strcmp(v[i].id, cur) == 0) ?
|
||||
" (current)" : "");
|
||||
shown++;
|
||||
}
|
||||
free(v);
|
||||
/*
|
||||
* The other harnesses' sessions in the same folder, through the foreign
|
||||
* plugin. Same reason as in session_search: it already knows the three
|
||||
* stores. A cwd that cannot be read is not passed as a filter -- the
|
||||
* foreign side would then list every folder, which is a different
|
||||
* question than the one asked.
|
||||
*/
|
||||
if (shown < limit) {
|
||||
struct sp_buf fa;
|
||||
|
||||
if (sp_buf_init(&fa) == 0) {
|
||||
(void)sp_buf_puts(&fa, "{\"limit\":");
|
||||
snprintf(num, sizeof(num), "%d", limit - shown);
|
||||
(void)sp_buf_puts(&fa, num);
|
||||
arg_str(&fa, "cwd", cwd);
|
||||
(void)sp_buf_puts(&fa, "}");
|
||||
(void)ask_foreign(h, "foreign_list", fa.p, out);
|
||||
sp_buf_free(&fa);
|
||||
}
|
||||
}
|
||||
if (shown == 0)
|
||||
sp_buf_puts(out, "no sessions");
|
||||
else if (shown >= limit)
|
||||
sp_buf_puts(out, "... (limit reached)\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_tool search_tool = {
|
||||
"session_search",
|
||||
"Search the logs of earlier sessions that ran in this working directory: "
|
||||
"what the user and the tools said, with date, session id and title. "
|
||||
"Sessions from other folders are not searched -- this answers \"what did "
|
||||
"we do here?\". Use it before asking the user something the fleet may "
|
||||
"already have answered, and when the prompt says this directory has "
|
||||
"earlier sessions. The running session is not searched; it is already in "
|
||||
"your context.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"query\":{\"type\":\"string\",\"description\":\"text to find "
|
||||
"(case-blind)\"},"
|
||||
"\"limit\":{\"type\":\"integer\",\"description\":\"max matches, default "
|
||||
"10, max 50\"},"
|
||||
"\"days\":{\"type\":\"integer\",\"description\":\"only sessions changed "
|
||||
"in the last N days\"},"
|
||||
"\"session\":{\"type\":\"string\",\"description\":\"only this session id "
|
||||
"from session_list\"}},"
|
||||
"\"required\":[\"query\"]}",
|
||||
SP_AUTH_READ,
|
||||
session_search,
|
||||
NULL,
|
||||
NULL
|
||||
};
|
||||
|
||||
static const struct sp_tool list_tool = {
|
||||
"session_list",
|
||||
"List the earlier sessions that ran in this working directory, newest "
|
||||
"first: date, id, size and title. Sessions from other folders are left "
|
||||
"out. Use it to see what was worked on here before, then session_search "
|
||||
"to read the part you need.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"limit\":{\"type\":\"integer\",\"description\":\"max sessions, default "
|
||||
"15, max 100\"},"
|
||||
"\"days\":{\"type\":\"integer\",\"description\":\"only sessions changed "
|
||||
"in the last N days\"}}}",
|
||||
SP_AUTH_READ,
|
||||
session_list_tool,
|
||||
NULL,
|
||||
NULL
|
||||
};
|
||||
|
||||
static int
|
||||
session_init(struct sp_host *h)
|
||||
{
|
||||
static struct sp_tool st = search_tool;
|
||||
static struct sp_tool lt = list_tool;
|
||||
|
||||
st.ctx = h;
|
||||
lt.ctx = h;
|
||||
if (sp_host_add_tool(h, &st) != 0)
|
||||
return -1;
|
||||
if (sp_host_add_tool(h, <) != 0)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_plugin session_plugin = {
|
||||
SP_PLUGIN_ABI, "session", "1.0.0", session_init, NULL, NULL
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &session_plugin;
|
||||
}
|
||||
+31
-9
@@ -8,6 +8,11 @@
|
||||
*
|
||||
* clock: 17:20:01 | ctx 12.3k/32k [|||||||...] | 41 tok/s | 1.2k tok | $0.0042
|
||||
*
|
||||
* The segments go to sp_host_add_status(): /status shows them in the
|
||||
* transcript and the Telegram gateway sends them with its replies. The chat's
|
||||
* status bar draws its own meters (context, cache, speed, the running turn);
|
||||
* the segments are not squeezed onto that line.
|
||||
*
|
||||
* The numbers come from the harness (struct sp_meter), never from the plugin
|
||||
* counting for itself: two counters that disagree are worse than none.
|
||||
*
|
||||
@@ -15,7 +20,8 @@
|
||||
*
|
||||
* SPLINTER_PRICE_IN=3.0 dollars per million input tokens
|
||||
* SPLINTER_PRICE_OUT=15.0 dollars per million output tokens
|
||||
* SPLINTER_PRICE_CACHED=0.3
|
||||
* SPLINTER_PRICE_CACHED=0.3 per million input tokens served from the
|
||||
* provider's cache (default: the input price)
|
||||
*
|
||||
* Without them the cost segment says nothing rather than inventing a number.
|
||||
*/
|
||||
@@ -30,6 +36,7 @@
|
||||
#define BAR_WIDTH 24
|
||||
|
||||
static double price_in, price_out, price_cached;
|
||||
static int have_cached; /* SPLINTER_PRICE_CACHED was set */
|
||||
|
||||
static void
|
||||
human(size_t n, char *buf, size_t len)
|
||||
@@ -121,18 +128,32 @@ render_cost(struct sp_host *h, char *buf, size_t len)
|
||||
const struct sp_meter *m = &mm;
|
||||
|
||||
sp_host_meter_get(h, &mm);
|
||||
/*
|
||||
* A provider that reports a cost is believed over our own arithmetic:
|
||||
* a router may bill differently than its list price.
|
||||
*/
|
||||
if (m->cost > 0) {
|
||||
snprintf(buf, len, "$%.4f", m->cost);
|
||||
return;
|
||||
}
|
||||
if (price_in == 0 && price_out == 0) {
|
||||
buf[0] = '\0';
|
||||
return;
|
||||
}
|
||||
/*
|
||||
* The price belongs to the model, the tokens belong to the harness: the
|
||||
* product is computed here so a price change needs no rebuild of anything
|
||||
* else.
|
||||
* Cached input tokens are part of tok_in and billed at their own
|
||||
* price; without one they cost what any input token does.
|
||||
*/
|
||||
snprintf(buf, len, "$%.4f",
|
||||
(double)m->tok_in * price_in / 1e6 +
|
||||
(double)m->tok_out * price_out / 1e6);
|
||||
{
|
||||
size_t cached = m->cached_total <= m->tok_in ?
|
||||
m->cached_total : m->tok_in;
|
||||
double pc = have_cached ? price_cached : price_in;
|
||||
|
||||
snprintf(buf, len, "$%.4f",
|
||||
(double)(m->tok_in - cached) * price_in / 1e6 +
|
||||
(double)cached * pc / 1e6 +
|
||||
(double)m->tok_out * price_out / 1e6);
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
@@ -185,9 +206,10 @@ status_init(struct sp_host *h)
|
||||
price_in = strtod(in, NULL);
|
||||
if (out != NULL && *out != '\0')
|
||||
price_out = strtod(out, NULL);
|
||||
if (cached != NULL && *cached != '\0')
|
||||
if (cached != NULL && *cached != '\0') {
|
||||
price_cached = strtod(cached, NULL);
|
||||
(void)price_cached;
|
||||
have_cached = 1;
|
||||
}
|
||||
|
||||
(void)sp_host_add_status(h, &seg_clock);
|
||||
(void)sp_host_add_status(h, &seg_ctx);
|
||||
|
||||
@@ -1,826 +0,0 @@
|
||||
/*
|
||||
* splinter -- drive a program that wants a terminal, through tmux.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Some programs cannot be run with `run`: a REPL, an installer that asks
|
||||
* questions, another agent's TUI. They need a terminal. tmux gives them one,
|
||||
* detached, and gives splinter two things back: what is on the pane
|
||||
* (capture-pane) and a way to type into it (send-keys).
|
||||
*
|
||||
* The tools:
|
||||
*
|
||||
* tmux_start cmd, name? start cmd in a detached session; it is the target
|
||||
* tmux_send text? keys? type text and Enter, and/or named keys (C-c, Up)
|
||||
* tmux_ask text, wait_ms? send, then wait until the pane has new output and
|
||||
* quiet_ms? has been quiet for quiet_ms; return only the new lines
|
||||
* tmux_read wait_ms? the lines that are new since the last read
|
||||
* tmux_capture lines? the pane as it is, newest lines
|
||||
* tmux_status the target, and whether it is alive
|
||||
*
|
||||
* "New" is a diff of two captures, kept in memory: there is no helper process,
|
||||
* no pid file and nothing left behind when splinter exits. A pane is a screen,
|
||||
* not a stream, so the diff finds where the old capture ends inside the new one
|
||||
* (output scrolls up) and returns what follows; a program that repaints the
|
||||
* whole screen gives the lines that changed at the bottom, or, when the old
|
||||
* capture cannot be found at all, the last SHOWN_MAX lines.
|
||||
*
|
||||
* Starting a session runs a shell command, so tmux_start is destructive, and
|
||||
* typing into a terminal is whatever that terminal does: tmux_send and
|
||||
* tmux_ask are mutating.
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "mcp.h"
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
#define NAME_MAX_LEN 64
|
||||
#define HISTORY 500 /* lines of scrollback looked at */
|
||||
#define SHOWN_MAX 200 /* lines handed to the model at once */
|
||||
#define POLL_MS 200
|
||||
#define WAIT_DEFAULT 15000
|
||||
#define WAIT_CAP 120000
|
||||
#define QUIET_DEFAULT 1200
|
||||
|
||||
static struct sp_host *host_ref;
|
||||
static char target[NAME_MAX_LEN * 2];
|
||||
static char *last; /* the previous capture */
|
||||
|
||||
/* ---------------------------------------------------------------- tmux */
|
||||
|
||||
/*
|
||||
* Run argv, collect stdout and stderr. The child does nothing between fork and
|
||||
* exec but dup2 and close, which is all a forked child of a threaded process may
|
||||
* safely do.
|
||||
*/
|
||||
static int
|
||||
run(char *const argv[], struct sp_buf *out)
|
||||
{
|
||||
int fd[2], st = 0;
|
||||
char buf[4096];
|
||||
ssize_t n;
|
||||
pid_t pid;
|
||||
|
||||
if (pipe(fd) != 0)
|
||||
return -1;
|
||||
if ((pid = fork()) < 0) {
|
||||
close(fd[0]);
|
||||
close(fd[1]);
|
||||
return -1;
|
||||
}
|
||||
if (pid == 0) {
|
||||
dup2(fd[1], 1);
|
||||
dup2(fd[1], 2);
|
||||
close(fd[0]);
|
||||
close(fd[1]);
|
||||
execvp(argv[0], argv);
|
||||
_exit(127);
|
||||
}
|
||||
close(fd[1]);
|
||||
while ((n = read(fd[0], buf, sizeof(buf))) > 0 ||
|
||||
(n < 0 && errno == EINTR))
|
||||
if (n > 0 && out != NULL)
|
||||
sp_buf_add(out, buf, (size_t)n);
|
||||
close(fd[0]);
|
||||
while (waitpid(pid, &st, 0) < 0 && errno == EINTR)
|
||||
;
|
||||
return WIFEXITED(st) ? WEXITSTATUS(st) : -1;
|
||||
}
|
||||
|
||||
static int
|
||||
have_tmux(void)
|
||||
{
|
||||
char *const argv[] = { "tmux", "-V", NULL };
|
||||
|
||||
return run(argv, NULL) == 0;
|
||||
}
|
||||
|
||||
/* A name that cannot be mistaken for an option or a second target. */
|
||||
static int
|
||||
safe_name(const char *s, size_t max)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (s == NULL || s[0] == '\0' || s[0] == '-' || strlen(s) >= max)
|
||||
return 0;
|
||||
for (i = 0; s[i] != '\0'; i++)
|
||||
if (!isalnum((unsigned char)s[i]) && strchr("_.-:%@", s[i]) == NULL)
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int
|
||||
alive(void)
|
||||
{
|
||||
char *const argv[] = { "tmux", "has-session", "-t", target, NULL };
|
||||
|
||||
return target[0] != '\0' && run(argv, NULL) == 0;
|
||||
}
|
||||
|
||||
static void
|
||||
target_file(char *path, size_t len)
|
||||
{
|
||||
const char *dir = sp_host_session_dir(host_ref);
|
||||
|
||||
if (dir != NULL && dir[0] != '\0')
|
||||
snprintf(path, len, "%s/tmux_target", dir);
|
||||
else
|
||||
path[0] = '\0';
|
||||
}
|
||||
|
||||
static void
|
||||
set_target(const char *name)
|
||||
{
|
||||
char path[600];
|
||||
FILE *f;
|
||||
|
||||
snprintf(target, sizeof(target), "%s", name);
|
||||
free(last);
|
||||
last = NULL;
|
||||
target_file(path, sizeof(path));
|
||||
if (path[0] != '\0' && (f = fopen(path, "w")) != NULL) {
|
||||
fprintf(f, "%s\n", target);
|
||||
fclose(f);
|
||||
}
|
||||
}
|
||||
|
||||
/* A resumed session finds its terminal again. */
|
||||
static void
|
||||
restore_target(void)
|
||||
{
|
||||
char path[600];
|
||||
FILE *f;
|
||||
|
||||
target_file(path, sizeof(path));
|
||||
if (path[0] == '\0' || (f = fopen(path, "r")) == NULL)
|
||||
return;
|
||||
if (fgets(target, sizeof(target), f) != NULL)
|
||||
target[strcspn(target, "\n")] = '\0';
|
||||
fclose(f);
|
||||
if (!safe_name(target, sizeof(target)))
|
||||
target[0] = '\0';
|
||||
}
|
||||
|
||||
static long
|
||||
now_ms(void)
|
||||
{
|
||||
struct timespec ts;
|
||||
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
|
||||
}
|
||||
|
||||
static void
|
||||
pause_ms(long ms)
|
||||
{
|
||||
struct timespec ts;
|
||||
|
||||
ts.tv_sec = ms / 1000;
|
||||
ts.tv_nsec = (ms % 1000) * 1000000L;
|
||||
nanosleep(&ts, NULL);
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------- capture and diff */
|
||||
|
||||
/*
|
||||
* The pane with its history, joined lines, without the empty rows tmux pads
|
||||
* a screen with. NULL when there is no pane.
|
||||
*/
|
||||
static char *
|
||||
capture(int lines)
|
||||
{
|
||||
struct sp_buf b;
|
||||
char from[32];
|
||||
char *const argv[] = { "tmux", "capture-pane", "-p", "-J", "-t",
|
||||
target, "-S", from, NULL };
|
||||
char *s;
|
||||
size_t n;
|
||||
|
||||
snprintf(from, sizeof(from), "-%d", lines);
|
||||
if (sp_buf_init(&b) != 0)
|
||||
return NULL;
|
||||
if (run(argv, &b) != 0) {
|
||||
sp_buf_free(&b);
|
||||
return NULL;
|
||||
}
|
||||
n = b.len;
|
||||
while (n > 0 && (b.p[n - 1] == '\n' || b.p[n - 1] == ' '))
|
||||
n--;
|
||||
s = malloc(n + 1);
|
||||
if (s != NULL) {
|
||||
memcpy(s, b.p, n);
|
||||
s[n] = '\0';
|
||||
}
|
||||
sp_buf_free(&b);
|
||||
return s;
|
||||
}
|
||||
|
||||
/* Split in place; v gets the start of every line. */
|
||||
static size_t
|
||||
split(char *text, char ***v)
|
||||
{
|
||||
size_t n = 0, cap = 0;
|
||||
char *p = text;
|
||||
|
||||
*v = NULL;
|
||||
for (;;) {
|
||||
char *nl;
|
||||
|
||||
if (n == cap) {
|
||||
char **nv = realloc(*v, (cap ? cap * 2 : 64) * sizeof(**v));
|
||||
|
||||
if (nv == NULL) {
|
||||
free(*v);
|
||||
*v = NULL;
|
||||
return 0;
|
||||
}
|
||||
*v = nv;
|
||||
cap = cap ? cap * 2 : 64;
|
||||
}
|
||||
(*v)[n++] = p;
|
||||
if ((nl = strchr(p, '\n')) == NULL)
|
||||
break;
|
||||
*nl = '\0';
|
||||
p = nl + 1;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/* Does b[0..k) equal a[from..from+k)? */
|
||||
static int
|
||||
same_run(char **a, size_t from, char **b, size_t k)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < k; i++)
|
||||
if (strcmp(a[from + i], b[i]) != 0)
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* Where in `neu` do the lines that are new begin? The old capture is found as a
|
||||
* run at the start of the new one (nothing scrolled), or as a tail of the old one
|
||||
* at the start of the new one (output pushed the top off). The old last line is
|
||||
* tried last and dropped, because it is the prompt or the line being edited and is
|
||||
* the one most likely to differ. Returns the index of the first new line, or 0
|
||||
* when nothing of the old capture can be found.
|
||||
*/
|
||||
static size_t
|
||||
first_new(char **old, size_t no, char **neu, size_t nn)
|
||||
{
|
||||
size_t trim, s;
|
||||
|
||||
for (trim = 0; trim <= 1 && trim < no; trim++) {
|
||||
size_t have = no - trim;
|
||||
|
||||
for (s = 0; s < have; s++) {
|
||||
size_t k = have - s;
|
||||
|
||||
if (k <= nn && same_run(old, s, neu, k))
|
||||
return k;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* The lines of `now` that `before` did not have. */
|
||||
static void
|
||||
delta(const char *before, const char *now, struct sp_buf *out)
|
||||
{
|
||||
char *a = NULL, *b = NULL, **av = NULL, **bv = NULL;
|
||||
size_t na = 0, nb, from, i;
|
||||
|
||||
if ((b = strdup(now)) == NULL)
|
||||
return;
|
||||
nb = split(b, &bv);
|
||||
if (before != NULL && before[0] != '\0') {
|
||||
a = strdup(before);
|
||||
if (a != NULL)
|
||||
na = split(a, &av);
|
||||
}
|
||||
from = (na > 0 && bv != NULL) ? first_new(av, na, bv, nb) : 0;
|
||||
if (bv != NULL && nb - from > SHOWN_MAX) {
|
||||
sp_buf_printf(out, "[%zu earlier lines omitted]\n",
|
||||
nb - from - SHOWN_MAX);
|
||||
from = nb - SHOWN_MAX;
|
||||
}
|
||||
for (i = from; bv != NULL && i < nb; i++)
|
||||
sp_buf_printf(out, "%s\n", bv[i]);
|
||||
free(av);
|
||||
free(bv);
|
||||
free(a);
|
||||
free(b);
|
||||
}
|
||||
|
||||
/* Capture, report what is new since the last capture, remember this one. */
|
||||
static int
|
||||
report_new(struct sp_buf *out)
|
||||
{
|
||||
char *now = capture(HISTORY);
|
||||
struct sp_buf d;
|
||||
|
||||
if (now == NULL)
|
||||
return sp_buf_puts(out, "error: the tmux pane is gone\n");
|
||||
if (sp_buf_init(&d) != 0) {
|
||||
free(now);
|
||||
return -1;
|
||||
}
|
||||
delta(last, now, &d);
|
||||
free(last);
|
||||
last = now;
|
||||
if (d.len == 0)
|
||||
sp_buf_puts(out, "(no new output)\n");
|
||||
else
|
||||
sp_buf_add(out, d.p, d.len);
|
||||
sp_buf_free(&d);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Wait until the pane differs from `base`, then until it has stayed the same for
|
||||
* quiet_ms, or until wait_ms is over. Returns 1 when something changed.
|
||||
*/
|
||||
static int
|
||||
settle(const char *base, long wait_ms, long quiet_ms)
|
||||
{
|
||||
long start = now_ms(), changed_at = 0;
|
||||
char *prev = base != NULL ? strdup(base) : strdup("");
|
||||
int changed = 0;
|
||||
|
||||
while (prev != NULL && now_ms() - start < wait_ms) {
|
||||
char *cur;
|
||||
|
||||
pause_ms(POLL_MS);
|
||||
if ((cur = capture(HISTORY)) == NULL)
|
||||
break;
|
||||
if (strcmp(cur, prev) != 0) {
|
||||
changed = 1;
|
||||
changed_at = now_ms();
|
||||
free(prev);
|
||||
prev = cur;
|
||||
continue;
|
||||
}
|
||||
free(cur);
|
||||
if (changed && now_ms() - changed_at >= quiet_ms)
|
||||
break;
|
||||
}
|
||||
free(prev);
|
||||
return changed;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ operations */
|
||||
|
||||
static int
|
||||
need_target(struct sp_buf *out)
|
||||
{
|
||||
if (target[0] == '\0')
|
||||
return !sp_buf_puts(out, "error: no tmux target; use tmux_start "
|
||||
"or /tmux attach\n");
|
||||
if (!alive())
|
||||
return !sp_buf_printf(out, "error: tmux session '%s' is gone\n",
|
||||
target);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int
|
||||
op_start(const char *cmd, const char *name, struct sp_buf *out)
|
||||
{
|
||||
char auto_name[NAME_MAX_LEN];
|
||||
char *const argv[] = { "tmux", "new-session", "-d", "-x", "200", "-y",
|
||||
"50", "-s", auto_name, "sh", "-c", (char *)cmd, NULL };
|
||||
struct sp_buf o;
|
||||
int rc;
|
||||
|
||||
if (cmd == NULL || cmd[0] == '\0')
|
||||
return sp_buf_puts(out, "error: cmd required\n");
|
||||
if (name == NULL || name[0] == '\0')
|
||||
snprintf(auto_name, sizeof(auto_name), "splinter-%d",
|
||||
(int)getpid());
|
||||
else if (!safe_name(name, sizeof(auto_name)) || strchr(name, ':') != NULL)
|
||||
return sp_buf_puts(out, "error: name may use letters, digits "
|
||||
"and _ . - only\n");
|
||||
else
|
||||
snprintf(auto_name, sizeof(auto_name), "%s", name);
|
||||
if (sp_buf_init(&o) != 0)
|
||||
return -1;
|
||||
snprintf(target, sizeof(target), "%s", auto_name);
|
||||
if (alive()) {
|
||||
set_target(auto_name);
|
||||
sp_buf_free(&o);
|
||||
return sp_buf_printf(out, "session %s exists, attached\n",
|
||||
auto_name);
|
||||
}
|
||||
rc = run(argv, &o);
|
||||
if (rc != 0) {
|
||||
target[0] = '\0';
|
||||
sp_buf_printf(out, "error: tmux new-session failed (%d): %s",
|
||||
rc, o.p != NULL ? o.p : "\n");
|
||||
sp_buf_free(&o);
|
||||
return 0;
|
||||
}
|
||||
sp_buf_free(&o);
|
||||
set_target(auto_name);
|
||||
free(last);
|
||||
last = capture(HISTORY);
|
||||
return sp_buf_printf(out, "target is %s (cmd: %s)\n", target, cmd);
|
||||
}
|
||||
|
||||
/* Named keys only: letters, digits and - + _, so none can be an option. */
|
||||
static int
|
||||
safe_keys(const char *keys)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; keys[i] != '\0'; i++)
|
||||
if (!isalnum((unsigned char)keys[i]) && keys[i] != ' ' &&
|
||||
keys[i] != '-' && keys[i] != '_' && keys[i] != '+')
|
||||
return 0;
|
||||
return keys[0] != '-';
|
||||
}
|
||||
|
||||
static int
|
||||
send_text(const char *text, int enter, struct sp_buf *out)
|
||||
{
|
||||
char *const lit[] = { "tmux", "send-keys", "-t", target, "-l", "--",
|
||||
(char *)text, NULL };
|
||||
char *const ret[] = { "tmux", "send-keys", "-t", target, "Enter", NULL };
|
||||
|
||||
if (text[0] != '\0' && run(lit, out) != 0)
|
||||
return -1;
|
||||
return enter ? run(ret, out) : 0;
|
||||
}
|
||||
|
||||
static int
|
||||
send_keys(const char *keys, struct sp_buf *out)
|
||||
{
|
||||
char *copy = strdup(keys), *argv[40], *save = NULL, *tok;
|
||||
int n = 0, rc;
|
||||
|
||||
if (copy == NULL)
|
||||
return -1;
|
||||
argv[n++] = "tmux";
|
||||
argv[n++] = "send-keys";
|
||||
argv[n++] = "-t";
|
||||
argv[n++] = target;
|
||||
for (tok = strtok_r(copy, " ", &save); tok != NULL && n < 38;
|
||||
tok = strtok_r(NULL, " ", &save))
|
||||
argv[n++] = tok;
|
||||
argv[n] = NULL;
|
||||
rc = n > 4 ? run(argv, out) : 0;
|
||||
free(copy);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int
|
||||
op_send(const char *text, const char *keys, int enter, struct sp_buf *out)
|
||||
{
|
||||
if (!need_target(out))
|
||||
return 0;
|
||||
if ((text == NULL || text[0] == '\0') && (keys == NULL || keys[0] == '\0'))
|
||||
return sp_buf_puts(out, "error: text or keys required\n");
|
||||
if (keys != NULL && !safe_keys(keys))
|
||||
return sp_buf_puts(out, "error: keys are names such as C-c, "
|
||||
"Up, Escape\n");
|
||||
if (text != NULL && text[0] != '\0' &&
|
||||
send_text(text, keys == NULL || keys[0] == '\0' ? enter : 0, out) != 0)
|
||||
return sp_buf_puts(out, "error: tmux send-keys failed\n");
|
||||
if (keys != NULL && keys[0] != '\0' && send_keys(keys, out) != 0)
|
||||
return sp_buf_puts(out, "error: tmux send-keys failed\n");
|
||||
return sp_buf_puts(out, "sent\n");
|
||||
}
|
||||
|
||||
static int
|
||||
op_ask(const char *text, long wait_ms, long quiet_ms, struct sp_buf *out)
|
||||
{
|
||||
char *before;
|
||||
|
||||
if (!need_target(out))
|
||||
return 0;
|
||||
if (text == NULL || text[0] == '\0')
|
||||
return sp_buf_puts(out, "error: text required\n");
|
||||
if ((before = capture(HISTORY)) == NULL)
|
||||
return sp_buf_puts(out, "error: the tmux pane is gone\n");
|
||||
free(last);
|
||||
last = before;
|
||||
if (send_text(text, 1, out) != 0)
|
||||
return sp_buf_puts(out, "error: tmux send-keys failed\n");
|
||||
if (!settle(before, wait_ms, quiet_ms))
|
||||
sp_buf_puts(out, "(timeout: the pane did not change; it may be "
|
||||
"busy or waiting; try tmux_read or tmux_capture)\n");
|
||||
return report_new(out);
|
||||
}
|
||||
|
||||
static int
|
||||
op_read(long wait_ms, long quiet_ms, struct sp_buf *out)
|
||||
{
|
||||
if (!need_target(out))
|
||||
return 0;
|
||||
if (wait_ms > 0 && last != NULL)
|
||||
(void)settle(last, wait_ms, quiet_ms);
|
||||
return report_new(out);
|
||||
}
|
||||
|
||||
static int
|
||||
op_capture(int lines, struct sp_buf *out)
|
||||
{
|
||||
char *s;
|
||||
|
||||
if (!need_target(out))
|
||||
return 0;
|
||||
if ((s = capture(lines)) == NULL)
|
||||
return sp_buf_puts(out, "error: the tmux pane is gone\n");
|
||||
sp_buf_printf(out, "[pane %s, last %d lines]\n%s\n", target, lines, s);
|
||||
free(s);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
op_status(struct sp_buf *out)
|
||||
{
|
||||
return sp_buf_printf(out, "tmux target: %s%s\n",
|
||||
target[0] != '\0' ? target : "(none)",
|
||||
target[0] == '\0' ? "" : alive() ? " (alive)" : " (gone)");
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- tools */
|
||||
|
||||
static long
|
||||
clamp(long v, long lo, long hi, long dflt)
|
||||
{
|
||||
if (v == -1)
|
||||
return dflt;
|
||||
return v < lo ? lo : v > hi ? hi : v;
|
||||
}
|
||||
|
||||
static mcp_json *
|
||||
parse(const char *args)
|
||||
{
|
||||
return mcp_parse(args != NULL ? args : "{}");
|
||||
}
|
||||
|
||||
#define WITH_ARGS(a, out) \
|
||||
if (((a) = parse(args)) == NULL) \
|
||||
return sp_buf_puts((out), "error: arguments are not JSON\n")
|
||||
|
||||
static int
|
||||
tool_start(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
mcp_json *a;
|
||||
int rc;
|
||||
|
||||
(void)ctx;
|
||||
WITH_ARGS(a, out);
|
||||
rc = op_start(mcp_arg_string(a, "cmd"), mcp_arg_string(a, "name"), out);
|
||||
mcp_json_free(a);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_send(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
mcp_json *a;
|
||||
int rc;
|
||||
|
||||
(void)ctx;
|
||||
WITH_ARGS(a, out);
|
||||
rc = op_send(mcp_arg_string(a, "text"), mcp_arg_string(a, "keys"),
|
||||
mcp_arg_bool(a, "enter", 1), out);
|
||||
mcp_json_free(a);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_ask(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
mcp_json *a;
|
||||
int rc;
|
||||
|
||||
(void)ctx;
|
||||
WITH_ARGS(a, out);
|
||||
rc = op_ask(mcp_arg_string(a, "text"),
|
||||
clamp(mcp_arg_int(a, "wait_ms", -1), 1000, WAIT_CAP, WAIT_DEFAULT),
|
||||
clamp(mcp_arg_int(a, "quiet_ms", -1), 200, 30000, QUIET_DEFAULT),
|
||||
out);
|
||||
mcp_json_free(a);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_read(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
mcp_json *a;
|
||||
int rc;
|
||||
|
||||
(void)ctx;
|
||||
WITH_ARGS(a, out);
|
||||
rc = op_read(clamp(mcp_arg_int(a, "wait_ms", -1), 0, WAIT_CAP, 0),
|
||||
QUIET_DEFAULT, out);
|
||||
mcp_json_free(a);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_capture(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
mcp_json *a;
|
||||
int rc;
|
||||
|
||||
(void)ctx;
|
||||
WITH_ARGS(a, out);
|
||||
rc = op_capture((int)clamp(mcp_arg_int(a, "lines", -1), 1, 5000, 200),
|
||||
out);
|
||||
mcp_json_free(a);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_status(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
(void)args;
|
||||
(void)ctx;
|
||||
return op_status(out);
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- command */
|
||||
|
||||
static const char *
|
||||
skip(const char *s)
|
||||
{
|
||||
while (*s == ' ')
|
||||
s++;
|
||||
return s;
|
||||
}
|
||||
|
||||
static int
|
||||
word(const char *args, const char *name, const char **rest)
|
||||
{
|
||||
size_t n = strlen(name);
|
||||
|
||||
if (strncmp(args, name, n) != 0 || (args[n] != '\0' && args[n] != ' '))
|
||||
return 0;
|
||||
*rest = skip(args + n);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int
|
||||
command(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
const char *r;
|
||||
|
||||
(void)ctx;
|
||||
host_ref = h;
|
||||
if (args == NULL || args[0] == '\0' || word(args, "status", &r))
|
||||
return op_status(out);
|
||||
if (word(args, "start", &r))
|
||||
return op_start(r, NULL, out);
|
||||
if (word(args, "attach", &r)) {
|
||||
if (!safe_name(r, sizeof(target)))
|
||||
return sp_buf_puts(out, "error: not a tmux target name\n");
|
||||
set_target(r);
|
||||
return op_status(out);
|
||||
}
|
||||
if (word(args, "send", &r))
|
||||
return op_send(r, NULL, 1, out);
|
||||
if (word(args, "keys", &r))
|
||||
return op_send(NULL, r, 0, out);
|
||||
if (word(args, "ask", &r))
|
||||
return op_ask(r, WAIT_DEFAULT, QUIET_DEFAULT, out);
|
||||
if (word(args, "read", &r))
|
||||
return op_read(clamp(*r != '\0' ? atol(r) : -1, 0, WAIT_CAP, 0),
|
||||
QUIET_DEFAULT, out);
|
||||
if (word(args, "capture", &r))
|
||||
return op_capture((int)clamp(*r != '\0' ? atol(r) : -1, 1, 5000,
|
||||
200), out);
|
||||
if (word(args, "stop", &r)) {
|
||||
char *const argv[] = { "tmux", "kill-session", "-t", target, NULL };
|
||||
|
||||
if (target[0] == '\0')
|
||||
return sp_buf_puts(out, "no target\n");
|
||||
(void)run(argv, NULL);
|
||||
sp_buf_printf(out, "killed %s\n", target);
|
||||
target[0] = '\0';
|
||||
free(last);
|
||||
last = NULL;
|
||||
return 0;
|
||||
}
|
||||
return sp_buf_puts(out, "usage: /tmux start <cmd> | attach <target> | "
|
||||
"send <text> | keys <names> | ask <text> | read [wait_ms] | "
|
||||
"capture [lines] | status | stop\n");
|
||||
}
|
||||
|
||||
static int
|
||||
tick(struct sp_host *h, const char *name, void *ctx)
|
||||
{
|
||||
char b[160];
|
||||
|
||||
(void)name;
|
||||
(void)ctx;
|
||||
host_ref = h;
|
||||
snprintf(b, sizeof(b), "%.100s", target);
|
||||
sp_host_widget_text(h, "tmux", b);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const struct sp_tool t_start = {
|
||||
"tmux_start",
|
||||
"Start a shell command in a detached tmux terminal and make it the "
|
||||
"target. For programs that need a terminal: REPLs, installers, TUIs. "
|
||||
"Use run for anything that just prints and exits.",
|
||||
"{\"type\":\"object\",\"properties\":{\"cmd\":{\"type\":\"string\"},"
|
||||
"\"name\":{\"type\":\"string\",\"description\":\"session name, "
|
||||
"letters digits _ . -\"}},\"required\":[\"cmd\"]}",
|
||||
SP_AUTH_DESTRUCTIVE, tool_start, NULL
|
||||
};
|
||||
|
||||
static const struct sp_tool t_send = {
|
||||
"tmux_send",
|
||||
"Type into the target terminal. text is typed literally and followed by "
|
||||
"Enter (enter=false to leave it off); keys are tmux key names such as "
|
||||
"C-c, Escape, Up, separated by spaces.",
|
||||
"{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"},"
|
||||
"\"keys\":{\"type\":\"string\"},\"enter\":{\"type\":\"boolean\"}}}",
|
||||
SP_AUTH_MUTATE, tool_send, NULL
|
||||
};
|
||||
|
||||
static const struct sp_tool t_ask = {
|
||||
"tmux_ask",
|
||||
"Type a line into the target terminal, wait until it has new output and "
|
||||
"has been quiet for quiet_ms, and return the new lines. Gives up after "
|
||||
"wait_ms (default 15000) and says so.",
|
||||
"{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"},"
|
||||
"\"wait_ms\":{\"type\":\"integer\"},\"quiet_ms\":{\"type\":\"integer\"}},"
|
||||
"\"required\":[\"text\"]}",
|
||||
SP_AUTH_MUTATE, tool_ask, NULL
|
||||
};
|
||||
|
||||
static const struct sp_tool t_read = {
|
||||
"tmux_read",
|
||||
"The lines on the target terminal that are new since the last "
|
||||
"tmux_ask or tmux_read. wait_ms waits for something to appear first.",
|
||||
"{\"type\":\"object\",\"properties\":{\"wait_ms\":{\"type\":\"integer\"}}}",
|
||||
SP_AUTH_READ, tool_read, NULL
|
||||
};
|
||||
|
||||
static const struct sp_tool t_capture = {
|
||||
"tmux_capture",
|
||||
"The target terminal as it is now: the last `lines` lines (default 200).",
|
||||
"{\"type\":\"object\",\"properties\":{\"lines\":{\"type\":\"integer\"}}}",
|
||||
SP_AUTH_READ, tool_capture, NULL
|
||||
};
|
||||
|
||||
static const struct sp_tool t_status = {
|
||||
"tmux_status",
|
||||
"The current tmux target and whether its session is alive.",
|
||||
"{\"type\":\"object\",\"properties\":{}}",
|
||||
SP_AUTH_READ, tool_status, NULL
|
||||
};
|
||||
|
||||
static const struct sp_widget tmux_widget = { "tmux", tick, NULL, NULL, 5000 };
|
||||
|
||||
static int
|
||||
init(struct sp_host *h)
|
||||
{
|
||||
if (!have_tmux())
|
||||
return -1; /* no tmux: the plugin does not load */
|
||||
host_ref = h;
|
||||
restore_target();
|
||||
sp_host_add_tool(h, &t_start);
|
||||
sp_host_add_tool(h, &t_send);
|
||||
sp_host_add_tool(h, &t_ask);
|
||||
sp_host_add_tool(h, &t_read);
|
||||
sp_host_add_tool(h, &t_capture);
|
||||
sp_host_add_tool(h, &t_status);
|
||||
sp_host_add_command(h, "tmux", command, NULL);
|
||||
sp_host_add_widget(h, &tmux_widget);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void
|
||||
shutdown_plugin(struct sp_host *h)
|
||||
{
|
||||
(void)h;
|
||||
free(last);
|
||||
last = NULL;
|
||||
}
|
||||
|
||||
static const struct sp_plugin plugin = {
|
||||
SP_PLUGIN_ABI, "tmux", "0.3", init, NULL, shutdown_plugin
|
||||
};
|
||||
|
||||
const struct sp_plugin *
|
||||
sp_plugin_describe(void)
|
||||
{
|
||||
return &plugin;
|
||||
}
|
||||
+133
-43
@@ -5,15 +5,45 @@
|
||||
# selbst - nie als leere Zeile.
|
||||
|
||||
ui.ready = bereit. Enter sendet, Ctrl-D beendet.
|
||||
ui.more_lines = ... %zu Zeilen mehr
|
||||
ui.working = laeuft...
|
||||
ui.steering_queued = Steuerung eingereiht
|
||||
ui.command_running = Kommando laeuft...
|
||||
ui.reconnected = wieder verbunden
|
||||
ui.reconnecting = Verbindung weg - verbinde neu ...
|
||||
ui.no_sessions = noch keine Sitzungen
|
||||
ui.untitled = (ohne Titel)
|
||||
ui.session_opened = Sitzung geoeffnet
|
||||
|
||||
# /sessions: the two-stage picker (source, then session)
|
||||
ui.sessions_title_source = Sitzungen: Quelle
|
||||
ui.sessions_title_session = Sitzungen
|
||||
ui.sessions_no_source = keine Quelle hat Sitzungen
|
||||
ui.sessions_hint_source = Enter oeffnet eine Quelle Esc bricht ab
|
||||
ui.sessions_hint_session = Enter oeffnet die Sitzung Esc zurueck
|
||||
ui.session_gone = Sitzung %s ist weg - jetzt auf %s
|
||||
ui.compacted = Kontext kompaktiert: %zu->%zu Nachrichten, %s->%s (%s->%s)
|
||||
ui.compact_nohost = compact: kein Plugin-Host, nichts zu kompaktieren
|
||||
ui.compact_pending = Kompaktierung eingereiht: laeuft am Ende des Turns (Ziel %zu Tokens)
|
||||
ui.steer_queued_line = Steuerung eingereiht: %s
|
||||
ui.badtool_note = kaputter Tool-Call, neuer Versuch in %d s (%d/%d)
|
||||
agent.badcall_answer = Ich konnte keinen ausfuehrbaren Tool-Call senden: die Argumente waren kein gueltiges JSON. Nichts lief. Der rohe Aufruf steht im Log; sag mir, wie es weitergehen soll.
|
||||
ui.steer_failed = Steuerung nicht angenommen (kein Turn laeuft)
|
||||
ui.model_title = Modell
|
||||
ui.open_busy = Sitzungswechsel geht nicht waehrend ein Turn laeuft; /open danach
|
||||
ui.attach_busy = ein anderer Client haengt schon dran: eine Unterhaltung fuehrt einen Turn zur Zeit - die andere Verbindung schliessen, oder sie benutzen
|
||||
ui.command_busy = nicht waehrend ein Turn laeuft; danach noch einmal
|
||||
ui.model_filter = filter:
|
||||
ui.model_hint = tippen filtert Pfeile bewegen Enter waehlt Esc bricht ab
|
||||
ui.status_turn = %lds
|
||||
ui.model_empty = keine Modelle konfiguriert
|
||||
ui.model_probing = frage den Endpoint, was er anbietet ...
|
||||
ui.model_none = kein Treffer
|
||||
|
||||
sidebar.session = Sitzung
|
||||
sidebar.cwd = Verzeichnis
|
||||
sidebar.last_turn = letzter Turn
|
||||
sidebar.tokens = %zu Tok (ein %zu)
|
||||
|
||||
status.title = splinter %s
|
||||
|
||||
role.you = du
|
||||
role.agent = modell
|
||||
role.thinking = denkt
|
||||
@@ -23,19 +53,30 @@ role.error = fehler
|
||||
|
||||
cmd.unknown = unbekanntes Kommando: /%s
|
||||
cmd.available = verfuegbar:
|
||||
widgets.none = kein Plugin hat eine Widget-Zeile veröffentlicht
|
||||
|
||||
err.oom = kein Speicher
|
||||
err.theme = Farbschema
|
||||
err.session = Sitzung
|
||||
err.plugin_failed = Plugin fehlgeschlagen
|
||||
|
||||
role.tool = werkzeug
|
||||
role.observation = ausgabe
|
||||
err.thread = Turn-Thread laesst sich nicht starten
|
||||
err.turn_failed = Turn fehlgeschlagen
|
||||
focus.reminder = Pruefe vor der Antwort, ob der letzte Schritt naeher am Ziel war; wenn nicht, sage das und nenne den naechsten Schritt. Ziel: %s
|
||||
focus.goal_prompt = Ziel: %s. Arbeite darauf hin. Wenn das Ziel vollstaendig erreicht ist, beende deine letzte Antwort mit der einen Zeile GOAL_COMPLETE, damit splinter es als succeeded markieren kann.
|
||||
focus.reminder = Recap zum Merken: %s. Pruefe vor der Antwort, ob der letzte Schritt naeher am Ziel war; wenn nicht, sage das und nenne den naechsten Schritt. Wenn das Ziel vollstaendig erreicht ist, beende deine letzte Antwort mit der einen Zeile GOAL_COMPLETE.
|
||||
focus.recap_prompt = Ziel: %s. Schreibe einen kurzen Recap zum Merken: 3-5 Punkte, was am Ende stimmen muss, die ersten konkreten Schritte und offene Fragen. Wenn das Ziel vollstaendig erreicht ist, beende deine letzte Antwort mit der einen Zeile GOAL_COMPLETE.
|
||||
focus.continue_prompt = Arbeite an diesem Ziel weiter: %s. Mach dort weiter, wo die Sitzung aufgehoert hat: pruefe den Stand, tue den naechsten konkreten Schritt und berichte, was sich geaendert hat. Wenn das Ziel vollstaendig erreicht ist, beende deine letzte Antwort mit der einen Zeile GOAL_COMPLETE.
|
||||
selfcheck.prompt = In dieser Sitzung ist etwas schiefgelaufen. Pruefe dich selbst, statt den Operator zu fragen: lies den Schluss unseres Gespraechs unten (Werkzeugausgaben sind gekuerzt), finde den Schritt, der fehlgeschlagen ist, nenne die Ursache, was du falsch gemacht hast und was du jetzt anders machst. Arbeite danach die Aufgabe dort weiter, wo sie stehen geblieben ist. Wiederhole keine Arbeit, die noch gueltig ist.
|
||||
selfcheck.empty = (noch keine Turns - es gibt nichts zu pruefen, also fang die Aufgabe an.)
|
||||
focus.set = Ziel gesetzt: %s
|
||||
focus.none = kein Ziel gesetzt (/goal <text>)
|
||||
focus.status = Ziel: %s (%u Erinnerungen, alle %u Turns)
|
||||
focus.status = Ziel: %s (%u Recaps, alle %u Turns)
|
||||
focus.status_done = Ziel: %s [succeeded] (%u Recaps, alle %u Turns)
|
||||
focus.widget_recap = Recap %u, alle %u Turns
|
||||
focus.note_goal = Ziel im Prompt
|
||||
focus.note_recap = Recap angewandt (Turn %u, alle %u Turns)
|
||||
focus.succeeded = Ziel erreicht: %s
|
||||
cps.idle = Leerlauf (angewandt %lu, vorbereitet %lu)
|
||||
cps.plan = Plan bereit: schnitt %zu/%zu, %zu -> %zu B
|
||||
cli.no_output = cli: '%s' lieferte keine Ausgabe
|
||||
@@ -43,24 +84,20 @@ cli.timeout = cli: '%s' lief nach %s s in das Zeitlimit
|
||||
cli.failed = cli: '%s' scheiterte (exit %d): %.400s
|
||||
ui.prompt_mark = >
|
||||
ui.steer_mark = steuern>
|
||||
ui.retry_note = neuer Versuch in %d s: %s
|
||||
ui.swarm_locked = [Schwarm gesperrt]
|
||||
ui.approve = %s ausfuehren (%s) %.60s? y/N
|
||||
auth.mutate = aendert Dateien
|
||||
auth.destructive = zerstoerend
|
||||
ui.status_ctx_bar = ctx %zu/%zu %s %d%%
|
||||
ui.status_ctx = ctx %zu
|
||||
ui.status_cache = cache %d%%
|
||||
ui.status_cache_none = cache -
|
||||
ui.status_tps = %d tok/s
|
||||
ui.status_tps_none = - tok/s
|
||||
role.diff = aenderung
|
||||
|
||||
# Zustimmung (ack): Kanalnachrichten, Antworten des Gateways, Terminal
|
||||
ack.request = Zustimmung %d: %s %s
|
||||
ack.how = Antwort: ok %d / no %d
|
||||
ack.prompt = Zustimmung %d: %s %s (%ds) - 'splinter --ack %d yes' oder hier y/N:
|
||||
ack.pending = Zustimmung %d: %s %s (%ds)
|
||||
ack.approved_by = splinter: zugestimmt von %s
|
||||
ack.none = keine offenen Anfragen
|
||||
ack.granted = Zustimmung erteilt.
|
||||
ack.refused = Abgelehnt.
|
||||
ack.gone = Diese Anfrage gibt es nicht (mehr).
|
||||
ack.waiting = Ich warte noch auf eine Zustimmung: ok %d / no %d
|
||||
focus.recap = Erinnerung fuer den naechsten Turn eingeplant
|
||||
|
||||
# openai transport
|
||||
openai.oom = openai: kein Speicher
|
||||
@@ -73,6 +110,7 @@ openai.transfer_failed = openai: Uebertragung fehlgeschlagen fuer %s
|
||||
openai.unparseable = openai: Antwort nicht lesbar (kein Status)
|
||||
openai.stream_failed = openai: Stream fehlgeschlagen fuer %s: %.300s
|
||||
openai.no_sse = openai: Endpoint sendete keine SSE-Daten: %.300s
|
||||
openai.http_status = openai: HTTP %ld von %s: %.300s
|
||||
openai.stream_no_answer = openai: Stream endete ohne Antwort: %.300s
|
||||
|
||||
# delegate
|
||||
@@ -82,26 +120,16 @@ delegate.parallel_timeout = [parallel: Zeitueberschreitung, Rest wird beendet]
|
||||
# telegram menu and approval buttons
|
||||
tg.cmd.start = Begruessung und Befehle
|
||||
tg.cmd.help = Hilfe und Befehle
|
||||
tg.cmd.goal = Ziel setzen oder zeigen
|
||||
tg.cmd.recap = Ziel in die naechste Runde legen
|
||||
tg.cmd.goal = Ziel setzen oder zeigen, dann zusammenfassen
|
||||
tg.cmd.run = fuehrt /%s aus
|
||||
tg.cmd.tasks = Plandateien zeigen
|
||||
tg.help = Ich bin splinter. Schreib eine Nachricht fuer einen Turn. /goal setzt das Ziel, /recap legt es in die naechste Runde, /tasks zeigt den Plan. Aenderungen fragen hier mit Ja/Nein oder ok <id> / no <id>.
|
||||
ack.yes = Ja
|
||||
ack.no = Nein
|
||||
ack.how = Antwort: Knopf unten oder ok %d / no %d
|
||||
tg.cmd.status = Sitzung, Modell, Tokens, Limits
|
||||
tg.cmd.menu = Menue: Status, Modell, Neu, Hilfe
|
||||
tg.help = Ich bin splinter. Schreib eine Nachricht fuer einen Turn. /goal setzt das Ziel und startet einen Recap-Turn, /tasks zeigt den Plan. Aenderungen fragen hier mit Ja/Nein oder ok <id> / no <id>.
|
||||
|
||||
tg.cmd.interview = Profil im Chat anlegen
|
||||
tg.interview.start = Erstes Gespraech fuer '%s'. Ich stelle %zu Fragen; /skip ueberspringt eine, /cancel bricht ab.
|
||||
tg.interview.question = Frage %zu/%zu: %s
|
||||
tg.interview.how = Antworte einfach in den Chat.
|
||||
tg.interview.saved = Profil geschrieben: %s
|
||||
tg.interview.cancel = Interview abgebrochen.
|
||||
tg.interview.busy = Das Interview laeuft; antworte, /skip oder /cancel.
|
||||
|
||||
# interview questions (terminal and Telegram)
|
||||
interview.intro = Erstes Gespraech fuer '%s'. Enter ueberspringt eine Frage, Ctrl-D bricht ab.
|
||||
interview.header = _Geschrieben von `splinter --interview`. Von Hand aenderbar; splinter liest sie beim Start._
|
||||
interview.q.language = In welcher Sprache soll ich mit dir reden?
|
||||
interview.h.language = z.B. deutsch, english, portugues
|
||||
interview.q.about = Wer bist du und woran arbeitest du gerade?
|
||||
@@ -111,31 +139,40 @@ interview.h.stack = z.B. C99/POSIX, kein Python, Make statt CMake
|
||||
interview.q.style = Wie soll ich antworten?
|
||||
interview.h.style = kurz/lang, mit oder ohne Begruendung, Code zuerst?
|
||||
interview.q.never = Was soll ich NIE tun?
|
||||
interview.h.never = z.B. keine Commits ohne Auftrag, nichts in /tmp
|
||||
interview.h.never = z.B. nie nach /home/carol schreiben, keine Secrets in Logs
|
||||
interview.q.paths = Welche Pfade sind heilig oder gefaehrlich?
|
||||
interview.h.paths = z.B. /home/carol nie anfassen
|
||||
interview.skipped = (nicht beantwortet)
|
||||
interview.written = Geschrieben: %s
|
||||
interview.error.nodir = interview: kein Sitzungsverzeichnis
|
||||
interview.error.write = interview: kann %s nicht schreiben
|
||||
# /model und /connect (Gateway)
|
||||
session.new = Neue Konversation: %s
|
||||
session.failed = Konnte keine neue Sitzung anlegen: %s
|
||||
session.renamed = Sitzung %s heisst jetzt "%s"
|
||||
session.rename_failed = Konnte die Sitzung nicht umbenennen: %s
|
||||
session.rename_usage = Aufruf: /rename [ID] TITEL
|
||||
session.removed = Sitzung %s entfernt
|
||||
session.remove_failed = Konnte %s nicht entfernen: %s
|
||||
session.rm_current = Die offene Sitzung nicht entfernbar; vorher /open auf eine andere
|
||||
session.rm_usage = Aufruf: /rm ID
|
||||
session.no_session = Keine solche Sitzung: %s
|
||||
tg.cmd.new = neue Konversation
|
||||
|
||||
tg.cmd.model = ein Modell waehlen
|
||||
tg.cmd.connect = einen Provider hinzufuegen
|
||||
tg.menu.text = Menü
|
||||
tg.menu.status = Status
|
||||
tg.menu.model = Modell
|
||||
tg.menu.new = Neu
|
||||
tg.menu.help = Hilfe
|
||||
tg.menu.toast = ok
|
||||
model.choose = Waehle ein Modell. Die Liste kommt aus der Konfiguration; die Wahl gilt fuer diese Sitzung.
|
||||
model.none = Kein Modell konfiguriert. Mit /connect kommt eins dazu.
|
||||
model.unknown = Kein solches Modell: %s
|
||||
model.pool = Pool %s: %s (Anbieter %s, diese Sitzung).
|
||||
model.pools = Pools:
|
||||
model.pending = Modellwechsel auf %s nach der laufenden Anfrage
|
||||
ui.cancelling = breche ab ... (Ctrl-C nochmal beendet)
|
||||
model.failed = Umschalten fehlgeschlagen: %s
|
||||
model.switched = Modell: %s (Provider %s, diese Sitzung).
|
||||
model.no_key = " (kein %s gesetzt)"
|
||||
model.no_key = , kein %s gesetzt
|
||||
|
||||
model.saved = Modell: %s (Provider %s). Fuer den naechsten Start gespeichert.
|
||||
model.save_failed = Modell: %s (Provider %s). Nicht gespeichert: %s
|
||||
model.probe = Endpoints nach Modellen fragen
|
||||
model.probe_start = Frage %zu Provider nach ihren Modellen ...
|
||||
@@ -164,7 +201,6 @@ connect.test_failed = Der Test schlug fehl: %s (gespeichert ist er trotzdem)
|
||||
connect.use = Jetzt nutzen
|
||||
connect.later = Spaeter
|
||||
|
||||
|
||||
reply.empty = (leer)
|
||||
|
||||
# Agent-Profile, Kontingent, Seitenleiste (mit den Profilen dazugekommen)
|
||||
@@ -173,13 +209,14 @@ sidebar.usage = Kontingent
|
||||
sidebar.turn_line = %.1f s, %zu Schritte, %zu Tools
|
||||
widget.focus = Ziel
|
||||
widget.plan = Plan
|
||||
widget.sysinfo = System
|
||||
widget.tasks = Aufgaben
|
||||
widget.tmux = tmux
|
||||
ui.running = laeuft %lds%s |%s Enter = steuern, Strg-C = abbrechen
|
||||
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
|
||||
@@ -188,6 +225,59 @@ usage.calls = %lu Aufrufe
|
||||
usage.room = , Platz in %s
|
||||
usage.of_calls = (%lu/%lu Aufrufe)
|
||||
usage.of_tokens = (%lu/%lu Tokens)
|
||||
plan.widget = %d offen, %d aktiv, %d erledigt
|
||||
plan.widget_active = #%d aktiv - %d offen, %d aktiv, %d erledigt
|
||||
ui.thinking = denkt
|
||||
status.title = Status (%s)
|
||||
status.session = Sitzung
|
||||
status.dir = Verzeichnis
|
||||
status.model = Modell
|
||||
status.endpoint = Endpunkt
|
||||
status.theme = Thema
|
||||
status.agent = Agent
|
||||
status.last = zuletzt
|
||||
status.last_value = %ld ms, %zu Schritte, %zu Toolaufrufe
|
||||
status.tokens = Tokens
|
||||
status.tokens_value = ein %zu, aus %zu
|
||||
status.steps = Schritte
|
||||
status.steps_value = %zu Schritte, %zu Toolaufrufe
|
||||
status.cost = Kosten
|
||||
status.cost_value = %.4f USD
|
||||
status.compact = Kompaktierung
|
||||
status.compact_value = %zu angewandt, %zu fehlgeschlagen, %zu Runden (Agent %zu)
|
||||
status.embed = Index
|
||||
status.limits = Limits
|
||||
status.limits_value = max_bytes %zu, max_steps %zu
|
||||
status.meter = Messwert
|
||||
status.meter_value = ctx %zu/%zu, Cache %zu, Tok %zu/%zu
|
||||
status.bar = Leiste
|
||||
status.swarm = Schwarm
|
||||
status.swarm_value = %s (Id %d)
|
||||
|
||||
interview.system = Du bist splinter und arbeitest zum ersten Mal mit dieser Person. Interview sie, um sie kennenzulernen: woran sie arbeitet, welche Werkzeuge und Sprachen sie nutzt, wie sie angesprochen werden will, was sie nie will und welche Projekte zaehlen. Stelle eine Frage auf einmal, hoere zu und gehe nach, wo es wichtig ist. Frage nicht nach Codedetails, die du im Repository lesen kannst. Wenn du genug hast, schreibe eine kompakte Zusammenfassung der Person und ihrer Arbeitsweise (ein paar Absaetze oder Punkte) und beende deine Antwort mit der einen Zeile INTERVIEW_COMPLETE. Diese Zusammenfassung wird in ~/.splinter/USER.txt gespeichert und am Anfang jeder spaeteren Sitzung gelesen.
|
||||
interview.saved = Interview in USER.txt gespeichert
|
||||
tg.interview.begin = Interview gestartet. Beantworte die Fragen des Modells; /new beendet das Interview.
|
||||
interview.kickoff = Beginne das Interview mit deiner ersten Frage.
|
||||
|
||||
# Kommandos in commands/, fehlendes Profil, die beiden Besetzt-Hinweise
|
||||
cmd.script.empty = Das Kommando /%s hat nichts ausgegeben.
|
||||
cmd.script.failed = /%s ist fehlgeschlagen: %s
|
||||
cmd.script.output = Ausgabe von /%s%s%s:
|
||||
main.no_profile = splinter: kein Profil fuer '%s' - `splinter --interview` legt eines an
|
||||
tg.busy = besetzt - ein Turn laeuft
|
||||
tg.interview.running = das Interview laeuft bereits
|
||||
ui.agent_busy = ein Turn laeuft; wechsle den Agenten, wenn er fertig ist
|
||||
|
||||
# /learn: mine the sessions of this folder for what stays true
|
||||
learn.empty = (keine frueheren Sitzungen in diesem Ordner - lerne aus diesem Gespraech und sag, was du behalten wuerdest.)
|
||||
|
||||
# der Dialog des `ask`-Tools: das Modell fragt, der Operator antwortet
|
||||
ui.ask_title = das Modell fragt
|
||||
ui.ask_empty = (keine Antwortvorschlaege - tippe deine Antwort und Enter)
|
||||
ui.ask_none = (kein Vorschlag passt - Enter schickt, was du getippt hast)
|
||||
ui.ask_filter = Antwort:
|
||||
ui.ask_hint = Enter nimmt die Zeile; Tippen ersetzt sie Esc bricht ab
|
||||
|
||||
# das `ask`-Tool im Telegram-Gateway: die Frage kommt als Nachricht
|
||||
ask.how = Antworte mit einer Nachricht.
|
||||
|
||||
# /cancel waehrend einer offenen ask-Frage: der Turn endet, die Frage ist weg
|
||||
ask.cancelled = abgebrochen - die Frage ist erledigt.
|
||||
+133
-41
@@ -4,14 +4,45 @@
|
||||
# key that exists nowhere is shown as itself, so nothing is silently empty.
|
||||
|
||||
ui.ready = ready. Enter sends, Ctrl-D quits.
|
||||
ui.more_lines = ... %zu more lines
|
||||
ui.working = working...
|
||||
ui.steering_queued = steering queued
|
||||
ui.command_running = running command...
|
||||
ui.reconnected = reconnected
|
||||
ui.reconnecting = connection lost - reconnecting ...
|
||||
ui.no_sessions = no sessions yet
|
||||
ui.untitled = (untitled)
|
||||
ui.session_opened = session opened
|
||||
|
||||
# /sessions: the two-stage picker (source, then session)
|
||||
ui.sessions_title_source = sessions: source
|
||||
ui.sessions_title_session = sessions
|
||||
ui.sessions_no_source = no source has sessions
|
||||
ui.sessions_hint_source = Enter opens a source Esc cancels
|
||||
ui.sessions_hint_session = Enter opens the session Esc back
|
||||
ui.session_gone = session %s is gone - now on %s
|
||||
ui.compacted = context compacted: %zu->%zu msgs, %s->%s (%s->%s)
|
||||
ui.compact_nohost = compact: no plugin host, nothing to compact
|
||||
ui.compact_pending = compaction queued: it runs when the turn ends (target %zu tokens)
|
||||
ui.steer_queued_line = steering queued: %s
|
||||
ui.badtool_note = broken tool call, trying again in %d s (%d/%d)
|
||||
agent.badcall_answer = I could not send a runnable tool call: the arguments were not valid JSON. Nothing ran. The raw call is in the log; tell me how to continue.
|
||||
ui.steer_failed = steering not accepted (no turn is running)
|
||||
ui.model_title = model
|
||||
ui.open_busy = cannot switch sessions while a turn runs; /open after the turn
|
||||
ui.attach_busy = another client is attached: one conversation runs one turn at a time - close the other connection, or use it
|
||||
ui.command_busy = not while a turn runs; run it again after the turn
|
||||
ui.model_filter = filter:
|
||||
ui.model_hint = type to filter Up/Down move Enter selects Esc cancels
|
||||
ui.status_turn = %lds
|
||||
ui.model_empty = no models configured
|
||||
ui.model_probing = asking the endpoint what it serves ...
|
||||
ui.model_none = no match
|
||||
|
||||
sidebar.session = session
|
||||
sidebar.cwd = dir
|
||||
sidebar.last_turn = last turn
|
||||
sidebar.tokens = %zu tok (in %zu)
|
||||
|
||||
status.title = splinter %s
|
||||
|
||||
role.you = you
|
||||
role.agent = agent
|
||||
@@ -22,19 +53,30 @@ role.error = error
|
||||
|
||||
cmd.unknown = unknown command: /%s
|
||||
cmd.available = available:
|
||||
widgets.none = no plugin published a widget line
|
||||
|
||||
err.oom = out of memory
|
||||
err.theme = theme
|
||||
err.session = session
|
||||
err.plugin_failed = plugin failed
|
||||
|
||||
role.tool = tool
|
||||
role.observation = output
|
||||
err.thread = cannot start the turn thread
|
||||
err.turn_failed = turn failed
|
||||
focus.reminder = Before answering, check whether the last step moved closer to the goal. If not, say so and name the next step. Goal: %s
|
||||
focus.goal_prompt = Goal: %s. Work toward it. When the goal is fully achieved, end your final answer with the single line GOAL_COMPLETE so splinter can mark it as succeeded.
|
||||
focus.reminder = Recap to remember: %s. Before answering, check whether the last step moved closer to the goal; if not, say so and name the next step. When the goal is fully achieved, end your final answer with the single line GOAL_COMPLETE.
|
||||
focus.recap_prompt = Goal: %s. Write a short recap to remember: 3-5 bullets, what must be true at the end, the first concrete steps, and open questions. When the goal is fully achieved, end your final answer with the single line GOAL_COMPLETE.
|
||||
focus.continue_prompt = Continue working toward this goal: %s. Pick up where the session stopped: check the current state, do the next concrete step, and report what changed. When the goal is fully achieved, end your final answer with the single line GOAL_COMPLETE.
|
||||
selfcheck.prompt = Something went wrong in this session, so check yourself instead of asking the operator: read the tail of our conversation below (tool output is shortened), find the step that failed, say what the cause was, what you got wrong, and what you will do differently now. Then continue the task from where it stopped. Do not repeat work that is still valid.
|
||||
selfcheck.empty = (no turns yet - there is nothing to check, so start the task.)
|
||||
focus.set = goal set: %s
|
||||
focus.none = no goal set (/goal <text>)
|
||||
focus.status = goal: %s (%u reminders, every %u turns)
|
||||
focus.status = goal: %s (%u recaps, every %u turns)
|
||||
focus.status_done = goal: %s [succeeded] (%u recaps, every %u turns)
|
||||
focus.widget_recap = recap %u, every %u turns
|
||||
focus.note_goal = goal in the prompt
|
||||
focus.note_recap = recap applied (turn %u, every %u turns)
|
||||
focus.succeeded = goal succeeded: %s
|
||||
cps.idle = idle (applied %lu, prepared %lu)
|
||||
cps.plan = plan ready: cut %zu/%zu, %zu -> %zu B
|
||||
cli.no_output = cli: '%s' produced no output
|
||||
@@ -42,24 +84,20 @@ cli.timeout = cli: '%s' timed out after %s s
|
||||
cli.failed = cli: '%s' failed (exit %d): %.400s
|
||||
ui.prompt_mark = >
|
||||
ui.steer_mark = steer>
|
||||
ui.retry_note = retrying in %d s: %s
|
||||
ui.swarm_locked = [swarm locked]
|
||||
ui.approve = run %s (%s) %.60s? y/N
|
||||
auth.mutate = changes files
|
||||
auth.destructive = destructive
|
||||
ui.status_ctx_bar = ctx %zu/%zu %s %d%%
|
||||
ui.status_ctx = ctx %zu
|
||||
ui.status_cache = cache %d%%
|
||||
ui.status_cache_none = cache -
|
||||
ui.status_tps = %d tok/s
|
||||
ui.status_tps_none = - tok/s
|
||||
role.diff = diff
|
||||
|
||||
# approvals (ack): channel messages, the gateway's replies, the terminal
|
||||
ack.request = Approval %d: %s %s
|
||||
ack.how = Answer: ok %d / no %d
|
||||
ack.prompt = approval %d: %s %s (%ds) - 'splinter --ack %d yes' or y/N here:
|
||||
ack.pending = approval %d: %s %s (%ds)
|
||||
ack.approved_by = splinter: approved by %s
|
||||
ack.none = no open requests
|
||||
ack.granted = Approved.
|
||||
ack.refused = Refused.
|
||||
ack.gone = There is no such request (any more).
|
||||
ack.waiting = Still waiting for an approval: ok %d / no %d
|
||||
focus.recap = reminder scheduled for the next turn
|
||||
|
||||
# openai transport
|
||||
openai.oom = openai: out of memory
|
||||
@@ -72,6 +110,7 @@ openai.transfer_failed = openai: transfer failed for %s
|
||||
openai.unparseable = openai: unparseable response (no status)
|
||||
openai.stream_failed = openai: stream failed for %s: %.300s
|
||||
openai.no_sse = openai: endpoint sent no SSE data: %.300s
|
||||
openai.http_status = openai: HTTP %ld from %s: %.300s
|
||||
openai.stream_no_answer = openai: stream ended with no answer: %.300s
|
||||
|
||||
# delegate
|
||||
@@ -81,26 +120,16 @@ delegate.parallel_timeout = [parallel: timeout, killing the rest]
|
||||
# telegram menu and approval buttons
|
||||
tg.cmd.start = Greeting and commands
|
||||
tg.cmd.help = Help and commands
|
||||
tg.cmd.goal = Set or show the goal
|
||||
tg.cmd.recap = Put the goal into the next turn
|
||||
tg.cmd.goal = Set or show the goal, then recap it
|
||||
tg.cmd.run = run /%s
|
||||
tg.cmd.tasks = Show the plan
|
||||
tg.help = I am splinter. Send a message for a turn. /goal sets the goal, /recap puts it into the next turn, /tasks shows the plan. Changes ask here with Yes/No or ok <id> / no <id>.
|
||||
ack.yes = Yes
|
||||
ack.no = No
|
||||
ack.how = Answer: button below or ok %d / no %d
|
||||
tg.cmd.status = session, model, tokens, limits
|
||||
tg.cmd.menu = menu: status, model, new, help
|
||||
tg.help = I am splinter. Send a message for a turn. /goal sets the goal and starts a recap turn, /tasks shows the plan. Changes ask here with Yes/No or ok <id> / no <id>.
|
||||
|
||||
tg.cmd.interview = create the profile in the chat
|
||||
tg.interview.start = First conversation for '%s'. I ask %zu questions; /skip skips one, /cancel stops.
|
||||
tg.interview.question = Question %zu/%zu: %s
|
||||
tg.interview.how = Just answer in the chat.
|
||||
tg.interview.saved = profile written: %s
|
||||
tg.interview.cancel = interview cancelled.
|
||||
tg.interview.busy = The interview is running; answer, /skip or /cancel.
|
||||
|
||||
# interview questions (terminal and Telegram)
|
||||
interview.intro = First conversation for '%s'. Enter skips a question, Ctrl-D aborts.
|
||||
interview.header = _Written by `splinter --interview`. Edit it by hand whenever you like; splinter reads it at start._
|
||||
interview.q.language = Which language should I speak with you in?
|
||||
interview.h.language = e.g. deutsch, english, portugues
|
||||
interview.q.about = Who are you and what are you working on right now?
|
||||
@@ -110,31 +139,40 @@ interview.h.stack = e.g. C99/POSIX, no Python, make instead of CMake
|
||||
interview.q.style = How should I answer?
|
||||
interview.h.style = short/long, with or without reasoning, code first?
|
||||
interview.q.never = What should I NEVER do?
|
||||
interview.h.never = e.g. no commits without a request, nothing in /tmp
|
||||
interview.h.never = e.g. never write to /home/carol, no secrets in logs
|
||||
interview.q.paths = Which paths are sacred or dangerous?
|
||||
interview.h.paths = e.g. never touch /home/carol
|
||||
interview.skipped = (not answered)
|
||||
interview.written = Written: %s
|
||||
interview.error.nodir = interview: no session directory
|
||||
interview.error.write = interview: cannot write %s
|
||||
# /model and /connect (gateway)
|
||||
session.new = New conversation: %s
|
||||
session.failed = Could not start a new session: %s
|
||||
session.renamed = Session %s renamed to "%s"
|
||||
session.rename_failed = Cannot rename the session: %s
|
||||
session.rename_usage = Usage: /rename [ID] TITLE
|
||||
session.removed = Session %s removed
|
||||
session.remove_failed = Cannot remove %s: %s
|
||||
session.rm_current = Cannot remove the open session; /open another first
|
||||
session.rm_usage = Usage: /rm ID
|
||||
session.no_session = No such session: %s
|
||||
tg.cmd.new = new conversation
|
||||
|
||||
tg.cmd.model = choose a model
|
||||
tg.cmd.connect = add a provider
|
||||
tg.menu.text = Menu
|
||||
tg.menu.status = Status
|
||||
tg.menu.model = Model
|
||||
tg.menu.new = New
|
||||
tg.menu.help = Help
|
||||
tg.menu.toast = ok
|
||||
model.choose = Choose a model. The list is the configuration; the choice lasts for this session.
|
||||
model.none = No model is configured. Add one with /connect.
|
||||
model.unknown = No such model: %s
|
||||
model.pool = Pool %s: using %s (provider %s, this session).
|
||||
model.pools = pools:
|
||||
model.pending = model switch to %s after the current request
|
||||
ui.cancelling = cancelling ... (Ctrl-C again quits)
|
||||
model.failed = Could not switch: %s
|
||||
model.switched = Model: %s (provider %s, this session).
|
||||
model.no_key = " (no %s set)"
|
||||
model.no_key = , no %s set
|
||||
|
||||
model.saved = Model: %s (provider %s). Saved for the next start.
|
||||
model.save_failed = Model: %s (provider %s). Not saved: %s
|
||||
model.probe = Ask the endpoints for their models
|
||||
model.probe_start = Asking %zu provider(s) for their models...
|
||||
@@ -172,13 +210,14 @@ sidebar.usage = usage
|
||||
sidebar.turn_line = %.1f s, %zu steps, %zu tools
|
||||
widget.focus = goal
|
||||
widget.plan = plan
|
||||
widget.sysinfo = system
|
||||
widget.tasks = tasks
|
||||
widget.tmux = tmux
|
||||
ui.running = running %lds%s |%s Enter = steer, Ctrl-C = cancel
|
||||
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
|
||||
@@ -187,6 +226,59 @@ usage.calls = %lu calls
|
||||
usage.room = , room in %s
|
||||
usage.of_calls = (%lu/%lu calls)
|
||||
usage.of_tokens = (%lu/%lu tokens)
|
||||
plan.widget = todo %d, doing %d, done %d
|
||||
plan.widget_active = #%d active - todo %d, doing %d, done %d
|
||||
ui.thinking = thinking
|
||||
status.title = status (%s)
|
||||
status.session = session
|
||||
status.dir = dir
|
||||
status.model = model
|
||||
status.endpoint = endpoint
|
||||
status.theme = theme
|
||||
status.agent = agent
|
||||
status.last = last
|
||||
status.last_value = %ld ms, %zu steps, %zu tool calls
|
||||
status.tokens = tokens
|
||||
status.tokens_value = in %zu, out %zu
|
||||
status.steps = steps
|
||||
status.steps_value = %zu steps, %zu tool calls
|
||||
status.cost = cost
|
||||
status.cost_value = %.4f USD
|
||||
status.compact = compact
|
||||
status.compact_value = %zu applied, %zu failed, %zu turns (agent %zu)
|
||||
status.embed = index
|
||||
status.limits = limits
|
||||
status.limits_value = max_bytes %zu, max_steps %zu
|
||||
status.meter = meter
|
||||
status.meter_value = ctx %zu/%zu, cache %zu, tok %zu/%zu
|
||||
status.bar = bar
|
||||
status.swarm = swarm
|
||||
status.swarm_value = %s (id %d)
|
||||
|
||||
interview.system = You are splinter, about to work with this person for the first time. Interview them to get to know them: what they work on, the tools and languages they reach for, how they want to be spoken to, what they never want, and which projects matter. Ask one question at a time, listen, and go deeper where it matters. Do not ask about code details you can read from the repository. When you have enough, write a compact summary of the person and how they want to work (a few paragraphs or bullets), then end your answer with the single line INTERVIEW_COMPLETE. That summary is saved to ~/.splinter/USER.txt and read at the start of every later session.
|
||||
interview.saved = interview saved to USER.txt
|
||||
tg.interview.begin = Interview started. Answer the model's questions; /new leaves the interview.
|
||||
interview.kickoff = Begin the interview with your first question.
|
||||
|
||||
# commands/ programs, a missing profile, and the two busy notices
|
||||
cmd.script.empty = The command /%s printed nothing.
|
||||
cmd.script.failed = /%s failed: %s
|
||||
cmd.script.output = Output of /%s%s%s:
|
||||
main.no_profile = splinter: no profile for '%s' - `splinter --interview` creates one
|
||||
tg.busy = busy - a turn is running
|
||||
tg.interview.running = the interview is already running
|
||||
ui.agent_busy = a turn is running; switch the agent when it is done
|
||||
|
||||
# /learn: mine the sessions of this folder for what stays true
|
||||
learn.empty = (no earlier sessions in this folder - learn from this conversation and say what you would keep.)
|
||||
|
||||
# the `ask` tool's dialog: the model asks, the operator answers
|
||||
ui.ask_title = the model asks
|
||||
ui.ask_empty = (no suggested answers - type your answer and press Enter)
|
||||
ui.ask_none = (no suggestion matches - Enter sends what you typed)
|
||||
ui.ask_filter = answer:
|
||||
ui.ask_hint = Enter takes the row; typing replaces it Esc cancels
|
||||
|
||||
# the `ask` tool in the Telegram gateway: the question arrives as a message
|
||||
ask.how = Answer with a message.
|
||||
|
||||
# /cancel while an `ask` question is open: the turn ends, the question is gone
|
||||
ask.cancelled = cancelled - the question is gone.
|
||||
+133
-43
@@ -5,23 +5,60 @@
|
||||
# uma linha vazia esconderia um bug.
|
||||
|
||||
ui.ready = pronto. Enter envia, Ctrl-D sai.
|
||||
ui.more_lines = ... %zu linhas a mais
|
||||
ui.working = trabalhando...
|
||||
ui.steering_queued = direcionamento na fila
|
||||
ui.command_running = executando comando...
|
||||
ui.reconnected = reconectado
|
||||
ui.reconnecting = conexao perdida - reconectando ...
|
||||
ui.no_sessions = nenhuma sessao ainda
|
||||
ui.untitled = (sem titulo)
|
||||
ui.session_opened = sessao aberta
|
||||
|
||||
# /sessions: the two-stage picker (source, then session)
|
||||
ui.sessions_title_source = sessoes: fonte
|
||||
ui.sessions_title_session = sessoes
|
||||
ui.sessions_no_source = nenhuma fonte tem sessoes
|
||||
ui.sessions_hint_source = Enter abre uma fonte Esc cancela
|
||||
ui.sessions_hint_session = Enter abre a sessao Esc volta
|
||||
ui.session_gone = sessao %s sumiu - agora em %s
|
||||
ui.compacted = contexto compactado: %zu->%zu msgs, %s->%s (%s->%s)
|
||||
ui.compact_nohost = compact: sem host de plugin, nada a compactar
|
||||
ui.compact_pending = compactacao na fila: roda no fim do turno (alvo %zu tokens)
|
||||
ui.steer_queued_line = direcionamento na fila: %s
|
||||
ui.badtool_note = chamada de ferramenta quebrada, nova tentativa em %d s (%d/%d)
|
||||
agent.badcall_answer = Nao consegui enviar uma chamada de ferramenta executavel: os argumentos nao eram JSON valido. Nada rodou. A chamada bruta esta no log; diga como continuar.
|
||||
ui.steer_failed = direcionamento nao aceito (nenhum turno em andamento)
|
||||
ui.model_title = modelo
|
||||
ui.open_busy = nao da para trocar de sessao durante um turno; /open depois
|
||||
ui.attach_busy = outro cliente ja esta conectado: uma conversa roda um turno por vez - feche a outra conexao, ou use-a
|
||||
ui.command_busy = nao durante um turno; rode de novo depois
|
||||
ui.model_filter = filtro:
|
||||
ui.model_hint = digite para filtrar setas movem Enter escolhe Esc cancela
|
||||
ui.status_turn = %lds
|
||||
ui.model_empty = nenhum modelo configurado
|
||||
ui.model_probing = perguntando ao endpoint o que ele serve ...
|
||||
ui.model_none = nenhum resultado
|
||||
ui.prompt_mark = >
|
||||
ui.steer_mark = direcionar>
|
||||
ui.retry_note = nova tentativa em %d s: %s
|
||||
ui.swarm_locked = [enxame bloqueado]
|
||||
ui.approve = executar %s (%s) %.60s? y/N
|
||||
ui.status_ctx_bar = ctx %zu/%zu %s %d%%
|
||||
ui.status_ctx = ctx %zu
|
||||
ui.status_cache = cache %d%%
|
||||
ui.status_cache_none = cache -
|
||||
ui.status_tps = %d tok/s
|
||||
ui.status_tps_none = - tok/s
|
||||
|
||||
sidebar.session = sessao
|
||||
sidebar.cwd = diretorio
|
||||
sidebar.last_turn = ultimo turno
|
||||
sidebar.tokens = %zu tok (entrada %zu)
|
||||
|
||||
status.title = splinter %s
|
||||
|
||||
role.you = voce
|
||||
role.agent = modelo
|
||||
role.thinking = pensando
|
||||
role.tool = ferramenta
|
||||
role.observation = saida
|
||||
role.shell = shell
|
||||
role.splinter = splinter
|
||||
role.error = erro
|
||||
@@ -29,21 +66,29 @@ role.diff = alteracao
|
||||
|
||||
cmd.unknown = comando desconhecido: /%s
|
||||
cmd.available = disponiveis:
|
||||
widgets.none = nenhum plugin publicou uma linha de widget
|
||||
|
||||
err.oom = sem memoria
|
||||
err.theme = tema
|
||||
err.session = sessao
|
||||
err.plugin_failed = plugin falhou
|
||||
err.thread = nao foi possivel iniciar a thread do turno
|
||||
err.turn_failed = turno falhou
|
||||
|
||||
auth.mutate = altera arquivos
|
||||
auth.destructive = destrutivo
|
||||
|
||||
focus.reminder = Antes de responder, verifique se o ultimo passo aproximou do objetivo; se nao, diga isso e proponha o proximo passo. Objetivo: %s
|
||||
focus.goal_prompt = Objetivo: %s. Trabalhe nisso. Quando o objetivo estiver totalmente alcancado, termine sua resposta final com a linha unica GOAL_COMPLETE para que o splinter possa marcar como succeeded.
|
||||
focus.reminder = Recap para lembrar: %s. Antes de responder, verifique se o ultimo passo aproximou do objetivo; se nao, diga isso e proponha o proximo passo. Quando o objetivo estiver totalmente alcancado, termine sua resposta final com a linha unica GOAL_COMPLETE.
|
||||
focus.recap_prompt = Objetivo: %s. Escreva um recap curto para lembrar: 3-5 pontos, o que precisa estar certo no final, os primeiros passos concretos e as perguntas abertas. Quando o objetivo estiver totalmente alcancado, termine sua resposta final com a linha unica GOAL_COMPLETE.
|
||||
focus.continue_prompt = Continue trabalhando neste objetivo: %s. Retome de onde a sessao parou: verifique o estado, faca o proximo passo concreto e relate o que mudou. Quando o objetivo estiver totalmente alcancado, termine sua resposta final com a linha unica GOAL_COMPLETE.
|
||||
selfcheck.prompt = Algo deu errado nesta sessao, entao verifique voce mesmo em vez de perguntar ao operador: leia o final da nossa conversa abaixo (a saida das ferramentas esta encurtada), encontre o passo que falhou, diga qual foi a causa, o que voce errou e o que vai fazer diferente agora. Depois continue a tarefa de onde ela parou. Nao repita trabalho que ainda e valido.
|
||||
selfcheck.empty = (ainda sem turnos - nao ha nada para verificar, entao comece a tarefa.)
|
||||
focus.set = objetivo definido: %s
|
||||
focus.none = nenhum objetivo definido (/goal <texto>)
|
||||
focus.status = objetivo: %s (%u lembretes, a cada %u turnos)
|
||||
focus.status = objetivo: %s (%u recaps, a cada %u turnos)
|
||||
focus.status_done = objetivo: %s [succeeded] (%u recaps, a cada %u turnos)
|
||||
focus.widget_recap = recap %u, a cada %u turnos
|
||||
focus.note_goal = objetivo no prompt
|
||||
focus.note_recap = recap aplicado (turno %u, a cada %u turnos)
|
||||
focus.succeeded = objetivo alcancado: %s
|
||||
|
||||
cps.idle = ocioso (aplicado %lu, preparado %lu)
|
||||
cps.plan = plano pronto: corte %zu/%zu, %zu -> %zu B
|
||||
@@ -55,15 +100,7 @@ cli.failed = cli: '%s' falhou (exit %d): %.400s
|
||||
# aprovacoes (ack): mensagens dos canais, respostas do gateway, terminal
|
||||
ack.request = Aprovacao %d: %s %s
|
||||
ack.how = Resposta: ok %d / no %d
|
||||
ack.prompt = aprovacao %d: %s %s (%ds) - 'splinter --ack %d yes' ou y/N aqui:
|
||||
ack.pending = aprovacao %d: %s %s (%ds)
|
||||
ack.approved_by = splinter: aprovado por %s
|
||||
ack.none = nenhum pedido aberto
|
||||
ack.granted = Aprovado.
|
||||
ack.refused = Recusado.
|
||||
ack.gone = Esse pedido nao existe (mais).
|
||||
ack.waiting = Ainda aguardando uma aprovacao: ok %d / no %d
|
||||
focus.recap = lembrete agendado para o proximo turno
|
||||
|
||||
# openai transport
|
||||
openai.oom = openai: sem memoria
|
||||
@@ -76,6 +113,7 @@ openai.transfer_failed = openai: falha na transferencia para %s
|
||||
openai.unparseable = openai: resposta ilegivel (sem status)
|
||||
openai.stream_failed = openai: stream falhou para %s: %.300s
|
||||
openai.no_sse = openai: endpoint nao enviou dados SSE: %.300s
|
||||
openai.http_status = openai: HTTP %ld de %s: %.300s
|
||||
openai.stream_no_answer = openai: stream terminou sem resposta: %.300s
|
||||
|
||||
# delegate
|
||||
@@ -85,26 +123,16 @@ delegate.parallel_timeout = [paralelo: tempo esgotado, encerrando o resto]
|
||||
# telegram menu and approval buttons
|
||||
tg.cmd.start = Saudacao e comandos
|
||||
tg.cmd.help = Ajuda e comandos
|
||||
tg.cmd.goal = Definir ou mostrar a meta
|
||||
tg.cmd.recap = Levar a meta para o proximo turno
|
||||
tg.cmd.goal = Definir ou mostrar a meta, depois resumir
|
||||
tg.cmd.run = executa /%s
|
||||
tg.cmd.tasks = Mostrar o plano
|
||||
tg.help = Eu sou o splinter. Envie uma mensagem para um turno. /goal define a meta, /recap leva a meta para o proximo turno, /tasks mostra o plano. Mudancas perguntam aqui com Sim/Nao ou ok <id> / no <id>.
|
||||
ack.yes = Sim
|
||||
ack.no = Nao
|
||||
ack.how = Resposta: botao abaixo ou ok %d / no %d
|
||||
tg.cmd.status = sessao, modelo, tokens, limites
|
||||
tg.cmd.menu = menu: status, modelo, novo, ajuda
|
||||
tg.help = Eu sou o splinter. Envie uma mensagem para um turno. /goal define a meta e inicia um turno de recap, /tasks mostra o plano. Mudancas perguntam aqui com Sim/Nao ou ok <id> / no <id>.
|
||||
|
||||
tg.cmd.interview = criar o perfil no chat
|
||||
tg.interview.start = Primeira conversa para '%s'. Sao %zu perguntas; /skip pula uma, /cancel cancela.
|
||||
tg.interview.question = Pergunta %zu/%zu: %s
|
||||
tg.interview.how = Responda no chat.
|
||||
tg.interview.saved = perfil escrito: %s
|
||||
tg.interview.cancel = entrevista cancelada.
|
||||
tg.interview.busy = A entrevista esta em andamento; responda, /skip ou /cancel.
|
||||
|
||||
# interview questions (terminal and Telegram)
|
||||
interview.intro = Primeira conversa para '%s'. Enter pula uma pergunta, Ctrl-D cancela.
|
||||
interview.header = _Escrito por `splinter --interview`. Edite a mao quando quiser; splinter le no inicio._
|
||||
interview.q.language = Em que lingua devo falar com voce?
|
||||
interview.h.language = ex.: deutsch, english, portugues
|
||||
interview.q.about = Quem e voce e no que esta trabalhando agora?
|
||||
@@ -114,31 +142,40 @@ interview.h.stack = ex.: C99/POSIX, sem Python, make em vez de CMake
|
||||
interview.q.style = Como devo responder?
|
||||
interview.h.style = curto/longo, com ou sem justificativa, codigo primeiro?
|
||||
interview.q.never = O que eu NUNCA devo fazer?
|
||||
interview.h.never = ex.: nenhum commit sem pedido, nada em /tmp
|
||||
interview.h.never = ex.: nunca escrever em /home/carol, nenhum segredo em logs
|
||||
interview.q.paths = Quais caminhos sao sagrados ou perigosos?
|
||||
interview.h.paths = ex.: nunca tocar em /home/carol
|
||||
interview.skipped = (nao respondido)
|
||||
interview.written = Escrito: %s
|
||||
interview.error.nodir = interview: sem diretorio de sessao
|
||||
interview.error.write = interview: nao consigo escrever %s
|
||||
# /model e /connect (gateway)
|
||||
session.new = Nova conversa: %s
|
||||
session.failed = Nao consegui abrir uma sessao nova: %s
|
||||
session.renamed = Sessao %s agora se chama "%s"
|
||||
session.rename_failed = Nao consegui renomear a sessao: %s
|
||||
session.rename_usage = Uso: /rename [ID] TITULO
|
||||
session.removed = Sessao %s removida
|
||||
session.remove_failed = Nao consegui remover %s: %s
|
||||
session.rm_current = Nao posso remover a sessao aberta; use /open em outra antes
|
||||
session.rm_usage = Uso: /rm ID
|
||||
session.no_session = Nenhuma sessao assim: %s
|
||||
tg.cmd.new = nova conversa
|
||||
|
||||
tg.cmd.model = escolher um modelo
|
||||
tg.cmd.connect = adicionar um provedor
|
||||
tg.menu.text = Menu
|
||||
tg.menu.status = Status
|
||||
tg.menu.model = Modelo
|
||||
tg.menu.new = Novo
|
||||
tg.menu.help = Ajuda
|
||||
tg.menu.toast = ok
|
||||
model.choose = Escolha um modelo. A lista e a configuracao; a escolha vale para esta sessao.
|
||||
model.none = Nenhum modelo configurado. Adicione um com /connect.
|
||||
model.unknown = Modelo inexistente: %s
|
||||
model.pool = Pool %s: usando %s (provedor %s, esta sessao).
|
||||
model.pools = Pools:
|
||||
model.pending = troca de modelo para %s depois da requisicao atual
|
||||
ui.cancelling = cancelando ... (Ctrl-C de novo encerra)
|
||||
model.failed = Nao consegui trocar: %s
|
||||
model.switched = Modelo: %s (provedor %s, esta sessao).
|
||||
model.no_key = " (%s nao definida)"
|
||||
model.no_key = , %s nao definida
|
||||
|
||||
model.saved = Modelo: %s (provedor %s). Salvo para a proxima sessao.
|
||||
model.save_failed = Modelo: %s (provedor %s). Nao salvo: %s
|
||||
model.probe = Perguntar aos endpoints quais modelos servem
|
||||
model.probe_start = Perguntando a %zu provedor(es) pelos modelos...
|
||||
@@ -167,7 +204,6 @@ connect.test_failed = O teste falhou: %s (mesmo assim esta salvo)
|
||||
connect.use = Usar agora
|
||||
connect.later = Depois
|
||||
|
||||
|
||||
reply.empty = (vazio)
|
||||
|
||||
# perfis de agente, uso, barra lateral (junto com os perfis)
|
||||
@@ -176,13 +212,14 @@ sidebar.usage = uso
|
||||
sidebar.turn_line = %.1f s, %zu passos, %zu ferramentas
|
||||
widget.focus = meta
|
||||
widget.plan = plano
|
||||
widget.sysinfo = sistema
|
||||
widget.tasks = tarefas
|
||||
widget.tmux = tmux
|
||||
ui.running = executando %lds%s |%s Enter = guiar, Ctrl-C = cancelar
|
||||
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
|
||||
@@ -191,6 +228,59 @@ usage.calls = %lu chamadas
|
||||
usage.room = , vaga em %s
|
||||
usage.of_calls = (%lu/%lu chamadas)
|
||||
usage.of_tokens = (%lu/%lu tokens)
|
||||
plan.widget = %d a fazer, %d em curso, %d feitas
|
||||
plan.widget_active = #%d ativa - %d a fazer, %d em curso, %d feitas
|
||||
ui.thinking = pensando
|
||||
status.title = status (%s)
|
||||
status.session = sessao
|
||||
status.dir = diretorio
|
||||
status.model = modelo
|
||||
status.endpoint = endpoint
|
||||
status.theme = tema
|
||||
status.agent = agente
|
||||
status.last = ultimo
|
||||
status.last_value = %ld ms, %zu passos, %zu chamadas de ferramenta
|
||||
status.tokens = tokens
|
||||
status.tokens_value = entrada %zu, saida %zu
|
||||
status.steps = passos
|
||||
status.steps_value = %zu passos, %zu chamadas de ferramenta
|
||||
status.cost = custo
|
||||
status.cost_value = %.4f USD
|
||||
status.compact = compactacao
|
||||
status.compact_value = %zu aplicadas, %zu falharam, %zu turnos (agente %zu)
|
||||
status.embed = indice
|
||||
status.limits = limites
|
||||
status.limits_value = max_bytes %zu, max_steps %zu
|
||||
status.meter = medidor
|
||||
status.meter_value = ctx %zu/%zu, cache %zu, tok %zu/%zu
|
||||
status.bar = barra
|
||||
status.swarm = enxame
|
||||
status.swarm_value = %s (id %d)
|
||||
|
||||
interview.system = Voce e o splinter e vai trabalhar com esta pessoa pela primeira vez. Entreviste-a para conhece-la: no que trabalha, quais ferramentas e linguagens usa, como quer ser tratada, o que nunca quer e quais projetos importam. Faca uma pergunta por vez, escute e aprofunde onde importa. Nao pergunte detalhes de codigo que voce pode ler no repositorio. Quando tiver o suficiente, escreva um resumo compacto da pessoa e de como ela quer trabalhar (alguns paragrafos ou pontos) e termine sua resposta com a linha unica INTERVIEW_COMPLETE. Esse resumo e salvo em ~/.splinter/USER.txt e lido no inicio de cada sessao posterior.
|
||||
interview.saved = entrevista salva em USER.txt
|
||||
tg.interview.begin = Entrevista iniciada. Responda as perguntas do modelo; /new encerra a entrevista.
|
||||
interview.kickoff = Comece a entrevista com sua primeira pergunta.
|
||||
|
||||
# comandos em commands/, perfil ausente, os dois avisos de ocupado
|
||||
cmd.script.empty = O comando /%s nao imprimiu nada.
|
||||
cmd.script.failed = /%s falhou: %s
|
||||
cmd.script.output = Saida de /%s%s%s:
|
||||
main.no_profile = splinter: sem perfil para '%s' - `splinter --interview` cria um
|
||||
tg.busy = ocupado - um turno esta em andamento
|
||||
tg.interview.running = a entrevista ja esta em andamento
|
||||
ui.agent_busy = um turno esta em andamento; troque de agente quando terminar
|
||||
|
||||
# /learn: mine the sessions of this folder for what stays true
|
||||
learn.empty = (nenhuma sessao anterior nesta pasta - aprenda com esta conversa e diga o que guardaria.)
|
||||
|
||||
# o dialogo da ferramenta `ask`: o modelo pergunta, o operador responde
|
||||
ui.ask_title = o modelo pergunta
|
||||
ui.ask_empty = (sem sugestoes - escreva a resposta e pressione Enter)
|
||||
ui.ask_none = (nenhuma sugestao corresponde - Enter envia o que voce escreveu)
|
||||
ui.ask_filter = resposta:
|
||||
ui.ask_hint = Enter pega a linha; digitar substitui Esc cancela
|
||||
|
||||
# a ferramenta `ask` no gateway do Telegram: a pergunta chega como mensagem
|
||||
ask.how = Responda com uma mensagem.
|
||||
|
||||
# /cancel com uma pergunta `ask` aberta: o turno termina, a pergunta some
|
||||
ask.cancelled = cancelado - a pergunta nao existe mais.
|
||||
-749
@@ -1,749 +0,0 @@
|
||||
/*
|
||||
* splinter -- the turn loop.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* One turn: append the user message, ask the transport, run the tools it asks
|
||||
* for, repeat until it answers or the step limit is hit. The conversation
|
||||
* lives in sp_conv and survives the turn, so splinter is not an amnesiac
|
||||
* one-shot.
|
||||
*
|
||||
* Invariants, in this order, before any tool runs:
|
||||
* 1. the conversation fits the byte budget, otherwise the turn fails and
|
||||
* nothing is sent (never rely on the endpoint to truncate);
|
||||
* 2. the tool exists in the registry, otherwise the model is told so;
|
||||
* 3. the tool's authorization class is honoured; a denial is reported back
|
||||
* as the observation, not silently skipped.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <errno.h>
|
||||
#include <poll.h>
|
||||
#include <pthread.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "i18n.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "ack.h"
|
||||
#include "log.h"
|
||||
#include "usage.h"
|
||||
|
||||
/*
|
||||
* The terminal as one more approval channel. It must be stoppable: when the
|
||||
* phone answers first, or the request times out, the agent goes on, and a
|
||||
* thread still sitting in fgets() would hold it until somebody pressed Enter.
|
||||
* So it polls the terminal together with a pipe, and a byte on the pipe ends it.
|
||||
*/
|
||||
struct ack_thread {
|
||||
int id;
|
||||
FILE *in;
|
||||
int stop; /* read end of the stop pipe */
|
||||
};
|
||||
|
||||
|
||||
struct quota_set_ctx { long status; long now; long retry_after_s; };
|
||||
static void quota_set_fn(struct sp_prov_state *st, void *p) {
|
||||
struct quota_set_ctx *c = p;
|
||||
long ra = 0;
|
||||
if (c->retry_after_s > 0) ra = c->now + c->retry_after_s;
|
||||
else if (c->status == 429 || c->status == 402) ra = c->now + 60;
|
||||
else if (c->status == 529) ra = c->now + 120;
|
||||
if (ra > 0 && st->quota_ready_at < ra) st->quota_ready_at = ra;
|
||||
if (ra > 0) st->last_429_at = c->now;
|
||||
if (ra > 0) snprintf(st->note, sizeof(st->note), "quota %ld ready_at=%ld", c->status, ra);
|
||||
}
|
||||
static void quota_hint(const char *provider, const char *key_id, long status, long retry_after_s) {
|
||||
struct quota_set_ctx c;
|
||||
if (!provider||!*provider||!key_id||!*key_id) return;
|
||||
if (status!=429 && status!=402 && status!=529) return;
|
||||
c.status = status; c.now = (long)time(NULL); c.retry_after_s = retry_after_s;
|
||||
sp_provstate_update(provider, key_id, quota_set_fn, &c);
|
||||
}
|
||||
|
||||
static void *
|
||||
ack_stdin_thread(void *arg)
|
||||
{
|
||||
struct ack_thread *at = arg;
|
||||
char line[64];
|
||||
struct pollfd pfd[2];
|
||||
|
||||
pfd[0].fd = fileno(at->in);
|
||||
pfd[0].events = POLLIN;
|
||||
pfd[1].fd = at->stop;
|
||||
pfd[1].events = POLLIN;
|
||||
for (;;) {
|
||||
pfd[0].revents = pfd[1].revents = 0;
|
||||
if (poll(pfd, 2, -1) < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
if (pfd[1].revents != 0)
|
||||
break; /* answered elsewhere or expired */
|
||||
if (pfd[0].revents != 0) {
|
||||
if (fgets(line, sizeof(line), at->in) != NULL)
|
||||
(void)sp_ack_answer(at->id,
|
||||
line[0] == 'y' || line[0] == 'Y', "terminal");
|
||||
break;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/*
|
||||
* Approval through the ack mechanism: the request becomes a file, the channels are
|
||||
* fired, and whoever answers first wins - the person at this terminal, a phone, or
|
||||
* a script. Without any channel configured this falls back to the plain prompt, so
|
||||
* nothing starts hanging that used to be synchronous.
|
||||
*/
|
||||
static int
|
||||
ack_approval(struct sp_agent *a, const struct sp_tool *t, const char *args)
|
||||
{
|
||||
const char *chans = getenv("SPLINTER_ACK_CHANNELS");
|
||||
const char *ttl_s = getenv("SPLINTER_ACK_TTL");
|
||||
struct sp_buf log;
|
||||
char who[64] = "";
|
||||
int id, ttl, yes;
|
||||
pthread_t th;
|
||||
int th_started = 0;
|
||||
int stop[2] = { -1, -1 };
|
||||
struct ack_thread at;
|
||||
|
||||
if (chans == NULL || *chans == '\0')
|
||||
return -1;
|
||||
ttl = ttl_s != NULL && *ttl_s != '\0' ? atoi(ttl_s) : 120;
|
||||
if (ttl <= 0)
|
||||
ttl = 120;
|
||||
id = sp_ack_request(t->name, args,
|
||||
t->auth == SP_AUTH_MUTATE ? "mutate" : "destructive", ttl);
|
||||
if (id < 0) {
|
||||
/* fail closed, but say why: a silent "denied" sends people hunting */
|
||||
fprintf(stderr, "splinter: cannot file an approval request in %s "
|
||||
"(missing, not yours, or writable by others): %s denied\n",
|
||||
sp_ack_dir() != NULL ? sp_ack_dir() : "(no ack dir)", t->name);
|
||||
return 0;
|
||||
}
|
||||
if (sp_buf_init(&log) == 0) {
|
||||
(void)sp_ack_notify(id, &log);
|
||||
if (log.p != NULL && *log.p != '\0')
|
||||
fprintf(stderr, "%s", log.p);
|
||||
sp_buf_free(&log);
|
||||
}
|
||||
if (a->cfg->approval_out != NULL)
|
||||
fprintf(a->cfg->approval_out, sp_td("ack.prompt",
|
||||
"approval %d: %s %s (%ds) - 'splinter --ack %d yes' or y/N "
|
||||
"here: "), id, t->name, args, ttl, id);
|
||||
else
|
||||
fprintf(stderr, sp_td("ack.pending", "approval %d: %s %s (%ds)\n"),
|
||||
id, t->name, args, ttl);
|
||||
if (a->cfg->approval_out != NULL)
|
||||
fflush(a->cfg->approval_out);
|
||||
|
||||
/* the terminal is one more channel, not a special case */
|
||||
if (a->cfg->approval_in != NULL && pipe(stop) == 0) {
|
||||
at.id = id;
|
||||
at.in = a->cfg->approval_in;
|
||||
at.stop = stop[0];
|
||||
if (pthread_create(&th, NULL, ack_stdin_thread, &at) == 0)
|
||||
th_started = 1;
|
||||
}
|
||||
yes = sp_ack_wait(id, ttl, who, sizeof(who));
|
||||
if (th_started) {
|
||||
(void)write(stop[1], "x", 1);
|
||||
(void)pthread_join(th, NULL);
|
||||
}
|
||||
if (stop[0] >= 0) {
|
||||
close(stop[0]);
|
||||
close(stop[1]);
|
||||
}
|
||||
if (yes && who[0] != '\0')
|
||||
fprintf(stderr, sp_td("ack.approved_by",
|
||||
"splinter: approved by %s\n"), who);
|
||||
return yes;
|
||||
}
|
||||
|
||||
static int
|
||||
ask_operator(struct sp_agent *a, const struct sp_tool *t, const char *args)
|
||||
{
|
||||
char line[64];
|
||||
int verdict;
|
||||
|
||||
if (a->cfg->approve != NULL && a->cfg->approve_is_channel)
|
||||
return a->cfg->approve(a->cfg->approve_ctx, t->name, (int)t->auth,
|
||||
args);
|
||||
verdict = ack_approval(a, t, args);
|
||||
if (verdict >= 0)
|
||||
return verdict;
|
||||
|
||||
if (a->cfg->approve != NULL)
|
||||
return a->cfg->approve(a->cfg->approve_ctx, t->name, (int)t->auth,
|
||||
args);
|
||||
if (a->cfg->approval_out != NULL) {
|
||||
fprintf(a->cfg->approval_out, "run %s (%s) %s? [y/N] ", t->name,
|
||||
t->auth == SP_AUTH_MUTATE ? "mutate" : "destructive", args);
|
||||
fflush(a->cfg->approval_out);
|
||||
}
|
||||
if (a->cfg->approval_in == NULL)
|
||||
return 0; /* fail closed */
|
||||
if (fgets(line, sizeof(line), a->cfg->approval_in) == NULL)
|
||||
return 0;
|
||||
return (line[0] == 'y' || line[0] == 'Y');
|
||||
}
|
||||
|
||||
/* The observation is always written: an error is an observation too. */
|
||||
/*
|
||||
* 0 = ran (obs is the observation), 1 = a person has to decide first (nothing
|
||||
* ran). have_decision/decision are used by a resume: the decision applies to
|
||||
* the pending calls instead of asking again.
|
||||
*/
|
||||
/* a name against a comma list of names; a trailing '*' is a prefix */
|
||||
static int
|
||||
in_name_list(const char *list, const char *name)
|
||||
{
|
||||
char buf[512], *t, *save = NULL;
|
||||
|
||||
snprintf(buf, sizeof(buf), "%s", list);
|
||||
for (t = strtok_r(buf, ", ", &save); t != NULL;
|
||||
t = strtok_r(NULL, ", ", &save)) {
|
||||
size_t n = strlen(t);
|
||||
|
||||
if (n > 0 && t[n - 1] == '*') {
|
||||
if (strncmp(name, t, n - 1) == 0)
|
||||
return 1;
|
||||
} else if (strcmp(name, t) == 0)
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
policy_allows(const struct sp_tool_policy *p, const struct sp_tool *t)
|
||||
{
|
||||
if (p == NULL)
|
||||
return 1;
|
||||
if (in_name_list(p->deny, t->name))
|
||||
return 0;
|
||||
if (in_name_list(p->allow, t->name))
|
||||
return 1;
|
||||
return p->max_auth < 0 || (int)t->auth <= p->max_auth;
|
||||
}
|
||||
|
||||
static int
|
||||
run_one_call(struct sp_agent *a, const struct sp_toolcall *call,
|
||||
struct sp_buf *obs, int have_decision, int decision)
|
||||
{
|
||||
const struct sp_tool *t;
|
||||
int verdict;
|
||||
|
||||
a->stats.tool_calls++;
|
||||
t = sp_registry_find(a->reg, call->name);
|
||||
if (t == NULL) {
|
||||
sp_buf_printf(obs, "error: unknown tool '%s'", call->name);
|
||||
return 0;
|
||||
}
|
||||
if (!policy_allows(a->policy, t)) {
|
||||
a->stats.denied++;
|
||||
sp_buf_printf(obs, "denied: '%s' is not available in the '%s' "
|
||||
"agent (%s); ask the user to switch agent (Tab) or use a "
|
||||
"tool that is allowed", t->name, a->policy->name,
|
||||
a->policy->max_auth == 0 ? "read-only" : "restricted");
|
||||
return 0;
|
||||
}
|
||||
/*
|
||||
* A gate may decide before anybody else: a plugin's policy (kid mode, a
|
||||
* sandbox) can allow a call outright or refuse it with a reason. Only when
|
||||
* no gate has an opinion do the normal rules apply.
|
||||
*/
|
||||
if (a->host != NULL) {
|
||||
char reason[256];
|
||||
|
||||
verdict = sp_host_gate(a->host, t->name, (int)t->auth,
|
||||
call->args, reason, sizeof(reason));
|
||||
if (verdict == 0) {
|
||||
a->stats.denied++;
|
||||
sp_buf_printf(obs, "denied: %s", reason[0] != '\0' ?
|
||||
reason : "by policy");
|
||||
sp_logf("gate", "%s denied: %s", t->name, reason);
|
||||
return 0;
|
||||
}
|
||||
if (verdict == 1) {
|
||||
if (t->run(call->args, obs, t->ctx) != 0)
|
||||
sp_buf_printf(obs, "error: tool '%s' failed",
|
||||
call->name);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (t->auth != SP_AUTH_READ && !a->cfg->autonomous) {
|
||||
if (have_decision)
|
||||
verdict = decision ? 1 : 0;
|
||||
else {
|
||||
verdict = ask_operator(a, t, call->args);
|
||||
if (verdict == 2)
|
||||
return 1; /* pause; nothing has run */
|
||||
}
|
||||
if (!verdict) {
|
||||
a->stats.denied++;
|
||||
sp_buf_puts(obs, "error: denied by operator");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if (t->run(call->args, obs, t->ctx) != 0)
|
||||
sp_buf_printf(obs, "error: tool '%s' failed", call->name);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* run one call and add its observation; 1 means approval is still required */
|
||||
static int
|
||||
run_one(struct sp_agent *a, struct sp_conv *conv,
|
||||
const struct sp_toolcall *call, int have_decision, int decision,
|
||||
struct sp_buf *obs, struct sp_buf *err)
|
||||
{
|
||||
struct sp_msg tm;
|
||||
int rc;
|
||||
|
||||
sp_buf_clear(obs);
|
||||
sp_logf("tool", "%s %s", call->name,
|
||||
call->args != NULL ? call->args : "");
|
||||
if (a->cfg->tool_begin != NULL)
|
||||
a->cfg->tool_begin(a->cfg->tool_begin_ctx, call->name,
|
||||
call->args);
|
||||
rc = run_one_call(a, call, obs, have_decision, decision);
|
||||
if (rc != 0)
|
||||
return rc;
|
||||
if (a->cfg->tool_end != NULL)
|
||||
a->cfg->tool_end(a->cfg->tool_end_ctx, call->name,
|
||||
obs->p != NULL ? obs->p : "");
|
||||
sp_logf("observation", "%s", obs->p != NULL ? obs->p : "");
|
||||
if (obs->p != NULL && strncmp(obs->p, "error", 5) == 0)
|
||||
sp_logf("tool failed", "%s: %s", call->name, obs->p);
|
||||
memset(&tm, 0, sizeof(tm));
|
||||
tm.role = "tool";
|
||||
tm.name = call->name;
|
||||
tm.call_id = call->id;
|
||||
tm.content = obs->p;
|
||||
if (sp_conv_add(conv, &tm) != 0) {
|
||||
sp_buf_puts(err, "agent: out of memory");
|
||||
return -1;
|
||||
}
|
||||
if (a->sess != NULL &&
|
||||
sp_session_append(a->sess, "observation", obs->p, err) != 0)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The waiter for callers without a screen (-p, the daemon, the servers): say
|
||||
* when the run goes on and sleep until then. 'ctx' points at the longest wait
|
||||
* in seconds; a longer one fails the turn instead, so a limit that lifts next
|
||||
* week does not hold a process for a week.
|
||||
*/
|
||||
int
|
||||
sp_limit_wait_default(void *ctx, long until, const char *why)
|
||||
{
|
||||
const long *maxw = ctx;
|
||||
long now = (long)time(NULL), cap = maxw != NULL &&
|
||||
*maxw > 0 ? *maxw : 12 * 3600;
|
||||
char when[32];
|
||||
struct tm tm;
|
||||
time_t tt = (time_t)until;
|
||||
|
||||
if (until - now > cap)
|
||||
return 0;
|
||||
strftime(when, sizeof(when), "%Y-%m-%d %H:%M", localtime_r(&tt, &tm));
|
||||
fprintf(stderr, "splinter: usage limit reached (%.80s); continuing at %s\n",
|
||||
why != NULL ? why : "", when);
|
||||
while ((long)time(NULL) < until)
|
||||
sleep(1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* A request ran into a usage limit. When the caller can wait, find out when the
|
||||
* limit lifts -- from the status and Retry-After, from "ready_at=", or from the
|
||||
* reset the provider named in its message -- bench the provider until then,
|
||||
* wait, and tell the loop to ask again. 0: not a limit, or not waiting.
|
||||
*/
|
||||
static int
|
||||
limit_retry(struct sp_agent *a, struct sp_buf *err, long status,
|
||||
long retry_after, long ready_at, int *tries)
|
||||
{
|
||||
long now = (long)time(NULL), until = 0;
|
||||
const char *e = err != NULL && err->p != NULL ? err->p : "";
|
||||
|
||||
if ((a->cfg->limit_wait == NULL && a->cfg->limit_switch == NULL) ||
|
||||
*tries >= 50)
|
||||
return 0;
|
||||
if (ready_at > now)
|
||||
until = ready_at;
|
||||
else if (status == 429 || status == 402 || status == 529)
|
||||
until = now + (retry_after > 0 ? retry_after :
|
||||
(status == 529 ? 120 : 60));
|
||||
else if (!sp_limit_parse(e, &until)) {
|
||||
const char *r = strstr(e, "ready_at=");
|
||||
|
||||
until = r != NULL ? strtol(r + 9, NULL, 10) : 0;
|
||||
} else if (strstr(e, "ready_at=") != NULL)
|
||||
until = strtol(strstr(e, "ready_at=") + 9, NULL, 10);
|
||||
if (until <= now)
|
||||
return 0;
|
||||
sp_cooldown_set(sp_usage_active(), until, e);
|
||||
if (a->cfg->limit_switch != NULL &&
|
||||
a->cfg->limit_switch(a->cfg->switch_ctx)) {
|
||||
if (err != NULL)
|
||||
sp_buf_clear(err);
|
||||
return 1;
|
||||
}
|
||||
(*tries)++;
|
||||
if (a->cfg->limit_wait == NULL ||
|
||||
!a->cfg->limit_wait(a->cfg->limit_ctx, until, e))
|
||||
return 0;
|
||||
if (err != NULL)
|
||||
sp_buf_clear(err);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int
|
||||
agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision,
|
||||
struct sp_buf *answer, struct sp_buf *err)
|
||||
{
|
||||
struct sp_buf obs;
|
||||
size_t step, i;
|
||||
int rc = -1, limit_tries = 0;
|
||||
|
||||
if (sp_buf_init(&obs) != 0) {
|
||||
sp_buf_puts(err, "agent: out of memory");
|
||||
return -1;
|
||||
}
|
||||
if (resume) {
|
||||
if (!a->has_pending || a->pending_from > a->pending.ncalls) {
|
||||
sp_buf_puts(err, "agent: no turn is waiting for input");
|
||||
goto out;
|
||||
}
|
||||
for (i = a->pending_from; i < a->pending.ncalls; i++) {
|
||||
int r = run_one(a, conv, &a->pending.calls[i], 1,
|
||||
decision, &obs, err);
|
||||
|
||||
if (r != 0) {
|
||||
if (r > 0)
|
||||
sp_buf_puts(err, "agent: approval "
|
||||
"needed again");
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
sp_reply_free(&a->pending);
|
||||
a->has_pending = 0;
|
||||
a->pending_from = 0;
|
||||
}
|
||||
/*
|
||||
* max_steps counts tool rounds, not requests: a turn with N tool rounds
|
||||
* needs N+1 requests, because the last one carries the answer and runs
|
||||
* no tool. Counting requests against max_steps therefore refused the
|
||||
* answer of a turn that had spent exactly its budget and ended in
|
||||
* "step limit (8) reached without an answer" after eight rounds.
|
||||
* So 'step' keeps counting requests (it is also what a quota wait
|
||||
* rewinds), and the budget is judged by the guard below, which lets one
|
||||
* request past the last round - the one that may answer.
|
||||
*/
|
||||
for (step = 0; ; step++) {
|
||||
struct sp_reply reply;
|
||||
size_t sent;
|
||||
|
||||
memset(&reply, 0, sizeof(reply));
|
||||
if (a->cfg->cancel != NULL && *a->cfg->cancel) {
|
||||
sp_buf_puts(err, "agent: cancelled by operator");
|
||||
goto out;
|
||||
}
|
||||
if (a->cfg->steer != NULL) {
|
||||
struct sp_buf steer;
|
||||
|
||||
if (sp_buf_init(&steer) != 0)
|
||||
goto oom;
|
||||
if (a->cfg->steer(a->cfg->steer_ctx, &steer) > 0 &&
|
||||
steer.len > 0) {
|
||||
if (sp_conv_push(conv, "user", NULL, steer.p) != 0) {
|
||||
sp_buf_free(&steer);
|
||||
goto oom;
|
||||
}
|
||||
if (a->sess != NULL)
|
||||
(void)sp_session_append(a->sess, "user",
|
||||
steer.p, err);
|
||||
}
|
||||
sp_buf_free(&steer);
|
||||
}
|
||||
/* compaction happens before the budget is judged, never after */
|
||||
if (a->host != NULL) {
|
||||
size_t cb = sp_conv_bytes(conv), cn = conv->n;
|
||||
|
||||
if (sp_host_compact(a->host, conv, a->cfg->max_bytes) > 0) {
|
||||
a->stats.compactions++;
|
||||
if (a->cfg != NULL && a->cfg->on_compact != NULL)
|
||||
a->cfg->on_compact(a->cfg->on_compact_ctx,
|
||||
cb, sp_conv_bytes(conv), cn, conv->n);
|
||||
}
|
||||
}
|
||||
sent = sp_conv_bytes(conv);
|
||||
if (a->cfg->max_bytes > 0 && sent > a->cfg->max_bytes) {
|
||||
sp_buf_printf(err, "agent: conversation budget exceeded "
|
||||
"(~%zu > %zu bytes); nothing sent", sent,
|
||||
a->cfg->max_bytes);
|
||||
goto out;
|
||||
}
|
||||
a->stats.bytes_sent += sent;
|
||||
a->stats.steps++;
|
||||
|
||||
{
|
||||
struct sp_prov_result pr;
|
||||
enum sp_prov_decision pd;
|
||||
|
||||
pd = sp_host_provider_preflight(a->host, a->tr.provider,
|
||||
a->tr.key_id, &pr);
|
||||
if (pd == SP_PROV_WAIT_QUOTA || pd == SP_PROV_DENY) {
|
||||
sp_buf_printf(err,
|
||||
"provider quota/policy: %s (ready_at=%ld retry_after=%lds)",
|
||||
pr.reason[0] ? pr.reason : "denied",
|
||||
pr.ready_at, pr.retry_after_s);
|
||||
if (pd == SP_PROV_WAIT_QUOTA &&
|
||||
limit_retry(a, err, 0, 0, pr.ready_at,
|
||||
&limit_tries)) {
|
||||
a->stats.steps--;
|
||||
step--;
|
||||
continue;
|
||||
}
|
||||
goto out;
|
||||
}
|
||||
if (pd == SP_PROV_DELAY && pr.retry_after_s > 0) {
|
||||
if (pr.retry_after_s <= 30)
|
||||
sleep((unsigned)pr.retry_after_s);
|
||||
else {
|
||||
sp_buf_printf(err,
|
||||
"provider quota/policy: %s (ready_at=%ld retry_after=%lds)",
|
||||
pr.reason[0] ? pr.reason : "delay",
|
||||
pr.ready_at, pr.retry_after_s);
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
int sent_rc;
|
||||
|
||||
if (a->cfg->stream != NULL &&
|
||||
a->tr.send_stream != NULL)
|
||||
sent_rc = a->tr.send_stream(a->tr.ctx, conv,
|
||||
&reply, err, a->cfg->stream,
|
||||
a->cfg->stream_ctx);
|
||||
else
|
||||
sent_rc = a->tr.send(a->tr.ctx, conv, &reply,
|
||||
err);
|
||||
if (sent_rc != 0) {
|
||||
sp_host_provider_account(a->host, a->tr.provider,
|
||||
a->tr.key_id, reply.status, 0, 0);
|
||||
if (limit_retry(a, err, reply.status,
|
||||
reply.retry_after_s, 0, &limit_tries)) {
|
||||
sp_reply_free(&reply);
|
||||
a->stats.steps--;
|
||||
step--;
|
||||
continue;
|
||||
}
|
||||
sp_reply_free(&reply);
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
if (reply.status < 200 || reply.status > 299) {
|
||||
sp_host_provider_account(a->host, a->tr.provider,
|
||||
a->tr.key_id, reply.status,
|
||||
(size_t)(reply.tokens_in > 0 ? reply.tokens_in : 0),
|
||||
(size_t)(reply.tokens_out > 0 ? reply.tokens_out : 0));
|
||||
quota_hint(a->tr.provider, a->tr.key_id, reply.status, reply.retry_after_s);
|
||||
/* a refused call benches the provider the run is on */
|
||||
if (reply.status == 429 || reply.status == 402 ||
|
||||
reply.status == 529)
|
||||
sp_cooldown_set(sp_usage_active(),
|
||||
(long)time(NULL) + (reply.retry_after_s > 0 ?
|
||||
reply.retry_after_s : 300), "refused (HTTP limit)");
|
||||
sp_buf_printf(err, "agent: transport status %ld",
|
||||
reply.status);
|
||||
if (limit_retry(a, err, reply.status, reply.retry_after_s,
|
||||
0, &limit_tries)) {
|
||||
sp_reply_free(&reply);
|
||||
a->stats.steps--;
|
||||
step--;
|
||||
continue;
|
||||
}
|
||||
sp_reply_free(&reply);
|
||||
goto out;
|
||||
}
|
||||
|
||||
sp_usage_record(sp_usage_active(), reply.tokens_in,
|
||||
reply.tokens_out);
|
||||
a->stats.tokens_in += (size_t)(reply.tokens_in > 0 ?
|
||||
reply.tokens_in : 0);
|
||||
a->stats.tokens_out += (size_t)(reply.tokens_out > 0 ?
|
||||
reply.tokens_out : 0);
|
||||
sp_host_provider_account(a->host, a->tr.provider, a->tr.key_id,
|
||||
reply.status,
|
||||
(size_t)(reply.tokens_in > 0 ? reply.tokens_in : 0),
|
||||
(size_t)(reply.tokens_out > 0 ? reply.tokens_out : 0));
|
||||
|
||||
if (reply.ncalls == 0) {
|
||||
const char *text = reply.content != NULL ?
|
||||
reply.content : "";
|
||||
|
||||
if (sp_buf_puts(answer, text) != 0 ||
|
||||
sp_conv_push(conv, "assistant", NULL, text) != 0) {
|
||||
sp_reply_free(&reply);
|
||||
goto oom;
|
||||
}
|
||||
if (a->sess != NULL &&
|
||||
sp_session_append(a->sess, "assistant", text,
|
||||
err) != 0) {
|
||||
sp_reply_free(&reply);
|
||||
goto out;
|
||||
}
|
||||
sp_reply_free(&reply);
|
||||
rc = 0;
|
||||
goto out;
|
||||
}
|
||||
|
||||
/*
|
||||
* The reply asks for a tool round. 'step' requests have been sent
|
||||
* so far, the first max_steps of which were allowed to run one
|
||||
* round each; when the budget is spent this one may not open
|
||||
* another. It is refused before the assistant message and its
|
||||
* calls enter the conversation, so the turn ends on the last
|
||||
* complete round instead of on a call with no observation.
|
||||
*/
|
||||
if (step >= a->cfg->max_steps) {
|
||||
sp_reply_free(&reply);
|
||||
sp_buf_printf(err,
|
||||
"agent: step limit (%zu) reached without an answer",
|
||||
a->cfg->max_steps);
|
||||
goto out;
|
||||
}
|
||||
|
||||
{
|
||||
struct sp_msg am;
|
||||
|
||||
memset(&am, 0, sizeof(am));
|
||||
am.role = "assistant";
|
||||
am.content = reply.content;
|
||||
am.calls = reply.calls_json;
|
||||
if (sp_conv_add(conv, &am) != 0) {
|
||||
sp_reply_free(&reply);
|
||||
goto oom;
|
||||
}
|
||||
}
|
||||
for (i = 0; i < reply.ncalls; i++) {
|
||||
int r = run_one(a, conv, &reply.calls[i], 0, 0, &obs,
|
||||
err);
|
||||
|
||||
if (r == 1) {
|
||||
/*
|
||||
* Pause with the assistant message already in the
|
||||
* conversation; the calls from here on have no
|
||||
* observation yet. The next run resumes them.
|
||||
*/
|
||||
a->pending = reply;
|
||||
memset(&reply, 0, sizeof(reply));
|
||||
a->pending_from = i;
|
||||
a->has_pending = 1;
|
||||
rc = SP_AGENT_INPUT_REQUIRED;
|
||||
goto out;
|
||||
}
|
||||
if (r != 0) {
|
||||
sp_reply_free(&reply);
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
sp_reply_free(&reply);
|
||||
}
|
||||
|
||||
oom:
|
||||
sp_buf_puts(err, "agent: out of memory");
|
||||
out:
|
||||
sp_buf_free(&obs);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int
|
||||
sp_agent_run(struct sp_agent *a, const char *user_text, struct sp_buf *answer,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
struct sp_conv local;
|
||||
struct sp_conv *conv;
|
||||
int rc;
|
||||
|
||||
if (a == NULL || a->reg == NULL || a->cfg == NULL)
|
||||
return -1;
|
||||
if (a->cfg->max_steps == 0)
|
||||
return -1;
|
||||
if (a->has_pending) {
|
||||
sp_buf_puts(err, "agent: a turn is waiting for input");
|
||||
return -1;
|
||||
}
|
||||
if (a->conv != NULL) {
|
||||
conv = a->conv;
|
||||
} else {
|
||||
sp_conv_init(&local);
|
||||
conv = &local;
|
||||
}
|
||||
sp_buf_clear(answer);
|
||||
/*
|
||||
* A turn gate runs before the model does. Kid mode ends the day here: the
|
||||
* child gets a sentence, the model gets nothing to answer.
|
||||
*/
|
||||
if (a->host != NULL) {
|
||||
char msg[256];
|
||||
|
||||
msg[0] = '\0';
|
||||
if (sp_host_turn_blocked(a->host, msg, sizeof(msg))) {
|
||||
sp_buf_puts(answer, msg[0] != '\0' ? msg :
|
||||
"today is over");
|
||||
if (conv == &local)
|
||||
sp_conv_free(&local);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
sp_host_turn(a->host);
|
||||
if (sp_conv_push(conv, "user", NULL, user_text) != 0) {
|
||||
sp_buf_puts(err, "agent: out of memory");
|
||||
if (conv == &local)
|
||||
sp_conv_free(&local);
|
||||
return -1;
|
||||
}
|
||||
if (a->sess != NULL &&
|
||||
sp_session_append(a->sess, "user", user_text, err) != 0) {
|
||||
if (conv == &local)
|
||||
sp_conv_free(&local);
|
||||
return -1;
|
||||
}
|
||||
rc = agent_loop(a, conv, 0, 0, answer, err);
|
||||
if (rc == SP_AGENT_INPUT_REQUIRED && conv == &local) {
|
||||
/* nowhere to resume from: do not leave a dangling pending turn */
|
||||
sp_reply_free(&a->pending);
|
||||
a->has_pending = 0;
|
||||
a->pending_from = 0;
|
||||
sp_buf_puts(err, "agent: input required without a persistent "
|
||||
"conversation");
|
||||
rc = -1;
|
||||
}
|
||||
if (conv == &local)
|
||||
sp_conv_free(&local);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int
|
||||
sp_agent_resume(struct sp_agent *a, int decision, struct sp_buf *answer,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
if (a == NULL || a->cfg == NULL || a->conv == NULL || !a->has_pending) {
|
||||
sp_buf_puts(err, "agent: no turn is waiting for input");
|
||||
return -1;
|
||||
}
|
||||
sp_buf_clear(answer);
|
||||
return agent_loop(a, a->conv, 1, decision ? 1 : 0, answer, err);
|
||||
}
|
||||
@@ -91,9 +91,6 @@ static struct a2a_ctx g_ctx[A2A_CONTEXTS];
|
||||
static unsigned g_seq;
|
||||
static unsigned g_ctx_seq;
|
||||
static unsigned long g_clock;
|
||||
static char g_ir_task[64]; /* task waiting for a decision */
|
||||
static char g_ir_context[128];
|
||||
static char g_ir_msg[512];
|
||||
static volatile int g_stop;
|
||||
|
||||
static void
|
||||
@@ -226,49 +223,34 @@ read_request(int fd, char *hdr, size_t cap, struct sp_buf *body)
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* the id member as it appeared: a string, a number, or null */
|
||||
/*
|
||||
* The request's top-level id as JSON: a string (escaped), a number, or ""
|
||||
* when there is none, which the replies write as null.
|
||||
*/
|
||||
static void
|
||||
json_id(const char *payload, char *out, size_t cap)
|
||||
json_id(const mcp_json *req, char *out, size_t cap)
|
||||
{
|
||||
const char *p;
|
||||
const mcp_json *id = mcp_arg(req, "id");
|
||||
struct sp_buf b;
|
||||
|
||||
out[0] = '\0';
|
||||
p = payload != NULL ? strstr(payload, "\"id\"") : NULL;
|
||||
if (p == NULL)
|
||||
if (id == NULL)
|
||||
return;
|
||||
p = strchr(p + 4, ':');
|
||||
if (p == NULL)
|
||||
if (id->t == MCP_NUM) {
|
||||
if (id->n == (double)(long long)id->n)
|
||||
snprintf(out, cap, "%lld", (long long)id->n);
|
||||
else
|
||||
snprintf(out, cap, "%.17g", id->n);
|
||||
return;
|
||||
p++;
|
||||
while (*p == ' ' || *p == '\t')
|
||||
p++;
|
||||
if (*p == '"') {
|
||||
const char *start = p;
|
||||
size_t n;
|
||||
|
||||
p++;
|
||||
while (*p != '\0' && *p != '"') {
|
||||
if (*p == '\\' && p[1] != '\0')
|
||||
p++;
|
||||
p++;
|
||||
}
|
||||
if (*p == '"')
|
||||
p++;
|
||||
n = (size_t)(p - start);
|
||||
if (n >= cap)
|
||||
n = cap - 1;
|
||||
memcpy(out, start, n);
|
||||
out[n] = '\0';
|
||||
} else {
|
||||
size_t n = 0;
|
||||
|
||||
while (p[n] != '\0' && p[n] != ',' && p[n] != '}' &&
|
||||
!isspace((unsigned char)p[n]) && n + 1 < cap) {
|
||||
out[n] = p[n];
|
||||
n++;
|
||||
}
|
||||
out[n] = '\0';
|
||||
}
|
||||
if (id->t != MCP_STR || id->s == NULL || sp_buf_init(&b) != 0)
|
||||
return;
|
||||
sp_buf_puts(&b, "\"");
|
||||
sp_json_escape(&b, id->s);
|
||||
sp_buf_puts(&b, "\"");
|
||||
if (b.p != NULL && b.len < cap)
|
||||
snprintf(out, cap, "%s", b.p);
|
||||
sp_buf_free(&b);
|
||||
}
|
||||
|
||||
static int url_host_allowed(const char *url);
|
||||
@@ -560,35 +542,6 @@ task_store(const char *context, const struct sp_buf *answer)
|
||||
return task_store_id(NULL, context, answer);
|
||||
}
|
||||
|
||||
static void
|
||||
task_update(struct a2a_task *t, const char *state, const struct sp_buf *answer)
|
||||
{
|
||||
snprintf(t->state, sizeof(t->state), "%s", state);
|
||||
sp_buf_clear(&t->answer);
|
||||
if (answer != NULL && answer->p != NULL)
|
||||
(void)sp_buf_add(&t->answer, answer->p, answer->len);
|
||||
}
|
||||
|
||||
static struct a2a_task *
|
||||
task_store_state(const char *id, const char *context, const char *state,
|
||||
const char *message)
|
||||
{
|
||||
struct sp_buf empty;
|
||||
struct a2a_task *t;
|
||||
|
||||
if (sp_buf_init(&empty) != 0)
|
||||
return NULL;
|
||||
t = task_store_id(id, context, &empty);
|
||||
sp_buf_free(&empty);
|
||||
if (t != NULL) {
|
||||
snprintf(t->state, sizeof(t->state), "%s", state);
|
||||
sp_buf_clear(&t->answer);
|
||||
if (message != NULL)
|
||||
(void)sp_buf_puts(&t->answer, message);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
static struct a2a_ctx *
|
||||
ctx_get(struct sp_agent *ag, const char *id, int create)
|
||||
{
|
||||
@@ -632,17 +585,29 @@ ctx_get(struct sp_agent *ag, const char *id, int create)
|
||||
}
|
||||
}
|
||||
|
||||
/* "<idkey>":"<task>","contextId":"<ctx>", both escaped: they are the client's */
|
||||
static void
|
||||
put_ids(struct sp_buf *b, const char *idkey, const char *task, const char *ctx)
|
||||
{
|
||||
sp_buf_printf(b, "\"%s\":\"", idkey);
|
||||
sp_json_escape(b, task);
|
||||
sp_buf_puts(b, "\",\"contextId\":\"");
|
||||
sp_json_escape(b, ctx);
|
||||
sp_buf_puts(b, "\"");
|
||||
}
|
||||
|
||||
static void
|
||||
task_obj(struct sp_buf *b, const struct a2a_task *t)
|
||||
{
|
||||
int completed = strcmp(t->state, "TASK_STATE_COMPLETED") == 0;
|
||||
|
||||
sp_buf_puts(b, "{\"id\":\"");
|
||||
sp_buf_puts(b, t->id);
|
||||
sp_buf_printf(b, "\",\"contextId\":\"%s\",\"status\":{\"state\":\"%s\","
|
||||
"\"message\":{\"messageId\":\"msg-%s\","
|
||||
"\"role\":\"ROLE_AGENT\",\"parts\":[{\"text\":\"", t->context,
|
||||
t->state[0] != '\0' ? t->state : "TASK_STATE_COMPLETED", t->id);
|
||||
sp_buf_puts(b, "{");
|
||||
put_ids(b, "id", t->id, t->context);
|
||||
sp_buf_printf(b, ",\"status\":{\"state\":\"%s\","
|
||||
"\"message\":{\"messageId\":\"msg-",
|
||||
t->state[0] != '\0' ? t->state : "TASK_STATE_COMPLETED");
|
||||
sp_json_escape(b, t->id);
|
||||
sp_buf_puts(b, "\",\"role\":\"ROLE_AGENT\",\"parts\":[{\"text\":\"");
|
||||
sp_json_escape(b, t->answer.p);
|
||||
sp_buf_puts(b, "\"}]}}");
|
||||
if (!completed) {
|
||||
@@ -650,7 +615,7 @@ task_obj(struct sp_buf *b, const struct a2a_task *t)
|
||||
return;
|
||||
}
|
||||
sp_buf_puts(b, ",\"artifacts\":[{\"artifactId\":\"a-");
|
||||
sp_buf_puts(b, t->id);
|
||||
sp_json_escape(b, t->id);
|
||||
sp_buf_puts(b, "\",\"parts\":[{\"text\":\"");
|
||||
sp_json_escape(b, t->answer.p);
|
||||
sp_buf_puts(b, "\"}]}]}");
|
||||
@@ -685,6 +650,14 @@ host_allowed(const char *url, const char *envname)
|
||||
return 0;
|
||||
p = strstr(url, "://");
|
||||
host = p + 3;
|
||||
/*
|
||||
* userinfo (http://localhost:x@169.254.169.254/) would make the host
|
||||
* read here differ from the one curl connects to: refuse it, and a
|
||||
* backslash in the authority, which some parsers take for a '/'.
|
||||
*/
|
||||
n = strcspn(host, "/?#");
|
||||
if (memchr(host, '@', n) != NULL || memchr(host, '\\', n) != NULL)
|
||||
return 0;
|
||||
if (*host == '[') {
|
||||
host++;
|
||||
end = strchr(host, ']');
|
||||
@@ -735,7 +708,8 @@ fetch_url_text(const char *url, struct sp_buf *out)
|
||||
struct sp_buf raw, err;
|
||||
pid_t pid = -1;
|
||||
char chunk[4096], *nl;
|
||||
size_t got;
|
||||
ssize_t got;
|
||||
size_t i;
|
||||
int fd, status = 0;
|
||||
long http;
|
||||
|
||||
@@ -750,14 +724,14 @@ fetch_url_text(const char *url, struct sp_buf *out)
|
||||
fd = sp_curl_start(args, url, NULL, 1, &pid, &err);
|
||||
if (fd < 0)
|
||||
goto fail;
|
||||
while ((got = read(fd, chunk, sizeof(chunk))) > 0) {
|
||||
if (raw.len + got > (1u << 20)) {
|
||||
close(fd);
|
||||
(void)kill(pid, SIGKILL);
|
||||
(void)waitpid(pid, NULL, 0);
|
||||
goto fail;
|
||||
}
|
||||
if (sp_buf_add(&raw, chunk, got) != 0) {
|
||||
for (;;) {
|
||||
got = read(fd, chunk, sizeof(chunk));
|
||||
if (got < 0 && errno == EINTR)
|
||||
continue;
|
||||
if (got == 0)
|
||||
break;
|
||||
if (got < 0 || raw.len + (size_t)got > (1u << 20) ||
|
||||
sp_buf_add(&raw, chunk, (size_t)got) != 0) {
|
||||
close(fd);
|
||||
(void)kill(pid, SIGKILL);
|
||||
(void)waitpid(pid, NULL, 0);
|
||||
@@ -768,13 +742,21 @@ fetch_url_text(const char *url, struct sp_buf *out)
|
||||
if (waitpid(pid, &status, 0) < 0 || !WIFEXITED(status) ||
|
||||
WEXITSTATUS(status) != 0)
|
||||
goto fail;
|
||||
if (raw.len < 2 || (nl = strrchr(raw.p, '\n')) == NULL)
|
||||
/* the body may hold NULs: find the status line by length, not strrchr */
|
||||
nl = NULL;
|
||||
for (i = raw.len; i > 0; i--)
|
||||
if (raw.p[i - 1] == '\n') {
|
||||
nl = raw.p + i - 1;
|
||||
break;
|
||||
}
|
||||
if (raw.len < 2 || nl == NULL)
|
||||
goto fail;
|
||||
http = strtol(nl + 1, NULL, 10);
|
||||
*nl = '\0';
|
||||
if (http < 200 || http > 299)
|
||||
goto fail;
|
||||
sp_buf_puts(out, raw.p);
|
||||
if (sp_buf_add(out, raw.p, (size_t)(nl - raw.p)) != 0)
|
||||
goto fail;
|
||||
sp_buf_free(&raw);
|
||||
sp_buf_free(&err);
|
||||
return 0;
|
||||
@@ -1040,30 +1022,13 @@ rpc_result(int fd, const char *id, const char *result)
|
||||
* One turn in its own conversation: the system prompt plus this caller's text.
|
||||
* The shared conversation from --chat would let one remote agent read another's
|
||||
* history.
|
||||
*
|
||||
* No approval callback: an A2A caller is not sitting in front of a prompt, and
|
||||
* splinter does not gate its own tools. The registry and the agent's policy say
|
||||
* what may run.
|
||||
*/
|
||||
static int
|
||||
a2a_approve(void *ctx, const char *name, int auth, const char *args)
|
||||
{
|
||||
(void)ctx;
|
||||
(void)auth;
|
||||
snprintf(g_ir_msg, sizeof(g_ir_msg), "approval required: %s %s",
|
||||
name, args != NULL ? args : "");
|
||||
return 2; /* pause; the task becomes INPUT_REQUIRED */
|
||||
}
|
||||
|
||||
static int
|
||||
a2a_deny(void *ctx, const char *name, int auth, const char *args)
|
||||
{
|
||||
(void)ctx;
|
||||
(void)name;
|
||||
(void)auth;
|
||||
(void)args;
|
||||
return 0; /* streaming has nowhere to resume from */
|
||||
}
|
||||
|
||||
static int
|
||||
run_turn(struct sp_agent *ag, struct sp_conv *conv, const char *text,
|
||||
int (*approve)(void *, const char *, int, const char *),
|
||||
turn_with(struct sp_agent *ag, struct sp_conv *conv, const char *text,
|
||||
struct sp_buf *answer, struct sp_buf *err)
|
||||
{
|
||||
struct sp_agent_config cfg;
|
||||
@@ -1076,9 +1041,6 @@ run_turn(struct sp_agent *ag, struct sp_conv *conv, const char *text,
|
||||
return -1;
|
||||
}
|
||||
cfg = *ag->cfg;
|
||||
cfg.approve = approve;
|
||||
cfg.approve_ctx = NULL;
|
||||
cfg.approve_is_channel = 1;
|
||||
savedcfg = ag->cfg;
|
||||
savedconv = ag->conv;
|
||||
ag->cfg = &cfg;
|
||||
@@ -1090,39 +1052,10 @@ run_turn(struct sp_agent *ag, struct sp_conv *conv, const char *text,
|
||||
}
|
||||
|
||||
static int
|
||||
resume_turn(struct sp_agent *ag, struct sp_conv *conv, int decision,
|
||||
run_turn(struct sp_agent *ag, struct sp_conv *conv, const char *text,
|
||||
struct sp_buf *answer, struct sp_buf *err)
|
||||
{
|
||||
struct sp_conv *saved;
|
||||
int rc;
|
||||
|
||||
saved = ag->conv;
|
||||
ag->conv = conv;
|
||||
rc = sp_agent_resume(ag, decision, answer, err);
|
||||
ag->conv = saved;
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* yes/ok/ja/sim -> 1, no/nein/nao -> 0, anything else -> -1 */
|
||||
static int
|
||||
decision_of(const char *text)
|
||||
{
|
||||
if (text == NULL)
|
||||
return -1;
|
||||
while (*text == ' ' || *text == '\t')
|
||||
text++;
|
||||
if (strncasecmp(text, "yes", 3) == 0 ||
|
||||
strncasecmp(text, "ja", 2) == 0 ||
|
||||
strncasecmp(text, "ok", 2) == 0 ||
|
||||
strncasecmp(text, "sim", 3) == 0 ||
|
||||
(text[0] == 'y' && (text[1] == '\0' || text[1] == ' ')))
|
||||
return 1;
|
||||
if (strncasecmp(text, "nein", 4) == 0 ||
|
||||
strncasecmp(text, "no", 2) == 0 ||
|
||||
strncasecmp(text, "nao", 3) == 0 ||
|
||||
(text[0] == 'n' && (text[1] == '\0' || text[1] == ' ')))
|
||||
return 0;
|
||||
return -1;
|
||||
return turn_with(ag, conv, text != NULL ? text : "", answer, err);
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -1175,8 +1108,9 @@ sse_task(struct sse_out *o, const char *state)
|
||||
|
||||
if (sp_buf_init(&b) != 0)
|
||||
return;
|
||||
sp_buf_printf(&b, "{\"task\":{\"id\":\"%s\",\"contextId\":\"%s\","
|
||||
"\"status\":{\"state\":\"%s\"}}}", o->task_id, o->context, state);
|
||||
sp_buf_puts(&b, "{\"task\":{");
|
||||
put_ids(&b, "id", o->task_id, o->context);
|
||||
sp_buf_printf(&b, ",\"status\":{\"state\":\"%s\"}}}", state);
|
||||
sse_write(o, b.p);
|
||||
sp_buf_free(&b);
|
||||
}
|
||||
@@ -1188,9 +1122,10 @@ sse_artifact(struct sse_out *o, const char *text)
|
||||
|
||||
if (sp_buf_init(&b) != 0)
|
||||
return;
|
||||
sp_buf_printf(&b, "{\"artifactUpdate\":{\"taskId\":\"%s\","
|
||||
"\"contextId\":\"%s\",\"artifact\":{\"artifactId\":\"answer\","
|
||||
"\"parts\":[{\"text\":\"", o->task_id, o->context);
|
||||
sp_buf_puts(&b, "{\"artifactUpdate\":{");
|
||||
put_ids(&b, "taskId", o->task_id, o->context);
|
||||
sp_buf_puts(&b, ",\"artifact\":{\"artifactId\":\"answer\","
|
||||
"\"parts\":[{\"text\":\"");
|
||||
sp_json_escape(&b, text);
|
||||
sp_buf_puts(&b, "\"}]},\"append\":true}}");
|
||||
sse_write(o, b.p);
|
||||
@@ -1205,9 +1140,9 @@ sse_status(struct sse_out *o, const char *state)
|
||||
|
||||
if (sp_buf_init(&b) != 0)
|
||||
return;
|
||||
sp_buf_printf(&b, "{\"statusUpdate\":{\"taskId\":\"%s\","
|
||||
"\"contextId\":\"%s\",\"status\":{\"state\":\"%s\"}}}",
|
||||
o->task_id, o->context, state);
|
||||
sp_buf_puts(&b, "{\"statusUpdate\":{");
|
||||
put_ids(&b, "taskId", o->task_id, o->context);
|
||||
sp_buf_printf(&b, ",\"status\":{\"state\":\"%s\"}}}", state);
|
||||
sse_write(o, b.p);
|
||||
sp_buf_free(&b);
|
||||
}
|
||||
@@ -1219,12 +1154,12 @@ sse_status_full(struct sse_out *o, const char *state, const char *message)
|
||||
|
||||
if (sp_buf_init(&b) != 0)
|
||||
return;
|
||||
sp_buf_printf(&b, "{\"statusUpdate\":{\"taskId\":\"%s\","
|
||||
"\"contextId\":\"%s\",\"status\":{\"state\":\"%s\"",
|
||||
o->task_id, o->context, state);
|
||||
sp_buf_puts(&b, "{\"statusUpdate\":{");
|
||||
put_ids(&b, "taskId", o->task_id, o->context);
|
||||
sp_buf_printf(&b, ",\"status\":{\"state\":\"%s\"", state);
|
||||
if (message != NULL && *message != '\0') {
|
||||
sp_buf_puts(&b, ",\"message\":{\"messageId\":\"msg-");
|
||||
sp_buf_puts(&b, o->task_id);
|
||||
sp_json_escape(&b, o->task_id);
|
||||
sp_buf_puts(&b, "\",\"role\":\"ROLE_AGENT\",\"parts\":"
|
||||
"[{\"text\":\"");
|
||||
sp_json_escape(&b, message);
|
||||
@@ -1324,11 +1259,6 @@ handle_stream(int fd, struct sp_agent *ag, const char *id,
|
||||
return;
|
||||
}
|
||||
sse_start(fd);
|
||||
if (g_ir_task[0] != '\0') {
|
||||
sse_error(&o, -32004, "a task is waiting for input; use "
|
||||
"SendMessage with its taskId");
|
||||
goto out;
|
||||
}
|
||||
message = mcp_arg(params, "message");
|
||||
parts = message != NULL ? mcp_arg(message, "parts") : NULL;
|
||||
{
|
||||
@@ -1348,6 +1278,9 @@ handle_stream(int fd, struct sp_agent *ag, const char *id,
|
||||
snprintf(ctxbuf, sizeof(ctxbuf), "ctx-%d-%u", (int)getpid(),
|
||||
++g_ctx_seq);
|
||||
ctx = ctxbuf;
|
||||
} else if (strlen(ctx) >= sizeof(o.context)) {
|
||||
sse_error(&o, -32602, "contextId too long");
|
||||
goto out;
|
||||
}
|
||||
snprintf(o.context, sizeof(o.context), "%s", ctx);
|
||||
if (ag->cfg == NULL) {
|
||||
@@ -1371,7 +1304,7 @@ handle_stream(int fd, struct sp_agent *ag, const char *id,
|
||||
cfg.stream_ctx = &o;
|
||||
ag->cfg = &cfg;
|
||||
rc = run_turn(ag, &cx->conv, text.p != NULL ? text.p : "",
|
||||
a2a_deny, &answer, &err);
|
||||
&answer, &err);
|
||||
ag->cfg = saved;
|
||||
if (rc != 0) {
|
||||
sse_error(&o, -32603, err.p != NULL && err.len > 0 ?
|
||||
@@ -1406,15 +1339,15 @@ handle_rpc(int fd, struct sp_agent *ag, const char *payload)
|
||||
{
|
||||
mcp_json *v;
|
||||
const mcp_json *params, *message, *parts;
|
||||
const char *method, *ctx, *task_id;
|
||||
const char *method, *ctx;
|
||||
char id[128], ctxbuf[128];
|
||||
struct sp_buf text, answer, err, out, perr;
|
||||
struct a2a_ctx *cx;
|
||||
struct a2a_push push;
|
||||
int rc;
|
||||
|
||||
json_id(payload, id, sizeof(id));
|
||||
v = mcp_parse(payload);
|
||||
json_id(v, id, sizeof(id));
|
||||
if (v == NULL) {
|
||||
rpc_error(fd, id, -32700, "parse error");
|
||||
return;
|
||||
@@ -1439,7 +1372,6 @@ handle_rpc(int fd, struct sp_agent *ag, const char *payload)
|
||||
goto send_out;
|
||||
}
|
||||
message = mcp_arg(params, "message");
|
||||
task_id = message != NULL ? mcp_arg_string(message, "taskId") : NULL;
|
||||
parts = message != NULL ? mcp_arg(message, "parts") : NULL;
|
||||
{
|
||||
char inbox[700];
|
||||
@@ -1459,96 +1391,23 @@ handle_rpc(int fd, struct sp_agent *ag, const char *payload)
|
||||
rpc_error(fd, id, rc == -2 ? -32003 : -32602, perr.p);
|
||||
goto send_out;
|
||||
}
|
||||
if (g_ir_task[0] != '\0') {
|
||||
struct a2a_task *t;
|
||||
int decision;
|
||||
|
||||
if (task_id == NULL ||
|
||||
strcmp(task_id, g_ir_task) != 0) {
|
||||
rpc_error(fd, id, -32004, "a task is waiting "
|
||||
"for input; send its taskId");
|
||||
goto send_out;
|
||||
}
|
||||
t = task_find(task_id);
|
||||
if (t == NULL) {
|
||||
rpc_error(fd, id, -32001, "task not found");
|
||||
goto send_out;
|
||||
}
|
||||
decision = decision_of(text.p);
|
||||
if (decision < 0) {
|
||||
rpc_error(fd, id, -32602, "expected yes or no");
|
||||
goto send_out;
|
||||
}
|
||||
cx = ctx_get(ag, t->context, 1);
|
||||
if (cx == NULL) {
|
||||
rpc_error(fd, id, -32603, "out of memory "
|
||||
"for a context");
|
||||
goto send_out;
|
||||
}
|
||||
rc = resume_turn(ag, &cx->conv, decision, &answer,
|
||||
&err);
|
||||
if (rc == SP_AGENT_INPUT_REQUIRED) {
|
||||
sp_buf_clear(&t->answer);
|
||||
(void)sp_buf_puts(&t->answer, g_ir_msg);
|
||||
task_json(&out, t);
|
||||
rpc_result(fd, id, out.p != NULL ? out.p : "{}");
|
||||
goto send_out;
|
||||
}
|
||||
if (rc != 0) {
|
||||
sp_reply_free(&ag->pending);
|
||||
ag->has_pending = 0;
|
||||
ag->pending_from = 0;
|
||||
g_ir_task[0] = '\0';
|
||||
g_ir_context[0] = '\0';
|
||||
task_update(t, "TASK_STATE_FAILED", &err);
|
||||
rpc_error(fd, id, -32603,
|
||||
err.p != NULL && err.len > 0 ? err.p :
|
||||
"the turn failed");
|
||||
goto send_out;
|
||||
}
|
||||
task_update(t, "TASK_STATE_COMPLETED", &answer);
|
||||
g_ir_task[0] = '\0';
|
||||
g_ir_context[0] = '\0';
|
||||
g_ir_msg[0] = '\0';
|
||||
task_json(&out, t);
|
||||
rpc_result(fd, id, out.p != NULL ? out.p : "{}");
|
||||
push_task(&push, t);
|
||||
goto send_out;
|
||||
}
|
||||
ctx = mcp_arg_string(message, "contextId");
|
||||
if (ctx == NULL || *ctx == '\0') {
|
||||
snprintf(ctxbuf, sizeof(ctxbuf), "ctx-%d-%u",
|
||||
(int)getpid(), ++g_ctx_seq);
|
||||
ctx = ctxbuf;
|
||||
} else if (strlen(ctx) >= sizeof(g_ctx[0].id)) {
|
||||
/* stored cut short it would join another conversation */
|
||||
rpc_error(fd, id, -32602, "contextId too long");
|
||||
goto send_out;
|
||||
}
|
||||
cx = ctx_get(ag, ctx, 1);
|
||||
if (cx == NULL) {
|
||||
rpc_error(fd, id, -32603, "out of memory for a context");
|
||||
goto send_out;
|
||||
}
|
||||
g_ir_task[0] = '\0';
|
||||
g_ir_context[0] = '\0';
|
||||
g_ir_msg[0] = '\0';
|
||||
rc = run_turn(ag, &cx->conv, text.p != NULL ? text.p : "",
|
||||
a2a_approve, &answer, &err);
|
||||
if (rc == SP_AGENT_INPUT_REQUIRED) {
|
||||
char tid[64];
|
||||
struct a2a_task *t;
|
||||
|
||||
gen_task_id(tid, sizeof(tid));
|
||||
t = task_store_state(tid, ctx,
|
||||
"TASK_STATE_INPUT_REQUIRED", g_ir_msg);
|
||||
if (t == NULL) {
|
||||
rpc_error(fd, id, -32603, "out of memory");
|
||||
goto send_out;
|
||||
}
|
||||
snprintf(g_ir_task, sizeof(g_ir_task), "%s", t->id);
|
||||
snprintf(g_ir_context, sizeof(g_ir_context), "%s",
|
||||
t->context);
|
||||
task_json(&out, t);
|
||||
rpc_result(fd, id, out.p != NULL ? out.p : "{}");
|
||||
goto send_out;
|
||||
}
|
||||
&answer, &err);
|
||||
if (rc != 0) {
|
||||
rpc_error(fd, id, -32603,
|
||||
err.p != NULL && err.len > 0 ? err.p :
|
||||
@@ -1642,34 +1501,12 @@ send_out:
|
||||
mcp_json_free(v);
|
||||
return;
|
||||
}
|
||||
if (strcmp(t->state, "TASK_STATE_INPUT_REQUIRED") == 0) {
|
||||
struct sp_buf out, msg;
|
||||
|
||||
if (ag->has_pending) {
|
||||
sp_reply_free(&ag->pending);
|
||||
ag->has_pending = 0;
|
||||
ag->pending_from = 0;
|
||||
}
|
||||
if (strcmp(g_ir_task, t->id) == 0)
|
||||
g_ir_task[0] = '\0';
|
||||
g_ir_context[0] = '\0';
|
||||
g_ir_msg[0] = '\0';
|
||||
memset(&msg, 0, sizeof(msg));
|
||||
sp_buf_init(&msg);
|
||||
sp_buf_puts(&msg, "task canceled");
|
||||
task_update(t, "TASK_STATE_CANCELED", &msg);
|
||||
sp_buf_free(&msg);
|
||||
memset(&out, 0, sizeof(out));
|
||||
if (sp_buf_init(&out) != 0) {
|
||||
rpc_error(fd, id, -32603, "out of memory");
|
||||
} else {
|
||||
task_json(&out, t);
|
||||
rpc_result(fd, id, out.p != NULL ? out.p : "{}");
|
||||
sp_buf_free(&out);
|
||||
}
|
||||
} else {
|
||||
rpc_error(fd, id, -32002, "task is already completed");
|
||||
}
|
||||
/*
|
||||
* A task no longer parks in INPUT_REQUIRED: a tool the registry
|
||||
* offers runs, so a task either completes or is cancelled while
|
||||
* it runs. Cancelling a finished task is an error.
|
||||
*/
|
||||
rpc_error(fd, id, -32002, "task is already completed");
|
||||
} else if (strcmp(method, "SubscribeToTask") == 0) {
|
||||
handle_subscribe(fd, id, params);
|
||||
} else if (strcmp(method, "CreateTaskPushNotificationConfig") == 0) {
|
||||
@@ -1842,7 +1679,7 @@ serve_conn(int fd, struct sp_agent *ag, const char *token)
|
||||
strstr(path, "/.well-known/agent-card.json") != NULL) {
|
||||
const char *host = header_value(hdr, "Host");
|
||||
char hostbuf[256];
|
||||
struct sp_buf card;
|
||||
struct sp_buf card, esc;
|
||||
|
||||
if (host != NULL) {
|
||||
size_t n = strcspn(host, "\r\n");
|
||||
@@ -1854,6 +1691,17 @@ serve_conn(int fd, struct sp_agent *ag, const char *token)
|
||||
} else {
|
||||
snprintf(hostbuf, sizeof(hostbuf), "127.0.0.1");
|
||||
}
|
||||
/*
|
||||
* The value is a header this connection sent, and it goes into
|
||||
* a JSON string: a quote in Host used to end the url and add a
|
||||
* key of the caller's choosing to supportedInterfaces[0].
|
||||
*/
|
||||
memset(&esc, 0, sizeof(esc));
|
||||
if (sp_buf_init(&esc) != 0 ||
|
||||
sp_json_escape(&esc, hostbuf) != 0) {
|
||||
sp_buf_free(&esc);
|
||||
memset(&esc, 0, sizeof(esc));
|
||||
}
|
||||
memset(&card, 0, sizeof(card));
|
||||
if (sp_buf_init(&card) != 0) {
|
||||
http_reply(fd, 500, "Internal Server Error",
|
||||
@@ -1868,10 +1716,12 @@ serve_conn(int fd, struct sp_agent *ag, const char *token)
|
||||
"\"capabilities\":{\"streaming\":true,\"pushNotifications\":true},"
|
||||
"\"defaultInputModes\":[\"text/plain\"],"
|
||||
"\"defaultOutputModes\":[\"text/plain\"],"
|
||||
"\"skills\":[]}", SP_VERSION, hostbuf);
|
||||
"\"skills\":[]}", SP_VERSION,
|
||||
esc.p != NULL ? esc.p : "");
|
||||
http_reply(fd, 200, "OK", card.p != NULL ? card.p : "{}");
|
||||
sp_buf_free(&card);
|
||||
}
|
||||
sp_buf_free(&esc);
|
||||
} else if (strcmp(method, "POST") == 0) {
|
||||
handle_rpc(fd, ag, body.p != NULL ? body.p : "");
|
||||
} else {
|
||||
@@ -1905,6 +1755,14 @@ sp_a2a_serve(struct sp_agent *ag, const char *ip, int port, struct sp_buf *err)
|
||||
sp_buf_printf(err, "a2a: socket: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
/*
|
||||
* No child may inherit the listening socket: the `run` tool forks
|
||||
* /bin/sh with the server's descriptors, and a command that leaves
|
||||
* something in the background ("nohup sleep 300 &") kept the port
|
||||
* bound after splinter exited, so the next start died with "Address
|
||||
* already in use". The same for the accepted connection below.
|
||||
*/
|
||||
(void)fcntl(s, F_SETFD, FD_CLOEXEC);
|
||||
(void)setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
|
||||
memset(&addr, 0, sizeof(addr));
|
||||
addr.sin_family = AF_INET;
|
||||
@@ -1939,9 +1797,20 @@ sp_a2a_serve(struct sp_agent *ag, const char *ip, int port, struct sp_buf *err)
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
(void)fcntl(c, F_SETFD, FD_CLOEXEC);
|
||||
{
|
||||
struct timeval tv = { 300, 0 };
|
||||
/*
|
||||
* One connection at a time, so an unanswered read
|
||||
* holds every other client: 5 minutes was a client
|
||||
* that opened a socket and went quiet. The duration
|
||||
* covers a whole request, body included, and a test
|
||||
* can shorten it.
|
||||
*/
|
||||
const char *tmo = getenv("SPLINTER_A2A_READ_TIMEOUT");
|
||||
struct timeval tv = { 120, 0 };
|
||||
|
||||
if (tmo != NULL && atoi(tmo) > 0)
|
||||
tv.tv_sec = atoi(tmo);
|
||||
(void)setsockopt(c, SOL_SOCKET, SO_RCVTIMEO, &tv,
|
||||
sizeof(tv));
|
||||
}
|
||||
@@ -1964,14 +1833,6 @@ sp_a2a_serve(struct sp_agent *ag, const char *ip, int port, struct sp_buf *err)
|
||||
}
|
||||
for (i = 0; i < 32; i++)
|
||||
g_pcfg[i].used = 0;
|
||||
if (ag->has_pending) {
|
||||
sp_reply_free(&ag->pending);
|
||||
ag->has_pending = 0;
|
||||
ag->pending_from = 0;
|
||||
}
|
||||
g_ir_task[0] = '\0';
|
||||
g_ir_context[0] = '\0';
|
||||
g_ir_msg[0] = '\0';
|
||||
}
|
||||
fprintf(stderr, "splinter: A2A server stopped\n");
|
||||
return 0;
|
||||
File renamed without changes.
@@ -37,7 +37,7 @@
|
||||
#include "i18n.h"
|
||||
#include "ack.h"
|
||||
|
||||
static char ack_root[512];
|
||||
#define ACK_ROOT_MAX 512
|
||||
|
||||
static int
|
||||
ensure_dir(const char *path)
|
||||
@@ -65,14 +65,23 @@ sp_ack_dir(void)
|
||||
const char *env = getenv("SPLINTER_ACK_DIR");
|
||||
const char *home = getenv("HOME");
|
||||
|
||||
/*
|
||||
* One buffer per thread. The path is a pure function of the environment,
|
||||
* so a per-thread copy says the same thing everywhere - but a waiter in
|
||||
* one thread and an answerer in another (the gateway does both) used to
|
||||
* sprintf into the same static while the other read it. TSan found it;
|
||||
* a garbled path here means an approval request that cannot be found.
|
||||
*/
|
||||
static __thread char root[ACK_ROOT_MAX];
|
||||
|
||||
if (env != NULL && *env != '\0') {
|
||||
snprintf(ack_root, sizeof(ack_root), "%s", env);
|
||||
return ack_root;
|
||||
snprintf(root, sizeof(root), "%s", env);
|
||||
return root;
|
||||
}
|
||||
if (home == NULL || *home == '\0')
|
||||
return NULL;
|
||||
snprintf(ack_root, sizeof(ack_root), "%s/.splinter/ack", home);
|
||||
return ack_root;
|
||||
snprintf(root, sizeof(root), "%s/.splinter/ack", home);
|
||||
return root;
|
||||
}
|
||||
|
||||
static int
|
||||
File renamed without changes.
+1041
File diff suppressed because it is too large.
Load diff
@@ -8,6 +8,7 @@
|
||||
#include <strings.h>
|
||||
|
||||
#include "agents.h"
|
||||
#include "log.h"
|
||||
|
||||
#define MAX_AGENTS 32
|
||||
|
||||
@@ -77,9 +78,103 @@ add_def(struct sp_agents *a, const struct sp_agent_def *d)
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* is 'name' an entry of the comma list 'list'? */
|
||||
static int
|
||||
in_list(const char *list, const char *name, size_t nlen)
|
||||
{
|
||||
const char *p = list;
|
||||
|
||||
while (*p != '\0') {
|
||||
const char *e = strchr(p, ',');
|
||||
size_t n = e != NULL ? (size_t)(e - p) : strlen(p);
|
||||
|
||||
if (n == nlen && strncmp(p, name, n) == 0)
|
||||
return 1;
|
||||
if (e == NULL)
|
||||
break;
|
||||
p = e + 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* A profile from a project directory comes with whatever repository was
|
||||
* cloned, so it must not give itself more than the user agreed to: it never
|
||||
* turns on autonomous mode, and when it replaces a profile (the built-in plan,
|
||||
* or one of the user's) it keeps that profile's limits: tools no wider, allow
|
||||
* only what was allowed before, deny everything denied before.
|
||||
*/
|
||||
static void
|
||||
narrow_untrusted(const struct sp_agents *a, struct sp_agent_def *d)
|
||||
{
|
||||
const struct sp_agent_def *o = NULL;
|
||||
char allow[sizeof(d->allow)];
|
||||
const char *p;
|
||||
size_t i, n = 0;
|
||||
|
||||
if (d->autonomous > 0) {
|
||||
sp_logf("agents", "%s: autonomous ignored in a project "
|
||||
"profile; set it in ~/.splinter/agents or the config",
|
||||
d->source);
|
||||
d->autonomous = -1;
|
||||
}
|
||||
for (i = 0; i < a->n; i++)
|
||||
if (strcmp(a->v[i].name, d->name) == 0)
|
||||
o = &a->v[i];
|
||||
if (o == NULL)
|
||||
return;
|
||||
if (o->autonomous == 0)
|
||||
d->autonomous = 0;
|
||||
if (o->max_auth >= 0 && (d->max_auth < 0 || d->max_auth > o->max_auth)) {
|
||||
sp_logf("agents", "%s: tools no wider than %s allows",
|
||||
d->source, o->source);
|
||||
d->max_auth = o->max_auth;
|
||||
}
|
||||
/* allow: only names the replaced profile allowed too */
|
||||
allow[0] = '\0';
|
||||
for (p = d->allow; *p != '\0'; ) {
|
||||
const char *e = strchr(p, ',');
|
||||
size_t len = e != NULL ? (size_t)(e - p) : strlen(p);
|
||||
|
||||
if (len > 0 && in_list(o->allow, p, len) &&
|
||||
n + len + 2 < sizeof(allow)) {
|
||||
if (n > 0)
|
||||
allow[n++] = ',';
|
||||
memcpy(allow + n, p, len);
|
||||
n += len;
|
||||
allow[n] = '\0';
|
||||
}
|
||||
if (e == NULL)
|
||||
break;
|
||||
p = e + 1;
|
||||
}
|
||||
if (strcmp(allow, d->allow) != 0)
|
||||
sp_logf("agents", "%s: allow narrowed to what %s allows",
|
||||
d->source, o->source);
|
||||
snprintf(d->allow, sizeof(d->allow), "%s", allow);
|
||||
/* deny: the old list plus the new one */
|
||||
for (p = o->deny; *p != '\0'; ) {
|
||||
const char *e = strchr(p, ',');
|
||||
size_t len = e != NULL ? (size_t)(e - p) : strlen(p);
|
||||
size_t dl = strlen(d->deny);
|
||||
|
||||
if (len > 0 && !in_list(d->deny, p, len) &&
|
||||
dl + len + 2 < sizeof(d->deny)) {
|
||||
if (dl > 0)
|
||||
d->deny[dl++] = ',';
|
||||
memcpy(d->deny + dl, p, len);
|
||||
d->deny[dl + len] = '\0';
|
||||
}
|
||||
if (e == NULL)
|
||||
break;
|
||||
p = e + 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* one markdown file into a definition; 1 added, 0 skipped */
|
||||
static int
|
||||
read_file(struct sp_agents *a, const char *path, const char *name)
|
||||
read_file(struct sp_agents *a, const char *path, const char *name,
|
||||
int trusted)
|
||||
{
|
||||
FILE *f = fopen(path, "r");
|
||||
char line[2048];
|
||||
@@ -176,11 +271,13 @@ read_file(struct sp_agents *a, const char *path, const char *name)
|
||||
sp_buf_free(&body);
|
||||
if (d.prompt == NULL)
|
||||
return 0;
|
||||
if (!trusted)
|
||||
narrow_untrusted(a, &d);
|
||||
return add_def(a, &d) == 0;
|
||||
}
|
||||
|
||||
static void
|
||||
read_dir(struct sp_agents *a, const char *dir)
|
||||
read_dir(struct sp_agents *a, const char *dir, int trusted)
|
||||
{
|
||||
DIR *dp = opendir(dir);
|
||||
struct dirent *e;
|
||||
@@ -213,7 +310,7 @@ read_dir(struct sp_agents *a, const char *dir)
|
||||
name[len] = '\0';
|
||||
snprintf(path, sizeof(path), "%.700s/%.150s", dir, names[i]);
|
||||
free(names[i]);
|
||||
(void)read_file(a, path, name);
|
||||
(void)read_file(a, path, name, trusted);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,7 +325,8 @@ int
|
||||
sp_agents_load(struct sp_agents *a, const char *cwd, const char *home)
|
||||
{
|
||||
struct sp_agent_def b, p;
|
||||
char dirs[10][700];
|
||||
char dirs[17][700];
|
||||
int trusted[17];
|
||||
size_t nd = 0, i;
|
||||
char cur[700];
|
||||
|
||||
@@ -264,8 +362,13 @@ sp_agents_load(struct sp_agents *a, const char *cwd, const char *home)
|
||||
add_def(a, &b);
|
||||
add_def(a, &p);
|
||||
|
||||
/* the user's, then the project's from far to near: the nearest wins */
|
||||
/*
|
||||
* The user's, then the project's from far to near: the nearest wins.
|
||||
* Only what lives in the home directory is the user's own; the rest
|
||||
* came with a checkout and is narrowed (narrow_untrusted).
|
||||
*/
|
||||
if (home != NULL && *home != '\0') {
|
||||
trusted[nd] = 1;
|
||||
snprintf(dirs[nd++], sizeof(dirs[0]), "%s/.splinter/agents", home);
|
||||
}
|
||||
if (cwd != NULL && *cwd != '\0') {
|
||||
@@ -285,15 +388,21 @@ sp_agents_load(struct sp_agents *a, const char *cwd, const char *home)
|
||||
*slash = '\0';
|
||||
}
|
||||
}
|
||||
for (k = nc; k > 0 && nd + 2 <= 10; k--) {
|
||||
/* chain[0] is the nearest; 8 levels always fit, far first */
|
||||
for (k = nc; k > 0 && nd + 2 <= 17; k--) {
|
||||
int t = home != NULL && *home != '\0' &&
|
||||
strcmp(chain[k - 1], home) == 0;
|
||||
|
||||
trusted[nd] = t;
|
||||
snprintf(dirs[nd++], sizeof(dirs[0]), "%s/.agents",
|
||||
chain[k - 1]);
|
||||
trusted[nd] = t;
|
||||
snprintf(dirs[nd++], sizeof(dirs[0]), "%s/.splinter/agents",
|
||||
chain[k - 1]);
|
||||
}
|
||||
}
|
||||
for (i = 0; i < nd; i++) {
|
||||
read_dir(a, dirs[i]);
|
||||
read_dir(a, dirs[i], trusted[i]);
|
||||
}
|
||||
/* build and plan stay first; the rest by name */
|
||||
if (a->n > 2)
|
||||
File renamed without changes.
@@ -106,6 +106,13 @@ json_emit(struct sp_buf *b, const mcp_json *v)
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* the same, for the OpenAI shaping (openai.c), which has no emitter */
|
||||
int
|
||||
sp_json_emit(struct sp_buf *b, const mcp_json *v)
|
||||
{
|
||||
return json_emit(b, v);
|
||||
}
|
||||
|
||||
/* the max output of one step; Anthropic requires the field */
|
||||
static int
|
||||
max_tokens(void)
|
||||
@@ -301,13 +308,14 @@ user_blocks(const struct sp_msg *m, struct sp_buf *b, int *first)
|
||||
}
|
||||
|
||||
int
|
||||
sp_anthropic_request(const struct sp_conv *conv, const char *model,
|
||||
const struct sp_registry *reg, int streaming, int oauth, struct sp_buf *out)
|
||||
sp_anthropic_request_opts(const struct sp_conv *conv, const char *model,
|
||||
const struct sp_registry *reg, int streaming, int oauth,
|
||||
const struct sp_gen_opts *gen, struct sp_buf *out)
|
||||
{
|
||||
struct sp_buf sys, blocks;
|
||||
const struct sp_tool *tv;
|
||||
size_t i, ntv, ntv0, k, nmsg = 0;
|
||||
int prev_assistant = -1, rc = -1;
|
||||
int prev_assistant = -1, rc = -1, mt;
|
||||
|
||||
if (conv == NULL || out == NULL)
|
||||
return -1;
|
||||
@@ -327,11 +335,23 @@ sp_anthropic_request(const struct sp_conv *conv, const char *model,
|
||||
}
|
||||
}
|
||||
|
||||
/* the API requires max_tokens; a caller's value wins inside its range */
|
||||
mt = max_tokens();
|
||||
if (gen != NULL && gen->have_max_tokens &&
|
||||
gen->max_tokens >= 256 && gen->max_tokens <= 128000)
|
||||
mt = (int)gen->max_tokens;
|
||||
sp_buf_clear(out);
|
||||
if (sp_buf_puts(out, "{\"model\":\"") != 0 ||
|
||||
sp_json_escape(out, model != NULL ? model : "") != 0 ||
|
||||
sp_buf_printf(out, "\",\"max_tokens\":%d,\"stream\":%s,",
|
||||
max_tokens(), streaming ? "true" : "false") != 0)
|
||||
mt, streaming ? "true" : "false") != 0)
|
||||
goto out;
|
||||
if (gen != NULL && gen->have_temperature &&
|
||||
sp_buf_printf(out, "\"temperature\":%.17g,",
|
||||
gen->temperature) != 0)
|
||||
goto out;
|
||||
if (gen != NULL && gen->have_top_p &&
|
||||
sp_buf_printf(out, "\"top_p\":%.17g,", gen->top_p) != 0)
|
||||
goto out;
|
||||
if (oauth || sys.len > 0) {
|
||||
int first = 1;
|
||||
@@ -373,23 +393,30 @@ sp_anthropic_request(const struct sp_conv *conv, const char *model,
|
||||
}
|
||||
if (!any)
|
||||
continue; /* nothing to say: no empty message */
|
||||
if (prev_assistant == assistant) {
|
||||
/*
|
||||
* Same role as the message before (observations of a parallel
|
||||
* round, or a user turn that failed and was asked again): its
|
||||
* blocks join the open message. The message stays open until
|
||||
* the role changes -- closing it first put the blocks outside
|
||||
* any message, and the API answered 400 "messages.N.role".
|
||||
*/
|
||||
if (nmsg > 0 && prev_assistant == assistant) {
|
||||
if (sp_buf_puts(out, ",") != 0 ||
|
||||
(blocks.len > 0 && sp_buf_add(out, blocks.p,
|
||||
blocks.len) != 0))
|
||||
sp_buf_add(out, blocks.p, blocks.len) != 0)
|
||||
goto out;
|
||||
continue;
|
||||
}
|
||||
if (nmsg++ > 0 && sp_buf_puts(out, ",") != 0)
|
||||
if (nmsg > 0 && sp_buf_puts(out, "]},") != 0)
|
||||
goto out;
|
||||
nmsg++;
|
||||
if (sp_buf_printf(out, "{\"role\":\"%s\",\"content\":[",
|
||||
assistant ? "assistant" : "user") != 0 ||
|
||||
(blocks.len > 0 && sp_buf_add(out, blocks.p,
|
||||
blocks.len) != 0) ||
|
||||
sp_buf_puts(out, "]}") != 0)
|
||||
sp_buf_add(out, blocks.p, blocks.len) != 0)
|
||||
goto out;
|
||||
prev_assistant = assistant;
|
||||
}
|
||||
if (nmsg > 0 && sp_buf_puts(out, "]}") != 0)
|
||||
goto out;
|
||||
if (sp_buf_puts(out, "]") != 0)
|
||||
goto out;
|
||||
|
||||
@@ -432,6 +459,14 @@ out:
|
||||
return rc;
|
||||
}
|
||||
|
||||
int
|
||||
sp_anthropic_request(const struct sp_conv *conv, const char *model,
|
||||
const struct sp_registry *reg, int streaming, int oauth, struct sp_buf *out)
|
||||
{
|
||||
return sp_anthropic_request_opts(conv, model, reg, streaming, oauth,
|
||||
NULL, out);
|
||||
}
|
||||
|
||||
/* the neutral call array this file stores in the conversation */
|
||||
static int
|
||||
calls_json(struct sp_reply *out, const char *const *ids,
|
||||
@@ -461,6 +496,8 @@ calls_json(struct sp_reply *out, const char *const *ids,
|
||||
return out->calls_json != NULL ? 0 : -1;
|
||||
}
|
||||
|
||||
static void as_usage_set(long *in, long *cached, const mcp_json *usage);
|
||||
|
||||
int
|
||||
sp_anthropic_reply(const char *json, struct sp_reply *out, struct sp_buf *err)
|
||||
{
|
||||
@@ -542,11 +579,12 @@ sp_anthropic_reply(const char *json, struct sp_reply *out, struct sp_buf *err)
|
||||
goto oom;
|
||||
usage = mcp_arg(v, "usage");
|
||||
if (usage != NULL) {
|
||||
int pin = mcp_arg_int(usage, "input_tokens", -1);
|
||||
int pout = mcp_arg_int(usage, "output_tokens", -1);
|
||||
long in = 0, cached = 0;
|
||||
int pout = mcp_arg_int(usage, "output_tokens", -1);
|
||||
|
||||
if (pin >= 0)
|
||||
out->tokens_in = pin;
|
||||
as_usage_set(&in, &cached, usage);
|
||||
out->tokens_in = in;
|
||||
out->tokens_cached = cached;
|
||||
if (pout >= 0)
|
||||
out->tokens_out = pout;
|
||||
}
|
||||
@@ -604,11 +642,45 @@ struct sp_as_sse {
|
||||
struct as_call calls[AS_MAX_CALLS];
|
||||
enum as_btype block[AS_MAX_BLOCKS];
|
||||
size_t nblocks;
|
||||
/*
|
||||
* Block index -> call index + 1 (0: not a call). Calls follow text and
|
||||
* thinking blocks, so the block index of the fifth call can be far
|
||||
* beyond the fifth slot.
|
||||
*/
|
||||
size_t callof[AS_MAX_BLOCKS];
|
||||
size_t ncalls;
|
||||
long tokens_in;
|
||||
long tokens_out;
|
||||
long tokens_cached;
|
||||
int done;
|
||||
};
|
||||
|
||||
/*
|
||||
* Anthropic reports the prompt in pieces: input_tokens excludes the cache
|
||||
* reads and writes. The context the request carried is the sum, and the cache
|
||||
* share is the read part. A later usage block with no cache fields (the
|
||||
* message_delta event) must not throw that away.
|
||||
*/
|
||||
static void
|
||||
as_usage_set(long *in, long *cached, const mcp_json *usage)
|
||||
{
|
||||
int pin = mcp_arg_int(usage, "input_tokens", -1);
|
||||
int cr = mcp_arg_int(usage, "cache_read_input_tokens", -1);
|
||||
int cc = mcp_arg_int(usage, "cache_creation_input_tokens", -1);
|
||||
|
||||
if (pin >= 0) {
|
||||
if (*in == 0 || cr >= 0 || cc >= 0) {
|
||||
*in = (pin > 0 ? pin : 0) +
|
||||
(cr > 0 ? cr : 0) + (cc > 0 ? cc : 0);
|
||||
if (cr >= 0)
|
||||
*cached = cr > 0 ? cr : 0;
|
||||
}
|
||||
} else if (cr >= 0) {
|
||||
*in += cr > 0 ? cr : 0;
|
||||
*cached = cr > 0 ? cr : 0;
|
||||
}
|
||||
}
|
||||
|
||||
struct sp_as_sse *
|
||||
sp_as_sse_new(void)
|
||||
{
|
||||
@@ -702,14 +774,18 @@ sp_as_sse_line(struct sp_as_sse *s, const char *line, struct sp_buf *out,
|
||||
if (strncmp(line, "data:", 5) != 0)
|
||||
return 0; /* event:/id:/retry: carry nothing we need */
|
||||
line += 5;
|
||||
while (*line == ' ')
|
||||
while (*line == ' ' || *line == '\t')
|
||||
line++;
|
||||
if (*line == '\0')
|
||||
return 0; /* an empty data line is a keepalive */
|
||||
if (strncmp(line, "[DONE]", 6) == 0) {
|
||||
s->done = 1;
|
||||
return 0;
|
||||
}
|
||||
v = mcp_parse(line);
|
||||
if (v == NULL) {
|
||||
if (*line != '{')
|
||||
return 0; /* text keepalive, not a JSON event */
|
||||
sp_buf_printf(err, "anthropic sse: unparseable data line: %.200s",
|
||||
line);
|
||||
return -1;
|
||||
@@ -730,22 +806,16 @@ sp_as_sse_line(struct sp_as_sse *s, const char *line, struct sp_buf *out,
|
||||
if (strcmp(type, "message_start") == 0) {
|
||||
msg = mcp_arg(v, "message");
|
||||
usage = msg != NULL ? mcp_arg(msg, "usage") : NULL;
|
||||
if (usage != NULL) {
|
||||
int in = mcp_arg_int(usage, "input_tokens", -1);
|
||||
|
||||
if (in >= 0)
|
||||
s->tokens_in = in;
|
||||
}
|
||||
if (usage != NULL)
|
||||
as_usage_set(&s->tokens_in, &s->tokens_cached, usage);
|
||||
} else if (strcmp(type, "message_delta") == 0) {
|
||||
usage = mcp_arg(v, "usage");
|
||||
if (usage != NULL) {
|
||||
int outt = mcp_arg_int(usage, "output_tokens", -1);
|
||||
int in = mcp_arg_int(usage, "input_tokens", -1);
|
||||
|
||||
if (outt >= 0)
|
||||
s->tokens_out = outt;
|
||||
if (in >= 0)
|
||||
s->tokens_in = in;
|
||||
as_usage_set(&s->tokens_in, &s->tokens_cached, usage);
|
||||
}
|
||||
} else if (strcmp(type, "content_block_start") == 0) {
|
||||
const char *bt;
|
||||
@@ -754,28 +824,41 @@ sp_as_sse_line(struct sp_as_sse *s, const char *line, struct sp_buf *out,
|
||||
block = mcp_arg(v, "content_block");
|
||||
bt = block != NULL ? mcp_arg_string(block, "type") : NULL;
|
||||
if (bt != NULL && strcmp(bt, "tool_use") == 0) {
|
||||
if (index < 0 || index >= AS_MAX_CALLS) {
|
||||
struct as_call *call;
|
||||
size_t ci;
|
||||
|
||||
if (index < 0 || index >= AS_MAX_BLOCKS ||
|
||||
(s->callof[index] == 0 &&
|
||||
s->ncalls >= AS_MAX_CALLS)) {
|
||||
sp_buf_puts(err, "anthropic sse: too many tool "
|
||||
"calls");
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
if (s->callof[index] == 0)
|
||||
s->callof[index] = ++s->ncalls;
|
||||
ci = s->callof[index] - 1;
|
||||
call = &s->calls[ci];
|
||||
block_set(s, index, AS_TOOL);
|
||||
if (sp_buf_init(&s->calls[index].input) != 0) {
|
||||
free(call->id);
|
||||
free(call->name);
|
||||
sp_buf_free(&call->input);
|
||||
call->id = NULL;
|
||||
call->name = NULL;
|
||||
if (sp_buf_init(&call->input) != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
s->calls[index].id = strdup(mcp_arg_string(block, "id") !=
|
||||
call->id = strdup(mcp_arg_string(block, "id") !=
|
||||
NULL ? mcp_arg_string(block, "id") : "");
|
||||
s->calls[index].name = strdup(mcp_arg_string(block,
|
||||
call->name = strdup(mcp_arg_string(block,
|
||||
"name") != NULL ? mcp_arg_string(block, "name") : "");
|
||||
s->calls[index].saw = 1;
|
||||
if (s->calls[index].id == NULL ||
|
||||
s->calls[index].name == NULL) {
|
||||
call->saw = 1;
|
||||
if (call->id == NULL || call->name == NULL) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
if (sp_buf_puts(out, s->calls[index].name) != 0) {
|
||||
if (sp_buf_puts(out, call->name) != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
@@ -798,8 +881,10 @@ sp_as_sse_line(struct sp_as_sse *s, const char *line, struct sp_buf *out,
|
||||
}
|
||||
if (strcmp(dt, "input_json_delta") == 0) {
|
||||
txt = mcp_arg_string(delta, "partial_json");
|
||||
if (txt != NULL && index >= 0 && index < AS_MAX_CALLS &&
|
||||
sp_buf_puts(&s->calls[index].input, txt) != 0) {
|
||||
if (txt != NULL && index >= 0 &&
|
||||
index < AS_MAX_BLOCKS && s->callof[index] != 0 &&
|
||||
sp_buf_puts(&s->calls[s->callof[index] - 1].input,
|
||||
txt) != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
@@ -850,6 +935,7 @@ sp_as_sse_finish(struct sp_as_sse *s, struct sp_reply *out, struct sp_buf *err)
|
||||
out->status = 200;
|
||||
out->tokens_in = s->tokens_in;
|
||||
out->tokens_out = s->tokens_out;
|
||||
out->tokens_cached = s->tokens_cached;
|
||||
out->content = strdup(s->content.p != NULL ? s->content.p : "");
|
||||
if (out->content == NULL)
|
||||
return -1;
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -9,6 +9,8 @@
|
||||
* Shell execution goes through popen("/bin/sh -c") and its exit status is
|
||||
* reported; a command that fails is an observation, not an exception.
|
||||
*/
|
||||
#define _XOPEN_SOURCE 700 /* realpath() for the tool root */
|
||||
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -84,7 +86,7 @@ tool_echo(const char *args, struct sp_buf *out, void *ctx)
|
||||
#define SECRET_MAX 32
|
||||
|
||||
static char secret_env[SECRET_MAX][96] = {
|
||||
"SPLINTER_API_KEY", "SPLINTER_TELEGRAM_TOKEN", "SPLINTER_MEM_KEY",
|
||||
"SPLINTER_API_KEY", "SPLINTER_TELEGRAM_TOKEN",
|
||||
"SPLINTER_DELEGATE_KEY_*", "CLAUDE_CODE_OAUTH_TOKEN", "OLLAMA_KEY",
|
||||
"SPLINTER_OLLAMA_KEY_*", "SPLINTER_MCP_TOKEN"
|
||||
};
|
||||
@@ -126,6 +128,35 @@ sp_secret_env_is(const char *entry)
|
||||
|
||||
extern char **environ;
|
||||
|
||||
#define TOOL_ROOT_MAX 1024
|
||||
|
||||
/*
|
||||
* The boundary the file tools stay inside, when the operator set one.
|
||||
*
|
||||
* Without it a model with mutate rights can write anything the process can:
|
||||
* ~/.ssh/authorized_keys, ~/.splinter/splinter.conf (which names the plugins
|
||||
* this harness loads), ~/.bashrc. The authorization classes say *whether* a
|
||||
* tool may run, not *where* it may look - and a prompt-injected model has the
|
||||
* same rights as a careful one.
|
||||
*
|
||||
* Empty root means no boundary, which is the default: a setup that works today
|
||||
* must keep working. `run` is not covered by this and cannot be - a shell can
|
||||
* open any path it likes; it gets the root as its working directory, which is a
|
||||
* convenience, not a fence.
|
||||
*
|
||||
* One struct per tool, because the registry's dispose callback frees it and a
|
||||
* shared pointer would be freed once per tool. It lives up here because
|
||||
* tool_run() - further down - already needs to know whether a root is set.
|
||||
*/
|
||||
struct tool_root {
|
||||
int on;
|
||||
char root[TOOL_ROOT_MAX]; /* canonical: realpath at registration */
|
||||
};
|
||||
|
||||
static int count_lines(const char *s, size_t upto);
|
||||
static int resolve_target(const char *path, char *out, size_t cap);
|
||||
static char *slurp(const char *path, size_t *lenp, struct sp_buf *err);
|
||||
|
||||
#define RUN_MAX_OUTPUT (1u << 20)
|
||||
#define RUN_TIMEOUT_S 600
|
||||
|
||||
@@ -133,9 +164,11 @@ extern char **environ;
|
||||
* Run a shell command for the model.
|
||||
*
|
||||
* fork/exec instead of popen(), for three reasons popen cannot give:
|
||||
* - a timeout: the child gets its own process group, and when it outlives
|
||||
* SPLINTER_RUN_TIMEOUT (default 300 s) the whole group is killed - a
|
||||
* 'sleep 1000' or an editor waiting for input no longer holds the agent;
|
||||
* - a timeout: the child gets its own process group, and when it stays
|
||||
* silent for SPLINTER_RUN_TIMEOUT (default 600 s) the whole group is
|
||||
* killed - a 'sleep 1000' or an editor waiting for input no longer holds
|
||||
* the agent. Every chunk the command prints moves the deadline: a build
|
||||
* that reports progress is working, not hung;
|
||||
* - stdin is /dev/null: a command that reads input used to read the curses
|
||||
* terminal, stealing the operator's keystrokes;
|
||||
* - the environment is filtered: see secret_env above.
|
||||
@@ -150,10 +183,10 @@ tool_run(const char *args, struct sp_buf *out, void *ctx)
|
||||
char **envp;
|
||||
size_t total = 0, n, i, j;
|
||||
int fds[2], status = 0, timeout_s, timed_out = 0, cut = 0;
|
||||
int reaped = 0;
|
||||
pid_t child;
|
||||
time_t end;
|
||||
|
||||
(void)ctx;
|
||||
if (sp_buf_init(&keep) != 0)
|
||||
return -1;
|
||||
cmd = arg_text(args, "command", &keep);
|
||||
@@ -195,6 +228,11 @@ tool_run(const char *args, struct sp_buf *out, void *ctx)
|
||||
int dn = open("/dev/null", O_RDONLY);
|
||||
|
||||
(void)setpgid(0, 0);
|
||||
/*
|
||||
* The root is not a fence for a shell - a child that wants to
|
||||
* leave it can. It is where the command starts, so a relative
|
||||
* path means what the operator meant.
|
||||
*/
|
||||
if (dn >= 0) {
|
||||
(void)dup2(dn, STDIN_FILENO);
|
||||
if (dn != STDIN_FILENO)
|
||||
@@ -202,6 +240,24 @@ tool_run(const char *args, struct sp_buf *out, void *ctx)
|
||||
}
|
||||
(void)dup2(fds[1], STDOUT_FILENO);
|
||||
(void)dup2(fds[1], STDERR_FILENO);
|
||||
/*
|
||||
* After the redirection, so the model reads it as part of the
|
||||
* observation: a command that ran in another directory than the
|
||||
* one it named must not look like it ran where it was told. Not
|
||||
* exit 127 either - that reads as "no such command".
|
||||
*/
|
||||
if (ctx != NULL && ((const struct tool_root *)ctx)->on &&
|
||||
chdir(((const struct tool_root *)ctx)->root) != 0) {
|
||||
static const char msg[] =
|
||||
"splinter: cannot enter the tool root: ";
|
||||
const char *why = strerror(errno);
|
||||
|
||||
/* sizeof - 1, never a counted number: a length typed by
|
||||
* hand is how half a message gets written. */
|
||||
(void)write(STDERR_FILENO, msg, sizeof(msg) - 1);
|
||||
(void)write(STDERR_FILENO, why, strlen(why));
|
||||
(void)write(STDERR_FILENO, "\n", 1);
|
||||
}
|
||||
close(fds[0]);
|
||||
close(fds[1]);
|
||||
execle("/bin/sh", "sh", "-c", cmd, (char *)NULL, envp);
|
||||
@@ -243,18 +299,35 @@ tool_run(const char *args, struct sp_buf *out, void *ctx)
|
||||
if (sp_buf_add(out, chunk, (size_t)got) != 0)
|
||||
break;
|
||||
total += (size_t)got;
|
||||
/*
|
||||
* The command said something, so it is working: give it
|
||||
* another full window. Ask the process, not the pipe - a
|
||||
* closed child can still have bytes buffered here.
|
||||
*/
|
||||
if (!reaped) {
|
||||
pid_t r;
|
||||
|
||||
do {
|
||||
r = waitpid(child, &status, WNOHANG);
|
||||
} while (r < 0 && errno == EINTR);
|
||||
if (r == child)
|
||||
reaped = 1;
|
||||
}
|
||||
if (!reaped)
|
||||
end = time(NULL) + timeout_s;
|
||||
}
|
||||
if (timed_out || cut)
|
||||
(void)kill(-child, SIGKILL);
|
||||
close(fds[0]);
|
||||
while (waitpid(child, &status, 0) < 0 && errno == EINTR)
|
||||
;
|
||||
if (!reaped)
|
||||
while (waitpid(child, &status, 0) < 0 && errno == EINTR)
|
||||
;
|
||||
sp_buf_free(&keep);
|
||||
if (cut)
|
||||
sp_buf_puts(out, "\n[output truncated at 1 MiB]");
|
||||
if (timed_out)
|
||||
return sp_buf_printf(out, "\n[timed out after %d s, killed]",
|
||||
timeout_s);
|
||||
return sp_buf_printf(out,
|
||||
"\n[timed out: no output for %d s, killed]", timeout_s);
|
||||
if (WIFEXITED(status))
|
||||
return sp_buf_printf(out, "\n[exit status %d]",
|
||||
WEXITSTATUS(status));
|
||||
@@ -278,8 +351,276 @@ tool_run(const char *args, struct sp_buf *out, void *ctx)
|
||||
#define TOOL_MAX_FILE (4 * 1024 * 1024)
|
||||
#define TOOL_MAX_HITS 100
|
||||
|
||||
static int count_lines(const char *s, size_t upto);
|
||||
static char *slurp(const char *path, size_t *lenp, struct sp_buf *err);
|
||||
static void
|
||||
tool_root_free(struct sp_tool *t)
|
||||
{
|
||||
free(t->ctx);
|
||||
t->ctx = NULL;
|
||||
}
|
||||
|
||||
static struct tool_root *
|
||||
tool_root_new(const char *root)
|
||||
{
|
||||
struct tool_root *tr;
|
||||
char real[TOOL_ROOT_MAX];
|
||||
|
||||
tr = calloc(1, sizeof(*tr));
|
||||
if (tr == NULL)
|
||||
return NULL;
|
||||
if (root == NULL || *root == '\0')
|
||||
return tr; /* off: every path is allowed */
|
||||
/*
|
||||
* The root is resolved once, at startup, so a symlinked root cannot make
|
||||
* the comparison lie, and a root that does not exist is an error the
|
||||
* operator sees instead of a fence that silently matches nothing.
|
||||
*/
|
||||
if (realpath(root, real) == NULL) {
|
||||
free(tr);
|
||||
return NULL;
|
||||
}
|
||||
tr->on = 1;
|
||||
snprintf(tr->root, sizeof(tr->root), "%s", real);
|
||||
return tr;
|
||||
}
|
||||
|
||||
static int
|
||||
under_root(const struct tool_root *tr, const char *real)
|
||||
{
|
||||
size_t n;
|
||||
|
||||
if (tr == NULL || !tr->on)
|
||||
return 1;
|
||||
if (strcmp(tr->root, "/") == 0)
|
||||
return real[0] == '/';
|
||||
n = strlen(tr->root);
|
||||
if (strncmp(real, tr->root, n) != 0)
|
||||
return 0;
|
||||
/* "/root" matches "/root" and "/root/x", never "/rootfs" */
|
||||
return real[n] == '\0' || real[n] == '/';
|
||||
}
|
||||
|
||||
/*
|
||||
* Is 'path' inside the root? 1 allowed, 0 refused.
|
||||
*
|
||||
* realpath() does the work: it resolves "..", "." and every symlink on the way,
|
||||
* so a link inside the root that points at /etc/passwd is refused for pointing
|
||||
* there - checking the string the model sent would say "inside".
|
||||
*
|
||||
* A path that does not exist yet (a write creating a file) cannot be resolved;
|
||||
* its directory can, and that is what decides. The last component is then taken
|
||||
* as given, which is safe: it is a name in a directory the root covers, and a
|
||||
* name that already is a symlink would have resolved above.
|
||||
*
|
||||
* 'resolved' (optional) gets the canonical path, which is what the tool then
|
||||
* uses: a check on one string and a write to another is the whole class of bug
|
||||
* this function exists to prevent.
|
||||
*/
|
||||
static int
|
||||
path_checked(const struct tool_root *tr, const char *path, char *resolved,
|
||||
size_t cap, struct sp_buf *err)
|
||||
{
|
||||
char full[TOOL_ROOT_MAX], dir[TOOL_ROOT_MAX];
|
||||
char dirreal[TOOL_ROOT_MAX], real[TOOL_ROOT_MAX];
|
||||
char target[TOOL_ROOT_MAX];
|
||||
const char *base;
|
||||
char *slash;
|
||||
size_t n, base_len;
|
||||
|
||||
if (path == NULL || *path == '\0')
|
||||
return 1; /* the caller reports its own error */
|
||||
if (resolved != NULL && cap > 0)
|
||||
snprintf(resolved, cap, "%s", path);
|
||||
if (tr == NULL || !tr->on)
|
||||
return 1;
|
||||
if (realpath(path, real) != NULL) {
|
||||
if (under_root(tr, real)) {
|
||||
if (resolved != NULL && cap > 0)
|
||||
snprintf(resolved, cap, "%s", real);
|
||||
return 1;
|
||||
}
|
||||
goto refused;
|
||||
}
|
||||
/*
|
||||
* realpath() failed: the path does not exist yet (a write creating a
|
||||
* file), or it is a dangling symlink. The second case is why the link
|
||||
* chain is resolved here with the same function write_atomic() uses:
|
||||
* a dangling link inside the root that points outside would otherwise
|
||||
* pass the directory check and then be followed out of the root by the
|
||||
* write. Resolving first means the check and the write agree on the
|
||||
* file - which is the only way a check is worth anything.
|
||||
*/
|
||||
if (resolve_target(path, target, sizeof(target)) != 0)
|
||||
goto refused;
|
||||
snprintf(full, sizeof(full), "%s", target);
|
||||
n = strlen(full);
|
||||
while (n > 1 && full[n - 1] == '/')
|
||||
full[--n] = '\0';
|
||||
slash = strrchr(full, '/');
|
||||
if (slash == NULL) {
|
||||
snprintf(dir, sizeof(dir), ".");
|
||||
base = full;
|
||||
} else {
|
||||
*slash = '\0';
|
||||
snprintf(dir, sizeof(dir), "%s", full[0] != '\0' ? full : "/");
|
||||
base = slash + 1;
|
||||
}
|
||||
/* "." or ".." as the name: nothing to create, nothing to allow */
|
||||
if (base[0] == '\0' || strcmp(base, ".") == 0 || strcmp(base, "..") == 0)
|
||||
goto refused;
|
||||
if (realpath(dir, dirreal) == NULL) {
|
||||
/* no such directory: the tool would fail on it anyway */
|
||||
return 1;
|
||||
}
|
||||
n = strlen(dirreal);
|
||||
/*
|
||||
* Built by hand rather than with snprintf: the lengths are checked right
|
||||
* here, and a "%s%s%s" into a fixed buffer makes the compiler warn about
|
||||
* a truncation that this check already rules out.
|
||||
*/
|
||||
base_len = strlen(base);
|
||||
if (n + 1 + base_len + 1 > sizeof(real))
|
||||
goto refused;
|
||||
memcpy(real, dirreal, n);
|
||||
real[n] = '/';
|
||||
memcpy(real + n + 1, base, base_len + 1);
|
||||
if (!under_root(tr, real))
|
||||
goto refused;
|
||||
if (resolved != NULL && cap > 0)
|
||||
snprintf(resolved, cap, "%s", real);
|
||||
return 1;
|
||||
refused:
|
||||
if (err != NULL)
|
||||
sp_buf_printf(err, "error: %s is outside the tool root %s", path,
|
||||
tr->root);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Follow a chain of symlinks to the file that will actually be replaced.
|
||||
*
|
||||
* rename(2) replaces the link, not what it points at, while the old
|
||||
* fopen(path, "w") went through it. Without this step a write to
|
||||
* ~/.splinter/splinter.conf -> ~/dotfiles/... would quietly turn the link into
|
||||
* a plain file and leave the real config untouched - the exact opposite of what
|
||||
* the operator asked for. A dangling link is followed to its (then created)
|
||||
* target, which is also what fopen("w") did.
|
||||
*/
|
||||
static int
|
||||
resolve_target(const char *path, char *out, size_t cap)
|
||||
{
|
||||
char cur[1024], link[1024], tmp[1024];
|
||||
size_t hops;
|
||||
|
||||
if (path == NULL || strlen(path) + 1 > sizeof(cur))
|
||||
return -1;
|
||||
snprintf(cur, sizeof(cur), "%s", path);
|
||||
for (hops = 0; hops < 16; hops++) {
|
||||
struct stat st;
|
||||
ssize_t n;
|
||||
|
||||
if (lstat(cur, &st) != 0 || !S_ISLNK(st.st_mode))
|
||||
break;
|
||||
n = readlink(cur, link, sizeof(link) - 1);
|
||||
if (n <= 0)
|
||||
return -1;
|
||||
link[n] = '\0';
|
||||
if (link[0] == '/') {
|
||||
n = snprintf(tmp, sizeof(tmp), "%s", link);
|
||||
} else {
|
||||
char *slash = strrchr(cur, '/');
|
||||
|
||||
if (slash == NULL)
|
||||
n = snprintf(tmp, sizeof(tmp), "%s", link);
|
||||
else
|
||||
n = snprintf(tmp, sizeof(tmp), "%.*s/%s",
|
||||
(int)(slash - cur), cur, link);
|
||||
}
|
||||
if (n < 0 || (size_t)n >= sizeof(tmp))
|
||||
return -1;
|
||||
if ((size_t)n >= sizeof(cur))
|
||||
return -1;
|
||||
snprintf(cur, sizeof(cur), "%s", tmp);
|
||||
}
|
||||
if (strlen(cur) + 1 > cap)
|
||||
return -1;
|
||||
snprintf(out, cap, "%s", cur);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Replace a file's content without ever leaving it half written.
|
||||
*
|
||||
* fopen(path, "w") truncates first: a disk that fills up, a write that is cut
|
||||
* short or a crash between the two leaves the operator with an empty or
|
||||
* truncated file and no way back - the old text is gone before the new one
|
||||
* exists. So the new content goes to a sibling ".tmp", is flushed to disk, and
|
||||
* only then is renamed over the target: rename(2) is atomic, so a reader sees
|
||||
* either the old file or the new one, never a torn one. On any failure the
|
||||
* temp file is unlinked and the original is left exactly as it was.
|
||||
*
|
||||
* The mode of an existing file is kept (a 0600 file must not become 0644 just
|
||||
* because a tool wrote it); a new file gets the usual 0666 masked by umask.
|
||||
*/
|
||||
static int
|
||||
write_atomic(const char *path, const char *text, size_t n, struct sp_buf *err)
|
||||
{
|
||||
char real[1024], tmp[1024];
|
||||
struct stat st;
|
||||
int have = 0, fd;
|
||||
FILE *f;
|
||||
|
||||
if (resolve_target(path, real, sizeof(real)) != 0)
|
||||
return sp_buf_puts(err, "error: path is too long");
|
||||
if (strlen(real) + 5 > sizeof(tmp))
|
||||
return sp_buf_puts(err, "error: path is too long");
|
||||
snprintf(tmp, sizeof(tmp), "%s.tmp", real);
|
||||
have = stat(real, &st) == 0;
|
||||
/*
|
||||
* rename(2) only needs write permission on the directory, so a 0444 file
|
||||
* would be replaced without a word - fopen(path, "w") refused it. The
|
||||
* tools must not gain a way around a file's own mode.
|
||||
*/
|
||||
if (have && access(real, W_OK) != 0) {
|
||||
sp_buf_printf(err, "error: %s: %s", real, strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, have ? 0600 : 0666);
|
||||
if (fd < 0) {
|
||||
sp_buf_printf(err, "error: %s: %s", tmp, strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
if (have && fchmod(fd, st.st_mode & 07777) != 0) {
|
||||
sp_buf_printf(err, "error: %s: %s", tmp, strerror(errno));
|
||||
(void)close(fd);
|
||||
(void)unlink(tmp);
|
||||
return -1;
|
||||
}
|
||||
f = fdopen(fd, "w");
|
||||
if (f == NULL) {
|
||||
sp_buf_printf(err, "error: %s: %s", tmp, strerror(errno));
|
||||
(void)close(fd);
|
||||
(void)unlink(tmp);
|
||||
return -1;
|
||||
}
|
||||
if ((n > 0 && fwrite(text, 1, n, f) != n) || fflush(f) != 0 ||
|
||||
fsync(fileno(f)) != 0) {
|
||||
sp_buf_printf(err, "error: short write: %s", strerror(errno));
|
||||
(void)fclose(f); /* closes fd */
|
||||
(void)unlink(tmp);
|
||||
return -1;
|
||||
}
|
||||
if (fclose(f) != 0) {
|
||||
sp_buf_printf(err, "error: %s: %s", tmp, strerror(errno));
|
||||
(void)unlink(tmp);
|
||||
return -1;
|
||||
}
|
||||
if (rename(tmp, real) != 0) {
|
||||
sp_buf_printf(err, "error: %s: %s", real, strerror(errno));
|
||||
(void)unlink(tmp);
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
arg_int(const char *args, const char *key, int dflt)
|
||||
@@ -314,11 +655,14 @@ struct lines {
|
||||
size_t n;
|
||||
};
|
||||
|
||||
static void free_lines(struct lines *);
|
||||
|
||||
/* On failure 'out' is left empty (v NULL, n 0): free_lines() stays safe. */
|
||||
static int
|
||||
split_lines(const char *text, struct lines *out)
|
||||
{
|
||||
char *copy, *p;
|
||||
size_t cap = 16;
|
||||
const char *p;
|
||||
size_t cap = 16;
|
||||
|
||||
out->v = malloc(cap * sizeof(*out->v));
|
||||
out->n = 0;
|
||||
@@ -326,34 +670,33 @@ split_lines(const char *text, struct lines *out)
|
||||
return -1;
|
||||
if (text == NULL || *text == '\0')
|
||||
return 0;
|
||||
copy = strdup(text);
|
||||
if (copy == NULL) {
|
||||
free(out->v);
|
||||
return -1;
|
||||
}
|
||||
for (p = copy; *p != '\0'; ) {
|
||||
char *nl = strchr(p, '\n');
|
||||
for (p = text; *p != '\0'; ) {
|
||||
const char *nl = strchr(p, '\n');
|
||||
size_t len = nl != NULL ? (size_t)(nl - p) : strlen(p);
|
||||
char *line;
|
||||
|
||||
if (out->n == cap) {
|
||||
char **bigger = realloc(out->v, cap * 2 * sizeof(*bigger));
|
||||
|
||||
if (bigger == NULL) {
|
||||
free(copy);
|
||||
free(out->v);
|
||||
free_lines(out);
|
||||
return -1;
|
||||
}
|
||||
out->v = bigger;
|
||||
cap *= 2;
|
||||
}
|
||||
out->v[out->n++] = strdup(p);
|
||||
if (out->v[out->n - 1] == NULL) {
|
||||
free(copy);
|
||||
line = malloc(len + 1);
|
||||
if (line == NULL) {
|
||||
free_lines(out);
|
||||
return -1;
|
||||
}
|
||||
memcpy(line, p, len);
|
||||
line[len] = '\0';
|
||||
out->v[out->n++] = line;
|
||||
if (nl == NULL)
|
||||
break;
|
||||
*strchr(out->v[out->n - 1], '\n') = '\0';
|
||||
p = nl + 1;
|
||||
}
|
||||
free(copy);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -440,12 +783,11 @@ tool_read(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
struct sp_buf keep;
|
||||
const char *path;
|
||||
char line[2048];
|
||||
char line[2048], real[TOOL_ROOT_MAX];
|
||||
FILE *f;
|
||||
int offset, limit, no = 0, printed = 0;
|
||||
size_t total = 0;
|
||||
|
||||
(void)ctx;
|
||||
if (sp_buf_init(&keep) != 0)
|
||||
return -1;
|
||||
path = arg_text(args, "path", &keep);
|
||||
@@ -453,6 +795,11 @@ tool_read(const char *args, struct sp_buf *out, void *ctx)
|
||||
sp_buf_free(&keep);
|
||||
return sp_buf_puts(out, "error: 'path' is required");
|
||||
}
|
||||
if (!path_checked(ctx, path, real, sizeof(real), out)) {
|
||||
sp_buf_free(&keep);
|
||||
return 0;
|
||||
}
|
||||
path = real;
|
||||
offset = arg_int(args, "offset", 1);
|
||||
limit = arg_int(args, "limit", 200);
|
||||
if (offset < 1)
|
||||
@@ -490,6 +837,10 @@ tool_read(const char *args, struct sp_buf *out, void *ctx)
|
||||
total += strlen(line);
|
||||
printed++;
|
||||
}
|
||||
/* a short read must say so, or it looks like the end of the file */
|
||||
if (ferror(f) && !(printed >= limit || total >= TOOL_MAX_READ))
|
||||
sp_buf_printf(out, "[%s: read error after line %d: %s]\n",
|
||||
path, no, strerror(errno));
|
||||
fclose(f);
|
||||
if (printed == 0 && no < offset)
|
||||
sp_buf_printf(out, "[%s: no lines at offset %d (file has %d)]\n",
|
||||
@@ -503,10 +854,9 @@ tool_write(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
struct sp_buf keep, content;
|
||||
const char *path, *text;
|
||||
FILE *f;
|
||||
char real[TOOL_ROOT_MAX];
|
||||
size_t n;
|
||||
|
||||
(void)ctx;
|
||||
if (sp_buf_init(&keep) != 0 || sp_buf_init(&content) != 0)
|
||||
return -1;
|
||||
path = arg_text(args, "path", &keep);
|
||||
@@ -516,6 +866,12 @@ tool_write(const char *args, struct sp_buf *out, void *ctx)
|
||||
sp_buf_free(&content);
|
||||
return sp_buf_puts(out, "error: 'path' and 'content' are required");
|
||||
}
|
||||
if (!path_checked(ctx, path, real, sizeof(real), out)) {
|
||||
sp_buf_free(&keep);
|
||||
sp_buf_free(&content);
|
||||
return 0;
|
||||
}
|
||||
path = real;
|
||||
n = strlen(text);
|
||||
if (n > TOOL_MAX_FILE) {
|
||||
sp_buf_printf(out, "error: refusing to write %zu bytes (limit %d)",
|
||||
@@ -526,31 +882,25 @@ tool_write(const char *args, struct sp_buf *out, void *ctx)
|
||||
}
|
||||
{
|
||||
/* the previous content, only to show what changed */
|
||||
size_t oldlen = 0;
|
||||
char *old = NULL;
|
||||
FILE *prev = fopen(path, "r");
|
||||
struct sp_buf scraperr;
|
||||
size_t oldlen = 0;
|
||||
char *old = NULL;
|
||||
|
||||
if (prev != NULL) {
|
||||
old = slurp(path, &oldlen, out);
|
||||
fclose(prev);
|
||||
/*
|
||||
* The old text is a courtesy, not a precondition: slurp() fails
|
||||
* on a binary or oversized file, and that message belongs
|
||||
* nowhere near the write result - a scratch buffer swallows it.
|
||||
*/
|
||||
if (sp_buf_init(&scraperr) == 0) {
|
||||
old = slurp(path, &oldlen, &scraperr);
|
||||
sp_buf_free(&scraperr);
|
||||
}
|
||||
f = fopen(path, "w");
|
||||
if (f == NULL) {
|
||||
sp_buf_printf(out, "error: %s: %s", path, strerror(errno));
|
||||
if (write_atomic(path, text, n, out) != 0) {
|
||||
free(old);
|
||||
sp_buf_free(&keep);
|
||||
sp_buf_free(&content);
|
||||
return 0;
|
||||
}
|
||||
if (n > 0 && fwrite(text, 1, n, f) != n) {
|
||||
sp_buf_printf(out, "error: short write: %s", strerror(errno));
|
||||
fclose(f);
|
||||
free(old);
|
||||
sp_buf_free(&keep);
|
||||
sp_buf_free(&content);
|
||||
return 0;
|
||||
}
|
||||
fclose(f);
|
||||
sp_buf_printf(out, "wrote %zu bytes to %s\n", n, path);
|
||||
emit_diff(out, path, old != NULL ? old : "", text);
|
||||
free(old);
|
||||
@@ -558,18 +908,6 @@ tool_write(const char *args, struct sp_buf *out, void *ctx)
|
||||
sp_buf_free(&content);
|
||||
return 0;
|
||||
}
|
||||
if (n > 0 && fwrite(text, 1, n, f) != n) {
|
||||
sp_buf_printf(out, "error: short write: %s", strerror(errno));
|
||||
fclose(f);
|
||||
sp_buf_free(&keep);
|
||||
sp_buf_free(&content);
|
||||
return 0;
|
||||
}
|
||||
fclose(f);
|
||||
sp_buf_printf(out, "wrote %zu bytes to %s", n, path);
|
||||
sp_buf_free(&keep);
|
||||
sp_buf_free(&content);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Read a whole file into memory; NULL when it is too large or binary. */
|
||||
@@ -604,6 +942,17 @@ slurp(const char *path, size_t *lenp, struct sp_buf *err)
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* A read error is not the end of the file. Without this, edit() would
|
||||
* take the truncated prefix for the whole file, find its `old` there
|
||||
* and write the prefix back - a silent data loss on the way out.
|
||||
*/
|
||||
if (ferror(f)) {
|
||||
sp_buf_printf(err, "error: %s: %s", path, strerror(errno));
|
||||
sp_buf_free(&buf);
|
||||
fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
fclose(f);
|
||||
if (buf.p == NULL) {
|
||||
sp_buf_free(&buf);
|
||||
@@ -636,11 +985,10 @@ tool_edit(const char *args, struct sp_buf *out, void *ctx)
|
||||
struct sp_buf keep, bufs[2];
|
||||
const char *path, *old, *new;
|
||||
char *text, *hit, *result;
|
||||
char real[TOOL_ROOT_MAX];
|
||||
size_t len, oldlen, newlen, prefix;
|
||||
int count;
|
||||
FILE *f;
|
||||
|
||||
(void)ctx;
|
||||
if (sp_buf_init(&keep) != 0 || sp_buf_init(&bufs[0]) != 0 ||
|
||||
sp_buf_init(&bufs[1]) != 0)
|
||||
return -1;
|
||||
@@ -653,6 +1001,13 @@ tool_edit(const char *args, struct sp_buf *out, void *ctx)
|
||||
sp_buf_free(&bufs[1]);
|
||||
return sp_buf_puts(out, "error: 'path', 'old' and 'new' are required");
|
||||
}
|
||||
if (!path_checked(ctx, path, real, sizeof(real), out)) {
|
||||
sp_buf_free(&keep);
|
||||
sp_buf_free(&bufs[0]);
|
||||
sp_buf_free(&bufs[1]);
|
||||
return 0;
|
||||
}
|
||||
path = real;
|
||||
oldlen = strlen(old);
|
||||
newlen = strlen(new);
|
||||
if (oldlen == 0) {
|
||||
@@ -697,21 +1052,10 @@ tool_edit(const char *args, struct sp_buf *out, void *ctx)
|
||||
len - prefix - oldlen);
|
||||
result[len - oldlen + newlen] = '\0';
|
||||
|
||||
f = fopen(path, "w");
|
||||
if (f == NULL) {
|
||||
sp_buf_printf(out, "error: %s: %s", path, strerror(errno));
|
||||
} else {
|
||||
size_t outlen = len - oldlen + newlen;
|
||||
|
||||
if (fwrite(result, 1, outlen, f) != outlen)
|
||||
sp_buf_printf(out, "error: short write: %s",
|
||||
strerror(errno));
|
||||
else {
|
||||
sp_buf_printf(out, "edited %s (line %d)\n", path,
|
||||
1 + count_lines(text, prefix));
|
||||
emit_diff(out, path, text, result);
|
||||
}
|
||||
fclose(f);
|
||||
if (write_atomic(path, result, len - oldlen + newlen, out) == 0) {
|
||||
sp_buf_printf(out, "edited %s (line %d)\n", path,
|
||||
1 + count_lines(text, prefix));
|
||||
emit_diff(out, path, text, result);
|
||||
}
|
||||
free(result);
|
||||
free(text);
|
||||
@@ -742,11 +1086,11 @@ skip_name(const char *name)
|
||||
|
||||
static void
|
||||
search_dir(const char *dir, const char *pattern, struct sp_buf *out, int *hits,
|
||||
int depth)
|
||||
int depth, const struct tool_root *tr)
|
||||
{
|
||||
DIR *d;
|
||||
struct dirent *e;
|
||||
char path[1024], line[2048];
|
||||
char path[1024], real[TOOL_ROOT_MAX], line[2048];
|
||||
struct stat st;
|
||||
|
||||
if (depth > 12 || *hits >= TOOL_MAX_HITS)
|
||||
@@ -760,21 +1104,30 @@ search_dir(const char *dir, const char *pattern, struct sp_buf *out, int *hits,
|
||||
if (skip_name(e->d_name))
|
||||
continue;
|
||||
snprintf(path, sizeof(path), "%s/%s", dir, e->d_name);
|
||||
if (stat(path, &st) != 0)
|
||||
/*
|
||||
* Each entry is resolved before it is looked at, exactly like an
|
||||
* argument: search recurses, and a directory symlink inside the root
|
||||
* that points outside would otherwise be walked (stat() follows it)
|
||||
* and its files read - a fence that only guards the argument is a
|
||||
* fence with a door in it.
|
||||
*/
|
||||
if (!path_checked(tr, path, real, sizeof(real), NULL))
|
||||
continue;
|
||||
if (stat(real, &st) != 0)
|
||||
continue;
|
||||
if (S_ISDIR(st.st_mode)) {
|
||||
search_dir(path, pattern, out, hits, depth + 1);
|
||||
search_dir(real, pattern, out, hits, depth + 1, tr);
|
||||
continue;
|
||||
}
|
||||
if (!S_ISREG(st.st_mode) || st.st_size > TOOL_MAX_FILE)
|
||||
continue;
|
||||
f = fopen(path, "r");
|
||||
f = fopen(real, "r");
|
||||
if (f == NULL)
|
||||
continue;
|
||||
while (fgets(line, sizeof(line), f) != NULL) {
|
||||
if (strstr(line, pattern) == NULL)
|
||||
continue;
|
||||
sp_buf_printf(out, "%s: %s", path, line);
|
||||
sp_buf_printf(out, "%s: %s", real, line);
|
||||
if (out->len > 0 && out->p[out->len - 1] != '\n')
|
||||
sp_buf_puts(out, "\n");
|
||||
(*hits)++;
|
||||
@@ -793,9 +1146,9 @@ tool_search(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
struct sp_buf keep, pbuf;
|
||||
const char *pattern, *root;
|
||||
char real[TOOL_ROOT_MAX];
|
||||
int hits = 0;
|
||||
|
||||
(void)ctx;
|
||||
if (sp_buf_init(&keep) != 0 || sp_buf_init(&pbuf) != 0)
|
||||
return -1;
|
||||
pattern = arg_text(args, "pattern", &keep);
|
||||
@@ -805,7 +1158,14 @@ tool_search(const char *args, struct sp_buf *out, void *ctx)
|
||||
sp_buf_free(&pbuf);
|
||||
return sp_buf_puts(out, "error: 'pattern' is required");
|
||||
}
|
||||
search_dir(root != NULL ? root : ".", pattern, out, &hits, 0);
|
||||
if (root == NULL)
|
||||
root = ".";
|
||||
if (!path_checked(ctx, root, real, sizeof(real), out)) {
|
||||
sp_buf_free(&keep);
|
||||
sp_buf_free(&pbuf);
|
||||
return 0;
|
||||
}
|
||||
search_dir(real, pattern, out, &hits, 0, ctx);
|
||||
if (hits == 0)
|
||||
sp_buf_puts(out, "(no match)");
|
||||
sp_buf_free(&keep);
|
||||
@@ -818,16 +1178,21 @@ tool_list(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
struct sp_buf keep;
|
||||
const char *path;
|
||||
char real[TOOL_ROOT_MAX];
|
||||
DIR *d;
|
||||
struct dirent *e;
|
||||
int n = 0;
|
||||
|
||||
(void)ctx;
|
||||
if (sp_buf_init(&keep) != 0)
|
||||
return -1;
|
||||
path = arg_text(args, "path", &keep);
|
||||
if (path == NULL)
|
||||
path = ".";
|
||||
if (!path_checked(ctx, path, real, sizeof(real), out)) {
|
||||
sp_buf_free(&keep);
|
||||
return 0;
|
||||
}
|
||||
path = real;
|
||||
d = opendir(path);
|
||||
if (d == NULL) {
|
||||
sp_buf_printf(out, "error: %s: %s", path, strerror(errno));
|
||||
@@ -835,7 +1200,7 @@ tool_list(const char *args, struct sp_buf *out, void *ctx)
|
||||
return 0;
|
||||
}
|
||||
while ((e = readdir(d)) != NULL && n < 300) {
|
||||
char full[1024];
|
||||
char full[TOOL_ROOT_MAX + 300]; /* root path + '/' + a name */
|
||||
struct stat st;
|
||||
|
||||
if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0)
|
||||
@@ -1095,10 +1460,44 @@ tool_webfetch(const char *args, struct sp_buf *out, void *ctx)
|
||||
}
|
||||
|
||||
|
||||
int
|
||||
sp_builtin_register(struct sp_registry *r)
|
||||
/*
|
||||
* Register one file tool with its own copy of the root.
|
||||
*
|
||||
* One struct per tool, because sp_registry_free() calls dispose once per tool:
|
||||
* a shared pointer would be freed as often as it was registered. Every
|
||||
* allocation happens before the tool is added, so a failure here leaves the
|
||||
* registry as it was.
|
||||
*/
|
||||
static int
|
||||
add_file_tool(struct sp_registry *r, const char *root, const char *name,
|
||||
const char *desc, const char *params, enum sp_auth auth, sp_tool_run fn)
|
||||
{
|
||||
struct sp_tool t;
|
||||
struct tool_root *tr;
|
||||
|
||||
tr = tool_root_new(root);
|
||||
if (tr == NULL)
|
||||
return -1;
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.name = name;
|
||||
t.description = desc;
|
||||
t.params = params;
|
||||
t.auth = auth;
|
||||
t.run = fn;
|
||||
t.ctx = tr;
|
||||
t.dispose = tool_root_free;
|
||||
if (sp_registry_add(r, &t) != 0) {
|
||||
tool_root_free(&t);
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_builtin_register(struct sp_registry *r, const char *root)
|
||||
{
|
||||
struct sp_tool t;
|
||||
int rc = 0;
|
||||
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.name = "echo";
|
||||
@@ -1148,69 +1547,57 @@ sp_builtin_register(struct sp_registry *r)
|
||||
"\"required\":[\"command\"]}";
|
||||
t.auth = SP_AUTH_DESTRUCTIVE;
|
||||
t.run = tool_run;
|
||||
if (sp_registry_add(r, &t) != 0)
|
||||
/* the shell gets the root as its working directory, not as a fence */
|
||||
t.ctx = tool_root_new(root);
|
||||
t.dispose = tool_root_free;
|
||||
if (t.ctx == NULL || (rc = sp_registry_add(r, &t)) != 0) {
|
||||
tool_root_free(&t);
|
||||
return -1;
|
||||
}
|
||||
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.name = "read";
|
||||
t.description = "Read a text file. Returns numbered lines and says "
|
||||
"where it stopped.";
|
||||
t.params = "{\"type\":\"object\",\"properties\":{"
|
||||
if (add_file_tool(r, root, "read",
|
||||
"Read a text file. Returns numbered lines and says where it stopped.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"path\":{\"type\":\"string\",\"description\":\"file to read\"},"
|
||||
"\"offset\":{\"type\":\"integer\",\"description\":\"first line, 1-based\"},"
|
||||
"\"limit\":{\"type\":\"integer\",\"description\":\"max lines\"}},"
|
||||
"\"required\":[\"path\"]}";
|
||||
t.auth = SP_AUTH_READ;
|
||||
t.run = tool_read;
|
||||
if (sp_registry_add(r, &t) != 0)
|
||||
"\"required\":[\"path\"]}",
|
||||
SP_AUTH_READ, tool_read) != 0)
|
||||
return -1;
|
||||
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.name = "write";
|
||||
t.description = "Write a file, replacing it if it exists.";
|
||||
t.params = "{\"type\":\"object\",\"properties\":{"
|
||||
if (add_file_tool(r, root, "write",
|
||||
"Write a file, replacing it if it exists.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"path\":{\"type\":\"string\"},"
|
||||
"\"content\":{\"type\":\"string\"}},"
|
||||
"\"required\":[\"path\",\"content\"]}";
|
||||
t.auth = SP_AUTH_MUTATE;
|
||||
t.run = tool_write;
|
||||
if (sp_registry_add(r, &t) != 0)
|
||||
"\"required\":[\"path\",\"content\"]}",
|
||||
SP_AUTH_MUTATE, tool_write) != 0)
|
||||
return -1;
|
||||
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.name = "edit";
|
||||
t.description = "Replace one occurrence of 'old' with 'new'. Refuses "
|
||||
"when 'old' is not unique.";
|
||||
t.params = "{\"type\":\"object\",\"properties\":{"
|
||||
if (add_file_tool(r, root, "edit",
|
||||
"Replace one occurrence of 'old' with 'new'. Refuses when 'old' is "
|
||||
"not unique.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"path\":{\"type\":\"string\"},"
|
||||
"\"old\":{\"type\":\"string\",\"description\":\"exact text to replace\"},"
|
||||
"\"new\":{\"type\":\"string\",\"description\":\"replacement\"}},"
|
||||
"\"required\":[\"path\",\"old\",\"new\"]}";
|
||||
t.auth = SP_AUTH_MUTATE;
|
||||
t.run = tool_edit;
|
||||
if (sp_registry_add(r, &t) != 0)
|
||||
"\"required\":[\"path\",\"old\",\"new\"]}",
|
||||
SP_AUTH_MUTATE, tool_edit) != 0)
|
||||
return -1;
|
||||
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.name = "search";
|
||||
t.description = "Search files under a directory for a literal string.";
|
||||
t.params = "{\"type\":\"object\",\"properties\":{"
|
||||
if (add_file_tool(r, root, "search",
|
||||
"Search files under a directory for a literal string.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"pattern\":{\"type\":\"string\"},"
|
||||
"\"path\":{\"type\":\"string\",\"description\":\"directory, default .\"}},"
|
||||
"\"required\":[\"pattern\"]}";
|
||||
t.auth = SP_AUTH_READ;
|
||||
t.run = tool_search;
|
||||
if (sp_registry_add(r, &t) != 0)
|
||||
"\"required\":[\"pattern\"]}",
|
||||
SP_AUTH_READ, tool_search) != 0)
|
||||
return -1;
|
||||
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.name = "list";
|
||||
t.description = "List a directory.";
|
||||
t.params = "{\"type\":\"object\",\"properties\":{"
|
||||
"\"path\":{\"type\":\"string\",\"description\":\"directory, default .\"}}}";
|
||||
t.auth = SP_AUTH_READ;
|
||||
t.run = tool_list;
|
||||
if (sp_registry_add(r, &t) != 0)
|
||||
if (add_file_tool(r, root, "list", "List a directory.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"path\":{\"type\":\"string\",\"description\":\"directory, default .\"}}}",
|
||||
SP_AUTH_READ, tool_list) != 0)
|
||||
return -1;
|
||||
|
||||
return 0;
|
||||
@@ -28,6 +28,7 @@
|
||||
|
||||
#include "splinter.h"
|
||||
#include "cmdscript.h"
|
||||
#include "i18n.h"
|
||||
|
||||
#define CMD_TIMEOUT_MS 300000
|
||||
#define CMD_MAX_BYTES (4u << 20)
|
||||
@@ -194,7 +195,8 @@ sp_cmdscript_run(const char *dir, const char *name, const char *args,
|
||||
/*
|
||||
* The entry point UI and gateway share: run /name and hand back the text the
|
||||
* model should see, already framed so it cannot be mistaken for the user's own
|
||||
* words.
|
||||
* words. 0 with the text in 'out'; -1 when the program could not run (or ran
|
||||
* out of time), with the reason in 'err' for the operator.
|
||||
*/
|
||||
int
|
||||
sp_slash_script(const char *dir, const char *name, const char *args,
|
||||
@@ -202,21 +204,31 @@ sp_slash_script(const char *dir, const char *name, const char *args,
|
||||
{
|
||||
struct sp_buf raw, errb;
|
||||
|
||||
(void)err;
|
||||
if (sp_buf_init(&raw) != 0 || sp_buf_init(&errb) != 0)
|
||||
if (sp_buf_init(&raw) != 0)
|
||||
return -1;
|
||||
if (sp_buf_init(&errb) != 0) {
|
||||
sp_buf_free(&raw);
|
||||
return -1;
|
||||
}
|
||||
if (sp_cmdscript_run(dir, name, args, &raw, &errb) != 0) {
|
||||
sp_buf_printf(out, "error: %s", errb.p != NULL ? errb.p : "failed");
|
||||
if (err != NULL)
|
||||
sp_buf_printf(err, sp_td("cmd.script.failed",
|
||||
"/%s failed: %s"), name,
|
||||
errb.p != NULL && errb.len > 0 ? errb.p : "?");
|
||||
sp_buf_free(&raw);
|
||||
sp_buf_free(&errb);
|
||||
return 0;
|
||||
return -1;
|
||||
}
|
||||
if (raw.p == NULL || raw.p[0] == '\0')
|
||||
sp_buf_printf(out, "Der Befehl /%s hat nichts ausgegeben.", name);
|
||||
else
|
||||
sp_buf_printf(out, "Ausgabe von /%s%s%s:\n\n%s", name,
|
||||
sp_buf_printf(out, sp_td("cmd.script.empty",
|
||||
"The command /%s printed nothing."), name);
|
||||
else {
|
||||
sp_buf_printf(out, sp_td("cmd.script.output",
|
||||
"Output of /%s%s%s:"), name,
|
||||
args != NULL && *args != '\0' ? " " : "",
|
||||
args != NULL ? args : "", raw.p);
|
||||
args != NULL ? args : "");
|
||||
sp_buf_printf(out, "\n\n%s", raw.p);
|
||||
}
|
||||
sp_buf_free(&raw);
|
||||
sp_buf_free(&errb);
|
||||
return 0;
|
||||
File renamed without changes.
@@ -0,0 +1,540 @@
|
||||
/*
|
||||
* splinter -- compact: the compactor the core owns.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Compaction used to live only in the lcm plugin, which made `compact_threshold`
|
||||
* and `compact_target` dead settings: the agent read them, built a budget from
|
||||
* them, and handed it to a compactor list that was empty unless a plugin had
|
||||
* been loaded. A harness whose own configuration does nothing is worse than one
|
||||
* that has no such configuration, because the operator believes it is working.
|
||||
*
|
||||
* So the core carries a compactor of its own, and it runs when no plugin does.
|
||||
*
|
||||
* Two things were learned the hard way, and they shape everything below.
|
||||
*
|
||||
* 1. A cut that leaves only a statistic line loses the thread. lcm replaced the
|
||||
* dropped range with "[lcm] 42 messages compacted out (user 12, ...)" and
|
||||
* quoted 120 characters of the oldest one. The model then no longer knew what
|
||||
* the work was, re-asked, and the operator called it "losing the fade" - a
|
||||
* correct complaint. What has to survive is not a count, it is the story:
|
||||
* who asked what, in order.
|
||||
*
|
||||
* 2. Tool output is where the bytes are, and the head of an observation is the
|
||||
* part that matters. Trimming bodies saves most of the budget before any
|
||||
* message has to go.
|
||||
*
|
||||
* So the order of work is:
|
||||
*
|
||||
* 1. trim every tool body outside the verbatim tail
|
||||
* 2. still over budget: build a THREAD DIGEST of the dropped range. Every user
|
||||
* message survives nearly whole; every assistant turn keeps its opening;
|
||||
* every observation is reduced to a line. The digest is one system message.
|
||||
* 3. the newest real user message is pinned after the digest, so the question
|
||||
* being answered is never something the model has to infer.
|
||||
* 4. if the digest plus the tail still exceeds the budget, the caps shrink
|
||||
* step by step, cheapest role first. The digest is never dropped whole.
|
||||
*
|
||||
* Nothing here calls a second model: a summary that costs a request and makes a
|
||||
* run unreproducible is a different feature, not a flag on this one.
|
||||
*
|
||||
* The tail boundary never lands on a "tool" message: its assistant turn carries
|
||||
* the tool_call, and a provider rejects an orphaned tool result with a 400.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
|
||||
#define COMPACT_KEEP_TAIL 6 /* messages always kept verbatim */
|
||||
#define COMPACT_KEEP_HEAD 8 /* leading system messages never digested */
|
||||
#define COMPACT_TOOL_TRIM 2048 /* a tool body outside the tail */
|
||||
|
||||
/* Per-role caps inside the digest. User text is the thread: keep it nearly
|
||||
* whole. An assistant turn is mostly restating its tool call, so its opening
|
||||
* is enough. An observation is already trimmed by then. */
|
||||
#define CAP_USER 800
|
||||
#define CAP_ASSISTANT 300
|
||||
#define CAP_TOOL 160
|
||||
#define CAP_MIN_USER 120
|
||||
#define CAP_MIN_ASSISTANT 40
|
||||
#define CAP_MIN_TOOL 0
|
||||
|
||||
struct caps {
|
||||
size_t user;
|
||||
size_t assistant;
|
||||
size_t tool;
|
||||
};
|
||||
|
||||
static size_t
|
||||
msg_bytes(const struct sp_msg *m)
|
||||
{
|
||||
size_t n = 16; /* JSON scaffolding, estimated */
|
||||
|
||||
n += m->role != NULL ? strlen(m->role) : 0;
|
||||
n += m->name != NULL ? strlen(m->name) : 0;
|
||||
n += m->content != NULL ? strlen(m->content) : 0;
|
||||
n += m->calls != NULL ? strlen(m->calls) : 0;
|
||||
return n;
|
||||
}
|
||||
|
||||
static int
|
||||
is_role(const struct sp_msg *m, const char *role)
|
||||
{
|
||||
return m->role != NULL && strcmp(m->role, role) == 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The engine's own continuation prompt ("Continue with the task ...") arrives as
|
||||
* a user message but is not the question. Pinning it keeps the keystroke and
|
||||
* loses the task it was meant to continue - measured on a session resumed after
|
||||
* a rate limit, which woke up with the prompt, one tool call and no task.
|
||||
*/
|
||||
static int
|
||||
is_continuation(const struct sp_msg *m)
|
||||
{
|
||||
static const char *prefix[] = {
|
||||
"Continue with the task",
|
||||
"Setze die Aufgabe",
|
||||
NULL
|
||||
};
|
||||
size_t i;
|
||||
|
||||
if (m->content == NULL)
|
||||
return 0;
|
||||
for (i = 0; prefix[i] != NULL; i++)
|
||||
if (strncmp(m->content, prefix[i], strlen(prefix[i])) == 0)
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Cut long tool outputs in [from, to). The head of an observation is the part
|
||||
* worth keeping: a tool prints its answer, then a stack of context. The marker
|
||||
* says the cut happened, so a model does not read a trimmed result as complete.
|
||||
*/
|
||||
static int
|
||||
trim_tools(struct sp_conv *conv, size_t from, size_t to, size_t limit)
|
||||
{
|
||||
size_t i;
|
||||
int trimmed = 0;
|
||||
|
||||
for (i = from; i < to; i++) {
|
||||
struct sp_msg *m = &conv->v[i];
|
||||
size_t len;
|
||||
char *cut;
|
||||
|
||||
if (!is_role(m, "tool") || m->content == NULL)
|
||||
continue;
|
||||
len = strlen(m->content);
|
||||
if (len <= limit)
|
||||
continue;
|
||||
cut = malloc(limit + 96);
|
||||
if (cut == NULL)
|
||||
return trimmed;
|
||||
memcpy(cut, m->content, limit);
|
||||
snprintf(cut + limit, 96, "\n[... %zu bytes trimmed by compaction]",
|
||||
len - limit);
|
||||
free(m->content);
|
||||
m->content = cut;
|
||||
trimmed++;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/* Append text with newlines flattened to spaces: the digest is a transcript of
|
||||
* one message, not a document with its own layout. */
|
||||
static void
|
||||
append_flat(struct sp_buf *b, const char *s, size_t cap)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (s == NULL)
|
||||
return;
|
||||
for (i = 0; i < cap && s[i] != '\0'; i++) {
|
||||
char c = s[i];
|
||||
|
||||
if (c == '\n' || c == '\r' || c == '\t')
|
||||
c = ' ';
|
||||
sp_buf_add(b, &c, 1);
|
||||
}
|
||||
if (s[i] != '\0')
|
||||
sp_buf_puts(b, "...");
|
||||
}
|
||||
|
||||
/*
|
||||
* The thread: one line per dropped message, in order. A user turn gets its
|
||||
* opening nearly whole - that is the task and the corrections to it. An
|
||||
* assistant turn gets its opening, which is what it claimed to be doing. An
|
||||
* observation gets enough to recognise it.
|
||||
*/
|
||||
/*
|
||||
* Does the registry offer history_search? Passed in rather than looked up here,
|
||||
* because build_digest runs inside the shrink loop and the answer never changes.
|
||||
*/
|
||||
static int
|
||||
build_digest(struct sp_conv *conv, size_t from, size_t to, struct caps caps,
|
||||
int searchable, struct sp_buf *out)
|
||||
{
|
||||
size_t i;
|
||||
size_t users = 0, assistants = 0, tools = 0, other = 0;
|
||||
|
||||
if (sp_buf_init(out) != 0)
|
||||
return -1;
|
||||
for (i = from; i < to; i++) {
|
||||
if (is_role(&conv->v[i], "user"))
|
||||
users++;
|
||||
else if (is_role(&conv->v[i], "assistant"))
|
||||
assistants++;
|
||||
else if (is_role(&conv->v[i], "tool"))
|
||||
tools++;
|
||||
else
|
||||
other++;
|
||||
}
|
||||
sp_buf_puts(out, "[thread so far - compacted] ");
|
||||
sp_buf_printf(out, "%zu earlier messages: %zu from the operator, %zu "
|
||||
"assistant turns, %zu tool results", to - from, users, assistants,
|
||||
tools);
|
||||
if (other > 0)
|
||||
sp_buf_printf(out, ", %zu other", other);
|
||||
sp_buf_puts(out, ". In order:\n");
|
||||
/*
|
||||
* Say where the rest went. Without this line the model reads a summary
|
||||
* that stops mid-thought and believes that is all there ever was: it
|
||||
* re-asks the operator what the operator already answered, which is the
|
||||
* exact complaint ("losing the fade") this digest exists to fix. The
|
||||
* tool is named only when it is really registered - a prompt pointing at
|
||||
* a missing tool teaches the model to call nothing.
|
||||
*/
|
||||
if (searchable)
|
||||
sp_buf_puts(out, "\n[The full transcript is still on disk. "
|
||||
"Call history_search with the words of what you are looking "
|
||||
"for to get it back: it searches this whole session by "
|
||||
"meaning, not just what is quoted here.]\n");
|
||||
|
||||
for (i = from; i < to; i++) {
|
||||
struct sp_msg *m = &conv->v[i];
|
||||
|
||||
if (is_role(m, "user")) {
|
||||
sp_buf_puts(out, "\nOPERATOR: ");
|
||||
append_flat(out, m->content, caps.user);
|
||||
} else if (is_role(m, "assistant")) {
|
||||
if (m->content == NULL && m->calls != NULL)
|
||||
continue; /* a bare tool call says nothing yet */
|
||||
sp_buf_puts(out, "\n assistant: ");
|
||||
append_flat(out, m->content, caps.assistant);
|
||||
} else if (is_role(m, "tool")) {
|
||||
if (caps.tool == 0)
|
||||
continue;
|
||||
sp_buf_puts(out, "\n ");
|
||||
if (m->name != NULL) {
|
||||
sp_buf_puts(out, m->name);
|
||||
sp_buf_puts(out, " -> ");
|
||||
} else
|
||||
sp_buf_puts(out, "tool -> ");
|
||||
append_flat(out, m->content, caps.tool);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Free the strings of [from, to) and close the gap. The vector, not the count. */
|
||||
static void
|
||||
drop_range(struct sp_conv *conv, size_t from, size_t to)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = from; i < to; i++) {
|
||||
free(conv->v[i].role);
|
||||
free(conv->v[i].name);
|
||||
free(conv->v[i].call_id);
|
||||
free(conv->v[i].content);
|
||||
free(conv->v[i].calls);
|
||||
}
|
||||
memmove(&conv->v[from], &conv->v[to],
|
||||
(conv->n - to) * sizeof(*conv->v));
|
||||
conv->n = from + (conv->n - to);
|
||||
}
|
||||
|
||||
/* Bytes that [from, to) currently costs. */
|
||||
static size_t
|
||||
range_bytes(struct sp_conv *conv, size_t from, size_t to)
|
||||
{
|
||||
size_t i, total = 0;
|
||||
|
||||
for (i = from; i < to; i++)
|
||||
total += msg_bytes(&conv->v[i]);
|
||||
return total;
|
||||
}
|
||||
|
||||
static int
|
||||
core_compact(struct sp_host *h, struct sp_conv *conv, size_t budget,
|
||||
unsigned turn)
|
||||
{
|
||||
struct sp_buf digest;
|
||||
struct sp_registry *reg;
|
||||
int searchable;
|
||||
struct caps caps;
|
||||
size_t bytes, drop_bytes, tail_bytes;
|
||||
char *best_p = NULL;
|
||||
size_t best_len = 0;
|
||||
size_t first, keep_from;
|
||||
long pin_at = -1;
|
||||
char *pin_content = NULL;
|
||||
char *pin_name = NULL;
|
||||
size_t pin_extra = 0;
|
||||
int trimmed, pinned = 0;
|
||||
int attempt;
|
||||
|
||||
(void)turn;
|
||||
/*
|
||||
* Whether the escape hatch exists decides whether the digest advertises
|
||||
* it. The embedding index is on by default, but `embed = off` is a
|
||||
* supported choice and the prompt must not lie about it.
|
||||
*/
|
||||
reg = h != NULL ? sp_host_registry(h) : NULL;
|
||||
searchable = reg != NULL && sp_registry_find(reg, "history_search") != NULL;
|
||||
if (conv == NULL || conv->n == 0 || budget == 0)
|
||||
return 0;
|
||||
bytes = sp_conv_bytes(conv);
|
||||
|
||||
if (bytes <= budget)
|
||||
return 0; /* fits: nothing to do */
|
||||
if (conv->n <= COMPACT_KEEP_TAIL + 1)
|
||||
return 0; /* too short to cut anything meaningful */
|
||||
|
||||
/*
|
||||
* The leading system messages stay. Plural, because a compactor plugin
|
||||
* that ran before this one put its own summary there - lcm's "[lcm] 42
|
||||
* messages compacted out", cps' plan. That message is the result of work
|
||||
* somebody already paid for, and digesting it away would replace the
|
||||
* plugin's summary with a worse one. The cap keeps a pathological lead of
|
||||
* system messages from eating the whole budget.
|
||||
*/
|
||||
for (first = 0; first < conv->n && first < COMPACT_KEEP_HEAD &&
|
||||
is_role(&conv->v[first], "system"); first++)
|
||||
;
|
||||
keep_from = conv->n - COMPACT_KEEP_TAIL;
|
||||
/*
|
||||
* The tail must not begin with a tool result: its assistant turn, the
|
||||
* one carrying the tool_call, would be cut away and a provider answers
|
||||
* an orphaned tool message with a 400. Walk BACK to that assistant
|
||||
* rather than forward past the results.
|
||||
*
|
||||
* Forward was the first try and it quietly broke the promise this
|
||||
* constant makes: a turn with two tool results in the tail boundary
|
||||
* kept four messages instead of six, because each result pushed the
|
||||
* start further in. Measured on system + user + [assistant, tool, tool]
|
||||
* x4 + user: 15 messages, tail of six, result was a tail of four. Going
|
||||
* back costs the bytes of one call record and keeps the size.
|
||||
*/
|
||||
while (keep_from < conv->n && keep_from > first &&
|
||||
is_role(&conv->v[keep_from], "tool"))
|
||||
keep_from--;
|
||||
if (keep_from >= conv->n || keep_from <= first)
|
||||
return 0;
|
||||
|
||||
/* 1. trim every tool body outside the verbatim tail */
|
||||
trimmed = trim_tools(conv, first, conv->n, COMPACT_TOOL_TRIM);
|
||||
bytes = sp_conv_bytes(conv);
|
||||
if (bytes <= budget)
|
||||
return trimmed > 0 ? 1 : 0;
|
||||
|
||||
/* 2. the question being answered, pinned after the digest */
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = conv->n; i > first; i--) {
|
||||
if (!is_role(&conv->v[i - 1], "user"))
|
||||
continue;
|
||||
if (is_continuation(&conv->v[i - 1]))
|
||||
continue;
|
||||
pin_at = (long)(i - 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (pin_at >= 0 && (size_t)pin_at >= keep_from) {
|
||||
/* it is already in the verbatim tail: nothing to pin */
|
||||
pin_at = -1;
|
||||
}
|
||||
if (pin_at >= 0) {
|
||||
pin_content = strdup(conv->v[pin_at].content != NULL ?
|
||||
conv->v[pin_at].content : "");
|
||||
if (conv->v[pin_at].name != NULL)
|
||||
pin_name = strdup(conv->v[pin_at].name);
|
||||
pinned = pin_content != NULL;
|
||||
if (pinned)
|
||||
pin_extra = strlen(pin_content) +
|
||||
(pin_name != NULL ? strlen(pin_name) : 0) + 20;
|
||||
}
|
||||
|
||||
caps.user = CAP_USER;
|
||||
caps.assistant = CAP_ASSISTANT;
|
||||
caps.tool = CAP_TOOL;
|
||||
|
||||
/*
|
||||
* What the digest has to beat is not the budget - it is what it replaces.
|
||||
* If it costs more than the range it stands in for, the rewrite makes the
|
||||
* conversation bigger and the next request pays for nothing. Shrink the
|
||||
* caps until the digest is smaller than the range, user text last: that is
|
||||
* the thread.
|
||||
*
|
||||
* The digest may also take at most its share of the budget, unless the
|
||||
* verbatim tail alone already leaves less room than that.
|
||||
*/
|
||||
/*
|
||||
* The digest has two hard limits, and it must satisfy both:
|
||||
*
|
||||
* a) smaller than the range it replaces, or the rewrite grows the
|
||||
* conversation and the next request pays for nothing
|
||||
* b) small enough that the digest plus the verbatim tail fits the
|
||||
* budget, or the turn is refused for exceeding it anyway
|
||||
*
|
||||
* (b) is the one that was missing: with a budget of 900 and a tail of
|
||||
* 1000 the digest could satisfy (a) all day and the request still went
|
||||
* out at 3776 bytes. When the tail alone already exceeds the budget,
|
||||
* (b) has no answer and (a) is the only rule left.
|
||||
*
|
||||
* Beyond those, the caps decide how much of the thread survives.
|
||||
* Shrinking them is a last resort: the thread IS the point, and a digest
|
||||
* that fits but says nothing is the failure this file exists to avoid.
|
||||
*/
|
||||
drop_bytes = range_bytes(conv, first, keep_from);
|
||||
tail_bytes = range_bytes(conv, keep_from, conv->n);
|
||||
{
|
||||
size_t room = drop_bytes > pin_extra + 64 ?
|
||||
drop_bytes - pin_extra - 64 : 0;
|
||||
size_t fit = budget > tail_bytes + pin_extra ?
|
||||
budget - tail_bytes - pin_extra : 0;
|
||||
|
||||
if (fit > 0 && fit < room)
|
||||
room = fit;
|
||||
|
||||
/*
|
||||
* Shrink until it fits, but keep the best attempt: when even the
|
||||
* smallest caps overshoot, the smallest digest is still worth more
|
||||
* than no thread at all. The best one is copied out as a plain
|
||||
* buffer, so ownership stays in one place.
|
||||
*/
|
||||
best_p = NULL;
|
||||
best_len = 0;
|
||||
for (attempt = 0; attempt < 16; attempt++) {
|
||||
if (build_digest(conv, first, keep_from, caps,
|
||||
searchable, &digest) != 0) {
|
||||
free(best_p);
|
||||
free(pin_content);
|
||||
free(pin_name);
|
||||
return -1;
|
||||
}
|
||||
if (digest.len == 0) {
|
||||
sp_buf_free(&digest);
|
||||
break;
|
||||
}
|
||||
if (best_p == NULL || digest.len < best_len) {
|
||||
char *copy = malloc(digest.len + 1);
|
||||
|
||||
if (copy != NULL) {
|
||||
memcpy(copy, digest.p, digest.len + 1);
|
||||
free(best_p);
|
||||
best_p = copy;
|
||||
best_len = digest.len;
|
||||
}
|
||||
}
|
||||
if (digest.len <= room) {
|
||||
sp_buf_free(&digest);
|
||||
break;
|
||||
}
|
||||
sp_buf_free(&digest);
|
||||
if (caps.tool > CAP_MIN_TOOL) {
|
||||
caps.tool = caps.tool / 2;
|
||||
continue;
|
||||
}
|
||||
if (caps.assistant > CAP_MIN_ASSISTANT) {
|
||||
caps.assistant = caps.assistant / 2;
|
||||
continue;
|
||||
}
|
||||
if (caps.user > CAP_MIN_USER) {
|
||||
caps.user = caps.user * 3 / 4;
|
||||
continue;
|
||||
}
|
||||
break; /* nothing left to shrink */
|
||||
}
|
||||
if (best_p == NULL) {
|
||||
free(pin_content);
|
||||
free(pin_name);
|
||||
return trimmed > 0 ? 1 : 0;
|
||||
}
|
||||
/*
|
||||
* Rule (a), enforced rather than merely computed. The shrink loop
|
||||
* stops at the minimum caps and keeps the smallest attempt even
|
||||
* when that attempt is still too big - and then the rewrite went
|
||||
* out anyway, replacing a short range with a longer digest plus a
|
||||
* pinned question. Measured on the case /resume produced: 317
|
||||
* bytes in, 476 bytes out, on a budget of 217. A compactor that
|
||||
* grows the conversation is worse than none, because the next
|
||||
* request pays for it and the turn is refused for size.
|
||||
*
|
||||
* There is nothing else to try at this point, so the honest
|
||||
* answer is "I could not help": the tool bodies were already
|
||||
* trimmed above, which is where the easy bytes were.
|
||||
*/
|
||||
if (best_len + pin_extra >= drop_bytes) {
|
||||
free(best_p);
|
||||
free(pin_content);
|
||||
free(pin_name);
|
||||
return trimmed > 0 ? 1 : 0;
|
||||
}
|
||||
if (sp_buf_init(&digest) != 0) {
|
||||
free(best_p);
|
||||
free(pin_content);
|
||||
free(pin_name);
|
||||
return -1;
|
||||
}
|
||||
sp_buf_add(&digest, best_p, best_len);
|
||||
free(best_p);
|
||||
}
|
||||
|
||||
drop_range(conv, first, keep_from);
|
||||
{
|
||||
struct sp_msg m;
|
||||
|
||||
memset(&m, 0, sizeof(m));
|
||||
m.role = "system";
|
||||
m.content = digest.p;
|
||||
if (sp_conv_insert(conv, first, &m) != 0) {
|
||||
sp_buf_free(&digest);
|
||||
free(pin_content);
|
||||
free(pin_name);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
if (pinned && pin_content != NULL && pin_content[0] != '\0') {
|
||||
struct sp_msg m;
|
||||
|
||||
memset(&m, 0, sizeof(m));
|
||||
m.role = "user";
|
||||
m.name = pin_name;
|
||||
m.content = pin_content;
|
||||
if (sp_conv_insert(conv, first + 1, &m) != 0) {
|
||||
sp_buf_free(&digest);
|
||||
free(pin_content);
|
||||
free(pin_name);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
sp_buf_free(&digest);
|
||||
free(pin_content);
|
||||
free(pin_name);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static const struct sp_compactor compact = { "compact", core_compact };
|
||||
|
||||
const struct sp_compactor *
|
||||
sp_core_compactor(void)
|
||||
{
|
||||
return &compact;
|
||||
}
|
||||
@@ -18,8 +18,10 @@ struct val {
|
||||
|
||||
struct ent {
|
||||
char key[48];
|
||||
char sub[96]; /* key NAME { ... }: the NAME */
|
||||
struct val v;
|
||||
unsigned line;
|
||||
int block; /* a nested { } block: items are A=b */
|
||||
};
|
||||
|
||||
struct cb {
|
||||
@@ -72,7 +74,8 @@ static void
|
||||
skip(struct cb *c, int nl)
|
||||
{
|
||||
for (;;) {
|
||||
if (*c->p == ' ' || *c->p == '\t' || *c->p == '\r')
|
||||
if (*c->p == ' ' || *c->p == '\t' || *c->p == '\r' ||
|
||||
*c->p == ';')
|
||||
c->p++;
|
||||
else if (*c->p == '\n' && nl) {
|
||||
c->line++;
|
||||
@@ -150,7 +153,8 @@ scalar(struct cb *c)
|
||||
} else {
|
||||
while (*c->p != '\0' && !isspace((unsigned char)*c->p) &&
|
||||
*c->p != '#' && *c->p != ',' && *c->p != ']' &&
|
||||
*c->p != '}' && *c->p != '[' && *c->p != '{') {
|
||||
*c->p != '}' && *c->p != '[' && *c->p != '{' &&
|
||||
*c->p != ';') {
|
||||
tmp[n] = *c->p++;
|
||||
if (n + 1 < sizeof(tmp))
|
||||
n++;
|
||||
@@ -277,6 +281,21 @@ clean(struct cb *c, const struct ent *e, const char *s)
|
||||
return 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* A core value becomes one "key = value" line: a newline in it would start a
|
||||
* second line, a key the block never named. '|' is harmless there (no field
|
||||
* line), so only line breaks are refused.
|
||||
*/
|
||||
static int
|
||||
clean_line(struct cb *c, const struct ent *e, const char *s)
|
||||
{
|
||||
if (strchr(s, '\n') != NULL || strchr(s, '\r') != NULL) {
|
||||
fail(c, e->line, "%s must not contain a newline", e->key);
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int
|
||||
in_list(const char *const *list, const char *k)
|
||||
{
|
||||
@@ -296,19 +315,24 @@ do_core(struct cb *c, struct ent *e, size_t n)
|
||||
char list[2048];
|
||||
|
||||
if (!strcmp(k, "plugins") || !strcmp(k, "skills")) {
|
||||
for (j = 0; j < e[i].v.n; j++)
|
||||
for (j = 0; j < e[i].v.n; j++) {
|
||||
if (!clean_line(c, &e[i], e[i].v.items[j]))
|
||||
return;
|
||||
emit(c, e[i].line, "%s = %s",
|
||||
k[0] == 'p' ? "plugin" : "skills_dir",
|
||||
e[i].v.items[j]);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (e[i].v.list) {
|
||||
joined(&e[i].v, list, sizeof(list));
|
||||
if (!clean_line(c, &e[i], list))
|
||||
return;
|
||||
emit(c, e[i].line, "%s = %s", k, list);
|
||||
continue;
|
||||
}
|
||||
s = one(c, &e[i]);
|
||||
if (s == NULL)
|
||||
if (s == NULL || !clean_line(c, &e[i], s))
|
||||
return;
|
||||
if (!strcmp(k, "autonomous") || !strcmp(k, "env_delegates"))
|
||||
emit(c, e[i].line, "%s = %d", k, boolean(s));
|
||||
@@ -322,7 +346,8 @@ do_provider(struct cb *c, const char *name, unsigned line, struct ent *e,
|
||||
size_t n)
|
||||
{
|
||||
static const char *const plain[] = { "kind", "cmd", "provider", "host",
|
||||
"endpoint", "model", "key_env", "prio", "max_parallel", "limit", "tokens", NULL };
|
||||
"endpoint", "model", "key_env", "ctx", "prio", "max_parallel",
|
||||
"limit", "tokens", NULL };
|
||||
struct sp_buf l;
|
||||
const char *about = "";
|
||||
size_t i, j;
|
||||
@@ -361,6 +386,12 @@ do_provider(struct cb *c, const char *name, unsigned line, struct ent *e,
|
||||
goto done;
|
||||
if (list[0] != '\0')
|
||||
sp_buf_printf(&l, " | tags=%s", list);
|
||||
} else if (!strcmp(k, "models")) {
|
||||
joined(&e[i].v, list, sizeof(list));
|
||||
if (!clean(c, &e[i], list))
|
||||
goto done;
|
||||
if (list[0] != '\0')
|
||||
sp_buf_printf(&l, " | models=%s", list);
|
||||
} else if (!strcmp(k, "key")) {
|
||||
/* the key itself, in the (0600) file: kept in a private
|
||||
* variable that key_env then names */
|
||||
@@ -459,6 +490,140 @@ done:
|
||||
sp_buf_free(&l);
|
||||
}
|
||||
|
||||
/* one setting of a plugin: plugin_conf = NAME | key=value */
|
||||
static void
|
||||
plugin_kv(struct cb *c, const struct ent *e, const char *plugin,
|
||||
const char *key, const char *val)
|
||||
{
|
||||
if (strchr(key, '=') != NULL || strchr(key, '|') != NULL) {
|
||||
fail(c, e->line, "bad plugin setting name '%s'", key);
|
||||
return;
|
||||
}
|
||||
if (!clean(c, e, val))
|
||||
return;
|
||||
emit(c, e->line, "plugin_conf = %s | %s=%s", plugin, key, val);
|
||||
}
|
||||
|
||||
/* plugin mcp { server ID { url = ... } }: the servers the mcp plugin runs */
|
||||
static void
|
||||
mcp_server(struct cb *c, const struct ent *e)
|
||||
{
|
||||
struct sp_buf l;
|
||||
size_t j;
|
||||
|
||||
if (e->sub[0] == '\0') {
|
||||
fail(c, e->line, "server needs a name: server NAME { url = ... }");
|
||||
return;
|
||||
}
|
||||
if (sp_buf_init(&l) != 0)
|
||||
return;
|
||||
sp_buf_printf(&l, "mcp = %s", e->sub);
|
||||
for (j = 0; j < e->v.n; j++) {
|
||||
const char *kv = e->v.items[j], *eq = strchr(kv, '=');
|
||||
size_t kl = eq != NULL ? (size_t)(eq - kv) : 0;
|
||||
|
||||
if (eq == NULL || !clean(c, e, kv))
|
||||
goto done;
|
||||
if ((kl == 3 && !strncmp(kv, "url", 3)) ||
|
||||
(kl == 3 && !strncmp(kv, "cmd", 3)) ||
|
||||
(kl == 6 && !strncmp(kv, "header", 6)))
|
||||
sp_buf_printf(&l, " | %s", kv);
|
||||
else if (kl == 7 && !strncmp(kv, "enabled", 7))
|
||||
sp_buf_printf(&l, " | enabled=%d", boolean(eq + 1));
|
||||
else {
|
||||
fail(c, e->line, "unknown mcp server field '%.*s'",
|
||||
(int)kl, kv);
|
||||
goto done;
|
||||
}
|
||||
}
|
||||
emit(c, e->line, "%s", l.p);
|
||||
done:
|
||||
sp_buf_free(&l);
|
||||
}
|
||||
|
||||
/*
|
||||
* plugin NAME { path = ... enabled = false anything = else }
|
||||
*
|
||||
* The block loads the plugin -- the shipped one for NAME unless 'path' names
|
||||
* another -- and everything else in it is the plugin's own configuration,
|
||||
* which it reads with sp_host_plugin_config(host, NAME, key).
|
||||
*/
|
||||
static void
|
||||
do_plugin(struct cb *c, const char *name, unsigned line, struct ent *e,
|
||||
size_t n)
|
||||
{
|
||||
const char *path = NULL;
|
||||
char full[1024], list[2048], key[200];
|
||||
size_t i, j;
|
||||
int on = 1;
|
||||
|
||||
for (i = 0; name[i] != '\0'; i++)
|
||||
if (!isalnum((unsigned char)name[i]) && name[i] != '_' &&
|
||||
name[i] != '-') {
|
||||
fail(c, line, "plugin name '%s': letters, digits, _ and - "
|
||||
"only", name);
|
||||
return;
|
||||
}
|
||||
for (i = 0; i < n && !c->failed; i++) {
|
||||
if (!strcmp(e[i].key, "path") && !e[i].block) {
|
||||
path = one(c, &e[i]);
|
||||
if (path != NULL && !clean(c, &e[i], path))
|
||||
return;
|
||||
} else if (!strcmp(e[i].key, "enabled") && !e[i].block) {
|
||||
const char *s = one(c, &e[i]);
|
||||
|
||||
if (s == NULL)
|
||||
return;
|
||||
on = boolean(s);
|
||||
}
|
||||
}
|
||||
if (c->failed || !on)
|
||||
return;
|
||||
if (path != NULL && path[0] == '~' && path[1] == '/' &&
|
||||
getenv("HOME") != NULL) {
|
||||
snprintf(full, sizeof(full), "%s%s", getenv("HOME"), path + 1);
|
||||
path = full;
|
||||
}
|
||||
/* a bare name is the shipped plugin: main.c looks it up */
|
||||
emit(c, line, "plugin = %s", path != NULL ? path : name);
|
||||
for (i = 0; i < n && !c->failed; i++) {
|
||||
const struct ent *x = &e[i];
|
||||
|
||||
if ((!strcmp(x->key, "path") || !strcmp(x->key, "enabled")) &&
|
||||
!x->block)
|
||||
continue;
|
||||
if (x->block) {
|
||||
if (!strcmp(name, "mcp") && !strcmp(x->key, "server")) {
|
||||
mcp_server(c, x);
|
||||
continue;
|
||||
}
|
||||
for (j = 0; j < x->v.n && !c->failed; j++) {
|
||||
const char *kv = x->v.items[j];
|
||||
const char *eq = strchr(kv, '=');
|
||||
|
||||
if (eq == NULL)
|
||||
continue;
|
||||
if (x->sub[0] != '\0')
|
||||
snprintf(key, sizeof(key), "%s.%s.%.*s",
|
||||
x->key, x->sub, (int)(eq - kv), kv);
|
||||
else
|
||||
snprintf(key, sizeof(key), "%s.%.*s",
|
||||
x->key, (int)(eq - kv), kv);
|
||||
plugin_kv(c, x, name, key, eq + 1);
|
||||
}
|
||||
} else if (x->v.list) {
|
||||
joined(&x->v, list, sizeof(list));
|
||||
plugin_kv(c, x, name, x->key, list);
|
||||
} else {
|
||||
const char *s = one(c, x);
|
||||
|
||||
if (s == NULL)
|
||||
return;
|
||||
plugin_kv(c, x, name, x->key, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
do_exit(struct cb *c, const char *name, unsigned line, struct ent *e, size_t n)
|
||||
{
|
||||
@@ -533,10 +698,30 @@ body(struct cb *c, struct ent *e, int *closed)
|
||||
snprintf(e[n].key, sizeof(e[n].key), "%s", key);
|
||||
e[n].line = line;
|
||||
skip(c, 0);
|
||||
if (*c->p != '{' && *c->p != '=' && *c->p != '\0' &&
|
||||
*c->p != '\n') {
|
||||
/* key NAME { ... }: a named nested block (server junction) */
|
||||
size_t m = 0;
|
||||
|
||||
while (isalnum((unsigned char)*c->p) || *c->p == '_' ||
|
||||
*c->p == '-' || *c->p == '.') {
|
||||
if (m + 1 < sizeof(e[n].sub))
|
||||
e[n].sub[m++] = *c->p;
|
||||
c->p++;
|
||||
}
|
||||
e[n].sub[m] = '\0';
|
||||
skip(c, 0);
|
||||
if (m == 0 || *c->p != '{') {
|
||||
fail(c, line, "expected '{' after %s %s", key,
|
||||
e[n].sub);
|
||||
return n;
|
||||
}
|
||||
}
|
||||
if (*c->p == '{') {
|
||||
/* env { A = b } */
|
||||
/* env { A = b }, server junction { url = ... } */
|
||||
c->p++;
|
||||
e[n].v.list = 1;
|
||||
e[n].block = 1;
|
||||
for (;;) {
|
||||
char nm[96];
|
||||
size_t m = 0;
|
||||
@@ -554,7 +739,8 @@ body(struct cb *c, struct ent *e, int *closed)
|
||||
return n;
|
||||
}
|
||||
vl = c->line;
|
||||
while (isalnum((unsigned char)*c->p) || *c->p == '_') {
|
||||
while (isalnum((unsigned char)*c->p) || *c->p == '_' ||
|
||||
*c->p == '-' || *c->p == '.') {
|
||||
if (m + 1 < sizeof(nm))
|
||||
nm[m++] = *c->p;
|
||||
c->p++;
|
||||
@@ -699,7 +885,7 @@ sp_confblock_translate(const char *text, const char *path, struct sp_buf *out,
|
||||
if (!c.failed && closed) {
|
||||
int needs_name = !strcmp(kind, "provider") ||
|
||||
!strcmp(kind, "pool") || !strcmp(kind, "exit") ||
|
||||
!strcmp(kind, "mcp");
|
||||
!strcmp(kind, "mcp") || !strcmp(kind, "plugin");
|
||||
|
||||
if (needs_name && name[0] == '\0')
|
||||
fail(&c, line, "%s needs a name: %s NAME { ... }",
|
||||
@@ -717,6 +903,13 @@ sp_confblock_translate(const char *text, const char *path, struct sp_buf *out,
|
||||
|
||||
joined(&e[i].v, list, sizeof(list));
|
||||
emit(&c, e[i].line, "telegram_allow = %s", list);
|
||||
} else if (!strcmp(e[i].key, "status_chat")) {
|
||||
const char *s = one(&c, &e[i]);
|
||||
|
||||
if (s == NULL || !clean(&c, &e[i], s))
|
||||
break;
|
||||
emit(&c, e[i].line,
|
||||
"telegram_status_chat = %s", s);
|
||||
} else
|
||||
fail(&c, e[i].line,
|
||||
"unknown telegram field '%s'", e[i].key);
|
||||
@@ -727,11 +920,14 @@ sp_confblock_translate(const char *text, const char *path, struct sp_buf *out,
|
||||
do_pool(&c, name, line, e, n);
|
||||
else if (!strcmp(kind, "exit"))
|
||||
do_exit(&c, name, line, e, n);
|
||||
else if (!strcmp(kind, "plugin"))
|
||||
do_plugin(&c, name, line, e, n);
|
||||
else if (!strcmp(kind, "mcp"))
|
||||
/* deprecated: plugin mcp { server ID { ... } } */
|
||||
do_mcp(&c, name, line, e, n);
|
||||
else
|
||||
fail(&c, line, "unknown block '%s' (core, telegram, "
|
||||
"provider, pool, exit, mcp)", kind);
|
||||
"provider, pool, exit, plugin)", kind);
|
||||
}
|
||||
ents_free(e, n);
|
||||
if (c.failed)
|
||||
File renamed without changes.
@@ -15,6 +15,7 @@
|
||||
#include <dirent.h>
|
||||
|
||||
#include "config.h"
|
||||
#include "embed.h"
|
||||
#include "usage.h"
|
||||
#include "confblock.h"
|
||||
|
||||
@@ -23,9 +24,40 @@ sp_config_init(struct sp_config *c)
|
||||
{
|
||||
memset(c, 0, sizeof(*c));
|
||||
c->autonomous = -1;
|
||||
/*
|
||||
* The index is on by default and it is the local encoder: the whole
|
||||
* point is that a session becomes searchable without a model, a key or
|
||||
* a network. `embed = off` turns it off; `embed = openai` swaps in a
|
||||
* trained encoder.
|
||||
*/
|
||||
c->embed = SP_EMBED_LOCAL;
|
||||
snprintf(c->key_env, sizeof(c->key_env), "SPLINTER_API_KEY");
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_config_state_dir(const struct sp_config *c)
|
||||
{
|
||||
static char buf[512];
|
||||
const char *home;
|
||||
|
||||
if (c != NULL && c->state_dir[0] != '\0')
|
||||
return c->state_dir;
|
||||
home = getenv("HOME");
|
||||
snprintf(buf, sizeof(buf), "%s/.splinter", home != NULL ? home : ".");
|
||||
return buf;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_config_session_dir(const struct sp_config *c)
|
||||
{
|
||||
static char buf[512];
|
||||
|
||||
if (c != NULL && c->session_dir[0] != '\0')
|
||||
return c->session_dir;
|
||||
snprintf(buf, sizeof(buf), "%s/sessions", sp_config_state_dir(c));
|
||||
return buf;
|
||||
}
|
||||
|
||||
int
|
||||
sp_config_path(char *buf, size_t len)
|
||||
{
|
||||
@@ -83,6 +115,29 @@ set_str(char *dst, size_t len, const char *src)
|
||||
snprintf(dst, len, "%s", src);
|
||||
}
|
||||
|
||||
/*
|
||||
* A setting that names a place on disk: "~/x" is the home directory and "~"
|
||||
* is home itself.
|
||||
*
|
||||
* The parser does not expand "~" - no shell is involved - so a config that
|
||||
* says "~/src" would otherwise fence the file tools against a directory
|
||||
* literally named "~". The shipped template suggests exactly that, so it has to
|
||||
* work. Only a leading "~/" (or a bare "~") is touched; a "~user" form is left
|
||||
* alone rather than half-guessed, because there is no portable way to look up
|
||||
* another user's home here.
|
||||
*/
|
||||
static void
|
||||
set_path(char *dst, size_t len, const char *src)
|
||||
{
|
||||
const char *home = getenv("HOME");
|
||||
|
||||
if (home != NULL && *home != '\0' && src[0] == '~' &&
|
||||
(src[1] == '/' || src[1] == '\0'))
|
||||
snprintf(dst, len, "%s%s", home, src + 1);
|
||||
else
|
||||
snprintf(dst, len, "%s", src);
|
||||
}
|
||||
|
||||
/*
|
||||
* delegate = id | what it is good at | tags=a,b | endpoint=... | model=...
|
||||
*
|
||||
@@ -289,8 +344,19 @@ parse_delegate(struct sp_delegate *d, const char *val, struct sp_buf *err,
|
||||
snprintf(d->endpoint, sizeof(d->endpoint), "%s", s + 9);
|
||||
else if (!strncmp(s, "model=", 6))
|
||||
snprintf(d->model, sizeof(d->model), "%s", s + 6);
|
||||
else if (!strncmp(s, "models=", 7))
|
||||
snprintf(d->models, sizeof(d->models), "%s", s + 7);
|
||||
else if (!strncmp(s, "key_env=", 8))
|
||||
snprintf(d->key_env, sizeof(d->key_env), "%s", s + 8);
|
||||
else if (!strncmp(s, "ctx=", 4)) {
|
||||
d->ctx = strtoul(s + 4, &end, 10);
|
||||
if (*end != '\0') {
|
||||
sp_buf_printf(err, "config: %s:%u: ctx= wants "
|
||||
"a number of tokens", path, lineno);
|
||||
free(copy);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else if (!strncmp(s, "env=", 4)) {
|
||||
if (add_env(d->env, &d->nenv, s + 4, err, path,
|
||||
lineno) != 0) {
|
||||
@@ -639,6 +705,16 @@ load_stream(struct sp_config *c, FILE *f, const char *path,
|
||||
set_str(c->endpoint, sizeof(c->endpoint), val);
|
||||
else if (!strcmp(key, "model"))
|
||||
set_str(c->model, sizeof(c->model), val);
|
||||
else if (!strcmp(key, "ctx")) {
|
||||
char *end;
|
||||
|
||||
c->ctx = strtoul(val, &end, 10);
|
||||
if (*end != '\0') {
|
||||
sp_buf_printf(err, "config: %s:%u: ctx wants "
|
||||
"a number of tokens", path, lineno);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else if (!strcmp(key, "api_key_env"))
|
||||
set_str(c->key_env, sizeof(c->key_env), val);
|
||||
else if (!strcmp(key, "kind")) {
|
||||
@@ -653,12 +729,10 @@ load_stream(struct sp_config *c, FILE *f, const char *path,
|
||||
}
|
||||
else if (!strcmp(key, "transport"))
|
||||
set_str(c->transport, sizeof(c->transport), val);
|
||||
else if (!strcmp(key, "memory_url"))
|
||||
set_str(c->memory_url, sizeof(c->memory_url), val);
|
||||
else if (!strcmp(key, "memory_key_env"))
|
||||
set_str(c->memory_key_env, sizeof(c->memory_key_env), val);
|
||||
else if (!strcmp(key, "telegram_allow"))
|
||||
set_str(c->telegram_allow, sizeof(c->telegram_allow), val);
|
||||
else if (!strcmp(key, "telegram_status_chat"))
|
||||
c->telegram_status_chat = strtol(val, NULL, 10);
|
||||
else if (!strcmp(key, "locale"))
|
||||
set_str(c->locale, sizeof(c->locale), val);
|
||||
else if (!strcmp(key, "theme"))
|
||||
@@ -666,7 +740,11 @@ load_stream(struct sp_config *c, FILE *f, const char *path,
|
||||
else if (!strcmp(key, "system_prompt"))
|
||||
set_str(c->system_prompt, sizeof(c->system_prompt), val);
|
||||
else if (!strcmp(key, "session_dir"))
|
||||
set_str(c->session_dir, sizeof(c->session_dir), val);
|
||||
set_path(c->session_dir, sizeof(c->session_dir), val);
|
||||
else if (!strcmp(key, "tools_root"))
|
||||
set_path(c->tools_root, sizeof(c->tools_root), val);
|
||||
else if (!strcmp(key, "state_dir"))
|
||||
set_path(c->state_dir, sizeof(c->state_dir), val);
|
||||
else if (!strcmp(key, "cli_cmd"))
|
||||
set_str(c->cli_cmd, sizeof(c->cli_cmd), val);
|
||||
else if (!strcmp(key, "cli_fallback"))
|
||||
@@ -712,6 +790,49 @@ load_stream(struct sp_config *c, FILE *f, const char *path,
|
||||
c->steps = (size_t)strtoul(val, NULL, 10);
|
||||
else if (!strcmp(key, "max_bytes"))
|
||||
c->max_bytes = (size_t)strtoul(val, NULL, 10);
|
||||
else if (!strcmp(key, "compact_threshold"))
|
||||
c->compact_threshold = (size_t)strtoul(val, NULL, 10);
|
||||
else if (!strcmp(key, "compact_target"))
|
||||
c->compact_target = (size_t)strtoul(val, NULL, 10);
|
||||
/*
|
||||
* The embedding index. `embed = local` is the built-in CPU
|
||||
* encoder (no model, no key), `openai` posts to
|
||||
* <embed_endpoint>/embeddings, `off` disables it.
|
||||
*/
|
||||
else if (!strcmp(key, "embed")) {
|
||||
if (!strcmp(val, "local") || !strcmp(val, "1") ||
|
||||
!strcmp(val, "true"))
|
||||
c->embed = SP_EMBED_LOCAL;
|
||||
else if (!strcmp(val, "openai") ||
|
||||
!strcmp(val, "remote"))
|
||||
c->embed = SP_EMBED_REMOTE;
|
||||
else if (!strcmp(val, "off") || !strcmp(val, "0") ||
|
||||
!strcmp(val, "false") || !strcmp(val, "none"))
|
||||
c->embed = SP_EMBED_OFF;
|
||||
else {
|
||||
sp_buf_printf(err, "config: %s:%u: embed is "
|
||||
"local, openai or off", path, lineno);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
else if (!strcmp(key, "embed_dims")) {
|
||||
long d = strtol(val, NULL, 10);
|
||||
|
||||
if (d < 8 || d > 4096) {
|
||||
sp_buf_printf(err, "config: %s:%u: embed_dims "
|
||||
"wants 8..4096", path, lineno);
|
||||
return -1;
|
||||
}
|
||||
c->embed_dims = (int)d;
|
||||
}
|
||||
else if (!strcmp(key, "embed_model"))
|
||||
set_str(c->embed_model, sizeof(c->embed_model), val);
|
||||
else if (!strcmp(key, "embed_endpoint"))
|
||||
set_str(c->embed_endpoint, sizeof(c->embed_endpoint), val);
|
||||
else if (!strcmp(key, "embed_key_env"))
|
||||
set_str(c->embed_key_env, sizeof(c->embed_key_env), val);
|
||||
else if (!strcmp(key, "embed_timeout"))
|
||||
c->embed_timeout = strtol(val, NULL, 10);
|
||||
else if (!strcmp(key, "http_timeout") ||
|
||||
!strcmp(key, "request_timeout"))
|
||||
c->http_timeout = strtol(val, NULL, 10);
|
||||
@@ -721,6 +842,8 @@ load_stream(struct sp_config *c, FILE *f, const char *path,
|
||||
c->delegate_timeout = strtol(val, NULL, 10);
|
||||
else if (!strcmp(key, "run_timeout"))
|
||||
c->run_timeout = strtol(val, NULL, 10);
|
||||
else if (!strcmp(key, "ask_timeout"))
|
||||
c->ask_timeout = strtol(val, NULL, 10);
|
||||
else if (!strcmp(key, "env_delegates"))
|
||||
c->env_delegates = (!strcmp(val, "1") ||
|
||||
!strcmp(val, "true") || !strcmp(val, "yes")) ? 1 : 0;
|
||||
@@ -734,8 +857,8 @@ load_stream(struct sp_config *c, FILE *f, const char *path,
|
||||
SP_CONFIG_MAX_DELEGATES);
|
||||
return -1;
|
||||
}
|
||||
snprintf(c->skills_dir[c->nskills_dir++],
|
||||
sizeof(c->skills_dir[0]), "%s", val);
|
||||
set_path(c->skills_dir[c->nskills_dir++],
|
||||
sizeof(c->skills_dir[0]), val);
|
||||
}
|
||||
else if (!strcmp(key, "exit")) {
|
||||
if (c->nexits == SP_CONFIG_MAX_DELEGATES) {
|
||||
@@ -776,6 +899,29 @@ load_stream(struct sp_config *c, FILE *f, const char *path,
|
||||
}
|
||||
else if (!strcmp(key, "default"))
|
||||
set_str(c->default_id, sizeof(c->default_id), val);
|
||||
else if (!strcmp(key, "plugin_conf")) {
|
||||
/* plugin_conf = NAME | key=value (from a plugin { } block) */
|
||||
struct sp_plugin_kv *kv;
|
||||
char *bar = strstr(val, " | "), *eq2;
|
||||
|
||||
if (bar == NULL || (eq2 = strchr(bar + 3, '=')) == NULL) {
|
||||
sp_buf_printf(err, "config: %s:%u: plugin_conf "
|
||||
"wants NAME | key=value", path, lineno);
|
||||
return -1;
|
||||
}
|
||||
if (c->nplugin_conf == SP_CONFIG_MAX_PLUGIN_KV) {
|
||||
sp_buf_printf(err, "config: %s:%u: more than %d "
|
||||
"plugin settings", path, lineno,
|
||||
SP_CONFIG_MAX_PLUGIN_KV);
|
||||
return -1;
|
||||
}
|
||||
kv = &c->plugin_conf[c->nplugin_conf++];
|
||||
*bar = '\0';
|
||||
*eq2 = '\0';
|
||||
set_str(kv->plugin, sizeof(kv->plugin), trim(val));
|
||||
set_str(kv->key, sizeof(kv->key), trim(bar + 3));
|
||||
set_str(kv->val, sizeof(kv->val), eq2 + 1);
|
||||
}
|
||||
else if (!strcmp(key, "plugin")) {
|
||||
if (c->nplugins == SP_CONFIG_MAX_PLUGINS) {
|
||||
sp_buf_printf(err, "config: %s:%u: more than %d "
|
||||
@@ -838,20 +984,34 @@ sp_config_write_example(const char *path, struct sp_buf *err)
|
||||
"\n"
|
||||
"core {\n"
|
||||
" default = local # a provider or pool below; -m overrides\n"
|
||||
" theme = Delphinium # splinter --list-themes\n"
|
||||
" theme = light # Xresources or a CDE palette, --list-themes\n"
|
||||
" autonomous = false # true: run mutating tools without asking\n"
|
||||
" #locale = de\n"
|
||||
" steps = 150 # tool rounds per turn\n"
|
||||
" #max_bytes = 0 # conversation budget, 0 = none\n"
|
||||
" #session_dir = ~/.splinter\n"
|
||||
" #tools_root = ~/src # file tools stay here; empty = no fence\n"
|
||||
"\n"
|
||||
" # A usage limit is waited out: splinter finds the reset and goes on.\n"
|
||||
" #on_limit = wait # or fail\n"
|
||||
" #max_wait = 12h\n"
|
||||
"\n"
|
||||
" #plugins = [plugins/lcm/lcm.so, plugins/cps/cps.so]\n"
|
||||
" # The session index behind history_search. `local` is built in and\n"
|
||||
" # needs no model: feature hashing on the CPU, in a background\n"
|
||||
" # thread, slower to build but never a request. `openai` sends to\n"
|
||||
" # embed_endpoint, `off` keeps the tool away.\n"
|
||||
" #embed = local\n"
|
||||
" #embed_dims = 256 # vector size for `local`\n"
|
||||
" #embed_endpoint = http://127.0.0.1:8080/v1\n"
|
||||
" #embed_model = nomic-embed-text\n"
|
||||
"}\n"
|
||||
"\n"
|
||||
"# One block per plugin; what is in it is that plugin's own setting.\n"
|
||||
"#plugin lcm { }\n"
|
||||
"#plugin mcp {\n"
|
||||
"# server junction { url = http://127.0.0.1:8090/mcp }\n"
|
||||
"#}\n"
|
||||
"\n"
|
||||
"#telegram { allow = [123456789] }\n"
|
||||
"\n"
|
||||
"provider local {\n"
|
||||
@@ -1086,3 +1246,21 @@ sp_cli_command(const struct sp_delegate *d, const char *model, char *out,
|
||||
snprintf(out, cap, "%s --model %s", cmd, full);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_config_plugin_value(const struct sp_config *c, const char *plugin,
|
||||
const char *key)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (c == NULL || plugin == NULL || key == NULL)
|
||||
return NULL;
|
||||
/* the last one wins, like every other setting */
|
||||
for (i = c->nplugin_conf; i > 0; i--) {
|
||||
const struct sp_plugin_kv *kv = &c->plugin_conf[i - 1];
|
||||
|
||||
if (strcmp(kv->plugin, plugin) == 0 && strcmp(kv->key, key) == 0)
|
||||
return kv->val;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
@@ -22,6 +22,18 @@
|
||||
#include "splinter.h"
|
||||
|
||||
#define SP_CONFIG_MAX_PLUGINS 32
|
||||
#define SP_CONFIG_MAX_PLUGIN_KV 96
|
||||
|
||||
/*
|
||||
* One setting of a plugin's own configuration: plugin NAME { key = value }.
|
||||
* A nested block (server junction { url = ... }) gives dotted keys,
|
||||
* "server.junction.url"; a list becomes "a,b,c".
|
||||
*/
|
||||
struct sp_plugin_kv {
|
||||
char plugin[48];
|
||||
char key[96];
|
||||
char val[512];
|
||||
};
|
||||
|
||||
/*
|
||||
* A delegate is another model splinter may hand work to: a name, what it is
|
||||
@@ -45,7 +57,7 @@
|
||||
*/
|
||||
struct sp_exit {
|
||||
char id[32];
|
||||
char label[64]; /* what shows up in the sidebar */
|
||||
char label[64]; /* the short name /usage and the logs show */
|
||||
char endpoint[512];
|
||||
char model[256];
|
||||
char key_env[64];
|
||||
@@ -65,7 +77,9 @@ struct sp_delegate {
|
||||
char tags[128]; /* comma separated, matched against the task */
|
||||
char endpoint[512];
|
||||
char model[256];
|
||||
char models[512]; /* optional comma list: the only models this provider offers */
|
||||
char key_env[64];
|
||||
unsigned long ctx; /* context window in tokens, 0 = unknown */
|
||||
char env[SP_CONFIG_MAX_ENV][SP_CONFIG_ENV_LEN]; /* NAME=VALUE */
|
||||
size_t nenv;
|
||||
/* the allowance, 0: none declared (see usage.h) */
|
||||
@@ -119,6 +133,7 @@ struct sp_config {
|
||||
char endpoint[512];
|
||||
char model[256];
|
||||
char key_env[64];
|
||||
unsigned long ctx; /* of the main provider, 0 = unknown */
|
||||
char kind[16]; /* of the main provider: "" (openai) or anthropic */
|
||||
unsigned long req_limit, tok_limit; /* of the main provider */
|
||||
long req_window, tok_window;
|
||||
@@ -126,24 +141,34 @@ struct sp_config {
|
||||
char theme[64];
|
||||
char system_prompt[1024];
|
||||
char session_dir[512];
|
||||
/*
|
||||
* The boundary the file tools stay inside. Empty means none, which keeps
|
||||
* a setup that works today working; see sp_builtin_register().
|
||||
*/
|
||||
char tools_root[1024];
|
||||
char state_dir[512]; /* config, token, commands, USER.txt; default ~/.splinter */
|
||||
char cli_cmd[512];
|
||||
char cli_env[SP_CONFIG_MAX_ENV][SP_CONFIG_ENV_LEN]; /* NAME=VALUE */
|
||||
size_t ncli_env;
|
||||
char cli_fallback[256]; /* cli delegate ids, comma separated */
|
||||
char memory_url[512];
|
||||
char memory_key_env[64];
|
||||
char telegram_allow[256]; /* comma separated user ids */
|
||||
long telegram_status_chat; /* 0: the first allow id */
|
||||
char locale[32]; /* language code, exported as SPLINTER_LOCALE */
|
||||
char plugins[SP_CONFIG_MAX_PLUGINS][512];
|
||||
size_t nplugins;
|
||||
struct sp_plugin_kv plugin_conf[SP_CONFIG_MAX_PLUGIN_KV];
|
||||
size_t nplugin_conf;
|
||||
struct sp_mcpserver mcp[SP_CONFIG_MAX_MCP];
|
||||
size_t nmcp;
|
||||
size_t steps; /* 0: not set */
|
||||
size_t max_bytes; /* 0: not set */
|
||||
size_t compact_threshold; /* tokens, 0 = off */
|
||||
size_t compact_target; /* tokens */
|
||||
long http_timeout; /* seconds for HTTP/SSE requests, 0: default */
|
||||
long cli_timeout; /* seconds for cli transport, 0: default */
|
||||
long delegate_timeout; /* seconds for delegate children, 0: default */
|
||||
long run_timeout; /* seconds for the run tool, 0: default */
|
||||
long ask_timeout; /* seconds an ask waits for an answer, 0: default */
|
||||
int autonomous; /* -1 not set, 0 off, 1 on */
|
||||
int on_limit_fail; /* 1: a usage limit fails the turn instead of waiting */
|
||||
long max_wait; /* longest wait for a limit, seconds, 0: 12 h */
|
||||
@@ -154,6 +179,17 @@ struct sp_config {
|
||||
* and there is already an explicit cli delegate for the same program.
|
||||
*/
|
||||
int env_delegates;
|
||||
/*
|
||||
* The embedding index (see embed.h). On by default with the local
|
||||
* encoder: a harness that needs an API key before it can remember
|
||||
* anything stops remembering the day the key expires.
|
||||
*/
|
||||
int embed; /* SP_EMBED_OFF | _LOCAL | _REMOTE */
|
||||
int embed_dims;
|
||||
char embed_model[256];
|
||||
char embed_endpoint[512];
|
||||
char embed_key_env[64];
|
||||
long embed_timeout;
|
||||
};
|
||||
|
||||
void sp_config_init(struct sp_config *);
|
||||
@@ -182,6 +218,21 @@ const char *sp_config_loaded_path(void);
|
||||
/* Write a commented starter file. Returns 0 or -1. */
|
||||
int sp_config_write_example(const char *path, struct sp_buf *err);
|
||||
|
||||
/*
|
||||
* The state root: config, token, commands and USER.txt. Default ~/.splinter.
|
||||
* The session root: where the .jsonl sessions live. Default <state>/sessions;
|
||||
* the Telegram daemon puts its own tree below <session>/telegram.
|
||||
*/
|
||||
const char *sp_config_state_dir(const struct sp_config *);
|
||||
const char *sp_config_session_dir(const struct sp_config *);
|
||||
|
||||
/*
|
||||
* A plugin's own setting (plugin NAME { key = value }), or NULL. 'key' may be
|
||||
* dotted for a nested block: "server.junction.url".
|
||||
*/
|
||||
const char *sp_config_plugin_value(const struct sp_config *,
|
||||
const char *plugin, const char *key);
|
||||
|
||||
/* Set every NAME=VALUE of 'env' in this process, overwriting. */
|
||||
void sp_config_apply_env(const char (*env)[SP_CONFIG_ENV_LEN], size_t n);
|
||||
|
||||
@@ -147,23 +147,3 @@ sp_conv_bytes(const struct sp_conv *c)
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
int
|
||||
sp_conv_trim(struct sp_conv *c, size_t keep_last)
|
||||
{
|
||||
size_t drop, i;
|
||||
|
||||
if (c == NULL || keep_last >= c->n)
|
||||
return 0;
|
||||
drop = c->n - keep_last;
|
||||
for (i = 0; i < drop; i++) {
|
||||
free(c->v[i].role);
|
||||
free(c->v[i].name);
|
||||
free(c->v[i].call_id);
|
||||
free(c->v[i].content);
|
||||
free(c->v[i].calls);
|
||||
}
|
||||
memmove(c->v, c->v + drop, (c->n - drop) * sizeof(*c->v));
|
||||
c->n -= drop;
|
||||
return 0;
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -98,12 +98,6 @@ json_str(const char *args, const char *key, struct sp_buf *keep)
|
||||
return keep->p;
|
||||
}
|
||||
|
||||
static void
|
||||
models_url(const char *endpoint, char *out, size_t len)
|
||||
{
|
||||
sp_endpoint_url(endpoint, "models", out, len);
|
||||
}
|
||||
|
||||
static int
|
||||
tool_delegate_list(const char *args, struct sp_buf *out, void *ctx)
|
||||
{
|
||||
@@ -148,49 +142,56 @@ tool_delegate_list(const char *args, struct sp_buf *out, void *ctx)
|
||||
d->host[0] != '\0' ? d->host : "");
|
||||
sp_buf_printf(out, " wofuer: %s\n", d->about);
|
||||
if (probe && d->endpoint[0] != '\0') {
|
||||
char url[600], cmd[700];
|
||||
FILE *fp;
|
||||
char line[512];
|
||||
int seen = 0;
|
||||
struct sp_provider pv;
|
||||
struct sp_buf ids = { 0 }, perr = { 0 };
|
||||
char kenv[sizeof(pv.key_env)];
|
||||
|
||||
models_url(d->endpoint, url, sizeof(url));
|
||||
snprintf(cmd, sizeof(cmd), "curl -sS --max-time 8 '%s'",
|
||||
url);
|
||||
fp = popen(cmd, "r");
|
||||
/*
|
||||
* The same route and the same reader as every other
|
||||
* model list: /models under the endpoint's base, with
|
||||
* the delegate's key and headers. The old popen(1)
|
||||
* variant sent no key and saw only the first "id" of a
|
||||
* one-line JSON answer.
|
||||
*/
|
||||
memset(&pv, 0, sizeof(pv));
|
||||
snprintf(pv.id, sizeof(pv.id), "%s", d->id);
|
||||
snprintf(pv.kind, sizeof(pv.kind), "%s", d->kind);
|
||||
snprintf(pv.endpoint, sizeof(pv.endpoint), "%s",
|
||||
d->endpoint);
|
||||
snprintf(pv.model, sizeof(pv.model), "%s", d->model);
|
||||
snprintf(pv.models, sizeof(pv.models), "%s", d->models);
|
||||
snprintf(pv.key_env, sizeof(pv.key_env), "%s",
|
||||
d->key_env);
|
||||
/* a literal key lives in 'key' until the child starts */
|
||||
if (pv.key_env[0] == '\0' && d->key[0] != '\0') {
|
||||
snprintf(kenv, sizeof(kenv),
|
||||
"SPLINTER_PROBE_KEY_%ld", (long)getpid());
|
||||
(void)setenv(kenv, d->key, 1);
|
||||
snprintf(pv.key_env, sizeof(pv.key_env), "%s",
|
||||
kenv);
|
||||
}
|
||||
sp_buf_puts(out, " models: ");
|
||||
if (fp == NULL) {
|
||||
sp_buf_puts(out, "nicht erreichbar\n");
|
||||
if (sp_buf_init(&ids) != 0 ||
|
||||
sp_buf_init(&perr) != 0) {
|
||||
sp_buf_puts(out, "(keine Modellliste)\n");
|
||||
} else if (sp_provider_served(&pv, &ids, &perr) != 0) {
|
||||
sp_buf_printf(out, "%s\n", perr.p != NULL ?
|
||||
perr.p : "(keine Modellliste)");
|
||||
} else {
|
||||
while (fgets(line, sizeof(line), fp) != NULL) {
|
||||
const char *m = strstr(line, "\"id\"");
|
||||
char *m, *save = NULL;
|
||||
int seen = 0;
|
||||
|
||||
if (m == NULL)
|
||||
continue;
|
||||
m = strchr(m, ':');
|
||||
if (m == NULL)
|
||||
continue;
|
||||
m = strchr(m, '"');
|
||||
if (m == NULL)
|
||||
continue;
|
||||
{
|
||||
const char *e = strchr(m + 1, '"');
|
||||
size_t n = e != NULL ?
|
||||
(size_t)(e - m - 1) : 0;
|
||||
|
||||
if (n > 0 && n < 80) {
|
||||
if (seen++)
|
||||
sp_buf_puts(out,
|
||||
", ");
|
||||
sp_buf_printf(out,
|
||||
"%.*s", (int)n, m + 1);
|
||||
}
|
||||
}
|
||||
for (m = strtok_r(ids.p, "\n", &save);
|
||||
m != NULL;
|
||||
m = strtok_r(NULL, "\n", &save)) {
|
||||
if (seen++)
|
||||
sp_buf_puts(out, ", ");
|
||||
sp_buf_printf(out, "%s", m);
|
||||
}
|
||||
(void)pclose(fp);
|
||||
if (!seen)
|
||||
sp_buf_puts(out, "(keine Modellliste)");
|
||||
sp_buf_puts(out, "\n");
|
||||
}
|
||||
sp_buf_free(&ids);
|
||||
sp_buf_free(&perr);
|
||||
}
|
||||
sp_buf_puts(out, "\n");
|
||||
}
|
||||
@@ -569,15 +570,30 @@ shell_quote(struct sp_buf *b, const char *s)
|
||||
void
|
||||
sp_delegate_cli_plugin(const char *self, char *out, size_t len)
|
||||
{
|
||||
char dir[512], cand[3][600];
|
||||
const char *env = getenv("SPLINTER_CLI_PLUGIN");
|
||||
const char *slash;
|
||||
size_t n = 0, i;
|
||||
const char *env = getenv("SPLINTER_CLI_PLUGIN");
|
||||
|
||||
if (env != NULL && *env != '\0') {
|
||||
snprintf(out, len, "%s", env);
|
||||
return;
|
||||
}
|
||||
sp_plugin_path(self, "cli", out, len);
|
||||
}
|
||||
|
||||
/*
|
||||
* A shipped plugin by name, for a binary at 'self'. Order:
|
||||
* <dir of self>/plugins/NAME/NAME.so the build tree
|
||||
* <dir of self>/../lib/splinter/plugins/NAME/NAME.so
|
||||
* <dir of self>/../lib/splinter/plugins/NAME.so what 'make install' writes
|
||||
* SPLINTER_PLUGIN_DIR/plugins/NAME/NAME.so the build tree compiled in
|
||||
* The first readable one wins; none: the first, so the error names a place.
|
||||
*/
|
||||
void
|
||||
sp_plugin_path(const char *self, const char *name, char *out, size_t len)
|
||||
{
|
||||
char dir[512], cand[4][700];
|
||||
const char *slash;
|
||||
size_t n = 0, i;
|
||||
|
||||
snprintf(dir, sizeof(dir), "%s",
|
||||
self != NULL && *self != '\0' ? self : "splinter");
|
||||
slash = strrchr(dir, '/');
|
||||
@@ -585,12 +601,15 @@ sp_delegate_cli_plugin(const char *self, char *out, size_t len)
|
||||
dir[slash - dir] = '\0';
|
||||
else
|
||||
snprintf(dir, sizeof(dir), ".");
|
||||
snprintf(cand[n++], sizeof(cand[0]), "%s/plugins/cli/cli.so", dir);
|
||||
snprintf(cand[n++], sizeof(cand[0]), "%s/plugins/%s/%s.so", dir, name,
|
||||
name);
|
||||
snprintf(cand[n++], sizeof(cand[0]),
|
||||
"%s/../lib/splinter/plugins/cli/cli.so", dir);
|
||||
"%s/../lib/splinter/plugins/%s/%s.so", dir, name, name);
|
||||
snprintf(cand[n++], sizeof(cand[0]),
|
||||
"%s/../lib/splinter/plugins/%s.so", dir, name);
|
||||
#ifdef SPLINTER_PLUGIN_DIR
|
||||
snprintf(cand[n++], sizeof(cand[0]), "%s/plugins/cli/cli.so",
|
||||
SPLINTER_PLUGIN_DIR);
|
||||
snprintf(cand[n++], sizeof(cand[0]), "%s/plugins/%s/%s.so",
|
||||
SPLINTER_PLUGIN_DIR, name, name);
|
||||
#endif
|
||||
for (i = 0; i < n; i++)
|
||||
if (access(cand[i], R_OK) == 0)
|
||||
@@ -942,9 +961,23 @@ write_sidecar(const char *base, const char *ext, const struct sp_buf *b)
|
||||
snprintf(tmp, sizeof(tmp), "%s.tmp", path);
|
||||
fp = fopen(tmp, "w");
|
||||
if (!fp) return;
|
||||
fwrite(b->p, 1, b->len, fp);
|
||||
fclose(fp);
|
||||
rename(tmp, path);
|
||||
/*
|
||||
* The job record is the only copy of a task, a result or the error that
|
||||
* explains a failed one. A write that cannot finish must not be renamed
|
||||
* over the good file: unlink the temp and keep what was there.
|
||||
*/
|
||||
{
|
||||
int bad = fwrite(b->p, 1, b->len, fp) != b->len;
|
||||
|
||||
if (fflush(fp) != 0 || fsync(fileno(fp)) != 0)
|
||||
bad = 1;
|
||||
if (fclose(fp) != 0)
|
||||
bad = 1;
|
||||
if (bad)
|
||||
(void)unlink(tmp);
|
||||
else
|
||||
(void)rename(tmp, path);
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
@@ -989,8 +1022,24 @@ jobrec_write(const struct del_ctx *c, struct jobrec *j)
|
||||
sp_buf_printf(&b, " \"has_result\":%s,\n \"has_error\":%s\n", (j->result.len>0?"true":"false"), (j->err.len>0?"true":"false"));
|
||||
sp_buf_puts(&b, "}\n");
|
||||
fp = fopen(tmp, "w");
|
||||
if (fp) { fputs(b.p?b.p:"{}", fp); fclose(fp); rename(tmp, path); }
|
||||
else unlink(tmp);
|
||||
/*
|
||||
* The record says which state a job is in; a torn one loses the job and
|
||||
* its remote id, so an unfinished write is dropped instead of renamed.
|
||||
* The writes are all attempted (no short-circuit) so the stream is
|
||||
* always closed.
|
||||
*/
|
||||
if (fp != NULL) {
|
||||
int bad = fputs(b.p != NULL ? b.p : "{}", fp) < 0;
|
||||
|
||||
if (fflush(fp) != 0 || fsync(fileno(fp)) != 0)
|
||||
bad = 1;
|
||||
if (fclose(fp) != 0)
|
||||
bad = 1;
|
||||
if (bad)
|
||||
(void)unlink(tmp);
|
||||
else if (rename(tmp, path) != 0)
|
||||
(void)unlink(tmp);
|
||||
}
|
||||
sp_buf_free(&b);
|
||||
if (j->task.len > 0) write_sidecar(base, "task", &j->task);
|
||||
if (j->result.len > 0) write_sidecar(base, "result", &j->result);
|
||||
@@ -1053,6 +1102,13 @@ jobrec_read(const struct del_ctx *c, const char *id, struct jobrec *j)
|
||||
*/
|
||||
#define COOLDOWN_DEFAULT 3600
|
||||
|
||||
/*
|
||||
* The longest bench that is still a bench. A reset further out than this is
|
||||
* not a reset: the value came from a provider's text or from a file, and an
|
||||
* accepted 9223372036854775807 would skip that delegate for ever.
|
||||
*/
|
||||
#define LIMIT_MAX_AHEAD (370L * 86400L)
|
||||
|
||||
static void
|
||||
cooldown_path(const char *id, char *buf, size_t len)
|
||||
{
|
||||
@@ -1066,13 +1122,20 @@ cooldown_path(const char *id, char *buf, size_t len)
|
||||
home != NULL ? home : "/tmp", id);
|
||||
}
|
||||
|
||||
/* the epoch the delegate is benched until, 0 when it is free */
|
||||
/*
|
||||
* the epoch the delegate is benched until, 0 when it is free.
|
||||
*
|
||||
* The file is not ours alone: it is plain text in a directory other splinter
|
||||
* runs (and a person) can write, so a value that is not a time is not a bench
|
||||
* either. Handing LONG_MAX back would wedge the delegate for good - choose()
|
||||
* skips it and says nothing.
|
||||
*/
|
||||
long
|
||||
sp_cooldown_until(const char *id)
|
||||
{
|
||||
char path[700];
|
||||
FILE *f;
|
||||
long until = 0;
|
||||
long until = 0, now = (long)time(NULL);
|
||||
|
||||
cooldown_path(id, path, sizeof(path));
|
||||
f = fopen(path, "r");
|
||||
@@ -1081,7 +1144,7 @@ sp_cooldown_until(const char *id)
|
||||
if (fscanf(f, "%ld", &until) != 1)
|
||||
until = 0;
|
||||
fclose(f);
|
||||
if (until <= (long)time(NULL)) {
|
||||
if (until <= now || until > now + LIMIT_MAX_AHEAD) {
|
||||
(void)unlink(path);
|
||||
return 0;
|
||||
}
|
||||
@@ -1196,7 +1259,50 @@ parse_reset(const char *e)
|
||||
return t > now ? t : 0;
|
||||
}
|
||||
|
||||
/* Is this error a limit, and until when? Returns 1 and sets *until. */
|
||||
/*
|
||||
* A 429 that is an HTTP status, as the transports write it ("HTTP 429",
|
||||
* "transport status 429", "Error: 429", "\"code\":429", "429 Too Many"), not
|
||||
* any "429" in the text: a line number or a count in a child's output tail
|
||||
* would bench a delegate for an hour.
|
||||
*/
|
||||
static int
|
||||
has_status_429(const char *e)
|
||||
{
|
||||
static const char *const before[] = {
|
||||
"http ", "http/1.0 ", "http/1.1 ", "http/2 ", "http/2.0 ",
|
||||
"status ", "status: ", "status=", "status\":", "status\": ",
|
||||
"code ", "code: ", "code=", "code\":", "code\": ",
|
||||
"error ", "error: ", NULL
|
||||
};
|
||||
const char *p;
|
||||
size_t i;
|
||||
|
||||
for (p = strstr(e, "429"); p != NULL; p = strstr(p + 1, "429")) {
|
||||
if ((p > e && isdigit((unsigned char)p[-1])) ||
|
||||
isdigit((unsigned char)p[3]))
|
||||
continue;
|
||||
if (strncasecmp(p + 3, " too many", 9) == 0)
|
||||
return 1;
|
||||
for (i = 0; before[i] != NULL; i++) {
|
||||
size_t n = strlen(before[i]);
|
||||
|
||||
if ((size_t)(p - e) >= n &&
|
||||
strncasecmp(p - n, before[i], n) == 0)
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Is this error a limit, and until when? Returns 1 and sets *until.
|
||||
*
|
||||
* The value comes out of text a provider sent, so it is not trusted to be a
|
||||
* time: "ready_at=9223372036854775807" was accepted as-is, written to the
|
||||
* cooldown file, and benched the delegate until the year 292 billion - not
|
||||
* one call, every call, and choose() skips a benched delegate without a word.
|
||||
* A reset beyond LIMIT_MAX_AHEAD is not a reset; the default bench applies.
|
||||
*/
|
||||
int
|
||||
sp_limit_parse(const char *e, long *until)
|
||||
{
|
||||
@@ -1205,13 +1311,15 @@ sp_limit_parse(const char *e, long *until)
|
||||
*until = 0;
|
||||
if (e == NULL)
|
||||
return 0;
|
||||
if (!(strstr(e, "429") != NULL || has_ci(e, "rate limit") ||
|
||||
if (!(has_status_429(e) || has_ci(e, "rate limit") ||
|
||||
has_ci(e, "rate_limit") || has_ci(e, "usage limit") ||
|
||||
has_ci(e, "weekly limit") || has_ci(e, "daily limit") ||
|
||||
has_ci(e, "hit your limit") || has_ci(e, "limit reached") ||
|
||||
has_ci(e, "quota") || strstr(e, "WAIT_QUOTA") != NULL))
|
||||
return 0;
|
||||
t = parse_reset(e);
|
||||
if (t > (long)time(NULL) + LIMIT_MAX_AHEAD)
|
||||
t = 0;
|
||||
*until = t > 0 ? t : (long)time(NULL) + COOLDOWN_DEFAULT;
|
||||
return 1;
|
||||
}
|
||||
@@ -1256,8 +1364,12 @@ run_child_fb(const struct del_ctx *c, const struct sp_delegate **dp,
|
||||
time_t tt = (time_t)until;
|
||||
struct tm tm;
|
||||
|
||||
strftime(when, sizeof(when), "%Y-%m-%d %H:%M",
|
||||
localtime_r(&tt, &tm));
|
||||
/* an unrepresentable time must not become a wrong one
|
||||
* (see agent.c); the benched note is read by the operator */
|
||||
strcpy(when, "?");
|
||||
if (localtime_r(&tt, &tm) != NULL)
|
||||
strftime(when, sizeof(when),
|
||||
"%Y-%m-%d %H:%M", &tm);
|
||||
sp_buf_printf(note, "[%s at its limit, benched until %s]\n",
|
||||
d->id, when);
|
||||
}
|
||||
@@ -1292,7 +1404,6 @@ run_child_fb(const struct del_ctx *c, const struct sp_delegate **dp,
|
||||
static const struct sp_delegate *find_delegate(const struct sp_config *cfg, const char *id);
|
||||
static int looks_transient(const char *e);
|
||||
static int looks_quota_wait(const char *e, long *ready_at);
|
||||
static void link_plan_quota(struct del_ctx *c, const char *plan_task_id, const char *run_after, const char *job_id);
|
||||
|
||||
static int
|
||||
tool_delegate(const char *args, struct sp_buf *out, void *ctx)
|
||||
@@ -1427,7 +1538,6 @@ tool_delegate(const char *args, struct sp_buf *out, void *ctx)
|
||||
if (ra>0) { snprintf(jr.run_after,sizeof(jr.run_after),"%ld",ra); snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",ra); }
|
||||
else snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",(long)time(NULL)+3600);
|
||||
jobrec_write(c, &jr);
|
||||
link_plan_quota(c, jr.plan_task_id, jr.run_after[0]?jr.run_after:jr.next_poll_at, jr.id);
|
||||
sp_buf_printf(out, "quota: %s\n[job %s: waiting_quota run_after=%s, auto-scheduled]\n", err.p?err.p:"quota", jr.id, jr.run_after);
|
||||
} else if (looks_transient(err.p)) {
|
||||
snprintf(jr.state, sizeof(jr.state), "waiting_poll");
|
||||
@@ -1597,7 +1707,10 @@ par_fallback(struct del_ctx *c, struct job *jobs, size_t njobs, size_t i,
|
||||
return 0;
|
||||
sp_cooldown_set(j->d->id, until, j->out.p);
|
||||
tt = (time_t)until;
|
||||
strftime(when, sizeof(when), "%Y-%m-%d %H:%M", localtime_r(&tt, &tm));
|
||||
/* an unrepresentable time must not become a wrong one (see agent.c) */
|
||||
strcpy(when, "?");
|
||||
if (localtime_r(&tt, &tm) != NULL)
|
||||
strftime(when, sizeof(when), "%Y-%m-%d %H:%M", &tm);
|
||||
nl = strlen(j->note);
|
||||
snprintf(j->note + nl, sizeof(j->note) - nl,
|
||||
"[%s at its limit, benched until %s]", j->d->id, when);
|
||||
@@ -2177,17 +2290,6 @@ sp_delegate_tick(struct sp_buf *out)
|
||||
}
|
||||
|
||||
|
||||
static void
|
||||
link_plan_quota(struct del_ctx *c, const char *plan_task_id, const char *run_after, const char *job_id)
|
||||
{
|
||||
struct sp_buf out, args;
|
||||
if (!c || !c->host || !plan_task_id || !*plan_task_id) return;
|
||||
if (sp_buf_init(&out)!=0 || sp_buf_init(&args)!=0) return;
|
||||
sp_buf_printf(&args, "wait %s %s job:%s", plan_task_id,
|
||||
(run_after && *run_after) ? run_after : "+3600", job_id ? job_id : "");
|
||||
(void)sp_host_command(c->host, "tasks", args.p ? args.p : "", &out);
|
||||
sp_buf_free(&out); sp_buf_free(&args);
|
||||
}
|
||||
|
||||
int
|
||||
sp_delegate_retry_job(const char *id, int force, struct sp_buf *out)
|
||||
@@ -2269,7 +2371,6 @@ sp_delegate_retry_job(const char *id, int force, struct sp_buf *out)
|
||||
snprintf(jr.state,sizeof(jr.state),"waiting_quota");
|
||||
if(ra>0){snprintf(jr.run_after,sizeof(jr.run_after),"%ld",ra); snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",ra);}
|
||||
else snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",(long)time(NULL)+3600);
|
||||
link_plan_quota(c, jr.plan_task_id, jr.run_after[0]?jr.run_after:jr.next_poll_at, jr.id);
|
||||
} else if (looks_transient(err.p)) {
|
||||
snprintf(jr.state,sizeof(jr.state),"waiting_poll");
|
||||
snprintf(jr.next_poll_at,sizeof(jr.next_poll_at),"%ld",(long)time(NULL)+60);
|
||||
@@ -2520,7 +2621,7 @@ sp_delegate_register(struct sp_registry *r, const struct sp_config *cfg,
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.name = "delegate_due";
|
||||
t.description = "List durable delegation jobs due for retry/poll now (waiting_quota/waiting_poll/queued with run_after/next_poll_at reached). Scheduler view.";
|
||||
t.params = "{}";
|
||||
t.params = "{\"type\":\"object\",\"properties\":{}}";
|
||||
t.auth = SP_AUTH_READ;
|
||||
t.run = tool_delegate_due;
|
||||
t.ctx = &ctx;
|
||||
@@ -2552,7 +2653,7 @@ sp_delegate_register(struct sp_registry *r, const struct sp_config *cfg,
|
||||
memset(&t, 0, sizeof(t));
|
||||
t.name = "delegate_jobs";
|
||||
t.description = "List durable delegation jobs (submit/poll): id, state, delegate, exit, times. Jobs persist in the session so results can be polled later.";
|
||||
t.params = "{}";
|
||||
t.params = "{\"type\":\"object\",\"properties\":{}}";
|
||||
t.auth = SP_AUTH_READ;
|
||||
t.run = tool_delegate_jobs;
|
||||
t.ctx = &ctx;
|
||||
+1734
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* splinter -- the embedding index of a session.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Compaction throws most of a session out of the context window. Until now the
|
||||
* only way back to it was a substring search (lcm's recall, the session
|
||||
* plugin's session_search), which answers "where does this word stand" and not
|
||||
* "what did we say about this". The index here is the second question: every
|
||||
* message a session ever wrote, with a vector, so the model can ask by meaning.
|
||||
*
|
||||
* Three rules shape it, and each one was paid for elsewhere in this tree.
|
||||
*
|
||||
* 1. It must work with no model at all. A harness that needs an embedding API
|
||||
* before it can remember anything is a harness that stops remembering the
|
||||
* day the key expires. So the default is local: the hashing trick over
|
||||
* words, word bigrams and character 4-grams, a few hundred dimensions,
|
||||
* pure CPU, microseconds per message. It is weaker than a trained encoder
|
||||
* and it is honest about being a lexical measure -- it will not match
|
||||
* "Kompaktierung" with "compaction", and its job does not require it to.
|
||||
* kind = openai points it at a real embedding model instead; the index
|
||||
* records which one built it, because a vector from one space compared to a
|
||||
* vector from another is noise that looks like a result.
|
||||
*
|
||||
* 2. It must never cost the turn. Embedding runs on a thread of its own; the
|
||||
* turn only says "this session grew" and goes on. Nothing waits for the
|
||||
* index, and an index that lags is reported as lagging instead of pretending
|
||||
* the newest messages are in it.
|
||||
*
|
||||
* 3. It indexes the session file, not the conversation. The conversation is
|
||||
* what is left after the last compaction; the file is everything that was
|
||||
* ever said. "Before compaction" is not a snapshot to take, it is the file.
|
||||
* That also makes the update incremental for free: the index stores the byte
|
||||
* offset it reached, so the next run reads only the new lines.
|
||||
*
|
||||
* The index is derived data. Losing it costs a rebuild, never history, so it
|
||||
* lives next to the session and is written append-only:
|
||||
*
|
||||
* <session_dir>/emb/<id>.emb
|
||||
*
|
||||
* one JSON object per line, the vector as base64 float32.
|
||||
*/
|
||||
#ifndef SPLINTER_EMBED_H
|
||||
#define SPLINTER_EMBED_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
struct sp_config;
|
||||
struct sp_registry;
|
||||
struct sp_embed_ctx;
|
||||
|
||||
enum sp_embed_kind {
|
||||
SP_EMBED_OFF = 0, /* kind = off */
|
||||
SP_EMBED_LOCAL, /* the built-in hashing encoder, CPU */
|
||||
SP_EMBED_REMOTE /* POST /embeddings somewhere */
|
||||
};
|
||||
|
||||
struct sp_embed_cfg {
|
||||
enum sp_embed_kind kind;
|
||||
int dims; /* local: the hash width */
|
||||
char model[256];
|
||||
char endpoint[512];
|
||||
char key_env[64];
|
||||
long timeout_s;
|
||||
};
|
||||
|
||||
/* the config file's embed settings, with the defaults applied */
|
||||
void sp_embed_cfg_from_config(const struct sp_config *, struct sp_embed_cfg *);
|
||||
|
||||
/*
|
||||
* One index per engine. ALWAYS returns a context, even with kind = off: the
|
||||
* call sites must not each decide what "off" means.
|
||||
*/
|
||||
struct sp_embed_ctx *sp_embed_new(const struct sp_config *);
|
||||
void sp_embed_free(struct sp_embed_ctx *);
|
||||
|
||||
/* The session the index belongs to. A changed id starts the new one's index;
|
||||
* the first bind of a session also queues the whole file, so a resume is
|
||||
* searchable before anything is compacted. */
|
||||
void sp_embed_bind(struct sp_embed_ctx *, const char *dir, const char *id);
|
||||
|
||||
/* A compaction just threw history out of the context. Cheap: a flag and a
|
||||
* signal, no I/O and no work on the caller's thread. */
|
||||
void sp_embed_note_compaction(struct sp_embed_ctx *);
|
||||
|
||||
/*
|
||||
* Wait until the worker has caught up: 1 when it is idle, 0 on timeout.
|
||||
* Tests need it; a shutdown may not.
|
||||
*/
|
||||
int sp_embed_flush(struct sp_embed_ctx *, long timeout_ms);
|
||||
|
||||
/* Register the history_search tool. ctx is the index, owned by the engine. */
|
||||
int sp_embed_register(struct sp_registry *, struct sp_embed_ctx *);
|
||||
|
||||
/* One line for /status or a widget: kind, records, how far behind. */
|
||||
void sp_embed_status(struct sp_embed_ctx *, char *buf, size_t cap);
|
||||
|
||||
/*
|
||||
* The pieces, exposed for tests and for the tool. None of these touch the
|
||||
* thread.
|
||||
*/
|
||||
|
||||
/* Local encoder: 'v' must hold dims doubles. Returns 0, or -1 for an empty
|
||||
* text (a vector of zeros has no direction). */
|
||||
int sp_embed_text(const char *text, int dims, double *v);
|
||||
|
||||
/* Cosine of two L2-normalised vectors, which is their dot product. */
|
||||
double sp_embed_dot(const double *a, const double *b, int dims);
|
||||
|
||||
/*
|
||||
* Run the indexer for one session now, on the caller's thread. 'err' gets a
|
||||
* message on failure and stays empty on success. Returns the number of records
|
||||
* added, or -1.
|
||||
*/
|
||||
int sp_embed_index_now(struct sp_embed_ctx *, char *err, size_t errcap);
|
||||
|
||||
/* Search the index: the 'limit' closest messages, written to out. */
|
||||
int sp_embed_search(struct sp_embed_ctx *, const char *query, size_t limit,
|
||||
struct sp_buf *out);
|
||||
/* The same, and with full != 0 each hit is followed by 'cap' bytes of the
|
||||
* message itself, read back from the session log. */
|
||||
int sp_embed_search_full(struct sp_embed_ctx *, const char *query,
|
||||
size_t limit, int full, size_t cap, struct sp_buf *out);
|
||||
|
||||
#endif /* SPLINTER_EMBED_H */
|
||||
File diff suppressed because it is too large.
Load diff
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,556 @@
|
||||
/*
|
||||
* splinter -- continue a session another tool owns.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Claude Code stops at its limit, opencode exits, hermes restarts -- and the
|
||||
* work is still in their store. --claude (or --opencode/--hermes) is the way
|
||||
* out: import the newest session that tool ran *in this directory* and open
|
||||
* the result as the session of this run.
|
||||
*
|
||||
* Why the import and not a live "read-through": a turn needs a splinter
|
||||
* session on disk (compaction, the embed index, /open and -c all speak it), and
|
||||
* the foreign plugin already writes exactly that shape. Doing it here means the
|
||||
* plugin owns the three formats and the engine owns only the order.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "embed.h"
|
||||
#include "foreignopen.h"
|
||||
#include "log.h"
|
||||
|
||||
/*
|
||||
* The tools the import needs, found by name: the plugin registers them, so the
|
||||
* engine does not have to know whether it was loaded from the config or by
|
||||
* --plugin.
|
||||
*/
|
||||
static const struct sp_tool *
|
||||
tool_of(struct sp_registry *reg, const char *name)
|
||||
{
|
||||
return sp_registry_find(reg, name);
|
||||
}
|
||||
|
||||
/*
|
||||
* How many rows one listing asks for. The foreign plugin accepts 1..100 and
|
||||
* silently falls back to its own default (25) for anything else, so asking for
|
||||
* more would *shrink* the answer.
|
||||
*/
|
||||
#define FOREIGN_ROW_MAX 100
|
||||
|
||||
/*
|
||||
* A list row is "DATE SOURCE ID TITLE CWD", fields separated by two
|
||||
* spaces. The id is the third field and the title is free text, so the row is
|
||||
* split from the left: the first three fields cannot contain the separator,
|
||||
* everything after them can.
|
||||
*
|
||||
* Returns the length of field `want` and points *start at it, or 0 when the
|
||||
* row has no such field (an error line, an empty list, a short row).
|
||||
*/
|
||||
static size_t
|
||||
column(const char *row, int want, const char **start)
|
||||
{
|
||||
const char *p = row;
|
||||
int field = 0;
|
||||
|
||||
for (;;) {
|
||||
const char *b = p;
|
||||
|
||||
while (*p != '\0' && *p != '\n' &&
|
||||
!(p[0] == ' ' && p[1] == ' '))
|
||||
p++;
|
||||
if (field == want) {
|
||||
*start = b;
|
||||
return (size_t)(p - b);
|
||||
}
|
||||
if (*p == '\0' || *p == '\n')
|
||||
return 0;
|
||||
while (*p == ' ')
|
||||
p++;
|
||||
field++;
|
||||
}
|
||||
}
|
||||
|
||||
/* one field of a "foreign=" marker ("claude:abc" -> "claude") */
|
||||
static void
|
||||
origin_source(const char *marker, char *out, size_t cap)
|
||||
{
|
||||
const char *c = strchr(marker, ':');
|
||||
size_t n = c != NULL ? (size_t)(c - marker) : strlen(marker);
|
||||
|
||||
if (cap == 0)
|
||||
return;
|
||||
if (n + 1 > cap)
|
||||
n = cap - 1;
|
||||
memcpy(out, marker, n);
|
||||
out[n] = '\0';
|
||||
}
|
||||
|
||||
static void
|
||||
origin_id(const char *marker, char *out, size_t cap)
|
||||
{
|
||||
const char *c = strchr(marker, ':');
|
||||
|
||||
if (cap == 0)
|
||||
return;
|
||||
snprintf(out, cap, "%s", c != NULL ? c + 1 : "");
|
||||
}
|
||||
|
||||
/*
|
||||
* The session an earlier --claude already imported, if there is one. The
|
||||
* imported session carries the source and its id in its sidecar, so a second
|
||||
* start continues *that* session: importing again would replace the file and
|
||||
* throw away everything the conversation did in splinter since.
|
||||
*
|
||||
* Returns 1 and fills `id` when found, 0 when there is none.
|
||||
*/
|
||||
static int
|
||||
imported_before(const char *dir, const char *source, const char *foreign,
|
||||
char *id, size_t cap)
|
||||
{
|
||||
struct sp_session_brief v[64];
|
||||
int n, i, found = 0;
|
||||
size_t nlen;
|
||||
|
||||
/*
|
||||
* sp_session_list is newest first, so the first session that carries
|
||||
* this origin is the one the user continued from last.
|
||||
*/
|
||||
n = sp_session_list(dir, v, sizeof(v) / sizeof(v[0]));
|
||||
for (i = 0; i < n && !found; i++) {
|
||||
char marker[160], src[32], fid[128];
|
||||
|
||||
if (sp_session_foreign(dir, v[i].id, marker,
|
||||
sizeof(marker)) != 0)
|
||||
continue;
|
||||
origin_source(marker, src, sizeof(src));
|
||||
origin_id(marker, fid, sizeof(fid));
|
||||
if (strcmp(src, source) != 0 || strcmp(fid, foreign) != 0)
|
||||
continue;
|
||||
/* v[i].id is bounded by its struct, so copy and clamp */
|
||||
nlen = strlen(v[i].id);
|
||||
if (nlen + 1 > cap)
|
||||
nlen = cap > 0 ? cap - 1 : 0;
|
||||
memcpy(id, v[i].id, nlen);
|
||||
if (cap > 0)
|
||||
id[nlen] = '\0';
|
||||
found = 1;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/*
|
||||
* The import line names the new session id ("... as sess-123 (...)"). The
|
||||
* engine has to open that exact session, so the id is read back from the
|
||||
* answer rather than guessed: how the plugin names a session is its business.
|
||||
*/
|
||||
static int
|
||||
id_from_answer(const char *answer, char *out, size_t cap)
|
||||
{
|
||||
const char *p = answer != NULL ? strstr(answer, " as ") : NULL;
|
||||
size_t n = 0;
|
||||
|
||||
if (p == NULL || cap == 0)
|
||||
return -1;
|
||||
p += 4;
|
||||
while (p[n] != '\0' && p[n] != ' ' && p[n] != '(' && p[n] != '\n' &&
|
||||
n + 1 < cap)
|
||||
n++;
|
||||
if (n == 0)
|
||||
return -1;
|
||||
memcpy(out, p, n);
|
||||
out[n] = '\0';
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Run one tool and copy its answer into `out`, which is cleared first. The
|
||||
* answer is copied because a later call reuses the same buffer while the
|
||||
* import answer is still needed.
|
||||
*/
|
||||
static int
|
||||
run_tool(const struct sp_tool *t, const char *args, struct sp_buf *out,
|
||||
struct sp_buf *tmp)
|
||||
{
|
||||
sp_buf_clear(out);
|
||||
sp_buf_clear(tmp);
|
||||
if (t->run(args, tmp, t->ctx) != 0)
|
||||
return -1;
|
||||
if (tmp->p != NULL && sp_buf_add(out, tmp->p, tmp->len) != 0)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Open `id` as the session of this run. The session directory stays the one
|
||||
* the run already uses, so an import lands beside the run's own sessions.
|
||||
* Everything keyed on the old id is rebound: the log, the cli session the
|
||||
* transport uses, and the embed index.
|
||||
*/
|
||||
static int
|
||||
take_session(struct sp_foreign_target *t, const char *id, struct sp_buf *err)
|
||||
{
|
||||
char keep[640];
|
||||
|
||||
/*
|
||||
* sp_session_open writes info->dir, and t->sess->dir is the source
|
||||
* here: copying it out first is what keeps the directory intact.
|
||||
*/
|
||||
snprintf(keep, sizeof(keep), "%s", t->sess->dir);
|
||||
if (sp_session_open(t->sess, keep, id, err) != 0)
|
||||
return -1;
|
||||
(void)sp_log_open(t->sess->dir, t->sess->id);
|
||||
(void)setenv("SPLINTER_CLI_SESSION", t->sess->id, 0);
|
||||
sp_openai_set_session(t->sess->id);
|
||||
if (t->emb != NULL)
|
||||
sp_embed_bind(t->emb, t->sess->dir, t->sess->id);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_foreign_open(struct sp_foreign_target *t, const char *source,
|
||||
const char *cwd, struct sp_buf *err)
|
||||
{
|
||||
const struct sp_tool *list;
|
||||
struct sp_buf args, out, tmp;
|
||||
char id[96];
|
||||
int rc = -1;
|
||||
|
||||
if (source == NULL || *source == '\0')
|
||||
return 0;
|
||||
if (strcmp(source, "claude") != 0 && strcmp(source, "hermes") != 0 &&
|
||||
strcmp(source, "opencode") != 0) {
|
||||
sp_buf_printf(err, "--%s is not a source: claude, hermes or "
|
||||
"opencode", source);
|
||||
return -1;
|
||||
}
|
||||
list = tool_of(t->reg, "foreign_list");
|
||||
if (list == NULL || tool_of(t->reg, "foreign_import") == NULL) {
|
||||
sp_buf_printf(err, "--%s needs the foreign plugin: add "
|
||||
"'plugin foreign' to the config", source);
|
||||
return -1;
|
||||
}
|
||||
if (sp_buf_init(&args) != 0 || sp_buf_init(&out) != 0 ||
|
||||
sp_buf_init(&tmp) != 0) {
|
||||
sp_buf_free(&args);
|
||||
sp_buf_free(&out);
|
||||
sp_buf_free(&tmp);
|
||||
return -1;
|
||||
}
|
||||
/*
|
||||
* The list is newest first and filtered by this directory, so the first
|
||||
* row is the session to continue. One row is enough: the import takes an
|
||||
* id, not a position.
|
||||
*/
|
||||
(void)sp_buf_printf(&args, "{\"source\":\"%s\",\"cwd\":\"%s\","
|
||||
"\"limit\":1}", source, cwd);
|
||||
if (run_tool(list, args.p, &out, &tmp) != 0) {
|
||||
sp_buf_printf(err, "cannot list %s sessions: %s", source,
|
||||
out.len > 0 && out.p != NULL ? out.p : "the tool failed");
|
||||
goto failed;
|
||||
}
|
||||
{
|
||||
const char *idp = NULL;
|
||||
size_t idn = column(out.p, 2, &idp);
|
||||
|
||||
if (idn == 0 || idn + 1 >= sizeof(id)) {
|
||||
sp_buf_printf(err, "no %s session in %s", source, cwd);
|
||||
goto failed;
|
||||
}
|
||||
memcpy(id, idp, idn);
|
||||
id[idn] = '\0';
|
||||
}
|
||||
rc = sp_foreign_import(t, source, id, err);
|
||||
sp_buf_free(&args);
|
||||
sp_buf_free(&out);
|
||||
sp_buf_free(&tmp);
|
||||
return rc;
|
||||
failed:
|
||||
/* keep what the plugin said: it knows why a store was unreadable */
|
||||
if (err->len == 0 && out.p != NULL && out.len > 0)
|
||||
sp_buf_add(err, out.p, out.len);
|
||||
sp_buf_free(&args);
|
||||
sp_buf_free(&out);
|
||||
sp_buf_free(&tmp);
|
||||
return rc;
|
||||
}
|
||||
|
||||
/*
|
||||
* Import one named session and make it the session of this run. The picker
|
||||
* behind /sessions uses this: the operator saw the row, so the id is the
|
||||
* choice, and sc_foreign_open is only the "newest in this folder" shortcut.
|
||||
*
|
||||
* An earlier import of the same foreign session is continued instead of being
|
||||
* imported again: the plugin replaces a file of the same name, which would
|
||||
* throw away everything the conversation did in splinter since.
|
||||
*/
|
||||
int
|
||||
sp_foreign_import(struct sp_foreign_target *t, const char *source,
|
||||
const char *id, struct sp_buf *err)
|
||||
{
|
||||
const struct sp_tool *import;
|
||||
struct sp_buf args, out, tmp;
|
||||
char newid[96];
|
||||
int rc = -1;
|
||||
|
||||
if (source == NULL || id == NULL || *id == '\0')
|
||||
return -1;
|
||||
if (strcmp(source, "claude") != 0 && strcmp(source, "hermes") != 0 &&
|
||||
strcmp(source, "opencode") != 0) {
|
||||
sp_buf_printf(err, "%s is not a source: claude, hermes or "
|
||||
"opencode", source);
|
||||
return -1;
|
||||
}
|
||||
import = tool_of(t->reg, "foreign_import");
|
||||
if (import == NULL) {
|
||||
sp_buf_puts(err, "the foreign plugin is not loaded");
|
||||
return -1;
|
||||
}
|
||||
if (sp_buf_init(&args) != 0 || sp_buf_init(&out) != 0 ||
|
||||
sp_buf_init(&tmp) != 0) {
|
||||
sp_buf_free(&args);
|
||||
sp_buf_free(&out);
|
||||
sp_buf_free(&tmp);
|
||||
return -1;
|
||||
}
|
||||
if (imported_before(t->sess->dir, source, id, newid, sizeof(newid))) {
|
||||
if (take_session(t, newid, err) != 0)
|
||||
goto out;
|
||||
sp_logf("session", "continuing %s session %s, imported before "
|
||||
"as %s", source, id, newid);
|
||||
rc = 0;
|
||||
goto out;
|
||||
}
|
||||
(void)sp_buf_printf(&args, "{\"source\":\"%s\",\"id\":\"%s\"}", source,
|
||||
id);
|
||||
if (run_tool(import, args.p, &out, &tmp) != 0 ||
|
||||
out.p == NULL || strncmp(out.p, "imported ", 9) != 0) {
|
||||
sp_buf_printf(err, "cannot import %s %s: %s", source, id,
|
||||
out.len > 0 && out.p != NULL ? out.p : "the import failed");
|
||||
goto out;
|
||||
}
|
||||
if (id_from_answer(out.p, newid, sizeof(newid)) != 0) {
|
||||
sp_buf_printf(err, "imported, but the new session id is not in "
|
||||
"the answer: %s", out.p);
|
||||
goto out;
|
||||
}
|
||||
/*
|
||||
* The import wrote a new file, and the log, the embed index and the
|
||||
* agent still point at the empty session this run started with.
|
||||
*/
|
||||
if (take_session(t, newid, err) != 0)
|
||||
goto out;
|
||||
sp_logf("session", "continuing %s session %s as %s", source, id, newid);
|
||||
rc = 0;
|
||||
out:
|
||||
sp_buf_free(&args);
|
||||
sp_buf_free(&out);
|
||||
sp_buf_free(&tmp);
|
||||
return rc;
|
||||
}
|
||||
|
||||
/*
|
||||
* The three sources this file knows and the plugin's list tool. Shared by the
|
||||
* two picker helpers below; -1 and `err` filled when the plugin is not loaded.
|
||||
*/
|
||||
static int
|
||||
foreign_list_tool(struct sp_foreign_target *t, const struct sp_tool **tool,
|
||||
struct sp_buf *err)
|
||||
{
|
||||
if (t == NULL || t->reg == NULL) {
|
||||
sp_buf_puts(err, "no registry");
|
||||
return -1;
|
||||
}
|
||||
*tool = tool_of(t->reg, "foreign_list");
|
||||
if (*tool == NULL) {
|
||||
sp_buf_puts(err, "the foreign plugin is not loaded");
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Ask the plugin for one source's sessions and hand every row to `cb`.
|
||||
* The row format is the plugin's ("DATE SOURCE ID TITLE CWD"), so the
|
||||
* splitting happens here once and both the count and the picker's labels come
|
||||
* out of it. Returns the number of rows, or -1 with `err` filled.
|
||||
*/
|
||||
static int
|
||||
list_rows(struct sp_foreign_target *t, const char *source,
|
||||
void (*cb)(void *cbctx, const char *id, const char *label, long mtime),
|
||||
void *cbctx, struct sp_buf *err)
|
||||
{
|
||||
const struct sp_tool *list;
|
||||
struct sp_buf args, out, tmp;
|
||||
char *line, *save;
|
||||
int n = 0;
|
||||
|
||||
if (foreign_list_tool(t, &list, err) != 0)
|
||||
return -1;
|
||||
if (sp_buf_init(&args) != 0)
|
||||
return -1;
|
||||
if (sp_buf_init(&out) != 0) {
|
||||
sp_buf_free(&args);
|
||||
return -1;
|
||||
}
|
||||
if (sp_buf_init(&tmp) != 0) {
|
||||
sp_buf_free(&args);
|
||||
sp_buf_free(&out);
|
||||
return -1;
|
||||
}
|
||||
(void)sp_buf_printf(&args, "{\"source\":\"%s\",\"cwd\":\"*\","
|
||||
"\"limit\":%d}", source, FOREIGN_ROW_MAX);
|
||||
if (run_tool(list, args.p, &out, &tmp) != 0 ||
|
||||
out.p == NULL || strncmp(out.p, "error:", 6) == 0) {
|
||||
sp_buf_printf(err, "%s", out.len > 0 && out.p != NULL ?
|
||||
out.p : "the foreign list failed");
|
||||
sp_buf_free(&args);
|
||||
sp_buf_free(&out);
|
||||
sp_buf_free(&tmp);
|
||||
return -1;
|
||||
}
|
||||
for (line = strtok_r(out.p, "\n", &save); line != NULL;
|
||||
line = strtok_r(NULL, "\n", &save)) {
|
||||
const char *idp = NULL, *datep = NULL, *rest;
|
||||
size_t idn, daten;
|
||||
char id[96], label[160], date[32];
|
||||
long mtime;
|
||||
|
||||
/* the plugin's own notes are not sessions */
|
||||
if (strncmp(line, "error:", 6) == 0 ||
|
||||
strncmp(line, "...", 3) == 0 ||
|
||||
strncmp(line, "no foreign sessions", 19) == 0)
|
||||
continue;
|
||||
idn = column(line, 2, &idp);
|
||||
if (idn == 0 || idn + 1 > sizeof(id))
|
||||
continue;
|
||||
memcpy(id, idp, idn);
|
||||
id[idn] = '\0';
|
||||
/*
|
||||
* An id is what foreign_import accepts, so anything that would
|
||||
* not survive as a JSON string or a file name is not one.
|
||||
*/
|
||||
if (strpbrk(id, "():\"'\\/") != NULL)
|
||||
continue;
|
||||
rest = idp + idn;
|
||||
while (*rest == ' ')
|
||||
rest++;
|
||||
snprintf(label, sizeof(label), "%.31s %s", id, rest);
|
||||
/*
|
||||
* The row carries the date the session last changed, and the
|
||||
* picker draws by it: a hard 0 would show every foreign row as
|
||||
* 1970-01-01. The plugin prints "?" when it has no date, which
|
||||
* stays 0 and is drawn as such.
|
||||
*/
|
||||
mtime = 0;
|
||||
daten = column(line, 0, &datep);
|
||||
if (daten > 0 && daten < sizeof(date)) {
|
||||
struct tm tm;
|
||||
int y = 0, mo = 0, d = 0, h = 0, mi = 0;
|
||||
|
||||
memcpy(date, datep, daten);
|
||||
date[daten] = '\0';
|
||||
/*
|
||||
* The plugin prints "%Y-%m-%d %H:%M" (stamp_of). Parsed
|
||||
* by hand because strptime is not declared under
|
||||
* _POSIX_C_SOURCE, and the format is fixed anyway.
|
||||
*/
|
||||
if (sscanf(date, "%d-%d-%d %d:%d", &y, &mo, &d, &h,
|
||||
&mi) == 5) {
|
||||
memset(&tm, 0, sizeof(tm));
|
||||
tm.tm_year = y - 1900;
|
||||
tm.tm_mon = mo - 1;
|
||||
tm.tm_mday = d;
|
||||
tm.tm_hour = h;
|
||||
tm.tm_min = mi;
|
||||
tm.tm_isdst = -1;
|
||||
mtime = (long)mktime(&tm);
|
||||
}
|
||||
}
|
||||
cb(cbctx, id, label, mtime);
|
||||
n++;
|
||||
}
|
||||
sp_buf_free(&args);
|
||||
sp_buf_free(&out);
|
||||
sp_buf_free(&tmp);
|
||||
return n;
|
||||
}
|
||||
|
||||
static void
|
||||
count_row(void *cbctx, const char *id, const char *label, long mtime)
|
||||
{
|
||||
int *n = cbctx;
|
||||
|
||||
(void)id;
|
||||
(void)label;
|
||||
(void)mtime;
|
||||
(*n)++;
|
||||
}
|
||||
|
||||
/*
|
||||
* Which foreign stores have sessions, and how many. The plugin's own listing
|
||||
* is the authority: a source that lists nothing (no store, an unreadable one,
|
||||
* a tracedb that sqlite3 cannot open) is not offered by the picker, and a store
|
||||
* that gained sessions since the last start shows up without a restart.
|
||||
*/
|
||||
int
|
||||
sp_foreign_sources(struct sp_foreign_target *t, struct sp_foreign_source *v,
|
||||
size_t max)
|
||||
{
|
||||
static const char *const src[] = { "claude", "hermes", "opencode" };
|
||||
struct sp_buf err;
|
||||
size_t i, n = 0;
|
||||
|
||||
if (v == NULL || max == 0)
|
||||
return 0;
|
||||
if (sp_buf_init(&err) != 0)
|
||||
return 0;
|
||||
for (i = 0; i < sizeof(src) / sizeof(src[0]) && n < max; i++) {
|
||||
int rows = 0;
|
||||
int rc;
|
||||
|
||||
/*
|
||||
* The count comes from the same listing the picker will show,
|
||||
* so "claude (82)" and the 82 rows behind it cannot disagree.
|
||||
*/
|
||||
rc = list_rows(t, src[i], count_row, &rows, &err);
|
||||
if (rc < 0 || rows == 0) {
|
||||
sp_buf_clear(&err);
|
||||
continue;
|
||||
}
|
||||
snprintf(v[n].name, sizeof(v[n].name), "%s", src[i]);
|
||||
v[n].count = rows;
|
||||
n++;
|
||||
}
|
||||
sp_buf_free(&err);
|
||||
return (int)n;
|
||||
}
|
||||
|
||||
/*
|
||||
* Every session of one foreign source, as the plugin lists it. One row is
|
||||
* "DATE SOURCE ID TITLE CWD"; the picker gets the id and the rest of the
|
||||
* row, so a title with an odd character in it cannot break the id.
|
||||
*/
|
||||
int
|
||||
sp_foreign_sessions(struct sp_foreign_target *t, const char *source,
|
||||
void (*cb)(void *cbctx, const char *id, const char *label, long mtime),
|
||||
void *cbctx, struct sp_buf *err)
|
||||
{
|
||||
struct sp_buf e;
|
||||
int n;
|
||||
|
||||
if (sp_buf_init(&e) != 0)
|
||||
return -1;
|
||||
n = list_rows(t, source, cb, cbctx, &e);
|
||||
if (n < 0 && err != NULL)
|
||||
sp_buf_printf(err, "%s", e.len > 0 && e.p != NULL ?
|
||||
e.p : "the foreign list failed");
|
||||
sp_buf_free(&e);
|
||||
return n;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* splinter -- continue a session another tool owns: the interface.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* The engine owns its own struct (it is private to engine.c), so this is the
|
||||
* short list of what the import touches. Handing over these instead of the
|
||||
* whole engine keeps the session/registry lifetimes in one place and lets the
|
||||
* import be tested without a running turn.
|
||||
*/
|
||||
#ifndef SPLINTER_FOREIGNOPEN_H
|
||||
#define SPLINTER_FOREIGNOPEN_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
struct sp_host;
|
||||
struct sp_registry;
|
||||
struct sp_embed_ctx;
|
||||
struct sp_buf;
|
||||
|
||||
struct sp_foreign_target {
|
||||
struct sp_session_info *sess;
|
||||
struct sp_registry *reg;
|
||||
struct sp_host *host;
|
||||
struct sp_embed_ctx *emb;
|
||||
};
|
||||
|
||||
/*
|
||||
* Import the newest session `source` ("claude", "opencode", "hermes") ran in
|
||||
* `cwd`, or continue the import that already exists, and make it the session
|
||||
* of this run. Returns 0 when there was nothing to do, when the session was
|
||||
* imported now, or when an earlier import was picked up again; -1 with `err`
|
||||
* filled otherwise.
|
||||
*/
|
||||
int sp_foreign_open(struct sp_foreign_target *t, const char *source,
|
||||
const char *cwd, struct sp_buf *err);
|
||||
|
||||
/* the same for one named session: the picker's choice */
|
||||
int sp_foreign_import(struct sp_foreign_target *t, const char *source,
|
||||
const char *id, struct sp_buf *err);
|
||||
|
||||
/*
|
||||
* The picker behind /sessions needs the other side of that: which foreign
|
||||
* stores have sessions at all, and every session of one store. Both ask the
|
||||
* foreign plugin's own list tool, so the three formats stay in the plugin and
|
||||
* this file only reads the rows it prints.
|
||||
*
|
||||
* sp_foreign_sources fills up to `max` entries with a name ("claude",
|
||||
* "hermes", "opencode") and the number of sessions it holds, and returns how
|
||||
* many it found; a source whose store is missing or unreadable is not one of
|
||||
* them - the picker offers what is there.
|
||||
*/
|
||||
struct sp_foreign_source {
|
||||
char name[16];
|
||||
int count;
|
||||
};
|
||||
int sp_foreign_sources(struct sp_foreign_target *t,
|
||||
struct sp_foreign_source *v, size_t max);
|
||||
|
||||
/*
|
||||
* Every session of `source`, newest first, as the plugin lists it. `label` is
|
||||
* the row without the date and source columns: what a picker can show as is.
|
||||
* `mtime` is the row's date as epoch seconds (0 when the plugin printed "?").
|
||||
* Returns the number of rows, or -1 with `err` filled when the store failed.
|
||||
*/
|
||||
int sp_foreign_sessions(struct sp_foreign_target *t, const char *source,
|
||||
void (*cb)(void *cbctx, const char *id, const char *label, long mtime),
|
||||
void *cbctx, struct sp_buf *err);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,312 @@
|
||||
/*
|
||||
* splinter -- shared HTTP/1.1 request and reply helpers.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "http.h"
|
||||
|
||||
int
|
||||
sp_http_write_all(int fd, const char *buf, size_t len)
|
||||
{
|
||||
while (len > 0) {
|
||||
ssize_t n = write(fd, buf, len);
|
||||
|
||||
if (n <= 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
return -1;
|
||||
}
|
||||
buf += n;
|
||||
len -= (size_t)n;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_http_header_value(const char *hdr, const char *name)
|
||||
{
|
||||
const char *p;
|
||||
size_t n;
|
||||
|
||||
if (hdr == NULL || name == NULL)
|
||||
return NULL;
|
||||
p = strstr(hdr, "\r\n");
|
||||
n = strlen(name);
|
||||
if (p == NULL)
|
||||
return NULL;
|
||||
while ((p = strstr(p, "\r\n")) != NULL) {
|
||||
p += 2;
|
||||
/* the blank line ends the headers; what follows is body */
|
||||
if (*p == '\0' || (p[0] == '\r' && p[1] == '\n'))
|
||||
break;
|
||||
if (strncasecmp(p, name, n) == 0 && p[n] == ':') {
|
||||
const char *v = p + n + 1;
|
||||
|
||||
while (*v == ' ' || *v == '\t')
|
||||
v++;
|
||||
return v;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int
|
||||
sp_http_bearer_is(const char *auth, const char *token)
|
||||
{
|
||||
size_t n;
|
||||
|
||||
if (auth == NULL || token == NULL)
|
||||
return 0;
|
||||
if (strncasecmp(auth, "Bearer ", 7) != 0)
|
||||
return 0;
|
||||
n = strlen(token);
|
||||
if (strncmp(auth + 7, token, n) != 0)
|
||||
return 0;
|
||||
return auth[7 + n] == '\r' || auth[7 + n] == '\n' ||
|
||||
auth[7 + n] == '\0';
|
||||
}
|
||||
|
||||
void
|
||||
sp_http_reply(int fd, int code, const char *reason, const char *type,
|
||||
const char *body)
|
||||
{
|
||||
sp_http_reply_ex(fd, code, reason, type, NULL, body);
|
||||
}
|
||||
|
||||
void
|
||||
sp_http_reply_ex(int fd, int code, const char *reason, const char *type,
|
||||
const char *extra, const char *body)
|
||||
{
|
||||
char hdr[1024];
|
||||
int n;
|
||||
|
||||
n = snprintf(hdr, sizeof(hdr),
|
||||
"HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %zu\r\n"
|
||||
"%sConnection: close\r\n\r\n", code, reason,
|
||||
type != NULL ? type : "application/json",
|
||||
strlen(body != NULL ? body : ""), extra != NULL ? extra : "");
|
||||
if (n > 0 && (size_t)n < sizeof(hdr))
|
||||
(void)sp_http_write_all(fd, hdr, (size_t)n);
|
||||
(void)sp_http_write_all(fd, body != NULL ? body : "",
|
||||
strlen(body != NULL ? body : ""));
|
||||
}
|
||||
|
||||
/* the bytes already read with the header, then the socket */
|
||||
struct http_src {
|
||||
int fd;
|
||||
const char *pre;
|
||||
size_t prelen;
|
||||
size_t pos;
|
||||
};
|
||||
|
||||
static ssize_t
|
||||
src_read(struct http_src *src, char *buf, size_t cap)
|
||||
{
|
||||
size_t n;
|
||||
|
||||
if (src->pos < src->prelen) {
|
||||
n = src->prelen - src->pos;
|
||||
if (n > cap)
|
||||
n = cap;
|
||||
memcpy(buf, src->pre + src->pos, n);
|
||||
src->pos += n;
|
||||
return (ssize_t)n;
|
||||
}
|
||||
return read(src->fd, buf, cap);
|
||||
}
|
||||
|
||||
/* one CRLF-terminated line, without its terminator; -1 on EOF or overflow */
|
||||
static int
|
||||
src_line(struct http_src *src, char *line, size_t cap)
|
||||
{
|
||||
size_t n = 0;
|
||||
|
||||
for (;;) {
|
||||
char ch;
|
||||
ssize_t got = src_read(src, &ch, 1);
|
||||
|
||||
if (got <= 0)
|
||||
return -1;
|
||||
if (ch == '\n')
|
||||
break;
|
||||
if (ch == '\r')
|
||||
continue;
|
||||
if (n + 1 >= cap)
|
||||
return -1;
|
||||
line[n++] = ch;
|
||||
}
|
||||
line[n] = '\0';
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
src_exact(struct http_src *src, size_t n, struct sp_buf *body)
|
||||
{
|
||||
char chunk[4096];
|
||||
|
||||
while (n > 0) {
|
||||
size_t want = n > sizeof(chunk) ? sizeof(chunk) : n;
|
||||
ssize_t got = src_read(src, chunk, want);
|
||||
|
||||
if (got <= 0)
|
||||
return -1;
|
||||
if (sp_buf_add(body, chunk, (size_t)got) != 0)
|
||||
return -1;
|
||||
n -= (size_t)got;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
read_chunked(struct http_src *src, struct sp_buf *body, size_t body_max)
|
||||
{
|
||||
char line[256];
|
||||
|
||||
for (;;) {
|
||||
char *end;
|
||||
unsigned long long n;
|
||||
size_t ln;
|
||||
char tail[2];
|
||||
|
||||
if (src_line(src, line, sizeof(line)) != 0)
|
||||
return -1;
|
||||
if ((end = strchr(line, ';')) != NULL)
|
||||
*end = '\0';
|
||||
ln = strlen(line);
|
||||
while (ln > 0 && (line[ln - 1] == ' ' ||
|
||||
line[ln - 1] == '\t'))
|
||||
line[--ln] = '\0';
|
||||
errno = 0;
|
||||
n = strtoull(line, &end, 16);
|
||||
if (errno != 0 || end == line || *end != '\0')
|
||||
return -1;
|
||||
if (n == 0)
|
||||
break;
|
||||
if (n > (unsigned long long)(body_max - body->len))
|
||||
return -1;
|
||||
if (src_exact(src, (size_t)n, body) != 0)
|
||||
return -1;
|
||||
/* the CRLF that closes the chunk; a read may return 1 byte */
|
||||
{
|
||||
size_t have = 0;
|
||||
|
||||
while (have < sizeof(tail)) {
|
||||
ssize_t got = src_read(src, tail + have,
|
||||
sizeof(tail) - have);
|
||||
|
||||
if (got < 0 && errno == EINTR)
|
||||
continue;
|
||||
if (got <= 0)
|
||||
return -1;
|
||||
have += (size_t)got;
|
||||
}
|
||||
}
|
||||
if (tail[1] != '\n')
|
||||
return -1;
|
||||
}
|
||||
/* trailer section: header lines up to the empty one */
|
||||
for (;;) {
|
||||
if (src_line(src, line, sizeof(line)) != 0)
|
||||
return -1;
|
||||
if (line[0] == '\0')
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int
|
||||
sp_http_begin_stream(int fd)
|
||||
{
|
||||
static const char hdr[] =
|
||||
"HTTP/1.1 200 OK\r\n"
|
||||
"Content-Type: text/event-stream\r\n"
|
||||
"Cache-Control: no-cache\r\n"
|
||||
"X-Accel-Buffering: no\r\n"
|
||||
"Connection: close\r\n\r\n";
|
||||
|
||||
return sp_http_write_all(fd, hdr, sizeof(hdr) - 1);
|
||||
}
|
||||
|
||||
int
|
||||
sp_http_read_request(int fd, char *hdr, size_t cap, struct sp_buf *body,
|
||||
size_t body_max)
|
||||
{
|
||||
size_t used = 0;
|
||||
char *hend;
|
||||
|
||||
for (;;) {
|
||||
ssize_t n;
|
||||
|
||||
if (used >= cap - 1)
|
||||
return -1;
|
||||
n = read(fd, hdr + used, cap - 1 - used);
|
||||
if (n <= 0)
|
||||
return -1;
|
||||
used += (size_t)n;
|
||||
hdr[used] = '\0';
|
||||
if ((hend = strstr(hdr, "\r\n\r\n")) != NULL)
|
||||
break;
|
||||
}
|
||||
{
|
||||
const char *te = sp_http_header_value(hdr,
|
||||
"Transfer-Encoding");
|
||||
|
||||
if (te != NULL) {
|
||||
/*
|
||||
* Only "chunked" is understood. A client that streams
|
||||
* its body has no Content-Length to trust.
|
||||
*/
|
||||
if (strncasecmp(te, "chunked", 7) != 0 ||
|
||||
(te[7] != '\r' && te[7] != '\n' &&
|
||||
te[7] != '\0' && te[7] != ' ' &&
|
||||
te[7] != '\t' && te[7] != ','))
|
||||
return -1;
|
||||
{
|
||||
struct http_src src;
|
||||
|
||||
src.fd = fd;
|
||||
src.pre = hend + 4;
|
||||
src.prelen = used - (size_t)(hend + 4 - hdr);
|
||||
src.pos = 0;
|
||||
if (src.prelen > body_max)
|
||||
return -1;
|
||||
return read_chunked(&src, body, body_max);
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
const char *v = sp_http_header_value(hdr, "Content-Length");
|
||||
long clen = v != NULL ? strtol(v, NULL, 10) : 0;
|
||||
size_t have;
|
||||
|
||||
if (clen < 0 || (size_t)clen > body_max)
|
||||
return -1;
|
||||
have = used - (size_t)(hend + 4 - hdr);
|
||||
if (have > (size_t)clen)
|
||||
have = (size_t)clen;
|
||||
if (have > 0 && sp_buf_add(body, hend + 4, have) != 0)
|
||||
return -1;
|
||||
while (body->len < (size_t)clen) {
|
||||
char chunk[4096];
|
||||
size_t want = (size_t)clen - body->len;
|
||||
ssize_t n;
|
||||
|
||||
if (want > sizeof(chunk))
|
||||
want = sizeof(chunk);
|
||||
n = read(fd, chunk, want);
|
||||
if (n <= 0)
|
||||
return -1;
|
||||
if (sp_buf_add(body, chunk, (size_t)n) != 0)
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* splinter -- the little HTTP/1.1 pieces the JSON servers share.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* Not a web framework: one request per connection, Content-Length only, one
|
||||
* reply, close. That is what a local tool endpoint needs, and it keeps the
|
||||
* parsing auditable. The A2A and MCP servers carry their own older copies;
|
||||
* new services use this one.
|
||||
*/
|
||||
#ifndef SPLINTER_HTTP_H
|
||||
#define SPLINTER_HTTP_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
struct sp_buf;
|
||||
|
||||
#define SP_HTTP_HDR_MAX 16384
|
||||
#define SP_HTTP_BODY_MAX (4 * 1024 * 1024)
|
||||
|
||||
int sp_http_write_all(int fd, const char *buf, size_t len);
|
||||
/* the value of a header, terminated by the CRLF of the next line */
|
||||
const char *sp_http_header_value(const char *hdr, const char *name);
|
||||
int sp_http_bearer_is(const char *auth, const char *token);
|
||||
/* one complete reply; type is the Content-Type, body is NUL-terminated */
|
||||
void sp_http_reply(int fd, int code, const char *reason, const char *type,
|
||||
const char *body);
|
||||
/* the same, with extra header lines (each ending in CRLF) or NULL */
|
||||
void sp_http_reply_ex(int fd, int code, const char *reason,
|
||||
const char *type, const char *extra, const char *body);
|
||||
/*
|
||||
* Start an event stream: status 200, text/event-stream, no Content-Length,
|
||||
* then the caller writes frames and closes the socket.
|
||||
*/
|
||||
int sp_http_begin_stream(int fd);
|
||||
/* headers into hdr, exactly Content-Length bytes into body; 0 or -1 */
|
||||
int sp_http_read_request(int fd, char *hdr, size_t cap,
|
||||
struct sp_buf *body, size_t body_max);
|
||||
|
||||
#endif /* SPLINTER_HTTP_H */
|
||||
+103
-20
@@ -57,7 +57,11 @@ trim(char *s)
|
||||
return s;
|
||||
}
|
||||
|
||||
/* Detect the language from the environment, ignoring the regional part. */
|
||||
/*
|
||||
* The language is English unless a config or SPLINTER_LOCALE says otherwise.
|
||||
* The desktop's LANG is deliberately not consulted: this tool's author works
|
||||
* in a German locale and wants one predictable language in the terminal.
|
||||
*/
|
||||
static void
|
||||
detect_language(const char *override_lang)
|
||||
{
|
||||
@@ -65,12 +69,6 @@ detect_language(const char *override_lang)
|
||||
|
||||
if (cand == NULL || *cand == '\0')
|
||||
cand = getenv("SPLINTER_LOCALE");
|
||||
if (cand == NULL || *cand == '\0')
|
||||
cand = getenv("LC_ALL");
|
||||
if (cand == NULL || *cand == '\0')
|
||||
cand = getenv("LC_MESSAGES");
|
||||
if (cand == NULL || *cand == '\0')
|
||||
cand = getenv("LANG");
|
||||
|
||||
memset(lang, 0, sizeof(lang));
|
||||
if (cand == NULL || *cand == '\0') {
|
||||
@@ -103,6 +101,81 @@ detect_language(const char *override_lang)
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* The printf conversions in 's' as a short signature ("s|zu|*d|"), so that a
|
||||
* catalogue entry can be checked against the text it replaces: catalogue
|
||||
* strings end up as format strings, and one with other conversions than the
|
||||
* caller passes arguments for is undefined behaviour. -1 for %n, which no
|
||||
* message ever needs, or a signature that does not fit.
|
||||
*/
|
||||
static int
|
||||
fmt_sig(const char *s, char *sig, size_t cap)
|
||||
{
|
||||
size_t n = 0;
|
||||
|
||||
if (cap == 0)
|
||||
return -1;
|
||||
sig[0] = '\0';
|
||||
while ((s = strchr(s, '%')) != NULL) {
|
||||
char one[16];
|
||||
size_t k = 0;
|
||||
|
||||
s++;
|
||||
if (*s == '%') {
|
||||
s++;
|
||||
continue;
|
||||
}
|
||||
while (*s != '\0' && strchr("-+ #0'", *s) != NULL)
|
||||
s++;
|
||||
if (*s == '*') {
|
||||
one[k++] = '*';
|
||||
s++;
|
||||
} else
|
||||
while (isdigit((unsigned char)*s))
|
||||
s++;
|
||||
if (*s == '$')
|
||||
return -1; /* positional: not checked, refused */
|
||||
if (*s == '.') {
|
||||
s++;
|
||||
if (*s == '*') {
|
||||
one[k++] = '*';
|
||||
s++;
|
||||
} else
|
||||
while (isdigit((unsigned char)*s))
|
||||
s++;
|
||||
}
|
||||
while (*s != '\0' && strchr("hljztLq", *s) != NULL && k < 8)
|
||||
one[k++] = *s++;
|
||||
if (*s == '\0')
|
||||
break; /* a lone '%' at the end prints nothing */
|
||||
if (*s == 'n')
|
||||
return -1;
|
||||
one[k++] = *s++;
|
||||
one[k++] = '|';
|
||||
if (n + k + 1 > cap)
|
||||
return -1;
|
||||
memcpy(sig + n, one, k);
|
||||
n += k;
|
||||
sig[n] = '\0';
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* may 'text' stand in for 'ref'? Same conversions, never %n */
|
||||
static int
|
||||
fmt_compatible(const char *text, const char *ref)
|
||||
{
|
||||
char a[128], b[128];
|
||||
|
||||
if (fmt_sig(text, a, sizeof(a)) != 0)
|
||||
return 0;
|
||||
if (ref == NULL)
|
||||
return 1;
|
||||
if (fmt_sig(ref, b, sizeof(b)) != 0)
|
||||
return 0;
|
||||
return strcmp(a, b) == 0;
|
||||
}
|
||||
|
||||
static size_t
|
||||
parse_stream(FILE *f, struct entry *cat, size_t max)
|
||||
{
|
||||
@@ -122,8 +195,8 @@ parse_stream(FILE *f, struct entry *cat, size_t max)
|
||||
*eq = '\0';
|
||||
val = trim(eq + 1);
|
||||
key = trim(key);
|
||||
if (*key == '\0')
|
||||
continue;
|
||||
if (*key == '\0' || !fmt_compatible(val, NULL))
|
||||
continue; /* %n: never a message */
|
||||
snprintf(cat[n].key, sizeof(cat[n].key), "%s", key);
|
||||
snprintf(cat[n].text, sizeof(cat[n].text), "%s", val);
|
||||
n++;
|
||||
@@ -227,14 +300,17 @@ sp_t(const char *key)
|
||||
{
|
||||
const char *v;
|
||||
|
||||
const char *en;
|
||||
|
||||
if (key == NULL)
|
||||
return "";
|
||||
v = lookup(main_cat, main_n, key);
|
||||
if (v != NULL)
|
||||
return v;
|
||||
v = lookup(fallback, fallback_n, key);
|
||||
if (v != NULL)
|
||||
en = lookup(fallback, fallback_n, key);
|
||||
/* a translation that takes other arguments than English is not used */
|
||||
if (v != NULL && (en == NULL || fmt_compatible(v, en)))
|
||||
return v;
|
||||
if (en != NULL)
|
||||
return en;
|
||||
return key; /* untranslated keys are visible */
|
||||
}
|
||||
|
||||
@@ -269,11 +345,12 @@ sp_td(const char *key, const char *dflt)
|
||||
|
||||
if (key == NULL)
|
||||
return dflt != NULL ? dflt : "";
|
||||
/* the caller's default says which arguments follow: nothing else fits */
|
||||
v = lookup(main_cat, main_n, key);
|
||||
if (v != NULL)
|
||||
if (v != NULL && fmt_compatible(v, dflt))
|
||||
return v;
|
||||
v = lookup(fallback, fallback_n, key);
|
||||
if (v != NULL)
|
||||
if (v != NULL && fmt_compatible(v, dflt))
|
||||
return v;
|
||||
return dflt != NULL ? dflt : key;
|
||||
}
|
||||
@@ -286,9 +363,10 @@ sp_i18n_init(const char *override_lang)
|
||||
detect_language(override_lang);
|
||||
|
||||
/*
|
||||
* Where catalogues may live. The executable's own directory comes first,
|
||||
* so `splinter` works from any working directory; then the explicit
|
||||
* override, then the source tree, then an installed prefix.
|
||||
* Where catalogues may live: the explicit override, then next to the
|
||||
* executable (the source tree, or <prefix>/bin -> <prefix>/share), then
|
||||
* an installed prefix. Never the working directory: catalogue strings
|
||||
* are format strings, and any repository could ship a share/locale.
|
||||
*/
|
||||
{
|
||||
const char *env = getenv("SPLINTER_LOCALE_DIR");
|
||||
@@ -300,7 +378,7 @@ sp_i18n_init(const char *override_lang)
|
||||
char exe[512];
|
||||
ssize_t n = readlink("/proc/self/exe", exe, sizeof(exe) - 1);
|
||||
|
||||
if (n > 0) {
|
||||
if (n > 0 && exe[0] == '/') {
|
||||
char dir[600];
|
||||
char *slash;
|
||||
|
||||
@@ -310,10 +388,15 @@ sp_i18n_init(const char *override_lang)
|
||||
*slash = '\0';
|
||||
snprintf(dir, sizeof(dir), "%s/share/locale", exe);
|
||||
sp_i18n_add_dir(dir);
|
||||
snprintf(dir, sizeof(dir),
|
||||
"%s/../share/splinter/locale", exe);
|
||||
sp_i18n_add_dir(dir);
|
||||
snprintf(dir, sizeof(dir), "%s/../share/locale",
|
||||
exe);
|
||||
sp_i18n_add_dir(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
sp_i18n_add_dir("share/locale");
|
||||
sp_i18n_add_dir("/usr/local/share/splinter/locale");
|
||||
|
||||
if (sp_buf_init(&err) != 0)
|
||||
File renamed without changes.
@@ -0,0 +1,172 @@
|
||||
/*
|
||||
* splinter -- the first conversation, and what it leaves behind.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* No questionnaire: the model talks to the user, one question at a time, about
|
||||
* whatever it needs to know to work well with them. When it has enough it
|
||||
* writes a summary and ends the answer with INTERVIEW_COMPLETE; that summary
|
||||
* goes to ~/.splinter/USER.txt and is put into the system prompt of every later
|
||||
* session. Facts about the operator should be the operator's, in one readable
|
||||
* file, not six fields a plugin guessed.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "i18n.h"
|
||||
#include "interview.h"
|
||||
|
||||
#define USER_FILE "USER.txt"
|
||||
#define USER_MAX (16 * 1024)
|
||||
#define DONE_LINE "INTERVIEW_COMPLETE"
|
||||
|
||||
static const char *
|
||||
user_path(const char *dir, char *buf, size_t cap)
|
||||
{
|
||||
if (dir == NULL || *dir == '\0')
|
||||
return NULL;
|
||||
snprintf(buf, cap, "%s/%s", dir, USER_FILE);
|
||||
return buf;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_interview_system(void)
|
||||
{
|
||||
return sp_td("interview.system",
|
||||
"You are splinter, about to work with this person for the first "
|
||||
"time. Interview them to get to know them: what they work on, the "
|
||||
"tools and languages they reach for, how they want to be spoken "
|
||||
"to, what they never want, and which projects matter. Ask one "
|
||||
"question at a time, listen, and go deeper where it matters. Do "
|
||||
"not ask about code details you can read from the repository. "
|
||||
"When you have enough, write a compact summary of the person and "
|
||||
"how they want to work (a few paragraphs or bullets), then end "
|
||||
"your answer with the single line INTERVIEW_COMPLETE. That "
|
||||
"summary is saved to ~/.splinter/USER.txt and read at the start "
|
||||
"of every later session.");
|
||||
}
|
||||
|
||||
char *
|
||||
sp_interview_user_block(const char *session_dir)
|
||||
{
|
||||
char path[700];
|
||||
FILE *f;
|
||||
struct sp_buf b;
|
||||
char chunk[4096];
|
||||
size_t n;
|
||||
|
||||
if (user_path(session_dir, path, sizeof(path)) == NULL)
|
||||
return NULL;
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL) {
|
||||
/* an installation from before USER.txt still has the profile */
|
||||
snprintf(path, sizeof(path), "%s/profile/%s.md", session_dir,
|
||||
sp_user_name());
|
||||
f = fopen(path, "r");
|
||||
if (f == NULL)
|
||||
return NULL;
|
||||
}
|
||||
if (sp_buf_init(&b) != 0) {
|
||||
fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
while ((n = fread(chunk, 1, sizeof(chunk), f)) > 0 &&
|
||||
b.len < USER_MAX)
|
||||
if (sp_buf_add(&b, chunk, n) != 0)
|
||||
break;
|
||||
fclose(f);
|
||||
if (b.len == 0) {
|
||||
sp_buf_free(&b);
|
||||
return NULL;
|
||||
}
|
||||
{
|
||||
struct sp_buf out;
|
||||
|
||||
if (sp_buf_init(&out) != 0) {
|
||||
sp_buf_free(&b);
|
||||
return NULL;
|
||||
}
|
||||
if (sp_buf_puts(&out, "\n\nWhat you know about the user "
|
||||
"(from the interview):\n") != 0 ||
|
||||
sp_buf_add(&out, b.p, b.len) != 0) {
|
||||
sp_buf_free(&b);
|
||||
sp_buf_free(&out);
|
||||
return NULL;
|
||||
}
|
||||
sp_buf_free(&b);
|
||||
return out.p;
|
||||
}
|
||||
}
|
||||
|
||||
int
|
||||
sp_interview_capture(const char *session_dir, const char *answer, char *clean,
|
||||
size_t cap)
|
||||
{
|
||||
char path[700], tmp[800];
|
||||
const char *mark;
|
||||
FILE *f;
|
||||
size_t n;
|
||||
|
||||
if (session_dir == NULL || *session_dir == '\0' || answer == NULL ||
|
||||
clean == NULL || cap == 0)
|
||||
return 0;
|
||||
mark = strstr(answer, DONE_LINE);
|
||||
if (mark == NULL)
|
||||
return 0;
|
||||
n = (size_t)(mark - answer);
|
||||
while (n > 0 && (answer[n - 1] == '\n' || answer[n - 1] == '\r' ||
|
||||
answer[n - 1] == ' ' || answer[n - 1] == '\t'))
|
||||
n--;
|
||||
if (n == 0)
|
||||
return 0;
|
||||
snprintf(clean, cap, "%.*s", (int)(n < cap ? n : cap - 1), answer);
|
||||
if (user_path(session_dir, path, sizeof(path)) == NULL)
|
||||
return 0;
|
||||
snprintf(tmp, sizeof(tmp), "%s.tmp", path);
|
||||
f = fopen(tmp, "w");
|
||||
if (f == NULL)
|
||||
return 0;
|
||||
{
|
||||
int bad = fprintf(f, "%s\n", clean) < 0;
|
||||
|
||||
/* always closed, even when the write failed */
|
||||
if (fclose(f) != 0)
|
||||
bad = 1;
|
||||
if (bad) {
|
||||
(void)unlink(tmp);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
(void)chmod(tmp, 0600);
|
||||
if (rename(tmp, path) != 0) {
|
||||
(void)unlink(tmp);
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
int
|
||||
sp_profile_exists(const char *session_dir)
|
||||
{
|
||||
char path[700];
|
||||
|
||||
if (user_path(session_dir, path, sizeof(path)) == NULL)
|
||||
return 0;
|
||||
if (access(path, F_OK) == 0)
|
||||
return 1;
|
||||
/* an installation from before USER.txt: profile/<user>.md */
|
||||
{
|
||||
char dir[700];
|
||||
const char *user = sp_user_name();
|
||||
|
||||
snprintf(dir, sizeof(dir), "%s/profile/%s.md", session_dir, user);
|
||||
return access(dir, F_OK) == 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* splinter -- the first conversation, and what it leaves behind.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#ifndef SPLINTER_INTERVIEW_H
|
||||
#define SPLINTER_INTERVIEW_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
/*
|
||||
* The interview is a model-driven conversation: the system prompt tells the
|
||||
* model to get to know the user and end with INTERVIEW_COMPLETE. The summary
|
||||
* before that line is written to <session dir>/USER.txt and read at the start
|
||||
* of every later session.
|
||||
*/
|
||||
const char *sp_interview_system(void);
|
||||
|
||||
/* "\n\nWhat you know about the user:\n...", malloc'd; NULL when there is none. */
|
||||
char *sp_interview_user_block(const char *session_dir);
|
||||
|
||||
/*
|
||||
* If answer carries INTERVIEW_COMPLETE, write the summary to USER.txt and copy
|
||||
* the answer without the marker to clean. 1 when it captured something.
|
||||
*/
|
||||
int sp_interview_capture(const char *session_dir, const char *answer,
|
||||
char *clean, size_t cap);
|
||||
|
||||
/* 1 when USER.txt exists (the old profile/<user>.md still counts). */
|
||||
int sp_profile_exists(const char *session_dir);
|
||||
|
||||
#endif /* SPLINTER_INTERVIEW_H */
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -29,7 +29,9 @@
|
||||
*/
|
||||
#include <arpa/inet.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <netinet/in.h>
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -40,11 +42,32 @@
|
||||
#include <unistd.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_engine.h"
|
||||
#include "mcp.h"
|
||||
#include "mcpserver.h"
|
||||
#include "mcpsession.h"
|
||||
|
||||
static volatile int mcp_stop;
|
||||
|
||||
/*
|
||||
* What a connection works on. With an engine the registry is asked from it on
|
||||
* every call (a session switch replaces the engine and with it the registry);
|
||||
* without one the server serves the registry it was handed.
|
||||
*/
|
||||
struct srv {
|
||||
struct sp_engine **eng;
|
||||
const struct sp_engine_opts *opts;
|
||||
const struct sp_registry *reg;
|
||||
};
|
||||
|
||||
static const struct sp_registry *
|
||||
srv_reg(const struct srv *s)
|
||||
{
|
||||
if (s->eng != NULL && *s->eng != NULL)
|
||||
return sp_engine_registry(*s->eng);
|
||||
return s->reg;
|
||||
}
|
||||
|
||||
static void
|
||||
on_signal(int sig)
|
||||
{
|
||||
@@ -52,6 +75,51 @@ on_signal(int sig)
|
||||
mcp_stop = 1;
|
||||
}
|
||||
|
||||
void
|
||||
sp_mcp_stop(void)
|
||||
{
|
||||
mcp_stop = 1;
|
||||
}
|
||||
|
||||
int
|
||||
sp_mcp_stopping(void)
|
||||
{
|
||||
return mcp_stop != 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Wait until fd is readable, in short slices so a stop request is seen
|
||||
* within a quarter second. 1: readable, 0: stopped or timed out (ms <= 0
|
||||
* waits for ever), -1: error.
|
||||
*/
|
||||
#define MCP_SLICE_MS 250
|
||||
|
||||
static int
|
||||
wait_readable(int fd, long ms)
|
||||
{
|
||||
long waited = 0;
|
||||
|
||||
while (!mcp_stop) {
|
||||
struct pollfd pfd;
|
||||
int r;
|
||||
|
||||
pfd.fd = fd;
|
||||
pfd.events = POLLIN;
|
||||
pfd.revents = 0;
|
||||
r = poll(&pfd, 1, MCP_SLICE_MS);
|
||||
if (r > 0)
|
||||
return 1;
|
||||
if (r < 0 && errno != EINTR)
|
||||
return -1;
|
||||
if (r == 0) {
|
||||
waited += MCP_SLICE_MS;
|
||||
if (ms > 0 && waited >= ms)
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* The object that follows "arguments" in the raw line, braces balanced. */
|
||||
static const char *
|
||||
slice_object(const char *at, size_t *lenp)
|
||||
@@ -132,21 +200,24 @@ reply_error(int fd, int id, int code, const char *message)
|
||||
}
|
||||
|
||||
static void
|
||||
reply_tools(int fd, int id, const struct sp_registry *reg)
|
||||
reply_tools(int fd, int id, const struct srv *s)
|
||||
{
|
||||
struct sp_buf b;
|
||||
size_t i, ntv;
|
||||
const struct sp_tool *tv;
|
||||
size_t i, ntv = 0;
|
||||
const struct sp_tool *tv = NULL;
|
||||
int first = 1;
|
||||
|
||||
if (sp_buf_init(&b) != 0)
|
||||
return;
|
||||
sp_buf_puts(&b, "{\"tools\":[");
|
||||
tv = sp_registry_tools(reg, &ntv);
|
||||
if (srv_reg(s) != NULL)
|
||||
tv = sp_registry_tools(srv_reg(s), &ntv);
|
||||
for (i = 0; i < ntv; i++) {
|
||||
const struct sp_tool *t = &tv[i];
|
||||
|
||||
if (i > 0)
|
||||
if (!first)
|
||||
sp_buf_puts(&b, ",");
|
||||
first = 0;
|
||||
sp_buf_puts(&b, "{\"name\":\"");
|
||||
(void)sp_json_escape(&b, t->name);
|
||||
sp_buf_puts(&b, "\",\"description\":\"");
|
||||
@@ -157,20 +228,22 @@ reply_tools(int fd, int id, const struct sp_registry *reg)
|
||||
"{\"type\":\"object\",\"properties\":{}}");
|
||||
sp_buf_puts(&b, "}");
|
||||
}
|
||||
sp_mcpsession_tools(&b, &first);
|
||||
sp_buf_puts(&b, "]}");
|
||||
reply_ok(fd, id, b.p);
|
||||
sp_buf_free(&b);
|
||||
}
|
||||
|
||||
static void
|
||||
call_tool(int fd, int id, const struct sp_registry *reg, const char *line,
|
||||
int allow_mutate)
|
||||
call_tool(int fd, int id, const struct srv *s, const char *line)
|
||||
{
|
||||
const struct sp_tool *t;
|
||||
const char *name, *argstart;
|
||||
const char *name, *argstart = NULL;
|
||||
char namebuf[128];
|
||||
struct sp_buf raw, out;
|
||||
mcp_json *v;
|
||||
size_t arglen = 0;
|
||||
int mine;
|
||||
|
||||
v = mcp_parse(line);
|
||||
if (v == NULL) {
|
||||
@@ -178,7 +251,6 @@ call_tool(int fd, int id, const struct sp_registry *reg, const char *line,
|
||||
return;
|
||||
}
|
||||
name = NULL;
|
||||
argstart = NULL;
|
||||
{
|
||||
const mcp_json *params = mcp_arg(v, "params");
|
||||
const mcp_json *args;
|
||||
@@ -194,18 +266,10 @@ call_tool(int fd, int id, const struct sp_registry *reg, const char *line,
|
||||
reply_error(fd, id, -32602, "params.name is required");
|
||||
return;
|
||||
}
|
||||
t = sp_registry_find(reg, name);
|
||||
if (t == NULL) {
|
||||
mcp_json_free(v);
|
||||
reply_error(fd, id, -32601, "unknown tool");
|
||||
return;
|
||||
}
|
||||
if (t->auth != SP_AUTH_READ && !allow_mutate) {
|
||||
mcp_json_free(v);
|
||||
reply_error(fd, id, -32000, "tool needs authorization; start the "
|
||||
"server with --autonomous to allow mutating calls");
|
||||
return;
|
||||
}
|
||||
/* the name lives in the parsed JSON: copy it before freeing that */
|
||||
snprintf(namebuf, sizeof(namebuf), "%s", name);
|
||||
name = namebuf;
|
||||
mine = sp_mcpsession_has(name);
|
||||
/* the arguments object, as text - tools parse their own arguments */
|
||||
{
|
||||
const char *p = strstr(line, "\"arguments\"");
|
||||
@@ -224,13 +288,23 @@ call_tool(int fd, int id, const struct sp_registry *reg, const char *line,
|
||||
(void)sp_buf_add(&raw, argstart, arglen);
|
||||
else
|
||||
(void)sp_buf_puts(&raw, "{}");
|
||||
|
||||
if (sp_buf_init(&out) != 0) {
|
||||
sp_buf_free(&raw);
|
||||
return;
|
||||
}
|
||||
if (t->run(raw.p, &out, t->ctx) != 0)
|
||||
sp_buf_puts(&out, "error: tool failed");
|
||||
if (mine) {
|
||||
(void)sp_mcpsession_call(name, raw.p, &out);
|
||||
} else {
|
||||
t = srv_reg(s) != NULL ? sp_registry_find(srv_reg(s), name) : NULL;
|
||||
if (t == NULL) {
|
||||
sp_buf_free(&raw);
|
||||
sp_buf_free(&out);
|
||||
reply_error(fd, id, -32601, "unknown tool");
|
||||
return;
|
||||
}
|
||||
if (t->run(raw.p, &out, t->ctx) != 0)
|
||||
sp_buf_puts(&out, "error: tool failed");
|
||||
}
|
||||
{
|
||||
struct sp_buf res;
|
||||
|
||||
@@ -247,8 +321,7 @@ call_tool(int fd, int id, const struct sp_registry *reg, const char *line,
|
||||
}
|
||||
|
||||
static void
|
||||
handle_line(int fd, const struct sp_registry *reg, const char *line,
|
||||
int allow_mutate)
|
||||
handle_line(int fd, const struct srv *s, const char *line)
|
||||
{
|
||||
mcp_json *v;
|
||||
const char *method;
|
||||
@@ -278,12 +351,12 @@ handle_line(int fd, const struct sp_registry *reg, const char *line,
|
||||
}
|
||||
if (strcmp(method, "tools/list") == 0) {
|
||||
mcp_json_free(v);
|
||||
reply_tools(fd, id, reg);
|
||||
reply_tools(fd, id, s);
|
||||
return;
|
||||
}
|
||||
if (strcmp(method, "tools/call") == 0) {
|
||||
mcp_json_free(v);
|
||||
call_tool(fd, id, reg, line, allow_mutate);
|
||||
call_tool(fd, id, s, line);
|
||||
return;
|
||||
}
|
||||
mcp_json_free(v);
|
||||
@@ -305,15 +378,19 @@ token_equal(const char *a, const char *b)
|
||||
}
|
||||
|
||||
static void
|
||||
serve_conn(int fd, const struct sp_registry *reg, int allow_mutate,
|
||||
const char *token)
|
||||
serve_conn(int fd, const struct srv *s, const char *token)
|
||||
{
|
||||
char line[16384];
|
||||
size_t used = 0;
|
||||
int authed = token == NULL;
|
||||
|
||||
for (;;) {
|
||||
ssize_t got = read(fd, line + used, sizeof(line) - used - 1);
|
||||
ssize_t got;
|
||||
|
||||
/* five quiet minutes close the connection, so does a stop */
|
||||
if (wait_readable(fd, 300 * 1000L) != 1)
|
||||
return;
|
||||
got = read(fd, line + used, sizeof(line) - used - 1);
|
||||
|
||||
if (got <= 0) {
|
||||
if (got < 0 && errno == EINTR)
|
||||
@@ -342,7 +419,7 @@ serve_conn(int fd, const struct sp_registry *reg, int allow_mutate,
|
||||
}
|
||||
authed = 1;
|
||||
} else if (line[0] == '{')
|
||||
handle_line(fd, reg, line, allow_mutate);
|
||||
handle_line(fd, s, line);
|
||||
len = (size_t)(nl - line) + 1;
|
||||
memmove(line, line + len, used - len + 1);
|
||||
used -= len;
|
||||
@@ -353,13 +430,24 @@ serve_conn(int fd, const struct sp_registry *reg, int allow_mutate,
|
||||
}
|
||||
|
||||
int
|
||||
sp_mcp_serve(const struct sp_registry *reg, const char *ip, int port,
|
||||
int allow_mutate, struct sp_buf *err)
|
||||
sp_mcp_serve(struct sp_engine **eng, const struct sp_engine_opts *opts,
|
||||
const struct sp_registry *reg, const char *ip, int port,
|
||||
int own_signals, struct sp_buf *err)
|
||||
{
|
||||
struct srv srv;
|
||||
int s, one = 1;
|
||||
struct sockaddr_in addr;
|
||||
|
||||
const char *token = getenv("SPLINTER_MCP_TOKEN");
|
||||
size_t ntools = reg != NULL ? reg->len : 0;
|
||||
|
||||
memset(&srv, 0, sizeof(srv));
|
||||
srv.eng = eng;
|
||||
srv.opts = opts;
|
||||
srv.reg = reg;
|
||||
sp_mcpsession_bind(eng, opts);
|
||||
if (eng != NULL && *eng != NULL && srv_reg(&srv) != NULL)
|
||||
ntools = srv_reg(&srv)->len;
|
||||
|
||||
if (ip == NULL || *ip == '\0')
|
||||
ip = "127.0.0.1";
|
||||
@@ -376,6 +464,8 @@ sp_mcp_serve(const struct sp_registry *reg, const char *ip, int port,
|
||||
sp_buf_printf(err, "mcp: socket: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
/* a tool child must not inherit the socket: see a2aserver.c */
|
||||
(void)fcntl(s, F_SETFD, FD_CLOEXEC);
|
||||
(void)setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
|
||||
memset(&addr, 0, sizeof(addr));
|
||||
addr.sin_family = AF_INET;
|
||||
@@ -396,22 +486,31 @@ sp_mcp_serve(const struct sp_registry *reg, const char *ip, int port,
|
||||
close(s);
|
||||
return -1;
|
||||
}
|
||||
(void)signal(SIGINT, on_signal);
|
||||
(void)signal(SIGTERM, on_signal);
|
||||
if (own_signals) {
|
||||
(void)signal(SIGINT, on_signal);
|
||||
(void)signal(SIGTERM, on_signal);
|
||||
}
|
||||
/* a client that hangs up mid-reply is a closed connection, not our death */
|
||||
(void)signal(SIGPIPE, SIG_IGN);
|
||||
fprintf(stderr, "splinter: MCP server on %s:%d (%zu tools, %s, %s)\n",
|
||||
ip, port, reg->len, allow_mutate ? "mutating allowed" : "read only",
|
||||
fprintf(stderr, "splinter: MCP server on %s:%d (%zu tools + %d "
|
||||
"session tools, %s)\n", ip, port, ntools, 12,
|
||||
token != NULL ? "token required" : "loopback, no token");
|
||||
|
||||
while (!mcp_stop) {
|
||||
int c = accept(s, NULL, NULL);
|
||||
int c, w;
|
||||
|
||||
w = wait_readable(s, 0);
|
||||
if (w < 0)
|
||||
break;
|
||||
if (w == 0)
|
||||
continue; /* stopping: the loop test ends it */
|
||||
c = accept(s, NULL, NULL);
|
||||
if (c < 0) {
|
||||
if (errno == EINTR)
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
(void)fcntl(c, F_SETFD, FD_CLOEXEC);
|
||||
{
|
||||
/*
|
||||
* One connection at a time, so an idle one must not hold
|
||||
@@ -422,7 +521,7 @@ sp_mcp_serve(const struct sp_registry *reg, const char *ip, int port,
|
||||
(void)setsockopt(c, SOL_SOCKET, SO_RCVTIMEO, &tv,
|
||||
sizeof(tv));
|
||||
}
|
||||
serve_conn(c, reg, allow_mutate, token);
|
||||
serve_conn(c, &srv, token);
|
||||
close(c);
|
||||
}
|
||||
close(s);
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* splinter -- the MCP server.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#ifndef SPLINTER_MCPSERVER_H
|
||||
#define SPLINTER_MCPSERVER_H
|
||||
|
||||
#include "splinter.h"
|
||||
|
||||
struct sp_engine;
|
||||
struct sp_engine_opts;
|
||||
|
||||
/*
|
||||
* eng/opts make the session tools work; NULL eng serves the registry only.
|
||||
* own_signals: 0 when the caller already has SIGINT/SIGTERM handlers (the
|
||||
* daemon runs the MCP server in a thread).
|
||||
*/
|
||||
int sp_mcp_serve(struct sp_engine **eng, const struct sp_engine_opts *opts,
|
||||
const struct sp_registry *, const char *ip, int port,
|
||||
int own_signals, struct sp_buf *err);
|
||||
|
||||
/*
|
||||
* Ask a running sp_mcp_serve() to return: it stops accepting, closes the
|
||||
* connection it serves and cancels a splinter_say turn, within a quarter
|
||||
* second or so. For a server on its own thread, before joining it.
|
||||
*/
|
||||
void sp_mcp_stop(void);
|
||||
int sp_mcp_stopping(void);
|
||||
|
||||
#endif /* SPLINTER_MCPSERVER_H */
|
||||
@@ -0,0 +1,628 @@
|
||||
/*
|
||||
* splinter -- the session tools of the MCP server.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* The file tools the MCP server exposes are the ones any MCP client already
|
||||
* has. What only splinter can answer is its own sessions: which exist, what
|
||||
* they said, what the model is, and how to put a prompt in and get the answer
|
||||
* back. That is this file.
|
||||
*
|
||||
* splinter_sessions list the sessions of this state directory
|
||||
* splinter_state model, profile, session, busy, counters
|
||||
* splinter_models the selectors /model takes
|
||||
* splinter_history the open session's user and assistant messages
|
||||
* splinter_agents the profiles
|
||||
* splinter_say submit a prompt, wait, return the answer
|
||||
* splinter_open switch to another session (or "new")
|
||||
* splinter_model switch the model (an ordinary /model selector)
|
||||
* splinter_agent switch the profile by name
|
||||
* splinter_steer type into the running turn
|
||||
* splinter_cancel cancel the running turn
|
||||
* splinter_answer answer the question the `ask` tool put to the operator
|
||||
*
|
||||
* A turn that parks on `ask` is not an error: splinter_say returns the
|
||||
* question and leaves the turn waiting, and splinter_answer answers it. The
|
||||
* server is one connection at a time, so there is at most one such turn.
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_engine.h"
|
||||
#include "mcp.h"
|
||||
#include "mcpserver.h"
|
||||
#include "mcpsession.h"
|
||||
|
||||
static struct sp_engine **session_eng;
|
||||
static const struct sp_engine_opts *session_opts;
|
||||
|
||||
#define SAY_TIMEOUT_S 3600
|
||||
#define SAY_ANSWER_MAX (256 * 1024)
|
||||
#define SAY_TEXT_MAX 8192
|
||||
#define HIST_TEXT_MAX 600
|
||||
#define BUSY_MSG "error: busy - a turn is running; wait or cancel it"
|
||||
|
||||
void
|
||||
sp_mcpsession_bind(struct sp_engine **eng, const struct sp_engine_opts *opts)
|
||||
{
|
||||
session_eng = eng;
|
||||
session_opts = opts;
|
||||
}
|
||||
|
||||
static const char *
|
||||
arg_string(const char *args, const char *key, char *out, size_t cap)
|
||||
{
|
||||
mcp_json *v;
|
||||
const char *s;
|
||||
|
||||
out[0] = '\0';
|
||||
if (args == NULL || *args == '\0')
|
||||
return out;
|
||||
v = mcp_parse(args);
|
||||
if (v == NULL)
|
||||
return out;
|
||||
s = mcp_arg_string(v, key);
|
||||
if (s != NULL)
|
||||
snprintf(out, cap, "%s", s);
|
||||
mcp_json_free(v);
|
||||
return out;
|
||||
}
|
||||
|
||||
static int
|
||||
arg_int(const char *args, const char *key, int dflt)
|
||||
{
|
||||
mcp_json *v;
|
||||
int n = dflt;
|
||||
|
||||
if (args == NULL || *args == '\0')
|
||||
return dflt;
|
||||
v = mcp_parse(args);
|
||||
if (v == NULL)
|
||||
return dflt;
|
||||
n = mcp_arg_int(v, key, dflt);
|
||||
mcp_json_free(v);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* ---- the tools ---- */
|
||||
|
||||
static const struct {
|
||||
const char *name;
|
||||
int auth;
|
||||
const char *description;
|
||||
const char *schema;
|
||||
} tools[] = {
|
||||
{ "splinter_sessions", SP_AUTH_READ,
|
||||
"List the splinter sessions in this state directory: id, title, "
|
||||
"mtime, size, and which one is open.",
|
||||
"{\"type\":\"object\",\"properties\":{}}" },
|
||||
{ "splinter_state", SP_AUTH_READ,
|
||||
"The running splinter: model, endpoint, profile, session, directory, "
|
||||
"busy/waiting, tokens, context use and the last turn.",
|
||||
"{\"type\":\"object\",\"properties\":{}}" },
|
||||
{ "splinter_models", SP_AUTH_READ,
|
||||
"The selectors /model takes (providers, then pools), with the current "
|
||||
"one marked.",
|
||||
"{\"type\":\"object\",\"properties\":{}}" },
|
||||
{ "splinter_agents", SP_AUTH_READ,
|
||||
"The agent profiles of this run, with the active one marked.",
|
||||
"{\"type\":\"object\",\"properties\":{}}" },
|
||||
{ "splinter_history", SP_AUTH_READ,
|
||||
"The open session's user and assistant messages, oldest first.",
|
||||
"{\"type\":\"object\",\"properties\":{\"limit\":{\"type\":\"integer\","
|
||||
"\"description\":\"how many messages, default 20, max 100\"}}}" },
|
||||
{ "splinter_say", SP_AUTH_MUTATE,
|
||||
"Send a prompt to the open session and wait for the answer. Returns "
|
||||
"the answer; if the model asks a question, returns it and leaves the "
|
||||
"turn parked (call splinter_answer).",
|
||||
"{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\","
|
||||
"\"description\":\"the prompt\"}},\"required\":[\"text\"]}" },
|
||||
{ "splinter_open", SP_AUTH_MUTATE,
|
||||
"Switch splinter to another session: a session id, \"new\" for a fresh "
|
||||
"one, or \"last\" for the newest.",
|
||||
"{\"type\":\"object\",\"properties\":{\"session\":{\"type\":\"string\","
|
||||
"\"description\":\"session id, new or last\"}},"
|
||||
"\"required\":[\"session\"]}" },
|
||||
{ "splinter_model", SP_AUTH_MUTATE,
|
||||
"Switch the model: a provider id, a pool id, provider/model, or a "
|
||||
"model name the provider serves (the same selector /model takes).",
|
||||
"{\"type\":\"object\",\"properties\":{\"model\":{\"type\":\"string\","
|
||||
"\"description\":\"what goes after /model\"}},\"required\":[\"model\"]}" },
|
||||
{ "splinter_agent", SP_AUTH_MUTATE,
|
||||
"Switch the agent profile by name.",
|
||||
"{\"type\":\"object\",\"properties\":{\"agent\":{\"type\":\"string\","
|
||||
"\"description\":\"profile name\"}},\"required\":[\"agent\"]}" },
|
||||
{ "splinter_steer", SP_AUTH_MUTATE,
|
||||
"Type into the running turn; the loop picks it up at the next step "
|
||||
"boundary.",
|
||||
"{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\","
|
||||
"\"description\":\"the steering text\"}},\"required\":[\"text\"]}" },
|
||||
{ "splinter_cancel", SP_AUTH_MUTATE,
|
||||
"Cancel the running turn.", "{\"type\":\"object\",\"properties\":{}}" },
|
||||
{ "splinter_answer", SP_AUTH_MUTATE,
|
||||
"Answer the question the `ask` tool put to the operator: the text of "
|
||||
"the answer. Use it when splinter_say returns \"the model asks\".",
|
||||
"{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\","
|
||||
"\"description\":\"the answer\"}},\"required\":[\"text\"]}" }
|
||||
};
|
||||
|
||||
int
|
||||
sp_mcpsession_has(const char *name)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < sizeof(tools) / sizeof(tools[0]); i++)
|
||||
if (strcmp(tools[i].name, name) == 0)
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_mcpsession_auth(const char *name)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < sizeof(tools) / sizeof(tools[0]); i++)
|
||||
if (strcmp(tools[i].name, name) == 0)
|
||||
return tools[i].auth;
|
||||
return SP_AUTH_READ;
|
||||
}
|
||||
|
||||
/* the JSON entries for tools/list, each prefixed with a comma when !first */
|
||||
void
|
||||
sp_mcpsession_tools(struct sp_buf *b, int *first)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < sizeof(tools) / sizeof(tools[0]); i++) {
|
||||
if (!*first)
|
||||
sp_buf_puts(b, ",");
|
||||
*first = 0;
|
||||
sp_buf_puts(b, "{\"name\":\"");
|
||||
(void)sp_json_escape(b, tools[i].name);
|
||||
sp_buf_puts(b, "\",\"description\":\"");
|
||||
(void)sp_json_escape(b, tools[i].description);
|
||||
sp_buf_puts(b, "\",\"inputSchema\":");
|
||||
sp_buf_puts(b, tools[i].schema);
|
||||
sp_buf_puts(b, "}");
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the handlers ---- */
|
||||
|
||||
static int
|
||||
tool_sessions(struct sp_buf *out)
|
||||
{
|
||||
struct sp_session_brief v[200];
|
||||
const char *cur;
|
||||
int n, i;
|
||||
const char *dir;
|
||||
|
||||
dir = sp_engine_state_dir(*session_eng);
|
||||
cur = sp_engine_session_id(*session_eng);
|
||||
n = sp_session_list(dir, v, 200);
|
||||
if (n < 0)
|
||||
n = 0;
|
||||
for (i = 0; i < n; i++) {
|
||||
char when[32] = "";
|
||||
time_t t = (time_t)v[i].mtime;
|
||||
struct tm tm;
|
||||
|
||||
if (localtime_r(&t, &tm) != NULL)
|
||||
strftime(when, sizeof(when), "%Y-%m-%d %H:%M", &tm);
|
||||
sp_buf_printf(out, "%c %s %-28s %7zu %s\n",
|
||||
strcmp(v[i].id, cur) == 0 ? '*' : ' ', when, v[i].id,
|
||||
v[i].bytes, v[i].title);
|
||||
}
|
||||
if (n == 0)
|
||||
sp_buf_puts(out, "no sessions yet\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_state(struct sp_buf *out)
|
||||
{
|
||||
struct sp_engine_state st;
|
||||
|
||||
if (sp_engine_state(*session_eng, &st) != 0) {
|
||||
sp_buf_puts(out, "error: no engine");
|
||||
return 0;
|
||||
}
|
||||
sp_buf_printf(out, "model: %s\n", st.model);
|
||||
sp_buf_printf(out, "endpoint: %s\n", st.endpoint);
|
||||
sp_buf_printf(out, "agent: %s\n", st.agent);
|
||||
sp_buf_printf(out, "session: %s\n", st.session);
|
||||
sp_buf_printf(out, "dir: %s\n", st.dir);
|
||||
sp_buf_printf(out, "busy: %s%s\n", st.busy ? "yes" : "no",
|
||||
st.asking ? " (the model is waiting for an answer)" : "");
|
||||
sp_buf_printf(out, "tokens: %zu in / %zu out\n", st.tokens_in,
|
||||
st.tokens_out);
|
||||
sp_buf_printf(out, "ctx: %zu/%zu", st.ctx_used, st.ctx_max);
|
||||
if (st.ctx_max > 0)
|
||||
sp_buf_printf(out, " (%u%%)",
|
||||
(unsigned)(100.0 * (double)st.ctx_used / (double)st.ctx_max));
|
||||
sp_buf_puts(out, "\n");
|
||||
sp_buf_printf(out, "last turn: %zu ms, %zu steps, %zu calls\n",
|
||||
st.last_ms, st.last_steps, st.last_calls);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_models(struct sp_buf *out)
|
||||
{
|
||||
struct sp_model_choice v[SP_MODEL_CHOICES];
|
||||
size_t n, i;
|
||||
|
||||
n = sp_engine_models(*session_eng, v, SP_MODEL_CHOICES);
|
||||
for (i = 0; i < n; i++)
|
||||
sp_buf_printf(out, "%c %-16s %s\n", v[i].current ? '*' : ' ',
|
||||
v[i].sel, v[i].label);
|
||||
if (n == 0)
|
||||
sp_buf_puts(out, "no models configured\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_agents(struct sp_buf *out)
|
||||
{
|
||||
int n, i, cur;
|
||||
|
||||
n = sp_engine_agents(*session_eng);
|
||||
cur = sp_engine_agent_cur(*session_eng);
|
||||
for (i = 0; i < n; i++)
|
||||
sp_buf_printf(out, "%c %s\n", i == cur ? '*' : ' ',
|
||||
sp_engine_agent_name(*session_eng, i));
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_history(const char *args, struct sp_buf *out)
|
||||
{
|
||||
const struct sp_conv *conv = sp_engine_conv(*session_eng);
|
||||
int limit = arg_int(args, "limit", 20);
|
||||
size_t i, from;
|
||||
|
||||
if (limit <= 0)
|
||||
limit = 20;
|
||||
if (limit > 100)
|
||||
limit = 100;
|
||||
if (conv == NULL) {
|
||||
sp_buf_puts(out, "no conversation");
|
||||
return 0;
|
||||
}
|
||||
/* a running turn (the engine's or the daemon's) is writing to it */
|
||||
if (sp_engine_hold(*session_eng) != 0) {
|
||||
sp_buf_puts(out, BUSY_MSG);
|
||||
return 0;
|
||||
}
|
||||
from = conv->n > (size_t)limit ? conv->n - (size_t)limit : 0;
|
||||
for (i = from; i < conv->n; i++) {
|
||||
const struct sp_msg *m = &conv->v[i];
|
||||
char text[HIST_TEXT_MAX + 1];
|
||||
|
||||
if (m->role == NULL || m->content == NULL)
|
||||
continue;
|
||||
if (strcmp(m->role, "user") != 0 &&
|
||||
strcmp(m->role, "assistant") != 0)
|
||||
continue;
|
||||
snprintf(text, sizeof(text), "%s", m->content);
|
||||
sp_buf_printf(out, "[%s] %s\n", m->role, text);
|
||||
}
|
||||
sp_engine_release(*session_eng);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* drain the events of a turn; returns 0 while it is still running */
|
||||
static int
|
||||
collect(struct sp_engine *e, char *answer, size_t cap, int *known,
|
||||
size_t *steps, size_t *calls)
|
||||
{
|
||||
struct sp_event ev;
|
||||
|
||||
while (sp_engine_poll(e, &ev)) {
|
||||
switch (ev.kind) {
|
||||
case SP_EV_TURN_END:
|
||||
if (ev.a != NULL)
|
||||
snprintf(answer, cap, "%s", ev.a);
|
||||
if (ev.b != NULL && ev.n != 0)
|
||||
snprintf(answer, cap, "error: %s", ev.b);
|
||||
*known = 1;
|
||||
break;
|
||||
case SP_EV_STEP:
|
||||
(*steps)++;
|
||||
break;
|
||||
case SP_EV_TOOL:
|
||||
(*calls)++;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
sp_engine_event_free(&ev);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_say(const char *args, struct sp_buf *out)
|
||||
{
|
||||
struct sp_engine *e = *session_eng;
|
||||
char *text, *answer;
|
||||
size_t steps = 0, calls = 0;
|
||||
int known = 0;
|
||||
time_t deadline;
|
||||
|
||||
/* an MCP thread's stack is small: the buffers live on the heap */
|
||||
text = malloc(SAY_TEXT_MAX);
|
||||
answer = malloc(SAY_ANSWER_MAX);
|
||||
if (text == NULL || answer == NULL) {
|
||||
free(text);
|
||||
free(answer);
|
||||
sp_buf_puts(out, "error: out of memory");
|
||||
return 0;
|
||||
}
|
||||
answer[0] = '\0';
|
||||
arg_string(args, "text", text, SAY_TEXT_MAX);
|
||||
if (text[0] == '\0') {
|
||||
sp_buf_puts(out, "error: 'text' is required");
|
||||
goto done;
|
||||
}
|
||||
if (sp_engine_busy(e)) {
|
||||
sp_buf_puts(out, "error: a turn is already running "
|
||||
"(splinter_steer or splinter_cancel)");
|
||||
goto done;
|
||||
}
|
||||
/* refused atomically when a daemon turn took the agent meanwhile */
|
||||
if (sp_engine_submit(e, text) != 0) {
|
||||
sp_buf_puts(out, BUSY_MSG);
|
||||
goto done;
|
||||
}
|
||||
deadline = time(NULL) + SAY_TIMEOUT_S;
|
||||
for (;;) {
|
||||
struct sp_engine_state st;
|
||||
|
||||
collect(e, answer, SAY_ANSWER_MAX, &known, &steps, &calls);
|
||||
if (!sp_engine_busy(e))
|
||||
break;
|
||||
/*
|
||||
* The model asked the operator something. The call returns
|
||||
* the question with the tool that answers it named. Waiting
|
||||
* here instead held the MCP call for the full ask wait
|
||||
* (sp_ask_wait_s(), 900 s by default; the client timed out at
|
||||
* 15 s).
|
||||
*/
|
||||
if (sp_engine_state(e, &st) == 0 && st.asking) {
|
||||
char qt[SP_ASK_MAX];
|
||||
|
||||
if (sp_engine_ask(e, qt, sizeof(qt), NULL, 0, NULL))
|
||||
sp_buf_printf(out, "the model asks: %s\n"
|
||||
"call splinter_answer {\"text\":\"...\"}\n",
|
||||
qt);
|
||||
else
|
||||
sp_buf_puts(out, "the model asks a question "
|
||||
"(it could not be read)\n"
|
||||
"call splinter_answer {\"text\":\"...\"}\n");
|
||||
goto done;
|
||||
}
|
||||
if (sp_mcp_stopping()) {
|
||||
/* the server is shutting down: do not hold it up */
|
||||
(void)sp_engine_cancel(e);
|
||||
(void)sp_engine_wait(e);
|
||||
sp_buf_puts(out, "error: the server is stopping; the "
|
||||
"turn was cancelled");
|
||||
goto done;
|
||||
}
|
||||
if (time(NULL) > deadline) {
|
||||
(void)sp_engine_cancel(e);
|
||||
sp_buf_puts(out, "error: the turn did not finish in "
|
||||
"time and was cancelled");
|
||||
goto done;
|
||||
}
|
||||
{
|
||||
struct timespec ts = { 0, 50 * 1000 * 1000L };
|
||||
|
||||
nanosleep(&ts, NULL);
|
||||
}
|
||||
}
|
||||
(void)sp_engine_wait(e);
|
||||
if (known)
|
||||
sp_buf_printf(out, "%s\n\n[%zu steps, %zu tool calls]\n",
|
||||
answer[0] != '\0' ? answer : "(empty answer)", steps, calls);
|
||||
else
|
||||
sp_buf_puts(out, "error: the turn ended without an answer\n");
|
||||
done:
|
||||
free(text);
|
||||
free(answer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_open(const char *args, struct sp_buf *out)
|
||||
{
|
||||
char id[128];
|
||||
struct sp_buf err;
|
||||
int rc;
|
||||
|
||||
arg_string(args, "session", id, sizeof(id));
|
||||
if (id[0] == '\0') {
|
||||
sp_buf_puts(out, "error: 'session' is required");
|
||||
return 0;
|
||||
}
|
||||
if (session_opts == NULL) {
|
||||
sp_buf_puts(out, "error: this server has no engine options; "
|
||||
"sessions cannot be switched");
|
||||
return 0;
|
||||
}
|
||||
if (sp_buf_init(&err) != 0)
|
||||
return -1;
|
||||
rc = sp_engine_switch(session_eng, session_opts, id, &err);
|
||||
if (rc != 0)
|
||||
sp_buf_printf(out, "error: %s\n",
|
||||
err.p != NULL ? err.p : "cannot open the session");
|
||||
else {
|
||||
struct sp_engine_state st;
|
||||
|
||||
if (sp_engine_state(*session_eng, &st) == 0)
|
||||
sp_buf_printf(out, "opened: %s\nmodel: %s\nagent: %s\n",
|
||||
st.session, st.model, st.agent);
|
||||
else
|
||||
sp_buf_puts(out, "opened\n");
|
||||
}
|
||||
sp_buf_free(&err);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_model(const char *args, struct sp_buf *out)
|
||||
{
|
||||
char sel[300], line[340];
|
||||
struct sp_buf reply;
|
||||
int kind;
|
||||
|
||||
arg_string(args, "model", sel, sizeof(sel));
|
||||
if (sel[0] == '\0') {
|
||||
sp_buf_puts(out, "error: 'model' is required "
|
||||
"(splinter_models lists the selectors)");
|
||||
return 0;
|
||||
}
|
||||
snprintf(line, sizeof(line), "/model %s", sel);
|
||||
if (sp_buf_init(&reply) != 0)
|
||||
return -1;
|
||||
/* held, not just checked: a daemon turn must not start under it */
|
||||
if (sp_engine_hold(*session_eng) != 0) {
|
||||
sp_buf_free(&reply);
|
||||
sp_buf_puts(out, BUSY_MSG);
|
||||
return 0;
|
||||
}
|
||||
kind = sp_engine_input(*session_eng, line, &reply);
|
||||
sp_engine_release(*session_eng);
|
||||
if (kind != SP_INPUT_HANDLED) {
|
||||
sp_buf_puts(out, "error: /model started a turn?");
|
||||
sp_buf_free(&reply);
|
||||
return 0;
|
||||
}
|
||||
sp_buf_printf(out, "%s", reply.p != NULL ? reply.p : "");
|
||||
sp_buf_free(&reply);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_agent(const char *args, struct sp_buf *out)
|
||||
{
|
||||
char name[64];
|
||||
int n, i, cur;
|
||||
|
||||
arg_string(args, "agent", name, sizeof(name));
|
||||
if (name[0] == '\0') {
|
||||
sp_buf_puts(out, "error: 'agent' is required");
|
||||
return 0;
|
||||
}
|
||||
if (sp_engine_hold(*session_eng) != 0) {
|
||||
sp_buf_puts(out, BUSY_MSG);
|
||||
return 0;
|
||||
}
|
||||
n = sp_engine_agents(*session_eng);
|
||||
cur = sp_engine_agent_cur(*session_eng);
|
||||
for (i = 0; i < n; i++)
|
||||
if (strcmp(sp_engine_agent_name(*session_eng, i), name) == 0) {
|
||||
int rc = sp_engine_agent_switch(*session_eng, i);
|
||||
|
||||
sp_engine_release(*session_eng);
|
||||
if (rc != 0) {
|
||||
sp_buf_puts(out, "error: cannot switch the agent");
|
||||
return 0;
|
||||
}
|
||||
sp_buf_printf(out, "agent: %s\n", name);
|
||||
return 0;
|
||||
}
|
||||
sp_engine_release(*session_eng);
|
||||
sp_buf_printf(out, "error: no agent '%s' (active is %s)\n", name,
|
||||
cur >= 0 ? sp_engine_agent_name(*session_eng, cur) : "?");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_steer(const char *args, struct sp_buf *out)
|
||||
{
|
||||
char text[4096];
|
||||
|
||||
arg_string(args, "text", text, sizeof(text));
|
||||
if (text[0] == '\0') {
|
||||
sp_buf_puts(out, "error: 'text' is required");
|
||||
return 0;
|
||||
}
|
||||
if (sp_engine_steer(*session_eng, text) != 0) {
|
||||
sp_buf_puts(out, "error: no turn is running");
|
||||
return 0;
|
||||
}
|
||||
sp_buf_puts(out, "queued: the loop picks it up at the next step\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_cancel(struct sp_buf *out)
|
||||
{
|
||||
if (!sp_engine_busy(*session_eng)) {
|
||||
sp_buf_puts(out, "no turn is running");
|
||||
return 0;
|
||||
}
|
||||
(void)sp_engine_cancel(*session_eng);
|
||||
sp_buf_puts(out, "cancel requested\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int
|
||||
tool_answer(const char *args, struct sp_buf *out)
|
||||
{
|
||||
char text[SP_ASK_MAX];
|
||||
|
||||
arg_string(args, "text", text, sizeof(text));
|
||||
if (text[0] == '\0') {
|
||||
sp_buf_puts(out, "error: 'text' is required");
|
||||
return 0;
|
||||
}
|
||||
if (sp_engine_answer(*session_eng, text) == 0) {
|
||||
sp_buf_puts(out, "error: no question is pending");
|
||||
return 0;
|
||||
}
|
||||
sp_buf_printf(out, "answered: %s\n", text);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_mcpsession_call(const char *name, const char *args, struct sp_buf *out)
|
||||
{
|
||||
if (session_eng == NULL || *session_eng == NULL) {
|
||||
sp_buf_puts(out, "error: this MCP server has no splinter engine");
|
||||
return 1;
|
||||
}
|
||||
if (strcmp(name, "splinter_sessions") == 0)
|
||||
return tool_sessions(out), 1;
|
||||
if (strcmp(name, "splinter_state") == 0)
|
||||
return tool_state(out), 1;
|
||||
if (strcmp(name, "splinter_models") == 0)
|
||||
return tool_models(out), 1;
|
||||
if (strcmp(name, "splinter_agents") == 0)
|
||||
return tool_agents(out), 1;
|
||||
if (strcmp(name, "splinter_history") == 0)
|
||||
return tool_history(args, out), 1;
|
||||
if (strcmp(name, "splinter_say") == 0)
|
||||
return tool_say(args, out), 1;
|
||||
if (strcmp(name, "splinter_open") == 0)
|
||||
return tool_open(args, out), 1;
|
||||
if (strcmp(name, "splinter_model") == 0)
|
||||
return tool_model(args, out), 1;
|
||||
if (strcmp(name, "splinter_agent") == 0)
|
||||
return tool_agent(args, out), 1;
|
||||
if (strcmp(name, "splinter_steer") == 0)
|
||||
return tool_steer(args, out), 1;
|
||||
if (strcmp(name, "splinter_cancel") == 0)
|
||||
return tool_cancel(out), 1;
|
||||
if (strcmp(name, "splinter_answer") == 0)
|
||||
return tool_answer(args, out), 1;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* splinter -- the MCP server's session tools.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*/
|
||||
#ifndef SPLINTER_MCPSESSION_H
|
||||
#define SPLINTER_MCPSESSION_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
struct sp_buf;
|
||||
struct sp_engine;
|
||||
struct sp_engine_opts;
|
||||
|
||||
/* The engine a connection works on; NULL means "file tools only". */
|
||||
void sp_mcpsession_bind(struct sp_engine **eng,
|
||||
const struct sp_engine_opts *opts);
|
||||
|
||||
/* 1 when the name is one of ours, and its authorization class. */
|
||||
int sp_mcpsession_has(const char *name);
|
||||
int sp_mcpsession_auth(const char *name);
|
||||
|
||||
/* tools/list entries, comma-prefixed unless *first is still 1 */
|
||||
void sp_mcpsession_tools(struct sp_buf *b, int *first);
|
||||
|
||||
/* 1 when handled (out filled), 0 when the name is not ours. */
|
||||
int sp_mcpsession_call(const char *name, const char *args,
|
||||
struct sp_buf *out);
|
||||
|
||||
#endif /* SPLINTER_MCPSESSION_H */
|
||||
File renamed without changes.
File renamed without changes.
@@ -32,9 +32,121 @@ put_field(struct sp_buf *b, const char *key, const char *value)
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* anthropic.c: a parsed value back to JSON text */
|
||||
int sp_json_emit(struct sp_buf *, const mcp_json *);
|
||||
|
||||
/*
|
||||
* The stored calls of an assistant turn, in OpenAI's shape. The conversation
|
||||
* keeps whatever the provider sent: after a /model switch from Anthropic that
|
||||
* is [{"id","name","input":{...}}], and OpenAI refuses it with a 400. Calls
|
||||
* already in OpenAI's shape go out verbatim; anything else is converted to
|
||||
* {"id","type":"function","function":{"name","arguments":"<json text>"}}.
|
||||
* Nothing is written when no usable call remains.
|
||||
*/
|
||||
static int
|
||||
put_calls(struct sp_buf *out, const char *calls)
|
||||
{
|
||||
mcp_json *v;
|
||||
struct sp_buf conv, args;
|
||||
size_t i, nout = 0;
|
||||
int native = 1, rc = -1;
|
||||
|
||||
v = mcp_parse(calls);
|
||||
if (v == NULL || v->t != MCP_ARR || v->count == 0) {
|
||||
mcp_json_free(v);
|
||||
return 0; /* unusable history is left out */
|
||||
}
|
||||
for (i = 0; i < v->count; i++) {
|
||||
const mcp_json *fn = mcp_arg(v->items[i], "function");
|
||||
|
||||
if (fn == NULL || fn->t != MCP_OBJ ||
|
||||
mcp_arg_string(fn, "name") == NULL ||
|
||||
mcp_arg_string(fn, "arguments") == NULL)
|
||||
native = 0;
|
||||
}
|
||||
if (native) {
|
||||
mcp_json_free(v);
|
||||
return sp_buf_printf(out, ",\"tool_calls\":%s", calls);
|
||||
}
|
||||
if (sp_buf_init(&conv) != 0) {
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
if (sp_buf_init(&args) != 0) {
|
||||
sp_buf_free(&conv);
|
||||
mcp_json_free(v);
|
||||
return -1;
|
||||
}
|
||||
for (i = 0; i < v->count; i++) {
|
||||
const mcp_json *c = v->items[i];
|
||||
const mcp_json *fn = mcp_arg(c, "function");
|
||||
const mcp_json *input = mcp_arg(c, "input");
|
||||
const char *id = mcp_arg_string(c, "id");
|
||||
const char *name = fn != NULL ? mcp_arg_string(fn, "name") :
|
||||
mcp_arg_string(c, "name");
|
||||
const char *a = fn != NULL ?
|
||||
mcp_arg_string(fn, "arguments") : NULL;
|
||||
char idbuf[32];
|
||||
|
||||
if (name == NULL || name[0] == '\0')
|
||||
continue;
|
||||
sp_buf_clear(&args);
|
||||
if (a != NULL) {
|
||||
if (sp_buf_puts(&args, a) != 0)
|
||||
goto out;
|
||||
} else if (input != NULL) {
|
||||
if (sp_json_emit(&args, input) != 0)
|
||||
goto out;
|
||||
} else if (sp_buf_puts(&args, "{}") != 0)
|
||||
goto out;
|
||||
if (id == NULL || id[0] == '\0') {
|
||||
snprintf(idbuf, sizeof(idbuf), "call-%zu", i);
|
||||
id = idbuf;
|
||||
}
|
||||
if (sp_buf_puts(&conv, nout > 0 ? "," : "") != 0 ||
|
||||
sp_buf_puts(&conv, "{") != 0 ||
|
||||
put_field(&conv, "id", id) != 0 ||
|
||||
sp_buf_puts(&conv, ",\"type\":\"function\","
|
||||
"\"function\":{") != 0 ||
|
||||
put_field(&conv, "name", name) != 0 ||
|
||||
sp_buf_puts(&conv, ",") != 0 ||
|
||||
put_field(&conv, "arguments", args.p != NULL ? args.p :
|
||||
"{}") != 0 ||
|
||||
sp_buf_puts(&conv, "}}") != 0)
|
||||
goto out;
|
||||
nout++;
|
||||
}
|
||||
rc = 0;
|
||||
if (nout > 0)
|
||||
rc = sp_buf_printf(out, ",\"tool_calls\":[%s]", conv.p);
|
||||
out:
|
||||
sp_buf_free(&args);
|
||||
sp_buf_free(&conv);
|
||||
mcp_json_free(v);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int
|
||||
gen_fields(struct sp_buf *out, const struct sp_gen_opts *g)
|
||||
{
|
||||
if (g == NULL)
|
||||
return 0;
|
||||
if (g->have_temperature &&
|
||||
sp_buf_printf(out, ",\"temperature\":%.17g", g->temperature) != 0)
|
||||
return -1;
|
||||
if (g->have_top_p &&
|
||||
sp_buf_printf(out, ",\"top_p\":%.17g", g->top_p) != 0)
|
||||
return -1;
|
||||
if (g->have_max_tokens &&
|
||||
sp_buf_printf(out, ",\"max_tokens\":%ld", g->max_tokens) != 0)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_openai_request(const struct sp_conv *conv, const char *model,
|
||||
const struct sp_registry *reg, int streaming, struct sp_buf *out)
|
||||
sp_openai_request_opts(const struct sp_conv *conv, const char *model,
|
||||
const struct sp_registry *reg, int streaming,
|
||||
const struct sp_gen_opts *gen, struct sp_buf *out)
|
||||
{
|
||||
size_t i, ntv;
|
||||
const struct sp_tool *tv;
|
||||
@@ -42,8 +154,13 @@ sp_openai_request(const struct sp_conv *conv, const char *model,
|
||||
sp_buf_clear(out);
|
||||
if (sp_buf_puts(out, "{\"model\":") != 0 || sp_buf_puts(out, "\"") != 0 ||
|
||||
sp_json_escape(out, model != NULL ? model : "") != 0 ||
|
||||
sp_buf_puts(out, streaming ? "\",\"stream\":true,\"messages\":["
|
||||
: "\",\"stream\":false,\"messages\":[") != 0)
|
||||
sp_buf_puts(out, streaming ? "\",\"stream\":true"
|
||||
: "\",\"stream\":false") != 0 ||
|
||||
gen_fields(out, gen) != 0 ||
|
||||
(streaming && gen != NULL && gen->include_usage &&
|
||||
sp_buf_puts(out, ",\"stream_options\":"
|
||||
"{\"include_usage\":true}") != 0) ||
|
||||
sp_buf_puts(out, ",\"messages\":[") != 0)
|
||||
return -1;
|
||||
|
||||
for (i = 0; i < conv->n; i++) {
|
||||
@@ -70,17 +187,26 @@ sp_openai_request(const struct sp_conv *conv, const char *model,
|
||||
return -1;
|
||||
}
|
||||
if (m->calls != NULL && *m->calls != '\0') {
|
||||
if (sp_buf_printf(out, ",\"tool_calls\":%s", m->calls) != 0)
|
||||
if (put_calls(out, m->calls) != 0)
|
||||
return -1;
|
||||
}
|
||||
if (sp_buf_puts(out, "}") != 0)
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* tools: name, description and an open parameter object */
|
||||
if (sp_buf_puts(out, "],\"tools\":[") != 0)
|
||||
/*
|
||||
* tools: name, description and an open parameter object. An empty
|
||||
* "tools":[] is refused by OpenAI itself (400), so no tools means no
|
||||
* field.
|
||||
*/
|
||||
if (sp_buf_puts(out, "]") != 0)
|
||||
return -1;
|
||||
ntv = 0;
|
||||
tv = reg != NULL ? sp_registry_tools(reg, &ntv) : NULL;
|
||||
if (tv == NULL || ntv == 0)
|
||||
return sp_buf_puts(out, "}");
|
||||
if (sp_buf_puts(out, ",\"tools\":[") != 0)
|
||||
return -1;
|
||||
tv = sp_registry_tools(reg, &ntv);
|
||||
for (i = 0; i < ntv; i++) {
|
||||
const struct sp_tool *t = &tv[i];
|
||||
|
||||
@@ -107,6 +233,13 @@ sp_openai_request(const struct sp_conv *conv, const char *model,
|
||||
return sp_buf_puts(out, "]}");
|
||||
}
|
||||
|
||||
int
|
||||
sp_openai_request(const struct sp_conv *conv, const char *model,
|
||||
const struct sp_registry *reg, int streaming, struct sp_buf *out)
|
||||
{
|
||||
return sp_openai_request_opts(conv, model, reg, streaming, NULL, out);
|
||||
}
|
||||
|
||||
/*
|
||||
* Extract the raw tool_calls array as text, so a later request can hand the
|
||||
* provider back exactly what it sent: re-encoding parsed calls would be a
|
||||
@@ -115,14 +248,33 @@ sp_openai_request(const struct sp_conv *conv, const char *model,
|
||||
static char *
|
||||
raw_calls(const char *json, const char *key)
|
||||
{
|
||||
const char *p = strstr(json, key);
|
||||
const char *start;
|
||||
const char *p = json;
|
||||
const char *start = NULL;
|
||||
int depth = 0, in_str = 0, esc = 0;
|
||||
size_t len;
|
||||
size_t len, klen = strlen(key);
|
||||
|
||||
if (p == NULL)
|
||||
return NULL;
|
||||
start = strchr(p + strlen(key), '[');
|
||||
/*
|
||||
* The key, not the first occurrence of its text: "finish_reason":
|
||||
* "tool_calls" carries the same quoted word as a value. A key is
|
||||
* followed by optional blanks and a colon, then the array.
|
||||
*/
|
||||
while ((p = strstr(p, key)) != NULL) {
|
||||
const char *q = p + klen;
|
||||
|
||||
while (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')
|
||||
q++;
|
||||
if (*q == ':') {
|
||||
q++;
|
||||
while (*q == ' ' || *q == '\t' || *q == '\n' ||
|
||||
*q == '\r')
|
||||
q++;
|
||||
if (*q == '[') {
|
||||
start = q;
|
||||
break;
|
||||
}
|
||||
}
|
||||
p += klen;
|
||||
}
|
||||
if (start == NULL)
|
||||
return NULL;
|
||||
for (p = start; *p != '\0'; p++) {
|
||||
@@ -203,6 +355,13 @@ sp_openai_reply(const char *json, struct sp_reply *out, struct sp_buf *err)
|
||||
return -1;
|
||||
}
|
||||
|
||||
{
|
||||
const char *fr = mcp_json_string(mcp_arg(choice,
|
||||
"finish_reason"));
|
||||
|
||||
if (fr != NULL)
|
||||
snprintf(out->finish, sizeof(out->finish), "%s", fr);
|
||||
}
|
||||
content = mcp_arg(message, "content");
|
||||
out->content = strdup(jstr(content) != NULL ? jstr(content) : "");
|
||||
if (out->content == NULL) {
|
||||
@@ -214,18 +373,40 @@ sp_openai_reply(const char *json, struct sp_reply *out, struct sp_buf *err)
|
||||
const mcp_json *usage = mcp_arg(v, "usage");
|
||||
|
||||
if (usage != NULL) {
|
||||
const mcp_json *details;
|
||||
long pin = (long)mcp_arg_int(usage, "prompt_tokens", -1);
|
||||
long pout = (long)mcp_arg_int(usage, "completion_tokens",
|
||||
-1);
|
||||
long cached = -1;
|
||||
|
||||
if (pin < 0)
|
||||
pin = (long)mcp_arg_int(usage, "input_tokens", -1);
|
||||
if (pout < 0)
|
||||
pout = (long)mcp_arg_int(usage, "output_tokens", -1);
|
||||
details = mcp_arg(usage, "prompt_tokens_details");
|
||||
if (details != NULL)
|
||||
cached = (long)mcp_arg_int(details,
|
||||
"cached_tokens", -1);
|
||||
if (cached < 0)
|
||||
cached = (long)mcp_arg_int(usage,
|
||||
"prompt_cache_hit_tokens", -1);
|
||||
if (cached < 0)
|
||||
cached = (long)mcp_arg_int(usage,
|
||||
"cache_read_input_tokens", -1);
|
||||
if (pin >= 0)
|
||||
out->tokens_in = pin;
|
||||
if (pout >= 0)
|
||||
out->tokens_out = pout;
|
||||
if (cached >= 0)
|
||||
out->tokens_cached = cached;
|
||||
{
|
||||
double c = mcp_arg_num(usage, "cost", -1);
|
||||
|
||||
if (c < 0)
|
||||
c = mcp_arg_num(usage, "cost_usd", -1);
|
||||
if (c >= 0)
|
||||
out->cost = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* splinter -- the OpenAI-compatible endpoint for another harness.
|
||||
*
|
||||
* Copyright (c) 2026 Konrad Lother
|
||||
* SPDX-License-Identifier: BSD-3-Clause
|
||||
*
|
||||
* The server lives in openai_server.c; this is what main starts it with.
|
||||
*/
|
||||
#ifndef SPLINTER_OPENAI_SERVER_H
|
||||
#define SPLINTER_OPENAI_SERVER_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
struct sp_registry;
|
||||
struct sp_config;
|
||||
struct sp_buf;
|
||||
|
||||
struct sp_gateway_opts {
|
||||
const char *ip;
|
||||
int port;
|
||||
const char *token; /* SPLINTER_GATEWAY_TOKEN, may be NULL */
|
||||
size_t max_steps; /* gateway tool rounds, 0: 16 */
|
||||
struct sp_registry *reg; /* splinter's own tools */
|
||||
struct sp_config *conf;
|
||||
const char *endpoint; /* upstream */
|
||||
const char *model;
|
||||
const char *key_env;
|
||||
const char *kind; /* "anthropic", or NULL */
|
||||
};
|
||||
|
||||
int sp_openai_serve(const struct sp_gateway_opts *, struct sp_buf *err);
|
||||
|
||||
#endif /* SPLINTER_OPENAI_SERVER_H */
|
||||
File renamed without changes.
File renamed without changes.
@@ -24,9 +24,11 @@
|
||||
|
||||
#include "splinter.h"
|
||||
#include "splinter_plugin.h"
|
||||
#include "config.h"
|
||||
|
||||
#define MAX_WIDGETS 32
|
||||
#define MAX_COMPACTORS 8
|
||||
#define MAX_STATUS 16 /* segments are cheap; sharing the cap hid a plugin */
|
||||
#define MAX_TRANSPORTS 8
|
||||
#define MAX_COMMANDS 16
|
||||
#define MAX_PLUGINS 32
|
||||
@@ -58,9 +60,11 @@ struct sp_host {
|
||||
size_t msg_head, msg_n;
|
||||
const struct sp_compactor *compact[MAX_COMPACTORS];
|
||||
size_t ncompact;
|
||||
/* set by a plugin that is preparing a plan; lasts one call */
|
||||
int compact_hold;
|
||||
const struct sp_gate *gate[MAX_COMPACTORS];
|
||||
size_t ngate;
|
||||
const struct sp_status *status[MAX_COMPACTORS];
|
||||
const struct sp_status *status[MAX_STATUS];
|
||||
size_t nstatus;
|
||||
struct sp_meter meter;
|
||||
const struct sp_task_ops *taskops;
|
||||
@@ -81,6 +85,10 @@ struct sp_host {
|
||||
size_t compactions;
|
||||
size_t failed;
|
||||
unsigned turns;
|
||||
char model[256]; /* what the run is on */
|
||||
char served_by[128]; /* who answered the last request */
|
||||
struct sp_judge_next judge; /* X-Junction-Judge-Next-* */
|
||||
char cache_mode[8]; /* X-Junction-Cache */
|
||||
/* loaded plugins, in load order, so shutdown() runs in reverse */
|
||||
const struct sp_plugin *loaded[MAX_PLUGINS];
|
||||
size_t nloaded;
|
||||
@@ -108,9 +116,27 @@ widget_thread(void *arg)
|
||||
|
||||
if (w->interval_ms == 0)
|
||||
break;
|
||||
ts.tv_sec = w->interval_ms / 1000;
|
||||
ts.tv_nsec = (long)(w->interval_ms % 1000) * 1000000L;
|
||||
nanosleep(&ts, NULL);
|
||||
/*
|
||||
* Sleep in short steps and look at the stop flag between them:
|
||||
* one long sleep made the exit wait for a whole interval, since
|
||||
* sp_host_free() joins this thread.
|
||||
*/
|
||||
{
|
||||
unsigned long left = w->interval_ms;
|
||||
int stop = 0;
|
||||
|
||||
while (left > 0 && !stop) {
|
||||
unsigned long step = left > 100 ? 100 : left;
|
||||
|
||||
ts.tv_sec = 0;
|
||||
ts.tv_nsec = (long)step * 1000000L;
|
||||
nanosleep(&ts, NULL);
|
||||
left -= step;
|
||||
pthread_mutex_lock(&w->lock);
|
||||
stop = w->stop;
|
||||
pthread_mutex_unlock(&w->lock);
|
||||
}
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
@@ -204,7 +230,7 @@ sp_host_add_status(struct sp_host *h, const struct sp_status *s)
|
||||
{
|
||||
if (h == NULL || s == NULL || s->render == NULL || s->name == NULL)
|
||||
return -1;
|
||||
if (h->nstatus == MAX_COMPACTORS)
|
||||
if (h->nstatus == MAX_STATUS)
|
||||
return -1;
|
||||
h->status[h->nstatus++] = s;
|
||||
return 0;
|
||||
@@ -352,11 +378,6 @@ sp_host_gate(struct sp_host *h, const char *tool, int auth, const char *args,
|
||||
return -1;
|
||||
}
|
||||
|
||||
/*
|
||||
* Run every compactor in registration order. A compactor that fails does not
|
||||
* stop the others and does not abort the turn: the failure is counted and the
|
||||
* loop carries on with whatever the conversation looks like now.
|
||||
*/
|
||||
int
|
||||
sp_host_add_transport(struct sp_host *h, const char *name,
|
||||
struct sp_transport tr)
|
||||
@@ -436,6 +457,11 @@ sp_host_command_help(struct sp_host *h, struct sp_buf *out)
|
||||
return h->ncommands;
|
||||
}
|
||||
|
||||
/*
|
||||
* Run every compactor in registration order. A compactor that fails does not
|
||||
* stop the others and does not abort the turn: the failure is counted and the
|
||||
* loop carries on with whatever the conversation looks like now.
|
||||
*/
|
||||
int
|
||||
sp_host_compact(struct sp_host *h, struct sp_conv *conv, size_t budget)
|
||||
{
|
||||
@@ -444,6 +470,27 @@ sp_host_compact(struct sp_host *h, struct sp_conv *conv, size_t budget)
|
||||
|
||||
if (h == NULL || conv == NULL)
|
||||
return 0;
|
||||
/*
|
||||
* The plugins get their turn first, and the core is the backstop.
|
||||
*
|
||||
* The old rule was "any plugin compactor means the core stays out", and
|
||||
* it was wrong twice over. compact_threshold and compact_target are core
|
||||
* settings, so a configuration whose plugins happened to register one
|
||||
* made them dead - the operator set a limit and the conversation grew
|
||||
* past the window until the provider cut it (254k of 131k, 2026-11-21).
|
||||
* And most plugin "compactors" do not compact at all: focus and reminder
|
||||
* insert one message and return 0 or 1. A plugin that inserts a goal
|
||||
* reminder must not be the reason an oversized request goes out whole.
|
||||
*
|
||||
* So the core always gets a look, and decides for itself: core_compact()
|
||||
* returns 0 without touching anything when the conversation already fits
|
||||
* the budget. That is the check that separates "focus inserted a
|
||||
* reminder into a small conversation" (616 bytes under a 1-byte budget
|
||||
* in a test, every real turn under its real budget) from "lcm cut the
|
||||
* transcript in half". Only the second kind of turn gets a digest, and
|
||||
* then it comes after the plugin's own work, so that work is what
|
||||
* survives where it did something.
|
||||
*/
|
||||
for (i = 0; i < h->ncompact; i++) {
|
||||
rc = h->compact[i]->compact(h, conv, budget,
|
||||
(unsigned)h->turns);
|
||||
@@ -454,9 +501,33 @@ sp_host_compact(struct sp_host *h, struct sp_conv *conv, size_t budget)
|
||||
h->failed++;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* A plugin that answered "not yet, my plan is still being prepared" asked
|
||||
* for one round of room. Its next call applies the plan. Cutting the
|
||||
* conversation in between would invalidate that plan, which is the bug
|
||||
* this flag exists to prevent.
|
||||
*/
|
||||
if (h->compact_hold) {
|
||||
h->compact_hold = 0;
|
||||
return changed;
|
||||
}
|
||||
rc = sp_core_compactor()->compact(h, conv, budget, (unsigned)h->turns);
|
||||
if (rc > 0) {
|
||||
changed = 1;
|
||||
h->compactions++;
|
||||
} else if (rc < 0) {
|
||||
h->failed++;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_compactor_hold(struct sp_host *h)
|
||||
{
|
||||
if (h != NULL)
|
||||
h->compact_hold = 1;
|
||||
}
|
||||
|
||||
size_t
|
||||
sp_host_compaction_stats(struct sp_host *h, size_t *compactions,
|
||||
size_t *failed, unsigned *turns)
|
||||
@@ -470,6 +541,80 @@ sp_host_compaction_stats(struct sp_host *h, size_t *compactions,
|
||||
return h != NULL ? h->compactions : 0;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_host_model(struct sp_host *h)
|
||||
{
|
||||
static __thread char copy[256];
|
||||
|
||||
if (h == NULL)
|
||||
return "";
|
||||
pthread_mutex_lock(&h->lock);
|
||||
snprintf(copy, sizeof(copy), "%s", h->model);
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
return copy;
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_set_model(struct sp_host *h, const char *model)
|
||||
{
|
||||
if (h == NULL)
|
||||
return;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
snprintf(h->model, sizeof(h->model), "%s", model != NULL ? model : "");
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_host_served_by(struct sp_host *h)
|
||||
{
|
||||
static __thread char copy[128];
|
||||
|
||||
if (h == NULL)
|
||||
return "";
|
||||
pthread_mutex_lock(&h->lock);
|
||||
snprintf(copy, sizeof(copy), "%s", h->served_by);
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
return copy;
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_set_served_by(struct sp_host *h, const char *endpoint)
|
||||
{
|
||||
if (h == NULL)
|
||||
return;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
snprintf(h->served_by, sizeof(h->served_by), "%s",
|
||||
endpoint != NULL ? endpoint : "");
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_set_judge_next(struct sp_host *h, const struct sp_judge_next *j)
|
||||
{
|
||||
if (h == NULL)
|
||||
return;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
if (j != NULL)
|
||||
h->judge = *j;
|
||||
else
|
||||
memset(&h->judge, 0, sizeof(h->judge));
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
}
|
||||
|
||||
int
|
||||
sp_host_judge_next(struct sp_host *h, struct sp_judge_next *out)
|
||||
{
|
||||
int valid = 0;
|
||||
|
||||
if (h == NULL || out == NULL)
|
||||
return 0;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
*out = h->judge;
|
||||
valid = h->judge.valid;
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
return valid;
|
||||
}
|
||||
|
||||
struct sp_registry *
|
||||
sp_host_registry(struct sp_host *h)
|
||||
{
|
||||
@@ -489,6 +634,33 @@ sp_host_set_config(struct sp_host *h, const void *conf)
|
||||
h->conf = conf;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_host_plugin_config(struct sp_host *h, const char *plugin, const char *key)
|
||||
{
|
||||
return sp_config_plugin_value(h != NULL ? h->conf : NULL, plugin, key);
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_host_plugin_config_at(struct sp_host *h, const char *plugin, size_t i,
|
||||
const char **key)
|
||||
{
|
||||
const struct sp_config *c = h != NULL ? h->conf : NULL;
|
||||
size_t k, seen = 0;
|
||||
|
||||
if (c == NULL || plugin == NULL)
|
||||
return NULL;
|
||||
for (k = 0; k < c->nplugin_conf; k++) {
|
||||
if (strcmp(c->plugin_conf[k].plugin, plugin) != 0)
|
||||
continue;
|
||||
if (seen++ == i) {
|
||||
if (key != NULL)
|
||||
*key = c->plugin_conf[k].key;
|
||||
return c->plugin_conf[k].val;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_turn(struct sp_host *h)
|
||||
{
|
||||
@@ -589,12 +761,6 @@ sp_host_widget_snapshot(struct sp_host *h, char *buf, size_t len)
|
||||
return used;
|
||||
}
|
||||
|
||||
struct sp_plugin_handle {
|
||||
void *dl;
|
||||
const struct sp_plugin *p;
|
||||
char path[512];
|
||||
};
|
||||
|
||||
/* how far each table was filled before a plugin's init() ran */
|
||||
struct host_mark {
|
||||
size_t tools, widgets, compact, gate, status;
|
||||
@@ -653,7 +819,7 @@ rollback(struct sp_host *h, const struct host_mark *m)
|
||||
int
|
||||
sp_plugin_load(struct sp_host *h, const char *path, struct sp_buf *err)
|
||||
{
|
||||
struct sp_plugin_handle *hd;
|
||||
void *hd;
|
||||
const struct sp_plugin *(*describe)(void);
|
||||
|
||||
if (h == NULL || path == NULL)
|
||||
@@ -741,6 +907,12 @@ sp_host_session_dir(struct sp_host *h)
|
||||
return (h != NULL) ? h->session_dir : NULL;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_host_session_id(struct sp_host *h)
|
||||
{
|
||||
return (h != NULL && h->sess != NULL) ? h->sess->id : NULL;
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_set_provider(struct sp_host *h, const struct sp_provider_ops *ops)
|
||||
{
|
||||
@@ -797,4 +969,28 @@ size_t
|
||||
sp_host_widget_count(struct sp_host *h)
|
||||
{
|
||||
return h != NULL ? h->nwidgets : 0;
|
||||
}
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_host_cache_mode(struct sp_host *h)
|
||||
{
|
||||
static __thread char copy[8];
|
||||
|
||||
if (h == NULL)
|
||||
return "";
|
||||
pthread_mutex_lock(&h->lock);
|
||||
snprintf(copy, sizeof(copy), "%s", h->cache_mode);
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
return copy;
|
||||
}
|
||||
|
||||
void
|
||||
sp_host_set_cache_mode(struct sp_host *h, const char *mode)
|
||||
{
|
||||
if (h == NULL)
|
||||
return;
|
||||
pthread_mutex_lock(&h->lock);
|
||||
snprintf(h->cache_mode, sizeof(h->cache_mode), "%s",
|
||||
mode != NULL ? mode : "");
|
||||
pthread_mutex_unlock(&h->lock);
|
||||
}
|
||||
@@ -35,6 +35,13 @@
|
||||
"plugins, skills. Reinventing a thing that is already there costs the user time " \
|
||||
"and trust.\n" \
|
||||
"\n" \
|
||||
"Use the knowledge tools actively, not only when asked: the mcp_* tools for " \
|
||||
"tasks (task_*), memory (memory_*), skills (skill_*) and knowledge bases " \
|
||||
"(wiki_*, page_*). A multi-step job belongs in the task list before you start, " \
|
||||
"something you learned belongs back in a skill or the wiki, and a decision or " \
|
||||
"preference belongs in memory. A finding that lives only in this conversation " \
|
||||
"is lost.\n" \
|
||||
"\n" \
|
||||
"Work through errors by changing the approach, not by repeating the same attempt. " \
|
||||
"Keep a short record of what you built and where it lives.\n" \
|
||||
"\n" \
|
||||
@@ -44,6 +51,22 @@
|
||||
"Answer briefly: the result first, where the files are, then the next step. Use " \
|
||||
"the language the user writes in.\n"
|
||||
|
||||
/* Append at most what fits; snprintf returns the untruncated length. */
|
||||
static size_t
|
||||
put(char *out, size_t cap, size_t used, const char *a, const char *b)
|
||||
{
|
||||
int n;
|
||||
|
||||
if (used + 1 >= cap)
|
||||
return used;
|
||||
n = snprintf(out + used, cap - used, "%s%s", a, b != NULL ? b : "");
|
||||
if (n < 0)
|
||||
return used;
|
||||
if ((size_t)n >= cap - used)
|
||||
return cap - 1;
|
||||
return used + (size_t)n;
|
||||
}
|
||||
|
||||
static void
|
||||
expand_into(const char *tmpl, char *out, size_t cap, const char *model)
|
||||
{
|
||||
@@ -52,25 +75,28 @@ expand_into(const char *tmpl, char *out, size_t cap, const char *model)
|
||||
struct utsname un;
|
||||
const char *home = getenv("HOME");
|
||||
char cwd[512];
|
||||
char os[300];
|
||||
|
||||
if (cap == 0)
|
||||
return;
|
||||
(void)uname(&un);
|
||||
snprintf(os, sizeof(os), "%s %s", un.sysname, un.release);
|
||||
if (getcwd(cwd, sizeof(cwd)) == NULL)
|
||||
snprintf(cwd, sizeof(cwd), "?");
|
||||
while (*src != '\0' && used + 1 < cap) {
|
||||
if (strncmp(src, "{{os}}", 6) == 0) {
|
||||
used += (size_t)snprintf(out + used, cap - used, "%s %s",
|
||||
un.sysname, un.release);
|
||||
used = put(out, cap, used, os, NULL);
|
||||
src += 6;
|
||||
} else if (strncmp(src, "{{home}}", 8) == 0) {
|
||||
used += (size_t)snprintf(out + used, cap - used, "%s",
|
||||
home != NULL ? home : "?");
|
||||
used = put(out, cap, used, home != NULL ? home : "?",
|
||||
NULL);
|
||||
src += 8;
|
||||
} else if (strncmp(src, "{{cwd}}", 7) == 0) {
|
||||
used += (size_t)snprintf(out + used, cap - used, "%s", cwd);
|
||||
used = put(out, cap, used, cwd, NULL);
|
||||
src += 7;
|
||||
} else if (strncmp(src, "{{model}}", 9) == 0) {
|
||||
used += (size_t)snprintf(out + used, cap - used, "%s",
|
||||
model != NULL ? model : "?");
|
||||
used = put(out, cap, used, model != NULL ? model : "?",
|
||||
NULL);
|
||||
src += 9;
|
||||
} else
|
||||
out[used++] = *src++;
|
||||
File renamed without changes.
@@ -17,6 +17,7 @@
|
||||
#include <ctype.h>
|
||||
#include <errno.h>
|
||||
#include <poll.h>
|
||||
#include <stdarg.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -78,6 +79,7 @@ sp_provider_at(const struct sp_config *cfg, size_t idx, struct sp_provider *out)
|
||||
cfg->endpoint);
|
||||
snprintf(out->model, sizeof(out->model), "%s", cfg->model);
|
||||
snprintf(out->key_env, sizeof(out->key_env), "%s", cfg->key_env);
|
||||
out->ctx = cfg->ctx;
|
||||
out->main = 1;
|
||||
return 0;
|
||||
}
|
||||
@@ -94,8 +96,11 @@ delegates:
|
||||
snprintf(out->kind, sizeof(out->kind), "%s", d->kind);
|
||||
snprintf(out->endpoint, sizeof(out->endpoint), "%s", d->endpoint);
|
||||
snprintf(out->model, sizeof(out->model), "%s", d->model);
|
||||
snprintf(out->models, sizeof(out->models), "%s", d->models);
|
||||
snprintf(out->key_env, sizeof(out->key_env), "%s", d->key_env);
|
||||
snprintf(out->key, sizeof(out->key), "%s", d->key);
|
||||
snprintf(out->about, sizeof(out->about), "%s", d->about);
|
||||
out->ctx = d->ctx;
|
||||
return 0;
|
||||
}
|
||||
for (i = 0; i < cfg->nexits; i++) {
|
||||
@@ -137,6 +142,58 @@ sp_provider_find(const struct sp_config *cfg, const char *id, size_t *idx)
|
||||
return 0;
|
||||
}
|
||||
|
||||
const char *
|
||||
sp_provider_label(const char *id)
|
||||
{
|
||||
if (id == NULL || *id == '\0' || strcmp(id, "main") == 0)
|
||||
return "local";
|
||||
return id;
|
||||
}
|
||||
|
||||
size_t
|
||||
sp_provider_choices(const struct sp_config *cfg, const char *cur_model,
|
||||
struct sp_model_choice *v, size_t max)
|
||||
{
|
||||
struct sp_provider p;
|
||||
size_t n, i, k = 0;
|
||||
|
||||
if (cfg == NULL || v == NULL || max == 0)
|
||||
return 0;
|
||||
n = sp_provider_count(cfg);
|
||||
for (i = 0; i < n && k < max; i++) {
|
||||
if (sp_provider_at(cfg, i, &p) != 0)
|
||||
continue;
|
||||
const char *name = sp_provider_label(p.id);
|
||||
|
||||
if (p.model[0] != '\0') {
|
||||
snprintf(v[k].sel, sizeof(v[k].sel), "%s/%s", name,
|
||||
p.model);
|
||||
snprintf(v[k].label, sizeof(v[k].label), "%s/%s", name,
|
||||
p.model);
|
||||
} else {
|
||||
snprintf(v[k].sel, sizeof(v[k].sel), "%s", name);
|
||||
snprintf(v[k].label, sizeof(v[k].label), "%s", name);
|
||||
}
|
||||
v[k].current = cur_model != NULL && *cur_model != '\0' &&
|
||||
strcmp(p.model, cur_model) == 0;
|
||||
k++;
|
||||
}
|
||||
for (i = 0; i < cfg->npools && k < max; i++) {
|
||||
const struct sp_pool *pl = &cfg->pool[i];
|
||||
size_t j, off;
|
||||
|
||||
snprintf(v[k].sel, sizeof(v[k].sel), "%s", pl->id);
|
||||
off = (size_t)snprintf(v[k].label, sizeof(v[k].label),
|
||||
"%s pool (%s):", pl->id, pl->strategy);
|
||||
for (j = 0; j < pl->nmembers && off < sizeof(v[k].label); j++)
|
||||
off += (size_t)snprintf(v[k].label + off,
|
||||
sizeof(v[k].label) - off, " %s", pl->member[j]);
|
||||
v[k].current = 0;
|
||||
k++;
|
||||
}
|
||||
return k;
|
||||
}
|
||||
|
||||
int
|
||||
sp_provider_select(const struct sp_config *cfg, const char *sel,
|
||||
struct sp_provider *out, char *model, size_t modelcap)
|
||||
@@ -165,13 +222,17 @@ sp_provider_identify(struct sp_transport *tr, const char *endpoint,
|
||||
{
|
||||
/*
|
||||
* The fingerprint outlives this call, and a ring holds several
|
||||
* transports at once, so it cannot be one static buffer: each identity
|
||||
* gets its own slot (a hash, never the secret).
|
||||
* transports at once, so it cannot be one static buffer. Each distinct
|
||||
* key gets one slot for the life of the process (a hash, never the
|
||||
* secret): the same key reuses its slot, a new one grows the table.
|
||||
* A fixed ring overwrote slots that live transports still pointed at.
|
||||
* The table only grows with distinct keys, which the config bounds.
|
||||
*/
|
||||
static char pool[16][32];
|
||||
static size_t slot;
|
||||
static char **pool;
|
||||
static size_t npool, cappool;
|
||||
const char *prov = "openai-compat";
|
||||
char *kfp;
|
||||
char kfp[32];
|
||||
size_t i;
|
||||
|
||||
if (tr == NULL)
|
||||
return;
|
||||
@@ -185,10 +246,28 @@ sp_provider_identify(struct sp_transport *tr, const char *endpoint,
|
||||
prov = "anthropic";
|
||||
tr->provider = prov;
|
||||
tr->key_id = NULL;
|
||||
if (secret != NULL && *secret != '\0') {
|
||||
kfp = pool[slot++ % 16];
|
||||
if (sp_key_fingerprint(secret, kfp, 32) != NULL)
|
||||
tr->key_id = kfp;
|
||||
if (secret != NULL && *secret != '\0' &&
|
||||
sp_key_fingerprint(secret, kfp, sizeof(kfp)) != NULL) {
|
||||
for (i = 0; i < npool; i++)
|
||||
if (strcmp(pool[i], kfp) == 0)
|
||||
break;
|
||||
if (i == npool) {
|
||||
/* the strings never move; only the index does */
|
||||
if (npool == cappool) {
|
||||
size_t nc = cappool > 0 ? cappool * 2 : 16;
|
||||
char **np = realloc(pool, nc * sizeof(*pool));
|
||||
|
||||
if (np != NULL) {
|
||||
pool = np;
|
||||
cappool = nc;
|
||||
}
|
||||
}
|
||||
if (npool < cappool &&
|
||||
(pool[npool] = strdup(kfp)) != NULL)
|
||||
npool++;
|
||||
}
|
||||
if (i < npool)
|
||||
tr->key_id = pool[i];
|
||||
}
|
||||
if (tr->key_id == NULL && strcmp(prov, "ollama") == 0)
|
||||
tr->key_id = "local";
|
||||
@@ -197,6 +276,20 @@ sp_provider_identify(struct sp_transport *tr, const char *endpoint,
|
||||
int
|
||||
sp_provider_apply(struct sp_agent *ag, const char *kind, const char *endpoint,
|
||||
const char *model, const char *key_env, struct sp_buf *err)
|
||||
{
|
||||
return sp_provider_apply_key(ag, kind, endpoint, model, key_env, NULL,
|
||||
err);
|
||||
}
|
||||
|
||||
/*
|
||||
* A literal key (an auto-detected Ollama delegate carries its token in
|
||||
* d->key, with no key_env) wins over key_env: reading only the environment
|
||||
* sent such a provider without a key, and it answered 401.
|
||||
*/
|
||||
int
|
||||
sp_provider_apply_key(struct sp_agent *ag, const char *kind,
|
||||
const char *endpoint, const char *model, const char *key_env,
|
||||
const char *literal, struct sp_buf *err)
|
||||
{
|
||||
const char *key = NULL;
|
||||
|
||||
@@ -208,14 +301,19 @@ sp_provider_apply(struct sp_agent *ag, const char *kind, const char *endpoint,
|
||||
sp_buf_puts(err, "no endpoint or model");
|
||||
return -1;
|
||||
}
|
||||
if (key_env != NULL && *key_env != '\0')
|
||||
if (literal != NULL && *literal != '\0')
|
||||
key = literal;
|
||||
else if (key_env != NULL && *key_env != '\0')
|
||||
key = getenv(key_env);
|
||||
if (kind != NULL && strcmp(kind, "anthropic") == 0)
|
||||
if (kind != NULL && strcmp(kind, "anthropic") == 0) {
|
||||
sp_transport_dispose(&ag->tr);
|
||||
ag->tr = sp_anthropic_transport(endpoint, model, key, ag->reg,
|
||||
PROVIDER_TIMEOUT_S);
|
||||
else
|
||||
} else {
|
||||
sp_transport_dispose(&ag->tr);
|
||||
ag->tr = sp_openai_transport(endpoint, model, key, ag->reg,
|
||||
PROVIDER_TIMEOUT_S);
|
||||
}
|
||||
sp_provider_identify(&ag->tr, endpoint, key);
|
||||
return 0;
|
||||
}
|
||||
@@ -231,8 +329,8 @@ sp_provider_use(struct sp_agent *ag, const struct sp_config *cfg, size_t idx,
|
||||
sp_buf_puts(err, "no such provider");
|
||||
return -1;
|
||||
}
|
||||
if (sp_provider_apply(ag, p.kind, p.endpoint, p.model, p.key_env,
|
||||
err) != 0)
|
||||
if (sp_provider_apply_key(ag, p.kind, p.endpoint, p.model, p.key_env,
|
||||
p.key, err) != 0)
|
||||
return -1;
|
||||
sp_usage_set_active(p.main ? "main" : p.id);
|
||||
return 0;
|
||||
@@ -245,6 +343,11 @@ sp_provider_use(struct sp_agent *ag, const struct sp_config *cfg, size_t idx,
|
||||
* One GET, no body. curl writes to a pipe; the URL and the header go to curl
|
||||
* on stdin/argv respectively, so a token never shows up in ps.
|
||||
*/
|
||||
/* A probe may not hang on a host that does not answer: 3s to connect, 8s
|
||||
* for the whole answer. */
|
||||
#define PROVIDER_CONNECT_TIMEOUT_S 3
|
||||
#define PROVIDER_GET_TIMEOUT_S 8
|
||||
|
||||
static int
|
||||
http_get(const char *url, const char *const *headers, struct sp_buf *out,
|
||||
struct sp_buf *err)
|
||||
@@ -253,10 +356,14 @@ http_get(const char *url, const char *const *headers, struct sp_buf *out,
|
||||
pid_t child;
|
||||
const char *args[8];
|
||||
int n = 0;
|
||||
char tbuf[16];
|
||||
char tbuf[16], cbuf[16];
|
||||
|
||||
snprintf(tbuf, sizeof(tbuf), "%d", 8);
|
||||
args[n++] = "-sS";
|
||||
snprintf(tbuf, sizeof(tbuf), "%d", PROVIDER_GET_TIMEOUT_S);
|
||||
snprintf(cbuf, sizeof(cbuf), "%d", PROVIDER_CONNECT_TIMEOUT_S);
|
||||
/* -s, not -sS: a probe can fail while curses owns the terminal */
|
||||
args[n++] = "-s";
|
||||
args[n++] = "--connect-timeout";
|
||||
args[n++] = cbuf;
|
||||
args[n++] = "-m";
|
||||
args[n++] = tbuf;
|
||||
args[n] = NULL;
|
||||
@@ -341,6 +448,30 @@ provider_headers(const struct sp_provider *p, char *hdr, size_t cap,
|
||||
return n;
|
||||
}
|
||||
|
||||
/* 1 when the provider's optional models= list is empty or names this id */
|
||||
static int
|
||||
provider_lists(const struct sp_provider *p, const char *id)
|
||||
{
|
||||
char list[512], *tok, *save = NULL;
|
||||
|
||||
if (p->models[0] == '\0')
|
||||
return 1;
|
||||
snprintf(list, sizeof(list), "%s", p->models);
|
||||
for (tok = strtok_r(list, ",", &save); tok != NULL;
|
||||
tok = strtok_r(NULL, ",", &save)) {
|
||||
char *end;
|
||||
|
||||
while (*tok == ' ' || *tok == '\t')
|
||||
tok++;
|
||||
end = tok + strlen(tok);
|
||||
while (end > tok && (end[-1] == ' ' || end[-1] == '\t'))
|
||||
*--end = '\0';
|
||||
if (*tok != '\0' && strcmp(tok, id) == 0)
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_provider_served(const struct sp_provider *p, struct sp_buf *ids,
|
||||
struct sp_buf *err)
|
||||
@@ -377,6 +508,8 @@ sp_provider_served(const struct sp_provider *p, struct sp_buf *ids,
|
||||
|
||||
if (id == NULL)
|
||||
continue;
|
||||
if (!provider_lists(p, id))
|
||||
continue;
|
||||
if (ids->len > 0 && sp_buf_puts(ids, "\n") != 0)
|
||||
goto oom;
|
||||
if (sp_buf_puts(ids, id) != 0)
|
||||
@@ -420,6 +553,30 @@ window_pct(const mcp_json *v, const char *name, char *out, size_t cap)
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Append to a fixed buffer. snprintf returns what it wanted to write, so a
|
||||
* plain n += snprintf(...) walks past cap on a long answer and the next call
|
||||
* writes out of bounds; this keeps n inside the buffer.
|
||||
*/
|
||||
static size_t
|
||||
catf(char *out, size_t cap, size_t n, const char *fmt, ...)
|
||||
{
|
||||
va_list ap;
|
||||
int w;
|
||||
|
||||
if (cap == 0 || n >= cap - 1)
|
||||
return n;
|
||||
va_start(ap, fmt);
|
||||
w = vsnprintf(out + n, cap - n, fmt, ap);
|
||||
va_end(ap);
|
||||
if (w < 0)
|
||||
return n;
|
||||
if ((size_t)w >= cap - n)
|
||||
return cap - 1;
|
||||
return n + (size_t)w;
|
||||
}
|
||||
|
||||
int
|
||||
sp_provider_remote_usage(const struct sp_provider *p, char *out, size_t cap)
|
||||
{
|
||||
@@ -487,18 +644,18 @@ sp_provider_remote_usage(const struct sp_provider *p, char *out, size_t cap)
|
||||
double buy = mcp_arg_num(pur, "balance_usd", -1.0);
|
||||
|
||||
if (ses != NULL)
|
||||
n += (size_t)snprintf(out + n, cap - n, "session %.0f%% left",
|
||||
n = catf(out, cap, n, "session %.0f%% left",
|
||||
mcp_arg_num(ses, "remaining_percent", 0));
|
||||
if (wk != NULL)
|
||||
n += (size_t)snprintf(out + n, cap - n, "%sweekly %.0f%% left",
|
||||
n = catf(out, cap, n, "%sweekly %.0f%% left",
|
||||
n ? ", " : "", mcp_arg_num(wk, "remaining_percent", 0));
|
||||
if (bal >= 0)
|
||||
n += (size_t)snprintf(out + n, cap - n, "%s$%.2f%s left",
|
||||
n = catf(out, cap, n, "%s$%.2f%s left",
|
||||
n ? ", " : "", bal, all >= 0 ? "" : "");
|
||||
if (bal >= 0 && all >= 0)
|
||||
n += (size_t)snprintf(out + n, cap - n, " of $%.0f", all);
|
||||
n = catf(out, cap, n, " of $%.0f", all);
|
||||
if (buy > 0)
|
||||
n += (size_t)snprintf(out + n, cap - n, "%s$%.2f bought",
|
||||
n = catf(out, cap, n, "%s$%.2f bought",
|
||||
n ? ", " : "", buy);
|
||||
} else {
|
||||
static const char *const names[] = { "rolling", "weekly",
|
||||
@@ -511,7 +668,7 @@ sp_provider_remote_usage(const struct sp_provider *p, char *out, size_t cap)
|
||||
if (window_pct(wrap != NULL ? wrap : v, names[k], line,
|
||||
sizeof(line)) &&
|
||||
n < cap)
|
||||
n += (size_t)snprintf(out + n, cap - n, "%s%s",
|
||||
n = catf(out, cap, n, "%s%s",
|
||||
n ? ", " : "", line);
|
||||
}
|
||||
mcp_json_free(v);
|
||||
@@ -543,14 +700,32 @@ sp_provider_test(const struct sp_provider *p, struct sp_buf *answer,
|
||||
sp_conv_free(&conv);
|
||||
return -1;
|
||||
}
|
||||
if (p->key_env[0] != '\0')
|
||||
if (p->key[0] != '\0')
|
||||
key = p->key;
|
||||
else if (p->key_env[0] != '\0')
|
||||
key = getenv(p->key_env);
|
||||
if (p->kind[0] != '\0' && strcmp(p->kind, "anthropic") == 0)
|
||||
tr = sp_anthropic_transport(p->endpoint, p->model, key, &empty,
|
||||
30);
|
||||
else
|
||||
tr = sp_openai_transport(p->endpoint, p->model, key, &empty, 30);
|
||||
if (tr.send == NULL) {
|
||||
if (err != NULL)
|
||||
sp_buf_puts(err, "cannot build the transport");
|
||||
sp_transport_dispose(&tr);
|
||||
sp_conv_free(&conv);
|
||||
return -1;
|
||||
}
|
||||
rc = tr.send(tr.ctx, &conv, &reply, err);
|
||||
sp_transport_dispose(&tr);
|
||||
/* an error page with status 429 is not "the provider answered" */
|
||||
if (rc == 0 && reply.status != 0 &&
|
||||
(reply.status < 200 || reply.status > 299)) {
|
||||
if (err != NULL)
|
||||
sp_buf_printf(err, "HTTP %ld: %.200s", reply.status,
|
||||
reply.content != NULL ? reply.content : "");
|
||||
rc = -1;
|
||||
}
|
||||
if (rc == 0) {
|
||||
size_t n = reply.content != NULL ? strlen(reply.content) : 0;
|
||||
|
||||
@@ -604,14 +779,25 @@ sp_provider_save_choice(const struct sp_config *cfg,
|
||||
(void)fchmod(fileno(f), 0600);
|
||||
fprintf(f, "# written by /model -- delete this file to go back to the "
|
||||
"configuration\n");
|
||||
/* without the kind, the next start would speak OpenAI at the Messages API */
|
||||
if (p->kind[0] != '\0' && strcmp(p->kind, "openai") != 0)
|
||||
fprintf(f, "kind = %s\n", p->kind);
|
||||
fprintf(f, "endpoint = %s\n", p->endpoint);
|
||||
fprintf(f, "model = %s\n", p->model);
|
||||
/* the key variable too: a keyless provider must not inherit one */
|
||||
fprintf(f, "api_key_env = %s\n",
|
||||
p->key_env[0] != '\0' ? p->key_env : "SPLINTER_API_KEY");
|
||||
/*
|
||||
* A model of the main endpoint has no provider block to name, so it is
|
||||
* still written out in full. Every other choice is a default: writing
|
||||
* endpoint/model there made the persisted choice shadow a core default
|
||||
* (the loader took the endpoint as if --endpoint had been given) and,
|
||||
* for a provider/model selection, put a slash-name into 'model'.
|
||||
*/
|
||||
if (strcmp(p->id, "main") == 0) {
|
||||
/* without the kind the next start would speak OpenAI at Messages */
|
||||
if (p->kind[0] != '\0' && strcmp(p->kind, "openai") != 0)
|
||||
fprintf(f, "kind = %s\n", p->kind);
|
||||
fprintf(f, "endpoint = %s\n", p->endpoint);
|
||||
fprintf(f, "model = %s\n", p->model);
|
||||
/* a keyless provider must not inherit one */
|
||||
fprintf(f, "api_key_env = %s\n",
|
||||
p->key_env[0] != '\0' ? p->key_env : "SPLINTER_API_KEY");
|
||||
} else {
|
||||
fprintf(f, "default = %s/%s\n", p->id, p->model);
|
||||
}
|
||||
if (fclose(f) != 0 || rename(tmp, path) != 0) {
|
||||
if (err != NULL)
|
||||
sp_buf_printf(err, "cannot replace %s: %s", path,
|
||||
@@ -801,13 +987,25 @@ save_dropin(const char *dir, const char *id, const char *line,
|
||||
rc = -1;
|
||||
} else {
|
||||
(void)fchmod(fileno(f), 0600);
|
||||
if (write_all(f, &out) != 0 || fclose(f) != 0) {
|
||||
if (err != NULL)
|
||||
sp_buf_printf(err, "cannot write %s",
|
||||
tmp);
|
||||
(void)unlink(tmp);
|
||||
rc = -1;
|
||||
} else if (rename(tmp, path) != 0) {
|
||||
/*
|
||||
* Both calls, always: `write_all(...) || fclose(f)`
|
||||
* skips the close as soon as the write fails, and a
|
||||
* full disk then leaks a descriptor per attempt.
|
||||
*/
|
||||
{
|
||||
int bad = write_all(f, &out) != 0;
|
||||
|
||||
if (fclose(f) != 0)
|
||||
bad = 1;
|
||||
if (bad) {
|
||||
if (err != NULL)
|
||||
sp_buf_printf(err, "cannot write %s",
|
||||
tmp);
|
||||
(void)unlink(tmp);
|
||||
rc = -1;
|
||||
}
|
||||
}
|
||||
if (rc == 0 && rename(tmp, path) != 0) {
|
||||
if (err != NULL)
|
||||
sp_buf_printf(err, "cannot replace %s: %s",
|
||||
path, strerror(errno));
|
||||
@@ -1021,6 +1219,26 @@ sp_pool_pick(const struct sp_config *cfg, const struct sp_pool *p,
|
||||
return best;
|
||||
}
|
||||
|
||||
/* one static stand-in for the core endpoint, filled per selection */
|
||||
static struct sp_delegate main_d;
|
||||
|
||||
static int
|
||||
main_choice(const struct sp_config *cfg, const char *model,
|
||||
struct sp_choice *out)
|
||||
{
|
||||
memset(&main_d, 0, sizeof(main_d));
|
||||
snprintf(main_d.id, sizeof(main_d.id), "main");
|
||||
snprintf(main_d.kind, sizeof(main_d.kind), "%s", cfg->kind);
|
||||
snprintf(main_d.endpoint, sizeof(main_d.endpoint), "%s",
|
||||
cfg->endpoint);
|
||||
snprintf(main_d.key_env, sizeof(main_d.key_env), "%s", cfg->key_env);
|
||||
snprintf(main_d.model, sizeof(main_d.model), "%s",
|
||||
model != NULL && *model != '\0' ? model : cfg->model);
|
||||
out->d = &main_d;
|
||||
snprintf(out->model, sizeof(out->model), "%s", main_d.model);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int
|
||||
sp_provider_choose(const struct sp_config *cfg, const char *sel,
|
||||
struct sp_choice *out)
|
||||
@@ -1049,6 +1267,15 @@ sp_provider_choose(const struct sp_config *cfg, const char *sel,
|
||||
snprintf(out->model, sizeof(out->model), "%s", d->model);
|
||||
return 0;
|
||||
}
|
||||
/*
|
||||
* The core endpoint has no provider block. It is called "local" in a
|
||||
* selector; "main" stays an alias for old configurations and files.
|
||||
* The static delegate is filled per call and only used by apply().
|
||||
*/
|
||||
if ((strcmp(sel, "local") == 0 || strcmp(sel, "main") == 0) &&
|
||||
cfg->endpoint[0] != '\0') {
|
||||
return main_choice(cfg, NULL, out);
|
||||
}
|
||||
/* provider/model: the provider's id is the part before the first '/' */
|
||||
slash = strchr(sel, '/');
|
||||
if (slash != NULL && slash != sel) {
|
||||
@@ -1058,6 +1285,11 @@ sp_provider_choose(const struct sp_config *cfg, const char *sel,
|
||||
if (n < sizeof(id)) {
|
||||
memcpy(id, sel, n);
|
||||
id[n] = '\0';
|
||||
if ((strcmp(id, "local") == 0 ||
|
||||
strcmp(id, "main") == 0) &&
|
||||
cfg->endpoint[0] != '\0' &&
|
||||
delegate_by_id(cfg, id) == NULL)
|
||||
return main_choice(cfg, slash + 1, out);
|
||||
d = delegate_by_id(cfg, id);
|
||||
if (d == NULL && sp_pool_find(cfg, id) != NULL) {
|
||||
p = sp_pool_find(cfg, id);
|
||||
@@ -1102,8 +1334,8 @@ sp_provider_failover(struct sp_agent *ag, const struct sp_config *cfg)
|
||||
return 0;
|
||||
if (sp_buf_init(&err) != 0)
|
||||
return 0;
|
||||
rc = sp_provider_apply(ag, d->kind, d->endpoint, d->model,
|
||||
d->key_env, &err);
|
||||
rc = sp_provider_apply_key(ag, d->kind, d->endpoint, d->model,
|
||||
d->key_env, d->key, &err);
|
||||
sp_buf_free(&err);
|
||||
if (rc != 0)
|
||||
return 0;
|
||||
@@ -10,6 +10,7 @@ struct sp_pool;
|
||||
struct sp_agent;
|
||||
struct sp_transport;
|
||||
struct sp_buf;
|
||||
struct sp_model_choice;
|
||||
|
||||
/*
|
||||
* One reachable model: the endpoint, the model name and the variable the key
|
||||
@@ -21,8 +22,11 @@ struct sp_provider {
|
||||
char kind[16]; /* "openai" (default), "anthropic" or "cli" */
|
||||
char endpoint[512];
|
||||
char model[256];
|
||||
char models[512]; /* optional comma list, filters what the endpoint serves */
|
||||
char key_env[64];
|
||||
char key[256]; /* a literal key (d->key), wins over key_env */
|
||||
char about[128];
|
||||
unsigned long ctx; /* context window, 0 = unknown */
|
||||
int main; /* the endpoint/model the run started with */
|
||||
};
|
||||
|
||||
@@ -31,6 +35,15 @@ size_t sp_provider_count(const struct sp_config *);
|
||||
int sp_provider_at(const struct sp_config *, size_t, struct sp_provider *);
|
||||
int sp_provider_find(const struct sp_config *, const char *id, size_t *idx);
|
||||
|
||||
/*
|
||||
* The list /model shows: every provider (selector = its id) followed by every
|
||||
* pool (selector = the pool id), with the model as the label and a marker for
|
||||
* the one the run is on. No network: it is the configuration, not the answer
|
||||
* to "what does the endpoint really serve".
|
||||
*/
|
||||
size_t sp_provider_choices(const struct sp_config *, const char *cur_model,
|
||||
struct sp_model_choice *, size_t max);
|
||||
|
||||
/*
|
||||
* A selector (-m, /model) as one provider to switch to: a pool, a provider,
|
||||
* "provider/model" or a model name one provider has. Fills 'out' with that
|
||||
@@ -58,6 +71,10 @@ int sp_provider_use(struct sp_agent *, const struct sp_config *, size_t,
|
||||
int sp_provider_apply(struct sp_agent *, const char *kind,
|
||||
const char *endpoint, const char *model, const char *key_env,
|
||||
struct sp_buf *err);
|
||||
/* the same with a literal key, used instead of key_env when not empty */
|
||||
int sp_provider_apply_key(struct sp_agent *, const char *kind,
|
||||
const char *endpoint, const char *model, const char *key_env,
|
||||
const char *key, struct sp_buf *err);
|
||||
|
||||
/* The drop-in directory next to the config file (…/splinter.conf.d). */
|
||||
int sp_provider_dir(char *, size_t);
|
||||
@@ -141,6 +158,12 @@ struct sp_choice {
|
||||
int sp_provider_choose(const struct sp_config *, const char *sel,
|
||||
struct sp_choice *out);
|
||||
|
||||
/*
|
||||
* The name people see: the core endpoint is "local", never "main"; every
|
||||
* configured provider keeps its id. Selectors are always "<name>/<model>".
|
||||
*/
|
||||
const char *sp_provider_label(const char *id);
|
||||
|
||||
/*
|
||||
* The provider the conversation is on is at its limit: move to another member
|
||||
* of its pool that has room. 1 when the agent now talks to another provider.
|
||||
Loaded 100 of 233 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user