Two things were wrong with .splinter-swarm.sock. Every chat bound it, wanted or not, so a shared working directory collected a leftover from every session and the next start that found one sat on "[swarm locked]" because nobody answered on it. And the master removed the file on its way out even when a member was still running, which left that member on a path that was gone. Now the fleet is opt-in. Without --swarm nothing binds or joins the file; with it, the file lives exactly as long as the fleet does, whatever order the members leave in. - main.c: --swarm is a flag; eo.swarm requires it (plus --chat, no --serve, no --daemon, no A2A/MCP/delegate). - swarm.c: join_or_bind() is the one place that decides master or slave, used at startup and again on takeover. A slave whose master says "bye" or whose connection just ends (SIGKILL) takes the fleet over: bind, or join whoever was faster. A leftover file with no listener is removed there and rebound, because a refused connect is proof nobody answers. - master_close() removes the file only when it is the last member. The peer check reads the sockets instead of trusting the cached flag: a peer that exited is only visible as EOF on read. - swarm_emergency_unlink() (SIGTERM/SIGHUP) keeps the file while a peer is live. A handler may not walk the peer table, so the master keeps a sig_atomic_t count of live peers for it. Tests, all against the real binary and the real signal path: - test_swarm.c: master leaves first, survivor takes over and the file stays; hard-killed master (EOF, no bye), survivor cleans the leftover up; the signal cleanup alone leaves the file for a live member; an unowned file is still never deleted. Mutation-checked: forcing master_close to always unlink, and dropping the peer count from swarm_emergency_unlink, each turn the suite red. - test_swarm_socket.sh (new, in make check): through tmux, --chat without --swarm creates no file at all; --chat --swarm creates one that accepts a member and is gone after Ctrl-D and after SIGTERM; two members share one file that outlives the master and goes with the last one; a SIGTERM-killed master does not take the fleet from the survivor. Mutation-checked: making the fleet unconditional (the old eo.swarm line) turns it red. make check: all tests passed. check_asan.sh: all 46 test binaries clean.
1684 lines
50 KiB
C
1684 lines
50 KiB
C
/*
|
|
* splinter -- command line entry point.
|
|
*
|
|
* Copyright (c) 2026 Konrad Lother
|
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
*
|
|
* Exit statuses: 0 the turn produced an answer, 1 the turn failed, 2 usage or
|
|
* configuration error, 3 the environment could not be set up (session dir).
|
|
*/
|
|
#include <errno.h>
|
|
#include <fcntl.h>
|
|
#include <pthread.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <strings.h>
|
|
#include <sys/file.h>
|
|
#include <time.h>
|
|
#include <unistd.h>
|
|
|
|
#include "splinter.h"
|
|
#include "splinter_engine.h"
|
|
#include "config.h"
|
|
#include "i18n.h"
|
|
#include "log.h"
|
|
#include "skills.h"
|
|
#include "memory.h"
|
|
#include "prompt.h"
|
|
#include "providers.h"
|
|
#include "usage.h"
|
|
#include "agents.h"
|
|
#include "folder.h"
|
|
#include "mcpserver.h"
|
|
#include "a2aserver.h"
|
|
#include "openai_server.h"
|
|
#include "interview.h"
|
|
#include "ack.h"
|
|
#include "splinter_plugin.h"
|
|
#include "theme.h"
|
|
#include "ui.h"
|
|
#include "ui_backend.h"
|
|
#include "protocol.h"
|
|
|
|
static void
|
|
usage(FILE *f)
|
|
{
|
|
fprintf(f,
|
|
"usage: splinter [options]\n\n"
|
|
" -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"
|
|
" --agent NAME start as that agent profile (build, plan, or a\n"
|
|
" file in ~/.splinter/agents, .agents/); Tab\n"
|
|
" switches in the chat\n"
|
|
" --agent-list list the agent profiles and exit\n"
|
|
" --doctor check every provider: key, reachability via\n"
|
|
" its model list (never spends tokens)\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"
|
|
" per line (no network; for tests and demos)\n"
|
|
" --config PATH read this config file instead of the default\n"
|
|
" --no-config ignore the config file entirely\n"
|
|
" --no-stream one-shot mode: wait for the whole reply\n"
|
|
" instead of printing it as it arrives\n"
|
|
" --init-config write a commented example config and exit\n"
|
|
" --plugin PATH load a plugin (.so) before the first turn\n"
|
|
" --transport NAME use a transport a plugin provides (\"cli\")\n"
|
|
" --kind NAME vendor shape of --endpoint: openai (default)\n"
|
|
" or anthropic\n"
|
|
" --chat interactive curses UI instead of one turn\n"
|
|
" --swarm join the local fleet: share this directory's\n"
|
|
" instances over .splinter-swarm.sock (needs\n"
|
|
" --chat; the file exists only while one runs)\n"
|
|
" --serve serve the line protocol on a Unix socket\n"
|
|
" --attach run the curses UI as a client of --serve\n"
|
|
" --socket PATH socket for --serve/--attach (default\n"
|
|
" ~/.splinter/splinter.sock)\n"
|
|
" --theme NAME UI theme: light (default), Xresources or a CDE\n"
|
|
" palette, e.g. Default, Delphinium, MakroSlate\n"
|
|
" --list-themes print the palette names and exit\n"
|
|
" --resume load the session's history into the conversation\n"
|
|
" --choose TEXT print which delegate fits TEXT, then exit\n"
|
|
" --delegate ID run that delegate with -p TEXT, print its "
|
|
"observation, exit\n"
|
|
" --daemon answer on Telegram until SIGINT\n"
|
|
" --notify TEXT send TEXT to the Telegram status chat and exit\n"
|
|
" (\"-\" reads stdin)\n"
|
|
" --no-stdin ignore data on standard input\n"
|
|
" -c, --continue continue the last session started in this "
|
|
"directory\n"
|
|
" --claude continue the newest claude session of this\n"
|
|
" directory (also --opencode, --hermes, or\n"
|
|
" --from=NAME)\n"
|
|
" --interview let the model interview you; writes "
|
|
"USER.txt\n"
|
|
" --mcp-server-listen IP serve MCP on IP (tools of this "
|
|
"registry);\n"
|
|
" beyond 127.x it needs "
|
|
"SPLINTER_MCP_TOKEN\n"
|
|
" --mcp-listen-port N MCP port, default 8098\n"
|
|
" --a2a-server-listen IP serve A2A on IP (JSON-RPC, agent "
|
|
"card);\n"
|
|
" beyond 127.x it needs "
|
|
"SPLINTER_A2A_SERVER_TOKEN\n"
|
|
" --a2a-listen-port N A2A port, default 8099\n"
|
|
" --openai-listen IP serve an OpenAI-compatible\n"
|
|
" /v1/chat/completions with local gw_\n"
|
|
" tools and caller tools passed through\n"
|
|
" --openai-listen-port N gateway port, default 8097\n"
|
|
" --autonomous run mutating tools without asking\n"
|
|
" --steps N tool rounds per turn (default 150)\n"
|
|
" --session DIR session directory (default ~/.splinter)\n"
|
|
" --session-id ID session id (default sess-<time>-<pid>)\n"
|
|
" --max-bytes N request budget in bytes (0 = no limit)\n"
|
|
" -V, --version print the version\n"
|
|
" -h, --help this text\n\n"
|
|
"Exactly one transport is required. With none, splinter refuses to\n"
|
|
"start rather than pretend it can talk to a model.\n");
|
|
}
|
|
|
|
static int
|
|
need_value(int argc, int i, const char *flag)
|
|
{
|
|
if (i + 1 >= argc) {
|
|
fprintf(stderr, "splinter: %s needs a value\n", flag);
|
|
return 0;
|
|
}
|
|
return 1;
|
|
}
|
|
/* one-shot mode: print the answer as it arrives, no buffering */
|
|
/* bytes the transport streamed: if none, the answer still has to be printed */
|
|
static size_t streamed_bytes;
|
|
|
|
static void
|
|
stdout_stream(void *ctx, int kind, const char *text)
|
|
{
|
|
(void)ctx;
|
|
if (kind != SP_STREAM_TEXT || text == NULL)
|
|
return;
|
|
streamed_bytes += strlen(text);
|
|
fputs(text, stdout);
|
|
fflush(stdout);
|
|
}
|
|
|
|
|
|
/*
|
|
* Data on stdin becomes context.
|
|
*
|
|
* cat /etc/passwd | splinter "explain the file"
|
|
*
|
|
* The block is framed and labelled with its size, so the model can tell the
|
|
* operator's question from the bytes that came through a pipe. A binary input is
|
|
* reported as such instead of being sprayed into the conversation, and the size
|
|
* is capped - an accidental `cat /dev/zero` must not eat the budget.
|
|
*/
|
|
#define STDIN_LIMIT (192 * 1024)
|
|
|
|
static int
|
|
read_stdin_block(struct sp_buf *out, int *is_binary, size_t *raw_len)
|
|
{
|
|
char chunk[8192];
|
|
ssize_t got;
|
|
size_t total = 0;
|
|
int nul = 0;
|
|
|
|
*is_binary = 0;
|
|
*raw_len = 0;
|
|
for (;;) {
|
|
size_t i;
|
|
|
|
got = read(STDIN_FILENO, chunk, sizeof(chunk));
|
|
if (got < 0) {
|
|
if (errno == EINTR)
|
|
continue;
|
|
return -1;
|
|
}
|
|
if (got == 0)
|
|
break;
|
|
total += (size_t)got;
|
|
for (i = 0; i < (size_t)got; i++)
|
|
if (chunk[i] == '\0')
|
|
nul = 1;
|
|
if (out->len < STDIN_LIMIT)
|
|
(void)sp_buf_add(out, chunk, (size_t)got);
|
|
}
|
|
*is_binary = nul;
|
|
*raw_len = total;
|
|
return 0;
|
|
}
|
|
|
|
/*
|
|
* The gateway has nobody to stream to: it sends one finished message. The
|
|
* callback still matters, because without it the agent asks the transport for a
|
|
* plain reply - and a provider that only speaks SSE then answers with a stream
|
|
* the non-streaming reader cannot parse.
|
|
*/
|
|
static void
|
|
daemon_stream(void *ctx, int kind, const char *text)
|
|
{
|
|
(void)ctx;
|
|
(void)kind;
|
|
(void)text;
|
|
}
|
|
|
|
/* the longest wait for a usage limit in seconds, 0: the default of 12 h */
|
|
static long g_max_wait;
|
|
|
|
/* everything the command line can say */
|
|
struct opts {
|
|
const char *prompt, *endpoint, *script, *model, *key_env;
|
|
const char *sessdir, *sessid, *theme, *transport, *config_path;
|
|
const char *notify;
|
|
const char *kind; /* "anthropic" when -m chose such a provider */
|
|
const char *choose, *mcp_ip;
|
|
const char *delegate;
|
|
const char *plugins[32];
|
|
size_t nplugins;
|
|
int init_config, no_config, list_themes, chat, resume;
|
|
int daemon, no_stdin, continue_here, interview;
|
|
const char *from_foreign; /* --claude/--opencode/--hermes */
|
|
int no_stream;
|
|
const char *select;
|
|
int model_list, no_probe, agent_list, doctor, live;
|
|
const char *agent;
|
|
int acklist, ack_id, ack_yes, mcp_port;
|
|
const char *a2a_ip;
|
|
int a2a_port;
|
|
const char *openai_ip;
|
|
int openai_port;
|
|
int serve, attach;
|
|
const char *socket;
|
|
int swarm; /* --swarm: join the local fleet */
|
|
};
|
|
|
|
/*
|
|
* A TCP port from the command line.
|
|
*
|
|
* atoi() took anything: "--openai-listen-port abc" bound port 0 (a random
|
|
* port the operator was never told) and "-5" bound 65531. Both looked like a
|
|
* running server on a port nobody chose, which is worse than a refusal.
|
|
*/
|
|
static int
|
|
port_arg(const char *what, const char *s, int *out)
|
|
{
|
|
char *end = NULL;
|
|
long v;
|
|
|
|
errno = 0;
|
|
v = strtol(s, &end, 10);
|
|
if (errno != 0 || end == s || *end != '\0' || v < 1 || v > 65535) {
|
|
fprintf(stderr, "splinter: %s wants a port between 1 and "
|
|
"65535, not '%s'\n", what, s);
|
|
return -1;
|
|
}
|
|
*out = (int)v;
|
|
return 0;
|
|
}
|
|
|
|
/* the yes/no word of --ack; -1 for anything else */
|
|
static int
|
|
ack_word(const char *w)
|
|
{
|
|
/* only a word that means yes is a yes: "nein" used to approve */
|
|
if (!strcmp(w, "yes") || !strcmp(w, "y") || !strcmp(w, "ok") ||
|
|
!strcmp(w, "ja"))
|
|
return 1;
|
|
if (!strcmp(w, "no") || !strcmp(w, "n") || !strcmp(w, "nein"))
|
|
return 0;
|
|
return -1;
|
|
}
|
|
static int
|
|
parse_args(int argc, char **argv, struct opts *o, struct sp_agent_config *cfg)
|
|
{
|
|
int i;
|
|
|
|
#define VALUE(dst) do { \
|
|
if (!need_value(argc, i, argv[i])) \
|
|
return 2; \
|
|
(dst) = argv[++i]; \
|
|
} while (0)
|
|
|
|
for (i = 1; i < argc; i++) {
|
|
const char *a = argv[i];
|
|
|
|
if (!strcmp(a, "-h") || !strcmp(a, "--help")) {
|
|
usage(stdout);
|
|
return 0;
|
|
} else if (!strcmp(a, "-V") || !strcmp(a, "--version")) {
|
|
/*
|
|
* The release number barely moves; the build stamp is what
|
|
* tells an installed binary from the tree that was built
|
|
* after it.
|
|
*/
|
|
if (sp_build_rev != NULL && sp_build_rev[0] != '\0')
|
|
printf("splinter %s (built %s, %s)\n",
|
|
SP_VERSION, sp_build_time, sp_build_rev);
|
|
else
|
|
printf("splinter %s (built %s)\n",
|
|
SP_VERSION, sp_build_time);
|
|
return 0;
|
|
} else if (!strcmp(a, "-p") || !strcmp(a, "--prompt"))
|
|
VALUE(o->prompt);
|
|
else if (!strcmp(a, "--endpoint"))
|
|
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, "--agent"))
|
|
VALUE(o->agent);
|
|
else if (!strcmp(a, "--doctor"))
|
|
o->doctor = 1;
|
|
else if (!strcmp(a, "--live"))
|
|
o->live = 1;
|
|
else if (!strcmp(a, "--agent-list"))
|
|
o->agent_list = 1;
|
|
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"))
|
|
o->init_config = 1;
|
|
else if (!strcmp(a, "--no-config"))
|
|
o->no_config = 1;
|
|
else if (!strcmp(a, "--no-stream"))
|
|
o->no_stream = 1;
|
|
else if (!strcmp(a, "--config"))
|
|
VALUE(o->config_path);
|
|
else if (!strcmp(a, "--transport"))
|
|
VALUE(o->transport);
|
|
else if (!strcmp(a, "--kind"))
|
|
VALUE(o->kind);
|
|
else if (!strcmp(a, "--script"))
|
|
VALUE(o->script);
|
|
else if (!strcmp(a, "--plugin")) {
|
|
if (!need_value(argc, i, a))
|
|
return 2;
|
|
if (o->nplugins == 32) {
|
|
fprintf(stderr, "splinter: at most 32 plugins\n");
|
|
return 2;
|
|
}
|
|
o->plugins[o->nplugins++] = argv[++i];
|
|
} else if (!strcmp(a, "--chat"))
|
|
o->chat = 1;
|
|
else if (!strcmp(a, "--swarm"))
|
|
o->swarm = 1;
|
|
else if (!strcmp(a, "--serve"))
|
|
o->serve = 1;
|
|
else if (!strcmp(a, "--attach"))
|
|
o->attach = 1;
|
|
else if (!strcmp(a, "--socket"))
|
|
VALUE(o->socket);
|
|
else if (!strcmp(a, "--choose")) {
|
|
if (i + 1 >= argc) {
|
|
fprintf(stderr, "splinter: --choose needs text\n");
|
|
return 2;
|
|
}
|
|
o->choose = argv[++i];
|
|
} else if (!strcmp(a, "--delegate")) {
|
|
if (i + 1 >= argc) {
|
|
fprintf(stderr, "splinter: --delegate needs an "
|
|
"id\n");
|
|
return 2;
|
|
}
|
|
o->delegate = argv[++i];
|
|
} else if (!strcmp(a, "--daemon"))
|
|
o->daemon = 1;
|
|
else if (!strcmp(a, "--notify")) {
|
|
if (i + 1 >= argc) {
|
|
fprintf(stderr, "splinter: --notify needs text "
|
|
"(or - for stdin)\n");
|
|
return 2;
|
|
}
|
|
o->notify = argv[++i];
|
|
} else if (!strcmp(a, "--ack") && i + 2 < argc) {
|
|
o->ack_id = atoi(argv[++i]);
|
|
o->ack_yes = ack_word(argv[++i]);
|
|
if (o->ack_yes < 0) {
|
|
fprintf(stderr, "splinter: --ack wants yes or no, "
|
|
"not '%s'\n", argv[i]);
|
|
return 2;
|
|
}
|
|
if (o->ack_id <= 0) {
|
|
fprintf(stderr, "splinter: --ack wants a request "
|
|
"id\n");
|
|
return 2;
|
|
}
|
|
} else if (!strcmp(a, "--ack-list"))
|
|
o->acklist = 1;
|
|
else if (!strcmp(a, "--interview"))
|
|
o->interview = 1;
|
|
else if (!strcmp(a, "--mcp-server-listen")) {
|
|
if (i + 1 >= argc) {
|
|
fprintf(stderr, "splinter: --mcp-server-listen "
|
|
"needs an address\n");
|
|
return 2;
|
|
}
|
|
o->mcp_ip = argv[++i];
|
|
} else if (!strcmp(a, "--mcp-listen-port")) {
|
|
if (i + 1 >= argc) {
|
|
fprintf(stderr, "splinter: --mcp-listen-port needs "
|
|
"a number\n");
|
|
return 2;
|
|
}
|
|
if (port_arg("--mcp-listen-port", argv[++i],
|
|
&o->mcp_port) != 0)
|
|
return 2;
|
|
} else if (!strcmp(a, "--a2a-server-listen")) {
|
|
if (i + 1 >= argc) {
|
|
fprintf(stderr, "splinter: --a2a-server-listen "
|
|
"needs an address\n");
|
|
return 2;
|
|
}
|
|
o->a2a_ip = argv[++i];
|
|
} else if (!strcmp(a, "--openai-listen")) {
|
|
if (i + 1 >= argc) {
|
|
fprintf(stderr, "splinter: --openai-listen needs "
|
|
"an address\n");
|
|
return 2;
|
|
}
|
|
o->openai_ip = argv[++i];
|
|
} else if (!strcmp(a, "--openai-listen-port")) {
|
|
if (i + 1 >= argc) {
|
|
fprintf(stderr, "splinter: --openai-listen-port "
|
|
"needs a number\n");
|
|
return 2;
|
|
}
|
|
if (port_arg("--openai-listen-port", argv[++i],
|
|
&o->openai_port) != 0)
|
|
return 2;
|
|
} else if (!strcmp(a, "--a2a-listen-port")) {
|
|
if (i + 1 >= argc) {
|
|
fprintf(stderr, "splinter: --a2a-listen-port needs "
|
|
"a number\n");
|
|
return 2;
|
|
}
|
|
if (port_arg("--a2a-listen-port", argv[++i],
|
|
&o->a2a_port) != 0)
|
|
return 2;
|
|
} else if (!strcmp(a, "-c") || !strcmp(a, "--continue"))
|
|
o->continue_here = 1;
|
|
/*
|
|
* --claude / --opencode / --hermes: continue the newest session
|
|
* of another tool that ran in this directory. Claude Code stops
|
|
* at its limit; the work is still in its store, so the way out
|
|
* is to import it and carry on here.
|
|
*/
|
|
else if (!strcmp(a, "--claude") || !strcmp(a, "--opencode") ||
|
|
!strcmp(a, "--hermes"))
|
|
o->from_foreign = a + 2;
|
|
else if (!strncmp(a, "--from=", 7))
|
|
o->from_foreign = a + 7;
|
|
else if (!strcmp(a, "--resume"))
|
|
o->resume = 1;
|
|
else if (!strcmp(a, "--autonomous"))
|
|
cfg->autonomous = 1;
|
|
else if (!strcmp(a, "--steps")) {
|
|
if (!need_value(argc, i, a))
|
|
return 2;
|
|
cfg->max_steps = (size_t)strtoul(argv[++i], NULL, 10);
|
|
} else if (!strcmp(a, "--max-bytes")) {
|
|
if (!need_value(argc, i, a))
|
|
return 2;
|
|
cfg->max_bytes = (size_t)strtoul(argv[++i], NULL, 10);
|
|
} else if (!strcmp(a, "--theme"))
|
|
VALUE(o->theme);
|
|
else if (!strcmp(a, "--list-themes"))
|
|
o->list_themes = 1;
|
|
else if (!strcmp(a, "--session"))
|
|
VALUE(o->sessdir);
|
|
else if (!strcmp(a, "--session-id"))
|
|
VALUE(o->sessid);
|
|
else if (a[0] != '-') {
|
|
/* a bare word is the prompt: splinter "explain this" */
|
|
if (o->prompt != NULL) {
|
|
fprintf(stderr, "splinter: two prompts given\n");
|
|
return 2;
|
|
}
|
|
o->prompt = a;
|
|
} else if (!strcmp(a, "--no-stdin"))
|
|
o->no_stdin = 1;
|
|
else {
|
|
fprintf(stderr, "splinter: unknown option %s\n", a);
|
|
return 2;
|
|
}
|
|
}
|
|
#undef VALUE
|
|
return -1;
|
|
}
|
|
|
|
/*
|
|
* Piped input is context, not a prompt. Only when the caller gave no prompt at
|
|
* all does the input become the prompt.
|
|
*/
|
|
static void
|
|
take_stdin(struct opts *o)
|
|
{
|
|
static char combined[STDIN_LIMIT + 4096];
|
|
struct sp_buf intake;
|
|
int is_binary = 0;
|
|
size_t raw = 0;
|
|
|
|
/* the interview asks its questions on stdin: leave it alone */
|
|
if (o->no_stdin || o->chat || o->attach || o->daemon ||
|
|
o->interview ||
|
|
isatty(STDIN_FILENO) || sp_buf_init(&intake) != 0)
|
|
return;
|
|
if (read_stdin_block(&intake, &is_binary, &raw) != 0 || raw == 0) {
|
|
sp_buf_free(&intake);
|
|
return;
|
|
}
|
|
if (is_binary)
|
|
snprintf(combined, sizeof(combined), "%s\n\n[stdin: %zu bytes of "
|
|
"binary data, not shown]\n", o->prompt != NULL ? o->prompt :
|
|
"", raw);
|
|
else if (o->prompt != NULL)
|
|
snprintf(combined, sizeof(combined),
|
|
"%s\n\n[stdin: %zu bytes]\n%s%s\n[/stdin]\n", o->prompt, raw,
|
|
intake.p != NULL ? intake.p : "",
|
|
raw > STDIN_LIMIT ? "\n[truncated]" : "");
|
|
else
|
|
snprintf(combined, sizeof(combined),
|
|
"[stdin: %zu bytes]\n%s%s\n[/stdin]\n", raw,
|
|
intake.p != NULL ? intake.p : "",
|
|
raw > STDIN_LIMIT ? "\n[truncated]" : "");
|
|
o->prompt = combined;
|
|
sp_buf_free(&intake);
|
|
}
|
|
|
|
/*
|
|
* The configuration file: defaults, the command line still wins. Returns -1
|
|
* to go on, or the exit status (--init-config, a broken file).
|
|
*/
|
|
static int
|
|
load_config(struct opts *o, struct sp_config *conf, struct sp_agent_config *cfg,
|
|
struct sp_buf *err)
|
|
{
|
|
char cpath[512];
|
|
size_t k;
|
|
|
|
sp_config_init(conf);
|
|
if (o->config_path == NULL) {
|
|
if (sp_config_path(cpath, sizeof(cpath)) != 0)
|
|
cpath[0] = '\0';
|
|
} else
|
|
snprintf(cpath, sizeof(cpath), "%s", o->config_path);
|
|
|
|
if (o->init_config) {
|
|
/*
|
|
* Never over somebody's working config. This wrote over a live
|
|
* splinter.conf once, with 200 lines of hand-written providers in it:
|
|
* a starter file that lands in a temp name is still useful, and the
|
|
* operator decides what replaces what.
|
|
*/
|
|
if (access(cpath, F_OK) == 0) {
|
|
char alt[900];
|
|
|
|
snprintf(alt, sizeof(alt), "%s.example", cpath);
|
|
if (sp_config_write_example(alt, err) != 0) {
|
|
fprintf(stderr, "splinter: %s\n",
|
|
err->len > 0 ? err->p :
|
|
"cannot write the example config");
|
|
return 3;
|
|
}
|
|
printf("splinter: %s exists; wrote %s instead\n",
|
|
cpath, alt);
|
|
return 0;
|
|
}
|
|
sp_buf_clear(err);
|
|
if (sp_config_write_example(cpath, err) != 0) {
|
|
fprintf(stderr, "splinter: %s\n",
|
|
err->len > 0 ? err->p : "cannot write config");
|
|
return 3;
|
|
}
|
|
printf("splinter: wrote %s\n", cpath);
|
|
return 0;
|
|
}
|
|
if (o->no_config || cpath[0] == '\0')
|
|
return -1;
|
|
sp_buf_clear(err);
|
|
if (sp_config_load(conf, cpath, err) != 0) {
|
|
if (strstr(err->len > 0 ? err->p : "", "not found") != NULL)
|
|
return -1; /* no file is not an error */
|
|
fprintf(stderr, "splinter: %s\n", err->p);
|
|
return 2;
|
|
}
|
|
|
|
/*
|
|
* The config's main endpoint is not a choice made on the command line:
|
|
* copying it into 'o' here made apply_selection() believe --endpoint had
|
|
* been given, so a core default was ignored as soon as a main endpoint
|
|
* (or /model's 90-model.conf) existed. It is used below only when no
|
|
* default names a provider.
|
|
*/
|
|
if (o->model == NULL && conf->model[0] != '\0')
|
|
o->model = conf->model;
|
|
if (o->theme == NULL && conf->theme[0] != '\0')
|
|
o->theme = conf->theme;
|
|
if (o->transport == NULL && conf->transport[0] != '\0')
|
|
o->transport = conf->transport;
|
|
if (o->nplugins == 0)
|
|
for (k = 0; k < conf->nplugins && k < 16; k++)
|
|
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)
|
|
cfg->autonomous = conf->autonomous;
|
|
if (o->sessdir == NULL && conf->session_dir[0] != '\0')
|
|
o->sessdir = conf->session_dir;
|
|
if (cfg->system_prompt == NULL && conf->system_prompt[0] != '\0')
|
|
cfg->system_prompt = conf->system_prompt;
|
|
if (conf->key_env[0] != '\0')
|
|
o->key_env = conf->key_env;
|
|
if (conf->locale[0] != '\0')
|
|
setenv("SPLINTER_LOCALE", conf->locale, 1);
|
|
/* the cli transport reads its command from the environment */
|
|
if (conf->cli_cmd[0] != '\0')
|
|
setenv("SPLINTER_CLI_CMD", conf->cli_cmd, 0);
|
|
/* cli_env: what the file says the cli program sees, it wins */
|
|
sp_config_apply_env((const char (*)[SP_CONFIG_ENV_LEN])conf->cli_env,
|
|
conf->ncli_env);
|
|
/*
|
|
* Timeouts: local models can take minutes to produce a first token.
|
|
* Config sets the baseline; an explicitly exported env var still wins,
|
|
* so one run can override without editing the file.
|
|
*/
|
|
{
|
|
char tbuf[32];
|
|
|
|
if (conf->http_timeout > 0) {
|
|
snprintf(tbuf, sizeof(tbuf), "%ld", conf->http_timeout);
|
|
setenv("SPLINTER_HTTP_TIMEOUT", tbuf, 0);
|
|
}
|
|
if (conf->cli_timeout > 0) {
|
|
snprintf(tbuf, sizeof(tbuf), "%ld", conf->cli_timeout);
|
|
setenv("SPLINTER_CLI_TIMEOUT", tbuf, 0);
|
|
}
|
|
if (conf->delegate_timeout > 0) {
|
|
snprintf(tbuf, sizeof(tbuf), "%ld", conf->delegate_timeout);
|
|
setenv("SPLINTER_DELEGATE_TIMEOUT", tbuf, 0);
|
|
}
|
|
if (conf->run_timeout > 0) {
|
|
snprintf(tbuf, sizeof(tbuf), "%ld", conf->run_timeout);
|
|
setenv("SPLINTER_RUN_TIMEOUT", tbuf, 0);
|
|
}
|
|
}
|
|
/* a config means "this is my setup": start the chat */
|
|
if (o->prompt == NULL)
|
|
o->chat = 1;
|
|
return -1;
|
|
}
|
|
|
|
/*
|
|
* Every variable that holds a key is taken out of the 'run' tool's
|
|
* environment, so the model cannot print splinter's credentials. The numbered
|
|
* variants of the env providers (OLLAMA_KEY_2, ...) are prefixes.
|
|
*/
|
|
static void
|
|
hide_secrets(const struct opts *o, const struct sp_config *conf)
|
|
{
|
|
size_t k;
|
|
|
|
(void)sp_secret_env_add(o->key_env);
|
|
(void)sp_secret_env_add(conf->key_env);
|
|
(void)sp_secret_env_add("OLLAMA_KEY_*");
|
|
(void)sp_secret_env_add("CLAUDE_CODE_OAUTH_TOKEN_*");
|
|
for (k = 0; k < conf->ndelegates; k++)
|
|
(void)sp_secret_env_add(conf->delegate[k].key_env);
|
|
for (k = 0; k < conf->nexits; k++)
|
|
(void)sp_secret_env_add(conf->exit[k].key_env);
|
|
}
|
|
|
|
/* --choose: which delegate fits the text, and why */
|
|
static int
|
|
run_choose(const struct sp_config *conf, const char *text)
|
|
{
|
|
char id[64], why[192];
|
|
int score = 0;
|
|
|
|
if (conf->ndelegates == 0) {
|
|
fprintf(stderr, "splinter: no delegate configured\n");
|
|
return 2;
|
|
}
|
|
if (sp_delegate_choose(conf, text, NULL, id, sizeof(id), why,
|
|
sizeof(why), &score) != 0) {
|
|
fprintf(stderr, "splinter: no delegate matches\n");
|
|
return 1;
|
|
}
|
|
printf("%s\tscore=%d\tprio=%d\t%s\n", id, score,
|
|
sp_delegate_prio(conf, id), why);
|
|
return 0;
|
|
}
|
|
|
|
/*
|
|
* --delegate ID -p TEXT: run one named delegate without a model and print the
|
|
* observation. This is the diagnostic path for a delegate that fails: the
|
|
* transport's own message, the child's exit status and the task/job lines are
|
|
* all in that observation.
|
|
*/
|
|
static int
|
|
run_delegate_cli(const struct sp_registry *reg, const char *id,
|
|
const char *task)
|
|
{
|
|
const struct sp_tool *t = sp_registry_find(reg, "delegate");
|
|
struct sp_buf out, args;
|
|
int rc = 0;
|
|
|
|
if (t == NULL) {
|
|
fprintf(stderr, "splinter: the delegate tool is not "
|
|
"registered\n");
|
|
return 3;
|
|
}
|
|
if (sp_buf_init(&out) != 0 || sp_buf_init(&args) != 0)
|
|
return 3;
|
|
if (sp_buf_puts(&args, "{\"task\":\"") != 0 ||
|
|
sp_json_escape(&args, task) != 0 ||
|
|
sp_buf_puts(&args, "\",\"delegate\":\"") != 0 ||
|
|
sp_json_escape(&args, id) != 0 ||
|
|
sp_buf_puts(&args, "\"}") != 0) {
|
|
sp_buf_free(&out);
|
|
sp_buf_free(&args);
|
|
return 3;
|
|
}
|
|
if (t->run(args.p, &out, t->ctx) != 0)
|
|
rc = 1;
|
|
if (out.p != NULL && out.len > 0)
|
|
printf("%s\n", out.p);
|
|
sp_buf_free(&out);
|
|
sp_buf_free(&args);
|
|
return rc;
|
|
}
|
|
|
|
/* exactly one transport, and a reason to run at all; 0 or the exit status */
|
|
static int
|
|
check_usage(const struct opts *o)
|
|
{
|
|
/* these answer files or ask questions; none of them runs a model */
|
|
if (o->ack_id > 0 || o->acklist || o->interview)
|
|
return 0;
|
|
if ((o->endpoint != NULL) + (o->script != NULL) +
|
|
(o->transport != NULL) > 1) {
|
|
fprintf(stderr, "splinter: choose one transport\n");
|
|
return 2;
|
|
}
|
|
if (o->transport == NULL && o->endpoint == NULL && o->script == NULL &&
|
|
o->mcp_ip == NULL && o->delegate == NULL) {
|
|
fprintf(stderr, "splinter: no transport (--endpoint, --script or "
|
|
"--transport)\n");
|
|
return 2;
|
|
}
|
|
if (o->delegate != NULL && o->prompt == NULL) {
|
|
fprintf(stderr, "splinter: --delegate needs -p TEXT\n");
|
|
return 2;
|
|
}
|
|
if (o->prompt == NULL && !o->chat && !o->daemon && o->mcp_ip == NULL &&
|
|
o->a2a_ip == NULL && o->openai_ip == NULL && !o->serve) {
|
|
fprintf(stderr, "splinter: -p/--prompt is required unless you pass "
|
|
"--chat, --serve, --daemon, --mcp-server-listen, "
|
|
"--a2a-server-listen or --openai-listen\n");
|
|
return 2;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static int
|
|
program_found(const char *cmd)
|
|
{
|
|
char word[128], *path, *dir, *save = NULL;
|
|
const char *penv;
|
|
size_t n = strcspn(cmd, " \t");
|
|
|
|
if (n == 0 || n >= sizeof(word))
|
|
return 0;
|
|
memcpy(word, cmd, n);
|
|
word[n] = '\0';
|
|
if (strchr(word, '/') != NULL)
|
|
return access(word, X_OK) == 0;
|
|
/* one getenv: asking twice reads as if the second answer may differ */
|
|
penv = getenv("PATH");
|
|
path = penv != NULL ? strdup(penv) : NULL;
|
|
if (path == NULL)
|
|
return 0;
|
|
for (dir = strtok_r(path, ":", &save); dir != NULL;
|
|
dir = strtok_r(NULL, ":", &save)) {
|
|
char full[600];
|
|
|
|
snprintf(full, sizeof(full), "%s/%s", dir, word);
|
|
if (access(full, X_OK) == 0) {
|
|
free(path);
|
|
return 1;
|
|
}
|
|
}
|
|
free(path);
|
|
return 0;
|
|
}
|
|
|
|
/* --doctor: does each provider work, said in one line each */
|
|
static int
|
|
run_doctor(const struct sp_config *conf, const struct opts *o)
|
|
{
|
|
size_t i;
|
|
int bad = 0;
|
|
|
|
(void)o;
|
|
|
|
for (i = 0; i < conf->ndelegates; i++) {
|
|
const struct sp_delegate *d = &conf->delegate[i];
|
|
struct sp_usage u;
|
|
char use[128], what[300];
|
|
int ok = 0;
|
|
|
|
sp_usage_for(conf, d->id, &u);
|
|
sp_usage_brief(&u, use, sizeof(use));
|
|
what[0] = '\0';
|
|
if (strcmp(d->kind, "cli") == 0) {
|
|
if (!program_found(d->cmd)) {
|
|
snprintf(what, sizeof(what), "%s: program not found",
|
|
d->cmd);
|
|
} else if (d->nenv == 0 && d->key_env[0] != '\0' &&
|
|
getenv(d->key_env) == NULL) {
|
|
snprintf(what, sizeof(what), "%s not set", d->key_env);
|
|
} else {
|
|
snprintf(what, sizeof(what), "program found");
|
|
ok = 1;
|
|
}
|
|
} else if (!sp_provider_has_key(d)) {
|
|
snprintf(what, sizeof(what), "%s is not set", d->key_env);
|
|
} else {
|
|
struct sp_provider pv;
|
|
struct sp_buf ids, perr;
|
|
|
|
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);
|
|
/* the model list only: never a completion, never a token spent */
|
|
if (sp_buf_init(&ids) == 0 && sp_buf_init(&perr) == 0) {
|
|
char rem[160];
|
|
int have_use = sp_provider_remote_usage(&pv, rem,
|
|
sizeof(rem)) == 0;
|
|
|
|
if (have_use)
|
|
snprintf(use, sizeof(use), "%.120s", rem);
|
|
if (sp_provider_served(&pv, &ids, &perr) == 0) {
|
|
ok = 1;
|
|
snprintf(what, sizeof(what), "%.40s%s", d->model,
|
|
ids.p != NULL && d->model[0] != '\0' &&
|
|
strstr(ids.p, d->model) == NULL ?
|
|
" (not in its model list)" : "");
|
|
} else if (have_use) {
|
|
/* no model route, but its usage API answered */
|
|
ok = 1;
|
|
snprintf(what, sizeof(what), "%.40s (no model list)",
|
|
d->model);
|
|
} else
|
|
snprintf(what, sizeof(what), "%.150s",
|
|
perr.len > 0 ? perr.p : "no answer");
|
|
}
|
|
sp_buf_free(&ids);
|
|
sp_buf_free(&perr);
|
|
}
|
|
printf("%-10.10s %-5s %s [%s]\n", d->id, ok ? "ok" : "FAIL", what, use);
|
|
fflush(stdout);
|
|
if (!ok)
|
|
bad++;
|
|
}
|
|
if (conf->ndelegates == 0)
|
|
printf("no providers in the config\n");
|
|
return bad == 0 ? 0 : 1;
|
|
}
|
|
|
|
/* -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) {
|
|
/* a transport on the command line is already the choice */
|
|
if (o->endpoint != NULL || o->script != NULL ||
|
|
o->transport != NULL)
|
|
return 0;
|
|
if (conf->default_id[0] != '\0') {
|
|
sel = conf->default_id;
|
|
} else {
|
|
/*
|
|
* No -m and no default: the main endpoint in the config
|
|
* is the transport. This is the fallback, not the first
|
|
* choice - an explicit default must win over it.
|
|
*/
|
|
if (conf->endpoint[0] != '\0') {
|
|
o->endpoint = conf->endpoint;
|
|
if (o->model == NULL)
|
|
o->model = conf->model;
|
|
}
|
|
return 0;
|
|
}
|
|
}
|
|
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;
|
|
if (!sp_provider_has_key(d)) {
|
|
fprintf(stderr, "splinter: %s needs the variable %s, and it is "
|
|
"not set\n", d->id, d->key_env);
|
|
return 2;
|
|
}
|
|
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;
|
|
|
|
char cmd[600];
|
|
|
|
o->transport = "cli";
|
|
if (sp_cli_command(d, ch.model, cmd, sizeof(cmd)) != 0) {
|
|
fprintf(stderr, "splinter: '%s' is not a model name\n",
|
|
ch.model);
|
|
return 2;
|
|
}
|
|
setenv("SPLINTER_CLI_CMD", cmd, 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';
|
|
(void)plug;
|
|
for (i = 0; i < o->nplugins; i++)
|
|
if (strstr(o->plugins[i], "cli.so") != NULL ||
|
|
strcmp(o->plugins[i], "cli") == 0)
|
|
have = 1;
|
|
/* by name: load_plugins finds the tree or the installed one */
|
|
if (!have && o->nplugins < 32)
|
|
o->plugins[o->nplugins++] = "cli";
|
|
}
|
|
return 0;
|
|
}
|
|
if (strcmp(d->kind, "anthropic") == 0) {
|
|
/*
|
|
* The token lives in the provider's env block (a Claude Code OAuth
|
|
* token, one per account). Applying it here means the run reads the
|
|
* right account's token from the environment it just set, and an
|
|
* unset key_env can name that block's first variable.
|
|
*/
|
|
sp_config_apply_env((const char (*)[SP_CONFIG_ENV_LEN])d->env,
|
|
d->nenv);
|
|
o->kind = d->kind;
|
|
if (d->key_env[0] == '\0' && d->nenv > 0) {
|
|
static char kenv[SP_CONFIG_ENV_LEN];
|
|
const char *eq = strchr(d->env[0], '=');
|
|
size_t n = eq != NULL ? (size_t)(eq - d->env[0]) : 0;
|
|
|
|
if (n > 0 && n < sizeof(kenv)) {
|
|
memcpy(kenv, d->env[0], n);
|
|
kenv[n] = '\0';
|
|
o->key_env = kenv;
|
|
}
|
|
}
|
|
}
|
|
o->endpoint = d->endpoint;
|
|
/*
|
|
* ch lives on this frame and dies with it; pointing o->model into it
|
|
* handed the transport a freed stack slot, and junction answered 403
|
|
* model_not_allowed with a model name of pure garbage.
|
|
*/
|
|
{
|
|
static char kmodel[256];
|
|
|
|
snprintf(kmodel, sizeof(kmodel), "%s",
|
|
ch.model[0] != '\0' ? ch.model : d->model);
|
|
o->model = kmodel;
|
|
}
|
|
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));
|
|
if (strcmp(d->kind, "cli") == 0) {
|
|
char cmd[300];
|
|
|
|
if (sp_cli_command(d, NULL, cmd, sizeof(cmd)) != 0)
|
|
snprintf(cmd, sizeof(cmd), "%s", d->cmd);
|
|
snprintf(line, sizeof(line), "cli: %s", cmd);
|
|
} else
|
|
snprintf(line, sizeof(line), "%s", d->model);
|
|
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.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);
|
|
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
|
|
daemon_lock(const char *dir, struct sp_buf *err)
|
|
{
|
|
char path[700], other[32];
|
|
int fd, n;
|
|
ssize_t r;
|
|
|
|
snprintf(path, sizeof(path), "%s/gateway.pid", dir);
|
|
fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0600);
|
|
if (fd < 0) {
|
|
sp_buf_printf(err, "gateway: cannot open %s: %s", path,
|
|
strerror(errno));
|
|
return -1;
|
|
}
|
|
if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
|
|
r = read(fd, other, sizeof(other) - 1);
|
|
other[r > 0 ? (size_t)r : 0] = '\0';
|
|
n = (int)strcspn(other, "\n");
|
|
other[n] = '\0';
|
|
sp_buf_printf(err, "gateway already running%s%s", other[0] ? " (pid " : "",
|
|
other[0] ? other : "");
|
|
if (other[0] != '\0')
|
|
sp_buf_puts(err, ")");
|
|
close(fd);
|
|
return -1;
|
|
}
|
|
(void)ftruncate(fd, 0);
|
|
n = snprintf(other, sizeof(other), "%ld\n", (long)getpid());
|
|
(void)!write(fd, other, (size_t)n);
|
|
/* fd stays open on purpose: closing it would drop the lock */
|
|
return fd;
|
|
}
|
|
|
|
/*
|
|
* The MCP server beside the Telegram daemon: its own thread, no signal
|
|
* handlers (the daemon's stay), no session switching (the daemon holds the
|
|
* engine and its agent).
|
|
*/
|
|
struct mcp_bg {
|
|
struct sp_engine **eng;
|
|
const char *ip;
|
|
int port;
|
|
int allow_mutate;
|
|
};
|
|
|
|
static void *
|
|
mcp_bg_thread(void *arg)
|
|
{
|
|
struct mcp_bg *bg = arg;
|
|
struct sp_buf err;
|
|
|
|
if (sp_buf_init(&err) == 0) {
|
|
(void)sp_mcp_serve(bg->eng, NULL, NULL, bg->ip, bg->port,
|
|
bg->allow_mutate, 0, &err);
|
|
sp_buf_free(&err);
|
|
}
|
|
free(bg);
|
|
return NULL;
|
|
}
|
|
|
|
/* --daemon: answer on Telegram until SIGINT */
|
|
static int
|
|
run_daemon(struct sp_engine *eng, const char *base_dir, struct sp_buf *err)
|
|
{
|
|
char token[256], tpath[700];
|
|
struct sp_config *conf = sp_engine_config(eng);
|
|
struct sp_agent *ag = sp_engine_agent(eng);
|
|
struct sp_host *host = sp_engine_host(eng);
|
|
const char *state_dir = base_dir != NULL && *base_dir != '\0' ?
|
|
base_dir : sp_engine_state_dir(eng);
|
|
int rc, lockfd;
|
|
|
|
snprintf(tpath, sizeof(tpath), "%s/telegram.token", state_dir);
|
|
if (sp_telegram_token(token, sizeof(token), tpath) != 0) {
|
|
fprintf(stderr, "splinter: no Telegram token: put it in %s (0600) "
|
|
"or set SPLINTER_TELEGRAM_TOKEN\n", tpath);
|
|
return 2;
|
|
}
|
|
if (conf->telegram_allow[0] == '\0') {
|
|
fprintf(stderr, "splinter: telegram_allow is empty - nobody would "
|
|
"be answered\n");
|
|
return 2;
|
|
}
|
|
lockfd = daemon_lock(state_dir, err);
|
|
if (lockfd < 0) {
|
|
fprintf(stderr, "splinter: %s\n",
|
|
err->len > 0 ? err->p : "gateway already running");
|
|
return 2;
|
|
}
|
|
sp_engine_set_stream(eng, daemon_stream, NULL);
|
|
rc = sp_telegram_run(ag, host, token, conf->telegram_allow, conf,
|
|
state_dir, err);
|
|
close(lockfd); /* the flock goes with it */
|
|
if (rc != 0)
|
|
fprintf(stderr, "splinter: %s\n",
|
|
err->len > 0 ? err->p : "gateway failed");
|
|
return rc == 0 ? 0 : 1;
|
|
}
|
|
|
|
/* a leading slash is a harness command, also without a TUI */
|
|
static int
|
|
run_slash_prompt(struct sp_engine *eng, const char *prompt)
|
|
{
|
|
struct sp_buf out;
|
|
int rc = 0, kind;
|
|
|
|
if (sp_buf_init(&out) != 0)
|
|
return 3;
|
|
kind = sp_engine_input(eng, prompt, &out);
|
|
if (kind == SP_INPUT_PROMPT) {
|
|
struct sp_buf err, answer;
|
|
int prc;
|
|
|
|
if (sp_buf_init(&err) != 0 || sp_buf_init(&answer) != 0) {
|
|
sp_buf_free(&out);
|
|
return 3;
|
|
}
|
|
prc = sp_engine_prompt(eng,
|
|
out.len > 0 ? out.p : prompt, NULL, NULL, &answer, &err);
|
|
if (prc == 0)
|
|
printf("%s\n", answer.p != NULL ? answer.p : "");
|
|
else {
|
|
fprintf(stderr, "splinter: %s\n",
|
|
err.len > 0 ? err.p : "turn failed");
|
|
rc = 1;
|
|
}
|
|
sp_buf_free(&err);
|
|
sp_buf_free(&answer);
|
|
} else if (kind == SP_INPUT_SUBMIT) {
|
|
/*
|
|
* A program in commands/ replaced the line: its output is the
|
|
* prompt. The entry the engine queued for it is shown first,
|
|
* then the turn runs on the text.
|
|
*/
|
|
struct sp_event ev;
|
|
struct sp_buf answer, err;
|
|
int prc;
|
|
|
|
while (sp_engine_poll(eng, &ev)) {
|
|
if (ev.kind == SP_EV_ENTRY && ev.b != NULL)
|
|
printf("%s\n", ev.b);
|
|
sp_engine_event_free(&ev);
|
|
}
|
|
if (sp_buf_init(&answer) != 0 || sp_buf_init(&err) != 0) {
|
|
sp_buf_free(&out);
|
|
return 3;
|
|
}
|
|
prc = sp_engine_prompt(eng, out.p != NULL ? out.p : "", NULL,
|
|
NULL, &answer, &err);
|
|
if (prc == 0)
|
|
printf("%s\n", answer.p != NULL ? answer.p : "");
|
|
else {
|
|
fprintf(stderr, "splinter: %s\n",
|
|
err.len > 0 ? err.p : "turn failed");
|
|
rc = 1;
|
|
}
|
|
sp_buf_free(&answer);
|
|
sp_buf_free(&err);
|
|
} else {
|
|
struct sp_event ev;
|
|
|
|
if (out.p != NULL && out.len > 0)
|
|
printf("%s\n", out.p);
|
|
/* a '!' shell line answers as an entry, not as a reply */
|
|
while (sp_engine_poll(eng, &ev)) {
|
|
if (ev.kind == SP_EV_ENTRY && ev.b != NULL)
|
|
printf("%s\n", ev.b);
|
|
sp_engine_event_free(&ev);
|
|
}
|
|
}
|
|
sp_buf_free(&out);
|
|
return rc;
|
|
}
|
|
|
|
/* -p: one turn, the answer on stdout */
|
|
static int
|
|
run_prompt(struct sp_engine *eng, const char *prompt, int no_stream,
|
|
struct sp_buf *err)
|
|
{
|
|
struct sp_buf answer;
|
|
struct sp_agent *ag = sp_engine_agent(eng);
|
|
int rc;
|
|
|
|
if (sp_buf_init(&answer) != 0)
|
|
return 3;
|
|
/*
|
|
* Only claim streaming when the transport can stream. With a transport
|
|
* that cannot (the cli plugin), setting the callback made the agent take
|
|
* the non-streaming path while main still assumed the text had already
|
|
* been printed - the answer vanished.
|
|
*/
|
|
rc = sp_engine_prompt(eng, prompt,
|
|
(!no_stream && ag->tr.send_stream != NULL) ? stdout_stream : NULL,
|
|
NULL, &answer, err);
|
|
if (rc == 0) {
|
|
if (streamed_bytes == 0)
|
|
printf("%s\n", answer.p != NULL ? answer.p : "");
|
|
else
|
|
printf("\n"); /* the stream already printed it */
|
|
} else
|
|
fprintf(stderr, "splinter: %s\n",
|
|
err->len > 0 ? err->p : "turn failed");
|
|
sp_buf_free(&answer);
|
|
return rc == 0 ? 0 : 1;
|
|
}
|
|
|
|
int
|
|
main(int argc, char **argv)
|
|
{
|
|
struct opts o;
|
|
struct sp_agent_config cfg;
|
|
struct sp_config conf;
|
|
struct sp_engine_opts eo;
|
|
struct sp_engine *eng = NULL;
|
|
struct sp_buf err;
|
|
const char *daemon_base = NULL;
|
|
char tgdir[1024], statebuf[1024], sessbuf[1024];
|
|
int rc;
|
|
|
|
memset(&o, 0, sizeof(o));
|
|
memset(&cfg, 0, sizeof(cfg));
|
|
o.key_env = "SPLINTER_API_KEY";
|
|
o.mcp_port = 8098;
|
|
o.a2a_port = 8099;
|
|
o.openai_port = 8097;
|
|
cfg.max_steps = 150;
|
|
cfg.limit_wait = sp_limit_wait_default;
|
|
cfg.limit_ctx = &g_max_wait;
|
|
if (sp_buf_init(&err) != 0)
|
|
return 3;
|
|
|
|
if ((rc = parse_args(argc, argv, &o, &cfg)) >= 0)
|
|
return rc;
|
|
/*
|
|
* The interview is a conversation, not a one-line question. In a terminal
|
|
* it opens the chat UI and sends the first turn itself (see below); with
|
|
* piped input it runs that one turn and prints the answer.
|
|
*/
|
|
if (o.interview && o.prompt == NULL) {
|
|
if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO))
|
|
o.chat = 1;
|
|
else
|
|
o.prompt = "Begin the interview with your first question.";
|
|
}
|
|
if (o.list_themes) {
|
|
const char **names;
|
|
size_t count, k;
|
|
|
|
sp_theme_list(&names, &count);
|
|
for (k = 0; k < count; k++)
|
|
printf("%s\n", names[k]);
|
|
return 0;
|
|
}
|
|
if (o.notify == NULL)
|
|
take_stdin(&o);
|
|
if ((rc = load_config(&o, &conf, &cfg, &err)) >= 0)
|
|
return rc;
|
|
/* providers from the environment: OLLAMA_KEY(_N), ... */
|
|
{
|
|
size_t auto_added = sp_config_scan_env(&conf);
|
|
|
|
if (auto_added > 0)
|
|
fprintf(stderr, "splinter: %zu provider(s) from the "
|
|
"environment\n", auto_added);
|
|
}
|
|
hide_secrets(&o, &conf);
|
|
/* the catalogue is chosen now: a config file may set the locale */
|
|
(void)sp_i18n_init(NULL);
|
|
if (o.notify != NULL) {
|
|
struct sp_buf text = { 0 };
|
|
const char *msg = o.notify;
|
|
|
|
if (strcmp(o.notify, "-") == 0) {
|
|
int binary;
|
|
size_t raw;
|
|
|
|
if (sp_buf_init(&text) != 0) {
|
|
sp_buf_free(&err);
|
|
return 3;
|
|
}
|
|
if (read_stdin_block(&text, &binary, &raw) != 0) {
|
|
fprintf(stderr, "splinter: --notify: cannot read "
|
|
"stdin\n");
|
|
sp_buf_free(&text);
|
|
sp_buf_free(&err);
|
|
return 2;
|
|
}
|
|
if (binary) {
|
|
fprintf(stderr, "splinter: --notify reads text, "
|
|
"not binary input\n");
|
|
sp_buf_free(&text);
|
|
sp_buf_free(&err);
|
|
return 2;
|
|
}
|
|
if (text.p == NULL || text.len == 0) {
|
|
fprintf(stderr, "splinter: --notify: empty "
|
|
"stdin\n");
|
|
sp_buf_free(&text);
|
|
sp_buf_free(&err);
|
|
return 2;
|
|
}
|
|
msg = text.p;
|
|
}
|
|
rc = sp_telegram_notify(&conf, msg, &err);
|
|
if (rc != 0)
|
|
fprintf(stderr, "splinter: %s\n",
|
|
err.len > 0 ? err.p : "notify failed");
|
|
sp_buf_free(&text);
|
|
sp_buf_free(&err);
|
|
return rc == 0 ? 0 : 1;
|
|
}
|
|
if (o.model_list)
|
|
return run_model_list(&conf, &o);
|
|
if (o.doctor)
|
|
return run_doctor(&conf, &o);
|
|
if (o.agent_list) {
|
|
struct sp_agents al;
|
|
char cwd[700];
|
|
size_t i;
|
|
|
|
if (getcwd(cwd, sizeof(cwd)) == NULL)
|
|
cwd[0] = '\0';
|
|
if (sp_agents_load(&al, cwd, getenv("HOME")) != 0)
|
|
return 3;
|
|
for (i = 0; i < al.n; i++)
|
|
printf("%-14s %s%s\n", al.v[i].name, al.v[i].description,
|
|
al.v[i].max_auth == 0 ? " [read-only]" : "");
|
|
for (i = 0; i < al.n; i++)
|
|
if (strcmp(al.v[i].source, "(built in)") != 0)
|
|
printf(" %s: %s\n", al.v[i].name, al.v[i].source);
|
|
sp_agents_free(&al);
|
|
return 0;
|
|
}
|
|
/*
|
|
* --attach is a front end, not a run: no provider, no session, no
|
|
* engine in this process. The backend is another program.
|
|
*/
|
|
if (o.attach) {
|
|
const struct ui_backend *be;
|
|
|
|
if (o.prompt != NULL || o.serve || o.daemon ||
|
|
o.mcp_ip != NULL || o.a2a_ip != NULL ||
|
|
o.select != NULL) {
|
|
fprintf(stderr, "splinter: --attach is the screen "
|
|
"alone; drop -p/-m/--serve/--daemon/the servers\n");
|
|
return 2;
|
|
}
|
|
|
|
sp_buf_clear(&err);
|
|
be = sp_ui_backend_remote(o.socket, &err);
|
|
if (be == NULL) {
|
|
fprintf(stderr, "splinter: %s\n",
|
|
err.len > 0 ? err.p : "cannot attach");
|
|
sp_buf_free(&err);
|
|
return 3;
|
|
}
|
|
rc = sp_ui_run(be, o.theme, NULL);
|
|
sp_buf_free(&err);
|
|
return rc;
|
|
}
|
|
if ((rc = apply_selection(&o, &conf)) != 0)
|
|
return rc;
|
|
if (o.choose != NULL)
|
|
return run_choose(&conf, o.choose);
|
|
if ((rc = check_usage(&o)) != 0)
|
|
return rc;
|
|
|
|
/*
|
|
* The modes that answer without an agent: a stored approval and the
|
|
* first-run interview. Everything else is built by the engine.
|
|
*/
|
|
if (o.acklist) {
|
|
struct sp_buf out;
|
|
|
|
if (sp_buf_init(&out) != 0)
|
|
return 1;
|
|
(void)sp_ack_list(&out);
|
|
printf("%s", out.p != NULL ? out.p : "");
|
|
sp_buf_free(&out);
|
|
return 0;
|
|
}
|
|
if (o.ack_id != 0) {
|
|
if (sp_ack_answer(o.ack_id, o.ack_yes,
|
|
getenv("SPLINTER_ACK_BY")) != 0) {
|
|
fprintf(stderr, "splinter: no open request %d (unknown, "
|
|
"answered or expired)\n", o.ack_id);
|
|
return 1;
|
|
}
|
|
printf("%s %d\n", o.ack_yes ? "yes" : "no", o.ack_id);
|
|
return 0;
|
|
}
|
|
memset(&eo, 0, sizeof(eo));
|
|
eo.conf = &conf;
|
|
eo.base = &cfg;
|
|
eo.endpoint = o.endpoint;
|
|
eo.model = o.model;
|
|
eo.key_env = o.key_env;
|
|
eo.transport = o.transport;
|
|
eo.kind = o.kind;
|
|
eo.script = o.script;
|
|
eo.agent = o.agent;
|
|
eo.session_dir = o.sessdir;
|
|
eo.session_id = o.sessid;
|
|
eo.resume = o.resume;
|
|
eo.continue_last = o.continue_here;
|
|
eo.from_foreign = o.from_foreign;
|
|
/*
|
|
* Telegram owns its sessions: the daemon writes below <state>/telegram,
|
|
* so a CLI -c in the same directory never picks a gateway conversation
|
|
* (and /new in the chat never creates a file a CLI would resume).
|
|
*/
|
|
if (o.daemon) {
|
|
const char *state = sp_config_state_dir(&conf);
|
|
const char *sess = o.sessdir;
|
|
|
|
snprintf(statebuf, sizeof(statebuf), "%s", state);
|
|
if (sess == NULL || *sess == '\0')
|
|
sess = sp_config_session_dir(&conf);
|
|
snprintf(sessbuf, sizeof(sessbuf), "%s", sess);
|
|
{
|
|
size_t blen = strlen(sessbuf);
|
|
|
|
if (blen + sizeof("/telegram") > sizeof(tgdir)) {
|
|
fprintf(stderr, "splinter: session path too long\n");
|
|
sp_buf_free(&err);
|
|
return 2;
|
|
}
|
|
memcpy(tgdir, sessbuf, blen);
|
|
memcpy(tgdir + blen, "/telegram", sizeof("/telegram"));
|
|
}
|
|
daemon_base = statebuf;
|
|
eo.session_dir = tgdir;
|
|
eo.session_id = NULL;
|
|
eo.resume = 1;
|
|
eo.continue_last = 0;
|
|
}
|
|
/*
|
|
* The MCP server is tools-only unless a model is given (or the daemon
|
|
* owns the engine): the session tools need a transport to run a turn.
|
|
*/
|
|
eo.interview = o.interview;
|
|
eo.no_transport = (o.mcp_ip != NULL && !o.daemon &&
|
|
o.endpoint == NULL && o.model == NULL) || o.delegate != NULL;
|
|
/*
|
|
* The fleet is opt-in (--swarm) and belongs to the curses chat, not to
|
|
* a served engine. Without the flag no instance binds or joins
|
|
* .splinter-swarm.sock, so a plain chat leaves no file in a shared
|
|
* working directory and no second instance can be locked by it.
|
|
*/
|
|
eo.swarm = o.swarm && o.chat && !o.serve && !o.daemon &&
|
|
o.a2a_ip == NULL && o.mcp_ip == NULL && o.delegate == NULL;
|
|
{
|
|
size_t k;
|
|
|
|
for (k = 0; k < o.nplugins && k < SP_ENGINE_PLUGINS; k++)
|
|
eo.plugins[k] = o.plugins[k];
|
|
eo.nplugins = k;
|
|
}
|
|
/*
|
|
* --serve owns its engines: it opens the first one itself and reopens
|
|
* another when a client asks for a session, so main must not hold a
|
|
* second engine.
|
|
*/
|
|
if (o.serve) {
|
|
struct sp_proto_opts po;
|
|
|
|
po.engine = &eo;
|
|
po.socket = o.socket;
|
|
rc = sp_proto_serve(&po, &err);
|
|
if (rc != 0) {
|
|
fprintf(stderr, "splinter: %s\n",
|
|
err.len > 0 ? err.p : "protocol server failed");
|
|
sp_buf_free(&err);
|
|
return 3;
|
|
}
|
|
sp_buf_free(&err);
|
|
return 0;
|
|
}
|
|
{
|
|
int erc = sp_engine_open(&eng, &eo, &err);
|
|
|
|
if (erc != 0) {
|
|
fprintf(stderr, "splinter: %s\n",
|
|
err.len > 0 ? err.p : "cannot start the engine");
|
|
sp_buf_free(&err);
|
|
return erc == -2 ? 2 : 3;
|
|
}
|
|
}
|
|
if (o.delegate != NULL)
|
|
rc = run_delegate_cli(sp_engine_registry(eng), o.delegate,
|
|
o.prompt);
|
|
else if (o.a2a_ip != NULL) {
|
|
rc = sp_a2a_serve(sp_engine_agent(eng), o.a2a_ip, o.a2a_port,
|
|
&err);
|
|
if (rc != 0)
|
|
fprintf(stderr, "splinter: %s\n",
|
|
err.len > 0 ? err.p : "A2A server failed");
|
|
rc = rc == 0 ? 0 : 1;
|
|
} else if (o.mcp_ip != NULL) {
|
|
if (o.daemon) {
|
|
/*
|
|
* The daemon answers on Telegram; the MCP server runs
|
|
* beside it on its own thread. Session switching is not
|
|
* available here (the daemon holds the engine), but the
|
|
* session tools - list, history, say, model, steer,
|
|
* cancel, approve - are.
|
|
*/
|
|
struct mcp_bg *bg = calloc(1, sizeof(*bg));
|
|
pthread_t th;
|
|
|
|
if (bg == NULL) {
|
|
fprintf(stderr, "splinter: out of memory\n");
|
|
rc = 3;
|
|
goto done;
|
|
}
|
|
bg->eng = ŋ
|
|
bg->ip = o.mcp_ip;
|
|
bg->port = o.mcp_port;
|
|
bg->allow_mutate = cfg.autonomous == 1;
|
|
if (pthread_create(&th, NULL, mcp_bg_thread, bg) != 0) {
|
|
fprintf(stderr, "splinter: cannot start the MCP "
|
|
"server thread\n");
|
|
free(bg);
|
|
rc = 3;
|
|
goto done;
|
|
}
|
|
rc = run_daemon(eng, daemon_base, &err);
|
|
/*
|
|
* The MCP thread works on this engine: it must be gone
|
|
* before sp_engine_close() frees it.
|
|
*/
|
|
sp_mcp_stop();
|
|
(void)pthread_join(th, NULL);
|
|
} else {
|
|
rc = sp_mcp_serve(&eng, &eo, sp_engine_registry(eng),
|
|
o.mcp_ip, o.mcp_port, cfg.autonomous == 1, 1, &err);
|
|
if (rc != 0)
|
|
fprintf(stderr, "splinter: %s\n",
|
|
err.len > 0 ? err.p : "MCP server failed");
|
|
rc = rc == 0 ? 0 : 1;
|
|
}
|
|
} else if (o.openai_ip != NULL) {
|
|
struct sp_gateway_opts go;
|
|
|
|
if (o.transport != NULL || o.endpoint == NULL) {
|
|
fprintf(stderr, "splinter: --openai-listen needs an "
|
|
"OpenAI-compatible or Anthropic provider "
|
|
"(--endpoint/--model or -m), not a plugin "
|
|
"transport\n");
|
|
rc = 2;
|
|
goto done;
|
|
}
|
|
memset(&go, 0, sizeof(go));
|
|
go.ip = o.openai_ip;
|
|
go.port = o.openai_port;
|
|
go.token = getenv("SPLINTER_GATEWAY_TOKEN");
|
|
go.autonomous = cfg.autonomous == 1;
|
|
go.max_steps = 16;
|
|
go.reg = sp_engine_registry(eng);
|
|
go.conf = &conf;
|
|
go.endpoint = o.endpoint;
|
|
go.model = o.model;
|
|
go.key_env = o.key_env;
|
|
go.kind = o.kind;
|
|
rc = sp_openai_serve(&go, &err);
|
|
if (rc != 0)
|
|
fprintf(stderr, "splinter: %s\n",
|
|
err.len > 0 ? err.p : "gateway failed");
|
|
rc = rc == 0 ? 0 : 1;
|
|
} else if (o.daemon)
|
|
rc = run_daemon(eng, daemon_base, &err);
|
|
else if (o.chat) {
|
|
if (!o.interview && !sp_profile_exists(sp_config_state_dir(&conf)))
|
|
fprintf(stderr, sp_td("main.no_profile",
|
|
"splinter: no profile for '%s' - "
|
|
"`splinter --interview` creates one\n"),
|
|
sp_user_name());
|
|
rc = sp_ui_run(sp_ui_backend_engine(&eng, &eo), o.theme,
|
|
o.interview
|
|
? sp_td("interview.kickoff",
|
|
"Begin the interview with your first question.")
|
|
: NULL);
|
|
} else if (o.prompt != NULL &&
|
|
(o.prompt[0] == '/' || o.prompt[0] == '!'))
|
|
rc = run_slash_prompt(eng, o.prompt);
|
|
else
|
|
rc = run_prompt(eng, o.prompt, o.no_stream, &err);
|
|
|
|
done:
|
|
sp_engine_close(eng);
|
|
sp_buf_free(&err);
|
|
return rc;
|
|
}
|