Files
splinter/src/main.c
T
lotherkandClaude Opus 5.5 75d8beeaa4 delegates and cli_env: hardcoded environment per cli program; swarm, provider, planner, scheduler, tmux
env=NAME=VALUE on a delegate line (repeatable) is set in the child right
before exec and beats what the parent exported, so two delegates can run
the same cli with two accounts. Remotely it goes in front as
`env 'NAME=VALUE'`, quoted like the rest. cli_env = NAME=VALUE does the
same for the main cli transport. A bad name is an error with the line.

Also in this commit, the work in progress from the tree: swarm and
provider state, the provider/scheduler/planner/tmux plugins, the ui test,
whose tmux session name is now per run so parallel runs do not collide.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 19:15:48 +00:00

1002 lines
29 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "splinter.h"
#include "config.h"
#include "i18n.h"
#include "log.h"
#include "skills.h"
#include "memory.h"
#include "prompt.h"
#include "folder.h"
#include "mcpserver.h"
#include "interview.h"
#include "ack.h"
#include "swarm.h"
#include "splinter_plugin.h"
#include "theme.h"
#include "ui.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"
" --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"
" --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"
" --chat interactive curses UI instead of one turn\n"
" --theme NAME CDE palette for the UI (default Delphinium)\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"
" --daemon answer on Telegram until SIGINT\n"
" --no-stdin ignore data on standard input\n"
" -c, --continue continue the last session started in this "
"directory\n"
" --interview ask the first-run questions and write the "
"profile\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"
" --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;
}
/*
* A script file is one reply per line, in the mock transport's own protocol
* ("answer ...", "tool <name> <args>"). Loading it up front means the whole
* turn is deterministic and re-runnable, with no network anywhere.
*/
static int
load_script(struct sp_mock *m, const char *path, struct sp_buf *err)
{
FILE *f;
char line[8192];
f = fopen(path, "r");
if (f == NULL) {
sp_buf_printf(err, "%s: %s", path, strerror(errno));
return -1;
}
while (fgets(line, sizeof(line), f) != NULL) {
line[strcspn(line, "\r\n")] = '\0';
if (line[0] == '\0' || line[0] == '#')
continue;
if (sp_mock_push(m, 200, line) != 0) {
fclose(f);
sp_buf_puts(err, sp_t("err.oom"));
return -1;
}
}
fclose(f);
return 0;
}
/* one-shot mode: print the answer as it arrives, no buffering */
/* bytes the transport streamed: if none, the answer still has to be printed */
static size_t streamed_bytes;
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;
}
/* 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 *choose, *mcp_ip;
const char *plugins[16];
size_t nplugins;
int init_config, no_config, list_themes, chat, resume;
int daemon, no_stdin, continue_here, interview;
int acklist, ack_id, ack_yes, mcp_port;
};
/* 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;
}
/*
* The command line into 'o' and 'cfg'. Returns -1 to go on, or the exit
* status (help and version exit 0, a bad option 2).
*/
static int
parse_args(int argc, char **argv, struct opts *o, struct sp_agent_config *cfg)
{
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")) {
printf("splinter %s\n", SP_VERSION);
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, "--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, "--config"))
VALUE(o->config_path);
else if (!strcmp(a, "--transport"))
VALUE(o->transport);
else if (!strcmp(a, "--script"))
VALUE(o->script);
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");
return 2;
}
o->plugins[o->nplugins++] = argv[++i];
} else if (!strcmp(a, "--chat"))
o->chat = 1;
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, "--daemon"))
o->daemon = 1;
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;
}
o->mcp_port = atoi(argv[++i]);
} else if (!strcmp(a, "-c") || !strcmp(a, "--continue"))
o->continue_here = 1;
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->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) {
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;
}
if (o->endpoint == NULL && conf->endpoint[0] != '\0')
o->endpoint = conf->endpoint;
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;
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(conf->memory_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;
}
/* exactly one transport, and a reason to run at all; 0 or the exit status */
static int
check_usage(const struct opts *o)
{
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) {
fprintf(stderr, "splinter: no transport (--endpoint, --script or "
"--transport)\n");
return 2;
}
if (o->prompt == NULL && !o->chat && !o->daemon && o->mcp_ip == NULL) {
fprintf(stderr, "splinter: -p/--prompt is required unless you pass "
"--chat, --daemon or --mcp-server-listen\n");
return 2;
}
return 0;
}
/* the session directory and id, opened; 0 or the exit status */
static int
open_session(struct opts *o, struct sp_session_info *sess, struct sp_buf *err)
{
static char sessbuf[512], idbuf[64];
if (o->sessdir == NULL) {
const char *home = getenv("HOME");
snprintf(sessbuf, sizeof(sessbuf), "%s/.splinter",
home != NULL ? home : ".");
o->sessdir = sessbuf;
}
/*
* -c means "the last session that happened *here*". The cwd at start is
* the key, so a session in another tree is never silently loaded.
*/
if (o->continue_here && o->sessid == NULL) {
char cwd[512];
if (getcwd(cwd, sizeof(cwd)) == NULL ||
sp_session_last_for(o->sessdir, cwd, idbuf,
sizeof(idbuf)) != 0) {
fprintf(stderr, "splinter: no session in %s yet\n",
getcwd(cwd, sizeof(cwd)) != NULL ? cwd : ".");
return 2;
}
o->sessid = idbuf;
o->resume = 1;
}
/*
* --resume continues the newest session in the directory unless an id was
* named. Opening a fresh id would resume nothing and still look like it
* worked - the first version of this flag did exactly that.
*/
if (o->resume && o->sessid == NULL &&
sp_session_latest(o->sessdir, idbuf, sizeof(idbuf)) == 0)
o->sessid = idbuf;
if (o->sessid == NULL) {
snprintf(idbuf, sizeof(idbuf), "sess-%ld-%d", (long)time(NULL),
(int)getpid());
o->sessid = idbuf;
}
if (sp_session_open(sess, o->sessdir, o->sessid, err) != 0) {
fprintf(stderr, "splinter: %s\n",
err->len > 0 ? err->p : sp_t("err.session"));
return 3;
}
(void)sp_log_open(sess->dir, sess->id);
return 0;
}
/*
* The plugin host and its plugins. A plugin that fails to load is reported and
* skipped: the harness keeps working, the operator sees why. Returns 0 or the
* exit status; *hostp stays NULL without plugins.
*/
static int
load_plugins(const struct opts *o, struct sp_registry *reg, struct sp_agent *ag,
struct sp_session_info *sess, const struct sp_config *conf,
struct sp_host **hostp, struct sp_buf *err)
{
struct sp_host *host;
size_t k;
*hostp = NULL;
if (o->nplugins == 0)
return 0;
host = sp_host_new(reg, ag, sess);
if (host == NULL) {
fprintf(stderr, "splinter: cannot create plugin host\n");
return 3;
}
/*
* The agent compacts through this pointer. It was never set, so every
* compactor - lcm, focus, reminder - was registered, tested in isolation,
* and never called by the real binary.
*/
ag->host = host;
sp_host_set_config(host, conf);
for (k = 0; k < o->nplugins; k++) {
sp_buf_clear(err);
if (sp_plugin_load(host, o->plugins[k], err) != 0)
fprintf(stderr, "splinter: %s\n", err->len > 0 ? err->p :
sp_t("err.plugin_failed"));
else
fprintf(stderr, "splinter: plugin %s loaded\n",
o->plugins[k]);
}
*hostp = host;
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,
const struct sp_registry *reg, struct sp_mock *mock, int *have_mock,
struct sp_buf *err)
{
if (o->transport != NULL) {
struct sp_transport *tr;
if (host == NULL) {
fprintf(stderr, "splinter: --transport needs a plugin that "
"provides it (--plugin)\n");
return 2;
}
tr = sp_host_transport(host, o->transport);
if (tr == NULL) {
fprintf(stderr, "splinter: no plugin provides the '%s' "
"transport\n", o->transport);
return 2;
}
ag->tr = *tr;
} else if (o->script != NULL) {
if (sp_mock_init(mock) != 0) {
fprintf(stderr, "splinter: %s\n", sp_t("err.oom"));
return 3;
}
*have_mock = 1;
if (load_script(mock, o->script, err) != 0) {
fprintf(stderr, "splinter: %s\n",
err->len > 0 ? err->p : "script");
return 3;
}
ag->tr = sp_mock_transport(mock);
} else if (o->mcp_ip == NULL) {
/* in MCP server mode no model is needed: we are the tool provider */
const char *hto;
long http_timeout;
if (o->model == NULL) {
fprintf(stderr, "splinter: --endpoint needs --model\n");
return 2;
}
hto = getenv("SPLINTER_HTTP_TIMEOUT");
http_timeout = hto != NULL && *hto != '\0' ? strtol(hto, NULL, 10) : 0;
if (http_timeout <= 0)
http_timeout = 900;
ag->tr = sp_openai_transport(o->endpoint, o->model,
getenv(o->key_env), reg, http_timeout);
/* provider identity for per-key quota/usage tracking (plugins) */
{
const char *ep = o->endpoint ? o->endpoint : "";
const char *prov = "openai-compat";
if (strstr(ep, "11434") || strstr(ep, "ollama"))
prov = "ollama";
else if (strstr(ep, "opencode") || strstr(ep, "open-code"))
prov = "opencode";
ag->tr.provider = prov;
}
{
const char *secret = getenv(o->key_env);
static char kfp[32];
if (secret && *secret && sp_key_fingerprint(secret, kfp, sizeof(kfp)))
ag->tr.key_id = kfp;
else if (ag->tr.provider && strcmp(ag->tr.provider, "ollama") == 0)
ag->tr.key_id = "local"; /* ollama often keyless/local */
}
}
return 0;
}
/*
* The conversation: the system prompt, expanded - placeholders are facts about
* this machine, and the model should not have to ask for them - and with
* --resume the session's history. Returns 0 or the exit status.
*/
static int
setup_conversation(const struct opts *o, struct sp_agent *ag,
struct sp_agent_config *cfg, struct sp_session_info *sess,
struct sp_buf *err)
{
static struct sp_conv conv;
static char expanded[8192];
size_t loaded = 0;
sp_conv_init(&conv);
sp_prompt_expand(cfg->system_prompt, expanded, sizeof(expanded), o->model);
cfg->system_prompt = expanded;
if (sp_conv_push(&conv, "system", NULL, cfg->system_prompt) != 0) {
fprintf(stderr, "splinter: %s\n", sp_t("err.oom"));
return 3;
}
ag->conv = &conv;
if (!o->resume)
return 0;
sp_buf_clear(err);
if (sp_session_load(sess, &conv, &loaded, err) != 0) {
fprintf(stderr, "splinter: %s\n",
err->len > 0 ? err->p : "cannot load the session");
return 3;
}
if (loaded > 0)
fprintf(stderr, "splinter: resumed %zu messages from %s\n", loaded,
sess->dir);
return 0;
}
/* --daemon: answer on Telegram until SIGINT */
static int
run_daemon(struct sp_agent *ag, struct sp_agent_config *cfg,
struct sp_host *host, const struct sp_session_info *sess,
const struct sp_config *conf, struct sp_buf *err)
{
char token[256], tpath[700];
int rc;
snprintf(tpath, sizeof(tpath), "%s/telegram.token", sess->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;
}
cfg->stream = daemon_stream;
cfg->stream_ctx = NULL;
rc = sp_telegram_run(ag, host, token, conf->telegram_allow, err);
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_host *host, const char *prompt)
{
char name[64], args[1536];
struct sp_buf out;
const char *sp = strchr(prompt, ' ');
int rc = 0;
if (sp == NULL) {
snprintf(name, sizeof(name), "%.63s", prompt + 1);
args[0] = '\0';
} else {
size_t nlen = (size_t)(sp - (prompt + 1));
if (nlen >= sizeof(name))
nlen = sizeof(name) - 1;
memcpy(name, prompt + 1, nlen);
name[nlen] = '\0';
snprintf(args, sizeof(args), "%s", sp + 1);
}
if (sp_buf_init(&out) != 0)
return 3;
if (sp_host_command(host, name, args, &out) != 0) {
sp_buf_clear(&out);
sp_buf_printf(&out, sp_t("cmd.unknown"), name);
sp_buf_printf(&out, "\n %s ", sp_t("cmd.available"));
(void)sp_host_command_help(host, &out);
rc = 2;
}
printf("%s\n", out.p != NULL ? out.p : "");
sp_buf_free(&out);
return rc;
}
/* -p: one turn, the answer on stdout */
static int
run_prompt(struct sp_agent *ag, struct sp_agent_config *cfg, const char *prompt,
struct sp_buf *err)
{
struct sp_buf answer;
int rc;
if (sp_buf_init(&answer) != 0)
return 3;
/*
* Only claim streaming when the transport can stream. With a transport
* that cannot (the cli plugin, an MCP-backed one), setting the callback
* made the agent take the non-streaming path while main still assumed the
* text had already been printed - the answer vanished and only a newline
* came out.
*/
cfg->stream = ag->tr.send_stream != NULL ? stdout_stream : NULL;
cfg->stream_ctx = NULL;
rc = sp_agent_run(ag, prompt, &answer, err);
if (rc == 0) {
if (cfg->stream == NULL || 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_registry reg;
struct sp_agent ag;
struct sp_agent_config cfg;
struct sp_session_info sess;
struct sp_config conf;
struct sp_mock mock;
struct sp_host *host = NULL;
struct sp_buf err;
int rc, have_mock = 0;
memset(&o, 0, sizeof(o));
memset(&reg, 0, sizeof(reg));
memset(&ag, 0, sizeof(ag));
memset(&cfg, 0, sizeof(cfg));
memset(&sess, 0, sizeof(sess));
o.key_env = "SPLINTER_API_KEY";
o.mcp_port = 8098;
cfg.max_steps = 150;
if (sp_buf_init(&err) != 0)
return 3;
if ((rc = parse_args(argc, argv, &o, &cfg)) >= 0)
return rc;
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;
}
take_stdin(&o);
if ((rc = load_config(&o, &conf, &cfg, &err)) >= 0)
return rc;
/* providers from the environment: OLLAMA_KEY(_N), CLAUDE_CODE_OAUTH_TOKEN(_N) */
{
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);
if (o.choose != NULL)
return run_choose(&conf, o.choose);
/* the catalogue is chosen now: a config file may set the locale */
(void)sp_i18n_init(NULL);
if ((rc = check_usage(&o)) != 0)
return rc;
if (sp_builtin_register(&reg) != 0 ||
sp_memory_register(&reg, &conf) != 0 ||
sp_skills_register(&reg, &conf) != 0) {
fprintf(stderr, "splinter: cannot register the builtin tools\n");
return 3;
}
if ((rc = open_session(&o, &sess, &err)) != 0)
return rc;
ag.sess = &sess;
/*
* Answering is not running an agent: any process may drop the answer,
* which is the whole point of the file behind it.
*/
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;
}
if (o.interview) {
rc = sp_interview_run(sess.dir, &err);
if (rc != 0)
fprintf(stderr, "splinter: %s\n",
err.len > 0 ? err.p : "interview failed");
return rc == 0 ? 0 : 1;
}
sp_logf("session", "started: %s", sess.id);
if ((rc = load_plugins(&o, &reg, &ag, &sess, &conf, &host, &err)) != 0)
return rc;
/*
* Registered here, not with the builtins: folder_history needs the
* session directory, and delegate needs the host for its task-panel
* entries. Before, the first got an uninitialised sess.dir and the second
* always got host == NULL - a delegation never showed up in the panel.
*/
if (sp_folder_register(&reg, sess.dir) != 0 ||
sp_delegate_register(&reg, &conf, host) != 0) {
fprintf(stderr, "splinter: cannot register folder_history or "
"delegate\n");
return 3;
}
if ((rc = pick_transport(&o, &ag, host, &reg, &mock, &have_mock,
&err)) != 0)
return rc;
if ((rc = setup_conversation(&o, &ag, &cfg, &sess, &err)) != 0)
return rc;
cfg.approval_in = stdin;
cfg.approval_out = stderr;
ag.reg = &reg;
ag.cfg = &cfg;
if (o.mcp_ip != NULL) {
rc = sp_mcp_serve(&reg, o.mcp_ip, o.mcp_port, cfg.autonomous == 1,
&err);
if (rc != 0)
fprintf(stderr, "splinter: %s\n",
err.len > 0 ? err.p : "MCP server failed");
rc = rc == 0 ? 0 : 1;
} else if (o.daemon)
rc = run_daemon(&ag, &cfg, host, &sess, &conf, &err);
else if (o.chat) {
if (!sp_profile_exists(sess.dir))
fprintf(stderr, "splinter: kein Profil fuer '%s' - "
"`splinter --interview` legt eins an\n",
sp_memory_user());
{
struct swarm sw;
char cwd[512];
if (getcwd(cwd, sizeof(cwd)) == NULL) cwd[0] = '\0';
swarm_init(&sw, cwd);
rc = sp_ui_run(&ag, o.endpoint, o.model, o.theme, host, &sw);
swarm_close(&sw);
}
} else if (o.prompt != NULL && o.prompt[0] == '/' && host != NULL)
rc = run_slash_prompt(host, o.prompt);
else
rc = run_prompt(&ag, &cfg, o.prompt, &err);
if (have_mock)
sp_mock_free(&mock);
sp_host_free(host);
sp_buf_free(&err);
sp_registry_free(&reg);
return rc;
}