diff --git a/Makefile b/Makefile index fed932f..73b7465 100644 --- a/Makefile +++ b/Makefile @@ -23,7 +23,7 @@ CURSES_A = $(CURSES_DIR)/libcurses/libcurses.a \ LIB = libsplinter.so LIBOBJ = src/buf.o src/tool.o src/session.o src/conv.o src/transport.o \ src/json.o src/sse.o src/openai.o src/transport_openai.o src/builtin.o \ - src/agent.o src/theme.o src/palettes.o src/decomp.o src/i18n.o src/delegate.o src/telegram.o src/log.o src/cmdscript.o src/skills.o src/memory.o src/prompt.o src/config.o src/plugin.o + src/agent.o src/theme.o src/palettes.o src/decomp.o src/i18n.o src/delegate.o src/telegram.o src/log.o src/cmdscript.o src/folder.o src/mcpserver.o src/skills.o src/memory.o src/prompt.o src/config.o src/plugin.o BIN = splinter BINOBJ = src/main.o src/ui.o PLUGIN = plugins/clock/clock.so plugins/lcm/lcm.so plugins/cps/cps.so \ @@ -107,6 +107,8 @@ src/delegate.o: src/config.h include/splinter.h src/telegram.o: include/splinter.h src/log.o: src/log.h src/cmdscript.o: src/cmdscript.h include/splinter.h +src/folder.o: src/folder.h include/splinter.h +src/mcpserver.o: src/mcpserver.h include/splinter.h src/skills.o: src/skills.h src/config.h include/splinter.h src/prompt.o: src/prompt.h include/splinter.h src/memory.o: src/memory.h src/config.h include/splinter.h diff --git a/include/splinter.h b/include/splinter.h index 40bb49b..44f32f9 100644 --- a/include/splinter.h +++ b/include/splinter.h @@ -178,6 +178,12 @@ int sp_session_append(const struct sp_session_info *, const char *role, int sp_session_count(const struct sp_session_info *, size_t *n, struct sp_buf *err); int sp_session_latest(const char *dir, char *id, size_t cap); +/* The newest session started in this directory - what '-c' means. */ +int sp_session_last_for(const char *dir, const char *cwd, char *id, + size_t cap); +/* What happened in a directory: sessions, turns, last question. */ +int sp_session_folder_history(const char *dir, const char *cwd, + unsigned limit, struct sp_buf *out); int sp_session_load(const struct sp_session_info *, struct sp_conv *conv, size_t *loaded, struct sp_buf *err); diff --git a/libsplinter.so b/libsplinter.so index d67e907..2f1eee2 100755 Binary files a/libsplinter.so and b/libsplinter.so differ diff --git a/src/folder.c b/src/folder.c new file mode 100644 index 0000000..9571596 --- /dev/null +++ b/src/folder.c @@ -0,0 +1,63 @@ +/* + * splinter -- the folder's memory. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + * + * A model that is asked "what happened here" should not guess. Every session + * records the directory it was started in, so the answer is a lookup: + * folder_history lists the sessions of a directory, newest first, with the + * number of turns and the last thing that was asked. + */ +#include +#include + +#include "splinter.h" +#include "mcp.h" +#include "folder.h" + +static char sessions_dir[512]; + +static int +tool_folder_history(const char *args, struct sp_buf *out, void *ctx) +{ + char path[512]; + const char *want = NULL; + mcp_json *v; + + (void)ctx; + if (args != NULL && args[0] == '{') { + v = mcp_parse(args); + if (v != NULL) { + want = mcp_arg_string(v, "path"); + if (want != NULL) + snprintf(path, sizeof(path), "%s", want); + mcp_json_free(v); + } + } + if (want == NULL) { + if (getcwd(path, sizeof(path)) == NULL) + return sp_buf_puts(out, "error: cannot read the working " + "directory"); + } + return sp_session_folder_history(sessions_dir, path, 10, out) == 0 ? 0 : + -1; +} + +int +sp_folder_register(struct sp_registry *r, const char *sessions) +{ + struct sp_tool t; + + snprintf(sessions_dir, sizeof(sessions_dir), "%s", sessions); + memset(&t, 0, sizeof(t)); + t.name = "folder_history"; + t.description = "What happened in a directory before: the sessions started " + "there, how many turns, and the last question. Defaults to the " + "current directory."; + t.params = "{\"type\":\"object\",\"properties\":{\"path\":" + "{\"type\":\"string\",\"description\":\"directory to look at\"}}}"; + t.auth = SP_AUTH_READ; + t.run = tool_folder_history; + return sp_registry_add(r, &t); +} diff --git a/src/folder.h b/src/folder.h new file mode 100644 index 0000000..04d45f6 --- /dev/null +++ b/src/folder.h @@ -0,0 +1,14 @@ +/* + * splinter -- the folder's memory. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + */ +#ifndef SPLINTER_FOLDER_H +#define SPLINTER_FOLDER_H + +#include "splinter.h" + +int sp_folder_register(struct sp_registry *, const char *sessions); + +#endif /* SPLINTER_FOLDER_H */ diff --git a/src/main.c b/src/main.c index c564049..6174400 100644 --- a/src/main.c +++ b/src/main.c @@ -22,6 +22,8 @@ #include "skills.h" #include "memory.h" #include "prompt.h" +#include "folder.h" +#include "mcpserver.h" #include "splinter_plugin.h" #include "theme.h" #include "ui.h" @@ -50,6 +52,11 @@ usage(FILE *f) " --choose TEXT print which delegate fits TEXT, then exit\n" " --daemon answer on Telegram until SIGINT\n" " --no-stdin ignore data on standard input\n" + " -c, --continue continue the last session started in this " + "directory\n" + " --mcp-server-listen IP serve MCP on IP (tools of this " + "registry)\n" + " --mcp-listen-port N MCP port, default 8098\n" " --autonomous run mutating tools without asking\n" " --steps N tool rounds per turn (default 8)\n" " --session DIR session directory (default ~/.splinter)\n" @@ -191,7 +198,9 @@ main(int argc, char **argv) struct sp_mock mock; int have_mock = 0; int i, rc, chatmode = 0, resume = 0; - int daemon_mode = 0, no_stdin = 0; + int daemon_mode = 0, no_stdin = 0, continue_here = 0; + const char *mcp_ip = NULL; + int mcp_port = 8098; struct sp_config conf; const char *choose_text = NULL; const char *plugins[16]; @@ -264,6 +273,23 @@ main(int argc, char **argv) choose_text = argv[++i]; } else if (!strcmp(argv[i], "--daemon")) { daemon_mode = 1; + } else if (!strcmp(argv[i], "--mcp-server-listen")) { + if (i + 1 >= argc) { + fprintf(stderr, "splinter: --mcp-server-listen " + "needs an address\n"); + return 2; + } + mcp_ip = argv[++i]; + } else if (!strcmp(argv[i], "--mcp-listen-port")) { + if (i + 1 >= argc) { + fprintf(stderr, "splinter: --mcp-listen-port " + "needs a number\n"); + return 2; + } + mcp_port = atoi(argv[++i]); + } else if (!strcmp(argv[i], "-c") || + !strcmp(argv[i], "--continue")) { + continue_here = 1; } else if (!strcmp(argv[i], "--resume")) { resume = 1; } else if (!strcmp(argv[i], "--autonomous")) { @@ -460,14 +486,15 @@ main(int argc, char **argv) fprintf(stderr, "splinter: choose one transport\n"); return 2; } - if (transport_name == NULL && endpoint == NULL && script == NULL) { + if (transport_name == NULL && endpoint == NULL && script == NULL && + mcp_ip == NULL) { fprintf(stderr, "splinter: no transport (--endpoint, --script " "or --transport)\n"); return 2; } - if (prompt == NULL && !chatmode) { + if (prompt == NULL && !chatmode && !daemon_mode && mcp_ip == NULL) { fprintf(stderr, "splinter: -p/--prompt is required unless you " - "pass --chat\n"); + "pass --chat, --daemon or --mcp-server-listen\n"); return 2; } @@ -487,6 +514,10 @@ main(int argc, char **argv) fprintf(stderr, "splinter: cannot register skills\n"); return 3; } + if (sp_folder_register(®, sess.dir) != 0) { + fprintf(stderr, "splinter: cannot register folder_history\n"); + return 3; + } if (sp_delegate_register(®, &conf) != 0) { fprintf(stderr, "splinter: cannot register delegate\n"); return 3; @@ -499,6 +530,24 @@ main(int argc, char **argv) snprintf(buf, sizeof(buf), "%s/.splinter", home ? home : "."); sessdir = buf; } + /* + * -c means "the last session that happened *here*". The cwd at start is + * the key, so a session in another tree is never silently loaded. + */ + if (continue_here && sessid == NULL && sessdir != NULL) { + char cwd[512]; + + if (getcwd(cwd, sizeof(cwd)) != NULL && + sp_session_last_for(sessdir, cwd, default_id, + sizeof(default_id)) == 0) { + sessid = default_id; + resume = 1; + } else { + fprintf(stderr, "splinter: no session in %s yet\n", cwd); + return 2; + } + } + /* * --resume continues the newest session in the directory unless an id was * named. Opening a fresh id would resume nothing and still look like it @@ -577,7 +626,8 @@ main(int argc, char **argv) return 3; } ag.tr = sp_mock_transport(&mock); - } else { + } else if (mcp_ip == NULL) { + /* in MCP server mode no model is needed: we are the tool provider */ const char *key = NULL; if (model == NULL) { @@ -638,6 +688,15 @@ main(int argc, char **argv) * harness keeps working, the operator sees why. */ + if (mcp_ip != NULL) { + rc = sp_mcp_serve(®, mcp_ip, mcp_port, cfg.autonomous == 1, + &err); + if (rc != 0) + fprintf(stderr, "splinter: %s\n", + err.p != NULL ? err.p : "MCP server failed"); + return rc == 0 ? 0 : 1; + } + if (daemon_mode) { char token[256], tpath[700]; diff --git a/src/mcpserver.c b/src/mcpserver.c new file mode 100644 index 0000000..b6f5062 --- /dev/null +++ b/src/mcpserver.c @@ -0,0 +1,369 @@ +/* + * splinter -- the MCP server. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + * + * The other direction of plugins/mcp: here splinter *is* the server, so another + * agent can use its tools over MCP. + * + * splinter --mcp-server-listen 0.0.0.0 --mcp-listen-port 8098 + * + * Speaks newline-delimited JSON-RPC over TCP - the same framing MCP uses on + * stdio, just on a socket. Handles initialize, tools/list and tools/call, plus + * the notifications a client sends. + * + * Authorization is the point: a read tool is served, a mutating or destructive + * one is refused unless the server was started with --autonomous. A remote agent + * does not get to run shell commands on this machine because it asked nicely. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "splinter.h" +#include "mcp.h" +#include "mcpserver.h" + +static volatile int mcp_stop; + +static void +on_signal(int sig) +{ + (void)sig; + mcp_stop = 1; +} + +/* The object that follows "arguments" in the raw line, braces balanced. */ +static const char * +slice_object(const char *at, size_t *lenp) +{ + const char *start; + int depth = 0, in_str = 0, esc = 0; + + start = strchr(at, '{'); + if (start == NULL) + return NULL; + for (at = start; *at != '\0'; at++) { + if (in_str) { + if (esc) + esc = 0; + else if (*at == '\\') + esc = 1; + else if (*at == '"') + in_str = 0; + continue; + } + if (*at == '"') + in_str = 1; + else if (*at == '{') + depth++; + else if (*at == '}') { + depth--; + if (depth == 0) { + *lenp = (size_t)(at - start) + 1; + return start; + } + } + } + return NULL; +} + +static void +write_all(int fd, const char *buf, size_t len) +{ + while (len > 0) { + ssize_t n = write(fd, buf, len); + + if (n <= 0) { + if (errno == EINTR) + continue; + return; + } + buf += n; + len -= (size_t)n; + } +} + +static void +reply_ok(int fd, int id, const char *result) +{ + struct sp_buf b; + + if (sp_buf_init(&b) != 0) + return; + sp_buf_printf(&b, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"result\":%s}\n", + id, result); + write_all(fd, b.p, b.len); + sp_buf_free(&b); +} + +static void +reply_error(int fd, int id, int code, const char *message) +{ + struct sp_buf b; + + if (sp_buf_init(&b) != 0) + return; + sp_buf_printf(&b, "{\"jsonrpc\":\"2.0\",\"id\":%d,\"error\":" + "{\"code\":%d,\"message\":\"", id, code); + (void)sp_json_escape(&b, message); + sp_buf_puts(&b, "\"}}\n"); + write_all(fd, b.p, b.len); + sp_buf_free(&b); +} + +static void +reply_tools(int fd, int id, const struct sp_registry *reg) +{ + struct sp_buf b; + size_t i; + + if (sp_buf_init(&b) != 0) + return; + sp_buf_puts(&b, "{\"tools\":["); + for (i = 0; i < reg->len; i++) { + const struct sp_tool *t = ®->tools[i]; + + if (i > 0) + sp_buf_puts(&b, ","); + sp_buf_puts(&b, "{\"name\":\""); + (void)sp_json_escape(&b, t->name); + sp_buf_puts(&b, "\",\"description\":\""); + (void)sp_json_escape(&b, t->description != NULL ? t->description : + ""); + sp_buf_puts(&b, "\",\"inputSchema\":"); + sp_buf_puts(&b, t->params != NULL ? t->params : + "{\"type\":\"object\",\"properties\":{}}"); + sp_buf_puts(&b, "}"); + } + sp_buf_puts(&b, "]}"); + reply_ok(fd, id, b.p); + sp_buf_free(&b); +} + +static void +call_tool(int fd, int id, const struct sp_registry *reg, const char *line, + int allow_mutate) +{ + const struct sp_tool *t; + const char *name, *argstart; + struct sp_buf raw, out; + mcp_json *v; + size_t arglen = 0; + + v = mcp_parse(line); + if (v == NULL) { + reply_error(fd, id, -32700, "parse error"); + return; + } + name = NULL; + argstart = NULL; + { + const mcp_json *params = mcp_arg(v, "params"); + const mcp_json *args; + + if (params != NULL) { + name = mcp_arg_string(params, "name"); + args = mcp_arg(params, "arguments"); + (void)args; + } + } + if (name == NULL) { + mcp_json_free(v); + reply_error(fd, id, -32602, "params.name is required"); + return; + } + t = sp_registry_find(reg, name); + if (t == NULL) { + mcp_json_free(v); + reply_error(fd, id, -32601, "unknown tool"); + return; + } + if (t->auth != SP_AUTH_READ && !allow_mutate) { + mcp_json_free(v); + reply_error(fd, id, -32000, "tool needs authorization; start the " + "server with --autonomous to allow mutating calls"); + return; + } + /* the arguments object, as text - tools parse their own arguments */ + { + const char *p = strstr(line, "\"arguments\""); + + if (p != NULL) { + const char *slice = slice_object(p, &arglen); + + argstart = slice; + } + } + mcp_json_free(v); + + if (sp_buf_init(&raw) != 0) + return; + if (argstart != NULL) + (void)sp_buf_add(&raw, argstart, arglen); + else + (void)sp_buf_puts(&raw, "{}"); + + if (sp_buf_init(&out) != 0) { + sp_buf_free(&raw); + return; + } + if (t->run(raw.p, &out, t->ctx) != 0) + sp_buf_puts(&out, "error: tool failed"); + { + struct sp_buf res; + + if (sp_buf_init(&res) == 0) { + sp_buf_puts(&res, "{\"content\":[{\"type\":\"text\",\"text\":\""); + (void)sp_json_escape(&res, out.p != NULL ? out.p : ""); + sp_buf_puts(&res, "\"}]}"); + reply_ok(fd, id, res.p); + sp_buf_free(&res); + } + } + sp_buf_free(&raw); + sp_buf_free(&out); +} + +static void +handle_line(int fd, const struct sp_registry *reg, const char *line, + int allow_mutate) +{ + mcp_json *v; + const char *method; + int id = -1; + + v = mcp_parse(line); + if (v == NULL) { + reply_error(fd, 0, -32700, "parse error"); + return; + } + method = mcp_arg_string(v, "method"); + id = mcp_arg_int(v, "id", -1); + if (method == NULL) { + mcp_json_free(v); + return; + } + if (strcmp(method, "initialize") == 0) { + char res[512]; + + snprintf(res, sizeof(res), + "{\"protocolVersion\":\"2024-11-05\",\"capabilities\":" + "{\"tools\":{}},\"serverInfo\":{\"name\":\"splinter\"," + "\"version\":\"%s\"}}", SP_VERSION); + mcp_json_free(v); + reply_ok(fd, id, res); + return; + } + if (strcmp(method, "tools/list") == 0) { + mcp_json_free(v); + reply_tools(fd, id, reg); + return; + } + if (strcmp(method, "tools/call") == 0) { + mcp_json_free(v); + call_tool(fd, id, reg, line, allow_mutate); + return; + } + mcp_json_free(v); + if (id >= 0) + reply_error(fd, id, -32601, "unknown method"); + /* a notification has no id and gets no answer */ +} + +static void +serve_conn(int fd, const struct sp_registry *reg, int allow_mutate) +{ + char line[16384]; + size_t used = 0; + + for (;;) { + ssize_t got = read(fd, line + used, sizeof(line) - used - 1); + + if (got <= 0) { + if (got < 0 && errno == EINTR) + continue; + return; + } + used += (size_t)got; + line[used] = '\0'; + for (;;) { + char *nl = strchr(line, '\n'); + size_t len; + + if (nl == NULL) + break; + *nl = '\0'; + if (line[0] == '{') + handle_line(fd, reg, line, allow_mutate); + len = (size_t)(nl - line) + 1; + memmove(line, line + len, used - len + 1); + used -= len; + } + if (used >= sizeof(line) - 1) + used = 0; /* a line we cannot hold */ + } +} + +int +sp_mcp_serve(const struct sp_registry *reg, const char *ip, int port, + int allow_mutate, struct sp_buf *err) +{ + int s, one = 1; + struct sockaddr_in addr; + + if (ip == NULL || *ip == '\0') + ip = "127.0.0.1"; + s = socket(AF_INET, SOCK_STREAM, 0); + if (s < 0) { + sp_buf_printf(err, "mcp: socket: %s", strerror(errno)); + return -1; + } + (void)setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + addr.sin_port = htons((unsigned short)port); + if (inet_pton(AF_INET, ip, &addr.sin_addr) != 1) { + sp_buf_printf(err, "mcp: '%s' is not an address", ip); + close(s); + return -1; + } + if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) != 0) { + sp_buf_printf(err, "mcp: bind %s:%d: %s", ip, port, + strerror(errno)); + close(s); + return -1; + } + if (listen(s, 8) != 0) { + sp_buf_printf(err, "mcp: listen: %s", strerror(errno)); + close(s); + return -1; + } + (void)signal(SIGINT, on_signal); + (void)signal(SIGTERM, on_signal); + fprintf(stderr, "splinter: MCP server on %s:%d (%zu tools, %s)\n", ip, + port, reg->len, allow_mutate ? "mutating allowed" : "read only"); + + while (!mcp_stop) { + int c = accept(s, NULL, NULL); + + if (c < 0) { + if (errno == EINTR) + continue; + break; + } + serve_conn(c, reg, allow_mutate); + close(c); + } + close(s); + fprintf(stderr, "splinter: MCP server stopped\n"); + return 0; +} diff --git a/src/mcpserver.h b/src/mcpserver.h new file mode 100644 index 0000000..0810828 --- /dev/null +++ b/src/mcpserver.h @@ -0,0 +1,15 @@ +/* + * splinter -- the MCP server. + * + * Copyright (c) 2026 Konrad Lother + * SPDX-License-Identifier: BSD-3-Clause + */ +#ifndef SPLINTER_MCPSERVER_H +#define SPLINTER_MCPSERVER_H + +#include "splinter.h" + +int sp_mcp_serve(const struct sp_registry *, const char *ip, int port, + int allow_mutate, struct sp_buf *err); + +#endif /* SPLINTER_MCPSERVER_H */ diff --git a/src/session.c b/src/session.c index 19c548c..1e8b2b6 100644 --- a/src/session.c +++ b/src/session.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -78,6 +79,27 @@ sp_session_open(struct sp_session_info *info, const char *dir, return -1; } close(fd); + /* + * A session belongs to the directory it was started in. That is what '-c' + * needs: the last session that happened *here*, not the last one anywhere. + */ + { + char mpath[700], cwd[512], tmp[800]; + FILE *m; + time_t now = time(NULL); + + if (getcwd(cwd, sizeof(cwd)) == NULL) + snprintf(cwd, sizeof(cwd), "?"); + snprintf(mpath, sizeof(mpath), "%s/%s.meta", dir, info->id); + snprintf(tmp, sizeof(tmp), "%s.tmp", mpath); + m = fopen(tmp, "w"); + if (m != NULL) { + fprintf(m, "cwd=%s\ncreated=%ld\nopened=%ld\n", cwd, + (long)now, (long)now); + fclose(m); + (void)rename(tmp, mpath); + } + } return 0; } @@ -274,3 +296,180 @@ sp_session_latest(const char *dir, char *id, size_t cap) snprintf(id, cap, "%s", best); return 0; } + + +/* The cwd recorded for a session, or NULL. */ +static int +meta_cwd(const char *dir, const char *id, char *buf, size_t cap) +{ + char path[700], line[600]; + FILE *f; + int found = 0; + + snprintf(path, sizeof(path), "%s/%s.meta", dir, id); + f = fopen(path, "r"); + if (f == NULL) + return -1; + while (fgets(line, sizeof(line), f) != NULL) { + if (strncmp(line, "cwd=", 4) != 0) + continue; + snprintf(buf, cap, "%.*s", (int)(cap - 1), line + 4); + buf[strcspn(buf, "\r\n")] = '\0'; + found = 1; + break; + } + fclose(f); + return found ? 0 : -1; +} + +/* + * The newest session started in this directory. + * + * 'splinter -c' in ~/src/splinter means "the last thing I did here" - not the + * last thing I did anywhere. Sessions from other directories are the wrong + * answer and would silently load the wrong context. + */ +int +sp_session_last_for(const char *dir, const char *cwd, char *id, size_t cap) +{ + DIR *d; + struct dirent *e; + char best[128] = ""; + time_t best_t = 0; + + d = opendir(dir); + if (d == NULL) + return -1; + while ((e = readdir(d)) != NULL) { + struct stat st; + char path[700], session_cwd[512]; + size_t len = strlen(e->d_name); + + if (len < 6 || strcmp(e->d_name + len - 5, ".meta") != 0) + continue; + e->d_name[len - 5] = '\0'; + snprintf(path, sizeof(path), "%s/%s.meta", dir, e->d_name); + if (stat(path, &st) != 0) + continue; + if (meta_cwd(dir, e->d_name, session_cwd, + sizeof(session_cwd)) != 0) + continue; + if (strcmp(session_cwd, cwd) != 0) + continue; + if (st.st_mtime >= best_t) { + best_t = st.st_mtime; + snprintf(best, sizeof(best), "%s", e->d_name); + } + } + closedir(d); + if (best[0] == '\0') + return -1; + snprintf(id, cap, "%s", best); + return 0; +} + +/* + * What happened in a directory: the sessions started there, newest first, with + * the number of turns and the last thing that was asked. This is the folder's + * memory - readable by the model through a tool, not guessed. + */ +int +sp_session_folder_history(const char *dir, const char *cwd, unsigned limit, + struct sp_buf *out) +{ + DIR *d; + struct dirent *e; + struct { + char name[128]; + time_t mtime; + } found[64]; + size_t n = 0, i, j; + + d = opendir(dir); + if (d == NULL) { + sp_buf_printf(out, "no sessions in %s\n", dir); + return 0; + } + while ((e = readdir(d)) != NULL && n < 64) { + struct stat st; + char path[700], session_cwd[512]; + size_t len = strlen(e->d_name); + + if (len < 6 || strcmp(e->d_name + len - 5, ".meta") != 0) + continue; + e->d_name[len - 5] = '\0'; + snprintf(path, sizeof(path), "%s/%s.meta", dir, e->d_name); + if (stat(path, &st) != 0) + continue; + if (meta_cwd(dir, e->d_name, session_cwd, + sizeof(session_cwd)) != 0) + continue; + if (cwd != NULL && strcmp(session_cwd, cwd) != 0) + continue; + snprintf(found[n].name, sizeof(found[n].name), "%s", e->d_name); + found[n].mtime = st.st_mtime; + n++; + } + closedir(d); + /* newest first, straight insertion: 64 entries, no library needed */ + for (i = 1; i < n; i++) { + for (j = i; j > 0 && found[j - 1].mtime < found[j].mtime; j--) { + char tn[128]; + time_t tm = found[j - 1].mtime; + + snprintf(tn, sizeof(tn), "%s", found[j - 1].name); + snprintf(found[j - 1].name, sizeof(found[j - 1].name), + "%s", found[j].name); + found[j - 1].mtime = found[j].mtime; + snprintf(found[j].name, sizeof(found[j].name), "%s", tn); + found[j].mtime = tm; + } + } + if (n == 0) { + sp_buf_printf(out, "no sessions in %s%s%s\n", dir, + cwd != NULL ? " for " : "", cwd != NULL ? cwd : ""); + return 0; + } + for (i = 0; i < n && i < limit; i++) { + char path[800], line[2048], stamp[32]; + struct tm tm; + FILE *f; + time_t when = found[i].mtime; + size_t turns = 0; + char last[512] = ""; + + (void)localtime_r(&when, &tm); + strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M", &tm); + snprintf(path, sizeof(path), "%.500s/%.120s.jsonl", dir, + found[i].name); + f = fopen(path, "r"); + if (f != NULL) { + while (fgets(line, sizeof(line), f) != NULL) { + turns++; + if (strstr(line, "\"role\":\"user\"") == NULL) + continue; + snprintf(last, sizeof(last), "%.511s", line); + } + fclose(f); + } + { + char *p = strstr(last, "\"text\":\""); + + if (p != NULL) { + char *v = p + 9; + size_t k = 0; + + while (*v != '\0' && *v != '"' && k + 1 < sizeof(last)) + last[k++] = *v++; + last[k] = '\0'; + } else + last[0] = '\0'; + } + sp_buf_printf(out, "%s %s %zu records%s%s\n", stamp, + found[i].name, turns / 2, + last[0] != '\0' ? " last: " : "", last); + } + if (n > limit) + sp_buf_printf(out, "(%zu more)\n", n - limit); + return 0; +}