cli: splinter -c --claude continues the newest claude session of this folder

The operator's claude ran into its limit mid-work; the session was too full to
continue there. The foreign plugin could already read and import it, but only
through a tool call inside a turn - there was no way in from the command line.

--claude, --opencode, --hermes and --from=NAME make the newest session that
tool ran in this directory the session of the run: it is imported before the
history is loaded, so the first turn already carries it. -c no longer fails in
a folder that has no splinter session yet; it falls back to "no session" and
lets the import decide. An empty placeholder session is removed again, whether
the import worked or not.

Repeating the call continues the same session instead of importing a second
time: sp_session_foreign() reads the foreign= marker back, so the work done in
splinter is kept. A second foreign_import into the same session replaces the
history rather than appending it twice (path_join built "id/.jsonl", so the
replace branch never fired).

Test: tests/test_foreignopen.c builds a claude fixture under its own HOME and
covers import, idempotency, replace-not-append, the empty placeholder and a
folder with no foreign session. make check exit 0, check_asan.sh clean.
This commit is contained in:
lotherk committed 2026-11-22 13:20:45 +00:00
1 parent 15d6eb1885
commit f19fbf6ac1
12 files changed
+924 -13

No files matched your search

+6 -3
View File
@@ -27,7 +27,7 @@ LIB = libsplinter.so
LIBOBJ = src/backend/buf.o src/backend/tool.o src/backend/session.o src/backend/conv.o src/backend/compact.o src/backend/transport.o \
src/backend/json.o src/backend/sse.o src/backend/openai.o src/backend/transport_openai.o \
src/backend/anthropic.o src/backend/transport_anthropic.o src/backend/builtin.o \
src/backend/agent.o src/backend/theme.o src/backend/palettes.o src/backend/decomp.o src/backend/i18n.o src/backend/delegate.o src/backend/telegram.o src/backend/log.o src/backend/cmdscript.o src/backend/folder.o src/backend/interview.o src/backend/ack.o src/backend/mcpserver.o src/backend/mcpsession.o src/backend/skills.o src/backend/user.o src/backend/prompt.o src/backend/config.o src/backend/plugin.o src/backend/curl.o src/backend/swarm.o src/backend/provstate.o src/backend/md.o src/backend/tgmd.o src/backend/b64.o src/backend/a2aserver.o src/backend/providers.o src/backend/usage.o src/backend/confblock.o src/backend/embed.o src/backend/agents.o src/backend/engine.o src/backend/http.o src/backend/openai_server.o src/backend/catalogs.o
src/backend/agent.o src/backend/theme.o src/backend/palettes.o src/backend/decomp.o src/backend/i18n.o src/backend/delegate.o src/backend/telegram.o src/backend/log.o src/backend/cmdscript.o src/backend/folder.o src/backend/interview.o src/backend/ack.o src/backend/mcpserver.o src/backend/mcpsession.o src/backend/skills.o src/backend/user.o src/backend/prompt.o src/backend/config.o src/backend/plugin.o src/backend/curl.o src/backend/swarm.o src/backend/provstate.o src/backend/md.o src/backend/tgmd.o src/backend/b64.o src/backend/a2aserver.o src/backend/providers.o src/backend/usage.o src/backend/confblock.o src/backend/embed.o src/backend/agents.o src/backend/foreignopen.o src/backend/engine.o src/backend/http.o src/backend/openai_server.o src/backend/catalogs.o
# buildinfo.o is separate: buildinfo.c is generated from the objects below.
LIBOBJ_ALL = $(LIBOBJ) src/backend/buildinfo.o
BIN = splinter
@@ -50,7 +50,8 @@ PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \
TESTS = tests/test_buf tests/test_tool tests/test_session tests/test_conv \
tests/test_transport tests/test_agent tests/test_openai \
tests/test_theme tests/test_plugin tests/test_skills tests/test_telegram tests/test_delegate tests/test_builtin tests/test_ascii tests/test_ack tests/test_i18n tests/test_config tests/test_focus tests/test_sse tests/test_anthropic tests/test_cli tests/test_compactor tests/test_corecompact tests/test_secrets tests/test_mcpclient tests/test_kids tests/test_lifecycle tests/test_md tests/test_tgmd tests/test_providers tests/test_b64 tests/test_pause tests/test_swarm tests/test_provstate tests/test_usage tests/test_agents tests/test_confblock tests/test_jobs tests/test_engine tests/test_self tests/test_fuzz \
tests/test_sessiontools tests/test_embed tests/test_foreign
tests/test_sessiontools tests/test_embed tests/test_foreign \
tests/test_foreignopen
RPATH = -Wl,-rpath,'$$ORIGIN'
PLUGIN_RPATH = -Wl,-rpath,'$$ORIGIN/../..'
@@ -272,10 +273,12 @@ tests/test_self: tests/test_self.c $(LIB) plugins/self/self.so
tests/test_fuzz: tests/test_fuzz.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_fuzz.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_sessiontools: tests/test_sessiontools.c $(LIB) plugins/session/session.so
tests/test_sessiontools: tests/test_sessiontools.c $(LIB) plugins/session/session.so plugins/foreign/foreign.so
$(CC) $(CFLAGS) -o $@ tests/test_sessiontools.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_foreign: tests/test_foreign.c $(LIB) plugins/foreign/foreign.so
$(CC) $(CFLAGS) -o $@ tests/test_foreign.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_foreignopen: tests/test_foreignopen.c $(LIB) plugins/foreign/foreign.so
$(CC) $(CFLAGS) -o $@ tests/test_foreignopen.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
tests/test_usage: tests/test_usage.c $(LIB)
$(CC) $(CFLAGS) -o $@ tests/test_usage.c -L. -lsplinter $(TEST_RPATH) $(LIBS)
+27
View File
@@ -55,6 +55,7 @@ splinter refuses to start rather than pretend it can talk to a model.
| `--serve`, `--attach`, `--socket PATH` | serve the line protocol on a Unix socket, or be a client of it (default `~/.splinter/splinter.sock`) |
| `--theme NAME`, `--list-themes` | UI theme (`Xresources` or a CDE palette such as `Default`, `Delphinium`, `MakroSlate`), and the names |
| `--resume`, `-c, --continue` | load the session's history; continue the last session started in this directory |
| `--claude`, `--opencode`, `--hermes`, `--from=NAME` | continue the newest session that tool ran in this directory (imports it on the first start) |
| `--session DIR`, `--session-id ID` | session directory (default `~/.splinter`) and id (default `sess-<time>-<pid>`) |
| `--steps N` | tool rounds per turn (default 150) |
| `--max-bytes N` | request budget in bytes, 0 = no limit |
@@ -848,6 +849,32 @@ Four tools — `foreign_list`, `foreign_search`, `foreign_read`, `foreign_import
/foreign read SOURCE ID one transcript, tool calls in place
/foreign import SOURCE ID adopt it as a splinter session
### Continuing another tool's session from the shell
The case this was built for: a Claude session hit its limit mid-thought and the
conversation has to go on *here*.
splinter -c --claude
`--claude` (likewise `--opencode`, `--hermes`, `--from=NAME`) finds the newest
session that tool ran in **this** directory, imports it and continues it —
the import happens before the history is loaded, so the first turn already
carries it. `-c` is not needed for that: `--claude` resumes by itself. What
`-c` adds is the fallback — with it, a directory that has neither a foreign
nor a splinter session is still an error that says so, instead of an empty
start.
A second start does not import again: the imported session carries
`foreign=<source>:<id>` in its sidecar, and that is what the next `-c --claude`
finds and continues. Importing again would replace the file and throw away
everything the conversation did in splinter since. The empty placeholder a run
opens before it knows what it continues is removed; a session that already had
content never is.
The plugin has to be loaded — either `plugin foreign` in the config, or
`--plugin plugins/foreign/foreign.so`. Without it the option says so by name
instead of silently starting a fresh session.
`import` writes a real splinter session and says so: the conversation as a
replayable `.jsonl`, and a `.meta` with the source's title, its start time and
**its** working directory, not the one you imported from. So `/open <new id>`
+20
View File
@@ -154,6 +154,26 @@ Session directory (default
.It Fl -session-id Ar ID
Session id (default
.Pa sess-<time>-<pid> ) .
.It Fl -claude , Fl -opencode , Fl -hermes , Fl -from Ns = Ns Ar NAME
Continue the newest session that tool ran in this directory, importing it
into
.Nm
on the first start.
The session this creates carries its origin in the sidecar
.Pq Ql foreign=source:id ,
so a later
.Fl -claude
continues that same session instead of importing the conversation again \(em
a second import would replace the file and lose everything done here since.
Works without
.Fl c ,
which only adds the rule that the run may also fall back to a
.Nm
session; a directory with no session of that source is an error either way.
Requires the foreign plugin
.Pq Ql plugin foreign
or
.Fl -plugin .
.It Fl V , -version
Print the version, the build time and the git revision, then exit.
The release number stays
+15
View File
@@ -333,6 +333,21 @@ int sp_session_get_goal_state(const char *dir, const char *id,
* The caller must not delete the session its engine has open.
*/
int sp_session_delete(const char *dir, const char *id, struct sp_buf *err);
/*
* Where a session came from, when a plugin imported it ("claude:<uuid>" as
* written by the foreign plugin). Returns 0 and fills buf, or -1 when the
* session is splinter's own. The engine reads this to continue the same
* imported session on a later start instead of importing it again.
*/
int sp_session_foreign(const char *dir, const char *id, char *buf,
size_t cap);
/*
* Remove a session that never got a message: the empty placeholder a run
* creates before it knows which session it will continue. A session with even
* one record is kept. Returns 0 when it was removed, -1 when it has content or
* does not exist.
*/
int sp_session_remove_if_empty(const char *dir, const char *id);
/* ----------------------------------------------------------------- agent */
+5
View File
@@ -67,6 +67,11 @@ struct sp_engine_opts {
size_t nplugins;
int resume; /* load the session's history */
int continue_last; /* -c: newest session in this cwd */
/*
* --claude/--opencode/--hermes: import the newest session that tool
* ran in this directory and continue that instead of a splinter one.
*/
const char *from_foreign;
int no_transport; /* tools only (MCP server, delegate) */
int interview; /* the model interviews the user */
int swarm; /* join the local fleet */
+74 -10
View File
@@ -35,6 +35,7 @@
#include "folder.h"
#include "i18n.h"
#include "embed.h"
#include "foreignopen.h"
#include "log.h"
#include "mcp.h"
#include "prompt.h"
@@ -3128,10 +3129,14 @@ sp_engine_input(struct sp_engine *e, const char *line, struct sp_buf *out)
/* ---------------------------------------------------------------- opening */
/* the session directory and id, opened */
/*
* The session directory and id, opened. *made is set when the id was invented
* here (no session to resume): that session is an empty placeholder, and a
* caller that is about to import another one may throw it away again.
*/
static int
open_session(struct sp_engine *e, const struct sp_engine_opts *o,
struct sp_buf *err, int *code)
struct sp_buf *err, int *code, int *made)
{
static char idbuf[64];
const char *dir = o->session_dir;
@@ -3150,18 +3155,34 @@ open_session(struct sp_engine *e, const struct sp_engine_opts *o,
/*
* -c means "the last session that happened *here*". The cwd at start is
* the key, so a session in another tree is never silently loaded.
*
* With --claude/--opencode/--hermes the newest foreign session is about
* to be imported, so a directory that has no splinter session yet is
* not an error: that is exactly the case the option exists for (Claude
* Code stopped at its limit in a folder this tool never ran in). A
* fresh, empty session is created and the import replaces it; the
* "latest of any directory" fallback below must not run here, it would
* resume an unrelated conversation first.
*/
if (o->continue_last && id == NULL) {
char cwd[512];
if (getcwd(cwd, sizeof(cwd)) == NULL ||
sp_session_last_for(dir, cwd, idbuf, sizeof(idbuf)) != 0) {
sp_buf_printf(err, "no session in %s yet",
getcwd(cwd, sizeof(cwd)) != NULL ? cwd : ".");
*code = -2;
return -1;
if (o->from_foreign == NULL ||
*o->from_foreign == '\0') {
sp_buf_printf(err, "no session in %s yet",
getcwd(cwd, sizeof(cwd)) != NULL ?
cwd : ".");
*code = -2;
return -1;
}
new_session_id(idbuf, sizeof(idbuf));
id = idbuf;
*made = 1;
} else {
id = idbuf;
}
id = idbuf;
}
if ((o->resume || o->continue_last) && id == NULL &&
sp_session_latest(dir, idbuf, sizeof(idbuf)) == 0)
@@ -3169,6 +3190,7 @@ open_session(struct sp_engine *e, const struct sp_engine_opts *o,
if (id == NULL) {
new_session_id(idbuf, sizeof(idbuf));
id = idbuf;
*made = 1;
}
if (sp_session_open(&e->sess, dir, id, err) != 0)
return -1;
@@ -3379,7 +3401,14 @@ setup_conversation(struct sp_engine *e, const struct sp_engine_opts *o,
return -1;
}
e->ag.conv = &e->conv;
if (!o->resume && !o->continue_last)
/*
* --claude/--opencode/--hermes is a resume by definition: the imported
* session exists to be continued. Without this, a plain `--claude`
* (without -c) opened the imported file and then talked to an empty
* conversation, which reads exactly like a broken import.
*/
if (!o->resume && !o->continue_last &&
(o->from_foreign == NULL || *o->from_foreign == '\0'))
return 0;
sp_buf_clear(err);
if (sp_session_load(&e->sess, &e->conv, &loaded, err) != 0)
@@ -3394,7 +3423,7 @@ sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o,
struct sp_engine_opts local;
struct sp_engine *e;
char cwd[700], saved[320], saved_model[320];
int start = -1, code = -1;
int start = -1, code = -1, placeholder = 0;
if (out == NULL || o == NULL || o->conf == NULL || o->base == NULL)
return -1;
@@ -3453,7 +3482,7 @@ sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o,
sp_buf_puts(err, "cannot register the builtin tools");
goto fail;
}
if (open_session(e, o, err, &code) != 0)
if (open_session(e, o, err, &code, &placeholder) != 0)
goto fail;
/*
* The index belongs to the session, so it is created with it. It starts
@@ -3498,6 +3527,41 @@ sp_engine_open(struct sp_engine **out, const struct sp_engine_opts *o,
sp_logf("session", "started: %s", e->sess.id);
if (load_plugins(e, o, err) != 0)
goto fail;
/*
* --claude/--opencode/--hermes: the newest session that tool ran here
* becomes the session of this run. Before setup_conversation, because
* that is what loads the history into the conversation.
*/
if (o->from_foreign != NULL && *o->from_foreign != '\0') {
struct sp_foreign_target ft;
char here[512], before[80];
int frc;
if (getcwd(here, sizeof(here)) == NULL)
snprintf(here, sizeof(here), ".");
snprintf(before, sizeof(before), "%s", e->sess.id);
ft.sess = &e->sess;
ft.reg = &e->reg;
ft.host = e->host;
ft.emb = e->emb;
frc = sp_foreign_open(&ft, o->from_foreign, here, err);
/*
* A run that started without a session to resume opened an empty
* placeholder, and the import replaced it (or never happened,
* because there was nothing to import). Either way nothing
* refers to it any more: leaving it behind puts an empty
* "session" into -c's list for the rest of the folder's life,
* and the next plain -c would resume that instead of saying
* there is nothing here yet.
*
* Only the placeholder goes: a session that existed before this
* run is never touched, whatever the import did.
*/
if (placeholder)
(void)sp_session_remove_if_empty(e->sess.dir, before);
if (frc != 0)
goto fail;
}
/*
* Registered here, not with the builtins: folder_history needs the
* session directory, and delegate needs the host for its task-panel
+302
View File
@@ -0,0 +1,302 @@
/*
* splinter -- continue a session another tool owns.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* Claude Code stops at its limit, opencode exits, hermes restarts -- and the
* work is still in their store. --claude (or --opencode/--hermes) is the way
* out: import the newest session that tool ran *in this directory* and open
* the result as the session of this run.
*
* Why the import and not a live "read-through": a turn needs a splinter
* session on disk (compaction, the embed index, /open and -c all speak it), and
* the foreign plugin already writes exactly that shape. Doing it here means the
* plugin owns the three formats and the engine owns only the order.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "splinter.h"
#include "splinter_plugin.h"
#include "embed.h"
#include "foreignopen.h"
#include "log.h"
/*
* The tools the import needs, found by name: the plugin registers them, so the
* engine does not have to know whether it was loaded from the config or by
* --plugin.
*/
static const struct sp_tool *
tool_of(struct sp_registry *reg, const char *name)
{
return sp_registry_find(reg, name);
}
/*
* A list row is "DATE SOURCE ID TITLE CWD", fields separated by two
* spaces. The id is the third field and the title is free text, so the row is
* split from the left: the first three fields cannot contain the separator,
* everything after them can.
*
* Returns the length of field `want` and points *start at it, or 0 when the
* row has no such field (an error line, an empty list, a short row).
*/
static size_t
column(const char *row, int want, const char **start)
{
const char *p = row;
int field = 0;
for (;;) {
const char *b = p;
while (*p != '\0' && *p != '\n' &&
!(p[0] == ' ' && p[1] == ' '))
p++;
if (field == want) {
*start = b;
return (size_t)(p - b);
}
if (*p == '\0' || *p == '\n')
return 0;
while (*p == ' ')
p++;
field++;
}
}
/* one field of a "foreign=" marker ("claude:abc" -> "claude") */
static void
origin_source(const char *marker, char *out, size_t cap)
{
const char *c = strchr(marker, ':');
size_t n = c != NULL ? (size_t)(c - marker) : strlen(marker);
if (cap == 0)
return;
if (n + 1 > cap)
n = cap - 1;
memcpy(out, marker, n);
out[n] = '\0';
}
static void
origin_id(const char *marker, char *out, size_t cap)
{
const char *c = strchr(marker, ':');
if (cap == 0)
return;
snprintf(out, cap, "%s", c != NULL ? c + 1 : "");
}
/*
* The session an earlier --claude already imported, if there is one. The
* imported session carries the source and its id in its sidecar, so a second
* start continues *that* session: importing again would replace the file and
* throw away everything the conversation did in splinter since.
*
* Returns 1 and fills `id` when found, 0 when there is none.
*/
static int
imported_before(const char *dir, const char *source, const char *foreign,
char *id, size_t cap)
{
struct sp_session_brief v[64];
int n, i, found = 0;
size_t nlen;
/*
* sp_session_list is newest first, so the first session that carries
* this origin is the one the user continued from last.
*/
n = sp_session_list(dir, v, sizeof(v) / sizeof(v[0]));
for (i = 0; i < n && !found; i++) {
char marker[160], src[32], fid[128];
if (sp_session_foreign(dir, v[i].id, marker,
sizeof(marker)) != 0)
continue;
origin_source(marker, src, sizeof(src));
origin_id(marker, fid, sizeof(fid));
if (strcmp(src, source) != 0 || strcmp(fid, foreign) != 0)
continue;
/* v[i].id is bounded by its struct, so copy and clamp */
nlen = strlen(v[i].id);
if (nlen + 1 > cap)
nlen = cap > 0 ? cap - 1 : 0;
memcpy(id, v[i].id, nlen);
if (cap > 0)
id[nlen] = '\0';
found = 1;
}
return found;
}
/*
* The import line names the new session id ("... as sess-123 (...)"). The
* engine has to open that exact session, so the id is read back from the
* answer rather than guessed: how the plugin names a session is its business.
*/
static int
id_from_answer(const char *answer, char *out, size_t cap)
{
const char *p = answer != NULL ? strstr(answer, " as ") : NULL;
size_t n = 0;
if (p == NULL || cap == 0)
return -1;
p += 4;
while (p[n] != '\0' && p[n] != ' ' && p[n] != '(' && p[n] != '\n' &&
n + 1 < cap)
n++;
if (n == 0)
return -1;
memcpy(out, p, n);
out[n] = '\0';
return 0;
}
/*
* Run one tool and copy its answer into `out`, which is cleared first. The
* answer is copied because a later call reuses the same buffer while the
* import answer is still needed.
*/
static int
run_tool(const struct sp_tool *t, const char *args, struct sp_buf *out,
struct sp_buf *tmp)
{
sp_buf_clear(out);
sp_buf_clear(tmp);
if (t->run(args, tmp, t->ctx) != 0)
return -1;
if (tmp->p != NULL && sp_buf_add(out, tmp->p, tmp->len) != 0)
return -1;
return 0;
}
/*
* Open `id` as the session of this run. The session directory stays the one
* the run already uses, so an import lands beside the run's own sessions.
* Everything keyed on the old id is rebound: the log, the cli session the
* transport uses, and the embed index.
*/
static int
take_session(struct sp_foreign_target *t, const char *id, struct sp_buf *err)
{
char keep[640];
/*
* sp_session_open writes info->dir, and t->sess->dir is the source
* here: copying it out first is what keeps the directory intact.
*/
snprintf(keep, sizeof(keep), "%s", t->sess->dir);
if (sp_session_open(t->sess, keep, id, err) != 0)
return -1;
(void)sp_log_open(t->sess->dir, t->sess->id);
(void)setenv("SPLINTER_CLI_SESSION", t->sess->id, 0);
sp_openai_set_session(t->sess->id);
if (t->emb != NULL)
sp_embed_bind(t->emb, t->sess->dir, t->sess->id);
return 0;
}
int
sp_foreign_open(struct sp_foreign_target *t, const char *source,
const char *cwd, struct sp_buf *err)
{
const struct sp_tool *list, *import;
struct sp_buf args, out, tmp;
char id[96], newid[96];
int rc = -1;
if (source == NULL || *source == '\0')
return 0;
if (strcmp(source, "claude") != 0 && strcmp(source, "hermes") != 0 &&
strcmp(source, "opencode") != 0) {
sp_buf_printf(err, "--%s is not a source: claude, hermes or "
"opencode", source);
return -1;
}
list = tool_of(t->reg, "foreign_list");
import = tool_of(t->reg, "foreign_import");
if (list == NULL || import == NULL) {
sp_buf_printf(err, "--%s needs the foreign plugin: add "
"'plugin foreign' to the config", source);
return -1;
}
if (sp_buf_init(&args) != 0 || sp_buf_init(&out) != 0 ||
sp_buf_init(&tmp) != 0) {
sp_buf_free(&args);
sp_buf_free(&out);
sp_buf_free(&tmp);
return -1;
}
/*
* The list is newest first and filtered by this directory, so the first
* row is the session to continue. One row is enough: the import takes an
* id, not a position.
*/
(void)sp_buf_printf(&args, "{\"source\":\"%s\",\"cwd\":\"%s\","
"\"limit\":1}", source, cwd);
if (run_tool(list, args.p, &out, &tmp) != 0) {
sp_buf_printf(err, "cannot list %s sessions: %s", source,
out.len > 0 && out.p != NULL ? out.p : "the tool failed");
goto failed;
}
{
const char *idp = NULL;
size_t idn = column(out.p, 2, &idp);
if (idn == 0 || idn + 1 >= sizeof(id)) {
sp_buf_printf(err, "no %s session in %s", source, cwd);
goto failed;
}
memcpy(id, idp, idn);
id[idn] = '\0';
}
if (imported_before(t->sess->dir, source, id, newid, sizeof(newid))) {
if (take_session(t, newid, err) != 0)
goto failed;
sp_logf("session", "continuing %s session %s, imported before "
"as %s", source, id, newid);
rc = 0;
goto out;
}
sp_buf_clear(&args);
(void)sp_buf_printf(&args, "{\"source\":\"%s\",\"id\":\"%s\"}", source,
id);
if (run_tool(import, args.p, &out, &tmp) != 0 ||
out.p == NULL || strncmp(out.p, "imported ", 9) != 0) {
sp_buf_printf(err, "cannot import %s %s: %s", source, id,
out.len > 0 && out.p != NULL ? out.p : "the import failed");
goto failed;
}
if (id_from_answer(out.p, newid, sizeof(newid)) != 0) {
sp_buf_printf(err, "imported, but the new session id is not in "
"the answer: %s", out.p);
goto failed;
}
/*
* The import wrote a new file, and the log, the embed index and the
* agent still point at the empty session this run started with.
*/
if (take_session(t, newid, err) != 0)
goto failed;
sp_logf("session", "continuing %s session %s as %s", source, id, newid);
rc = 0;
out:
sp_buf_free(&args);
sp_buf_free(&out);
sp_buf_free(&tmp);
return rc;
failed:
/* keep what the plugin said: it knows why a store was unreadable */
if (err->len == 0 && out.p != NULL && out.len > 0)
sp_buf_add(err, out.p, out.len);
goto out;
}
+41
View File
@@ -0,0 +1,41 @@
/*
* splinter -- continue a session another tool owns: the interface.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* The engine owns its own struct (it is private to engine.c), so this is the
* short list of what the import touches. Handing over these instead of the
* whole engine keeps the session/registry lifetimes in one place and lets the
* import be tested without a running turn.
*/
#ifndef SPLINTER_FOREIGNOPEN_H
#define SPLINTER_FOREIGNOPEN_H
#include <stddef.h>
#include "splinter.h"
struct sp_host;
struct sp_registry;
struct sp_embed_ctx;
struct sp_buf;
struct sp_foreign_target {
struct sp_session_info *sess;
struct sp_registry *reg;
struct sp_host *host;
struct sp_embed_ctx *emb;
};
/*
* Import the newest session `source` ("claude", "opencode", "hermes") ran in
* `cwd`, or continue the import that already exists, and make it the session
* of this run. Returns 0 when there was nothing to do, when the session was
* imported now, or when an earlier import was picked up again; -1 with `err`
* filled otherwise.
*/
int sp_foreign_open(struct sp_foreign_target *t, const char *source,
const char *cwd, struct sp_buf *err);
#endif
+52
View File
@@ -1129,6 +1129,58 @@ sp_session_cwd(const char *dir, const char *id, char *buf, size_t cap)
return meta_cwd(dir, id, buf, cap);
}
/*
* The session's origin when a plugin imported it, as "claude:<uuid>". The
* marker lives in the meta sidecar (the core carries lines it does not own
* through every rewrite), so this is a lookup and not a second format.
*/
int
sp_session_foreign(const char *dir, const char *id, char *buf, size_t cap)
{
struct session_meta m;
size_t i;
if (dir == NULL || id == NULL || buf == NULL || cap == 0)
return -1;
buf[0] = '\0';
if (meta_read(dir, id, &m) != 0)
return -1;
for (i = 0; i < m.nextra; i++) {
const char *e = m.extra[i];
if (strncmp(e, "foreign=", 8) != 0)
continue;
snprintf(buf, cap, "%s", e + 8);
return 0;
}
return -1;
}
/*
* The empty placeholder of a run that had not decided on its session yet. Only
* a session with no record at all is removed: one message means the user or the
* model wrote something there, and that is never thrown away.
*/
int
sp_session_remove_if_empty(const char *dir, const char *id)
{
char path[800], side[800];
struct stat st;
if (dir == NULL || id == NULL || !valid_id(id))
return -1;
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, id);
if (stat(path, &st) != 0 || st.st_size != 0)
return -1;
if (unlink(path) != 0)
return -1;
snprintf(side, sizeof(side), "%s/%s.meta", dir, id);
(void)unlink(side);
snprintf(side, sizeof(side), "%s/%s.meta.tmp", dir, id);
(void)unlink(side);
return 0;
}
/*
* One paragraph for the system prompt: does this working directory have earlier
* sessions? Then the model should look there before asking the user or starting
+16
View File
@@ -90,6 +90,9 @@ usage(FILE *f)
" --no-stdin ignore data on standard input\n"
" -c, --continue continue the last session started in this "
"directory\n"
" --claude continue the newest claude session of this\n"
" directory (also --opencode, --hermes, or\n"
" --from=NAME)\n"
" --interview let the model interview you; writes "
"USER.txt\n"
" --mcp-server-listen IP serve MCP on IP (tools of this "
@@ -216,6 +219,7 @@ struct opts {
size_t nplugins;
int init_config, no_config, list_themes, chat, resume;
int daemon, no_stdin, continue_here, interview;
const char *from_foreign; /* --claude/--opencode/--hermes */
int no_stream;
const char *select;
int model_list, no_probe, agent_list, doctor, live;
@@ -406,6 +410,17 @@ parse_args(int argc, char **argv, struct opts *o, struct sp_agent_config *cfg)
o->a2a_port = atoi(argv[++i]);
} else if (!strcmp(a, "-c") || !strcmp(a, "--continue"))
o->continue_here = 1;
/*
* --claude / --opencode / --hermes: continue the newest session
* of another tool that ran in this directory. Claude Code stops
* at its limit; the work is still in its store, so the way out
* is to import it and carry on here.
*/
else if (!strcmp(a, "--claude") || !strcmp(a, "--opencode") ||
!strcmp(a, "--hermes"))
o->from_foreign = a + 2;
else if (!strncmp(a, "--from=", 7))
o->from_foreign = a + 7;
else if (!strcmp(a, "--resume"))
o->resume = 1;
else if (!strcmp(a, "--autonomous"))
@@ -1439,6 +1454,7 @@ main(int argc, char **argv)
eo.session_id = o.sessid;
eo.resume = o.resume;
eo.continue_last = o.continue_here;
eo.from_foreign = o.from_foreign;
/*
* Telegram owns its sessions: the daemon writes below <state>/telegram,
* so a CLI -c in the same directory never picks a gateway conversation
+35
View File
@@ -0,0 +1,35 @@
# fake OpenAI endpoint: echoes the whole prompt it was sent, so a test can see
# whether a resumed conversation really carried the imported history.
# argv: port
import http.server, json, sys
def ev(d):
return ("data: " + json.dumps(d) + "\n\n").encode()
class H(http.server.BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_POST(self):
n = int(self.headers.get("Content-Length", 0))
req = json.loads(self.rfile.read(n))
parts = []
for m in req.get("messages", []):
c = m.get("content")
if isinstance(c, list):
c = " ".join(p.get("text", "") for p in c
if isinstance(p, dict))
parts.append("[%s] %s" % (m.get("role"), c))
body = "\n".join(parts)
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
w = self.wfile.write
w(ev({"choices": [{"delta": {"content":
"PROMPT-BEGIN\n" + body + "\nPROMPT-END"}}]}))
w(b"data: [DONE]\n\n")
http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
+331
View File
@@ -0,0 +1,331 @@
/*
* splinter -- -c --claude: continue the session another tool stopped in.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* What it guards, against a fixture it writes itself (the machine's real
* Claude store is not a test):
*
* - the newest Claude session of *this* directory is imported and becomes the
* session of the run, with the source's history in it;
* - a second start continues that same session instead of importing again:
* the plugin's import replaces a file of the same name, so a second import
* would throw away everything the conversation did in splinter since;
* - a directory without a Claude session is an error, not an empty session;
* - the empty placeholder a run opens before it knows what it continues is
* removed, and a session that already had content never is.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "splinter.h"
#include "splinter_plugin.h"
#include "foreignopen.h"
static int failures;
#define CHECK(cond) do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \
#cond); \
failures++; \
} \
} while (0)
static int
contains(const char *hay, const char *needle)
{
return hay != NULL && strstr(hay, needle) != NULL;
}
static void
write_text(const char *path, const char *text)
{
FILE *f = fopen(path, "w");
CHECK(f != NULL);
if (f == NULL)
return;
fputs(text, f);
fclose(f);
}
static void
mkdir_p(const char *path)
{
char buf[800];
size_t i;
snprintf(buf, sizeof(buf), "%s", path);
for (i = 1; buf[i] != '\0'; i++) {
if (buf[i] != '/')
continue;
buf[i] = '\0';
(void)mkdir(buf, 0755);
buf[i] = '/';
}
(void)mkdir(buf, 0755);
}
/* "the directory a session ran in" as the Claude store spells it */
static void
claude_slug(const char *dir, char *out, size_t cap)
{
size_t i, n = 0;
for (i = 0; dir[i] != '\0' && n + 1 < cap; i++)
out[n++] = dir[i] == '/' ? '-' : dir[i];
out[n] = '\0';
}
/* one Claude session that ran in `cwd`, with a title the import takes over */
static void
claude_session(const char *home, const char *cwd, const char *uuid,
const char *title, const char *asked, const char *answered)
{
char slug[400], store[1200], path[1300];
struct sp_buf j;
claude_slug(cwd, slug, sizeof(slug));
snprintf(store, sizeof(store), "%s/.claude/projects/%s", home, slug);
mkdir_p(store);
snprintf(path, sizeof(path), "%s/%s.jsonl", store, uuid);
CHECK(sp_buf_init(&j) == 0);
sp_buf_printf(&j, "{\"type\":\"summary\",\"summary\":\"%s\","
"\"cwd\":\"%s\"}\n", title, cwd);
sp_buf_printf(&j, "{\"type\":\"user\",\"cwd\":\"%s\",\"message\":"
"{\"role\":\"user\",\"content\":\"%s\"}}\n", cwd, asked);
sp_buf_printf(&j, "{\"type\":\"assistant\",\"cwd\":\"%s\",\"message\":"
"{\"role\":\"assistant\",\"content\":[{\"type\":\"text\","
"\"text\":\"%s\"}]}}\n", cwd, answered);
write_text(path, j.p);
sp_buf_free(&j);
}
/* how many sessions with this id prefix the directory holds */
static int
sessions_named(const char *dir, const char *prefix)
{
struct sp_session_brief v[64];
int n, i, found = 0;
n = sp_session_list(dir, v, sizeof(v) / sizeof(v[0]));
for (i = 0; i < n; i++)
if (strncmp(v[i].id, prefix, strlen(prefix)) == 0)
found++;
return found;
}
/* does exactly this session exist */
static int
session_exists(const char *dir, const char *id)
{
struct sp_session_brief v[64];
int n, i;
n = sp_session_list(dir, v, sizeof(v) / sizeof(v[0]));
for (i = 0; i < n; i++)
if (strcmp(v[i].id, id) == 0)
return 1;
return 0;
}
/* the whole file of one session, for "is the old message still there" */
static void
read_session(const char *dir, const char *id, struct sp_buf *out)
{
char path[900];
FILE *f;
char buf[4096];
size_t n;
snprintf(path, sizeof(path), "%s/%s.jsonl", dir, id);
f = fopen(path, "r");
if (f == NULL)
return;
while ((n = fread(buf, 1, sizeof(buf), f)) > 0)
(void)sp_buf_add(out, buf, n);
fclose(f);
}
int
main(void)
{
char base[512], home[700], work[700], work2[700];
char sessions[800], back[600];
struct sp_host *host;
struct sp_registry reg;
struct sp_agent ag;
struct sp_session_info sess;
struct sp_foreign_target ft;
struct sp_buf err, out;
int rc;
(void)getcwd(back, sizeof(back));
snprintf(base, sizeof(base), "/tmp/sp_fo_XXXXXX");
CHECK(mkdtemp(base) != NULL);
snprintf(home, sizeof(home), "%s/home", base);
snprintf(work, sizeof(work), "%s/work", base);
snprintf(work2, sizeof(work2), "%s/empty", base);
mkdir_p(home);
mkdir_p(work);
mkdir_p(work2);
CHECK(setenv("HOME", home, 1) == 0);
/*
* The plugin reads its stores at the first call and caches the paths,
* so HOME has to be in place before the host exists.
*/
claude_session(home, work, "11111111-2222-3333-4444-555555555555",
"CC-TITLE", "the claude question", "the claude answer");
snprintf(sessions, sizeof(sessions), "%s/.splinter/sessions", home);
memset(&reg, 0, sizeof(reg));
memset(&ag, 0, sizeof(ag));
memset(&sess, 0, sizeof(sess));
sp_buf_init(&err);
sp_buf_init(&out);
CHECK(sp_session_open(&sess, sessions, "sess-placeholder", &err) == 0);
host = sp_host_new(&reg, &ag, &sess);
CHECK(host != NULL);
sp_buf_clear(&err);
CHECK(sp_plugin_load(host, "plugins/foreign/foreign.so", &err) == 0);
sp_buf_clear(&err);
ft.sess = &sess;
ft.reg = &reg;
ft.host = host;
ft.emb = NULL;
/* --- the import: the newest claude session of this directory wins --- */
rc = sp_foreign_open(&ft, "claude", work, &err);
CHECK(rc == 0);
CHECK(strncmp(sess.id, "fcl-", 4) == 0);
CHECK(strstr(sess.id, "11111111-2222-3333-4444-555555555555") != NULL);
sp_buf_clear(&out);
read_session(sess.dir, sess.id, &out);
CHECK(contains(out.p, "the claude question"));
CHECK(contains(out.p, "the claude answer"));
/* the origin is what makes a second start continue instead of re-import */
{
char marker[200];
CHECK(sp_session_foreign(sess.dir, sess.id, marker,
sizeof(marker)) == 0);
CHECK(contains(marker, "claude:"));
}
/* --- what the conversation did afterwards must survive a restart --- */
{
struct sp_buf serr;
sp_buf_init(&serr);
CHECK(sp_session_append(&sess, "user", "spoken in splinter",
&serr) == 0);
sp_buf_free(&serr);
}
memset(&sess, 0, sizeof(sess));
CHECK(sp_session_open(&sess, sessions, "sess-placeholder2", &err) == 0);
ft.sess = &sess;
sp_buf_clear(&err);
rc = sp_foreign_open(&ft, "claude", work, &err);
CHECK(rc == 0);
sp_buf_clear(&out);
read_session(sess.dir, sess.id, &out);
CHECK(contains(out.p, "spoken in splinter"));
/* exactly one import: a second one would have replaced the file */
CHECK(sessions_named(sessions, "fcl-") == 1);
/*
* --- importing the same session twice replaces, it does not append ---
*
* The engine shields this by continuing an existing import, so it has to
* be checked on the tool itself: import_any deletes the target file
* first, and whether it finds it depends on how the path is built. It
* was built as dir/<id>/.jsonl - a directory that never exists - so the
* delete never happened and every import hung the whole history onto
* the last one.
*/
{
const struct sp_tool *imp = sp_registry_find(&reg, "foreign_import");
struct sp_buf iout, serr;
struct sp_session_info is;
size_t count = 0;
int pass;
CHECK(imp != NULL);
sp_buf_init(&iout);
sp_buf_init(&serr);
for (pass = 0; pass < 3; pass++) {
sp_buf_clear(&iout);
CHECK(imp->run("{\"source\":\"claude\",\"id\":"
"\"11111111-2222-3333-4444-555555555555\"}", &iout,
imp->ctx) == 0);
}
CHECK(sp_session_open(&is, sessions,
"fcl-11111111-2222-3333-4444-555555555555",
&serr) == 0);
CHECK(sp_session_count(&is, &count, &serr) == 0);
/* two messages in the source, however often it is imported */
CHECK(count == 2);
sp_buf_free(&iout);
sp_buf_free(&serr);
}
/* --- a directory with no claude session is an error, not a session --- */
memset(&sess, 0, sizeof(sess));
CHECK(sp_session_open(&sess, sessions, "sess-empty", &err) == 0);
ft.sess = &sess;
sp_buf_clear(&err);
rc = sp_foreign_open(&ft, "claude", work2, &err);
CHECK(rc != 0);
CHECK(contains(err.p, "no claude session"));
CHECK(sessions_named(sessions, "fcl-") == 1);
/* --- an unknown source is refused by name --- */
sp_buf_clear(&err);
CHECK(sp_foreign_open(&ft, "cursor", work, &err) != 0);
CHECK(contains(err.p, "not a source"));
/* --- the placeholder is removable, a session with content is not --- */
{
struct sp_session_info full;
struct sp_buf serr;
memset(&full, 0, sizeof(full));
sp_buf_init(&serr);
CHECK(sp_session_open(&full, sessions, "sess-placeholder",
&serr) == 0);
CHECK(sp_session_append(&full, "user", "work that must survive",
&serr) == 0);
sp_buf_free(&serr);
}
memset(&sess, 0, sizeof(sess));
CHECK(sp_session_open(&sess, sessions, "sess-emptyshell", &err) == 0);
CHECK(sp_session_remove_if_empty(sessions, "sess-emptyshell") == 0);
CHECK(session_exists(sessions, "sess-emptyshell") == 0);
CHECK(sp_session_remove_if_empty(sessions, "sess-placeholder") != 0);
CHECK(session_exists(sessions, "sess-placeholder") == 1);
sp_buf_free(&err);
sp_buf_free(&out);
sp_host_free(host);
sp_registry_free(&reg);
{
char cmd[900];
snprintf(cmd, sizeof(cmd), "rm -rf %s", base);
if (system(cmd) != 0)
fprintf(stderr, "note: %s left behind\n", base);
}
CHECK(chdir(back) == 0);
if (failures != 0) {
fprintf(stderr, "test_foreignopen: %d failure(s)\n", failures);
return 1;
}
printf("test_foreignopen: ok\n");
return 0;
}