config blocks, pools, -m/--model-list, waiting out usage limits

Config: { } blocks (core, telegram, provider, pool, exit) translated to the flat
reader with source line numbers; flat form still loads; delegate/plugin limits
raised. Pools: failover/balance, used by delegation (tag-safe), by -m and for
the conversation when its provider hits a limit. -m SEL picks a pool, provider,
provider/model or model name; --model-list lists them with served models.
Usage limits: the agent finds the reset and waits (UI: Ctrl-C stops, /resume
goes on; on_limit=fail turns it off).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
lotherkandClaude Sonnet 5.5 committed 2026-11-11 22:12:26 +00:00
1 parent fac5cffc6f
commit 0b7a91e3b7
19 files changed
+2158 -84

No files matched your search

+16 -3
View File
@@ -23,7 +23,7 @@ CURSES_A = $(CURSES_DIR)/libcurses/libcurses.a \
LIB = libsplinter.so
LIBOBJ = src/buf.o src/tool.o src/session.o src/conv.o src/transport.o \
src/json.o src/sse.o src/openai.o src/transport_openai.o src/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/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
BIN = splinter
BINOBJ = src/main.o src/ui.o
PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \
@@ -37,7 +37,7 @@ PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \
plugins/tmux/tmux.so
TESTS = tests/test_buf tests/test_tool tests/test_session tests/test_conv \
tests/test_transport tests/test_agent tests/test_openai \
tests/test_theme tests/test_plugin tests/test_memory tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_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_jobs
tests/test_theme tests/test_plugin tests/test_memory tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_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_confblock tests/test_jobs
RPATH = -Wl,-rpath,'$$ORIGIN'
PLUGIN_RPATH = -Wl,-rpath,'$$ORIGIN/../..'
@@ -103,6 +103,12 @@ plugins/cps/cps.so: plugins/cps/cps.c $(LIB)
.c.o:
$(CC) $(CFLAGS) -c -o $@ $<
# 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
$(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.
@@ -199,6 +205,9 @@ tests/test_provstate: tests/test_provstate.c $(LIB)
tests/test_planner: tests/test_planner.c $(LIB) $(PLUGIN)
$(CC) $(CFLAGS) -o $@ tests/test_planner.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_confblock: tests/test_confblock.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_confblock.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_usage: tests/test_usage.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_usage.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_tmux: tests/test_tmux.c $(LIB) $(PLUGIN)
@@ -239,6 +248,8 @@ check: $(LIB) $(BIN) $(PLUGIN) $(TESTS)
echo "== tests/test_a2a_ui.sh"; sh tests/test_a2a_ui.sh; \
echo "== tests/test_a2a_server.sh"; sh tests/test_a2a_server.sh; \
echo "== tests/test_a2a_context.sh"; sh tests/test_a2a_context.sh; \
echo "== tests/test_limit_wait.sh"; sh tests/test_limit_wait.sh; \
echo "== tests/test_pools.sh"; sh tests/test_pools.sh; \
echo "== tests/test_a2a_input.sh"; sh tests/test_a2a_input.sh; \
echo "== tests/test_ui.sh"; sh tests/test_ui.sh; \
echo "all tests passed"
@@ -247,11 +258,13 @@ check: $(LIB) $(BIN) $(PLUGIN) $(TESTS)
# ($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
mkdir -p $(DESTDIR)$(PREFIX)/bin $(DESTDIR)$(PREFIX)/lib
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/
@echo "installed $(DESTDIR)$(PREFIX)/bin/splinter"
clean:
+87 -3
View File
@@ -14,9 +14,88 @@ instead.
for one run, `--no-config` ignores the file entirely, and `--init-config`
writes a commented example.
Format: one `key = value` per line, `#` starts a comment, blank lines are
ignored. Not JSON, on purpose — this file gets edited by hand, and a missing
comma must not be the reason the harness will not start.
## Format
Blocks with `{ }`, settings as `name = value`, lists in `[ ]`, `#` starts a
comment, `"${NAME}"` inserts an environment variable. Not JSON, on purpose —
this file gets edited by hand, and a missing comma must not be the reason the
harness will not start. An error names the line you wrote.
```
core {
default = main # a provider or a pool, below
theme = Delphinium
autonomous = true
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]
}
telegram { allow = [123456789] }
provider ocgo {
about = "fast and cheap, good at planning"
tags = [cloud, code, fast]
endpoint = https://api.example.org/v1/chat/completions
model = some-model
key_env = EXAMPLE_API_KEY
prio = 10
limit = 100/5h
}
provider claude-a {
kind = cli
cmd = "claude -p"
tags = [cli, big]
limit = 40/5h
env { CLAUDE_CODE_OAUTH_TOKEN = "${CLAUDE_A_TOKEN}" }
}
pool claude { members = [claude-a, claude-b] strategy = balance }
```
Blocks: `core` (everything that is not a provider; bare `name = value` lines at
the top level also go there), `telegram`, `provider NAME`, `pool NAME`,
`exit NAME`. A provider is anything the run or a delegation can talk to: the
fields are the ones of `delegate =` below, plus `delegate = false` to keep it
out of delegation. Several files work: every `splinter.conf.d/*.conf` is read
too, each in either format.
The older flat form (`key = value` per line, `delegate = id | text | k=v`)
still loads, and is what the tables below describe key by key.
## Choosing a model: `-m` and `--model-list`
```
splinter --model-list # everything -m takes; asks each endpoint what it serves
splinter -m claude # a pool (the member with the most left)
splinter -m ocgo # a provider
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.
## Pools
A pool is a name for providers that stand in for each other:
- `failover` takes the first member that has room, in the order listed;
- `balance` takes the member with the most left of its allowance.
For the conversation: when the provider it is on hits a limit, splinter moves
to the next member with room and repeats the request. For delegation: a task
that fits a member goes to whichever member the pool picks, as long as that
member has every tag of the one that matched (a private task never leaves
the `private` provider). A cli member's pool mates become its fallback.
## When everything is at its limit
splinter finds out when the limit lifts (from `Retry-After`, from the reset a
provider names in its message, or from its own count), says so, waits and
repeats the request: `on_limit = wait`, the default. `max_wait` bounds it
(default 12h). In the chat the screen stays alive; Ctrl-C stops the wait and
`/resume` goes on. `on_limit = fail` reports the limit instead.
## Not in the file: the goal
@@ -52,6 +131,11 @@ lies about what it does.
| `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) |
| `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 |
| `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 |
+22
View File
@@ -246,6 +246,17 @@ struct sp_agent_config {
size_t msgs_before, size_t msgs_after);
void *on_compact_ctx;
/*
* Called when a request hit a usage limit that lifts at 'until' (epoch).
* The callback waits (it may take hours) and returns 1 to ask again, or
* 0 to give up and let the turn fail with the error. NULL: fail at once.
*/
int (*limit_wait)(void *ctx, long until, const char *why);
void *limit_ctx;
/* tried before waiting: move to another provider; 1 if it did */
int (*limit_switch)(void *ctx);
void *switch_ctx;
/* incremental output, if the transport and the caller both support it */
sp_stream_cb stream;
void *stream_ctx;
@@ -261,6 +272,9 @@ struct sp_agent_stats {
size_t bytes_sent;
};
/* waits for a usage limit without a screen; ctx: const long *max_wait_secs */
int sp_limit_wait_default(void *ctx, long until, const char *why);
struct sp_host; /* plugin host, see splinter_plugin.h */
struct sp_agent {
@@ -314,6 +328,14 @@ const char *sp_memory_user(void);
int sp_slash_script(const char *dir, const char *name, const char *args,
struct sp_buf *out, struct sp_buf *err);
int sp_delegate_prio(const struct sp_config *, const char *id);
/*
* Where the child of a cli delegate finds the cli transport: the plugin path
* for a binary at 'self'. $SPLINTER_CLI_PLUGIN wins outright; otherwise the
* build tree next to the binary, the installed layout, then the build
* directory compiled in. When none of them exists the first candidate is
* returned, so the child's own error names the place that was expected.
*/
void sp_delegate_cli_plugin(const char *self, char *out, size_t len);
/*
* Limits. sp_limit_parse: is this error text a rate/usage limit (429, "weekly
+120 -6
View File
@@ -296,13 +296,84 @@ run_one(struct sp_agent *a, struct sp_conv *conv,
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;
int rc = -1, limit_tries = 0;
if (sp_buf_init(&obs) != 0) {
sp_buf_puts(err, "agent: out of memory");
@@ -328,7 +399,17 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision,
a->has_pending = 0;
a->pending_from = 0;
}
for (step = 0; step < a->cfg->max_steps; step++) {
/*
* 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;
@@ -386,6 +467,13 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision,
"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) {
@@ -414,6 +502,13 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision,
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;
}
@@ -432,6 +527,13 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision,
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;
}
@@ -467,6 +569,22 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision,
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;
@@ -504,10 +622,6 @@ agent_loop(struct sp_agent *a, struct sp_conv *conv, int resume, int decision,
sp_reply_free(&reply);
}
sp_buf_printf(err, "agent: step limit (%zu) reached without an answer",
a->cfg->max_steps);
goto out;
oom:
sp_buf_puts(err, "agent: out of memory");
out:
+701
View File
@@ -0,0 +1,701 @@
/* splinter -- config block syntax; see confblock.h. */
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "confblock.h"
#define MAX_ITEMS 64
#define MAX_ENTRIES 64
struct val {
char *items[MAX_ITEMS];
size_t n;
int list;
};
struct ent {
char key[48];
struct val v;
unsigned line;
};
struct cb {
const char *p;
unsigned line;
const char *path;
struct sp_buf *err;
struct sp_buf *out;
unsigned *map;
size_t nmap, capmap;
int failed;
};
static void
fail(struct cb *c, unsigned line, const char *fmt, ...)
{
va_list ap;
char msg[400];
if (c->failed)
return;
c->failed = 1;
va_start(ap, fmt);
vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
sp_buf_printf(c->err, "config: %s:%u: %s", c->path, line, msg);
}
static void
val_free(struct val *v)
{
size_t i;
for (i = 0; i < v->n; i++)
free(v->items[i]);
v->n = 0;
}
static void
ents_free(struct ent *e, size_t n)
{
size_t i;
for (i = 0; i < n; i++)
val_free(&e[i].v);
}
/* blanks and comments; newlines too when 'nl' */
static void
skip(struct cb *c, int nl)
{
for (;;) {
if (*c->p == ' ' || *c->p == '\t' || *c->p == '\r')
c->p++;
else if (*c->p == '\n' && nl) {
c->line++;
c->p++;
} else if (*c->p == '#') {
while (*c->p != '\0' && *c->p != '\n')
c->p++;
} else
break;
}
}
/* ${NAME} becomes the variable's value, empty when it is not set */
static char *
expand(const char *s)
{
struct sp_buf b;
char *r;
if (sp_buf_init(&b) != 0)
return NULL;
while (*s != '\0') {
if (s[0] == '$' && s[1] == '{') {
const char *e = strchr(s + 2, '}');
char name[96];
size_t n;
const char *v;
if (e != NULL && (size_t)(e - s - 2) < sizeof(name)) {
n = (size_t)(e - s - 2);
memcpy(name, s + 2, n);
name[n] = '\0';
v = getenv(name);
if (v != NULL)
sp_buf_puts(&b, v);
s = e + 1;
continue;
}
}
sp_buf_add(&b, s, 1);
s++;
}
r = b.p != NULL ? strdup(b.p) : strdup("");
sp_buf_free(&b);
return r;
}
/* one scalar: "quoted with \" \\ \n" or a bare word */
static char *
scalar(struct cb *c)
{
char tmp[2048];
size_t n = 0;
char *r;
if (*c->p == '"') {
unsigned start = c->line;
c->p++;
while (*c->p != '"') {
if (*c->p == '\0' || *c->p == '\n') {
fail(c, start, "string without a closing quote");
return NULL;
}
if (*c->p == '\\' && c->p[1] != '\0') {
c->p++;
tmp[n] = *c->p == 'n' ? '\n' : *c->p;
} else
tmp[n] = *c->p;
if (n + 1 < sizeof(tmp))
n++;
c->p++;
}
c->p++;
} else {
while (*c->p != '\0' && !isspace((unsigned char)*c->p) &&
*c->p != '#' && *c->p != ',' && *c->p != ']' &&
*c->p != '}' && *c->p != '[' && *c->p != '{') {
tmp[n] = *c->p++;
if (n + 1 < sizeof(tmp))
n++;
}
if (n == 0) {
fail(c, c->line, "a value is missing");
return NULL;
}
}
tmp[n] = '\0';
r = expand(tmp);
if (r == NULL)
fail(c, c->line, "out of memory");
return r;
}
static int
value(struct cb *c, struct val *v)
{
memset(v, 0, sizeof(*v));
skip(c, 0);
if (*c->p == '[') {
unsigned start = c->line;
v->list = 1;
c->p++;
for (;;) {
skip(c, 1);
if (*c->p == ',') {
c->p++;
continue;
}
if (*c->p == ']') {
c->p++;
break;
}
if (*c->p == '\0') {
fail(c, start, "list without a closing ]");
return -1;
}
if (v->n == MAX_ITEMS) {
fail(c, c->line, "more than %d items in a list",
MAX_ITEMS);
return -1;
}
v->items[v->n] = scalar(c);
if (v->items[v->n] == NULL)
return -1;
v->n++;
}
return 0;
}
v->items[0] = scalar(c);
if (v->items[0] == NULL)
return -1;
v->n = 1;
return 0;
}
static const char *
one(struct cb *c, const struct ent *e)
{
if (e->v.n != 1 || e->v.list) {
fail(c, e->line, "%s wants one value, not a list", e->key);
return NULL;
}
return e->v.items[0];
}
/* the items as "a,b,c" */
static void
joined(const struct val *v, char *buf, size_t cap)
{
size_t i, n = 0;
buf[0] = '\0';
for (i = 0; i < v->n && n + 1 < cap; i++)
n += (size_t)snprintf(buf + n, cap - n, "%s%s", i > 0 ? "," : "",
v->items[i]);
if (n >= cap)
buf[cap - 1] = '\0';
}
static int
boolean(const char *s)
{
return !strcmp(s, "true") || !strcmp(s, "yes") || !strcmp(s, "on") ||
!strcmp(s, "1");
}
static void
emit(struct cb *c, unsigned line, const char *fmt, ...)
{
va_list ap;
char l[4096];
va_start(ap, fmt);
vsnprintf(l, sizeof(l), fmt, ap);
va_end(ap);
sp_buf_puts(c->out, l);
sp_buf_puts(c->out, "\n");
if (c->nmap == c->capmap) {
size_t nc = c->capmap != 0 ? c->capmap * 2 : 64;
unsigned *nm = realloc(c->map, nc * sizeof(*nm));
if (nm == NULL) {
fail(c, line, "out of memory");
return;
}
c->map = nm;
c->capmap = nc;
}
c->map[c->nmap++] = line;
}
/* a field value goes into a '|' separated line: it must not hold one */
static int
clean(struct cb *c, const struct ent *e, const char *s)
{
if (strchr(s, '|') != NULL || strchr(s, '\n') != NULL) {
fail(c, e->line, "%s must not contain '|' or a newline", e->key);
return 0;
}
return 1;
}
static int
in_list(const char *const *list, const char *k)
{
for (; *list != NULL; list++)
if (!strcmp(*list, k))
return 1;
return 0;
}
static void
do_core(struct cb *c, struct ent *e, size_t n)
{
size_t i, j;
for (i = 0; i < n && !c->failed; i++) {
const char *k = e[i].key, *s;
char list[2048];
if (!strcmp(k, "plugins") || !strcmp(k, "skills")) {
for (j = 0; j < e[i].v.n; j++)
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));
emit(c, e[i].line, "%s = %s", k, list);
continue;
}
s = one(c, &e[i]);
if (s == NULL)
return;
if (!strcmp(k, "autonomous") || !strcmp(k, "env_delegates"))
emit(c, e[i].line, "%s = %d", k, boolean(s));
else
emit(c, e[i].line, "%s = %s", k, s);
}
}
static void
do_provider(struct cb *c, const char *name, unsigned line, struct ent *e,
size_t n)
{
static const char *const plain[] = { "kind", "cmd", "host", "endpoint",
"model", "key_env", "prio", "max_parallel", "limit", "tokens", NULL };
struct sp_buf l;
const char *about = "";
size_t i, j;
int skip_it = 0;
if (sp_buf_init(&l) != 0) {
fail(c, line, "out of memory");
return;
}
for (i = 0; i < n; i++) {
if (!strcmp(e[i].key, "about") || !strcmp(e[i].key, "description")) {
about = one(c, &e[i]);
if (about == NULL || !clean(c, &e[i], about))
goto done;
} else if (!strcmp(e[i].key, "delegate")) {
const char *s = one(c, &e[i]);
if (s == NULL)
goto done;
skip_it = !boolean(s);
}
}
sp_buf_printf(&l, "delegate = %s", name);
if (about[0] != '\0')
sp_buf_printf(&l, " | %s", about);
for (i = 0; i < n; i++) {
const char *k = e[i].key, *s;
char list[1024];
if (!strcmp(k, "about") || !strcmp(k, "description") ||
!strcmp(k, "delegate"))
continue;
if (!strcmp(k, "tags")) {
joined(&e[i].v, list, sizeof(list));
if (!clean(c, &e[i], list))
goto done;
if (list[0] != '\0')
sp_buf_printf(&l, " | tags=%s", list);
} else if (!strcmp(k, "env")) {
for (j = 0; j < e[i].v.n; j++) {
const char *kv = e[i].v.items[j], *eq = strchr(kv, '=');
/* NAME= with nothing after it: the variable was not set */
if (eq == NULL || eq[1] == '\0')
continue;
if (!clean(c, &e[i], kv))
goto done;
sp_buf_printf(&l, " | env=%s", kv);
}
} else if (in_list(plain, k)) {
s = one(c, &e[i]);
if (s == NULL || !clean(c, &e[i], s))
goto done;
sp_buf_printf(&l, " | %s=%s", k, s);
} else {
fail(c, e[i].line, "unknown provider field '%s'", k);
goto done;
}
}
if (!skip_it && l.p != NULL)
emit(c, line, "%s", l.p);
done:
sp_buf_free(&l);
}
static void
do_pool(struct cb *c, const char *name, unsigned line, struct ent *e, size_t n)
{
char members[512] = "";
const char *strategy = "failover";
size_t i;
for (i = 0; i < n; i++) {
if (!strcmp(e[i].key, "members"))
joined(&e[i].v, members, sizeof(members));
else if (!strcmp(e[i].key, "strategy")) {
strategy = one(c, &e[i]);
if (strategy == NULL)
return;
} else {
fail(c, e[i].line, "unknown pool field '%s'", e[i].key);
return;
}
}
if (members[0] == '\0') {
fail(c, line, "pool %s has no members", name);
return;
}
emit(c, line, "pool = %s | strategy=%s | members=%s", name, strategy,
members);
}
static void
do_exit(struct cb *c, const char *name, unsigned line, struct ent *e, size_t n)
{
struct sp_buf l;
size_t i;
if (sp_buf_init(&l) != 0)
return;
sp_buf_printf(&l, "exit = %s", name);
for (i = 0; i < n; i++) {
const char *s = one(c, &e[i]);
if (s == NULL || !clean(c, &e[i], s))
goto done;
if (!strcmp(e[i].key, "label") || !strcmp(e[i].key, "about"))
sp_buf_printf(&l, " | %s", s);
else if (!strcmp(e[i].key, "endpoint") ||
!strcmp(e[i].key, "model") || !strcmp(e[i].key, "key_env"))
sp_buf_printf(&l, " | %s=%s", e[i].key, s);
else {
fail(c, e[i].line, "unknown exit field '%s'", e[i].key);
goto done;
}
}
emit(c, line, "%s", l.p);
done:
sp_buf_free(&l);
}
/*
* The body of a block, after its '{': key = value entries, and for 'env' a
* nested block of NAME = value lines which becomes the list of NAME=value.
*/
static size_t
body(struct cb *c, struct ent *e, int *closed)
{
size_t n = 0;
*closed = 0;
for (;;) {
char key[48];
size_t k = 0;
unsigned line;
skip(c, 1);
if (*c->p == '}') {
c->p++;
*closed = 1;
return n;
}
if (*c->p == '\0') {
fail(c, c->line, "block without a closing }");
return n;
}
line = c->line;
while (isalnum((unsigned char)*c->p) || *c->p == '_' ||
*c->p == '-' || *c->p == '.') {
if (k + 1 < sizeof(key))
key[k++] = *c->p;
c->p++;
}
key[k] = '\0';
if (k == 0) {
fail(c, line, "expected a name, found '%c'", *c->p);
return n;
}
if (n == MAX_ENTRIES) {
fail(c, line, "more than %d entries in a block", MAX_ENTRIES);
return n;
}
memset(&e[n], 0, sizeof(e[n]));
snprintf(e[n].key, sizeof(e[n].key), "%s", key);
e[n].line = line;
skip(c, 0);
if (*c->p == '{') {
/* env { A = b } */
c->p++;
e[n].v.list = 1;
for (;;) {
char nm[96];
size_t m = 0;
char *v;
unsigned vl;
skip(c, 1);
if (*c->p == '}') {
c->p++;
break;
}
if (*c->p == '\0') {
fail(c, line, "block without a closing }");
n++;
return n;
}
vl = c->line;
while (isalnum((unsigned char)*c->p) || *c->p == '_') {
if (m + 1 < sizeof(nm))
nm[m++] = *c->p;
c->p++;
}
nm[m] = '\0';
skip(c, 0);
if (m == 0 || *c->p != '=') {
fail(c, vl, "expected NAME = value");
n++;
return n;
}
c->p++;
skip(c, 0);
v = scalar(c);
if (v == NULL) {
n++;
return n;
}
if (e[n].v.n < MAX_ITEMS) {
size_t len = strlen(nm) + strlen(v) + 2;
char *kv = malloc(len);
if (kv != NULL) {
snprintf(kv, len, "%s=%s", nm, v);
e[n].v.items[e[n].v.n++] = kv;
}
}
free(v);
}
n++;
continue;
}
if (*c->p != '=') {
fail(c, line, "expected '=' after %s", key);
return n;
}
c->p++;
if (value(c, &e[n].v) != 0) {
n++;
return n;
}
n++;
}
}
int
sp_confblock_is(const char *text)
{
const char *p = text;
while (*p != '\0') {
const char *eol = strchr(p, '\n'), *q;
if (eol == NULL)
eol = p + strlen(p);
for (q = p; q < eol && (*q == ' ' || *q == '\t'); q++)
;
if (q < eol && *q != '#') {
for (; q < eol; q++) {
if (*q == '=')
return 0;
if (*q == '{')
return 1;
}
return 0;
}
p = *eol == '\n' ? eol + 1 : eol;
}
return 0;
}
int
sp_confblock_translate(const char *text, const char *path, struct sp_buf *out,
unsigned **map, size_t *nmap, struct sp_buf *err)
{
struct cb c;
struct ent *e;
memset(&c, 0, sizeof(c));
c.p = text;
c.line = 1;
c.path = path;
c.err = err;
c.out = out;
e = calloc(MAX_ENTRIES, sizeof(*e));
if (e == NULL) {
sp_buf_printf(err, "config: %s: out of memory", path);
return -1;
}
for (;;) {
char kind[48], name[96];
size_t k = 0, n;
unsigned line;
int closed;
skip(&c, 1);
if (*c.p == '\0' || c.failed)
break;
line = c.line;
while (isalnum((unsigned char)*c.p) || *c.p == '_' || *c.p == '-')
if (k + 1 < sizeof(kind))
kind[k++] = *c.p++;
else
c.p++;
kind[k] = '\0';
if (k == 0) {
fail(&c, line, "expected a block or a setting, found '%c'",
*c.p);
break;
}
skip(&c, 0);
if (*c.p == '=') {
/* a bare setting at the top level belongs to core */
c.p++;
snprintf(e[0].key, sizeof(e[0].key), "%s", kind);
e[0].line = line;
if (value(&c, &e[0].v) != 0)
break;
do_core(&c, e, 1);
ents_free(e, 1);
continue;
}
name[0] = '\0';
if (*c.p != '{') {
size_t m = 0;
while (*c.p != '\0' && !isspace((unsigned char)*c.p) &&
*c.p != '{' && *c.p != '#')
if (m + 1 < sizeof(name))
name[m++] = *c.p++;
else
c.p++;
name[m] = '\0';
skip(&c, 0);
}
if (*c.p != '{') {
fail(&c, line, "expected '{' after %s", kind);
break;
}
c.p++;
n = body(&c, e, &closed);
if (!c.failed && closed) {
int needs_name = !strcmp(kind, "provider") ||
!strcmp(kind, "pool") || !strcmp(kind, "exit");
if (needs_name && name[0] == '\0')
fail(&c, line, "%s needs a name: %s NAME { ... }",
kind, kind);
else if (!needs_name && name[0] != '\0')
fail(&c, line, "%s takes no name", kind);
else if (!strcmp(kind, "core"))
do_core(&c, e, n);
else if (!strcmp(kind, "telegram")) {
size_t i;
for (i = 0; i < n && !c.failed; i++) {
if (!strcmp(e[i].key, "allow")) {
char list[256];
joined(&e[i].v, list, sizeof(list));
emit(&c, e[i].line, "telegram_allow = %s", list);
} else
fail(&c, e[i].line,
"unknown telegram field '%s'", e[i].key);
}
} else if (!strcmp(kind, "provider"))
do_provider(&c, name, line, e, n);
else if (!strcmp(kind, "pool"))
do_pool(&c, name, line, e, n);
else if (!strcmp(kind, "exit"))
do_exit(&c, name, line, e, n);
else
fail(&c, line, "unknown block '%s' (core, telegram, "
"provider, pool, exit)", kind);
}
ents_free(e, n);
if (c.failed)
break;
}
free(e);
if (c.failed) {
free(c.map);
return -1;
}
*map = c.map;
*nmap = c.nmap;
return 0;
}
+36
View File
@@ -0,0 +1,36 @@
/* splinter -- the block syntax of the config file. */
#ifndef SP_CONFBLOCK_H
#define SP_CONFBLOCK_H
#include <stddef.h>
#include "splinter.h"
/*
* The config file is written as blocks:
*
* core { theme = Delphinium steps = 40 plugins = [a.so, b.so] }
* provider claude-a {
* kind = cli
* cmd = "claude -p"
* env { CLAUDE_CODE_OAUTH_TOKEN = "${CLAUDE_A}" }
* limit = 45/5h
* }
* pool claude { members = [claude-a, claude-b] strategy = balance }
*
* Reading it is translation: every block becomes the lines the flat reader
* already knows, and 'map' says which line of the file each of them came from,
* so an error names the line you wrote, not a line of the translation.
*/
/* 1 when the text is written in blocks, 0 for the flat key = value form */
int sp_confblock_is(const char *text);
/*
* 'out' gets the flat lines; *map gets, per flat line, the line number in the
* source (malloc'ed, free it). 0 or -1 with a message in 'err'.
*/
int sp_confblock_translate(const char *text, const char *path,
struct sp_buf *out, unsigned **map, size_t *nmap,
struct sp_buf *err);
#endif
+213 -59
View File
@@ -16,6 +16,7 @@
#include "config.h"
#include "usage.h"
#include "confblock.h"
void
sp_config_init(struct sp_config *c)
@@ -395,12 +396,82 @@ sp_config_load(struct sp_config *c, const char *path, struct sp_buf *err)
return load_dropins(c, path, err);
}
/* pool = id | strategy=failover|balance | members=a,b,c */
static int
parse_pool(struct sp_pool *p, const char *val, struct sp_buf *err,
const char *path, unsigned lineno)
{
char *copy, *field, *save = NULL;
int first = 1;
memset(p, 0, sizeof(*p));
snprintf(p->strategy, sizeof(p->strategy), "failover");
copy = strdup(val);
if (copy == NULL)
return -1;
for (field = strtok_r(copy, "|", &save); field != NULL;
field = strtok_r(NULL, "|", &save)) {
char *s = trim(field);
if (*s == '\0')
continue;
if (first) {
snprintf(p->id, sizeof(p->id), "%s", s);
first = 0;
} else if (!strncmp(s, "strategy=", 9)) {
if (strcmp(s + 9, "failover") && strcmp(s + 9, "balance")) {
sp_buf_printf(err, "config: %s:%u: strategy is "
"failover or balance", path, lineno);
free(copy);
return -1;
}
snprintf(p->strategy, sizeof(p->strategy), "%s", s + 9);
} else if (!strncmp(s, "members=", 8)) {
char *m, *msave = NULL;
for (m = strtok_r(s + 8, ",", &msave); m != NULL;
m = strtok_r(NULL, ",", &msave)) {
m = trim(m);
if (*m == '\0')
continue;
if (p->nmembers == SP_CONFIG_POOL_MEMBERS) {
sp_buf_printf(err, "config: %s:%u: more than "
"%d members", path, lineno,
SP_CONFIG_POOL_MEMBERS);
free(copy);
return -1;
}
snprintf(p->member[p->nmembers++],
sizeof(p->member[0]), "%s", m);
}
} else {
sp_buf_printf(err, "config: %s:%u: unknown pool field "
"'%s'", path, lineno, s);
free(copy);
return -1;
}
}
free(copy);
if (p->id[0] == '\0' || p->nmembers == 0) {
sp_buf_printf(err, "config: %s:%u: a pool needs an id and "
"members", path, lineno);
return -1;
}
return 0;
}
static int
load_stream(struct sp_config *c, FILE *f, const char *path,
const unsigned *linemap, size_t nmap, struct sp_buf *err);
static int
load_one(struct sp_config *c, const char *path, struct sp_buf *err)
{
FILE *f;
char line[2048];
unsigned lineno = 0;
char *text = NULL;
size_t len = 0, cap = 0;
int rc;
if (c == NULL || path == NULL)
return -1;
@@ -413,11 +484,83 @@ load_one(struct sp_config *c, const char *path, struct sp_buf *err)
strerror(errno));
return -1;
}
for (;;) {
char *nt;
size_t n;
if (len + 4096 + 1 > cap) {
cap = cap != 0 ? cap * 2 : 8192;
nt = realloc(text, cap);
if (nt == NULL) {
free(text);
fclose(f);
return -1;
}
text = nt;
}
n = fread(text + len, 1, cap - len - 1, f);
if (n == 0)
break;
len += n;
}
fclose(f);
if (text == NULL)
text = calloc(1, 1);
else
text[len] = '\0';
if (text != NULL && sp_confblock_is(text)) {
struct sp_buf flat;
unsigned *map = NULL;
size_t nmap = 0;
FILE *mf;
if (sp_buf_init(&flat) != 0) {
free(text);
return -1;
}
if (sp_confblock_translate(text, path, &flat, &map, &nmap,
err) != 0) {
sp_buf_free(&flat);
free(text);
return -1;
}
mf = fmemopen(flat.p != NULL ? flat.p : (char *)"", flat.len, "r");
if (mf == NULL && flat.len == 0) {
rc = 0;
} else if (mf == NULL) {
rc = -1;
} else {
rc = load_stream(c, mf, path, map, nmap, err);
fclose(mf);
}
free(map);
sp_buf_free(&flat);
free(text);
return rc;
}
f = fmemopen(text, len, "r");
if (f == NULL) {
rc = len == 0 ? 0 : -1;
} else {
rc = load_stream(c, f, path, NULL, 0, err);
fclose(f);
}
free(text);
return rc;
}
static int
load_stream(struct sp_config *c, FILE *f, const char *path,
const unsigned *linemap, size_t nmap, struct sp_buf *err)
{
char line[4096];
unsigned lineno = 0, phys = 0;
while (fgets(line, sizeof(line), f) != NULL) {
char *eq, *key, *val;
lineno++;
phys++;
lineno = linemap != NULL && phys <= nmap ? linemap[phys - 1] : phys;
key = trim(line);
if (*key == '\0' || *key == '#')
continue;
@@ -425,7 +568,6 @@ load_one(struct sp_config *c, const char *path, struct sp_buf *err)
if (eq == NULL) {
sp_buf_printf(err, "config: %s:%u: no '=' in: %s",
path, lineno, key);
fclose(f);
return -1;
}
*eq = '\0';
@@ -461,7 +603,6 @@ load_one(struct sp_config *c, const char *path, struct sp_buf *err)
else if (!strcmp(key, "cli_env")) {
if (add_env(c->cli_env, &c->ncli_env, val, err, path,
lineno) != 0) {
fclose(f);
return -1;
}
}
@@ -474,7 +615,25 @@ load_one(struct sp_config *c, const char *path, struct sp_buf *err)
sp_buf_printf(err, "config: %s:%u: %s wants "
"N/window, e.g. %s", path, lineno, key,
lim ? "45/5h" : "2000000/7d");
fclose(f);
return -1;
}
}
else if (!strcmp(key, "on_limit")) {
if (!strcmp(val, "wait"))
c->on_limit_fail = 0;
else if (!strcmp(val, "fail"))
c->on_limit_fail = 1;
else {
sp_buf_printf(err, "config: %s:%u: on_limit is "
"wait or fail", path, lineno);
return -1;
}
}
else if (!strcmp(key, "max_wait")) {
c->max_wait = sp_usage_window(val);
if (c->max_wait == 0) {
sp_buf_printf(err, "config: %s:%u: max_wait is a "
"duration like 6h or 2d", path, lineno);
return -1;
}
}
@@ -502,7 +661,6 @@ load_one(struct sp_config *c, const char *path, struct sp_buf *err)
sp_buf_printf(err, "config: %s:%u: more than %d "
"skills_dir", path, lineno,
SP_CONFIG_MAX_DELEGATES);
fclose(f);
return -1;
}
snprintf(c->skills_dir[c->nskills_dir++],
@@ -513,12 +671,10 @@ load_one(struct sp_config *c, const char *path, struct sp_buf *err)
sp_buf_printf(err, "config: %s:%u: more than %d "
"exits", path, lineno,
SP_CONFIG_MAX_DELEGATES);
fclose(f);
return -1;
}
if (parse_exit(&c->exit[c->nexits], val, err, path,
lineno) != 0) {
fclose(f);
return -1;
}
c->nexits++;
@@ -528,32 +684,40 @@ load_one(struct sp_config *c, const char *path, struct sp_buf *err)
sp_buf_printf(err, "config: %s:%u: more than %d "
"delegates", path, lineno,
SP_CONFIG_MAX_DELEGATES);
fclose(f);
return -1;
}
if (parse_delegate(&c->delegate[c->ndelegates], val,
err, path, lineno) != 0) {
fclose(f);
return -1;
}
c->ndelegates++;
}
else if (!strcmp(key, "pool")) {
if (c->npools == SP_CONFIG_MAX_POOLS) {
sp_buf_printf(err, "config: %s:%u: more than %d "
"pools", path, lineno, SP_CONFIG_MAX_POOLS);
return -1;
}
if (parse_pool(&c->pool[c->npools], val, err, path,
lineno) != 0)
return -1;
c->npools++;
}
else if (!strcmp(key, "default"))
set_str(c->default_id, sizeof(c->default_id), val);
else if (!strcmp(key, "plugin")) {
if (c->nplugins == SP_CONFIG_MAX_PLUGINS) {
sp_buf_printf(err, "config: %s:%u: more than %d "
"plugins", path, lineno, SP_CONFIG_MAX_PLUGINS);
fclose(f);
return -1;
}
set_str(c->plugins[c->nplugins++], 512, val);
} else {
sp_buf_printf(err, "config: %s:%u: unknown key '%s'",
path, lineno, key);
fclose(f);
return -1;
}
}
fclose(f);
return 0;
}
@@ -583,58 +747,48 @@ sp_config_write_example(const char *path, struct sp_buf *err)
fprintf(f,
"# splinter configuration\n"
"#\n"
"# Plain key = value. '#' starts a comment. Command line wins over\n"
"# this file, this file wins over the built-in default. An unknown\n"
"# key is an error, so a typo cannot quietly do nothing.\n"
"# Blocks with { }, settings as name = value, lists in [ ].\n"
"# \"${NAME}\" inserts an environment variable. '#' starts a comment.\n"
"# An unknown name is an error, so a typo cannot quietly do nothing.\n"
"# Command line wins over this file, this file over the built-in default.\n"
"\n"
"# Where the answers come from. Either an OpenAI-compatible endpoint\n"
"# (endpoint + model), or a transport a plugin provides (transport).\n"
"endpoint = http://127.0.0.1:8080/v1/chat/completions\n"
"model = \n"
"core {\n"
" default = local # a provider or pool below; -m overrides\n"
" theme = Delphinium # splinter --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"
"\n"
"# Name of the environment variable holding the API key.\n"
"# Empty/missing means no Authorization header is sent.\n"
"api_key_env = SPLINTER_API_KEY\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"
"# A transport provided by a plugin, e.g. \"cli\" for any command as the\n"
"# model. Use either this or endpoint/model, not both.\n"
"#transport = cli\n"
"#cli_cmd = claude -p\n"
"#cli_env = CLAUDE_CODE_OAUTH_TOKEN=sk-ant-...\n"
"#cli_fallback = claude1, claude0\n"
" #plugins = [plugins/lcm/lcm.so, plugins/cps/cps.so]\n"
"}\n"
"\n"
"# Plugins to load, one per line. Paths are relative to the working\n"
"# directory unless absolute.\n"
"#plugin = plugins/lcm/lcm.so\n"
"#plugin = plugins/cps/cps.so\n"
"#telegram { allow = [123456789] }\n"
"\n"
"# Language: two-letter code, e.g. de or en. Catalogues live in\n"
"# share/locale. Without this, the environment decides (LANG).\n"
"#locale = de\n"
"provider local {\n"
" about = \"my local model\"\n"
" endpoint = http://127.0.0.1:8080/v1/chat/completions\n"
" model = my-model # the name the endpoint serves\n"
" tags = [local, code]\n"
" #key_env = SPLINTER_API_KEY # name of the variable holding the key\n"
"}\n"
"\n"
"# CDE palette for the UI. `splinter --list-themes` prints them all.\n"
"theme = Delphinium\n"
"# A subscription with an allowance splinter should watch:\n"
"#provider claude-a {\n"
"# kind = cli\n"
"# cmd = \"claude -p\"\n"
"# tags = [cli, big]\n"
"# limit = 40/5h # calls per window; tokens = N/window too\n"
"# env { CLAUDE_CODE_OAUTH_TOKEN = \"${CLAUDE_A_TOKEN}\" }\n"
"#}\n"
"\n"
"# Run mutating and destructive tools without asking. 0 or 1.\n"
"autonomous = 0\n"
"\n"
"# Tool rounds per turn, and the conversation budget in bytes\n"
"# (0 = no limit).\n"
"steps = 150\n"
"max_bytes = 0\n"
"\n"
"# Timeouts in seconds. Local models can take long to answer: raise\n"
"# these instead of failing mid-turn. 0 means the built-in default.\n"
"#http_timeout = 900\n"
"#cli_timeout = 1800\n"
"#delegate_timeout = 900\n"
"#run_timeout = 600\n"
"\n"
"# Where session logs go (default ~/.splinter).\n"
"#session_dir = ~/.splinter\n"
"\n"
"# Sent once at the start of a conversation.\n"
"#system_prompt = Du bist knapp. Keine Floskeln.\n");
"# Providers that stand in for each other:\n"
"#pool claude { members = [claude-a, claude-b] strategy = balance }\n");
if (ferror(f)) {
sp_buf_printf(err, "config: %s: write failed", path);
fclose(f);
+21 -2
View File
@@ -21,14 +21,14 @@
#include "splinter.h"
#define SP_CONFIG_MAX_PLUGINS 8
#define SP_CONFIG_MAX_PLUGINS 32
/*
* A delegate is another model splinter may hand work to: a name, what it is
* good at, and where it lives. No profiles - a profile is a directory with a
* dozen files, and all this needs is a line you can read at 2 a.m.
*/
#define SP_CONFIG_MAX_DELEGATES 8
#define SP_CONFIG_MAX_DELEGATES 32
/*
* Extra environment for a program splinter starts: NAME=VALUE, set in the
@@ -71,7 +71,24 @@ struct sp_delegate {
long req_window, tok_window;
};
/*
* A pool: providers that stand in for each other. 'failover' takes the first
* member that has room, in the order listed; 'balance' the one with the most
* left of its allowance.
*/
#define SP_CONFIG_MAX_POOLS 16
#define SP_CONFIG_POOL_MEMBERS 16
struct sp_pool {
char id[32];
char strategy[16];
char member[SP_CONFIG_POOL_MEMBERS][32];
size_t nmembers;
};
struct sp_config {
struct sp_pool pool[SP_CONFIG_MAX_POOLS];
size_t npools;
char default_id[32]; /* the provider or pool the conversation starts on */
struct sp_delegate delegate[SP_CONFIG_MAX_DELEGATES];
size_t ndelegates;
char skills_dir[SP_CONFIG_MAX_DELEGATES][512];
@@ -104,6 +121,8 @@ struct sp_config {
long delegate_timeout; /* seconds for delegate children, 0: default */
long run_timeout; /* seconds for the run tool, 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 */
/*
* Delegates built from environment tokens (CLAUDE_CODE_OAUTH_TOKEN and the
* numbered variants) are off unless asked for. An entry that appears because
+86 -8
View File
@@ -37,6 +37,7 @@
#include "mcp.h"
#include "config.h"
#include "usage.h"
#include "providers.h"
#include <sys/stat.h>
#include <dirent.h>
@@ -300,6 +301,26 @@ choose(const struct sp_config *cfg, const char *task, const char *wanted,
}
}
}
/*
* A member of a pool stands for the pool: the task fits the member's
* tags, but the one to use is whichever the pool's strategy picks now.
*/
if (best != NULL) {
const struct sp_pool *pool = sp_pool_of(cfg, best->id);
if (pool != NULL) {
const struct sp_delegate *m =
sp_pool_pick(cfg, pool, NULL, best->tags, NULL);
if (m != NULL && m != best) {
size_t n = strlen(why);
snprintf(why + n, whylen - n, "%spool %s: %s",
n > 0 ? ", " : "", pool->id, m->id);
best = m;
}
}
}
if (score_out != NULL)
*score_out = best_score;
return best;
@@ -325,6 +346,58 @@ shell_quote(struct sp_buf *b, const char *s)
return sp_buf_puts(b, "'");
}
/*
* Where the child of a cli delegate finds the cli transport. The child is this
* binary again in one-shot mode, and for a cli delegate it has to load
* plugins/cli/cli.so.
*
* Deriving that path from /proc/self/exe alone assumed the binary sits in the
* build tree. An installed splinter sits in $(PREFIX)/bin, 'make install' put
* no plugins next to it, so the child loaded nothing, registered no 'cli'
* transport and exited 2. The parent reported that 2 as the delegate's exit
* code, which made a healthy CLI behind it look broken.
*
* Order:
* $SPLINTER_CLI_PLUGIN explicit, used as given
* <dir of self>/plugins/cli/cli.so running from the tree
* <dir of self>/../lib/splinter/plugins/cli/cli.so installed layout
* SPLINTER_PLUGIN_DIR/plugins/cli/cli.so the build tree, compiled in
* Of the three derived ones the first readable file wins; when none exists the
* first is returned, so the child's own error names the place that was
* expected.
*/
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;
if (env != NULL && *env != '\0') {
snprintf(out, len, "%s", env);
return;
}
snprintf(dir, sizeof(dir), "%s",
self != NULL && *self != '\0' ? self : "splinter");
slash = strrchr(dir, '/');
if (slash != NULL)
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/../lib/splinter/plugins/cli/cli.so", dir);
#ifdef SPLINTER_PLUGIN_DIR
snprintf(cand[n++], sizeof(cand[0]), "%s/plugins/cli/cli.so",
SPLINTER_PLUGIN_DIR);
#endif
for (i = 0; i < n; i++)
if (access(cand[i], R_OK) == 0)
break;
snprintf(out, len, "%s", cand[i < n ? i : 0]);
}
/*
* The child side of every delegation, single or parallel: build the argument
* vector and exec. It used to be written twice, and the two copies had drifted
@@ -356,14 +429,7 @@ exec_delegate(const struct del_ctx *c, const struct sp_delegate *d,
* environment where the program expects it.
*/
if (cli) {
char *slash;
snprintf(plug, sizeof(plug), "%s", c->self);
slash = strrchr(plug, '/');
if (slash != NULL)
*slash = '\0';
snprintf(plug + strlen(plug), sizeof(plug) - strlen(plug),
"/plugins/cli/cli.so");
sp_delegate_cli_plugin(c->self, plug, sizeof(plug));
if (d->cmd[0] != '\0')
(void)setenv("SPLINTER_CLI_CMD", d->cmd, 1);
if (d->key[0] != '\0' && !remote) {
@@ -1752,10 +1818,22 @@ static const struct sp_delegate *
find_delegate(const struct sp_config *cfg, const char *id)
{
size_t i;
const struct sp_pool *p;
if (!cfg || !id) return NULL;
for (i = 0; i < cfg->ndelegates; i++)
if (strcmp(cfg->delegate[i].id, id) == 0)
return &cfg->delegate[i];
/* a pool's name stands for the member the pool picks now */
if ((p = sp_pool_find(cfg, id)) != NULL) {
const struct sp_delegate *m = sp_pool_pick(cfg, p, NULL, NULL, NULL);
if (m != NULL)
return m;
for (i = 0; i < cfg->ndelegates; i++)
if (strcmp(cfg->delegate[i].id, p->member[0]) == 0)
return &cfg->delegate[i];
}
return NULL;
}
+185 -3
View File
@@ -22,6 +22,7 @@
#include "memory.h"
#include "prompt.h"
#include "providers.h"
#include "usage.h"
#include "folder.h"
#include "mcpserver.h"
#include "a2aserver.h"
@@ -40,6 +41,10 @@ usage(FILE *f)
" -p, --prompt TEXT run one turn with TEXT and exit\n"
" --endpoint URL transport: OpenAI-compatible chat endpoint\n"
" --model NAME model name for --endpoint (required)\n"
" -m, --select SEL use a provider or pool of the config: ID,\n"
" ID/MODEL, POOL, or a model name it has\n"
" --model-list list what -m accepts (asks each endpoint\n"
" which models it serves; --no-probe skips)\n"
" --api-key-env VAR read the API key from VAR (default\n"
" SPLINTER_API_KEY; missing means no auth)\n"
" --script FILE transport: replay replies from FILE, one\n"
@@ -206,11 +211,13 @@ struct opts {
const char *sessdir, *sessid, *theme, *transport, *config_path;
const char *choose, *mcp_ip;
const char *delegate;
const char *plugins[16];
const char *plugins[32];
size_t nplugins;
int init_config, no_config, list_themes, chat, resume;
int daemon, no_stdin, continue_here, interview;
int no_stream;
const char *select;
int model_list, no_probe;
int acklist, ack_id, ack_yes, mcp_port;
const char *a2a_ip;
int a2a_port;
@@ -229,6 +236,20 @@ ack_word(const char *w)
return -1;
}
static struct sp_agent *g_ag;
static struct sp_config *g_conf;
/* a provider at its limit: another member of its pool, if one has room */
static int
main_switch(void *ctx)
{
(void)ctx;
return sp_provider_failover(g_ag, g_conf);
}
/* the longest wait for a usage limit in seconds, 0: the default of 12 h */
static long g_max_wait;
/*
* The command line into 'o' and 'cfg'. Returns -1 to go on, or the exit
* status (help and version exit 0, a bad option 2).
@@ -259,6 +280,12 @@ parse_args(int argc, char **argv, struct opts *o, struct sp_agent_config *cfg)
VALUE(o->endpoint);
else if (!strcmp(a, "--model"))
VALUE(o->model);
else if (!strcmp(a, "-m") || !strcmp(a, "--select"))
VALUE(o->select);
else if (!strcmp(a, "--model-list"))
o->model_list = 1;
else if (!strcmp(a, "--no-probe"))
o->no_probe = 1;
else if (!strcmp(a, "--api-key-env"))
VALUE(o->key_env);
else if (!strcmp(a, "--init-config"))
@@ -276,8 +303,8 @@ parse_args(int argc, char **argv, struct opts *o, struct sp_agent_config *cfg)
else if (!strcmp(a, "--plugin")) {
if (!need_value(argc, i, a))
return 2;
if (o->nplugins == 16) {
fprintf(stderr, "splinter: at most 16 plugins\n");
if (o->nplugins == 32) {
fprintf(stderr, "splinter: at most 32 plugins\n");
return 2;
}
o->plugins[o->nplugins++] = argv[++i];
@@ -472,6 +499,10 @@ load_config(struct opts *o, struct sp_config *conf, struct sp_agent_config *cfg,
o->plugins[o->nplugins++] = conf->plugins[k];
if (conf->steps > 0)
cfg->max_steps = conf->steps;
/* waiting out a usage limit is the default; on_limit = fail turns it off */
g_max_wait = conf->max_wait;
if (conf->on_limit_fail)
cfg->limit_wait = NULL;
if (conf->max_bytes > 0)
cfg->max_bytes = conf->max_bytes;
if (conf->autonomous >= 0)
@@ -733,6 +764,145 @@ load_plugins(const struct opts *o, struct sp_registry *reg, struct sp_agent *ag,
return 0;
}
/* -m: the provider (or the config's default) becomes the run's transport */
static int
apply_selection(struct opts *o, struct sp_config *conf)
{
const char *sel = o->select;
struct sp_choice ch;
const struct sp_delegate *d;
if (sel == NULL) {
if (o->endpoint != NULL || o->script != NULL ||
o->transport != NULL || conf->default_id[0] == '\0')
return 0;
sel = conf->default_id;
}
if (sp_provider_choose(conf, sel, &ch) != 0) {
fprintf(stderr, "splinter: no provider, pool or model '%s' "
"(splinter --model-list shows them)\n", sel);
return 2;
}
d = ch.d;
sp_usage_set_active(d->id);
if (strcmp(d->kind, "cli") == 0) {
const struct sp_pool *pool = sp_pool_of(conf, d->id);
char self[512], plug[600], *slash;
ssize_t n;
size_t k;
o->transport = "cli";
setenv("SPLINTER_CLI_CMD", d->cmd[0] != '\0' ? d->cmd :
"claude -p", 1);
setenv("SPLINTER_CLI_ID", d->id, 1);
sp_config_apply_env((const char (*)[SP_CONFIG_ENV_LEN])d->env,
d->nenv);
/* the rest of its pool answers when this account is at its limit */
conf->cli_fallback[0] = '\0';
for (k = 0; pool != NULL && k < pool->nmembers; k++) {
if (strcmp(pool->member[k], d->id) == 0)
continue;
snprintf(conf->cli_fallback + strlen(conf->cli_fallback),
sizeof(conf->cli_fallback) - strlen(conf->cli_fallback),
"%s%s", conf->cli_fallback[0] != '\0' ? "," : "",
pool->member[k]);
}
n = readlink("/proc/self/exe", self, sizeof(self) - 1);
if (n > 0) {
size_t i;
int have = 0;
self[n] = '\0';
slash = strrchr(self, '/');
if (slash != NULL)
*slash = '\0';
snprintf(plug, sizeof(plug), "%s/plugins/cli/cli.so", self);
for (i = 0; i < o->nplugins; i++)
if (strstr(o->plugins[i], "cli.so") != NULL)
have = 1;
if (!have && o->nplugins < 32) {
static char keep[600];
snprintf(keep, sizeof(keep), "%s", plug);
o->plugins[o->nplugins++] = keep;
}
}
return 0;
}
o->endpoint = d->endpoint;
o->model = ch.model[0] != '\0' ? ch.model : d->model;
if (d->key_env[0] != '\0')
o->key_env = d->key_env;
return 0;
}
/* --model-list: what -m takes, one selector per line */
static int
run_model_list(const struct sp_config *conf, const struct opts *o)
{
size_t i, j;
if (conf->default_id[0] != '\0')
printf("# default: %s\n", conf->default_id);
if (conf->npools > 0)
printf("# pools\n");
for (i = 0; i < conf->npools; i++) {
const struct sp_pool *p = &conf->pool[i];
printf("%-34s pool, %s:", p->id, p->strategy);
for (j = 0; j < p->nmembers; j++)
printf(" %s", p->member[j]);
printf("\n");
}
printf("# providers (use with -m)\n");
for (i = 0; i < conf->ndelegates; i++) {
const struct sp_delegate *d = &conf->delegate[i];
struct sp_usage u;
char use[128], line[400];
struct sp_buf ids, perr;
int served = 0;
sp_usage_for(conf, d->id, &u);
sp_usage_brief(&u, use, sizeof(use));
snprintf(line, sizeof(line), "%s%s%s", d->kind[0] != '\0' &&
strcmp(d->kind, "cli") == 0 ? "cli: " : "",
d->kind[0] != '\0' && strcmp(d->kind, "cli") == 0 ? d->cmd :
d->model, d->about[0] != '\0' ? "" : "");
printf("%-34s %s [%s]\n", d->id, line, use);
if (o->no_probe || strcmp(d->kind, "cli") == 0 ||
d->endpoint[0] == '\0')
continue;
if (sp_buf_init(&ids) != 0 || sp_buf_init(&perr) != 0)
continue;
{
struct sp_provider pv;
memset(&pv, 0, sizeof(pv));
snprintf(pv.id, sizeof(pv.id), "%s", d->id);
snprintf(pv.endpoint, sizeof(pv.endpoint), "%s", d->endpoint);
snprintf(pv.model, sizeof(pv.model), "%s", d->model);
snprintf(pv.key_env, sizeof(pv.key_env), "%s", d->key_env);
served = sp_provider_served(&pv, &ids, &perr) == 0;
}
if (served && ids.p != NULL) {
char *m, *save = NULL;
for (m = strtok_r(ids.p, "\n", &save); m != NULL;
m = strtok_r(NULL, "\n", &save)) {
char sel[300];
if (*m == '\0' || strcmp(m, d->model) == 0)
continue;
snprintf(sel, sizeof(sel), "%s/%s", d->id, m);
printf("%-34.34s served\n", sel);
}
}
sp_buf_free(&ids);
sp_buf_free(&perr);
}
return 0;
}
/* the transport the options name; 0 or the exit status */
static int
pick_transport(const struct opts *o, struct sp_agent *ag, struct sp_host *host,
@@ -945,6 +1115,8 @@ main(int argc, char **argv)
o.mcp_port = 8098;
o.a2a_port = 8099;
cfg.max_steps = 150;
cfg.limit_wait = sp_limit_wait_default;
cfg.limit_ctx = &g_max_wait;
if (sp_buf_init(&err) != 0)
return 3;
@@ -971,6 +1143,10 @@ main(int argc, char **argv)
"environment\n", auto_added);
}
hide_secrets(&o, &conf);
if (o.model_list)
return run_model_list(&conf, &o);
if ((rc = apply_selection(&o, &conf)) != 0)
return rc;
if (o.choose != NULL)
return run_choose(&conf, o.choose);
@@ -1056,6 +1232,12 @@ main(int argc, char **argv)
cfg.approval_out = stderr;
ag.reg = &reg;
ag.cfg = &cfg;
g_ag = &ag;
g_conf = &conf;
if (conf.npools > 0) {
cfg.limit_switch = main_switch;
cfg.switch_ctx = NULL;
}
if (o.a2a_ip != NULL) {
rc = sp_a2a_serve(&ag, o.a2a_ip, o.a2a_port, &err);
+192
View File
@@ -698,3 +698,195 @@ sp_provider_add(struct sp_config *cfg, const char *dir, const char *id,
cfg->ndelegates++;
return 0;
}
/* ---------------------------------------------------------------- pools */
const struct sp_pool *
sp_pool_find(const struct sp_config *cfg, const char *id)
{
size_t i;
for (i = 0; cfg != NULL && id != NULL && i < cfg->npools; i++)
if (strcmp(cfg->pool[i].id, id) == 0)
return &cfg->pool[i];
return NULL;
}
const struct sp_pool *
sp_pool_of(const struct sp_config *cfg, const char *member)
{
size_t i, j;
for (i = 0; cfg != NULL && member != NULL && i < cfg->npools; i++)
for (j = 0; j < cfg->pool[i].nmembers; j++)
if (strcmp(cfg->pool[i].member[j], member) == 0)
return &cfg->pool[i];
return NULL;
}
static const struct sp_delegate *
delegate_by_id(const struct sp_config *cfg, const char *id)
{
size_t i;
for (i = 0; cfg != NULL && i < cfg->ndelegates; i++)
if (strcmp(cfg->delegate[i].id, id) == 0)
return &cfg->delegate[i];
return NULL;
}
/* every tag of 'need' (comma list) is among 'have' */
static int
has_all_tags(const char *have, const char *need)
{
char buf[256], *t, *save = NULL;
if (need == NULL || *need == '\0')
return 1;
snprintf(buf, sizeof(buf), "%s", need);
for (t = strtok_r(buf, ", ", &save); t != NULL;
t = strtok_r(NULL, ", ", &save)) {
const char *h = have;
size_t n = strlen(t);
int found = 0;
while (*h != '\0') {
while (*h == ',' || *h == ' ')
h++;
if (strncmp(h, t, n) == 0 && (h[n] == ',' || h[n] == '\0' ||
h[n] == ' '))
found = 1;
while (*h != '\0' && *h != ',')
h++;
}
if (!found)
return 0;
}
return 1;
}
const struct sp_delegate *
sp_pool_pick(const struct sp_config *cfg, const struct sp_pool *p,
const char *skip, const char *need_tags, long *soonest)
{
const struct sp_delegate *best = NULL;
double best_frac = 3;
size_t i;
if (soonest != NULL)
*soonest = 0;
for (i = 0; i < p->nmembers; i++) {
const struct sp_delegate *d = delegate_by_id(cfg, p->member[i]);
struct sp_usage u;
long back;
if (d == NULL || (skip != NULL && strcmp(skip, d->id) == 0))
continue;
if (!has_all_tags(d->tags, need_tags))
continue;
sp_usage_for(cfg, d->id, &u);
if (u.benched_until > 0 || u.frac >= 1.0) {
back = u.benched_until > 0 ? u.benched_until : u.reset_at;
if (soonest != NULL && back > 0 &&
(*soonest == 0 || back < *soonest))
*soonest = back;
continue;
}
if (strcmp(p->strategy, "balance") != 0)
return d; /* failover: the first with room */
if ((u.frac < 0 ? 0 : u.frac) < best_frac) {
best_frac = u.frac < 0 ? 0 : u.frac;
best = d;
}
}
return best;
}
int
sp_provider_choose(const struct sp_config *cfg, const char *sel,
struct sp_choice *out)
{
const struct sp_pool *p;
const struct sp_delegate *d;
const char *slash;
size_t i;
memset(out, 0, sizeof(*out));
if (cfg == NULL || sel == NULL || *sel == '\0')
return -1;
if ((p = sp_pool_find(cfg, sel)) != NULL) {
d = sp_pool_pick(cfg, p, NULL, NULL, NULL);
/* all at their limit: the first one, the run will wait for it */
if (d == NULL)
d = delegate_by_id(cfg, p->member[0]);
if (d == NULL)
return -1;
out->d = d;
snprintf(out->model, sizeof(out->model), "%s", d->model);
return 0;
}
if ((d = delegate_by_id(cfg, sel)) != NULL) {
out->d = d;
snprintf(out->model, sizeof(out->model), "%s", d->model);
return 0;
}
/* provider/model: the provider's id is the part before the first '/' */
slash = strchr(sel, '/');
if (slash != NULL && slash != sel) {
char id[64];
size_t n = (size_t)(slash - sel);
if (n < sizeof(id)) {
memcpy(id, sel, n);
id[n] = '\0';
d = delegate_by_id(cfg, id);
if (d == NULL && sp_pool_find(cfg, id) != NULL) {
p = sp_pool_find(cfg, id);
d = sp_pool_pick(cfg, p, NULL, NULL, NULL);
if (d == NULL)
d = delegate_by_id(cfg, p->member[0]);
}
if (d != NULL) {
out->d = d;
snprintf(out->model, sizeof(out->model), "%s",
slash + 1);
return 0;
}
}
}
/* a model name that one provider has */
for (i = 0; i < cfg->ndelegates; i++)
if (strcmp(cfg->delegate[i].model, sel) == 0) {
out->d = &cfg->delegate[i];
snprintf(out->model, sizeof(out->model), "%s", sel);
return 0;
}
return -1;
}
int
sp_provider_failover(struct sp_agent *ag, const struct sp_config *cfg)
{
const char *active = sp_usage_active();
const struct sp_pool *p = sp_pool_of(cfg, active);
const struct sp_delegate *d;
struct sp_buf err;
int rc;
if (p == NULL && cfg != NULL && cfg->default_id[0] != '\0')
p = sp_pool_find(cfg, cfg->default_id);
if (p == NULL || ag == NULL)
return 0;
d = sp_pool_pick(cfg, p, active, NULL, NULL);
/* a cli member is reached through the cli plugin's own fallback */
if (d == NULL || strcmp(d->kind, "cli") == 0 || d->endpoint[0] == '\0')
return 0;
if (sp_buf_init(&err) != 0)
return 0;
rc = sp_provider_apply(ag, d->endpoint, d->model, d->key_env, &err);
sp_buf_free(&err);
if (rc != 0)
return 0;
sp_usage_set_active(d->id);
return 1;
}
+33
View File
@@ -5,6 +5,8 @@
#include <stddef.h>
struct sp_config;
struct sp_delegate;
struct sp_pool;
struct sp_agent;
struct sp_transport;
struct sp_buf;
@@ -90,4 +92,35 @@ int sp_provider_save_choice(const struct sp_config *,
int sp_provider_line(char *buf, size_t len, const char *id,
const char *endpoint, const char *model, const char *key_env);
/*
* Pools. A pool is a name for providers that stand in for each other.
* sp_pool_pick gives the member to use now -- first with room (failover) or
* the one with the most left (balance) -- never 'skip' (the one that just
* failed) and only one that has every tag of 'need_tags' (comma list, NULL:
* any), and NULL when every member is benched or used up; *soonest then
* holds the epoch the first of them is back (0: unknown).
*/
const struct sp_pool *sp_pool_find(const struct sp_config *, const char *id);
const struct sp_pool *sp_pool_of(const struct sp_config *, const char *member);
const struct sp_delegate *sp_pool_pick(const struct sp_config *,
const struct sp_pool *, const char *skip, const char *need_tags,
long *soonest);
/*
* What the user means by "-m SEL": a pool, a provider, "provider/model", or a
* model name one of the providers has. 0, or -1 when nothing matches.
*/
struct sp_choice {
const struct sp_delegate *d;
char model[256]; /* the model to ask for, the provider's own by default */
};
int sp_provider_choose(const struct sp_config *, const char *sel,
struct sp_choice *out);
/*
* 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.
*/
int sp_provider_failover(struct sp_agent *, const struct sp_config *);
#endif /* SPLINTER_PROVIDERS_H */
+51
View File
@@ -252,6 +252,45 @@ stream_cb(void *ctx, int kind, const char *text)
pthread_mutex_unlock(&t->lock);
}
/*
* The turn hit a usage limit: say so in the status line and in the reasoning,
* and wait for the reset on the turn thread. The screen stays alive (it is
* another thread), Ctrl-C ends the wait, and /resume goes on later.
*/
static long g_max_wait = 12 * 3600;
static int
ui_limit_wait(void *ctx, long until, const char *why)
{
struct turn *t = ctx;
char when[32], line[300];
struct tm tm;
time_t tt = (time_t)until;
if (until - (long)time(NULL) > g_max_wait)
return 0;
strftime(when, sizeof(when), "%a %H:%M", localtime_r(&tt, &tm));
(void)why;
snprintf(line, sizeof(line), "usage limit: continuing at %s", when);
pthread_mutex_lock(&t->lock);
snprintf(t->tool_line, sizeof(t->tool_line), "%s (Ctrl-C stops, /resume goes on)", line);
if (t->flow.len > 0 && t->flow.p[t->flow.len - 1] != '\n')
(void)sp_buf_puts(&t->flow, "\n");
(void)sp_buf_puts(&t->flow, "\xe2\x80\xba ");
(void)sp_buf_puts(&t->flow, line);
(void)sp_buf_puts(&t->flow, "\n\n");
pthread_mutex_unlock(&t->lock);
while ((long)time(NULL) < until && !t->cancel) {
struct timespec ts = { 0, 250000000L };
nanosleep(&ts, NULL);
}
pthread_mutex_lock(&t->lock);
t->tool_line[0] = '\0';
pthread_mutex_unlock(&t->lock);
return !t->cancel;
}
static int
steer_cb(void *ctx, struct sp_buf *out)
{
@@ -1524,6 +1563,7 @@ slash_collect(struct sp_agent *ag, struct sp_host *host,
slash_add_match(matches, &n, max, "status");
slash_add_match(matches, &n, max, "usage");
slash_add_match(matches, &n, max, "resume");
slash_add_match(matches, &n, max, "swarm");
if (host != NULL && sp_buf_init(&b) == 0) {
if (sp_host_command_help(host, &b) > 0 && b.p != NULL) {
@@ -2526,6 +2566,10 @@ ui_turn(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
cfg.tool_begin_ctx = &tu;
cfg.on_compact = compact_cb;
cfg.on_compact_ctx = &tu;
if (orig->limit_wait != NULL) {
cfg.limit_wait = ui_limit_wait;
cfg.limit_ctx = &tu;
}
sp_openai_set_cancel(&tu.cancel);
ag->cfg = &cfg;
@@ -2667,6 +2711,8 @@ ui_start(struct ui_state *s, struct sp_agent *ag, struct sp_host *host,
model != NULL ? model : "");
s->endpoint = s->cur_endpoint;
s->conf = conf;
if (conf != NULL && conf->max_wait > 0)
g_max_wait = conf->max_wait;
s->sw = sw;
s->model = s->cur_model;
if (user != NULL && *user != '\0')
@@ -2767,6 +2813,11 @@ sp_ui_run(struct sp_agent *ag, const char *endpoint, const char *model,
ui_shell(&s, ag, input + 1);
continue;
}
/* after a stopped wait (or any stopped turn): go on */
if (strcmp(input, "/resume") == 0)
snprintf(input, sizeof(input), "Continue with the task "
"you were working on. Do not repeat work that is "
"already done.");
if (input[0] == '/' && input[1] != '\0' &&
ui_slash(&s, ag, host, input, sizeof(input)))
continue;
+48
View File
@@ -0,0 +1,48 @@
# fake OpenAI endpoint: the first request is refused with 429 and
# Retry-After: 2, every later one is answered. argv: port, request log;
# a third argument 'always' refuses every request (a provider at its limit).
import http.server, json, sys
hits = [0]
class H(http.server.BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_POST(self):
n = int(self.headers.get("Content-Length", 0))
req = json.loads(self.rfile.read(n))
hits[0] += 1
with open(sys.argv[2], "a") as f:
f.write("request %d\n" % hits[0])
if hits[0] == 1 or (len(sys.argv) > 3 and sys.argv[3] == "always"):
b = b'{"error":{"message":"rate limit reached"}}'
self.send_response(429)
self.send_header("Retry-After", "300" if len(sys.argv) > 3 else "2")
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
return
text = "weiter gemacht"
if req.get("stream"):
chunks = [{"choices": [{"delta": {"content": text}}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]}]
b = ("".join("data: " + json.dumps(c) + "\n\n" for c in chunks)
+ "data: [DONE]\n\n").encode()
ctype = "text/event-stream"
else:
b = json.dumps({"id": "f", "choices": [{"index": 0, "message": {
"role": "assistant", "content": text},
"finish_reason": "stop"}],
"usage": {"prompt_tokens": 1, "completion_tokens": 1}}).encode()
ctype = "application/json"
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
+44
View File
@@ -187,6 +187,50 @@ main(void)
CHECK(strstr(err.p, "status 500") != NULL);
sp_mock_free(&m);
/*
* 10. max_steps counts tool rounds, not requests: a turn that spends
* its whole round budget and then answers must still answer. The
* shape is the one from session sess-1794213769-672784 (2026-11-09
* 08:45:38): eight requests, every one of them a tool round, no
* answer - it died on "step limit (8)". Eight rounds leave the
* ninth request for the answer.
*/
sp_buf_clear(&err);
CHECK(sp_mock_init(&m) == 0);
CHECK(sp_mock_push(&m, 200, "tool echo r1") == 0);
CHECK(sp_mock_push(&m, 200, "tool echo r2") == 0);
CHECK(sp_mock_push(&m, 200, "tool echo r3") == 0);
CHECK(sp_mock_push(&m, 200, "tool echo r4") == 0);
CHECK(sp_mock_push(&m, 200, "tool echo r5") == 0);
CHECK(sp_mock_push(&m, 200, "tool echo r6") == 0);
CHECK(sp_mock_push(&m, 200, "tool echo r7") == 0);
CHECK(sp_mock_push(&m, 200, "tool echo r8") == 0);
CHECK(sp_mock_push(&m, 200, "answer done") == 0);
CHECK(run_turn(&m, &r, "eight rounds", 1, 8, 0, &answer, &err, &st) == 0);
CHECK(strcmp(answer.p, "done") == 0);
CHECK(st.tool_calls == 8);
CHECK(m.requests == 9);
CHECK(st.steps == 9);
sp_mock_free(&m);
/*
* 11. one tool round more than the budget is still refused, and the
* refused round does not run: the last observation in the request
* is round two's, not round three's.
*/
sp_buf_clear(&err);
CHECK(sp_mock_init(&m) == 0);
CHECK(sp_mock_push(&m, 200, "tool echo a") == 0);
CHECK(sp_mock_push(&m, 200, "tool echo b") == 0);
CHECK(sp_mock_push(&m, 200, "tool echo c") == 0);
CHECK(run_turn(&m, &r, "too many rounds", 1, 2, 0, &answer, &err, &st) != 0);
CHECK(strstr(err.p, "step limit") != NULL);
CHECK(st.tool_calls == 2);
CHECK(m.requests == 3);
CHECK(strstr(m.last_request.p, "observe echo b") != NULL);
CHECK(strstr(m.last_request.p, "observe echo c") == NULL);
sp_mock_free(&m);
sp_buf_free(&answer);
sp_buf_free(&err);
sp_registry_free(&r);
+120
View File
@@ -0,0 +1,120 @@
/*
* splinter -- the block syntax of the config file.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "splinter.h"
#include "config.h"
static int failures;
#define CHECK(cond) do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
failures++; \
} \
} while (0)
static int
load(const char *text, struct sp_config *c, struct sp_buf *err)
{
char path[] = "/var/tmp/splinter-cb-XXXXXX";
int fd = mkstemp(path), rc;
ssize_t w;
if (fd < 0)
return -2;
w = write(fd, text, strlen(text));
(void)w;
close(fd);
sp_config_init(c);
rc = sp_config_load(c, path, err);
unlink(path);
return rc;
}
int
main(void)
{
struct sp_config *c = calloc(1, sizeof(*c));
struct sp_buf err;
sp_buf_init(&err);
setenv("CB_TOKEN", "sekrit", 1);
unsetenv("CB_UNSET");
CHECK(load(
"# a comment\n"
"core {\n"
" theme = Delphinium\n"
" steps = 40\n"
" autonomous = true\n"
" default = claude\n"
" plugins = [a.so, \"b c.so\"]\n"
" on_limit = wait\n"
" max_wait = 6h\n"
"}\n"
"telegram { allow = [1, 2] }\n"
"provider local {\n"
" about = \"the local one\"\n"
" endpoint = http://h:1/v1/chat/completions\n"
" model = m\n"
" tags = [local, code]\n"
" prio = 5\n"
" limit = 10/5h\n"
"}\n"
"provider claude-a {\n"
" kind = cli\n"
" cmd = \"claude -p\"\n"
" tags = [cli, big]\n"
" env { CLAUDE_CODE_OAUTH_TOKEN = \"${CB_TOKEN}\" OTHER = \"${CB_UNSET}\" }\n"
"}\n"
"provider hidden { endpoint = http://x/v1 model = z delegate = false }\n"
"pool claude { members = [claude-a, local] strategy = balance }\n",
c, &err) == 0);
if (err.len > 0) fprintf(stderr, "err: %s\n", err.p);
CHECK(strcmp(c->theme, "Delphinium") == 0);
CHECK(c->steps == 40);
CHECK(c->autonomous == 1);
CHECK(strcmp(c->default_id, "claude") == 0);
CHECK(c->nplugins == 2 && strcmp(c->plugins[1], "b c.so") == 0);
CHECK(c->max_wait == 6 * 3600);
CHECK(strcmp(c->telegram_allow, "1,2") == 0);
CHECK(c->ndelegates == 2);
CHECK(strcmp(c->delegate[0].id, "local") == 0);
CHECK(strcmp(c->delegate[0].about, "the local one") == 0);
CHECK(strcmp(c->delegate[0].tags, "local,code") == 0);
CHECK(c->delegate[0].req_limit == 10 && c->delegate[0].req_window == 18000);
CHECK(c->delegate[1].nenv == 1);
CHECK(strstr(c->delegate[1].env[0], "=sekrit") != NULL);
CHECK(strcmp(c->delegate[1].kind, "cli") == 0);
CHECK(c->npools == 1 && c->pool[0].nmembers == 2);
CHECK(strcmp(c->pool[0].strategy, "balance") == 0);
/* errors name the line that was written */
sp_buf_clear(&err);
CHECK(load("core {\n steps = 1\n bogus_key = 2\n}\n", c, &err) != 0);
CHECK(strstr(err.p, ":3:") != NULL && strstr(err.p, "bogus_key") != NULL);
sp_buf_clear(&err);
CHECK(load("provider x {\n nope = 1\n}\n", c, &err) != 0);
CHECK(strstr(err.p, ":2:") != NULL && strstr(err.p, "nope") != NULL);
sp_buf_clear(&err);
CHECK(load("core {\n steps = 1\n", c, &err) != 0);
CHECK(strstr(err.p, "closing }") != NULL);
sp_buf_clear(&err);
CHECK(load("pool p { strategy = balance }\n", c, &err) != 0);
sp_buf_clear(&err);
CHECK(load("provider p { about = \"a|b\" }\n", c, &err) != 0);
/* the flat form still loads */
sp_buf_clear(&err);
CHECK(load("model = m\nsteps = 7\n", c, &err) == 0 && c->steps == 7);
free(c);
if (failures == 0)
puts("test_confblock: ok");
return failures != 0;
}
+67
View File
@@ -38,6 +38,72 @@ add(struct sp_config *c, const char *id, const char *about, const char *tags)
snprintf(d->model, sizeof(d->model), "m");
}
/*
* The child of a cli delegate has to find plugins/cli/cli.so also when the
* binary was installed away from the tree. Before this, the path was
* dirname(self)/plugins/... and nothing else: an installed splinter found no
* plugin, registered no 'cli' transport, and its exit 2 was reported as the
* delegate's.
*/
static void
test_cli_plugin_path(void)
{
char root[512], dir[1024], tree[700], inst[700], got[700];
char expect[1024];
const char *tmp = getenv("TMPDIR");
FILE *f;
snprintf(root, sizeof(root), "%s/splinter-delegate-XXXXXX",
tmp != NULL && *tmp != '\0' ? tmp : "/var/tmp");
CHECK(mkdtemp(root) != NULL);
snprintf(dir, sizeof(dir), "mkdir -p '%s/bin'", root);
CHECK(system(dir) == 0);
snprintf(dir, sizeof(dir), "mkdir -p '%s/lib/splinter/plugins/cli'", root);
CHECK(system(dir) == 0);
snprintf(dir, sizeof(dir), "mkdir -p '%s/bin/plugins/cli'", root);
CHECK(system(dir) == 0);
snprintf(tree, sizeof(tree), "%s/bin/plugins/cli/cli.so", root);
snprintf(inst, sizeof(inst), "%s/lib/splinter/plugins/cli/cli.so", root);
snprintf(dir, sizeof(dir), "%s/bin/splinter", root);
(void)unsetenv("SPLINTER_CLI_PLUGIN");
/* installed layout: the sibling of the binary is not there */
f = fopen(inst, "w");
CHECK(f != NULL);
if (f != NULL)
fclose(f);
sp_delegate_cli_plugin(dir, got, sizeof(got));
snprintf(expect, sizeof(expect), "%s/bin/../lib/splinter/plugins/cli/cli.so",
root);
CHECK(strcmp(got, expect) == 0);
/* running from the tree: the sibling wins over the installed layout */
f = fopen(tree, "w");
CHECK(f != NULL);
if (f != NULL)
fclose(f);
sp_delegate_cli_plugin(dir, got, sizeof(got));
CHECK(strcmp(got, tree) == 0);
/* an explicit path is used as given, existing or not */
(void)setenv("SPLINTER_CLI_PLUGIN", "/explicit/cli.so", 1);
sp_delegate_cli_plugin(dir, got, sizeof(got));
CHECK(strcmp(got, "/explicit/cli.so") == 0);
(void)unsetenv("SPLINTER_CLI_PLUGIN");
/* nothing found: the answer still names a cli plugin, so the child's
* own error points at a place one can put it in (or at the build tree
* this binary was compiled in) */
(void)unlink(tree);
(void)unlink(inst);
sp_delegate_cli_plugin(dir, got, sizeof(got));
CHECK(got[0] != '\0');
CHECK(strstr(got, "/plugins/cli/cli.so") != NULL);
snprintf(dir, sizeof(dir), "rm -rf '%s'", root);
(void)system(dir);
}
int
main(void)
{
@@ -45,6 +111,7 @@ main(void)
char id[64], why[192];
int score;
test_cli_plugin_path();
memset(&c, 0, sizeof(c));
add(&c, "coder", "C99, POSIX, kennt den Quellbaum", "code,c99,review");
add(&c, "quick", "kurze Antworten, Chat", "chat,cheap,summary");
+49
View File
@@ -0,0 +1,49 @@
#!/bin/sh
#
# splinter -- a usage limit is waited out, not reported as a failure.
#
# The fake model refuses the first request with 429 and Retry-After: 2. The
# run must say when it goes on, ask again and print the answer; with
# on_limit = fail it must fail instead.
set -u
cd "$(dirname "$0")/.." || exit 1
D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-lw-XXXXXX") || exit 1
P=$((20000 + $$ % 30000))
trap 'kill $F 2>/dev/null; rm -rf "$D"' EXIT
fails=0
check() { d=$1; shift; if "$@"; then :; else echo "FAIL $d"; fails=$((fails + 1)); fi; }
mkdir -p "$D/home"
python3 -I tests/fake_openai_limit.py "$P" "$D/req.log" &
F=$!
for i in $(seq 1 50); do
curl -s -o /dev/null "http://127.0.0.1:$P/x" && break
sleep 0.2
done
HOME="$D/home" SPLINTER_USAGE_DIR="$D/usage" SPLINTER_COOLDOWN_DIR="$D/cd" \
./splinter --no-config --no-stream --endpoint "http://127.0.0.1:$P/v1/chat/completions" \
--model m -p "hallo" </dev/null > "$D/out.txt" 2> "$D/err.txt"
check "the answer arrives after the wait" grep -q 'weiter gemacht' "$D/out.txt"
check "it said when it goes on" grep -q 'usage limit reached' "$D/err.txt"
check "the request was repeated" test "$(grep -c '^request' "$D/req.log")" -ge 2
# with on_limit = fail the first refusal ends the run
rm -f "$D/req.log" "$D/cd"/*
kill $F 2>/dev/null; wait $F 2>/dev/null
python3 -I tests/fake_openai_limit.py "$P" "$D/req.log" &
F=$!
for i in $(seq 1 50); do
curl -s -o /dev/null "http://127.0.0.1:$P/x" && break
sleep 0.2
done
printf 'endpoint = http://127.0.0.1:%s/v1/chat/completions\nmodel = m\non_limit = fail\n' "$P" > "$D/home/splinter.conf"
HOME="$D/home" SPLINTER_USAGE_DIR="$D/usage" SPLINTER_COOLDOWN_DIR="$D/cd" \
./splinter --config "$D/home/splinter.conf" --no-stream -p "hallo" \
</dev/null > "$D/out2.txt" 2> "$D/err2.txt"
check "on_limit = fail does not wait" test ! -s "$D/out2.txt"
check "on_limit = fail says why" grep -q 'status 429' "$D/err2.txt"
if [ "$fails" -eq 0 ]; then echo "test_limit_wait: ok"; exit 0; fi
cat "$D/err.txt" "$D/err2.txt"
exit 1
+67
View File
@@ -0,0 +1,67 @@
#!/bin/sh
#
# splinter -- pools, -m and --model-list.
#
# Two fake providers in a failover pool: the first refuses everything with 429,
# the second answers. The run must end up on the second without waiting.
set -u
cd "$(dirname "$0")/.." || exit 1
D=$(mktemp -d "${TMPDIR:-/var/tmp}/splinter-pool-XXXXXX") || exit 1
PA=$((20000 + $$ % 20000)); PB=$((PA + 1))
trap 'kill $FA $FB 2>/dev/null; rm -rf "$D"' EXIT
fails=0
check() { d=$1; shift; if "$@"; then :; else echo "FAIL $d"; fails=$((fails + 1)); fi; }
mkdir -p "$D/home"
python3 -I tests/fake_openai_limit.py "$PA" "$D/a.log" always &
FA=$!
python3 -I tests/fake_openai_limit.py "$PB" "$D/b.log" &
FB=$!
# B refuses its first request too: make it answer at once by priming it
for p in $PA $PB; do
for i in $(seq 1 50); do
curl -s -o /dev/null "http://127.0.0.1:$p/x" && break
sleep 0.2
done
done
curl -s -o /dev/null -X POST -d '{}' "http://127.0.0.1:$PB/prime"
cat > "$D/home/splinter.conf" <<CONF
core { default = duo }
provider first {
endpoint = http://127.0.0.1:$PA/v1/chat/completions
model = ma
tags = [t]
}
provider second {
endpoint = http://127.0.0.1:$PB/v1/chat/completions
model = mb
tags = [t]
}
pool duo { members = [first, second] strategy = failover }
CONF
export HOME="$D/home" SPLINTER_USAGE_DIR="$D/usage" SPLINTER_COOLDOWN_DIR="$D/cd"
# the model list names pools and providers
./splinter --config "$D/home/splinter.conf" --model-list --no-probe </dev/null > "$D/list.txt" 2>&1
check "the list names the pool" grep -q '^duo .*pool, failover: first second' "$D/list.txt"
check "the list names a provider" grep -q '^second ' "$D/list.txt"
check "the list names the default" grep -q '^# default: duo' "$D/list.txt"
# -m picks a provider, provider/model overrides the model, unknown is refused
./splinter --config "$D/home/splinter.conf" -m second --no-stream -p hallo </dev/null > "$D/o1.txt" 2>&1
check "-m second reaches second" grep -q 'weiter gemacht' "$D/o1.txt"
check "-m second did not touch first" test ! -s "$D/a.log"
./splinter --config "$D/home/splinter.conf" -m nope -p x </dev/null > "$D/o2.txt" 2>&1
check "-m with an unknown name is refused" grep -q "no provider, pool or model 'nope'" "$D/o2.txt"
# the pool's first member is at its limit: the run moves on to the second
rm -f "$D/b.log"; rm -rf "$D/cd" "$D/usage"
./splinter --config "$D/home/splinter.conf" --no-stream -p hallo </dev/null > "$D/o3.txt" 2>&1
check "the pool run ends on the second provider" grep -q 'weiter gemacht' "$D/o3.txt"
check "the first provider was asked" test -s "$D/a.log"
check "the second provider was asked" test -s "$D/b.log"
if [ "$fails" -eq 0 ]; then echo "test_pools: ok"; exit 0; fi
cat "$D/o1.txt" "$D/o3.txt"
exit 1