Files
splinter/plugins/foreign/foreign.c
T
lotherk 80f055711d races: five data races fixed, make check-tsan to keep them fixed
Found with ThreadSanitizer over the whole suite, not by reading:

- ack: sp_ack_dir() returned one static buffer. The waiter and the
  answerer (the gateway is both) sprintf'd into each other's path, so an
  approval request could be looked for in the wrong place. One buffer per
  thread now; test_ack asserts the two threads get different addresses.
- mcp: `stopping` was a plain volatile int with no happens-before, so a
  server thread could read 0 after shutdown killed its child and keep
  using buffers that teardown frees. Acquire/release accessors.
- foreign: fr.ready was set before the paths it guards were filled, so a
  second thread returned early and read empty paths; the flag and the host
  handle are now an atomic pair (publish) plus a mutex (the init itself).
- embed: catch_up() read c->path, c->offset and c->id outside the lock. A
  session switch mid-index published the old file's byte offset into the
  new session's index - everything below that offset was never searched
  again. A generation counter makes that run drop its batch, and the
  search path takes its snapshot under the same lock.

Proof, both directions:
- make check-tsan: 45/45 test binaries free of races (new target; the
  tree is rebuilt under TSan and back, like check-asan).
- test_embed's new gated test (a server that holds the batch until the
  session has been switched): without the generation check short.emb ends
  with 4 records, 1 of them leaked from the other session; with it, 1
  and 0. The test is deterministic, so it fails on a plain build too.
- test_ack: reverting to `static char root[]` fails
  "the two threads do not share one buffer".
- make check: all tests passed; make check-asan: 45/45 clean.
2026-11-23 08:30:29 +00:00

3362 lines
93 KiB
C

/*
* splinter -- foreign sessions: Claude Code, Hermes and opencode, read natively.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* Three harnesses keep their conversations on this machine, each in its own
* shape:
*
* claude ~/.claude/projects/<slug>/<uuid>.jsonl
* one JSON object per line, type user|assistant, content an array
* of text / thinking / tool_use / tool_result blocks, and one
* assistant message split over several lines (one per block, same
* message id, chained by parentUuid).
* hermes <root>/state.db, and <root>/profiles/<name>/state.db
* SQLite: sessions(id,title,cwd,started_at) and
* messages(session_id,role,content,tool_call_id,tool_calls,
* tool_name,...), in OpenAI's shape.
* opencode ~/.local/share/opencode/opencode.db
* SQLite: session_v2 for the list and session_message
* (type user|assistant|system|compaction, data JSON) for the
* transcript; older databases keep message + part instead, older
* roots only the table 'session'.
*
* None of them is a splinter session, and asking a model to "remember"
* another harness's conversation is not the same as having it: resume, /open,
* compaction and the session tools work on splinter's own append-only JSONL.
*
* So this plugin does two things and nothing else:
*
* read list, search and print the foreign sessions (four tools and
* /foreign). Read-only, SP_AUTH_READ.
* import write one of them into the session directory as a splinter
* session - the same records splinter writes itself, every tool call
* paired with its observation - so --session-id <id> --resume,
* -c and the name in the sidecar
* continue that conversation natively afterwards.
*
* The import keeps the foreign session's working directory and start time in
* the .meta sidecar, so the imported session appears under the folder it
* happened in and `-c` finds it there. That is the one place the plugin writes
* a file splinter defines (session.c's key=value sidecar); it merges the keys
* it owns into whatever is already there and keeps the rest.
*
* SQLite is read through the sqlite3(1) CLI in read-only mode, exec'd directly
* (never through a shell, so a session id cannot become an argument): the
* harness has no SQLite dependency and this plugin does not add one. A missing
* sqlite3 says so instead of pretending the store is empty.
*
* Configuration, all optional; the standard paths are the default:
*
* plugin foreign {
* claude = ~/.claude/projects
* hermes = ~/.hermes, ~/.hermes-personal
* opencode = ~/.local/share/opencode/opencode.db
* max_bytes = 33554432 # per transcript, then truncated
* limit = 25 # rows and hits per answer
* }
*
* SPLINTER_FOREIGN_CLAUDE / _HERMES / _OPENCODE override the paths for one run
* (the test uses them; so does a disk mounted somewhere else).
*/
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include "splinter.h"
#include "splinter_plugin.h"
#include "mcp.h"
/* anthropic.c and openai.c declare this locally; libsplinter exports it */
int sp_json_emit(struct sp_buf *, const mcp_json *);
#define FR_PATHS 8 /* hermes roots */
#define FR_PATH 700
#define FR_TITLE 110
#define FR_MAX_MSG 4000 /* records per imported transcript */
#define FR_MAX_BYTES (32u * 1024 * 1024)
#define FR_MAX_LINE (16u * 1024 * 1024)
#define FR_ROW_BYTES 262144 /* one SQL row, so 500 of them stay bounded */
#define FR_SQL_BYTES (48u * 1024 * 1024)
#define FR_SQL_ROWS 400
#define FR_SQL_TIMEOUT 30 /* seconds per sqlite3 call */
#define FR_HEAD_BYTES (192u * 1024) /* how much of a claude file a title reads */
enum fr_src { SRC_CLAUDE = 0, SRC_HERMES, SRC_OPENCODE, SRC_NONE };
static const char *const src_name[] = { "claude", "hermes", "opencode" };
static const char *const src_tag[] = { "fcl-", "fhm-", "foc-" };
/* ------------------------------------------------------------------ config */
/*
* One initialisation guard for the paths below. The widget thread (foreign_tick)
* and the thread that runs a tool both call resolve_paths(); the flag used to be
* set *before* the paths it guards were filled, so the second thread returned at
* once and read empty paths - and the plain `int` read/write was a data race on
* top. The mutex serialises the init, the atomic publishes it.
*/
static pthread_mutex_t fr_init_mu = PTHREAD_MUTEX_INITIALIZER;
static int fr_ready;
static struct {
struct sp_host *host;
char claude[FR_PATH];
char hermes[FR_PATHS][FR_PATH];
size_t nhermes;
char opencode[FR_PATH];
size_t max_bytes;
int limit;
} fr = { NULL, "", { { "" } }, 0, "", FR_MAX_BYTES, 25 };
/* ~ at the front of a configured path; a trailing slash is dropped */
static int
path_expand(const char *in, char *out, size_t cap)
{
const char *home = getenv("HOME");
size_t n;
if (in == NULL || out == NULL || cap == 0)
return -1;
if (in[0] == '~' && (in[1] == '/' || in[1] == '\0')) {
if (home == NULL)
return -1;
if ((size_t)snprintf(out, cap, "%s%s", home, in + 1) >= cap)
return -1;
} else if ((size_t)snprintf(out, cap, "%s", in) >= cap) {
return -1;
}
while ((n = strlen(out)) > 1 && out[n - 1] == '/')
out[n - 1] = '\0';
return 0;
}
/* a + "/" + b (+ c): -1 instead of a silently cut path */
static int
path_join(char *out, size_t cap, const char *a, const char *b, const char *c)
{
size_t n = 0;
const char *parts[3];
size_t i;
parts[0] = a;
parts[1] = b;
parts[2] = c;
for (i = 0; i < 3; i++) {
const char *p = parts[i];
if (p == NULL || *p == '\0')
continue;
if (n > 0 && out[n - 1] != '/') {
if (n + 1 >= cap)
return -1;
out[n++] = '/';
}
while (*p != '\0') {
if (n + 1 >= cap)
return -1;
out[n++] = *p++;
}
}
if (cap == 0)
return -1;
out[n] = '\0';
return 0;
}
static void
hermes_add(const char *path)
{
char buf[FR_PATH];
size_t i;
if (path == NULL || *path == '\0' || fr.nhermes == FR_PATHS)
return;
if (path_expand(path, buf, sizeof(buf)) != 0)
return;
for (i = 0; i < fr.nhermes; i++)
if (strcmp(fr.hermes[i], buf) == 0)
return;
snprintf(fr.hermes[fr.nhermes++], FR_PATH, "%s", buf);
}
/* a configured value that is a list "a, b" or a single path */
static void
hermes_list(const char *val)
{
char *copy, *p, *save = NULL;
if (val == NULL)
return;
copy = strdup(val);
if (copy == NULL)
return;
for (p = strtok_r(copy, ",", &save); p != NULL;
p = strtok_r(NULL, ",", &save)) {
while (*p == ' ' || *p == '\t')
p++;
hermes_add(p);
}
free(copy);
}
/*
* The host handle, read and written from the widget thread and from whichever
* thread runs a tool. Every writer passes the same handle today, so the race was
* harmless - but an unsynchronised word is still a race, and a build with two
* hosts in one process (dlopen shares this file's statics) would make it matter.
* Store release, load acquire: a thread that sees the handle sees its config.
*/
static void
set_host(struct sp_host *h)
{
__atomic_store_n(&fr.host, h, __ATOMIC_RELEASE);
}
static struct sp_host *
get_host(void)
{
return __atomic_load_n(&fr.host, __ATOMIC_ACQUIRE);
}
static const char *
conf(const char *key)
{
struct sp_host *h = get_host();
return h != NULL ? sp_host_plugin_config(h, "foreign", key) : NULL;
}
static void
resolve_paths(void)
{
const char *v;
char home[FR_PATH];
if (__atomic_load_n(&fr_ready, __ATOMIC_ACQUIRE))
return;
pthread_mutex_lock(&fr_init_mu);
if (__atomic_load_n(&fr_ready, __ATOMIC_ACQUIRE)) {
pthread_mutex_unlock(&fr_init_mu);
return;
}
snprintf(home, sizeof(home), "%s",
getenv("HOME") != NULL ? getenv("HOME") : "");
v = conf("claude");
if (v == NULL)
v = getenv("SPLINTER_FOREIGN_CLAUDE");
if (v != NULL && *v != '\0') {
(void)path_expand(v, fr.claude, sizeof(fr.claude));
} else if (home[0] != '\0') {
(void)path_join(fr.claude, sizeof(fr.claude), home,
".claude", "projects");
}
v = conf("hermes");
if (v != NULL) {
hermes_list(v);
} else if ((v = getenv("SPLINTER_FOREIGN_HERMES")) != NULL) {
hermes_list(v);
} else if (home[0] != '\0') {
DIR *d;
struct dirent *e;
hermes_add("~/.hermes");
/* profiles and stubs sit next to it as ~/.hermes-NAME */
d = opendir(home);
while (d != NULL && (e = readdir(d)) != NULL) {
char cand[FR_PATH];
if (strncmp(e->d_name, ".hermes-", 8) != 0)
continue;
if (path_join(cand, sizeof(cand), home, e->d_name,
NULL) == 0)
hermes_add(cand);
}
if (d != NULL)
closedir(d);
}
v = conf("opencode");
if (v == NULL)
v = getenv("SPLINTER_FOREIGN_OPENCODE");
if (v != NULL && *v != '\0') {
(void)path_expand(v, fr.opencode, sizeof(fr.opencode));
} else {
const char *xdg = getenv("XDG_DATA_HOME");
if (xdg != NULL && *xdg != '\0')
(void)path_join(fr.opencode, sizeof(fr.opencode), xdg,
"opencode", "opencode.db");
else if (home[0] != '\0')
(void)path_join(fr.opencode, sizeof(fr.opencode), home,
".local/share/opencode", "opencode.db");
}
if (conf("max_bytes") != NULL) {
unsigned long mb = strtoul(conf("max_bytes"), NULL, 10);
if (mb >= 65536)
fr.max_bytes = (size_t)mb;
}
if (conf("limit") != NULL)
fr.limit = atoi(conf("limit"));
if (fr.limit < 1 || fr.limit > 200)
fr.limit = 25;
/* everything above is visible before the flag that says so */
__atomic_store_n(&fr_ready, 1, __ATOMIC_RELEASE);
pthread_mutex_unlock(&fr_init_mu);
}
static enum fr_src
src_of(const char *s)
{
if (s == NULL)
return SRC_NONE;
if (strcmp(s, "claude") == 0 || strcmp(s, "claude-code") == 0)
return SRC_CLAUDE;
if (strcmp(s, "hermes") == 0)
return SRC_HERMES;
if (strcmp(s, "opencode") == 0 || strcmp(s, "opencode-go") == 0 ||
strcmp(s, "oc") == 0)
return SRC_OPENCODE;
return SRC_NONE;
}
/* ------------------------------------------------------------------- child */
/*
* Run a program with an argument vector and capture stdout. No shell: a
* session id from a tool call must not be able to become an argument, let
* alone a command. The child only does dup2/execv/_exit, which is safe after
* fork() in a process that has threads.
*/
static int
run_argv(char *const argv[], struct sp_buf *out, char *err, size_t errcap,
int timeout_s, size_t cap_bytes)
{
int op[2], ep[2], status = 0, rc = -1, dead = 0, over = 0;
pid_t child;
time_t deadline;
if (err != NULL && errcap > 0)
err[0] = '\0';
if (pipe(op) != 0)
return -1;
if (pipe(ep) != 0) {
close(op[0]);
close(op[1]);
return -1;
}
child = fork();
if (child < 0) {
close(op[0]);
close(op[1]);
close(ep[0]);
close(ep[1]);
return -1;
}
if (child == 0) {
(void)setpgid(0, 0);
close(op[0]);
close(ep[0]);
if (dup2(op[1], STDOUT_FILENO) < 0 ||
dup2(ep[1], STDERR_FILENO) < 0)
_exit(127);
close(op[1]);
close(ep[1]);
execv(argv[0], argv);
_exit(127);
}
(void)setpgid(child, child);
close(op[1]);
close(ep[1]);
deadline = time(NULL) + (timeout_s > 0 ? timeout_s : FR_SQL_TIMEOUT);
while (!dead && !over) {
struct pollfd pfd[2];
int pr;
if (time(NULL) > deadline) {
(void)kill(-child, SIGKILL);
if (err != NULL)
snprintf(err, errcap, "timed out after %d s",
timeout_s > 0 ? timeout_s : FR_SQL_TIMEOUT);
over = 1;
break;
}
pfd[0].fd = op[0];
pfd[0].events = POLLIN;
pfd[0].revents = 0;
pfd[1].fd = ep[0];
pfd[1].events = POLLIN;
pfd[1].revents = 0;
pr = poll(pfd, 2, 200);
if (pr < 0) {
if (errno == EINTR)
continue;
break;
}
if (pr == 0)
continue;
if ((pfd[0].revents & (POLLIN | POLLHUP)) != 0) {
char chunk[8192];
ssize_t got = read(op[0], chunk, sizeof(chunk));
if (got < 0 && errno != EINTR)
break;
if (got == 0) {
close(op[0]);
op[0] = -1;
} else if (out != NULL && out->len + (size_t)got <=
cap_bytes) {
if (sp_buf_add(out, chunk, (size_t)got) != 0)
break;
} else {
(void)kill(-child, SIGKILL);
if (err != NULL)
snprintf(err, errcap, "output larger than "
"%zu bytes", cap_bytes);
over = 1;
break;
}
}
if ((pfd[1].revents & (POLLIN | POLLHUP)) != 0) {
char chunk[2048];
ssize_t got = read(ep[0], chunk, sizeof(chunk));
if (got > 0 && err != NULL && errcap > 0) {
size_t have = strlen(err);
if (have + (size_t)got < errcap - 1)
memcpy(err + have, chunk, (size_t)got);
} else if (got == 0) {
close(ep[0]);
ep[0] = -1;
}
}
if (op[0] < 0 && ep[0] < 0)
dead = 1;
}
if (op[0] >= 0)
close(op[0]);
if (ep[0] >= 0)
close(ep[0]);
while (waitpid(child, &status, 0) < 0 && errno == EINTR)
;
if (!over && WIFEXITED(status) && WEXITSTATUS(status) == 0)
rc = 0;
else if (!over && err != NULL && err[0] == '\0')
snprintf(err, errcap, "exit status %d",
WIFEXITED(status) ? WEXITSTATUS(status) : -1);
return rc;
}
/* where the sqlite3 CLI is, resolved before fork so the child only execs */
static const char *
sqlite3_bin(void)
{
static const char *cand[] = {
"/usr/bin/sqlite3", "/usr/local/bin/sqlite3", "/bin/sqlite3",
"/opt/homebrew/bin/sqlite3", NULL
};
const char *env = getenv("SPLINTER_SQLITE3");
size_t i;
if (env != NULL && *env != '\0' && access(env, X_OK) == 0)
return env;
for (i = 0; cand[i] != NULL; i++)
if (access(cand[i], X_OK) == 0)
return cand[i];
return NULL;
}
/*
* One read-only query, answered as a JSON array. -batch keeps the CLI from
* drawing a prompt or a table and -json makes it parseable with the same
* parser the rest of the harness uses; the .timeout waits out a writer
* instead of failing on a busy WAL.
*/
static mcp_json *
sql_json(const char *db, const char *sql, char *err, size_t errcap)
{
struct sp_buf out;
char *argv[9];
const char *bin = sqlite3_bin();
mcp_json *v = NULL;
int rc_ok = 0;
if (bin == NULL) {
if (err != NULL)
snprintf(err, errcap, "sqlite3 not found (set "
"SPLINTER_SQLITE3)");
return NULL;
}
if (sp_buf_init(&out) != 0)
return NULL;
argv[0] = (char *)bin;
argv[1] = (char *)"-readonly";
argv[2] = (char *)"-batch";
argv[3] = (char *)"-json";
argv[4] = (char *)"-cmd";
argv[5] = (char *)".timeout 3000";
argv[6] = (char *)db;
argv[7] = (char *)sql;
argv[8] = NULL;
if (run_argv(argv, &out, err, errcap, FR_SQL_TIMEOUT, FR_SQL_BYTES) != 0) {
sp_buf_free(&out);
return NULL;
}
rc_ok = 1;
if (out.p != NULL && out.len > 0) {
v = mcp_parse(out.p);
if (v == NULL && err != NULL)
snprintf(err, errcap, "unparsable sqlite output: %.100s",
out.p);
} else if (rc_ok) {
/*
* sqlite3 -json prints nothing when the query matched no row.
* That is an empty answer, not a failure: returning NULL made
* every caller take its "query failed" branch, so a session
* whose rows had already been read once (or a count that was
* zero) looked like a broken database.
*/
v = mcp_parse("[]");
}
sp_buf_free(&out);
return v;
}
/* a string literal for SQL; the caller passes text, never SQL */
static const char *
sql_lit(struct sp_buf *b, const char *s)
{
const char *p;
sp_buf_clear(b);
if (sp_buf_puts(b, "'") != 0)
return "''";
for (p = s; *p != '\0'; p++) {
if (*p == '\'') {
if (sp_buf_puts(b, "''") != 0)
return "''";
} else if (sp_buf_add(b, p, 1) != 0) {
return "''";
}
}
if (sp_buf_puts(b, "'") != 0)
return "''";
return b->p != NULL ? b->p : "''";
}
/* ------------------------------------------------------------- transcript */
struct frec {
char *role;
char *text;
char *name;
char *call_id;
char *calls; /* raw JSON array, OpenAI shape */
};
struct fconv {
struct frec *v;
size_t n;
size_t cap;
size_t bytes;
int truncated;
};
static void
frec_free(struct frec *r)
{
free(r->role);
free(r->text);
free(r->name);
free(r->call_id);
free(r->calls);
memset(r, 0, sizeof(*r));
}
static void
fconv_free(struct fconv *c)
{
size_t i;
if (c == NULL)
return;
for (i = 0; i < c->n; i++)
frec_free(&c->v[i]);
free(c->v);
memset(c, 0, sizeof(*c));
}
static size_t
str_cap(size_t n, size_t max)
{
return n > max ? max : n;
}
static struct frec *
fconv_add(struct fconv *c, const char *role, const char *text, const char *name,
const char *call_id, const char *calls)
{
struct frec *r;
size_t n = str_cap(text != NULL ? strlen(text) : 0,
4u * 1024 * 1024);
if (c->n >= FR_MAX_MSG || c->bytes >= fr.max_bytes) {
c->truncated = 1;
return NULL;
}
if (c->n == c->cap) {
size_t ncap = c->cap == 0 ? 16 : c->cap * 2;
struct frec *nv = realloc(c->v, ncap * sizeof(*nv));
if (nv == NULL)
return NULL;
c->v = nv;
c->cap = ncap;
}
r = &c->v[c->n];
memset(r, 0, sizeof(*r));
r->role = strdup(role != NULL ? role : "user");
r->text = calloc(1, n + 1);
if (r->text != NULL && text != NULL)
memcpy(r->text, text, n);
if (r->role == NULL || r->text == NULL ||
(name != NULL && (r->name = strdup(name)) == NULL) ||
(call_id != NULL && (r->call_id = strdup(call_id)) == NULL) ||
(calls != NULL && (r->calls = strdup(calls)) == NULL)) {
frec_free(r);
return NULL;
}
c->n++;
c->bytes += n + 24;
return r;
}
/* Every tool call needs its observation and every observation its call: a
* provider rejects a transcript where one side is missing (OpenAI: tool_calls
* must be followed by tool messages; Anthropic: a tool_result without a
* tool_use). Foreign transcripts are usually paired, a truncated import or a
* compacted log is not - so the pairing is enforced here, once, instead of
* leaving a session that fails on its first resumed request. */
static int
has_str(char **v, size_t n, const char *s)
{
size_t i;
for (i = 0; i < n; i++)
if (strcmp(v[i], s) == 0)
return 1;
return 0;
}
static void
calls_keep(struct frec *r, char **answered, size_t nans, char ***kept,
size_t *nkept)
{
mcp_json *arr = mcp_parse(r->calls);
struct sp_buf b;
size_t k;
int any = 0;
free(r->calls);
r->calls = NULL;
if (arr == NULL || arr->t != MCP_ARR) {
mcp_json_free(arr);
return;
}
if (sp_buf_init(&b) != 0) {
mcp_json_free(arr);
return;
}
for (k = 0; k < mcp_array_len(arr); k++) {
const mcp_json *one = mcp_array_at(arr, k);
const char *id = mcp_arg_string(one, "id");
struct sp_buf one_buf;
if (id == NULL || !has_str(answered, nans, id))
continue;
if (sp_buf_init(&one_buf) != 0)
break;
if (sp_json_emit(&one_buf, one) == 0 && one_buf.p != NULL) {
if ((any && sp_buf_puts(&b, ",") != 0) ||
sp_buf_puts(&b, one_buf.p) != 0) {
sp_buf_free(&one_buf);
break;
}
any = 1;
if (!has_str(*kept, *nkept, id)) {
char **nv = realloc(*kept, (*nkept + 1) *
sizeof(**kept));
if (nv != NULL) {
*kept = nv;
(*kept)[*nkept] = strdup(id);
if ((*kept)[*nkept] != NULL)
(*nkept)++;
}
}
}
sp_buf_free(&one_buf);
}
mcp_json_free(arr);
if (any && b.len > 0) {
struct sp_buf full;
if (sp_buf_init(&full) == 0) {
if (sp_buf_puts(&full, "[") == 0 &&
sp_buf_puts(&full, b.p) == 0 &&
sp_buf_puts(&full, "]") == 0)
r->calls = strdup(full.p);
sp_buf_free(&full);
}
}
sp_buf_free(&b);
}
static void
fconv_pair(struct fconv *c)
{
char **answered = NULL, **kept = NULL;
size_t nans = 0, nkept = 0, i, out = 0;
answered = calloc(c->n + 1, sizeof(*answered));
if (answered == NULL)
return;
/* an observation that says nothing still answers its call */
for (i = 0; i < c->n; i++) {
struct frec *r = &c->v[i];
if (strcmp(r->role, "tool") != 0)
continue;
if (r->text[0] == '\0') {
free(r->text);
r->text = strdup("(no output)");
if (r->text == NULL)
r->text = strdup("");
}
if (r->call_id != NULL) {
answered[nans] = strdup(r->call_id);
if (answered[nans] != NULL)
nans++;
}
}
for (i = 0; i < c->n; i++)
if (strcmp(c->v[i].role, "assistant") == 0 &&
c->v[i].calls != NULL && c->v[i].calls[0] != '\0')
calls_keep(&c->v[i], answered, nans, &kept, &nkept);
/* drop observations whose call did not survive, and empty records */
for (i = 0; i < c->n; i++) {
struct frec *r = &c->v[i];
int keep = 1;
if (strcmp(r->role, "tool") == 0 &&
(r->call_id == NULL || !has_str(kept, nkept, r->call_id)))
keep = 0;
if ((r->text == NULL || r->text[0] == '\0') &&
(r->calls == NULL || r->calls[0] == '\0'))
keep = 0;
if (!keep) {
frec_free(r);
continue;
}
c->v[out++] = *r;
}
c->n = out;
for (i = 0; i < nans; i++)
free(answered[i]);
free(answered);
for (i = 0; i < nkept; i++)
free(kept[i]);
free(kept);
}
/* one line, no control bytes, at most cap-1 bytes of UTF-8 */
static void
one_line(const char *text, char *out, size_t cap)
{
const char *p = text != NULL ? text : "";
size_t n = 0;
if (cap == 0)
return;
while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
p++;
while (*p != '\0' && *p != '\n' && *p != '\r' && n + 1 < cap) {
unsigned char ch = (unsigned char)*p;
out[n++] = (ch < 0x20 || ch == 0x7f) ? ' ' : (char)ch;
p++;
}
while (n > 0 && out[n - 1] == ' ')
n--;
/*
* A cut in the middle of a UTF-8 sequence leaves a lead byte without
* enough continuation bytes; drop the whole character.
*/
while (n > 0) {
size_t start = n, need;
unsigned char ch;
while (start > 0 && ((unsigned char)out[start - 1] & 0xC0) == 0x80)
start--;
if (start == 0)
break;
ch = (unsigned char)out[start - 1];
need = (ch & 0x80) == 0 ? 1 : (ch & 0xE0) == 0xC0 ? 2 :
(ch & 0xF0) == 0xE0 ? 3 : (ch & 0xF8) == 0xF0 ? 4 : 0;
if (need == 0 || n - (start - 1) < need)
n = start - 1;
else
break;
}
out[n] = '\0';
}
/* case-blind substring, and where it is */
static int
has_ci(const char *hay, const char *needle)
{
size_t i, n = strlen(needle);
const char *p;
if (n == 0)
return 1;
for (p = hay; *p != '\0'; p++) {
for (i = 0; i < n && p[i] != '\0'; i++)
if (tolower((unsigned char)p[i]) !=
tolower((unsigned char)needle[i]))
break;
if (i == n)
return 1;
}
return 0;
}
static long
find_ci(const char *hay, const char *needle)
{
size_t i, n = strlen(needle);
const char *p;
for (p = hay; *p != '\0'; p++) {
for (i = 0; i < n && p[i] != '\0'; i++)
if (tolower((unsigned char)p[i]) !=
tolower((unsigned char)needle[i]))
break;
if (i == n)
return (long)(p - hay);
}
return -1;
}
static void
snippet(struct sp_buf *b, const char *text, const char *query, size_t cap)
{
long at = find_ci(text, query);
size_t len = strlen(text), from = 0, n, i;
if (at > 60)
from = (size_t)at - 60;
n = len - from;
if (n > cap)
n = cap;
if (from > 0)
sp_buf_puts(b, "...");
for (i = 0; i < n; i++) {
char ch = text[from + i];
if ((unsigned char)ch < 0x20 || (unsigned char)ch == 0x7f)
ch = ' ';
(void)sp_buf_add(b, &ch, 1);
}
if (from + n < len)
sp_buf_puts(b, "...");
}
static void
stamp_of(long secs, char *buf, size_t cap)
{
struct tm tm;
if (secs <= 0 || localtime_r(&(time_t){ secs }, &tm) == NULL) {
snprintf(buf, cap, "?");
return;
}
strftime(buf, cap, "%Y-%m-%d %H:%M", &tm);
}
/* a content value as text: a string, or the text blocks of an array */
static void
content_text(const mcp_json *content, struct sp_buf *out)
{
size_t i;
if (content == NULL)
return;
if (content->t == MCP_STR) {
const char *p = mcp_json_string(content);
if (p != NULL)
(void)sp_buf_puts(out, p);
return;
}
if (content->t != MCP_ARR)
return;
for (i = 0; i < mcp_array_len(content); i++) {
const mcp_json *blk = mcp_array_at(content, i);
const char *type = mcp_arg_string(blk, "type");
const char *text;
if (type == NULL)
continue;
text = mcp_arg_string(blk, "text");
if (text != NULL && strcmp(type, "text") == 0) {
if (out->len > 0)
(void)sp_buf_puts(out, "\n");
(void)sp_buf_puts(out, text);
} else if (strcmp(type, "image") == 0) {
if (out->len > 0)
(void)sp_buf_puts(out, "\n");
(void)sp_buf_puts(out, "[image omitted]");
}
}
}
/* the arguments of a call, as the JSON text OpenAI's shape wants */
static void
args_text(const mcp_json *input, struct sp_buf *out)
{
sp_buf_clear(out);
if (input == NULL || input->t == MCP_NULL) {
(void)sp_buf_puts(out, "{}");
return;
}
if (sp_json_emit(out, input) != 0 || out->len == 0) {
sp_buf_clear(out);
(void)sp_buf_puts(out, "{}");
}
}
/*
* One tool call as it goes into a `calls` array: the OpenAI shape the session
* file and the provider both read. The brackets belong here, not to the
* callers: `calls_keep` parses what this produces as an array, and a run of
* elements without them parsed as nothing, so every imported tool call was
* dropped and the import kept only the prose around it.
*/
static void
calls_append(struct sp_buf *b, const char *id, const char *name,
const char *args)
{
int first = b->len == 0;
if (sp_buf_printf(b, "%s{\"id\":\"", first ? "[" : ",") != 0 ||
sp_json_escape(b, id != NULL ? id : "call") != 0 ||
sp_buf_puts(b, "\",\"type\":\"function\",\"function\":{\"name\":\"") !=
0 ||
sp_json_escape(b, name != NULL ? name : "tool") != 0 ||
sp_buf_puts(b, "\",\"arguments\":\"") != 0 ||
sp_json_escape(b, args != NULL ? args : "{}") != 0)
return;
(void)sp_buf_puts(b, "\"}}");
}
/*
* Hand the finished array to the record writer and leave the buffer empty for
* the next message. The closing bracket is written here, once, so a call site
* cannot forget it: `calls_append` writes elements, this makes them an array.
*/
static const char *
calls_take(struct sp_buf *b)
{
if (b->len == 0)
return NULL;
if (sp_buf_puts(b, "]") != 0)
return NULL;
return b->p;
}
/* after the record is written, the buffer starts over */
static void
calls_done(struct sp_buf *b)
{
sp_buf_clear(b);
}
/* ------------------------------------------------------------------- ids */
static int
valid_id(const char *id)
{
size_t i, n;
if (id == NULL || *id == '\0')
return 0;
n = strlen(id);
if (n >= 64)
return 0;
for (i = 0; i < n; i++)
if (!((id[i] >= 'a' && id[i] <= 'z') ||
(id[i] >= 'A' && id[i] <= 'Z') ||
(id[i] >= '0' && id[i] <= '9') ||
id[i] == '-' || id[i] == '_' || id[i] == '.'))
return 0;
return strstr(id, "..") == NULL;
}
/* a foreign id, made into one splinter's session file names accept */
static void
import_id(enum fr_src s, const char *foreign, char *out, size_t cap)
{
size_t i, n;
snprintf(out, cap, "%s", src_tag[s]);
n = strlen(out);
for (i = 0; foreign[i] != '\0' && n + 1 < cap && n < 60; i++) {
unsigned char ch = (unsigned char)foreign[i];
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') || ch == '-' || ch == '_' ||
ch == '.')
out[n++] = (char)ch;
else
out[n++] = '-';
}
out[n] = '\0';
while (n > 0 && out[n - 1] == '.')
out[--n] = '\0';
{
char *dot;
while (n > 0 && (dot = strstr(out, "..")) != NULL)
dot[1] = '-';
}
}
/* ------------------------------------------------------------------ claude */
/* <claude>/<slug>/<id>.jsonl across every project directory */
static int
claude_find(const char *id, char *out, size_t cap)
{
DIR *d;
struct dirent *e;
int found = -1;
d = opendir(fr.claude);
if (d == NULL)
return -1;
while ((e = readdir(d)) != NULL) {
char path[FR_PATH];
if (e->d_name[0] == '.')
continue;
if (path_join(path, sizeof(path), fr.claude, e->d_name, id)
!= 0)
continue;
{
size_t pl = strlen(path);
if (pl + 7 >= sizeof(path))
continue;
memcpy(path + pl, ".jsonl", 7);
}
if (access(path, R_OK) == 0) {
snprintf(out, cap, "%s", path);
found = 0;
break;
}
}
closedir(d);
return found;
}
struct fbrief {
char id[96];
char title[FR_TITLE];
char cwd[512];
long mtime;
size_t bytes;
};
static int
brief_cmp(const void *a, const void *b)
{
const struct fbrief *x = a, *y = b;
if (x->mtime != y->mtime)
return x->mtime < y->mtime ? 1 : -1;
return strcmp(x->id, y->id);
}
/*
* A claude file's title and directory without reading all of it: cwd rides on
* every line, the title is an ai-title line, and the first real user text is
* the fallback splinter itself uses for an untitled session.
*/
static void
claude_head(const char *path, struct fbrief *b)
{
char *line = NULL;
size_t linecap = 0, read = 0;
FILE *f = fopen(path, "r");
b->title[0] = '\0';
b->cwd[0] = '\0';
if (f == NULL)
return;
while (read < FR_HEAD_BYTES && getline(&line, &linecap, f) > 0) {
mcp_json *o;
read += strlen(line);
if (line[0] != '{')
continue;
o = mcp_parse(line);
if (o == NULL)
continue;
if (b->cwd[0] == '\0') {
const char *cwd = mcp_arg_string(o, "cwd");
if (cwd != NULL)
snprintf(b->cwd, sizeof(b->cwd), "%s", cwd);
}
if (b->title[0] == '\0' &&
strstr(line, "\"type\":\"ai-title\"") != NULL) {
const char *t = mcp_arg_string(o, "aiTitle");
if (t != NULL)
one_line(t, b->title, sizeof(b->title));
}
if (b->title[0] == '\0' &&
strstr(line, "\"type\":\"user\"") != NULL &&
strstr(line, "\"tool_result\"") == NULL &&
strstr(line, "\"isSidechain\":true") == NULL) {
const mcp_json *m = mcp_arg(o, "message");
struct sp_buf text;
if (sp_buf_init(&text) == 0) {
content_text(m != NULL ? mcp_arg(m, "content") :
NULL, &text);
if (text.len > 0)
one_line(text.p, b->title,
sizeof(b->title));
sp_buf_free(&text);
}
}
mcp_json_free(o);
if (b->title[0] != '\0' && b->cwd[0] != '\0')
break;
}
free(line);
fclose(f);
/* a checkpoint prefix is not a title */
while (b->title[0] == '<')
memmove(b->title, b->title + 1, strlen(b->title));
if (b->title[0] == '\0')
snprintf(b->title, sizeof(b->title), "(untitled)");
}
/* the project directory Claude Code uses for a working directory: the path
* with every separator as '-', under <claude>/ */
static int
claude_slug_dir(const char *cwd, char *out, size_t cap)
{
char full[FR_PATH];
size_t i, n = 0;
/* '~'-free absolute path or nothing; the check used to be inverted, so
* every real directory looked unusable and the slug lookup never ran */
if (cwd == NULL || cwd[0] == '\0')
return -1;
{
size_t need = strlen(cwd) + strlen(fr.claude) + 2;
if (need > sizeof(full))
return -1;
}
n = (size_t)snprintf(full, sizeof(full), "%s/", fr.claude);
for (i = 0; cwd[i] != '\0' && n + 1 < sizeof(full); i++)
full[n++] = cwd[i] == '/' ? '-' : cwd[i];
full[n] = '\0';
if (access(full, R_OK) != 0)
return -1;
snprintf(out, cap, "%s", full);
return 0;
}
/* one claude project directory's sessions */
static void
claude_dir(const char *proj, const char *only_cwd, struct fbrief *v, size_t max,
size_t *n)
{
DIR *pd = opendir(proj);
struct dirent *pe;
while (pd != NULL && (pe = readdir(pd)) != NULL && *n < max) {
char path[FR_PATH];
struct stat st;
size_t len;
struct fbrief *b;
len = strlen(pe->d_name);
if (len < 7 || strcmp(pe->d_name + len - 6, ".jsonl") != 0)
continue;
if (len - 6 >= sizeof(v[0].id))
continue;
snprintf(path, sizeof(path), "%s/%s", proj, pe->d_name);
if (stat(path, &st) != 0 || !S_ISREG(st.st_mode))
continue;
b = &v[*n];
memset(b, 0, sizeof(*b));
memcpy(b->id, pe->d_name, len - 6);
b->id[len - 6] = '\0';
b->mtime = (long)st.st_mtime;
b->bytes = (size_t)st.st_size;
claude_head(path, b);
if (only_cwd != NULL && *only_cwd != '\0' &&
strcmp(b->cwd, only_cwd) != 0)
continue;
(*n)++;
}
if (pd != NULL)
closedir(pd);
}
static int
list_claude(const char *only_cwd, struct fbrief *v, size_t max, size_t *n,
char *err, size_t errcap)
{
char one[FR_PATH] = "";
DIR *d;
*n = 0;
/*
* A working directory maps to one project directory by name, so the
* common case reads 2 files instead of 143. A cwd that does not map
* (no such slug) still gets the fallback below: the slug is Claude
* Code's convention, not a promise about this tree.
*/
if (only_cwd != NULL && *only_cwd != '\0' &&
claude_slug_dir(only_cwd, one, sizeof(one)) == 0) {
claude_dir(one, only_cwd, v, max, n);
qsort(v, *n, sizeof(*v), brief_cmp);
return 0;
}
d = opendir(fr.claude);
if (d == NULL) {
snprintf(err, errcap, "%s: %s",
fr.claude[0] != '\0' ? fr.claude : "(unset)",
strerror(errno));
return -1;
}
while (d != NULL) {
struct dirent *e = readdir(d);
char proj[FR_PATH];
if (e == NULL)
break;
if (e->d_name[0] == '.')
continue;
if (path_join(proj, sizeof(proj), fr.claude, e->d_name,
NULL) != 0)
continue;
claude_dir(proj, only_cwd, v, max, n);
}
closedir(d);
qsort(v, *n, sizeof(*v), brief_cmp);
return 0;
}
static int
count_claude(void)
{
DIR *d = opendir(fr.claude);
int n = 0;
while (d != NULL) {
struct dirent *e = readdir(d);
char proj[FR_PATH];
DIR *pd;
struct dirent *pe;
if (e == NULL)
break;
if (e->d_name[0] == '.')
continue;
if (path_join(proj, sizeof(proj), fr.claude, e->d_name,
NULL) != 0)
continue;
pd = opendir(proj);
if (pd == NULL)
continue;
while ((pe = readdir(pd)) != NULL) {
size_t len = strlen(pe->d_name);
if (len > 6 && strcmp(pe->d_name + len - 6, ".jsonl") == 0)
n++;
}
closedir(pd);
}
if (d != NULL)
closedir(d);
return n;
}
/*
* One claude line as a hit: the text blocks of the message it carries, with
* the query as the anchor. The raw line is JSON-escaped, so it is parsed
* instead of sliced.
*/
static void
claude_hit(struct sp_buf *out, const char *id, const char *line,
const char *query, int *hits)
{
mcp_json *o = mcp_parse(line);
const char *type;
const mcp_json *m, *content;
struct sp_buf text;
if (o == NULL)
return;
type = mcp_arg_string(o, "type");
m = mcp_arg(o, "message");
content = m != NULL ? mcp_arg(m, "content") : NULL;
if (type == NULL || content == NULL) {
mcp_json_free(o);
return;
}
if (sp_buf_init(&text) != 0) {
mcp_json_free(o);
return;
}
content_text(content, &text);
if (text.len > 0 && has_ci(text.p, query)) {
sp_buf_printf(out, " claude %s %s: ", id, type);
snippet(out, text.p, query, 200);
(void)sp_buf_puts(out, "\n");
(*hits)++;
} else if (has_ci(line, query)) {
/* the hit is in an argument, not in the text: say so */
sp_buf_printf(out, " claude %s %s: ", id, type);
snippet(out, line, query, 160);
(void)sp_buf_puts(out, "\n");
(*hits)++;
}
sp_buf_free(&text);
mcp_json_free(o);
}
/* does this transcript claim to have run in `cwd`? -1 when it does not say */
static int
claude_cwd_is(const char *path, const char *cwd)
{
struct fbrief b;
memset(&b, 0, sizeof(b));
claude_head(path, &b);
if (b.cwd[0] == '\0')
return -1;
return strcmp(b.cwd, cwd) == 0;
}
/*
* Search one claude project directory. `only_cwd` filters per file unless the
* caller already picked the directory by slug -- then the file's own claim is
* what decides, because a transcript can sit in a slug directory and say it
* ran somewhere else (the fixture that guards the list has exactly this).
*/
static int
search_claude_dir(const char *proj, const char *only_cwd, const char *query,
int limit, int days, struct sp_buf *out, int *hits)
{
DIR *pd = opendir(proj);
struct dirent *pe;
long now = (long)time(NULL);
while (pd != NULL && (pe = readdir(pd)) != NULL && *hits < limit) {
char path[FR_PATH], id[96], *line = NULL;
size_t len, linecap = 0;
struct stat st;
FILE *f;
len = strlen(pe->d_name);
if (len < 7 || strcmp(pe->d_name + len - 6, ".jsonl") != 0)
continue;
if (len - 6 >= sizeof(id))
continue;
memcpy(id, pe->d_name, len - 6);
id[len - 6] = '\0';
if (path_join(path, sizeof(path), proj, pe->d_name, NULL) != 0)
continue;
if (stat(path, &st) != 0 || !S_ISREG(st.st_mode))
continue;
if (days > 0 && (long)st.st_mtime < now - (long)days * 86400)
continue;
if (only_cwd != NULL && claude_cwd_is(path, only_cwd) != 1)
continue;
/*
* A byte search first: 500 MB of transcripts is not something to
* parse line by line, and only a file that matches gets the JSON
* pass.
*/
f = fopen(path, "r");
if (f == NULL)
continue;
while (*hits < limit && getline(&line, &linecap, f) > 0) {
if (!has_ci(line, query))
continue;
if (strstr(line, "\"isSidechain\":true") != NULL)
continue;
claude_hit(out, id, line, query, hits);
}
free(line);
fclose(f);
}
if (pd != NULL)
closedir(pd);
return *hits;
}
static int
search_claude(const char *query, int limit, int days, struct sp_buf *out,
const char *only_cwd)
{
DIR *d;
int hits = 0;
char one[FR_PATH];
/*
* A cwd maps to one project directory by name. Reading only that one
* turns a walk over every project into the two files that can match --
* and it is the same rule the list uses, so both answer the same
* question the same way.
*/
if (only_cwd != NULL && *only_cwd != '\0' &&
claude_slug_dir(only_cwd, one, sizeof(one)) == 0)
return search_claude_dir(one, only_cwd, query, limit, days, out,
&hits);
d = opendir(fr.claude);
if (d == NULL)
return 0;
while (d != NULL) {
struct dirent *e = readdir(d);
char proj[FR_PATH];
if (e == NULL)
break;
if (e->d_name[0] == '.')
continue;
if (path_join(proj, sizeof(proj), fr.claude, e->d_name,
NULL) != 0)
continue;
search_claude_dir(proj, only_cwd, query, limit, days, out, &hits);
}
closedir(d);
return hits;
}
static int
load_claude(const char *id, struct fconv *conv, char *err, size_t errcap)
{
char path[FR_PATH], *line = NULL;
size_t linecap = 0;
FILE *f;
/* the assistant message being assembled: one per message id */
struct {
char id[80];
int used;
struct sp_buf text;
struct sp_buf calls;
} p;
struct {
char id[80];
char name[80];
} names[256];
size_t nnames = 0;
if (claude_find(id, path, sizeof(path)) != 0) {
snprintf(err, errcap, "no claude session '%s'", id);
return -1;
}
f = fopen(path, "r");
if (f == NULL) {
snprintf(err, errcap, "cannot read the claude session: %s",
strerror(errno));
return -1;
}
memset(&p, 0, sizeof(p));
(void)sp_buf_init(&p.text);
(void)sp_buf_init(&p.calls);
while (getline(&line, &linecap, f) > 0) {
mcp_json *o;
const char *type;
const mcp_json *m, *content;
size_t i;
if (line[0] != '{' || strlen(line) > FR_MAX_LINE)
continue;
o = mcp_parse(line);
if (o == NULL)
continue;
type = mcp_arg_string(o, "type");
if (type == NULL || (strcmp(type, "user") != 0 &&
strcmp(type, "assistant") != 0)) {
mcp_json_free(o);
continue;
}
/* a subagent's sidechain is a different conversation */
if (mcp_arg_bool(o, "isSidechain", 0)) {
mcp_json_free(o);
continue;
}
m = mcp_arg(o, "message");
content = m != NULL ? mcp_arg(m, "content") : NULL;
if (content == NULL) {
mcp_json_free(o);
continue;
}
if (strcmp(type, "assistant") == 0) {
const char *mid = mcp_arg_string(m, "id");
/* one message can arrive as several lines */
if (!p.used || (mid != NULL && p.id[0] != '\0' &&
strcmp(mid, p.id) != 0)) {
if (p.used) {
(void)fconv_add(conv, "assistant",
p.text.p, NULL, NULL,
calls_take(&p.calls));
calls_done(&p.calls);
}
p.used = 1;
p.id[0] = '\0';
sp_buf_clear(&p.text);
sp_buf_clear(&p.calls);
snprintf(p.id, sizeof(p.id), "%s",
mid != NULL ? mid : "");
}
for (i = 0; content->t == MCP_ARR &&
i < mcp_array_len(content); i++) {
const mcp_json *blk = mcp_array_at(content, i);
const char *bt = mcp_arg_string(blk, "type");
const char *t;
if (bt == NULL)
continue;
t = mcp_arg_string(blk, "text");
if (strcmp(bt, "text") == 0 && t != NULL) {
if (p.text.len > 0)
(void)sp_buf_puts(&p.text, "\n");
(void)sp_buf_puts(&p.text, t);
} else if (strcmp(bt, "tool_use") == 0) {
const char *cid = mcp_arg_string(blk,
"id");
const char *name = mcp_arg_string(blk,
"name");
struct sp_buf args;
if (sp_buf_init(&args) != 0)
continue;
args_text(mcp_arg(blk, "input"), &args);
calls_append(&p.calls, cid, name,
args.p);
if (cid != NULL && name != NULL &&
nnames < 256) {
snprintf(names[nnames].id,
sizeof(names[0].id), "%s",
cid);
snprintf(names[nnames].name,
sizeof(names[0].name), "%s",
name);
nnames++;
}
sp_buf_free(&args);
}
/* thinking is not a message */
}
mcp_json_free(o);
continue;
}
/* user: tool results answer the open calls, text is the turn */
if (p.used) {
(void)fconv_add(conv, "assistant", p.text.p, NULL, NULL,
calls_take(&p.calls));
calls_done(&p.calls);
p.used = 0;
p.id[0] = '\0';
sp_buf_clear(&p.text);
sp_buf_clear(&p.calls);
}
for (i = 0; content->t == MCP_ARR &&
i < mcp_array_len(content); i++) {
const mcp_json *blk = mcp_array_at(content, i);
const char *bt = mcp_arg_string(blk, "type");
const char *t = mcp_arg_string(blk, "text");
if (bt == NULL)
continue;
if (strcmp(bt, "tool_result") == 0) {
const char *cid = mcp_arg_string(blk,
"tool_use_id");
const char *name = "tool";
struct sp_buf text;
size_t k;
if (sp_buf_init(&text) != 0)
continue;
content_text(mcp_arg(blk, "content"), &text);
for (k = 0; k < nnames; k++)
if (cid != NULL &&
strcmp(names[k].id, cid) == 0) {
name = names[k].name;
break;
}
(void)fconv_add(conv, "tool", text.p, name, cid,
NULL);
sp_buf_free(&text);
} else if (strcmp(bt, "text") == 0 && t != NULL) {
(void)fconv_add(conv, "user", t, NULL, NULL,
NULL);
}
}
if (content->t == MCP_STR) {
const char *s = mcp_json_string(content);
if (s != NULL)
(void)fconv_add(conv, "user", s, NULL, NULL,
NULL);
}
mcp_json_free(o);
}
if (p.used && (p.text.len > 0 || p.calls.len > 0)) {
(void)fconv_add(conv, "assistant", p.text.p, NULL, NULL,
calls_take(&p.calls));
calls_done(&p.calls);
}
sp_buf_free(&p.text);
sp_buf_free(&p.calls);
free(line);
fclose(f);
if (conv->n == 0) {
snprintf(err, errcap, "claude session '%s' has no messages", id);
return -1;
}
return 0;
}
/* ------------------------------------------------------------------ hermes */
static void
hermes_dbs(char dbs[][FR_PATH], size_t max, size_t *n)
{
size_t i;
*n = 0;
for (i = 0; i < fr.nhermes && *n < max; i++) {
char path[FR_PATH], pdir[FR_PATH];
struct stat st;
DIR *d;
struct dirent *e;
snprintf(path, sizeof(path), "%s/state.db", fr.hermes[i]);
if (stat(path, &st) == 0 && S_ISREG(st.st_mode))
snprintf(dbs[(*n)++], FR_PATH, "%s", path);
/* profiles under one root, each with its own state.db */
snprintf(pdir, sizeof(pdir), "%s/profiles", fr.hermes[i]);
d = opendir(pdir);
while (d != NULL && (e = readdir(d)) != NULL && *n < max) {
if (e->d_name[0] == '.')
continue;
if (path_join(path, sizeof(path), pdir, e->d_name,
"state.db") != 0)
continue;
if (stat(path, &st) == 0 && S_ISREG(st.st_mode))
snprintf(dbs[(*n)++], FR_PATH, "%s", path);
}
if (d != NULL)
closedir(d);
}
}
static int
list_hermes(const char *only_cwd, struct fbrief *v, size_t max, size_t *n,
int rows_wanted)
{
char dbs[32][FR_PATH], why[FR_PATH + 96];
size_t nd = 0, i;
struct sp_buf lit, sql;
*n = 0;
hermes_dbs(dbs, 32, &nd);
if (nd == 0)
return -1;
if (sp_buf_init(&lit) != 0 || sp_buf_init(&sql) != 0) {
sp_buf_free(&lit);
sp_buf_free(&sql);
return -1;
}
for (i = 0; i < nd && *n < max; i++) {
mcp_json *rows;
size_t k;
sp_buf_clear(&sql);
if (only_cwd != NULL && *only_cwd != '\0') {
(void)sp_buf_printf(&sql, "select id, coalesce(title,'') "
"as title, coalesce(cwd,'') as cwd, "
"cast(started_at as integer) as ts from sessions "
"where cwd = %s order by ts desc limit %d;",
sql_lit(&lit, only_cwd), rows_wanted);
} else {
(void)sp_buf_printf(&sql, "select id, coalesce(title,'') "
"as title, coalesce(cwd,'') as cwd, "
"cast(started_at as integer) as ts from sessions "
"order by ts desc limit %d;", rows_wanted);
}
/* a store that answers nothing is not an error worth stopping */
rows = sql_json(dbs[i], sql.p, why, sizeof(why));
if (rows == NULL)
continue;
for (k = 0; k < mcp_array_len(rows) && *n < max; k++) {
const mcp_json *r = mcp_array_at(rows, k);
const char *id = mcp_arg_string(r, "id");
const char *title = mcp_arg_string(r, "title");
const char *cwd = mcp_arg_string(r, "cwd");
struct fbrief *b;
if (id == NULL || strlen(id) >= sizeof(v[0].id))
continue;
b = &v[(*n)++];
memset(b, 0, sizeof(*b));
snprintf(b->id, sizeof(b->id), "%s", id);
if (title != NULL)
one_line(title, b->title, sizeof(b->title));
if (b->title[0] == '\0')
snprintf(b->title, sizeof(b->title),
"(untitled)");
if (cwd != NULL)
snprintf(b->cwd, sizeof(b->cwd), "%s", cwd);
b->mtime = (long)mcp_arg_int(r, "ts", 0);
}
mcp_json_free(rows);
}
sp_buf_free(&lit);
sp_buf_free(&sql);
qsort(v, *n, sizeof(*v), brief_cmp);
return 0;
}
static int
count_hermes(void)
{
char dbs[32][FR_PATH], why[FR_PATH + 96];
size_t nd = 0, i;
int total = 0;
hermes_dbs(dbs, 32, &nd);
for (i = 0; i < nd; i++) {
mcp_json *rows = sql_json(dbs[i],
"select count(*) as n from sessions;", why, sizeof(why));
if (rows == NULL)
continue;
total += mcp_arg_int(mcp_array_at(rows, 0), "n", 0);
mcp_json_free(rows);
}
return total;
}
static int
hermes_db_for(const char *id, char *db, size_t cap, char *err, size_t errcap)
{
char dbs[32][FR_PATH], why[FR_PATH + 96];
size_t nd = 0, i;
struct sp_buf lit, sql;
hermes_dbs(dbs, 32, &nd);
if (nd == 0) {
snprintf(err, errcap, "no hermes state.db under %zu root%s",
fr.nhermes, fr.nhermes == 1 ? "" : "s");
return -1;
}
if (sp_buf_init(&lit) != 0 || sp_buf_init(&sql) != 0) {
sp_buf_free(&lit);
sp_buf_free(&sql);
snprintf(err, errcap, "out of memory");
return -1;
}
for (i = 0; i < nd; i++) {
mcp_json *rows;
int n = 0;
sp_buf_clear(&sql);
(void)sp_buf_printf(&sql, "select count(*) as n from sessions "
"where id = %s;", sql_lit(&lit, id));
rows = sql_json(dbs[i], sql.p, why, sizeof(why));
if (rows != NULL) {
n = mcp_arg_int(mcp_array_at(rows, 0), "n", 0);
mcp_json_free(rows);
}
if (n > 0) {
if ((size_t)snprintf(db, cap, "%s", dbs[i]) >= cap) {
sp_buf_free(&lit);
sp_buf_free(&sql);
snprintf(err, errcap, "state.db path too long");
return -1;
}
sp_buf_free(&lit);
sp_buf_free(&sql);
return 0;
}
}
sp_buf_free(&lit);
sp_buf_free(&sql);
snprintf(err, errcap, "no hermes session '%s' in %zu state.db file%s",
id, nd, nd == 1 ? "" : "s");
return -1;
}
/* the stored tool_calls of a hermes row, in OpenAI's shape, rebuilt */
static void
hermes_calls(const char *raw, struct sp_buf *out)
{
mcp_json *root, *arr;
size_t i;
sp_buf_clear(out);
if (raw == NULL || raw[0] == '\0')
return;
root = mcp_parse(raw);
if (root == NULL)
return;
arr = root;
if (root->t == MCP_OBJ) {
const mcp_json *t = mcp_arg(root, "tool_calls");
if (t == NULL || t->t != MCP_ARR) {
mcp_json_free(root);
return;
}
arr = (mcp_json *)t; /* borrowed from root, freed below */
}
for (i = 0; i < mcp_array_len(arr); i++) {
const mcp_json *c = mcp_array_at(arr, i);
const mcp_json *fn = mcp_arg(c, "function");
const char *id = mcp_arg_string(c, "id");
const char *name = fn != NULL ? mcp_arg_string(fn, "name") :
mcp_arg_string(c, "name");
const char *a = fn != NULL ?
mcp_arg_string(fn, "arguments") : NULL;
struct sp_buf args;
if (name == NULL)
continue;
if (sp_buf_init(&args) != 0)
break;
if (a != NULL) {
if (sp_buf_puts(&args, a) != 0) {
sp_buf_free(&args);
break;
}
} else {
args_text(mcp_arg(c, "input"), &args);
}
calls_append(out, id, name, args.p);
sp_buf_free(&args);
}
mcp_json_free(root);
}
/* hermes stores structured content with a NUL-prefixed JSON marker */
static void
hermes_text(const char *content, struct sp_buf *out)
{
const char *p = content;
sp_buf_clear(out);
if (content == NULL)
return;
/*
* The NUL-prefixed 'json:' marker is stripped in SQL (substr(content,7)),
* not here: a content of "" is a one-byte allocation, so any strncmp
* against "\x00json:" reads past its end.
*/
if (p[0] == '{' || p[0] == '[') {
mcp_json *v = mcp_parse(p);
if (v != NULL) {
content_text(v, out);
if (out->len == 0) {
const char *t = mcp_arg_string(v, "text");
const char *c = mcp_arg_string(v, "content");
if (t != NULL)
(void)sp_buf_puts(out, t);
else if (c != NULL)
(void)sp_buf_puts(out, c);
}
mcp_json_free(v);
if (out->len > 0)
return;
}
}
(void)sp_buf_puts(out, p);
}
static int
load_hermes(const char *id, struct fconv *conv, char *err, size_t errcap)
{
char db[FR_PATH], why[FR_PATH + 96];
struct sp_buf lit, sql;
size_t offset = 0;
if (hermes_db_for(id, db, sizeof(db), err, errcap) != 0)
return -1;
if (sp_buf_init(&lit) != 0 || sp_buf_init(&sql) != 0) {
sp_buf_free(&lit);
sp_buf_free(&sql);
snprintf(err, errcap, "out of memory");
return -1;
}
for (;;) {
mcp_json *rows;
size_t i;
sp_buf_clear(&sql);
(void)sp_buf_printf(&sql, "select role, "
"case when substr(content,1,6) = char(0)||'json:' then "
"substr(content,7) else substr(content,1,%d) end as body, "
"tool_call_id, tool_calls, tool_name from messages where "
"session_id = %s and active = 1 and compacted = 0 and role "
"in ('user','assistant','tool','system') order by timestamp, "
"id limit %d offset %zu;", FR_ROW_BYTES,
sql_lit(&lit, id), FR_SQL_ROWS, offset);
rows = sql_json(db, sql.p, why, sizeof(why));
if (rows == NULL) {
snprintf(err, errcap, "%s",
why[0] != '\0' ? why : "hermes query failed");
sp_buf_free(&lit);
sp_buf_free(&sql);
return -1;
}
if (mcp_array_len(rows) == 0) {
mcp_json_free(rows);
break;
}
for (i = 0; i < mcp_array_len(rows); i++) {
const mcp_json *r = mcp_array_at(rows, i);
const char *role = mcp_arg_string(r, "role");
const char *cid = mcp_arg_string(r, "tool_call_id");
const char *name = mcp_arg_string(r, "tool_name");
struct sp_buf text, calls;
int istool;
if (role == NULL)
continue;
istool = strcmp(role, "tool") == 0;
if (sp_buf_init(&text) != 0 || sp_buf_init(&calls) != 0) {
sp_buf_free(&text);
sp_buf_free(&calls);
break;
}
hermes_text(mcp_arg_string(r, "body"), &text);
if (strcmp(role, "assistant") == 0)
hermes_calls(mcp_arg_string(r, "tool_calls"),
&calls);
(void)fconv_add(conv, role, text.p, istool ? name : NULL,
istool ? cid : NULL, calls_take(&calls));
sp_buf_free(&text);
sp_buf_free(&calls);
}
offset += mcp_array_len(rows);
mcp_json_free(rows);
if (conv->truncated)
break;
}
sp_buf_free(&lit);
sp_buf_free(&sql);
if (conv->n == 0) {
snprintf(err, errcap, "hermes session '%s' has no active "
"messages", id);
return -1;
}
return 0;
}
/* ---------------------------------------------------------------- opencode */
static int
list_opencode(const char *only_cwd, struct fbrief *v, size_t max, size_t *n,
int rows_wanted, char *err, size_t errcap)
{
struct sp_buf lit, sql;
mcp_json *rows;
char why[FR_PATH + 96] = "";
size_t i;
*n = 0;
if (fr.opencode[0] == '\0') {
snprintf(err, errcap, "no opencode database configured "
"(set opencode in the plugin config or "
"SPLINTER_FOREIGN_OPENCODE)");
return -1;
}
if (access(fr.opencode, R_OK) != 0) {
snprintf(err, errcap, "%s: %s", fr.opencode,
strerror(errno));
return -1;
}
if (sp_buf_init(&lit) != 0 || sp_buf_init(&sql) != 0) {
sp_buf_free(&lit);
sp_buf_free(&sql);
return -1;
}
/* session_v2 is current; older databases only have 'session' */
if (only_cwd != NULL && *only_cwd != '\0') {
(void)sp_buf_printf(&sql, "select id, coalesce(title,'') as "
"title, directory, cast(time_updated as integer) as updated "
"from session_v2 where directory = %s order by updated desc "
"limit %d;", sql_lit(&lit, only_cwd), rows_wanted);
} else {
(void)sp_buf_printf(&sql, "select id, coalesce(title,'') as "
"title, directory, cast(time_updated as integer) as updated "
"from session_v2 order by updated desc limit %d;",
rows_wanted);
}
rows = sql_json(fr.opencode, sql.p, why, sizeof(why));
if (rows == NULL) {
sp_buf_clear(&sql);
if (only_cwd != NULL && *only_cwd != '\0') {
(void)sp_buf_printf(&sql, "select id, coalesce(title,'') "
"as title, directory, cast(time_updated as integer) "
"as updated from session where directory = %s order "
"by updated desc limit %d;",
sql_lit(&lit, only_cwd), rows_wanted);
} else {
(void)sp_buf_printf(&sql, "select id, coalesce(title,'') "
"as title, directory, cast(time_updated as integer) "
"as updated from session order by updated desc "
"limit %d;", rows_wanted);
}
rows = sql_json(fr.opencode, sql.p, why, sizeof(why));
}
sp_buf_free(&lit);
sp_buf_free(&sql);
if (rows == NULL) {
snprintf(err, errcap, "%s", why[0] != '\0' ? why :
"query failed");
return -1;
}
for (i = 0; i < mcp_array_len(rows) && *n < max; i++) {
const mcp_json *r = mcp_array_at(rows, i);
const char *id = mcp_arg_string(r, "id");
const char *title = mcp_arg_string(r, "title");
const char *directory = mcp_arg_string(r, "directory");
struct fbrief *b;
if (id == NULL || strlen(id) >= sizeof(v[0].id))
continue;
b = &v[(*n)++];
memset(b, 0, sizeof(*b));
snprintf(b->id, sizeof(b->id), "%s", id);
if (title != NULL)
one_line(title, b->title, sizeof(b->title));
if (b->title[0] == '\0')
snprintf(b->title, sizeof(b->title), "(untitled)");
if (directory != NULL)
snprintf(b->cwd, sizeof(b->cwd), "%s", directory);
/* milliseconds since the epoch, like every opencode time */
b->mtime = (long)(mcp_arg_num(r, "updated", 0) / 1000.0);
}
mcp_json_free(rows);
return 0;
}
static int
count_opencode(void)
{
char why[FR_PATH + 96];
mcp_json *rows;
int n = 0;
if (fr.opencode[0] == '\0' || access(fr.opencode, R_OK) != 0)
return 0;
rows = sql_json(fr.opencode, "select count(*) as n from session_v2;",
why, sizeof(why));
if (rows == NULL)
rows = sql_json(fr.opencode, "select count(*) as n from session;",
why, sizeof(why));
if (rows == NULL)
return 0;
n = mcp_arg_int(mcp_array_at(rows, 0), "n", 0);
mcp_json_free(rows);
return n;
}
static void
oc_tool_output(const mcp_json *tool, struct sp_buf *out)
{
const mcp_json *state = mcp_arg(tool, "state");
const mcp_json *content = state != NULL ? mcp_arg(state, "content") :
NULL;
const mcp_json *meta = state != NULL ? mcp_arg(state, "metadata") : NULL;
const char *status = state != NULL ? mcp_arg_string(state, "status") :
NULL;
sp_buf_clear(out);
content_text(content, out);
if (out->len == 0 && meta != NULL) {
const char *o = mcp_arg_string(meta, "output");
const char *e = mcp_arg_string(meta, "error");
if (o != NULL)
(void)sp_buf_puts(out, o);
else if (e != NULL)
(void)sp_buf_puts(out, e);
}
if (out->len == 0 && status != NULL)
(void)sp_buf_printf(out, "[%s]", status);
}
/* one assistant record: its text, then its calls, then their observations */
static void
oc_assistant(struct fconv *conv, const mcp_json *data)
{
const mcp_json *content = mcp_arg(data, "content");
struct sp_buf text, calls, args, out;
size_t i;
if (sp_buf_init(&text) != 0 || sp_buf_init(&calls) != 0 ||
sp_buf_init(&args) != 0 || sp_buf_init(&out) != 0) {
sp_buf_free(&text);
sp_buf_free(&calls);
sp_buf_free(&args);
sp_buf_free(&out);
return;
}
for (i = 0; i < mcp_array_len(content); i++) {
const mcp_json *blk = mcp_array_at(content, i);
const char *bt = mcp_arg_string(blk, "type");
const char *t;
if (bt == NULL || strcmp(bt, "text") != 0)
continue; /* reasoning is not a message */
t = mcp_arg_string(blk, "text");
if (t == NULL || t[0] == '\0')
continue;
if (text.len > 0)
(void)sp_buf_puts(&text, "\n");
(void)sp_buf_puts(&text, t);
}
for (i = 0; i < mcp_array_len(content); i++) {
const mcp_json *blk = mcp_array_at(content, i);
const char *bt = mcp_arg_string(blk, "type");
const mcp_json *state;
if (bt == NULL || strcmp(bt, "tool") != 0)
continue;
state = mcp_arg(blk, "state");
args_text(state != NULL ? mcp_arg(state, "input") : NULL, &args);
calls_append(&calls, mcp_arg_string(blk, "id"),
mcp_arg_string(blk, "name"), args.p);
}
/*
* The call record goes before its observations, because a provider
* pairs them in that order; the text of the same turn rides on it.
*/
if (text.len > 0 || calls.len > 0)
(void)fconv_add(conv, "assistant", text.p, NULL, NULL,
calls_take(&calls));
for (i = 0; i < mcp_array_len(content); i++) {
const mcp_json *blk = mcp_array_at(content, i);
const char *bt = mcp_arg_string(blk, "type");
if (bt == NULL || strcmp(bt, "tool") != 0)
continue;
oc_tool_output(blk, &out);
(void)fconv_add(conv, "tool", out.p, mcp_arg_string(blk, "name"),
mcp_arg_string(blk, "id"), NULL);
}
sp_buf_free(&text);
sp_buf_free(&calls);
sp_buf_free(&args);
sp_buf_free(&out);
}
static int
oc_load_v2(const char *id, struct fconv *conv, char *why, size_t whycap)
{
struct sp_buf lit, sql;
size_t offset = 0;
for (;;) {
mcp_json *rows;
size_t i;
if (sp_buf_init(&lit) != 0 || sp_buf_init(&sql) != 0) {
sp_buf_free(&lit);
sp_buf_free(&sql);
return -1;
}
(void)sp_buf_printf(&sql, "select type, substr(data,1,%d) as data "
"from session_message where session_id = %s and type in "
"('user','assistant','system','compaction') order by seq "
"limit %d offset %zu;", FR_ROW_BYTES, sql_lit(&lit, id),
FR_SQL_ROWS, offset);
rows = sql_json(fr.opencode, sql.p, why, whycap);
sp_buf_free(&lit);
sp_buf_free(&sql);
if (rows == NULL)
return -1;
if (mcp_array_len(rows) == 0) {
mcp_json_free(rows);
return 0;
}
for (i = 0; i < mcp_array_len(rows); i++) {
const mcp_json *r = mcp_array_at(rows, i);
const char *type = mcp_arg_string(r, "type");
const char *raw = mcp_arg_string(r, "data");
mcp_json *data;
if (type == NULL || raw == NULL)
continue;
data = mcp_parse(raw);
if (data == NULL)
continue;
if (strcmp(type, "user") == 0) {
struct sp_buf t;
if (sp_buf_init(&t) == 0) {
content_text(mcp_arg(data, "text"), &t);
if (t.len > 0)
(void)fconv_add(conv, "user", t.p,
NULL, NULL, NULL);
sp_buf_free(&t);
}
} else if (strcmp(type, "assistant") == 0) {
oc_assistant(conv, data);
} else if (strcmp(type, "compaction") == 0) {
const char *sum = mcp_arg_string(data, "summary");
if (sum != NULL && sum[0] != '\0')
(void)fconv_add(conv, "system", sum,
NULL, NULL, NULL);
} else if (strcmp(type, "system") == 0) {
const char *t = mcp_arg_string(data, "text");
if (t != NULL && t[0] != '\0')
(void)fconv_add(conv, "system", t, NULL,
NULL, NULL);
}
mcp_json_free(data);
}
offset += mcp_array_len(rows);
mcp_json_free(rows);
if (conv->truncated)
return 0;
}
}
/* the pre-session_message layout: message rows plus part rows */
static int
oc_load_legacy(const char *id, struct fconv *conv, char *why, size_t whycap)
{
struct sp_buf lit, sql;
size_t offset = 0;
for (;;) {
mcp_json *rows;
size_t i;
if (sp_buf_init(&lit) != 0 || sp_buf_init(&sql) != 0) {
sp_buf_free(&lit);
sp_buf_free(&sql);
return -1;
}
(void)sp_buf_printf(&sql, "select m.data as mdata, "
"substr(p.data,1,%d) as pdata from message m join part p on "
"p.message_id = m.id where m.session_id = %s order by "
"m.time_created, p.id limit %d offset %zu;", FR_ROW_BYTES,
sql_lit(&lit, id), FR_SQL_ROWS, offset);
rows = sql_json(fr.opencode, sql.p, why, whycap);
sp_buf_free(&lit);
sp_buf_free(&sql);
if (rows == NULL)
return -1;
if (mcp_array_len(rows) == 0) {
mcp_json_free(rows);
return 0;
}
for (i = 0; i < mcp_array_len(rows); i++) {
const mcp_json *r = mcp_array_at(rows, i);
mcp_json *md = mcp_parse(mcp_arg_string(r, "mdata"));
mcp_json *pd = mcp_parse(mcp_arg_string(r, "pdata"));
const char *role = md != NULL ?
mcp_arg_string(md, "role") : NULL;
const char *ptype = pd != NULL ?
mcp_arg_string(pd, "type") : NULL;
if (role == NULL || ptype == NULL) {
mcp_json_free(md);
mcp_json_free(pd);
continue;
}
if (strcmp(role, "user") == 0 && strcmp(ptype, "text") ==
0) {
const char *t = mcp_arg_string(pd, "text");
if (t != NULL && t[0] != '\0')
(void)fconv_add(conv, "user", t, NULL,
NULL, NULL);
} else if (strcmp(role, "assistant") == 0 &&
strcmp(ptype, "text") == 0) {
const char *t = mcp_arg_string(pd, "text");
if (t != NULL && t[0] != '\0')
(void)fconv_add(conv, "assistant", t,
NULL, NULL, NULL);
} else if (strcmp(role, "assistant") == 0 &&
strcmp(ptype, "tool") == 0) {
const char *name = mcp_arg_string(pd, "tool");
const char *cid = mcp_arg_string(pd, "callID");
const mcp_json *state = mcp_arg(pd, "state");
struct sp_buf args, calls, out;
if (sp_buf_init(&args) != 0 ||
sp_buf_init(&calls) != 0) {
sp_buf_free(&args);
sp_buf_free(&calls);
mcp_json_free(md);
mcp_json_free(pd);
continue;
}
if (sp_buf_init(&out) != 0) {
sp_buf_free(&args);
sp_buf_free(&calls);
mcp_json_free(md);
mcp_json_free(pd);
continue;
}
args_text(state != NULL ?
mcp_arg(state, "input") : NULL, &args);
calls_append(&calls, cid, name, args.p);
(void)fconv_add(conv, "assistant", "", NULL,
NULL, calls_take(&calls));
oc_tool_output(pd, &out);
(void)fconv_add(conv, "tool", out.p, name, cid,
NULL);
sp_buf_free(&args);
sp_buf_free(&calls);
sp_buf_free(&out);
}
mcp_json_free(md);
mcp_json_free(pd);
}
offset += mcp_array_len(rows);
mcp_json_free(rows);
if (conv->truncated)
return 0;
}
}
static int
load_opencode(const char *id, struct fconv *conv, char *err, size_t errcap)
{
char why[FR_PATH + 96] = "";
if (fr.opencode[0] == '\0') {
snprintf(err, errcap, "no opencode database configured");
return -1;
}
if (access(fr.opencode, R_OK) != 0) {
snprintf(err, errcap, "cannot read %s: %s", fr.opencode,
strerror(errno));
return -1;
}
if (oc_load_v2(id, conv, why, sizeof(why)) != 0) {
fconv_free(conv);
if (oc_load_legacy(id, conv, why, sizeof(why)) != 0) {
snprintf(err, errcap, "%s",
why[0] != '\0' ? why : "opencode query failed");
return -1;
}
}
if (conv->n == 0) {
snprintf(err, errcap, "opencode session '%s' has no messages",
id);
return -1;
}
return 0;
}
/* ---------------------------------------------------------------- sources */
static int
load_any(enum fr_src s, const char *id, struct fconv *conv, char *err,
size_t errcap)
{
memset(conv, 0, sizeof(*conv));
resolve_paths();
if (!valid_id(id)) {
snprintf(err, errcap, "not a session id: '%s'",
id != NULL ? id : "");
return -1;
}
switch (s) {
case SRC_CLAUDE:
return load_claude(id, conv, err, errcap);
case SRC_HERMES:
return load_hermes(id, conv, err, errcap);
case SRC_OPENCODE:
return load_opencode(id, conv, err, errcap);
default:
snprintf(err, errcap, "unknown source");
return -1;
}
}
/*
* `rows_wanted` is how many rows the caller asked for, which is not always
* fr.limit: that is the configured default (25). The SQL sources used to query
* with fr.limit regardless, so a caller that asked for 100 got 25 rows and the
* picker claimed a store had 25 sessions when it had 290.
*/
static int
list_any(enum fr_src s, const char *cwd, struct fbrief *v, size_t max,
size_t *n, int rows_wanted, char *err, size_t errcap)
{
resolve_paths();
*n = 0;
switch (s) {
case SRC_CLAUDE:
return list_claude(cwd, v, max, n, err, errcap) == 0 ? 0 : -1;
case SRC_HERMES:
if (list_hermes(cwd, v, max, n, rows_wanted) != 0) {
snprintf(err, errcap, "no hermes state.db under %zu "
"root%s", fr.nhermes, fr.nhermes == 1 ? "" : "s");
return -1;
}
return 0;
case SRC_OPENCODE:
return list_opencode(cwd, v, max, n, rows_wanted, err,
errcap) == 0 ? 0 : -1;
default:
snprintf(err, errcap, "unknown source");
return -1;
}
}
/* ------------------------------------------------------------------ render */
static void
render_conv(struct fconv *c, struct sp_buf *out, size_t limit)
{
size_t i;
for (i = 0; i < c->n && out->len < limit; i++) {
struct frec *r = &c->v[i];
if (strcmp(r->role, "assistant") == 0)
(void)sp_buf_puts(out, "\n[assistant]\n");
else if (strcmp(r->role, "tool") == 0)
(void)sp_buf_printf(out, "\n[tool %s]\n",
r->name != NULL ? r->name : "");
else
(void)sp_buf_printf(out, "\n[%s]\n", r->role);
if (r->text != NULL && r->text[0] != '\0')
(void)sp_buf_puts(out, r->text);
(void)sp_buf_puts(out, "\n");
}
if (i < c->n)
(void)sp_buf_puts(out, "... (transcript truncated; import it or "
"read with a larger bytes value)\n");
}
/* ------------------------------------------------------------------ import */
/*
* <dir>/<id>.meta, merged: the keys this plugin owns are replaced, the rest
* survives. session.c drops unknown keys on its next write, so a later /rename
* simply forgets the foreign tag - the id prefix still says where the session
* came from.
*/
static int
meta_merge(const char *dir, const char *id, const char *cwd, long created,
const char *title, const char *foreign)
{
char path[FR_PATH], tmp[FR_PATH + 8], *line = NULL;
size_t cap = 0, n = 0;
FILE *f, *o;
char **keep = NULL;
size_t nkeep = 0;
int rc = -1;
/* dir/id.meta, not dir/id/.meta: path_join puts a slash between parts */
if ((size_t)snprintf(path, sizeof(path), "%s/%s.meta", dir, id) >=
sizeof(path))
return -1;
if ((size_t)snprintf(tmp, sizeof(tmp), "%s.tmp", path) >= sizeof(tmp))
return -1;
keep = calloc(256, sizeof(*keep));
if (keep == NULL)
return -1;
f = fopen(path, "r");
while (f != NULL && nkeep < 256 && getline(&line, &cap, f) > 0) {
if (strncmp(line, "cwd=", 4) == 0 ||
strncmp(line, "created=", 8) == 0 ||
strncmp(line, "opened=", 7) == 0 ||
strncmp(line, "title=", 6) == 0 ||
strncmp(line, "foreign=", 8) == 0)
continue;
keep[nkeep++] = strdup(line);
}
if (f != NULL)
fclose(f);
free(line);
o = fopen(tmp, "w");
if (o == NULL)
goto out;
fprintf(o, "cwd=%s\ncreated=%ld\nopened=%ld\n", cwd, created,
(long)time(NULL));
if (title != NULL && title[0] != '\0')
fprintf(o, "title=%s\n", title);
if (foreign != NULL && foreign[0] != '\0')
fprintf(o, "foreign=%s\n", foreign);
while (n < nkeep) {
fputs(keep[n], o);
free(keep[n]);
n++;
}
if (fclose(o) != 0) {
(void)unlink(tmp);
goto out;
}
rc = rename(tmp, path) == 0 ? 0 : -1;
if (rc != 0)
(void)unlink(tmp);
out:
while (n < nkeep)
free(keep[n++]);
free(keep);
return rc;
}
/* the source's own title, directory and start time, for the import */
static void
import_meta_fields(enum fr_src s, const char *foreign_id, char *title,
size_t tcap, char *cwd, size_t ccap, long *created)
{
char err[FR_PATH + 96];
size_t i, n = 0, max = 200;
struct fbrief *v = calloc(max, sizeof(*v));
if (v == NULL)
return;
if (list_any(s, NULL, v, max, &n, (int)max, err, sizeof(err)) == 0)
for (i = 0; i < n; i++)
if (strcmp(v[i].id, foreign_id) == 0) {
if (v[i].title[0] != '\0' &&
strcmp(v[i].title, "(untitled)") != 0)
snprintf(title, tcap, "%s", v[i].title);
if (v[i].cwd[0] != '\0')
snprintf(cwd, ccap, "%s", v[i].cwd);
if (v[i].mtime > 0)
*created = v[i].mtime;
break;
}
free(v);
}
static int
import_any(struct sp_host *h, enum fr_src s, const char *foreign_id,
struct sp_buf *out)
{
struct fconv c;
char err[FR_PATH + 96], newid[80], dir[FR_PATH], path[FR_PATH];
char tag[96], title[FR_TITLE], cwd[512] = "";
struct sp_session_info si;
struct sp_buf serr;
size_t i;
long created = 0;
const char *d;
resolve_paths();
if (!valid_id(foreign_id))
return sp_buf_puts(out, "error: 'id' is not a session id");
set_host(h);
if (load_any(s, foreign_id, &c, err, sizeof(err)) != 0)
return sp_buf_printf(out, "error: %s", err);
fconv_pair(&c);
if (c.n == 0) {
fconv_free(&c);
return sp_buf_printf(out, "error: '%s' has nothing to import "
"(every record was empty or had no counterpart)", foreign_id);
}
import_id(s, foreign_id, newid, sizeof(newid));
d = h != NULL ? sp_host_session_dir(h) : NULL;
if (d == NULL || *d == '\0') {
fconv_free(&c);
return sp_buf_puts(out, "error: no session directory");
}
snprintf(dir, sizeof(dir), "%s", d);
/*
* The id and its extension are one name, not two path components:
* path_join(dir, newid, ".jsonl") would build dir/newid/.jsonl and the
* replace below would never find the file it is meant to replace.
*/
if (path_join(path, sizeof(path), dir, newid, NULL) != 0 ||
strlen(path) + sizeof(".jsonl") > sizeof(path)) {
fconv_free(&c);
return sp_buf_puts(out, "error: session path too long");
}
strcat(path, ".jsonl");
if (access(path, F_OK) == 0 && unlink(path) != 0) {
fconv_free(&c);
return sp_buf_printf(out, "error: cannot replace %s: %s", path,
strerror(errno));
}
if (sp_buf_init(&serr) != 0) {
fconv_free(&c);
return sp_buf_puts(out, "error: out of memory");
}
if (sp_session_open(&si, dir, newid, &serr) != 0) {
sp_buf_printf(out, "error: %s", serr.p != NULL ? serr.p : "?");
sp_buf_free(&serr);
fconv_free(&c);
return -1;
}
for (i = 0; i < c.n; i++) {
struct sp_sess_rec rec;
memset(&rec, 0, sizeof(rec));
rec.role = c.v[i].role;
rec.text = c.v[i].text;
rec.name = c.v[i].name;
rec.call_id = c.v[i].call_id;
rec.calls = c.v[i].calls;
sp_buf_clear(&serr);
if (sp_session_append_rec(&si, &rec, &serr) != 0) {
sp_buf_printf(out, "error: writing %s: %s", path,
serr.p != NULL ? serr.p : "?");
sp_buf_free(&serr);
fconv_free(&c);
return -1;
}
}
sp_buf_free(&serr);
/*
* The source's own title is the better one; the first user message is
* only the fallback when the store has none. Asking the list first
* also fills cwd and created, which is what makes an imported session
* show up under the directory it ran in instead of this one.
*/
title[0] = '\0';
import_meta_fields(s, foreign_id, title, sizeof(title), cwd,
sizeof(cwd), &created);
if (title[0] == '\0')
for (i = 0; i < c.n; i++)
if (strcmp(c.v[i].role, "user") == 0 &&
c.v[i].text != NULL && c.v[i].text[0] != '\0') {
one_line(c.v[i].text, title, sizeof(title));
break;
}
if (title[0] == '\0')
snprintf(title, sizeof(title), "imported %s session",
src_name[s]);
if (cwd[0] == '\0' && getcwd(cwd, sizeof(cwd)) == NULL)
snprintf(cwd, sizeof(cwd), "?");
if (created == 0)
created = (long)time(NULL);
snprintf(tag, sizeof(tag), "%s:%s", src_name[s], foreign_id);
(void)meta_merge(dir, newid, cwd, created, title, tag);
sp_buf_printf(out, "imported %s session %s as %s (%zu messages%s)\n",
src_name[s], foreign_id, newid, c.n,
c.truncated ? ", truncated at the message or byte cap" : "");
/*
* Two ways, because they belong to two places: /open is the TUI's
* command, --session-id is what a shell has (a one-shot run has no
* /commands beyond the plugins, so /open there answers "unknown
* command" and looks like a broken import).
*/
sp_buf_printf(out, "continue it with: /open %s (in the chat) or "
"splinter --session-id %s --resume\n", newid, newid);
sp_buf_printf(out, "it is listed under %s\n", cwd);
fconv_free(&c);
return 0;
}
/* ------------------------------------------------------------------- tools */
static int
tool_list(const char *args, struct sp_buf *out, void *ctx)
{
char err[FR_PATH + 96], cwd[512];
char srcbuf[32] = "", onlybuf[512] = "";
const char *src = NULL, *only = NULL;
struct fbrief *v;
size_t max = 200, n = 0, i, k, shown = 0;
int limit = fr.limit, all_cwd = 0;
enum fr_src want = SRC_NONE;
mcp_json *a;
(void)ctx;
resolve_paths();
/*
* The argument strings live inside the parsed JSON and are gone once
* it is freed. Copy them out first: reading them afterwards handed
* the caller freed memory (a cwd filter that matched nothing, and a
* garbage string in the "no sessions" line).
*/
if (args != NULL && args[0] == '{' && (a = mcp_parse(args)) != NULL) {
const char *s = mcp_arg_string(a, "source");
const char *o = mcp_arg_string(a, "cwd");
if (s != NULL)
snprintf(srcbuf, sizeof(srcbuf), "%s", s);
if (o != NULL)
snprintf(onlybuf, sizeof(onlybuf), "%s", o);
limit = mcp_arg_int(a, "limit", fr.limit);
mcp_json_free(a);
src = srcbuf[0] != '\0' ? srcbuf : NULL;
only = onlybuf[0] != '\0' ? onlybuf : NULL;
}
if (src != NULL && src_of(src) == SRC_NONE)
return sp_buf_puts(out, "error: 'source' must be claude, hermes or "
"opencode");
want = src_of(src);
if (limit < 1 || limit > 100)
limit = fr.limit;
/*
* cwd="*" means every directory. It has to be remembered as a
* decision: setting 'only' to NULL and then falling back to getcwd()
* below made the wildcard filter by the current directory like an
* omitted argument, so "list everything" listed nothing here.
*/
if (only != NULL && strcmp(only, "*") == 0) {
only = NULL;
all_cwd = 1;
}
if (only == NULL && !all_cwd && getcwd(cwd, sizeof(cwd)) != NULL)
only = cwd;
v = calloc(max, sizeof(*v));
if (v == NULL)
return sp_buf_puts(out, "error: out of memory");
for (i = 0; i < 3 && shown < (size_t)limit; i++) {
if (want != SRC_NONE && want != (enum fr_src)i)
continue;
if (list_any((enum fr_src)i, only, v, max, &n, limit,
err, sizeof(err)) != 0) {
sp_buf_printf(out, "%s: %s\n", src_name[i], err);
continue;
}
for (k = 0; k < n && shown < (size_t)limit; k++) {
char stamp[32];
stamp_of(v[k].mtime, stamp, sizeof(stamp));
sp_buf_printf(out, "%s %-8s %-42s %s %s\n", stamp,
src_name[i], v[k].id, v[k].title,
v[k].cwd[0] != '\0' ? v[k].cwd : "");
shown++;
}
}
free(v);
if (shown == 0)
sp_buf_printf(out, "no foreign sessions%s%s%s\n",
only != NULL ? " in " : "", only != NULL ? only : "",
want != SRC_NONE ? " for that source" : "");
else if (shown >= (size_t)limit)
(void)sp_buf_puts(out, "... (limit reached; cwd=\"*\" or a "
"higher limit lists more)\n");
return 0;
}
static int
tool_read(const char *args, struct sp_buf *out, void *ctx)
{
struct fconv c;
char err[FR_PATH + 96];
char srcbuf[32] = "", idbuf[256] = "";
const char *src = NULL, *id = NULL;
enum fr_src s;
int limit = 40000;
mcp_json *a;
(void)ctx;
if (args != NULL && args[0] == '{' && (a = mcp_parse(args)) != NULL) {
const char *sv = mcp_arg_string(a, "source");
const char *iv = mcp_arg_string(a, "id");
if (sv != NULL)
snprintf(srcbuf, sizeof(srcbuf), "%s", sv);
if (iv != NULL)
snprintf(idbuf, sizeof(idbuf), "%s", iv);
limit = mcp_arg_int(a, "bytes", 40000);
mcp_json_free(a);
src = srcbuf[0] != '\0' ? srcbuf : NULL;
id = idbuf[0] != '\0' ? idbuf : NULL;
}
s = src_of(src);
if (s == SRC_NONE)
return sp_buf_puts(out, "error: 'source' must be claude, hermes "
"or opencode");
if (id == NULL || *id == '\0')
return sp_buf_puts(out, "error: 'id' is required");
if (limit < 1000)
limit = 1000;
if (limit > 400000)
limit = 400000;
if (load_any(s, id, &c, err, sizeof(err)) != 0)
return sp_buf_printf(out, "error: %s", err);
sp_buf_printf(out, "%s %s: %zu messages%s\n", src_name[s], id, c.n,
c.truncated ? " (truncated)" : "");
render_conv(&c, out, (size_t)limit);
fconv_free(&c);
return 0;
}
static int
tool_import(const char *args, struct sp_buf *out, void *ctx)
{
char srcbuf[32] = "", idbuf[256] = "";
const char *src = NULL, *id = NULL;
enum fr_src s;
mcp_json *a;
int rc;
if (args != NULL && args[0] == '{' && (a = mcp_parse(args)) != NULL) {
const char *sv = mcp_arg_string(a, "source");
const char *iv = mcp_arg_string(a, "id");
if (sv != NULL)
snprintf(srcbuf, sizeof(srcbuf), "%s", sv);
if (iv != NULL)
snprintf(idbuf, sizeof(idbuf), "%s", iv);
mcp_json_free(a);
src = srcbuf[0] != '\0' ? srcbuf : NULL;
id = idbuf[0] != '\0' ? idbuf : NULL;
}
s = src_of(src);
if (s == SRC_NONE)
return sp_buf_puts(out, "error: 'source' must be claude, hermes "
"or opencode");
if (id == NULL || *id == '\0')
return sp_buf_puts(out, "error: 'id' is required");
rc = import_any(ctx, s, id, out);
if (rc == 0)
(void)sp_host_note(ctx, "foreign session imported");
return rc;
}
static int
search_hermes(const char *query, int limit, int days, struct sp_buf *out,
int *hits, const char *only_cwd)
{
char dbs[32][FR_PATH], why[FR_PATH + 96];
size_t nd = 0, i;
struct sp_buf lit, lit2, sql;
long since = days > 0 ? (long)time(NULL) -
(long)days * 86400 : 0;
hermes_dbs(dbs, 32, &nd);
if (sp_buf_init(&lit) != 0 || sp_buf_init(&lit2) != 0 ||
sp_buf_init(&sql) != 0) {
sp_buf_free(&lit);
sp_buf_free(&lit2);
sp_buf_free(&sql);
return *hits;
}
for (i = 0; i < nd && *hits < limit; i++) {
mcp_json *rows;
size_t k;
/*
* Two literals, two buffers. sql_lit() writes into the buffer it
* is given and both %s in one printf were fed the same one: the
* second call cleared the first, so the cwd filter compared
* against the query and matched nothing (or worse, the query).
*/
/*
* Match the whole content, cut only the copy that is shown.
* `substr(content,1,400)` used to sit inside the WHERE, so a
* needle past byte 400 was invisible although the row had it.
*/
sp_buf_clear(&sql);
(void)sp_buf_printf(&sql, "select session_id as sid, role, "
"substr(content,1,%d) as body from messages where content "
"like '%%' || %s || '%%' and role in ('user','assistant') "
"%s%s%s order by timestamp desc limit %d;",
FR_ROW_BYTES, sql_lit(&lit, query),
only_cwd != NULL ? "and session_id in (select id from sessions "
"where cwd = " : "",
only_cwd != NULL ? sql_lit(&lit2, only_cwd) : "",
only_cwd != NULL ? ")" : "",
limit - *hits);
if (since > 0) {
char num[32];
snprintf(num, sizeof(num), "%ld", since);
sp_buf_clear(&sql);
(void)sp_buf_printf(&sql, "select session_id as sid, "
"role, substr(content,1,%d) as body from messages "
"where content like '%%' || %s || '%%' and role in "
"('user','assistant') and timestamp >= %s%s%s%s "
"order by timestamp desc limit %d;",
FR_ROW_BYTES, sql_lit(&lit, query), num,
only_cwd != NULL ? "and session_id in (select id "
"from sessions where cwd = " : "",
only_cwd != NULL ? sql_lit(&lit2, only_cwd) : "",
only_cwd != NULL ? ")" : "",
limit - *hits);
}
rows = sql_json(dbs[i], sql.p, why, sizeof(why));
if (rows == NULL)
continue;
for (k = 0; k < mcp_array_len(rows) && *hits < limit; k++) {
const mcp_json *r = mcp_array_at(rows, k);
const char *sid = mcp_arg_string(r, "sid");
const char *role = mcp_arg_string(r, "role");
const char *txt = mcp_arg_string(r, "body");
if (txt == NULL || !has_ci(txt, query))
continue;
sp_buf_printf(out, " hermes %s %s: ",
sid != NULL ? sid : "?", role != NULL ? role : "?");
snippet(out, txt, query, 200);
(void)sp_buf_puts(out, "\n");
(*hits)++;
}
mcp_json_free(rows);
}
sp_buf_free(&lit);
sp_buf_free(&lit2);
sp_buf_free(&sql);
return *hits;
}
/*
* The text of one opencode message, as SQL sees it. `session_message.data` is
* JSON in two shapes: a user message carries `text`, an assistant message
* carries `content[], and the prose lives in the `text` blocks of that array.
* Reading only `data.text` made every assistant message invisible to search,
* and cutting the JSON to 20000 bytes before parsing dropped every message
* longer than that (2973 of them, up to 15 MB) on top.
*/
#define OC_BODY_SQL \
"select session_id as sid, type, time_created, " \
"case when json_extract(data,'$.text') is not null " \
"then json_extract(data,'$.text') else (select group_concat(" \
"json_extract(j.value,'$.text'), char(10)) from json_each(" \
"json_extract(data,'$.content')) j where json_extract(" \
"j.value,'$.type')='text') end as body, " \
"case when json_extract(data,'$.text') is not null " \
"then 0 else 1 end as from_content " \
"from session_message where type in ('user','assistant')"
static int
search_opencode(const char *query, int limit, int days, struct sp_buf *out,
int *hits, const char *only_cwd)
{
struct sp_buf lit, sql;
mcp_json *rows;
char why[256];
long since = days > 0 ? ((long)time(NULL) -
(long)days * 86400) * 1000L : 0;
size_t k, nallowed = 0;
struct fbrief allowed[256];
if (fr.opencode[0] == '\0' || access(fr.opencode, R_OK) != 0)
return *hits;
if (sp_buf_init(&lit) != 0 || sp_buf_init(&sql) != 0) {
sp_buf_free(&lit);
sp_buf_free(&sql);
return *hits;
}
sp_buf_clear(&sql);
if (since > 0) {
char num[32];
snprintf(num, sizeof(num), "%ld", since);
(void)sp_buf_printf(&sql, "select sid, type, substr(body,1,%d) "
"as body from (" OC_BODY_SQL ") where body like '%%' || %s "
"|| '%%' and time_created >= %s order by time_created desc "
"limit %d;", FR_ROW_BYTES, sql_lit(&lit, query), num,
limit - *hits);
} else {
(void)sp_buf_printf(&sql, "select sid, type, substr(body,1,%d) "
"as body from (" OC_BODY_SQL ") where body like '%%' || %s "
"|| '%%' order by time_created desc limit %d;",
FR_ROW_BYTES, sql_lit(&lit, query), limit - *hits);
}
sp_buf_free(&lit);
rows = sql_json(fr.opencode, sql.p, why, sizeof(why));
sp_buf_free(&sql);
if (rows == NULL)
return *hits;
/*
* A cwd filter is answered by the session list, not by a second SQL
* shape: session_v2 and the older `session` table are two schemas, and
* list_opencode() already knows which one this database has. Membership
* in that list is then the same rule the list itself uses.
*/
if (only_cwd != NULL && *only_cwd != '\0') {
if (list_opencode(only_cwd, allowed, 256, &nallowed, 256,
why, sizeof(why)) != 0)
nallowed = 0;
} else {
nallowed = 0;
}
for (k = 0; k < mcp_array_len(rows) && *hits < limit; k++) {
const mcp_json *r = mcp_array_at(rows, k);
const char *body = mcp_arg_string(r, "body");
const char *sid = mcp_arg_string(r, "sid");
const char *type = mcp_arg_string(r, "type");
if (body == NULL || body[0] == '\0')
continue;
/* a session in another folder is not this folder's history */
if (only_cwd != NULL && *only_cwd != '\0') {
size_t i2;
for (i2 = 0; sid != NULL && i2 < nallowed; i2++)
if (strcmp(allowed[i2].id, sid) == 0)
break;
if (sid == NULL || i2 == nallowed)
continue;
}
/*
* SQL already matched case-blind (LIKE) and already pulled the
* prose out of both shapes. Re-checking in C keeps the rule one
* rule: the hit is the text that will be shown.
*/
if (has_ci(body, query)) {
sp_buf_printf(out, " opencode %s %s: ",
sid != NULL ? sid : "?", type != NULL ? type : "?");
snippet(out, body, query, 200);
(void)sp_buf_puts(out, "\n");
(*hits)++;
}
}
mcp_json_free(rows);
return *hits;
}
static int
tool_search(const char *args, struct sp_buf *out, void *ctx)
{
char qbuf[256] = "", srcbuf[32] = "",
onlybuf[512] = "";
const char *query = NULL, *src = NULL, *only = NULL;
int limit = 10, days = 0, hits = 0;
enum fr_src s = SRC_NONE;
mcp_json *a;
(void)ctx;
resolve_paths();
if (args != NULL && args[0] == '{' && (a = mcp_parse(args)) != NULL) {
const char *q = mcp_arg_string(a, "query");
const char *sv = mcp_arg_string(a, "source");
const char *o = mcp_arg_string(a, "cwd");
if (q != NULL)
snprintf(qbuf, sizeof(qbuf), "%s", q);
if (sv != NULL)
snprintf(srcbuf, sizeof(srcbuf), "%s", sv);
if (o != NULL)
snprintf(onlybuf, sizeof(onlybuf), "%s", o);
limit = mcp_arg_int(a, "limit", 10);
days = mcp_arg_int(a, "days", 0);
mcp_json_free(a);
query = qbuf[0] != '\0' ? qbuf : NULL;
src = srcbuf[0] != '\0' ? srcbuf : NULL;
only = onlybuf[0] != '\0' ? onlybuf : NULL;
}
if (query == NULL || *query == '\0')
return sp_buf_puts(out, "error: 'query' is required");
if (strlen(query) > 200)
return sp_buf_puts(out, "error: 'query' is too long");
if (src != NULL) {
s = src_of(src);
if (s == SRC_NONE)
return sp_buf_puts(out, "error: 'source' must be claude, "
"hermes or opencode");
}
if (limit < 1 || limit > 50)
limit = 10;
/*
* cwd="*" means every folder, and so does an omitted cwd here: search
* asks "what does the machine know", while list asks "what did we do
* here". Passing the default in would silently cut the answer down to
* the current directory and make a search that used to find the fix
* stop finding it.
*/
if (only != NULL && strcmp(only, "*") == 0)
only = NULL;
if (s == SRC_NONE || s == SRC_CLAUDE)
hits = search_claude(query, limit, days, out, only);
if ((s == SRC_NONE || s == SRC_HERMES) && hits < limit)
hits = search_hermes(query, limit, days, out, &hits, only);
if ((s == SRC_NONE || s == SRC_OPENCODE) && hits < limit)
hits = search_opencode(query, limit, days, out, &hits, only);
if (hits == 0)
sp_buf_printf(out, "no message in the %s sessions contains '%s'\n",
s == SRC_NONE ? "claude, hermes and opencode" : src_name[s],
query);
else if (hits >= limit)
(void)sp_buf_puts(out, "... (limit reached; narrow the query or "
"raise limit)\n");
return 0;
}
/* ---------------------------------------------------------------- command */
static void
args_split(const char *args, char *sub, size_t scap, char *a1, size_t a1cap,
char *a2, size_t a2cap)
{
const char *p = args != NULL ? args : "";
size_t n;
sub[0] = a1[0] = a2[0] = '\0';
while (*p == ' ' || *p == '\t')
p++;
for (n = 0; *p != '\0' && *p != ' ' && n + 1 < scap; n++)
sub[n] = *p++;
sub[n] = '\0';
while (*p == ' ' || *p == '\t')
p++;
for (n = 0; *p != '\0' && *p != ' ' && n + 1 < a1cap; n++)
a1[n] = *p++;
a1[n] = '\0';
while (*p == ' ' || *p == '\t')
p++;
for (n = 0; *p != '\0' && n + 1 < a2cap; n++)
a2[n] = *p++;
a2[n] = '\0';
}
static int
cmd_foreign(struct sp_host *h, const char *args, struct sp_buf *out, void *ctx)
{
char sub[32], a1[128], a2[512];
char err[FR_PATH + 96];
size_t i, n = 0;
struct sp_buf j;
int rc;
(void)ctx;
set_host(h);
resolve_paths();
args_split(args, sub, sizeof(sub), a1, sizeof(a1), a2, sizeof(a2));
if (sub[0] == '\0' || strcmp(sub, "list") == 0 ||
strcmp(sub, "sources") == 0) {
struct fbrief *v = calloc(64, sizeof(*v));
if (v == NULL)
return sp_buf_puts(out, "error: out of memory");
sp_buf_puts(out, "foreign session stores:\n");
sp_buf_printf(out, " claude %s\n",
fr.claude[0] != '\0' ? fr.claude : "(unset)");
for (i = 0; i < fr.nhermes; i++)
sp_buf_printf(out, " hermes %s\n", fr.hermes[i]);
if (fr.nhermes == 0)
sp_buf_puts(out, " hermes (unset)\n");
sp_buf_printf(out, " opencode %s\n",
fr.opencode[0] != '\0' ? fr.opencode : "(unset)");
for (i = 0; i < 3; i++) {
if (list_any((enum fr_src)i, NULL, v, 64, &n, 64,
err, sizeof(err)) != 0) {
sp_buf_printf(out, " %-8s %s\n", src_name[i],
err);
continue;
}
sp_buf_printf(out, " %-8s %zu listed\n", src_name[i], n);
}
free(v);
sp_buf_puts(out, "\n/foreign list|read SOURCE ID|search TEXT|"
"import SOURCE ID\n");
sp_buf_puts(out, "import writes a splinter session; /open <new "
"id> continues it in the chat, splinter --session-id <new "
"id> --resume in a shell.\n");
return 0;
}
if (strcmp(sub, "read") == 0) {
if (src_of(a1) == SRC_NONE || a2[0] == '\0')
return sp_buf_puts(out, "usage: /foreign read SOURCE ID");
} else if (strcmp(sub, "import") == 0) {
if (src_of(a1) == SRC_NONE || a2[0] == '\0')
return sp_buf_puts(out, "usage: /foreign import SOURCE ID");
} else if (strcmp(sub, "search") == 0) {
if (a1[0] == '\0')
return sp_buf_puts(out, "usage: /foreign search TEXT");
} else {
sp_buf_printf(out, "unknown /foreign subcommand '%s'\n", sub);
return sp_buf_puts(out, "usage: /foreign [list|read SOURCE ID|"
"search TEXT|import SOURCE ID]");
}
if (sp_buf_init(&j) != 0)
return sp_buf_puts(out, "error: out of memory");
if (strcmp(sub, "search") == 0) {
/*
* The text is the operator's, so it is escaped: a quote in
* /foreign search he said "hi" used to end the JSON string
* early and the whole search was answered with "'query' is
* required".
*/
sp_buf_puts(&j, "{\"query\":\"");
(void)sp_json_escape(&j, a1);
if (a2[0] != '\0') {
sp_buf_puts(&j, " ");
(void)sp_json_escape(&j, a2);
}
sp_buf_puts(&j, "\"}");
rc = tool_search(j.p, out, h);
} else {
sp_buf_puts(&j, "{\"source\":\"");
(void)sp_json_escape(&j, a1);
sp_buf_puts(&j, "\",\"id\":\"");
(void)sp_json_escape(&j, a2);
sp_buf_puts(&j, "\"}");
rc = strcmp(sub, "import") == 0 ? import_any(h, src_of(a1), a2,
out) : tool_read(j.p, out, h);
}
sp_buf_free(&j);
return rc;
}
/* ----------------------------------------------------------------- widget */
static int
foreign_tick(struct sp_host *h, const char *name, void *ctx)
{
char text[128];
(void)ctx;
set_host(h);
resolve_paths();
snprintf(text, sizeof(text), "claude %d hermes %d oc %d",
count_claude(), count_hermes(), count_opencode());
return sp_host_widget_text(h, name, text);
}
/* ------------------------------------------------------------------- init */
static int
foreign_init(struct sp_host *h)
{
static struct sp_tool t[4];
static const struct sp_widget w = {
"foreign", foreign_tick, NULL, NULL, 0
};
size_t i;
memset(t, 0, sizeof(t));
set_host(h);
resolve_paths();
t[0].name = "foreign_list";
t[0].description = "List the sessions of the other harnesses on this "
"machine -- Claude Code, Hermes and opencode -- with date, id, "
"title and the directory each conversation ran in. Defaults to the "
"current working directory; cwd:\"*\" lists every folder. Use it "
"before asking what an earlier Claude or opencode session did, and "
"foreign_import to continue one here.";
t[0].params = "{\"type\":\"object\",\"properties\":{"
"\"source\":{\"type\":\"string\",\"enum\":[\"claude\",\"hermes\","
"\"opencode\"],\"description\":\"omit for all three\"},"
"\"cwd\":{\"type\":\"string\",\"description\":\"only sessions that "
"ran in this directory; \\\"*\\\" for every one (default: the "
"current directory)\"},"
"\"limit\":{\"type\":\"integer\",\"description\":\"max rows, "
"default 25\"}}}";
t[0].auth = SP_AUTH_READ;
t[0].run = tool_list;
t[0].ctx = h;
t[1].name = "foreign_search";
t[1].description = "Search inside the Claude Code, Hermes and opencode "
"sessions (case-blind): what was asked and answered, with the "
"session id needed to read or import it. Cheaper than reading a "
"whole transcript and the way to find the session that already "
"solved something.";
t[1].params = "{\"type\":\"object\",\"properties\":{"
"\"query\":{\"type\":\"string\",\"description\":\"text to find\"},"
"\"source\":{\"type\":\"string\",\"enum\":[\"claude\",\"hermes\","
"\"opencode\"],\"description\":\"omit for all\"},"
"\"limit\":{\"type\":\"integer\",\"description\":\"max hits, "
"default 10, max 50\"},"
"\"days\":{\"type\":\"integer\",\"description\":\"only sessions "
"changed in the last N days\"}},"
"\"required\":[\"query\"]}";
t[1].auth = SP_AUTH_READ;
t[1].run = tool_search;
t[1].ctx = h;
t[2].name = "foreign_read";
t[2].description = "Read one Claude Code, Hermes or opencode session as "
"a transcript: role, text, and the tool calls with their results "
"in place. Read-only; to give splinter the conversation, use "
"foreign_import instead.";
t[2].params = "{\"type\":\"object\",\"properties\":{"
"\"source\":{\"type\":\"string\",\"enum\":[\"claude\",\"hermes\","
"\"opencode\"]},"
"\"id\":{\"type\":\"string\",\"description\":\"the session id from "
"foreign_list\"},"
"\"bytes\":{\"type\":\"integer\",\"description\":\"how much of the "
"transcript to print, default 40000\"}},"
"\"required\":[\"source\",\"id\"]}";
t[2].auth = SP_AUTH_READ;
t[2].run = tool_read;
t[2].ctx = h;
t[3].name = "foreign_import";
t[3].description = "Import one Claude Code, Hermes or opencode session "
"into splinter as a splinter session, so /open <new id> (in the "
"chat), --session-id <new id> --resume (in a shell) and -c continue "
"that conversation here with its history, its tool calls and its "
"working directory. Prints the new session id.";
t[3].params = "{\"type\":\"object\",\"properties\":{"
"\"source\":{\"type\":\"string\",\"enum\":[\"claude\",\"hermes\","
"\"opencode\"]},"
"\"id\":{\"type\":\"string\",\"description\":\"the session id from "
"foreign_list\"}},"
"\"required\":[\"source\",\"id\"]}";
t[3].auth = SP_AUTH_MUTATE; /* it writes a session file */
t[3].run = tool_import;
t[3].ctx = h;
for (i = 0; i < 4; i++)
if (sp_host_add_tool(h, &t[i]) != 0)
return -1;
if (sp_host_add_widget(h, &w) != 0)
return -1;
if (sp_host_add_command(h, "foreign", cmd_foreign, NULL) != 0)
return -1;
return 0;
}
static const struct sp_plugin foreign_plugin = {
SP_PLUGIN_ABI, "foreign", "1.0.0", foreign_init, NULL, NULL
};
const struct sp_plugin *
sp_plugin_describe(void)
{
return &foreign_plugin;
}